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>namespace RemoteServer.Model
{
public class Application
{
public string Title { get; set; }
public string Path { get; set; }
public Application(string title, string path)
{
Title = title;
Path = path;
}
}
}<file_sep>using System;
namespace RemoteServer.CustomEventArgs
{
public class StringEventArgument : EventArgs
{
public string TextMessage { get; set; }
public StringEventArgument(string text)
{
TextMessage = text;
}
}
}<file_sep>namespace RemoteServer.Model
{
public class Response
{
public bool Result;
public int Code;
public string Message;
public Response(bool result, int code, string message)
{
Result = result;
Code = code;
Message = message;
}
public override string ToString()
{
return $"Result: {Result}, Code: {Code}, Message: {Message}";
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;
using RemoteServer.Helper;
using RemoteServer.Model;
namespace RemoteServer.Controller
{
public class SettingsController
{
private const string Filename = "settings.json";
public static void Save(Settings settings)
{
StreamWriter stream = null;
try
{
stream = new StreamWriter(File.Open(Filename, FileMode.Create));
var json = JsonHelper.ConvertSettings(settings);
stream.Write(json);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
// ignored
}
finally
{
stream?.Close();
}
}
public static Settings Load()
{
StreamReader stream = null;
try
{
if (File.Exists(Filename))
{
stream = new StreamReader(File.Open(Filename, FileMode.Open));
var read = stream.ReadToEnd();
var returnSettings = JsonHelper.GetSettings(read);
return returnSettings;
}
var settings = new Settings(true);
Save(settings);
return settings;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return new Settings(true);
}
finally
{
stream?.Close();
}
}
}
}<file_sep>
using System.Drawing.Text;
namespace RemoteServer.Controller
{
public interface ISocketInterface
{
void Initalize(string ip, int port);
void Start();
void Stop();
bool IsActive();
}
}<file_sep>namespace RemoteServer.Helper
{
public enum Commands
{
VolumeUp, VolumeDown, VolumeMute, Check,
Play, Pause, Stop, Space, Next, Previous
}
}<file_sep>using Newtonsoft.Json;
using RemoteServer.Model;
namespace RemoteServer.Helper
{
public class JsonHelper
{
// private string Error = null;
public static ControlMessage GetControlMessage(string text)
{
try
{
return JsonConvert.DeserializeObject<ControlMessage>(text);
}
catch (JsonException ex)
{
//throw ex;
return null;
}
}
public static string ConvertResponse(Response response)
{
try
{
return JsonConvert.SerializeObject(response);
}
catch (JsonException ex)
{
//throw ex;
return null;
}
}
public static string ConvertSettings(Settings settings)
{
try
{
return JsonConvert.SerializeObject(settings);
}
catch (JsonException ex)
{
throw ex;
return null;
}
}
public static Settings GetSettings(string text)
{
try
{
return JsonConvert.DeserializeObject<Settings>(text);
}
catch (JsonException ex)
{
throw ex;
return null;
}
}
}
}<file_sep>using System;
using RemoteServer.Model;
namespace RemoteServer.CustomEventArgs
{
public class ControlMessageArgument : EventArgs
{
public bool IsError { get; }
public string Error { get; }
public string Result { get; }
public ControlMessage Message { get; }
public ControlMessageArgument(string text, bool isError, ControlMessage controlMessage)
{
this.IsError = isError;
if (isError)
{
Error = text;
Result = null;
Message = null;
}
else
{
Error = null;
Result = text;
Message = controlMessage;
}
}
public override string ToString()
{
var result = IsError ?
$"Error: {Error}, Message: {Message?.ToString()}" :
$"Result: {Result}, Message: {Message?.ToString()}";
return result;
}
}
}<file_sep>http://stackoverflow.com/questions/8930870/how-can-i-convert-system-drawing-icon-to-system-drawing-image
http://en.code-bude.net/2013/10/17/qrcoder-an-open-source-qr-code-generator-implementation-in-csharp/
http://stackoverflow.com/questions/3388264/how-can-i-get-file-icon
http://stackoverflow.com/questions/9644311/sending-ctrl-space-with-sendkeys-in-c<file_sep>
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using RemoteServer.CustomEventArgs;
using RemoteServer.Helper;
using RemoteServer.Model;
namespace RemoteServer.Controller
{
public class SocketController : ISocketInterface
{
private Socket _socket;
private List<Thread> _threads;
private const int Maximum = 2;
private const int Size = 1024;
private bool _active;
public SocketController()
{
}
public delegate void ServerEventHandler(object sender, ControlMessageArgument e);
public delegate void ServerStringHandler(object sender, StringEventArgument e);
public event ServerEventHandler OnServerMessage;
public event ServerStringHandler OnStringHandled;
public void Initalize(string ip, int port)
{
var ipAddress = IPAddress.Parse(ip);
var endPoint = new IPEndPoint(ipAddress, port);
_socket?.Close();
_socket?.Dispose();
_socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind(endPoint);
_socket.Listen(Maximum);
_threads = new List<Thread>();
HandleString("Server starts listening");
}
public void Start()
{
_active = true;
for (var i = 0; i < Maximum; i++)
{
var thread = new Thread(Listening);
thread.Start();
_threads.Add(thread);
}
// throw new System.NotImplementedException();
}
public bool IsActive() => _active;
public void Stop()
{
try
{
_active = false;
_socket?.Dispose();
_socket?.Disconnect(true);
foreach (var th in _threads)
th.Abort();
}
catch (Exception ex)
{
DefineEvent(ex.Message, true, null);
}
finally
{
_socket?.Close();
}
}
private void Listening()
{
while (_active)
{
try
{
var handler = _socket?.Accept();
if (handler == null) continue;
if (!(handler?.Connected ?? false)) continue;
var message = ReceiveMessage(handler);
if (string.IsNullOrEmpty(message)) continue;
var controlMessage = JsonHelper.GetControlMessage(message);
var response = JsonHelper.ConvertResponse(
controlMessage != null
? new Response(true, 200, "success")
: new Response(false, 300, "null object"));
SendMessage(response, handler);
if (controlMessage != null)
{
HandleString(message);
}
else
{
HandleString(message);
}
handler = null;
}
catch (Exception e)
{
// DefineEvent(e.Message, true, null);
// Console.WriteLine(e);
}
}
}
private string ReceiveMessage(Socket handler)
{
try
{
var bytes = new byte[Size];
var b = handler.Receive(bytes);
var message = Encoding.UTF8.GetString(bytes, 0, b);
return message;
}
catch (Exception ex)
{
DefineEvent(ex.Message, true, null);
return null;
}
}
private void CloseConnection(Socket handler)
{
try
{
handler?.Shutdown(SocketShutdown.Both);
}
catch (Exception ex)
{
DefineEvent(ex.Message, true, null);
}
finally
{
handler?.Close();
//handler = null;
}
}
private bool SendMessage(string text, Socket handler)
{
try
{
var toSend = Encoding.UTF8.GetBytes(text);
handler.Send(toSend, toSend.Length, SocketFlags.None);
CloseConnection(handler);
return true;
}
catch (Exception ex)
{
DefineEvent(ex.Message, true, null);
return false;
}
}
private void DefineEvent(string text, bool error, ControlMessage message)
{
var eventArgs = new ControlMessageArgument(text, error, message);
OnServerMessage?.Invoke(this, eventArgs);
}
protected void HandleString(string text)
{
var args = new StringEventArgument(text);
OnStringHandled?.Invoke(this, args);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using RemoteServer.Controller;
using RemoteServer.CustomEventArgs;
using RemoteServer.Helper;
using RemoteServer.Properties;
using Settings = RemoteServer.Model.Settings;
namespace RemoteServer
{
public partial class Form1 : Form
{
private readonly SocketController _socketController;
private Settings _settings;
public Form1()
{
InitializeComponent();
_socketController = new SocketController();
_socketController.OnServerMessage += HandleServerEvent;
_socketController.OnStringHandled += HandleServerString;
}
private string ExecuteRemoteCommand(string json)
{
var result = "";
try
{
var controlMessage = JsonHelper.GetControlMessage(json);
switch (controlMessage.Application)
{
case "System":
if (!_settings.AllowSystemControlling)
{
result = "Do not have permissions to control OS statement";
break;
}
var command = CommandController.GetCommand(controlMessage);
SystemController.ExecuteCommand(command);
break;
case "Application":
if (!_settings.AllowOtherApplications)
{
result = "Do not have permissions to start Applications";
break;
}
result = SystemController.LaunchApplication(controlMessage.Action)
? $"{controlMessage.Action} launched"
: $"Cannot launch {controlMessage.Action}";
break;
default:
result = controlMessage.ToString();
break;
}
}
catch (JsonException ex)
{
result = ex.Message;
}
return result;
}
private void HandleServerString(object sender, StringEventArgument e)
{
var result = e.TextMessage.Contains("Server starts listening")
? e.TextMessage :
ExecuteRemoteCommand(e.TextMessage);
AddToLog(result);
}
private void Form1_Load(object sender, EventArgs e)
{
_settings = SettingsController.Load();
/*
* _server = new SocketServerController(_myTitle, _myLimit);
_server.OnServerMessage += HandleServerMessage;
*
*/
}
private void AddToLog(string text)
{
try
{
var toLog = $" {GetTime()} {text} \r\n";
if (textBox1.InvokeRequired)
textBox1.Invoke(new Action<string>((s) => textBox1.Text += s), toLog);
else
textBox1.Text += toLog;
}
catch (Exception ex)
{
textBox1.Text += $"{ex.Message}\r\n";
}
}
private string GetTime() => "[" + DateTime.Now.ToString("dd-MM-yy | HH:mm:ss") + "]";
private void HandleServerEvent(object sender, ControlMessageArgument controlMessageArgument)
{
AddToLog(controlMessageArgument.ToString());
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
var textBox = (TextBox) sender;
textBox.SelectionStart = textBox.Text.Length;
textBox.ScrollToCaret();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
_socketController.Stop();
}
private string GetAppLabel(int i)
{
return _settings.Applications[i].Path != ""
? $"App {i + 1}" :
"No app";
}
private Image GetApplicationIcon(int i)
{
Icon icon = null;
try
{
icon = _settings.Applications[i].Path != ""
? Icon.ExtractAssociatedIcon(_settings.Applications[i].Path)
: null;
}
catch (Exception e)
{
// ignored
}
return icon?.ToBitmap() ?? Resources.question;
}
private void Form1_Shown(object sender, EventArgs e)
{
labelApp1.Text = GetAppLabel(0);
picApp1.Image = GetApplicationIcon(0);
labelApp2.Text = GetAppLabel(1);
picApp2.Image = GetApplicationIcon(1);
labelApp3.Text = GetAppLabel(2);
picApp3.Image = GetApplicationIcon(2);
labelApp4.Text = GetAppLabel(3);
picApp4.Image = GetApplicationIcon(3);
labelApp5.Text = GetAppLabel(4);
picApp5.Image = GetApplicationIcon(4);
// ----------------------------------
var ips = ConnectionData.GetIpList();
var text = ips.Aggregate($"Server IP: ", (current, ip) => current + (ip + " "));
statusLabel.Text = text;
if (_settings.StartOnLaunch)
{
StartOrStopServer();
}
}
private void включитьСерверToolStripMenuItem_Click(object sender, EventArgs e)
{
StartOrStopServer();
}
private void StartOrStopServer()
{
if (!_socketController.IsActive())
{
_socketController.Initalize("0.0.0.0", 14880);
_socketController.Start();
EnableServerButton.Text = Resources.disable_server;
}
else
{
_socketController.Stop();
EnableServerButton.Text = Resources.enable_server;
}
}
private void настройкиToolStripMenuItem_Click(object sender, EventArgs e)
{
new SettingsForm().ShowDialog();
}
private void формаКнопокToolStripMenuItem_Click(object sender, EventArgs e)
{
Process.Start("https://github.com/maximgorbatyuk/RemoteServer");
}
}
}
<file_sep>using System.Collections.Generic;
namespace RemoteServer.Model
{
public class Settings
{
public List<Application> Applications { get; set; }
public bool AllowSystemControlling { get; set; }
public bool AllowOtherApplications { get; set; }
public bool StartOnLaunch { get; set; }
public Settings()
{
Initiate();
}
public Settings(bool dfl)
{
Initiate(dfl);
}
private void Initiate(bool dfl = false)
{
AllowOtherApplications = true;
if (dfl)
{
Applications = new List<Application>
{
new Application("application1", ""),
new Application("application2", ""),
new Application("application3", ""),
new Application("application4", ""),
new Application("application5", "")
};
}
else
{
Applications = new List<Application>(5);
}
AllowSystemControlling = true;
StartOnLaunch = false;
}
}
}<file_sep>
namespace RemoteServer.Model
{
public class ControlMessage
{
public string Application;
public string Action;
public int Value;
public ControlMessage()
{
Application = null;
Action = null;
Value = 0;
}
public ControlMessage(string application, string action, int value)
{
Application = application;
Action = action;
Value = value;
}
public override string ToString()
{
return $"Application: {Application}, Action: {Action}, Value: {Value}";
}
}
}
<file_sep>using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using RemoteServer.Helper;
namespace RemoteServer.Controller
{
public abstract class SystemController
{
[DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
public static bool ExecuteCommand(Commands command)
{
var key = Keys.None;
switch (command)
{
case Commands.VolumeUp:
key = Keys.VolumeUp;
break;
case Commands.VolumeDown:
key = Keys.VolumeDown;
break;
case Commands.VolumeMute:
key = Keys.VolumeMute;
break;
case Commands.Play:
key = Keys.MediaPlayPause;
SendKeys.SendWait("^( )");
break;
case Commands.Pause:
key = Keys.Pause;
SendKeys.SendWait("^( )");
break;
case Commands.Next:
key = Keys.MediaNextTrack;
break;
case Commands.Previous:
key = Keys.MediaPreviousTrack;
break;
case Commands.Space:
key = Keys.Space;
break;
case Commands.Check:
break;
case Commands.Stop:
break;
default:
key = Keys.None;
break;
}
Press(key);
return true;
}
private static void Press(Keys key)
{
keybd_event((byte) key, 0, 0, 0);
}
public static bool LaunchApplication(string application)
{
//
string path;
var settings = SettingsController.Load();
switch (application)
{
case "application1":
path = settings.Applications[0].Path;
break;
case "application2":
path = settings.Applications[1].Path;
break;
case "application3":
path = settings.Applications[2].Path;
break;
case "application4":
path = settings.Applications[3].Path;
break;
case "application5":
path = settings.Applications[4].Path;
break;
default:
path = "";
break;
}
if (path == "") return false;
try
{
Process.Start(path);
return true;
}
catch (Exception ignored)
{
// ignored
}
return false;
}
}
}<file_sep>using System.Drawing;
using System.Threading.Tasks;
using QRCoder;
namespace RemoteServer.Controller
{
public class BarcodeController
{
public static async Task<Bitmap> RenderBarcodeAsync(string text, int width)
{
var qrGenerator = new QRCodeGenerator();
var qrCodeData = qrGenerator.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q);
var qrCode = new QRCode(qrCodeData);
var qrCodeImage = qrCode.GetGraphic(width);
return qrCodeImage;
}
}
}<file_sep>using RemoteServer.Helper;
using RemoteServer.Model;
namespace RemoteServer.Controller
{
public class CommandController
{
public static Commands GetCommand(ControlMessage message)
{
switch (message.Action)
{
case "VolumeUp":
return Commands.VolumeUp;
case "VolumeDown":
return Commands.VolumeDown;
case "VolumeMute":
return Commands.VolumeMute;
case "Check":
return Commands.Check;
default:
return Commands.Check;
}
}
}
}<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.Threading.Tasks;
using System.Windows.Forms;
using RemoteServer.Controller;
using RemoteServer.Helper;
using RemoteServer.Model;
namespace RemoteServer
{
public partial class SettingsForm : Form
{
private Settings _settings;
public SettingsForm()
{
InitializeComponent();
}
private void SettingsForm_Load(object sender, EventArgs e)
{
ShowBarcodeAsync();
}
private async void ShowBarcodeAsync()
{
var ip = ConnectionData.GetIpList().Last();
var image = await BarcodeController.RenderBarcodeAsync(ip.ToString(), 10);
pictureBox1.Image = image;
}
private void button2_Click(object sender, EventArgs e)
{
UpdateSettings();
SettingsController.Save(_settings);
}
private void button1_Click(object sender, EventArgs e)
{
UpdateSettings();
SettingsController.Save(_settings);
Close();
}
private void UpdateSettings()
{
_settings.AllowSystemControlling = checkBox1.Checked;
_settings.AllowOtherApplications = checkBox2.Checked;
_settings.StartOnLaunch = checkBox3.Checked;
//-------------
_settings.Applications[0].Path = editApp1.Text;
_settings.Applications[1].Path = editApp2.Text;
_settings.Applications[2].Path = editApp3.Text;
_settings.Applications[3].Path = editApp4.Text;
_settings.Applications[4].Path = editApp5.Text;
}
private void button3_Click(object sender, EventArgs e)
{
Close();
}
private void SettingsForm_Shown(object sender, EventArgs e)
{
_settings = SettingsController.Load();
DisplaySettings();
}
private void DisplaySettings()
{
checkBox1.Checked = _settings.AllowSystemControlling;
checkBox2.Checked = _settings.AllowOtherApplications;
checkBox3.Checked = _settings.StartOnLaunch;
editApp1.Text = _settings.Applications[0].Path;
editApp2.Text = _settings.Applications[1].Path;
editApp3.Text = _settings.Applications[2].Path;
editApp4.Text = _settings.Applications[3].Path;
editApp5.Text = _settings.Applications[4].Path;
}
private void OpenDialog(int tag)
{
openFileDialog1.Tag = tag;
openFileDialog1.ShowDialog();
}
private void butApp1_Click(object sender, EventArgs e)
{
OpenDialog(1);
}
private void butApp2_Click(object sender, EventArgs e)
{
OpenDialog(2);
}
private void butApp3_Click(object sender, EventArgs e)
{
OpenDialog(3);
}
private void butApp4_Click(object sender, EventArgs e)
{
OpenDialog(4);
}
private void butApp5_Click(object sender, EventArgs e)
{
OpenDialog(5);
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
var tag = (int) openFileDialog1.Tag;
var filename = openFileDialog1.FileName;
switch (tag)
{
case 1:
editApp1.Text = filename;
break;
case 2:
editApp2.Text = filename;
break;
case 3:
editApp3.Text = filename;
break;
case 4:
editApp4.Text = filename;
break;
case 5:
editApp5.Text = filename;
break;
}
}
}
}
<file_sep>using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
namespace RemoteServer.Helper
{
public class ConnectionData
{
public static string GetLocalIp()
{
foreach (var ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
return ip.ToString();
}
return "cannot define local ip";
}
public static IEnumerable<IPAddress> GetIpList()
{
return Dns.GetHostByName(Dns.GetHostName()).AddressList;
}
}
}<file_sep># Remotlin Server
English version is available [here](https://github.com/maximgorbatyuk/RemoteServer/blob/master/readme_en.md)
## Описание проекта
Проект предназначен для организации системы управления компьютером со смартфона на Android.
Это приложение - часть системы, которая устанавливается на управляемый компьютер и парсит команды от смартфона.
Приложение для смартфона доступно [здесь](https://github.com/maximgorbatyuk/Remotlin)
## Q&A
| Вопрос | Ответ |
|--------|-------|
| Что это? | Программа для обработки команд от смартфона |
| Какие требования к ОС? | Установенный .Net Framework не ниже 4.5.2 |
| Кто автор? | Ссылки на мой профиль в православном [Вконтакте](https://vk.com/maximgorbatyuk) и в буржуйском [Фейсбуке](https://www.facebook.com/maximgorbatyuk191093) |
| А зачем мне ссылки? | Чтобы прислать мне багрепорт со скриншотом или сообщить свои предложения и пожелания |
| Сколько стоит? | Свободно распространяется на основании [лицензии](https://github.com/maximgorbatyuk/RemoteServer/blob/master/license.md) |
| Как использовать? | Смартфон и ПК должны находиться в одной локальной сети (WiFi). В настройках программы есть QR код, в котором записан IP. Сканируй код и используй приложение|
| Как скачать? | [Прямая ссылка](https://github.com/maximgorbatyuk/RemoteServer/blob/master/RemotlinServer?raw=true) на скачивание архива |
## Планы
## Лицензия
Это приложение является свободно распространяемым продуктом, но так как используемые мною при разработке костыли и велосипеды мои, то я не хотел бы, чтобы кто-то прилепил свое название к приложению и распространял его как свое. Посему данные ПО распространяется под лицензией [Apache 2.0](https://github.com/maximgorbatyuk/RemoteServer/blob/master/license.md).
|
c5cd2b6caacbf3c3b323a2e424c1b2cee1051c69
|
[
"Markdown",
"C#"
] | 19
|
C#
|
maximgorbatyuk/RemoteServer
|
b5af805b78d22835f7cfe4cbad1f3472b253a705
|
82f8b999ea9c5cf750cd76b1253934159afa78f0
|
refs/heads/master
|
<file_sep>package element;
import com.badlogic.gdx.math.Vector2;
public class Pair {
String left;
Vector2 right;
public Pair(String left, Vector2 right) {
this.left = left;
this.right = right;
}
public String getLeft() {
return left;
}
public void setLeft(String left) {
this.left = left;
}
public Vector2 getRight() {
return right;
}
public void setRight(Vector2 right) {
this.right = right;
}
}
<file_sep>package com.mygdx.game.desktop;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import gameValues.Constants;
import graphics.AgarAI;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = "Agar.AI";
config.width = Constants.SCREEN_WIDTH;
config.height = Constants.SCREEN_HEIGHT;
new LwjglApplication(new AgarAI(), config);
}
}
<file_sep>package gameValues;
import graphics.AgarAI;
public class BlobManager extends Thread {
GameManager manager;
public BlobManager(AgarAI game) {
manager = GameManager.getInstance(game);
}
@Override
public void run() {
while(true) {
try {
manager.manageActors();
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
<file_sep>package element;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Vector2;
import gameValues.Constants;
import it.unical.mat.embasp.languages.Id;
import it.unical.mat.embasp.languages.Param;
@Id("blob")
public class Blob {
/* EmbASP integration */
@Param(0)
protected int id;
@Param(1)
protected float x;
@Param(2)
protected float y;
@Param(3)
protected float radius;
protected Pair target;
protected Color color;
/* Concurrency */
Lock l = new ReentrantLock();
public Blob() {}
public Blob(int id, float x, float y, float radius, Color color) {
this.id = id;
this.x = x;
this.y = y;
this.radius = radius;
this.target = new Pair(Constants.INSEGUI,
new Vector2((float) ((Math.random()*Constants.fieldDim*2)-Constants.fieldDim),
(float) ((Math.random()*Constants.fieldDim*2)-Constants.fieldDim)));
this.color = color;
}
public void setRandomBlob(int id) {
this.id = id;
this.radius = (float) (Math.random() * 20) + 5;
this.target = new Pair(Constants.INSEGUI,
new Vector2((float) ((Math.random()*Constants.fieldDim*2)-Constants.fieldDim),
(float) ((Math.random()*Constants.fieldDim*2)-Constants.fieldDim)));
this.color = Constants.colors[Math.abs(this.id)%Constants.colors.length];
setRandomPosition();
}
public int getId() {
return id;
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public float getRadius() {
return radius;
}
public void setRadius(float radius) {
this.radius = radius;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public void setTarget(Pair target) {
this.target = target;
}
public Pair getTarget() {
return target;
}
public void setRandomPosition() {
float xTmp = (float) ((Math.random() * Constants.fieldDim/2) - Constants.fieldDim/2);
float yTmp = (float) ((Math.random() * Constants.fieldDim/2) - Constants.fieldDim/2);
setX(xTmp);
setY(yTmp);
}
public void move() {
if(target.getLeft().equals(Constants.INSEGUI) && id<=0)
moveToTarget();
else if(target.getLeft().equals(Constants.SCAPPA) && id<=0)
goAway();
}
public void moveToTarget() {
float MoveToX = target.getRight().x;
float MoveToY = target.getRight().y;
float diffX = MoveToX - x;
float diffY = MoveToY - y;
float angle = (float)Math.atan2(diffY, diffX);
addPos((float)Math.cos(angle)*Constants.lerp,
(float)Math.sin(angle)*Constants.lerp);
}
public void goAway() {
float MoveToX = target.getRight().x;
float MoveToY = target.getRight().y;
float diffX = MoveToX - x;
float diffY = MoveToY - y;
float angle = (float)Math.atan2(diffY, diffX);
addPos(-(float)Math.cos(angle)*Constants.lerp,
-(float)Math.sin(angle)*Constants.lerp);
}
public void addPos(float x, float y) {
double speed = Math.pow(radius*2, -0.5);
if((this.x + x*speed)>=-(Constants.fieldDim)/2 &&
(this.x + x*speed)<=(Constants.fieldDim)/2) {
this.x += x * speed;
}
if((this.y + y*speed)>=-(Constants.fieldDim)/2 &&
(this.y + y*speed)<=(Constants.fieldDim)/2) {
this.y += y * speed;
}
}
public void increment(final float inc) {
new Thread() {
public void run() {
l.lock();
float initial = radius;
float target = initial + inc;
while(radius < target) {
radius += 0.2f;
try {
sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
l.unlock();
};
}.start();
}
public boolean checkCollision(Blob blob) {
if(new Vector2(this.x, this.y).dst(new Vector2(blob.x, blob.y)) < this.radius + blob.radius)
return true;
return false;
}
public float checkDistance(Blob blob) {
return new Vector2(blob.getX(), blob.getY()).dst(x, y);
}
}
<file_sep>package gameValues;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
public abstract class Constants {
/* Graphic Constants */
public static TextureAtlas texture = new TextureAtlas(Gdx.files.internal("skin/glassy-ui.atlas"));
public static Skin skin = new Skin(Gdx.files.internal("skin/glassy-ui.json"), texture);
/* Screen Constants */
public static final int SCREEN_WIDTH = 1000;
public static final int SCREEN_HEIGHT = 600;
/* Game Constants */
public static final String INSEGUI = "insegui";
public static final String SCAPPA = "scappa";
public static final String ALLONTANATI = "allontanatiDalBordo";
public static final float lerp = 25f;
public static int inanimatedBlobs = 10;
public static int animatedBlobs =10;
public static boolean isHumanPlayer = false;
public static final int fieldDim = 2000;
/* Field Corners */
public static final Vector2 topRight = new Vector2(fieldDim/2, fieldDim/2);
public static final Vector2 bottomRight = new Vector2(fieldDim/2, -fieldDim/2);
public static final Vector2 topLeft = new Vector2(-fieldDim/2, fieldDim/2);
public static final Vector2 bottomLeft = new Vector2(-fieldDim/2, -fieldDim/2);
public static final float top = fieldDim/2;
public static final float bottom = -fieldDim/2;
public static final float right = fieldDim/2;
public static final float left = -fieldDim/2;
/* Colors */
public static final Color[] colors = {
Color.BLUE, Color.RED, Color.YELLOW,
Color.GREEN, Color.ORANGE, Color.BROWN,
Color.LIME, Color.CYAN, Color.MAGENTA,
Color.PINK, Color.NAVY
};
}
<file_sep># Agar.AI
Artificial Intelligence project for University
<file_sep>package graphics;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import gameValues.Constants;
public class StartScreen implements Screen {
AgarAI game;
Stage stage;
SpriteBatch batch;
public Texture background = new Texture("img/bg.jpg");
public StartScreen(final AgarAI game) {
this.game = game;
stage = new Stage();
batch = new SpriteBatch();
Button button = new TextButton("Start", Constants.skin);
button.setPosition(350, 350);
button.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
game.changeScreen("main");
}
});
stage.addActor(button);
Button options = new TextButton("Options", Constants.skin);
options.setPosition(350, 150);
options.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
game.changeScreen("options");
}
});
stage.addActor(options);
}
@Override
public void show() {
Gdx.input.setInputProcessor(stage);
}
@Override
public void render(float delta) {
batch.begin();
batch.draw(background,0,0);
batch.end();
stage.act();
stage.draw();
}
@Override
public void resize(int width, int height) {}
@Override
public void pause() {}
@Override
public void resume() {}
@Override
public void hide() {}
@Override
public void dispose() {
batch.dispose();
stage.dispose();
}
}
|
e0c63e92a2be1ac841032ae4e0eb54e972053dbe
|
[
"Markdown",
"Java"
] | 7
|
Java
|
shaba81/Agar.AI
|
a2274217f843b98e70be6bfa4cdf10cca2b0f624
|
5cea6bd05daf3c8768041d5d7f19fcab9db981f0
|
refs/heads/master
|
<repo_name>KAmaia/Server<file_sep>/Server/Core/ServerEvents/ServerStartEvent.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eventing.Library;
namespace Server.Core.ServerEvents {
class ServerStartEvent : IEvent {
public string Message { get { return "Server Starting Up"; }}
}
}
<file_sep>/Server/Core/ServerCore.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eventing.Library.Impl;
using Server.Core.ServerEvents;
using Eventing.Library;
namespace Server.Core {
class ServerCore {
private EventManager eventManager;
public ServerCore(EventManager em ) {
eventManager = em;
StartReceiving( );
}
private void StartUp( ServerStartEvent @event ) {
Console.WriteLine( @event.Message );
}
private void StartReceiving( ) {
eventManager.StartReceiving<ServerStartEvent>( @event => this.StartUp( @event ) );
}
}
}
<file_sep>/Server/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eventing.Library;
using Eventing.Library.Impl;
using System.Threading;
using Server.Core.ServerEvents;
using Server.Core;
namespace Server {
class Program {
static void Main( string[ ] args ) {
var synchronizationContext = new SingleThreadSynchronizationContext( "Client" );
var eventManager = new EventManager(new MessageBus());
SynchronizationContext.SetSynchronizationContext( synchronizationContext );
ServerCore server = new ServerCore(eventManager);
eventManager.RaiseEvent( new ServerStartEvent( ) );
}
}
}
|
b371c7b9e9d490151852c39400559ab71496ee9b
|
[
"C#"
] | 3
|
C#
|
KAmaia/Server
|
b2a7d06d212dd44927272111ba4c1cb3ea4ed0eb
|
12b3a2564b6741f2b7ed65864595986e2b9277ec
|
refs/heads/master
|
<repo_name>MateuszSwiniarski/homework07<file_sep>/src/main/java/com/rodzyn/homework07/controller/MenuController.java
package com.rodzyn.homework07.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("menu")
public class MenuController {
@GetMapping
public String getMenu(){
return "menu";
}
}
<file_sep>/src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://remotemysql.com:3306/3kKO1vAoTT
spring.datasource.username=3kKO1vAoTT
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver<file_sep>/src/main/java/com/rodzyn/homework07/repository/CarRepository.java
package com.rodzyn.homework07.repository;
import com.rodzyn.homework07.model.Cars;
import java.util.List;
public interface CarRepository {
List<Cars> getAllCar();
void saveCar(long carId, String mark, String model, String color, long productionYear);
void deleteCar(long id);
void updateCar(Cars newCar);
Cars getCarById(long id);
List<Cars> getCarByYear(long start, long end);
void deleteAllCars();
}
<file_sep>/src/main/java/com/rodzyn/homework07/model/news/News.java
package com.rodzyn.homework07.model.news;
public class News {
private long newsId;
private String author;
private String title;
private String description;
private String url;
private String published;
public News() {
}
public News(String author, String title, String description, String url, String published) {
this.author = author;
this.title = title;
this.description = description;
this.url = url;
this.published = published;
}
public News(long newsId, String author, String title, String description, String url, String published) {
this.newsId = newsId;
this.author = author;
this.title = title;
this.description = description;
this.url = url;
this.published = published;
}
public long getNewsId() {
return newsId;
}
public void setNewsId(long newsId) {
this.newsId = newsId;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPublished() {
return published;
}
public void setPublished(String published) {
this.published = published;
}
@Override
public String toString() {
return "News{" +
". news_id'" + newsId + '\'' +
", author='" + author + '\'' +
", title='" + title + '\'' +
", description='" + description + '\'' +
", url='" + url + '\'' +
", published='" + published + '\'' +
'}';
}
}
<file_sep>/src/main/java/com/rodzyn/homework07/service/CarService.java
package com.rodzyn.homework07.service;
import com.rodzyn.homework07.model.Cars;
import com.rodzyn.homework07.model.Range;
import com.rodzyn.homework07.repository.CarRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class CarService {
private CarRepository carRepository;
@Autowired
public CarService(CarRepository carRepository) {
this.carRepository = carRepository;
carRepository.deleteAllCars();
carRepository.saveCar(1L, "Fiat", "126p", "blue", 1994L);
carRepository.saveCar(2L, "Polonez", "Caro", "red", 1997L);
carRepository.saveCar(3L, "Audi", "Q8", "white", 2017L);
carRepository.saveCar(4L, "Kia", "Ceed", "black", 2016L);
}
public List<Cars> getAllCars(){
return carRepository.getAllCar();
}
public void saveCar(long carId, String mark, String model, String color, long productionYear){
carRepository.saveCar(carId, mark, model, color, productionYear);
}
public void updateCar(Cars newCar){
carRepository.updateCar(newCar);
}
public void deleteCar(long id){
carRepository.deleteCar(id);
}
public Cars getCarById(long id){
return carRepository.getCarById(id);
}
public List<Cars> getCarsByYears(long start, long end){
return carRepository.getCarByYear(start, end);
}
private Range newRange = new Range();
public Range getNewRange() {
return newRange;
}
public void setNewRange(Range newRange) {
this.newRange = newRange;
}
}
|
8fa8d9d532ecf2c38f13ef9368412f382fe90a0f
|
[
"Java",
"INI"
] | 5
|
Java
|
MateuszSwiniarski/homework07
|
3eebbc8602d707f9dccd62fcba8382264bd076ab
|
68b36482371ddb2c65a1cb7557cad4925f013685
|
refs/heads/master
|
<repo_name>suman-somu/contactsMessageApp<file_sep>/src/MyApp.java
import java.sql.SQLOutput;
import java.util.Scanner;
public class MyApp {
public static Scanner sc= new Scanner(System.in);
//shown the name and after greetings ,
// transfer the control to MainFunction method to continue.
public static void main(String[] args) {
System.out.println("enter your name:");
String name=sc.nextLine();
System.out.println("hello " + name +"\nwelcome to the app");
MainFunction();
}
public static void MainFunction(){
System.out.println("options: \n"+
"\t1 manage contacts \n"+
"\t2 messages \n"+
"\t3 quit ");
int choice =sc.nextInt();
switch (choice){
case 1:
manageContacts();
break;
case 2:
manageMessages();
break;
case 3:
break;
default:
System.out.println(" invalid choice \n choose a number from available options");
MainFunction();
break;
}
}
private static void manageMessages() {
System.out.println("options: \n" +
"\t1 see the list of messages \n" +
"\t2 send a new message \n" +
"\t3 go back to previous menu \n");
int choice= sc.nextInt();
switch (choice){
case 1:
//show all messages
Messages.showAllMessages();
manageMessages();
break;
case 2:
//send a new message
Messages.sendNewMessage();
manageMessages();
break;
case 3:
//go back to previous menu
MainFunction();
break;
}
}
private static void manageContacts(){
System.out.println("choices available: \n"+
"\t1 show all contacts \n"+
"\t2 add a new contact \n"+
"\t3 search a contact \n"+
"\t4 delete a contact \n"+
"\t5 go back to previous menu ");
int choice = sc.nextInt();
switch (choice){
case 1:
//show all contacts
Contacts.showAllContacts();
manageContacts();
break;
case 2:
// add a new contact
Contacts.addContacts();
manageContacts();
break;
case 3:
//search contacts
Contacts.searchContacts();
manageContacts();
break;
case 4:
//delete a contact
Contacts.deleteContact();
manageContacts();
break;
case 5:
//go back to previous menu
MainFunction();
break;
default:
System.out.println(" invalid choice \n choose a number from available options");
manageContacts();
break;
}
}
}<file_sep>/README.md
<h1><div align="center"> Contacts and Message Program </div></h1>
<br><br>
This lets you do all the things in a contacts and messaging app but without GUI.
written in java.
|
a0705474a3c3f70b733fe195116ff68cead02438
|
[
"Markdown",
"Java"
] | 2
|
Java
|
suman-somu/contactsMessageApp
|
ec87d06a91e35fb0bfc1fde6eca8b61788e7e7d7
|
12bbdee864cd4bfc1c4fc28927840c31da1aae33
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import csv from 'jquery-csv'
class MergeCsv extends Component {
constructor(props) {
super(props);
this.state = {
todayDate: null,
dateUseAsNow: "2020-01-23",
cpqCSV: null,
pacDailyCSV: null,
isReadyToProces: false,
smartlyAPIToken: '861fe5f87ac243bd50f11e79c09dbed46d542219',
studykikAuth: '<KEY>',
notFoundLength: 0,
tempNotFoundLength: 0
}
}
componentDidMount() {
var yesterday = new Date((new Date()).valueOf() - 1000*60*60*24);
this.state.todayDate = this.formatDate(yesterday);
}
formatDate(d) {
var day = d.getUTCDate() > 9 ? d.getUTCDate() : '0'+d.getUTCDate();
var month = d.getUTCMonth()+1 > 9 ? (d.getUTCMonth()+1) : '0'+(d.getUTCMonth()+1);
return d.getUTCFullYear() + '-' + month + '-' + day;
}
getFile = name => e => {
var _this = this;
var file = e.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var _csv = event.target.result;
var data = csv.toArrays(_csv);
if(name === 'cpqCSV'){
data[0].push('newSignUp');
data[0].push('sourceName');
data[0].push('isMediaTracking');
data[0].push('tierNumber');
data[0].push('sponsor');
//_this.finalizeMergedCSVFile(data);
}
_this.state[name] = data;
if(_this.state.cpqCSV != null && _this.state.pacDailyCSV != null)
_this.setState({isReadyToProces: true});
}
}
startMergingProcess = () => {
var _this = this;
var header = this.state.cpqCSV[0];
var cpqCSV = this.state.cpqCSV;
cpqCSV.shift();
var pacDailyCSV = this.state.pacDailyCSV;
pacDailyCSV.shift();
var ctr = 0;
var matchedStudyIDs = [];
cpqCSV.forEach(cpqEl => {
var tempStudyID = cpqEl[3];
var tempIndication = cpqEl[8];
var matchFound = pacDailyCSV.filter(function(pacEl){
return (pacEl[0] == tempStudyID && pacEl[2] == tempIndication);
});
if(matchFound.length) { //FOUND
ctr+=1;
var sum = 0;
for (var i = matchFound.length - 1; i >= 0; i--) {
sum += parseInt(matchFound[i][1]);
};
matchedStudyIDs.push(matchFound[0][0]);
matchFound = ['', sum, '', matchFound[0][3], matchFound[0][4], matchFound[0][5], matchFound[0][6]];
} else { //NOT FOUND
matchFound = ['', 0, '', '', '', '', '', ''];
}
cpqEl.push(matchFound[1]);
cpqEl.push(matchFound[3]);
cpqEl.push(matchFound[4]);
cpqEl.push(matchFound[5]);
cpqEl.push(matchFound[6]);
});
cpqCSV.unshift(header);
console.log('total matchFound: '+ctr);
this.processNotFound(matchedStudyIDs);
//this.finalizeMergedCSVFile(cpqCSV);
}
processNotFound = (matchedStudyIDs) => {
var notFound = [];
for(var i=0; i<this.state.pacDailyCSV.length; i++) {
var pacEl = this.state.pacDailyCSV[i];
var tempStudyID = pacEl[0];
var matchFound = matchedStudyIDs.find(function(el){
return (el == tempStudyID);
});
if(matchFound == undefined) {
notFound.push(pacEl);
}
}
this.state.notFoundLength = notFound.length;
console.log(notFound);
console.log('total notFound: ' +this.state.notFoundLength);
var reqCtr = 0;
for(var i=0; i<this.state.notFoundLength; i++) {
var newCSVValue = [];
var _tempNotFound = notFound[i];
this.sendRequest(_tempNotFound);
}
// this.state.cpqCSV.push()
}
sendRequest = (tempNotFound, callback) => {
var studyID = tempNotFound[0];
var url = "https://api.studykik.com/api/v1/studies/"+studyID+"?filter={%22include%22:[{%22relation%22:%22campaigns%22,%22scope%22:{%22order%22:%22orderNumber%20DESC%22}},{%22relation%22:%22protocol%22},{%22relation%22:%22site%22},{%22relation%22:%22sources%22},{%22relation%22:%22sponsor%22},{%22relation%22:%22indication%22}]}";
fetch(url, {
headers: {
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Authorization": this.state.studykikAuth
},
credentials: "include"
})
.then(response => response.json())
.then(json => {
json["tempNotFound"] = tempNotFound;
//callback(json);
var newCSVValue = [];
var campaign = json.campaigns && json.campaigns.length ? json.campaigns[0] : "";
newCSVValue[0] = campaign.id;
newCSVValue[1] = this.getDateToUTCSK(campaign.startDate);
newCSVValue[2] = this.getDateToUTCSK(campaign.endDate);
newCSVValue[3] = json.id;
newCSVValue[4] = json.site_id;
newCSVValue[5] = campaign.central ? "TRUE" : "FALSE";
newCSVValue[6] = campaign.patientQualificationSuite ? "TRUE" : "FALSE";
newCSVValue[7] = this.getLevel(campaign.level_id);
newCSVValue[8] = json.indication.name;
newCSVValue[9] = json.protocol.number;
newCSVValue[10] = json.site.name;
newCSVValue[11] = json.site.city;
newCSVValue[12] = json.site.state;
newCSVValue[13] = json.site.zip;
newCSVValue[14] = tempNotFound[1];
newCSVValue[15] = 0;
newCSVValue[16] = 0;
newCSVValue[17] = this.state.dateUseAsNow;
newCSVValue[18] = campaign.startDate
newCSVValue[19] = campaign.endDate
newCSVValue[20] = 0;
newCSVValue[21] = tempNotFound[1];
newCSVValue[22] = 0;
newCSVValue[23] = 0;
newCSVValue[24] = tempNotFound[1];
newCSVValue[25] = 0;
newCSVValue[26] = 0;
newCSVValue[27] = 0;
newCSVValue[28] = 0;
newCSVValue[29] = 0;
newCSVValue[30] = 0;
newCSVValue[31] = 0;
newCSVValue[32] = tempNotFound[1];
newCSVValue[33] = 0;
newCSVValue[34] = 0;
newCSVValue[35] = 0;
newCSVValue[36] = 0;
newCSVValue[37] = 0;
newCSVValue[38] = 0;
newCSVValue[39] = 0;
newCSVValue[40] = tempNotFound[1];
newCSVValue[41] = tempNotFound[3];
newCSVValue[42] = tempNotFound[4];
newCSVValue[43] = tempNotFound[5];
newCSVValue[44] = tempNotFound[6];
//console.log('end here...');
//console.log(newCSVValue);
this.state.cpqCSV.push(newCSVValue);
this.state.tempNotFoundLength = this.state.tempNotFoundLength+1;
if(this.state.tempNotFoundLength == this.state.notFoundLength)
console.log(this.state.cpqCSV);
/*console.log(reqCtr);
if(reqCtr+1 == this.state.notFoundLength) {
console.log(this.state.cpqCSV);
this.finalizeMergedCSVFile(this.state.cpqCSV);
}*/
})
.catch((error) => {
console.log(error);
});
}
getLevel = (levelID) => {
var levels = [
"Bronze",
"Silver",
"Gold",
"Platinum",
"Diamond",
"Ruby",
"Platinum Plus",
"Diamond Plus",
"Ruby Plus"
];
return levels[levelID-1];
}
getDateToUTCSK = (date) => {
var dayName = [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
];
var monthName = [
"Jan", "Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
var _date = new Date(date);
var day = _date.getUTCDate();
var dayVal = dayName[_date.getUTCDay()];
var monVal = monthName[_date.getUTCMonth()];
var year = _date.getUTCFullYear();
return dayVal + " " + monVal + " " + day + " " + year + " 00:00:00 GMT+0000 (UTC)";
}
saveToCSV = () => {
this.finalizeMergedCSVFile(this.state.cpqCSV);
}
finalizeMergedCSVFile = (cpqCSV) => {
console.log(cpqCSV);
var csvContent = "data:text/csv;charset=utf-8,"
+ csv.fromArrays(cpqCSV);
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link);
link.click();
}
render() {
return (
<div className="process-csv" style={{'textAlign':'left'}}>
<hr/>
<h2>
Merging of campaign_patient_quality and pac_daily_report
</h2>
<p>Change the value of studykik auth and daily date before merging the files</p>
<br/>
<div style={{'float':'left'}}>
<div>Select campaign_patient_quality CSV</div>
<input type="file" accept=".csv" onChange={this.getFile('cpqCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<br/>
<div style={{'float':'left'}}>
<div>Select pac_daily_report CSV</div>
<input type="file" accept=".csv" onChange={this.getFile('pacDailyCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<br/>
{(this.state.isReadyToProces) && <button onClick={this.startMergingProcess}>Start Merging!</button>}
<br/>
<br/>
<button onClick={this.saveToCSV}>Click When Done Fetching!</button>
</div>
);
}
}
export default MergeCsv;<file_sep>import React, { Component } from 'react';
import csv from 'jquery-csv'
class MergeCraigslistAdspent extends Component {
constructor(props) {
super(props);
this.state = {
todayDate: null,
dateUseAsNow: "2020-01-22",
cpqCSV: null,
craigslistAdSpentCSV: null
}
}
componentDidMount() {
var yesterday = new Date((new Date()).valueOf() - 1000*60*60*24);
this.state.todayDate = this.formatDate(yesterday);
}
formatDate(d) {
var day = d.getUTCDate() > 9 ? d.getUTCDate() : '0'+d.getUTCDate();
var month = d.getUTCMonth()+1 > 9 ? (d.getUTCMonth()+1) : '0'+(d.getUTCMonth()+1);
return d.getUTCFullYear() + '-' + month + '-' + day;
}
getFile = name => e => {
var _this = this;
var file = e.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var _csv = event.target.result;
var data = csv.toArrays(_csv);
if(name === 'cpqCSV'){
data[0].push('sponsorId');
data[0].push('croId');
data[0].push('cro');
data[0].push('disposition');
data[0].push('dispositionTotal');
data[0].push('clAdspent');
}
_this.state[name] = data;
if(_this.state.cpqCSV != null && _this.state.craigslistAdSpentCSV != null)
_this.setState({isReadyToProces: true});
}
}
startMergingProcess = () => {
var _this = this;
var header = this.state.cpqCSV[0];
var cpqCSV = this.state.cpqCSV;
cpqCSV.shift();
var craigslistAdSpentCSV = this.state.craigslistAdSpentCSV;
craigslistAdSpentCSV.shift();
craigslistAdSpentCSV.shift();
console.log(craigslistAdSpentCSV);
var dateUseAsNow = new Date(this.state.dateUseAsNow);
//clean craigslistAdSpentCSV data
var filteredCraigslistAdSpentCSV = craigslistAdSpentCSV.filter(function(el){
var startDate = new Date(el[4]); //cl start date
var endDate = new Date(el[5]); //cl end date
//var endDate = new Date((new Date(el[5])).valueOf() - 1000*60*60*24);
return (startDate <= dateUseAsNow && endDate >= dateUseAsNow);
});
console.log(filteredCraigslistAdSpentCSV);
var temparr = [];
for(var i=0; i<this.state.cpqCSV.length; i++) {
var temp = this.state.cpqCSV[i];
var tempCLSpent = filteredCraigslistAdSpentCSV.filter(function(el) {
return (el[1] == temp[3]);
});
var spent = 0;
if(tempCLSpent.length) {
tempCLSpent.forEach(function(el) {
var number = Number(el[6].replace(/[^0-9.-]+/g,"")); //DONE CHANGING THIS TO TOTAL SPENT! - COL 6
spent += number;
});
temparr.push(this.state.cpqCSV[i]);
}
this.state.cpqCSV[i][50] = spent;
}
console.log('with spent');
console.log(temparr);
var nomatch = filteredCraigslistAdSpentCSV.filter(function(el) {
var f = temparr.find(function(t){
return (t[3] == el[1]);
});
return !(f);
});
console.log('did not match');
console.log(nomatch);
this.state.cpqCSV.unshift(header);
this.finalizeMergedCSVFile(this.state.cpqCSV);
}
saveToCSV = () => {
this.finalizeMergedCSVFile(this.state.cpqCSV);
}
finalizeMergedCSVFile = (cpqCSV) => {
console.log(cpqCSV);
var csvContent = "data:text/csv;charset=utf-8,"
+ csv.fromArrays(cpqCSV);
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link);
link.click();
}
render() {
return (
<div className="process-csv" style={{'textAlign':'left'}}>
<hr/>
<h2>
Merging of campaign_patient_quality MERGEDFINAL2! and Craigslist Ad Spent
</h2>
<br/>
<div style={{'float':'left'}}>
<div>Select campaign_patient_quality MERGEDFINAL2! CSV</div>
<input type="file" accept=".csv" onChange={this.getFile('cpqCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<br/>
<div style={{'float':'left'}}>
<div>Select Craigslist Ad Spent CSV</div>
<input type="file" accept=".csv" onChange={this.getFile('craigslistAdSpentCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<br/>
{(this.state.isReadyToProces) && <button onClick={this.startMergingProcess}>Start Merging!</button>}
<br/>
<br/>
<button onClick={this.saveToCSV}>Click When Done Fetching!</button>
</div>
);
}
}
export default MergeCraigslistAdspent;<file_sep>import React, { Component } from 'react';
import csv from 'jquery-csv'
class UpdatedCPQ_PAC_CLSpent_Merging extends Component {
constructor(props) {
super(props);
this.state = {
actualYesterdayDateUTC: null,
dateUseAsNow: "2020-07-30",
previousCpqCSV: null,
currentCpqCSV: null,
pacDailyUTMCSV: null,
craigslistAdSpentCSV: null,
studyPatientMediaCSV: null,
kenshooSpentCSV: null,
finalCPQCSV: null,
campaignCostSummaryCSV: null,
headerToUse: [],
patientsPreScreenedCNCByMediaName: [],
patientsSignUpByMediaName: [],
studyPatientsByMedia: [],
mediaNamesTracked: ['fb', //FACEBOOK
'cl', //CRAIGSLIST
'fg', //FOCUS GROUP
'snapchat', //SNAPCHAT
'tek918', //TEST UTM
'clla',
'clb',
'clch',
'clny',
'luna',
'clxgigs',
'clxjobs',
'facebooklink',
'instagramlink',
'facebookmessenger',
'instagramstory',
'emailblast',
'googleadwords',
],
isReadyToProces: false,
smartlyAPIToken: '861fe5f87ac243bd50f11e79c09dbed46d542219',
studykikAuth: '<KEY>',
clPTSD_Watch: [
4011675,
4011674,
4011673,
4011671,
4011670,
4011668,
4011667,
4011666,
4011665,
4011664,
4011651,
4011650,
4011649,
4011648,
4011647,
4011644,
4011642,
4011641,
4011639,
4011638,
4011637,
4011635,
4011632,
4011662,
4011646,
4011643,
4011640,
4011645,
4011672,
4011663,
4011661,
4011660,
4011658,
4011657,
4011656,
4011655,
4011654,
4011653,
4011652,
4011629,
4011627,
4011626,
4011625,
4011631,
4011623,
4011628,
4011630,
4011621,
4011622
],
clPTSDProtocol_Watch: [
"331-201-00072",
"331-201-00071",
"331-201-00071 and 331-201-00072 bucket"
],
}
}
componentDidMount() {
var yesterday = new Date((new Date()).valueOf() - 1000*60*60*24);
this.state.actualYesterdayDateUTC = this.formatDateUTC(yesterday);
}
formatDateUTC(d) {
var day = d.getUTCDate() > 9 ? d.getUTCDate() : '0'+d.getUTCDate();
var month = d.getUTCMonth()+1 > 9 ? (d.getUTCMonth()+1) : '0'+(d.getUTCMonth()+1);
return d.getUTCFullYear() + '-' + month + '-' + day;
}
getFile = name => e => {
var _this = this;
var file = e.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var _csv = event.target.result;
var data = csv.toArrays(_csv);
if(name === 'previousCpqCSV'){
_this.state.headerToUse = data[0];
}
_this.state[name] = data;
//ALL FILES HAS BEEN LOADED!
/*if(_this.state.previousCpqCSV != null &&
_this.state.currentCpqCSV != null &&
_this.state.pacDailyUTMCSV != null &&
_this.state.craigslistAdSpentCSV != null) {
_this.setState({isReadyToProces: true});
}*/
if(_this.state.currentCpqCSV != null) {
_this.setState({isReadyToProces: true});
}
}
}
removeHeaders = () => {
if(this.state.currentCpqCSV) this.state.currentCpqCSV.shift();
if(this.state.pacDailyUTMCSV) this.state.pacDailyUTMCSV.shift();
if(this.state.previousCpqCSV) this.state.previousCpqCSV.shift();
if(this.state.craigslistAdSpentCSV) {
this.state.craigslistAdSpentCSV.shift();
this.state.craigslistAdSpentCSV.shift()
}
if(this.state.studyPatientMediaCSV) this.state.studyPatientMediaCSV.shift();
if(this.state.kenshooSpentCSV) this.state.kenshooSpentCSV.shift();
}
startMergingProcess = () => {
var _this = this;
console.log('FINAL HEADERS');
console.log(this.state.headerToUse);
this.removeHeaders();
//STEP1: Flatten currentCpqCSV and create new array for patients, prescreened, cnc by media name
this.step1FlattenCurrentCpqCSV();
//STEP2: MERGE currentCpqCSV AND pacDailyUTMCSV
this.step2MergePACDailyUTMCSV();
}
startCampaignCostMergingProcess = () => {
//if(this.state.finalCPQCSV) this.state.finalCPQCSV.shift();
if(this.state.campaignCostSummaryCSV) this.state.campaignCostSummaryCSV.shift();
var notFoundStudies = [];
var sumNotFoundStudiesSpent = 0;
for(var i=0; i<this.state.campaignCostSummaryCSV.length; i++){
var temp = this.state.campaignCostSummaryCSV[i];
var findStudy = this.state.finalCPQCSV.find(function(el, index) {
return el[3] == temp[0];
});
if(findStudy == undefined) {
notFoundStudies.push(temp);
sumNotFoundStudiesSpent += (temp[1] > 0) ? parseFloat(temp[1]) : 0;
} else {
var checkDupe = this.state.finalCPQCSV.filter(function(el) {
return el[3] == temp[0];
});
var tempStudyIndex = null;
for(var j=1; j<this.state.finalCPQCSV.length; j++) {
if(checkDupe.length > 1){
if(this.state.finalCPQCSV[j][3] == temp[0] && tempStudyIndex == null) {
tempStudyIndex = j;
} else if(this.state.finalCPQCSV[j][3] == temp[0]) {
var currDate = new Date(this.state.finalCPQCSV[tempStudyIndex][18]+" 00:00:00");
var tempDate = new Date(this.state.finalCPQCSV[j][18]+" 00:00:00");
tempStudyIndex = (currDate >= tempDate) ? tempStudyIndex : j;
}
} else if(this.state.finalCPQCSV[j][3] == temp[0]) {
tempStudyIndex = j;
break;
}
}
this.state.finalCPQCSV[tempStudyIndex][54] = (temp[1] > 0) ? temp[1] : 0;
}
}
console.log("!!! STUDIES IN CAMPAIGN COST CSV BUT NOT IN DAILY DATA");
console.log(notFoundStudies);
console.log('!!! TOTAL OF NOT FOUND STUDIES IN CAMPAIGN COST CSV: '+sumNotFoundStudiesSpent);
this.finalizeMergedCSVFile(this.state.finalCPQCSV);
}
/**
* STEP1: Flatten currentCpqCSV
* And create new array for patients, prescreened, cnc by media name
*/
step1FlattenCurrentCpqCSV = () => {
console.log('>>>Start Step1 FlattenCurrentCpqCSV');
var doneProcessing = [];
var newCPQ = [];
for(var i=0; i<this.state.currentCpqCSV.length; i++) {
var study = this.state.currentCpqCSV[i];
var isProcessed = doneProcessing.find(function(el) {
return (study[0] == el[0] && //campaignID
study[3] == el[3] && //studyID
study[4] == el[4] && //siteID
study[5] == el[5] && //central
study[6] == el[6] ); //pqs
});
if(isProcessed) {
continue;
}
else {
var findStudy = this.state.currentCpqCSV.filter(function(el, index) {
return (study[0] == el[0] && //campaignID
study[3] == el[3] && //studyID
study[4] == el[4] && //siteID
study[5] == el[5] && //central
study[6] == el[6] ); //pqs
});
if(findStudy.length) {
doneProcessing.push(findStudy[0]);
var tempSumPPSCNC = [0, 0, 0];
var tempByMediaPPSCNC = {'campaignID':study[0], 'studyID':study[3], 'patientsByMedia':[]};
for(var j=0; j<findStudy.length; j++) {
tempSumPPSCNC[0] += parseInt(findStudy[j][15]); //patients
tempSumPPSCNC[1] += parseInt(findStudy[j][16]); //prescreened
tempSumPPSCNC[2] += parseInt(findStudy[j][17]); //cnc
tempByMediaPPSCNC.patientsByMedia.push([findStudy[j][0], findStudy[j][3], findStudy[j][10] == '' ? 'fb' : findStudy[j][10], parseInt(findStudy[j][15]), parseInt(findStudy[j][16]), parseInt(findStudy[j][17])]);
}
study.splice(10, 1);//REMOVE UTM COLUMN
study[14] = tempSumPPSCNC[0]; //new patients
study[15] = tempSumPPSCNC[1]; //new prescreened
study[16] = tempSumPPSCNC[2]; //new cnc
this.state.patientsPreScreenedCNCByMediaName.push(tempByMediaPPSCNC);
newCPQ.push(study);
}
}
}
this.state.currentCpqCSV = newCPQ;
//this.finalizeMergedCSVFile(newCPQ);
}
/**
* STEP2: MERGE currentCpqCSV AND pacDailyUTMCSV
* Columns: newSignUp, sourceName, isMediaTracking, tierNumber, sponsor
*/
step2MergePACDailyUTMCSV = () => {
console.log('>>>Start Step2 MergePACDailyUTMCSV');
var matchedStudyIDs = [];
var currentCpqCSV = this.state.currentCpqCSV;
var pacDailyUTMCSV = this.state.pacDailyUTMCSV;
for(var z=0; z<this.state.currentCpqCSV.length; z++) {
var cpqEl = this.state.currentCpqCSV[z];
var tempStudyID = cpqEl[3];
var tempIndication = cpqEl[8];
var tempByMediaSignUp = {'studyID': tempStudyID, 'signUp':[]};
var firstIndex = this.state.currentCpqCSV.findIndex(function(el, index){
return (tempStudyID == el[3]);
});
var filterStudy = this.state.currentCpqCSV.filter(function(el){
return (tempStudyID == el[3]);
});
var matchFound = pacDailyUTMCSV.filter(function(pacEl){
return (pacEl[0] == tempStudyID); // && pacEl[2] == tempIndication); REMOVING THE INDICATION ON THE MATCHING CONDITION BECAUSE OF SPECIAL CHARACTER ISSUE
});
if(matchFound.length) { //FOUND
var sum = 0;
for (var i = matchFound.length - 1; i >= 0; i--) {
sum += parseInt(matchFound[i][1]);
tempByMediaSignUp.signUp.push([tempStudyID, matchFound[i][4] == '' ? 'fb' : matchFound[i][4], parseInt(matchFound[i][1])]);
};
this.state.patientsSignUpByMediaName.push(tempByMediaSignUp);
matchedStudyIDs.push(tempStudyID);
if(filterStudy.length > 1 && firstIndex == z) {
sum = 0; //INITIAL SUM IS SET O, ASSUMED THIS IS THE PREVIOUS CAMPAIGN ID
}
// SIGNUPS SOURCENAME ISMEDIATRACKING TIERNUMBER SPONSOR
matchFound = [sum, matchFound[0][3], matchFound[0][7], matchFound[0][5], matchFound[0][6]];
} else { //NOT FOUND
matchFound = [0, '', '', '', '', '', ''];
}
cpqEl[17] = this.state.dateUseAsNow; //DATE
cpqEl[18] = this.getDateFormatted(cpqEl[1]); //DATEFROMPARSED
cpqEl[19] = this.getDateFormatted(cpqEl[2]); //DATEFROMPARSED
// MERGE2 COLUMNS
cpqEl[40] = matchFound[0]; //NEW SIGNUP
cpqEl[41] = matchFound[1]; //SOURCE NAME
cpqEl[42] = matchFound[2]; //IS MEDIA TRACKING
cpqEl[43] = matchFound[3]; //TIER NUMBER
cpqEl[44] = matchFound[4]; //SPONSOR
this.state.currentCpqCSV[z] = cpqEl;
}
console.log('Total MatchFound in PAC Daily UTM: '+matchedStudyIDs.length);
//this.finalizeMergedCSVFile(currentCpqCSV);
this.processNotFoundPacDailyStudies(matchedStudyIDs);
}
processNotFoundPacDailyStudies = (matchedStudyIDs) => {
var notFound = [];
for(var i=0; i<this.state.pacDailyUTMCSV.length; i++) {
var pacEl = this.state.pacDailyUTMCSV[i];
var tempStudyID = pacEl[0];
var matchFound = matchedStudyIDs.find(function(el){
return (el == tempStudyID);
});
var matchDupe = notFound.find(function(_pacEl){
return (_pacEl[0] == tempStudyID);
});
if(matchFound == undefined && matchDupe == undefined) {
notFound.push(pacEl);
}
}
this.state.notFoundLength = notFound.length;
console.log('Total Not Found in PAC Daily UTM: ' +this.state.notFoundLength);
if(notFound.length == 0) { //NOTE REMOVE THIS
console.log('>>>All PAC Daily UTM has been matched');
//this.finalizeMergedCSVFile(this.state.currentCpqCSV);
this.step3MergeCraigslistAdspent();
} else {
console.log('!!!!! Pac Daily Studies Not Found in CPQ');
console.log('!!!!! These studies are not added on the daily CPQ data');
console.log(notFound);
this.step3MergeCraigslistAdspent();
/* COMMENTED FOR 2020-02-05 DATA ONWARDS
this.state.isSendingRequests = true;
var _this = this;
var i=0;
console.log('>>>Sending request for Pac Daily Merge Not Found');
this.state.intervalId = setInterval(function() {
_this.sendPacDailyMergeNotFoundRequest(notFound[i], i);
i++;
if(i == _this.state.notFoundLength) {
console.log('>>>Cleared interval for sendPacDailyMergeNotFoundRequest');
_this.state.isSendingRequests = false;
clearInterval(_this.state.intervalId);
}
}, 200);
*/
}
}
//GET THE INFO OF THE STUDIES IN PAC DAILY THAT IS NOT ON CPQ
sendPacDailyMergeNotFoundRequest = (tempNotFound, index) => {
var studyID = tempNotFound[0];
var url = "https://api.studykik.com/api/v1/studies/"+studyID+"?filter={%22include%22:[{%22relation%22:%22campaigns%22,%22scope%22:{%22order%22:%22orderNumber%20DESC%22}},{%22relation%22:%22protocol%22},{%22relation%22:%22site%22},{%22relation%22:%22sources%22},{%22relation%22:%22sponsor%22},{%22relation%22:%22indication%22}]}";
fetch(url, {
headers: {
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Authorization": this.state.studykikAuth
},
credentials: "include"
})
.then(response => response.json())
.then(json => {
json["tempNotFound"] = tempNotFound;
var newCSVValue = [];
var campaign = json.campaigns && json.campaigns.length ? json.campaigns[0] : "";
newCSVValue[0] = campaign.id;
newCSVValue[1] = this.getDateToUTCSK(campaign.startDate);
newCSVValue[2] = this.getDateToUTCSK(campaign.endDate);
newCSVValue[3] = json.id;
newCSVValue[4] = json.site_id;
newCSVValue[5] = campaign.central ? "TRUE" : "FALSE";
newCSVValue[6] = campaign.patientQualificationSuite ? "TRUE" : "FALSE";
newCSVValue[7] = this.getLevel(campaign.level_id);
newCSVValue[8] = json.indication.name;
newCSVValue[9] = json.protocol.number;
newCSVValue[10] = json.site.name;
newCSVValue[11] = json.site.city;
newCSVValue[12] = json.site.state;
newCSVValue[13] = json.site.zip;
newCSVValue[14] = tempNotFound[1]; //patients
newCSVValue[15] = 0;
newCSVValue[16] = 0;
newCSVValue[17] = this.state.dateUseAsNow;
newCSVValue[18] = campaign.startDate
newCSVValue[19] = campaign.endDate
newCSVValue[20] = 0;
newCSVValue[21] = tempNotFound[1]; //patients_acc
newCSVValue[22] = 0;
newCSVValue[23] = 0;
newCSVValue[24] = tempNotFound[1]; //New Patient
newCSVValue[25] = 0;
newCSVValue[26] = 0;
newCSVValue[27] = 0;
newCSVValue[28] = 0;
newCSVValue[29] = 0;
newCSVValue[30] = 0;
newCSVValue[31] = 0;
newCSVValue[32] = tempNotFound[1]; //New Patient Acc
newCSVValue[33] = 0;
newCSVValue[34] = 0;
newCSVValue[35] = 0;
newCSVValue[36] = 0;
newCSVValue[37] = 0;
newCSVValue[38] = 0;
newCSVValue[39] = 0;
//CALCULATE FOR TOTAL SIGNUPS AND SIGNUPS BY MEDIA NAME
var matchFound = this.state.pacDailyUTMCSV.filter(function(pacEl){
return (pacEl[0] == tempNotFound[0]);
});
var sum = 0;
if(matchFound.length) { //FOUND
var tempByMediaSignUp = {'studyID': studyID, 'signUp':[]};
for (var i = matchFound.length - 1; i >= 0; i--) {
sum += parseInt(matchFound[i][1]);
tempByMediaSignUp.signUp.push([studyID, matchFound[i][4] == '' ? 'fb' : matchFound[i][4], parseInt(matchFound[i][1])]);
};
this.state.patientsSignUpByMediaName.push(tempByMediaSignUp);
}
newCSVValue[40] = sum; //tempNotFound[1]; //compute!
newCSVValue[41] = tempNotFound[3];
newCSVValue[42] = tempNotFound[7];
newCSVValue[43] = tempNotFound[5];
newCSVValue[44] = tempNotFound[6];
this.state.currentCpqCSV.push(newCSVValue);
if(index == this.state.notFoundLength-1){
//this.finalizeMergedCSVFile(this.state.currentCpqCSV);
console.log('>>>Done all sendPacDailyMergeNotFoundRequest');
this.step3MergeCraigslistAdspent();
}
})
.catch((error) => {
console.log(error);
});
}
/**
* STEP3: MERGE CRAIGSLIST ADSPENT AND COUNT REPOSTS
* Columns: clAdspent, clCummTotalSpent, clInitialSpent, clRepost
*/
step3MergeCraigslistAdspent = () => {
console.log('>>>Start Step3 MergeCraigslistAdspent');
var _this = this;
var craigslistAdSpentCSV = this.state.craigslistAdSpentCSV;
var dateUseAsNow = new Date(this.state.dateUseAsNow + " 00:00:00");
var temparr = [];
var clAdDiscrepancy = [];
for(var i=0; i<this.state.currentCpqCSV.length; i++) {
var temp = this.state.currentCpqCSV[i];
var totalAdSpentByStudy = 0;
var totalLatestInitSpent = 0;
var firstIndex = this.state.currentCpqCSV.findIndex(function(el, index){
return (temp[3] == el[3]);
});
var filterStudy = this.state.currentCpqCSV.filter(function(el){
return (temp[3] == el[3]);
});
//FILTER BY STUDY ID
var filteredCraigslistAdSpentCSV = craigslistAdSpentCSV.filter(function(el) {
return (el[1] == temp[3]);
});
//FIND VALUE WITH MAX CL START DATE
var filteredCraigslistMaxCLStartDate = null;
var filteredCraigslistStartDateLessDateNow = null;
if(filteredCraigslistAdSpentCSV.length) {
filteredCraigslistMaxCLStartDate = filteredCraigslistAdSpentCSV[0];
filteredCraigslistStartDateLessDateNow = filteredCraigslistAdSpentCSV[0];
totalAdSpentByStudy = Number(filteredCraigslistAdSpentCSV[0][6].replace(/[^0-9.-]+/g,""));
var tempDate = new Date(filteredCraigslistAdSpentCSV[0][4]+" 00:00:00");
totalLatestInitSpent = (dateUseAsNow.getTime() === tempDate.getTime()) ? parseFloat(filteredCraigslistAdSpentCSV[0][6]) : 0;
for(var z=1; z<filteredCraigslistAdSpentCSV.length; z++){
var prevDate = new Date(filteredCraigslistMaxCLStartDate[4]+" 00:00:00");
var currDate = new Date(filteredCraigslistAdSpentCSV[z][4]+" 00:00:00");
filteredCraigslistMaxCLStartDate = (currDate >= prevDate) ? filteredCraigslistAdSpentCSV[z] : filteredCraigslistMaxCLStartDate;
filteredCraigslistStartDateLessDateNow = (currDate <= dateUseAsNow) ? filteredCraigslistAdSpentCSV[z] : filteredCraigslistStartDateLessDateNow;
totalLatestInitSpent += (dateUseAsNow.getTime() === currDate.getTime()) ? parseFloat(filteredCraigslistAdSpentCSV[z][6]) : 0;
totalAdSpentByStudy += (currDate <= dateUseAsNow) ? parseFloat(filteredCraigslistAdSpentCSV[z][6]) : 0;//Number(filteredCraigslistAdSpentCSV[z][6].replace(/[^0-9.-]+/g,"")) : 0;
}
}
var maxCLStartDate = (filteredCraigslistMaxCLStartDate) ? new Date(filteredCraigslistMaxCLStartDate[4] + " 00:00:00") : null;
var maxCurrStartDate = (filteredCraigslistStartDateLessDateNow) ? new Date(filteredCraigslistStartDateLessDateNow[4] + " 00:00:00") : null;
if(maxCurrStartDate && maxCurrStartDate <= dateUseAsNow) {
var spent = (filteredCraigslistStartDateLessDateNow) ? parseFloat(filteredCraigslistStartDateLessDateNow[6]) : 0;// Number(filteredCraigslistStartDateLessDateNow[6].replace(/[^0-9.-]+/g,"")) : 0;
spent = (filterStudy.length > 1 && firstIndex == i) ? 0 : spent; //IF STUDY IS DUPE IN CPQ, SET TO 0
totalLatestInitSpent = (filterStudy.length > 1 && firstIndex == i) ? 0 : totalLatestInitSpent;
this.state.currentCpqCSV[i][50] = spent; //CURRENT RESPOST SPENT
this.state.currentCpqCSV[i][51] = totalAdSpentByStudy; //TOTAL ADSPENT TILL CL START DATE
this.state.currentCpqCSV[i][52] = totalLatestInitSpent;//(dateUseAsNow.getTime() === maxCurrStartDate.getTime()) ? spent : 0; //INITIAL SPENT OF THE STUDY
this.state.currentCpqCSV[i][53] = filteredCraigslistAdSpentCSV.length; //REPOST COUNT
}
if(maxCLStartDate > dateUseAsNow ) {
clAdDiscrepancy.push(filteredCraigslistAdSpentCSV[0][1]);
}
}
if(clAdDiscrepancy.length) {
console.log('!!!!! CL Ad Spent Discrepancy: Found in CL but Ad is not yet active, Study is in CPQ');
console.log(clAdDiscrepancy);
}
clAdDiscrepancy = [];
//Ad Spent Discrepancy: CL Start Date is active in CL but Study not found in CPQ
var filteredActiveCL = craigslistAdSpentCSV.filter(function(el){
var startDate = new Date(el[4]+" 00:00:00");
return (startDate >= dateUseAsNow);
});
for(var i=0; i<filteredActiveCL.length; i++){
var tempStudyID = filteredActiveCL[i][1];
var findStudy = this.state.currentCpqCSV.find(function(el){
return el[3] == tempStudyID;
});
if(findStudy == undefined) {
clAdDiscrepancy.push(tempStudyID)
}
}
if(clAdDiscrepancy.length) {
console.log('!!!!! CL Ad Spent Discrepancy: Active CL AdSpent but Study is not in CPQ');
console.log(clAdDiscrepancy);
}
//this.finalizeMergedCSVFile(this.state.currentCpqCSV);
this.step4KenshooAdspent();
this.step5AccumulationFromPrevDay();
}
/**
* STEP4: MERGE KENSHOO ADSPENT FOR FACEBOOK
* Columns: adspent
*/
step4KenshooAdspent = () => {
console.log('>>>Start Step4 Merge KenshooAdspent');
//adspent column 20
for(var i=0; i<this.state.currentCpqCSV.length; i++) {
var studyID = this.state.currentCpqCSV[i][3];
var firstIndex = this.state.currentCpqCSV.findIndex(function(el, index){
return (studyID == el[3]);
});
var filterStudy = this.state.currentCpqCSV.filter(function(el){
return (studyID == el[3]);
});
if(filterStudy.length > 1 && firstIndex == i){
continue;
} else {
var filterKenshoo = this.state.kenshooSpentCSV.filter(function(el){
return (el[1].includes(studyID)); //(el[2].includes(studyID));
});
if(filterKenshoo && filterKenshoo.length){
var sumSpent = 0;
sumSpent = filterKenshoo.reduce(function(total, current){
return total + parseFloat(current[3]);//parseFloat(current[4]);
}, 0);
this.state.currentCpqCSV[i][20] = sumSpent;
}
}
}
this.checkNoMatchKenshooSpent();
}
checkNoMatchKenshooSpent = () => {
var noMatchCPQ = [];
for(var i=0; i<this.state.kenshooSpentCSV.length; i++){
var tempLine = this.state.kenshooSpentCSV[i];
var findCL = this.state.currentCpqCSV.find(function(el){
return (tempLine[1].includes(el[3]));//(tempLine[2].includes(el[3]));
});
if(findCL == undefined && parseFloat(tempLine[3]) > 0) { //parseFloat(tempLine[4]) > 0) {
noMatchCPQ.push([tempLine[1], tempLine[3]]);//noMatchCPQ.push([tempLine[2], tempLine[4]]);
}
}
console.log('!!!!! NO MATCH CPQ STUDIES WITH FB (KENSHOO) SPENT');
console.log(noMatchCPQ);
}
/**
* STEP5: ACCUMULATE PREVIOUS DAY CPQ TO CURRENT CPQ CSV
* Columns: patients_acc, prescreened_acc, cnc_acc, New Patient_Acc Call, Attempted_Acc, DNQ_Acc, Action Needed_Acc, Scheduled_Acc, Consented_Acc, Screen Failed_Acc, Randomized_Acc
*/
step5AccumulationFromPrevDay = () => {
console.log('>>>Start Step5 AccumulationFromPrevDay');
var notFound = [];
//NOTFOUNDLENGTH IS # OF PAC DAILY STUDIES THAT WERE NOT IN CPQ
for(var i=0; i < (this.state.currentCpqCSV.length - this.state.notFoundLength); i++) {
var currDayStudy = this.state.currentCpqCSV[i];
var prevDayStudy = this.state.previousCpqCSV.find(function(el){
return (el[0] == currDayStudy[0] && el[3] == currDayStudy[3]);
});
if(prevDayStudy){
var index = 14; //Patient,Prescreened,CNC Index
for(var j=0; j<3; j++) {
this.state.currentCpqCSV[i][21+j] = (currDayStudy[index+j] - prevDayStudy[index+j] < 0) ? 0 : (currDayStudy[index+j] - prevDayStudy[index+j]);
}
var index = 24; //Raw Patient Categories Index, 2020-02-05 Defaulted to 0 because of API restriction
for(var j=0; j<8; j++) {
this.state.currentCpqCSV[i][32+j] = 0; //(currDayStudy[index+j] - prevDayStudy[index+j] < 0) ? 0 : (currDayStudy[index+j] - prevDayStudy[index+j]);
}
} else {
var index = 14; //Patient,Prescreened,CNC Index
for(var j=0; j<3; j++) {
this.state.currentCpqCSV[i][21+j] = currDayStudy[index+j];
}
var index = 24; //Raw Patient Categories Index, 2020-02-05 Defaulted to 0 because of API restriction
for(var j=0; j<8; j++) {
this.state.currentCpqCSV[i][32+j] = 0; //currDayStudy[index+j];
}
notFound.push(this.state.currentCpqCSV[i]);
}
}
//this.finalizeMergedCSVFile(this.state.currentCpqCSV);
//this.finalizeMergedCSVFile(notFound);
this.step6AccumulationPatientNewSignUpMediaName();
}
/**
* GENERATES NEW CSV FILE FOR STUDY PATIENT MEDIA TRACKING
*/
step6AccumulationPatientNewSignUpMediaName = () => {
console.log('>>>Start Step6 AccumulationPatientNewSignUpMediaName');
//console.log('patientsPreScreenedCNCByMediaName');
//console.log(this.state.patientsPreScreenedCNCByMediaName);
//console.log('patientsSignUpByMediaName');
//console.log(this.state.patientsSignUpByMediaName);
//console.log('studyPatientMediaCSV');
//console.log(this.state.studyPatientMediaCSV);
this.state.studyPatientsByMedia = [];
for(var i=0; i < (this.state.currentCpqCSV.length); i++) {
var currDayStudy = this.state.currentCpqCSV[i];
var prevDayStudy = this.state.studyPatientMediaCSV.filter(function(el){
return (el[0] == currDayStudy[0] && el[1] == currDayStudy[3]); //CAMPAIGNID AND STUDYID
});
var patients = this.state.patientsPreScreenedCNCByMediaName.find(function(el){
return (el.campaignID == currDayStudy[0] && el.studyID == currDayStudy[3]);
});
var patientSignUp = this.state.patientsSignUpByMediaName.find(function(el){
return el.studyID == currDayStudy[3];
});
var firstIndex = this.state.currentCpqCSV.findIndex(function(el, index){
return (currDayStudy[3] == el[3]);
});
var filterStudy = this.state.currentCpqCSV.filter(function(el){
return (currDayStudy[3] == el[3]);
});
for(var z=0; z<this.state.mediaNamesTracked.length; z++) {
var currentMediaName = this.state.mediaNamesTracked[z];
var tempMedia = [];
tempMedia[0] = currDayStudy[0]; //CAMPAIGNID
tempMedia[1] = currDayStudy[3]; //STUDYID
tempMedia[2] = currDayStudy[4]; //SITE
tempMedia[3] = this.state.dateUseAsNow; //DATE
tempMedia[4] = currentMediaName; //MEDIA NAME
//PATIENT, PRESCREENED, CNC VALUES
var prevStudyMedia = prevDayStudy.filter(function(el){
return (el[4].toLowerCase() == currentMediaName); //MEDIA NAME
});
var prevLatestStudyMedia = (prevStudyMedia.length) ? prevStudyMedia[0] : null;
if(prevStudyMedia.length > 1) {
//FIND MAX DATE VALUE
for(var d=1; d<prevStudyMedia.length; d++){
var currDate = new Date(prevStudyMedia[d][3]+" 00:00:00");
var maxDate = new Date(prevLatestStudyMedia[3]+" 00:00:00");
prevLatestStudyMedia = (currDate >= maxDate) ? prevStudyMedia[d] : prevLatestStudyMedia;
}
}
var patientMediaValue = (patients) ? patients.patientsByMedia.find(function(el){
return el[2].toLowerCase() == currentMediaName;
}) : undefined;
var patientSignUpMedia = (patientSignUp) ? patientSignUp.signUp.find(function(el){
return el[1].toLowerCase() == currentMediaName;
}) : undefined;
var isPatientMedia = false;
var isSignUpMedia = false;
if(prevLatestStudyMedia == null && patientMediaValue != undefined) {
//IT IS A NEW ENTRY
isPatientMedia = true;
tempMedia[5] = patientMediaValue[3];
tempMedia[6] = patientMediaValue[4];
tempMedia[7] = patientMediaValue[5];
tempMedia[8] = patientMediaValue[3];
tempMedia[9] = patientMediaValue[4];
tempMedia[10] = patientMediaValue[5];
} else if(prevLatestStudyMedia != null && patientMediaValue != undefined){
//DEAL WITH PREVIOUS STUDY MEDIA VALUE
isPatientMedia = true;
tempMedia[5] = patientMediaValue[3];
tempMedia[6] = patientMediaValue[4];
tempMedia[7] = patientMediaValue[5];
tempMedia[8] = (patientMediaValue[3] - prevLatestStudyMedia[5] > 0) ? patientMediaValue[3] - prevLatestStudyMedia[5] : 0;
tempMedia[9] = (patientMediaValue[4] - prevLatestStudyMedia[6] > 0) ? patientMediaValue[4] - prevLatestStudyMedia[6] : 0;
tempMedia[10] =(patientMediaValue[5] - prevLatestStudyMedia[7] >0 ) ? patientMediaValue[5] - prevLatestStudyMedia[7] : 0;
} else if(patientMediaValue == undefined){
//CHECK IF STUDY HAS CL SPENT, AND DEFAULT THE TRACKING TO 0
/*if(currentMediaName == 'cl') {
console.log(currDayStudy[3] + " " + currDayStudy[51]);
}*/
if(((currentMediaName.includes('cl') && currDayStudy[51] > 0) || (currentMediaName == 'fb' && currDayStudy[20] > 0)) && (filterStudy.length == 1 || (filterStudy.length > 1 && firstIndex != i))) {
isPatientMedia = true;
tempMedia[5] = 0;
tempMedia[6] = 0;
tempMedia[7] = 0;
tempMedia[8] = 0;
tempMedia[9] = 0;
tempMedia[10] = 0;
}
}
//check for signup
if(patientSignUpMedia != undefined && (filterStudy.length == 1 || (filterStudy.length > 1 && firstIndex != i))) {
isSignUpMedia = true;
tempMedia[11] = patientSignUpMedia[2]; //newPatient
}
if(isPatientMedia || isSignUpMedia) {
this.state.studyPatientsByMedia.push(tempMedia);
}
}
}
//console.log(this.state.currentCpqCSV);
this.state.currentCpqCSV.unshift(this.state.headerToUse);
this.finalizeMergedCSVFile(this.state.currentCpqCSV);
this.finalizeMergedCSVFile(this.state.studyPatientsByMedia);
console.log('DONE!')
//this.step7TemporaryMigratePTSDFBSignupToCLSignUp();
}
/**
* Migrate FB Signup of all PTSD Studies with CL Adspent and 0 FB Adspent to CL
* Applied to a list of Study IDs based on All Craigslist Adspent sheet
* STARTED ON: 01-27
* ENDED ON: 01-30 DATA
*/
step7TemporaryMigratePTSDFBSignupToCLSignUp = () => {
console.log('>>>Start Step6 TemporaryMigratePTSDFBSignupToCLSignUp');
var _this = this;
var totalNewCLPush = [];
var sumOfAllTransferedSignUp = 0;
for(var i=0; i<this.state.clPTSDProtocol_Watch.length; i++){
var clProtocol = this.state.clPTSDProtocol_Watch[i];
var filterStudiesByProtocol = this.state.currentCpqCSV.filter(function(el){
return (el[9] == clProtocol);
});
for(var k=0; k<filterStudiesByProtocol.length; k++){
/*var clStudyID = this.state.clPTSD_Watch[i];
var filterStudies = this.state.currentCpqCSV.filter(function(el){
return (el[3] == clStudyID);
});
var foundStudy = null;
if(filterStudies.length > 1) { //FIND LATEST CAMPAIGN OF A STUDY IF IT APPREAD TWICE ON THE LIST
var maxStudy = filterStudies[0]; //LATEST CAMPAIGN OF STUDY
for(var j=1; j<filterStudies.length; j++){
var maxStudyDate = new Date(maxStudy[18]+" 00:00:00");
var currStudyDate = new Date(filterStudies[j][18]+" 00:00:00");
maxStudy = (maxStudyDate >= currStudyDate) ? maxStudy : filterStudies[j];
}
foundStudy = maxStudy;
} else if(filterStudies.length == 1) {
foundStudy = filterStudies[0];
}*/
var foundStudy = filterStudiesByProtocol[k];
//IF STUDY HAS CL SPENT BUT NO FB SPENT - wrong
//IF STUDY FOUND UNDER THOSE PROTOCOL, MIGRATE FB SIGNUP TO CL IMMEDIATELY
if(foundStudy) {
var studyPatientFB = this.state.studyPatientsByMedia.findIndex(function(el){
return (el[0] == foundStudy[0] && el[1] == foundStudy[3] && el[4] == 'fb'); //compare campaignID, studyID, medianame
});
var studyPatientCL = this.state.studyPatientsByMedia.findIndex(function(el){
return (el[0] == foundStudy[0] && el[1] == foundStudy[3] && el[4] == 'cl');
});
//IF STUDY HAS FB AND CL ENTRY IN studyPatientsByMedia
if(studyPatientFB != -1 && studyPatientCL != -1) {
var tempFBSignUp = parseInt(this.state.studyPatientsByMedia[studyPatientFB][11]) > 0 ? parseInt(this.state.studyPatientsByMedia[studyPatientFB][11]) : 0;
var tempCLSignUp = parseInt(this.state.studyPatientsByMedia[studyPatientCL][11]) > 0 ? parseInt(this.state.studyPatientsByMedia[studyPatientCL][11]) : 0;
this.state.studyPatientsByMedia[studyPatientCL][11] = tempFBSignUp + tempCLSignUp;
this.state.studyPatientsByMedia[studyPatientFB][11] = 0;
console.log(">> FOUND STUDY WITH FB AND CL PRESENT IN studyPatientsByMedia "+tempFBSignUp);
sumOfAllTransferedSignUp += tempFBSignUp;
console.log(foundStudy[0]+" "+foundStudy[3]);
} else if(studyPatientFB != -1 && studyPatientCL == -1) {
var tempFBSignUp = parseInt(this.state.studyPatientsByMedia[studyPatientFB][11]) > 0 ? parseInt(this.state.studyPatientsByMedia[studyPatientFB][11]) : 0;
var newCLpush = [];
newCLpush[0] = this.state.studyPatientsByMedia[studyPatientFB][0];
newCLpush[1] = this.state.studyPatientsByMedia[studyPatientFB][1];
newCLpush[2] = this.state.studyPatientsByMedia[studyPatientFB][2];
newCLpush[3] = this.state.studyPatientsByMedia[studyPatientFB][3];
newCLpush[4] = 'cl';
newCLpush[5] = tempFBSignUp; //patients
newCLpush[6] = 0;
newCLpush[7] = 0;
newCLpush[8] = tempFBSignUp; //patients_acc
newCLpush[9] = 0;
newCLpush[10] = 0;
newCLpush[11] = tempFBSignUp;
this.state.studyPatientsByMedia[studyPatientFB][11] = 0;
totalNewCLPush.push(newCLpush);
console.log(">> HERE ONLY FB IS PRESENT IN studyPatientsByMedia "+ tempFBSignUp);
sumOfAllTransferedSignUp += tempFBSignUp;
console.log(foundStudy[0]+" "+foundStudy[3]);
}
}
}
}
this.state.studyPatientsByMedia = this.state.studyPatientsByMedia.concat(totalNewCLPush);
console.log('sumOfAllTransferedSignUp!' + sumOfAllTransferedSignUp)
//this.finalizeMergedCSVFile(this.state.currentCpqCSV);
//this.finalizeMergedCSVFile(this.state.studyPatientsByMedia);
console.log('DONE!');
}
//INITIAL DATA FOR 01-23
step5InitialAccumulationPatientNewSignUpMediaName = () => {
console.log('>>>Start Step5 AccumulationPatientNewSignUpMediaName');
console.log('patientsPreScreenedCNCByMediaName');
console.log(this.state.patientsPreScreenedCNCByMediaName);
console.log('patientsSignUpByMediaName');
console.log(this.state.patientsSignUpByMediaName);
//studyPatientsByMedia
//no need for new patients to compare prev day
for(var i=0; i < (this.state.currentCpqCSV.length); i++) {
var fbArr = [];
var clArr = [];
var currDayStudy = this.state.currentCpqCSV[i];
var prevDayStudy = this.state.previousCpqCSV.find(function(el){
return (el[0] == currDayStudy[0] && el[3] == currDayStudy[3]);
});
fbArr[0] = currDayStudy[0];
fbArr[1] = currDayStudy[3];
fbArr[2] = currDayStudy[4];
fbArr[3] = this.state.dateUseAsNow;
fbArr[4] = 'fb';
clArr[0] = currDayStudy[0];
clArr[1] = currDayStudy[3];
clArr[2] = currDayStudy[4];
clArr[3] = this.state.dateUseAsNow;
clArr[4] = 'cl';
var patients = this.state.patientsPreScreenedCNCByMediaName.find(function(el){
return (el.campaignID == currDayStudy[0] && el.studyID == currDayStudy[3]);
});
var patientFB = (patients) ? patients.patientsByMedia.find(function(el){
return el[2] == 'fb';
}) : null;
var patientCL = (patients) ? patients.patientsByMedia.find(function(el){
return el[2] == 'cl';
}) : null;
var patientOthers = (patients) ? patients.patientsByMedia.find(function(el){
return el[2] != 'fb' && el[2] != 'cl';
}) : null;
if(patientOthers != null && patientOthers != undefined) {
console.log('WARNING! OTHER MEDIAS FOUND IN UTM');
console.log(patientOthers);
}
var firstIndex = this.state.currentCpqCSV.findIndex(function(el, index){
return (currDayStudy[3] == el[3]);
});
var filterStudy = this.state.currentCpqCSV.filter(function(el){
return (currDayStudy[3] == el[3]);
});
var patientSignUp = this.state.patientsSignUpByMediaName.find(function(el){
return el.studyID == currDayStudy[3];
});
var patientSignUpFB = (patientSignUp) ? patientSignUp.signUp.find(function(el){
return el[1] == 'fb';
}) : null;
var patientSignUpCL = (patientSignUp) ? patientSignUp.signUp.find(function(el){
return el[1] == 'cl';
}) : null;
var patientSignUpOthers = (patientSignUp) ? patientSignUp.signUp.find(function(el){
return el[1] != 'fb' && el[1] != 'cl';
}) : null;
if(patientSignUpOthers != null && patientSignUpOthers!= undefined) {
console.log('WARNING! OTHER MEDIAS FOUND IN PAC DAILY');
console.log(patientSignUpOthers);
}
if(patientFB) {
this.state.currentCpqCSV[i][54] = patientFB[3];
this.state.currentCpqCSV[i][55] = patientFB[4];
this.state.currentCpqCSV[i][56] = patientFB[5];
fbArr[5] = patientFB[3];
fbArr[6] = patientFB[4];
fbArr[7] = patientFB[5];
}
this.state.currentCpqCSV[i][60] = (patientSignUpFB && (filterStudy.length == 1 || (filterStudy.length > 1 && firstIndex != i))) ? patientSignUpFB[2] : 0; //newPatients_FB
fbArr[11] = this.state.currentCpqCSV[i][60];
if(patientCL != null && patientCL != undefined) {
this.state.currentCpqCSV[i][61] = patientCL[3];
this.state.currentCpqCSV[i][62] = patientCL[4];
this.state.currentCpqCSV[i][63] = patientCL[5];
//01-23 ONLY
this.state.currentCpqCSV[i][64] = patientCL[3];
this.state.currentCpqCSV[i][65] = patientCL[4];
this.state.currentCpqCSV[i][66] = patientCL[5];
clArr[5] = patientCL[3];
clArr[6] = patientCL[4];
clArr[7] = patientCL[5];
clArr[8] = patientCL[3];
clArr[9] = patientCL[4];
clArr[10] = patientCL[5];
} else {
this.state.currentCpqCSV[i][61] = 0;
this.state.currentCpqCSV[i][62] = 0;
this.state.currentCpqCSV[i][63] = 0;
//01-23 ONLY
this.state.currentCpqCSV[i][64] = 0;
this.state.currentCpqCSV[i][65] = 0;
this.state.currentCpqCSV[i][66] = 0;
clArr[5] = 0;
clArr[6] = 0;
clArr[7] = 0;
clArr[8] = 0;
clArr[9] = 0;
clArr[10] = 0;
}
this.state.currentCpqCSV[i][67] = (patientSignUpCL && (filterStudy.length == 1 || (filterStudy.length > 1 && firstIndex != i))) ? patientSignUpCL[2] : 0; //newPatients_CL
clArr[11] = this.state.currentCpqCSV[i][67];
//01-23 ONLY
this.state.currentCpqCSV[i][57] = (this.state.currentCpqCSV[i][21] - this.state.currentCpqCSV[i][64] < 0) ? 0 : (this.state.currentCpqCSV[i][21] - this.state.currentCpqCSV[i][64]);
this.state.currentCpqCSV[i][58] = (this.state.currentCpqCSV[i][22] - this.state.currentCpqCSV[i][65] < 0) ? 0 : (this.state.currentCpqCSV[i][22] - this.state.currentCpqCSV[i][65]);
this.state.currentCpqCSV[i][59] = (this.state.currentCpqCSV[i][23] - this.state.currentCpqCSV[i][66] < 0) ? 0 : (this.state.currentCpqCSV[i][23] - this.state.currentCpqCSV[i][66]);
fbArr[8] = this.state.currentCpqCSV[i][57];
fbArr[9] = this.state.currentCpqCSV[i][58];
fbArr[10] = this.state.currentCpqCSV[i][59];
this.state.studyPatientsByMedia.push(fbArr);
this.state.studyPatientsByMedia.push(clArr);
}
console.log(this.state.currentCpqCSV);
this.state.currentCpqCSV.unshift(this.state.headerToUse);
this.finalizeMergedCSVFile(this.state.currentCpqCSV);
this.finalizeMergedCSVFile(this.state.studyPatientsByMedia);
}
getLevel = (levelID) => {
var levels = [
"Bronze", //1
"Silver", //2
"Gold", //3
"Platinum", //4
"Diamond", //5
"Ruby", //6
"Platinum Plus", //7
"Diamond Plus", //8
"Ruby Plus" //9
];
return levels[levelID-1];
}
getDateToUTCSK = (date) => {
var dayName = [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
];
var monthName = [
"Jan", "Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
var _date = new Date(date);
var day = _date.getUTCDate();
var dayVal = dayName[_date.getUTCDay()];
var monVal = monthName[_date.getUTCMonth()];
var year = _date.getUTCFullYear();
return dayVal + " " + monVal + " " + day + " " + year + " 00:00:00 GMT+0000 (UTC)";
}
//FORMAT DATE TO YYYY-MM-DD
getDateFormatted = (date) => {
var _date = new Date(date);
var dayVal = (_date.getUTCDate() < 10) ? '0'+_date.getUTCDate() : _date.getUTCDate();
var monVal = ((_date.getUTCMonth()+1) < 10) ? '0'+(_date.getUTCMonth()+1) : (_date.getUTCMonth()+1);
var year = _date.getUTCFullYear();
return year+'-'+monVal+'-'+dayVal;
}
saveToCSV = () => {
this.finalizeMergedCSVFile(this.state.currentCpqCSV);
}
finalizeMergedCSVFile = (saveFile) => {
//console.log(saveFile);
var rawFile = csv.fromArrays(saveFile);
// var csvContent = "data:text/csv;charset=utf-8,"
// + csv.fromArrays(saveFile);
//var encodedUri = encodeURI(csvContent);
// var link = document.createElement("a");
// link.setAttribute("href", encodedUri);
// link.setAttribute("download", "my_data.csv");
// document.body.appendChild(link);
// link.click();
var link = document.createElement("a");
link.href = URL.createObjectURL(new Blob([rawFile], {
type: 'text/csv'
}));
link.setAttribute('download', "my_data.csv");
document.body.appendChild(link);
link.click();
}
render() {
return (
<div className="process-csv" style={{'textAlign':'left'}}>
<hr/>
<h2>
Updated Overall Merging Process
</h2>
<p>Change the value of studykik auth and daily date before merging the files!</p>
<p>Date: {this.state.dateUseAsNow}</p>
<br/>
<div style={{'float':'left'}}>
<div>Select Previous Final campaign_patient_quality CSV</div>
<input type="file" accept=".csv" onChange={this.getFile('previousCpqCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<br/>
<div style={{'float':'left'}}>
<div>Select Current Raw campaign_patient_quality CSV</div>
<input type="file" accept=".csv" onChange={this.getFile('currentCpqCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<br/>
<div style={{'float':'left'}}>
<div>Select Pac Daily with UTM CSV</div>
<input type="file" accept=".csv" onChange={this.getFile('pacDailyUTMCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<br/>
<div style={{'float':'left'}}>
<div>Select Craigslist AdSpent CSV</div>
<input type="file" accept=".csv" onChange={this.getFile('craigslistAdSpentCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<br/>
<div style={{'float':'left'}}>
<div>Select Previous Day Study Patient Media CSV</div>
<input type="file" accept=".csv" onChange={this.getFile('studyPatientMediaCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<br/>
<div style={{'float':'left'}}>
<div>Select Kenshoo Spent CSV</div>
<input type="file" accept=".csv" onChange={this.getFile('kenshooSpentCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<br/>
{(this.state.isReadyToProces) && <button onClick={this.startMergingProcess}>Start Merging!</button>}
<br/>
<br/>
<button onClick={this.saveToCSV}>Click To Save Data!</button>
<hr/>
<br/>
<br/>
<br/>
<br/>
<div style={{'float':'left'}}>
<div>Select FINAL Campaign Patient Quality CSV</div>
<input type="file" accept=".csv" onChange={this.getFile('finalCPQCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<div style={{'float':'left'}}>
<div>Select Campaign Cost Summary CSV</div>
<input type="file" accept=".csv" onChange={this.getFile('campaignCostSummaryCSV')} style={{'float':'left'}}/>
</div>
<br/><br/>
<button onClick={this.startCampaignCostMergingProcess}>Start Merging of Campaign Cost Summary</button>
<br/>
<br/>
</div>
);
}
}
export default UpdatedCPQ_PAC_CLSpent_Merging;<file_sep>/* MODAL STYLE */
/* The Modal (background) */
.customized-modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 10000; /* Sit on top */
padding-top: 5%; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.customized-modal .modal-content {
position: relative;
background-color: #fefefe;
margin: 0;
padding: 0;
border: 1px solid #888;
border-radius: 10px !important;
width: 100%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s
}
/* Add Animation */
@-webkit-keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
@keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
.customized-modal .modal-title {
padding-left: 20px;
}
/* The Close Button */
.customized-modal .close {
color: white;
float: right;
font-size: 28px;
font-weight: bold;
background: none;
border: none;
margin-top: 10px;
padding-right: 20px;
}
.customized-modal .close:hover,
.customized-modal .close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
.customized-modal .modal-dialog {
max-height: 80%;
width: 500px;
/*overflow: auto;*/
}
.customized-modal .modal-header {
/*padding: 2px 16px;*/
/*position: fixed;
width: inherit;*/
border-radius: 10px 10px 0 0;
border-bottom: 0;
/*border-left: 1px solid #888;*/
padding-bottom: 0;
margin-top: -1px;
background-color: #f5f5f5 !important;
color: white;
}
.customized-modal .modal-header button {
top: 0px !important;
color: #333 !important;
}
.customized-modal .modal-body {
padding: 20px 16px;
/*height: 80%*/
}
.customized-modal .modal-footer {
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}
<!-- Modal -->
<div class="modal customized-modal" id="myModal" role="dialog" data-renewalclicked="false">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" style="padding-right: 0px; margin: 10px 0 0 0;">×</button>
<div class="image-content" style="text-align: center;">
<img src="https://res.cloudinary.com/teembr/image/upload/v1572886257/studykik/nodiscount-renewal.png" style="width: 440px; margin-top: -70px;">
</div>
</div>
<div class="modal-body">
<h3 style="text-align: center;">
<strong>
<span style="color:#666666;">Hello, your campaign will<br>
be <em>Ending Soon!</em></span>
</strong>
</h3>
<div>
<h5 style="text-align: center;">
<span style="color:#888888;">Click below to Renew <em>instantly</em> and<br>
keep your study enrolling.</span>
</h5>
</div>
<div style="text-align: center; margin: 40px 0 20px 0;">
<div class="renewal-campaign-btn" style="background-color:rgba(245, 142, 49, 1)!important;color:rgba(255, 255, 255, 1)!important;padding: 10px 15px;border-radius: 3px; font-weight: bold; width: 220px; margin: auto; cursor: pointer;">RENEW CAMPAIGN</div>
</div>
</div>
</div>
</div>
</div>
#main .home-page .container-fluid NAV
>>>>
history.pushState = ( f => function pushState(){
var ret = f.apply(this, arguments);
window.dispatchEvent(new Event('pushstate'));
window.dispatchEvent(new Event('locationchange'));
return ret;
})(history.pushState);
history.replaceState = ( f => function replaceState(){
var ret = f.apply(this, arguments);
window.dispatchEvent(new Event('replacestate'));
window.dispatchEvent(new Event('locationchange'));
return ret;
})(history.replaceState);
window.addEventListener('popstate',()=>{
window.dispatchEvent(new Event('locationchange'))
});
var globalCount = 0;
///////// LISTEN TO SPA HISTORY CHANGE /////////
window.addEventListener('locationchange', function(){
console.log('window locationchange func '+globalCount);
window.cleanAllTimeout();
if(window.location.pathname == '/client/home') {
setTimeout(function(){
var studyItems = document.querySelectorAll(".table-holder table tbody > tr.study-item");
var singleActive = 0;
var within3Days = new Date();
within3Days.setDate(within3Days.getDate()+3);
for(var i=0; i<studyItems.length; i++){
var checkStatus = studyItems[i].getElementsByClassName('status');
var checkEndDate = studyItems[i].getElementsByClassName('end-date');
var isValidEndDate = false;
var isCentral = true;
if(checkEndDate.length == 1){
var endDate = new Date(checkEndDate[0].textContent);
if(endDate <= within3Days) {
isValidEndDate = true;
}
}
if(studyItems[i].querySelector('.central-flag') && studyItems[i].querySelector('.central-flag').getAttribute('data-central') == 'false'){
isCentral = false;
}
if(checkStatus.length == 1 && checkStatus[0].textContent == 'Active' && isValidEndDate && !isCentral) {
singleActive++;
break;
}
}
if(window.location.pathname == '/client/home' && singleActive && document.querySelector('div:not(.customized-modal) > .modal-dialog') == null) {
console.log('locationchange open modal');
var body = document.getElementsByTagName('body')[0];
var modal = document.getElementById("myModal");
modal.style.display = "block";
body.style.overflow = 'hidden';
}
}, 6500); //6.5 SECONDS DELAY
}
globalCount++;
});
///////// INITIAL CONDITIN WHEN THE PAGE LOADED /////////
if(globalCount == 0) {
console.log('plain if func '+globalCount);
window.cleanAllTimeout();
setTimeout(function(){
var studyItems = document.querySelectorAll(".table-holder table tbody > tr.study-item");
if(studyItems.length > 0 && studyItems[0].querySelector('.central-flag') == null) {
for(var i=0; i<studyItems.length; i++){
var studyID = studyItems[i].querySelector('.indication>div.tooltip-element').getAttribute('data-tip');
checkStudyID(studyID, studyItems[i]);
}
console.log('init checking but not present.. calling checkStudy()');
} else {
console.log('init checking but already present');
}
}, 2000); //CHECK FECTH OF CENTRAL FLAG AFTER 2 SECONDS
setTimeout(function(){
var studyItems = document.querySelectorAll(".table-holder table tbody > tr.study-item");
var singleActive = 0;
var within3Days = new Date();
within3Days.setDate(within3Days.getDate()+3);
for(var i=0; i<studyItems.length; i++){
var checkStatus = studyItems[i].getElementsByClassName('status');
var checkEndDate = studyItems[i].getElementsByClassName('end-date');
var isValidEndDate = false;
var isCentral = true;
if(checkEndDate.length == 1){
var endDate = new Date(checkEndDate[0].textContent);
if(endDate <= within3Days) {
isValidEndDate = true;
}
}
if(studyItems[i].querySelector('.central-flag') && studyItems[i].querySelector('.central-flag').getAttribute('data-central') == 'false'){
isCentral = false;
}
if(checkStatus.length == 1 && checkStatus[0].textContent == 'Active' && isValidEndDate && !isCentral) {
singleActive++;
break;
}
}
if(window.location.pathname == '/client/home' && singleActive && document.querySelector('div:not(.customized-modal) > .modal-dialog') == null) {
console.log('init if open modal');
var body = document.getElementsByTagName('body')[0];
var modal = document.getElementById("myModal");
modal.style.display = "block";
body.style.overflow = 'hidden';
}
}, 6500); //6.5 SECONDS DELAY
globalCount++;
}
/////////
document.addEventListener('click', function(e){
///////// RENEWAL FORM CLOSE X BUTTON CLICKED /////////
if(e.target == document.querySelector('.modal-header button.close')) {
var body = document.getElementsByTagName('body')[0];
var modal = document.getElementById("myModal");
modal.style.display = "none";
body.style.overflow = '';
document.querySelector('.customized-modal').setAttribute('data-renewalclicked', 'false');
e.preventDefault();
ABTastyClickTracking('Popup Close X Button Click CT', null, 504225);
}
///////// RENEWAL FORM MODAL OVERLAY CLICKED /////////
else if(e.target == document.getElementById("myModal")){
var body = document.getElementsByTagName('body')[0];
var modal = document.getElementById("myModal");
modal.style.display = "none";
body.style.overflow = '';
document.querySelector('.customized-modal').setAttribute('data-renewalclicked', 'false');
}
///////// RENEWAL FORM RENEWAL CAMPAIGN BTN CLICKED /////////
else if(document.querySelector('div.renewal-campaign-btn') == e.target) {
var body = document.getElementsByTagName('body')[0];
var modal = document.getElementById("myModal");
modal.style.display = "none";
body.style.overflow = '';
document.querySelector('.customized-modal').setAttribute('data-renewalclicked', 'true');
e.preventDefault();
ABTastyClickTracking('Popup Renew Campaign Click CT', null, 504225);
var studyItems = document.querySelectorAll(".table-holder table tbody > tr.study-item");
var singleActive = 0;
var activeRow = [];
var within3Days = new Date();
within3Days.setDate(within3Days.getDate()+3);
for(var i=0; i<studyItems.length; i++){
var checkStatus = studyItems[i].getElementsByClassName('status');
var checkEndDate = studyItems[i].getElementsByClassName('end-date');
var isValidEndDate = false;
if(checkEndDate.length == 1){
var endDate = new Date(checkEndDate[0].textContent);
if(endDate <= within3Days) {
isValidEndDate = true;
}
}
if(checkStatus.length == 1 && checkStatus[0].textContent == 'Active' && isValidEndDate) {
activeRow.push(studyItems[i]);
singleActive++;
break;
}
}
if(singleActive && activeRow.length) {
activeRow[0].querySelector("span[data-tip='Renew']").click();
}
}
///////// RENEWAL FORM SUBMIT FOR RENEW CLICKED /////////
else if(document.querySelector('#renew-study .form-study .card-selection + button') == e.target ||
document.querySelector('#renew-study .form-study .card-selection + button span') == e.target) {
e.preventDefault();
if(document.querySelector('.customized-modal').getAttribute('data-renewalclicked') == 'true')
ABTastyClickTracking('Renew Campaign Form Submit Click CT', null, 504225);
}
});
///////// LISTEN TO MUTAION ON THE DOM IF STUDY LIST WAS ALREADY POPULATED /////////
const config = { attributes: false, childList: true, subtree: true };
const callback = function(mutationsList, observer) {
for(let mutation of mutationsList) {
console.log(mutation);
if (mutation.type === 'childList' && mutation.addedNodes[0] && mutation.addedNodes[0].className == 'study-container study-item') {
var studyID = mutation.addedNodes[0].querySelector('.indication>div.tooltip-element').getAttribute('data-tip');
checkStudyID(studyID, mutation.addedNodes[0]);
}
}
};
const observer = new MutationObserver(callback);
observer.observe(document.body, config);
////////// FETCH CENTRAL FLAG TO STUDYKIK API /////////
async function checkStudyID(studyID, studyNode) {
console.log('checkStudyID func '+globalCount);
var apiHost = location.host == 'studykik.com' ? 'api' : 'api-staging';
var url = 'https://'+apiHost+'.studykik.com/api/v1/studies/'+studyID+'?filter={%22include%22:[{%22relation%22:%22campaigns%22,%22scope%22:{%22order%22:%22isCurrent%20DESC%22}}]}';
var response = await fetch(url, {
headers: {
Authorization: window.localStorage.getItem('auth_token')
}
});
var commits = await response.json();
if(commits && commits.campaigns.length) {
var centralFlag = commits.campaigns[0].central;
var centralTd = document.createElement("td");
centralTd.classList = 'central-flag'
centralTd.style = 'display:none';
centralTd.setAttribute('data-central', centralFlag);
if(studyNode.querySelector('.central-flag') == null)
studyNode.insertAdjacentElement('afterbegin', centralTd);
}
}
>>> remove console logs before
history.pushState = ( f => function pushState(){
var ret = f.apply(this, arguments);
window.dispatchEvent(new Event('pushstate'));
window.dispatchEvent(new Event('locationchange'));
return ret;
})(history.pushState);
history.replaceState = ( f => function replaceState(){
var ret = f.apply(this, arguments);
window.dispatchEvent(new Event('replacestate'));
window.dispatchEvent(new Event('locationchange'));
return ret;
})(history.replaceState);
window.addEventListener('popstate',()=>{
window.dispatchEvent(new Event('locationchange'))
});
var globalCount = 0;
var _TimeoutCollector = [];
///////// LISTEN TO SPA HISTORY CHANGE /////////
window.addEventListener('locationchange', function(){
console.log('window locationchange func '+globalCount);
//window.cleanAllTimeout();
_cleanAllTimeout();
if(window.location.pathname == '/client/home') {
var locChangeTimeoutID = setTimeout(function(){
var studyItems = document.querySelectorAll(".table-holder table tbody > tr.study-item");
var singleActive = 0;
var within3Days = new Date();
within3Days.setDate(within3Days.getDate()+3);
for(var i=0; i<studyItems.length; i++){
var checkStatus = studyItems[i].getElementsByClassName('status');
var checkEndDate = studyItems[i].getElementsByClassName('end-date');
var isValidEndDate = false;
var isCentral = true;
if(checkEndDate.length == 1){
var endDate = new Date(checkEndDate[0].textContent);
if(endDate <= within3Days) {
isValidEndDate = true;
}
}
if(studyItems[i].querySelector('.central-flag') && studyItems[i].querySelector('.central-flag').getAttribute('data-central') == 'false'){
isCentral = false;
}
if(checkStatus.length == 1 && checkStatus[0].textContent == 'Active' && isValidEndDate && !isCentral) {
singleActive++;
break;
}
}
if(window.location.pathname == '/client/home' && singleActive && document.querySelector('div:not(.customized-modal) > .modal-dialog') == null) {
console.log('locationchange open modal');
document.querySelector('.customized-modal').setAttribute('data-renewalclicked', 'false');
var body = document.getElementsByTagName('body')[0];
var modal = document.getElementById("myModal");
modal.style.display = "block";
body.style.overflow = 'hidden';
}
}, 6500); //6.5 SECONDS DELAY
_TimeoutCollector.push(locChangeTimeoutID);
}
globalCount++;
});
///////// INITIAL CONDITIN WHEN THE PAGE LOADED /////////
if(globalCount == 0) {
console.log('plain if func '+globalCount);
//window.cleanAllTimeout();
_cleanAllTimeout();
var initFetchTimeout = setTimeout(function(){
var studyItems = document.querySelectorAll(".table-holder table tbody > tr.study-item");
if(studyItems.length > 0 && studyItems[0].querySelector('.central-flag') == null) {
for(var i=0; i<studyItems.length; i++){
var studyID = studyItems[i].querySelector('.indication>div.tooltip-element').getAttribute('data-tip');
checkStudyID(studyID, studyItems[i]);
}
console.log('init checking but not present.. calling checkStudy()');
} else {
console.log('init checking but already present');
}
}, 2000); //CHECK FECTH OF CENTRAL FLAG AFTER 2 SECONDS
_TimeoutCollector.push(initFetchTimeout);
var modalTimeout = setTimeout(function(){
var studyItems = document.querySelectorAll(".table-holder table tbody > tr.study-item");
var singleActive = 0;
var within3Days = new Date();
within3Days.setDate(within3Days.getDate()+3);
for(var i=0; i<studyItems.length; i++){
var checkStatus = studyItems[i].getElementsByClassName('status');
var checkEndDate = studyItems[i].getElementsByClassName('end-date');
var isValidEndDate = false;
var isCentral = true;
if(checkEndDate.length == 1){
var endDate = new Date(checkEndDate[0].textContent);
if(endDate <= within3Days) {
isValidEndDate = true;
}
}
if(studyItems[i].querySelector('.central-flag') && studyItems[i].querySelector('.central-flag').getAttribute('data-central') == 'false'){
isCentral = false;
}
if(checkStatus.length == 1 && checkStatus[0].textContent == 'Active' && isValidEndDate && !isCentral) {
singleActive++;
break;
}
}
if(window.location.pathname == '/client/home' && singleActive && document.querySelector('div:not(.customized-modal) > .modal-dialog') == null) {
console.log('init if open modal');
var body = document.getElementsByTagName('body')[0];
var modal = document.getElementById("myModal");
modal.style.display = "block";
body.style.overflow = 'hidden';
}
}, 6500); //6.5 SECONDS DELAY
_TimeoutCollector.push(modalTimeout);
globalCount++;
}
/////////
document.addEventListener('click', function(e){
///////// RENEWAL FORM CLOSE X BUTTON CLICKED /////////
if(e.target == document.querySelector('.modal-header button.close')) {
var body = document.getElementsByTagName('body')[0];
var modal = document.getElementById("myModal");
modal.style.display = "none";
body.style.overflow = '';
document.querySelector('.customized-modal').setAttribute('data-renewalclicked', 'false');
e.preventDefault();
ABTastyClickTracking('Popup Close X Button Click CT', null, 504225);
}
///////// RENEWAL FORM MODAL OVERLAY CLICKED /////////
else if(e.target == document.getElementById("myModal")){
var body = document.getElementsByTagName('body')[0];
var modal = document.getElementById("myModal");
modal.style.display = "none";
body.style.overflow = '';
document.querySelector('.customized-modal').setAttribute('data-renewalclicked', 'false');
}
///////// RENEWAL FORM RENEWAL CAMPAIGN BTN CLICKED /////////
else if(document.querySelector('div.renewal-campaign-btn') == e.target) {
var body = document.getElementsByTagName('body')[0];
var modal = document.getElementById("myModal");
modal.style.display = "none";
body.style.overflow = '';
document.querySelector('.customized-modal').setAttribute('data-renewalclicked', 'true');
e.preventDefault();
ABTastyClickTracking('Popup Renew Campaign Click CT', null, 504225);
var studyItems = document.querySelectorAll(".table-holder table tbody > tr.study-item");
var singleActive = 0;
var activeRow = [];
var within3Days = new Date();
within3Days.setDate(within3Days.getDate()+3);
for(var i=0; i<studyItems.length; i++){
var checkStatus = studyItems[i].getElementsByClassName('status');
var checkEndDate = studyItems[i].getElementsByClassName('end-date');
var isValidEndDate = false;
if(checkEndDate.length == 1){
var endDate = new Date(checkEndDate[0].textContent);
if(endDate <= within3Days) {
isValidEndDate = true;
}
}
if(checkStatus.length == 1 && checkStatus[0].textContent == 'Active' && isValidEndDate) {
activeRow.push(studyItems[i]);
singleActive++;
break;
}
}
if(singleActive && activeRow.length) {
activeRow[0].querySelector("span[data-tip='Renew']").click();
}
}
///////// RENEWAL FORM SUBMIT FOR RENEW CLICKED /////////
else if(document.querySelector('#renew-study .form-study .card-selection + button') == e.target ||
document.querySelector('#renew-study .form-study .card-selection + button span') == e.target) {
e.preventDefault();
if(document.querySelector('.customized-modal').getAttribute('data-renewalclicked') == 'true')
ABTastyClickTracking('Renew Campaign Form Submit Click CT', null, 504225);
document.querySelector('.customized-modal').setAttribute('data-renewalclicked', 'false');
}
});
///////// LISTEN TO MUTAION ON THE DOM IF STUDY LIST WAS ALREADY POPULATED /////////
const config = { attributes: false, childList: true, subtree: true };
const callback = function(mutationsList, observer) {
for(let mutation of mutationsList) {
console.log(mutation);
if (mutation.type === 'childList' && mutation.addedNodes[0] && mutation.addedNodes[0].className == 'study-container study-item') {
var studyID = mutation.addedNodes[0].querySelector('.indication>div.tooltip-element').getAttribute('data-tip');
checkStudyID(studyID, mutation.addedNodes[0]);
}
}
};
const observer = new MutationObserver(callback);
observer.observe(document.body, config);
////////// FETCH CENTRAL FLAG TO STUDYKIK API /////////
async function checkStudyID(studyID, studyNode) {
console.log('checkStudyID func '+globalCount);
var apiHost = location.host == 'studykik.com' ? 'api' : 'api-staging';
var url = 'https://'+apiHost+'.studykik.com/api/v1/studies/'+studyID+'?filter={%22include%22:[{%22relation%22:%22campaigns%22,%22scope%22:{%22order%22:%22isCurrent%20DESC%22}}]}';
var response = await fetch(url, {
headers: {
Authorization: window.localStorage.getItem('auth_token')
}
});
var commits = await response.json();
if(commits && commits.campaigns.length) {
var centralFlag = commits.campaigns[0].central;
var centralTd = document.createElement("td");
centralTd.classList = 'central-flag'
centralTd.style = 'display:none';
centralTd.setAttribute('data-central', centralFlag);
if(studyNode.querySelector('.central-flag') == null)
studyNode.insertAdjacentElement('afterbegin', centralTd);
}
}
////////// CLEAR ALL TIMEOUTS /////////
function _cleanAllTimeout() {
//for(var t=0;t<TimeoutCollector.length;t++)clearTimeout(TimeoutCollector[t].trigger);window.TimeoutCollector=[];
for(var t=0;t<_TimeoutCollector.length;t++)clearTimeout(_TimeoutCollector[t]);
_TimeoutCollector=[];
};<file_sep>import React, { Component } from 'react';
import csv from 'jquery-csv'
class MergeAndUpdateCsv extends Component {
constructor(props) {
super(props);
this.state = {
todayDate: null,
dateUseAsNow: "2020-01-03",
dateUseAsTomorrow: "2020-01-04",
cpqCSV: null,
pacDailyCSV: null,
isReadyToProces: false,
smartlyAPIToken: '861fe5f87ac243bd50f11e79c09dbed46d542219',
studykikAuth: '<KEY>',
notFoundLength: 0,
tempNotFoundLength: 0,
tempFoundLength: 0,
tempToProcessFoundLength: 0,
tempToProcessFoundLength2: 0,
isSendingRequests: false,
intervalId: 0
}
}
componentDidMount() {
var yesterday = new Date((new Date()).valueOf() - 1000*60*60*24);
this.state.todayDate = this.formatDate(yesterday);
}
formatDate(d) {
var day = d.getUTCDate() > 9 ? d.getUTCDate() : '0'+d.getUTCDate();
var month = d.getUTCMonth()+1 > 9 ? (d.getUTCMonth()+1) : '0'+(d.getUTCMonth()+1);
return d.getUTCFullYear() + '-' + month + '-' + day;
}
getFile = name => e => {
var _this = this;
var file = e.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var _csv = event.target.result;
var data = csv.toArrays(_csv);
if(name === 'cpqCSV'){
data[0].push('newSignUp');
data[0].push('sourceName');
data[0].push('isMediaTracking');
data[0].push('tierNumber');
data[0].push('sponsor');
data[0].push('sponsorId');
data[0].push('croId');
data[0].push('cro');
data[0].push('disposition');
data[0].push('dispositionTotal');
//_this.finalizeMergedCSVFile(data);
}
_this.state[name] = data;
if(_this.state.cpqCSV != null && _this.state.pacDailyCSV != null)
_this.setState({isReadyToProces: true});
}
}
getForDispoFile = name => e => {
var _this = this;
var file = e.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var _csv = event.target.result;
var data = csv.toArrays(_csv);
_this.state[name] = data;
if(_this.state.cpqCSV != null)
_this.setState({isReadyToProces: true});
}
}
startMergingProcess = () => {
var _this = this;
var header = this.state.cpqCSV[0];
var cpqCSV = this.state.cpqCSV;
cpqCSV.shift();
var pacDailyCSV = this.state.pacDailyCSV;
pacDailyCSV.shift();
var ctr = 0;
var matchedStudyIDs = [];
cpqCSV.forEach(cpqEl => {
var tempStudyID = cpqEl[3];
var tempIndication = cpqEl[8];
var matchFound = pacDailyCSV.find(function(pacEl){
return (pacEl[0] == tempStudyID && pacEl[2] == tempIndication);
});
ctr += (matchFound == undefined) ? 0 : 1;
matchFound = (matchFound == undefined) ? ['', 0, '', '', '', '', '', ''] : matchFound;
if(matchFound[1] > 0) {
matchedStudyIDs.push(matchFound[0]); //studyId
}
cpqEl.push(matchFound[1]); //newSignUp
cpqEl.push(matchFound[3]); //sourceName
cpqEl.push(matchFound[4]); //isMediaTracking
cpqEl.push(matchFound[5]); //tierNumber
cpqEl.push(matchFound[6]); //sponsor
});
cpqCSV.unshift(header);
console.log('total matchFound: '+ctr);
this.processNotFound(matchedStudyIDs);
}
processNotFound = (matchedStudyIDs) => {
var notFound = [];
for(var i=0; i<this.state.pacDailyCSV.length; i++) {
var pacEl = this.state.pacDailyCSV[i];
var tempStudyID = pacEl[0];
var matchFound = matchedStudyIDs.find(function(el){
return (el == tempStudyID);
});
if(matchFound == undefined) {
notFound.push(pacEl);
}
}
this.state.notFoundLength = notFound.length;
console.log(notFound);
console.log('total notFound: ' +this.state.notFoundLength);
var reqCtr = 0;
for(var i=0; i<this.state.notFoundLength; i++) {
var newCSVValue = [];
var _tempNotFound = notFound[i];
this.sendRequestStudiesNotFound(_tempNotFound);
}
}
sendRequestStudiesNotFound = (tempNotFound, callback) => {
var studyID = tempNotFound[0];
var url = "https://api.studykik.com/api/v1/studies/"+studyID+"?filter={%22include%22:[{%22relation%22:%22campaigns%22,%22scope%22:{%22order%22:%22orderNumber%20DESC%22}},{%22relation%22:%22protocol%22},{%22relation%22:%22site%22},{%22relation%22:%22sources%22},{%22relation%22:%22sponsor%22},{%22relation%22:%22indication%22},{%22relation%22:%22cro%22}]}";
fetch(url, {
headers: {
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Authorization": this.state.studykikAuth
},
credentials: "include"
})
.then(response => response.json())
.then(json => {
json["tempNotFound"] = tempNotFound;
var newCSVValue = [];
var campaign = json.campaigns && json.campaigns.length ? json.campaigns[0] : "";
newCSVValue[0] = campaign.id;
newCSVValue[1] = this.getDateToUTCSK(campaign.startDate);
newCSVValue[2] = this.getDateToUTCSK(campaign.endDate);
newCSVValue[3] = json.id;
newCSVValue[4] = json.site_id;
newCSVValue[5] = campaign.central ? "TRUE" : "FALSE";
newCSVValue[6] = campaign.patientQualificationSuite ? "TRUE" : "FALSE";
newCSVValue[7] = this.getLevel(campaign.level_id);
newCSVValue[8] = json.indication.name;
newCSVValue[9] = json.protocol.number;
newCSVValue[10] = json.site.name;
newCSVValue[11] = json.site.city;
newCSVValue[12] = json.site.state;
newCSVValue[13] = json.site.zip;
newCSVValue[14] = tempNotFound[1]; //patients
newCSVValue[15] = 0;
newCSVValue[16] = 0;
newCSVValue[17] = this.state.dateUseAsNow;
newCSVValue[18] = campaign.startDate
newCSVValue[19] = campaign.endDate
newCSVValue[20] = 0; //adspent defaulted to 0
newCSVValue[21] = tempNotFound[1]; //patients_acc
newCSVValue[22] = 0;
newCSVValue[23] = 0;
newCSVValue[24] = tempNotFound[1]; //New Patient
newCSVValue[25] = 0;
newCSVValue[26] = 0;
newCSVValue[27] = 0;
newCSVValue[28] = 0;
newCSVValue[29] = 0;
newCSVValue[30] = 0;
newCSVValue[31] = 0;
newCSVValue[32] = tempNotFound[1]; //New Patient_Acc
newCSVValue[33] = 0;
newCSVValue[34] = 0;
newCSVValue[35] = 0;
newCSVValue[36] = 0;
newCSVValue[37] = 0;
newCSVValue[38] = 0;
newCSVValue[39] = 0;
newCSVValue[40] = tempNotFound[1];
newCSVValue[41] = tempNotFound[3];
newCSVValue[42] = tempNotFound[4];
newCSVValue[43] = tempNotFound[5];
newCSVValue[44] = tempNotFound[6];
newCSVValue[45] = json.sponsor.id;
newCSVValue[46] = json.cro ? json.cro.id : "";
newCSVValue[47] = json.cro ? json.cro.name : "";
this.state.cpqCSV.push(newCSVValue);
this.state.tempNotFoundLength = this.state.tempNotFoundLength+1;
if(this.state.tempNotFoundLength == this.state.notFoundLength) {
console.log("DONE sendRequestStudiesNotFound FOR ALL -------");
console.log(this.state.cpqCSV);
this.processFoundStudies();
}
})
.catch((error) => {
console.log(error);
});
}
processFoundStudies = () => {
console.log('called processFoundStudies');
this.state.isSendingRequests = true;
var _this = this;
var i=1;
this.state.intervalId = setInterval(function() {
var study = _this.state.cpqCSV[i];
if(study.length < 48 || study[42] === "" || study[44] === "" || study[45] === "") { //isMediaTracking, sponsor, sponsorId
_this.state.tempToProcessFoundLength = _this.state.tempToProcessFoundLength+1;
_this.sendRequestStudiesFound(i);
}
i++;
console.log('interval '+i);
if(i == _this.state.cpqCSV.length) {
console.log('cleared interval');
_this.state.isSendingRequests = false;
clearInterval(_this.state.intervalId);
}
}, 500);
console.log("done calling processFoundStudies "+this.state.tempToProcessFoundLength);
}
sendRequestStudiesFound = (cpqStudyIndex) => {
var study = this.state.cpqCSV[cpqStudyIndex];
var studyID = study[3];
var url = "https://api.studykik.com/api/v1/studies/"+studyID+"?filter={%22include%22:[{%22relation%22:%22campaigns%22,%22scope%22:{%22order%22:%22orderNumber%20DESC%22}},{%22relation%22:%22protocol%22},{%22relation%22:%22site%22},{%22relation%22:%22sources%22},{%22relation%22:%22sponsor%22},{%22relation%22:%22indication%22},{%22relation%22:%22cro%22}]}";
fetch(url, {
headers: {
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Authorization": this.state.studykikAuth
},
credentials: "include"
})
.then(response => response.json())
.then(json => {
if(study[42] == "") //isMediaTracking
this.state.cpqCSV[cpqStudyIndex][42] = (json.mediaTracking) ? "TRUE" : "FALSE";
this.state.cpqCSV[cpqStudyIndex][44] = json.sponsor ? json.sponsor.name : "";
this.state.cpqCSV[cpqStudyIndex][45] = json.sponsor ? json.sponsor.id : "";
this.state.cpqCSV[cpqStudyIndex][46] = json.cro ? json.cro.id : "";
this.state.cpqCSV[cpqStudyIndex][47] = json.cro ? json.cro.name : "";
this.state.tempFoundLength = this.state.tempFoundLength+1;
console.log(this.state.tempFoundLength);
if(this.state.tempFoundLength == this.state.tempToProcessFoundLength && !this.state.isSendingRequests) {
console.log("DONE sendRequestStudiesFound FOR ALL -------");
console.log(this.state.cpqCSV);
this.processAllStudies("sendRequestStudiesDispositions");
}
})
.catch((error) => {
console.log(error);
});
}
startFetchingDispo = () => {
console.log(this.state.cpqCSV);
console.log("will start to processAllStudies");
this.processAllStudies("sendRequestStudiesDispositions");
}
processAllStudies = (functionName) => {
console.log('called '+functionName);
this.state.tempToProcessFoundLength = 0;
this.state.tempFoundLength = 0;
this.state.isSendingRequests = true;
var _this = this;
var i=1;
this.state.intervalId = setInterval(function() {
_this.state.tempToProcessFoundLength = _this.state.tempToProcessFoundLength+1;
if(functionName == "sendRequestStudiesByProtocolTotalsTmp") {
_this.state.tempToProcessFoundLength = _this.state.tempToProcessFoundLength+1;
_this.sendRequestStudiesByProtocolTotalsTmp(i);
}
else if(functionName == "sendRequestStudiesDispositions"){
_this.state.tempToProcessFoundLength = _this.state.tempToProcessFoundLength+1;
_this.sendRequestStudiesDispositions(i);
}
i++;
console.log('interval '+i);
if(i == _this.state.cpqCSV.length) {
console.log('cleared interval');
_this.state.isSendingRequests = false;
clearInterval(_this.state.intervalId);
}
}, 1000);
/*for(var i = 1; i < this.state.cpqCSV.length; i++) {
this.state.tempToProcessFoundLength = this.state.tempToProcessFoundLength+1;
if(functionName == "sendRequestStudiesByProtocolTotalsTmp") {
this.sendRequestStudiesByProtocolTotalsTmp(i);
}
else if(functionName == "sendRequestStudiesDispositions"){
this.sendRequestStudiesDispositions(i);
}
}*/
console.log("done calling "+functionName);
}
sendRequestStudiesDispositions = (cpqStudyIndex) => {
var study = this.state.cpqCSV[cpqStudyIndex];
var studyID = study[3];
var url = "https://api.studykik.com/api/v1/studies/getStudiesByDispositionTotals?"+
"studyID=" + studyID + "&" +
"study=" + studyID + "&" +
"sponsorRoleId=" + study[45] + "&" +
"protocol=" + encodeURI(study[9]) + "&" +
"indication=" + encodeURI(study[8]) + "&" +
"cro=" + encodeURI(study[47]) + "&" +
"messaging=true&" +
"timezone=America%2FChicago&" +
"status=All&" +
"startDate=" + this.state.dateUseAsNow + "T06%3A00%3A00.000Z&" +
"endDate=" + this.state.dateUseAsTomorrow + "T06%3A00%3A00.000Z";
fetch(url, {
headers: {
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Authorization": this.state.studykikAuth
},
credentials: "include"
})
.then(response => response.json())
.then(json => {
if(json && json.length) {
for(var i=0; i<json.length; i++) {
if(json[i].source == "StudyKIK") {
this.state.cpqCSV[cpqStudyIndex][48] = json[i].stats[0];
var total = json[i].stats.reduce((a, b) => parseInt(a) + parseInt(b));
this.state.cpqCSV[cpqStudyIndex][49] = total;
break;
}
}
}
this.state.tempFoundLength = this.state.tempFoundLength+1;
console.log(this.state.tempFoundLength);
if(this.state.tempFoundLength == this.state.tempToProcessFoundLength && !this.state.isSendingRequests) {
console.log("DONE sendRequestStudiesDispositions FOR ALL -------");
console.log(this.state.cpqCSV);
}
})
.catch((error) => {
console.log(error);
});
}
sendRequestStudiesByProtocolTotalsTmp = (cpqStudyIndex) => {
var study = this.state.cpqCSV[cpqStudyIndex];
var studyID = study[3];
var url = "https://api.studykik.com/api/v1/studies/getStudiesByProtocolTotalsTmp?"+
"studyID=" + studyID + "&" +
"study=" + studyID + "&" +
"sponsorRoleId=" + study[45] + "&" +
"protocol=" + encodeURI(study[9]) + "&" +
"indication=" + encodeURI(study[8]) + "&" +
"cro=" + encodeURI(study[47]) + "&" +
"messaging=true&" +
"timezone=America%2FChicago&" +
"source=1&" +
"status=All&" +
"startDate=" + this.state.dateUseAsNow + "T06%3A00%3A00.000Z&" +
"endDate=" + this.state.dateUseAsTomorrow + "T06%3A00%3A00.000Z";
console.log(study);
console.log(url);
fetch(url, {
headers: {
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Authorization": this.state.studykikAuth
},
credentials: "include"
})
.then(response => response.json())
.then(json => {
if(json) {
this.state.cpqCSV[cpqStudyIndex][48] = this.state.cpqCSV[cpqStudyIndex][40];
this.state.cpqCSV[cpqStudyIndex][49] = json.call_attempted;
this.state.cpqCSV[cpqStudyIndex][50] = json.dnq;
this.state.cpqCSV[cpqStudyIndex][51] = json.action_needed;
this.state.cpqCSV[cpqStudyIndex][52] = json.scheduled;
this.state.cpqCSV[cpqStudyIndex][53] = json.consented;
this.state.cpqCSV[cpqStudyIndex][54] = json.screen_failed;
this.state.cpqCSV[cpqStudyIndex][55] = json.randomized;
}
this.state.tempFoundLength = this.state.tempFoundLength+1;
console.log(this.state.tempFoundLength);
if(this.state.tempFoundLength == this.state.tempToProcessFoundLength) {
console.log("DONE sendRequestStudiesByProtocolTotalsTmp FOR ALL -------");
console.log(this.state.cpqCSV);
}
})
.catch((error) => {
console.log(error);
});
}
getLevel = (levelID) => {
var levels = [
"Bronze",
"Silver",
"Gold",
"Platinum",
"Diamond",
"Ruby",
"Platinum Plus",
"Diamond Plus",
"Ruby Plus"
];
return levels[levelID-1];
}
getDateToUTCSK = (date) => {
var dayName = [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
];
var monthName = [
"Jan", "Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
var _date = new Date(date);
var day = _date.getUTCDate();
var dayVal = dayName[_date.getUTCDay()];
var monVal = monthName[_date.getUTCMonth()];
var year = _date.getUTCFullYear();
return dayVal + " " + monVal + " " + day + " " + year + " 00:00:00 GMT+0000 (UTC)";
}
saveToCSV = () => {
this.finalizeMergedCSVFile(this.state.cpqCSV);
}
finalizeMergedCSVFile = (cpqCSV) => {
console.log(cpqCSV);
var csvContent = "data:text/csv;charset=utf-8,"
+ csv.fromArrays(cpqCSV);
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link);
link.click();
}
render() {
return (
<div className="process-csv" style={{'textAlign':'left'}}>
<hr/>
<h2>
Merging of campaign_patient_quality and pac_daily_report<br/>
And add the disposition data
</h2>
<br/>
<div style={{'float':'left'}}>
<div>Select campaign_patient_quality CSV</div>
<input type="file" accept=".csv" onChange={this.getFile('cpqCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<br/>
<div style={{'float':'left'}}>
<div>Select pac_daily_report CSV</div>
<input type="file" accept=".csv" onChange={this.getFile('pacDailyCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<br/>
{(this.state.isReadyToProces) && <button onClick={this.startMergingProcess}>Start Merging!</button>}
<br/>
<br/>
<button onClick={this.saveToCSV}>Click When Done Fetching!</button>
<br/>
<br/>
<div style={{'float':'left'}}>
<div>Select campaign_patient_quality CSV For Fetching Disposition</div>
<input type="file" accept=".csv" onChange={this.getForDispoFile('cpqCSV')} style={{'float':'left'}}/>
</div>
{(this.state.isReadyToProces) && <button onClick={this.startFetchingDispo}>Start Merging!</button>}
</div>
);
}
}
export default MergeAndUpdateCsv;<file_sep>@media (max-width: 700px) {
.secure-badge>img {
width: 20em;
float: none;
}
.verasafe-cert>img {
width: 19em;
float: none;
}
.secure-badge, .verasafe-cert {
margin-bottom: 20px;
text-align: center;
vertical-align: middle;
display: table-cell;
}
}
.secure-badge>img {
width: 15em;
float: right;
}
---
@media (max-width: 767px) {
.secure-badge>img {
width : 20em;
float : none;
}
.verasafe-cert>img {
width : 19em;
float : none;
}
.secure-badge, .verasafe-cert {
margin-bottom : 20px;
text-align : center;
vertical-align : middle;
display : table-cell;
}
}
.secure-badge>img {
width : 15em;
float : right;
}
.verasafe-cert>img {
width : 14em;
}
var articleElement = document.createElement('article');
articleElement.className = "landing post";
articleElement.innerHTML = "<div class='row' style='margin-bottom: 30px'><div class='col-xs-12 col-sm-6 in-viewport slideInLeft secure-badge'><img src='https://res.cloudinary.com/teembr/image/upload/v1562688119/studykik/secure-website.png'></div><div class='col-xs-12 col-sm-6 pull-right in-viewport slideInRight verasafe-cert'><img src='https://ab-testing.s3.amazonaws.com/SecurSafe/VeraSafe+(1).png'></div></div>";
var parentElement = document.querySelector("#main > .container");
parentElement.insertBefore(articleElement, parentElement.childNodes[1]);
<file_sep>import React, { Component } from 'react';
import csv from 'jquery-csv'
class ProcessCsv extends Component {
constructor(props) {
super(props);
this.state = {
todayDate: null,
toProcessCSV: null,
previousCSV: null,
isReadyToProces: false,
smartlyAPIToken: '861fe5f87ac243bd50f11e79c09dbed46d542219'
}
}
componentDidMount() {
var yesterday = new Date((new Date()).valueOf() - 1000*60*60*24);
this.state.todayDate = this.formatDate(yesterday);
}
formatDate(d) {
var day = d.getUTCDate() > 9 ? d.getUTCDate() : '0'+d.getUTCDate();
var month = d.getUTCMonth()+1 > 9 ? (d.getUTCMonth()+1) : '0'+(d.getUTCMonth()+1);
return d.getUTCFullYear() + '-' + month + '-' + day;
}
getFile = name => e => {
var _this = this;
var file = e.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var _csv = event.target.result;
var data = csv.toArrays(_csv);
if(name === 'toProcessCSV'){
data.shift();
}
_this.state[name] = data;
if(_this.state.toProcessCSV != null && _this.state.previousCSV != null)
_this.setState({isReadyToProces: true});
}
}
startCampaignPatientQualityProcess = () => {
var _this = this;
this.state.toProcessCSV.forEach(element => {
var datefromparsed = this.formatDate(new Date(element[1]));
var datetoparsed = this.formatDate(new Date(element[2]));
_this.fetchSmartlyAdSpent(element[4], element[8], _this.state.yesterday, _this.state.yesterday);
element.push(this.state.todayDate);
element.push(datefromparsed);
element.push(datetoparsed);
});
console.log(this.state.toProcessCSV);
}
fetchSmartlyAdSpent(studyID, indication, datefrom, dateto){
var accountID = '5ced43ceed768137e47078c2'; //OTHER, TO DELETE
var url = "https://stats-api.smartly.io/v1.2/stats";
url = url + "?account_id=" + accountID;
url = url + "&api_token=" + this.state.smartlyAPIToken;
url = url + "&stats=" + datefrom + ":" + dateto;
url = url + "&format=json&csv_col_separator=,&csv_dec_separator=.&filter_type=$and&metrics=spent&groupby=account_name&filters=";
var filters=[{"key":"adgroup_name","op":"contains","value": studyID}];
var urlEncode = url + encodeURIComponent(JSON.stringify(filters));
this.sendRequest(urlEncode, (json) => {
console.log(json.summary.spent);
});
}
sendRequest = (url, callback) => {
fetch(url, {
/*headers: {
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*"
},*/
//credentials: "include"
})
.then(response => response.json())
.then(json => {
callback(json);
})
.catch((error) => {
console.log(error);
});
}
render() {
return (
<div className="process-csv">
<div style={{'float':'left'}}>
<div>Select CSV to Process</div>
<input type="file" accept=".csv" onChange={this.getFile('toProcessCSV')}/>
</div>
<div style={{'float':'left'}}>
<div>Select CSV from previous day to Process</div>
<input type="file" accept=".csv" onChange={this.getFile('previousCSV')}/>
</div>
<br/>
{(this.state.isReadyToProces) && <button onClick={this.startCampaignPatientQualityProcess}>Start</button>}
</div>
);
}
}
export default ProcessCsv;
<file_sep>import React from 'react';
import logo from './logo.svg';
import './App.css';
import ProcessCsv from './js/ProcessCsv';
import MergeCsv from './js/MergeCsv';
import MergeAndUpdateCsv from './js/MergeAndUpdateCsv';
import PatientMediaTracking from './js/PatientMediaTracking';
import MergeCraigslistAdspent from './js/MergeCraigslistAdspent';
import UpdatedCPQ_PAC_CLSpent_Merging from './js/UpdatedCPQ_PAC_CLSpent_Merging';
import UpdatedCLSignUps from './js/UpdatedCLSignUps';
import TempCLSignUp from './js/TempCLSignUp';
import CheckKenshooSpentFromMerge4 from './js/CheckKenshooSpentFromMerge4';
//var csv = require('./jquery.csv.js');
function App() {
return (
<div className="App">
<header className="App-header">
<p>
Studykik Data Processor
</p>
<UpdatedCPQ_PAC_CLSpent_Merging/>
<iframe src="https://www.upwork.com/ab/feed/jobs/rss?q=analytics&sort=recency&paging=0%3B10&api_params=1&securityToken=b4f42b611022e9d44f4e2d2a6ab64b00c56e61bd2b6ee837bfe7a04e13f54ad4d53bbed38f156705a29747f1e017e1881714f6b87c8a6c2d2e26e05dde1d5c72&userUid=424301271808458752&orgUid=424301271812653057"></iframe>
</header>
</div>
);
}
export default App;
<file_sep>import React, { Component } from 'react';
import csv from 'jquery-csv'
class PatientMediaTracking extends Component {
constructor(props) {
super(props);
this.state = {
todayDate: null,
dateUseAsNow: "2020-01-23",
studyListCSV: null,
patientMediaTrackingHistoryCSV: null,
patientMediaTrackedToday: [],
isReadyToProces: false,
isSendingRequests: false,
studykikAuth: '<KEY>',
}
}
componentDidMount() {
var yesterday = new Date((new Date()).valueOf() - 1000*60*60*24);
this.state.todayDate = this.formatDate(yesterday);
}
formatDate(d) {
var day = d.getUTCDate() > 9 ? d.getUTCDate() : '0'+d.getUTCDate();
var month = d.getUTCMonth()+1 > 9 ? (d.getUTCMonth()+1) : '0'+(d.getUTCMonth()+1);
return d.getUTCFullYear() + '-' + month + '-' + day;
}
getFile = name => e => {
var _this = this;
var file = e.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var _csv = event.target.result;
var data = csv.toArrays(_csv);
//data.shift(); //remove header
_this.state[name] = data;
if(_this.state.studyListCSV != null && _this.state.patientMediaTrackingHistoryCSV != null)
_this.setState({isReadyToProces: true});
}
}
startStudyPatientTrackingProcess = () => {
console.log('called startStudyPatientTrackingProcess...');
this.state.studyListCSV.shift(); //remove header
this.state.isSendingRequests = true;
var _this = this;
var i=0;
this.state.intervalId = setInterval(function() {
console.log('sending request for study at index '+i);
_this.sendRequestStudyPatients(i);
i++;
if(i == _this.state.studyListCSV.length) {
console.log('cleared interval');
_this.state.isSendingRequests = false;
clearInterval(_this.state.intervalId);
}
}, 500);
console.log("done calling startStudyPatientTrackingProcess");
}
sendRequestStudyPatients = (index) => {
var studyID = this.state.studyListCSV[index][1];
var campaignID = this.state.studyListCSV[index][0];
var siteID = this.state.studyListCSV[index][2];
var url = "https://api.studykik.com/api/v1/studies/"+studyID+"/patients?campaignId="+campaignID;
fetch(url, {
headers: {
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Authorization": this.state.studykikAuth
},
credentials: "include"
})
.then(response => response.json())
.then(json => {
for(var i=0; i<json.length; i++) {
var _json = json[i];
var categoryID = _json.id;
for (var j = 0; j < _json.patients.length; j++) {
var patient = _json.patients[j].patient;
var patientID = patient.id;
var campaignID = patient.campaign_id;
var siteID = patient.site_id;
//ADD DATE CHECKER CONDITION HERE!
this.state.patientMediaTrackedToday.push(
[campaignID,
studyID,
siteID,
this.state.dateUseAsNow,
patientID,
categoryID]
);
};
}
console.log('done fetched sendRequestStudyPatients for index '+index);
//console.log(this.state.patientMediaTrackedToday);
if(index == this.state.studyListCSV.length-1)
this.startStudyDispositionTrackingProcess();
})
.catch((error) => {
console.log(error);
});
}
startStudyDispositionTrackingProcess = () => {
//this.state.studyListCSV.shift(); //remove header
console.log('called startStudyDispositionTrackingProcess...');
this.state.isSendingRequests = true;
var _this = this;
var i=0;
this.state.intervalId = setInterval(function() {
console.log('sending request for study at index '+i);
_this.sendRequestStudyDisposition(i);
i++;
if(i == _this.state.studyListCSV.length) {
console.log('cleared interval');
_this.state.isSendingRequests = false;
clearInterval(_this.state.intervalId);
}
}, 500);
console.log("done calling startStudyDispositionTrackingProcess");
}
sendRequestStudyDisposition = (index) => {
var studyID = this.state.studyListCSV[index][1];
var url = "https://api.studykik.com/api/v1/studies/"+studyID+"/dispositions";
fetch(url, {
headers: {
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Authorization": this.state.studykikAuth
},
credentials: "include"
})
.then(response => response.json())
.then(json => {
for(var i=0; i<this.state.patientMediaTrackedToday.length; i++) {
var tempPatient = this.state.patientMediaTrackedToday[i];
if(tempPatient[1] == studyID) {
var findDisposition = json.find(function(el) {
return (el.patient_id == tempPatient[4]);
});
if(findDisposition) {
//var recentUpdate = findDisposition.created.substr(0,10) == '2020-01-16' ? true : false;
//this.state.patientMediaTrackingHistoryCSV[i][6] = (recentUpdate) ? '' : findDisposition.dispositionKey;
this.state.patientMediaTrackedToday[i][6] = findDisposition.dispositionKey;
} else {
this.state.patientMediaTrackedToday[i][6] = '';
}
}
}
console.log('done fetched sendRequestStudyDisposition for index '+index);
if(index == this.state.studyListCSV.length-1)
this.finalizeMergedCSVFile(this.state.patientMediaTrackedToday);
})
.catch((error) => {
console.log(error);
});
}
startPatientMediaTrackingProcess = () => {
console.log('called startPatientMediaTrackingProcess...');
this.state.isSendingRequests = true;
var _this = this;
var i=0;
this.state.intervalId = setInterval(function() {
console.log('sending request for study/patient at index '+i);
_this.sendRequestPatientMediaTracking(i);
i++;
if(i == _this.state.patientMediaTrackingHistoryCSV.length) {
console.log('cleared interval');
_this.state.isSendingRequests = false;
clearInterval(_this.state.intervalId);
}
}, 300);
console.log("done calling startPatientMediaTrackingProcess");
}
sendRequestPatientMediaTracking = (index, withDispo) => {
console.log('index '+index);
console.log('>. '+this.state.patientMediaTrackingHistoryCSV[index]);
//return '';
var patientID = this.state.patientMediaTrackingHistoryCSV[index][4];
var url = "https://api.studykik.com/api/v1/patients/"+patientID+"?filter=%7B%22include%22%3A[%22studySource%22,%22source%22]%7D";
fetch(url, {
headers: {
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Authorization": this.state.studykikAuth
},
credentials: "include"
})
.then(response => response.json())
.then(json => {
var studySource = json.studySource.name == null ? 'fb' : json.studySource.name;
var temp = this.state.patientMediaTrackingHistoryCSV[index];
if(withDispo) {
var tempDispo = temp[6]; //move dispo to column 7
temp[7] = tempDispo;
temp[6] = studySource;
} else {
temp[6] = studySource;
}
this.state.patientMediaTrackingHistoryCSV[index] = temp;
console.log('done fetched sendRequestPatientMediaTracking for index '+index);
//console.log(this.state.patientMediaTrackedToday);
})
.catch((error) => {
console.log(error);
});
}
startAccumulatingPatientMediaTrackingProcess = () => {
var accumulated = [];
this.state.studyListCSV.shift();
for(var i=0; i<this.state.studyListCSV.length; i++) {
var studyID = this.state.studyListCSV[i][1];
var campaignID = this.state.studyListCSV[i][0];
var tempAcc = [
campaignID,
studyID,
this.state.studyListCSV[i][2],
this.state.dateUseAsNow,
0,0,0,0,0,0,0,0]; //row for NA
var filteredPatients = this.state.patientMediaTrackingHistoryCSV.filter(function(el){
return el[0] == campaignID && el[1] == studyID;
});
//cl media name
for(var j=1; j<=8; j++) {
var filteredMedia = filteredPatients.filter(function(el){
return el[5] == j && el[6] == 'cl';
});
tempAcc.push(filteredMedia.length);
}
//fb media name
for(var j=1; j<=8; j++) {
var filteredMedia = filteredPatients.filter(function(el){
return el[5] == j && el[6] == 'fb';
});
tempAcc.push(filteredMedia.length);
}
//cl disposition
for(var j=1; j<=4; j++) {
var filteredMedia = filteredPatients.filter(function(el){
return (el[7] == j && el[6] == 'cl');
});
tempAcc.push(filteredMedia.length);
}
//fb disposition
for(var j=1; j<=4; j++) {
var filteredMedia = filteredPatients.filter(function(el){
return (el[7] == j && el[6] == 'fb');
});
tempAcc.push(filteredMedia.length);
}
//fg media name
for(var j=1; j<=8; j++) {
var filteredMedia = filteredPatients.filter(function(el){
return el[5] == j && el[6] == 'fg';
});
tempAcc.push(filteredMedia.length);
}
//fg disposition
for(var j=1; j<=4; j++) {
var filteredMedia = filteredPatients.filter(function(el){
return (el[7] == j && el[6] == 'fg');
});
tempAcc.push(filteredMedia.length);
}
accumulated.push(tempAcc);
}
this.finalizeMergedCSVFile(accumulated);
}
startMergePatientsMediaTrackNoDataYet = () => {
//studyListCSV -- with media tracked
//patientMediaTrackingHistoryCSV
var tempPatients = [];
for(var i=0; i<this.state.patientMediaTrackingHistoryCSV.length; i++) {
var temp = this.state.patientMediaTrackingHistoryCSV[i];
var filteredMedia = this.state.studyListCSV.filter(function(el){
return (el[0] == temp[0] && //campaignID
el[1] == temp[1] && //studyID
el[2] == temp[2] && //siteID
el[4] == temp[4]); //patientID
});
if(filteredMedia.length) {
var tempDispo = this.state.patientMediaTrackingHistoryCSV[i][6]
this.state.patientMediaTrackingHistoryCSV[i][7] = tempDispo; //move dispo value to column 7
this.state.patientMediaTrackingHistoryCSV[i][6] = filteredMedia[0][6];
} else {
//needs media tracking fetched from api
var _t = [...this.state.patientMediaTrackingHistoryCSV[i]];
_t[7] = i; //index;
tempPatients.push(_t);
}
}
console.log(tempPatients);
console.log(this.state.patientMediaTrackingHistoryCSV);
this.startMergePatientsMediaTrackWithData(tempPatients);
}
startMergePatientsMediaTrackWithData = (tempPatients) => {
console.log('called startMergePatientsMediaTrackWithData...');
this.state.isSendingRequests = true;
var _this = this;
var i=0;
this.state.intervalId = setInterval(function() {
console.log('sending request for study/patient at index '+i);
//if(_this.state.patientMediaTrackingHistoryCSV[i][6] == '' || _this.state.patientMediaTrackingHistoryCSV[i][6] == null)
_this.sendRequestPatientMediaTracking(tempPatients[i][7], true);
i++;
if(i == tempPatients.length) {
console.log('cleared interval');
_this.state.isSendingRequests = false;
clearInterval(_this.state.intervalId);
}
}, 300);
console.log("done calling startMergePatientsMediaTrackWithData");
}
startAccumulatingTwoBeforeAfterPatientMT = () => {
//studyListCSV -- before
//patientMediaTrackingHistoryCSV -- today
var newArray = [];
for(var i=0; i<this.state.patientMediaTrackingHistoryCSV.length; i++) {
var temp = this.state.patientMediaTrackingHistoryCSV[i];
//patient found but patient category or patient disposition column moved
var filteredMedia = this.state.studyListCSV.filter(function(el){
return (el[0] == temp[0] && //campaignID
el[1] == temp[1] && //studyID
el[2] == temp[2] && //siteID
el[4] == temp[4] && //patientID
(el[5] != temp[5] || //patientCategory
el[7] != temp[7])); //patientDisposition
});
//patient is present on the list
var isPatientNew = this.state.studyListCSV.find(function(el){
return (el[4] == temp[4]);
});
if(filteredMedia.length) {
temp[5] = (filteredMedia[0][5] == temp[5]) ? "" : temp[5]; //override patientCategory if previous day data didnt update
temp[7] = (filteredMedia[0][7] == temp[7]) ? "" : temp[7]; //override patientDisposition if previous day data didnt update
newArray.push(temp);
}
else if(isPatientNew == undefined) {
newArray.push(temp);
}
}
this.finalizeMergedCSVFile(newArray);
}
getLevel = (levelID) => {
var levels = [
"Bronze",
"Silver",
"Gold",
"Platinum",
"Diamond",
"Ruby",
"Platinum Plus",
"Diamond Plus",
"Ruby Plus"
];
return levels[levelID-1];
}
getDateToUTCSK = (date) => {
var dayName = [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
];
var monthName = [
"Jan", "Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
var _date = new Date(date);
var day = _date.getUTCDate();
var dayVal = dayName[_date.getUTCDay()];
var monVal = monthName[_date.getUTCMonth()];
var year = _date.getUTCFullYear();
return dayVal + " " + monVal + " " + day + " " + year + " 00:00:00 GMT+0000 (UTC)";
}
saveToCSV = () => {
//console.log(file);
//if(file == 'patientMediaTrackedToday')
//this.finalizeMergedCSVFile(this.state.patientMediaTrackedToday); //startStudyPatientTrackingProcess
//this.finalizeMergedCSVFile(this.state.cpqCSV);
this.finalizeMergedCSVFile(this.state.patientMediaTrackingHistoryCSV); //startMergePatientsMediaTrackNoDataYet
}
finalizeMergedCSVFile = (cpqCSV) => {
console.log(cpqCSV);
var csvContent = "data:text/csv;charset=utf-8,"
+ csv.fromArrays(cpqCSV);
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link);
link.click();
}
render() {
return (
<div className="process-csv" style={{'textAlign':'left'}}>
<hr/>
<h2>
Merging of campaign_patient_quality and pac_daily_report
</h2>
<p>Change the value of studykik auth and daily date!</p>
<p>Date: {this.state.dateUseAsNow}</p>
<br/>
<div style={{'float':'left'}}>
<div>Select CSV for list of studies to track:</div>
<input type="file" accept=".csv" onChange={this.getFile('studyListCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<br/>
<div style={{'float':'left'}}>
<div>Select CSV with the patient media tracking history:</div>
<input type="file" accept=".csv" onChange={this.getFile('patientMediaTrackingHistoryCSV')} style={{'float':'left'}}/>
</div>
<br/>
<br/>
<br/>
{(this.state.isReadyToProces) && <button onClick={this.startStudyPatientTrackingProcess}>1 Start Study-Patient Tracking!</button>}
<br/>
{(this.state.isReadyToProces) && <button onClick={this.startPatientMediaTrackingProcess}>Start Patient Media Tracking!</button>}
<br/>
{(this.state.isReadyToProces) && <button onClick={this.startAccumulatingPatientMediaTrackingProcess}>4 Start Accumulating Patient Media Tracking!</button>}
<br/>
{(this.state.isReadyToProces) && <button onClick={this.startMergePatientsMediaTrackNoDataYet}>2 Merge The Patients Media Tracking, No fetching of New Data Yet!</button>}
<br/>
{(this.state.isReadyToProces) && <button onClick={this.startAccumulatingTwoBeforeAfterPatientMT}>3 Before and Today Patient Media Accumulating!</button>}
<br/>
<button onClick={this.saveToCSV}>Click When Done Fetching!</button>
<br/>
<button onClick={this.saveToCSV}>Download with no media tracking yet!</button>
</div>
);
}
}
export default PatientMediaTracking;
|
1262eac11b06a2152b6a697de1249cb9cb2badb0
|
[
"JavaScript",
"HTML"
] | 9
|
JavaScript
|
daisyriedumali/studykik-daily-import
|
e29fedfd6cddb05f30b8ce04fa2fce36e9837847
|
2d60e95b3c9b7b8498c89f24bda0b259aa3fe052
|
refs/heads/master
|
<file_sep>window.onload = function() {
setTimeout(function() {
var player = new Player(document.getElementById('myVid'));
//document.getElementById('myVid2').src = "http://172.16.58.3/staticVideo";
}, 1000);
}<file_sep>'use strict';
function Player(el) {
'use strict';
var VERBOSE = false;
if (!MediaSource) {
throw new Error('NO MEDIASOURCE!');
}
//manage vos
var _latestVos = [];
var maxLatestVos = 20;
var requestId;
//booleans
var updatedStarted, locked, starting = true;
//playback info
var segDuration = 0,
playOffset = 0,
stuckCounter = 0,
enterFrameCounter = 0,
previousCurrentTime = 0,
segmentIndex = 0,
totalSegments = 0,
paused = false,
skipCount = 0;
////-----------------
//SETUP
////-----------------
var _currentVo;
var mediaSource;
var sourceBuffer;
var _effects;
var videoElement = el;
var onBufferUpdateStartBound = onBufferUpdateStart.bind(this);
var onBufferUpdateEndBound = onBufferUpdateEnd.bind(this);
mediaSource = new MediaSource();
var url = URL.createObjectURL(mediaSource);
videoElement.src = url;
mediaSource.addEventListener('error', _onSourceError, false);
mediaSource.addEventListener('sourceopen', _onSourceOpen, false);
//requestId = window.requestAnimationFrame(onUpdate);
function _onSourceError(e) {
if (VERBOSE) {
console.log(e);
}
}
function _onSourceOpen(e) {
starting = false;
newBufferSouce('avc1.4d400d');
//newBufferSouce('avc1.4d401f,mp4a.40.2');
}
function newBufferSouce(codecs) {
mediaSource.removeEventListener('sourceopen', _onSourceOpen);
sourceBuffer = mediaSource.addSourceBuffer('video/mp4; codecs="' + codecs + '"');
sourceBuffer.addEventListener('updatestart', onBufferUpdateStartBound);
sourceBuffer.addEventListener('updateend', onBufferUpdateEndBound);
if (VERBOSE) {
console.log('Source Open');
}
request();
}
videoElement.addEventListener("timeupdate", onUpdate, false);
videoElement.addEventListener("ended", _onVideoEnded, false);
////-----------------
//VIDEO HANDLERS
////-----------------
function _onVideoEnded(e) {
console.warn('Video Ended');
}
////-----------------
//BUFFER HANDLERS
////-----------------
function onBufferUpdateStart() {
updatedStarted = true;
}
function onBufferUpdateEnd() {
updatedStarted = false;
locked = false;
}
////-----------------
//UPDATE
////-----------------
function _manageVos() {
_latestVos.push(_currentVo);
if (_latestVos.length === maxLatestVos) {
_latestVos.shift();
}
}
function onUpdate() {}
function preciseUpdate() {}
//----------
//PLAY A VO
//----------
/*
{
url:
}
*/
function request() {
getSidx('QcIy9NiNbmo');
return;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://52.90.55.176/getVideoIndex?id=TTUpgAVwrXE', true);
xhr.responseType = 'arraybuffer';
xhr.addEventListener("readystatechange", function() {
if (xhr.readyState == xhr.DONE) {
console.log(xhr);
sourceBuffer.appendBuffer(new Uint8Array(xhr.response));
}
});
xhr.send();
return;
var xhr = new XMLHttpRequest();
if (VERBOSE) {
console.log(data['url'], data['byteRange']);
}
xhr.open('GET', 'http://52.90.55.176/getVideoSidx?id=TTUpgAVwrXE', true);
xhr.send();
xhr.responseType = 'arraybuffer';
xhr.addEventListener("readystatechange", function() {
if (xhr.readyState == xhr.DONE) { //wait for video to load
if (!sourceBuffer || !mediaSource) {
return;
}
var segResp = new Uint8Array(xhr.response);
var off = 0;
if (sourceBuffer.buffered.length > 0) {
off = sourceBuffer.buffered.end(sourceBuffer.buffered.length - 1);
}
function _trySettingOffset() {
try {
sourceBuffer.timestampOffset = off || 0;
initialRequest(data, __addInit);
} catch (e) {
console.log(e);
//resetMediasource();
}
}
function __addInit(initRes) {
sourceBuffer.appendBuffer(initRes);
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://52.90.55.176/getVideo?id=TTUpgAVwrXE', true);
xhr.send();
xhr.responseType = 'arraybuffer';
xhr.addEventListener("readystatechange", function() {
if (xhr.readyState == xhr.DONE) { //wait for video to load
var segResp = new Uint8Array(xhr.response);
sourceBuffer.appendBuffer(segResp);
}
});
if (VERBOSE) {
console.log('init added');
}
}
function __onInitAddStart() {
}
function __onInitAdded() {
if (mediaSource.readyState === 'open') {
sourceBuffer.removeEventListener('updatestart', __onInitAddStart);
sourceBuffer.removeEventListener('updateend', __onInitAdded);
sourceBuffer.addEventListener('updateend', onBufferUpdateEndBound);
sourceBuffer.addEventListener('updatestart', onBufferUpdateStartBound);
if (VERBOSE) {
console.log(segmentIndex, '/', totalSegments);
}
sourceBuffer.timestampOffset = off -= data['timestampOffset'];
//sourceBuffer.timestampOffset = sourceBuffer.timestampOffset - data['timestampOffset'];
sourceBuffer.appendBuffer(segResp);
segmentIndex++;
}
}
_trySettingOffset();
}
}, false);
}
function addSegment(currentVo) {
var formData = new FormData();
formData.append('url', currentVo.url);
formData.append('byteRange', currentVo.byteRange);
var xhr = new XMLHttpRequest();
if (VERBOSE) {
console.log(currentVo['url'], currentVo['byteRange']);
}
xhr.open('POST', 'http://52.90.55.176/getVideo', true);
xhr.responseType = 'arraybuffer';
xhr.send(formData);
xhr.addEventListener("readystatechange", function() {
console.log(xhr);
if (xhr.readyState == xhr.DONE) { //wait for video to load
console.log("DONE");
if (!sourceBuffer || !mediaSource) {
return;
}
var segResp = new Uint8Array(xhr.response);
var off = 0;
if (sourceBuffer.buffered.length > 0) {
off = sourceBuffer.buffered.end(sourceBuffer.buffered.length - 1);
}
function _trySettingOffset() {
console.log("_trySettingOffset");
try {
sourceBuffer.timestampOffset = off || 0;
initialRequest(currentVo, __addInit);
} catch (e) {
console.log("Error _trySettingOffset");
resetMediasource();
}
}
function __addInit(initRes) {
if (VERBOSE) {
console.log("readyState", mediaSource.readyState);
}
console.log(mediaSource.readyState);
if (mediaSource.readyState === 'open' && sourceBuffer) {
sourceBuffer.removeEventListener('updatestart', onBufferUpdateStartBound);
sourceBuffer.removeEventListener('updateend', onBufferUpdateEndBound);
sourceBuffer.addEventListener('updatestart', __onInitAddStart);
sourceBuffer.addEventListener('updateend', __onInitAdded);
if (VERBOSE) {
console.log("Is updating:", sourceBuffer.updating);
}
try {
sourceBuffer.appendBuffer(initRes);
if (VERBOSE) {
console.log('init added');
}
} catch (e) {
console.log(e);
resetMediasource();
}
}
}
function __onInitAddStart() {
}
function __onInitAdded() {
console.log("readyState", mediaSource.readyState);
if (mediaSource.readyState === 'open' && sourceBuffer) {
sourceBuffer.removeEventListener('updatestart', __onInitAddStart);
sourceBuffer.removeEventListener('updateend', __onInitAdded);
sourceBuffer.addEventListener('updateend', onBufferUpdateEndBound);
sourceBuffer.addEventListener('updatestart', onBufferUpdateStartBound);
if (VERBOSE) {
console.log("Segment duration:", currentVo.duration);
console.log(segmentIndex, '/', StreamerPlaylist.getLength());
}
off -= currentVo['timestampOffset'];
if (VERBOSE) {
console.log("Segment TimeOff:", currentVo['timestampOffset'], "Total TimeOff:", off);
}
try {
sourceBuffer.timestampOffset = off;
} catch (e) {
console.log(e);
resetMediasource();
}
//sourceBuffer.timestampOffset = sourceBuffer.timestampOffset - currentVo['timestampOffset'];
try {
sourceBuffer.appendBuffer(segResp);
} catch (e) {
console.log(e);
resetMediasource();
}
segmentIndex++;
}
}
_trySettingOffset();
}
}, false);
}
function getSidx(id) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://52.90.55.176/getVideoSidx?id=' + id, true);
xhr.addEventListener("readystatechange", function() {
if (xhr.readyState == xhr.DONE) {
var parsed = JSON.parse(xhr.response);
var vo = _chooseReference(parsed);
console.log(vo);
addSegment(vo);
}
});
xhr.send();
}
function _chooseReference(data) {
var startIndex = 0;
var endIndex = 5;
var duration = 0;
var references = data.sidx.references;
var sRef = references[startIndex];
var eRef = references[endIndex];
for (var j = startIndex; j < endIndex; j++) {
duration += references[j]['durationSec'];
}
var brEnd = (parseInt(eRef['mediaRange'].split('-')[0], 10) - 1);
var brMax = brEnd + 1;
var videoVo = {};
videoVo['url'] = data['url'];
videoVo['byteRange'] = sRef['mediaRange'].split('-')[0] + '-' + brEnd;
videoVo['byteRangeMax'] = brMax;
videoVo['codecs'] = data['codecs'];
videoVo['indexRange'] = data['indexRange'];
videoVo['timestampOffset'] = sRef['startTimeSec'];
videoVo['duration'] = duration;
return videoVo;
}
function initialRequest(data, callback) {
var xhr = new XMLHttpRequest();
var formData = new FormData();
formData.append('url', data.url);
formData.append('indexRange', data.indexRange);
xhr.open('POST', 'http://172.16.58.3/getVideoIndex', true);
xhr.send(formData);
xhr.responseType = 'arraybuffer';
try {
xhr.addEventListener("readystatechange", function() {
if (xhr.readyState == xhr.DONE) { // wait for video to load
callback(new Uint8Array(xhr.response));
}
}, false);
} catch (e) {
log(e);
}
}
return {
request: request
}
};
module.exports = Player;<file_sep>var _ = require('lodash');
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors'); // "Request" library
var fs = require('fs'); // "Request" library
var DL = require('./playlist_downloader');
var YT = require('ytdl-core');
var request = require('request');
var multiparty = require('multiparty');
var EXPRESS = (function() {
var app = express();
var server, routes;
app.use(cors());
/*app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));*/
app.get('/', function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Hello AWSBOX\n');
});
app.get('/goofy', function(req, res) {
request('http://images1.wikia.nocookie.net/__cb20120715102950/disney/images/a/a5/Disneygoofy2012.jpeg').pipe(res);
});
app.get('/goofy2', function(req, res) {
request('https://s3-eu-west-1.amazonaws.com/chromegno.me/images/locations/08.jpg').pipe(res);
});
app.get('/getImage', function(req, res) {
request("https://s3-eu-west-1.amazonaws.com/chromegno.me/bergsjostolen.jpg").pipe(res);
});
app.get('/getImage2', function(req, res) {
var stat = fs.statSync(__dirname + '/920.jpeg');
res.writeHead(200, {
'Content-Type': 'image/jpeg',
'Content-Length': stat.size
});
var s = fs.createReadStream(__dirname + '/920.jpeg');
s.on('open', function() {
// This just pipes the read stream to the response object (which goes to the client)
s.pipe(res);
});
});
app.get('/staticVideo', function(req, res) {
YT("http://www.youtube.com/watch?v=zg_fAUsNVJ4").pipe(res)
});
/*app.get('/getVideo', function(req, res) {
//https://placebear.com/1110/920
DL.getSidx(req.query).then(function(data) {
var url = data.url + '&range=' + data.range;
console.log(data.range, data.max);
res.writeHead(206, {
'Content-Range': 'bytes ' + data.range + '/' + data.max,
//'Content-Range': 'bytes ' + range + '/27908',
//'Content-Length': '27908',
'X-Accel-Buffering': 'no',
'Content-Length': data.max,
'Accept-Ranges': 'bytes',
'Content-Type': 'video/mp4',
"Access-Control-Allow-Origin": "*"
});
console.log(url);
var r = request({
url: url,
//url: 'https://radvisions.s3-eu-west-1.amazonaws.com/2b173550-a6b9-11e5-a7b6-b9c2f8eca471'
}).on('response', function(response) {
response.on('data', function(data) {
console.log("data chunk received: " + data.length)
});
response.on('end', function(data) {
console.log('Video completed');
});
}).pipe(res);
r.on('error', function(err) {
console.log(err);
});
});
});*/
app.post('/getVideo', function(req, res) {
var form = new multiparty.Form();
form.parse(req, function(err, data, files) {
console.log(data);
var url = data.url + '&range=' + data.byteRange;
res.writeHead(206, {
'Content-Range': 'bytes ' + data.byteRange + '/' + data.max,
//'Content-Range': 'bytes ' + range + '/27908',
//'Content-Length': '27908',
'X-Accel-Buffering': 'no',
'Content-Length': data.byteRangeMax,
'Accept-Ranges': 'bytes',
'Content-Type': 'video/mp4',
"Access-Control-Allow-Origin": "*"
});
console.log(url);
var r = request({
url: url,
//url: 'https://radvisions.s3-eu-west-1.amazonaws.com/2b173550-a6b9-11e5-a7b6-b9c2f8eca471'
}).on('response', function(response) {
response.on('data', function(data) {
console.log("data chunk received: " + data.length)
});
response.on('end', function(data) {
console.log('Video completed');
});
}).pipe(res);
r.on('error', function(err) {
console.log(err);
});
});
});
app.post('/getVideoIndex', function(req, res) {
var form = new multiparty.Form();
form.parse(req, function(err, data, files) {
console.log(data);
var url = data.url + '&range=' + data.indexRange;
res.writeHead(206, {
'Content-Range': 'bytes ' + data.indexRange,
'X-Accel-Buffering': 'no',
'Content-Length': data.indexRangeMax,
'Accept-Ranges': 'bytes',
'Content-Type': 'video/mp4',
"Access-Control-Allow-Origin": "*"
});
console.log(url);
var r = request({
url: url,
//url: 'https://radvisions.s3-eu-west-1.amazonaws.com/2b173550-a6b9-11e5-a7b6-b9c2f8eca471'
}).on('response', function(response) {
response.on('data', function(data) {
console.log("data chunk received: " + data.length)
});
response.on('end', function(data) {
console.log('Video completed');
});
}).pipe(res);
r.on('error', function(err) {
console.log(err);
});
});
});
app.get('/getVideoSidx', function(req, res) {
DL.getSidx(req.query).then(function(data) {
res.send(data);
});
});
/* app.get('/getVideo2', function(req, res) {
DL.getSidx().then(function(data) {
var url = data.url + '&range=' + data.range;
console.log(data.range, data.max);
res.writeHead(206, {
'Content-Range': 'bytes ' + data.range + '/' + data.max,
//'Content-Range': 'bytes ' + range + '/27908',
//'Content-Length': '27908',
'Content-Length': data.max,
'Accept-Ranges': 'bytes',
'Content-Type': 'video/mp4',
"Access-Control-Allow-Origin": "*"
});
console.log(url);
var r = request({
url: url,
//url: 'https://radvisions.s3-eu-west-1.amazonaws.com/2b173550-a6b9-11e5-a7b6-b9c2f8eca471'
}).on('response', function(response) {
response.on('data', function(data) {
res.write(data);
console.log("data chunk received: " + data.length)
});
response.on('end', function(data) {
res.end();
console.log('Video completed');
});
});
r.on('error', function(err) {
console.log(err);
});
});
});*/
//routes
//routes = require('./routes')(app);
server = app.listen(process.env['PORT'] || 8080, '127.0.0.1');
console.log("STARTED, ", process.env['PORT']);
})();
module.exports = EXPRESS;<file_sep>var _ = require("lodash");
var request = require('request');
var DL = require('./playlist_downloader');
var ROUTES = function(exp) {
var express = exp;
express.get('/video', function(req, res) {
console.log(__dirname);
/* DL.getSidx().then(function(data) {
var url = data.url + '&range=' + data.range;
var r = request({
url: url
}, function(err, response, body) {
res.writeHead(206, {
'Content-Range': 'bytes ' + data.range + '/' + data.max,
'Content-Length': data.max,
'Accept-Ranges': 'bytes',
'Content-Type': 'video/mp4'
});
r.pipe(res);
});
r.on('error', function(err) {
console.log(err);
});
});*/
});
console.log("sdsd");
};
module.exports = ROUTES;<file_sep>var _ = require('lodash');
var Q = require('bluebird');
var request = require('request');
var fs = require('fs');
var path = require('path');
var YT = require('ytdl-core');
var request = require('request');
var xml2js = require('xml2js');
var YOUTUBE_KEY = '<KEY>';
var RESOLUTIONS = ['720p', '480p', '360p'];
var DASH = ['133', '134', '135', '136'];
var PLAYLIST_ID = "PLRy338DcC4FLXMjXid_T-yn9GXbmiN6s-";
var V_ID = "KsdAIYmSHAg";
var YoutubeScraper = (function() {
'use strict';
var parser = new xml2js.Parser();
function getSidx(query) {
V_ID = query.id;
return new Q(function(resolve, reject) {
var url = 'http://www.youtube.com/watch?v=' + query.id;
YT.getInfo(url, {}, function(err, info) {
extractMpdRepresentation(info).then(function(data) {
resolve(data);
});
});
/*
*/
});
}
function extractMpdRepresentation(ytInfo, format) {
return new Q(function(resolve, reject) {
var r = request({
url: ytInfo['dashmpd']
}, function(err, response, body) {
if (err) {
console.log(err);
return;
}
var mpdVo = {};
parser.parseString(body, function(err, result) {
if (err || !result) {
return;
}
var adaptionSets = result['MPD']['Period'][0]['AdaptationSet'];
var representations = [];
var videoResults = [];
_.each(adaptionSets, function(adaption) {
var mimeType = adaption['$']['mimeType'];
//has video
if (mimeType === ('video/mp4')) {
representations = adaption['Representation'];
}
});
_.each(representations, function(representation) {
var res = representation['$'];
_.each(DASH, function(iTag) {
if (res.id === iTag) {
var index = representation.SegmentBase[0].Initialization[0]['$'].range.split('-')[0];
var range = representation.SegmentBase[0]['$'].indexRange.split('-')[1];
var indexRange = index + '-' + range;
videoResults.push({
$: res,
BaseURL: representation.BaseURL,
SegmentBase: representation.SegmentBase,
url: representation.BaseURL[0]['_'],
indexRange: indexRange,
codecs: res.codecs
});
}
});
});
var test = videoResults[0];
sidxFromInitRange(test.url, test.indexRange).then(function(sidx) {
//var f = fs.createWriteStream(path.join(__dirname, 'xx.mp4'));
test.sidx = sidx;
resolve(test);
return;
var rr = test.indexRange.split('-')[0];
var ee = sidx.references[20].mediaRange.split('-')[1];
resolve({
url: test.url,
references: sidx.references,
indexRange: rr + '-' + ee,
indexRangeMax: test.indexRange.split('-')[1],
range: rr + '-' + ee,
max: Number(ee) + 1,
codecs: test.codecs
});
});
//fs.writeFileSync(path.join(__dirname, 'xx.json'), JSON.stringify(result), null, 4);
});
});
r.on('error', function(err) {
console.log(err);
});
});
}
function sidxFromInitRange(url, indexRange) {
return new Q(function(resolve, reject) {
var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.setRequestHeader("Range", "bytes=" + indexRange);
xhr.send();
xhr.responseType = 'arraybuffer';
try {
xhr.addEventListener("readystatechange", function() {
if (xhr.readyState == xhr.DONE) { // wait for video to load
// Add response to buffer
var p = require('./sidx').parseSidx(xhr.response);
resolve(p);
}
}, false);
} catch (e) {
console.log(e);
}
})
}
return {
getSidx: getSidx
}
})();
module.exports = YoutubeScraper;
|
b465eb0d118e142b4d08fc3db556b2595303fb00
|
[
"JavaScript"
] | 5
|
JavaScript
|
samradical/yt-dash-reader
|
eac549b026d02e4a239e73b510d40513918359f3
|
4ec40b6cada8498dbe4b499bdf0b40817fd1b2d8
|
refs/heads/master
|
<file_sep># Symfony 2 with NGINX Base Box
To get started, first you need to create the VM.
git clone <EMAIL>:alsbury/symfony2nginx.git sf2
cd sf2
By installing the hostsupdater plugin, you don't have to edit the hosts file every time you turn the VM on. This will require you to type an adminsitrator password when you turn the VM on or off. But it makes everything a lot easier if you happen to run more than one Vagrant VM.
vagrant install plugin vagrant-hostsupdater
Then you can launch the VM:
vagrant up
At this point, you should be able to visit http://sf2.debug
<file_sep>apt-get -y update
export DEBIAN_FRONTEND=noninteractive
echo "mysql-server-5.6 mysql-server/root_password_again password <PASSWORD>" | debconf-set-selections
echo "mysql-server-5.6 mysql-server/root_password password <PASSWORD>" | debconf-set-selections
apt-get -y -q install php5-fpm nginx php5 php5-json php5-gd php5-mysql php5-cli php5-xdebug mysql-server-5.6
rm /etc/nginx/sites-enabled/default
cp /vagrant/vagrant/files/mysql_default_charset.cnf /etc/mysql/conf.d/default_charset.cnf
cp /vagrant/vagrant/files/nginx_server.conf /etc/nginx/sites-available/default
ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default
sed -i "s/user www-data;/user vagrant;/" /etc/nginx/nginx.conf
sed -i "s/user = www-data/user = vagrant/" /etc/php5/fpm/pool.d/www.conf
sed -i "s/group = www-data/group = vagrant/" /etc/php5/fpm/pool.d/www.conf
service nginx restart
service php5-fpm restart<file_sep>project
=======
A Symfony project created on April 27, 2015, 6:38 pm.
|
50552ff1ecf81f6652aadadbf15b7516f478273d
|
[
"Markdown",
"Shell"
] | 3
|
Markdown
|
alsbury/symfony2nginx
|
6ad13c9178158075bcca052ba3c0d38d037a2318
|
51e6087cd527d66affe15f1b205e85b433221b38
|
refs/heads/master
|
<file_sep>using AntShares.SmartContract.Framework;
using AntShares.SmartContract.Framework.Services.AntShares;
using AntShares.SmartContract.Framework.Services.System;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace remotegen
{
class tcode : FunctionCode
{
public static int Main()
{
return 1;
}
}
}
<file_sep># antshares-code-plugin README
contract editor plugin for antshares blockchain
## Features
在Visual Studio Code中使用C#开发小蚁区块链的智能合约,并提供相关功能
## TODO
* 让c#编译器生成的dll自动被处理,生成avm代码(调用csc.exe然后convert.exe)
* 注册到测试链
* command调用合约
* command查询小蚁地址状态
* command类似小蚁区块浏览器的功能
* 调试功能
<file_sep>'use strict';
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "antshares-code-plugin" is now active!');
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
let disposableOfQueryAnsBalance = vscode.commands.registerCommand('extension.queryAnsBalance', () => {
// The code you place here will be executed every time your command is executed
// TODO
// Display a message box to the user
vscode.window.showInformationMessage('TODO: Hello World!');
});
let disposableOfRunAntsharesContract = vscode.commands.registerCommand('extension.runAnsContract', () => {
// The code you place here will be executed every time your command is executed
// TODO
// Display a message box to the user
vscode.window.showInformationMessage('TODO: Hello World, runAnsContract!');
});
let disposableOfCompileCsharp = vscode.commands.registerCommand('extension.compile_avm', () => {
// The code you place here will be executed every time your command is executed
const cp = require('child_process')
const process = require('process');
const state = arguments[0];
console.log(arguments, state); // TODO: cs filename
const extensionPath = state.extensionPath;
const workspacePath = vscode.workspace.rootPath;
process.chdir(extensionPath);
const docs = vscode.workspace.textDocuments;
var csharpDocs = docs.filter((f) => f.languageId === "csharp")
if(csharpDocs.length !== 1) {
vscode.window.showInformationMessage('error: ' + "工作文件夹中只能唯一选择一个C#源文件");
return;
}
const filename = csharpDocs[0].fileName;
const outFilename = filename + ".avm";
cp.exec(extensionPath + '/antshares/ascsc-testnet ' + filename + " " + outFilename, (err, stdout, stderr) => {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (err) {
vscode.window.showInformationMessage('error: ' + err);
return;
}
vscode.window.showInformationMessage('compile to avm successfully: ');
});
});
context.subscriptions.push(disposableOfQueryAnsBalance);
context.subscriptions.push(disposableOfCompileCsharp);
context.subscriptions.push(disposableOfRunAntsharesContract);
}
// this method is called when your extension is deactivated
export function deactivate() {
}
|
96e1b21475ebe4c08907fa2bc60a9180a7ebcb4d
|
[
"Markdown",
"C#",
"TypeScript"
] | 3
|
C#
|
zoowii/antshares-code-plugin
|
cbac68aaad4a293fd094548b1a4f6c2dac17f116
|
df486a89346dcb99ba5f964bc0d836e8b1cac77b
|
refs/heads/master
|
<file_sep>#include <math.h>
#include <stdio.h>
#include <cctype>
#include <cstdlib>
#include <string.h>
#define PI 3.14159265359
class CTime
{
public:
CTime(char* newTime);
CTime(){};
void setTime(char* newTime);
int getHours() { return _hours; };
int getMinutes() { return _minutes; };
private:
enum timeMode {time24, time12};
int _hours;
int _minutes;
timeMode _mode;
char* _time;
void parseTime();
void parseMinutes();
void parseHours();
void parseMode();
void setHours(int newHours);
void setMinutes(int newMinutes);
};
CTime::CTime(char* newTime)
{
_time = newTime;
parseTime();
}
void CTime::setTime(char* newTime)
{
_time = newTime;
parseTime();
}
void CTime::parseMode()
{ //TODO: будет выход за пределы массива
if ((_time[7] == 'A' || _time[7] == 'P') && _time[8] == 'M')
{
_mode = time12;
}
_mode = time24;
}
void CTime::parseHours()
{
if ( !isdigit(_time[0]) && !isdigit(_time[1]) )
{
//TODO: error
}
_hours = (_time[0] - '0') * 10 + ((_time[1] - '0'));
if ((_mode == time24 && _hours > 24 && _hours < 0) ||
(_mode == time12 && _hours > 12 && _hours < 0) )
{
//TODO: error
}
}
void CTime::parseMinutes()
{
if ( !isdigit(_time[3]) && !isdigit(_time[4]) )
{
//TODO: error
}
_minutes = (_time[3] - '0') * 10 + ((_time[4] - '0'));
if (_minutes > 60 && _minutes < 0)
{
//TODO: error
}
}
void CTime::parseTime()
{
parseMode();
parseHours();
parseMinutes();
//TODO: дописать
}
//
// Describes an angle
// Angle is saved in degrees
//
class CAngle
{
public:
enum AngleType {rad, deg, dms};
CAngle(){};
CAngle(double value, AngleType type);
void setAngle(double newAngle);
void setAngleType(AngleType type);
void setAngleType(char* angleTypeString);
void print(AngleType type);
void print();
private:
double _value;
AngleType _type;
};
CAngle::CAngle(double value, AngleType type)
{
setAngle(value);
setAngleType(type);
}
void CAngle::setAngle(double newAngle)
{
//TODO: check data
_value = fmod(newAngle, 360); //if so happened that we have an angle bigger than 360 deg
if (_value >= 180)
{
_value = 360 - _value; // we return the smaller angle
}
}
void CAngle::setAngleType(AngleType type)
{
_type = type;
}
void CAngle::setAngleType(char* angleTypeString)
{
if (strcmp(angleTypeString, "rad"))
{
setAngleType(CAngle::rad);
return;
}
if (strcmp(angleTypeString, "dms"))
{
setAngleType(CAngle::dms);
return;
}
if (strcmp(angleTypeString, "deg"))
{
setAngleType(CAngle::deg);
return;
}
//TODO: error
}
//
// Prints a string in the way, which is indicated in parameter type
// Input:
// type - in which unit of measure we want to print
// it can be: deg (degrees), rad (radians), dms (degrees, minutes, seconds)
//
void CAngle::print(AngleType type)
{
switch(type)
{
case rad:
{
double radians = (PI / 180) * _value; // 1rad = 180deg / pi
printf("%.4f\n", radians);
break;
}
case deg:
{
printf("%.0f\n", _value);
break;
}
case dms:
{
int degrees = int(_value);
int minutes = int((_value - int(_value)) * 60); // 60min in a degree
int seconds = int((_value - int(_value) - minutes) * 60);
printf("%3d.%d\'%d\"\n", degrees, minutes, seconds);
break;
}
default:
break;
}
}
void CAngle::print()
{
CAngle::print(_type);
}
//
// The class describes a clock
//
class CClock
{
public:
enum ClockType { quar, mech };
CClock(){};
~CClock(){};
void setTime(char* newTime);
void setHours(int hours);
void setMinutes(int minutes);
void setType(ClockType type);
void setType(char* typeString);
int getHours() { return _hours; };
int getMinutes() { return _minutes; };
ClockType getType() { return _type; };
void setAngleType(char* angleTypeString);
CAngle getAngle();
void calcAngle();
private:
CTime _time;
ClockType _type;
int _hours;
int _minutes;
CAngle _angle;
};
void CClock::setHours(int hours)
{
_hours = hours % 12;
}
void CClock::setTime(char* newTime)
{
_time.setTime(newTime);
}
void CClock::setMinutes(int minutes)
{
_minutes = minutes % 60;
}
void CClock::setType(ClockType type)
{
_type = type;
}
void CClock::setType(char* typeString)
{
if (!strcmp(typeString, "mech") )
{
setType(CClock::mech);
return;
}
if (!strcmp(typeString, "quar") )
{
setType(CClock::quar);
return;
}
//TODO: error
}
void CClock::calcAngle()
{
const double degreesPerHour = 360 / 12;
const double degreesPerMinute = 360 / 60;
double hourHandAngle = _hours * degreesPerHour;
if (_type == mech)
hourHandAngle += _minutes * degreesPerMinute;
double minuteHandAngle = _minutes * degreesPerMinute;
double degrees = fabs(hourHandAngle - minuteHandAngle);
_angle.setAngle(degrees);
}
CAngle CClock::getAngle()
{
return _angle;
}
void CClock::setAngleType(char* angleTypeString)
{
_angle.setAngleType(angleTypeString);
}
int main(int argc, char* argv[])
{
CClock clock;
clock.setTime(argv[1]); // установка времени
clock.setType(argv[3]); // установка типа часов
clock.setAngleType(argv[2]);
}
<file_sep>yandex_clock
============
a task that have to be done for yandex intership.
|
5856d40bb0189fbd6b9e39f1b6c6c8a20c68e2fb
|
[
"Markdown",
"C++"
] | 2
|
C++
|
simonuvarov/yandex_clock
|
14a82980473d9c5685bb6022c8a1f1f2a827455f
|
099370240585af6828298b78269f7942cecfff9a
|
refs/heads/main
|
<repo_name>nayana1809/nlp-project<file_sep>/filenlp.py
def review(sentence, word1,word2,word3,word4):
s = sentence.split(" ")
for i in s:
if (i == word1):
return True
elif (i==word2):
return True
elif (i==word3):
return True
elif (i==word4):
return True
return False
s = "the product was not usable"
word1 = "not"
word2="bad"
word3="didn't"
word4="un"
if (review(s, word1,word2,word3,word4)):
print("the customer had negative feed back")
else:
print("the costumer had positive feedback")
|
223bb2b219197792a93ca62aab4f37245aeec142
|
[
"Python"
] | 1
|
Python
|
nayana1809/nlp-project
|
82744a00486361df76b04aae9ca1c2c7fa007fe7
|
f642ee885fb24cf75e8546bc3d5e9620e0654b78
|
refs/heads/master
|
<repo_name>wieczorekmarcin/ffr-api<file_sep>/src/main/resources/application.properties
spring.jackson.serialization.INDENT_OUTPUT=true
spring.h2.console.enabled=true
spring.h2.console.settings.web-allow-others=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.servlet.multipart.enabled=true
spring.jackson.mapper.sort-properties-alphabetically=false
jwt.header=Authorization
jwt.secret=mySecret!@##@!
jwt.expiration=604800
jwt.route.authentication.path=/auth
jwt.route.authentication.refresh=/refresh
ftp.username=f1230_ffr
ftp.password=<PASSWORD>
ftp.server=ftp://s38.mydevil.net
ftp.baseURI=http://wieczorekmarcin.usermd.net/ffr
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=utf-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
<file_sep>/README.md
# Flat For Rent - Thesis - Spring Web API
## Technologies
- Java 8
- Spring Boot 2
- Spring Security (JSON Web Token - JWT)
- Maven
- H2 + H2 console
- Swagger UI
### Generating password hash for new users
I'm using [bcrypt](https://en.wikipedia.org/wiki/Bcrypt) to encode passwords.
#### Inspiration for JWT
https://www.toptal.com/java/rest-security-with-jwt-spring-security-and-java
<file_sep>/src/main/java/pl/cdv/ffr/service/AlertService.java
package pl.cdv.ffr.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import pl.cdv.ffr.model.Alert;
import pl.cdv.ffr.model.JwtUser;
import pl.cdv.ffr.model.Property;
import pl.cdv.ffr.repository.AlertRepository;
import pl.cdv.ffr.repository.PropertyRepository;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
@Service
public class AlertService extends BaseService {
@Autowired
AlertRepository alertRepository;
@Autowired
PropertyRepository propertyRepository;
@Autowired
private JwtUserDetailsService userService;
@Value("${jwt.header}")
private String tokenHeader;
public List<Alert> findAllPropertyAlerts(HttpServletRequest request, String property_ID) {
JwtUser user = userService.getUserInfo(request, tokenHeader);
List<Alert> alerts = new ArrayList<>();
if (isRentier(user)) {
user.getRentier().getProperties().forEach(p -> {
if (p.getId() == Long.parseLong(property_ID)) {
p.getAlerts().forEach(a -> {
if (a.isVisible()) {
alerts.add(a);
}
});
}
});
} else {
Property tenatProperty = user.getTenat().getProperty();
if (tenatProperty != null && tenatProperty.getId() == Long.parseLong(property_ID)) {
tenatProperty.getAlerts().forEach(a -> {
if (a.isVisible()) {
alerts.add(a);
}
});
}
}
return alerts;
}
public Alert findPropertyAlertById(HttpServletRequest request, String property_ID, String alert_id) {
JwtUser user = userService.getUserInfo(request, tokenHeader);
if (isRentier(user)) {
for (Property property : user.getRentier().getProperties()) {
if (property.getId() == Long.parseLong(property_ID)) {
for (Alert alert : property.getAlerts()) {
if (alert.getId() == Long.parseLong(alert_id) && alert.isVisible()) {
return alert;
}
}
}
}
} else {
if (user.getTenat().getProperty().getId() == Long.parseLong(property_ID)) {
for (Alert alert : user.getTenat().getProperty().getAlerts()) {
if (alert.getId() == Long.parseLong(alert_id) && alert.isVisible()) {
return alert;
}
}
}
}
throw new UsernameNotFoundException("User " + user.getEmail() + " has no property with id:" + property_ID + " or bill with id:" + alert_id);
}
public Alert createPropertyAlert(HttpServletRequest request, String property_ID, Alert alert) {
JwtUser user = userService.getUserInfo(request, tokenHeader);
alert.setCreatedDate(getCurrentDate());
alertRepository.save(alert);
Property property;
if (isRentier(user)) {
property = user.getRentier().getProperties().stream()
.filter(p -> p.getId() == Long.parseLong(property_ID))
.findFirst()
.get();
} else {
property = Stream.of(user.getTenat().getProperty())
.filter(p -> p.getId() == Long.parseLong(property_ID))
.findFirst()
.get();
}
List<Alert> alerts = property.getAlerts();
alerts.add(alert);
property.setAlerts(alerts);
propertyRepository.save(property);
return alert;
}
public Alert updatePropertyAlert(HttpServletRequest request, String property_ID, String alert_id, Alert newAlert) {
JwtUser user = userService.getUserInfo(request, tokenHeader);
Property property;
if (isRentier(user)) {
property = user.getRentier().getProperties().stream()
.filter(p -> p.getId() == Long.parseLong(property_ID))
.findFirst()
.get();
} else {
property = Stream.of(user.getTenat().getProperty())
.filter(p -> p.getId() == Long.parseLong(property_ID))
.findFirst()
.get();
}
return property.getAlerts().stream()
.filter(a -> a.getId() == Long.parseLong(alert_id))
.findFirst()
.map(alert -> {
copyNonNullProperties(newAlert, alert);
return alertRepository.save(alert);
})
.orElseGet(() -> {
newAlert.setId(Long.parseLong(alert_id));
return alertRepository.save(newAlert);
});
}
public void deletePropertyAlert(HttpServletRequest request, String property_ID, String alert_id) {
JwtUser user = userService.getUserInfo(request, tokenHeader);
Alert alert = null;
for (Property property : user.getRentier().getProperties()) {
if (property.getId() == Long.parseLong(property_ID)) {
for (Alert a : property.getAlerts()) {
if (a.getId() == Long.parseLong(alert_id)) {
alert = a;
}
}
}
}
if (alert != null) {
alertRepository.delete(alert);
}
}
}
<file_sep>/src/main/java/pl/cdv/ffr/repository/AuthorityRepository.java
package pl.cdv.ffr.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.cdv.ffr.model.Authority;
public interface AuthorityRepository extends JpaRepository<Authority, Long> {
}
<file_sep>/src/main/java/pl/cdv/ffr/model/PropertyStatus.java
package pl.cdv.ffr.model;
public enum PropertyStatus {
FOR_RENT, RENTED, ACTIVE, INACTIVE;
}<file_sep>/src/main/java/pl/cdv/ffr/controller/TenatController.java
package pl.cdv.ffr.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pl.cdv.ffr.model.Tenat;
import pl.cdv.ffr.service.TenatService;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
public class TenatController {
@Autowired
TenatService tenatService;
@RequestMapping(path = "/tenats", method = RequestMethod.GET)
public List<Tenat> getAllTenats() {
return tenatService.findAllTenats();
}
@RequestMapping(path = "/tenats/{id}", method = RequestMethod.GET)
public Tenat getTenat(@PathVariable("id") String id) {
return tenatService.findTenatById(id);
}
@RequestMapping(path = "/tenats", method = RequestMethod.POST)
public Tenat createTenat(HttpServletRequest request, @RequestBody Tenat property) {
return tenatService.createTenat(request, property);
}
@RequestMapping(path = "/tenats/{id}", method = RequestMethod.PUT)
public Tenat updateTenat(@RequestBody Tenat property, @PathVariable("id") String id) {
return tenatService.updateTenat(property, id);
}
@RequestMapping(path = "/tenats/{id}", method = RequestMethod.DELETE)
public void deleteTenat(@PathVariable("id") String id) {
tenatService.deleteTenat(id);
}
}
<file_sep>/src/main/java/pl/cdv/ffr/controller/UserController.java
package pl.cdv.ffr.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import pl.cdv.ffr.model.JwtUser;
import pl.cdv.ffr.model.User;
import pl.cdv.ffr.model.UserType;
import pl.cdv.ffr.service.JwtUserDetailsService;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
public class UserController {
@Value("${jwt.header}")
private String tokenHeader;
@Autowired
private JwtUserDetailsService userService;
@RequestMapping(path = "/userInfo", method = RequestMethod.GET)
public JwtUser getUserInfo(HttpServletRequest request) {
JwtUser user = userService.getUserInfo(request, tokenHeader);
return user;
}
@RequestMapping(path = "/users", method = RequestMethod.GET)
public List<JwtUser> getAllUsersWithParams(@RequestParam(value = "status", required = false) UserType userType) {
if (userType != null) {
return userService.findUserByUserType(userType);
} else {
return userService.findAllUsers();
}
}
@RequestMapping(path = "/users/{id}", method = RequestMethod.GET)
public JwtUser getUserById(@PathVariable("id") String id) {
return userService.findUserById(id);
}
@RequestMapping(path = "/users", method = RequestMethod.POST)
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
@RequestMapping(path = "/users/{id}", method = RequestMethod.PUT)
public User updateUser(@RequestBody User user, @PathVariable("id") String id) {
return userService.updateUser(user, id);
}
@RequestMapping(path = "/users/{id}", method = RequestMethod.DELETE)
public void deleteUser(@PathVariable("id") String id) {
userService.deleteUser(id);
}
}
<file_sep>/src/main/java/pl/cdv/ffr/model/Rentier.java
package pl.cdv.ffr.model;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import java.util.List;
@Entity
@DynamicUpdate
public class Rentier extends BaseEntity {
@Column(name = "FIRSTNAME", length = 50)
private String firstName;
@Column(name = "LASTNAME", length = 50)
private String lastName;
private String pesel;
private String idNumber;
private String email;
private String phoneNumber;
@OneToMany(cascade=CascadeType.MERGE)
@JoinTable(
name = "RENTIER_PROPERTY",
joinColumns = {@JoinColumn(name = "RENTIER_ID", referencedColumnName = "ID")},
inverseJoinColumns = {@JoinColumn(name = "PROPERTY_ID", referencedColumnName = "ID")})
private List<Property> properties;
@OneToMany(cascade=CascadeType.MERGE)
@JoinTable(
name = "RENTIER_TENAT",
joinColumns = {@JoinColumn(name = "RENTIER_ID", referencedColumnName = "ID")},
inverseJoinColumns = {@JoinColumn(name = "TENAT_ID", referencedColumnName = "ID")})
private List<Tenat> tenats;
public Rentier() {
}
public Rentier(String firstName, String lastName, String pesel, String idNumber, String email, String phoneNumber, List<Property> properties, List<Tenat> tenats) {
this.firstName = firstName;
this.lastName = lastName;
this.pesel = pesel;
this.idNumber = idNumber;
this.email = email;
this.phoneNumber = phoneNumber;
this.properties = properties;
this.tenats = tenats;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPesel() {
return pesel;
}
public void setPesel(String pesel) {
this.pesel = pesel;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public List<Property> getProperties() {
return properties;
}
public void setProperties(List<Property> properties) {
this.properties = properties;
}
public List<Tenat> getTenats() {
return tenats;
}
public void setTenats(List<Tenat> tenats) {
this.tenats = tenats;
}
}
<file_sep>/src/main/java/pl/cdv/ffr/service/BaseService.java
package pl.cdv.ffr.service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pl.cdv.ffr.model.BaseEntity;
import pl.cdv.ffr.model.JwtUser;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class BaseService {
public void copyNonNullProperties(Object src, Object target) {
BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}
public String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
public boolean isRentier(JwtUser user) {
if (user.getRentier() != null && user.getRentier().getId() != null) {
return true;
} else {
return false;
}
}
public String getCurrentBaseUrl() {
ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest req = sra.getRequest();
return req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath();
}
public List<? extends BaseEntity> filterByVisible(List<? extends BaseEntity> enities) {
return enities.stream()
.filter(e -> e.isVisible() == true)
.collect(Collectors.toList());
}
public String getCurrentDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
return dateFormat.format(date);
}
}
<file_sep>/src/main/java/pl/cdv/ffr/model/BaseEntity.java
package pl.cdv.ffr.model;
import javax.persistence.*;
@MappedSuperclass
public class BaseEntity {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private boolean visible = true;
public BaseEntity() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
}
<file_sep>/src/main/java/pl/cdv/ffr/controller/PropertyController.java
package pl.cdv.ffr.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import pl.cdv.ffr.model.*;
import pl.cdv.ffr.service.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
public class PropertyController {
@Autowired
PropertyService propertyService;
@Autowired
BillService billService;
@Autowired
TenatService tenatService;
@Autowired
AlertService alertService;
@Autowired
InvoiceService invoiceService;
@RequestMapping(path = "/properties", method = RequestMethod.GET)
public List<Property> getAllProperties(HttpServletRequest request, @RequestParam(value = "status", required = false) PropertyStatus propertyStatus) {
if (propertyStatus != null) {
return propertyService.findPropertysByStatus(request, propertyStatus);
} else {
return propertyService.findAllProperties(request);
}
}
@RequestMapping(path = "/properties", method = RequestMethod.POST)
public Property createProperty(HttpServletRequest request, @RequestBody Property property) {
return propertyService.createProperty(request, property);
}
@RequestMapping(path = "/properties/{property_ID}", method = RequestMethod.GET)
public Property getPropertyById(HttpServletRequest request, @PathVariable("property_ID") String property_ID) {
return propertyService.findPropertyById(request, property_ID);
}
@RequestMapping(path = "/properties/{property_ID}", method = RequestMethod.PUT)
public Property updateProperty(HttpServletRequest request, @RequestBody Property property, @PathVariable("property_ID") String property_ID) {
return propertyService.updateProperty(request, property, property_ID);
}
@RequestMapping(path = "/properties/{property_ID}", method = RequestMethod.DELETE)
public void deleteProperty(HttpServletRequest request, @PathVariable("property_ID") String property_ID) {
propertyService.deleteProperty(request, property_ID);
}
@RequestMapping(path = "/properties/{property_ID}/alerts", method = RequestMethod.GET)
public List<Alert> getAllPropertyAlerts(HttpServletRequest request, @PathVariable("property_ID") String property_ID) {
return alertService.findAllPropertyAlerts(request, property_ID);
}
@RequestMapping(path = "/properties/{property_ID}/alerts", method = RequestMethod.POST)
public Alert createPropertyAlert(HttpServletRequest request, @PathVariable("property_ID") String property_ID, @RequestBody Alert alert) {
return alertService.createPropertyAlert(request, property_ID, alert);
}
@RequestMapping(path = "/properties/{property_ID}/alerts/{alert_ID}", method = RequestMethod.GET)
public Alert getPropertyAlertById(HttpServletRequest request, @PathVariable("property_ID") String property_ID, @PathVariable("alert_ID") String alert_ID) {
return alertService.findPropertyAlertById(request, property_ID, alert_ID);
}
@RequestMapping(path = "/properties/{property_ID}/alerts/{alert_ID}", method = RequestMethod.PUT)
public Alert updatePropertyAlert(HttpServletRequest request, @PathVariable("property_ID") String property_ID, @PathVariable("alert_ID") String bill_ID, @RequestBody Alert alert) {
return alertService.updatePropertyAlert(request, property_ID, bill_ID, alert);
}
@RequestMapping(path = "/properties/{property_ID}/alerts/{alert_ID}", method = RequestMethod.DELETE)
public void deletePropertyAlert(HttpServletRequest request, @PathVariable("property_ID") String property_ID, @PathVariable("alert_ID") String alert_ID) {
alertService.deletePropertyAlert(request, property_ID, alert_ID);
}
@RequestMapping(path = "/properties/{property_ID}/bills", method = RequestMethod.GET)
public List<Bill> getAllPropertyBills(HttpServletRequest request, @PathVariable("property_ID") String property_ID) {
return billService.findAllPropertyBills(request, property_ID);
}
@RequestMapping(path = "/properties/{property_ID}/bills", method = RequestMethod.POST)
public Bill createPropertyBill(HttpServletRequest request, @PathVariable("property_ID") String property_ID, @RequestBody Bill bill) {
return billService.createPropertyBill(request, property_ID, bill);
}
@RequestMapping(path = "/properties/{property_ID}/bills/{bill_ID}", method = RequestMethod.GET)
public Bill getPropertyBillById(HttpServletRequest request, @PathVariable("property_ID") String property_ID, @PathVariable("bill_ID") String bill_ID) {
return billService.findPropertyBillById(request, property_ID, bill_ID);
}
@RequestMapping(path = "/properties/{property_ID}/bills/{bill_ID}", method = RequestMethod.PUT)
public Bill updatePropertyBill(HttpServletRequest request, @PathVariable("property_ID") String property_ID, @PathVariable("bill_ID") String bill_ID, @RequestBody Bill bill) {
return billService.updatePropertyBill(request, property_ID, bill_ID, bill);
}
@RequestMapping(path = "/properties/{property_ID}/bills/{bill_ID}", method = RequestMethod.DELETE)
public void deletePropertyBill(HttpServletRequest request, @PathVariable("property_ID") String property_ID, @PathVariable("bill_ID") String bill_ID) {
billService.deletePropertyBill(request, property_ID, bill_ID);
}
@RequestMapping(path = "/properties/{property_ID}/bills/calculate", method = RequestMethod.GET)
public CalculateResponse calculate(HttpServletRequest request, @PathVariable("property_ID") String property_ID, @RequestParam(value = "status", required = true) String status, @RequestParam(value = "billType", required = true) BillType billType, @RequestParam(value = "rate", required = true) String rate) {
return billService.calculate(request, property_ID, billType, status, rate);
}
@RequestMapping(value = "/properties/{property_ID}/bills/{bill_ID}/invoice", method = RequestMethod.GET, produces = MediaType.APPLICATION_PDF_VALUE)
public String generateInvoice(HttpServletRequest request, @PathVariable("property_ID") String property_ID, @PathVariable("bill_ID") String bill_ID) throws IOException {
return invoiceService.generateInvoice(request, property_ID, bill_ID);
}
@RequestMapping(path = "/properties/{property_ID}/invoices", method = RequestMethod.GET)
public List<Invoice> getAllPropertyInvoices(HttpServletRequest request, @PathVariable("property_ID") String property_ID) {
return invoiceService.findAllPropertyInvoices(request, property_ID);
}
@RequestMapping(path = "/properties/{property_ID}/invoices", method = RequestMethod.POST)
public Invoice createPropertyInvoices(HttpServletRequest request, @PathVariable("property_ID") String property_ID, @RequestBody Invoice invoice) {
return invoiceService.createPropertyInvoice(request, property_ID, invoice);
}
@RequestMapping(path = "/properties/{property_ID}/invoices/{invoice_ID}", method = RequestMethod.GET)
public Invoice getPropertyInvoiceById(HttpServletRequest request, @PathVariable("property_ID") String property_ID, @PathVariable("invoice_ID") String invoice_ID) {
return invoiceService.findPropertyInvoiceById(request, property_ID, invoice_ID);
}
@RequestMapping(path = "/properties/{property_ID}/invoices/{invoice_ID}", method = RequestMethod.PUT)
public Invoice updatePropertyInvoice(HttpServletRequest request, @PathVariable("property_ID") String property_ID, @PathVariable("invoice_ID") String invoice_ID, @RequestBody Invoice invoice) {
return invoiceService.updatePropertyInvoice(request, property_ID, invoice_ID, invoice);
}
@RequestMapping(path = "/properties/{property_ID}/invoices/{invoice_ID}", method = RequestMethod.DELETE)
public void deletePropertyInvoices(HttpServletRequest request, @PathVariable("property_ID") String property_ID, @PathVariable("invoice_ID") String invoice_ID) {
invoiceService.deletePropertyInvoice(request, property_ID, invoice_ID);
}
}<file_sep>/src/main/java/pl/cdv/ffr/model/Tenat.java
package pl.cdv.ffr.model;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
@Entity
@DynamicUpdate
public class Tenat extends BaseEntity {
@Column(name = "FIRSTNAME", length = 50)
private String firstName;
@Column(name = "LASTNAME", length = 50)
private String lastName;
private String pesel;
private String idNumber;
private String email;
private String phoneNumber;
@OneToOne(fetch = FetchType.EAGER)
@JoinTable(
name = "TENAT_PROPERTY",
joinColumns = {@JoinColumn(name = "TENAT_ID", referencedColumnName = "ID")},
inverseJoinColumns = {@JoinColumn(name = "PROPERTY_ID", referencedColumnName = "ID")})
private Property property;
public Tenat() {
}
public Tenat(String firstName, String lastName, String pesel, String idNumber, String email, String phoneNumber, Property property) {
this.firstName = firstName;
this.lastName = lastName;
this.pesel = pesel;
this.idNumber = idNumber;
this.email = email;
this.phoneNumber = phoneNumber;
this.property = property;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPesel() {
return pesel;
}
public void setPesel(String pesel) {
this.pesel = pesel;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Property getProperty() {
return property;
}
public void setProperty(Property property) {
this.property = property;
}
}
<file_sep>/src/main/java/pl/cdv/ffr/service/TenatService.java
package pl.cdv.ffr.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import pl.cdv.ffr.model.*;
import pl.cdv.ffr.repository.AuthorityRepository;
import pl.cdv.ffr.repository.PropertyRepository;
import pl.cdv.ffr.repository.TenatRepository;
import pl.cdv.ffr.repository.UserRepository;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
public class TenatService extends BaseService {
@Autowired
TenatRepository tenatRepository;
@Autowired
AuthorityRepository authorityRepository;
@Autowired
UserRepository userRepository;
@Autowired
PropertyRepository propertyRepository;
@Autowired
PropertyService propertyService;
public List<Tenat> findAllTenats() {
return (List<Tenat>) filterByVisible(tenatRepository.findAll());
}
public Tenat findTenatById(String id) {
Optional<Tenat> byId = tenatRepository.findById(Long.parseLong(id));
return byId.get();
}
public Tenat createTenat(HttpServletRequest request, Tenat tenat) {
User user = new User();
user.setFirstname(tenat.getFirstName());
user.setLastname(tenat.getLastName());
user.setEmail(tenat.getEmail());
user.setEnabled(true);
user.setUsername(user.getEmail());
user.setLastPasswordResetDate(new Date());
List<Authority> authorities = new ArrayList<>();
authorities.add(authorityRepository.findById(Long.parseLong("1")).get());
user.setAuthorities(authorities);
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(tenat.getPesel());
user.setPassword(hashedPassword);
user.setUserType(UserType.TENAT);
user.setTenat(tenat);
userRepository.save(user);
Tenat toReturn = tenatRepository.save(tenat);
changePropertyStatus(request, toReturn);
return toReturn;
}
public Tenat updateTenat(Tenat newTenat, String id) {
return tenatRepository.findById(Long.parseLong(id))
.map(tenat -> {
copyNonNullProperties(newTenat, tenat);
//changePropertyStatus(newTenat);
return tenatRepository.save(tenat);
})
.orElseGet(() -> {
newTenat.setId(Long.parseLong(id));
return tenatRepository.save(newTenat);
});
}
public void deleteTenat(String id) {
tenatRepository.deleteById(Long.parseLong(id));
}
private void changePropertyStatus(HttpServletRequest request,Tenat tenat) {
Property property = tenat.getProperty();
if (property == null) {
return;
} else {
property.setPropertyStatus(PropertyStatus.RENTED);
propertyService.updateProperty(request, property, property.getId().toString());
}
}
}
<file_sep>/src/main/java/pl/cdv/ffr/model/Trash.java
package pl.cdv.ffr.model;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
@Entity
@DynamicUpdate
public class Trash extends BaseMedia {
private String unit = "os.";
public Trash() {
}
public Trash(String status, String rate, String used, String date, String amount, String unit) {
super(status, rate, used, date, amount, unit);
}
@Override
public String getUnit() {
return unit;
}
@Override
public void setUnit(String unit) {
this.unit = unit;
}
}
<file_sep>/src/main/java/pl/cdv/ffr/model/BillType.java
package pl.cdv.ffr.model;
public enum BillType {
COLD_WATER, COMMON_PART, ELECTRICITY, HEATING, HOT_WATER, REPAIR_FOUND, TRASH;
private String billType;
public String getBillType() {
return billType;
}
public void setBillType(String billType) {
this.billType = billType;
}
}
<file_sep>/src/main/java/pl/cdv/ffr/utils/ftp/FTPHelper.java
package pl.cdv.ffr.utils.ftp;
import org.apache.commons.vfs2.*;
import org.apache.commons.vfs2.auth.StaticUserAuthenticator;
import org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder;
import org.apache.commons.vfs2.provider.ftp.FtpFileSystemConfigBuilder;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
@Component
public class FTPHelper {
@Autowired
FTPProperties ftpProperties;
public InputStream getDecodedInputStream(String base64, String extension) throws IOException {
byte[] file = Base64.getDecoder().decode(base64);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ImageIO.write(image, extension, buffer);
return new ByteArrayInputStream(buffer.toByteArray());
}
public String createAndSaveDecodedFile(InputStream in, String extension, String prefix, String directoryName) throws IOException {
org.apache.commons.vfs2.FileObject root = getBasicVFSPathPassiveIfNeeded(ftpProperties.getServer(), ftpProperties.getUsername(), ftpProperties.getPassword());
String fileName = getFileName("." + extension, prefix);
String fullFilePath = "/" + directoryName + "/" + fileName;
org.apache.commons.vfs2.FileObject fileObject = root.resolveFile(fullFilePath);
fileObject.createFile();
OutputStream out = fileObject.getContent().getOutputStream();
try {
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
return ftpProperties.getBaseURI() + fullFilePath;
}
public String getFileName(String userFileName, String prefix) {
String extension = "";
int i = userFileName.lastIndexOf('.');
if (i >= 0) {
extension = userFileName.substring(i + 1);
}
return prefix + "_" + new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()) + "." + extension;
}
public FileObject getBasicVFSPathPassiveIfNeeded(String connectionPath, String username, String password) throws FileSystemException {
FileSystemOptions opts = createBasicOpts(username, password);
if (connectionPath.startsWith("ftp://")) {
FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
}
FileSystemManager fsManager = VFS.getManager();
return fsManager.resolveFile(connectionPath, opts);
}
public FileSystemOptions createBasicOpts(String username, String password) throws FileSystemException {
FileSystemOptions opts = new FileSystemOptions();
if (username != null && password != null) {
StaticUserAuthenticator auth = new StaticUserAuthenticator(null, username, password);
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
}
return opts;
}
}
<file_sep>/src/main/java/pl/cdv/ffr/repository/PropertyRepository.java
package pl.cdv.ffr.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.cdv.ffr.model.Property;
import pl.cdv.ffr.model.PropertyStatus;
import java.util.List;
@Repository
public interface PropertyRepository extends JpaRepository<Property, Long> {
List<Property> findByPropertyStatus(PropertyStatus propertyStatusStatus);
}
<file_sep>/src/main/java/pl/cdv/ffr/model/CalculateResponse.java
package pl.cdv.ffr.model;
public class CalculateResponse {
private String amount;
private String used;
private String rate;
public CalculateResponse() {
}
public CalculateResponse(String amount, String used, String rate) {
this.amount = amount;
this.used = used;
this.rate = rate;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getUsed() {
return used;
}
public void setUsed(String used) {
this.used = used;
}
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
}
|
9837da64c6dcf654a1ba041f4616a20ffee4dcdd
|
[
"Markdown",
"Java",
"INI"
] | 18
|
INI
|
wieczorekmarcin/ffr-api
|
3a9af538c5d981e05ade6611de82617e9c909db5
|
16c6ca32973b15a0da161002cee54e2b08047573
|
refs/heads/master
|
<repo_name>AimanAnizan56/YeppelGadget<file_sep>/admin/content/table-user.php
<?php
session_start();
require_once("../../database/config.php");
$db = Database::getInstance();
?>
<div class="card-panel z-depth-2" style="margin-bottom: 3rem;">
<table>
<thead>
<tr>
<th>User Id</th>
<th>Username</th>
<th>Name</th>
<th>User Role</th>
<th>Created At</th>
<th>Total Purchased</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$users = $db -> query("SELECT user.id, user.username, user.name, user.created_at, role.type as role_type FROM user INNER JOIN role ON user.role_id = role.id") or die("Query Error: ".$db -> error);
foreach($users as $user): ?>
<tr>
<td> <?php echo $user['id']; ?> </td>
<td>
<?php
if($user['id'] == $_SESSION['id'])
echo "<b class='light-blue-text text-darken-1'>".$user['username']."</b>";
else
echo $user['username'];
?>
</td>
<td> <?php echo $user['name']; ?> </td>
<td> <?php echo ucwords($user['role_type']); ?> </td>
<td> <?php echo date("d F Y", strtotime($user['created_at'])); ?> </td>
<td>
<?php
if($user['role_type'] != 'admin'){
$total_purchased = $db -> query("select sum(total) as total from payment inner join orders on orders.id = payment.orders_id where orders.user_id = '".$user['id']."'");
if($total_purchased -> num_rows > 0){
echo "RM ".number_format($total_purchased -> fetch_assoc()['total']);
}else {
echo "RM 0";
}
}else {
echo "------------";
}
?>
</td>
<td>
<?php if($user['role_type'] != 'admin'): ?>
<a href="" onclick="event.preventDefault();confirmbox_deleteUser(<?php echo $user['id']; ?>)" class="transparent"><i class="material-icons red-text">delete</i></a>
<?php endif; ?>
</td>
</tr>
<?php endforeach;
?>
</tbody>
</table>
</div><file_sep>/index.php
<?php
session_start();
// database class
require_once('database/config.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home | Yeppel</title>
<link rel="shortcut icon" href="image/favicon2.png" type="image/x-icon">
<!-- Content Delivery Network - CSS -->
<?php include("component/cdn-css.php"); ?>
<!-- Customize CSS -->
<link rel="stylesheet" href="css/style.css">
</head>
<body class="grey lighten-3">
<!-- Navigation bar -->
<?php include("component/navigation.php"); ?>
<!-- Carousel - Slide -->
<div class="carousel carousel-slider center">
<div class="carousel-fixed-item center">
<a href="product.php" class="btn waves-effect light-blue darken-1 hoverable btn-buynow">BUY NOW</a>
</div>
<div class="carousel-item">
<img class="carousel-item-img" src="image/financing-products-og-202006.jpg" alt="Image 1">
</div>
<div class="carousel-item">
<img src="image/iphone.jpg" alt="Image 2">
</div>
<div class="carousel-item">
<img src="image/apple-pay-apple-watch-16-9.jpeg" alt="Image 3">
</div>
</div>
<div class="row container">
<div class="col s12 center-align">
<h3 class="bold">BROWSE BY CATEGORY</h3>
</div>
<?php
// get instance of mysql object
$db = Database::getInstance();
$category = $db -> query("SELECT * FROM category"); // retrieved catergory from database
// store associative array into a variable
while($data = $category -> fetch_assoc()):
?>
<div class="col s12 m6 l4">
<a href="product.php?category=<?php echo $data['name'] ?>">
<div class="card hoverable">
<div class="card-image blue">
<img class="category-img" src="data:image/jpeg;base64,<?php echo base64_encode($data['image']); ?>"> <!-- Base64 -- encode binary blob into base64 to display image -->
</div>
<div class="card-content center-align">
<h5><?php echo strtoupper($data['name']); ?></h5>
</div>
</div>
</a>
</div>
<?php endwhile; ?>
</div>
<!-- Content Delivery Network - JS -->
<?php include("component/cdn-js.php"); ?>
<!-- Customize Javascript -->
<script src="js/main.js"></script>
<script src="js/carousel-with-slider.js"></script>
<script>
$(()=>{
$('#home-page').addClass("active");
})
</script>
</body>
</html><file_sep>/js/carousel-normal.js
$(() => {
// add carousel method from jquery
$(".carousel").carousel({
fullWidth: false
}, setTimeout(autoSlide, 4500));
function autoSlide(){
$('.carousel').carousel('next');
setTimeout(autoSlide,4500);
}
})<file_sep>/user/password-updated.php
<?php
if(isset($_POST['confirm'])):
// update success
if(isset($updated) and $updated):
$updated = false;
unset($_POST);
?>
<!-- Modal popup -->
<style>
.modal{
width: 20vw!important;
padding: 0 10px;
}
</style>
<div id="success" class="modal">
<div class="modal-content center-align">
<i class="material-icons tick green-text">check_circle</i>
</div>
<div class="modal-footer text-center">
Password Updated
</div>
</div>
<script>
$(()=>{
/* Set transition duration in out popup */
$("#success").modal({
inDuration: 500,
outDuration: 500,
endingTop: "20%"
});
/* Open popup */
$("#success").modal("open");
/* Close popup after 2 second */
setTimeout(()=>{
$("#success").modal("close");
},2000)
})
</script>
<?php
endif;
// update failed
if(isset($error) and $error):
$error = false;
unset($_POST);
?>
<style>
.modal{
width: 20vw!important;
padding: 0 10px;
}
</style>
<!-- Modal popup -->
<div id="error" class="modal">
<div class="modal-content center-align">
<i class="material-icons tick red-text">error</i>
</div>
<div class="modal-footer text-center">
Password False
</div>
</div>
<script>
$(()=>{
/* Set transition duration in out popup */
$("#error").modal({
inDuration: 500,
outDuration: 500,
endingTop: "20%"
});
/* Open popup */
$("#error").modal("open");
/* Close popup after 2 second */
setTimeout(()=>{
$("#error").modal("close");
},2000)
})
</script>
<?php
endif;
endif;
?><file_sep>/user/remove-item.php
<?php
// FOR AJAX USE
if(isset($_POST['item_id'])){
// get instance of mysqli
require_once('../database/config.php');
$db = Database::getInstance();
// escape string
$item_id = $db -> real_escape_string($_POST['item_id']);
// query -- get quantity by item id
$result_1 = $db -> query("SELECT product.price as product_price, item.quantity as quantity FROM item INNER JOIN product ON product.id = item.product_id WHERE item.id = '$item_id'") or die("'query 1 failed");
// check if number of rows retrieved more than 1 and fetch associative array, store in variable
if($result_1 -> num_rows > 0 and $data_1 = $result_1 -> fetch_assoc()):
// if item quantity is one, than delete the whole item
if($data_1['quantity'] == 1):
$db -> query("DELETE FROM item WHERE id=$item_id") or die("could not delete item");
else:
// else update current cart -- remove one from existing quantity
$new_quantity = $db -> real_escape_string($data_1['quantity'] - 1);
$new_item_price = $db -> real_escape_string($data_1['product_price'] * $new_quantity);
$db -> query("UPDATE item SET quantity = '$new_quantity', price = '$new_item_price' WHERE id = '$item_id'") or die("query 2 failed");
endif;
else:
// error output if the item id did not exist
echo "item id not exist -- could not delete";
die();
endif;
}
?><file_sep>/create-acc-page.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Account | Yeppel</title>
<link rel="shortcut icon" href="image/favicon2.png" type="image/x-icon">
<!-- Content Delivery Network -->
<?php include("component/cdn-css.php"); ?>
<!-- Customize CSS -->
<link rel="stylesheet" href="css/style.css">
</head>
<body class="grey lighten-3">
<div class="container">
<div class="" style="margin-top:3rem"></div>
<div class="card-panel">
<div class="row">
<div class="col l6 m6 hide-on-med-and-down">
<img src="image/login-img.jpg" alt="" class="responsive-img fix-img hide-on-small-only">
</div>
<div class="col l6 m12 s12">
<h3 class="brand-heading center-align">Create Account</h3>
<div style="margin-top: 1rem;"></div>
<form id="form" action="database/create_acc.php" method="post">
<div class="input-field">
<i class="material-icons prefix">person</i>
<input type="text" name="name" id="name" class="validate" required>
<label for="name">Name</label>
</div>
<div class="input-field">
<i class="material-icons prefix">fingerprint</i>
<input type="text" name="username" id="username" class="validate" required>
<label for="username">Username</label>
</div>
<div class="input-field">
<i class="material-icons prefix">home</i>
<input type="text" name="address" id="address" class="validate" required>
<label for="address">Address</label>
</div>
<div class="input-field">
<i class="material-icons prefix">lock</i>
<input type="password" name="password" id="password" class="validate" required>
<label for="password">Password</label>
</div>
<label class="input-field" style="margin-left: 3rem; display: block">
<input type="checkbox" name="agreement" id="agreement" required>
<span>I agree with term and conditions</span>
</label>
<button type="button" id="create-acc" disabled style="width: 100%; margin-bottom: 1rem; margin-top: 1rem" class="waves-effect waves-light btn light-blue darken-1">SIGN UP</button>
<a href="index.php" style="width: 100%; margin-bottom: 1rem" class="waves-effect waves-light btn grey lighten-5 black-text">CANCEL</a>
<a href="login-page.php">Login account</a>
</form>
</div>
</div>
</div>
</div>
<div class="modal" id="confirmation-box" style="width: 25rem">
<div class="modal-content">
<h4 class="center-align" style="margin-top: 1rem;">Create account?</h4>
<div class="right" style="padding: 1rem 0;">
<button type="button" id="confirm" class="btn waves-effect waves-light light-blue darken-1" href="">Create</button>
<button type="button" id="confirmation-close" class="btn waves-effect waves-light white black-text" href="">Cancel</button>
</div>
</div>
</div>
<!-- Content Delivery Network - JS -->
<?php include("component/cdn-js.php"); ?>
<!-- Customize Javascript -->
<script src="js/main.js"></script>
<script>
$(()=>{
$("#create-acc").click(()=>{
// check if there is empty field of input
if($("#name").val() == ""){
$("#name").focus();
return;
}
if($("#username").val() == ""){
$("#username").focus();
return;
}
if($("#address").val() == ""){
$("#address").focus();
return;
}
if($("#password").val() == ""){
$("#password").focus();
return;
}
// open confirmation modal -- get confirmation from user
$("#confirmation-box").modal("open");
})
// close confirmation modal -- if user clicked button no
$("#confirmation-close").click(()=>{
$("#confirmation-box").modal("close");
});
// add event for confirm button clicked -- submit form to another file.
$("#confirm").click(()=>{
$("#form").submit();
});
})
</script>
</body>
</html><file_sep>/README.md
# Yeppel Gadget :desktop_computer:
:scroll:Step to use:-
1. Create database name `yeppel gadget`.
2. Import `yeppel_gadget.sql` into `yeppel gadget`.
3. Start your local server and point to this file.
4. Your local server will automatically execute `index.php`.
:warning:This is my final year project and I develop it alone. Since I am student, it may have some disfunctionality. <br>
:warning:This web-based ecommerce did not responsive enough due to time limit.
<file_sep>/user/change-profile.php
<?php
$updated = false;
// check -- button save clicked
if(isset($_POST['save'])){
if($_SESSION['role'] == 'admin'){
require_once('../database/config.php');
}else {
require_once('database/config.php');
}
// get instance of mysql
$db = Database::getInstance();
/* Escape string -- prevent sql injection */
$name = $db -> real_escape_string($_POST['name']);
$address = $db -> real_escape_string($_POST['address']);
$username = $db -> real_escape_string($_SESSION['username']);
/* SQL update query */
if($db -> query("UPDATE user set name='$name',address='$address' where username='$username'")){
if($db->affected_rows===1){
$updated = true;
}
}
}
?><file_sep>/login-page.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login | Yeppel</title>
<link rel="shortcut icon" href="image/favicon2.png" type="image/x-icon">
<!-- Content Delivery Network -->
<?php include("component/cdn-css.php"); ?>
<!-- Customize CSS -->
<link rel="stylesheet" href="css/style.css">
</head>
<body class="grey lighten-3">
<div class="container">
<div class="" style="margin-top:3rem"></div>
<div class="card-panel">
<div class="row">
<div class="col l6 hide-on-med-and-down">
<img src="image/login-img.jpg" alt="" class="responsive-img hide-on-small-only">
</div>
<div class="col l6 m12 s12">
<h3 class="brand-heading center-align">SIGN IN</h3>
<div style="margin-top: 4rem;"></div>
<form action="database/login-auth.php" method="post">
<div class="input-field">
<i class="material-icons prefix">fingerprint</i>
<input type="text" name="username" id="username" class="validate" value="<?php if(isset($_COOKIE['username'])){ echo $_COOKIE['username']; } else echo "" ?>" required>
<label for="username">Username</label>
</div>
<div class="input-field">
<i id="password-icon" class="material-icons prefix">lock</i>
<input type="password" name="password" id="password" class="validate" value="<?php if(isset($_COOKIE['password'])){ echo $_COOKIE['password']; } ?>" required>
<label for="password">Password</label>
</div>
<label style="margin-left: 3rem; display: block">
<input type="checkbox" name="remember" id="remember">
<span>Remember me</span>
</label>
<button type="submit" style="width: 100%; margin-bottom: 1rem; margin-top: 1rem" class="waves-effect waves-light btn light-blue darken-1">LOGIN</button>
<a href="index.php" style="width: 100%; margin-bottom: 1rem" class="waves-effect waves-light btn grey lighten-5 black-text">CANCEL</a>
<a href="create-acc-page.php">Create account</a>
</form>
</div>
</div>
</div>
</div>
<!-- Content Delivery Network - JS -->
<?php include("component/cdn-js.php"); ?>
<!-- Customize Javascript -->
<script src="js/main.js"></script>
</body>
</html><file_sep>/admin/content/add-product-db.php
<?php
// get instance of mysqli
require_once("../../database/config.php");
$db = Database::getInstance();
// escape string
$product_name = $db -> real_escape_string($_POST['product_name']);
$product_price = $db -> real_escape_string($_POST['product_price']);
$product_description = $db -> real_escape_string($_POST['product_description']);
$product_category = $db -> real_escape_string($_POST['product_category']);
// query -- insert product details
$db -> query("INSERT INTO product VALUES ('','$product_name','$product_price','$product_description','$product_category','1')") or die ("Query Error: ".$db -> error);
if($db -> affected_rows === 1) {
// name, type, tmp_name, error, size
$product_id = $db -> query("SELECT last_insert_id() as last") -> fetch_assoc()['last'] or die ("Query Error: ".$db -> error);
$stmt = $db -> prepare("INSERT INTO image VALUES (?,?,?,?,?,?)") or die("Could not prepare sql");
$stmt -> bind_param("ssisbi",$param_id, $param_name, $param_size, $param_type, $param_data, $param_prod_id);
$param_id = '';
$param_prod_id = $product_id;
for ($i=0; $i < count($_FILES['image']['name']); $i++) {
$param_name = $_FILES['image']['name'][$i];
$param_size = $_FILES['image']['size'][$i];
$param_type = $_FILES['image']['type'][$i];
$param_data = file_get_contents($_FILES['image']['tmp_name'][$i]);
$stmt -> send_long_data(4,$param_data);
$stmt -> execute() or die ("Could not execute file ".$i);
}
echo 'successfully added';
}
/*
Array
(
[image] => Array
(
[name] => Array
(
[0] => product interface desktop retrieved database.png
[1] => product interface desktop.png
[2] => product interface mobile retrived db.jpg
)
[type] => Array
(
[0] => image/png
[1] => image/png
[2] => image/jpeg
)
[tmp_name] => Array
(
[0] => D:\Web Environment\xampp\tmp\php57F5.tmp
[1] => D:\Web Environment\xampp\tmp\php5805.tmp
[2] => D:\Web Environment\xampp\tmp\php5816.tmp
)
[error] => Array
(
[0] => 0
[1] => 0
[2] => 0
)
[size] => Array
(
[0] => 734852
[1] => 326626
[2] => 33800
)
)
)
*/
?><file_sep>/user/password-algo.php
<?php
/* Get instance of mysqli object */
$db = Database::getInstance();
/* Check if user click confirm button */
if(isset($_POST['confirm'])):
/* Get username and escape */
$username = $db -> real_escape_string($_SESSION['username']);
/* Get hashed password */
if($result = $db -> query("SELECT password FROM user WHERE username='$username'")):
/* Check row retrieved */
if($result -> num_rows === 1):
/* Get data from row and store as array */
$data = $result -> fetch_assoc();
/* Verify current password */
if(password_verify($_POST['current_password'],$data['password'])):
/* Get new password and password confirmation */
$newPassword = $db -> real_escape_string($_POST['new_password']);
$confirmPassword = $db -> real_escape_string($_POST['confirm_password']);
// check if new and confirm password is same
if($newPassword===$confirmPassword):
// hash password and escape before inserting
$hash = $db -> real_escape_string(password_hash($newPassword,PASSWORD_DEFAULT));
// begin query -- update password
if($db-> query("UPDATE user SET password = '$hash' WHERE username = '$username'")){
// check if there is affected rows
if($db->affected_rows===1){
$updated = true;
}
}
endif;
else:
// show error popup (password verify failed) -- password incorrect
$error = true;
endif;
endif; // end if for num of row retrieve
endif; // endif for query
endif; // endif for get
?><file_sep>/database/config.php
<?php
// singleton class
class Database {
// variable for database initialization
private static $instance = null;
private const HOST = 'localhost';
private const USERNAME = 'root';
private const PASSWORD = '';
private const DATABASE = 'yeppel gadget';
// constructor -- to initialize database connection
private function __construct() {
$conn = new mysqli(
self::HOST, // localhost
self::USERNAME, // root
self::PASSWORD, // none
self::DATABASE // yeppel gadget
);
// check error for database connection
if($conn -> connect_errno) {
// print formatted string
printf(
"<h1>%s</h1> <did>%s</did>",
"ERROR! CANNOT CONNECT TO THE DATABASE",
"Error: ".$conn -> connect_error
);
exit; // print error and terminate program
}
self::$instance = $conn; // assign $conn to $instance if no error
}
// static method -- return mysql database
public static function getInstance(): MySQLi {
if(self::$instance === null){
// call constructor -- $instance will be initialize
new static();
}
return self::$instance; // return static variable -- $instance
}
public static function getRows(string $sql) : array {
$rows = array();
$result = self::getInstance() -> query($sql);
while($row = $result -> fetch_object()){
$rows[] = $row;
}
return $rows;
}
}
// close database connection
function close_connection(){
Database::getInstance() -> close(); // close mysqli connection
}
// -- execute function at the end of file
register_shutdown_function('close_connection');
?><file_sep>/admin/content/manage-product.php
<?php
require_once("../../database/config.php");
$db = Database::getInstance();
$sql = "SELECT product.id as prod_id, product.name as prod_name, product.price as prod_price, product.availability_id as prod_availability, image.id as img_id from product inner join image on product.id = image.product_id group by prod_id";
$result = $db -> query($sql);
?>
<div class="row">
<h4>Click button to change availability</h4>
<?php while($result -> num_rows > 0 and $data = $result -> fetch_assoc()): // output product -- by category / search / all product ?>
<a>
<div class="col s12 m6 l3">
<div class="card">
<div class="card-image">
<img class="" src="../database/retrieve-img.php?id=<?php echo $data['img_id'] ?>">
</div>
<div class="card-content" style="height: 8rem;">
<span class="black-text"><h6><?php echo $data['prod_name'] ?></h6></span>
<h6> Price: RM <?php echo number_format($data['prod_price'],2); ?> </h6>
</div>
<div class="card-action center">
<?php if(strtolower($data['prod_availability']) == "1"): ?>
<button class="btn light-blue darken-1 waves-effect waves-light" onclick="changeAvailability(<?php echo $data['prod_id']; ?>)">
Available
</button>
<?php else: ?>
<button class="btn red darken-1 waves-effect waves-light" onclick="changeAvailability(<?php echo $data['prod_id']; ?>)">
Not Available
</button>
<?php endif; ?>
</div>
</div>
</div>
</a>
<?php endwhile; ?>
</div><file_sep>/product-detail.php
<?php
session_start();
// database class
require_once('database/config.php');
$db = Database::getInstance();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product | Yeppel</title>
<link rel="shortcut icon" href="image/favicon2.png" type="image/x-icon">
<!-- Content Delivery Network - CSS -->
<?php include("component/cdn-css.php"); ?>
<!-- Customize CSS -->
<link rel="stylesheet" href="css/style.css">
<style>
.modal{
width: 20vw;
padding: 0 10px;
}
#description, #description > ol{
font-size: 1.7rem!important;
text-align: justify!important;
}
</style>
</head>
<body class="grey lighten-3">
<!-- Navigation bar -->
<?php include("component/navigation.php"); ?>
<?php
// get product id -- user selected
if (isset($_GET['product'])):
// escape string before inserting into database
$searchId = $db -> real_escape_string($_GET['product']);
// begin query -- get product details including all image for the product
$result = $db -> query("SELECT product.id as prod_id, product.name as prod_name, product.price as prod_price, product.description as description, image.id as img_id, image.name as img_name from product inner join image on product.id = image.product_id where product.id = $searchId;");
?>
<div class="row card-panel z-depth-5" style="transform: scale(0.85); margin-top: -2rem">
<div class="col s12 m12 l6">
<div class="carousel carousel-slider center z-depth-3">
<?php while($data = $result -> fetch_assoc()): // make loop to display all image with carousel slider ?>
<div class="carousel-item">
<img class="carousel-product" src="database/retrieve-img.php?id=<?php echo $data['img_id']; ?>" alt="<?php echo $data['img_name']; ?>">
</div>
<?php endwhile; ?>
</div>
</div>
<div class="col s12 m12 l6">
<?php
$result -> data_seek(0); // change index of row to 0
$detail = $result -> fetch_assoc(); // retrieve associative array
?>
<div class="col l12">
<h1 class="bold"><?php echo $detail['prod_name']; ?></h1>
</div>
<div class="col l12">
<h1 class="card-panel"><span class="blue-text"> RM <?php echo number_format($detail['prod_price'],2); ?></span> </h1>
</div>
<div class="col l12" style="margin-bottom: 2rem;">
<div id="description">
<?php echo $detail['description']; ?>
</div>
</div>
<div class="col l12">
<button onclick="addItem('<?php echo $_GET['product']; ?>')" name="add-to-cart" class="btn btn-large waves-effect waves-block light-blue darken-1" style="width: 100%">
<i class="material-icons" style="position: absolute; margin-left: 7rem">add_shopping_cart</i>
Add to Cart
</button>
</div>
</div>
</div>
<?php
endif;
?>
<div id="added-to-cart" class="modal">
<div class="modal-content">
<i class="material-icons center green-text text-darken-1" style="width: 100%; font-size: 10rem">check_circle</i>
<h4 class="center">Added to cart</h4>
</div>
</div>
<!-- Content Delivery Network - JS -->
<?php include("component/cdn-js.php"); ?>
<!-- Customize Javascript -->
<script src="js/main.js"></script>
<script src="js/carousel-normal.js"></script>
<script>
$(()=>{
$('#product-page').addClass("active");
// assign modal method
$('#added-to-cart').modal({ // customize modal popup to display (add to cart) message
endingTop: "30%", // margin top
dismissible: true, // make modal dismissible with keyboard and mouse
inDuration: 500, // duration for modal popup in
outDuration: 500 // duration fro modal popup out
});
})
function addItem(productId){
// perform ajax post http request
$.post("user/add-item.php" /* Path file */,{
product_id: productId // variable to pass
},
(data, status)=>{
// status -- success/failed to execute
// data -- output from file
// succed added to cart
if(data === "added to cart"){
// open modal popup -- added to cart with icon
$('#added-to-cart').modal("open");
// execute function after 1 sec
setTimeout(()=>{
$("#added-to-cart").modal("close"); // close modal after 1 sec
},1000);
} else {
console.log(data)
}
if (data == "login required") {
window.location.replace("login-page.php"); // redirect to login page
}
}
);
}
</script>
</body>
</html><file_sep>/database/login-auth.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login | Yeppel</title>
<link rel="shortcut icon" href="../image/favicon2.png" type="image/x-icon">
<!-- Content Delivery Network - CSS -->
<?php include("../component/cdn-css.php"); ?>
<!-- Customize CSS -->
<link rel="stylesheet" href="../css/style.css">
<style>
.modal{
width: 28vw;
padding: 0 10px;
}
</style>
<!-- Content Delivery Network - JS -->
<?php include("../component/cdn-js.php"); ?>
<!-- Customize Javascript -->
<script src="../js/main.js"></script>
<script>
</script>
</head>
<body>
<!-- modal popup -->
<div class="modal" id="output-modal">
<div class="modal-content center-align">
<h3 id="modal-head"></h3>
<p id="modal-body"></p>
</div>
<div class="modal-footer">
<a id="btn-cont" class="modal-close waves-effect btn"></a>
</div>
</div>
<?php
if(isset($_POST)):
/* Get instance of mysql connection */
require_once("config.php");
$db = Database::getInstance();
/* Escape string for security purpose */
$username = $db -> real_escape_string($_POST['username']);
$password = $db -> real_escape_string($_POST['password']);
/* Retrieve data from database by username */
if($result = $db -> query("select user.id as id, user.username as username, user.password as password, role.type as role_type from user inner join role on user.role_id = role.id WHERE user.username = '$username'")):
$error = true; // -- boolean to store error bool
/* Check -- number of rows retrieved */
if($result -> num_rows > 0){
/* Get data and store into array */
$data = $result->fetch_assoc();
/* Verify passord */
if(password_verify($password,$data['password'])){
$error = false; // -- assign error bool false
// set browser cookies to save login auth
if(isset($_POST['remember']) and $_POST['remember']==='on'){
setcookie("username",$username,time()+(7*24*60*60),"/"); //? store username into cookies for a week
setcookie("password",$password,time()+(7*24*60*60),"/"); //? store password into cookies for a week
}
/* Start session and save data intor session array */
session_start();
$_SESSION['id'] = $data['id'];
$_SESSION['username'] = $data['username'];
$_SESSION['role'] = $data['role_type'];
if(isset($_SESSION['redirect-url'])){
$url = $_SESSION['redirect-url']; // store url information -- exist when user clicked (add to cart) but not login yet
unset($_SESSION['redirect-url']); // destroy session variable for redirect-url index
header("Location: $url"); // redirect to current product location
exit; // terminate file script
}
header("Location: ../index.php"); // redirect to main index if user login from index page
}
}
if($error){
// show error -- username has already exist
?>
<script>
$(()=>{
$("#modal-head").text("Could not login !");
$("#modal-head").css({
"color": "red",
"font-weight": "600"
});
$("#modal-body").text("Username or password incorrect");
$("#btn-cont").text("Back");
$("#btn-cont").addClass("red darken-1")
$("#btn-cont").attr("href","../login-page.php");
});
$(()=>{
// prevent modal popup from close by overlay click
$('#output-modal').modal({
dismissible: false
});
// assign modal method
$('#output-modal').modal('open');
});
</script>
<?php
}
endif; // endif -- query
endif; // endif -- isset
?>
</body>
</html>
<file_sep>/database/confirm-received.php
<?php
if(isset($_POST['payment_id'])):
// get instance of mysqli class
require_once("config.php");
$db = Database::getInstance();
// escape string
$payment_id = $db -> real_escape_string($_POST['payment_id']);
// begin query -- update shipment status (from "to receive" to "received")
$db -> query("UPDATE payment SET shipment_id = '3' WHERE id = '$payment_id'") or die("Query Error: ".$db -> error);
// output data
if($db -> affected_rows === 1){
echo 'update success';
exit;
}
echo 'update failed';
endif;
?><file_sep>/user/profile-updated.php
<?php
if(isset($updated) and $updated):
$updated = false;
?>
<style>
.modal{
width: 20vw!important;
padding: 0 10px;
}
</style>
<!-- Modal popup -->
<div id="success" class="modal">
<div class="modal-content center-align">
<i class="material-icons tick green-text">check_circle</i>
</div>
<div class="modal-footer text-center">
Profile Updated
</div>
</div>
<script>
$(()=>{
/* Set transition duration in out popup */
$("#success").modal({
inDuration: 500,
outDuration: 500,
endingTop: "20%"
});
/* Open popup */
$("#success").modal("open");
/* Close popup after 2 second */
setTimeout(()=>{
$("#success").modal("close");
},2000)
})
</script>
<?php
endif;
?><file_sep>/admin/content/view-sales.php
<?php
require_once("../../database/config.php");
$db = Database::getInstance();
// select item.id as id, item.quantity as quantity, item.price as price, item.orders_id as orders_id, item.product_id as product_id, product.name as product_name, count(orders_id) from item inner join product on product.id = item.product_id inner join orders on orders.id = item.orders_id where orders_id != 'NULL' and orders.status = 'complete' group by product.name order by count(product.name) desc;
$result_most_sales = $db -> query("select item.id as id, item.price as price, product.name as product_name, count(orders_id) as total_sold from item inner join product on product.id = item.product_id inner join orders on orders.id = item.orders_id where orders_id != 'NULL' and orders.status_id = '2' group by product.name order by count(product.name) desc limit 5")
or die("Query Failed: ".$db -> error);
// select user.username as username, orders.id as orders_id, orders.status as ordres_status, sum(payment.total) as total_purchase from orders inner join user on user.id = orders.user_id inner join payment on payment.orders_id = orders.id where orders.status = 'complete' group by user.username order by sum(payment.total) desc;
$result_most_purchased_user = $db -> query("select user.username as username, user.name as name, sum(payment.total) as total_purchase from orders inner join user on user.id = orders.user_id inner join payment on payment.orders_id = orders.id where orders.status_id = '2' group by user.username order by sum(payment.total) desc limit 5")
or die("Query Error: ".$db -> error);
$counter = 0;
?>
<div class="card-panel z-depth-2" style="margin-bottom: 3rem;">
<div class="row">
<div class="col s12">
<?php if($result_most_sales -> num_rows > 0): ?>
<h4 class="center" style="margin-bottom: 2rem;">
Most Product Sold
</h4>
<table>
<thead>
<tr>
<th>No</th>
<th>Product Name</th>
<th>Product Price</th>
<th>Quantity Sold</th>
<th>Total Sold</th>
</tr>
</thead>
<tbody>
<?php foreach($result_most_sales as $row): ?>
<?php //echo "<pre>", print_r($row), "</pre>"; ?>
<tr>
<td> <?php echo ++$counter; ?> </td>
<td> <?php echo $row['product_name']; ?> </td>
<td> <?php echo "RM ".number_format($row['price']); ?> </td>
<td> <?php echo $row['total_sold']; ?> </td>
<th class="light-blue-text darken-1"> <?php echo "RM ".number_format($row['price'] * $row['total_sold']); ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
</div>
</div>
<div class="card-panel z-depth-2" style="margin-bottom: 3rem;">
<div class="row">
<div class="col s12">
<?php if($result_most_purchased_user -> num_rows > 0): $counter = 0; ?>
<h4 class="center" style="margin-bottom: 2rem;">
Most Purchased User
</h4>
<table>
<thead>
<tr>
<th>No</th>
<th>Username</th>
<th>Name</th>
<th>Total Purchased</th>
</tr>
</thead>
<tbody>
<?php foreach($result_most_purchased_user as $row): ?>
<?php //echo "<pre>", print_r($row), "</pre>"; ?>
<tr>
<td> <?php echo ++$counter; ?> </td>
<td> <?php echo $row['username']; ?> </td>
<td> <?php echo $row['name']; ?> </td>
<th class="light-blue-text darken-1"> <?php echo "RM ".number_format($row['total_purchase']); ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
</div>
</div><file_sep>/user/make-payment.php
<?php
// ajax post
if (isset($_POST['gateway_id']) and isset($_POST['orders_id'])):
// get instance of mysqli object
require_once "../database/config.php";
$db = Database::getInstance();
// escape string
$gateway_id = $db -> real_escape_string($_POST['gateway_id']);
$orders_id = $db -> real_escape_string($_POST['orders_id']);
// get total price of orders
$total = 0;
$item_price = $db -> query("SELECT item.price as item_price FROM item WHERE orders_id = '$orders_id'") or die("Query 1 Error: ".$db -> error);
foreach($item_price as $row){
$total += $row['item_price'];
}
$total = $db -> real_escape_string($total);
// insert into payment
$db -> query("INSERT INTO payment (total,orders_id,shipment_id,gateway_id) VALUES ('$total','$orders_id','1','$gateway_id')") or die("Query 2 Error: ".$db -> error);
// update orders - change order to complete
$db -> query("UPDATE orders set status_id='2' WHERE id = '$orders_id'") or die("Query 3 Error: ".$db -> error);
if ($db -> error == null) {
echo 'orders complete';
}
endif;
?><file_sep>/database/retrieve-img.php
<?php
// retrieve database static class
require_once('config.php');
// get instace of mysqli connection
$db = Database::getInstance();
// *** USE THIS HTML TAG TO RETRIEVE IMAGE ***
// *** <img src="retrieve-img.php?id=0001"> ***
// check if method get --- id index
if(isset($_GET['id'])){
// escape string before retrieve data from database
$id = $db -> real_escape_string($_GET['id']);
// execute query
if($result = $db -> query("SELECT type,data FROM image WHERE id='$id'")){
// check row retrieved and fetch data into a array
if($result -> num_rows === 1 and $image = $result -> fetch_assoc()){
// indicate media type -- image
header("Content-Type: ".$image['type']);
// output data of image
echo $image['data'];
}else {
// output error image
errorImage();
}
}
}else errorImage();
// display error image -- no image
function errorImage(){
$error = file_get_contents("../image/no_photo.png");
header("content-type: image/png");
echo $error;
}
?><file_sep>/admin/content/process-shipment.php
<?php
session_start();
// print_r($_POST);
// check if user is admin
if($_SESSION['role'] == "admin"):
// get instance of mysqli class
require_once("../../database/config.php");
$db = Database::getInstance();
// escape string
$payment_id = $db -> real_escape_string($_POST['payment_id']);
$sql = "UPDATE payment SET shipment_id = '2' WHERE id = '$payment_id'";
// query -- update shipment
$db -> query($sql) or die("Query Error: ".$db -> error);
// check affected row
if($db -> affected_rows == 1){
echo 'success';
}else {
echo 'something wrong: '.$sql;
}
endif;
?><file_sep>/admin/content/delete-user.php
<?php
session_start();
//print_r($_SESSION);
// check if user is admin
if($_SESSION['role'] == "admin"):
// get instance of mysqli class
require_once("../../database/config.php");
$db = Database::getInstance();
// escape string
$user_id = $db -> real_escape_string($_POST['user_id']);
$sql = "DELETE FROM user WHERE id = '$user_id'";
// query -- delete user
$db -> query($sql) or die("Query Error: ".$db -> error);
// check affected row
if($db -> affected_rows == 1){
echo 'deleted';
}else {
echo 'something wrong: '.$sql;
}
endif;
?><file_sep>/component/navigation.php
<?php
if(isset($_SESSION['role']) and $_SESSION['role'] == 'admin'){
header("location: admin/homepage.php");
}
?>
<div class="navbar-fixed">
<nav class="nav-wrapper light-blue darken-1">
<a href="index.php" class="brand-logo brand-heading">Yeppel</a>
<a href="#" class="sidenav-trigger" data-target="mobile-links">
<i class="material-icons">menu</i>
</a>
<ul class="right hide-on-med-and-down menu">
<li><i id="search-icon" class="material-icons tooltipped" data-position="bottom" data-tooltip="Search" style="margin-right: 1.3rem; margin-top: 0.2rem">search</i></li>
<li id="home-page" class=""><a href="index.php">Home</a></li>
<li id="product-page" class=""><a href="product.php">Product</a></li>
<li id="about-page" class=""><a href="about-us.php">About</a></li>
<?php
/* Check if user already login or not */
if(isset($_SESSION['username'])) {
/* Output username at navigation bar */
?>
<li id="profile-page"><a href="#" class="dropdown-trigger" data-target="dropdown-user">
<?php echo $_SESSION['username']; ?></a> <!-- Output username -- replaced login button -->
</li>
<ul id="dropdown-user" class="dropdown-content">
<li><a class="light-blue-text text-darken-1" href="profile.php">My Account</a></li>
<li><a class="light-blue-text text-darken-1" href="my-purchase.php">My Purchase</a></li>
<li><a class="light-blue-text text-darken-1" href="database/logout.php">Logout</a></li>
</ul>
<?php
}else {
?> <li><a href="login-page.php">Login</a></li> <?php // default login button -- useer did not login yet
}
?>
</ul>
<a href="cart.php" class="brand-logo right cart tooltipped" data-position="left" data-tooltip="View Cart" style="margin-top: 0.2rem;"><i class="material-icons cart">shopping_cart</i></a>
</nav>
</div>
<div class="modal" id="search-box" style="width: 30rem;">
<form action="product.php" method="GET" class="modal-content">
<span class="data input-field">
<i class="material-icons prefix">search</i>
<input type="text" class="validate" name="search" id="search" required>
<label for="search">Search</label>
</span>
<span>
<button type="submit" class="waves-effect waves-light btn light-blue darken-1" style="width: 100%; margin: 0.5rem 0">Search</button>
</span>
</form>
</div><file_sep>/cart.php
<?php
session_start();
// database class
require_once('database/config.php');
$db = Database::getInstance();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Cache-control" content="no-cache">
<title>Cart | Yeppel</title>
<link rel="shortcut icon" href="image/favicon2.png" type="image/x-icon">
<!-- Content Delivery Network - CSS -->
<?php include("component/cdn-css.php"); ?>
<!-- Customize CSS -->
<link rel="stylesheet" href="css/style.css">
<style>
.modal{
width: 20vw;
padding: 0 10px;
}
</style>
</head>
<body class="grey lighten-3">
<!-- Navigation bar -->
<?php include("component/navigation.php"); ?>
<div class="container">
<div class="row card-panel" style="margin-top: 3rem">
<div class="col l12">
<blockquote style="border-left-color: #039be5;">
<h3>Cart</h3>
</blockquote>
</div>
<div class="col l12">
<ol class="collection">
<?php
// check if user already login
if(isset($_SESSION['id']) and isset($_SESSION['username'])):
// escape string
$user_id = $db -> real_escape_string($_SESSION['id']);
$order = $db -> query("select id from orders where status_id = '1' and user_id='$user_id'") or die("Query failed: ".$db -> error);
if($order -> num_rows == 1):
// escape string
$order_id = $db -> real_escape_string($order -> fetch_assoc()['id']);
// begin query -- retrieve item added into cart with limit one image
$result = $db -> query("select item.id as item_id, product.name as product_name,product.price as price_per_item, item.quantity as item_quantity, item.price as item_price, image.id as image from item inner join product on item.product_id = product.id inner join image on image.product_id = product.id inner join orders on orders.id = item.orders_id where orders.id = '$order_id' and product.availability_id = '1' group by item.id")
or die("query 1 failed");
// variable to store total price
$total_price = 0;
// check if rows more thant one
if($result -> num_rows > 0):
// fetch associative array - store into a variable
while($data = $result -> fetch_assoc()):
$total_price += $data['item_price']; // add into variable -- used to store total of all product
?>
<li class="collection-item avatar black-text">
<img src="database/retrieve-img.php?id=<?php echo $data['image']; ?>" alt="" class="circle">
<span class="title">
<h6>
<?php echo $data['product_name']; ?>
</h6>
</span>
<p>
  <b>RM <?php echo number_format($data['price_per_item'],2); ?> </b> x <?php echo $data['item_quantity']; ?> = <b class="light-blue-text text-darken-1">RM <?php echo number_format($data['item_price'],2); ?></b>
</p>
<a href="" onclick="event.preventDefault();deleteItem('<?php echo $data['item_id']; ?>')" class="secondary-content red-text tooltipped" data-position="right" data-tooltip="Remove item">
<i class="material-icons">
remove_shopping_cart
</i>
</a>
</li>
<?php
endwhile;
goto skip_none; // skip display
else:
goto display_none; // show display -- nothing added
endif;
else:
goto display_none;
endif;
display_none:
?>
<li class="collection-item avatar black-text">
<span class="title">
<h6>
Nothing added yet
</h6>
</span>
</li>
<?php
else:
header("location: login-page.php");
endif;
?>
<?php skip_none: ?>
</ol>
</div>
<?php if(isset($total_price) and $total_price > 0): // check if variable is set ?>
<div class="col l12">
<ul class="collection">
<li class="collection-item">
<div class="right-align">
SUBTOTAL:  
<span class="light-blue-text text-darken-1" style="font-size: 1.8rem!important">
RM <?php echo number_format($total_price,2); ?>
</span>
</div>
</li>
</ul>
</div>
<?php endif; ?>
<div class="col l12">
<?php if(isset($result) and $result -> num_rows > 0): ?>
<a href="check-out.php" class="btn waves-effect waves-light light-blue darken-1 right">
Check Out
</a>
<?php endif; ?>
<a href="index.php" class="btn waves-effect grey lighten-4 black-text right" style="margin-right: 1rem;">
Cancel
</a>
</div>
</div>
</div>
<!-- Content Delivery Network - JS -->
<?php include("component/cdn-js.php"); ?>
<!-- Customize Javascript -->
<script src="js/main.js"></script>
<script>
function deleteItem(itemId){
// perform ajax post http request
$.post("user/remove-item.php" /* path */,{
item_id: itemId /* variable to pass */
},
(data, status)=>{
window.location.href=window.location.href;
}
);
}
</script>
</body>
</html><file_sep>/js/main.js
$(document).ready(function () {
// add side navigation method from jquery
$('.sidenav').sidenav();
// add modal method from jquery
$(".modal").modal();
// add dropdodwn method from jquery
$(".dropdown-trigger").dropdown();
// add tooltip method from jquery
$('.tooltipped').tooltip();
// add tabs method from jquery
$('.tabs').tabs();
// add select option method from jquery
$('select').formSelect();
// add event listener for term and condition checkbox
// -- if check, sign up button will enabled, by default its disabled
$("#agreement").click(() => {
if ($("#agreement").prop("checked")) {
$("#create-acc").prop('disabled', false);
} else {
$("#create-acc").prop('disabled', true);
}
});
$("#search-icon").click(() => {
$("#search-box").modal("open");
});
})<file_sep>/product.php
<?php
session_start();
// database class
require_once('database/config.php');
$db = Database::getInstance();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product | Yeppel</title>
<link rel="shortcut icon" href="image/favicon2.png" type="image/x-icon">
<!-- Content Delivery Network - CSS -->
<?php include("component/cdn-css.php"); ?>
<!-- Customize CSS -->
<link rel="stylesheet" href="css/style.css">
</head>
<body class="grey lighten-3">
<!-- Navigation bar -->
<?php include("component/navigation.php"); ?>
<?php
// default sql -- retrieve all product
$sql = "SELECT product.id as prod_id, product.name as prod_name, product.price as prod_price, image.id as img_id from product inner join image on product.id = image.product_id where product.availability_id = '1' group by prod_id";
echo '<blockquote class="container" style="border-left-color: #039be5">';
// if user browse by category
if(isset($_GET['category'])):
// output header -- (ucfirst -- upper case first char)
echo "<h2>".ucfirst($_GET['category'])."</h2>";
// escape string before retrieveing from database
$category = $db -> real_escape_string($_GET['category']);
// retrieve image by category selected from user
$sql = "SELECT product.id as prod_id, product.name as prod_name, product.price as prod_price, image.id as img_id from product inner join image on product.id = image.product_id inner join category on product.category_id = category.id where category.name = '$category' and product.availability_id = '1' group by prod_id";
//if user browse by searching keyword
elseif(isset($_GET['search'])):
// output header
echo "<h2> Search Keyword: ".$_GET['search']."</h2>";
// escape string before retrieving from database
$search = $db -> real_escape_string("%".$_GET['search']."%");
// retrieve image by searching keyword -- use (like) and (%) to search entire word
$sql = "SELECT product.id as prod_id, product.name as prod_name, product.price as prod_price, image.id as img_id from product inner join image on product.id = image.product_id inner join category on product.category_id = category.id where product.name like '$search' and product.availability_id = '1' group by prod_id";
else:
// default header for all product
echo '<h2>All Product</h2>';
endif; // end if get category
echo '</blockquote>';
// execute sql query
$result = $db -> query($sql) or die($db -> error);
?>
<div class="container row" style="margin-top: 3rem;">
<?php while($result -> num_rows > 0 and $data = $result -> fetch_assoc()): // output product -- by category / search / all product ?>
<a href="product-detail.php?product=<?php echo $data['prod_id'] ?>">
<div class="col s12 m6 l3">
<div class="card hoverable">
<div class="card-image">
<img class="" src="database/retrieve-img.php?id=<?php echo $data['img_id'] ?>">
</div>
<div class="card-content" style="height: 8rem;">
<span class="black-text"><h6><?php echo $data['prod_name'] ?></h6></span>
</div>
<div class="card-action">
<h5>
from RM <?php echo number_format($data['prod_price'],2); ?>
</h5>
</div>
</div>
</div>
</a>
<?php endwhile; ?>
<?php if($result -> num_rows == 0 and isset($_GET['search'])): ?>
<div class="col s12 m12 l12">
<h5> Your search for <b style="padding: 0 0.5rem;" class="grey lighten-1"><?php echo $_GET['search']; ?></b> did not yield any results. </h5>
</div>
<?php endif;?>
</div>
<!-- Content Delivery Network - JS -->
<?php include("component/cdn-js.php"); ?>
<!-- Customize Javascript -->
<script src="js/main.js"></script>
<script>
$(()=>{
$('#product-page').addClass("active")
})
</script>
</body>
</html><file_sep>/admin/content/add-new-product.php
<?php
require_once("../../database/config.php");
$db = Database::getInstance();
$result_category = $db -> query("SELECT id, name FROM category") or die("Query Error: ".$db -> error);
$category = array();
foreach($result_category as $row){
$category[] = $row;
}
?>
<style>
.dropdown-content li>span {
color: #039be5 !important;
}
</style>
<div class="card-panel">
<div class="row">
<div class="col s12 center-align">
<h4>Add New Product</h4>
</div>
<div class="col s12">
<form id="product-form" enctype="multipart/form-data" onsubmit="add_product(this)">
<div class="input-field col s4">
<input type="text" class="" name="product_name" id="product_name" required>
<label for="product_name">Product Name</label>
</div>
<div class="input-field col s4">
<input type="number" name="product_price" id="product_price" required>
<label for="product_price">Product Price</label>
</div>
<div class="input-field col s4">
<select name="product_category" id="product_category">
<!-- <option value="" disabled selected>Choose Category</option> -->
<?php foreach($category as $row): ?>
<option value="<?php echo $row['id'] ?>"> <?php echo $row['name']; ?> </option>
<?php endforeach; ?>
</select>
<label>Product Category</label>
</div>
<div class="input-field col s12">
<textarea class="materialize-textarea" name="product_description" id="product_description" cols="30" rows="10" required></textarea>
<label for="product_description">Product Description</label>
</div>
<div class="file-field input-field col s12">
<div class="btn light-blue darken-1">
<span>Choose Image</span>
<input type="file" name="image[]" id="image[]" multiple required>
</div>
<div class="file-path-wrapper">
<input type="text" class="file-path validate" placeholder="Upload one image or more">
</div>
</div>
<div class="col s12 center">
<button type="submit" id="btn-add-product" class="btn btn-block waves-effect waves-light light-blue darken-1">
Add product
</button>
</div>
</form>
</div>
</div>
<script>
$(()=>{
// add select option method from jquery
$('select').formSelect();
/* $("#product-form").submit(()=> {
event.preventDefault();
var form_data = $("#product-form");
// var product_form = new FormData(form_data);
$("manage-content").load(JSON.stringify(form_data));
}) */
/* $("#btn-add-product").click(()=>{
}) */
})
</script><file_sep>/admin/change-password-admin.php
<?php
session_start();
require_once('../database/config.php');
$updated = false
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Password | Yeppel</title>
<link rel="shortcut icon" href="image/favicon2.png" type="image/x-icon">
<!-- Content Develivery Network - CSS -->
<?php include("../component/cdn-css.php") ?>
<!-- Customize CSS -->
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="../css/profile.css">
</head>
<body>
<!-- Navigation Bar -->
<?php include("../component/navigation-admin.php") ?>
<div class="container">
<div class="s12 card card-acc white">
<form action="" method="post">
<div class="row">
<blockquote class="col s12" style="border-left-color: #039be5;">
<h4 style="margin-top: 0;">Change Password</h4>
<span>For your account's security, do not share your password with anyone else</span>
</blockquote>
</div>
<hr>
<!-- Current Password -->
<div class="row margin-top-2">
<div class="col s1"></div>
<div class="col s3">
<span class="type">Current Password</span>
</div>
<div class="col s8">
<span class="data input-field">
<input type="password" name="current_password" id="current_password" required>
</span>
</div>
</div>
<!-- New Password -->
<div class="row margin-top-2">
<div class="col s1"></div>
<div class="col s3">
<span class="type">New Password</span>
</div>
<div class="col s8">
<span class="data input-field">
<input type="password" name="new_password" id="new_password">
</span>
</div>
</div>
<!-- Confirm Password -->
<div class="row margin-top-2">
<div class="col s1"></div>
<div class="col s3">
<span class="type">Confirm Password</span>
</div>
<div class="col s8">
<span class="data input-field">
<input type="password" name="confirm_password" id="confirm_password">
<span class="helper-text" for="confirm_password" data-error="wrong" data-success="right"></span>
</span>
</div>
</div>
<div class="row margin-top-2">
<div class="col s4"></div>
<div class="col s7">
<button id="confirm_btn" type="submit" name="confirm" disabled class="waves-effect waves-light btn light-blue darken-1"><i class="material-icons left">save</i>confirm</button>
</div>
</div>
</form>
<!-- Password Change Algorithm -->
<?php require_once("../user/password-algo.php") ?>
</div>
</div>
<!-- Content Delivery Network - JS -->
<?php include("../component/cdn-js.php"); ?>
<!-- Customize Javascript -->
<script src="../js/main.js"></script>
<!-- For passwordd corfirmation -->
<script src="../js/change-password.js"></script>
<!-- popup -->
<?php require_once("../user/password-updated.php"); ?>
</body>
</html><file_sep>/check-out.php
<?php
session_start();
// database class
require_once('database/config.php');
$db = Database::getInstance();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Check Out | Yeppel</title>
<link rel="shortcut icon" href="image/favicon2.png" type="image/x-icon">
<!-- Content Delivery Network - CSS -->
<?php include("component/cdn-css.php"); ?>
<!-- Customize CSS -->
<link rel="stylesheet" href="css/style.css">
<style>
.modal{
width: 20vw;
padding: 0 10px;
}
</style>
</head>
<body class="grey lighten-3">
<!-- Navigation bar -->
<?php include("component/navigation.php"); ?>
<div class="container">
<div class="row card-panel" style="margin-top: 3rem">
<div class="col l12">
<blockquote style="border-left-color: #039be5;">
<h3>Check Out</h3>
</blockquote>
</div>
<div class="col l6">
<h6>
Shipping Detail
</h6>
<ul class="collection">
<li class="collection-item row">
<?php
// escape string
$user_id = $db -> real_escape_string($_SESSION['id']);
// begin query -- retrieve name and address using username as condition
$result = $db -> query("select name, address from user where id='$user_id'") or die("Query for user failed");
// check row retrieved
if($result -> num_rows == 1):
// fetch associative array - store into a variable
$data = $result -> fetch_assoc();
?>
<span class="title col l2">
Name
</span>
<span class="col l10" style="font-weight: 600">
<?php echo $data['name']; ?>
</span>
</li>
<li class="collection-item row">
<span class="title col l2">
Ship to
</span>
<span class="col l10" style="font-weight: 600">
<?php echo $data['address']; endif;?>
</span>
</li>
<li class="collection-item row">
<span class="title col l2">
Method
</span>
<span class="col l10" style="font-weight: 600">
Free Shipping
</span>
</li>
</ul>
<h6>
Payment
</h6>
<?php
$gateway = Database::getRows("SELECT * FROM gateway"); $checked = true;
?>
<span>All transactions are secure and encrypted.</span>
<ul class="collection">
<?php foreach($gateway as $row): ?>
<li class="collection-item">
<label>
<input class="with-gap" name="gateway_id" id="gateway_id" value="<?php echo $row -> id; ?>" type="radio" required <?php if($checked==true){ echo 'checked'; $checked = false; } ?> >
<span class="black-text"><?php echo $row -> name; ?></span>
</label>
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="col l6">
<ol class="collection">
<?php
// begin query -- retrieve item added into cart with limit one image
$result = $db -> query("select item.id as item_id, product.name as product_name,product.price as price_per_item, item.quantity as item_quantity, item.price as item_price, image.id as image, orders.id as orders_id from item inner join product on item.product_id = product.id inner join image on image.product_id = product.id inner join orders on orders.id = item.orders_id where orders.user_id = '$user_id' and orders.status_id = '1' group by item.id")
or die("query for item failed");
// variable to store total price and orders id
$total_price = 0;
$orders_id = "";
// check if rows more thant one
if($result -> num_rows > 0):
// fetch associative array - store into a variable
while($data = $result -> fetch_assoc()):
$orders_id = $data['orders_id'];
$total_price += $data['item_price']; // add into variable -- used to store total of all product
?>
<li class="collection-item avatar black-text">
<img src="database/retrieve-img.php?id=<?php echo $data['image']; ?>" alt="" class="circle">
<span class="title">
<h6>
<?php echo $data['product_name']; ?>
</h6>
</span>
<p>
  <b>RM <?php echo number_format($data['price_per_item'],2); ?> </b> x <?php echo $data['item_quantity']; ?> = <b class="light-blue-text text-darken-1">RM <?php echo number_format($data['item_price'],2); ?></b>
</p>
</li>
<?php
endwhile;
endif;
?>
</ol>
<ul class="collection">
<li class="collection-item black-text">
<div>
<span class="left-align">
Subtotal
</span>
<span class="right light-blue-text text-darken-1" style="font-size: 1.3rem!important">
<b>RM <?php echo number_format($total_price,2); ?></b>
</span>
</div>
<div style="margin-top: 1rem;">
<span class="left-align">
Shipping
</span>
<span class="right light-blue-text text-darken-1" style="font-size: 1.3rem!important">
<b>Free</b>
</span>
</div>
</li>
<li class="collection-item black-text">
<div>
<span class="left-align">
Total
</span>
<span class="right light-blue-text text-darken-1" style="font-size: 1.3rem!important">
<b>RM <?php echo number_format($total_price,2); ?></b>
</span>
</div>
</li>
</ul>
</div>
<div class="col l12">
<a href="index.php" class="btn waves-effect grey lighten-4 black-text right" style="margin-right: 1rem;">
Cancel
</a>
<button type="button" id="btn-submit" class="btn waves-effect waves-light light-blue darken-1 right" style="margin-right: 1rem;">
Continue to Payment
</button>
</div>
</div>
</div>
<div id="complete-order" class="modal">
<div class="modal-content">
<i class="material-icons center green-text text-darken-1" style="width: 100%; font-size: 10rem">check_circle</i>
<h4 class="center">Thank you for purchasing</h4>
</div>
</div>
<!-- Content Delivery Network - JS -->
<?php include("component/cdn-js.php"); ?>
<!-- Customize Javascript -->
<script>
$(()=>{
// add event listener for submit button
$("#btn-submit").click(()=>{
// post request -- send gateway id and orders id
$.post( "user/make-payment.php" , {
gateway_id: $("#gateway_id:checked").val(),
orders_id: "<?php echo $orders_id; ?>"
},
(data, status)=>{
// alert(data);
// check if payment complete
if(data == "orders complete") {
// initialize modal
$('#complete-order').modal({
dismissible: false
});
// open modal popup
$('#complete-order').modal("open");
// redirect user after 1 sec
setTimeout(()=>{
window.location.replace("my-purchase.php");
},1000)
}
}
);
})
})
</script>
<script src="js/main.js"></script>
</body>
</html><file_sep>/admin/homepage.js
$(()=>{
$('#home-page').addClass("active");
$('#manage-content').load("content/list-new-order.php");
$('#btn-new-order').click(()=>{
$('#manage-content').load("content/list-new-order.php");
})
$('#btn-processed-order').click(()=>{
$('#manage-content').load("content/list-processed-order.php");
})
$('#btn-complete-order').click(()=>{
$('#manage-content').load("content/list-complete-order.php");
})
$('#btn-view-sales').click(()=>{
$('#manage-content').load("content/view-sales.php");
})
$('#btn-add-product').click(()=>{
$('#manage-content').load("content/add-new-product.php");
})
$('#btn-manage-user').click(()=>{
$('#manage-content').load("content/table-user.php");
})
$('#btn-manage-product').click(()=>{
$('#manage-content').load("content/manage-product.php");
})
})
var process_payment_id = null;
function confirmbox_processShipment(id) {
process_payment_id = id;
$("#confirm-process-shipment-popup").modal("open");
}
function processShipment() {
// execute php file -- process shipment;
$.post("content/process-shipment.php", {
payment_id: process_payment_id
},
(data,status) => {
/* alert(data); */
if(data == 'success'){
$('#manage-content').load("content/list-new-order.php");
$("#confirm-process-shipment-popup").modal("close");
/* $("#success-shipment-update-popup").modal("open"); */
$("#text-popup").html("Successfully Updated");
$("#success-popup").modal("open");
setTimeout(()=> {
$("#success-popup").modal("close");
},2000)
}
}
)
}
var del_user_id = null;
function confirmbox_deleteUser(id){
del_user_id = id;
$("#confirm-delete-popup").modal("open");
}
function deleteUser(){
// execute php file -- delete user;
$.post("content/delete-user.php", {
user_id: del_user_id
},
(data,status) => {
if(data == 'deleted'){
$('#manage-content').load("content/table-user.php");
$('#total-user-board').html(parseInt($('#total-user-board').html()) - 1);
$("#confirm-delete-popup").modal("close");
/* $("#success-delete-popup").modal("open"); */
$("#text-popup").html("Successfully Deleted");
$("#success-popup").modal("open");
setTimeout(()=> {
$("#success-popup").modal("close");
},2000)
}
}
)
}
function add_product(obj) {
event.preventDefault();
var product_form = new FormData(obj);
$.ajax({
method: "post",
contentType: false,
processData: false,
cache: false,
url: "content/add-product-db.php",
data: product_form,
enctype: "multipart/form-data",
success: (data) => {
if(data == 'successfully added'){
$('#manage-content').load("content/add-new-product.php");
$('#total-product-board').html(parseInt($('#total-product-board').html()) + 1);
$("#text-popup").html("Product Added");
$("#success-popup").modal("open");
setTimeout(()=> {
$("#success-popup").modal("close");
},2000)
}
}
})
}
function changeAvailability(product_id) {
$.post("content/change-availability.php", {
product_id: product_id
},
(data,status) => {
if(data == "changed") {
$('#manage-content').load("content/manage-product.php");
}
})
}<file_sep>/admin/profile-admin.php
<?php
session_start();
// database class
require_once('../database/config.php');
// query code -- change profile
require_once('../user/change-profile.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Account | Yeppel</title>
<link rel="shortcut icon" href="image/favicon2.png" type="image/x-icon">
<!-- Content Delivery Network - CSS -->
<?php include("../component/cdn-css.php"); ?>
<!-- Customize CSS -->
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="../css/profile.css">
</head>
<body class="grey lighten-3">
<!-- Navigation bar -->
<?php include("../component/navigation-admin.php"); ?>
<div class="container">
<div class="s12 card card-acc white">
<?php
// get database instance
$db = Database::getInstance();
// escape string -- prevent sql injection
$username = $db -> real_escape_string($_SESSION['username']);
// retrieve column from database by username
if($result = $db -> query("SELECT * FROM user WHERE username='$username' ")):
// check if column retrieved 1
if($result->num_rows===1):
// fetching data and store as array
$data = $result->fetch_assoc();
?>
<form action="" method="post">
<div class="row">
<blockquote class="col s12" style="border-left-color: #039be5;">
<h4 style="margin-top: 0;">My Profile</h4>
<span>Manage your account</span>
</blockquote>
</div>
<hr>
<!-- Username -->
<div class="row margin-top-2">
<div class="col s1"></div>
<div class="col s3">
<span class="type">Username</span>
</div>
<div class="col s8">
<span class="data">
<?php echo $data['username'] ?>
<!-- <input disabled type="text" value=""> -->
</span>
</div>
</div>
<!-- Name -->
<div class="row margin-top-2">
<div class="col s1"></div>
<div class="col s3">
<span class="type">Name</span>
</div>
<div class="col s8">
<span class="data input-field">
<input type="text" name="name" id="name" value="<?php echo $data['name'] ?>">
</span>
</div>
</div>
<!-- Address -->
<div class="row margin-top-2">
<div class="col s1"></div>
<div class="col s3">
<span class="type">Address</span>
</div>
<div class="col s8">
<span class="data input-field">
<textarea class="materialize-textarea" name="address" id="address"><?php echo $data['address'] ?></textarea>
</span>
</div>
</div>
<!-- Date created -->
<div class="row margin-top-2">
<div class="col s1"></div>
<div class="col s3">
<span class="type">Created At</span>
</div>
<div class="col s8">
<span class="data">
<?php echo date("d F Y", strtotime($data['created_at'])); ?>
<!-- <input disabled type="text" value=""> -->
</span>
</div>
</div>
<div class="row margin-top-2">
<div class="col s4"></div>
<div class="col s7">
<button type="submit" name="save" class="waves-effect waves-light btn light-blue darken-1"><i class="material-icons left">save</i>Save</button>
<a href="change-password-admin.php" class="waves-effect waves-light btn light-blue darken-1">Change Password</a>
</div>
</div>
</form>
<?php
endif; // result
endif; // query
?>
</div>
</div>
<!-- Content Delivery Network - JS -->
<?php include("../component/cdn-js.php"); ?>
<!-- Customize Javascript -->
<script src="../js/main.js"></script>
<script>
$(()=>{
$('#profile-page').addClass("active")
})
</script>
<?php require_once("../user/profile-updated.php"); ?>
</body>
</html><file_sep>/database/create_acc.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Create Account | Yeppel </title>
<link rel="shortcut icon" href="../image/favicon2.png" type="image/x-icon">
<!-- Content Delivery Network - CSS -->
<?php include("../component/cdn-css.php"); ?>
<!-- Customize CSS -->
<link rel="stylesheet" href="../css/style.css">
<style>
.modal {
width: 20vw;
padding: 0 10px;
}
</style>
<!-- Content Delivery Network - JS -->
<?php include("../component/cdn-js.php"); ?>
<!-- Customize Javascript -->
<script src="../js/main.js"></script>
<script>
$(()=>{
// prevent modal popup from close by overlay click
$('#output-modal').modal({
dismissible: false,
inDuration: 500
});
// assign modal method
$('#output-modal').modal('open');
});
</script>
</head>
<body>
<!-- modal popup -->
<div class="modal" id="output-modal">
<div class="modal-content center-align">
<h3 id="modal-head"></h3>
<i id="icon" class='material-icons' style="font-size: 10rem;"></i>
<p id="modal-body" style="font-size: 1.2rem;"></p>
<a id="btn-cont" class="modal-close waves-effect btn" style="width: 100%;"></a>
</div>
</div>
<?php
if(isset($_POST)):
// database retrieve
require_once("config.php");
$db = Database::getInstance();
$username = $db -> real_escape_string( $_POST['username'] ); // escape string to prevent sql injection
if($result = $db -> query("SELECT * FROM user WHERE username='$username'")): // query to retrieve username
// check if username have been inserted
if($result -> num_rows > 0):
// show error -- username has already exist
?>
<script>
$(()=>{
$("#modal-head").text("Failed !");
$("#modal-head").css({
"color": "red",
"font-weight": "600"
});
$("#modal-body").text("Could not create! Username might been existed.");
$("#icon").addClass("red-text");
$("#icon").text("error");
$("#btn-cont").text("Back");
$("#btn-cont").addClass("red darken-1")
$("#btn-cont").attr("href","../create-acc-page.php");
});
</script>
<?php
else:
// continue -- username did not exist yet
// -- retrieve from input field
$name = $db -> real_escape_string( $_POST['name'] );
$address = $db -> real_escape_string( $_POST['address'] );
$hashedPassword = $db -> real_escape_string( password_hash($_POST['password'], PASSWORD_DEFAULT) ); // hashed password
// insert into database
if($db -> query("INSERT INTO user(username,name,password,address,role_id) VALUES ('$username','$name','$hashedPassword','$address','2')")){
if($db -> affected_rows > 0):
// show success popup
?>
<script>
$(()=>{
$("#modal-head").text("Success !");
$("#modal-head").css({
"font-weight": "600"
});
$("#modal-head").addClass("green-text text-darken-1");
$("#icon").addClass("green-text text-darken-1");
$("#icon").text("check_circle");
$("#modal-body").text("Your profile has been created.");
$("#btn-cont").text("Okay");
$("#btn-cont").addClass("green darken-1");
$("#btn-cont").attr("href","../login-page.php");
});
</script>
<?php
endif;
}else {
// print error message - query failed
printf(
"<h1 style='text-align:center'>%s</h1><div style='text-align:center'>%s</div>",
"ERROR",
"Query failed to execute!"
);
}
endif; // end if -- num_rows
endif; // end if -- select query
endif; // end if -- isset
?>
</body>
</html><file_sep>/user/add-item.php
<?php
// For AJAX
session_start();
if(isset($_SESSION['id']) and isset($_SESSION['username'])):
$error = false;
// get instance of mysql
require_once("../database/config.php");
$db = Database::getInstance();
// escape string
$user_id = $db -> real_escape_string($_SESSION['id']);
$user_username = $db -> real_escape_string($_SESSION['username']);
$product_id = $db -> real_escape_string($_POST['product_id']); // product id that user wanted to add
$product_price = $db -> query("SELECT price FROM product WHERE id = '$product_id'") -> fetch_assoc()['price'] or die("query 0 error: ".$db -> error);
// begin select query -- to check order by user
if($order_result = $db -> query("SELECT id as orders_id from orders where user_id='$user_id' and status_id = '1' limit 1")):
// check retrieved row
if($order_result -> num_rows == 0):
// insert new order
$db -> query("INSERT INTO orders VALUES (NULL,'1','$user_id')") or die("query 1 error: ".$db -> error);
// retrieve new order inserted
$order_id = $db -> query("SELECT last_insert_id() as id") -> fetch_assoc()['id'];
// insert new item
insert_product('',1,$product_price,$order_id,$product_id, $db);
else:
// -- continue order
// fetch order id
$order_id = $order_result -> fetch_assoc()['orders_id'];
// check item -- add current quantity / continue current quantity
$item = $db -> query("SELECT id, quantity FROM item WHERE product_id = '$product_id' and orders_id = '$order_id'") or die('query 4 error: '.$db -> error);
// check row retrieved
if($item -> num_rows == 0){
// insert new item
insert_product('',1,$product_price,$order_id,$product_id,$db);
}
// fetch existing item
$item_data = $item->fetch_assoc();
$item_id = $item_data['id'];
// assign new quantitiy and price
$new_quantity = $item_data['quantity'] + 1;
$new_price = $new_quantity * $product_price;
// update exisiting data -- item
$db -> query("UPDATE item SET price = '$new_price', quantity = '$new_quantity' WHERE id ='$item_id'") or die("query 5 error");
die("added to cart");
endif;
else:
die('main query error');
endif;
else:
// store current path -- for product that user selected
$_SESSION['redirect-url'] = $_SERVER['HTTP_REFERER'];
echo 'login required'; // output this and reutrn data by ajax -- checked later with if else statement
endif;
function insert_product(
string $id = NULL,
int $quantity,
int $price,
string $orderId,
string $productId,
mysqli $conn
){
$conn -> query("INSERT INTO item VALUES (NULL,$quantity,'$price','$orderId','$productId')") or die("query 3 error: ".$conn -> error);
die ("added to cart");
exit;
}
?><file_sep>/admin/homepage.php
<?php
session_start();
// database class
require_once('../database/config.php');
$db = Database::getInstance();
$result_total_order = $db -> query("SELECT count(payment.id) as total_order FROM payment inner join orders on orders.id = payment.orders_id") or die('Query Error: '.$db -> error);
$total_order = $result_total_order -> num_rows == 0 ? 0 : $result_total_order -> fetch_assoc()['total_order'];
$result_total_sales = $db -> query("SELECT sum(total) as total_sales FROM payment inner join orders on orders.id = payment.orders_id") or die('Query Error: '.$db -> error);
$total_sales = $result_total_sales -> num_rows == 0 ? 0 : $result_total_sales -> fetch_assoc()['total_sales'];
$total_product = $db -> query("SELECT count(id) as total_product FROM product") -> fetch_assoc()['total_product'] or die('Query Error: '.$db -> error);
$total_user = $db -> query("SELECT count(id) as total_user FROM user") -> fetch_assoc()['total_user'] or die('Query Error: '.$db -> error);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homepage | Yeppel</title>
<link rel="shortcut icon" href="../image/favicon2.png" type="image/x-icon">
<!-- Content Delivery Network - CSS -->
<?php include("../component/cdn-css.php"); ?>
<!-- Customize CSS -->
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="homepage.css">
</head>
<body class="grey lighten-3">
<!-- Navigation bar -->
<?php include("../component/navigation-admin.php"); ?>
<div class="container">
<div class="row" style="margin-top: 3rem;">
<div class="col s3">
<div class="col s12 card-panel light-blue darken-1 white-text center z-depth-3">
<h5>TOTAL ORDERS</h5>
<h3> <b> <?php echo $total_order; ?> </b> </h3>
</div>
</div>
<div class="col s3">
<div class="col s12 card-panel green darken-1 white-text center z-depth-3">
<h5>TOTAL SALES</h5>
<h3> <b> <?php echo "RM ".number_format($total_sales); ?> </b> </h3>
</div>
</div>
<div class="col s3">
<div class="col s12 card-panel deep-purple darken-1 white-text center z-depth-3">
<h5>TOTAL PRODUCTS</h5>
<h3> <b id="total-product-board"> <?php echo $total_product; ?> </b> </h3>
</div>
</div>
<div class="col s3">
<div class="col s12 card-panel pink darken-1 white-text center z-depth-3">
<h5> TOTAL USERS </h5>
<h3> <b id="total-user-board"> <?php echo $total_user; ?> </b> </h3>
</div>
</div>
</div>
<div class="row">
<div class="col s3" style="margin-bottom: 1rem;">
<button type="button" id="btn-new-order" class="btn btn-block waves-effect waves-light col s12 light-blue darken-1 z-depth-3">To-Process Shipment</button>
</div>
<div class="col s3" style="margin-bottom: 1rem;">
<button type="button" id="btn-processed-order" class="btn btn-block waves-effect waves-light col s12 light-blue darken-1 z-depth-3">Processed Shipment</button>
</div>
<div class="col s3" style="margin-bottom: 1rem;">
<button type="button" id="btn-complete-order" class="btn btn-block waves-effect waves-light col s12 light-blue darken-1 z-depth-3">Complete Orders</button>
</div>
<div class="col s3" style="margin-bottom: 1rem;">
<button type="button" id="btn-manage-user" class="btn btn-block waves-effect waves-light col s12 light-blue darken-1 z-depth-3">Manage Users</button>
</div>
<div class="col s4" style="margin-bottom: 1rem;">
<button type="button" id="btn-view-sales" class="btn btn-block waves-effect waves-light col s12 light-blue darken-1 z-depth-3">View Sales</button>
</div>
<div class="col s4" style="margin-bottom: 1rem;">
<button type="button" id="btn-add-product" class="btn btn-block waves-effect waves-light col s12 light-blue darken-1 z-depth-3">Add New Products</button>
</div>
<div class="col s4" style="margin-bottom: 1rem;">
<button type="button" id="btn-manage-product" class="btn btn-block waves-effect waves-light col s12 light-blue darken-1 z-depth-3">Manage Products</button>
</div>
</div>
<div class="row">
<div id="manage-content" class="col s12">
</div>
</div>
</div>
<!-- Popup -->
<?php include("modal-popup.php") ?>
<!-- Content Delivery Network - JS -->
<?php include("../component/cdn-js.php"); ?>
<!-- Customize Javascript -->
<script src="../js/main.js"></script>
<script src="homepage.js"></script>
</body>
</html><file_sep>/about-us.php
<?php
session_start();
// database class
require_once('database/config.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home | Yeppel</title>
<link rel="shortcut icon" href="image/favicon2.png" type="image/x-icon">
<!-- Content Delivery Network - CSS -->
<?php include("component/cdn-css.php"); ?>
<!-- Customize CSS -->
<link rel="stylesheet" href="css/style.css">
<style>
.image-table {
width: 10vw;
}
th, td{
border: 1px solid rgba(0,0,0,0.12);
}
th {
padding-left: 1rem;
}
</style>
</head>
<body class="grey lighten-3">
<!-- Navigation bar -->
<?php include("component/navigation.php"); ?>
<div class="row container" style="margin-top: 1rem; width: 60vw">
<table class="centered card-panel z-depth-5">
<caption>
<h2><i>Group Member's Information</i></h2>
</caption>
<tr>
<td></td>
<td>
<img class="image-table center-block" src="image/aiman_anizan.JPG" alt=""> <br>
</td>
<td>
<img class="image-table center-block" src="image/aiman_anizan.JPG" alt=""> <br>
</td>
<td>
<img class="image-table center-block" src="image/aiman_anizan.JPG" alt=""> <br>
</td>
</tr>
<tr>
<th>Name</th>
<td>
<div class="center-block" style="width: 10vw">
<i><b><NAME></b></i>
</div>
</td>
<td>
<div class="center-block" style="width: 10vw">
<i><b><NAME> bin <NAME></b></i>
</div>
</td>
<td>
<div class="center-block" style="width: 10vw">
<i><b><NAME></b></i>
</div>
</td>
</tr>
<tr>
<th>Student Number</th>
<td>
<i>2018659558</i>
</td>
<td>
<i>2018659558</i>
</td>
<td>
<i>2018659558</i>
</td>
</tr>
<tr>
<th>Group</th>
<td>
<i>CS110 5D</i>
</td>
<td>
<i>CS110 5D</i>
</td>
<td>
<i>CS110 5D</i>
</td>
</tr>
<tr>
<th>Email</th>
<td><a href="mailto:<EMAIL>"><b><i><EMAIL></i></b></a></td>
<td><a href="mailto:<EMAIL>"><b><i><EMAIL></i></b></a></td>
<td><a href="mailto:<EMAIL>"><b><i><EMAIL></i></b></a></td>
</tr>
<!-- <thead>
<tr>
<th>Name</th>
<th>Student Number</th>
<th>Group</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<img class="image-table" src="image/aiman_anizan.JPG" alt=""> <br>
<NAME>
</td>
<td>2018659558</td>
<td>CS110 5D</td>
<td>
<a href="mailto:<EMAIL>"><EMAIL></a>
</td>
</tr>
</tbody> -->
</table>
</div>
<!-- Content Delivery Network - JS -->
<?php include("component/cdn-js.php"); ?>
<!-- Customize Javascript -->
<script src="js/main.js"></script>
<script src="js/carousel-with-slider.js"></script>
<script>
$(()=>{
$('#about-page').addClass("active")
})
</script>
</body>
</html><file_sep>/admin/content/list-new-order.php
<?php
require_once("../../database/config.php");
$db = Database::getInstance();
$result_orders = $db -> query(" select orders.id as orders_id, orders.status_id as order_status, user.username as username, payment.id as payment_id, payment.purchased_at as purchased_date, payment.total as total_purchased, shipment.status as shipment_status, gateway.name as payment_gateway from orders inner join user on orders.user_id = user.id inner join payment on payment.orders_id = orders.id inner join shipment on shipment.id = payment.shipment_id inner join gateway on gateway.id = payment.gateway_id where orders.status_id = '2' and shipment.status = 'to ship'") or die("Query Error: ".$db -> error);
$orders = array();
if($result_orders -> num_rows > 0):
foreach($result_orders as $row):
$orders[] = $row;
endforeach;
// echo "<pre>",print_r($orders) , "</pre>";
endif;
?>
<?php if($orders != null): ?>
<?php foreach($orders as $order): ?>
<div class="card-panel z-depth-2" style="margin-bottom: 3rem;">
<div class="row">
<div class="col s12">
<span class="col s4">
<b class="details">Username</b>
<span> <b>: </b> <?php echo $order['username']; ?> </span>
</span>
<span class="col s4">
<b class="details">Payment Id</b>
<span> <b>: </b> <?php echo $order['payment_id']; ?> </span>
</span>
<span class="col s4">
<b class="details">Purchase Date</b>
<span> <b>: </b> <?php echo date("d F Y", strtotime($order['purchased_date'])); ?> </span>
</span>
<span class="col s4">
<b class="details">Orders Id</b>
<span> <b>: </b> <?php echo $order['orders_id']; ?> </span>
</span>
<span class="col s4">
<b class="details">Payment Gateway</b>
<span> <b>: </b> <?php echo $order['payment_gateway']; ?> </span>
</span>
<span class="col s4">
<b class="details">Shipping Status</b>
<b>: </b>
<span class="light-blue darken-1 white-text" style="padding: 0 0.5rem;">
<?php echo ucwords($order['shipment_status']); ?>
</span>
</span>
</div>
</div>
<!-- Display items with current orders id -->
<ol class="collection">
<?php
// begin query -- retrieve item added into cart with limit one image
$order_id = $db -> real_escape_string($order['orders_id']);
$total_price = 0;
$result_item = $db -> query("select item.id as item_id, product.name as product_name,product.price as price_per_item, item.quantity as item_quantity, item.price as item_price, image.id as image from item inner join product on item.product_id = product.id inner join image on image.product_id = product.id inner join orders on orders.id = item.orders_id where orders.id = '$order_id' group by item.id")
or die("query 1 failed");
while($data = $result_item -> fetch_assoc()):
$total_price += $data['item_price']; // add into variable -- used to store total of all product
?>
<li class="collection-item avatar black-text">
<img src="../database/retrieve-img.php?id=<?php echo $data['image']; ?>" alt="" class="circle">
<span class="title">
<h6>
<?php echo $data['product_name']; ?>
</h6>
</span>
<p>
  <b>RM <?php echo number_format($data['price_per_item'],2); ?> </b> x <?php echo $data['item_quantity']; ?> = <b class="light-blue-text text-darken-1">RM <?php echo number_format($data['item_price'],2); ?></b>
</p>
</li>
<?php endwhile; ?>
</ol>
<!-- Subtotal and button to received order -->
<div class="row">
<span class="col s12 right-align">
<button type="button" onclick="confirmbox_processShipment(<?php echo $order['payment_id']; ?>)" class="btn waves-effect waves-light light-blue darken-1" style="margin-right: 2rem;">
<i class="material-icons right">send</i>
Process Shipment
</button>
SUBTOTAL:  
<span class="light-blue-text text-darken-1" style="font-size: 1.3rem!important">
RM <?php echo number_format($order['total_purchased'],2); ?>
</span>
</span>
</div>
</div>
<?php endforeach; ?>
<?php else: ?>
<div class="card-panel z-depth-2" style="margin-bottom: 3rem;">
<h5>No Order</h5>
</div>
<?php endif; ?>
<file_sep>/js/carousel-with-slider.js
$(() => {
// add carousel with slider method from jquery
$(".carousel.carousel-slider").carousel({
fullWidth: true,
indicators: true
}, setTimeout(autoSlide, 4500));
function autoSlide(){
$('.carousel').carousel('next');
setTimeout(autoSlide,4500);
}
})<file_sep>/my-purchase.php
<?php
session_start();
// database class
require_once('database/config.php');
$db = Database::getInstance();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Purchase | Yeppel</title>
<link rel="shortcut icon" href="image/favicon2.png" type="image/x-icon">
<!-- Content Delivery Network - CSS -->
<?php include("component/cdn-css.php"); ?>
<!-- Customize CSS -->
<link rel="stylesheet" href="css/style.css">
<style>
.modal{
width: 20vw;
padding: 0 10px;
}
.details {
display: inline-block;
width: 6vw;
}
</style>
</head>
<body class="grey lighten-3">
<!-- Navigation bar -->
<?php include("component/navigation.php"); ?>
<div class="container">
<div class="row card-panel z-depth-5" style="margin: 3rem 0">
<div class="col s12">
<blockquote style="border-left-color: #039be5;">
<h3>My Purchase</h3>
</blockquote>
</div>
<div class="col s12">
<?php
// check if user already login
if(isset($_SESSION['id']) and isset($_SESSION['username'])):
// escape string
$user_id = $db -> real_escape_string($_SESSION['id']);
// begin query -- select complete order
$order = $db -> query("select id from orders where status_id = '2' and user_id='$user_id' order by orders.id desc") or die("Query failed: ".$db -> error);
// check row retrieved
if($order -> num_rows > 0):
// variable to store total price
$total_price = 0;
// looping -- display completed purchased product
foreach($order as $row):
// escape string
$order_id = $db -> real_escape_string($row['id']);
// begin query -- retrieved items purchased detail by orders id
$payment = $db -> query("SELECT payment.id as payment_id, payment.orders_id as orders_id, payment.purchased_at as purchase_date, shipment.status as shipment_status, shipment.id as shipment_id from payment inner join shipment on payment.shipment_id = shipment.id where payment.orders_id = '$order_id'") -> fetch_assoc() or die ("Error: ". $db -> error);
$subtotal = $db -> query("SELECT sum(price) as subtotal FROM item WHERE orders_id = '$order_id'") -> fetch_assoc()['subtotal'] or die("Query failed: ".$db -> error);
// begin query -- retrieve item added into cart with limit one image
$result = $db -> query("select item.id as item_id, product.name as product_name,product.price as price_per_item, item.quantity as item_quantity, item.price as item_price, image.id as image from item inner join product on item.product_id = product.id inner join image on image.product_id = product.id inner join orders on orders.id = item.orders_id where orders.id = '$order_id' group by item.id")
or die("query 1 failed");
// check if rows more thant one
if($result -> num_rows > 0):
// fetch associative array - store into a variable
?>
<!-- Display current order with card panel -->
<div class="card-panel z-depth-2" style="margin-bottom: 3rem;">
<div class="row">
<div class="col s12">
<span class="col s6">
<b class="details">Orders Id</b>
<span> <b>: </b> <?php echo $order_id; ?> </span>
</span>
<span class="col s6">
<b class="details">Payment Id</b>
<span> <b>: </b> <?php echo $payment['payment_id']; ?> </span>
</span>
<span class="col s6">
<b class="details">Purchase Date</b>
<span> <b>: </b> <?php echo date("d F Y", strtotime($payment['purchase_date'])); ?> </span>
</span>
<span class="col s6">
<b class="details">Shipping Status</b>
<?php
if(strtolower($payment['shipment_status']) == 'received'){
?>
<b>: </b>
<span class="green darken-1 white-text" style="padding: 0 0.5rem;">
<?php echo ucwords($payment['shipment_status']); ?>
</span>
<?php
}else {
?>
<b>: </b>
<span class="light-blue darken-1 white-text" style="padding: 0 0.5rem;">
<?php echo ucwords($payment['shipment_status']); ?>
</span>
<?php
}
?>
</span>
</div>
</div>
<!-- Display items with current orders id -->
<ol class="collection">
<?php
while($data = $result -> fetch_assoc()):
$total_price += $data['item_price']; // add into variable -- used to store total of all product
?>
<li class="collection-item avatar black-text">
<img src="database/retrieve-img.php?id=<?php echo $data['image']; ?>" alt="" class="circle">
<span class="title">
<h6>
<?php echo $data['product_name']; ?>
</h6>
</span>
<p>
  <b>RM <?php echo number_format($data['price_per_item'],2); ?> </b> x <?php echo $data['item_quantity']; ?> = <b class="light-blue-text text-darken-1">RM <?php echo number_format($data['item_price'],2); ?></b>
</p>
</li>
<?php endwhile; ?>
</ol>
<!-- Subtotal and button to received order -->
<div class="row">
<span class="col s12 right-align">
<?php
if(strtolower($payment['shipment_status']) == 'received'){
?>
<label class="btn green darken-1" style="margin-right: 2rem;">
<i class="material-icons right">check</i>
Completed
</label>
<?php
} else if (strtolower($payment['shipment_status']) == 'to receive') {
?>
<button type="button" onclick="received_order(<?php echo $payment['payment_id']; ?>)" class="btn waves-effect waves-light light-blue darken-1" style="margin-right: 2rem;">
Received Order
</button>
<?php
}else {
?>
<label class="btn light-blue darken-1" style="margin-right: 2rem;">
<i class="material-icons right">local_shipping</i>
Pending
</label>
<?php
}
?>
SUBTOTAL:  
<span class="light-blue-text text-darken-1" style="font-size: 1.3rem!important">
RM <?php echo number_format($subtotal,2); ?>
</span>
</span>
</div>
</div>
<?php
else:
goto display_none; // show display -- nothing added
endif;
endforeach;
goto skip_none; // skip display
else:
goto display_none;
endif;
// display this if user do not buy anything yet
display_none:
?>
<ol class="collection">
<li class="collection-item avatar black-text">
<span class="title">
<h6>
You had not purchased anything yet
</h6>
</span>
</li>
</ol>
<?php
else:
header("location: login-page.php");
endif;
?>
<!-- Skip here if user has buy at least one product -->
<?php skip_none: ?>
</div>
<?php if(isset($total_price) and $total_price > 0): // check if variable is set ?>
<div class="col s12">
<ul class="collection">
<li class="collection-item">
<div class="right-align">
TOTAL PURCHASED:  
<span class="light-blue-text text-darken-1" style="font-size: 1.8rem!important">
RM <?php echo number_format($total_price,2); ?>
</span>
</div>
</li>
</ul>
</div>
<?php endif; ?>
<div class="col s12">
<!-- <a href="index.php" class="btn waves-effect grey lighten-4 black-text right" style="margin-right: 1rem;">
Cancel
</a> -->
</div>
</div>
</div>
<div class="modal" id="modal-confirm-received" style="margin-top: 8rem;">
<div class="modal-content center">
<h3>
Received order?
</h3>
<button id="btn-confirm-received" class="btn btn-block waves-effect waves-light light-blue darken-1">
Yes
</button>
<button class="btn btn-block waves-effect waves-light white black-text modal-close">
No
</button>
</div>
</div>
<!-- Content Delivery Network - JS -->
<?php include("component/cdn-js.php"); ?>
<!-- Customize Javascript -->
<script>
var current_payment_id = "";
$(()=>{
$("#profile-page").addClass("active");
$("#btn-confirm-received").click(()=>{
// send post using jquery and load
$.post("database/confirm-received.php",
{
payment_id: current_payment_id
},
(data, status)=>{
if(data == "update success") {
window.location.reload(true);
}
})
})
})
function received_order ( payment_id) {
$(()=>{
$("#modal-confirm-received").modal("open");
current_payment_id = payment_id;
})
}
</script>
<script src="js/main.js"></script>
</body>
</html><file_sep>/component/navigation-admin.php
<?php
if (!isset($_SESSION['role']) or $_SESSION['role'] != 'admin') {
header("location: ../index.php");
echo '<script>alert("safdddfasdf");</script>';
}
?>
<div class="navbar-fixed">
<nav class="nav-wrapper light-blue darken-1">
<a href="index.php" class="brand-logo brand-heading">Yeppel</a>
<a href="#" class="sidenav-trigger" data-target="mobile-links">
<i class="material-icons">menu</i>
</a>
<ul class="right hide-on-med-and-down menu">
<li id="home-page" class=""><a href="homepage.php">Home</a></li>
<?php
/* Check if user already login or not */
if (isset($_SESSION['username'])) {
/* Output username at navigation bar */ ?>
<li id="profile-page"><a href="#" class="dropdown-trigger" data-target="dropdown-user">
<?php echo $_SESSION['username']; ?></a> <!-- Output username -- replaced login button -->
</li>
<ul id="dropdown-user" class="dropdown-content">
<li><a class="light-blue-text text-darken-1" href="profile-admin.php">My Account</a></li>
<li><a class="light-blue-text text-darken-1" href="../database/logout.php">Logout</a></li>
</ul>
<?php
} else {
?> <li><a href="login-page.php">Login</a></li> <?php // default login button -- useer did not login yet
}
?>
</ul>
<label class="brand-logo right cart tooltipped" data-position="left" data-tooltip="Administrator" style="margin-top: 0.2rem;"><i class="material-icons cart">person</i></label>
</nav>
</div><file_sep>/admin/content/change-availability.php
<?php
require_once("../../database/config.php");
$db = Database::getInstance();
$product_id = $db -> real_escape_string($_POST['product_id']);
$current_availability = $db -> query("SELECT availability_id FROM product WHERE id = '$product_id'") -> fetch_assoc()['availability_id'] or die('Query Error: '.$db -> error);
if($current_availability == '1') {
$db -> query("UPDATE product SET availability_id = '2' WHERE id = '$product_id'") or die ('Query Error: '.$db -> error);
} else {
$db -> query("UPDATE product SET availability_id = '1' WHERE id = '$product_id'") or die ('Query Error: '.$db -> error);
}
if($db -> affected_rows == 1) {
echo "changed";
}
?>
|
8020f0cadca39c1ac44cfd6a4ba89c3a2331b6a9
|
[
"JavaScript",
"Markdown",
"PHP"
] | 40
|
PHP
|
AimanAnizan56/YeppelGadget
|
c08a34caec75ce8dc2d7ec4ab6bca2645dce67a1
|
1807775991dcbd2b38ac4ce0a9da202430df7cc8
|
refs/heads/master
|
<repo_name>pcrubianoa/login<file_sep>/inc/config.php
<?
define ("PATH","login");
?><file_sep>/api/usuarios.php
<? session_start();
function __autoload($class_name) {
require_once "../mod/" . $class_name . '.php';
}
function row($value) {
echo "<tr class='registro' id='".$value['id']."'>
<td>".$value['id']."</td>
<td>".$value['nombre']."</td>
<td>".$value['grupo']."</td>
</tr>";
}
$usuario = new Usuario();
if ((isset($_GET['selectAll']))&&(isset($_GET['selector']))) {
echo "<option value='' disabled>Seleccione...</option>";
if ($regs = $usuario->selectAll())
foreach ($regs as $key => $value) {
echo "<option value='".$value['id']."'>".$value['nombre']."</option>";
}
}
elseif (isset($_GET['selectAll'])) {
$usuario->setJoin("B.nombre AS grupo","grupos B","A.id_grupo = B.id");
$usuario->limit($_POST['pag'].",50");
if ($regs = $usuario->selectAll())
foreach ($regs as $key => $value) {
row($value);
}
}
elseif (isset($_GET['selectOnce'])) {
$regs = $usuario->selectOnce($_POST['id']);
echo json_encode($regs);
}
elseif ((isset($_POST['id']))&&(!isset($_GET['delete']))) {
foreach ($_POST as $campo => $value) {
if ($campo!="id") {
$funcion = "set".ucwords($campo);
$usuario->$funcion($value);
}
}
if ($_POST['id']=="") {
$usuario->insert();
$regs = $usuario->last();
$_POST['id']=$regs['id'];
}
elseif (!isset($_GET['selectOnce'])) {
$usuario->update($_POST['id']);
}
$usuario->setJoin("B.nombre AS grupo","grupos B","A.id_grupo = B.id");
$value = $usuario->selectOnce($_POST['id']);
row($value);
} else {
$usuario->delete($_POST['id']);
}?><file_sep>/mod/config.php
<? @session_start();
define('DB_HOST', 'localhost');
define('DB_NAME', 'logis_users');
define('DB_USER', 'root');
define('DB_PASS', '<PASSWORD>');
?><file_sep>/inc/header.php
<? session_start();
require_once 'config.php';
$path = $_SERVER['DOCUMENT_ROOT']."/".PATH;
$_SESSION['path'] = $_SERVER['DOCUMENT_ROOT']."/".PATH;
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$dir = "https://".$_SERVER['SERVER_NAME']."/".PATH;
} else {
$dir = "http://".$_SERVER['SERVER_NAME']."/".PATH;
}
define("MODULO",$modulo);
//if (!isset($_SESSION['id_usuario'])) header("Location:$dir");
?>
<!DOCTYPE html>
<html lang="es">
<head>
<title>Logis | <? echo $modulo!='' ? $modulo : "Bienvenido";?></title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="shortcut icon" href="<?echo $dir;?>/img/favicon.png" type="image/x-icon"/>
<!-- Bootstrap CSS -->
<!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">-->
<link rel="stylesheet" href="<?echo $dir;?>/css/bootstrap/bootstrap.min.css" >
<link rel="stylesheet" href="<?echo $dir;?>/css/bootstrap/bootstrap-switch.css" >
<link rel="stylesheet" href="<?echo $dir;?>/css/jquery/jquery.ui.css">
<!-- Own Style -->
<link rel="stylesheet" type="text/css" href="<?echo $dir;?>/css/style.css">
<link rel="stylesheet" type="text/css" href="<?echo $dir;?>/css/fonts.css">
<link rel="stylesheet" href="<?echo $dir;?>/lib/fonts/css/all.css">
</head><file_sep>/mod/Crud.php
<? @session_start();
require_once 'DB.php';
abstract class Crud extends DB {
protected $table;
public $select="A.*";
public $where="";
public $order="";
public $group="";
public $limit="";
public $joinSelect="";
public $joinFrom="";
abstract public function insert();
public function setJoin($select, $from="", $where="") {
if ($select == "") {
$this->joinSelect = "";
$this->joinFrom = "";
$this->where="";
} else {
$this->joinSelect .= ", ".$select;
$this->joinFrom .= ", ".$from;
if ($this->where=="")
$this->where="WHERE ".$where;
else
$this->where.=" AND ".$where;
}
}
public function select($select) {
$this->select .= ", ".$select;
}
public function where($where) {
if ($where=="")
$this->where="";
elseif ($this->where=="")
$this->where="WHERE ".$where;
else
$this->where.=" AND ".$where;
}
public function order($order,$p="ASC") {
if ($order=="")
$this->order="";
elseif ($this->order=="")
$this->order = "ORDER BY ".$order. " ".$p;
else
$this->order .= ", ".$order;
}
public function group($group) {
if ($group=="")
$this->group="";
elseif ($this->group=="")
$this->group = "GROUP BY ".$group;
else
$this->group .= ", ".$group;
}
public function limit($limit) {
$this->limit = "LIMIT ".$limit;
}
public function result($stmt) {
$array=array();
if ($stmt)
while ($rec = mysqli_fetch_assoc($stmt)) {
$array[] = $rec;
}
return $array;
}
public function resultOnce($stmt) {
if ($stmt)
$array = mysqli_fetch_assoc($stmt);
return $array;
}
public function selectOnce($id,$table="A") {
if ($this->where=="")
$this->where .= "WHERE ".$table.".id=".$id;
else
$this->where .= " AND ".$table.".id=".$id;
$sql = "SELECT ".$this->select." ".$this->joinSelect." FROM ".$this->table." A".$this->joinFrom." ".$this->where." ".$this->group." ".$this->order." ".$this->limit;
//$sql = "SELECT A.* FROM ".$this->table." AS A WHERE A.id = ".$id;
$stmt = DB::execute($sql);
return self::resultOnce($stmt);
}
public function query($sql) {
if ($stmt = DB::execute($sql))
return self::result($stmt);
}
public function queryNR($sql) {
$stmt = DB::execute($sql);
}
public function selectAll() {
$sql = "SELECT ".$this->select." ".$this->joinSelect." FROM ".$this->table." A".$this->joinFrom." ".$this->where." ".$this->group." ".$this->order." ".$this->limit;
$stmt = DB::execute($sql);
return self::result($stmt);
}
public function findBetween($a, $b) {
$sql = "SELECT ".$this->table.".*".$this->func." FROM ".$this->table.$this->extra.$this->order." LIMIT $a, $b";
$stmt = DB::execute($sql);
return self::result($stmt);
}
public function last() {
$sql = "SELECT MAX(id) AS id FROM ".$this->table.$this->where;
$stmt = DB::execute($sql);
return self::resultOnce($stmt);
}
public function countRegs($sql="") {
if ($sql=="")
$sql = "SELECT DISTINCT (A.id), ".$this->select." ".$this->joinSelect." FROM ".$this->table." A".$this->joinFrom." ".$this->where." ".$this->group." ".$this->order." ".$this->limit;
$stmt = DB::execute($sql);
$regs = mysqli_num_rows($stmt);
return $regs;
}
public function delete($id) {
$sql = "DELETE FROM ".$this->table." WHERE id = ".$id." LIMIT 1";
$stmt = DB::execute($sql);
}
public function updateField($field,$value,$id) {
$sql = "UPDATE ".$this->table." SET ".$field."='".$value."' WHERE ".$this->table.".id = ".$id." LIMIT 1";
$stmt = DB::execute($sql);
}
public function sum($field) {
$sql = "SELECT SUM($field) AS $field FROM ".$this->table." ".$this->where;
if ($stmt = DB::execute($sql)) {
$array = mysqli_fetch_assoc($stmt);
$sum = $array[$field];
return $sum;
}
}
}
?>
<file_sep>/index.php
<? session_start();
include("lang/es/index.php");
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?echo NOMBRE_APP; ?> | Bienvenido</title>
<link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon"/>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/fontawesome-all.min.css">
<link rel="stylesheet" type="text/css" href="css/iofrm-style.css">
<link rel="stylesheet" type="text/css" href="css/iofrm-theme1.css">
</head>
<body>
<div class="form-body" class="container-fluid">
<div class="website-logo">
<a href="./">
<div class="logo">
<img height="" src="images/logo_logis.png" alt="">
</div>
</a>
</div>
<div class="row">
<div class="img-holder">
<div class="bg"></div>
<div class="info-holder">
</div>
</div>
<div class="form-holder">
<div class="form-content">
<div class="form-items">
<h3>Bienvenido!</h3>
<br>
<form action="./res/validacion/" method="POST">
<input class="form-control" type="text" name="usuario" placeholder="Usuario" required autofocus>
<input class="form-control" type="password" name="clave" placeholder="<PASSWORD>" required>
<div class="form-button">
<button id="submit" type="submit" class="ibtn">Ingresar</button>
</div>
</form>
<?
if (isset($_GET['code'])) {
if ($_GET['code']=='402') { ?>
<p>
Nombre de usuario o clave incorrectos.<br>
</p>
<?}
if ($_GET['code']=='403') { ?>
<p>
Acceso no autorizado.
</p>
<?}
if (isset($_GET['timeout'])) { ?>
<p>
Sesión caducada por inactividad.<br>
</p>
<?}
}?>
<div class="other-links">
<span>Powered by</span><a target="_BLANK" href="http://pclinea.com.co"><img height="30" src="./images/logo.png"></a>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/popper.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html><file_sep>/inc/inc.php
<? include $path."/inc/footer.php"; ?>
<? include $path."/inc/toast.php";?>
<? include $path."/inc/report.php";?>
<? include $path."/inc/emergente.php";?><file_sep>/lang/en/index.php
<?
define("NOMBRE_APP","Logis");
define("BIENVENIDO", "Welcome To ");
define("LABEL_USUARIO","Username");
define("LABEL_CLAVE","Password");
define ("BOTON_CREAR","Create");
define ("BOTON_EDITAR","Edit");
define ("BOTON_GUARDAR","Save");
define ("BOTON_INICIAR","Sesion Start");
define ("BOTON_AGREGAR","<span class='glyphicon glyphicon-plus'></span> New");
define ("BOTON_BUSCAR","<span class='glyphicon glyphicon-search'></span> Search");
define("TEXT_CARGANDO", "Loading...");
?><file_sep>/mod/DB.php
<? @session_start();
require_once 'config.php';
class DB {
private static $conn;
public static function getInstance() {
try {
self::$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME,"3306");
self::$conn->set_charset("utf8");
} catch (Exception $e){
echo "Error 101. Falló la conexión con MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
return self::$conn;
}
public static function execute($sql) {
$stmt = self::getInstance();
try {
return $stmt->query($sql);
$stmt->close();
} catch (Exception $e) {
echo "Error 102. Error realizando operación: " . $e;
}
}
}
?><file_sep>/res/validacion/index.php
<? session_start();
unset($_SESSION['empresa']);
function __autoload($class_name) {
require_once "../../mod/" . $class_name . '.php';
}
$data = explode('.', $_POST['usuario']);
$hoy = strtotime(date('Ymd'));
$usuario = new Usuario();
$usuario->where("A.usuario = '".$_POST['usuario']."'");
$usuario->setJoin("B.DB, B.fecha_caducidad","empresas B","B.id = A.id_empresa AND B.DB = '".$data[1]."'");
$usuario->limit(1);
if($usu = $usuario->selectAll()) {
$_SESSION['id_empresa'] = $usu[0]['id_empresa'];
$venc = strtotime($usu[0]['fecha_caducidad']);
$diff = round(($venc - $hoy) / 86400);
$_SESSION['limit_days'] = $diff;
if ($diff >= 0)
header("Location:../../../app/res/validacion/?usuario=".$data[0]."&clave=".$_POST["clave"]."&empresa=".$data[1]);
else {
header("Location:../../../account/res/validacion/?key=".$data[0]."&empresa=".$data[1]);
}
} else {
header("Location:../../?code=402");
}
unset($usuario);
?><file_sep>/inc/js.php
<!-- JQuery -->
<script src="<?echo $dir;?>/js/jquery/jquery-3.3.1.js"></script>
<script src="<?echo $dir;?>/js/jquery/popper.min.js"></script>
<script src="<?echo $dir;?>/js/jquery/jquery.validate.js"></script>
<script src="<?echo $dir;?>/js/bootstrap/bootstrap.min.js"></script>
<script src="<?echo $dir;?>/js/bootstrap/bootstrap-switch.js"></script>
<script src="<?echo $dir;?>/js/jquery/jquery.ui.js"></script>
<script src="<?echo $dir;?>/js/jquery/jquery.PrintArea.js"></script>
<!-- Librerias Propias -->
<!-- Controlador Funciones Globales -->
<script type="text/javascript" src="<?echo $dir;?>/js/init.js"></script>
<file_sep>/mod/Usuario.php
<?
require_once 'Crud.php';
class Usuario extends Crud {
protected $table = 'usuarios';
private $nombre=""; public function setNombre($nombre) { $this->nombre = $nombre;}
private $usuario=""; public function setUsuario($usuario) { $this->usuario = $usuario;}
private $clave=""; public function setClave($clave) { $this->clave = md5($clave);}
private $id_grupo=""; public function setId_grupo($id_grupo) { $this->id_grupo = $id_grupo;}
public function __construct() {
self::order("A.nombre");
}
public function insert() {
$sql = "INSERT INTO ".$this->table." (nombre,usuario,clave,id_grupo) VALUES (";
$sql .= "'".$this->nombre."',";
$sql .= "'".$this->usuario."',";
$sql .= "'".$this->clave."',";
$sql .= "'".$this->id_grupo."'";
$sql .= ")";
try {
$stmt = DB::execute($sql);
} catch (Exception $e) {
echo "Error 201. Error insertando registro" . $e;
}
}
public function update($id) {
$sql = "UPDATE ".$this->table." SET ";
$sql .= " `nombre` = '".$this->nombre."',";
$sql .= " `usuario` = '".$this->usuario."',";
$sql .= " `id_grupo` = '".$this->id_grupo."'";
$sql .= " WHERE id = ".$id." LIMIT 1";
try {
$stmt = DB::execute($sql);
} catch (Exception $e) {
echo "Error 201. Error actualizando registro" . $e;
}
}
public function actualizarClave($id,$field,$value) {
$value = md5($value);
$sql = "UPDATE ".$this->table." SET `".$field."` = '".$value."' WHERE id = ".$id." LIMIT 1";
$stmt = DB::execute($sql);
}
}
?><file_sep>/index_.php
<? session_start();
include("lang/es/index.php");
require_once "inc/header.php";
?>
<body>
<div class="container-fluid text-center mt-5">
<h1>
<?echo NOMBRE_APP; ?>
</h1>
<div class="row mt-5">
<div class="col-md-6 offset-md-3">
<!-- Inicio CardView -->
<div class="card text-center">
<div class="card-header">
<strong><?echo BIENVENIDO.NOMBRE_APP; ?></strong>
</div>
<div class="card-body">
<form name="session_start" action="./res/validacion/" method="POST" class="row">
<div class="form-group text-left col-md-6">
<label for="usuario"><?echo LABEL_USUARIO; ?></label>
<input type="text" class="form-control" id="usuario" name="usuario" placeholder="<?echo LABEL_USUARIO; ?>" required autofocus>
</div>
<div class="form-group text-left col-md-6">
<label for="clave"><?echo LABEL_CLAVE; ?></label>
<input type="password" class="form-control" id="clave" name="clave" placeholder="<?echo LABEL_CLAVE; ?>" required>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-outline-primary text-center" value="<? echo BOTON_INICIAR; ?>">
</div>
</form>
<!-- Fin Tab Configuración -->
</div>
<!-- Fin CardView -->
</div>
</div>
</div>
<?
if (isset($_GET['error'])) {
if ($_GET['error']=='402') { ?>
<div class="col-md-6 offset-md-3 alert alert-danger mt-5">
Nombre de usuario o clave incorrectos!!! :(<br>
Verifique los datos e intente de nuevo.<br>
</div>
<?}
if ($_GET['error']=='403') { ?>
<div class="col-md-6 offset-md-3 alert alert-danger mt-5">
Acceso no autorizado!!!<br>
Ingreso las credenciales de inicio de sesión.<br>
</div>
<?}
}
$datetime1 = new DateTime('2018-05-31');
$datetime2 = new DateTime(date('Y-m-d'));
$interval = $datetime1->diff($datetime2);
/*
if ((isset($_GET['time']))||($interval->format('%a')>15)) { ?>
<div class="col-md-6 offset-md-3 alert alert-danger mt-5">
El periodo de prueba ha finalizado!!! :(<br>
Comuniquese ahora con un asesor comercial.<br>
Tel. (1)8900900 - 300 200 2914
</div>
<?}
if (($interval->format('%a')>10)&&($interval->format('%a')<16)) {
$dias = 16-$interval->format('%a');
?>
<div class="col-md-6 offset-md-3 alert alert-info mt-5">
Restan <?echo $dias;?> para finalizar el periodo de prueba<br>
Comuniquese ahora con un asesor comercial.<br>
Tel. (1)8900900 - 300 200 2914
</div>
<?}*/?>
</div>
<? //include("inc/toast.php");?>
</body>
</html>
<!--
<script type="text/javascript" src="js/init.js"></script>
<script type="text/javascript">
$(document).ready(function(){
toastConfirm();
});
</script>
-->
<file_sep>/lang/es/index.php
<?
define("NOMBRE_APP","Logis");
define("BIENVENIDO", "Bienvenido a ");
define("LABEL_USUARIO","Usuario");
define("LABEL_CLAVE","Clave");
define ("BOTON_CREAR","Crear");
define ("BOTON_EDITAR","Editar");
define ("BOTON_GUARDAR","<span class='fas fa-save'></span> Guardar");
define ("BOTON_IMPRIMIR","<span class='fas fa-print'></span>");
define ("BOTON_ACTUALIZAR","<span class='fas fa-save'></span> Actualizar");
define ("BOTON_CONTINUAR","Continuar <span class='fas fa-arrow-right'></span>");
define ("BOTON_INICIAR","Iniciar Sesión");
define ("BOTON_NUEVO","<span class='fas fa-plus'></span> Nuevo");
define ("BOTON_AGREGAR","<span class='glyphicon glyphicon-copy'></span> Agregar");
define ("BOTON_BUSCAR","<span class='fas fa-search'></span> Buscar");
define ("BOTON_CERRAR","<span class='fas fa-times'></span> Cerrar");
define ("BOTON_LIMPIAR","<span class='fas fa-eraser'></span> Borrar Busqueda");
define ("TAB_PROYECTOS","Proyectos");
define ("TAB_NUEVO","Nuevo");
define ("TAB_CONFIG","Configuración");
define("TEXT_CARGANDO", "Cargando...");
define("TEXT_CONFIRMA", "<span class='fas fa-bullhorn'></span> Operación Completada!");
?>
|
45c10646f53ef3316b4da1df17290c330fc0a3ed
|
[
"PHP"
] | 14
|
PHP
|
pcrubianoa/login
|
eb9b2594baf8453cc79292d26da633d06a636fd8
|
1035b75dbd789ee95ecaf9b88f210eff96aa4a9d
|
refs/heads/master
|
<repo_name>LuksSouza/FuntamentosJavaScript<file_sep>/js/hello.js
alert("Hello World com arquivo externo!");
var empresa = "Caelum";
empresa = empresa.replace("lum", "tano");
alert(empresa);
/*var soma = 0;
for (var i = 1; i < 101; i++) {
soma+=i;
}
alert("Soma: " + soma);*/
var pessoas = ["João", "José", "Maria", "Sebastião", "Antônio"];
for (var i = 0; i < pessoas.length; i++) {
if (pessoas[i].length == 4) {
alert("Nome com 4 caracteres: " + pessoas[i]);
}
}<file_sep>/js/functions.js
var titulo = document.querySelector("#titulo");
titulo.onclick = mostraQualquerCoisa;
function mostraQualquerCoisa() {
alert("Chamou a minha função!");
}<file_sep>/README.md
# FuntamentosJavaScript
Repositório dedicado a publicação de projetos de estudo sobre JavaScript
|
3528617197b9a3942f6e8da4083973ffcf9ef25c
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
LuksSouza/FuntamentosJavaScript
|
4f9ba1c719b17c83e6f63a156cda0ea9e78531f9
|
2873c69ea21a8f0ff73e71cb1878ae725263ae75
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Segment.Stats
{
public class Statistics
{
public uint Submitted { get; set; }
public uint Succeeded { get; set; }
public uint Failed { get; set; }
}
}
|
e49d337c52dd8a3d6812a44aecbc1ec3daa79364
|
[
"C#"
] | 1
|
C#
|
jzebedee/Analytics.NET
|
232ad2345de523de9ec01c8aef052bacf94e634a
|
d8f376e3168b26921a95f430b919564b2930117d
|
refs/heads/main
|
<file_sep>import math
import socket
import sys
import time
import errno
from multiprocessing import Process
ok_message = 'HTTP/1.0 200 OK\n\n'
nok_message = 'HTTP/1.0 404 Not Found\n\n'
def process_start(s_sock):
s_sock.send(str.encode("***Welcome to Online Calculator***\n"))
while True:
pilihan = s_sock.recv(2048).decode("utf-8").split(":")
if pilihan[0] == "A":
result = math.log(float(pilihan[1]))
elif pilihan[0] == "B":
result = math.sqrt(float(pilihan[1]))
elif pilihan[0] == "C":
result = math.exp(float(pilihan[1]))
elif pilihan[0] not in 'ABC':
result = math.exp(float(0))
elif pilihan[0] == "Q":
break
s_sock.sendall(str.encode(str(result)))
s_sock.close()
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 8888))
print("Listening...")
s.listen(3)
try:
while True:
try:
s_sock,s_addr = s.accept()
print ("\nConnection from : ", s_addr)
p = Process(target = process_start,args = (s_sock,))
p.start()
except socket.error:
print('got a socket error')
except Exception as e:
print('an exception occured!')
print(e)
<file_sep>import sys
import socket
clientSocket = socket.socket()
host = '192.168.56.104'
port = 8888
print("Waiting for connection")
try:
clientSocket.connect((host, port))
except socket.error as e:
print(str(e))
response = clientSocket.recv(1024)
print(response.decode())
while True:
option = input('Choose mathematical function, A -Logarithmic, B -Square Root, C -Exponential or Q to quit: ')
if option == 'A' or option == 'B' or option == 'C':
value = input("Enter a value: ")
option = option + ":" + value
clientSocket.send(str.encode(option))
response = clientSocket.recv(1024)
print(response.decode("utf-8"))
elif option == 'Q':
print("Quiting app.")
clientSocket.send(str.encode(option))
sys.exit()
else:
print("Invalid input! Enter only A,B,C")
print("Please try again.")
option = "0"
clientSocket.send(str.encode(option))
response = clientSocket.recv(1024)
print('***********')
clientSocket.close()
|
6dff81a811e833714ac32ae10ef4f7aef1da36d5
|
[
"Python"
] | 2
|
Python
|
amirulikmal99/Lab6
|
0730936710811c5a9d22a6dbfd321058edf925ee
|
c518d4e3d6aa240d9ca6d0bcb868dd6422b3d26f
|
refs/heads/master
|
<file_sep>class CreateHelps < ActiveRecord::Migration
def change
create_table :helps do |t|
t.string :content
t.string :time
t.string :reward
t.string :user_id
t.timestamps
end
add_index :helps, :user_id
end
end
<file_sep>class AddInfoToUser < ActiveRecord::Migration
def change
add_column :users, :true_name, :string
add_column :users, :sex, :string
add_column :users, :birthday, :string
add_column :users, :university, :string
add_column :users, :school_year, :string
add_column :users, :love_status, :string
add_column :users, :location, :string
end
end
<file_sep>class ReportsController < ApplicationController
before_filter :authenticate
before_filter :authorized_user, :only => :destroy
def show
@report = Report.find(params[:id])
end
def create
@report = current_user.reports.build(params[:report])
if @report.save
redirect_to home_path, :flash =>{ :success =>"发布成功!"}
else
@feed_items = []
render 'pages/home'
end
end
def destroy
@report.destroy
redirect_to home_path, :flash =>{ :success =>"删除成功!"}
end
private
def authorized_user
@report = Report.find(params[:id])
redirect_to root_path unless current_user?(@report.user)
end
end
<file_sep># -*- coding: utf-8 -*-
module ApplicationHelper
def error_messages_for(object_name, options = {})
options = options.symbolize_keys
object = instance_variable_get("@#{object_name}")
unless object.errors.empty?
error_lis = []
object.errors.each{ |key, msg| error_lis << content_tag("li", msg) }
content_tag("div", content_tag(options[:header_tag] || "h2", "发生#{object.errors.count}个错误" ) + content_tag("ul", error_lis), "id" => options[:id] || "errorExplanation", "class" => options[:class] || "errorExplanation" )
end
end
end
<file_sep>class PagesController < ApplicationController
def home
if signed_in?
@micropost = Micropost.new
@report = Report.new
@help = Help.new
@feed_items = current_user.feed.paginate( :page => params[:page])
@feed_helps = current_user.feed_help.paginate( :page => params[:page])
@feed_reports = current_user.feed_report.paginate( :page => params[:page])
#评论
@comment = @micropost.comments.build
@micropost.comments.pop
end
end
def friends
end
def groups
end
def activities
end
end
<file_sep>class HelpsController < ApplicationController
before_filter :authenticate
before_filter :authorized_user, :only => :destroy
def show
@help = Help.find(params[:id])
end
def create
@help = current_user.helps.build(params[:help])
if @help.save
redirect_to home_path, :flash =>{ :success =>"发布成功!"}
else
@feed_items = []
render 'pages/home'
end
end
def destroy
@help.destroy
redirect_to home_path, :flash =>{ :success =>"删除成功!"}
end
private
def authorized_user
@help = Help.find(params[:id])
redirect_to root_path unless current_user?(@help.user)
end
end
<file_sep>class Comment < ActiveRecord::Base
attr_accessible :comment, :commentable_id, :commentable_type
include ActsAsCommentable::Comment
belongs_to :commentable, :polymorphic => true
default_scope -> { order('created_at ASC') }
# NOTE: install the acts_as_votable plugin if you
# want user to vote on the quality of comments.
#acts_as_voteable
# NOTE: Comments belong to a user
belongs_to :user
private
def self.followed_by(user)
followed_ids = %(SELECT followed_id FROM relationships
WHERE follower_id = :user_id)
where("user_id IN(#{followed_ids}) OR user_id = :user_id ",
:user_id => user)
end
end
<file_sep># nihong社交网站
刚学rails时候的一个sns网站。
|
1147523dd458853a92a615713d3459d88212eccf
|
[
"Markdown",
"Ruby"
] | 8
|
Ruby
|
kouunn/nihong
|
44133cbeffd6bc3b64ac76e0e5a8c38c9c4fa0ec
|
26535ae59c60efba057604ebddbbb65e1320f959
|
refs/heads/master
|
<repo_name>Dep-Testings/web-pos-frontend<file_sep>/src/app/manage-items/manage-items.component.ts
/**
* @author : <NAME> <<EMAIL>>
* @since : 11/26/20
**/
import manageItems from './manage-items.component.html';
import style from './manage-items.component.scss';
import '../../../node_modules/admin-lte/plugins/datatables/jquery.dataTables.min.js';
import '../../../node_modules/admin-lte/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js';
import '../../../node_modules/admin-lte/plugins/datatables-responsive/js/dataTables.responsive.min.js';
import '../../../node_modules/admin-lte/plugins/datatables-responsive/js/responsive.bootstrap4.min.js';
import { getAllItems } from '../service/item.service';
import { Item } from '../model/item';
$("app-manage-items").replaceWith('<div id="manage-items">' + manageItems + '</div>');
var html = '<style>' + style + '</style>';
$("#dashboard").append(html);
async function loadAllItems(){
let items = await getAllItems();
for (const item of items){
$("#tbl-items tbody").append(`
<tr>
<td>${item.itemCode}</td>
<td>${item.description}</td>
<td>${item.qty}</td>
<td>${item.unitPrice}</td>
<td><i class="fas fa-trash"></i></td>
</tr>
`);
}
($("#tbl-items") as any).DataTable({
"info": false,
"searching": false,
"lengthChange": false,
"pageLength": 5,
});
}
loadAllItems();
<file_sep>/src/app/service/item.service.ts
import { Item } from '../model/item';
//let customers: Customer[] = [];
let items: Array<Item> = [];
export function getAllItems(): Promise<Array<Item>>{
//to-do:
return new Promise((resolve, reject)=>{
// 1.Initiate a XMLHttpRequest //sometimes may have two steps
let http = new XMLHttpRequest();
// 2. setting up the call back function
http.onreadystatechange = function (){
if (http.readyState ===4){
//console.log(http.responseText);
items = JSON.parse(http.responseText);
resolve(items);
// if(http.readyState === 4){
// let dom = $(http.responseXML as any);
// console.log(dom.find("table").html());
// $(dom).find("item").each((index, elm)=>{
// let itemCode = $(elm).find("code").text();
// let description = $(elm).find("description").text();
// let qty = $(elm).find("qty").text();
// let unitPrice = $(elm).find("unit-price").text();
// items.push(new Item(itemCode, description, qty, unitPrice));
// });
// resolve(items);
// }
}
}
// 3. open the request
http.open('GET', 'http://localhost:8080/pos/items', true);
// 4. if we have to set headers
// 5.
http.send();
/* for (let i = 0; i < 50; i++) {
// new Customer('C'+i, 'Kasun', 'Galle')
customers.push(new Customer(`C${i}`, 'Kasun', 'Galle'));
} */
});
}<file_sep>/src/app/model/item.ts
export class Item{
constructor(public itemCode: string, public description: string ,
public qty: string, public unitPrice: String){
}
}
|
6e01a340fe1d76fa6e847007c476b2e8f8d03ff7
|
[
"TypeScript"
] | 3
|
TypeScript
|
Dep-Testings/web-pos-frontend
|
4ecb5544916a93207e472352adfb00d2b7aa6ba9
|
cb3c77f4cafcdc562dda8a44eff9bf9abb0b5ad8
|
refs/heads/master
|
<file_sep>processo = "1000"
sei = window.open("https://sei.sistemas.ro.gov.br/sei/");
setTimeout(
function(){
pesquisa = sei.document.getElementById("frmProtocoloPesquisaRapida");
pesquisa.elements[0].value = processo;
pesquisa.submit();
}, 3000);
<file_sep>//imacros-js:showsteps yes
function getcode(url) {
ret = iimPlay("CODE:URL GOTO=" + url +
"\nTAG POS=1 TYPE=BODY ATTR=TXT:* EXTRACT=TXT\n");
extract = iimGetExtract(1);
return extract;
}
function Macro(iim) {
this.url = "https://raw.githubusercontent.com/franklinbaldo/macros/master/rpv/" + iim + ".iim";
this.code = getcode(this.url);
this.play = iimPlay(this.code);
}
function waitForString(string) { //use essa função para fazer o imacros esperar até uma string aparecer na página
extract = "";
var stringNotFound = true;
while (stringNotFound) {
iimPlay("CODE:TAG POS=1 TYPE=* ATTR=TXT:" + string + " EXTRACT=TXT");
extract = iimGetExtract();
stringNotFound = extract == "#EANF#";
}
iimDisplay("found string");
return extract;
}
function hermescomenta(processo, comentario) { //cria um comentario no hermes
if(hermesmacro === null){
hermesmacro = new Macro("hermescomenta");
}
iimSet("PROCESSO", processo);
iimSet("COMENTARIO", comentario);
hermesmacro.play();
extract = iimGetExtract();
iimDisplay(display);
return extract;
}
function extrairTabela(url,tab) {
if(extrairTabelamacro === null){
extrairTabelamacro = new Macro("hermescomenta");
}
tabisundefined = typeof tab === "undefined";
if (tabisundefined) {
tab = 1;
}
iimSet("TAB", tab);
iimSet("URL", url);
extrairTabelamacro.play();
extract = iimGetExtract(1);
newarray = extract.split("\n");
for (linha in extract) {
var novo = linha.split('","');
newarray.push(novo);
};
return extract;
}
//imacros-js:showsteps yes
extrairTabela("1","https://docs.google.com/spreadsheets/d/1ssErjk-e_BLdxtf8NkNMceRzvByC9WSHvCepDCafV08/gviz/tq?tqx=out:html&tq=select+C,+D,+E,+F,+G,+H+where+J=true&gid=1538920654");
<file_sep>var CriarMacro = function getcode (url) {
this.url = url
ret = iimPlay ("CODE:VERSION BUILD=844 RECORDER=CR\n" +
"TAB T=1\n" +
"TAB CLOSEALLOTHERS\n" +
"URL GOTO=" + url +
"\nTAG POS=1 TYPE=BODY ATTR=TXT:* EXTRACT=TXT\n" );
extract = iimGetExtract(1);
this.code = "CODE:"+extract};
var loop = 0;
getloop = new CriarMacro("https://raw.githubusercontent.com/franklinbaldo/macros/master/pje/getloop.iim");
peticionar = new CriarMacro("https://raw.githubusercontent.com/franklinbaldo/macros/master/pje/peticionar.iim");
logon = new CriarMacro("https://raw.githubusercontent.com/franklinbaldo/macros/master/pje/logon.iim");
ret = iimPlay (getloop.code);
loop = iimGetExtract();
ret = iimPlay (logon.code);
for (i=0;i<loop;i++){
iimPlay(peticionar.code)};
<file_sep>function abrirExpediente(idExpediente) {
let grau = (window.location.href+"").includes("\/pg\/")?"\/pg":"\/sg";
let idProcesso = (window.document.querySelectorAll("input[title$='detalhes do processo']")[0].onclick+"").match(/\?id=([^&]*)&/)[1];
let url = grau+'/Painel/painel_usuario/popup/visualizarExpediente.seam?idPpe=' + idExpediente + '&idProcesso=' + idProcesso;
let u = window.open(url);
setTimeout(function() {
u.close();
}, 2000);
}
Array.from(window.document.querySelector("tbody[id='formExpedientes:tbExpedientes:tb']").rows).map(e => e.firstChild.id.split(":")[2]).forEach(abrirExpediente);
<file_sep>return "Hello"
|
c48d4fdf8459640becb06fbf9a1a23601ff24884
|
[
"JavaScript"
] | 5
|
JavaScript
|
franklinbaldo/macros
|
b286b8a11850f73ad65c9ce42261d74a27f9e160
|
3678311c9fa1158cc29dd5f418d93d969aa163f5
|
refs/heads/main
|
<file_sep>// let { add, multiply } = require("./cleverFunctions");
// let cleverFunctions = require("./cleverFunctions")
// console.log(multiply(2, 3));
// console.log(cleverFunctions.add(5, 5))
// import { add, multiply } from "./cleverFunctions.js";
import cleverFunctions, { multiply as times } from "./cleverFunctions.js";
console.log(cleverFunctions);
console.log(times);
console.log("hi there from the feature branch")
<file_sep>const add = (num1, num2) => {
return num1 + num2;
};
export const multiply = (num1, num2) => {
return num1 * num2;
};
// module.exports = {
// add,
// multiply,
// };
export default add;
|
1adee792d13769e536ee8d0dad0d21a6f3f356ac
|
[
"JavaScript"
] | 2
|
JavaScript
|
benmaudslay/m28-node-demo
|
a11571c0d1e8881e31cdd6ee1f8be5cd370b4c8e
|
f4e878bc51ea1f98f0772a0a2c511ff60deded2a
|
refs/heads/master
|
<repo_name>rdcx/assemble<file_sep>/models/node.js
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var nodeSchema = new Schema({
name: String,
ip: String,
created_at: Date,
updated_at: Date
});
var Node = mongoose.model('Node', nodeSchema);
// make this available to our users in our Node applications
module.exports = Node;
<file_sep>/controllers/main/index.js
exports.index = function(req, res){
res.redirect('/nodes');
};
<file_sep>/controllers/container/index.js
/**
* Module dependencies.
*/
var Container = require('../../models/container');
exports.engine = 'ejs';
exports.before = function(req, res, next){
var container = db.containers[req.params.container_id];
if (!container) return next('route');
req.container = container;
next();
};
exports.show = function(req, res, next){
res.render('show', { container: req.container });
};
exports.edit = function(req, res, next){
res.render('edit', { container: req.container });
};
exports.update = function(req, res, next){
var body = req.body;
req.container.name = body.container.name;
req.container.image = body.container.image;
res.message('Information updated!');
res.redirect('/container/' + req.container.id);
};
<file_sep>/controllers/node/index.js
/**
* Module dependencies.
*/
var Node = require('../../models/node');
exports.before = function(req, res, next) {
var id = req.params.node_id;
if (!id) return next();
// pretend to query a database...
process.nextTick(function() {
Node.findOne({
_id: id
}, function(err, node) {
req.node = node;
// cant find that host
if (!req.node) return next('route');
// found it, move on to the routes
next();
});
});
};
exports.list = function(req, res, next) {
Node.find({}, function(err, nodes) {
res.render('list', {
nodes: nodes
});
});
};
exports.edit = function(req, res, next) {
res.render('edit', {
node: req.node
});
};
exports.add = function(req, res, next) {
res.render('add');
};
exports.create = function(req, res, next) {
var body = req.body;
var node = new Node({
name: body.node.name,
ip: body.node.ip
});
console.log(node);
node.save(function(err) {
if (err) throw err;
res.message('Information updated!');
res.redirect('/node/' + node._id);
});
};
exports.show = function(req, res, next) {
var docker = require('docker-remote-api');
var request = docker({
host: '/var/run/docker.sock'
});
request.get('/containers/json', {
json: true
}, function(err, containers) {
if (err) throw err
console.log('containers', containers)
// res.render('show', {
// node: req.node
// });
});
};
exports.update = function(req, res, next) {
var body = req.body;
req.node.name = body.node.name;
res.message('Information updated!');
res.redirect('/host/' + req.node.id);
};
<file_sep>/Readme.md
# Docker Assemble
|
91e470d6c0404568df7897fd94d8b15121083970
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
rdcx/assemble
|
c9607dae6206a19714c3330b2fbd6f4989edfe4a
|
7b530ed4072c23fa47526306e729196d1e3e1559
|
refs/heads/master
|
<repo_name>joker314/unofficial-camper<file_sep>/ADMIN.js
module.exports = [
{
"on": "message",
"wantsArgs": true,
"cmd": "warn",
"prefix": true,
"then": (msg, command, data, args) => {
// As this is a moderator command,
// The user must either be of "modRoles" or
if(!msg.member) {
msg.reply("Please do this in the admin chat, **on the server**.")
return;
}
if(msg.member.hasPermission("BAN_MEMBERS", false, true, true)) {
let modChannel = data.client.storage.get("MOD CHANNEL")
console.log(modChannel)
if(!modChannel) {
msg.reply({
embed: {
color: 0xff0000,
title: "Could not give warning",
description: "I could not warn the user because there is no moderator log channel. This channel should be public. Use `!modchannel #channel`."
}
})
} else {
if(!msg.mentions.users.size) {
msg.reply({
embed: {
color: 0xff0000,
title: "Could not give warning",
description: "I could not warn the user because you didn't mention one!"
}
})
} else {
data.client.channels.get(modChannel).send(msg.mentions.users.array().join(" ") + " have been officially **warned** by an admin.", {
embed: {
color: 0x000000,
title: "Official Warning",
description: "This is an official warning. Stop doing what you're doing please",
fields: [{
name: "Users being warned",
value: msg.mentions.users.array().join(", "),
inline: true
}, {
name: "Moderator making warning",
value: msg.author + "",
inline: true
}, {
name: "Reason",
value: args.join(" ")
}]
}
})
}
}
}
}
},
{
"on": "message",
"wantsArgs": true,
"cmd": "modchannel",
"prefix": true,
"then": (msg, command, data, args) => {
if(msg.member.hasPermission("BAN_MEMBERS", false, true, true)) {
let channels = (msg.content.match(/<#\d+>/g) || []).map(x => x.replace(/[<>#]/g, ""));
if(channels.length) {
data.client.storage.set("MOD CHANNEL", channels[0])
msg.reply({
embed: {
color: 0x00ff00,
title: "Set channel",
description: "I managed to set the channel!"
}
})
} else {
msg.reply({
embed: {
color:0xff0000,
title: "Failed to set channel",
description: "You didn't #mention the channel"
}
})
}
}
}
},
{
"on": "guildBanAdd",
"then": (data, guild, user) => {
guild.fetchAuditLogs()
.then(audit => {
if(data.client.storage.get("MOD CHANNEL")) {
data.client.channels.get(data.client.storage.get("MOD CHANNEL")).send({
embed: {
title: "User banned",
color: 0xffaa00,
description: audit.entries.first().target + " was banned by " + audit.entries.first().executor,
fields: [{
name: "Reason",
value: audit.entries.first().reason || "<no reason was given>"
}]
}
})
}
})
}
},
{
"on": "guildBanAdd",
"then": (data, guild, user) => {
guild.fetchAuditLogs()
.then(audit => {
if(data.client.storage.get("MOD CHANNEL")) {
data.client.channels.get(data.client.storage.get("MOD CHANNEL")).send({
embed: {
title: "User banned",
color: 0xffaa00,
description: audit.entries.first().target + " was banned by " + audit.entries.first().executor,
fields: [{
name: "Reason",
value: audit.entries.first().reason || "<no reason was given>"
}]
}
})
}
})
}
}
]
<file_sep>/USER.js
// This is the user module. It interacts with user profiles.
/*
* Colour coding for embeds
* GREEN = OKAY (e.g. brownie points sent)
* MAGENTA = WARN (e.g. deleted non-existant data)
* RED = ERR (e.g. invalid param)
*/
module.exports = [
{
"on": "message",
"then": (data, msg) => {
console.log("msg", msg.content)
if(/\bt(h|hn|hnk)?(y|q|x)(sm)?\b|thank\s(yo)?u/g.test(msg.content)) {
console.log`checkpoint + 0`
if(msg.mentions.users.size) {
console.log`checkpoint + 1`
msg.mentions.members.forEach(member => {
console.log`checkpoint + 2`
if(data.client.storage.get(member.user.id) === null) {
member.user.send("Hi! I'm a bot over at the freeCodeCamp unofficial server. I've now remembered that your user account has **1** unofficial brownie point. If you want this data removed, please respond somewhere with `" + data.prefix + "dataclear` and leave the server. I won't ever remember **new** information about someone who leaves the server, but you must remember to use the `" + data.prefix + "dataclear` command. **I won't message you about this issue again until you clear the data**")
}
console.log`checkpoint + 3`
console.log(data.client.storage.get(member.user.id) + " => " + ((data.client.storage.get(member.user.id) || 0) + 1))
data.client.storage.set(member.user.id, (data.client.storage.get(member.user.id) || 0) + 1)
msg.channel.send("Send 1 brownie point to " + member + " TOTAL = " + data.client.storage.get(member.user.id))
})
}
}
}
},
{
"on": "message",
"cmd": "dataclear",
"prefix": true,
"then": (data, msg) => {
console.log("Clearing data...")
const existed = data.client.storage.get(msg.author.id) !== null
data.client.storage.delete(msg.author.id)
msg.reply({
embed: {
color: existed ? 0x00ff00 : 0xff00ff,
title: "All data removed",
description: "I removed all the data I had about you in my memory." + (existed ? "" : " However, I wasn't storing any data about you anyway!")
}
})
}
}
]
<file_sep>/index.js
// A Discord bot to interact with freeCodeCamp; and to moderate freeCodeCamp-oriented chatrooms.
const Discord = require("discord.js")
const client = new Discord.Client()
// First, let's get our "database" up and running
const Enmap = require("enmap")
const EnmapLevel = require("enmap-level")
const provider = new EnmapLevel({name: "fcc"})
client.storage = new Enmap({provider})
// Here, we pull in all modules. When adding or removing a module, you'll need to do so here,
// as well as actually removing the file itself.
const modules = [
require("./PONG.js"),
require("./HELP.js"),
require("./USER.js"),
require("./MISC.js"),
require("./ADMIN.js"),
];
const prefix = "!";
// Here, we pluck out each module, and then from each one of those modules, we register event
// listeners for their commands.
modules.forEach(module => {
module.forEach(command => {
client.on(command.on, (...args) => {
if(command.on === "message") {
if(args[0].author.bot) return; // isn't a bot
if(command.prefix && !args[0].content.startsWith(prefix)) return; // starts with prefix
if(command.cmd && !args[0].content.startsWith((command.prefix ? prefix : "") + command.cmd)) return; // starts with command
console.log("REACHED HERE")
if(command.wantsArgs) {
let split = args[0].content.split(" ")
command.then(args[0], split[0], {prefix, client}, split.slice(1))
} else {
command.then({prefix, client}, args[0])
}
} else {
command.then({prefix, client}, ...args)
}
})
})
})
// And once everything is hooked up, we can log in.
client.login("CLIENT TOKEN GOES HERE")
<file_sep>/README.md
# unofficial-camper
An bot designed to interact with unofficial Discord servers which discuss freeCodeCamp
|
85a6fc91890a9cff79e3104126533cd605c5bf5e
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
joker314/unofficial-camper
|
86e9a10f9c5298747e7e011976f158dbbcb677fa
|
94f821e0e7ecea68697b2a5f72ce80c3f98d449d
|
refs/heads/master
|
<repo_name>nordbjorn/learntocode<file_sep>/README.md
# learntocode
Studying Projects
<file_sep>/app/views/listings/show.json.jbuilder
json.extract! @listing, :id, :name, :secription, :price, :created_at, :updated_at
|
295a7cdcd29748c7e454fe6c69830c377be63684
|
[
"Markdown",
"Ruby"
] | 2
|
Markdown
|
nordbjorn/learntocode
|
112631a454b083ca0b060f1d6404ae71d182ec1b
|
d0a61314e7be9f042b1e1c469954cd78e28b1aa4
|
refs/heads/master
|
<repo_name>AyranaGabriela/sd-admin-2<file_sep>/src/main/resources/data.sql
INSERT INTO contatos (nome,email) VALUES ('<NAME>','<EMAIL>');
INSERT INTO contatos (nome,email) VALUES ('<NAME>','<EMAIL>');
INSERT INTO contatos (nome,email) VALUES ('<NAME>','<EMAIL>');
INSERT INTO contatos (nome,email) VALUES ('<NAME>','<EMAIL>');
INSERT INTO contatos (nome,email) VALUES ('<NAME>','<EMAIL>');<file_sep>/src/main/java/br/com/service/ContatoService.java
/**
*
*/
package br.com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import br.com.model.Contato;
import br.com.repository.ContatosRepository;
/**
* @author carlosbarbosagomesfilho
*
*/
@Service
public class ContatoService {
@Autowired
private ContatosRepository repository;
@Transactional(readOnly=true)
public List<Contato> list(){
return this.repository.findAll();
}
@Transactional
public void save(Contato contato) {
this.repository.save(contato);
}
@Transactional
public void remove(Long id) {
this.repository.delete(id);
}
@Transactional(readOnly=true)
public Contato getById(Long id) {
return this.repository.findOne(id);
}
}
<file_sep>/src/main/java/br/com/controller/ContatosController.java
package br.com.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.model.Contato;
import br.com.service.ContatoService;
@Controller
@RequestMapping("/contatos")
public class ContatosController {
@Autowired
private ContatoService service;
@GetMapping
public ModelAndView listar() {
List<Contato> lista = service.list();
ModelAndView modelAndView = new ModelAndView("pages/contato/contatos");
modelAndView.addObject("contatos", lista);
return modelAndView;
}
@GetMapping("/delete/{id}")
public ModelAndView excluir(@PathVariable Long id, RedirectAttributes attributes) {
ModelAndView mv = new ModelAndView("redirect:/contatos");
this.service.remove(id);
attributes.addFlashAttribute("removido", "Contato removido com sucesso!");
return mv;
}
@GetMapping("/edit/{id}")
public ModelAndView edit(@PathVariable("id") Long id) {
Contato contato = this.service.getById(id);
System.out.println(contato.getNome());
return novo(contato);
}
@GetMapping("/novo")
public ModelAndView novo(Contato contato) {
ModelAndView mv = new ModelAndView("pages/contato/novo_contato");
mv.addObject("contato", contato);
return mv;
}
@PostMapping("/save")
public ModelAndView salvar(@Valid Contato contato, BindingResult result, Model model, RedirectAttributes attributes){
ModelAndView mv = new ModelAndView("redirect:/contatos");
if (result.hasErrors()) {
return novo(contato);
}
attributes.addFlashAttribute("mensagem", "Contato salvo com sucesso");
this.service.save(contato);
return mv;
}
}
|
3925aa36b4bb871592ad004f13bd14c43085405e
|
[
"Java",
"SQL"
] | 3
|
SQL
|
AyranaGabriela/sd-admin-2
|
9bd5d8910b5423ad9caecb5c1c8bea6a4730cfe6
|
f3ef72f4870187cc4cdeac7cc140a8f86b7e0711
|
refs/heads/master
|
<file_sep>package org.csveed.bean.conversion;
import static org.csveed.bean.conversion.ConversionUtil.hasLength;
public class CustomBooleanConverter extends AbstractConverter<Boolean> {
public static final String VALUE_TRUE = "true";
public static final String VALUE_FALSE = "false";
public static final String VALUE_ON = "on";
public static final String VALUE_OFF = "off";
public static final String VALUE_YES = "yes";
public static final String VALUE_NO = "no";
public static final String VALUE_1 = "1";
public static final String VALUE_0 = "0";
private final String trueString;
private final String falseString;
private final boolean allowEmpty;
public CustomBooleanConverter(boolean allowEmpty) {
this(null, null, allowEmpty);
}
public CustomBooleanConverter(String trueString, String falseString, boolean allowEmpty) {
super(Boolean.class);
this.trueString = trueString;
this.falseString = falseString;
this.allowEmpty = allowEmpty;
}
@Override
public Boolean fromString(String text) throws Exception {
String input = (text != null ? text.trim() : null);
if (this.allowEmpty && !hasLength(input)) {
return null;
}
else if (this.trueString != null && input.equalsIgnoreCase(this.trueString)) {
return Boolean.TRUE;
}
else if (this.falseString != null && input.equalsIgnoreCase(this.falseString)) {
return Boolean.FALSE;
}
else if (this.trueString == null &&
(input.equalsIgnoreCase(VALUE_TRUE) || input.equalsIgnoreCase(VALUE_ON) ||
input.equalsIgnoreCase(VALUE_YES) || input.equals(VALUE_1))) {
return Boolean.TRUE;
}
else if (this.falseString == null &&
(input.equalsIgnoreCase(VALUE_FALSE) || input.equalsIgnoreCase(VALUE_OFF) ||
input.equalsIgnoreCase(VALUE_NO) || input.equals(VALUE_0))) {
return Boolean.FALSE;
}
else {
throw new IllegalArgumentException("Invalid boolean value [" + text + "]");
}
}
@Override
public String toString(Boolean value) throws Exception {
if (Boolean.TRUE.equals(value)) {
return (this.trueString != null ? this.trueString : VALUE_TRUE);
}
else if (Boolean.FALSE.equals(value)) {
return (this.falseString != null ? this.falseString : VALUE_FALSE);
}
else {
return "";
}
}
}
<file_sep>package org.csveed.bean;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.csveed.common.Column;
import org.junit.Test;
public class DynamicColumnTest {
@Test
public void advanceAndReset() {
int startColumn = 5;
int numberOfColumns = 7;
DynamicColumn column = new DynamicColumn(new Column(startColumn));
for (int i = 0; i < numberOfColumns - startColumn + 1; i++) {
column.advanceDynamicColumn();
assertFalse("Must not be at first column now", column.atFirstDynamicColumn());
column.checkForReset(numberOfColumns);
}
assertTrue("Must be at first dynamic column now", column.atFirstDynamicColumn());
}
@Test
public void weHaveNoDynamicColumns() {
DynamicColumn column = new DynamicColumn(null);
column.advanceDynamicColumn(); // should have no effect
assertTrue("Must be at first dynamic column now", column.atFirstDynamicColumn()); // always the case if empty
}
@Test
public void activeDynamicColumns() {
Column activeColumn = new Column(4);
Column inactiveColumn = new Column(5);
DynamicColumn dynamicColumn = new DynamicColumn(activeColumn);
assertTrue("Column "+activeColumn.getColumnIndex()+" must be active", dynamicColumn.isDynamicColumnActive(activeColumn));
assertFalse("Column "+inactiveColumn.getColumnIndex()+" must be active", dynamicColumn.isDynamicColumnActive(inactiveColumn));
}
}
<file_sep>import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
public class RandoopTests {
public static boolean debug = false;
@Test
public void test01() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test01");
org.csveed.common.Column column0 = null;
try {
org.csveed.common.Column column1 = new org.csveed.common.Column(column0);
org.junit.Assert.fail("Expected exception of type java.lang.NullPointerException; message: null");
} catch (java.lang.NullPointerException e) {
}
}
@Test
public void test02() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test02");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
java.lang.String str8 = column0.getExcelColumn();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertTrue("'" + str8 + "' != '" + "A" + "'", str8.equals("A"));
}
@Test
public void test03() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test03");
int int0 = org.csveed.common.Column.FIRST_COLUMN_INDEX;
org.junit.Assert.assertTrue("'" + int0 + "' != '" + 1 + "'", int0 == 1);
}
@Test
public void test04() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test04");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
org.csveed.common.Column column3 = new org.csveed.common.Column();
org.csveed.common.Column column4 = new org.csveed.common.Column();
int int5 = column3.compareTo(column4);
int int6 = column1.compareTo(column4);
int int7 = column1.getColumnIndex();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + int5 + "' != '" + 0 + "'", int5 == 0);
org.junit.Assert.assertTrue("'" + int6 + "' != '" + 0 + "'", int6 == 0);
org.junit.Assert.assertTrue("'" + int7 + "' != '" + 1 + "'", int7 == 1);
}
@Test
public void test05() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test05");
org.csveed.common.Column column1 = new org.csveed.common.Column("A");
}
@Test
public void test06() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test06");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
org.csveed.common.Column column3 = new org.csveed.common.Column();
org.csveed.common.Column column4 = new org.csveed.common.Column();
int int5 = column3.compareTo(column4);
int int6 = column1.compareTo(column3);
column3.setColumnIndex((int) '#');
org.csveed.common.Column column9 = new org.csveed.common.Column();
org.csveed.common.Column column10 = new org.csveed.common.Column();
int int11 = column9.compareTo(column10);
column9.setColumnName("");
org.csveed.common.Column column15 = new org.csveed.common.Column(10);
int int16 = column9.compareTo(column15);
org.csveed.common.Column column17 = column15.nextLine();
int int18 = column3.compareTo(column17);
org.csveed.api.Header header19 = null;
org.csveed.common.Column column20 = column3.setHeader(header19);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + int5 + "' != '" + 0 + "'", int5 == 0);
org.junit.Assert.assertTrue("'" + int6 + "' != '" + 0 + "'", int6 == 0);
org.junit.Assert.assertTrue("'" + int11 + "' != '" + 0 + "'", int11 == 0);
org.junit.Assert.assertTrue("'" + int16 + "' != '" + 1 + "'", int16 == 1);
org.junit.Assert.assertNotNull(column17);
org.junit.Assert.assertTrue("'" + int18 + "' != '" + 1 + "'", int18 == 1);
org.junit.Assert.assertNotNull(column20);
}
@Test
public void test07() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test07");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
org.csveed.common.Column column3 = new org.csveed.common.Column(column0);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
}
@Test
public void test08() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test08");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
java.lang.String str5 = column0.toString();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + str5 + "' != '" + "Column Name: " + "'", str5.equals("Column Name: "));
org.junit.Assert.assertNotNull(column7);
}
@Test
public void test09() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test09");
org.csveed.common.Column column0 = new org.csveed.common.Column();
java.lang.String str1 = column0.getColumnName();
java.lang.Class<?> wildcardClass2 = column0.getClass();
org.junit.Assert.assertNull(str1);
org.junit.Assert.assertNotNull(wildcardClass2);
}
@Test
public void test10() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test10");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
java.lang.Class<?> wildcardClass5 = column0.getClass();
java.lang.String str6 = column0.getColumnText();
java.lang.String str7 = column0.getExcelColumn();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(wildcardClass5);
org.junit.Assert.assertTrue("'" + str6 + "' != '" + " index 1 (A) name \"\"" + "'", str6.equals(" index 1 (A) name \"\""));
org.junit.Assert.assertTrue("'" + str7 + "' != '" + "A" + "'", str7.equals("A"));
}
@Test
public void test11() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test11");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
int int6 = column5.getColumnIndex();
org.csveed.common.Column column7 = new org.csveed.common.Column();
org.csveed.common.Column column8 = new org.csveed.common.Column();
int int9 = column7.compareTo(column8);
column7.setColumnName("");
org.csveed.common.Column column12 = column7.nextColumn();
org.csveed.api.Header header13 = null;
org.csveed.common.Column column14 = column7.setHeader(header13);
org.csveed.api.Header header15 = null;
org.csveed.common.Column column16 = column14.setHeader(header15);
int int17 = column16.getColumnIndex();
int int18 = column5.compareTo(column16);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertTrue("'" + int6 + "' != '" + 2 + "'", int6 == 2);
org.junit.Assert.assertTrue("'" + int9 + "' != '" + 0 + "'", int9 == 0);
org.junit.Assert.assertNotNull(column12);
org.junit.Assert.assertNotNull(column14);
org.junit.Assert.assertNotNull(column16);
org.junit.Assert.assertTrue("'" + int17 + "' != '" + 1 + "'", int17 == 1);
org.junit.Assert.assertTrue("'" + int18 + "' != '" + (-1) + "'", int18 == (-1));
}
@Test
public void test12() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test12");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
org.csveed.common.Column column3 = new org.csveed.common.Column();
org.csveed.common.Column column4 = new org.csveed.common.Column();
int int5 = column3.compareTo(column4);
int int6 = column1.compareTo(column3);
column3.setColumnIndex((int) '#');
java.lang.String str9 = column3.getColumnText();
org.csveed.common.Column column10 = column3.nextColumn();
java.lang.String str11 = column10.getExcelColumn();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + int5 + "' != '" + 0 + "'", int5 == 0);
org.junit.Assert.assertTrue("'" + int6 + "' != '" + 0 + "'", int6 == 0);
org.junit.Assert.assertTrue("'" + str9 + "' != '" + " index 35 (AI)" + "'", str9.equals(" index 35 (AI)"));
org.junit.Assert.assertNotNull(column10);
org.junit.Assert.assertTrue("'" + str11 + "' != '" + "AJ" + "'", str11.equals("AJ"));
}
@Test
public void test13() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test13");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
org.csveed.api.Header header8 = null;
org.csveed.common.Column column9 = column7.setHeader(header8);
org.csveed.common.Column column10 = new org.csveed.common.Column();
org.csveed.common.Column column11 = new org.csveed.common.Column();
int int12 = column10.compareTo(column11);
column10.setColumnName("");
java.lang.Class<?> wildcardClass15 = column10.getClass();
org.csveed.api.Header header16 = null;
org.csveed.common.Column column17 = column10.setHeader(header16);
boolean boolean18 = column9.equals((java.lang.Object) header16);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertNotNull(column9);
org.junit.Assert.assertTrue("'" + int12 + "' != '" + 0 + "'", int12 == 0);
org.junit.Assert.assertNotNull(wildcardClass15);
org.junit.Assert.assertNotNull(column17);
org.junit.Assert.assertTrue("'" + boolean18 + "' != '" + false + "'", boolean18 == false);
}
@Test
public void test14() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test14");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
java.lang.Class<?> wildcardClass3 = column1.getClass();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(wildcardClass3);
}
@Test
public void test15() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test15");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
column0.setColumnName("");
java.lang.String str10 = column0.getColumnText();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertTrue("'" + str10 + "' != '" + " index 1 (A) name \"\"" + "'", str10.equals(" index 1 (A) name \"\""));
}
@Test
public void test16() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test16");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
org.csveed.api.Header header8 = null;
org.csveed.common.Column column9 = column7.setHeader(header8);
org.csveed.api.Header header10 = null;
org.csveed.common.Column column11 = column7.setHeader(header10);
java.lang.Class<?> wildcardClass12 = column7.getClass();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertNotNull(column9);
org.junit.Assert.assertNotNull(column11);
org.junit.Assert.assertNotNull(wildcardClass12);
}
@Test
public void test17() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test17");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
org.csveed.api.Header header8 = null;
org.csveed.common.Column column9 = column7.setHeader(header8);
org.csveed.api.Header header10 = null;
org.csveed.common.Column column11 = column9.setHeader(header10);
org.csveed.common.Column column12 = new org.csveed.common.Column();
org.csveed.common.Column column13 = new org.csveed.common.Column();
int int14 = column12.compareTo(column13);
column12.setColumnName("");
org.csveed.common.Column column17 = column12.nextColumn();
org.csveed.api.Header header18 = null;
org.csveed.common.Column column19 = column12.setHeader(header18);
column12.setColumnName("");
org.csveed.common.Column column22 = column12.nextLine();
int int23 = column11.compareTo(column22);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertNotNull(column9);
org.junit.Assert.assertNotNull(column11);
org.junit.Assert.assertTrue("'" + int14 + "' != '" + 0 + "'", int14 == 0);
org.junit.Assert.assertNotNull(column17);
org.junit.Assert.assertNotNull(column19);
org.junit.Assert.assertNotNull(column22);
org.junit.Assert.assertTrue("'" + int23 + "' != '" + 1 + "'", int23 == 1);
}
@Test
public void test18() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test18");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
org.csveed.common.Column column3 = new org.csveed.common.Column();
org.csveed.common.Column column4 = new org.csveed.common.Column();
int int5 = column3.compareTo(column4);
int int6 = column1.compareTo(column4);
column1.setColumnName("hi!");
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + int5 + "' != '" + 0 + "'", int5 == 0);
org.junit.Assert.assertTrue("'" + int6 + "' != '" + 0 + "'", int6 == 0);
}
@Test
public void test19() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test19");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
java.lang.Class<?> wildcardClass5 = column0.getClass();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
int int8 = column0.getColumnIndex();
int int9 = column0.getColumnIndex();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(wildcardClass5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertTrue("'" + int8 + "' != '" + 1 + "'", int8 == 1);
org.junit.Assert.assertTrue("'" + int9 + "' != '" + 1 + "'", int9 == 1);
}
@Test
public void test20() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test20");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
java.lang.String str6 = column0.getColumnName();
org.csveed.common.Column column7 = new org.csveed.common.Column(column0);
org.csveed.common.Column column8 = column0.nextLine();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertTrue("'" + str6 + "' != '" + "" + "'", str6.equals(""));
org.junit.Assert.assertNotNull(column8);
}
@Test
public void test21() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test21");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column6 = new org.csveed.common.Column(10);
int int7 = column0.compareTo(column6);
org.csveed.api.Header header8 = null;
org.csveed.common.Column column9 = column6.setHeader(header8);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + int7 + "' != '" + 1 + "'", int7 == 1);
org.junit.Assert.assertNotNull(column9);
}
@Test
public void test22() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test22");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
java.lang.String str5 = column0.toString();
org.csveed.common.Column column6 = column0.nextLine();
java.lang.String str7 = column0.getColumnName();
org.csveed.api.Header header8 = null;
org.csveed.common.Column column9 = column0.setHeader(header8);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + str5 + "' != '" + "Column Name: " + "'", str5.equals("Column Name: "));
org.junit.Assert.assertNotNull(column6);
org.junit.Assert.assertTrue("'" + str7 + "' != '" + "" + "'", str7.equals(""));
org.junit.Assert.assertNotNull(column9);
}
@Test
public void test23() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test23");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
int int6 = column5.getColumnIndex();
java.lang.String str7 = column5.getColumnText();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertTrue("'" + int6 + "' != '" + 2 + "'", int6 == 2);
org.junit.Assert.assertTrue("'" + str7 + "' != '" + " index 2 (B)" + "'", str7.equals(" index 2 (B)"));
}
@Test
public void test24() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test24");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
java.lang.Class<?> wildcardClass5 = column0.getClass();
org.csveed.common.Column column6 = column0.nextLine();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(wildcardClass5);
org.junit.Assert.assertNotNull(column6);
}
@Test
public void test25() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test25");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
org.csveed.api.Header header8 = null;
org.csveed.common.Column column9 = column7.setHeader(header8);
org.csveed.api.Header header10 = null;
org.csveed.common.Column column11 = column9.setHeader(header10);
java.lang.String str12 = column11.getColumnName();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertNotNull(column9);
org.junit.Assert.assertNotNull(column11);
org.junit.Assert.assertTrue("'" + str12 + "' != '" + "" + "'", str12.equals(""));
}
@Test
public void test26() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test26");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
org.csveed.common.Column column3 = column0.nextColumn();
java.lang.String str4 = column0.getExcelColumn();
org.csveed.common.Column column5 = new org.csveed.common.Column();
org.csveed.common.Column column6 = new org.csveed.common.Column();
int int7 = column5.compareTo(column6);
column5.setColumnName("");
org.csveed.common.Column column11 = new org.csveed.common.Column(10);
int int12 = column5.compareTo(column11);
column5.setColumnName(" index 35 (AI)");
int int15 = column0.compareTo(column5);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column3);
org.junit.Assert.assertTrue("'" + str4 + "' != '" + "A" + "'", str4.equals("A"));
org.junit.Assert.assertTrue("'" + int7 + "' != '" + 0 + "'", int7 == 0);
org.junit.Assert.assertTrue("'" + int12 + "' != '" + 1 + "'", int12 == 1);
org.junit.Assert.assertTrue("'" + int15 + "' != '" + (-1) + "'", int15 == (-1));
}
@Test
public void test27() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test27");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
java.lang.String str6 = column0.getColumnName();
org.csveed.api.Header header7 = null;
org.csveed.common.Column column8 = column0.setHeader(header7);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertTrue("'" + str6 + "' != '" + "" + "'", str6.equals(""));
org.junit.Assert.assertNotNull(column8);
}
@Test
public void test28() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test28");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column6 = new org.csveed.common.Column(10);
int int7 = column0.compareTo(column6);
column0.setColumnName("hi!");
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + int7 + "' != '" + 1 + "'", int7 == 1);
}
@Test
public void test29() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test29");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
org.csveed.common.Column column3 = new org.csveed.common.Column();
org.csveed.common.Column column4 = new org.csveed.common.Column();
int int5 = column3.compareTo(column4);
int int6 = column1.compareTo(column3);
column3.setColumnIndex((int) '#');
org.csveed.common.Column column9 = new org.csveed.common.Column();
org.csveed.common.Column column10 = new org.csveed.common.Column();
int int11 = column9.compareTo(column10);
column9.setColumnName("");
org.csveed.common.Column column15 = new org.csveed.common.Column(10);
int int16 = column9.compareTo(column15);
org.csveed.common.Column column17 = column15.nextLine();
int int18 = column3.compareTo(column17);
int int19 = column3.getColumnIndex();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + int5 + "' != '" + 0 + "'", int5 == 0);
org.junit.Assert.assertTrue("'" + int6 + "' != '" + 0 + "'", int6 == 0);
org.junit.Assert.assertTrue("'" + int11 + "' != '" + 0 + "'", int11 == 0);
org.junit.Assert.assertTrue("'" + int16 + "' != '" + 1 + "'", int16 == 1);
org.junit.Assert.assertNotNull(column17);
org.junit.Assert.assertTrue("'" + int18 + "' != '" + 1 + "'", int18 == 1);
org.junit.Assert.assertTrue("'" + int19 + "' != '" + 35 + "'", int19 == 35);
}
@Test
public void test30() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test30");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
java.lang.String str6 = column0.getColumnName();
column0.setColumnName("hi!");
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertTrue("'" + str6 + "' != '" + "" + "'", str6.equals(""));
}
@Test
public void test31() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test31");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
java.lang.Class<?> wildcardClass5 = column0.getClass();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
org.csveed.common.Column column8 = new org.csveed.common.Column();
org.csveed.common.Column column9 = new org.csveed.common.Column();
int int10 = column8.compareTo(column9);
org.csveed.common.Column column11 = new org.csveed.common.Column();
org.csveed.common.Column column12 = new org.csveed.common.Column();
int int13 = column11.compareTo(column12);
int int14 = column9.compareTo(column11);
column11.setColumnIndex((int) '#');
org.csveed.common.Column column17 = new org.csveed.common.Column();
org.csveed.common.Column column18 = new org.csveed.common.Column();
int int19 = column17.compareTo(column18);
column17.setColumnName("");
org.csveed.common.Column column23 = new org.csveed.common.Column(10);
int int24 = column17.compareTo(column23);
org.csveed.common.Column column25 = column23.nextLine();
int int26 = column11.compareTo(column25);
org.csveed.common.Column column27 = new org.csveed.common.Column();
org.csveed.common.Column column28 = new org.csveed.common.Column();
int int29 = column27.compareTo(column28);
org.csveed.common.Column column30 = new org.csveed.common.Column();
org.csveed.common.Column column31 = new org.csveed.common.Column();
int int32 = column30.compareTo(column31);
int int33 = column28.compareTo(column30);
column30.setColumnIndex((int) '#');
org.csveed.common.Column column36 = new org.csveed.common.Column();
org.csveed.common.Column column37 = new org.csveed.common.Column();
int int38 = column36.compareTo(column37);
column36.setColumnName("");
org.csveed.common.Column column42 = new org.csveed.common.Column(10);
int int43 = column36.compareTo(column42);
org.csveed.common.Column column44 = column42.nextLine();
int int45 = column30.compareTo(column44);
org.csveed.common.Column column46 = column44.nextLine();
int int47 = column25.compareTo(column44);
int int48 = column0.compareTo(column44);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(wildcardClass5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertTrue("'" + int10 + "' != '" + 0 + "'", int10 == 0);
org.junit.Assert.assertTrue("'" + int13 + "' != '" + 0 + "'", int13 == 0);
org.junit.Assert.assertTrue("'" + int14 + "' != '" + 0 + "'", int14 == 0);
org.junit.Assert.assertTrue("'" + int19 + "' != '" + 0 + "'", int19 == 0);
org.junit.Assert.assertTrue("'" + int24 + "' != '" + 1 + "'", int24 == 1);
org.junit.Assert.assertNotNull(column25);
org.junit.Assert.assertTrue("'" + int26 + "' != '" + 1 + "'", int26 == 1);
org.junit.Assert.assertTrue("'" + int29 + "' != '" + 0 + "'", int29 == 0);
org.junit.Assert.assertTrue("'" + int32 + "' != '" + 0 + "'", int32 == 0);
org.junit.Assert.assertTrue("'" + int33 + "' != '" + 0 + "'", int33 == 0);
org.junit.Assert.assertTrue("'" + int38 + "' != '" + 0 + "'", int38 == 0);
org.junit.Assert.assertTrue("'" + int43 + "' != '" + 1 + "'", int43 == 1);
org.junit.Assert.assertNotNull(column44);
org.junit.Assert.assertTrue("'" + int45 + "' != '" + 1 + "'", int45 == 1);
org.junit.Assert.assertNotNull(column46);
org.junit.Assert.assertTrue("'" + int47 + "' != '" + 0 + "'", int47 == 0);
org.junit.Assert.assertTrue("'" + int48 + "' != '" + 1 + "'", int48 == 1);
}
@Test
public void test32() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test32");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
org.csveed.api.Header header8 = null;
org.csveed.common.Column column9 = column7.setHeader(header8);
java.lang.Class<?> wildcardClass10 = column9.getClass();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertNotNull(column9);
org.junit.Assert.assertNotNull(wildcardClass10);
}
@Test
public void test33() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test33");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
org.csveed.api.Header header8 = null;
org.csveed.common.Column column9 = column7.setHeader(header8);
org.csveed.common.Column column10 = new org.csveed.common.Column();
org.csveed.common.Column column11 = new org.csveed.common.Column();
int int12 = column10.compareTo(column11);
column10.setColumnName("");
org.csveed.common.Column column15 = column10.nextColumn();
org.csveed.api.Header header16 = null;
org.csveed.common.Column column17 = column10.setHeader(header16);
org.csveed.api.Header header18 = null;
org.csveed.common.Column column19 = column17.setHeader(header18);
int int20 = column9.compareTo(column17);
org.csveed.common.Column column21 = column9.nextColumn();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertNotNull(column9);
org.junit.Assert.assertTrue("'" + int12 + "' != '" + 0 + "'", int12 == 0);
org.junit.Assert.assertNotNull(column15);
org.junit.Assert.assertNotNull(column17);
org.junit.Assert.assertNotNull(column19);
org.junit.Assert.assertTrue("'" + int20 + "' != '" + 0 + "'", int20 == 0);
org.junit.Assert.assertNotNull(column21);
}
@Test
public void test34() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test34");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.common.Column column6 = new org.csveed.common.Column(column5);
org.csveed.common.Column column7 = new org.csveed.common.Column();
org.csveed.common.Column column8 = new org.csveed.common.Column();
int int9 = column7.compareTo(column8);
column7.setColumnName("");
org.csveed.common.Column column12 = column7.nextColumn();
org.csveed.api.Header header13 = null;
org.csveed.common.Column column14 = column7.setHeader(header13);
org.csveed.api.Header header15 = null;
org.csveed.common.Column column16 = column14.setHeader(header15);
org.csveed.api.Header header17 = null;
org.csveed.common.Column column18 = column14.setHeader(header17);
column18.setColumnName(" index 1 (A) name \"\"");
int int21 = column6.compareTo(column18);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertTrue("'" + int9 + "' != '" + 0 + "'", int9 == 0);
org.junit.Assert.assertNotNull(column12);
org.junit.Assert.assertNotNull(column14);
org.junit.Assert.assertNotNull(column16);
org.junit.Assert.assertNotNull(column18);
org.junit.Assert.assertTrue("'" + int21 + "' != '" + (-1) + "'", int21 == (-1));
}
@Test
public void test35() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test35");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
org.csveed.common.Column column3 = new org.csveed.common.Column();
org.csveed.common.Column column4 = new org.csveed.common.Column();
int int5 = column3.compareTo(column4);
int int6 = column1.compareTo(column3);
column3.setColumnIndex((int) '#');
column3.setColumnName(" index 2 (B)");
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + int5 + "' != '" + 0 + "'", int5 == 0);
org.junit.Assert.assertTrue("'" + int6 + "' != '" + 0 + "'", int6 == 0);
}
@Test
public void test36() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test36");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
java.lang.Class<?> wildcardClass5 = column0.getClass();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
java.lang.String str8 = column7.getColumnText();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(wildcardClass5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertTrue("'" + str8 + "' != '" + " index 1 (A) name \"\"" + "'", str8.equals(" index 1 (A) name \"\""));
}
@Test
public void test37() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test37");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
java.lang.Class<?> wildcardClass5 = column0.getClass();
org.csveed.common.Column column6 = new org.csveed.common.Column(column0);
column6.setColumnIndex(0);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(wildcardClass5);
}
@Test
public void test38() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test38");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
java.lang.String str5 = column0.toString();
int int6 = column0.getColumnIndex();
column0.setColumnIndex((int) (byte) 0);
java.lang.String str9 = column0.getColumnName();
column0.setColumnName(" index 2 (B)");
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + str5 + "' != '" + "Column Name: " + "'", str5.equals("Column Name: "));
org.junit.Assert.assertTrue("'" + int6 + "' != '" + 1 + "'", int6 == 1);
org.junit.Assert.assertTrue("'" + str9 + "' != '" + "" + "'", str9.equals(""));
}
@Test
public void test39() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test39");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
org.csveed.api.Header header8 = null;
org.csveed.common.Column column9 = column7.setHeader(header8);
org.csveed.api.Header header10 = null;
org.csveed.common.Column column11 = column7.setHeader(header10);
column11.setColumnName(" index 1 (A) name \"\"");
column11.setColumnName(" index 35 (AI)");
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertNotNull(column9);
org.junit.Assert.assertNotNull(column11);
}
@Test
public void test40() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test40");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
org.csveed.api.Header header8 = null;
org.csveed.common.Column column9 = column7.setHeader(header8);
org.csveed.api.Header header10 = null;
org.csveed.common.Column column11 = column7.setHeader(header10);
int int12 = column11.getColumnIndex();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertNotNull(column9);
org.junit.Assert.assertNotNull(column11);
org.junit.Assert.assertTrue("'" + int12 + "' != '" + 1 + "'", int12 == 1);
}
@Test
public void test41() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test41");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
org.csveed.common.Column column3 = new org.csveed.common.Column();
org.csveed.common.Column column4 = new org.csveed.common.Column();
int int5 = column3.compareTo(column4);
int int6 = column1.compareTo(column3);
column3.setColumnIndex((int) '#');
org.csveed.common.Column column9 = new org.csveed.common.Column();
org.csveed.common.Column column10 = new org.csveed.common.Column();
int int11 = column9.compareTo(column10);
column9.setColumnName("");
org.csveed.common.Column column15 = new org.csveed.common.Column(10);
int int16 = column9.compareTo(column15);
org.csveed.common.Column column17 = column15.nextLine();
int int18 = column3.compareTo(column17);
org.csveed.common.Column column19 = column17.nextLine();
org.csveed.api.Header header20 = null;
org.csveed.common.Column column21 = column17.setHeader(header20);
org.csveed.common.Column column22 = column17.nextColumn();
org.csveed.api.Header header23 = null;
org.csveed.common.Column column24 = column22.setHeader(header23);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + int5 + "' != '" + 0 + "'", int5 == 0);
org.junit.Assert.assertTrue("'" + int6 + "' != '" + 0 + "'", int6 == 0);
org.junit.Assert.assertTrue("'" + int11 + "' != '" + 0 + "'", int11 == 0);
org.junit.Assert.assertTrue("'" + int16 + "' != '" + 1 + "'", int16 == 1);
org.junit.Assert.assertNotNull(column17);
org.junit.Assert.assertTrue("'" + int18 + "' != '" + 1 + "'", int18 == 1);
org.junit.Assert.assertNotNull(column19);
org.junit.Assert.assertNotNull(column21);
org.junit.Assert.assertNotNull(column22);
org.junit.Assert.assertNotNull(column24);
}
@Test
public void test42() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test42");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
column0.setColumnName("");
org.csveed.common.Column column10 = column0.nextLine();
java.lang.String str11 = column0.getColumnName();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertNotNull(column10);
org.junit.Assert.assertTrue("'" + str11 + "' != '" + "" + "'", str11.equals(""));
}
@Test
public void test43() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test43");
org.csveed.common.Column column1 = new org.csveed.common.Column(1);
column1.setColumnIndex((int) (byte) 100);
}
@Test
public void test44() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test44");
org.csveed.common.Column column1 = new org.csveed.common.Column("Column Name: ");
column1.setColumnIndex(0);
}
@Test
public void test45() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test45");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
column0.setColumnName("");
org.csveed.common.Column column10 = column0.nextColumn();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertNotNull(column10);
}
@Test
public void test46() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test46");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
org.csveed.common.Column column3 = new org.csveed.common.Column();
org.csveed.common.Column column4 = new org.csveed.common.Column();
int int5 = column3.compareTo(column4);
int int6 = column1.compareTo(column3);
column3.setColumnIndex((int) '#');
org.csveed.common.Column column9 = new org.csveed.common.Column();
org.csveed.common.Column column10 = new org.csveed.common.Column();
int int11 = column9.compareTo(column10);
column9.setColumnName("");
org.csveed.common.Column column15 = new org.csveed.common.Column(10);
int int16 = column9.compareTo(column15);
org.csveed.common.Column column17 = column15.nextLine();
int int18 = column3.compareTo(column17);
org.csveed.common.Column column19 = column17.nextLine();
org.csveed.api.Header header20 = null;
org.csveed.common.Column column21 = column17.setHeader(header20);
org.csveed.common.Column column22 = column17.nextColumn();
column22.setColumnName(" index 35 (AI)");
java.lang.String str25 = column22.getColumnName();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + int5 + "' != '" + 0 + "'", int5 == 0);
org.junit.Assert.assertTrue("'" + int6 + "' != '" + 0 + "'", int6 == 0);
org.junit.Assert.assertTrue("'" + int11 + "' != '" + 0 + "'", int11 == 0);
org.junit.Assert.assertTrue("'" + int16 + "' != '" + 1 + "'", int16 == 1);
org.junit.Assert.assertNotNull(column17);
org.junit.Assert.assertTrue("'" + int18 + "' != '" + 1 + "'", int18 == 1);
org.junit.Assert.assertNotNull(column19);
org.junit.Assert.assertNotNull(column21);
org.junit.Assert.assertNotNull(column22);
org.junit.Assert.assertTrue("'" + str25 + "' != '" + " index 35 (ai)" + "'", str25.equals(" index 35 (ai)"));
}
@Test
public void test47() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test47");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
column0.setColumnName("");
org.csveed.common.Column column10 = column0.nextLine();
org.csveed.common.Column column11 = new org.csveed.common.Column();
org.csveed.common.Column column12 = new org.csveed.common.Column();
int int13 = column11.compareTo(column12);
org.csveed.common.Column column14 = new org.csveed.common.Column();
org.csveed.common.Column column15 = new org.csveed.common.Column();
int int16 = column14.compareTo(column15);
int int17 = column12.compareTo(column14);
column14.setColumnIndex((int) '#');
java.lang.String str20 = column14.getColumnText();
org.csveed.common.Column column21 = column14.nextColumn();
int int22 = column0.compareTo(column14);
org.csveed.common.Column column23 = new org.csveed.common.Column();
org.csveed.common.Column column24 = new org.csveed.common.Column();
int int25 = column23.compareTo(column24);
column23.setColumnName("");
java.lang.String str28 = column23.toString();
org.csveed.common.Column column29 = column23.nextLine();
java.lang.String str30 = column23.getColumnName();
boolean boolean31 = column14.equals((java.lang.Object) str30);
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertNotNull(column10);
org.junit.Assert.assertTrue("'" + int13 + "' != '" + 0 + "'", int13 == 0);
org.junit.Assert.assertTrue("'" + int16 + "' != '" + 0 + "'", int16 == 0);
org.junit.Assert.assertTrue("'" + int17 + "' != '" + 0 + "'", int17 == 0);
org.junit.Assert.assertTrue("'" + str20 + "' != '" + " index 35 (AI)" + "'", str20.equals(" index 35 (AI)"));
org.junit.Assert.assertNotNull(column21);
org.junit.Assert.assertTrue("'" + int22 + "' != '" + 1 + "'", int22 == 1);
org.junit.Assert.assertTrue("'" + int25 + "' != '" + 0 + "'", int25 == 0);
org.junit.Assert.assertTrue("'" + str28 + "' != '" + "Column Name: " + "'", str28.equals("Column Name: "));
org.junit.Assert.assertNotNull(column29);
org.junit.Assert.assertTrue("'" + str30 + "' != '" + "" + "'", str30.equals(""));
org.junit.Assert.assertTrue("'" + boolean31 + "' != '" + false + "'", boolean31 == false);
}
@Test
public void test48() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test48");
org.csveed.common.Column column1 = new org.csveed.common.Column(" index 2 (B)");
}
@Test
public void test49() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test49");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
column0.setColumnName("");
org.csveed.common.Column column5 = column0.nextColumn();
org.csveed.api.Header header6 = null;
org.csveed.common.Column column7 = column0.setHeader(header6);
org.csveed.api.Header header8 = null;
org.csveed.common.Column column9 = column7.setHeader(header8);
org.csveed.api.Header header10 = null;
org.csveed.common.Column column11 = column7.setHeader(header10);
column7.setColumnName("");
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertNotNull(column5);
org.junit.Assert.assertNotNull(column7);
org.junit.Assert.assertNotNull(column9);
org.junit.Assert.assertNotNull(column11);
}
@Test
public void test50() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test50");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
org.csveed.common.Column column3 = new org.csveed.common.Column();
org.csveed.common.Column column4 = new org.csveed.common.Column();
int int5 = column3.compareTo(column4);
int int6 = column1.compareTo(column4);
java.lang.String str7 = column4.getExcelColumn();
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + int5 + "' != '" + 0 + "'", int5 == 0);
org.junit.Assert.assertTrue("'" + int6 + "' != '" + 0 + "'", int6 == 0);
org.junit.Assert.assertTrue("'" + str7 + "' != '" + "A" + "'", str7.equals("A"));
}
@Test
public void test51() throws Throwable {
if (debug)
System.out.format("%n%s%n", "RegressionTest0.test51");
org.csveed.common.Column column0 = new org.csveed.common.Column();
org.csveed.common.Column column1 = new org.csveed.common.Column();
int int2 = column0.compareTo(column1);
org.csveed.common.Column column3 = new org.csveed.common.Column();
org.csveed.common.Column column4 = new org.csveed.common.Column();
int int5 = column3.compareTo(column4);
int int6 = column1.compareTo(column4);
column4.setColumnName("");
org.junit.Assert.assertTrue("'" + int2 + "' != '" + 0 + "'", int2 == 0);
org.junit.Assert.assertTrue("'" + int5 + "' != '" + 0 + "'", int5 == 0);
org.junit.Assert.assertTrue("'" + int6 + "' != '" + 0 + "'", int6 == 0);
}
}
<file_sep>package org.csveed.common;
import org.csveed.report.CsvException;
import org.csveed.report.GeneralError;
import org.csveed.report.RowPart;
import org.junit.Test;
import java.util.List;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
public class CSVExceptionTest {
@Test
public void getError() {
GeneralError error = new GeneralError("error");
CsvException exception = new CsvException(error);
assertEquals(exception.getError(), error);
}
@Test
public void getMessageTest() {
GeneralError error = new GeneralError("Message ERROR");
CsvException exception = new CsvException(error);
assertEquals(exception.getMessage(), "Message ERROR");
}
@Test
public void getLocalizedMessageTest() {
GeneralError error = new GeneralError("Message ERROR");
List<String> errorInLines = error.getPrintableLines();
CsvException exception = new CsvException(error);
assertEquals(exception.getLocalizedMessage(), "Message ERROR");
}
@Test
public void generalErrorTest() {
GeneralError error = new GeneralError("Message ERROR");
assertEquals(error.getLineNumber(), -1);
}
@Test
public void getRowTest() {
GeneralError error = new GeneralError("Message ERROR");
ArrayList<RowPart> emptyRowparts = new ArrayList<RowPart>();
assertEquals(error.getRowParts(), emptyRowparts);
}
}
|
f66f309ca95abb6b327493347451ca6d284b8735
|
[
"Java"
] | 4
|
Java
|
sarahsz/CSVeed
|
73e5871bff14c773704af1479d89ed61fb27d637
|
b68d36f4f121762e7673fd4bdc69ceed81b98ad2
|
refs/heads/main
|
<repo_name>andrew-song-archive/latale-guild-discord-bot<file_sep>/src/events/greetings.ts
import EventLoader from "./_loader";
import * as Discord from 'discord.js';
EventLoader.addEvent('안녕', (message: Discord.Message) => {
message.reply('반가워요!');
});<file_sep>/src/events/_loader.ts
import * as fs from 'fs';
import * as path from 'path';
const events = {}
function addEvent(eventName, func) {
events[eventName] = func;
}
export default {
events,
addEvent,
}
fs.readdirSync(`${__dirname}`)
.filter(file => (file.indexOf('.') !== 0) && (file.indexOf('_') !== 0) && (file.slice(-3) === '.js'))
.map(file => require(path.join(`${__dirname}`, file)))<file_sep>/src/router.ts
import EventLoader from './events/_loader';
import * as Discord from 'discord.js';
function route(message: Discord.Message) {
const content = message.content;
if (!content.startsWith('!')) return;
console.log(content);
const tokens = content.split(/\s+/);
const eventName = tokens[0].slice(1);
const eventArgs = tokens.slice(1);
console.log(tokens);
if (EventLoader.events.hasOwnProperty(eventName)) {
console.log(`call ${eventName}`)
EventLoader.events[eventName](message, eventArgs);
}
}
export default {
route,
}<file_sep>/src/events/notice.ts
import EventLoader from "./_loader";
import * as Discord from 'discord.js';
EventLoader.addEvent('공지', (message: Discord.Message, args: Array<string>) => {
});<file_sep>/src/index.ts
import * as dotenv from 'dotenv';
import * as Discord from 'discord.js';
import router from './router';
dotenv.config();
const bot = new Discord.Client();
bot.login(process.env.DISCORD_BOT_TOKEN);
bot.on('ready', () => console.log(`Ready ${bot.user.tag}`));
bot.on('message', message => router.route(message));
|
36b83ea16eeb621af2123ad54c3d5bbd00b62430
|
[
"TypeScript"
] | 5
|
TypeScript
|
andrew-song-archive/latale-guild-discord-bot
|
8fa6ae0efaebc1d7308954cb5c1d6708f857912d
|
95d223fa3258ea8a77cfb69bfc2f7582102edd85
|
refs/heads/master
|
<repo_name>anhmaivu88/Spark<file_sep>/NYCTaxi_SparkR.r
#######################################################################################
#
# Load Data
#
#######################################################################################
rawdata <- read.df("/nyc_taxi_data.csv","csv", header = "true", inferSchema = "true", na.strings = "NA")
#head(rawdata)
showDF(rawdata)
schema(rawdata)
count(rawdata)
createOrReplaceTempView(rawdata, "rawdata_sql")
#######################################################################################
#
# Explore Data
#
#######################################################################################
# How many unique cars are there (based on vehicle_id)
count(summarize(groupBy(rawdata, rawdata$vehicle_id), number_of_vehicles = count(rawdata$vehicle_id)))
# Describe / find basic stats for numerical data
showDF(describe(rawdata,"trip_distance","passenger_count","payment_amount","tip_amount"))
# Option 1 - What are my top earning cars
showDF(summarize(groupBy(rawdata, rawdata$vehicle_id), total_payment = sum(rawdata$payment_amount)) )
# Option 2 - What are my top earning cars
createOrReplaceTempView(rawdata, "rawdata_sql")
showDF(sql("SELECT vehicle_id, sum(payment_amount) as sum FROM rawdata_sql group by vehicle_id order by sum desc"))
# What is the average distance and average payment by car/vehicle
showDF(sql("SELECT vehicle_id, mean(trip_distance) as avg_distance, mean(payment_amount) as avg_payment FROM rawdata_sql group by vehicle_id order by avg_distance desc"))
# Covariance
cov(rawdata, 'payment_amount', 'fare_amount')
cov(rawdata, 'payment_amount', 'fare_amount')
# Correlation
corr(rawdata,"payment_amount", "fare_amount")
corr(rawdata,"tip_amount", "fare_amount")
# CrossTab
#showDF(crosstab(rawdata, "item1", "item2"))
#######################################################################################
#
# Transformations
#
#######################################################################################
transformed1 <- selectExpr(rawdata,
"vehicle_id",
"pickup_datetime",
"pickup_latitude",
"pickup_longitude",
"trip_distance",
"passenger_count",
"dropoff_datetime",
"dropoff_latitude",
"dropoff_longitude",
"fare_amount",
"tolls_amount",
"taxes_amount",
"tip_amount",
"payment_amount",
"cast(split(split(pickup_datetime,' ')[0],'/')[1] as int) pickup_day",
"cast(split(split(pickup_datetime,' ')[1],':')[0] as int) pickup_hour"
)
schema(transformed1)
#showDF(transformed1)
#######################################################################################
#
# Model Prep
#
#######################################################################################
# Split into Training and Testing DFs
df_training_testing <- randomSplit(transformed1, weights=c(0.8, 0.2), seed=12345)
trainingDF <- df_training_testing[[1]]
testingDF <- df_training_testing[[2]]
count(trainingDF)
count(testingDF)
#showDF(trainingDF)
###########################################################################################
#
# Modeling (GLM)
#
###########################################################################################
# Family may include (https://stat.ethz.ch/R-manual/R-devel/library/stats/html/family.html):
# binomial(link = "logit")
# gaussian(link = "identity")
# Gamma(link = "inverse")
# inverse.gaussian(link = "1/mu^2")
# poisson(link = "log")
# quasi(link = "identity", variance = "constant")
# quasibinomial(link = "logit")
# quasipoisson(link = "log")
gaussianGLM <- spark.glm(trainingDF, trip_distance ~ passenger_count + fare_amount + tolls_amount + tip_amount, family = "gaussian")
# Model summary
summary(gaussianGLM)
# Prediction
gaussianPredictions <- predict(gaussianGLM, testingDF)
showDF(select(gaussianPredictions, "label","prediction")
#ZEND<file_sep>/spark_tuning_tool_ambari.py
###################################################################################################
#
# Spark Tuning Tool (via Ambari)
# <NAME>
#
# This tool will extract cluster information from your cluster (via Ambari APIs), then the
# code will use these extracted parameters in order to calculate the optimal Spark configuration.
#
# Usage: spark_tuning_tool_ambari.py --ambari_hostname=dzaratsian_hdp.field.hortonworks.com --ambari_port --ambari_cluster_name --username=admin --password=<PASSWORD>
#
# https://github.com/apache/ambari/blob/trunk/ambari-server/docs/api/v1/index.md#resources
###################################################################################################
import sys,re
import getopt
import requests
import json
import math
try:
opts, args = getopt.getopt(sys.argv[1:], 'x', ['ambari_hostname=', 'ambari_port=', 'cluster_name=', 'username=', 'password='])
ambari_hostname = [opt[1] for opt in opts if opt[0]=='--ambari_hostname'][0]
ambari_port = [opt[1] for opt in opts if opt[0]=='--ambari_port'][0]
cluster_name = [opt[1] for opt in opts if opt[0]=='--ambari_cluster_name'][0]
username = [opt[1] for opt in opts if opt[0]=='--username'][0]
password = [opt[1] for opt in opts if opt[0]=='--password'][0]
except:
print '\n\n[ USAGE ] spark_tuning_tool_ambari.py --ambari_hostname=<hostname> --ambari_port=<port> --cluster_name=<cluster_name> --username=<string> --password=<string>\n\n'
sys.exit(1)
def get_datanode_parameters(ambari_hostname, ambari_port, cluster_name, username, password):
nodes_names = []
node_cores = []
node_ram = []
url = 'http://' + str(ambari_hostname) + ':' + str(ambari_port) + '/api/v1/clusters/' + str(cluster_name) + '/services/HDFS/components/DATANODE'
print '[ INFO ] Collection data from ' + str(url)
req = requests.get(url, auth=(username,password) )
if req.status_code == 200:
cluster_info = json.loads(req.content)
for host in cluster_info['host_components']:
url = host['href'].replace('/host_components/DATANODE','')
print '[ INFO ] Collection data from ' + str(url)
req2 = requests.get(url, auth=(username,password) )
host_info = json.loads(req2.content)
nodes_names.append(host['HostRoles']['host_name'])
node_cores.append(host_info['Hosts']['cpu_count'])
node_ram.append( int(math.floor(host_info['Hosts']['total_mem'] / float(1000*1000))) )
node_count = len(nodes_names)
node_cores = min(node_cores)
node_ram = min(node_ram)
return (node_count, node_cores, node_ram)
node_count, node_cores, node_ram = get_datanode_parameters(ambari_hostname, ambari_port, cluster_name, username, password)
if ((node_cores-1)/5) > 1:
executor_cores = 5
elif ((node_cores-1)/4) > 1:
executor_cores = 4
elif ((node_cores-1)/3) > 1:
executor_cores = 3
else:
executor_cores = 2
total_cores = node_count * node_cores
total_ram = node_count * node_ram
def get_yarn_parameters(ambari_hostname, ambari_port, cluster_name, username, password):
url = 'http://' + str(ambari_hostname) + ':' + str(ambari_port) + '/api/v1/clusters/' + str(cluster_name) + '/configurations/service_config_versions?service_name=YARN&service_config_version=1'
print '[ INFO ] Collection data from ' + str(url)
req = requests.get(url, auth=(username,password))
if req.status_code == 200:
cluster_info = json.loads(req.content)
yarn_site = [config for config in cluster_info['items'][0]['configurations'] if config['type']=='yarn-site']
yarn_nodemanager_resource_memory_mb = int(yarn_site[0]['properties']['yarn.nodemanager.resource.memory-mb'])
#yarn_nodemanager_resource_memory_mb = (node_ram - 2) * 1024
yarn_nodemanager_resource_cpu_vcores = int(yarn_site[0]['properties']['yarn.nodemanager.resource.cpu-vcores'])
#yarn_nodemanager_resource_cpu_vcores = (node_cores - 1)
return (yarn_nodemanager_resource_memory_mb, yarn_nodemanager_resource_cpu_vcores)
yarn_nodemanager_resource_memory_mb, yarn_nodemanager_resource_cpu_vcores = get_yarn_parameters(ambari_hostname, ambari_port, cluster_name, username, password)
executor_cores = executor_cores # ~5 or less typically and ideally is a divisor of yarn.nodemanager.resource.cpu-vcores)
executors_per_node = yarn_nodemanager_resource_cpu_vcores / executor_cores
executor_memory = ((yarn_nodemanager_resource_memory_mb / executors_per_node))/1024 - 2 # Subtract 2GB for buffer/extra space
num_executors = (node_count * executors_per_node ) - 1 # Subtract 1 for Driver, since Driver will consume 1 of exector slots
driver_cores = executor_cores
driver_memory = executor_memory
# Output Summary
print '\n\n####################################################################\n' + \
'\nNode Count: ' + str(node_count) + \
'\nNode Cores: ' + str(node_cores) + \
'\nNode RAM: ' + str(node_ram) + ' GB' \
'\n' + \
'\nTotal Cores: ' + str(total_cores) + \
'\nTotal RAM: ' + str(total_ram) + ' GB' \
'\n' + \
'\nYARN Nodemanager RAM (mb): ' + str(yarn_nodemanager_resource_memory_mb) + \
'\nYARN Nodemanager CPU Vcores: ' + str(yarn_nodemanager_resource_cpu_vcores) + \
'\n' + \
'\nexecutors_per_node: ' + str(executors_per_node) + \
'\n' + \
'\n--executor-cores: ' + str(executor_cores) + \
'\n--executor-memory: ' + str(executor_memory) + ' GB' \
'\n--num-executors: ' + str(num_executors) + \
'\n\n' + \
'./bin/spark-submit --master yarn --deploy-mode cluster' + ' --driver-cores ' + str(driver_cores) + ' --driver-memory ' + str(driver_memory) + 'G' + ' --executor-memory ' + str(executor_memory) + 'G' + ' --num-executors ' + str(num_executors) + ' --executor-cores ' + str(executor_cores) + \
'\n\n' + \
'/usr/hdp/current/spark2-client/bin/pyspark --master yarn --deploy-mode client' + ' --driver-cores ' + str(driver_cores) + ' --driver-memory ' + str(driver_memory) + 'G' + ' --executor-memory ' + str(executor_memory) + 'G' + ' --num-executors ' + str(num_executors) + ' --executor-cores ' + str(executor_cores) + \
'\n\n####################################################################\n'
# Add unused core count per node
# Add unused memory per node
#ZEND
<file_sep>/pyspark_sentiment.py
############################################################################################
#
# PySpark (Basic) Sentiment Analysis
#
############################################################################################
from pyspark.ml.feature import HashingTF, IDF, Tokenizer, CountVectorizer
from pyspark.sql.types import *
from pyspark.sql.functions import *
from pyspark.ml.linalg import Vectors, SparseVector
from pyspark.ml.clustering import LDA, BisectingKMeans
from pyspark.sql.functions import monotonically_increasing_id
import re
from textblob import TextBlob
spark = SparkSession \
.builder \
.appName("PySpark Text Analytics") \
.enableHiveSupport() \
.getOrCreate()
# Read Data from Hive
#rawdata = spark.sql("SELECT * FROM hotel_reviews")
rawdata = spark.read.csv("/tomorrowland.csv", inferSchema=True, header=True)
rawdata.show(50)
'''
rawdata_list =[
(100, 1, 'this is the best product, i love it.'),
(101, 0, 'this has been a great experience but the product was not satisfactory.'),
(102, 1, 'the product is awesome.'),
(103, -1, 'i hate the product and the price is terrible'),
(104, 1, 'the product works great and it is awesome to use'),
(105, -1, 'customer service was helpful but the product is expensive and it is bad')
]
rawdata = spark.createDataFrame(rawdata_list, ['id','lable','text'])
'''
def zsentiment(text):
return TextBlob(text).sentiment.polarity
udf_cleantext = udf(zsentiment , FloatType())
text_variable = 'text'
clean_text = rawdata.withColumn("sentiment_score", udf_cleantext( rawdata[text_variable] ))
clean_text.show(10,False)
#ZEND
<file_sep>/pyspark_basic_template.py
from pyspark.sql.types import *
from pyspark.sql.functions import monotonically_increasing_id, col, expr, when, concat, lit, udf, split
spark = SparkSession \
.builder \
.appName("spark_validation") \
.config("hive.exec.dynamic.partition", "true") \
.config("hive.exec.dynamic.partition.mode", "nonstrict") \
.enableHiveSupport() \
.getOrCreate()
# Load data from HDFS
rawdata = spark.read.load('/tmp/nyc_taxi_data.csv', format="csv", header=True, inferSchema=True)
# Display results
rawdata.show(10,False)
# Parse Fixed Length file
rawdata.select(
rawdata.value.substr(1,3).alias('id'),
rawdata.value.substr(4,8).alias('date'),
rawdata.value.substr(12,3).alias('string'),
rawdata.value.substr(15,4).cast('integer').alias('integer')
).show(10,False)
# How many unique cars are there (based on vehicle_id)
rawdata.select('vehicle_id').distinct().count()
# Describe / find basic stats for numerical data
rawdata.describe(['trip_distance','passenger_count','payment_amount']).show()
# Option 1 - What are my top earning cars
rawdata.groupBy('vehicle_id') \
.agg({'payment_amount': 'sum'}) \
.sort("sum(payment_amount)", ascending=False) \
.show()
df.agg({"age": "max"}).collect()
# Option 2 - What are my top earning cars
rawdata.createOrReplaceTempView("rawdata_sql")
spark.sql("SELECT vehicle_id, sum(payment_amount) as sum FROM rawdata_sql group by vehicle_id order by sum desc").show()
# Write spark DF to Hive (stored as ORC)
enriched_data \
.write.format("orc") \
.partitionBy("var1","var2") \
.mode("overwrite") \
.saveAsTable("myhivetable")
#ZEND
<file_sep>/pysparkling_water_loan_prediction.py
###############################################################################################################
#
# H2O Sparkling Water
# https://www.h2o.ai/download/
# http://docs.h2o.ai/h2o/latest-stable/h2o-docs/welcome.html#hadoop-users
# http://docs.h2o.ai/h2o/latest-stable/index.html
#
# Simple example to predict loan defaults (note: minimal data prep was done for this example)
# Lending Club Loan Dataset: https://www.kaggle.com/wendykan/lending-club-loan-data
# ./bin/pysparkling
# ./bin/pyspark --py-files /sparkling-water-2.1.14/py/build/dist/h2o_pysparkling_2.1-2.1.14.zip
#
# To get it to work in Zeppelin:
# Within ./conf/zeppelin-env.sh, add export SPARK_SUBMIT_OPTIONS="--files /sparkling-water-2.1.14/py/build/dist/h2o_pysparkling_2.1-2.1.14.zip"
# Within ./bin/interpreter.sh, add .zip file to PYTHONPATH, such as editing this line: export PYTHONPATH="$SPARK_HOME/python/:/sparkling-water-2.1.14/py/build/dist/h2o_pysparkling_2.1-2.1.14.zip:$PYTHONPATH"
#
###############################################################################################################
from pysparkling import *
hc = H2OContext.getOrCreate(spark)
import h2o
from h2o.estimators.gbm import H2OGradientBoostingEstimator
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
from pyspark.sql.types import *
from pyspark.sql.functions import *
# Import Data
# https://h2o-release.s3.amazonaws.com/h2o/rel-ueno/2/docs-website/h2o-py/docs/h2o.html
loans = h2o.import_file( \
path="/loan.csv" \
,header=0 \
#,sep=',', \
#,col_names=column_names, \
#,col_types=column_types \
)
# Data Descriptive Info
loans.columns
loans.head()
loans.types
loans.summary()
loans.shape
# Drop unneeded columns and filter NA columns
# Define schema, this is used to keep variables.
# It would also be used to ingest data to a specific format (when possible and depending on number of columns)
keep_schema = {
"id":"string"
,"member_id":"string"
,"loan_amnt":"float"
,"term":"int"
,"int_rate":"float"
,"installment":"string"
,"grade":"string"
#,"sub_grade":"string"
,"emp_length":"int"
,"home_ownership":"int"
,"annual_inc":"float"
,"loan_status":"int"
#,"purpose":"string"
#,"fico_range_high":"int"
#,"fico_range_low":"int"
#,"zip_code":"string"
,"addr_state":"string"
#,"delinq_2yrs":"int"
#,"open_acc":"int"
,"total_acc":"int"
,"open_acc":"int"
,"tot_coll_amt":"float"
#,"revol_util":"float" # Revolving line utilization rate, or the amount of credit the borrower is using relative to all available revolving credit.
}
keep_columns = [col[0] for col in keep_schema.iteritems()]
loans.shape
loans = loans.drop([col for col in loans.columns if col not in keep_columns])
loans.shape
columns_to_keep = loans.filter_na_cols(frac=0.2) # Returns a list of indices of columns that have fewer NAs than "frac". If all columns are filtered, None is returned.
loans = loans.drop([col for i,col in enumerate(loans.columns) if i not in columns_to_keep]) if [col for i,col in enumerate(loans.columns) if i not in columns_to_keep] != [] else loans
loans.shape
loans["addr_state"].table()
loans["loan_status"].table()
# Restructure Target Variable (i.e. loan default or not)
# Convert from H2O DF to Spark DF
df_loans = hc.as_spark_frame(loans,)
# Convert from Spark DF to H20 DF
#loans = hc.as_h2o_frame(df_loans)
df_loans = df_loans.withColumn("loan_status", when((df_loans["loan_status"]=="Default") | (df_loans["loan_status"]=="Charged Off"), "default").when((df_loans["loan_status"]=="Fully Paid") | (df_loans["loan_status"]=="Current"), "no default").otherwise(df_loans["loan_status"]) )
df_loans.count()
df_loans = df_loans.filter( (df_loans["loan_status"] == "default") | (df_loans["loan_status"] == "no default") )
df_loans.count()
# Create equal split of "default" and "no default" records
number_of_no_defaults = df_loans.groupBy("loan_status").count().filter(df_loans["loan_status"]=="no default").collect()[0][1]
number_of_defaults = df_loans.groupBy("loan_status").count().filter(df_loans["loan_status"]=="default").collect()[0][1]
stratified_ratio = number_of_defaults / float(number_of_no_defaults)
df_loans.groupBy("loan_status").count().show()
df_loans = df_loans.sampleBy("loan_status", fractions={"default": 1.00, "no default": stratified_ratio}, seed=0)
df_loans.groupBy("loan_status").count().show()
# Convert from Spark DF to H20 DF
loans = hc.as_h2o_frame(df_loans)
# H2O Change Data type
# Change "string" to "enum" for H2O dataframe
string_columns = [col[0] for col in loans.types.iteritems() if col[1]=='string']
for col in string_columns:
loans[col] = loans[col].asfactor() # Convert to factor / enum
loans.summary()
# Loan Status Distributions
loans["loan_status"].table()
# Split H2O data table into train test and ** validation ** datasets
training, testing, validation = loans.split_frame([0.60,0.20],seed=12345)
training.shape
testing.shape
validation.shape
# Specify Target
target = "loan_status"
# Specify Predictors
predictors = loans.columns[:]
predictors.remove(target)
predictors.remove("id")
predictors.remove("member_id")
# Modeling
model_gbm = H2OGradientBoostingEstimator(ntrees=50, max_depth=6, learn_rate=0.1, distribution="bernoulli")
model_gbm.train(x=predictors, y=target, training_frame=training)
model_gbm.varimp(True)
model_gbm.confusion_matrix(train = True)
model_gbm.auc(train=True)
model_gbm.model_performance(testing)
predictions = model_gbm.predict(testing)
predictions.head()
# Simple Deep Learning - Predict Arrest
model_dl = H2ODeepLearningEstimator(variable_importances=True, loss="Automatic")
model_dl.train(x=predictors, y=target, training_frame=training, validation_frame=validation)
model_dl.varimp(True)
model_dl.confusion_matrix(train = True)
model_dl.auc(train=True)
model_dl.model_performance(testing)
predictions = model_dl.predict(testing)
predictions.head()
# Save Model
model_path = h2o.save_model(model=model_gbm, path="/tmp/", force=True)
print model_path
# Python web framework setup:
id = 12345
member_id = 12345
loan_status = 'no default'
loan_amnt = 10000
term = "60 months"
int_rate = 12.5
installment = 300
grade = "C"
emp_length = "5 years"
home_ownership = "RENT"
annual_inc = 40000
addr_state = "CA"
total_acc = 15
tot_coll_amt = 10000
input_column_names = [ "loan_amnt", "term", "int_rate", "installment", "grade", "emp_length", "home_ownership", "annual_inc", "addr_state", "total_acc", "tot_coll_amt" ]
test_input = h2o.H2OFrame.from_python( [(loan_amnt, term, int_rate, installment, grade, emp_length, home_ownership, annual_inc, addr_state, total_acc, tot_coll_amt)], column_names=input_column_names)
test_input.head()
# Load the model
# model_gbm = h2o.load_model(model_path)
result = model_gbm.predict(test_input)
default_probability = result.as_data_frame()['default'][0]
#ZEND
<file_sep>/pyspark_parse_xml.py
#/spark/bin/pyspark --packages com.databricks:spark-xml_2.11:0.4.1
from pyspark.sql.functions import *
from pyspark.sql.types import *
df = spark.read.format('com.databricks.spark.xml').options(rowTag='record').load('/tmp/data.xml')
df.show()
def parse_list(column, index):
return column[index]
udf_parse_list = udf(parse_list, StringType())
df.withColumn('size', udf_parse_list(df.transaction, lit(0))) \
.withColumn('value', udf_parse_list(df.transaction, lit(1))) \
.show()
# data.xml (below)
'''
<?xml version="1.0"?>
<records>
<record>
<id>1000</id>
<transaction>
<value>10</value>
<size>S</size>
</transaction>
</record>
<record>
<id>2000</id>
<transaction>
<value>20</value>
<size>M</size>
</transaction>
</record>
<record>
<id>3000</id>
<transaction>
<value>30</value>
<size>L</size>
</transaction>
</record>
<record>
<id>4000</id>
<transaction>
<value>40</value>
<size>XL</size>
</transaction>
</record>
<record>
<id>5000</id>
<transaction>
<value>50</value>
<size>XXL</size>
</transaction>
</record>
</records>
'''
#ZEND
<file_sep>/pyspark_image_classification.py
############################################################################################################
#
# PySpark Image Classification
#
'''
Download Data:
wget https://github.com/zsellami/images_classification/blob/master/personalities.zip
wget https://dl.bintray.com/spark-packages/maven/databricks/spark-deep-learning/0.1.0-spark2.1-s_2.11/spark-deep-learning-0.1.0-spark2.1-s_2.11.jar -o /tmp/spark-deep-learning-0.1.0-spark2.1-s_2.11.jar
Usage:
/usr/hdp/current/spark2-client/bin/pyspark --packages databricks:spark-deep-learning:0.1.0-spark2.1-s_2.11 --master yarn --deploy-mode client --driver-memory 5G --conf "spark.dynamicAllocation.enabled=true" --conf "spark.shuffle.service.enabled=true" --conf "spark.dynamicAllocation.initialExecutors=12"
pip install numpy
pip install nose
pip install pillow
pip install keras
pip install h5py
pip install py4j
pip install tensorflow
'''
#
# https://github.com/databricks/spark-deep-learning
# https://mvnrepository.com/artifact/databricks/spark-deep-learning
# https://databricks.com/blog/2017/06/06/databricks-vision-simplify-large-scale-deep-learning.html
# https://medium.com/linagora-engineering/making-image-classification-simple-with-spark-deep-learning-f654a8b876b8 --driver-memory=5G --executor-memory=5G
# https://github.com/databricks/spark-deep-learning/issues/18
#
############################################################################################################
from pyspark.sql.types import *
from pyspark.sql.functions import *
from pyspark.ml.classification import LogisticRegression, GBTClassifier, RandomForestClassifier
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
from pyspark.ml import Pipeline
from sparkdl import DeepImageFeaturizer
from sparkdl import readImages
import sys, glob, os
sys.path.extend(glob.glob(os.path.join("tmp/*.jar")))
img_dir = "/tmp/personalities/"
jobs_df = readImages(img_dir + "/jobs").withColumn("label", lit(1))
zuck_df = readImages(img_dir + "/zuckerberg").withColumn("label", lit(0))
training_pct = 0.70
testing_pct = 0.30
jobs_train, jobs_test = jobs_df.randomSplit([training_pct, testing_pct])
zuck_train, zuck_test = zuck_df.randomSplit([training_pct, testing_pct])
train_df = jobs_train.unionAll(zuck_train)
print '[ INFO ] Number of Training Records: ' + str(train_df.count())
test_df = jobs_test.unionAll(zuck_test)
print '[ INFO ] Number of Training Records: ' + str(test_df.count())
featurizer = DeepImageFeaturizer(inputCol="image", outputCol="features", modelName="InceptionV3")
lr = LogisticRegression(maxIter=20, regParam=0.05, elasticNetParam=0.3, labelCol="label")
gb = GBTClassifier(featuresCol="features", labelCol="label", predictionCol="prediction", maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, lossType="logistic", maxIter=5, stepSize=0.1, seed=None, subsamplingRate=1.0)
rf = RandomForestClassifier(featuresCol="features", labelCol="label", predictionCol="prediction", probabilityCol="probability", rawPredictionCol="rawPrediction", maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini", numTrees=20, featureSubsetStrategy="auto", seed=12345)
pipe = Pipeline(stages=[featurizer, gb])
pipe_model = pipe.fit(train_df)
predictions = pipe_model.transform(test_df)
predictions.select("filePath", "prediction").show(10,False)
predictionAndLabels = predictions.select("prediction", "label")
evaluator = MulticlassClassificationEvaluator(metricName="accuracy")
print("Training set accuracy = " + str(evaluator.evaluate(predictionAndLabels)))
#ZEND
<file_sep>/spark_tuning_tool.py
##########################################################################################
#
# Spark Tuning Tool
#
# <NAME>
#
# Usage: spark_tuning_tool.py --node_count=20 --node_cores=16 --node_ram=64 [ --executor_cores=5 ] [ --yarn_memory=8192 ] [ --yarn_vcores=8 ]
#
##########################################################################################
import sys
import argparse
if __name__ == "__main__":
# Arguments
ap = argparse.ArgumentParser()
ap.add_argument("--node_count", required=True, type=int, help="Number of workers")
ap.add_argument("--node_cores", required=True, type=int, help="Cores per node")
ap.add_argument("--node_ram", required=True, type=int, help="Node RAM (in GBs)")
ap.add_argument("--executor_cores", required=False, type=int, help="Number of cores per executor")
ap.add_argument("--yarn_memory", required=False, type=int, help="YARN memory (in bytes)")
ap.add_argument("--yarn_vcores", required=False, type=int, help="YARN vcores")
args = vars(ap.parse_args())
try:
executor_cores = int(args['executor_cores'])
except:
executor_cores = 5 # ~5 or less typically and ideally is a divisor of yarn.nodemanager.resource.cpu-vcores)
try:
yarn_nodemanager_resource_memory_mb = int(args['yarn_memory'])
except:
yarn_nodemanager_resource_memory_mb = (args['node_ram'] - 4) * 1024
try:
yarn_nodemanager_resource_cpu_vcores = int(args['yarn_vcores'])
except:
yarn_nodemanager_resource_cpu_vcores = (args['node_cores'] - 2)
total_cores = args['node_count'] * args['node_cores']
total_ram = args['node_count'] * args['node_ram']
executor_cores = executor_cores # ~5 or less typically and ideally is a divisor of yarn.nodemanager.resource.cpu-vcores)
executors_per_node = yarn_nodemanager_resource_cpu_vcores / executor_cores
executor_memory = round( ((yarn_nodemanager_resource_memory_mb / executors_per_node))/1024 - 2) # Subtract 2GB for buffer/extra space
num_executors = round((args['node_count'] * executors_per_node ) - 1) # Subtract 1 for Driver, since Driver will consume 1 of exector slots
driver_cores = executor_cores
driver_memory = executor_memory
# Output Summary
print('\n\n####################################################################\n' + \
'\nNode Count: ' + str(args['node_count']) + \
'\nNode Cores: ' + str(args['node_cores']) + \
'\nNode RAM: ' + str(args['node_ram']) + ' GB' \
'\n' + \
'\nTotal Cores: ' + str(total_cores) + \
'\nTotal RAM: ' + str(total_ram) + ' GB' \
'\n' + \
'\nYARN Nodemanager RAM (mb): ' + str(yarn_nodemanager_resource_memory_mb) + \
'\nYARN Nodemanager CPU Vcores: ' + str(yarn_nodemanager_resource_cpu_vcores) + \
'\n' + \
'\nexecutors_per_node: ' + str(executors_per_node) + \
'\n' + \
'\n--executor-cores: ' + str(executor_cores) + \
'\n--executor-memory: ' + str(executor_memory) + ' GB' \
'\n--num-executors: ' + str(num_executors) + \
'\n\n' + \
'./bin/spark-submit --master yarn --deploy-mode cluster' + ' --driver-cores ' + str(driver_cores) + ' --driver-memory ' + str(driver_memory) + 'G' + ' --executor-memory ' + str(executor_memory) + 'G' + ' --num-executors ' + str(num_executors) + ' --executor-cores ' + str(executor_cores) + \
'\n\n' + \
'/usr/hdp/current/spark2-client/bin/pyspark --master yarn --deploy-mode client' + ' --driver-cores ' + str(driver_cores) + ' --driver-memory ' + str(driver_memory) + 'G' + ' --executor-memory ' + str(executor_memory) + 'G' + ' --num-executors ' + str(num_executors) + ' --executor-cores ' + str(executor_cores) + \
'\n\n####################################################################\n')
# TODO
# Add unused core count per node
# Add unused memory per node
#ZEND
<file_sep>/spark_fuzzy_matching.py
#####################################################################################################################
#
# PySpark Fuzzy Matching
#
# Soundex http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html#pyspark.sql.functions.soundex
# Levenshtein
# https://medium.com/@mrpowers/fuzzy-matching-in-spark-with-soundex-and-levenshtein-distance-6749f5af8f28
#
#####################################################################################################################
from pyspark.sql import SparkSession
from pyspark import SparkContext, SparkConf
from pyspark.sql.types import *
from pyspark.sql.functions import soundex, concat, levenshtein, unix_timestamp, from_unixtime
import datetime,time
#####################################################################################################################
#
# Fuzzy Matching within a single table (using Soundex)
#
#####################################################################################################################
# Generate Dataframe for testing
df = spark.createDataFrame(
[
(['dan', 'ocean', 'nc', '05/25/1983']),
(['daniel', 'ocean', 'nc', '05/25/1983']),
(['danny', 'ocean', 'nc', '05/26/1983']),
(['danny', 'ocen', 'nc', '05/26/1983']),
(['danny', 'oceans11', 'nc', '04/26/1982']),
(['tess', 'ocean', 'nc', '02/10/1988']),
(['john', 'smith', 'ca', '01/30/1980']),
(['john', 'smith', 'ca', '09/30/1981'])
],
['firstname','lastname','state','dob']
)
df.show(10,False)
# Step 1: Resolve any known name aliases, states, etc (i.e. dan, daniel, danny)
# For this POC code, I chose not to include this step since it's straight-forward to add a dictionary for matching and resolving known aliases.
# Step 2: Clean & Process other fields (ie. convert dates)
df = df.withColumn('dob_formatted', from_unixtime(unix_timestamp('dob', 'MM/dd/yyyy'), format='yyyy_MMMMMMMM_dd') )
# Step 3: Concat all relevant matching fields
df = df.withColumn('record_uid', concat(df.state, df.dob_formatted, df.firstname, df.lastname))
# Step 4: Soundex encoding (score record_uid for similarities)
df.withColumn('score_soundex', soundex(df.record_uid)).show(10,False)
#####################################################################################################################
#
# Fuzzy Matching Join using Levenshtein
#
#####################################################################################################################
# Generate Dataframe for testing
df = spark.createDataFrame(
[
(['dan', 'ocean', 'nc', '05/25/1983']),
(['daniel', 'ocean', 'nc', '05/25/1983']),
(['danny', 'ocean', 'nc', '05/26/1983']),
(['danny', 'ocen', 'nc', '05/26/1983']),
(['danny', 'oceans11', 'nc', '04/26/1982']),
(['tess', 'ocean', 'nc', '02/10/1988']),
(['john', 'smith', 'ca', '01/30/1980']),
(['john', 'smith', 'ca', '09/30/1981'])
],
['firstname','lastname','state','dob']
)
df.show(10,False)
# Generate Dataframe 2 for testing
df2 = spark.createDataFrame(
[
(['dan', 'ocean', '05/25/1983', 'medical code AAA']),
(['danny', 'oceans11', '04/26/1982', 'medical code BBB']),
(['tess', 'ocean', '02/10/1988', 'medical code CCC']),
(['john', 'smith', '01/30/1980', 'medical code DDD']),
(['john', 'smith', '09/30/1981', 'medical code EEE'])
],
['firstname','lastname','dob','medical_code']
)
df2.show(10,False)
# 1) Concat relevant fields used for fuzzy matching into a field called join_id
# 2) Apply levenshtein distance (which generates a score)
# 3) Use this score as a join criteria
# 4) Join on join_id
joinedDF = df.join(df2,
levenshtein( concat(df.dob,df.firstname,df.lastname), concat(df2.dob,df2.firstname,df2.lastname) ) < 5,
how='left_outer'
)
joinedDF.show(10,False)
#ZEND<file_sep>/spark_livy_client.py
##################################################################################################
#
# Livy Server - Spark Example (REST API)
#
##################################################################################################
import requests
import json
import datetime,time
import cloudpickle
host = 'dzaratsian5.field.hortonworks.com'
port = '8999'
url = 'http://' + str(host) +':'+ str(port)
headers = {'Content-Type': 'application/json', 'X-Requested-By': 'spark'}
def livy_get_sessions():
req_sessions = requests.get(url + '/sessions', headers=headers)
sessions_payload = json.loads(req_sessions.content)
print '[ INFO ] Total Sessions: ' + str(sessions_payload['total'])
for session in sessions_payload['sessions']:
print '[ INFO ] Session ID ' + str(session['id']) + ', state: ' + str(session['state']) + ', appID: ' + str(session['appId'])
return sessions_payload
def livy_delete_all_sessions():
req_sessions = requests.get(url + '/sessions', headers=headers)
sessions_payload = json.loads(req_sessions.content)
print '[ INFO ] Total Sessions: ' + str(sessions_payload['total'])
for session in sessions_payload['sessions']:
session_id = session['id']
delete_session = requests.delete(url + '/sessions/' + str(session_id), headers=headers)
print '[ INFO ] Deleted Session ID: ' + str(session_id)
def livy_initialize_spark_session():
data = {'kind': 'pyspark'}
spark_session = requests.post(url + '/sessions', data=json.dumps(data), headers=headers)
if spark_session.status_code == 201:
print '[ INFO ] Status Code: ' + str(spark_session.status_code)
print '[ INFO ] State: ' + str(spark_session.json()['state'])
print '[ INFO ] Payload: ' + str(spark_session.content)
session_id = spark_session.json()['id']
session_url = url + spark_session.headers['location']
else:
print '[ INFO ] Status Code: ' + str(spark_session.status_code)
return spark_session
if __name__ == "__main__":
spark_session = livy_initialize_spark_session()
session_url = url + spark_session.headers['location']
check_session = requests.get(session_url, headers=headers)
print '[ INFO ] Session ' + str(check_session.json()['id']) + ' state: ' + str(check_session.json()['state'])
data = {'code': 'print spark.range(0,10).count()'}
data = {'code': '1 + 1'}
statement_url = session_url + '/statements'
submit_code = requests.post(statement_url, data=json.dumps(data), headers=headers)
submit_code.status_code
submit_code.json()
statement_url = url + submit_code.headers['location']
code_response = requests.get(statement_url, headers=headers)
code_response.status_code
code_response.json()
#ZEND
<file_sep>/convert_zeppelin.py
###########################################################################
#
# Convert Zeppelin Notebook to Python Script
#
# USAGE: convert_zeppelin.py <zeppelin_notebook_file> <output_python_script>
#
###########################################################################
import json
import codecs
import sys
import re
path_to_zeppelin_nb = sys.argv[1]
path_to_python_output = open(sys.argv[2], 'w')
notebook = json.load(codecs.open(path_to_zeppelin_nb, 'r', 'utf-8-sig'))
for para in notebook["paragraphs"]:
text = re.sub('^\%[a-zA-Z]+\n', '', para['text'])
if para['config']['editorSetting']['language'] == 'text':
path_to_python_output.write( "\n'''\n{}\n'''\n".format( text ) )
elif para['config']['editorSetting']['language'] == 'python':
path_to_python_output.write( "\n{}\n".format( text ) )
path_to_python_output.close()
#ZEND
<file_sep>/spark_performance_check.py
####################################################################################################
#
# Spark Performance Check
#
# This script will simulate data, execute basic commands (counts(), show(), ect.) and collect
# cluster setting and runtime stats that can be used for Spark tuninig and configuration.
#
# Usage: ./bin/spark-submit spark_performance_check.py <number_of_records, default=50 million>
# This will also run from the pyspark shell
#
# Output results will be written to /tmp/spark_performance_check.txt
#
####################################################################################################
from pyspark.sql.types import *
from pyspark.sql.functions import *
from pyspark.sql import SparkSession
from pyspark import SparkContext, SparkConf
import datetime
import requests
import json
import sys
try:
number_of_records = int(sys.argv[1])
except:
number_of_records = 50000000
conf = SparkConf().setAppName('Spark Performance Check').setMaster('yarn').set('deploy-mode','client')
sc = SparkContext(conf=conf)
spark = SparkSession \
.builder \
.config(conf=conf) \
.getOrCreate()
file = '/tmp/spark_performance_check.txt'
output_file = open(file,'wb')
start_time = datetime.datetime.now()
start_time_total = start_time
df = spark.range(0,number_of_records)
def sim_random():
import random
return random.random()
def sim_rate():
import random
return random.random() * random.triangular(100,1000,100)
def sim_bool1():
import random
return random.choice(['TRUE']*2 + ['FALSE']*8)
def sim_bool2():
import random
return int(random.choice([1]*2 + [0]*8))
def sim_gender():
import random
return random.choice(['MALE']*3 + ['FEMALE']*6)
def sim_age():
import random
return int(random.triangular(15,90,35))
def sim_rating():
import random
return int(random.triangular(1,10,6))
def sim_state():
import random
return ['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'][int(random.triangular(0,49,2))]
def sim_name():
import random
return ['Frank','Dean','Dan','Sammy','James','Andrew','Scott','Steven','Kristen','Stephen','William','Craig','Stacy','Stuart','Christopher','Alan','Megan','Brian','Kevin','Kate','Molly','Derek','Martin','Thomas','Neil','Barry','Ian','Ashley','Iain','Gordon','Alexander','Graeme','Peter','Darren','Graham','George','Kenneth','Allan','Lauren','Douglas','Keith','Lee','Katy','Grant','Ross','Jonathan','Gavin','Nicholas','Joseph','Stewart'][int(random.triangular(0,49,2))]
def sim_date():
import random
return random.choice(['2015','2016','2017']) + '-' + str(random.choice(range(1,13))).zfill(2) + '-' + str(random.choice(range(1,30))).zfill(2)
udf_random = udf(sim_random, FloatType())
udf_rate = udf(sim_rate, FloatType())
udf_bool1 = udf(sim_bool1, StringType())
udf_bool2 = udf(sim_bool2, IntegerType())
udf_gender = udf(sim_gender, StringType())
udf_age = udf(sim_age, IntegerType())
udf_state = udf(sim_state, StringType())
udf_name = udf(sim_name, StringType())
udf_date = udf(sim_date, StringType())
udf_rating = udf(sim_rating, IntegerType())
sim = df.withColumn('date', udf_date() ) \
.withColumn('name', udf_name() ) \
.withColumn('age', udf_age() ) \
.withColumn('gender', udf_gender() ) \
.withColumn('state', udf_state() ) \
.withColumn('flag1', udf_bool1() ) \
.withColumn('flag2', udf_bool2() ) \
.withColumn('metric1', udf_random() ) \
.withColumn('metric1', udf_random() ) \
.withColumn('metric1', udf_random() ) \
.withColumn('rating', udf_rating() )
print '\n\n' + '#'*100
print '#'
print '# Spark Performance Check - Results'
print '#'
print '#'*100
runtime_msg = '\n[ INFO ] Simulated ' + str(number_of_records) + ' records (' + str(len(sim.columns)) + ' columns) in ' + str((datetime.datetime.now() - start_time).seconds) + ' seconds\n'
print runtime_msg
output_file.write(runtime_msg)
#start_time = datetime.datetime.now()
#sim.show()
#runtime_msg = '\n[ INFO ] show() Runtime: ' + str((datetime.datetime.now() - start_time).seconds) + ' seconds\n'
#print runtime_msg
#output_file.write(runtime_msg)
start_time = datetime.datetime.now()
sim.count()
runtime_msg = '\n[ INFO ] count() Runtime: ' + str((datetime.datetime.now() - start_time).seconds) + ' seconds\n'
print runtime_msg
output_file.write(runtime_msg)
output_file.write('\n[ INFO ] SPARK CONFIGS AND METRICS:\n\n')
for metric in sc._conf.getAll():
output_file.write(str(metric))
output_file.write('\n')
req = requests.get('http://localhost:4040/api/v1/applications')
appid = json.loads(req.content)[0]['id']
output_file.write('\n[ INFO ] Spark App ID: ' + str(appid))
output_file.write('\n')
#req = requests.get('http://localhost:4040/api/v1/applications/' + str(appid) + '/environment')
output_file.write('\n[ INFO ] Spark Executors:')
req = requests.get('http://localhost:4040/api/v1/applications/' + str(appid) + '/executors')
runtime_msg = str(req.content)
output_file.write(runtime_msg)
output_file.write('\n')
output_file.write('\n[ INFO ] Spark Jobs:')
req = requests.get('http://localhost:4040/api/v1/applications/' + str(appid) + '/jobs')
runtime_msg = str(req.content)
output_file.write(runtime_msg)
output_file.write('\n')
jobid = json.loads(req.content)[0]['jobId']
# Try to get estimated memory of 'sim' dataframe
try:
import py4j.protocol
from py4j.protocol import Py4JJavaError
from py4j.java_gateway import JavaObject
from py4j.java_collections import JavaArray, JavaList
from pyspark import RDD, SparkContext
from pyspark.serializers import PickleSerializer, AutoBatchedSerializer
# Helper function to convert python object to Java objects
def _to_java_object_rdd(rdd):
"""
Return a JavaRDD of Object by unpickling
It will convert each Python object into Java object by Pyrolite, whenever the
RDD is serialized in batch or not.
"""
rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer()))
return rdd.ctx._jvm.org.apache.spark.mllib.api.python.SerDe.pythonToJava(rdd._jrdd, True)
JavaObj = _to_java_object_rdd(sim.rdd)
# Now we can run the estimator
output_file.write('\n[ INFO ] Estimated size (in bytes): ' + str(sc._jvm.org.apache.spark.util.SizeEstimator.estimate(JavaObj)))
except:
pass
runtime_msg = 'Total Runtime: ' + str((datetime.datetime.now() - start_time_total).seconds) + ' seconds'
output_file.write('\n\n[ INFO ] ' + runtime_msg + '\n')
output_file.close()
print '\n\n' + '#'*100
print '#'
print '# Complete - Results can be found at ' + str(file)
print '# ' + str(runtime_msg)
print '#'
print '#'*100 + '\n\n'
#ZEND
<file_sep>/ncaa_sparkml.py
from pyspark.sql.types import *
from pyspark.sql.functions import monotonically_increasing_id, col, expr, when, concat, lit
from pyspark.ml.linalg import Vectors
from pyspark.ml.regression import GBTRegressor
from pyspark.ml.classification import GBTClassifier
from pyspark.ml.feature import VectorIndexer, VectorAssembler, StringIndexer
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml import Pipeline
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
#######################################################################################
#
# Read in Data
#
#######################################################################################
mm_season = spark.read.load("/RegularSeasonDetailedResults.csv", format="csv", header=True)
#mm_season.createOrReplaceTempView('mm_season_sql')
mm_teams = spark.read.load("/Teams.csv", format="csv", header=True)
#mm_teams.createOrReplaceTempView('mm_teams_sql')
mm_tournament = spark.read.load("/TourneyDetailedResults.csv", format="csv", header=True)
#mm_tournament.createOrReplaceTempView('mm_tournament_sql')
mm_season.count()
mm_teams.count()
mm_tournament.count()
#######################################################################################
#
# Combine Data
#
#######################################################################################
#mm_tournament = mm_tournament.withColumn("id", 900000 + monotonically_increasing_id())
alldata = mm_season.unionAll(mm_tournament)
alldata.show()
alldata.count()
mm_season.count()
mm_tournament.count()
#######################################################################################
#
# Clean Up and Transform Data
#
#######################################################################################
# Set the lower ID as TeamA (as per Kaggle: https://www.kaggle.com/c/march-machine-learning-mania-2017#evaluation)
# TeamB will be the larger Team ID.
# Cast as desired Type
alldata_transformed = alldata \
.withColumn("Season", alldata["Season"].cast(IntegerType())) \
.withColumn("Daynum", alldata["Daynum"].cast(IntegerType())) \
.withColumn("TeamA", expr("""IF(Wteam < Lteam, Wteam, Lteam)""")) \
.withColumn("TeamA_Score", expr("""IF(Wteam < Lteam, Wscore, Lscore)""")) \
.withColumn("TeamA_OffReb", expr("""IF(Wteam < Lteam, Wor, Lor)""").cast(IntegerType())) \
.withColumn("TeamA_DefReb", expr("""IF(Wteam < Lteam, Wdr, Ldr)""").cast(IntegerType())) \
.withColumn("TeamA_Turnover", expr("""IF(Wteam < Lteam, Wto, Lto)""").cast(IntegerType())) \
.withColumn("TeamA_Steals", expr("""IF(Wteam < Lteam, Wstl, Lstl)""").cast(IntegerType())) \
.withColumn("TeamA_Blocks", expr("""IF(Wteam < Lteam, Wblk, Lblk)""").cast(IntegerType())) \
.withColumn("TeamA_Fouls", expr("""IF(Wteam < Lteam, Wpf, Lpf)""").cast(IntegerType())) \
\
.withColumn("TeamB", expr("""IF(Wteam < Lteam, Lteam, Wteam)""")) \
.withColumn("TeamB_Score", expr("""IF(Wteam < Lteam, Lscore, Wscore)""")) \
.withColumn("TeamB_OffReb", expr("""IF(Wteam < Lteam, Lor, Wor)""").cast(IntegerType())) \
.withColumn("TeamB_DefReb", expr("""IF(Wteam < Lteam, Ldr, Wdr)""").cast(IntegerType())) \
.withColumn("TeamB_Turnover", expr("""IF(Wteam < Lteam, Lto, Wto)""").cast(IntegerType())) \
.withColumn("TeamB_Steals", expr("""IF(Wteam < Lteam, Lstl, Wstl)""").cast(IntegerType())) \
.withColumn("TeamB_Blocks", expr("""IF(Wteam < Lteam, Lblk, Wblk)""").cast(IntegerType())) \
.withColumn("TeamB_Fouls", expr("""IF(Wteam < Lteam, Lpf, Wpf)""").cast(IntegerType())) \
\
.withColumn("WinFlag", expr("""IF(int(TeamA_Score) > int(TeamB_Score), 1, 0)""")) \
.withColumn("WinRatio", expr(""" round(TeamA_Score/float(TeamB_Score),2) """)) \
.withColumn("Matchup", concat("TeamA",lit("_"),"TeamB")) \
.select('season','daynum','WinFlag','WinRatio', \
'TeamA','TeamB', \
'TeamA_OffReb','TeamB_OffReb', \
'TeamA_DefReb','TeamB_DefReb', \
'TeamA_Turnover','TeamB_Turnover', \
'TeamA_Steals','TeamB_Steals', \
'TeamA_Blocks','TeamB_Blocks', \
'TeamA_Fouls','TeamB_Fouls')
alldata_transformed.show()
# For modeling purposes, I should take the average stats per team by season (or other interval).
# To keep things simple, I'll make predictions based on individual games and generalize to a season average.
#test = alldata_transformed.groupBy('season',).agg({"TeamA_OffReb": "avg", "TeamA_DefReb": "avg"}).show()
# Use StringIndexer to convert all string inputs into Indexed Values (this converts multiple columns)
'''
>>>> Not needed with the current data structure
indexers = [StringIndexer(inputCol=column, outputCol=column+"_index").fit(alldata) for column in ["TeamA","TeamB"] ]
pipeline = Pipeline(stages=indexers)
alldata_out = pipeline.fit(alldata).transform(alldata)
alldata_out.show()
'''
# Generate Features Vector and Label
va = VectorAssembler(inputCols=['season', 'daynum', 'TeamA_OffReb', 'TeamB_OffReb', 'TeamA_DefReb', 'TeamB_DefReb', 'TeamA_Turnover', 'TeamB_Turnover', 'TeamA_Steals', 'TeamB_Steals', 'TeamA_Blocks', 'TeamB_Blocks', 'TeamA_Fouls', 'TeamB_Fouls'], outputCol="features")
alldata_out_with_features = va.transform(alldata_transformed) \
.withColumn("label", col("WinFlag"))
alldata_out_with_features.show()
#######################################################################################
#
# Define TRAINING and TESTING dataframes
#
#######################################################################################
# Random Spliting
#training, testing = alldata_out_with_features.randomSplit([0.8, 0.2])
# Holdout 2016 data for testing - train on all other seasons
training = alldata_out_with_features.filter('season != 2016')
testing = alldata_out_with_features.filter('season == 2016')
alldata_out_with_features.count()
training.count()
testing.count()
#######################################################################################
#
# Gradient Boost Model
#
#######################################################################################
#gbt = GBTRegressor(featuresCol="features", labelCol="label", predictionCol="prediction", maxDepth=5, maxBins=32, maxIter=20, seed=12345)
gbt = GBTClassifier(featuresCol="features", labelCol="label", predictionCol="prediction", maxDepth=5, maxBins=32, maxIter=20, seed=12345)
gbtmodel = gbt.fit(training)
# Make predictions.
predictions = gbtmodel.transform(testing)
# Select example rows to display.
predictions.select("prediction", "label", "features").show(10)
# Select (prediction, true label) and compute test error
evaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="accuracy")
accuracy = evaluator.evaluate(predictions)
print("Accuracy = " + str(accuracy))
# Accuracy = 0.862582781457
join_pred_with_team = predictions.join(mm_teams, predictions.TeamA==mm_teams.Team_Id, "left") \
.drop("Team_Id") \
.withColumnRenamed("Team_Name", "TeamA_Name")
join_pred_with_team2 = join_pred_with_team.join(mm_teams, join_pred_with_team.TeamB==mm_teams.Team_Id, "left") \
.drop("Team_Id") \
.withColumnRenamed("Team_Name", "TeamB_Name")
join_pred_with_team2.where( \
join_pred_with_team2["TeamA_Name"].isin({"NC State", "North Carolina", "Duke"}) | \
join_pred_with_team2["TeamB_Name"].isin({"NC State", "North Carolina", "Duke"})) \
.select("TeamA_Name","TeamB_Name","label","prediction") \
.show(25,False)
#######################################################################################
#
# Merge Predictions with Team Names
#
#######################################################################################
results = predictions.join(mm_teams, predictions.TeamA == mm_teams.Team_Id, 'left_outer') \
.withColumnRenamed("Team_Name", "TeamA_Name").drop("Team_Id") \
.join(mm_teams, predictions.TeamB == mm_teams.Team_Id, 'left_outer') \
.withColumnRenamed("Team_Name", "TeamB_Name").drop("Team_Id")
#ZEND
<file_sep>/kaggle_instacart.py
####################################################################################################################
#
# Kaggle Instacart Competition
#
# Predict which previously purchased products will be in a user’s next order.
#
####################################################################################################################
'''
Download Data from: https://www.kaggle.com/c/instacart-market-basket-analysis/data
scp -i ~/.ssh/field.pem ~/Downloads/aisles.csv.zip <EMAIL>:/tmp/.
scp -i ~/.ssh/field.pem ~/Downloads/departments.csv.zip <EMAIL>:/tmp/.
scp -i ~/.ssh/field.pem ~/Downloads/order_products__prior.csv.zip <EMAIL>:/tmp/.
scp -i ~/.ssh/field.pem ~/Downloads/order_products__train.csv.zip <EMAIL>:/tmp/.
scp -i ~/.ssh/field.pem ~/Downloads/orders.csv.zip <EMAIL>:/tmp/.
scp -i ~/.ssh/field.pem ~/Downloads/products.csv.zip <EMAIL>:/tmp/.
ssh -i ~/.ssh/field.pem dzaratsian4.field.hortonworks.com
cd /tmp
unzip aisles.csv.zip
unzip departments.csv.zip
unzip order_products__prior.csv.zip
unzip order_products__train.csv.zip
unzip orders.csv.zip
unzip products.csv.zip
sudo su
su hdfs
hadoop fs -mkdir /data/
hadoop fs -mkdir /data/instacart
hadoop fs -mkdir /data/instacart/aisles
hadoop fs -mkdir /data/instacart/departments
hadoop fs -mkdir /data/instacart/order_products__prior
hadoop fs -mkdir /data/instacart/order_products__train
hadoop fs -mkdir /data/instacart/orders
hadoop fs -mkdir /data/instacart/products
hadoop fs -put /tmp/aisles.csv /data/instacart/aisles/.
hadoop fs -put /tmp/departments.csv /data/instacart/departments/.
hadoop fs -put /tmp/order_products__prior.csv /data/instacart/order_products__prior/.
hadoop fs -put /tmp/order_products__train.csv /data/instacart/order_products__train/.
hadoop fs -put /tmp/orders.csv /data/instacart/orders/.
hadoop fs -put /tmp/products.csv /data/instacart/products/.
'''
from pyspark.sql import SparkSession
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml.recommendation import ALS
from pyspark.sql import Row
from pyspark.sql.functions import col, collect_set
spark = SparkSession \
.builder \
.appName("PySpark Instacart") \
.enableHiveSupport() \
.getOrCreate()
####################################################################################################################
#
# Load Data
#
####################################################################################################################
df_aisles = spark.read.csv('hdfs:///data/instacart/aisles/aisles.csv', inferSchema=True, header=True)
df_aisles.show(10,False)
df_departments = spark.read.csv('hdfs:///data/instacart/departments/departments.csv', inferSchema=True, header=True)
df_departments.show(10,False)
df_order_products__prior = spark.read.csv('hdfs:///data/instacart/order_products__prior/order_products__prior.csv', inferSchema=True, header=True)
df_order_products__prior.show(10,False)
df_order_products__train = spark.read.csv('hdfs:///data/instacart/order_products__train/order_products__train.csv', inferSchema=True, header=True)
df_order_products__train.show(10,False)
df_orders = spark.read.csv('hdfs:///data/instacart/orders/orders.csv', inferSchema=True, header=True)
df_orders.show(10,False)
df_products = spark.read.csv('hdfs:///data/instacart/products/products.csv', inferSchema=True, header=True)
df_products.show(10,False)
####################################################################################################################
#
# Descriptive Stats
#
####################################################################################################################
def descriptive_stats(df):
print('*'*100)
print('\nRow Count: ' + str(df.count()) + '\n')
print('\nColumns and Data Types:')
for column,dtype in df.dtypes:
print('\t' + str(column) + ', ' + str(dtype))
print('\n')
categorical_cols = [item[0] for item in df.dtypes if item[1]=='string']
for categorical_col in categorical_cols:
df.groupBy(categorical_col).count().orderBy(col('count').desc()).show()
print('\n')
df.describe().show(10,False)
print('*'*100)
print('\n\nDescriptive Stats for: df_aisles')
descriptive_stats(df_aisles)
print('\n\nDescriptive Stats for: df_departments')
descriptive_stats(df_departments)
print('\n\nDescriptive Stats for: df_order_products__train')
descriptive_stats(df_order_products__train)
print('\n\nDescriptive Stats for: df_orders')
descriptive_stats(df_orders)
print('\n\nDescriptive Stats for: df_products')
descriptive_stats(df_products)
####################################################################################################################
#
# Drop NAs
#
####################################################################################################################
df_aisles.count()
df_aisles = df_aisles.na.drop()
df_aisles.count()
df_departments.count()
df_departments = df_departments.na.drop()
df_departments.count()
df_order_products__train.count()
df_order_products__train = df_order_products__train.na.drop()
df_order_products__train.count()
df_orders.count()
df_orders = df_orders.na.drop()
df_orders.count()
df_products.count()
df_products = df_products.na.drop()
df_products.count()
####################################################################################################################
#
# Joins
#
####################################################################################################################
df_joined1 = df_order_products__train.join(df_orders, df_order_products__train.order_id == df_orders.order_id, 'left') \
.drop(df_orders.order_id)
df_joined1.show(20,False)
df_order_products__train.count()
df_orders.count()
df_joined1.count()
# Descriptive Stats
df_joined1.describe().show(10,False)
####################################################################################################################
#
# Model Prep
#
####################################################################################################################
order_list = df_order_products__train \
.select(['order_id','product_id']) \
.groupby("order_id") \
.agg(collect_set("product_id")) \
.withColumnRenamed('collect_set(product_id)','product_set')
order_list.show(20,False)
#(training, test) = df_joined1.randomSplit([0.8, 0.2])
####################################################################################################################
#
# Train Model
#
####################################################################################################################
fpGrowth = FPGrowth(itemsCol="product_set", minSupport=0.01, minConfidence=0.05)
model = fpGrowth.fit(order_list)
# Display frequent itemsets.
model.freqItemsets.show(20,False)
# Display generated association rules.
association = model.associationRules \
.withColumn('antecedent_value', col('antecedent')[0]) \
.withColumn('consequent_value', col('consequent')[0])
association.show(20,False)
association.count()
df_products.count()
join_assoc1 = association.join(df_products.select(['product_id','product_name']), association.antecedent_value == df_products.product_id, 'left').drop('product_id').withColumnRenamed('product_name','antecedent_name')
join_assoc2 = join_assoc1.join(df_products.select(['product_id','product_name']), join_assoc1.consequent_value == df_products.product_id, 'left').drop('product_id').withColumnRenamed('product_name','consequent_name')
join_assoc1.count()
join_assoc2.count()
join_assoc2.show(100,False)
# transform examines the input items against all the association rules and summarize the
# consequents as prediction
model.transform(order_list).show(20,False)
#ZEND<file_sep>/kaggle_movielens.py
#######################################################################################################################
#
# Spark Analysis on the MovieLens Dataset (26 Million Movie Reviews)
#
# Download Movie Dataset from here: https://grouplens.org/datasets/movielens/
# Here's the direct link: http://files.grouplens.org/datasets/movielens/ml-latest.zip
#
# Additional info and background can be found here as well: https://www.kaggle.com/grouplens/movielens-20m-dataset
#
# Datasets contains 26 million reviews (Stored in HDFS as CSV and also in Hive as ORC using https://github.com/zaratsian/Apache-Hive/blob/master/movielens.sql)
# 1.) movies that contains movie information
# 2.) ratings that contains ratings of movies by users
# 3.) links that contains identifiers that can be used to link to other sources
# 4.) tags that contains tags applied to movies by users
#
# Developed on:
# Spark 2.1.1.2.6.1.0-129
# Python 2.7.5
#
#######################################################################################################################
import datetime
from pyspark.sql import SparkSession
from pyspark.sql import Row
from pyspark.sql.functions import col, split, explode
from pyspark.sql.functions import udf
from pyspark.sql.types import *
from pyspark.ml.regression import GBTRegressor, RandomForestRegressor, GeneralizedLinearRegression, LinearRegression
from pyspark.ml.classification import GBTClassifier
from pyspark.ml.feature import VectorIndexer, VectorAssembler, StringIndexer
from pyspark.ml import Pipeline, PipelineModel
from pyspark.ml.evaluation import RegressionEvaluator
spark = SparkSession \
.builder \
.appName("pyspark_movielens") \
.enableHiveSupport() \
.getOrCreate()
start_time = datetime.datetime.now()
# Load Data from Hive
#movies = spark.sql("SELECT * FROM movies")
#ratings = spark.sql("SELECT * FROM ratings")
#links = spark.sql("SELECT * FROM links")
#tags = spark.sql("SELECT * FROM tags")
# Load Data from HDFS (as CSV)
movies = spark.read.load("/ml-latest/movies.csv", "csv", delimiter=",", inferSchema=True, header=True)
ratings = spark.read.load("/ml-latest/ratings.csv", "csv", delimiter=",", inferSchema=True, header=True)
links = spark.read.load("/ml-latest/links.csv", "csv", delimiter=",", inferSchema=True, header=True)
tags = spark.read.load("/ml-latest/tags.csv", "csv", delimiter=",", inferSchema=True, header=True)
print '[ INFO ] Number of Records in movies: ' + str(movies.count())
print '[ INFO ] Number of Records in ratings: ' + str(ratings.count())
print '[ INFO ] Number of Records in links: ' + str(links.count())
print '[ INFO ] Number of Records in tags: ' + str(tags.count())
# Pyspark Dataframe Joins
join1 = ratings.join(movies, ratings.movieId == movies.movieId).drop(movies.movieId)
print '[ INFO ] Number of Records in join1: ' + str(join1.count())
join1.show()
join2 = join1.join(tags, (join1.movieId == tags.movieId) & (join1.userId == tags.userId), how='leftouter').drop(movies.movieId).drop(tags.movieId).drop(tags.userId).drop(tags.timestamp)
print '[ INFO ] Number of Records in join2: ' + str(join2.count())
join2.show()
genres = join2.select(explode(split(col('genres'), '\|'))).distinct()
genres.show()
genres = genres.collect()
genres = [genre[0].encode('utf-8') for genre in genres]
def extract_genres(genres_string):
return [1 if genre in genres_string.split('|') else 0 for genre in genres]
udf_extract_genres = udf(extract_genres, ArrayType(IntegerType()))
#join2.select(['userid','movieid', udf_extract_genres(col('genres'))]).show()
enriched1 = join2.withColumn('genres_vector', udf_extract_genres(col('genres'))) \
.withColumn(genres[0].lower(), col('genres_vector')[0]) \
.withColumn(genres[1].lower(), col('genres_vector')[1]) \
.withColumn(genres[2].lower(), col('genres_vector')[2]) \
.withColumn(genres[3].lower(), col('genres_vector')[3]) \
.withColumn(genres[4].lower(), col('genres_vector')[4]) \
.withColumn(genres[5].lower(), col('genres_vector')[5]) \
.withColumn(genres[6].lower(), col('genres_vector')[6]) \
.withColumn(genres[7].lower(), col('genres_vector')[7]) \
.withColumn(genres[8].lower(), col('genres_vector')[8]) \
.withColumn(genres[9].lower(), col('genres_vector')[9]) \
.withColumn(genres[10].lower(), col('genres_vector')[10]) \
.withColumn(genres[11].lower(), col('genres_vector')[11]) \
.withColumn(genres[12].lower(), col('genres_vector')[12]) \
.withColumn(genres[13].lower(), col('genres_vector')[13]) \
.withColumn(genres[14].lower(), col('genres_vector')[14]) \
.withColumn(genres[15].lower(), col('genres_vector')[15]) \
.withColumn(genres[16].lower(), col('genres_vector')[16]) \
.withColumn(genres[17].lower(), col('genres_vector')[17]) \
.withColumn(genres[18].lower(), col('genres_vector')[18]) \
.withColumn(genres[19].lower(), col('genres_vector')[19]) \
.drop('genres', 'genres_vector')
print '[ INFO ] Listing columns...'
print ','.join(enriched1.columns)
print '\r\n'
print '[ INFO ] Printing Data Types...'
for datatype in enriched1.dtypes:
print datatype
var_target = 'rating'
var_features = [col for col in enriched1.columns if col not in ['userId','movieId','rating','timestamp','title','tag']]
# Generate Features Vector and Label
va = VectorAssembler(inputCols=var_features, outputCol="features")
modelprep1 = va.transform(enriched1).select('userId','movieId','rating','features')
training, testing, other = modelprep1.randomSplit([0.07, 0.03, 0.90])
print '[ INFO ] Training: ' + str(training.count()) + ' records'
print '[ INFO ] Testing: ' + str(training.count()) + ' records'
gb = GBTRegressor(featuresCol="features", labelCol=var_target, predictionCol="prediction", maxDepth=5, maxBins=32, maxIter=20, seed=12345)
gbmodel = gb.fit(training)
#gbmodel.save('/tmp/spark_models/kaggle_bike_sharing_gb_model')
predictions = gbmodel.transform(testing)
print '[ INFO ] Printing predictions vs label...'
predictions.show(10,False).select('prediction',var_target)
evaluator = RegressionEvaluator(labelCol=var_target, predictionCol="prediction")
print '[ INFO ] Model Fit (RMSE): ' + str(evaluator.evaluate(predictions, {evaluator.metricName: "rmse"}))
#print '[ INFO ] Model Fit (MSE): ' + str(evaluator.evaluate(predictions, {evaluator.metricName: "mse"}))
#print '[ INFO ] Model Fit (R2): ' + str(evaluator.evaluate(predictions, {evaluator.metricName: "r2"}))
total_runtime_seconds = (datetime.datetime.now() - start_time).seconds
print '#'*100
print '[ INFO ] Total Runtime: ' + str(total_runtime_seconds) + ' seconds'
print '#'*100
#ZEND
<file_sep>/pyspark_loan_model.py
########################################################################################################
#
# PySpark Basic Model Flow (used to show model deployment strategies)
#
# Note: The goal of this code is not to produce the best possible model, but rather to
# show the framework for a pyspark model pipeline, which we will then deploy into production.
#
########################################################################################################
'''
Usage:
/usr/hdp/current/spark2-client/bin/pyspark --master yarn --deploy-mode client --driver-memory 4G --conf "spark.dynamicAllocation.enabled=true" --conf "spark.shuffle.service.enabled=true" --conf "spark.dynamicAllocation.initialExecutors=6"
'''
import datetime
from pyspark.sql.types import *
from pyspark.sql.functions import *
from pyspark.ml.linalg import Vectors
from pyspark.ml.regression import DecisionTreeRegressor, GBTRegressor, LinearRegression, GeneralizedLinearRegression
from pyspark.ml.classification import GBTClassifier
from pyspark.ml.feature import VectorIndexer, VectorAssembler, StringIndexer, OneHotEncoder
from pyspark.ml import Pipeline
from pyspark.ml.evaluation import RegressionEvaluator, MulticlassClassificationEvaluator, BinaryClassificationEvaluator
rawdata = spark.read.load('hdfs:///tmp/loan_200k_new.csv', format="csv", header=True, inferSchema=True)
rawdata.show(10,False)
print '\nTotal Records: ' + str(rawdata.count()) + '\n'
for i in rawdata.dtypes: print i
rawdata.groupby(rawdata.purpose).count().show(20,False)
rawdata.groupby(rawdata.default).count().show(20,False)
#training, testing = rawdata.randomSplit([0.80, 0.20])
df_defaults = rawdata.filter(rawdata.default==1)
df_nodefault = rawdata.filter(rawdata.default==0)
training_defaults, testing_defaults = df_defaults.randomSplit([0.80, 0.20])
default_pct = training_defaults.count() / float(df_nodefault.count())
training_nodefault, testing_nodefault = df_nodefault.randomSplit([default_pct, (1.0 - default_pct)])
training = training_defaults.unionAll(training_nodefault)
testing = testing_defaults.unionAll(testing_nodefault)
si = StringIndexer(inputCol="purpose", outputCol="purpose_index")
hot = OneHotEncoder(inputCol="purpose_index", outputCol="purpose_features")
va = VectorAssembler(inputCols=["loan_amnt", "interest_rate", "employment_length", "home_owner", "income", "verified", "open_accts", "credit_debt", "purpose_features"], outputCol="features")
dtr = DecisionTreeRegressor(featuresCol="features", labelCol="default", predictionCol="prediction", maxDepth=2, varianceCol="variance")
gbr = GBTRegressor(featuresCol="features", labelCol="default", predictionCol="prediction", maxDepth=5, maxBins=32, maxIter=20, seed=12345)
gbc = GBTClassifier(featuresCol="features", labelCol="default", predictionCol="prediction", maxDepth=5, maxIter=20, seed=12345)
pipeline = Pipeline(stages=[si, hot, va, gbc])
model = pipeline.fit(training)
model.write().overwrite().save('hdfs:///tmp/spark_model')
predictions = model.transform(testing)
predictions.select(['default','prediction']).sort(col('prediction').desc()).show(25,False)
#evaluator = RegressionEvaluator(predictionCol="prediction", labelCol="default")
#rmse = evaluator.evaluate(predictions, {evaluator.metricName: "rmse"})
#r2 = evaluator.evaluate(predictions, {evaluator.metricName: "r2"})
#evaluator = BinaryClassificationEvaluator(rawPredictionCol="prediction", labelCol="default")
#evaluator.evaluate(predictions)
#evaluator.evaluate(predictions, {evaluator.metricName: "areaUnderPR"})
evaluator = MulticlassClassificationEvaluator(predictionCol="prediction", labelCol="default")
evaluator.evaluate(predictions, {evaluator.metricName: "accuracy"})
#ZEND
<file_sep>/text_analytics_datadriven_topics.py
################################################################################################
# http://spark.apache.org/docs/2.0.2/ml-guide.html
# http://spark.apache.org/docs/2.0.2/sql-programming-guide.html
# http://spark.apache.org/docs/2.0.2/ml-features.html#tf-idf
# http://spark.apache.org/docs/2.0.2/api/python/pyspark.ml.html#pyspark.ml.feature.IDF
################################################################################################
from pyspark.ml.feature import HashingTF, IDF, Tokenizer, CountVectorizer
from pyspark.sql.types import *
from pyspark.sql.functions import *
from pyspark.ml.linalg import Vectors, SparseVector
from pyspark.ml.clustering import LDA, BisectingKMeans
from pyspark.sql.functions import monotonically_increasing_id
import re
################################################################################################
#
# Import Rawdata
#
################################################################################################
rawdata = spark.read.load("hdfs://sandbox.hortonworks.com:8020/tmp/airlines.csv", format="csv", header=True)
rawdata = rawdata.fillna({'review': ''}) # Replace nulls with blank string
rawdata = rawdata.withColumn("uid", monotonically_increasing_id()) # Create Unique ID
rawdata = rawdata.withColumn("year_month", rawdata.date.substr(1,7)) # Generate YYYY-MM variable
# Show rawdata (as DataFrame)
rawdata.show(10)
# Print data types
for type in rawdata.dtypes:
print type
target = rawdata.select(rawdata['rating'].cast(IntegerType()))
target.dtypes
################################################################################################
#
# Text Pre-processing (consider using one or all of the following):
# - Remove common words (with stoplist)
# - Handle punctuation
# - lowcase/upcase
# - Stemming
# - Part-of-Speech Tagging (nouns, verbs, adj, etc.)
#
################################################################################################
def cleanup_text(record):
text = record[8]
uid = record[9]
words = text.split()
# Default list of Stopwords
stopwords_core = ['a', u'about', u'above', u'after', u'again', u'against', u'all', u'am', u'an', u'and', u'any', u'are', u'arent', u'as', u'at',
u'be', u'because', u'been', u'before', u'being', u'below', u'between', u'both', u'but', u'by',
u'can', 'cant', 'come', u'could', 'couldnt',
u'd', u'did', u'didn', u'do', u'does', u'doesnt', u'doing', u'dont', u'down', u'during',
u'each',
u'few', 'finally', u'for', u'from', u'further',
u'had', u'hadnt', u'has', u'hasnt', u'have', u'havent', u'having', u'he', u'her', u'here', u'hers', u'herself', u'him', u'himself', u'his', u'how',
u'i', u'if', u'in', u'into', u'is', u'isnt', u'it', u'its', u'itself',
u'just',
u'll',
u'm', u'me', u'might', u'more', u'most', u'must', u'my', u'myself',
u'no', u'nor', u'not', u'now',
u'o', u'of', u'off', u'on', u'once', u'only', u'or', u'other', u'our', u'ours', u'ourselves', u'out', u'over', u'own',
u'r', u're',
u's', 'said', u'same', u'she', u'should', u'shouldnt', u'so', u'some', u'such',
u't', u'than', u'that', 'thats', u'the', u'their', u'theirs', u'them', u'themselves', u'then', u'there', u'these', u'they', u'this', u'those', u'through', u'to', u'too',
u'under', u'until', u'up',
u'very',
u'was', u'wasnt', u'we', u'were', u'werent', u'what', u'when', u'where', u'which', u'while', u'who', u'whom', u'why', u'will', u'with', u'wont', u'would',
u'y', u'you', u'your', u'yours', u'yourself', u'yourselves']
# Custom List of Stopwords - Add your own here
stopwords_custom = ['']
stopwords = stopwords_core + stopwords_custom
stopwords = [word.lower() for word in stopwords]
text_out = [re.sub('[^a-zA-Z0-9]','',word) for word in words] # Remove special characters
text_out = [word.lower() for word in text_out if len(word)>2 and word.lower() not in stopwords] # Remove stopwords and words under X length
return text_out
udf_cleantext = udf(cleanup_text , ArrayType(StringType()))
clean_text = rawdata.withColumn("words", udf_cleantext(struct([rawdata[x] for x in rawdata.columns])))
#tokenizer = Tokenizer(inputCol="description", outputCol="words")
#wordsData = tokenizer.transform(text)
################################################################################################
#
# Generate TFIDF
#
################################################################################################
# Term Frequency Vectorization - Option 1 (Using hashingTF):
#hashingTF = HashingTF(inputCol="words", outputCol="rawFeatures", numFeatures=20)
#featurizedData = hashingTF.transform(clean_text)
# Term Frequency Vectorization - Option 2 (CountVectorizer) :
cv = CountVectorizer(inputCol="words", outputCol="rawFeatures", vocabSize = 1000)
cvmodel = cv.fit(clean_text)
featurizedData = cvmodel.transform(clean_text)
vocab = cvmodel.vocabulary
vocab_broadcast = sc.broadcast(vocab)
idf = IDF(inputCol="rawFeatures", outputCol="features")
idfModel = idf.fit(featurizedData)
rescaledData = idfModel.transform(featurizedData)
################################################################################################
#
# LDA Clustering - Find Data-driven Topics
#
################################################################################################
lda = LDA(k=25, seed=123, optimizer="em", featuresCol="features")
ldamodel = lda.fit(rescaledData)
#model.isDistributed()
#model.vocabSize()
ldatopics = ldamodel.describeTopics()
ldatopics.show(25)
def map_termID_to_Word(termIndices):
words = []
for termID in termIndices:
words.append(vocab_broadcast.value[termID])
return words
udf_map_termID_to_Word = udf(map_termID_to_Word , ArrayType(StringType()))
ldatopics_mapped = ldatopics.withColumn("topic_desc", udf_map_termID_to_Word(ldatopics.termIndices))
ldatopics_mapped.select(ldatopics_mapped.topic, ldatopics_mapped.topic_desc).show(25,False)
ldaResults = ldamodel.transform(rescaledData)
ldaResults.show()
################################################################################################
#
# Breakout LDA Topics for Modeling and Reporting
#
################################################################################################
def breakout_array(index_number, record):
vectorlist = record.tolist()
return vectorlist[index_number]
udf_breakout_array = udf(breakout_array, FloatType())
enrichedData = ldaResults \
.withColumn("Topic_12", udf_breakout_array(lit(12), ldaResults.topicDistribution)) \
.withColumn("topic_20", udf_breakout_array(lit(20), ldaResults.topicDistribution))
enrichedData.show()
#enrichedData.agg(max("Topic_12")).show()
################################################################################################
#
# Register Table for SparkSQL
#
################################################################################################
enrichedData.createOrReplaceTempView("enrichedData")
spark.sql("SELECT id, airline, date, rating, topic_12 FROM enrichedData")
spark.sql("SELECT id, airline, date, rating, topic_20 FROM enrichedData")
#ZEND
<file_sep>/clinical_analysis/README.md
<h3>Clinical Trials Analysis</h3>
This project contains publicly available clinical trials data and the code used for the analysis of this information. I used Spark (pySpark) for my analysis and Zeppelin as the code editor & visualization tool.
<br>
<br>The purpose of this project is to provide an example of how to analyze both structured and unstructured data using Spark. This involves parsing and cleansing the raw data, text analytics (to find data-driven topics), and basic visualization techniques available within Zeppelin.
<br>
<br><b>References:</b>
<br><a href="http://hortonworks.com/downloads/#sandbox">Hortonworks HDP 2.5 Sandbox</a>
<br><a href="http://spark.apache.org/docs/latest/api/python/index.html">PySpark Docs</a>
<br>
<br><img src="screenshots/screenshot1.png" class="inline"/>
<br>
<br>
<br><img src="screenshots/screenshot2.png" class="inline"/>
<br>
<br>
<br><img src="screenshots/screenshot3.png" class="inline"/>
<br>
<file_sep>/spark_history_server_allocation.py
#!/bin/python
import urllib, sys, json
data = json.loads(urllib.urlopen("http://"+sys.argv[1]+":18080/api/v1/applications?status=running").read())
dyna = []
nondyna = []
#The History REST API for environments is not until Spark 2. So mining the html pages.
#Is not HA Safe, is not YARN App restart safe will only mine the first app attempts
for app in data:
env = urllib.urlopen("http://"+sys.argv[1]+":18080/history/"+app['id']+"/1/environment").read()
if "spark.executor.instances" not in env:
dyna.append(app['id'])
else:
nondyna.append(app['id'])
print dyna
print nondyna
#Code credits <NAME>
#ZEND
<file_sep>/pyspark_imdb_movies_livy.py
##################################################################################################
'''
NOTES:
1.) Install Anaconda across nodes
2.) Set PYSPARK_PYTHON env var:
sudo su
su livy
cd ~
echo "" >> ~/.bashrc
echo "export PYSPARK_PYTHON=/opt/anaconda2/bin/python2.7" >> ~/.bashrc
3.) Set spark.yarn.appMasterEnv.PYSPARK_PYTHON = /opt/anaconda2/bin/python2.7
'''
##################################################################################################
#
# Livy Server - Spark Example (REST API)
#
##################################################################################################
import requests
import json
import datetime,time
##################################################################################################
#
# Function: Initial Session and Submit Code
#
##################################################################################################
'''
host='dzaratsian5.field.hortonworks.com'
port='8999'
code_payload = {'code': "spark.range(0,10).count()"}
session_id=''
'''
def spark_livy_interactive(host='', port='8999', code_payload='', session_id=''):
result = ''
base_url = 'http://' + str(host) +':'+ str(port)
session_url = base_url + '/sessions'
headers = {'Content-Type': 'application/json', 'X-Requested-By': 'spark'}
if session_id == '':
#data = {'kind': 'pyspark'}
data = {'kind': 'pyspark', 'conf':{'spark.yarn.appMasterEnv.PYSPARK_PYTHON':'/opt/anaconda2/bin/python2.7'}}
spark_session = requests.post(base_url + '/sessions', data=json.dumps(data), headers=headers)
if spark_session.status_code == 201:
session_id = spark_session.json()['id']
session_url = base_url + spark_session.headers['location']
print '[ INFO ] Status Code: ' + str(spark_session.status_code)
print '[ INFO ] Session State: ' + str(spark_session.json()['state'])
print '[ INFO ] Session ID: ' + str(session_id)
print '[ INFO ] Payload: ' + str(spark_session.content)
# Loop until Spark Session is ready (i.e. In the Idle State)
session_state = ''
while (session_state == '') or (session_state == 'starting'):
time.sleep(0.25)
print '[ INFO ] Session State: ' + str(session_state)
session = requests.get(session_url, headers=headers)
if session.status_code == 200:
session_state = session.json()['state']
else:
print '[ ERROR ] Status Code: ' + str(session.status_code)
session_state = 'end'
print '[ INFO ] Session State: ' + str(session_state)
print '[ INFO ] Spark App ID: ' + str(session.json()['appId'])
print '[ INFO ] Spark App URL: ' + str(session.json()['appInfo']['sparkUiUrl'])
else:
print '[ ERROR ] Failed to start Spark Session, Status Code: ' + str(spark_session.status_code)
else:
print '[ INFO ] Using existing Session ID: ' + str(session_id)
try:
submit_code = requests.post(base_url + '/sessions/' + str(session_id) + '/statements', data=json.dumps(code_payload), headers=headers)
except:
result = {'state':'Error with code submission'}
return session_id, result
if submit_code.status_code == 201:
submit_code_state = ''
while (submit_code_state == '') or (submit_code_state == 'running'):
time.sleep(0.25)
code_response = requests.get(base_url + submit_code.headers['location'], headers=headers)
if code_response.status_code == 200:
result = code_response.json()
submit_code_state = code_response.json()['state']
print '[ INFO ] Code Submit State: ' + str(submit_code_state)
#print '\n' + '#'*50
#print '[ INFO ] Result: ' + str(result)
#print '#'*50
else:
print '[ ERROR ] Status Code: ' + str(code_response.status_code)
else:
print '[ ERROR ] Failed to submit Spark code successfully, Status Code: ' + str(submit_code.status_code)
return session_id, result
##################################################################################################
#
# Function: Delete Session
#
##################################################################################################
def delete_spark_livy_session(host='', port='', session_id=''):
print '[ INFO ] Deleting Session ' + str(session_id) + '...'
time.sleep(1)
base_url = 'http://' + str(host) +':'+ str(port)
headers = {'Content-Type': 'application/json', 'X-Requested-By': 'spark'}
del_request = requests.delete(base_url + '/sessions/' + str(session_id), headers=headers)
if del_request.status_code == 200: print '[ INFO ] Successfully deleted Session ' + str(session_id)
##################################################################################################
#
# Test Function
#
##################################################################################################
code_payload = {'code': '''
import os
os.environ["PYSPARK_DRIVER_PYTHON"] = "/opt/anaconda2/bin/python2.7"
os.environ["PYSPARK_PYTHON"] = "/opt/anaconda2/bin/python2.7"
import datetime, time
import re, random, sys
from pyspark.sql.types import StructType, StructField, ArrayType, IntegerType, StringType, FloatType, LongType
from pyspark.sql.functions import struct, array, lit, monotonically_increasing_id, col, expr, when, concat, udf, split, size
from pyspark.ml.linalg import Vectors
from pyspark.ml.regression import GBTRegressor, LinearRegression, GeneralizedLinearRegression, RandomForestRegressor
from pyspark.ml.classification import GBTClassifier, RandomForestClassifier
from pyspark.ml.feature import VectorIndexer, VectorAssembler, StringIndexer
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml import Pipeline, PipelineModel
from pyspark.ml.evaluation import MulticlassClassificationEvaluator, RegressionEvaluator
from pyspark.ml.feature import HashingTF, IDF, Tokenizer, CountVectorizer
from pyspark.ml.clustering import LDA, BisectingKMeans
from pyspark.ml.feature import Word2Vec
#import nltk
#import spacy
#nlp = spacy.load("en")
#import sparknlp.annotators as sparknlp
#sc.setLogLevel("ERROR")
from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("pyspark_livy_movie_app_dz") \
.getOrCreate()
############################################################################################################
#
# Load Rawdata
# Source: https://www.kaggle.com/tmdb/tmdb-movie-metadata
#
############################################################################################################
schema = StructType([ \
StructField("budget", IntegerType(), True), \
StructField("genres", StringType(), True), \
StructField("homepage", StringType(), True), \
StructField("id", StringType(), True), \
StructField("keywords", StringType(), True), \
StructField("original_language", StringType(), True), \
StructField("original_title", StringType(), True), \
StructField("overview", StringType(), True), \
StructField("popularity", FloatType(), True), \
StructField("production_companies", StringType(), True), \
StructField("production_countries", StringType(), True), \
StructField("release_date", StringType(), True), \
StructField("revenue", LongType(), True), \
StructField("runtime", IntegerType(), True), \
StructField("spoken_languages", StringType(), True), \
StructField("status", StringType(), True), \
StructField("tagline", StringType(), True), \
StructField("title", StringType(), True), \
StructField("vote_average", FloatType(), True), \
StructField("vote_count", IntegerType(), True)])
rawdata = spark.read.format('csv').load('hdfs://dzaratsian0.field.hortonworks.com:8020/tmp/tmdb_5000_movies.csv', format="csv", header=True, schema=schema, quote='"', escape='"', mode="DROPMALFORMED")
############################################################################################################
#
# Extract Genres from JSON
#
############################################################################################################
def extract_genre(column_name):
import json
try:
genre = json.loads(column_name)[0]['name'].strip()
if (genre=='Action') or (genre=='Adventure'):
genre = 'Action/Adventure'
elif (genre=='Fantasy') or (genre=='Science Fiction'):
genre = 'Science Fiction'
elif (genre=='Horror') or (genre=='Thriller'):
genre = 'Horror'
elif (genre=='Drama'):
genre = 'Drama'
elif (genre=='Comedy'):
genre = 'Comedy'
else:
genre = 'Other'
return genre
except:
return 'Other'
udf_extract_genre = udf(extract_genre, StringType())
enriched1 = rawdata.withColumn("genre", udf_extract_genre('genres'))
#enriched1.cache
#enriched1.count()
#enriched1.select(['genres','genre']).show(20,False)
#enriched1.groupBy('genre').count().show(50,False)
############################################################################################################
#
# Transformations
#
############################################################################################################
json_columns = ['genres','keywords','production_companies','production_countries','spoken_languages']
text_columns = ['original_title','overview','tagline','title']
drop_columns = json_columns + ['original_title','tagline','popularity','release_date','status','original_language','homepage']
# Filter DF, drop where revenue == 0
enriched2 = enriched1.filter('revenue != 0')
# Extract Date/Time Variables
def extract_year(date_var):
try:
return datetime.datetime.strptime(date_var, '%Y-%m-%d').year
except:
return random.randint(2005,2016)
def extract_month(date_var):
try:
return datetime.datetime.strptime(date_var, '%Y-%m-%d').month
except:
return random.randint(1,12)
def extract_day(date_var):
try:
return datetime.datetime.strptime(date_var, '%Y-%m-%d').day
except:
return random.randint(1,28)
udf_year = udf(extract_year, IntegerType())
udf_month = udf(extract_month, IntegerType())
udf_day = udf(extract_day, IntegerType())
enriched2 = enriched2.withColumn("year", udf_year('release_date')) \
.withColumn("month", udf_month('release_date')) \
.withColumn("day", udf_day('release_date'))
def bucket_revenue(revenue):
if revenue <= 10000000:
return 'Less than $10M'
elif 10000000 < revenue <= 25000000:
return '$10M - $25M'
elif 25000000 < revenue <= 50000000:
return '$25M - $50M'
elif 50000000 < revenue <= 100000000:
return '$50M - $100M'
elif 100000000 < revenue <= 200000000:
return '$100M - $200M'
elif revenue > 200000000:
return 'Over $200M'
else:
return -1
udf_bucket_revenue = udf(bucket_revenue, StringType())
enriched2 = enriched2.withColumn("revenue_bucket", udf_bucket_revenue('revenue'))
enriched2 = enriched2.withColumn('revenue_over_100M', when(col("revenue") >= 100000000, 1).otherwise(0))
def bucket_vote(vote_average):
if vote_average >= 7.0:
return 'Great'
elif 6.0 <= vote_average < 7.0:
return 'Good'
elif 5.0 <= vote_average < 6.0:
return 'Ok'
elif vote_average < 5.0:
return 'Bad'
else:
return 'No Vote'
udf_bucket_vote = udf(bucket_vote, StringType())
enriched2 = enriched2.withColumn("vote_bucket", udf_bucket_vote('vote_average'))
# Drop Columns
for c in drop_columns:
enriched2 = enriched2.drop(c)
#enriched2.cache()
enriched2.count()
############################################################################################################
#
# Model Pipeline (similar to above) - Regression
#
############################################################################################################
target = 'revenue'
features = ['budget','runtime','vote_average','vote_count','year','month','day','genre_index']
# Model Input Variables: ( budget|runtime|vote_average|vote_count|year|month|day )
training, testing = enriched2.randomSplit([0.8, 0.2], seed=12345)
si = StringIndexer(inputCol="genre", outputCol="genre_index")
va = VectorAssembler(inputCols=features, outputCol="features")
gbr = GBTRegressor(featuresCol="features", labelCol=target, predictionCol="prediction", maxDepth=5, maxBins=32, maxIter=20, seed=12345)
pipeline = Pipeline(stages=[si, va, gbr])
mlmodel = pipeline.fit(training)
predictions = mlmodel.transform(testing)
evaluator = RegressionEvaluator(metricName="rmse", labelCol=target) # rmse (default)|mse|r2|mae
RMSE = evaluator.evaluate(predictions)
#print 'RMSE: ' + str(RMSE)
evaluator = RegressionEvaluator(metricName="r2", labelCol=target)
R2 = evaluator.evaluate(predictions)
#print 'R2: ' + str(R2)
mlmodel.save('hdfs://dzaratsian0.field.hortonworks.com:8020/tmp/model_predict_movie_revenue')
'''}
#code_payload = {'code': ''' spark.range(0,10).count() '''}
session_id, result = spark_livy_interactive(host='dzaratsian4.field.hortonworks.com', port='8999', code_payload=code_payload, session_id='')
session_id
result
result['output']['data']['text/plain']
code_payload = {'code': '''
spark.range(0,50).count()
'''}
session_id, result = spark_livy_interactive(host='dzaratsian4.field.hortonworks.com', port='8999', code_payload=code_payload, session_id=session_id)
session_id
result
result['output']['data']['text/plain']
delete_spark_livy_session(host='dzaratsian4.field.hortonworks.com', port='8999', session_id='10')
#ZEND
<file_sep>/sparkR_Airlines.R
###########################################################################################
#
# SparkR Code
#
# Tested on Hortonworks HDP 2.5
# Spark 2.0.0
# http://spark.apache.org/docs/2.0.0/sparkr.html
#
# In Zeppelin, make sure to start Livy Server (start up on port 8998)
# su - livy
# /usr/hdp/current/livy-client/bin/livy-server start
#
###########################################################################################
###########################################################################################
#
# Import Data
#
###########################################################################################
rawdata <- read.df("hdfs:/demo/data/airlines/airlines.csv","csv", header = "true", inferSchema = "false", na.strings = "NA")
head(rawdata)
schema(rawdata)
count(rawdata)
###########################################################################################
#
# Data Processing / Transformations
#
###########################################################################################
# Keep only certain records (drop the column which contains airline reviews, "review")
rawdata$review <- NULL
showDF(rawdata)
schema(rawdata)
count(rawdata)
# id airline date location rating cabin value recommended
#1 10001 Delta Air Lines 2015-06-21 Thailand 7 Economy 4 YES
#2 10002 Delta Air Lines 2015-06-19 USA 0 Economy 2 NO
#3 10003 Delta Air Lines 2015-06-18 USA 0 Economy 1 NO
#4 10004 Delta Air Lines 2015-06-17 USA 9 Business 4 YES
#5 10005 Delta Air Lines 2015-06-17 Ecuador 7 Economy 3 YES
#6 10006 Delta Air Lines 2015-06-17 USA 9 Business 5 YES
# Derive Year, Month, and Day from the date variable.
transformed <- selectExpr(rawdata,
"id",
"date",
"airline",
"location",
"cast(rating as int) rating",
"cabin",
"value",
"recommended",
"substr(date, 1, 4) as year",
"substr(date, 6, 2) as month",
"substr(date, 9, 2) as day"
)
schema(transformed)
# Filter results to show only Delta data
# Where Airline = Delta and Location = USA
head(filter(transformed, transformed$airline == "Delta Air Lines" & transformed$location == "USA"))
showDF(transformed)
###########################################################################################
#
# Aggregations
#
###########################################################################################
# Number of reviews by Airline
showDF(summarize(groupBy(transformed, transformed$airline), number_of_reviews = count(transformed$airline)))
# Average Rating by Airline:
showDF(summarize(groupBy(transformed, transformed$airline), number_of_reviews = count(transformed$airline), average_rating = mean(transformed$rating)))
# Average Rating by Airline and Cabin Type:
showDF(summarize(groupBy(transformed, transformed$airline, transformed$cabin), average_rating = mean(transformed$rating)))
# Number of Categories by "Airline"
showDF(summarize(groupBy(transformed, transformed$airline), number_of_reviews = count(transformed$id)))
# Number of Categories by "Location"
showDF(summarize(groupBy(transformed, transformed$location), number_of_reviews = count(transformed$id)))
# Number of Categories by "Cabin"
showDF(summarize(groupBy(transformed, transformed$cabin), number_of_reviews = count(transformed$id)))
###########################################################################################
#
# SQL Operations
#
###########################################################################################
createOrReplaceTempView(transformed, "transformed_sql")
# Calculate the Average Rating by Airline, order by descending avg_rating
showDF(sql("
SELECT airline, count(*) as number_of_reviews, mean(rating) as avg_rating
FROM transformed_sql
group by airline
order by avg_rating desc"))
###########################################################################################
#
# Applying custom function (UDF)
#
###########################################################################################
s <- structType(structField("id", "string"),
structField("airline", "string"),
structField("rating", "integer"),
structField("test", "integer"))
test <- dapply(transformed, function(x)
{
temp <- x[5] + 500L
test <- cbind(x[1], x[2], x[5], temp )
},
s)
head(test)
###########################################################################################
#
# Modeling (NaiveBayes)
#
###########################################################################################
# Split into Training and Testing DFs
df_training_testing <- randomSplit(transformed, weights=c(0.8, 0.2), seed=12345)
trainingDF <- df_training_testing[[1]]
testingDF <- df_training_testing[[2]]
count(trainingDF)
count(testingDF)
showDF(trainingDF)
nbmodel <- spark.naiveBayes(trainingDF, recommended ~ airline + cabin + year + month + value )
# Model summary
summary(nbmodel)
# Prediction
nbPredictions <- predict(nbmodel, testingDF)
showDF(nbPredictions, 25)
# Show accuracy matrix
accuracy1 <- selectExpr(
summarize(groupBy(nbPredictions, nbPredictions$recommended, nbPredictions$prediction), number_of_reviews = count(transformed$id))
,
"recommended",
"prediction",
"number_of_reviews",
"IF (recommended==prediction, 1, 0) as accurate")
showDF(accuracy1)
#+-----------+----------+-----------------+--------+
#|recommended|prediction|number_of_reviews|accurate|
#+-----------+----------+-----------------+--------+
#| NO| YES| 27| 0|
#| YES| YES| 49| 1|
#| NO| NO| 110| 1|
#| YES| NO| 26| 0|
#+-----------+----------+-----------------+--------+
accuracy2 <- summarize(groupBy(accuracy1, accuracy1$accurate), count = sum(accuracy1$number_of_reviews))
showDF(accuracy2)
# Calculate Accuracy Score
createOrReplaceTempView(nbPredictions, "nbPredictions_sql")
showDF(sql("
select (sum(*) / count(*)) as Accuracy_Score
from
(SELECT IF(recommended==prediction, 1, 0) as accuracy FROM nbPredictions_sql)
"))
# Accuracy_Score
# 0.75
#############################
# Save and Load Model
#############################
#modelPath <- tempfile(pattern = "/tmp/ml", fileext = ".tmp")
#write.ml(nbmodel, modelPath)
#nbmodel2 <- read.ml(modelPath)
#unlink(modelPath)
###########################################################################################
#
# Modeling (GLM)
# (1) Gaussian & (2) Binomial Predictions
#
###########################################################################################
# Family may include (https://stat.ethz.ch/R-manual/R-devel/library/stats/html/family.html):
# binomial(link = "logit")
# gaussian(link = "identity")
# Gamma(link = "inverse")
# inverse.gaussian(link = "1/mu^2")
# poisson(link = "log")
# quasi(link = "identity", variance = "constant")
# quasibinomial(link = "logit")
# quasipoisson(link = "log")
gaussianGLM <- spark.glm(trainingDF, rating ~ airline + cabin + year + month + value, family = "gaussian")
# Model summary
summary(gaussianGLM)
# Prediction
gaussianPredictions <- predict(gaussianGLM, testingDF)
showDF(gaussianPredictions)
#+-----+----------+---------------+-----------+------+-----------+-----+-----------+----+-----+---+-----+------------------+
#| id| date| airline| location|rating| cabin|value|recommended|year|month|day|label| prediction|
#+-----+----------+---------------+-----------+------+-----------+-----+-----------+----+-----+---+-----+------------------+
#|10005|2015-06-17|Delta Air Lines| Ecuador| 7| Economy| 3| YES|2015| 6| 17| 7.0| 4.543003058474369|
#|10008|2015-06-14|Delta Air Lines| USA| 0| Economy| 1| NO|2015| 6| 14| 0.0| 1.548625588686491|
#|10009|2015-06-13|Delta Air Lines| USA| 4| Business| 2| NO|2015| 6| 13| 4.0| 5.146936019287523|
#|10016|2015-06-05|Delta Air Lines| USA| 0| Economy| 1| NO|2015| 6| 5| 0.0| 1.548625588686491|
#|10017|2015-06-03|Delta Air Lines| Canada| 9| Economy| 4| YES|2015| 6| 3| 9.0| 6.040191793368194|
#|10018|2015-06-02|Delta Air Lines| USA| 9| Economy| 5| YES|2015| 6| 2| 9.0| 7.53738052826202|
#|10036|2015-05-05|Delta Air Lines| USA| 5| Economy| 3| NO|2015| 5| 5| 5.0|4.5656995657975585|
#|10077|2015-03-12|Delta Air Lines| USA| 5| Economy| 3| NO|2015| 3| 12| 5.0| 4.61109258044371|
#|10080|2015-03-03|Delta Air Lines| USA| 0|First Class| 1| NO|2015| 3| 3| 0.0| 2.878129135126983|
#|10081|2015-03-03|Delta Air Lines| Germany| 10| Business| 4| YES|2015| 3| 3| 10.0| 8.209403011044742|
#|10089|2015-02-18|Delta Air Lines| USA| 2| Economy| 2| NO|2015| 2| 18| 2.0|3.1366003528726196|
#|10094|2015-02-10|Delta Air Lines| Ireland| 7| Economy| 3| YES|2015| 2| 10| 7.0| 4.633789087766672|
#|10102|2015-01-20|Delta Air Lines| USA| 0| Economy| 1| NO|2015| 1| 20| 0.0|1.6621081253019838|
#+-----+----------+---------------+-----------+------+-----------+-----+-----------+----+-----+---+-----+------------------+
# Fit a generalized linear model of family "binomial" with spark.glm
binomialGLM <- spark.glm(trainingDF, recommended ~ airline + cabin + year + month + value, family = "binomial")
# Model summary
summary(binomialGLM)
# Prediction
binomialPredictions <- predict(binomialGLM, testingDF)
showDF(binomialPredictions)
#+-----+----------+---------------+-----------+------+-----------+-----+-----------+----+-----+---+-----+-------------------+
#| id| date| airline| location|rating| cabin|value|recommended|year|month|day|label| prediction|
#+-----+----------+---------------+-----------+------+-----------+-----+-----------+----+-----+---+-----+-------------------+
#|10005|2015-06-17|Delta Air Lines| Ecuador| 7| Economy| 3| YES|2015| 6| 17| 1.0| 0.5647025067536203|
#|10008|2015-06-14|Delta Air Lines| USA| 0| Economy| 1| NO|2015| 6| 14| 0.0|0.16484310555455592|
#|10009|2015-06-13|Delta Air Lines| USA| 4| Business| 2| NO|2015| 6| 13| 0.0| 0.5491552805132383|
#|10016|2015-06-05|Delta Air Lines| USA| 0| Economy| 1| NO|2015| 6| 5| 0.0|0.16484310555455592|
#|10017|2015-06-03|Delta Air Lines| Canada| 9| Economy| 4| YES|2015| 6| 3| 1.0| 0.7688300479888639|
#|10018|2015-06-02|Delta Air Lines| USA| 9| Economy| 5| YES|2015| 6| 2| 1.0| 0.8950282664177464|
#|10036|2015-05-05|Delta Air Lines| USA| 5| Economy| 3| NO|2015| 5| 5| 0.0| 0.545022785906816|
#|10041|2015-05-04|Delta Air Lines|Switzerland| 10| Economy| 5| YES|2015| 5| 4| 1.0| 0.8873021365295578|
#|10043|2015-05-04|Delta Air Lines| USA| 1| Economy| 1| NO|2015| 5| 4| 0.0| 0.1541632118831403|
#|10080|2015-03-03|Delta Air Lines| USA| 0|First Class| 1| NO|2015| 3| 3| 0.0| 0.1975240148562852|
#|10081|2015-03-03|Delta Air Lines| Germany| 10| Business| 4| YES|2015| 3| 3| 1.0| 0.863077070741532|
#|10089|2015-02-18|Delta Air Lines| USA| 2| Economy| 2| NO|2015| 2| 18| 0.0| 0.2689543087086207|
#|10094|2015-02-10|Delta Air Lines| Ireland| 7| Economy| 3| YES|2015| 2| 10| 1.0|0.48538240625978296|
#|10102|2015-01-20|Delta Air Lines| USA| 0| Economy| 1| NO|2015| 1| 20| 0.0| 0.1170082958954653|
#+-----+----------+---------------+-----------+------+-----------+-----+-----------+----+-----+---+-----+-------------------+
###########################################################################################
#
# Modeling (KMeans Clustering) - Unsupervised
#
###########################################################################################
kmeansdata <- selectExpr(rawdata,
"id",
"date",
"airline",
"location",
"cast(rating as int) as rating",
"cabin",
"cast(value as int) as value",
"recommended",
"cast(substr(date, 1, 4) as int) as year",
"cast(substr(date, 6, 2) as int) as month",
"cast(substr(date, 9, 2) as int) as day"
)
showDF(kmeansdata)
schema(kmeansdata)
# Split into Training and Testing DFs
df_training_testing <- randomSplit(kmeansdata, weights=c(0.8, 0.2), seed=12345)
trainingDF <- df_training_testing[[1]]
testingDF <- df_training_testing[[2]]
count(trainingDF)
count(testingDF)
kmeansModel <- spark.kmeans(trainingDF, ~ rating + value + year + month + day,
k = 5)
# Model summary
summary(kmeansModel)
# Get fitted result from the k-means model
showDF(fitted(kmeansModel))
# Make predictions on holdout/test data
kmeansPredictions <- predict(kmeansModel, testingDF)
showDF(kmeansPredictions)
#ZEND
<file_sep>/text_analytics_classification/README.md
<h3>Text Classification (using Naive Bayes)</h3>
<p>
<strong>Purpose:</strong>
<br>Shows how to use unstructured text data, combined with structured data, to predict an outcome. In this example, I am using labeled data to build a model that predicts airline ratings, based on the customer review of that airline. The rating ranges from 0-10, where 10 is the best rating.
<br>
<br><strong>Input Dataset:</strong>
<br>Airline Reviews as CSV file in HDFS (which I collected using a custom webcrawler)
<br>
<br><strong>Output Result:</strong>
<br>A model, which can be used to score new customer reviews.
<br>I also print out a confusion matrix to show the results (true positives vs misclassifications).
<br>
<br>NOTES:
<br><a href="http://spark.apache.org/docs/latest/api/python/index.html" target="_blank">PySpark Documentation</a>
<br><a href="https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#module-pyspark.mllib.feature" target="_blank">PySpark Mllib Feature Extraction</a>
<br><a href="https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#module-pyspark.mllib.classification" target="_blank">PySpark Mllib Classification Algorithms</a>
<br><a href="http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#module-pyspark.mllib.evaluation" target="_blank">PySpark Mllib Model Evaluation</a>
</p>
note.json is a Zeppelin notebook, which can be imported into your environment and/or viewed from https://www.zeppelinhub.com/viewer/.
<file_sep>/README.md
<img src="Apache_Spark_logo.png" class="inline"/><b>Tips and Tricks</b></h3>
<br>
<br>This repo contains a random collection of Spark code, written mostly in python (using the <a href="http://spark.apache.org/docs/latest/api/python/index.html">PySpark API</a>). I have also included code/scripts in Scala and SparkR. Feel free to copy and use as-in. Let me know if you have any questions or feedback regarding any of the code.
<br>
<br>Zeppelin Notebook Hub (can be used to view Zeppelin notebooks, in json format): https://www.zeppelinhub.com/viewer/
<br>
<br>Spark Tuning & Best Practices Reference: https://github.com/zaratsian/HDP_Tuning_Unofficial
<br>Spark Tuning Tool: https://github.com/zaratsian/Spark/blob/master/spark_tuning_tool.py
<br>
<br><b>Machine Learning Cheatsheets:</b>
<br> • <a href="http://scikit-learn.org/stable/tutorial/machine_learning_map/">SKLearn - Choosing the right estimator</a>
<br> • <a href="https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Keras_Cheat_Sheet_Python.pdf">Keras Cheatsheet</a>
<br> • <a href="http://blogs.sas.com/content/subconsciousmusings/2017/04/12/machine-learning-algorithm-use/">SAS - ML Algorithms</a>
<br> • <a href="https://docs.microsoft.com/en-in/azure/machine-learning/machine-learning-algorithm-cheat-sheet">MS Azure - ML Algorithms</a>
<br> • <a href="https://www.kaggle.com/sudalairajkumar/winning-solutions-of-kaggle-competitions">Kaggle ML Solutions</a>
<br>
<br><b>References:</b>
<br> • <a href="http://spark.apache.org/docs/latest/quick-start.html">Apache Spark Quickstart</a>
<br> • <a href="http://spark.apache.org/docs/latest/api/python/index.html">Spark PySpark (Python) API</a>
<br> • <a href="https://docs.cloud.databricks.com/docs/latest/databricks_guide/index.html#00%20Welcome%20to%20Databricks.html">Databricks - Guide</a>
<br> • <a href="https://sparkhub.databricks.com/resources/">Databricks - Developer Resources</a>
<br> • <a href="https://spark.apache.org/docs/latest/tuning.html">Spark Tuning Guide</a>
<br> • <a href="https://databricks.com/blog/2015/05/28/tuning-java-garbage-collection-for-spark-applications.html">Spark Tuning - Garbage Collection</a>
<br> • <a href="http://docs.hortonworks.com/HDPDocuments/HDP2/HDP-2.5.3/bk_spark-component-guide/content/ch_introduction-spark.html">Hortonworks - Spark Reference</a>
<br> • <a href="https://www.continuum.io/blog/developer-blog/self-service-open-data-science-custom-anaconda-management-packs-hortonworks-hdp">Anaconda Hortonworks Management Packs</a>
<br> • <a href="https://www.gitbook.com/book/umbertogriffo/apache-spark-best-practices-and-tuning/details">Apache Spark - Best Practices & Tuning</a>
<br> • <a href="http://cdn.qubole.com/wp-content/uploads/2017/08/PySpark_SQL_Cheat_Sheet_Python.pdf">PySpark Cheatsheet</a>
<br>
<file_sep>/spark_tuning_tricks.py
# ...in progress...
# Get Spark Configs
def get_spark_configs():
configs = {}
for config in sc._conf.getAll():
configs[config[0]] = config[1]
return configs
# Add python package to all executors
def import_py_packages(executor_num):
import textblob
return executor_num
rdd = sc.parallelize([1, 2, 3])
rdd.map(lambda x: import_py_packages(x))
rdd.collect()
#ZEND
<file_sep>/pyspark_adserver_model.py
import datetime
from pyspark.sql.types import *
from pyspark.sql.functions import monotonically_increasing_id, col, expr, when, concat, lit, udf, split
from pyspark.ml.linalg import Vectors
from pyspark.ml.regression import GBTRegressor, LinearRegression, GeneralizedLinearRegression, RandomForestRegressor
from pyspark.ml.classification import GBTClassifier, RandomForestClassifier, NaiveBayes
from pyspark.ml.clustering import KMeans
from pyspark.ml.feature import VectorIndexer, VectorAssembler, StringIndexer
from pyspark.ml.recommendation import ALS
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml import Pipeline
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
#######################################################################################
#
# Load Data
#
#######################################################################################
rawdata = spark.read.load('/training_data.csv', format="csv", header=True, inferSchema=True)
rawdata.show(10)
print '\nTotal Records: ' + str(rawdata.count()) + '\n'
for i in rawdata.dtypes: print i
#######################################################################################
#
# Explore Data
#
#######################################################################################
'''
# How many unique cars are there (based on vehicle_id)
rawdata.select('activity').distinct().count()
# Describe / find basic stats for numerical data
rawdata.describe(['trip_distance','passenger_count','payment_amount']).show()
# Option 1 - What are my top earning cars
rawdata.groupBy('vehicle_id') \
.agg({'payment_amount': 'sum'}) \
.sort("sum(payment_amount)", ascending=False) \
.show()
'''
# Option 2 - What are my top earning cars
rawdata.createOrReplaceTempView("rawdata_sql")
spark.sql("SELECT activity, count(*) as count FROM rawdata_sql group by activity order by count desc").show()
'''
# What is the average distance and average payment by car/vehicle
spark.sql("SELECT vehicle_id, mean(trip_distance) as avg_distance, mean(payment_amount) as avg_payment FROM rawdata_sql group by vehicle_id order by avg_distance desc").show()
# Covariance
rawdata.stat.cov('payment_amount', 'fare_amount')
rawdata.stat.cov('payment_amount', 'fare_amount')
# Correlation
rawdata.stat.corr('payment_amount', 'fare_amount')
rawdata.stat.corr('tip_amount', 'fare_amount')
# CrossTab
#rawdata.stat.crosstab("item1", "item2").show()
# Frequent Items
#freq = rawdata.stat.freqItems(["a", "b", "c"], 0.4) # Find freqent items up to 40%
#freq.collect()[0]
'''
#######################################################################################
#
# Transformations
#
#######################################################################################
'''
# Extract Trip time
def time_delta(pickup_time, dropoff_time):
pickup_time_out = datetime.datetime.strptime(pickup_time, '%m/%d/%y %H:%M')
dropoff_time_out = datetime.datetime.strptime(dropoff_time, '%m/%d/%y %H:%M')
trip_time = (dropoff_time_out - pickup_time_out).seconds / float(60)
return trip_time
f = udf(time_delta, FloatType())
# (1) Calculate "trip_time"
# (2) Create a "tip_flag" for any record where a customer leaves a tip
# (3) Extract the Pickup Day (as an integer)
# (4) Extract the Pickup Hour (as an integer)
transformed1 = rawdata.withColumn("trip_time", f(rawdata.pickup_datetime, rawdata.dropoff_datetime)) \
.withColumn("tip_flag", (when(rawdata.tip_amount > 0.0, 1).otherwise(0)) ) \
.withColumn("pickup_day", split(rawdata.pickup_datetime,"\/")[1].cast("integer") ) \
.withColumn("pickup_hour", split(split(rawdata.pickup_datetime," ")[1],":")[0].cast("integer") )
'''
#######################################################################################
#
# Model Prep
#
#######################################################################################
# Encode Target (Impression, Hover, Click) on a scale of 1,2,3 respectively
transformeddata = rawdata.withColumn("activity_label", when(col("activity")=='impression', 0) \
.when(col("activity")=='hover', 0) \
.when(col("activity")=='click', 1) \
.otherwise(1))
# String Indexer
strindexer = StringIndexer(inputCol="mediatype", outputCol="mediatype_index")
transformeddata = strindexer.fit(transformeddata).transform(transformeddata)
strindexer = StringIndexer(inputCol="adtype", outputCol="adtype_index")
transformeddata = strindexer.fit(transformeddata).transform(transformeddata)
strindexer = StringIndexer(inputCol="city", outputCol="city_index")
transformeddata = strindexer.fit(transformeddata).transform(transformeddata)
strindexer = StringIndexer(inputCol="state", outputCol="state_index")
transformeddata = strindexer.fit(transformeddata).transform(transformeddata)
strindexer = StringIndexer(inputCol="campaign_category", outputCol="campaign_category_index")
transformeddata = strindexer.fit(transformeddata).transform(transformeddata)
features = ['age','mediatype_index','adtype_index','state_index','campaign_category_index']
# Generate Features Vector and Label
va = VectorAssembler(inputCols=features, outputCol="features")
modelprep = va.transform(transformeddata).withColumn("label", col("activity_label"))
#######################################################################################
#
# Define TRAINING and TESTING dataframes
#
#######################################################################################
# Random Spliting
training, testing = modelprep.randomSplit([0.8, 0.2])
#modelprep2.count()
#training.count()
#testing.count()
#######################################################################################
#
# Modeling - GLM (Regression)
#
#######################################################################################
glm = GeneralizedLinearRegression(featuresCol="features", labelCol="label", maxIter=10, regParam=0.3)
glmmodel = glm.fit(training)
summary = glmmodel.summary
# Show Coefficients and Intercept
print("\nFeatures: " + str(features) + "\n")
print("\nCoefficients: " + str(glmmodel.coefficients) + "\n")
print("\nIntercept: " + str(glmmodel.intercept) + "\n")
print("\nPValues: " + str(summary.pValues) + "\n")
# Summarize the model over the training set and print out some metrics
#print("\nCoefficient Standard Errors: " + str(summary.coefficientStandardErrors))
#print("T Values: " + str(summary.tValues))
#print("P Values: " + str(summary.pValues))
#print("Dispersion: " + str(summary.dispersion))
#print("Null Deviance: " + str(summary.nullDeviance))
#print("Residual Degree Of Freedom Null: " + str(summary.residualDegreeOfFreedomNull))
#print("Deviance: " + str(summary.deviance))
#print("Residual Degree Of Freedom: " + str(summary.residualDegreeOfFreedom))
#print("AIC: " + str(summary.aic))
#print("Deviance Residuals: ")
#summary.residuals().show()
# Make predictions.
predictions = glmmodel.transform(testing)
predictions.registerTempTable('predictions_sql')
# Select example rows to display.
predictions.select("prediction", "label").show(30,False)
evaluator = RegressionEvaluator(metricName="rmse") # rmse (default)|mse|r2|mae
RMSE = evaluator.evaluate(predictions)
print 'RMSE: ' + str(RMSE)
#######################################################################################
#
# Modeling - Gradient Boosting (Classifier)
#
#######################################################################################
#gbt = GBTRegressor(featuresCol="features", labelCol="label", predictionCol="prediction", maxDepth=5, maxBins=32, maxIter=20, seed=12345)
gbt = GBTClassifier(featuresCol="features", labelCol="label", predictionCol="prediction", maxDepth=5, maxBins=75, maxIter=20, seed=12345)
#rf = RandomForestClassifier(featuresCol="features", labelCol="label", predictionCol="prediction", numTrees=3, maxDepth=2, seed=42)
#rf = RandomForestRegressor(featuresCol="features", labelCol="label", predictionCol="prediction", numTrees=2, maxDepth=2, seed=42)
#nb = NaiveBayes(featuresCol="features", labelCol="label", predictionCol="prediction", smoothing=1.0, modelType="multinomial", weightCol=None)
model = gbt.fit(training)
# Get model tree
#model.toDebugString
# Make predictions.
predictions = model.transform(testing)
# Select example rows to display.
predictions.select("prediction", "label").show(30,False)
confusion_matrix = predictions.crosstab('label','prediction')
confusion_matrix.show(10,False)
predictions.createOrReplaceTempView("predictions_sql")
accuracy = spark.sql("SELECT count(*) from predictions_sql where int(prediction) == int(label)").collect()[0][0] / float(predictions.count())
print '\r\nFeature Importance: ' + str(model.featureImportances) + '\r\n'
print '\r\nAccuracy: ' + str(accuracy) + '\r\n'
#######################################################################################
#
# Clustering
#
#######################################################################################
kmeans = KMeans(k=7, seed=12345)
kmmodel = kmeans.fit(training)
centers = model.clusterCenters()
predictions = kmmodel.transform(testing).select("features", "prediction")
predictions.show(30,False)
#ZEND<file_sep>/Sessioning.py
###############################################################################################################
#
# Usage:
#
# Download Data: ftp://ita.ee.lbl.gov/traces/NASA_access_log_Jul95.gz
#
###############################################################################################################
import re,sys
import datetime
from pyspark.sql import Row
from pyspark.sql.types import *
from pyspark.sql.window import Window
from pyspark.sql.functions import rank, lag
from pyspark.sql.functions import udf, sum
##################################################################################
#
# Import Logs
#
##################################################################################
# docker cp ~/Downloads/NASA_access_log_Jul95 zeppelin:/.
logs = sc.textFile("/NASA_access_log_Jul95")
# HOST, TIMESTAMP (DAY MON DD HH:MM:SS YYYY, timezone is -0400), REQUEST, HTTP REPLY CODE, BYTES IN REPLY
##################################################################################
#
# Clean & Parse Logs
#
##################################################################################
records = logs.map(lambda x: x.split(" "))
def cleanrecord(record):
try:
timestamp = datetime.datetime.strptime(record[3].replace("[",""), '%d/%b/%Y:%H:%M:%S')
out = ( str(record[0]),timestamp,str(record[5]).replace('"',"").strip(),str(record[6]).strip(),record[8].strip(),int(record[9]) )
except:
out = ('',datetime.datetime.now(),'','','',0)
return out
recordsDF = records.map(cleanrecord).toDF(("host","datetime","type","request","status_code","bytes"))
#recordsDF.show(10,False)
'''
+--------------------+---------------------+----+-----------------------------------------------+-----------+-----+
|host |datetime |type|request |status_code|bytes|
+--------------------+---------------------+----+-----------------------------------------------+-----------+-----+
|172.16.58.3 |1995-07-01 00:00:01.0|GET |/history/apollo/ |200 |6245 |
|unicomp6.unicomp.net|1995-07-01 00:00:06.0|GET |/shuttle/countdown/ |200 |3985 |
|172.16.31.10 |1995-07-01 00:00:09.0|GET |/shuttle/missions/sts-73/mission-sts-73.html |200 |4085 |
|burger.letters.com |1995-07-01 00:00:11.0|GET |/shuttle/countdown/liftoff.html |304 |0 |
|172.16.31.10 |1995-07-01 00:00:11.0|GET |/shuttle/missions/sts-73/sts-73-patch-small.gif|200 |4179 |
|burger.letters.com |1995-07-01 00:00:12.0|GET |/images/NASA-logosmall.gif |304 |0 |
|burger.letters.com |1995-07-01 00:00:12.0|GET |/shuttle/countdown/video/livevideo.gif |200 |0 |
|172.16.31.10 |1995-07-01 00:00:12.0|GET |/shuttle/countdown/countdown.html |200 |3985 |
|d104.aa.net |1995-07-01 00:00:13.0|GET |/shuttle/countdown/ |200 |3985 |
|192.168.127.12 |1995-07-01 00:00:13.0|GET |/ |200 |7074 |
+--------------------+---------------------+----+-----------------------------------------------+-----------+-----+
'''
##################################################################################
#
# Capture previous (Lag) datetime of session.
# This will be used to calculate time since last visit / session duration.
#
# Partition by HOST
# Sort by DATETIME
#
##################################################################################
wSpec = Window.partitionBy("host").orderBy("datetime")
sessions1 = recordsDF.filter(recordsDF.bytes>=50000).withColumn("previous_time", lag(recordsDF.datetime, 1).over(wSpec) )
#sessions1.show(10,False)
'''
+--------------+---------------------+----+------------------------------------------------------+-----------+------+---------------------+
|host |datetime |type|request |status_code|bytes |previous_time |
+--------------+---------------------+----+------------------------------------------------------+-----------+------+---------------------+
|172.16.17.32|1995-07-05 13:04:31.0|GET |/shuttle/missions/sts-71/images/KSC-95EC-0917.jpg |200 |52491 |null |
|172.16.17.32|1995-07-05 13:36:34.0|GET |/shuttle/missions/sts-71/images/KSC-95EC-0912.jpg |200 |66202 |1995-07-05 13:04:31.0|
|172.16.17.32|1995-07-05 13:51:24.0|GET |/shuttle/technology/sts-newsref/stsref-toc.html |200 |84907 |1995-07-05 13:36:34.0|
|172.16.17.32|1995-07-05 13:52:45.0|GET |/shuttle/technology/sts-newsref/sts_asm.html |200 |71656 |1995-07-05 13:51:24.0|
|172.16.17.32|1995-07-05 13:53:02.0|GET |/shuttle/technology/images/srb_mod_compare_3-small.gif|200 |55666 |1995-07-05 13:52:45.0|
|172.16.17.32|1995-07-05 14:37:37.0|GET |/shuttle/technology/images/srb_mod_compare_3.jpg |200 |258334|1995-07-05 13:53:02.0|
|172.16.17.32|1995-07-06 11:54:06.0|GET |/shuttle/technology/sts-newsref/spacelab.html |200 |104916|null |
|172.16.17.32|1995-07-10 14:56:37.0|GET |/shuttle/technology/sts-newsref/spacelab.html |200 |104916|1995-07-06 11:54:06.0|
|172.16.17.32|1995-07-17 12:06:20.0|GET |/shuttle/technology/sts-newsref/spacelab.html |200 |104914|1995-07-10 14:56:37.0|
|172.16.17.32|1995-07-20 14:55:02.0|GET |/shuttle/technology/sts-newsref/stsref-toc.html |200 |84905 |1995-07-17 12:06:20.0|
+--------------+---------------------+----+------------------------------------------------------+-----------+------+---------------------+
'''
##################################################################################
#
# Calculate time delta between sessions
# This metric can be used for time out purposes, inferring session length, etc.
#
##################################################################################
def time_delta(x,y):
try:
#start = datetime.datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f')
#end = datetime.datetime.strptime(y, '%Y-%m-%d %H:%M:%S.%f')
delta = int((y-x).total_seconds())
except:
delta = 0
return delta
# Register as a UDF
f = udf(time_delta, IntegerType())
sessions2 = sessions1.withColumn('duration', f(sessions1.previous_time, sessions1.datetime))
#sessions2.show(10,False)
'''
+--------------+---------------------+----+------------------------------------------------------+-----------+------+---------------------+--------+
|host |datetime |type|request |status_code|bytes |previous_time |duration|
+--------------+---------------------+----+------------------------------------------------------+-----------+------+---------------------+--------+
|172.16.17.32|1995-07-05 13:04:31.0|GET |/shuttle/missions/sts-71/images/KSC-95EC-0917.jpg |200 |52491 |null |0 |
|172.16.17.32|1995-07-05 13:36:34.0|GET |/shuttle/missions/sts-71/images/KSC-95EC-0912.jpg |200 |66202 |1995-07-05 13:04:31.0|1923 |
|172.16.17.32|1995-07-05 13:51:24.0|GET |/shuttle/technology/sts-newsref/stsref-toc.html |200 |84907 |1995-07-05 13:36:34.0|890 |
|172.16.17.32|1995-07-05 13:52:45.0|GET |/shuttle/technology/sts-newsref/sts_asm.html |200 |71656 |1995-07-05 13:51:24.0|81 |
|172.16.17.32|1995-07-05 13:53:02.0|GET |/shuttle/technology/images/srb_mod_compare_3-small.gif|200 |55666 |1995-07-05 13:52:45.0|17 |
|172.16.17.32|1995-07-05 14:37:37.0|GET |/shuttle/technology/images/srb_mod_compare_3.jpg |200 |258334|1995-07-05 13:53:02.0|2675 |
|172.16.17.32|1995-07-06 11:54:06.0|GET |/shuttle/technology/sts-newsref/spacelab.html |200 |104916|null |0 |
|172.16.17.32|1995-07-10 14:56:37.0|GET |/shuttle/technology/sts-newsref/spacelab.html |200 |104916|1995-07-06 11:54:06.0|356551 |
|172.16.17.32|1995-07-17 12:06:20.0|GET |/shuttle/technology/sts-newsref/spacelab.html |200 |104914|1995-07-10 14:56:37.0|594583 |
|172.16.17.32|1995-07-20 14:55:02.0|GET |/shuttle/technology/sts-newsref/stsref-toc.html |200 |84905 |1995-07-17 12:06:20.0|269322 |
+--------------+---------------------+----+------------------------------------------------------+-----------+------+---------------------+--------+
'''
##################################################################################
#
# Calculate number of sessions for each host
# A session will "timeout" after 900 seconds (15 minutes) of inactivity.
#
##################################################################################
def create_timeout_flag(duration):
session_timeout = 900 # 15 minutes
out = 0
if (duration >= session_timeout) or (duration==0):
out = 1
return out
# Register as a UDF
f = udf(create_timeout_flag, IntegerType())
sessions2.withColumn('timeout_flag', f(sessions2.duration)).registerTempTable("sessions3")
sessions4 = sqlContext.sql("""
SELECT *,
sum(timeout_flag) OVER (PARTITION BY host ORDER BY datetime) as number_of_sessions
FROM sessions3
""")
'''
+--------------+---------------------+----+------------------------------------------------------+-----------+------+---------------------+--------+------------+------------------+
|host |datetime |type|request |status_code|bytes |previous_time |duration|timeout_flag|number_of_sessions|
+--------------+---------------------+----+------------------------------------------------------+-----------+------+---------------------+--------+------------+------------------+
|172.16.17.32|1995-07-05 13:04:31.0|GET |/shuttle/missions/sts-71/images/KSC-95EC-0917.jpg |200 |52491 |null |0 |0 |0 |
|172.16.17.32|1995-07-05 13:36:34.0|GET |/shuttle/missions/sts-71/images/KSC-95EC-0912.jpg |200 |66202 |1995-07-05 13:04:31.0|1923 |1 |1 |
|172.16.17.32|1995-07-05 13:51:24.0|GET |/shuttle/technology/sts-newsref/stsref-toc.html |200 |84907 |1995-07-05 13:36:34.0|890 |0 |1 |
|172.16.17.32|1995-07-05 13:52:45.0|GET |/shuttle/technology/sts-newsref/sts_asm.html |200 |71656 |1995-07-05 13:51:24.0|81 |0 |1 |
|172.16.17.32|1995-07-05 13:53:02.0|GET |/shuttle/technology/images/srb_mod_compare_3-small.gif|200 |55666 |1995-07-05 13:52:45.0|17 |0 |1 |
|172.16.17.32|1995-07-05 14:37:37.0|GET |/shuttle/technology/images/srb_mod_compare_3.jpg |200 |258334|1995-07-05 13:53:02.0|2675 |1 |2 |
|172.16.17.32|1995-07-06 11:54:06.0|GET |/shuttle/technology/sts-newsref/spacelab.html |200 |104916|null |0 |0 |0 |
|172.16.17.32|1995-07-10 14:56:37.0|GET |/shuttle/technology/sts-newsref/spacelab.html |200 |104916|1995-07-06 11:54:06.0|356551 |1 |1 |
|172.16.17.32|1995-07-17 12:06:20.0|GET |/shuttle/technology/sts-newsref/spacelab.html |200 |104914|1995-07-10 14:56:37.0|594583 |1 |2 |
|192.168.3.1130|1995-07-20 14:55:02.0|GET |/shuttle/technology/sts-newsref/stsref-toc.html |200 |84905 |1995-07-17 12:06:20.0|269322 |1 |3 |
+--------------+---------------------+----+------------------------------------------------------+-----------+------+---------------------+--------+------------+------------------+
'''
sessions4.groupBy("host").avg("duration").alias("avg_duration").show(10,False)
#ZEND
|
cfb05fc3661064a5f4fb0e8aba6b8e087b61b575
|
[
"Markdown",
"Python",
"R"
] | 26
|
R
|
anhmaivu88/Spark
|
5304b4741646c9ab0f29025bf0ebb20ce88e5fc4
|
a7c8a6a5f1008cf41358963c043b34d3ba5f61fc
|
refs/heads/master
|
<file_sep>const hljs = require('highlight.js');
// Initialize highlight.js
$(document).ready(function() {
hljs.initHighlightingOnLoad()
});
|
ed7b71f6e0860e67bcfd2fdc048ab1e95c153771
|
[
"JavaScript"
] | 1
|
JavaScript
|
LilyBell/symfonyEncore
|
b5aab7758788cded4b828d24890f6cab3e7d90d4
|
b786938cac4436c41c03c9239a6e62e197428aca
|
refs/heads/main
|
<file_sep>module github.com/digitalocean/mtls-tech-talk
go 1.16
<file_sep>BASE_DIR := $(shell git rev-parse --show-toplevel 2>/dev/null)
export VAULT_ADDR=http://127.0.0.1:8200
# =====================================================================
# Services
# =====================================================================
.PHONY: run-mtls-service
run-mtls-service:
go run ./cmd/mtls-service/main.go \
-cert target/server.crt \
-key target/server.pem
.PHONY: run-verify-connection
run-verify-connection:
go run ./cmd/verify-connection/main.go
.PHONY: run-verify-middleware
run-verify-middleware:
go run ./cmd/verify-middleware/main.go
.PHONY: run-alice-pki-service
run-alice-pki-service:
go run ./cmd/mtls-service/main.go -root target/alice-ca.crt
.PHONY: run-http-service
run-http-service:
go run ./cmd/http-service/main.go
.PHONY: run-nginx
run-nginx:
nginx -g 'daemon off;' -p ${BASE_DIR} -c ${BASE_DIR}/nginx.conf
.PHONY: run-haproxy
run-haproxy:
cat target/server.crt > target/server-all.crt
cat target/server.pem >> target/server-all.crt
haproxy -C ${BASE_DIR} -f haproxy.conf
# =====================================================================
# Clients
# =====================================================================
.PHONY: run-alice-client
run-alice-client:
go run ./cmd/mtls-client/main.go \
-cert target/alice.crt \
-key target/alice.pem \
-name Alice
.PHONY: run-bob-client
run-bob-client:
go run ./cmd/mtls-client/main.go \
-cert target/bob.crt \
-key target/bob.pem \
-name Bob
.PHONY: run-alice-pki-client
run-alice-pki-client:
go run ./cmd/mtls-client/main.go \
-cert target/alice-pki.crt \
-key target/alice-pki.pem \
-name Alice
.PHONY: run-bob-pki-client
run-bob-pki-client:
go run ./cmd/mtls-client/main.go \
-cert target/bob-pki.crt \
-key target/bob-pki.pem \
-name Bob
# =====================================================================
# Vault PKI
# =====================================================================
.PHONY: clean
clean:
rm -rf target
target:
mkdir target
target/vault: | target
ifeq ($(shell uname -s),Darwin)
curl -SsfL -o target/vault.zip https://releases.hashicorp.com/vault/1.5.4/vault_1.5.4_darwin_amd64.zip
else
curl -SsfL -o target/vault.zip https://releases.hashicorp.com/vault/1.5.4/vault_1.5.4_linux_amd64.zip
endif
unzip target/vault.zip -d target
rm target/vault.zip
chmod +x target/vault
.PHONY: run-vault
run-vault: | target/vault
bash -c 'trap "rm -f ~/.vault-token" EXIT; ./target/vault server -dev -dev-root-token-id="root"'
.PHONY: setup-pki
setup-pki: setup-root-pki setup-alice-pki setup-bob-pki
.PHONY: setup-root-pki
setup-root-pki: setup-root-ca issue-server-cert issue-alice-cert issue-bob-cert
.PHONY: setup-alice-pki
setup-alice-pki: setup-alice-ca issue-alice-pki-cert
.PHONY: setup-bob-pki
setup-bob-pki: setup-bob-ca issue-bob-pki-cert
.PHONY: setup-root-ca
setup-root-ca: | target/vault
./target/vault secrets enable \
-path pki_local \
-max-lease-ttl=87600h \
pki
./target/vault write pki_local/config/urls \
issuing_certificates="http://127.0.0.1:8200/v1/pki_local/ca" \
crl_distribution_points="http://127.0.0.1:8200/v1/pki_local/crl"
./target/vault write -format=json \
pki_local/root/generate/internal \
common_name="Local Root CA" \
ttl=87600h \
key_type=rsa \
key_bits=2048 \
> target/root.json
./target/vault write pki_local/roles/service \
allowed_domains="example.com" \
allow_bare_domains="true" \
allow_subdomains="true" \
allow_localhost="true" \
enforce_hostnames="true" \
allow_ip_sans="true" \
max_ttl="720h" \
key_type=rsa \
key_bits=2048
jq -r '.data.certificate' target/root.json > target/root.crt
openssl x509 -text -noout -in target/root.crt
.PHONY: issue-server-cert
issue-server-cert: | target/vault
./target/vault write -format=json \
pki_local/issue/service \
common_name=www.example.com \
alt_names=localhost \
ip_sans=127.0.0.1 \
> target/server.json
jq -r '.data.certificate' target/server.json > target/server.crt
jq -r '.data.private_key' target/server.json > target/server.pem
openssl x509 -text -noout -in target/server.crt
.PHONY: issue-alice-cert
issue-alice-cert: | target/vault
./target/vault write -format=json \
pki_local/issue/service \
common_name=alice.example.com \
> target/alice.json
jq -r '.data.certificate' target/alice.json > target/alice.crt
jq -r '.data.private_key' target/alice.json > target/alice.pem
openssl x509 -text -noout -in target/alice.crt
.PHONY: issue-bob-cert
issue-bob-cert: | target/vault
./target/vault write -format=json \
pki_local/issue/service \
common_name=bob.example.com \
> target/bob.json
jq -r '.data.certificate' target/bob.json > target/bob.crt
jq -r '.data.private_key' target/bob.json > target/bob.pem
openssl x509 -text -noout -in target/bob.crt
.PHONY: setup-alice-ca
setup-alice-ca: | target/vault
./target/vault secrets enable -path=pki_alice pki
./target/vault secrets tune -max-lease-ttl=43800h pki_alice
./target/vault write -format=json \
pki_alice/intermediate/generate/internal \
common_name="Alice Intermediate Authority" \
ttl=43800h \
> target/alice-ca-csr.json
jq -r '.data.csr' target/alice-ca-csr.json > target/alice-ca.csr
./target/vault write -format=json \
pki_local/root/sign-intermediate \
csr=@target/alice-ca.csr \
format=pem_bundle \
ttl=43800h \
> target/alice-ca.json
jq -r '.data.certificate' target/alice-ca.json > target/alice-ca.crt
./target/vault write \
pki_alice/intermediate/set-signed \
certificate=@target/alice-ca.crt
./target/vault write pki_alice/config/urls \
issuing_certificates="http://127.0.0.1:8200/v1/pki_alice/ca" \
crl_distribution_points="http://127.0.0.1:8200/v1/pki_alice/crl"
./target/vault write pki_alice/roles/service \
allowed_domains="example.com" \
allow_bare_domains="true" \
allow_subdomains="true" \
allow_localhost="true" \
enforce_hostnames="true" \
allow_ip_sans="true" \
max_ttl="720h" \
key_type=rsa \
key_bits=2048
openssl x509 -text -noout -in target/alice-ca.crt
.PHONY: setup-bob-ca
setup-bob-ca: | target/vault
./target/vault secrets enable -path=pki_bob pki
./target/vault secrets tune -max-lease-ttl=43800h pki_bob
./target/vault write -format=json \
pki_bob/intermediate/generate/internal \
common_name="Bob Intermediate Authority" \
ttl=43800h \
> target/bob-ca-csr.json
jq -r '.data.csr' target/bob-ca-csr.json > target/bob-ca.csr
./target/vault write -format=json \
pki_local/root/sign-intermediate \
csr=@target/bob-ca.csr \
format=pem_bundle \
ttl=43800h \
> target/bob-ca.json
jq -r '.data.certificate' target/bob-ca.json > target/bob-ca.crt
./target/vault write \
pki_bob/intermediate/set-signed \
certificate=@target/bob-ca.crt
./target/vault write pki_bob/config/urls \
issuing_certificates="http://127.0.0.1:8200/v1/pki_bob/ca" \
crl_distribution_points="http://127.0.0.1:8200/v1/pki_bob/crl"
./target/vault write pki_bob/roles/service \
allowed_domains="example.com" \
allow_bare_domains="true" \
allow_subdomains="true" \
allow_localhost="true" \
enforce_hostnames="true" \
allow_ip_sans="true" \
max_ttl="720h" \
key_type=rsa \
key_bits=2048
openssl x509 -text -noout -in target/bob-ca.crt
.PHONY: issue-alice-pki-cert
issue-alice-pki-cert: | target/vault
./target/vault write -format=json \
pki_alice/issue/service \
common_name=alice.example.com \
> target/alice-pki.json
jq -r '.data.certificate' target/alice-pki.json > target/alice-pki.crt
jq -r '.data.issuing_ca' target/alice-pki.json >> target/alice-pki.crt
jq -r '.data.private_key' target/alice-pki.json > target/alice-pki.pem
openssl x509 -text -noout -in target/alice-pki.crt
.PHONY: issue-bob-pki-cert
issue-bob-pki-cert: | target/vault
./target/vault write -format=json \
pki_bob/issue/service \
common_name=bob.example.com \
> target/bob-pki.json
jq -r '.data.certificate' target/bob-pki.json > target/bob-pki.crt
jq -r '.data.issuing_ca' target/bob-pki.json >> target/bob-pki.crt
jq -r '.data.private_key' target/bob-pki.json > target/bob-pki.pem
openssl x509 -text -noout -in target/bob-pki.crt
<file_sep>package main
import (
"fmt"
"log"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
name = "World"
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, "Hello", name)
}
func main() {
log.Println("starting server")
http.ListenAndServe(":3001", http.HandlerFunc(handler))
}
<file_sep># mtls-tech-talk
[From Wikipedia](https://en.wikipedia.org/wiki/Mutual_authentication)
> Mutual authentication or two-way authentication refers to two parties authenticating each other at the same time, being a default mode of authentication in some protocols (IKE, SSH) and optional in others (TLS). By default the TLS protocol only proves the identity of the server to the client using X.509 certificate and the authentication of the client to the server is left to the application layer. TLS also offers client-to-server authentication using client-side X.509 authentication. As it requires provisioning of the certificates to the clients and involves less user-friendly experience, it's rarely used in end-user applications.
Managing a PKI (public key infrastructure) and provisioning of client and server certificates is frequently seen as tedious and painful. The same can be said for configuring clients and servers, with the added annoyance of native key & certificate store formats.
In the last few years products like HashiCorp's [Vault](https://www.vaultproject.io/) have make managing a PKI easier, and have provided reasonable APIs to make issuing certificates a straight-forward process. Language libraries have evolved to allow developers to easily configure TLS for clients and servers. Tools have also evolved to make the conversion between certificate formats easier (for example [pemToJks](https://github.com/tomcz/pemToJks)).
I'd like to show you how to use Vault to manage a PKI infrastructure that allows for mTLS between golang-based clients and servers. All the following code is also available for you to explore in this repository.
## Requirements
1. Three open terminals (#1, #2, and #3)
2. [go v1.16](https://golang.org/dl/)
3. [curl](https://curl.haxx.se/)
4. [jq](https://stedolan.github.io/jq/)
5. [openssl](https://www.openssl.org/)
## Set up Vault
Download [Vault](https://www.vaultproject.io/downloads):
### On Linux
```
$> mkdir target
$> curl -SsfL -o target/vault.zip https://releases.hashicorp.com/vault/1.5.4/vault_1.5.4_linux_amd64.zip
$> unzip target/vault.zip -d target
$> rm target/vault.zip
$> chmod +x target/vault
```
### On OSX
```
$> mkdir target
$> curl -SsfL -o target/vault.zip https://releases.hashicorp.com/vault/1.5.4/vault_1.5.4_darwin_amd64.zip
$> unzip target/vault.zip -d target
$> rm target/vault.zip
$> chmod +x target/vault
```
### Start the Vault server in dev mode
This is great for experimentation as it does not require any backing data stores (like [Consul](https://learn.hashicorp.com/collections/vault/day-one-consul)), but it should not be how you run Vault in production.
In terminal #1:
```
$> ./target/vault server -dev -dev-root-token-id="root"
```
This will create a `.vault-token` file at the root of your home directory that will contain the `root` Vault token. We are going to skip a lot of Vault configuration that you'd need to make for a serious production setup because this is not an article about configuring Vault, but please note that using root tokens in production is a terrible idea.
If we want Vault to create TLS certificates for us it needs to be set up to act as a certifying authority (CA).
### Create a root certifying authority in vault
With Vault running in terminal #1, run the following in terminal #2:
```
$> export VAULT_ADDR='http://127.0.0.1:8200'
$> ./target/vault secrets enable \
-path pki_local \
-max-lease-ttl=87600h \
pki
$> ./target/vault write pki_local/config/urls \
issuing_certificates="http://127.0.0.1:8200/v1/pki_local/ca" \
crl_distribution_points="http://127.0.0.1:8200/v1/pki_local/crl"
$> ./target/vault write -format=json \
pki_local/root/generate/internal \
common_name="Local Root CA" \
ttl=87600h \
key_type=rsa \
key_bits=2048 \
> target/root.json
$> ./target/vault write pki_local/roles/service \
allowed_domains="example.com" \
allow_bare_domains="true" \
allow_subdomains="true" \
allow_localhost="true" \
enforce_hostnames="true" \
allow_ip_sans="true" \
max_ttl="720h" \
key_type=rsa \
key_bits=2048
$> jq -r '.data.certificate' target/root.json > target/root.crt
```
We now have a running Vault instance, set up to generate TLS certificates, and `target/root.crt` contains the public certificate of our new root CA.
## Server and client-side TLS (mTLS)
### Issue a server certificate using our new root CA
With Vault running in terminal #1, run the following in terminal #2:
```
$> export VAULT_ADDR='http://127.0.0.1:8200'
$> ./target/vault write -format=json \
pki_local/issue/service \
common_name=www.example.com \
alt_names=localhost \
ip_sans=127.0.0.1 \
> target/server.json
$> jq -r '.data.certificate' target/server.json > target/server.crt
$> jq -r '.data.private_key' target/server.json > target/server.pem
```
This creates two files: `target/server.crt` which contains the server's public certificate, and `target/server.pem` which contains the server's private key.
### Issue a client certificate for Alice using our new root CA
With Vault running in terminal #1, run the following in terminal #2:
```
$> export VAULT_ADDR='http://127.0.0.1:8200'
$> ./target/vault write -format=json \
pki_local/issue/service \
common_name=alice.example.com \
> target/alice.json
$> jq -r '.data.certificate' target/alice.json > target/alice.crt
$> jq -r '.data.private_key' target/alice.json > target/alice.pem
```
This creates two files: `target/alice.crt` which contains Alice's public certificate, and `target/alice.pem` which contains Alice's private key.
### Create a golang HTTPS service that requires client TLS certificates
The server presents its own TLS certificate to clients during the HTTPS handshake, and requires that a client must present its own certificate during the handshake. It validates a client's certificate to ensure that it has been signed by our root CA.
[cmd/mtls-service/main.go](https://github.com/digitalocean/mtls-tech-talk/blob/main/cmd/mtls-service/main.go)
```go
package main
import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
)
var (
rootFile = flag.String("root", "target/root.crt", "Root CA certificate file")
certFile = flag.String("cert", "target/server.crt", "Server TLS certificate file")
keyFile = flag.String("key", "target/server.pem", "Server TLS private key file")
)
func handler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
name = "World"
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, "Hello", name)
}
func main() {
flag.Parse()
rootCaPool := x509.NewCertPool()
rootPEM, err := ioutil.ReadFile(*rootFile)
if err != nil {
log.Fatalln(err)
}
if ok := rootCaPool.AppendCertsFromPEM(rootPEM); !ok {
log.Fatalln("failed to parse Root CA file")
}
serverCert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
if err != nil {
log.Fatalln(err)
}
tlsCfg := &tls.Config{
Certificates: []tls.Certificate{serverCert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: rootCaPool,
}
server := &http.Server{
Addr: ":3000",
Handler: http.HandlerFunc(handler),
TLSConfig: tlsCfg,
}
log.Println("starting server")
if err := server.ListenAndServeTLS("", ""); err != nil {
log.Fatalln(err)
}
}
```
### Create a golang HTTPS client that presents its own TLS certificate
The client presents its own TLS certificate to a server during the HTTPS handshake, and validates the server's certificate to ensure that it has been signed by our root CA.
[cmd/mtls-client/main.go](https://github.com/digitalocean/mtls-tech-talk/blob/main/cmd/mtls-client/main.go)
```go
package main
import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
)
var (
rootFile = flag.String("root", "target/root.crt", "Root CA certificate file")
certFile = flag.String("cert", "", "Client TLS certificate file")
keyFile = flag.String("key", "", "Client TLS private key file")
sendName = flag.String("name", "", "Name to send to the server")
)
func main() {
flag.Parse()
rootCaPool := x509.NewCertPool()
rootPEM, err := ioutil.ReadFile(*rootFile)
if err != nil {
log.Fatalln(err)
}
if ok := rootCaPool.AppendCertsFromPEM(rootPEM); !ok {
log.Fatalln("failed to parse Root CA file")
}
clientCert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
if err != nil {
log.Fatalln(err)
}
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: rootCaPool,
Certificates: []tls.Certificate{clientCert},
},
},
}
req, err := http.NewRequest("GET", "https://localhost:3000/", nil)
if err != nil {
log.Fatalln(err)
}
if *sendName != "" {
q := req.URL.Query()
q.Add("name", *sendName)
req.URL.RawQuery = q.Encode()
}
res, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatalln(err)
}
fmt.Println(string(body))
}
```
### Test it out
Run the server using in terminal #2:
```
$> go run ./cmd/mtls-service/main.go
```
Run the client as Alice in terminal #3:
```
$> go run ./cmd/mtls-client/main.go -name Alice -cert target/alice.crt -key target/alice.pem
Hello Alice
```
## What about Bob?
We can generate a certificate for Bob using Vault in terminal #3:
```
$> export VAULT_ADDR='http://127.0.0.1:8200'
$> ./target/vault write -format=json \
pki_local/issue/service \
common_name=bob.example.com \
> target/bob.json
$> jq -r '.data.certificate' target/bob.json > target/bob.crt
$> jq -r '.data.private_key' target/bob.json > target/bob.pem
```
We can call the service as Bob in terminal #3:
```
go run ./cmd/mtls-client/main.go -name Bob -cert target/bob.crt -key target/bob.pem
Hello Bob
```
### What if we don't want to allow Bob to access the service?
The standard answer in some places is multiple CAs, and this is a valid option if you cannot configure your services in more complex ways.
1. We could create a two different CAs. One that generates certificates for Bobs, and another that generates certificates for Alices. That way a server that only trusts an Alice will never trust a Bob.
2. We could keep our root CA, and have it sign two intermediate CA certificates, one for an Alice CA and another for a Bob CA. This is an extension to option 1 that allows some services to trust the root CA and therefore allow any Alice or Bob to access them, but still have services that only trust the intermediate CAs and therefore only allow Alice to access Alices' services, and Bob to access Bobs' services.
#### Multiple intermediate CAs with vault
Set up an Alice-only CA in terminal #2:
```
$> export VAULT_ADDR='http://127.0.0.1:8200'
$> ./target/vault secrets enable -path=pki_alice pki
$> ./target/vault secrets tune -max-lease-ttl=43800h pki_alice
$> ./target/vault write -format=json \
pki_alice/intermediate/generate/internal \
common_name="Alice Intermediate Authority" \
ttl=43800h \
> target/alice-ca-csr.json
$> jq -r '.data.csr' target/alice-ca-csr.json > target/alice-ca.csr
$> ./target/vault write -format=json \
pki_local/root/sign-intermediate \
csr=@target/alice-ca.csr \
format=pem_bundle \
ttl=43800h \
> target/alice-ca.json
$> jq -r '.data.certificate' target/alice-ca.json > target/alice-ca.crt
$> ./target/vault write \
pki_alice/intermediate/set-signed \
certificate=@target/alice-ca.crt
$> ./target/vault write pki_alice/config/urls \
issuing_certificates="http://127.0.0.1:8200/v1/pki_alice/ca" \
crl_distribution_points="http://127.0.0.1:8200/v1/pki_alice/crl"
$> ./target/vault write pki_alice/roles/service \
allowed_domains="example.com" \
allow_bare_domains="true" \
allow_subdomains="true" \
allow_localhost="true" \
enforce_hostnames="true" \
allow_ip_sans="true" \
max_ttl="720h" \
key_type=rsa \
key_bits=2048
```
Set up a Bob-only CA in terminal #2:
```
$> export VAULT_ADDR='http://127.0.0.1:8200'
$> ./target/vault secrets enable -path=pki_bob pki
$> ./target/vault secrets tune -max-lease-ttl=43800h pki_bob
$> ./target/vault write -format=json \
pki_bob/intermediate/generate/internal \
common_name="Bob Intermediate Authority" \
ttl=43800h \
> target/bob-ca-csr.json
$> jq -r '.data.csr' target/bob-ca-csr.json > target/bob-ca.csr
$> ./target/vault write -format=json \
pki_local/root/sign-intermediate \
csr=@target/bob-ca.csr \
format=pem_bundle \
ttl=43800h \
> target/bob-ca.json
$> jq -r '.data.certificate' target/bob-ca.json > target/bob-ca.crt
./target/vault write \
pki_bob/intermediate/set-signed \
certificate=@target/bob-ca.crt
$> ./target/vault write pki_bob/config/urls \
issuing_certificates="http://127.0.0.1:8200/v1/pki_bob/ca" \
crl_distribution_points="http://127.0.0.1:8200/v1/pki_bob/crl"
$> ./target/vault write pki_bob/roles/service \
allowed_domains="example.com" \
allow_bare_domains="true" \
allow_subdomains="true" \
allow_localhost="true" \
enforce_hostnames="true" \
allow_ip_sans="true" \
max_ttl="720h" \
key_type=rsa \
key_bits=2048
```
Issue an Alice TLS certificate using the Alice-only CA in terminal #2:
```
$> export VAULT_ADDR='http://127.0.0.1:8200'
$> ./target/vault write -format=json \
pki_alice/issue/service \
common_name=alice.example.com \
> target/alice-pki.json
$> jq -r '.data.certificate' target/alice-pki.json > target/alice-pki.crt
$> jq -r '.data.issuing_ca' target/alice-pki.json >> target/alice-pki.crt
$> jq -r '.data.private_key' target/alice-pki.json > target/alice-pki.pem
```
Please note that we are also appending the certificate of the issuing CA (ie. Alice Intermediate Authority) to `target/alice-pki.crt` so that services that only trust the root CA can verify that Alice's certificate was ultimately issued by a CA that they trust.
Issue a Bob TLS certificate using the Bob-only CA in terminal #2:
```
$> export VAULT_ADDR='http://127.0.0.1:8200'
$> ./target/vault write -format=json \
pki_bob/issue/service \
common_name=bob.example.com \
> target/bob-pki.json
$> jq -r '.data.certificate' target/bob-pki.json > target/bob-pki.crt
$> jq -r '.data.issuing_ca' target/bob-pki.json >> target/bob-pki.crt
$> jq -r '.data.private_key' target/bob-pki.json > target/bob-pki.pem
```
Please note that we are also appending the certificate of the issuing CA (ie. Bob Intermediate Authority) to `target/bob-pki.crt` so that services that only trust the root CA can verify that Bob's certificate was ultimately issued by a CA that they trust.
In terminal #2, start the service using the root CA:
```
$> go run ./cmd/mtls-service/main.go -root target/root.crt
```
In terminal #3, both Alice and Bob should still have access using their new intermediate CA generated client certificates:
```
$> go run ./cmd/mtls-client/main.go -name Alice -cert target/alice-pki.crt -key target/alice-pki.pem
Hello Alice
$> go run ./cmd/mtls-client/main.go -name Bob -cert target/bob-pki.crt -key target/bob-pki.pem
Hello Bob
```
In terminal #2, if we change the service to use the Alice-only CA:
```
$> go run ./cmd/mtls-service/main.go -root target/alice-ca.crt
```
In terminal #3, Alice should be able to connect, and Bob fails for a mysterious certificate error:
```
$> go run ./cmd/mtls-client/main.go -cert target/alice-pki.crt -key target/alice-pki.pem
Hello World
$> go run ./cmd/mtls-client/main.go -cert target/bob-pki.crt -key target/bob-pki.pem
2020/09/22 10:14:07 Get "https://localhost:3000/?name=Bob": remote error: tls: bad certificate
```
Even the server logs in terminal #2 are not helpful:
```
2020/09/22 10:14:07 http: TLS handshake error from [::1]:61014: tls: client didn't provide a certificate
```
This is good enough, but we can do better.
### What if we want to only have the one CA?
But we still do not want to allow Bob to access services that only Alice should have access to.
There are three common options:
1. Generic: Use a proxy (like HAProxy or Nginx) to terminate TLS and validate the client certificate.
2. Go-specific: Fail certificate verification if the certificate does not belong to an Alice.
3. Go-specific: Use middleware to verify the certificate so that we can capture more information.
#### Option 1a - Nginx:
Create a Nginx configuration file to only permit Alice's Common Name:
[nginx.conf](https://github.com/digitalocean/mtls-tech-talk/blob/main/nginx.conf)
```
worker_processes 1;
error_log stderr;
events {
worker_connections 1024;
}
http {
default_type application/octet-stream;
access_log /dev/stdout;
keepalive_timeout 60;
gzip on;
map $ssl_client_s_dn $ssl_client_s_dn_cn {
default "";
~CN=(?<CN>[^,]+) $CN;
}
map $ssl_client_s_dn_cn $ssl_client_s_dn_cn_allowed {
default "no";
~^alice\.example\.com$ "yes";
}
server {
listen 3000 ssl;
ssl_certificate target/server.crt;
ssl_certificate_key target/server.pem;
ssl_client_certificate target/root.crt;
ssl_verify_client on;
ssl_verify_depth 3;
if ($ssl_client_s_dn_cn_allowed = "no") {
return 403;
}
location / {
proxy_pass http://127.0.0.1:3001;
proxy_redirect off;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
}
}
```
In terminal #1, start a basic http service:
```
go run ./cmd/http-service/main.go
```
In terminal #2, start Nginx:
```
$> export BASE_DIR=$(git rev-parse --show-toplevel 2>/dev/null)
$> nginx -g 'daemon off;' -p ${BASE_DIR} -c ${BASE_DIR}/nginx.conf
```
Connect as Alice and Bob in terminal #3:
```
$> go run ./cmd/mtls-client/main.go -name Alice -cert target/alice.crt -key target/alice.pem
Hello Alice
$> go run ./cmd/mtls-client/main.go -name Bob -cert target/bob.crt -key target/bob.pem
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.19.2</center>
</body>
</html>
```
Better than failing the TLS handshake.
#### Option 1b - HAProxy:
Create a HAProxy configuration file to only permit Alice's Common Name:
[haproxy.conf](https://github.com/digitalocean/mtls-tech-talk/blob/main/haproxy.conf)
```
global
maxconn 256
log stdout local0
defaults
mode http
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
log global
frontend http-in
bind *:3000 ssl crt target/server-all.crt ca-file target/root.crt verify required
default_backend servers
acl tls_client_cn_allowed ssl_c_s_dn(cn) -m reg ^alice\.example\.com$
http-request deny unless tls_client_cn_allowed
http-request add-header X-Forwarded-Proto https
backend servers
server server1 127.0.0.1:3001 maxconn 32
```
In terminal #1, start a basic http service:
```
go run ./cmd/http-service/main.go
```
In terminal #2, start HAProxy. Please note that HAProxy requires that the certificate and private key are in a single file:
```
$> export BASE_DIR=$(git rev-parse --show-toplevel 2>/dev/null)
$> cat target/server.crt > target/server-all.crt
$> cat target/server.pem >> target/server-all.crt
$> haproxy -C ${BASE_DIR} -f haproxy.conf
```
Connect as Alice and Bob in terminal #3:
```
$> go run ./cmd/mtls-client/main.go -name Alice -cert target/alice.crt -key target/alice.pem
Hello Alice
$> go run ./cmd/mtls-client/main.go -name Bob -cert target/bob.crt -key target/bob.pem
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
```
Better than failing the TLS handshake, less config than Nginx, but not really all that great.
#### Option 2:
Go's `net/http` TLS configuration allows us to abort the TLS handshake after its standard verification steps have completed. We can use that to reject non-Alice certificates.
[cmd/verify-connection/main.go](https://github.com/digitalocean/mtls-tech-talk/blob/main/cmd/verify-connection/main.go)
```go
package main
import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
)
var (
rootFile = flag.String("root", "target/root.crt", "Root CA certificate file")
certFile = flag.String("cert", "target/server.crt", "Server TLS certificate file")
keyFile = flag.String("key", "target/server.pem", "Server TLS private key file")
)
func handler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
name = "World"
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, "Hello", name)
}
func verifyConnection(state tls.ConnectionState) error {
clientCert := state.PeerCertificates[0]
cn := clientCert.Subject.CommonName
if cn != "alice.example.com" {
return fmt.Errorf("%s is not allowed", cn)
}
return nil
}
func main() {
flag.Parse()
rootCaPool := x509.NewCertPool()
rootPEM, err := ioutil.ReadFile(*rootFile)
if err != nil {
log.Fatalln(err)
}
if ok := rootCaPool.AppendCertsFromPEM(rootPEM); !ok {
log.Fatalln("failed to parse Root CA file")
}
serverCert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
if err != nil {
log.Fatalln(err)
}
tlsCfg := &tls.Config{
Certificates: []tls.Certificate{serverCert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: rootCaPool,
VerifyConnection: verifyConnection,
}
server := &http.Server{
Addr: ":3000",
Handler: http.HandlerFunc(handler),
TLSConfig: tlsCfg,
}
log.Println("starting server")
if err := server.ListenAndServeTLS("", ""); err != nil {
log.Fatalln(err)
}
}
```
Run the service in terminal #2:
```
$> go run ./cmd/verify-connection/main.go
```
Connect as Alice and Bob in terminal #3:
```
$> go run ./cmd/mtls-client/main.go -name Alice -cert target/alice.crt -key target/alice.pem
Hello Alice
$> go run ./cmd/mtls-client/main.go -name Bob -cert target/bob.crt -key target/bob.pem
2020/09/22 10:15:36 Get "https://localhost:3000/?name=Bob": remote error: tls: bad certificate
```
Alice can connect, Bob fails with a bad certificate error and attempts to tear their hair out figuring why they have a bad certificate. Meanwhile, the server terminal #2 shows a suspicious TLS error:
```
2020/09/22 10:15:36 http: TLS handshake error from [::1]:61025: bob.example.com not allowed
```
Oops, this is a bit worse than a proxy. We must be able to do better.
#### Option 3:
We can let the TLS connection get established, then use middleware to inspect the request and see who has connected to us. This allows us to return more informative errors to clients rather than just killing the HTTPS handshake.
[cmd/verify-middleware/main.go](https://github.com/digitalocean/mtls-tech-talk/tree/main/cmd/verify-middleware/main.go)
```go
package main
import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
)
var (
rootFile = flag.String("root", "target/root.crt", "Root CA certificate file")
certFile = flag.String("cert", "target/server.crt", "Server TLS certificate file")
keyFile = flag.String("key", "target/server.pem", "Server TLS private key file")
)
func handler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
name = "World"
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, "Hello", name)
}
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
clientCert := r.TLS.PeerCertificates[0]
cn := clientCert.Subject.CommonName
if cn != "alice.example.com" {
log.Printf("%s is not allowed\n", cn)
msg := fmt.Sprintf("you cannot be here %s", cn)
http.Error(w, msg, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
flag.Parse()
rootCaPool := x509.NewCertPool()
rootPEM, err := ioutil.ReadFile(*rootFile)
if err != nil {
log.Fatalln(err)
}
if ok := rootCaPool.AppendCertsFromPEM(rootPEM); !ok {
log.Fatalln("failed to parse Root CA file")
}
serverCert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
if err != nil {
log.Fatalln(err)
}
tlsCfg := &tls.Config{
Certificates: []tls.Certificate{serverCert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: rootCaPool,
}
server := &http.Server{
Addr: ":3000",
Handler: middleware(http.HandlerFunc(handler)),
TLSConfig: tlsCfg,
}
log.Println("starting server")
if err := server.ListenAndServeTLS("", ""); err != nil {
log.Fatalln(err)
}
}
```
Run the service in terminal #1:
```
$> go run ./cmd/verify-middleware/main.go
```
Connect as Alice and Bob in terminal #2:
```
$> go run ./cmd/mtls-client/main.go -name Alice -cert target/alice.crt -key target/alice.pem
Hello Alice
$> go run ./cmd/mtls-client/main.go -name Bob -cert target/bob.crt -key target/bob.pem
you cannot be here bob.example.com
```
Alice can connect, Bob fails with a much nicer error and far less hair pulling.
## gRPC and mTLS
The examples provided here have focused on HTTPS so that we could create relatively simple and self-contained services and clients. If you are looking to enable mTLS in a gRPC ecosystem then you may want to look at the various options for mTLS authentication and authorization provided by this author's [example-grpc](https://github.com/tomcz/example-grpc) project on GitHub.
## Summary
Allowing an organization to benefit from mTLS has required in the past significant operational and engineering effort, thus restricting it to companies with fairly large engineering and operations teams. This is no longer the case with products like Vault, and languages like Go, that make it easier to set up a custom PKI infrastructure and create services that have appropriate levels of authentication and authorization between them.
<file_sep>package main
import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
)
var (
rootFile = flag.String("root", "target/root.crt", "Root CA certificate file")
certFile = flag.String("cert", "target/server.crt", "Server TLS certificate file")
keyFile = flag.String("key", "target/server.pem", "Server TLS private key file")
)
func handler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
name = "World"
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, "Hello", name)
}
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
clientCert := r.TLS.PeerCertificates[0]
cn := clientCert.Subject.CommonName
if cn != "alice.example.com" {
log.Printf("%s is not allowed\n", cn)
msg := fmt.Sprintf("you cannot be here %s", cn)
http.Error(w, msg, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
flag.Parse()
rootCaPool := x509.NewCertPool()
rootPEM, err := ioutil.ReadFile(*rootFile)
if err != nil {
log.Fatalln(err)
}
if ok := rootCaPool.AppendCertsFromPEM(rootPEM); !ok {
log.Fatalln("failed to parse Root CA file")
}
serverCert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
if err != nil {
log.Fatalln(err)
}
tlsCfg := &tls.Config{
Certificates: []tls.Certificate{serverCert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: rootCaPool,
}
server := &http.Server{
Addr: ":3000",
Handler: middleware(http.HandlerFunc(handler)),
TLSConfig: tlsCfg,
}
log.Println("starting server")
if err := server.ListenAndServeTLS("", ""); err != nil {
log.Fatalln(err)
}
}
<file_sep>package main
import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
)
var (
rootFile = flag.String("root", "target/root.crt", "Root CA certificate file")
certFile = flag.String("cert", "", "Client TLS certificate file")
keyFile = flag.String("key", "", "Client TLS private key file")
sendName = flag.String("name", "", "Name to send to the server")
)
func main() {
flag.Parse()
rootCaPool := x509.NewCertPool()
rootPEM, err := ioutil.ReadFile(*rootFile)
if err != nil {
log.Fatalln(err)
}
if ok := rootCaPool.AppendCertsFromPEM(rootPEM); !ok {
log.Fatalln("failed to parse Root CA file")
}
clientCert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
if err != nil {
log.Fatalln(err)
}
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: rootCaPool,
Certificates: []tls.Certificate{clientCert},
},
},
}
req, err := http.NewRequest("GET", "https://localhost:3000/", nil)
if err != nil {
log.Fatalln(err)
}
if *sendName != "" {
q := req.URL.Query()
q.Add("name", *sendName)
req.URL.RawQuery = q.Encode()
}
res, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatalln(err)
}
fmt.Println(string(body))
}
|
af6ceb697ad2dd0056b68774551a14ed0dbc8343
|
[
"Makefile",
"Go Module",
"Go",
"Markdown"
] | 6
|
Go Module
|
digitalocean/mtls-tech-talk
|
3b0a90d24b3912d9338dfb9db77fda04facfc28b
|
4d096a7aec562c90cd2ab52fe5d6520dbab4cec6
|
refs/heads/master
|
<repo_name>orlandol23/provaangularorlando<file_sep>/src/app/app-routing.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { SidebarComponent } from './sidebar/sidebar.component';
import { PricingComponent } from './pricing/pricing.component';
import { FormsComponent } from './forms/forms.component';
import { BlocksComponent } from './blocks/blocks.component';
import { CardsComponent } from './cards/cards.component';
export const routes: Routes = [
{
path: 'blocks',
component: BlocksComponent
},
{
path: 'cards',
component: CardsComponent
},
{
path: 'forms',
component: FormsComponent
},
{
path: 'pricing',
component: PricingComponent
},
];
@NgModule({
declarations: [],
imports: [RouterModule.forRoot(routes)],
exports:[RouterModule]
})
export class AppRoutingModule { }
|
656dd8c08e3c03a199c7271088ccda66df74cf4b
|
[
"TypeScript"
] | 1
|
TypeScript
|
orlandol23/provaangularorlando
|
e036940a8f6ceaafb8eefe5d9c75f10baa4b1557
|
25c4c65f4681fe3082f8fe3c99fccc610bb5cab2
|
refs/heads/master
|
<repo_name>ciocancosmin/online-voting-system<file_sep>/api/api.php
<?php
session_start();
require "../vendor/autoload.php";
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$client = new MongoDB\Client;
$main_db = $client -> voting_db;
$users = $main_db -> users;
$campaigns = $main_db -> campaigns;
$votes = $main_db -> votes;
if(!isset($_SESSION['cnp'])) $_SESSION['cnp'] = "none";
if(!isset($_SESSION['target_campaign'])) $_SESSION['target_campaign'] = "none";
if(!isset($_SESSION['campaign'])) $_SESSION['campaign'] = "none";
if(isset($_GET['q']))
{
$query = htmlspecialchars($_GET['q']);
if($query == "9iGyYTJOEY")
{
//check logged in
if($_SESSION['cnp'] == "none")
{
echo "0";
}
else
{
echo "1";
}
}
if($query == "1qH5BwXYrY")
{
if(isset($_GET['d1']))
{
$cnp = $_GET['d1'];
if(strlen($cnp) == 13)
{
$ok = 1;
for ($i=0; $i < strlen($cnp); $i++) {
if( ord($cnp[$i]) < 48 || ord($cnp[$i]) > 57 )
{
$ok = 0;
break;
}
}
if($ok == 0) echo "cnp_format_failed";
else
{
//checking if exists in the db
$f = $users->findOne([
'cnp' => $cnp,
]);
if(!isset($f['_id']))
{
$code = generateRandomString(40);
$insertOneResult = $users->insertOne([
'cnp' => $cnp,
'voted' => '',
'unique_code' => $code,
]);
echo $code;
}
else
{
echo "cnp_already_exists";
}
}
}
else
{
echo "cnp_format_failed";
}
}
}
if($query == "rkziiLU2YL")
{
if($_SESSION['cnp'] == "adm1n")
{
echo "1";
}
else echo "0";
}
if($query == "fu1qXajFkp")
{
if($_SESSION['cnp'] == "adm1n")
{
if(isset($_GET['d1'])) $camp_data = $_GET['d1'];
$dd1 = explode("/***/", $camp_data);
$dd2 = explode("/**/", $dd1[1]);
$votes_count_special = "";
foreach ($dd2 as $k) {
$votes_count_special = $votes_count_special.$k."_"."0"."/**/";
}
$votes_count_special = substr_replace($votes_count_special, "", -4);
//get year
$current_year = date("Y");
$insertOneResult = $campaigns->insertOne([
'type' => $dd1[0],
'status' => '0',
'vote_evidence' => $votes_count_special,
'total_number_of_votes' => '0',
'year' => $current_year
]);
echo "campaign_created_s";
}
}
if($query == "IqoWPsgiCN")
{
if(isset($_GET['d1']))
{
$dd = $_GET['d1'];
$dd_split = explode("/***/", $dd);
$cnp_login = $dd_split[0];
$cnp_code = $dd_split[1];
$f = $users->findOne([
'cnp' => $cnp_login,
]);
if(isset($f['_id']))
{
if($cnp_code == $f['unique_code'])
{
$_SESSION['cnp'] = $f['cnp'];
echo "1";
}
else echo "Codul unic nu este corect!";
}
else
{
echo "Cnp-ul introdus nu este inregistrat in baza de date!";
}
}
}
if($query == "lNOCgqTqi1")
{
$_SESSION['cnp'] = "none";
echo "1";
}
if($query == "qFPBqKalcd")
{
$f2 = $campaigns -> find();
$send_data = "";
foreach ($f2 as $key => $value) {
$send_data .= $value['type']."/***/".$value['status']."/***/".$value['year']."/***/".$value['_id']."/*!*/" ;
}
$send_data = substr_replace($send_data, "", -5);
echo $send_data;
}
if($query == "wJ9u6EsC9Y")
{
if(isset($_GET['d1'])) $camp_data = $_GET['d1'];
if($_SESSION['cnp'] == "adm1n")
{
$updateResult = $campaigns->updateOne(
[ '_id' => new MongoDB\BSON\ObjectID( $camp_data ) ],
[ '$set' => [ 'status' => '1' ]]
);
}
}
if($query == "PAIMnK5H3b")
{
if(isset($_GET['d1'])) $camp_data = $_GET['d1'];
if($_SESSION['cnp'] == "adm1n")
{
$updateResult = $campaigns->updateOne(
[ '_id' => new MongoDB\BSON\ObjectID( $camp_data ) ],
[ '$set' => [ 'status' => '2' ]]
);
}
}
if($query == "EJXzPfGbsP")
{
$_SESSION['target_campaign'] = $_GET['d1'];
echo "1";
//echo $_SESSION['target_campaign'];
}
if($query == "wZU39C8wKz")
{
if($_SESSION['cnp'] != "none")
{
$q = $campaigns->findOne([
'_id' => new MongoDB\BSON\ObjectID( $_SESSION['target_campaign'] ),
]);
if(isset($q['_id']))
{
$v = $votes -> findOne([
'from' => $_SESSION['cnp'],
'which' => (string)$q['_id']
]);
if(!isset($v['_id'])) echo $q['vote_evidence']."/**/".$q['_id'];
else echo "0";
}
else
{
echo "0";
}
}
else
{
echo "0";
}
}
if($query == "2IAnNEhqtN")
{
if(isset($_GET['d1'])) $vote_data = $_GET['d1'];
$q_split = explode("_", $vote_data);
$vote_id = $q_split[1];
$vote_name = $q_split[0];
$campaign_id = $q_split[2];
if($_SESSION['cnp'] != "none")
{
$f = $campaigns->findOne([
"_id" => new MongoDB\BSON\ObjectID( $campaign_id )
]);
if(isset($f['_id']))
{
$v = $votes -> findOne([
'from' => $_SESSION['cnp'],
'which' => (string)$f['_id']
]);
if(!isset($v['_id']))
{
$f_split = explode("/**/", $f['vote_evidence']);
$t = $f_split[$vote_id];
$t_split = explode("_", $t);
$target_reassemble = $t_split[0]."_".(intval($t_split[1])+1);
$new_f = "";
for ($i=0; $i <sizeof($f_split); $i++) {
if($f_split[$i] == $t)
{
$new_f .= $target_reassemble."/**/";
}
else
{
$new_f .= $f_split[$i]."/**/";
}
}
$new_f = substr_replace($new_f, "", -4);
$new_nr_of_votes = intval($f['total_number_of_votes'])+1;
//echo $new_f." ".$new_nr_of_votes;
$updateResult = $campaigns->updateOne(
[ '_id' => new MongoDB\BSON\ObjectID( $f['_id'] ) ],
[ '$set' => [ 'vote_evidence' => $new_f,'total_number_of_votes' => $new_nr_of_votes ]]
);
$votes -> insertOne([
'from' => $_SESSION['cnp'],
'who' => $vote_name,
'which' => $campaign_id
]);
}
}
}
}
if($query == "E9wdPyeUNs")
{
if( $_SESSION['cnp'] != "none" )
{
$q = $votes->find([
"from" => $_SESSION['cnp']
]);
$spit = "";
foreach ($q as $key => $value) {
$spit .= $value['who']."/**/";
}
$spit = substr_replace($spit, "", -4);
echo $spit;
}
else
{
echo "0";
}
}
if($query == "a977gReIOo")
{
if(isset($_GET['d1']))
{
$_SESSION['campaign'] = $_GET['d1'];
echo "1";
}
}
if($query == "OXTwQTiW41")
{
$q = $campaigns -> findOne([
"_id" => new MongoDB\BSON\ObjectID( $_SESSION['campaign'] )
]);
if(isset($q['_id']))
{
echo $q['vote_evidence']."/**/".$q['total_number_of_votes'];
}
else
{
echo "0";
}
}
}
?><file_sep>/js/main.js
function check_logged_in()
{
$.ajax({
url: "api/api.php?q=9iGyYTJOEY",
type:"GET",
success: function(data){
if(data == "0")
{
$("#vote_btn").attr("href","login.html");
$("#my_votes_btn").attr("href","login.html");
}
else if(data == "1")
{
$("#vote_btn").attr("href","index.html#campaigns_now");
$("#my_votes_btn").attr("href","myvotes.html");
var p = '<li class="nav-item" id="logout_btn"><a class="nav-link navbar_text" href="#">Delogheaza-te</a></li>';
document.getElementById("nvbr").innerHTML += p;
$("#logout_btn").attr("onclick","logout()");
}
}
});
}
function logout()
{
$.ajax({
url: "api/api.php?q=lNOCgqTqi1",
type:"GET",
success: function(data){
if(data == "1") window.location.href = "index.html";
}
});
}
function load_campaigns()
{
$.ajax({
url: "api/api.php?q=qFPBqKalcd",
type:"GET",
success: function(data){
str_spl = data.split("/*!*/");
n_active = 0;
n_started = 0;
n_done = 0;
for (var i = 0; i < str_spl.length; i++) {
final_splt = str_spl[i].split("/***/");
c_name = "";
if(final_splt[0] == "0") c_name = "Parlamentare";
if(final_splt[0] == "1") c_name = "Europarlamentare";
if(final_splt[0] == "2") c_name = "Prezidentiale";
c_year = final_splt[2];
document.getElementById("campaigns_now_div").innerHTML = "";
if(final_splt[1] == "0")
{
if( $("body").attr("id") == "1")
{
n_started++;
var qq = '<div class="normal_campaign_div" id="normal_campaign_div_'+i+'" val="'+final_splt[3]+'"><img src="img/r_img1.jpg" class="normal_campaign_div_img"><div style="margin-top: 30px;"></div><h4 style="text-align: center;">Alegeri '+c_name+" "+c_year+'</h6><div style="margin-top: 30px;"></div><button class="btn btn-success c_form_btn" onclick="start_vote('+i+')">Start vot</button></div>';
document.getElementById("campaigns_now_div").innerHTML += qq;
}
}
if(final_splt[1] == "1")
{
n_active++;
if( $("body").attr("id") == "1")
{
var qq = '<div class="normal_campaign_div" id="normal_campaign_div_'+i+'" val="'+final_splt[3]+'"><img src="img/r_img1.jpg" class="normal_campaign_div_img"><div style="margin-top: 30px;"></div><h4 style="text-align: center;">Alegeri '+c_name+" "+c_year+'</h6><div style="margin-top: 30px;"></div><button class="btn btn-danger c_form_btn" onclick="stop_vote('+i+')">Stop vot</button></div>';
document.getElementById("campaigns_now_div").innerHTML += qq;
}
else
{
var qq = '<div class="normal_campaign_div" id="normal_campaign_div_'+i+'" val="'+final_splt[3]+'"><img src="img/r_img1.jpg" class="normal_campaign_div_img"><div style="margin-top: 30px;"></div><h4 style="text-align: center;">Alegeri '+c_name+" "+c_year+'</h6><div style="margin-top: 30px;"></div><button class="btn btn-success c_form_btn" onclick="s_vote('+i+')" >Voteaza</button></div>';
document.getElementById("campaigns_now_div").innerHTML += qq;
}
}
if(final_splt[1] == "2")
{
n_done++;
var qq = '<div class="normal_campaign_div" style="cursor:pointer;" id="normal_campaign_div_'+i+'" val="'+final_splt[3]+'" onclick="go_to_camp('+i+');";><img src="img/r_img1.jpg" class="normal_campaign_div_img"><div style="margin-top: 30px;"></div><h4 style="text-align: center;">Alegeri '+c_name+" "+c_year+'</h6><div style="margin-top: 30px;"></div></div>';
document.getElementById("campaigns_old").innerHTML += qq;
}
if(n_started == 0 && n_active == 0)
{
document.getElementById("campaigns_now_div").innerHTML += '<div class="empty_campaign_div">Nu sunt campanii electorale in desfasurare in acest moment</div>';
}
}
}
});
}
function check_admin()
{
$.ajax({
url: "api/api.php?q=rkziiLU2YL",
type:"GET",
success: function(data){
if(data == "1") $("body").attr("id","1");
}
});
}
function start_vote(nr)
{
var qq = $("#normal_campaign_div_"+nr).attr("val");
$.ajax({
url: "api/api.php?q=wJ9u6EsC9Y&d1="+qq,
type:"GET",
success: function(data){
window.location.reload();
}
});
}
function stop_vote(nr)
{
var qq = $("#normal_campaign_div_"+nr).attr("val");
$.ajax({
url: "api/api.php?q=PAIMnK5H3b&d1="+qq,
type:"GET",
success: function(data){
window.location.reload();
}
});
}
function s_vote(nr)
{
var qq = $("#normal_campaign_div_"+nr).attr("val");
$.ajax({
url: "api/api.php?q=EJXzPfGbsP&d1="+qq,
type:"GET",
success: function(data){
window.location.href = "vote.html";
}
});
}
function go_to_camp(id)
{
var v = $("#normal_campaign_div_"+id).attr("val");
$.ajax({
url: "api/api.php?q=a977gReIOo&d1="+v,
type:"GET",
success: function(data){
window.location.href = "analytics.html";
}
});
}
$(document).ready(function(){
check_logged_in();
check_admin();
load_campaigns();
});<file_sep>/js/admin.js
var c = 0;
$( document ).ready(function() {
loadpage();
$("#add_candidate_btn").attr("onclick","add_candidate()");
$("#create_campaign_btn").attr("onclick","send_data()");
});
function loadpage()
{
$.ajax({
url: "api/api.php?q=rkziiLU2YL",
type:"GET",
success: function(data){
if(data == "1")
{
var div = '<div class="text-center border border-light p-5" id="campaign_form"><p class="h4 mb-4">Creeaza campanie de votare</p><div id="campaign_form_div"><label>Tip de alegeri</label><select class="browser-default custom-select mb-4" id="campaign_type_select"><option>Parlamentare</option><option>Europarlamentare</option><option>Prezidentiale</option></select></div><button class="btn btn-success btn-block" id="add_candidate_btn" onclick="add_candidate()">Adauga candidat</button><button class="btn btn-info btn-block" id="create_campaign_btn" onclick="send_data()">Creaza campania de votare</button></div>';
$("body").append(div);
}
}
});
}
function add_candidate()
{
document.getElementById("campaign_form_div").innerHTML += ' <input type="text" id="candidate_name_'+c+'" class="form-control mb-4" placeholder="<NAME>"> ';
c++;
}
function send_data()
{
var campaign_type = $('#campaign_type_select').find(":selected").text();
campaign_type = $.trim(campaign_type);
var append1 = -1;
if(campaign_type == "Parlamentare") append1 = 0;
if(campaign_type == "Prezidentiale") append1 = 2;
if(campaign_type == "Europarlamentare") append1 = 1;
final_data = "";
final_data += append1;
final_data += "/***/";
for(var i = 0;i<c;i++)
{
var n_candidate = $("#candidate_name_"+i).val();
$.trim(n_candidate);
final_data += n_candidate;
final_data += "/**/";
}
final_data = final_data.substring(0, final_data.length - 4);
$.ajax({
url: "api/api.php?q=fu1qXajFkp&d1="+final_data,
type:"GET",
success: function(data){
if(data == "campaign_created_s")
{
window.location.href = 'index.html';
}
}
});
}<file_sep>/js/analytics.js
function load_analytics()
{
$.ajax({
url: "api/api.php?q=OXTwQTiW41&d1",
type:"GET",
success: function(data){
if(data != "0")
{
var data_votes = []
var data_s = []
f_split = data.split("/**/");
total_vote_nr = f_split[f_split.length-1];
for (var i = 0; i < f_split.length-1; i++) {
s_split = f_split[i].split("_");
vote_nr = parseInt(s_split[1]);
vote_name = s_split[0];
data_to_push = []
data_to_push.push(vote_nr);
data_s.push({
seriesType:"bar",
collectionAlias:vote_name,
data:data_to_push
});
}
$("#chart2").shieldChart({
exportOptions: {
image: false,
print: false
},
axisY: {
title: {
text: "Numar de voturi"
}
},
dataSeries: data_s
});
}
}
});
}
$(document).ready(function(){
load_analytics();
});<file_sep>/js/voting.js
var vote_id = -1;
function select_vote(id)
{
if(vote_id != -1) $("#vote_pos_button_"+vote_id).attr("class","btn btn-info");
vote_id = id;
$("#vote_pos_button_"+id).attr("class","btn btn-danger");
}
function send_vote()
{
var q = $("#vote_h_id_"+vote_id).text();
var send = q+"_"+vote_id+"_"+$("body").attr("id");
$.ajax({
url: "api/api.php?q=2IAnNEhqtN&d1="+send,
type:"GET",
success: function(data){
//alert(data);
window.location.href = "myvotes.html";
}
});
}
function load_votes()
{
$.ajax({
url: "api/api.php?q=wZU39C8wKz",
type:"GET",
success: function(data){
if(data != "0")
{
f_split = data.split("/**/");
$("body").attr("id",f_split[f_split.length-1]);
for (var i = 0; i < f_split.length-1; i++) {
s_split = f_split[i].split("_");
cand_name = s_split[0]; //here dude here is that thing you need
v_count = s_split[1]; //here dude here is that thing you need
document.getElementById("camp_1").innerHTML += '<div class="col-md-4"><div class="vote_post"><h3 class="vote_h" id="vote_h_id_'+i+'" >'+cand_name+'</h3><button type="button" class="btn btn-info" id="vote_pos_button_'+i+'" onclick="select_vote('+i+');">Selecteaza</button></div></div>';
}
document.getElementById("camp_2").innerHTML += '<div class="col-lg-12"><button type="button" class="btn btn-success" style="width: 100%;" onclick="send_vote()">Voteaza</button></div>';
}
}
});
}
load_votes();
$(document).ready(function(){
//
});<file_sep>/js/login.js
$(document).ready(function(){
$("#login_btn").attr("onclick","send_login_details()");
});
function send_login_details()
{
cnp_normal = $.trim( $("#cnp_normal").val() );
cnp_code = $.trim( $("#cnp_code").val() );
data_to_send = cnp_normal+"/***/"+cnp_code;
//ajax
$.ajax({
url: "api/api.php?q=IqoWPsgiCN&d1="+data_to_send,
type:"GET",
success: function(data){
if(data == "1") window.location.href = "index.html";
else
{
$("#login_error").text(data);
}
}
});
}<file_sep>/api/insert_admin.php
<?php
require "../vendor/autoload.php";
$client = new MongoDB\Client;
$main_db = $client -> voting_db;
$users = $main_db -> users;
$res = $users -> insertOne([
'cnp' => 'adm1n',
'unique_code' => 'klausiohannis'
]);
?>
|
cdfa8504273bacbb178c353a54d24b4e72158385
|
[
"JavaScript",
"PHP"
] | 7
|
PHP
|
ciocancosmin/online-voting-system
|
2ec5704e94a97ff6d10b993e98e55c5e45387681
|
75253de95159ee7693a2350757c9f26f60bd2087
|
refs/heads/master
|
<repo_name>merajsam/ass<file_sep>/ass/InputValue/src/MainFunction.java
public class Person {
<NAME>fdkjfhds
ghfsjkhg
ldfhdslkg
sdjgkjsd
gkjsfdlkg
int a=10;
public void add()
{
System.out.print(a);
}
}
public class MainFunction {
/**
* @param args
*/
public static void main(String[] args) {
Person ob=new Person();
ob.add();
}
}
|
a8766fd585d92983cb287afa8c99adeb6a499d68
|
[
"Java"
] | 1
|
Java
|
merajsam/ass
|
17899fddb8d8e459034a3f7c49ad197a5ee51154
|
63470d418176ef015105b3835b506c73d7d80af8
|
refs/heads/master
|
<repo_name>haogaoming123/swift-HMDatePickerview<file_sep>/README.md
# swift-HMDatePickerview
时间选择器,可以自定义最大时间值和最小时间值,可以设置当前选中时间

<file_sep>/DataPickerViewDemo/DataPickerViewDemo/PickerView.swift
//
// THAgePickerView.swift
// HealthCloud
//
// Created by 李宝龙 on 16/9/6.
// Copyright © 2016年 thealth. All rights reserved.
//
import UIKit
// 屏幕的宽
let SCREEN_WIDTH:CGFloat = UIScreen.main.bounds.size.width
// 屏幕的高
let SCREEN_HEIGHT:CGFloat = UIScreen.main.bounds.size.height
let FONTSYS14 = UIFont.systemFont(ofSize: 14) //H9:28px
class PickerView: UIView {
/// 回调闭包
fileprivate var btnCallBackBlock: ((_ date: Date) -> ())?
/// 遮幕
fileprivate lazy var coverView: UIView = {
let coverview = UIView()
coverview.backgroundColor = UIColor.darkGray
let tapGes = UITapGestureRecognizer(target: self, action: #selector(yesBtnDidClick))
coverview.addGestureRecognizer(tapGes)
return coverview
}()
/// 主体view的高度
fileprivate var contenViewHeight: CGFloat = 0
/// 主体view
fileprivate lazy var contenView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 3
view.clipsToBounds = true
return view
}()
/// 时间pickerView
fileprivate lazy var pickerView: UIPickerView = {
let pickerview = UIPickerView()
pickerview.delegate = self
pickerview.dataSource = self
return pickerview
}()
/// 日历
fileprivate lazy var calendar: NSCalendar = {
return NSCalendar(calendarIdentifier: NSCalendar.Identifier.chinese)!
}()
/// 最小日期
fileprivate lazy var minDate = Date()
/// 最大日期
fileprivate lazy var maxDate = Date(timeIntervalSinceReferenceDate: Date().timeIntervalSinceReferenceDate + 180*24*3600)
/// 默认最早的日期
fileprivate lazy var earliestPresentedDate: Date = {
return self.showOnlyValidDates ? self.minDate : Date(timeIntervalSince1970: 0)
}()
/// 显示日期行数
fileprivate var nDays:Int?
/// 是否只显示有效日期
fileprivate var showOnlyValidDates:Bool = true
/// 保存最终返回的日期
fileprivate var date:Date?
/// 字体配色
fileprivate var color:UIColor = UIColor.white
fileprivate var bgColor:UIColor = UIColor.black
/// 初始化
///
/// - Parameters:
/// - frame: frame
/// - minDate: 最小时间
/// - maxDate: 最大时间
/// - showOnlyValidDates: 是否显示有效时间
init(frame: CGRect,
minDate: Date? = nil,
maxDate: Date? = nil,
selectDate: Date? = nil,
showOnlyValidDates: Bool = true)
{
super.init(frame: frame)
//设置最小的时间
if minDate != nil{
self.minDate = minDate!
}
//设置最大的时间
if maxDate != nil{
self.maxDate = maxDate!
}
//是否只显示有效日期
self.showOnlyValidDates = showOnlyValidDates
//设置当前应该选中的时间
initDate(selectDate: selectDate)
//添加遮罩
coverView.alpha = 0.2
coverView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
addSubview(coverView)
//设置主体view的frame
contenViewHeight = SCREEN_HEIGHT/3 + 40
contenView.frame = CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: contenViewHeight)
//添加主体view
addSubview(contenView)
//添加上半部分的[取消、确定]按钮
let oneView = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 40))
setOneView(oneView: oneView)
contenView.addSubview(oneView)
//添加时间选择器
pickerView.frame = CGRect(x: 0, y: oneView.frame.maxY, width: SCREEN_WIDTH, height: contenViewHeight - oneView.frame.size.height)
contenView.addSubview(pickerView)
//显示页面
showDateOnPicker(date: self.date!)
UIView.animate(withDuration: 0.35) {
self.contenView.frame = CGRect(x: 0, y: SCREEN_HEIGHT - self.contenViewHeight, width: SCREEN_WIDTH, height: self.contenViewHeight)
self.coverView.alpha = 0.6
}
}
/// 显示pakerView
func showInWindow(btnCallBackBlock: @escaping ((_ date:Date) -> ())){
let keyWindow = UIApplication.shared.keyWindow
keyWindow!.addSubview(self)
keyWindow!.bringSubview(toFront: self)
self.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
self.btnCallBackBlock = btnCallBackBlock
}
/// 移除view
func removePickerView() {
UIView.animate(withDuration: 0.5, animations: {
self.contenView.frame = CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: self.contenViewHeight)
self.coverView.alpha = 0.2
UIApplication.shared.sendAction(#selector(self.resignFirstResponder), to: nil, from: nil, for: nil)
}) { (suc) in
self.removeFromSuperview()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - 初始化返回日期
extension PickerView
{
/// 初始化返回日期
fileprivate func initDate(selectDate: Date?) {
var startDay = 0
var startHour = 0
var startMinute = 0
// 创建一个包含天数,从最小日期到最大日期的组件
let components = self.calendar.components(.day, from: self.minDate as Date, to: self.maxDate as Date, options: NSCalendar.Options(rawValue: 0))
// 拿到天数的行数
nDays = components.day! + 1
// 赋值给返回的日期
if selectDate != nil {
self.date = selectDate!
return
}
// 最大的日期
var dateToPresent:Date?
if self.minDate.compare(Date() as Date) == ComparisonResult.orderedDescending{
dateToPresent = self.minDate
} else if self.maxDate.compare(Date() as Date) == ComparisonResult.orderedAscending {
dateToPresent = self.maxDate
} else {
dateToPresent = Date()
}
// 创建一个包含天时分,从最早日期到最大日期的组件
let todaysComponents = self.calendar.components([.day,.hour,.minute], from: self.earliestPresentedDate as Date, to: dateToPresent! as Date, options: NSCalendar.Options(rawValue: 0))
// 转换为时间戳并赋值
startDay = todaysComponents.day! * 60 * 60 * 24
startHour = todaysComponents.hour! * 60 * 60
startMinute = todaysComponents.minute! * 60
// 计算总时间戳
let timeInterval:TimeInterval = Double(startDay + startHour + startMinute)
// 赋值给返回的日期
self.date = Date(timeInterval: timeInterval, since: self.earliestPresentedDate as Date)
}
}
// MARK: - 设置顶部view:[确定、取消]按钮
extension PickerView
{
/// 设置pakerview第一栏样式
///
/// - Parameter oneView: [确定、取消]按钮
fileprivate func setOneView(oneView: UIView){
oneView.backgroundColor = UIColor.white
//取消按钮
let cancleBtn = UIButton()
cancleBtn.frame = CGRect(x: 10, y: 0, width: 50, height: oneView.frame.size.height)
cancleBtn.setTitleColor(UIColor.gray, for: .normal)
cancleBtn.setTitle("取消", for: .normal)
cancleBtn.titleLabel?.font = FONTSYS14
cancleBtn.addTarget(self, action: #selector(yesBtnDidClick), for: .touchUpInside)
oneView.addSubview(cancleBtn)
//选择时间
let titleLb = UILabel(frame: CGRect(x: cancleBtn.frame.maxX, y: 0, width: oneView.frame.width-cancleBtn.frame.maxX * 2, height: oneView.frame.size.height))
titleLb.text = "选择时间"
titleLb.textAlignment = .center
oneView.addSubview(titleLb)
//确定按钮
let yesBtn = UIButton()
yesBtn.frame = CGRect(x: titleLb.frame.maxX, y: cancleBtn.frame.origin.y, width: cancleBtn.frame.size.width, height: cancleBtn.frame.size.height)
yesBtn.setTitle("确定", for: .normal)
yesBtn.setTitleColor(UIColor.gray, for: .normal)
yesBtn.titleLabel?.font = FONTSYS14
yesBtn.addTarget(self, action: #selector(yesBtnDidClick), for: .touchUpInside)
oneView.addSubview(yesBtn)
//横线
let lineView = UIView(frame: CGRect(x: 0, y: oneView.frame.size.height-0.5, width: oneView.frame.size.width, height: 0.5))
lineView.backgroundColor = UIColor.gray
lineView.alpha = 0.3
oneView.addSubview(lineView)
}
//点击 [确认 | 取消] 按钮
@objc fileprivate func yesBtnDidClick(){
print("确定")
// let format = DateFormatter()
// format.dateFormat = "yyyy-MM-dd"
// // 获取系统当前时区
// let zone = NSTimeZone.system
// // 计算与GMT时区的差
// let interval = zone.secondsFromGMT(for: date! as Date)
// // 加上差的时时间戳
// let localeDate = date?.addingTimeInterval(Double(interval))
// 回调闭包
self.btnCallBackBlock?(date!)
// 移除view
removePickerView()
}
}
// MARK: - 根据日期滑动到对于的row
extension PickerView
{
/// 根据日期滑动到对于的row
///
/// - Parameter date: 滑动日期
func showDateOnPicker(date:Date) {
self.date = date
// 创一个由年月日,最早的日期组成的组件
var components = self.calendar.components([NSCalendar.Unit.year,.month,.day], from: self.earliestPresentedDate as Date)
// 根据组件从日历中拿到NSDate
let fromDate = self.calendar.date(from: components)
// 创建一个日时分,从fromDate到需要显示的date的组件
components = self.calendar.components([.day,.hour,.minute], from: fromDate!, to: date as Date, options: NSCalendar.Options(rawValue: 0))
// 计算行数,在计算分钟和小时的时候,为避免滑动到第0行,加上x * (Int(INT16_MAX) / 120),其中x等于对于的进制
let hoursRow = components.hour! + 24 * (Int(INT16_MAX) / 120)
let minutesRow = components.minute! + 60 * (Int(INT16_MAX) / 120)
let daysRow = components.day
// 滑动到对于的行
pickerView.selectRow(daysRow!, inComponent: 0, animated: true)
pickerView.selectRow(hoursRow, inComponent: 1, animated: true)
pickerView.selectRow(minutesRow, inComponent: 2, animated: true)
}
}
// MARK: - UIPickerView的代理
extension PickerView: UIPickerViewDelegate,UIPickerViewDataSource
{
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return nDays ?? 0
}
else if component == 1 {
return Int(INT16_MAX)
} else {
return Int(INT16_MAX)
}
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
switch component {
case 0:
return SCREEN_WIDTH/2
case 1:
return SCREEN_WIDTH/4
case 2:
return SCREEN_WIDTH/4
default:
return 0
}
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 45
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
// 定义一个label用于展示时间
let dateLabel = UILabel()
// 字体大小
dateLabel.font = UIFont.systemFont(ofSize: 25)
if component == 0 {// 天数
// 根据当前的行数转换为时间戳,记录当前行数所表示的日期
let aDate = Date(timeInterval: Double(row * 24 * 60 * 60), since: self.earliestPresentedDate as Date)
// 创建一个有纪元年月日组成的,当前时间的组件
var components = self.calendar.components([.era,.year,.month,.day], from: Date())
// 根据组件从日历里拿到今天的NSDate()
let toDay = self.calendar.date(from: components)
// 组件变为由当前行数所表示的日期组成的组件
components = self.calendar.components([.era,.year,.month,.day], from: aDate)
// 根据组件从日历拿到当前行数表示的NSDate
let otherDate = self.calendar.date(from: components)
// 如果今天的NSDate等于当前行数表示的NSDate,就设置文字为今天
if toDay!.compare(otherDate!) == ComparisonResult.orderedSame{
dateLabel.text = "今天"
} else {
// 如果不是,创建一个NSDateFormatter
let formatter = DateFormatter()
// 地区设置
formatter.locale = NSLocale.current
// 日期格式设置
formatter.dateFormat = "M月d日"
// label文字设置
dateLabel.text = formatter.string(from: aDate)
}
dateLabel.textAlignment = NSTextAlignment.center
} else if component == 1 {// 小时
// 小时的范围0-23,长度是24
let max = self.calendar.maximumRange(of: NSCalendar.Unit.hour).length
// label文字
dateLabel.text = String(format:"%02ld",row % max)
dateLabel.textAlignment = NSTextAlignment.left
} else if component == 2 {// 分钟
// 分钟的范围0-59,长度是60
let max = self.calendar.maximumRange(of: NSCalendar.Unit.minute).length
dateLabel.text = String(format:"%02ld",row % max)
dateLabel.textAlignment = NSTextAlignment.left
}
return dateLabel
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// 选择的日的行数
let daysRow = pickerView.selectedRow(inComponent: 0)
// 根据行数转换为时间戳
let chosenDate = Date(timeInterval: Double(daysRow * 24 * 60 * 60), since: self.earliestPresentedDate as Date)
// 选择的小时的行数
let hoursRow = pickerView.selectedRow(inComponent: 1)
// 选择的分钟的行数
let minutesRow = pickerView.selectedRow(inComponent: 2)
// 根据选择的日期的时间戳,创建一个有年月日的日历组件
var components = self.calendar.components([.day,.month,.year], from: chosenDate)
// 设置组件的小时
components.hour = hoursRow % 24
// 设置组件的分钟
components.minute = minutesRow % 60
// 根据组件从日历中拿到对应的NSDate,赋值给date
self.date = self.calendar.date(from: components)!
// 比较date与限定的最大最小时间,如果超过最大时间或小于最小时间,就回滚到有效时间内
if self.date!.compare(self.minDate as Date) == ComparisonResult.orderedAscending {
self.showDateOnPicker(date: self.minDate)
} else if self.date!.compare(self.maxDate as Date) == ComparisonResult.orderedDescending {
self.showDateOnPicker(date: self.maxDate)
}
}
}
<file_sep>/DataPickerViewDemo/DataPickerViewDemo/ViewController.swift
//
// ViewController.swift
// DataPickerViewDemo
//
// Created by haogaoming on 2017/11/23.
// Copyright © 2017年 郝高明. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let btn1 = UIButton()
btn1.setTitle("时间选择器", for: .normal)
btn1.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
btn1.backgroundColor = UIColor.orange
btn1.addTarget(self, action: #selector(btn1DidClick), for: .touchUpInside)
self.view.addSubview(btn1)
}
@objc func btn1DidClick(){
let showPickerView : PickerView = PickerView(frame: self.view.frame, minDate: nil, maxDate: nil, selectDate: nil, showOnlyValidDates: true)
showPickerView.showInWindow { [unowned self] (date) in
print(date)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
afcb2d49ebec81ab22e182f416306a7f68061209
|
[
"Markdown",
"Swift"
] | 3
|
Markdown
|
haogaoming123/swift-HMDatePickerview
|
8ddfbfeb39293000b1a450bb02d739d4152bfe71
|
a58319a7f2a6f172c4349c5ae14a34d4a696b249
|
refs/heads/master
|
<file_sep># PySuiteCRM
[](https://github.com/RussellJuma/PySuiteCRM/issues)
[](https://github.com/RussellJuma/PySuiteCRM/stargazers)
[](https://github.com/RussellJuma/PySuiteCRM/blob/master/LICENSE)
PySuiteCRM ultilizes the SuiteCRM V8 API via Oauth2
PySuiteCRM supports all versions of SuiteCRM `7.10+`
## Contents
- [Installation](#Installation)
- [OAuth2 Setup](#OAuth2_Setup)
- [SuiteCRM Setup](#SuiteCRM_Setup)
- [PySuiteCRM Setup](#PySuiteCRM_Setup)
- [Usage](#Usage)
- [Create](#Create)
- [Update](#Update)
- [Get](#Get)
- [Delete](#Delete)
- [Create_Relationship](#Create_Relationship)
- [Get_Relationship](#Get_Relationship)
- [Delete_Relationship](#Delete_Relationship)
- [Fields](#Fields)
- [Performance](#Performance)
- [Contributing](#Contributing)
- [Credits](#Credits)
- [License](#License)
## Installation
### OAuth2_Setup
[SuiteCRM Oauth2 Setup source](https://docs.suitecrm.com/developer/api/developer-setup-guide/json-api/#_generate_private_and_public_key_for_oauth2)
SuiteCRM Api uses OAuth2 protocol, which needs public and private keys.
First, open a terminal and go to
```
{{suitecrm.root}}/Api/V8/OAuth2
```
Generate a private key:
```bash
openssl genrsa -out private.key 2048
```
Generate a public key:
```bash
openssl rsa -in private.key -pubout -out public.key
```
If you need more information about generating, [please visit this page](https://oauth2.thephpleague.com/installation/).
The permission of the key files must be 600 or 660, so change it.
```bash
sudo chmod 600 private.key public.key
```
Make sure that the config files are owned by PHP
```bash
sudo chown www-data:www-data p*.key
```
OAuth2’s Authorization Server needs to set an encryption key for security reasons. This key has been gererated during the SuiteCRM installation and stored in the config.php under "oauth2_encryption_key". If you would like to change its value you may generate a new one by running and then storing the output in the config.php.
```bash
echo base64_encode(random_bytes(32)).PHP_EOL;
```
If you need more information about this issue, [please visit this page](https://oauth2.thephpleague.com/v5-security-improvements/)
<br/>
### SuiteCRM_Setup
Login as Admin and navigate to Admin>OAuth2 Clients and Tokens>New Client Credentials Client and generate Client Credentials.
## PySuiteCRM_Setup
Run the following command inside the directory of SuiteCRMPy
```bash
pip install -r requirements.txt
```
## Usage
### Import
```python
from SuiteCRM import SuiteCRM
suitecrm = SuiteCRM(client_id='client_id',
client_secret='client_secret',
url='https://your_suite_crm_location/Api/V8')
```
### Create
```python
result = suitecrm.Contacts.create(title='Software Engineer', first_name='Russell', last_name='Juma')
```
### Update
```python
result = suitecrm.Contacts.update(id='11129071-da4c-18ef-3107-5ead3a71d6fe', account_id='555-555-5555')
```
### Get
```python
# Request a record by id, returns a single record.
result = suitecrm.Contacts.get(id='11129071-da4c-18ef-3107-5ead3a71d6fe')
# Filter records by first and last name, returns a list of records.
result = suitecrm.Contacts.get(first_name='Russell', last_name='Juma')
# Filter records by first name, sort on last name, and only return full name and mobile phone in the records.
result = suitecrm.Contacts.get(fields=['full_name', 'phone_mobile'], first_name= 'Sarah', sort='last_name')
# return all records in a given module, default will pull 100 records per Get request to API.
result = suitecrm.Contacts.get_all()
```
Limitations
Get cannot filter on custom fields due to [bug #7285](https://github.com/salesagility/SuiteCRM/issues/7285) in SuiteCRM.
### Delete
```python
# Delete record by id
result = suitecrm.Contacts.delete(id='11129071-da4c-18ef-3107-5ead3a71d6fe')
```
### Create_Relationship
```python
# Create relationship between '11129071-da4c-18ef-3107-5ead3a71d6fe' in the Contacts and Accounts with id ='555-555-5555'
result = suitecrm.Contacts.create_relationship('11129071-da4c-18ef-3107-5ead3a71d6fe', 'Accounts', '555-555-5555')
```
### Get_Relationship
```python
# Get relationships between '11129071-da4c-18ef-3107-5ead3a71d6fe' in the Contacts with any in Accounts.
result = suitecrm.Contacts.get_relationship('11129071-da4c-18ef-3107-5ead3a71d6fe', 'Accounts')
```
### Delete_Relationship
```python
# Delete relationship between '11129071-da4c-18ef-3107-5ead3a71d6fe' in the Contacts and Accounts with id ='555-555-5555'
result = suitecrm.Contacts.delete('11129071-da4c-18ef-3107-5ead3a71d6fe', 'Accounts', '555-555-5555')
```
### Fields
```python
# Returns all the attributes in a module that can be set.
result = suitecrm.Contacts.fields()
['name', 'date_entered', 'date_modified', 'etc...']
```
## Performance
With Cache set to `True`, all Get, Create, Update requests are stored local within the module's cache. Cache is only
pulled went the specific id is given,ie. `get(suitecrm.Contacts.id='11129071-da4c-18ef-3107-5ead3a71d6fe')`
## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
## Credits
- [<NAME>](https://github.com/RussellJuma)
## License
PySuiteCRM is open source software licensed under the MIT license. See [LICENSE](LICENSE) for more information.<file_sep>import json
import uuid
import atexit
import math
import datetime
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient, TokenExpiredError, InvalidClientError
from oauthlib.oauth2.rfc6749.errors import CustomOAuth2Error
class SuiteCRM:
def __init__(self, client_id, client_secret, url, cache=False, cache_timeout=300):
self.client_id = client_id
self.client_secret = client_secret
self.baseurl = url
self.cache = cache
self.cache_timeout_seconds = cache_timeout
self.logout_on_exit = False
self.headers = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' \
'Chrome/85.0.4183.83 Safari/537.36'
self._login()
self._modules()
def _modules(self):
self.Accounts = Module(self, 'Accounts')
self.Bugs = Module(self, 'Bugs')
self.Calendar = Module(self, 'Calendar')
self.Calls = Module(self, 'Calls')
self.Cases = Module(self, 'Cases')
self.Campaigns = Module(self, 'Campaigns')
self.Contacts = Module(self, 'Contacts')
self.Documents = Module(self, 'Documents')
self.Email = Module(self, 'Email')
self.Emails = Module(self, 'Emails')
self.Employees = Module(self, 'Employees')
self.Leads = Module(self, 'Leads')
self.Lists = Module(self, 'Lists')
self.Meetings = Module(self, 'Meetings')
self.Notes = Module(self, 'Notes')
self.Opportunities = Module(self, 'Opportunities')
self.Projects = Module(self, 'Projects')
self.Spots = Module(self, 'Spots')
self.Surveys = Module(self, 'Surveys')
self.Target = Module(self, 'Target')
self.Targets = Module(self, 'Targets')
self.Tasks = Module(self, 'Tasks')
self.Templates = Module(self, 'Templates')
def _refresh_token(self):
"""
Fetch a new token from from token access url, specified in config file.
:return: None
"""
try:
self.OAuth2Session.fetch_token(token_url=self.baseurl[:-2] + 'access_token',
client_id=self.client_id,
client_secret=self.client_secret)
except InvalidClientError:
exit('401 (Unauthorized) - client id/secret')
except CustomOAuth2Error:
exit('401 (Unauthorized) - client id')
# Update configuration file with new token'
with open('AccessToken.txt', 'w+') as file:
file.write(str(self.OAuth2Session.token))
def _login(self):
"""
Checks to see if a Oauth2 Session exists, if not builds a session and retrieves the token from the config file,
if no token in config file, fetch a new one.
:return: None
"""
# Does session exist?
if not hasattr(self, 'OAuth2Session'):
client = BackendApplicationClient(client_id=self.client_id)
self.OAuth2Session = OAuth2Session(client=client,
client_id=self.client_id)
self.OAuth2Session.headers.update({"User-Agent": self.headers,
'Content-Type': 'application/json'})
with open('AccessToken.txt', 'w+') as file:
token = file.read()
if token == '':
self._refresh_token()
else:
self.OAuth2Session.token = token
else:
self._refresh_token()
# Logout on exit
if self.logout_on_exit:
atexit.register(self._logout)
def _logout(self):
"""
Logs out current Oauth2 Session
:return: None
"""
url = '/logout'
self.request(f'{self.baseurl}{url}', 'post')
with open('AccessToken.txt', 'w+') as file:
file.write('')
def request(self, url, method, parameters=''):
"""
Makes a request to the given url with a specific method and data. If the request fails because the token expired
the session will re-authenticate and attempt the request again with a new token.
:param url: (string) The url
:param method: (string) Get, Post, Patch, Delete
:param parameters: (dictionary) Data to be posted
:return: (dictionary) Data
"""
data = json.dumps({"data": parameters})
try:
the_method = getattr(self.OAuth2Session, method)
except AttributeError:
return
try:
if parameters == '':
data = the_method(url)
else:
data = the_method(url, data=data)
except TokenExpiredError:
self._refresh_token()
if parameters == '':
data = the_method(url)
else:
data = the_method(url, data=data)
# Revoked Token
attempts = 0
while data.status_code == 401 and attempts < 1:
self._refresh_token()
if parameters == '':
data = the_method(url)
else:
data = the_method(url, data=data)
attempts += 1
if data.status_code == 401:
exit('401 (Unauthorized) client id/secret has been revoked, new token was attempted and failed.')
# Database Failure
# SuiteCRM does not allow to query by a custom field see README, #Limitations
if data.status_code == 400 and 'Database failure.' in data.content.decode():
raise Exception(data.content.decode())
return json.loads(data.content)
class Module:
def __init__(self, suitecrm, module_name):
self.module_name = module_name
self.suitecrm = suitecrm
self.cache = {}
self.cache_time = {}
self.cache_status = self.suitecrm.cache
self.cache_timeout_seconds = self.suitecrm.cache_timeout_seconds
def _cache_delete(self, **by):
"""
Clears cache by define by an option
:param by: (string) Option of all,id, or old cache
:return: None
"""
if 'all' in by and by['all']:
self.cache.clear()
elif 'id' in by and by['id'] in self.cache and self.cache_status:
del self.cache[by['id']]
del self.cache_time[by['id']]
elif 'old' in by and by['old']:
for record, time in self.cache.items():
if time + datetime.timedelta(seconds=self.cache_timeout_seconds) <= datetime.datetime.now():
del self.cache[record]
del self.cache_time[record]
def _cache_set(self, request):
"""
Set cache with the id of each record as the key
:param request: (JSON) data
:return: (dictionary) of request, or (JSON) of request if it fails
"""
try:
if len(request['data']) != 0:
# A single record
if type(request['data']) is dict:
if self.cache_status:
self.cache[request['data']['id']] = request['data']
self.cache_time[request['data']['id']] = datetime.datetime.now()
return request['data']
# A list of records
if self.cache_status:
for record in request['data']:
self.cache[record['id']] = record
self.cache_time[record['id']] = datetime.datetime.now()
return request['data']
except:
pass
return request
def _cache_get(self, id):
"""
Retrieves from the cache the record, if cache is expire it will renew
:param id: (string) id of the record
:return: (dictionary) record
"""
if id in self.cache and self.cache_status:
# Expired
if self.cache_time[id] + datetime.timedelta(seconds=self.cache_timeout_seconds) >= datetime.datetime.now():
return self.cache[id]
else:
# Expire record, delete cache and request new
self._cache_delete(id=id)
return self.get(id=id)
def create(self, **attributes):
"""
Creates a record with given attributes
:param attributes: (**kwargs) fields with data you want to populate the record with.
:return: (dictionary) The record that was created with the attributes.
"""
url = '/module'
data = {'type': self.module_name, 'id': str(uuid.uuid4()), 'attributes': attributes}
return self._cache_set(self.suitecrm.request(f'{self.suitecrm.baseurl}{url}', 'post', data))
def delete(self, id):
"""
Delete a specific record by id.
:param id: (string) The record id within the module you want to delete.
:return: (dictionary) Confirmation of deletion of record.
"""
# Delete
url = f'/module/{self.module_name}/{id}'
self._cache_delete(id=id)
return self.suitecrm.request(f'{self.suitecrm.baseurl}{url}', 'delete')
def fields(self):
"""
Gets all the attributes that can be set in a record.
:return: (list) All the names of attributes in a record.
"""
# Get total record count
url = f'/module/{self.module_name}?page[number]=1&page[size]=1'
return list(self.suitecrm.request(f'{self.suitecrm.baseurl}{url}', 'get')['data'][0]['attributes'].keys())
def get(self, fields=None, sort=None, **filters):
"""
Gets records given a specific id or filters, can be sorted only once, and the fields returned for each record
can be specified.
:param fields: (list) A list of fields you want to be returned from each record.
:param sort: (string) The field you want the records to be sorted by.
:param filters: (**kwargs) fields that the record has that you want to filter on.
Important notice: we don’t support multiple level sorting right now!
:return: (dictionary/list) A list or dictionary of record(s) that meet the filter criteria.
(list) If more than one record
(dictionary) if a single record
"""
# Fields Constructor
if fields:
fields = f'?fields[{self.module_name}]=' + ', '.join([fields])
url = f'/module/{self.module_name}{fields}&filter'
else:
url = f'/module/{self.module_name}?filter'
# Filter Constructor
for field, value in filters.items():
url = f'{url}[{field}][eq]={value}and&'
url = url[:-4]
# Sort
if sort:
url = f'{url}&sort=-{sort}'
# Execute
if 'id' in filters and len(filters) == 1 and filters['id'] in self.cache:
return self._cache_get(id=filters['id'])
else:
return self._cache_set(self.suitecrm.request(f'{self.suitecrm.baseurl}{url}', 'get'))
def get_all(self, record_per_page=100):
"""
Gets all the records in the module.
:return: (list) All the records(dictionary) within a module.
"""
# Get total record count
url = f'/module/{self.module_name}?page[number]=1&page[size]=1'
pages = math.ceil(self.suitecrm.request(f'{self.suitecrm.baseurl}{url}', 'get')['meta']['total-pages'] /
record_per_page) + 1
result = []
for page in range(1, pages):
url = f'/module/{self.module_name}?page[number]={page}&page[size]={record_per_page}'
result.extend(self._cache_set(self.suitecrm.request(f'{self.suitecrm.baseurl}{url}', 'get')))
return result
def update(self, id, **attributes):
"""
updates a record.
:param id: (string) id of the current module record.
:param attributes: (**kwargs) fields inside of the record to be updated.
:return: (dictionary) The updated record
"""
url = '/module'
data = {'type': self.module_name, 'id': id, 'attributes': attributes}
return self._cache_set(self.suitecrm.request(f'{self.suitecrm.baseurl}{url}', 'patch', data))
def get_relationship(self, id, related_module_name):
"""
returns the relationship between this record and another module.
:param id: (string) id of the current module record.
:param related_module_name: (string) the module name you want to search relationships for, ie. Contacts.
:return: (dictionary) A list of relationships that this module's record contains with the related module.
"""
url = f'/module/{self.module_name}/{id}/relationships/{related_module_name.lower()}'
return self.suitecrm.request(f'{self.suitecrm.baseurl}{url}', 'get')
def create_relationship(self, id, related_module_name, related_bean_id):
"""
Creates a relationship between 2 records.
:param id: (string) id of the current module record.
:param related_module_name: (string) the module name of the record you want to create a relationship,
ie. Contacts.
:param related_bean_id: (string) id of the record inside of the other module.
:return: (dictionary) A record that the relationship was created.
"""
# Post
url = f'/module/{self.module_name}/{id}/relationships'
data = {'type': related_module_name.capitalize(), 'id': related_bean_id}
return self.suitecrm.request(f'{self.suitecrm.baseurl}{url}', 'post', data)
def delete_relationship(self, id, related_module_name, related_bean_id):
"""
Deletes a relationship between 2 records.
:param id: (string) id of the current module record.
:param related_module_name: (string) the module name of the record you want to delete a relationship,
ie. Contacts.
:param related_bean_id: (string) id of the record inside of the other module.
:return: (dictionary) A record that the relationship was deleted.
"""
url = f'/module/{self.module_name}/{id}/relationships/{related_module_name.lower()}/{related_bean_id}'
return self.suitecrm.request(f'{self.suitecrm.baseurl}{url}', 'delete')
|
522ffb05aa507efe3918350e6268aec2c75f1366
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
stjordanis/PySuiteCRM
|
9b0f1a92868835f541c3cc9bd414a39d099efd28
|
501006204a526f91786b98b2ff737368be75bd38
|
refs/heads/master
|
<file_sep>#ifndef CREATE_SUITE_H
#define CREATE_SUITE_H
#include <CUnit/TestDB.h>
typedef CU_pSuite (*suite_creator_t)(char *suite_name, CU_SetUpFunc before_each, CU_TearDownFunc after_each);
typedef void (*test_adder_t)(CU_pSuite suite, const char *name, void (*testfcn)(void));
#endif // CREATE_SUITE_H
<file_sep>#include "counted_alloc.h"
#include <stdlib.h>
int succeed_next_nmalloc = -1;
int succeed_next_nrealloc = -1;
int malloc_calls = 0;
int realloc_calls = 0;
int free_calls = 0;
void *counted_malloc(size_t sz)
{
if (succeed_next_nmalloc == 0)
{
succeed_next_nmalloc = -1;
return NULL;
}
else
{
--succeed_next_nmalloc;
}
++malloc_calls;
return malloc(sz);
}
void *counted_realloc(void *block, size_t sz)
{
if (succeed_next_nrealloc == 0)
{
succeed_next_nrealloc = -1;
return NULL;
}
else
{
--succeed_next_nrealloc;
}
++realloc_calls;
return realloc(block, sz);
}
void counted_free(void *block)
{
++free_calls;
free(block);
}
void clear_counts(void)
{
malloc_calls = 0;
realloc_calls = 0;
free_calls = 0;
succeed_next_nmalloc = -1;
succeed_next_nrealloc = -1;
}
<file_sep>function (add_gluglib)
include(cmake/detect_os.cmake)
include(cmake/set_export_defs.cmake)
include(cmake/link_libs.cmake)
detect_os()
set(OPTIONS)
set(SINGLE_VALS STATIC_BUILD TARGET_NAME)
set(MULTI_VALS SOURCE LIBS)
cmake_parse_arguments(GLUG "${OPTIONS}" "${SINGLE_VALS}" "${MULTI_VALS}" ${ARGN})
# set the library type
set(LIB_TYPE SHARED)
if (GLUG_STATIC_BUILD)
set(LIB_TYPE STATIC)
endif()
# create the library target
add_library(${GLUG_TARGET_NAME} ${LIB_TYPE} ${GLUG_SOURCE})
# set the defs for the target
set(WINDEFS FALSE)
if (DEFINED GLUG_OS_WIN32)
set(WINDEFS TRUE)
endif()
set_export_defs(${GLUG_TARGET_NAME} ${GLUG_STATIC_BUILD} ${WINDEFS})
# link to other libraries
link_libs(${GLUG_TARGET_NAME} "${GLUG_LIBS}")
endfunction()
<file_sep>#ifndef GLUG_CONT_CONFIG_T_H
#define GLUG_CONT_CONFIG_T_H
#include <stddef.h>
#define T void
typedef void (*glug_copy_el_t)(T *dst, const T *src);
typedef void (*glug_free_el_t)(T *el);
#undef T
struct glug_cont_config
{
size_t el_size;
glug_copy_el_t copy_el;
glug_free_el_t free_el;
};
#ifdef GLUG_USE_TYPEDEFS
typedef struct glug_cont_config glug_cont_config_t;
#endif
struct glug_range_config
{
size_t start, end, stride;
};
#endif // GLUG_CONT_CONFIG_T_H
<file_sep>#include "suites.h"
#include <CUnit/Assert.h>
#include <create_suite.h>
#include <counted_alloc.h>
#include <glug/containers/alloc_t.h>
#include <glug/containers/array/array.h>
#include <glug/containers/config.h>
#include <stdint.h>
#include <stdlib.h>
static struct glug_array *array;
static enum glug_cont_error err;
static struct glug_allocator alloc =
{
.malloc = counted_malloc,
.free = counted_free,
};
static struct glug_cont_config conf;
static void before_each(void)
{
array = NULL;
err = glug_cont_ok;
alloc.malloc = counted_malloc;
alloc.free = counted_free;
clear_counts();
get_uint32_config(&conf);
}
static void after_each(void)
{
if (array)
glug_array_free(&array);
}
static void test_alloc_and_free(void)
{
err = glug_array_alloc(&array, 0, &conf);
CU_ASSERT_EQUAL(err, glug_cont_einvcap);
err = glug_array_alloc(&array, 40, &conf);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_PTR_NOT_NULL(array);
CU_ASSERT_EQUAL(glug_array_capacity(array), 40);
CU_ASSERT_EQUAL(glug_array_elem_size(array), sizeof(uint32_t));
glug_array_free(&array);
CU_ASSERT_PTR_NULL(array);
conf.el_size = 0;
err = glug_array_alloc(&array, 10, &conf);
CU_ASSERT_EQUAL(err, glug_cont_einvconf);
conf.el_size = sizeof(uint32_t);
conf.copy_el = NULL;
err = glug_array_alloc(&array, 10, &conf);
CU_ASSERT_EQUAL(err, glug_cont_einvconf);
}
static void test_alloc_custom(void)
{
conf.el_size = 0;
err = glug_array_alloc_custom(&array, 10, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_einvconf);
CU_ASSERT_PTR_NULL(array);
conf.el_size = sizeof(uint32_t);
conf.copy_el = NULL;
err = glug_array_alloc_custom(&array, 10, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_einvconf);
CU_ASSERT_PTR_NULL(array);
get_uint32_config(&conf);
err = glug_array_alloc_custom(&array, 0, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_einvcap);
err = glug_array_alloc_custom(&array, 200, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_PTR_NOT_NULL(array);
CU_ASSERT_EQUAL(glug_array_capacity(array), 200);
CU_ASSERT_EQUAL(glug_array_elem_size(array), sizeof(uint32_t));
CU_ASSERT_EQUAL(malloc_calls, 2);
glug_array_free(&array);
CU_ASSERT_PTR_NULL(array);
CU_ASSERT_EQUAL(free_calls, 2);
succeed_next_nmalloc = 0;
err = glug_array_alloc_custom(&array, 220, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_enomem);
CU_ASSERT_PTR_NULL(array);
CU_ASSERT_EQUAL(malloc_calls, 2); // not change since last successful malloc
succeed_next_nmalloc = 1;
err = glug_array_alloc_custom(&array, 220, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_enomem);
CU_ASSERT_PTR_NULL(array);
CU_ASSERT_EQUAL(malloc_calls, 3);
CU_ASSERT_EQUAL(free_calls, 3);
}
static void test_invalid_allocator(void)
{
err = glug_array_alloc_custom(&array, 220, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_ok);
glug_array_free(&array);
alloc.malloc = NULL;
err = glug_array_alloc_custom(&array, 220, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_einvalloc);
alloc.malloc = counted_malloc;
alloc.free = NULL;
err = glug_array_alloc_custom(&array, 220, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_einvalloc);
CU_ASSERT_PTR_NULL(array);
err = glug_array_alloc_custom(&array, 220, &conf, NULL);
CU_ASSERT_EQUAL(err, glug_cont_einvalloc);
CU_ASSERT_PTR_NULL(array);
}
static void test_clone(void)
{
struct glug_array *array2 = NULL;
uint32_t i1, i2;
err = glug_array_alloc(&array, 140, &conf);
i1 = 23;
glug_array_set(array, 0, &i1);
err = glug_array_clone(&array2, array);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_PTR_NOT_NULL(array2);
CU_ASSERT_EQUAL(glug_array_capacity(array), glug_array_capacity(array2));
CU_ASSERT_EQUAL(glug_array_elem_size(array), glug_array_elem_size(array2));
glug_array_at(array, 0, &i1);
glug_array_at(array2, 0, &i2);
CU_ASSERT_EQUAL(i1, i2);
i1 = 514;
glug_array_set(array2, 0, &i1);
glug_array_at(array, 0, &i1);
glug_array_at(array2, 0, &i2);
CU_ASSERT_NOT_EQUAL(i1, i2);
CU_ASSERT_EQUAL(i1, 23);
CU_ASSERT_EQUAL(i2, 514);
glug_array_free(&array2);
}
static void test_clone_custom(void)
{
struct glug_array *array2 = NULL;
uint32_t i1, i2;
err = glug_array_alloc(&array, 140, &conf);
i1 = 13;
glug_array_set(array, 0, &i1);
succeed_next_nmalloc = 0;
err = glug_array_clone_custom(&array2, array, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_enomem);
CU_ASSERT_PTR_NULL(array2);
err = glug_array_clone_custom(&array2, array, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_PTR_NOT_NULL(array2);
CU_ASSERT_EQUAL(glug_array_capacity(array), glug_array_capacity(array2));
glug_array_at(array, 0, &i1);
glug_array_at(array2, 0, &i2);
CU_ASSERT_EQUAL(i1, i2);
i1 = 73;
glug_array_set(array2, 0, &i1);
glug_array_at(array, 0, &i1);
glug_array_at(array2, 0, &i2);
CU_ASSERT_NOT_EQUAL(i1, i2);
CU_ASSERT_EQUAL(i1, 13);
CU_ASSERT_EQUAL(i2, 73);
glug_array_free(&array2);
}
static void test_copy(void)
{
uint32_t val;
size_t idx1 = 12, idx2 = 25;
struct glug_array *array2 = NULL;
glug_array_alloc_custom(&array, 30, &conf, &alloc);
val = 1717171;
glug_array_set(array, idx1, &val);
glug_array_alloc_custom(&array2, 30, &conf, &alloc);
err = glug_array_copy(array2, array);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_EQUAL(free_calls, 0);
CU_ASSERT_EQUAL(glug_array_capacity(array2), 30);
CU_ASSERT_EQUAL(glug_array_capacity(array), glug_array_capacity(array2));
// "validate the data"
glug_array_at(array, idx1, &val);
CU_ASSERT_EQUAL(val, 1717171);
glug_array_at(array2, idx1, &val);
CU_ASSERT_EQUAL(val, 1717171);
val = 400400400;
glug_array_set(array, idx2, &val);
glug_array_at(array, idx2, &val);
CU_ASSERT_EQUAL(val, 400400400);
glug_array_at(array2, idx2, &val);
CU_ASSERT_EQUAL(val, 0);
}
static void test_invalid_copy(void)
{
struct glug_cont_config int8_config;
struct glug_array *array2, *array3;
get_int8_config(&int8_config);
glug_array_alloc(&array, 100, &conf);
glug_array_alloc(&array2, 50, &int8_config);
glug_array_alloc(&array3, 50, &conf);
err = glug_array_copy(array2, array);
CU_ASSERT_EQUAL(err, glug_cont_eincompat);
err = glug_array_copy(array3, array);
CU_ASSERT_EQUAL(err, glug_cont_eincompat);
}
static void test_set(void)
{
uint32_t val;
glug_array_alloc(&array, 15, &conf);
val = 81;
err = glug_array_set(array, 100, &val);
CU_ASSERT_EQUAL(err, glug_cont_ebounds);
err = glug_array_at(array, 100, (void *)NULL);
CU_ASSERT_EQUAL(err, glug_cont_ebounds);
val = 1234567;
glug_array_set(array, 0, &val);
val = 7654321;
glug_array_set(array, 1, &val);
glug_array_at(array, 0, &val);
CU_ASSERT_EQUAL(val, 1234567);
glug_array_at(array, 1, &val);
CU_ASSERT_EQUAL(val, 7654321);
}
static void test_insert(void)
{
uint32_t val, i, scale = 3;
size_t cap = 5, inserted = 2;
glug_array_alloc(&array, cap, &conf);
for (i = 0; i < cap; ++i)
{
val = i * scale;
glug_array_set(array, i, &val);
}
val = 0;
err = glug_array_insert(array, 10, &val);
CU_ASSERT_EQUAL(err, glug_cont_ebounds);
val = 702;
err = glug_array_insert(array, inserted, &val);
CU_ASSERT_EQUAL(err, glug_cont_ok);
for (i = 0; i < cap; ++i)
{
uint32_t exp;
if (i > inserted)
exp = (i - 1) * scale;
else
exp = i * scale;
glug_array_at(array, i, &val);
if (i != inserted)
{
CU_ASSERT_EQUAL(val, exp);
}
else
{
glug_array_at(array, inserted, &val);
CU_ASSERT_EQUAL(val, 702);
}
}
}
static void test_splice(void)
{
uint32_t val, i, scale = 7;
size_t cap = 6, spliced = 3;
glug_array_alloc(&array, cap, &conf);
for (i = 0; i < cap; ++i)
{
val = i * scale;
glug_array_set(array, i, &val);
}
err = glug_array_splice(array, 10);
CU_ASSERT_EQUAL(err, glug_cont_ebounds);
err = glug_array_splice(array, spliced);
CU_ASSERT_EQUAL(err, glug_cont_ok);
for (i = 0; i < cap; ++i)
{
uint32_t exp;
if (i >= spliced)
exp = (i + 1) * scale;
else
exp = i * scale;
glug_array_at(array, i, &val);
if (i != cap - 1)
{
CU_ASSERT_EQUAL(val, exp);
}
else
{
glug_array_at(array, cap - 1, &val);
CU_ASSERT_EQUAL(val, 0);
}
}
}
static void test_swap(void)
{
uint32_t val, i, scale = 10;
size_t cap = 8, idx1 = 1, idx2 = 5;
glug_array_alloc(&array, cap, &conf);
for (i = 0; i < cap; ++i)
{
val = i * scale;
glug_array_set(array, i, &val);
}
err = glug_array_swap(array, idx1, 20);
CU_ASSERT_EQUAL(err, glug_cont_ebounds);
err = glug_array_swap(array, 20, idx2);
CU_ASSERT_EQUAL(err, glug_cont_ebounds);
err = glug_array_swap(array, idx1, idx2);
CU_ASSERT_EQUAL(err, glug_cont_ok);
for (i = 0; i < cap; ++i)
{
uint32_t exp = i * scale;
if (i == idx1)
exp = idx2 * scale;
if (i == idx2)
exp = idx1 * scale;
glug_array_at(array, i, &val);
CU_ASSERT_EQUAL(val, exp);
}
}
struct arr_el
{
int i;
char c;
double d;
void *v;
};
void copy_arr_el(struct arr_el *dst, const struct arr_el *src)
{
dst->i = src->i;
dst->c = src->c;
dst->d = src->d;
// probably don't want to do this, but for the sake of example...
dst->v = counted_malloc(sizeof(dst->i));
*(int *)dst->v = *(int *)src->v;
}
void free_arr_el(struct arr_el *c)
{
// ... and to make sure all malloced elements in copy are freed
if (c->v)
counted_free(c->v);
}
void test_complex_elems(void)
{
struct arr_el c;
struct glug_cont_config conf =
{
.el_size = sizeof(struct arr_el),
.copy_el = (glug_copy_el_t)copy_arr_el,
.free_el = (glug_free_el_t)free_arr_el
};
glug_array_alloc_custom(&array, 10, &conf, &alloc);
CU_ASSERT_EQUAL(malloc_calls, 2);
c.i = 7;
c.d = 3.14;
c.c = 'f';
c.v = &c.i;
glug_array_set(array, 0, &c);
glug_array_set(array, 1, &c);
memset(&c, 0, sizeof(struct arr_el));
glug_array_at(array, 0, &c);
CU_ASSERT_EQUAL(c.i, 7);
CU_ASSERT_EQUAL(c.d, 3.14);
CU_ASSERT_EQUAL(c.c, 'f');
CU_ASSERT_EQUAL(*(int *)c.v, 7);
glug_array_free(&array);
CU_ASSERT_EQUAL(malloc_calls, 4);
CU_ASSERT_EQUAL(free_calls, 4);
}
void add_array_suite(suite_creator_t create_suite, test_adder_t add_test)
{
CU_pSuite suite = create_suite("array", before_each, after_each);
add_test(suite, "alloc and free", test_alloc_and_free);
add_test(suite, "alloc custom", test_alloc_custom);
add_test(suite, "invalid allocator", test_invalid_allocator);
add_test(suite, "clone", test_clone);
add_test(suite, "clone custom", test_clone_custom);
add_test(suite, "copy", test_copy);
add_test(suite, "invalid copy", test_invalid_copy);
add_test(suite, "set", test_set);
add_test(suite, "insert", test_insert);
add_test(suite, "splice", test_splice);
add_test(suite, "swap", test_swap);
add_test(suite, "complex elements", test_complex_elems);
}
<file_sep>#include <glug/containers/array/range.h>
#include "array_t.h"
#include <glug/containers/config_t.h>
#include <alloc.h>
#include <glug/bool.h>
static const uint8_t *inc(const uint8_t *pdata, size_t stride)
{
return pdata + stride;
}
static const uint8_t *dec(const uint8_t *pdata, size_t stride)
{
return pdata - stride;
}
static const uint8_t *ptr_at_idx(const struct glug_array *ary, size_t idx)
{
return ary->data + idx * ary->config.el_size;
}
static size_t ptr_to_idx(const struct glug_array *ary, const uint8_t *ptr)
{
return (ptr - ary->data) / ary->config.el_size;
}
enum glug_range_error glug_array_range_alloc(struct glug_array_range **range, const struct glug_array *ary,
const struct glug_range_config *config)
{
struct glug_allocator alloc =
{
.malloc = get_def_malloc(),
.free = get_def_free()
};
return glug_array_range_alloc_custom(range, ary, config, &alloc);
}
enum glug_range_error glug_array_range_alloc_custom(struct glug_array_range **range, const struct glug_array *ary,
const struct glug_range_config *config,
const struct glug_allocator *alloc)
{
struct glug_array_range *new_range;
size_t cont_sz;
glug_bool forward;
if (!alloc || !alloc->malloc || !alloc->free) return glug_range_einvalloc;
if (!config || !config->stride) return glug_range_einvconf;
cont_sz = glug_array_capacity(ary);
if (config->start >= cont_sz || config->end >= cont_sz) return glug_range_ebounds;
if (!glug_malloc(alloc->malloc, (void **)&new_range, sizeof(struct glug_array_range)))
return glug_range_enomem;
forward = config->end > config->start;
new_range->free = alloc->free;
new_range->ary = ary;
new_range->start = config->start;
new_range->end = config->end;
new_range->front = ptr_at_idx(ary, config->start);
new_range->back = ptr_at_idx(ary, config->end);
new_range->stride = config->stride;
new_range->next = forward ? inc : dec;
new_range->prev = forward ? dec : inc;
*range = new_range;
return glug_range_ok;
}
void glug_array_range_free(struct glug_array_range **range)
{
glug_free((*range)->free, (void **)range);
}
enum glug_range_error glug_array_range_front(const struct glug_array_range *range, void *val)
{
size_t idx = ptr_to_idx(range->ary, range->front);
if (glug_array_range_empty(range)) return glug_range_eempty;
if (glug_array_at(range->ary, idx, val)) return glug_range_ebounds;
return glug_range_ok;
}
enum glug_range_error glug_array_range_back(const struct glug_array_range *range, void *val)
{
size_t idx = ptr_to_idx(range->ary, range->back);
if (glug_array_range_empty(range)) return glug_range_eempty;
if (glug_array_at(range->ary, idx, val)) return glug_range_ebounds;
return glug_range_ok;
}
enum glug_range_error glug_array_range_pop_front(struct glug_array_range *range)
{
if (glug_array_range_empty(range)) return glug_range_eempty;
range->front = range->next(range->front, range->stride * range->ary->config.el_size);
return glug_range_ok;
}
enum glug_range_error glug_array_range_pop_back(struct glug_array_range *range)
{
if (glug_array_range_empty(range)) return glug_range_eempty;
range->back = range->prev(range->back, range->stride * range->ary->config.el_size);
return glug_range_ok;
}
glug_bool glug_array_range_empty(const struct glug_array_range *range)
{
return (range->end > range->start && range->front > range->back) ||
(range->end < range->start && range->front < range->back);
}
size_t glug_array_range_length(const struct glug_array_range *range)
{
const uint8_t *high, *low;
uint8_t rev;
if (glug_array_range_empty(range)) return 0;
// interpolate the pointers based on direction
rev = range->front > range->back;
high = (const uint8_t *)(rev * (uintptr_t)range->front + (1 - rev) * (uintptr_t)range->back);
low = (const uint8_t *)(rev * (uintptr_t)range->back + (1 - rev) * (uintptr_t)range->front);
return (ptr_to_idx(range->ary, high) - ptr_to_idx(range->ary, low) + 1) / range->stride;
}
<file_sep>#ifndef GLUG_ARRAY_RANGE_H
#define GLUG_ARRAY_RANGE_H
#include "array_t.h"
#include <glug/import.h>
#include <glug/extern.h>
#include <glug/containers/error_t.h>
#include <glug/bool.h>
#include <stddef.h>
GLUG_EXTERN_START
struct glug_array;
struct glug_allocator;
struct glug_range_config;
GLUG_LIB_API enum glug_range_error glug_array_range_alloc(struct glug_array_range **range, const struct glug_array *ary,
const struct glug_range_config *config);
GLUG_LIB_API enum glug_range_error glug_array_range_alloc_custom(struct glug_array_range **range,
const struct glug_array *ary,
const struct glug_range_config *config,
const struct glug_allocator *allocator);
GLUG_LIB_API void glug_array_range_free(struct glug_array_range **range);
GLUG_LIB_API enum glug_range_error glug_array_range_front(const struct glug_array_range *range, void *val);
GLUG_LIB_API enum glug_range_error glug_array_range_back (const struct glug_array_range *range, void *val);
GLUG_LIB_API enum glug_range_error glug_array_range_pop_front(struct glug_array_range *range);
GLUG_LIB_API enum glug_range_error glug_array_range_pop_back (struct glug_array_range *range);
GLUG_LIB_API glug_bool glug_array_range_empty(const struct glug_array_range *range);
GLUG_LIB_API size_t glug_array_range_length(const struct glug_array_range *range);
GLUG_EXTERN_END
#endif // GLUG_ARRAY_RANGE_H
<file_sep>#ifndef GLUG_BITSET_H
#define GLUG_BITSET_H
#include "bitset_t.h"
#include <glug/import.h>
#include <glug/extern.h>
#include <glug/containers/error_t.h>
#include <glug/bool.h>
#include <stddef.h>
GLUG_EXTERN_START
struct glug_allocator;
GLUG_LIB_API enum glug_cont_error glug_bitset_alloc(struct glug_bitset **bs, size_t cap);
GLUG_LIB_API enum glug_cont_error glug_bitset_alloc_custom(struct glug_bitset **bs, size_t cap,
const struct glug_allocator *alloc);
GLUG_LIB_API void glug_bitset_free(struct glug_bitset **bs);
GLUG_LIB_API enum glug_cont_error glug_bitset_clone(struct glug_bitset **dst, const struct glug_bitset *src);
GLUG_LIB_API enum glug_cont_error glug_bitset_clone_custom(struct glug_bitset **dst, const struct glug_bitset *src,
const struct glug_allocator *alloc);
GLUG_LIB_API enum glug_cont_error glug_bitset_copy(struct glug_bitset *dst, const struct glug_bitset *src);
GLUG_LIB_API size_t glug_bitset_capacity(const struct glug_bitset *bs);
GLUG_LIB_API enum glug_cont_error glug_bitset_set(struct glug_bitset *bs, size_t bit);
GLUG_LIB_API enum glug_cont_error glug_bitset_unset(struct glug_bitset *bs, size_t bit);
GLUG_LIB_API enum glug_cont_error glug_bitset_flip(struct glug_bitset *bs, size_t bit);
GLUG_LIB_API enum glug_cont_error glug_bitset_test(const struct glug_bitset *bs, size_t bit, glug_bool *val);
GLUG_LIB_API void glug_bitset_clear(struct glug_bitset *bs);
GLUG_LIB_API glug_bool glug_bitset_all (const struct glug_bitset *bs);
GLUG_LIB_API glug_bool glug_bitset_none(const struct glug_bitset *bs);
GLUG_LIB_API glug_bool glug_bitset_any (const struct glug_bitset *bs);
GLUG_EXTERN_END
#endif // GLUG_BITSET_H
<file_sep>#include "suites.h"
#include <CUnit/Assert.h>
#include <create_suite.h>
#include <counted_alloc.h>
#include <glug/containers/alloc_t.h>
#include <glug/containers/bitset/bitset.h>
#include <stdlib.h>
static struct glug_bitset *bitset = NULL;
static enum glug_cont_error err;
static struct glug_allocator alloc =
{
.malloc = counted_malloc,
.free = counted_free,
};
static void before_each(void)
{
bitset = NULL;
err = glug_cont_ok;
alloc.malloc = counted_malloc;
alloc.free = counted_free;
clear_counts();
}
static void after_each(void)
{
if (bitset)
glug_bitset_free(&bitset);
}
static void test_alloc_and_free(void)
{
err = glug_bitset_alloc(&bitset, 0);
CU_ASSERT_EQUAL(err, glug_cont_einvcap);
err = glug_bitset_alloc(&bitset, 40);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_PTR_NOT_NULL(bitset);
glug_bitset_free(&bitset);
CU_ASSERT_PTR_NULL(bitset);
}
static void test_alloc_custom(void)
{
err = glug_bitset_alloc_custom(&bitset, 0, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_einvcap);
err = glug_bitset_alloc_custom(&bitset, 200, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_PTR_NOT_NULL(bitset);
CU_ASSERT_EQUAL(malloc_calls, 1);
glug_bitset_free(&bitset);
CU_ASSERT_PTR_NULL(bitset);
CU_ASSERT_EQUAL(free_calls, 1);
succeed_next_nmalloc = 0;
err = glug_bitset_alloc_custom(&bitset, 220, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_enomem);
CU_ASSERT_PTR_NULL(bitset);
CU_ASSERT_EQUAL(malloc_calls, 1); // not change since last successful malloc
}
static void test_invalid_allocator(void)
{
alloc.malloc = NULL;
err = glug_bitset_alloc_custom(&bitset, 220, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_einvalloc);
alloc.malloc = counted_malloc;
alloc.free = NULL;
err = glug_bitset_alloc_custom(&bitset, 220, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_einvalloc);
err = glug_bitset_alloc_custom(&bitset, 220, NULL);
CU_ASSERT_EQUAL(err, glug_cont_einvalloc);
}
static void test_clone(void)
{
struct glug_bitset *bitset2 = NULL;
glug_bool bit1, bit2;
err = glug_bitset_alloc(&bitset, 140);
err = glug_bitset_clone(&bitset2, bitset);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_PTR_NOT_NULL(bitset2);
CU_ASSERT_EQUAL(glug_bitset_capacity(bitset), glug_bitset_capacity(bitset2));
glug_bitset_set(bitset, 1);
glug_bitset_test(bitset, 1, &bit1);
glug_bitset_test(bitset2, 1, &bit2);
CU_ASSERT_NOT_EQUAL(bit1, bit2);
glug_bitset_free(&bitset2);
}
static void test_clone_custom(void)
{
struct glug_bitset *bitset2 = NULL;
glug_bool bit1, bit2;
err = glug_bitset_alloc(&bitset, 140);
succeed_next_nmalloc = 0;
err = glug_bitset_clone_custom(&bitset2, bitset, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_enomem);
CU_ASSERT_PTR_NULL(bitset2);
err = glug_bitset_clone_custom(&bitset2, bitset, &alloc);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_PTR_NOT_NULL(bitset2);
CU_ASSERT_EQUAL(glug_bitset_capacity(bitset), glug_bitset_capacity(bitset2));
glug_bitset_set(bitset, 1);
glug_bitset_test(bitset, 1, &bit1);
glug_bitset_test(bitset2, 1, &bit2);
CU_ASSERT_NOT_EQUAL(bit1, bit2);
glug_bitset_free(&bitset2);
}
static void test_copy(void)
{
glug_bool val;
size_t idx1 = 3, idx2 = 11;
struct glug_bitset *bitset2 = NULL;
glug_bitset_alloc(&bitset, 12);
glug_bitset_set(bitset, idx1);
glug_bitset_alloc(&bitset2, 12);
err = glug_bitset_copy(bitset2, bitset);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_EQUAL(free_calls, 0);
CU_ASSERT_EQUAL(glug_bitset_capacity(bitset2), 12);
CU_ASSERT_EQUAL(glug_bitset_capacity(bitset), glug_bitset_capacity(bitset2));
// "validate the data"
glug_bitset_test(bitset, idx1, &val);
CU_ASSERT_TRUE(val);
glug_bitset_test(bitset2, idx1, &val);
CU_ASSERT_TRUE(val);
glug_bitset_set(bitset, idx2);
glug_bitset_test(bitset, idx2, &val);
CU_ASSERT_TRUE(val);
glug_bitset_test(bitset2, idx2, &val);
CU_ASSERT_FALSE(val);
}
static void test_invalid_copy(void)
{
struct glug_bitset *bitset2;
glug_bitset_alloc(&bitset, 100);
glug_bitset_alloc(&bitset2, 50);
err = glug_bitset_copy(bitset2, bitset);
CU_ASSERT_EQUAL(err, glug_cont_eincompat);
}
static void test_set(void)
{
glug_bool bit;
size_t i = 0;
glug_bitset_alloc(&bitset, 20);
err = glug_bitset_test(bitset, 120, &bit);
CU_ASSERT_EQUAL(err, glug_cont_ebounds);
for (i = 0; i < glug_bitset_capacity(bitset); ++i)
{
err = glug_bitset_test(bitset, i, &bit);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_FALSE(bit);
}
glug_bitset_set(bitset, 5);
glug_bitset_set(bitset, 8);
glug_bitset_set(bitset, 15);
glug_bitset_set(bitset, 18);
for (i = 0; i < glug_bitset_capacity(bitset); ++i)
{
if (i == 5 || i == 8 || i == 15 || i == 18)
{
err = glug_bitset_test(bitset, i, &bit);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_TRUE(bit);
}
else
{
err = glug_bitset_test(bitset, i, &bit);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_FALSE(bit);
}
}
err = glug_bitset_set(bitset, 0);
CU_ASSERT_EQUAL(err, glug_cont_ok);
err = glug_bitset_set(bitset, 20);
CU_ASSERT_EQUAL(err, glug_cont_ebounds);
}
static void test_unset(void)
{
glug_bool bit;
glug_bitset_alloc(&bitset, 30);
glug_bitset_set(bitset, 21);
err = glug_bitset_test(bitset, 21, &bit);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_TRUE(bit);
glug_bitset_unset(bitset, 21);
err = glug_bitset_test(bitset, 21, &bit);
CU_ASSERT_EQUAL(err, glug_cont_ok);
CU_ASSERT_FALSE(bit);
err = glug_bitset_unset(bitset, 30);
CU_ASSERT_EQUAL(err, glug_cont_ebounds);
}
static void test_flip(void)
{
glug_bool bit;
glug_bitset_alloc(&bitset, 10);
glug_bitset_flip(bitset, 4);
err = glug_bitset_test(bitset, 4, &bit);
CU_ASSERT_TRUE(bit);
glug_bitset_flip(bitset, 4);
err = glug_bitset_test(bitset, 4, &bit);
CU_ASSERT_FALSE(bit);
err = glug_bitset_flip(bitset, 10);
CU_ASSERT_EQUAL(err, glug_cont_ebounds);
}
static void test_clear(void)
{
glug_bool bit;
glug_bitset_alloc(&bitset, 25);
glug_bitset_set(bitset, 7);
glug_bitset_set(bitset, 11);
glug_bitset_set(bitset, 13);
glug_bitset_set(bitset, 17);
glug_bitset_clear(bitset);
glug_bitset_test(bitset, 7, &bit);
CU_ASSERT_FALSE(bit);
glug_bitset_test(bitset, 11, &bit);
CU_ASSERT_FALSE(bit);
glug_bitset_test(bitset, 13, &bit);
CU_ASSERT_FALSE(bit);
glug_bitset_test(bitset, 17, &bit);
CU_ASSERT_FALSE(bit);
}
static void test_all(void)
{
glug_bitset_alloc(&bitset, 12);
glug_bitset_set(bitset, 0);
glug_bitset_set(bitset, 1);
glug_bitset_set(bitset, 2);
glug_bitset_set(bitset, 3);
glug_bitset_set(bitset, 4);
glug_bitset_set(bitset, 5);
glug_bitset_set(bitset, 6);
glug_bitset_set(bitset, 7);
glug_bitset_set(bitset, 8);
glug_bitset_set(bitset, 9);
glug_bitset_set(bitset, 10);
glug_bitset_set(bitset, 11);
CU_ASSERT_TRUE(glug_bitset_all(bitset));
glug_bitset_unset(bitset, 5);
CU_ASSERT_FALSE(glug_bitset_all(bitset));
glug_bitset_set(bitset, 5);
glug_bitset_unset(bitset, 0);
CU_ASSERT_FALSE(glug_bitset_all(bitset));
glug_bitset_set(bitset, 0);
glug_bitset_unset(bitset, 11);
CU_ASSERT_FALSE(glug_bitset_all(bitset));
glug_bitset_set(bitset, 11);
}
static void test_none(void)
{
glug_bitset_alloc(&bitset, 10);
CU_ASSERT_TRUE(glug_bitset_none(bitset));
glug_bitset_set(bitset, 6);
CU_ASSERT_FALSE(glug_bitset_none(bitset));
glug_bitset_unset(bitset, 6);
glug_bitset_set(bitset, 0);
CU_ASSERT_FALSE(glug_bitset_none(bitset));
glug_bitset_unset(bitset, 0);
glug_bitset_set(bitset, 9);
CU_ASSERT_FALSE(glug_bitset_none(bitset));
glug_bitset_unset(bitset, 9);
}
static void test_any(void)
{
glug_bitset_alloc(&bitset, 15);
CU_ASSERT_FALSE(glug_bitset_any(bitset));
glug_bitset_set(bitset, 6);
CU_ASSERT_TRUE(glug_bitset_any(bitset));
glug_bitset_unset(bitset, 6);
CU_ASSERT_FALSE(glug_bitset_any(bitset));
glug_bitset_set(bitset, 0);
CU_ASSERT_TRUE(glug_bitset_any(bitset));
glug_bitset_unset(bitset, 0);
glug_bitset_set(bitset, 14);
CU_ASSERT_TRUE(glug_bitset_any(bitset));
glug_bitset_unset(bitset, 14);
}
void add_bitset_suite(suite_creator_t create_suite, test_adder_t add_test)
{
CU_pSuite suite = create_suite("bitset", before_each, after_each);
add_test(suite, "alloc and free", test_alloc_and_free);
add_test(suite, "alloc custom", test_alloc_custom);
add_test(suite, "invalid allocator", test_invalid_allocator);
add_test(suite, "clone", test_clone);
add_test(suite, "clone custom", test_clone_custom);
add_test(suite, "copy", test_copy);
add_test(suite, "invalid copy", test_invalid_copy);
add_test(suite, "set", test_set);
add_test(suite, "unset", test_unset);
add_test(suite, "flip", test_flip);
add_test(suite, "clear", test_clear);
add_test(suite, "all", test_all);
add_test(suite, "none", test_none);
add_test(suite, "any", test_any);
}
<file_sep>#include "array_t.h"
#include <glug/containers/array/array.h>
#include <alloc.h>
#include <stdint.h>
#include <string.h>
enum glug_cont_error glug_array_alloc(struct glug_array **ary, size_t cap, const struct glug_cont_config *config)
{
struct glug_allocator alloc =
{
.malloc = get_def_malloc(),
.free = get_def_free()
};
return glug_array_alloc_custom(ary, cap, config, &alloc);
}
enum glug_cont_error glug_array_alloc_custom(struct glug_array **ary, size_t cap,
const struct glug_cont_config *config,
const struct glug_allocator *alloc)
{
struct glug_array *new_ary;
void *temp;
size_t size;
if (!cap) return glug_cont_einvcap;
if (!alloc || !alloc->malloc || !alloc->free) return glug_cont_einvalloc;
if (!config || !config->el_size || !config->copy_el || !config->free_el) return glug_cont_einvconf;
size = config->el_size * cap + sizeof(struct glug_array);
if (!glug_malloc(alloc->malloc, (void **)&new_ary, size))
return glug_cont_enomem;
if (!glug_malloc(alloc->malloc, &temp, config->el_size))
{
glug_free(alloc->free, (void **)&new_ary);
return glug_cont_enomem;
}
new_ary->temp = temp;
new_ary->free = alloc->free;
new_ary->config = *config;
new_ary->capacity = cap;
memset(new_ary->data, 0, config->el_size * cap);
*ary = new_ary;
return glug_cont_ok;
}
void glug_array_free(struct glug_array **ary)
{
struct glug_array *array = *ary;
size_t i;
for (i = 0; i < array->capacity; ++i)
{
memcpy(array->temp, &array->data[i * array->config.el_size], array->config.el_size);
array->config.free_el(array->temp);
}
glug_free(array->free, &array->temp);
glug_free(array->free, (void **)ary);
}
enum glug_cont_error glug_array_clone(struct glug_array **dst, const struct glug_array *src)
{
struct glug_array *new_ary;
if (glug_array_alloc(&new_ary, src->capacity, &src->config) != glug_cont_ok)
return glug_cont_enomem;
memcpy(new_ary->data, src->data, src->config.el_size * src->capacity);
*dst = new_ary;
return glug_cont_ok;
}
enum glug_cont_error glug_array_clone_custom(struct glug_array **dst, const struct glug_array *src,
const struct glug_allocator *alloc)
{
struct glug_array *new_ary;
if (glug_array_alloc_custom(&new_ary, src->capacity, &src->config, alloc) != glug_cont_ok)
return glug_cont_enomem;
memcpy(new_ary->data, src->data, src->capacity * src->config.el_size);
*dst = new_ary;
return glug_cont_ok;
}
enum glug_cont_error glug_array_copy(struct glug_array *dst, const struct glug_array *src)
{
size_t i;
if (dst->capacity != src->capacity || dst->config.el_size != src->config.el_size) return glug_cont_eincompat;
for (i = 0; i < dst->capacity; ++i)
{
memcpy(dst->temp, &dst->data[i * dst->config.el_size], dst->config.el_size);
dst->config.free_el(dst->temp);
}
dst->config = src->config;
for (i = 0; i < src->capacity; ++i)
{
memcpy(dst->temp, &src->data[i * src->config.el_size], src->config.el_size);
memcpy(dst->data + i * dst->config.el_size, dst->temp, dst->config.el_size);
}
return glug_cont_ok;
}
void glug_array_get_config(const struct glug_array *ary, struct glug_cont_config *config)
{
*config = ary->config;
}
size_t glug_array_capacity(const struct glug_array *ary)
{
return ary->capacity;
}
size_t glug_array_elem_size(const struct glug_array *ary)
{
return ary->config.el_size;
}
enum glug_cont_error glug_array_at(const struct glug_array *ary, size_t idx, void *val)
{
if (idx >= ary->capacity) return glug_cont_ebounds;
idx *= ary->config.el_size;
memcpy(val, ary->data + idx, ary->config.el_size);
return glug_cont_ok;
}
enum glug_cont_error glug_array_set(struct glug_array *ary, size_t idx, void *new_val)
{
if (idx >= ary->capacity) return glug_cont_ebounds;
idx *= ary->config.el_size;
ary->config.copy_el(ary->temp, new_val);
memcpy(ary->data + idx, ary->temp, ary->config.el_size);
return glug_cont_ok;
}
enum glug_cont_error glug_array_insert(struct glug_array *ary, size_t idx, void *new_val)
{
size_t nelems, last;
uint8_t *pidx, *plast;
if (idx >= ary->capacity) return glug_cont_ebounds;
last = ary->capacity - 1;
nelems = last - idx;
pidx = ary->data + idx * ary->config.el_size;
plast = ary->data + last * ary->config.el_size;
// copy the last element to `temp` and "free" it
memcpy(ary->temp, plast, ary->config.el_size);
ary->config.free_el(ary->temp);
// shift up all elements starting at `idx`
memmove(pidx + ary->config.el_size, pidx, nelems * ary->config.el_size);
// set the element we were inserting
glug_array_set(ary, idx, new_val);
return glug_cont_ok;
}
enum glug_cont_error glug_array_splice(struct glug_array *ary, size_t idx)
{
size_t nelems, last;
uint8_t *pidx, *plast;
if (idx >= ary->capacity) return glug_cont_ebounds;
last = ary->capacity - 1;
nelems = last - idx;
pidx = ary->data + idx * ary->config.el_size;
plast = ary->data + last * ary->config.el_size;
// copy the element at `idx` to `temp` and "free" it
memcpy(ary->temp, pidx, ary->config.el_size);
ary->config.free_el(ary->temp);
//shift down all elements start at `idx + 1`
memmove(pidx, pidx + ary->config.el_size, nelems * ary->config.el_size);
// zero out the last element that was "shifted" in
memset(plast, 0, ary->config.el_size);
return glug_cont_ok;
}
enum glug_cont_error glug_array_swap(struct glug_array *ary, size_t idx1, size_t idx2)
{
uint8_t *pindx1, *pindx2;
if (idx1 >= ary->capacity || idx2 >= ary->capacity) return glug_cont_ebounds;
pindx1 = ary->data + idx1 * ary->config.el_size;
pindx2 = ary->data + idx2 * ary->config.el_size;
memcpy(ary->temp, pindx1, ary->config.el_size);
memcpy(pindx1, pindx2, ary->config.el_size);
memcpy(pindx2, ary->temp, ary->config.el_size);
return glug_cont_ok;
}
<file_sep>#include "suites.h"
#include <CUnit/Assert.h>
#include <create_suite.h>
#include <counted_alloc.h>
#include <glug/containers/alloc_t.h>
#include <glug/containers/config.h>
#include <glug/containers/array/array.h>
#include <glug/containers/array/iterator.h>
#include <stdint.h>
#include <stdlib.h>
static struct glug_array *array;
static struct glug_array_iter *iterator;
static enum glug_iterator_error err;
static struct glug_allocator alloc =
{
.malloc = counted_malloc,
.free = counted_free,
};
static void before_each(void)
{
struct glug_cont_config conf;
get_float_config(&conf);
array = NULL;
glug_array_alloc(&array, 10, &conf);
alloc.malloc = counted_malloc;
alloc.free = counted_free;
clear_counts();
iterator = NULL;
err = glug_iter_ok;
}
static void after_each(void)
{
if (array)
glug_array_free(&array);
if (iterator)
glug_array_iter_free(&iterator);
}
static void test_alloc_and_free(void)
{
err = glug_array_iter_alloc(&iterator, array);
CU_ASSERT_EQUAL(err, glug_iter_ok);
CU_ASSERT_PTR_NOT_NULL(iterator);
glug_array_iter_free(&iterator);
err = glug_array_riter_alloc(&iterator, array);
CU_ASSERT_EQUAL(err, glug_iter_ok);
CU_ASSERT_PTR_NOT_NULL(iterator);
glug_array_iter_free(&iterator);
}
static void test_alloc_custom(void)
{
err = glug_array_iter_alloc_custom(&iterator, array, &alloc);
CU_ASSERT_EQUAL(err, glug_iter_ok);
CU_ASSERT_PTR_NOT_NULL(iterator);
CU_ASSERT_EQUAL(malloc_calls, 1);
glug_array_iter_free(&iterator);
CU_ASSERT_EQUAL(free_calls, 1);
err = glug_array_riter_alloc_custom(&iterator, array, &alloc);
CU_ASSERT_EQUAL(err, glug_iter_ok);
CU_ASSERT_PTR_NOT_NULL(iterator);
CU_ASSERT_EQUAL(malloc_calls, 2);
glug_array_iter_free(&iterator);
CU_ASSERT_EQUAL(free_calls, 2);
}
static void test_invalid_allocator(void)
{
alloc.malloc = NULL;
err = glug_array_iter_alloc_custom(&iterator, array, &alloc);
CU_ASSERT_EQUAL(err, glug_iter_einvalloc);
CU_ASSERT_PTR_NULL(iterator);
alloc.malloc = counted_malloc;
alloc.free = NULL;
err = glug_array_iter_alloc_custom(&iterator, array, &alloc);
CU_ASSERT_EQUAL(err, glug_iter_einvalloc);
CU_ASSERT_PTR_NULL(iterator);
alloc.free = counted_free;
alloc.malloc = NULL;
err = glug_array_riter_alloc_custom(&iterator, array, &alloc);
CU_ASSERT_EQUAL(err, glug_iter_einvalloc);
CU_ASSERT_PTR_NULL(iterator);
alloc.malloc = counted_malloc;
alloc.free = NULL;
err = glug_array_riter_alloc_custom(&iterator, array, &alloc);
CU_ASSERT_EQUAL(err, glug_iter_einvalloc);
CU_ASSERT_PTR_NULL(iterator);
alloc.free = counted_free;
}
static void test_iterate_array(void)
{
size_t i;
float val;
// fill array
for (i = 0; i < glug_array_capacity(array); ++i)
{
float val = (i + 5) * 0.314f;
glug_array_set(array, i, &val);
}
i = 0;
for (glug_array_iter_alloc(&iterator, array); !glug_array_iter_at_end(iterator); glug_array_iter_next(iterator))
{
glug_array_iter_val(iterator, &val);
CU_ASSERT_DOUBLE_EQUAL(val, (i + 5) * 0.314f, 0.0001);
++i;
}
CU_ASSERT_EQUAL(i, 10);
err = glug_array_iter_val(iterator, &val);
CU_ASSERT_EQUAL(err, glug_iter_eatend);
// "revert" the iterator to the start position
while (!glug_array_iter_at_begin(iterator))
glug_array_iter_prev(iterator);
err = glug_array_iter_val(iterator, &val);
CU_ASSERT_EQUAL(err, glug_iter_ok);
CU_ASSERT_DOUBLE_EQUAL(val, 5 * 0.314f, 0.0001);
glug_array_iter_free(&iterator);
}
static void test_reviterate_array(void)
{
size_t i, cap = glug_array_capacity(array);
float val;
// fill array
for (i = 0; i < cap; ++i)
{
float val = (i + 3) * 0.7654f;
glug_array_set(array, i, &val);
}
i = 0;
for (glug_array_riter_alloc(&iterator, array); !glug_array_iter_at_end(iterator); glug_array_iter_next(iterator))
{
glug_array_iter_val(iterator, &val);
CU_ASSERT_DOUBLE_EQUAL(val, (cap - i + 2) * 0.7654f, 0.0001);
++i;
}
CU_ASSERT_EQUAL(i, 10);
err = glug_array_iter_val(iterator, &val);
CU_ASSERT_EQUAL(err, glug_iter_eatend);
// "revert" the iterator to the start position
while (!glug_array_iter_at_begin(iterator))
glug_array_iter_prev(iterator);
err = glug_array_iter_val(iterator, &val);
CU_ASSERT_EQUAL(err, glug_iter_ok);
CU_ASSERT_DOUBLE_EQUAL(val, (cap + 2) * 0.7654f, 0.0001);
glug_array_iter_free(&iterator);
}
void add_array_iter_suite(suite_creator_t create_suite, test_adder_t add_test)
{
CU_pSuite suite = create_suite("array iterator", before_each, after_each);
add_test(suite, "alloc and free", test_alloc_and_free);
add_test(suite, "alloc custom", test_alloc_custom);
add_test(suite, "invalid allocator", test_invalid_allocator);
add_test(suite, "iterate array", test_iterate_array);
add_test(suite, "reverse iterate array", test_reviterate_array);
}
<file_sep>#ifndef BITSET_T_H
#define BITSET_T_H
#include <glug/containers/bitset/bitset.h>
#include <glug/containers/alloc_t.h>
#include <stddef.h>
#include <stdint.h>
struct glug_bitset
{
glug_free_t free;
size_t capacity;
uint8_t data[];
};
struct glug_bitset_iter
{
glug_free_t free;
const struct glug_bitset *bs;
int8_t stride;
uint8_t bit;
const uint8_t *pdata;
};
struct glug_bitset_range
{
glug_free_t free;
const struct glug_bitset *bitset;
size_t stride, start, end;
const uint8_t *front, *back;
int8_t frontbit, backbit;
void (*next)(const uint8_t **, int8_t *, size_t), (*prev)(const uint8_t **, int8_t *, size_t);
};
#endif // BITSET_T_H
<file_sep>#include <CUnit/Basic.h>
#include <CUnit/Assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include "create_suite.h"
#include "suites/suites.h"
int run_tests(CU_BasicRunMode);
CU_pSuite create_suite(char *, CU_SetUpFunc, CU_TearDownFunc);
void add_test_to_suite(CU_pSuite, const char *, void (*)(void));
int main(void)
{
CU_ErrorCode err = CUE_SUCCESS;
/* initialize the CUnit test registry */
if ((err = CU_initialize_registry()) != CUE_SUCCESS)
return err;
/* setup test suites */
add_array_suite(create_suite, add_test_to_suite);
add_array_iter_suite(create_suite, add_test_to_suite);
add_array_range_suite(create_suite, add_test_to_suite);
add_bitset_suite(create_suite, add_test_to_suite);
add_bitset_iter_suite(create_suite, add_test_to_suite);
add_bitset_range_suite(create_suite, add_test_to_suite);
return run_tests(CU_BRM_VERBOSE);
}
CU_pSuite create_suite(char *suite_name, CU_SetUpFunc before_each, CU_TearDownFunc after_each)
{
CU_pSuite suite;
/* add suites to the registry */
suite = CU_add_suite_with_setup_and_teardown(suite_name, NULL, NULL, before_each, after_each);
if (!suite)
{
CU_cleanup_registry();
printf("Unable to allocate test suite");
exit(CU_get_error());
}
return suite;
}
void add_test_to_suite(CU_pSuite suite, const char *name, void (*testfcn)(void))
{
CU_pTest test = CU_add_test(suite, name, testfcn);
if (!test)
{
CU_cleanup_registry();
printf("Unable to allocate test");
exit(CU_get_error());
}
}
int run_tests(CU_BasicRunMode run_mode)
{
int failures = 0;
/* Run all tests using the console interface */
CU_basic_set_mode(run_mode);
if (CU_basic_run_tests() != CUE_SUCCESS)
{
CU_cleanup_registry();
return CU_get_error();
}
failures = (int)CU_get_number_of_tests_failed();
CU_cleanup_registry();
return failures;
}
<file_sep>#ifndef ARRAY_T_H
#define ARRAY_T_H
#include <glug/containers/array/array.h>
#include <glug/containers/alloc_t.h>
#include <glug/containers/config_t.h>
#include <stddef.h>
#include <stdint.h>
struct glug_array
{
glug_free_t free;
struct glug_cont_config config;
size_t capacity;
void *temp;
uint8_t data[];
};
struct glug_array_iter
{
glug_free_t free;
const struct glug_array *ary;
int8_t stride;
const uint8_t *pdata;
};
struct glug_array_range
{
glug_free_t free;
const struct glug_array *ary;
size_t stride, start, end;
const uint8_t *front, *back;
const uint8_t *(*next)(const uint8_t *, size_t), *(*prev)(const uint8_t *, size_t);
};
#endif // ARRAY_T_H
<file_sep>#include "alloc.h"
#include <stdlib.h>
glug_malloc_t get_def_malloc(void)
{
return malloc;
}
glug_realloc_t get_def_realloc(void)
{
return realloc;
}
glug_free_t get_def_free(void)
{
return free;
}
glug_bool glug_malloc(glug_malloc_t alloc_f, void **block, size_t sz)
{
void *new_block = alloc_f(sz);
if (!new_block)
return false;
*block = new_block;
return true;
}
glug_bool glug_realloc(glug_realloc_t realloc_f, void **block, size_t sz)
{
void *new_block = realloc_f(*block, sz);
if (!new_block)
return false;
*block = new_block;
return true;
}
void glug_free(glug_free_t free_f, void **block)
{
free_f(*block);
*block = NULL;
}
<file_sep>#include "bitset_t.h"
#include <glug/containers/bitset/iterator.h>
#include <alloc.h>
#include <defs.h>
#include <string.h>
static enum glug_iterator_error create_iterator(struct glug_bitset_iter **iter, const struct glug_bitset *bs,
const struct glug_allocator *alloc, size_t start, int8_t stride)
{
struct glug_bitset_iter *new_iter;
if (!alloc || !alloc->malloc || !alloc->free) return glug_iter_einvalloc;
if (!glug_malloc(alloc->malloc, (void **)&new_iter, sizeof(struct glug_bitset_iter)))
return glug_iter_enomem;
new_iter->free = alloc->free;
new_iter->bs = bs;
new_iter->stride = stride;
new_iter->bit = start % CHARBIT;
new_iter->pdata = bs->data + BIT_TO_BYTE(start);
*iter = new_iter;
return glug_iter_ok;
}
static const uint8_t *last_element(const struct glug_bitset *ary)
{
return ary->data + BIT_TO_BYTE(ary->capacity - 1);
}
enum glug_iterator_error glug_bitset_iter_alloc(struct glug_bitset_iter **iter, const struct glug_bitset *ary)
{
struct glug_allocator allocator =
{
.malloc = get_def_malloc(),
.free = get_def_free(),
};
return glug_bitset_iter_alloc_custom(iter, ary, &allocator);
}
enum glug_iterator_error glug_bitset_riter_alloc(struct glug_bitset_iter **iter, const struct glug_bitset *ary)
{
struct glug_allocator allocator =
{
.malloc = get_def_malloc(),
.free = get_def_free(),
};
return glug_bitset_riter_alloc_custom(iter, ary, &allocator);
}
enum glug_iterator_error glug_bitset_iter_alloc_custom(struct glug_bitset_iter **iter, const struct glug_bitset *ary,
const struct glug_allocator *allocator)
{
return create_iterator(iter, ary, allocator, 0, 1);
}
enum glug_iterator_error glug_bitset_riter_alloc_custom(struct glug_bitset_iter **iter, const struct glug_bitset *ary,
const struct glug_allocator *allocator)
{
return create_iterator(iter, ary, allocator, ary->capacity - 1, -1);
}
void glug_bitset_iter_free(struct glug_bitset_iter **iter)
{
glug_free((*iter)->free, (void **)iter);
}
glug_bool glug_bitset_iter_at_begin(const struct glug_bitset_iter *iter)
{
return
// forward
(iter->stride > 0 && iter->pdata == iter->bs->data && iter->bit == 0) ||
// reverse
(iter->stride < 0 && iter->pdata == last_element(iter->bs) && iter->bit == 0);
}
glug_bool glug_bitset_iter_at_end(const struct glug_bitset_iter *iter)
{
return
// forward
(iter->stride > 0 && iter->pdata >= last_element(iter->bs) && iter->bit == iter->bs->capacity % CHARBIT) ||
// reverse
(iter->stride < 0 && iter->pdata < iter->bs->data);
}
enum glug_iterator_error glug_bitset_iter_prev(struct glug_bitset_iter *iter)
{
if (glug_bitset_iter_at_begin(iter))
return glug_iter_ebounds;
iter->bit += iter->stride;
iter->pdata -= BIT_TO_BYTE(BYTE_TO_BIT(1) & iter->bit) * iter->stride;
iter->bit &= BYTE_TO_BIT(1) - 1;
return glug_iter_ok;
}
enum glug_iterator_error glug_bitset_iter_next(struct glug_bitset_iter *iter)
{
if (glug_bitset_iter_at_end(iter))
return glug_iter_ebounds;
iter->bit += iter->stride;
iter->pdata += BIT_TO_BYTE(BYTE_TO_BIT(1) & iter->bit) * iter->stride;
iter->bit &= BYTE_TO_BIT(1) - 1;
return glug_iter_ok;
}
enum glug_iterator_error glug_bitset_iter_val(struct glug_bitset_iter *iter, glug_bool *val)
{
if (glug_bitset_iter_at_end(iter))
return glug_iter_eatend;
*val = (*iter->pdata & 1 << iter->bit) > 0;
return glug_iter_ok;
}
<file_sep>#ifndef GLUG_TEST_ALLOC_H
#define GLUG_TEST_ALLOC_H
#include <stddef.h>
extern int succeed_next_nmalloc;
extern int succeed_next_nrealloc;
extern int malloc_calls;
extern int realloc_calls;
extern int free_calls;
void *counted_malloc(size_t sz);
void *counted_realloc(void *block, size_t sz);
void counted_free(void *block);
void clear_counts(void);
#endif // GLUG_TEST_ALLOC_H
<file_sep>#ifndef GLUG_BITSET_RANGE_H
#define GLUG_BITSET_RANGE_H
#include "bitset_t.h"
#include <glug/import.h>
#include <glug/extern.h>
#include <glug/containers/error_t.h>
#include <glug/bool.h>
#include <stddef.h>
GLUG_EXTERN_START
struct glug_bitset;
struct glug_allocator;
struct glug_range_config;
GLUG_LIB_API enum glug_range_error glug_bitset_range_alloc(struct glug_bitset_range **range,
const struct glug_bitset *ary,
const struct glug_range_config *config);
GLUG_LIB_API enum glug_range_error glug_bitset_range_alloc_custom(struct glug_bitset_range **range,
const struct glug_bitset *ary,
const struct glug_range_config *config,
const struct glug_allocator *allocator);
GLUG_LIB_API void glug_bitset_range_free(struct glug_bitset_range **range);
GLUG_LIB_API enum glug_range_error glug_bitset_range_front(const struct glug_bitset_range *range, glug_bool *val);
GLUG_LIB_API enum glug_range_error glug_bitset_range_back (const struct glug_bitset_range *range, glug_bool *val);
GLUG_LIB_API enum glug_range_error glug_bitset_range_pop_front(struct glug_bitset_range *range);
GLUG_LIB_API enum glug_range_error glug_bitset_range_pop_back (struct glug_bitset_range *range);
GLUG_LIB_API glug_bool glug_bitset_range_empty(const struct glug_bitset_range *range);
GLUG_LIB_API size_t glug_bitset_range_length(const struct glug_bitset_range *range);
GLUG_EXTERN_END
#endif // GLUG_BITSET_RANGE_H
<file_sep>#ifndef GLUG_ALLOC_T_H
#define GLUG_ALLOC_T_H
#include <stddef.h>
typedef void *(*glug_malloc_t) (size_t nbytes);
typedef void *(*glug_realloc_t)(void *block, size_t nbytes);
typedef void (*glug_free_t) (void *block);
struct glug_allocator
{
glug_malloc_t malloc;
glug_free_t free;
};
#ifdef GLUG_USE_TYPEDEFS
typedef struct glug_allocator glug_allocator_t;
#endif
#endif // GLUG_ALLOC_T_H
<file_sep>#include "suites.h"
#include <CUnit/Assert.h>
#include <create_suite.h>
#include <counted_alloc.h>
#include <glug/containers/alloc_t.h>
#include <glug/containers/bitset/bitset.h>
#include <glug/containers/bitset/iterator.h>
#include <stdint.h>
#include <stdlib.h>
static struct glug_bitset *bitset;
static struct glug_bitset_iter *iterator;
static enum glug_iterator_error err;
static struct glug_allocator alloc =
{
.malloc = counted_malloc,
.free = counted_free,
};
static void before_each(void)
{
bitset = NULL;
glug_bitset_alloc(&bitset, 25);
alloc.malloc = counted_malloc;
alloc.free = counted_free;
clear_counts();
iterator = NULL;
err = glug_iter_ok;
}
static void after_each(void)
{
if (bitset)
glug_bitset_free(&bitset);
if (iterator)
glug_bitset_iter_free(&iterator);
}
static void test_alloc_and_free(void)
{
err = glug_bitset_iter_alloc(&iterator, bitset);
CU_ASSERT_EQUAL(err, glug_iter_ok);
CU_ASSERT_PTR_NOT_NULL(iterator);
glug_bitset_iter_free(&iterator);
err = glug_bitset_riter_alloc(&iterator, bitset);
CU_ASSERT_EQUAL(err, glug_iter_ok);
CU_ASSERT_PTR_NOT_NULL(iterator);
glug_bitset_iter_free(&iterator);
}
static void test_alloc_custom(void)
{
err = glug_bitset_iter_alloc_custom(&iterator, bitset, &alloc);
CU_ASSERT_EQUAL(err, glug_iter_ok);
CU_ASSERT_PTR_NOT_NULL(iterator);
CU_ASSERT_EQUAL(malloc_calls, 1);
glug_bitset_iter_free(&iterator);
CU_ASSERT_EQUAL(free_calls, 1);
err = glug_bitset_riter_alloc_custom(&iterator, bitset, &alloc);
CU_ASSERT_EQUAL(err, glug_iter_ok);
CU_ASSERT_PTR_NOT_NULL(iterator);
CU_ASSERT_EQUAL(malloc_calls, 2);
glug_bitset_iter_free(&iterator);
CU_ASSERT_EQUAL(free_calls, 2);
}
static void test_invalid_allocator(void)
{
alloc.malloc = NULL;
err = glug_bitset_iter_alloc_custom(&iterator, bitset, &alloc);
CU_ASSERT_EQUAL(err, glug_iter_einvalloc);
CU_ASSERT_PTR_NULL(iterator);
alloc.malloc = counted_malloc;
alloc.free = NULL;
err = glug_bitset_iter_alloc_custom(&iterator, bitset, &alloc);
CU_ASSERT_EQUAL(err, glug_iter_einvalloc);
CU_ASSERT_PTR_NULL(iterator);
alloc.free = counted_free;
alloc.malloc = NULL;
err = glug_bitset_riter_alloc_custom(&iterator, bitset, &alloc);
CU_ASSERT_EQUAL(err, glug_iter_einvalloc);
CU_ASSERT_PTR_NULL(iterator);
alloc.malloc = counted_malloc;
alloc.free = NULL;
err = glug_bitset_riter_alloc_custom(&iterator, bitset, &alloc);
CU_ASSERT_EQUAL(err, glug_iter_einvalloc);
CU_ASSERT_PTR_NULL(iterator);
alloc.free = counted_free;
}
static void test_iterate_bitset(void)
{
size_t i, cap = glug_bitset_capacity(bitset);
glug_bool val;
// set arbitrary bits
glug_bitset_set(bitset, 1);
glug_bitset_set(bitset, 5);
glug_bitset_set(bitset, 6);
glug_bitset_set(bitset, 7);
glug_bitset_set(bitset, 15);
i = 0;
for (glug_bitset_iter_alloc(&iterator, bitset); !glug_bitset_iter_at_end(iterator); glug_bitset_iter_next(iterator))
{
glug_bitset_iter_val(iterator, &val);
if (i == 1 || i == 5 || i == 6 || i == 7 || i == 15)
CU_ASSERT_TRUE(val)
else
CU_ASSERT_FALSE(val)
++i;
}
CU_ASSERT_EQUAL(i, cap);
err = glug_bitset_iter_val(iterator, &val);
CU_ASSERT_EQUAL(err, glug_iter_eatend);
// "revert" the iterator to the start position
while (!glug_bitset_iter_at_begin(iterator))
glug_bitset_iter_prev(iterator);
err = glug_bitset_iter_val(iterator, &val);
CU_ASSERT_EQUAL(err, glug_iter_ok);
CU_ASSERT_FALSE(val);
glug_bitset_iter_next(iterator);
err = glug_bitset_iter_val(iterator, &val);
CU_ASSERT_EQUAL(err, glug_iter_ok);
CU_ASSERT_TRUE(val);
glug_bitset_iter_free(&iterator);
}
static void test_reviterate_bitset(void)
{
size_t i, cap = glug_bitset_capacity(bitset);
glug_bool val;
// set arbitrary bits
glug_bitset_set(bitset, 5);
glug_bitset_set(bitset, 6);
glug_bitset_set(bitset, 7);
glug_bitset_set(bitset, 15);
glug_bitset_set(bitset, 23);
i = 0;
for (glug_bitset_riter_alloc(&iterator, bitset); !glug_bitset_iter_at_end(iterator); glug_bitset_iter_next(iterator))
{
size_t rev_i = cap - i - 1;
glug_bitset_iter_val(iterator, &val);
if (rev_i == 5 || rev_i == 6 || rev_i == 7 || rev_i == 15 || rev_i == 23)
CU_ASSERT_TRUE(val)
else
CU_ASSERT_FALSE(val)
++i;
}
CU_ASSERT_EQUAL(i, cap);
err = glug_bitset_iter_val(iterator, &val);
CU_ASSERT_EQUAL(err, glug_iter_eatend);
// "revert" the iterator to the start position
while (!glug_bitset_iter_at_begin(iterator))
glug_bitset_iter_prev(iterator);
err = glug_bitset_iter_val(iterator, &val);
CU_ASSERT_EQUAL(err, glug_iter_ok);
CU_ASSERT_FALSE(val);
glug_bitset_iter_next(iterator);
err = glug_bitset_iter_val(iterator, &val);
CU_ASSERT_EQUAL(err, glug_iter_ok);
CU_ASSERT_TRUE(val);
glug_bitset_iter_free(&iterator);
}
void add_bitset_iter_suite(suite_creator_t create_suite, test_adder_t add_test)
{
CU_pSuite suite = create_suite("bitset iterator", before_each, after_each);
add_test(suite, "alloc and free", test_alloc_and_free);
add_test(suite, "alloc custom", test_alloc_custom);
add_test(suite, "invalid allocator", test_invalid_allocator);
add_test(suite, "iterate bitset", test_iterate_bitset);
add_test(suite, "reverse iterate bitset", test_reviterate_bitset);
}
<file_sep>#ifndef GLUG_BITSET_ITERATOR_H
#define GLUG_BITSET_ITERATOR_H
#include "bitset_t.h"
#include <glug/import.h>
#include <glug/extern.h>
#include <glug/bool.h>
#include <glug/containers/error_t.h>
GLUG_EXTERN_START
GLUG_LIB_API enum glug_iterator_error glug_bitset_iter_alloc(struct glug_bitset_iter **iter,
const struct glug_bitset *ary);
GLUG_LIB_API enum glug_iterator_error glug_bitset_riter_alloc(struct glug_bitset_iter **iter,
const struct glug_bitset *ary);
GLUG_LIB_API enum glug_iterator_error glug_bitset_iter_alloc_custom(struct glug_bitset_iter **iter,
const struct glug_bitset *ary,
const struct glug_allocator *allocator);
GLUG_LIB_API enum glug_iterator_error glug_bitset_riter_alloc_custom(struct glug_bitset_iter **iter,
const struct glug_bitset *ary,
const struct glug_allocator *allocator);
GLUG_LIB_API void glug_bitset_iter_free(struct glug_bitset_iter **iter);
GLUG_LIB_API glug_bool glug_bitset_iter_at_begin(const struct glug_bitset_iter *iter);
GLUG_LIB_API glug_bool glug_bitset_iter_at_end(const struct glug_bitset_iter *iter);
GLUG_LIB_API enum glug_iterator_error glug_bitset_iter_prev(struct glug_bitset_iter *iter);
GLUG_LIB_API enum glug_iterator_error glug_bitset_iter_next(struct glug_bitset_iter *iter);
GLUG_LIB_API enum glug_iterator_error glug_bitset_iter_val(struct glug_bitset_iter *iter, glug_bool *val);
GLUG_EXTERN_END
#endif // GLUG_BITSET_ITERATOR_H
<file_sep>#include <glug/containers/bitset/range.h>
#include "bitset_t.h"
#include <glug/containers/config_t.h>
#include <alloc.h>
#include <glug/bool.h>
#include <defs.h>
static void inc(const uint8_t **pdata, int8_t *bit, size_t stride)
{
int8_t next_bit = *bit;
next_bit = next_bit + stride % CHARBIT;
*pdata += BIT_TO_BYTE(stride) + BIT_TO_BYTE(next_bit);
*bit = next_bit % CHARBIT;
}
static void dec(const uint8_t **pdata, int8_t *bit, size_t stride)
{
uint8_t neg;
int8_t next_bit = *bit;
next_bit = next_bit - stride % CHARBIT;
neg = (next_bit & 1LL << MSB(int8_t)) >> MSB(int8_t);
next_bit += CHARBIT + neg + neg * next_bit;
*pdata -= BIT_TO_BYTE(stride) + neg;
*bit = next_bit % CHARBIT;
}
static const uint8_t *ptr_at_idx(const struct glug_bitset *bs, size_t idx)
{
return bs->data + BIT_TO_BYTE(idx);
}
static size_t ptr_to_idx(const struct glug_bitset *bs, const uint8_t *ptr, int8_t bit)
{
return (ptr - bs->data) * CHARBIT + bit;
}
enum glug_range_error glug_bitset_range_alloc(struct glug_bitset_range **range, const struct glug_bitset *bs,
const struct glug_range_config *config)
{
struct glug_allocator alloc =
{
.malloc = get_def_malloc(),
.free = get_def_free()
};
return glug_bitset_range_alloc_custom(range, bs, config, &alloc);
}
enum glug_range_error glug_bitset_range_alloc_custom(struct glug_bitset_range **range,
const struct glug_bitset *bs,
const struct glug_range_config *config,
const struct glug_allocator *alloc)
{
struct glug_bitset_range *new_range;
size_t cont_sz;
glug_bool forward;
if (!alloc || !alloc->malloc || !alloc->free) return glug_range_einvalloc;
if (!config || !config->stride) return glug_range_einvconf;
cont_sz = glug_bitset_capacity(bs);
if (config->start >= cont_sz || config->end >= cont_sz) return glug_range_ebounds;
if (!glug_malloc(alloc->malloc, (void **)&new_range, sizeof(struct glug_bitset_range))) return glug_range_enomem;
forward = config->end > config->start;
new_range->free = alloc->free;
new_range->bitset = bs;
new_range->start = config->start;
new_range->end = config->end;
new_range->front = ptr_at_idx(bs, config->start);
new_range->back = ptr_at_idx(bs, config->end);
new_range->frontbit = config->start % CHARBIT;
new_range->backbit = config->end % CHARBIT;
new_range->stride = config->stride;
new_range->next = forward ? inc : dec;
new_range->prev = forward ? dec : inc;
*range = new_range;
return glug_range_ok;
}
void glug_bitset_range_free(struct glug_bitset_range **range)
{
glug_free((*range)->free, (void **)range);
}
enum glug_range_error glug_bitset_range_front(const struct glug_bitset_range *range, glug_bool *val)
{
size_t idx = ptr_to_idx(range->bitset, range->front, range->frontbit);
if (glug_bitset_range_empty(range)) return glug_range_eempty;
glug_bitset_test(range->bitset, idx, val);
return glug_range_ok;
}
enum glug_range_error glug_bitset_range_back(const struct glug_bitset_range *range, glug_bool *val)
{
size_t idx = ptr_to_idx(range->bitset, range->back, range->backbit);
if (glug_bitset_range_empty(range)) return glug_range_eempty;
glug_bitset_test(range->bitset, idx, val);
return glug_range_ok;
}
enum glug_range_error glug_bitset_range_pop_front(struct glug_bitset_range *range)
{
if (glug_bitset_range_empty(range)) return glug_range_eempty;
range->next(&range->front, &range->frontbit, range->stride);
return glug_range_ok;
}
enum glug_range_error glug_bitset_range_pop_back(struct glug_bitset_range *range)
{
if (glug_bitset_range_empty(range)) return glug_range_eempty;
range->prev(&range->back, &range->backbit, range->stride);
return glug_range_ok;
}
glug_bool glug_bitset_range_empty(const struct glug_bitset_range *range)
{
const struct glug_bitset *bs = range->bitset;
size_t frontidx = ptr_to_idx(bs, range->front, range->frontbit),
backidx = ptr_to_idx(bs, range->back, range->backbit);
return (range->start < range->end &&
(range->front > range->back || (range->front == range->back && frontidx > backidx))) ||
(range->start > range->end &&
(range->front < range->back || (range->front == range->back && frontidx < backidx)));
}
size_t glug_bitset_range_length(const struct glug_bitset_range *range)
{
const uint8_t *high, *low;
uint8_t highbit, lowbit, rev;
size_t bytediff, bitdiff;
if (glug_bitset_range_empty(range)) return 0;
// interpolate the pointers based on direction
rev = range->front > range->back;
high = (const uint8_t *)(rev * (uintptr_t)range->front + (1 - rev) * (uintptr_t)range->back);
low = (const uint8_t *)(rev * (uintptr_t)range->back + (1 - rev) * (uintptr_t)range->front);
bytediff = high - low;
// interpolate the bits based on direction
highbit = rev * range->frontbit + (1 - rev) * range->backbit;
lowbit = rev * range->backbit + (1 - rev) * range->frontbit;
bitdiff = highbit - lowbit;
return (bytediff * CHARBIT + (high >= low && highbit > lowbit) * bitdiff + 1) / range->stride;
}
<file_sep>#ifndef GLUG_ARRAY_ITERATOR_H
#define GLUG_ARRAY_ITERATOR_H
#include "array_t.h"
#include <glug/import.h>
#include <glug/extern.h>
#include <glug/bool.h>
#include <glug/containers/error_t.h>
GLUG_EXTERN_START
GLUG_LIB_API enum glug_iterator_error glug_array_iter_alloc(struct glug_array_iter **iter,
const struct glug_array *ary);
GLUG_LIB_API enum glug_iterator_error glug_array_riter_alloc(struct glug_array_iter **iter,
const struct glug_array *ary);
GLUG_LIB_API enum glug_iterator_error glug_array_iter_alloc_custom(struct glug_array_iter **iter,
const struct glug_array *ary,
const struct glug_allocator *allocator);
GLUG_LIB_API enum glug_iterator_error glug_array_riter_alloc_custom(struct glug_array_iter **iter,
const struct glug_array *ary,
const struct glug_allocator *allocator);
GLUG_LIB_API void glug_array_iter_free(struct glug_array_iter **iter);
GLUG_LIB_API glug_bool glug_array_iter_at_begin(const struct glug_array_iter *iter);
GLUG_LIB_API glug_bool glug_array_iter_at_end(const struct glug_array_iter *iter);
GLUG_LIB_API enum glug_iterator_error glug_array_iter_prev(struct glug_array_iter *iter);
GLUG_LIB_API enum glug_iterator_error glug_array_iter_next(struct glug_array_iter *iter);
GLUG_LIB_API enum glug_iterator_error glug_array_iter_val(struct glug_array_iter *iter, void *val);
GLUG_EXTERN_END
#endif // GLUG_ARRAY_ITERATOR_H
<file_sep>#include "suites.h"
#include <CUnit/Assert.h>
#include <create_suite.h>
#include <counted_alloc.h>
#include <glug/containers/alloc_t.h>
#include <glug/containers/config.h>
#include <glug/containers/bitset/bitset.h>
#include <glug/containers/bitset/range.h>
#include <stdint.h>
#include <stdlib.h>
static struct glug_bitset *bitset;
static struct glug_bitset_range *range;
static enum glug_range_error err;
static struct glug_allocator alloc =
{
.malloc = counted_malloc,
.free = counted_free,
};
static struct glug_range_config conf;
static void before_each(void)
{
size_t cap = 30;
bitset = NULL;
glug_bitset_alloc(&bitset, cap);
alloc.malloc = counted_malloc;
alloc.free = counted_free;
clear_counts();
range = NULL;
err = glug_range_ok;
conf.start = 0;
conf.end = cap - 1;
conf.stride = 1;
}
static void after_each(void)
{
if (bitset)
glug_bitset_free(&bitset);
if (range)
glug_bitset_range_free(&range);
}
static void test_alloc_and_free(void)
{
err = glug_bitset_range_alloc(&range, bitset, &conf);
CU_ASSERT_EQUAL(err, glug_range_ok);
CU_ASSERT_PTR_NOT_NULL(range);
CU_ASSERT_EQUAL(glug_bitset_range_length(range), glug_bitset_capacity(bitset));
glug_bitset_range_free(&range);
// swap start and end indices
conf.start ^= conf.end;
conf.end ^= conf.start;
conf.start ^= conf.end;
err = glug_bitset_range_alloc(&range, bitset, &conf);
CU_ASSERT_EQUAL(err, glug_range_ok);
CU_ASSERT_PTR_NOT_NULL(range);
CU_ASSERT_EQUAL(glug_bitset_range_length(range), glug_bitset_capacity(bitset));
glug_bitset_range_free(&range);
}
static void test_alloc_custom(void)
{
err = glug_bitset_range_alloc_custom(&range, bitset, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_range_ok);
CU_ASSERT_PTR_NOT_NULL(range);
CU_ASSERT_EQUAL(glug_bitset_range_length(range), glug_bitset_capacity(bitset));
CU_ASSERT_EQUAL(malloc_calls, 1);
glug_bitset_range_free(&range);
CU_ASSERT_EQUAL(free_calls, 1);
// swap start and end indices
conf.start ^= conf.end;
conf.end ^= conf.start;
conf.start ^= conf.end;
err = glug_bitset_range_alloc_custom(&range, bitset, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_range_ok);
CU_ASSERT_PTR_NOT_NULL(range);
CU_ASSERT_EQUAL(glug_bitset_range_length(range), glug_bitset_capacity(bitset));
CU_ASSERT_EQUAL(malloc_calls, 2);
glug_bitset_range_free(&range);
CU_ASSERT_EQUAL(free_calls, 2);
}
static void test_invalid_allocator(void)
{
alloc.malloc = NULL;
err = glug_bitset_range_alloc_custom(&range, bitset, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_range_einvalloc);
CU_ASSERT_PTR_NULL(range);
alloc.malloc = counted_malloc;
alloc.free = NULL;
err = glug_bitset_range_alloc_custom(&range, bitset, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_range_einvalloc);
CU_ASSERT_PTR_NULL(range);
alloc.free = counted_free;
}
static void test_iterate_sub_range(void)
{
size_t start = 4, end = 15, i;
glug_bool val;
conf.start = start;
conf.end = end;
glug_bitset_set(bitset, 4);
glug_bitset_set(bitset, 5);
glug_bitset_set(bitset, 6);
glug_bitset_set(bitset, 10);
glug_bitset_set(bitset, 13);
i = start;
for (glug_bitset_range_alloc(&range, bitset, &conf);
!glug_bitset_range_empty(range);
glug_bitset_range_pop_front(range))
{
glug_bitset_range_front(range, &val);
if (i == 4 || i == 5 || i == 6 || i == 10 || i == 13)
{
CU_ASSERT_TRUE(val);
}
else
{
CU_ASSERT_FALSE(val);
}
++i;
}
CU_ASSERT_EQUAL(end + 1, i);
}
static void test_iterate_reverse_sub_range(void)
{
size_t start = 20, end = 5, i;
glug_bool val;
conf.start = start;
conf.end = end;
glug_bitset_set(bitset, 0);
glug_bitset_set(bitset, 5);
glug_bitset_set(bitset, 7);
glug_bitset_set(bitset, 16);
glug_bitset_set(bitset, 17);
i = start + 1;
for (glug_bitset_range_alloc(&range, bitset, &conf);
!glug_bitset_range_empty(range);
glug_bitset_range_pop_front(range))
{
--i;
glug_bitset_range_front(range, &val);
if (i == 0 || i == 5 || i == 7 || i == 16 || i == 17)
{
CU_ASSERT_TRUE(val);
}
else
{
CU_ASSERT_FALSE(val);
}
}
CU_ASSERT_EQUAL(end, i);
}
static void test_iterate_forward(void)
{
size_t i, cap = glug_bitset_capacity(bitset);
glug_bool val;
glug_bitset_set(bitset, 1);
glug_bitset_set(bitset, 2);
glug_bitset_set(bitset, 12);
glug_bitset_set(bitset, 16);
glug_bitset_set(bitset, 21);
i = 0;
for (glug_bitset_range_alloc(&range, bitset, &conf);
!glug_bitset_range_empty(range);
glug_bitset_range_pop_front(range))
{
glug_bitset_range_front(range, &val);
if (i == 1 || i == 2 || i == 12 || i == 16 || i == 21)
CU_ASSERT_TRUE(val)
else
CU_ASSERT_FALSE(val)
++i;
}
CU_ASSERT_EQUAL(i, cap);
CU_ASSERT_EQUAL(glug_bitset_range_length(range), 0);
err = glug_bitset_range_pop_front(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
err = glug_bitset_range_pop_back(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
}
static void test_iterate_backward(void)
{
size_t i;
glug_bool val;
glug_bitset_set(bitset, 0);
glug_bitset_set(bitset, 2);
glug_bitset_set(bitset, 5);
glug_bitset_set(bitset, 17);
glug_bitset_set(bitset, 22);
glug_bitset_range_alloc(&range, bitset, &conf);
i = glug_bitset_range_length(range);
for (; !glug_bitset_range_empty(range); glug_bitset_range_pop_back(range))
{
--i;
glug_bitset_range_back(range, &val);
if (i == 0 || i == 2 || i == 5 || i == 17 || i == 22)
CU_ASSERT_TRUE(val)
else
CU_ASSERT_FALSE(val)
}
CU_ASSERT_EQUAL(i, 0);
CU_ASSERT_EQUAL(glug_bitset_range_length(range), 0);
err = glug_bitset_range_pop_front(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
err = glug_bitset_range_pop_back(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
}
static void test_iterate_reverse(void)
{
size_t i;
glug_bool val;
glug_bitset_set(bitset, 3);
glug_bitset_set(bitset, 4);
glug_bitset_set(bitset, 5);
glug_bitset_set(bitset, 16);
glug_bitset_set(bitset, 24);
// swap start and end indices
conf.start ^= conf.end;
conf.end ^= conf.start;
conf.start ^= conf.end;
glug_bitset_range_alloc(&range, bitset, &conf);
i = glug_bitset_range_length(range);
for (; !glug_bitset_range_empty(range); glug_bitset_range_pop_front(range))
{
--i;
glug_bitset_range_front(range, &val);
if (i == 3 || i == 4 || i == 5 || i == 16 || i == 24)
CU_ASSERT_TRUE(val)
else
CU_ASSERT_FALSE(val)
}
CU_ASSERT_EQUAL(i, 0);
CU_ASSERT_EQUAL(glug_bitset_range_length(range), 0);
err = glug_bitset_range_pop_front(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
err = glug_bitset_range_pop_back(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
}
static void test_iterate_reverse_backward(void)
{
size_t i, cap = glug_bitset_capacity(bitset);
glug_bool val;
glug_bitset_set(bitset, 0);
glug_bitset_set(bitset, 8);
glug_bitset_set(bitset, 16);
glug_bitset_set(bitset, 24);
// swap start and end indices
conf.start ^= conf.end;
conf.end ^= conf.start;
conf.start ^= conf.end;
i = 0;
for (glug_bitset_range_alloc(&range, bitset, &conf);
!glug_bitset_range_empty(range);
glug_bitset_range_pop_back(range))
{
glug_bitset_range_back(range, &val);
if (i == 0 || i == 8 || i == 16 || i == 24)
CU_ASSERT_TRUE(val)
else
CU_ASSERT_FALSE(val)
++i;
}
CU_ASSERT_EQUAL(i, cap);
CU_ASSERT_EQUAL(glug_bitset_range_length(range), 0);
err = glug_bitset_range_pop_front(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
err = glug_bitset_range_pop_back(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
}
static void test_iterate_x7(void)
{
size_t i, cap = glug_bitset_capacity(bitset);
size_t stride = 7;
glug_bool val;
glug_bitset_set(bitset, 0);
glug_bitset_set(bitset, 14);
glug_bitset_set(bitset, 21);
glug_bitset_set(bitset, 28);
// swap start and end indices
conf.stride = stride;
glug_bitset_range_alloc(&range, bitset, &conf);
CU_ASSERT_EQUAL(glug_bitset_range_length(range), cap / stride);
i = 0;
for (; !glug_bitset_range_empty(range); glug_bitset_range_pop_front(range))
{
glug_bitset_range_front(range, &val);
if (i == 1)
CU_ASSERT_FALSE(val)
else
CU_ASSERT_TRUE(val)
++i;
}
CU_ASSERT_EQUAL(i, cap / stride + 1);
CU_ASSERT_EQUAL(glug_bitset_range_length(range), 0);
}
static void test_iterate_backward_x10(void)
{
size_t i, cap = glug_bitset_capacity(bitset);
size_t stride = 10;
glug_bool val;
glug_bitset_set(bitset, 9);
glug_bitset_set(bitset, 29);
// swap start and end indices
conf.stride = stride;
glug_bitset_range_alloc(&range, bitset, &conf);
CU_ASSERT_EQUAL(glug_bitset_range_length(range), cap / stride);
i = glug_bitset_range_length(range);
for (; !glug_bitset_range_empty(range); glug_bitset_range_pop_back(range))
{
--i;
glug_bitset_range_back(range, &val);
if (i == 0 || i == 2)
CU_ASSERT_TRUE(val)
else
CU_ASSERT_FALSE(val)
}
CU_ASSERT_EQUAL(i, 0);
CU_ASSERT_EQUAL(glug_bitset_range_length(range), 0);
}
void add_bitset_range_suite(suite_creator_t create_suite, test_adder_t add_test)
{
CU_pSuite suite = create_suite("bitset range", before_each, after_each);
add_test(suite, "alloc and free", test_alloc_and_free);
add_test(suite, "alloc custom", test_alloc_custom);
add_test(suite, "invalid allocator", test_invalid_allocator);
add_test(suite, "iterate sub-range", test_iterate_sub_range);
add_test(suite, "iterate reverse sub-range", test_iterate_reverse_sub_range);
add_test(suite, "iterate range forward", test_iterate_forward);
add_test(suite, "iterate range backward", test_iterate_backward);
add_test(suite, "iterate reverse range", test_iterate_reverse);
add_test(suite, "iterate reverse range backward", test_iterate_reverse_backward);
add_test(suite, "iterate range w/ stride", test_iterate_x7);
add_test(suite, "iterate range backward w/ stride", test_iterate_backward_x10);
}
<file_sep>#ifndef GLUG_BITSET_T_H
#define GLUG_BITSET_T_H
struct glug_bitset;
#ifdef GLUG_USE_TYPEDEFS
typedef struct glug_bitset glug_bitset_t;
#endif
struct glug_bitset_iter;
#ifdef GLUG_USE_TYPEDEFS
typedef struct glug_bitset_iter glug_bitset_iter_t;
#endif
struct glug_bitset_range;
#ifdef GLUG_USE_TYPEDEFS
typedef struct glug_bitset_range glug_bitset_range_t;
#endif
#endif // GLUG_BITSET_T_H
<file_sep>
#define CHARBIT 8
#define BIT_TO_BYTE(x) ((x) >> 3)
#define BYTE_TO_BIT(x) ((x) << 3)
#define BITSOF(x) (sizeof(x) * CHARBIT)
#define MSB(x) (BITSOF(x) - 1)
<file_sep># create simple example with simple dependencies
function (add_example)
set(SINGLE_VALS TARGET_NAME LINK_LIB INSTALL_PATH)
set(MULTI_VALS SRCS)
cmake_parse_arguments(GLUG "" "${SINGLE_VALS}" "${MULTI_VALS}" ${ARGN})
set(GLUG_XMPL_NAME ${GLUG_TARGET_NAME})
add_executable(${GLUG_XMPL_NAME} ${PLATFORM} ${GLUG_SRCS})
target_link_libraries(${GLUG_XMPL_NAME} ${GLUG_LINK_LIB})
set_target_properties(
${GLUG_XMPL_NAME}
PROPERTIES
INSTALL_RPATH "$ORIGIN;@loader_path"
BUILD_WITH_INSTALL_RPATH TRUE
)
endfunction()
<file_sep>#include "suites.h"
#include <CUnit/Assert.h>
#include <create_suite.h>
#include <counted_alloc.h>
#include <glug/containers/alloc_t.h>
#include <glug/containers/config.h>
#include <glug/containers/array/array.h>
#include <glug/containers/array/range.h>
#include <stdint.h>
#include <stdlib.h>
static struct glug_array *array;
static struct glug_array_range *range;
static enum glug_range_error err;
static struct glug_allocator alloc =
{
.malloc = counted_malloc,
.free = counted_free,
};
static struct glug_range_config conf;
static void before_each(void)
{
struct glug_cont_config aryconf;
size_t cap = 25;
get_float_config(&aryconf);
array = NULL;
glug_array_alloc(&array, cap, &aryconf);
alloc.malloc = counted_malloc;
alloc.free = counted_free;
clear_counts();
range = NULL;
err = glug_range_ok;
conf.start = 0;
conf.end = cap - 1;
conf.stride = 1;
}
static void after_each(void)
{
if (array)
glug_array_free(&array);
if (range)
glug_array_range_free(&range);
}
static void test_alloc_and_free(void)
{
err = glug_array_range_alloc(&range, array, &conf);
CU_ASSERT_EQUAL(err, glug_range_ok);
CU_ASSERT_PTR_NOT_NULL(range);
CU_ASSERT_EQUAL(glug_array_range_length(range), glug_array_capacity(array));
glug_array_range_free(&range);
// swap start and end indices
conf.start ^= conf.end;
conf.end ^= conf.start;
conf.start ^= conf.end;
err = glug_array_range_alloc(&range, array, &conf);
CU_ASSERT_EQUAL(err, glug_range_ok);
CU_ASSERT_PTR_NOT_NULL(range);
CU_ASSERT_EQUAL(glug_array_range_length(range), glug_array_capacity(array));
glug_array_range_free(&range);
}
static void test_alloc_custom(void)
{
err = glug_array_range_alloc_custom(&range, array, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_range_ok);
CU_ASSERT_PTR_NOT_NULL(range);
CU_ASSERT_EQUAL(glug_array_range_length(range), glug_array_capacity(array));
CU_ASSERT_EQUAL(malloc_calls, 1);
glug_array_range_free(&range);
CU_ASSERT_EQUAL(free_calls, 1);
// swap start and end indices
conf.start ^= conf.end;
conf.end ^= conf.start;
conf.start ^= conf.end;
err = glug_array_range_alloc_custom(&range, array, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_range_ok);
CU_ASSERT_PTR_NOT_NULL(range);
CU_ASSERT_EQUAL(glug_array_range_length(range), glug_array_capacity(array));
CU_ASSERT_EQUAL(malloc_calls, 2);
glug_array_range_free(&range);
CU_ASSERT_EQUAL(free_calls, 2);
}
static void test_invalid_allocator(void)
{
alloc.malloc = NULL;
err = glug_array_range_alloc_custom(&range, array, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_range_einvalloc);
CU_ASSERT_PTR_NULL(range);
alloc.malloc = counted_malloc;
alloc.free = NULL;
err = glug_array_range_alloc_custom(&range, array, &conf, &alloc);
CU_ASSERT_EQUAL(err, glug_range_einvalloc);
CU_ASSERT_PTR_NULL(range);
alloc.free = counted_free;
}
static void test_iterate_sub_range(void)
{
size_t start = 4, end = 15, i;
float val;
conf.start = start;
conf.end = end;
for (i = 0; i < glug_array_capacity(array); ++i)
{
val = 0.1f * i;
glug_array_set(array, i, &val);
}
i = start;
for (glug_array_range_alloc(&range, array, &conf);
!glug_array_range_empty(range);
glug_array_range_pop_front(range))
{
glug_array_range_front(range, &val);
CU_ASSERT_DOUBLE_EQUAL(val, i * 0.1f, 0.0001);
++i;
}
CU_ASSERT_EQUAL(end + 1, i);
}
static void test_iterate_reverse_sub_range(void)
{
size_t start = 20, end = 5, i;
float val;
conf.start = start;
conf.end = end;
for (i = 0; i < glug_array_capacity(array); ++i)
{
val = 0.25f * i;
glug_array_set(array, i, &val);
}
i = start + 1;
for (glug_array_range_alloc(&range, array, &conf);
!glug_array_range_empty(range);
glug_array_range_pop_front(range))
{
--i;
glug_array_range_front(range, &val);
CU_ASSERT_DOUBLE_EQUAL(val, i * 0.25f, 0.0001);
}
CU_ASSERT_EQUAL(end, i);
}
static void test_iterate_forward(void)
{
size_t i, cap = glug_array_capacity(array);
float val;
// fill array
for (i = 0; i < cap; ++i)
{
float val = (3 * i + 1) * 0.314f;
glug_array_set(array, i, &val);
}
i = 0;
for (glug_array_range_alloc(&range, array, &conf); !glug_array_range_empty(range); glug_array_range_pop_front(range))
{
glug_array_range_front(range, &val);
CU_ASSERT_DOUBLE_EQUAL(val, (3 * i + 1) * 0.314f, 0.0001);
++i;
}
CU_ASSERT_EQUAL(i, cap);
CU_ASSERT_EQUAL(glug_array_range_length(range), 0);
err = glug_array_range_pop_front(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
err = glug_array_range_pop_back(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
}
static void test_iterate_backward(void)
{
size_t i, cap = glug_array_capacity(array);
float val;
// fill array
for (i = 0; i < cap; ++i)
{
float val = (i + 10) * 0.542f;
glug_array_set(array, i, &val);
}
glug_array_range_alloc(&range, array, &conf);
i = glug_array_range_length(range);
for (; !glug_array_range_empty(range); glug_array_range_pop_back(range))
{
--i;
glug_array_range_back(range, &val);
CU_ASSERT_DOUBLE_EQUAL(val, (i + 10) * 0.542f, 0.0001);
}
CU_ASSERT_EQUAL(i, 0);
CU_ASSERT_EQUAL(glug_array_range_length(range), 0);
err = glug_array_range_pop_front(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
err = glug_array_range_pop_back(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
}
static void test_iterate_reverse(void)
{
size_t i, cap = glug_array_capacity(array);
float val;
// fill array
for (i = 0; i < cap; ++i)
{
float val = (i + 7) * 0.221f;
glug_array_set(array, i, &val);
}
// swap start and end indices
conf.start ^= conf.end;
conf.end ^= conf.start;
conf.start ^= conf.end;
glug_array_range_alloc(&range, array, &conf);
i = glug_array_range_length(range);
for (; !glug_array_range_empty(range); glug_array_range_pop_front(range))
{
--i;
glug_array_range_front(range, &val);
CU_ASSERT_DOUBLE_EQUAL(val, (i + 7) * 0.221f, 0.0001);
}
CU_ASSERT_EQUAL(i, 0);
CU_ASSERT_EQUAL(glug_array_range_length(range), 0);
err = glug_array_range_pop_front(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
err = glug_array_range_pop_back(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
}
static void test_iterate_reverse_backward(void)
{
size_t i, cap = glug_array_capacity(array);
float val;
// fill array
for (i = 0; i < cap; ++i)
{
float val = (i + 1) * 1.2312f;
glug_array_set(array, i, &val);
}
// swap start and end indices
conf.start ^= conf.end;
conf.end ^= conf.start;
conf.start ^= conf.end;
i = 0;
for (glug_array_range_alloc(&range, array, &conf); !glug_array_range_empty(range); glug_array_range_pop_back(range))
{
glug_array_range_back(range, &val);
CU_ASSERT_DOUBLE_EQUAL(val, (i + 1) * 1.2312f, 0.0001);
++i;
}
CU_ASSERT_EQUAL(i, cap);
CU_ASSERT_EQUAL(glug_array_range_length(range), 0);
err = glug_array_range_pop_front(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
err = glug_array_range_pop_back(range);
CU_ASSERT_EQUAL(err, glug_range_eempty);
}
static void test_iterate_by_three(void)
{
size_t i, cap = glug_array_capacity(array);
size_t stride = 3;
float val;
// fill array
for (i = 0; i < cap; ++i)
{
float val = i * 2.5f;
glug_array_set(array, i, &val);
}
// swap start and end indices
conf.stride = stride;
glug_array_range_alloc(&range, array, &conf);
CU_ASSERT_EQUAL(glug_array_range_length(range), cap / stride);
i = 0;
for (; !glug_array_range_empty(range); glug_array_range_pop_front(range))
{
glug_array_range_front(range, &val);
CU_ASSERT_DOUBLE_EQUAL(val, (i * 3) * 2.5f, 0.0001);
++i;
}
CU_ASSERT_EQUAL(i, cap / stride + 1);
CU_ASSERT_EQUAL(glug_array_range_length(range), 0);
}
void add_array_range_suite(suite_creator_t create_suite, test_adder_t add_test)
{
CU_pSuite suite = create_suite("array range", before_each, after_each);
add_test(suite, "alloc and free", test_alloc_and_free);
add_test(suite, "alloc custom", test_alloc_custom);
add_test(suite, "invalid allocator", test_invalid_allocator);
add_test(suite, "iterate sub-range", test_iterate_sub_range);
add_test(suite, "iterate reverse sub-range", test_iterate_reverse_sub_range);
add_test(suite, "iterate range forward", test_iterate_forward);
add_test(suite, "iterate range backward", test_iterate_backward);
add_test(suite, "iterate reverse range", test_iterate_reverse);
add_test(suite, "iterate reverse range backward", test_iterate_reverse_backward);
add_test(suite, "iterate range w/ stride", test_iterate_by_three);
}
<file_sep>#ifndef GLUG_CONT_ERROR_T_H
#define GLUG_CONT_ERROR_T_H
enum glug_cont_error
{
glug_cont_ok,
glug_cont_enomem,
glug_cont_einvalloc,
glug_cont_ebounds,
glug_cont_einvcap,
glug_cont_einvconf,
glug_cont_eincompat
};
#ifdef GLUG_USE_TYPEDEFS
typedef enum glug_cont_error glug_cont_error_t;
#endif
enum glug_iterator_error
{
glug_iter_ok,
glug_iter_enomem,
glug_iter_einvalloc,
glug_iter_ebounds,
glug_iter_eatend
};
#ifdef GLUG_USE_TYPEDEFS
typedef enum glug_iterator_error glug_iterator_error_t;
#endif
enum glug_range_error
{
glug_range_ok,
glug_range_enomem,
glug_range_einvalloc,
glug_range_ebounds,
glug_range_einvconf,
glug_range_eempty
};
#ifdef GLUG_USE_TYPEDEFS
typedef enum glug_range_error glug_range_error_t;
#endif
#endif // GLUG_CONT_ERROR_T_H
<file_sep>#include <glug/containers/config.h>
#include <stdint.h>
static void no_op(void *el)
{
(void) el;
}
static void copy_uint8(uint8_t *dst, uint8_t *src)
{
*dst = *src;
}
void get_uint8_config(struct glug_cont_config *config)
{
config->el_size = sizeof(uint8_t);
config->copy_el = (glug_copy_el_t)copy_uint8;
config->free_el = no_op;
}
void get_int8_config(struct glug_cont_config *config)
{
config->el_size = sizeof(int8_t);
config->copy_el = (glug_copy_el_t)copy_uint8;
config->free_el = no_op;
}
static void copy_uint16(uint16_t *dst, uint16_t *src)
{
*dst = *src;
}
void get_uint16_config(struct glug_cont_config *config)
{
config->el_size = sizeof(uint16_t);
config->copy_el = (glug_copy_el_t)copy_uint16;
config->free_el = no_op;
}
void get_int16_config(struct glug_cont_config *config)
{
config->el_size = sizeof(int16_t);
config->copy_el = (glug_copy_el_t)copy_uint16;
config->free_el = no_op;
}
static void copy_uint32(uint32_t *dst, uint32_t *src)
{
*dst = *src;
}
void get_uint32_config(struct glug_cont_config *config)
{
config->el_size = sizeof(uint32_t);
config->copy_el = (glug_copy_el_t)copy_uint32;
config->free_el = no_op;
}
void get_int32_config(struct glug_cont_config *config)
{
config->el_size = sizeof(int32_t);
config->copy_el = (glug_copy_el_t)copy_uint32;
config->free_el = no_op;
}
static void copy_uint64(uint64_t *dst, uint64_t *src)
{
*dst = *src;
}
void get_uint64_config(struct glug_cont_config *config)
{
config->el_size = sizeof(uint64_t);
config->copy_el = (glug_copy_el_t)copy_uint64;
config->free_el = no_op;
}
void get_int64_config(struct glug_cont_config *config)
{
config->el_size = sizeof(int64_t);
config->copy_el = (glug_copy_el_t)copy_uint64;
config->free_el = no_op;
}
static void copy_size(size_t *dst, size_t *src)
{
*dst = *src;
}
void get_sizet_config(struct glug_cont_config *config)
{
config->el_size = sizeof(size_t);
config->copy_el = (glug_copy_el_t)copy_size;
config->free_el = no_op;
}
static void copy_float(float *dst, float *src)
{
*dst = *src;
}
void get_float_config(struct glug_cont_config *config)
{
config->el_size = sizeof(float);
config->copy_el = (glug_copy_el_t)copy_float;
config->free_el = no_op;
}
static void copy_double(double *dst, double *src)
{
*dst = *src;
}
void get_double_config(struct glug_cont_config *config)
{
config->el_size = sizeof(float);
config->copy_el = (glug_copy_el_t)copy_double;
config->free_el = no_op;
}
static void copy_ldouble(long double *dst, long double *src)
{
*dst = *src;
}
void get_long_double_config(struct glug_cont_config *config)
{
config->el_size = sizeof(float);
config->copy_el = (glug_copy_el_t)copy_ldouble;
config->free_el = no_op;
}
static void copy_ptr(void **dst, void **src)
{
*dst = *src;
}
void get_ptr_config(struct glug_cont_config *config)
{
config->el_size = sizeof(uintptr_t);
config->copy_el = (glug_copy_el_t)copy_ptr;
config->free_el = no_op;
}
<file_sep>cmake_minimum_required(VERSION 3.0)
set(VER_MAJOR 1)
set(VER_MINOR 0)
set(VER_PATCH 0)
project(
glug_containers
VERSION ${VER_MAJOR}.${VER_MINOR}.${VER_PATCH}
LANGUAGES C
)
include(cmake/add_gluglib.cmake)
option(BUILD_STATIC "Build as a static library instead of shared" "OFF")
set(COM_ROOT common_headers/include/glug)
set(SRC_ROOT src)
set(INC_ROOT include/glug/containers/)
list(
APPEND
SOURCE
${COM_ROOT}/bool.h
${COM_ROOT}/extern.h
${COM_ROOT}/import.h
${COM_ROOT}/os.h
${INC_ROOT}/alloc_t.h
${INC_ROOT}/config_t.h
${INC_ROOT}/config.h
${INC_ROOT}/error_t.h
${SRC_ROOT}/alloc.h
${SRC_ROOT}/alloc.c
${SRC_ROOT}/config.c
${SRC_ROOT}/defs.h
${INC_ROOT}/array/array_t.h
${INC_ROOT}/array/array.h
${INC_ROOT}/array/iterator.h
${INC_ROOT}/array/range.h
${SRC_ROOT}/array/array_t.h
${SRC_ROOT}/array/array.c
${SRC_ROOT}/array/iterator.c
${SRC_ROOT}/array/range.c
${INC_ROOT}/bitset/bitset_t.h
${INC_ROOT}/bitset/bitset.h
${INC_ROOT}/bitset/iterator.h
${INC_ROOT}/bitset/range.h
${SRC_ROOT}/bitset/bitset_t.h
${SRC_ROOT}/bitset/bitset.c
${SRC_ROOT}/bitset/iterator.c
${SRC_ROOT}/bitset/range.c
)
add_gluglib(
TARGET_NAME ${PROJECT_NAME}
STATIC_BUILD ${BUILD_STATIC}
SOURCE ${SOURCE}
)
target_include_directories(
${PROJECT_NAME}
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/common_headers/include>
INTERFACE
$<INSTALL_INTERFACE:include>
PRIVATE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src>
)
# install the library
install(
TARGETS
${PROJECT_NAME}
EXPORT
Find${PROJECT_NAME}
DESTINATION
lib
)
#install the lib's headers
install(
DIRECTORY
include/
DESTINATION
include
)
# export the package to be included in other projects
export(PACKAGE ${PROJECT_NAME})
export(
TARGETS
${PROJECT_NAME}
FILE
${PROJECT_NAME}-config.cmake
)
# install export file
install(
EXPORT
Find${PROJECT_NAME}
DESTINATION
cmake
)
<file_sep>
# containers
<file_sep>#ifndef GLUG_ARRAY_T_H
#define GLUG_ARRAY_T_H
struct glug_array;
#ifdef GLUG_USE_TYPEDEFS
typedef struct glug_array glug_array_t;
#endif
struct glug_array_iter;
#ifdef GLUG_USE_TYPEDEFS
typedef struct glug_array_iter glug_array_iter_t;
#endif
struct glug_array_range;
#ifdef GLUG_USE_TYPEDEFS
typedef struct glug_array_range glug_array_range_t;
#endif
#endif // GLUG_ARRAY_T_H
<file_sep>#include "array_t.h"
#include <glug/containers/array/iterator.h>
#include <alloc.h>
#include <string.h>
static enum glug_iterator_error create_iterator(struct glug_array_iter **iter, const struct glug_array *ary,
const struct glug_allocator *alloc, size_t start, int8_t stride)
{
struct glug_array_iter *new_iter;
if (!alloc || !alloc->malloc || !alloc->free) return glug_iter_einvalloc;
if (!glug_malloc(alloc->malloc, (void **)&new_iter, sizeof(struct glug_array_iter)))
return glug_iter_enomem;
new_iter->free = alloc->free;
new_iter->ary = ary;
new_iter->stride = stride;
new_iter->pdata = ary->data + ary->config.el_size * start;
*iter = new_iter;
return glug_iter_ok;
}
static const uint8_t *last_element(const struct glug_array *ary)
{
return ary->data + (ary->capacity - 1) * ary->config.el_size;
}
enum glug_iterator_error glug_array_iter_alloc(struct glug_array_iter **iter, const struct glug_array *ary)
{
struct glug_allocator allocator =
{
.malloc = get_def_malloc(),
.free = get_def_free(),
};
return glug_array_iter_alloc_custom(iter, ary, &allocator);
}
enum glug_iterator_error glug_array_riter_alloc(struct glug_array_iter **iter, const struct glug_array *ary)
{
struct glug_allocator allocator =
{
.malloc = get_def_malloc(),
.free = get_def_free(),
};
return glug_array_riter_alloc_custom(iter, ary, &allocator);
}
enum glug_iterator_error glug_array_iter_alloc_custom(struct glug_array_iter **iter, const struct glug_array *ary,
const struct glug_allocator *allocator)
{
return create_iterator(iter, ary, allocator, 0, 1);
}
enum glug_iterator_error glug_array_riter_alloc_custom(struct glug_array_iter **iter, const struct glug_array *ary,
const struct glug_allocator *allocator)
{
return create_iterator(iter, ary, allocator, ary->capacity - 1, -1);
}
void glug_array_iter_free(struct glug_array_iter **iter)
{
glug_free((*iter)->free, (void **)iter);
}
glug_bool glug_array_iter_at_begin(const struct glug_array_iter *iter)
{
return (iter->stride > 0 && iter->pdata == iter->ary->data) ||
(iter->stride < 0 && iter->pdata == last_element(iter->ary));
}
glug_bool glug_array_iter_at_end(const struct glug_array_iter *iter)
{
return (iter->stride > 0 && iter->pdata > last_element(iter->ary)) ||
(iter->stride < 0 && iter->pdata < iter->ary->data);
}
enum glug_iterator_error glug_array_iter_prev(struct glug_array_iter *iter)
{
if (glug_array_iter_at_begin(iter))
return glug_iter_ebounds;
iter->pdata -= iter->stride * iter->ary->config.el_size;
return glug_iter_ok;
}
enum glug_iterator_error glug_array_iter_next(struct glug_array_iter *iter)
{
if (glug_array_iter_at_end(iter))
return glug_iter_ebounds;
iter->pdata += iter->stride * iter->ary->config.el_size;
return glug_iter_ok;
}
enum glug_iterator_error glug_array_iter_val(struct glug_array_iter *iter, void *val)
{
if (glug_array_iter_at_end(iter))
return glug_iter_eatend;
memcpy(val, iter->pdata, iter->ary->config.el_size);
return glug_iter_ok;
}
<file_sep>#ifndef GLUG_TEST_SUITES_H
#define GLUG_TEST_SUITES_H
#include <create_suite.h>
void add_array_suite(suite_creator_t, test_adder_t);
void add_array_iter_suite(suite_creator_t, test_adder_t);
void add_array_range_suite(suite_creator_t, test_adder_t);
void add_bitset_suite(suite_creator_t, test_adder_t);
void add_bitset_iter_suite(suite_creator_t, test_adder_t);
void add_bitset_range_suite(suite_creator_t, test_adder_t);
#endif // GLUG_TEST_SUITES_H
<file_sep>add_subdirectory(cunit/CUnit EXCLUDE_FROM_ALL)
include(cmake/add_glug_test.cmake)
set(TESTED_LIB glug_containers)
find_package(${TESTED_LIB} REQUIRED)
set(TEST_TARGET_NAME ${TESTED_LIB}_test)
add_glug_test(
TARGETNAME
${TEST_TARGET_NAME}
SOURCES
main.c
create_suite.h
counted_alloc.h
counted_alloc.c
suites/suites.h
suites/array.c
suites/array_iter.c
suites/array_range.c
suites/bitset.c
suites/bitset_iter.c
suites/bitset_range.c
INCLUDE_DIRS
${INCLUDE_DIRS}
"."
LINK_LIBS
${TESTED_LIB}
CUnit
)
# create a custom target which builds tests and their dependencies
# (bug in CMake? (https://gitlab.kitware.com/cmake/cmake/issues/8774))
add_custom_target(
check
ALL
DEPENDS
${TEST_TARGET_NAME}
)
# copy the CUnit library and the target lib for the tests
add_custom_command(
TARGET
check POST_BUILD
COMMAND
${CMAKE_COMMAND} -E copy
$<TARGET_FILE:CUnit> ${CMAKE_CURRENT_BINARY_DIR}
COMMAND
${CMAKE_COMMAND} -E copy
$<TARGET_FILE:${TESTED_LIB}> ${CMAKE_CURRENT_BINARY_DIR}
)
<file_sep>#include "bitset_t.h"
#include <glug/containers/bitset/bitset.h>
#include <alloc.h>
#include <defs.h>
#include <stdint.h>
#include <string.h>
static size_t bit_of_byte(size_t bit)
{
return bit % CHARBIT;
}
static size_t bits_to_bytes(size_t bits)
{
return BIT_TO_BYTE(bits - 1) + 1;
}
enum glug_cont_error glug_bitset_alloc(struct glug_bitset **bs, size_t cap)
{
struct glug_allocator conf =
{
.malloc = get_def_malloc(),
.free = get_def_free()
};
return glug_bitset_alloc_custom(bs, cap, &conf);
}
enum glug_cont_error glug_bitset_alloc_custom(struct glug_bitset **bs, size_t cap, const struct glug_allocator *alloc)
{
struct glug_bitset *new_bs;
size_t size;
if (!cap) return glug_cont_einvcap;
if (!alloc || !alloc->malloc || !alloc->free) return glug_cont_einvalloc;
size = bits_to_bytes(cap) + sizeof(struct glug_bitset);
if (!glug_malloc(alloc->malloc, (void **)&new_bs, size))
return glug_cont_enomem;
new_bs->free = alloc->free;
new_bs->capacity = cap;
glug_bitset_clear(new_bs);
*bs = new_bs;
return glug_cont_ok;
}
void glug_bitset_free(struct glug_bitset **bs)
{
glug_free((*bs)->free, (void **)bs);
}
enum glug_cont_error glug_bitset_clone(struct glug_bitset **dst, const struct glug_bitset *src)
{
struct glug_bitset *new_bs;
if (glug_bitset_alloc(&new_bs, src->capacity) != glug_cont_ok)
return glug_cont_enomem;
memcpy(new_bs->data, src->data, bits_to_bytes(src->capacity));
*dst = new_bs;
return glug_cont_ok;
}
enum glug_cont_error glug_bitset_clone_custom(struct glug_bitset **dst, const struct glug_bitset *src,
const struct glug_allocator *alloc)
{
struct glug_bitset *new_bs;
if (!alloc || !alloc->malloc || !alloc->free) return glug_cont_einvalloc;
if (glug_bitset_alloc_custom(&new_bs, src->capacity, alloc) != glug_cont_ok)
return glug_cont_enomem;
memcpy(new_bs->data, src->data, bits_to_bytes(src->capacity));
*dst = new_bs;
return glug_cont_ok;
}
enum glug_cont_error glug_bitset_copy(struct glug_bitset *dst, const struct glug_bitset *src)
{
size_t datasz;
if (dst->capacity != src->capacity) return glug_cont_eincompat;
datasz = bits_to_bytes(src->capacity);
memcpy(dst->data, src->data, datasz);
return glug_cont_ok;
}
size_t glug_bitset_capacity(const struct glug_bitset *bs)
{
return bs->capacity;
}
enum glug_cont_error glug_bitset_set(struct glug_bitset *bs, size_t bit)
{
size_t byte;
if (bit >= bs->capacity) return glug_cont_ebounds;
byte = BIT_TO_BYTE(bit);
bit = bit_of_byte(bit);
bs->data[byte] |= 1 << bit;
return glug_cont_ok;
}
enum glug_cont_error glug_bitset_unset(struct glug_bitset *bs, size_t bit)
{
size_t byte;
if (bit >= bs->capacity) return glug_cont_ebounds;
byte = BIT_TO_BYTE(bit);
bit = bit_of_byte(bit);
bs->data[byte] &= ~(1 << bit);
return glug_cont_ok;
}
enum glug_cont_error glug_bitset_flip(struct glug_bitset *bs, size_t bit)
{
size_t byte;
if (bit >= bs->capacity) return glug_cont_ebounds;
byte = BIT_TO_BYTE(bit);
bit = bit_of_byte(bit);
bs->data[byte] ^= 1 << bit;
return glug_cont_ok;
}
enum glug_cont_error glug_bitset_test(const struct glug_bitset *bs, size_t bit, glug_bool *val)
{
size_t byte;
if (bit >= bs->capacity) return glug_cont_ebounds;
byte = BIT_TO_BYTE(bit);
bit = bit_of_byte(bit);
*val = (bs->data[byte] & (1 << bit)) != 0;
return glug_cont_ok;
}
void glug_bitset_clear(struct glug_bitset *bs)
{
memset(bs->data, 0, bits_to_bytes(bs->capacity));
}
glug_bool glug_bitset_all(const struct glug_bitset *bs)
{
size_t i = BIT_TO_BYTE(bs->capacity);
size_t bits = bit_of_byte(bs->capacity) - 1;
// handle MSB in the valid bit range
while (bits)
{
if (!(bs->data[i] & (1 << bits)))
return false;
bits >>= 1;
}
while (i--)
if (bs->data[i] ^ 0xff)
return false;
return true;
}
glug_bool glug_bitset_none(const struct glug_bitset *bs)
{
size_t i = BIT_TO_BYTE(bs->capacity);
size_t bits = bit_of_byte(bs->capacity) - 1;
// handle MSB in the valid bit range
while (bits)
{
if (bs->data[i] & (1 << bits))
return false;
bits >>= 1;
}
while (i--)
if (bs->data[i] & 0xff)
return false;
return true;
}
glug_bool glug_bitset_any(const struct glug_bitset *bs)
{
size_t i = BIT_TO_BYTE(bs->capacity);
size_t bits = bit_of_byte(bs->capacity) - 1;
// handle MSB in the valid bit range
while (bits)
{
if (bs->data[i] & (1 << bits))
return true;
bits >>= 1;
}
while (i--)
if (bs->data[i] & 0xff)
return true;
return false;
}
<file_sep>#ifndef GLUG_CONT_CONFIG_H
#define GLUG_CONT_CONFIG_H
#include <glug/import.h>
#include <glug/extern.h>
#include <glug/containers/config_t.h>
GLUG_EXTERN_START
GLUG_LIB_API void get_uint8_config(struct glug_cont_config *config);
GLUG_LIB_API void get_int8_config(struct glug_cont_config *config);
GLUG_LIB_API void get_uint16_config(struct glug_cont_config *config);
GLUG_LIB_API void get_int16_config(struct glug_cont_config *config);
GLUG_LIB_API void get_uint32_config(struct glug_cont_config *config);
GLUG_LIB_API void get_int32_config(struct glug_cont_config *config);
GLUG_LIB_API void get_uint64_config(struct glug_cont_config *config);
GLUG_LIB_API void get_int64_config(struct glug_cont_config *config);
GLUG_LIB_API void get_sizet_config(struct glug_cont_config *config);
GLUG_LIB_API void get_float_config(struct glug_cont_config *config);
GLUG_LIB_API void get_double_config(struct glug_cont_config *config);
GLUG_LIB_API void get_long_double_config(struct glug_cont_config *config);
GLUG_LIB_API void get_ptr_config(struct glug_cont_config *config);
GLUG_EXTERN_END
#endif // GLUG_CONT_CONFIG_H
<file_sep>#ifndef GLUG_ARRAY_H
#define GLUG_ARRAY_H
#include "array_t.h"
#include <glug/import.h>
#include <glug/extern.h>
#include <glug/containers/error_t.h>
#include <glug/bool.h>
#include <stddef.h>
GLUG_EXTERN_START
struct glug_allocator;
struct glug_cont_config;
GLUG_LIB_API enum glug_cont_error glug_array_alloc(struct glug_array **ary, size_t cap,
const struct glug_cont_config *config);
GLUG_LIB_API enum glug_cont_error glug_array_alloc_custom(struct glug_array **ary, size_t cap,
const struct glug_cont_config *config,
const struct glug_allocator *allocator);
GLUG_LIB_API void glug_array_free(struct glug_array **ary);
GLUG_LIB_API enum glug_cont_error glug_array_clone(struct glug_array **dst, const struct glug_array *src);
GLUG_LIB_API enum glug_cont_error glug_array_clone_custom(struct glug_array **dst, const struct glug_array *src,
const struct glug_allocator *allocator);
GLUG_LIB_API enum glug_cont_error glug_array_copy(struct glug_array *dst, const struct glug_array *src);
GLUG_LIB_API void glug_array_get_config(const struct glug_array *ary, struct glug_cont_config *config);
GLUG_LIB_API size_t glug_array_capacity(const struct glug_array *ary);
GLUG_LIB_API size_t glug_array_elem_size(const struct glug_array *ary);
GLUG_LIB_API enum glug_cont_error glug_array_at(const struct glug_array *ary, size_t idx, void *val);
GLUG_LIB_API enum glug_cont_error glug_array_set(struct glug_array *ary, size_t idx, void *new_val);
GLUG_LIB_API enum glug_cont_error glug_array_insert(struct glug_array *ary, size_t idx, void *new_val);
GLUG_LIB_API enum glug_cont_error glug_array_splice(struct glug_array *ary, size_t idx);
GLUG_LIB_API enum glug_cont_error glug_array_swap(struct glug_array *ary, size_t idx1, size_t idx2);
GLUG_EXTERN_END
#endif // GLUG_ARRAY_H
<file_sep>#ifndef GLUG_ALLOC_H
#define GLUG_ALLOC_H
#include <glug/containers/alloc_t.h>
#include <glug/containers/error_t.h>
#include <glug/bool.h>
#include <stddef.h>
GLUG_LIB_LOCAL glug_malloc_t get_def_malloc (void);
GLUG_LIB_LOCAL glug_realloc_t get_def_realloc(void);
GLUG_LIB_LOCAL glug_free_t get_def_free (void);
GLUG_LIB_LOCAL glug_bool glug_malloc (glug_malloc_t malloc_f, void **block, size_t sz);
GLUG_LIB_LOCAL glug_bool glug_realloc(glug_realloc_t realloc_f, void **block, size_t sz);
GLUG_LIB_LOCAL void glug_free (glug_free_t free_f, void **block);
#endif // GLUG_ALLOC_H
|
3ac0b264892779851f60088dc052c09fed2ffb28
|
[
"Markdown",
"C",
"CMake"
] | 40
|
C
|
libglug/datastructs
|
4f4675268f7cd048ae6b9684273a7f460ae80644
|
2f8f50ee153bc00a56ff1337f88610f2bbdec084
|
refs/heads/master
|
<file_sep># Sfevy
Sockets for everyone - Easy sockets within python, no stress networking.
### What is Sfevy?
Sfevy is an simple wrapper for the python sockets library. Sfevy was created so that anyone can simply create a networking application in python.
Although it is a
### Requirements
- Python 3.x.x
### Features
- Made for quick and easy usage
- Threaded networking
- Made for beginners, but scaleable for more advanced users
### Setting up Sfevy
Start by cloning Sfevy from github
[Clone Sfevy](https://github.com/TheVoxcraft/Sfevy)
Then continue by importing Sfevy into your project
```python
import Sfevy
```
### Documentation
Start by initializing Sfevy
```python
sf = Sfevy.sockets
```
If you have the the proper parameters, initialize this way
```python
sf = Sfevy.sockets(HOST, PORT, IP)
```
- Host being the server or what you'll be trying to connect to
- IP being your ip, either local or external
- Port being the port you want to communicate through
These parameters can be later changed at any point, manually or through the Sfevy methods
```python
sf.HOST = '172.16.31.10'
sf.PORT = 1234
sf.IP = '127.0.0.1'
```
Or
```python
sf.setHost('1.2.3.4', 1234) # changing the host you'll communicate out from and the port
sf.setAddress('1.2.3.4', 1234) # changing the ip you'll communicate back through and the port
```
You can easily send data through Sfevy using the `sendData()` function. This is threaded
Call this with the proper parameters: `data` and `protocol`. Also some optional parameters `buffer` and `raw`
- Data is what you want to send to the host ip, this could be for exampel text or binary.
- Protocol is what internet protocol you would like to use, either `UDP` or `TCP`. Example: `Protocol.TCP`
- If you don't know which to use - use this as referance:
[Learn more about TCP and UDP](http://www.diffen.com/difference/TCP_vs_UDP)
- Buffer is how much data you want to send. Buffer is set to `1024` by default.
- Raw is a boolean, for if you want to send text, or raw data with no encoding. Raw is set to `False` by default.
Example:
```python
sf.sendData('Hello Server!', Protocol.UDP) # or ('Hello Server!', Protocol.UDP, buffer=1024, raw=False)
```
You can quickly also set up python to listen for traffic heading it's way
This is done by using the `startListening` method which starts listening for data. This is also threaded
You can call this with the following parameters: `dataHandler` and `protocol`.This also has the optional parameters `buffer` and `raw`.
For the listening function you need a function that handles the data when it comes.
- The Data Handler is the name of your function that handles the data when it comes in. Your function must have two parameters `data` for the incoming data, and `addr` for the address the data is coming from.
```python
myDataFunc(data, addr):
print( "Data is %s, coming from %s" % (str(data), str(addr)) ) # assuming the data isn't raw
sf.startListening('myDataFunc', Sfevy.Protocol.UDP)
```
- Protocol is what internet protocol you would like to use, either `UDP` or `TCP`. Example: `Protocol.UDP`
- If you don't know which to use - use this as referance:
[Learn more about TCP and UDP](http://www.diffen.com/difference/TCP_vs_UDP)
- Buffer is how much data you want to send. Buffer is set to `1024` by default.
- Raw is a boolean, for if you want to send text, or raw data with no encoding. Raw is set to `False` by default.
Example:
```python
sf.startListening('myDataFunc', Protocol.UDP) # extended: ('myDataFunc', Sfevy.Protocol.UDP, buffer=1024, raw=False)
```
#### UDP Echo Client/Server Example:
- Client:
```python
import Sfevy
import random
import time
Protocol = Sfevy.Protocol
sf = Sfevy.sockets('172.16.31.10', 1234) # 172.16.31.10 being the server ip
def reciveDataFunc(data, addr):
print(data)
sf.startListening('reciveDataFunc', Protocol.UDP)
while 1:
time.sleep(2)
dataToSend = str( random.randint(0,10000) )
sf.sendData(dataToSend, Protocol.UDP) # sends random number to server
```
- Server:
```python
import Sfevy
import time
Protocol = Sfevy.Protocol
sf = Sfevy.sockets('0.0.0.0', 1234, '127.0.0.1') # host ip doesn't matter on the server since it's not going to connect
def echoFunc(data, addr):
sf.sendData(data, addr) # send same data back
sf.startListening('echoFunc', Protocol.UDP)
while 1:
time.sleep(5)
print('waiting for data...')
```
<file_sep># Sfevy - Sockets for everyone
# by Vox
# Copyright (c) 2017 VOX
# MIT LICENSE
import socket
import threading
class Protocol():
TCP = 1
UDP = 2
class sockets:
def __init__(self, host, port, ip=socket.gethostname()):
self.listening = False
self.IP = ip
self.HOST = host
self.PORT = port
def setHost(host, port):
self.HOST = host
self.PORT = port
def setAddress(self, ip, port):
self.IP = ip
self.PORT = port
def sendData(self, data, pcol, raw=False):
if raw == False:
data = bytes(data, "utf-8")
if pcol == Protocol.TCP:
threading.Thread(target=sockets._sendTCPThread, args=(self, data)).start()
elif pcol == Protocol.UDP:
threading.Thread(target=sockets._sendUDPThread, args=(self, data)).start()
else:
print("error: Not avaliable protocol.")
def _sendUDPThread(self, data):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(data, (self.HOST, self.PORT))
sock.close()
def _sendTCPThread(self, data):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP
sock.connect((self.HOST, self.PORT))
sock.sendall(data)
sock.close()
def startListening(self, dataHandler, pcol, buffer=1024, raw=False):
if(self.listening == False and pcol == Protocol.UDP):
threading.Thread(target=sockets._listenUDP, args=(self, dataHandler, buffer, raw)).start()
elif(self.listening == False and pcol == Protocol.TCP):
threading.Thread(target=sockets._listenTCP, args=(self, dataHandler, buffer, raw)).start()
else:
print("error: Already listening.")
def _listenUDP(self, dataHandler, buffer, raw):
while 1:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((self.IP, self.PORT))
data, addr = sock.recvfrom(buffer)
if not raw:
gData = data.decode()
gAddr = addr[0]
threading.Thread(target=sockets._gotData, args=(gData,gAddr,dataHandler)).start()
sock.close()
def _listenTCP(self, dataHandler, buffer, raw):
while 1:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((self.IP, self.PORT))
sock.listen(5)
connection, client_address = sock.accept()
while True:
data = connection.recv(buffer)
if data:
if not raw:
data = data.decode()
threading.Thread(target=sockets._gotData, args=(data,client_address,dataHandler)).start()
else:
break
connection.close()
sock.close()
def _gotData(data, addr, callTarget):
## Call user function here
main_module = __import__('__main__')
callFunc = getattr(main_module, callTarget)
callFunc(data, addr)
|
d63e9858487b89b86abdb04a7422d3541a60bdf7
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
TheVoxcraft/Sfevy
|
e78d3e60444d5bfad43288e227c2b788684149f6
|
00622a3110db5de13cf03ffa13a6d3ca1b42bc60
|
refs/heads/master
|
<file_sep>package mx.com.itam.adsi.ejercicio;
import org.apache.log4j.Logger;
/**
*Clase Nodo
*
*Liga Nodos para crear una estructura de lista
*@author <NAME> 158228
*/
public class Node {
/**
*registra los métodos de la clase
*/
private final static Logger LOG = Logger.getLogger(Node.class);
/**
*información que guarda el nodo
*/
private String data;
/**
*siguiente nodo ligado
*/
private Node next;
/**
*Constructor que guarda data en el Nodo
*/
public Node(String data){
this.data = data;
}
/**
*Invierte la lista y regresa el último nodo
*
*No regresa nada
*/
public Node gus(){
if(next == null)
return this;
Node otro = next;
next = null;
Node tavo = otro.gus();
otro.next = this;
return tavo;
}
/**
*Imprime en la consola la secuencia de Nodos que
*componen a esta lista. Por ejemplo, para la lista
*que devuelve el método "build", la invocación de
*este método escribe en la consola:
*
* A-->B-->C-->D-->E-->F-->
*
*Lo anterior sería lo que se visualiza en la consola
*justo después de ejecutar las siguientes dos líneas:
* Node a = build();
* a.prn();
*
*/
public void prn(){
Node imprime = this;
do{
System.out.print(imprime.data + "-->");
}while(imprime.next != null)
}
}
|
7619526ec2035a30c838c87007ebf68553c97e12
|
[
"Java"
] | 1
|
Java
|
adsi-itam-27/Examen_2
|
0ef95711b9a67a44cfec91147924a61d8b534c8f
|
ae1639115a1cf6430d1f0a9b5fb8126cf9696d74
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
import pexpect
from getpass import getpass
import re
import time
import sys
def main():
username='pyclass'
#ip_addr=raw_input("enter ip: ")
ip_addr='172.16.31.10'
port = 22
password = getpass()
ssh_conn = pexpect.spawn('ssh -l {} {} -p {}'.format(username, ip_addr, port))
ssh_conn.timeout=3
ssh_conn.expect('ssword:')
ssh_conn.sendline(password) # automatically adds newline
ssh_conn.expect('#')
ssh_conn.sendline('terminal length 0')
ssh_conn.expect('#')
#print ssh_conn.before
#print "sending cmd...\n"
ssh_conn.sendline('show run | inc logging')
ssh_conn.expect('#')
print ssh_conn.before
ssh_conn.sendline('config term')
ssh_conn.expect('#')
ssh_conn.sendline('logging buffered 11223')
ssh_conn.expect('#')
ssh_conn.sendline('end')
ssh_conn.expect('#')
ssh_conn.sendline('wr')
ssh_conn.expect('#')
ssh_conn.sendline('show run | inc logging')
ssh_conn.expect('#')
print ssh_conn.before
if __name__ == "__main__":
main()
<file_sep>''' watchconfigsave.py
Watch router for config changes
and send email alert
save data in file, can be called from cron
'''
from snmp_helper import snmp_get_oid_v3,snmp_extract
import time
import pickle
import yaml
import json
from email_helper import send_mail
def debug(self,msg):
if self.debugflag:
print("Debug: " + msg)
ip='172.16.58.3'
port=161
devicename='pynet-rtr2'
a_user='pysnmp'
auth_key='galileo1'
encrypt_key='galileo1'
statefileprefix='watchconfigstate'
to='<EMAIL>'
fromwho='<EMAIL>'
#filetype='pickle'
#filetype='yaml'
filetype='json'
device=(ip,port)
snmp_user=(a_user, auth_key, encrypt_key)
oidlist=[
('ccmHistoryRunningLastChanged','1.3.6.1.4.1.9.9.43.1.1.1.0'),
('ccmHistoryRunningLastSaved','1.3.6.1.4.1.9.9.43.1.1.2.0' ),
('ccmHistoryStartupLastChanged','1.3.6.1.4.1.9.9.43.1.1.3.0')
]
##polltime=100 # seconds (typ 300 = 5 min)
count=len(oidlist)
currentvalue=[]
previousvalue=[]
def readfile(statefileprefix):
try:
if filetype == 'pickle':
f=open(statefileprefix + ".pk1","rb")
previousvalue=pickle.load(f)
elif filetype == 'yaml':
f=open(statefileprefix + ".yaml","r")
previousvalue=yaml.load(f)
else:
f=open(statefileprefix + ".json","r")
previousvalue=json.load(f)
except IOError:
previousvalue=[]
return previousvalue
def writefile(statefileprefix,previousvalue):
if filetype == 'pickle':
f=open(statefileprefix + ".pk1","wb")
pickle.dump(previousvalue,f)
elif filetype == 'yaml':
f=open(statefileprefix + ".yaml","w")
f.write(yaml.dump(previousvalue, default_flow_style=False))
else:
f=open(statefileprefix + ".json","w")
json.dump(previousvalue,f)
return
previousvalue=readfile(statefileprefix)
print('time {}'.format(time.strftime('%Y/%m/%d %H:%M:%S')))
print('readfile')
print previousvalue
for i in range(count):
oid=oidlist[i][1]
snmp_data=snmp_get_oid_v3(device,snmp_user, oid)
data=snmp_extract(snmp_data)
##print oidlist[i][0] + " " + data
if len(currentvalue) <= i:
##print('len(currentvalue) {}'.format(len(currentvalue)))
currentvalue.append(data)
else:
##print('len(currentvalue) {}'.format(len(currentvalue)))
currentvalue[i]=data
# check for change
##print('len(previousvalue) {}'.format(len(previousvalue)))
##print('i {}'.format(i))
##if len(previousvalue) > i:
##print('data {} prev {}'.format(data,previousvalue[i]))
##if data !=previousvalue[i]:
##print "CHANGED"
if not ( len(previousvalue) <= i or data == previousvalue[i] ):
subject="router config changed"
text='{} value of {} changed from {} to {}'.format(
time.strftime('%Y/%m/%d %H:%M:%S'),
oidlist[i][0],
previousvalue[i],data)
print(text)
if send_mail(to,subject,text,fromwho):
print 'email sent ok'
break # only send email on first value that changed
previousvalue=currentvalue[:] # make copy of list
# (without [:] it would beanother pointer to same list)
print "writefile"
print previousvalue
writefile(statefileprefix,previousvalue)
# no sleep, writing file instead
#time.sleep(polltime)
<file_sep>#!/usr/bin/env python
import pexpect
from getpass import getpass
import re
import time
import sys
def main():
username='pyclass'
#ip_addr=raw_input("enter ip: ")
ip_addr='172.16.58.3'
port = 22
password = getpass()
ssh_conn = pexpect.spawn('ssh -l {} {} -p {}'.format(username, ip_addr, port))
ssh_conn.logfile = sys.stdout # for debugging
ssh_conn.timeout=3
ssh_conn.expect('ssword:')
ssh_conn.sendline(password) # automatically adds newline
ssh_conn.expect('#')
ssh_conn.sendline('terminal length 0')
ssh_conn.expect('#')
ssh_conn.sendline('show ip int brief')
ssh_conn.expect('#')
print ssh_conn.before
if __name__ == "__main__":
main()
<file_sep>''' watchconfig.py
Watch router for config changes
and send email alert
'''
from snmp_helper import snmp_get_oid_v3,snmp_extract
import time
def debug(self,msg):
if self.debugflag:
print("Debug: " + msg)
ip='172.16.17.32'
port=161
devicename='pynet-rtr2'
device=(ip,port)
a_user='pysnmp'
auth_key='galileo1'
encrypt_key='galileo1'
snmp_user=(a_user, auth_key, encrypt_key)
oidlist=[
('ccmHistoryRunningLastChanged','1.3.6.1.4.192.168.127.12.1.1.1.0'),
('ccmHistoryRunningLastSaved','1.3.6.1.4.192.168.127.12.1.1.2.0' ),
('ccmHistoryStartupLastChanged','1.3.6.1.4.192.168.127.12.1.1.3.0')
]
polltime=100 # seconds (typ 300 = 5 min)
count=len(oidlist)
currentvalue=[]
previousvalue=[]
found=False
while True:
print('time {}'.format(time.strftime('%Y/%m/%d %H:%M:%S')))
for i in range(count):
oid=oidlist[i][1]
snmp_data=snmp_get_oid_v3(device,snmp_user, oid)
data=snmp_extract(snmp_data)
##print oidlist[i][0] + " " + data
if len(currentvalue) <= i:
##print('len(currentvalue) {}'.format(len(currentvalue)))
currentvalue.append(data)
else:
##print('len(currentvalue) {}'.format(len(currentvalue)))
currentvalue[i]=data
# check for change
##print('len(previousvalue) {}'.format(len(previousvalue)))
##print('i {}'.format(i))
##if len(previousvalue) > i:
##print('data {} prev {}'.format(data,previousvalue[i]))
##if data !=previousvalue[i]:
##print "CHANGED"
if not ( len(previousvalue) <= i or data == previousvalue[i] ):
print('{} value of {} changed from {} to {}'.format(
time.strftime('%Y/%m/%d %H:%M:%S'),
oidlist[i][0],
previousvalue[i],data))
found=True
break # from 'for', but really want to exit 'while'
if found:
break # break out another layer to exit
previousvalue=currentvalue[:] # make copy of list
# (without [:] it would beanother pointer to same list)
print previousvalue
time.sleep(polltime)
<file_sep># ciscoread_w1e8.py
from ciscoconfparse import CiscoConfParse
cisco_cfg=CiscoConfParse("cisco_ipsec.txt")
crypto = cisco_cfg.find_objects(r"^crypto map CRYPTO")
for i in crypto:
print i.text
for j in i.all_children:
print j.text
<file_sep># pynet_testz - Python and Ansible class 2017/07
<file_sep># ciscoread_w1e8.py
from ciscoconfparse import CiscoConfParse
import re
cisco_cfg=CiscoConfParse("cisco_ipsec.txt")
crypto = cisco_cfg.find_objects_wo_child(parentspec=r"^crypto map CRYPTO", childspec=r"transform-set AES")
for i in crypto:
#print i.text
for j in i.all_children:
#print j.text
match=re.search(r"set transform-set (.*)$",j.text)
if match:
encrypt=match.group(1)
#print "alt----"
print "{0} -uses- {1}".format(i.text.strip(),encrypt)
<file_sep>#!/usr/bin/env python
''' paramiko_w4e2.py '''
import paramiko
from getpass import getpass
import time
ip_addr = '172.16.17.32'
username='pyclass'
password=getpass()
port=22
remote_conn_pre = paramiko.SSHClient() # create object
remote_conn_pre.load_system_host_keys() # reads .ssh/known_hosts
remote_conn_pre.connect(ip_addr, username=username, password=<PASSWORD>, look_for_keys=False,allow_agent=False, port=port) # make outer ssh connection
remote_conn = remote_conn_pre.invoke_shell() # ssh session inside the connection
remote_conn.send("terminal length 0\n")
time.sleep(1)
remote_conn.send("show run | inc logging\n")
time.sleep(1)
outp=remote_conn.recv(500)
print outp
remote_conn.send("config term\n")
time.sleep(1)
remote_conn.send("logging buffered 10101\n")
time.sleep(1)
remote_conn.send("end\n")
time.sleep(1)
remote_conn.send("wr\n")
time.sleep(10)
remote_conn.send("show run | inc logging\n")
time.sleep(1)
outp=remote_conn.recv(500)
print outp
remote_conn.close()
remote_conn_pre.close()
<file_sep>#!/usr/bin/env python
from netmiko import ConnectHandler
from getpass import getpass
password='<PASSWORD>'
pynet1={'device_type': 'cisco_ios',
'ip':'172.16.17.32',
'username':'pyclass',
'password':<PASSWORD>
}
pynet2={'device_type': 'cisco_ios',
'ip':'172.16.58.3',
'username':'pyclass',
'password':<PASSWORD>
}
juniper_srx={'device_type': 'juniper',
'ip':'172.16.58.3',
'username':'pyclass',
'password':<PASSWORD>
}
for svr in [ pynet1, pynet2, juniper_srx]:
conn=ConnectHandler(**svr)
#conn.config_mode()
outp=conn.send_command("show arp")
print svr.get("ip")
print outp
<file_sep>
''' telnet_rtr.py '''
import telnetlib
import time
ip_addr='172.16.17.32'
TELNET_PORT=23
TELNET_TIMEOUT=6
username='pyclass'
password='<PASSWORD>'
cmd='show ip int brief'
conn=telnetlib.Telnet(ip_addr, TELNET_PORT, TELNET_TIMEOUT)
out=conn.read_until("sername:", TELNET_TIMEOUT)
conn.write(username + '\n')
out=conn.read_until("ssword:", TELNET_TIMEOUT)
conn.write(password + '\n')
out=conn.read_until("#", TELNET_TIMEOUT)
conn.write(cmd + '\n')
out=conn.read_until("#", TELNET_TIMEOUT)
print out
conn.close
<file_sep>''' graphdata.py
graph the data collected in watchdata.py
used by programs like watchsnmp.py
auto-gen the x axis from the timestamps
'''
''' UPDATE TO USE watchdata TO READ THE FILE '''
import pickle
import time
import pygal
import json
def debug(msg):
if debugflag:
print("Debug: " + msg)
filename='snmpdata.dat'
outfile=filename + ".svg"
debugflag=True
jsonfile='graphdata.json'
# open json file
f2=open(jsonfile,"w")
# read file
try:
f=open(filename,'rb')
except IOError:
raise IOError('error - file is not readable')
try:
var_list=pickle.load(f)
diff=pickle.load(f)
initial=pickle.load(f)
except EOFError:
raise ValueError('error - file exists but no proper header')
data=[]
while True:
try:
datarow=pickle.load(f)
data.append(datarow)
except EOFError:
break
# calc x axis labels as hours and minutes
xlabels=[]
for datarow in data:
timestamp=datarow[0]
##print timestamp
rowtimestruct=time.strptime(timestamp,'%Y/%m/%d %H:%M:%S')
rowhrmin=time.strftime('%H:%M',rowtimestruct)
##print rowhrmin
xlabels.append(rowhrmin)
line_chart = pygal.Line()
title='Input/Output Packets and Bytes'
line_chart.title = title
json.dump(title,f2)
debug('xlabels: {}'.format(xlabels))
json.dump(xlabels,f2)
line_chart.x_labels = xlabels
# get data for each variable
# only numeric data that can be graphed
for i in [1]: ## debug
##for i in range(len(var_list)):
debug('variable number {}'.format(i))
varobj=var_list[i]
if type(varobj) == 'str':
varname=varobj
else:
varname=varobj[0]
debug('varname {}'.format(varname))
numflag=True
graphdata=[]
for datarow in data:
datastring=datarow[i+1] # offset by one due to timestamp
##debug('varnum {}, varname {}, datastring {}'.format(i,varname,datastring))
try:
value=float(datastring)
value=(float(datastring) - 1949433248) / 1000 ## debug
except ValueError:
numflag=False
debug('non-numeric data, skipping: {}'.format(datastring))
break
graphdata.append(value)
if numflag:
debug('graphdata: {}'.format(graphdata))
line_chart(varname, graphdata)
json.dump(varname,f2)
json.dump(graphdata,f2)
# generate graph
line_chart.render_to_file(outfile)
print "download and view " + outfile + " in web browser"
<file_sep>#!/usr/bin/env python
import pexpect
from getpass import getpass
import re
import time
import sys
def main():
username='pyclass'
ip_addr=raw_input("enter ip: ")
port = 22
password = getpass()
ssh_conn = pexpect.spawn('ssh -l {} {} -p {}'.format(username, ip_addr, port))
ssh_conn.logfile = sys.stdout # for debugging
ssh_conn.timeout=3
ssh_conn.expect('ssword:')
ssh_conn.sendline(password) # automatically adds newline
ssh_conn.expect('#')
ssh_conn.sendline('terminal length 0')
ssh_conn.expect('#')
ssh_conn.sendline('show version')
# the "re.MULTILINE" tells it to match any line in the string
# otherwise ^ would be start of string instead of line
pattern = re.compile(r'^Lic.*DI:.*$', re.MULTILINE)
ssh_conn.expect(pattern)
#print "before " + ssh_conn.before # what it saw before the last expect
#print "after " + ssh_conn.after # what matched the last expect
time.sleep(10)
if __name__ == "__main__":
main()
<file_sep>#!/usr/bin/env python
# test_telnet.py
import telnetlib
import time
import socket
import sys
TELNET_PORT=23
TELNET_TIMEOUT=6
def telnet_connect(ip_addr, TELNET_PORT, TELNET_TIMEOUT):
try:
return telnetlib.Telnet(ip_addr, TELNET_PORT, TELNET_TIMEOUT)
except socket.timeout:
sys.exit("Connection timed out")
def login(remote_conn, username, password):
output=remote_conn.read_until("sername:", TELNET_TIMEOUT)
remote_conn.write(username + '\n')
output += remote_conn.read_until("ssword:", TELNET_TIMEOUT)
remote_conn.write(password + '\n')
return output
def send_command(remote_conn, cmd):
cmd=cmd.rstrip() # remove trailing linefeed if any
remote_conn.write(cmd + '\n')
time.sleep(1)
return remote_conn.read_very_eager()
def main():
ip_addr='172.16.31.10'
username='pyclass'
password='<PASSWORD>'
remote_conn=telnet_connect(ip_addr, TELNET_PORT, TELNET_TIMEOUT)
output=login(remote_conn, username, password)
print output
time.sleep(1)
output=remote_conn.read_very_eager()
print output
output=send_command(remote_conn, 'terminal length 0')
print output
output=send_command(remote_conn, 'show version')
print output
remote_conn.close
if __name__ == '__main__':
main()
<file_sep>''' watchsnmp.py
set snmp device(s) to monitor
set snmp oid list to monitor
get snmp info from devices using oid list
save snmp data
read saved snmp data
diff from prev smp data
graph snmp data
send alert email
'''
from snmp_helper import snmp_get_oid_v3,snmp_extract
from watchdata import WatchData
import time
from pprint import pprint
ip='172.16.17.32'
port=161
devicename='pynet-rtr1'
device=(ip,port)
a_user='pysnmp'
auth_key='galileo1'
encrypt_key='galileo1'
snmp_user=(a_user, auth_key, encrypt_key)
filename='snmpdata.dat'
polltime=300
endtime=3600
#debugflag=False
debugflag=True
oidlist=[
('ifDescr_fa4', '1.3.6.1.2.1.2.2.1.2.5'),
('ifInOctets_fa4', '1.3.6.1.2.1.2.2.1.10.5'),
('ifInUcastPkts_fa4', '1.3.6.1.2.1.2.2.1.11.5'),
('ifOutOctets_fa4', '1.3.6.1.2.1.2.2.1.16.5'),
('ifOutUcastPkts_fa4', '1.3.6.1.2.1.2.2.1.17.5')
]
''' data structures:
oid_nums [oid1, oid2, ...]
oid_names [oid1name, oid2name, ...]
oid_sets [ [oid1name, oid1], [oid2name, oid2], ...]
Uses the "WatchData" class
polltime (single value in seconds)
device IP list
Note that first reading is the initial values,
not graphed or reported if using differences
'''
def debug(msg):
if debugflag:
##print type(msg)
print("Debug: " + msg)
watchobj=WatchData(filename,oidlist,debugflag=debugflag)
# polling loop
timer=0
while timer <= endtime:
# gather data
valuelist=[]
for (oidname,oid) in oidlist:
snmp_data=snmp_get_oid_v3(device,snmp_user, oid)
data=snmp_extract(snmp_data)
debug( "valuelist before: {}".format(valuelist))
debug( oidname + " " + oid + " " + data)
valuelist.append(data)
watchobj.add(valuelist)
time.sleep(polltime)
timer += polltime
##print type(timer)
debug('timer: {}'.format(timer))
<file_sep># ciscoread_w1e8.py
from ciscoconfparse import CiscoConfParse
cisco_cfg=CiscoConfParse("cisco_ipsec.txt")
crypto = cisco_cfg.find_objects_w_child(parentspec=r"^crypto map CRYPTO", childspec=r"pfs group2")
for i in crypto:
print i.text
for j in i.all_children:
print j.text
<file_sep>from my_func import my_hello
my_hello()
<file_sep>''' watchdata.py
read and write timestamped data to file in python pickle format
intended for monitoring
'''
import pickle
import sys
import time
import tempfile
import os
class WatchData(object):
''' data structures:
var_list [var1, var2, ...]
times [time1, time2, ...]
data (list of lists)
[ [var1 data at time1, data at time2, ...],
[var2 data at time1, data at time2, ...],
...]
saved in file (appended) as:
var_list
diff
timestamp, var1 data, var2 data, ...
Note that first line is the initial values,
not graphed or reported if using differences
'''
def debug(self,msg):
if self.debugflag:
print("Debug: " + msg)
def __init__(self, filename, var_list=None, initial='', diff='no', debugflag=False):
''' if file has not been initialized, then var_list is required
initial is an optional list of initial (previous) values,
prefixed with its timestamp (timestamp can be empty):
[ timestamp, var1 initial value, var2 initial value, ...]
used if carrying over from another log file,
so that each log file can be stand-alone.
"diff" is one of:
"no" use values directly
"diff" use difference between current and previous value
"change" highlight any change in value
"diff" can be a single value or a list of values, one per var
if any are not "no",
then either "initial" or the first reading
will be used as the comparison, and not reported or graphed
4 cases:
1. No file, no var_list, error
2. No file, var_list, create file
3. file exists, no var list, read var_list from file
4. file exists, var_list, var_list must match file
'''
self.debugflag=debugflag
# default values if not in arguments
data=[]
# try to read any existing file
fileexists=False
try:
f=open(filename,'rb')
fileexists=True
except IOError:
self.debug( 'notice - file does not exist yet')
if fileexists:
self.debug( 'try to read file header')
try:
file_var_list=pickle.load(f)
self.debug('file_var_list {}'.format(file_var_list))
file_diff=pickle.load(f)
self.debug('file_diff {}'.format(file_diff))
file_initial=pickle.load(f)
self.debug('file_initial {}'.format(file_initial))
except EOFError:
raise ValueError('error - file exists but no proper header')
file_data=[]
while True:
try:
datarow=pickle.load(f)
file_data.append(datarow)
self.debug('read data row {}'.format(datarow))
except EOFError:
break
self.debug('total data from file {}'.format(file_data))
if var_list:
# case 4. file exists, var_list, var_list must match file
if file_var_list != var_list:
raise ValueError('error - file exists, but variable list does not match')
else:
# case 3. file exists, no var list, use var_list from file
if file_initial:
print 'warning - file exists, initial list ignored'
var_list=file_var_list
diff=file_diff
initial=file_initial
# in either case, data comes from file
data=file_data
# file has been read, now switch to write append
self.debug('close file and reopen for append')
f.close()
try:
f=open(filename,'ab')
except IOError:
raise IOError('error - file is not writable')
else: # file does not exist
if not var_list:
# case 1. No file, no var_list, error
raise ValueError('error - file not found and no variable list given')
else:
# case 2. No file, var_list, create file
self.debug('create new file')
f=open(filename,'wb')
pickle.dump(var_list,f)
pickle.dump(diff,f)
pickle.dump(initial,f)
f.flush()
# set object variables last
self.filename=filename
self.var_list= var_list
self.initial=initial
self.diff=diff
self.data=data
self.f=f
def __del__(self):
try:
self.f.close()
except:
# ok if it was never created
pass
def add(self, datarow, timestamp=None):
if not timestamp:
timestamp=time.strftime('%Y/%m/%d %H:%M:%S')
datarow.insert(0,timestamp)
pickle.dump(datarow,self.f)
self.f.flush()
self.data.append(datarow)
self.debug('added row {}'.format(datarow))
def get_vars(self):
return self.var_list
def get_diff(self):
return self.diff
def get_initial(self):
return self.initial
def get_data(self):
return self.data
def test():
''' test of WatchData '''
# create random filename
# by creating and deleting a tempfile
f1=tempfile.NamedTemporaryFile(suffix='pk1',delete=False)
filename1=f1.name
f1.close()
os.remove(filename1)
# now use the filename for a new file
varlist=['name','age']
mywatch=WatchData(filename1,varlist,debugflag=True)
print("vars {}".format(mywatch.get_vars()))
print("diff default {}".format(mywatch.get_diff()))
print("initial default {}".format(mywatch.get_initial()))
print("data should be empty: {}".format(mywatch.get_data()))
mywatch.add(['fred',24])
print("data with one row {}".format(mywatch.get_data()))
mywatch.add(['sam',16])
print("data with two rows {}".format(mywatch.get_data()))
# now close, move to new name
print('close and reopen with new name')
mywatch.f.close()
filename2=filename1 + "x"
os.rename(filename1, filename2)
# open existing file
mywatch2=WatchData(filename2,debugflag=True)
print("vars {}".format(mywatch2.get_vars()))
print("diff default {}".format(mywatch2.get_diff()))
print("initial default {}".format(mywatch2.get_initial()))
print("data should have two rows {}".format(mywatch2.get_data()))
mywatch2.add(['jo',3])
print("data with three rows {}".format(mywatch2.get_data()))
# delete temp file
os.remove(filename2)
if __name__ == '__main__':
test()
<file_sep>#!/usr/bin/env python
'''
Convert to class
Write a script that connects to the lab pynet-rtr1, logins, and executes the
'show ip int brief' command.
'''
#import telnetlib
from telnetlib import Telnet
import time
import socket
import sys
import getpass
TELNET_PORT = 23
TELNET_TIMEOUT = 6
class MyTelnet(Telnet):
def __init__(self,host=None, port=TELNET_PORT, timeout=TELNET_TIMEOUT):
Telnet.__init__(self,host,port,timeout)
def send_command(self, cmd):
'''
Send a command down the telnet channel
Return the response
'''
cmd = cmd.rstrip()
self.write(cmd + '\n')
time.sleep(1)
return self.read_very_eager()
def login(self, username, password):
'''
Login to network device
'''
output = self.read_until("sername:", TELNET_TIMEOUT)
self.write(username + '\n')
output += self.read_until("ssword:", TELNET_TIMEOUT)
self.write(password + '\n')
return output
def disable_paging(self, paging_cmd='terminal length 0'):
'''
Disable the paging of output (i.e. --More--)
'''
return self.send_command(paging_cmd)
def telnet_connect(self, ip_addr):
'''
Establish telnet connection
'''
try:
return Telnet(ip_addr, TELNET_PORT, TELNET_TIMEOUT)
except socket.timeout:
sys.exit("Connection timed-out")
def main():
'''
Write a script that connects to the lab pynet-rtr1, logins, and executes the
'show ip int brief' command.
'''
ip_addr = raw_input("IP address: ")
ip_addr = ip_addr.strip()
username = 'pyclass'
password = <PASSWORD>()
remote_conn=MyTelnet(ip_addr)
#remote_conn.telnet_connect(ip_addr)
output = remote_conn.login(username, password)
time.sleep(1)
remote_conn.read_very_eager()
remote_conn.disable_paging()
output = remote_conn.send_command('show ip int brief')
print "\n\n"
print output
print "\n\n"
remote_conn.close()
if __name__ == "__main__":
main()
<file_sep>#!/usr/bin/env python
''' paramiko_w4e1.py '''
import paramiko
from getpass import getpass
import time
ip_addr = '192.168.127.12'
username='pyclass'
password=getpass()
port=22
remote_conn_pre = paramiko.SSHClient() # create object
remote_conn_pre.load_system_host_keys() # reads .ssh/known_hosts
remote_conn_pre.connect(ip_addr, username=username, password=<PASSWORD>, look_for_keys=False,allow_agent=False, port=port) # make outer ssh connection
remote_conn = remote_conn_pre.invoke_shell() # ssh session inside the connection
remote_conn.send("terminal length 0\n")
time.sleep(1)
char_cnt=remote_conn.send("show version\n")
time.sleep(3)
outp=remote_conn.recv(65535)
print outp
remote_conn.close()
remote_conn_pre.close()
<file_sep>#!/usr/bin/env python
from netmiko import ConnectHandler
from getpass import getpass
password='<PASSWORD>'
pynet2={'device_type': 'cisco_ios',
'ip':'172.16.17.32',
'username':'pyclass',
'password':<PASSWORD>
}
pynet_rtr2=ConnectHandler(**pynet2)
pynet_rtr2.config_mode()
state=pynet_rtr2.check_config_mode()
print state
<file_sep># read_yaml_json_w1e6.py
import yaml
import json
from pprint import pprint
with open("my_file_w1e6.yml") as f:
my_list=yaml.load(f)
print yaml.dump(my_list, default_flow_style=False)
pprint(my_list)
with open("my_file_w1e6.json") as f:
my_list=json.load(f)
for element in my_list:
print element
pprint(my_list)
<file_sep>
''' get_snmp_name_desc.py '''
from snmp_helper import snmp_get_oid,snmp_extract
PORT=161
COMMUNITY='galileo'
rtrs={'pynet-rtr1':'192.168.127.12', 'pynet-rtr2':'172.16.31.10'}
oids={'sysName':'1.3.6.1.2.1.1.5.0', 'sysDescr':'1.3.6.1.2.1.1.1.0'}
for rtr in rtrs.keys():
print rtr
for oid in oids.keys():
print " " + oid + " = " + snmp_extract(snmp_get_oid((rtrs[rtr],COMMUNITY,PORT),oids[oid]))
<file_sep>#!/usr/bin/env python
from netmiko import ConnectHandler
from getpass import getpass
password='<PASSWORD>'
pynet1={'device_type': 'cisco_ios',
'ip':'172.16.17.32',
'username':'pyclass',
'password':<PASSWORD>
}
pynet2={'device_type': 'cisco_ios',
'ip':'192.168.3.11',
'username':'pyclass',
'password':<PASSWORD>
}
juniper_srx={'device_type': 'juniper',
'ip':'192.168.127.12',
'username':'pyclass',
'password':<PASSWORD>
}
for svr in [ pynet2 ]:
conn=ConnectHandler(**svr)
print svr.get("ip")
#outp=conn.config_mode()
#print outp
outp=conn.find_prompt()
print outp
outp=conn.send_command("show run | inc logging")
print outp
config_commands = ['logging buffered 14441']
outp =conn.send_config_set(config_commands)
print outp
outp=conn.send_command("wr")
print outp
outp=conn.send_command("show run | inc logging")
print outp
<file_sep>''' testsvg.py '''
import pygal
fa4_in_packets = [24, 21, 40, 32, 21, 21, 49, 9, 21, 34, 24, 21]
fa4_out_packets = [21, 24, 21, 40, 32, 21, 21, 49, 9, 21, 34, 24]
# Create a Chart of type Line
line_chart = pygal.Line()
# Title
line_chart.title = 'Input/Output Packets and Bytes'
# X-axis labels (samples were every five minutes)
line_chart.x_labels = ['5', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55', '60']
# Add each one of the above lists into the graph as a line with corresponding label
line_chart.add('InPackets', fa4_in_packets)
line_chart.add('OutPackets', fa4_out_packets)
# Create an output image file from this
line_chart.render_to_file('test.svg')
<file_sep>
''' my_func.py '''
def my_hello():
print "hello"
<file_sep># write_yaml_json_w1e6.py
import yaml
import json
my_list = [1,2,3,{'name':'fred','last':'flintstone','age':99}]
with open("my_file_w1e6.yml","w") as f:
f.write(yaml.dump(my_list, default_flow_style=False))
with open("my_file_w1e6.json","w") as f:
json.dump(my_list,f)
|
04a35751b7fee56c2a11f63813b1b6013b7082c7
|
[
"Markdown",
"Python"
] | 26
|
Python
|
dnsbob/pynet_testz
|
8a4c778e8592efd796dc27417b7ae7ee4d9111cc
|
96716fecba6041772b8861e537b6ac4fbde98e2c
|
refs/heads/main
|
<file_sep>class Fish:
evol_count = 0
def __init__(self,types,scale,fins,gills,tooth,):
self.types = types
self.scale = scale
self.fins = fins
self.gills = gills
self.tooth = tooth
self. energy = 40
Fish.evol_count +=1
def show_type(self):
return f'{self.types} {self.scale} {self.fins} {self.gills} {self.tooth}'
def die(self,food):
if food > 0:
print('Наелся')
else:
print('умер от голода')
def swim(self,km):
res = km // 10
self.energy -= res
return res
class Fight:
def kill(self,Whale,Shark):
self.Whale = Whale
self. Shark = Shark
if Whale > Shark:
print('Победил Синий кит')
else:
print('Победила Белая акула')
class White_Shark(Fish):
def __init__(self,types,scale,fins,gills,tooth):
super().__init__(types,scale,fins,gills,tooth)
self.size = 6
self.speed = 56
self.terrible = True
self.sharp_tooth = True
self.very_hungry = True
self.energy = 50
self.fly = True
def swim(self,km):
res = km // 10
self.energy -= res
if self.energy > 0:
return print(f'акула прошла дистанцию')
else:
return print(f'у вас недастаточно энергии ')
def eat(self,food):
if food == 'fish':
self.energy = self.energy + 20
return print(f'энергия восполнилась на {self.energy} %')
elif food == 'tiger_shark':
self.energy = self.energy + 50
return print(f'энергия восполнилась на {self.energy} %')
elif food == 'human':
self.energy = self.energy + 100
return print(f'энергия восполнилась на {self.energy} %')
def Fly(self,shark):
if shark >= self.energy:
print('Вы можете летать')
else:
print('У вас не зватает энергии')
class Blue_Whale(Fish):
def __init__(self,types, scale, fins, gills, tooth):
super().__init__(types,scale, fins, gills, tooth)
self.types = types
self.size = 25
self.blowhole = True
self.whalebone = True
self.hungry = True
self.energy = 70
def show_type(self):
return f'{self.types} {self.scale} {self.fins} {self.gills} {self.tooth}'
def growth(self,food):
if food == 'plankton':
self.size = self.size + 1
print(self.size)
elif food == 'fish':
self.size = self.size + 2
print(self.size)
elif food == 'shark':
self.size = self.size + 3
print(self.size)
def evolution(self,whale):
if whale > 1000:
print('спустя 1000 лет эволюций киты научились дышать под водой')
else:
print('еще не эволюционировал')
shark = White_Shark('Белая акула','Кожа','Плавники','Жабры','Острые зубы')
print(shark.show_type())
shark.swim(100)
whale = Blue_Whale ('Синий кит','Кожа','Плавники','Легкие','Китовый ус')
print(whale.show_type())
whale.growth('shark')
whale.size = 25
whale.evolution(1200)
Whale = Fight()
Shark = Fight()
Whale.kill(500,300)
<file_sep>class AnonumousSurvey:
def __init__(self,question):
self.question = question
self.responses = []
def show_question(self):
print(f'Ответьте на вопрос: {self.question}')
def add_answer(self,new_answer):
self.responses.append(new_answer)
def show_answers(self):
for anwser in self.responses:
print(f'- {anwser}')
question = 'Какой язык программирование самый луший?'
test_poll = AnonumousSurvey(question)
test_poll.add_answer('Phyton')
test_poll.show_answers()<file_sep>from unitest import AnonumousSurvey
from unittest import TestCase
class TestAnonumousSurvey(TestCase):
def test_single_response(self):
question = 'Какой это автомабиль?'
new_poll = AnonumousSurvey(question)
response = 'Бугати'
new_poll.add_answer(response)
self.assertIn(response,new_poll.responses)
def test_list_responses(self):
question = 'Какой чай вы предологаете?'
responses = ['Elite','lipton','Акбар','Жемчужина нила']
new_poll = AnonumousSurvey(question)
for response in responses:
new_poll.add_answer(response)
self.assertEqual(len(responses),len(new_poll.responses))
self.<file_sep>from fish import Fish,White_Shark,Blue_Whale
from unittest import TestCase
class TestFish(TestCase):
def test_size(self):
new_shark = White_Shark('кожа','плавники','жабры','острые зубы')
self.assertEqual(new_shark.size,6)
|
fcbbf41354a8efbfac294b791791554f1c289d3c
|
[
"Python"
] | 4
|
Python
|
Erjan18/task_classes
|
9a3eea7e6247152fab3fbdaba1afa97c6cae632c
|
26fb6970e451485ace6f9f75e39872e892f2f89d
|
refs/heads/master
|
<repo_name>etnul/imager<file_sep>/app.rb
require 'sinatra'
require 'json'
require 'digest'
require 'base64'
post '/img/' do
if params[:uri]
raw = params[:uri]
bits = Base64.decode64(raw[22..-1])
digest = Base64.encode64(Digest::SHA256.digest(bits)).chomp.gsub(/[^a-zA-Z0-9]/,'')
filename = digest + '.png'
File.open(File.dirname(__FILE__) + '/public/cache/' + filename, 'w') do |f|
f.write(bits)
end
# Set cross origin header if you need it
# Next line allows use from anywhere
# response.headers['Access-Control-Allow-Origin'] = '*'
content_type :json
{ :url => request.url.gsub(/img.?$/, '') + 'cache/' + filename}.to_json
end
end
<file_sep>/Gemfile
source 'https://rubygems.org'
gem 'sinatra', '>=1.3.1'
gem 'json'
gem 'shotgun'
<file_sep>/README.md
# imager
Tiny web service to capture and convert data uri images (png) to linkable image assets, or build movies/gifs from data uris...
Public domain
|
7a53b135c7fdf1c9a2ed93231be0c8ef73b1e844
|
[
"Markdown",
"Ruby"
] | 3
|
Ruby
|
etnul/imager
|
acec24561d9c19916b766089e19e5b62a6cf109b
|
fe1053390dfc26f1679c3972904af1c363143805
|
refs/heads/master
|
<repo_name>vmachan/sqlchi<file_sep>/test.sql
SELECT selected_column1 AS selected_column1_alias
,selected_column2
,selected_column3 AS selected_column3_alias
FROM table_name
WHERE where_column1 = 'where_column1_value'
AND where_column2 = 'where_column2_value'
OR where_column3 = 'where_column3_value'
GROUP
BY group_by_column1
,group_by_column2
ORDER
BY order_by_column1
,order_by_column2
;
<file_sep>/sqlchi.py
import os
import sqlparse
from sqlparse import tokens
import treechal as tc
def get_selected_columns(s):
# get selected column names from input sql s
None
def chal_node(n, d):
if hasattr(n, 'tokens'):
for t in n.tokens:
chal_node(t, d+1)
else:
return n
def print_node(n, d):
if hasattr(n, 'tokens'):
for t in n.tokens:
print_node(t, d+1)
else:
print(' ' * d, n, "--", n.ttype)
in_sql_file = open("test.sql")
in_sql_str = in_sql_file.read().replace('\n', '').replace(' ', ' ')
parsed_sql = sqlparse.parse(in_sql_str)
for sql_stmt in parsed_sql:
# print("********** SQL STATEMENT-->", sql_stmt)
for parsed_sql_token in sql_stmt.tokens:
if (
parsed_sql_token.ttype != tokens.Token.Text.Whitespace
and parsed_sql_token.ttype != tokens.Token.Text.Whitespace.Newline
):
# print("********** TOKEN-->", parsed_sql_token, " -- TTYPE-->", parsed_sql_token.ttype)
print_node(parsed_sql_token, 0)
<file_sep>/treechal.py
from collections import deque
from sqlparse.sql import TokenList
class SQLTokenVisitor:
def visit(self, token):
"""Visit a token."""
method = 'visit_' + type(token).__name__
visitor = getattr(self, method, self.generic_visit)
return visitor(token)
def generic_visit(self, token):
"""Called if no explicit visitor function exists for a node."""
if not isinstance(token, TokenList):
return
for tok in token:
print(tok)
self.visit(tok)
def walk_tokens(token):
queue = deque([token])
while queue:
token = queue.popleft()
if isinstance(token, TokenList):
queue.extend(token)
yield token
|
d72a89cceae4ed000e3541a2cdbc49f693ab2e77
|
[
"SQL",
"Python"
] | 3
|
SQL
|
vmachan/sqlchi
|
ba2f8f8a0aa5ab9452ae58ed28f0d714ef0054aa
|
f1190970ff44d6501017b316ce8de23b5262cf4a
|
refs/heads/master
|
<repo_name>jpshade/DihedralPathGen<file_sep>/groupDictionarySetup.py
import re
def groupGenerate(n, myGroup):
for i in range(1,n):
myGroup.append('r'+ str(i))
myGroup.append('s')
for i in range(1,n):
myGroup.append('r'+str(i)+'s')
def rrChange(matchedSubstring,n):
numLengthCheck = re.compile('[0-9]+')
exponents = numLengthCheck.findall(matchedSubstring)
newExponent = 0
for num in exponents:
newExponent = newExponent + int(num)
return newExponent
def srChange(matchedSubstring,n):
numLengthCheck = re.compile('[0-9]+')
exponent = numLengthCheck.findall(matchedSubstring)
return int(exponent[0])*(n-1)
def multiply(firstElement, secondElement, n):
#Regex for determining if two r values next to each other
rrCheck = re.compile('r[0-9]+r[0-9]+')
#regex for determining if r comes after s
srCheck = re.compile('sr[0-9]+')
#regex for checking if an r exponent is greater than n
rNCheck = re.compile('[0-9]+')
totalString = firstElement + secondElement
if 'e' in totalString:
totalString = totalString.replace('e','')
#Loop to make replacements. If element is in D8 or is empty, exit loop
while True:
changesMade = False
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#replace sr with r(n-1)
srMatch = srCheck.search(totalString)
while srMatch:
totalString = totalString[:srMatch.start()] + 'r' + str(srChange(totalString[srMatch.start():srMatch.end()],n)) + 's' + totalString[srMatch.end():]
changesMade = True
srMatch = srCheck.search(totalString)
#~~~~~~~~~~~~~~~~~~~~~~~
#if r values side by side, add exponents
rrMatch = rrCheck.search(totalString)
while rrMatch:
newExponent = rrChange(totalString[rrMatch.start():rrMatch.end()],n)
totalString = totalString[:rrMatch.start()] + 'r' + str(newExponent) + totalString[rrMatch.end():]
changesMade = True
rrMatch = rrCheck.search(totalString)
#~~~~~~~~~~~~~~~~~~~~~~~~`
#Check r4
rNMatch = rNCheck.findall(totalString)
for exponent in rNMatch:
if int(exponent) >= n:
newExponent = int(exponent) % n
totalString = totalString.replace(exponent, str(newExponent))
if ('ss' in totalString) or ('r0' in totalString):
totalString = totalString.replace('ss', '').replace('r0', '')
changesMade = True
#Check exit condition
if not changesMade:
break
if totalString == '':
totalString = 'e'
return totalString
<file_sep>/excelMaker.py
import os
import pathCreator
import pandas as pd
import openpyxl as op
def makeDataFrame(appendedWorkDir, order):
counterDict = {}
with open(os.path.join(appendedWorkDir, 'D{}ResultsDict.txt'.format(order)), 'r') as f:
counterDict = eval(f.read())
return pd.DataFrame(counterDict)
def sortedDataFrame(appendedWorkDir, order):
orderList = []
with open(os.path.join(appendedWorkDir, 'D{}Group.txt'.format(order)), 'r') as f:
orderList = eval(f.read())
myFrame = makeDataFrame(appendedWorkDir, order).reindex_axis(orderList, axis=1)
myFrame = myFrame.reindex_axis(orderList, axis=0)
return myFrame
def makeExcelSheet(myWorkDir, appendedWorkDir, order):
groupFrame = sortedDataFrame(appendedWorkDir, order)
if not (os.path.exists('DihedralGroups.xlsx')):
wb = op.Workbook()
wb.save('DihedralGroups.xlsx')
book = op.load_workbook('DihedralGroups.xlsx')
writer = pd.ExcelWriter('DihedralGroups.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
groupFrame.to_excel(writer, "D{}".format(order))
writer.save()
def colorCells(myWorkDir, order):
completeFill = op.styles.PatternFill(start_color='FF77CAE6', end_color='FF77CAE6', fill_type='solid')
anomalyFill = op.styles.PatternFill(start_color='FFE69377', end_color='FFE69377', fill_type='solid')
diagonalFill = op.styles.PatternFill(start_color = 'FFA1D490', end_color = 'FFA1D490', fill_type = 'solid')
wb = op.load_workbook('DihedralGroups.xlsx')
ws = wb.get_sheet_by_name("D{}".format(order))
for row in ws.rows:
for cell in row:
if isinstance(cell.value, int):
if cell.row == cell.col_idx:
cell.fill = diagonalFill
if cell.value == order:
cell.fill = completeFill
if pathCreator.isAnomalous(cell.value, order):
cell.fill = anomalyFill
wb.save('DihedralGroups.xlsx')
def mainFunction(order):
myWorkDir = os.path.dirname(__file__)
appendedWorkDir = pathCreator.writeResults(order)
makeExcelSheet(myWorkDir, appendedWorkDir, order)
colorCells(myWorkDir, order)
if __name__ == '__main__':
order = int(input('2n = ? '))
mainFunction(order)
<file_sep>/pathCreator.py
import os
import groupDictionarySetup
myGroup = ['e']
groupDict = {}
paths = []
completePaths = []
lengthAnomalies = []
prematurePaths = []
def isPowerOfTwo(num):
return bin(num).count('1') == 1
def isAnomalous(pathLength, order):
return bool((not isPowerOfTwo(pathLength)) and (order % pathLength))
def resetGroup():
for elementIndex in range(1,len(myGroup)):
myGroup.pop()
for i in list(groupDict):
groupDict.pop(i)
for elementIndex in range(1,len(paths)+1):
paths.pop()
for elementIndex in range(1,len(completePaths)+1):
completePaths.pop()
for elementIndex in range(1,len(lengthAnomalies)+1):
lengthAnomalies.pop()
for elementIndex in range(1,len(prematurePaths)+1):
prematurePaths.pop()
def generatePath(firstElement, secondElement, order):
pathList = ['e']
counter = 0
newElement = ''
while newElement not in pathList[:-1]:
if counter%2 == 0:
newElement = groupDict[(firstElement, pathList[-1])]
else:
newElement = groupDict[(secondElement, pathList[-1])]
pathList.append(newElement)
counter = counter + 1
pathString = ''
for element in pathList:
pathString = pathString + element + ' -> '
pathString = pathString[:-4]
fullString = '{:<15}: {:<10}: {}'.format('(' + firstElement + ' , ' + secondElement + ')', str(counter) + ' steps', pathString)
pathDict = {'elements' : (firstElement, secondElement), 'pathList' : pathList, 'counter' : counter, 'fullString': fullString}
if pathDict['counter'] == order:
completePaths.append(pathDict)
if (isAnomalous(pathDict['counter'], order)):
lengthAnomalies.append(pathDict)
if (firstElement != 'e') and (secondElement != 'e') and (pathDict['pathList'][-1] != 'e'):
prematurePaths.append(pathDict)
return pathDict
def writeResults(order):
myWorkDir = initializeGroup(order)
with open(myWorkDir + 'D' + str(order) + 'Group.txt', 'w') as f:
f.write('[')
groupStr = ''
for element in myGroup:
groupStr = groupStr + '\'' + element + '\','
f.write(groupStr[:-1] + ']')
with open(myWorkDir + 'D' + str(order) + 'ResultsDict.txt', 'w') as f:
f.write('{\n')
for firstElement in myGroup:
f.write('\t\'' + firstElement + '\' : {')
for secondElement in myGroup:
currentPath = generatePath(firstElement,secondElement,order)
f.write('\'' + secondElement + '\' : ' + str(currentPath['counter']) + ', ')
f.write('},\n')
f.write('}')
with open(myWorkDir + 'D' + str(order) + 'SignificantPaths.txt', 'w') as f:
f.write("Complete Paths: {}\nLength Anomalies: {}\nPremature Paths: {}\n\n".format(str(len(completePaths)),
str(len(lengthAnomalies)), str(len(prematurePaths))))
f.write("Complete Paths: Total {}\n\n".format(str(len(completePaths))))
for path in completePaths:
f.write(path['fullString']+'\n')
f.write('\n\nLength Anomalies: Total {}\n\n'.format(str(len(lengthAnomalies))))
for path in lengthAnomalies:
f.write(path['fullString'] + '\n')
f.write('\n\nPremature Paths: Total {}\n\n'.format(str(len(prematurePaths))))
for path in prematurePaths:
f.write(path['fullString']+'\n')
return myWorkDir
def makeMultiplicationTable(n, myWorkDir):
with open( myWorkDir + 'D{}MultiplicationTable.py'.format(str(2*n)), 'w') as f:
f.write('D{}: ['.format(str(2*n)))
for element in myGroup:
f.write(element + ' ')
f.write(']\n')
f.write("D{}Dict = {{\n".format(str(2*n)))
for firstElement in myGroup:
for secondElement in myGroup:
newElement = groupDictionarySetup.multiply(firstElement,secondElement,n)
f.write('\t(\'' + firstElement + '\',\'' + secondElement + '\') : \''+ newElement + '\'\n' )
groupDict[(firstElement, secondElement)] = newElement
f.write("}")
def initializeGroup(order):
resetGroup()
dir = os.path.dirname(__file__)
myWorkDir = dir + '\\D' + str(order) + '\\'
n = int(order/2)
if not os.path.exists(myWorkDir):
os.makedirs(myWorkDir)
#initialize(n, myGroup, groupDict)
groupDictionarySetup.groupGenerate(n, myGroup)
makeMultiplicationTable(n, myWorkDir)
return myWorkDir
if __name__ == "__main__":
order = int(input('2n = ? '))
writeResults(order)
|
60ce5c4ceaaee57549591ce77ebc086d5623c543
|
[
"Python"
] | 3
|
Python
|
jpshade/DihedralPathGen
|
56daa252457c387a927fe784ea7d0bc9843b8909
|
01cbb683252a373d6b8992cc783765cefe26c3d9
|
refs/heads/master
|
<file_sep>var express = require("express");
var app = express();
var useragent = require('express-useragent');
var userInfo = {
ipaddress: null,
language: null,
OS: null
}
app.enable('trust proxy');
app.use(useragent.express());
app.get("/", function(req, res){
userInfo.ipaddress = req.ip;
userInfo.language = req.acceptsLanguages()[0];
userInfo.OS = req.useragent.os;
console.log(req.ip);
res.send(JSON.stringify(userInfo));
})
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function(){
console.log('Node app is now running on port', app.get('port'));
});<file_sep>## API Basejump: Request Header Parser Microservice
## User Story:
I can get the IP address, language and operating system for my browser.
## Live Site
[https://powerful-fortress-30434.herokuapp.com/](https://powerful-fortress-30434.herokuapp.com/)
|
09c07b09c1f529f69ef02b18604d741bd9df5645
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
aplchian/parser
|
2b3d2111b9b3a4378b60a6e8d0b2d702f767ed39
|
6df0fb3ce429b6854d86886a0b6f516900f42b5e
|
refs/heads/master
|
<repo_name>anna-sakhlyan/AppboyTest<file_sep>/Podfile
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'AppboyTest' do
pod 'Appboy-iOS-SDK', '~>2.29'
end
|
6418ccdb5e3c34eb924a9937f9cc09e0f548f38d
|
[
"Ruby"
] | 1
|
Ruby
|
anna-sakhlyan/AppboyTest
|
dfa1be645bdcd30fcda71fbf945ba1dccd2f9d7a
|
0c1109924f16d4cdef50eeed0bfce085951b68a8
|
refs/heads/master
|
<repo_name>esabban/knife_rax_cluster<file_sep>/lib/chef/knife/rax_cluster_change.rb
require 'chef/knife/rax_cluster_base'
class Chef
class Knife
class RaxClusterChange < Knife
attr_accessor :headers, :rax_endpoint, :lb_id
include Knife::RaxClusterBase
banner "knife rax cluster change LB_ID (chef_options)"
deps do
require 'fog'
require 'readline'
require 'chef/json_compat'
require 'chef/knife/bootstrap'
Chef::Knife::Bootstrap.load_deps
end
option :lb_region,
:short => "-r lb_region",
:long => "--load-balancer-region lb_region",
:description => "Load balancer region (only supports ORD || DFW)",
:proc => Proc.new { |lb_region| Chef::Config[:knife][:lb_region] = lb_region},
:default => "ORD"
option :run_list,
:long => "--run-list run_list",
:description => "Pass a comma delimted run list --run-list 'recipe[apt],role[base]'",
:proc => Proc.new { |run_list| Chef::Config[:knife][:run_list] = run_list}
option :chef_env,
:long => "--chef-env environment",
:description => "Pass a comma delimted run list --run-list 'recipe[apt],role[base]'",
:proc => Proc.new { |chef_env| Chef::Config[:knife][:chef_env] = chef_env}
=begin
Takes an array of hashes of instance data and a block that provides
what work should be done. This function will look up the chef object
For the node and pass that object into the calling block.
=end
def change_chef_vars(instances, &block)
instances.each { |inst|
query = "name:#{inst['server_name']}"
query_nodes = Chef::Search::Query.new
query_nodes.search('node', query) do |node_item|
yield node_item
end
}
end
=begin
Looks up the LB meta data and grabs the server name for every node
In the LB pool
Looks them up in chef and changes there run_list or chef_env
=end
def run
if !config[:run_list] and !config[:chef_env]
ui.fatal "Please specify either --run-list or --chef-env to change on your cluster"
exit(1)
end
if @name_args.empty?
ui.fatal "Please specify a load balancer ID to update"
exit(1)
end
lb_auth = authenticate()
headers = {"x-auth-token" => lb_auth['auth_token'], "content-type" => "application/json"}
lb_url = ""
lb_auth['lb_urls'].each {|lb|
if config[:lb_region].to_s.downcase == lb['region'].to_s.downcase
lb_url = lb['publicURL']
break
end
lb_url = lb['publicURL']
}
@name_args.each {|arg|
lb_url = lb_url + "/loadbalancers/#{arg}"
lb_data = make_web_call("get", lb_url, headers)
lb_data = JSON.parse(lb_data.body)
instances = []
lb_data['loadBalancer']['metadata'].each{|md|
instances << {"server_name" => md['key'], "uuid" => md['uuid']}
}
if config[:run_list]
config[:run_list] = config[:run_list].split(",")
change_chef_vars(instances) { |node_item|
ui.msg "Changing #{node_item.name} run list to #{config[:run_list]}"
node_item.run_list(config[:run_list])
node_item.save
}
end
if config[:chef_env]
change_chef_vars(instances){|node_item|
ui.msg "Changing #{node_item.name} chef environment to #{config[:chef_env]}"
node_item.chef_environment(config[:chef_env])
node_item.save
}
end
}
end
end
end
end
<file_sep>/knife-rax-cluster.gemspec
Gem::Specification.new do |s|
s.name = 'knife-rackspace-cluster'
s.version = '0.0.8'
s.date = '2013-02-19'
s.summary = "Knife rax cluster"
s.description = "Creates rax clusters"
s.authors = ["<NAME>"]
s.email = '<EMAIL>'
s.files = Dir.glob("{lib}/**/*")
s.homepage = "http://github.com/jrcloud/knife_rax_cluster"
s.add_dependency "fog", ">= 1.22"
s.add_dependency "knife-rackspace"
end
<file_sep>/lib/chef/knife/rax_cluster_base.rb
require 'chef/knife'
#require 'chef/knife/rackspace/rackspace_base'
#require 'chef/knife/rackspafce/rackspace_server_create'
# Make sure you subclass from Chef::Knife
class Chef
class Knife
module RaxClusterBase
def self.included(includer)
includer.class_eval do
deps do
require "net/https"
require 'net/http'
require "uri"
requie 'json'
#require 'chef/shef/ext'
#require 'rubygems'
#require 'chef/knife/rackspace_server_create'
#require 'json'
require 'fog'
#require "thread"
#require 'net/ssh/multi'
require 'readline'
require 'chef/knife/bootstrap'
require 'chef/json_compat'
Chef::Knife::Bootstrap.load_deps
#include Knife::RackspaceBase
end
#option :rax_cluster_auth,
# :short => "-auth auth_url_for_cluster",
# :long => "--rackspace-api-url url",
# :description => "Specify the URL to auth for creation of LB's, i.e. (https:////identity.api.rackspacecloud.com/v1.1)",
# :proc => Proc.new { |key| Chef::Config[:knife][:rax_cluster_auth] = key }
#option :rackspace_api_key,
# :short => "-K KEY",
# :long => "--rackspace-api-key KEY",
# :description => "Your rackspace API key",
# :proc => Proc.new { |key| Chef::Config[:knife][:rackspace_api_key] = key }
#
#option :rackspace_username,
# :short => "-A USERNAME",
# :long => "--rackspace-username USERNAME",
# :description => "Your rackspace API username",
# :proc => Proc.new { |username| Chef::Config[:knife][:rackspace_username] = username }
#
#option :rackspace_version,
# :long => '--rackspace-version VERSION',
# :description => 'Rackspace Cloud Servers API version',
# :default => "v1",
# :proc => Proc.new { |version| Chef::Config[:knife][:rackspace_version] = version }
#
#option :rackspace_api_auth_url,
# :long => "--rackspace-api-auth-url URL",
# :description => "Your rackspace API auth url",
# :default => "auth.api.rackspacecloud.com",
# :proc => Proc.new { |url| Chef::Config[:knife][:rackspace_api_auth_url] = url },
# :default => "https://identity.api.rackspacecloud.com/v1.1/auth"
#
#option :rackspace_endpoint,
# :long => "--rackspace-endpoint URL",
# :description => "Your rackspace API endpoint",
# :default => "https://dfw.servers.api.rackspacecloud.com/v2",
# :proc => Proc.new { |url| Chef::Config[:knife][:rackspace_endpoint] = url }
end
end
def populate_environment
self.setup_environment_vars{
rackspace_username = Chef::Config[:knife][:rackspace_username]
rackspace_password = Chef::Config[:knife][:rackspace_password]
rackspace_endpoint = Chef::Config[:knife][:rackspace_auth_url]
@headers = {"x-auth-user" => rackspace_username, "x-auth-key" => rackspace_password,
"auth_url" => rackspace_endpoint,
"content-type" => "application/json", "Accept" => "application/json"}
#@rax_endpoint = Chef::Config[:knife][:narciss_url] + "/" + Chef::Config[:knife][:narciss_version] + "/"
#if rackspace_username_set
# @rackspace_username = rackspace_username
#end
#if rackspace_password_set
# @rackspace_password = <PASSWORD>
#end
#if rackspace_tenant_set
# @rackspace_tenant = rackspace_tenant
#end
#if rackspace_endpoint_set
# @rackspace_endpoint = rackspace_endpoint
#end
}
end
def make_web_call(httpVerb,uri,headers=nil, request_content=nil)
verbs =
{"get" => "Net::HTTP::Get.new(uri.request_uri, headers)",
"head" => "Net::HTTP::Head.new(uri.request_uri, headers)",
"put" => "Net::HTTP::Put.new(uri.request_uri, headers)",
"delete" => "Net::HTTP::Delete.new(uri.request_uri, headers)",
"post" => "Net::HTTP::Post.new(uri.request_uri, headers)"
}
#Get to work boy! This is Ruby!
ssl_used = false
if uri =~ /https/
ssl_used = true
end
uri = URI.parse(uri)
http = Net::HTTP.new(uri.host, uri.port)
if ssl_used
http.use_ssl = true
end
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = eval verbs[httpVerb]
if httpVerb == 'post' or httpVerb == 'put'
request.body = request_content
end
response = http.request(request)
if not ('200'..'204').include? response.code
puts "Error making web call"
puts "Response code : #{response.code}"
puts "Response body : #{response.body}"
#puts "Response Headers : #{response.headers}"
end
return response
end
#Just used for lbaas since fog doesn't allow meta data on LB's
def authenticate(auth_url='https://identity.api.rackspacecloud.com/v1.1/auth',username=Chef::Config[:knife][:rackspace_api_username] ,password=<PASSWORD>::Config[:knife][:rackspace_api_key])
auth_json = {
"credentials" => {
"username" => username,
"key" => <PASSWORD>
}
}
headers = {"Content-Type" => "application/json"}
auth_data = make_web_call('post', auth_url, headers, auth_json.to_json)
lb_data = JSON.parse(auth_data.body)
lb_returned = {'auth_token' => lb_data['auth']['token']['id'], 'lb_urls' => lb_data['auth']['serviceCatalog']['cloudLoadBalancers'] }
return lb_returned
end
def msg_pair(label, value, color=:cyan)
if value && !value.to_s.empty?
puts "#{ui.color(label, color)}: #{value}"
end
end
end
end
end
<file_sep>/README.rdoc
= Knife Rackspace Cluster
= Description:
This tool hooks into opscode's knife-rackspace ruby gem. This plugin allows you to create rackspace "clusters". A rackspace cluster is a group of nodes that are behind a cloud load balancer. This tool will build your nodes and automatically put them behind a cloud loadbalancer. This tool allows you to specify a blueprint file that contains: quantity of nodes, chef run list and environment, flavor and image to be used. Please use ruby 1.9 for best performance (i.e. threaded server deploys).
= Installation
Install chef (as of right now this plugin has only been tested against chef 10.22.0):
sudo gem install chef --version 10.22.0
Install Make
sudo apt-get install make
sudo yum install make
To satisfy the requirements of the nokogiri gem you must also follow the instructions here:
http://nokogiri.org/tutorials/installing_nokogiri.html
Install the knife rackspace cluster Gem:
sudo gem install knife-rackspace-cluster
There are issues with fog 1.9.0 creating rackspace servers. This plugin has a version contraint on fog 1.8.0. If you already have 1.9.0 installed you can do the following until this is fixed:
sudo gem uninstall fog --version 1.9.0
sudo gem install fog --version 1.8.0
= CONFIGURATION
You will need to make the following entries into your knife.rb file in order to communicate with the rackspace API:
knife[:rackspace_api_username] = "username"
knife[:rackspace_api_key] = "api_key"
knife[:rackspace_version] = 'v2'
knife[:rackspace_endpoint] = "https://ord.servers.api.rackspacecloud.com/v2"
Please see the knife-rackspace readme for more details on configuring your knife.rb
= SUBCOMMANDS:
This plugin provides the following sub commands:
= knife rax cluster create
This command requires that you pass it a name for your cloud load balancer and the -B (blueprint) flag followed by a blueprint file. You can generate a template file by running:
knife rax cluster create -G
This will create a file called map_template.json in your current directory. An example template looks as follows:
{
"blue_print" :
{
"name_convention" : "web",
"run_list" : [
"recipe[apt]",
"role[base]"
],
"quantity" : 2,
"chef_env" : "dev",
"image_ref" : "c195ef3b-9195-4474-b6f7-16e5bd86acd0",
"flavor" : 2
}
}
This will tell the plugin to build 2 servers and use the settings specified. The servers will be named based on your name_convetion setting and random digits will be appeneded to the name. The servers will be built using threads if you're using ruby 1.9. Once the servers have been built and bootstrapped with chef a load balancer will be created and the nodes will be added to the LB pool.
To create your cluster you can run the following command:
knife rax cluster create web_heads -B map_template.json -r ord
If you do not specify any other parameters this will create a load balancer that is listening on port 80 using the ROUND_ROBIN algorithm. It will also rename the load balancer to web_heads_cluster so the plugin can search for valid clusters using the list sub command. You must specify the -r(region) switch to tell the plugin what data center to create your load balancer in.
= knife rax cluster list
This command will look for any load balancers in the specified data center with the name suffixed by _cluster. It will return the load balancer name, Load balancer id, LB algorithm, LB protocol, LB node Count. You must specify the -r (region) to tell the plugin what data center to look in.
Example:
knife rax cluster list -r ord
= knife rax cluser show
This command takes a load balancer ID of one of your clusters and the -r switch to tell the tool what region the LB resides. It will display information regarding the LB and the nodes belonging to it.
Example:
knife rax cluster show LB_ID -r ord
= knife rax cluster change
This command will allow you to change the chef environment and chef run_lists of the existing members of the cluster. You will need to pass the plugin a load balancer ID of your cluster and the --run-list or the --chef-env flags. Examples
knife rax cluster change 1234 --run-list 'recipe[apt],role[base]'
knife rax cluster change 1234 --chef-env prod
= knife rax cluster expand
This command will allow you to add additional nodes to an existing rax cluster. You will need to pass it a load balancer ID that you wish to add nodes to as well as the -B (blueprint) flag for instructions on the new nodes.
Example:
knife rax cluster expand 1234 -B map_template.json -r ord
= knife rax cluster delete
This command takes the load balancer ID as an argument and the -r (region) switch. Running this command will delete all the servers that are apart of the cluster from the rackspace cloud as well as from your chef server.
Example:
knife rax cluster delete 1234 -r ord
= Troubleshooting
If you run into errors such as this:
Fog::Compute::RackspaceV2::BadRequest: Fog::Compute::RackspaceV2::BadRequest
Make sure to check that values in your blue print file are valid. For example if you specify an incorrect image or flavor you may see this message. Also check that you are passing the correct rackspace username and api key.
It's recomended to use Ruby 1.9 and gems 1.8 with this plugin. If you're having trouble installing ruby 1.9 with your OS, try using chef's installer located here:
http://www.opscode.com/chef/install/
This will put ruby and gems under:
/opt/chef/embedded/bin
This is a quick way to get ruby 1.9 running on a system.
= LICENSE
Author:: <NAME> (<<EMAIL>>)
Copyright:: Copyright (c) 2013 <NAME>
License:: Apache License, Version 2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
<file_sep>/lib/chef/knife/rax_cluster_list.rb
require 'chef/knife/rax_cluster_base'
class Chef
class Knife
class RaxClusterList < Knife
attr_accessor :headers, :rax_endpoint, :lb_id
include Knife::RaxClusterBase
banner "knife rax cluster list -r lb_region"
deps do
require 'fog'
require 'readline'
require 'chef/json_compat'
require 'chef/knife/bootstrap'
Chef::Knife::Bootstrap.load_deps
end
option :lb_region,
:short => "-r lb_region",
:long => "--load-balancer-region lb_region",
:description => "Load balancer region (only supports ORD || DFW)",
:proc => Proc.new { |lb_region| Chef::Config[:knife][:lb_region] = lb_region},
:default => "ORD"
=begin
Looks for lb's named $variable_cluster and lists them
=end
def run
lb_auth = authenticate
headers = {"x-auth-token" => lb_auth['auth_token'], "content-type" => "application/json"}
lb_url = ""
lb_auth['lb_urls'].each {|lb|
if config[:lb_region].to_s.downcase == lb['region'].to_s.downcase
lb_url = lb['publicURL']
break
end
lb_url = lb['publicURL']
}
lb_url = lb_url + "/loadbalancers"
lb_list = make_web_call("get", lb_url, headers)
lb_list = JSON.parse(lb_list.body)
lb_list['loadBalancers'].each {|lb|
if (lb['name'] =~ /_cluster/i)
msg_pair("LB Details for #{lb['name']}", " ")
msg_pair("\s\s\s\sLB ID", "#{lb['id']}")
msg_pair("\s\s\s\sLB Port", "#{lb['port']}")
msg_pair("\s\s\s\sLB Algorithm", "#{lb['algorithm']}")
msg_pair("\s\s\s\sLB Protocol", "#{lb['protocol']}")
msg_pair("\s\s\s\sLB Node Count", "#{lb['nodeCount']}")
ui.msg "\n\n"
end
}
end
end
end
end
<file_sep>/lib/chef/knife/rax_cluster_create.rb
require 'chef/knife/rax_cluster_base'
require 'chef/knife/rax_cluster_build'
class Chef
class Knife
class RaxClusterCreate < Knife
attr_accessor :headers, :rax_endpoint, :lb_name
include Knife::RaxClusterBase
banner "knife rax cluster create (cluster_name) [options]"
deps do
require 'fog'
require 'readline'
require 'chef/json_compat'
require 'chef/knife/bootstrap'
Chef::Knife::Bootstrap.load_deps
end
option :algorithm,
:short => "-a Load_balacner_algorithm",
:long => "--algorithm algorithm",
:description => "Load balancer algorithm",
:proc => Proc.new { |algorithm| Chef::Config[:knife][:algorithm] = algorithm },
:default => "ROUND_ROBIN"
option :blue_print,
:short => "-B Blue_print_file",
:long => "--map blue_print_file",
:description => "Path to blue Print json file",
:proc => Proc.new { |i| Chef::Config[:knife][:blue_print] = i.to_s }
option :port,
:short => "-lb_port port",
:long => "--load-balancer-port port",
:description => "Load balancer port",
:proc => Proc.new { |port| Chef::Config[:knife][:port] = port},
:default => "80"
option :timeout,
:short => "-t timeout",
:long => "--load-balancer-timeout timeout",
:description => "Load balancer timeout",
:proc => Proc.new { |timeout| Chef::Config[:knife][:timeout] = timeout},
:default => "30"
option :lb_region,
:short => "-r lb_region",
:long => "--load-balancer-region lb_region",
:description => "Load balancer region (only supports ORD || DFW)",
:proc => Proc.new { |lb_region| Chef::Config[:knife][:lb_region] = lb_region},
:default => "ORD"
option :protocol,
:short => "-p protocol",
:long => "--load-balancer-protocol protocol",
:description => "Load balancer protocol",
:proc => Proc.new { |protocol| Chef::Config[:knife][:protocol] = protocol},
:default => 'HTTP'
option :generate_map_template,
:short => "-G",
:long => "--generate_map_template",
:description => "Generate server map Template in current dir named map_template.json"
#option :session_persistence,
#:short => "-S on_or_off",
#:long => "--session-persistence session_persistence_on_or_off",
#:description => "Load balancer session persistence on or off",
#:proc => Proc.new { |session_persistence| Chef::Config[:knife][:session_persistence] = session_persistence}
=begin
Generates a template json file in the current dir called
map_template.json
=end
def generate_map_template
file_name = "./map_template.json"
template = %q(
{
"blue_print" :
{
"name_convention" : "web",
"run_list" : [
"recipe[apt]"
],
"quantity" : 1,
"chef_env" : "dev",
"image_ref" : "a9753ff4-f46c-427d-9498-1358564f622f",
"flavor" : 2
}
}
)
File.open(file_name, 'w') { |file| file.write(template)}
end
=begin
Takes instance array of hash data and creates a load balancer.
Will put all nodes created in the LB pool (using private IP)
Will store servers in meta data using key = server name
value = uuid, this is for updates on chef vars on these nodes
=end
def create_lb(instances,error_text=nil)
lb_request = {
"loadBalancer" => {
"name" => @lb_name.to_s + "_cluster",
"port" => config[:port] || '80',
"protocol" => config[:protocol] || 'HTTP',
"algorithm" => config[:algorithm] || 'ROUND_ROBIN',
"virtualIps" => [
{
"type" => "PUBLIC"
}
],
"nodes" => [],
"metadata" => []
}
}
instances.each {|inst|
lb_request['loadBalancer']['nodes'] << {"address" => inst['ip_address'], 'port' =>Chef::Config[:knife][:port] || '80', "condition" => "ENABLED" }
lb_request['loadBalancer']['metadata'] << {"key" => inst['server_name'], "value" => inst['uuid']}
}
lb_authenticate = authenticate()
lb_url = ""
lb_authenticate['lb_urls'].each {|lb|
if config[:lb_region].to_s.downcase == lb['region'].to_s.downcase
lb_url = lb['publicURL']
break
end
lb_url = lb['publicURL']
}
lb_url = lb_url + "/loadbalancers"
headers = {'Content-type' => 'application/json', 'x-auth-token' => lb_authenticate['auth_token']}
create_lb_call = make_web_call("post",lb_url, headers, lb_request.to_json )
lb_details = JSON.parse(create_lb_call.body)
ui.msg "Load Balancer Cluster Sucesfully Created"
ui.msg "Load Balancer ID: #{lb_details['loadBalancer']['id']}"
ui.msg "Load Balancer Name: #{lb_details['loadBalancer']['name']}"
lb_ip = ""
lb_details['loadBalancer']['virtualIps'].each {|lb| (lb['ipVersion'] == "IPV4") ? lb_ip = lb['address'] : "not_found"}
ui.msg "Load Balancer IP Address: #{lb_ip}"
if error_text
ui.msg "Some nodes failed to bootstrap or boot, verify with knife node list and or nova list to track down errors"
end
end
=begin
Parses json, creates blue_prints w/ specified chef vars
If ruby 1.9 is used builds will be spun up with Threads
If update_cluster is specified, an LB will not be created
an array of instance data will be returned to the caller
=end
def deploy(blue_print,update_cluster=nil)
(File.exist?(blue_print)) ? map_contents = JSON.parse(File.read(blue_print)) : map_contents = JSON.parse(blue_print)
sleep_interval = 1
instances = []
if map_contents.has_key?("blue_print")
bp_values = map_contents['blue_print']
unless bp_values.has_key?("image_ref")
ui.fatal "You must specify an image_ref, run the -G command to generate a template blueprint"
exit(1)
end
unless bp_values.has_key?("name_convention")
ui.fatal "You must specify a name_convention, run the -G command to generate a template blueprint"
exit(1)
end
unless bp_values.has_key?("flavor")
ui.fatal "You must specify a flavor, run the -G command to generate a template blueprint"
exit(1)
end
unless bp_values.has_key?("quantity")
ui.fatal "You must specify a quantity of servers, run the -G command to generate a template blueprint"
exit(1)
end
bootstrap_nodes = []
failed_attempts = 0
quantity = bp_values['quantity'].to_i
quantity.times do |node_name|
node_name = rand(900000000)
create_server = Chef::Knife::RaxClusterBuild.new
#create_server.config[:identity_file] = config[:identity_file]
Chef::Config[:knife][:image] = bp_values['image_ref']
create_server.config[:chef_node_name] = bp_values['name_convention'] + node_name.to_s
create_server.config[:environment] = bp_values['chef_env']
Chef::Config[:environment] = bp_values['chef_env']
create_server.config[:run_list] = bp_values['run_list']
Chef::Config[:knife][:flavor] = bp_values['flavor']
bootstrap_nodes << Thread.new { Thread.current['server_return'] = create_server.run }
end
quantity.times do |times|
if quantity > 20
sleep_interval = 6
else
sleep_interval = 4
end
sleep(sleep_interval)
begin
bootstrap_nodes[times].join
rescue
failed_attempts += 1
if failed_attempts == quantity
ui.fatal "All servers failed to bootstrap, check network connectivy and vet all cookbooks used"
exit(1)
else
next
end
end
instances << {"server_name" => bootstrap_nodes[times]['server_return']['server_name'],
"ip_address" => bootstrap_nodes[times]['server_return']['private_ip'],
"uuid" => bootstrap_nodes[times]['server_return']['server_id'],
"name_convention" => bp_values['name_convention'],
"chef_env" => bp_values['chef_env'],
"run_list" => bp_values['run_list']
}
end
end
if update_cluster
instance_return = {}
if failed_attempts > 0
instance_return = {'instances' => instances, "error_text" => true}
else
instance_return = {'instances' => instances, "error_text" => false}
end
return instance_return
else
if failed_attempts > 0
create_lb(instances,true)
else
create_lb(instances)
end
end
end
def run
#Generate template config
if config[:generate_map_template]
generate_map_template()
ui.msg "Map template saved as ./map_template.json"
exit()
end
if @name_args.empty? or @name_args.size > 1
ui.fatal "Please specify a single name for your cluster"
exit(1)
end
#Set load balancer name
@lb_name = @name_args[0]
if config[:blue_print]
deploy(config[:blue_print])
end
end
end
end
end
<file_sep>/lib/chef/knife/rax_cluster_delete.rb
require 'chef/knife/rax_cluster_base'
require 'chef/knife/rackspace_server_delete'
class Chef
class Knife
class RaxClusterDelete < Knife
attr_accessor :headers, :rax_endpoint, :lb_name
include Knife::RaxClusterBase
banner "knife rax cluster delete (load_balancer_id) [options]"
deps do
require 'fog'
require 'readline'
require 'chef/json_compat'
require 'chef/knife/bootstrap'
Chef::Knife::Bootstrap.load_deps
end
option :lb_region,
:short => "-r lb_region",
:long => "--load-balancer-region lb_region",
:description => "Load balancer region (only supports ORD || DFW)",
:proc => Proc.new { |lb_region| Chef::Config[:knife][:lb_region] = lb_region},
:default => "ORD"
=begin
Looks up all nodes from lb meta data, deletes them from chef and nova
Via knife rackspace method
AFter node deletion it will delete the LB
=end
def delete_cluster
lb_authenticate = authenticate()
lb_url = ""
headers = {"x-auth-token" => lb_authenticate['auth_token'], "content-type" => "application/json"}
lb_authenticate['lb_urls'].each {|lb|
if config[:lb_region].to_s.downcase == lb['region'].to_s.downcase
lb_url = lb['publicURL']
break
end
lb_url = lb['publicURL']
}
@name_args.each {|arg|
server_uuids = []
lb_url = lb_url + "/loadbalancers/#{arg}"
get_uuids = make_web_call("get", lb_url, headers )
if get_uuids.code == '404'
ui.msg "Make sure you specify the -r flag to specify what region the LB is located"
exit(1)
end
lb_data = JSON.parse(get_uuids.body)
lb_data['loadBalancer']['metadata'].each{|meta|
server_uuids << {'uuid' => meta['value'], 'server_name' => meta['key'] }
}
server_uuids.each { |uuid|
rs_delete = RackspaceServerDelete.new
rs_delete.config[:yes] = 'yes'
rs_delete.name_args = [ uuid['uuid'] ]
rs_delete.config[:purge] = true
rs_delete.config[:chef_node_name] = uuid['server_name']
rs_delete.run
}
delete_lb_call = make_web_call("delete", lb_url, headers)
puts "Deleted loadbalancer id #{arg}"
}
end
def run
if @name_args.empty?
ui.fatal "Please specify a Load balancer ID to delete"
end
ui.confirm("Are you sure you want to delete this Load balancer and ALL nodes associated with it?")
delete_cluster
end
end
end
end
<file_sep>/lib/chef/knife/rax_cluster_expand.rb
require 'chef/knife/rax_cluster_base'
require 'chef/knife/rackspace_server_delete'
class Chef
class Knife
class RaxClusterExpand < Knife
attr_accessor :headers, :rax_endpoint, :lb_id
include Knife::RaxClusterBase
banner "knife rax cluster expand (load_balancer_id) -B template_file.json"
deps do
require 'fog'
require 'readline'
require 'chef/json_compat'
require 'chef/knife/bootstrap'
Chef::Knife::Bootstrap.load_deps
end
option :blue_print,
:short => "-B Blue_print_file",
:long => "--map blue_print_file",
:description => "Path to blue Print json file",
:proc => Proc.new { |i| Chef::Config[:knife][:blue_print] = i.to_s }
option :port,
:short => "-lb_port port",
:long => "--load-balancer-port port",
:description => "Load balancer port",
:proc => Proc.new { |port| Chef::Config[:knife][:port] = port},
:default => "80"
option :lb_region,
:short => "-r lb_region",
:long => "--load-balancer-region lb_region",
:description => "Load balancer region (only supports ORD || DFW)",
:proc => Proc.new { |lb_region| Chef::Config[:knife][:lb_region] = lb_region},
:default => "ORD"
=begin
This will take a blueprint file and call the raxClusterCreate
Class to handle parsing and building the nodes. It will then
update the LB ID passed on the CLI with the nodes and meta data
=end
def expand_cluster
rs_cluster = RaxClusterCreate.new
rs_cluster.config[:blue_print] = config[:blue_print]
rs_cluster.lb_name = @name_args[0]
instance_return = rs_cluster.deploy(config[:blue_print],'update_cluster')
instance_errors = instance_return['error_text']
instance_return = instance_return['instances']
lb_auth = authenticate()
puts lb_auth['auth_token']
headers = {"x-auth-token" => lb_auth['auth_token'], "content-type" => "application/json"}
lb_url = ""
lb_auth['lb_urls'].each {|lb|
if config[:lb_region].to_s.downcase == lb['region'].to_s.downcase
lb_url = lb['publicURL']
break
end
lb_url = lb['publicURL']
}
meta_data_request = {
"metadata" => []
}
node_data_request = {
"nodes" => []
}
meta_url = lb_url + "/loadbalancers/#{@lb_id}/metadata"
node_url = lb_url + "/loadbalancers/#{@lb_id}/nodes"
instance_return.each {|inst|
node_data_request['nodes'] << {"address" => inst['ip_address'], 'port' =>Chef::Config[:knife][:port] || '80', "condition" => "ENABLED" }
meta_data_request['metadata'] << {"key" => inst['server_name'], "value" => inst['uuid']}
}
meta_request = make_web_call("post", meta_url, headers, meta_data_request.to_json)
lb_status = lb_url + "/loadbalancers/#{@lb_id}"
lb_stats = make_web_call("get", lb_status, headers)
lb_stats = JSON.parse(lb_stats.body)
while lb_stats['loadBalancer']['status'].to_s.downcase != 'active'
sleep(5)
lb_stats = make_web_call("get", lb_status, headers)
lb_stats = JSON.parse(lb_stats.body)
end
node_request = make_web_call("post", node_url, headers, node_data_request.to_json)
if instance_errors
ui.msg "There were problems bootstrapping/booting nodes, verify with knife node list or nova list to track down issues"
end
ui.msg "Load balancer id #{@lb_id} has been updated"
end
def run
if @name_args.empty?
ui.fatal "Please specify Load balancer ID to add nodes too"
exit(1)
end
if !config[:blue_print]
ui.fatal "Please specify a blue print file to parse with -B"
exit(1)
end
if config[:blue_print]
@lb_id = @name_args[0]
expand_cluster
end
end
end
end
end
|
b96633c01687493133111d9fb14f9c4ea360f5a4
|
[
"RDoc",
"Ruby"
] | 8
|
Ruby
|
esabban/knife_rax_cluster
|
4f68176581fa6686e8203ae5aa4061fc3689bbb8
|
673048ff3ce6f8d74e4f52610c2bc49d17f732fb
|
refs/heads/master
|
<repo_name>mthamil/PSycheTest<file_sep>/PSycheTest.Runners.Framework/ITestScript.cs
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation.Language;
using PSycheTest.Runners.Framework.Results;
using PSycheTest.Runners.Framework.Utilities;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Defines a test script.
/// </summary>
public interface ITestScript : ITestResultProvider
{
/// <summary>
/// The file a script came from.
/// </summary>
FileInfo Source { get; }
/// <summary>
/// The text content of a script.
/// </summary>
string Text { get; }
/// <summary>
/// The tests contained with a script.
/// </summary>
IEnumerable<ITestFunction> Tests { get; }
/// <summary>
/// An optional test setup function.
/// </summary>
Option<FunctionDefinitionAst> TestSetup { get; }
/// <summary>
/// An optional test cleanup function.
/// </summary>
Option<FunctionDefinitionAst> TestCleanup { get; }
/// <summary>
/// Returns a script's results grouped by their parent <see cref="TestFunction"/>s.
/// </summary>
ILookup<ITestFunction, TestResult> ResultsByTest { get; }
}
}<file_sep>/PSycheTest.Runners.Framework/Results/SkippedResult.cs
using System;
using System.Linq;
namespace PSycheTest.Runners.Framework.Results
{
/// <summary>
/// Represents the result of a test that was skipped.
/// </summary>
public class SkippedResult : TestResult
{
/// <summary>
/// Initializes a new <see cref="SkippedResult"/>.
/// </summary>
/// ><param name="skipReason">The reason a test was skipped.</param>
public SkippedResult(string skipReason)
: base(null, Enumerable.Empty<Uri>())
{
SkipReason = skipReason;
}
/// <see cref="TestResult.Status"/>
public override TestStatus Status
{
get { return TestStatus.Skipped; }
}
/// <summary>
/// The reason a test was skipped.
/// </summary>
public string SkipReason { get; private set; }
}
}<file_sep>/Tests.Integration/PSycheTest/AssertEqualCmdletTests.cs
using System.Management.Automation;
using PSycheTest;
using PSycheTest.Exceptions;
using Xunit;
namespace Tests.Integration.PSycheTest
{
public class AssertEqualCmdletTests : CmdletTestBase<AssertEqualCmdlet>
{
[Fact]
public void Test_Assert_Failure_With_Same_Type()
{
// Arrange.
AddCmdlet();
AddParameter(p => p.Expected, 1);
AddParameter(p => p.Actual, 2);
// Act/Assert.
var exception = Assert.Throws<CmdletInvocationException>(() =>
Current.Shell.Invoke());
Assert.NotNull(exception.InnerException);
var assertException = Assert.IsType<ExpectedActualException>(exception.InnerException);
Assert.Equal(1, assertException.Expected);
Assert.Equal(2, assertException.Actual);
}
[Fact]
public void Test_Assert_Failure_With_Different_Types()
{
// Arrange.
AddCmdlet();
AddParameter(p => p.Expected, 1);
AddParameter(p => p.Actual, "hello");
// Act/Assert.
var exception = Assert.Throws<CmdletInvocationException>(() =>
Current.Shell.Invoke());
Assert.NotNull(exception.InnerException);
var assertException = Assert.IsType<ExpectedActualException>(exception.InnerException);
Assert.Equal(1, assertException.Expected);
Assert.Equal("hello", assertException.Actual);
}
[Fact]
public void Test_Assert_Success()
{
// Arrange.
AddCmdlet();
AddParameter(p => p.Expected, 10);
AddParameter(p => p.Actual, 10);
// Act/Assert.
Assert.DoesNotThrow(() => Current.Shell.Invoke());
}
}
}<file_sep>/Tests.Integration/PSycheTest/AssertNotNullCmdletTests.cs
using System.Management.Automation;
using PSycheTest;
using PSycheTest.Exceptions;
using Xunit;
namespace Tests.Integration.PSycheTest
{
public class AssertNotNullCmdletTests : CmdletTestBase<AssertNotNullCmdlet>
{
[Fact]
public void Test_Assert_Failure()
{
// Arrange.
AddCmdlet();
AddParameter(p => p.Value, null);
// Act/Assert.
var exception = Assert.Throws<CmdletInvocationException>(() =>
Current.Shell.Invoke());
Assert.NotNull(exception.InnerException);
Assert.IsType<AssertionException>(exception.InnerException);
}
[Fact]
public void Test_Assert_Success()
{
// Arrange.
AddCmdlet();
AddParameter(p => p.Value, new object());
// Act/Assert.
Assert.DoesNotThrow(() => Current.Shell.Invoke());
}
}
}<file_sep>/PSycheTest.Runners.Framework/Timers/StopwatchTimer.cs
using System;
using System.Diagnostics;
namespace PSycheTest.Runners.Framework.Timers
{
/// <summary>
/// A test timer based on <see cref="Stopwatch"/>.
/// </summary>
internal class StopwatchTimer : ITestTimer
{
/// <see cref="ITestTimer.Start"/>
public IDisposable Start()
{
stopwatch.Start();
return new TimerToken(this);
}
/// <see cref="ITestTimer.Stop"/>
public void Stop()
{
stopwatch.Stop();
Elapsed = stopwatch.Elapsed;
}
/// <see cref="ITestTimer.Elapsed"/>
public TimeSpan Elapsed { get; private set; }
private readonly Stopwatch stopwatch = new Stopwatch();
}
}<file_sep>/Tests.Integration/PSycheTest.Runners.Framework/PowerShellTestDiscovererTests.cs
using System.Linq;
using Moq;
using PSycheTest.Runners.Framework;
using Tests.Integration.TestScripts;
using Xunit;
namespace Tests.Integration.PSycheTest.Runners.Framework
{
public class PowerShellTestDiscovererTests
{
public PowerShellTestDiscovererTests()
{
discoverer = new PowerShellTestDiscoverer(logger.Object);
}
[Fact]
public void Test_Discover_With_Single_File_Single_Test()
{
// Arrange.
var file = ScriptFiles.HasOneTest;
// Act.
var testScript = discoverer.Discover(file);
// Assert.
Assert.True(testScript.HasValue);
var test = Assert.Single(testScript.Value.Tests);
Assert.Equal(file.FullName + ":Test-AssertTrue-Failure", test.UniqueName);
Assert.Equal("Test-AssertTrue-Failure", test.DisplayName);
Assert.Equal("Test!", test.CustomTitle);
Assert.Equal(1, test.Source.LineNumber);
Assert.Equal(1, test.Source.ColumnNumber);
Assert.Equal(file.FullName, test.Source.File.FullName);
Assert.False(testScript.Value.TestSetup.HasValue);
Assert.False(testScript.Value.TestCleanup.HasValue);
}
[Fact]
public void Test_Discover_With_Single_File_Multiple_Tests()
{
// Arrange.
var file = ScriptFiles.HasMultipleTests;
// Act.
var testScript = discoverer.Discover(file);
// Assert.
Assert.True(testScript.HasValue);
Assert.Equal(4, testScript.Value.Tests.Count());
}
[Fact]
public void Test_Discover_With_Single_File_With_Skipped_Test()
{
// Arrange.
var file = ScriptFiles.HasSkippedTest;
// Act.
var testScript = discoverer.Discover(file);
// Assert.
Assert.True(testScript.HasValue);
Assert.Equal(2, testScript.Value.Tests.Count());
var skippedTest = testScript.Value.Tests.First();
Assert.Equal(file.FullName + ":Test-ShouldBeSkipped", skippedTest.UniqueName);
Assert.Equal("Test-ShouldBeSkipped", skippedTest.DisplayName);
Assert.Equal("Should be skipped", skippedTest.CustomTitle);
Assert.True(skippedTest.ShouldSkip);
Assert.Equal("I said so.", skippedTest.SkipReason);
Assert.Equal(1, skippedTest.Source.LineNumber);
Assert.Equal(1, skippedTest.Source.ColumnNumber);
Assert.Equal(file.FullName, skippedTest.Source.File.FullName);
var normalTest = testScript.Value.Tests.Last();
Assert.Equal(file.FullName + ":Test-OneEqualsOne", normalTest.UniqueName);
Assert.Equal("Test-OneEqualsOne", normalTest.DisplayName);
Assert.Equal("Test 1 = 1", normalTest.CustomTitle);
Assert.False(normalTest.ShouldSkip);
Assert.Equal(string.Empty, normalTest.SkipReason);
Assert.Equal(9, normalTest.Source.LineNumber);
Assert.Equal(1, normalTest.Source.ColumnNumber);
Assert.Equal(file.FullName, normalTest.Source.File.FullName);
}
[Fact]
public void Test_Discover_With_Setup_And_Cleanup()
{
// Arrange.
var file = ScriptFiles.HasSetupAndCleanup;
// Act.
var testScript = discoverer.Discover(file);
// Assert.
Assert.True(testScript.HasValue);
Assert.Equal(2, testScript.Value.Tests.Count());
Assert.True(testScript.Value.TestSetup.HasValue);
Assert.True(testScript.Value.TestCleanup.HasValue);
}
[Fact]
public void Test_Discover_With_Multiple_Files()
{
// Arrange.
var files = new[]
{
ScriptFiles.HasOneTest,
ScriptFiles.HasSetupAndCleanup,
ScriptFiles.HasMultipleTests
};
// Act.
var scripts = discoverer.Discover(files).ToList();
// Assert.
Assert.Equal(3, scripts.Count);
Assert.Equal(1, scripts[0].Tests.Count());
Assert.Equal(2, scripts[1].Tests.Count());
Assert.Equal(4, scripts[2].Tests.Count());
}
private readonly PowerShellTestDiscoverer discoverer;
private readonly Mock<ILogger> logger = new Mock<ILogger>();
}
}<file_sep>/PSycheTest.Runners.Framework/Results/TestStatus.cs
namespace PSycheTest.Runners.Framework.Results
{
/// <summary>
/// The possible states of a test.
/// </summary>
public enum TestStatus
{
/// <summary>
/// Indicates that a test has not been run.
/// </summary>
NotExecuted,
/// <summary>
/// Indicates that a test has completed successfully.
/// </summary>
Passed,
/// <summary>
/// Indicates that a test has failed.
/// </summary>
Failed,
/// <summary>
/// Indicates that a test was skipped.
/// </summary>
Skipped
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.VisualStudio/Core/Monitoring/ProjectFileMonitorTests.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.Shell.Interop;
using Moq;
using PSycheTest.Runners.VisualStudio.Core.Monitoring;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.VisualStudio.Core.Monitoring
{
public class ProjectFileMonitorTests
{
public ProjectFileMonitorTests()
{
serviceProvider.Setup(sp => sp.GetService(typeof(SVsTrackProjectDocuments)))
.Returns(docTracker.Object);
monitor = new ProjectFileMonitor(serviceProvider.Object);
}
[Fact]
public void Test_StartMonitoring()
{
// Act.
monitor.StartMonitoring();
// Assert.
uint cookie;
docTracker.Verify(s => s.AdviseTrackProjectDocumentsEvents(monitor, out cookie));
}
[Fact]
public void Test_StopMonitoring()
{
// Arrange.
uint cookie = 123;
docTracker.Setup(s => s.AdviseTrackProjectDocumentsEvents(monitor, out cookie));
monitor.StartMonitoring();
// Act.
monitor.StopMonitoring();
// Assert.
docTracker.Verify(s => s.UnadviseTrackProjectDocumentsEvents(123));
}
[Fact]
public void Test_OnAfterAddFilesEx()
{
// Arrange.
var projects = Mocks.Of<IVsProject>().Take(3).ToArray();
projectFiles[projects[0]] = new[] { "file1", "file2", "file3" };
projectFiles[projects[1]] = new[] { "file4", "file5" };
projectFiles[projects[2]] = new[] { "file6" };
var args = new List<ProjectFileChangedEventArgs>();
EventHandler<ProjectFileChangedEventArgs> handler = (o, e) => args.Add(e);
monitor.FileChanged += handler;
// Act.
monitor.OnAfterAddFilesEx(projects.Length, projectFiles.Select(pf => pf.Value.Count).Sum(), projects,
new[] { 0, 3, 5 }, projectFiles.SelectMany(pf => pf.Value).ToArray(), new VSADDFILEFLAGS[0]);
// Assert.
Assert.Equal(6, args.Count);
Assert.True(args.All(a => a.ChangeType == FileChangeType.Added));
var firstProjectArgs = Enumerable.Range(0, 3).Select(i => args[i]).ToList();
Assert.True(firstProjectArgs.All(a => a.Project == projects[0]));
Assert.Equal(new[] { "file1", "file2", "file3" }, firstProjectArgs.Select(a => a.FilePath).ToArray());
var secondProjectArgs = Enumerable.Range(3, 2).Select(i => args[i]).ToList();
Assert.True(secondProjectArgs.All(a => a.Project == projects[1]));
Assert.Equal(new[] { "file4", "file5" }, secondProjectArgs.Select(a => a.FilePath).ToArray());
var thirdProjectArgs = Enumerable.Range(5, 1).Select(i => args[i]).ToList();
Assert.True(thirdProjectArgs.All(a => a.Project == projects[2]));
Assert.Equal(new[] { "file6" }, thirdProjectArgs.Select(a => a.FilePath).ToArray());
}
[Fact]
public void Test_OnAfterRemoveFiles()
{
// Arrange.
var projects = Mocks.Of<IVsProject>().Take(3).ToArray();
projectFiles[projects[0]] = new[] { "file1", "file2", "file3" };
projectFiles[projects[1]] = new[] { "file4", "file5" };
projectFiles[projects[2]] = new[] { "file6" };
var args = new List<ProjectFileChangedEventArgs>();
EventHandler<ProjectFileChangedEventArgs> handler = (o, e) => args.Add(e);
monitor.FileChanged += handler;
// Act.
monitor.OnAfterRemoveFiles(projects.Length, projectFiles.Select(pf => pf.Value.Count).Sum(), projects,
new[] { 0, 3, 5 }, projectFiles.SelectMany(pf => pf.Value).ToArray(), new VSREMOVEFILEFLAGS[0]);
// Assert.
Assert.Equal(6, args.Count);
Assert.True(args.All(a => a.ChangeType == FileChangeType.Removed));
var firstProjectArgs = Enumerable.Range(0, 3).Select(i => args[i]).ToList();
Assert.True(firstProjectArgs.All(a => a.Project == projects[0]));
Assert.Equal(new[] { "file1", "file2", "file3" }, firstProjectArgs.Select(a => a.FilePath).ToArray());
var secondProjectArgs = Enumerable.Range(3, 2).Select(i => args[i]).ToList();
Assert.True(secondProjectArgs.All(a => a.Project == projects[1]));
Assert.Equal(new[] { "file4", "file5" }, secondProjectArgs.Select(a => a.FilePath).ToArray());
var thirdProjectArgs = Enumerable.Range(5, 1).Select(i => args[i]).ToList();
Assert.True(thirdProjectArgs.All(a => a.Project == projects[2]));
Assert.Equal(new[] { "file6" }, thirdProjectArgs.Select(a => a.FilePath).ToArray());
}
[Fact]
public void Test_OnAfterRenameFiles()
{
// Arrange.
var project = Mock.Of<IVsProject>();
var oldFiles = new[] { "file1", "file2", "file3" };
var newFiles = new[] { "file1a", "file2a", "file3a" };
var args = new List<ProjectFileChangedEventArgs>();
EventHandler<ProjectFileChangedEventArgs> handler = (o, e) => args.Add(e);
monitor.FileChanged += handler;
// Act.
monitor.OnAfterRenameFiles(1, 3, new[] { project }, new[] { 0 },
oldFiles, newFiles, new VSRENAMEFILEFLAGS[0]);
// Assert.
Assert.Equal(6, args.Count);
Assert.True(args.All(a => a.Project == project));
var removedArgs = Enumerable.Range(0, 3).Select(i => args[i]).ToList();
Assert.True(removedArgs.All(a => a.ChangeType == FileChangeType.Removed));
Assert.Equal(new[] { "file1", "file2", "file3" }, removedArgs.Select(a => a.FilePath).ToArray());
var addedArgs = Enumerable.Range(3, 3).Select(i => args[i]).ToList();
Assert.True(addedArgs.All(a => a.ChangeType == FileChangeType.Added));
Assert.Equal(new[] { "file1a", "file2a", "file3a" }, addedArgs.Select(a => a.FilePath).ToArray());
}
private readonly ProjectFileMonitor monitor;
private readonly IDictionary<IVsProject, ICollection<string>> projectFiles = new Dictionary<IVsProject, ICollection<string>>();
private readonly Mock<IVsTrackProjectDocuments2> docTracker = new Mock<IVsTrackProjectDocuments2>();
private readonly Mock<IServiceProvider> serviceProvider = new Mock<IServiceProvider>();
}
}<file_sep>/Tests.Unit/PSycheTest/Core/SessionStateExtensionsTests.cs
using System.Management.Automation;
using PSycheTest.Core;
using Tests.Support;
using Xunit;
namespace Tests.Unit.PSycheTest.Core
{
public class SessionStateExtensionsTests
{
[Fact]
[UseRunspace]
public void Test_Set_Variable()
{
// Arrange.
var sessionState = new SessionState();
// Act.
sessionState.Variables().aTestVariable = "testing";
// Assert.
Assert.Equal("testing", sessionState.PSVariable.GetValue("aTestVariable"));
}
[Fact]
[UseRunspace]
public void Test_Get_Variable()
{
// Arrange.
var sessionState = new SessionState();
sessionState.PSVariable.Set("aTestVariable", "testing");
// Act.
string value = sessionState.Variables().aTestVariable;
// Assert.
Assert.Equal("testing", value);
}
[Fact]
[UseRunspace]
public void Test_Unset_Variable()
{
// Arrange.
var sessionState = new SessionState();
// Act.
object value = sessionState.Variables().aTestVariable;
// Assert.
Assert.Null(value);
}
}
}<file_sep>/PSycheTest.Runners.Framework/TestScriptEndedEventArgs.cs
using System;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Contains diagnostic information about when a test script has ended.
/// </summary>
public class TestScriptEndedEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of <see cref="TestScriptStartingEventArgs"/>.
/// </summary>
/// <param name="script">The test script that has ended</param>
public TestScriptEndedEventArgs(ITestScript script)
{
Script = script;
}
/// <summary>
/// The test script that has ended.
/// </summary>
public ITestScript Script { get; private set; }
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.VisualStudio/Core/PowerShellTestContainerTests.cs
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestWindow.Extensibility;
using Moq;
using PSycheTest.Runners.Framework.Utilities.InputOutput;
using PSycheTest.Runners.VisualStudio.Core;
using Tests.Support;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.VisualStudio.Core
{
public class PowerShellTestContainerTests : IDisposable
{
public PowerShellTestContainerTests()
{
originalProjectInfoFactory = VisualStudioHierarchyExtensions.ProjectInfoFactory;
VisualStudioHierarchyExtensions.ProjectInfoFactory = p => projects[p];
}
[Fact]
public void Test_Initialization()
{
// Arrange.
var discoverer = Mock.Of<ITestContainerDiscoverer>();
string scriptPath = @".\test.ps1";
var project = Mock.Of<IVsProject>();
projects[project] = Mock.Of<IProjectInfo>(p => p.File == new FileInfo("Project"));
// Act.
var container = new PowerShellTestContainer(
discoverer, scriptPath, project);
// Assert.
Assert.Equal(discoverer, container.Discoverer);
Assert.Equal(@".\test.ps1", container.Source);
Assert.Equal(project, container.Project);
Assert.Empty(container.DebugEngines);
Assert.Equal(FrameworkVersion.None, container.TargetFramework);
Assert.Equal(Architecture.AnyCPU, container.TargetPlatform);
}
[Fact]
public void Test_CompareTo()
{
// Arrange.
var discoverer = Mock.Of<ITestContainerDiscoverer>();
var project = Mock.Of<IVsProject>();
projects[project] = Mock.Of<IProjectInfo>(p => p.File == new FileInfo("Project"));
using (var script = new TemporaryFile().Touch())
{
var container = new PowerShellTestContainer(
discoverer, script.File.FullName, project);
var otherContainer = new PowerShellTestContainer(
discoverer, script.File.FullName, project);
// Act.
int result = container.CompareTo(otherContainer);
// Assert.
Assert.Equal(0, result);
}
}
[Fact]
public void Test_CompareTo_Null()
{
// Arrange.
var discoverer = Mock.Of<ITestContainerDiscoverer>();
var project = Mock.Of<IVsProject>();
projects[project] = Mock.Of<IProjectInfo>();
using (var script = new TemporaryFile().Touch())
{
var container = new PowerShellTestContainer(
discoverer, script.File.FullName, project);
// Act.
int result = container.CompareTo(null);
// Assert.
Assert.Equal(-1, result);
}
}
[Fact]
public void Test_CompareTo_Different_Sources()
{
// Arrange.
var discoverer = Mock.Of<ITestContainerDiscoverer>();
var project = Mock.Of<IVsProject>();
projects[project] = Mock.Of<IProjectInfo>();
using (var script = new TemporaryFile().Touch())
using (var otherScript = new TemporaryFile().Touch())
{
var container = new PowerShellTestContainer(
discoverer, script.File.FullName, project);
var otherContainer = new PowerShellTestContainer(
discoverer, otherScript.File.FullName, project);
// Act.
int result = container.CompareTo(otherContainer);
// Assert.
Assert.NotEqual(0, result);
}
}
[Fact]
public void Test_CompareTo_Different_Projects()
{
// Arrange.
var discoverer = Mock.Of<ITestContainerDiscoverer>();
var project = Mock.Of<IVsProject>();
projects[project] = Mock.Of<IProjectInfo>(p => p.File == new FileInfo("Project1"));
var otherProject = Mock.Of<IVsProject>();
projects[otherProject] = Mock.Of<IProjectInfo>(p => p.File == new FileInfo("Project2"));
using (var script = new TemporaryFile().Touch())
{
var container = new PowerShellTestContainer(
discoverer, script.File.FullName, project);
var otherContainer = new PowerShellTestContainer(
discoverer, script.File.FullName, otherProject);
// Act.
int result = container.CompareTo(otherContainer);
// Assert.
Assert.NotEqual(0, result);
}
}
public void Dispose()
{
VisualStudioHierarchyExtensions.ProjectInfoFactory = originalProjectInfoFactory;
}
private readonly IDictionary<IVsProject, IProjectInfo> projects = new Dictionary<IVsProject, IProjectInfo>();
private readonly Func<IVsProject, IProjectInfo> originalProjectInfoFactory;
}
}<file_sep>/PSycheTest.Runners.Framework/TestExecutionTransaction.cs
using System.IO;
using System.Management.Automation;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Class that manages and resets the appropriate PowerShell execution state between individual tests.
/// </summary>
public class TestExecutionTransaction: ITestExecutionTransaction
{
/// <summary>
/// Initializes a new <see cref="TestExecutionTransaction"/>.
/// </summary>
/// <param name="powershell">The <see cref="PowerShell"/> to manage</param>
/// <param name="locationManager">Manages a test's output</param>
public TestExecutionTransaction(PowerShell powershell, ILocationManager locationManager)
{
_powershell = powershell;
_locationManager = locationManager;
OutputDirectory = locationManager.OutputDirectory;
powershell.Runspace.SessionStateProxy.Path.SetLocation(_locationManager.ScriptLocation.FullName);
}
/// <see cref="ITestExecutionTransaction.OutputDirectory"/>
public DirectoryInfo OutputDirectory { get; private set; }
/// <summary>
/// Cleans up after a test, including clearing errors, etc.
/// </summary>
public void Dispose()
{
_powershell.Commands.Clear();
_powershell.Streams.ClearStreams();
_locationManager.Dispose();
// ResetRunspace resets the global variable table back to the initial state for that runspace
// (as well as cleaning up a few other things). What it doesn't do is clean out function definitions,
// types and format files or unload modules. This allows the API to be much faster. Also note that the
// Runspace has to have been created using an InitialSessionState object, not a RunspaceConfiguration
// instance.
// http://stackoverflow.com/questions/13096061/call-a-powershell-script-in-a-new-clean-powershell-instance-from-within-anothe
_powershell.Runspace.ResetRunspaceState();
}
private readonly ILocationManager _locationManager;
private readonly PowerShell _powershell;
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/TestMapper.cs
using System;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using PSycheTest.Runners.Framework;
using PSycheTest.Runners.Framework.Results;
using VSTestResult = Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult;
using PSTestResult = PSycheTest.Runners.Framework.Results.TestResult;
namespace PSycheTest.Runners.VisualStudio.Core
{
/// <summary>
/// Maps <see cref="TestFunction"/>s to <see cref="TestCase"/>s.
/// </summary>
internal class TestMapper
{
/// <summary>
/// Maps a <see cref="TestFunction"/> to a <see cref="TestCase"/>.
/// </summary>
/// <param name="test">The test to map</param>
/// <returns>A Visual Studio <see cref="TestCase"/></returns>
public TestCase Map(ITestFunction test)
{
return new TestCase(test.UniqueName, VSTestExecutor.ExecutorUri, test.Source.File.FullName)
{
CodeFilePath = test.Source.File.FullName,
DisplayName = test.DisplayName,
LineNumber = test.Source.LineNumber
};
}
/// <summary>
/// Maps a <see cref="TestStatus"/> to a <see cref="TestOutcome"/>.
/// </summary>
/// <param name="status">The status to map</param>
/// <returns>A Visual Studio <see cref="TestOutcome"/></returns>
public TestOutcome Map(TestStatus status)
{
switch (status)
{
case TestStatus.NotExecuted:
return TestOutcome.None;
case TestStatus.Passed:
return TestOutcome.Passed;
case TestStatus.Failed:
return TestOutcome.Failed;
case TestStatus.Skipped:
return TestOutcome.Skipped;
}
return TestOutcome.None;
}
/// <summary>
/// Maps a <see cref="Framework.Results.TestResult"/> to a <see cref="Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult"/>.
/// </summary>
/// <param name="testCase">An existing <see cref="TestCase"/></param>
/// <param name="result">The result to map</param>
/// <returns>A Visual Studio <see cref="Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult"/></returns>
public VSTestResult Map(TestCase testCase, PSTestResult result)
{
var vsResult = new VSTestResult(testCase)
{
Outcome = Map(result.Status),
Duration = result.Duration.HasValue ? result.Duration.Value : TimeSpan.Zero,
};
foreach (var artifact in result.Artifacts)
{
var attachmentSet = new AttachmentSet(artifact, "Attachment");
attachmentSet.Attachments.Add(new UriDataAttachment(artifact, string.Empty));
vsResult.Attachments.Add(attachmentSet);
}
var failedResult = result as FailedResult;
if (failedResult != null)
{
vsResult.ErrorMessage = failedResult.Reason.Message;
vsResult.ErrorStackTrace = failedResult.Reason.StackTrace;
}
return vsResult;
}
}
}<file_sep>/Tests.Support/UsePowerShellAttribute.cs
using System;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Reflection;
using System.Threading;
using PSycheTest.Runners.Framework.Extensions;
using Xunit;
namespace Tests.Support
{
/// <summary>
/// Runs a test with a PowerShell environment running.
/// </summary>
public class UsePowerShellAttribute : BeforeAfterTestAttribute
{
/// <summary>
/// Adds cmdlets for the given implementing types to the current runspace config.
/// </summary>
public Type[] WithCmdlets { get; set; }
public override void Before(MethodInfo methodUnderTest)
{
_powershell = new ThreadLocal<PowerShell>(() => PowerShell.Create(RunspaceMode.NewRunspace));
if (WithCmdlets != null)
{
var currentRunspaceConfig = _powershell.Value.Runspace.RunspaceConfiguration;
currentRunspaceConfig.Cmdlets.Append(
WithCmdlets
.Select(t => CmdletExtensions.FromCmdletType(t))
.Select(c => new CmdletConfigurationEntry(c.Name, c.ImplementingType, c.HelpFileName)));
currentRunspaceConfig.Cmdlets.Update();
}
}
public override void After(MethodInfo methodUnderTest)
{
_powershell.Value.Dispose();
_powershell.Dispose();
}
/// <summary>
/// The current <see cref="PowerShell"/> instance.
/// </summary>
public static PowerShell Shell
{
get { return _powershell.Value; }
}
private static ThreadLocal<PowerShell> _powershell;
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.VisualStudio/Core/Utilities/CaseInsensitiveEqualityComparerTests.cs
using PSycheTest.Runners.VisualStudio.Core.Utilities;
using Xunit;
using Xunit.Extensions;
namespace Tests.Unit.PSycheTest.Runners.VisualStudio.Core.Utilities
{
public class CaseInsensitiveEqualityComparerTests
{
[Theory]
[InlineData(true, "abcde", "abcde")]
[InlineData(true, "abcde", "abcDE")]
[InlineData(true, "ABCde", "abcde")]
[InlineData(false, "abcde", "abc")]
[InlineData(false, "abcde", null)]
public void Test_Equals(bool expected, string first, string second)
{
// Act.
bool actual = comparer.Equals(first, second);
// Assert.
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(@"ABc_De")]
[InlineData(@"abC_DE")]
public void Test_GetHashCode(string input)
{
// Arrange.
var expected = comparer.GetHashCode(@"abc_de");
// Act.
int actual = comparer.GetHashCode(input);
// Assert.
Assert.Equal(expected, actual);
}
private readonly CaseInsensitiveEqualityComparer comparer = new CaseInsensitiveEqualityComparer();
}
}<file_sep>/PSycheTest/AssertTrueCmdlet.cs
using System.Management.Automation;
using PSycheTest.Exceptions;
namespace PSycheTest
{
/// <summary>
/// Cmdlet that verifies that a statement is true.
/// </summary>
[Cmdlet(VerbsLifecycle.Assert, "True")]
public class AssertTrueCmdlet : AssertConditionCmdlet
{
/// <see cref="AssertionCmdletBase.Assert"/>
protected override void Assert()
{
if (!Condition)
throw new ExpectedActualException(true, false, Message ?? "Assert-True Failure");
}
}
}<file_sep>/PSycheTest.Runners.Framework/PSScriptParser.cs
using System.IO;
using System.Management.Automation.Language;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// An <see cref="IScriptParser"/> that uses <see cref="System.Management.Automation.Language.Parser"/>.
/// </summary>
internal class PSScriptParser : IScriptParser
{
/// <see cref="IScriptParser.Parse(string)"/>
public ParseResult Parse(string script)
{
Token[] tokens;
ParseError[] errors;
var ast = Parser.ParseInput(script, out tokens, out errors);
return new ParseResult(ast, tokens, errors);
}
/// <see cref="IScriptParser.Parse(FileInfo)"/>
public ParseResult Parse(FileInfo scriptFile)
{
Token[] tokens;
ParseError[] errors;
var ast = Parser.ParseFile(scriptFile.FullName, out tokens, out errors);
return new ParseResult(ast, tokens, errors);
}
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/PSycheTestRunSettings.cs
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
namespace PSycheTest.Runners.VisualStudio.Core
{
/// <summary>
/// Represents test run settings.
/// </summary>
[XmlRoot(SettingsProviderName)]
public class PSycheTestRunSettings : TestRunSettings, IXmlSerializable, IPSycheTestRunSettings
{
/// <summary>
/// Initializes a new <see cref="PSycheTestRunSettings"/> instance.
/// </summary>
public PSycheTestRunSettings()
: base(SettingsProviderName)
{
}
/// <summary>
/// Any modules to initially import specified in the settings file.
/// </summary>
[XmlIgnore]
public ICollection<string> Modules { get { return _modules; } }
/// <see cref="TestRunSettings.ToXml"/>
public override XmlElement ToXml()
{
var stringWriter = new StringWriter();
_serializer.Serialize(stringWriter, this);
var xml = stringWriter.ToString();
var document = new XmlDocument();
document.LoadXml(xml);
return document.DocumentElement;
}
/// <see cref="IXmlSerializable.GetSchema"/>
public XmlSchema GetSchema()
{
return null;
}
/// <see cref="IXmlSerializable.ReadXml"/>
public void ReadXml(XmlReader reader)
{
var xml = XDocument.Load(reader);
var psycheTestSettings = xml.Descendants(XName.Get(SettingsProviderName)).FirstOrDefault();
if (psycheTestSettings != null)
{
var modulesElement = psycheTestSettings.Element(XName.Get("Modules"));
if (modulesElement != null)
{
var moduleElements = modulesElement.Elements(XName.Get("Module"));
foreach (var moduleElement in moduleElements)
_modules.Add(moduleElement.Value);
}
}
}
/// <see cref="IXmlSerializable.WriteXml"/>
public void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("Modules");
foreach (var module in _modules)
writer.WriteElementString("Module", module);
writer.WriteEndElement();
}
/// <summary>
/// The name of the settings provider.
/// </summary>
public const string SettingsProviderName = "PSycheTest";
private readonly IList<string> _modules = new List<string>();
private static readonly XmlSerializer _serializer = new XmlSerializer(typeof(PSycheTestRunSettings));
}
}<file_sep>/PSycheTest/AssertNullCmdlet.cs
using System.Management.Automation;
using PSycheTest.Exceptions;
namespace PSycheTest
{
/// <summary>
/// Cmdlet that verifies that a value is null.
/// </summary>
[Cmdlet(VerbsLifecycle.Assert, "Null")]
public class AssertNullCmdlet : AssertionCmdletBase
{
/// <summary>
/// The actual value.
/// </summary>
[Parameter(Mandatory = true, Position = 0)]
[AllowNull]
public object Actual { get; set; }
/// <see cref="AssertionCmdletBase.Assert"/>
protected override void Assert()
{
if (Actual != null)
throw new ExpectedActualException(null, Actual, Message ?? "Assert-Null Failure");
}
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Monitoring/SolutionMonitor.cs
using System;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using PSycheTest.Runners.VisualStudio.Core.Utilities;
namespace PSycheTest.Runners.VisualStudio.Core.Monitoring
{
/// <summary>
/// Monitors a solution for various events.
/// </summary>
[Export(typeof(ISolutionMonitor))]
public class SolutionMonitor : IVsSolutionEvents, IVsSolutionLoadEvents, ISolutionMonitor
{
/// <summary>
/// Initializes a new <see cref="SolutionMonitor"/>.
/// </summary>
/// <param name="serviceProvider">Used to retrieve the current solution</param>
[ImportingConstructor]
public SolutionMonitor([Import(typeof(SVsServiceProvider))]IServiceProvider serviceProvider)
{
ValidateArg.NotNull(serviceProvider, "serviceProvider");
_currentSolution = serviceProvider.GetService<IVsSolution, SVsSolution>();
}
/// <see cref="ISolutionMonitor.SolutionChanged"/>
public event EventHandler<SolutionChangedEventArgs> SolutionChanged;
private void OnSolutionChanged(IVsSolution solution, SolutionChangeType changeType)
{
var localEvent = SolutionChanged;
if (localEvent != null)
localEvent(this, new SolutionChangedEventArgs(solution, changeType));
}
/// <see cref="ISolutionMonitor.ProjectChanged"/>
public event EventHandler<ProjectChangedEventArgs> ProjectChanged;
private void OnProjectChanged(IVsSolution solution, IVsProject project, ProjectChangeType changeType)
{
var localEvent = ProjectChanged;
if (localEvent != null)
localEvent(this, new ProjectChangedEventArgs(solution, project, changeType));
}
/// <see cref="ISolutionMonitor.StartMonitoring"/>
public void StartMonitoring()
{
if (_currentSolution == null)
return;
// Subscribe to solution events.
int result = _currentSolution.AdviseSolutionEvents(this, out _cookie);
ErrorHandler.ThrowOnFailure(result); // Throw on failure.
}
/// <see cref="ISolutionMonitor.StopMonitoring"/>
public void StopMonitoring()
{
if (_currentSolution == null || _cookie == VSConstants.VSCOOKIE_NIL)
return;
// Unsubscribe from solution events.
int result = _currentSolution.UnadviseSolutionEvents(_cookie);
ErrorHandler.Succeeded(result); // Ignore failure.
_cookie = VSConstants.VSCOOKIE_NIL; // Clear cookie value.
}
/// <see cref="IVsSolutionEvents.OnAfterLoadProject"/>
public int OnAfterLoadProject(IVsHierarchy pStubHierarchy, IVsHierarchy pRealHierarchy)
{
var project = pRealHierarchy as IVsProject;
if (project != null)
OnProjectChanged(_currentSolution, project, ProjectChangeType.Loaded);
return VSConstants.S_OK;
}
/// <see cref="IVsSolutionEvents.OnAfterLoadProject"/>
public int OnBeforeUnloadProject(IVsHierarchy pRealHierarchy, IVsHierarchy pStubHierarchy)
{
var project = pRealHierarchy as IVsProject;
if (project != null)
OnProjectChanged(_currentSolution, project, ProjectChangeType.Unloaded);
return VSConstants.S_OK;
}
/// <see cref="IVsSolutionEvents.OnAfterLoadProject"/>
public int OnAfterCloseSolution(object pUnkReserved)
{
OnSolutionChanged(_currentSolution, SolutionChangeType.Unloaded);
return VSConstants.S_OK;
}
/// <see cref="IVsSolutionLoadEvents.OnAfterBackgroundSolutionLoadComplete"/>
public int OnAfterBackgroundSolutionLoadComplete()
{
OnSolutionChanged(_currentSolution, SolutionChangeType.Loaded);
return VSConstants.S_OK;
}
#region Unused Solution Events
/// <see cref="IVsSolutionEvents.OnAfterLoadProject"/>
public int OnAfterOpenProject(IVsHierarchy pHierarchy, int fAdded)
{
return VSConstants.S_OK;
}
/// <see cref="IVsSolutionEvents.OnAfterLoadProject"/>
public int OnQueryCloseProject(IVsHierarchy pHierarchy, int fRemoving, ref int pfCancel)
{
return VSConstants.S_OK;
}
/// <see cref="IVsSolutionEvents.OnAfterLoadProject"/>
public int OnBeforeCloseProject(IVsHierarchy pHierarchy, int fRemoved)
{
return VSConstants.S_OK;
}
/// <see cref="IVsSolutionEvents.OnAfterLoadProject"/>
public int OnQueryUnloadProject(IVsHierarchy pRealHierarchy, ref int pfCancel)
{
return VSConstants.S_OK;
}
/// <see cref="IVsSolutionEvents.OnQueryCloseSolution"/>
public int OnQueryCloseSolution(object pUnkReserved, ref int pfCancel)
{
return VSConstants.S_OK;
}
/// <see cref="IVsSolutionEvents.OnAfterLoadProject"/>
public int OnBeforeCloseSolution(object pUnkReserved)
{
return VSConstants.S_OK;
}
/// <see cref="IVsSolutionEvents.OnAfterLoadProject"/>
public int OnAfterOpenSolution(object pUnkReserved, int fNewSolution)
{
return VSConstants.S_OK;
}
/// <see cref="IVsSolutionLoadEvents.OnBeforeOpenSolution"/>
public int OnBeforeOpenSolution(string pszSolutionFilename)
{
return VSConstants.S_OK;
}
/// <see cref="IVsSolutionLoadEvents.OnBeforeBackgroundSolutionLoadBegins"/>
public int OnBeforeBackgroundSolutionLoadBegins()
{
return VSConstants.S_OK;
}
/// <see cref="IVsSolutionLoadEvents.OnQueryBackgroundLoadProjectBatch"/>
public int OnQueryBackgroundLoadProjectBatch(out bool pfShouldDelayLoadToNextIdle)
{
pfShouldDelayLoadToNextIdle = false;
return VSConstants.S_OK;
}
/// <see cref="IVsSolutionLoadEvents.OnBeforeLoadProjectBatch"/>
public int OnBeforeLoadProjectBatch(bool fIsBackgroundIdleBatch)
{
return VSConstants.S_OK;
}
/// <see cref="IVsSolutionLoadEvents.OnAfterLoadProjectBatch"/>
public int OnAfterLoadProjectBatch(bool fIsBackgroundIdleBatch)
{
return VSConstants.S_OK;
}
#endregion Unused Solution Events
private uint _cookie = VSConstants.VSCOOKIE_NIL;
private readonly IVsSolution _currentSolution;
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.Framework/Results/FailedResultTests.cs
using System;
using PSycheTest.Runners.Framework.Results;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.Framework.Results
{
public class FailedResultTests
{
[Fact]
public void Test_FailedResult()
{
// Act.
var result = new FailedResult(
TimeSpan.FromMilliseconds(13),
new ExceptionScriptError(new InvalidOperationException()));
// Assert.
Assert.Equal(TimeSpan.FromMilliseconds(13), result.Duration);
Assert.IsType<InvalidOperationException>(result.Reason.Exception);
Assert.Equal(TestStatus.Failed, result.Status);
}
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.VisualStudio/VSTestExecutorTests.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Moq;
using PSycheTest.Runners.Framework;
using PSycheTest.Runners.Framework.Utilities.InputOutput;
using PSycheTest.Runners.VisualStudio;
using PSycheTest.Runners.VisualStudio.Core;
using Tests.Support;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.VisualStudio
{
public class VSTestExecutorTests : IDisposable
{
public VSTestExecutorTests()
{
modulePath = new TemporaryDirectory();
testSettings.SetupGet(ts => ts.Modules).Returns(new string[0]);
var settingsService = new Mock<IPSycheTestSettingsService>();
settingsService.SetupGet(ss => ss.Settings).Returns(testSettings.Object);
runContext = Mock.Of<IRunContext>(rc =>
rc.SolutionDirectory == modulePath.Directory.FullName &&
rc.TestRunDirectory == Directory.GetCurrentDirectory() &&
rc.RunSettings == Mock.Of<IRunSettings>(rs =>
rs.GetSettings(PSycheTestRunSettings.SettingsProviderName) ==
settingsService.As<ISettingsProvider>().Object));
vsExecutor = new VSTestExecutor(_ => executor.Object, _ => discoverer.Object);
executor.SetupProperty(e => e.OutputDirectory);
executor.Setup(e => e.ExecuteAsync(
It.IsAny<IEnumerable<ITestScript>>(),
It.IsAny<Predicate<ITestFunction>>(),
It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<object>(null));
discoverer.Setup(d => d.Discover(It.IsAny<IEnumerable<FileInfo>>()))
.Returns((IEnumerable<FileInfo> files) =>
files.Select(f => Mock.Of<ITestScript>(ts => ts.Source == f)).ToList());
}
[Fact]
public void Test_RunTests_From_Sources()
{
// Arrange.
var sources = new[] { @"C:\test1.ps1", @"C:\test2.ps1" };
// Act.
vsExecutor.RunTests(sources, runContext, frameworkHandle.Object);
// Assert.
discoverer.Verify(d => d.Discover(It.Is<IEnumerable<FileInfo>>(fs =>
fs.Select(f => f.FullName).SequenceEqual(sources))));
executor.Verify(e => e.ExecuteAsync(It.Is<IEnumerable<ITestScript>>(ts =>
ts.Select(t => t.Source.FullName).SequenceEqual(new[] { @"C:\test1.ps1", @"C:\test2.ps1" })),
It.IsAny<Predicate<ITestFunction>>(),
It.IsAny<CancellationToken>()), Times.Once());
}
[Fact]
public void Test_RunTests_From_TestCases()
{
// Arrange.
var sources = new[] { @"C:\test1.ps1", @"C:\test2.ps1" };
var testCases = sources.Select(source => new TestCase(source, executorUri, source)).ToList();
// Act.
vsExecutor.RunTests(testCases, runContext, frameworkHandle.Object);
// Assert.
executor.Verify(e => e.ExecuteAsync(It.Is<IEnumerable<ITestScript>>(ts =>
ts.Select(t => t.Source.FullName).SequenceEqual(sources)),
It.IsAny<Predicate<ITestFunction>>(),
It.IsAny<CancellationToken>()), Times.Once());
}
[Fact]
public void Test_RunTests_From_TestCases_Multiple_Tests_Per_Script()
{
// Arrange.
var sources = new[] { @"C:\test1.ps1", @"C:\test2.ps1" };
var testCases = sources
.SelectMany(
source => Enumerable.Range(1, 2),
(source, index) => new TestCase(source + ":" + index, executorUri, source)).ToList();
// Act.
vsExecutor.RunTests(testCases, runContext, frameworkHandle.Object);
// Assert.
executor.Verify(e => e.ExecuteAsync(It.Is<IEnumerable<ITestScript>>(ts =>
ts.Select(t => t.Source.FullName).SequenceEqual(sources)),
It.IsAny<Predicate<ITestFunction>>(),
It.IsAny<CancellationToken>()), Times.Once());
}
[Fact]
public void Test_Modules()
{
// Arrange.
testSettings.SetupGet(ts => ts.Modules).Returns(new[] { "Module1.psd1", "Module2.psd2" });
executor.SetupGet(e => e.InitialModules).Returns(new List<string>());
var sources = new[] { @"C:\test1.ps1" };
// Act.
vsExecutor.RunTests(sources, runContext, frameworkHandle.Object);
// Assert.
Assert.Equal(new[] { "Module1.psd1", "Module2.psd2" }, executor.Object.InitialModules.ToArray());
}
public void Dispose()
{
modulePath.Dispose();
}
private readonly VSTestExecutor vsExecutor;
private readonly Mock<IFrameworkHandle> frameworkHandle = new Mock<IFrameworkHandle>();
private readonly IRunContext runContext;
private readonly Mock<IPSycheTestRunSettings> testSettings = new Mock<IPSycheTestRunSettings> { DefaultValue = DefaultValue.Empty };
private readonly Mock<IPowerShellTestExecutor> executor = new Mock<IPowerShellTestExecutor>();
private readonly Mock<IPowerShellTestDiscoverer> discoverer = new Mock<IPowerShellTestDiscoverer>();
private readonly TemporaryDirectory modulePath;
private static readonly Uri executorUri = new Uri("executor://test");
}
}<file_sep>/PSycheTest.Runners.Framework/Utilities/InputOutput/TemporaryDirectory.cs
using System;
using System.IO;
namespace PSycheTest.Runners.Framework.Utilities.InputOutput
{
/// <summary>
/// Class that manages a temporary directory and aids in clean up
/// after its use.
/// </summary>
public class TemporaryDirectory : IDisposable
{
/// <summary>
/// Initializes a new <see cref="TemporaryDirectory"/> in the given directory.
/// </summary>
/// <param name="parent">The parent directory to use</param>
/// <param name="name">The name of the directory</param>
public TemporaryDirectory(DirectoryInfo parent = null, string name = null)
{
string parentPath = parent != null ? parent.FullName : Path.GetTempPath();
name = name ?? Path.GetRandomFileName();
Directory = new DirectoryInfo(Path.Combine(parentPath, name));
Directory.Create();
}
/// <summary>
/// The actual temporary directory.
/// </summary>
public DirectoryInfo Directory { get; private set; }
#region IDisposable Implementation
/// <summary>
/// Implements the actual disposal logic. Subclasses should
/// override this method to clean up resources.
/// </summary>
/// <param name="disposing">Whether the class is disposing from the Dispose() method</param>
protected void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (Directory.Exists)
Directory.Delete(true);
_isDisposed = true;
}
}
/// <see cref="IDisposable.Dispose"/>
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>
/// Use C# destructor syntax for finalization code.
/// This destructor will run only if the Dispose method
/// does not get called.
/// It gives your base class the opportunity to finalize.
/// Do not provide destructors in types derived from this class.
/// </summary>
~TemporaryDirectory()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
private bool _isDisposed;
#endregion IDisposable Implementation
}
}<file_sep>/Tests.Support/PowerShellFixture.cs
using System;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using PSycheTest.Runners.Framework.Extensions;
using PSycheTest.Runners.Framework.Utilities.Collections;
namespace Tests.Support
{
/// <summary>
/// Allows use of the same <see cref="PowerShell"/> for a fixture.
/// </summary>
public class PowerShellFixture : IDisposable
{
/// <summary>
/// Adds cmdlets for the given implementing types to the current
/// <see cref="System.Management.Automation.Runspaces.RunspaceConfiguration"/>.
/// </summary>
public void AddCmdlets(Type firstCmdlet, params Type[] otherCmdlets)
{
var cmdlets = firstCmdlet.ToEnumerable().Concat(otherCmdlets);
var currentRunspaceConfig = Shell.Runspace.RunspaceConfiguration;
currentRunspaceConfig.Cmdlets
.Append(cmdlets
.Select(t => t.FromCmdletType())
.Select(c => new CmdletConfigurationEntry(c.Name, c.ImplementingType, c.HelpFileName)));
currentRunspaceConfig.Cmdlets.Update();
}
/// <summary>
/// Accesses the current <see cref="PowerShell"/>.
/// </summary>
public PowerShell Shell { get { return _powershell.Value; } }
private readonly Lazy<PowerShell> _powershell =
new Lazy<PowerShell>(() => PowerShell.Create(RunspaceMode.NewRunspace));
public void Dispose()
{
Shell.Dispose();
}
}
}<file_sep>/PSycheTest.Runners.Framework/Extensions/PowerShellExtensions.cs
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Threading.Tasks;
namespace PSycheTest.Runners.Framework.Extensions
{
/// <summary>
/// Contains extension methods for <see cref="PowerShell"/>.
/// </summary>
public static class PowerShellExtensions
{
/// <summary>
/// Invokes a PowerShell pipeline asynchronously
/// </summary>
/// <param name="powerShell">The <see cref="PowerShell"/> instance to invoke</param>
/// <param name="taskScheduler">An optional <see cref="TaskScheduler"/></param>
/// <returns>A <see cref="Task"/> representing the asynchronous invocation</returns>
public static async Task<IReadOnlyCollection<ErrorRecord>> InvokeAsync(this PowerShell powerShell, TaskScheduler taskScheduler = null)
{
await Task.Factory.FromAsync(
powerShell.BeginInvoke(),
r => powerShell.EndInvoke(r),
TaskCreationOptions.None, taskScheduler ?? TaskScheduler.Default).ConfigureAwait(false);
return powerShell.Streams.Error.ToList();
}
}
}<file_sep>/PSycheTest/TestAttribute.cs
using System;
namespace PSycheTest
{
/// <summary>
/// Attribute that identifies a test case.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class TestAttribute : Attribute
{
/// <summary>
/// Initializes a new <see cref="TestAttribute"/>.
/// </summary>
public TestAttribute()
{
Title = string.Empty;
}
/// <summary>
/// A test case's optional title.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Indicates that a test should be skipped and what the reason for that is.
/// </summary>
public string SkipBecause { get; set; }
}
}<file_sep>/PSycheTest.Runners.Framework/ILogger.cs
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// An interface for logging messages.
/// </summary>
public interface ILogger
{
/// <summary>
/// Logs an informational message.
/// </summary>
/// <param name="message">The informational message</param>
/// <param name="arguments">Any message format arguments</param>
void Info(string message, params object[] arguments);
/// <summary>
/// Logs a warning message.
/// </summary>
/// <param name="message">The warning message</param>
/// <param name="arguments">Any message format arguments</param>
void Warn(string message, params object[] arguments);
/// <summary>
/// Logs an error message.
/// </summary>
/// <param name="message">The error message</param>
/// <param name="arguments">Any message format arguments</param>
void Error(string message, params object[] arguments);
}
}<file_sep>/PSycheTest/Exceptions/AssertionException.cs
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace PSycheTest.Exceptions
{
/// <summary>
/// Base exception for all assertions.
/// </summary>
[Serializable]
public class AssertionException : Exception
{
/// <summary>
/// A user provided message
/// </summary>
public string UserMessage { get; protected set; }
/// <see cref="Exception.Message"/>
public override string Message
{
get
{
return UserMessage;
}
}
/// <summary>
/// Initializes a new <see cref="AssertionException"/>.
/// </summary>
public AssertionException() { }
/// <summary>
/// Initializes a new <see cref="AssertionException"/>.
/// </summary>
/// <param name="userMessage">A user provided message</param>
public AssertionException(string userMessage)
: base(userMessage)
{
UserMessage = userMessage;
}
/// <summary>
/// Initializes a new <see cref="AssertionException"/>.
/// </summary>
/// <param name="userMessage">A user provided message</param>
/// <param name="innerException">The exception that caused this exception</param>
protected AssertionException(string userMessage, Exception innerException)
: base(userMessage, innerException)
{
}
/// <see cref="Exception(SerializationInfo,StreamingContext)"/>
protected AssertionException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
UserMessage = info.GetString("UserMessage");
}
/// <see cref="Exception.GetObjectData"/>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
info.AddValue("UserMessage", UserMessage);
base.GetObjectData(info, context);
}
}
}<file_sep>/PSycheTest/AssertEqualCmdlet.cs
using System.Management.Automation;
using PSycheTest.Exceptions;
namespace PSycheTest
{
/// <summary>
/// Cmdlet that verifies that an expected value matches an actual value.
/// </summary>
[Cmdlet(VerbsLifecycle.Assert, "Equal")]
public class AssertEqualCmdlet : AssertionCmdletBase
{
/// <summary>
/// The expected value.
/// </summary>
[Parameter(Mandatory = true, Position = 0)]
public object Expected { get; set; }
/// <summary>
/// The actual value.
/// </summary>
[Parameter(Mandatory = true, Position = 1)]
public object Actual { get; set; }
/// <see cref="AssertionCmdletBase.Assert"/>
protected override void Assert()
{
if (!Equals(Expected, Actual))
throw new ExpectedActualException(Expected, Actual, Message ?? "Assert-Equal Failure");
}
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Monitoring/IProjectFileMonitor.cs
using System;
namespace PSycheTest.Runners.VisualStudio.Core.Monitoring
{
/// <summary>
/// Interface for an object that monitor project file changes.
/// </summary>
public interface IProjectFileMonitor
{
/// <summary>
/// Event raised when a file is changed.
/// </summary>
event EventHandler<ProjectFileChangedEventArgs> FileChanged;
/// <summary>
/// Begins monitoring a project for file changes.
/// </summary>
void StartMonitoring();
/// <summary>
/// Stops monitoring a project for file changes.
/// </summary>
void StopMonitoring();
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Monitoring/ProjectFileChangedEventArgs.cs
using System;
using Microsoft.VisualStudio.Shell.Interop;
namespace PSycheTest.Runners.VisualStudio.Core.Monitoring
{
/// <summary>
/// Contains information about file changes.
/// </summary>
public sealed class ProjectFileChangedEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of <see cref="ProjectFileChangedEventArgs"/>.
/// </summary>
/// <param name="project">The file's parent project</param>
/// <param name="filePath">The path of the affected file</param>
/// <param name="changeType">The type of change</param>
public ProjectFileChangedEventArgs(IVsProject project, string filePath, FileChangeType changeType)
{
Project = project;
FilePath = filePath;
ChangeType = changeType;
}
/// <summary>
/// The file's parent project.
/// </summary>
public IVsProject Project { get; private set; }
/// <summary>
/// The path of the affected file.
/// </summary>
public string FilePath { get; private set; }
/// <summary>
/// The type of change.
/// </summary>
public FileChangeType ChangeType { get; private set; }
}
}<file_sep>/PSycheTest.Runners.Framework/IScriptParser.cs
using System.IO;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Interface for a parser that creates an abstract syntax tree from a script file.
/// </summary>
internal interface IScriptParser
{
/// <summary>
/// Parses the contents of a string.
/// </summary>
/// <param name="script">A string containing script code</param>
/// <returns>An object containing an abstract syntax tree and any errors</returns>
ParseResult Parse(string script);
/// <summary>
/// Parses the contents of a file.
/// </summary>
/// <param name="scriptFile">A file containing script code</param>
/// <returns>An object containing an abstract syntax tree and any errors</returns>
ParseResult Parse(FileInfo scriptFile);
}
}<file_sep>/Tests.Support/MethodRecorder.cs
using System;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
namespace Tests.Support
{
/// <summary>
/// Proxy that records method invocations.
/// </summary>
public class MethodRecorder<T> : RealProxy
{
/// <summary>
/// Creates a new interceptor that records method invocations.
/// </summary>
public MethodRecorder()
: base(typeof(T))
{
_proxy = new Lazy<T>(() => (T)base.GetTransparentProxy());
}
/// <summary>
/// The underlying proxy.
/// </summary>
public T Proxy
{
get { return _proxy.Value; }
}
/// <summary>
/// The most recent invocation made on the proxy.
/// </summary>
public IMethodCallMessage LastInvocation { get; private set; }
/// <see cref="RealProxy.Invoke"/>
public override IMessage Invoke(IMessage msg)
{
var methodCall = msg as IMethodCallMessage;
LastInvocation = methodCall;
object returnValue = null;
var method = methodCall.MethodBase as MethodInfo;
if (method != null)
{
returnValue = GetDefaultValue(method.ReturnType);
}
return new ReturnMessage(returnValue, new object[0], 0, methodCall.LogicalCallContext, methodCall);
}
/// <summary>
/// If a type is a primitive such as int, returns its default, otherwise
/// null is returned.
/// </summary>
private static object GetDefaultValue(Type type)
{
if (type.IsValueType && type != _voidType) // can't create an instance of Void
return Activator.CreateInstance(type);
return null;
}
private readonly Lazy<T> _proxy;
private static readonly Type _voidType = typeof(void);
}
}
<file_sep>/PSycheTest.Runners.VisualStudio/Core/ISolutionInfo.cs
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.Shell.Interop;
namespace PSycheTest.Runners.VisualStudio.Core
{
/// <summary>
/// Provides information about an <see cref="IVsSolution"/>.
/// </summary>
public interface ISolutionInfo
{
/// <summary>
/// Iterates over the projects in an <see cref="IVsSolution"/>.
/// </summary>
IEnumerable<IVsProject> GetProjects();
/// <summary>
/// Returns the directory a solution is in.
/// </summary>
DirectoryInfo GetDirectory();
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/PowerShellTestContainer.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestWindow.Extensibility;
using Microsoft.VisualStudio.TestWindow.Extensibility.Model;
namespace PSycheTest.Runners.VisualStudio.Core
{
/// <summary>
/// Represents a PowerShell script containing tests.
/// </summary>
public class PowerShellTestContainer : IVSTestContainer
{
/// <summary>
/// Initializes a new <see cref="PowerShellTestContainer"/>.
/// </summary>
/// <param name="containerDiscoverer">The associated discoverer</param>
/// <param name="scriptPath">A string representing the container source, ie. a file path</param>
/// <param name="project">A source's parent project</param>
public PowerShellTestContainer(ITestContainerDiscoverer containerDiscoverer, string scriptPath, IVsProject project)
: this(containerDiscoverer, scriptPath, project, Enumerable.Empty<Guid>()) { }
/// <summary>
/// Initializes a new <see cref="PowerShellTestContainer"/>.
/// </summary>
/// <param name="containerDiscoverer">The associated discoverer</param>
/// <param name="scriptPath">A string representing the container source, ie. a file path</param>
/// <param name="project">A source's parent project</param>
/// <param name="debugEngines">Any debugging engines</param>
public PowerShellTestContainer(ITestContainerDiscoverer containerDiscoverer, string scriptPath, IVsProject project, IEnumerable<Guid> debugEngines)
{
_containerDiscoverer = ValidateArg.NotNull(containerDiscoverer, "containerDiscoverer"); ;
_scriptPath = ValidateArg.NotNull(scriptPath, "scriptPath");
Project = ValidateArg.NotNull(project, "project");
_projectFile = project.Info().File;
TargetFramework = FrameworkVersion.None;
TargetPlatform = Architecture.AnyCPU;
DebugEngines = debugEngines;
_timestamp = GetTimestamp();
}
/// <summary>
/// Initializes a new <see cref="PowerShellTestContainer"/> with an existing instance.
/// </summary>
/// <param name="source">The <see cref="PowerShellTestContainer"/> to copy</param>
private PowerShellTestContainer(PowerShellTestContainer source)
: this(source.Discoverer, source.Source, source.Project)
{
_timestamp = source._timestamp;
}
/// <see cref="IVSTestContainer.Project"/>
public IVsProject Project { get; private set; }
/// <see cref="ITestContainer.Discoverer"/>
public ITestContainerDiscoverer Discoverer
{
get { return _containerDiscoverer; }
}
/// <see cref="ITestContainer.Source"/>
public string Source
{
get { return _scriptPath; }
}
/// <see cref="ITestContainer.DebugEngines"/>
public IEnumerable<Guid> DebugEngines { get; private set; }
/// <see cref="ITestContainer.TargetFramework"/>
public FrameworkVersion TargetFramework { get; private set; }
/// <see cref="ITestContainer.TargetPlatform"/>
public Architecture TargetPlatform { get; private set; }
/// <see cref="ITestContainer.IsAppContainerTestContainer"/>
public bool IsAppContainerTestContainer { get { return false; } }
/// <see cref="ITestContainer.DeployAppContainer"/>
public IDeploymentData DeployAppContainer()
{
return null;
}
/// <see cref="ITestContainer.CompareTo"/>
public int CompareTo(ITestContainer other)
{
var testContainer = other as PowerShellTestContainer;
if (testContainer == null)
return -1;
var sourcesEqual = String.Compare(Source, testContainer.Source, StringComparison.OrdinalIgnoreCase);
if (sourcesEqual != 0)
return sourcesEqual;
var projectsEqual = String.Compare(_projectFile.FullName, testContainer._projectFile.FullName, StringComparison.Ordinal);
if (projectsEqual != 0)
return projectsEqual;
return _timestamp.CompareTo(testContainer._timestamp);
}
/// <see cref="ITestContainer.Snapshot"/>
public ITestContainer Snapshot()
{
return new PowerShellTestContainer(this);
}
/// <summary>
/// Determines a timestamp for the container.
/// </summary>
private DateTime GetTimestamp()
{
if (!String.IsNullOrEmpty(Source) && File.Exists(Source))
return File.GetLastWriteTime(Source);
return DateTime.MinValue;
}
private DateTime _timestamp;
private readonly string _scriptPath;
private readonly FileInfo _projectFile;
private readonly ITestContainerDiscoverer _containerDiscoverer;
}
}<file_sep>/PSycheTest.Runners.Framework/Utilities/Text/StringExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace PSycheTest.Runners.Framework.Utilities.Text
{
/// <summary>
/// Contains general purpose <see cref="string"/> extension methods.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Splits a string into trimmed lines.
/// </summary>
/// <param name="string">The string to split</param>
/// <returns>An enumerable over the trimmed lines in a string</returns>
public static IEnumerable<string> Lines(this string @string)
{
if (String.IsNullOrEmpty(@string))
return Enumerable.Empty<string>();
return @string.Split('\n').Select(line => line.Trim());
}
}
}<file_sep>/Tests.Support/UseRunspaceAttribute.cs
using System.Management.Automation.Runspaces;
using System.Reflection;
using Xunit;
namespace Tests.Support
{
/// <summary>
/// Populates <see cref="Runspace.DefaultRunspace"/> for a test and then restores the original.
/// </summary>
public class UseRunspaceAttribute : BeforeAfterTestAttribute
{
public override void Before(MethodInfo methodUnderTest)
{
_original = Runspace.DefaultRunspace;
Runspace.DefaultRunspace = RunspaceFactory.CreateRunspace();
Runspace.DefaultRunspace.Open();
}
public override void After(MethodInfo methodUnderTest)
{
Runspace.DefaultRunspace.Dispose();
Runspace.DefaultRunspace = _original;
}
private Runspace _original;
}
}<file_sep>/PSycheTest.Runners.Framework/TestLocationManager.cs
using System.IO;
using System.Linq;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Manages a test's output and working directory, including directories.
/// </summary>
public class TestLocationManager : ILocationManager
{
/// <summary>
/// Initializes a new <see cref="TestLocationManager"/> for a test.
/// </summary>
/// <param name="outputDirectory">The root working directory of a test</param>
/// <param name="script">The current test script</param>
/// <param name="test">The current test</param>
public TestLocationManager(DirectoryInfo outputDirectory, ITestScript script, ITestFunction test)
{
_scriptDirectory = new DirectoryInfo(Path.Combine(
outputDirectory.FullName, script.Source.Name));
if (!_scriptDirectory.Exists)
_scriptDirectory.Create();
_testDirectory = _scriptDirectory.CreateSubdirectory(test.DisplayName);
OutputDirectory = _testDirectory;
ScriptLocation = script.Source.Directory;
}
/// <see cref="ILocationManager.OutputDirectory"/>
public DirectoryInfo OutputDirectory { get; private set; }
/// <see cref="ILocationManager.ScriptLocation"/>
public DirectoryInfo ScriptLocation { get; private set; }
/// <summary>
/// Cleans up a test's output.
/// </summary>
public void Dispose()
{
if (_testDirectory.Exists && !_testDirectory.EnumerateFileSystemInfos().Any())
_testDirectory.Delete();
if (_scriptDirectory.Exists && !_scriptDirectory.EnumerateFileSystemInfos().Any())
_scriptDirectory.Delete();
}
private readonly DirectoryInfo _testDirectory;
private readonly DirectoryInfo _scriptDirectory;
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Utilities/Chronology/ITimer.cs
using System;
namespace PSycheTest.Runners.VisualStudio.Core.Utilities.Chronology
{
/// <summary>
/// This interface brings consistency to both the Form and Thread based versions of Windows timers.
/// </summary>
internal interface ITimer
{
/// <summary>
/// Set the timer interval
/// </summary>
TimeSpan Interval { get; set; }
/// <summary>
/// Call to start the timer
/// </summary>
/// <param name="state">Optional user data</param>
/// <exception cref="System.InvalidOperationException">
/// Thrown if the timer has already been started.
/// </exception>
void Start(object state = null);
/// <summary>
/// Attempts to start a timer. Returns false if the timer
/// was already started.
/// </summary>
/// <param name="state">Optional user data</param>
/// <returns>False if the timer was already started</returns>
bool TryStart(object state = null);
/// <summary>
/// Call to stop the timer
/// </summary>
/// <exception cref="System.InvalidOperationException">
/// Thrown if the timer has not yet been started.
/// </exception>
void Stop();
/// <summary>
/// Attempts to stop a timer. Returns false if the timer
/// was already stopped.
/// </summary>
/// <returns>False if the timer was already stopped</returns>
bool TryStop();
/// <summary>
/// Stops a timer if it was already started, and then starts it again.
/// </summary>
/// <param name="state">Optional user data</param>
void Restart(object state = null);
/// <summary>
/// Whether a timer is running.
/// </summary>
bool Started { get; }
/// <summary>
/// This event is raised when the timer has elapsed
/// </summary>
event EventHandler<TimerElapsedEventArgs> Elapsed;
}
/// <summary>
/// Event args for when a timer interval elapses.
/// </summary>
public class TimerElapsedEventArgs : EventArgs
{
/// <summary>
/// Creates new event args.
/// </summary>
/// <param name="signalTime">The time the elapsed event was raised</param>
/// <param name="state">Arbitrary data provided by timer consumers</param>
public TimerElapsedEventArgs(DateTime signalTime, object state)
{
SignalTime = signalTime;
State = state;
}
/// <summary>
/// The time the elapsed event was raised.
/// </summary>
public DateTime SignalTime { get; private set; }
/// <summary>
/// Arbitrary data provided by timer consumers.
/// </summary>
public object State { get; private set; }
}
}
<file_sep>/PSycheTest.Runners.Framework/Results/PassedResult.cs
using System;
using System.Collections.Generic;
namespace PSycheTest.Runners.Framework.Results
{
/// <summary>
/// Represents the result of a test that passed.
/// </summary>
public class PassedResult : TestResult
{
/// <summary>
/// Initializes a new <see cref="PassedResult"/>.
/// </summary>
/// <param name="duration">The time it took a test to execute</param>
/// <param name="artifacts">Any artifacts created during execution</param>
public PassedResult(TimeSpan duration, IEnumerable<Uri> artifacts)
: base(duration, artifacts)
{
}
/// <see cref="TestResult.Status"/>
public override TestStatus Status
{
get { return TestStatus.Passed; }
}
}
}<file_sep>/PSycheTest/AssertContainsCmdlet.cs
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using PSycheTest.Exceptions;
namespace PSycheTest
{
/// <summary>
/// Cmdlet that verifies that a collection contains a given value.
/// </summary>
[Cmdlet(VerbsLifecycle.Assert, "Contains")]
public class AssertContainsCmdlet : AssertionCmdletBase
{
/// <summary>
/// The expected value.
/// </summary>
[Parameter(Mandatory = true, Position = 0)]
public object Expected { get; set; }
/// <summary>
/// The collection to check.
/// </summary>
[Parameter(Mandatory = true, Position = 1)]
[ValidateNotNull]
public IEnumerable<object> Collection { get; set; }
/// <see cref="AssertionCmdletBase.Assert"/>
protected override void Assert()
{
if (!Collection.Contains(Expected))
throw new ContainsException(Expected, Message ?? "Assert-Contains Failure");
}
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Monitoring/ProjectChangeType.cs
namespace PSycheTest.Runners.VisualStudio.Core.Monitoring
{
/// <summary>
/// Contains types of Visual Studio project changes.
/// </summary>
public enum ProjectChangeType
{
/// <summary>
/// Indicates a project was loaded.
/// </summary>
Loaded,
/// <summary>
/// Indicates a project was unloaded.
/// </summary>
Unloaded
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Monitoring/FileChangeType.cs
namespace PSycheTest.Runners.VisualStudio.Core.Monitoring
{
/// <summary>
/// Contains possible file change types.
/// </summary>
public enum FileChangeType
{
/// <summary>
/// Indicates that a file was added.
/// </summary>
Added,
/// <summary>
/// Indicates that a file was deleted.
/// </summary>
Removed,
/// <summary>
/// Indicates that a file was updated.
/// </summary>
Modified
}
}<file_sep>/PSycheTest.AutomationProvider/PSycheTestAutomatedTestDiscoverer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using PSycheTest.Runners.Framework;
using TestCaseAutomator.AutomationProviders.Interfaces;
namespace PSycheTest.AutomationProvider
{
/// <summary>
/// Wraps the core PSycheTest discoverer and creates <see cref="ITestAutomation"/> objects from the
/// discovered tests.
/// </summary>
[Export(typeof(ITestAutomationDiscoverer))]
public class PSycheTestAutomatedTestDiscoverer : ITestAutomationDiscoverer
{
/// <summary>
/// Initializes a new <see cref="PSycheTestAutomatedTestDiscoverer"/>. This constructor is
/// used by MEF.
/// </summary>
[ImportingConstructor]
public PSycheTestAutomatedTestDiscoverer()
: this(() => new PowerShellTestDiscoverer(new NullLogger()))
{
}
/// <summary>
/// Initializes a new <see cref="PSycheTestAutomatedTestDiscoverer"/> with injectable
/// arguments.
/// </summary>
/// <param name="testDiscovererFactory">Creates test discoverers</param>
public PSycheTestAutomatedTestDiscoverer(Func<IPowerShellTestDiscoverer> testDiscovererFactory)
{
_testDiscovererFactory = testDiscovererFactory;
}
/// <see cref="ITestAutomationDiscoverer.SupportedFileExtensions"/>
public IEnumerable<string> SupportedFileExtensions { get { return _extensions; } }
/// <see cref="ITestAutomationDiscoverer.DiscoverAutomatedTests"/>
public IEnumerable<ITestAutomation> DiscoverAutomatedTests(IEnumerable<string> sources)
{
var testDiscoverer = _testDiscovererFactory();
var testScripts = testDiscoverer.Discover(
sources.Where(s => _extensions.Contains(Path.GetExtension(s)))
.Select(f => new FileInfo(f)));
var tests = testScripts.SelectMany(script => script.Tests, (script, test) => new { Test = test, Script = script })
.Select(t => new AutomatedPSycheTest(t.Script, t.Test))
.ToList();
return tests;
}
private readonly Func<IPowerShellTestDiscoverer> _testDiscovererFactory;
private static readonly ICollection<string> _extensions = new HashSet<string> { TestScript.FileExtension };
private class NullLogger : ILogger
{
public void Info(string message, params object[] arguments)
{
}
public void Warn(string message, params object[] arguments)
{
}
public void Error(string message, params object[] arguments)
{
}
}
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Monitoring/SolutionChangedEventArgs.cs
using System;
using Microsoft.VisualStudio.Shell.Interop;
namespace PSycheTest.Runners.VisualStudio.Core.Monitoring
{
/// <summary>
/// Contains information about solution changes.
/// </summary>
public sealed class SolutionChangedEventArgs : EventArgs
{
/// <summary>
/// Initializes new event args.
/// </summary>
/// <param name="solution">The parent solution</param>
/// <param name="changeType">The type of change</param>
public SolutionChangedEventArgs(IVsSolution solution, SolutionChangeType changeType)
{
Solution = solution;
ChangeType = changeType;
}
/// <summary>
/// The parent solution.
/// </summary>
public IVsSolution Solution { get; private set; }
/// <summary>
/// The type of change.
/// </summary>
public SolutionChangeType ChangeType { get; private set; }
}
}<file_sep>/PSycheTest.Runners.Framework/Results/TestResult.cs
using System;
using System.Collections.Generic;
namespace PSycheTest.Runners.Framework.Results
{
/// <summary>
/// Represents a test result.
/// </summary>
public abstract class TestResult
{
/// <summary>
/// Initializes a new <see cref="TestResult"/>.
/// </summary>
/// <param name="duration">The time it took a test to execute</param>
/// <param name="artifacts">Any artifacts created during execution</param>
protected TestResult(TimeSpan? duration, IEnumerable<Uri> artifacts)
{
Duration = duration;
Artifacts = new List<Uri>(artifacts);
}
/// <summary>
/// A value representing a result's state.
/// </summary>
public abstract TestStatus Status { get; }
/// <summary>
/// The time it took a test to execute.
/// </summary>
public TimeSpan? Duration { get; private set; }
/// <summary>
/// Any artifacts from test execution.
/// </summary>
public IEnumerable<Uri> Artifacts { get; private set; }
}
}<file_sep>/PSycheTest/Core/TestExecutionContext.cs
using System;
using System.Collections.Generic;
using System.IO;
namespace PSycheTest.Core
{
/// <summary>
/// Manages test-specific state.
/// </summary>
public class TestExecutionContext
{
/// <summary>
/// The location where test output should be stored.
/// </summary>
public DirectoryInfo OutputDirectory { get; set; }
/// <summary>
/// Any artifact files produced during a test.
/// </summary>
public IEnumerable<Uri> Artifacts { get { return _artifacts; } }
/// <summary>
/// Adds an artifact and copies it to its archival destination if it is a local file.
/// </summary>
/// <param name="artifact">The file to attach</param>
public void AttachArtifact(Uri artifact)
{
if (artifact.IsFile)
{
string source = artifact.OriginalString;
string destination = Path.Combine(OutputDirectory.FullName, Path.GetFileName(source));
File.Copy(source, destination, true);
_artifacts.Add(new Uri(destination));
}
else
{
_artifacts.Add(artifact);
}
}
private readonly IList<Uri> _artifacts = new List<Uri>();
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.Framework/TestScriptTests.cs
using System;
using System.Linq;
using System.Management.Automation.Language;
using PSycheTest;
using PSycheTest.Runners.Framework;
using PSycheTest.Runners.Framework.Results;
using PSycheTest.Runners.Framework.Utilities;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.Framework
{
public class TestScriptTests
{
public TestScriptTests()
{
firstFunction = SyntaxTree.OfFunctionNamed("Test-First", attribute: SyntaxTree.OfAttribute<TestAttribute>());
secondFunction = SyntaxTree.OfFunctionNamed("Test-Second", attribute: SyntaxTree.OfAttribute<TestAttribute>());
scriptBlock = SyntaxTree.OfScript(statements: new[] { firstFunction, secondFunction });
}
[Fact]
public void Test_Results()
{
// Arrange.
var firstTest = new TestFunction(firstFunction);
var secondTest = new TestFunction(secondFunction);
var script = new TestScript(scriptBlock, new[] { firstTest, secondTest },
Option<FunctionDefinitionAst>.None(), Option<FunctionDefinitionAst>.None());
firstTest.AddResult(new PassedResult(TimeSpan.FromMilliseconds(200), Enumerable.Empty<Uri>()));
firstTest.AddResult(new FailedResult(TimeSpan.FromMilliseconds(300), new ExceptionScriptError(new InvalidOperationException())));
secondTest.AddResult(new SkippedResult("Skipped!"));
// Act.
var allResults = script.Results;
// Assert.
Assert.Equal(3, allResults.Count());
}
[Fact]
public void Test_ResultsByTest()
{
// Arrange.
var firstTest = new TestFunction(firstFunction);
var secondTest = new TestFunction(secondFunction);
var script = new TestScript(scriptBlock, new[] { firstTest, secondTest },
Option<FunctionDefinitionAst>.None(), Option<FunctionDefinitionAst>.None());
firstTest.AddResult(new PassedResult(TimeSpan.FromMilliseconds(200), Enumerable.Empty<Uri>()));
firstTest.AddResult(new FailedResult(TimeSpan.FromMilliseconds(300), new ExceptionScriptError(new InvalidOperationException())));
secondTest.AddResult(new SkippedResult("Skipped!"));
// Act.
var groupedResults = script.ResultsByTest;
// Assert.
Assert.Equal(2, groupedResults.Count);
Assert.Equal(2, groupedResults[firstTest].Count());
Assert.Equal(1, groupedResults[secondTest].Count());
}
private readonly FunctionDefinitionAst firstFunction;
private readonly FunctionDefinitionAst secondFunction;
private readonly ScriptBlockAst scriptBlock;
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Utilities/ServiceProviderExtensions.cs
using System;
namespace PSycheTest.Runners.VisualStudio.Core.Utilities
{
/// <summary>
/// Contains extension methods for <see cref="IServiceProvider"/>.
/// </summary>
internal static class ServiceProviderExtensions
{
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <typeparam name="TService">The type of the actual desired service</typeparam>
/// <typeparam name="TRequestKey">The type used to request the service</typeparam>
/// <param name="serviceProvider">A service provider instance</param>
/// <returns>The desired service</returns>
public static TService GetService<TService, TRequestKey>(this IServiceProvider serviceProvider) where TService : class
{
return (TService)serviceProvider.GetService(typeof(TRequestKey));
}
}
}<file_sep>/PSycheTest.Runners.Framework/Results/PSScriptError.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using PSycheTest.Runners.Framework.Utilities.Text;
namespace PSycheTest.Runners.Framework.Results
{
/// <summary>
/// Contains information about an error in a PowerShell script.
/// </summary>
public class PSScriptError : ScriptError
{
/// <summary>
/// Initializes a new <see cref="PSScriptError"/>.
/// </summary>
/// <param name="errorRecord">A PowerShell script error record</param>
/// <param name="testScriptFile">The source script file</param>
public PSScriptError(IErrorRecord errorRecord, FileInfo testScriptFile)
{
_errorRecord = errorRecord;
_testScriptFile = testScriptFile;
_scriptStackTrace = errorRecord.ScriptStackTrace
.Lines()
.Where(line => !String.IsNullOrWhiteSpace(line))
.Select(line => new ScriptStackFrame(line))
.ToList();
}
/// <see cref="ScriptError.StackTrace"/>
public override string Message
{
get { return _errorRecord.Exception.Message; }
}
/// <see cref="ScriptError.StackTrace"/>
public override string StackTrace
{
get
{
var formattedStackTrace = _scriptStackTrace.Select(stackFrame => FormatScriptStackFrame(stackFrame, _testScriptFile));
return String.Format("{1}{0}{2}",
Environment.NewLine,
FilterStackTrace(base.StackTrace),
String.Join(Environment.NewLine, formattedStackTrace));
}
}
private static string FormatScriptStackFrame(ScriptStackFrame stackFrame, FileInfo testScriptFile)
{
var file = stackFrame.File ?? testScriptFile;
return String.Format(StackFrameFormat,
file.Name,
String.IsNullOrEmpty(stackFrame.Function) ? string.Empty : String.Format(":{0}()", stackFrame.Function),
file.FullName,
stackFrame.Line);
}
/// <see cref="ScriptError.FilterStackTrace"/>
protected override string FilterStackTrace(string stackTrace)
{
var filteredStack = stackTrace
.Lines()
.TakeWhile(line => !_stackFilterPrefixes.Any(line.StartsWith));
return String.Join(Environment.NewLine, filteredStack);
}
/// <see cref="ScriptError.Exception"/>
public override Exception Exception
{
get { return _errorRecord.Exception; }
}
private readonly IErrorRecord _errorRecord;
private readonly FileInfo _testScriptFile;
private readonly IEnumerable<ScriptStackFrame> _scriptStackTrace;
private const string StackFrameFormat = "at {0}{1} in {2}:line {3}"; // 0 = file name, 1 = function name, 2 = full file path, 3 = line number
private static readonly IEnumerable<string> _stackFilterPrefixes = new List<string>
{
String.Format("at {0}.Assert", typeof(AssertionCmdletBase).Namespace)
};
private class ScriptStackFrame
{
public ScriptStackFrame(string stackFrame)
{
int commaIndex = stackFrame.IndexOf(",");
var functionName = stackFrame.Substring(3, commaIndex - 3);
Function = functionName == ScriptBlockPlaceHolder ? null : functionName;
int lineDelimiterIndex = stackFrame.IndexOf(": line ");
var fileName = stackFrame.Substring(commaIndex + 1, lineDelimiterIndex - commaIndex - 1).Trim();
File = fileName == NoFilePlaceholder ? null : new FileInfo(fileName);
Line = Int32.Parse(stackFrame.Substring(lineDelimiterIndex + 7));
}
/// <summary>
/// The name of the function or null if error did not occur in a function.
/// </summary>
public string Function { get; private set; }
/// <summary>
/// The script file or null if the file is not available.
/// </summary>
public FileInfo File { get; private set; }
/// <summary>
/// The line number.
/// </summary>
public int Line { get; private set; }
private const string ScriptBlockPlaceHolder = "<ScriptBlock>";
private const string NoFilePlaceholder = "<No file>";
}
}
}<file_sep>/PSycheTest.Runners.Framework/ILocationManager.cs
using System;
using System.IO;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Interface for an object that manages the location of a test's output and current location.
/// </summary>
public interface ILocationManager : IDisposable
{
/// <summary>
/// A test's output directory. If empty after execution of a test, it will be removed.
/// </summary>
DirectoryInfo OutputDirectory { get; }
/// <summary>
/// The actual location of an executing script.
/// </summary>
DirectoryInfo ScriptLocation { get; }
}
}<file_sep>/Tests.Integration/PSycheTest/CmdletTestBase.cs
using System;
using System.Linq.Expressions;
using System.Management.Automation;
using PSycheTest.Runners.Framework.Extensions;
using PSycheTest.Runners.Framework.Utilities.Reflection;
using Tests.Support;
using Xunit;
namespace Tests.Integration.PSycheTest
{
/// <summary>
/// Base for classes which test cmdlets.
/// </summary>
public abstract class CmdletTestBase<TCmdlet> : IUseFixture<PowerShellFixture> where TCmdlet : PSCmdlet
{
public void SetFixture(PowerShellFixture data)
{
Current = data;
Current.Shell.Commands.Clear();
Current.AddCmdlets(typeof(TCmdlet));
}
protected string CmdletName
{
get { return typeof(TCmdlet).CmdletName(); }
}
protected string NameOf<TValue>(Expression<Func<TCmdlet, TValue>> propertyAccessor)
{
return Reflect.PropertyOf(propertyAccessor).Name;
}
protected PowerShell AddCmdlet()
{
return Current.Shell.AddCommand(CmdletName);
}
protected PowerShell AddParameter<TValue>(Expression<Func<TCmdlet, TValue>> propertyAccessor, TValue value)
{
return Current.Shell.AddParameter(NameOf(propertyAccessor), value);
}
protected PowerShellFixture Current { get; private set; }
}
}<file_sep>/PSycheTest.Runners.Framework/TestDiscoveryVisitor.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;
using PSycheTest.Runners.Framework.Utilities;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// And <see cref="AstVisitor"/> that collects all test cases in a script.
/// </summary>
internal class TestDiscoveryVisitor : AstVisitor
{
/// <summary>
/// Initializes a new <see cref="TestDiscoveryVisitor"/>.
/// </summary>
public TestDiscoveryVisitor()
{
TestSetupFunction = Option<FunctionDefinitionAst>.None();
TestCleanupFunction = Option<FunctionDefinitionAst>.None();
}
/// <summary>
/// Collected test functions.
/// </summary>
public IEnumerable<FunctionDefinitionAst> TestFunctions { get { return _testFunctions; } }
/// <summary>
/// An individual test setup function.
/// </summary>
public Option<FunctionDefinitionAst> TestSetupFunction { get; private set; }
/// <summary>
/// An individual test cleanup function.
/// </summary>
public Option<FunctionDefinitionAst> TestCleanupFunction { get; private set; }
/// <see cref="AstVisitor.VisitFunctionDefinition"/>
public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst function)
{
if (HasAttribute<TestAttribute>(function))
{
_testFunctions.Add(function);
return AstVisitAction.SkipChildren;
}
if (HasAttribute<TestSetupAttribute>(function))
{
TestSetupFunction = function;
return AstVisitAction.SkipChildren;
}
if (HasAttribute<TestCleanupAttribute>(function))
{
TestCleanupFunction = function;
return AstVisitAction.SkipChildren;
}
return AstVisitAction.Continue;
}
private static bool HasAttribute<TAttribute>(FunctionDefinitionAst function)
where TAttribute : Attribute
{
if (ReferenceEquals(function.Body.ParamBlock, null))
return false;
var attributeAsts = function.Body.ParamBlock.Attributes;
return attributeAsts.Any(AttributeMatches<TAttribute>);
}
private static bool AttributeMatches<TAttribute>(AttributeAst attributeAst)
where TAttribute :Attribute
{
var attributeType = typeof(TAttribute);
// A corresponding property must exist for each named argument.
var matchingProperties = attributeAst.NamedArguments
.Select(arg => attributeType.GetProperty(arg.ArgumentName, arg.Argument.StaticType));
if (matchingProperties.Any(p => p == null))
return false;
// A constructor must exist with the number of position parameters given.
var constructorArgs = attributeAst.PositionalArguments.Select(arg => arg.StaticType).ToArray();
var matchingConstructor = attributeType.GetConstructor(constructorArgs);
if (matchingConstructor == null)
return false;
return (attributeAst.TypeName.FullName + "Attribute").Equals(attributeType.FullName);
}
private readonly List<FunctionDefinitionAst> _testFunctions = new List<FunctionDefinitionAst>();
}
}<file_sep>/PSycheTest.Runners.Framework/Results/IErrorRecord.cs
using System;
namespace PSycheTest.Runners.Framework.Results
{
/// <summary>
/// Represents a PowerShell script error.
/// </summary>
public interface IErrorRecord
{
/// <summary>
/// The script stack trace for the error.
/// </summary>
string ScriptStackTrace { get; }
/// <summary>
/// The exception that is associated with this error record.
/// </summary>
Exception Exception { get; }
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/IVSTestContainer.cs
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestWindow.Extensibility;
namespace PSycheTest.Runners.VisualStudio.Core
{
/// <summary>
/// Represents a Visual Studio test container.
/// </summary>
public interface IVSTestContainer : ITestContainer
{
/// <summary>
/// A test container's parent project.
/// </summary>
IVsProject Project { get; }
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.Framework/TestExecutionTransactionTests.cs
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using Moq;
using PSycheTest.Runners.Framework;
using PSycheTest.Runners.Framework.Utilities.InputOutput;
using Tests.Support;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.Framework
{
public class TestExecutionTransactionTests
{
[Fact]
public void Test_Transaction_Disposal_Clears_Streams_And_Commands()
{
// Arrange.
using (var runspace = RunspaceFactory.CreateRunspace(InitialSessionState.Create()))
{
runspace.Open();
using (var powershell = PowerShell.Create())
using (var tempDir = new TemporaryDirectory())
{
var transaction = new TestExecutionTransaction(powershell,
Mock.Of<ILocationManager>(m =>
m.OutputDirectory == tempDir.Directory &&
m.ScriptLocation == tempDir.Directory));
powershell.Runspace = runspace;
powershell.Commands.AddCommand("Get-Host");
powershell.Commands.AddCommand("Get-Random");
powershell.Streams.Error.Add(new ErrorRecord(new InvalidOperationException(), "10", ErrorCategory.InvalidOperation, new object()));
// Act.
transaction.Dispose();
// Assert.
Assert.Empty(powershell.Commands.Commands);
Assert.Empty(powershell.Streams.Error);
}
}
}
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.Framework/Results/SkippedResultTests.cs
using PSycheTest.Runners.Framework.Results;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.Framework.Results
{
public class SkippedResultTests
{
[Fact]
public void Test_SkippedResult()
{
// Act.
var result = new SkippedResult("Skipped");
// Assert.
Assert.Null(result.Duration);
Assert.Equal(TestStatus.Skipped, result.Status);
Assert.Equal("Skipped", result.SkipReason);
}
}
}<file_sep>/PSycheTest.Runners.Framework/TestSourceInfo.cs
using System.IO;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Represents where a test came from.
/// </summary>
public class TestSourceInfo
{
/// <summary>
/// Initializes a new instance of <see cref="TestSourceInfo"/>.
/// </summary>
public TestSourceInfo(FileInfo sourceFile, int lineNumber, int columnNumber)
{
File = sourceFile;
LineNumber = lineNumber;
ColumnNumber = columnNumber;
}
/// <summary>
/// The file containing a test.
/// </summary>
public FileInfo File { get; private set; }
/// <summary>
/// The line in a file where a test begins.
/// </summary>
public int LineNumber { get; private set; }
/// <summary>
/// The column in a filer where a test begins.
/// </summary>
public int ColumnNumber { get; private set; }
}
}<file_sep>/PSycheTest.Runners.Framework/Results/ScriptError.cs
using System;
namespace PSycheTest.Runners.Framework.Results
{
/// <summary>
/// Base class for information about an error that occurred while executing a test script.
/// </summary>
public abstract class ScriptError
{
/// <summary>
/// A description of the error.
/// </summary>
public abstract string Message { get; }
/// <summary>
/// The script error stack trace.
/// </summary>
public virtual string StackTrace
{
get { return Exception.StackTrace ?? string.Empty; } // Some internal PowerShell exceptions seem to have null stack traces.
}
/// <summary>
/// An error's associated exception.
/// </summary>
public abstract Exception Exception { get; }
/// <summary>
/// Allows filtering an error's stack trace.
/// </summary>
/// <param name="stackTrace">The stack trace to filter</param>
/// <returns>The filtered stack trace</returns>
protected virtual string FilterStackTrace(string stackTrace)
{
return stackTrace;
}
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/ProjectInfo.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace PSycheTest.Runners.VisualStudio.Core
{
/// <summary>
/// Provides information about an <see cref="IVsProject"/>.
/// </summary>
internal class ProjectInfo : IProjectInfo
{
/// <summary>
/// Initializes a new <see cref="ProjectInfo"/>.
/// </summary>
/// <param name="project">The project to provide information about</param>
public ProjectInfo(IVsProject project)
{
_project = project;
}
/// <see cref="IProjectInfo.Name"/>
public string Name
{
get
{
string name = (string)GetProjectPropertyValue(__VSHPROPID.VSHPROPID_Name);
return name;
}
}
/// <see cref="IProjectInfo.File"/>
public FileInfo File
{
get
{
string projectFile;
ErrorHandler.ThrowOnFailure(_project.GetMkDocument(VSConstants.VSITEMID_ROOT, out projectFile));
return new FileInfo(projectFile);
}
}
/// <see cref="IProjectInfo.IsPhysicalProject"/>
public bool IsPhysicalProject
{
get
{
var projectType = GetProjectPropertyValue(__VSHPROPID.VSHPROPID_TypeName);
return projectType != null;
}
}
/// <see cref="IProjectInfo.GetProjectItems"/>
public IEnumerable<string> GetProjectItems()
{
return GetProjectItems((IVsHierarchy)_project, VSConstants.VSITEMID_ROOT);
}
private static IEnumerable<string> GetProjectItems(IVsHierarchy hierarchyItem, uint itemId)
{
object propertyValue = GetPropertyValue(hierarchyItem, (int)__VSHPROPID.VSHPROPID_FirstChild, itemId);
uint childId = GetItemId(propertyValue);
while (childId != VSConstants.VSITEMID_NIL)
{
string childPath = GetCanonicalName(hierarchyItem, childId);
yield return childPath;
foreach (var childNodePath in GetProjectItems(hierarchyItem, childId))
yield return childNodePath;
propertyValue = GetPropertyValue(hierarchyItem, (int)__VSHPROPID.VSHPROPID_NextSibling, childId);
childId = GetItemId(propertyValue);
}
}
private object GetProjectPropertyValue(__VSHPROPID property)
{
return GetPropertyValue((IVsHierarchy)_project, (int)property, VSConstants.VSITEMID_ROOT);
}
private static uint GetItemId(object pvar)
{
if (pvar == null)
return VSConstants.VSITEMID_NIL;
if (pvar is int)
return (uint)(int)pvar;
if (pvar is uint)
return (uint)pvar;
if (pvar is short)
return (uint)(short)pvar;
if (pvar is ushort)
return (ushort)pvar;
if (pvar is long)
return (uint)(long)pvar;
return VSConstants.VSITEMID_NIL;
}
private static object GetPropertyValue(IVsHierarchy vsHierarchy, int propid, uint itemId)
{
if (itemId == VSConstants.VSITEMID_NIL)
{
return null;
}
try
{
object o;
ErrorHandler.ThrowOnFailure(vsHierarchy.GetProperty(itemId, propid, out o));
return o;
}
catch (NotImplementedException)
{
return null;
}
catch (COMException)
{
return null;
}
catch (ArgumentException)
{
return null;
}
}
private static string GetCanonicalName(IVsHierarchy hierarchy, uint itemId)
{
string strRet = string.Empty;
int hr = hierarchy.GetCanonicalName(itemId, out strRet);
if (hr == VSConstants.E_NOTIMPL)
{
// Special case E_NOTIMLP to avoid perf hit to throw an exception.
return string.Empty;
}
try
{
ErrorHandler.ThrowOnFailure(hr);
}
catch (COMException)
{
strRet = string.Empty;
}
// This could be in the case of S_OK, S_FALSE, etc.
return strRet;
}
private readonly IVsProject _project;
}
}<file_sep>/PSycheTest.Runners.VisualStudio/VSTestContainerDiscoverer.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestWindow.Extensibility;
using PSycheTest.Runners.Framework;
using PSycheTest.Runners.VisualStudio.Core;
using PSycheTest.Runners.VisualStudio.Core.Monitoring;
using PSycheTest.Runners.VisualStudio.Core.Utilities;
using PSycheTest.Runners.VisualStudio.Core.Utilities.InputOutput;
using ILogger = PSycheTest.Runners.Framework.ILogger;
using ValidateArg = Microsoft.VisualStudio.TestPlatform.ObjectModel.ValidateArg;
namespace PSycheTest.Runners.VisualStudio
{
/// <summary>
/// Finds PowerShell scripts containing tests.
/// </summary>
[Export(typeof(ITestContainerDiscoverer))]
public class VSTestContainerDiscoverer : ITestContainerDiscoverer, IDisposable
{
/// <summary>
/// Initializes a new <see cref="VSTestContainerDiscoverer"/>.
/// </summary>
/// <param name="serviceProvider">Provides access to Visual Studio services</param>
/// <param name="solutionMonitor">Monitors a solution for changes</param>
/// <param name="projectFileMonitor">Monitors a project for changes to its child items</param>
[ImportingConstructor]
public VSTestContainerDiscoverer(
[Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider,
ISolutionMonitor solutionMonitor,
IProjectFileMonitor projectFileMonitor)
: this(serviceProvider,
new ActivityLogger(serviceProvider.GetService<IVsActivityLog, SVsActivityLog>(), typeof(VSTestContainerDiscoverer)),
solutionMonitor,
projectFileMonitor,
new FileSystemWatcherAdapter(new FileSystemWatcher()),
(disc, file, project) => new PowerShellTestContainer(disc, file, project))
{
}
/// <summary>
/// Initializes a new <see cref="VSTestContainerDiscoverer"/>.
/// </summary>
/// <param name="serviceProvider">Provides access to Visual Studio services</param>
/// <param name="logger">Object that logs messages</param>
/// <param name="solutionMonitor">Monitors a solution for changes</param>
/// <param name="projectFileMonitor">Monitors a project for changes to its child items</param>
/// <param name="fileWatcher">A file system watcher</param>
/// <param name="containerFactory">Creates new <see cref="ITestContainer"/>s</param>
public VSTestContainerDiscoverer(
IServiceProvider serviceProvider,
ILogger logger,
ISolutionMonitor solutionMonitor,
IProjectFileMonitor projectFileMonitor,
IFileSystemWatcher fileWatcher,
Func<ITestContainerDiscoverer, string, IVsProject, IVSTestContainer> containerFactory)
{
_serviceProvider = ValidateArg.NotNull(serviceProvider, "serviceProvider");
_logger = ValidateArg.NotNull(logger, "logger");
_solutionMonitor = ValidateArg.NotNull(solutionMonitor, "solutionMonitor");
_projectFileMonitor = ValidateArg.NotNull(projectFileMonitor, "projectFileMonitor");
_fileWatcher = ValidateArg.NotNull(fileWatcher, "fileWatcher");
_containerFactory = ValidateArg.NotNull(containerFactory, "containerFactory");
_solutionMonitor.SolutionChanged += solutionMonitor_SolutionChanged;
_solutionMonitor.ProjectChanged += solutionMonitor_ProjectChanged;
_solutionMonitor.StartMonitoring();
_projectFileMonitor.FileChanged += projectFileMonitor_FileChanged;
_projectFileMonitor.StartMonitoring();
_fileWatcher.NotifyFilter = NotifyFilters.LastWrite;
_fileWatcher.Filter = String.Format("*{0}", TestScript.FileExtension);
_fileWatcher.IncludeSubdirectories = true;
_fileWatcher.Error += fileWatcher_Error;
}
/// <summary>
/// Initializes cache with test containers from the current solution.
/// </summary>
private void Initialize()
{
var solution = _serviceProvider.GetService<IVsSolution, SVsSolution>();
var projects = solution.Info().GetProjects().Where(p => p.Info().IsPhysicalProject);
foreach (var project in projects)
AddProjectToCache(project);
_fileWatcher.Path = solution.Info().GetDirectory().FullName;
_fileWatcher.Changed += fileWatcher_Changed;
_fileWatcher.EnableRaisingEvents = true;
_isInitialized = true;
}
void solutionMonitor_SolutionChanged(object sender, SolutionChangedEventArgs e)
{
switch (e.ChangeType)
{
case SolutionChangeType.Loaded:
if (!_isInitialized)
Initialize();
OnTestContainersUpdated();
break;
case SolutionChangeType.Unloaded:
_containerCache.Clear();
_fileWatcher.EnableRaisingEvents = false;
_fileWatcher.Changed -= fileWatcher_Changed;
_isInitialized = false;
break;
}
}
void solutionMonitor_ProjectChanged(object sender, ProjectChangedEventArgs e)
{
switch (e.ChangeType)
{
case ProjectChangeType.Loaded:
RemoveProjectFromCache(e.Project);
var containers = DiscoverTestContainers(e.Project);
foreach (var container in containers)
AddContainerToCache(container, e.Project);
break;
case ProjectChangeType.Unloaded:
RemoveProjectFromCache(e.Project);
break;
}
OnTestContainersUpdated();
}
void projectFileMonitor_FileChanged(object sender, ProjectFileChangedEventArgs e)
{
switch (e.ChangeType)
{
case FileChangeType.Added:
AddContainerToCache(_containerFactory(this, e.FilePath, e.Project), e.Project);
break;
case FileChangeType.Removed:
RemoveContainerFromCache(e.FilePath, e.Project);
break;
}
OnTestContainersUpdated();
}
void fileWatcher_Changed(object sender, FileSystemEventArgs e)
{
// This check prevents handling of the event multiple times in a row
// since it seems to be raised at least twice for a single change.
DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);
if (lastWriteTime != _lastFileUpdate)
{
if (e.ChangeType == WatcherChangeTypes.Changed)
{
// Only refresh for files included in the solution.
IVSTestContainer oldContainer;
if (_containerCache.TryRemove(e.FullPath, out oldContainer))
{
// Create a new container.
_containerCache[oldContainer.Source] = _containerFactory(this, oldContainer.Source, oldContainer.Project);
OnTestContainersUpdated();
}
}
_lastFileUpdate = lastWriteTime;
}
}
void fileWatcher_Error(object sender, ErrorEventArgs e)
{
var exception = e.GetException();
_logger.Error("FileSystemWatcher error: {0}{1}{2}", exception.Message, Environment.NewLine, exception.StackTrace);
}
/// <see cref="ITestContainerDiscoverer.ExecutorUri"/>
public Uri ExecutorUri { get { return VSTestExecutor.ExecutorUri; } }
/// <see cref="ITestContainerDiscoverer.TestContainers"/>
public IEnumerable<ITestContainer> TestContainers
{
get
{
if (!_isInitialized)
Initialize();
return _containerCache.Values;
}
}
/// <see cref="ITestContainerDiscoverer.TestContainersUpdated"/>
public event EventHandler TestContainersUpdated;
private void OnTestContainersUpdated()
{
var localEvent = TestContainersUpdated;
if (localEvent != null)
localEvent(this, EventArgs.Empty);
}
private IEnumerable<IVSTestContainer> DiscoverTestContainers(IVsProject project)
{
var files = project.Info().GetProjectItems().Where(IsScriptFile);
return files.Select(file => _containerFactory(this, file, project));
}
private static bool IsScriptFile(string path)
{
// Comparison is reversed due to possible null reference (no extension).
return TestScript.FileExtension.Equals(Path.GetExtension(path), StringComparison.OrdinalIgnoreCase);
}
private void AddContainerToCache(IVSTestContainer container, IVsProject project)
{
_containerCache[container.Source] = container;
if (!_containersPerProject.ContainsKey(project))
_containersPerProject[project] = new List<IVSTestContainer>();
_containersPerProject[project].Add(container);
}
private void RemoveContainerFromCache(string source, IVsProject project)
{
IVSTestContainer throwaway;
_containerCache.TryRemove(source, out throwaway);
ICollection<IVSTestContainer> projectContainers;
if (_containersPerProject.TryGetValue(project, out projectContainers))
projectContainers.Remove(throwaway);
}
private void AddProjectToCache(IVsProject project)
{
var containers = DiscoverTestContainers(project);
foreach (var container in containers)
AddContainerToCache(container, project);
}
private void RemoveProjectFromCache(IVsProject project)
{
ICollection<IVSTestContainer> existingContainers;
if (_containersPerProject.TryRemove(project, out existingContainers))
{
foreach (var container in existingContainers)
{
IVSTestContainer throwaway;
_containerCache.TryRemove(container.Source, out throwaway);
}
}
}
#region IDisposable Implementation
private void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
_solutionMonitor.SolutionChanged -= solutionMonitor_SolutionChanged;
_solutionMonitor.ProjectChanged -= solutionMonitor_ProjectChanged;
_projectFileMonitor.FileChanged -= projectFileMonitor_FileChanged;
_fileWatcher.Changed -= fileWatcher_Changed;
_fileWatcher.Error -= fileWatcher_Error;
_fileWatcher.EnableRaisingEvents = false;
_fileWatcher.Dispose();
}
_isDisposed = true;
}
}
/// <see cref="IDisposable.Dispose"/>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~VSTestContainerDiscoverer()
{
Dispose(false);
}
private bool _isDisposed;
#endregion IDisposable Implementation
private DateTime _lastFileUpdate = DateTime.MinValue;
private bool _isInitialized;
private readonly ConcurrentDictionary<string, IVSTestContainer> _containerCache =
new ConcurrentDictionary<string, IVSTestContainer>(CaseInsensitiveEqualityComparer.Instance);
private readonly ConcurrentDictionary<IVsProject, ICollection<IVSTestContainer>> _containersPerProject =
new ConcurrentDictionary<IVsProject, ICollection<IVSTestContainer>>();
private readonly IServiceProvider _serviceProvider;
private readonly ILogger _logger;
private readonly ISolutionMonitor _solutionMonitor;
private readonly IProjectFileMonitor _projectFileMonitor;
private readonly Func<ITestContainerDiscoverer, string, IVsProject, IVSTestContainer> _containerFactory;
private readonly IFileSystemWatcher _fileWatcher;
}
}<file_sep>/AssemblyInfo.Global.cs
using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyCompany("<NAME>")]
[assembly: AssemblyProduct("PSycheTest")]
[assembly: AssemblyCopyright("© 2013 <NAME> All Rights Reserved.")]
// The Product version of the assembly. This is the version common across all files included
// with the product, and is the customer-facing version. Whilst this version can be a string,
// (such as '1.0 Release Candidate'), the value here is expected to be in format
// Major.Minor.Revision. The Build Number is generated by the (Production) build process.
//
// Example syntax: "1.0.0"
[assembly: AssemblyInformationalVersion("1.0")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif<file_sep>/PSycheTest.Runners.Framework/TestStartingEventArgs.cs
using System;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Contains diagnostic information about when a test is about to start.
/// </summary>
public class TestStartingEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of <see cref="TestStartingEventArgs"/>.
/// </summary>
/// <param name="test">The test that is starting</param>
public TestStartingEventArgs(ITestFunction test)
{
Test = test;
}
/// <summary>
/// The test that is starting.
/// </summary>
public ITestFunction Test { get; private set; }
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Utilities/CaseInsensitiveEqualityComparer.cs
using System;
using System.Collections.Generic;
namespace PSycheTest.Runners.VisualStudio.Core.Utilities
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> that compares strings in a non-case-sensitive way.
/// </summary>
public class CaseInsensitiveEqualityComparer : IEqualityComparer<string>
{
/// <see cref="IEqualityComparer{T}.Equals(T,T)"/>
public bool Equals(string x, string y)
{
return String.Equals(x, y, StringComparison.InvariantCultureIgnoreCase);
}
/// <summary>
/// Returns a file's hashcode.
/// </summary>
public int GetHashCode(string obj)
{
return obj.ToLowerInvariant().GetHashCode();
}
/// <summary>
/// Gets a <see cref="CaseInsensitiveEqualityComparer"/>.
/// </summary>
public static IEqualityComparer<string> Instance
{
get { return instance; }
}
private static readonly IEqualityComparer<string> instance = new CaseInsensitiveEqualityComparer();
}
}<file_sep>/Tests.Integration/PSycheTest.Runners.Framework/AttachFileCmdletTests.cs
using System;
using System.IO;
using PSycheTest;
using PSycheTest.Core;
using PSycheTest.Core.Extensions;
using Tests.Support;
using Xunit;
namespace Tests.Integration.PSycheTest
{
public class AttachFileCmdletTests : CmdletTestBase<AttachFileCmdlet>, IDisposable
{
public AttachFileCmdletTests()
{
testContext.OutputDirectory = outputDir.Directory;
}
[Fact]
public void Test_AttachFile()
{
// Arrange.
Current.Shell.Runspace.SessionStateProxy.Variables().__testContext__ = testContext;
AddCmdlet();
AddParameter(p => p.Artifact, new Uri(artifactFile.File.FullName));
// Act.
Current.Shell.Invoke();
// Assert.
var file = Assert.Single(testContext.Artifacts);
Assert.Equal(Path.Combine(outputDir.Directory.FullName, artifactFile.File.Name), file.OriginalString);
}
[Fact]
public void Test_AttachFile_With_Relative_Path()
{
// Arrange.
Current.Shell.Runspace.SessionStateProxy.Variables().__testContext__ = testContext;
Current.Shell.Runspace.SessionStateProxy.Path.SetLocation(artifactFile.File.Directory.FullName);
AddCmdlet();
AddParameter(p => p.Artifact, new Uri(Path.Combine(@".\", artifactFile.File.Name), UriKind.Relative));
// Act.
Current.Shell.Invoke();
// Assert.
var file = Assert.Single(testContext.Artifacts);
Assert.Equal(Path.Combine(outputDir.Directory.FullName, artifactFile.File.Name), file.LocalPath);
}
public void Dispose()
{
artifactFile.Dispose();
outputDir.Dispose();
}
private readonly TemporaryFile artifactFile = new TemporaryFile().Touch();
private readonly TemporaryDirectory outputDir = new TemporaryDirectory();
private readonly TestExecutionContext testContext = new TestExecutionContext();
}
}<file_sep>/PSycheTest/AttachFileCmdlet.cs
using System;
using System.IO;
using System.Management.Automation;
using PSycheTest.Core;
namespace PSycheTest
{
/// <summary>
/// Includes a file for archival in the current test run.
/// </summary>
[Cmdlet("Attach", "File")]
public class AttachFileCmdlet : PSCmdlet
{
/// <summary>
/// A file to attach.
/// </summary>
[Parameter(Mandatory = true, Position = 0)]
[ValidateNotNull]
public Uri Artifact { get; set; }
protected override void BeginProcessing()
{
var context = SessionState.Variables().__testContext__ as TestExecutionContext;
if (context != null)
{
// Relative files are written to the current working directory.
if (!Artifact.IsAbsoluteUri)
Artifact = new Uri(Path.Combine(SessionState.Path.CurrentLocation.Path, Artifact.OriginalString));
context.AttachArtifact(Artifact);
}
}
}
}<file_sep>/PSycheTest/AssertConditionCmdlet.cs
using System.Management.Automation;
namespace PSycheTest
{
/// <summary>
/// Base class for a cmdlet that verifies the truth of a statement.
/// </summary>
public abstract class AssertConditionCmdlet : AssertionCmdletBase
{
/// <summary>
/// The expected value.
/// </summary>
[Parameter(Mandatory = true, Position = 0)]
public bool Condition { get; set; }
}
}<file_sep>/PSycheTest.Runners.Framework/Utilities/Reflection/Reflect.cs
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
namespace PSycheTest.Runners.Framework.Utilities.Reflection
{
/// <summary>
/// Contains methods used to extract reflection information in a type-safe manner.
/// </summary>
public static class Reflect
{
/// <summary>
/// Extracts the PropertyInfo for the property referred to by the given lambda expression.
/// </summary>
/// <remarks>This is usually the most convenient overload to use because it requires the fewest generic arguments.</remarks>
/// <typeparam name="TDeclaring">The type that should contain the property</typeparam>
/// <param name="propertyAccessor">A lambda expression referring to the property</param>
/// <returns>The PropertyInfo of the given property</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public static PropertyInfo PropertyOf<TDeclaring>(Expression<Func<TDeclaring, object>> propertyAccessor)
{
return PropertyOf<TDeclaring, object>(propertyAccessor);
}
/// <summary>
/// Extracts the PropertyInfo for the property referred to by the given lambda expression.
/// </summary>
/// <typeparam name="TDeclaring">The type that should contain the property</typeparam>
/// <typeparam name="TValue">The type of the property's value</typeparam>
/// <param name="propertyAccessor">A lambda expression referring to the property</param>
/// <returns>The PropertyInfo of the given property</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public static PropertyInfo PropertyOf<TDeclaring, TValue>(Expression<Func<TDeclaring, TValue>> propertyAccessor)
{
return PropertyOf(typeof(TDeclaring), propertyAccessor);
}
/// <summary>
/// Extracts the PropertyInfo for the property referred to by the given lambda expression.
/// </summary>
/// <param name="declaring">The declaring type</param>
/// <param name="propertyAccessor">A lambda expression referring to the property</param>
/// <returns>The PropertyInfo of the given property</returns>
public static PropertyInfo PropertyOf(Type declaring, LambdaExpression propertyAccessor)
{
return ExtractProperty(declaring, propertyAccessor);
}
private static PropertyInfo ExtractProperty(Type type, LambdaExpression propertyAccessor)
{
MemberExpression memberExpr = ExtractMemberExpression(type, propertyAccessor);
if (memberExpr == null)
throw new ArgumentException("The body of the expression must be a member of " + type.Name, "propertyAccessor");
PropertyInfo property = memberExpr.Member as PropertyInfo;
if (property == null)
throw new ArgumentException("The body of the expression must be a property invocation.", "propertyAccessor");
return property;
}
private static MemberExpression ExtractMemberExpression(Type type, LambdaExpression memberAccessor)
{
MemberExpression memberExpr = memberAccessor.Body as MemberExpression;
if (memberExpr != null)
return memberExpr;
// Value type members may be wrapped in Convert expressions.
if (memberAccessor.Body.NodeType == ExpressionType.Convert)
{
UnaryExpression unaryExpr = memberAccessor.Body as UnaryExpression;
if (unaryExpr != null)
{
memberExpr = unaryExpr.Operand as MemberExpression;
if (memberExpr != null && type.IsAssignableFrom(memberExpr.Member.DeclaringType))
{
return memberExpr;
}
}
}
return null;
}
/// <summary>
/// Extracts a void-returning method from a lambda expression.
/// </summary>
/// <typeparam name="T">The declaring type of the method</typeparam>
/// <param name="methodCaller">An expression that invokes the method</param>
/// <returns>The MethodInfo of the given method</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public static MethodInfo MethodOf<T>(this Expression<Action<T>> methodCaller)
{
return ExtractMethodCall(typeof(T), methodCaller).Method;
}
/// <summary>
/// Extracts a method with a return type from a lambda expression.
/// </summary>
/// <typeparam name="T">The declaring type of the method</typeparam>
/// <param name="methodCaller">The expression that invokes the method</param>
/// <returns>The MethodInfo of the given method</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public static MethodInfo MethodOf<T>(this Expression<Func<T, object>> methodCaller)
{
return ExtractMethodCall(typeof(T), methodCaller).Method;
}
private static MethodCallExpression ExtractMethodCall(Type type, LambdaExpression methodCaller)
{
MethodCallExpression methodCall = methodCaller.Body as MethodCallExpression;
if (methodCall == null)
throw new ArgumentException("The body of the expression must be a method of " + type.Name, "methodCaller");
return methodCall;
}
}
}<file_sep>/PSycheTest/Exceptions/NotContainsException.cs
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace PSycheTest.Exceptions
{
/// <summary>
/// Assertion exception for when a certain value was not expected to be in a collection
/// but it was found.
/// </summary>
[Serializable]
public class NotContainsException : AssertionException
{
/// <summary>
/// The value that should not be found.
/// </summary>
public object Unexpected { get; private set; }
/// <see cref="Exception.Message"/>
public override string Message
{
get
{
return String.Format("{0}{2}Found: {1}",
base.Message,
Unexpected ?? "(null)",
Environment.NewLine);
}
}
/// <summary>
/// Initializes a new <see cref="NotContainsException"/>.
/// </summary>
/// <param name="unexpected">The value that should not be found</param>
/// <param name="userMessage">A user provided message</param>
public NotContainsException(object unexpected, string userMessage)
{
Unexpected = unexpected;
UserMessage = userMessage;
}
/// <see cref="Exception(SerializationInfo,StreamingContext)"/>
protected NotContainsException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
Unexpected = info.GetValue("Unexpected", typeof(object));
}
/// <see cref="Exception.GetObjectData"/>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
info.AddValue("Unexpected", Unexpected);
base.GetObjectData(info, context);
}
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Utilities/Chronology/TimerBase.cs
using System;
namespace PSycheTest.Runners.VisualStudio.Core.Utilities.Chronology
{
/// <summary>
/// Provides a convenient base class for timers.
/// </summary>
internal abstract class TimerBase : ITimer
{
/// <see cref="ITimer.Interval"/>
public virtual TimeSpan Interval { get; set; }
/// <see cref="ITimer.Start"/>
public void Start(object state = null)
{
lock (SyncObject)
{
if (!TryStart(state))
throw new InvalidOperationException("Timer is already started.");
}
}
/// <see cref="ITimer.TryStart"/>
public abstract bool TryStart(object state = null);
/// <see cref="ITimer.Stop"/>
public void Stop()
{
lock (SyncObject)
{
if (!TryStop())
throw new InvalidOperationException("Timer is already stopped.");
}
}
/// <see cref="ITimer.TryStop"/>
public abstract bool TryStop();
/// <see cref="ITimer.Restart"/>
public void Restart(object state = null)
{
lock (SyncObject)
{
TryStop();
Start(state);
}
}
/// <see cref="ITimer.Started"/>
public abstract bool Started { get; }
/// <see cref="ITimer.Elapsed"/>
public event EventHandler<TimerElapsedEventArgs> Elapsed;
/// <summary>
/// Raises the <see cref="ITimer.Elapsed"/> event.
/// </summary>
/// <param name="elapsedTime">The time at which the timer period elapsed</param>
/// <param name="state">Associated user state</param>
protected void OnElapsed(DateTime elapsedTime, object state)
{
var localEvent = Elapsed;
if (localEvent != null)
localEvent(this, new TimerElapsedEventArgs(elapsedTime, state));
}
/// <summary>
/// Object used for locking.
/// </summary>
protected object SyncObject
{
get { return _syncObject; }
}
private readonly object _syncObject = new object();
}
}<file_sep>/PSycheTest.Runners.VisualStudio/VSTestExecutor.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using PSycheTest.Runners.Framework;
using PSycheTest.Runners.VisualStudio.Core;
namespace PSycheTest.Runners.VisualStudio
{
/// <summary>
/// An <see cref="ITestExecutor"/> that execute PowerShell test cases.
/// </summary>
[ExtensionUri(ExecutorUriString)]
[Export(typeof(ITestExecutor))]
public class VSTestExecutor : ITestExecutor
{
/// <summary>
/// Initializes a new <see cref="VSTestExecutor"/>.
/// </summary>
[ImportingConstructor]
public VSTestExecutor()
: this(logger => new PowerShellTestExecutor(logger),
logger => new PowerShellTestDiscoverer(logger))
{
}
/// <summary>
/// Initializes a new <see cref="VSTestExecutor"/>.
/// </summary>
/// <param name="executorFactory">Creates text executors</param>
/// <param name="discovererFactory">Creates test discoverers</param>
public VSTestExecutor(
Func<ILogger, IPowerShellTestExecutor> executorFactory,
Func<ILogger, IPowerShellTestDiscoverer> discovererFactory)
{
_executorFactory = executorFactory;
_discovererFactory = discovererFactory;
}
/// <see cref="ITestExecutor.RunTests(IEnumerable{TestCase},IRunContext,IFrameworkHandle)"/>
/// <remarks>This method is executed when test cases have already been discovered or when a selected subset of tests are run.</remarks>
public void RunTests(IEnumerable<TestCase> tests, IRunContext runContext, IFrameworkHandle frameworkHandle)
{
if (runContext.KeepAlive)
frameworkHandle.EnableShutdownAfterTestRun = true;
Channels.UnregisterAll();
var selectedTests = new HashSet<string>(tests.Select(test => test.FullyQualifiedName));
var logger = new VSLogger(frameworkHandle);
var discoverer = _discovererFactory(logger);
var scriptFiles = tests.Select(test => test.Source).Distinct().Select(source => new FileInfo(source));
var scripts = discoverer.Discover(scriptFiles);
RunTestsCore(scripts, test => selectedTests.Contains(test.UniqueName), logger, runContext, frameworkHandle);
}
/// <see cref="ITestExecutor.RunTests(IEnumerable{string},IRunContext,IFrameworkHandle)"/>
public void RunTests(IEnumerable<string> sources, IRunContext runContext, IFrameworkHandle frameworkHandle)
{
if (runContext.KeepAlive)
frameworkHandle.EnableShutdownAfterTestRun = true;
Channels.UnregisterAll();
var logger = new VSLogger(frameworkHandle);
var discoverer = _discovererFactory(logger);
var scripts = discoverer.Discover(sources.Select(s => new FileInfo(s)));
RunTestsCore(scripts, _ => true, logger, runContext, frameworkHandle);
}
private void RunTestsCore(IEnumerable<ITestScript> tests, Predicate<ITestFunction> filter, ILogger logger, IRunContext runContext, ITestExecutionRecorder recorder)
{
var settingsService = runContext.RunSettings.GetSettings(PSycheTestRunSettings.SettingsProviderName) as IPSycheTestSettingsService ?? new PSycheTestSettingsService();
var testCaseMap = new Dictionary<ITestFunction, TestCase>();
var executor = _executorFactory(logger);
executor.OutputDirectory = new DirectoryInfo(runContext.TestRunDirectory);
logger.Info("Test output directory: {0}", executor.OutputDirectory.FullName);
foreach (var module in settingsService.Settings.Modules)
{
logger.Info("Adding module '{0}'", module);
executor.InitialModules.Add(module);
}
executor.TestStarting += (o, e) =>
{
var testCase = _mapper.Map(e.Test);
testCaseMap[e.Test] = testCase;
recorder.RecordStart(testCase);
};
executor.TestEnded += (o, e) =>
{
var testCase = testCaseMap[e.Test];
recorder.RecordEnd(testCase, _mapper.Map(e.Result.Status));
recorder.RecordResult(_mapper.Map(testCase, e.Result));
};
using (_cancellationTokenSource = new CancellationTokenSource())
{
executor.ExecuteAsync(tests, filter, _cancellationTokenSource.Token).Wait(); // Awaiting seems to cause odd behavior, just block instead.
}
_cancellationTokenSource = null;
}
/// <see cref="ITestExecutor.Cancel"/>
public void Cancel()
{
if (_cancellationTokenSource != null)
_cancellationTokenSource.Cancel();
}
private CancellationTokenSource _cancellationTokenSource;
private readonly TestMapper _mapper = new TestMapper();
private readonly Func<ILogger, IPowerShellTestExecutor> _executorFactory;
private readonly Func<ILogger, IPowerShellTestDiscoverer> _discovererFactory;
/// <summary>
/// The Uri used to identify the <see cref="VSTestExecutor"/>.
/// </summary>
public const string ExecutorUriString = "executor://PSycheTest.Runners.VisualStudio/VSTestExecutor";
/// <summary>
/// The Uri used to identify the <see cref="VSTestExecutor"/>.
/// </summary>
public static readonly Uri ExecutorUri = new Uri(ExecutorUriString);
}
}<file_sep>/Tests.Integration/PSycheTest/AssertNullCmdletTests.cs
using System.Management.Automation;
using PSycheTest;
using PSycheTest.Exceptions;
using Xunit;
namespace Tests.Integration.PSycheTest
{
public class AssertNullCmdletTests : CmdletTestBase<AssertNullCmdlet>
{
[Fact]
public void Test_Assert_Failure()
{
// Arrange.
var actual = new object();
AddCmdlet();
AddParameter(p => p.Actual, actual);
// Act/Assert.
var exception = Assert.Throws<CmdletInvocationException>(() =>
Current.Shell.Invoke());
Assert.NotNull(exception.InnerException);
var assertException = Assert.IsType<ExpectedActualException>(exception.InnerException);
Assert.Equal(null, assertException.Expected);
Assert.Equal(actual, assertException.Actual);
}
[Fact]
public void Test_Assert_Success()
{
// Arrange.
AddCmdlet();
AddParameter(p => p.Actual, null);
// Act/Assert.
Assert.DoesNotThrow(() => Current.Shell.Invoke());
}
}
}<file_sep>/PSycheTest.Runners.Framework/Extensions/RunspaceExtensions.cs
using System;
using System.Management.Automation.Runspaces;
using System.Threading.Tasks;
namespace PSycheTest.Runners.Framework.Extensions
{
/// <summary>
/// Provides extension methods for <see cref="Runspace"/>s.
/// </summary>
public static class RunspaceExtensions
{
/// <summary>
/// Opens a <see cref="Runspace"/> asynchronously.
/// </summary>
/// <param name="runspace">The runspace to open</param>
/// <returns>A task that will complete when the runspace opens</returns>
public static Task OpenTaskAsync(this Runspace runspace)
{
// If the runspace is already open, return immediately.
if (runspace.RunspaceStateInfo.State == RunspaceState.Opened)
return Task.FromResult<object>(null);
var tcs = new TaskCompletionSource<object>();
EventHandler<RunspaceStateEventArgs> stateHandler = null;
stateHandler = (o, e) =>
{
if (e.RunspaceStateInfo.Reason != null)
{
runspace.StateChanged -= stateHandler;
tcs.TrySetException(e.RunspaceStateInfo.Reason);
}
else if (e.RunspaceStateInfo.State == RunspaceState.Opened)
{
runspace.StateChanged -= stateHandler;
tcs.TrySetResult(null);
}
};
runspace.StateChanged += stateHandler;
runspace.OpenAsync();
return tcs.Task;
}
}
}<file_sep>/PSycheTest/Exceptions/ExpectedActualException.cs
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace PSycheTest.Exceptions
{
/// <summary>
/// Assertion exception for when a certain value was expected and the actual value did
/// not match.
/// </summary>
[Serializable]
public class ExpectedActualException : AssertionException
{
/// <summary>
/// The expected value.
/// </summary>
public object Expected { get; private set; }
/// <summary>
/// The actual value.
/// </summary>
public object Actual { get; private set; }
/// <see cref="Exception.Message"/>
public override string Message
{
get
{
return String.Format("{0}{3}Expected: {1}{3}Actual: {2}",
base.Message,
Expected ?? "(null)",
Actual ?? "(null)",
Environment.NewLine);
}
}
/// <summary>
/// Initializes a new <see cref="ExpectedActualException"/>.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value</param>
/// <param name="userMessage">A user provided message</param>
public ExpectedActualException(object expected, object actual, string userMessage)
: base(userMessage)
{
Expected = expected;
Actual = actual;
}
/// <see cref="Exception(SerializationInfo,StreamingContext)"/>
protected ExpectedActualException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
Expected = info.GetValue("Expected", typeof(object));
Actual = info.GetValue("Actual", typeof(object));
}
/// <see cref="Exception.GetObjectData"/>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
info.AddValue("Expected", Expected);
info.AddValue("Actual", Actual);
base.GetObjectData(info, context);
}
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/IProjectInfo.cs
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.Shell.Interop;
namespace PSycheTest.Runners.VisualStudio.Core
{
/// <summary>
/// Provides information about an <see cref="IVsProject"/>.
/// </summary>
public interface IProjectInfo
{
/// <summary>
/// A project's name.
/// </summary>
string Name { get; }
/// <summary>
/// A project's file.
/// </summary>
FileInfo File { get; }
/// <summary>
/// Whether a project corresponds to an actual project file or
/// instead represents solution files or currently open
/// files that do not belong to a solution (ie. "Miscellaneous Files").
/// </summary>
bool IsPhysicalProject { get; }
/// <summary>
/// Iterates over the child items of an <see cref="IVsProject"/>.
/// </summary>
IEnumerable<string> GetProjectItems();
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Utilities/InputOutput/FileSystemWatcherAdapter.cs
using System;
using System.IO;
namespace PSycheTest.Runners.VisualStudio.Core.Utilities.InputOutput
{
/// <summary>
/// A wrapper around FileSystemWatcher.
/// </summary>
internal class FileSystemWatcherAdapter : IFileSystemWatcher
{
/// <summary>
/// Creates a file system watcher.
/// </summary>
public FileSystemWatcherAdapter()
: this(new FileSystemWatcher()) { }
/// <summary>
/// Creates a file system watcher using an existing watcher.
/// </summary>
/// <param name="fileSystemWatcher">An existing file system watcher</param>
public FileSystemWatcherAdapter(FileSystemWatcher fileSystemWatcher)
{
_fileSystemWatcher = fileSystemWatcher;
}
/// <summary>
/// Gets or sets the path of the directory to watch.
/// </summary>
/// <returns>
/// The path to monitor. The default is an empty string ("").
/// </returns>
/// <exception cref="T:System.ArgumentException">
/// The specified path does not exist or could not be found.-or-
/// The specified path contains wildcard characters.-or- The specified
/// path contains invalid path characters.</exception>
public string Path
{
get { return _fileSystemWatcher.Path; }
set { _fileSystemWatcher.Path = value; }
}
/// <summary>
/// Gets or sets a value indicating whether subdirectories within the specified path should be monitored.
/// </summary>
public bool IncludeSubdirectories
{
get { return _fileSystemWatcher.IncludeSubdirectories; }
set { _fileSystemWatcher.IncludeSubdirectories = value; }
}
/// <summary>
/// Gets or sets the filter string used to determine what files are monitored in a directory.
/// </summary>
/// <returns>
/// The filter string. The default is "*.*" (Watches all files.)
/// </returns>
public string Filter
{
get { return _fileSystemWatcher.Filter; }
set { _fileSystemWatcher.Filter = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the component is enabled.
/// </summary>
public bool EnableRaisingEvents
{
get { return _fileSystemWatcher.EnableRaisingEvents; }
set { _fileSystemWatcher.EnableRaisingEvents = value; }
}
/// <summary>
/// Gets or sets the type of changes to watch for.
/// </summary>
public NotifyFilters NotifyFilter
{
get { return _fileSystemWatcher.NotifyFilter; }
set { _fileSystemWatcher.NotifyFilter = value; }
}
/// <summary>
/// Occurs when a file or directory in the specified <see cref="P:System.IO.FileSystemWatcher.Path"/> is changed.
/// </summary>
public event FileSystemEventHandler Changed
{
add { _fileSystemWatcher.Changed += value; }
remove { _fileSystemWatcher.Changed -= value; }
}
/// <summary>
/// Occurs when a file or directory in the specified <see cref="P:System.IO.FileSystemWatcher.Path"/> is created.
/// </summary>
public event FileSystemEventHandler Created
{
add { _fileSystemWatcher.Created += value; }
remove { _fileSystemWatcher.Created -= value; }
}
/// <summary>
/// Occurs when a file or directory in the specified <see cref="P:System.IO.FileSystemWatcher.Path"/> is deleted.
/// </summary>
public event FileSystemEventHandler Deleted
{
add { _fileSystemWatcher.Deleted += value; }
remove { _fileSystemWatcher.Deleted -= value; }
}
/// <summary>
/// Occurs when a file or directory in the specified <see cref="P:System.IO.FileSystemWatcher.Path"/> is renamed.
/// </summary>
public event RenamedEventHandler Renamed
{
add { _fileSystemWatcher.Renamed += value; }
remove { _fileSystemWatcher.Renamed -= value; }
}
/// <summary>
/// Occurs when the internal buffer overflows.
/// </summary>
public event ErrorEventHandler Error
{
add { _fileSystemWatcher.Error += value; }
remove { _fileSystemWatcher.Error -= value; }
}
/// <see cref="IDisposable.Dispose"/>
public void Dispose()
{
_fileSystemWatcher.Dispose();
}
private readonly FileSystemWatcher _fileSystemWatcher;
}
}<file_sep>/PSycheTest/Core/SessionStateExtensions.cs
using System.Dynamic;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace PSycheTest.Core
{
/// <summary>
/// Provides extension methods for operating on PowerShell session state.
/// </summary>
public static class SessionStateExtensions
{
/// <summary>
/// Provides access to session variables.
/// </summary>
/// <param name="sessionState">The session state to access</param>
/// <returns>An object providing access to session variables</returns>
public static dynamic Variables(this SessionState sessionState)
{
return new SessionVariables(sessionState.PSVariable);
}
/// <summary>
/// Provides access to session variables.
/// </summary>
/// <param name="sessionState">The session state to access</param>
/// <returns>An object providing access to session variables</returns>
public static dynamic Variables(this SessionStateProxy sessionState)
{
return new SessionVariables(sessionState.PSVariable);
}
}
/// <summary>
/// Provides access to PowerShell variables.
/// </summary>
public class SessionVariables : DynamicObject
{
/// <summary>
/// Initializes a new instance of <see cref="SessionVariables"/>.
/// </summary>
/// <param name="variables">The inner variables object</param>
public SessionVariables(PSVariableIntrinsics variables)
{
_variables = variables;
}
/// <see cref="DynamicObject.TryGetMember"/>
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var value = _variables.GetValue(binder.Name);
result = value;
return true;
}
/// <see cref="DynamicObject.TrySetMember"/>
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_variables.Set(binder.Name, value);
return true;
}
private readonly PSVariableIntrinsics _variables;
}
}<file_sep>/PSycheTest.Runners.Framework/Timers/TimerToken.cs
using System;
namespace PSycheTest.Runners.Framework.Timers
{
internal class TimerToken : IDisposable
{
/// <summary>
/// Initializes a new <see cref="TimerToken"/>.
/// </summary>
/// <param name="timer">The <see cref="ITestTimer"/> to manage</param>
public TimerToken(ITestTimer timer)
{
_timer = timer;
}
/// <see cref="IDisposable.Dispose"/>
public void Dispose()
{
_timer.Stop();
}
private readonly ITestTimer _timer;
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/IPSycheTestRunSettings.cs
using System.Collections.Generic;
namespace PSycheTest.Runners.VisualStudio.Core
{
/// <summary>
/// Contains test run settings.
/// </summary>
public interface IPSycheTestRunSettings
{
/// <summary>
/// Any modules that should be imported into the initial session state.
/// </summary>
ICollection<string> Modules { get; }
}
}<file_sep>/PSycheTest.Runners.Framework/PowerShellTestDiscoverer.cs
using System.Collections.Generic;
using System.IO;
using System.Linq;
using PSycheTest.Runners.Framework.Utilities;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// A class that discovers tests based on script files.
/// </summary>
public class PowerShellTestDiscoverer : IPowerShellTestDiscoverer
{
/// <summary>
/// Initializes a new <see cref="PowerShellTestDiscoverer"/>.
/// </summary>
/// <param name="logger">A message logger</param>
public PowerShellTestDiscoverer(ILogger logger)
: this(new PSScriptParser(), logger) { }
/// <summary>
/// Initializes a new <see cref="PowerShellTestDiscoverer"/>.
/// </summary>
/// <param name="parser">The parser to use for scripts</param>
/// <param name="logger">A message logger</param>
internal PowerShellTestDiscoverer(IScriptParser parser, ILogger logger)
{
_parser = parser;
_logger = logger;
}
/// <summary>
/// Finds test cases in a collection of script files.
/// </summary>
/// <param name="sourceFiles">The script files to search for test cases</param>
/// <returns>Any discovered test cases</returns>
public IEnumerable<ITestScript> Discover(IEnumerable<FileInfo> sourceFiles)
{
return sourceFiles.Select(Discover)
.Where(script => script.HasValue)
.Select(script => script.Value);
}
/// <summary>
/// Finds test cases in a single file.
/// </summary>
/// <param name="sourceFile">The file to search for test cases</param>
/// <returns>Any discovered test cases</returns>
public Option<ITestScript> Discover(FileInfo sourceFile)
{
_logger.Info("Analyzing file '{0}' for tests.", sourceFile.FullName);
var result = _parser.Parse(sourceFile);
if (result.Errors.Any())
{
foreach (var error in result.Errors)
{
_logger.Error("Parsing error: {0} at Line: {1}, Column: {2}", error.Message, error.Extent.StartLineNumber, error.Extent.StartColumnNumber);
}
return Option<ITestScript>.None();
}
var visitor = new TestDiscoveryVisitor();
result.SyntaxTree.Visit(visitor);
var tests = visitor.TestFunctions.Select(function => new TestFunction(function)).ToList();
if (!tests.Any())
return Option<ITestScript>.None();
return new TestScript(result.SyntaxTree, tests, visitor.TestSetupFunction, visitor.TestCleanupFunction);
}
private readonly IScriptParser _parser;
private readonly ILogger _logger;
}
}<file_sep>/PSycheTest/AssertFalseCmdlet.cs
using System.Management.Automation;
using PSycheTest.Exceptions;
namespace PSycheTest
{
/// <summary>
/// Cmdlet that verifies that a statement is false.
/// </summary>
[Cmdlet(VerbsLifecycle.Assert, "False")]
public class AssertFalseCmdlet : AssertConditionCmdlet
{
/// <see cref="AssertionCmdletBase.Assert"/>
protected override void Assert()
{
if (Condition)
throw new ExpectedActualException(false, true, Message ?? "Assert-False Failure");
}
}
}<file_sep>/PSycheTest.Runners.Framework/ITestExecutionTransaction.cs
using System;
using System.IO;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Interface for an object that manages and resets the appropriate PowerShell execution state between individual tests.
/// </summary>
public interface ITestExecutionTransaction : IDisposable
{
/// <summary>
/// A test's output directory. If empty after execution of a test, it will be removed.
/// </summary>
DirectoryInfo OutputDirectory { get; }
}
}<file_sep>/PSycheTest.Runners.Framework/TestFunction.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Language;
using PSycheTest.Runners.Framework.Results;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Represents a PowerShell function test.
/// </summary>
public class TestFunction : ITestFunction
{
/// <summary>
/// Initializes a new <see cref="TestFunction"/>.
/// </summary>
/// <param name="functionSyntaxTree">The syntax tree of a function that represents a test</param>
public TestFunction(FunctionDefinitionAst functionSyntaxTree)
{
SyntaxTree = functionSyntaxTree;
Function = SyntaxTree.Body.GetScriptBlock();
UniqueName = String.Format("{0}:{1}", SyntaxTree.Extent.File, SyntaxTree.Name);
DisplayName = SyntaxTree.Name;
FunctionName = SyntaxTree.Name;
Source = new TestSourceInfo(
new FileInfo(SyntaxTree.Extent.File),
SyntaxTree.Extent.StartLineNumber,
SyntaxTree.Extent.StartColumnNumber);
var testAttribute = Function.Attributes.OfType<TestAttribute>().Single();
CustomTitle = testAttribute.Title ?? string.Empty;
ShouldSkip = !String.IsNullOrEmpty(testAttribute.SkipBecause);
SkipReason = ShouldSkip ? testAttribute.SkipBecause : string.Empty;
}
/// <summary>
/// A test's full, unique name.
/// </summary>
public string UniqueName { get; private set; }
/// <summary>
/// A test's display name.
/// </summary>
public string DisplayName { get; private set; }
/// <summary>
/// A test function's programmatic name. This may or may not be the same as <see cref="UniqueName"/>.
/// </summary>
public string FunctionName { get; private set; }
/// <summary>
/// An optional test title.
/// </summary>
public string CustomTitle { get; private set; }
/// <summary>
/// Whether a test should be skipped.
/// </summary>
public bool ShouldSkip { get; private set; }
/// <summary>
/// If <see cref="ShouldSkip"/> is true, this should be the reason
/// for skipping a test.
/// </summary>
public string SkipReason { get; private set; }
/// <summary>
/// Contains information about where a test came from.
/// </summary>
public TestSourceInfo Source { get; private set; }
/// <summary>
/// The actual compiled function for a test.
/// </summary>
internal ScriptBlock Function { get; private set; }
/// <summary>
/// The syntax tree for the test function.
/// </summary>
internal FunctionDefinitionAst SyntaxTree { get; private set; }
/// <summary>
/// Adds a test result to a test.
/// </summary>
/// <param name="result">The result to add</param>
public void AddResult(TestResult result)
{
_results.Add(result);
}
/// <see cref="ITestResultProvider.Results"/>
public IEnumerable<TestResult> Results { get { return _results; } }
/// <see cref="object.ToString"/>
public override string ToString()
{
return UniqueName;
}
private readonly ICollection<TestResult> _results = new List<TestResult>();
}
}<file_sep>/PSycheTest.Runners.Framework/TestScript.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Language;
using PSycheTest.Runners.Framework.Results;
using PSycheTest.Runners.Framework.Utilities;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Represents a PowerShell script containing tests.
/// </summary>
public class TestScript : ITestScript
{
/// <summary>
/// Initializes a new <see cref="TestScript"/>.
/// </summary>
/// <param name="scriptSyntaxTree">The syntax tree for a script</param>
/// <param name="tests">The tests belonging to the script</param>
/// <param name="testSetup">An optional test setup function</param>
/// <param name="testCleanup">An optional test cleanup function</param>
public TestScript(ScriptBlockAst scriptSyntaxTree, IEnumerable<TestFunction> tests,
Option<FunctionDefinitionAst> testSetup, Option<FunctionDefinitionAst> testCleanup)
{
if (scriptSyntaxTree == null)
throw new ArgumentNullException("scriptSyntaxTree");
if (tests == null)
throw new ArgumentNullException("tests");
if (testSetup == null)
throw new ArgumentNullException("testSetup");
if (testCleanup == null)
throw new ArgumentNullException("testCleanup");
_scriptSyntaxTree = scriptSyntaxTree;
Source = new FileInfo(_scriptSyntaxTree.Extent.File);
ScriptBlock = _scriptSyntaxTree.GetScriptBlock();
_tests = new List<TestFunction>(tests);
TestSetup = testSetup;
TestCleanup = testCleanup;
}
/// <summary>
/// The file a script came from.
/// </summary>
public FileInfo Source { get; private set; }
/// <summary>
/// The text content of a script.
/// </summary>
public string Text
{
get { return _scriptSyntaxTree.Extent.Text; }
}
/// <summary>
/// The tests contained with a script.
/// </summary>
public IEnumerable<ITestFunction> Tests { get { return _tests; } }
/// <summary>
/// An optional test setup function.
/// </summary>
public Option<FunctionDefinitionAst> TestSetup { get; private set; }
/// <summary>
/// An optional test cleanup function.
/// </summary>
public Option<FunctionDefinitionAst> TestCleanup { get; private set; }
/// <see cref="ITestResultProvider.Results"/>
public IEnumerable<TestResult> Results
{
get { return _tests.SelectMany(t => t.Results); }
}
/// <summary>
/// Returns a script's results grouped by their parent <see cref="ITestFunction"/>s.
/// </summary>
public ILookup<ITestFunction, TestResult> ResultsByTest
{
get
{
var results = _tests.SelectMany(
test => test.Results,
(test, result) => new { Test = (ITestFunction)test, Result = result });
return results.ToLookup(t => t.Test, t => t.Result);
}
}
/// <summary>
/// The compiled script code.
/// </summary>
public ScriptBlock ScriptBlock { get; private set; }
/// <see cref="object.ToString"/>
public override string ToString()
{
return Source.Name;
}
private readonly ICollection<TestFunction> _tests;
private readonly ScriptBlockAst _scriptSyntaxTree;
/// <summary>
/// The file extension for PowerShell scripts.
/// </summary>
public const string FileExtension = ".ps1";
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.VisualStudio/Core/PSycheTestRunSettingsTests.cs
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using PSycheTest.Runners.VisualStudio.Core;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.VisualStudio.Core
{
public class PSycheTestRunSettingsTests
{
[Fact]
public void Test_ReadXml()
{
// Arrange.
var xmlReader = XmlReader.Create(new StringReader(
@"<?xml version='1.0' encoding='utf-8' ?>
<RunSettings>
<PSycheTest>
<Modules>
<Module>TestModule1.psd1</Module>
<Module>TestModule2.dll</Module>
</Modules>
</PSycheTest>
</RunSettings>"));
// Act.
settings.ReadXml(xmlReader);
// Assert.
Assert.Equal(new[] { "TestModule1.psd1", "TestModule2.dll" }, settings.Modules.ToArray());
}
[Fact]
public void Test_ReadXml_With_No_PSycheTest_Element()
{
// Arrange.
var xmlReader = XmlReader.Create(new StringReader(
@"<?xml version='1.0' encoding='utf-8' ?>
<RunSettings>
</RunSettings>"));
// Act.
settings.ReadXml(xmlReader);
// Assert.
Assert.Empty(settings.Modules);
}
[Fact]
public void Test_ReadXml_With_No_Modules()
{
// Arrange.
var xmlReader = XmlReader.Create(new StringReader(
@"<?xml version='1.0' encoding='utf-8' ?>
<RunSettings>
<PSycheTest>
</PSycheTest>
</RunSettings>"));
// Act.
settings.ReadXml(xmlReader);
// Assert.
Assert.Empty(settings.Modules);
}
[Fact]
public void Test_WriteXml()
{
// Arrange.
var sink = new StringBuilder();
using (var xmlWriter = XmlWriter.Create(sink, writerSettings))
{
settings.Modules.Add("TestModule1");
settings.Modules.Add(@".\TestModule2.psd1");
// Act.
settings.WriteXml(xmlWriter);
}
// Assert.
Assert.Equal(
@"<Modules><Module>TestModule1</Module><Module>.\TestModule2.psd1</Module></Modules>",
sink.ToString());
}
[Fact]
public void Test_WriteXml_With_No_Modules()
{
// Arrange.
var sink = new StringBuilder();
using (var xmlWriter = XmlWriter.Create(sink, writerSettings))
{
// Act.
settings.WriteXml(xmlWriter);
}
// Assert.
Assert.Equal(@"<Modules />", sink.ToString());
}
private readonly PSycheTestRunSettings settings = new PSycheTestRunSettings();
private static readonly XmlWriterSettings writerSettings = new XmlWriterSettings
{
ConformanceLevel = ConformanceLevel.Fragment,
Encoding = Encoding.UTF8,
OmitXmlDeclaration = true
};
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Channels.cs
using System.Runtime.Remoting.Channels;
namespace PSycheTest.Runners.VisualStudio.Core
{
/// <summary>
/// Contains methods to help with channel cleanup.
/// </summary>
internal static class Channels
{
/// <summary>
/// Unregisters any currently registered remoting channels.
/// </summary>
/// <remarks>
/// After looking at other Visual Studio test runners, apparently remoting channels are opened but
/// not cleaned up by Visual Studio and so this is necessary.
/// </remarks>
internal static void UnregisterAll()
{
foreach (IChannel chan in ChannelServices.RegisteredChannels)
ChannelServices.UnregisterChannel(chan);
}
}
}<file_sep>/PSycheTest.Runners.Framework/TestScriptStartingEventArgs.cs
using System;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Contains diagnostic information about when a test script is about to start.
/// </summary>
public class TestScriptStartingEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of <see cref="TestScriptStartingEventArgs"/>.
/// </summary>
/// <param name="script">The test script that is starting</param>
public TestScriptStartingEventArgs(ITestScript script)
{
Script = script;
}
/// <summary>
/// The test script that is starting.
/// </summary>
public ITestScript Script { get; private set; }
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/SolutionInfo.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace PSycheTest.Runners.VisualStudio.Core
{
/// <summary>
/// Provides information about an <see cref="IVsSolution"/>.
/// </summary>
internal class SolutionInfo : ISolutionInfo
{
/// <summary>
/// Initializes a new <see cref="SolutionInfo"/>.
/// </summary>
/// <param name="solution">The solution to provide information about</param>
public SolutionInfo(IVsSolution solution)
{
_solution = solution;
}
/// <see cref="ISolutionInfo.GetProjects"/>
public IEnumerable<IVsProject> GetProjects()
{
return GetChildren(__VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION).OfType<IVsProject>();
}
/// <summary>
/// Iterates over the child items of an <see cref="IVsSolution"/>.
/// </summary>
/// <param name="enumFlags">Project options</param>
private IEnumerable<IVsHierarchy> GetChildren(__VSENUMPROJFLAGS enumFlags)
{
var projectType = Guid.Empty;
IEnumHierarchies hierarchyEnum;
var result = _solution.GetProjectEnum((uint)enumFlags, ref projectType, out hierarchyEnum);
if (ErrorHandler.Succeeded(result) && hierarchyEnum != null)
{
uint fetched;
var hierarchies = new IVsHierarchy[1];
while (hierarchyEnum.Next(1, hierarchies, out fetched) == VSConstants.S_OK)
{
yield return hierarchies[0];
}
}
}
/// <see cref="ISolutionInfo.GetDirectory"/>
public DirectoryInfo GetDirectory()
{
string directory;
string file;
string userOptionsFile;
int result = _solution.GetSolutionInfo(out directory, out file, out userOptionsFile);
ErrorHandler.ThrowOnFailure(result);
return new DirectoryInfo(directory);
}
private readonly IVsSolution _solution;
}
}<file_sep>/PSycheTest.Runners.VisualStudio/VSTestDiscoverer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using PSycheTest.Runners.Framework;
using PSycheTest.Runners.VisualStudio.Core;
namespace PSycheTest.Runners.VisualStudio
{
/// <summary>
/// An <see cref="ITestDiscoverer"/> that parses PowerShell scripts and turns them into test cases.
/// </summary>
[FileExtension(TestScript.FileExtension)]
[DefaultExecutorUri(VSTestExecutor.ExecutorUriString)]
[Export(typeof(ITestDiscoverer))]
public class VSTestDiscoverer : ITestDiscoverer
{
/// <summary>
/// Initializes a new <see cref="VSTestDiscoverer"/>.
/// </summary>
[ImportingConstructor]
public VSTestDiscoverer()
: this(logger => new PowerShellTestDiscoverer(logger))
{
}
/// <summary>
/// Initializes a new <see cref="VSTestDiscoverer"/>.
/// </summary>
/// <param name="discovererFactory">Creates test discoverers</param>
public VSTestDiscoverer(Func<ILogger, IPowerShellTestDiscoverer> discovererFactory)
{
_discovererFactory = discovererFactory;
}
/// <see cref="ITestDiscoverer.DiscoverTests"/>
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
{
Channels.UnregisterAll();
var discoverer = _discovererFactory(new VSLogger(logger));
var tests = discoverer.Discover(sources
.Where(source => Path.GetExtension(source).Equals(TestScript.FileExtension, StringComparison.InvariantCultureIgnoreCase))
.Select(s => new FileInfo(s)))
.SelectMany(testScript => testScript.Tests)
.Select(test => _mapper.Map(test));
foreach (var test in tests)
discoverySink.SendTestCase(test);
}
private readonly TestMapper _mapper = new TestMapper();
private readonly Func<ILogger, IPowerShellTestDiscoverer> _discovererFactory;
}
}<file_sep>/Tests.Unit/SyntaxTree.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;
using Moq;
using PSycheTest.Runners.Framework.Utilities.Collections;
namespace Tests.Unit
{
/// <summary>
/// Creates PowerShell syntax trees for testing purposes.
/// </summary>
public static class SyntaxTree
{
public static FunctionDefinitionAst OfFunctionNamed(string name, string fromFile = DefaultFileName, bool hasParamBlock = true, AttributeAst attribute = null, IScriptExtent extent = null)
{
var scriptExtent = extent ?? Extent(fromFile, 4, 5);
var body = new ScriptBlockAst(scriptExtent,
hasParamBlock
? ParamBlock(scriptExtent, attribute: attribute)
: null,
StatementBlock(scriptExtent), false);
return new FunctionDefinitionAst(scriptExtent, false, false, name, Enumerable.Empty<ParameterAst>(), body);
}
public static AttributeAst OfAttribute<TAttribute>(IEnumerable<ExpressionAst> positionalArguments = null, IEnumerable<NamedAttributeArgumentAst> namedArguments = null)
where TAttribute : Attribute
{
var typeName = Mock.Of<ITypeName>(t =>
t.GetReflectionAttributeType() == typeof(TAttribute) &&
t.Name == typeof(TAttribute).Name.Replace("Attribute", string.Empty) &&
t.FullName == typeof(TAttribute).FullName.Replace("Attribute", string.Empty));
return new AttributeAst(Mock.Of<IScriptExtent>(),
typeName,
positionalArguments ?? Enumerable.Empty<ExpressionAst>(),
namedArguments ?? Enumerable.Empty<NamedAttributeArgumentAst>());
}
public static ScriptBlockAst OfScript(string file = DefaultFileName, bool hasParamBlock = true, AttributeAst attribute = null, IEnumerable<StatementAst> statements = null)
{
var extent = Extent(file, 4, 5);
return new ScriptBlockAst(extent,
hasParamBlock
? ParamBlock(extent, attribute: attribute)
: null,
StatementBlock(extent, statements), false);
}
public static IScriptExtent Extent(string fileName = DefaultFileName, int startLine = 0, int startColumn = 0, string text = "")
{
return Mock.Of<IScriptExtent>(e =>
e.File == fileName &&
e.Text == text &&
e.StartLineNumber == startLine &&
e.StartColumnNumber == startColumn);
}
public static ParamBlockAst ParamBlock(IScriptExtent extent, IEnumerable<ParameterAst> parameters = null, AttributeAst attribute = null)
{
return new ParamBlockAst(extent,
attribute == null ? Enumerable.Empty<AttributeAst>() : attribute.ToEnumerable(),
parameters ?? Enumerable.Empty<ParameterAst>());
}
public static StatementBlockAst StatementBlock(IScriptExtent extent, IEnumerable<StatementAst> statements = null)
{
return new StatementBlockAst(extent, statements ?? Enumerable.Empty<StatementAst>(), Enumerable.Empty<TrapStatementAst>());
}
private const string DefaultFileName = @".\File.ps1";
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/ActivityLogger.cs
using System;
using Microsoft.VisualStudio.Shell.Interop;
using PSycheTest.Runners.Framework;
namespace PSycheTest.Runners.VisualStudio.Core
{
/// <summary>
/// An <see cref="ILogger"/> that writes to the Visual Studio Activity Log.
/// </summary>
public class ActivityLogger : ILogger
{
/// <summary>
/// Initializes a new <see cref="ActivityLogger"/>.
/// </summary>
/// <param name="activityLog">The Visual Studio activity log</param>
/// <param name="logType">The type a logger is for</param>
public ActivityLogger(IVsActivityLog activityLog, Type logType)
{
_activityLog = activityLog;
_logType = logType;
}
/// <see cref="ILogger.Info"/>
public void Info(string message, params object[] arguments)
{
Log(__ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION, message, arguments);
}
/// <see cref="ILogger.Warn"/>
public void Warn(string message, params object[] arguments)
{
Log(__ACTIVITYLOG_ENTRYTYPE.ALE_WARNING, message, arguments);
}
/// <see cref="ILogger.Error"/>
public void Error(string message, params object[] arguments)
{
Log(__ACTIVITYLOG_ENTRYTYPE.ALE_ERROR, message, arguments);
}
private void Log(__ACTIVITYLOG_ENTRYTYPE level, string message, params object[] arguments)
{
_activityLog.LogEntry((uint)level, _logType.Name, String.Format(message, arguments));
}
private readonly IVsActivityLog _activityLog;
private readonly Type _logType;
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Monitoring/ProjectFileMonitor.cs
using System;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using PSycheTest.Runners.VisualStudio.Core.Utilities;
namespace PSycheTest.Runners.VisualStudio.Core.Monitoring
{
/// <summary>
/// Monitors projects for changes to child items.
/// </summary>
[Export(typeof(IProjectFileMonitor))]
public class ProjectFileMonitor : IProjectFileMonitor, IVsTrackProjectDocumentsEvents2
{
/// <summary>
/// Initializes a new <see cref="ProjectFileMonitor"/>.
/// </summary>
/// <param name="serviceProvider">Provides access to services</param>
[ImportingConstructor]
public ProjectFileMonitor([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider)
{
ValidateArg.NotNull(serviceProvider, "serviceProvider");
_projectDocumentTracker = serviceProvider.GetService<IVsTrackProjectDocuments2, SVsTrackProjectDocuments>();
}
/// <see cref="IProjectFileMonitor.FileChanged"/>
public event EventHandler<ProjectFileChangedEventArgs> FileChanged;
private void OnFileChanged(IVsProject project, string filePath, FileChangeType changeType)
{
var localEvent = FileChanged;
if (localEvent != null)
localEvent(this, new ProjectFileChangedEventArgs(project, filePath, changeType));
}
private void OnFilesChanged(int changedProjectCount, IVsProject[] projects, int[] projectStartIndices, int changedFileCount, string[] changedFiles, FileChangeType changeType)
{
for (int projectIndex = 0; projectIndex < changedProjectCount; projectIndex++)
{
var project = projects[projectIndex];
var fileIndexUpperBound = projectIndex == changedProjectCount - 1 ? changedFileCount : projectStartIndices[projectIndex + 1];
for (int fileIndex = projectStartIndices[projectIndex]; fileIndex < fileIndexUpperBound; fileIndex++)
{
var file = changedFiles[fileIndex];
OnFileChanged(project, file, changeType);
}
}
}
/// <see cref="IProjectFileMonitor.StartMonitoring"/>
public void StartMonitoring()
{
if (_projectDocumentTracker == null)
return;
// Subscribe to project events.
int result = _projectDocumentTracker.AdviseTrackProjectDocumentsEvents(this, out _cookie);
ErrorHandler.ThrowOnFailure(result);
}
/// <see cref="IProjectFileMonitor.StopMonitoring"/>
public void StopMonitoring()
{
if (_projectDocumentTracker == null || _cookie == VSConstants.VSCOOKIE_NIL)
return;
// Unsubscribe from project events.
int result = _projectDocumentTracker.UnadviseTrackProjectDocumentsEvents(_cookie);
ErrorHandler.Succeeded(result); // Ignore failure.
_cookie = VSConstants.VSCOOKIE_NIL; // Clear cookie value.
}
/// <see cref="IVsTrackProjectDocumentsEvents2.OnAfterAddFilesEx"/>
public int OnAfterAddFilesEx(int cProjects, int cFiles, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgpszMkDocuments, VSADDFILEFLAGS[] rgFlags)
{
OnFilesChanged(cProjects, rgpProjects, rgFirstIndices, cFiles, rgpszMkDocuments, FileChangeType.Added);
return VSConstants.S_OK;
}
/// <see cref="IVsTrackProjectDocumentsEvents2.OnAfterRemoveFiles"/>
public int OnAfterRemoveFiles(int cProjects, int cFiles, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgpszMkDocuments, VSREMOVEFILEFLAGS[] rgFlags)
{
OnFilesChanged(cProjects, rgpProjects, rgFirstIndices, cFiles, rgpszMkDocuments, FileChangeType.Removed);
return VSConstants.S_OK;
}
/// <see cref="IVsTrackProjectDocumentsEvents2.OnAfterRenameFiles"/>
public int OnAfterRenameFiles(int cProjects, int cFiles, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgszMkOldNames, string[] rgszMkNewNames, VSRENAMEFILEFLAGS[] rgFlags)
{
OnFilesChanged(cProjects, rgpProjects, rgFirstIndices, cFiles, rgszMkOldNames, FileChangeType.Removed);
OnFilesChanged(cProjects, rgpProjects, rgFirstIndices, cFiles, rgszMkNewNames, FileChangeType.Added);
return VSConstants.S_OK;
}
#region Unused Project File Events
/// <see cref="IVsTrackProjectDocumentsEvents2.OnQueryAddFiles"/>
public int OnQueryAddFiles(IVsProject pProject, int cFiles, string[] rgpszMkDocuments, VSQUERYADDFILEFLAGS[] rgFlags, VSQUERYADDFILERESULTS[] pSummaryResult,
VSQUERYADDFILERESULTS[] rgResults)
{
return VSConstants.S_OK;
}
/// <see cref="IVsTrackProjectDocumentsEvents2.OnAfterAddDirectoriesEx"/>
public int OnAfterAddDirectoriesEx(int cProjects, int cDirectories, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgpszMkDocuments, VSADDDIRECTORYFLAGS[] rgFlags)
{
return VSConstants.S_OK;
}
/// <see cref="IVsTrackProjectDocumentsEvents2.OnAfterRemoveDirectories"/>
public int OnAfterRemoveDirectories(int cProjects, int cDirectories, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgpszMkDocuments, VSREMOVEDIRECTORYFLAGS[] rgFlags)
{
return VSConstants.S_OK;
}
/// <see cref="IVsTrackProjectDocumentsEvents2.OnQueryRenameFiles"/>
public int OnQueryRenameFiles(IVsProject pProject, int cFiles, string[] rgszMkOldNames, string[] rgszMkNewNames, VSQUERYRENAMEFILEFLAGS[] rgFlags,
VSQUERYRENAMEFILERESULTS[] pSummaryResult, VSQUERYRENAMEFILERESULTS[] rgResults)
{
return VSConstants.S_OK;
}
/// <see cref="IVsTrackProjectDocumentsEvents2.OnQueryRenameDirectories"/>
public int OnQueryRenameDirectories(IVsProject pProject, int cDirs, string[] rgszMkOldNames, string[] rgszMkNewNames, VSQUERYRENAMEDIRECTORYFLAGS[] rgFlags,
VSQUERYRENAMEDIRECTORYRESULTS[] pSummaryResult, VSQUERYRENAMEDIRECTORYRESULTS[] rgResults)
{
return VSConstants.S_OK;
}
/// <see cref="IVsTrackProjectDocumentsEvents2.OnAfterRenameDirectories"/>
public int OnAfterRenameDirectories(int cProjects, int cDirs, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgszMkOldNames, string[] rgszMkNewNames,
VSRENAMEDIRECTORYFLAGS[] rgFlags)
{
return VSConstants.S_OK;
}
/// <see cref="IVsTrackProjectDocumentsEvents2.OnQueryAddDirectories"/>
public int OnQueryAddDirectories(IVsProject pProject, int cDirectories, string[] rgpszMkDocuments, VSQUERYADDDIRECTORYFLAGS[] rgFlags, VSQUERYADDDIRECTORYRESULTS[] pSummaryResult,
VSQUERYADDDIRECTORYRESULTS[] rgResults)
{
return VSConstants.S_OK;
}
/// <see cref="IVsTrackProjectDocumentsEvents2.OnQueryRemoveFiles"/>
public int OnQueryRemoveFiles(IVsProject pProject, int cFiles, string[] rgpszMkDocuments, VSQUERYREMOVEFILEFLAGS[] rgFlags, VSQUERYREMOVEFILERESULTS[] pSummaryResult,
VSQUERYREMOVEFILERESULTS[] rgResults)
{
return VSConstants.S_OK;
}
/// <see cref="IVsTrackProjectDocumentsEvents2.OnQueryRemoveDirectories"/>
public int OnQueryRemoveDirectories(IVsProject pProject, int cDirectories, string[] rgpszMkDocuments, VSQUERYREMOVEDIRECTORYFLAGS[] rgFlags, VSQUERYREMOVEDIRECTORYRESULTS[] pSummaryResult,
VSQUERYREMOVEDIRECTORYRESULTS[] rgResults)
{
return VSConstants.S_OK;
}
/// <see cref="IVsTrackProjectDocumentsEvents2.OnAfterSccStatusChanged"/>
public int OnAfterSccStatusChanged(int cProjects, int cFiles, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgpszMkDocuments, uint[] rgdwSccStatus)
{
return VSConstants.S_OK;
}
#endregion Unused Project File Events
private uint _cookie = VSConstants.VSCOOKIE_NIL;
private readonly IVsTrackProjectDocuments2 _projectDocumentTracker;
}
}<file_sep>/PSycheTest.Runners.Framework/ParseResult.cs
using System.Collections.Generic;
using System.Management.Automation.Language;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Contains the results of a parse operation.
/// </summary>
internal class ParseResult
{
/// <summary>
/// Initializes a new <see cref="ParseResult"/>.
/// </summary>
/// <param name="syntaxTree">The resulting abstract syntax tree</param>
/// <param name="tokens">Parsed tokens</param>
/// <param name="errors">Any parsing errors</param>
public ParseResult(ScriptBlockAst syntaxTree, IEnumerable<Token> tokens, IEnumerable<ParseError> errors)
{
SyntaxTree = syntaxTree;
Tokens = tokens;
Errors = errors;
}
/// <summary>
/// The resulting abstract syntax tree.
/// </summary>
public ScriptBlockAst SyntaxTree { get; private set; }
/// <summary>
/// Parsed tokens.
/// </summary>
public IEnumerable<Token> Tokens { get; private set; }
/// <summary>
/// Any parsing errors.
/// </summary>
public IEnumerable<ParseError> Errors { get; private set; }
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/VisualStudioHierarchyExtensions.cs
using System;
using Microsoft.VisualStudio.Shell.Interop;
namespace PSycheTest.Runners.VisualStudio.Core
{
/// <summary>
/// Contains extension methods for Visual Studio project hierarchy-related objects.
/// </summary>
public static class VisualStudioHierarchyExtensions
{
/// <summary>
/// Provides access to additional information about a solution.
/// </summary>
/// <param name="solution">The solution to provide information about</param>
/// <returns>An object with access to more solution data</returns>
public static ISolutionInfo Info(this IVsSolution solution)
{
return SolutionInfoFactory(solution);
}
/// <summary>
/// Provides access to additional information about a project.
/// </summary>
/// <param name="project">The project to provide information about</param>
/// <returns>An object with access to more project data</returns>
public static IProjectInfo Info(this IVsProject project)
{
return ProjectInfoFactory(project);
}
/// <summary>
/// Factory for <see cref="ISolutionInfo"/>s.
/// </summary>
internal static Func<IVsSolution, ISolutionInfo> SolutionInfoFactory = solution => new SolutionInfo(solution);
/// <summary>
/// Factory for <see cref="IProjectInfo"/>s.
/// </summary>
internal static Func<IVsProject, IProjectInfo> ProjectInfoFactory = project => new ProjectInfo(project);
}
}<file_sep>/PSycheTest/Exceptions/SequenceEqualException.cs
using System;
using System.Collections;
using System.Linq;
using System.Runtime.Serialization;
namespace PSycheTest.Exceptions
{
/// <summary>
/// Exceptionsthrown when two sequences are not equivalent.
/// </summary>
[Serializable]
public class SequenceEqualException : AssertionException
{
/// <summary>
/// Creates a new instance of the <see cref="SequenceEqualException"/> class.
/// </summary>
/// <param name="expected">The expected sequence</param>
/// <param name="expectedFullyDrained">Whether the entirety of the expected sequence was evaluated</param>
/// <param name="actual">The actual sequence</param>
/// <param name="actualFullyDrained">Whether the entirety of the actual sequence was evaluated</param>
public SequenceEqualException(IEnumerable expected, bool expectedFullyDrained, IEnumerable actual, bool actualFullyDrained)
: base(typeof(SequenceEqualException).Name + " : SequenceEqual Assertion Failure")
{
_expected = expected;
_actual = actual;
_expectedFullyDrained = expectedFullyDrained;
_actualFullyDrained = actualFullyDrained;
Actual = String.Join(",", _actual.Cast<object>());
Expected = String.Join(",", _expected.Cast<object>());
}
/// <summary>
/// Gets the actual sequence.
/// </summary>
public string Actual { get; private set; }
/// <summary>
/// Gets the expected sequence.
/// </summary>
public string Expected { get; private set; }
/// <summary>
/// Gets a message that describes the current exception.
/// </summary>
/// <returns>The error message that explains the reason for the exception, or an empty string("").</returns>
public override string Message
{
get
{
return String.Format("{0}{1}Expected: {2}{3}{1}Actual: {4}{5}",
base.Message,
Environment.NewLine,
Expected == string.Empty ? EMPTY_COLLECTION_MESSAGE : Expected,
_expectedFullyDrained ? string.Empty : ",...",
Actual == string.Empty ? EMPTY_COLLECTION_MESSAGE : Actual,
_actualFullyDrained ? string.Empty : ",...");
}
}
/// <see cref="System.Exception(SerializationInfo, StreamingContext)"/>
protected SequenceEqualException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
/// <see cref="ISerializable.GetObjectData"/>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
base.GetObjectData(info, context);
}
private readonly IEnumerable _expected;
private readonly IEnumerable _actual;
private readonly bool _expectedFullyDrained;
private readonly bool _actualFullyDrained;
private const string EMPTY_COLLECTION_MESSAGE = "Empty Sequence";
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/VSLogger.cs
using System;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using PSycheTest.Runners.Framework;
namespace PSycheTest.Runners.VisualStudio.Core
{
/// <summary>
/// An <see cref="ILogger"/> based on <see cref="IMessageLogger"/>.
/// </summary>
internal class VSLogger : ILogger
{
/// <summary>
/// Initializes a new <see cref="VSLogger"/>.
/// </summary>
/// <param name="innerLogger">A Visual Studio message logger.</param>
public VSLogger(IMessageLogger innerLogger)
{
_innerLogger = innerLogger;
}
/// <see cref="ILogger.Info"/>
public void Info(string message, params object[] arguments)
{
Log(TestMessageLevel.Informational, message, arguments);
}
/// <see cref="ILogger.Warn"/>
public void Warn(string message, params object[] arguments)
{
Log(TestMessageLevel.Warning, message, arguments);
}
/// <see cref="ILogger.Error"/>
public void Error(string message, params object[] arguments)
{
Log(TestMessageLevel.Error, message, arguments);
}
private void Log(TestMessageLevel level, string message, params object[] arguments)
{
_innerLogger.SendMessage(level, String.Format(message, arguments));
}
private readonly IMessageLogger _innerLogger;
}
}<file_sep>/PSycheTest/TestCleanupAttribute.cs
using System;
namespace PSycheTest
{
/// <summary>
/// Indicates that a function should be run after each test in a script.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class TestCleanupAttribute : Attribute { }
}<file_sep>/PSycheTest/AssertionCmdletBase.cs
using System.Management.Automation;
namespace PSycheTest
{
/// <summary>
/// Base class for assertion cmdlets.
/// </summary>
public abstract class AssertionCmdletBase : PSCmdlet
{
/// <summary>
/// An optional user message.
/// </summary>
[Parameter(Mandatory = false)]
public string Message { get; set; }
/// <see cref="Cmdlet.ProcessRecord"/>
protected override void ProcessRecord()
{
Assert();
}
/// <summary>
/// Executes a cmdlet's assertion.
/// </summary>
protected abstract void Assert();
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.VisualStudio/Core/Monitoring/SolutionMonitorTests.cs
using System;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Moq;
using PSycheTest.Runners.VisualStudio.Core.Monitoring;
using Tests.Support;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.VisualStudio.Core.Monitoring
{
public class SolutionMonitorTests
{
public SolutionMonitorTests()
{
serviceProvider.Setup(sp => sp.GetService(typeof(SVsSolution)))
.Returns(solution.Object);
monitor = new SolutionMonitor(serviceProvider.Object);
}
[Fact]
public void Test_StartMonitoring()
{
// Act.
monitor.StartMonitoring();
// Assert.
uint cookie;
solution.Verify(s => s.AdviseSolutionEvents(monitor, out cookie));
}
[Fact]
public void Test_StopMonitoring()
{
// Arrange.
uint cookie = 123;
solution.Setup(s => s.AdviseSolutionEvents(monitor, out cookie));
monitor.StartMonitoring();
// Act.
monitor.StopMonitoring();
// Assert.
solution.Verify(s => s.UnadviseSolutionEvents(123));
}
[Fact]
public void Test_OnAfterOpenSolution()
{
// Act/Assert.
int result = Int32.MinValue;
AssertThat.DoesNotRaise<ISolutionMonitor>(
monitor, sm => sm.SolutionChanged += null,
() => result = monitor.OnAfterOpenSolution(null, 0));
Assert.Equal(VSConstants.S_OK, result);
}
[Fact]
public void Test_OnAfterCloseSolution()
{
// Act/Assert.
int result = Int32.MinValue;
var args = AssertThat.RaisesWithEventArgs<ISolutionMonitor, SolutionChangedEventArgs>(
monitor, sm => sm.SolutionChanged += null,
() => result = monitor.OnAfterCloseSolution(null));
Assert.Equal(VSConstants.S_OK, result);
Assert.Equal(SolutionChangeType.Unloaded, args.ChangeType);
Assert.Equal(solution.Object, args.Solution);
}
[Fact]
public void Test_OnAfterBackgroundSolutionLoadComplete()
{
// Act/Assert.
int result = Int32.MinValue;
var args = AssertThat.RaisesWithEventArgs<ISolutionMonitor, SolutionChangedEventArgs>(
monitor, sm => sm.SolutionChanged += null,
() => result = monitor.OnAfterBackgroundSolutionLoadComplete());
Assert.Equal(VSConstants.S_OK, result);
Assert.Equal(SolutionChangeType.Loaded, args.ChangeType);
Assert.Equal(solution.Object, args.Solution);
}
[Fact]
public void Test_OnAfterLoadProject()
{
// Act/Assert.
int result = Int32.MinValue;
var args = AssertThat.RaisesWithEventArgs<ISolutionMonitor, ProjectChangedEventArgs>(
monitor, sm => sm.ProjectChanged += null,
() => result = monitor.OnAfterLoadProject(null, project.As<IVsHierarchy>().Object));
Assert.Equal(VSConstants.S_OK, result);
Assert.Equal(ProjectChangeType.Loaded, args.ChangeType);
Assert.Equal(solution.Object, args.Solution);
Assert.Equal(project.Object, args.Project);
}
[Fact]
public void Test_OnBeforeUnloadProject()
{
// Act/Assert.
int result = Int32.MinValue;
var args = AssertThat.RaisesWithEventArgs<ISolutionMonitor, ProjectChangedEventArgs>(
monitor, sm => sm.ProjectChanged += null,
() => result = monitor.OnBeforeUnloadProject(project.As<IVsHierarchy>().Object, null));
Assert.Equal(VSConstants.S_OK, result);
Assert.Equal(ProjectChangeType.Unloaded, args.ChangeType);
Assert.Equal(solution.Object, args.Solution);
Assert.Equal(project.Object, args.Project);
}
private readonly SolutionMonitor monitor;
private readonly Mock<IVsProject> project = new Mock<IVsProject>();
private readonly Mock<IVsSolution> solution = new Mock<IVsSolution>();
private readonly Mock<IServiceProvider> serviceProvider = new Mock<IServiceProvider>();
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Monitoring/SolutionChangeType.cs
namespace PSycheTest.Runners.VisualStudio.Core.Monitoring
{
/// <summary>
/// Contains possible Visual Studio solution changes.
/// </summary>
public enum SolutionChangeType
{
/// <summary>
/// Indicates a solution was loaded.
/// </summary>
Loaded,
/// <summary>
/// Indicates a solution was unloaded.
/// </summary>
Unloaded
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Monitoring/ProjectChangedEventArgs.cs
using System;
using Microsoft.VisualStudio.Shell.Interop;
namespace PSycheTest.Runners.VisualStudio.Core.Monitoring
{
/// <summary>
/// Contains information about project changes.
/// </summary>
public sealed class ProjectChangedEventArgs : EventArgs
{
/// <summary>
/// Initializes new event args.
/// </summary>
/// <param name="solution">The parent solution</param>
/// <param name="project">The project that changed</param>
/// <param name="changeType">The type of change</param>
public ProjectChangedEventArgs(IVsSolution solution, IVsProject project, ProjectChangeType changeType)
{
Solution = solution;
Project = project;
ChangeType = changeType;
}
/// <summary>
/// The parent solution.
/// </summary>
public IVsSolution Solution { get; private set; }
/// <summary>
/// The project that changed.
/// </summary>
public IVsProject Project { get; private set; }
/// <summary>
/// The type of change.
/// </summary>
public ProjectChangeType ChangeType { get; private set; }
}
}<file_sep>/PSycheTest/AssertNotNullCmdlet.cs
using System.Management.Automation;
using PSycheTest.Exceptions;
namespace PSycheTest
{
/// <summary>
/// Cmdlet that verifies that a value is not null.
/// </summary>
[Cmdlet(VerbsLifecycle.Assert, "NotNull")]
public class AssertNotNullCmdlet : AssertionCmdletBase
{
/// <summary>
/// The value that should not be null.
/// </summary>
[Parameter(Mandatory = true, Position = 0)]
[AllowNull]
public object Value { get; set; }
/// <see cref="AssertionCmdletBase.Assert"/>
protected override void Assert()
{
if (Value == null)
throw new AssertionException(Message ?? "Assert-NotNull Failure");
}
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.Framework/TestDiscoveryVisitorTests.cs
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;
using Moq;
using PSycheTest;
using PSycheTest.Runners.Framework;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.Framework
{
public class TestDiscoveryVisitorTests
{
[Fact]
public void Test_Visit()
{
// Arrange.
var functionSyntaxTree = SyntaxTree.OfFunctionNamed("Test-Function",
attribute: SyntaxTree.OfAttribute<TestAttribute>());
// Act.
functionSyntaxTree.Visit(visitor);
// Assert.
Assert.Single(visitor.TestFunctions);
Assert.False(visitor.TestSetupFunction.HasValue);
Assert.False(visitor.TestCleanupFunction.HasValue);
var function = visitor.TestFunctions.Single();
Assert.Equal("Test-Function", function.Name);
var compiled = function.Body.GetScriptBlock();
Assert.Single(compiled.Attributes.OfType<TestAttribute>());
}
[Fact]
public void Test_Visit_With_Invalid_Attribute_Constructor_Arguments()
{
// Arrange.
var positionalArgs = new List<ExpressionAst>
{
new ConstantExpressionAst(Mock.Of<IScriptExtent>(), "invalid")
};
var functionSyntaxTree = SyntaxTree.OfFunctionNamed("Test-Function",
attribute: SyntaxTree.OfAttribute<TestAttribute>(positionalArgs));
// Act.
functionSyntaxTree.Visit(visitor);
// Assert.
Assert.Empty(visitor.TestFunctions);
}
[Fact]
public void Test_Visit_With_Invalid_Attribute_Property_Count()
{
// Arrange.
var extent = Mock.Of<IScriptExtent>();
var namedArgs = new List<NamedAttributeArgumentAst>
{
new NamedAttributeArgumentAst(extent, "Description", new ConstantExpressionAst(extent, "descr"), false),
new NamedAttributeArgumentAst(extent, "NonExistent", new ConstantExpressionAst(extent, "invalid"), false)
};
var functionSyntaxTree = SyntaxTree.OfFunctionNamed("Test-Function",
attribute: SyntaxTree.OfAttribute<TestAttribute>(namedArguments:namedArgs));
// Act.
functionSyntaxTree.Visit(visitor);
// Assert.
Assert.Empty(visitor.TestFunctions);
}
[Fact]
public void Test_Visit_With_Invalid_Attribute_Property_Type()
{
// Arrange.
var extent = Mock.Of<IScriptExtent>();
var namedArgs = new List<NamedAttributeArgumentAst>
{
new NamedAttributeArgumentAst(extent, "Description", new ConstantExpressionAst(extent, 1), false),
};
var functionSyntaxTree = SyntaxTree.OfFunctionNamed("Test-Function",
attribute: SyntaxTree.OfAttribute<TestAttribute>(namedArguments: namedArgs));
// Act.
functionSyntaxTree.Visit(visitor);
// Assert.
Assert.Empty(visitor.TestFunctions);
}
[Fact]
public void Test_Visit_With_No_Test_Attribute()
{
// Arrange.
var functionSyntaxTree = SyntaxTree.OfFunctionNamed("Test-Function");
// Act.
functionSyntaxTree.Visit(visitor);
// Assert.
Assert.Empty(visitor.TestFunctions);
Assert.False(visitor.TestSetupFunction.HasValue);
Assert.False(visitor.TestCleanupFunction.HasValue);
}
[Fact]
public void Test_Visit_With_No_Param_Block()
{
// Arrange.
var functionSyntaxTree = SyntaxTree.OfFunctionNamed("Test-Function", hasParamBlock:false);
// Act.
functionSyntaxTree.Visit(visitor);
// Assert.
Assert.Empty(visitor.TestFunctions);
Assert.False(visitor.TestSetupFunction.HasValue);
Assert.False(visitor.TestCleanupFunction.HasValue);
}
[Fact]
public void Test_Visit_Setup_Attribute()
{
// Arrange.
var functionSyntaxTree = SyntaxTree.OfFunctionNamed("Setup-Function",
attribute: SyntaxTree.OfAttribute<TestSetupAttribute>());
// Act.
functionSyntaxTree.Visit(visitor);
// Assert.
Assert.True(visitor.TestSetupFunction.HasValue);
Assert.False(visitor.TestCleanupFunction.HasValue);
var setup = visitor.TestSetupFunction.Value;
Assert.Equal("Setup-Function", setup.Name);
var compiled = setup.Body.GetScriptBlock();
Assert.Single(compiled.Attributes.OfType<TestSetupAttribute>());
}
[Fact]
public void Test_Visit_Cleanup_Attribute()
{
// Arrange.
var functionSyntaxTree = SyntaxTree.OfFunctionNamed("Cleanup-Function",
attribute: SyntaxTree.OfAttribute<TestCleanupAttribute>());
// Act.
functionSyntaxTree.Visit(visitor);
// Assert.
Assert.True(visitor.TestCleanupFunction.HasValue);
Assert.False(visitor.TestSetupFunction.HasValue);
var cleanup = visitor.TestCleanupFunction.Value;
Assert.Equal("Cleanup-Function", cleanup.Name);
var compiled = cleanup.Body.GetScriptBlock();
Assert.Single(compiled.Attributes.OfType<TestCleanupAttribute>());
}
private readonly TestDiscoveryVisitor visitor = new TestDiscoveryVisitor();
}
}<file_sep>/README.md
PSycheTest
==========
PSycheTest is a framework that enables running tests written in PowerShell.
Currently there is only one test runner, a plugin for Visual Studio/Team Foundation Server.
<file_sep>/PSycheTest.Runners.Framework/Timers/ITestTimer.cs
using System;
namespace PSycheTest.Runners.Framework.Timers
{
/// <summary>
/// Interface for a timer for tests.
/// </summary>
public interface ITestTimer
{
/// <summary>
/// Starts a timer and returns a token that will
/// automatically stop the timer when disposed.
/// </summary>
IDisposable Start();
/// <summary>
/// Stops a timer.
/// </summary>
void Stop();
/// <summary>
/// The amount of time elapsed.
/// </summary>
TimeSpan Elapsed { get; }
}
}<file_sep>/PSycheTest.Runners.Framework/IPowerShellTestDiscoverer.cs
using System.Collections.Generic;
using System.IO;
using PSycheTest.Runners.Framework.Utilities;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Interface for an object that finds PowerShell tests.
/// </summary>
public interface IPowerShellTestDiscoverer
{
/// <summary>
/// Finds test cases in a collection of script files.
/// </summary>
/// <param name="sourceFiles">The script files to search for test cases</param>
/// <returns>Any discovered test cases</returns>
IEnumerable<ITestScript> Discover(IEnumerable<FileInfo> sourceFiles);
/// <summary>
/// Finds test cases in a single file.
/// </summary>
/// <param name="sourceFile">The file to search for test cases</param>
/// <returns>Any discovered test cases</returns>
Option<ITestScript> Discover(FileInfo sourceFile);
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.VisualStudio/VSTestContainerDiscovererTests.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestWindow.Extensibility;
using Moq;
using PSycheTest.Runners.VisualStudio;
using PSycheTest.Runners.VisualStudio.Core;
using PSycheTest.Runners.VisualStudio.Core.Monitoring;
using PSycheTest.Runners.VisualStudio.Core.Utilities.InputOutput;
using Tests.Support;
using Xunit;
using ILogger = PSycheTest.Runners.Framework.ILogger;
namespace Tests.Unit.PSycheTest.Runners.VisualStudio
{
public class VSTestContainerDiscovererTests : IDisposable
{
public VSTestContainerDiscovererTests()
{
originalSolutionInfoFactory = VisualStudioHierarchyExtensions.SolutionInfoFactory;
VisualStudioHierarchyExtensions.SolutionInfoFactory = p => solutionInfo;
originalProjectInfoFactory = VisualStudioHierarchyExtensions.ProjectInfoFactory;
VisualStudioHierarchyExtensions.ProjectInfoFactory = p => projects[p];
solutionInfo = Mock.Of<ISolutionInfo>(si =>
si.GetProjects() == projects.Keys &&
si.GetDirectory() == new DirectoryInfo(@"C:\Solution"));
serviceProvider.Setup(s => s.GetService(typeof(SVsSolution)))
.Returns(solution.Object);
discoverer = new VSTestContainerDiscoverer(serviceProvider.Object, logger.Object,
solutionMonitor.Object, projectMonitor.Object, fileWatcher.Object, CreateContainer);
}
[Fact]
public void Test_SolutionLoaded()
{
// Arrange.
var projectInfo = Mock.Of<IProjectInfo>(p =>
p.GetProjectItems() == new[] { @"C:\test.ps2", @"file.txt", @"C:\test.ps1" } && p.IsPhysicalProject == true);
projects[Mock.Of<IVsProject>()] = projectInfo;
// Act.
AssertThat.Raises<ITestContainerDiscoverer>(discoverer, d => d.TestContainersUpdated += null,
() => solutionMonitor.Raise(sm => sm.SolutionChanged += null,
new SolutionChangedEventArgs(solution.Object, SolutionChangeType.Loaded)));
// Assert.
var container = Assert.Single(discoverer.TestContainers);
Assert.Equal(@"C:\test.ps1", container.Source);
Assert.Equal(discoverer, container.Discoverer);
}
[Fact]
public void Test_SolutionLoaded_NonPhysical_Projects_Filtered_Out()
{
// Arrange.
var projectInfo = Mock.Of<IProjectInfo>(p =>
p.GetProjectItems() == new[] { @"C:\test.ps2", @"file.txt", @"C:\test.ps1" } && p.IsPhysicalProject == false);
projects[Mock.Of<IVsProject>()] = projectInfo;
// Act.
AssertThat.Raises<ITestContainerDiscoverer>(discoverer, d => d.TestContainersUpdated += null,
() => solutionMonitor.Raise(sm => sm.SolutionChanged += null,
new SolutionChangedEventArgs(solution.Object, SolutionChangeType.Loaded)));
// Assert.
Assert.Empty(discoverer.TestContainers);
}
[Fact]
public void Test_SolutionUnloaded()
{
// Arrange.
InitializeWith(Proj(Mock.Of<IVsProject>(), Mock.Of<IProjectInfo>(p =>
p.GetProjectItems() == new[] { @"C:\test.ps1" } && p.IsPhysicalProject == true)));
// Act.
solutionMonitor.Raise(sm => sm.SolutionChanged += null,
new SolutionChangedEventArgs(solution.Object, SolutionChangeType.Unloaded));
projects.Clear();
// Assert.
Assert.Empty(discoverer.TestContainers);
}
[Fact]
public void Test_SolutionLoaded_Starts_Monitoring_File_Changes()
{
// Act.
solutionMonitor.Raise(sm => sm.SolutionChanged += null,
new SolutionChangedEventArgs(solution.Object, SolutionChangeType.Loaded));
// Assert.
fileWatcher.VerifySet(fw => fw.EnableRaisingEvents = true);
fileWatcher.VerifySet(fw => fw.IncludeSubdirectories = true);
fileWatcher.VerifySet(fw => fw.Path = @"C:\Solution");
fileWatcher.VerifySet(fw => fw.Filter = "*.ps1");
fileWatcher.VerifySet(fw => fw.NotifyFilter = NotifyFilters.LastWrite);
}
[Fact]
public void Test_SolutionUnloaded_Stops_Monitoring_File_Changes()
{
// Act.
solutionMonitor.Raise(sm => sm.SolutionChanged += null,
new SolutionChangedEventArgs(solution.Object, SolutionChangeType.Unloaded));
// Assert.
fileWatcher.VerifySet(fw => fw.EnableRaisingEvents = false);
}
[Fact]
public void Test_ProjectLoaded()
{
// Arrange.
var project = Mock.Of<IVsProject>();
var projectInfo = Mock.Of<IProjectInfo>(p =>
p.GetProjectItems() == new[] { @"C:\test1.ps1" } && p.IsPhysicalProject == true);
projects[project] = projectInfo;
// Act.
AssertThat.Raises<ITestContainerDiscoverer>(discoverer, d => d.TestContainersUpdated += null,
() => solutionMonitor.Raise(sm => sm.ProjectChanged += null,
new ProjectChangedEventArgs(solution.Object, project, ProjectChangeType.Loaded)));
var containers = discoverer.TestContainers.OrderBy(t => t.Source).ToList();
// Assert.
var container = Assert.Single(containers);
Assert.Equal(@"C:\test1.ps1", container.Source);
}
[Fact]
public void Test_ProjectReloaded()
{
// Arrange.
var projectInfo1 = Mock.Of<IProjectInfo>(p =>
p.GetProjectItems() == new[] { @"C:\test1.ps1" } && p.IsPhysicalProject == true);
var project2 = Mock.Of<IVsProject>();
var project2Files = new List<string> { @"C:\test2.ps1", @"C:\test3.ps1" };
var projectInfo2 = Mock.Of<IProjectInfo>(p => p.GetProjectItems() == project2Files);
InitializeWith(Proj(Mock.Of<IVsProject>(), projectInfo1), Proj(project2, projectInfo2));
project2Files.Remove(@"C:\test2.ps1"); // Remove a file from project 2.
// Act.
solutionMonitor.Raise(sm => sm.ProjectChanged += null,
new ProjectChangedEventArgs(solution.Object, project2, ProjectChangeType.Loaded));
var containers = discoverer.TestContainers.OrderBy(t => t.Source).ToList();
// Assert.
Assert.Equal(2, containers.Count);
Assert.Equal(@"C:\test1.ps1", containers.First().Source);
Assert.Equal(@"C:\test3.ps1", containers.Last().Source);
}
[Fact]
public void Test_ProjectUnloaded()
{
// Arrange.
var project1 = Mock.Of<IVsProject>();
var projectInfo1 = Mock.Of<IProjectInfo>(p =>
p.GetProjectItems() == new[] { @"C:\test1.ps1", @"C:\test2.ps1" } && p.IsPhysicalProject == true);
var project2Files = new List<string> { @"C:\test3.ps1" };
var projectInfo2 = Mock.Of<IProjectInfo>(p => p.GetProjectItems() == project2Files && p.IsPhysicalProject == true);
InitializeWith(Proj(project1, projectInfo1), Proj(Mock.Of<IVsProject>(), projectInfo2));
projects.Remove(project1);
// Act.
AssertThat.Raises<ITestContainerDiscoverer>(discoverer, d => d.TestContainersUpdated += null,
() => solutionMonitor.Raise(sm => sm.ProjectChanged += null,
new ProjectChangedEventArgs(solution.Object, project1, ProjectChangeType.Unloaded)));
// Assert.
var container = Assert.Single(discoverer.TestContainers);
Assert.Equal(@"C:\test3.ps1", container.Source);
}
[Fact]
public void Test_File_Removed()
{
// Arrange.
var project = Mock.Of<IVsProject>();
var projectInfo = Mock.Of<IProjectInfo>(p =>
p.GetProjectItems() == new[] { @"C:\test1.ps1", @"C:\test2.ps1", @"C:\test3.ps1" } && p.IsPhysicalProject == true);
InitializeWith(Proj(project, projectInfo));
// Act.
AssertThat.Raises<ITestContainerDiscoverer>(discoverer, d => d.TestContainersUpdated += null,
() => projectMonitor.Raise(pm => pm.FileChanged += null,
new ProjectFileChangedEventArgs(project, @"C:\test2.ps1", FileChangeType.Removed)));
var containers = discoverer.TestContainers.OrderBy(t => t.Source).ToList();
// Assert.
Assert.Equal(2, containers.Count);
Assert.Equal(@"C:\test1.ps1", containers.First().Source);
Assert.Equal(@"C:\test3.ps1", containers.Last().Source);
}
[Fact]
public void Test_File_Added()
{
// Arrange.
var project = Mock.Of<IVsProject>();
var projectInfo = Mock.Of<IProjectInfo>(p =>
p.GetProjectItems() == new[] { @"C:\test1.ps1", @"C:\test2.ps1" } && p.IsPhysicalProject == true);
InitializeWith(Proj(project, projectInfo));
// Act.
AssertThat.Raises<ITestContainerDiscoverer>(discoverer, d => d.TestContainersUpdated += null,
() => projectMonitor.Raise(pm => pm.FileChanged += null,
new ProjectFileChangedEventArgs(project, @"C:\test3.ps1", FileChangeType.Added)));
var containers = discoverer.TestContainers.OrderBy(t => t.Source).ToList();
// Assert.
Assert.Equal(3, containers.Count);
Assert.Equal(@"C:\test1.ps1", containers[0].Source);
Assert.Equal(@"C:\test2.ps1", containers[1].Source);
Assert.Equal(@"C:\test3.ps1", containers[2].Source);
}
[Fact]
public void Test_File_Changed()
{
// Arrange.
var project = Mock.Of<IVsProject>();
var projectInfo = Mock.Of<IProjectInfo>(p =>
p.GetProjectItems() == new[] { @"C:\test1.ps1", @"C:\test2.ps1" } && p.IsPhysicalProject == true);
InitializeWith(Proj(project, projectInfo));
// Act.
AssertThat.Raises<ITestContainerDiscoverer>(discoverer, d => d.TestContainersUpdated += null,
() => fileWatcher.Raise(fw => fw.Changed += null,
new FileSystemEventArgs(WatcherChangeTypes.Changed, @"C:\", "test1.ps1")));
var containers = discoverer.TestContainers.OrderBy(t => t.Source).ToList();
// Assert.
Assert.Equal(2, containers.Count);
Assert.Equal(@"C:\test1.ps1", containers[0].Source);
Assert.Equal(@"C:\test2.ps1", containers[1].Source);
}
[Fact]
public void Test_File_Changed_When_File_Not_In_Solution()
{
// Arrange.
var project = Mock.Of<IVsProject>();
var projectInfo = Mock.Of<IProjectInfo>(p =>
p.GetProjectItems() == new[] { @"C:\test1.ps1", @"C:\test2.ps1" } && p.IsPhysicalProject == true);
InitializeWith(Proj(project, projectInfo));
// Act.
AssertThat.DoesNotRaise<ITestContainerDiscoverer>(discoverer, d => d.TestContainersUpdated += null,
() => fileWatcher.Raise(fw => fw.Changed += null,
new FileSystemEventArgs(WatcherChangeTypes.Changed, @"C:\", "test3.ps1")));
var containers = discoverer.TestContainers.OrderBy(t => t.Source).ToList();
// Assert.
Assert.Equal(2, containers.Count);
Assert.Equal(@"C:\test1.ps1", containers[0].Source);
Assert.Equal(@"C:\test2.ps1", containers[1].Source);
}
[Fact]
public void Test_FileSystemWatcher_Errors_Logged()
{
// Arrange.
var exception = new InvalidOperationException();
// Act.
fileWatcher.Raise(fsw => fsw.Error += null, new ErrorEventArgs(exception));
// Assert.
logger.Verify(l => l.Error(It.IsAny<string>(), It.IsAny<object[]>()), Times.Once());
}
[Fact]
public void Test_Dispose()
{
// Act.
discoverer.Dispose();
// Assert.
fileWatcher.VerifySet(fw => fw.EnableRaisingEvents = false);
fileWatcher.Verify(fw => fw.Dispose());
}
private void InitializeWith(params Tuple<IVsProject, IProjectInfo>[] initialProjects)
{
foreach (var initialProject in initialProjects)
projects[initialProject.Item1] = initialProject.Item2;
solutionMonitor.Raise(sm => sm.SolutionChanged += null,
new SolutionChangedEventArgs(solution.Object, SolutionChangeType.Loaded));
}
private static Tuple<IVsProject, IProjectInfo> Proj(IVsProject project, IProjectInfo info)
{
return Tuple.Create(project, info);
}
private static IVSTestContainer CreateContainer(ITestContainerDiscoverer discoverer, string source, IVsProject project)
{
return Mock.Of<IVSTestContainer>(c => c.Discoverer == discoverer && c.Source == source && c.Project == project);
}
public void Dispose()
{
VisualStudioHierarchyExtensions.SolutionInfoFactory = originalSolutionInfoFactory;
VisualStudioHierarchyExtensions.ProjectInfoFactory = originalProjectInfoFactory;
}
private readonly VSTestContainerDiscoverer discoverer;
private readonly Mock<IVsSolution> solution = new Mock<IVsSolution>();
private readonly ISolutionInfo solutionInfo;
private readonly IDictionary<IVsProject, IProjectInfo> projects = new Dictionary<IVsProject, IProjectInfo>();
private readonly Mock<IServiceProvider> serviceProvider = new Mock<IServiceProvider>();
private readonly Mock<ILogger> logger = new Mock<ILogger>();
private readonly Mock<ISolutionMonitor> solutionMonitor = new Mock<ISolutionMonitor>();
private readonly Mock<IProjectFileMonitor> projectMonitor = new Mock<IProjectFileMonitor>();
private readonly Mock<IFileSystemWatcher> fileWatcher = new Mock<IFileSystemWatcher>();
private readonly Func<IVsSolution, ISolutionInfo> originalSolutionInfoFactory;
private readonly Func<IVsProject, IProjectInfo> originalProjectInfoFactory;
}
}<file_sep>/PSycheTest.Runners.Framework/Results/FailedResult.cs
using System;
using System.Linq;
namespace PSycheTest.Runners.Framework.Results
{
/// <summary>
/// Represents the result of a test that failed.
/// </summary>
public class FailedResult : TestResult
{
/// <summary>
/// Initializes a new <see cref="FailedResult"/>.
/// </summary>
/// <param name="duration">The time it took a test to execute</param>
/// <param name="reason">The error that caused the failure</param>
public FailedResult(TimeSpan duration, ScriptError reason)
: base(duration, Enumerable.Empty<Uri>())
{
Reason = reason;
}
/// <see cref="TestResult.Status"/>
public override TestStatus Status
{
get { return TestStatus.Failed; }
}
/// <summary>
/// The error that caused the test failure.
/// </summary>
public ScriptError Reason { get; private set; }
}
}<file_sep>/PSycheTest.Runners.Framework/TestEndedEventArgs.cs
using System;
using PSycheTest.Runners.Framework.Results;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Contains diagnostic information about when a test has ended.
/// </summary>
public class TestEndedEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of <see cref="TestStartingEventArgs"/>.
/// </summary>
/// <param name="test">The test that has ended</param>
/// <param name="result">The result of the test</param>
public TestEndedEventArgs(ITestFunction test, TestResult result)
{
Test = test;
Result = result;
}
/// <summary>
/// The test that has ended.
/// </summary>
public ITestFunction Test { get; private set; }
/// <summary>
/// The result of the test.
/// </summary>
public TestResult Result { get; private set; }
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.Framework/Utilities/Text/StringExtensionsTests.cs
using System.Linq;
using PSycheTest.Runners.Framework.Utilities.Text;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.Framework.Utilities.Text
{
public class StringExtensionsTests
{
[Fact]
public void Test_Lines_With_Empty_String()
{
// Act.
var lines = "".Lines();
// Assert.
Assert.Empty(lines);
}
[Fact]
public void Test_Lines_With_One_Line()
{
// Act.
var lines = "Testing 1, 2, 3".Lines();
// Assert.
var line = Assert.Single(lines);
Assert.Equal("Testing 1, 2, 3", line);
}
[Fact]
public void Test_Lines_With_Multiple_Lines()
{
// Act.
var lines = @"Testing, 1, 2, 3
Hello, world
This is a test".Lines().ToList();
// Assert.
Assert.Equal(3, lines.Count);
Assert.Equal("Testing, 1, 2, 3", lines[0]);
Assert.Equal("Hello, world", lines[1]);
Assert.Equal("This is a test", lines[2]);
}
}
}<file_sep>/PSycheTest.Runners.Framework/ITestResultProvider.cs
using System.Collections.Generic;
using PSycheTest.Runners.Framework.Results;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Interface for an object that provides test results.
/// </summary>
public interface ITestResultProvider
{
/// <summary>
/// Gets any test results.
/// </summary>
IEnumerable<TestResult> Results { get; }
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.Framework/Results/PassedResultTests.cs
using System;
using PSycheTest.Runners.Framework.Results;
using PSycheTest.Runners.Framework.Utilities.Collections;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.Framework.Results
{
public class PassedResultTests
{
[Fact]
public void Test_PassedResult()
{
// Act.
var result = new PassedResult(
TimeSpan.FromMilliseconds(5), new Uri(@"C:\output.txt").ToEnumerable());
// Assert.
Assert.Equal(TimeSpan.FromMilliseconds(5), result.Duration);
Assert.Equal(TestStatus.Passed, result.Status);
var artifact = Assert.Single(result.Artifacts);
Assert.Equal(@"C:\output.txt", artifact.OriginalString);
}
}
}<file_sep>/PSycheTest/AssertNotContainsCmdlet.cs
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using PSycheTest.Exceptions;
namespace PSycheTest
{
/// <summary>
/// Cmdlet that verifies that a collection does not contain a given value.
/// </summary>
[Cmdlet(VerbsLifecycle.Assert, "NotContains")]
public class AssertNotContainsCmdlet : AssertionCmdletBase
{
/// <summary>
/// The value that should not be found.
/// </summary>
[Parameter(Mandatory = true, Position = 0)]
public object Unexpected { get; set; }
/// <summary>
/// The collection to check.
/// </summary>
[Parameter(Mandatory = true, Position = 1)]
[ValidateNotNull]
public IEnumerable<object> Collection { get; set; }
/// <see cref="AssertionCmdletBase.Assert"/>
protected override void Assert()
{
if (Collection.Contains(Unexpected))
throw new NotContainsException(Unexpected, Message ?? "Assert-NotContains Failure");
}
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.VisualStudio/Core/TestMapperTests.cs
using System;
using System.Management.Automation.Language;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Moq;
using PSycheTest;
using PSycheTest.Runners.Framework;
using PSycheTest.Runners.Framework.Results;
using PSycheTest.Runners.Framework.Utilities.Collections;
using PSycheTest.Runners.VisualStudio;
using PSycheTest.Runners.VisualStudio.Core;
using Xunit;
using Xunit.Extensions;
namespace Tests.Unit.PSycheTest.Runners.VisualStudio.Core
{
public class TestMapperTests
{
[Fact]
public void Test_Map_TestFunction()
{
// Arrange.
var extent = Mock.Of<IScriptExtent>(e =>
e.File == @"C:\TestScript.ps1" &&
e.StartLineNumber == 12 &&
e.StartColumnNumber == 20);
var testFunction = new TestFunction(SyntaxTree.OfFunctionNamed("Test-Function",
attribute: SyntaxTree.OfAttribute<TestAttribute>(), extent: extent));
// Act.
var testCase = mapper.Map(testFunction);
// Assert.
Assert.Equal("Test-Function", testCase.DisplayName);
Assert.Equal(@"C:\TestScript.ps1:Test-Function", testCase.FullyQualifiedName);
Assert.Equal(@"C:\TestScript.ps1", testCase.Source);
Assert.Equal(@"C:\TestScript.ps1", testCase.CodeFilePath);
Assert.Equal(12, testCase.LineNumber);
Assert.Equal(VSTestExecutor.ExecutorUri, testCase.ExecutorUri);
}
[Theory]
[InlineData(TestOutcome.None, TestStatus.NotExecuted)]
[InlineData(TestOutcome.Passed, TestStatus.Passed)]
[InlineData(TestOutcome.Failed, TestStatus.Failed)]
[InlineData(TestOutcome.Skipped, TestStatus.Skipped)]
public void Test_Map_TestStatus(TestOutcome expected, TestStatus status)
{
// Act.
var actual = mapper.Map(status);
// Assert.
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Map_PassedResult()
{
// Arrange.
var testCase = new TestCase("This.Is.A.Test", new Uri("executor://The.Executor"), @"C:\TestScript.ps1");
var result = new PassedResult(TimeSpan.FromSeconds(2), new Uri(@"C:\artifact.txt").ToEnumerable());
// Act.
var mappedResult = mapper.Map(testCase, result);
// Assert.
Assert.Equal(TestOutcome.Passed, mappedResult.Outcome);
Assert.Equal(TimeSpan.FromSeconds(2), mappedResult.Duration);
Assert.Equal(testCase, mappedResult.TestCase);
Assert.Null(mappedResult.ErrorStackTrace);
Assert.Null(mappedResult.ErrorMessage);
var attachmentSet = Assert.Single(mappedResult.Attachments);
var attachment = Assert.Single(attachmentSet.Attachments);
Assert.Equal(@"C:\artifact.txt", attachment.Uri.OriginalString);
}
[Fact]
public void Test_Map_FailedResult()
{
// Arrange.
var testCase = new TestCase("This.Is.A.Test", new Uri("executor://The.Executor"), @"C:\TestScript.ps1");
var exception = Record.Exception(() => { throw new InvalidOperationException("Error!"); }); // Populate the stack trace.
var result = new FailedResult(TimeSpan.FromSeconds(3), new ExceptionScriptError(exception));
// Act.
var mappedResult = mapper.Map(testCase, result);
// Assert.
Assert.Equal(TestOutcome.Failed, mappedResult.Outcome);
Assert.Equal(TimeSpan.FromSeconds(3), mappedResult.Duration);
Assert.Equal(testCase, mappedResult.TestCase);
Assert.Equal(exception.StackTrace, mappedResult.ErrorStackTrace);
Assert.Equal(exception.Message, mappedResult.ErrorMessage);
}
[Fact]
public void Test_Map_SkippedResult()
{
// Arrange.
var testCase = new TestCase("This.Is.A.Test", new Uri("executor://The.Executor"), @"C:\TestScript.ps1");
var result = new SkippedResult("Because!");
// Act.
var mappedResult = mapper.Map(testCase, result);
// Assert.
Assert.Equal(TestOutcome.Skipped, mappedResult.Outcome);
Assert.Equal(TimeSpan.Zero, mappedResult.Duration);
Assert.Equal(testCase, mappedResult.TestCase);
Assert.Null(mappedResult.ErrorStackTrace);
Assert.Null(mappedResult.ErrorMessage);
}
private readonly TestMapper mapper = new TestMapper();
}
}<file_sep>/PSycheTest.Runners.Framework/ITestFunction.cs
using PSycheTest.Runners.Framework.Results;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Represents information about a test function.
/// </summary>
public interface ITestFunction : ITestResultProvider
{
/// <summary>
/// A test's full, unique name.
/// </summary>
string UniqueName { get; }
/// <summary>
/// A test's display name.
/// </summary>
string DisplayName { get; }
/// <summary>
/// A test function's programmatic name. This may or may not be the same as <see cref="UniqueName"/>.
/// </summary>
string FunctionName { get; }
/// <summary>
/// An optional test title.
/// </summary>
string CustomTitle { get; }
/// <summary>
/// Whether a test should be skipped.
/// </summary>
bool ShouldSkip { get; }
/// <summary>
/// If <see cref="ShouldSkip"/> is true, this should be the reason
/// for skipping a test.
/// </summary>
string SkipReason { get; }
/// <summary>
/// Contains information about where a test came from.
/// </summary>
TestSourceInfo Source { get; }
/// <summary>
/// Adds a test result to a test.
/// </summary>
/// <param name="result">The result to add</param>
void AddResult(TestResult result);
}
}<file_sep>/Tests.Integration/PSycheTest/AssertNotEqualCmdletTests.cs
using System.Management.Automation;
using PSycheTest;
using PSycheTest.Exceptions;
using Xunit;
namespace Tests.Integration.PSycheTest
{
public class AssertNotEqualCmdletTests : CmdletTestBase<AssertNotEqualCmdlet>
{
[Fact]
public void Test_Assert_Failure()
{
// Arrange.
AddCmdlet();
AddParameter(p => p.First, "test");
AddParameter(p => p.Second, "test");
// Act/Assert.
var exception = Assert.Throws<CmdletInvocationException>(() =>
Current.Shell.Invoke());
Assert.NotNull(exception.InnerException);
Assert.IsType<AssertionException>(exception.InnerException);
}
[Fact]
public void Test_Assert_Success()
{
// Arrange.
AddCmdlet();
AddParameter(p => p.First, 13);
AddParameter(p => p.Second, 12);
// Act/Assert.
Assert.DoesNotThrow(() => Current.Shell.Invoke());
}
}
}<file_sep>/PSycheTest/AssertNotEqualCmdlet.cs
using System.Management.Automation;
using PSycheTest.Exceptions;
namespace PSycheTest
{
/// <summary>
/// Cmdlet that verifies that an expected value matches an actual value.
/// </summary>
[Cmdlet(VerbsLifecycle.Assert, "NotEqual")]
public class AssertNotEqualCmdlet : AssertionCmdletBase
{
/// <summary>
/// The first value.
/// </summary>
[Parameter(Mandatory = true, Position = 0)]
public object First { get; set; }
/// <summary>
/// The second value.
/// </summary>
[Parameter(Mandatory = true, Position = 1)]
public object Second { get; set; }
/// <see cref="AssertionCmdletBase.Assert"/>
protected override void Assert()
{
if (Equals(First, Second))
throw new AssertionException(Message ?? "Assert-NotEqual Failure");
}
}
}<file_sep>/Tests.Integration/PSycheTest/AssertTrueCmdletTests.cs
using System.Management.Automation;
using PSycheTest;
using PSycheTest.Exceptions;
using Xunit;
namespace Tests.Integration.PSycheTest
{
public class AssertTrueCmdletTests : CmdletTestBase<AssertTrueCmdlet>
{
[Fact]
public void Test_Assert_Failure()
{
// Arrange.
AddCmdlet();
AddParameter(p => p.Condition, false);
// Act/Assert.
var exception = Assert.Throws<CmdletInvocationException>(() =>
Current.Shell.Invoke());
Assert.NotNull(exception.InnerException);
var assertException = Assert.IsType<ExpectedActualException>(exception.InnerException);
Assert.Equal(true, assertException.Expected);
Assert.Equal(false, assertException.Actual);
}
[Fact]
public void Test_Assert_Success()
{
// Arrange.
AddCmdlet();
AddParameter(p => p.Condition, true);
// Act/Assert.
Assert.DoesNotThrow(() => Current.Shell.Invoke());
}
}
}<file_sep>/PSycheTest.Runners.VisualStudio/IPSycheTestSettingsService.cs
using PSycheTest.Runners.VisualStudio.Core;
namespace PSycheTest.Runners.VisualStudio
{
/// <summary>
/// Provides access to PSycheTest settings.
/// </summary>
public interface IPSycheTestSettingsService
{
/// <summary>
/// The provided settings.
/// </summary>
IPSycheTestRunSettings Settings { get; }
}
}<file_sep>/PSycheTest.AutomationProvider/AutomatedPSycheTest.cs
using System;
using PSycheTest.Runners.Framework;
using TestCaseAutomator.AutomationProviders.Interfaces;
namespace PSycheTest.AutomationProvider
{
/// <summary>
/// Represents an automated test from PSycheTest.
/// </summary>
public class AutomatedPSycheTest : ITestAutomation
{
/// <summary>
/// Initializes a new <see cref="AutomatedPSycheTest"/>.
/// </summary>
/// <param name="script">The test script containing a test</param>
/// <param name="test">The test function</param>
public AutomatedPSycheTest(ITestScript script, ITestFunction test)
{
Name = String.Format("{0}:{1}", script.Source.Name, test.DisplayName);
TestType = "Integration Test";
Storage = script.Source.Name;
Identifier = _identifierFactory.CreateIdentifier(Name);
}
/// <see cref="ITestAutomation.Identifier"/>
public Guid Identifier { get; private set; }
/// <see cref="ITestAutomation.Name"/>
public string Name { get; private set; }
/// <see cref="ITestAutomation.TestType"/>
public string TestType { get; private set; }
/// <see cref="ITestAutomation.Storage"/>
public string Storage { get; private set; }
private static readonly ITestIdentifierFactory _identifierFactory = new HashedIdentifierFactory();
}
}<file_sep>/PSycheTest.Runners.Framework/Extensions/CmdletExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Reflection;
namespace PSycheTest.Runners.Framework.Extensions
{
/// <summary>
/// Class that helps build collections of cmdlets.
/// </summary>
public static class CmdletExtensions
{
/// <summary>
/// Retrieves a collection of cmdlets defined in an assembly.
/// </summary>
/// <param name="assembly">An assembly containing the cmdlet classes</param>
/// <returns>A new list of cmdlet definitions</returns>
public static IEnumerable<SessionStateCmdletEntry> GetCmdlets(this Assembly assembly)
{
var cmdlets = from type in assembly.GetTypes()
where type.IsClass
from cmdletAttribute in type.GetCustomAttributes<CmdletAttribute>()
select CreateCmdletConfig(type);
return cmdlets.ToList();
}
/// <summary>
/// Creates a <see cref="CmdletConfigurationEntry"/> from a <see cref="PSCmdlet"/>.
/// </summary>
/// <param name="cmdletType">The type of cmdlet to use</param>
/// <returns>A new <see cref="CmdletConfigurationEntry"/> for the given cmdlet</returns>
public static SessionStateCmdletEntry FromCmdletType(this Type cmdletType)
{
return CreateCmdletConfig(cmdletType);
}
/// <summary>
/// Gets the name of a cmdlet from its implementing type.
/// </summary>
/// <param name="cmdletType">The type of cmdlet</param>
/// <returns>The name of the cmdlet</returns>
public static string CmdletName(this Type cmdletType)
{
var cmdletAttribute = cmdletType.GetCustomAttribute<CmdletAttribute>();
if (cmdletAttribute == null)
throw new ArgumentException(cmdletType.Name + " does not have a " + typeof(CmdletAttribute).Name, "cmdletType");
return cmdletAttribute.VerbName + "-" + cmdletAttribute.NounName;
}
private static SessionStateCmdletEntry CreateCmdletConfig(Type cmdletType)
{
return new SessionStateCmdletEntry(cmdletType.CmdletName(), cmdletType, null);
}
}
}<file_sep>/PSycheTest/Exceptions/ContainsException.cs
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace PSycheTest.Exceptions
{
/// <summary>
/// Assertion exception for when a certain value was expected to be in a collection
/// and was not found.
/// </summary>
[Serializable]
public class ContainsException : AssertionException
{
/// <summary>
/// The expected value.
/// </summary>
public object Expected { get; private set; }
/// <see cref="Exception.Message"/>
public override string Message
{
get
{
return String.Format("{0}{2}Not found: {1}",
base.Message,
Expected ?? "(null)",
Environment.NewLine);
}
}
/// <summary>
/// Initializes a new <see cref="ContainsException"/>.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="userMessage">A user provided message</param>
public ContainsException(object expected, string userMessage)
{
Expected = expected;
UserMessage = userMessage;
}
/// <see cref="Exception(SerializationInfo,StreamingContext)"/>
protected ContainsException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
Expected = info.GetValue("Expected", typeof(object));
}
/// <see cref="Exception.GetObjectData"/>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
info.AddValue("Expected", Expected);
base.GetObjectData(info, context);
}
}
}<file_sep>/PSycheTest.Runners.Framework/Results/ExceptionScriptError.cs
using System;
namespace PSycheTest.Runners.Framework.Results
{
/// <summary>
/// Contains information about an exception-based script error.
/// </summary>
public class ExceptionScriptError : ScriptError
{
/// <summary>
/// Initializes a new <see cref="ExceptionScriptError"/>.
/// </summary>
/// <param name="exception">The exception that caused the error</param>
public ExceptionScriptError(Exception exception)
{
_exception = exception;
}
/// <see cref="ScriptError.StackTrace"/>
public override string Message
{
get { return _exception.Message; }
}
/// <see cref="ScriptError.Exception"/>
public override Exception Exception
{
get { return _exception; }
}
private readonly Exception _exception;
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.Framework/Utilities/InputOutput/TemporaryDirectoryTests.cs
using System;
using System.IO;
using PSycheTest.Runners.Framework.Utilities.InputOutput;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.Framework.Utilities.InputOutput
{
public class TemporaryDirectoryTests
{
[Fact]
public void Test_Directory()
{
// Arrange.
using (var temp = new TemporaryDirectory())
{
// Act.
var directory = temp.Directory;
// Assert.
Assert.NotNull(directory);
Assert.True(directory.Exists);
Assert.Equal(Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar), directory.Parent.FullName.TrimEnd(Path.DirectorySeparatorChar));
}
}
[Fact]
public void Test_Directory_With_Name()
{
// Arrange.
using (var temp = new TemporaryDirectory(name: "testDir"))
{
// Act.
var directory = temp.Directory;
// Assert.
Assert.NotNull(directory);
Assert.True(directory.Exists);
Assert.Equal(Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar), directory.Parent.FullName.TrimEnd(Path.DirectorySeparatorChar));
Assert.Equal("testDir", directory.Name);
}
}
[Fact]
public void Test_Directory_In_Parent()
{
// Arrange.
var parent = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
using (var temp = new TemporaryDirectory(new DirectoryInfo(parent)))
{
// Act.
var directory = temp.Directory;
// Assert.
Assert.NotNull(directory);
Assert.True(directory.Exists);
Assert.Equal(parent.TrimEnd(Path.DirectorySeparatorChar), directory.Parent.FullName.TrimEnd(Path.DirectorySeparatorChar));
}
}
[Fact]
public void Test_Dispose()
{
// Arrange.
var temp = new TemporaryDirectory();
// Act.
temp.Dispose();
temp.Directory.Refresh();
// Assert.
Assert.False(temp.Directory.Exists);
}
[Fact]
public void Test_Destructor()
{
// Act.
var directory = GetTempDir();
GC.Collect();
GC.WaitForPendingFinalizers();
directory.Refresh();
// Assert.
Assert.False(directory.Exists);
}
private DirectoryInfo GetTempDir()
{
var temp = new TemporaryDirectory();
return temp.Directory;
}
}
}<file_sep>/PSycheTest.Runners.VisualStudio/Core/Monitoring/ISolutionMonitor.cs
using System;
namespace PSycheTest.Runners.VisualStudio.Core.Monitoring
{
/// <summary>
/// Interface for an object that monitors a Visual Studio solution for changes.
/// </summary>
public interface ISolutionMonitor
{
/// <summary>
/// Event raised when a solution is changed.
/// </summary>
event EventHandler<SolutionChangedEventArgs> SolutionChanged;
/// <summary>
/// Event raised when a project is changed.
/// </summary>
event EventHandler<ProjectChangedEventArgs> ProjectChanged;
/// <summary>
/// Begins monitoring a solution for changes.
/// </summary>
void StartMonitoring();
/// <summary>
/// Stops monitoring a solution for changes.
/// </summary>
void StopMonitoring();
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.Framework/Results/ExceptionScriptErrorTests.cs
using System;
using PSycheTest.Runners.Framework.Results;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.Framework.Results
{
public class ExceptionScriptErrorTests
{
[Fact]
public void Test_StackTrace_When_Exception_Has_Null_StackTrace()
{
// Arrange.
var error = new ExceptionScriptError(new Exception());
// Act.
var stackTrace = error.StackTrace;
// Assert.
Assert.Equal(string.Empty, stackTrace);
}
[Fact]
public void Test_Message()
{
// Arrange.
var error = new ExceptionScriptError(new Exception("Oops!"));
// Act.
var message = error.Message;
// Assert.
Assert.Equal("Oops!", message);
}
}
}<file_sep>/PSycheTest.Runners.VisualStudio/PSycheTestSettingsService.cs
using System.ComponentModel.Composition;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestWindow.Extensibility;
using PSycheTest.Runners.VisualStudio.Core;
namespace PSycheTest.Runners.VisualStudio
{
/// <summary>
/// Provides serialization and deserialization of PSycheTest Visual Studio settings.
/// </summary>
[Export(typeof(ISettingsProvider))]
[Export(typeof(IRunSettingsService))]
[Export(typeof(IPSycheTestSettingsService))]
[SettingsName(PSycheTestRunSettings.SettingsProviderName)]
public class PSycheTestSettingsService : IRunSettingsService, ISettingsProvider, IPSycheTestSettingsService
{
/// <summary>
/// Initializes a new <see cref="PSycheTestSettingsService"/>.
/// </summary>
public PSycheTestSettingsService()
{
Name = PSycheTestRunSettings.SettingsProviderName;
Settings = new PSycheTestRunSettings();
_serializer = new XmlSerializer(typeof(PSycheTestRunSettings));
}
/// <see cref="IPSycheTestSettingsService.Settings"/>
public IPSycheTestRunSettings Settings { get; private set; }
/// <see cref="IRunSettingsService.AddRunSettings"/>
public IXPathNavigable AddRunSettings(IXPathNavigable inputRunSettingDocument, IRunSettingsConfigurationInfo configurationInfo, ILogger log)
{
ValidateArg.NotNull(inputRunSettingDocument, "inputRunSettingDocument");
ValidateArg.NotNull(configurationInfo, "configurationInfo");
var navigator = inputRunSettingDocument.CreateNavigator();
navigator.MoveToRoot();
return navigator;
}
/// <see cref="IRunSettingsService.Name"/>
public string Name { get; private set; }
/// <see cref="ISettingsProvider.Load"/>
public void Load(XmlReader reader)
{
ValidateArg.NotNull(reader, "reader");
if (reader.Read() && reader.Name.Equals(PSycheTestRunSettings.SettingsProviderName))
Settings = _serializer.Deserialize(reader) as PSycheTestRunSettings;
}
private readonly XmlSerializer _serializer;
}
}<file_sep>/Tests.Integration/PSycheTest.Runners.Framework/PowerShellTestExecutorTests.cs
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Moq;
using PSycheTest.Exceptions;
using PSycheTest.Runners.Framework;
using PSycheTest.Runners.Framework.Results;
using PSycheTest.Runners.Framework.Timers;
using PSycheTest.Runners.Framework.Utilities.Collections;
using Tests.Integration.TestScripts;
using Tests.Support;
using Xunit;
namespace Tests.Integration.PSycheTest.Runners.Framework
{
public class PowerShellTestExecutorTests
{
public PowerShellTestExecutorTests()
{
discoverer = new PowerShellTestDiscoverer(logger.Object);
executor = new PowerShellTestExecutor(logger.Object, () => new StopwatchTimer(), new SynchronousTaskScheduler())
{
OutputDirectory = new DirectoryInfo(Directory.GetCurrentDirectory())
};
}
[Fact]
public async Task Test_ExecuteAsync_Single_File_Single_Test()
{
// Arrange.
var testScript = discoverer.Discover(ScriptFiles.HasOneTest);
// Act.
await executor.ExecuteAsync(testScript.Value.ToEnumerable());
var results = testScript.Value.Results.ToList();
// Assert.
Assert.NotEmpty(results);
Assert.Single(results);
var result = Assert.IsType<FailedResult>(results.Single());
Assert.Equal(TestStatus.Failed, result.Status);
Assert.NotNull(result.Duration);
Assert.True(result.Duration > TimeSpan.Zero);
var reason = Assert.IsType<ExpectedActualException>(result.Reason.Exception);
Assert.Equal(true, reason.Expected);
Assert.Equal(false, reason.Actual);
}
[Fact]
public async Task Test_ExecuteAsync_Single_File_Multiple_Tests()
{
// Arrange.
var testScript = discoverer.Discover(ScriptFiles.HasMultipleTests);
// Act.
await executor.ExecuteAsync(testScript.Value.ToEnumerable());
var results = testScript.Value.Results.ToList();
// Assert.
Assert.Equal(4, results.Count);
var firstResult = Assert.IsType<FailedResult>(results[0]);
Assert.Equal(TestStatus.Failed, firstResult.Status);
Assert.NotNull(firstResult.Duration);
Assert.True(firstResult.Duration > TimeSpan.Zero);
Assert.IsType<ExpectedActualException>(firstResult.Reason.Exception);
var secondResult = Assert.IsType<FailedResult>(results[1]);
Assert.Equal(TestStatus.Failed, secondResult.Status);
Assert.NotNull(secondResult.Duration);
Assert.True(secondResult.Duration > TimeSpan.Zero);
Assert.IsType<ExpectedActualException>(secondResult.Reason.Exception);
var thirdResult = Assert.IsType<PassedResult>(results[2]);
Assert.Equal(TestStatus.Passed, thirdResult.Status);
Assert.NotNull(thirdResult.Duration);
Assert.True(thirdResult.Duration > TimeSpan.Zero);
var fourthResult = Assert.IsType<PassedResult>(results[3]);
Assert.Equal(TestStatus.Passed, fourthResult.Status);
Assert.NotNull(fourthResult.Duration);
Assert.True(fourthResult.Duration > TimeSpan.Zero);
}
[Fact]
public async Task Test_ExecuteAsync_Single_File_Skipped_Test()
{
// Arrange.
var testScript = discoverer.Discover(ScriptFiles.HasSkippedTest);
// Act.
await executor.ExecuteAsync(testScript.Value.ToEnumerable());
var results = testScript.Value.Results.ToList();
// Assert.
Assert.NotEmpty(results);
Assert.Equal(2, results.Count);
var skippedResult = Assert.IsType<SkippedResult>(results.First());
Assert.Equal(TestStatus.Skipped, skippedResult.Status);
Assert.Null(skippedResult.Duration);
var passedResult = Assert.IsType<PassedResult>(results.Last());
Assert.Equal(TestStatus.Passed, passedResult.Status);
Assert.NotNull(passedResult.Duration);
Assert.True(passedResult.Duration > TimeSpan.Zero);
}
[Fact]
public async Task Test_ExecuteAsync_Single_File_Setup_And_Cleanup()
{
// Arrange.
var testScript = discoverer.Discover(ScriptFiles.HasSetupAndCleanup);
// Act.
await executor.ExecuteAsync(testScript.Value.ToEnumerable());
var results = testScript.Value.Results.ToList();
// Assert.
Assert.NotEmpty(results);
Assert.Equal(2, results.Count);
foreach (var result in results)
{
Assert.IsType<PassedResult>(result);
Assert.Equal(TestStatus.Passed, result.Status);
Assert.NotNull(result.Duration);
Assert.True(result.Duration > TimeSpan.Zero);
}
}
[Fact]
public async Task Test_ExecuteAsync_Multiple_Files()
{
// Arrange.
var scripts = discoverer.Discover(new[]
{
ScriptFiles.HasSetupAndCleanup, ScriptFiles.HasMultipleTests
}).ToList();
// Act.
await executor.ExecuteAsync(scripts);
var results = scripts.SelectMany(s => s.Results).ToList();
// Assert.
Assert.Equal(6, results.Count);
Assert.Equal(new[] { TestStatus.Passed, TestStatus.Passed, TestStatus.Failed, TestStatus.Failed, TestStatus.Passed, TestStatus.Passed },
results.Select(r => r.Status));
}
[Fact]
public async Task Test_ExecuteAsync_Tests_Failed_By_NonFunction_Error()
{
// Arrange.
var testScript = discoverer.Discover(ScriptFiles.HasNonFunctionErrors);
// Act.
await executor.ExecuteAsync(testScript.Value.ToEnumerable());
var results = testScript.Value.Results.ToList();
// Assert.
Assert.Equal(2, results.Count);
var firstResult = Assert.IsType<FailedResult>(results[0]);
Assert.Equal(TestStatus.Failed, firstResult.Status);
Assert.NotNull(firstResult.Duration);
Assert.True(firstResult.Duration > TimeSpan.Zero);
Assert.IsType<ExpectedActualException>(firstResult.Reason.Exception);
var secondResult = Assert.IsType<FailedResult>(results[1]);
Assert.Equal(TestStatus.Failed, secondResult.Status);
Assert.NotNull(secondResult.Duration);
Assert.True(secondResult.Duration > TimeSpan.Zero);
Assert.IsType<ExpectedActualException>(secondResult.Reason.Exception);
}
[Fact]
public async Task Test_ExecuteAsync_With_Filter()
{
// Arrange.
var testScript = discoverer.Discover(ScriptFiles.HasMultipleTests).Value;
// Act.
await executor.ExecuteAsync(testScript.ToEnumerable(), tf => !tf.FunctionName.EndsWith("Failure"));
var results = testScript.Results.ToList();
// Assert.
Assert.Equal(2, results.Count);
foreach (var result in results)
{
var passed = Assert.IsType<PassedResult>(result);
Assert.Equal(TestStatus.Passed, passed.Status);
}
}
[Fact]
public async Task Test_ExecuteAsync_With_External_Script_Reference()
{
// Arrange.
var testScript = discoverer.Discover(ScriptFiles.HasScriptReferences);
// Act.
await executor.ExecuteAsync(testScript.Value.ToEnumerable());
var results = testScript.Value.Results.ToList();
// Assert.
Assert.NotEmpty(results);
Assert.Single(results);
var result = Assert.IsType<PassedResult>(results.Single());
Assert.Equal(TestStatus.Passed, result.Status);
Assert.NotNull(result.Duration);
Assert.True(result.Duration > TimeSpan.Zero);
}
private readonly PowerShellTestExecutor executor;
private readonly PowerShellTestDiscoverer discoverer;
private readonly Mock<ILogger> logger = new Mock<ILogger>();
}
}<file_sep>/PSycheTest.Runners.Framework/Utilities/Collections/ReverseComparer.cs
using System;
using System.Collections.Generic;
namespace PSycheTest.Runners.Framework.Utilities.Collections
{
/// <summary>
/// A wrapper around a comparer that reverses the comparison results.
/// </summary>
public class ReverseComparer<T> : IComparer<T>
{
private readonly IComparer<T> baseComparer;
/// <summary>
/// Creates a new ReverseComparer for the given IComparer.
/// </summary>
/// <param name="baseComparer">The original comparer</param>
public ReverseComparer(IComparer<T> baseComparer)
{
if (baseComparer == null)
throw new ArgumentNullException("baseComparer");
this.baseComparer = baseComparer;
}
/// <see cref="IComparer{T}.Compare" />
public int Compare(T x, T y)
{
return baseComparer.Compare(y, x);
}
}
}<file_sep>/Tests.Integration/TestScripts/ScriptFiles.cs
using System.IO;
namespace Tests.Integration.TestScripts
{
/// <summary>
/// Contains references to test script files.
/// </summary>
public static class ScriptFiles
{
public static readonly FileInfo HasMultipleTests =
new FileInfo(@".\TestScripts\HasMultipleTests.ps1");
public static readonly FileInfo HasNonFunctionErrors =
new FileInfo(@".\TestScripts\HasNonFunctionErrors.ps1");
public static readonly FileInfo HasOneTest =
new FileInfo(@".\TestScripts\HasOneTest.ps1");
public static readonly FileInfo HasScriptReferences =
new FileInfo(@".\TestScripts\HasScriptReferences.ps1");
public static readonly FileInfo HasSetupAndCleanup =
new FileInfo(@".\TestScripts\HasSetupAndCleanup.ps1");
public static readonly FileInfo HasSkippedTest =
new FileInfo(@".\TestScripts\HasSkippedTest.ps1");
public static readonly FileInfo Helpers =
new FileInfo(@".\TestScripts\Helpers.ps1");
}
}<file_sep>/PSycheTest.Runners.Framework/Utilities/Option.cs
using System;
namespace PSycheTest.Runners.Framework.Utilities
{
/// <summary>
/// Provides a safe method for handling objects where it is expected that a value may not exist.
/// This is similar to a Nullable type, but it is also usable with reference types using the
/// Option/Maybe monad pattern. It is intended to serve the same function that F#'s Options module
/// does, but implemented in C#.
/// </summary>
public abstract class Option<T>
{
/// <summary>
/// This constructor is internal to disallow further subclassing.
/// </summary>
internal Option() { }
/// <summary>
/// Returns a None Option of a given type.
/// </summary>
public static Option<T> None()
{
return none;
}
private static readonly Option<T> none = new None<T>(); // this can be a singleton for each type because None has no variable properties
/// <summary>
/// Creates a Some Option with the given value.
/// </summary>
public static Option<T> Some(T value)
{
return new Some<T>(value);
}
/// <summary>
/// Creates an Option from a value that may be null.
/// None will be returned if the value is null, otherwise
/// Some.
/// </summary>
public static Option<T> From(T value)
{
return value == null ? None() : Some(value);
}
/// <summary>
/// Converts a value to an Option type.
/// </summary>
public static implicit operator Option<T>(T value)
{
return From(value);
}
/// <summary>
/// True if a value exists.
/// </summary>
public abstract bool HasValue { get; }
/// <summary>
/// The value if it exists.
/// </summary>
public abstract T Value { get; }
/// <summary>
/// Applies a mapping function to an Option. If the Option is a Some,
/// its value is mapped. If the Option is a None, a None of the
/// destination type is returned.
/// </summary>
/// <typeparam name="TResult">The type to map to</typeparam>
/// <param name="selector">The mapping function</param>
/// <returns>A Some with the mapped value or a None</returns>
public abstract Option<TResult> Select<TResult>(Func<T, TResult> selector);
/// <summary>
/// Applies a mapping function to an Option.
/// </summary>
/// <typeparam name="TResult">The type of Option to map to</typeparam>
/// <param name="optionSelector">The mapping function</param>
/// <remarks>This method corresponds to the monad pattern's Bind.</remarks>
public abstract Option<TResult> SelectMany<TResult>(Func<T, Option<TResult>> optionSelector);
/// <summary>
/// Applies a mapping function to an Option.
/// </summary>
public abstract Option<TResult> SelectMany<TIntermediate, TResult>(Func<T, Option<TIntermediate>> optionSelector, Func<T, TIntermediate, TResult> resultSelector);
/// <summary>
/// Returns this Option if it is Some and its value matches the given predicate.
/// Otherwise, None is returned.
/// </summary>
/// <param name="predicate">The condition to be met</param>
public abstract Option<T> Where(Func<T, bool> predicate);
/// <summary>
/// Performs an action on an Option's value if it is Some,
/// otherwise no action is performed.
/// </summary>
/// <param name="action">The action to perform</param>
public abstract void Apply(Action<T> action);
/// <summary>
/// Returns Option.Some if an Option is Some, otherwise if None,
/// the given function is executed to return an alternative.
/// </summary>
/// <param name="fallbackAction">The alternative function</param>
public abstract Option<T> OrElse(Func<Option<T>> fallbackAction);
/// <summary>
/// Retrieves an Option's value if it is Some. Otherwise if None, the given function
/// is executed to return an alternative value.
/// </summary>
/// <param name="fallbackAction">The alternative function</param>
public abstract T GetOrElse(Func<T> fallbackAction);
}
/// <summary>
/// Represents an Option with no value.
/// </summary>
internal class None<T> : Option<T>
{
/// <summary>
/// Always returns false.
/// </summary>
public override bool HasValue
{
get { return false; }
}
/// <summary>
/// Throws an exception because no value exists.
/// </summary>
public override T Value
{
get { throw new InvalidOperationException(); }
}
/// <summary>
/// Returns None of the result type.
/// </summary>
public override Option<TResult> Select<TResult>(Func<T, TResult> selector)
{
return Option<TResult>.None();
}
/// <summary>
/// Returns None of the result type.
/// </summary>
public override Option<TResult> SelectMany<TResult>(Func<T, Option<TResult>> optionSelector)
{
return Option<TResult>.None();
}
/// <summary>
/// Returns None of the result type.
/// </summary>
public override Option<TResult> SelectMany<TIntermediate, TResult>(Func<T, Option<TIntermediate>> optionSelector, Func<T, TIntermediate, TResult> resultSelector)
{
return Option<TResult>.None();
}
/// <summary>
/// Returns None.
/// </summary>
public override Option<T> Where(Func<T, bool> predicate)
{
return None();
}
/// <summary>
/// Does nothing.
/// </summary>
public override void Apply(Action<T> action)
{
// Do nothing.
}
/// <summary>
/// Executes an alternative function.
/// </summary>
public override Option<T> OrElse(Func<Option<T>> fallbackAction)
{
return fallbackAction();
}
/// <summary>
/// Executes an alternative function.
/// </summary>
public override T GetOrElse(Func<T> fallbackAction)
{
return fallbackAction();
}
}
/// <summary>
/// Represents an Option that has a value.
/// </summary>
internal class Some<T> : Option<T>
{
/// <summary>
/// Creates a new Some Option with the given value.
/// </summary>
/// <param name="value">The value of the Option</param>
public Some(T value)
{
if (value == null)
throw new ArgumentNullException("value");
_value = value;
}
/// <summary>
/// Always returns true.
/// </summary>
public override bool HasValue
{
get { return true; }
}
/// <summary>
/// The value of the Option.
/// </summary>
public override T Value
{
get { return _value; }
}
/// <summary>
/// Applies a mapping function to a Some's value.
/// </summary>
public override Option<TResult> Select<TResult>(Func<T, TResult> selector)
{
return Option<TResult>.From(selector(Value));
}
/// <summary>
/// Applies a mapping function to a Some's value.
/// </summary>
public override Option<TResult> SelectMany<TResult>(Func<T, Option<TResult>> optionSelector)
{
return optionSelector(Value);
}
/// <summary>
/// Applies a mapping function to a Some's value.
/// </summary>
public override Option<TResult> SelectMany<TIntermediate, TResult>(Func<T, Option<TIntermediate>> optionSelector, Func<T, TIntermediate, TResult> resultSelector)
{
var intermediate = optionSelector(Value);
if (intermediate.HasValue)
return Option<TResult>.From(resultSelector(Value, intermediate.Value));
return Option<TResult>.None();
}
/// <summary>
/// Returns this Option if its value meets the given condition.
/// </summary>
public override Option<T> Where(Func<T, bool> predicate)
{
return predicate(Value) ? this : None();
}
/// <summary>
/// Performs an action on the Option's value.
/// </summary>
public override void Apply(Action<T> action)
{
action(Value);
}
/// <summary>
/// Returns this.
/// </summary>
public override Option<T> OrElse(Func<Option<T>> fallbackAction)
{
return this;
}
/// <summary>
/// Returns this Option's value.
/// </summary>
public override T GetOrElse(Func<T> fallbackAction)
{
return Value;
}
/// <summary>
/// Whether a Some Option is equal to another.
/// </summary>
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (ReferenceEquals(this, obj))
return true;
Some<T> other = obj as Some<T>;
if (other == null)
return false;
return Value.Equals(other.Value);
}
/// <summary>
/// Gets the hash code for a Some Option.
/// </summary>
public override int GetHashCode()
{
return Value.GetHashCode();
}
private readonly T _value;
}
}<file_sep>/PSycheTest.Runners.Framework/Results/ErrorRecordWrapper.cs
using System;
using System.Management.Automation;
namespace PSycheTest.Runners.Framework.Results
{
/// <summary>
/// A wrapper around an <see cref="ErrorRecord"/>.
/// </summary>
public class ErrorRecordWrapper : IErrorRecord
{
/// <summary>
/// Initializes a new <see cref="ErrorRecordWrapper"/>.
/// </summary>
/// <param name="innerError">The wrapped error</param>
public ErrorRecordWrapper(ErrorRecord innerError)
{
_innerError = innerError;
}
/// <see cref="IErrorRecord.ScriptStackTrace"/>
public string ScriptStackTrace { get { return _innerError.ScriptStackTrace; } }
/// <see cref="IErrorRecord.Exception"/>
public Exception Exception { get { return _innerError.Exception; } }
private readonly ErrorRecord _innerError;
}
}<file_sep>/PSycheTest/TestSetupAttribute.cs
using System;
namespace PSycheTest
{
/// <summary>
/// Indicates that a function should be run before each test in a script.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class TestSetupAttribute : Attribute { }
}<file_sep>/Tests.Unit/PSycheTest.Runners.Framework/Results/PSScriptErrorTests.cs
using System;
using System.IO;
using System.Runtime.CompilerServices;
using Moq;
using PSycheTest.Runners.Framework.Results;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.Framework.Results
{
public class PSScriptErrorTests
{
[Fact]
public void Test_StackTrace()
{
// Arrange.
var exception = Throw();
var errorRecord = Mock.Of<IErrorRecord>(er =>
er.Exception == exception &&
er.ScriptStackTrace ==
@"at <ScriptBlock>, C:\Tests\Helpers.ps1: line 34
at Test-Things, <No file>: line 116".Trim());
var thisFilePath = GetThisFile();
var error = new PSScriptError(errorRecord, new FileInfo(@"C:\Tests\Test-Stuff.ps1"));
// Act.
var stackTrace = error.StackTrace;
// Assert.
Assert.Equal(String.Format(
@"at {0}.{1}() in {2}:line 60
at Helpers.ps1 in C:\Tests\Helpers.ps1:line 34
at Test-Stuff.ps1:Test-Things() in C:\Tests\Test-Stuff.ps1:line 116", GetType().FullName, "Throw", thisFilePath),
stackTrace);
}
[Fact]
public void Test_Message()
{
// Arrange.
var exception = Throw();
var errorRecord = Mock.Of<IErrorRecord>(er =>
er.Exception == exception &&
er.ScriptStackTrace == string.Empty);
var error = new PSScriptError(errorRecord, new FileInfo(@"C:\Tests\Test-Stuff.ps1"));
// Act.
var message = error.Message;
// Assert.
Assert.Equal("Error!", message);
}
private Exception Throw()
{
try
{
throw new InvalidOperationException("Error!");
}
catch (Exception e)
{
return e;
}
}
private string GetThisFile([CallerFilePath] string thisFile = null)
{
return thisFile;
}
}
}<file_sep>/PSycheTest.Runners.Framework/IPowerShellTestExecutor.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Interface for an object that executes PowerShell tests.
/// </summary>
public interface IPowerShellTestExecutor
{
/// <summary>
/// A collection of module names that will be added to a test run's initial session state
/// and which will persist across test executions.
/// </summary>
ICollection<string> InitialModules { get; }
/// <summary>
/// The directory where test results and artifacts should be placed.
/// </summary>
DirectoryInfo OutputDirectory { get; set; }
/// <summary>
/// Event raised when a test script is about to start.
/// </summary>
event EventHandler<TestScriptStartingEventArgs> TestScriptStarting;
/// <summary>
/// Event raised when a test is about to start.
/// </summary>
event EventHandler<TestStartingEventArgs> TestStarting;
/// <summary>
/// Event raised when a test has ended.
/// </summary>
event EventHandler<TestEndedEventArgs> TestEnded;
/// <summary>
/// Event raised when a test script has ended.
/// </summary>
event EventHandler<TestScriptEndedEventArgs> TestScriptEnded;
/// <summary>
/// Executes a collection of tests.
/// </summary>
/// <param name="testScripts">The test scripts to execute</param>
/// <param name="filter">An optional predicate that determines whether a test should be run</param>
/// <param name="cancellationToken">An optional cancellation token</param>
Task ExecuteAsync(IEnumerable<ITestScript> testScripts, Predicate<ITestFunction> filter = null, CancellationToken cancellationToken = default(CancellationToken));
}
}<file_sep>/Tests.Unit/PSycheTest.Runners.Framework/TestFunctionTests.cs
using System.IO;
using System.Management.Automation.Language;
using PSycheTest;
using PSycheTest.Runners.Framework;
using Xunit;
namespace Tests.Unit.PSycheTest.Runners.Framework
{
public class TestFunctionTests
{
public TestFunctionTests()
{
function = SyntaxTree.OfFunctionNamed("Test-Function", fromFile: @".\Script.ps1", attribute: SyntaxTree.OfAttribute<TestAttribute>());
}
[Fact]
public void Test_Properties()
{
// Act.
var test = new TestFunction(function);
// Assert.
Assert.Equal(@".\Script.ps1:Test-Function", test.UniqueName);
Assert.Equal("Test-Function", test.DisplayName);
Assert.Equal(Path.GetFullPath(@".\Script.ps1"), test.Source.File.FullName);
Assert.False(test.ShouldSkip);
Assert.Equal(string.Empty, test.SkipReason);
}
private readonly FunctionDefinitionAst function;
}
}<file_sep>/PSycheTest.Runners.Framework/PowerShellTestExecutor.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using PSycheTest.Core;
using PSycheTest.Runners.Framework.Extensions;
using PSycheTest.Runners.Framework.Results;
using PSycheTest.Runners.Framework.Timers;
using PSycheTest.Runners.Framework.Utilities.Collections;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Executes PowerShell tests.
/// </summary>
public class PowerShellTestExecutor : IPowerShellTestExecutor
{
/// <summary>
/// Initializes a new <see cref="PowerShellTestExecutor"/>.
/// </summary>
/// <param name="logger">A message logger</param>
public PowerShellTestExecutor(ILogger logger)
: this(logger, () => new StopwatchTimer(), TaskScheduler.Default)
{
}
/// <summary>
/// Initializes a new <see cref="PowerShellTestExecutor"/>.
/// </summary>
/// <param name="logger">A message logger</param>
/// <param name="timerFactory">Creates new <see cref="ITestTimer"/>s</param>
/// <param name="taskScheduler">The scheduler to use for tasks</param>
public PowerShellTestExecutor(ILogger logger, Func<ITestTimer> timerFactory, TaskScheduler taskScheduler)
{
_logger = logger;
_timerFactory = timerFactory;
_taskScheduler = taskScheduler;
_testTransactionFactory = (p, ts, tf, d) => new TestExecutionTransaction(p, new TestLocationManager(d, ts, tf));
InitialModules = new List<string>
{
Assembly.GetAssembly(typeof(AssertionCmdletBase)).Location
};
_initialSessionState = new Lazy<InitialSessionState>(() =>
{
var initialState = InitialSessionState.CreateDefault();
initialState.ThrowOnRunspaceOpenError = true;
foreach (var moduleName in InitialModules)
initialState.ImportPSModule(new[] { moduleName });
return initialState;
});
}
/// <summary>
/// A collection of modules that will be added to a test run's initial session state
/// and which will persist across test executions.
/// </summary>
public ICollection<string> InitialModules { get; private set; }
/// <summary>
/// The root directory where test results and artifacts should be placed.
/// </summary>
public DirectoryInfo OutputDirectory { get; set; }
#region Events
/// <summary>
/// Event raised when a test script is about to start.
/// </summary>
public event EventHandler<TestScriptStartingEventArgs> TestScriptStarting;
private void OnTestScriptStarting(ITestScript script)
{
var localEvent = TestScriptStarting;
if (localEvent != null)
localEvent(this, new TestScriptStartingEventArgs(script));
}
/// <summary>
/// Event raised when a test is about to start.
/// </summary>
public event EventHandler<TestStartingEventArgs> TestStarting;
private void OnTestStarting(ITestFunction test)
{
var localEvent = TestStarting;
if (localEvent != null)
localEvent(this, new TestStartingEventArgs(test));
}
/// <summary>
/// Event raised when a test has ended.
/// </summary>
public event EventHandler<TestEndedEventArgs> TestEnded;
private void OnTestEnded(ITestFunction test, TestResult result)
{
var localEvent = TestEnded;
if (localEvent != null)
localEvent(this, new TestEndedEventArgs(test, result));
}
/// <summary>
/// Event raised when a test script has ended.
/// </summary>
public event EventHandler<TestScriptEndedEventArgs> TestScriptEnded;
private void OnTestScriptEnded(ITestScript script)
{
var localEvent = TestScriptEnded;
if (localEvent != null)
localEvent(this, new TestScriptEndedEventArgs(script));
}
#endregion Events
/// <summary>
/// Executes a collection of tests.
/// </summary>
/// <param name="testScripts">The test scripts to execute</param>
/// <param name="filter">An optional predicate that determines whether a test should be run</param>
/// <param name="cancellationToken">An optional cancellation token</param>
public async Task ExecuteAsync(IEnumerable<ITestScript> testScripts, Predicate<ITestFunction> filter = null, CancellationToken cancellationToken = default(CancellationToken))
{
filter = filter ?? (_ => true);
using (var runspace = RunspaceFactory.CreateRunspace(_initialSessionState.Value))
{
runspace.Open();
foreach (var testScript in testScripts)
{
_logger.Info("Executing test script: '{0}':", testScript.Source.FullName);
OnTestScriptStarting(testScript);
using (var powershell = PowerShell.Create(RunspaceMode.NewRunspace))
using (var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
linkedTokenSource.Token.Register(() =>
{
_logger.Info("Cancelling test execution...");
powershell.Stop();
});
powershell.Runspace = runspace;
foreach (var test in testScript.Tests.Where(test => filter(test)))
{
_logger.Info("Executing test '{0}'", test.DisplayName);
cancellationToken.ThrowIfCancellationRequested();
using (var transaction = _testTransactionFactory(powershell, testScript, test, OutputDirectory))
{
OnTestStarting(test);
var results = await ExecuteAsync(transaction, powershell, test, testScript).ConfigureAwait(false);
foreach (var result in results)
{
_logger.Info("Test '{0}': {1}", test.DisplayName, result.Status);
test.AddResult(result);
OnTestEnded(test, result);
}
}
}
}
OnTestScriptEnded(testScript);
}
}
}
/// <summary>
/// Executes a test function.
/// </summary>
/// <param name="transaction">The current test transaction</param>
/// <param name="powershell">The PowerShell instance to us</param>
/// <param name="test">The test to run</param>
/// <param name="script">The parent script</param>
private async Task<IEnumerable<TestResult>> ExecuteAsync(ITestExecutionTransaction transaction, PowerShell powershell, ITestFunction test, ITestScript script)
{
var timer = _timerFactory();
try
{
if (test.ShouldSkip)
return new SkippedResult(test.SkipReason).ToEnumerable();
var testContext = InitializeTestContext(powershell, transaction.OutputDirectory);
IReadOnlyCollection<ErrorRecord> errors;
using (timer.Start())
{
errors = await ExecuteCoreAsync(powershell, test, script).ConfigureAwait(false);
}
if (errors.Any())
return new FailedResult(timer.Elapsed, new PSScriptError(new ErrorRecordWrapper(errors.First()), test.Source.File)).ToEnumerable();
return new PassedResult(timer.Elapsed, testContext.Artifacts).ToEnumerable();
}
catch (CmdletInvocationException cmdletException)
{
return CreateFailed(timer.Elapsed, cmdletException.InnerException ?? cmdletException).ToEnumerable();
}
catch (Exception exception)
{
_logger.Error("Exception occurred during test '{0}': {1}{2}{3}", test.UniqueName, exception.Message, Environment.NewLine, exception.StackTrace);
return CreateFailed(timer.Elapsed, exception).ToEnumerable();
}
}
private async Task<IReadOnlyCollection<ErrorRecord>> ExecuteCoreAsync(PowerShell powershell, ITestFunction test, ITestScript script)
{
// Add the script's functions/variables to the pipeline.
powershell.AddScript(script.Text);
var scriptErrors = await powershell.InvokeAsync(_taskScheduler).ConfigureAwait(false);
powershell.Commands.Clear(); // Clear the pipeline.
if (scriptErrors.Any())
return scriptErrors;
// Now execute the test function plus setup/teardown.
script.TestSetup.Apply(s => powershell.AddCommand(s.Name));
powershell.AddCommand(test.FunctionName);
script.TestCleanup.Apply(s => powershell.AddCommand(s.Name));
var testErrors = await powershell.InvokeAsync(_taskScheduler).ConfigureAwait(false);
if (testErrors.Any())
return testErrors;
return new ErrorRecord[0];
}
private static TestExecutionContext InitializeTestContext(PowerShell powershell, DirectoryInfo outputDirectory)
{
var testContext = new TestExecutionContext
{
OutputDirectory = outputDirectory
};
powershell.Runspace.SessionStateProxy.Variables().__testContext__ = testContext;
return testContext;
}
private static TestResult CreateFailed(TimeSpan elapsed, Exception exception)
{
return new FailedResult(elapsed, new ExceptionScriptError(exception));
}
private readonly Lazy<InitialSessionState> _initialSessionState;
private readonly ILogger _logger;
private readonly Func<ITestTimer> _timerFactory;
private readonly Func<PowerShell, ITestScript, ITestFunction, DirectoryInfo, ITestExecutionTransaction> _testTransactionFactory;
private readonly TaskScheduler _taskScheduler;
}
}
|
821768a0e07e7f5f5fd819b1e970a2920753317a
|
[
"Markdown",
"C#"
] | 137
|
C#
|
mthamil/PSycheTest
|
cb2f1f510f1e72f28d3263abd70018cd1421c435
|
a6892703b8cdee300a1e155e08bd44f304af746f
|
refs/heads/master
|
<file_sep><?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>
<h1>Upload Image</h1>
<?= view_cell('\App\Controllers\Admin\Menu::option') ?>
<form action="<?= base_url('/admin/menu/insert') ?>" method="post" enctype="multipart/form-data">
Gambar: <input type="file" name="gambar" required>
<br>
<button type="submit" class="btn btn-primary">Tambah Data</button>
</form>
<?= $this->endSection(); ?><file_sep><!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="<?= base_url('bootstrap-4.4.1-dist/css/bootstrap.min.css') ?> ">
<title>Aplikasi | Login</title>
<style>
.form-signin {
width: 100%;
max-width: 330px;
padding: 15px;
margin: auto;
}
.alert {
width: 100%;
max-width: 330px;
padding: 15px;
margin: auto;
}
.form-signin .email {
margin-bottom: -1px;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
.form-signin .pass {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
</style>
</head>
<body class="text-center mt-5">
<img src="<?= base_url('upload/logo.jpg') ?>" alt="Logo" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal">Login Admin</h1>
<?php if (!empty($info)) : ?>
<div class="alert alert-danger" role="alert">
<?= $info ?>
</div>
<?php endif; ?>
<form action="<?= base_url('/admin/login') ?>" method="post" class="form-signin">
<label for="email" class="sr-only">email:</label>
<input type="email" id="email" name="email" class="form-control email" placeholder="email" required autofocus>
<label for="password" class="sr-only">Password</label>
<input type="<PASSWORD>" id="password" name="password" class="form-control mb-3 pass" placeholder="<PASSWORD>" required>
<button class="btn btn-lg btn-primary btn-block" name="tombol" type="submit">Login</button>
</form>
<script src=<?= base_url("bootstrap-4.4.1-dist/js/bootstrap.bundle.min.js") ?>></script>
<script src=<?= base_url("bootstrap-4.4.1-dist/jqpop/jquery-3.5.1.slim.min.js") ?>></script>
<script src=<?= base_url("bootstrap-4.4.1-dist/jqpop/popper.min.js") ?>></script>
<script src=<?= base_url("bootstrap-4.4.1-dist/js/bootstrap.min.js") ?>></script>
</body>
</html><file_sep><?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>
<div class="row">
<div class="col">
<h1><?= $judul ?></h1>
</div>
</div>
<div class="row">
<div class="col">
<p>Pembeli: <?= $orders[0]['pelanggan'] ?></p>
</div>
<div class="col">
<p>Tanggal: <?= date("d-m-y", strtotime($orders[0]['tglorder'])) ?></p>
</div>
<div class="col">
<p>Total: <b> <?= number_format($orders[0]['total']) ?></b></p>
</div>
</div>
<div class="row">
<div class="col">
<?php if (session()->getFlashdata('pesan')) : ?>
<div class="alert alert-danger" role="alert">
<?= session()->getFlashdata('pesan') ?>
</div>
<?php endif; ?>
</div>
</div>
<div class="row">
<div class="col-6">
<form action="<?= base_url('/admin/order/update') ?>" method="post">
<div class="form-group">
<label for="bayar">Bayar:</label>
<input type="number" name="bayar" autocomplete="off" autofocus required class="form-control" id="bayar">
</div>
<div>
<input type="hidden" name="total" value="<?= $orders[0]['total'] ?>" autocomplete="off" required class="form-control">
<input type="hidden" name="idorder" value="<?= $orders[0]['idorder'] ?>" autocomplete="off" required class="form-control">
</div>
<button type="submit" href="awddw" class="btn btn-primary">Bayar</button>
</form>
</div>
</div>
<div class="row mt-4">
<div class="col">
<h2>Rincian Order</h2>
</div>
</div>
<div class="row">
<div class="col">
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Menu</th>
<th>Harga</th>
<th>Jumlah</th>
<th>Total</th>
</tr>
<?php $no = 1 ?>
<?php foreach ($details as $detail => $value) : ?>
<tr>
<td><?= $no++ ?></td>
<td><?= $value['menu'] ?></td>
<td><?= $value['harga'] ?></td>
<td><?= $value['jumlah'] ?></td>
<td><?= $value['jumlah'] * $value['hargajual'] ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?php
namespace App\Controllers\Admin;
use App\Controllers\BaseController;
use App\Models\Kategori_M;
class Kategori extends BaseController
{
public function index()
{
echo "<h2> ini controller (adminKategori) method index</h2>";
}
public function read()
{
$pager = \Config\Services::pager();
$model = new Kategori_M();
$data = [
'title' => 'Aplikasi|Select',
'judul' => 'Daftar Kategori',
'kategori' => $model->paginate(3, 'group1'),
'pager' => $model->pager
];
return view('kategori/select', $data);
}
public function create()
{
$data = [
'title' => 'Aplikasi|forminsert',
'judul' => "INSERT"
];
return view('kategori/insert', $data);
}
public function insert()
{
$model = new Kategori_M();
if ($model->insert($_POST) === false) {
$error = $model->errors();
session()->setFlashdata('pesan', $error['kategori']);
return redirect()->to(base_url("/admin/kategori/create"));
} else {
session()->setFlashdata('berhasil', 'data berhasil di tambahkan');
return redirect()->to(base_url("/admin/kategori"));
}
}
public function find($id = null)
{
$model = new Kategori_M();
$kategori = $model->find($id);
$data = [
'title' => 'Aplikasi | find',
'judul' => 'UPDATE',
'kategori' => $kategori
];
return view('kategori/update', $data);
}
public function update()
{
$model = new Kategori_M();
$id = $_POST['idkategori'];
if ($model->save($_POST) === false) {
$error = $model->errors();
session()->setFlashdata('pesan', $error['kategori']);
return redirect()->to(base_url("/admin/kategori/find/$id"));
} else {
session()->setFlashdata('berhasil', 'data berhasil di tambahkan');
return redirect()->to(base_url("/admin/kategori"));
}
return redirect()->to(base_url("/admin/kategori"));
}
public function delete($id = null)
{
$model = new Kategori_M();
$model->delete($id);
return redirect()->to(base_url("/admin/kategori"));
}
}
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
<!-- Bootstrap css -->
<link rel="stylesheet" href="<?= base_url('bootstrap-4.4.1-dist/css/bootstrap.min.css') ?> ">
<!-- My CSS -->
<link rel="stylesheet" href="<?= base_url('css/style.css') ?>">
<link rel="stylesheet" href="<?= base_url('css/fixed.css') ?>" />
<link rel="stylesheet" href="<?= base_url('css/login.css') ?>">
<!-- My Icon -->
<link rel="icon" href="../upload/logo.jpg">
</head>
<body>
<?php
if (session()->getFlashdata('pesan')) {
echo "<script>alert('Selamat Anda Register Silahkan Login');</script>";
}
?>
<!-- Navbar -->
<nav class=" navbar navbar-expand-lg navbar-light">
<div class="container">
<a class="navbar-brand mb-0 h-1" href="<?= base_url('homepage') ?>"><img width="60" height="60" class="d-inline-block align-top" alt="" loading="lazy" src="<?= base_url('upload/logo.jpg') ?>" alt=""></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav ml-auto">
<a class="nav-link" href="<?= base_url('front/daftar') ?>">Daftar</a>
<a class="nav-item nav-link active" href="<?= base_url('login') ?>">Login <span class="sr-only">(current)</span></a>
</div>
</div>
</div>
</nav>
<!-- End Navbar -->
<div class="jumbotron forlogin jumbotron-fluid">
<div class="container">
<h1 class="display-4"><span>Login Page</span></h1>
</div>
</div>
<section class="loginarea section_gap">
<div class="container">
<div class="row">
<div class="col-lg-6">
<div class="login-img">
<img class="img-fluid" src="<?= base_url('upload/login.jpg') ?>" alt="">
<div class="hover">
<h4>New to our website?</h4>
<a class="btn btn-primary" href="<?= base_url('front/daftar') ?>">Create an Account</a>
</div>
</div>
</div>
<div class="col-lg-6 ">
<div class="login-form-in">
<?php if (!empty($info)) : ?>
<div class="alert alert-danger" role="alert">
<?= $info ?>
</div>
<?php endif; ?>
<h3>Log in to enter</h3>
<form class="login-form" action="<?= base_url('/front/loginp') ?>" method="post">
<div class="col-md-12 form-group">
<input type="email" class="form-control" name="email" placeholder="Email" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Email'">
</div>
<div class="col-md-12 form-group">
<input type="<PASSWORD>" class="form-control" name="password" placeholder="<PASSWORD>" onfocus="this.placeholder = ''" onblur="this.placeholder = '<PASSWORD>'">
</div>
<!-- <div class="col-md-12 form-group">
<div class="creat_account">
<input type="checkbox" id="f-option2" name="selector">
<label for="f-option2">Keep me logged in</label>
</div>
</div> -->
<div class="col-md-12 form-group">
<button type="submit" value="submit" class="btn btn-primary">Log In</button>
<!-- <a href="#">Forgot Password?</a> -->
</div>
</form>
</div>
</div>
</div>
</div>
</section>
<!-- footer area -->
<footer class="page-footer bg-dark">
<div class="bg-primary">
<div class="container">
<div class="row py-4 d-flex align-items-center">
<div class="col-md-12 text-center">
<a href="#"><i class="fab fa-facebook-square text-white mr-4"></i></a>
<a href="#"><i class="fab fa-twitter text-white mr-4"></i></a>
<a href="#"><i class="fab fa-google-play text-white"></i></a>
</div>
</div>
</div>
</div>
<div class="container text-white text-center text-md-left mt-5">
<div class="row">
<div class="col-md-3 mx-auto mb-4">
<h6 class="text-uppercase font-weight-bold">About us</h6>
<hr class="bg-primary mb-4 mt-0 d-inline-block mx-auto" style="width: 80px; height: 2px;">
<div>
<img mt width="60" height="60" class="d-inline-block mx-auto" alt="" loading="lazy" src="<?= base_url('upload/logo.jpg') ?>" alt="">
<p class="mt-2">Lorem ipsum dolor sit amet consectetur adipisicing elit. Vitae aspernatur libero explicabo veniam pariatur adipisci nemo a labore error, ducimus fugit ipsum obcaecati nam. Rem!</p>
</div>
</div>
<div class="col-md-2 mx-auto mb-4">
<h6 class="text-uppercase font-weight-bold">Products</h6>
<hr class="bg-primary mb-4 mt-0 d-inline-block mx-auto" style="width: 85px; height: 2px;">
<ul class="list-unstyled">
<li class="my-2"><a class="text-white" href="#">Our apps</a></li>
</ul>
</div>
<div class="col-md-2 mx-auto mb-4">
<h6 class="text-uppercase font-weight-bold">Usefull Links</h6>
<hr class="bg-primary mb-4 mt-0 d-inline-block mx-auto" style="width: 115px; height: 2px;">
<ul class="list-unstyled">
<li class="my-2"><a class="text-white" href="#">About Us</a></li>
<li class="my-2"><a class="text-white" href="#">Terms & Conditions</a></li>
<li class="my-2"><a class="text-white" href="#">Contact Us</a></li>
</ul>
</div>
<div class="col-md-3 mx-auto mb-4">
<h6 class="text-uppercase font-weight-bold">Contacts</h6>
<hr class="bg-primary mb-4 mt-0 d-inline-block mx-auto" style="width: 115px; height: 2px;">
<ul class="list-unstyled">
<li class="my-2"><i class="fas fa-home mr-3"></i> <NAME></li>
<li class="my-2"><i class="fas fa-envelope mr-3"></i><EMAIL></li>
<li class="my-2"><i class="fas fa-phone mr-3"></i> 0009919297421496</li>
</ul>
</div>
</div>
</footer>
<div class="footer-copyright text-center py-3">
<p>© Copyright
<a href="">FoodsApp</a></p>
<p>Desigend By Rsiyun</p>
</div>
<!-- End Footer area -->
<!-- My javascript -->
<script src="<?= base_url() ?>/bootstrap-4.4.1-dist/jqpop/jquery-3.5.1.slim.min.js"></script>
<script src="<?= base_url() ?>/bootstrap-4.4.1-dist/js/bootstrap.bundle.min.js"></script>
<script src="<?= base_url() ?>/bootstrap-4.4.1-dist/js/fontawesome.js"></script>
</body>
</html><file_sep><?php
namespace App\Controllers\Admin;
use App\Controllers\BaseController;
use App\Models\User_M;
class User extends BaseController
{
protected $userModel, $pager;
public function __construct()
{
$this->userModel = new User_M();
$this->pager = \Config\Services::pager();
}
public function index()
{
$data = [
'title' => 'Aplikasi|User',
'judul' => 'Data User',
'users' => $this->userModel->paginate(3, 'group1'),
'pager' => $this->userModel->pager,
];
return view('user/select', $data);
}
public function find($id = null)
{
$user = $this->userModel->find($id);
$data = [
'title' => 'Aplikasi | Update',
'judul' => 'UPDATE',
'user' => $user,
'level' => ['Admin', 'Koki', 'Kasir', 'Gudang']
];
return view('user/update', $data);
}
public function ubah()
{
$id = $_POST['iduser'];
$data = [
'email' => $this->request->getPost('email'),
'level' => $this->request->getPost('level'),
];
$this->userModel->update($id, $data);
return redirect()->to(base_url("/admin/user"));
}
public function create()
{
$data = [
'title' => 'Aplikasi|User',
'judul' => 'Tambah data User',
'level' => ['Admin', 'Koki', 'Kasir', 'Gudang']
];
return view('user/insert', $data);
}
public function insert()
{
if (isset($_POST['password'])) {
$password = $this->request->getPost('password');
$data = [
'user' => $this->request->getPost('user'),
'email' => $this->request->getPost('email'),
'password' => password_hash($password, PASSWORD_DEFAULT),
'level' => $this->request->getPost('level'),
'aktif' => 1
];
if ($this->userModel->insert($data) === false) {
$error = $this->userModel->errors();
session()->setFlashdata('pesan', $error);
return redirect()->to(base_url("/admin/user/create"));
} else {
session()->setFlashdata('berhasil', 'data berhasil di tambahkan');
return redirect()->to(base_url("/admin/user"));
}
}
}
public function delete($id = null)
{
$this->userModel->delete($id);
return redirect()->to(base_url("/admin/user"));
}
public function update($id = null, $isi = 1)
{
if ($isi == 1) {
$isi = 0;
} else {
$isi = 1;
}
$data = [
'aktif' => $isi
];
$this->userModel->update($id, $data);
return redirect()->to(base_url("/admin/user"));
}
}
<file_sep><?php
namespace App\Models;
use CodeIgniter\Model;
class OrderDetail_M extends Model
{
protected $table = 'vorderdetail';
protected $primaryKey = 'idorderdetail';
}
<file_sep><?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>
<div class="col">
<h1><?= $judul ?></h1>
<?php if (session()->getFlashdata('pesan')) : ?>
<div class="alert alert-danger" role="alert">
<?php
$errors = session()->getFlashdata('pesan'); ?>
<?php foreach ($errors as $error) : ?>
<?= $error ?>
<br>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<div class="col-6">
<form action="<?= base_url() ?>/admin/user/ubah" method="post">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" name="email" value="<?= $user['email'] ?>" autocomplete="off" required class="form-control" id="email">
</div>
<!-- <div class="form-group">
<label for="confirm">Konfirmasi Password:</label>
<input type="password" name="confirm" autocomplete="off" required class="form-control" id="confirm">
</div> -->
</div>
<div class="col-3">
<div class="form-group">
<label for="opsi">Level:</label>
<select id="opsi" class="custom-select" name="level" id="level" autofocus>
<?php foreach ($level as $kategori => $value) : ?>
<option <?= ($user['level'] == $value) ? "selected" : "" ?> value="<?= $value ?>"><?= $value ?></option>
<?php endforeach; ?>
</select>
</div>
<input type="hidden" name="iduser" value="<?= $user['iduser']; ?>" id="menu">
<button type="submit" class="btn btn-primary">Ubah Data</button>
</form>
</div>
<?= $this->endSection(); ?><file_sep><?= $this->extend('frontend/layout/template'); ?>
<?= $this->section('content2'); ?>
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-4"><span><?= $judul ?></span></h1>
<h3 class="text-white ">Temukan Semua makanan disini</h3>
<form class="form-control-sm mt-3" action="<?= base_url('homepage/read') ?>" method="get">
<?= view_cell('\App\Controllers\homepage::option') ?>
</form>
</div>
</div>
<div class="container d-flex justify-content-center flex-wrap mb-5">
<?php foreach ($menus as $menu) : ?>
<div class="card " style="width: 15rem; margin:10px">
<img style="height:220px; " src="<?= base_url() ?>/upload/<?= $menu['gambar'] ?>" class="card-img-top">
<div class="card-body">
<h5 class="card-title"><?= $menu['menu'] ?></h5>
<p class="card-text">Rp.<?= $menu['harga'] ?></p>
<a class="btn btn-primary" href="<?= base_url('cart/keranjang/' . $menu["idmenu"]) ?>" role="button">Add to cart</a>
</div>
</div>
<?php endforeach; ?>
</div>
<div class="container mr-5 mb-4">
<?= $pager->makeLinks(1, $tampil, $total, 'bootstrap') ?>
</div>
<?= $this->endSection(); ?><file_sep><?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>
<div class="col">
<h1><?= $judul ?></h1>
<?php if (session()->getFlashdata('pesan')) : ?>
<div class="alert alert-danger" role="alert">
<?php
$error = session()->getFlashdata('pesan');
foreach ($error as $key) {
echo $key;
echo "</br>";
}
?>
</div>
<?php endif; ?>
</div>
<div class="col-6">
<form action="<?= base_url() ?>/admin/menu/update" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="opsi">Kategori:</label>
<select id="opsi" class="custom-select" name="idkategori" id="idkategori" autofocus>
<?php foreach ($kategoris as $kategori => $value) : ?>
<option value="<?= $value['idkategori'] ?>"><?= $value['kategori'] ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="menu">Menu:</label>
<input type="text" name="menu" value="<?= $menu['menu']; ?>" autocomplete="off" required class="form-control" id="menu">
</div>
<div class="form-group">
<label for="harga">Harga:</label>
<input type="text" min="500" value="<?= $menu['harga']; ?>" name="harga" autocomplete="off" required class="form-control" id="harga">
</div>
<div class="form-group">
<div class="custom-file">
<input name="gambar" type="file" class="custom-file-input" id="gambar">
<label class="custom-file-label" for="gambar">Pilih Gambar Menu</label>
</div>
</div>
<input type="hidden" name="gambar" required class="form-control" value="<?= $menu['gambar']; ?>">
<input type="hidden" name="idmenu" required class="form-control" value="<?= $menu['idmenu']; ?>">
<button type="submit" class="btn btn-primary">Ubah Data</button>
</form>
</div>
<?= $this->endSection(); ?><file_sep><?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>
<?php
if (isset($_GET['page_group1'])) {
$jumlah = 3;
$page = $_GET['page_group1'];
$no = ($page * $jumlah) - $jumlah + 1;
} else {
$no = 1;
}
?>
<div class="row">
<div class="col">
<h3><?= $judul ?></h3>
</div>
</div>
<div class="row">
<div class="col">
<?php if (session()->getFlashdata('berhasil')) : ?>
<div class="alert alert-success" role="alert">
<?= session()->getFlashdata('berhasil') ?>
</div>
<?php endif; ?>
<div class="row">
<div class="col-12">
<form action="<?= base_url('/admin/orderdetail/cari') ?>" method="post">
<div class="form-group col-6 float-left">
<label for="awal">Awal:</label>
<input type="date" name="awal" id="awal" required class="form-control">
</div>
<div class="form-group col-6 float-left">
<label for="akhir">Akhir:</label>
<input type="date" name="akhir" id="akhir" required class="form-control">
</div>
<div class="form-group ml-3">
<button class="btn btn-primary" name="cari" type="Submit">Cari</button>
</div>
</form>
</div>
</div>
<table class="table table-bordered">
<tr>
<th class="text-center">No</th>
<th class="text-center">Tanggal Order</th>
<th class="text-center">Menu</th>
<th class="text-center">Harga</th>
<th class="text-center">Jumlah</th>
<th class="text-center">Total</th>
</tr>
<?php $no; ?>
<?php foreach ($orderdetail as $cat => $value) : ?>
<td><?= $no++; ?></td>
<td><?= $value['tglorder'] ?></td>
<td><?= $value['menu']; ?></td>
<td><?= $value['harga']; ?></td>
<td><?= $value['jumlah']; ?></td>
<td><?= $value['jumlah'] * $value['harga']; ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?php
namespace App\Models;
use CodeIgniter\Model;
class User_M extends Model
{
protected $table = 'tbluser';
protected $allowedFields = ['user', 'email', 'password', 'level', 'aktif'];
protected $primaryKey = 'iduser';
protected $validationRules = [
'user' => 'min_length[3]|is_unique[tbluser.user]',
'email' => 'valid_email|is_unique[tbluser.user]'
];
protected $validationMessages = [
'user' => [
'min_length' => '-sorry minimum user 3 letter numbers',
'is_unique' => '-sorry user has been taken please choose another'
],
'email' => [
'valid_email' => '-Sorry email should be alphabet and number',
'is_unique' => '-sorry email has been taken please choose another'
],
];
}
<file_sep><?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>
<?php
if (isset($_GET['page_group1'])) {
$jumlah = 3;
$page = $_GET['page_group1'];
$no = ($page * $jumlah) - $jumlah + 1;
} else {
$no = 1;
}
?>
<div class="row">
<div class="col-4">
<a class="btn btn-primary" href="<?= base_url('/admin/menu/create') ?>">Tambah Data</a>
</div>
<div class="col">
<h3><?= $judul ?></h3>
</div>
</div>
<div class="row mt-2">
<div class="col-6">
<form action="<?= base_url('/admin/menu/read') ?>" method="get">
<?= view_cell('\App\Controllers\Admin\Menu::option') ?>
</form>
</div>
</div>
<div class="row">
<div class="col mt-2">
<?php if (session()->getFlashdata('berhasil')) : ?>
<div class="alert alert-success" role="alert">
<?= session()->getFlashdata('berhasil') ?>
</div>
<?php endif; ?>
<table class="table table-bordered">
<tr>
<th class="text-center">No</th>
<th class="text-center">Menu</th>
<th class="text-center">Harga</th>
<th class="text-center">Gambar</th>
<th colspan="2" class="text-center">Aksi</th>
</tr>
<?php $no; ?>
<?php foreach ($menu as $cat => $value) : ?>
<td><?= $no++; ?></td>
<td><?= $value['menu']; ?></td>
<td><?= $value['harga']; ?></td>
<td><img style="width: 100px;" src="<?= base_url() ?>/upload/<?= $value['gambar'] ?>" alt="gambar"></td>
<td>
<form class="text-center" action="menu/<?= $value['idmenu'] ?>" method="post">
<?= csrf_field() ?>
<input type="hidden" name="_method" value="DELETE">
<button onclick="return confirm('apakah anda yakin ?');" type="submit" class="btn btn-danger"><img src="<?= base_url('/icon/trash.svg') ?>" alt="sampah"></button>
<!-- <td><a class="btn btn-danger" href="<?= base_url() ?>/admin/menu/delete/<?= $value['idmenu'] ?>" onclick="return confirm('apakah anda yakin ?');"></a></td> -->
</form>
</td>
<td class="text-center"><a class="btn btn-warning" href="<?= base_url() ?>/admin/menu/find/<?= $value['idmenu'] ?>"><img src="<?= base_url('/icon/pencil.svg') ?>" alt="Pencil"></a></td>
</tr>
<?php endforeach; ?>
</table>
<?= $pager->links('group1', 'bootstrap'); ?>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?php
namespace App\Models;
use CodeIgniter\Model;
class Menu_M extends Model
{
protected $table = 'tblmenu';
protected $allowedFields = ['idkategori', 'menu', 'gambar', 'harga'];
protected $primaryKey = 'idmenu';
protected $validationRules = [
'menu' => 'min_length[3]|is_unique[tblmenu.menu]',
'harga' => 'numeric'
];
protected $validationMessages = [
'menu' => [
'min_length' => '-sorry minimum menu 3 letter numbers',
'is_unique' => '-sorry menu has been taken please choose another'
],
'harga' => [
'numeric' => '-Sorry harga should be number'
],
];
}
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $title ?></title>
<!-- Bootstrap css -->
<link rel="stylesheet" href="<?= base_url('bootstrap-4.4.1-dist/css/bootstrap.min.css') ?> ">
<!-- My CSS -->
<link rel="stylesheet" href="<?= base_url('css/style.css') ?>">
<link rel="stylesheet" href="<?= base_url('css/fixed.css') ?>" />
<!-- My Icon -->
<link rel="icon" href="../upload/logo.jpg">
</head>
<body>
<!-- Navbar -->
<nav class=" navbar navbar-expand-lg navbar-light">
<div class="container">
<a class="navbar-brand mb-0 h-1" href="<?= base_url('homepage') ?>"><img width="60" height="60" class="d-inline-block align-top" alt="" loading="lazy" src="<?= base_url('upload/logo.jpg') ?>" alt=""></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav ml-auto">
<?php if (empty(session()->get('pelanggan'))) : ?>
<a class="nav-link" href="<?= base_url('front/daftar') ?>">Daftar</a>
<a class="nav-item nav-link active" href="<?= base_url('login') ?>">Login <span class="sr-only">(current)</span></a>
<?php endif; ?>
<?php if (!empty(session()->get('pelanggan'))) : ?>
<a class="nav-link" href="<?= base_url('front/history') ?>">History <i class="fa fa-history" aria-hidden="true"></i></a>
<?php endif ?>
<?php if (!empty(session()->get('pelanggan'))) : ?>
<a class="nav-link" href="<?= base_url('/cart/keranjang') ?>">Cart <i class="fa fa-shopping-cart" aria-hidden="true"></i></a>
<?php endif ?>
<a class="nav-link">
<?php if (!empty(session()->get('pelanggan'))) {
echo session()->get('pelanggan');
} ?>
<i class="fa fa-user" aria-hidden="true"></i></a>
<?php if (!empty(session()->get('pelanggan'))) : ?>
<a class="nav-link" href="<?= base_url('front/loginp/logout') ?>">Logout <i class="fa fa-power-off" aria-hidden="true"></i></a>
<?php endif ?>
</div>
</div>
</div>
</nav>
<!-- End Navbar -->
<?= $this->renderSection('content2'); ?>
<!-- footer area -->
<footer class="page-footer bg-dark">
<div class="bg-primary">
<div class="container">
<div class="row py-4 d-flex align-items-center">
<div class="col-md-12 text-center">
<a href="#"><i class="fab fa-facebook-square text-white mr-4"></i></a>
<a href="#"><i class="fab fa-twitter text-white mr-4"></i></a>
<a href="#"><i class="fab fa-google-play text-white"></i></a>
</div>
</div>
</div>
</div>
<div class="container text-white text-center text-md-left mt-5">
<div class="row">
<div class="col-md-3 mx-auto mb-4">
<h6 class="text-uppercase font-weight-bold">About us</h6>
<hr class="bg-primary mb-4 mt-0 d-inline-block mx-auto" style="width: 80px; height: 2px;">
<div>
<img mt width="60" height="60" class="d-inline-block mx-auto" alt="" loading="lazy" src="<?= base_url('upload/logo.jpg') ?>" alt="">
<p class="mt-2">Lorem ipsum dolor sit amet consectetur adipisicing elit. Vitae aspernatur libero explicabo veniam pariatur adipisci nemo a labore error, ducimus fugit ipsum obcaecati nam. Rem!</p>
</div>
</div>
<div class="col-md-2 mx-auto mb-4">
<h6 class="text-uppercase font-weight-bold">Products</h6>
<hr class="bg-primary mb-4 mt-0 d-inline-block mx-auto" style="width: 85px; height: 2px;">
<ul class="list-unstyled">
<li class="my-2"><a class="text-white" href="#">Our apps</a></li>
</ul>
</div>
<div class="col-md-2 mx-auto mb-4">
<h6 class="text-uppercase font-weight-bold">Usefull Links</h6>
<hr class="bg-primary mb-4 mt-0 d-inline-block mx-auto" style="width: 115px; height: 2px;">
<ul class="list-unstyled">
<li class="my-2"><a class="text-white" href="#">About Us</a></li>
<li class="my-2"><a class="text-white" href="#">Terms & Conditions</a></li>
<li class="my-2"><a class="text-white" href="#">Contact Us</a></li>
</ul>
</div>
<div class="col-md-3 mx-auto mb-4">
<h6 class="text-uppercase font-weight-bold">Contacts</h6>
<hr class="bg-primary mb-4 mt-0 d-inline-block mx-auto" style="width: 115px; height: 2px;">
<ul class="list-unstyled">
<li class="my-2"><i class="fas fa-home mr-3"></i> Sidoarjo Sukodono</li>
<li class="my-2"><i class="fas fa-envelope mr-3"></i><EMAIL></li>
<li class="my-2"><i class="fas fa-phone mr-3"></i> 0009919297421496</li>
</ul>
</div>
</div>
</footer>
<div class="footer-copyright text-center py-3">
<p>© Copyright
<a href="">FoodsApp</a></p>
<p>Desigend By Rsiyun</p>
</div>
<!-- End Footer area -->
<!-- My javascript -->
<script src="<?= base_url('bootstrap-4.4.1-dist/jqpop/jquery-3.5.1.slim.min.js') ?>"></script>
<script src="<?= base_url('bootstrap-4.4.1-dist/js/bootstrap.bundle.min.js') ?>"></script>
<script src="<?= base_url('bootstrap-4.4.1-dist/js/fontawesome.js') ?>"></script>
</body>
</html><file_sep><?= $this->extend('layout/template') ?>
<?= $this->section('content') ?>
<?php
if (isset($_GET['page'])) {
$jumlah = 3;
$page = $_GET['page'];
$no = ($page * $jumlah) - $jumlah + 1;
} else {
$no = 1;
}
?>
<div class="row">
<div class="col">
<h3><?= $judul ?></h3>
</div>
</div>
<div class="row">
<div class="col">
<table class="table table-bordered">
<tr>
<th>No</th>
<th>ID Order</th>
<th>Pelanggan</th>
<th>Tanggal</th>
<th>Total</th>
<th>Bayar</th>
<th>Kembali</th>
<th>Status</th>
</tr>
<tr>
<?php $no; ?>
<?php foreach ($orders as $order => $value) : ?>
<td><?= $no++; ?></td>
<td><?= $value['idorder']; ?></td>
<td><?= $value['pelanggan']; ?></td>
<td><?= $value['tglorder']; ?></td>
<td><?= $value['total']; ?></td>
<td><?= $value['bayar']; ?></td>
<td><?= $value['kembali']; ?></td>
<?php
if ($value['status'] == 1) {
$status = 'Lunas';
} else {
$link = base_url('/admin/order/find/') . '/' . $value['idorder'];
$status = '<a href="' . $link . '" class="btn btn-primary">Bayar</a>';
}
?>
<td><?= $status ?></td>
</tr>
<?php endforeach; ?>
</table>
<?= $pager->makeLinks(1, $tampil, $total, 'bootstrap') ?>
</div>
</div>
<?php $this->endSection() ?><file_sep><?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>
<?php
if (isset($_GET['page_group1'])) {
$jumlah = 3;
$page = $_GET['page_group1'];
$no = ($page * $jumlah) - $jumlah + 1;
} else {
$no = 1;
}
?>
<div class="row">
<div class="col">
<h3><?= $judul ?></h3>
</div>
</div>
<div class="row">
<div class="col">
<?php if (session()->getFlashdata('berhasil')) : ?>
<div class="alert alert-success" role="alert">
<?= session()->getFlashdata('berhasil') ?>
</div>
<?php endif; ?>
<table class="table table-bordered">
<tr>
<th class="text-center">No</th>
<th class="text-center">pelanggan</th>
<th class="text-center">Alamat</th>
<th class="text-center">email</th>
<th class="text-center">Aksi</th>
<th class="text-center">Status</th>
</tr>
<tr>
<?php $no; ?>
<?php foreach ($pelanggan as $cat => $value) : ?>
<td><?= $no++; ?></td>
<td><?= $value['pelanggan']; ?></td>
<td><?= $value['alamat']; ?></td>
<td><?= $value['email']; ?></td>
<td>
<form class="text-center" action="pelanggan/<?= $value['idpelanggan'] ?>" method="post">
<?= csrf_field() ?>
<input type="hidden" name="_method" value="DELETE">
<button onclick="return confirm('apakah anda yakin ?');" type="submit" class="btn btn-danger"><img src="<?= base_url('/icon/trash.svg') ?>" alt="sampah"></button>
<!-- <td><a class="btn btn-danger" href="<?= base_url() ?>/admin/pelanggan/delete/<?= $value['idpelanggan'] ?>" onclick="return confirm('apakah anda yakin ?');"></a></td> -->
</form>
</td>
<?php
if ($value['aktif'] == 1) {
$aktif = 'Aktif';
} else {
$aktif = 'Non Aktif';
}
?>
<td class="text-center"><a class="btn btn-primary" href="<?= base_url() ?>/admin/pelanggan/update/<?= $value['idpelanggan'] ?>/<?= $value['aktif'] ?>"><?= $aktif ?></a></td>
</tr>
<?php endforeach; ?>
</table>
<?= $pager->links('group1', 'bootstrap'); ?>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>
<?php
if (isset($_GET['page_group1'])) {
$jumlah = 3;
$page = $_GET['page_group1'];
$no = ($page * $jumlah) - $jumlah + 1;
} else {
$no = 1;
}
?>
<div class="row">
<div class="col-4">
<a class="btn btn-primary" href="<?= base_url('/admin/kategori/create') ?>">Tambah Data</a>
</div>
<div class="col">
<h3><?= $judul ?></h3>
</div>
</div>
<div class="row">
<div class="col">
<?php if (session()->getFlashdata('berhasil')) : ?>
<div class="alert alert-success" role="alert">
<?= session()->getFlashdata('berhasil') ?>
</div>
<?php endif; ?>
<table class="table table-bordered">
<tr>
<th class="text-center">No</th>
<th class="text-center">Kategori</th>
<th class="text-center">Keterangan</th>
<th colspan="2" class="text-center">Aksi</th>
</tr>
<?php $no; ?>
<?php foreach ($kategori as $cat => $value) : ?>
<td><?= $no++; ?></td>
<td><?= $value['kategori']; ?></td>
<td><?= $value['keterangan']; ?></td>
<td class="text-center"><a class="btn btn-danger" href="<?= base_url() ?>/admin/kategori/delete/<?= $value['idkategori'] ?>" onclick="return confirm('apakah anda yakin ?');"><img src="<?= base_url('/icon/trash.svg') ?>" alt="sampah"></a></td>
<td class="text-center"><a class="btn btn-warning" href="<?= base_url() ?>/admin/kategori/find/<?= $value['idkategori'] ?>"><img src="<?= base_url('/icon/pencil.svg') ?>" alt="pencil"></a></td>
</tr>
<?php endforeach; ?>
</table>
<?= $pager->links('group1', 'bootstrap'); ?>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?php
namespace App\Controllers\Admin;
use App\Controllers\BaseController;
use App\Models\Kategori_M;
use App\Models\Menu_M;
class Menu extends BaseController
{
protected $modelMenu, $pager, $modelKategori;
public function __construct()
{
$this->modelMenu = new Menu_M();
$this->modelKategori = new Kategori_M();
$this->pager = \Config\Services::pager();
}
public function index()
{
$data = [
'title' => 'Aplikasi|Select',
'judul' => 'Daftar Menu',
'menu' => $this->modelMenu->paginate(3, 'group1'),
'pager' => $this->modelMenu->pager
];
return view('menu/select', $data);
}
public function option()
{
$kategori = $this->modelKategori->findAll();
$data = [
'kategoris' => $kategori
];
return view('layout/option', $data);
}
public function read()
{
if (isset($_GET['idkategori'])) {
$id = $_GET['idkategori'];
$jumlah = $this->modelMenu->where('idkategori', $id)->findAll();
$count = count($jumlah);
$tampil = 3;
$mulai = 0;
if (isset($_GET['page'])) {
$page = $_GET['page'];
$mulai = ($tampil * $page) - $tampil;
}
$menu = $this->modelMenu->where('idkategori', $id)->findAll($tampil, $mulai);
$data = [
'title' => 'Aplikasi|Select',
'judul' => 'Daftar Menu',
'menu' => $menu,
'pager' => $this->pager,
'tampil' => $tampil,
'total' => $count
];
return view('menu/cari', $data);
}
}
public function delete($id = null)
{
$this->modelMenu->delete($id);
return redirect()->to(base_url("/admin/menu"));
}
public function find($id = null)
{
$kategori = $this->modelKategori->findAll();
$menu = $this->modelMenu->find($id);
$data = [
'title' => 'Aplikasi|Update',
'judul' => 'Update',
'menu' => $menu,
'kategoris' => $kategori,
'validation' => \Config\Services::validation()
];
return view('menu/update', $data);
}
public function update()
{
$modelMenu = $this->modelMenu;
$id = $this->request->getPost('idmenu');
$file = $this->request->getFile('gambar');
if (empty($nama)) {
$nama = $this->request->getPost('gambar');
} else {
$nama = $file->getName();
$file->move('./upload');
}
$data = [
'idkategori' => $this->request->getPost('idkategori'),
'menu' => $this->request->getPost('menu'),
'gambar' => $nama,
'harga' => $this->request->getPost('harga')
];
if ($modelMenu->update($id, $data) === false) {
$error = $modelMenu->errors();
session()->setFlashdata('pesan', $error);
return redirect()->to(base_url("/admin/menu/find/$id"));
} else {
session()->setFlashdata('berhasil', 'data berhasil di tambahkan');
return redirect()->to(base_url("/admin/menu"));
}
}
public function create()
{
$kategori = $this->modelKategori->findAll();
$data = [
'title' => 'Aplikasi|forminsert',
'judul' => "INSERT",
'kategoris' => $kategori
];
return view('menu/insert', $data);
}
public function insert()
{
$modelMenu = $this->modelMenu;
$file = $this->request->getFile('gambar');
$nama = $file->getName();
$data = [
'idkategori' => $this->request->getPost('idkategori'),
'menu' => $this->request->getPost('menu'),
'harga' => $this->request->getPost('harga'),
'gambar' => $nama
];
if ($modelMenu->insert($data) === false) {
$error = $modelMenu->errors();
session()->setFlashdata('pesan', $error['menu']);
return redirect()->to(base_url("/admin/menu/create"));
} else {
$file->move('./upload');
session()->setFlashdata('berhasil', 'data berhasil di tambahkan');
return redirect()->to(base_url("/admin/menu"));
}
}
}
<file_sep><?php
namespace App\Controllers\Admin;
use App\Controllers\BaseController;
use App\Models\OrderDetail_M;
class OrderDetail extends BaseController
{
protected $model, $pager;
public function __construct()
{
$this->pager = \Config\Services::pager();
$this->model = new OrderDetail_M();
}
public function index()
{
$data = [
'title' => 'Aplikasi|Select',
'judul' => 'Daftar Rincian order',
'orderdetail' => $this->model->paginate(3, 'group1'),
'pager' => $this->model->pager
];
return view('orderdetail/select', $data);
}
public function cari()
{
if (isset($_POST['awal'])) {
$awal = $_POST['awal'];
$akhir = $_POST['akhir'];
$sql = "SELECT * FROM vorderdetail WHERE tglorder BETWEEN '$awal' AND '$akhir'";
$conn = \Config\Database::connect();
$result = $conn->query($sql);
$detail = $result->getResult('array');
$data = [
'title' => 'cari',
'judul' => 'search data',
'orderdetail' => $detail
];
return view('orderdetail/cari', $data);
}
}
}
<file_sep><?php
namespace App\Controllers\Admin;
use App\Controllers\BaseController;
use App\Models\Kategori_M;
class Menu2 extends BaseController
{
public function index()
{
$data = [
'title' => 'Select|Menu'
];
return view('menu/form', $data);
}
public function insert()
{
$file = $this->request->getFile('gambar');
$nama = $file->getname();
$file->move('./upload', $nama);
echo $nama . " Sudah di upload";
}
public function option()
{
$model = new Kategori_M();
$kategori = $model->findAll();
$data = [
'kategoris' => $kategori
];
return view('layout/option', $data);
}
}
<file_sep><?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>
<div class="col">
<h3><?= $judul ?></h3>
<?php if (session()->getFlashdata('pesan')) : ?>
<div class="alert alert-danger" role="alert">
<?= session()->getFlashdata('pesan') ?>
</div>
<?php endif; ?>
</div>
<div class="col-6">
<form action="<?= base_url('/admin/kategori/insert') ?>" method="post">
<div class="form-group">
<label for="kategori">Kategori:</label>
<input type="text" name="kategori" autocomplete="off" required class="form-control" id="kategori">
</div>
<div class="form-group">
<label for="keterangan">Keterangan:</label>
<input type="text" name="keterangan" autocomplete="off" required class="form-control" id="keterangan">
</div>
<button type="submit" class="btn btn-primary">Tambah Data</button>
</form>
</div>
<?= $this->endSection(); ?>
|
858a47b3dc490f23072e608da9a36958a12eea3f
|
[
"PHP"
] | 22
|
PHP
|
rsiyun/project-restoran-ci4
|
c2f731789c3807ff085ff86a91303edba3dfe045
|
0d46a98c2fb4f8b1fe4399cb2eb51186c30941d6
|
refs/heads/master
|
<file_sep>from setuptools import setup
setup(
name='edoxrd',
version='0.1',
description='',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/ezatterin/edoxrd',
packages = ['edoxrd'],
install_requires=[
'numpy',
'matplotlib',
'scipy',
'pandas'
],
long_description = """
Work in progress.
"""
)
<file_sep>import numpy as np
from pkg_resources import resource_filename
from edoxrd.utils import asf, mat_dict, tt2q
from edoxrd.read import read_data
from edoxrd.calc import calc_str_fac
def calc_ctr(fname, sub, film, Nfilm, c_film, Nelectrode_b=0, Nelectrode_t=0,
c_electrode_b=0, c_electrode_t=0, scale=1e7, Nsub=1e4, c_sub=None,
comm='*'):
"""
Calculate the thickness of a thin film on top of a substrate from its
Laue oscillations.
Parameters
----------
fname: string
The filename in .asc format.
datadir: string
The directory containing fname.
sub: string
The name of the substrate material.
film: string
The name of the film material
Nfilm: int
The thickness of the film in unit cells.
c_film: float
The out-of-plane lattice parameter of the film in A.
Nelectrode_b: int
The thickness of the Bottom electrode (SRO_b) in unit cells.
Default: 0 (No bottom Electrode).
Nelectrode_t: int
The thickness of the Top electrode (SRO_t) in unit cells.
Default: 0 (No top Electrode).
c_electrode_b: float
The out-of-plane lattice parameter of the Bottom electrode in A.
Default: 0 (No bottom Electrode).
c_electrode_t: float
The out-of-plane lattice parameter of the Top electrode in A.
Default: 0 (No top Electrode).
scale: int
Overall multiplier for the calculated intensity.
Default: 1e7.
Nsub: int
Thickness of the Substrate layer.
Default: 1e4.
Returns
-------
xdata: ndarray
The original measured twotheta range.
I: ndarray
The calculated Intensity.
Example
-------
>>> x, y = xrd.calc_ctr('e16014_09_t2t_002.ras', d, 'KTO', 'PTO', 60, 3.92)
"""
# Constants
wave = 1.5406
mu = 4e4
elec_b = 'SRO_b'
elec_t = 'SRO_t'
param, pos = mat_dict()
if c_sub is None:
c_sub = param[sub][2]
elif c_sub is not None:
print('using c_sub as {0}, the "original" value is {1}'
.format(c_sub, param[sub][2]))
# Read the data
xdata, ydata = read_data(fname)
q = tt2q(xdata)
# No electrodes
if Nelectrode_b <=0 and Nelectrode_t <= 0:
# Load data
mats = [sub, film]
t = (Nsub*c_sub + Nfilm*c_film)
# Calc structure factor and build shape function dictionary
F = {}
for material in mats:
F[material] = calc_str_fac(material, xdata) # does not want q, fix?
S = {sub:0, film:0}
# Calc shape function for each material
for l in range(0, int(Nsub)):
S[sub] += np.exp((t-l*c_sub) * (1j*q-(4*np.pi)/(mu*wave*q)))
for l in range(0, int(Nfilm)):
S[film] += np.exp((t - (l*c_film + Nsub*c_sub)) *
(1j*q - (4*np.pi) / (mu*wave*q)))
# Top electrode
elif Nelectrode_b <= 0 and Nelectrode_t > 0:
# Load data
mats = [sub, elec_t, film]
t = (Nsub*c_sub + Nelectrode_t*c_electrode_t + Nfilm*c_film)
# Calc structure factor and build shape function dictionary
F = {}
for material in mats:
F[material] = calc_str_fac(material, xdata)
S = {sub:0, film:0, elec_t:0}
# ?
for l in range(0,int(Nsub)):
S[sub] += np.exp((t-l*c_sub) * (1j*q-(4*np.pi)/(mu*wave*q)))
for l in range(0, int(Nfilm)):
S[film] += np.exp((t - (l*c_film + Nsub*c_sub)) *
(1j*q - (4*np.pi) / (mu*wave*q)))
for l in range(0, int(Nelectrode_t)):
S[elec_t] += np.exp((t - (l*c_electrode_t + Nfilm*c_film
+ Nsub*c_sub)) * (1j*q - (4*np.pi) / (mu*wave*q)))
# Bottom electrode
elif Nelectrode_b > 0 and Nelectrode_t <= 0:
mats = [sub, elec_b, film]
t = (Nsub*c_sub + Nelectrode_b*c_electrode_b + Nfilm*c_film)
F = {}
for material in mats:
F[material] = calc_str_fac(material, xdata)
S = {sub:0, film:0, elec_b:0}
# ?
for l in range(0,int(Nsub)):
S[sub] += np.exp((t-l*c_sub) * (1j*q-(4*np.pi)/(mu*wave*q)))
for l in range(0, int(Nelectrode_b)):
S[elec_b] += np.exp((t - (l*c_electrode_b + Nsub*c_sub)) *
(1j*q - (4*np.pi) / (mu*wave*q)))
for l in range(0, int(Nfilm)):
S[film] += np.exp((t - (l*c_film + Nelectrode_b*c_electrode_b
+ Nsub*c_sub)) * (1j*q - (4*np.pi) / (mu*wave*q)))
# Both electrodes
elif Nelectrode_b > 0 and Nelectrode_t > 0:
mats = [sub,film,elec_b,elec_t]
t = (Nsub*c_sub + Nelectrode_b*c_electrode_b + Nfilm*c_film +
Nelectrode_t*c_electrode_t)
F = {}
for material in mats:
F[material] = calc_str_fac(material, xdata)
S = {sub:0, film:0, elec_b:0, elec_t:0}
# ?
for l in range(0,int(Nsub)):
S[sub] += np.exp((t-l*c_sub) * (1j*q-(4*np.pi)/(mu*wave*q)))
for l in range(0, int(Nelectrode_b)):
S[elec_b] += np.exp((t - (l*c_electrode_b + Nsub*c_sub)) *
(1j*q - (4*np.pi) / (mu*wave*q)))
for l in range(0, int(Nfilm)):
S[film] += np.exp((t - (l*c_film + Nelectrode_b*c_electrode_b
+ Nsub*c_sub)) * (1j*q - (4*np.pi) / (mu*wave*q)))
for l in range(0, int(Nelectrode_t)):
S[elec_t] += np.exp((t - (l*c_electrode_t + Nfilm*c_film +
Nelectrode_b*c_electrode_b + Nsub*c_sub)) *
(1j*q - (4*np.pi) / (mu*wave*q)))
g = 0
for material in mats:
g += F[material]*S[material]
# Normalisation and Intensity
g = g / g.max()
I = scale * g * np.conj(g)
return xdata, I
<file_sep>"""
Set of functions to read CTR and RSM data as generated by a Rigaku SmartLab
Diffractometer.
"""
import numpy as np
from pandas import read_csv
def read_data(fname):
"""
Reads .ras Rigaku files.
Parameters
----------
fname: string
File path in .ras extension.
Returns
-------
xdata: ndarray
Array of Two Theta values.
ydata: ndarray
Array of Intensity values.
Example
-------
>>> xdata, ydata = read_data('/home/e16014_01_t2t_001.ras')
"""
# Define path to file
path = fname
# Read it into an array
try:
data = np.genfromtxt(path, delimiter=" ", comments='*', encoding='latin1')
except ValueError:
data = np.genfromtxt(path, delimiter=" ", comments='#', encoding='latin1')
xdata = data[:,0] # 2theta in degrees
ydata = data[:,1] # Intensity
offset = data[:,2] # Offset
# Correct for detector attenuation
if np.any(offset > 1):
mask = offset > 1
indeces = np.where(mask)
ydata[indeces] = ydata[indeces] * offset[indeces]
return xdata, ydata
def read_rsm_data(fname, coordinates='qspace'):
"""
Read data from a Reciprocal Space Map, in .asc format.
Parameters
----------
fname: string
File path in .asc extension.
coordinates: string
Coordinate frame for Intensity mapping. Can be in 2theta, omega space
('angles'), or qspace ('qspace'). Default is 'qspace'.
Returns
-------
q1: ndarray
Array of q1 values.
q2: ndarray
Array of q2 values.
I: ndarray
Array of Intensity values.
Example
-------
>>> qx, qz, I = read_rsm_data('/home/e16019_01_-103_KTO_RSM_2-Theta.asc')
"""
# read data as lines
d = np.genfromtxt(fname, dtype='str', delimiter='\n', encoding='latin1')
# Wavelength
wave = [line for line in d if '*WAVE_LENGTH1' in line]
lambdaone = float(wave[0].split()[2])
# Scan speed
speed_name = [line for line in d if '*SPEED' in line]
speed = int(speed_name[1].split()[2])
# build array of measured Twotheta values
start = [line for line in d if '*START' in line]
twotheta_start = float(start[0].split()[2])
stop = [line for line in d if '*STOP' in line]
twotheta_stop = float(stop[0].split()[2])
step = [line for line in d if '*STEP' in line]
twotheta_step = float(step[0].split()[2])
count = [line for line in d if '*COUNT' in line]
no_twotheta = int(count[1].split()[2]) # there is a 'counter' line
# 1D array of meas twotheta
twotheta = np.arange(twotheta_start, twotheta_stop, twotheta_step)
# build array of measured Omega values
sec_count = [line for line in d if '*SEC_COUNT' in line]
no_omega = int(sec_count[0].split()[2])
omega_lines = [line for line in d if '*OFFSET' in line]
# 1D array of meas omega
omega = np.zeros(len(omega_lines, ))
for index, line in enumerate(omega_lines):
omega[index] = line.split()[2]
# build array of measured Intensity values
d2 = read_csv(fname, header=None, comment='*')
d2 = d2.values.flatten() # 1D nparray of I
d2 = d2[np.logical_not(np.isnan(d2))] # delete NaN values
d2 = d2.reshape(no_twotheta, no_omega, order='F') # matlab order
I = d2 / speed # Normalise to counts per second
# make ttheta, omega mesh
xx, yy = np.meshgrid(twotheta, omega, indexing='ij')
# to radiants
ttrad = np.deg2rad(xx)
omrad = np.deg2rad(yy)
if coordinates=='angles':
return yy, xx, I
elif coordinates=='qspace':
# to qx, qz
qx = (2*np.pi / lambdaone) * (np.cos(omrad) - np.cos(ttrad - omrad))
qz = (2*np.pi / lambdaone) * (np.sin(omrad) + np.sin(ttrad - omrad))
return qx, qz, I<file_sep>""" Initialisation file for the edoxrd module. Updated 7.11 """
from edoxrd.read import read_data
from edoxrd.read import read_rsm_data
from edoxrd.utils import mat_dict
from edoxrd.utils import tt2q
from edoxrd.utils import asf
from edoxrd.utils import find_osc
from edoxrd.calc import calc_str_fac
from edoxrd.calc import calc_thickness
from edoxrd.ctr import calc_ctr
from edoxrd.plots import plt_rsm
from edoxrd.plots import plt_prof
<file_sep>"""
Set of functions to simulate CTRs and RSMs. Updated 7.11.
"""
import numpy as np
import matplotlib.pyplot as plt
from pkg_resources import resource_filename
from edoxrd.utils import asf, mat_dict, tt2q, find_osc
from edoxrd.read import read_data, read_rsm_data
def calc_str_fac(material,ttheta):
"""
Calculate the Structure Factor of a material belonging to the Perovskite
Oxides family. Materials: STO,PTO,MTO,SRO,KTO,DSO.
Parameters
----------
material: string
ttheta: ndarray
Returns
-------
F: ndarray
Example
-------
>>> F = calc_str_fac('PTO',xdata)
"""
# Initialise
mat_param, mat_pos = mat_dict()
q = tt2q(ttheta)
f = asf(q)
ls = dict(
STO = (['Sr', 'Ti'] + ['O']*3),
PTO = (['Pb', 'Ti'] + ['O']*3),
MTO = (['Mn', 'Ti'] + ['O']*3),
SRO = (['Sr', 'Ti'] + ['O']*3),
KTO = (['K', 'Ta'] + ['O']*3),
DSO = (['Dy', 'Sc'] + ['O']*3)
)
if material == 'SRO_b' or material == 'SRO_t':
atom_list = ls['SRO']
else:
atom_list = ls[material]
F = 0
for i, atom in enumerate(atom_list):
F += f[atom] * np.exp(1j * ( q * mat_pos[material][i,2]*mat_param[material][2]))
return F
def calc_thickness(fname, threshold=1e-4, distance=20, side='r'):
"""
Calculate the thickness of a thin film on top of a substrate from its
Laue oscillations.
Parameters
----------
fname: string
The filename in .ras format.
thres : float between [0., 1.]
Normalized threshold. Only the peaks with amplitude higher than the
threshold will be detected. Default: 1e-4
min_dist : int
Minimum distance between each detected peak. The peak with the highest
amplitude is preferred to satisfy this constraint. Default: 20.
side: string
Side of the film peak where to look for oscillations. Either 'l'
(left), or 'r' (right). Default: 'r'
Returns
-------
t: float
Thickness of the film.
Example
-------
>>> t = calc_thickness(dset, d, threshold=1e-5, distance=15, side='l')
"""
xpeaks, ypeaks = find_osc(fname, threshold=threshold,
m_distance=distance, peak_side=side)
x = np.asarray([x for x in range(len(xpeaks))]) # oscillation peak order
y = 4 * np.pi * np.sin(np.deg2rad(xpeaks/2)) / 0.15406 # q_m's
m, b = np.polyfit(x, y, 1) # linear fit
t = abs(2 * np.pi / m)
fig, ax = plt.subplots(1,2, figsize=(12,4))
fig.suptitle('The thickness of sample {0} is {1:.3f} nm with accuracy {2:.3f}'\
.format(fname[:6], t, 1./x.max() ))
ax[0].scatter(xpeaks, ypeaks,c='red')
ax[0].plot(*read_data(fname)); ax[0].set_yscale('log')
ax[1].scatter(x, y)
ax[1].plot(x, x*m+b, c='red', label='$q_m = {0:.3f}m + {1:.3f}$'.format(m, b))
ax[1].legend(); plt.show()
return t
def l_prof_max(filelist, d, L=None, q=False):
""" TODO! """
# select correct dataset
pto = filelist[1]
# read data
h, l, i = read_rsm_data(pto, d, scale='lin')
if L==None:
L = l[np.where(i==i.max())]
# find indexes of values close to selected L
a = abs(l-L)
mask_a = ((a > 0) & (a < 1e-4))
lst_a = []
for number in a[mask_a]:
lst_a.append([(int(np.where(a==number)[0])),int(np.where(a==number)[1])])
idx_l = np.array(lst_a)
I = i[idx_l[:,0], idx_l[:,1]][::-1]
H = h[idx_l[:,0], idx_l[:,1]][::-1]
if q == True:
H = (2*np.pi/0.399)*(H +1)
return H, I
<file_sep>"""
Set of functions to plot and compare CTRs and RSMs. Updated 7.11.
"""
import numpy as np
import matplotlib.pyplot as plt
from edoxrd.read import read_rsm_data
def plt_rsm(sub, film, normalisation='sub', scale='log', coordinates='hkl'):
"""
Plot the RSM of a substrate and film around a reflection on the same
figure.
Parameters
----------
sub: string
The substrate scan, in .asc format.
film: string
The film scan, in .asc format.
d: string
Directory containing sub and film.
normalisation: string
Either 'film' or 'sub'. Normalise the plotted intensity with respect to
the film or substrate maximum, respecively. Default: 'sub'.
scale: string
Either 'log' or 'lin'. Logarithmic or Linear intensity scale for
the plot, respectively. Default: 'log'.
coordinates: string
Either 'hkl' or 'ttomega'. Reciprocal or Real space coordinate mapping
for the measured intensity.
Returns
-------
Plot. Can be overridden.
Example
-------
>>> plt_rsm('e16014_01_-103_KTO_RSM_2-Theta.asc',
'e16014_02_-103_PTO_RSM_2-Theta.asc',d)
"""
# Read data
h, l, i = read_rsm_data(sub, scale=scale, coordinates=coordinates)
H, L, I = read_rsm_data(film, scale=scale, coordinates=coordinates)
# plot
if normalisation == 'sub':
plt.pcolormesh(h,l,i,vmin=I.min(),vmax=I.max())
plt.pcolormesh(H,L,I)
plt.axis([H[0].min(),H[:,0].max(),l[0].min(),L[:,0].max()])
plt.axes().set_aspect('equal')
plt.colorbar()
elif normalisation == 'film':
plt.pcolormesh(h,l,i)
plt.pcolormesh(H,L,I,vmin=i.min(),vmax=i.max())
plt.axis([H[0].min(),H[:,0].max(),l[0].min(),L[:,0].max()])
plt.axes().set_aspect('equal')
plt.colorbar()
if coordinates == 'ttomega':
plt.xlabel(r'$/omega$'); plt.ylabel(r'$2/theta')
elif coordinates == 'hkl':
plt.xlabel('H'); plt.ylabel('L')
def plt_prof(sample, H, L, scale='log'):
"""
Plots profile of an RSM plot. TODO!
"""
h,l,I = read_rsm_data(sample, scale=scale)
a = abs(l-L)
b = abs(h-H)
mask_a = ((a > 0) & (a < 1e-4))
mask_b = ((b > 0) & (b < 1e-4))
lst_a, lst_b = [], []
for number in a[mask_a]:
lst_a.append([(int(np.where(a==number)[0])),int(np.where(a==number)[1])])
for number in b[mask_b]:
lst_b.append([(int(np.where(b==number)[0])),int(np.where(b==number)[1])])
idx_l = np.array(lst_a)
idx_h = np.array(lst_b)
I_h = I[idx_l[:,0], idx_l[:,1]][::-1]
I_l = I[idx_h[:,0], idx_h[:,1]][::-1]
h_h = h[idx_l[:,0], idx_l[:,1]][::-1]
l_l = l[idx_h[:,0], idx_h[:,1]][::-1]
fig, ax = plt.subplots(1,3, figsize=(13,5))
ax[0].pcolormesh(h,l,I); ax[0].set_ylabel('L'); ax[0].set_xlabel('H')
ax[0].plot([h.min(),h.max()],[L,L],'r-')
ax[0].plot([H, H], [l.min(),l.max()],'r-')
ax[1].plot(h_h, I_h); ax[1].set_ylabel(r'$I$'); ax[1].set_xlabel('H')
ax[2].plot(l_l, I_l); ax[2].set_ylabel(r'$I$'); ax[2].set_xlabel('L')
plt.tight_layout()
plt.show()
<file_sep>"""
Set of functions to perform a variety of tasks related to Diffraction data
analysis. Updated 11.7.
"""
import numpy as np
import peakutils as pk
from pkg_resources import resource_filename
from edoxrd.read import read_data
def mat_dict():
"""
Generates a tuple containing dictionaries with Unit Cell Parameters and
Atomic coordinates for a range of materials.
Returns
-------
out: tuple
A tuple of two dictionaries, Material_name:Parameters and
Material_name:Atomic_coordinates
Example
-------
>>> param, pos = mat_dict()
>>> print(param['PTO'])
"""
# Load data files
mat_param = resource_filename('edoxrd','/data/material_parameters.txt')
atom_positions = resource_filename('edoxrd', '/data/atom_positions.txt')
# Generate arrays of parameters and material names
param = np.genfromtxt(mat_param, usecols=(0,1,2))
names = list(np.genfromtxt(mat_param, usecols=3, dtype='U5'))
# Make a dictionary Mat_name:Parameters(a,b,c)
mat_param = {}
for n, a in zip(names, param):
mat_param[n] = a
# Generate array of atomic positions for each material
pos = np.genfromtxt(atom_positions).reshape(((len(mat_param)+1),5,3))
# Make a dicitonary Mat_name:Positions(x,y,z)
mat_pos = {}
for name, array in zip(mat_param.keys(), pos):
mat_pos[name] = array
return mat_param, mat_pos
def tt2q(ttheta):
"""
Convert TwoTheta values to Q (Scattering vector).
Parameters
----------
ttheta: 1D array of TwoTheta angles
Returns
-------
out: ndarray
1D Array of Q values
Example
-------
>>> Qx = tt2q(two_theta_x)
"""
q = 4 * np.pi * np.sin(np.deg2rad(ttheta/2))/1.5406
return q
def asf(q):
"""
Function to calculate the Atomic Scattering Factor of several atoms.
Parameters
----------
q: ndarray
Array of scattering vectors.
Returns
-------
out: dictionary
Each entry of the output dictionary contains the ASF (ndarray) for the specified
material key.
Example
-------
>>> F_Ti = asf(q)['Ti']
"""
# Load data
filepath = resource_filename('edoxrd','/data/asf_atom_constants.txt')
# Generate list of scattering constants for each atom
atom_const = np.genfromtxt(filepath)
atom_list = ['Mn', 'O', 'Pb', 'Ru', 'Sr', 'Ti', 'K', 'Ta', 'Mg', 'Dy', 'Sc']
atom_asf = {}
for name, array in zip(atom_list, atom_const):
atom_asf[name] = array
# Calc the ASF for each atom and append in dictionary
fmat = {}
for name, m in atom_asf.items(): #each m is the atom array
f = m[0] * np.exp(-m[1]*q/4/np.pi) +\
m[2] * np.exp(-m[3]*q/4/np.pi) +\
m[4] * np.exp(-m[5]*q/4/np.pi) +\
m[6] * np.exp(-m[7]*q/4/np.pi) +\
m[8]
fmat[name] = f
return fmat
def find_osc(fname, threshold=0.000006, m_distance=10, peak_side='r'):
"""TODO!"""
xdata, ydata = read_data(fname)
idxs = pk.indexes(ydata, thres=threshold, min_dist=m_distance)
film_peak = ydata[idxs].argsort()[::-1][1]
peaks = ydata[idxs].argsort()[::-1][2:]
xpeaks, ypeaks = xdata[idxs][peaks],ydata[idxs][peaks]
if peak_side == 'r':
xpeaks, ypeaks = xpeaks[xpeaks > xdata[idxs][film_peak]], ypeaks[xpeaks > xdata[idxs][film_peak]]
else:
xpeaks, ypeaks = xpeaks[xpeaks < xdata[idxs][film_peak]], ypeaks[xpeaks < xdata[idxs][film_peak]]
return xpeaks[0:12], ypeaks[0:12]
def make_superlattice(m1, m2, Nm1, Nm2, MM, Ntot):
""" Function to make a superlattice. TODO! """
superlattice = np.zeros((Ntot,2)); #first column: m1, second column: m2
# Build up the superlattice. Array reflects its periodicity
if Nm2 > 0 and m2 > 0:
qm1 = Nm1
qm2 = Nm2
N = 1
while N < Ntot:
while qm1 >= 1:
if N < Ntot:
superlattice[N-1,0] = 1
superlattice[N-1,1] = 0
N = N + 1
qm1 = qm1 - 1
if N < Ntot:
superlattice[N-1,0] = qm1
superlattice[N-1,1] = 1 - qm1
qm2 = qm2 - superlattice[N,1]
N = N + 1
while qm2 >= 1:
if N < Ntot:
superlattice[N-1,0] = 0
superlattice[N-1,1] = 1
N = N + 1
qm2 = qm2 - 1
if N < Ntot:
superlattice[N-1,0] = 1 - qm2
superlattice[N-1,1] = qm2
qm1 = Nm1 - superlattice[N-1,0]
qm2 = Nm2
N = N + 1
superlattice[N-1,1] = qm2
if superlattice[N-1,1] == 0:
superlattice[N-1,1] = 1
else:
superlattice[:,0] = np.ones((Ntot,))
return superlattice
<file_sep>
def plot_prof_compare(sample, sample2, d, d2, scale, L, H, win,polyorder):
h,l,I = ut.read_rsm_data(sample, d, scale)
h2, l2, I2 = ut.read_rsm_data(sample2, d2, scale)
a = abs(l-L)
b = abs(h-H)
a2 = abs(l2-L)
b2 = abs(h2-H)
mask_a = ((a > 0) & (a < 1e-4))
mask_b = ((b > 0) & (b < 1e-4))
mask_a2 = ((a2 > 0) & (a2 < 1e-4))
mask_b2 = ((b2 > 0) & (b2 < 1e-4))
lst_a, lst_b = [], []
lst_a2, lst_b2 = [], []
for number in a[mask_a]:
lst_a.append([(int(np.where(a==number)[0])),int(np.where(a==number)[1])])
for number in b[mask_b]:
lst_b.append([(int(np.where(b==number)[0])),int(np.where(b==number)[1])])
for number in a2[mask_a2]:
lst_a2.append([(int(np.where(a2==number)[0])),int(np.where(a2==number)[1])])
for number in b2[mask_b2]:
lst_b2.append([(int(np.where(b2==number)[0])),int(np.where(b2==number)[1])])
idx_l = np.array(lst_a)
idx_h = np.array(lst_b)
idx_l2 = np.array(lst_a2)
idx_h2 = np.array(lst_b2)
I_h = I[idx_l[:,0], idx_l[:,1]][::-1]
I_l = I[idx_h[:,0], idx_h[:,1]][::-1]
I_h2 = I2[idx_l2[:,0], idx_l2[:,1]][::-1]
I_l2 = I2[idx_h2[:,0], idx_h2[:,1]][::-1]
h_h = h[idx_l[:,0], idx_l[:,1]][::-1]
l_l = l[idx_h[:,0], idx_h[:,1]][::-1]
h_h2 = h2[idx_l2[:,0], idx_l2[:,1]][::-1]
l_l2 = l2[idx_h2[:,0], idx_h2[:,1]][::-1]
# Plotting
fig, ax = plt.subplots(1,4, figsize=(15,5))
ax[0].pcolormesh(h,l,I); ax[0].set_ylabel('L'); ax[0].set_xlabel('H')
ax[0].plot([h.min(),h.max()],[L,L],'r-')
ax[0].plot([H, H], [l.min(),l.max()],'r-')
ax[0].set_title(sample, fontsize=9)
ax[1].pcolormesh(h2,l2,I2); ax[1].set_ylabel('L'); ax[1].set_xlabel('H')
ax[1].plot([h2.min(),h2.max()],[L,L],'r-')
ax[1].plot([H, H], [l2.min(),l2.max()],'r-')
ax[1].set_title(sample2, fontsize=9)
ax[2].plot(h_h, I_h, label=sample); ax[2].set_ylabel(r'$I$'); ax[2].set_xlabel('H')
ax[2].plot(h_h2, I_h2, label=sample2); ax[2].set_ylabel(r'$I$'); ax[2].set_xlabel('H')
plt.legend(fontsize=9)
ax[3].plot(l_l, I_l, label=sample); ax[3].set_ylabel('$I$'); ax[3].set_xlabel('L')
ax[3].plot(l_l2, I_l2, label=sample2); ax[3].set_ylabel('$I$'); ax[3].set_xlabel('L')
plt.legend(fontsize=9)
plt.tight_layout()
plt.show()
|
20f38e9998c8913311f61d26b2e437460f60c9c3
|
[
"Python"
] | 8
|
Python
|
ezatterin/edoxrd
|
9505f24cd42296cb6af9ca4d22cbd3e0f9367548
|
b9b6f728603053ee0860ffb4ef1de06e23381da6
|
refs/heads/master
|
<file_sep>import kfp.dsl as dsl
import kfp.compiler as compiler
@dsl.pipeline(name='load-predict-pipeline-logreg')
def pipeline(project_id='loan-predict'):
preprocessor = dsl.ContainerOp(
name='preprocessor',
image='praveen049/loan-predict-logreg-preproc',
command=['python', 'preproc/preprocessor.py'],
arguments=[
'--project_id', project_id,
'--output-x-path', 'x.pkl',
'--output-x-path-file', 'x.txt',
'--output-y-path', 'y.pkl',
'--output-y-path-file', 'y.txt',
],
file_outputs={
'x-output': 'x.pkl',
'y-output': 'y.pkl',
}
)
trainer = dsl.ContainerOp(
name='trainer',
image='praveen049/loan-predict-logreg-train',
command=['python', 'train/train.py'],
arguments=[
'--project_id', project_id,
'--input-x-path', preprocessor.outputs['x-output'],
'--input-y-path', preprocessor.outputs['y-output'],
'--output-model-path', 'model.pkl',
'--output-model-path-file', 'model.txt'
],
file_outputs={
'model': 'model.pkl',
'model-path': 'model.txt',
}
)
trainer.after(preprocessor)
if __name__ == '__main__':
compiler.Compiler().compile(pipeline, 'load-predict-pipeline-logreg.zip')
<file_sep># Implementation from kaggle kernel : https://www.kaggle.com/sazid28/home-loan-prediction/notebook
import argparse
import pickle
from pathlib import Path
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
def load_feature(input_x_path):
with open(input_x_path, 'rb') as input_x_file:
return pickle.loads(input_x_file.read())
def load_label(input_y_path):
with open(input_y_path, 'rb') as input_y_file:
return pickle.loads(input_y_file.read())
parser = argparse.ArgumentParser()
parser.add_argument('--input-x-path', type=str, help='')
parser.add_argument('--input-y-path', type=str, help='')
parser.add_argument('--output-model-path', type=str, help='')
parser.add_argument('--output-model-path-file', type=str, help='')
args = parser.parse_args()
X = load_feature(args.input_x_path)
y = load_label(args.input_y_path)
x_train, x_cv, y_train, y_cv = train_test_split(X, y,
test_size=0.3,
random_state=1)
logistic_model = LogisticRegression(random_state=1)
logistic_model.fit(x_train,y_train)
pred_cv_logistic = logistic_model.predict(x_cv)
score_logistic = accuracy_score(pred_cv_logistic,y_cv)*100
with open(args.output_model_path, 'w') as output_model:
pickle.dump(logistic_model, output_model)
Path(args.output_model_path_file).parent.mkdir(parents=True, exist_ok=True)
Path(args.output_model_path_file).write_text(args.output_model_path)
|
1bc38c469ea44d5799389554fad6d10541d91b23
|
[
"Python"
] | 2
|
Python
|
absaj/kubeflow101
|
843d2d6becbb9a7eeca6fce2f81c92fa1249136c
|
6d7508a1068530429a5351dbb46ba62b546d8b5c
|
refs/heads/master
|
<repo_name>robinsonGA/restaurante-BLACEY<file_sep>/js/menu.js
$(document).ready(function() {
var desayunos = $("#btn-desayunos");
var postres = $("#btn-postres");
var ensaladas = $("#btn-ensaladas");
var botanasAntojitos = $("#btn-botanasAntojitos");
var comidas = $("#btn-comidas");
var bebidas = $("#btn-bebidas");
var cajaDesayunos = $("#desayunos");
var cajaPostre = $("#postres");
var cajaEnsaladas = $("#ensaladas");
var cajaBotanasAntojitos = $("#botanasAntojitos");
var cajaComidas = $("#comidas");
var cajaBebidas = $("#bedidas");
desayunos.click(function() {
cajaPostre.hide();
cajaEnsaladas.hide();
cajaBotanasAntojitos.hide();
cajaComidas.hide();
cajaBebidas.hide();
cajaDesayunos.toggle(1000);
});
postres.click(function() {
cajaDesayunos.hide();
cajaEnsaladas.hide();
cajaBotanasAntojitos.hide();
cajaComidas.hide();
cajaBebidas.hide();
cajaPostre.toggle(1000);
});
ensaladas.click(function() {
cajaDesayunos.hide();
cajaPostre.hide();
cajaBotanasAntojitos.hide();
cajaComidas.hide();
cajaBebidas.hide();
cajaEnsaladas.toggle(1000);
});
botanasAntojitos.click(function() {
cajaDesayunos.hide();
cajaEnsaladas.hide();
cajaPostre.hide();
cajaComidas.hide();
cajaBebidas.hide();
cajaBotanasAntojitos.toggle(1000);
});
comidas.click(function() {
cajaDesayunos.hide();
cajaEnsaladas.hide();
cajaPostre.hide();
cajaBotanasAntojitos.hide();
cajaBebidas.hide();
cajaComidas.toggle(1000);
});
bebidas.click(function() {
cajaDesayunos.hide();
cajaEnsaladas.hide();
cajaPostre.hide();
cajaBotanasAntojitos.hide();
cajaComidas.hide();
cajaBebidas.toggle(1000);
});
});
window.onload = function() {
$("#load").fadeOut();
$("body").removeClass("hidden");
};
|
f943513da2ac58d60f1a49572301b85ed8b50c19
|
[
"JavaScript"
] | 1
|
JavaScript
|
robinsonGA/restaurante-BLACEY
|
343240da1f3fd8acbbf0bf9812f10dfec66ff301
|
d677596bc27369537701d63b4d2b544e77361506
|
refs/heads/master
|
<repo_name>firedtoad/cpp-taskflow<file_sep>/taskflow/core/topology.hpp
#pragma once
#include "taskflow.hpp"
namespace tf {
// ----------------------------------------------------------------------------
// class: Topology
class Topology {
friend class Taskflow;
friend class Executor;
public:
template <typename P>
Topology(P&&);
private:
std::promise<void> _promise;
std::shared_future<void> _future {_promise.get_future().share()};
PassiveVector<Node*> _sources;
std::atomic<int> _num_sinks {0};
int _cached_num_sinks {0};
std::function<bool()> _pred {nullptr};
std::function<void()> _work {nullptr};
void _bind(Graph& g);
void _recover_num_sinks();
};
// Constructor
template <typename P>
inline Topology::Topology(P&& p):
_pred {std::forward<P>(p)} {
}
// Procedure: _bind
// Re-builds the source links and the sink number for this topology.
inline void Topology::_bind(Graph& g) {
_num_sinks = 0;
_sources.clear();
// scan each node in the graph and build up the links
for(auto& node : g) {
node._topology = this;
if(node.num_dependents() == 0) {
_sources.push_back(&node);
}
if(node.num_successors() == 0) {
_num_sinks++;
}
}
_cached_num_sinks = _num_sinks;
}
// Procedure: _recover_num_sinks
inline void Topology::_recover_num_sinks() {
_num_sinks = _cached_num_sinks;
}
} // end of namespace tf. ----------------------------------------------------
|
a6f3fc1b8321cc83292d27dcaf66fc306b438f04
|
[
"C++"
] | 1
|
C++
|
firedtoad/cpp-taskflow
|
c7abd3df617829e23c2ef5942e0c6b180c978d9a
|
d3fd9ed6487b9f43e365ef3e19f7abba64981970
|
refs/heads/master
|
<file_sep>package com.li.kong.mapper;
import com.li.kong.entity.User;
import java.util.List;
public interface UserMapper {
int save(User user);
User loadEmail(String email);
int updateInfo(User user);
int updatePassword(User user);
List<User> listUser();
int updateForbidden(User user);
User loadUser(Integer id);
}
<file_sep>package com.li.kong.mapper;
import com.li.kong.entity.Comment;
import java.util.List;
public interface CommentMapper {
int save(Comment comment);
List<Comment> findNote(String id);
Comment find(Integer id);
int update(Comment comment);
int deleteNote(String noteId);
int delete(int id);
}
<file_sep>package com.li.kong.service;
import com.li.kong.dao.NoteDao;
import com.li.kong.entity.Note;
import com.li.kong.exception.DaoException;
import java.util.List;
public class NoteService {
NoteDao nd = new NoteDao();
CommentService cs = new CommentService();
PhotosService ps = new PhotosService();
/**
* 保存文章
* @param note
* @return
*/
public Boolean save(Note note){
try {
note.setUpVote(0);
note.setDownVote(0);
nd.save(note);
return true;
}catch (Exception e){
throw new DaoException(""+e);
//return false;
}
}
/**
* 更新文章
* @param note
* @return
*/
public boolean update(Note note){
boolean isUpdate;
try{
isUpdate = nd.update(note);
}catch (Exception e){
throw new DaoException(""+e);
}
return isUpdate;
}
/**
* 根据id查询文章
* @param id
* @return
*/
public Note find(String id){
Note note;
try{
note = nd.find(id);
}catch (Exception e){
throw new DaoException(""+e);
}
return note;
}
/**
* 根据类型查询所有的文章
* @param categoryId
* @return
*/
public List<Note> findCategoryAll(Integer categoryId){
List<Note> list;
try{
list = nd.findCategoryIdAll(categoryId);
}catch (Exception e){
throw new DaoException(""+e);
}
return list;
}
/**
* 根据文章id删除文章
* @param id
* @return
*/
public boolean delete(String id){
try {
cs.delete(id);
ps.delete(id);
nd.delete(id);
}catch (Exception e){
throw new DaoException(""+e);
}
return true;
}
}
<file_sep>package com.li.kong.dao;
import com.li.kong.entity.User;
import com.li.kong.exception.DaoException;
import com.li.kong.mapper.UserMapper;
import com.li.kong.utils.DataSource;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class UserDao implements Dao<User,Integer> {
private SqlSession session ;
UserMapper mapper;
@Override
public Integer save(User o) throws DaoException{
int count;
try{
session = new DataSource().init();
mapper = session.getMapper(UserMapper.class);
count = mapper.save(o);
session.commit();
}catch (Exception e){
session.rollback();
throw new RuntimeException();
}
session.close();
return count;
}
@Override
public boolean delete(Integer id) throws DaoException {
return false;
}
@Override
public boolean update(User user) throws DaoException {
int count;
try{
session = new DataSource().init();
mapper = session.getMapper(UserMapper.class);
count = mapper.updateInfo(user);
session.commit();
}catch (Exception e){
session.rollback();
throw new RuntimeException(e);
}
session.close();
if(count>=1){
return true;
}else {
return false;
}
}
/**
* 修改密码
* @param user
* @return
* @throws DaoException
*/
public boolean updatePassword(User user) throws DaoException {
int count;
try{
session = new DataSource().init();
mapper = session.getMapper(UserMapper.class);
count = mapper.updatePassword(user);
session.commit();
}catch (Exception e){
session.rollback();
throw new RuntimeException(e);
}
session.close();
if(count>=1){
return true;
}else {
return false;
}
}
/**
* 修改用户状态,是否被禁用
* @param user
* @return
* @throws DaoException
*/
public boolean updateForbidden(User user) throws DaoException {
int count;
try{
session = new DataSource().init();
mapper = session.getMapper(UserMapper.class);
count = mapper.updateForbidden(user);
session.commit();
}catch (Exception e){
session.rollback();
throw new RuntimeException(e);
}
session.close();
if(count>=1){
return true;
}else {
return false;
}
}
@Override
public User find(Integer id) throws DaoException {
return null;
}
@Override
public User load(User user) throws DaoException {
return null;
}
/**
* 根据邮箱查询
* @param email 用户邮箱
* @return 返回用户信息
* @throws DaoException
*/
public User loadEmail(String email) throws DaoException{
User user;
try{
session = new DataSource().init();
mapper = session.getMapper(UserMapper.class);
user = mapper.loadEmail(email);
}catch (Exception e){
throw new RuntimeException(e);
}
session.close();
return user;
}
/**
* 根据用户id查询用户
* @param id
* @return
* @throws DaoException
*/
public User loadId(Integer id) throws DaoException{
User user;
try{
session = new DataSource().init();
mapper = session.getMapper(UserMapper.class);
user = mapper.loadUser(id);
}catch (Exception e){
throw new RuntimeException(e);
}
session.close();
return user;
}
@Override
public List<User> loadList(User user) throws DaoException {
return null;
}
@Override
public List<User> findAll() throws DaoException {
List<User> list;
try{
session = new DataSource().init();
mapper = session.getMapper(UserMapper.class);
list = mapper.listUser();
}catch (Exception e){
throw new RuntimeException(e);
}
session.close();
return list;
}
}
<file_sep>package com.li.kong.service;
import com.li.kong.dao.RoleDao;
import com.li.kong.dao.UserDao;
import com.li.kong.entity.Role;
import com.li.kong.entity.User;
import com.li.kong.exception.DaoException;
import com.li.kong.utils.MessageDigestType;
import com.li.kong.utils.StringHelper;
import java.util.ArrayList;
import java.util.List;
public class UserService {
UserDao userDao = new UserDao();
RoleDao rd = new RoleDao();
/**
* 保存用户
* @param user
* @return
*/
public Boolean save(User user){
String pass = StringHelper.encrypt( user.getPassword() , MessageDigestType.MD5, null );
user.setPassword(pass);
user.setForbidden("N");
try {
userDao.save(user);
return true;
}catch (Exception e){
// throw new DaoException(""+e);
return false;
}
}
/**
* 根据邮箱查询用户
* @param email 邮箱
* @return 返回用户
*/
public User loadEmail(String email){
try{
return userDao.loadEmail(email);
}catch (Exception e){
return null;
}
}
public boolean updateInfo(User user){
User user1;
try{
user1 = userDao.loadEmail(user.getEmail());
user1.setPetName(user.getPetName());
user1.setQq(user.getQq());
userDao.update(user1);
return true;
}catch (Exception e){
throw new DaoException("更新失败"+e);
}
}
/**
* 修改密码
* @param user 用户对象
* @return
*/
public boolean updatePassword(User user){
User user1;
try{
user1 = userDao.loadEmail(user.getEmail());
String pass = StringHelper.encrypt( user.getPassword() , MessageDigestType.MD5, null );
user1.setPassword(pass);
userDao.updatePassword(user1);
return true;
}catch (Exception e){
throw new DaoException("更新失败"+e);
}
}
/**
* 修改用户状态,是否被禁用
* @param user
* @return
*/
public boolean updateForbidden(User user){
User user1;
try{
user1 = userDao.loadEmail(user.getEmail());
user1.setForbidden(user.getForbidden());
userDao.updateForbidden(user1);
return true;
}catch (Exception e){
throw new DaoException("更新失败"+e);
}
}
/**
* 查询所有的用户
* @return
*/
public List<User> findAll(){
List<User> list;
List<User> list1 = new ArrayList();
try{
list = userDao.findAll();
for (User user:list){
Role role = rd.findId(user.getRoleId());
user.setRole(role);
list1.add(user);
}
return list1;
}catch (Exception e){
throw new DaoException("更新失败"+e);
}
}
}
<file_sep>package com.li.kong.service;
import com.li.kong.dao.InformationDao;
import com.li.kong.entity.Information;
import com.li.kong.exception.DaoException;
import java.util.Date;
import java.util.List;
public class InformationService {
InformationDao informationDao = new InformationDao();
/**
* 保存全部实时资讯
* @param information
* @return
*/
public int save(Information information){
Date date = new Date();
information.setDownVote(0);
information.setUpVote(0);
information.setInfoDate(date);
int count;
try{
count = informationDao.save(information);
return count;
}catch (Exception e){
throw new DaoException(""+e);
}
}
/**
* 查询全部实时资讯
* @return
*/
public List<Information> findAll(){
List<Information> list;
try {
list = informationDao.findAll();
}catch (Exception e){
throw new DaoException(""+e);
}
return list;
}
/**
* 删除实时资讯
* @param id
* @return
*/
public boolean deleteInfo(Integer id){
try {
informationDao.delete(id);
return true;
}catch (Exception e){
// throw new DaoException(""+e);
return false;
}
}
/**
* 更新实时资讯
* @param information
* @return
*/
public boolean update(Information information){
boolean isUpdate;
try{
isUpdate = informationDao.update(information);
}catch (Exception e){
throw new DaoException(""+e);
}
return isUpdate;
}
/**
* 根据查询实时资讯
* @param id
* @return
*/
public Information find(Integer id){
Information information;
try{
information = informationDao.find(id);
}catch (Exception e){
throw new DaoException(""+e);
}
return information;
}
}
<file_sep>
-- SET FOREIGN_KEY_CHECKS=0;
DROP DATABASE IF EXISTS `kong`;
-- 创建数据库
CREATE DATABASE `kong` CHARACTER SET UTF8 ;
-- 打开数据库
use kong ;
-- 1
drop table if exists t_role ;
-- 角色表
create table t_role (
id int primary key auto_increment comment '角色编号',
name varchar(255) comment '角色名称'
);
-- 临时数据
insert into t_role(id,name) VALUES (1,'管理员');
insert into t_role(id,name) VALUES (2,'会员');
-- 2
-- 用户表
DROP TABLE IF EXISTS t_user;
CREATE TABLE t_user(
id INT PRIMARY KEY AUTO_INCREMENT COMMENT '用户id',
email VARCHAR(50) NOT NULL UNIQUE COMMENT '用户邮箱,即登录名称,也作为账号',
password VARCHAR(32) NOT NULL COMMENT '<PASSWORD>',
pet_name VARCHAR(255) COMMENT '用户昵称',
qq VARCHAR(20) COMMENT '用户qq',
forbidden char(1) DEFAULT 'N' COMMENT '是否禁用',
role_id int COMMENT '用户角色id',
FOREIGN KEY (role_id) REFERENCES t_role(id)
);
-- 3
DROP TABLE IF EXISTS t_category;
-- 分类
CREATE TABLE t_category(
id int PRIMARY KEY AUTO_INCREMENT COMMENT '分类id',
name VARCHAR(150) COMMENT '类型名称'
);
INSERT INTO t_category VALUES(1,'旅游景点');
INSERT INTO t_category VALUES(2,'风味小吃');
INSERT INTO t_category VALUES(3,'民族风情');
INSERT INTO t_category VALUES(4,'历史文化');
INSERT INTO t_category VALUES(5,'古茶产品');
INSERT INTO t_category VALUES(6,'古茶文化');
INSERT INTO t_category VALUES(7,'本地特产');
-- 4
DROP TABLE IF EXISTS t_note;
-- 文章表
CREATE TABLE t_note(
id VARCHAR(32) PRIMARY KEY COMMENT '简介id',
title VARCHAR(255) NOT NULL COMMENT '标题',
content TEXT COMMENT '内容',
up_vote int default 0 comment '赞成' ,
down_vote int default 0 comment '反对' ,
category_id int COMMENT '分类id',
FOREIGN KEY (category_id) REFERENCES t_category(id)
);
-- 5
DROP TABLE IF EXISTS t_images;
-- 图片表
CREATE TABLE t_images(
id VARCHAR(32) PRIMARY KEY COMMENT '图片id',
title VARCHAR(255) NOT NULL COMMENT '标题',
image_url TEXT COMMENT '图片路径',
note_id VARCHAR(32) COMMENT '简介id',
FOREIGN KEY (note_id) REFERENCES t_note(id)
);
-- 6
DROP TABLE IF EXISTS t_comment;
-- 评论表
CREATE TABLE t_comment(
id INT PRIMARY KEY AUTO_INCREMENT COMMENT '评论id',
content VARCHAR(1024) COMMENT '评论的内容',
user_id int COMMENT '用户id',
note_id VARCHAR(32) COMMENT '简介id',
comment_date DATE COMMENT '评论时间',
up_vote int default 0 COMMENT '赞成' ,
down_vote int default 0 COMMENT '反对' ,
FOREIGN KEY (user_id) REFERENCES t_user(id),
FOREIGN KEY (note_id) REFERENCES t_note(id)
);
-- 7
DROP TABLE IF EXISTS t_information;
-- 时日资讯表
CREATE TABLE t_information(
id int PRIMARY KEY AUTO_INCREMENT COMMENT 'id',
title VARCHAR(255) NOT NULL COMMENT '标题',
content TEXT COMMENT '内容',
up_vote int default 0 COMMENT '赞成' ,
down_vote int default 0 COMMENT '反对' ,
info_data DATE COMMENT '实时资讯时间'
);
<file_sep>package com.li.kong.mapper;
import com.li.kong.entity.Information;
import java.util.List;
public interface InformationMapper {
int save(Information information);
List<Information> findAll();
Information find(Integer id);
int delete(Integer id);
int update(Information information);
}
<file_sep>package com.li.kong.dao;
import com.li.kong.entity.Information;
import com.li.kong.exception.DaoException;
import com.li.kong.mapper.InformationMapper;
import com.li.kong.utils.DataSource;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class InformationDao implements Dao<Information,Integer> {
private SqlSession session ;
InformationMapper mapper;
@Override
public Integer save(Information o) throws DaoException {
int count;
try{
session = new DataSource().init();
mapper = session.getMapper(InformationMapper.class);
count = mapper.save(o);
session.commit();
}catch (Exception e){
throw new RuntimeException(e);
}
return count;
}
@Override
public boolean delete(Integer id) throws DaoException {
int count;
try {
session = new DataSource().init();
mapper = session.getMapper(InformationMapper.class);
count = mapper.delete(id);
session.commit();
}catch (Exception e){
throw new RuntimeException(e);
}
if(count>=1){
return true;
}else {
return false;
}
}
@Override
public boolean update(Information information) throws DaoException {
int count;
try {
session = new DataSource().init();
mapper = session.getMapper(InformationMapper.class);
count = mapper.update(information);
session.commit();
}catch (Exception e){
session.rollback();
throw new RuntimeException(e);
}
if(count>=1){
return true;
}else {
return false;
}
}
@Override
public Information find(Integer id) throws DaoException {
Information information;
try{
session = new DataSource().init();
mapper = session.getMapper(InformationMapper.class);
information = mapper.find(id);
}catch (Exception e){
throw new RuntimeException(e);
}
return information;
}
@Override
public Information load(Information information) throws DaoException {
return null;
}
@Override
public List<Information> loadList(Information information) throws DaoException {
return null;
}
@Override
public List<Information> findAll() throws DaoException {
List<Information> list;
try{
session = new DataSource().init();
mapper = session.getMapper(InformationMapper.class);
list = mapper.findAll();
}catch (Exception e){
throw new RuntimeException(e);
}
return list;
}
}
<file_sep>package com.li.kong.dao;
import com.li.kong.entity.Comment;
import com.li.kong.exception.DaoException;
import com.li.kong.mapper.CommentMapper;
import com.li.kong.utils.DataSource;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class CommentDao implements Dao<Comment,Integer> {
private SqlSession session ;
private CommentMapper mapper;
@Override
public Integer save(Comment o) throws DaoException {
int count;
try{
session = new DataSource().init();
mapper = session.getMapper(CommentMapper.class);
count = mapper.save(o);
session.commit();
}catch (Exception e){
session.rollback();
throw new RuntimeException(e);
}
session.close();
return count;
}
@Override
public boolean delete(Integer id) throws DaoException {
int count;
try {
session = new DataSource().init();
mapper = session.getMapper(CommentMapper.class);
count = mapper.delete(id);
session.commit();
}catch (Exception e){
throw new RuntimeException(e);
}
if(count>=1){
return true;
}else {
return false;
}
}
/**
* 根据文章id删除评论
* @param id
* @return
* @throws DaoException
*/
public boolean deleteNote(String id) throws DaoException{
int count;
try {
session = new DataSource().init();
mapper = session.getMapper(CommentMapper.class);
count = mapper.deleteNote(id);
session.commit();
}catch (Exception e){
throw new RuntimeException(e);
}
if(count>=1){
return true;
}else {
return false;
}
}
@Override
public boolean update(Comment comment) throws DaoException {
int count;
try {
session = new DataSource().init();
mapper = session.getMapper(CommentMapper.class);
count = mapper.update(comment);
session.commit();
}catch (Exception e){
session.rollback();
throw new RuntimeException(e);
}
if(count>=1){
return true;
}else {
return false;
}
}
@Override
public Comment find(Integer id) throws DaoException {
Comment comment;
try{
session = new DataSource().init();
mapper = session.getMapper(CommentMapper.class);
comment = mapper.find(id);
}catch (Exception e){
throw new RuntimeException(e);
}
session.close();
return comment;
}
@Override
public Comment load(Comment comment) throws DaoException {
return null;
}
@Override
public List<Comment> loadList(Comment comment) throws DaoException {
return null;
}
@Override
public List<Comment> findAll() throws DaoException {
return null;
}
public List<Comment> findNote(String id) throws DaoException {
List<Comment> list;
try{
session = new DataSource().init();
mapper = session.getMapper(CommentMapper.class);
list = mapper.findNote(id);
}catch (Exception e){
throw new RuntimeException(e);
}
session.close();
return list;
}
}
<file_sep>package com.li.kong.mapper;
import com.li.kong.entity.Role;
public interface RoleMapper {
Role find(String name);
Role findId(int id);
}
<file_sep>package com.li.kong.dao;
import com.li.kong.entity.Note;
import com.li.kong.exception.DaoException;
import com.li.kong.mapper.NoteMapper;
import com.li.kong.utils.DataSource;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class NoteDao implements Dao<Note,Integer> {
private SqlSession session ;
NoteMapper noteMapper;
@Override
public Integer save(Note o) throws DaoException {
int count;
try{
session = new DataSource().init();
noteMapper = session.getMapper(NoteMapper.class);
count = noteMapper.save(o);
session.commit();
}catch (Exception e){
session.rollback();
throw new RuntimeException();
}
session.close();
return count;
}
@Override
public boolean delete(Integer id) throws DaoException {
return false;
}
/**
* 根据文章ID删除文章
* @param id
* @return
* @throws DaoException
*/
public boolean delete(String id) throws DaoException {
int count;
try {
session = new DataSource().init();
noteMapper = session.getMapper(NoteMapper.class);
count = noteMapper.delete(id);
session.commit();
}catch (Exception e){
throw new RuntimeException(e);
}
if(count>=1){
return true;
}else {
return false;
}
}
@Override
public boolean update(Note note) throws DaoException {
int count;
try {
session = new DataSource().init();
noteMapper = session.getMapper(NoteMapper.class);
count = noteMapper.update(note);
session.commit();
}catch (Exception e){
session.rollback();
throw new RuntimeException(e);
}
if(count>=1){
return true;
}else {
return false;
}
}
@Override
public Note find(Integer id) throws DaoException {
return null;
}
public Note find(String id) throws DaoException {
Note note;
try{
session = new DataSource().init();
noteMapper = session.getMapper(NoteMapper.class);
note = noteMapper.find(id);
}catch (Exception e){
throw new RuntimeException();
}
session.close();
return note;
}
@Override
public Note load(Note note) throws DaoException {
return null;
}
@Override
public List<Note> loadList(Note note) throws DaoException {
return null;
}
@Override
public List<Note> findAll() throws DaoException {
/*List<Note> list;
try{
session = new DataSource().init();
noteMapper = session.getMapper(NoteMapper.class);
list = noteMapper.findAll();
}catch (Exception e){
throw new RuntimeException();
}
session.close();*/
return null;
}
public List<Note> findCategoryIdAll(Integer categoryId) throws DaoException {
List<Note> list;
try{
session = new DataSource().init();
noteMapper = session.getMapper(NoteMapper.class);
list = noteMapper.findAll(categoryId);
}catch (Exception e){
throw new RuntimeException();
}
session.close();
return list;
}
}
<file_sep>package com.li.kong.dao;
import com.li.kong.entity.Category;
import com.li.kong.exception.DaoException;
import com.li.kong.mapper.CategoryMapper;
import com.li.kong.utils.DataSource;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class CategoryDao implements Dao<Category, Integer> {
private SqlSession session;
private CategoryMapper mapper;
@Override
public Integer save(Category o) throws DaoException {
return null;
}
@Override
public boolean delete(Integer id) throws DaoException {
return false;
}
@Override
public boolean update(Category category) throws DaoException {
return false;
}
@Override
public Category find(Integer id) throws DaoException {
return null;
}
/**
* 根据类型名称查找类型
* @param name
* @return
* @throws DaoException
*/
public Category findString(String name) throws DaoException {
Category category;
try {
session = new DataSource().init();
mapper = session.getMapper(CategoryMapper.class);
category = mapper.find(name);
} catch (Exception e) {
throw new RuntimeException(e);
}
session.close();
return category;
}
@Override
public Category load(Category category) throws DaoException {
return null;
}
@Override
public List<Category> loadList(Category category) throws DaoException {
return null;
}
@Override
public List<Category> findAll() throws DaoException {
List<Category> list;
try {
session = new DataSource().init();
mapper = session.getMapper(CategoryMapper.class);
list = mapper.findAll();
} catch (Exception e) {
throw new RuntimeException(e);
}
session.close();
return list;
}
}
<file_sep>package com.li.kong.entity;
import java.io.Serializable;
import java.util.Date;
/**
* 实时资讯实体类
*/
public class Information implements Serializable {
private Integer id;
private String title;
private String content;
private Integer upVote;
private Integer downVote;
private Date infoDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getUpVote() {
return upVote;
}
public void setUpVote(Integer upVote) {
this.upVote = upVote;
}
public Integer getDownVote() {
return downVote;
}
public void setDownVote(Integer downVote) {
this.downVote = downVote;
}
public Date getInfoDate() {
return infoDate;
}
public void setInfoDate(Date infoDate) {
this.infoDate = infoDate;
}
}
<file_sep>package com.li.kong.entity;
import java.io.Serializable;
import java.util.List;
/**
* 用户实例
*/
public class User implements Serializable {
private Integer id;
private String email;
private String password;
private String petName;
private String qq;
private String forbidden;
private Integer roleId;
private Role role;//一对一,当前用户的类型
private List<Comment> commentList;//一对多,一个用户有多条评论
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPetName() {
return petName;
}
public void setPetName(String petName) {
this.petName = petName;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getForbidden() {
return forbidden;
}
public void setForbidden(String forbidden) {
this.forbidden = forbidden;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public List<Comment> getCommentList() {
return commentList;
}
public void setCommentList(List<Comment> commentList) {
this.commentList = commentList;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
}
<file_sep>spring.mail.host=smtp.qq.com
spring.mail.username=<EMAIL>
spring.mail.password=<PASSWORD>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
<file_sep>package com.li.kong.web;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.UUID;
@RestController
@EnableAutoConfiguration
@RequestMapping("/upload")
public class Upload {
String uploadDir = "F:/E";
@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
public String uploadImage(@RequestParam(value = "file") MultipartFile[] files){
StringBuffer result = new StringBuffer();
try {
for (int i = 0; i < files.length; i++) {
if (files[i] != null) {
//调用上传方法
String fileName = executeUpload(files[i]);
result.append(fileName+";");
}
}
} catch (Exception e) {
System.out.println(e);
}
return result.toString();
}
private String executeUpload(MultipartFile file) throws Exception{
//文件后缀名
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//上传文件名
String fileName = UUID.randomUUID()+suffix;
//服务端保存的文件对象
File serverFile = new File(uploadDir+suffix);
// 检测是否存在目录
if (!serverFile.getParentFile().exists()) {
serverFile.getParentFile().mkdirs();
}
//将上传的文件写入到服务器端文件内
file.transferTo(serverFile);
return null;
}
}
<file_sep>
### 使用的知识点
>1. 使用element UI做前端UI界面
>2. 使用spring boot做后台框架
>3. 前端使用vue.js,后端使用Java
>4. 前端使用到的只是有javaScript、HTML、sass、vuejs、vue-cli。后端使用到的语言Java、sql,使用到的
框架有spring boot、mybatis。
### 前后端分离开发
* 传统的web开发模式,后端一定程度上依赖与前端页面的开发,而前端一定程度的依赖后端的数据接口的开发。
整个开发过程中部分阶段处于串行状态。就是前端和后端处于同一项目下。而前后端分离的核心思路就是打破这种串行,
使得前端与后端能够并行开发,将前端和后端分离,是前端单独使用一个项目目录,并基于nodejs开启一个服务,开发时可以单独运行。
后端将前端分离出来,不依赖于前端界面,只要编写好前端请求接口就可以,无需前端页面。前端与后端通过接口进行交互,其他代码
互不干预。前端页面数据获取是前端发送一个请求到后端,后端返回数据,前端接收到数据后对数据进行渲染,显示在页面上。
* 此项目中异步请求数据通过axios向后后端发送请求。如向后端发送一个请求,获取所有的实时资讯
```javascript
this.$axios.post('/local/manager/findAllInfo').then(function (response) {
self.info = response.data
self.infoLength = response.data.length
}).catch(function (error) {
self.$Message.error('服务器异常')
});
```
以上代码中“/local/manager/findAllInfo”是请求后端的接口,response是后端返回的数据。后端在kong项目中web文件下的Manager.java
中有此段代码
```
/**
* 获取所有的实时资讯
*
* @return
*/
public @RequestMapping("findAllInfo")
List<Information> findAllInfo() {
List<Information> list;
try {
list = infoService.findAll();
return list;
} catch (Exception e) {
return null;
}
}
```
此段代码就是后端从数据库中获取所有的实时资讯,此时前后端接口已经打通。
### 前端项目
<file_sep>package com.li.kong.entity;
import java.io.Serializable;
import java.util.List;
/**
* 分类实体类
*/
public class Category implements Serializable {
private Integer id;
private String name;
private List<Note> noteList;//多对一,一个类型对应多篇文字
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Note> getNoteList() {
return noteList;
}
public void setNoteList(List<Note> noteList) {
this.noteList = noteList;
}
}
|
d4b3807f4eb0dccf4f85fe0b8cf6c2eaaa1bae92
|
[
"Markdown",
"Java",
"SQL",
"INI"
] | 19
|
Java
|
Romenluo/kong
|
af79aecb9fc969eff1222520003b6871b0676654
|
3326f7dacee449ac3df2c183574f82ee0c983eac
|
refs/heads/master
|
<repo_name>superraylin/209HCI-TinyKeyboard<file_sep>/keyboard - Copy - Copy.js
var tapped = false;
var double_tapped = false;
//for 2touch
let two_touch = false;
let touch_counts = 0;
/******load event listener to each keyboar_key*******/
function Init(){
document.addEventListener('contextmenu', event => event.preventDefault());
["pointerdown", "pointerup"].forEach(function(e) {
document.getElementById("button_abc").addEventListener(e, PointerHandlerABC);
document.getElementById("button_def").addEventListener(e, PointerHandlerDEF);
document.getElementById("button_ghi").addEventListener(e, PointerHandlerGHI);
document.getElementById("button_jkl").addEventListener(e, PointerHandlerJKL);
document.getElementById("button_mno").addEventListener(e, PointerHandlerMN);
document.getElementById("button_pqr").addEventListener(e, PointerHandlerOPQ);
document.getElementById("button_stu").addEventListener(e, PointerHandlerRST);
document.getElementById("button_vwx").addEventListener(e, PointerHandlerUVW);
document.getElementById("button_yz").addEventListener(e, PointerHandlerXYZ);
});
}
/*****Word library******/
const tags = [
'my',
'watch',
'fell',
'in',
'the',
'water',
'prevailing',
'wind',
'from',
'the',
'east',
'never',
'too',
'rich',
'and',
'never',
'too',
'thin',
'breathing',
'is',
'difficult',
'i',
'can',
'see',
'the',
'rings',
'on',
'saturn',
'physics',
'and',
'chemistry',
'are',
'hard',
'my',
'bank',
'account',
'is',
'overdrawn',
'elections',
'bring',
'out',
'the',
'best',
'we',
'are',
'having',
'spaghetti',
'time',
'to',
'go',
'shopping',
'a',
'problem',
'with',
'the',
'engine',
'elephants',
'are',
'afraid',
'of',
'mice',
'my',
'favorite',
'place',
'to',
'visit',
'three',
'two',
'one',
'zero',
'blast',
'off',
'my',
'favorite',
'subject',
'is',
'psychology',
'circumstances',
'are',
'unacceptable',
'watch',
'out',
'for',
'low',
'flying',
'objects',
'if',
'at',
'first',
'you',
'do',
'not',
'succeed',
'please',
'provide',
'your',
'date',
'of',
'birth',
'we',
'run',
'the',
'risk',
'of',
'failure',
'prayer',
'in',
'schools',
'offends',
'some',
'he',
'is',
'just',
'like',
'everyone',
'else',
'great',
'disturbance',
'in',
'the',
'force',
'love',
'means',
'many',
'things',
'you',
'must',
'be',
'getting',
'old',
'the',
'world',
'is',
'a',
'stage',
'can',
'i',
'skate',
'with',
'sister',
'today',
'neither',
'a',
'borrower',
'nor',
'a',
'lender',
'be',
'one',
'heck',
'of',
'a',
'question',
'question',
'that',
'must',
'be',
'answered',
'beware',
'the',
'ides',
'of',
'march',
'double',
'double',
'toil',
'and',
'trouble',
'the',
'power',
'of',
'denial',
'i',
'agree',
'with',
'you',
'do',
'not',
'say',
'anything',
'play',
'it',
'again',
'sam',
'the',
'force',
'is',
'with',
'you',
'you',
'are',
'not',
'a',
'jedi',
'yet',
'an',
'offer',
'you',
'cannot',
'refuse',
'are',
'you',
'talking',
'to',
'me',
'yes',
'you',
'are',
'very',
'smart',
'all',
'work',
'and',
'no',
'play',
'hair',
'gel',
'is',
'very',
'greasy',
'valium',
'in',
'the',
'economy',
'size',
'the',
'facts',
'get',
'in',
'the',
'way',
'the',
'dreamers',
'of',
'dreams',
'did',
'you',
'have',
'a',
'good',
'time',
'space',
'is',
'a',
'high',
'priority',
'you',
'are',
'a',
'wonderful',
'example',
'do',
'not',
'squander',
'your',
'time',
'do',
'not',
'drink',
'too',
'much',
'take',
'a',
'coffee',
'break',
'popularity',
'is',
'desired',
'by',
'all',
'the',
'music',
'is',
'better',
'than',
'it',
'sounds',
'starlight',
'and',
'dewdrop',
'the',
'living',
'is',
'easy',
'fish',
'are',
'jumping',
'the',
'cotton',
'is',
'high',
'drove',
'my',
'chevy',
'to',
'the',
'levee',
'but',
'the',
'levee',
'was',
'dry',
'i',
'took',
'the',
'rover',
'from',
'the',
'shop',
'movie',
'about',
'a',
'nutty',
'professor',
'come',
'and',
'see',
'our',
'new',
'car',
'coming',
'up',
'with',
'killer',
'sound',
'bites',
'i',
'am',
'going',
'to',
'a',
'music',
'lesson',
'the',
'opposing',
'team',
'is',
'over',
'there',
'soon',
'we',
'will',
'return',
'from',
'the',
'city',
'i',
'am',
'wearing',
'a',
'tie',
'and',
'a',
'jacket',
'the',
'quick',
'brown',
'fox',
'jumped',
'all',
'together',
'in',
'one',
'big',
'pile',
'wear',
'a',
'crown',
'with',
'many',
'jewels',
'there',
'will',
'be',
'some',
'fog',
'tonight',
'i',
'am',
'allergic',
'to',
'bees',
'and',
'peanuts',
'he',
'is',
'still',
'on',
'our',
'team',
'the',
'dow',
'jones',
'index',
'has',
'risen',
'my',
'preferred',
'treat',
'is',
'chocolate',
'the',
'king',
'sends',
'you',
'to',
'the',
'tower',
'we',
'are',
'subjects',
'and',
'must',
'obey',
'mom',
'made',
'her',
'a',
'turtleneck',
'goldilocks',
'and',
'the',
'three',
'bears',
'we',
'went',
'grocery',
'shopping',
'the',
'assignment',
'is',
'due',
'today',
'what',
'you',
'see',
'is',
'what',
'you',
'get',
'for',
'your',
'information',
'only',
'a',
'quarter',
'of',
'a',
'century',
'the',
'store',
'will',
'close',
'at',
'ten',
'head',
'shoulders',
'knees',
'and',
'toes',
'vanilla',
'flavored',
'ice',
'cream',
'frequently',
'asked',
'questions',
'round',
'robin',
'scheduling',
'information',
'super',
'highway',
'my',
'favorite',
'web',
'browser',
'the',
'laser',
'printer',
'is',
'jammed',
'all',
'good',
'boys',
'deserve',
'fudge',
'the',
'second',
'largest',
'country',
'call',
'for',
'more',
'details',
'just',
'in',
'time',
'for',
'the',
'party',
'have',
'a',
'good',
'weekend',
'video',
'camera',
'with',
'a',
'zoom',
'lens',
'what',
'a',
'monkey',
'sees',
'a',
'monkey',
'will',
'do',
'that',
'is',
'very',
'unfortunate',
'the',
'back',
'yard',
'of',
'our',
'house',
'this',
'is',
'a',
'very',
'good',
'idea',
'reading',
'week',
'is',
'just',
'about',
'here',
'our',
'fax',
'number',
'has',
'changed',
'thank',
'you',
'for',
'your',
'help',
'no',
'exchange',
'without',
'a',
'bill',
'the',
'early',
'bird',
'gets',
'the',
'worm',
'buckle',
'up',
'for',
'safety',
'this',
'is',
'too',
'much',
'to',
'handle',
'protect',
'your',
'environment',
'world',
'population',
'is',
'growing',
'the',
'library',
'is',
'closed',
'today',
'mary',
'had',
'a',
'little',
'lamb',
'teaching',
'services',
'will',
'help',
'we',
'accept',
'personal',
'checks',
'this',
'is',
'a',
'non',
'profit',
'organization',
'user',
'friendly',
'interface',
'healthy',
'food',
'is',
'good',
'for',
'you',
'hands',
'on',
'experience',
'with',
'a',
'job',
'this',
'watch',
'is',
'too',
'expensive',
'the',
'postal',
'service',
'is',
'very',
'slow',
'communicate',
'through',
'email',
'the',
'capital',
'of',
'our',
'nation',
'travel',
'at',
'the',
'speed',
'of',
'light',
'i',
'do',
'not',
'fully',
'agree',
'with',
'you',
'gas',
'bills',
'are',
'sent',
'monthly',
'earth',
'quakes',
'are',
'predictable',
'life',
'is',
'but',
'a',
'dream',
'take',
'it',
'to',
'the',
'recycling',
'depot',
'sent',
'this',
'by',
'registered',
'mail',
'fall',
'is',
'my',
'favorite',
'season',
'a',
'fox',
'is',
'a',
'very',
'smart',
'animal',
'the',
'kids',
'are',
'very',
'excited',
'parking',
'lot',
'is',
'full',
'of',
'trucks',
'my',
'bike',
'has',
'a',
'flat',
'tire',
'do',
'not',
'walk',
'too',
'quickly',
'a',
'duck',
'quacks',
'to',
'ask',
'for',
'food',
'limited',
'warranty',
'of',
'two',
'years',
'the',
'four',
'seasons',
'will',
'come',
'the',
'sun',
'rises',
'in',
'the',
'east',
'it',
'is',
'very',
'windy',
'today',
'do',
'not',
'worry',
'about',
'this',
'dashing',
'through',
'the',
'snow',
'want',
'to',
'join',
'us',
'for',
'lunch',
'stay',
'away',
'from',
'strangers',
'accompanied',
'by',
'an',
'adult',
'see',
'you',
'later',
'alligator',
'make',
'my',
'day',
'you',
'sucker',
'i',
'can',
'play',
'much',
'better',
'now',
'she',
'wears',
'too',
'much',
'makeup',
'my',
'bare',
'face',
'in',
'the',
'wind',
'batman',
'wears',
'a',
'cape',
'i',
'hate',
'baking',
'pies',
'lydia',
'wants',
'to',
'go',
'home',
'win',
'first',
'prize',
'in',
'the',
'contest',
'freud',
'wrote',
'of',
'the',
'ego',
'i',
'do',
'not',
'care',
'if',
'you',
'do',
'that',
'always',
'cover',
'all',
'the',
'bases',
'nobody',
'cares',
'anymore',
'can',
'we',
'play',
'cards',
'tonight',
'get',
'rid',
'of',
'that',
'immediately',
'i',
'watched',
'blazing',
'saddles',
'the',
'sum',
'of',
'the',
'parts',
'they',
'love',
'to',
'yap',
'about',
'nothing',
'peek',
'out',
'the',
'window',
'be',
'home',
'before',
'midnight',
'he',
'played',
'a',
'pimp',
'in',
'that',
'movie',
'i',
'skimmed',
'through',
'your',
'proposal',
'he',
'was',
'wearing',
'a',
'sweatshirt',
'no',
'more',
'war',
'no',
'more',
'bloodshed',
'toss',
'the',
'ball',
'around',
'i',
'will',
'meet',
'you',
'at',
'noon',
'i',
'want',
'to',
'hold',
'your',
'hand',
'the',
'children',
'are',
'playing',
'superman',
'never',
'wore',
'a',
'mask',
'i',
'listen',
'to',
'the',
'tape',
'everyday',
'he',
'is',
'shouting',
'loudly',
'correct',
'your',
'diction',
'immediately',
'seasoned',
'golfers',
'love',
'the',
'game',
'he',
'cooled',
'off',
'after',
'she',
'left',
'my',
'dog',
'sheds',
'his',
'hair',
'join',
'us',
'on',
'the',
'patio',
'these',
'cookies',
'are',
'so',
'amazing',
'i',
'can',
'still',
'feel',
'your',
'presence',
'the',
'dog',
'will',
'bite',
'you',
'a',
'most',
'ridiculous',
'thing',
'where',
'did',
'you',
'get',
'that',
'tie',
'what',
'a',
'lovely',
'red',
'jacket',
'do',
'you',
'like',
'to',
'shop',
'on',
'sunday',
'i',
'spilled',
'coffee',
'on',
'the',
'carpet',
'the',
'largest',
'of',
'the',
'five',
'oceans',
'shall',
'we',
'play',
'a',
'round',
'of',
'cards',
'olympic',
'athletes',
'use',
'drugs',
'my',
'mother',
'makes',
'good',
'cookies',
'do',
'a',
'good',
'deed',
'to',
'someone',
'quick',
'there',
'is',
'someone',
'knocking',
'flashing',
'red',
'light',
'means',
'stop',
'sprawling',
'subdivisions',
'are',
'bad',
'where',
'did',
'i',
'leave',
'my',
'glasses',
'on',
'the',
'way',
'to',
'the',
'cottage',
'a',
'lot',
'of',
'chlorine',
'in',
'the',
'water',
'do',
'not',
'drink',
'the',
'water',
'my',
'car',
'always',
'breaks',
'in',
'the',
'winter',
'santa',
'claus',
'got',
'stuck',
'public',
'transit',
'is',
'much',
'faster',
'zero',
'in',
'on',
'the',
'facts',
'make',
'up',
'a',
'few',
'more',
'phrases',
'my',
'fingers',
'are',
'very',
'cold',
'rain',
'rain',
'go',
'away',
'bad',
'for',
'the',
'environment',
'universities',
'are',
'too',
'expensive',
'the',
'price',
'of',
'gas',
'is',
'high',
'the',
'winner',
'of',
'the',
'race',
'we',
'drive',
'on',
'parkways',
'we',
'park',
'in',
'driveways',
'go',
'out',
'for',
'some',
'pizza',
'and',
'beer',
'effort',
'is',
'what',
'it',
'will',
'take',
'where',
'can',
'my',
'little',
'dog',
'be',
'if',
'you',
'were',
'not',
'so',
'stupid',
'not',
'quite',
'so',
'smart',
'as',
'you',
'think',
'do',
'you',
'like',
'to',
'go',
'camping',
'this',
'person',
'is',
'a',
'disaster',
'the',
'imagination',
'of',
'the',
'nation',
'universally',
'understood',
'to',
'be',
'wrong',
'listen',
'to',
'five',
'hours',
'of',
'opera',
'an',
'occasional',
'taste',
'of',
'chocolate',
'victims',
'deserve',
'more',
'redress',
'the',
'protesters',
'blocked',
'all',
'traffic',
'the',
'acceptance',
'speech',
'was',
'boring',
'work',
'hard',
'to',
'reach',
'the',
'summit',
'a',
'little',
'encouragement',
'is',
'needed',
'stiff',
'penalty',
'for',
'staying',
'out',
'late',
'the',
'pen',
'is',
'mightier',
'than',
'the',
'sword',
'exceed',
'the',
'maximum',
'speed',
'limit',
'in',
'sharp',
'contrast',
'to',
'your',
'words',
'this',
'leather',
'jacket',
'is',
'too',
'warm',
'consequences',
'of',
'a',
'wrong',
'turn',
'this',
'mission',
'statement',
'is',
'baloney',
'you',
'will',
'loose',
'your',
'voice',
'every',
'apple',
'from',
'every',
'tree',
'are',
'you',
'sure',
'you',
'want',
'this',
'the',
'fourth',
'edition',
'was',
'better',
'this',
'system',
'of',
'taxation',
'beautiful',
'paintings',
'in',
'the',
'gallery',
'a',
'yard',
'is',
'almost',
'as',
'long',
'as',
'a',
'meter',
'we',
'missed',
'your',
'birthday',
'coalition',
'governments',
'never',
'work',
'destruction',
'of',
'the',
'rain',
'forest',
'i',
'like',
'to',
'play',
'tennis',
'acutely',
'aware',
'of',
'her',
'good',
'looks',
'you',
'want',
'to',
'eat',
'your',
'cake',
'machinery',
'is',
'too',
'complicated',
'a',
'glance',
'in',
'the',
'right',
'direction',
'i',
'just',
'cannot',
'figure',
'this',
'out',
'please',
'follow',
'the',
'guidelines',
'an',
'airport',
'is',
'a',
'very',
'busy',
'place',
'mystery',
'of',
'the',
'lost',
'lagoon',
'is',
'there',
'any',
'indication',
'of',
'this',
'the',
'chamber',
'makes',
'important',
'decisions',
'this',
'phenomenon',
'will',
'never',
'occur',
'obligations',
'must',
'be',
'met',
'first',
'valid',
'until',
'the',
'end',
'of',
'the',
'year',
'file',
'all',
'complaints',
'in',
'writing',
'tickets',
'are',
'very',
'expensive',
'a',
'picture',
'is',
'worth',
'many',
'words',
'this',
'camera',
'takes',
'nice',
'photographs',
'it',
'looks',
'like',
'a',
'shack',
'the',
'dog',
'buried',
'the',
'bone',
'the',
'daring',
'young',
'man',
'this',
'equation',
'is',
'too',
'complicated',
'express',
'delivery',
'is',
'very',
'fast',
'i',
'will',
'put',
'on',
'my',
'glasses',
'a',
'touchdown',
'in',
'the',
'last',
'minute',
'the',
'treasury',
'department',
'is',
'broke',
'a',
'good',
'response',
'to',
'the',
'question',
'well',
'connected',
'with',
'people',
'the',
'bathroom',
'is',
'good',
'for',
'reading',
'the',
'generation',
'gap',
'gets',
'wider',
'chemical',
'spill',
'took',
'forever',
'prepare',
'for',
'the',
'exam',
'in',
'advance',
'interesting',
'observation',
'was',
'made',
'bank',
'transaction',
'was',
'not',
'registered',
'your',
'etiquette',
'needs',
'some',
'work',
'we',
'better',
'investigate',
'this',
'stability',
'of',
'the',
'nation',
'house',
'with',
'new',
'electrical',
'panel',
'our',
'silver',
'anniversary',
'is',
'coming',
'the',
'presidential',
'suite',
'is',
'very',
'busy',
'the',
'punishment',
'should',
'fit',
'the',
'crime',
'sharp',
'cheese',
'keeps',
'the',
'mind',
'sharp',
'the',
'registration',
'period',
'is',
'over',
'you',
'have',
'my',
'sympathy',
'the',
'objective',
'of',
'the',
'exercise',
'historic',
'meeting',
'without',
'a',
'result',
'very',
'reluctant',
'to',
'enter',
'good',
'at',
'addition',
'and',
'subtraction',
'six',
'daughters',
'and',
'seven',
'sons',
'a',
'thoroughly',
'disgusting',
'thing',
'to',
'say',
'sign',
'the',
'withdrawal',
'slip',
'relations',
'are',
'very',
'strained',
'the',
'minimum',
'amount',
'of',
'time',
'a',
'very',
'traditional',
'way',
'to',
'dress',
'the',
'aspirations',
'of',
'a',
'nation',
'medieval',
'times',
'were',
'very',
'hard',
'a',
'security',
'force',
'of',
'eight',
'thousand',
'there',
'are',
'winners',
'and',
'losers',
'the',
'voters',
'turfed',
'him',
'out',
'pay',
'off',
'a',
'mortgage',
'for',
'a',
'house',
'the',
'collapse',
'of',
'the',
'roman',
'empire',
'did',
'you',
'see',
'that',
'spectacular',
'explosion',
'keep',
'receipts',
'for',
'all',
'your',
'expenses',
'the',
'assault',
'took',
'six',
'months',
'get',
'your',
'priorities',
'in',
'order',
'traveling',
'requires',
'a',
'lot',
'of',
'fuel',
'longer',
'than',
'a',
'football',
'field',
'a',
'good',
'joke',
'deserves',
'a',
'good',
'laugh',
'the',
'union',
'will',
'go',
'on',
'strike',
'never',
'mix',
'religion',
'and',
'politics',
'interactions',
'between',
'men',
'and',
'women',
'where',
'did',
'you',
'get',
'such',
'a',
'silly',
'idea',
'it',
'should',
'be',
'sunny',
'tomorrow',
'a',
'psychiatrist',
'will',
'help',
'you',
'you',
'should',
'visit',
'to',
'a',
'doctor',
'you',
'must',
'make',
'an',
'appointment',
'the',
'fax',
'machine',
'is',
'broken',
'players',
'must',
'know',
'all',
'the',
'rules',
'a',
'dog',
'is',
'the',
'best',
'friend',
'of',
'a',
'man',
'would',
'you',
'like',
'to',
'come',
'to',
'my',
'house',
'february',
'has',
'an',
'extra',
'day',
'do',
'not',
'feel',
'too',
'bad',
'about',
'it',
'this',
'library',
'has',
'many',
'books',
'construction',
'makes',
'traveling',
'difficult',
'he',
'called',
'seven',
'times',
'that',
'is',
'a',
'very',
'odd',
'question',
'a',
'feeling',
'of',
'complete',
'exasperation',
'we',
'must',
'redouble',
'our',
'efforts',
'no',
'kissing',
'in',
'the',
'library',
'that',
'agreement',
'is',
'rife',
'with',
'problems',
'vote',
'according',
'to',
'your',
'conscience',
'my',
'favourite',
'sport',
'is',
'racketball',
'sad',
'to',
'hear',
'that',
'news',
'the',
'gun',
'discharged',
'by',
'accident',
'one',
'of',
'the',
'poorest',
'nations',
'the',
'algorithm',
'is',
'too',
'complicated',
'your',
'presentation',
'was',
'inspiring',
'that',
'land',
'is',
'owned',
'by',
'the',
'government',
'burglars',
'never',
'leave',
'their',
'business',
'card',
'the',
'fire',
'blazed',
'all',
'weekend',
'if',
'diplomacy',
'does',
'not',
'work',
'please',
'keep',
'this',
'confidential',
'the',
'rationale',
'behind',
'the',
'decision',
'the',
'cat',
'has',
'a',
'pleasant',
'temperament',
'our',
'housekeeper',
'does',
'a',
'thorough',
'job',
'her',
'majesty',
'visited',
'our',
'country',
'handicapped',
'persons',
'need',
'consideration',
'these',
'barracks',
'are',
'big',
'enough',
'sing',
'the',
'gospel',
'and',
'the',
'blues',
'he',
'underwent',
'triple',
'bypass',
'surgery',
'the',
'hopes',
'of',
'a',
'new',
'organization',
'peering',
'through',
'a',
'small',
'hole',
'rapidly',
'running',
'short',
'on',
'words',
'it',
'is',
'difficult',
'to',
'concentrate',
'give',
'me',
'one',
'spoonful',
'of',
'coffee',
'two',
'or',
'three',
'cups',
'of',
'coffee',
'just',
'like',
'it',
'says',
'on',
'the',
'can',
'companies',
'announce',
'a',
'merger',
'electric',
'cars',
'need',
'big',
'fuel',
'cells',
'the',
'plug',
'does',
'not',
'fit',
'the',
'socket',
'drugs',
'should',
'be',
'avoided',
'the',
'most',
'beautiful',
'sunset',
'we',
'dine',
'out',
'on',
'the',
'weekends',
'get',
'aboard',
'the',
'ship',
'is',
'leaving',
'the',
'water',
'was',
'monitored',
'daily',
'he',
'watched',
'in',
'astonishment',
'a',
'big',
'scratch',
'on',
'the',
'tabletop',
'salesmen',
'must',
'make',
'their',
'monthly',
'quota',
'saving',
'that',
'child',
'was',
'an',
'heroic',
'effort',
'granite',
'is',
'the',
'hardest',
'of',
'all',
'rocks',
'bring',
'the',
'offenders',
'to',
'justice',
'every',
'saturday',
'he',
'folds',
'the',
'laundry',
'careless',
'driving',
'results',
'in',
'a',
'fine',
'microscopes',
'make',
'small',
'things',
'look',
'big',
'a',
'coupon',
'for',
'a',
'free',
'sample',
'fine',
'but',
'only',
'in',
'moderation',
'a',
'subject',
'one',
'can',
'really',
'enjoy',
'important',
'for',
'political',
'parties',
'that',
'sticker',
'needs',
'to',
'be',
'validated',
'the',
'fire',
'raged',
'for',
'an',
'entire',
'month',
'one',
'never',
'takes',
'too',
'many',
'precautions',
'we',
'have',
'enough',
'witnesses',
'labour',
'unions',
'know',
'how',
'to',
'organize',
'people',
'blow',
'their',
'horn',
'a',
'lot',
'a',
'correction',
'had',
'to',
'be',
'published',
'i',
'like',
'baroque',
'and',
'classical',
'music',
'the',
'proprietor',
'was',
'unavailable',
'be',
'discreet',
'about',
'your',
'meeting',
'meet',
'tomorrow',
'in',
'the',
'lavatory',
'suburbs',
'are',
'sprawling',
'up',
'everywhere',
'shivering',
'is',
'one',
'way',
'to',
'keep',
'warm',
'dolphins',
'leap',
'high',
'out',
'of',
'the',
'water',
'try',
'to',
'enjoy',
'your',
'maternity',
'leave',
'the',
'ventilation',
'system',
'is',
'broken',
'dinosaurs',
'have',
'been',
'extinct',
'for',
'ages',
'an',
'inefficient',
'way',
'to',
'heat',
'a',
'house',
'the',
'bus',
'was',
'very',
'crowded',
'an',
'injustice',
'is',
'committed',
'every',
'day',
'the',
'coronation',
'was',
'very',
'exciting',
'look',
'in',
'the',
'syllabus',
'for',
'the',
'course',
'rectangular',
'objects',
'have',
'four',
'sides',
'prescription',
'drugs',
'require',
'a',
'note',
'the',
'insulation',
'is',
'not',
'working',
'nothing',
'finer',
'than',
'discovering',
'a',
'treasure',
'our',
'life',
'expectancy',
'has',
'increased',
'the',
'cream',
'rises',
'to',
'the',
'top',
'the',
'high',
'waves',
'will',
'swamp',
'us',
'the',
'treasurer',
'must',
'balance',
'her',
'books',
'completely',
'sold',
'out',
'of',
'that',
'the',
'location',
'of',
'the',
'crime',
'the',
'chancellor',
'was',
'very',
'boring',
'the',
'accident',
'scene',
'is',
'a',
'shrine',
'for',
'fans',
'a',
'tumor',
'is',
'ok',
'provided',
'it',
'is',
'benign',
'please',
'take',
'a',
'bath',
'this',
'month',
'rent',
'is',
'paid',
'at',
'the',
'beginning',
'of',
'the',
'month',
'for',
'murder',
'you',
'get',
'a',
'long',
'prison',
'sentence',
'a',
'much',
'higher',
'risk',
'of',
'getting',
'cancer',
'quit',
'while',
'you',
'are',
'ahead',
'knee',
'bone',
'is',
'connected',
'to',
'the',
'thigh',
'bone',
'safe',
'to',
'walk',
'the',
'streets',
'in',
'the',
'evening',
'luckily',
'my',
'wallet',
'was',
'found',
'one',
'hour',
'is',
'allotted',
'for',
'questions',
'so',
'you',
'think',
'you',
'deserve',
'a',
'raise',
'they',
'watched',
'the',
'entire',
'movie',
'good',
'jobs',
'for',
'those',
'with',
'education',
'jumping',
'right',
'out',
'of',
'the',
'water',
'the',
'trains',
'are',
'always',
'late',
'sit',
'at',
'the',
'front',
'of',
'the',
'bus',
'do',
'you',
'prefer',
'a',
'window',
'seat',
'the',
'food',
'at',
'this',
'restaurant',
'canada',
'has',
'ten',
'provinces',
'the',
'elevator',
'door',
'appears',
'to',
'be',
'stuck',
'raindrops',
'keep',
'falling',
'on',
'my',
'head',
'spill',
'coffee',
'on',
'the',
'carpet',
'an',
'excellent',
'way',
'to',
'communicate',
'with',
'each',
'step',
'forward',
'faster',
'than',
'a',
'speeding',
'bullet',
'wishful',
'thinking',
'is',
'fine',
'nothing',
'wrong',
'with',
'his',
'style',
'arguing',
'with',
'the',
'boss',
'is',
'futile',
'taking',
'the',
'train',
'is',
'usually',
'faster',
'what',
'goes',
'up',
'must',
'come',
'down',
'be',
'persistent',
'to',
'win',
'a',
'strike',
'presidents',
'drive',
'expensive',
'cars',
'the',
'stock',
'exchange',
'dipped',
'why',
'do',
'you',
'ask',
'silly',
'questions',
'that',
'is',
'a',
'very',
'nasty',
'cut',
'what',
'to',
'do',
'when',
'the',
'oil',
'runs',
'dry',
'learn',
'to',
'walk',
'before',
'you',
'run',
'insurance',
'is',
'important',
'for',
'bad',
'drivers',
'traveling',
'to',
'conferences',
'is',
'fun',
'do',
'you',
'get',
'nervous',
'when',
'you',
'speak',
'pumping',
'helps',
'if',
'the',
'roads',
'are',
'slippery',
'parking',
'tickets',
'can',
'be',
'challenged',
'apartments',
'are',
'too',
'expensive',
'find',
'a',
'nearby',
'parking',
'spot',
'gun',
'powder',
'must',
'be',
'handled',
'with',
'care',
'just',
'what',
'the',
'doctor',
'ordered',
'a',
'rattle',
'snake',
'is',
'very',
'poisonous',
'weeping',
'willows',
'are',
'found',
'near',
'water',
'i',
'cannot',
'believe',
'i',
'ate',
'the',
'whole',
'thing',
'the',
'biggest',
'hamburger',
'i',
'have',
'ever',
'seen',
'gamblers',
'eventually',
'loose',
'their',
'shirts',
'exercise',
'is',
'good',
'for',
'the',
'mind',
'irregular',
'verbs',
'are',
'the',
'hardest',
'to',
'learn',
'they',
'might',
'find',
'your',
'comment',
'offensive',
'tell',
'a',
'lie',
'and',
'your',
'nose',
'will',
'grow',
'an',
'enlarged',
'nose',
'suggests',
'you',
'are',
'a',
'liar',
'lie',
'detector',
'tests',
'never',
'work',
'do',
'not',
'lie',
'in',
'court',
'or',
'else',
'most',
'judges',
'are',
'very',
'honest',
'only',
'an',
'idiot',
'would',
'lie',
'in',
'court',
'important',
'news',
'always',
'seems',
'to',
'be',
'late',
'please',
'try',
'to',
'be',
'home',
'before',
'midnight',
'if',
'you',
'come',
'home',
'late',
'the',
'doors',
'are',
'locked',
'dormitory',
'doors',
'are',
'locked',
'at',
'midnight',
'staying',
'up',
'all',
'night',
'is',
'a',
'bad',
'idea',
'you',
'are',
'a',
'capitalist',
'pig',
'motivational',
'seminars',
'make',
'me',
'sick',
'questioning',
'the',
'wisdom',
'of',
'the',
'courts',
'rejection',
'letters',
'are',
'discouraging',
'the',
'first',
'time',
'he',
'tried',
'to',
'swim',
'that',
'referendum',
'asked',
'a',
'silly',
'question',
'a',
'steep',
'learning',
'curve',
'in',
'riding',
'a',
'unicycle',
'a',
'good',
'stimulus',
'deserves',
'a',
'good',
'response',
'everybody',
'looses',
'in',
'custody',
'battles',
'put',
'garbage',
'in',
'an',
'abandoned',
'mine',
'employee',
'recruitment',
'takes',
'a',
'lot',
'of',
'effort',
'experience',
'is',
'hard',
'to',
'come',
'by',
'everyone',
'wants',
'to',
'win',
'the',
'lottery',
'the',
'picket',
'line',
'gives',
'me',
'the',
'chills'
];
/*************Word Autocomplete Algorithm begin*************/
/**
* @param {string[]} sentences
* Get the frequency of all elements(words) in sentences
* for each letter in Alphabet
*/
var AutocompleteSystem = function(sentences) {
this.searchHistory = {};
'abcdefghijklmnopqrstuvwxyz'.split('').forEach(char => {
this.searchHistory[char] = {};
});
for (let i = 0; i < sentences.length; i++) {
const sentence = sentences[i];
if (!this.searchHistory[sentence[0]][sentence]) {
this.searchHistory[sentence[0]][sentence] = 1;
} else {
this.searchHistory[sentence[0]][sentence] += 1;
}
}
};
/**
* @param {string} str
* @return {string[]} results
* Get the sorted results of elements (words) based on their frequency
*/
AutocompleteSystem.prototype.input = function(str) {
const firstChar = str[0];
const results = Object.keys(this.searchHistory[firstChar]).filter(sentence => {
return sentence.startsWith(str);
});
results.sort((a, b) => {
const aFreq = this.searchHistory[firstChar][a];
const bFreq = this.searchHistory[firstChar][b];
return aFreq !== bFreq ? bFreq - aFreq : (a > b ? 1 : -1);
});
return results;
};
var ac = new AutocompleteSystem(tags);
/*************Word Autocomplete Algorithm end*************/
/**************Pointer Handler begin******************/
function PointerHandlerABC(event){
event.preventDefault();
if (event.type === "pointerdown"){
if(!tapped){
tapped = setTimeout(function(){
hideall();
double_tapped = false;
showButtonText("a","b","c");
delete_swipe_down(event);
tapped = null;
}, 200);
} else {
double_tapped = true;
clearTimeout(tapped); //stop timeout callback
tapped=null;
let sentence = document.getElementById("txt_area").value;
let t_arr = sentence.split(' ');
t_ch = t_arr[t_arr.length - 1];
document.getElementById("txt_area").value -= t_ch;
document.getElementById("txt_area").value = sentence.substring(0,sentence.length - t_ch.length) +document.getElementById('sel1').innerText + " ";
document.getElementById('sel1').innerText = " ";
document.getElementById('sel2').innerText = " ";
document.getElementById('sel3').innerText = " ";
}
}
if(event.type ==="pointerup") {
setTimeout(restoreall,200);
touch_counts -=1;
}
if (event.type === "pointerup" && event.isPrimary){
if(!tapped && !double_tapped){
enter_text(event,"c","b","a","");
}
}
}
function PointerHandlerDEF(event){
event.preventDefault();
if (event.type === "pointerdown"){
hideall();
showButtonText("d","e","f");
delete_swipe_down(event);
}
if(event.type ==="pointerup") {
touch_counts -=1;
}
if (event.type === "pointerup"&& event.isPrimary){
if(!delete_swipe_up(event)){
enter_text(event,"f","e","d","");
}
}
}
function PointerHandlerGHI(event) {
event.preventDefault();
if (event.type === "pointerdown"){
hideall();
showButtonText("g","h","i");
delete_swipe_down(event);
}
if(event.type ==="pointerup") {
touch_counts -=1;
}
if (event.type === "pointerup"&& event.isPrimary){
if(!delete_swipe_up(event)){
enter_text(event,"i","h","g","");
}
}
}
function PointerHandlerJKL(event) {
event.preventDefault();
if (event.type === "pointerdown") {
if(!tapped){
tapped = setTimeout(function(){
hideall();
double_tapped = false;
showButtonText("j","k","l");
delete_swipe_down(event);
tapped = null;
}, 200);
} else {
double_tapped = true;
clearTimeout(tapped); //stop timeout callback
tapped=null;
let sentence = document.getElementById("txt_area").value;
let t_arr = sentence.split(' ');
t_ch = t_arr[t_arr.length - 1];
document.getElementById("txt_area").value -= t_ch;
document.getElementById("txt_area").value = sentence.substring(0,sentence.length - t_ch.length) +document.getElementById('sel2').innerText + " ";
document.getElementById('sel1').innerText = " ";
document.getElementById('sel2').innerText = " ";
document.getElementById('sel3').innerText = " ";
}
}
if(event.type ==="pointerup") {
setTimeout(restoreall,200);
touch_counts -=1;
}
if (event.type === "pointerup" && event.isPrimary) {
if(!tapped && !double_tapped){
enter_text(event,"l","k","j","");
}
}
}
function PointerHandlerMN(event) {
event.preventDefault();
if (event.type === "pointerdown"){
hideall();
showButtonText("m","n","o");
delete_swipe_down(event);
}
if(event.type ==="pointerup") {
setTimeout(restoreall,200);
touch_counts -=1;
}
if (event.type ==="pointerup" && event.isPrimary) {
if(!delete_swipe_up(event)){
enter_text(event,"o","n","m","");
}
}
}
function PointerHandlerOPQ(event) {
event.preventDefault();
if (event.type === "pointerdown"){
hideall();
showButtonText("p","q","r");
delete_swipe_down(event);
}
if (event.type ==="pointerup") {
setTimeout(restoreall,200);
touch_counts -=1;
}
if (event.type === "pointerup"&& event.isPrimary) {
if(!delete_swipe_up(event)){
enter_text(event,"r","q","p","");
}
}
}
function PointerHandlerRST(event) {
event.preventDefault();
if (event.type === "pointerdown"){
if(!tapped){
tapped = setTimeout(function(){
hideall();
double_tapped = false;
showButtonText("s","t","u");
delete_swipe_down(event);
tapped = null;
}, 200);
} else {
double_tapped = true;
clearTimeout(tapped); //stop timeout callback
tapped=null;
let sentence = document.getElementById("txt_area").value;
let t_arr = sentence.split(' ');
t_ch = t_arr[t_arr.length - 1];
document.getElementById("txt_area").value -= t_ch;
document.getElementById("txt_area").value = sentence.substring(0,sentence.length - t_ch.length) +document.getElementById('sel3').innerText + " ";
document.getElementById('sel1').innerText = " ";
document.getElementById('sel2').innerText = " ";
document.getElementById('sel3').innerText = " ";
}
}
if(event.type ==="pointerup") {
setTimeout(restoreall,200);
touch_counts -=1;
}
if (event.type === "pointerup" && event.isPrimary) {
if(!tapped && !double_tapped) {
enter_text(event,"u","t","s","");
}
}
}
function PointerHandlerUVW(event){
event.preventDefault();
if (event.type === "pointerdown") {
hideall();
showButtonText("v","w","x");
delete_swipe_down(event);
}
if (event.type ==="pointerup") {
setTimeout(restoreall,200);
touch_counts -=1;
}
if (event.type ==="pointerup"&& event.isPrimary) {
if(!delete_swipe_up(event)) {
enter_text(event,"x","w","v","");
}
}
}
function PointerHandlerXYZ(event){
event.preventDefault();
if (event.type === "pointerdown"){
/*Delay for double tap*/
if(!tapped){
tapped = setTimeout(function(){
hideall();
double_tapped = false;
showButtonText("del","y","z");
delete_swipe_down(event);
tapped = null;
}, 200);
} else{
double_tapped = true;
clearTimeout(tapped); //stop timeout callback
tapped=null;
document.getElementById("txt_area").value += " ";
document.getElementById('sel1').innerText = " ";
document.getElementById('sel2').innerText = " ";
document.getElementById('sel3').innerText = " ";
}
}
if(event.type ==="pointerup") {
setTimeout(restoreall,200);
touch_counts -=1;
}
if (event.type === "pointerup"&& event.isPrimary){
if(!tapped && !double_tapped){
enter_text(event,"z","y","del","");
}
}
}
/**************Pointer Handler end***********************/
/***************Double tap function begin ****************/
function delete_swipe_down(event){
touch_counts += 1;
if (touch_counts >=2){
two_touch = true;
hideall();
document.getElementById("button_abc").firstChild.data = "d";
document.getElementById("button_jkl").firstChild.data = "e";
document.getElementById("button_rst").firstChild.data = "l";
}
}
function delete_swipe_up(event){
if(two_touch === true && event.isPrimary === true){
let cursor_pos = position_button(event.clientX,event.clientY);
if(cursor_pos === 2 || cursor_pos ===3){
let str = document.getElementById("txt_area").value;
document.getElementById("txt_area").value = str.substring(0, str.length - 1);
two_touch = false;
}
restoreall();
return true;
}
}
/***************double tap function end ****************/
/***********enter/delete text respect to pointerup position****/
function enter_text(event,ch1,ch2,ch3,ch4){
let button_name = event.target.id
let current_text = document.getElementById(button_name).firstChild.data;
let cursor_pos = position_button(event.clientX,event.clientY);
switch(cursor_pos){
case 1: document.getElementById("txt_area").value += ch1;
break;
case 2: document.getElementById("txt_area").value += ch2;
break;
case 3: if(ch3 == "del"){
let str = document.getElementById("txt_area").value;
document.getElementById("txt_area").value = str.substring(0, str.length - 1);
}else{
document.getElementById("txt_area").value += ch3;
}
break;
case 4: document.getElementById("txt_area").value += ch4;
break;
}
var div = document.getElementsByTagName('div')[0];
var deleteNode = document.getElementsByTagName("ul")[0];
if(deleteNode) div.removeChild(deleteNode);
// Get the top three words with highest frequency value
var t = document.getElementById("txt_area").value;
if(t) {
let words = t.split(" ");
t = words[words.length - 1];
var res = ac.input(t);
var text1 = " ";
var text2 = " ";
var text3 = " ";
if(res.length > 0) text1 = res[0];
if(res.length > 1) text2 = res[1];
if(res.length > 2) text3 = res[2];
document.getElementById('sel1').innerText = text1;
document.getElementById('sel2').innerText = text2;
document.getElementById('sel3').innerText = text3;
} else {
document.getElementById('sel1').innerText = "";
document.getElementById('sel2').innerText = "";
document.getElementById('sel3').innerText = "";
}
let scroll = document.getElementById("txt_area");
scroll.scrollTop = scroll.scrollHeight;
restoreall();
}
/********************assign letter to corner keys*****/
function showButtonText(stu_ch,abc_ch,ghi_ch){
document.getElementById("button_abc").firstChild.data = abc_ch;
document.getElementById("button_ghi").firstChild.data = ghi_ch;
document.getElementById("button_stu").firstChild.data = stu_ch;
}
/***********clrear all key text**************/
function hideall(){
let all_buttons = document.getElementsByClassName("keyboard_key");
Array.prototype.forEach.call(all_buttons, function(single_button) {
single_button.firstChild.data = " ";
})
}
// restore all key text
function restoreall(){
let all_buttons = document.getElementsByClassName("keyboard_key");
Array.prototype.forEach.call(all_buttons, function(single_button) {
let str = single_button.id
let next_text = str.substring(7,str.length)
single_button.firstChild.data = next_text;
})
}
// return (1~4) quadrant on release cursor position
function position_button(x,y){
var rect = document.getElementById("keyboardbox").getBoundingClientRect();
console.log(rect.left, rect.right,rect.top, rect.bottom, );
let x_mid = (rect.left+ rect.right)/2;
let y_mid = (rect.top+ rect.bottom)/2;
if (x >= rect.left && x <= x_mid){
if(y >= 123 && y<= y_mid){
return 2; //second quadrant
}else if(y > y_mid && y< rect.bottom){
return 3; //third quadrant
} else return 0; //out of bound
}
else if(x > x_mid && x < rect.right){
if(y >= rect.top && y<= y_mid){
return 1; //first quadrant
}else if(y > y_mid && y< rect.bottom){
return 4; //fourth quadrant
} else return 0; //out of bound
}
else { return 0; //out of bound}
}
}
<file_sep>/README.md
# 209HCI-Tiny Keyboard FatFinger
2x2cm touch screen design
demo in youtube
[](https://www.youtube.com/watch?v=_6b-5mxXi2Q)
https://www.youtube.com/watch?v=_6b-5mxXi2Q
|
b85b557564ef0077931b803c042fb384c4de0f4d
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
superraylin/209HCI-TinyKeyboard
|
1e80888a88d99ae9020b42d234de7dd60b1daa72
|
2897b596f8e110b6245367a2d4da152fa0fffca0
|
refs/heads/master
|
<repo_name>VasanthR6899/victoream<file_sep>/README.md
# victoream
Estimation of Steering Angle using Machine Learning and Computer Vision
<file_sep>/complete .py
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 20 11:14:06 2020
@author: gauth
"""
# Multiple Linear Regression
# Importing the libraries
import numpy as np
#import matplotlib.pyplot as plt
import pandas as pd
#import RPi.GPIO as gpio
import argparse
import numpy as np
#import time
#import imutils
import cv2
#import serial
#import string
#import pynmea2
import pandas as pd
# Importing the dataset
dataset = pd.read_csv(r'C:\Users\Vasanth\Desktop\project files/data.csv')
dataset.head()
X = dataset.iloc[:, :3].values
y = dataset.iloc[:, 5].values
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train1, X_test1, y_train1, y_test1 = train_test_split(X, y, test_size = 0.2, random_state = 0)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train1 = sc_X.fit_transform(X_train1)
X_test1 = sc_X.transform(X_test1)
sc_y = StandardScaler()
# Fitting Multiple Linear Regression to the Training set
from sklearn.svm import SVR
regressor = SVR(kernel='rbf')
regressor.fit(X_train1, y_train1)
y_pred_svr = regressor.predict(X_test1)
def region_of_interest(image):
height = image.shape[0]
triangle = np.array([
[(-30,height),(224,106),(580,height)]
])
mask = np.zeros_like(image)
cv2.fillPoly(mask,triangle,255)
masked_image = cv2.bitwise_and(image,mask)
return masked_image
def displaylines(image,lines):
lineimage = np.zeros_like(image)
if lines is not None:
for line in lines:
m,n,o,p = line.reshape(4)
cv2.line(lineimage,(m,n),(o,p),(255,0,0),10)
return lineimage #print(line)
# Read the frames
cap = cv2.VideoCapture(r'D:\project\challenge_video.mp4')
car_casade = cv2.CascadeClassifier(r'C:\Users\Vasanth\project files\cars.xml')
# Predicting the Test set results
while True:
_,image =cap.read()
#latitude,longitude=gps.get_data()
#print(latitude,longitude) #height = 240, width = 320
frame = cv2.resize(image,(int(image.shape[1]*1.4),int(image.shape[0]*1.4)),interpolation = cv2.INTER_AREA)
# print("{} {}".format(int(frame.shape[0]),int(frame.shape[1])))
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
canny = cv2.Canny(blur,50,150)
car = car_casade.detectMultiScale(gray)
for (x,y,w,h) in car :
cv2.rectangle(frame, (x,y),(x+w,y+h),(0,0,255),2)
print("{} {} {} {}".format(x,y,w,h))
df=pd.DataFrame([[x,x+w,y]])
#print(df)
cv2.putText(frame, "{}in".format(w),(int(x),int(y-2)),cv2.FONT_HERSHEY_SIMPLEX,0.45,(0,0,0),1)
#from sklearn.svm import SVR
#regressor = SVR(kernel='rbf')
#regressor.fit(X_train1, y_train1)
#i=SVR.regressor.predict(df)
#print(i)
masked = region_of_interest(canny)
lines = cv2.HoughLinesP(masked,2,np.pi/180,100,np.array([]),minLineLength=40,maxLineGap = 5)
line_image = displaylines(frame,lines)
final_image = cv2.addWeighted(frame,0.8, line_image,1,1)
key = cv2.waitKey(1) & 0xFF
#cv2.imshow("gau",frame)
cv2.imshow("Final",final_image)
# motormovement.forward(5)
#if(w>80):
# motormovement.halt()
if(key == ord("q")):
#gpio.cleanup()
break
cap.release()
cv2.destroyAllWindows()
|
6dad27148ccabe5825f41fde839a218bdcc31018
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
VasanthR6899/victoream
|
ee321240edc4b8d0a26ecb175195afb655eff107
|
399e71d8da8e05704152b75e1daadc57538a4a19
|
refs/heads/master
|
<file_sep>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable({
providedIn: 'root'
})
export class AmountService {
uri = 'https://lighthouse-test-front-end.firebaseio.com/amount.json';
constructor(private http: Http) {
}
getAmount(): Promise<any> {
return this.http.get(this.uri).toPromise();
}
}
<file_sep>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MessengerService {
private messageSource: BehaviorSubject<boolean> = new BehaviorSubject(true);
public message = this.messageSource.asObservable();
public redraw(value: boolean) {
this.messageSource.next(value);
}
}
<file_sep>import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { MessengerService } from './_service/messenger.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Dashboard';
sideNavOpened = true;
numNotifications = Math.trunc(Math.random() * 10);
constructor(
public router: Router,
private messenger: MessengerService
) {
}
toggleSideNav() {
this.sideNavOpened = !this.sideNavOpened;
this.messenger.redraw(true);
}
viewNotifications() {
this.numNotifications = undefined;
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable({
providedIn: 'root'
})
export class ExpensesService {
uri = 'https://lighthouse-test-front-end.firebaseio.com/estimatedExpenses.json';
constructor(private http: Http) {
}
obterExpenses(): Promise<any> {
return this.http.get(this.uri).toPromise();
}
}
<file_sep>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'moeda'
})
export class MoedaPipe implements PipeTransform {
transform(value: number): any {
const moeda = value.toFixed(2);
return 'R$ ' + moeda.toString().replace('.', ',');
}
}
<file_sep>import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { SobreComponent } from './sobre/sobre.component';
const appRoutes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'ciclovendas', component: SobreComponent },
{ path: 'marketing', component: SobreComponent },
{ path: 'calendario', component: SobreComponent },
{ path: 'atividades', component: SobreComponent },
{ path: 'tarefa', component: SobreComponent },
{ path: 'email', component: SobreComponent },
{ path: 'contato', component: SobreComponent },
{ path: 'lead', component: SobreComponent },
{ path: 'questao', component: SobreComponent },
{ path: '**', redirectTo: 'home' }
];
export const routing = RouterModule.forRoot(appRoutes);
<file_sep>import { Component, OnInit } from '@angular/core';
import { ExpensesService } from '../_service/expenses.service';
import { Chart } from 'angular-highcharts';
import { AmountService } from '../_service/amount.service';
import { MessengerService } from '../_service/messenger.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
expenses: any = {};
amounts: any = {};
expensesLoading = true;
amountsLoading = true;
chart: Chart;
chartType: String;
constructor(
private expensesService: ExpensesService,
private amountService: AmountService,
private messengerService: MessengerService
) {
this.messengerService.message.subscribe((val) => {
this.drawChart(this.chartType);
});
}
ngOnInit() {
this.expensesService.obterExpenses()
.then(res => this.expenses = res.json())
.catch(err => console.log(err))
.then(() => this.expensesLoading = false);
this.drawChart('line');
}
drawChart(type) {
this.chartType = type;
this.amountService.getAmount()
.then(res => this.amounts = res.json())
.catch(err => console.log(err))
.then(() => {
const that = this;
const data: any = [];
this.amounts.days.forEach((el, idx) => {
data.push([el, this.amounts.values[idx]]);
});
this.chart = new Chart({
chart: {
type: type
},
credits: {
enabled: false
},
series: [
{
name: 'Valores',
data: data
}
],
xAxis: {
labels: {
formatter: function() {
return that.amounts.days[this.value];
}
}
}
});
})
.then(() => this.amountsLoading = false);
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpModule } from '@angular/http';
import { routing } from './app.routing';
import { AppComponent } from './app.component';
import { MyMaterialModule } from './my-material/my-material.module';
import { HttpClientModule } from '@angular/common/http';
import { MAT_DATE_LOCALE } from '@angular/material';
import { HomeComponent } from './home/home.component';
import { SobreComponent } from './sobre/sobre.component';
import { MoedaPipe } from './_pipe/moeda.pipe';
import { ChartModule } from 'angular-highcharts';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
SobreComponent,
MoedaPipe
],
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpModule,
HttpClientModule,
MyMaterialModule,
routing,
ChartModule
],
providers: [
{provide: MAT_DATE_LOCALE, useValue: 'pt-BR'},
],
bootstrap: [AppComponent]
})
export class AppModule { }
|
7db47711b19fe19d8183d1988af37d37a79e1ade
|
[
"TypeScript"
] | 8
|
TypeScript
|
antunezz/test-front-end-developer
|
3332f823c9d7b3f4d4525038c5f974a0fbc029a4
|
868d8814f9e7da7d86cd510de23c66c52d65a315
|
refs/heads/main
|
<file_sep>export type Comment = {
id: number;
postId?: number;
name?: string;
email?: string;
body: string;
}<file_sep>import { createSlice, createEntityAdapter, createAsyncThunk } from '@reduxjs/toolkit';
import { RootState } from '../../app/store';
export const fetchComments = createAsyncThunk(
'comments/fetchComments',
async () => {
const data = await fetch(
`http://localhost:3001/comments?_limit=10`
).then((res) => res.json());
const tags = data.reduce((prev: any, curr: any) => [...prev, curr.tags], []).flat();
const likes = data.reduce((prev: any, curr: any) => [...prev, curr.likes], []).flat();
const comments = data.map(({id, body}: any) => ({id, body}));
return {
comments,
likes,
tags,
}
}
);
export const deleteComment = createAsyncThunk(
'comments/deleteComment',
async (id: number) => {
await fetch(
`http://localhost:3001/comments/${id}`, {
method: 'DELETE'
}
);
return id;
}
);
export const patchComment = createAsyncThunk(
'comments/patchComment',
async ({id, newObj}: any) => {
await fetch(
`http://localhost:3001/comments/${id}`, {
method: 'PATCH',
body: JSON.stringify(newObj)
}
).then((res) => res.json());
return { id, changes: newObj };
}
);
const commentsAdapter = createEntityAdapter({
selectId: (comment: any) => comment.id,
});
const likesAdapter = createEntityAdapter({
selectId: (like: any) => like.id,
});
const tagsAdapter = createEntityAdapter({
selectId: (tag: any) => tag.id,
});
const commentsSlice = createSlice({
name: 'comments',
initialState: commentsAdapter.getInitialState({
loading: false,
tags: tagsAdapter.getInitialState(),
likes: likesAdapter.getInitialState(),
}),
reducers: {
setAllComments: commentsAdapter.setAll,
setOneComments: commentsAdapter.addOne,
setManyComments: commentsAdapter.addMany,
updateOneComment: commentsAdapter.updateOne,
removeLikes: (state) => {
likesAdapter.removeAll(state.likes);
},
removeTagById: (state, {payload: tagId}: any) => {
tagsAdapter.removeOne(state.tags, tagId);
}
},
extraReducers: (builder) => {
builder
.addCase(fetchComments.pending, (state) => {
state.loading = true;
})
.addCase(fetchComments.fulfilled, (state, { payload }: any) => {
state.loading = false;
commentsAdapter.setAll(state, payload.comments);
likesAdapter.setAll(state.likes, payload.likes);
tagsAdapter.setAll(state.tags, payload.tags);
})
.addCase(fetchComments.rejected, (state) => {
state.loading = false;
})
.addCase(deleteComment.pending, (state) => {
state.loading = true;
})
.addCase(deleteComment.fulfilled, (state, { payload: id }: any) => {
state.loading = false;
commentsAdapter.removeOne(state, id);
})
.addCase(deleteComment.rejected, (state) => {
state.loading = false;
})
.addCase(patchComment.pending, (state) => {
state.loading = true;
})
.addCase(patchComment.fulfilled, (state, { payload: { id, changes } }) => {
state.loading = false;
commentsAdapter.updateOne(state, {id, changes})
})
.addCase(patchComment.rejected, (state) => {
state.loading = false;
})
},
});
export const {
setAllComments,
setOneComments,
setManyComments,
updateOneComment,
removeLikes,
removeTagById,
} = commentsSlice.actions;
export const commentsSelectors = commentsAdapter.getSelectors(
(state: RootState) => state.comments
);
export const likesSelectors = likesAdapter.getSelectors(
(state: RootState) => state.comments.likes
)
export const tagsSelectors = tagsAdapter.getSelectors(
(state: RootState) => state.comments.tags
)
export default commentsSlice.reducer;
|
a114923025353c7747fb0e80a7df24b3ed295b80
|
[
"TypeScript"
] | 2
|
TypeScript
|
MoonG25/study-redux
|
d46664c5ffab31b00612bcc24dcf550e25bb5016
|
8a871229825207209864d1778b7b1dfd96e4f0c1
|
refs/heads/main
|
<file_sep>using FlightControlWeb;
using Microsoft.AspNetCore.Mvc.Formatters.Xml;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace UnitTestFlightControlWeb
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
// @@@Arrange@@@
//create fp = (pass,name,init_loc,segments)
int passengers = 250;
string companyName = "El-Down";
InitialLocation init = new InitialLocation(30, 30, "2020-05-27T00:00:00Z");
Segment a = new Segment(33, 33, 10);
Segment b = new Segment(40, 40, 20);
List<Segment> segments = new List<Segment>();
segments.Add(a);
segments.Add(b);
FlightPlan fp = new FlightPlan(passengers, companyName, init, segments);
FlightData fd = new FlightData(fp);
DateTime dateA = DateTime.Parse("2020-05-27T00:00:00Z").ToUniversalTime(); // on start
bool expectedA = true;
DateTime dateB = DateTime.Parse("2020-05-27T00:00:30Z").ToUniversalTime(); // on end
bool expectedB = true;
DateTime dateC = DateTime.Parse("2020-05-27T00:00:07Z").ToUniversalTime(); // on middle
bool expectedC = true;
DateTime dateD = DateTime.Parse("2020-05-27T00:00:10Z").ToUniversalTime(); // on segment
bool expectedD = true;
DateTime dateE = DateTime.Parse("2020-05-27T00:00:31Z").ToUniversalTime(); // after flight
bool expectedE = false;
DateTime dateF = DateTime.Parse("2020-05-26T00:00:00Z").ToUniversalTime(); // before flight
bool expectedF = false;
// @@@Act@@@
bool actualA = fd.onAir(dateA);
bool actualB = fd.onAir(dateB);
bool actualC = fd.onAir(dateC);
bool actualD = fd.onAir(dateD);
bool actualE = fd.onAir(dateE);
bool actualF = fd.onAir(dateF);
// @@@Assert@@@
Assert.AreEqual(expectedA, actualA);
Assert.AreEqual(expectedB, actualB);
Assert.AreEqual(expectedC, actualC);
Assert.AreEqual(expectedD, actualD);
Assert.AreEqual(expectedE, actualE);
Assert.AreEqual(expectedF, actualF);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FlightControlWeb
{
public class ServerInfo
{
string serverId;
string serverURL;
public ServerInfo()
{
}
public ServerInfo(string serverId, string serverURL)
{
ServerId = serverId;
ServerURL = serverURL;
}
public string ServerId
{
get { return serverId; }
set { serverId = value; }
}
public string ServerURL
{
get { return serverURL; }
set { serverURL = value; }
}
}
}<file_sep>using System;
namespace FlightControlWeb
{
public class Flight
{
string flight_id;
double longitude;
double latitude;
int passengers;
string company_name;
DateTime date_time;
bool is_external;
public Flight()
{
}
public Flight(string flight_id, double longitude, double latitude, int passengers,
string company_name, DateTime date_time, bool is_external)
{
Flight_id = flight_id;
Longitude = longitude;
Latitude = latitude;
Passengers = passengers;
Company_name = company_name;
Date_time = date_time;
Is_external = is_external;
}
public string Flight_id
{
get { return flight_id; }
set { flight_id = value; }
}
public double Longitude
{
get { return longitude; }
set { longitude = value; }
}
public double Latitude
{
get { return latitude; }
set { latitude = value; }
}
public int Passengers
{
get { return passengers; }
set { passengers = value; }
}
public string Company_name
{
get { return company_name; }
set { company_name = value; }
}
public DateTime Date_time
{
get { return date_time; }
set { date_time = value; }
}
public bool Is_external
{
get { return is_external; }
set { is_external = value; }
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FlightControlWeb
{
public class Segment
{
private double longitude;
public double Longitude
{
get { return longitude; }
set { longitude = value; }
}
private double latitude;
public double Latitude
{
get { return latitude; }
set { latitude = value; }
}
private int timespan_seconds;
public Segment(double longitude, double latitude, int timespan_seconds)
{
Longitude = longitude;
Latitude = latitude;
Timespan_seconds = timespan_seconds;
}
public Segment()
{
}
public int Timespan_seconds
{
get { return timespan_seconds; }
set { timespan_seconds = value; }
}
}
}
<file_sep># WEB-Flight-Controller
REST Based Web Application
Using C# to build the server side, and JS, HTML for the client side.
<file_sep>let map;
var markers = [];
var clicked = null;
var flightPath;
var landing_longi;
var landing_lati;
var segmantLocations = [];
var flags;
var flightPlanCoordinates = [];
var flightPath;
var counter = 0;
var init_loc;
function run() { // this function runs when body loads, initializes stuff & listeners
// drop component :
var dropbox = document.getElementById("list_in");
dropbox.addEventListener('dragenter', dragEnter, false);
dropbox.addEventListener('dragleave', dragExit, false);
dropbox.addEventListener('dragover', noopHandler, false);
dropbox.addEventListener('drop', drop, false);
function dragEnter(evt) {
evt.stopPropagation();
evt.preventDefault();
document.getElementById('internal_header').style.display = 'none';
document.getElementById('internal_list').style.display = 'none';
document.getElementById("list_in").style.backgroundColor = '#e6e6ff';
var dropText = document.createElement("h3");
dropText.innerHTML = "Drop Here";
dropText.id = "drop";
dropText.style.position = "relative";
dropText.style.left = "0%";
dropText.style.top = "40%";
dropText.style.pointerEvents = 'none';
document.getElementById("list_in").appendChild(dropText);
}
function dragExit(evt) {
evt.stopPropagation();
evt.preventDefault();
var element = document.getElementById("drop");
element.parentNode.removeChild(element);
document.getElementById("list_in").style.backgroundColor = 'rgba(255, 255, 255, 0.8)';
document.getElementById('internal_header').style.display = 'inherit';
document.getElementById('internal_list').style.display = 'inherit';
}
function noopHandler(evt) {
evt.stopPropagation();
evt.preventDefault();
}
function drop(evt) {
evt.stopPropagation();
evt.preventDefault();
var element = document.getElementById("drop");
element.parentNode.removeChild(element);
document.getElementById("list_in").style.backgroundColor = 'rgba(255, 255, 255, 0.8)';
document.getElementById('internal_header').style.display = 'inherit';
document.getElementById('internal_list').style.display = 'inherit';
var files = evt.dataTransfer.files; // Get array of files dropped
for (var i = 0, file; file = files[i]; i++) { // For each file caught, send to server
var extension = file.name.split('.').pop();
if (extension == 'json' || extension == 'txt') {
var reader = new FileReader();
reader.onload = function (event) {
var data = event.target.result;
(async function () {
var response = await fetch("/api/FlightPlan", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: data
});
if (response.status !== 200) {
alert('Looks like there was a problem. Status Code: ' +
response.status);
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
})();
};
reader.readAsText(file);
}
}
}
var intervalID = window.setInterval(get_flights_service, 3000); // run flights service every 3000 ms
}
function get_flights_service() { // function will run every fixed amount of time and brings data from server to client
var xmlhttp = new XMLHttpRequest();
//calculate current date utc :
var d = new Date();
var hrs = d.getUTCHours();
var mins = d.getUTCMinutes();
var secs = d.getUTCSeconds();
if (hrs < 10) {
hrs = "0" + hrs.toString();
} else { hrs = hrs.toString(); }
if (mins < 10) {
mins = "0" + mins.toString();
} else { mins = mins.toString(); }
if (secs < 10) {
secs = "0" + secs.toString();
} else { secs = secs.toString(); }
var date = d.getUTCFullYear() + "-" + (d.getUTCMonth() + 1) + "-" + d.getUTCDate() + "T" + hrs + ":" + mins + ":" + secs + "Z";
fetch("/api/Flights?relative_to=" + date + "&sync_all") // send request to server
.then(
function (response) {
if (response.status !== 200) {
alert('Looks like there was a problem. Status Code: ' +
response.status);
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
response.json().then(function (data) {
var arr = data;
$("#internal_list").empty();
$("#external_list").empty();
deleteMarkers();
for (var i in arr) { // for each flight caught
var f = new Flight(arr[i]);
//put flight in list
var id = f.get_flight_id();
if (f.get_is_external() == true) {
$("<li id='" + id + "'><div class='text'>" + id + "</div></li>").appendTo("#external_list");
}
else {
$("<li id='" + id + "'><div class='text'>" + id + "</div><button class='x' onclick=\"delete_from_list('" + id + "')\">X</button></li>").appendTo("#internal_list");
}
add_onclick(id);
// add icon to map
var image = {
url: "planeicon.png",
// This marker is 20 pixels wide by 32 pixels high.
size: new google.maps.Size(40, 40),
// The origin for this image is (0,0)
origin: new google.maps.Point(0, 0),
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(0, 0)
};
addMarker({
coords: { lat: f.get_latitude(), lng: f.get_longitude() },
iconImage: image,
animation: google.maps.Animation.BOUNCE,
id: f.get_flight_id(),
});
}
if (clicked != null) { // if flight is clicked, mark it
var elem = document.getElementById(clicked);
elem.style.border = "thin solid #0000ff";
}
});
}
)
}
function clearClicked() { // clears all signs of clicked flight
if (clicked != null) {
//remove info
document.getElementById("info_flight_id").innerHTML = "";
document.getElementById("info_air_company").innerHTML = "";
document.getElementById("info_passengers").innerHTML = "";
document.getElementById("info_departure_loc").innerHTML = "";
document.getElementById("info_departure_time").innerHTML = "";
document.getElementById("info_landing_loc").innerHTML = "";
document.getElementById("info_landing_time").innerHTML = "";
//remove border
var elem = document.getElementById(clicked);
elem.style.border = "";
//remove path
removeLine();
}
clicked = null;
}
function add_onclick(id) { // on click for any flight
var elem = document.getElementById(id);
elem.setAttribute('onclick', "show_more_details(\"" + id + "\")"); // show more detail at info
elem.addEventListener("mouseenter", function (event) { //highlight list item when hover
if (clicked != id) {
event.target.style.border = "thin solid #ff0000";
}
});
elem.addEventListener("mouseleave", function (event) {
if (clicked != id) {
event.target.style.border = "";
}
});
}
function highlightFlight(id) {
var elem = document.getElementById(id);
elem.style.border = "thin solid #0000ff";
}
function show_more_details(id) { //shows info for flight id, and path on map
if (clicked != null) { clearClicked(); }
clicked = id;
highlightFlight(id);
segmantLocations = [];
flightPlanCoordinates = [];
fetch("/api/FlightPlan/" + id) //get flight plan from server
.then(
function (response) {
if (response.status !== 200) {
alert('Looks like there was a problem. Status Code: ' +
response.status);
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
response.json().then(function (data) {
var plan = new FlightPlan(data);
document.getElementById("info_flight_id").innerHTML = id;
document.getElementById("info_air_company").innerHTML = plan.get_company_name();
document.getElementById("info_passengers").innerHTML = plan.get_passengers();
init_loc = new InitialLocation(plan.get_initial_location());
document.getElementById("info_departure_loc").innerHTML = "(" + init_loc.get_latitude() + "," + init_loc.get_longitude() + ")";
segmantLocations.push(init_loc.get_latitude());
segmantLocations.push(init_loc.get_longitude());
var departure_time = new Date(init_loc.get_date_time());
var split = departure_time.toString().split('+');
document.getElementById("info_departure_time").innerHTML = split[0];
var seconds = 0;
var landing_time = new Date(init_loc.get_date_time());
var segments = plan.get_segments();
for (var i in segments) {
var s = new Segment(segments[i]);
landing_lati = s.get_latitude();
segmantLocations.push(landing_lati);
landing_longi = s.get_longitude();
segmantLocations.push(landing_longi);
seconds += s.get_timespan_seconds();
}
drawLine();
document.getElementById("info_landing_loc").innerHTML = "(" + landing_lati + "," + landing_longi + ")";
landing_time.setSeconds(landing_time.getSeconds() + seconds);
var split = landing_time.toString().split('+');
document.getElementById("info_landing_time").innerHTML = split[0];
});
}
)
}
function delete_from_list(id) { //delete flight from server
event.stopPropagation();
//remove from server
(async function () {
var response = await fetch("/api/Flights/" + id, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
});
if (response.status !== 200) {
alert('Looks like there was a problem. Status Code: ' +
response.status);
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
})();
//remove manually
if (id == clicked) {
clearClicked();
}
get_flights_service();
}
function initMap() { // initialize map
// The location of Uluru
var uluru = { lat: 31.771959, lng: 35.217018 };
// The map, centered at Uluru
map = new google.maps.Map(
document.getElementById('map'), { zoom: 5, center: uluru });
google.maps.event.addListener(map, "click", function () {
//event.preventDefault();
if (clicked != null) {
get_flights_service();
clearClicked();
}
});
}
function addMarker(props) { // add marker to map
var marker = new google.maps.Marker({
position: props.coords,
map: map,
});
if (props.iconImage) { // check for icon change
marker.setIcon(props.iconImage);
}
if (clicked == props.id) {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
google.maps.event.addListener(marker, "click", function () { //icon jupms on click
event.preventDefault();
get_flights_service();
marker.setAnimation(google.maps.Animation.BOUNCE);
show_more_details(props.id);
});
markers.push(marker);
}
function drawLine() { // draws path on map
for (i = 0; i < segmantLocations.length; i += 2) {
var point = new google.maps.LatLng(segmantLocations[i], segmantLocations[i + 1]);
flightPlanCoordinates.push(point);
}
flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
addLine();
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
}
// Shows any markers currently in the array.
function showMarkers() {
setMapOnAll(map);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
markers = [];
}
function addLine() {
flightPath.setMap(map);
}
function removeLine() {
flightPath.setMap(null);
}
// Classes representation:
class Flight {
constructor(obj) {
Object.assign(this,obj)
}
get_flight_id() { return this.flight_id; }
get_longitude() { return this.longitude; }
get_latitude() { return this.latitude; }
get_passengers() { return this.passengers; }
get_company_name() { return this.company_name; }
get_date_time() { return this.date_time; }
get_is_external() { return this.is_external; }
}
class FlightPlan {
constructor(obj) {
Object.assign(this, obj)
}
get_passengers() { return this.passengers; }
get_company_name() { return this.company_name; }
get_initial_location() { return this.initial_location; }
get_segments() { return this.segments; }
}
class InitialLocation {
constructor(obj) {
Object.assign(this, obj)
}
get_longitude() { return this.longitude; }
get_latitude() { return this.latitude; }
get_date_time() { return this.date_time; }
}
class Segment {
constructor(obj) {
Object.assign(this, obj)
}
get_longitude() { return this.longitude; }
get_latitude() { return this.latitude; }
get_timespan_seconds() { return this.timespan_seconds; }
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace FlightControlWeb.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class serversController : ControllerBase
{
[HttpGet]
public ActionResult<List<ServerInfo>> Get()
{
return FlightManager.externalFlightsServers;
}
[HttpPost]
public void Post([FromBody] ServerInfo si)
{
FlightManager fm = new FlightManager();
fm.addExternalServer(si);
}
[HttpDelete]
[Route("{id}")]
public void Delete(string id)
{
FlightManager fm = new FlightManager();
fm.deleteServer(id);
}
}
}<file_sep>using System;
namespace FlightControlWeb
{
public class FlightData
{
private string id;
public string Id
{
get { return id; }
set { id = value; }
}
private FlightPlan fp;
public FlightData(FlightPlan fp)
{
Random rnd = new Random();
int a = rnd.Next(10);
int b = rnd.Next(10);
int c = rnd.Next(10);
int d = rnd.Next(10);
int e = rnd.Next(10);
int f = rnd.Next(10);
string serial1 = a.ToString() + b.ToString() + c.ToString() + d.ToString();
string serial2 = e.ToString() + f.ToString();
Id = "FLY" + serial1 + "NM" + serial2;
this.fp = fp;
}
public FlightPlan Fp
{
get { return fp; }
set { fp = value; }
}
public bool onAir(DateTime dt) // checks if flight is on air according to time
{
//calculate end time:
DateTime landingTime = fp.Initial_location.Date_time;
foreach (Segment s in fp.Segments)
{
landingTime = landingTime.AddSeconds(s.Timespan_seconds); //summing segmengs second to departure time = landing time
}
if (dt.CompareTo(fp.Initial_location.Date_time)>=0 && dt.CompareTo(landingTime)<=0)
{
return true;
}
return false;
}
public Location getAccuratePosition(DateTime dt) // returns position of flight according to time
{
DateTime a = fp.Initial_location.Date_time;
DateTime b;
Segment sa = new Segment(fp.Initial_location.Longitude, fp.Initial_location.Latitude, 0);
Segment sb;
foreach (Segment s in fp.Segments) // iterate over sergments
{
b = a;
b = b.AddSeconds(s.Timespan_seconds);
sb = s;
if (dt.CompareTo(a) > 0 && dt.CompareTo(b) < 0)
{ // if time is between the adjacent segments a,b calcualte percise value
TimeSpan secondsOnAirFromA = dt.Subtract(a);
double partialTimeOnAir = secondsOnAirFromA.TotalSeconds / s.Timespan_seconds;
double startLongitude = sa.Longitude;
double startLatitude = sa.Latitude ;
double endLongitude = sb.Longitude;
double endLatitude = sb.Latitude;
double ansLongitude = sa.Longitude + (endLongitude - startLongitude) * partialTimeOnAir;
double ansLatitude = sa.Latitude + (endLatitude - startLatitude) * partialTimeOnAir;
return new Location(ansLongitude, ansLatitude);
}
sa = sb;
a = b;
}
return null;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace FlightControlWeb
{
public class InitialLocation
{
private double longitude;
public double Longitude
{
get { return longitude; }
set { longitude = value; }
}
private double latitude;
public double Latitude
{
get { return latitude; }
set { latitude = value; }
}
public InitialLocation(double longitude, double latitude, string date_time)
{
Longitude = longitude;
Latitude = latitude;
Date_time = DateTime.Parse(date_time);
Date_time = Date_time.ToUniversalTime();
}
public InitialLocation()
{
}
private DateTime date_time;
public DateTime Date_time
{
get { return date_time; }
set { date_time = value; }
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
namespace FlightControlWeb
{
public class FlightPlan
{
private int passengers;
public int Passengers
{
get { return passengers; }
set { passengers = value; }
}
private string company_name;
public string Company_name
{
get { return company_name; }
set { company_name = value; }
}
private InitialLocation initial_location;
public InitialLocation Initial_location
{
get { return initial_location; }
set { initial_location = value; }
}
private List<Segment> segments;
public List<Segment> Segments
{
get { return segments; }
set { segments = value; }
}
public FlightPlan(int passengers, string company_name, InitialLocation initial_location, List<Segment> segments)
{
this.passengers = passengers;
this.company_name = company_name;
this.initial_location = initial_location;
this.segments = segments;
}
public FlightPlan()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FlightControlWeb
{
public class Location
{
private double longitude;
public double Longitude
{
get { return longitude; }
set { longitude = value; }
}
private double latitude;
public double Latitude
{
get { return latitude; }
set { latitude = value; }
}
public Location(double longitude, double latitude)
{
this.longitude = longitude;
this.latitude = latitude;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace FlightControlWeb
{
public class FlightManager
{
public static List<FlightData> internalFlights = new List<FlightData>();
public static List<ServerInfo> externalFlightsServers = new List<ServerInfo>();
public List<Flight> getInternal(DateTime time) // get list of internal flights according to time
{
List<Flight> list = new List<Flight>();
foreach (FlightData x in internalFlights){
if (x.onAir(time))
{
Location loc = x.getAccuratePosition(time);
Flight f = new Flight(x.Id, loc.Longitude, loc.Latitude, x.Fp.Passengers, x.Fp.Company_name, time, false);
list.Add(f);
}
}
return list;
}
public async Task<List<Flight>> getAllFlights(DateTime time) // get list of all flights according to time
{
List<Flight> list = getInternal(time); // first get internals
//add to list from external servers
foreach (ServerInfo si in externalFlightsServers.ToList<ServerInfo>())
{
List<Flight> exList = new List<Flight>();
// Create a New HttpClient object.
HttpClient client = new HttpClient();
// Call asynchronous network methods in a try/catch block to handle exceptions
try
{
HttpResponseMessage response = await client.GetAsync(si.ServerURL+ "/api/Flights?relative_to="+
time.ToString("yyyy-MM-ddTHH:mm:ssZ") );
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
try
{
exList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Flight>>(responseBody);
}
catch
{
exList = new List<Flight>();
}
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
// Need to call dispose on the HttpClient object
// when done using it, so the app doesn't leak resources
client.Dispose();
foreach (Flight f in exList.ToList())
{
f.Is_external = true;
}
list.AddRange(exList); // add the external list got from server to total list
}
return list ;
}
public void addInternal(FlightPlan fp)
{
FlightData fd = new FlightData(fp);
internalFlights.Add(fd);
}
public void addExternalServer(ServerInfo si)
{
externalFlightsServers.Add(si);
}
public async Task<FlightPlan> GetFlightPlan(string id)
{
FlightPlan fp = null;
foreach (FlightData x in internalFlights) // first search in internals
{
if (x.Id == id)
{
fp = x.Fp;
}
}
if (fp == null) // if not found search in externals
{
foreach (ServerInfo si in externalFlightsServers.ToList<ServerInfo>())
{
// Create a New HttpClient object.
HttpClient client = new HttpClient();
// Call asynchronous network methods in a try/catch block to handle exceptions
try
{
HttpResponseMessage response = await client.GetAsync(si.ServerURL + "/api/FlightPlan/" + id);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
fp = Newtonsoft.Json.JsonConvert.DeserializeObject<FlightPlan>(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
// Need to call dispose on the HttpClient object
// when done using it, so the app doesn't leak resources
client.Dispose();
//responseBody now holds info that came from server
//convert from Json to list:
if (fp.Company_name != null)
{
return fp;
}
}
}
else
{
return fp;
}
return null;
}
public void deleteInternal(string id)
{
foreach (FlightData x in internalFlights.ToList<FlightData>())
{
if (x.Id == id)
{
internalFlights.Remove(x);
}
}
}
public void deleteServer(string id)
{
foreach (ServerInfo x in externalFlightsServers.ToList<ServerInfo>())
{
if (x.ServerId == id)
{
externalFlightsServers.Remove(x);
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace FlightControlWeb.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class FlightsController : ControllerBase
{
[HttpGet]
public ActionResult<List<Flight>> GetInternal([FromQuery(Name = "relative_to")] DateTime time)
{
time = time.ToUniversalTime();
FlightManager fm = new FlightManager();
if (Request.Query.ContainsKey("sync_all"))
{
try
{
return fm.getAllFlights(time).Result;
}
catch
{
}
}
return fm.getInternal(time);
}
[HttpDelete]
[Route("{id}")]
public void Delete(string id)
{
FlightManager fm = new FlightManager();
fm.deleteInternal(id);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace FlightControlWeb.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class FlightPlanController : ControllerBase
{
[HttpGet]
[Route("{id}")]
public ActionResult<FlightPlan> Get(string id)
{
Console.WriteLine(id);
Debug.WriteLine(id);
FlightManager fm = new FlightManager();
return fm.GetFlightPlan(id).Result;
}
[HttpPost]
public void Post([FromBody] FlightPlan fp)
{
FlightManager fm = new FlightManager();
fm.addInternal(fp);
}
}
}
<file_sep>using System;
using Microsoft.AspNetCore.Mvc;
namespace FlightControlWeb.Controllers
{
[Route("api")]
[Route("")]
[ApiController]
public class DefaultController : ControllerBase
{
[HttpGet]
public ActionResult<String> Get()
{
string html = System.IO.File.ReadAllText("wwwroot/mainView.html");
return Content(html, "text/html");
}
}
}
|
9fb2a19b90b400b8296fb26f83570f2d9f1950a0
|
[
"Markdown",
"C#",
"JavaScript"
] | 15
|
C#
|
KarinShimel/WEB-Flight-Controller
|
5800b45f42a78ec18b0db8c83756f9fd81c9c294
|
5f81f88dc3eb53ba99b8c207dd7401c5df8caaff
|
refs/heads/main
|
<file_sep>export const FloatingButtonActions = [
{
text: "Accessibility",
name: "bt_accessibility",
position: 2
},
{
text: "Language",
/* icon: require("./images/ic_language_white.png"),*/
name: "bt_language",
position: 1
},
{
text: "Location",
/* icon: require("./images/ic_room_white.png"),*/
name: "bt_room",
position: 3
},
{
text: "Video",
/*icon: require("./images/ic_videocam_white.png"),*/
name: "bt_videocam",
position: 4
}
];
<file_sep>export interface StartPageProps {
goToMain: () => void;
}
<file_sep># healthy_cookies
healthy cookies network
|
6e594bcfbf0ab031a26f0de6ebe3238ebdd3dfc3
|
[
"Markdown",
"TypeScript"
] | 3
|
TypeScript
|
liewik/healthy_cookies
|
be2a3b75dd8a6b18a75d340025171721c8d7b1fd
|
ab1cbb4775706ad3ed407ddaca6efda6254220d7
|
refs/heads/master
|
<repo_name>sranjan001/bookstore_oauth-api<file_sep>/src/domain/access_token/service.go
package access_token
import (
"fmt"
"github.com/sranjan001/bookstore_oauth-api/src/respository/rest"
"github.com/sranjan001/bookstore_oauth-api/src/utils/errors"
"strings"
)
type Repository interface {
GetById(string) (*AccessToken, *errors.RestError)
Create(AccessToken) *errors.RestError
UpdateExpirationTime(AccessToken) *errors.RestError
}
type Service interface {
GetById(string) (*AccessToken, *errors.RestError)
Create(AccessTokenRequest) (*AccessToken, *errors.RestError)
UpdateExpirationTime(AccessToken) *errors.RestError
}
type service struct {
dbRepo Repository
userRepo rest.RestUserRepository
}
func NewService(repo Repository, userRepo rest.RestUserRepository) Service {
return &service{
dbRepo: repo,
userRepo: userRepo,
}
}
func (s *service) GetById(accessTokenId string) (*AccessToken, *errors.RestError) {
accessTokenId = strings.TrimSpace(accessTokenId)
if len(accessTokenId) == 0 {
return nil, errors.NewBadRequestError("invalid access token id")
}
accessToken, err := s.dbRepo.GetById(accessTokenId)
if err != nil {
return nil, err
}
return accessToken, nil
}
func (s *service) Create(atr AccessTokenRequest) (*AccessToken, *errors.RestError) {
if err := atr.validate(); err != nil {
return nil, err
}
//TODO: support both client_credentials and password grant types
//Authenticate user against the Users Api
user, err := s.userRepo.LoginUser(atr.Username, atr.Password)
if err != nil {
fmt.Println(err)
return nil, err
}
fmt.Println("User : ", user)
//Generate a new access token
at := GetNewAccessToken(user.Id)
at.Generate()
fmt.Println("User accesstoken : ", at)
//Save the new access token in Cassandra
if err := s.dbRepo.Create(at); err != nil {
return nil, err
}
return &at, nil
}
func (s *service) UpdateExpirationTime(at AccessToken) *errors.RestError {
//if err := at.validate(); err != nil {
// return err
//}
//return s.dbRepo.UpdateExpirationTime(at)
return nil
}
<file_sep>/src/respository/rest/users_repository_test.go
package rest
import (
"testing"
)
//func TestMain(m *testing.M) {
// fmt.Println("about to start test cases")
// //rest.StartMockupServer()
// //os.Exit(m.Run())
//}
func TestLoginUserTimeoutFromApi(t *testing.T) {
//rest.FlushMockups()
//rest.AddMockups(&rest.Mock{
// URL: "",
// HTTPMethod: http.MethodPost
//})
//repository := usersRepository{}
//
//user, err := repository.LoginUser("<EMAIL>", "<PASSWORD>")
//fmt.Println(user)
//fmt.Println(err)
}
func TestLoginUserInvalidErrorInterface(t *testing.T) {
}
func TestLoginUserInvalidUserJsonResponse(t *testing.T) {
}
//func Test() {
//
//}
<file_sep>/README.md
# bookstore_oauth-api
Bookstore OAuth api
//rest client
resty<file_sep>/src/domain/access_token/access_token.go
package access_token
import (
"github.com/sranjan001/bookstore_oauth-api/src/utils/errors"
"math/rand"
"strings"
"time"
)
const (
expirationTime = 24
grantTypePassword = "<PASSWORD>"
grantTypeClientCredentials = "client_credentials"
)
type AccessToken struct {
AccessToken string `json:"access_token"`
UserId int64 `json:"user_id"`
ClientId int64 `json:"client_id"`
Expires int64 `json:"expires"`
}
type AccessTokenRequest struct {
GrantType string `json:"grant_type"`
//Used for password grant type
Username string `json:"username"`
Password string `json:"<PASSWORD>"`
//Used for client_credentials grant type
ClientId string `json:"client_id"`
ClientSecret string `json:"client_secret"`
Scope string `json:"scope"`
}
func (at *AccessTokenRequest) validate() *errors.RestError {
if at.GrantType != grantTypePassword && at.GrantType != grantTypeClientCredentials {
return errors.NewBadRequestError("Invalid grant_type parameters")
}
//TODO validate for each grant type
return nil
}
func GetNewAccessToken(userId int64) AccessToken {
return AccessToken{
UserId: userId,
Expires: time.Now().UTC().Add(expirationTime * time.Hour).Unix(),
}
}
func (at AccessToken) IsExpired() bool {
return time.Unix(at.Expires, 0).Before(time.Now().UTC())
}
func (at *AccessToken) Generate() {
rand.Seed(time.Now().UnixNano())
chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ" +
"abcdefghijklmnopqrstuvwxyzåäö" +
"0123456789")
length := 8
var b strings.Builder
for i := 0; i < length; i++ {
b.WriteRune(chars[rand.Intn(len(chars))])
}
at.AccessToken = b.String() // E.g. "<PASSWORD>"
}
//Web frontend - Client-Id: 123
//Android APP - Client-Id: 234
<file_sep>/cassandra-ddl.cql
CREATE KEYSPACE oauth WITH REPLICATION ={'class': 'SimpleStrategy','replication_factor': 1}
USE oauth
CREATE TABLE access_tokens( access_token varchar PRIMARY KEY, USER_ID bigint, client_id bigint, expires bigint);
|
60613cbf6443b559e21108f1a8140c19947fca8e
|
[
"Markdown",
"SQL",
"Go"
] | 5
|
Go
|
sranjan001/bookstore_oauth-api
|
f2729cf4e675fedd41068b939c39a6c030e84514
|
4f633fa48b8a154817770abb1c25ea8c3bb4443b
|
refs/heads/master
|
<repo_name>titusTong/journey<file_sep>/mywebpack.config.js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool:'cheap-eval-source-map',
entry:[
'webpack-dev-server/client?http://127.0.0.1:9000',
'./src/components/app.jsx',
],
output:{
path:path.resolve(__dirname, 'dist'),
filename:'js/index.js'
},
module:{
rules:[
{
test:/\.(js|jsx)$/,
exclude:/(node_modules|bower_components)/,
use:{
loader:'babel-loader',
options:{
presets:['es2015', 'react']
}
}
},
{
test:/\.css$/,
use:['style-loader','css-loader']
},
{
test:/\.less$/,
use:[
{
loader:'style-loader'
},{
loader:'css-loader'
},{
loader:'less-loader'
}
]
}
]
},
plugins:[
new HtmlWebpackPlugin ({
filename:'index.html',
template:'index.html',
inject:'body'
})
],
devServer:{
contentBase:path.join(__dirname, 'dist'),
compress:true,
port:9000
}
}
<file_sep>/src/components/app.jsx
import React from 'react';
import IndexView from './views/IndexView.jsx';
const App = ({location})=>{
let View = IndexView;
const path = {location}.location.pathname;
if(path == '/') {
View = IndexView
};
return (<View />)
}
export default App;
<file_sep>/README.md
# journey
webpack2
|
59f4487d89557504402c907244fa75e5fe640a17
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
titusTong/journey
|
4aeb31c82fe9e71f0dee81a1e51de4788acf846a
|
3a1e22eb66eb84c12c116abc02bf781a791c25b0
|
refs/heads/master
|
<repo_name>R-Prince/junior-dev-test<file_sep>/README.md
# CharlieHR Junior Dev Tech Test
## <NAME>
Language - Python
Please see [main.py](main.py) for User class and [test_class.py](test_class.py) for testing suite.
To run the test please type "python -m unnittest test_class" in the command line.
<file_sep>/main.py
from datetime import date
class User:
# Assign values for name and date of birth
def __init__(self, name, date_of_birth):
self.name = name
self.date_of_birth = date_of_birth
# Return an Integer representing the user's current age
def age(self):
today = date.today()
dob = self.date_of_birth
age = today.year - dob.year - (
(today.month, today.day) < (dob.month, dob.day))
return age
# Return a Date object for the user's current upcoming birthday
def next_birthday(self):
today = date.today()
birthday_this_year = self.date_of_birth.replace(year=today.year)
if today < birthday_this_year:
next_birthday = birthday_this_year
else:
next_birthday = birthday_this_year.replace(year=today.year + 1)
return next_birthday
<file_sep>/test_class.py
import unittest
from datetime import date
from main import User
class TestClass (unittest.TestCase):
def test_return_correct_age(self):
today = date.today()
# Tests
test1 = User("test1", date(1986, 1, 1))
test2 = User("test2", date(1988, today.month, today.day))
test3 = User("test3", date(1990, 12, 30))
# Action to determine age
result1 = test1.age()
result2 = test2.age()
result3 = test3.age()
# Assert - Results function should return
self.assertEqual(result1, 34)
self.assertEqual(result2, 32)
self.assertEqual(result3, 29)
def test_return_correct_next_birthday(self):
today = date.today()
# Tests
test1 = User("test1", date(1986, 1, 1))
test2 = User("test2", date(1988, today.month, today.day))
test3 = User("test3", date(1990, 12, 30))
# Action to determine next birthday
result1 = test1.next_birthday()
result2 = test2.next_birthday()
result3 = test3.next_birthday()
# Assert - Results function should return
self.assertEqual(result1, date(2021, 1, 1))
self.assertEqual(result2, date(2021, 11, 6))
self.assertEqual(result3, date(2020, 12, 30))
|
639f89e3a8f706197d7e91a8b08ca25071aa67e6
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
R-Prince/junior-dev-test
|
8e6546546dd8de2a8a59b25e5ac5616691d41129
|
187e4ba1a97854eab838a347767a8137517234f4
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Oct 23 09:19:16 2014
@author: Suzanne
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data_path = 'C:/Users/Public/Documents/MSc-DataScience/INM430/Data/'
data_file = 'censusCrimeClean.csv'
dirty_file = 'censusCrime.csv'
csv_census = pd.read_csv(data_path + data_file)
# --------------------------------------------------------------------------
numpyArray = csv_census.as_matrix(["medIncome", "ViolentCrimesPerPop"])
arr1 = numpyArray[:,0] # now this holds "medIncome" values
arr2 = numpyArray[:,1] # this holds "ViolentCrimesPerPop" values
# -----------------------------------------------------------------------
# Example of doing x and y histograms around the scatterplot
# -----------------------------------------------------------------------
# the random data
x = arr1
y = arr2
# definitions for the axes
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left+width+0.02
rect_scatter = [left, bottom, width, height]
rect_histx = [left, bottom_h, width, 0.2]
rect_histy = [left_h, bottom, 0.2, height]
# start with a rectangular Figure
plt.figure(1, figsize=(8,8))
axScatter = plt.axes(rect_scatter)
axHistx = plt.axes(rect_histx)
axHisty = plt.axes(rect_histy)
# no labels
#axHistx.xaxis.set_major_formatter(nullfmt)
#axHisty.yaxis.set_major_formatter(nullfmt)
# the scatter plot:
axScatter.scatter(x, y)
binwidth = .1
xymax = np.max( [np.max(np.fabs(x)), np.max(np.fabs(y))] )
lim = ( int(xymax/binwidth) + 1) * binwidth
#axScatter.set_xlim( (-lim, lim) )
#axScatter.set_ylim( (-lim, lim) )
bins = np.arange(-lim, lim + binwidth, binwidth)
axHistx.hist(x, bins=bins)
axHisty.hist(y, bins=bins, orientation='horizontal')
axHistx.set_xlim( axScatter.get_xlim() )
axHisty.set_ylim( axScatter.get_ylim() )
plt.show()
# ------------------------------------------------------------
# Doing several plots on a page
# Arguments - 211 (which could also be written in 3-tuple form as (2,1,1) means two rows
# of plot windows; one column; the third digit specifies the positining relative to the
# other subplot windows--in this case, this is the first plot (which places it on row 1,
# hence the 1. plot number one," and the argument passed to the second call to add_subplot,
# differs from the first only by the trailing digit (a 2 instead of a 1, because this plot
# is the second plot.
# A bigger example: if instead you wanted four plots on a page, in a 2x2 matrix configuration,
# you would call the add_subplot method four times, passing in these four
# arguments (221), (222), (223), and (224), to create four plots on a
# page at 10, 2, 8, and 4 o'clock, respectively and in this order.
# ------------------------------------------------------------
fig = plt.figure()
plt.title("Four plots")
ax1 = fig.add_subplot(221)
ax1.plot([(1, 2), (3, 4)], [(4, 3), (2, 3)])
ax2 = fig.add_subplot(222)
ax2.plot([(7, 2), (5, 3)], [(1, 6), (9, 5)])
ax3 = fig.add_subplot(223)
ax3.plot([(7, 2), (5, 3)], [(1, 6), (9, 5)])
ax4 = fig.add_subplot(224)
ax4.plot([(7, 2), (5, 3)], [(1, 6), (9, 5)])
plt.show()
# Another multiple chars example
#import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=4, ncols=4)
fig.tight_layout() # Or equivalently, "plt.tight_layout()"
plt.show()
# ===================================================================
# Multiple charts, 1 row
# ===================================================================
# Test data
x = np.random.random(10)
y = np.random.random(10)
# Four axes, returned as a 2-d array
plot_rows = 1
plot_cols = 2
fig, axarr = plt.subplots(plot_rows, plot_cols)
fig.tight_layout()
# Histogram of the input data
# use azarr[r, c] if r > 1
axarr[0].hist(x)
axarr[0].set_title("x variable")
# Histogram of the normal distribution
axarr[1].hist(y)
axarr[1].set_title('y variable')
plt.show()
# ===================================================================
# Multiple charts, 2 x 3
# ===================================================================
# Test data
x = np.random.random(10)
y = np.random.random(10)
# Four axes, returned as a 2-d array
plot_rows = 2
plot_cols = 3
fig, axarr = plt.subplots(plot_rows, plot_cols)
fig.tight_layout()
# ============================
# Row 0
# ============================
# Scatter of x by y
axarr[0, 0].scatter(x, y)
axarr[0, 0].set_title('x x y variable')
# Histogram of the input data
axarr[0, 1].hist(x)
axarr[0, 1].set_title('x variable')
# ============================
# Row 1
# ============================
# Scatter of y by x
axarr[1, 0].scatter(y, x)
axarr[1, 0].set_title('y x x variable')
# Histogram of the normal distribution
axarr[1, 1].hist(y)
axarr[1, 1].set_title('y variable')
plt.show()
|
58dba93073d1f99bdfd81ee353385e5892660797
|
[
"Python"
] | 1
|
Python
|
suzannefox/PythonExamples
|
ea5b1ea4617ec5e8dbdfffd408ff7f81363dc954
|
80e272da7aabbada2ce414f9b9d5ee36775536ed
|
refs/heads/master
|
<file_sep>import { Injectable } from '@angular/core';
import { Http, Jsonp } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
@Injectable()
export class RecipesService {
private API_URL: string = 'http://www.recipepuppy.com/api/?';
constructor(
private http: Http,
private jsonp: Jsonp
) {}
/**
* fetches a list of recipes from the provided ingredients
* @param ingredients - a string of comma-separated ingredients
*/
fetchRecipesByIngredient(ingredients: string): Observable<any> {
return this.http.get(`${this.API_URL}i=${ingredients}`)
.map(res => res.json());
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {NgForm} from '@angular/forms';
// import services
import { RecipesService } from '../services/recipes/recipes.service';
@Component({
selector: 'app-ingredients-page',
templateUrl: './ingredients-page.component.html',
styleUrls: ['./ingredients-page.component.css']
})
export class IngredientsPageComponent implements OnInit {
constructor(
private RecipesService: RecipesService
) { }
ngOnInit() {
}
public recipes: Array<Object>;
formSubmit(f: NgForm) {
let searchTerm = '';
f.value.ingredients.map((ingredient) => {
searchTerm += `${ingredient.value},`;
});
this.RecipesService.fetchRecipesByIngredient(searchTerm)
.subscribe((response) => {
this.recipes = response.results.map((recipe) => {
console.log(recipe);
return recipe;
})
});
}
}
<file_sep>import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
// import components
import { HomePageComponent } from './home-page/home-page.component';
import { IngredientsPageComponent } from './ingredients-page/ingredients-page.component';
import { RecipesPageComponent } from './recipes-page/recipes-page.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
const routes: Routes = [
// root path
{
path: '',
children: [
{
path: '',
pathMatch: 'full',
component: HomePageComponent
},
{
path: 'ingredients',
pathMatch: 'full',
component: IngredientsPageComponent
},
{
path: 'recipes',
pathMatch: 'full',
component: RecipesPageComponent
}
]
},
// if user navigates to an undefined route, redirect to PageNotFoundComponent
{
path: '**',
component: PageNotFoundComponent,
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
|
00bb40de6d7445986eb0fceacef408462e3de88e
|
[
"TypeScript"
] | 3
|
TypeScript
|
bryanpbaker/pantry
|
f53d6f979db3aa1922bae9894e47be82e74948c2
|
db23e1d872de300d8084efc393ea08774e9ff54e
|
refs/heads/master
|
<file_sep>module ReviewsHelper
def review_instance_from(article)
@review = article.reviews.find_by(user_id: current_user.id)
end
def avg_reviews(reviews)
(reviews.map(&:star).inject(0.0){ |r, i| r+=i } / reviews.size).round(2)
end
end
<file_sep>class StaticPagesController < ApplicationController
def index
@articles = Article.order("created_at DESC").page(params[:page]).per(24)
end
def new
end
def search
@articles = Article.search(params[:keyword])
@articles = @articles.order("created_at DESC").page(params[:article]).per(24) if @articles
end
end
|
17893c489d2c594fb5abfc8c97d125dd3c9b5219
|
[
"Ruby"
] | 2
|
Ruby
|
kyutech-stairs/note-
|
5b7ce95e7549180fc2cc8dd1f266932747c42413
|
b155183476bd12011af2fe1828c2e85038e624fc
|
refs/heads/main
|
<repo_name>HE140317/CI53_HW2<file_sep>/b2.js
class Book {
id;
name;
price;
publishedDate;
constructor(id, name, price, publishedDate) {
this.id = id;
this.name = name;
this.price = price;
this.publishedDate = publishedDate;
}
update(data) {
}
}
class ComicBook extends Book {
funny;
pageNumber;
constructor(id, name, price, publishedDate, funny, pageNumber) {
super(id, name, price, publishedDate);
this.funny = funny;
this.pageNumber = pageNumber;
}
}
class TextBook extends Book {
subject;
grade;
constructor(id, name, price, publishedDate, subject, grade) {
super(id, name, price, publishedDate);
this.subject = subject;
this.grade = grade;
}
}
class ScienceBook extends Book {
major;
constructor(id, name, price, publishedDate, major) {
super(id, name, price, publishedDate);
this.major = major;
}
}
class BookShelf {
name;
owner;
dateModified;
constructor(name, owner, dateModified) {
this.name = name;
this.owner = owner;
this.dateModified = dateModified;
}
addBook(book) {
}
updateBook(id, data) {
}
deleteBook(id) {
}
showBooks() {
}
findBook(name) {
}
//có thể vì chúng đều được kế thừa từ class Book()
}
|
995db4f3280846186cdaf29200e81ab336f88181
|
[
"JavaScript"
] | 1
|
JavaScript
|
HE140317/CI53_HW2
|
05c739e71e1c85ea93113c03197bc4685d25a270
|
262b1cb5a53760c15483f75080f32abb445e8b25
|
refs/heads/master
|
<file_sep>let cUsers;
class Title extends React.Component {
render() {
return (
<div className="title">
<span>User management</span>
</div>
);
}
}
class FormItem extends React.Component {
constructor(props) {
super(props);
this.addUser = this.addUser.bind(this);
}
clearInput() {
this.refs.name.value = '';
this.refs.age.value = '';
this.refs.skill.value = '';
}
addUser() {
var that = this;
var userInfo = {
name: this.refs.name.value,
age: this.refs.age.value,
skill: this.refs.skill.value
};
$.post("/addUser", userInfo, function (data) { //save data to server
cUsers.state.users = data;
cUsers.setState(cUsers.state);
that.clearInput();
});
}
render() {
return (
<div>
<div className="control-group">
<div className="label">
<span>User</span>
</div>
<div className="input">
<input type="text" ref="name" placeholder="Name"/>
</div>
</div>
<div className="control-group">
<div className="label">
<span>Age</span>
</div>
<div className="input">
<input type="text" ref="age" placeholder="Age..."/>
</div>
</div>
<div className="control-group">
<div className="label">
<span>Skill</span>
</div>
<div className="input">
<input type="text" ref="skill" placeholder="Skill..."/>
</div>
</div>
<div className="control-group">
<div className="input">
<button onClick={this.addUser}>Add</button>
</div>
</div>
</div>
);
}
}
class Form extends React.Component {
render() {
return (
<div className="form">
<FormItem/>
</div>
);
}
}
class HeadList extends React.Component {
render() {
return (
<thead>
<tr>
<th>User</th>
<th>Age</th>
<th>Skill</th>
<th>Action</th>
</tr>
</thead>
);
}
}
class Row extends React.Component {
constructor(props) {
super(props);
this.deleteUser = this.deleteUser.bind(this);
this.editUser = this.editUser.bind(this);
this.saveUser = this.saveUser.bind(this);
this.cancelUser = this.cancelUser.bind(this);
this.state = {
onEdit: false
}
}
deleteUser(e) {
var idUser = e.target.parentNode.parentNode.getAttribute('id');
$.post('/deleteUser', {idDelete: idUser}, function (data) {
cUsers.state.users = data;
cUsers.setState(cUsers.state);
});
}
editUser() {
this.state.onEdit = true;
this.setState(this.state);
}
saveUser(e) {
var that = this;
var userInfo = {
name: this.refs.name.value,
age: this.refs.age.value,
skill: this.refs.skill.value
};
var idEdit = e.target.parentNode.parentNode.getAttribute('id');
$.post('/updateUser', {
idEdit: idEdit,
name: userInfo.name,
age: userInfo.age,
skill: userInfo.skill
}, function (data) {
that.state.onEdit = false;
that.setState(that.state);
cUsers.state.users = data;
cUsers.setState(cUsers.state);
});
}
cancelUser() {
this.state.onEdit = false;
this.setState(this.state);
}
render() {
if (this.state.onEdit) {
return (
<tr id={this.props.idx}>
<td>
<input defaultValue={this.props.user.name} type="text" ref="name"/>
</td>
<td>
<input defaultValue={this.props.user.age} type="text" ref="age"/>
</td>
<td>
<input defaultValue={this.props.user.skill} type="text" ref="skill"/>
</td>
<td className="action">
<button className="btnEdit" onClick={this.saveUser}>Save</button>
<button className="btnDelete" onClick={this.cancelUser}>Cancel</button>
</td>
</tr>
);
}
else {
console.log('sdfdsfsd', JSON.stringify(this.props.user, null, 2), this.props.user.name)
return (
<tr id={this.props.idx}>
<td>{this.props.user.name}</td>
<td>{this.props.user.age}</td>
<td>{this.props.user.skill}</td>
<td className="action">
<button className="btnEdit" onClick={this.editUser}>Edit</button>
<button className="btnDelete" onClick={this.deleteUser}>Delete</button>
</td>
</tr>
);
}
}
}
class BodyList extends React.Component {
constructor(props) {
super(props);
cUsers = this;
this.state = {
users: []
};
}
render() {
return (
<tbody>
{
this.state.users.map(function (user, i) {
return (
<Row user={user} idx={i} key={i}/>
);
})
}
</tbody>
);
}
}
class UserList extends React.Component {
render() {
return (
<div className="listUser">
<table>
<HeadList/>
<BodyList/>
</table>
</div>
);
}
}
class AddUser extends React.Component {
render() {
return (
<div className="addUser">
<Title/>
<Form/>
<UserList/>
</div>
);
}
}
ReactDOM.render(
<AddUser/>,
document.getElementById('app')
);
|
0ffc2dd1fc469c3f9d8b0c585f4d8659674ab0f8
|
[
"JavaScript"
] | 1
|
JavaScript
|
minhkhanb/NodeJS-ReactJS-Client
|
615759fefbfd8030d906d2fb436bf5746195f7ed
|
bada89545406b3db96105034ba71d666afa62ce4
|
refs/heads/master
|
<repo_name>owlcoder13/OwlOrm<file_sep>/src/Schema/Table.php
<?php
namespace Owlcoder\OwlOrm\Schema;
class Table
{
/** @var Schema */
public $schema;
public $columnNames = [];
/** @var Column[] */
public $columns = [];
public $name;
public $indexes;
public $delete = false;
/** @var ForeignKey[] */
public $fks = [];
/** @var Table[] */
public $dependencies = [];
/** @var string[] */
public $pk = [];
public function addColumn(Column $column)
{
$this->columns[] = $column;
}
/**
* Возвращает модель колонки
* @param $name
* @return Column|null
*/
public function getColumn($name)
{
foreach ($this->columns as &$col) {
if ($col->name == $name) {
return $col;
}
}
return null;
}
/**
* @param ForeignKey $fk
* @return bool|ForeignKey
*/
public function getFk(ForeignKey $fk)
{
foreach ($this->fks as $fk1) {
if (
$fk1->table === $fk->table
&& $fk1->column === $fk->column
&& $fk1->refTable === $fk->refTable
&& $fk1->refColumn === $fk->refColumn
) {
return $fk1;
}
}
return false;
}
}<file_sep>/src/Schema/LaravelSchemaGenerator.php
<?php
namespace Owlcoder\OwlOrm\Schema;
class LaravelSchemaGenerator extends SchemaGenerator
{
/** @var Database */
public $database;
public $path;
public $output = '';
// Касательно каждой таблицы
public $aboutTable = [];
// Общие запросы
public $commonQuery = '';
public function renderTemplate($variables)
{
if (empty($this->path)) {
$this->output .= $variables['code'] . "\n";
return;
}
$micro_date = microtime();
$date_array = explode(" ", $micro_date);
$time = gmdate('ymd_His_') . substr($date_array[0], 2);
extract($variables);
$classname = 'm' . $time . '_' . $name;
$templatePath = __DIR__ . '/../../templates/yii2/Migration.php';
ob_start();
require $templatePath;
$result = ob_get_clean();
$fileName = $classname . '.php';
if ( ! empty($this->path)) {
file_put_contents($this->path . '/' . $fileName, $result);
}
$this->output .= $result . "\n";
}
public function ColumnDefinition(Column $column)
{
$length = empty($column->length) ? '' : $column->length;
$funcMode = true;
$funcMapping = [
'datetime' => "\$this->dateTime($length)",
'timestamp' => "\$this->timestamp($length)",
'time' => "\$this->time($length)",
'varchar' => "\$this->string($length)",
'text' => "\$this->text($length)",
'int' => "\$this->integer($length)",
'tinyint' => "\$this->boolean()",
];
if ( ! isset($funcMapping[$column->dbType])) {
$funcMode = false;
$def = [];
$def[] = $column->dbType;
} else {
$def = $funcMapping[$column->dbType];
}
// Если не в виде функций
if ( ! $funcMode) {
if ($column->notNull) {
$def[] = 'not null';
} else {
$def[] = 'null';
}
if ($column->default !== null) {
$def[] = "default $column->default";
}
if ($column->extra) {
$def[] = "$column->extra";
}
return '"' . join(' ', $def) . '"';
}
// В виде функций
if ($column->notNull) {
$def .= '->notNull()';
} else {
$def .= '->null()';
}
if ($column->default !== null) {
if ($column->default === 'CURRENT_TIMESTAMP') {
$def .= "->defaultExpression('{$column->default}')";
} else {
$def .= "->defaultValue('{$column->default}')";
}
}
if ($column->extra) {
$def .= " . ' $column->extra'";
}
return $def;
}
public function DropColumn(Column $one)
{
$this->renderTemplate([
'name' => 'drop_column',
'code' => "\$this->dropColumn('{$one->table->name}', '{$one->name}');",
]);
}
protected function createAboutTable($table)
{
// if ( ! isset($this->aboutTable[$one->table])) {
// $this->aboutTable[$one->table] = [];
// }
}
public function DropFk(ForeignKey $one)
{
$fkName = $this->database->getFkNameFromDb($one);
$this->renderTemplate([
'name' => 'drop_fk',
'code' => "\$this->dropForeignKey('$fkName', '{$one->table}');",
]);
}
public function DropTable(Table $one)
{
$this->renderTemplate([
'name' => 'drop_table',
'code' => "\$this->dropTable('$one->name');",
]);
}
public function AlterColumn(Column $one)
{
$columnDefinition = $this->ColumnDefinition($one);
$this->renderTemplate([
'name' => 'alter_column',
'code' => "\$this->alterColumn('{$one->table->name}', '{$one->name}', {$columnDefinition});",
]);
}
public function AddColumn(Column $one)
{
$this->createAboutTable($one->table);
// if($one->typ)
}
public function CreateTable(Table $one)
{
$colDefinitions = '';
foreach ($one->columns as $column) {
// if ($column->name == 'id') continue;
$columnDefinition = $this->ColumnDefinition($column);
// todo: set PK
if (is_array($one->pk) && in_array($column->name, $one->pk)) {
$columnDefinition .= ' . " PRIMARY KEY"';
}
$colDefinitions .= "\t\t\t'{$column->name}' => $columnDefinition,\n";
}
$this->renderTemplate([
'name' => 'create_table_' . $one->name,
'code' => "\$this->createTable('{$one->name}', [\n $colDefinitions \n\t\t]);",
]);
}
public function CreateFk(ForeignKey $one)
{
$this->createAboutTable($one->table);
$this->aboutTable[$one->table] = "\table->foreign('$one->column')->references('$one->refColumn')->on('$one->refTable')";
}
public function migrate($execute = false)
{
ob_start();
foreach ($this->aboutTable as $table => $definitions) {
?>
Schema::table('<?=$table?>', function(Blueprint $table){
<?=$definitions?>
});
<?php
}
$tableDefitions = ob_get_clean();
}
}<file_sep>/src/Schema/SchemaDump.php
<?php
namespace Owlcoder\OwlOrm\Schema;
class SchemaDump
{
public static function ToString(Schema $schema)
{
$output = [];
foreach ($schema->tables as $table) {
$output[$table->name] = [
'columns' => []
];
foreach ($table->columns as $columnName => $columnInfo) {
$definition = [];
if ( ! is_null($columnInfo->length) && $columnInfo->length != null) {
$definition[] = $columnInfo->dbType . "($columnInfo->length)";
} else {
$definition[] = $columnInfo->dbType;
}
$definition[] = $columnInfo->notNull ? 'notNull' : 'null';
if ( ! is_null($columnInfo->default)) {
$definition[] = "default($columnInfo->default)";
}
if ( ! is_null($columnInfo->extra) && $columnInfo->extra != null) {
$definition[] = "extra($columnInfo->extra)";
}
if ( ! is_null($columnInfo->unsigned) && $columnInfo->unsigned != null) {
$definition[] = 'u';
}
if (in_array($columnInfo->name, $table->pk)) {
$definition[] = 'pk';
}
$output[$table->name]['columns'][$columnInfo->name] = join(':', $definition);
}
foreach ($table->fks as $fk) {
if ( ! isset($output[$table->name]['fks'])) {
$output[$table->name]['fks'] = [];
}
$output[$table->name]['fks'][$fk->column] = $fk->refTable . '(' . $fk->refColumn . '):' . $fk->onDelete . ':' . $fk->onUpdate;
}
}
return \Symfony\Component\Yaml\Yaml::dump($output, 5);
}
public static function Dump(Schema $schema, $path)
{
$output = self::ToString($schema);
file_put_contents($path, $output);
}
}<file_sep>/src/Helpers/ArrHelper.php
<?php
namespace Owlcoder\OwlOrm\Helpers;
class ArrHelper
{
/**
* @param $arr
* @return bool
*/
public static function isAssoc($arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
}<file_sep>/src/Orm/Query.php
<?php
namespace Owlcoder\OwlOrm\Orm;
use Owlcoder\OwlOrm\Schema\Database;
class Query implements IQuery
{
/**
* @var Database
*/
public $connection;
protected $select = ['*'];
protected $from = '';
public $limit = null;
public $joins = [];
public $conditions = [];
public $order = [];
public $params = [];
public function getFrom()
{
return $this->from;
}
public function getConditions()
{
return $this->conditions;
}
public function getSelect()
{
return $this->select;
}
public function select($select)
{
if (is_string($select)) {
$this->select = array_map('trim', explode(',', $select));
} else {
$this->select = $select;
}
return $this;
}
public function from($from)
{
$this->from = $from;
return $this;
}
public function where($condition)
{
$this->conditions[] = $condition;
return $this;
}
public function toSql()
{
$builderClass = $this->connection->getBuilderClass();
$builder = new $builderClass($this);
$sql = $builder->build();
$this->params = $builder->params;
return $sql;
}
public function orderBy($condition)
{
if (is_string($condition)) {
$this->order[] = $condition;
} else {
$this->order = $condition;
}
return $this;
}
public function getOrder()
{
return $this->order;
}
public function all()
{
return $this->connection->all($this->toSql(), $this->params);
}
public function limit($limit)
{
$this->limit = $limit;
return $this;
}
public function getLimit()
{
return $this->limit;
}
public function first()
{
return $this->connection->first($this->toSql(), $this->params);
}
public function scalar()
{
return $this->connection->scalar($this->toSql(), $this->params);
}
public function count()
{
$q = clone $this;
return $q->select('count(*)')->scalar();
}
}<file_sep>/src/Schema/CompareApp.php
<?php
namespace Owlcoder\OwlOrm\Schema;
class CompareApp
{
public function run(){
}
}<file_sep>/src/Schema/DbConnectionParams.php
<?php
namespace Owlcoder\OwlOrm\Schema;
class DbConnectionParams extends BaseObject
{
public $host = 'localhost';
public $user = 'root';
public $password = <PASSWORD>;
public $database = null;
public $port = 3306;
public $driver;
}<file_sep>/src/Schema/providers/SchemaProvider.php
<?php
namespace Owlcoder\OwlOrm\Schema\providers;
use Owlcoder\OwlOrm\Schema\BaseObject;
use Owlcoder\OwlOrm\Schema\Database;
use Owlcoder\OwlOrm\Schema\Schema;
abstract class SchemaProvider
{
/**
* @var Database
*/
protected $connection;
public function __construct($connection)
{
$this->connection = $connection;
}
/**
* Parse string. For example: article(id) return ['article', 'id']
* @param $type
* @return array
*/
public function parseFuncString($type)
{
preg_match("/([A-z_0-9,]*?)\\((.*?)\\)/", $type, $matches);
if (count($matches) === 3) {
return [$matches[1], $matches[2]];
}
return null;
}
/** @return Schema */
public function getSchema()
{
$this->schema = new Schema();
$this->prepareSchema();
$this->checkSchema();
return $this->schema;
}
/** @var Schema */
public $schema;
/**
* Create db schema
* must not return some value
*/
abstract public function prepareSchema();
/**
* Check schema integrity constraints
*/
public function checkSchema()
{
$schema = $this->schema;
foreach ($schema->tables as &$table) {
foreach ($table->fks as $fk) {
$refTable = $schema->getTable($fk->refTable);
if ($refTable == null) {
echo "Нарушены условия FK - не найдена искомая таблица $fk->refTable у зависимости {$fk->table}($fk->column)\n";
continue;
}
$refColumn = $refTable->getColumn($fk->refColumn);
if ($refColumn == null) {
echo "Нарушены условия FK - не найдена искомая таблица $fk->refTable у зависимости {$fk->table}($fk->column)\n";
continue;
}
}
}
}
abstract public function getTable($name);
}<file_sep>/tests/index.php
<?php
$connection = \Owlcoder\OwlOrm\Tests\Models\BaseModel::$connection;
$schema = $connection->getSchema();
//$userTable = $schema->getTable('tbl_user');
//print '<pre>';
//print_r($schema->getTable('tbl_person'));
//exit();
$query = \Owlcoder\OwlOrm\Tests\Models\User::query()
->where(['=', 'email', '<EMAIL>']);
print '<pre>';
print_r($query->all()[0]->roles);
exit();
<file_sep>/src/Schema/providers/MysqlSchemaProvider.php
<?php
namespace Owlcoder\OwlOrm\Schema\providers;
use Owlcoder\OwlOrm\Schema\Database;
use Owlcoder\OwlOrm\Schema\Table;
use Owlcoder\OwlOrm\Schema\Column;
use Owlcoder\OwlOrm\Schema\ForeignKey;
class MysqlSchemaProvider extends SchemaProvider
{
/** @var Database */
public $database;
public $typeConfig = 'mysql';
/**
* @param $columnInfo
* @return Column
*/
public function prepareColumn($columnInfo)
{
$length = null;
$columnModel = new Column;
$columnModel->name = $columnInfo['Field'];
$dbtype = $this->parseFuncString($columnInfo['Type']);
if ($dbtype != null) {
list($dbtype, $length) = $dbtype;
} else {
$dbtype = $columnInfo['Type'];
}
if (strpos($columnInfo['Type'], 'unsigned') !== false) {
$columnModel->unsigned = true;
}
$columnModel->dbType = $dbtype;
$columnModel->length = $length != null ? $length : null;
$columnModel->notNull = $columnInfo['Null'] == 'NO';
$columnModel->default = $columnInfo['Default'];
$columnModel->extra = $columnInfo['Extra'];
return $columnModel;
}
/**
* @param $tableName
* @return Table|bool
*/
public function prepareTable($tableName)
{
$tableModel = new Table();
$tableModel->name = $tableName;
$columnsInfo = $this->getTableInfo($tableName);
if ($columnsInfo === false) {
return false;
}
foreach ($columnsInfo as $columnInfo) {
$columnModel = $this->prepareColumn($columnInfo);
$columnModel->table = $tableModel;
$tableModel->addColumn($columnModel);
$tableModel->columnNames = $columnModel->name;
}
return $tableModel;
}
public function getTable($name)
{
return $this->prepareTable($name);
}
public function prepareSchema()
{
foreach ($this->getTableNames() as $tableName) {
$tableModel = $this->prepareTable($tableName);
if ($tableModel !== false) {
// Обратная ссылка на схему
$tableModel->schema = $this->schema;
$this->schema->addTable($tableModel);
}
}
$this->fetchFkConstraints();
}
public function fetchFkConstraints($table = null)
{
$rows = $this->getFkConstraints($table);
foreach ($rows as $row) {
$tableModel = $this->schema->getTable($row['TABLE_NAME']);
if ($tableModel == null) {
throw new \Exception('table can not be null if constraint exists');
}
if ($row['CONSTRAINT_NAME'] == 'PRIMARY') {
$tableModel->pk = [$row['COLUMN_NAME']];
} else {
if (isset($row['TABLE_NAME'])
&& isset($row['COLUMN_NAME'])
&& isset($row['REFERENCED_TABLE_NAME'])
&& isset($row['REFERENCED_COLUMN_NAME'])
) {
$col = $tableModel->getColumn($row['COLUMN_NAME']);
$fk = new ForeignKey([
'table' => $row['TABLE_NAME'],
'column' => $row['COLUMN_NAME'],
'refTable' => $row['REFERENCED_TABLE_NAME'],
'refColumn' => $row['REFERENCED_COLUMN_NAME'],
'onDelete' => strtolower($row['DELETE_RULE']),
'onUpdate' => strtolower($row['UPDATE_RULE']),
]);
$col->fks[] = $fk;
$tableModel->fks[] = $fk;
}
}
}
}
public function fetchIndexes()
{
}
public function getTableNames()
{
$q = "show full tables where Table_Type = 'BASE TABLE'";
$result = $this->connection->column($q);
return $result;
}
public function getTableInfo($table)
{
return $this->connection->all('describe `' . $table . '`');
}
public function getFkNameFromDb(ForeignKey $fk)
{
$q = "
SELECT CONSTRAINT_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
TABLE_SCHEMA = '{$this->dbConnectionParams->database}' AND
TABLE_NAME = '{$fk->table}'
and TABLE_NAME = '{$fk->table}'
and COLUMN_NAME = '{$fk->column}'
and REFERENCED_TABLE_NAME='{$fk->refTable}'
and REFERENCED_COLUMN_NAME='{$fk->refColumn}';";
$res = mysqli_query($this->conn, $q);
$field = mysqli_fetch_row($res);
return $field[0];
}
public function getFkConstraints($table = null)
{
$q = "SELECT
kcu.TABLE_NAME,kcu.COLUMN_NAME,kcu.CONSTRAINT_NAME, kcu.REFERENCED_TABLE_NAME,kcu.REFERENCED_COLUMN_NAME, rc.UPDATE_RULE, rc.DELETE_RULE
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
left join information_schema.REFERENTIAL_CONSTRAINTS rc
on rc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME and rc.CONSTRAINT_SCHEMA = '{$this->dbConnectionParams->database}'
WHERE
kcu.TABLE_SCHEMA = '{$this->dbConnectionParams->database}'";
if ( ! empty($table)) {
$q .= " and table = `${table}`";
}
$res = mysqli_query($this->conn, $q);
return $this->fetchAllAssoc($res);
}
public function getForeignKeys($table)
{
$q = "
SELECT
kcu.TABLE_NAME,kcu.COLUMN_NAME,kcu.CONSTRAINT_NAME, kcu.REFERENCED_TABLE_NAME,kcu.REFERENCED_COLUMN_NAME, rc.UPDATE_RULE, rc.DELETE_RULE
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
left join information_schema.REFERENTIAL_CONSTRAINTS rc on rc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
WHERE
kcu.TABLE_SCHEMA = '{$this->dbConnectionParams->database}' AND
kcu.TABLE_NAME = '{$table}';
";
$res = mysqli_query($this->conn, $q);
return $this->fetchAllAssoc($res);
}
public function query($command)
{
$stm = mysqli_query($this->conn, $command);
$rows = [];
while (($row = mysqli_fetch_assoc($stm)) != null) {
$rows[] = $row;
}
return $rows;
}
}<file_sep>/src/Schema/providers/YamlSchemaProvider.php
<?php
namespace Owlcoder\OwlOrm\Schema\providers;
use Owlcoder\OwlOrm\Schema\Table;
use Owlcoder\OwlOrm\Schema\Column;
use Owlcoder\OwlOrm\Schema\ForeignKey;
use function PHPSTORM_META\type;
use Symfony\Component\Yaml\Yaml;
class YamlSchemaProvider extends SchemaProvider
{
public $path;
public $str;
/**
* Разделяет строку на части с учётом вложенных скобок
* @param $str
* @return array
*/
function explodeColumnInfo($str)
{
$nestedBraces = 0;
$positions = [];
for ($i = 0; $i < mb_strlen($str); $i++) {
$c = mb_substr($str, $i, 1);
if ($c == '(') $nestedBraces++;
if ($c == ')') $nestedBraces--;
if ($nestedBraces == 0 && $c == ':') {
$positions[] = $i;
}
}
$output = [];
$prevPos = 0;
foreach ($positions as $position) {
$output[] = mb_substr($str, $prevPos, $position - $prevPos);
$prevPos = $position + 1;
}
$output[] = mb_substr($str, $prevPos);
return $output;
}
/**
* @param $columnName
* @param $columnInfo
* @param $tableModel
* @throws \Exception
* @return Column
*/
public function createColumn($columnName, $columnInfo, Table &$tableModel)
{
// short syntax
if (is_string($columnInfo)) {
if ($columnInfo === 'pk') {
$columnInfo = [
'length' => '11',
'type' => 'int',
'notNull' => true,
'extra' => 'auto_increment',
];
$tableModel->pk = ['id'];
} else {
$parts = $this->explodeColumnInfo($columnInfo);
$columnInfo = [];
foreach ($parts as $key => $part) {
if (strpos($part, '(') !== false) {
list($t, $l) = $this->parseFuncString($part);
switch ($t) {
case 'string':
case 'varchar':
$columnInfo['type'] = 'varchar';
$columnInfo['length'] = $l;
break;
case 'int':
$columnInfo['type'] = 'int';
$columnInfo['length'] = $l;
break;
case 'd':
case 'default':
$columnInfo['default'] = $l;
break;
case 'extra':
$columnInfo['extra'] = $l;
break;
default:
if ($key == 0) { // Тип - обязательно должен быть на первой позиции если он необычный
$columnInfo['type'] = $t;
$columnInfo['length'] = $l;
}
}
} else {
switch ($part) {
case 'notNull':
$columnInfo['notNull'] = true;
break;
case 'u':
$columnInfo['unsigned'] = true;
break;
case 'string':
$columnInfo['type'] = 'varchar';
$columnInfo['length'] = 128;
break;
case 'int':
$columnInfo['type'] = 'int';
$columnInfo['length'] = 11;
break;
case 'boolean':
case 'bool':
$columnInfo['type'] = 'tinyint';
$columnInfo['length'] = 1;
break;
case 'pk':
$tableModel->pk[] = $columnName;
break;
default:
if ($key == 0) {
$columnInfo['type'] = $part;
}
}
}
// Если у колонки стоит только pk
if (empty($columnInfo['type']) && in_array($columnName, $tableModel->pk)) {
$columnInfo['type'] = 'int';
$columnInfo['length'] = '11';
$columnInfo['extra'] = 'auto_increment';
}
// Проставление типов без length
if (in_array($part, ['datetime', 'date', 'timestamp', 'text', 'float', 'double'])) {
$columnInfo['type'] = $part;
}
}
}
}
$columnModel = new Column;
$columnModel->table = $tableModel;
$columnModel->name = $columnName;
$columnModel->dbType = isset($columnInfo['type']) ? $columnInfo['type'] : 'unknown_type';
$columnModel->notNull = isset($columnInfo['notNull']) ? (bool) $columnInfo['notNull'] : false;
$columnModel->default = isset($columnInfo['default']) ? $columnInfo['default'] : null;
if ( ! empty($columnInfo['length'])) {
$columnModel->length = $columnInfo['length'];
}
$columnModel->extra = isset($columnInfo['extra']) ? $columnInfo['extra'] : null;
$columnModel->unsigned = isset($columnInfo['unsigned']) ? $columnInfo['unsigned'] : null;
/**
* Check for timestamp column. It can not be timestamp while notNull and not have default value.
* There are some auto generate extra: on update CURRENT_TIMESTAMP and it can give you bad behavior
* in second start of comparator
**/
if ($columnModel->dbType == 'timestamp' && $columnModel->notNull && empty($columnModel->default)) {
$coldef = print_r($columnInfo, true);
throw new \Exception("You must specify default value for notNull timestamp. Table: {$tableModel->name} Column definition: $coldef");
}
foreach ($tableModel->columns as $col) {
if (in_array($col->name, $tableModel->pk) && ! $col->notNull) {
throw new \Exception('All parts of a PRIMARY KEY must be NOT NULL; table: ' . $tableModel->name);
}
}
return $columnModel;
}
/**
* @inheritdoc
* @throws \Exception
*/
public function prepareSchema()
{
if ( ! empty($this->path)) {
$data = Yaml::parse(file_get_contents($this->path));
} else if ( ! empty($this->str)) {
$data = Yaml::parse($this->str);
} else {
throw new \Exception('You must specify str or path variable');
}
if ( ! is_array($data)) {
$data = [];
}
$all = [];
foreach ($data as $tableName => $tableInfo) {
// // pass tables for test
// if($tableName != 'django_admin_log'){
// continue;
// }
if ($tableName[0] == '_') {
$all = $tableInfo;
continue;
}
$tableModel = new Table();
$tableModel->name = $tableName;
$tableModel->pk = [];
$columnsInfo = $tableInfo['columns'];
foreach ($columnsInfo as $columnName => $columnInfo) {
$columnModel = $this->createColumn($columnName, $columnInfo, $tableModel);
$tableModel->addColumn($columnModel);
}
if (isset($tableInfo['fks'])) {
foreach ($tableInfo['fks'] as $sourceColname => $keyInfo) {
// if no actions find in fk
if (strpos($keyInfo, ':') === false) {
$onDelete = 'cascade';
$onUpdate = 'cascade';
} else {
list($keyInfo, $onDelete, $onUpdate) = explode(':', $keyInfo);
}
list($m1, $m2) = $this->parseFuncString($keyInfo);
if (isset($m1) && isset($m2)) {
$col = $tableModel->getColumn($sourceColname);
if ($col == null) {
throw new \Exception("FK ERROR: Такой колонки нет {$tableName}:{$sourceColname}");
}
$fk = new ForeignKey([
'table' => $tableName,
'column' => $sourceColname,
'refTable' => $m1,
'refColumn' => $m2,
'onDelete' => $onDelete,
'onUpdate' => $onUpdate,
]);
$col->dependencies[] = $fk;
$tableModel->fks[] = $fk;
} else {
}
}
}
// Обратная ссылка на схему
$tableModel->schema = $this->schema;
$this->schema->addTable($tableModel);
}
$except = isset($all['except']) ? explode(',', $all['except']) : [];
if (isset($all['columns'])) {
foreach ($this->schema->tables as $tableModel) {
if (in_array($tableModel->name, $except)) {
continue;
}
foreach ($all['columns'] as $columnName => $columnInfo) {
$columnModel = $this->createColumn($columnName, $columnInfo, $tableModel);
$tableModel->addColumn($columnModel);
}
}
}
}
}<file_sep>/src/Orm/QueryBuilders/IQueryBuilder.php
<?php
namespace Owlcoder\OwlOrm\Orm\QueryBuilders;
use Owlcoder\OwlOrm\Orm\IQuery;
/**
* Classes build query string for any database
*
* Interface IQueryBuilder
* @package Owlcoder\OwlOrm\Orm\QueryBuilders
*/
interface IQueryBuilder
{
/**
* IQueryBuilder constructor.
* @param IQuery $query
*/
public function __construct(IQuery $query);
/**
* @return string
*/
public function build();
}<file_sep>/src/Schema/Column.php
<?php
namespace Owlcoder\OwlOrm\Schema;
class Column
{
/** @var Table */
public $table;
public $name;
public $dbType;
public $comment;
public $notNull;
public $extra;
public $default;
public $length;
public $unsigned;
public $delete = false;
public $fks = [];
/** @var Column[] */
public $dependencies = [];
// public $mappingDbTypes = [
// 'integer' => 'int(11)';
// ];
public function compare($otherColumn)
{
$fields = ['name', 'dbType', 'comment', 'notNull', 'extra', 'default', 'length', 'unsigned'];
foreach ($fields as $field) {
$eq = $this->$field == $otherColumn->$field;
if ( ! $eq) {
// echo "compare field {$otherColumn->name} mismatch $field \n";
// echo "{$otherColumn->table->name} : {$otherColumn->$field} != {$this->$field}\n";
return false;
}
}
return true;
}
public function isColumnDependsOfMe(Column $column)
{
foreach ($column->table->fks as $fk) {
if (
$fk->refTable == $this->table->name &&
$fk->refColumn == $this->name) {
return true;
}
}
return false;
}
/** @return ForeignKey|bool */
public function isDependOf(Column $column)
{
foreach ($this->table->fks as $fk) {
if (
$fk->refTable == $column->table->name &&
$fk->column == $this->name &&
$fk->refColumn == $column->name
) {
return $fk;
}
}
return false;
}
}<file_sep>/src/Orm/IQuery.php
<?php
namespace Owlcoder\OwlOrm\Orm;
interface IQuery
{
}<file_sep>/src/Orm/OrmModel.php
<?php
namespace Owlcoder\OwlOrm\Orm;
use Owlcoder\OwlOrm\Exceptions\PropertyDoesNotExists;
use Owlcoder\OwlOrm\Orm\Relations\HasManyRelation;
use Owlcoder\OwlOrm\Orm\Relations\Relation;
use Owlcoder\OwlOrm\Schema\Column;
use \Owlcoder\OwlOrm\Schema\Database;
class OrmModel
{
/** @var Database */
public static $connection;
/** @var string */
public $_table;
/** @var string */
public $_primaryKey = 'id';
public $attributes = [];
public function getPrimaryValue()
{
return $this->{$this->_primaryKey};
}
public static function instance()
{
return new static();
}
public static function InitConnection($connectionParams)
{
static::$connection = new Database($connectionParams);
}
public function getConnection()
{
return static::$connection;
}
public static function query()
{
$builder = new ModelQuery();
$builder->connection = static::instance()->getConnection();
$builder->modelClass = static::class;
$builder->from(self::instance()->_table);
return $builder;
}
public function getAttributesNames()
{
return array_map(function (Column $column) {
return $column->name;
}, static::$connection->getSchema()->getTable($this->_table)->columns);
}
public function getAttributes()
{
$out = [];
foreach ($this->getAttributesNames() as $attributeName) {
$out[$attributeName] = $this->$attributeName;
}
return $out;
}
public function __get($property)
{
$getterMethod = 'get' . ucfirst($property);
if (method_exists($this, $getterMethod)) {
$result = $this->$getterMethod();
if ($result instanceof HasManyRelation) {
return $result->get()->all();
}
return $result;
}
if (isset($this->attributes[$property])) {
return $this->attributes[$property];
}
}
public function __set($property, $value)
{
if (in_array($property, $this->getAttributesNames())) {
$this->attributes[$property] = $value;
}
}
/**
* Create hasMany relation
* @param $className
* @param $foreignKey
* @return HasManyRelation
*/
public function hasMany($className, $foreignKey)
{
$relation = new HasManyRelation();
$relation->foreignKey = $foreignKey;
$relation->className = $className;
$relation->parent = $this;
return $relation;
}
public function setAttributes($attributes)
{
$this->attributes = $attributes;
}
public function getTableSchema()
{
return $this->getConnection()->getSchema()->getTable($this->_table);
}
public function getAttributeNames()
{
$this->getTableSchema()->columnNames;
}
}<file_sep>/src/Orm/Relations/HasManyRelation.php
<?php
namespace Owlcoder\OwlOrm\Orm\Relations;
class HasManyRelation extends Relation
{
public $parent = null;
public $foreignKey = null;
public $className = null;
public function get()
{
$relationModelClassName = $this->className;
$query = $relationModelClassName::query()->where([
$this->foreignKey => $this->parent->id
]);
return $query;
}
}<file_sep>/tests/Models/User.php
<?php
namespace Owlcoder\OwlOrm\Tests\Models;
/**
* @Column(id)
* @TableName(user)
*
* Class User
*/
class User extends BaseModel
{
public $_table = 'tbl_person';
public function getRoles()
{
return $this->hasMany(UserRole::class, 'person_id');
}
}<file_sep>/src/Schema/SchemaGenerator.php
<?php
namespace Owlcoder\OwlOrm\Schema;
abstract class SchemaGenerator extends BaseObject
{
abstract public function DropColumn(Column $one);
abstract public function DropFk(ForeignKey $one);
abstract public function DropTable(Table $one);
abstract public function AlterColumn(Column $one);
abstract public function AddColumn(Column $one);
abstract public function CreateTable(Table $one);
abstract public function CreateFk(ForeignKey $one);
public function CreateFkName(ForeignKey $fk)
{
return 'fk_' . $fk->table . '_' . $fk->column;
}
abstract public function migrate($execute = false);
}<file_sep>/README.md
# OwlOrm One more active record orm for PHP
Project is under development<file_sep>/src/Orm/Relations/Relation.php
<?php
namespace Owlcoder\OwlOrm\Orm\Relations;
use Owlcoder\OwlOrm\Orm\ModelQuery;
use Owlcoder\OwlOrm\Orm\Query;
class Relation
{
}<file_sep>/src/Schema/commands/InspectDbCommand.php
<?php
namespace Owlcoder\OwlOrm\Schema\commands;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use \Owlcoder\OwlOrm\Schema\providers\MysqlSchemaProvider;
use \Owlcoder\OwlOrm\Schema\SchemaDump;
/**
* Create yml from db
* Class InspectDbCommand
* @package Owlcoder\OwlOrm\Schema\commands
*/
class InspectDbCommand extends DbCommand
{
/**
* @inheritdoc
*/
protected function configure()
{
parent::configure();
$this->setName('inspectdb');
}
/**
* @inheritdoc
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
parent::execute($input, $output);
$provider = new MysqlSchemaProvider(['database' => $this->db]);
$output->writeln("Write schema to file");
$schema = $provider->getSchema();
$output->writeln("write schema to file: " . $this->path);
SchemaDump::Dump($schema, $this->path);
$output->writeln("done");
}
}<file_sep>/src/Orm/ModelQuery.php
<?php
namespace Owlcoder\OwlOrm\Orm;
use PDO;
class ModelQuery extends Query implements IQuery
{
public $modelClass = null;
public function all()
{
$st = $this->connection->execStatement($this->toSql(), $this->params);
return array_map(function ($data) {
$model = new $this->modelClass;
$this->populate($data, $model);
return $model;
}, $st->fetchAll(PDO::FETCH_ASSOC));
}
public function first()
{
$result = $this->all();
return $result[0] ?? null;
}
public function populate($data, &$model)
{
$model->setAttributes($data);
return $model;
}
}<file_sep>/src/Schema/MysqlSchemaGenerator.php
<?php
namespace Owlcoder\OwlOrm\Schema;
class MysqlSchemaGenerator extends SchemaGenerator
{
public $queries = [];
/** @var Database */
public $database;
protected $_typeConfig = null;
public function getType($type)
{
if ($this->_typeConfig == null) {
$typeConfig = require __DIR__ . '/config/type-mappings.php';
$this->_typeConfig = array_flip(array_reverse($typeConfig['mysql']));
}
return $this->_typeConfig[$type];
}
/**
* Construct column definition
* @param Column $column
* @return string
*/
public function ColumnDefinition(Column $column)
{
$definition = [];
// Column name
$definition[] = $column->name;
// Data type
$dbType = $column->dbType;
if ($column->length) {
$dbType .= "({$column->length})";
}
if ($column->unsigned) {
$dbType .= ' ' . 'unsigned';
}
$definition[] = $dbType;
// Is null
$definition[] = $column->notNull ? 'not null' : 'null';
if ($column->default != null) {
if ($column->default === 'CURRENT_TIMESTAMP') {
$definition[] = "default $column->default";
} else {
$definition[] = "default '$column->default'";
}
}
$extra = $column->extra;
if ( ! empty($extra)) {
$definition[] = $extra;
}
return join(' ', $definition);
}
public function AlterColumn(Column $column)
{
$this->queries[] = "alter table {$column->table->name} modify COLUMN " . self::ColumnDefinition($column) . ";\n";
}
public function DropColumn(Column $column)
{
$this->queries[] = "alter table {$column->table->name} drop column {$column->name};\n";
}
public function AddColumn(Column $column)
{
$this->queries[] = "alter table {$column->table->name} add column " . self::ColumnDefinition($column) . ";\n";
}
public function DropTable(Table $table)
{
$this->queries[] = "drop table $table->name" . ";\n";
}
public function CreateTable(Table $table)
{
$columns = [];
foreach ($table->columns as $one) {
$columns[] = "\t" . self::ColumnDefinition($one);
}
if (count($table->pk) > 0) {
$pkstr = join(',', $table->pk);
$columns[] = "PRIMARY KEY($pkstr)\n";
}
$this->queries[] = "create table $table->name (" . "\n"
. join(",\n", $columns)
. "\n);\n";
}
public function CreateFk(ForeignKey $fk)
{
$fkName = self::CreateFkName($fk);
$this->queries[] = "alter table $fk->table add constraint $fkName foreign key ($fk->column) references {$fk->refTable}({$fk->refColumn}) ON DELETE {$fk->onDelete} ON UPDATE {$fk->onUpdate};\n";
}
public function DropFk(ForeignKey $fk)
{
$this->queries[] = "alter table {$fk->table} DROP FOREIGN KEY {$fk->name};\n";
}
public function migrate($execute = false)
{
if ($execute) {
foreach ($this->queries as $query) {
$this->database->exec($query);
}
} else {
// echo join("\n", $this->queries);
}
}
}<file_sep>/src/Orm/QueryBuilders/MysqlQueryBuilder.php
<?php
namespace Owlcoder\OwlOrm\Orm\QueryBuilders;
use Owlcoder\OwlOrm\Exceptions\WrongConditionException;
use Owlcoder\OwlOrm\Helpers\ArrHelper;
use Owlcoder\OwlOrm\Orm\IQuery;
class MysqlQueryBuilder implements IQueryBuilder
{
/** @var Query */
public $query;
public $params = [];
public $paramCounter = 0;
public function __construct(IQuery $query)
{
$this->query = $query;
}
public function escapeParameter($value)
{
$i = $this->paramCounter++;
$key = ':param' . $i;
$this->params[$key] = $value;
return $key;
}
/**
* @param $conditions
* @return string
* @throws WrongConditionException
*/
public function buildConditions($conditions)
{
$out = [];
foreach ($conditions as $condition) {
if (is_array($condition)) {
if (ArrHelper::isAssoc($condition)) {
// handle key => value condition
foreach ($condition as $key => $value) {
if (is_array($value)) {
if (count($value) > 0) {
$value = join(', ', $value);
$out[] = "{$key} in ($value)";
}
} else {
$out[] = "{$key} = $value";
}
}
} else {
switch ($condition[0]) {
case 'like':
$escapedValue = $this->escapeParameter($condition[2]);
$out[] = "{$condition[1]} like {$escapedValue}";
break;
case '=':
$escapedValue = $this->escapeParameter($condition[2]);
$out[] = "{$condition[1]} = {$escapedValue}";
break;
case '!=':
$escapedValue = $this->escapeParameter($condition[2]);
$out[] = "{$condition[1]} != {$escapedValue}";
break;
case 'in':
if (count($condition[2]) > 0) {
$escapedValues = array_map(function ($item) {
return $this->escapeParameter($item);
}, []);
$joined = join(', ', $escapedValues);
$out[] = "{$condition[1]} in ({$joined})";
}
break;
default:
throw new WrongConditionException('Bad condition error found: ' . print_r($condition, true));
}
}
}
}
return count($out) > 0 ? ' WHERE ' . join(' AND ', $out) : '';
}
public function buildSelect()
{
return join(',', $this->query->getSelect());
}
/**
* @return string
* @throws WrongConditionException
*/
public function build()
{
$this->params = [];
$this->paramCounter = 0;
$from = $this->query->getFrom();
$select = $this->buildSelect();
$conditions = $this->buildConditions($this->query->getConditions());
$order = $this->buildOrder($this->query->getOrder());
$limit = $this->buildLimit();
return "select {$select} from {$from}{$conditions}{$order}{$limit}";
}
public function buildOrder($orders)
{
if (count($orders) > 0) {
$joined = join(', ', $orders);
return " order by $joined";
}
return '';
}
public function buildLimit()
{
return $this->query->limit ? ' limit ' . $this->query->limit : '';
}
}<file_sep>/src/Schema/commands/SyncCommand.php
<?php
namespace Owlcoder\OwlOrm\Schema\commands;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use \Owlcoder\OwlOrm\Schema\providers\MysqlSchemaProvider;
use \Owlcoder\OwlOrm\Schema\providers\YamlSchemaProvider;
use \Owlcoder\OwlOrm\Schema\MysqlSchemaGenerator;
use \Owlcoder\OwlOrm\Schema\Yii1SchemaGenerator;
use \Owlcoder\OwlOrm\Schema\Yii2SchemaGenerator;
use \Owlcoder\OwlOrm\Schema\SchemaCompare;
/**
* Sync yml schema to db
* Class SyncCommand
* @package Owlcoder\OwlOrm\Schema\commands
*/
class SyncCommand extends DbCommand
{
/**
* @inheritdoc
*/
protected function configure()
{
parent::configure();
$this->setName('sync');
$this->addOption('generator', 'g', InputOption::VALUE_OPTIONAL, 'which generator use: yii1,yii2,raw', 'raw');
$this->addOption('dpath', null, InputOption::VALUE_OPTIONAL, 'where to save generated files', '');
$this->addOption('execute', 'e', InputOption::VALUE_OPTIONAL, 'execute if generator is raw', false);
}
/**
* @inheritdoc
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
parent::execute($input, $output);
$output->writeln("Get schema from db");
$provider = new MysqlSchemaProvider(['database' => $this->db]);
$schema1 = $provider->getSchema();
$output->writeln("Get schema yml db");
$schema2 = new YamlSchemaProvider(['path' => $this->path]);
$schema2 = $schema2->getSchema();
$g = $input->getOption('generator');
$dpath = $input->getOption('dpath');
$generator = null;
if ($g === 'raw') {
$generator = new MysqlSchemaGenerator([
'database' => $this->db
]);
}
if ($g === 'yii1') {
$generator = new Yii1SchemaGenerator([
'database' => $this->db,
'path' => $dpath
]);
}
if ($g === 'yii2') {
$generator = new Yii2SchemaGenerator([
'database' => $this->db,
'path' => $dpath
]);
}
$compare = new SchemaCompare([
'schema1' => $schema1,
'schema2' => $schema2,
'generator' => $generator,
'database' => $this->db,
]);
$output->writeln("compare");
$generator = $compare->compare();
$output->writeln("migrate");
$generator->migrate($input->getOption('execute'));
$output->writeln("done");
}
}<file_sep>/src/Schema/Yii1SchemaGenerator.php
<?php
namespace Owlcoder\OwlOrm\Schema;
class Yii1SchemaGenerator extends SchemaGenerator
{
/** @var Database */
public $database;
public $path;
public $output;
public function renderTemplate($variables)
{
if (empty($this->path)) {
$this->output .= $variables['code'] . "\n";
return;
}
$micro_date = microtime();
$date_array = explode(" ", $micro_date);
$time = gmdate('ymd_His_') . substr($date_array[0], 2);
extract($variables);
$classname = 'm' . $time . '_' . $name;
$templatePath = __DIR__ . '/../../templates/yii1/Migration.php';
ob_start();
require $templatePath;
$result = ob_get_clean();
$fileName = $classname . '.php';
if ( ! empty($this->path)) {
file_put_contents($this->path . '/' . $fileName, $result);
}
$this->output .= $result . "\n";
}
/**
* @inheritdoc
*/
public function ColumnDefinition(Column $column)
{
$definition = [];
$dbType = $column->dbType;
if ($column->length) {
$dbType .= "({$column->length})";
}
$definition[] = $dbType;
$notNull = $column->notNull ? 'not null' : 'null';
$definition[] = $notNull;
$default = $column->default ? "default '$column->default'" : '';
if(!empty($default)){
$definition[] = $default;
}
$extra = $column->extra;
if(!empty($extra)){
$definition[] = $extra;
}
return join(' ', $definition);
}
public function DropColumn(Column $one)
{
$this->renderTemplate([
'name' => "drop_column_{$one->name}_from_{$one->table->name}",
'code' => "\$this->dropColumn('{$one->table->name}', '{$one->name}');",
]);
}
public function DropFk(ForeignKey $one)
{
$fkName = $this->database->getFkNameFromDb($one);
$this->renderTemplate([
'name' => "drop_fk_{$one->table}_{$one->column}",
'code' => "\$this->dropForeignKey('$fkName', '{$one->table}');",
]);
}
public function DropTable(Table $one)
{
$this->renderTemplate([
'name' => 'drop_table',
'code' => "\$this->dropTable('$one->name');",
]);
}
public function AlterColumn(Column $one)
{
$columnDefinition = $this->ColumnDefinition($one);
$this->renderTemplate([
'name' => 'alter_column',
'code' => "\$this->alterColumn('{$one->table->name}', '{$one->name}', '{$columnDefinition}');",
]);
}
public function AddColumn(Column $one)
{
$columnDefinition = $this->ColumnDefinition($one);
$this->renderTemplate([
'name' => "add_column_{$one->name}_to_{$one->table->name}",
'code' => "\$this->addColumn('{$one->table->name}', '{$one->name}', '{$columnDefinition}');",
]);
}
public function CreateTable(Table $one)
{
$colDefinitions = '';
if ( ! empty($one->pk)) {
$colDefinitions .= "\t\t\t'id' => 'pk',\n";
}
foreach ($one->columns as $column) {
if ($column->name == 'id') continue;
$columnDefinition = $this->ColumnDefinition($column);
$colDefinitions .= "\t\t\t'{$column->name}' => \"$columnDefinition\",\n";
}
$this->renderTemplate([
'name' => 'create_table_' . $one->name,
'code' => "\$this->createTable('{$one->name}', [\n $colDefinitions \n\t\t]);",
]);
}
public function CreateFk(ForeignKey $one)
{
$fkName = $this->CreateFkName($one);
$this->renderTemplate([
'name' => "add_fk_{$one->table}_{$one->column}",
'code' => "\$this->addForeignKey('{$fkName}', '{$one->table}', '{$one->column}', '{$one->refTable}', '{$one->refColumn}', '{$one->onDelete}', '{$one->onUpdate}');",
]);
}
public function migrate($execute = false)
{
// TODO: Implement migrate() method.
}
}<file_sep>/src/Schema/Schema.php
<?php
namespace Owlcoder\OwlOrm\Schema;
use Owlcoder\OwlOrm\Schema\providers\SchemaProvider;
class Schema
{
/** @var Table[] */
public $tables = [];
/** @var SchemaProvider */
public $schemaProvider;
/**
* Schema constructor.
* @param SchemaProvider $schemaProvider
*/
public function __construct($schemaProvider)
{
$this->schemaProvider = $schemaProvider;
}
/**
* Найти таблицу
* @param $name
* @return null|Table
*/
public function getTable($name)
{
if (isset($this->tables[$name])) {
return $this->tables[$name];
}
$this->tables[$name] = $this->schemaProvider->getTable($name);
return $this->tables[$name];
}
public function getTableNames()
{
return $this->schemaProvider->getTableNames();
}
/**
* Добавить таблицу в схему
* @param Table $table
* @throws \Exception
*/
public function addTable(Table $table)
{
if (empty($table->name)) {
throw new \Exception('Table name can not be empty');
}
$this->tables[$table->name] = $table;
}
/**
* Получить информацию о зависимости колонки
* @param Column $column
* @return ForeignKey[]
*/
public function getColumnDependency(Column $column)
{
$output = [];
foreach ($this->tables as $table) {
foreach ($table->fks as $fk) {
if ($fk->refTable == $column->table->name && $fk->refColumn == $column->name) {
$output[] = $fk;
}
}
}
return $output;
}
}<file_sep>/src/Schema/SchemaCompare.php
<?php
namespace Owlcoder\OwlOrm\Schema;
use Owlcoder\OwlOrm\Schema\providers\MysqlSchemaProvider;
class SchemaCompare extends BaseObject
{
/** @var DbConnectionParams */
public $dbConnectionParams;
/** @var Database */
public $database;
/** @var Schema */
public $schema1;
/** @var Schema */
public $schema2;
/** @var Table[] */
public $dropTables = [];
/** @var Table[] */
public $createTables = [];
/** @var Column[] */
public $createColumns = [];
/** @var Column[] */
public $dropColumns = [];
/** @var Column */
public $alterColumns = [];
/** @var MysqlSchemaProvider */
public $sqlProvider;
public $addFks = [];
public $dropFks = [];
public $queries = [];
/** @var SchemaGenerator */
public $generator;
public function array_swap(array &$array, $key, $key2)
{
if (isset($array[$key]) && isset($array[$key2])) {
list($array[$key], $array[$key2]) = array($array[$key2], $array[$key]);
return true;
}
return false;
}
/**
* Clear comparator
*/
public function clear()
{
$this->createColumns = [];
$this->dropColumns = [];
$this->alterColumns = [];
$this->createTables = [];
$this->dropTables = [];
$this->dropFks = [];
$this->addFks = [];
}
/** @return SchemaGenerator */
public function compare()
{
// Проверка таблиц из первой схемы
foreach ($this->schema1->tables as $table1) {
$table2 = $this->schema2->getTable($table1->name);
if ($table2 == null) {
// во второй схеме нет таблицы, нужно удалить её из первой базы
$table1->delete = true;
$this->dropTables[] = $table1;
continue;
}
// наличие колонки во второй таблице
foreach ($table1->columns as $column1) {
$column2 = $table2->getColumn($column1->name);
if ($column2 == null) {
$column1->delete = true;
$this->dropColumns[] = $column1; // Колонки больше нет - удалить
} else if ( ! $column1->compare($column2)) {
// Колонки не одинаковые пересоздать
$this->alterColumns[] = $column2;
$len = count($this->alterColumns);
for ($i = 0; $i < $len - 1; $i++) {
// Если колонка участвует в FK, то необходимо удалить fk и добавить заново
$fk = $column2->isDependOf($this->alterColumns[$i]);
if ($fk !== false) {
$fk->name = $this->database->getFkNameFromDb($fk);
$this->dropFks[] = $fk;
$this->addFks[] = $fk;
}
}
}
}
// новые колонки
foreach ($table2->columns as $column2) {
if ($table1->getColumn($column2->name) == null) {
// нужно создать новую колонку в исходной базе и проверить, нужно ли создавать fk
$this->createColumns[] = $column2;
}
}
}
// проверка таблиц из второй схемы
foreach ($this->schema2->tables as $table2) {
$table1 = $this->schema1->getTable($table2->name);
if ($table1 == null) {
$this->createTables[] = $table2; // Таблица новая - создать
continue;
}
}
// Удаление старых ключей
foreach ($this->schema1->tables as $table1) {
if ( ! $table1->delete) { // зачем второй раз проходиться
$table2 = $this->schema2->getTable($table1->name);
foreach ($table1->fks as &$fk1) {
if ($table2->getFk($fk1) === false) {
$fk1->name = $this->database->getFkNameFromDb($fk1);
$this->dropFks[] = $fk1;
}
}
}
}
// Создание новых ключей
foreach ($this->schema2->tables as $table2) {
if ( ! $table2->delete) { // зачем второй раз проходиться
$table1 = $this->schema1->getTable($table2->name);
foreach ($table2->fks as $_fk1) {
if ($table1 == null) {
$this->addFks[] = $_fk1;
continue;
}
$otherFk = $table1->getFk($_fk1);
if ($otherFk === false || $table1 == null) {
$this->addFks[] = $_fk1;
} else if ( ! $otherFk->compare($_fk1)) {
// recreate constraint
$otherFk->name = $this->database->getFkNameFromDb($otherFk);
$this->dropFks[] = $otherFk;
$this->addFks[] = $_fk1;
}
}
}
}
$this->run();
$this->prepareStatement();
return $this->generator;
}
public function prepareStatement()
{
foreach ($this->dropFks as $one) {
$this->generator->DropFk($one);
}
foreach ($this->dropColumns as $one) {
$this->generator->DropColumn($one);
}
foreach ($this->dropTables as $one) {
$this->generator->DropTable($one);
}
foreach ($this->alterColumns as $one) {
$this->generator->AlterColumn($one);
}
foreach ($this->createColumns as $one) {
$this->generator->AddColumn($one);
}
foreach ($this->createTables as $one) {
$this->generator->CreateTable($one);
}
foreach ($this->addFks as $one) {
$this->generator->CreateFk($one);
}
}
public function run()
{
/**
* При удалении таблицы, нужно посмотреть не зависят ли от неё другие.
* при этом, если находятся зависимые колонки в неудалённой таблице, они должны быть помечены удалёнными или
* сама таблица должена быть помечена удалённой.
* Если хотя-бы одна колонка не помечена, как удалённая, то выбросить ошибку
*
* При выполнении скрипта, сначала удаляются колонки, при этом идёт свап зависимых колонок между собой
* Далее удаляются таблицы, также обеспечивая свап между собой.
*
* Добавляются новые колонки существующих таблиц
* добавляются новые таблицы
* Добавляются ключи
*/
$changed = true;
while ($changed) {
$changed = false;
// Удаляем таблицы к чертям
foreach ($this->dropTables as $k1 => $table) {
foreach ($table->columns as $column) {
$colDependencies = $this->schema1->getColumnDependency($column);
foreach ($colDependencies as $dependencyColumn) {
$t1 = $this->schema1->getTable($dependencyColumn->table);
// А теперь делаем правильный порядок удаления
$k1 = $this->searchArrayKey($this->dropTables, $table);
$k2 = $this->searchArrayKey($this->dropTables, $t1);
if ($k1 != -1 && $k2 != -1 && $k1 < $k2) {
$changed = true;
$this->array_swap($this->dropTables, $k1, $k2);
break 2;
}
}
}
}
}
// Создаём новые таблички
foreach ($this->createTables as $k1 => $table) {
foreach ($table->columns as $column) {
$colDependencies = $this->schema1->getColumnDependency($column);
foreach ($colDependencies as $dependencyColumn) {
$t1 = $this->schema2->getTable($dependencyColumn->table);
// А теперь делаем правильный порядок удаления
$k1 = $this->searchArrayKey($this->createTables, $table);
$k2 = $this->searchArrayKey($this->createTables, $t1);
if ($k1 != -1 && $k2 != -1 && $k1 < $k2) {
$this->array_swap($this->createTables, $k1, $k2);
}
}
}
}
}
public function searchArrayKey($arr, $obj)
{
foreach ($arr as $key => $item) {
if ($item->name == $obj->name) {
return $key;
}
}
return -1;
}
}<file_sep>/src/Exceptions/WrongConditionException.php
<?php
namespace Owlcoder\OwlOrm\Exceptions;
class WrongConditionException extends \Exception
{
}<file_sep>/src/Schema/BaseObject.php
<?php
namespace Owlcoder\OwlOrm\Schema;
class BaseObject
{
public function __construct($options = [])
{
foreach ($options as $key => $value) {
$this->$key = $value;
}
}
}<file_sep>/src/Schema/providers/PostgresSchemaProvider.php
<?php
namespace Owlcoder\OwlOrm\Schema\providers;
use Owlcoder\OwlOrm\Schema\Database;
use Owlcoder\OwlOrm\Schema\Table;
use Owlcoder\OwlOrm\Schema\Column;
use Owlcoder\OwlOrm\Schema\ForeignKey;
class PostgresSchemaProvider extends SchemaProvider
{
/** @var Database */
public $database;
public $typeConfig = 'mysql';
/**
* @param $columnInfo
* @return Column
*/
public function prepareColumn($columnInfo)
{
$length = null;
$columnModel = new Column;
$columnModel->name = $columnInfo['Field'];
$dbtype = $this->parseFuncString($columnInfo['Type']);
if ($dbtype != null) {
list($dbtype, $length) = $dbtype;
} else {
$dbtype = $columnInfo['Type'];
}
if (strpos($dbtype, 'unsigned') !== false) {
$dbtype = trim(str_replace('unsigned', '', $dbtype));
$columnModel->unsigned = true;
}
$columnModel->dbType = $dbtype;
$columnModel->length = $length != null ? $length : null;
$columnModel->notNull = $columnInfo['Null'] == 'NO';
$columnModel->default = $columnInfo['Default'];
// if($columnModel->default !== null){
// echo var_dump($columnModel->default);
// }
$columnModel->extra = $columnInfo['Extra'];
return $columnModel;
}
/**
* @param $tableName
* @return Table|bool
*/
public function prepareTable($tableName)
{
$tableModel = new Table();
$tableModel->name = $tableName;
$columnsInfo = $this->database->getTableInfo($tableName);
if ($columnsInfo === false) {
return false;
}
foreach ($columnsInfo as $columnInfo) {
$columnModel = $this->prepareColumn($columnInfo);
$columnModel->table = $tableModel;
$tableModel->addColumn($columnModel);
}
return $tableModel;
}
public function prepareSchema()
{
foreach ($this->database->getTableNames() as $tableName) {
$tableModel = $this->prepareTable($tableName);
if ($tableModel !== false) {
// Обратная ссылка на схему
$tableModel->schema = $this->schema;
$this->schema->addTable($tableModel);
}
}
$this->fetchFkConstraints();
}
public function fetchFkConstraints()
{
$rows = $this->database->fetchFkConstraints();
foreach ($rows as $row) {
$tableModel = $this->schema->getTable($row['TABLE_NAME']);
if($tableModel == null){
throw new \Exception('table can not be null if constraint exists');
}
if ($row['CONSTRAINT_NAME'] == 'PRIMARY') {
$tableModel->pk = [$row['COLUMN_NAME']];
} else {
if (isset($row['TABLE_NAME'])
&& isset($row['COLUMN_NAME'])
&& isset($row['REFERENCED_TABLE_NAME'])
&& isset($row['REFERENCED_COLUMN_NAME'])
) {
$col = $tableModel->getColumn($row['COLUMN_NAME']);
$fk = new ForeignKey([
'table' => $row['TABLE_NAME'],
'column' => $row['COLUMN_NAME'],
'refTable' => $row['REFERENCED_TABLE_NAME'],
'refColumn' => $row['REFERENCED_COLUMN_NAME'],
'onDelete' => strtolower($row['DELETE_RULE']),
'onUpdate' => strtolower($row['UPDATE_RULE']),
]);
$col->fks[] = $fk;
$tableModel->fks[] = $fk;
}
}
}
}
public function fetchIndexes()
{
}
}<file_sep>/src/Schema/Database.php
<?php
namespace Owlcoder\OwlOrm\Schema;
use Owlcoder\OwlOrm\Orm\QueryBuilders\MysqlQueryBuilder;
use Owlcoder\OwlOrm\Schema\providers\MysqlSchemaProvider;
use PDO;
class Database
{
/** @var PDO */
public $conn;
/** @var string */
public $dsn;
/** @var DbConnectionParams */
public $dbConnectionParams;
public function __construct(array $options = [])
{
$this->dbConnectionParams = new DbConnectionParams($options);
$this->dsn = "{$this->dbConnectionParams->driver}:host={$this->dbConnectionParams->host};dbname={$this->dbConnectionParams->database}";
$this->conn = new PDO($this->dsn, $this->dbConnectionParams->user, $this->dbConnectionParams->password, [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
]);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
/**
* @return Schema
*/
public function getSchema()
{
return new Schema(new MysqlSchemaProvider($this));
}
public function execStatement($sql, $params = [])
{
$st = $this->conn->prepare($sql);
$st->execute($params);
return $st;
}
public function first($sql, $params = [])
{
$st = $this->execStatement($sql, $params);
return $st->fetch();
}
public function all($sql, $params = [])
{
$st = $this->execStatement($sql, $params);
return $st->fetchAll();
}
public function column($sql, $params = [])
{
$st = $this->execStatement($sql, $params);
$items = [];
while ($item = $st->fetchColumn()) {
$items[] = $item;
}
return $items;
}
public function scalar($sql, $params = [])
{
$st = $this->execStatement($sql, $params);
return $st->fetchColumn();
}
public function getBuilderClass()
{
return [
'mysql' => MysqlQueryBuilder::class,
][$this->dbConnectionParams->driver];
}
}<file_sep>/tests/Models/UserRole.php
<?php
namespace Owlcoder\OwlOrm\Tests\Models;
/**
* @Column(id)
* @TableName(user)
*
* Class User
*/
class UserRole extends BaseModel
{
public $_table = 'tbl_person_role';
}<file_sep>/tests/test.sh
./vendor/bin/phpunit tests/OrmModelTest.php --bootstrap=tests/bootstrap.php<file_sep>/tests/bootstrap.php
<?php
require __DIR__ . '/../vendor/autoload.php';
\Owlcoder\OwlOrm\Tests\Models\BaseModel::InitConnection([
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'portal',
'username' => 'root',
'password' => '<PASSWORD>',
]);<file_sep>/tests/OrmModelTest.php
<?php
use PHPUnit\Framework\TestCase;
class OrmModelTest extends TestCase
{
public function testFetchAll()
{
$model = \Owlcoder\OwlOrm\Tests\Models\User::query()
->where(['=', 'email', '<EMAIL>'])->all();
$this->assertTrue(count($model) == 1);
}
public function testRelationAndFetchFirst()
{
$model = \Owlcoder\OwlOrm\Tests\Models\User::query()
->where(['=', 'email', '<EMAIL>'])->first();
$this->assertTrue($model instanceof \Owlcoder\OwlOrm\Tests\Models\User);
$this->assertTrue($model instanceof \Owlcoder\OwlOrm\Tests\Models\User);
}
public function testLimit()
{
$model = \Owlcoder\OwlOrm\Tests\Models\User::query()->limit(1)->all();
$this->assertCount(1, $model);
}
public function testOrderAndInCondition()
{
$model = \Owlcoder\OwlOrm\Tests\Models\User::query()->orderBy('id desc')->where(['id' => [21, 22, 23]])->all();
$this->assertCount(3, $model);
$this->assertTrue($model[0]->id == 23);
}
public function testCount()
{
$cnt = \Owlcoder\OwlOrm\Tests\Models\User::query()->where(['id' => [21, 22, 23]])->count();
$this->assertEquals($cnt, 3);
}
}<file_sep>/tests/Models/BaseModel.php
<?php
namespace Owlcoder\OwlOrm\Tests\Models;
use Owlcoder\OwlOrm\Orm\Relations\HasManyRelation;
class BaseModel extends \Owlcoder\OwlOrm\Orm\OrmModel
{
}<file_sep>/src/Schema/config/type-mappings.php
<?php
return [
'mysql' => [
'int' => 'integer',
'varchar' => 'string',
'text' => 'text',
'tinyint' => 'tinyint',
'blob' => 'blob',
'timestamp' => 'timestamp',
'char' => 'cstring',
'datetime' => 'datetime',
'longblob' => 'lblob',
'bit' => 'bit',
'date' => 'date',
'float' => 'float',
'double' => 'double',
'decimal' => 'decimal',
'longtext' => 'longtext',
'smallint' => 'sinteger',
],
];<file_sep>/src/Schema/DbSchemaHelper.php
<?php
namespace Owlcoder\OwlOrm\Schema;
class DbSchemaHelper
{
public $conn;
public $database = 'portal';
public $schema;
public function getTableNames(){
$q = "show tables";
$res = mysqli_query($this->conn, $q);
return array_map(function($item){ return $item[0]; }, mysqli_fetch_all($res));
}
protected function fetchAllAssoc($res){
$output = [];
while($row = mysqli_fetch_assoc($res)){
$output[] = $row;
}
return $output;
}
public function getTableInfo($table){
$res = mysqli_query($this->conn, 'describe ' . $table);
if($res === false){
return false;
// throw new Exception('false result for table ' . $table);
}
return $this->fetchAllAssoc($res);
}
public function getForeignKeys($table){
$q = "
SELECT
TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
TABLE_SCHEMA = '{$this->database}' AND
TABLE_NAME = '{$table}';
";
$res = mysqli_query($this->conn, $q);
return $this->fetchAllAssoc($res);
}
}<file_sep>/src/Schema/ForeignKey.php
<?php
namespace Owlcoder\OwlOrm\Schema;
class ForeignKey extends BaseObject
{
public $table;
public $column;
public $refTable;
public $refColumn;
public $onDelete = null;
public $onUpdate = null;
public $name;
public function compare(ForeignKey $otherFk){
$fields = ['table', 'column', 'refTable', 'refColumn', 'onDelete', 'onUpdate'];
foreach($fields as $field){
$eq = $this->$field == $otherFk->$field;
if (!$eq){
echo "compare field {$otherFk->name} mismatch $field\n";
return false;
}
}
return true;
}
}<file_sep>/src/Exceptions/PropertyDoesNotExists.php
<?php
namespace Owlcoder\OwlOrm\Exceptions;
class PropertyDoesNotExists extends \Exception
{
}<file_sep>/src/Schema/commands/DbCommand.php
<?php
namespace Owlcoder\OwlOrm\Schema\commands;
use Owlcoder\OwlOrm\Schema\Database;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Common class for commands which use database
* Class DbCommand
* @package Owlcoder\OwlOrm\Schema\commands
*/
class DbCommand extends Command
{
/** @var Database */
public $db;
/** @var string */
public $path;
/**
* @inheritdoc
*/
protected function configure()
{
$this->setName('unknown')
->setDescription('get schema from db and write it to yml file')
->addArgument('path', InputArgument::REQUIRED, 'path to save yml')
->addOption('host', 'l', InputArgument::OPTIONAL, 'database host', 'localhost')
->addOption('user', 'u', InputArgument::OPTIONAL, 'database user', 'root')
->addOption('password', 'w', InputArgument::OPTIONAL, 'database password', '')
->addOption('port', 'p', InputArgument::OPTIONAL, 'database port', '')
->addArgument('database',InputArgument::REQUIRED, 'database name')
;
}
/**
* @inheritdoc
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->db = new Database([
'database' => $input->getArgument('database'),
'user' => $input->getOption('user'),
'password' => $input->getOption('<PASSWORD>'),
'port' => (int)$input->getOption('port'),
'host' => $input->getOption('host'),
]);
$this->path = $input->getArgument('path');
}
}
|
de62c01db725211b30f11219b11aaa75be917e80
|
[
"Markdown",
"PHP",
"Shell"
] | 42
|
PHP
|
owlcoder13/OwlOrm
|
d7b6495c218c0d47f2cf64d0df4025710fdf66d4
|
925a6d6a888a1e6f75377f741221fce0867331eb
|
refs/heads/master
|
<repo_name>slinkymoose/ComputerVisionEdge-HeroCategorizer<file_sep>/CV_Edge/Assets/HeroModel.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Media;
using Windows.Storage;
using Windows.AI.MachineLearning.Preview;
// 6fba5602-2416-4582-8f3b-931bc0eadc24_c97c9b55-21f5-48b8-9a25-83f235a0d8d7
namespace CV_Edge
{
public sealed class _x0036_fba5602_x002D_2416_x002D_4582_x002D_8f3b_x002D_931bc0eadc24_c97c9b55_x002D_21f5_x002D_48b8_x002D_9a25_x002D_83f235a0d8d7ModelInput
{
public VideoFrame data { get; set; }
}
public sealed class _x0036_fba5602_x002D_2416_x002D_4582_x002D_8f3b_x002D_931bc0eadc24_c97c9b55_x002D_21f5_x002D_48b8_x002D_9a25_x002D_83f235a0d8d7ModelOutput
{
public IList<string> classLabel { get; set; }
public IDictionary<string, float> loss { get; set; }
public _x0036_fba5602_x002D_2416_x002D_4582_x002D_8f3b_x002D_931bc0eadc24_c97c9b55_x002D_21f5_x002D_48b8_x002D_9a25_x002D_83f235a0d8d7ModelOutput()
{
this.classLabel = new List<string>();
this.loss = new Dictionary<string, float>()
{
{ "Batman", float.NaN },
{ "Superman", float.NaN },
};
}
}
public sealed class _x0036_fba5602_x002D_2416_x002D_4582_x002D_8f3b_x002D_931bc0eadc24_c97c9b55_x002D_21f5_x002D_48b8_x002D_9a25_x002D_83f235a0d8d7Model
{
private LearningModelPreview learningModel;
public static async Task<_x0036_fba5602_x002D_2416_x002D_4582_x002D_8f3b_x002D_931bc0eadc24_c97c9b55_x002D_21f5_x002D_48b8_x002D_9a25_x002D_83f235a0d8d7Model> Create_x0036_fba5602_x002D_2416_x002D_4582_x002D_8f3b_x002D_931bc0eadc24_c97c9b55_x002D_21f5_x002D_48b8_x002D_9a25_x002D_83f235a0d8d7Model(StorageFile file)
{
LearningModelPreview learningModel = await LearningModelPreview.LoadModelFromStorageFileAsync(file);
_x0036_fba5602_x002D_2416_x002D_4582_x002D_8f3b_x002D_931bc0eadc24_c97c9b55_x002D_21f5_x002D_48b8_x002D_9a25_x002D_83f235a0d8d7Model model = new _x0036_fba5602_x002D_2416_x002D_4582_x002D_8f3b_x002D_931bc0eadc24_c97c9b55_x002D_21f5_x002D_48b8_x002D_9a25_x002D_83f235a0d8d7Model();
model.learningModel = learningModel;
return model;
}
public async Task<_x0036_fba5602_x002D_2416_x002D_4582_x002D_8f3b_x002D_931bc0eadc24_c97c9b55_x002D_21f5_x002D_48b8_x002D_9a25_x002D_83f235a0d8d7ModelOutput> EvaluateAsync(_x0036_fba5602_x002D_2416_x002D_4582_x002D_8f3b_x002D_931bc0eadc24_c97c9b55_x002D_21f5_x002D_48b8_x002D_9a25_x002D_83f235a0d8d7ModelInput input) {
_x0036_fba5602_x002D_2416_x002D_4582_x002D_8f3b_x002D_931bc0eadc24_c97c9b55_x002D_21f5_x002D_48b8_x002D_9a25_x002D_83f235a0d8d7ModelOutput output = new _x0036_fba5602_x002D_2416_x002D_4582_x002D_8f3b_x002D_931bc0eadc24_c97c9b55_x002D_21f5_x002D_48b8_x002D_9a25_x002D_83f235a0d8d7ModelOutput();
LearningModelBindingPreview binding = new LearningModelBindingPreview(learningModel);
binding.Bind("data", input.data);
binding.Bind("classLabel", output.classLabel);
binding.Bind("loss", output.loss);
LearningModelEvaluationResultPreview evalResult = await learningModel.EvaluateAsync(binding, string.Empty);
return output;
}
}
}
<file_sep>/CV_Edge/MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Windows.Input;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Imaging;
using Windows.Media;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using Prism.Commands;
using PropertyChanged;
namespace CV_Edge
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
[AddINotifyPropertyChangedInterface]
public sealed partial class MainPage : Page
{
private const string ModelPath = @"ms-appx:///Assets/HeroModel.onnx";
public HeroModelInput ModelInput { get; set; } = new HeroModelInput();
public HeroModelOutput ModelOutput { get; set; } = new HeroModelOutput();
public HeroModel Model { get; set; } = new HeroModel();
public ICommand AnalyzeCommand { get; set; }
public ICommand BrowseCommand { get; set; }
public string Results { get; set; }
public MainPage()
{
this.InitializeComponent();
this.DataContext = this;
AnalyzeCommand = new DelegateCommand(AnalyzeImage);
BrowseCommand = new DelegateCommand(BrowseForImage);
LoadModel();
}
private async void LoadModel()
{
var modelFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(ModelPath));
Model = await HeroModel.CreateHeroModel(modelFile);
}
private async void BrowseForImage()
{
Results = "Press Analyze to process image...";
var picker = new FileOpenPicker
{
ViewMode = PickerViewMode.Thumbnail,
SuggestedStartLocation = PickerLocationId.PicturesLibrary
};
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
var file = await picker.PickSingleFileAsync();
if (file != null)
{
using (IRandomAccessStream fileStream =
await file.OpenAsync(FileAccessMode.Read))
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(fileStream);
MainImage.Source = bitmapImage;
}
}
}
private async void AnalyzeImage()
{
var rtBitmap = new RenderTargetBitmap();
await rtBitmap.RenderAsync(MainImage);
var buffer = await rtBitmap.GetPixelsAsync();
var softwareBitmap = SoftwareBitmap.CreateCopyFromBuffer(buffer, BitmapPixelFormat.Bgra8,
rtBitmap.PixelWidth, rtBitmap.PixelHeight);
buffer = null;
rtBitmap = null;
var frame = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap);
//var croppedFrame = await CropAndDisplayInputImageAsync(frame);
ModelInput.data = frame;
ModelOutput = await Model.EvaluateAsync(ModelInput);
if (ModelOutput.classLabel.Count > 0)
{
Results = $"{ModelOutput.classLabel.First()} - ";
}
else
{
Results = "could not identify image";
}
}
}
}
|
d09711f8e2fefff19b481c81b1cb8ed832e638da
|
[
"C#"
] | 2
|
C#
|
slinkymoose/ComputerVisionEdge-HeroCategorizer
|
c4848ed5b910317baa97af96eb4182fd07227496
|
7d434a152bf5f0b18c0963217e30631d076040b3
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebStore.ViewModels
{
public class EmployeeView
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[Display(Name = "Имя")]
public string FirstName { get; set; }
[Display(Name = "Фамилия")]
public string SecondName { get; set; }
[Display(Name = "Отчество")]
public string Patronymic { get; set; }
[Display(Name = "Возраст")]
public int Age { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Internal;
using WebStore.ViewModels;
namespace WebStore.Controllers
{
public class EmployeesController : Controller
{
private static readonly List<EmployeeView> __Employees = new List<EmployeeView>
{
new EmployeeView { Id = 1, SecondName = "Иванов", FirstName = "Иван", Patronymic = "Иванович", Age = 35 },
new EmployeeView { Id = 2, SecondName = "Петров", FirstName = "Пётр", Patronymic = "Петрович", Age = 25 },
new EmployeeView { Id = 3, SecondName = "Сидоров", FirstName = "Сидор", Patronymic = "Сидорович", Age = 18 },
};
public IActionResult Index()
{
ViewBag.SomeData = "Hello World!";
ViewData["Test"] = "TestData";
return View(__Employees);
}
public IActionResult Details(int? Id)
{
if (Id is null)
return BadRequest();
var employee = __Employees.FirstOrDefault(e => e.Id == Id);
if (employee is null)
return NotFound();
return View(employee);
}
public IActionResult DetailsName(string FirstName, string LastName)
{
if (FirstName is null && LastName is null)
return BadRequest();
IEnumerable<EmployeeView> employees = __Employees;
if (!string.IsNullOrWhiteSpace(FirstName))
employees = employees.Where(e => e.FirstName == FirstName);
if (!string.IsNullOrWhiteSpace(LastName))
employees = employees.Where(e => e.SecondName == LastName);
var employee = employees.FirstOrDefault();
if (employee is null)
return NotFound();
return View(nameof(Details), employee);
}
[HttpPost]
public IActionResult Edit(int id, [FromBody] EmployeeView Employee)
{
return RedirectToAction(nameof(Index));
}
}
}
|
0c9aa3127ca4f9edeb498a95fdc5e0f1d6588537
|
[
"C#"
] | 2
|
C#
|
VenenS/WebStore
|
d7758a358e0c6a2cacda4ab4d5b176959de56ab5
|
24b86380cc6aec43cda07fd067a6f6b3fe4217bf
|
refs/heads/master
|
<file_sep>package br.com.eventoapp.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class EventoController {
@RequestMapping("/cadastrarEvento")
public ModelAndView form() {
return new ModelAndView("evento/formEvento");
}
}
|
9a03f205a72116f79605da32eb9fe46382ed077a
|
[
"Java"
] | 1
|
Java
|
KelvySilva/eventoapp
|
c9c9f64453e685015b777c941cd3a7d87b712ae4
|
6bca1ffda309346eae4619b5c0bf039b5c59f970
|
refs/heads/master
|
<file_sep>function TPL(html, data) {
for (var i in data) {
html = html.replace(new RegExp('{{\\s*' + i + '\\s*}}', 'g'), data[i]);
}
return html;
}
function urlQuery() {
if (location.search) {
var q = decodeURIComponent(location.search.substr(1));
var obj = {};
q.split('&').forEach(function(v) {
var t = v.split('=');
obj[t[0]] = t[1];
});
return obj;
}
return {};
}
<file_sep>var APIURL = 'http://zhufu.sinaapp.com/api';
var ls = window.localStorage;
var VERSION = chrome.runtime.getManifest().version;
var ss = window.sessionStorage;
<file_sep>var ls = window.localStorage;
var ss = window.sessionStorage;
var ID = (+new Date());
var VERSION = chrome.runtime.getManifest().version;
// var MAX_NOTIFY = 6;
//从localstorage读取设置
var settings = ls.settings ? ls.settings : '{}';
//关键词
var keywords = ls.keywords ? ls.keywords : '[]';
//静默时间
var quietTimer = ls.quietTimer ? ls.quietTimer : '';
quietTimer = quietTimer.split('-');
if (quietTimer.length !== 2) {
quietTimer = false;
} else if ((quietTimer[0] | 0) >= (quietTimer[1] | 0)) {
quietTimer = false;
} else {
quietTimer = [quietTimer[0] | 0, quietTimer[1] | 0];
}
try {
settings = JSON.parse(settings);
} catch (e) {
settings = {};
ls.settings = '{}';
}
try {
keywords = JSON.parse(keywords);
} catch (e) {
keywords = [];
ls.keywords = '[]';
}
settings = $.extend({
openKeyword: true,
openMusic: true,
beQuiet: true,
openNotice: true
}, settings);
var emptyFn = function() {};
var feedTimer, noticeTimer;
var feedInterval = 113000;
var noticeInterval = 113000;
var curmaxid = ls.maxCnDealId;
if (!curmaxid) {
chrome.browserAction.setBadgeBackgroundColor({
color: [255, 68, 68, 255]
});
chrome.browserAction.setBadgeText({
text: '+'
});
chrome.browserAction.setTitle({
title: '里面这么多好东西您不点开看,鼠标在这悬着干嘛啊您!'
});
} else {
checkNewFeed();
}
feedTimer = setInterval(checkNewFeed, feedInterval);
function checkNewFeed() {
var curmaxidloop = ls.maxCnDealId ? ls.maxCnDealId : 0;
$.get('http://zhufu.sinaapp.com/api/newfeed.php?v=' + VERSION + '&id=' + curmaxidloop, function(data) {
if (data > 99) {
//不再更新
clearInterval(feedTimer);
feedTimer = null;
chrome.browserAction.setBadgeBackgroundColor({
color: [255, 68, 68, 255]
});
chrome.browserAction.setBadgeText({
text: '99+'
});
chrome.browserAction.setTitle({
title: '更新条数太多了,您快来看看吧'
});
} else if (data > 0) {
chrome.browserAction.setBadgeBackgroundColor({
color: [255, 68, 68, 255]
});
chrome.browserAction.setBadgeText({
text: data
});
chrome.browserAction.setTitle({
title: '您上次看过以后,这都' + data + '条儿更新了'
});
}
});
}
chrome.runtime.onMessage.addListener(function(obj, sender, callback) {
switch (obj.action) {
case 'startFeedTimer':
//如果收到popup的消息,并且通知类型是显示数字
if (!feedTimer /*&& ls.noticeType === 'number'*/ ) {
feedTimer = setInterval(checkNewFeed, feedInterval);
}
break;
case 'updateQuietTimer':
quietTimer = ls.quietTimer ? ls.quietTimer : '';
quietTimer = quietTimer.split('-');
if (quietTimer.length !== 2) {
quietTimer = false;
ls.removeItem('quietTimer');
} else if ((quietTimer[0] | 0) >= (quietTimer[1] | 0)) {
quietTimer = false;
ls.removeItem('quietTimer');
} else {
quietTimer = [quietTimer[0] | 0, quietTimer[1] | 0];
}
break;
case 'startNotice':
if (!noticeTimer) {
noticeTimer = setInterval(checkKeyWordNotice, noticeInterval);
}
break;
case 'updateSwitch':
try {
settings = JSON.parse(ls.settings);
if (obj.id === 'beQuiet' && obj.value === true) {
ls.removeItem('quietTimer');
}
} catch (e) {}
break;
case 'updateKeyword':
try {
keywords = JSON.parse(ls.keywords);
} catch (e) {}
break;
}
});
noticeTimer = setInterval(checkKeyWordNotice, noticeInterval);
function checkKeyWordNotice() {
if (!settings.openNotice && (keywords.length === 0 || !settings.openKeyword)) {
//没有打开提醒,并且关键词也没打开
return;
}
var maxnotifyid = ls.maxnotifyid;
if (!maxnotifyid) {
maxnotifyid = 0;
}
var MAX_NOTIFY = ls.MAX_NOTIFY;
if (!ls.MAX_NOTIFY) {
//默认弹窗数量为6
MAX_NOTIFY = 3;
} else if (ls.MAX_NOTIFY === 'ALL') {
MAX_NOTIFY = 30;
} else {
MAX_NOTIFY |= 0;
if (MAX_NOTIFY === 0) {
MAX_NOTIFY = 3;
}
}
$.getJSON('http://zhufu.sinaapp.com/api/getdata.php?v=' + VERSION + '&t=' + (+new Date()) + '&page=1&maxnotifyid=' + maxnotifyid, function(json) {
if (json.errno === 0) {
var kw;
ls.maxnotifyid = json.maxid;
var play = false;
var notifyCount = 1;
json.data.forEach(function(v) {
var id, opt;
var now = Date.now();
//订阅关键字,保证最多弹MAX_NOTIFY个
if (keywords.length && settings.openKeyword && notifyCount <= MAX_NOTIFY) {
kw = searchKeywords(v.title, v.mallname);
// console.log(kw);
if (kw) {
v.keyword = kw;
var t = kw.split('+'),
title;
if (t.length === 2) {
title = '在【' + t[1] + '】找到【' + t[0] + '】的折扣信息';
} else {
title = '找到【' + kw + '】的折扣信息';
}
opt = {
type: 'basic',
title: title,
message: v.title,
iconUrl: v.img,
buttons: [{
title: '立即去抢购 >>',
iconUrl: 'img/icon64.png'
}, {
title: '设置消息提醒 >>',
iconUrl: 'img/options.png'
}]
};
id = 'kw' + (now++);
chrome.notifications.create(id, opt, function() {
//存入sessionStorage
ss[id] = JSON.stringify(v);
if (!play) {
playNotificationSound();
}
play = true;
});
notifyCount++;
}
}
if (settings.openNotice && notifyCount <= MAX_NOTIFY) {
var hour = new Date().getHours();
hour = hour | 0;
var cb = function() {
opt = {
type: 'basic',
title: v.title,
message: v.detail.slice(0, 30) + '..',
iconUrl: v.img,
buttons: [{
title: '立即去抢购 >>',
iconUrl: 'img/icon64.png'
}, {
title: '设置消息提醒 >>',
iconUrl: 'img/options.png'
}]
};
id = 'item' + (now++);
chrome.notifications.create(id, opt, function() {
//存入sessionStorage
ss[id] = JSON.stringify(v);
if (!play) {
playNotificationSound();
}
play = true;
});
notifyCount++;
};
if (!settings.beQuiet) {
//如果没有设置安静时间
// console.log('没有设置安静时间');
cb();
} else if (quietTimer &&
Array.isArray(quietTimer) &&
quietTimer.length === 2 &&
quietTimer[0] < quietTimer[1] &&
(hour >= quietTimer[0] && hour < quietTimer[1])) {
// console.log('在安静时间内');
} else {
// console.log('其他时间');
cb();
}
}
});
}
});
}
chrome.notifications.onClicked.addListener(function(id) {
if (ss[id]) {
try {
var obj = JSON.parse(ss[id]);
if (obj.url) {
chrome.tabs.create({
url: obj.url
});
}
} catch (e) {
ss.removeItem(id);
}
}
});
chrome.notifications.onButtonClicked.addListener(function(id, i) {
if (ss[id]) {
if (i === 0) {
try {
var obj = JSON.parse(ss[id]);
if (obj.url) {
chrome.tabs.create({
url: obj.url
});
}
} catch (e) {
ss.removeItem(id);
}
} else if (i === 1) {
chrome.tabs.create({
url: 'options.html'
});
}
} else if (id.indexOf('install_') === 0 || id.indexOf('update_notify_') === 0) {
if (i === 0) {
chrome.tabs.create({
url: 'options.html'
});
} else if (i === 1) {
chrome.tabs.create({
url: 'help.html'
});
}
}
});
/**
* 判断是否是关键词
* @param {String} q 查询的query
* @param {String} mallname 商城名称
* @return {string} 返回查询到的关键字
*/
function searchKeywords(q, mallname) {
var kw = keywords;
if (kw.length === 0) {
return false;
}
for (var i = 0, len = kw.length; i < len; i++) {
var v = kw[i];
var t = v.split('+');
if (t.length === 2) {
//说明需要判断是否是商城名称
if (q.indexOf(t[0]) !== -1 && mallname.indexOf(t[1].trim()) !== -1) {
return v;
}
} else {
if (q.indexOf(v) !== -1) {
return v;
}
}
}
return false;
}
function playNotificationSound() {
if (settings.beQuiet) {
return;
}
try {
var notifyAudio = new Audio('sound/notify.mp3');
notifyAudio.play();
} catch (e) {}
}
//监控更新
chrome.runtime.onInstalled.addListener(function(details) {
var version = chrome.runtime.getManifest().version;
var opt = {
type: 'basic',
title: '折扣商品实时推送更新了!',
message: '当前版本:v' + version,
iconUrl: 'img/icon128.png'
};
if (details.reason === 'install') {
opt.title = '您已经安装成功【折扣商品实时推送】';
opt.buttons = [{
title: '设置 >>',
iconUrl: 'img/options.png'
}, {
title: '查看帮助 >>',
iconUrl: 'img/question.png'
}];
chrome.notifications.create('install_' + (+new Date()), opt, function() {});
} else if (details.reason === 'update') {
version = chrome.runtime.getManifest().version;
opt.message += '\n1. 增加全部特价商品\n2. 增加定制高级关键词';
opt.buttons = [{
title: '设置 >>',
iconUrl: 'img/options.png'
}, {
title: '查看帮助 >>',
iconUrl: 'img/question.png'
}];
chrome.notifications.create('update_notify_' + (+new Date()), opt, function() {});
}
});
<file_sep>var VERSION = chrome.runtime.getManifest().version;
var API = {
list: 'http://zhufu.sinaapp.com/api/getdata.php?v=' + VERSION + '&page=',
maxid: 'http://zhufu.sinapp.com/api/getmaxid.php?v=' + VERSION
};
var emptyFn = function() {};
var FIRST = true;
$(function() {
var Template = $('#J-template').html();
var $content = $('#J-content');
var $loadmore = $('#J-loadmore');
$('#J-loadBtn').click(function() {
$loadmore.hide();
$loading.show();
$.getJSON(API.list + PAGE).done(append);
});
var $loading = $('#J-loading');
var PAGE = 1;
$('#J-close').click(function() {
window.close();
});
$('#J-refresh').click(function() {
refresh();
return false;
});
function refresh() {
PAGE = 1;
$content.empty();
$loadmore.hide();
$loading.show();
$.getJSON(API.list + PAGE).done(append);
}
$content.delegate('button.buy', 'click', function() {
chrome.tabs.create({
url: $(this).data('link')
});
}).delegate('p.J-desc', 'click', function() {
$(this).find('.J-more').toggle();
});
function append(json, source) {
if (json.errno === 0) {
var now = +new Date();
PAGE++;
var html = '';
// console.log(json.data);
json.data.forEach(function(v) {
var detail = v.detail;
v.detail = detail.slice(0, 80);
v.more = detail.slice(80);
if (!v.more) {
v.more = '';
}
html += TPL(Template, v);
});
$content.append(html);
if (FIRST && json.maxid) {
FIRST = false;
localStorage.maxCnDealId = json.maxid;
chrome.browserAction.setBadgeBackgroundColor({
color: [255, 68, 68, 255]
});
chrome.browserAction.setBadgeText({
text: ''
});
chrome.browserAction.setTitle({
title: '里面条目您都看过了,等有更新了我立马儿通知您!'
});
}
if (source !== 'from cache') {
try {
json.expire = now + 60 * 60 * 2000; //两分钟过期
sessionStorage.newData = JSON.stringify(json);
} catch (e) {}
}
}
$loading.hide();
$loadmore.show();
}
try {
var data = sessionStorage.newData;
data = JSON.parse(data);
var now = +new Date();
if (now < data.expire) {
append(data, 'from cache');
}
} catch (e) {
setTimeout(function() {
$.getJSON(API.list + PAGE).done(append);
}, 50);
}
});
//= include _tpl.js
chrome.runtime.sendMessage({
action: 'startFeedTimer'
}, emptyFn);
|
4574976154da2c72c666c25ce880063bbaeb4de1
|
[
"JavaScript"
] | 4
|
JavaScript
|
bihai/works
|
378cb282d3ccafb3df8ce2951ad5b951844c6211
|
e1a7aa80e99e6085ad94fe0ce1f35076bd927dd5
|
refs/heads/master
|
<repo_name>TheTesla/ATXMega128A4U-Keyboard<file_sep>/KEYBOARD_EXAMPLE2/src/ASF/common/services/usb/class/hid/device/kbd/example/atxmega128a4u_stk600-rc044x/ui.c
/**
* \file
*
* \brief User Interface
*
* Copyright (c) 2011 - 2012 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* 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. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#include <asf.h>
#include "ui.h"
void ui_init(void){}
void ui_powerdown(void){}
void ui_wakeup_enable(void){}
void ui_wakeup_disable(void){}
void ui_wakeup(void){}
void ui_process(uint16_t framenumber)
{
static int32_t i = 0;
i+=1;
switch(i){
case 10:
udi_hid_kbd_down(HID_H);
udi_hid_kbd_up(HID_H);
break;
case 20:
udi_hid_kbd_down(HID_A);
udi_hid_kbd_up(HID_A);
break;
case 30:
udi_hid_kbd_down(HID_L);
udi_hid_kbd_up(HID_L);
break;
case 40:
udi_hid_kbd_down(HID_L);
udi_hid_kbd_up(HID_L);
break;
case 50:
udi_hid_kbd_down(HID_O);
udi_hid_kbd_up(HID_O);
break;
case 60:
udi_hid_kbd_down(HID_SPACEBAR);
udi_hid_kbd_up(HID_SPACEBAR);
break;
case 70:
udi_hid_kbd_down(HID_W);
udi_hid_kbd_up(HID_W);
break;
case 80:
udi_hid_kbd_down(HID_E);
udi_hid_kbd_up(HID_E);
break;
case 90:
udi_hid_kbd_down(HID_L);
udi_hid_kbd_up(HID_L);
break;
case 100:
udi_hid_kbd_down(HID_T);
udi_hid_kbd_up(HID_T);
break;
case 110:
udi_hid_kbd_down(HID_ENTER);
udi_hid_kbd_up(HID_ENTER);
break; case 500:
i = 0;
default:
break;
}
}
void ui_kbd_led(uint8_t value)
{
}
/**
* \defgroup UI User Interface
*
* Human interface on STK600:
* - Led 0 is on when USB line is in IDLE mode, and off in SUSPEND mode
* - Led 1 blinks when USB host has checked and enabled HID Keyboard interface
* - Led 2 displays numeric lock status.
* - Led 3 displays caps lock status.
* - The switch 0 open a note pad application on Windows O.S.
* and send key sequence "Atmel AVR USB Keyboard"
* - The switch 0 can be used to wakeup USB Host in remote wakeup mode.
*
* Setup for STK600:
* - LEDS connector is connected to PORTA
* - SWITCHES are connected to PORTB
* - Warning! The AREF1 jumper must be removed
* because AREF1 connected on PORTB0 overrides switch 0.
*/
|
0880b962b36a9ccec6f9e1cc864491125f9af742
|
[
"C"
] | 1
|
C
|
TheTesla/ATXMega128A4U-Keyboard
|
c88388e70b872d4ec60b6eb68267d1b1d2c7a770
|
8f57600020b27cf328bcc5ea2fcd3937c030608b
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LanguageFeatures.Model;
using Microsoft.AspNetCore.Mvc;
namespace LanguageFeatures.Controllers
{
public class HomeController : Controller
{
public string Index(int input)
{
return string.Format("Index with parameter {0}", input);
}
public string Baum()
{
return "Baum";
}
public ViewResult AutoProperty()
{
Product product = new Product()
{
Name = "Hayek"
};
return View("Result", (object)string.Format("Product name: {0}", product.Name));
}
}
}
|
83f8b890d27d41aec0900de17990844ed58bf9df
|
[
"C#"
] | 1
|
C#
|
m5sgh2a/LanguageFeature
|
4418bd418a05e6f95f7ac46b95d60a370c66250f
|
b6e9ffa8314eb5a3a338875595a87e4ebc446e9a
|
refs/heads/master
|
<file_sep>import pandas as pd
import os
class FileOperation:
@staticmethod
def get_file_list(_input_path: str, _is_recursive: bool = False, _can_return_abspath: bool = False):
"""
指定したフォルダの中のファイルリストを作成し、配列として返す機能
:param _input_path: ファイルリストを取得したいフォルダパス
:param _is_recursive: 指定したフォルダの中にサブフォルダがある場合、そこも検索するか(default:検索しない)
:param _can_return_abspath: 戻り値のファイルパスは絶対パスにするか(default: _input_pathからの相対パス)
:return:
"""
# Exit if input path is file path.
if os.path.isfile(_input_path):
print('[file_operation.py][get_file_list][Warn] Do not input file path.')
exit(1)
# 再帰的に検索
if _is_recursive:
fileList = []
for root, dirs, files in os.walk(_input_path):
for fr in files:
if os.path.isfile(os.path.join(root, fr)):
# return with absolute path.
if _can_return_abspath:
fileList.append(os.path.join(root, fr))
else:
local_root = os.path.split(_input_path)[1]
if os.name == 'nt':
ary = root.split('\\')
else:
ary = root.split('/')
if len(ary[ary.index(local_root)+1:-1]) == 0:
relative_path = './' + fr
else:
relative_path = './' + '/'.join(ary[ary.index(local_root)+1:-1]) + '/' + fr
fileList.append(relative_path)
return fileList
# 再帰的に検索しない
else:
files = os.listdir(_input_path)
return [f for f in files if os.path.isfile(os.path.join(_input_path, f))]
@staticmethod
def detect_char_code(_path: str):
"""
指定したファイルの文字コードを判別して返す機能
:param _path: 文字コードを判別したいファイル
:return: 文字コード
"""
import chardet
with open(_path, mode='rb') as f:
binary = f.readline()
result = chardet.detect(binary)
return result['encoding']
def csv_to_df(self, _path: str, date_convert=False, date_format='YYYY-mm-dd', date_data_loc: int = 0, header=None):
"""
import csv and return the data as DataFrame.
:param _path: csv path
:param date_convert: convert flag if the data contain date format data.
:param date_format: date data format e.g. YYYY-mm-dd
:param date_data_loc: date data column location in csv file.
:param header: row num to use column name (default: None which means no header).
:return: DataFrame
"""
ext = os.path.splitext(_path)[1]
if not ext in ['.csv', '.tsv']:
print('[csv_to_df] Extension must be csv or tsv.')
return None
sep = ',' if ext == '.csv' else '\t'
if date_convert:
my_parser = lambda date: pd.datetime.strptime(date, date_format)
return pd.read_csv(_path, parse_dates=[date_data_loc], sep=sep,
date_parser=my_parser, encoding=self.detect_char_code(_path), header=header)
return pd.read_csv(_path, header=header, sep=sep)
@staticmethod
def df_to_csv(_df: pd.DataFrame, _output_dir: str = './', _output_file: str = 'UtilTool.csv', _encode: str = 'utf8'):
"""
dataframe を csvとして返す処理。
:param _df:
:param _output_dir:
:param _output_file:
:param _encode: char encode type (default: utf-8)
:return:
"""
if os.path.splitext(_output_file)[1] != '.csv':
print('[df_to_csv] Extension must be csv.')
return None
_df.to_csv(os.path.join(_output_dir, _output_file), index=False, encoding=_encode)
@staticmethod
def excel_to_df(_input_path: str, _header: int = 0):
"""
Excel の読み込み
:param _input_path: 入力するExcelのファイルパス
:param _header: ヘッダーの行(0スタート)
:return: Excelデータを格納したDataFrame(読み込めない場合はNone)
"""
if not os.path.splitext(_input_path)[1] in ['.xlsx', '.xls']:
print('[file_operation.py][excel_to_df] Input file must be xlsx or xls.')
exit(1)
entire_row_data = pd.ExcelFile(_input_path)
sheet_names = entire_row_data.sheet_names
if len(sheet_names) == 1: # シートが1つの時
row_data = entire_row_data.parse(sheet_names[0], header=_header)
elif len(sheet_names) > 1: # 複数のシートが存在する場合
print('シートが複数存在します。読み込むシートの番号を下記から選択してください。')
for sht_num in range(len(sheet_names)):
print(str(sht_num) + ' : ' + sheet_names[sht_num])
input_sht_num = input('>>> ')
row_data = entire_row_data.parse(sheet_names[int(input_sht_num)], header=_header)
else:
return None
return row_data
@staticmethod
def df_to_excel(_df: pd.DataFrame, _output_dir: str = './',
_output_file: str = 'output.xlsx', _sheet_name='exported',
_encoding: str = 'utf8', _index: bool=False):
"""
Excelの書き出し
:param _output_dir:
:param _output_file: 出力するExcelのファイル名
:param _df: 出力するデータ(DataFrame型)
:param _sheet_name: exportしたexcelのシート名
:param _encoding: エクスポート時の文字コード(default: utf-8)
:param _index: excel出力時にインデックスもexportするかどうか。
:return: always None
"""
if os.path.splitext(_output_file)[1] != '.xlsx':
print('[df_to_excel] Extension must be xlsx.')
return None
_df.to_excel(os.path.join(_output_dir, _output_file), sheet_name=_sheet_name, index=_index, encoding=_encoding)
@staticmethod
def multiple_df_to_excel(_output_dir: str, _output_file: str, _output_df_list: list or dict):
"""
DataframeをExcelの複数シートに保存する機能。
:param _output_dir: 保存先のディレクトリパス
:param _output_file: 保存するExcelファイル名
:param _output_df_list: Dataframeのリストもしくは辞書型変数。リストだとインデックス番号、辞書型の場合はkey名がシート名になる。
:return:
"""
from pandas import ExcelWriter
with ExcelWriter(os.path.join(_output_dir, _output_file), engine='openpyxl') as writer:
if "list" in str(type(_output_df_list)):
for idx, df in enumerate(_output_df_list):
df.to_excel(writer, 'sheets%s' % idx)
writer.save()
elif 'dict' in str(type(_output_df_list)):
for key in _output_df_list.keys():
_output_df_list[key].to_excel(writer, str(key), index=False)
writer.save()
@staticmethod
def txt_to_ary(_path: str, _encoding: str = 'utf8'):
"""
対象のファイルを1行ごとに配列に格納してreturnする。
改行は配列に入れる際に削除される。
:param _path: 配列に格納したファイルのパス
:param _encoding: file encoding
:return: 1行1要素として格納された配列
"""
_list = []
with open(_path, encoding=_encoding) as f:
for line in f:
_list.append(line.replace('\n', ''))
return _list # type: list
@staticmethod
def ary_to_txt_1D(_list: list,
_output_file: str,
_mode: str,
_encoding: str = 'utf8'):
"""
list型変数を要素ごとにテキストに書き出す。
:param _list: 書き出したい配列LIST
:param _output_file: 書き出し先
:param _mode: 書き込みモード(w:書き出し, x:新規作成&書き込み用に開く, a:末尾に追記)
:param _encoding: 書き込み時の文字コード
:return:
"""
with open(_output_file, _mode, encoding=_encoding) as f:
f.write('\n'.join(_list))
f.write('\n')
f.close()
@staticmethod
def ary_to_txt_2D(_list: list, _output_file: str, _mode: str, _encoding: str = 'utf8'):
"""
:param _list: 書き出したい配列LIST(2次元)
:param _output_file: 書き出し先ファイルパス
:param _mode: 書き込みモード(w:書き出し, x:新規作成&書き込み用に開く, a:末尾に追記)
:param _encoding: 書き込み時の文字コード
:return:
"""
if len([len(v) for v in _list]) >= 3: # return error if the size is more than 3d.
print("[ary_to_txt_2D]: Can not export the list. Your list size is " + str([len(v) for v in _list]))
return None
with open(_output_file, _mode, encoding=_encoding) as f:
for l in _list:
f.write(','.join(l))
f.write('\n')
f.close()
@staticmethod
def dic_to_csv(_dic: dict, _output_file: str, _mode: str, _encoding: str = 'utf8'):
"""
辞書型配列のkeyとvalueを2列のcsvにして書き出す機能。
:param _dic: 書き出したい辞書型配列
:param _output_file: 書き出し先ファイルパス
:param _mode: 書き込みモード(w:書き出し, x:新規作成&書き込み用に開く, a:末尾に追記)
:param _encoding: 書き込み時の文字コード
:return:
"""
if str(type(_dic)) != "<class 'dict'>":
print("[dic_to_txt]: Set _dic as dict type.")
return None
if _output_file.split('.')[-1] != 'csv':
print("[dic_to_txt]: Set _output_file as csv file.")
return None
with open(_output_file, _mode, encoding=_encoding) as f:
for key in _dic.keys():
f.write(str(key) + ',' + str(_dic[key]))
f.write('\n')
f.close()
def excel_to_dic(self, _input_excel_file_path: str):
"""
excelの1列目をkey, 2列目をValueとしてdictionaryに変換する機能
:param _input_excel_file_path:
:return:
"""
if os.path.splitext(_input_excel_file_path)[1] != '.xlsx':
print('[df_to_excel] Extension must be xlsx.')
return None
df = self.excel_to_df(_input_excel_file_path)
dic = {}
for idx, row in df.iterrows():
dic[row.iloc[0]] = row.iloc[1]
return dic
<file_sep>import os
import pandas as pd
class Common:
@staticmethod
def nowtime():
"""
今の時間をstr形式で返すだけの関数
:return:
"""
from datetime import datetime
return str(datetime.now().strftime('%Y%m%d%H%M%S'))
def extract_all_combination(self, _df: pd.DataFrame, _combination_pare_column: list):
"""
データフレームの指定した列内に出現する値の総組合せを配列で返す機能。
まだ試作段階。
:param _df:
:param _combination_pare_column:
:return:
"""
import itertools
num_of_param = len(_combination_pare_column)
return_ary = []
if num_of_param == 2:
p1 = self.remove_duplication(_df[_combination_pare_column[0]].values)
p2 = self.remove_duplication(_df[_combination_pare_column[1]].values)
for _1, _2 in itertools.product(p1, p2):
return_ary.append([_1, _2])
elif num_of_param == 3:
p1 = self.remove_duplication(_df[_combination_pare_column[0]].values)
p2 = self.remove_duplication(_df[_combination_pare_column[1]].values)
p3 = self.remove_duplication(_df[_combination_pare_column[2]].values)
for _1, _2, _3 in itertools.product(p1, p2, p3):
return_ary.append([_1, _2, _3])
elif num_of_param == 4:
p1 = self.remove_duplication(_df[_combination_pare_column[0]].values)
p2 = self.remove_duplication(_df[_combination_pare_column[1]].values)
p3 = self.remove_duplication(_df[_combination_pare_column[2]].values)
p4 = self.remove_duplication(_df[_combination_pare_column[3]].values)
for _1, _2, _3, _4 in itertools.product(p1, p2, p3, p4):
return_ary.append([_1, _2, _3, _4])
elif num_of_param == 5:
p1 = self.remove_duplication(_df[_combination_pare_column[0]].values)
p2 = self.remove_duplication(_df[_combination_pare_column[1]].values)
p3 = self.remove_duplication(_df[_combination_pare_column[2]].values)
p4 = self.remove_duplication(_df[_combination_pare_column[3]].values)
p5 = self.remove_duplication(_df[_combination_pare_column[4]].values)
for _1, _2, _3, _4, _5 in itertools.product(p1, p2, p3, p4, p5):
return_ary.append([_1, _2, _3, _4, _5])
else:
print('The number of params you specified is too many. Reduce less than 5.')
return None
return return_ary # type: list
@staticmethod
def range_check(_param, _min, _max):
"""
変数が指定された範囲内にいるか確認する機能
:param _param:
:param _min:
:param _max:
:return:
"""
if _min <= _param <= _max:
return True
else:
return False
@staticmethod
def folder_check(_path):
"""
フォルダの存在確認をしてくれる機能
:param _path: 確認したいフォルダのパス
:return:
"""
if not os.path.isdir(_path):
try:
os.mkdir(_path)
print('[common.py][folder_check] Create -> ' + _path)
return True
except:
print('[common.py][Warn] Cannot create folder. ' + _path)
return False
else:
return True
@staticmethod
def remove_duplication(_list: list):
"""
リストの重複を削除する機能
:param _list: 重複を削除したい配列
:return: 重複を削除した配列
"""
seen = set()
seen_add = seen.add
return [x for x in _list if x not in seen and not seen_add(x)]
@staticmethod
def file_exist_check(_file_path):
"""
ファイルが存在するかどうか確認し、存在するならファイル名の末尾にカウンター文字を付与して返す機能
e.g.
hoge.txt を_file_pathに入力し、すでにhoge.txtが存在していれば hoge_(1).txtを返す。
:param _file_path: 存在確認したいファイルパス
:return: 保存して大丈夫なファイルパス
"""
if os.path.exists(_file_path):
base = os.path.dirname(_file_path)
name = os.path.basename(_file_path).split('.')
counter = 1
cwd = os.getcwd()
while os.path.exists(os.path.join(cwd, base, ''.join(name[0:-1]) + '_(' + str(counter) + ').' + str(name[-1]))):
counter += 1
return os.path.join(cwd, base, ''.join(name[0:-1]) + '_(' + str(counter) + ').' + str(name[-1]))
else:
return _file_path
<file_sep># -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import MeCab
import os
import mojimoji
from gensim.models import word2vec
from tqdm import tqdm
from multiprocessing import Pool
from gensim.models.doc2vec import Doc2Vec
from gensim.models.doc2vec import TaggedDocument
class NaturalLang:
def __init__(self, num_to_exec_multithread: int = 3):
self.num_to_exec_multithread = num_to_exec_multithread
self.wakachi_result_for_multiprocess = {}
pass
def do_wakachi(self, args: list):
"""
分かち書きの処理を行う機能(multi_threadとして呼び出される側の関数)
:param args: 引数を纏めたリスト[0]: MeCabのオプション、[1]: 分かち書き結果のdict変数の開始キー、[2]: 分かち書き対象のSeries.
:return:
"""
_out_num = args[0]
_option = args[1]
_item_count = args[2]
df = args[3]
_col = args[4]
word_dict = {}
try:
each_item = df[_col].values # type: np.ndarray
except:
print('[Warn][wakachi_mecab] 列「' + _col + '」が見つかりません。')
return None
# 文字列の統一
for g in range(len(each_item)):
each_item[g] = mojimoji.han_to_zen(str(each_item[g]), kana=False, ascii=False)
each_item[g] = each_item[g].replace('(', '(').replace(')', ')')
# MeCabで分かち書き
# In Ochasen
# \t 区切り
# [0]: 単語
# [1]: よみ
# [2]: 原型?
# [3]: 品詞
option = '-Ochasen' if _option is None else '-Ochasen ' + _option
m = MeCab.Tagger(option)
item_cnt = _item_count
print('start')
for each_sentence in tqdm(each_item):
gc = str(item_cnt).zfill(6)
tmp = m.parse(each_sentence).split('\n')
word_dict[gc] = {}
word_cnt = 1
for w in tmp:
wc = str(word_cnt).zfill(4)
# 'EOS'対策
try:
w.split('\t')[3] # EOSだと4要素目は無いのでExceptionが起こる
except IndexError:
continue
word_dict[gc][wc] = {}
try:
# 品詞の登録 for Ochasen
word_dict[gc][wc]['hinshi'] = []
for i in range(4):
try:
word_dict[gc][wc]['hinshi'].append(w.split('\t')[3].split('-')[i])
except IndexError:
word_dict[gc][wc]['hinshi'].append('')
# 単語の登録 for Ochasen
word_dict[gc][wc]['word'] = w.split('\t')[0]
word_cnt += 1
# 'EOS'対策
except:
continue
item_cnt += 1
return [_out_num, word_dict]
def wakachi_mecab(self,
_df: pd.DataFrame,
_col: str, _export_result_wakachi: bool = False,
_export_file_path: str='./export_result_wakachi.csv',
_option: str = None):
"""
:param _df: excelデータをDataFrameへ変換したもの。
:param _col: _df内の、分かち書きをしたい列名
:param _export_result_wakachi: 分かち書きした結果を品詞とともにcsvにエクスポートするかどうか(default: False)
:param _export_file_path: file path to be exported.
:param _option: MeCab option you wanna use.
:return: dict
"""
# 分かち書きするデータ数が100未満なら、シングルコアで処理する
total_num_of_exec = len(_df)
if total_num_of_exec < 100:
word_dict = self.do_wakachi(args=[0, _option, 1, _df, _col])[1]
# multiprocess で分かち書き
else:
word_dict = {}
num_of_thread = 3
p = Pool(num_of_thread)
q, mod = divmod(len(_df), num_of_thread)
args = []
for i in range(num_of_thread):
if i == num_of_thread - 1:
args.append([i, _option, q * i + 1, _df.iloc[q*i:q*(i + 1)+mod, :].reset_index(drop=True), _col])
else:
args.append([i, _option, q*i+1, _df.iloc[q*i:q*(i+1), :].reset_index(drop=True), _col])
word_dicts = p.map(self.do_wakachi, args)
p.close()
for wd in word_dicts:
self.wakachi_result_for_multiprocess[wd[0]] = wd[1]
for i in range(num_of_thread):
word_dict.update(self.wakachi_result_for_multiprocess[i])
# Write csv file to check the result of wakachi-gaki.
if _export_result_wakachi:
with open(_export_file_path, 'w') as f:
import csv
w = csv.writer(f)
_for = list(word_dict.keys())
_for.sort()
for i in _for:
_tmpw = []
_tmph = []
_for2 = list(word_dict[i].keys())
_for2.sort()
for j in _for2:
_tmpw.append(word_dict[i][j]['word'])
_tmph.append('-'.join(word_dict[i][j]['hinshi']))
w.writerow(_tmpw) # word
w.writerow(_tmph) # 品詞
f.close()
return word_dict
def create_histogram(self, _df: pd.DataFrame, _column: str, _typ: str, _ext_hinshi: list=['一般', '固有名詞'], _op = None):
"""
ヒストグラムを作成する。
:param _df:
:param _column:
:param _typ: meishi, or all
:param _ext_hinshi:
:param _op: MeCab option if needed.
:return:
"""
import collections
_word_box = []
count = 0
print('[Info] Start to import file.')
gaiyo = _df[_column].values # type: np.ndarray
# 文字列の統一
for g in range(len(gaiyo)):
import mojimoji
gaiyo[g] = mojimoji.han_to_zen(str(gaiyo[g]), kana=False, ascii=False) # 半角→全角
gaiyo[g] = gaiyo[g].replace('(', '(').replace(')', ')') # 半角カッコを全角に統一する
print('[Info] Start to create histogram.')
if _op is not None:
m = MeCab.Tagger(_op)
else:
m = MeCab.Tagger()
for i in tqdm(gaiyo):
count += len(i.split(' '))
if _typ == 'meishi':
_word_info = i.split(' ')
for _each_word in _word_info:
if _each_word == '': continue
_w = m.parse(_each_word).split('\n')[0:-2]
hinshi = _w[0].split('\t')[1]
if hinshi.split(',')[0] == '名詞':
type1 = hinshi.split(',')[1]
if type1 in _ext_hinshi:
_word_box.append(_w[0].split('\t')[0])
elif _typ == 'all':
_word_info = i.split(' ') # MeCab default dic
_word_box.extend(_word_info)
else:
print('invalid type.')
cnt = collections.Counter(_word_box)
# count words.
cnt_df = pd.DataFrame.from_dict(cnt, orient='index') # convert Counter to DataFrame
cnt_df = cnt_df.rename(columns={0: 'count'}) # rename columns
cnt_df = cnt_df.sort_values('count', ascending=False) # sort in descending order
f_brackets = lambda x: x / count
cnt_df_2 = cnt_df.iloc[:, 0].map(f_brackets)
output_df = pd.concat([cnt_df, cnt_df_2], axis=1)
return output_df
def knp_parsing(self, _sentences: str):
from pyknp import KNP
k = KNP(option='-tab', jumanpp=False)
k.parse(_sentences)
def tfidf(self, _corpus: list, _min_df: float = 0.03):
"""
TF-IDFによって、特徴語を抽出する機能.
:param _corpus: インプットとなるコーパス(type: [ [I like vim] [I like python] ... ])
:param _min_df: 結果として表示するidf値の最小値(default: 0.03)
:return:
"""
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(min_df=_min_df)
tfidf_x = vectorizer.fit_transform(_corpus).toarray() # type: np.ndarray
feature_names = np.array(vectorizer.get_feature_names())
index = tfidf_x.argsort(axis=1)[:, ::-1] # np.ndarray
feature_words = [feature_names[doc] for doc in index] # type: list
return feature_words # type: list
def bm25(self, _corpus: list):
from gensim.summarization.bm25 import get_bm25_weights
result = get_bm25_weights(_corpus)
class W2V:
def __init__(self, _sentences, _model=None):
"""
:param _sentences: 学習に使うコーパス [['I', 'like', 'python'], ['You', 'like', 'python']...]
"""
self.sentences = _sentences
self.w2v_model = _model
def create_model(self, _size: int, _min_cnt: int, _window: int):
"""
create word2vec model.
:param _size: 構築する単語ベクトルのサイズ
:param _min_cnt: ベクトルを作成する単語の最小出現回数
:param _window: skip-gramで使うウィンドウサイズ
:return:
"""
self.w2v_model = word2vec.Word2Vec(sentences=self.sentences,
size=_size, min_count=_min_cnt,
window=_window,
compute_loss=True) # type: word2vec.Word2Vec
def train(self, _epoch: int, _alpha: float = 0.0001, _return_loss: bool = False):
"""
W2Vモデルを学習させる。
:param _epoch: エポック数(ここではイテレーションの回数)
:param _alpha: 学習率
:param _return_loss: エポック毎の損失関数値をリストで返すかどうか
:return:
"""
loss = [] # type: list
for i in range(_epoch):
self.w2v_model.train(self.sentences,
total_examples=len(self.sentences),
end_alpha=_alpha,
epochs=1,
compute_loss=True)
loss.append([i, self.w2v_model.get_latest_training_loss()])
if _return_loss:
return loss
def save_model(self, _output_folder: str = './', _output_model_name: str = 'w2v_model.model'):
"""
作成したモデルを保存するメソッド
:param _output_folder: 保存先フォルダパス
:param _output_model_name: 保存する際のモデル名(default: w2v_model.model)
:return:
"""
if self.w2v_model is None:
print("[save_model] Model you wanna save is None.")
return
self.w2v_model.save(os.path.join(_output_folder, _output_model_name))
def search_sim_word(self, _word: str, topn: int = 20):
"""
類似語を検索し、返す機能。
:param _word:
:param topn:
:return:
"""
if self.w2v_model is None:
print("[save_model] W2V model is None.")
return None
return self.w2v_model.most_similar(positive=_word, topn=topn) # type: list
class D2V:
def __init__(self, _sentences, _model=None):
self.d2v_model = _model
self.sentences = [TaggedDocument(doc, [i]) for i, doc in enumerate(_sentences)]
def create_model(self, _dm: int=1, _size: int=300, _window: int=8, _min_count: int=10, _workers: int=4):
"""
Doc2Vecのモデルを生成する機能
:param _dm: training algorithm. 1 means 'distributed memory'. otherwise, 'distributed bag-of-words'
:param _size: vector size of model.
:param _window:
:param _min_count:
:param _workers: Use these many worker threads to train the model (=faster training with multi-core machines).
:return:
"""
self.d2v_model = Doc2Vec(documents=self.sentences,
dm=_dm,
size=_size,
window=_window,
alpha=0.025,
min_alpha=0.025,
min_count=_min_count,
workers=_workers,
compute_loss=True) # type: Doc2Vec
def train(self, _epoch: int):
"""
create_modelで生成したモデルを学習させる機能 loss計算機能はまだないらしい
:param _epoch:
:return:
"""
if self.d2v_model is None:
print('[D2V] model is empty.')
return None
for i in tqdm(range(_epoch)):
print('now alpha : ' + str(self.d2v_model.alpha))
self.d2v_model.train(self.sentences,
total_examples=len(self.sentences),
epochs=1)
self.d2v_model.alpha -= (0.025 - 0.0001)/_epoch
def save_model(self, _save_path):
"""
Doc2Vecのモデルを保存する処理。
:param _save_path: 保存するファイルパス
:return:
"""
if self.d2v_model is None:
print('[D2V] model is None.')
return None
self.d2v_model.save(_save_path)
def load_model(self, _load_path):
self.d2v_model = Doc2Vec.load(_load_path)
def search_sim_word(self, word1, word2):
if self.d2v_model is None:
print('[D2V] model is None.')
return None
return self.d2v_model.similarity(word1, word2)
<file_sep>import pathlib
import glob
import MeCab
class ImportData:
def __init__(self):
pass
def import_livedoor(self, _path: str):
"""
Livedoor newsデータを読み込む処理.
:param _path:
:return: [['今日', 'は', '熱い'], ['今日', 'は', '眠い'], ['今日', 'は', '寒い'], ]
"""
pth = pathlib.Path(_path)
label = []
m = MeCab.Tagger('-Owakati')
for p in pth.glob('**/*.txt'):
if p.name in ['CHANGES.txt', 'README.txt', 'LICENSE.txt']:
continue
with open(p, 'r', encoding='utf-8-sig') as f:
buff = f.read()
label.extend(m.parse(buff).split(' ')[:-1])
return label
<file_sep>import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns
import pandas as pd
import numpy as np
import os
from . import common
from scipy import fftpack
class Plot:
@staticmethod
def pure_2d_plot(_df: pd.DataFrame,
_x: int,
_y: list,
_figsize=(16, 12),
_title='pure_2d_plot',
_output_folder_path='./',
_output_file_name='pure_2d_plot.png'):
"""
DataFrame内の2列を使って二次元プロットを行う機能。
:param _df: 使用するDataFrame
:param _x: x軸のラベル番号
:param _y: y軸のラベル番号
:param _figsize: 保存する画像のサイズ(デフォルト:(16, 12)
:param _title: グラフのタイトル
:param _output_folder_path: folder path for saving figure.
:param _output_file_name: file name of figure.
:return: matplotlib.pyplotクラス
"""
plt.figure(figsize=_figsize) # plot size
plt.title(_title)
plt.tight_layout()
column = _df.columns.values
for data in _y:
plt.plot(_df.iloc[:, _x].values, _df.iloc[:, data].values, label=column[data])
if len(_y) > 1:
plt.legend()
plt.savefig(common.Common.file_exist_check(os.path.join(_output_folder_path, _output_file_name)))
plt.close()
# return plt
@staticmethod
def pure_2d_scatter(_df: pd.DataFrame,
_x: int,
_y: int,
_figsize=(16, 12),
_title='pure_2d_scatter',
_s=0.5,
_output_folder_path='./',
_output_file_name='pure_2d_scatter.png'):
"""
DataFrame内の2列を使って二次元プロットを行う機能。
:param _df: 使用するDataFrame
:param _x: x軸のラベル番号
:param _y: y軸のラベル番号
:param _figsize: 保存する画像のサイズ(デフォルト:(16, 12)
:param _title: タイトル
:param _s: Size of scatter plot.
:param _output_folder_path: folder path for saving figure.
:param _output_file_name: file name of figure.
:return: matplotlib.pyplotクラス
"""
c = common.Common()
plt.figure(figsize=_figsize) # plot size
plt.title(_title)
plt.xticks(rotation=90)
plt.tight_layout()
plt.scatter(_df.iloc[:, _x].values, _df.iloc[:, _y].values, s=_s)
if c.folder_check(_output_folder_path):
plt.savefig(c.file_exist_check(os.path.join(_output_folder_path, _output_file_name)))
plt.close()
# return plt
@staticmethod
def simple_histogram(x: list, color: list, xlabel: str = 'xlabel',
_output_file_name: str = 'histogram.png',
bins: int = 10, label: list = None, hist_type: str = 'side-by-side'):
"""
ヒストグラムを作成する機能。グラフはbins毎に各ラベル纏めてプロットする。
:param x: ヒストグラムを作成したいデータ。複数ラベル分作成したい場合は、list型にまとめること。
:param color: グラフの色。複数ラベルある場合は、複数ラベル分纏めてlist型で指定すること。
:param xlabel: x軸の名称(default: xlabel)
:param _output_file_name: 出力ファイル名(default: ./histogram.png)
:param bins: ヒストグラムの分割数(default: 10)
:param label: legendで指定する名前。複数ラベル分ある時は、その分list型にまとめて指定する事(default: None)
:param hist_type: ヒストグラムの描画方法([default]side-by-side: 各要素横並び、stacked: 各要素を積み上げる)
:return:
"""
if len(x) == 0: return
if len(color) == 0: return
if len(x) != len(color):
print('[simplt_histogram] the size of each list x, colo must be same.')
return
plt.ylabel('count')
plt.xlabel(xlabel)
stacked = False if hist_type == 'side-by-side' else True
if label is None:
plt.hist(x, color=color, bins=bins, stacked=stacked)
else:
if len(x) != len(label):
print('[simple_histogram] the size of each list x, label must be same.')
return
plt.hist(x, color=color, bins=bins, label=label, stacked=stacked)
plt.legend()
plt.savefig(_output_file_name)
plt.close()
@staticmethod
def corr_map(_df: pd.DataFrame,
_output_folder_path='./',
_output_file_name='corr_map.png',
_figsize=(16, 12),
_graph_title='corr_map'):
"""
各変数の相関係数のヒートマップ画像を保存する機能。
:param _df: ヒートマップの基となるDataFrame.
:param _output_folder_path: 保存するフォルダのパス(デフォルト:カレントディレクトリ)
:param _output_file_name: 保存する画像ファイル名(デフォルト:corr_map.png)
:param _figsize: 保存する画像のサイズ(デフォルト:(16, 12)
:param _graph_title: グラフのタイトル(デフォルト:corr_map)
:return: None.
"""
plt.figure(figsize=_figsize) # heat map size
plt.title(_graph_title)
sns.set(font_scale=0.6)
sns.heatmap(_df.corr(), annot=True, cmap='plasma', linewidths=.5, annot_kws={"size": 5}, vmin=-1, vmax=1)
plt.yticks(rotation=0)
plt.xticks(rotation=90)
plt.tight_layout()
plt.savefig(common.Common.file_exist_check(os.path.join(_output_folder_path, _output_file_name)))
plt.close()
@staticmethod
def scatter_with_histogram(_df: pd.DataFrame,
dim_reduction: bool=False,
_figsize: tuple=(16, 12),
_output_folder_path: str='./',
_output_file_name: str='scatter_with_histogram.png'):
"""
ヒストグラム付き散布図の画像を保存する機能。
:param _df: 散布図の基となるDataFrame.
:param dim_reduction: 次元削減するかどうか(default=False)
:param _figsize: 保存する画像のサイズ(デフォルト:(16, 12)
:param _output_folder_path: 保存するフォルダのパス
:param _output_file_name: 保存する画像ファイル名(デフォルト:scatter_with_histogram.png)
:return: None.
"""
plt.figure(figsize=_figsize)
plt.xticks(rotation=90)
if dim_reduction:
from .data_mining import DataManipulation
pca = DataManipulation()
_trn = pd.DataFrame(pca.pca_reduction(_df, 2, False))
sns.jointplot(0, 1, _trn, kind='scatter')
plt.savefig(_output_file_name)
return None
plt.tight_layout()
sns.jointplot(0, 1, _df, kind='scatter')
plt.savefig(common.Common.file_exist_check(os.path.join(_output_folder_path, _output_file_name)))
plt.close()
@staticmethod
def pair_plot(_df: pd.DataFrame,
_figsize: tuple=(16, 12),
_output_folder_path: str='./',
_output_file_name: str='pair_plot.png'):
"""
seabornのPariplot画像を保存する機能。
:param _df: pairplotしたいDataFrame
:param _figsize: 保存する画像のサイズ(デフォルト:(16, 12))
:param _output_folder_path: 保存するフォルダのパス
:param _output_file_name: 保存する画像ファイル名(デフォルト:pair_plot.png)
:return: None.
"""
plt.figure(figsize=_figsize)
plt.xticks(rotation=90)
plt.tight_layout()
sns.pairplot(_df)
plt.savefig(common.Common.file_exist_check(os.path.join(_output_folder_path, _output_file_name)))
plt.close()
@staticmethod
def scatter_emphasis(_df: pd.DataFrame,
_x: int,
_y: int,
_c: int,
_labeldict: dict,
_color_box: list=None,
_figsize: tuple=(16, 12),
_output_folder_path: str='./',
_output_file_name: str='scatter_emphasis.png',
_s: int=2):
"""
ラベルによって色を変えて散布図を表示する機能。
:param _df: 表示させたいDataFrame
:param _x: x軸の要素
:param _y: y軸の要素
:param _c: 色を変えるラベルとなる要素
:param _labeldict: legendに表示するラベル
:param _color_box: a list of color associated with _c.
:param _figsize: 保存する画像のサイズ(デフォルト:(16, 12))
:param _output_folder_path: 保存するフォルダのパス
:param _output_file_name: 保存する画像ファイル名(デフォルト:scatter_emphasis.png)
:param _s: size of point.
:return: None.
"""
# 色の補色関係に従い、順に並べること
if _color_box is None:
color_box = ['red', 'green', 'mediumorchid', 'gold', 'blue', 'darkorange', 'cyan', 'purple', 'lime', 'black', 'darkred']
else:
color_box = _color_box
# cdict と label を合わせる
label = common.Common().remove_duplication(_df.iloc[:, _c].values)
if len(label) > len(color_box):
print('[Warn] The number of label is too large. ' +
'Reduce it less than ' + str(len(color_box)) +
'. Or add color to the variable named "color_box" in scatter_emphasis of plot.py.')
cdict = {}
for idx, c in enumerate(label):
cdict[c] = color_box[idx]
plt.figure(figsize=_figsize)
fig, ax = plt.subplots()
for g in np.unique(_df.iloc[:, _c]):
ix = np.where(_df.iloc[:, _c] == g)
ax.scatter(_df.iloc[:, _x].values[ix], _df.iloc[:, _y].values[ix], c=cdict[g], label=_labeldict[g], s=_s)
ax.legend()
plt.xticks(rotation=90)
plt.plot(_df.iloc[:, _x].values, _df.iloc[:, 7].values)
plt.tight_layout()
plt.savefig(common.Common.file_exist_check(os.path.join(_output_folder_path, _output_file_name)))
plt.close()
@staticmethod
def colormap(_df: pd.DataFrame,
_x: str,
_y: str,
_z: str,
_figsize: tuple=(16, 12),
_output_folder_path: str='./',
_output_file_name: str='pcolormesh.png'):
"""
二次元カラーマップを作製する機能
:param _df: プロットの基となるDataFrame
:param _x: x軸としたい項目名
:param _y: y軸としたい項目名
:param _z: z(等高線)で示したい項目名
:param _figsize: 保存する画像のサイズ(デフォルト:(16, 12))
:param _output_folder_path: 保存するフォルダのパス
:param _output_file_name: 保存する画像ファイル名(デフォルト:pcolormesh.png)
:return: None
"""
plt.figure(figsize=_figsize)
z = []
tmp = _df.loc[:, [_x, _y, _z]]
for i in range(int(tmp[_y].min()), int(tmp[_y].max() + 1)):
z.append(tmp[tmp[_y] == i].sort_values(_x)[_z].values)
plt.pcolormesh(_df[_x].drop_duplicates().sort_values().values, _df[_y].drop_duplicates().sort_values().values, z, cmap='hsv')
pp = plt.colorbar(orientation='vertical')
pp.set_label(_z)
plt.xlabel(_x)
plt.ylabel(_y)
plt.tight_layout()
plt.xticks(rotation=90)
plt.tight_layout()
plt.savefig(common.Common.file_exist_check(os.path.join(_output_folder_path, _output_file_name)))
plt.close()
@staticmethod
def show_correlogram(_df: pd.DataFrame,
_col: int,
_lag: int=10,
_figsize: tuple=(16, 12),
_output_folder_path: str='./',
_output_file_name: str='correlogram.png'):
"""
コレログラムのグラフを画像として保存する機能。欠損値を補完しておく必要がある。
:param _df: 対象のデータフレーム
:param _col: コレログラムでプロットしたいデータフレームの列名
:param _lag: コレログラムで表示するラグ(デフォルト値: 10)
:param _figsize: 保存する画像のサイズ(デフォルト:(16, 12))
:param _output_file_name: 保存する画像ファイルの名前(デフォルト値: correlogram.png)
:param _output_folder_path: 保存先のパス(デフォルト値: カレントディレクトリ)
:return:
"""
import statsmodels.api as sm
fig, ax = plt.subplots(nrows=1, figsize=_figsize)
plt.xlabel('Lag')
plt.ylabel('Correlation coefficient')
sm.graphics.tsa.plot_acf(_df.iloc[:, _col], lags=_lag, ax=ax)
plt.tight_layout()
plt.savefig(common.Common.file_exist_check(os.path.join(_output_folder_path, _output_file_name)))
plt.close()
def plot_all_combination(self, _df: pd.DataFrame, _cols: list, _x: int, _y: int):
"""
DataFrameの中にあるキー情報の全組合せにてグラフをプロットする機能。
:param _df: 対象のDataFrame
:param _cols: キー情報としたい列名(column名で)
:param _x: プロットするときのx軸(番号)
:param _y: プロットするときのy軸(番号)
:return:
"""
from . import common
c = common.Common()
combination = c.extract_all_combination(_df, _cols)
for each_combination in combination:
_df_extracted = _df[_df[_cols[0] == each_combination[0]] & _df[_cols[1] == each_combination[1]]]
self.pure_2d_scatter(_df=_df_extracted, _x=0, _y=1)
def simple_fft(self, _series: pd.Series,
_output_file_name: str,
_output_folder_path: str,
_title: str,
_figsize: tuple = (16, 12)):
"""
入力値を離散フーリエ変換し、周波数成分でプロットする機能。
:param _series: Series to be analysed.
:param _output_file_name:
:param _output_folder_path:
:param _title:
:param _figsize: 保存する画像のサイズ(デフォルト:(16, 12))
:return: None
"""
data = _series.values # type: np.ndarray
sample_freq = fftpack.fftfreq(data[:].size, d=1)
y_fft = fftpack.fft(data[:])
pidxs = np.where(sample_freq > 0)
freqs, power = sample_freq[pidxs], np.abs(y_fft)[pidxs]
plt.figure(figsize=_figsize)
plt.title(_title)
plt.xlabel("Frequency[Hz]")
plt.ylabel("Power")
plt.plot(freqs, power, 'b-')
plt.tight_layout()
plt.savefig(common.Common.file_exist_check(os.path.join(_output_folder_path, _output_file_name)))
plt.close()
<file_sep>from tqdm import tqdm
from skimage import morphology, io
import cv2
import os
import numpy as np
import UtilTools.common
class Image_processing:
def __init__(self):
self.c = UtilTools.common.Common()
def smooth_histogram(self, _path: str):
"""
ヒストグラム平滑化する機能。
:param _path: 平滑化する画像のパス。
:return:
"""
img = cv2.imread(_path, 2)
hist, bins = np.histogram(img.flatten(), img.max() + 1, [0, img.max()])
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max() / cdf.max()
cdf_m = np.ma.masked_equal(cdf, 0)
cdf_m = (cdf_m - cdf_m.min()) * img.max() / (cdf_m.max() - cdf_m.min())
cdf = np.ma.filled(cdf_m, 0).astype('uint16')
img2 = cdf[img]
# output_fol = '/'.join(_path.split('/')[0:-1]) + '/smoothed'
# if self.c.folder_check(output_fol):
# output_img = ''.join(_path.split('/')[-1].split('.')[0:-1]) + '_smoothed.png'
# cv2.imwrite(os.path.join(output_fol, '/' + output_img), img2)
return img2
def gamma_correction(self, _path: str, _gamma: float, _outpath='./'):
"""
ガンマ補正を行う機能。
:param _path: 補正する画像のパス。
:param _gamma: ガンマ値。
:param _outpath: 出力先のフォルダ
:return:
"""
img = cv2.imread(_path, 0)
img_gamma = np.zeros_like(img, dtype='uint16')
m = img.max()
for h in tqdm(range(img.shape[0])):
for w in range(img.shape[1]):
img_gamma[h][w] = m * pow(img[h][w] / m, 1 / _gamma)
# res = np.hstack((img, img_gamma))
# cv2.imshow('corrected.', res)
# cv2.waitKey(0)
output_img = ''.join(_path.split('/')[-1].split('.')[0:-1]) + '_' + str(_gamma) + '.png'
if self.c.folder_check(_outpath):
cv2.imwrite(os.path.join(_outpath, output_img), img_gamma)
def extract_imgs(self, _h: int, _w: int, _path: str, _outpath='./'):
"""
画像を定形に細切れにする機能。
:param _h: 細切れにする高さ。
:param _w: 細切れにする幅。
:param _path: 細切れにする画像のパス。
:param _outpath: 細切れにした画像を保存するフォルダのパス。
:return:
"""
img = cv2.imread(_path, 0)
if img.shape[0] % _h != 0 or img.shape[1] % _w != 0:
print('[Warn] Image cannot be divided by _w, or _h.')
exit(1)
if not self.c.folder_check(_outpath):
exit(1)
for ew in range(0, len(img[1]), _w):
for eh in range(0, len(img[0]), _h):
extracted_patch = img[eh:eh + _h - 1, ew:ew + _w - 1]
cv2.imwrite(os.path.join(_outpath, _path.split('/')[-1].split('.')[0] + '_extpatch_h' + str(eh) + '_w' + str(ew) + '.png'), extracted_patch)
def extract_img(self, _s: list, _h: int, _w: int, _path: str, _outpath='./'):
"""
画像から単一の画像を切り取る処理
:param _s: 切り取る開始位置(リスト型変数で、[x,y])
:param _h: 切り取る画像の高さ
:param _w: 切り取る画像の幅
:param _path: 切り取る基の画像のパス
:param _outpath: 出力先のフォルダのパス
:return:
"""
if len(_s) != 2:
print('_s must be list as [x, y].')
exit(1)
img = cv2.imread(_path, 0)
ext_img = img[_s[0]:_s[0] + _h, _s[1]:_s[1] + _w]
if self.c.folder_check(_outpath):
cv2.imwrite(os.path.join(_outpath, _path.split('/')[-1].split('.')[0] + '_ext_h' + str(_h) + '_w' + str(_w) + '.png'), ext_img)
def extract_random_img(self, _num: int, _h: int, _w: int, _path: str, _outpath='./'):
"""
特定の画像から、決まったサイズの画像をランダムに切り取る処理
:param _num: 切り取る画像の数
:param _h: 切り取る画像の高さ
:param _w: 切り取る画像の幅
:param _path: 切り取る画像ファイルのパス
:param _outpath: 出力先のフォルダのパス
:return:
"""
import random
img = cv2.imread(_path, 0)
for count in range(0, _num):
width = random.randint(0, len(img[0, :]) - _w)
height = random.randint(0, len(img[:, 0]) - _h)
ext_img = img[height:height + _h, width:width + _w]
if self.c.folder_check(_outpath):
cv2.imwrite(os.path.join(_outpath, str(count) + '.png'), ext_img)
def erosion(self, _img: np.array, _kernel_size: int):
"""
入力画像を収縮する処理
:param _img:収縮させる画像(ndarray)
:param _kernel_size:収縮のカーネルサイズ
:return:
"""
kernel = np.ones((_kernel_size, _kernel_size), np.uint8)
return cv2.erode(_img, kernel, iterations=1)
def dilation(self, _img: np.ndarray, _kernel_size: int):
"""
入力画像を膨張させる処理
:param _img:
:param _kernel_size:
:return:
"""
kernel = np.ones((_kernel_size, _kernel_size), np.uint8)
return cv2.dilate(_img, kernel, iterations=1)
def opening(self, _img: np.ndarray, _kernel_size: int):
"""
入力画像をオープニング(収縮→膨張)する処理。
ホワイトノイズを消すのに強い。
:param _img:
:param _kernel_size:
:return:
"""
kernel = np.ones((_kernel_size, _kernel_size), np.uint8)
return cv2.morphologyEx(_img, cv2.MORPH_OPEN, kernel)
def closing(self, _img: np.ndarray, _kernel_size: int):
"""
入力画像をクロージング(膨張→収縮)する処理。
オブジェクト内にあるノイズを消すのに強い。
:param _img:
:param _kernel_size:
:return:
"""
kernel = np.ones((_kernel_size, _kernel_size), np.uint8)
return cv2.morphologyEx(_img, cv2.MORPH_CLOSE, kernel)
def ma_filter(self):
pass
def skeltonize(self, _img: np.ndarray):
"""
細線化する処理
:param _img: 細線化したい画像ファイル
:return:
"""
import matplotlib.pyplot as plt
img = morphology.skeletonize(_img)
plt.imsave('skel.png', img)
return img
<file_sep>from keras import Sequential
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import os
class SupervisedLearning:
def __init__(self):
self.optimizer = None
self.x_train = None
self.y_train = None
self.x_valid = None
self.y_valid = None
self.train_generator = None
self.validation_generator = None
def import_data(self, _x, _y):
self.x_train, self.x_valid, self.y_train, self.y_valid = train_test_split(_x.values, _y.values, test_size=0.25)
def import_data_from_dir(self, _train_dir: str, _valid_dir: str, _img_size: tuple):
self.train_generator = ImageDataGenerator().flow_from_directory(
directory=_train_dir,
target_size=(_img_size[0], _img_size[1]),
batch_size=30,
class_mode='categorical')
self.validation_generator = ImageDataGenerator().flow_from_directory(
directory=_valid_dir,
target_size=(_img_size[0], _img_size[1]),
batch_size=1,
class_mode='categorical')
def define_optimizer(self):
self.optimizer = Adam(lr=0.001)
def execute_keras_model(self, _type: str,
_model: Sequential,
_optimizer=None,
_batch_size: int = 64,
_epoch: int = 5):
"""
受け取ったモデルで学習を実行する機能
:param _type: 'category' or 'regression'
:param _model: Keras model.
:param _optimizer: Keras Optimizer.
:param _batch_size: Batch Size. Default: 64
:param _epoch: Epoch. Default: 5
:return: None as Error. 0 as Success.
"""
#Train and Valid data check.
# if (self.x_train is None or self.y_train is None) or self.train_generator is None: return None
# if (self.x_valid is None or self.y_valid is None) or self.validation_generator is None: return None
train_data_type = None
if self.x_train is not None:
train_data_type = 'from_list'
elif self.train_generator is not None:
train_data_type = 'from_dir'
else:
return train_data_type
# Optimizer check.
if _optimizer is None:
self.define_optimizer()
else:
self.optimizer = _optimizer
# Compile model.
if _type == 'category':
_model.compile(optimizer=self.optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
elif _type == 'regression':
_model.compile(optimizer=self.optimizer, loss='mean_squared_error', metrics=['accuracy'])
if train_data_type == 'from_list':
history = _model.fit(self.x_train, self.y_train,
batch_size=_batch_size, epochs=_epoch,
validation_data=(self.x_valid, self.y_valid))
elif train_data_type == 'from_dir':
history = _model.fit_generator(self.train_generator,
batch_size=_batch_size, epochs=_epoch,
validation_data=self.validation_generator,
shuffle=True, verbose=1)
else:
print('[Warn] Invalid type.')
return None
# Save graph of loss.
plt.figure(figsize=(8, 5))
plt.ylabel('val_loss')
plt.xlabel('epochs')
plt.tight_layout()
plt.plot(history.history['val_loss'], "o-", markersize=2, label='val_loss')
plt.plot(history.history['loss'], "o-", markersize=2, label='loss')
plt.legend()
plt.savefig(os.path.join('..', 'loss.png'))
# Save graph of accuracy.
plt.figure(figsize=(8, 5))
plt.ylabel('accuracy')
plt.xlabel('epochs')
plt.tight_layout()
plt.plot(history.history['val_acc'], "o-", markersize=2, label='val_acc')
plt.plot(history.history['acc'], "o-", markersize=2, label='acc')
plt.legend()
plt.savefig(os.path.join('..', 'acc.png'))
return 0
<file_sep>import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn.decomposition import FastICA
from sklearn.manifold import TSNE
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from scipy import fftpack
from tqdm import tqdm
from . import plot
class DataManipulation:
def __init__(self):
self.p = plot.Plot()
def ica_reduction(self, _df: pd.DataFrame, _dim: int, _return_with_model=False):
"""
独立成分分析でノイズを除去するもの。
:param _df: 次元削減したいデータ(DataFrame形式)
:param _dim: 削減後の次元数
:param _return_with_model: 主成分分析のモデルもreturnするかどうかのフラグ
:return: 主成分分析後のndarray
"""
ica = FastICA(n_components=_dim) # type: FastICA
M = np.mean(_df.values, axis=1)[:, np.newaxis] # type: np.ndarray
norm_ary = _df.values - M # type: np.ndarray
ica.fit(norm_ary)
transformed = ica.transform(norm_ary)
if _return_with_model:
return transformed, ica
else:
return transformed
def pca_reduction(self, _df: pd.DataFrame, _dim: int, _return_with_model=False):
"""
主成分分析で次元を削減するもの。
:param _df: 次元削減したいデータ(DataFrame形式)
:param _dim: 削減後の次元数
:param _return_with_model: 主成分分析のモデルもreturnするかどうかのフラグ
:return: 主成分分析後のデータフレーム(ndarray)
"""
pca = PCA(n_components=_dim) # type: PCA
pca.fit(_df.values)
transformed = pca.fit_transform(_df.values) # type: np.ndarray
if _return_with_model:
return transformed, pca
else:
return transformed
def lda_reduction(self, _df: pd.DataFrame, _x: int, _y: int, _dim: int, _return_with_model=False):
"""
LDAによる教師有データの次元削減を行う機能
:param _df: 次元削減したいデータ(DataFrame形式)
:param _x: 学習データ
:param _y: 正解データ
:param _dim: 削減後の次元数
:param _return_with_model: 主成分分析のモデルもreturnするかどうかのフラグ
:return:
"""
lda = LDA(n_components=_dim) # type: LDA
lda.fit(_df.iloc[:, _x].values, _df.iloc[:, _y].values)
transformed = lda.fit_transform(_df.values) # type: np.ndarray
if _return_with_model:
return transformed, lda
else:
return transformed
def tsne_reduction(self, _dim: int, _x, _return_with_model: bool):
"""
t-SNEによる次元削減を行う機能
:param _dim: 削減後の次元数(t-SNEの場合、2or3次元)
:param _x: 次元削減したいデータ(DataFrame形式)
:param _return_with_model:
:return:
"""
if _dim > 3:
print('[Warn][tsne_reduction] It is to be desired that the dimention is 2 or 3.')
tsne = TSNE(n_components=_dim)
transformed = tsne.fit_transform(_x)
if _return_with_model:
return transformed, tsne
else:
return transformed
def simple_fft(self, _input_file: str):
"""
入力値を離散フーリエ変換し、周波数成分に分解する機能
:param _input_file: 変換したいcsvファイル
:return: None
"""
# Todo: UtilToolsに合うように、_dfインプットからのpure2dplot連携を実現したい
import matplotlib.pyplot as plt
(time, data) = np.loadtxt(_input_file, unpack=True, delimiter=",",
usecols=(0, 1)) # type: (np.ndarray, np.ndarray)
sample_freq = fftpack.fftfreq(data[:].size, d=1)
y_fft = fftpack.fft(data[:])
pidxs = np.where(sample_freq > 0)
freqs, power = sample_freq[pidxs], np.abs(y_fft)[pidxs]
plt.figure()
plt.plot(freqs, power, 'b-')
plt.xlabel("Frequency[Hz]")
plt.ylabel("Power")
plt.show()
def fill_na(self, _df: pd.DataFrame, _typ: int):
"""
fill na to all columns with previous value.
:param _df: NAを埋めたいData Frame.
:param _typ: NAの埋め方(0: 前行値で補完、1: 線形補完)
:return: NAを前行の値で埋めたDataFrame.
"""
_df_isnull = _df.isnull()
# 前行補完
if _typ == 0:
for i in range(len(_df)):
for j in range(len(_df.index)):
if _df_isnull.iat[j, i]:
_df.replace(_df.iat[j, i], _df.iat[j - 1, i], inplace=True)
return _df
# 線形補完
elif _typ == 1:
return _df.interpolate()
def drop_na(self, _df: pd.DataFrame):
"""
NAが含まれる行を削除するもの。
:param _df: NAが含まれる行を削除したいデータ(DataFrame形式)
:return: NAが削除された後のDataFrame
"""
return _df.dropna(how='any')
def crosstabs(self, _df: pd.DataFrame, _x: int, _y: int, _val: int = None):
return pd.crosstab(_df.iloc[:, _x], _df.iloc[:, _y])
def moving_avg(self, _df: pd.DataFrame, _column: str, _typ: str = 'behind', _window: int = 3):
"""
移動平均を算出し、列を追加して返す処理.
:param _df:
:param _column:
:param _typ: "behind" or "center". "behind" is default value.
:param _window:
:return:
"""
if _typ == 'behind':
ma_series = _df[_column].rolling(_window).mean()
elif _typ == 'center':
if _window % 2 == 1:
_tmp_ma_ndary = _df[_column].values
ave = np.convolve(_tmp_ma_ndary, np.ones(_window) / float(_window), 'same')
margin = _window//2
ave[:margin] = np.nan
ave[-1 * margin:] = np.nan
ma_series = pd.Series(ave)
else:
print('[Warn] Window size must be Odd number.')
return None
else:
print('[Warn] _typ is invalid.')
return None
_df.reset_index(drop=True, inplace=True)
concat_df = pd.concat([_df, pd.DataFrame(ma_series.T)], axis=1)
new_col = list(_df.columns)
new_col.append(_column + '_ma')
concat_df.columns = new_col
return concat_df
class FeatureSelection:
def __init__(self):
pass
@staticmethod
def col_based_feature_selection(_df: pd.DataFrame,
_cor_threshold: float=0.95,
_cor_matrix: pd.DataFrame = None,
_drop: bool=True,
_return_col: bool=False):
"""
フィルターメソッドを使った次元削減方法.
(相関係数の高い変数同士を探して、次元削減を行う処理)
※ 注意点として、複数変数同士が合わさって初めて相関が出るようなケースには使えない
参考:https://ocw.tsukuba.ac.jp/wp/wp-content/uploads/2019/10/fa67c4f9c50e67abbe3c9a684bea594c.pdf
:param _df:
:param _cor_threshold:
:param _cor_matrix:
:param _drop:
:param _return_col:
:return:
"""
bef_var = len(_df.columns)
feat_corr = set()
if _cor_matrix is None:
_cor_matrix = _df.corr()
for i in tqdm(range(len(_cor_matrix.columns))):
for j in range(i):
if abs(_cor_matrix.iloc[i, j]) > _cor_threshold:
feat_name = _cor_matrix.columns[i]
feat_corr.add(feat_name)
if _drop:
_df.drop(labels=feat_corr, axis='columns', inplace=True)
print('Feature variables reduced to ' + str(bef_var - len(feat_corr)) + ' from ' + str(bef_var) + '.')
if _return_col:
return _df, list(feat_corr)
else:
return _df
@staticmethod
def lasso_based_feature_selection(_x, _t, _alpha: float=1.0, _iter: int=10000):
"""
Lasso回帰(L1正則化)による次元削減.
Σ(t_i - w^T * x_i)^2 + alpla * ||w||_1
:param _x: 学習変数
:param _t: 目的変数
:param _alpha: 正則化パラメーター(λのこと). 0:正則化無し
:param _iter:
:return:
"""
from sklearn.linear_model import Lasso
lasso = Lasso(alpha=_alpha, normalize=True, max_iter=_iter)
lasso.fit(_x, _t)
return lasso
<file_sep>from sklearn.cluster import KMeans
from sklearn.cluster import AgglomerativeClustering
from sklearn.cluster import DBSCAN
from sklearn.metrics import silhouette_samples
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
class util:
def __init__(self):
pass
def silhouette_coefficient(self, _x, _y):
"""
シルエット関数を使ってクラスタリングの結果を検証する機能
:param _x: 学習データ
:param _y: クラスタリング結果
:return:
"""
cluster_labels = np.unique(_y)
n_clusters = cluster_labels.shape[0]
# calc silhoette coefficient
silhouette_vals = silhouette_samples(_x, _y, metric='euclidean')
y_as_lower, y_as_upper = 0, 0
yticks = []
for i, c in enumerate(cluster_labels):
c_silhouette_vals = silhouette_vals[_y == c]
c_silhouette_vals.sort()
y_as_upper += len(c_silhouette_vals)
color = cm.jet(float(i) / n_clusters)
plt.barh(range(y_as_lower, y_as_upper),
c_silhouette_vals, height=1.0, edgecolor='none', color=color)
yticks.append((y_as_lower + y_as_upper) / 2)
y_as_lower += len(c_silhouette_vals)
silhouette_average = np.mean(silhouette_vals)
plt.axvline(silhouette_average, color='red', linestyle='--')
plt.yticks(yticks, cluster_labels + 1)
plt.ylabel('Cluster')
plt.xlabel('Silhouette coefficient')
plt.tight_layout()
plt.show()
class Kmeans_Clustering:
"""
K-meansを扱うクラス
"""
def __init__(self):
pass
def train(self, _n_class: int, _x, _concat: bool = False):
"""
k-meansでクラスタリングを行う
:param _n_class: 分割したいクラス数
:param _x: 学習で使用するデータ
:param _concat: 学習データと分割データを結合して返すかどうか(default: False)
:return:
"""
km = KMeans(n_clusters=_n_class, init='k-means++', n_init=10, max_iter=300, tol=1e-04, random_state=0)
y_km = km.fit_predict(_x) # np.ndarray
if _concat:
return np.hstack([_x.values, y_km.reshape(len(y_km), 1)])
else:
return y_km
def elbow(self, _max_cluster: int, _x):
"""
エルボー法で、最適なクラスタ数を求める機能。
:param _max_cluster: 検証する分割クラスタの最大数
:param _x: 学習用データ
:return:
"""
distortions = []
for i in range(1, _max_cluster + 1):
km = KMeans(n_clusters=i, init='k-means++', n_init=10, max_iter=300, random_state=0)
km.fit(_x)
distortions.append(km.inertia_)
plt.title('elbow method result')
plt.xlabel('num of cluster')
plt.ylabel('distortions')
plt.plot(range(1, _max_cluster + 1), distortions)
plt.show()
class Agglomerative_Clustering:
def __init__(self):
pass
def train(self, n_class: int, _x, _concat: bool = False):
"""
凝集型階層的クラスタリングを行う機能
:param n_class: 分割したいクラス数
:param _x: 学習で使用するデータ
:param _concat: 学習データと分割データを結合して返すかどうか(default: False)
:return:
"""
ac = AgglomerativeClustering(n_clusters=n_class, affinity='euclidean', linkage='complete')
y_ac = ac.fit_predict(_x)
if _concat:
return np.hstack([_x.values, y_ac.reshape(len(y_ac), 1)])
else:
return y_ac
class Dbscan:
def __init__(self):
pass
def train(self, _x, _eps: float = 0.2, _min_samples: int = 5, _concat: bool = False):
"""
DBSCANのクラスタリングを行う機能
:param _x: 学習で使用するデータ
:param _eps: 隣接点とみなす2点間の最大距離
:param _min_samples: ボーダー点の最小個数
:param _concat: 学習データと分割データを結合して返すかどうか(default: False)
:return:
"""
db = DBSCAN(eps=_eps, min_samples=_min_samples, metric='euclidean')
y_db = db.fit_predict(_x)
if _concat:
return np.hstack([_x.values, y_db.reshape(len(y_db), 1)])
else:
return y_db
|
ae8faec7e795335e0d3e71e43261cb4a578ce93a
|
[
"Python"
] | 9
|
Python
|
Mugicha/UtilTools
|
0c1846112b27e1f61db4502504b2619eca5ea4e2
|
fcd4b609a1c184f9a224b34026a505f879c7e2cd
|
refs/heads/master
|
<file_sep>package com.bhuman.exm.models;
/* Glentry POJO */
public class Glentry {
private String accountNo;
private String trx_amount;
public Glentry() {
}
public Glentry(String accountNo, String trx_amount) {
this.accountNo = accountNo;
this.trx_amount = trx_amount;
}
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
public String getTrx_amount() {
return trx_amount;
}
public void setTrx_amount(String trx_amount) {
this.trx_amount = trx_amount;
}
}
<file_sep>package com.bhuman.exm.api;
/*
* A generic API interface. It provides generic
* methods to authenticate, post and retrieve
* journal entries
*/
public interface API<T> {
public T authenticate();
}
<file_sep>package com.bhuman.exm.util;
public class Constants {
public static String sageFactoryKey = "sage";
}
<file_sep># Sage API consumption for EX-M
This project provides an outline i.e. a structure for how to consume Sage API.
## Structure
This project is divided into 3 packages i.e. Model, API, and Util and each corresponding package has it's own set of unit test methods.
### Model
Contains models that provide a mapping to it's corresponding types found in [Sage docs]. At this stage, all the models are POJOs and they are
- Credentials
- Glentry
- JournalEntry
- Project
### API
The API package consists of generic interfaces for authentication and CRUD operations.
```
public interface API<T> {
public T authenticate();
}
public interface CrudAPI<T> {
public T create(T entry, String sessionId);
public List<T> retrieveEntries(String sessionId);
public T updateJournalEntry(T entry, String sessionId);
public boolean delete(T entry, String sessionId);
}
```
They are implemented by the
- SageImpl that aims to query external Sage API
which is access via the APIFactory, which is a uses the Factory pattern in combination with the Singleton pattern to avoid multiple if statements in the future
```
public class APIFactory {
private Map<String, API<Credentials>> authMap = new HashMap<String, API<Credentials>>();
private Map<String, CrudAPI<JournalEntry>> crudMap = new HashMap<String, CrudAPI<JournalEntry>>();
//let's just have one instance of this factory in the project
public static APIFactory factory = new APIFactory();
/
* So far we only have crud and auth implementations for Sage */
private APIFactory() {
SageImpl sageImpl = new SageImpl();
authMap.put(Constants.sageFactoryKey, sageImpl);
crudMap.put(Constants.sageFactoryKey, sageImpl);
}
public API<Credentials> getAuthAPI(String name) {
return authMap.get(name);
}
public CrudAPI<JournalEntry> getCrudAPI(String name) {
return crudMap.get(name);
}
}
```
### Util
The util package contains the necessary information such as
- enum - has the relative Sage urls
```
public enum SageUrls {
AUTHENTICATE(""),
POST_JOURNAL_ENTRY("https://developer.intacct.com/api/general-ledger/journal-entries/#create-journal-entry"),
RETRIEVE_JOURNAL_ENTRIES("https://developer.intacct.com/api/project-resource-mgmt/projects/");
private String urlStr = null;
private SageUrls(String desc){
this.urlStr = desc;
}
public String getUrlStr() {
return urlStr;
}
}
```
- Constants - has the key to fetch the API from APIFactory
```
package com.bhuman.exm.util;
public class Constants {
public static String sageFactoryKey = "sage";
}
```
# Further reading
- [Singleton Pattern]
- [Factory Pattern]
- [Mockito]
- [Java REST app with Jersey]
- [Maven project with Java How-To]
- [Java on HackerRank]
[Sage docs]: https://developer.intacct.com/api/general-ledger/journal-entries/#create-journal-entry
[Singleton Pattern]: https://refactoring.guru/design-patterns/singleton
[Factory Pattern]: https://www.tutorialspoint.com/design_pattern/factory_pattern.htm
[Mockito]: https://site.mockito.org/
[Java REST app with Jersey]: https://mydaytodo.com/java-restful-backend-for-an-app/
[Maven project with Java How-To]: https://mkyong.com/maven/how-to-create-a-java-project-with-maven/
[Java on HackerRank]: https://mydaytodo.com/java-stack-brackets-hackerrank/
|
0613c20465a69326253d16430c8b1f4088db592a
|
[
"Markdown",
"Java"
] | 4
|
Java
|
cptdanko/JavaGenericSageAPI
|
726bed4ca41d454d457bd735f70f9afe567853b3
|
df8556884985b6aa7c11899402da7d95b579d446
|
refs/heads/master
|
<file_sep>CREATE TABLE pokemonTrait (
"traitId" INTEGER,
"pokemonId" INTEGER,
FOREIGN KEY ("traitId") REFERENCES trait(id),
FOREIGN KEY ("pokemonId") REFERENCES pokemon(id)
);<file_sep>const {Pool} = require('pg');
const databaseConfig = require('./secrets/databaseConfig.js');
const pool = new Pool(databaseConfig);
module.exports = pool;
/*
//CHECKING FOR A SUCCESSFUL CONNECTION
pool.query('SELECT * FROM generation', (err, res)=> {
if(err) return console.log('error', err);
console.log('res.rows', res.rows);
});
*/
<file_sep>import { PUBLIC_POKEMONS } from './types';
import { BACKEND } from '../config';
export const fetchPublicPokemons = () => dispatch => {
dispatch({ type: PUBLIC_POKEMONS.FETCH });
return fetch(`${BACKEND.ADDRESS}/pokemon/public-pokemons`)
.then(response => response.json())
.then(json => {
if (json.type === 'error') {
dispatch({ type: PUBLIC_POKEMONS.FETCH_ERROR, message: json.message });
}
else {
dispatch({ type: PUBLIC_POKEMONS.FETCH_SUCCESS, message: json.message, pokemons: json.pokemons})
}
})
.catch(error => dispatch({type: PUBLIC_POKEMONS.FETCH_ERROR, message: error.message}));
}<file_sep>import { PUBLIC_POKEMONS } from '../actions/types';
import fetchStates from './fetchStates';
const DEFAULT_PUBLIC_POKEMONS = {pokemons: []};
const publicPokemons = (state= DEFAULT_PUBLIC_POKEMONS, action) => {
switch(action.type){
case PUBLIC_POKEMONS.FETCH:
return { ...state, status: fetchStates.fetching };
case PUBLIC_POKEMONS.FETCH_ERROR:
return {...state, status: fetchStates.error, message: action.message};
case PUBLIC_POKEMONS.FETCH_SUCCESS:
return {...state, status: fetchStates.success, message: action.message, pokemons: action.pokemons};
default:
return state;
}
}
export default publicPokemons;<file_sep>CREATE TABLE accountPokemon(
"accountId" INTEGER REFERENCES account(id),
"pokemonId" INTEGER REFERENCES pokemon(id),
PRIMARY KEY ("accountId", "pokemonId")
);<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import PokemonAvatar from './PokemonAvatar';
import { Button } from 'react-bootstrap';
import { fetchPokemon } from '../actions/pokemon';
import fetchStates from '../reducers/fetchStates';
// const DEFAULT_POKEMON = {
// nickname: '',
// generationId: '',
// pokemonId: '',
// birthdate: '',
// traits: []
// };
class Pokemon extends Component {
get PokemonView() {
if (this.props.pokemon.status === fetchStates.error) {
return <span>{this.props.pokemon.message}</span>
}
return (
<div>
<PokemonAvatar pokemon={this.props.pokemon} />
</div>
)
}
// state = { pokemon: DEFAULT_POKEMON };
// componentDidMount() {
// this.props.fetchPokemon();
// }
// fetchPokemon = () => {
// fetch('http://localhost:3000/pokemon/new')
// .then(response => response.json())
// .then(json => this.setState({ pokemon: json.pokemon }))
// .catch(error => console.error('error', error));
// }
render() {
return (
/*Here we are passing the properties(props) of parent component i.e. Pokemon
to the child component PokemonAvatar using the pokemon={} part. */
<div>
<Button onClick={this.props.fetchPokemon}>New Pokemon</Button>
<br />
{this.PokemonView}
</div>
);
}
}
const mapStateToProps = (state) => {
const pokemon = state.pokemon;
return { pokemon };
};
export default connect(
mapStateToProps,
{ fetchPokemon }
)(Pokemon);
<file_sep>const { REFRESH_RATE, SECONDS } = require('../config.js');
const Pokemon = require('../pokemon/index.js')
const refreshRate = REFRESH_RATE * SECONDS;
class Generation {
constructor() {
this.accountIds = new Set();
this.expiration = this.calculateExpiration();
this.generationId = undefined;
}
calculateExpiration(){
const expirationPeriod = Math.floor(Math.random() * (refreshRate / 2));
const msUntilExpiration = Math.random() < 0.5 ?
refreshRate - expirationPeriod :
refreshRate + expirationPeriod;
return new Date(Date.now() + msUntilExpiration);
}
newPokemon({accountId }){
if(Date.now()>this.expiration){
throw new Error('This generation has expired on'+this.expiration);
}
if(this.accountIds.has(accountId)){
throw new Error('You already have a pokemon from this generation');
}
this.accountIds.add(accountId)
return new Pokemon({ generationId: this.generationId });
}
}
module.exports = Generation;<file_sep>import { combineReducers } from 'redux';
import generation from './generation';
import pokemon from './pokemon';
import account from './account';
import accountPokemons from './accountPokemons';
import accountInfo from './accountInfo';
import publicPokemons from './publicPokemons';
export default combineReducers({
account,
generation,
pokemon,
accountPokemons,
accountInfo,
publicPokemons
});<file_sep>import React, { Component } from 'react';
import { Button } from 'react-bootstrap';
import { connect } from 'react-redux';
import { BACKEND } from '../config';
class MatingOptions extends Component {
mate = ({matronPokemonId, patronPokemonId}) =>() => {
fetch(`${BACKEND.ADDRESS}/pokemon/mate`, {
method: 'POST',
credentials: 'include',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({matronPokemonId, patronPokemonId})
})
.then(response => response.json())
.then(json => {
alert(json.message);
if(json.type !== 'error'){
history.push('/account-pokemons');
}
})
}
render() {
return(
<div>
<h4>Pick one of your Pokemons to mate with:</h4>
{
this.props.accountPokemons.pokemons.map(pokemon => {
const {pokemonId, generationId, nickname} = pokemon;
return(
<span key={pokemonId}>
<Button onClick={
this.mate({
patronPokemonId: this.props.patronPokemonId,
matronPokemonId: pokemon.pokemonId
})
}>
GID:{generationId} PID: {pokemonId}.{nickname}
</Button>
{' '}
</span>
)
})
}
</div>
)
}
}
const mapStateToProps = (state) => {
const accountPokemons = state.accountPokemons;
return { accountPokemons };
}
export default connect(mapStateToProps, null)(MatingOptions);<file_sep>const APP_SECRET = 'abc!123';
module.exports = { APP_SECRET }<file_sep>import {ACCOUNT_POKEMONS } from './types';
import {fetchFromAccount} from './account';
export const fetchAccountPokemons = () => fetchFromAccount({
endpoint: 'pokemons',
options: {credentials: 'include'},
SUCCESS_TYPE: ACCOUNT_POKEMONS.FETCH_SUCCESS,
FETCH_TYPE: ACCOUNT_POKEMONS.FETCH,
ERROR_TYPE: ACCOUNT_POKEMONS.FETCH_ERROR
});<file_sep>const SHA256 = require('crypto-js/sha256');
const { APP_SECRET } = require('../../secrets/index.js');
const hash = string => {
// SHA256 method returns an object with inner methods so to obtain hashed password .toString() i used
return SHA256(`${APP_SECRET}${string}${APP_SECRET}`).toString();
}
module.exports = { hash };<file_sep>import React, { Component } from 'react';
import PokemonAvatar from './PokemonAvatar';
import { Button } from 'react-bootstrap';
import { BACKEND } from '../config'
class AccountPokemonRow extends Component {
state = {
nickname: this.props.pokemon.nickname,
edit: false,
isPublic: this.props.pokemon.isPublic,
saleValue: this.props.pokemon.saleValue,
sireValue: this.props.pokemon.sireValue
}
updateNickname = event => {
this.setState({ nickname: event.target.value });
}
updateSaleValue = event => {
this.setState({saleValue: event.target.value});
}
updateSireValue = event => {
this.setState({sireValue: event.target.value});
}
updateIsPublic = event => {
this.setState({isPublic: event.target.checked})
}
get saveAndCancelButton() {
return (
<div>
<Button onClick={this.toggleEdit}>Cancel</Button>
<span> </span>
<Button onClick={this.save}>Save</Button>
</div>
)
}
get editButton() {
return <Button onClick={this.toggleEdit}>Edit</Button>
}
toggleEdit = () => {
this.setState({ edit: !this.state.edit });
}
save = () => {
fetch(`${BACKEND.ADDRESS}/pokemon/update`,
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pokemonId: this.props.pokemon.pokemonId,
nickname: this.state.nickname,
isPublic: this.state.isPublic,
saleValue: this.state.saleValue,
sireValue: this.state.sireValue
})
})
.then(response => response.json())
.then(json => {
if (json.type === 'error') {
alert(json.message);
}
else {
this.toggleEdit();
}
})
.catch(error => alert(error.message));
}
render() {
return (
<div>
<input type='text'
value={this.state.nickname}
onChange={this.updateNickname}
disabled={!this.state.edit}
/>
<br />
<PokemonAvatar pokemon={this.props.pokemon} />
<div>
<span>
Sale Value:{' '}
<input
type='number'
disabled={!this.state.edit}
value={this.state.saleValue}
onChange={this.updateSaleValue}
className='account-pokemon-row-input'
/>
</span>
{' '}
<span>
Sire Value:{' '}
<input
type='number'
disabled={!this.state.edit}
value={this.state.sireValue}
onChange={this.updateSireValue}
className='account-pokemon-row-input'
/>
</span>
{' '}
<span>
Public:{' '}
<input
type='checkbox'
disabled={!this.state.edit}
value={this.state.isPublic}
onChange={this.updateIsPublic}
/>
</span>
{' '}
{
this.state.edit ? this.saveAndCancelButton : this.editButton
}
</div>
</div>
);
}
}
export default AccountPokemonRow;
<file_sep>import React, { Component } from 'react';
import { skinny, patchy, slender, plain, sporty, spotty, stocky, striped } from '../../assets';
const propertyMap = {
bgColor: {
black: '#263238',
white: '#cfd8dc',
green: '#a5d6a7',
blue: '#0277bd'
},
build: { slender, stocky, sporty, skinny },
pattern: { patchy, plain, spotty, striped },
size: { small: 80, medium: 120, large: 160, gigantic: 200 }
};
class PokemonAvatar extends Component {
get PokemonImage() {
const pokemonPropertyMap = {};
this.props.pokemon.traits.forEach(trait => {
const { traitType, traitValue } = trait;
pokemonPropertyMap[traitType] = propertyMap[traitType][traitValue];
})
const { bgColor, build, pattern, size } = pokemonPropertyMap;
const sizing = { width: size, height: size };
return (
<div className='pokemon-avatar-image-wrapper'>
<div className='pokemon-avatar-image-background' style={{ backgroundColor: bgColor, width: sizing.width, height: sizing.height }}></div>
<img className='pokemon-avatar-image-pattern' src={pattern} style={{ width: sizing.width, height: sizing.height }} />
<img className='pokemon-avatar-image' src={build} style={{ width: sizing.width, height: sizing.height }} />
</div>
);
}
render() {
const { generationId, pokemonId, traits } = this.props.pokemon;
//console.log(this.props.pokemon);
if (!pokemonId) {
return <div></div>
}
return (
<div>
<span>GID: {generationId}.</span>
<span>PID: {pokemonId}.</span>
{traits.map(trait => trait.traitValue).join(', ')}
{this.PokemonImage}
</div>
)
}
}
export default PokemonAvatar;<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchAccountPokemons } from '../actions/accountPokemons';
import AccountPokemonRow from './AccountPokemonRow';
import {Link} from 'react-router-dom';
import { Button } from 'react-bootstrap';
class AccountPokemons extends Component {
componentDidMount() {
this.props.fetchAccountPokemons();
}
render() {
return (
<div>
<h3>Account Pokemons</h3>
{
this.props.accountPokemons.pokemons.map(pokemon => {
return (
<div key={pokemon.pokemonId}>
<AccountPokemonRow pokemon={pokemon} />
<hr />
</div>
)
})
}
<Link to='/'>Home</Link>
</div>
);
}
}
const mapStateToProps = (state) => {
const accountPokemons = state.accountPokemons;
return {accountPokemons};
}
export default connect(
mapStateToProps,
{ fetchAccountPokemons }
)(AccountPokemons);
<file_sep># Pokemon MarketPlace
A full stack web application where one can buy, sell as well as breed pokemons. It's simple and easy to use, just create your account and you're ready to go.
## Motivation
This is a self learning project to understand how a full stack web application is developed. This project is more of a way to get my feet wet in the area of web development.
## Installation
Clone the repository and fire the following commands in the respective directories.
### 1. /backend
1. Install all dependencies using
```bash
npm run install
```
2. Fire up backend using
```bash
npm run configure-dev
```
### 2. /frontend
1. Install all dependencies using
```bash
npm run install
```
2. Fire up backend using
```bash
npm run dev
```
**NOTES:**
1. Before firing up the backend, navigate to /backend/bin and modify the configdb.sh according to your environment. Open the file for more details.
2. Accordingly change the respective database related details in the /backend/secrets/databaseConfig.js.
2. Access the application at [**http://localhost:1234**](http://localhost:1234).
## Screenshots
1. **Login/Signup Page**
<br />

2. **Home Page**
<br />

3. **Account Pokemons**
<br />

4. **Public Pokemons**
<br />

## **Built Using**
1. [React](https://reactjs.org/) - A JavaScript library for building user interfaces.
2. [Node.js](https://reactjs.org/) - JavaScript runtime built on V8.
3. [Express.js](https://expressjs.com/) - A web framework for Node.js.
4. [Redux](https://redux.js.org/) - A Predictable State Container for JS Apps.
5. [PostgreSQL](https://www.postgresql.org/) - Relational Database.
<file_sep>import React from 'react';
import thunk from 'redux-thunk';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, compose, applyMiddleware } from 'redux';
import { Router, Switch, Route, Redirect } from 'react-router-dom';
import rootReducer from './reducers';
import './index.css';
import Root from './components/Root';
import AccountPokemons from './components/AccountPokemons';
import PublicPokemons from './components/PublicPokemons';
import { fetchAuthenticated } from './actions/account';
import history from './history'
//import createBrowserHistory from 'history/createBrowserHistory';
//THUNK is used to handle action objects which contains function instead of normal plain object functions
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
// const history = createBrowserHistory();
const store = createStore(
rootReducer,
composeEnhancer(applyMiddleware(thunk)),
);
const AuthRoute = (props) => {
if(!store.getState().account.loggedIn){
return(
<Redirect to={{pathname: '/'}}/>
)
}
const {component, path } = props;
return(
<Route path={path} component={component}/>
)
}
store.dispatch(fetchAuthenticated())
.then(() => {
render(
<Provider store={store}>
<Router history={history}>
<Switch>
<Route exact={true} path='/' component={Root} />
<AuthRoute path='/account-pokemons' component={AccountPokemons} />
<AuthRoute path='/public-pokemons' component={PublicPokemons} />
</Switch>
</Router>
</Provider>,
document.getElementById('root')
);
});
//store.subscribe(() => console.log('store state update', store.getState()));
/*
THIS FETCH FUNCTION IS IMPLEMENTED IN GENERATION COMPONENT BY BINDING THIS DISPATCH FUNCTION IN THAT COMPONENT
fetch('http://localhost:3000/generation')
.then(response => response.json())
.then(json => {
store.dispatch(generationActionCreator(json.generation))
})
*/
<file_sep>/*
const Pokemon = require('./pokemon.js');
const pikachu = new Pokemon({
birthdate: new Date(),
nickname: 'Pikachu'
});
const raichu = new Pokemon({
birthdate: new Date(),
nickname: 'Raichu'
});
const charlizard = new Pokemon({
birthdate: new Date(),
nickname: 'Charlizard',
traits: [{traitType: 'nature', traitValue: 'fire'}]})
setTimeout(() => {
const charmendar = new Pokemon();
console.log('charmendar', charmendar);
},3000);
console.log('pikachu', pikachu);
console.log('raichu', raichu);
console.log('charlizard', charlizard);
*/
/*
const Generation = require('./generation.js');
const generation = new Generation();
console.log('generation',generation);
const pikachu =generation.newDragon();
console.log('pikachu', pikachu);
setTimeout(() => {
const raichu = generation.newDragon();
console.log('raichu',raichu);
}, 4999);
*/
/*
const GenerationEngine = require('./engine.js');
const engine = new GenerationEngine();
engine.start();
setTimeout(() => {
engine.stop();
}, 20000);
*/
const express = require('express');
const cors = require('cors'); //const cors is a fn
const pokeRouter = require('./api/pokemon.js');
const genRouter = require('./api/generation.js');
const accRouter = require('./api/account.js');
const GenerationEngine = require('./generation/engine.js');
const cookieParser = require('cookie-parser');
const engine = new GenerationEngine();
const app = express();
const bodyParser = require('body-parser');
app.locals.engine = engine;
app.use(cors({origin: 'http://localhost:1234', credentials: true}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use('/account', accRouter);
app.use('/pokemon', pokeRouter);
app.use('/generation', genRouter);
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
res.status(statusCode).json({
type: 'error', message: err.message
});
})
engine.start();
module.exports = app;<file_sep>#!/bin/bash
# change the following fields according to your environment
# 1. PGPASSWORD
# 2. Replace 'username' with your own psql username
# 3. Replace 'database' with your own database name
export PGPASSWORD='<PASSWORD>'
echo "configuring pokemon database"
dropdb -U username database
createdb -U username database
psql -U username database < ./bin/sql/account.sql
psql -U username database < ./bin/sql/generation.sql
psql -U username database < ./bin/sql/pokemon.sql
psql -U username database < ./bin/sql/trait.sql
psql -U username database < ./bin/sql/pokemonTrait.sql
psql -U username database < ./bin/sql/accountPokemon.sql
node ./bin/insertTraits.js
echo "pokemon database configured"
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchGeneration } from '../actions/generation';
import fetchStates from '../reducers/fetchStates'
const DEFAULT_GENERATION = {
generationId: '',
expiration: ''
}
const MINIMUM_DELAY = 3000;
class Generation extends Component {
/*
constructor(){
this.state = {};
}
This can also be done using modern syntax of JS i.e. writing state={}
*/
state = { generation: DEFAULT_GENERATION };
timer = null;
componentDidMount() {
this.fetchNextGeneration();
}
componentWillUnmount() {
clearTimeout(this.timer);
}
/*
NO LONGER NEEDED SINCE THIS FUNCTION IS MAPPED TO PROPS OF THIS COMPONENT
fetchGeneration = () => {
fetch('http://localhost:3000/generation')
.then(response => response.json())
.then(json => {
console.log('json', json)
// below line is no longer needed since we use redux state instead of local state of this component
//this.setState({generation: json.generation});
/*this.props.dispatch(generationActionCreator(json.generation));
this.props.dispatchGeneration(json.generation);
})
.catch(error => console.log('error', error));
};
*/
fetchNextGeneration = () => {
this.props.fetchGeneration();
let delay = new Date(this.props.generation.expiration).getTime() - new Date().getTime();
if (delay < MINIMUM_DELAY) {
delay = MINIMUM_DELAY;
}
this.timer = setTimeout(() => this.fetchNextGeneration(), delay);
}
render() {
console.log('this.props', this.props);
/* const generation = this.state.generation
is equivalent to
const { generation } = this.state ---> this is called destructuring*/
const { generation } = this.props;
if (generation.status === fetchStates.error) {
return <div>{generation.message}</div>;
}
return (
<div>
<h3>Generation {generation.generationId}. Expires on: </h3>
{/* THIS IS THE WAY TO ADD COMMENTS IN JSX
new Date() returns the expiration field's date format in human readable form and since JSX renders string values we convert it by using .toString()
*/}
<h4>{new Date(generation.expiration).toString()}</h4>
</div>
)
}
}
const mapStateToProps = (state) => {
const generation = state.generation;
return { generation };
};
/*const mapDispatchToProps = (dispatch) => {
return {
/*dispatchGeneration: (generation) => dispatch(
generationActionCreator(generation)
),
fetchGeneration: () => fetchGeneration(dispatch)
};
};*/
const componentsConnector = connect(
mapStateToProps,
{ fetchGeneration });
export default componentsConnector(Generation);<file_sep>const pool = require('../../databasePool.js');
const traitTable = require('../trait/table.js')
class PokemonTraitTable {
static storePokemonTrait({ pokemonId, traitType, traitValue }) {
return new Promise((resolve, reject) => {
traitTable.getTraitId({ traitType, traitValue })
.then(({ traitId }) => {
pool.query(
'INSERT INTO pokemonTrait("traitId","pokemonId") VALUES($1, $2)',
[traitId, pokemonId],
(error, response) => {
if (error) return reject(error);
resolve();
}
)
});
});
}
}
module.exports = PokemonTraitTable;<file_sep>// holds global constants which defines the default behaviour of concept of generation works for pokemons
const SECONDS = 1000;
const MINUTES = SECONDS * 60;
const HOURS = MINUTES * 60;
const DAYS = HOURS * 24;
const STARTING_BALANCE = 50;
// the value of refresh rate for generation is unit
const REFRESH_RATE = 5;
module.exports = {
SECONDS,
MINUTES,
HOURS,
DAYS,
REFRESH_RATE,
STARTING_BALANCE
};
|
02c2b681b4ef598a795deb7dbb66a91c0ba7834c
|
[
"JavaScript",
"SQL",
"Markdown",
"Shell"
] | 22
|
SQL
|
parichay28/Pokemon-MarketPlace
|
95c63aa8714f0cc13f7b71387062fbea25fc8f07
|
61b9614a325f3414a019090f4d7dbc2a2c33e1d4
|
refs/heads/main
|
<repo_name>sambunthet/rice-home<file_sep>/components/Feature.js
import React from 'react';
import { Container, Row, Col } from "reactstrap";
import Image from "next/image";
const FeatureBox = (props) => {
return (
<>
{props.features.map((feature, key) =>
feature.id % 2 !== 0 ? (
<Row
key={key}
className={
feature.id === 1
? "align-items-center"
: "align-items-center mt-5"
}
>
<Col md={5} data-aos="fade-right">
<div>
<Image
src={feature.img}
alt="Picture of the author"
width={500}
height={500}
/>
</div>
</Col>
<Col md={{ size: 6, offset: 1 }} data-aos="fade-left">
<div className="mt-5 mt-sm-0 mb-4">
<div className="my-4">
<i className={feature.icon}></i>
</div>
<h5 className="text-dark font-weight-normal mb-3 pt-3">
{feature.title}
</h5>
<p className="text-muted mb-3 f-15">{feature.desc}</p>
<a href={feature.link} className="f-16 text-warning">
Read More <span className="right-icon ml-2">→</span>
</a>
</div>
</Col>
</Row>
) : (
<Row key={key} className="align-items-center mt-5">
<Col md={6} data-aos="fade-right">
<div className="mb-4">
<div className="my-4">
<i className="mdi mdi-account-group"></i>
</div>
<h5 className="text-dark font-weight-normal mb-3 pt-3">
{feature.title}
</h5>
<p className="text-muted mb-3 f-15">{feature.desc}</p>
<a href={feature.link} className="f-16 text-warning">
Read More <span className="right-icon ml-2">→</span>
</a>
</div>
</Col>
<Col
md={{ size: 5, offset: 1 }}
className="mt-5 mt-sm-0"
data-aos="fade-left"
>
<div>
<Image
src={feature.img}
alt="Picture of the author"
width={500}
height={500}
/>
</div>
</Col>
</Row>
)
)}
</>
);
}
const Feature = () => {
const features = [
{
id: 1,
img: "http://rice.com.kh/products/67/Zhao_Qing.jpg",
title: "<NAME>",
desc: "It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.",
link: "/",
},
{
id: 2,
img: "http://rice.com.kh/products/63/LF_Rice___U.jpg",
title: "<NAME>",
desc: "Sed perspiciatis unde omnis natus error voluptatem accusantium doloremque laudantium totam rem aperiam eaque ipsa quae ab illo excepturi sint occaecati cupiditate architecto.",
link: "/",
},
{
id: 3,
img: "http://rice.com.kh/products/53/400g1_copy.jpg",
title: "<NAME> CamRice",
desc: "It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.",
link: "/",
},
{
id: 4,
img: "http://rice.com.kh/products/56/Camrice_YS.jpg",
title: "Fine Rice Vermicelli CamRice",
desc: "It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.",
link: "/",
},
];
return (
<section className="section" id="feature">
<Container>
<Row className="justify-content-center">
<Col lg={6} md={8} data-aos="flip-left">
<div className="title text-center mb-5">
<h3 className="font-weight-normal text-dark">
<span className="text-warning">Rice Vermicelli</span>
</h3>
<p className="text-muted">
Indochina Rice Mill has gained the confidence and trust of our
valuable worldwide customers in our top quality rice and rice
vermicelli products. Armed with a serious management team and
our stringent quality control, we are here to consistently
provide the most competitive price and the best quality rice and
rice vermicelli to our customers, and are ready to be your
trustworthy partner.
</p>
</div>
</Col>
</Row>
<FeatureBox features={features} />
</Container>
</section>
);
}
export default Feature;
<file_sep>/components/About.js
import React from 'react';
import { Container, Row, Col } from "reactstrap";
import Link from "next/link";
const About = () => {
return (
<section className="section bg-light" id="about">
<Container>
<Row className="justify-content-center">
<Col lg={6} md={8}>
<div className="title text-center">
<h3 className="font-weight-normal text-dark">
About <span className="text-warning">Us</span>
</h3>
</div>
<div className="title text-left mb-5 text-muted">
{/* <h3 className="font-weight-normal text-dark">
About <span className="text-warning">Us</span>
</h3> */}
<ul>
<li>
<a>
Indochina Rice Mill has the capacity to produce large
quantities of quality rice and rice vermicelli to our
valuable customers all around the world.
</a>
</li>
<li>
<a>
Indochina Rice Mill is strategically located in Kompong
Chhnang Province on National Road No. 5 along the way to
Pursat province and Battambang province where the best
fragrant jasmine rice is grown.
</a>
</li>
<li>
<a>
The place is nature’s gift for farming being rich in fertile
soil, which produces excellent quality rice for our
customers.
</a>
</li>
<li>
<a>
We carefully select the best quality paddy for our premium
quality milled rice.
</a>
</li>
<li>
<a>
We are a reliable source with the ability to supply our
customers with a consistent product. Our factory’s warehouse
is able to store up to 30,000 metric tons using modern
machinery.
</a>
</li>
<li>
<a>
Honest and consistent, our company is growing continuously
and steadily; we endeavor to become your long term business
partner.
</a>
</li>
</ul>
</div>
</Col>
</Row>
<Row>
<Col md={4}>
<h2 className="font-weight-light line-height-1_6 text-dark mb-4">
Lorem Ipsum has been the industry's standard dummy text
</h2>
</Col>
<Col md={{ size: 7, offset: 1 }}>
<Row>
<Col md={6}>
<h6 className="text-dark font-weight-light f-20 mb-3">
Our Mission
</h6>
<p className="text-muted font-weight-light">
We are committed to collaborating with our business partners
around the world, supplying them with top quality products and
services.
</p>
</Col>
<Col md={6}>
<h6 className="text-dark font-weight-light f-20 mb-3">
Our Market
</h6>
<p className="text-muted font-weight-light">
Our core business is exporting premium quality rice and rice
vermicelli to Europe, USA, Australia, Africa, China, Hong Kong
etc…
</p>
</Col>
</Row>
</Col>
</Row>
</Container>
</section>
);
}
export default About;
|
164790e296f69fb613af044b4c963808e02e06cb
|
[
"JavaScript"
] | 2
|
JavaScript
|
sambunthet/rice-home
|
62b27eebabda979527cc3ee6f3d97dafe1b0eb26
|
4ff737ff7ea68e38a60f3affd2a69aa41b9c6733
|
refs/heads/master
|
<repo_name>enicho/go-socket<file_sep>/cmd/playground-term/render.go
package main
import (
termbox "github.com/nsf/termbox-go"
)
func main() {
err := termbox.Init()
if err != nil {
panic(err)
}
defer termbox.Close()
}
<file_sep>/socket/manager.go
package socket
import (
"log"
"net/http"
"github.com/gorilla/websocket"
)
type Manager struct {
upgrader websocket.Upgrader
}
func NewManager(in websocket.Upgrader) (obj *Manager) {
obj = &Manager{}
obj.upgrader = in
return
}
func (m *Manager) Echo(w http.ResponseWriter, r *http.Request) {
c, err := m.upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer c.Close()
for {
mt, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", message)
err = c.WriteMessage(mt, message)
if err != nil {
log.Println("write:", err)
break
}
}
}
<file_sep>/util/channel.go
package util
import (
"github.com/gomodule/redigo/redis"
)
var redisCli redis.Conn
func InitUtil() {
redisCli, _ = redis.Dial("tcp", ":6379")
}
func GetClient() redis.Conn {
if redisCli == nil {
InitUtil()
}
return redisCli
}
<file_sep>/cmd/server/app.go
package main
import (
"fmt"
"math/rand"
"net/http"
"strings"
"time"
"github.com/enicho/go-socket/util"
"github.com/gomodule/redigo/redis"
"github.com/gorilla/mux"
grace "gopkg.in/paytm/grace.v1"
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
func RandStringBytes(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
var (
matchName map[string]string
)
func main() {
matchName = make(map[string]string)
router := mux.NewRouter()
router.HandleFunc("/v1/register", Register).Methods("GET")
grace.Serve(":9002", router)
}
func Register(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "err: %v", err)
}
param1 := r.URL.Query().Get("name")
if param1 != "" {
result, err := redis.String(redis.DoWithTimeout(util.GetClient(), 10*time.Second, "GET", param1))
if err == nil {
if !strings.EqualFold(result, "") {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, result)
return
}
}
if val, ok := matchName[param1]; ok {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, val)
return
}
matchID := RandStringBytes(20)
matchName[param1] = matchID
redis.DoWithTimeout(util.GetClient(), 10*time.Second, "SET", param1, matchID)
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, matchName[param1])
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "ok")
return
}
<file_sep>/README.md
# go-socket
learning web socket implementation on gaoling
<file_sep>/app.go
package main
import (
"log"
"net/http"
"github.com/enicho/go-socket/socket"
"github.com/gorilla/websocket"
)
func main() {
sockManage := socket.NewManager(websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
}})
http.HandleFunc("/echo", sockManage.Echo)
log.Fatal(http.ListenAndServe(":8080", nil))
}
<file_sep>/cmd/sender/app.go
package main
import (
"bufio"
"log"
"net/url"
"os"
"os/signal"
"time"
"github.com/gorilla/websocket"
)
type (
SendData struct {
clientID string
message string
}
ReceiveData struct {
clientID string
message string
}
)
func main() {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
tmp := "ws://localhost:8080/ws?name=elliot"
// u := url.URL{Scheme: "ws", Host: "localhost:8080", Path: "/ws"}
u, _ := url.Parse(tmp)
log.Printf("connecting to %s", u.String())
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
done := make(chan struct{})
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
log.Printf("recv: %s", message)
}
}()
sendMsg := make(chan string)
go chat(sendMsg)
for {
select {
case <-done:
return
case t := <-sendMsg:
err := c.WriteMessage(websocket.TextMessage, []byte(t))
if err != nil {
log.Println("write:", err)
return
}
case <-interrupt:
log.Println("interrupt")
// Cleanly close the connection by sending a close message and then
// waiting (with timeout) for the server to close the connection.
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
select {
case <-done:
case <-time.After(time.Second):
}
return
}
}
}
func chat(c chan string) {
for {
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
c <- text
}
}
|
8e6c307294aa3194d7a978a1dc5fdacec92494d5
|
[
"Markdown",
"Go"
] | 7
|
Go
|
enicho/go-socket
|
abc2ebe458c30173227b64a6f6175e045cea3fbd
|
96b1f5cbb3317347b9e62b4ae300c0dc28288ac9
|
refs/heads/master
|
<file_sep>#Micro Reddit - an Odin Project
Check user.rb, post.rb, comment.rb in app/model folders
<file_sep>class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
validates :comment_title, presence: true
validates :comment_body, presence: true
end
|
1abefab2524192ef0269659b95f1276ed4327f17
|
[
"Markdown",
"Ruby"
] | 2
|
Markdown
|
Deepak5050/reddit_two
|
f319749301ab9a1fec2240fd7dc1b785978891f7
|
a39822bb260fe0d125cc396d6e3e989477f8597d
|
refs/heads/master
|
<repo_name>LuMistro/OpenWeatherApi<file_sep>/src/main/java/model/Temperatura.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 model;
/**
*
* @author <NAME>
*/
public class Temperatura {
private Main main;
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
@Override
public String toString() {
return "Temperatura{" + "main=" + main + '}';
}
}
<file_sep>/README.md
# OpenWeatherApi
Consumo de API de temperatura
<file_sep>/src/main/java/dao/daoTemp.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import com.google.gson.Gson;
import model.Temperatura;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
*
* @author <NAME>
*/
public class daoTemp {
private static Temperatura temperatura;
public static Double retornaTemperatura() {
String link = "http://api.openweathermap.org/data/2.5/weather?q=palho%C3%A7a,br&appid=a229614ea2dc0d9e7e48d2384b4d0779";
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(link);
HttpResponse resposta;
Gson gson = new Gson();
try {
resposta = closeableHttpClient.execute(get);
HttpEntity entity = resposta.getEntity();
String conteudo = EntityUtils.toString(entity);
temperatura = gson.fromJson(conteudo, Temperatura.class);
} catch (Exception e) {
}
return temperatura.getMain().getTemp();
}
}
|
9405f8e60b25758c1d33681a140641b94aa39e04
|
[
"Markdown",
"Java"
] | 3
|
Java
|
LuMistro/OpenWeatherApi
|
4677c2c35045486fdc15786715ba1bcaac5ddba5
|
8cd60e6d6f9e2c8ea01d3c0f332a96cc2d892a42
|
refs/heads/master
|
<file_sep><script type="text/javascript">
window.onload = function(){
//Check File API support
if(window.File && window.FileList && window.FileReader)
{
var filesInput = document.getElementById("files");
filesInput.addEventListener("change", function(event){
var files = event.target.files; //FileList object
var output = document.getElementById("result");
for(var i = 0; i< files.length; i++)
{
var file = files[i];
//Only pics
if(!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load",function(event){
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/>";
output.insertBefore(div,null);
});
//Read the image
picReader.readAsDataURL(file);
}
});
}
else
{
console.log("Your browser does not support File API");
}
}
</script>
<center><h1>Edit User</h1>
<?php foreach($lists as $value)
{
?>
<form name="edit" method="post" action="<?=base_url();?>controller/userupdate?id=<?php echo $value['userid'];?>" enctype="multipart/form-data">
<table>
<tr>
<tr><td><?php echo validation_errors();?></td></tr>
<td>Fullname</td><td><input type="text" name="fullname" value="<?php echo $value['fullname'];?>">
</td><td><?php //echo form_error('fullname');?></td></tr>
<tr><td>Username:</td><td><input type="text" name="username" value="<?php echo $value['username'];?>"></td></tr>
<tr><td>Password:</td><td><input type="<PASSWORD>" name="password" value="<?php echo $value['password'];?>"></td></tr>
<tr><td>Email Id:</td><td><input type="text" name="emailid" value="<?php echo $value['emailid'];?>"></td></tr>
<tr><td>Phone:</td><td><input type="text" name="phone" value="<?php echo $value['phone'];?>"></td></tr>
<tr><td>Uset type:</td><td><?php
$options=array(''=>'select','user'=>'user','candidate'=>'candidate');
echo form_dropdown('user_type',$options,$value['user_type']);?></td>
<td><?php echo form_error('user_type');?></td><tr><td>Image</td>
<td><input type="file" id="files" name="userfile[]" value="<?php echo base_url("/uploads/".$value['image']);?>" multiple/>
<input type="hidden" name="img" value="<?php echo $value['image'];?>">
<?php
//}
?>
</td>
<td> <?php
$str=$value['image'];
($data['img']=(explode(',',$str)));
foreach($data as $va){
// for($i=0;$i>=0;$i++){
$a= count($va);
for($i=0;$i<$a;$i++)
{
$st = $va[$i];
?>
<img src="<?php echo base_url("/uploads/".$st);?>" width="50" height="50" alt=""/>
<?php
}
}?></td>
<td></td></tr></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Update"></td></tr>
<tr><td><output id="result" /></td></tr>
<?php
}
?>
</table>
</form>
</center><file_sep><center><h1>Votting</h1>
<?php echo form_open('controller/addvote');
echo validation_errors();?>
<table>
<tr><th>Name</th><th>Vote</th><th>Rate</th></tr>
<tr> <?php
$i='0';
foreach ($lists as $value) {
//print_r($value);
//exit();
?>
<td> <?php echo $value['fullname'] ;?></td>
<?php echo form_hidden('text_'.$value['userid'],$value['fullname']);?>
<td><?php echo form_radio('vote',$value['userid']);?>
</td>
<td>
<?php
$options=array(''=>'select','0'=>'0','1'=>'1','2'=>'2','3'=>'3','4'=>'4','5'=>'5',
'6'=>'6','7'=>'7','8'=>'8','9'=>'9','10'=>'10');
;
echo form_dropdown($rate='rate_'.$value['userid'],$options);?>
</td></tr>
<?php
$i++;
}
?>
<tr><td colspan="3" align="center"><?php echo form_submit('submit','OK');?></td></tr>
</table>
</form>
</center><file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Auto Complete Input box</title>
<link rel="stylesheet" href="<?=base_url();?>css/jquery.ui.all.css">
<script src="<?=base_url();?>js/jquery-1.8.3.js"></script>
<script src="<?=base_url();?>js/ui/jquery.ui.core.js"></script>
<script src="<?=base_url();?>js/ui/jquery.ui.widget.js"></script>
<script src="<?=base_url();?>js/ui/jquery.ui.position.js"></script>
<script src="<?=base_url();?>js/ui/jquery.ui.menu.js"></script>
<script src="<?=base_url();?>js/ui/jquery.ui.autocomplete.js"></script>
<script>
$(document).ready(function(){
autocompletefn();
// $(".person").autocomplete( "search", "" );
// $('.person').click(function() {
// $('#autocomplete').trigger("focus"); //or "click", at least one should work
// });
$('.addbtn').live("click",function() {
$(this).remove();
$("#persons").append('<div><label>Person:</label><input name="tag1" type="text" class="person" size="20"/><button class="removebtn">-</button> <button class="addbtn">+</button></div>');
autocompletefn();
});
$(".removebtn").live("click",function() {
$( this ).parent().remove();
if($('.addbtn').length==0){
$("#persons div").last().append('<button class="addbtn">+</button>');
}
});
});
function autocompletefn(){
var availableTags = [
"MongoDB",
"ExpressJS",
"Angular",
"NodeJS",
"JavaScript",
"jQuery",
"jQuery UI",
"PHP",
"Zend Framework",
"JSON",
"MySQL",
"PostgreSQL",
"SQL Server",
"Oracle",
"Informix",
"Java",
"Visual basic",
"Yii",
"Technology",
"Wil<EMAIL>"
];
$( ".person" ).autocomplete({
source: availableTags ,
minLength: 0
}).focus(function(){
$(this).data("autocomplete").search($(this).val());
});
}
</script>
</head>
<body>
<div id="persons">
<div>
<label>Person:</label>
<input name="tag" type="text" id="tag1" class='person' size="20"/>
<button class="addbtn">+</button>
</div>
</div>
</body>
</html><file_sep><?php //echo anchor('controller/login','Back');?>
<!--<a href="<?=base_url();?>controller/login">Back</a>-->
<center><h1>Current Status</h1>
<table border="0" cellpaddig="5" cellspacing="5">
<tr><th>Candidate name</th><th></th><th>votes</th><th>Rate</th></tr>
<tr>
<?php
//print_r($query);
//print_r($lists);?>
<?php foreach($query as $value){
?>
<td><?php echo $value->candidate_name;?>
</td>
<td></td >
<td><?php echo $value->id;?>
</td>
<td><?php echo $value->rate;?>
</td>
</tr>
<?php
}
?>
</table>
</center><file_sep>
<center> <table>
<?php foreach($lists as $value)
{
?>
<tr>
<tr><td></td><td><?php
//print_r($value['image']);
$str=$value['image'];
($data['img']=(explode(',',$str)));
foreach($data as $va){
// for($i=0;$i>=0;$i++){
$a= count($va);
for($i=0;$i<$a;$i++)
{
$st = $va[$i];
?>
<img src="<?php echo base_url("/uploads/".$st);?>" width="50" height="50"/>
<?php
}
}
?></td></tr>
<td>Fullname</td><td><?php echo $value['fullname'];?></td></tr>
<tr><td>Username:</td><td><?php echo $value['username'];?></td></tr>
<tr><td>Password:</td><td><?php echo $value['password'];?></td></tr>
<tr><td>Email Id:</td><td><?php echo $value['emailid'];?></td></tr>
<tr><td>Phone:</td><td><?php echo $value['phone'];?></td></tr>
<tr><td>Uset type:</td><td><?php echo $value['user_type'];?></td></tr>
<tr><td>Id:</td><td><?php echo $value['id'];?></td></tr>
<?php
}
?>
</table>
</center><file_sep>
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<th>Username</th><th>Fullname</th>
</tr>
<?php
if($search!=null)
{
foreach ($search as $value)
{
?>
<tr>
<td><?php echo $value['username'] ?></td>
<td><?php echo $value['fullname'] ?></td>
</tr>
<?php
}
}
?>
</table>
</form><file_sep>
<?php //echo anchor('controller/add','Add User and Candidate');?>
<a href="<?=base_url();?>controller/search">Search</a>
<a href="<?=base_url();?>controller/add">Add user and candidate</a>
<a href="<?=base_url();?>controller/update">Publish List</a>
<center><table><tr><th>User Id</th><th>Fullname</th><th>Username</th><th>Password</th>
<th>Email Id</th><th>Phone</th><th>User type</th><th>Code</th><th>Image</th><th></th><th></th><th></th></tr>
<tr><?php
foreach ($lists as $value)
{
?>
<td><?php echo $value['userid'];?></td>
<td><?php echo $value['fullname'];?></td>
<td><?php echo $value['username'];?></td>
<td><?php echo $value['password'];?></td>
<td><?php echo $value['emailid'];?></td>
<td><?php echo $value['phone'];?></td>
<td><?php echo $value['user_type'];?></td>
<td><?php echo $value['id'];?></td>
<td>
<?php
//print_r($value['image']);
$str=$value['image'];
($data['img']=(explode(',',$str)));
foreach($data as $va){
// for($i=0;$i>=0;$i++){
$a= count($va);
for($i=0;$i<$a;$i++)
{
$st = $va[$i];
?>
<img src="<?php echo base_url("/uploads/".$st);?>" width="50" height="50"/>
<?php
}
}
?>
</td>
<td><a href="<?=base_url();?>controller/edit?id=<?php echo $value['userid'];?>">Edit</a></td>
<td><a href="<?=base_url();?>controller/delete?id=<?php echo $value['userid'];?>">Delete</a></td>
<td><a href="https://gmail.com">Mail</a></td></tr>
<?php
}
?>
</table></center><file_sep><?php
class model extends CI_Model{
public function validateUser($loginArray, $table)
{
return $this->db->select('*')->from($table)->where($loginArray)->get()->num_rows();
}
public function search()
{
$keyword=$_POST['keyword'];
$this->db->select('* from user');
$this->db->like('username','%".$keyword."%');
$query=$this->db->get();
return $query->result();
}
public function status()
{
$this->db->select(' count(voteid) as id,candidateid,candidate_name,sum(rate) as rate,status from vote');
$this->db->where('status',1);
$this->db->group_by('candidateid');
$query=$this->db->get();
return $query->result();
}
public function id()
{
$this->db->select('id from user');
$this->db->where('user_type','user');
$this->db->order_by('id','desc');
$query=$this->db->get();
return $query->row();
}
public function link()
{
$this->db->select('status from vote');
$this->db->where('status',1);
$this->db->group_by('status');
$query=$this->db->get();
return $query->result();
}
public function fetchRows($table,$fields=NULL,$condition=NULL,$extra=NULL)
{
if($extra==NULL)
{
if($condition != NULL && $fields != NULL)
{
$this->db->select($fields)->from($table)->where($condition);
$result11 = $this->db->get();
return($result11->result_array());
}
if($condition == NULL && $fields != NULL)
{
return $this->db->select($fields)->from($table)->get()->result_array();
}
if($condition != NULL && $fields == NULL)
{
$this->db->select('*')->from($table)->where($condition);
$result11 = $this->db->get();
return($result11->result_array());
}
if($condition == NULL && $fields == NULL)
{
$qr= $this->db->get($table)->result_array();
return $qr;
}
}
else
{
if($condition != NULL && $fields != NULL)
{
$this->db->select($fields)->from($table)->where($condition)->order_by($extra);
$result11 = $this->db->get();
return($result11->result_array());
}
if($condition == NULL && $fields != NULL)
{
$this->db->select($fields)->from($table)->order_by($extra);
$result11 = $this->db->get();
return($result11->result_array());
}
if($condition != NULL && $fields == NULL)
{
$this->db->select('*')->from($table)->where($condition);
$result11 = $this->db->get();
return($result11->result_array());
}
if($condition == NULL && $fields == NULL)
{ $this->db->order_by($extra);
$qr= $this->db->get($table)->result_array();
return $qr;
}
}
}
public function fetchRowOrderby($table,$spec=NULL,$condition=NULL,$extra=NULL)
{
$this->db->select('*');
$this->db->from($table);
foreach($extra as $key=>$v)
{
$this->db->join($key,$v,'INNER');
}
$this->db->where($condition);
$this->db->order_by($spec);
$query = $this->db->get();
return($query->result_array());
}
public function fetchRowsno($table,$fields=NULL,$condition=NULL,$extra=NULL)
{
if($condition != NULL && $fields != NULL)
{
return $this->db->select($fields)->from($table)->where_not_in($condition,$extra)->get()->result_array();
}
if($condition != NULL && $fields == NULL)
{
$this->db->select('*')->from($table)->where_not_in($condition,$extra);
$result11 = $this->db->get();
return($result11->result_array());
}
}
public function fetchRowJoin($table,$condition=NULL,$extra=NULL)
{
if($condition==NULL)
{
$this->db->select('*')->from($table);
foreach($extra as $key=>$v)
{
$this->db->join($key,$v,'INNER');
}
$query = $this->db->get();
return($query->result_array());
}
else
{
$this->db->select('*');
$this->db->from($table);
foreach($extra as $key=>$v)
{
$this->db->join($key,$v,'INNER');
}
$this->db->where($condition);
$query = $this->db->get();
return($query->result_array());
}
}
public function fetchRowsLike($table,$fields = NULL,$target = NULL,$item = NULL , $condition = NULL )
{
if($table!= NULL && $fields != NULL && $target != NULL && $item != NULL && $condition != NULL)
{
$this->db->select($fields);
$this->db->like($target, $item);
$this->db->from($table);
$this->db->where($condition);
$query = $this->db->get();
return($query->result_array());
}
elseif($table!= NULL && $fields != NULL && $target != NULL && $item != NULL && $condition == NULL)
{
$this->db->select($fields);
$this->db->like($target, $item);
$this->db->from($table);
$query = $this->db->get();
return($query->result_array());
}
return(0);
}
public function fetchSum($table,$fields,$condn)
{
$this->db->select_sum($fields)->from($table)->where($condn);
$er=$this->db->get();
return $er->result_array();
}
public function insertEntry($table,$fields)
{
return $this->db->insert($table,$fields);
}
public function updateEntry($fieldValues,$table,$condition)
{
return $this->db->update($table, $fieldValues, $condition);
}
public function deleteRows($table, $condition)
{
return $this->db->delete($table,$condition);
}
public function fetchJoinSpec($table,$condition=NULL,$extra=NULL,$type=NULL,$fields=NULL)
{
if($condition==NULL)
{
if($type=='groupby')
{
$this->db->select('*');
$this->db->from($table);
foreach($extra as $key=>$v)
{
$this->db->join($key,$v,'INNER');
}
$this->db->group_by($fields);
$query = $this->db->get();
return($query->result_array());
}
}
else
{
if($type=='groupby')
{
$this->db->select('*');
$this->db->from($table);
foreach($extra as $key=>$v)
{
$this->db->join($key,$v,'INNER');
}
$this->db->where($condition);
$this->db->group_by($fields);
$query = $this->db->get();
return($query->result_array());
}
}
}
public function fetchCalc($table,$condition=NULL,$fld=NULL,$type=NULL,$fields=NULL)
{
if($type=='groupby')
{
$this->db->select($fld);
$this->db->from($table);
if($condition){
$this->db->where($condition);
}
$this->db->group_by($fields);
$query = $this->db->get();
return($query->result_array());
}
}
function get_productcode($q)
{
$this->db->select('Product_Code');
$this->db->like('Product_Code', $q);
$query = $this->db->get('Product_Master');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['Product_Code'])); //build an array
}
echo json_encode($row_set); //format the array into json data
}
}
function get_customer($q){
$this->db->select('Customer_Name');
$this->db->like('Customer_Name', $q);
$query = $this->db->get('Customer_Master');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['Customer_Name'])); //build an array
}
echo json_encode($row_set); //format the array into json data
}
}
}
?>
<file_sep><script type="text/javascript">
function msglgth()
{
var password=document.login.password.value;
var a=document.getElementById('password').innerHTML='minimum 5 charecters : '+password.length;
if(password.length > 5 && password.length < 50) {
document.getElementById('password').style.color="blue";
}
else {
document.getElementById('password').style.color="red";
}
}
</script>
<?php //echo anchor('base_url()controller/status','View Status of the Candidates');
foreach($content as $value)
{
if($value->status==1)
{
?>
<a href="<?=base_url();?>controller/status">View Status of the Candidates</a>
<?php
}
}
?>
<center><h1>Login</h2>
<?php //echo form_open('controller/login');
//echo validation_errors();?>
<form name="login" method="post" action="<?=base_url();?>controller/login">
<table>
<tr><td>Username:</td><td><?php echo form_input('username');?></td>
<td><?php echo form_error('username');?></td></tr>
<tr><td>Password:</td><td><input type="password" name="password" value="" onkeyup="msglgth()"></td><td><?php
echo form_error('password');?></td><td><div id="password"></div></td></tr>
<tr><td colspan="2" align="center">
<?php //echo form_submit('submit','Login');?>
<input type="submit" name="submit" value="Login" onClick="return submitvalidation()"/>
</td></tr>
</table>
</form>
</center><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Viewmanager {
private $CI;
function __construct()
{
$this->CI =& get_instance();
$this->CI->load->helper('url');
$this->CI->load->library('session');
$this->CI->load->library('authentication');
}
/** Clear the old cache (usage optional) **/
public function loadView($page_view , $data , $extra = NULL)
{
/*echo "<pre>"; print_r($page_view); print_r($data);
$base_url = $this->CI->config->item('base_url');
print_r($base_url);
exit(); */
$base_url = $this->CI->config->item('base_url');
$this->CI->session->breadCrumList = array('Dashboard' => 'dashboard');
$data['base_url'] = $base_url ;
$data['base_url_main'] = $base_url."../" ;
$data['userDetails'] = $this->CI->authentication->getUserDetails();
$data['page_title'] = 'Dashboard' ;
$data['breadCrumList'] = $this->getBreadCrums() ;
$this->CI->load->view('include/header',$data);
$this->CI->load->view('include/slidingbar',$data);
$this->CI->load->view('include/topbar',$data);
$this->CI->load->view('include/pageslideleft',$data);
$this->CI->load->view('include/pageslideright',$data);
$this->CI->load->view('include/maincontainer',$data);
$this->CI->load->view($page_view, $data);
if($extra){
$this->CI->load->view($extra, $data);
}
$this->CI->load->view('include/footer',$data);
}
public function getBreadCrums()
{
foreach ($this->CI->session->breadCrumList as $breadCrumItem => $value) {
$breadCrums[$breadCrumItem] = $value;
}
return $breadCrums;
}
}
/* End of file Someclass.php */<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Authentication {
private $CI;
function __construct()
{
$this->CI =& get_instance();
$this->CI->load->helper('url');
$this->CI->load->library('session');
}
/** Clear the old cache (usage optional) **/
public function no_cache()
{
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0',false);
header('Pragma: no-cache');
}
//function no_cache ends here
public function check_login($user_type = NULL)
{
if(
($this->CI->session->userdata('username') &&
($this->CI->session->userdata('role')=='admin')) ||
($this->CI->session->userdata('role')=='user')
)
{ }
else
{
redirect('login/logout');
exit();
}
}
public function getUserDetails()
{
foreach ($this->CI->session->userdata as $user_data => $value) {
$user[$user_data] = $value;
}
return $user;
}
}
/* End of file Someclass.php */<file_sep><?php foreach($vote as $value)
{
?>
<a href="<?=base_url();?>controller/profile?id=<?php echo $value['userid'];?>">View profile</a>
<center><table cellpadding="10" cellspacing="10">
<tr><th >Candidate name:</th><td><?php echo $value['candidate_name'];?></td></tr>
<tr><th>Rate:</th><td><?php echo $value['rate'];?></td></tr>
<?php
}?>
</table></center><file_sep><?php
if(! defined('BASEPATH')) exit('No direct access');
class controller extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->model('model');
$this->load->helper('url');
$this->load->helper('form');
}
public function index()
{
$this->load->view('header');
$this->load->view('login');
$this->load->view('layout');
}
public function logout()
{
//$this->session->unset_userdata($newdata);
$this->session->sess_destroy();
redirect('controller/login');
}
public function no_cache()
{
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0',false);
header('Pragma: no-cache');
}
public function checkUser(){
$a = $this->no_cache();
$userData = $this->session->all_userdata();
echo "<pre>";
//print_r($userData['loginStatus']) ;
if (!$userData['loginStatus']) {
redirect('controller/logout');
return(0);
}
else{
return(1);
}
}
public function admin()
{
if ($userData['user_type']!='admin') {
redirect('controller/logout');
return(0);
}
else {
return(1);
}
}
public function login()
{
$data['data']=$this->model->link();
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'username','required' );
$this->form_validation->set_rules('password', '<PASSWORD>','<PASSWORD>]' );
if($this->form_validation->run()== FALSE)
{
$this->load->view('header');
$this->load->view('login',$data);
$this->load->view('layout');
}
else
{
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
//$userid=$_POST['userid'];
if(isset($username))
{
$cond=array(
"username"=>addslashes($username),
"password"=>addslashes($password),
//"userid"=>addslashes($userid),
//"Login_Password"=>addslashes( md5($_POST['password']) )
);
$userData=$this->model->fetchRows("user",NULL,$cond,NULL);
//print_r($userData);
if ($userData!=NULL )
{
$newdata = array(
'username' =>$userData[0]['username'],
'password'=>$<PASSWORD>[0]['<PASSWORD>'],
'loginStatus'=>1,
'user_type'=>$userData[0]['user_type'],
'userid'=>$userData[0]['userid'],
);
$this->session->set_userdata($newdata);
$userData = $this->session->all_userdata();
if ($userData['user_type']=='admin') {
redirect('controller/view');
}
else
$username = $_POST['username'];
if(isset($username))
{
$cond=array(
"username"=>addslashes($username),
//"userid"=>addslashes($userid),
//"Login_Password"=>addslashes( md5($_POST['password']) )
);
$userData=$this->model->fetchRows("vote",NULL,$cond,NULL);
//print_r($userData);
if ($userData!=NULL )
{
redirect('controller/viewvote');
}
else
redirect('controller/vote');
}
}
else
{
redirect('controller/login');
}
}
}
}
public function view()
{
//$c=$this->admin();
$r = $this->checkUser();
$table='user';
$fields = NULL;
$condition = NULL;
$data['lists'] = $this->model->fetchRows($table,$fields,$condition);
//print_r
$this->load->view('header');
$this->load->view('list',$data);
$this->load->view('layout');
}
public function profile()
{
$r = $this->checkUser();
$id=$_GET['id'];
$table='user';
$fields = NULL;
$condition = array('userid'=>$id);
$data['lists'] = $this->model->fetchRows($table,$fields,$condition);
$this->load->view('header');
$this->load->view('profile',$data);
$this->load->view('layout');
}
public function add()
{
//$upload=$this->do_upload();
$r = $this->checkUser();
$this->load->library('form_validation');
$this->form_validation->set_rules('fullname', 'fullname','required' );
$this->form_validation->set_rules('username', 'username', 'required');
$this->form_validation->set_rules('password', '<PASSWORD>','<PASSWORD>' );
$this->form_validation->set_rules('emailid', 'emailid', 'required');
$this->form_validation->set_rules('phone', 'phone', 'required');
$this->form_validation->set_rules('user_type', 'user_type', 'required');
if (empty($_FILES['image']['name'])) {
$this->form_validation->set_rules('image', 'Document', 'required');
}
if($this->form_validation->run()== FALSE)
{
//$data['content']=
$this->load->view('header');
$this->load->view('useradd');
$this->load->view('layout');
}
else{
$upload=$this->do_upload();
print_r($upload);
$entry_data = array(
'fullname' => addslashes($_POST['fullname']),
'username' => addslashes($_POST['username']),
'password' =>addslashes($_POST['<PASSWORD>']),
'emailid' =>addslashes($_POST['emailid']),
'phone' =>addslashes($_POST['phone']),
'user_type' =>addslashes($_POST['user_type']),
'image'=>addslashes($upload)
// 'image'=>addslashes($image)
);
$this->model->insertEntry("user",$entry_data);
// print_r($entry_data);
$this->load->view('header');
redirect('controller/view');
$this->load->view('layout');
}
}
public function edit()
{
$r = $this->checkUser();
$id=$_GET['id'];
$table='user';
$fields = NULL;
$condition = array('userid'=>$id);
$data['lists'] = $this->model->fetchRows($table,$fields,$condition);
$this->load->view('header');
$this->load->view('edit',$data);
$this->load->view('layout');
}
public function userupdate()
{
//$upload=$this->do_upload();
$r = $this->checkUser();//print_r($_POST);exit;
/*//$this->load->library('form_validation');
//$this->form_validation->set_rules('fullname', 'fullname','required' );
$this->form_validation->set_rules('username', 'username', 'required');
$this->form_validation->set_rules('password', '<PASSWORD>','<PASSWORD>' );
$this->form_validation->set_rules('emailid', 'emailid', 'required');
$this->form_validation->set_rules('phone', 'phone', 'required');
$this->form_validation->set_rules('user_type', 'user_type', 'required');
$this->form_validation->set_rules('image', 'document', 'required');
if($this->form_validation->run()== FALSE)
{
$id=$_GET['id'];
$table='user';
$fields = NULL;
$condition = array('userid'=>$id);
$data['lists'] = $this->model->fetchRows($table,$fields,$condition);
$this->load->view('header');
$this->load->view('edit',$data);
$this->load->view('layout');
}
else
{*/
$this->load->library('form_validation');
$this->form_validation->set_rules('fullname', 'fullname','required' );
$this->form_validation->set_rules('username', 'username', 'required');
$this->form_validation->set_rules('password', '<PASSWORD>','<PASSWORD>' );
$this->form_validation->set_rules('emailid', 'emailid', 'required');
$this->form_validation->set_rules('phone', 'phone', 'required');
$this->form_validation->set_rules('user_type', 'user_type', 'required');
if (empty($_FILES['image']['name'])) {
$this->form_validation->set_rules('image', 'Document', 'required');
}
if($this->form_validation->run()== FALSE)
{
//$data['content']=
$this->load->view('header');
redirect('controller/edit');
$this->load->view('layout');
}
else{
$id=$_GET['id'];
//echo $id;exit;print_r($_POST);exit;
$cond = array('userid'=>$id);
$upload=$this->do_upload();
// print_r($upload);
$entry_data = array(
'fullname' => addslashes($_POST['fullname']),
'username' => addslashes($_POST['username']),
'password' =>addslashes($_POST['<PASSWORD>']),
'emailid' =>addslashes($_POST['emailid']),
'phone' =>addslashes($_POST['phone']),
'user_type' =>addslashes($_POST['user_type']),
'image' =>addslashes($upload)
);
// echo '<pre>';
//print_r($entry_data);exit;
$userData=$this->model->updateEntry($entry_data,"user",$cond);
redirect('controller/view');
} //}
}
public function delete()
{
$id=$_GET['id'];
$cond=array("userid"=>$id);
$this->model->deleteRows("user",$cond);
redirect('controller/view');
}
public function vote()
{
$r = $this->checkUser();
$table='user';
$fields = NULL;
$condition =array('user_type'=>'candidate') ;
$data['lists'] = $this->model->fetchRows($table,$fields,$condition);
$this->load->view('header');
$this->load->view('voteform',$data);
$this->load->view('layout');
}
public function addvote()
{
$r = $this->checkUser();
$this->load->library('form_validation');
$this->form_validation->set_rules('vote', 'vote','required' );
if(isset($_POST['vote'])){
$this->form_validation->set_rules('rate_'.$_POST['vote'], 'Rating', 'required');
}
if($this->form_validation->run()== FALSE)
{
$table='user';
$fields = NULL;
$condition =array('user_type'=>'candidate') ;
$data['lists'] = $this->model->fetchRows($table,$fields,$condition);
$this->load->view('header');
$this->load->view('voteform',$data);
$this->load->view('layout');
}
else
{
$table='user';
$fields = NULL;
$condition =array('user_type'=>'candidate') ;
$data['lists'] = $this->model->fetchRows($table,$fields,$condition);
//_p$userid=$this->session->userData('userid');
//echo "<pre>";
//print_r($_POST);
//exit();
$entry_data = array(
'candidateid' => addslashes($_POST['vote']),
'candidate_name' => addslashes($_POST['text_'.$_POST['vote']]),
'username' => addslashes($this->session->userData('username')),
'userid'=>addslashes($this->session->userData('userid')),
'vote' =>addslashes($_POST['vote']),
'rate' =>addslashes($_POST['rate_'.$_POST['vote']]),
'status'=>0
);
$this->model->insertEntry("vote",$entry_data);
$this->load->view('header');
//print_r($_POST);
redirect('controller/viewvote');
$this->load->view('layout');
}
}
public function viewvote()
{
$r = $this->checkUser();
$userData = $this->session->all_userdata();
$table='vote';
$fields = NULL;
$condition = array('username'=>$this->session->userData('username'));
$data['vote'] = $this->model->fetchRows($table,$fields,$condition);
$this->load->view('header');
$this->load->view('viewvote',$data);
$this->load->view('layout');
}
public function update()
{
$cond=NULL;
$entry_data = array(
'status' => 1
);
$userData=$this->model->updateEntry($entry_data,"vote",$cond);
redirect('controller/status');
}
public function status()
{
//$r = $this->checkUser();
$data['query']=$this->model->status();
//$table='vote';
//$fields = NULL;
//$condition=NULL;
//$data['view'] = $this->model->fetchRows($table,$fields,$condition);
$this->load->view('header');
$this->load->view('status',$data);
$this->load->view('layout');
}
public function do_upload()
{
if (!empty($_FILES['image']['name'])) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '10240';
$config['max_height'] = '7680';
$this->load->library('upload', $config);//print_r($_FILES);exit;
if (!$this->upload->do_upload('image')) {
$error = array('error' => $this->upload->display_errors());
$this->form_validation->set_message('image', $this->upload->display_errors());
$this->load->view('header');
$this->load->view('useradd');
$this->load->view('layout');
}
else {
$upload_data = $this->upload->data();
$image =$upload_data['file_name'];
return $image;
//print_r($image);
//_p$userid=$this->session->userData('userid');
//echo "<pre>";
//print_r($_POST);
//exit();
/*$entry_data = array(
'image' => addslashes($upload_data['file_name']),
);
$this->model->insertEntry("user",$entry_data);*/
}
}
}
}
?>
<!--$userData = $this->session->all_userdata();
$userData['user_type'] = 'user'
$this->session->set_userdata($userData);--><file_sep><style type="text/css">
.req{color:red}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function() {
// alert('in ajax post');
$.post('<?=base_url();?>controller/addsave',
$('#forme').serialize()).done(function(data){
alert(data);
});
});
});
// $.post("<?=base_url();?>controller/addsave",
// $("#submit").serialize()).done(function(s){
// location.reload(true); });
function validation()
{
var fullname=document.add.fullname.value;
var username=document.add.username.value;
var password=<PASSWORD>;
var emailid=document.add.emailid.value;
var phone=document.add.phone.value;
var user_type=document.add.user_type.value;
//var userfile[]=document.add.userfile[].value;
var flg=0;
if(fullname=='')
{
flg=1;
document.getElementById('fullname').innerHTML="Please enter fullname";
}
if(username=='')
{
flg=1;
document.getElementById('username').innerHTML="Please enter username";
}
if(password=='')
{
flg=1;
document.getElementById('password').innerHTML="<PASSWORD>";
}
if(emailid=='')
{
flg=1;
document.getElementById('emailid').innerHTML="Please enter emailid";
}
if(phone=='')
{
flg=1;
document.getElementById('phone').innerHTML="Please enter phone";
}
if(user_type=='')
{
flg=1;
document.getElementById('user_type').innerHTML="Please enter user_type";
}
if(flg==0)
{
return true;
}
else
{
return false;
}
}
window.onload = function(){
//Check File API support
if(window.File && window.FileList && window.FileReader)
{
var filesInput = document.getElementById("files");
filesInput.addEventListener("change", function(event){
var files = event.target.files; //FileList object
var output = document.getElementById("result");
for(var i = 0; i< files.length; i++)
{
var file = files[i];
//Only pics
if(!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load",function(event){
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/>";
output.insertBefore(div,null);
});
//Read the image
picReader.readAsDataURL(file);
}
});
}
else
{
console.log("Your browser does not support File API");
}
}
</script>
<?php //echo anchor('controller/view','Back');?>
<a href="<?=base_url();?>controller/view">Back</a>
<center><h1>USER ADD</h1>
<form action="#" name="add" method="post" id="forme" enctype="multipart/form-data">
<?php //echo form_open_multipart('controller/add');
//echo validation_errors();
?>
<table>
<tr><td>Fullname:</td>
<td><span class="req"><?php echo form_error('fullname');?><div id="fullname"></span></div>
<?php echo form_input('fullname');?></td></tr>
<tr><td>Username:</td>
<td><span class="req"><?php echo form_error('username');?><div id="username"></div></span>
<?php echo form_input('username');?></td></tr></tr>
<tr><td>Password:</td>
<td><span class="req"><?php echo form_error('password');?><div id="password"></div></span>
<?php echo form_password('password');?></td></tr>
<tr><td>Email Id:</td>
<td><span class="req"><?php echo form_error('emailid');?><div id="emailid"></div></span>
<?php echo form_input('emailid');?></td></tr>
<tr><td>Phone:</td>
<td><span class="req"><?php echo form_error('phone');?><div id="phone"></div></span>
<?php echo form_input('phone');?></td>
</tr>
<tr><td>User Type:</td>
<td><span class="req"><?php echo form_error('user_type');?><div id="user_type"></div></span><?php
$options=array(''=>'select','user'=>'user','candidate'=>'candidate');
echo form_dropdown('user_type',$options);?></td>
</tr>
</tr> <td>Image:</td> <td><input id="files" type="file" name="userfile[]" multiple/></td><td><?php //echo form_error('image');?></td></tr>
<tr><td colspan="2" align="center"><?php //echo form_submit('submit','Add'); ?>
<input type="button" name="submit" value="Add" id="submit" onClick="return validation()"/ >
</td><td><output id="result" /></td></tr>
</table>
</form></center>
<file_sep><?php
if(! defined('BASEPATH')) exit('No direct access');
class controller extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->model('model');
$this->load->helper('url');
$this->load->helper('form');
$this->log->no_cache();
}
public function index()
{ $data['content']=$this->model->link();
$this->load->view('header');
$this->load->view('login',$data);
$this->load->view('layout');
}
public function logout()
{
$this->session->unset_userdata($newdata);
$this->session->sess_destroy();
redirect('controller/login');
}
public function checkUser(){
//$a = $this->no_cache();
$userData = $this->session->all_userdata();
echo "<pre>";
//print_r($userData['loginStatus']) ;
if (!$userData['loginStatus']) {
redirect('controller/logout');
return(0);
}
else{
return(1);
}
}
public function admin()
{
if ($userData['user_type']!='admin') {
redirect('controller/logout');
return(0);
}
else {
return(1);
}
}
public function login()
{
$data['content']=$this->model->link();
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'username','required' );
$this->form_validation->set_rules('password', 'password','required|min_length[5]|max_length[12]' );
if($this->form_validation->run()== FALSE)
{
$this->load->view('header');
$this->load->view('login',$data);
$this->load->view('layout');
}
else
{
$username = $_POST['username'];
$password = $_POST['password'];
//$userid=$_POST['userid'];
if(isset($username))
{
$cond=array(
"username"=>addslashes($username),
"password"=>addslashes($<PASSWORD>),
//"userid"=>addslashes($userid),
//"Login_Password"=>addslashes( md5($_POST['password']) )
);
$userData=$this->model->fetchRows("user",NULL,$cond,NULL);
//print_r($userData);
if ($userData!=NULL )
{
$newdata = array(
'username' =>$userData[0]['username'],
'password'=>$userData[0]['password'],
'loginStatus'=>1,
'user_type'=>$userData[0]['user_type'],
'userid'=>$userData[0]['userid'],
);
$this->session->set_userdata($newdata);
$userData = $this->session->all_userdata();
if ($userData['user_type']=='admin') {
redirect('controller/view');
}
else
$username = $_POST['username'];
if(isset($username))
{
$cond=array(
"username"=>addslashes($username),
//"userid"=>addslashes($userid),
//"Login_Password"=>addslashes( md5($_POST['password']) )
);
$userData=$this->model->fetchRows("vote",NULL,$cond,NULL);
//print_r($userData);
if ($userData!=NULL )
{
redirect('controller/viewvote');
}
else
redirect('controller/vote');
}
}
else
{
redirect('controller/login');
}
}
}
}
public function view()
{
//$c=$this->admin();
$r = $this->checkUser();
$table='user';
$fields = NULL;
$condition = NULL;
$data['lists'] = $this->model->fetchRows($table,$fields,$condition);
//print_r
$this->load->view('header');
$this->load->view('list',$data);
$this->load->view('layout');
}
public function profile()
{
$r = $this->checkUser();
$id=$_GET['id'];
$table='user';
$fields = NULL;
$condition = array('userid'=>$id);
$data['lists'] = $this->model->fetchRows($table,$fields,$condition);
$this->load->view('header');
$this->load->view('profile',$data);
$this->load->view('layout');
}
public function add()
{
$r = $this->checkUser();
// $this->load->view('header');
$this->load->view('useradd');
$this->load->view('layout');
//$upload=$this->do_upload();
//$this->load->view('header');
///redirect('controller/view');
//$this->load->view('layout');
}
public function addsave()
{
$r = $this->checkUser();
$this->load->library('form_validation');
$this->form_validation->set_rules('fullname', 'fullname','required' );
$this->form_validation->set_rules('username', 'username', 'required');
$this->form_validation->set_rules('password', '<PASSWORD>','<PASSWORD>' );
$this->form_validation->set_rules('emailid', 'emailid', 'required');
$this->form_validation->set_rules('phone', 'phone', 'required');
$this->form_validation->set_rules('user_type', 'user_type', 'required');
//if (empty($_FILES['userfile']['name'])) {
// $this->form_validation->set_rules('userfile[]', 'Document', 'required');
//}
if($this->form_validation->run()== FALSE)
{
$this->load->view('header');
$this->load->view('useradd');
$this->load->view('layout');
}
else
{
$upload=$this->do_upload();
//print_r($upload);
$condition=array('user_type'=>$_POST['user_type']);
$table='user';
$fields='id';
$extra='id desc';
$data['lists'] = $this->model-> fetchrows($table,$fields, $condition,$extra);
// print_r($data); exit;
//echo $data[0]['id'];
// exit;
// $data['query'] = $this->model->id();
//$ids = array();
foreach($data as $value){
$str = $value[0]['id'];
}
$a=substr($str,3,7);
$b= ltrim($a,0);
$new=$b+1;
if($b==0)
{
$i=1;
}
else{
$i=$new;
}
if($_POST['user_type']=='candidate')
{
$str = "CAN";
}
else
{
$str='USR';
}
$id= $str.str_pad($i,4,0,STR_PAD_LEFT);
$entry_data = array(
'fullname' => addslashes($_POST['fullname']),
'username' => addslashes($_POST['username']),
'password' =>add<PASSWORD>($_POST['<PASSWORD>']),
'emailid' =>addslashes($_POST['emailid']),
'phone' =>addslashes($_POST['phone']),
'user_type' =>addslashes($_POST['user_type']),
'image'=>addslashes($upload),
'id'=>addslashes($id)
);
//print_r($entry_data);exit;
$this->model->insertEntry("user",$entry_data);
// print_r($entry_data);
echo "success";
}
}
public function edit()
{
$r = $this->checkUser();
$id=$_GET['id'];
$table='user';
$fields = NULL;
$condition = array('userid'=>$id);
$data['lists'] = $this->model->fetchRows($table,$fields,$condition);
$this->load->view('header');
$this->load->view('edit',$data);
$this->load->view('layout');
}
public function userupdate()
{
// $upload=$this->do_upload();
// print_r($upload);
$r = $this->checkUser();//print_r($_POST);exit;
$this->load->library('form_validation');
$this->form_validation->set_rules('fullname', 'fullname','required' );
$this->form_validation->set_rules('username', 'username', 'required');
$this->form_validation->set_rules('password', 'password','required' );
$this->form_validation->set_rules('emailid', 'emailid', 'required');
$this->form_validation->set_rules('phone', 'phone', 'required');
$this->form_validation->set_rules('user_type', 'user_type', 'required');
$this->form_validation->set_rules('img', 'image', 'required');
// if (empty($_FILES['image']['name'])) {
// $this->form_validation->set_rules('image', 'Document', 'required');
// }
if($this->form_validation->run()== FALSE)
{
$this->load->view('header');
$id=$_GET['id'];
$table='user';
$fields = NULL;
$condition = array('userid'=>$id);
$data['lists'] = $this->model->fetchRows($table,$fields,$condition);
$this->load->view('header');
$this->load->view('edit',$data);
$this->load->view('layout');
//$this->load->view('layout');
}
else
{
$upload=$this->do_upload();
$id=$_GET['id'];
//$upload=$this->do_upload();
//echo $id;exit;print_r($_POST);exit;
$cond = array('userid'=>$id);
//$upload=$this->do_upload();
$a=$upload;
// print_r($upload);
if($upload==''){
$a=$_POST['img'];
}
//print_r($a);
// exit;
$entry_data = array(
'fullname' => addslashes($_POST['fullname']),
'username' => addslashes($_POST['username']),
'password' =>addslashes($_POST['<PASSWORD>']),
'emailid' =>addslashes($_POST['emailid']),
'phone' =>addslashes($_POST['phone']),
'user_type' =>addslashes($_POST['user_type']),
'image' =>addslashes($a)
);
// echo '<pre>';
// print_r($entry_data);exit;
$userData=$this->model->updateEntry($entry_data,"user",$cond);
redirect('controller/view');
} //}
}
public function delete()
{
$id=$_GET['id'];
$cond=array("userid"=>$id);
$this->model->deleteRows("user",$cond);
redirect('controller/view');
}
public function vote()
{
$r = $this->checkUser();
$table='user';
$fields = NULL;
$condition =array('user_type'=>'candidate') ;
$data['lists'] = $this->model->fetchRows($table,$fields,$condition);
$this->load->view('header');
$this->load->view('voteform',$data);
$this->load->view('layout');
}
public function addvote()
{
$r = $this->checkUser();
$this->load->library('form_validation');
$this->form_validation->set_rules('vote', 'vote','required' );
if(isset($_POST['vote'])){
$this->form_validation->set_rules('rate_'.$_POST['vote'], 'Rating', 'required');
}
if($this->form_validation->run()== FALSE)
{
$table='user';
$fields = NULL;
$condition =array('user_type'=>'candidate') ;
$data['lists'] = $this->model->fetchRows($table,$fields,$condition);
$this->load->view('header');
$this->load->view('voteform',$data);
$this->load->view('layout');
}
else
{
$table='user';
$fields = NULL;
$condition =array('user_type'=>'candidate') ;
$data['lists'] = $this->model->fetchRows($table,$fields,$condition);
//_p$userid=$this->session->userData('userid');
//echo "<pre>";
//print_r($_POST);
//exit();
$entry_data = array(
'candidateid' => addslashes($_POST['vote']),
'candidate_name' => addslashes($_POST['text_'.$_POST['vote']]),
'username' => addslashes($this->session->userData('username')),
'userid'=>addslashes($this->session->userData('userid')),
'vote' =>addslashes($_POST['vote']),
'rate' =>addslashes($_POST['rate_'.$_POST['vote']]),
'status'=>0
);
$this->model->insertEntry("vote",$entry_data);
$this->load->view('header');
//print_r($_POST);
redirect('controller/viewvote');
$this->load->view('layout');
}
}
public function viewvote()
{
$r = $this->checkUser();
$userData = $this->session->all_userdata();
$table='vote';
$fields = NULL;
$condition = array('username'=>$this->session->userData('username'));
$data['vote'] = $this->model->fetchRows($table,$fields,$condition);
$this->load->view('header');
$this->load->view('viewvote',$data);
$this->load->view('layout');
}
public function update()
{
$cond=NULL;
$entry_data = array(
'status' => 1
);
$userData=$this->model->updateEntry($entry_data,"vote",$cond);
redirect('controller/status');
}
public function status()
{
//$r = $this->checkUser();
$data['query']=$this->model->status();
//$table='vote';
//$fields = NULL;
//$condition=NULL;
//$data['view'] = $this->model->fetchRows($table,$fields,$condition);
$this->load->view('header');
$this->load->view('status',$data);
$this->load->view('layout');
}
public function search()
{
// $keyword=$_POST['keyword'];
// $data['search']= $this->model->search();
// $this->load->view('search');
$this->load->view('search');
$table='user';
$fields = 'username';
$data['lists'] = $this->model->fetchRows($table,$fields);
}
public function searchlist($w =NULL)
{
// $a = array("PHp","AppleScript","Asp","BASIC","C","Apple");
$vnames= array();
//echo json_encode($a);
//die();
$table='user';
$fields = 'username';
$data['lists'] = $this->model->fetchRows($table,$fields);
foreach ($data as $value) {
$a=count($value);
for($i=0;$i<$a;$i++){
$vnames[] = $value[$i]['username']."\n";
}echo json_encode($vnames);
// echo json_encode($vnames);
}
}
public function do_upload()
{
$name_array = array();
echo '<pre>';
print_r($_POST);
//print_r($_FILES);
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++) {
$_FILES['userfile']['name']=$value['name'][$s];
$_FILES['userfile']['type'] = $value['type'][$s];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['userfile']['error'] = $value['error'][$s];
$_FILES['userfile']['size'] = $value['size'][$s];
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name'];
}
$image= implode(',', $name_array);
print_r($image);
return $image;
//echo $image;
//print_r($image) ;
}
}
?><file_sep>
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Log {
private $CI;
function __construct()
{
$this->CI =& get_instance();
$this->CI->load->helper('url');
$this->CI->load->library('session');
}
public function no_cache()
{
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0',false);
header('Pragma: no-cache');
}
}
|
b13ef754bd738b324a78e80785492fef2855de90
|
[
"PHP"
] | 16
|
PHP
|
goleevia/freelance
|
58ab1df70368c319431a1905833ea005a703d400
|
704f032bc693f4f7dfb7694f14edda0337f81d97
|
refs/heads/master
|
<file_sep><?php
/* @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Models\Openinghours::class, function (Faker\Generator $faker) {
$start = new Carbon\Carbon('2017-01-01');
$end = $start->copy()->modify('31 December');
return [
'active' => 1,
'start_date' => $start->subYear(),
'end_date' => $end->addYear(),
'label' => $faker->text($maxNbChars = 30),
];
});
<file_sep><?php
/* @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Models\Event::class, function (Faker\Generator $faker) {
$dt = new Carbon\Carbon('2017-01-01');
$dt->minute = 00;
$dt->second = 00;
$start = $dt->copy();
$start->hour = 9;
$end = $dt->copy();
$end->hour = 18;
return [
'rrule' => 'BYDAY=MO,TU,WE,TH,FR;FREQ=WEEKLY',
'start_date' => $start,
'end_date' => $end,
'label' => 1,
'until' => $dt->modify('31 December')->addYear(),
];
});
<file_sep><?php
/* @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Models\Channel::class, function (Faker\Generator $faker) {
return [
'label' => $faker->text($maxNbChars = 30),
'service_id' => 1,
];
});
<file_sep><?php
/* @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Models\Calendar::class, function (Faker\Generator $faker) {
return [
'priority' => 0,
'summary' => '',
'label' => 'Normale uren',
'closinghours' => 0,
];
});
<file_sep><?php
/* @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Models\Service::class, function (Faker\Generator $faker) {
return [
'label' => $faker->text,
'uri' => $faker->url,
'description' => $faker->text,
'draft' => 0,
];
});
<file_sep><?php
define('NET_SSH2_LOGGING', \phpseclib\Net\SSH2::LOG_COMPLEX);
use DigipolisGent\Robo\Laravel\RoboFileBase;
class RoboFile extends RoboFileBase
{
/**
* @inheritdoc
*/
protected function clearCacheTask($worker, $auth, $remote)
{
$currentProjectRoot = $remote['currentdir'] . '/..';
$collection = $this->collectionBuilder();
$collection->addTask(parent::clearCacheTask($worker, $auth, $remote));
// Restart the queue after clearing cache.
$collection->taskSsh($worker, $auth)
->remoteDirectory($currentProjectRoot, true)
->timeout(120)
->exec('php artisan queue:restart');
return $collection;
}
/**
* Run Tests.
*/
public function test()
{
$this->stopOnFail(true);
$this->taskPHPUnit()
->option('disallow-test-output')
->option('strict-coverage')
->option('-d error_reporting=-1')
->option('--coverage-clover=build/logs/clover.xml')
->arg('tests')
->run();
}
/**
* Install precommit hook.
*/
public function precommitInstall()
{
// Create the git/hooks symlinks.
$files = array_diff(scandir(__DIR__ . '/.git-hooks'), ['..', '.']);
foreach ($files as $file) {
$this->say(sprintf('Add git hook : %s.', $file));
// Only if symlink does not exists yet.
$to = '.git/hooks/' . $file;
if (file_exists($to)) {
$this->say('✔ Already exists.');
continue;
}
$this->taskFilesystemStack()
->symlink(__DIR__ . '/.git-hooks/' . $file, $to)
->run();
$this->say('✔ Created symlink.');
}
}
}
|
dfefd15caf8a3275251bbe6daa4062489888761c
|
[
"PHP"
] | 6
|
PHP
|
ZedanDredal/laravel_site_opening-hours
|
7a2730cb7006eb3f46ef8535addbb601d9388533
|
c9e78952e58cb8fb17fb17ed0e893e8d740bde1c
|
refs/heads/master
|
<repo_name>inamura-nakamura-lab/timecard-api-rust<file_sep>/src/domain/repository/user_repository.rs
use crate::domain::model::user::User;
use crate::infrastructure::persistence::model::user::NewUser;
use futures::Future;
use std::error::Error;
pub trait UserRepository {
fn insert_user(&self, new_user: &NewUser) -> Box<Future<Item = Option<bool>, Error = String>>;
fn select_user(&self, user_id: &i32) -> Box<Future<Item = Option<Vec<User>>, Error = String>>;
fn delete_user(&self, user_id: &i32) -> Box<Future<Item = Option<bool>, Error = String>>;
}
pub trait UsesUserRepository {
type UserRepository: UserRepository;
fn user_repository(&self) -> Self::UserRepository;
}
<file_sep>/README.md
# timecard-api-rust<file_sep>/src/infrastructure/persistence/repository/user_repository.rs
use crate::domain::repository::user_repository::{UserRepository, UsesUserRepository};
use crate::infrastructure::persistence::model::user::NewUser;
use crate::infrastructure::persistence::schema::user::schema;
use futures::Future;
use infrastructure::persistence::model::user::User;
use std::error::Error;
trait UserRepositoryImpl {}
impl<T: UserRepositoryImpl> UserRepository for T {
fn insert_user(&self, new_user: &NewUser) -> Box<Future<Item = Option<bool>, Error = Error>> {
diesel::insert_into(users::table);
}
fn select_user(&self, user_id: &i32) -> Box<Future<Item = Option<User>, Error = Error>> {}
fn delete_user(&self, user_id: &i32) -> Box<Future<Item = Option<bool>, Error = Error>> {}
}
<file_sep>/src/domain/model/user.rs
use uuid::Uuid;
use serde::{Deserialize, Serialize};
use std::time::SystemTime;
#[derive(Serialize, Deserialize)]
pub struct User {
id: Option<i32>,
name: Option<String>,
student_number: Option<String>,
date: SystemTime
}<file_sep>/src/lib.rs
extern crate futures;
pub mod domain;
pub mod infrastructure;
<file_sep>/Cargo.toml
[package]
name = "timecard-api-rust"
version = "1.3.4"
authors = [ "tozastation <<EMAIL>>" ]
[dependencies]
hyper = "0.12"
serde_json = "1.0"
futures = "0.1"
uuid = "0.7"
diesel = { version = "1.0.0", features = ["mysql"] }
dotenv = "0.9.0"<file_sep>/src/main.rs
#[macro_use]
extern crate diesel;
<file_sep>/src/domain/service/user_service.rs
use crate::domain::model::user::User;
use crate::domain::repository::user_repository::UsesUserRepository;
use futures::Future;
use std::error::Error;
trait UserService: UsesUserRepository {
fn add_user(&self, new_user: &User) -> Box<Future<Item = Option<bool>, Error = String>>;
fn get_user(&self, user_id: &i32) -> Box<Future<Item = Option<User>, Error = String>>;
fn delete_user(&self, user_id: &i32) -> Box<Future<Item = Option<bool>, Error = String>>;
}
trait UsesUserService {
type UserService: UserService;
fn user_service(&self) -> Self::UserService;
}
impl<T: UsesUserRepository> UserService for T {
fn add_user(&self, new_user: &User) -> Box<Future<Item = Option<bool>, Error = String>> {
self.user_repository().insert_user();
}
fn get_user(&self, user_id: &i32) -> Box<Future<Item = Option<User>, Error = String>> {}
fn delete_user(&self, user_id: &i32) -> Box<Future<Item = Option<bool>, Error = String>> {}
}
|
15b4f251e7a78374d48b5c221c83bd6367944457
|
[
"Markdown",
"Rust",
"TOML"
] | 8
|
Rust
|
inamura-nakamura-lab/timecard-api-rust
|
8d6ba1ce522d62fb99e5b940b301493a47cbaaeb
|
bb3c1b50cc90b5818cd22fca771e68f50b5abdf7
|
refs/heads/master
|
<repo_name>m4ndr4ck/BTC<file_sep>/src/com/dhp/service/ResgateBitcoinService.java
package com.dhp.service;
import java.util.List;
import com.dhp.model.ResgateBitcoin;
public interface ResgateBitcoinService {
public void save(ResgateBitcoin resgateBitcoin);
public List<ResgateBitcoin> findResgates(Long clienteId);
}
<file_sep>/src/com/dhp/afiliados/model/ResgateBitcoinAfiliado.java
package com.dhp.afiliados.model;
import com.dhp.model.LocalDateTimeConverter;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name = "afl_saque")
public class ResgateBitcoinAfiliado {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(precision=16, scale=8)
private double bitcoins;
@Column
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime dataHora;
@Column
private String enderecobitcoin;
@Column
private Long afiliadoid;
@Transient
String erros;
@Transient
String nome;
@Transient
String totalresgatado;
public String getTotalresgatado() {
return totalresgatado;
}
public void setTotalresgatado(String totalresgatado) {
this.totalresgatado = totalresgatado;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getErros() {
return erros;
}
public void setErros(String erros) {
this.erros = erros;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public double getBitcoins() {
return bitcoins;
}
public void setBitcoins(double bitcoins) {
this.bitcoins = bitcoins;
}
public String getEnderecobitcoin() {
return enderecobitcoin;
}
public void setEnderecobitcoin(String enderecobitcoin) {
this.enderecobitcoin = enderecobitcoin;
}
public LocalDateTime getDataHora() {
return dataHora;
}
public void setDataHora(LocalDateTime dataHora) {
this.dataHora = dataHora;
}
public Long getAfiliadoid() {
return afiliadoid;
}
public void setAfiliadoid(Long afiliadoid) {
this.afiliadoid = afiliadoid;
}
}
<file_sep>/web/resources/js/checkout-cartao.js
function brandCard() {
PagSeguroDirectPayment.getBrand({
cardBin: $("#numerocartao").val(),
success: function(response) {
return response.brand.name;
},
error: function(response) {
$("#numerocartao").css('border', '2px solid red');
$("#numerocartao").focus();
},
complete: function(response) {
}
});
}
function pagarCartao(senderHash) {
var bandname = brandCard();
var data =$('#validade').text();
var arr = data.split('/');
var mesExpiracao = arr[0];
var anoExpiracao = arr[1];
PagSeguroDirectPayment.setSessionId("${sessaoid}");
PagSeguroDirectPayment.createCardToken({
cardNumber: $("#numerocartao").val(),
brand: bandname,
cvv: $("#cvv").val(),
expirationMonth: mesExpiracao,
expirationYear: anoExpiracao,
success: function (response) {
alert("Deu certo");
alert(response.card.token);
$("#creditCardToken").val(response.card.token);
},
error: function (response) {
alert("Deu erro");
if (response.error) {
console.log("4" + response);
$.each(response.errors, function (index, value) {
console.log(value);
});
}
},
complete: function (response) {
}
});
/**$.ajax({
type: 'POST',
url: 'pagamentoCartao.php',
cache: false,
data: {
id: 11111,
email: $("#senderEmail").val(),
nome: $("#senderName").val(),
cpf: $("#senderCPF").val(),
ddd: $("#senderAreaCode").val(),
telefone: $("#senderPhone").val(),
cep: $("#shippingAddressPostalCode").val(),
endereco: $("#shippingAddressStreet").val(),
numero: $("#shippingAddressNumber").val(),
complemento: $("#shippingAddressComplement").val(),
bairro: $("#shippingAddressDistrict").val(),
cidade: $("#shippingAddressCity").val(),
estado: $("#shippingAddressState").val(),
pais: "BRA",
senderHash: senderHash,
enderecoPagamento: $("#billingAddressStreet").val(),
numeroPagamento: $("#billingAddressNumber").val(),
complementoPagamento: $("#billingAddressComplement").val(),
bairroPagamento: $("#billingAddressDistrict").val(),
cepPagamento: $("#billingAddressPostalCode").val(),
cidadePagamento: $("#billingAddressCity").val(),
estadoPagamento: $("#billingAddressState").val(),
cardToken: $("#creditCardToken").val(),
cardNome: $("#creditCardHolderName").val(),
cardCPF: $("#creditCardHolderCPF").val(),
cardNasc: $("#creditCardHolderBirthDate").val(),
cardFoneArea: $("#creditCardHolderAreaCode").val(),
cardFoneNum: $("#creditCardHolderPhone").val(),
numParcelas: $("#installmentQuantity").val(),
valorParcelas: $("#installmentValue").val(),
},
success: function(data) {
//console.log(data);
if (data.error) {
if (data.error.code == "53037") {
$("#creditCardPaymentButton").click();
} else {
$("#modal-title").html("<font color='red'>Erro</font>");
$("#modal-body").html("");
$.each(data.error, function (index, value) {
if (value.code) {
tratarError(value.code);
} else {
tratarError(data.error.code)
}
})
//console.log("2 " + data);
}
} else {
$.ajax({
type: 'POST',
url: 'getStatus.php',
cache: false,
data: {
id: data.code,
},
success: function(status) {
if (status == "7") {
//alert(data);
$("#modal-title").html("<font color='red'>Erro</font>");
$("#modal-body").html("Erro ao processar o seu pagamento.<br/> Não se preocupe pois esse valor <b>não será debitado de sua conta ou não constará em sua fatura</b><br /><br />Verifique se você possui limite suficiente para efetuar a transação e/ou tente um cartão diferente");
} else {
window.location = "http://download.infoenem.com.br/pagamento-efetuado/";
setTimeout(function () {
$("#modal-body").html("");
$("#modal-title").html("<font color='green'>Sucesso!</font>")
$("#modal-body").html("Caso você não seja redirecionado para a nossa página de instruções, clique no botão abaixo.<br /><br /><a href='http://download.infoenem.com.br/pagamento-efetuado/'><center><button class='btn-success btn-block btn-lg'>Ir para a página de instruções</button></center></a>");
}, 1500);
}
}
});
//console.log("1 " + data);
}
}
});*/
}
<file_sep>/src/com/dhp/service/ResgateContaBancariaService.java
package com.dhp.service;
import java.util.List;
import com.dhp.model.ResgateContaBancaria;
public interface ResgateContaBancariaService {
public void save(ResgateContaBancaria resgateContaBancaria);
public List<ResgateContaBancaria> findResgates(Long clienteId);
}
<file_sep>/src/com/dhp/pagamentos/CheckoutTransparente.java
package com.dhp.pagamentos;
/*
* 2007-2016 [PagSeguro Internet Ltda.]
*
* NOTICE OF LICENSE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright: 2007-2016 PagSeguro Internet Ltda.
* Licence: http://www.apache.org/licenses/LICENSE-2.0
*/
import br.com.uol.pagseguro.api.PagSeguro;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Map;
import br.com.uol.pagseguro.api.PagSeguroEnv;
import br.com.uol.pagseguro.api.common.domain.BankName;
import br.com.uol.pagseguro.api.common.domain.ShippingType;
import br.com.uol.pagseguro.api.common.domain.builder.*;
import br.com.uol.pagseguro.api.common.domain.enums.Currency;
import br.com.uol.pagseguro.api.common.domain.enums.DocumentType;
import br.com.uol.pagseguro.api.common.domain.enums.State;
import br.com.uol.pagseguro.api.credential.Credential;
import br.com.uol.pagseguro.api.http.JSEHttpClient;
import br.com.uol.pagseguro.api.session.CreatedSession;
import br.com.uol.pagseguro.api.transaction.register.DirectPaymentRegistrationBuilder;
import br.com.uol.pagseguro.api.transaction.search.TransactionDetail;
import br.com.uol.pagseguro.api.utils.logging.SimpleLoggerFactory;
/**
* @author PagSeguro Internet Ltda.
*/
public class CheckoutTransparente {
public static String pagamentoCartao(Map<String, String> dadosComprador){
try{
String sellerEmail = "";
//String sellerToken = ""; //DEV
String sellerToken = ""; //PROD
final PagSeguro pagSeguro = PagSeguro
.instance(new SimpleLoggerFactory(), new JSEHttpClient(),
Credential.sellerCredential(sellerEmail, sellerToken), PagSeguroEnv.PRODUCTION);
CreatedSession createdSessionApplication = pagSeguro.sessions().create();
System.out.println(createdSessionApplication.getId());
// Checkout transparente (pagamento direto) com cartao de credito
TransactionDetail creditCardTransaction =
pagSeguro.transactions().register(new DirectPaymentRegistrationBuilder()
.withPaymentMode("default")
.withCurrency(Currency.BRL)
.addItem(new PaymentItemBuilder()//
.withId("0001")//
.withDescription("BTC "+dadosComprador.get("bitcoin")) //
.withAmount(new BigDecimal(dadosComprador.get("preco")))//
.withQuantity(1)
.withWeight(1000))
.withNotificationURL("https://btcmoedas.com.br/retorno")
.withReference(dadosComprador.get("referencia"))
.withSender(new SenderBuilder()//
.withHash(dadosComprador.get("senderhash"))
//.withEmail("<EMAIL>")//
.withEmail(dadosComprador.get("email"))//
.withName(dadosComprador.get("nome"))
.withCPF(dadosComprador.get("cpf"))
.withPhone(new PhoneBuilder()//
.withAreaCode(dadosComprador.get("celDDD")) //
.withNumber(dadosComprador.get("celNum")))) //
.withShipping(new ShippingBuilder()//
.withType(ShippingType.Type.USER_CHOISE) //
.withCost(BigDecimal.ZERO)//
.withAddress(new AddressBuilder() //
.withPostalCode(dadosComprador.get("cep"))
.withCountry("BRA")
.withState(dadosComprador.get("uf"))//
.withCity(dadosComprador.get("cidade"))
.withComplement(dadosComprador.get("complemento"))
.withDistrict(dadosComprador.get("bairro"))
.withNumber(dadosComprador.get("numero"))
.withStreet(dadosComprador.get("logradouro")))
)
).withCreditCard(new CreditCardBuilder()
.withBillingAddress(new AddressBuilder() //
.withPostalCode(dadosComprador.get("cep"))
.withCountry("BRA")
.withState(dadosComprador.get("uf"))//
.withCity(dadosComprador.get("cidade"))
.withComplement(dadosComprador.get("complemento"))
.withDistrict(dadosComprador.get("bairro"))
.withNumber(dadosComprador.get("numero"))
.withStreet(dadosComprador.get("logradouro"))
)
.withInstallment(new InstallmentBuilder()
.withQuantity(1)
.withValue(new BigDecimal(dadosComprador.get("preco")))
)
.withHolder(new HolderBuilder()
.addDocument(new DocumentBuilder()
.withType(DocumentType.CPF)
.withValue(dadosComprador.get("cpf"))
)
.withName(dadosComprador.get("nome"))
.withBithDate(new SimpleDateFormat("dd/MM/yyyy").parse(dadosComprador.get("nascimento")))
.withPhone(new PhoneBuilder()
.withAreaCode(dadosComprador.get("celDDD"))
.withNumber(dadosComprador.get("celNum"))
)
)
.withToken(dadosComprador.get("tokencartao"))
);
System.out.println(creditCardTransaction);
return "ok";
}catch (Exception e){
e.printStackTrace();
}
return "erro";
}
public static String pagamentoDebito(Map<String, String> dadosComprador) {
String sellerEmail = "<EMAIL>";
//String sellerToken = "<KEY>"; //DEV
String sellerToken = "<KEY>D66849D40F697019912"; //PROD
br.com.uol.pagseguro.api.common.domain.BankName.Name banco =null;
final PagSeguro pagSeguro = PagSeguro
.instance(new SimpleLoggerFactory(), new JSEHttpClient(),
Credential.sellerCredential(sellerEmail, sellerToken), PagSeguroEnv.PRODUCTION);
try{
if(dadosComprador.get("banco").equals("bradesco")) banco = BankName.Name.BRADESCO;
if(dadosComprador.get("banco").equals("itau")) banco = BankName.Name.ITAU;
if(dadosComprador.get("banco").equals("bb")) banco = BankName.Name.BANCO_DO_BRASIL;
//Checkout transparente (pagamento direto) com debito online
TransactionDetail onlineDebitTransaction =
pagSeguro.transactions().register(new DirectPaymentRegistrationBuilder()
.withPaymentMode("default")
.withCurrency(Currency.BRL)
.addItem(new PaymentItemBuilder()//
.withId("0001")//
.withDescription("BTC " + dadosComprador.get("bitcoin")) //
.withAmount(new BigDecimal(dadosComprador.get("preco")))//
.withQuantity(1)
.withWeight(1000))
.withNotificationURL("https://btcmoedas.com.br/retorno")
.withReference(dadosComprador.get("referencia"))
.withSender(new SenderBuilder()//
.withHash(dadosComprador.get("senderhash"))
//.withEmail("<EMAIL>")//
.withEmail(dadosComprador.get("email"))//
.withName(dadosComprador.get("nome"))
.withCPF(dadosComprador.get("cpf"))
.withPhone(new PhoneBuilder()//
.withAreaCode(dadosComprador.get("celDDD")) //
.withNumber(dadosComprador.get("celNum")))) //
.withShipping(new ShippingBuilder()//
.withType(ShippingType.Type.USER_CHOISE) //
.withAddress(new AddressBuilder() //
.withPostalCode(dadosComprador.get("cep"))
.withCountry("BRA")
.withState(dadosComprador.get("uf"))//
.withCity(dadosComprador.get("cidade"))
.withComplement(dadosComprador.get("complemento"))
.withDistrict(dadosComprador.get("bairro"))
.withNumber(dadosComprador.get("numero"))
.withStreet(dadosComprador.get("logradouro")))
)
).withOnlineDebit(new BankBuilder()
.withName(banco)
);
System.out.println(onlineDebitTransaction.getPaymentLink());
return onlineDebitTransaction.getPaymentLink();
}catch (Exception e){
e.printStackTrace();
}
return "erro";
}
public static String pagamentoBoleto(Map<String, String> dadosComprador) {
String sellerEmail = "<EMAIL>";
//String sellerToken = "<KEY>"; //DEV
String sellerToken = "<KEY>"; //PROD
final PagSeguro pagSeguro = PagSeguro
.instance(new SimpleLoggerFactory(), new JSEHttpClient(),
Credential.sellerCredential(sellerEmail, sellerToken), PagSeguroEnv.PRODUCTION);
try{
//Checkout transparente (pagamento direto) com debito online
TransactionDetail bankSlipTransaction =
pagSeguro.transactions().register(new DirectPaymentRegistrationBuilder()
.withPaymentMode("default")
.withCurrency(Currency.BRL)
.addItem(new PaymentItemBuilder()//
.withId("0001")//
.withDescription("BTC por Boleto") //
.withAmount(new BigDecimal(dadosComprador.get("preco")))//
.withQuantity(1)
.withWeight(1000))
.withNotificationURL("https://btcmoedas.com.br/retorno")
.withReference(dadosComprador.get("referencia"))
.withSender(new SenderBuilder()//
.withHash(dadosComprador.get("senderhash"))
//.withEmail("<EMAIL>")//
.withEmail(dadosComprador.get("email"))//
.withName(dadosComprador.get("nome"))
.withCPF(dadosComprador.get("cpf"))
.withPhone(new PhoneBuilder()//
.withAreaCode(dadosComprador.get("celDDD")) //
.withNumber(dadosComprador.get("celNum")))) //
.withShipping(new ShippingBuilder()//
.withType(ShippingType.Type.USER_CHOISE) //
.withAddress(new AddressBuilder() //
.withPostalCode(dadosComprador.get("cep"))
.withCountry("BRA")
.withState(dadosComprador.get("uf"))//
.withCity(dadosComprador.get("cidade"))
.withComplement(dadosComprador.get("complemento"))
.withDistrict(dadosComprador.get("bairro"))
.withNumber(dadosComprador.get("numero"))
.withStreet(dadosComprador.get("logradouro")))
)
).withBankSlip();
System.out.println(bankSlipTransaction);
return bankSlipTransaction.getPaymentLink();
}catch (Exception e){
e.printStackTrace();
}
return "erro";
}
public static void main(String[] args) {
String sellerEmail = "<EMAIL>";
String sellerToken = "6<PASSWORD>94D66849D40F697019912";
final PagSeguro pagSeguro = PagSeguro
.instance(new SimpleLoggerFactory(), new JSEHttpClient(),
Credential.sellerCredential(sellerEmail, sellerToken), PagSeguroEnv.PRODUCTION);
try{
// Checkout transparente (pagamento direto) com boleto
TransactionDetail bankSlipTransaction =
pagSeguro.transactions().register(new DirectPaymentRegistrationBuilder()
.withPaymentMode("default")
.withCurrency(Currency.BRL)
.addItem(new PaymentItemBuilder()//
.withId("9234")//
.withDescription("Produto PagSeguroI") //
.withAmount(new BigDecimal(100.00))//
.withQuantity(1)
.withWeight(1000))
.withNotificationURL("https://btcmoedas.com.br/retorno")
.withReference("LIBJAVA_DIRECT_PAYMENT")
.withSender(new SenderBuilder()//
.withHash("")
.withEmail("<EMAIL>")//
.withName("<NAME>")
.withCPF("21418824941")
.withPhone(new PhoneBuilder()//
.withAreaCode("41") //
.withNumber("999737902"))) //
.withShipping(new ShippingBuilder()//
.withType(ShippingType.Type.USER_CHOISE) //
.withAddress(new AddressBuilder() //
.withPostalCode("80610260")
.withCountry("BRA")
.withState(State.PR)//
.withCity("Cidade Exemplo")
.withComplement("99o andar")
.withDistrict("Jardim Internet")
.withNumber("9999")
.withStreet("Av. PagSeguro")))
).withBankSlip();
System.out.println(bankSlipTransaction);
}catch (Exception e){
e.printStackTrace();
}
}
}
<file_sep>/src/resources/validation.properties
NotEmpty=Esse campo é obrigatório
Size.userForm.username=Please use between 6 and 32 characters.
Duplicate.userForm.username=Someone already has that username.
Size.userForm.password=Informe uma senha com no mínimo 6 caracteres
Diff.userForm.passwordConfirm=As senhas não conicidem
saldo.insuficiente=Saldo insuficiente para saque.<file_sep>/src/com/dhp/afiliados/repository/ResgateBitcoinAfiliadoRepository.java
package com.dhp.afiliados.repository;
import com.dhp.afiliados.model.ResgateBitcoinAfiliado;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ResgateBitcoinAfiliadoRepository extends JpaRepository<ResgateBitcoinAfiliado, Long> {
List<ResgateBitcoinAfiliado> findByAfiliadoid(Long afiliadoid);
}
<file_sep>/src/com/dhp/service/PagamentosService.java
package com.dhp.service;
import java.util.List;
import com.dhp.model.Pagamentos;
public interface PagamentosService {
void save(Pagamentos pagamento);
List<Pagamentos> findPagamentos(long clienteId);
Pagamentos findByPagseguroid(String pagseguroid);
}<file_sep>/src/com/dhp/model/ResgateBitcoin.java
package com.dhp.model;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name = "resgatebitcoin")
public class ResgateBitcoin {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(precision=16, scale=8)
private double bitcoins;
@Column
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime dataHora;
@Column
private String enderecobitcoin;
@Column
private Long clienteid;
@Transient
String erros;
@Transient
String nome;
@Transient
String totalresgatado;
public String getTotalresgatado() {
return totalresgatado;
}
public void setTotalresgatado(String totalresgatado) {
this.totalresgatado = totalresgatado;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getErros() {
return erros;
}
public void setErros(String erros) {
this.erros = erros;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public double getBitcoins() {
return bitcoins;
}
public void setBitcoins(double bitcoins) {
this.bitcoins = bitcoins;
}
public String getEnderecobitcoin() {
return enderecobitcoin;
}
public void setEnderecobitcoin(String enderecobitcoin) {
this.enderecobitcoin = enderecobitcoin;
}
public LocalDateTime getDataHora() {
return dataHora;
}
public void setDataHora(LocalDateTime dataHora) {
this.dataHora = dataHora;
}
public Long getClienteid() {
return clienteid;
}
public void setClienteid(Long clienteid) {
this.clienteid = clienteid;
}
}
<file_sep>/src/com/dhp/repository/ResgateContaBancariaRepository.java
package com.dhp.repository;
import com.dhp.model.ResgateContaBancaria;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ResgateContaBancariaRepository extends JpaRepository<ResgateContaBancaria, Long>{
List<ResgateContaBancaria> findByClienteid(Long clienteid);
}<file_sep>/src/com/dhp/util/Crypto.java
package com.dhp.util;
//import org.bitcoinj.protocols.channels.PaymentChannelServer;
import org.apache.commons.lang3.RandomStringUtils;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.salt.RandomSaltGenerator;
import sun.misc.BASE64Decoder;
import javax.crypto.Cipher;
import java.io.*;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class Crypto {
public static void main(String[] args)
{
/** String publicKeyFilename = "/home/m4ndr4ck/BTC/RSA/public_key.pem";
String inputFilename = "/home/m4ndr4ck/BTC/RSA/plaintext";
String encryptedFilename = "/home/m4ndr4ck/BTC/RSA/crypted";
Crypto rsaEncryptFile = new Crypto();
rsaEncryptFile.encrypt(publicKeyFilename, inputFilename, encryptedFilename);
char[] possibleCharacters = (new String("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$%*")).toCharArray();
String randomStr = RandomStringUtils.random( 12, 0, possibleCharacters.length-1, false, false, possibleCharacters, new SecureRandom() );
System.out.println( randomStr );**/
}
static public String encrypt (String apikey){
String value="";
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
String publicKeyFilename = "/opt/public_key.pem";
String key = readFileAsString(publicKeyFilename);
BASE64Decoder b64 = new BASE64Decoder();
AsymmetricKeyParameter publicKey =
(AsymmetricKeyParameter) PublicKeyFactory.createKey(b64.decodeBuffer(key));
AsymmetricBlockCipher e = new RSAEngine();
e = new org.bouncycastle.crypto.encodings.PKCS1Encoding(e);
e.init(true, publicKey);
String inputdata = apikey;
byte[] messageBytes = inputdata.getBytes();
int i = 0;
int len = e.getInputBlockSize();
while (i < messageBytes.length)
{
if (i + len > messageBytes.length)
len = messageBytes.length - i;
byte[] hexEncodedCipher = e.processBlock(messageBytes, i, len);
value = value + getHexString(hexEncodedCipher);
i += e.getInputBlockSize();
}
}
catch (Exception e) {
System.out.println(e);
}
return value;
}
public static String getHexString(byte[] b) throws Exception {
String result = "";
for (int i=0; i < b.length; i++) {
result +=
Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return result;
}
private static String readFileAsString(String filePath)
throws java.io.IOException{
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = new BufferedReader(
new FileReader(filePath));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
System.out.println(fileData.toString());
return fileData.toString();
}
public static PublicKey get(String filename)
throws Exception {
byte[] keyBytes = Files.readAllBytes(Paths.get(filename));
X509EncodedKeySpec spec =
new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
}
<file_sep>/src/com/dhp/web/BaseController.java
package com.dhp.web;
import com.dhp.util.Helpers;
import org.hibernate.type.BigDecimalType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import static com.dhp.web.CotacaoControllerAdvice.FeeLocalBitcoins;
public class BaseController {
static NumberFormat formatter = new DecimalFormat("0.00000000");
static Locale locale = new Locale("pt", "BR");
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
static NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
///public static double getCotacaoCOMPRA(){return Helpers.geraCotacaoBitvalor();}
public static double getCotacaoCOMPRA(){return CotacaoControllerAdvice.geraCotacaoWall();}
public static String getCotacaoCOMPRAcomBRL(){return currencyFormatter.format(getCotacaoCOMPRA());}
public static double getCotacaoVENDA(){return CotacaoControllerAdvice.getCotacaoVENDA();}
public static double getTaxaBTC(){return 0.0003;}
public static double getTaxaBTC(BigDecimal valorPagamento, double bitcoins) {
double taxa = 0;
BigDecimal cem = new BigDecimal("100");
BigDecimal duzentos = new BigDecimal("200");
BigDecimal trezentos = new BigDecimal("300");
BigDecimal quatrocentos = new BigDecimal("400");
BigDecimal quinhetos = new BigDecimal("500");
if (valorPagamento.compareTo(cem) >= 0 && valorPagamento.compareTo(duzentos) < 0) {
taxa = bitcoins * 0.35;
} else if (valorPagamento.compareTo(duzentos) >= 0 && valorPagamento.compareTo(trezentos) < 0){
taxa = bitcoins * 0.25;
}else if (valorPagamento.compareTo(trezentos)>=0){
taxa = bitcoins * 0.10;
}
//return taxa;
return 0.0003;
}
public static String getTaxaBTCcomvirgula(){return formatter.format(getTaxaBTC()).replace(".", ",");}
public static double getFeeLocalBitcoins(){return FeeLocalBitcoins();}
public static String getfeeLocalBitcoinscomvirgula(){return formatter.format(getFeeLocalBitcoins()).replace(".", ",");}
public static final Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
protected HttpServletRequest context;
@Autowired
protected JavaMailSender mailSender;
}
<file_sep>/src/resources/pagseguro.properties
email=<EMAIL>
token=<PASSWORD>
environment=production
<file_sep>/src/com/dhp/web/UserController.java
package com.dhp.web;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.security.Principal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dhp.afiliados.model.Afiliado;
import com.dhp.afiliados.service.AfiliadoService;
import com.dhp.pagamentos.CheckoutTransparente;
import com.dhp.service.*;
import com.dhp.util.PaymentWithPayPalServlet;
import com.dhp.util.SendBitcoin;
import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.PaymentExecution;
import com.paypal.base.rest.APIContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.filter.RequestContextFilter;
import org.springframework.web.multipart.MultipartFile;
import com.dhp.blockchain.Carteiras;
import com.dhp.model.ContaBancaria;
import com.dhp.model.EnderecosBTC;
import com.dhp.model.Pagamentos;
import com.dhp.model.ResgateBitcoin;
import com.dhp.model.ResgateContaBancaria;
import com.dhp.model.UploadedFile;
import com.dhp.model.User;
import com.dhp.pagamentos.PagSeg;
import com.dhp.util.GenericResponse;
import com.dhp.util.Helpers;
import com.dhp.validator.AdminValidator;
import com.dhp.validator.PagamentosValidator;
import com.dhp.validator.RecuperarSenhaValidator;
import com.dhp.validator.ResgateBitcoinValidator;
import com.dhp.validator.ResgateContaBancariaValidator;
import com.dhp.validator.SenhaValidator;
import com.dhp.validator.UserValidator;
import com.dhp.web.dto.PasswordDto;
import com.google.protobuf.TextFormat.ParseException;
import static com.dhp.web.BaseController.*;
@Controller
public class UserController {
private static double getCotacaoCOMPRA(){return BaseController.getCotacaoCOMPRA();}
private static double getCotacaoVENDA(){return BaseController.getCotacaoVENDA();}
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
private MessageSource messages;
@Autowired
private Environment env;
@Autowired
private JavaMailSender mailSender;
@Autowired
private UserService userService;
@Autowired
private SecurityService securityService;
@Autowired
private EnderecosBTCService enderecosBTCService;
@Autowired
private PagamentosService pagamentosService;
@Autowired
private ResgateBitcoinService resgateBitcoinService;
@Autowired
private ContaBancariaService contaBancariaService;
@Autowired
private ResgateContaBancariaService resgateContaBancariaService;
@Autowired
private AdminService adminService;
@Autowired
private UserValidator userValidator;
@Autowired
private SenhaValidator senhaValidator;
@Autowired
private ResgateContaBancariaValidator resgateContaBancariaValidator;
@Autowired
private ResgateBitcoinValidator resgateBitcoinValidator;
@Autowired
private RecuperarSenhaValidator recuperarSenhaValidator;
@Autowired
private PagamentosValidator pagamentosValidator;
@Autowired
private AdminValidator adminValidator;
@Autowired
private EntityManager entityManager;
@Autowired
AfiliadoService afiliadoService;
@Autowired
private HttpServletRequest context;
Pagamentos pagamentosObj;
ResgateBitcoin resgateBitcoinObj;
ResgateContaBancaria resgateContaBancariaObj;
Locale locale = new Locale("pt", "BR");
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
NumberFormat formatter = new DecimalFormat("0.00000000");
String refAfiliado;
@Bean
public RequestContextFilter requestContextListener(){
return new RequestContextFilter();
}
@Transactional
@RequestMapping(value = "/retorno", method = {RequestMethod.POST, RequestMethod.GET}, headers = "content-type=application/x-www-form-urlencoded", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public @ResponseBody String retorno(@RequestParam("notificationCode") String notificationCode, @RequestParam("notificationType") String notificationType) throws Exception {
String refCode = Helpers.notificaPagSeg(notificationCode, false);
String referencia = refCode.replace("BTCM", "");
String status = Helpers.notificaPagSeg(Integer.parseInt(referencia), false);
String pagseguroid = Helpers.notificaPagSeg(Integer.parseInt(referencia), true);
System.out.println("Notification code: " + notificationCode);
System.out.println("Ref code: " + refCode);
System.out.println("Status: " + status);
System.out.println("Pagseguro ID: " + pagseguroid);
//Atualiza status de pagamento
Pagamentos pagamento = entityManager.find(Pagamentos.class, Long.parseLong(referencia)); //Consider em as JPA EntityManager
if(pagamento.getStatus() != 3) {
pagamento.setStatus(Long.parseLong(status));
if (pagamento.getPagseguroid() == null) pagamento.setPagseguroid(pagseguroid);
entityManager.merge(pagamento);
//Atualiza saldo
if (Integer.valueOf(status) == 3) { // 3/4 = Aprovado
EnderecosBTC cliente = entityManager.find(EnderecosBTC.class, pagamento.getClienteid()); //Consider em as JPA EntityManager
double saldoAtual = cliente.getSaldo();
double novoSaldo = saldoAtual + pagamento.getBitcoins();
cliente.setSaldo(novoSaldo);
entityManager.merge(cliente);
}
}
return null;
}
@RequestMapping(value = "/retorno", method = RequestMethod.GET)
public String retorno() {
System.out.println("Notificacao Pagseguro: " + context.getParameter("notificationCode"));
return "redirect:/painel";
}
@RequestMapping(value = {"/", "/"}, method = RequestMethod.GET)
public String home() {
return "home";
}
@RequestMapping(value = {"/"}, params = {"ref"}, method = RequestMethod.GET)
public String homeRef(@RequestParam(value="ref", required = false) String ref, Model model) {
System.out.println("Ref: "+ref);
if(ref!=null) {
Afiliado afiliado = afiliadoService.findByRefFinal(ref);
if (afiliado != null) {
refAfiliado = afiliado.getRef();
}
else refAfiliado = "noref";
} else{
refAfiliado = "noref";
}
return "redirect:/";
}
@RequestMapping(value = {"/como-funciona"}, method = RequestMethod.GET)
public String comoFunciona(Model model) {
model.addAttribute("bitcoinFEE", getFeeLocalBitcoins());
model.addAttribute("taxaBTC", formatter.format(getTaxaBTC()).replace(".", ","));
return "home-como-funciona";
}
@RequestMapping(value = {"/simulador"}, method = RequestMethod.GET)
public String simulador(Model model) {
model.addAttribute("cotacaoCompraSemBRL", String.valueOf(getCotacaoCOMPRA()));
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
model.addAttribute("taxaBTC", getTaxaBTC());
model.addAttribute("taxaBTCcomvirgula", formatter.format(getTaxaBTC()).replace(".", ","));
model.addAttribute("feeLocalBitcoinscomvirgula", getfeeLocalBitcoinscomvirgula());
model.addAttribute("feeLocalBitcoins", getFeeLocalBitcoins());
//model.asMap().clear();
//return "redirect:/";
return "home-simulador";
}
@RequestMapping(value = {"/comprar-bitcoin"}, method = RequestMethod.GET)
public String comprarBitcoin(Model model) {
model.addAttribute("cotacaoCompraSemBRL", String.valueOf(getCotacaoCOMPRA()));
model.addAttribute("cotacaoCOMPRA", getCotacaoCOMPRAcomBRL());
return "home-comprar-bitcoin";
}
@RequestMapping(value = {"/contato"}, method = RequestMethod.GET)
public String contatoGet() {
return "home-contato";
}
@RequestMapping(value = {"/contato"}, method = RequestMethod.POST)
public String contatoPost() {
String nome = context.getParameter("nome");
String email = context.getParameter("email");
String mensagem = context.getParameter("mensagem");
mailSender.send(constructContato(nome, email, mensagem ));
context.setAttribute("sucesso", true);
return "home-contato";
}
@RequestMapping(value = {"/sobre"}, method = RequestMethod.GET)
public String sobre() {
return "home-sobre-nos";
}
@RequestMapping(value = {"/comprar-bitcoin-com-cartao-de-credito"}, method = RequestMethod.GET)
public String comprarBitcoinComCartaoDeCredito() {
return "home-comprar-bitcoin-com-cartao-de-credito";
}
@RequestMapping(value = "/cadastro", method = RequestMethod.GET)
public String registration(Model model) {
User user = new User();
//if (!refAfiliado.isEmpty())
user.setRef(refAfiliado);
model.addAttribute("userForm", user);
model.addAttribute("referencia", refAfiliado);
return "cadastro";
}
@RequestMapping(value = "/cadastro/{ref}", method = RequestMethod.GET)
public String registrationRef(@PathVariable(value="ref") String ref, Model model) {
Afiliado afiliado = afiliadoService.findByRefFinal(ref);
String referencia = afiliado.getRef();
User user = new User();
if (!referencia.isEmpty())
user.setRef(referencia);
model.addAttribute("userForm", user);
model.addAttribute("ref", referencia);
return "cadastro";
}
@RequestMapping(value = "/cadastro", method = RequestMethod.POST)
public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model, Principal principal) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "cadastro";
}
//char[] possibleCharacters = (new String("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$%*")).toCharArray();
//String apikey = RandomStringUtils.random( 12, 0, possibleCharacters.length-1, false, false, possibleCharacters, new SecureRandom() );
//String encryptedApiKey = Crypto.encrypt(apikey);
//serForm.setApikey(encryptedApiKey);
userForm.setCelular(userForm.getCelular()
.replace("(", "")
.replace(")", "")
.replace("-", "")
.replace(" ", ""));
userService.save(userForm);
//CreateWalletResponse enderecoBTC = Carteiras.criarCarteira(apikey, userForm.getNome(), userForm.getEmail());
int clienteId = Integer.valueOf(userService.findByCpf(userForm.getCpf()).getId().toString());
String enderecoBTC = Carteiras.criarEndereco(clienteId);
String cpf = userForm.getCpf();
//enderecosBTCService.save(clienteId, enderecoBTC.getAddress(), enderecoBTC.getIdentifier());
enderecosBTCService.save(clienteId, enderecoBTC);
securityService.autologin(userForm.getCpf(), userForm.getConfirmaSenha());
File dir = new File("/home/dhp/" + cpf);
if (!dir.exists()) dir.mkdirs();
EnderecosBTC enderecoBTCpage = enderecosBTCService.findByClienteid((long)clienteId);
//Double saldoBTC = Consultas.verificaSaldo(clienteId);
double saldoBTC = enderecoBTCpage.getSaldo();
double saldoBRL = getCotacaoVENDA() * saldoBTC;
model.addAttribute("enderecoBTC", enderecoBTCpage.getEndereco());
BigDecimal bd = new BigDecimal(saldoBTC);
DecimalFormat f = new DecimalFormat("0.00000000");
String saldo = f.format(bd);
model.addAttribute("saldoBTC", saldo);
model.addAttribute("saldoBRL", currencyFormatter.format(saldoBRL));
int verificado = userService.findById(clienteId).getVerificado();
model.addAttribute("verificado", verificado);
model.asMap().clear();
return "redirect:/painel";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
if (error != null)
model.addAttribute("error", "Login inválido, tente novamente.");
//if (logout != null)
// model.addAttribute("message", "You have been logged out successfully.");
return "login";
}
@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
logger.info("logout ok");
}
return "login";//You can redirect wherever you want, but generally it's a good practice to show login screen again.
}
@RequestMapping(value = "/admlogin", method = RequestMethod.GET)
public String admin(Model model, String error, String logout) {
model.addAttribute("adminForm", new User());
//if (logout != null)
// model.addAttribute("message", "You have been logged out successfully.");
return "admlogin";
}
/**@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adm(Model model) {
model.addAttribute("userForm", new User());
return "admin";
}*/
@RequestMapping(value = {"/painel"}, method = RequestMethod.GET)
public String painel(Model model, Principal principal) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
String nome = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getNome();
model.addAttribute("message", nome);
long clienteId = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getId();
EnderecosBTC enderecoBTC = enderecosBTCService.findByClienteid(clienteId);
//Double saldoBTC = Consultas.verificaSaldo(clienteId);
double saldoBTC = enderecoBTC.getSaldo();
double saldoBRL = 0;
model.addAttribute("enderecoBTC", enderecoBTC.getEndereco());
BigDecimal bd = new BigDecimal(saldoBTC);
DecimalFormat f = new DecimalFormat("0.00000000");
String saldo = f.format(bd);
model.addAttribute("saldoBTC", saldo);
model.addAttribute("saldoBRL", currencyFormatter.format(saldoBRL));
int verificado = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getVerificado();
model.addAttribute("verificado", verificado);
return "painel";
}
@RequestMapping(value = {"/painel/comprar-bitcoin"}, method = RequestMethod.GET)
public String comprar(@ModelAttribute("Pagamento") Pagamentos pagamento, BindingResult bindingresult, Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
model.addAttribute("cotacaoCompraSemBRL", String.valueOf(getCotacaoCOMPRA()));
return "comprar";
}
@RequestMapping(value = {"/painel/comprar-bitcoin"}, method = RequestMethod.POST)
public String comprar(@ModelAttribute("Pagamento") Pagamentos pagamento, BindingResult bindingresult, Model model, Principal principal) throws ParseException, java.text.ParseException {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
model.addAttribute("Pagamento", pagamento);
model.addAttribute("cotacaoCompraSemBRL", String.valueOf(getCotacaoCOMPRA()));
long clienteId = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getId();
int verificado = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getVerificado();
BigDecimal valorPagamento = Helpers.parse(context.getParameter("valorPagamento"), locale);
//BigDecimal valorPagamentoComTaxaBD = valorPagamento.multiply(new BigDecimal(1.0999)).add(new BigDecimal(5));
//BigDecimal valorPagamentoComTaxaBD = valorPagamento.add(new BigDecimal(5));
//Sem taxa
BigDecimal valorPagamentoComTaxaBD = valorPagamento.add(new BigDecimal(0));
String valorPagamentoComTaxa = currencyFormatter.format(Double.valueOf(valorPagamentoComTaxaBD.toString()));
Map<String, Object> dadosValidacao = new HashMap<>();
dadosValidacao.put("verificado", String.valueOf(verificado));
dadosValidacao.put("valorPagamento", valorPagamento);
pagamentosValidator.validate(dadosValidacao, bindingresult);
if (bindingresult.hasErrors()){
for (ObjectError error : bindingresult.getAllErrors()){
if (!error.getCode().equals("typeMismatch"))
return "comprar";
}
}
double bitcoins = Double.valueOf(context.getParameter("bitcoins").replace(",", "."));
double taxa = getTaxaBTC(valorPagamento, bitcoins);
double bitcoinsComTaxa = bitcoins - taxa;
model.addAttribute("cotacao", pagamento.getCotacao());
model.addAttribute("dataHora", LocalDateTime.now().format(format).toString());
model.addAttribute("diaMes", LocalDateTime.now().getDayOfMonth());
model.addAttribute("taxaBTCcomvirgula", formatter.format(taxa).replace(".", ","));
model.addAttribute("bitcoins2",
formatter.format(bitcoinsComTaxa).replace(".", ","));
model.addAttribute("bitcoins", context.getParameter("bitcoins"));
model.addAttribute("valorPagamento", valorPagamentoComTaxa);
// model.addAttribute("tipoPagamento", context.getParameter("tipoPagamento"));
Locale locBrazil = new Locale("pt", "BR");
NumberFormat nf = NumberFormat.getInstance(locBrazil);
pagamentosObj = new Pagamentos();
pagamentosObj.setCotacao(currencyFormatter.format(getCotacaoCOMPRA()));
pagamentosObj.setClienteid(clienteId);
pagamentosObj.setDataHora(LocalDateTime.parse(LocalDateTime.now().format(format).toString(), format));
pagamentosObj.setBitcoins(bitcoins - taxa);
pagamentosObj.setTaxa(taxa);
//pagamentosObj.setTipoPagamento(Integer.valueOf(context.getParameter("tipoPagamento")));
pagamentosObj.setTipoPagamento(2);
pagamentosObj.setValorPagamento((Double.valueOf(nf.parse(context.getParameter("valorPagamento").replace("R$ ", "")).doubleValue())));
pagamentosObj.setValorPagamentoComTaxa(valorPagamentoComTaxa);
return "confirmar";
}
@RequestMapping(value = {"/painel/checkout"}, method = RequestMethod.GET)
public String checkout(Model model) {
double valorPagamento = pagamentosObj.getValorPagamento();
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
return "checkout";
}
@RequestMapping(value = {"/painel/checkout/cartao"}, method = RequestMethod.GET)
public String checkoutCartao(Model model, Principal principal) {
if(pagamentosObj.getValorPagamento()>200) {
model.asMap().clear();
return "redirect:/painel";
}
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
String cpf = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf();
User user = userService.findByCpf(cpf);
String nome = user.getNome();
String sessaoid = PagSeg.criaSessao();
model.addAttribute("nome", nome);
model.addAttribute("cpf", cpf);
model.addAttribute("sessaoid", sessaoid);
return "checkout-cartao";
}
@Transactional
@RequestMapping(value = {"/painel/checkout/cartao"}, method = RequestMethod.POST)
public @ResponseBody String checkoutCartaoEfetiva(Model model, Principal principal) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
//Salva pedido na base de dados
pagamentosService.save(pagamentosObj);
String cpf = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf();
User user = userService.findByCpf(cpf);
String nome = context.getParameter("nome");
String nascimento = context.getParameter("nascimento");
String email = user.getEmail();
String celDDD = user.getCelular().substring(0, 2);
String celNum = user.getCelular().substring(2);
String cep = context.getParameter("cep").replaceAll("-", "");
String logradouro = context.getParameter("logradouro");
String numero = context.getParameter("numero");
String complemento = context.getParameter("complemento");
String bairro = context.getParameter("bairro").equals("") ? "Centro" : context.getParameter("bairro");
String cidade = context.getParameter("cidade");
String uf = context.getParameter("uf");
String tokencartao = context.getParameter("tokencartao");
String senderhash = context.getParameter("senderhash");
String bitcoin = formatter.format(pagamentosObj.getBitcoins()).replace('.',',');
String preco = String.valueOf(pagamentosObj.getValorPagamento());
String referencia = "BTC"+pagamentosObj.getId();
Map<String, String> dadosComprador = new HashMap<>();
dadosComprador.put("nome", nome);
dadosComprador.put("cpf", cpf);
dadosComprador.put("nascimento", nascimento);
dadosComprador.put("email", email);
dadosComprador.put("celDDD", celDDD);
dadosComprador.put("celNum", celNum);
dadosComprador.put("cep", cep);
dadosComprador.put("logradouro", logradouro);
dadosComprador.put("numero", numero);
dadosComprador.put("complemento", complemento);
dadosComprador.put("bairro", bairro);
dadosComprador.put("cidade", cidade);
dadosComprador.put("uf", uf);
dadosComprador.put("tokencartao", tokencartao);
dadosComprador.put("senderhash", senderhash);
dadosComprador.put("bitcoin", bitcoin);
dadosComprador.put("preco", preco);
dadosComprador.put("referencia", referencia);
String response = CheckoutTransparente.pagamentoCartao(dadosComprador);
//Envia e-mail para o cliente
mailSender.send(constructComprarBitcoinEmail(user, pagamentosObj));
//Envia e-mail para admin
mailSender.send(constructComprarBitcoinEmailAdmin(user, pagamentosObj));
// Se tudo der certo, salva pedido na base de dados
if (response.equals("erro")){
return "erro";
}else{
return "ok";
}
}
@RequestMapping(value = {"/painel/checkout/debito"}, method = RequestMethod.GET)
public String checkoutDebito(Model model, Principal principal) {
if(pagamentosObj.getValorPagamento()>200) {
model.asMap().clear();
return "redirect:/painel";
}
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
String cpf = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf();
User user = userService.findByCpf(cpf);
String nome = user.getNome();
model.addAttribute("nome", nome);
model.addAttribute("cpf", cpf);
return "checkout-debito";
}
@Transactional
@RequestMapping(value = {"/painel/checkout/debito"}, method = RequestMethod.POST)
public @ResponseBody String checkoutDebitoEfetiva(Model model, Principal principal) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
//Salva pedido na base de dados
pagamentosService.save(pagamentosObj);
String cpf = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf();
User user = userService.findByCpf(cpf);
String nome = context.getParameter("nome");
String nascimento = context.getParameter("nascimento");
String email = user.getEmail();
String celDDD = user.getCelular().substring(0, 2);
String celNum = user.getCelular().substring(2);
String cep = context.getParameter("cep").replaceAll("-", "");
String logradouro = context.getParameter("logradouro");
String numero = context.getParameter("numero");
String complemento = context.getParameter("complemento");
String bairro = context.getParameter("bairro").equals("") ? "Centro" : context.getParameter("bairro");
String cidade = context.getParameter("cidade");
String uf = context.getParameter("uf");
String banco = context.getParameter("banco");
String senderhash = context.getParameter("senderhash");
String bitcoin = formatter.format(pagamentosObj.getBitcoins()).replace('.',',');
String preco = String.valueOf(pagamentosObj.getValorPagamento());
String referencia = "BTC"+pagamentosObj.getId();
Map<String, String> dadosComprador = new HashMap<>();
dadosComprador.put("nome", nome);
dadosComprador.put("cpf", cpf);
dadosComprador.put("nascimento", nascimento);
dadosComprador.put("email", email);
dadosComprador.put("celDDD", celDDD);
dadosComprador.put("celNum", celNum);
dadosComprador.put("cep", cep);
dadosComprador.put("logradouro", logradouro);
dadosComprador.put("numero", numero);
dadosComprador.put("complemento", complemento);
dadosComprador.put("bairro", bairro);
dadosComprador.put("cidade", cidade);
dadosComprador.put("uf", uf);
dadosComprador.put("banco", banco);
dadosComprador.put("senderhash", senderhash);
dadosComprador.put("bitcoin", bitcoin);
dadosComprador.put("preco", preco);
dadosComprador.put("referencia", referencia);
String linkPagamento = CheckoutTransparente.pagamentoDebito(dadosComprador); //Link pagamento
//Envia e-mail para o cliente
mailSender.send(constructComprarBitcoinEmail(user, pagamentosObj));
//Envia e-mail para admin
mailSender.send(constructComprarBitcoinEmailAdmin(user, pagamentosObj));
// Se tudo der certo, salva pedido na base de dados
//if (!response.equals("erro")) pagamentosService.save(pagamentosObj);
return linkPagamento;
}
@RequestMapping(value = {"/painel/checkout/boleto"}, method = RequestMethod.GET)
public String checkoutBoleto(Model model, Principal principal) {
if(pagamentosObj.getValorPagamento()>200) {
model.asMap().clear();
return "redirect:/painel";
}
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
String cpf = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf();
User user = userService.findByCpf(cpf);
String nome = user.getNome();
model.addAttribute("nome", nome);
model.addAttribute("cpf", cpf);
return "checkout-boleto";
}
@Transactional
@RequestMapping(value = {"/painel/checkout/boleto"}, method = RequestMethod.POST)
public @ResponseBody String checkoutBoletoEfetiva(Model model, Principal principal) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
//Salva pedido na base de dados
pagamentosService.save(pagamentosObj);
String cpf = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf();
User user = userService.findByCpf(cpf);
String nome = context.getParameter("nome");
String nascimento = context.getParameter("nascimento");
String email = user.getEmail();
String celDDD = user.getCelular().substring(0, 2);
String celNum = user.getCelular().substring(2);
String cep = context.getParameter("cep").replaceAll("-", "");
String logradouro = context.getParameter("logradouro");
String numero = context.getParameter("numero");
String complemento = context.getParameter("complemento");
String bairro = context.getParameter("bairro").equals("") ? "Centro" : context.getParameter("bairro");
String cidade = context.getParameter("cidade");
String uf = context.getParameter("uf");
String banco = context.getParameter("banco");
String senderhash = context.getParameter("senderhash");
String bitcoin = formatter.format(pagamentosObj.getBitcoins()).replace('.',',');
String preco = String.valueOf(pagamentosObj.getValorPagamento());
String referencia = "BTC"+pagamentosObj.getId();
Map<String, String> dadosComprador = new HashMap<>();
dadosComprador.put("nome", nome);
dadosComprador.put("cpf", cpf);
dadosComprador.put("nascimento", nascimento);
dadosComprador.put("email", email);
dadosComprador.put("celDDD", celDDD);
dadosComprador.put("celNum", celNum);
dadosComprador.put("cep", cep);
dadosComprador.put("logradouro", logradouro);
dadosComprador.put("numero", numero);
dadosComprador.put("complemento", complemento);
dadosComprador.put("bairro", bairro);
dadosComprador.put("cidade", cidade);
dadosComprador.put("uf", uf);
dadosComprador.put("banco", banco);
dadosComprador.put("senderhash", senderhash);
dadosComprador.put("bitcoin", bitcoin);
dadosComprador.put("preco", preco);
dadosComprador.put("referencia", referencia);
String linkPagamento = CheckoutTransparente.pagamentoBoleto(dadosComprador); //Link pagamento
//Envia e-mail para o cliente
mailSender.send(constructComprarBitcoinEmail(user, pagamentosObj));
//Envia e-mail para admin
mailSender.send(constructComprarBitcoinEmailAdmin(user, pagamentosObj));
// Se tudo der certo, salva pedido na base de dados
//if (!response.equals("erro")) pagamentosService.save(pagamentosObj);
return linkPagamento;
}
@RequestMapping(value = {"/painel/checkout/transferencia"}, method = RequestMethod.GET)
public String checkoutTransferencia(Model model, Principal principal) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
String cpf = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf();
User user = userService.findByCpf(cpf);
String nome = user.getNome();
String valorPagamento = currencyFormatter.format(pagamentosObj.getValorPagamento());
model.addAttribute("nome", nome);
model.addAttribute("cpf", cpf);
model.addAttribute("valorPagamento", valorPagamento);
return "checkout-transferencia";
}
@Transactional
@RequestMapping(value = {"/painel/checkout/transferencia"}, method = RequestMethod.POST)
public @ResponseBody void checkoutTransferenciaEfetiva(Model model, Principal principal) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
//Salva pedido na base de dados
pagamentosService.save(pagamentosObj);
String cpf = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf();
User user = userService.findByCpf(cpf);
//Envia e-mail para o cliente
mailSender.send(constructComprarBitcoinEmail(user, pagamentosObj));
//Envia e-mail para admin
mailSender.send(constructComprarBitcoinEmailAdmin(user, pagamentosObj));
// Se tudo der certo, salva pedido na base de dados
//if (!response.equals("erro")) pagamentosService.save(pagamentosObj);
}
@RequestMapping(value = {"/painel/checkout/paypal"}, method = RequestMethod.GET)
public String paypal(Model model, HttpServletResponse response, Principal principal) {
String cpf = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf();
User user = userService.findByCpf(cpf);
String valorPagamento = String.valueOf(pagamentosObj.getValorPagamento());
String bitcoin = formatter.format(pagamentosObj.getBitcoins());
PaymentWithPayPalServlet paymentWithPayPalServlet = new PaymentWithPayPalServlet();
Payment payment = paymentWithPayPalServlet.createPayment(context, response, valorPagamento, bitcoin);
//Salva pedido na base de dados
pagamentosObj.setPagseguroid(payment.getId());
pagamentosService.save(pagamentosObj);
String linkPagamento = "";
for(Links link :payment.getLinks())
if(link.getHref().contains("express"))
linkPagamento =link.getHref();
//Envia e-mail para o cliente
mailSender.send(constructComprarBitcoinEmail(user, pagamentosObj));
//Envia e-mail para admin
mailSender.send(constructComprarBitcoinEmailAdmin(user, pagamentosObj));
return "redirect:"+linkPagamento;
}
@Transactional
@RequestMapping(method = RequestMethod.GET, value = "/painel/paypal")
public String successPay(@RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId, Model model){
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
try {
APIContext apiContext = new APIContext("<KEY>dQOg", "<KEY>", "live");
String linkPagamento = "";
Payment payment = new Payment();
payment.setId(paymentId);
PaymentExecution paymentExecute = new PaymentExecution();
paymentExecute.setPayerId(payerId);
Payment returnP = payment.execute(apiContext, paymentExecute);
//Obtem pagamento pelo paymentid
Pagamentos pagamento = pagamentosService.findByPagseguroid(paymentId);
//Atualiza status do pagamento e ret
if(returnP.getState().equals("approved")){
EnderecosBTC cliente = entityManager.find(EnderecosBTC.class, pagamento.getClienteid()); //Consider em as JPA EntityManager
double saldoAtual = cliente.getSaldo();
double novoSaldo = saldoAtual + pagamento.getBitcoins();
cliente.setSaldo(novoSaldo);
pagamento.setStatus(3L);
entityManager.merge(cliente);
return "paypal-success";
}
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/painel";
}
@RequestMapping(value = {"/painel/checkout/pagseguro"}, method = RequestMethod.GET)
public String pagseguro(Model model, HttpServletResponse response, Principal principal) {
int tipoPagamento = pagamentosObj.getTipoPagamento();
//Salva pedido na base de dados
pagamentosService.save(pagamentosObj);
String cpf = ((CustomUser) ((Authentication) principal).getPrincipal()).getCpf();
User user = userService.findByCpf(cpf);
String nome = user.getNome();
String email = user.getEmail();
long referencia = pagamentosObj.getId();
String urlRedir = "";
urlRedir = PagSeg.NovoPagamento(
String.valueOf(pagamentosObj.getValorPagamento()),
formatter.format(pagamentosObj.getBitcoins()).replace('.',','),
nome,
email,
cpf,
referencia
);
//Envia e-mail para o cliente
mailSender.send(constructComprarBitcoinEmail(user, pagamentosObj));
//Envia e-mail para admin
mailSender.send(constructComprarBitcoinEmailAdmin(user, pagamentosObj));
return "redirect:"+urlRedir;
}
@RequestMapping(value = {"/painel/comprar-bitcoin/confirmar"}, method = RequestMethod.GET)
public String confirmar(Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
return "confirmar";
}
@RequestMapping(value = {"/painel/comprar-bitcoin/confirmar"}, method = RequestMethod.POST)
public String confirmar(@ModelAttribute("Pagamento") Pagamentos pagamento, BindingResult result, Model model, Principal principal) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
int tipoPagamento = pagamentosObj.getTipoPagamento();
//Salva pedido na base de dados
//pagamentosService.save(pagamentosObj);
String cpf = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf();
User user = userService.findByCpf(cpf);
String nome = user.getNome();
String email = user.getEmail();
String urlRedir = "";
/**if(tipoPagamento==2){
urlRedir = PagSeg.NovoPagamento(
String.valueOf(pagamentosObj.getValorPagamento()),
formatter.format(pagamentosObj.getBitcoins()).replace('.',','),
nome,
email,
cpf,
referencia
);
}*/
if(tipoPagamento==2){
model.addAttribute("valorPagamento", pagamentosObj.getValorPagamento());
return "checkout";
}
if(tipoPagamento==1) {
//Salva pedido na base de dados
pagamentosService.save(pagamentosObj);
long referencia = pagamentosObj.getId();
urlRedir = PagSeg.NovaAssinatura(
String.valueOf(pagamentosObj.getValorPagamento()),
String.valueOf(formatter.format(pagamentosObj.getBitcoins())),
nome,
email,
cpf,
referencia
);
}
//Envia e-mail para o cliente
mailSender.send(constructComprarBitcoinEmail(user, pagamentosObj));
//Envia e-mail para admin
mailSender.send(constructComprarBitcoinEmailAdmin(user, pagamentosObj));
return "redirect:"+urlRedir;
}
@RequestMapping(value = {"/painel/resgatar"}, method = RequestMethod.GET)
public String resgatar(Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
return "resgatar";
}
@RequestMapping(value = {"/painel/resgatar/conta-bancaria"}, method = RequestMethod.GET)
public String resgatarContaBancaria(Principal principal, Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
model.addAttribute("Resgatar", new ResgateContaBancaria());
long clienteId = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getId();
double cotacaoVenda = getCotacaoVENDA();
EnderecosBTC enderecoBTC = enderecosBTCService.findByClienteid(clienteId);
//Double saldoBTC = Consultas.verificaSaldo(clienteId);
double saldoBTC = enderecoBTC.getSaldo();
double saldoBRL = cotacaoVenda * saldoBTC;
model.addAttribute("saldoBRL", currencyFormatter.format(saldoBRL));
model.addAttribute("cotacaoVENDA", currencyFormatter.format(cotacaoVenda));
model.asMap().clear();
return "redirect:/painel";
//return "resgatar-conta-bancaria";
}
@RequestMapping(value = {"/painel/resgatar/conta-bancaria"}, method = RequestMethod.POST)
public String resgatarContaBancaria(@ModelAttribute("Resgatar") ResgateContaBancaria resgateContaBancaria, BindingResult bindingresult, Principal principal, Model model) throws ParseException, java.text.ParseException {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
long clienteId = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getId();
List<ContaBancaria> contacadastrada = (List<ContaBancaria>) contaBancariaService.findByClienteid(clienteId);
ContaBancaria conta = contacadastrada.size() > 0 ? contacadastrada.get(0) : null;
double cotacaoVenda = getCotacaoVENDA();
String valoResgateform = context.getParameter("valorResgate");
EnderecosBTC enderecoBTC = enderecosBTCService.findByClienteid(clienteId);
//Double saldoBTC = Consultas.verificaSaldo(clienteId);
double saldoBTC = enderecoBTC.getSaldo();
double saldoBRL = cotacaoVenda * saldoBTC;
model.addAttribute("saldoBRL", currencyFormatter.format(saldoBRL));
if (conta == null){
resgateContaBancariaValidator.validate(true, bindingresult);
return "resgatar-conta-bancaria";
}
if (valoResgateform.isEmpty()){
resgateContaBancariaValidator.validate(valoResgateform, bindingresult);
return "resgatar-conta-bancaria";
}
BigDecimal valorResgate = Helpers.parse(context.getParameter("valorResgate"), locale);
int verificado = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getVerificado();
Map<String, BigDecimal> saldos = new HashMap<>();
saldos.put("saldoBRL", BigDecimal.valueOf(saldoBRL));
saldos.put("valorResgate", valorResgate);
saldos.put("verificado", BigDecimal.valueOf(verificado));
resgateContaBancariaValidator.validate(saldos, bindingresult);
if(bindingresult.hasErrors()){
return "resgatar-conta-bancaria";
}
String cpf = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf();
String nome = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getNome();
model.addAttribute("dataHora", LocalDateTime.now().format(format).toString());
model.addAttribute("contaCadastrada", contacadastrada);
model.addAttribute("valorResgate", context.getParameter("valorResgate"));
model.addAttribute("cpf", cpf);
model.addAttribute("nome", nome);
resgateContaBancariaObj = new ResgateContaBancaria();
resgateContaBancariaObj.setValorResgate(context.getParameter("valorResgate").replace(',', '.').replace("R$ ", ""));
resgateContaBancariaObj.setClienteid(clienteId);
resgateContaBancariaObj.setBanco(conta.getBanco());
resgateContaBancariaObj.setTipodeconta(conta.getTipodeconta());
resgateContaBancariaObj.setAgencia(conta.getAgencia());
resgateContaBancariaObj.setConta(conta.getConta());
resgateContaBancariaObj.setDadosadicionais(conta.getDadosadicionais());
return "confirmar-resgate-conta-bancaria";
}
@RequestMapping(value = {"/painel/resgatar/confirmar-resgate-conta-bancaria"}, method = RequestMethod.GET)
public String confirmarResgateContaBancaria(Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
return "confirmar-resgate-conta-bancaria";
}
@RequestMapping(value = {"/painel/resgatar/confirmar-resgate-conta-bancaria"}, method = RequestMethod.POST)
public String confirmarResgateContaBancaria(@ModelAttribute("Resgate") ResgateContaBancaria resgateContaBancaria, BindingResult result, Principal principal, Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
long clienteId = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getId();
User user = userService.findByCpf(( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf());
List<ContaBancaria> contacadastrada = (List<ContaBancaria>) contaBancariaService.findByClienteid(clienteId);
ContaBancaria conta = contacadastrada.get(0);
String valorResgate = resgateContaBancariaObj.getValorResgate();
resgateContaBancariaObj.setValorResgate(valorResgate);
resgateContaBancariaObj.setClienteid(clienteId);
resgateContaBancariaObj.setBanco(conta.getBanco());
resgateContaBancariaObj.setTipodeconta(conta.getTipodeconta());
resgateContaBancariaObj.setAgencia(conta.getAgencia());
resgateContaBancariaObj.setConta(conta.getConta());
resgateContaBancariaObj.setDadosadicionais(conta.getDadosadicionais());
resgateContaBancariaService.save(resgateContaBancariaObj);
mailSender.send(constructResgateContaBancariaEmail(user, resgateContaBancariaObj));
return "finalizar-resgate-conta-bancaria";
}
@RequestMapping(value = {"/painel/resgatar/finalizar-resgate-conta-bancaria"}, method = RequestMethod.GET)
public String finalizarResgateContaBancaria(Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
return "finalizar-resgate-conta-bancaria";
}
@RequestMapping(value = {"/painel/resgatar/carteira-bitcoin"}, method = RequestMethod.GET)
public String resgatarCarteiraBitcoin(Model model, Principal principal) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
model.addAttribute("Resgate", new ResgateBitcoin());
long clienteId = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getId();
EnderecosBTC enderecoBTC = enderecosBTCService.findByClienteid(clienteId);
//Double saldoBTC = Consultas.verificaSaldo(clienteId);
double saldoBTC = enderecoBTC.getSaldo();
BigDecimal bd = new BigDecimal(saldoBTC);
DecimalFormat f = new DecimalFormat("0.00000000");
String saldo = f.format(bd).replace('.', ',');
model.addAttribute("saldoBTC", saldo);
model.addAttribute("fee", BaseController.getfeeLocalBitcoinscomvirgula());
return "resgatar-carteira-bitcoin";
}
@RequestMapping(value = {"/painel/resgatar/carteira-bitcoin"}, method = RequestMethod.POST)
public String resgatarCarteiraBitcoin(@ModelAttribute("Resgate") ResgateBitcoin resgateBitcoin, BindingResult bindingresult, Model model, Principal principal) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
long clienteId = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getId();
double bitcoinantesdafee = Double.valueOf(context.getParameter("bitcoins").replace(',', '.'));
double valordoresgate = bitcoinantesdafee - getFeeLocalBitcoins();
EnderecosBTC enderecoBTC = enderecosBTCService.findByClienteid(clienteId);
//Double saldoBTC = Consultas.verificaSaldo(clienteId);
double saldoBTC = enderecoBTC.getSaldo();
BigDecimal bd = new BigDecimal(valordoresgate);
DecimalFormat f = new DecimalFormat("0.00000000");
String totalresgatado = f.format(bd);
int verificado = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getVerificado();
Map<String, String> dadosValidacao = new HashMap<>();
dadosValidacao.put("valordoresgate", context.getParameter("bitcoins").replace(',', '.'));
dadosValidacao.put("totalresgatado", totalresgatado);
dadosValidacao.put("saldoBTC", String.valueOf(saldoBTC).replace(',', '.'));
dadosValidacao.put("enderecobitcoin", context.getParameter("enderecobitcoin"));
dadosValidacao.put("verificado", String.valueOf(verificado));
context.setAttribute("bitcoins", 0.0);
model.addAttribute("bitcoins", context.getParameter("bitcoins").replace(',', '.'));
resgateBitcoinValidator.validate(dadosValidacao, bindingresult);
if (bindingresult.hasErrors()){
BigDecimal bd2 = new BigDecimal(saldoBTC);
String saldo = f.format(bd2).replace('.', ',');
model.addAttribute("saldoBTC", saldo);
for (ObjectError error : bindingresult.getAllErrors()){
if (!error.getCode().equals("typeMismatch")) {
model.addAttribute("fee", BaseController.getfeeLocalBitcoinscomvirgula());
return "resgatar-carteira-bitcoin";
}
}
}
model.addAttribute("dataHora", LocalDateTime.now().format(format).toString());
model.addAttribute("bitcoins", context.getParameter("bitcoins").replace('.', ','));
model.addAttribute("totalresgatado", totalresgatado.replace('.', ','));
model.addAttribute("feeBTC", formatter.format(getFeeLocalBitcoins()).replace('.', ','));
model.addAttribute("enderecobitcoin", context.getParameter("enderecobitcoin"));
resgateBitcoinObj = new ResgateBitcoin();
resgateBitcoinObj.setClienteid(clienteId);
resgateBitcoinObj.setBitcoins(bitcoinantesdafee);
resgateBitcoinObj.setTotalresgatado(totalresgatado);
resgateBitcoinObj.setDataHora(LocalDateTime.parse(LocalDateTime.now().format(format).toString(), format));
resgateBitcoinObj.setEnderecobitcoin(context.getParameter("enderecobitcoin"));
return "confirmar-resgate-bitcoin";
}
@RequestMapping(value = {"/painel/resgatar/confirmar-resgate-bitcoin"}, method = RequestMethod.GET)
public String confirmarResgateBitcoin(Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
model.addAttribute("feeBTC", getFeeLocalBitcoins());
return "confirmar-resgate-bitcoin";
}
@Transactional
@RequestMapping(value = {"/painel/resgatar/confirmar-resgate-bitcoin"}, method = RequestMethod.POST)
public String confirmarResgateBitcoin(Model model, Principal principal) throws Exception {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
String enderecoBTC = resgateBitcoinObj.getEnderecobitcoin();
double valorResgate = Double.valueOf(resgateBitcoinObj.getBitcoins());
double feeBTC = getFeeLocalBitcoins();
String totalResgatado = String.valueOf(valorResgate - feeBTC);
BigDecimal bd = new BigDecimal(totalResgatado);
DecimalFormat f = new DecimalFormat("0.00000000");
String totalresgatadoFormatado = f.format(bd).replace(",", ".");
SendBitcoin sendBitcoin = new SendBitcoin();
String result = sendBitcoin.send(enderecoBTC, totalresgatadoFormatado);
if(result.equals("200")){
//Atualiza saldo
EnderecosBTC cliente = entityManager.find(EnderecosBTC.class, resgateBitcoinObj.getClienteid()); //Consider em as JPA EntityManager
double saldoAtual = cliente.getSaldo();
double novoSaldo = saldoAtual - valorResgate;
cliente.setSaldo(novoSaldo);
entityManager.merge(cliente);
} else{
return "erro-resgate-bitcoin";
}
long clienteId = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getId();
User user = userService.findByCpf(( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf());
resgateBitcoinService.save(resgateBitcoinObj);
mailSender.send(constructResgateBitcoinEmail(user, resgateBitcoinObj));
//Envia e-mail para admin
mailSender.send(constructResgateBitcoinEmailAdmin(user, resgateBitcoinObj));
return "redirect:/painel/resgatar/finalizar-resgate-bitcoin";
}
@RequestMapping(value = {"/painel/resgatar/finalizar-resgate-bitcoin"}, method = RequestMethod.GET)
public String finalizarResgateBitcoin(Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
return "finalizar-resgate-bitcoin";
}
@RequestMapping(value = {"/painel/minha-conta"}, method = RequestMethod.GET)
public String minhaConta(Principal principal, Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
int verificado = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getVerificado();
model.addAttribute("verificado", verificado);
return "minha-conta";
}
@RequestMapping(value = {"/painel/minhas-compras"}, method = RequestMethod.GET)
public String minhasCompras(Principal principal, Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
long clienteId = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getId();
List<Pagamentos> pagamentos = pagamentosService.findPagamentos(clienteId);
for(Pagamentos pagamento : pagamentos){
pagamento.setDataHora(LocalDateTime.parse(
pagamento.getDataHora().toString().length() < 18 ?
pagamento.getDataHora().toString() +":01":
pagamento.getDataHora().toString()
));
}
model.addAttribute("Pagamentos", pagamentos);
return "minhas-compras";
}
@RequestMapping(value = {"/painel/meus-resgates"}, method = RequestMethod.GET)
public String meusResgates(Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
return "meus-resgates";
}
// ADICIONAR CONTA BANCARIA - INICIO //
@RequestMapping(value = {"/painel/adicionar-conta-bancaria"}, method = RequestMethod.GET)
public String adiconarContaBancaria(Principal principal, Model model, ContaBancaria contabancaria) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
Long clienteId = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getId();
List<ContaBancaria> contacadastrada = (List<ContaBancaria>) contaBancariaService.findByClienteid(clienteId);
model.addAttribute("contaCadastrada", contacadastrada);
return "adicionar-conta-bancaria";
}
@RequestMapping(value = {"/painel/adicionar-conta-bancaria"}, method = RequestMethod.POST)
public String adiconarContaBancaria(@ModelAttribute("ContaBancaria") ContaBancaria contabancaria, Principal principal, Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
long clienteId = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getId();
contabancaria.setClienteid(clienteId);
contaBancariaService.save(contabancaria);
return "redirect:/painel/adicionar-conta-bancaria";
}
@RequestMapping(value = {"/painel/remover-conta-bancaria"}, method = RequestMethod.POST)
public String removerContaBancaria(Principal principal, Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
long clienteId = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getId();
contaBancariaService.delete(clienteId);
return "redirect:/painel/adicionar-conta-bancaria";
}
// ADICIONAR CONTA BANCARIA - FIM //
@RequestMapping(value = {"/painel/alterar-senha"}, method = RequestMethod.GET)
public String alterarSenha(Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
model.addAttribute("senhaAlterarForm", new PasswordDto());
return "alterar-senha";
}
@RequestMapping(value = {"/painel/alterar-senha"}, method = RequestMethod.POST)
public String alterarSenha(@ModelAttribute("senhaAlterarForm") PasswordDto senhaAlterarForm, BindingResult bindingResult, HttpServletRequest request, Model model, Principal principal) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
String cpf = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf();
User user = userService.findByCpf(cpf);
senhaValidator.validate(senhaAlterarForm, bindingResult);
if (!userService.checkIfValidOldPassword(user, senhaAlterarForm.getOldPassword())) {
bindingResult.rejectValue("oldPassword", "message.invalidOldPassword");
return "alterar-senha";
}
if (bindingResult.hasErrors()) {
return "alterar-senha";
}
userService.changeUserPassword(user, senhaAlterarForm.getNewPassword());
String response = new GenericResponse(
messages.getMessage("message.resetPasswordEmail", null,
request.getLocale())).getMessage();
request.setAttribute("response", response);
return "alterar-senha";
}
@RequestMapping(value = {"/painel/solicitar-verificacao"}, method = RequestMethod.POST)
public String solicitarVerificao(Principal principal, Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
User user = userService.findByCpf(( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf());
String nome = user.getNome() ;
String email = user.getEmail();
mailSender.send(constructSolicitarVerificao(nome, email));
return "solicitar-verificacao";
}
@RequestMapping(value = {"/painel/enviar-documentos"}, method = RequestMethod.GET)
public String enviarDocumentos(Principal principal, Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
String cpf = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf();
List<String> documentosAnexados = Helpers.listarArquivos("/home/dhp/" + cpf);
model.addAttribute("documentosAnexados", documentosAnexados);
return "enviar-documentos";
}
@RequestMapping(value = "/painel/enviar-documentos", method = RequestMethod.POST)
public String enviarDocumentos(@ModelAttribute("Documentos") UploadedFile uploadedFile, Principal principal) {
MultipartFile file = uploadedFile.getFile();
String name = uploadedFile.getFile().getOriginalFilename();
String cpf = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getCpf();
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
//File dir = new File(rootPath + File.separator + "tmpFiles");
File dir = new File("/home/dhp/" + cpf);
//if (!dir.exists())
// dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
logger.info("Server File Location="
+ serverFile.getAbsolutePath());
System.out.println("You successfully uploaded file=" + name);
return "enviar-documentos";
} catch (Exception e) {
System.out.println("Erro ao fazer upload do arquivo" + e.getStackTrace());
return "enviar-documentos";
}
} else {
System.out.println("You failed to upload " + name + " because the file was empty.");
return "enviar-documentos";
}
}
@RequestMapping(value = {"/painel/meus-resgates-conta-bancaria"}, method = RequestMethod.GET)
public String meusResgatesContaBancaria(Principal principal, Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
long clienteId = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getId();
List<ResgateContaBancaria> resgates = resgateContaBancariaService.findResgates(clienteId);
model.addAttribute("Resgates", resgates);
return "meus-resgates-conta-bancaria";
}
@RequestMapping(value = {"/painel/meus-resgates-carteira-bitcoin"}, method = RequestMethod.GET)
public String meusResgatesCarteriaBitcoin(Principal principal, Model model) {
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
long clienteId = ( (CustomUser) ((Authentication)principal).getPrincipal() ).getId();
List<ResgateBitcoin> resgates = resgateBitcoinService.findResgates(clienteId);
model.addAttribute("Resgates", resgates);
return "meus-resgates-carteira-bitcoin";
}
@RequestMapping(value = {"/recuperar-senha"}, method = RequestMethod.GET)
public String esqueciaMinhaSenha(Principal principal, Model model) {
model.addAttribute("userForm", new User());
return "senha-recuperar";
}
@RequestMapping(value = "/recuperar-senha", method = RequestMethod.POST)
public String resetPassword(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, HttpServletRequest request,
@RequestParam("cpf") String cpf) throws Exception {
User user = userService.findByCpf(cpf);
recuperarSenhaValidator.validate(cpf, bindingResult);
if (bindingResult.hasErrors()) {
return "senha-recuperar";
}
if (user == null) {
throw new Exception();
}
String token = UUID.randomUUID().toString();
userService.createPasswordResetTokenForUser(user, token);
mailSender.send(constructResetTokenEmail(getAppUrl(request),
request.getLocale(), token, user));
String response = new GenericResponse(
messages.getMessage("message.resetPasswordEmail", null,
request.getLocale())).getMessage();
request.setAttribute("response", response);
return "senha-recuperar";
}
@RequestMapping(value = "/mudar-senha", method = RequestMethod.GET)
public String showChangePasswordPage(final Locale locale, final Model model, @RequestParam("cpf") final String cpf, @RequestParam("token") final String token) {
final String result = userService.validatePasswordResetToken(cpf, token);
if (result != null) {
model.addAttribute("message", messages.getMessage("auth.message." + result, null, locale));
return "redirect:/login?lang=" + locale.getLanguage();
}
return "redirect:/atualizar-senha?lang=" + locale.getLanguage();
}
@RequestMapping(value = {"/atualizar-senha"}, method = RequestMethod.GET)
public String atualizarSenha(Principal principal, Model model) {
model.addAttribute("senhaForm", new PasswordDto());
return "senha-atualizar";
}
@RequestMapping(value = "/atualizar-senha", method = RequestMethod.POST)
public String savePassword(@ModelAttribute("senhaForm") PasswordDto senhaForm,
BindingResult bindingResult, Locale locale, HttpServletRequest request) {
senhaValidator.validate(senhaForm, bindingResult);
if (bindingResult.hasErrors()) {
return "senha-atualizar";
}
User user =
(User) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
userService.changeUserPassword(user, senhaForm.getNewPassword());
String response = new GenericResponse(
messages.getMessage("message.resetPasswordSuc", null, locale)).getMessage();
request.setAttribute("response", response);
return "senha-atualizar";
}
// ============== ADMIN AREA ============ //
@RequestMapping(value = {"/admin/clientes"}, method = RequestMethod.GET)
public String adminClientes(Model model) {
List<User> clientes = adminService.retrieveAllCustomers();
model.addAttribute("Clientes", clientes);
double saldoBTCTotal = 0;
List<EnderecosBTC> enderecosBTC = enderecosBTCService.findAll();
for(EnderecosBTC endereco : enderecosBTC)
saldoBTCTotal += endereco.getSaldo();
NumberFormat formatter = new DecimalFormat("0.00000000");
model.addAttribute("SaldoBTCTotal", formatter.format(saldoBTCTotal));
return "admin-clientes";
}
@RequestMapping(value = {"/admin/clientes/{ID}"}, method = RequestMethod.GET)
public String adminClienteHome(@PathVariable(value="ID") String id, Model model) {
User cliente = userService.findById(Long.valueOf(id));
String cpf = cliente.getCpf();
int verificado = cliente.getVerificado();
NumberFormat formatter = new DecimalFormat("0.00000000");
Double saldoBTC = enderecosBTCService.findByClienteid(Long.valueOf(id)).getSaldo();
model.addAttribute("SaldoBTC", formatter.format(saldoBTC));
List<Pagamentos> compras = pagamentosService.findPagamentos(Long.valueOf(id));
for(Pagamentos pagamento : compras){
pagamento.setDataHora(LocalDateTime.parse(
pagamento.getDataHora().toString().length() < 18 ?
pagamento.getDataHora().toString() +":01":
pagamento.getDataHora().toString()
));
}
model.addAttribute("Compras", compras);
List<ResgateBitcoin> resgates = resgateBitcoinService.findResgates(Long.valueOf(id));
for(ResgateBitcoin resgate : resgates){
resgate.setDataHora(LocalDateTime.parse(
resgate.getDataHora().toString().length() < 18 ?
resgate.getDataHora().toString() +":01":
resgate.getDataHora().toString()
));
}
model.addAttribute("Resgates", resgates);
List<String> documentosAnexados = Helpers.listarArquivos("/home/dhp/" + cpf);
model.addAttribute("DocumentosAnexados", documentosAnexados);
model.addAttribute("Cliente", cliente);
model.addAttribute("verificado", verificado);
model.addAttribute("id", id);
return "admin-cliente-home";
}
@RequestMapping(value = {"/admin/compras"}, method = RequestMethod.GET)
public String adminCompras(Model model) {
List<Pagamentos> compras = adminService.retrieveAllCompras();
for(Pagamentos compra : compras){
compra.setDataHora(LocalDateTime.parse(
compra.getDataHora().toString().length() < 18 ?
compra.getDataHora().toString() +":01":
compra.getDataHora().toString()
));
User user = userService.findById(compra.getClienteid());
compra.setNome(user.getNome());
}
model.addAttribute("Compras", compras);
return "admin-compras";
}
@RequestMapping(value = {"/admin/resgates/bitcoin"}, method = RequestMethod.GET)
public String adminResgatesBitcoin(Model model) {
List<ResgateBitcoin> resgates = adminService.retrieveAllResgateBitcoin();
for(ResgateBitcoin resgate : resgates){
resgate.setDataHora(LocalDateTime.parse(
resgate.getDataHora().toString().length() < 18 ?
resgate.getDataHora().toString() +":01":
resgate.getDataHora().toString()
));
User user = userService.findById(resgate.getClienteid());
resgate.setNome(user.getNome());
}
model.addAttribute("Resgates", resgates);
return "admin-resgates-bitcoin";
}
@RequestMapping(value = {"/admin/resgates/conta-bancaria"}, method = RequestMethod.GET)
public String adminResgatesContaBancaria(Model model) {
List<ResgateContaBancaria> resgates = adminService.retrieveAllResgateContaBancaria();
for(ResgateContaBancaria resgate : resgates){
User user = userService.findById(resgate.getClienteid());
resgate.setNome(user.getNome());
}
model.addAttribute("Resgates", resgates);
return "admin-resgates-conta-bancaria";
}
@Transactional
@RequestMapping(value = {"/admin/verificar-cadastro"}, method = RequestMethod.POST)
public String adminVerificarCadastro(Model model) {
long id = Long.valueOf((String)context.getParameter("id"));
User cliente = entityManager.find(User.class, id); //Consider em as JPA EntityManager
String flag = context.getParameter("flag");
SimpleMailMessage email = constructEmail("[BTC Moedas]Cadastro verificado",
"Oi "+ cliente.getNome().split("\\s+")[0]+ ",\n\n" +
"Seu cadastro foi verificado com sucesso.\n\n"
+ "Você já pode comprar bitcoin."
+ "\n\n"
+ "Atenciosamente,\n"
+ "<NAME>\n" +
"BTC Moedas",
cliente
);
if (flag.equals("v")){
mailSender.send(email);
cliente.setVerificado(1);
} else if (flag.equals("r")){
cliente.setVerificado(0);
}
entityManager.merge(cliente);
return "redirect:/admin/clientes/"+id;
}
@Transactional
@RequestMapping(value = {"/admin/atualizar-saldo"}, method = RequestMethod.POST)
public String adminAtualizarSaldo(Model model) {
long id = Long.valueOf((String)context.getParameter("id"));
EnderecosBTC cliente = entityManager.find(EnderecosBTC.class, id); //Consider em as JPA EntityManager
Double saldoBTC = Double.valueOf(context.getParameter("saldoBTC").toString());
cliente.setSaldo(saldoBTC);
entityManager.merge(cliente);
return "redirect:/admin/clientes/"+id;
}
@Transactional
@RequestMapping(value = {"/admin/confirmar-compra"}, method = RequestMethod.POST)
public String confirmarCompra(Model model) {
long id = Long.valueOf((String)context.getParameter("id"));
User user = userService.findById(id);
mailSender.send(constructConfirmaCompra(user));
return "redirect:/admin/clientes/"+id;
}
// ============== ADMIN AREA ============ //
// ============== NON-API ============
private SimpleMailMessage constructResetTokenEmail(final String contextPath, final Locale locale, final String token, final User user) {
final String url = contextPath + "/mudar-senha?cpf=" + user.getCpf() + "&token=" + token;
final String message = messages.getMessage("message.resetPassword", null, locale);
return constructEmail("Recuperar senha", message + " \r\n\n" + url, user);
}
private MimeMessage constructComprarBitcoinEmail(final User user, Pagamentos pagamentos) {
NumberFormat formatter = new DecimalFormat("0.00000000");
String nome = user.getNome().split("\\s+")[0];
String tipodepagamento = pagamentosObj.getTipoPagamento() == 2 ? "Compra Avulsa" : "Mensal";
String mensagem = "<div style='font-size: 14px; line-height: 14px; font-family: Ubuntu, Tahoma, Verdana, Segoe, sans-serif;' data-mce-style='font-size: 12px; line-height: 14px; font-family: Ubuntu, Tahoma, Verdana, Segoe, sans-serif;'>"+
"<p style='font-size: 14px; line-height: 16px;' data-mce-style='font-size: 14px; line-height: 16px;'>"+
"Olá <strong>"+nome+"</strong>,"+
"<br />"+
"<br />"+
"Obrigado por comprar bitcoin através de nossa plataforma. Confira os detalhes da sua compra:"+
"<br />"+
"<br />"+
"Cotação: "+"<b>"+pagamentosObj.getCotacao()+"</b>"+
"<br />"+
"Taxa de transação: "+"<b>"+formatter.format(pagamentosObj.getTaxa()).replace('.', ',')+" BTC</b>"+
"<br />"+
"Bitcoin: "+"<b>"+formatter.format(pagamentosObj.getBitcoins()+pagamentosObj.getTaxa()).replace('.', ',')+" BTC</b>"+
"<br />"+
"Valor total da compra: "+"<b>"+pagamentosObj.getValorPagamentoComTaxa()+"</b>"+
"<br />"+
"Você vai receber: "+"<b>"+formatter.format(pagamentosObj.getBitcoins()).replace('.', ',')+" BTC</b>"+
"<br />"+
"O prazo para liberação dos bitcoins é de <b>2</b> até <b>24</b> horas após aprovação do pagamento."+
"</p>"+
"<p style='font-size: 14px; line-height: 16px;' data-mce-style='font-size: 14px; line-height: 16px;'>"+
"Se tiver qualquer dúvida basta responder este e-mail ou então nos contatar pelo número <b>41</b> <b>99973-7902</b>."+
"<br />"+
"<br />Atenciosamente,"+
"<br />BTC Moedas"+
"</p>"+
"</div>";
return constructEmailHtml("[BTC Moedas]Sua compra de bitcoin", mensagem, user);
}
private MimeMessage constructComprarBitcoinEmailAdmin(final User user, Pagamentos pagamentos) {
NumberFormat formatter = new DecimalFormat("0.00000000");
DateTimeFormatter dateformatter = DateTimeFormatter.ofPattern("dd/MM/YYY HH:mm");
String formattedDateTime = pagamentosObj.getDataHora().format(dateformatter);
String nome = user.getNome().split("\\s+")[0];
String tipodepagamento = pagamentosObj.getTipoPagamento() == 2 ? "Compra Avulsa" : "Mensal";
String mensagem = "<div style='font-size: 14px; line-height: 14px; font-family: Ubuntu, Tahoma, Verdana, Segoe, sans-serif;' data-mce-style='font-size: 12px; line-height: 14px; font-family: Ubuntu, Tahoma, Verdana, Segoe, sans-serif;'>"+
"<p style='font-size: 14px; line-height: 16px;' data-mce-style='font-size: 14px; line-height: 16px;'>"+
"Olá,"+
"<br />"+
"<br />"+
"Uma nova compra de bitcoin foi feita:"+
"<br />"+
"<br />"+
"Cotação: "+"<b>"+pagamentosObj.getCotacao()+"</b>"+
"<br />"+
"Data e Hora: "+"<b>"+formattedDateTime+"</b>"+
"<br />"+
"<br />"+
"<br />"+
"Cliente: "+"<b>"+user.getNome()+"</b>"+
"<br />" +
"CPF: "+"<b>"+user.getCpf()+"</b>"+
"<br />"+
"E-mail: "+"<b>"+user.getEmail()+"</b>"+
"<br />"+
"Celular: "+"<b>"+user.getCelular()+"</b>"+
"<br />"+
"<br />"+
"Tipo de pagamento: "+"<b>"+tipodepagamento+"</b>"+
"<br />"+
"Quantidade de bitcoin: "+"<b>"+formatter.format(pagamentosObj.getBitcoins()).replace('.', ',')+" BTC</b>"+
"<br />"+
"Taxa de transação: "+"<b>"+formatter.format(pagamentosObj.getTaxa()).replace('.', ',')+" BTC</b>"+
"<br />"+
"Valor total: "+"<b>"+pagamentosObj.getValorPagamentoComTaxa()+"</b>"+
"<br />"+
"<br />"+
"O prazo para liberação dos bitcoins é de <b>2</b> até <b>24</b> horas após aprovação do pagamento."+
"</p>"+
"<p style='font-size: 14px; line-height: 16px;' data-mce-style='font-size: 14px; line-height: 16px;'>"+
"<br />Atenciosamente,"+
"<br />BTC Moedas"+
"</p>"+
"</div>";
return constructEmailAdminHtml("[Admin]Nova compra de bitcoin", mensagem, user);
}
private MimeMessage constructResgateContaBancariaEmail(final User user, ResgateContaBancaria resgatecontabancaria) {
String nome = user.getNome().split("\\s+")[0];
String tipodeconta = resgatecontabancaria.getTipodeconta().equals("1") ? "Conta Corrente" : "Poupança";
String valordoresgate = currencyFormatter.format(Double.valueOf(resgatecontabancaria.getValorResgate()));
String mensagem ="<div style='font-size: 12px; line-height: 14px; font-family: Ubuntu, Tahoma, Verdana, Segoe, sans-serif;' data-mce-style='font-size: 12px; line-height: 14px; font-family: Ubuntu, Tahoma, Verdana, Segoe, sans-serif;'>"+
"<p style='font-size: 14px; line-height: 16px;' data-mce-style='font-size: 14px; line-height: 16px;'>"+
"Olá <strong>"+nome+"</strong>,"+
"<br />"+
"<br />"+
"Sua solicitação de resgate para conta bancária foi feita com sucesso."+
"<br />"+
"<br />"+
"Vamos fazer a seguinte transferência:"+
"<br />"+
"<br />"+
"Banco: "+"<b>"+resgatecontabancaria.getBanco()+"</b>"+
"<br />"+
"Tipo de Conta: "+"<b>"+tipodeconta+"</b>"+
"<br />"+
"Agência: "+"<b>"+resgatecontabancaria.getAgencia()+"</b>"+
"<br />"+
"Conta com dígito:"+"<b>"+resgatecontabancaria.getConta()+"</b>"+
"<br />"+
"Nome: "+"<b>"+user.getNome()+"</b>"+
"<br />"+
"CPF: "+"<b>"+user.getCpf()+"</b>"+
"<br />"+
"Valor: "+"<b>"+valordoresgate+"</b>"+
"<br />"+
"<br />"+
"Se o seu banco não for conveniado (Itaú, Bradesco, Caixa, BB e Santander), iremos deduzir o valor de R$8,90 referente a taxa de transferência bancária."+
"<br />"+
"<br />"+
"O prazo para transferência do dinheiro é de <b>3</b> até <b>5</b> dias úteis.</p>"+
"<p style='font-size: 14px; line-height: 16px;' data-mce-style='font-size: 14px; line-height: 16px;'>"+
"Caso tenha qualquer dúvida basta responder esta e-mail ou então nos contatar pelo número <b>41</b> <b>99973-7902</b>."+
"<br />"+
"<br />Atenciosamente,"+
"<br />BTC Moedas"+
"</p>"+
"</div>";
return constructEmailHtml("[BTC Moedas]Seu resgate para conta bancaria", mensagem, user);
}
private MimeMessage constructResgateBitcoinEmail(final User user, ResgateBitcoin resgatebitcoin) {
String nome = user.getNome().split("\\s+")[0];
String mensagem ="<div style='font-size: 12px; line-height: 14px; font-family: Ubuntu, Tahoma, Verdana, Segoe, sans-serif;' data-mce-style='font-size: 12px; line-height: 14px; font-family: Ubuntu, Tahoma, Verdana, Segoe, sans-serif;'>"+
"<p style='font-size: 14px; line-height: 16px;' data-mce-style='font-size: 14px; line-height: 16px;'>"+
"Olá <strong>"+nome+"</strong>,"+
"<br />"+
"<br />"+
"Sua solicitação de saque para carteira bitcoin foi feita com sucesso."+
"<br />"+
"<br />"+
"Vamos fazer a seguinte transferência:"+
"<br />"+
"<br />"+
"Valor do Saque: "+"<b>"+formatter.format(resgatebitcoin.getBitcoins())+" BTC"+"</b>"+
"<br />"+
"Taxa de Transferência: "+"<b>"+ getfeeLocalBitcoinscomvirgula()+" BTC</b>"+
"<br />"+
"Total Sacado: "+"<b>"+resgatebitcoin.getTotalresgatado()+" BTC"+"</b>"+
"<br />"+
"Endereço bitcoin: "+"<b>"+resgatebitcoin.getEnderecobitcoin()+"</b>"+
"<br />"+
"<br />"+
"O prazo para transferência de bitcoin é de <b>2</b> até <b>24</b> horas.</p>"+
"<p style='font-size: 14px; line-height: 16px;' data-mce-style='font-size: 14px; line-height: 16px;'>"+
"Caso tenha qualquer dúvida basta responder esta e-mail ou então nos contatar pelo número <b>41</b> <b>99973-7902</b>."+
"<br />"+
"<br />Atenciosamente,"+
"<br />BTC Moedas"+
"</p>"+
"</div>";
return constructEmailHtml("[BTC Moedas]Seu saque para carteira bitcoin", mensagem, user);
}
private MimeMessage constructResgateBitcoinEmailAdmin(final User user, ResgateBitcoin resgatebitcoin) {
String mensagem ="<div style='font-size: 12px; line-height: 14px; font-family: Ubuntu, Tahoma, Verdana, Segoe, sans-serif;' data-mce-style='font-size: 12px; line-height: 14px; font-family: Ubuntu, Tahoma, Verdana, Segoe, sans-serif;'>"+
"<p style='font-size: 14px; line-height: 16px;' data-mce-style='font-size: 14px; line-height: 16px;'>"+
"Olá <strong>Davi</strong>,"+
"<br />"+
"<br />"+
"Foi efetuado com sucesso o seguinte saque bitcoin:"+
"<br />"+
"<br />"+
"Cliente: "+"<b>"+user.getNome()+"</b>"+
"<br />"+
"E-mail: "+"<b>"+user.getEmail()+"</b>"+
"<br />"+
"Valor do Saque: "+"<b>"+formatter.format(resgatebitcoin.getBitcoins())+" BTC"+"</b>"+
"<br />"+
"Taxa de Transferência: "+"<b>"+ getfeeLocalBitcoinscomvirgula()+" BTC</b>"+
"<br />"+
"Total Sacado: "+"<b>"+resgatebitcoin.getTotalresgatado()+" BTC"+"</b>"+
"<br />"+
"Endereço bitcoin: "+"<b>"+resgatebitcoin.getEnderecobitcoin()+"</b>"+
"<br />"+
"<br />"+
"<br />Atenciosamente,"+
"<br />BTC Moedas"+
"</p>"+
"</div>";
return constructEmailHtmlResgate("[BTC Moedas]Novo saque bitcoin", mensagem, user);
}
private SimpleMailMessage constructSolicitarVerificao(String nome, String email) {
return constructEmailAdmin("Solicitação de Verificação de Documentos - "+nome, "O cliente "+nome+" - "+email+" solicitou a verificação de seus documentos."+"\r\n\n");
}
private SimpleMailMessage constructContato(String nome, String email, String mensagem) {
return constructEmailAdmin("Nova Mensagem do Site", "Nome: "+nome+"\n"+
"Email: " +email+"\n"+
"Mensagem: "+mensagem+
"\r\n\n");
}
private SimpleMailMessage constructConfirmaCompra(User user) {
return constructEmail(
"[BTC Moedas]Compra confirmada",
"Olá " + user.getNome().split("\\s+")[0]+","+
"\n\n"+"Obrigado por comprar bitcoin conosco."+
"\n\n"+"Sua compra de bitcoin foi confirmada e o bitcoin já está disponível na sua conta."+
"\n\n"+"Se tiver qualquer dúvida, só me chamar aqui ou pelo cel/whatsapp 41 99973-7902."+
"\n\n"+"Atenciosamente,"+
"\n"+"<NAME>"+
"\n"+"BTC Moedas"
,
user);
}
private MimeMessage constructEmailHtml(String subject, String mensagem, User user) {
MimeMessage email = mailSender.createMimeMessage();
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(email, true, "ISO-8859-1");
helper.setSubject(subject);
helper.setText(mensagem, true);
helper.setTo(user.getEmail());
helper.setFrom("<EMAIL>");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return email;
}
private MimeMessage constructEmailHtmlResgate(String subject, String mensagem, User user) {
MimeMessage email = mailSender.createMimeMessage();
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(email, true, "ISO-8859-1");
helper.setSubject(subject);
helper.setText(mensagem, true);
helper.setTo("<EMAIL>");
helper.setFrom("<EMAIL>");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return email;
}
private SimpleMailMessage constructEmail(String subject, String body, User user) {
final SimpleMailMessage email = new SimpleMailMessage();
email.setSubject(subject);
email.setText(body);
email.setTo(user.getEmail());
email.setFrom("<EMAIL>");
return email;
}
private SimpleMailMessage constructEmailAdmin(String subject, String body) {
final SimpleMailMessage email = new SimpleMailMessage();
email.setSubject(subject);
email.setText(body);
email.setTo("<EMAIL>");
email.setFrom("<EMAIL>");
return email;
}
private MimeMessage constructEmailAdminHtml(String subject, String mensagem, User user) {
MimeMessage email = mailSender.createMimeMessage();
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(email, true);
helper.setSubject(subject);
helper.setText(mensagem, true);
helper.setTo("<EMAIL>");
helper.setFrom("<EMAIL>");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return email;
}
private static String getAppUrl(HttpServletRequest request) {
return "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
}
}
<file_sep>/src/com/dhp/util/SendBitcoin.java
package com.dhp.util;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class SendBitcoin {
public String send(String address, String amount) throws Exception {
long unixTime = System.currentTimeMillis() / 1000L;
String hmac_key = "";
String api_endpoint ="/api/wallet-send/";
String postParameters = "address="+address+"&amount="+amount;
String secret = "";
String message = unixTime + hmac_key + api_endpoint + postParameters;
String url = "https://localbitcoins.com/api/wallet-send/";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Apiauth-Key", "");
con.setRequestProperty("Apiauth-Nonce", String.valueOf(unixTime));
con.setRequestProperty("Apiauth-Signature", hmacDigest(message, secret, "HmacSHA256"));
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in;
if (responseCode == 200) {
return "200";
} else{
in = new BufferedReader(new InputStreamReader(con.getErrorStream(), Charset.forName("UTF-8")));
}
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(responseCode);
return ("400");
//return ("200");
}
public String hmacDigest(String msg, String keyString, String algo) {
String digest = null;
try {
SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), algo);
Mac mac = Mac.getInstance(algo);
mac.init(key);
byte[] bytes = mac.doFinal(msg.getBytes("ASCII"));
StringBuffer hash = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
hash.append('0');
}
hash.append(hex);
}
digest = hash.toString();
} catch (UnsupportedEncodingException e) {
} catch (InvalidKeyException e) {
} catch (NoSuchAlgorithmException e) {
}
return digest;
}
}
<file_sep>/src/resources/application.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/dhp?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=<PASSWORD><file_sep>/src/com/dhp/repository/EnderecosBTCRepository.java
package com.dhp.repository;
import com.dhp.model.EnderecosBTC;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface EnderecosBTCRepository extends JpaRepository<EnderecosBTC, Long>{
EnderecosBTC findByClienteid(Long clienteid);
@Override
List<EnderecosBTC> findAll();
}
<file_sep>/src/com/dhp/service/UserDetailsServiceImpl.java
package com.dhp.service;
import com.dhp.afiliados.model.Afiliado;
import com.dhp.afiliados.repository.AfiliadoRepository;
import com.dhp.model.Role;
import com.dhp.model.User;
import com.dhp.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;
public class UserDetailsServiceImpl implements UserDetailsService{
@Autowired
private UserRepository userRepository;
@Autowired
private AfiliadoRepository afiliadoRepository;
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String cpfOuEmail) throws UsernameNotFoundException {
if(cpfOuEmail.matches("(.*)[a-zA-Z](.*)")){
Afiliado afiliado = afiliadoRepository.findByEmail(cpfOuEmail);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Role role : afiliado.getRoles()){
grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
}
return new CustomUser(afiliado.getEmail(), afiliado.getSenha(), afiliado.getNome(), afiliado.getId(), 0, grantedAuthorities);
}
if(!(cpfOuEmail.matches("(.*)[a-zA-Z](.*)"))){
User user = userRepository.findByCpf(cpfOuEmail);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Role role : user.getRoles()){
grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
}
return new CustomUser(user.getCpf(), user.getSenha(), user.getNome(), user.getId(), user.getVerificado(), grantedAuthorities);
}
return null;
}
}
<file_sep>/src/com/dhp/service/AdminServiceImpl.java
package com.dhp.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dhp.model.Pagamentos;
import com.dhp.model.ResgateBitcoin;
import com.dhp.model.ResgateContaBancaria;
import com.dhp.model.User;
import com.dhp.repository.PagamentosRepository;
import com.dhp.repository.ResgateBitcoinRepository;
import com.dhp.repository.ResgateContaBancariaRepository;
import com.dhp.repository.UserRepository;
@Service
public class AdminServiceImpl implements AdminService {
@Autowired
private UserRepository userRepository;
@Autowired
private PagamentosRepository pagamentosRepository;
@Autowired
private ResgateBitcoinRepository resgateBitcoinRepository;
@Autowired
private ResgateContaBancariaRepository resgateContaBancariaRepository;
public List<User> retrieveAllCustomers(){
return userRepository.findAll();
}
public List<Pagamentos> retrieveAllCompras(){
return pagamentosRepository.findAll();
}
public List<ResgateBitcoin> retrieveAllResgateBitcoin(){
return resgateBitcoinRepository.findAll();
}
public List<ResgateContaBancaria> retrieveAllResgateContaBancaria(){
return resgateContaBancariaRepository.findAll();
}
}
<file_sep>/src/com/dhp/model/ContaBancaria.java
package com.dhp.model;
import javax.persistence.*;
@Entity
@Table(name = "contabancaria")
public class ContaBancaria {
private Long clienteid;
private Long id;
private String banco;
private String tipodeconta;
private String agencia;
private String conta;
private String dadosadicionais;
public Long getClienteid() {
return clienteid;
}
public void setClienteid(Long clienteid) {
this.clienteid = clienteid;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getBanco() {
return banco;
}
public void setBanco(String banco) {
this.banco = banco;
}
public String getTipodeconta() {
return tipodeconta;
}
public void setTipodeconta(String tipodeconta) {
this.tipodeconta = tipodeconta;
}
public String getAgencia() {
return agencia;
}
public void setAgencia(String agencia) {
this.agencia = agencia;
}
public String getConta() {
return conta;
}
public void setConta(String conta) {
this.conta = conta;
}
public String getDadosadicionais() {
return dadosadicionais;
}
public void setDadosadicionais(String dadosadicionais) {
this.dadosadicionais = dadosadicionais;
}
}
<file_sep>/src/com/dhp/service/PagamentosServiceImpl.java
package com.dhp.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dhp.model.Pagamentos;
import com.dhp.repository.PagamentosRepository;
@Service
public class PagamentosServiceImpl implements PagamentosService {
@Autowired
private PagamentosRepository pagamentosRepository;
@Override
public void save(Pagamentos pagamento) {
pagamentosRepository.saveAndFlush(pagamento);
}
@Override
public List<Pagamentos> findPagamentos(long clienteId){
return pagamentosRepository.findByClienteid(clienteId);
}
@Override
public Pagamentos findByPagseguroid(String pagseguroid){
return pagamentosRepository.findByPagseguroid(pagseguroid);
};
}
<file_sep>/src/com/dhp/service/UserService.java
package com.dhp.service;
import com.dhp.model.PasswordResetToken;
import com.dhp.model.User;
import java.util.List;
public interface UserService {
void save(User user);
User findByCpf(String cpf);
User findById(long id);
List<User> findByRef(String ref);
User findByRefFinal(String refFinal);
public void createPasswordResetTokenForUser(final User user, final String token);
String validatePasswordResetToken(String cpf, String token);
User getUser(String verificationToken);
void changeUserPassword(User user, String password);
boolean checkIfValidOldPassword(User user, String password);
}
<file_sep>/README.md
# BTC
Developed with Java and Spring MVC this is a complete plataform to sell bitcoin through credit card.
<file_sep>/src/com/dhp/afiliados/service/ResgateBitcoinAfiliadoService.java
package com.dhp.afiliados.service;
import com.dhp.afiliados.model.ResgateBitcoinAfiliado;
import java.util.List;
public interface ResgateBitcoinAfiliadoService {
public void save(ResgateBitcoinAfiliado resgateBitcoinAfiliado);
public List<ResgateBitcoinAfiliado> findResgates(Long afiliado);
}<file_sep>/src/com/dhp/validator/AdminValidator.java
package com.dhp.validator;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.dhp.model.Role;
import com.dhp.model.User;
import com.dhp.service.UserService;
import com.dhp.web.dto.PasswordDto;
@Component
public class AdminValidator implements Validator {
@Autowired
private UserService userService;
@Override
public boolean supports(Class<?> aClass) {
return PasswordDto.class.equals(aClass);
}
@Override
public void validate(Object o, Errors errors) {
User user = (User) o;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "cpf", "NotEmpty");
if (!user.getCpf().equals("05864388904")) {
errors.rejectValue("cpf", "erro.generico");
}
if (user.getCpf() == null) {
errors.rejectValue("cpf", "erro.generico");
}
}
}
<file_sep>/src/com/dhp/afiliados/service/AfiliadoServiceImpl.java
package com.dhp.afiliados.service;
import com.dhp.afiliados.model.PasswordResetTokenAfiliado;
import com.dhp.afiliados.repository.AfiliadoRepository;
import com.dhp.afiliados.repository.PasswordResetTokenAfiliadoRepository;
import com.dhp.model.Role;
import com.dhp.afiliados.model.Afiliado;
import com.dhp.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;
@Service
public class AfiliadoServiceImpl implements AfiliadoService {
@Autowired
private AfiliadoRepository afiliadoRepository;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
private PasswordResetTokenAfiliadoRepository passwordResetTokenAfiliadoRepository;
@Override
public void save(Afiliado afiliado) {
afiliado.setSenha(bCryptPasswordEncoder.encode(afiliado.getSenha()));
Set<Role> roles = new HashSet<>();
Role role = new Role();
role.setId(3L); // 1 = User Role
roles.add(role);
//user.setRoles(new HashSet<>(roleRepository.findAll()));
afiliado.setRoles(roles);
afiliadoRepository.save(afiliado);
}
@Override
public Afiliado findByEmail(String email) {
return afiliadoRepository.findByEmail(email);
}
@Override
public Afiliado findById(long id) {
return afiliadoRepository.findById(id);
}
@Override
public Afiliado findByRefFinal(String refFinal) {
return afiliadoRepository.findByRefEndingWith(refFinal);
}
@Override
public void changeUserPassword(final Afiliado afiliado, final String password) {
afiliado.setSenha(bCryptPasswordEncoder.encode(password));
afiliadoRepository.save(afiliado);
}
@Override
public boolean checkIfValidOldPassword(final Afiliado afiliado, final String oldPassword) {
return bCryptPasswordEncoder.matches(oldPassword, afiliado.getSenha());
}
@Override
public String validatePasswordResetToken(String email, String token) {
final PasswordResetTokenAfiliado passToken = passwordResetTokenAfiliadoRepository.findByToken(token);
final Afiliado afiliado = afiliadoRepository.findByEmail(email);
//System.out.println(passToken.getUser().getCpf());
if ((passToken == null) || (!afiliado.getEmail().equals(email))) {
return "invalidToken";
}
final Calendar cal = Calendar.getInstance();
if ((passToken.getExpiryDate()
.getTime() - cal.getTime()
.getTime()) <= 0) {
return "expired";
}
//final User user = passToken.getUser();
final Authentication auth = new UsernamePasswordAuthenticationToken(afiliado, null, Arrays.asList(new SimpleGrantedAuthority("CHANGE_PASSWORD_PRIVILEGE")));
SecurityContextHolder.getContext()
.setAuthentication(auth);
return null;
}
@Override
public void createPasswordResetTokenForUser(final Afiliado afiliado, final String token) {
final PasswordResetTokenAfiliado myToken = new PasswordResetTokenAfiliado(token, afiliado);
passwordResetTokenAfiliadoRepository.save(myToken);
}
}
<file_sep>/src/com/dhp/web/ErrorController.java
package com.dhp.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@Controller
public class ErrorController {
@RequestMapping(value = "errors", method = RequestMethod.GET)
public ModelAndView renderErrorPage(HttpServletRequest httpRequest) {
ModelAndView errorPage = new ModelAndView("errorPage");
String errorMsg = "";
int httpErrorCode = getErrorCode(httpRequest);
switch (httpErrorCode) {
case 400: {
errorMsg = "Requisição feita incorretamente";
break;
}
case 401: {
errorMsg = "Acesso são autorizado";
break;
}
case 403:{
return new ModelAndView("redirect:/");
}
case 404: {
errorMsg = "Página não encontrada";
break;
}
case 500: {
errorMsg = "Houve um erro ao processar sua requisição";
break;
}
default:
errorMsg = "Erro ao processar sua requisção";
}
errorPage.addObject("errorMsg", errorMsg);
return errorPage;
}
private int getErrorCode(HttpServletRequest httpRequest) {
return (Integer) httpRequest
.getAttribute("javax.servlet.error.status_code");
}
}<file_sep>/src/com/dhp/service/ResgateContaBancariaServiceImpl.java
package com.dhp.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.dhp.model.ResgateContaBancaria;
import com.dhp.repository.ResgateContaBancariaRepository;
import org.springframework.stereotype.Service;
@Service
public class ResgateContaBancariaServiceImpl implements ResgateContaBancariaService {
@Autowired
ResgateContaBancariaRepository resgateContaBancariaService;
public void save(ResgateContaBancaria resgateContaBancaria){
resgateContaBancariaService.save(resgateContaBancaria);
}
public List<ResgateContaBancaria> findResgates(Long clienteId){
return resgateContaBancariaService.findByClienteid(clienteId);
};
}
<file_sep>/src/com/dhp/util/RSADecryption.java
package com.dhp.util;
import java.io.*;
import java.security.Security;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import sun.misc.BASE64Decoder;
public class RSADecryption {
public static void main(String[] args) throws Exception
{
//@Cleanup
FileReader privateKeyReader = new FileReader(new File("/home/m4ndr4ck/BTC/RSA/private_key.pem"));
//@Cleanup
PEMParser parser = new PEMParser(privateKeyReader);
PEMKeyPair keyPair = (PEMKeyPair) parser.readObject();
//keyPair.getPrivateKeyInfo();
String privateKeyFilename = "/home/m4ndr4ck/BTC/RSA/private_key.pem";
String encryptedData = "/home/m4ndr4ck/BTC/RSA/crypted";
String outputFilename = "/home/m4ndr4ck/BTC/RSA/out";
RSADecryption rsaDecryption = new RSADecryption();
rsaDecryption.decrypt(keyPair, encryptedData, outputFilename);
}
private void decrypt (PEMKeyPair keyPair, String encryptedFilename, String outputFilename){
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//String key = readFileAsString(keyPair);
BASE64Decoder b64 = new BASE64Decoder();
AsymmetricKeyParameter privateKey =
(AsymmetricKeyParameter) PrivateKeyFactory.createKey(keyPair.getPrivateKeyInfo());
AsymmetricBlockCipher e = new RSAEngine();
e = new org.bouncycastle.crypto.encodings.PKCS1Encoding(e);
e.init(false, privateKey);
String inputdata = readFileAsString(encryptedFilename);
byte[] messageBytes = hexStringToByteArray(inputdata);
byte[] hexEncodedCipher = e.processBlock(messageBytes, 0, messageBytes.length);
System.out.println(new String(hexEncodedCipher));
BufferedWriter out = new BufferedWriter(new FileWriter(outputFilename));
out.write(new String(hexEncodedCipher));
out.close();
}
catch (Exception e) {
System.out.println(e);
}
}
private String decrypt (String privateKeyFilename, String encryptedData) {
String outputData = null;
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
String key = readFileAsString(privateKeyFilename);
BASE64Decoder b64 = new BASE64Decoder();
AsymmetricKeyParameter privateKey =
(AsymmetricKeyParameter) PrivateKeyFactory.createKey(b64.decodeBuffer(key));
AsymmetricBlockCipher e = new RSAEngine();
e = new org.bouncycastle.crypto.encodings.PKCS1Encoding(e);
e.init(false, privateKey);
byte[] messageBytes = hexStringToByteArray(encryptedData);
byte[] hexEncodedCipher = e.processBlock(messageBytes, 0, messageBytes.length);
System.out.println(new String(hexEncodedCipher));
outputData = new String(hexEncodedCipher);
}
catch (Exception e) {
e.printStackTrace();
}
return outputData;
}
public static String getHexString(byte[] b) throws Exception {
String result = "";
for (int i=0; i < b.length; i++) {
result +=
Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return result;
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
private static String readFileAsString(String filePath)
throws java.io.IOException{
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = new BufferedReader(
new FileReader(filePath));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
System.out.println(fileData.toString());
return fileData.toString();
}
}<file_sep>/src/com/dhp/web/CotacaoControllerAdvice.java
package com.dhp.web;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.NumberFormat;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import com.google.gson.*;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import com.dhp.util.Helpers;
@ControllerAdvice(annotations = CotacaoController.class)
public class CotacaoControllerAdvice {
public static double getCotacaoCOMPRA(){return Helpers.geraCotacaoLocalBitcoins();}
public static double getCotacaoVENDA(){return geraCotacaoLocalBitcoins("sell");}
//public static double getFee(){return FeeLocalBitcoins().get("fee");}
//public static double getFee(){return 0.00025;}
//public static double getTaxaBTC(){return FeeLocalBitcoins();}
Locale locale = new Locale("pt", "BR");
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
@ModelAttribute
public void setCotacoes(Model model){
model.addAttribute("cotacaoCOMPRA", currencyFormatter.format(getCotacaoCOMPRA()));
// model.addAttribute("cotacaoVENDA", currencyFormatter.format(getCotacaoVENDA()));
// model.addAttribute("bitcoinFEE", getFee());
// model.addAttribute("taxaBTC", getTaxaBTC());
}
public static double FeeLocalBitcoins(){
double fee=0;
try {
String url = "https://localbitcoins.com/api/fees/";
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
// read all the lines of the response into response StringBuffer
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = bufferedReader.readLine()) != null) {
response.append(inputLine);
}
bufferedReader.close();
// print result in nice format using the Gson library
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(response.toString());
String strFee = jp.parse(response.toString()).getAsJsonObject().get("data").getAsJsonObject().get("outgoing_fee").toString().replace("\"", "");
//System.out.println("Taxa: " + strFee);
fee = Double.valueOf(strFee);
}catch (Exception e){
e.printStackTrace();
}
Map<String, Double> taxas = new HashMap<>();
taxas.put("fee", fee);
taxas.put("taxaBTC", 0.0005);
return fee;
}
public static double geraCotacaoWall(){
double cotacao = 99999;
try {
String url = "https://s3.amazonaws.com/data-production-walltime-info/production/dynamic/walltime-info.json?now=1528962473468.679.0000000000873";
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
// read all the lines of the response into response StringBuffer
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = bufferedReader.readLine()) != null) {
response.append(inputLine);
}
bufferedReader.close();
// print result in nice format using the Gson library
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(response.toString());
JsonObject test = je.getAsJsonObject();
cotacao = jp.parse(response.toString()).getAsJsonObject().get("BRL_XBT").getAsJsonObject().get("last_inexact").getAsDouble();
}catch (Exception e){
e.printStackTrace();
}
return cotacao+1750;
}
public static double geraCotacaoLocalBitcoins(String param){
double cotacao = 0;
String tipo = param.equals("buy") ? "compra" : "venda";
try {
String url = "https://localbitcoins.com/"+param+"-bitcoins-online/brl/.json";
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
// read all the lines of the response into response StringBuffer
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = bufferedReader.readLine()) != null) {
response.append(inputLine);
}
bufferedReader.close();
// print result in nice format using the Gson library
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(response.toString());
JsonObject test = je.getAsJsonObject();
JsonArray Jarray = (JsonArray) jp.parse(response.toString()).getAsJsonObject().get("data").getAsJsonObject().getAsJsonArray("ad_list");
double total = 4500;
for (int i = 0; i < 10; i++) {
double price = Double.valueOf(Jarray
.get(i)
.getAsJsonObject()
.get("data")
.getAsJsonObject()
.get("temp_price")
.toString().replace("\"", ""));
double minAmount = Double.valueOf(Jarray
.get(i)
.getAsJsonObject()
.get("data")
.getAsJsonObject()
.get("min_amount")
.toString().replace("\"", ""));
total = total + price;
double cotacaoCompra =total / 10;
double cotacaoVenda =total / 10;
double porcentagemVenda = cotacaoVenda * 0;
if (tipo.equals("compra"))
cotacao = cotacaoCompra + 4500;
else cotacao = cotacaoVenda - porcentagemVenda;
}
}catch (Exception e){
e.printStackTrace();
}
return cotacao;
}
public static void main(String... args){
System.out.print(geraCotacaoWall());
}
}
<file_sep>/src/com/dhp/service/SecurityService.java
package com.dhp.service;
public interface SecurityService {
String findLoggedInUsername();
void autologin(String cpf, String senha);
}
<file_sep>/src/com/dhp/afiliados/repository/AfiliadoRepository.java
package com.dhp.afiliados.repository;
import com.dhp.afiliados.model.Afiliado;
import com.dhp.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface AfiliadoRepository extends JpaRepository<Afiliado, Long> {
Afiliado findByEmail(String email);
Afiliado findById(long id);
@Override
List<Afiliado> findAll();
Afiliado findByRefEndingWith(String refFinal);
}
<file_sep>/src/com/dhp/model/ResgateContaBancaria.java
package com.dhp.model;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name = "resgatecontabancaria")
public class ResgateContaBancaria {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private Long clienteid;
@Column
private String banco;
@Column
private String tipodeconta;
@Column
private String agencia;
@Column
private String conta;
@Column
private String dadosadicionais;
@Column(precision=13, scale=2)
private String valorResgate;
@Column
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime dataHora;
@Transient
String nome;
public String getErros() {
return erros;
}
public void setErros(String erros) {
this.erros = erros;
}
@Transient
String erros;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getClienteid() {
return clienteid;
}
public void setClienteid(Long clienteid) {
this.clienteid = clienteid;
}
public String getValorResgate() {
return valorResgate;
}
public void setValorResgate(String valorResgate) {
this.valorResgate = valorResgate;
}
public LocalDateTime getDataHora() {
return dataHora;
}
public void setDataHora(LocalDateTime dataHora) {
this.dataHora = dataHora;
}
public String getBanco() {
return banco;
}
public void setBanco(String banco) {
this.banco = banco;
}
public String getTipodeconta() {
return tipodeconta;
}
public void setTipodeconta(String tipodeconta) {
this.tipodeconta = tipodeconta;
}
public String getAgencia() {
return agencia;
}
public void setAgencia(String agencia) {
this.agencia = agencia;
}
public String getConta() {
return conta;
}
public void setConta(String conta) {
this.conta = conta;
}
public String getDadosadicionais() {
return dadosadicionais;
}
public void setDadosadicionais(String dadosadicionais) {
this.dadosadicionais = dadosadicionais;
}
}
<file_sep>/src/com/dhp/afiliados/model/Afiliado.java
package com.dhp.afiliados.model;
import com.dhp.model.Role;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import javax.validation.constraints.Size;
import java.util.Set;
import java.util.UUID;
@Entity
@Table(name = "afl_afiliado")
public class Afiliado {
private Long id;
private String nome;
private String email;
private String senha;
private String confirmaSenha;
@Column(precision=16, scale=8)
private double saldo;
@Transient
private String ref = UUID.randomUUID().toString();
private String link;
private Set<Role> roles;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
@Transient
public String getConfirmaSenha() {
return confirmaSenha;
}
public void setConfirmaSenha(String confirmaSenha) {
this.confirmaSenha = confirmaSenha;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
@ManyToMany
@JoinTable(name = "afiliado_role", joinColumns = @JoinColumn(name = "afiliado_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public double getSaldo() {
return saldo;
}
public void setSaldo(double saldo) {
this.saldo = saldo;
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>BTC</groupId>
<artifactId>BTC</artifactId>
<version>1.1-test-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>Cp1252</project.build.sourceEncoding>
</properties>
<build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.2</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
<configuration> <!-- add this to disable checking -->
<additionalparam>-Xdoclint:none</additionalparam>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>Cp1252</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<warSourceDirectory>web</warSourceDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>1.5.1</version>
<configuration>
<container>
<containerId>tomcat7x</containerId>
<type>remote</type>
</container>
<configuration>
<type>runtime</type>
<properties>
<cargo.tomcat.manager.url>http://btcmoedas.com.br/manager/text</cargo.tomcat.manager.url>
</properties>
</configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<server>TomcatServer</server>
<url>http://btcmoedas.com.br/manager/text</url>
<path>/DHP</path>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>api-v1-client-java-mvn-repo</id>
<url>https://raw.githubusercontent.com/blockchain/api-v1-client-java/mvn-repo/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.passay</groupId>
<artifactId>passay</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>info.blockchain</groupId>
<artifactId>api</artifactId>
<version>LATEST</version> <!-- for a specific version see the list of tags -->
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>[4.3.18,)</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.7.RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.7.RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.7.RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.7.RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.0.4.RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.0.4.RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.11.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.1.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
<version>5.1.0.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.1.RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>[1.13.12,)</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.bitcoinj</groupId>
<artifactId>bitcoinj-core</artifactId>
<version>0.14.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>PagSeguro</groupId>
<artifactId>PagSeguro</artifactId>
<version>3.1.1</version>
<scope>system</scope>
<systemPath>${basedir}/web/WEB-INF/lib/pagseguro-api-3.1.1.jar</systemPath>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>[1.3.3,)</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.sargue</groupId>
<artifactId>java-time-jsptags</artifactId>
<version>1.1.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20170516</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.58</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.58</version>
</dependency>
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>com.paypal.sdk</groupId>
<artifactId>rest-api-sdk</artifactId>
<version>LATEST</version>
<exclusions>
<exclusion> <!-- declare the exclusion here -->
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<distributionManagement>
<repository>
<uniqueVersion>false</uniqueVersion>
<id>nexus</id>
<name>nexus</name>
<url>http://localhost:8081/repository/btc-release/</url>
<layout>default</layout>
</repository>
<snapshotRepository>
<uniqueVersion>false</uniqueVersion>
<id>nexus</id>
<name>nexus</name>
<url>http://localhost:8081/repository/btc-snapshot/</url>
<layout>default</layout>
</snapshotRepository>
</distributionManagement>
</project>
<file_sep>/src/com/dhp/afiliados/service/ResgateBitcoinAfiliadoServiceImpl.java
package com.dhp.afiliados.service;
import com.dhp.afiliados.model.ResgateBitcoinAfiliado;
import com.dhp.afiliados.repository.ResgateBitcoinAfiliadoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ResgateBitcoinAfiliadoServiceImpl implements ResgateBitcoinAfiliadoService {
@Autowired
private ResgateBitcoinAfiliadoRepository resgateBitcoinAfiliadoRepository;
public void save(ResgateBitcoinAfiliado resgateBitcoinAfiliado){
resgateBitcoinAfiliadoRepository.save(resgateBitcoinAfiliado);
}
public List<ResgateBitcoinAfiliado> findResgates(Long afiliadoid){
return resgateBitcoinAfiliadoRepository.findByAfiliadoid(afiliadoid);
}
}<file_sep>/src/com/dhp/web/CotacaoTaxaSingleton.java
package com.dhp.web;
import com.google.gson.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class CotacaoTaxaSingleton {
private static CotacaoTaxaSingleton instance = null;
private CotacaoTaxaSingleton(){
}
public static synchronized CotacaoTaxaSingleton getInstance() {
if(instance == null) {
instance = new CotacaoTaxaSingleton();
}
return instance;
}
public Map<String, Double> FeeLocalBitcoins(){
double fee=0;
try {
String url = "https://localbitcoins.com/api/fees/";
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
// read all the lines of the response into response StringBuffer
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = bufferedReader.readLine()) != null) {
response.append(inputLine);
}
bufferedReader.close();
// print result in nice format using the Gson library
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(response.toString());
String strFee = jp.parse(response.toString()).getAsJsonObject().get("data").getAsJsonObject().get("outgoing_fee").toString().replace("\"", "");
//System.out.println("Taxa: " + strFee);
fee = Double.valueOf(strFee);
}catch (Exception e){
e.printStackTrace();
}
Map<String, Double> taxas = new HashMap<>();
taxas.put("fee", fee);
taxas.put("taxaBTC", fee*2);
return taxas;
}
public double geraCotacaoLocalBitcoins(String param){
double cotacao = 0;
String tipo = param.equals("buy") ? "compra" : "venda";
try {
String url = "https://localbitcoins.com/"+param+"-bitcoins-online/brl/.json";
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
// read all the lines of the response into response StringBuffer
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = bufferedReader.readLine()) != null) {
response.append(inputLine);
}
bufferedReader.close();
// print result in nice format using the Gson library
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(response.toString());
JsonObject test = je.getAsJsonObject();
JsonArray Jarray = (JsonArray) jp.parse(response.toString()).getAsJsonObject().get("data").getAsJsonObject().getAsJsonArray("ad_list");
double total = 0;
for (int i = 0; i < 10; i++) {
double price = Double.valueOf(Jarray
.get(i)
.getAsJsonObject()
.get("data")
.getAsJsonObject()
.get("temp_price")
.toString().replace("\"", ""));
double minAmount = Double.valueOf(Jarray
.get(i)
.getAsJsonObject()
.get("data")
.getAsJsonObject()
.get("min_amount")
.toString().replace("\"", ""));
total = total + price;
double cotacaoCompra =total / 10 * 0.05;
double cotacaoVenda =total / 10;
double porcentagemVenda = cotacaoVenda * 0.03;
if (tipo.equals("compra"))
cotacao = cotacaoCompra;
else cotacao = cotacaoVenda - porcentagemVenda;
}
}catch (Exception e){
e.printStackTrace();
}
return cotacao;
}
}
|
acac52fecc1413074ec2395ccb89b2b5c3655b33
|
[
"JavaScript",
"Markdown",
"Maven POM",
"INI",
"Java"
] | 37
|
Java
|
m4ndr4ck/BTC
|
97695df35d73ff09c7de29f23d2b81bccf9ce4ab
|
7275570d5e451df4dda43f70c9d1137d8b72fb18
|
refs/heads/master
|
<repo_name>martinpelli/Api-Log-y-Opt<file_sep>/src/main/java/edu/unsj/fcefn/lcc/optimizacion/api/model/repositories/FramesRepository.java
package edu.unsj.fcefn.lcc.optimizacion.api.model.repositories;
import edu.unsj.fcefn.lcc.optimizacion.api.model.entities.FramesEntity;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface FramesRepository extends CrudRepository<FramesEntity,Integer> {
List<FramesEntity> findAll();
}
<file_sep>/src/main/java/edu/unsj/fcefn/lcc/optimizacion/api/services/FramesService.java
package edu.unsj.fcefn.lcc.optimizacion.api.services;
import edu.unsj.fcefn.lcc.optimizacion.api.model.domain.FramesDTO;
import edu.unsj.fcefn.lcc.optimizacion.api.model.mappers.FramesMapper;
import edu.unsj.fcefn.lcc.optimizacion.api.model.repositories.FramesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class FramesService {
@Autowired
FramesRepository framesRepository;
@Autowired
FramesMapper framesMapper;
public List<FramesDTO> frames;
@PostConstruct
private void init(){
this.frames = this.findAll();
}
public List<FramesDTO> getFrames(){
return this.frames;
}
public List<FramesDTO> findByIdDepartureStopAndIdArrivalStop(Integer idDepartureStop, Integer idArrivalStop){
return this.frames
.stream()
.filter(frameDTO -> frameDTO.getId_stop_departure().getId().equals(idDepartureStop))
.filter(frameDTO -> frameDTO.getId_stop_arrival().equals(idArrivalStop))
.collect(Collectors.toList());
}
public List<FramesDTO> findAll(){
return framesRepository
.findAll()
.stream()
.map(framesEntity -> framesMapper.entityToDTO(framesEntity))
.collect(Collectors.toList());
}
}
<file_sep>/src/main/java/edu/unsj/fcefn/lcc/optimizacion/api/model/mappers/AlgorithmMapper.java
package edu.unsj.fcefn.lcc.optimizacion.api.model.mappers;
import edu.unsj.fcefn.lcc.optimizacion.api.model.domain.FramesDTO;
import edu.unsj.fcefn.lcc.optimizacion.api.model.domain.StopsDTO;
import edu.unsj.fcefn.lcc.optimizacion.api.services.FramesService;
import org.moeaframework.core.variable.Permutation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class AlgorithmMapper {
@Autowired
FramesService framesService;
public List<FramesDTO> permutationToDTO(Permutation permutation, List<StopsDTO> stops) {
List<FramesDTO> route = new ArrayList<>();
for(int i = 0;i < permutation.size() - 1;i++){
Integer departureStopId = stops.get(i).getId();
Integer arrivalStopId = stops.get(i + 1).getId();
FramesDTO frame = framesService
.findByIdDepartureStopAndIdArrivalStop(departureStopId, arrivalStopId)
.stream()
.findFirst()
.get();
route.add(frame);
}
return route;
}
}
|
18a914de6713b27e124da29432ec645c5df05060
|
[
"Java"
] | 3
|
Java
|
martinpelli/Api-Log-y-Opt
|
ebb948053060aa90a51ef5bb0040858dd2813352
|
c20daac9f74ab7bba891a6f607d3861e895dec68
|
refs/heads/master
|
<repo_name>rcristi/spotify-dedup<file_sep>/update-gh-pages.js
var ghpages = require('gh-pages');
ghpages.publish('dist', function(err) {
console.log('done', err);
});
|
489105845d15a05d50f1b17ffac08043e500332d
|
[
"JavaScript"
] | 1
|
JavaScript
|
rcristi/spotify-dedup
|
0897e493200156054ac2ea9d6212bf9f70d60d5b
|
bf13d8c636cbb67267d89fe609f484129facfbc3
|
refs/heads/master
|
<file_sep>package com.licenser.testtaskforroi.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity
@Table(uniqueConstraints={@UniqueConstraint(name = "UC_CATEGORY", columnNames={"type"})}, name = "CATEGORY")
public class CategoryPO extends AbstractPO{
@Column(name = "type", nullable = false)
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
<file_sep>package com.licenser.testtaskforroi.converters;
import com.licenser.testtaskforroi.entity.CategoryPO;
import com.licenser.testtaskforroi.transfer.CategoryTO;
import org.springframework.stereotype.Component;
@Component
public class CategoryPOConverter {
CategoryTO convert(CategoryPO category) {
CategoryTO result = new CategoryTO();
result.setId(category.getId());
result.setType(category.getType());
return result;
}
}
<file_sep>package com.licenser.testtaskforroi.service;
import com.licenser.testtaskforroi.converters.CategoryTOConverter;
import com.licenser.testtaskforroi.converters.ProductPOConverter;
import com.licenser.testtaskforroi.converters.ProductTOConverter;
import com.licenser.testtaskforroi.entity.ProductPO;
import com.licenser.testtaskforroi.repository.ProductRepository;
import com.licenser.testtaskforroi.transfer.ProductTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class ProductService {
@Autowired
private ProductRepository repository;
@Autowired
private ProductPOConverter productPOConverter;
@Autowired
private ProductTOConverter productTOConverter;
@Autowired
private CategoryTOConverter categoryTOConverter;
public void add(ProductTO entity) {
ProductPO convert = productTOConverter.convert(entity);
repository.save(convert);
}
public ProductTO get(Long id) {
Optional<ProductPO> product = repository.findById(id);
return product.map(productPO -> productPOConverter.convert(productPO)).orElse(null);
}
public List<ProductTO> getAll() {
Iterable<ProductPO> all = repository.findAll();
return productPOConverter.convert(all);
}
public void update(ProductTO entity) {
ProductPO convert = productTOConverter.convert(entity);
repository.save(convert);
}
public void delete(Long id) {
repository.deleteById(id);
}
public List<ProductTO> getByName(String name) {
List<ProductPO> products = repository.getByName(name);
return productPOConverter.convert(products);
}
public List<ProductTO> getByCategory(String category) {
List<ProductPO> products = repository.getByCategory(category);
List<ProductTO> result = new ArrayList<>();
for (ProductPO productPO : products) {
result.add(productPOConverter.convert(productPO));
}
return result;
}
}
<file_sep>spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/DataBase_ROI?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
server.port=8080<file_sep>package com.licenser.testtaskforroi.entity;
import javax.persistence.*;
import javax.validation.constraints.Size;
import java.util.Set;
@Entity
@Table(uniqueConstraints = {@UniqueConstraint(name = "UC_PRODUCT", columnNames = {"name"})}, name = "PRODUCT")
public class ProductPO extends AbstractPO {
@Column(name = "name", nullable = false)
private String name;
@Column(name = "description")
private String description;
@ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
@JoinTable(name = "PRODUCT_X_CATEGORY",
joinColumns = @JoinColumn(name = "PRODUCT_ID"),
inverseJoinColumns = @JoinColumn(name = "CATEGORY_ID")
)
@Size(min = 1)
private Set<CategoryPO> category;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<CategoryPO> getCategory() {
return category;
}
public void setCategory(Set<CategoryPO> category) {
this.category = category;
}
}
<file_sep>package com.licenser.testtaskforroi.repository;
import com.licenser.testtaskforroi.entity.ProductPO;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<ProductPO, Long>, Product {
}
<file_sep>package com.licenser.testtaskforroi.repository;
import com.licenser.testtaskforroi.entity.ProductPO;
import java.util.List;
public interface Product {
List<ProductPO> getByName(String name);
List<ProductPO> getByCategory(String type);
}
|
31c6f50881c81b87ff958e2461a7bdcee2628d2e
|
[
"Java",
"INI"
] | 7
|
Java
|
LicenserX/TestTaskForRoi
|
397f03867503670eda81cb164d8ce77c5c10e167
|
448783f93d588130901339531c5b897b897d4625
|
refs/heads/master
|
<file_sep>import Hls from '../../src/hls';
const assert = require('assert');
describe('Hls', function () {
it('should return a bandwidth estimate if the estimator exists', function () {
const MOCKED_ESTIMATE = 2000;
const hls = new Hls();
hls.abrController = {
_bwEstimator: {
getEstimate: () => MOCKED_ESTIMATE
}
};
assert.strictEqual(hls.bandwidthEstimate, MOCKED_ESTIMATE);
});
it('should return NaN if the estimator does not exist', function () {
const hls = new Hls();
assert.strictEqual(isNaN(hls.bandwidthEstimate), true);
});
});
<file_sep>import sinon from 'sinon';
import SubtitleTrackController from '../../../src/controller/subtitle-track-controller';
import Hls from '../../../src/hls';
const assert = require('assert');
describe('SubtitleTrackController', () => {
let subtitleTrackController;
let videoElement;
beforeEach(() => {
const hls = new Hls();
videoElement = document.createElement('video');
subtitleTrackController = new SubtitleTrackController(hls);
subtitleTrackController.media = videoElement;
subtitleTrackController.tracks = [{ id: 0, url: 'baz', details: { live: false } }, { id: 1, url: 'bar' }, { id: 2, details: { live: true }, url: 'foo' }];
const textTrack1 = videoElement.addTextTrack('subtitles', 'English', 'en');
const textTrack2 = videoElement.addTextTrack('subtitles', 'Swedish', 'se');
textTrack1.mode = 'disabled';
textTrack2.mode = 'disabled';
});
describe('onTextTrackChanged', () => {
it('should set subtitleTrack to -1 if disabled', () => {
assert.strictEqual(subtitleTrackController.subtitleTrack, -1);
videoElement.textTracks[0].mode = 'disabled';
subtitleTrackController._onTextTracksChanged();
assert.strictEqual(subtitleTrackController.subtitleTrack, -1);
});
it('should set subtitleTrack to 0 if hidden', () => {
assert.strictEqual(subtitleTrackController.subtitleTrack, -1);
videoElement.textTracks[0].mode = 'hidden';
subtitleTrackController._onTextTracksChanged();
assert.strictEqual(subtitleTrackController.subtitleTrack, 0);
});
it('should set subtitleTrack to 0 if showing', () => {
assert.strictEqual(subtitleTrackController.subtitleTrack, -1);
videoElement.textTracks[0].mode = 'showing';
subtitleTrackController._onTextTracksChanged();
assert.strictEqual(subtitleTrackController.subtitleTrack, 0);
});
});
describe('set subtitleTrack', () => {
it('should set active text track mode to showing', () => {
videoElement.textTracks[0].mode = 'disabled';
subtitleTrackController.subtitleDisplay = true;
subtitleTrackController.subtitleTrack = 0;
assert.strictEqual(videoElement.textTracks[0].mode, 'showing');
});
it('should set active text track mode to hidden', () => {
videoElement.textTracks[0].mode = 'disabled';
subtitleTrackController.subtitleDisplay = false;
subtitleTrackController.subtitleTrack = 0;
assert.strictEqual(videoElement.textTracks[0].mode, 'hidden');
});
it('should disable previous track', () => {
// Change active track without triggering setSubtitleTrackInternal
subtitleTrackController.trackId = 0;
// Change active track and trigger setSubtitleTrackInternal
subtitleTrackController.subtitleTrack = 1;
assert.strictEqual(videoElement.textTracks[0].mode, 'disabled');
});
it('should trigger SUBTITLE_TRACK_SWITCH', function () {
const triggerSpy = sinon.spy(subtitleTrackController.hls, 'trigger');
subtitleTrackController.trackId = 0;
subtitleTrackController.subtitleTrack = 1;
assert.equal(triggerSpy.callCount, 2);
assert.equal(triggerSpy.firstCall.calledWith('hlsSubtitleTrackSwitch', { id: 1 }), true);
});
it('should trigger SUBTITLE_TRACK_LOADING if the track has no details', function () {
const triggerSpy = sinon.spy(subtitleTrackController.hls, 'trigger');
subtitleTrackController.trackId = 0;
subtitleTrackController.subtitleTrack = 1;
assert.equal(triggerSpy.callCount, 2);
assert.equal(triggerSpy.secondCall.calledWith('hlsSubtitleTrackLoading', { url: 'bar', id: 1 }), true);
});
it('should not trigger SUBTITLE_TRACK_LOADING if the track has details and is not live', function () {
const triggerSpy = sinon.spy(subtitleTrackController.hls, 'trigger');
subtitleTrackController.trackId = 1;
subtitleTrackController.subtitleTrack = 0;
assert.equal(triggerSpy.callCount, 1);
assert.equal(triggerSpy.firstCall.calledWith('hlsSubtitleTrackSwitch', { id: 0 }), true);
});
it('should trigger SUBTITLE_TRACK_SWITCH if passed -1', function () {
const stopTimerSpy = sinon.spy(subtitleTrackController, '_stopTimer');
const triggerSpy = sinon.spy(subtitleTrackController.hls, 'trigger');
subtitleTrackController.trackId = 0;
subtitleTrackController.subtitleTrack = -1;
assert.equal(stopTimerSpy.callCount, 1);
assert.equal(triggerSpy.firstCall.calledWith('hlsSubtitleTrackSwitch', { id: -1 }), true);
});
it('should trigger SUBTITLE_TRACK_LOADING if the track is live, even if it has details', function () {
const triggerSpy = sinon.spy(subtitleTrackController.hls, 'trigger');
subtitleTrackController.trackId = 0;
subtitleTrackController.subtitleTrack = 2;
assert.equal(triggerSpy.callCount, 2);
assert.equal(triggerSpy.secondCall.calledWith('hlsSubtitleTrackLoading', { url: 'foo', id: 2 }), true);
});
it('should do nothing if called with out of bound indicies', function () {
const stopTimerSpy = sinon.spy(subtitleTrackController, '_stopTimer');
subtitleTrackController.subtitleTrack = 5;
subtitleTrackController.subtitleTrack = -2;
assert.equal(stopTimerSpy.callCount, 0);
});
it('should do nothing if called with a non-number', function () {
subtitleTrackController.subtitleTrack = undefined;
subtitleTrackController.subtitleTrack = null;
});
describe('_toggleTrackModes', function () {
// This can be the case when setting the subtitleTrack before Hls.js attaches to the mediaElement
it('should not throw an exception if trackId is out of the mediaElement text track bounds', function () {
subtitleTrackController.trackId = 3;
subtitleTrackController._toggleTrackModes(1);
});
it('should disable all textTracks if called with -1', function () {
[].slice.call(videoElement.textTracks).forEach(t => {
t.mode = 'showing';
});
subtitleTrackController._toggleTrackModes(-1);
[].slice.call(videoElement.textTracks).forEach(t => {
assert.equal(t.mode, 'disabled');
});
});
it('should not throw an exception if the mediaElement does not exist', function () {
subtitleTrackController.media = null;
subtitleTrackController._toggleTrackModes(1);
});
});
});
});
|
4d9f27970fd30f5c87191d84fac6a45cfa2e4702
|
[
"JavaScript"
] | 2
|
JavaScript
|
Beraliv/hls.js
|
72d11ecd0c1bd547f69d924b93f9d9ad7451242c
|
c044ccd93d9fdad5cc786245c8dd0400bacda643
|
refs/heads/master
|
<repo_name>arrebagrove/Money<file_sep>/src/Money.UI/Services/Models/Builders/OutcomeBuilder.cs
using Microsoft.EntityFrameworkCore;
using Money.Data;
using Money.Events;
using Money.Services.Models.Queries;
using Neptuo;
using Neptuo.Activators;
using Neptuo.Events.Handlers;
using Neptuo.Models.Keys;
using Neptuo.Queries.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Money.Services.Models.Builders
{
public class OutcomeBuilder : IEventHandler<OutcomeCreated>,
IEventHandler<OutcomeCategoryAdded>,
IEventHandler<OutcomeAmountChanged>,
IEventHandler<OutcomeDescriptionChanged>,
IEventHandler<OutcomeWhenChanged>,
IEventHandler<OutcomeDeleted>,
IQueryHandler<ListMonthWithOutcome, IEnumerable<MonthModel>>,
IQueryHandler<ListMonthCategoryWithOutcome, IEnumerable<CategoryWithAmountModel>>,
IQueryHandler<GetTotalMonthOutcome, Price>,
IQueryHandler<GetCategoryName, string>,
IQueryHandler<ListMonthOutcomeFromCategory, IEnumerable<OutcomeOverviewModel>>,
IQueryHandler<ListYearOutcomeFromCategory, IEnumerable<OutcomeOverviewModel>>
{
private readonly IFactory<Price, decimal> priceFactory;
public OutcomeBuilder(IFactory<Price, decimal> priceFactory)
{
Ensure.NotNull(priceFactory, "priceFactory");
this.priceFactory = priceFactory;
}
public async Task<IEnumerable<MonthModel>> HandleAsync(ListMonthWithOutcome query)
{
using (ReadModelContext db = new ReadModelContext())
{
var entities = await db.Outcomes
.OrderByDescending(o => o.When)
.Select(o => new { Year = o.When.Year, Month = o.When.Month })
.Distinct()
.ToListAsync();
return entities
.Select(o => new MonthModel(o.Year, o.Month));
}
}
public async Task<IEnumerable<CategoryWithAmountModel>> HandleAsync(ListMonthCategoryWithOutcome query)
{
using (ReadModelContext db = new ReadModelContext())
{
Dictionary<Guid, Price> totals = new Dictionary<Guid, Price>();
List<OutcomeEntity> outcomes = await db.Outcomes
.Where(o => o.When.Month == query.Month.Month && o.When.Year == query.Month.Year)
.Include(o => o.Categories)
.ToListAsync();
foreach (OutcomeEntity outcome in outcomes)
{
foreach (OutcomeCategoryEntity category in outcome.Categories)
{
Price price;
if (totals.TryGetValue(category.CategoryId, out price))
price = price + new Price(outcome.Amount, outcome.Currency);
else
price = new Price(outcome.Amount, outcome.Currency);
totals[category.CategoryId] = price;
}
}
List<CategoryWithAmountModel> result = new List<CategoryWithAmountModel>();
foreach (var item in totals)
{
CategoryModel model = (await db.Categories.FindAsync(item.Key)).ToModel();
result.Add(new CategoryWithAmountModel(
model.Key,
model.Name,
model.Description,
model.Color,
item.Value
));
}
return result.OrderBy(m => m.Name);
}
}
public async Task<string> HandleAsync(GetCategoryName query)
{
using (ReadModelContext db = new ReadModelContext())
{
CategoryEntity category = await db.Categories.FindAsync(query.CategoryKey.AsGuidKey().Guid);
if (category == null)
throw Ensure.Exception.ArgumentOutOfRange("categoryKey", "No such category with key '{0}'.", query.CategoryKey);
return category.Name;
}
}
public async Task<Price> HandleAsync(GetTotalMonthOutcome query)
{
using (ReadModelContext db = new ReadModelContext())
{
List<Price> outcomes = await db.Outcomes
.Where(o => o.When.Month == query.Month.Month && o.When.Year == query.Month.Year)
.Select(o => new Price(o.Amount, o.Currency))
.ToListAsync();
Price price = priceFactory.Create(0);
foreach (Price outcome in outcomes)
price += outcome;
return price;
}
}
public async Task<IEnumerable<OutcomeOverviewModel>> HandleAsync(ListYearOutcomeFromCategory query)
{
using (ReadModelContext db = new ReadModelContext())
{
IQueryable<OutcomeEntity> entities = db.Outcomes;
if (!query.CategoryKey.IsEmpty)
entities = entities.Where(o => o.Categories.Select(c => c.CategoryId).Contains(query.CategoryKey.AsGuidKey().Guid));
List<OutcomeOverviewModel> outcomes = await entities
.Where(o => o.When.Year == query.Year.Year)
.OrderBy(o => o.When)
.Select(o => o.ToOverviewModel())
.ToListAsync();
return outcomes;
}
}
public async Task<IEnumerable<OutcomeOverviewModel>> HandleAsync(ListMonthOutcomeFromCategory query)
{
using (ReadModelContext db = new ReadModelContext())
{
IQueryable<OutcomeEntity> entities = db.Outcomes;
if (!query.CategoryKey.IsEmpty)
entities = entities.Where(o => o.Categories.Select(c => c.CategoryId).Contains(query.CategoryKey.AsGuidKey().Guid));
List<OutcomeOverviewModel> outcomes = await entities
.Where(o => o.When.Month == query.Month.Month && o.When.Year == query.Month.Year)
.OrderBy(o => o.When)
.Select(o => o.ToOverviewModel())
.ToListAsync();
return outcomes;
}
}
public Task HandleAsync(OutcomeCreated payload)
{
using (ReadModelContext db = new ReadModelContext())
{
db.Outcomes.Add(new OutcomeEntity(new OutcomeModel(
payload.AggregateKey,
payload.Amount,
payload.When,
payload.Description,
new List<IKey>() { payload.CategoryKey }
)));
return db.SaveChangesAsync();
}
}
public async Task HandleAsync(OutcomeCategoryAdded payload)
{
using (ReadModelContext db = new ReadModelContext())
{
OutcomeEntity entity = await db.Outcomes.FindAsync(payload.AggregateKey.AsGuidKey().Guid);
if (entity != null)
{
entity.Categories.Add(new OutcomeCategoryEntity()
{
OutcomeId = payload.AggregateKey.AsGuidKey().Guid,
CategoryId = payload.CategoryKey.AsGuidKey().Guid
});
await db.SaveChangesAsync();
}
}
}
public async Task HandleAsync(OutcomeAmountChanged payload)
{
using (ReadModelContext db = new ReadModelContext())
{
OutcomeEntity entity = await db.Outcomes.FindAsync(payload.AggregateKey.AsGuidKey().Guid);
if (entity != null)
{
entity.Amount = payload.NewValue.Value;
entity.Currency = payload.NewValue.Currency;
await db.SaveChangesAsync();
}
}
}
public async Task HandleAsync(OutcomeDescriptionChanged payload)
{
using (ReadModelContext db = new ReadModelContext())
{
OutcomeEntity entity = await db.Outcomes.FindAsync(payload.AggregateKey.AsGuidKey().Guid);
if (entity != null)
{
entity.Description = payload.Description;
await db.SaveChangesAsync();
}
}
}
public async Task HandleAsync(OutcomeWhenChanged payload)
{
using (ReadModelContext db = new ReadModelContext())
{
OutcomeEntity entity = await db.Outcomes.FindAsync(payload.AggregateKey.AsGuidKey().Guid);
if (entity != null)
{
entity.When = payload.When;
await db.SaveChangesAsync();
}
}
}
public async Task HandleAsync(OutcomeDeleted payload)
{
using (ReadModelContext db = new ReadModelContext())
{
OutcomeEntity entity = await db.Outcomes.FindAsync(payload.AggregateKey.AsGuidKey().Guid);
if (entity != null)
{
db.Outcomes.Remove(entity);
await db.SaveChangesAsync();
}
}
}
}
}
<file_sep>/src/Money.UI/Data/EventSourcingContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Money.Data
{
internal class EventSourcingContext : Neptuo.Data.Entity.EventSourcingContext
{
public EventSourcingContext()
: base("Filename=EventSourcing.db")
{ }
}
}
<file_sep>/src/Money.UI/Views/Converters/BoolConverter.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
namespace Money.Views.Converters
{
public class BoolConverter : IValueConverter
{
[DefaultValue(true)]
public bool Test { get; set; } = true;
public object TrueValue { get; set; }
public object FalseValue { get; set; }
public object Convert(object value, Type targetType, object parameter, string language)
{
bool? boolValue = value as bool?;
if (boolValue == null)
boolValue = false;
if (Test == boolValue.Value)
return TrueValue;
return FalseValue;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
<file_sep>/src/Money.UI/Bootstrap/BootstrapTask.cs
using Microsoft.EntityFrameworkCore;
using Money.Data;
using Money.Services;
using Money.Services.Models.Builders;
using Money.Services.Tiles;
using Neptuo;
using Neptuo.Activators;
using Neptuo.Converters;
using Neptuo.Data;
using Neptuo.Events;
using Neptuo.Exceptions.Handlers;
using Neptuo.Formatters;
using Neptuo.Formatters.Converters;
using Neptuo.Formatters.Metadata;
using Neptuo.Models.Keys;
using Neptuo.Models.Repositories;
using Neptuo.Models.Snapshots;
using Neptuo.Queries;
using Neptuo.ReadModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI;
namespace Money.Bootstrap
{
public class BootstrapTask : IExceptionHandler
{
private PersistentEventDispatcher eventDispatcher;
public IFactory<Price, decimal> PriceFactory { get; private set; }
public IRepository<Outcome, IKey> OutcomeRepository { get; private set; }
public IRepository<Category, IKey> CategoryRepository { get; private set; }
public IDomainFacade DomainFacade { get; private set; }
public EntityEventStore EventStore { get; private set; }
public IFormatter EventFormatter { get; private set; }
public IQueryDispatcher QueryDispatcher { get; private set; }
public void Initialize()
{
Domain();
ReadModels();
ServiceProvider.QueryDispatcher = QueryDispatcher;
ServiceProvider.DomainFacade = DomainFacade;
ServiceProvider.UpgradeService = new UpgradeService(DomainFacade, EventStore, EventFormatter);
ServiceProvider.TileService = new TileService();
}
private void Domain()
{
Converts.Repository
.AddJsonEnumSearchHandler()
.AddJsonPrimitivesSearchHandler()
.AddJsonObjectSearchHandler()
.AddJsonKey()
.AddJsonTimeSpan()
.Add(new ColorConverter());
EventStore = new EntityEventStore(Factory.Default<EventSourcingContext>());
eventDispatcher = new PersistentEventDispatcher(new EmptyEventStore());
eventDispatcher.DispatcherExceptionHandlers.Add(this);
eventDispatcher.EventExceptionHandlers.Add(this);
IFactory<ICompositeStorage> compositeStorageFactory = Factory.Default<JsonCompositeStorage>();
ICompositeTypeProvider typeProvider = new ReflectionCompositeTypeProvider(
new ReflectionCompositeDelegateFactory(),
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public
);
EventFormatter = new CompositeEventFormatter(typeProvider, compositeStorageFactory);
OutcomeRepository = new AggregateRootRepository<Outcome>(
EventStore,
EventFormatter,
new ReflectionAggregateRootFactory<Outcome>(),
eventDispatcher,
new NoSnapshotProvider(),
new EmptySnapshotStore()
);
CategoryRepository = new AggregateRootRepository<Category>(
EventStore,
EventFormatter,
new ReflectionAggregateRootFactory<Category>(),
eventDispatcher,
new NoSnapshotProvider(),
new EmptySnapshotStore()
);
PriceFactory = new PriceFactory("CZK");
DomainFacade = new DefaultDomainFacade(
OutcomeRepository,
CategoryRepository,
PriceFactory
);
}
private void ReadModels()
{
// Should match with RecreateReadModelContext.
DefaultQueryDispatcher queryDispatcher = new DefaultQueryDispatcher();
QueryDispatcher = queryDispatcher;
CategoryBuilder categoryBuilder = new CategoryBuilder();
queryDispatcher.AddAll(categoryBuilder);
eventDispatcher.Handlers.AddAll(categoryBuilder);
OutcomeBuilder outcomeBuilder = new OutcomeBuilder(PriceFactory);
queryDispatcher.AddAll(outcomeBuilder);
eventDispatcher.Handlers.AddAll(outcomeBuilder);
}
public void Handle(Exception exception)
{
throw new NotImplementedException();
}
}
}
<file_sep>/src/Money.UI/Views/Controls/CategoryEdit.xaml.cs
using Money.ViewModels;
using Money.ViewModels.Collections;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.ComponentModel;
using Windows.System;
namespace Money.Views.Controls
{
public sealed partial class CategoryEdit : UserControl
{
public CategoryEdit()
{
InitializeComponent();
}
private void OnDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs e)
{
CategoryEditViewModel viewModel = e.NewValue as CategoryEditViewModel;
if (viewModel != null)
{
viewModel.PropertyChanged += OnViewModelPropertyChanged;
if (viewModel.Key.IsEmpty)
flyRename.ShowAt(btnRename);
}
}
private void OnViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(CategoryEditViewModel.Color))
flyColor.Hide();
else if (e.PropertyName == nameof(CategoryEditViewModel.Name) || e.PropertyName == nameof(CategoryEditViewModel.Description))
flyRename.Hide();
}
private void flyRename_Opened(object sender, object e)
{
tbxName.Focus(FocusState.Keyboard);
}
private void tbxName_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Enter)
{
tbxDescription.Focus(FocusState.Keyboard);
e.Handled = true;
}
}
private void tbxDescription_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Enter)
{
if (btnSave.Command.CanExecute(null))
btnSave.Command.Execute(null);
}
}
private void btnBack_Click(object sender, RoutedEventArgs e)
{
flyRename.Hide();
}
}
}
<file_sep>/src/Money.UI/Views/DesignData/SummaryGroupViewModelProvider.cs
using Money.ViewModels;
using Neptuo.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
namespace Money.Views.DesignData
{
internal class SummaryGroupViewModelProvider : SummaryViewModel.IProvider
{
public Task<Price> GetTotalAmount()
{
return Task.FromResult(new Price(7800, "CZK"));
}
public Task ReplaceAsync(IList<SummaryCategoryViewModel> collection)
{
collection.Add(new SummaryCategoryViewModel()
{
Amount = new Price(2500, "CZK"),
Name = "Food",
Color = Colors.CadetBlue
});
collection.Add(new SummaryCategoryViewModel()
{
Amount = new Price(900, "CZK"),
Name = "Eating out",
Color = Colors.Brown
});
collection.Add(new SummaryCategoryViewModel()
{
Amount = new Price(4400, "CZK"),
Name = "Home",
Color = Colors.Gold
});
return Async.CompletedTask;
}
}
}
<file_sep>/src/Money.UI/Views/StateTriggers/MobileStateTrigger.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.System.Profile;
using Windows.UI.Xaml;
namespace Money.Views.StateTriggers
{
public class MobileStateTrigger : StateTriggerBase
{
public MobileStateTrigger()
{
string deviceFamily = AnalyticsInfo.VersionInfo.DeviceFamily;
bool isActive = deviceFamily == "Windows.Mobile";
SetActive(isActive);
}
}
}
<file_sep>/src/Money.UI/Services/IDomainFacade.cs
using Money.Services.Models;
using Neptuo;
using Neptuo.Activators;
using Neptuo.Models.Keys;
using Neptuo.Models.Repositories;
using Neptuo.Queries;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
namespace Money.Services
{
/// <summary>
/// A command facade for Money domain.
/// </summary>
public interface IDomainFacade
{
/// <summary>
/// Gets a factory for creating prices.
/// </summary>
IFactory<Price, decimal> PriceFactory { get; }
/// <summary>
/// Creates an category.
/// </summary>
/// <param name="name">A name of the category.</param>
/// <param name="color">A color of the category.</param>
/// <returns>Continuation task. The result contains a key of the new category.</returns>
Task<IKey> CreateCategoryAsync(string name, Color color);
/// <summary>
/// Creates an outcome.
/// </summary>
/// <param name="amount">An amount of the outcome.</param>
/// <param name="description">A description of the outcome.</param>
/// <param name="when">A date and time when the outcome occured.</param>
/// <returns>Continuation task. The result contains a key of the new outcome.</returns>
Task<IKey> CreateOutcomeAsync(Price amount, string description, DateTime when, IKey categoryKey);
/// <summary>
/// Adds <paramref name="categoryKey"/> to the <paramref name="outcomeKey"/>.
/// </summary>
/// <param name="outcomeKey">A key of the outcome to add category to.</param>
/// <param name="categoryKey">A key of the category to add outcome to.</param>
/// <returns>Continuation task.</returns>
Task AddOutcomeCategoryAsync(IKey outcomeKey, IKey categoryKey);
/// <summary>
/// Changes an <paramref name="amount"/> of the outcome with <paramref name="key"/>.
/// </summary>
/// <param name="outcomeKey">A key of the outcome to modify.</param>
/// <param name="amount">A new outcome value.</param>
/// <returns>Continuation task.</returns>
Task ChangeOutcomeAmount(IKey outcomeKey, Price amount);
/// <summary>
/// Changes a <paramref name="description"/> of the outcome with <paramref name="key"/>.
/// </summary>
/// <param name="outcomeKey">A key of the outcome to modify.</param>
/// <param name="description">A new description of the outcome.</param>
/// <returns>Continuation task.</returns>
Task ChangeOutcomeDescription(IKey outcomeKey, string description);
/// <summary>
/// Changes a <paramref name="when"/> of the outcome with <paramref name="key"/>.
/// </summary>
/// <param name="outcomeKey">A key of the outcome to modify.</param>
/// <param name="when">A date when the outcome occured.</param>
/// <returns>Continuation task.</returns>
Task ChangeOutcomeWhen(IKey outcomeKey, DateTime when);
/// <summary>
/// Deletes an outcome with <paramref name="outcomeKey"/>.
/// </summary>
/// <param name="outcomeKey">A key of the outcome to delete.</param>
/// <returns>Continuation task.</returns>
Task DeleteOutcome(IKey outcomeKey);
/// <summary>
/// Renames a category with a key <paramref name="categoryKey"/>.
/// </summary>
/// <param name="categoryKey">A key of the category to rename.</param>
/// <param name="newName">A new name of the category.</param>
/// <returns>Continuation task.</returns>
Task RenameCategory(IKey categoryKey, string newName);
/// <summary>
/// Changes a description of a category with a key <paramref name="categoryKey"/>.
/// </summary>
/// <param name="categoryKey">A key of the category.</param>
/// <param name="description">A new description of the category.</param>
/// <returns>Continuation task.</returns>
Task ChangeCategoryDescription(IKey categoryKey, string description);
/// <summary>
/// Changes a color of a category with a key <paramref name="categoryKey"/>.
/// </summary>
/// <param name="categoryKey">A key of the category.</param>
/// <param name="color">A new color of the category.</param>
/// <returns>Continuation task.</returns>
Task ChangeCategoryColor(IKey categoryKey, Color color);
}
}
<file_sep>/src/Money.UI/Views/Controls/MainMenuAppBarToggleButton.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel.Core;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace Money.Views.Controls
{
public sealed partial class MainMenuAppBarToggleButton : AppBarToggleButton, IDisposable
{
public MainMenuAppBarToggleButton()
{
InitializeComponent();
CoreWindow window = CoreWindow.GetForCurrentThread();
window.SizeChanged += OnWindowSizeChanged;
EnsureVisibility(window);
}
private void OnWindowSizeChanged(CoreWindow window, WindowSizeChangedEventArgs e)
{
EnsureVisibility(window);
}
private void EnsureVisibility(CoreWindow window)
{
Visibility = window.Bounds.Width < (double)Application.Current.Resources["MediumSize"]
? Visibility.Visible
: Visibility.Collapsed;
}
public void Dispose()
{
CoreWindow window = CoreWindow.GetForCurrentThread();
window.SizeChanged -= OnWindowSizeChanged;
}
}
}
<file_sep>/src/Money.UI/Views/Overview.xaml.cs
using Money.Services;
using Money.Services.Models;
using Money.Services.Models.Queries;
using Money.ViewModels;
using Money.ViewModels.Commands;
using Money.ViewModels.Navigation;
using Money.ViewModels.Parameters;
using Money.Views.Dialogs;
using Money.Views.Navigation;
using Neptuo.Models.Keys;
using Neptuo.Queries;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace Money.Views
{
[NavigationParameter(typeof(OverviewParameter))]
public sealed partial class Overview : Page
{
private readonly INavigator navigator = ServiceProvider.Navigator;
private readonly IQueryDispatcher queryDispatcher = ServiceProvider.QueryDispatcher;
private readonly IDomainFacade domainFacade = ServiceProvider.DomainFacade;
private MonthModel month;
private YearModel year;
private bool isDateSorted = true;
private bool isAmountSorted;
private bool isDescriptionSorted;
public OverviewViewModel ViewModel
{
get { return (OverviewViewModel)DataContext; }
set { DataContext = value; }
}
public Overview()
{
InitializeComponent();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
OverviewParameter parameter = (OverviewParameter)e.Parameter;
string categoryName = parameter.CategoryKey.IsEmpty
? "All"
: await queryDispatcher.QueryAsync(new GetCategoryName(parameter.CategoryKey));
object period = null;
IEnumerable<OutcomeOverviewModel> models = null;
if (parameter.Month != null)
{
month = parameter.Month;
period = parameter.Month;
models = await queryDispatcher.QueryAsync(new ListMonthOutcomeFromCategory(parameter.CategoryKey, parameter.Month));
}
if (parameter.Year != null)
{
year = parameter.Year;
period = parameter.Year;
models = await queryDispatcher.QueryAsync(new ListYearOutcomeFromCategory(parameter.CategoryKey, parameter.Year));
}
ViewModel = new OverviewViewModel(navigator, parameter.CategoryKey, categoryName, period);
if (models != null)
{
foreach (OutcomeOverviewModel model in models)
ViewModel.Items.Add(new OutcomeOverviewViewModel(model));
}
}
private void mfiSortDate_Click(object sender, RoutedEventArgs e)
{
if (isDateSorted)
{
ViewModel.Items.SortDescending(i => i.When);
isDateSorted = false;
}
else
{
ViewModel.Items.Sort(i => i.When);
isDateSorted = true;
}
isAmountSorted = false;
isDescriptionSorted = false;
}
private void mfiSortAmount_Click(object sender, RoutedEventArgs e)
{
if (isAmountSorted)
{
ViewModel.Items.SortDescending(i => i.Amount.Value);
isAmountSorted = false;
}
else
{
ViewModel.Items.Sort(i => i.Amount.Value);
isAmountSorted = true;
}
isDateSorted = false;
isDescriptionSorted = false;
}
private void mfiSortDescription_Click(object sender, RoutedEventArgs e)
{
if (isDescriptionSorted)
{
ViewModel.Items.SortDescending(i => i.Description);
isDescriptionSorted = false;
}
else
{
ViewModel.Items.Sort(i => i.Description);
isDescriptionSorted = true;
}
isAmountSorted = false;
isDateSorted = false;
}
private void lvwItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
OutcomeOverviewViewModel selected = (OutcomeOverviewViewModel)e.AddedItems.FirstOrDefault();
foreach (OutcomeOverviewViewModel viewModel in ViewModel.Items)
viewModel.IsSelected = selected == viewModel;
}
private async void btnAmount_Click(object sender, RoutedEventArgs e)
{
OutcomeOverviewViewModel viewModel = (OutcomeOverviewViewModel)((Button)sender).DataContext;
OutcomeAmount dialog = new OutcomeAmount();
dialog.Value = (double)viewModel.Amount.Value;
ContentDialogResult result = await dialog.ShowAsync();
decimal newValue = (decimal)dialog.Value;
if (result == ContentDialogResult.Primary && newValue != viewModel.Amount.Value)
{
Price newAmount = new Price(newValue, viewModel.Amount.Currency);
await domainFacade.ChangeOutcomeAmount(viewModel.Key, newAmount);
viewModel.Amount = newAmount;
}
}
private async void btnDescription_Click(object sender, RoutedEventArgs e)
{
OutcomeOverviewViewModel viewModel = (OutcomeOverviewViewModel)((Button)sender).DataContext;
OutcomeDescription dialog = new OutcomeDescription();
dialog.Value = viewModel.Description;
ContentDialogResult result = await dialog.ShowAsync();
if (result == ContentDialogResult.Primary && dialog.Value != viewModel.Description)
{
await domainFacade.ChangeOutcomeDescription(viewModel.Key, dialog.Value);
viewModel.Description = dialog.Value;
}
}
private async void btnWhen_Click(object sender, RoutedEventArgs e)
{
OutcomeOverviewViewModel viewModel = (OutcomeOverviewViewModel)((Button)sender).DataContext;
OutcomeWhen dialog = new OutcomeWhen();
dialog.Value = viewModel.When;
ContentDialogResult result = await dialog.ShowAsync();
if (result == ContentDialogResult.Primary && dialog.Value != viewModel.When)
{
await domainFacade.ChangeOutcomeWhen(viewModel.Key, dialog.Value);
viewModel.When = dialog.Value;
if (month != null && (dialog.Value.Year != month.Year || dialog.Value.Month != month.Month))
ViewModel.Items.Remove(viewModel);
if (year != null && (dialog.Value.Year != year.Year))
ViewModel.Items.Remove(viewModel);
}
}
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
OutcomeOverviewViewModel viewModel = (OutcomeOverviewViewModel)((Button)sender).DataContext;
navigator
.Message(String.Format("Do you realy want to delete an outcome for '{0}' from '{1}'?", viewModel.Amount, viewModel.When))
.Button("Yes", new DeleteOutcomeCommand(domainFacade, viewModel.Key).AddExecuted(() => ViewModel.Items.Remove(viewModel)))
.ButtonClose("No")
.Show();
}
}
}
<file_sep>/src/Money.UI/Views/Template.xaml.cs
using Money.ViewModels;
using Money.ViewModels.Navigation;
using Money.ViewModels.Parameters;
using Money.Views.Controls;
using Neptuo;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace Money.Views
{
public sealed partial class Template : Page
{
private readonly INavigator navigator = ServiceProvider.Navigator;
private readonly List<MenuItemViewModel> menuItems;
public Frame ContentFrame
{
get { return frmContent; }
}
public MainMenu MainMenu
{
get { return mnuMain; }
}
public bool IsMainMenuOpened
{
get { return (bool)GetValue(IsMainMenuOpenedProperty); }
set { SetValue(IsMainMenuOpenedProperty, value); }
}
public static readonly DependencyProperty IsMainMenuOpenedProperty = DependencyProperty.Register(
"IsMainMenuOpened",
typeof(bool),
typeof(Template),
new PropertyMetadata(false)
);
public Template()
{
InitializeComponent();
menuItems = new List<MenuItemViewModel>()
{
new MenuItemViewModel("Pie Chart", "\uEB05", new SummaryParameter(SummaryViewType.PieChart)) { Group = "Summary" },
new MenuItemViewModel("Bar Graph", "\uE94C", new SummaryParameter(SummaryViewType.BarGraph)) { Group = "Summary" },
new MenuItemViewModel("Categories", "\uE8FD", new CategoryListParameter()) { Group = "Manage" },
new MenuItemViewModel("Currencies", "\uE1D0", new EmptyParameter()) { Group = "Manage" },
new MenuItemViewModel("Settings", "\uE713", new EmptyParameter()) { Group = "Settings" },
};
MenuItemsSource.Source = menuItems.GroupBy(i => i.Group);
// TODO: Remove after making the synchronization of selected item.
mnuMain.SelectedIndex = 1;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
navigator
.Open(e.Parameter)
.Show();
}
private void OnMainMenuItemInvoked(object sender, ListViewItem e)
{
MenuItemViewModel item = (MenuItemViewModel)((MainMenu)sender).ItemFromContainer(e);
navigator
.Open(item.Parameter)
.Show();
}
/// <summary>
/// Updates currently active/selected menu item to match <paramref name="parameter"/>.
/// </summary>
/// <param name="parameter">A parameter to by selected.</param>
public void UpdateActiveMenuItem(object parameter)
{
Ensure.NotNull(parameter, "parameter");
foreach (MenuItemViewModel item in menuItems)
{
if (item.Parameter.Equals(parameter))
{
mnuMain.SelectedItem = item;
return;
}
}
Type parameterType = parameter.GetType();
foreach (MenuItemViewModel item in menuItems)
{
if (item.Parameter.GetType() == parameterType)
{
mnuMain.SelectedItem = item;
return;
}
}
mnuMain.SelectedItem = null;
}
public void ShowLoading()
{
loaContent.IsActive = true;
}
public void HideLoading()
{
loaContent.IsActive = false;
}
}
}
<file_sep>/src/Money.UI/Bootstrap/DefaultDomainFacade.cs
using Money.Services;
using Money.Services.Models;
using Neptuo;
using Neptuo.Activators;
using Neptuo.Models.Keys;
using Neptuo.Models.Repositories;
using Neptuo.Queries;
using Neptuo.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
namespace Money.Bootstrap
{
/// <summary>
/// A default implementation of <see cref="IDomainFacade"/>.
/// </summary>
internal class DefaultDomainFacade : IDomainFacade
{
private readonly IRepository<Outcome, IKey> outcomeRepository;
private readonly IRepository<Category, IKey> categoryRepository;
public IFactory<Price, decimal> PriceFactory { get; private set; }
public DefaultDomainFacade(
IRepository<Outcome, IKey> outcomeRepository,
IRepository<Category, IKey> categoryRepository,
IFactory<Price, decimal> priceFactory)
{
Ensure.NotNull(outcomeRepository, "outcomeRepository");
Ensure.NotNull(categoryRepository, "categoryRepository");
Ensure.NotNull(priceFactory, "priceFactory");
this.outcomeRepository = outcomeRepository;
this.categoryRepository = categoryRepository;
PriceFactory = priceFactory;
}
public Task<IKey> CreateCategoryAsync(string name, Color color)
{
return Task.Factory.StartNew(() =>
{
Category model = new Category(name, color);
categoryRepository.Save(model);
return model.Key;
});
}
public Task<IKey> CreateOutcomeAsync(Price amount, string description, DateTime when, IKey categoryKey)
{
return Task.Factory.StartNew(() =>
{
Outcome model = new Outcome(amount, description, when, categoryKey);
outcomeRepository.Save(model);
return model.Key;
});
}
public Task AddOutcomeCategoryAsync(IKey outcomeKey, IKey categoryKey)
{
return Task.Factory.StartNew(() =>
{
Outcome model = outcomeRepository.Find(outcomeKey);
model.AddCategory(categoryKey);
outcomeRepository.Save(model);
});
}
public Task RenameCategory(IKey categoryKey, string newName)
{
return Task.Factory.StartNew(() =>
{
Category category = categoryRepository.Get(categoryKey);
category.Rename(newName);
categoryRepository.Save(category);
});
}
public Task ChangeCategoryDescription(IKey categoryKey, string description)
{
return Task.Factory.StartNew(() =>
{
Category category = categoryRepository.Get(categoryKey);
category.ChangeDescription(description);
categoryRepository.Save(category);
});
}
public Task ChangeCategoryColor(IKey categoryKey, Color color)
{
return Task.Factory.StartNew(() =>
{
Category category = categoryRepository.Get(categoryKey);
category.ChangeColor(color);
categoryRepository.Save(category);
});
}
public Task ChangeOutcomeAmount(IKey outcomeKey, Price amount)
{
return Task.Factory.StartNew(() =>
{
Outcome outcome = outcomeRepository.Get(outcomeKey);
outcome.ChangeAmount(amount);
outcomeRepository.Save(outcome);
});
}
public Task ChangeOutcomeDescription(IKey outcomeKey, string description)
{
return Task.Factory.StartNew(() =>
{
Outcome outcome = outcomeRepository.Get(outcomeKey);
outcome.ChangeDescription(description);
outcomeRepository.Save(outcome);
});
}
public Task ChangeOutcomeWhen(IKey outcomeKey, DateTime when)
{
return Task.Factory.StartNew(() =>
{
Outcome outcome = outcomeRepository.Get(outcomeKey);
outcome.ChangeWhen(when);
outcomeRepository.Save(outcome);
});
}
public Task DeleteOutcome(IKey outcomeKey)
{
return Task.Factory.StartNew(() =>
{
Outcome outcome = outcomeRepository.Get(outcomeKey);
outcome.Delete();
outcomeRepository.Save(outcome);
});
}
}
}
<file_sep>/src/Money.UI/ViewModels/Commands/NavigateCommand.cs
using Money.ViewModels.Navigation;
using Neptuo;
using Neptuo.Observables.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace Money.ViewModels.Commands
{
public class NavigateCommand : Command
{
private readonly INavigator navigator;
private readonly object parameter;
public NavigateCommand(INavigator navigator, object parameter)
{
Ensure.NotNull(navigator, "navigator");
Ensure.NotNull(parameter, "parameter");
this.navigator = navigator;
this.parameter = parameter;
}
public override bool CanExecute()
{
return true;
}
public override void Execute()
{
navigator
.Open(parameter)
.Show();
}
}
}
<file_sep>/src/Money.UI/Views/Controls/Loading.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace Money.Views.Controls
{
public sealed partial class Loading : UserControl
{
public bool IsActive
{
get { return (bool)GetValue(IsActiveProperty); }
set { SetValue(IsActiveProperty, value); }
}
public static readonly DependencyProperty IsActiveProperty = DependencyProperty.Register(
"IsActive",
typeof(bool),
typeof(Loading),
new PropertyMetadata(false, OnIsActiveChanged)
);
private static void OnIsActiveChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Loading control = (Loading)d;
control.Visibility = control.IsActive ? Visibility.Visible : Visibility.Collapsed;
}
public Loading()
{
InitializeComponent();
}
}
}
<file_sep>/src/Money.UI/ViewModels/OverviewViewModel.cs
using Money.ViewModels.Commands;
using Money.ViewModels.Navigation;
using Money.ViewModels.Parameters;
using Neptuo;
using Neptuo.Models.Keys;
using Neptuo.Observables.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Money.ViewModels
{
/// <summary>
/// A view model for category outcome overview.
/// </summary>
public class OverviewViewModel : ViewModel
{
/// <summary>
/// Gets a key of the category.
/// </summary>
public IKey Key { get; private set; }
/// <summary>
/// Gets a name of the category.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets a period displayed (year or month).
/// </summary>
public object Period { get; private set; }
/// <summary>
/// Gets a collection of outcome models.
/// </summary>
public SortableObservableCollection<OutcomeOverviewViewModel> Items { get; private set; }
/// <summary>
/// Gets a command for editing current category.
/// </summary>
public ICommand EditCategory { get; private set; }
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="navigator">An instance of the navigator.</param>
/// <param name="key">A key of the category</param>
/// <param name="name">A name of the category.</param>
/// <param name="period">A period displayed (year or month).</param>
public OverviewViewModel(INavigator navigator, IKey key, string name, object period)
: base(navigator, key)
{
Ensure.NotNull(key, "key");
Key = key;
Name = name;
Period = period;
Items = new SortableObservableCollection<OutcomeOverviewViewModel>();
if (!key.IsEmpty)
EditCategory = new NavigateCommand(navigator, new CategoryListParameter(key));
}
}
}
<file_sep>/src/Money.UI/Views/DesignData/ViewModelLocator.cs
using Money.Services;
using Money.Services.Models;
using Money.Services.Tiles;
using Money.ViewModels;
using Money.ViewModels.Navigation;
using Neptuo;
using Neptuo.Models.Keys;
using Neptuo.Queries;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.UI;
using Windows.UI.Xaml.Controls;
namespace Money.Views.DesignData
{
internal class ViewModelLocator
{
private IQueryDispatcher queryDispatcher;
public IQueryDispatcher QueryDispatcher
{
get
{
if (queryDispatcher == null)
queryDispatcher = new QueryDispatcher();
return queryDispatcher;
}
}
private IDomainFacade domainFacade;
public IDomainFacade DomainFacade
{
get
{
if (domainFacade == null)
domainFacade = new DomainFacade();
return domainFacade;
}
}
private INavigator navigator;
public INavigator Navigator
{
get
{
if (navigator == null)
navigator = new Navigator();
return navigator;
}
}
private GroupViewModel group;
public GroupViewModel Group
{
get
{
if (group == null)
{
group = new GroupViewModel(ServiceProvider.Navigator);
group.Add("August", null);
group.Add("September", null);
group.Add("October", null);
group.Add("December", null);
}
return group;
}
}
private SummaryViewModel summary;
public SummaryViewModel Summary
{
get
{
if (summary == null)
{
summary = new SummaryViewModel(ServiceProvider.Navigator, ServiceProvider.QueryDispatcher);
summary.Items.Add(new SummaryCategoryViewModel()
{
Name = "Food",
Color = Colors.Olive,
Amount = new Price(9540, "CZK"),
});
summary.Items.Add(new SummaryCategoryViewModel()
{
Name = "Eating Out",
Color = Colors.DarkRed,
Amount = new Price(3430, "CZK"),
});
summary.Items.Add(new SummaryCategoryViewModel()
{
Name = "Home",
Color = Colors.RosyBrown,
Amount = new Price(950, "CZK"),
});
summary.Items.Add(new SummaryTotalViewModel(new Price(13520, "CZK")));
summary.IsLoading = false;
}
return summary;
}
}
private OverviewViewModel overview;
public OverviewViewModel Overview
{
get
{
if (overview == null)
{
overview = new OverviewViewModel(ServiceProvider.Navigator, KeyFactory.Create(typeof(Category)), "Food", new MonthModel(2016, 11));
overview.Items.Add(new OutcomeOverviewViewModel(new OutcomeOverviewModel(KeyFactory.Create(typeof(Outcome)), new Price(1250, "CZK"), new DateTime(2016, 11, 05), "Saturday's buy on market")));
overview.Items.Add(new OutcomeOverviewViewModel(new OutcomeOverviewModel(KeyFactory.Create(typeof(Outcome)), new Price(350, "CZK"), new DateTime(2016, 11, 14), "Cheese")));
overview.Items.Add(new OutcomeOverviewViewModel(new OutcomeOverviewModel(KeyFactory.Create(typeof(Outcome)), new Price(400, "CZK"), new DateTime(2016, 11, 15), "Vine")));
overview.Items.Add(new OutcomeOverviewViewModel(new OutcomeOverviewModel(KeyFactory.Create(typeof(Outcome)), new Price(550, "CZK"), new DateTime(2016, 11, 15), "Pasta, pasta, pasta")));
overview.Items[2].IsSelected = true;
}
return overview;
}
}
private OutcomeViewModel createOutcome;
public OutcomeViewModel CreateOutcome
{
get
{
if (createOutcome == null)
{
createOutcome = new OutcomeViewModel(ServiceProvider.Navigator, ServiceProvider.DomainFacade);
createOutcome.Amount = 5400;
createOutcome.Description = "New home PC motherboard";
createOutcome.Categories.Add(new CategoryModel(KeyFactory.Create(typeof(Category)), "Food", "Making out loved foods from igredients", Colors.CadetBlue));
createOutcome.Categories.Add(new CategoryModel(KeyFactory.Create(typeof(Category)), "Eating out", "When we are lay and let others to feed us", Colors.Brown));
createOutcome.Categories.Add(new CategoryModel(KeyFactory.Create(typeof(Category)), "Home", "Manly stuff", Colors.Gold));
}
return createOutcome;
}
}
private CategoryListViewModel categoryList;
public CategoryListViewModel CategoryList
{
get
{
if (categoryList == null)
{
categoryList = new CategoryListViewModel(ServiceProvider.DomainFacade);
categoryList.Items.Add(new CategoryEditViewModel(ServiceProvider.DomainFacade, KeyFactory.Create(typeof(Category)), "Food", "Making out loved foods from igredients", Colors.CadetBlue));
categoryList.Items.Add(new CategoryEditViewModel(ServiceProvider.DomainFacade, KeyFactory.Create(typeof(Category)), "Eating out", "When we are lazy and let others to feed us", Colors.Brown) { IsSelected = true });
categoryList.Items.Add(new CategoryEditViewModel(ServiceProvider.DomainFacade, KeyFactory.Create(typeof(Category)), "Home", "Manly stuff", Colors.Gold));
}
return categoryList;
}
}
private CategoryEditViewModel categoryEdit;
public CategoryEditViewModel CategoryEdit
{
get
{
if (categoryEdit == null)
{
categoryEdit = new CategoryEditViewModel(ServiceProvider.DomainFacade, KeyFactory.Create(typeof(Category)), "Eating out", "When we are lazy and let others to feed us", Colors.Brown);
categoryEdit.IsSelected = true;
}
return categoryEdit;
}
}
private MigrateViewModel migrate;
public MigrateViewModel Migrate
{
get
{
if (migrate == null)
{
migrate = new MigrateViewModel(new UpgradeService());
migrate.StartAsync();
}
return migrate;
}
}
public ViewModelLocator()
{
if (DesignMode.DesignModeEnabled)
{
ServiceProvider.QueryDispatcher = QueryDispatcher;
ServiceProvider.DomainFacade = DomainFacade;
ServiceProvider.Navigator = Navigator;
ServiceProvider.TileService = new TileService();
}
}
}
}
<file_sep>/src/Money.UI/ServiceProvider.cs
using Money.Services;
using Money.Services.Tiles;
using Money.ViewModels.Navigation;
using Neptuo.Migrations;
using Neptuo.Queries;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Money
{
internal static class ServiceProvider
{
public static IQueryDispatcher QueryDispatcher { get; set; }
public static IDomainFacade DomainFacade { get; set; }
public static INavigator Navigator { get; set; }
public static IUpgradeService UpgradeService { get; set; }
public static TileService TileService { get; set; }
}
}
<file_sep>/src/Money.UI/Views/Dialogs/OutcomeCreate.cs
using Money.Services;
using Money.ViewModels.Parameters;
using Money.Views.Navigation;
using Neptuo.Activators;
using Neptuo.Models.Keys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
namespace Money.Views.Dialogs
{
[NavigationParameter(typeof(OutcomeParameter))]
public class OutcomeCreate : IWizard
{
private readonly IDomainFacade domainFacade = ServiceProvider.DomainFacade;
public async Task ShowAsync(object context)
{
OutcomeParameter parameter = (OutcomeParameter)context;
decimal amount = 0;
string description = String.Empty;
DateTime when = DateTime.Now;
IKey categoryKey = parameter.CategoryKey;
OutcomeAmount amountDialog = new OutcomeAmount();
amountDialog.PrimaryButtonText = "Next";
if (parameter.CategoryKey.IsEmpty)
amountDialog.SecondaryButtonText = String.Empty;
else
amountDialog.SecondaryButtonText = "Create today";
if (parameter.Amount != null)
amountDialog.Value = (double)parameter.Amount.Value;
ContentDialogResult result = await amountDialog.ShowAsync();
if (result == ContentDialogResult.None)
return;
amount = (decimal)amountDialog.Value;
if (result == ContentDialogResult.Primary)
{
OutcomeDescription descriptionDialog = new OutcomeDescription();
descriptionDialog.PrimaryButtonText = "Next";
if (parameter.CategoryKey.IsEmpty)
descriptionDialog.SecondaryButtonText = String.Empty;
else
descriptionDialog.SecondaryButtonText = "Create today";
result = await descriptionDialog.ShowAsync();
if (result == ContentDialogResult.None && !descriptionDialog.IsEnterPressed)
return;
description = descriptionDialog.Value;
if (result == ContentDialogResult.Primary || descriptionDialog.IsEnterPressed)
{
CategoryPicker categoryDialog = new CategoryPicker();
categoryDialog.PrimaryButtonText = "Next";
categoryDialog.SecondaryButtonText = "Create today";
if (!parameter.CategoryKey.IsEmpty)
categoryDialog.SelectedKey = parameter.CategoryKey;
result = await categoryDialog.ShowAsync();
if (result == ContentDialogResult.None)
return;
categoryKey = categoryDialog.SelectedKey;
if (result == ContentDialogResult.Primary)
{
OutcomeWhen whenDialog = new OutcomeWhen();
whenDialog.PrimaryButtonText = "Create";
whenDialog.SecondaryButtonText = "Cancel";
whenDialog.Value = when;
result = await whenDialog.ShowAsync();
if (result != ContentDialogResult.Primary)
return;
when = whenDialog.Value;
}
}
}
await domainFacade.CreateOutcomeAsync(
domainFacade.PriceFactory.Create(amount),
description,
when,
categoryKey
);
//OutcomeCreatedGuidePost nextDialog = new OutcomeCreatedGuidePost();
//await nextDialog.ShowAsync();
}
}
}
<file_sep>/src/Money.UI/ViewModels/CategoryEditViewModel.cs
using Money.Services;
using Money.ViewModels.Commands;
using Neptuo;
using Neptuo.Models.Keys;
using Neptuo.Observables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.UI;
using Windows.UI.Xaml.Media;
namespace Money.ViewModels
{
public class CategoryEditViewModel : ObservableObject
{
public IKey Key { get; internal set; }
private string name;
public string Name
{
get { return name; }
set
{
if (name != value)
{
name = value;
RaisePropertyChanged();
}
}
}
private string description;
public string Description
{
get { return description; }
set
{
if (description != value)
{
description = value;
RaisePropertyChanged();
}
}
}
private Color color;
public Color Color
{
get { return color; }
set
{
if (color != value)
{
color = value;
RaisePropertyChanged();
RaisePropertyChanged(nameof(ColorBrush));
}
}
}
public Brush ColorBrush
{
get { return new SolidColorBrush(Color); }
}
private bool isSelected;
public bool IsSelected
{
get { return isSelected; }
set
{
if (isSelected != value)
{
isSelected = value;
RaisePropertyChanged();
}
}
}
public ICommand Rename { get; private set; }
public ICommand ChangeColor { get; private set; }
public CategoryEditViewModel(IDomainFacade domainFacade, IKey key)
{
Ensure.NotNull(domainFacade, "domainFacade");
Ensure.NotNull(key, "key");
Key = key;
CreateCommands(domainFacade);
}
public CategoryEditViewModel(IDomainFacade domainFacade, IKey key, string name, string description, Color color)
{
Ensure.NotNull(domainFacade, "domainFacade");
Ensure.Condition.NotEmptyKey(key);
Key = key;
Name = name;
Description = description;
Color = color;
CreateCommands(domainFacade);
}
private void CreateCommands(IDomainFacade domainFacade)
{
Rename = new CategoryRenameCommand(domainFacade, this);
ChangeColor = new CategoryChangeColorCommand(domainFacade, this);
}
}
}
<file_sep>/src/Money.UI/Services/Models/CategoryModel.cs
using Neptuo;
using Neptuo.Models.Keys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
namespace Money.Services.Models
{
/// <summary>
/// A model of a outcome or income category.
/// </summary>
public class CategoryModel
{
/// <summary>
/// Gets a key of the category.
/// </summary>
public IKey Key { get; private set; }
/// <summary>
/// Gets a name of the category.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets a description of the category.
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Gets a color of the category.
/// </summary>
public Color Color { get; private set; }
public CategoryModel(IKey key, string name, string description, Color color)
{
Ensure.Condition.NotEmptyKey(key);
Key = key;
Name = name;
Description = description;
Color = color;
}
}
}
<file_sep>/src/Money.UI/Services/Models/Builders/CategoryBuilder.cs
using Microsoft.EntityFrameworkCore;
using Money.Data;
using Money.Events;
using Money.Services.Models.Queries;
using Neptuo;
using Neptuo.Events.Handlers;
using Neptuo.Models.Keys;
using Neptuo.Queries.Handlers;
using Neptuo.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI;
namespace Money.Services.Models.Builders
{
/// <summary>
/// A builder for querying categories.
/// </summary>
public class CategoryBuilder :
IEventHandler<CategoryCreated>,
IEventHandler<CategoryRenamed>,
IEventHandler<CategoryDescriptionChanged>,
IEventHandler<CategoryColorChanged>,
IQueryHandler<ListAllCategory, List<CategoryModel>>
{
public Task<List<CategoryModel>> HandleAsync(ListAllCategory query)
{
List<CategoryModel> result = new List<CategoryModel>();
using (ReadModelContext db = new ReadModelContext())
{
return db.Categories
.OrderBy(c => c.Name)
.Select(e => e.ToModel())
.ToListAsync();
}
}
public Task HandleAsync(CategoryCreated payload)
{
using (ReadModelContext db = new ReadModelContext())
{
db.Categories.Add(new CategoryEntity(new CategoryModel(
payload.AggregateKey,
payload.Name,
null,
payload.Color
)));
return db.SaveChangesAsync();
}
}
public Task HandleAsync(CategoryRenamed payload)
{
using (ReadModelContext db = new ReadModelContext())
{
CategoryEntity entity = db.Categories.Find(payload.AggregateKey.AsGuidKey().Guid);
entity.Name = payload.NewName;
return db.SaveChangesAsync();
}
}
public Task HandleAsync(CategoryDescriptionChanged payload)
{
using (ReadModelContext db = new ReadModelContext())
{
CategoryEntity entity = db.Categories.Find(payload.AggregateKey.AsGuidKey().Guid);
entity.Description = payload.Description;
return db.SaveChangesAsync();
}
}
public Task HandleAsync(CategoryColorChanged payload)
{
using (ReadModelContext db = new ReadModelContext())
{
CategoryEntity entity = db.Categories.Find(payload.AggregateKey.AsGuidKey().Guid);
entity.SetColor(payload.Color);
return db.SaveChangesAsync();
}
}
}
}
<file_sep>/src/Money.UI/Views/DesignData/DomainFacade.cs
using Money.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Neptuo.Activators;
using Money.Services.Models;
using Neptuo.Models.Keys;
using Neptuo.Queries;
using Windows.UI;
namespace Money.Views.DesignData
{
internal class DomainFacade : IDomainFacade
{
public IFactory<Price, decimal> PriceFactory
{
get { throw new NotImplementedException(); }
}
public Task AddOutcomeCategoryAsync(IKey outcomeKey, IKey categoryKey)
{
throw new NotImplementedException();
}
public Task ChangeCategoryColor(IKey categoryKey, Color color)
{
throw new NotImplementedException();
}
public Task ChangeCategoryDescription(IKey categoryKey, string description)
{
throw new NotImplementedException();
}
public Task ChangeOutcomeAmount(IKey outcomeKey, Price amount)
{
throw new NotImplementedException();
}
public Task ChangeOutcomeDescription(IKey outcomeKey, string description)
{
throw new NotImplementedException();
}
public Task ChangeOutcomeWhen(IKey outcomeKey, DateTime when)
{
throw new NotImplementedException();
}
public Task<IKey> CreateCategoryAsync(string name, Color color)
{
throw new NotImplementedException();
}
public Task<IKey> CreateOutcomeAsync(Price amount, string description, DateTime when, IKey categoryKey)
{
throw new NotImplementedException();
}
public Task DeleteOutcome(IKey outcomeKey)
{
throw new NotImplementedException();
}
public Task<TOutput> QueryAsync<TOutput>(IQuery<TOutput> query)
{
throw new NotImplementedException();
}
public Task RenameCategory(IKey categoryKey, string newName)
{
throw new NotImplementedException();
}
}
}
<file_sep>/src/Money.UI/Views/Controls/SummaryContent.xaml.cs
using Money.Services.Models;
using Money.ViewModels;
using Money.ViewModels.Navigation;
using Money.ViewModels.Parameters;
using Neptuo;
using Neptuo.Models.Keys;
using Neptuo.Queries;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace Money.Views.Controls
{
/// <summary>
/// User control containing month or year summary of outcomes.
/// </summary>
public sealed partial class SummaryContent : UserControl
{
private readonly INavigator navigator = ServiceProvider.Navigator;
private readonly IQueryDispatcher queryDispatcher = ServiceProvider.QueryDispatcher;
/// <summary>
/// [Internal]
/// Gets or sets a view model.
/// </summary>
public SummaryViewModel ViewModel
{
get { return (SummaryViewModel)grdMain.DataContext; }
private set { grdMain.DataContext = value; }
}
/// <summary>
/// Gets or sets a prefered view type.
/// </summary>
public SummaryViewType PreferedViewType
{
get { return (SummaryViewType)GetValue(PreferedViewTypeProperty); }
set { SetValue(PreferedViewTypeProperty, value); }
}
/// <summary>
/// A dependency property for prefered view type.
/// </summary>
public static readonly DependencyProperty PreferedViewTypeProperty = DependencyProperty.Register(
"PreferedViewType",
typeof(SummaryViewType),
typeof(SummaryContent),
new PropertyMetadata(SummaryViewType.BarGraph, OnPreferedViewTypeChanged)
);
private static void OnPreferedViewTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SummaryContent control = (SummaryContent)d;
switch (control.PreferedViewType)
{
case SummaryViewType.PieChart:
control.IsPieChartPrefered = true;
control.IsBarGraphPrefered = false;
break;
case SummaryViewType.BarGraph:
control.IsPieChartPrefered = false;
control.IsBarGraphPrefered = true;
break;
default:
throw Ensure.Exception.NotSupported(control.PreferedViewType.ToString());
}
}
public bool IsPieChartPrefered
{
get { return (bool)GetValue(IsPieChartPreferedProperty); }
set { SetValue(IsPieChartPreferedProperty, value); }
}
public static readonly DependencyProperty IsPieChartPreferedProperty = DependencyProperty.Register(
"IsPieChartPrefered",
typeof(bool),
typeof(SummaryContent),
new PropertyMetadata(false)
);
public bool IsBarGraphPrefered
{
get { return (bool)GetValue(IsBarGraphPreferedProperty); }
set { SetValue(IsBarGraphPreferedProperty, value); }
}
public static readonly DependencyProperty IsBarGraphPreferedProperty = DependencyProperty.Register(
"IsBarGraphPrefered",
typeof(bool),
typeof(SummaryContent),
new PropertyMetadata(false)
);
public object SelectedItem
{
get { return (object)GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register(
"SelectedItem",
typeof(object),
typeof(SummaryContent),
new PropertyMetadata(null, OnSelectedItemChanged)
);
private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SummaryContent control = (SummaryContent)d;
control.OnSelectedItemChanged(e);
}
public SortDescriptor<SummarySortType> SortDescriptor
{
get { return (SortDescriptor<SummarySortType>)GetValue(SortDescriptorProperty); }
set { SetValue(SortDescriptorProperty, value); }
}
public static readonly DependencyProperty SortDescriptorProperty = DependencyProperty.Register(
"SortDescriptor",
typeof(SortDescriptor<SummarySortType>),
typeof(SummaryContent),
new PropertyMetadata(null, OnSortDescriptorChanged)
);
private static void OnSortDescriptorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SummaryContent control = (SummaryContent)d;
if (control.SortDescriptor != null)
{
switch (control.SortDescriptor.Type)
{
case SummarySortType.ByAmount:
if (control.SortDescriptor.Direction == SortDirection.Ascending)
control.ViewModel.Items.Sort(items => items.OfType<SummaryCategoryViewModel>().OrderBy(i => i.AmountValue));
else
control.ViewModel.Items.Sort(items => items.OfType<SummaryCategoryViewModel>().OrderByDescending(i => i.AmountValue));
break;
case SummarySortType.ByCategory:
if (control.SortDescriptor.Direction == SortDirection.Ascending)
control.ViewModel.Items.Sort(items => items.OfType<SummaryCategoryViewModel>().OrderBy(i => i.Name));
else
control.ViewModel.Items.Sort(items => items.OfType<SummaryCategoryViewModel>().OrderByDescending(i => i.Name));
break;
}
}
}
public SummaryContent()
{
InitializeComponent();
ViewModel = new SummaryViewModel(navigator, queryDispatcher);
}
private void OnSelectedItemChanged(DependencyPropertyChangedEventArgs e)
{
MonthModel month = SelectedItem as MonthModel;
if (month != null)
{
ViewModel.Month = month;
return;
}
YearModel year = SelectedItem as YearModel;
if (year != null)
{
throw new NotImplementedException();
}
throw Ensure.Exception.NotSupported();
}
private void lvwBarGraph_ItemClick(object sender, ItemClickEventArgs e)
{
ISummaryItemViewModel item = (ISummaryItemViewModel)e.ClickedItem;
OpenOverview(item.CategoryKey);
}
private void OpenOverview(IKey categoryKey)
{
OverviewParameter parameter = null;
MonthModel month = SelectedItem as MonthModel;
if (month != null)
parameter = new OverviewParameter(categoryKey, month);
YearModel year = SelectedItem as YearModel;
if (year != null)
parameter = new OverviewParameter(categoryKey, year);
navigator
.Open(parameter)
.Show();
}
}
}
<file_sep>/src/Money.UI/Services/Models/CategoryWIthAmountModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Neptuo.Models.Keys;
using Windows.UI;
namespace Money.Services.Models
{
public class CategoryWithAmountModel : CategoryModel
{
public Price TotalAmount { get; private set; }
public CategoryWithAmountModel(IKey key, string name, string description, Color color, Price totalAmount)
: base(key, name, description, color)
{
TotalAmount = totalAmount;
}
}
}
<file_sep>/src/Money.UI/ViewModels/CategoryListViewModel.cs
using Money.Services;
using Neptuo;
using Neptuo.Observables;
using Neptuo.Observables.Collections;
using Neptuo.Observables.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.UI;
namespace Money.ViewModels
{
public class CategoryListViewModel : ObservableObject
{
private readonly IDomainFacade domainFacade;
public ObservableCollection<CategoryEditViewModel> Items { get; private set; }
public ICommand New { get; private set; }
public CategoryListViewModel(IDomainFacade domainFacade)
{
Ensure.NotNull(domainFacade, "domainFacade");
this.domainFacade = domainFacade;
Items = new ObservableCollection<CategoryEditViewModel>();
New = new DelegateCommand(NewExecuted);
}
private void NewExecuted()
{
Items.Add(new CategoryEditViewModel(domainFacade, KeyFactory.Empty(typeof(Category))));
}
}
}
<file_sep>/src/Money.UI/Data/CategoryEntity.cs
using Money.Services.Models;
using Neptuo;
using Neptuo.Models.Keys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
namespace Money.Data
{
internal class CategoryEntity
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public byte ColorA { get; set; }
public byte ColorR { get; set; }
public byte ColorG { get; set; }
public byte ColorB { get; set; }
public IList<OutcomeCategoryEntity> Outcomes { get; set; }
public CategoryEntity()
{ }
public CategoryEntity(CategoryModel model)
{
Id = model.Key.AsGuidKey().Guid;
Name = model.Name;
Description = model.Description;
SetColor(model.Color);
}
public void SetColor(Color color)
{
ColorA = color.A;
ColorR = color.R;
ColorG = color.G;
ColorB = color.B;
}
public CategoryModel ToModel()
{
return new CategoryModel(
GuidKey.Create(Id, KeyFactory.Empty(typeof(Category)).Type),
Name,
Description,
Color.FromArgb(ColorA, ColorR, ColorG, ColorB)
);
}
}
}
<file_sep>/src/Money.UI/Data/ReadModelContext.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace Money.Data
{
internal class ReadModelContext : DbContext
{
public DbSet<CategoryEntity> Categories { get; set; }
public DbSet<OutcomeEntity> Outcomes { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Filename=ReadModel.db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<OutcomeCategoryEntity>()
.HasKey(t => new { t.OutcomeId, t.CategoryId });
modelBuilder.Entity<OutcomeCategoryEntity>()
.HasOne(pt => pt.Outcome)
.WithMany(p => p.Categories)
.HasForeignKey(pt => pt.OutcomeId);
modelBuilder.Entity<OutcomeCategoryEntity>()
.HasOne(pt => pt.Category)
.WithMany(t => t.Outcomes)
.HasForeignKey(pt => pt.CategoryId);
}
}
}
<file_sep>/src/Money.UI/Bootstrap/UpgradeService.cs
using Microsoft.EntityFrameworkCore;
using Money.Data;
using Money.Services;
using Money.Services.Models.Builders;
using Neptuo;
using Neptuo.Data;
using Neptuo.Events;
using Neptuo.Formatters;
using Neptuo.Migrations;
using Neptuo.ReadModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI;
namespace Money.Bootstrap
{
internal class UpgradeService : IUpgradeService
{
private readonly IDomainFacade domainFacade;
private readonly IEventRebuilderStore eventStore;
private readonly IFormatter eventFormatter;
public const int CurrentVersion = 2;
public UpgradeService(IDomainFacade domainFacade, IEventRebuilderStore eventStore, IFormatter eventFormatter)
{
Ensure.NotNull(domainFacade, "domainFacade");
Ensure.NotNull(eventStore, "eventStore");
Ensure.NotNull(eventFormatter, "eventFormatter");
this.domainFacade = domainFacade;
this.eventStore = eventStore;
this.eventFormatter = eventFormatter;
}
public bool IsRequired()
{
return CurrentVersion > GetCurrentVersion();
}
public async Task UpgradeAsync(IUpgradeContext context)
{
int currentVersion = GetCurrentVersion();
if (CurrentVersion <= currentVersion)
return;
context.TotalSteps(CurrentVersion - currentVersion);
await Task.Delay(500);
if (currentVersion < 1)
{
context.StartingStep(currentVersion - 0, "Creating default categories.");
await UpgradeVersion1();
}
if (currentVersion < 2)
{
context.StartingStep(currentVersion - 1, "Rebuilding internal database.");
await UpgradeVersion2();
}
ApplicationDataContainer migrationContainer = GetMigrationContainer();
migrationContainer.Values["Version"] = CurrentVersion;
}
private ApplicationDataContainer GetMigrationContainer()
{
ApplicationDataContainer root = ApplicationData.Current.LocalSettings;
ApplicationDataContainer migrationContainer;
if (!root.Containers.TryGetValue("Migration", out migrationContainer))
migrationContainer = root.CreateContainer("Migration", ApplicationDataCreateDisposition.Always);
return migrationContainer;
}
private int GetCurrentVersion()
{
ApplicationDataContainer migrationContainer = GetMigrationContainer();
int currentVersion = (int?)migrationContainer.Values["Version"] ?? 0;
return currentVersion;
}
private async Task UpgradeVersion1()
{
EventSourcingContext();
await RecreateReadModelContext();
await domainFacade.CreateCategoryAsync("Home", Colors.SandyBrown);
await domainFacade.CreateCategoryAsync("Food", Colors.OrangeRed);
await domainFacade.CreateCategoryAsync("Eating Out", Colors.DarkRed);
}
private Task UpgradeVersion2()
{
return RecreateReadModelContext();
}
private void EventSourcingContext()
{
using (var eventSourcing = new EventSourcingContext())
{
eventSourcing.Database.EnsureDeleted();
eventSourcing.Database.EnsureCreated();
eventSourcing.Database.Migrate();
}
}
private Task RecreateReadModelContext()
{
using (var readModels = new ReadModelContext())
{
readModels.Database.EnsureDeleted();
readModels.Database.EnsureCreated();
}
// Should match with ReadModels.
Rebuilder rebuilder = new Rebuilder(eventStore, eventFormatter);
rebuilder.AddAll(new CategoryBuilder());
rebuilder.AddAll(new OutcomeBuilder(domainFacade.PriceFactory));
return rebuilder.RunAsync();
}
}
}
<file_sep>/src/Money.UI/Views/Navigation/ApplicationNavigatorForm.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
namespace Money.Views.Navigation
{
internal class ApplicationNavigatorForm : PageNavigatorForm
{
private readonly Template template;
public ApplicationNavigatorForm(Template template, Type pageType, object parameter)
: base(template.ContentFrame, pageType, parameter)
{
this.template = template;
}
public override void Show()
{
base.Show();
template.ShowLoading();
}
}
}
<file_sep>/src/Money.UI/Views/Navigation/WizardNavigatorForm.cs
using Money.ViewModels.Navigation;
using Money.Views.Dialogs;
using Neptuo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Money.Views.Navigation
{
public class WizardNavigatorForm : INavigatorForm
{
private readonly Type wizardType;
private readonly object parameter;
public WizardNavigatorForm(Type wizardType, object parameter)
{
Ensure.NotNull(wizardType, "wizardType");
Ensure.NotNull(parameter, "parameter");
this.wizardType = wizardType;
this.parameter = parameter;
}
public void Show()
{
IWizard wizard = (IWizard)Activator.CreateInstance(wizardType);
wizard.ShowAsync(parameter);
}
}
}
<file_sep>/src/Money.UI/Views/Summary.xaml.cs
using Money.Services.Models;
using Money.Services.Models.Queries;
using Money.ViewModels;
using Money.ViewModels.Navigation;
using Money.ViewModels.Parameters;
using Money.Views.Controls;
using Money.Views.Navigation;
using Neptuo;
using Neptuo.Models.Keys;
using Neptuo.Queries;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
namespace Money.Views
{
[NavigationParameter(typeof(SummaryParameter))]
public sealed partial class Summary : Page, INavigatorPage, INavigatorParameterPage
{
private readonly INavigator navigator = ServiceProvider.Navigator;
private readonly IQueryDispatcher queryDispatcher = ServiceProvider.QueryDispatcher;
private SummaryParameter parameter;
private bool isAmountSorted;
private bool isCategorySorted = true;
public event EventHandler ContentLoaded;
public object Parameter
{
get { return parameter; }
}
public GroupViewModel ViewModel
{
get { return (GroupViewModel)DataContext; }
private set { DataContext = value; }
}
public Summary()
{
InitializeComponent();
ViewModel = new GroupViewModel(navigator);
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
parameter = (SummaryParameter)e.Parameter;
ViewModel.ViewType = parameter.ViewType;
switch (parameter.PeriodType)
{
case SummaryPeriodType.Month:
await LoadMonthViewAsync(ViewModel, parameter.Month);
break;
case SummaryPeriodType.Year:
await LoadYearViewAsync(ViewModel, parameter.Year);
break;
default:
throw Ensure.Exception.NotSupported(parameter.PeriodType.ToString());
}
if (parameter.SortDescriptor != null)
ViewModel.SortDescriptor = parameter.SortDescriptor;
ContentLoaded?.Invoke(this, EventArgs.Empty);
}
private async Task LoadMonthViewAsync(GroupViewModel viewModel, MonthModel prefered)
{
ViewModel.IsLoading = true;
IEnumerable<MonthModel> months = await queryDispatcher.QueryAsync(new ListMonthWithOutcome());
int? preferedIndex = null;
int index = 0;
foreach (MonthModel month in months)
{
viewModel.Add(month.ToString(), month);
if (prefered == month)
preferedIndex = index;
index++;
}
if (preferedIndex != null)
pvtGroups.SelectedIndex = preferedIndex.Value;
ViewModel.IsLoading = false;
}
private async Task LoadYearViewAsync(GroupViewModel viewModel, YearModel prefered)
{
throw new NotImplementedException();
}
public void DecorateParameter(SummaryParameter parameter)
{
if (parameter.Month == null && parameter.Year == null)
{
GroupItemViewModel viewModel = pvtGroups.SelectedItem as GroupItemViewModel;
if (viewModel != null)
{
MonthModel month = viewModel.Parameter as MonthModel;
if (month != null)
{
parameter.Month = month;
return;
}
YearModel year = viewModel.Parameter as YearModel;
if (year != null)
{
parameter.Year = year;
return;
}
}
}
}
private void mfiSortAmount_Click(object sender, RoutedEventArgs e)
{
ViewModel.SortDescriptor = ViewModel.SortDescriptor.Update(SummarySortType.ByAmount);
parameter.SortDescriptor = ViewModel.SortDescriptor;
isAmountSorted = !isAmountSorted;
isCategorySorted = false;
}
private void mfiSortCategory_Click(object sender, RoutedEventArgs e)
{
ViewModel.SortDescriptor = ViewModel.SortDescriptor.Update(SummarySortType.ByCategory);
parameter.SortDescriptor = ViewModel.SortDescriptor;
isCategorySorted = !isCategorySorted;
isAmountSorted = false;
}
private void pvtGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
GroupItemViewModel viewModel = (GroupItemViewModel)e.AddedItems.FirstOrDefault();
MonthModel month = viewModel.Parameter as MonthModel;
if (month != null)
this.parameter.Month = month;
YearModel year = viewModel.Parameter as YearModel;
if (year != null)
this.parameter.Year = year;
}
}
}
<file_sep>/src/Money.UI/ViewModels/Commands/CategoryRenameCommand.cs
using Money.Services;
using Neptuo;
using Neptuo.Models.Keys;
using Neptuo.Observables.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
namespace Money.ViewModels.Commands
{
public class CategoryRenameCommand : Command
{
private readonly IDomainFacade domainFacade;
private readonly CategoryEditViewModel viewModel;
public string Name { get; set; }
public string Description { get; set; }
public CategoryRenameCommand(IDomainFacade domainFacade, CategoryEditViewModel viewModel)
{
Ensure.NotNull(domainFacade, "domainFacade");
Ensure.NotNull(viewModel, "viewModel");
this.domainFacade = domainFacade;
this.viewModel = viewModel;
Name = viewModel.Name;
Description = viewModel.Description;
}
public override bool CanExecute()
{
return true;
}
public override async void Execute()
{
if (String.IsNullOrEmpty(Name))
return;
if (viewModel.Key.IsEmpty)
{
Color color = Colors.Black;
viewModel.Key = await domainFacade.CreateCategoryAsync(Name, color);
viewModel.Name = Name;
viewModel.Color = color;
}
else if (viewModel.Name != Name)
{
await domainFacade.RenameCategory(viewModel.Key, Name);
viewModel.Name = Name;
}
if (viewModel.Description != Description)
{
await domainFacade.ChangeCategoryDescription(viewModel.Key, Description);
viewModel.Description = Description;
}
}
}
}
<file_sep>/src/Money.UI/ViewModels/Commands/CategoryChangeColorCommand.cs
using Money.Services;
using Neptuo;
using Neptuo.Observables.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
namespace Money.ViewModels.Commands
{
public class CategoryChangeColorCommand : Command
{
private readonly IDomainFacade domainFacade;
private readonly CategoryEditViewModel viewModel;
private Color color;
public Color Color
{
get { return color; }
set
{
color = value;
Execute();
}
}
public CategoryChangeColorCommand(IDomainFacade domainFacade, CategoryEditViewModel viewModel)
{
Ensure.NotNull(domainFacade, "domainFacade");
Ensure.NotNull(viewModel, "viewModel");
this.domainFacade = domainFacade;
this.viewModel = viewModel;
color = viewModel.Color;
}
public override bool CanExecute()
{
return true;
}
public override async void Execute()
{
if (Color != viewModel.Color)
{
await domainFacade.ChangeCategoryColor(viewModel.Key, Color);
viewModel.Color = Color;
}
}
}
}
<file_sep>/src/Money/Data/IOutcomeRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Money.Data
{
/// <summary>
/// Describes contract for loading and saving outcome models.
/// </summary>
public interface IOutcomeRepository
{
/// <summary>
/// Enumerates all outcomes.
/// </summary>
/// <returns>Enumeration of all outcomes.</returns>
IEnumerable<Outcome> Enumerate();
/// <summary>
/// Saves <paramref name="model "/>.
/// </summary>
/// <param name="model">The outcome to save (insert or update).</param>
void Save(Outcome model);
/// <summary>
/// Deletes outcome by <paramref name="id"/>.
/// </summary>
/// <param name="id">The id of outcome to delete.</param>
void Delete(Guid id);
}
}
<file_sep>/src/Money.UI/Views/Dialogs/OutcomeAmount.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace Money.Views.Dialogs
{
public sealed partial class OutcomeAmount : ContentDialog
{
public double Value
{
get { return (double)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
"Value",
typeof(double),
typeof(OutcomeAmount),
new PropertyMetadata(0d)
);
public OutcomeAmount()
{
InitializeComponent();
}
private void OnNumberButtonClick(object sender, RoutedEventArgs e)
{
string value = ((Button)sender).Content as string;
if (value != null)
Value = Double.Parse(tbxAmount.Text + value);
//if (tbxAmount.Text.StartsWith("0") && tbxAmount.Text.Length > 1)
//tbxAmount.Text = tbxAmount.Text.Substring(1);
}
private void OnUndoClick(object sender, RoutedEventArgs e)
{
if (tbxAmount.Text.Length > 1)
Value = Double.Parse(tbxAmount.Text.Substring(0, tbxAmount.Text.Length - 1));
else
Value = 0;
}
}
}
|
3342673009f5137bf2c5c59fc4f29eb485aa72be
|
[
"C#"
] | 35
|
C#
|
arrebagrove/Money
|
f0e9096bc359a70283c8b4e62d7d1ff1223644c0
|
5f30a0ebf0e439d613e551e24b6cbf03a80ab771
|
refs/heads/master
|
<repo_name>ivamotelolamounier/ContatosJson<file_sep>/app/src/main/java/com/ivamotelo/contatosCard/ClickItensContactsListener.kt
package com.ivamotelo.contatosCard
interface ClickItensContactsListener {
fun clickItenContact(contact: Contacts){
}
}<file_sep>/app/src/main/java/com/ivamotelo/contatosCard/ContactsAdapter.kt
/**
* Classe para gerenciar as listas do aplicativo, bem como sua reciclagem
* para sua implementação, é obrigatório, a implementação de outras classes
* 1- Classe ADAPTER - função de gerenciar a lista de contatos
* 2- Classe ViewHolder - responsável por gerenciar CADA ITEM da lista, que poderá ser uma classe
* externa ou interna (caso em uso).
* 3- No construtor da classe 'ContactAdapter', é passada a classe 'ContactAdapterViewHolder' como
* referência.
* 4- a classe 'ContactAdapter, exige a implementação de alguns métodos OBRIGATÓRIOS:
* a) - onCreateViewHolder
* b) - onBindViewHolder
* c) - getItemCount
*
*
*/
package com.ivamotelo.contatosCard
import android.provider.ContactsContract
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
/**
* A classe ADAPTER, gerencia toda a lista da Data Classe Contact, e o 'Holder', gerencia
* cada Iten da Data Classe.
* Para que a tela de detalhes do contato 'ContactDetails' seja aberta e receba os dados do
* adapter, é necessário passa-la como parâmentro no construtor 'ContactsAdapter()'
*/
class ContactsAdapter(var listener: ClickItensContactsListener) :
RecyclerView.Adapter<ContactsAdapter.ContatctsAdapterViewHolder>() {
/**
* É necessário a criação de uma MutableList para armazenar os dados que serão exibidos
* na RecyclerView, que terá a Data classe 'Contact' (modelo de dado desejado)
*/
val list : MutableList<Contacts> = mutableListOf()
/**
* Esta função 'onCreateViewHolder', é reponsável por criar cada item na tela do app, diferente
* da função 'onBindViewHolder'. A primeira, é a criação do elemento grafico na RecyclerView,
* e a segunda é sua 'população' com os dados a serem exibidos. Assim, esta função CRIA O LAYOUT
* e INFRA a View, anterior a função OnBindViewHolder, que povoa esta criação com os dados a
* serem exibidos. O retorno será a classe 'ContactAdapterViewHoder, com a a variável 'view'
* como parâmetro que é um CARD.
* Para que o contato selecionado seja passado para a tela de detalhes do contato 'ContactDetails'
* é necessário que o retorno 'ContactsAdapterViewHolder(), também receba em seu construtor, o
* 'listner'
*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContatctsAdapterViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.contact_item, parent, false)
return ContatctsAdapterViewHolder(view, list, listener)
}
/**
* Função responsável por percorrer a array de itens da lista e preencher a mesma na tela
* chamado de 'bind', que consiste em 'popular' os cards da RecyclerView.
* A lógica da função 'onBindViewHolder', consiste na renderização da RecyclerView, atualizando
* a posição dos cards a cada rolagem na tela, ou a cada passagem pelo item.
* Assim, sendo da mesma classe 'ContactAdapterViewHolder', implementa-se o 'holder.bind'
* que recebe 'list', através do index 'position' do construtor
*/
override fun onBindViewHolder(holder: ContatctsAdapterViewHolder, position: Int) {
holder.bind(list[position])
}
/**
* Função para informar quantos itens possui a lista, que será retornada como Int.
*/
override fun getItemCount(): Int {
return list.size
}
/**
* Para passar a lista de uma classe EXTERNA (MainActivity.kt) para dentro do ADAPTER,
* é necessaŕio a criaçao de uma funçao PÚBLICA que acessará o adapter e repasse a lista
* para a classe 'ContactsAdapter'
* 1- o método recebe uma lista do tipo list
* 2- sempre que o método for chamado, ele limpará a lista interna (list)
* 3- após a limpeza da lista, a mesma será populada novamente
* 4- isso feito, será chamdo o método 'notifyDataSetChanged ' que notificará o adapter,
* informando que a lista (list) utilizada para fazer a renderização, foi modificada.
* Deste modo, reinicia-se o ciclo da lógica implementada.
*/
fun updateLista(list: List<Contacts>){
this.list.clear()
this.list.addAll(list)
notifyDataSetChanged()
}
/**
* A classe 'ContactAdapter', gerencia TODA a lista da Data Classe 'Contact' e a classe
* ContactAdapterViewHolder', gerencia CADA ITEM da lista Data Classe, ou seja, cada
* "contato" de Contact.
* São declaradas as val referentes aos campos da lista, que serão ligados á RecyclerView
* através de seus 'id' do arquivo 'contact_item.xml'.
* Isso feito, na função 'bind()', será atribuido a cada item da 'fun getItemCount()' para
* cada componente Text e Image da ViewCard.
* Para que o contato selecionado seja exibido na tela de 'ContactDetails', é necessário passar
* uma var 'list', do tipo List<Contacts>, dentro do construtor da classe ContactsAdapterViewHolder.
* Do mesmo modo, é necessário a passagem no construtor da mesma classe, do método 'listner' do tipo
* ClickItensContactsListener.
*/
class ContatctsAdapterViewHolder(ItemView : View, var list: List<Contacts>, listener: ClickItensContactsListener) :
RecyclerView.ViewHolder(ItemView) {
private val iv_photo: ImageView = ItemView.findViewById(R.id.iv_photo)
private val tv_name: TextView = ItemView.findViewById(R.id.tv_name)
private val tv_phone: TextView = ItemView.findViewById(R.id.tv_phone)
/**
* Cria o click dentro do item, ou seja, quando o usuário clicar no item da lista selecionado
* o método 'setOnClickListener' do listener será chamado, no caso, em cima da View 'itemView'
* que chamará o método 'listener.clickItenContact' da interface 'ClickItensContactsListener'
* que foi implementado na Activity, que por sua vez irá executar a instrução declarada na
* 'init' abaixo
*/
init {
itemView.setOnClickListener{
listener.clickItenContact(list[adapterPosition])
}
}
fun bind(contact: Contacts){
tv_name.text = contact.name
tv_phone.text = contact.phone
// falta tratar iv_photo
}
}
}<file_sep>/app/src/main/java/com/ivamotelo/contatosCard/MainActivity.kt
package com.ivamotelo.contatosCard
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.widget.Toolbar
import androidx.core.content.edit
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.ivamotelo.contatosCard.ContactsDetails.Companion.EXTRA_CONTACT
class MainActivity : AppCompatActivity(), ClickItensContactsListener {
/**
* Declaração de uma variável 'rv_list' da classe RecyclerView, com atraso (lazy)
* Declaração de uma variável 'adapter' do tipo Adapter, que receberá a classe
* 'ContactsAdapter()', já instânciada.
*/
private val rv_list : RecyclerView by lazy {
findViewById<RecyclerView>(R.id.rv_list)
}
/**
* Aqui, é implementado no construtor do adapter, a chamada para a abertura e passagem de dados
* necessários a abertura da tela de detelahes do contato 'ContactsDetails', no caso 'this', ou seja
* a classe atual já implementa a interface
*/
private val adapter = ContactsAdapter(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.drawer_menu)
// A ordem de chamada é importante
iniDrawer()
fetchListContacts()
bindView()
}
/**
* Função utilizada para fazer a chamda da RecyclerView 'rv_list', juntamente com o seu adapter
* 'adpter' instanciado com a ContactsAdapter().
* Logo, o adapter da classe 'ContactsAdapter', será utilizado na MainActivity, através da ligaçõa
* feita com a declaração da val adapter acima.
* Também é definida a forma como a recyclerView irá se comportar, sendo um tratamento interno, mas
* necessário para seu funcionamento, através de seus 'layoutManger', que no caso em tela será
* através do método 'LinearLayoutManeger', no contexto da própria MainActivity (this)
*/
private fun bindView(){
rv_list.adapter = adapter
rv_list.layoutManager = LinearLayoutManager(this)
updateList()
}
/**
* Método para obter a lista de contatos do arquivo de preferencias do usuário "PREFERENCES"
* em forma de uma String, necessita de uma chave: 'contatcts' e um valor valor padrão, caso
* a chave não exista, ou seja nula, retornando um array vazio '[]' para não 'quebrar a aplicação
* Se a String for válida, então será feita a conversão da String em um objeto de classe através
* do JSON
*/
private fun getListContacts() : List<Contacts> {
val list = getInstanceSharedPreferences().getString("contacts", "[]")
val turnsType = object : TypeToken<List<Contacts>>(){}.type
return Gson().fromJson(list, turnsType)
}
/**
* Função que atualiza a lista JSON retornada da função 'getListContacts()
*/
private fun updateList(){
val list = getListContacts()
adapter.updateLista(list)
//adapter.updateLista(getListContacts())
}
/**
* Método para a criação do MENUS DE CONTEXTO do App
* utiliza-se o método 'infrate' para infrar o menu, que receberá o xml do arquivo 'menu'
*/
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val infrater : MenuInflater = menuInflater
infrater.inflate(R.menu.menu, menu)
return true
}
/**
* Método encapsulado para tratar os TOASTS do componente de menus
*/
private fun showToast(message : String){
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
/**
* Método utilizado para receber a opção de menu que foi clicada
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId){
R.id.itens_menu1 -> {
showToast("Exibindo menu itens 1")
return true
}
R.id.itens_menu2 -> {
showToast("Exibindo menu itens 2")
return true
}
else -> super.onOptionsItemSelected(item)
}
}
/**
* Método para inicializar o MENU TOOLBAR.
*/
private fun iniDrawer(){
val drawerLayout = findViewById<View>(R.id.drawer_layout) as DrawerLayout
val toolbar = findViewById<Toolbar>(R.id.menu_toolbar)
setSupportActionBar(toolbar)
val toogle = ActionBarDrawerToggle(
this,
drawerLayout,
toolbar,
R.string.open_drawer,
R.string.close_drawer)
drawerLayout.addDrawerListener(toogle)
// sincroniza o evento de abrir e fechar com o drawerlayout
toogle.syncState()
}
/**
* Função para iniciar a atividade referente a tela de detalhes do contato 'ContactsDetails'
* para que haja o trafego de forma correta, foi necessário o plugin kotlin-extensions, que foi
* descontinuado.
* continuando, implementa-se uma 'Intent' com o método 'putextra()' que possui o conceito
* 'chave x valor' para ser recuperado na tela de detalhes 'ContactDetail', com a mesma 'chaveValor'
* Esta chaveValor será criada na Activity "ContactDetails'
* Chave: 'EXTRA_CONTACT' e valor 'contact'
*/
override fun clickItenContact(contact: Contacts){
val intent = Intent(this, ContactsDetails::class.java)
intent.putExtra(EXTRA_CONTACT, contact)
startActivity(intent)
}
/**
* \método para gravar as preferências do usuário, no caso uma lista de contatos preferidos
* através da API. O método faz uma consulta na lista e retorna os registros marcados como
* favoritos
*/
fun fetchListContacts(){
val list = arrayListOf(
Contacts(
name = "<NAME>",
phone = "(35) 99999-12345",
avatar = "img.png"
),
Contacts(
name = "<NAME>",
phone = "(32) 45687-3251",
avatar = "img.png"
)
)
/**
* Será realizada uma conversão de objeto de classe (array) para uma String, através da
* biblioteca JSON. Existem dois métodos para gravar a presitência de dados: 'apply' e 'commit'
* sendo que 'apply' grava de modo sincromo, ou seja, não broqueia a thread principal, já o modo
* 'commit' e realizado de modo assincorno, o que poderá travar a thread principal, se a
* gravação da presistência de dados for muito grande. no nosso exemplo, a gravção é
* praticamente instantânea, mas por segurança, utiliza-se o COMMIT para que a thread seja
* bloqueada até o final da gravção da presitência dos dados gravados, garantido que seja
* anterior a uma consulta no app
*/
getInstanceSharedPreferences().edit {
val json = Gson().toJson(list)
putString("contatcts", json)
commit()
//putString("contacts", Gson().toJson(list))
}
}
/**
* Método nativo 'getSharedPreferences()', que tem como contexto conforme documentação do Android
* que recomenda que o arquivo de preferências seja único no aplicativo e tenha um nome expressivo
* usando o 'nome do pacote da aplicação", no caso 'com.ivamotelo.contatos. PREFERENCES'
*/
fun getInstanceSharedPreferences() : SharedPreferences {
return getSharedPreferences("com.ivamotelo.contatosCard.PREFERENCES", Context.MODE_PRIVATE)
}
}
<file_sep>/app/src/main/java/com/ivamotelo/contatosCard/ContactDetails.kt
package com.ivamotelo.contatosCard
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
/**
* Cria-se a função 'getExtras()' para recuperar os dados passados da MainActivity, quando da
* seleção do contato para ser mostrado em detalhes na Activity 'ContactsDetail'
*/
class ContactsDetails : AppCompatActivity() {
private var contact : Contacts? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_contact_details)
initToolBar()
getExtras()
bindViews()
}
/**
* Criação da função 'getExtras' para fins de recuperar os dados do contato selecionado para
* exibir os detalhes, através da chaveValor 'EXTRA_CONTACT'
*/
fun getExtras(){
contact = intent.getParcelableExtra(EXTRA_CONTACT)
}
/**
* Estando os dados salvos na variável 'contact', os mesmos serão 'setados' na tela da Activity
* 'activity_contact_details.xml', fazendo o 'bind' - ligação dos dados entre as telas
*/
private fun bindViews(){
findViewById<TextView>(R.id.tv_name).text = contact?.name
findViewById<TextView>(R.id.tv_phone).text = contact?.phone
}
/**
* Criação de um companation object (Visível em toda aplicação) da chave x valor referente
* ao contato que será selecionado na Activiy e será recuperada na Activity ContactsDetail
*/
companion object {
const val EXTRA_CONTACT : String = "EXTRA_CONTACT"
}
/**
* Implementação de uma 'toolBar' na Activity 'ContactDetails'
* habilita (true) o botão voltar na toolBar com o método 'supportActionBar, que
* pode receber nulo (?)
*/
private fun initToolBar(){
val toolbar = findViewById<Toolbar>(R.id.menu_toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
/**
* Após o toque na seta para voltar, é implementado o método nativo 'onSupportNavegateUp()
* para retornar a tela principal ActivityMain, destuindo a Activity ativa 'activity_contact_detail.xml
* e reconstruindo a activity principal MainActivity. Pode-se utilizar o modo nativo super.
* ou simplesmente retornar verdadeiro 'return true'
*/
override fun onSupportNavigateUp(): Boolean {
finish()
return true
//return super.onSupportNavigateUp()
}
}<file_sep>/app/src/main/java/com/ivamotelo/contatosCard/Contacts.kt
package com.ivamotelo.contatosCard
import android.os.Parcelable
import android.widget.ImageView
import kotlinx.android.parcel.Parcelize
/**
* Implementar as dependências do 'kotlin-android-extensions' no gradle, e fazer a notação'@'
* como parcelaize. Com a implementação do 'Parcelable', fica habilitado o tráfego de dados entre
* as telas - necessário destacar que este plugin foi descontinuado em 2021
*/
@Parcelize
data class Contacts(
var name : String,
var phone : String,
var avatar : String
) : Parcelable
<file_sep>/settings.gradle
rootProject.name = "Contatos com Recicler e Card View"
include ':app'
|
8f263dac86c5e6d12c41e96d331a66b504871599
|
[
"Kotlin",
"Gradle"
] | 6
|
Kotlin
|
ivamotelolamounier/ContatosJson
|
e7a10aae5b5db85fa77d36441351aaf9bda695b0
|
7e8c005598befaa3f15dfc4d4e09a511179b966d
|
refs/heads/master
|
<repo_name>qinzhengmei/object-detection<file_sep>/README.md
# object-detection
Few Shot Object Detection using TensorFlow and Python
<file_sep>/my_Object_detection_webcam_2.py
import cv2
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import pathlib
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
from IPython.display import display
from object_detection.utils import ops as utils_ops
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
threshold = 0.6
def get_output_tensor(interpreter, index):
"""Returns the output tensor at the given index."""
output_details = interpreter.get_output_details()[index]
tensor = np.squeeze(interpreter.get_tensor(output_details['index']))
return tensor
def name(id):
if id == 0:
return "drink_pet_small"
elif id == 1:
return "drink_pet_large"
elif id == 2:
return "drink_aluminum"
elif id == 3:
return "detergents"
elif id == 4:
return "paper_large"
model_path = "tflite_tf2/model.tflite"
interpreter = tf.lite.Interpreter(model_path=model_path)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
input_shape = input_details[0]['shape']
# Initialize webcam feed
video = cv2.VideoCapture('videos/video_2.h264')
# video_writer = cv2.VideoWriter('output_3.mp4', fourcc=cv2.VideoWriter_fourcc(*'mp4v'), fps=30.0, frameSize=(1280,720))
while(True):
ret, frame = video.read()
if not ret:
break
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w, _ = frame.shape
input_data = cv2.resize(frame, (300, 300))
input_data = input_data.astype(np.float32)
input_data = input_data / 255.0
input_data = np.reshape(input_data, (1, 300, 300, 3))
# input_data = np.array(np.random.random_sample(input_shape), dtype=np.uint8)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
boxes = get_output_tensor(interpreter, 0)
classes = get_output_tensor(interpreter, 1)
scores = get_output_tensor(interpreter, 2)
count = int(get_output_tensor(interpreter, 3))
results = []
for i in range(10):
if scores[i] >= threshold:
result = {
'bounding_box': boxes[i],
'class_id': classes[i],
'score': scores[i]
}
results.append(result)
for obj in results:
# Convert the bounding box figures from relative coordinates
# to absolute coordinates based on the original resolution
ymin, xmin, ymax, xmax = obj['bounding_box']
xmin = int(xmin * w)
xmax = int(xmax * w)
ymin = int(ymin * h)
ymax = int(ymax * h)
cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), (255,0,0), 3)
print(obj['class_id'], obj['score'])
cv2.putText(frame, name(obj['class_id']), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255))
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
# All the results have been drawn on the frame, so it's time to display it.
cv2.imshow('Object detector', frame)
# video_writer.write(frame)
if cv2.waitKey(1) == ord('q'): # Press 'q' to quit
break
# Clean up
video.release()
# video_writer.release()
cv2.destroyAllWindows()<file_sep>/my_Object_detection_webcam.py
import cv2
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import pathlib
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
from IPython.display import display
from object_detection.utils import ops as utils_ops
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = 'images/labelmap.pbtxt'
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
detection_model = tf.saved_model.load(str('inference_graph/saved_model'))
model_fn = detection_model.signatures['serving_default']
# Initialize webcam feed
video = cv2.VideoCapture('videos/video_3.h264')
# video = cv2.VideoCapture(0)
# video_writer = cv2.VideoWriter('output_5.mp4', fourcc=cv2.VideoWriter_fourcc(*'mp4v'), fps=30.0, frameSize=(1280,720))
count = 52
while(True):
# Acquire frame and expand frame dimensions to have shape: [1, None, None, 3]
# i.e. a single-column array, where each item in the column has the pixel RGB value
ret, frame = video.read()
original_frame = frame
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
input_tensor = tf.convert_to_tensor(frame)
# The model expects a batch of images, so add an axis with `tf.newaxis`.
input_tensor = input_tensor[tf.newaxis,...]
# Run inference
output_dict = model_fn(input_tensor)
# All outputs are batches tensors.
# Convert to numpy arrays, and take index [0] to remove the batch dimension.
# We're only interested in the first num_detections.
num_detections = int(output_dict.pop('num_detections'))
output_dict = {key:value[0, :num_detections].numpy()
for key,value in output_dict.items()}
output_dict['num_detections'] = num_detections
# detection_classes should be ints.
output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64)
# Handle models with masks:
if 'detection_masks' in output_dict:
# Reframe the the bbox mask to the image size.
detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
output_dict['detection_masks'], output_dict['detection_boxes'],
frame.shape[0], frame.shape[1])
detection_masks_reframed = tf.cast(detection_masks_reframed > 0.1,
tf.uint8)
output_dict['detection_masks_reframed'] = detection_masks_reframed.numpy()
vis_util.visualize_boxes_and_labels_on_image_array(
frame,
output_dict['detection_boxes'],
output_dict['detection_classes'],
output_dict['detection_scores'],
category_index,
instance_masks=output_dict.get('detection_masks_reframed', None),
use_normalized_coordinates=True,
min_score_thresh=.7,
max_boxes_to_draw=1,
line_thickness=8)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
# if np.max(output_dict['detection_scores']) > 0.7:
# index = np.argmax(output_dict['detection_scores'])
# class_id = output_dict['detection_classes'][index]
# text = category_index[class_id]['name']
# cv2.putText(frame, text, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
# All the results have been drawn on the frame, so it's time to display it.
cv2.imshow('Object detector', frame)
# video_writer.write(frame)
if cv2.waitKey(1) == ord('c'):
cv2.imwrite(f'{count}.jpg', original_frame)
count += 1
# Press 'q' to quit
if cv2.waitKey(1) == ord('q'):
break
# Clean up
video.release()
# video_writer.release()
cv2.destroyAllWindows()
|
df41d9e1aa0223a110a3da758eb56364639b6e3d
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
qinzhengmei/object-detection
|
e96734dbfdf2b8fb3f4c438ed2a6ed05a4070b55
|
13f818666549b76f7cc592d40cc3702aaed0b6bd
|
refs/heads/master
|
<repo_name>sheen4n/react-monster<file_sep>/src/App.js
import React, { Component } from 'react'
import './App.css';
import CardList from './components/card-list/card-list.component';
import SearchBox from './components/search-box/search-box.component';
export class App extends Component {
state = {
monsters: [],
searchField: ""
}
async componentDidMount() {
var response = await fetch("https://jsonplaceholder.typicode.com/users");
var users = await response.json();
this.setState({ monsters: users });
// console.log("TCL: App -> componentDidMount -> users", users)
}
handleChange = (e) => {
this.setState({ searchField: e.target.value });
}
render() {
const { monsters, searchField } = this.state;
const constFilteredMonster = monsters.filter(monster =>
monster.name.toLowerCase().includes(searchField.toLowerCase())
);
return (
<div className="App">
<h1>Monster Rodolox</h1>
<SearchBox placeholder="Search Monsters"
handleChange={this.handleChange} />
<CardList monsters={constFilteredMonster} />
</div>
)
}
}
export default App
|
0b221ec373b0f4f7dd27b4c6ce75705dc2780156
|
[
"JavaScript"
] | 1
|
JavaScript
|
sheen4n/react-monster
|
afea3e79271c5f876f3f99b9b4f7a829af1bc18e
|
51650b4e5c68fdaad7c81ff694a3a4bdfda13c42
|
refs/heads/master
|
<repo_name>bimiabi/papertowns<file_sep>/app/models/airdb.rb
class Airdb < ActiveRecord::Base
def self.search(query)
where("product_name || description || product_model || serial_number || price || stock || id like ?", "%#{query}%")
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
#This allows the director to register users
devise_for :users#, :skip => [:registrations]
devise_scope :user do
get "signup", :to => "users#new"
get "signin", :to => "devise/sessions#new"
get "signout", :to => "devise/sessions#destroy"
get "cancel_user_registration", :to => "devise/registrations#cancel"
post "user_registration", :to => "users#create"
get "new_user_registration", :to => "users#new"
get "edit_user_registration", :to => "users#edit"
end
resources :users
resources :purchases
resources :appointments do
resources :comments
end
resources :customers
resources :products
root 'airdb#home'
get 'airdb/home'
get '/weeklyAppointments', to: 'appointments#weeklyAppointments'
get '/dailyAppointments', to: 'appointments#dailyAppointments'
get '/allAppointments', to: 'appointments#allAppointments'
get '/finishedAppointments', to: 'appointments#finishedAppointments'
get '/pendingAppointments', to: 'appointments#pendingAppointments'
get '/appointmentsForTomorrow', to: 'appointments#appointmentsForTomorrow'
end
<file_sep>/app/controllers/airdb_controller.rb
class AirdbController < ApplicationController
def home
if params[:search]
@products = Product.search(params[:search]).order("created_at DESC")
else
@products = Product.order("created_at DESC")
end
if user_signed_in?
else
redirect_to new_user_session_path
end
end
end
<file_sep>/app/mailers/appointment_mailer.rb
class AppointmentMailer < ActionMailer::Base
def appointmentMail_created(current_user,appointment_user, customer_name, appointment_note, technician_name, phone_number, appointment_type, address, product_model, appointment_date)
@current_user = current_user
@appointment_user = appointment_user
@customer_name = customer_name
@appointment_note = appointment_note
@technician_name = technician_name
@phone_number = phone_number
@appointment_type = appointment_type
@address = address
@product_model = product_model
@appointment_date = appointment_date
# if appointment_date < 24.hours.from_now # we can use this logic to send automated email if the appointment date is 24 hours from the now
mail(to: appointment_user.email,
from: "<EMAIL>", #using Gmail smtp settings it will override "from:" so it doesnt matter what we put here
subject: "Appointment Created",
)
# end
end
end
<file_sep>/app/models/customer.rb
class Customer < ActiveRecord::Base
#When we install deivise for the cusomters we haveto delete the password field
validates :customer_name, :username, :password, :registration_date, :email, :phone_number, :address, :gender, presence: true
def self.search(query)
where("customer_name || username || password || registration_date || email || phone_number || address || gender || id like ?", "%#{query}%")
end
end
<file_sep>/app/controllers/appointments_controller.rb
class AppointmentsController < ApplicationController
before_action :authenticate_user!
load_and_authorize_resource except: [:create]
skip_authorize_resource :only => [:dailyAppointments, :weeklyAppointments, :allAppointments, :pendingAppointments, :finishedAppointments]
before_action :set_appointment, only: [:show, :edit, :update, :destroy]
# GET /appointments
# GET /appointments.json
def index
if params[:search]
@appointments = Appointment.search(params[:search]).order("created_at DESC")
else
@appointments = Appointment.order("created_at DESC")
end
end
# GET /appointments/1
# GET /appointments/1.json
def show
end
def allAppointments
@appointments = Appointment.order("created_at DESC")
end
def dailyAppointments
@appointments = Appointment.order("created_at DESC")
end
def weeklyAppointments
@appointments = Appointment.order("created_at DESC")
end
def finishedAppointments
@appointments = Appointment.order("created_at DESC")
end
def pendingAppointments
@appointments = Appointment.order("created_at DESC")
end
# GET /appointments/new
def new
@appointment = Appointment.new
end
def test
@appointment = Appointment.new
end
# GET /appointments/1/edit
def edit
end
# POST /appointments
# POST /appointments.json
def create
@user = current_user
@appointment = @user.appointments.new(appointment_params)
respond_to do |format|
if @appointment.save
format.html { redirect_to @appointment, notice: 'Appointment was successfully created.' }
format.json { render :show, status: :created, location: @appointment }
else
format.html { render :new }
format.json { render json: @appointment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /appointments/1
# PATCH/PUT /appointments/1.json
def update
respond_to do |format|
if @appointment.update(appointment_params)
format.html { redirect_to @appointment, notice: 'Appointment was successfully updated.' }
format.json { render :show, status: :ok, location: @appointment }
else
format.html { render :edit }
format.json { render json: @appointment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /appointments/1
# DELETE /appointments/1.json
def destroy
@appointment.destroy
respond_to do |format|
format.html { redirect_to appointments_url, notice: 'Appointment was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_appointment
@appointment = Appointment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def appointment_params
params.require(:appointment).permit(:customer_name, :appointment_note, :technician_name, :phone_number, :appointment_type, :address, :product_model, :appointment_date, :status)
end
end
<file_sep>/README.rdoc
README
* Ruby version: 2.1.5
* Rails version: 4.2.4
* System dependencies: Check GEMFILE and run bundle install
* Configuration of the root path is: root 'airdb#home'
* Database creation: localhost, default ruby sqlite database
* Database initialization: migration of all necessary objects is under the "db/migrate" folder in the project files
* How to run the test suite:
To run the test first download the project as zip file,
extract it check the steps below under "Deployment" b-point.
* Deployment instructions:
Manual Deployment,
Please do not use this command for deployment
<tt>bundle install --deployment</tt> because this is manual deployment and it will create a gigantic bit where as a result you will be unable to commit the new changes to the working branch.
Instead use the following commands until we come to the decision of using an automatic deployment method:
<tt>bundle install</tt>
<tt>rake db:migrate</tt>
<tt>rails s or rails server</tt>
* Services:
This is the first implementation of the project
In this pull request you will find:
* 1. CRUD, via scaffold for pages:
• Products
• Users
• Customers
• Appointments
• Purchases
* 2. Bootstrap, base styling for most HTML elements
• Searchbar
• Tables
• Buttons
• Fonts
• Alerts
* 3. application.html.erb is the core file for the structure of our project
• Please keep the structure in this format so we can avoid repetition
• In this file we can also define permission for different users
*Things to do next:
1. Wait for customers feedback upon the most valuable user stories
2. Wait for customers feedback upon the first look of the system
Edit the project on the "master-update" branch, after doing so, create a pull request.
All the best from Athens.
Ibrax :)
<file_sep>/app/models/purchase.rb
class Purchase < ActiveRecord::Base
validates :customer_name, :product_name, :product_model, :price, :purchase_date, :maintnance_date, presence: true
def self.search(query)
where("customer_name || product_name || product_model || price || purchase_date || maintnance_date || id like ?", "%#{query}%")
end
end
<file_sep>/app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def create
@appointment = Appointment.find(params[:appointment_id])
@comment = @appointment.comments.create(comments_params)
CommentMailer.comment_created(current_user,@appointment.user,@comment.content, @comment.status, @appointment, @appointment.customer_name, @appointment.technician_name, @appointment.appointment_date, @appointment.phone_number, @appointment.address, @appointment.appointment_type).deliver
redirect_to appointment_path(@appointment)
end
private
def comments_params
params.require(:comment).permit(:status, :content)
end
end
|
2463c1f615032e13527d1060b4b802c68aaded5e
|
[
"RDoc",
"Ruby"
] | 9
|
Ruby
|
bimiabi/papertowns
|
21b7b96a8679abfb0d8423a9df04e7453cefa048
|
70ab1e98dc95a881d236da421f4936b82cc49d98
|
refs/heads/master
|
<repo_name>roshaans/covid-house-management-tool<file_sep>/src/app/admin-registeration/admin-registeration-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AdminRegisterationPage } from './admin-registeration.page';
const routes: Routes = [
{
path: '',
component: AdminRegisterationPage
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class AdminRegisterationPageRoutingModule {}
<file_sep>/src/app/norm-creator/norm-creator.page.ts
import { Component, OnInit } from '@angular/core';
import {
ModalController,
NavParams
} from '@ionic/angular';
@Component({
selector: 'app-norm-creator',
templateUrl: './norm-creator.page.html',
styleUrls: ['./norm-creator.page.scss'],
})
export class NormCreatorPage implements OnInit {
constructor( private modalController: ModalController) { }
ngOnInit() {
}
async closeModal() {
const onClosedData: string = "Wrapped Up!";
await this.modalController.dismiss(onClosedData);
}
submitNorm() {
}
}
<file_sep>/src/app/tab3/tab3.page.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-tab3',
templateUrl: 'tab3.page.html',
styleUrls: ['tab3.page.scss']
})
export class Tab3Page implements OnInit{
username = "<NAME>"
group_id = "379snx9"
constructor() {}
ngOnInit() {
this.getUsername()
this.getGroupID()
}
getUsername() {
}
getGroupID(){
}
signOut() {
}
}
<file_sep>/src/app/tab2/tab2.page.ts
import { NormCreatorPage } from './../norm-creator/norm-creator.page';
import { Component,OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
@Component({
selector: 'app-tab2',
templateUrl: 'tab2.page.html',
styleUrls: ['tab2.page.scss']
})
export class Tab2Page implements OnInit {
norms = ["Never DO THIS THiS", "No more than 5 people in the living room"]
constructor(public modalController: ModalController) {}
ngOnInit() {
this.loadNorms()
}
loadNorms() {
}
async presentModal() {
const modal = await this.modalController.create({
component: NormCreatorPage,
cssClass: 'my-custom-class'
});
return await modal.present();
}
flagNorm(event) {
}
}
<file_sep>/src/app/tab1/tab1.page.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-tab1',
templateUrl: 'tab1.page.html',
styleUrls: ['tab1.page.scss']
})
export class Tab1Page implements OnInit {
maxNum = 13
currNum = 4
minOccupancy = 4
selectedColor = "#abfb8e"
trackerColors = ["#abfb8e", "#dbfb8e", "#f9fb8e", "#fbde8e", "#fba78e", "#f96e6e", "#ff0202"]
constructor() {}
doRefresh(event){
this.loadVal()
}
ngOnInit() {
this.loadVal()
}
loadVal() {
this.currNum = 4
this.maxNum = 13
this.minOccupancy = 4
}
setColor() {
var percentage = Math.round((this.currNum/this.maxNum) * 10) - this.minOccupancy;
if(this.currNum == this.minOccupancy) {
this.selectedColor = this.trackerColors[0]
} else if (this.currNum >= this.maxNum){
this.selectedColor = this.trackerColors[this.trackerColors.length-1]
}
else {
this.selectedColor = this.trackerColors[percentage]
}
}
addPerson() {
this.currNum += 1
this.setColor()
}
subtractPerson() {
if(this.currNum <= this.minOccupancy) {
} else {
this.currNum -= 1
}
this.setColor()
}
}
|
e7944c7ae53102a7001001d77853548a0bdfa40d
|
[
"TypeScript"
] | 5
|
TypeScript
|
roshaans/covid-house-management-tool
|
7d7cc799d7b1a73e028297b23dadd935689af775
|
3d8fe682f6a94316e29b33f900f28fbf3829f153
|
refs/heads/master
|
<file_sep>#include "linker.h"
#include <iostream>
#include <iomanip>
void Linker::addObjectFile(ifstream& inputFile) {
try {
unsigned tableSize;
inputFile.read(reinterpret_cast<char*>(&tableSize), sizeof(tableSize));
for (unsigned i = 0; i < tableSize; i++) {
TableEntry entry;
inputFile.read(reinterpret_cast<char*>(&entry.id), sizeof(entry.id));
unsigned labelSize;
inputFile.read(reinterpret_cast<char*>(&labelSize), sizeof(labelSize));
char* buffer = new char[labelSize];
inputFile.read(buffer, labelSize);
entry.label.assign(buffer, labelSize);
delete buffer;
inputFile.read(reinterpret_cast<char*>(&entry.section), sizeof(entry.section));
inputFile.read(reinterpret_cast<char*>(&entry.value), sizeof(entry.value));
inputFile.read(reinterpret_cast<char*>(&entry.visibility), sizeof(entry.visibility));
inputFile.read(reinterpret_cast<char*>(&entry.isExt), sizeof(entry.isExt));
inputFile.read(reinterpret_cast<char*>(&entry.size), sizeof(entry.size));
entry.fileId = numOfFiles;
if (entry.id != 0 && entry.id != 1) //undefined and absolute sections
table.insertSymbol(entry);
}
//read sections: code and reloc tables
unsigned numberOfSections;
inputFile.read(reinterpret_cast<char*>(&numberOfSections), sizeof(numberOfSections));
numberOfSections -= 2; //remove UND and ABS
for (int i = 0; i < numberOfSections; i++) {
unsigned labelSize;
SectionData s;
inputFile.read(reinterpret_cast<char*>(&s.id), sizeof(s.id));
inputFile.read(reinterpret_cast<char*>(&labelSize), sizeof(labelSize));
char* buffer = new char[labelSize];
inputFile.read(buffer, labelSize);
s.label.assign(buffer, labelSize);
inputFile.read(reinterpret_cast<char*>(&s.size), sizeof(s.size));
delete buffer;
buffer = new char[s.size];
inputFile.read(buffer, s.size);
s.data.assign(buffer, s.size);
delete buffer;
s.fileId = numOfFiles;
unsigned relocSize;
inputFile.read(reinterpret_cast<char*>(&relocSize), sizeof(relocSize));
for (unsigned j = 0; j < relocSize; j++) {
RelocationEntry r;
inputFile.read(reinterpret_cast<char*>(&r.offset), sizeof(r.offset));
inputFile.read(reinterpret_cast<char*>(&r.relType), sizeof(r.relType));
inputFile.read(reinterpret_cast<char*>(&r.ordinal), sizeof(r.ordinal));
s.relocTable.push_back(r);
}
sections.push_back(s);
}
numOfFiles++;
}
catch (LinkerException g) {
cout << "Error :" << g.getMsg() << endl;
}
}
void Linker::generateHex() {
try {
auto symbols = table.getUnknownUsedSymbols();
if (symbols.size() > 0) {
string msg = "Undefined symbols ";
for (auto s : symbols) {
msg += s + " ";
}
msg += '!';
throw LinkerException(msg);
}
table.createGlobalTable(places);
table.checkIfPlaceable();
//merge sections with the same name, read from relocation table and fill in the information needed
//skip UND and ABS sections and copy others
for (unsigned i = 2; i < table.numSectionsGlobal; i++) {
TableEntry& entry = table.getSymbolGlobal(i);
string data = "";
for (auto section : sections) {
if (section.label == entry.label) {
data += section.data;
}
}
code.insert({ entry.value, data });
}
for (auto section : sections) {
TableEntry& sectionEntry = table.getSymbol(section.id, section.fileId);
for (auto rEntry : section.relocTable) {
TableEntry& entry = table.getSymbol(rEntry.ordinal, section.fileId);
rEntry.offset += sectionEntry.value;
auto mem = code.lower_bound(rEntry.offset);
string block;
if (mem == code.end()) {
mem = prev(code.end());
}
else if (mem->first != rEntry.offset)
{
mem--;
}
int offset = rEntry.offset - mem->first;
if (rEntry.relType == RelocationEntry::R_386_16) {
short value = (mem->second[offset] << 8) | (mem->second[offset + 1]);
value += entry.value;
mem->second[offset] = (value & 0xFF00) >> 8;
mem->second[offset + 1] = (value & 0xFF);
}
else if (rEntry.relType == RelocationEntry::R_386_16D) {
short value = (mem->second[offset + 1] << 8) | (mem->second[offset]);
value += entry.value;
mem->second[offset] = (value & 0xFF);
mem->second[offset + 1] = (value & 0xFF00) >> 8;
}
else if (rEntry.relType == RelocationEntry::R_386_PC16) {
if (entry.id == 1) //ABS
{
short value = (mem->second[offset] << 8) | (mem->second[offset + 1]);
value -= rEntry.offset;
mem->second[offset] = (value & 0xFF00) >> 8;
mem->second[offset + 1] = (value & 0xFF);
}
else {
short value = (mem->second[offset] << 8) | (mem->second[offset + 1]);
value += entry.value - rEntry.offset;
mem->second[offset] = (value & 0xFF00) >> 8;
mem->second[offset + 1] = (value & 0xFF);
}
}
else if (rEntry.relType == RelocationEntry::R_386_PC16D) {
if (entry.id == 1) //ABS
{
short value = (mem->second[offset + 1] << 8) | (mem->second[offset]);
value -= rEntry.offset;
mem->second[offset] = (value & 0xFF);
mem->second[offset + 1] = (value & 0xFF00) >> 8;
}
else {
short value = (mem->second[offset + 1] << 8) | (mem->second[offset]);
value += entry.value - rEntry.offset;
mem->second[offset] = (value & 0xFF);
mem->second[offset + 1] = (value & 0xFF00) >> 8;
}
}
}
}
writeHexFile();
}
catch (LinkerException e) {
cout << "Error :" << e.getMsg() << endl;
}
}
void Linker::generateLinkable() {
table.createGlobalTableLinkable();
//merge section data and reloc tables
for (unsigned i = 2; i < table.numSectionsGlobal; i++) {
TableEntry& entry = table.getSymbolGlobal(i);
SectionData newSecData;
newSecData.id = entry.id;
newSecData.label = entry.label;
newSecData.size = entry.size;
newSecData.data = "";
for (auto section : sections) {
if (section.label == entry.label) {
newSecData.data += section.data;
int offsetSection = table.getSymbol(section.id, section.fileId).value;
for (auto rel : section.relocTable) {
rel.offset += offsetSection;
TableEntry& symbol = table.getSymbol(rel.ordinal, section.fileId);
rel.ordinal = symbol.globalId;
TableEntry& symbolGlobal = table.getSymbolGlobal(symbol.globalId);
if (rel.relType == RelocationEntry::R_386_PC16 && newSecData.id == symbolGlobal.section) {
short addend = ((newSecData.data[rel.offset] & 0xFF) << 8) | (newSecData.data[rel.offset + 1] & 0xFF);
addend += symbol.value - rel.offset;
newSecData.data[rel.offset] = (addend & 0xFF00) >> 8;
newSecData.data[rel.offset + 1] = (addend & 0xFF);
}
else newSecData.relocTable.push_back(rel);
}
}
}
sectionsGlobal.push_back(newSecData);
}
writeObjectFile();
}
void Linker::writeHexFile()
{
int prevAddr = -1;
unsigned offset = -1;
int addr;
for (auto block : code) {
addr = 8 * (block.first / 8);
string& data = block.second;
if (prevAddr != addr) {
if (prevAddr != -1) {
outputFile << endl << endl;
}
offset = block.first % 8;
outputFile << setw(4) << setfill('0') << hex << addr << ": ";
for (unsigned i = 0; i < offset; i++) {
outputFile << " ";
}
}
for (unsigned i = 0; i < data.size(); i++) {
if (offset == 8) {
offset = 0;
addr += 8;
outputFile << endl;
outputFile << setw(4) << setfill('0') << hex << addr << ": ";
}
outputFile << setw(2) << setfill('0') << hex << ((unsigned)data[i] & 0xFF);
if (++offset < 8) {
outputFile << " ";
}
}
prevAddr = addr;
}
}
void Linker::writeObjectFile()
{
table.printSymbolTableGlobal(outputFile);
int outputColumnCnt;
int addr;
for (auto section : sectionsGlobal) {
outputFile << right << "$." << section.label << ":" << hex << section.size << endl;
outputColumnCnt = 0;
addr = 0;
outputFile << setw(4) << setfill('0') << hex << addr << ": ";
for (unsigned i = 0; i < section.data.size(); i++) {
if (outputColumnCnt == 8) {
outputColumnCnt = 0;
addr += 8;
outputFile << endl;
outputFile << setw(4) << setfill('0') << hex << addr << ": ";
}
outputFile << setw(2) << setfill('0') << hex << ((unsigned)section.data[i] & 0xFF);
if (++outputColumnCnt < 8) {
outputFile << " ";
}
}
outputFile << endl << "$relocation data" << endl << left << hex << setw(10) << setfill(' ') << "offset" << setw(12) << "type"
<< setw(10) << "ordinal" << endl;
for (auto r : section.relocTable) {
string relocType = "";
switch (r.relType) {
case RelocationEntry::R_386_16:
relocType = "R_386_16";
break;
case RelocationEntry::R_386_16D:
relocType = "R_386_16D";
break;
case RelocationEntry::R_386_PC16:
relocType = "R_386_PC16";
break;
case RelocationEntry::R_386_PC16D:
relocType = "R_386_PC16D";
break;
default: break;
}
outputFile << setw(10) << r.offset << setw(12) << relocType << r.ordinal << endl;
}
outputFile << endl;
}
}
<file_sep>#ifndef RELOCATIONENTRY_H
#define RELOCATIONENTRY_H
#include <string>
struct RelocationEntry {
enum type{R_386_16 , R_386_PC16, R_386_16D , R_386_PC16D};
RelocationEntry(){}
RelocationEntry(int offset, type relType, int ordinal) : offset(offset),
relType(relType), ordinal(ordinal) {}
int offset;
type relType;
int ordinal;
};
#endif // !RELOCATIONENTRY_H
<file_sep>#include "symbolTable.h"
#include <iomanip>
void MySymbolTable::insertSymbol(TableEntry& entryT) {
if (entryT.isExt) {
if (definedGlobalSymbols.find(entryT.label) == definedGlobalSymbols.end()) {
usedGlobalSymbols.insert(entryT.label);
}
table.push_back(entryT);
return;
}
if (entryT.visibility == 'g') {
if (usedGlobalSymbols.find(entryT.label) != usedGlobalSymbols.end()) {
usedGlobalSymbols.erase(entryT.label);
}
if (definedGlobalSymbols.find(entryT.label) != definedGlobalSymbols.end()) {
string msg = "Redefinition of global symbol ";
msg += entryT.label + "!";
throw LinkerException(msg);
}
else definedGlobalSymbols.insert(entryT.label);
table.push_back(entryT);
}
else {
if (entryT.id == entryT.section && entryT.label != "UND" && entryT.label != "ABS") { //section
table.insert(table.begin() + numSections++, entryT);
}
else {
table.push_back(entryT);
}
}
}
void MySymbolTable::createGlobalTable(unordered_map<string, int>& places)
{
int maxAddr = -1, maxAddrSectionSize = 0;
string name = "";
for (auto addr : places) {
if (addr.second > maxAddr) {
maxAddr = addr.second;
name = addr.first;
}
}
for (unsigned i = 0; name != "" && i < numSections; i++) {
if (name == table[i].label) {
maxAddrSectionSize += table[i].size;
}
}
int oldAddress = (maxAddr == -1 ? 0 : maxAddr) + maxAddrSectionSize;
bool placeAddress = false;
for (unsigned i = 0; i < numSections; i++) {
TableEntry newSec;
TableEntry& sec1 = table[i];
if (sec1.isExt) //that section has been merged already
continue;
int address = oldAddress;
unordered_map<string, int>::iterator g = places.find(sec1.label);
if (g != places.end()) {
address = g->second;
placeAddress = true;
}
newSec.id = idGlobal;
newSec.section = idGlobal;
newSec.label = sec1.label;
newSec.visibility = sec1.visibility;
newSec.value = address;
newSec.size = sec1.size;
newSec.isExt = true;
newSec.fileId = 0;
sec1.value = newSec.value;
address = address + newSec.size;
for (unsigned j = i + 1; j < numSections; j++) {
TableEntry& sec2 = table[j];
if (sec2.label == sec1.label) {
table[j].isExt = true;//mark
table[j].value = address;
newSec.size += sec2.size;
address += sec2.size;
}
}
idGlobal++;
numSectionsGlobal++;
tableGlobal.push_back(newSec);
if (!placeAddress) {
oldAddress += newSec.size;
}
placeAddress = false;
}
vector<int> external;
unordered_map<string, TableEntry> global;
for (unsigned i = numSections; i < table.size(); i++) {
TableEntry& symbol = table[i];
if (symbol.isExt) {
external.push_back(i);
continue;
}
TableEntry newSym;
string label;
for (unsigned j = 0; j < numSections; j++) {
TableEntry& section = table[j];
if (section.id == symbol.section && (symbol.fileId == section.fileId || symbol.section == 1 || symbol.section == 0)) {
newSym.value = symbol.value + section.value;
symbol.value = newSym.value;
label = section.label;
break;
}
}
for (unsigned j = 0; j < numSectionsGlobal; j++) {
if (label == tableGlobal[j].label) {
newSym.section = tableGlobal[j].id;
}
}
newSym.id = idGlobal;
newSym.visibility = symbol.visibility;
newSym.label = symbol.label;
newSym.isExt = symbol.isExt;
newSym.size = symbol.size;
newSym.fileId = symbol.fileId;
if (newSym.visibility == 'g') {
global.insert({ newSym.label, newSym });
}
idGlobal++;
tableGlobal.push_back(newSym);
}
for (unsigned i = 0; i < external.size(); i++) {
TableEntry& extSym = table[external[i]];
unordered_map<string, TableEntry>::iterator get = global.find(extSym.label);
if (get != global.end()) {
extSym.value = get->second.value;
}
else {
TableEntry newSym;
newSym = extSym;
newSym.id = idGlobal++;
tableGlobal.push_back(newSym);
}
}
}
void MySymbolTable::createGlobalTableLinkable()
{
for (unsigned i = 0; i < numSections; i++) {
TableEntry newSec;
TableEntry& sec1 = table[i];
if (sec1.isExt) //that section has been merged already
continue;
int address = 0;
newSec.id = idGlobal;
newSec.section = idGlobal;
newSec.label = sec1.label;
newSec.visibility = sec1.visibility;
newSec.value = address;
newSec.size = sec1.size;
newSec.isExt = false;
newSec.fileId = 0;
sec1.value = newSec.value;
sec1.globalId = idGlobal;
address = address + newSec.size;
for (unsigned j = i + 1; j < numSections; j++) {
TableEntry& sec2 = table[j];
if (sec2.label == sec1.label) {
table[j].isExt = true;//mark
table[j].value = address;
table[j].globalId = idGlobal;
newSec.size += sec2.size;
address += sec2.size;
}
}
idGlobal++;
numSectionsGlobal++;
tableGlobal.push_back(newSec);
}
vector<int> external;
unordered_map<string, TableEntry> global;
for (unsigned i = numSections; i < table.size(); i++) {
TableEntry& symbol = table[i];
if (symbol.isExt) {
external.push_back(i);
continue;
}
TableEntry newSym;
string label;
for (unsigned j = 0; j < numSections; j++) {
TableEntry& section = table[j];
if (section.id == symbol.section && (symbol.fileId == section.fileId || symbol.section == 1 || symbol.section == 0)) {
newSym.value = symbol.value + section.value;
symbol.value = newSym.value;
label = section.label;
break;
}
}
for (unsigned j = 0; j < numSectionsGlobal; j++) {
if (label == tableGlobal[j].label) {
newSym.section = tableGlobal[j].id;
}
}
newSym.id = idGlobal;
newSym.visibility = symbol.visibility;
newSym.label = symbol.label;
newSym.isExt = symbol.isExt;
newSym.size = symbol.size;
newSym.fileId = symbol.fileId;
symbol.globalId = idGlobal;
if (newSym.visibility == 'g') {
global.insert({ newSym.label, newSym });
}
idGlobal++;
tableGlobal.push_back(newSym);
}
for (unsigned i = 0; i < external.size(); i++) {
TableEntry& extSym = table[external[i]];
unordered_map<string, TableEntry>::iterator get = global.find(extSym.label);
if (get != global.end()) {
extSym.value = get->second.value;
extSym.globalId = get->second.id;
}
else {
TableEntry newSym;
newSym = extSym;
newSym.id = idGlobal;
newSym.globalId = idGlobal;
idGlobal++;
tableGlobal.push_back(newSym);
}
}
}
void MySymbolTable::checkIfPlaceable()
{
TableEntry t;
for (unsigned i = 2; i < numSectionsGlobal; i++) {
TableEntry& s1 = tableGlobal[i];
unsigned startAddr = s1.value;
unsigned endAddr = s1.value + s1.size;
for (unsigned j = i + 1; j < numSectionsGlobal; j++) {
TableEntry& s2 = tableGlobal[j];
unsigned startAddr2 = s2.value;
unsigned endAddr2 = s2.value + s2.size;
if (doSectionsOverlap(startAddr, endAddr, startAddr2, endAddr2)) {
string msg = "Sections ";
msg += s1.label + " " + s2.label + " overlap!";
throw LinkerException(msg);
}
}
}
}
bool MySymbolTable::doSectionsOverlap(int start1, int end1, int start2, int end2)
{
if ( end1 <= start2 || start1 >= end2 ) {
return false;
}
else {
return true;
}
}
void MySymbolTable::setOrdinals()
{
for (auto it = table.begin() + sectionId; it != table.end(); it++) {
it->id = sectionId++;
}
}
TableEntry & MySymbolTable::getSymbol(int id, int fileId)
{
if (id == 0) {
return table[id];
}
else if (id == 1) {
return table[id];
}
for (unsigned i = 0; i < table.size(); i++) {
TableEntry& symbol = table[i];
if (symbol.id == id && symbol.fileId == fileId) {
return symbol;
}
}
TableEntry& t = table[0];
return t;
}
TableEntry & MySymbolTable::getSymbolGlobal(unsigned index)
{
return tableGlobal[index];
}
unordered_set<string> MySymbolTable::getUnknownUsedSymbols()
{
return usedGlobalSymbols;
}
void MySymbolTable::printSymbolTable(ofstream & outputFileTxt, ofstream & outputFileBinary)
{
outputFileTxt << setw(10) << left << hex << "id" << setw(15) << "name" << setw(10) << "section" << setw(10) << "value" << setw(12) << "visibility" << setw(10) << "is extern"<< setw(10) << "size" << endl;
for (auto entry : table) {
outputFileTxt << setw(10) << left << hex << entry.id << setw(15) << entry.label << setw(10) << entry.section << setw(10) << entry.value << setw(12) << entry.visibility << setw(10) << entry.isExt << setw(10) << entry.size << endl;
}
unsigned tableSize = table.size();
outputFileBinary.write(reinterpret_cast<char*> (&tableSize), sizeof(tableSize));
for (auto entry : table) {
outputFileBinary.write(reinterpret_cast<char*> (&entry.id), sizeof(entry.id));
unsigned labelSize = entry.label.size();
outputFileBinary.write(reinterpret_cast<char*> (&labelSize), sizeof(labelSize));
outputFileBinary.write(entry.label.c_str(), sizeof(entry.label.size()));
outputFileBinary.write(reinterpret_cast<char*> (&entry.section), sizeof(entry.section));
outputFileBinary.write(reinterpret_cast<char*> (&entry.value), sizeof(entry.value));
outputFileBinary.write(reinterpret_cast<char*> (&entry.visibility), sizeof(entry.visibility));
outputFileBinary.write(reinterpret_cast<char*> (&entry.isExt), sizeof(entry.isExt));
outputFileBinary.write(reinterpret_cast<char*> (&entry.size), sizeof(entry.size));
}
}
void MySymbolTable::printSymbolTableGlobal(ofstream & outputFileTxt)
{
outputFileTxt << setw(10) << left << hex << "id" << setw(15) << "name" << setw(10) << "section" << setw(10) << "value" << setw(12) << "visibility" << setw(10) << "is extern" << setw(10) << "size" << endl;
for (auto entry : tableGlobal) {
outputFileTxt << setw(10) << left << hex << entry.id << setw(15) << entry.label << setw(10) << entry.section << setw(10) << entry.value << setw(12) << entry.visibility << setw(10) << entry.isExt << setw(10) << entry.size << endl;
}
}
bool MySymbolTable::canBeDeclaredGlobal(TableEntry& entry)
{
return !entry.isExt && entry.id == -1 && entry.section != 0 && entry.section != 1 && entry.visibility == 'l'; //id == -1 means that the symbol has yet to receive an id and that it is not a section
}
MySymbolTable::MySymbolTable()
{
//insert undefined and absolute section
table.push_back(TableEntry(sectionId++, "UND", 0, 0, 'l'));//undefined
table.push_back(TableEntry(sectionId++, "ABS", 1, 0, 'l'));//absolute
}
MySymbolTable::~MySymbolTable()
{
}<file_sep>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <unordered_map>
#include <regex>
#include "linker.h"
using namespace std;
int main(int argc, char** argv) {
vector<string> inputFileNames;
string outputFileName = "";
unordered_map<string, int> places;
string option = ""; // hex or linkable
regex placeRegex("^-place=([A-Za-z_]\\w*)@(0[xX][0-9A-Fa-f]{4})");
smatch placeMatch;
bool o_option = false;
for (int i = 1; i < argc; i++) {
string word = argv[i];
if (word.find('-') != string::npos) {//command argument
if (o_option) {
cout << "Wrong command line arguments!" << endl;
return -1;
}
if (word == "-hex" && option.empty())
option = word;
else if (word == "-linkable" && option.empty())
option = word;
else if (regex_search(word, placeMatch, placeRegex)) {
int address = stoi(placeMatch[2], nullptr, 16);
places.insert({ placeMatch[1], address });
}
else if (word == "-o" && outputFileName.empty())
o_option = true;
else {
cout << "Wrong command line arguments!" << endl;
return -1;
}
}
else {//file argument
if (o_option) {
o_option = false;
outputFileName = word;
}
else {
inputFileNames.push_back(word);
}
}
}
if (option.empty() || inputFileNames.empty())
{
cout << "Wrong command line arguments!" << endl;
return -1;
}
if (outputFileName.empty()) {
if (option == "-hex")
outputFileName = "output.hex";
else
outputFileName = "output.o";
}
ifstream inputFile;
ofstream outputFile;
outputFile.open(outputFileName, ios::out);
if (!outputFile) {
cout << "Error: Unable to open text output file" << endl;
outputFile.close();
return 0;
}
Linker linker(places, outputFile);
for (auto fname : inputFileNames) {
inputFile.open(fname, ios::in | ios::binary);
if (!inputFile) {
cout << "Error: Unable to open input file " << fname << endl;
outputFile.close();
return 0;
}
linker.addObjectFile(inputFile);
inputFile.close();
}
if (option == "-hex")
linker.generateHex();
else
linker.generateLinkable();
inputFile.close();
outputFile.close();
return 0;
}<file_sep>#ifndef LINKEREXCEPTION_H
#define LINKEREXCEPTION_H
#include <exception>
#include <string>
using namespace std;
class LinkerException : public exception
{
public:
LinkerException(string msg) : msg(msg) {};
string getMsg() { return msg; }
private:
string msg;
};
#endif<file_sep>#ifndef SECTIONDATA_H
#define SECTIONDATA_H
#include "relocationEntry.h"
#include <vector>
#include <string>
using namespace std;
class SectionData
{
public:
SectionData(){}
~SectionData(){}
int fileId;
int id;
string label;
int size;
vector<RelocationEntry> relocTable;
string data;
};
#endif
<file_sep>#ifndef LINKER_H
#define LINKER_H
#include <fstream>
#include "symbolTable.h"
#include "relocationEntry.h"
#include "SectionData.h"
#include <unordered_map>
#include <map>
class Linker
{
public:
Linker(unordered_map<string, int>& places, ofstream& outputFile) : places(places), outputFile(outputFile) {}
~Linker() {}
void addObjectFile(ifstream& inputFile);
void generateHex();
void generateLinkable();
private:
ofstream& outputFile;
MySymbolTable table;
vector<RelocationEntry> relocTable;
vector<SectionData> sections;
vector<SectionData> sectionsGlobal;
unordered_map<string, int>& places;
map<unsigned, string> code;
unsigned numOfFiles = 0;
void writeHexFile();
void writeObjectFile();
};
#endif // !LINKER_H
<file_sep>#ifndef TABLEENTRY_H
#define TABLEENTRY_H
#include <string>
using namespace std;
struct TableEntry
{
public:
TableEntry(){}
TableEntry(int id, string label, int section, int value, char visibility, bool isExt = false) : id(id), label(label), section(section),
value(value), visibility(visibility), isExt(isExt) {}
~TableEntry(){}
int id = 0;
string label = "";//label name
int section = 0; //0 = undefined, 1 = absolute symbol, otherwise section id
int value = 0;//label value
char visibility = 'l';//'l' for local and 'g' for global
bool isExt = false;//whether symbol is extern
int size = 0;//section size
int fileId = 0;
int globalId = 0;
};
#endif // !TABLEENTRY_H
<file_sep>#ifndef SYMBOLTABLE_H
#define SYMBOLTABLE_H
#include <vector>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <fstream>
#include "TableEntry.h"
#include "linkerException.h"
using namespace std;
class MySymbolTable
{
public:
unsigned numSections = 2;
unsigned numSectionsGlobal = 0;
MySymbolTable();
~MySymbolTable();
void insertSymbol(TableEntry& entry);
void createGlobalTable(unordered_map<string, int>& places);
void createGlobalTableLinkable();
void checkIfPlaceable();
bool doSectionsOverlap(int start1, int end1, int start2, int end2);
//when we reach end of a section we need to update its size in the table
void updateSectionSize(int entryNum, int size);
//save symbol if it has not been already defined or declared as extern so that we can check if there are some unknown symbols
void markAsUsed(string label);
//delete all rows
void clearTable();
//check if there are unknown symbols
bool areAllSymbolsKnown();
//after the first pass we need to enumerate non-section table entries (give them ids)
void setOrdinals();
TableEntry& getSymbol(int id, int fileId);
//return symbol data
TableEntry& getSymbolGlobal(unsigned index);
//acquire undefined and undeclared symbols if any
unordered_set<string> getUnknownUsedSymbols();
void printSymbolTable(ofstream& outputFileTxt, ofstream& outputFileBinary);
void printSymbolTableGlobal(ofstream& outputFileTxt);
private:
unordered_set<string> definedGlobalSymbols;
unordered_set<string> usedGlobalSymbols;
vector<TableEntry> table;
vector<TableEntry> tableGlobal;
int sectionId = 0;
int idGlobal = 0;;
bool canBeDeclaredGlobal(TableEntry& entry);
};
#endif
|
b7d491b78688c7cd6f0f74dc503a6fc9af156378
|
[
"C++"
] | 9
|
C++
|
codeIgy/linker
|
e4eb1518ab8afb2f90b36c8657ad232e6f45a06a
|
005fce467f4e9dde481f68cd0c8c5805238329e6
|
refs/heads/master
|
<repo_name>rhythmof/DjangoStudy<file_sep>/blog/admin.py
from django.contrib import admin
from .models import Post
from .models import Comment
# admin에서 모든 model을 넣을 필요는 없음. admin에서 관리하고싶은 것만 등록
# CRUD 중에 고를 수 있음
# admin.site.register(Post)
# admin.site.register(Comment) #기본 ModelAdmin 으로 동작
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
pass
@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
pass<file_sep>/savanna/urls.py
from django.contrib import admin
from django.urls import path, include
from django.http import HttpResponseRedirect
def root(request):
return HttpResponseRedirect('/blog/')
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')), # path converter
path('shop/', include('shop.urls')),
path('', root),
]<file_sep>/README.md
GitHub Test
GitHub Push Test
GitHub Fetch
cli test
cli test2<file_sep>/requirements.txt
# 필요한 library를 요 파일에 명시하면 heroku에서 알아서 install해줌
django~=2.1.0
gunicorn
requests
beautifulsoup4<file_sep>/blog/models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content=models.TextField()
tags = models.CharField(max_length=10, default='')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Comment(models.Model):
auth_name = models.CharField(max_length=10)
message = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)<file_sep>/blog/views.py
from django.shortcuts import render
from django.http import HttpResponse
from bs4 import BeautifulSoup
import requests
def year_conv(request, year):
# f: python 3.7부터 생긴 기능 (기존 format함수대체)
return HttpResponse(f'''
{year}에 대한 목록
''')
def hello(request, times): # 키워드 인자 방식이므로 이름을 정확하게!
message = "hi" * times
return HttpResponse(message)
def index(request):
return render(request, 'blog/index.html') # render 함수가 response를 생성해서 준다
# 함수에의한 view, class에 의한 view, library에 의한 view로 모두 구현 가능
def naver_real_keyword(request):
res = requests.get("http://naver.com")
html = res.text
soup = BeautifulSoup(html, 'html.parser')
tag_list = soup.select('.PM_CL_realtimeKeyword_rolling .ah_k')
text = '<br/>\n'.join([tag.text for tag in tag_list])
return HttpResponse(text)
def naver_blog_search(request):
# query = request.GET.get('query') # get함수를 쓰면 key가 없으면 none을 Return
# query = requests.GET('query') # 그냥 이렇게만 쓰면 key가 없을 때 에러남
query = request.GET.get('query', '')
post_list = []
msg = f'{query} 검색할거야'
if query:
url = 'https://search.naver.com/search.naver'
params = {
'where' : 'post',
'sm' : 'tab_jum',
'query' : query,
}
res = requests.get(url, params=params)
html = res.text
soup= BeautifulSoup(html, 'html.parser')
tag_list = soup.select('.sh_blog_title')
for tag in tag_list:
post_url = tag['href']
post_title = tag['title']
post_list.append('{}:{}'.format(post_url, post_title))
# return HttpResponse(post_list)
# return render(request, 'blog/naver_blog_search.html', {
# 'query' : query,
# 'post_list' : post_list},)
# else :
# msg = f'{query} 검색할거야'
# return HttpResponse(msg)
return render(request, 'blog/naver_blog_search.html', {
'query' : query,
'post_list' : post_list},)<file_sep>/blog/urls.py
from django.contrib import admin
from django.urls import path
from django.urls import register_converter
from blog.views import hello, index
from blog.views import year_conv
from blog.views import naver_real_keyword
from blog.views import naver_blog_search
from blog.convert import YearConvertDo
app_name = 'blog' # URL Reverse 기능을 할 때, 사용.
register_converter(YearConvertDo,'year')
urlpatterns = [
path('articles/<year:year>', year_conv), # path에서는 반드시 함수를 호출해야함
path('hello/<int:times>/', hello), # path converter
path('', index), # = re_path(r'^$')
path('naver/real_time', naver_real_keyword),
path('naver/blog_search', naver_blog_search),
]<file_sep>/shop/urls.py
from django.urls import path
from shop.views import shop_list
app_name = 'shop' # URL Reverse 기능을 할 때, 사용.
urlpatterns = [
path('shop_list', shop_list),
]
|
4acc85813d5edcc4b2aec4c182b35e90b599d927
|
[
"Markdown",
"Python",
"Text"
] | 8
|
Python
|
rhythmof/DjangoStudy
|
ea8ecf835ceb485f41cdebc358c123034012e0f5
|
fc42748a0dba75e9c12618d1c9462cb75a75e05c
|
refs/heads/master
|
<repo_name>NiclasvanEyk/udpfilesockets<file_sep>/udp_server-BEISPIELPROGRAMM.c
/* Beispiel UDP Echo-Server
* Gekürzt aus Stevens: Unix Network Programming
* getestet unter Ubuntu 10.04 32Bit
*/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SRV_PORT 8998
#define MAX_SOCK 10
#define MAXLINE 512
// Vorwaertsdeklarationen
void dg_echo (int);
void err_abort (char *str);
// Explizite Deklaration zur Vermeidung von Warnungen
void exit (int code);
void *memset (void *s, int c, size_t n);
int main (int argc, char *argv[]) {
// Deskriptor
int sockfd;
// Socket Adresse
struct sockaddr_in srv_addr;
// TCP-Socket erzeugen
if ((sockfd=socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
err_abort("Kann Stream-Socket nicht oeffnen!");
}
// Binden der lokalen Adresse damit Clients uns erreichen
memset ((void *)&srv_addr, '\0', sizeof(srv_addr));
srv_addr.sin_family = AF_INET;
srv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
srv_addr.sin_port = htons(SRV_PORT);
if (bind (sockfd, (struct sockaddr *)&srv_addr,
sizeof(srv_addr)) < 0 ) {
err_abort("Kann lokale Adresse nicht binden, laeuft fremder Server?");
}
printf ("UDP Echo-Server: bereit ...\n");
dg_echo(sockfd);
}
/* dg_echo: Lesen von Daten vom Socket und an den Client zuruecksenden */
void dg_echo (int sockfd) {
int alen, n;
char in[MAXLINE], out[MAXLINE+6];
struct sockaddr_in cli_addr;
for(;;) {
alen = sizeof(cli_addr);
memset((void *)&in,'\0',sizeof(in));
// Daten vom Socket lesen
n = recvfrom(sockfd, in, MAXLINE, 0, (struct sockaddr *)& cli_addr, &alen);
if( n<0 ) {
err_abort ("Fehler beim Lesen des Sockets!");
}
sprintf (out,"Echo: %s",in);
// Daten schreiben
if (sendto(sockfd, out, n+6, 0, (struct sockaddr *) &cli_addr, alen) != n + 6) {
err_abort("Fehler beim Schreiben des Sockets!");
}
}
}
/* Ausgabe von Fehlermeldungen */
void err_abort(char *str){
fprintf(stderr," UDP Echo-Server: %s\n",str);
fflush(stdout);
fflush(stderr);
exit(1);
}
<file_sep>/UDPfilesockets_server/FileWorker.cpp
/*
* 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.
*/
/*
* File: FileWorker.cpp
* Author: niclas
*
* Created on April 13, 2016, 6:47 PM
*/
#include "FileWorker.h"
using namespace std;
/**
* Versucht die Datei zu öffnen, falls das nicht klappt wird this->error auf den
* passenden Fehlerwert gesetzt
* @param filename Pfad zur Datei
*/
FileWorker::FileWorker(string filename, int chunksize, long sid) {
cout << "Erstelle neuen FileWorker, filename: " << filename << ", cs: " << chunksize << ", sid: " << sid << endl;
this->file = new ifstream();
this->sid = sid;
this->chunks = new vector<string>();
this->chunkcounter = 0;
this->width = chunksize;
this->file->open(filename.c_str());
this->status = (this->file->is_open()) ? FILEWORKER_OK : FILEWORKER_FNF;
}
FileWorker::~FileWorker() {
if (this->file != NULL)
this->file->close();
if (this->sid != NULL)
printf("Fileworker %ld closed", this->sid);
}
string FileWorker::getChunk (long nr) {
string chunk;
cout << "FILEWORKER: Reading chunk " << nr << endl;
if (nr >= this->chunkcounter &&
!this->file->eof()) {
// Neuen chunk einlesen
char c;
for (int i=0; i<this->width; i++) {
this->file->get(c);
chunk += c;
}
cout << "FILEWORKER: new chunk: " << chunk << endl;
if (this->file->eof()) {
this->status = FILEWORKER_END;
} else {
chunkcounter++;
}
this->chunks->push_back(chunk);
} else {
// Vorhandenen Chunk zurückgeben
chunk = this->chunks->at(nr);
cout << "FILEWORKER: Chunk cached: " << chunk << endl;
}
cout << "FWW: " << this->file->width() << endl;
return chunk;
}<file_sep>/UDPfilesockets_server/UDP_Server.cpp
/*
* File: UDP_Server.cpp
* Author: jannieyk
*
* Created on 11. April 2016, 15:09
*/
#include "UDP_Server.h"
using namespace std;
UDP_Server::UDP_Server() {
this->sessionCounter = 0;
int port = 8999;
// UDP-Socket erzeugen
if ((this->sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
printf("Kann Stream-Socket nicht oeffnen!");
}
// Binden der lokalen Adresse damit Clients uns erreichen
memset ((void *) &(this->srv_addr), '\0', sizeof(this->srv_addr));
this->srv_addr.sin_family = AF_INET;
this->srv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
this->srv_addr.sin_port = htons(port);
if (bind(this->sockfd, (struct sockaddr *)&(this->srv_addr),
sizeof(this->srv_addr)) < 0 ) {
printf("Kann lokale Adresse nicht binden, laeuft fremder Server?");
}
printf("UDP Server: gestartet ...\n");
}
/**
* Server beginnt Anfragen anzunehmen
* @return Ob es geklappt hat oder nicht
*/
bool UDP_Server::listen () {
int n;
socklen_t alen;
char in[MAXLINE], out[MAXLINE];
struct sockaddr_in cli_addr;
memset((void *) out,'\0',sizeof(char)*(MAXLINE+6));
cout << "Server is listening on port " << htons(this->srv_addr.sin_port) << endl;
for(;;) {
alen = sizeof(cli_addr);
memset((void *)&in,'\0',sizeof(in));
// Daten vom Socket lesen
n = recvfrom(this->sockfd, in, MAXLINE, 0, (struct sockaddr *)& cli_addr, &alen);
if( n < 0 ) {
printf("Fehler beim Lesen des Sockets!");
}
cout << "Neue Request:" << in << endl;
memset((void *) out,'\0',sizeof(char)*(MAXLINE+6));
//buffer leeren
memset((void *) out,'\0',sizeof(char)*(MAXLINE+6));
strcpy(out, this->handleRequest(in).c_str());
// Daten schreiben
if (sendto(this->sockfd, out, strlen(out), 0, (struct sockaddr *) &cli_addr, alen) != strlen(out)) {
printf("Fehler beim Schreiben des Sockets!");
}
}
}
/**
* Bearbeitet eine eingehende Anfrage
* @param in Inhalt der Anfrage
* @return Den output, also das was zurückgeschickt werden soll (response)
*/
string UDP_Server::handleRequest (char* in) {
string input(in);
string method = input.substr(8, 5);
string content = input.substr(13);
string output = "";
cout << "Method: " << method << endl;
if (method == "GETXX") { // Anforderung eines Datei Segments
int sid = this->getSessionID(content);
int chunknr = this->getPackageNumber(content);
FileWorker* worker = this->getFileWorker(sid);
if (worker != NULL &&
worker->status == FILEWORKER_OK) {
cout << "worker ok" << endl;
string data = worker->getChunk(chunknr);
stringstream s_chunknr, s_length;
s_chunknr << chunknr;
s_length << data.length();
output.append("HSOSSTP_DATAX;");
output.append(s_chunknr.str());
output.append(";");
output.append(s_length.str());
output.append(";");
output.append(data);
} else if (worker == NULL) {
// Keinen zugehörigen Fileworker gefunden => keine session
output = SERVER_NOS;
} else if (worker->status == FILEWORKER_FNF) {
output = SERVER_FNF;
} else if (worker->status == FILEWORKER_END) {
cout << "File finished!" << cout;
if (chunknr > worker->chunkcounter) {
output = SERVER_CNF;
} else {
string data = worker->getChunk(chunknr);
stringstream s_chunknr, s_length;
s_chunknr << chunknr;
s_length << data.length();
output.append("HSOSSTP_DATAX;");
output.append(s_chunknr.str());
output.append(";");
output.append(s_length.str());
output.append(";");
output.append(data);
}
}
} else if (method == "INITX") { // Verbindung initiieren
FileWorker* worker = this->spawnFileWorker(this->getFilename(content),
this->getChunkNr(content));
if (worker->status == FILEWORKER_OK) {
stringstream ok;
ok << "HSOSSTP_SIDXX;";
ok << worker->sid;
output = ok.str();
} else if (worker->status == FILEWORKER_FNF) {
// worker->status zurückschicken
output = SERVER_FNF;
}
} else { // Default
printf("Unbekannte Methode");
output = "Unbekannte Methode";
}
cout << "Sende: " << output << endl;
return output;
}
/**
* Erstellt zur Session und Datei einen FileWorker und speichert die Referenz
* @param filename den Dateinamen/den Pfad zur Datei
* @returns Pointer auf den erzeugten worker
*/
FileWorker* UDP_Server::spawnFileWorker (string filename, int chunksize) {
long sessionID = this->sessionCounter;
this->sessionCounter++;
FileWorker* worker = new FileWorker(filename, chunksize, sessionID);
if (worker->status == FILEWORKER_OK) {
cout << "caching reference to worker...." << endl;
this->workers.insert(pair<long, FileWorker*>(sessionID, worker));
}
return worker;
}
/**
* Liefert den entsprechenden FileWorker zurück
* @param sid
* @return Pointer auf den FileWorker oder null, falls er nicht existiert
*/
FileWorker* UDP_Server::getFileWorker(long sid) {
return this->workers.at(sid);
}
/**
* Spaltet einen String auf (an einem bestimmten char/string)
* @param s Der zu aufspaltende String
* @param delim der char wo gespalten werden soll
* @return Einen vector mit einzelnen Strings
*/
vector<string> UDP_Server::split (const string s, const char delim) {
vector<string> tokens;
stringstream ss(s);
string token;
// String teilen
while (getline(ss, token, delim)) {
tokens.push_back(token);
}
return tokens;
}
/**
* Gibt die SessionID aus dem Content String eines Sockets zurück
* @param content der Content Part der Socket Anfrage
* @return Die sessionID
*/
long UDP_Server::getSessionID (string content) {
return atol(this->split(content, ';').at(0).c_str());
}
/**
* Gibt die Chunk nummer aus dem Content String eines Sockets zurück
* @param content der Content Part der Socket Anfrage
* @return Die Chunk nummer
*/
long UDP_Server::getChunkNr (string s) {
return atol(this->split(s, ';').at(1).c_str());
}
string UDP_Server::getFilename (string s) {
return this->split(s, ';').at(2);
}
int UDP_Server::getPackageNumber (string s) {
return atoi(this->split(s, ';').at(2).c_str());
}<file_sep>/UDPfilesockets_server/UDP_Server.h
/*
* File: UDP_Server.h
* Author: jannieyk
*
* Created on 11. April 2016, 15:09
*/
#ifndef UDP_SERVER_H
#define UDP_SERVER_H
#define MAXLINE 255
#include "FileWorker.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <cstdlib>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <map>
#include <vector>
#include <cstring>
#define SERVER_FNF "HSOSSTP_ERROR;FNF"
#define SERVER_CNF "HSOSSTP_ERROR;CNF"
#define SERVER_NOS "HSOSSTP_ERROR;NOS"
using namespace std;
class UDP_Server {
public:
UDP_Server();
bool listen();
private:
int sockfd; // Socket
struct sockaddr_in srv_addr; // Infos zum Server
long sessionCounter;
map<long, FileWorker*> workers; // Map<Sessionkey, Pointer auf zugehörigen Worker>
string handleRequest(char* in);
void initSession();
FileWorker* spawnFileWorker(string filename, int chunksize);
FileWorker* getFileWorker(long sid);
long getSessionID(string s);
string getFilename(string s);
long getChunkNr(string s);
int getPackageNumber(string s);
vector<string> split(const string s, const char delim);
};
#endif /* UDP_SERVER_H */
<file_sep>/UDPfilesockets_server/FileWorker.h
/*
* 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.
*/
/*
* File: FileWorker.h
* Author: niclas
*
* Created on April 13, 2016, 6:47 PM
*/
#ifndef FILEWORKER_H
#define FILEWORKER_H
#define FILEWORKER_OK 200
#define FILEWORKER_FNF 404
#define FILEWORKER_END 42
#include <string>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
class FileWorker {
public:
FileWorker(string filename, int chunksize, long sid);
FileWorker(const FileWorker& orig);
virtual ~FileWorker();
int status;
long sid;
string getChunk(long nr);
long chunkcounter;
private:
ifstream* file;
int width;
vector<string>* chunks;
};
#endif /* FILEWORKER_H */
<file_sep>/UDPfilesockets_server/server.cpp
/*
* File: server.cpp
* Author: jannieyk
*
* Created on 11. April 2016, 15:00
*/
#include <cstdlib>
#include "UDP_Server.h"
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
UDP_Server* server = new UDP_Server();
server->listen();
return 0;
}
|
243ba21da8dc8bef29f72c01a7a5b54e5b0464e4
|
[
"C",
"C++"
] | 6
|
C
|
NiclasvanEyk/udpfilesockets
|
1b153837ec12b06ddc160a70e7551af73ee73a60
|
ee9b01a860d65e2b5111b837fe9dbc88bdedf0da
|
refs/heads/master
|
<repo_name>mlee212/cs180-testparser<file_sep>/testpull.js
// all data
var data = []
// each line
var obj = []
let match
const lineReader = require('readline').createInterface({
input: require('fs').createReadStream('testpull.txt')
});
lineReader.on('line', function (line) {
var splitter = new RegExp(/[^,]+/,'g')
//data.push({txt: match[2]})
console.log('Line from file:', line);
//match = splitter.exec(line)
while ((match = splitter.exec(line)) !== null) {
console.log(`Found ${match[0]} start=${match.index} end=${splitter.lastIndex}.`);
obj.push(match[0])
// expected output: "Found football start=6 end=14."
// expected output: "Found foosball start=16 end=24."
}
data.push(obj)
console.log(data)
obj = []
});
// var data = ["David", "Cynthia", "Raymond"]
// for(var i = 0; i < 10; i++){
// }
// /((?:-)*\d+(?:[-.]\d+)*(?:[ :]\d+)*)|(\w+(?:[- \/]\w+)*(?:[.])*)/gm
// var line = data.readline()
// console.log(line)
|
364f6e274f34e6e59de673e23abd089a0feaffe5
|
[
"JavaScript"
] | 1
|
JavaScript
|
mlee212/cs180-testparser
|
51f6f9ad678fdc16f1d2f2b8094a3a9128abb3b3
|
2d0761cb7bfa1ffaf9e441ef9887893acddda044
|
refs/heads/master
|
<file_sep>import Link from "next/link";
import styled from "styled-components";
import Signin from "../components/Signin";
import { BREAKPOINTS } from "../components/styles/Layout";
import { toRem } from "../components/utils/unitConversion";
const BackgroundWrapper = styled.div`
position: relative;
width: 100vw;
min-height: 100vh;
background-image: url("../static/images/background-pattern.jpg");
background-size: cover;
background-repeat: no-repeat;
@media (max-width: ${BREAKPOINTS.mobile.large}) {
padding: ${toRem(40)} 0;
}
`;
const SigninPosition = styled.div`
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
@media (max-width: ${BREAKPOINTS.mobile.large}) {
position: relative;
left: 0;
top: 0;
transform: none;
}
`;
const SigninPage = props => (
<BackgroundWrapper>
<SigninPosition>
<Signin />
</SigninPosition>
</BackgroundWrapper>
);
export default SigninPage;
<file_sep>import React, { Component } from "react";
import { Mutation } from "react-apollo";
import gql from "graphql-tag";
import styled from "styled-components";
import Router from "next/router";
import { NOTES_QUERY } from "../InfluencerNotes";
import { toRem } from "../utils/unitConversion";
import { BREAKPOINTS, GRID } from "../styles/Layout";
import TYPE from "../styles/Typography";
import ZINDEX from "../styles/Zindex";
import ANIMATION from "../styles/Animation";
import { CardContainer } from "../CardContainer";
import { TextFieldSimple } from "../TextField";
import { TextAreaSimple } from "../TextArea";
import Select from "../Select";
import Button from "../Button";
import Error from "../ErrorMessage";
import CloseIcon from "react-svg-loader!../../static/icons/input/cancel/default.svg";
const BackgroundOverlay = styled.div`
background-color: ${props => props.theme.background.overlay};
${GRID.wrapper}
max-width: none;
width: calc(100vw - ${toRem(200)});
transform: translateX(${toRem(200)});
height: 0;
min-height: 100vh;
padding: ${toRem(60)} 0;
position: fixed;
overflow: hidden;
left: 0;
top: 0;
z-index: ${ZINDEX.overlay};
${ANIMATION.default}
transition-property: opacity;
pointer-events: none;
opacity: 0;
&.show {
pointer-events: auto;
opacity: 1;
overflow-y: scroll;
}
@media (max-width: ${BREAKPOINTS.tablet.large}) {
transform: translateX(6.5em);
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
transform: translateX(4rem);
}
`;
const ModalWrapper = styled.div`
position: relative;
${GRID.container}
`;
const Modal = styled(CardContainer)`
position: relative;
grid-column: 2 /12;
margin-bottom: 0;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: 1 /9;
padding: ${toRem(20)};
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: 1 /5;
padding: ${toRem(20)};
}
`;
const ModalHeader = styled.div`
padding-bottom: ${toRem(20)};
border-bottom: 1px solid ${props => props.theme.color.subdued};
`;
const ModalTitle = styled.h4`
${TYPE.heading.feature.ink}
display: inline-block;
margin: 0;
max-width: calc(100% - 2.25rem);
`;
const ModalClose = styled.button`
border: none;
background: none;
padding: 0;
float: right;
width: 2rem;
height: 2rem;
margin-bottom: 0.25rem;
:focus {
outline: none;
}
`;
const ModalInput = styled.div`
padding-top: ${toRem(40)};
margin-bottom: ${toRem(20)};
> div {
margin: 0;
margin-bottom: ${toRem(20)};
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
width: 100%;
}
`;
const NoteContent = styled(TextAreaSimple)`
margin: 0;
display: block;
margin-bottom: ${toRem(20)};
`;
const ModalButtons = styled.div`
float: right;
> button {
margin-top: 0;
margin-bottom: 0;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
float: left;
> button {
display: block;
margin-left: 0;
margin-bottom: ${toRem(10)};
}
}
`;
const CREATE_NOTE_MUTATION = gql`
mutation CREATE_NOTE_MUTATION(
$content: String!
$isShown: Boolean!
$influencerId: String!
) {
createNote(
content: $content
isShown: $isShown
influencerId: $influencerId
) {
createdAt
}
}
`;
class AddNoteModal extends Component {
state = {
show: this.props.show,
content: "",
isShown: true,
influencerId: this.props.influencerId
};
handleChange = e => {
const { name, type, value } = e.target;
const val = type === "number" ? parseFloat(value) : value;
this.setState({ [name]: val });
};
componentWillReceiveProps(props) {
this.setState({ show: props.show });
}
render() {
return (
<BackgroundOverlay className={this.state.show ? "show" : null}>
<ModalWrapper>
<Modal>
<Mutation
mutation={CREATE_NOTE_MUTATION}
variables={this.state}
refetchQueries={[
{
query: NOTES_QUERY,
variables: { id: this.state.influencerId }
}
]}
>
{(createNote, { loading, error }) => (
<form
onSubmit={async e => {
e.preventDefault();
const res = await createNote();
this.setState({ content: "" });
this.props.hide();
}}
>
<Error error={error} />
<fieldset disabled={loading} aria-busy={loading}>
<ModalHeader>
<ModalTitle>Add a Note</ModalTitle>
<ModalClose type="button" onClick={this.props.hide}>
<CloseIcon />
</ModalClose>
</ModalHeader>
<ModalInput>
<NoteContent
label="Note"
labelFor="note"
textInputName="content"
textInputPlaceholder="Add a quick note"
inputType="secondary"
required
value={this.state.content}
onChange={this.handleChange}
/>
</ModalInput>
<ModalButtons>
<Button buttonType="primary" type="submit">
Submit
</Button>
<Button
buttonType="secondary"
type="button"
onClick={this.props.hide}
>
Cancel
</Button>
</ModalButtons>
</fieldset>
</form>
)}
</Mutation>
</Modal>
</ModalWrapper>
</BackgroundOverlay>
);
}
}
export default AddNoteModal;
export { CREATE_NOTE_MUTATION };
<file_sep>import React, { Component } from "react";
import { Query } from "react-apollo";
import Head from "next/head";
import Router from "next/router";
import gql from "graphql-tag";
import styled from "styled-components";
import { toRem } from "./utils/unitConversion";
import { GRID, BREAKPOINTS } from "./styles/Layout";
import TYPE from "./styles/Typography";
import Error from "./ErrorMessage";
import ContentWrapper from "./ContentWrapper";
import Button from "./Button";
import InfluencerCard from "./InfluencerCard";
import InfluencerLoggedActivities from "./InfluencerLoggedActivities";
import InfluencerNotes from "./InfluencerNotes";
import AddLoggedActivityModal from "./modals/AddLoggedActivity";
import AddNoteModal from "./modals/AddNote";
import User from "./User";
const InfluencerContainer = styled.div`
${GRID.container};
grid-row-gap: 1.5rem;
padding: ${toRem(40)} 0;
`;
const InfluencerHeader = styled.div`
grid-column: span 12;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: span 8;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: span 4;
}
> .backButton {
display: block;
margin: ${toRem(5)} 0;
}
`;
const SINGLE_INFLUENCER_QUERY = gql`
query SINGLE_INFLUENCER_QUERY($id: ID!) {
influencer(where: { id: $id }) {
id
firstName
lastName
phone
description
thumbnail
image
activeCampaigns
pastCampaigns
}
}
`;
class Influencer extends Component {
state = {
showAddLoggedActivityModal: false,
showAddNoteModal: false,
loggedIn: false
};
showActivityModal = () => {
this.setState({ showAddLoggedActivityModal: true });
document.querySelector("body").classList.add("modalOpen");
};
hideActivityModal = () => {
this.setState({ showAddLoggedActivityModal: false });
document.querySelector("body").classList.remove("modalOpen");
};
showNoteModal = () => {
this.setState({ showAddNoteModal: true });
document.querySelector("body").classList.add("modalOpen");
};
hideNoteModal = () => {
this.setState({ showAddNoteModal: false });
document.querySelector("body").classList.remove("modalOpen");
};
render() {
return (
<User>
{({ data: { loggedInUser } }) => (
<>
{/* {loggedInUser ? this.setState({ loggedIn: true }) : null} */}
<AddLoggedActivityModal
show={this.state.showAddLoggedActivityModal}
hide={this.hideActivityModal}
influencerId={this.props.id}
/>
<AddNoteModal
show={this.state.showAddNoteModal}
hide={this.hideNoteModal}
influencerId={this.props.id}
/>
<ContentWrapper>
<InfluencerContainer>
<InfluencerHeader>
<Button
className="backButton"
buttonType="outline"
onClick={() => Router.back()}
>
← Back to Influencers
</Button>
</InfluencerHeader>
<Query
query={SINGLE_INFLUENCER_QUERY}
variables={{ id: this.props.id }}
>
{({ data, error, loading }) => {
if (loading) return <p>Loading...</p>;
if (error) return <Error error={error} />;
if (!data.influencer)
return <p>No influencer found for {this.props.id}</p>;
const influencer = data.influencer;
return (
<>
<Head>
<title>fence | {influencer.firstName}</title>
</Head>
<InfluencerCard
influencer={influencer}
key={influencer.id}
/>
<InfluencerLoggedActivities
influencer={influencer}
showModal={this.showActivityModal}
/>
<InfluencerNotes
influencer={influencer}
showModal={this.showNoteModal}
/>
</>
);
}}
</Query>
</InfluencerContainer>
</ContentWrapper>
</>
)}
</User>
);
}
}
export default Influencer;
<file_sep>import THEME from "./Theme";
const TYPE = {
displayLarge: {
feature: {
white: `
color: ${THEME.color.gray.white};
font-size: 3.375rem;
line-height: 5.0625rem;
font-family: 'Crimson Text';
font-weight: 600;
margin: 0;
`,
subdued: `
color: ${THEME.color.gray.subdued};
font-size: 3.375rem;
line-height: 5.0625rem;
font-family: 'Crimson Text';
font-weight: 600;
margin: 0;
`,
ink: `
color: ${THEME.color.gray.ink};
font-size: 3.375rem;
line-height: 5.0625rem;
font-family: 'Crimson Text';
font-weight: 600;
margin: 0;
`
}
},
displaySmall: {
feature: {
white: `
color: ${THEME.color.gray.white};
font-size: 2.25rem;
line-height: 3.375rem;
font-family: 'Crimson Text';
font-weight: 600;
margin: 0;
`,
subdued: `
color: ${THEME.color.gray.subdued};
font-size: 2.25rem;
line-height: 3.375rem;
font-family: 'Crimson Text';
font-weight: 600;
margin: 0;
`,
ink: `
color: ${THEME.color.gray.ink};
font-size: 2.25rem;
line-height: 3.375rem;
font-family: 'Crimson Text';
font-weight: 600;
margin: 0;
`
}
},
heading: {
feature: {
white: `
color: ${THEME.color.gray.white};
font-size: 1.5rem;
line-height: 2.25rem;
font-family: 'Crimson Text';
font-weight: 700;
margin: 0;
letter-spacing: -.01875rem;
`,
subdued: `
color: ${THEME.color.gray.subdued};
font-size: 1.5rem;
line-height: 2.25rem;
font-family: 'Crimson Text';
font-weight: 700;
margin: 0;
letter-spacing: -.01875rem;
`,
ink: `
color: ${THEME.color.gray.ink};
font-size: 1.5rem;
line-height: 2.25rem;
font-family: 'Crimson Text';
font-weight: 700;
margin: 0;
letter-spacing: -.01875rem;
`
},
primary: {
white: `
color: ${THEME.color.gray.white};
font-size: 1.5rem;
line-height: 2.25rem;
font-family: 'Lato';
font-weight: 700;
margin: 0;
`,
subdued: `
color: ${THEME.color.gray.subdued};
font-size: 1.5rem;
line-height: 2.25rem;
font-family: 'Lato';
font-weight: 700;
margin: 0;
`,
ink: `
color: ${THEME.color.gray.ink};
font-size: 1.5rem;
line-height: 2.25rem;
font-family: 'Lato';
font-weight: 700;
margin: 0;
`
}
},
subheading: {
feature: {
white: `
color: ${THEME.color.gray.white};
font-size: 1.25rem;
line-height: 1.75rem;
font-family: 'Crimson Text';
font-weight: 400;
margin: 0;
`,
subdued: `
color: ${THEME.color.gray.subdued};
font-size: 1.25rem;
line-height: 1.75rem;
font-family: 'Crimson Text';
font-weight: 400;
margin: 0;
`,
ink: `
color: ${THEME.color.gray.ink};
font-size: 1.25rem;
line-height: 1.75rem;
font-family: 'Crimson Text';
font-weight: 400;
margin: 0;
`
},
primary: {
white: `
color: ${THEME.color.gray.white};
font-size: 1rem;
line-height: 1.5rem;
font-family: 'Lato';
font-weight: 700;
letter-spacing: .0375rem;
text-transform: uppercase;
margin: 0;
`,
subdued: `
color: ${THEME.color.gray.subdued};
font-size: 1rem;
line-height: 1.5rem;
font-family: 'Lato';
font-weight: 700;
letter-spacing: .0375rem;
text-transform: uppercase;
margin: 0;
`,
ink: `
color: ${THEME.color.gray.ink};
font-size: 1rem;
line-height: 1.5rem;
font-family: 'Lato';
font-weight: 700;
letter-spacing: .0375rem;
text-transform: uppercase;
margin: 0;
`
}
},
body: {
feature: {
white: `
color: ${THEME.color.gray.white};
font-size: 1rem;
line-height: 1.5rem;
font-family: 'Crimson Text';
font-weight: 400;
margin: 0;
`,
subdued: `
color: ${THEME.color.gray.subdued};
font-size: 1rem;
line-height: 1.5rem;
font-family: 'Crimson Text';
font-weight: 400;
margin: 0;
`,
ink: `
color: ${THEME.color.gray.ink};
font-size: 1rem;
line-height: 1.5rem;
font-family: 'Crimson Text';
font-weight: 400;
margin: 0;
`
},
primary: {
white: `
color: ${THEME.color.gray.white};
font-size: 1rem;
line-height: 1.5rem;
font-family: 'Lato';
font-weight: 400;
margin: 0;
`,
subdued: `
color: ${THEME.color.gray.subdued};
font-size: 1rem;
line-height: 1.5rem;
font-family: 'Lato';
font-weight: 400;
margin: 0;
`,
ink: `
color: ${THEME.color.gray.ink};
font-size: 1rem;
line-height: 1.5rem;
font-family: 'Lato';
font-weight: 400;
margin: 0;
`
}
},
caption: {
feature: {
white: `
color: ${THEME.color.gray.white};
font-size: .6875rem;
line-height: 1rem;
font-family: 'Crimson Text';
font-weight: 400;
margin: 0;
`,
subdued: `
color: ${THEME.color.gray.subdued};
font-size: .6875rem;
line-height: 1rem;
font-family: 'Crimson Text';
font-weight: 400;
margin: 0;
`,
ink: `
color: ${THEME.color.gray.ink};
font-size: .6875rem;
line-height: 1rem;
font-family: 'Crimson Text';
font-weight: 400;
margin: 0;
`
},
primary: {
white: `
color: ${THEME.color.gray.white};
font-size: .6875rem;
line-height: 1rem;
font-family: 'Lato';
font-weight: 400;
margin: 0;
`,
subdued: `
color: ${THEME.color.gray.subdued};
font-size: .6875rem;
line-height: 1rem;
font-family: 'Lato';
font-weight: 400;
margin: 0;
`,
ink: `
color: ${THEME.color.gray.ink};
font-size: .6875rem;
line-height: 1rem;
font-family: 'Lato';
font-weight: 400;
margin: 0;
`
}
}
};
export default TYPE;
<file_sep>const BREAKPOINTS = {
mobile: {
small: "375px",
large: "680px"
},
tablet: {
small: "840px",
large: "1140px"
},
desktop: {
small: "1280px",
large: "1440px"
}
};
const GRID = {
wrapper: `
display: block;
margin: 0 auto;
width: calc(100vw - 12.5rem - 4rem);
max-width: 960px;
transform: translateX(6.25rem);
@media (max-width: ${BREAKPOINTS.tablet.large}) {
width: calc(100vw - 6.5rem);
transform: translateX(3.25em);
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
width: calc(100vw - 4rem);
transform: translateX(2rem);
}
`,
container: `
display: grid;
max-width: 60rem;
margin: 0 auto;
grid-template-columns: repeat( 12, 1fr );
grid-column-gap: 1.5rem;
grid-row-gap: 2.5rem;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
max-width: calc(100vw - 4rem - 6.5rem);
grid-template-columns: repeat( 8, 1fr );
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
max-width: calc(100vw - 2rem - 4rem);
grid-template-columns: repeat( 4, 1fr );
}
`
};
const MARKETING_GRID = {
wrapper: `
display: block;
margin: 0 auto;
width: calc(100vw - 4rem);
max-width: 960px;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
max-width: calc(100vw - 4rem);
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
max-width: calc(100vw - 2rem);
}
`,
container: `
display: grid;
max-width: 60rem;
margin: 0 auto;
grid-template-columns: repeat( 12, 1fr );
grid-gap: 1.5rem;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
max-width: calc(100vw - 4rem);
grid-template-columns: repeat( 8, 1fr );
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
max-width: calc(100vw - 2rem);
grid-template-columns: repeat( 4, 1fr );
}
`
};
export { GRID, MARKETING_GRID, BREAKPOINTS };
<file_sep># fence
#### Setup
Run `npm install` in both the frontend and backend folders in dev.
#### Running fence
To run the app, in both fronend and backend folders, run `npm run dev`
The app can be accessed at `localhost:7777` with the GraphQL playground accessible at `localhost:4444`.
#### .env Secrets and Keys
The app won't run without these. If you've been provided the keys, update the .env.sample file in the backend folder with the secrets. Then rename it just '.env'.
#### Currently Available
The influencers overview page is completed. You can see all the influencers in the database at `localhost:7777/influencers` or by using the nav and selecting `influencers`. Here you can create a new influencer via the `+Add a New Influencer` button in the top right. Fill out the info and a new influencer will be created. You can see this new influencer through refreshing the page (appending the new influencer without reload is slotted for later).
To Note:
Images are stored on Cloudinary, which will be the image CDN of choice for this project.
Each influencer links to their corresponding profile page. Currently, these pages show more details about the influencer. The most detailed influencer atm is `<NAME>`, so select that influencer to get a better overview of what details are stored. Each of the categories are a different query and this component can be found in `frontend/components/InfluencerCard.js`.
Alongside these pages, you can see an overview of the smaller and more granular components at `localhost:7777/components`.
<file_sep>import React, { Component } from "react";
import styled from "styled-components";
import Influencers from "../components/Influencers";
import AdminHeader from "../components/AdminHeader";
// const InfluencersPage = props => <Influencers />;
const InfluencersPage = props => (
<>
<AdminHeader />
<Influencers />
</>
);
export default InfluencersPage;
<file_sep>import React, { Component } from "react";
import { Query } from "react-apollo";
import gql from "graphql-tag";
import styled from "styled-components";
import Router from "next/router";
import { toRem } from "./utils/unitConversion";
import { GRID, BREAKPOINTS } from "./styles/Layout";
import TYPE from "./styles/Typography";
import User from "./User";
import ContentWrapper from "./ContentWrapper";
import InfluencerSnapshotCard from "./InfluencerSnapshotCard";
import Button from "./Button";
import AddInfluencerModal from "./modals/AddInfluencer";
const InfluencersContainer = styled.div`
${GRID.container};
grid-gap: 1.5rem;
padding: ${toRem(40)} 0;
@media (max-width: ${BREAKPOINTS.mobile.large}) {
display: block;
}
`;
const InfluencersHeader = styled.div`
grid-column: span 12;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: span 8;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: span 4;
}
`;
const InfluencersTitle = styled.h1`
${TYPE.displaySmall.feature.ink}
display: inline-block;
margin-top: 0;
@media (max-width: ${BREAKPOINTS.mobile.large}) {
display: block;
margin-bottom: ${toRem(20)};
}
`;
const AddInfluencerButton = styled(Button)`
margin: 0;
margin-top: ${toRem(5)};
float: right;
@media (max-width: ${BREAKPOINTS.mobile.large}) {
float: none;
margin: 0;
margin-bottom: ${toRem(20)};
}
`;
const InfluencersEmpty = styled.p`
${TYPE.body.primary.subdued}
font-style: italic;
display: block;
text-align: center;
padding-top: ${toRem(60)};
cursor: pointer;
grid-column: span 12;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: span 8;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: span 4;
}
`;
const SeeMore = styled.a`
${TYPE.body.primary.ink};
font-weight: 700;
color: ${props => props.theme.color.green.feature};
display: block;
text-align: center;
cursor: pointer;
padding-top: ${toRem(10)};
grid-column: span 12;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: span 8;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: span 4;
}
`;
const ALL_INFLUENCERS_QUERY = gql`
query ALL_INFLUENCERS_QUERY($id: ID!, $cursor: String) {
influencersConnection(
first: 9
after: $cursor
where: { user: { id: $id } }
orderBy: updatedAt_DESC
) {
pageInfo {
hasNextPage
endCursor
}
edges {
node {
id
firstName
lastName
phone
description
thumbnail
image
updatedAt
activeCampaigns
pastCampaigns
}
}
}
}
`;
class Influencers extends Component {
state = {
showAddInfluencerModal: false,
loggedIn: false
};
showModal = () => {
this.setState({ showAddInfluencerModal: true });
document.querySelector("body").classList.toggle("modalOpen");
};
render() {
return (
<User>
{({ data: { loggedInUser } }) => (
<>
<AddInfluencerModal
show={this.state.showAddInfluencerModal}
userId={loggedInUser ? loggedInUser.id : null}
/>
<ContentWrapper>
<InfluencersContainer>
<InfluencersHeader>
<InfluencersTitle>Influencers</InfluencersTitle>
<AddInfluencerButton
buttonType="primary"
onClick={this.showModal}
>
+ Add a New Influencer
</AddInfluencerButton>
</InfluencersHeader>
{loggedInUser && (
<Query
query={ALL_INFLUENCERS_QUERY}
variables={{ id: loggedInUser.id }}
>
{({ data, error, loading, fetchMore }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
const influencersConnection = data.influencersConnection;
if (influencersConnection.edges.length == 0) {
return (
<InfluencersEmpty>
No influencers added yet.
</InfluencersEmpty>
);
}
return (
<>
{influencersConnection.edges.map(influencer => (
<InfluencerSnapshotCard
influencer={influencer.node}
key={influencer.node.id}
/>
))}
{influencersConnection.pageInfo.hasNextPage ? (
<SeeMore
onClick={() => {
fetchMore({
variables: {
cursor:
influencersConnection.pageInfo.endCursor
},
updateQuery: (
previousResult,
{ fetchMoreResult }
) => {
const newEdges =
fetchMoreResult.influencersConnection
.edges;
const pageInfo =
fetchMoreResult.influencersConnection
.pageInfo;
return newEdges.length
? {
influencersConnection: {
__typename:
previousResult
.influencersConnection
.__typename,
edges: [
...previousResult
.influencersConnection.edges,
...newEdges
],
pageInfo
}
}
: previousResult;
}
});
}}
>
See More
</SeeMore>
) : null}
</>
);
}}
</Query>
)}
</InfluencersContainer>
</ContentWrapper>
</>
)}
</User>
);
}
}
export default Influencers;
export { ALL_INFLUENCERS_QUERY };
<file_sep>import React, { Component } from "react";
import styled from "styled-components";
import ANIMATION from "./styles/Animation";
import TYPE from "./styles/Typography";
import { toRem } from "./utils/unitConversion";
const SelectWrapper = styled.div`
margin: 1rem;
> button {
margin-top: 0;
margin-bottom: 0;
}
`;
const Label = styled.label`
${TYPE.body.primary.ink}
margin: 0;
display: block;
`;
const SelectContainer = styled.select`
border-radius: 0.125rem;
border-width: 0.0625rem;
border-style: solid;
padding: 0.625rem ${toRem(10)};
height: 2.75rem;
${TYPE.body.primary.white}
${ANIMATION.default}
float: ${props => props.float};
background: ${props => props.theme.color.green.feature};
color: ${props => (props.color ? props.color : props.theme.color.gray.white)};
border-color: ${props => props.theme.color.green.feature};
margin: ${toRem(5)} 0 0 0;
width: 100%; */
:hover {
box-shadow: ${props => props.theme.shadow.drop};
}
:focus {
border-color: ${props => props.theme.color.green.darkest};
box-shadow: inset 0 0 0 0.0625rem
${props => props.theme.color.green.darkest};
}
:active {
box-shadow: ${props => props.theme.shadow.inner};
}
`;
const SelectOption = styled.option``;
const Select = props => {
const options = propOptions => {
return (
<>
{propOptions.map(option => (
<SelectOption
value={option.charAt(0).toLowerCase() + option.substring(1)}
>
{option.charAt(0).toUpperCase() + option.substring(1)}
</SelectOption>
))}
</>
);
};
return (
<SelectWrapper className={props.className}>
<Label htmlfor={props.labelFor ? props.labelFor : "title"}>
{props.label ? props.label : "Label"}
</Label>
<SelectContainer
float={props.float}
color={props.color}
onChange={props.onChange}
>
{options(props.options)}
</SelectContainer>
</SelectWrapper>
);
};
export default Select;
<file_sep>import React, { Component } from "react";
import styled from "styled-components";
import PropTypes from "prop-types";
import { BREAKPOINTS } from "../components/styles/Layout";
import { toRem } from "./utils/unitConversion";
import TYPE from "./styles/Typography";
import Facebook from "react-svg-loader!../static/icons/social/ink/facebook.svg";
import Instagram from "react-svg-loader!../static/icons/social/ink/instagram.svg";
import Snapchat from "react-svg-loader!../static/icons/social/ink/snapchat.svg";
import Twitter from "react-svg-loader!../static/icons/social/ink/twitter.svg";
import Celebration from "react-svg-loader!../static/icons/social/ink/celebration.svg";
import Meeting from "react-svg-loader!../static/icons/social/ink/meeting.svg";
import Event from "react-svg-loader!../static/icons/social/ink/event.svg";
const InfluencerActivityWrapper = styled.div`
padding: ${toRem(10)};
border-top: ${toRem(1)} solid ${props => props.theme.color.gray.ink};
display: flex;
justify-content: space-between;
@media (max-width: ${BREAKPOINTS.mobile.large}) {
display: block;
}
`;
const InfluencerActivityDescription = styled.div`
display: flex;
margin-right: ${toRem(30)};
`;
const InfluencerActivityIconWrapper = styled.span`
display: inline-block;
flex: 0 0 1rem;
width: 1rem;
height: 1rem;
margin-right: ${toRem(5)};
transform: translateY(0.25rem);
> svg {
vertical-align: top;
}
`;
const InfluencerActivityDescriptionText = styled.p`
vertical-align: top;
display: inline-block;
${TYPE.body.primary.ink}
margin-bottom: 0;
`;
const InfluencerActivityDate = styled.p`
/* display: inline-block; */
vertical-align: middle;
text-align: right;
flex: 0 0 ${toRem(128)};
width: ${toRem(128)};
${TYPE.body.primary.ink}
margin-bottom: 0;
@media (max-width: ${BREAKPOINTS.mobile.large}) {
display: block;
${TYPE.caption.primary.subdued}
text-align: left;
margin-top: ${toRem(10)};
}
`;
class InfluencerLoggedActivity extends Component {
static propTpes = {
loggedActivity: PropTypes.object.isRequired
};
activityIcon(activityType) {
if (activityType == "INSTAGRAM") {
return <Instagram />;
} else if (activityType == "TWITTER") {
return <Twitter />;
} else if (activityType == "FACEBOOK") {
return <Facebook />;
} else if (activityType == "EVENT") {
return <Event />;
} else if (activityType == "MEETING") {
return <Meeting />;
} else if (activityType == "CALL") {
return <Meeting />;
} else if (activityType == "COFFEE") {
return <Meeting />;
} else if (activityType == "CELEBRATION") {
return <Celebration />;
} else if (activityType == "OTHER") {
return <Celebration />;
}
}
formatDate(date) {
const dateOptions = { month: "long", day: "numeric", year: "numeric" };
const activityDate = new Date(date).toLocaleDateString(
"en-US",
dateOptions
);
return <InfluencerActivityDate>{activityDate}</InfluencerActivityDate>;
}
render() {
const { loggedActivity } = this.props;
return (
<InfluencerActivityWrapper>
<InfluencerActivityDescription>
<InfluencerActivityIconWrapper>
{this.activityIcon(loggedActivity.eventType)}
</InfluencerActivityIconWrapper>
<InfluencerActivityDescriptionText>
{loggedActivity.description}
</InfluencerActivityDescriptionText>
</InfluencerActivityDescription>
{this.formatDate(loggedActivity.updatedAt)}
</InfluencerActivityWrapper>
);
}
}
export default InfluencerLoggedActivity;
<file_sep>import Link from "next/link";
import Influencer from "../components/Influencer";
import AdminHeader from "../components/AdminHeader";
const InfluencerProfile = props => (
<>
<AdminHeader />
<Influencer id={props.query.id} />
</>
);
export default InfluencerProfile;
<file_sep>import Link from "next/link";
import styled from "styled-components";
import Signup from "../components/Signup";
import { BREAKPOINTS } from "../components/styles/Layout";
import { toRem } from "../components/utils/unitConversion";
const BackgroundWrapper = styled.div`
position: relative;
width: 100vw;
min-height: 100vh;
background-image: url("../static/images/background-pattern.jpg");
background-size: cover;
background-repeat: no-repeat;
@media (max-width: ${BREAKPOINTS.mobile.large}) {
padding: ${toRem(40)} 0;
}
`;
const SignupPosition = styled.div`
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
@media (max-width: ${BREAKPOINTS.mobile.large}) {
position: relative;
left: 0;
top: 0;
transform: none;
}
`;
const SignupPage = props => (
<>
<BackgroundWrapper>
<SignupPosition>
<Signup />
</SignupPosition>
</BackgroundWrapper>
</>
);
export default SignupPage;
<file_sep>import styled from "styled-components";
import { toRem } from "./utils/unitConversion";
import TYPE from "./styles/Typography";
import ANIMATION from "./styles/Animation";
const TagWrapper = styled.a`
border-radius: 0.125rem;
border-width: 0.0625rem;
border-style: solid;
padding: ${toRem(5)} ${toRem(10)};
height: 2.75rem;
${TYPE.body.primary.white}
${ANIMATION.default}
margin: 0 1rem 1rem 0;
float: ${props => props.float};
cursor: pointer;
:hover {
box-shadow: ${props => props.theme.shadow.drop};
}
:focus {
outline: none;
}
&.active {
background: ${props => props.theme.color.green.feature};
color: ${props =>
props.color ? props.color : props.theme.color.gray.white};
border-color: ${props => props.theme.color.green.feature};
:focus {
border-color: ${props => props.theme.color.green.darkest};
box-shadow: inset 0 0 0 0.0625rem
${props => props.theme.color.green.darkest};
}
:active {
box-shadow: ${props => props.theme.shadow.inner};
}
}
&.upcoming {
background: ${props => props.theme.color.gray.white};
color: ${props =>
props.color ? props.color : props.theme.color.gray.subdued};
border-color: ${props => props.theme.color.gray.ink};
:focus {
border-color: ${props => props.theme.color.gray.ink};
box-shadow: inset 0 0 0 0.0625rem ${props => props.theme.color.gray.ink};
}
:active {
box-shadow: ${props => props.theme.shadow.inner};
}
}
&.past {
background: none;
color: ${props =>
props.color ? props.color : props.theme.color.gray.subdued};
border-color: ${props => props.theme.color.gray.subdued};
:hover {
background-color: ${props => props.theme.color.gray.white};
color: ${props =>
props.color ? props.color : props.theme.color.gray.ink};
}
:focus {
background-color: ${props => props.theme.color.gray.white};
border-color: ${props => props.theme.color.gray.ink};
color: ${props =>
props.color ? props.color : props.theme.color.gray.ink};
box-shadow: inset 0 0 0 0.0625rem ${props => props.theme.color.gray.ink};
}
:active {
background-color: ${props => props.theme.color.gray.white};
color: ${props =>
props.color ? props.color : props.theme.color.gray.ink};
box-shadow: ${props => props.theme.shadow.inner};
}
}
&.cancelled {
background: ${props => props.theme.color.gray.white};
border-color: ${props => props.theme.color.red.feature};
color: ${props =>
props.color ? props.color : props.theme.color.red.feature};
:hover {
background-color: ${props => props.theme.color.red.feature};
border-color: ${props => props.theme.color.red.feature};
color: ${props => props.theme.color.gray.white};
}
:focus {
border-color: ${props => props.theme.color.red.dark};
box-shadow: inset 0 0 0 0.0625rem ${props => props.theme.color.red.dark};
}
:active {
box-shadow: ${props => props.theme.shadow.inner};
}
}
`;
const TagContent = styled.span`
display: inline-block;
transform: translateY(-0.0625rem);
`;
const Tag = props => {
return (
<TagWrapper
className={props.tagType ? props.tagType : null}
float={props.float ? props.float : null}
>
<TagContent>{props.children}</TagContent>
</TagWrapper>
);
};
export default Tag;
<file_sep>import React, { Component } from "react";
import { Query } from "react-apollo";
import gql from "graphql-tag";
import PropTypes from "prop-types";
import styled from "styled-components";
import { toRem } from "./utils/unitConversion";
import TYPE from "./styles/Typography";
import { BREAKPOINTS } from "./styles/Layout";
import InfluencerLoggedActivity from "./InfluencerLoggedActivity";
import Button from "./Button";
const LoggedActivitiesWrapper = styled.div`
grid-column: 5 /13;
height: min-content;
> div:last-of-type {
border-bottom: ${toRem(1)} solid ${props => props.theme.color.gray.ink};
}
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: span 8;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: span 4;
}
`;
const LoggedActivitiesHeader = styled.h2`
${TYPE.displaySmall.feature.ink}
display: inline-block;
margin-top: 0;
margin-bottom: ${toRem(30)};
@media (max-width: ${BREAKPOINTS.mobile.large}) {
display: block;
margin-bottom: ${toRem(20)};
}
`;
const LoggedActivitiesEmpty = styled.p`
${TYPE.body.primary.subdued}
font-style: italic;
display: block;
text-align: center;
`;
const AddLoggedActivityButton = styled(Button)`
margin: 0;
margin-top: ${toRem(5)};
margin-bottom: ${toRem(20)};
float: right;
@media (max-width: ${BREAKPOINTS.mobile.large}) {
float: none;
display: 0;
margin: 0;
margin-bottom: ${toRem(20)};
}
`;
const SeeMore = styled.a`
${TYPE.body.primary.ink};
font-weight: 700;
color: ${props => props.theme.color.green.feature};
/* grid-column: span 2; */
margin-top: ${toRem(10)};
display: block;
text-align: center;
cursor: pointer;
`;
const LOGGED_ACTIVITIES_QUERY = gql`
query SINGLE_INFLUENCER_LOGGED_ACTIVITIES_QUERY($id: ID!, $cursor: String) {
loggedActivitiesConnection(
first: 10
after: $cursor
where: { influencer: { id: $id } }
orderBy: updatedAt_DESC
) {
pageInfo {
hasNextPage
endCursor
}
edges {
node {
eventType
description
updatedAt
}
}
}
}
`;
class InfluencerLoggedActivities extends Component {
static propTypes = {
influencer: PropTypes.object.isRequired
};
render() {
const { influencer } = this.props;
return (
<LoggedActivitiesWrapper>
<LoggedActivitiesHeader>Logged Activity</LoggedActivitiesHeader>
<AddLoggedActivityButton
buttonType="primary"
onClick={this.props.showModal}
>
+ Log an Activity
</AddLoggedActivityButton>
<Query
query={LOGGED_ACTIVITIES_QUERY}
variables={{ id: influencer.id }}
>
{({ data, error, loading, fetchMore }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
const loggedActivitiesConnection = data.loggedActivitiesConnection;
if (loggedActivitiesConnection.edges.length == 0) {
return (
<LoggedActivitiesEmpty>
No logged events yet.
</LoggedActivitiesEmpty>
);
}
return (
<>
{loggedActivitiesConnection.edges.map(loggedActivity => (
<InfluencerLoggedActivity
loggedActivity={loggedActivity.node}
key={loggedActivity.node.updatedAt}
/>
))}
{loggedActivitiesConnection.pageInfo.hasNextPage ? (
<SeeMore
onClick={() => {
fetchMore({
variables: {
cursor: loggedActivitiesConnection.pageInfo.endCursor
},
updateQuery: (previousResult, { fetchMoreResult }) => {
const newEdges =
fetchMoreResult.loggedActivitiesConnection.edges;
const pageInfo =
fetchMoreResult.loggedActivitiesConnection.pageInfo;
return newEdges.length
? {
loggedActivitiesConnection: {
__typename:
previousResult.loggedActivitiesConnection
.__typename,
edges: [
...previousResult.loggedActivitiesConnection
.edges,
...newEdges
],
pageInfo
}
}
: previousResult;
}
});
}}
>
See More
</SeeMore>
) : null}
</>
);
}}
</Query>
</LoggedActivitiesWrapper>
);
}
}
export default InfluencerLoggedActivities;
export { LOGGED_ACTIVITIES_QUERY };
<file_sep>const { forwardTo } = require("prisma-binding");
const Query = {
items: forwardTo("db"),
influencers: forwardTo("db"),
influencersConnection: forwardTo("db"),
influencer: forwardTo("db"),
addresses: forwardTo("db"),
socials: forwardTo("db"),
sizes: forwardTo("db"),
loggedActivities: forwardTo("db"),
loggedActivitiesConnection: forwardTo("db"),
notes: forwardTo("db"),
notesConnection: forwardTo("db"),
loggedInUser(parent, args, ctx, info) {
if (!ctx.request.userId) {
return null;
}
return ctx.db.query.user(
{
where: {
id: ctx.request.userId
}
},
info
);
}
// async items(parent, args, ctx, info) {
// const items = ctx.db.query.items();
// return items;
// }
};
module.exports = Query;
<file_sep>import React, { Component } from "react";
import { Mutation } from "react-apollo";
import gql from "graphql-tag";
import styled from "styled-components";
import Router from "next/router";
import { LOGGED_ACTIVITIES_QUERY } from "../InfluencerLoggedActivities";
import { toRem } from "../utils/unitConversion";
import { BREAKPOINTS, GRID } from "../styles/Layout";
import TYPE from "../styles/Typography";
import ZINDEX from "../styles/Zindex";
import ANIMATION from "../styles/Animation";
import { CardContainer } from "../CardContainer";
import { TextFieldSimple } from "../TextField";
import Select from "../Select";
import Button from "../Button";
import Error from "../ErrorMessage";
import CloseIcon from "react-svg-loader!../../static/icons/input/cancel/default.svg";
const BackgroundOverlay = styled.div`
background-color: ${props => props.theme.background.overlay};
${GRID.wrapper}
max-width: none;
width: calc(100vw - ${toRem(200)});
transform: translateX(${toRem(200)});
height: 0;
min-height: 100vh;
padding: ${toRem(60)} 0;
position: fixed;
overflow: hidden;
left: 0;
top: 0;
z-index: ${ZINDEX.overlay};
${ANIMATION.default}
transition-property: opacity;
pointer-events: none;
opacity: 0;
&.show {
pointer-events: auto;
opacity: 1;
overflow-y: scroll;
}
@media (max-width: ${BREAKPOINTS.tablet.large}) {
transform: translateX(6.5em);
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
transform: translateX(4rem);
}
`;
const ModalWrapper = styled.div`
position: relative;
${GRID.container}
`;
const Modal = styled(CardContainer)`
position: relative;
grid-column: 2 /12;
margin-bottom: 0;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: 1 /9;
padding: ${toRem(20)};
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: 1 /5;
padding: ${toRem(20)};
}
`;
const ModalHeader = styled.div`
padding-bottom: ${toRem(20)};
border-bottom: 1px solid ${props => props.theme.color.subdued};
`;
const ModalTitle = styled.h4`
${TYPE.heading.feature.ink}
display: inline-block;
margin: 0;
max-width: calc(100% - 2.25rem);
`;
const ModalClose = styled.button`
border: none;
background: none;
padding: 0;
float: right;
width: 2rem;
height: 2rem;
margin-bottom: 0.25rem;
:focus {
outline: none;
}
`;
const ModalInput = styled.div`
padding-top: ${toRem(40)};
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: ${toRem(40)};
margin-bottom: ${toRem(20)};
@media (max-width: ${BREAKPOINTS.mobile.large}) {
width: 100%;
grid-gap: ${toRem(20)};
}
`;
const ActivityDescription = styled(TextFieldSimple)`
margin: 0;
display: inline-block;
margin-bottom: ${toRem(20)};
grid-column: span 3;
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: span 4;
}
`;
const ModalButtons = styled.div`
float: right;
> button {
margin-top: 0;
margin-bottom: 0;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
float: left;
> button {
display: block;
margin-left: 0;
margin-bottom: ${toRem(10)};
}
}
`;
const ActivitySelect = styled(Select)`
grid-column: span 1;
margin: 0;
margin-bottom: ${toRem(20)};
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: span 4;
margin-bottom: 0;
}
`;
const CREATE_LOGGED_ACTIVITY_MUTATION = gql`
mutation CREATE_LOGGED_ACTIVITY_MUTATION(
$activity: activityType!
$description: String!
$influencerId: String!
) {
createLoggedActivity(
eventType: $activity
description: $description
influencerId: $influencerId
) {
createdAt
}
}
`;
class AddLoggedActivityModal extends Component {
state = {
show: this.props.show,
description: "",
activity: "instagram",
activityOptions: [
"Instagram",
"Twitter",
"Facebook",
"Event",
"Meeting",
"Call",
"Coffee",
"Celebration",
"Other"
],
activityOptionsPlaceholders: {
instagram: "New Instagram Post",
twitter: "New Tweet",
facebook: "New Facebook Post",
event: "Attended an event",
meeting: "Had a meeting",
call: "Had a call",
coffee: "Grabbed a coffee",
celebration: "Had a celebration",
other: "Something happened"
},
influencerId: this.props.influencerId
};
handleChange = e => {
const { name, type, value } = e.target;
const val = type === "number" ? parseFloat(value) : value;
this.setState({ [name]: val });
};
activityHandleChange = e => {
const activityType = e.target.value;
const description = e.target.parentNode.parentNode.querySelector("input");
description.placeholder = this.state.activityOptionsPlaceholders[
activityType
];
this.setState({ activity: activityType });
};
componentWillReceiveProps(props) {
this.setState({ show: props.show });
}
render() {
return (
<BackgroundOverlay className={this.state.show ? "show" : null}>
<ModalWrapper>
<Modal>
<Mutation
mutation={CREATE_LOGGED_ACTIVITY_MUTATION}
variables={{
activity: this.state.activity.toUpperCase(),
description: this.state.description
? this.state.description
: this.state.activityOptionsPlaceholders[this.state.activity],
influencerId: this.state.influencerId
}}
refetchQueries={[
{
query: LOGGED_ACTIVITIES_QUERY,
variables: { id: this.state.influencerId }
}
]}
>
{(createLoggedActivity, { loading, error }) => (
<form
onSubmit={async e => {
e.preventDefault();
const res = await createLoggedActivity();
this.setState({ description: "" });
this.props.hide();
}}
>
<Error error={error} />
<fieldset disabled={loading} aria-busy={loading}>
<ModalHeader>
<ModalTitle>Log an Activity</ModalTitle>
<ModalClose type="button" onClick={this.props.hide}>
<CloseIcon />
</ModalClose>
</ModalHeader>
<ModalInput>
<ActivitySelect
labelFor="activity"
label="Activity"
options={this.state.activityOptions}
onChange={this.activityHandleChange}
/>
<ActivityDescription
label="Description"
labelFor="description"
textInputName="description"
textInputPlaceholder={
this.state.activityOptionsPlaceholders[
this.state.activity
]
}
inputType="secondary"
className="halfInput"
value={this.state.description}
onChange={this.handleChange}
/>
</ModalInput>
<ModalButtons>
<Button buttonType="primary" type="submit">
Submit
</Button>
<Button
buttonType="secondary"
type="button"
onClick={this.props.hide}
>
Cancel
</Button>
</ModalButtons>
</fieldset>
</form>
)}
</Mutation>
</Modal>
</ModalWrapper>
</BackgroundOverlay>
);
}
}
export default AddLoggedActivityModal;
export { CREATE_LOGGED_ACTIVITY_MUTATION };
<file_sep>import Link from "next/link";
import styled from "styled-components";
import { PropTypes } from "react";
import Router from "next/router";
import gql from "graphql-tag";
import { Mutation } from "react-apollo";
import MarketingNav from "./MarketingNav";
import { GRID, BREAKPOINTS } from "./styles/Layout";
import { toRem } from "./utils/unitConversion";
import TYPE from "./styles/Typography";
import ANIMATION from "./styles/Animation";
import ZINDEX from "./styles/Zindex";
import Logo from "react-svg-loader!../static/icons/brand/logo.svg";
import Campaigns from "react-svg-loader!../static/icons/nav/campaigns.svg";
import Contacts from "react-svg-loader!../static/icons/nav/contacts.svg";
import LogOut from "react-svg-loader!../static/icons/nav/logOut.svg";
import Profile from "react-svg-loader!../static/icons/nav/profile.svg";
import Settings from "react-svg-loader!../static/icons/nav/settings.svg";
import { CURRENT_USER_QUERY } from "./User";
const AdminHeaderWrapper = styled.header`
position: fixed;
left: 0;
top: 0;
width: ${toRem(200)};
height: 100vh;
min-height: min-content;
background: ${props => props.theme.color.gray.white};
box-shadow: ${props => props.theme.shadow.drop};
padding: ${toRem(40)} 0;
z-index: ${ZINDEX.header};
@media (max-width: ${BREAKPOINTS.tablet.large}) {
width: ${toRem(104)};
padding: ${toRem(20)} 0;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
width: ${toRem(64)};
}
`;
const LogoWrapper = styled.div`
width: 6rem;
height: 6rem;
margin: 0 auto ${toRem(60)};
@media (max-width: ${BREAKPOINTS.tablet.large}) {
width: 4rem;
height: 4rem;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
width: ${toRem(32)};
height: ${toRem(32)};
}
`;
const NavLink = styled.a`
text-decoration: none;
display: block;
clear: both;
padding: ${toRem(15)} ${toRem(40)};
/* margin-bottom: ${toRem(10)}; */
cursor: pointer;
@media (max-width: ${BREAKPOINTS.mobile.large}) {
padding: ${toRem(15)} ${toRem(20)};
}
:hover {
> p {
color: ${props => props.theme.color.gray.ink};
}
> div > svg {
opacity: 1;
}
}
&.active {
border-left: ${toRem(5)} solid ${props => props.theme.color.green.feature};
padding-left: calc(${toRem(40)} - ${toRem(5)});
@media (max-width: ${BREAKPOINTS.tablet.large}) {
text-align: center;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
padding-left: calc(${toRem(20)} - ${toRem(5)});
}
> p {
color: ${props => props.theme.color.green.feature};
font-weight: 700;
}
> div > svg {
opacity: 1;
}
&#navInfluencers {
> div > svg > g {
stroke: ${props => props.theme.color.green.feature};
}
}
}
`;
const NavIconWrapper = styled.div`
display: inline-block;
width: 1.5rem;
height: 1.5rem;
margin-right: ${toRem(10)};
@media (max-width: ${BREAKPOINTS.mobile.large}) {
margin: 0 auto;
}
svg {
width: 100%;
opacity: 0.76;
${ANIMATION.default}
}
`;
const NavLinkText = styled.p`
display: inline-block;
vertical-align: top;
${TYPE.body.primary.subdued}
margin-bottom: 0;
${ANIMATION.default}
@media (max-width: ${BREAKPOINTS.tablet.large}) {
display: none;
}
`;
const LinksContainer = styled.div`
display: flex;
flex-direction: column;
justify-content: space-between;
height: calc(100vh - 6rem - 3.75rem - 5rem);
min-height: min-content;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
height: calc(100vh - 6.5rem - 3.75rem);
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
height: calc(100vh - 5.75rem - 2.5rem);
}
`;
const NavLinksContainer = styled.div``;
const SettingsLineBreak = styled.hr`
width: calc(100% - ${toRem(80)});
/* padding: 0 ${toRem(40)}; */
margin-bottom: ${toRem(30)};
@media (max-width: ${BREAKPOINTS.tablet.large}) {
width: calc(100% - ${toRem(60)});
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
width: calc(100% - ${toRem(40)});
}
`;
const SettingsContainer = styled.div`
/* padding-top: ${toRem(30)}; */
/* border-top: 1px solid ${props => props.theme.color.gray.subdued}; */
vertical-align: bottom;
a:last-child {
margin: 0;
}
`;
const SIGN_OUT_MUTATION = gql`
mutation SIGN_OUT_MUTATION {
signout {
message
}
}
`;
class AdminHeader extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
let activeNavCategory = Router.route.split("/");
activeNavCategory =
activeNavCategory[1].charAt(0).toUpperCase() +
activeNavCategory[1].slice(1);
if (activeNavCategory) {
const adminNavCtgy = document.getElementById("nav" + activeNavCategory);
adminNavCtgy ? adminNavCtgy.classList.add("active") : null;
}
}
render() {
return (
<AdminHeaderWrapper>
<LogoWrapper>
<Link href="./signup">
<Logo />
</Link>
</LogoWrapper>
<LinksContainer>
<NavLinksContainer>
<NavLink id="navCampaigns">
<NavIconWrapper>
<Campaigns />
</NavIconWrapper>
<NavLinkText>Campaigns</NavLinkText>
</NavLink>
<NavLink id="navInfluencers" href="/influencers">
<NavIconWrapper>
<Contacts />
</NavIconWrapper>
<NavLinkText>Influencers</NavLinkText>
</NavLink>
<NavLink id="navProfile">
<NavIconWrapper>
<Profile />
</NavIconWrapper>
<NavLinkText>Profile</NavLinkText>
</NavLink>
</NavLinksContainer>
<SettingsContainer>
<SettingsLineBreak />
<NavLink id="navSettings">
<NavIconWrapper>
<Settings />
</NavIconWrapper>
<NavLinkText>Settings</NavLinkText>
</NavLink>
<Mutation
mutation={SIGN_OUT_MUTATION}
refetchQueries={[{ query: CURRENT_USER_QUERY }]}
>
{signout => (
<NavLink
onClick={async e => {
e.preventDefault();
signout();
Router.push({
pathname: "/"
});
}}
>
<NavIconWrapper>
<LogOut />
</NavIconWrapper>
<NavLinkText>Log Out</NavLinkText>
</NavLink>
)}
</Mutation>
</SettingsContainer>
</LinksContainer>
</AdminHeaderWrapper>
);
}
}
export default AdminHeader;
<file_sep>import styled from "styled-components";
import TYPE from "../components/styles/Typography";
import ANIMATION from "../components/styles/Animation";
const TextArea = styled.textarea`
border-radius: 0.125rem;
border-width: 0.0625rem;
border-style: solid;
border-color: ${props => props.theme.color.gray.medium};
padding: 0.625rem;
height: 7.25rem;
width: 100%;
${TYPE.body.primary.ink}
${ANIMATION.default}
margin: 1rem;
resize: none;
:focus {
outline: none;
border-color: ${props => props.theme.color.gray.ink};
}
::placeholder {
color: ${props => props.theme.color.gray.medium};
}
&.primary {
:focus {
border-color: ${props => props.theme.color.green.feature};
}
}
&.secondary {
}
&.outline {
background: none;
:focus {
background-color: ${props => props.theme.color.gray.white};
border-color: ${props => props.theme.color.gray.subdued};
}
}
&.danger {
:focus {
border-color: ${props => props.theme.color.red.feature};
}
}
`;
const TextAreaInput = props => {
return (
<TextArea
type={props.type ? props.type : "text"}
name={props.textInputName ? props.textInputName : "textInput"}
placeholder={
props.textInputPlaceholder
? props.textInputPlaceholder
: "Type Somthing..."
}
className={props.inputType ? props.inputType : null}
required={props.required ? true : null}
value={props.value}
onChange={props.onChange}
/>
);
};
export default TextAreaInput;
<file_sep>import Link from "next/link";
import styled from "styled-components";
import Button from "../components/Button";
import {
ButtonPrimaryGroup,
ButtonSecondaryGroup,
ButtonOutlineGroup
} from "../components/ButtonGroup";
import {
CardContainer,
CreamCardContainer,
DarkCardContainer
} from "../components/CardContainer";
import {
TextDisplayLarge,
TextDisplayLargeSubdued,
TextDisplayLargeWhite,
TextDisplaySmall,
TextDisplaySmallSubdued,
TextDisplaySmallWhite,
TextHeadingFeature,
TextHeadingFeatureSubdued,
TextHeadingFeatureWhite,
TextHeadingPrimary,
TextHeadingPrimarySubdued,
TextHeadingPrimaryWhite,
TextSubheadingFeature,
TextSubheadingFeatureSubdued,
TextSubheadingFeatureWhite,
TextSubheadingPrimary,
TextSubheadingPrimarySubdued,
TextSubheadingPrimaryWhite,
TextBodyFeature,
TextBodyFeatureSubdued,
TextBodyFeatureWhite,
TextBodyPrimary,
TextBodyPrimarySubdued,
TextBodyPrimaryWhite,
TextCaptionFeature,
TextCaptionFeatureSubdued,
TextCaptionFeatureWhite,
TextCaptionPrimary,
TextCaptionPrimarySubdued,
TextCaptionPrimaryWhite
} from "../components/Typography";
import { BREAKPOINTS, GRID } from "../components/styles/Layout";
import TextField from "../components/TextField";
import TextArea from "../components/TextArea";
import TextFieldInput from "../components/TextFieldInput";
import TextAreaInput from "../components/TextAreaInput";
import THEME from "../components/styles/Theme";
const Wrapper = styled.div`
${GRID.wrapper}
`;
const Container = styled.div`
${GRID.container}
`;
const Section = styled.div`
/* margin: 2rem 0 4rem; */
grid-column: span 12;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: span 8;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: span 4;
}
`;
const ColorBlockWrapper = styled.div`
grid-column: span 4;
`;
const ColorBlockContainer = styled(CardContainer)`
padding: 0;
border: none;
`;
const ColorBlock = styled.div`
background: ${props =>
props.displayColor ? props.displayColor : props.theme.color.gray.white};
padding: 1rem;
`;
const ColorName = styled(TextBodyPrimary)`
color: ${props => (props.white ? props.theme.color.gray.white : null)};
display: inline-block;
margin: 0;
`;
const ColorCode = styled(ColorName)`
float: right;
`;
const Home = props => (
<>
<Wrapper>
<Container>
<Section>
<TextSubheadingPrimarySubdued>Buttons</TextSubheadingPrimarySubdued>
{/* <ButtonPrimary>Primary</ButtonPrimary>
<ButtonSecondary>Secondary</ButtonSecondary>
<ButtonOutline>Outline</ButtonOutline>
<ButtonDanger>Danger</ButtonDanger> */}
<Button buttonType="primary">Primary</Button>
<Button buttonType="secondary">Secondary</Button>
<Button buttonType="outline">Outline</Button>
<Button buttonType="danger">Danger</Button>
</Section>
<Section>
<TextSubheadingPrimarySubdued>
Grouped Buttons
</TextSubheadingPrimarySubdued>
<ButtonPrimaryGroup>
<Button buttonType="primary">Left</Button>
<Button buttonType="primary">Primary</Button>
<Button buttonType="primary">Right</Button>
</ButtonPrimaryGroup>
<ButtonSecondaryGroup>
<Button buttonType="secondary">Left</Button>
<Button buttonType="secondary">Secondary</Button>
<Button buttonType="secondary">Right</Button>
</ButtonSecondaryGroup>
<ButtonOutlineGroup>
<Button buttonType="outline">Left</Button>
<Button buttonType="outline">Outline</Button>
<Button buttonType="outline">Right</Button>
</ButtonOutlineGroup>
</Section>
<Section>
<TextSubheadingPrimarySubdued>
Pagination
</TextSubheadingPrimarySubdued>
<Button buttonType="outline">← Back</Button>
<Button buttonType="outline">Next →</Button>
</Section>
<Section>
<TextSubheadingPrimarySubdued>
Simple Inputs
</TextSubheadingPrimarySubdued>
<TextField label="Primary" textFieldType="primary" />
<TextField label="Secondary" textFieldType="secondary" />
<TextField label="Outline" textFieldType="outline" />
<TextField label="Danger" textFieldType="danger" />
<TextArea label="Primary" textAreaType="primary" />
<TextArea label="Secondary" textAreaType="secondary" />
<TextArea label="Outline" textAreaType="outline" />
<TextArea label="Danger" textAreaType="danger" />
</Section>
<Section>
<TextSubheadingPrimarySubdued>
Card Containers
</TextSubheadingPrimarySubdued>
<CardContainer>
<TextSubheadingPrimarySubdued>
Card Containers
</TextSubheadingPrimarySubdued>
<TextBodyPrimary>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Mollis
aliquam ut porttitor leo a diam sollicitudin tempor. Faucibus in
ornare quam viverra. Ultricies mi quis hendrerit dolor magna eget
est lorem ipsum. Auctor urna nunc id cursus. Nascetur ridiculus
mus mauris vitae ultricies. Quam elementum pulvinar etiam non quam
lacus suspendisse faucibus interdum. Convallis tellus id interdum
velit laoreet id. Pharetra massa massa ultricies mi quis hendrerit
dolor. Neque ornare aenean euismod elementum. Ullamcorper velit
sed ullamcorper morbi tincidunt ornare massa eget. Scelerisque
felis imperdiet proin fermentum. Justo donec enim diam vulputate
ut. In eu mi bibendum neque egestas congue quisque egestas. Sapien
eget mi proin sed. Dictumst vestibulum rhoncus est pellentesque
elit.
</TextBodyPrimary>
</CardContainer>
<DarkCardContainer>
<TextSubheadingPrimaryWhite>
Card Containers
</TextSubheadingPrimaryWhite>
<TextBodyPrimaryWhite>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Mollis
aliquam ut porttitor leo a diam sollicitudin tempor. Faucibus in
ornare quam viverra. Ultricies mi quis hendrerit dolor magna eget
est lorem ipsum. Auctor urna nunc id cursus. Nascetur ridiculus
mus mauris vitae ultricies. Quam elementum pulvinar etiam non quam
lacus suspendisse faucibus interdum. Convallis tellus id interdum
velit laoreet id. Pharetra massa massa ultricies mi quis hendrerit
dolor. Neque ornare aenean euismod elementum. Ullamcorper velit
sed ullamcorper morbi tincidunt ornare massa eget. Scelerisque
felis imperdiet proin fermentum. Justo donec enim diam vulputate
ut. In eu mi bibendum neque egestas congue quisque egestas. Sapien
eget mi proin sed. Dictumst vestibulum rhoncus est pellentesque
elit.
</TextBodyPrimaryWhite>
</DarkCardContainer>
</Section>
<Section>
<TextSubheadingPrimarySubdued>
Typography
</TextSubheadingPrimarySubdued>
<CardContainer>
<TextSubheadingPrimarySubdued>
Ink on White
</TextSubheadingPrimarySubdued>
<TextDisplayLarge>
Display-Large / Crimson Text / SemiBold - 54px / 81px
</TextDisplayLarge>
<TextDisplaySmall>
Display-Small / Crimson Text / SemiBold - 36px / 54px
</TextDisplaySmall>
<TextHeadingFeature>
Heading / Crimson Text / Bold - 24px / 36px
</TextHeadingFeature>
<TextHeadingPrimary>
Heading / Lato / Bold - 24px / 36px
</TextHeadingPrimary>
<TextSubheadingFeature>
Subheading / Crimson Text / Bold - 20px / 28px
</TextSubheadingFeature>
<TextSubheadingPrimary>
SUBHEADING / LATO / BOLD - 16PX / 24PX
</TextSubheadingPrimary>
<TextBodyFeature>
Body / Crimson Text / Regular - 16px / 24px
</TextBodyFeature>
<TextBodyPrimary>
Body / Lato / Regular - 16px / 24px
</TextBodyPrimary>
<TextCaptionFeature>
Caption / Crimson Text / Regular - 11px / 16px
</TextCaptionFeature>
<TextCaptionPrimary>
Caption / Lato / Regular - 11px / 16px
</TextCaptionPrimary>
</CardContainer>
<CreamCardContainer>
<TextSubheadingPrimarySubdued>
Subdued on Cream
</TextSubheadingPrimarySubdued>
<TextDisplayLargeSubdued>
Display-Large / Crimson Text / SemiBold - 54px / 81px
</TextDisplayLargeSubdued>
<TextDisplaySmallSubdued>
Display-Small / Crimson Text / SemiBold - 36px / 54px
</TextDisplaySmallSubdued>
<TextHeadingFeatureSubdued>
Heading / Crimson Text / Bold - 24px / 36px
</TextHeadingFeatureSubdued>
<TextHeadingPrimarySubdued>
Heading / Lato / Bold - 24px / 36px
</TextHeadingPrimarySubdued>
<TextSubheadingFeatureSubdued>
Subheading / Crimson Text / Bold - 20px / 28px
</TextSubheadingFeatureSubdued>
<TextSubheadingPrimarySubdued>
SUBHEADING / LATO / BOLD - 16PX / 24PX
</TextSubheadingPrimarySubdued>
<TextBodyFeatureSubdued>
Body / Crimson Text / Regular - 16px / 24px
</TextBodyFeatureSubdued>
<TextBodyPrimarySubdued>
Body / Lato / Regular - 16px / 24px
</TextBodyPrimarySubdued>
<TextCaptionFeatureSubdued>
Caption / Crimson Text / Regular - 11px / 16px
</TextCaptionFeatureSubdued>
<TextCaptionPrimarySubdued>
Caption / Lato / Regular - 11px / 16px
</TextCaptionPrimarySubdued>
</CreamCardContainer>
<DarkCardContainer>
<TextSubheadingPrimaryWhite>
White on Ink
</TextSubheadingPrimaryWhite>
<TextDisplayLargeWhite>
Display-Large / Crimson Text / SemiBold - 54px / 81px
</TextDisplayLargeWhite>
<TextDisplaySmallWhite>
Display-Small / Crimson Text / SemiBold - 36px / 54px
</TextDisplaySmallWhite>
<TextHeadingFeatureWhite>
Heading / Crimson Text / Bold - 24px / 36px
</TextHeadingFeatureWhite>
<TextHeadingPrimaryWhite>
Heading / Lato / Bold - 24px / 36px
</TextHeadingPrimaryWhite>
<TextSubheadingFeatureWhite>
Subheading / Crimson Text / Bold - 20px / 28px
</TextSubheadingFeatureWhite>
<TextSubheadingPrimaryWhite>
SUBHEADING / LATO / BOLD - 16PX / 24PX
</TextSubheadingPrimaryWhite>
<TextBodyFeatureWhite>
Body / Crimson Text / Regular - 16px / 24px
</TextBodyFeatureWhite>
<TextBodyPrimaryWhite>
Body / Lato / Regular - 16px / 24px
</TextBodyPrimaryWhite>
<TextCaptionFeatureWhite>
Caption / Crimson Text / Regular - 11px / 16px
</TextCaptionFeatureWhite>
<TextCaptionPrimaryWhite>
Caption / Lato / Regular - 11px / 16px
</TextCaptionPrimaryWhite>
</DarkCardContainer>
</Section>
<ColorBlockWrapper>
<TextSubheadingPrimarySubdued>Gray</TextSubheadingPrimarySubdued>
<ColorBlockContainer>
<ColorBlock displayColor={props => props.theme.color.gray.white}>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[1] +
" / " +
Object.getOwnPropertyNames(THEME.color.gray)[0]}
</ColorName>
<ColorCode>{THEME.color.gray.white}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.gray.light}>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[1] +
" / " +
Object.getOwnPropertyNames(THEME.color.gray)[1]}
</ColorName>
<ColorCode>{THEME.color.gray.light}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.gray.medium}>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[1] +
" / " +
Object.getOwnPropertyNames(THEME.color.gray)[2]}
</ColorName>
<ColorCode>{THEME.color.gray.medium}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.gray.subdued}>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[1] +
" / " +
Object.getOwnPropertyNames(THEME.color.gray)[3]}
</ColorName>
<ColorCode white>{THEME.color.gray.subdued}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.gray.ink}>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[1] +
" / " +
Object.getOwnPropertyNames(THEME.color.gray)[4]}
</ColorName>
<ColorCode white>{THEME.color.gray.ink}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.gray.black}>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[1] +
" / " +
Object.getOwnPropertyNames(THEME.color.gray)[5]}
</ColorName>
<ColorCode white>{THEME.color.gray.black}</ColorCode>
</ColorBlock>
</ColorBlockContainer>
</ColorBlockWrapper>
<ColorBlockWrapper>
<TextSubheadingPrimarySubdued>Cream</TextSubheadingPrimarySubdued>
<ColorBlockContainer>
<ColorBlock displayColor={props => props.theme.color.cream}>
<ColorName>cream</ColorName>
<ColorCode>{THEME.color.cream}</ColorCode>
</ColorBlock>
</ColorBlockContainer>
</ColorBlockWrapper>
<ColorBlockWrapper>
<TextSubheadingPrimarySubdued>Red</TextSubheadingPrimarySubdued>
<ColorBlockContainer>
<ColorBlock displayColor={props => props.theme.color.red.lightest}>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[2] +
" / " +
Object.getOwnPropertyNames(THEME.color.red)[0]}
</ColorName>
<ColorCode>{THEME.color.red.lightest}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.red.light}>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[2] +
" / " +
Object.getOwnPropertyNames(THEME.color.red)[1]}
</ColorName>
<ColorCode>{THEME.color.red.light}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.red.feature}>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[2] +
" / " +
Object.getOwnPropertyNames(THEME.color.red)[2]}
</ColorName>
<ColorCode white>{THEME.color.red.feature}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.red.dark}>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[2] +
" / " +
Object.getOwnPropertyNames(THEME.color.red)[3]}
</ColorName>
<ColorCode white>{THEME.color.red.dark}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.red.darker}>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[2] +
" / " +
Object.getOwnPropertyNames(THEME.color.red)[4]}
</ColorName>
<ColorCode white>{THEME.color.red.darker}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.red.darkest}>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[2] +
" / " +
Object.getOwnPropertyNames(THEME.color.red)[5]}
</ColorName>
<ColorCode white>{THEME.color.red.darkest}</ColorCode>
</ColorBlock>
</ColorBlockContainer>
</ColorBlockWrapper>
<ColorBlockWrapper>
<TextSubheadingPrimarySubdued>Blue</TextSubheadingPrimarySubdued>
<ColorBlockContainer>
<ColorBlock displayColor={props => props.theme.color.blue.lightest}>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[3] +
" / " +
Object.getOwnPropertyNames(THEME.color.blue)[0]}
</ColorName>
<ColorCode>{THEME.color.blue.lightest}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.blue.light}>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[3] +
" / " +
Object.getOwnPropertyNames(THEME.color.blue)[1]}
</ColorName>
<ColorCode>{THEME.color.blue.light}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.blue.medium}>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[3] +
" / " +
Object.getOwnPropertyNames(THEME.color.blue)[3]}
</ColorName>
<ColorCode white>{THEME.color.blue.medium}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.blue.dark}>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[3] +
" / " +
Object.getOwnPropertyNames(THEME.color.blue)[4]}
</ColorName>
<ColorCode white>{THEME.color.blue.dark}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.blue.feature}>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[3] +
" / " +
Object.getOwnPropertyNames(THEME.color.blue)[4]}
</ColorName>
<ColorCode white>{THEME.color.blue.feature}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.blue.darkest}>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[3] +
" / " +
Object.getOwnPropertyNames(THEME.color.blue)[5]}
</ColorName>
<ColorCode white>{THEME.color.blue.darkest}</ColorCode>
</ColorBlock>
</ColorBlockContainer>
</ColorBlockWrapper>
<ColorBlockWrapper>
<TextSubheadingPrimarySubdued>Blue</TextSubheadingPrimarySubdued>
<ColorBlockContainer>
<ColorBlock
displayColor={props => props.theme.color.green.lightest}
>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[4] +
" / " +
Object.getOwnPropertyNames(THEME.color.green)[0]}
</ColorName>
<ColorCode>{THEME.color.green.lightest}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.green.light}>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[4] +
" / " +
Object.getOwnPropertyNames(THEME.color.green)[1]}
</ColorName>
<ColorCode>{THEME.color.green.light}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.green.medium}>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[4] +
" / " +
Object.getOwnPropertyNames(THEME.color.green)[4]}
</ColorName>
<ColorCode>{THEME.color.green.medium}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.green.dark}>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[4] +
" / " +
Object.getOwnPropertyNames(THEME.color.green)[3]}
</ColorName>
<ColorCode>{THEME.color.green.dark}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.green.feature}>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[4] +
" / " +
Object.getOwnPropertyNames(THEME.color.green)[4]}
</ColorName>
<ColorCode white>{THEME.color.green.feature}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.green.darkest}>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[4] +
" / " +
Object.getOwnPropertyNames(THEME.color.green)[5]}
</ColorName>
<ColorCode white>{THEME.color.green.darkest}</ColorCode>
</ColorBlock>
</ColorBlockContainer>
</ColorBlockWrapper>
<ColorBlockWrapper>
<TextSubheadingPrimarySubdued>Yellow</TextSubheadingPrimarySubdued>
<ColorBlockContainer>
<ColorBlock
displayColor={props => props.theme.color.yellow.lightest}
>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[5] +
" / " +
Object.getOwnPropertyNames(THEME.color.yellow)[0]}
</ColorName>
<ColorCode>{THEME.color.yellow.lightest}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.yellow.light}>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[5] +
" / " +
Object.getOwnPropertyNames(THEME.color.yellow)[1]}
</ColorName>
<ColorCode>{THEME.color.yellow.light}</ColorCode>
</ColorBlock>
<ColorBlock
displayColor={props => props.theme.color.yellow.feature}
>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[5] +
" / " +
Object.getOwnPropertyNames(THEME.color.yellow)[2]}
</ColorName>
<ColorCode>{THEME.color.yellow.feature}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.yellow.dark}>
<ColorName>
{Object.getOwnPropertyNames(THEME.color)[5] +
" / " +
Object.getOwnPropertyNames(THEME.color.yellow)[3]}
</ColorName>
<ColorCode>{THEME.color.yellow.dark}</ColorCode>
</ColorBlock>
<ColorBlock displayColor={props => props.theme.color.yellow.darker}>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[5] +
" / " +
Object.getOwnPropertyNames(THEME.color.yellow)[4]}
</ColorName>
<ColorCode white>{THEME.color.yellow.darker}</ColorCode>
</ColorBlock>
<ColorBlock
displayColor={props => props.theme.color.yellow.darkest}
>
<ColorName white>
{Object.getOwnPropertyNames(THEME.color)[5] +
" / " +
Object.getOwnPropertyNames(THEME.color.yellow)[5]}
</ColorName>
<ColorCode white>{THEME.color.yellow.darkest}</ColorCode>
</ColorBlock>
</ColorBlockContainer>
</ColorBlockWrapper>
</Container>
</Wrapper>
</>
);
export default Home;
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import Link from "next/link";
import { toRem } from "./utils/unitConversion";
import ANIMATION from "./styles/Animation";
import TYPE from "./styles/Typography";
import { BREAKPOINTS } from "./styles/Layout";
import { CardContainer } from "./CardContainer";
import Tag from "./Tag";
import EmptyProfileImg from "react-svg-loader!../static/icons/emptyState/influencer.svg";
const InfluencerCardContainer = styled(CardContainer)`
grid-column: span 4;
padding: ${toRem(30)} ${toRem(20)};
margin-bottom: 0;
@media (max-width: ${BREAKPOINTS.mobile.large}) {
margin-bottom: ${toRem(20)};
}
`;
const InfluencerProfileImg = styled.a`
display: block;
width: 6.5rem;
height: 6.5rem;
border-radius: 50%;
overflow: hidden;
margin: 0 auto ${toRem(20)};
background-color: ${props => props.theme.color.blue.feature};
/* ${ANIMATION.default} */
>img, svg {
${ANIMATION.default}
width: 100%;
height: 100%;
object-fit: cover;
}
:hover {
> img, svg {
opacity: 0.8;
}
}
`;
const InfluencerInfo = styled.a`
display: block;
text-align: center;
padding: 0 ${toRem(20)};
margin-bottom: ${toRem(30)};
cursor: pointer;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
padding: 0;
}
:hover {
h3 {
color: ${props => props.theme.color.blue.feature};
}
p {
color: ${props => props.theme.color.blue.feature};
}
}
`;
const InfluencerName = styled.h3`
${TYPE.heading.feature.ink}
margin: 0;
${ANIMATION.default}
`;
const InfluencerDescription = styled.p`
${TYPE.caption.primary.subdued}
font-style: italic;
padding: 0 ${toRem(40)};
margin: 0;
${ANIMATION.default}
`;
const InfluencerCampaigns = styled.div`
display: block;
`;
const InfluencerCampaignsTitle = styled.h4`
${TYPE.body.primary.ink}
font-weight: 700;
margin-bottom: ${toRem(10)};
`;
class InfluencerSnapshotCard extends Component {
static propTpes = {
influencer: PropTypes.object.isRequired
};
render() {
const { influencer } = this.props;
return (
<InfluencerCardContainer>
<Link
href={{
pathname: "/influencer",
query: { id: influencer.id }
}}
>
<InfluencerProfileImg>
{influencer.thumbnail ? (
<img
src={influencer.thumbnail}
alt={influencer.firstName + " profile image"}
/>
) : (
<EmptyProfileImg />
)}
</InfluencerProfileImg>
</Link>
<Link
href={{
pathname: "/influencer",
query: { id: influencer.id }
}}
>
<InfluencerInfo>
<InfluencerName>
{influencer.firstName} {influencer.lastName}
</InfluencerName>
<InfluencerDescription>
{influencer.description
? influencer.description
: '"No description, but I’m sure they’re great"'}
</InfluencerDescription>
</InfluencerInfo>
</Link>
<InfluencerCampaigns>
<InfluencerCampaignsTitle>Campaigns</InfluencerCampaignsTitle>
<Tag tagType="active">#IXD2019</Tag>
</InfluencerCampaigns>
</InfluencerCardContainer>
);
}
}
export default InfluencerSnapshotCard;
<file_sep>import React, { Component } from "react";
import styled from "styled-components";
import TYPE from "./styles/Typography";
import { BREAKPOINTS } from "./styles/Layout";
import { toRem } from "./utils/unitConversion";
const UploadFieldInputWrapper = styled.div`
margin: 1rem;
`;
const UploadFieldInput = styled.input`
margin-bottom: ${toRem(10)};
`;
const Label = styled.label`
${TYPE.body.primary.ink}
margin: 0;
> input {
margin: ${toRem(5)} 0 0 0;
width: 100%;
}
> img {
width: 50%;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
> img {
width: 100%;
}
}
`;
class UploadField extends Component {
constructor(props) {
super(props);
this.state = {
image: ""
};
}
componentWillReceiveProps(props) {
this.setState({ image: props.image });
}
render() {
return (
<UploadFieldInputWrapper className={this.props.className}>
<Label htmlfor={this.props.labelFor ? this.props.labelFor : "title"}>
{this.props.label ? this.props.label : "Label"}
<UploadFieldInput
type="file"
name={this.props.name ? this.props.name : "file"}
placeholder={
this.props.placeholder
? this.props.placeholder
: "Upload an image"
}
required={this.props.required ? true : null}
onChange={this.props.onChange}
/>
{this.state.image && (
<img src={this.state.image} alt="Upload Preview" />
)}
</Label>
</UploadFieldInputWrapper>
);
}
}
export default UploadField;
<file_sep>import React, { Component } from "react";
import { Mutation } from "react-apollo";
import gql from "graphql-tag";
import styled from "styled-components";
import Link from "next/link";
import Router from "next/router";
import { CURRENT_USER_QUERY } from "./User";
import TYPE from "./styles/Typography";
import { MARKETING_GRID, BREAKPOINTS } from "./styles/Layout";
import { toRem } from "./utils/unitConversion";
import Error from "./ErrorMessage";
import { CardContainer } from "./CardContainer";
import { TextFieldSimple } from "./TextField";
import Button from "./Button";
import User from "./User";
import Logo from "react-svg-loader!../static/icons/brand/logo.svg";
const SigninWrapper = styled.div`
${MARKETING_GRID.wrapper}
`;
const SigninContainer = styled.div`
${MARKETING_GRID.container}
`;
const SigninCard = styled(CardContainer)`
grid-column: 2 / 12;
padding: 2.5rem 5rem;
text-align: center;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: 2 /8;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: 1 /5;
padding: 2rem;
}
`;
const LogoWrapper = styled.div`
grid-column: 4 /6;
padding: ${toRem(20)};
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: span 8;
text-align: center;
> svg {
margin: 0 auto;
width: ${toRem(80)};
height: ${toRem(80)};
}
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: span 4;
}
`;
const SigninInputWrapper = styled.div`
display: grid;
grid-template-columns: repeat(8, 1fr);
grid-column-gap: 1.5rem;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
/* grid-template-columns: repeat(4, 1fr); */
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-template-columns: repeat(4, 1fr);
}
`;
const SigninTextField = styled(TextFieldSimple)`
grid-column: 3 /7;
margin: 0;
margin-bottom: ${toRem(20)};
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: 2 /8;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: span 4;
}
`;
const SigninButton = styled(Button)`
display: block;
margin: ${toRem(20)} auto 0;
`;
const SigninForgotPassword = styled.a`
${TYPE.caption.primary};
grid-column: 3 /7;
color: ${props => props.theme.color.blue.feature};
cursor: pointer;
margin-top: ${toRem(-10)};
margin-bottom: ${toRem(20)};
text-align: right;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: 2 /8;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: span 4;
}
`;
const SignupLink = styled.a`
${TYPE.caption.primary};
color: ${props => props.theme.color.blue.feature};
cursor: pointer;
margin-top: ${toRem(20)};
display: block;
text-align: center;
`;
const LoggedInMessage = styled.h4`
${TYPE.heading.primary.ink};
text-align: center;
margin: ${toRem(40)} 0;
`;
const LoggedInRedirect = styled.a`
${TYPE.body.primary.ink};
display: inline-block;
color: ${props => props.theme.color.blue.feature};
margin-bottom: ${toRem(40)};
cursor: pointer;
`;
const SIGNIN_MUTATION = gql`
mutation SIGNin_MUTATION($email: String!, $password: String!) {
signin(email: $email, password: $password) {
id
email
name
}
}
`;
class Signin extends Component {
state = {
email: "",
password: ""
};
saveToState = e => {
this.setState({ [e.target.name]: e.target.value });
};
render() {
return (
<User>
{({ data: { loggedInUser } }) => (
<>
<SigninWrapper>
<SigninContainer>
<SigninCard>
{loggedInUser ? (
<>
<LoggedInMessage>
You're already logged in!
</LoggedInMessage>
<Link href={{ pathname: "/influencers" }}>
<LoggedInRedirect>Go to Dashboard</LoggedInRedirect>
</Link>
</>
) : (
<>
<Mutation
mutation={SIGNIN_MUTATION}
variables={this.state}
refetchQueries={[{ query: CURRENT_USER_QUERY }]}
>
{(signin, { error, loading }) => {
return (
<form
method="post"
onSubmit={async e => {
e.preventDefault();
await signin();
Router.push({
pathname: "/influencers"
});
// this.setState({ email: "", password: "" });
}}
>
<fieldset disabled={loading} aria-busy={loading}>
<Error error={error} />
<SigninInputWrapper>
<LogoWrapper>
<Logo />
</LogoWrapper>
<SigninTextField
label="Email"
labelFor="email"
type="email"
textInputName="email"
textInputPlaceholder="Enter your email"
inputType="secondary"
required
value={this.state.email}
onChange={this.saveToState}
/>
<SigninTextField
label="Password"
labelFor="password"
type="password"
textInputName="password"
textInputPlaceholder="Enter your password"
inputType="secondary"
required
value={this.state.password}
onChange={this.saveToState}
/>
<SigninForgotPassword>
Forgot your password?
</SigninForgotPassword>
</SigninInputWrapper>
<SigninButton
buttonType="primary"
type="submit"
>
Sign In
</SigninButton>
</fieldset>
</form>
);
}}
</Mutation>
<Link href={{ pathname: "/signup" }}>
<SignupLink>
Don't have an account? <b>Sign Up</b>
</SignupLink>
</Link>
</>
)}
</SigninCard>
</SigninContainer>
</SigninWrapper>
</>
)}
</User>
);
}
}
export default Signin;
<file_sep>const ANIMATION = {
default: `
transition-timing-function: ease-in-out;
transition-duration: 400ms;
`
};
export default ANIMATION;
<file_sep>import styled from "styled-components";
export const CardContainer = styled.div`
border-radius: 0.125rem;
border-width: 0.0625rem;
border-color: ${props => props.theme.color.gray.light};
border-style: solid;
background: ${props => props.theme.color.gray.white};
padding: 2.5rem 2.5rem;
margin-bottom: 2rem;
box-shadow: ${props => props.theme.shadow.drop};
`;
export const CreamCardContainer = styled(CardContainer)`
border-width: 0;
background: ${props => props.theme.color.cream};
`;
export const DarkCardContainer = styled(CardContainer)`
border-width: 0;
background: ${props => props.theme.color.gray.ink};
`;
<file_sep>import { GRID, BREAKPOINTS } from "./styles/Layout";
import styled from "styled-components";
import TYPE from "./styles/Typography";
import Link from "next/link";
const NavLinksWrapper = styled.div`
grid-column: 10 /13;
display: flex;
align-items: center;
justify-content: flex-end;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: 5 /9;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: 2 /5;
}
`;
const NavLink = styled.a`
display: inline-block;
color: ${props => props.theme.color.gray.ink};
${TYPE.body.primary.ink}
margin-left: 1rem;
`;
const MarketingNav = () => (
<NavLinksWrapper>
<NavLink href="/">log in</NavLink>
<NavLink href="/">sign up</NavLink>
</NavLinksWrapper>
);
export default MarketingNav;
<file_sep>import React, { Component } from "react";
import { Query } from "react-apollo";
import gql from "graphql-tag";
import PropTypes from "prop-types";
import styled from "styled-components";
import { toRem } from "./utils/unitConversion";
import ANIMATION from "./styles/Animation";
import TYPE from "./styles/Typography";
import { BREAKPOINTS } from "./styles/Layout";
import { CardContainer } from "./CardContainer";
import Tag from "./Tag";
import EmptyProfileImg from "react-svg-loader!../static/icons/emptyState/influencer.svg";
import HamburgerMenu from "react-svg-loader!../static/icons/nav/hamburger.svg";
import Facebook from "react-svg-loader!../static/icons/social/ink/facebook.svg";
import Instagram from "react-svg-loader!../static/icons/social/ink/instagram.svg";
import Snapchat from "react-svg-loader!../static/icons/social/ink/snapchat.svg";
import Twitter from "react-svg-loader!../static/icons/social/ink/twitter.svg";
import Website from "react-svg-loader!../static/icons/social/ink/web.svg";
const InfluencerCardWrapper = styled.div`
grid-column: span 4;
grid-row: span 3;
height: min-content;
margin: 0;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: span 8;
grid-row: span 1;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: span 4;
}
`;
const InfluencerCardContainer = styled(CardContainer)`
padding: ${toRem(30)} ${toRem(20)} 0;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
margin-bottom: 0;
}
`;
const InfluencerProfile = styled.div`
display: block;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
}
`;
const InfluencerProfileImg = styled.div`
display: block;
width: 6.5rem;
height: 6.5rem;
border-radius: 50%;
overflow: hidden;
margin: 0 auto ${toRem(20)};
> img,
svg {
width: 100%;
}
@media (max-width: ${BREAKPOINTS.tablet.large}) {
display: inline-block;
margin: 0 ${toRem(30)} ${toRem(20)} 0;
vertical-align: middle;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
display: block;
margin: 0 auto ${toRem(20)};
}
`;
const InfluencerInfo = styled.div`
display: block;
text-align: center;
padding: 0 ${toRem(20)};
margin-bottom: ${toRem(30)};
@media (max-width: ${BREAKPOINTS.tablet.large}) {
display: inline-block;
text-align: left;
vertical-align: middle;
padding: 0;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
display: block;
text-align: center;
padding: 0 ${toRem(20)};
}
`;
const InfluencerName = styled.h3`
${TYPE.heading.feature.ink}
margin: 0;
`;
const InfluencerDescription = styled.p`
${TYPE.caption.primary.subdued}
font-style: italic;
padding: 0 ${toRem(40)};
margin: 0;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
padding: 0;
}
`;
const InfluencerDetails = styled.div`
@media (max-width: ${BREAKPOINTS.mobile.large}) {
display: grid;
grid-template-columns: 1fr 1fr;
}
`;
const InfluencerStat = styled.div`
display: block;
margin-bottom: ${toRem(30)};
@media (max-width: ${BREAKPOINTS.tablet.large}) {
display: inline-block;
margin-right: ${toRem(30)};
vertical-align: top;
}
`;
const InfluencerSocialStat = styled(InfluencerStat)`
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: span 2;
margin-right: 0;
}
`;
const InfluencerStatTitle = styled.h4`
${TYPE.body.primary.ink}
font-weight: 700;
margin-bottom: ${toRem(10)};
`;
const InfluencerContent = styled.p`
${TYPE.caption.primary.subdued}
margin: 0;
display: inline-block;
`;
const InfluencerContentWrapper = styled.div`
display: flex;
justify-content: space-between;
flex-wrap: wrap;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
display: grid;
grid-template-columns: 1fr 1fr;
grid-column-gap: 1.25rem;
margin: 0;
width: calc(13rem + ${toRem(20)});
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column-gap: 0;
width: 100%;
}
`;
const InfluencerSocial = styled.a`
width: calc(50% - ${toRem(10)});
height: 1rem;
display: inline-block;
margin-bottom: ${toRem(10)};
> p {
vertical-align: top;
${ANIMATION.default}
}
:hover {
> p {
color: ${props => props.theme.color.blue.feature};
}
> svg > g {
stroke: ${props => props.theme.color.blue.feature};
}
}
@media (max-width: ${BREAKPOINTS.tablet.large}) {
width: max-content;
flex: 0 0 max-content;
margin-right: ${toRem(20)};
:nth-child(2n) {
margin-right: 0;
}
}
`;
const InfluencerSocialIconWrapper = styled.div`
display: inline-block;
width: 1rem;
height: 1rem;
margin-right: ${toRem(5)};
> svg {
vertical-align: top;
}
`;
const SINGLE_INFLUENCER_ADRESS_QUERY = gql`
query SINGLE_INFLUENCER_ADDRESS_QUERY($id: ID) {
addresses(where: { influencer: { id: $id } }) {
unit
streetNumber
street
city
country
postalCode
}
}
`;
const SINGLE_INFLUENCER_SOCIALMEDIA_QUERY = gql`
query SINGLE_INFLUENCER_SOCIALMEDIA_QUERY($id: ID) {
socials(where: { influencer: { id: $id } }) {
twitter
instagram
facebook
snapchat
website
}
}
`;
const SINGLE_INFLUENCER_SIZE_QUERY = gql`
query SINGLE_INFLUENCER_SIZE_QUERY($id: ID) {
sizes(where: { influencer: { id: $id } }) {
shirt
pant
shoe
}
}
`;
class InfluencerCard extends Component {
static propTypes = {
influencer: PropTypes.object.isRequired
};
render() {
const { influencer } = this.props;
return (
<InfluencerCardWrapper>
<InfluencerCardContainer>
<InfluencerProfile>
<InfluencerProfileImg>
{influencer.thumbnail ? (
<img
src={influencer.thumbnail}
alt={influencer.firstName + " profile image"}
/>
) : (
<EmptyProfileImg />
)}
</InfluencerProfileImg>
<InfluencerInfo>
<InfluencerName>
{influencer.firstName} {influencer.lastName}
</InfluencerName>
<InfluencerDescription>
{influencer.description
? influencer.description
: '"No description, but I’m sure they’re great"'}
</InfluencerDescription>
</InfluencerInfo>
</InfluencerProfile>
<InfluencerDetails>
<Query
query={SINGLE_INFLUENCER_SOCIALMEDIA_QUERY}
variables={{ id: influencer.id }}
>
{({ data, error, loading }) => {
if (loading) return <p>Loading...</p>;
if (error) return <Error error={error} />;
if (!data.socials[0]) {
return null;
}
const social = data.socials[0];
return (
<>
<InfluencerSocialStat>
<InfluencerStatTitle>Social</InfluencerStatTitle>
<InfluencerContentWrapper>
{social.facebook ? (
<InfluencerSocial
href={"https://www.facebook.com/" + social.facebook}
target="_blank"
>
<InfluencerSocialIconWrapper>
<Facebook />
</InfluencerSocialIconWrapper>
<InfluencerContent>
@{social.facebook}
</InfluencerContent>
</InfluencerSocial>
) : null}
{social.instagram ? (
<InfluencerSocial
href={
"https://www.instagram.com/" + social.instagram
}
target="_blank"
>
<InfluencerSocialIconWrapper>
<Instagram />
</InfluencerSocialIconWrapper>
<InfluencerContent>
@{social.instagram}
</InfluencerContent>
</InfluencerSocial>
) : null}
{social.twitter ? (
<InfluencerSocial
href={"https://www.twitter.com/" + social.twitter}
target="_blank"
>
<InfluencerSocialIconWrapper>
<Twitter />
</InfluencerSocialIconWrapper>
<InfluencerContent>
@{social.twitter}
</InfluencerContent>
</InfluencerSocial>
) : null}
{social.snapchat ? (
<InfluencerSocial>
<InfluencerSocialIconWrapper>
<Snapchat />
</InfluencerSocialIconWrapper>
<InfluencerContent>
{social.snapchat}
</InfluencerContent>
</InfluencerSocial>
) : null}
{social.website ? (
<InfluencerSocial
href={
social.website.substring(0, 4) == "http"
? social.website
: "http://" + social.website
}
target="_blank"
>
<InfluencerSocialIconWrapper>
<Website />
</InfluencerSocialIconWrapper>
<InfluencerContent>
{social.website.replace("www.", "")}
</InfluencerContent>
</InfluencerSocial>
) : null}
</InfluencerContentWrapper>
</InfluencerSocialStat>
</>
);
}}
</Query>
<Query
query={SINGLE_INFLUENCER_ADRESS_QUERY}
variables={{ id: influencer.id }}
>
{({ data, error, loading }) => {
if (loading) return <p>Loading...</p>;
if (error) return <Error error={error} />;
if (!data.addresses[0]) {
return null;
}
const address = data.addresses[0];
return (
<>
<InfluencerStat>
<InfluencerStatTitle>Address</InfluencerStatTitle>
<InfluencerContent>
{address.unit ? "Unit " + address.unit : null}
{address.streetNumber &&
address.street &&
address.unit ? (
<br />
) : null}
{address.streetNumber} {address.street}
{address.city ? <br /> : null} {address.city}
{address.country ? <br /> : null} {address.country}
{address.postalCode ? <br /> : null}{" "}
{address.postalCode}
</InfluencerContent>
</InfluencerStat>
</>
);
}}
</Query>
<Query
query={SINGLE_INFLUENCER_SIZE_QUERY}
variables={{ id: influencer.id }}
>
{({ data, error, loading }) => {
if (loading) return <p>Loading...</p>;
if (error) return <Error error={error} />;
if (!data.sizes[0]) {
return null;
}
const size = data.sizes[0];
return (
<>
<InfluencerStat>
<InfluencerStatTitle>Sizes</InfluencerStatTitle>
<InfluencerContent>
{size.shirt ? "Shirt: " + size.shirt : null}
{size.pant ? <br /> : null}
{size.pant ? "Pant: " + size.pant : null}
{size.shoe ? <br /> : null}
{size.shoe ? "Shoe: " + size.shoe / 10 : null}
</InfluencerContent>
</InfluencerStat>
</>
);
}}
</Query>
</InfluencerDetails>
</InfluencerCardContainer>
</InfluencerCardWrapper>
);
}
}
export default InfluencerCard;
<file_sep>import Link from "next/link";
import NProgress from "nprogress";
import Router from "next/router";
import styled from "styled-components";
import { PropTypes } from "react";
import MarketingNav from "./MarketingNav";
import { GRID, BREAKPOINTS } from "./styles/Layout";
import ANIMATION from "./styles/Animation";
import Logo from "react-svg-loader!../static/icons/brand/logo.svg";
Router.onRouteChangeStart = () => {
NProgress.start();
};
Router.onRouteChangeComplete = () => {
NProgress.done();
};
Router.onRouteChangeError = () => {
NProgress.done();
};
const HeaderWrapper = styled.div`
position: fixed;
width: 100vw;
top: 0;
left: 50%;
transform: translateX(-50%);
z-index: 999;
${ANIMATION.default}
&.scrolled {
background-color: ${props => props.theme.color.gray.white};
}
`;
const HeaderContainer = styled.div`
${GRID.container}
padding: 1rem 0;
`;
const LogoWrapper = styled.div`
grid-column: 1 /3;
max-width: 5rem;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: 1 /3;
max-width: 5rem;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: 1 /2;
}
`;
class Header extends React.Component {
constructor(props) {
super(props);
this.state = { navBackgroundWhite: false };
}
componentDidMount() {
document.addEventListener("scroll", () => {
const navBackgroundWhite = window.scrollY > 50;
if (navBackgroundWhite !== this.state.navBackgroundWhite) {
this.setState({ navBackgroundWhite });
}
});
}
render() {
return (
<HeaderWrapper
className={this.state.navBackgroundWhite ? "scrolled" : null}
>
<HeaderContainer>
<LogoWrapper>
<Logo />
</LogoWrapper>
<MarketingNav />
</HeaderContainer>
</HeaderWrapper>
);
}
}
export default Header;
// <div className="bar">
// </div>
// <Link href="/">
// <a><NAME></a>
// </Link>
<file_sep>import React, { Component } from "react";
import { Mutation } from "react-apollo";
import gql from "graphql-tag";
import styled from "styled-components";
import Link from "next/link";
import Router from "next/router";
import TYPE from "./styles/Typography";
import { MARKETING_GRID, BREAKPOINTS } from "./styles/Layout";
import { toRem } from "./utils/unitConversion";
import Error from "./ErrorMessage";
import { CardContainer } from "./CardContainer";
import { TextFieldSimple } from "./TextField";
import Button from "./Button";
import User from "./User";
import Logo from "react-svg-loader!../static/icons/brand/logo.svg";
const SignupWrapper = styled.div`
${MARKETING_GRID.wrapper}
`;
const SignupContainer = styled.div`
${MARKETING_GRID.container}
`;
const SignupCard = styled(CardContainer)`
grid-column: 2 / 12;
padding: 2.5rem 5rem;
text-align: center;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: 2 /8;
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: 1 /5;
padding: 2rem;
}
`;
const LogoWrapper = styled.div`
grid-column: 4 /6;
padding: ${toRem(20)};
@media (max-width: ${BREAKPOINTS.tablet.large}) {
grid-column: span 8;
text-align: center;
> svg {
margin: 0 auto;
width: ${toRem(80)};
height: ${toRem(80)};
}
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-column: span 4;
}
`;
const SignupInputWrapper = styled.div`
display: grid;
grid-template-columns: repeat(8, 1fr);
grid-column-gap: 1.5rem;
@media (max-width: ${BREAKPOINTS.tablet.large}) {
/* grid-template-columns: repeat(4, 1fr); */
}
@media (max-width: ${BREAKPOINTS.mobile.large}) {
grid-template-columns: repeat(4, 1fr);
}
`;
const SignupTextField = styled(TextFieldSimple)`
grid-column: span 4;
margin: 0;
margin-bottom: ${toRem(20)};
`;
const SignupButton = styled(Button)`
display: block;
margin: ${toRem(20)} auto 0;
`;
const SigninLink = styled.a`
${TYPE.caption.primary};
color: ${props => props.theme.color.blue.feature};
cursor: pointer;
margin-top: ${toRem(20)};
display: block;
text-align: center;
`;
const LoggedInMessage = styled.h4`
${TYPE.heading.primary.ink};
text-align: center;
margin: ${toRem(40)} 0;
`;
const LoggedInRedirect = styled.a`
${TYPE.body.primary.ink};
display: inline-block;
color: ${props => props.theme.color.blue.feature};
margin-bottom: ${toRem(40)};
cursor: pointer;
`;
const SIGNUP_MUTATION = gql`
mutation SIGNUP_MUTATION(
$name: String!
$businessName: String
$email: String!
$password: String!
) {
signup(
name: $name
businessName: $businessName
email: $email
password: <PASSWORD>
) {
id
email
name
}
}
`;
class Signup extends Component {
state = {
name: "",
password: "",
email: "",
businessName: "",
loggedIn: false
};
saveToState = e => {
this.setState({ [e.target.name]: e.target.value });
};
componentDidMount() {
if (this.state.loggedIn) {
Router.push({
pathname: "/influencers"
});
}
}
render() {
return (
<User>
{({ data: { loggedInUser } }) => (
<>
<SignupWrapper>
<SignupContainer>
<SignupCard>
{loggedInUser ? (
<>
<LoggedInMessage>
You're already logged in!
</LoggedInMessage>
<Link href={{ pathname: "/influencers" }}>
<LoggedInRedirect>Go to Dashboard</LoggedInRedirect>
</Link>
</>
) : (
<>
<Mutation
mutation={SIGNUP_MUTATION}
variables={this.state}
>
{(signup, { error, loading }) => {
return (
<form
method="post"
onSubmit={async e => {
e.preventDefault();
await signup();
// this.setState({ name: "", email: "", password: "" });
Router.push({
pathname: "/influencers"
});
}}
>
<fieldset disabled={loading} aria-busy={loading}>
<Error error={error} />
<SignupInputWrapper>
<LogoWrapper>
<Logo />
</LogoWrapper>
<SignupTextField
label="Name"
labelFor="name"
textInputName="name"
textInputPlaceholder="Enter your name"
inputType="secondary"
required
value={this.state.name}
onChange={this.saveToState}
/>
<SignupTextField
label="Business Name (Optional)"
labelFor="businessName"
textInputName="businessName"
textInputPlaceholder="Enter your business's name"
inputType="secondary"
value={this.state.businessName}
onChange={this.saveToState}
/>
<SignupTextField
label="Email"
labelFor="email"
type="email"
textInputName="email"
textInputPlaceholder="Enter your email"
inputType="secondary"
required
value={this.state.email}
onChange={this.saveToState}
/>
<SignupTextField
label="Password"
labelFor="password"
type="password"
textInputName="password"
textInputPlaceholder="Enter your password"
inputType="secondary"
required
value={this.state.password}
onChange={this.saveToState}
/>
</SignupInputWrapper>
<SignupButton
buttonType="primary"
type="submit"
>
Sign Up
</SignupButton>
</fieldset>
</form>
);
}}
</Mutation>
<Link href={{ pathname: "/signin" }}>
<SigninLink>
Already have an account? <b>Sign In</b>
</SigninLink>
</Link>
</>
)}
</SignupCard>
</SignupContainer>
</SignupWrapper>
</>
)}
</User>
);
}
}
export default Signup;
|
3cfd851ea92ec7e4df4a5e675bf6af950660eb74
|
[
"JavaScript",
"Markdown"
] | 28
|
JavaScript
|
KasparIsSo/fence
|
a6d725df2280e0274f860dee7733f9930bb0fe87
|
ee3a269a72530bb047ea8f5462b6c21369c772a9
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.