branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>rjkip/OpenConext-engineblock<file_sep>/docs/release_notes/4.2.10.md
# OpenConext EngineBlock v4.2.10 Release Notes #
Bugfix release:
[json_encode(): Invalid UTF-8 sequence in argument in Log.php #104](https://github.com/OpenConext/OpenConext-engineblock/issues/104).
See also: [4.2.10 issue list](https://github.com/OpenConext/OpenConext-engineblock/issues?q=milestone%3A4.2.10+is%3Aclosed)
<file_sep>/docs/release_notes/4.2.9.md
# OpenConext EngineBlock v4.2.9 Release Notes #
Bugfix release:
[Improve dumping attachments to syslog #71](https://github.com/OpenConext/OpenConext-engineblock/issues/71).
<file_sep>/docs/release_notes/4.2.11.md
# OpenConext EngineBlock v4.2.11 Release Notes #
Bugfix release:
[Fixes #89 Ability to set SSP baseurlpath to specific value #122](https://github.com/OpenConext/OpenConext-engineblock/issues/89).
See also: [4.2.11 issue list](https://github.com/OpenConext/OpenConext-engineblock/issues?q=milestone%3A4.2.11+is%3Aclosed)
<file_sep>/library/EngineBlock/Doctrine/ConfigMapper.php
<?php
class EngineBlock_Doctrine_ConfigMapper
{
/**
* @var EngineBlock_Log
*/
private $logger;
/**
* @param EngineBlock_Log $log
*/
public function __construct(EngineBlock_Log $log)
{
$this->logger = $log;
}
public function map(Zend_Config $applicationConfiguration)
{
$databaseConfig = $applicationConfiguration->get('database');
if (!$databaseConfig || !$databaseConfig instanceof Zend_Config) {
throw new RuntimeException('No database configuration');
}
$masterParams = $this->mapMasterConfig($databaseConfig);
return array(
'wrapperClass' => 'Doctrine\DBAL\Connections\MasterSlaveConnection',
'driver' => $masterParams['driver'],
'master' => $masterParams,
'slaves' => $this->mapSlavesConfig($databaseConfig, $masterParams),
);
}
private function getParamsFromConfig(Zend_Config $config)
{
$dsn = $config->get('dsn');
$firstColonPos = strpos($dsn, ':');
$driver = substr($dsn, 0, $firstColonPos);
$params = array(
'driver' => 'pdo_' . $driver,
'user' => $config->get('user'),
'password' => $config->get('password'),
);
$dsn = substr($dsn, $firstColonPos+1);
$dsnRawParams = explode(';', $dsn);
foreach ($dsnRawParams as $dsnRawParam) {
$firstEqualsPos = strpos($dsnRawParam, '=');
$params[substr($dsnRawParam, 0, $firstEqualsPos)] = substr($dsnRawParam, $firstEqualsPos + 1);
}
return $params;
}
/**
* @param $databaseConfig
* @return array
* @throws Zend_Log_Exception
*/
private function mapMasterConfig(Zend_Config $databaseConfig)
{
$masters = $databaseConfig->get('masters');
if (!$masters || !$masters instanceof Zend_Config || $masters->count() === 0) {
throw new RuntimeException('No master databases configured');
}
if (count($masters) > 1) {
$this->logger->log('More than 1 master detected, using first', EngineBlock_Log::WARN);
}
$masterId = $masters->current();
$masterConfig = $databaseConfig->get($masterId);
if (!$masterConfig || !$masterConfig instanceof Zend_Config) {
throw new RuntimeException("Master '{$masterId}' mentioned but not configured");
}
return $this->getParamsFromConfig($masterConfig);
}
/**
* @param $databaseConfig
* @param $masterParams
* @return array
* @throws Zend_Log_Exception
*/
private function mapSlavesConfig(Zend_Config $databaseConfig, $masterParams)
{
$slaves = $databaseConfig->get('slaves');
if (!$slaves || !$slaves instanceof Zend_Config || $slaves->count() === 0) {
$slaves = array();
}
$slavesParams = array();
foreach ($slaves as $slaveId) {
$slaveConfig = $databaseConfig->get($slaveId);
if (!$slaveConfig || !$slaveConfig instanceof Zend_Config) {
$this->logger->log('Slave specified that has no configuration. Skipping.', EngineBlock_Log::WARN);
continue;
}
$slaveParams = $this->getParamsFromConfig($slaveConfig);
if ($slavesParams['driver'] !== $masterParams['driver']) {
$this->logger->log(
'Slave specified with different driver from master. Unsupported. Skipping.',
EngineBlock_Log::WARN
);
continue;
}
$slavesParams[] = $slaveParams;
}
if (empty($slavesParams)) {
$this->logger->log('No usable slaves configured, using master as slave', EngineBlock_Log::WARN);
$slavesParams[] = $masterParams;
}
return $slavesParams;
}
}
|
9470d6c2fc102225cf4a150092dc0233d116870d
|
[
"Markdown",
"PHP"
] | 4
|
Markdown
|
rjkip/OpenConext-engineblock
|
0783a1b0e8cb794d07f20be2b7f68fe20b3422a6
|
26274fda94437f237a0d7b20f9ebd4dce89aec0c
|
refs/heads/master
|
<file_sep>-- Onscreen widgets module for Conscience theme
local infojets = require("infojets")
local pango = infojets.util.pango
local wibox = require("wibox")
local asyncshell = require("asyncshell")
local onscreen = {}
local config = {}
function onscreen.init()
if theme.onscreen_config then
config = theme.onscreen_config
end
onscreen.init_logwatcher()
onscreen.init_processwatcher()
onscreen.init_calendar()
onscreen.init_jetclock()
end
function onscreen.init_logwatcher()
local c = config.logwatcher or {}
local wheight = c.height or 195
local wb = infojets.create_wibox({ width = c.width or 695,
height = wheight,
x = c.x or 23,
y = c.y or -29,
bg_color = theme.bg_onscreen })
w = infojets.logwatcher.new()
-- w:add_log_directory('/home/unlogic', { { file = '.xsession-errors',
-- mask = "(.+)" } })
w:add_log_directory('/var/log', {
{ file = 'auth.log',
mask = ".+ (%d%d:%d%d:%d%d )%w+ (.+)",
ignore = { "crond:session" }
},
-- { file = 'user.log',
-- mask = ".+ (%d%d:%d%d:%d%d )%w+ (.+)",
-- ignore = { "mtp-probe:" }
-- },
{ file = 'errors.log',
mask = ".+ (%d%d:%d%d:%d%d )%w+ (.+)",
ignore = { "dhcpcd", "sendmail" }
},
{ file = 'kernel.log',
mask = ".+ (%d%d:%d%d:%d%d )%w+ (%w+: )%[%s*[%d%.]+%] (.+)"
},
{ file = 'messages.log',
mask = ".+ (%d%d:%d%d:%d%d )%w+ (.+)",
ignore = { "\\-\\- MARK \\-\\-",
" kernel: " }
},
{ file = 'pacman.log',
mask = "%[(%d%d%d%d%-%d%d%-%d%d %d%d:%d%d)%](.+)" ,
ignore = { "Running " }
}
})
w.font = 'Helvetica 9'
w.title_font = 'Helvetica 9'
w:calculate_line_count(wheight)
w.line_length = c.line_length or 120
w:run()
wb:set_widget(w.widget)
end
function onscreen.init_processwatcher()
local c = config.processwatcher or {}
local wheight = c.height or 193
local wb = infojets.create_wibox({ width = c.width or 200, height = wheight,
x = c.x or -26, y = c.y or -31,
bg_color = theme.bg_onscreen })
infojets.processwatcher.default.current_file = 2
w = infojets.processwatcher.new()
w:set_process_sorters({ { name = "Top CPU",
sort_by = "pcpu",
ignore = { "defunct", "migration" } },
{ name = "Top memory",
sort_by = "rss",
ignore = { "defunct", "migration" } } })
w.font = 'DejaVu Sans Mono 10'
w.title_font = 'Helvetica 10'
w:calculate_line_count(wheight)
w.line_length = c.line_length or 40
w:run()
wb:set_widget(w.widget)
end
function onscreen.init_calendar()
local c = config.calendar or {}
local editor = "emacsclient -c"
local gcal_org = "/home/unlogic/Documents/Notes/gcal.org"
require('orglendar')
orglendar.files = { "/home/unlogic/Documents/Notes/edu.org",
gcal_org }
orglendar.text_color = c.text_color or theme.fg_focus
orglendar.today_color = c.today_color or theme.fg_onscreen
orglendar.event_color = theme.motive
orglendar.font = "DejaVu Sans Mono 10"
orglendar.char_width = 8.20
orglendar.limit_todo_length = c.limit_todo_length or 50
orglendar.parse_on_show = false
local cal_box_height = c.cal_height or 120
local cal_box = infojets.create_wibox({ width = c.cal_width or 170, height = cal_box_height,
x = c.cal_x or -35, y = c.cal_y or 45,
bg_color = theme.bg_onscreen })
infojets.reposition_wibox(cal_box)
local cal_layout = wibox.layout.align.horizontal()
local cal_tb = wibox.widget.textbox()
cal_tb:set_valign("top")
cal_layout:set_right(cal_tb)
cal_box:set_widget(cal_layout)
local todo_box = infojets.create_wibox({ width = c.todo_width or 300,
height = c.todo_height or 290,
x = c.todo_x or -30, y = (c.todo_y or 47) + cal_box_height,
bg_color = theme.bg_onscreen })
local todo_tb = wibox.widget.textbox()
local todo_layout = wibox.layout.align.horizontal()
todo_tb:set_valign("top")
todo_layout:set_left(todo_tb)
todo_box:set_widget(todo_layout)
local offset = 0
local update_orglendar =
function(inc_offset)
offset = offset + (inc_offset or 0)
local cal, todo = orglendar.get_calendar_and_todo_text(offset)
cal_tb:set_markup(cal)
todo_tb:set_markup(todo)
todo_box.width = orglendar.limit_todo_length * orglendar.char_width
infojets.reposition_wibox(todo_box)
end
local update_gcal_file =
function()
local ical_script = "/home/unlogic/scripts/ical2org"
local private_link = private.gcal_link
local dest = gcal_org
local req = "wget " .. private_link .. " -O /tmp/gcal.ics"
print(req)
asyncshell.request(req,
function()
os.execute(ical_script .. " < /tmp/gcal.ics > " .. dest)
orglendar.parse_agenda()
update_orglendar()
end)
end
update_gcal_file()
cal_tb:buttons(awful.util.table.join(
awful.button({ }, 2,
function ()
offset = 0
update_orglendar()
end),
awful.button({ }, 4,
function ()
update_orglendar(-1)
end),
awful.button({ }, 5,
function ()
update_orglendar(1)
end)))
todo_tb:buttons(awful.util.table.join(
awful.button({ }, 1,
function ()
awful.util.spawn(editor .. " " .. orglendar.files[1])
end),
awful.button({ }, 4,
function ()
update_orglendar(-1)
end),
awful.button({ }, 5,
function ()
update_orglendar(1)
end),
awful.button({ }, 3,
function ()
update_gcal_file()
orglendar.parse_agenda()
update_orglendar()
end)))
update_orglendar()
-- repeat_every(update_todo,600)
end
function onscreen.init_jetclock()
local c = config.clock or {}
local scrwidth = c.scrwidth or 1280 -- For current display
local radius = c.radius or 132
local clock_width = c.clock_hard_width or (radius * 2)
local clock_height = c.clock_hard_height or (radius * 2)
local info_height = c.height or 95
local wb = infojets.create_wibox({ width = clock_width,
height = clock_height + info_height,
x = c.x or (scrwidth / 2 - radius - 2),
y = c.y or 100,
bg_color = theme.bg_onscreen})
infojets.jetclock.bg_color = c.bg_color or "#222222CC"
infojets.jetclock.ring_bg_color = c.ring_bg_color or "#AAAAAA33"
infojets.jetclock.ring_fg_color = c.ring_fg_color or "#AAAAAAFF"
infojets.jetclock.hand_color = c.hand_color or "#CCCCCCCC"
infojets.jetclock.hand_motive = c.hand_motive or "#76eec6CC"
infojets.jetclock.text_hlight = c.text_hlight or theme.motive
infojets.jetclock.text_font = c.text_font or "Helvetica 11"
infojets.jetclock.shift_str = c.shift or " "
infojets.jetclock.shape = c.shape or "circle"
w = infojets.jetclock.new(clock_width, clock_height, info_height, radius)
remind = function(...) w:remind(...) end
w:run()
wb:set_widget(w.widget)
end
return onscreen<file_sep>-- Conscience awesome theme
-- By Unlogic, based on Blazeix nice-and-clean theme and Zhuravlik's theme
local util = require("awful.util")
local lustrous = require("lustrous")
theme = {}
local function res(res_name)
return theme.time_spec_dir .. "/" .. res_name
end
local function png_res(res_name)
return "png:" .. res(res_name)
end
theme.name = "Conscience v0.5"
theme.theme_dir = awful.util.getdir("config") .. "/themes/conscience"
theme.onscreen_file = "/onscreen.lua"
theme.time = lustrous.init({ theme_dir = theme.theme_dir,
lat = 50, lon = 30, offset = 3 })
theme.time_spec_dir = theme.theme_dir .. "/" .. theme.time
dofile(res("time_specific.lua"))
lustrous.update_gtk_theme('/home/unlogic/.gtkrc-2.0', res('.gtkrc-2.0'))
theme.wallpaper_cmd = { "awsetbg " .. res("background.jpg") }
theme.icon_dir = res("icons")
theme.font = "sans 8"
theme.bg_normal = png_res("bg_normal.png")
theme.bg_focus = png_res("bg_focus.png")
-- Display the taglist squares
theme.taglist_squares_sel = res("taglist/squarefw.png")
theme.taglist_squares_unsel = res("taglist/squarew.png")
-- Menu settings
theme.menu_submenu_icon = res("icons/submenu.png")
theme.menu_height = 15
theme.menu_width = 110
theme.menu_border_width = 0
-- Layout icons. I use only four layouts so the rest are not provided
-- and commented here. Add your own icons for missing layouts.
theme.layout_floating = res("layouts/floating.png")
theme.layout_max = res("layouts/max.png")
theme.layout_tile = res("layouts/tile.png")
theme.layout_tilebottom = res("layouts/tilebottom.png")
-- theme.layout_fairh = res("layouts/fairh.png")
-- theme.layout_fairv = res("layouts/fairv.png")
-- theme.layout_magnifier = res("layouts/magnifier.png")
-- theme.layout_fullscreen = res("layouts/fullscreen.png")
-- theme.layout_tileleft = res("layouts/tileleft.png")
-- theme.layout_tiletop = res("layouts/tiletop.png")
-- theme.layout_spiral = res("layouts/spiral.png")
-- theme.layout_dwindle = res("layouts/dwindle.png")
theme.awesome_icon = res("icons/awesome16.png")
-- Configure naughty
if naughty then
local presets = naughty.config.presets
presets.normal.bg = theme.bg_normal_color
presets.normal.fg = theme.fg_normal_color
presets.low.bg = theme.bg_normal_color
presets.low.fg = theme.fg_normal_color
presets.normal.border_color = theme.bg_focus_color
presets.low.border_color = theme.bg_focus_color
presets.critical.border_color = theme.motive
presets.critical.bg = theme.bg_urgent
presets.critical.fg = theme.motive
end
-- Onscreen widgets
local onscreen_file = theme.theme_dir .. theme.onscreen_file
if util.file_readable(onscreen_file) then
theme.onscreen = dofile(onscreen_file)
else
error("E: beautiful: file not found: " .. onscreen_file)
end
return theme
<file_sep>## Description ##
Conscience is an advanced theme for Awesome WM, which includes PNG
taskbar background and on-screen widgets. You can see how it looks on
the screenshot.png file.
Note that only a few layout icons are colored (because I use only
those layouts).
## Dependencies ##
Conscience depends on the following projects:
* [awesome pre-3.5](http://git.naquadah.org/awesome.git)
* [infojets v.0.4.0](https://github.com/alexander-yakushev/infojets)
* [orglendar v1.0.0](https://github.com/alexander-yakushev/Orglendar)
## Instalation ##
Install this awesome theme as normal. Place all files in conscience/
directory in in your themes directory, such as ~/.config/awesome/themes/conscience, and update your
rc.lua file:
beautiful.init("path/to/themes/conscience/theme.lua")
beautiful.onscreen.init()
<file_sep>-- Night mode of Conscience theme
theme.font = "sans 8"
theme.motive = "#76eec6"
theme.bg_normal_color = "#222222"
theme.bg_focus_color = "#444444"
theme.bg_urgent = "#7f7f7f"
theme.bg_minimize = "#444444"
theme.bg_onscreen = "#22222200"
theme.fg_normal = "#dddddd"
theme.fg_focus = "#ffffff"
theme.fg_urgent = "#ffffff"
theme.fg_minimize = "#ffffff"
theme.fg_onscreen = "#7f7f7f"
theme.border_width = 1
theme.border_normal = "#222222"
theme.border_focus = "#000000"
theme.border_marked = "#91231c"
theme.blingbling = { text_color = theme.bg_focus_color,
graph_color = theme.motive,
bg_graph_color = theme.bg_normal_color }
theme.onscreen_config = { logwatcher = { x = -20, y = -20, line_length = 80, width = 470 },
processwatcher = { x = -20, y = 30 },
clock = { x = 490, y = -172, radius = 123.25, height = 85,
clock_hard_width = 300,
clock_hard_height = 90 * 2.5,
ring_bg_color = theme.fg_normal .. "33",
ring_fg_color = theme.motive .. "FF",
hand_color = theme.motive .. "CC",
shape = "triangle",
shift = " "},
calendar = { text_color = theme.fg_normal,
today_color = theme.fg_onscreen,
cal_x = 15, todo_x = 15,
cal_y = 30, todo_y = 30 } }<file_sep>-- Day mode of Conscience theme
theme.font = "sans 8"
theme.motive = "#590900"
theme.motive2 = "#84472a"
theme.bg_normal_color = "#e3dad1"
theme.bg_focus_color = "#444444"
theme.bg_urgent = "#c77b4b"
theme.bg_minimize = "#e3dad1"
theme.bg_onscreen = "#FFFFFF00"
theme.fg_normal = "#000000"
theme.fg_focus = "#ffffff"
theme.fg_urgent = "#000000"
theme.fg_minimize = "#000000"
theme.fg_onscreen = "#7f7f7f"
theme.border_width = 1
theme.border_normal = "#222222"
theme.border_focus = "#000000"
theme.border_marked = "#91231c"
theme.blingbling = { text_color = theme.fg_focus,
graph_color = "#dec9b4",
bg_graph_color = "#590900" }
theme.onscreen_config = { logwatcher = { x = -20, y = -20, line_length = 80, width = 470 },
processwatcher = { x = -20, y = 30 },
clock = { x = 398, y = -1, radius = 160, height = 85,
ring_bg_color = theme.motive2 .. "33",
ring_fg_color = theme.motive2 .. "FF",
hand_color = theme.motive2 .. "CC",
shift = " ",
shape = "circle" },
calendar = { text_color = theme.fg_normal,
today_color = theme.motive2,
cal_x = 15, todo_x = 15,
cal_y = 30, todo_y = 30 } }
|
594b08a37fdd627f23e5a0ce1f81319ee349b54d
|
[
"Markdown",
"Lua"
] | 5
|
Lua
|
alexander-yakushev/conscience-awesome-theme
|
bc79820a1ac8b886d7496955fd36884aa06c201c
|
f5388040aa56287f3efa0cb04766c8275690bdaf
|
refs/heads/master
|
<repo_name>Vermillio/All-Hammocks-Finding-Graph<file_sep>/Task21/T_Graph.h
#ifndef T_GRAPH_H
#define T_GRAPH_H
#include <list>
#include <vector>
#include <list>
#include <set>
using namespace std;
class T_Graph
{
vector<list<int>> graph;
vector<bool> vizited;
vector<set<int>> hammocks;
set<int> stack;
void ErrorMessage (string _error);
vector<set<int>> getDominatorsForeachVertex (vector<list<int>> gp, int end);
bool IsNotMinimalHammock(vector<set<int>> hammocks, int start, int end);
public:
int start, end;
vector<list<int>> transpose ();
void fexport (string _filename);
void fimport (string _filename);
vector<set<int>> findHammocks ();
void printGraph ();
void printHammocks ();
T_Graph (vector<list<int>> gr)
: graph(gr) {};
T_Graph () {};
};
set<int> intersection (set<int> A, set<int> B);
void print(vector<set<int>> x);
void print(set<int> x);
#endif<file_sep>/Task21/T_Graph.cpp
#include "T_Graph.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <string>
#include <list>
#include <set>
#include <queue>
#include <iterator>
using namespace std;
void T_Graph::ErrorMessage (string _error)
{
cout << "Error : " << _error << ". " << endl;
}
vector<set<int>> T_Graph::getDominatorsForeachVertex (vector<list<int>> gp, int end)
{
vector<set<int>> dp;
dp.resize(gp.size());
for (int i = 0; i < gp.size(); ++i)
for (int j = 0; j < gp.size(); ++j)
dp[i].insert(j);
dp[end].clear();
dp[end].insert(end);
bool change;
vector<bool> changed(gp.size());
for (int i = 0; i < gp.size(); ++i)
changed[i] = false;
changed[end] = true;
do
{
change = false;
for (int i = 0; i < gp.size(); i++)
{
int oldSize = dp[i].size();
for (int next : gp[i])
{
if (changed[next])
{
set<int> tmp;
set_intersection(dp[i].begin(), dp[i].end(), dp[next].begin(), dp[next].end(), std::inserter(tmp, tmp.begin()));
dp[i].clear();
dp[i] = tmp;
tmp.clear();
}
}
dp[i].insert(i);
if (i != end)
changed[i] = (oldSize != dp[i].size());
if (oldSize != dp[i].size())
change = true;
}
} while (change);
return dp;
}
vector<list<int>> T_Graph::transpose ()
{
int size = graph.size();
vector<list<int>> transp(size);
for (int i = 0; i < size; ++i)
{
for (auto j = graph[i].begin(); j != graph[i].end(); ++j)
transp[*j].push_back(i);
}
return transp;
};
void T_Graph::fimport (string _filename)
{
ifstream fin(_filename);
if (!fin.is_open())
{
ErrorMessage("Couldn't open file.");
return;
}
char buff[20];
int i = 0, num;
start = i;
while (!fin.eof())
{
fin >> buff;
if (isdigit(buff[0]))
{
num = atoi(buff);
if (graph.size() <= num)
graph.resize(num + 1);
graph[i].push_back(num);
}
else {
++i;
if (graph.size() < i)
graph.resize(i);
}
}
end = i-1;
fin.close();
}
vector<set<int>> T_Graph::findHammocks ()
{
auto g_t = transpose();
vector<set<int>> dp = getDominatorsForeachVertex(graph, end);
vector<set<int>> dpt = getDominatorsForeachVertex(g_t, start);
for (int i = 0; i < graph.size(); i++)
{
dp[i].erase(i);
set<int> newSet;
for (int v : dp[i])
if (dpt[v].find(i) != dpt[v].end())
newSet.insert(v);
dp[i] = newSet;
}
for (int v = 0; v < dp.size(); v++)
{
auto u = dp[v].begin();
while (u != dp[v].end())
{
if (IsNotMinimalHammock(dp, v, *u))
dp[v].erase(u++);
else u++;
}
}
hammocks = dp;
return dp;
}
bool T_Graph::IsNotMinimalHammock (vector<set<int>> hammocks, int start, int end)
{
set<int> used;
queue<int> q;
q.push(start);
used.insert(start);
while (q.size() > 0)
{
int cur = q.front();
q.pop();
if (cur == end)
return true;
for (int next : hammocks[cur])
{
if (used.find(next) == used.end() )
{
if (cur == start && next == end)
continue;
q.push(next);
used.insert(next);
}
}
}
return false;
}
void T_Graph::printGraph ()
{
}
void T_Graph::fexport (string _filename)
{
ofstream fout(_filename);
if (!fout.is_open())
ErrorMessage(0);
for (int i = 0; i<graph.size(); ++i)
{
for (auto j = graph[i].begin(); j != graph[i].end(); ++j)
{
fout << *j;
fout << " ";
}
fout << "|";
}
fout.close();
}
void print (set<int> x)
{
cout << "{ ";
for (auto i : x)
cout << i << " ";
cout << "}" << endl;
}
void print (vector<set<int>> x)
{
for (auto i : x)
print(i);
}<file_sep>/Task21/Source.cpp
#include "T_Graph.h"
#include <string>
#include <xstring>
#include <iostream>
using namespace std;
string getcd()
{
wchar_t *s = nullptr;
wstring ws = _wgetcwd(s, _MAX_PATH);
return string(ws.begin(), ws.end());
}
int main()
{
string cd = getcd();
string filename;
cout << "Enter filename (should be stored here: " << endl << "( " << cd << " )" << endl;
cin >> filename;
T_Graph gr;
gr.fimport(cd + "\\" + filename);
vector<set<int>> hammocks = gr.findHammocks();
print(hammocks);
system("pause");
return 0;
}
|
f191d70e8019d0ddedcf8e515a4e0e30e3b68d4f
|
[
"C++"
] | 3
|
C++
|
Vermillio/All-Hammocks-Finding-Graph
|
0a2e88de6beb7559f8eed204f5028d317cbb4509
|
119a27c3082c6fb017fe3f8165a801526126312f
|
refs/heads/master
|
<repo_name>francescooliva/RPi-Temperature-And-Humidity-station-with-camera<file_sep>/dht22_sensing.py
#!/usr/bin/python
# for the Adafruit_DHT library:
# Copyright (c) 2014 Adafruit Industries
# Author: <NAME>
# for the MySQL and PhP part I also took for reference:
# http://www.instructables.com/id/Raspberry-PI-and-DHT22-temperature-and-humidity-lo/
# https://github.com/jjpFin/DHT22-TemperatureLogger/blob/master/DHT22logger.py
# Author: <NAME>
import sys
import time
import datetime
import MySQLdb
import Adafruit_DHT
# Parse command line parameters.
sensor_args = { '11': Adafruit_DHT.DHT11,
'22': Adafruit_DHT.DHT22,
'2302': Adafruit_DHT.AM2302 }
if len(sys.argv) == 3 and sys.argv[1] in sensor_args:
sensor = sensor_args[sys.argv[1]]
pin = sys.argv[2]
else:
print('usage: sudo ./Adafruit_DHT.py [11|22|2302] GPIOpin#')
print('example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO #4')
sys.exit(1)
# grab a sensor reading, the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
currentTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print (time.strftime("%c"))
if humidity is not None and temperature is not None:
print('Temperature = {0:0.1f}* Humidity = {1:0.1f}%'.format(temperature, humidity))
else:
print('Failed to get reading. Try again!')
sys.exit(1)
# database connection
db = MySQLdb.connect("localhost", "logger", "password", "<PASSWORD>")
curs = db.cursor()
# insert query
query = "INSERT INTO temperaturedata SET dateandtime='%s', temperature='%s', humidity='%s'" % (currentTime, temperature, humidity)
try:
curs.execute(query)
db.commit()
except:
print "Error: the database is being rolled back"
db.rollback()
sys.exit(0)
# close stdout and stderr before exiting the script
try:
sys.stdout.close()
except:
pass
try:
sys.stderr.close()
except:
pass
<file_sep>/myscript.sh
#!/bin/bash
sudo /etc/init.d/motion stop && \
sudo python /home/pi/Desktop/workspace/dht22_sensing.py 22 4 > \
/home/pi/Desktop/workspace/text.txt && \
sudo /etc/init.d/motion start
<file_sep>/index.php
<?php $fh = fopen('/home/pi/Desktop/workspace/text.txt','r'); while ($line = fgets($fh)) {
// <... Do your work with the line ...>
echo "<br>";
echo "<b>{$line}</b>", PHP_EOL;
echo "<br>";
}
fclose($fh);
?>
<head>
</head>
<html>
<br>
<img src= "lastsnap.jpg"/>
<p><strong>Live streaming: http://meteoficobianco.hopto.org:8081/</strong></p>
</html>
<?php
// credits: http://www.instructables.com/id/Raspberry-PI-and-DHT22-temperature-and-humidity-lo
// settings
// host, user and password settings
$host = "localhost";
$user = "logger";
$password = "<PASSWORD>";
$database = "temperatures";
//how many hours backwards do you want results to be shown in web page.
$hours = 24;
// make connection to database
$con = mysql_connect($host,$user,$password);
// select db
mysql_select_db($database,$con);
// sql command that selects all entires from current time and X hours backwards
$sql="SELECT * FROM temperaturedata WHERE dateandtime >= (NOW() - INTERVAL $hours HOUR) ORDER BY dateandtime DESC ";
// set query to variable
$temperatures = mysql_query($sql);
?>
<html>
<head>
<title>Raspberry Pi Temperature And Humidity station with camera </title>
</head>
<body>
</body>
<br>
<table width="400" border = "1" >
<caption><b>Previous readings from the database</b></caption>
<tr>
<th>Date</th>
<th>Temperature</th>
<th>Humidity</th>
</tr>
<?php
// loop all the results that were read from database and "draw" to web page
while($temperature=mysql_fetch_assoc($temperatures)){
echo "<tr>";
echo "<td>".$temperature['dateandtime']."</td>";
echo "<td>".$temperature['temperature']."</td>";
echo "<td>".$temperature['humidity']."</td>";
echo "<tr>";
}
?>
</table>
</html>
<file_sep>/README.md
## A little project for the UC Irvine IoT specialization capstone on Coursera.
https://www.youtube.com/watch?v=OG_WmlhB90A
## Sources and Bibliography:
https://learn.adafruit.com/dht-humidity-sensing-on-raspberry-pi-with-gdocs-logging/overview
http://www.instructables.com/id/Raspberry-Pi-remote-webcam/
http://www.instructables.com/id/Raspberry-Pi-Temperature-Humidity-Network-Monitor/
http://www.instructables.com/id/Raspberry-PI-and-DHT22-temperature-and-humidity-lo/
http://raspberrywebserver.com/sql-databases/using-mysql-on-a-raspberry-pi.html/
http://www.noip.com/support/knowledgebase/install-ip-duc-onto-raspberry-pi/
https://www.raspberrypi.org/documentation/remote-access/
https://www.raspberrypi.org/documentation/linux/usage/cron.md
https://www.raspberrypi.org/learning/lamp-web-server-with-wordpress/
<file_sep>/testwebcam/index.php
<?php
$fh = fopen('/home/pi/Desktop/workspace/text.txt','r');
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
echo "<br>";
echo "<b>{$line}</b>", PHP_EOL;
echo "<br>";
}
fclose($fh);
?>
<head>
</head>
<html>
<br>
<img src= "http://<?php echo $_SERVER['HTTP_HOST'];?>:8081/?action=stream"/>
<br>
</html>
|
b093c072dcf3e3a4ccb4446f5e1196f04b9841d8
|
[
"Markdown",
"Python",
"PHP",
"Shell"
] | 5
|
Python
|
francescooliva/RPi-Temperature-And-Humidity-station-with-camera
|
d13abc11350592ab8fb6ca67780ae40d40bc412f
|
e75638ae81c27d8721d3ae5d09328b16567d2b60
|
refs/heads/master
|
<file_sep>--Up function
function up()
turtle.up()
turtle.up()
turtle.digUp()
turtle.up()
turtle.up()
turtle.select(1)
turtle.placeDown()
end
--Down function
function down()
turtle.digDown()
turtle.down()
turtle.down()
turtle.select(1)
turtle.placeUp()
turtle.down()
turtle.down()
end
--Was function
function wassen()
rs.setOutput("front", true)
rs.setOutput("back", false)
rs.setBundledOutput("top", colors.orange)
i=0
repeat
rs.setOutput("left", true)
rs.setOutput("right", true)
rs.setOutput("bottom", true)
sleep(0.5)
rs.setOutput("left", false)
rs.setOutput("right", false)
rs.setOutput("bottom", false)
sleep(0.5)
i=i+1
until i==20
sleep(3)
rs.setBundledOutput("top", colors.white)
i=0
repeat
rs.setOutput("left", true)
rs.setOutput("right", true)
rs.setOutput("bottom", true)
sleep(0.5)
rs.setOutput("left", false)
rs.setOutput("right", false)
rs.setOutput("bottom", false)
sleep(0.5)
i=i+1
until i==25
rs.setOutput("left", true)
rs.setOutput("right", true)
rs.setOutput("bottom", true)
rs.setBundledOutput("top", 0)
rs.setOutput("back", true)
print("gelukt")
end
--Code
print("Up or down?")
input = read()
if input=="Up" then
up()
print("Check")
elseif input=="Down" then
down()
print("Check")
elseif input=="Wassen" then
up()
wassen()
print("Check")
elseif input=="Reset" then
rs.setOutput("front", false)
rs.setOutput("back", false)
rs.setBundledOutput("top", 0)
down()
print("Check")
end
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author roemerhendrikx
*/
import essentials.InstallerInput;
public class bioinstall {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
InstallerInput roemba = new InstallerInput();
roemba.setVisible(true);
System.out.println("bioinstall finished running");
}
}
|
263d21236d11793a92d06fbcd7e2bcde3d377b2b
|
[
"Java",
"Lua"
] | 2
|
Lua
|
roemba/BioCraft-Installer
|
16802f0e426222d33741c44c75374c95413bd308
|
1e58dca24a97e61b21f367b0fdd8b363616d16de
|
refs/heads/master
|
<repo_name>NandoKstroNet/brazi.la<file_sep>/modules/hello.js
'use strict';
/**
*
*/
module.exports = function(req, res){
console.log('Hello World!!');
};
<file_sep>/README.md
Brazi.la [![Build Status][travis-image]][travis-url] [![Dependency Status][depstat-image]][depstat-url]
====
A fresh new CMS made with MEAN and love :P
## Installing
Run this:
```bash
git clone <EMAIL>:NodeJS-Brasil/brazi.la.git brazila
cd brazila
npm install
```
Create the config.js with your environment configs.
Use the config-exemple.js for instructions
## Contributing
1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request :D
## Licence
[The MIT License](http://nodejsbrasil.mit-license.org/) @NodeJSBrasil
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[](https://bitdeli.com/free "Bitdeli Badge")
[travis-url]: https://travis-ci.org/NodeJS-Brasil/brazi.la
[travis-image]: https://travis-ci.org/NodeJS-Brasil/brazi.la.png?branch=master
[depstat-url]: https://david-dm.org/NodeJS-Brasil/brazi.la
[depstat-image]: https://david-dm.org/NodeJS-Brasil/brazi.la.png<file_sep>/config-exemple.js
'use strict';
module.exports = {
general: {
lang: 'en_US',
debug: false,
admin_url: 'admin',
modules_url: 'modules',
themes_url: 'themes',
uploads: 'uploads'
},
personal: {
active_theme: 'rio',
actived_modules: [
'hello'
]
},
development: {
url: 'http://localhost/brazila',
mail: {},
database: {},
},
production: {},
};<file_sep>/index.js
'use strict';
var config = require('./config'),
core = require('./system/core'),
validConfig = core.validateConfigs(config);
if(validConfig !== true){
core.init(config);
} else {
console.log(validConfig);
}
|
31843e9923bba8aee588e62909a3f004179dd84c
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
NandoKstroNet/brazi.la
|
0e4d8c0a5eb22f42f4aca4579c8deac76d2e20c6
|
2478dfc8fb42bd189341e1f1598d5bffe7364fd4
|
refs/heads/master
|
<file_sep>'use strict';
var Router = require('./app/router');
var App = Marionette.Application.extend({
initialize: function() {
this.router = new Router();
}
});
$(function() {
$(document).on('click', 'a[data-ref]', function(e) {
e.preventDefault();
Backbone.history.navigate($(this).data('ref'), { trigger: true });
});
});
module.exports = new App();<file_sep>'use strict';
module.exports = Marionette.AppRouter.extend({
routes: {
'list': 'list'
},
list: function() {
console.log('List.');
}
});
|
080fff17309218502acba3630d260d359659522f
|
[
"JavaScript"
] | 2
|
JavaScript
|
vstukanov/webpack-marionette-seed
|
61bba7f16b45d8a3b346eaa17e73a7e2a96ca066
|
d0aa30dc41e7d466e09bc2e221d7ad477d939bcb
|
refs/heads/master
|
<repo_name>vvchuong/real-estate<file_sep>/config/routes.rb
Application.routes.draw do
use_doorkeeper
devise_for :users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
mount API::Base => '/api'
root to: 'index#index'
end
<file_sep>/db/seeds.rb
['registered', 'agent', 'company', 'admin'].each do |role|
Role.find_or_create_by({name: role})
end
users = %w(jon.snow hodor shae tyrion.lannister).map do |username|
{ email: <EMAIL>", password: '<PASSWORD>' }
end
User.create(users)
oauth_app = {
name: 'Angular Application',
redirect_uri: "http://#{ENV['HOST']}",
uid: ENV['APPLICATION_ID']
}
Doorkeeper::Application.find_or_create_by(oauth_app)
|
c1f250cead2e4488ecebaec5bf6acd93b45d6ce5
|
[
"Ruby"
] | 2
|
Ruby
|
vvchuong/real-estate
|
5052f79a945bca78ae8b75ffff918ceddcf86ada
|
8b8be8296876fbf112c861e21ae6d2b1bdd8ed3a
|
refs/heads/master
|
<repo_name>SreekrishnaSridhar/ExData_Plotting1<file_sep>/MainData.R
data <- read.table("household_power_consumption.txt",header = TRUE,sep = ";",colClasses = c("character","character",rep("numeric",7),na="?"))
data$Time <- strptime(paste(data$Date, data$Time), "%d/%m/%Y %H:%M:%S")
data$Date <- as.Date(data$Date,"%d/%m/%Y")
date <- as.Date(c("2007-02-01","2007-02-02"),"%Y-%m-%d")
data <- subset(data, Date %in% date)<file_sep>/plot3.R
source("MainData.R")
png("plot3.png",width = 480,height = 480)
par(mfrow = c(1,1))
plot(data$Time,data$Sub_metering_1,ylab = "Energy Sub metering",col = "black",type = "l",xlab = "")
lines(data$Time,data$Sub_metering_2,col = "red")
lines(data$Time,data$Sub_metering_3,col = "blue")
legend("topright", lty = 1, col = c("black","red","blue"),c("Sub_metering_1","Sub_metering_2","Sub_metering_3"))
dev.off()<file_sep>/plot4.R
source("MainData.R")
png("plot4.png",width = 480,height = 480)
par(mfrow = c(2,2))
##1
plot(data$Time,as.numeric(data$Global_active_power),type = "l",xlab = "",ylab = "Global Active Power(kilowatts)")
##2
plot(data$Time,data$Voltage,type = "l",xlab = "datetime",ylab = "Voltage")
##3
plot(data$Time,data$Sub_metering_1,ylab = "Energy Sub metering",col = "black",type = "l",xlab = "")
lines(data$Time,data$Sub_metering_2,col = "red")
lines(data$Time,data$Sub_metering_3,col = "blue")
legend("topright", lty = 1, col = c("black","red","blue"),c("Sub_metering_1","Sub_metering_2","Sub_metering_3"))
##4
plot(data$Time,as.numeric(data$Global_reactive_power),type = "l",xlab = "datetime",ylab = "Global_reactive_power")
dev.off()<file_sep>/plot1.R
source("MainData.R")
png("plot1.png",width = 480,height = 480)
par(mfrow = c(1,1))
hist(as.numeric(data$Global_active_power), xlab = "Global Active Power(kilowatts)",col = "red",main = "Global Active Power")
dev.off()<file_sep>/plot2.R
source("MainData.R")
png("plot2.png",width = 480,height = 480)
par(mfrow = c(1,1))
plot(data$Time,as.numeric(data$Global_active_power),type = "l",xlab = "",ylab = "Global Active Power(kilowatts)")
dev.off()
|
2e8acf6d27521f1032bf9c5e22d76c6cc85e9034
|
[
"R"
] | 5
|
R
|
SreekrishnaSridhar/ExData_Plotting1
|
a2272e5f8d96584147f0234d6dbd0e52bd81cebe
|
98c77e0e146159e99d99bd86d5949bb2c19758f6
|
refs/heads/master
|
<file_sep>import db from '../db';
import Promise from 'bluebird';
const TABLE_NAME = 'dc_post';
function formatWhere(where) {
let _where = [];
for (let k in where) {
_where.push(`${k} = ${db.escape(where[k])}`);
}
return _where.join(' && ');
}
function promisify(sql) {
return new Promise(function(resolve, reject) {
db.query(sql, function(err, rows) {
if (err) {
reject(err);
} else {
resolve(rows);
}
});
});
}
export function count() {
let sql = `SELECT count(id) FROM ${TABLE_NAME}`;
return promisify(sql).then(rows => {
return rows.length > 0 ? rows[0]['count(id)'] : 0;
});
}
export function findByPathname(pathname) {
let where = formatWhere({ pathname: pathname });
let sql = `SELECT * FROM ${TABLE_NAME} WHERE ${where}`;
return promisify(sql).then(rows => {
return rows.length > 0 ? rows[0] : null;
});
}
export async function findByPage(currentPage) {
let pageSize = 2;
let totals = await count();
let totalPages = Math.ceil(totals / pageSize);
let limit = (currentPage - 1) * pageSize + ',' + pageSize;
let sql = `SELECT * FROM ${TABLE_NAME} ORDER BY create_time DESC LIMIT ${limit}`;
return promisify(sql).then(rows => ({ totals, rows, pageSize, currentPage, totalPages }));
}
<file_sep># 52dachu
https://52dachu.com
|
f8b6dfedcf506ec2f31e8f5c7d27071d81243a13
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
xiaoyann/52dachu
|
a28762b9ad669b3322fdd2dba9ba8c6d67a92b6c
|
c047110e1d50364048d930326aa9773e82957209
|
refs/heads/master
|
<repo_name>nGustavin/clone-twitter<file_sep>/src/components/Feed/styles.ts
import styled from 'styled-components'
export const Container = styled.div`
display: flex;
flex-direction: column;
`
export const Tab = styled.div`
margin-top: 10px;
padding: 11px 0 15px;
`
|
3c5f6796a408c9e7bc82853e7699c1ba4ddf49c0
|
[
"TypeScript"
] | 1
|
TypeScript
|
nGustavin/clone-twitter
|
b29f04ef8643c406bd1584d1d742e6e5c1d55494
|
1a8053d1d07a31dd8851c5c3cdf7e75f21798076
|
refs/heads/main
|
<repo_name>elenuco/OPorprisiones-landing-page<file_sep>/src/App.js
import "./styles.css";
import Navbar from "./components/Navbar";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
export default function App() {
return (
<body id="e11_1">
<div clas="row" name="nav-bar">
<div class="col-md-3"></div>
<div id="e42_4" class="col-md-9"></div>
</div>
<div class="container-fluid">
<form class="d-flex">
<img src="/assets/check_box.svg" alt="Oporprisiones logo" id="logo" />
<span id="e15_77">Oporprisiones</span>
<span id="e16_7">Registrate</span>
<span id="e16_6">Iniciar</span>
</form>
</div>
<div name="presentacion">
<span id="e16_57">Aprueba con nuestro método</span>
<span id="e16_58">
Unete al Cuerpo de Ayudantes de Instituciones Penitenciarias
</span>
<img
src="/assets/Analytics process_Monochromatic.svg"
alt="personas analizando datos"
id="icono_1"
/>
</div>
<div name="Que-es">
<img
src="/assets/Information flow_Monochromatic.svg"
alt="persona trabajando"
id="icono_2"
/>
</div>
</body>
);
}
<file_sep>/README.md
# OPorprisiones-landing-page
Created with CodeSandbox
|
954819aceb422b05427fd17b551e980f8b71923c
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
elenuco/OPorprisiones-landing-page
|
b118bda88920d1ec3f04b939f270ae73dd92dcf6
|
7ca54fa2d2884f102007ce3d63bd8e7fbe5dc994
|
refs/heads/main
|
<file_sep>#!/usr/bin/env python
# coding: utf-8
# In[6]:
import numpy as np
# In[ ]:
Question:1
get_ipython().set_next_input('Convert a 1D array to a 2D array with 2 rows');get_ipython().run_line_magic('pinfo', 'rows')
Desired output::
array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
# In[26]:
a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a.reshape(2,5)
# In[ ]:
Question:2
get_ipython().set_next_input('How to stack two arrays vertically');get_ipython().run_line_magic('pinfo', 'vertically')
Desired Output::
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]])
# In[29]:
arr1 = np.array([[0, 1, 2, 3, 4] , [5, 6, 7, 8, 9]])
arr2 = np.array([[1, 1, 1, 1, 1] , [1, 1, 1, 1, 1]])
arr = np.vstack((arr1, arr2))
print(arr)
# In[ ]:
Question:3
get_ipython().set_next_input('How to stack two arrays horizontally');get_ipython().run_line_magic('pinfo', 'horizontally')
Desired Output::
array([[0, 1, 2, 3, 4, 1, 1, 1, 1, 1],
[5, 6, 7, 8, 9, 1, 1, 1, 1, 1]])
# In[33]:
arr1 = np.array([[0, 1, 2, 3, 4] , [5, 6, 7, 8, 9]])
arr2 = np.array([[1, 1, 1, 1, 1] , [1, 1, 1, 1, 1]])
arr = np.hstack((arr1, arr2))
print(arr)
# In[ ]:
Question:4
get_ipython().set_next_input('How to convert an array of arrays into a flat 1d array');get_ipython().run_line_magic('pinfo', 'array')
Desired Output::
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# In[41]:
f = np.array([[0,1,2,3,4], [5,6,7,8,9,]])
x = f.reshape(-1)
print(x)
# In[ ]:
Question:5
get_ipython().set_next_input('How to Convert higher dimension into one dimension');get_ipython().run_line_magic('pinfo', 'dimension')
Desired Output::
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
# In[49]:
f = np.array([[[0,1,2,3,4,], [5,6,7,8,9] , [10,11,12,13,14]]])
x = f.reshape(-1)
print(x)
# In[ ]:
Question:6
get_ipython().set_next_input('Convert one dimension to higher dimension');get_ipython().run_line_magic('pinfo', 'dimension')
Desired Output::
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14]])
# In[51]:
f = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14])
x = f.reshape(5,3)
print(x)
# In[ ]:
Question:7
get_ipython().set_next_input('Create 5x5 an array and find the square of an array');get_ipython().run_line_magic('pinfo', 'array')
# In[62]:
a = np.random.randn(5,5)
a
# In[69]:
np.square(a)
# In[ ]:
Question:8
get_ipython().set_next_input('Create 5x6 an array and find the mean');get_ipython().run_line_magic('pinfo', 'mean')
# In[70]:
a = np.random.randn(5,6)
a
# In[71]:
a.mean()
# In[ ]:
Question:9
get_ipython().set_next_input('Find the standard deviation of the previous array in Q8');get_ipython().run_line_magic('pinfo', 'Q8')
# In[73]:
a.std()
# In[ ]:
Question:10
get_ipython().set_next_input('Find the median of the previous array in Q8');get_ipython().run_line_magic('pinfo', 'Q8')
# In[75]:
np.median(a)
# In[ ]:
Question:11
get_ipython().set_next_input('Find the transpose of the previous array in Q8');get_ipython().run_line_magic('pinfo', 'Q8')
# In[78]:
a.T
# In[ ]:
Question:12
get_ipython().set_next_input('Create a 4x4 an array and find the sum of diagonal elements');get_ipython().run_line_magic('pinfo', 'elements')
# In[81]:
a = np.random.randn(4,4)
a
# In[82]:
np.trace(a)
# In[ ]:
Question:13
get_ipython().set_next_input('Find the determinant of the previous array in Q12');get_ipython().run_line_magic('pinfo', 'Q12')
# In[88]:
det = np.linalg.det(a)
det
# In[ ]:
Question:14
get_ipython().set_next_input('Find the 5th and 95th percentile of an array');get_ipython().run_line_magic('pinfo', 'array')
# In[98]:
np.percentile(a, 5)
# In[99]:
np.percentile(a, 95)
# In[ ]:
Question:15
get_ipython().set_next_input('How to find if a given array has any null values');get_ipython().run_line_magic('pinfo', 'values')
# In[92]:
a = np.random.randn(2,2)
a
# In[100]:
np.isnan(a)
|
72897023bc42c5e85380af0a9bde016188f0de9b
|
[
"Python"
] | 1
|
Python
|
AhmadFaraz3233/PIAIC-NUMPY-
|
01f439a3573b5f27164986c665e3ab56b856e4e0
|
99ecaf4def609b5207c3a09832f2dde27e05c5f3
|
refs/heads/master
|
<file_sep># Part Number Finder
Supportig tool for ProCat<file_sep>DELIMITER //
CREATE TRIGGER formatted_item_code_reset_by_year BEFORE INSERT ON part_numbers FOR EACH ROW
BEGIN
IF (
SELECT COUNT(item_code)
FROM part_numbers
WHERE item_name = NEW.item_name
AND short_desc = NEW.short_desc
AND po_text = NEW.po_text) > 0 THEN
SET NEW.item_code =
(SELECT item_code
FROM part_numbers
WHERE item_name = NEW.item_name
AND short_desc = NEW.short_desc
AND po_text = NEW.po_text
LIMIT 1);
ELSE
SET NEW.item_code =
(SELECT IFNULL(MAX(item_code),0)+1
FROM part_numbers
WHERE DATE_FORMAT(created_at,"%Y") = DATE_FORMAT(now(),"%Y"));
END IF;
END//
DELIMITER ;<file_sep><?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
factory('App\User')->create([
'username' => 'super',
'name' => 'Super Administrator',
'email' => '<EMAIL>',
]);
factory('App\User')->create([
'username' => 'admin',
'name' => 'Administrator',
'email' => '<EMAIL>',
]);
factory('App\User')->create([
'username' => 'khoerodin',
'name' => 'Khoerodin',
'email' => '<EMAIL>',
]);
factory('App\Role')->create([
'name' => 'super',
'label' => 'Super Administrator',
]);
factory('App\Role')->create([
'name' => 'admin',
'label' => 'Administrator',
]);
factory('App\Role')->create([
'name' => 'user',
'label' => 'User',
]);
factory('App\Permission')->create([
'name' => 'partnumber.view',
'label' => 'Mambuka Halaman Pencarian',
]);
factory('App\Permission')->create([
'name' => 'partnumber.search',
'label' => 'Melakukan Pencarian',
]);
factory('App\Permission')->create([
'name' => 'partnumber.download',
'label' => 'Melakukan Download Hasil Pencarian',
]);
factory('App\Permission')->create([
'name' => 'import.view',
'label' => 'Membuka Halaman Import',
]);
factory('App\Permission')->create([
'name' => 'import.import',
'label' => 'Meng-import data',
]);
factory('App\Permission')->create([
'name' => 'user.register',
'label' => 'Me-registrasikan User',
]);
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePartNumberTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('part_numbers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('item_code');
$table->string('inc', 5)->default('');
$table->string('item_name');
$table->string('short_desc', 50);
$table->string('man_code', 10);
$table->string('man_name')->default('');
$table->string('part_number');
$table->text('po_text');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('part_numbers');
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Auth::routes();
Route::group(['middleware' => 'auth'], function () {
Route::get('/', 'PartNumberController@index');
Route::get('search', 'PartNumberController@search');
Route::get('excel', 'PartNumberController@excel');
Route::get('me', 'MeController@index');
Route::post('me/update', 'MeController@update');
Route::get('import', 'ImportController@index');
Route::post('import/upload', 'ImportController@upload')->name('upload');
Route::get('import/read/{file}', 'ImportController@read');
Route::get('import/import-part-number/{file}', 'ImportController@importPartNumber');
Route::resource('users', 'UserController');
Route::resource('users.roles', 'UserRoleController');
Route::post('users/{user}/roles', 'UserRoleController@update');
Route::resource('users.permissions', 'UserPermissionController');
Route::post('users/{user}/permissions', 'UserPermissionController@update');
Route::resource('roles', 'RoleController');
Route::get('roles/{role}/permissions', 'RolePermissionController@index');
Route::post('roles/{role}/permissions', 'RolePermissionController@update');
});
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class MeController extends Controller
{
public function index()
{
return view('me');
}
public function update(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users,email,'.\Auth::user()->id,
'username' => 'required|alpha_num|max:255|unique:users,username,'.\Auth::user()->id,
'password' => '<PASSWORD>',
'password_confirmation' => '<PASSWORD>',
]);
if ($request->password == '' || $request->password == null) {
$user = User::find(\Auth::user()->id);
$user->name = $request->name;
$user->email = $request->email;
$user->username = $request->username;
$user->save();
}else{
$user = User::find(\Auth::user()->id);
$user->name = $request->name;
$user->email = $request->email;
$user->username = $request->username;
$user->password = <PASSWORD>($request->password);
$user->save();
}
return redirect('me')->with('status', 'Profile updated!');;
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFormattedItemCodeResetByYearTrigger extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::unprepared('
CREATE TRIGGER formatted_item_code_reset_by_year BEFORE INSERT ON part_numbers FOR EACH ROW
BEGIN
IF (
SELECT COUNT(item_code)
FROM part_numbers
WHERE item_name = NEW.item_name
AND short_desc = NEW.short_desc
AND po_text = NEW.po_text) > 0 THEN
SET NEW.item_code =
(SELECT item_code
FROM part_numbers
WHERE item_name = NEW.item_name
AND short_desc = NEW.short_desc
AND po_text = NEW.po_text
LIMIT 1);
ELSE
SET NEW.item_code =
(SELECT IFNULL(MAX(item_code),0)+1
FROM part_numbers
WHERE DATE_FORMAT(created_at,"%Y") = DATE_FORMAT(now(),"%Y"));
END IF;
END
');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::unprepared('DROP TRIGGER `formatted_item_code_reset_by_year`');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PartNumber extends Model
{
protected $fillable = [
'item_code',
'inc',
'item_name',
'short_desc',
'man_code',
'man_name',
'part_number',
'po_text',
];
protected $dates = ['created_at', 'updated_at'];
public function partnumbers()
{
return $this->hasMany('App\PartNumber', 'item_code', 'item_code');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\PartNumber;
class PartNumberController extends Controller
{
public function index()
{
if (\Gate::denies('partNumberView', PartNumber::class)) {
abort(404);
}
return view('partnumber');
}
private function clean($string) {
// source http://stackoverflow.com/questions/14114411/remove-all-special-characters-from-a-string
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
$string = preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
$string = str_replace('-', '', $string);
return $string;
}
private function query($request)
{
$searchQueries = preg_split('/\s+/', $request, -1, PREG_SPLIT_NO_EMPTY);
return $results = PartNumber::where(function ($q) use ($searchQueries) {
foreach ($searchQueries as $value) {
$q->orWhere(\DB::raw('REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
REPLACE(REPLACE(REPLACE(part_number, \'"\', \'\'),\' \', \'\'),
\'.\', \'\'),\'?\', \'\'),\'`\', \'\'),\'<\', \'\'),\'=\', \'\'),\'{\',
\'\'),\'}\',\'\'),\'[\', \'\'),\']\', \'\'),\'|\', \'\'),'.\DB::getPdo()->quote('\'').',
\'\'),\':\', \'\'),\';\', \'\'),\'~\', \'\'),\'!\', \'\'),\'@\', \'\'),
\'#\', \'\'),\'$\', \'\'),\'%\', \'\'),\'^\', \'\'),\'&\', \'\'),\'*\',
\'\'),\'_\', \'\'),\'+\', \'\'),\',\', \'\'),\'/\', \'\'),\'(\', \'\'),\')\',
\'\'),\'-\', \'\'),\'>\', \'\')'),
'like', '%'.$this->clean($value).'%');
}
});
}
public function search(Request $request)
{
if (\Gate::denies('partNumberSearch', PartNumber::class)) {
abort(404);
}
if($request->q <> '' OR $request->q <> null){
$results = $this->query($request->q)
->with('partnumbers')
->paginate(10);
}else{
$results = [];
}
$q = $request->q;
return view('results', compact('results','q'));
}
public function excel(Request $request)
{
if (\Gate::denies('partNumberDownload', PartNumber::class)) {
abort(404);
}
$content = $this->query($request->q)
->select(\DB::raw('
CONCAT(RIGHT(DATE_FORMAT(created_at,"%Y"),2),LPAD(item_code,5,0)),
part_number,
man_code,
man_name,
inc,
item_name,
short_desc,
po_text'
)
);
$results = PartNumber::select(\DB::raw('
"CATALOG NO",
"PART NUMBER",
"MAN CODE",
"MANUFACTURER NAME",
"INC",
"ITEM NAME",
"SHORT DESCRIPTION",
"PO TEXT"
')
)
->limit(1)
->union($content)
->get();
\Exporter::make('Excel')
->load($results)
->stream(str_replace(' ', '_', strtolower($request->q)).'.xlsx');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;
use App\PartNumber;
class ImportController extends Controller
{
public function index()
{
if (\Gate::denies('importView', PartNumber::class)) {
abort(404);
}
return view('import');
}
private function cekSize(){
$file_max = ini_get('upload_max_filesize');
$file_max_str_leng = strlen($file_max);
$file_max_meassure_unit = substr($file_max,$file_max_str_leng - 1,1);
$file_max_meassure_unit = $file_max_meassure_unit == 'K' ? 'kb' : ($file_max_meassure_unit == 'M' ? 'mb' : ($file_max_meassure_unit == 'G' ? 'gb' : 'unidades'));
$file_max = substr($file_max,0,$file_max_str_leng - 1);
$file_max = intval($file_max);
//handle second case
if((empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'))
{
return false;
}
return true;
}
public function upload(Request $request) {
if (\Gate::denies('importImport', PartNumber::class)) {
abort(404);
}
$this->validate($request, [
'document' => 'required|mimes:xlsx,ods',
]);
$fileName = time().'.'.$request->document->getClientOriginalExtension();
if($request->document->move(storage_path('app/uploads'), $fileName)){
return array('file' => $fileName);
}
}
private function readSpreadSheet($filename){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(strtolower($ext == 'ods')){
$reader = ReaderFactory::create(Type::ODS);
}else{
$reader = ReaderFactory::create(Type::XLSX);
}
$reader->open(storage_path('app/uploads/' . $filename));
return $reader;
}
public function read($filename){
if (\Gate::denies('importImport', PartNumber::class)) {
abort(404);
}
$reader = $this->readSpreadSheet($filename);
foreach ($reader->getSheetIterator() as $sheet) {
$i = 1;
$table_name ='';
foreach ($sheet->getRowIterator() as $rows) {
if($i++ == 1){
$table_name = strtoupper(trim($rows[0]));
}
}
}
if($table_name == 'PART NUMBER'){
$status = array();
foreach ($reader->getSheetIterator() as $sheet) {
$i = 1;
foreach ($sheet->getRowIterator() as $rows) {
if($i++ == 2){
if(strtoupper(trim($rows[0])) == 'INC'){
$status[] = 1;
}else{
$status[] = 0;
}
if(strtoupper(trim($rows[1])) == 'ITEM NAME'){
$status[] = 1;
}else{
$status[] = 0;
}
if(strtoupper(trim($rows[2])) == 'SHORT DESCRIPTION'){
$status[] = 1;
}else{
$status[] = 0;
}
if(strtoupper(trim($rows[3])) == 'MAN CODE'){
$status[] = 1;
}else{
$status[] = 0;
}
if(strtoupper(trim($rows[4])) == 'MANUFACTURER NAME'){
$status[] = 1;
}else{
$status[] = 0;
}
if(strtoupper(trim($rows[5])) == 'PART NUMBER'){
$status[] = 1;
}else{
$status[] = 0;
}
if(strtoupper(trim($rows[6])) == 'PO TEXT'){
$status[] = 1;
}else{
$status[] = 0;
}
}
}
}
if (in_array(0, $status)) {
echo "<span class='text-danger'>TABLE COLUMN DIDN'T MATCH</span>";
}else{
echo "<div id='uploaded_area'>";
echo "<hr/>";
$table = "<div id='message' style='margin-top:10px;'>READY TO IMPORT YOUR <strong><span id='counter'></span> OF PART NUMBER</strong> DATA</div>";
$table .= "<table id='datatables' class='table table-striped table-bordered table-condensed' width='100%'>";
foreach ($reader->getSheetIterator() as $sheet) {
$i = 1;
$first = true;
$urut = 3;
$cek_already_in_db = [];
$warn_already_in_db = [];
$check_duplicate_row = [];
$max_str = [];
$warn_max_str = [];
$check_empty_item_name = [];
$check_empty_short_desc = [];
$check_empty_man_code = [];
$check_empty_part_number = [];
$check_empty_po_text = [];
$data_counter = [];
foreach ($sheet->getRowIterator() as $rows) {
if($i++ > 1){
if($first){
$table .= "<thead><tr>";
$table .= "<th width='3%'>#</th>";
$table .= "<th width='10%'>".strtoupper(trim($rows[0]))."</th>";
$table .= "<th width='14%'>".strtoupper(trim($rows[1]))."</th>";
$table .= "<th width='16%'>".strtoupper(trim($rows[2]))."</th>";
$table .= "<th width='10%'>".strtoupper(trim($rows[3]))."</th>";
$table .= "<th width='14%'>".strtoupper(trim($rows[4]))."</th>";
$table .= "<th width='19%'>".strtoupper(trim($rows[5]))."</th>";
$table .= "<th width='14%'>".strtoupper(trim($rows[6]))."</th>";
$table .= "</tr></thead>";
$table .= "<tbody>";
$first = false;
}else{
// VALIDATION
// ===============================================
$adakah_di_db = PartNumber::select('id')
->where('item_name', trim($rows[1]))
->where('short_desc', trim($rows[2]))
->where('man_code', trim($rows[3]))
->where('part_number', trim($rows[5]))
->where('po_text', trim($rows[6]))
->first();
if(count($adakah_di_db)>0){
$cek_already_in_db[] = 0;
$warn_already_in_db[] = '<b>ITEM NAME:</b> '.strtoupper(trim($rows[1])).' WITH <b>SHORT DESCRIPTION:</b> '.strtoupper(trim($rows[2])).' WITH <b>MAN CODE:</b> '.strtoupper(trim($rows[3])).' WITH <b>PART NUMBER: </b> '.strtoupper(trim($rows[5])).' WITH <b>PO TEXT: </b> '.strtoupper(trim($rows[6]));
}else{
$cek_already_in_db[] = 1;
}
$check_duplicate_row[] .= '<b>ITEM NAME:</b> '.strtoupper(trim($rows[1])).' WITH <b>SHORT DESCRIPTION:</b> '.strtoupper(trim($rows[2])).' WITH <b>MAN CODE:</b> '.strtoupper(trim($rows[3])).' WITH <b>PART NUMBER: </b> '.strtoupper(trim($rows[5])).' WITH <b>PO TEXT: </b> '.strtoupper(trim($rows[6]));
if(strlen(trim($rows[0])) > 5){
$max_str[] = 0;
$warn_max_str[] = '<b>INC</b> "'.strtoupper(trim($rows[0])).'" LENGTH MAY NOT BE GREATER THAN 5';
}else{
$max_str[] = 1;
}
if(strlen(trim($rows[1])) > 255){
$max_str[] = 0;
$warn_max_str[] = '<b>ITEM NAME</b> "'.strtoupper(trim($rows[1])).'" LENGTH MAY NOT BE GREATHER THAN 255';
}else{
$max_str[] = 1;
}
if(strlen(trim($rows[2])) > 255){
$max_str[] = 0;
$warn_max_str[] = '<b>SHORT DESCRIPTION</b> "'.strtoupper(trim($rows[2])).'" LENGTH MAY NOT BE GREATHER THAN 255';
}else{
$max_str[] = 1;
}
if(strlen(trim($rows[3])) > 10){
$max_str[] = 0;
$warn_max_str[] = '<b>MAN CODE</b> "'.strtoupper(trim($rows[3])).'" LENGTH MAY NOT BE GREATHER THAN 10';
}else{
$max_str[] = 1;
}
if(strlen(trim($rows[4])) > 255){
$max_str[] = 0;
$warn_max_str[] = '<b>MANUFACTURER NAME</b> "'.strtoupper(trim($rows[4])).'" LENGTH MAY NOT BE GREATHER THAN 255';
}else{
$max_str[] = 1;
}
if(strlen(trim($rows[5])) > 255){
$max_str[] = 0;
$warn_max_str[] = '<b>PART NUMBER</b> "'.strtoupper(trim($rows[5])).'" LENGTH MAY NOT BE GREATHER THAN 255';
}else{
$max_str[] = 1;
}
$check_empty_item_name[] .= $rows[1];
$check_empty_short_desc[] .= $rows[2];
$check_empty_man_code[] .= $rows[3];
$check_empty_part_number[] .= $rows[5];
$check_empty_po_text[] .= $rows[6];
// TABLE
// ====================================================
$table .= "<tr><td>".$urut++."</td>";
$table .= "<td>".strtoupper(trim($rows[0]))."</td>";
$table .= "<td>".strtoupper(trim($rows[1]))."</td>";
$table .= "<td>".strtoupper(trim($rows[2]))."</td>";
$table .= "<td>".strtoupper(trim($rows[3]))."</td>";
$table .= "<td>".strtoupper(trim($rows[4]))."</td>";
$table .= "<td>".strtoupper(trim($rows[5]))."</td>";
$table .= "<td>".strtoupper(trim($rows[6]))."</td></tr>";
$data_counter[] = 1;
}
}
}
}
$table .= "</tbody></table>";
$row_check_duplicate = array_count_values($check_duplicate_row);
$chek_dupl_row = array();
foreach ($row_check_duplicate as $key => $value) {
if($value > 1) {
$chek_dupl_row[] = 0;
}else{
$chek_dupl_row[] = 1;
}
}
$empty_item_name = array();
foreach ($check_empty_item_name as $value) {
if(is_null($value) || $value == ''){
$empty_item_name[] = 0;
}else{
$empty_item_name[] = 1;
}
}
$empty_short_desc = array();
foreach ($check_empty_short_desc as $value) {
if(is_null($value) || $value == ''){
$empty_short_desc[] = 0;
}else{
$empty_short_desc[] = 1;
}
}
$empty_man_code = array();
foreach ($check_empty_man_code as $value) {
if(is_null($value) || $value == ''){
$empty_man_code[] = 0;
}else{
$empty_man_code[] = 1;
}
}
$empty_part_number = array();
foreach ($check_empty_part_number as $value) {
if(is_null($value) || $value == ''){
$empty_part_number[] = 0;
}else{
$empty_part_number[] = 1;
}
}
$empty_po_text = array();
foreach ($check_empty_po_text as $value) {
if(is_null($value) || $value == ''){
$empty_po_text[] = 0;
}else{
$empty_po_text[] = 1;
}
}
if(count($data_counter) < 1){
echo '<span class="text-danger">YOU TRY TO UPLOAD SPREADSHEET WITH EMPTY INC DATA</span>';
}elseif(
in_array(0, $cek_already_in_db) ||
in_array(0, $chek_dupl_row) ||
in_array(0, $max_str) ||
in_array(0, $empty_item_name) ||
in_array(0, $empty_short_desc) ||
in_array(0, $empty_man_code) ||
in_array(0, $empty_part_number) ||
in_array(0, $empty_po_text)
){
echo "<span><strong>PLEASE CHECK YOUR PART NUMBER SPREADSHEET</strong></span>";
$already = '';
if(in_array(0, $cek_already_in_db)){
$validasi = "<br><br><strong class='text-danger'><u>ALREADY IN DATABASE:</u> </strong>";
foreach ($warn_already_in_db as $value) {
$validasi .= '<br/>'.$value;
}
$already = $validasi;
}
$max_length = '';
if(in_array(0, $max_str)){
$validasi = "<br><br><strong class='text-danger'><u>CHARACTER LENGTH MORE THAN ALLOWED:</u> </strong>";
foreach ($warn_max_str as $value) {
$validasi .= '<br/>'.$value;
}
$max_length = $validasi;
}
$dupl_row_ = '';
$dupl_row = '';
if(in_array(0, $chek_dupl_row)){
$validasi = '';
$check_duplicate_row_again = array_count_values($check_duplicate_row);
foreach($check_duplicate_row_again as $key=>$value){
if(is_null($key) || $key == '')
unset($check_duplicate_row_again[$key]);
}
$ada = array();
foreach ($check_duplicate_row_again as $key => $value) {
if($value > 1) {
$validasi .= '<br/>'.$key;
$ada[] = 1;
}else{
$ada[] = 0;
}
}
$dupl_row_ = $validasi;
if(in_array(1, $ada)){
$dupl_row = "<br><br><strong class='text-danger'><u>DUPLICATE :</u></strong> ";
$dupl_row .= $dupl_row_;
}else{
$dupl_row = '';
}
}
$item_name_empty = '';
if(in_array(0, $empty_item_name)){
$validasi = "<br><br><strong class='text-danger'><u>EMPTY ITEM NAME:</u> </strong> ";
$i = 3;
foreach ($check_empty_item_name as $value) {
if(is_null($value) || $value == ''){
$validasi .= '<br/>ON LINE <b>#'.$i++.'</b> IN YOUR SPREADSHEET.';
}else{
$i++;
}
}
$item_name_empty = $validasi;
}
$short_desc_empty = '';
if(in_array(0, $empty_short_desc)){
$validasi = "<br><br><strong class='text-danger'><u>EMPTY SHORT DESCRIPTION:</u> </strong> ";
$i = 3;
foreach ($check_empty_short_desc as $value) {
if(is_null($value) || $value == ''){
$validasi .= '<br/>ON LINE <b>#'.$i++.'</b> IN YOUR SPREADSHEET.';
}else{
$i++;
}
}
$short_desc_empty = $validasi;
}
$man_code_empty = '';
if(in_array(0, $empty_man_code)){
$validasi = "<br><br><strong class='text-danger'><u>EMPTY MAN CODE:</u> </strong> ";
$i = 3;
foreach ($check_empty_man_code as $value) {
if(is_null($value) || $value == ''){
$validasi .= '<br/>ON LINE <b>#'.$i++.'</b> IN YOUR SPREADSHEET.';
}else{
$i++;
}
}
$man_code_empty = $validasi;
}
$part_number_empty = '';
if(in_array(0, $empty_part_number)){
$validasi = "<br><br><strong class='text-danger'><u>EMPTY PART NUMBER:</u> </strong> ";
$i = 3;
foreach ($check_empty_part_number as $value) {
if(is_null($value) || $value == ''){
$validasi .= '<br/>ON LINE <b>#'.$i++.'</b> IN YOUR SPREADSHEET.';
}else{
$i++;
}
}
$part_number_empty = $validasi;
}
$po_text_empty = '';
if(in_array(0, $empty_po_text)){
$validasi = "<br><br><strong class='text-danger'><u>EMPTY PO TEXT:</u> </strong> ";
$i = 3;
foreach ($check_empty_po_text as $value) {
if(is_null($value) || $value == ''){
$validasi .= '<br/>ON LINE <b>#'.$i++.'</b> IN YOUR SPREADSHEET.';
}else{
$i++;
}
}
$po_text_empty = $validasi;
}
echo $already;
echo $max_length;
echo $dupl_row;
echo $item_name_empty;
echo $short_desc_empty;
echo $man_code_empty;
echo $part_number_empty;
echo $po_text_empty;
}else{
echo "<span id='data_counter'>".number_format(count($data_counter))."</span>";
echo "<input type='button' class='import_to_db import_part_number btn btn-sm btn-primary' value='IMPORT PART NUMBER DATA'>";
echo $table;
}
echo "</div>";
}
}else{
echo 'Wrong Spreadsheet.';
}
}
public function importPartNumber($file){
if (\Gate::denies('importImport', PartNumber::class)) {
abort(404);
}
$reader = $this->readSpreadSheet($file);
foreach ($reader->getSheetIterator() as $sheet) {
$rows = $sheet->getRowIterator();
\DB::transaction(function () use($rows){
$i = 1;
foreach ($rows as $cel) {
$key = $i++;
if($key > 2){
$item_code = 1;
$inc = strtoupper(trim($cel[0]));
$item_name = strtoupper(trim($cel[1]));
$short_desc = strtoupper(trim($cel[2]));
$man_code = strtoupper(trim($cel[3]));
$man_name = strtoupper(trim($cel[4]));
$part_number = strtoupper(trim($cel[5]));
$po_text = strtoupper(trim($cel[6]));
$date = \Carbon\Carbon::now();
$data = [
'item_code' => $item_code,
'inc' => $inc,
'item_name' => $item_name,
'short_desc' => $short_desc,
'man_code' => $man_code,
'man_name' => $man_name,
'part_number' => $part_number,
'po_text' => $po_text,
'created_at' => $date,
'updated_at' => $date
];
PartNumber::create($data);
}
}
});
};
}
}
<file_sep><?php
namespace App\Policies;
use App\User;
use App\PartNumber;
use Illuminate\Auth\Access\HandlesAuthorization;
class PartNumberPolicy
{
use HandlesAuthorization;
public function before($user, $ability)
{
if ($user->isSuper()) return true;
}
public function partNumberView(User $user)
{
return $user->hasPermission('partnumber.view');
}
public function partNumberSearch(User $user)
{
return $user->hasPermission('partnumber.search');
}
public function partNumberDownload(User $user)
{
return $user->hasPermission('partnumber.download');
}
public function importView(User $user)
{
return $user->hasPermission('import.view');
}
public function importImport(User $user)
{
return $user->hasPermission('import.import');
}
public function userView(User $user)
{
return $user->hasPermission('user.view');
}
public function roleView(User $user)
{
return $user->hasPermission('role.view');
}
}
|
9aaf18fd8d192b46de75b6a3638101b7d0ffe84b
|
[
"Markdown",
"SQL",
"PHP"
] | 11
|
Markdown
|
khoerodin/partfinder
|
21e2980eaa14b02e128a467bbe2af3aa702ac96f
|
7e21e84be5c90fde0941513c74a03028d331ebb2
|
refs/heads/main
|
<file_sep>package com.bw.webservice.repository;
import com.bw.webservice.domain.Posts;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.LocalDateTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
public class PostsRepositroyTest {
@Autowired
private PostsRepositroy postsRepositroy;
@Test
public void 게시글저장_불러오기() {
//given
postsRepositroy.save(Posts.builder()
.title("테스트 게시글")
.content("테스트 본문")
.author("작성자")
.build());
//when
List<Posts> postsList = postsRepositroy.findAll();
//then
Posts posts =postsList.get(0);
assertThat(posts.getTitle()).isEqualTo("테스트 게시글");
assertThat(posts.getContent()).isEqualTo("테스트 본문");
assertThat(posts.getAuthor()).isEqualTo("작성자");
}
@Test
public void BaseTimeEntity_등록 () {
//given
LocalDateTime now = LocalDateTime.now();
postsRepositroy.save(Posts.builder()
.title("테스트 게시글")
.content("테스트 본문")
.author("작성자")
.build());
//when
List<Posts> postsList = postsRepositroy.findAll();
//then
Posts posts = postsList.get(0);
assertThat(posts.getCreatedDate().isAfter(now));
assertThat(posts.getModifiedDate().isAfter(now));
}
}<file_sep>## SpringBoot 학습 Repository입니다. [](https://travis-ci.org/ybw903/springboot-webservice)
개발환경
- IDE : IntelliJ IDEA
- OS : Windows 10
- SpringBoot 2.4.2
- JAVA11
- Gradle
|
dc6f60bf5c0bb75e82668c0683b90b420a65290e
|
[
"Markdown",
"Java"
] | 2
|
Java
|
ybw903/springboot-webservice
|
49dea1ecfc99dfcc98c186fd8256259f7e6b8207
|
f34587a93f326b8237ecd4cd98e25bcc13014fed
|
refs/heads/master
|
<file_sep><?php
if(defined("IS_INDEX") == false)
{
die("Please stop here!");
}
$nim = $_GET['nim'];
hapus_mahasiswa($nim);
redirect_to("mahasiswa");
?>
<file_sep><?php
if(defined("IS_INDEX") == false)
{
die("Please stop here!");
}
?>
<h4>
Data Mahasiswa
<span class="float-right">
<a href="index.php?page=from_add_mahasiswa" class="btn btn-primary">
Tambah Data Mahasiswa
</a>
</span>
</h4>
<?php
$mahasiswa = get_mahasiswa();
?>
<table class="table table-bordered">
<tr>
<th>nim</th>
<th>nama</th>
<th>alamat</th>
<th>aksi</th>
</tr>
<?php
while($row = mysqli_fetch_assoc($mahasiswa))
{
echo "<tr>
<td>".$row['nim']."</td>
<td>".$row['nama']."</td>
<td>".$row['alamat']."</td>
<td>
<a href='index.php?page=edit_mahasiswa&nim=".$row['nim']."'>Edit</a> |
<a href='index.php?page=hapus_mahasiswa&nim=".$row['nim']."'>Hapus</a>
</td>
</tr>";
}
?>
</table>
<file_sep><?php
if(defined("IS_INDEX") == false)
{
die("Please stop here!");
}
?>
<h1>Beranda</h1>
<a class="nav-link" href="profil.php">profil</a><file_sep><?php
if(defined("IS_INDEX") == false)
{
die("Please stop here!");
}
?>
<h4>
From Edit Data Mahasiswa
<span class="float-right">
<a href="index.php?page=mahasiswa" class="btn btn-light">
Kembali
</a>
</span>
</h4>
<br/>
<?php
$nim = $_GET['nim'];
$data = get_mahasiswa_by_nim($nim);
?>
<form action="index.php?page=update_mahasiswa" method="post">
<input type="hidden" name="nim" value="<?php echo $nim;?>"/>
<table>
<tr>
<td>Nama</td>
<td>:</td>
<td><input type="text" name="nama" value="<?php echo $data['nama']?>"/></td>
</tr>
<tr>
<td>Alamat</td>
<td>:</td>
<td><input type="text" name="alamat" value="<?php echo $data['alamat']?>"/></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit"/></td>
</tr>
</table>
</form><file_sep><?php
if(defined("IS_INDEX") == false)
{
die("Please stop here!");
}
?>
<h1>Dashboard</h1>
<p>Welcome, <?php echo $_SESSION['username'];?>!</p><file_sep><?php
if(defined("IS_INDEX") == false)
{
die("Please stop here!");
}
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$cek_login = proses_login($username,$password);
if($cek_login == true)
{
//tandai di session
$_SESSION['username'] = $username;
//redirect kedasboard
redirect_to("dashboard");
}
else
{
//redirect ke halaman login
redirect_to("login_form&error=1");
}
?><file_sep><?php
if(defined("IS_INDEX") == false)
{
die("Please stop here!");
}
?>
<h4>
Data Mahasiswa
<span class="float-right">
<a href="index.php?page=mahasiswa" class="btn btn-default">
Kembali
</a>
</span>
</h4>
<br/>
<form action="index.php?page=simpan_mahasiswa" method="post">
<table>
<tr>
<td>NIM</td>
<td>:</td>
<td><input type="text" name="nim" /></td>
</tr>
<tr>
<td>Nama</td>
<td>:</td>
<td><input type="text" name="nama" /></td>
</tr>
<tr>
<td>Alamat</td>
<td>:</td>
<td><input type="text" name="alamat" /></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" /></td>
</tr>
</table>
</form><file_sep><?php
if(defined("IS_INDEX") == false)
{
die("Please stop here!");
}
?>
<h1>Profil</h1><file_sep><?php
if(defined("IS_INDEX") == false)
{
die("Please stop here!");
}
// mengubah di database
$data = array(
'nim' => $_POST['nim'],
'nama' => $_POST['nama'],
'alamat' => $_POST['alamat'],
);
update_data_mahasiswa($data);
redirect_to("mahasiswa");
?><file_sep><?php
session_start();
?>
<!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">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<title>Hello, Sanah!</title>
</head>
<body>
<div class="container">
<div class="row header">
<h1>APLIKASI-QUH</h1>
</div>
<div class="row main">
<div class="col-4 sidebar" style="background-color:pink;">
SIDEBAR
</div>
<div class="col-8 content" style="background-color:white;">
<?php
define("IS_INDEX", true); //variabel konstan hanya sekali
//regustnya apa dulu, disini pake get dan variabel nya variabel page
if(isset($_GET['page']))
{
$page = $_GET['page'];
}
else
{
$page = "beranda";
}
require_once("aplikasi.php"); //harus diatas page supaya tidak error
require_once($page.".php"); //guna untuk menuju ke file php yang ada
?>
</div>
</div>
</div clas="row">
<div class="col">Copyright @2019</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep><?php if (defined("IS_INDEX")==false)
{
die("Please stop here!");
}
?>
<?php
function connect_to_db()
{
$conn = mysqli_connect("127.0.0.1","root","","webprogramming");
if($conn == false)
{
echo mysqli_connect_error();
die();
}
else
{
return $conn;
}
}
function select_db($sql)
{
$conn = connect_to_db();
return mysqli_query($conn, $sql);
}
function get_mahasiswa()
{
$sql = "select * from mahasiswa";
return select_db($sql);
}
function get_mahasiswa_by_nim($nim)
{
$conn = connect_to_db();
$sql = "select * from mahasiswa where nim=".$nim;
$query = mysqli_query($conn,$sql);
return mysqli_fetch_array($query);
}
function hapus_mahasiswa($nim)
{
$conn = connect_to_db();
$sql = "delete from mahasiswa where nim=".$nim;
mysqli_query($conn,$sql);
}
function simpan_data_mahasiswa($data)
{
$conn = connect_to_db();
$nim = $data['nim'];
$nama = $data['nama'];
$alamat = $data['alamat'];
$sql = "insert into mahasiswa
values ('$nim', '$nama', '$alamat')";
mysqli_query($conn, $sql);
}
function update_data_mahasiswa($data)
{
$conn = connect_to_db();
$nim = $data['nim'];
$nama = $data['nama'];
$alamat = $data['alamat'];
$sql = "update mahasiswa
set nama='$nama', alamat='$alamat'
where nim='$nim'";
mysqli_query($conn, $sql);
}
function proses_login($username,$password)
{
$conn = connect_to_db();
$sql = "SELECT * FROM pengguna WHERE username='$username'
AND password='".md5($password)."'";
$query = mysqli_query($conn,$sql);
$num = mysqli_num_rows($query);
return ($num > 0);
}
function redirect_to($page)
{
echo"<script>
window.location = 'index.php?page=$page'
</script>";
}
function tambah_mahasiswa($nim)
{
$conn = connect_to_db();
$sql = "INSERT INTO mahasiswa VALUES ('$nim', '$nama', '$alamat')";
mysqli_query($conn,$sql);
}
?>
<file_sep><?php
if(defined("IS_INDEX") == false)
{
die("Please stop here!");
}
?>
<h4>
Form Login
</h4>
<br/>
<?php
if(isset($GET['error']) && $_GET['error'] ==1)
{
echo "Login gagal.";
}
?>
<form action="index.php?page=proses_login" method="post">
<table>
<tr>
<td>Username</td>
<td>:</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input type="<PASSWORD>" name="password" /></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" /></td>
</tr>
</table>
</form>
|
ddc3d612b7a5c1b63f3e846d94142bee38e4faae
|
[
"PHP"
] | 12
|
PHP
|
arifatulkhasanah/webprogramming
|
fee2d57f8c7b9d77a8691229cd06c45777fe1004
|
fe8bf4d4e9b648372e13b20cdc2ca692522ab677
|
refs/heads/master
|
<file_sep>
# file names
main = './data/ninth_Main.txt'
spot_telo = './data/ninth_telo550_spots.txt'
spot_bp1 = './data/ninth_53bp1_spots.txt'
# import the datatabels
df_main = read.table(main, header = TRUE, sep = "\t")
df_telo = read.table(spot_telo, header = TRUE, sep = "\t")
df_bp1 = read.table(spot_bp1, header = TRUE, sep = "\t")
# calculate the distances
df_main_with_distance = calculate_distance(df_main,'telo550_spots..Counts', 'X53bp1_spots..Counts', df_telo, df_bp1, decfriend = T)
<file_sep># Spot_Distance
Calculate distance for two sub_objection unites in a ScanR analysis result file
<file_sep># packages to import:
library(Rfast)
## below is a set of function for adding a column to you data that include the average distance between spots
## inside a nuclues, the idx-spots1-2 is the string name for the spots in the dataframe for the spots, and '
## depends on what you called it in the scanR analysis software.
## The decfriend if set to true will calculate whether the spot1 and spot2 is matched pairwise or not
## it can take 3 values: BFF - paired, drama - not paired, unsymetrical - not the same amount of spot1 as spot2
## it depends on the two function below: distance_matrix and point_distance
calculate_distance = function(main_df, idx_spots1, idx_spots2,
df_spot1, df_spot2, decfriend = FALSE){
for (idx in c(1:nrow(main_df))){
# check whether both spots are present for the nucleus and draw the data from the two spots_df
if (main_df[idx, idx_spots1] > 0 & main_df[idx, idx_spots2] > 0){
sub_spot1 = df_spot1[df_spot1$Parent.Object.ID..MO. == main_df[idx, 'Object.ID'],]
sub_spot2 = df_spot2[df_spot2$Parent.Object.ID..MO. == main_df[idx, 'Object.ID'],]
# calculate the distance between all spots
dist_matrix = distance_matrix(sub_spot1,sub_spot2)
#locate nearest spots for sport 1 and spot 2 respectivly, from the distance matrix
spots1_dist = rowMins(dist_matrix, value = TRUE)
spots2_dist = colMins(dist_matrix, value = TRUE)
# add the value to the dataframe
main_df[idx,'SpotDistance'] = mean(c(spots1_dist, spots2_dist))
# calculte the whether they are paired or not, if instructed in the begining
if (decfriend == TRUE){
# 3 cases BFF means spots are paired, unsymetrical means not equaly amount of two spots
# drama means spots are not paired
if (sum(spots1_dist) == sum(spots2_dist)){
# if the distanse is identical they are all paired
main_df[idx,'SpotsFriend'] = 'BFF'
}
else if (nrow(sub_spot1) == nrow(sub_spot2)){
# if there is the same number but the distance is different they are not paired
main_df[idx,'SpotsFriend'] = 'Drama'
}
else {
#the last case is for different numbers of spot1 and spot2
main_df[idx,'SpotsFriend'] = 'Unsymetrical'
}
}
}
else {
# add standard values if there is not spot in either spot1 or spot2
# I have used NA to make it easier to do further calculation.
main_df[idx,'SpotDistance'] = NA
if (decfriend == TRUE){
main_df[idx,'SpotsFriend'] = NA
}
}
}
return(main_df)
}
# calculate all the distance between two sets of point - depends on the point_distance function below
distance_matrix = function(pointset1, pointset2){
result_matrix = matrix(0,nrow(pointset1),nrow(pointset2))
for (rowidx in c(1:nrow(pointset2))){
dist_vector = apply(pointset1, 1, point_distance, point2 = pointset2[rowidx,])
result_matrix[,rowidx] = unlist(dist_vector)
}
return(result_matrix)
}
# calculate the distance between two points
point_distance = function(point1, point2){
distance = ((point1['Center.X']-point2['Center.X'])^2+(point1['Center.Y']-point2['Center.Y'])^2)^0.5
return(distance)
}
# for testing create a limited df with shorter name
# df_main_filtered = data.frame(
# 'Object.ID' = df_main$Object.ID,
# 'Spots_bp1' = df_main$X53bp1_spots..Counts,
# 'Spots_telo' = df_main$telo550_spots..Counts
# )
|
558361f17efb38cda5d5b0756c521ea21d82be42
|
[
"Markdown",
"R"
] | 3
|
R
|
JesD12/Spot_Distance
|
363d58430828d5f0bbad85534b477a8d1e5ece15
|
34bce2f317ea5ac65f587759d8f8fe83632834ba
|
refs/heads/master
|
<repo_name>IMULMUL/Privexec<file_sep>/vendor/bela/include/bela/io.hpp
// Bela IO utils
#ifndef BELA_IO_HPP
#define BELA_IO_HPP
#include "base.hpp"
#include "types.hpp"
#include "buffer.hpp"
#include "os.hpp"
#include "path.hpp"
namespace bela::io {
// Size get file size
inline int64_t Size(HANDLE fd, bela::error_code &ec) {
FILE_STANDARD_INFO si;
if (GetFileInformationByHandleEx(fd, FileStandardInfo, &si, sizeof(si)) != TRUE) {
ec = bela::make_system_error_code(L"GetFileInformationByHandleEx(): ");
return bela::SizeUnInitialized;
}
return si.EndOfFile.QuadPart;
}
// Size get file size
inline int64_t Size(std::wstring_view filename, bela::error_code &ec) {
WIN32_FILE_ATTRIBUTE_DATA wdata;
if (GetFileAttributesExW(filename.data(), GetFileExInfoStandard, &wdata) != TRUE) {
ec = bela::make_system_error_code(L"GetFileAttributesExW(): ");
return bela::SizeUnInitialized;
}
return static_cast<unsigned long long>(wdata.nFileSizeHigh) << 32 | wdata.nFileSizeLow;
}
enum Whence : DWORD {
SeekStart = FILE_BEGIN,
SeekCurrent = FILE_CURRENT,
SeekEnd = FILE_END,
};
// Seek pos
inline bool Seek(HANDLE fd, int64_t pos, bela::error_code &ec, Whence whence = SeekStart) {
LARGE_INTEGER new_pos{.QuadPart = 0};
if (SetFilePointerEx(fd, *reinterpret_cast<LARGE_INTEGER const *>(&pos), &new_pos, whence) != TRUE) {
ec = bela::make_system_error_code(L"SetFilePointerEx(): ");
return false;
}
return true;
}
// Avoid the uint8_t buffer from incorrectly matching the template function
template <class T>
concept vectorizable_derived = std::is_standard_layout_v<T> &&(!std::same_as<T, uint8_t>);
template <class T>
concept exclude_buffer_derived = std::is_standard_layout_v<T> &&(!std::same_as<T, bela::Buffer>);
class FD {
private:
void Free();
void MoveFrom(FD &&o);
public:
FD() = default;
FD(HANDLE fd_, bool needClosed_ = true) : fd(fd_), needClosed(needClosed_) {}
FD(const FD &) = delete;
FD &operator=(const FD &) = delete;
FD(FD &&o) { MoveFrom(std::move(o)); }
FD &operator=(FD &&o) {
MoveFrom(std::move(o));
return *this;
}
~FD() { Free(); }
FD &Assgin(FD &&o) {
MoveFrom(std::move(o));
return *this;
}
FD &Assgin(HANDLE fd_, bool needClosed_ = true) {
Free();
fd = fd_;
needClosed = needClosed_;
return *this;
}
explicit operator bool() const { return fd != INVALID_HANDLE_VALUE; }
const auto NativeFD() const { return fd; }
int64_t Size(bela::error_code &ec) const { return bela::io::Size(fd, ec); }
bool Seek(int64_t pos, bela::error_code &ec, Whence whence = SeekStart) const {
return bela::io::Seek(fd, pos, ec, whence);
}
// ReadAt reads buffer.size() bytes into p starting at offset off in the underlying input source. 0 <= outlen <=
// buffer.size()
// Try to read bytes into the buffer
bool ReadAt(std::span<uint8_t> buffer, int64_t pos, int64_t &outlen, bela::error_code &ec) const;
// ReadAt reads buffer.size() bytes into p starting at offset off in the underlying input source. 0 <= outlen <=
// buffer.size()
// Try to read bytes into the buffer
template <typename T>
requires exclude_buffer_derived<T>
bool ReadAt(T &t, int64_t pos, int64_t &outlen, bela::error_code &ec) const {
return ReadAt({reinterpret_cast<uint8_t *>(&t), sizeof(T)}, pos, outlen, ec);
}
// ReadAt reads buffer.size() bytes into p starting at offset off in the underlying input source. 0 <= outlen <=
// buffer.size()
// Try to read bytes into the buffer
template <typename T>
requires vectorizable_derived<T>
bool ReadAt(std::vector<T> &tv, int64_t pos, int64_t &outlen, bela::error_code &ec) const {
return ReadAt({reinterpret_cast<uint8_t *>(tv.data()), sizeof(T) * tv.size()}, pos, outlen, ec);
}
// ReadAt reads buffer.size() bytes from the File starting at byte offset pos.
bool ReadFull(std::span<uint8_t> buffer, bela::error_code &ec) const;
bool ReadFull(bela::Buffer &buffer, size_t nbytes, bela::error_code &ec) const {
if (auto p = buffer.make_span(nbytes); ReadFull(p, ec)) {
buffer.size() = p.size();
return true;
}
return false;
}
// ReadAt reads buffer.size() bytes into p starting at offset off in the underlying input source
// Force a full buffer
bool ReadAt(std::span<uint8_t> buffer, int64_t pos, bela::error_code &ec) const;
// ReadAt reads nbytes bytes into p starting at offset off in the underlying input source
// Force a full buffer
bool ReadAt(bela::Buffer &buffer, size_t nbytes, int64_t pos, bela::error_code &ec) const {
if (auto p = buffer.make_span(nbytes); ReadAt(p, pos, ec)) {
buffer.size() = p.size();
return true;
}
return false;
}
template <typename T>
requires exclude_buffer_derived<T>
bool ReadFull(T &t, bela::error_code &ec) const { return ReadFull({reinterpret_cast<uint8_t *>(&t), sizeof(T)}, ec); }
template <typename T>
requires vectorizable_derived<T>
bool ReadFull(std::vector<T> &tv, bela::error_code &ec) const {
return ReadFull({reinterpret_cast<uint8_t *>(tv.data()), sizeof(T) * tv.size()}, ec);
}
// ReadAt reads sizeof T bytes into p starting at offset off in the underlying input source
// Force a full buffer
template <typename T>
requires exclude_buffer_derived<T>
bool ReadAt(T &t, int64_t pos, bela::error_code &ec) const {
return ReadAt({reinterpret_cast<uint8_t *>(&t), sizeof(T)}, pos, ec);
}
// ReadAt reads vector bytes into p starting at offset off in the underlying input source
// Force a full buffer
template <typename T>
requires vectorizable_derived<T>
bool ReadAt(std::vector<T> &tv, int64_t pos, bela::error_code &ec) const {
return ReadAt({reinterpret_cast<uint8_t *>(tv.data()), sizeof(T) * tv.size()}, pos, ec);
}
private:
HANDLE fd{INVALID_HANDLE_VALUE};
bool needClosed{true};
};
std::optional<FD> NewFile(std::wstring_view file, bela::error_code &ec);
std::optional<FD> NewFile(std::wstring_view file, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes, HANDLE hTemplateFile, bela::error_code &ec);
inline bool ReadAt(HANDLE fd, void *buffer, size_t len, int64_t pos, size_t &outlen, bela::error_code &ec) {
if (!bela::io::Seek(fd, pos, ec)) {
return false;
}
DWORD dwSize = {0};
if (::ReadFile(fd, buffer, static_cast<DWORD>(len), &dwSize, nullptr) != TRUE) {
ec = bela::make_system_error_code(L"ReadFile: ");
return false;
}
outlen = static_cast<size_t>(len);
return true;
}
[[maybe_unused]] constexpr auto MaximumRead = 1024ull * 1024 * 8; // 8MB
[[maybe_unused]] constexpr auto MaximumLineLength = 1024ull * 64; // 64KB
bool ReadFile(std::wstring_view file, std::wstring &out, bela::error_code &ec, uint64_t maxsize = MaximumRead);
bool ReadFile(std::wstring_view file, std::string &out, bela::error_code &ec, uint64_t maxsize = MaximumRead);
bool ReadLine(std::wstring_view file, std::wstring &out, bela::error_code &ec, uint64_t maxline = MaximumLineLength);
inline std::optional<std::wstring> ReadLine(std::wstring_view file, bela::error_code &ec,
uint64_t maxline = MaximumLineLength) {
std::wstring line;
if (ReadLine(file, line, ec, maxline)) {
return std::make_optional(std::move(line));
}
return std::nullopt;
}
bool WriteTextU16LE(std::wstring_view text, std::wstring_view file, bela::error_code &ec);
bool WriteText(std::string_view text, std::wstring_view file, bela::error_code &ec);
bool WriteTextAtomic(std::string_view text, std::wstring_view file, bela::error_code &ec);
inline bool WriteText(std::wstring_view text, std::wstring_view file, bela::error_code &ec) {
return WriteText(bela::encode_into<wchar_t, char>(text), file, ec);
}
inline bool WriteText(std::u16string_view text, std::wstring_view file, bela::error_code &ec) {
return WriteText(bela::encode_into<char16_t, char>(text), file, ec);
}
} // namespace bela::io
#endif<file_sep>/vendor/bela/src/belawin/pe/symbol.cc
//
#include "internal.hpp"
namespace bela::pe {
std::string symbolFullName(const COFFSymbol &sm, const StringTable &st) {
if (sm.Name[0] == 0 && sm.Name[1] == 0 && sm.Name[2] == 0 && sm.Name[3] == 0) {
auto offset = bela::cast_fromle<uint32_t>(sm.Name + 4);
bela::error_code ec;
return std::string(st.make_cstring_view(offset, ec));
}
return std::string(bela::cstring_view(sm.Name));
}
// Auxiliary Symbol Records
bool removeAuxSymbols(const std::vector<COFFSymbol> &csyms, const StringTable &st, std::vector<Symbol> &syms,
bela::error_code &ec) {
if (csyms.empty()) {
return true;
}
uint8_t aux = 0;
for (const auto &cm : csyms) {
if (aux > 0) {
aux--;
continue;
}
aux = cm.NumberOfAuxSymbols;
Symbol sm;
sm.Name = symbolFullName(cm, st);
sm.Value = cm.Value;
sm.SectionNumber = cm.SectionNumber;
sm.StorageClass = cm.StorageClass;
sm.Type = cm.Type;
syms.emplace_back(std::move(sm));
}
return true;
}
bool File::readCOFFSymbols(std::vector<COFFSymbol> &symbols, bela::error_code &ec) const {
if (fh.PointerToSymbolTable == 0 || fh.NumberOfSymbols <= 0) {
return true;
}
symbols.resize(fh.NumberOfSymbols);
if (!fd.ReadAt(symbols, fh.PointerToSymbolTable, ec)) {
return false;
}
if constexpr (bela::IsBigEndian()) {
for (auto &s : symbols) {
s.SectionNumber = bela::fromle(s.SectionNumber);
s.Type = bela::fromle(s.Type);
s.Value = bela::fromle(s.Value);
}
}
return true;
}
// https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#auxiliary-symbol-records
bool File::LookupSymbols(std::vector<Symbol> &syms, bela::error_code &ec) const {
std::vector<COFFSymbol> csyms;
if (!readCOFFSymbols(csyms, ec)) {
return false;
}
return removeAuxSymbols(csyms, stringTable, syms, ec);
}
} // namespace bela::pe<file_sep>/vendor/bela/test/base/base.cc
#include <bela/base.hpp>
#include <bela/terminal.hpp>
#include <bela/str_cat_narrow.hpp>
#include <bela/win32.hpp>
int wmain(int argc, wchar_t **argv) {
if (argc >= 2) {
FILE *fd = nullptr;
if (auto e = _wfopen_s(&fd, argv[1], L"rb"); e != 0) {
auto ec = bela::make_stdc_error_code(e);
bela::FPrintF(stderr, L"unable open: %s\n", ec);
return 1;
}
fclose(fd);
}
bela::FPrintF(stderr, L"%s\n", bela::narrow::StringCat("H: ", bela::narrow::AlphaNum(bela::narrow::Hex(123456))));
bela::FPrintF(stderr, L"EADDRINUSE: %s\nEWOULDBLOCK: %s\n", bela::make_stdc_error_code(EADDRINUSE).message,
bela::make_stdc_error_code(EWOULDBLOCK).message);
auto version = bela::windows::version();
bela::FPrintF(stderr, L"%d.%d.%d %d.%d\n", version.major, version.minor, version.build, version.service_pack_major,
version.service_pack_minor);
return 0;
}<file_sep>/vendor/bela/include/bela/charconv/xcharconv.hpp
// Porting from MSVC STL
// xcharconv.h internal header
// Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef BELA_CHARCONV_FWD_HPP
#define BELA_CHARCONV_FWD_HPP
#include <type_traits>
#include <system_error>
#include <cstring>
#include <cstdint>
#include <bela/macros.hpp>
namespace bela {
enum class chars_format {
scientific = 0b001,
fixed = 0b010,
hex = 0b100,
general = fixed | scientific,
};
[[nodiscard]] constexpr chars_format operator&(chars_format L, chars_format R) noexcept {
using I = std::underlying_type_t<chars_format>;
return static_cast<chars_format>(static_cast<I>(L) & static_cast<I>(R));
}
[[nodiscard]] constexpr chars_format operator|(chars_format L, chars_format R) noexcept {
using I = std::underlying_type_t<chars_format>;
return static_cast<chars_format>(static_cast<I>(L) | static_cast<I>(R));
}
struct to_chars_result {
wchar_t *ptr;
std::errc ec;
[[nodiscard]] friend bool operator==(const to_chars_result &, const to_chars_result &) = default;
};
template <typename T> T _Min_value(T a, T b) { return a < b ? a : b; }
template <typename T> T _Max_value(T a, T b) { return a > b ? a : b; }
template <typename T> void ArrayCopy(void *dst, const T *src, size_t n) { memcpy(dst, src, n * sizeof(T)); }
} // namespace bela
#endif
<file_sep>/vendor/bela/src/bela/CMakeLists.txt
# bela base libaray
add_library(
bela STATIC
errno.cc
ascii.cc
city.cc
codecvt.cc
escaping.cc
fmt.cc
fnmatch.cc
int128.cc
match.cc
memutil.cc
numbers.cc
str_split.cc
str_split_narrow.cc
str_replace.cc
str_replace_narrow.cc
str_cat.cc
str_cat_narrow.cc
subsitute.cc
subsitute_narrow.cc
terminal.cc)
if(BELA_ENABLE_LTO)
set_property(TARGET bela PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
endif()
<file_sep>/vendor/bela/src/belahash/CMakeLists.txt
# bela::hash https://docs.microsoft.com/en-us/cpp/intrinsics/arm64-intrinsics
# https://static.docs.arm.com/ihi0073/c/IHI0073C_arm_neon_intrinsics_ref.pdf
string(TOLOWER "${CMAKE_C_COMPILER_ARCHITECTURE_ID}" BELA_COMPILER_ARCH_ID)
message(STATUS "CMAKE_CXX_COMPILER_ID ${CMAKE_CXX_COMPILER_ID}")
# blake3
if("${BELA_COMPILER_ARCH_ID}" STREQUAL "x86_64"
OR "${BELA_COMPILER_ARCH_ID}" STREQUAL "amd64"
OR "${BELA_COMPILER_ARCH_ID}" STREQUAL "x64"
OR "${BELA_COMPILER_ARCH_ID}" STREQUAL "x86")
# support clang-cl
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
set(BLAKE3_SIMDSRC blake3/blake3_sse2_x86-64_windows_gnu.S blake3/blake3_sse41_x86-64_windows_gnu.S
blake3/blake3_avx2_x86-64_windows_gnu.S blake3/blake3_avx512_x86-64_windows_gnu.S)
else()
# msvc
set(BLAKE3_SIMDSRC blake3/blake3_sse2.c blake3/blake3_sse41.c blake3/blake3_avx2.c blake3/blake3_avx512.c)
set_source_files_properties(blake3_avx512.c PROPERTIES COMPILE_FLAGS "-arch:AVX512")
endif()
elseif("${BELA_COMPILER_ARCH_ID}" STREQUAL "arm64")
set(BLAKE3_SIMDSRC blake3/blake3_neon.c)
else()
message(FATAL "unsupport target")
endif()
add_library(
belahash STATIC
sha256.cc
sha512.cc
sha3.cc
sm3.cc
blake3/blake3.c
blake3/blake3_dispatch.c
blake3/blake3_portable.c
${BLAKE3_SIMDSRC})
target_link_libraries(belahash bela)
if(BELA_ENABLE_LTO)
set_property(TARGET belahash PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
endif()
<file_sep>/vendor/bela/include/bela/strings.hpp
// ---------------------------------------------------------------------------
// Copyright (C) 2022, Bela contributors
//
// 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
//
// https://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.
//
// Includes work from abseil-cpp (https://github.com/abseil/abseil-cpp)
// with modifications.
//
// Copyright 2019 The Abseil Authors.
//
// 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
//
// https://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.
// ---------------------------------------------------------------------------
#ifndef BELA_STRINGS_HPP
#define BELA_STRINGS_HPP
#include <string>
#include <string_view>
#include "ascii.hpp"
namespace bela {
inline char16_t ascii_tolower(char16_t c) { return (c > 0xFF ? c : ascii_internal::kToLower[c]); }
inline char16_t ascii_toupper(char16_t c) { return (c > 0xFF ? c : ascii_internal::kToUpper[c]); }
inline char8_t ascii_tolower(char8_t c) { return static_cast<char8_t>(ascii_internal::kToLower[c]); }
inline char8_t ascii_toupper(char8_t c) { return static_cast<char8_t>(ascii_internal::kToUpper[c]); }
// Returns std::u16string_view with whitespace stripped from the beginning of the
// given u16string_view.
inline std::u16string_view StripLeadingAsciiWhitespace(std::u16string_view str) {
// auto it = std::find_if_not(str.begin(), str.end(), ascii_isspace);
for (auto it = str.begin(); it != str.end(); it++) {
if (!ascii_isspace(static_cast<wchar_t>(*it))) {
str.remove_prefix(it - str.begin());
break;
}
}
return str;
}
// Returns std::u8string_view with whitespace stripped from the beginning of the
// given u8string_view.
inline std::u8string_view StripLeadingAsciiWhitespace(std::u8string_view str) {
// auto it = std::find_if_not(str.begin(), str.end(), ascii_isspace);
for (auto it = str.begin(); it != str.end(); it++) {
if (!ascii_isspace(static_cast<char8_t>(*it))) {
str.remove_prefix(it - str.begin());
break;
}
}
return str;
}
// Strips in place whitespace from the beginning of the given u8string.
inline void StripLeadingAsciiWhitespace(std::u8string *str) {
// auto it = std::find_if_not(str->begin(), str->end(), ascii_isspace);
for (auto it = str->begin(); it != str->end(); it++) {
if (!ascii_isspace(*it)) {
str->erase(str->begin(), it);
break;
}
}
}
// Strips in place whitespace from the beginning of the given u16string.
inline void StripLeadingAsciiWhitespace(std::u16string *str) {
// auto it = std::find_if_not(str->begin(), str->end(), ascii_isspace);
for (auto it = str->begin(); it != str->end(); it++) {
if (!ascii_isspace(static_cast<wchar_t>(*it))) {
str->erase(str->begin(), it);
break;
}
}
}
} // namespace bela
#endif<file_sep>/vendor/bela/include/bela/macros.hpp
// ---------------------------------------------------------------------------
// Copyright (C) 2022, Bela contributors
//
// 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
//
// https://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.
//
// Includes work from abseil-cpp (https://github.com/abseil/abseil-cpp)
// with modifications.
//
// Copyright 2018 The Abseil Authors.
//
// 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
//
// https://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.
// ---------------------------------------------------------------------------
#ifndef BELA_MACROS_HPP
#define BELA_MACROS_HPP
#include <cassert>
#ifdef __has_builtin
#define BELA_HAVE_BUILTIN(x) __has_builtin(x)
#else
#define BELA_HAVE_BUILTIN(x) 0
#endif
#if BELA_HAVE_BUILTIN(__builtin_expect) || (defined(__GNUC__) && !defined(__clang__))
#define BELA_PREDICT_FALSE(x) (__builtin_expect(x, 0))
#define BELA_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
#else
#define BELA_PREDICT_FALSE(x) (x)
#define BELA_PREDICT_TRUE(x) (x)
#endif
#if defined(__has_attribute)
// BELA_HAVE_ATTRIBUTE
//
// A function-like feature checking macro that is a wrapper around
#define BELA_HAVE_ATTRIBUTE(x) __has_attribute(x)
#else
#define BELA_HAVE_ATTRIBUTE(x) 0
#endif
// BELA_ATTRIBUTE_WEAK
//
// Tags a function as weak for the purposes of compilation and linking.
// Weak attributes currently do not work properly in LLVM's Windows backend,
// so disable them there. See https://bugs.llvm.org/show_bug.cgi?id=37598
// for further information.
// The MinGW compiler doesn't complain about the weak attribute until the link
// step, presumably because Windows doesn't use ELF binaries.
#if (BELA_HAVE_ATTRIBUTE(weak) || (defined(__GNUC__) && !defined(__clang__))) && \
!(defined(__llvm__) && defined(_WIN32)) && !defined(__MINGW32__)
#undef BELA_ATTRIBUTE_WEAK
#define BELA_ATTRIBUTE_WEAK __attribute__((weak))
#define BELA_HAVE_ATTRIBUTE_WEAK 1
#else
#define BELA_ATTRIBUTE_WEAK
#define BELA_HAVE_ATTRIBUTE_WEAK 0
#endif
// BELA_HAVE_CPP_ATTRIBUTE
//
// A function-like feature checking macro that accepts C++11 style attributes.
// It's a wrapper around `__has_cpp_attribute`, defined by ISO C++ SD-6
// (https://en.cppreference.com/w/cpp/experimental/feature_test). If we don't
// find `__has_cpp_attribute`, will evaluate to 0.
#if defined(__cplusplus) && defined(__has_cpp_attribute)
// NOTE: requiring __cplusplus above should not be necessary, but
// works around https://bugs.llvm.org/show_bug.cgi?id=23435.
#define BELA_HAVE_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
#else
#define BELA_HAVE_CPP_ATTRIBUTE(x) 0
#endif
#if BELA_HAVE_CPP_ATTRIBUTE(clang::require_constant_initialization)
#define BELA_CONST_INIT [[clang::require_constant_initialization]]
#else
#define BELA_CONST_INIT
#endif // BELA_HAVE_CPP_ATTRIBUTE(clang::require_constant_initialization)
#if defined(__clang__)
#define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x))
#else
#define THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op
#endif
#define GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
#if defined(NDEBUG)
#define BELA_ASSERT(expr) (false ? static_cast<void>(expr) : static_cast<void>(0))
#else
#define BELA_ASSERT(expr) \
(BELA_PREDICT_TRUE((expr)) ? static_cast<void>(0) : [] { assert(false && #expr); }()) // NOLINT
#endif
// BELA_EXCLUSIVE_LOCKS_REQUIRED() / BELA_SHARED_LOCKS_REQUIRED()
//
// Documents a function that expects a mutex to be held prior to entry.
// The mutex is expected to be held both on entry to, and exit from, the
// function.
//
// An exclusive lock allows read-write access to the guarded data member(s), and
// only one thread can acquire a lock exclusively at any one time. A shared lock
// allows read-only access, and any number of threads can acquire a shared lock
// concurrently.
//
// Generally, non-const methods should be annotated with
// BELA_EXCLUSIVE_LOCKS_REQUIRED, while const methods should be annotated with
// BELA_SHARED_LOCKS_REQUIRED.
//
// Example:
//
// Mutex mu1, mu2;
// int a BELA_GUARDED_BY(mu1);
// int b BELA_GUARDED_BY(mu2);
//
// void foo() BELA_EXCLUSIVE_LOCKS_REQUIRED(mu1, mu2) { ... }
// void bar() const BELA_SHARED_LOCKS_REQUIRED(mu1, mu2) { ... }
#if BELA_HAVE_ATTRIBUTE(exclusive_locks_required)
#define BELA_EXCLUSIVE_LOCKS_REQUIRED(...) __attribute__((exclusive_locks_required(__VA_ARGS__)))
#else
#define BELA_EXCLUSIVE_LOCKS_REQUIRED(...)
#endif
#if defined(_MSC_VER) && !defined(__clang__)
#define BELA_FORCE_INLINE __forceinline
#define BELA_ATTRIBUTE_ALWAYS_INLINE
#else
#define BELA_ATTRIBUTE_ALWAYS_INLINE __attribute__((always_inline))
#define BELA_FORCE_INLINE inline BELA_ATTRIBUTE_ALWAYS_INLINE
#endif
#if (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
#define BELA_IS_LITTLE_ENDIAN 1
#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define BELA_IS_BIG_ENDIAN 1
#elif defined(_WIN32)
#define BELA_IS_LITTLE_ENDIAN 1
#else
#error "bela endian detection needs to be set up for your compiler"
#endif
#endif
<file_sep>/vendor/bela/include/bela/fnmatch.hpp
//
#ifndef BELA_FNMATCH_HPP
#define BELA_FNMATCH_HPP
#include <string_view>
namespace bela {
namespace fnmatch {
[[maybe_unused]] constexpr int PathName = 0x1;
[[maybe_unused]] constexpr int NoEscape = 0x2;
[[maybe_unused]] constexpr int Period = 0x4;
[[maybe_unused]] constexpr int LeadingDir = 0x8;
[[maybe_unused]] constexpr int CaseFold = 0x10;
[[maybe_unused]] constexpr int FileName = PathName;
} // namespace fnmatch
// POSIX fnmatch impl see http://man7.org/linux/man-pages/man3/fnmatch.3.html
bool FnMatch(std::u16string_view pattern, std::u16string_view text, int flags = 0);
bool FnMatch(std::wstring_view pattern, std::wstring_view text, int flags = 0);
} // namespace bela
#endif<file_sep>/vendor/bela/test/base/fnmatch.cc
#include <bela/terminal.hpp>
#include <bela/fnmatch.hpp>
void round0() {
constexpr const std::wstring_view rules[] = {L"dev", L"dev*", L"dev?", L"dev+X", L"dev!",
L"car", L"*car", L"?car", L"爱*了"};
constexpr const std::wstring_view strs[] = {L"dev", L"devXX", L"dev/jack", L"car",
L"jackcar", L"jack/car", L"jack.car", L"爱不了"};
bela::FPrintF(stderr, L"|Text\\Rules|");
for (auto r : rules) {
bela::FPrintF(stderr, L"`%s`|", r);
}
bela::FPrintF(stderr, L"\n|---");
for (auto i = 0; i < std::size(rules); i++) {
bela::FPrintF(stderr, L"|---");
}
bela::FPrintF(stderr, L"|\n");
for (auto s : strs) {
bela::FPrintF(stderr, L"|`%s`|", s);
for (auto r : rules) {
bela::FPrintF(stderr, L"`%b`|", bela::FnMatch(r, s, 0));
}
bela::FPrintF(stderr, L"\n");
}
}
int wmain() {
round0();
return 0;
}<file_sep>/vendor/bela/src/belawin/io.cc
//
#include <bela/base.hpp>
#include <bela/endian.hpp>
#include <bela/io.hpp>
#include <bela/path.hpp>
namespace bela::io {
void FD::Free() {
if (fd != INVALID_HANDLE_VALUE && needClosed) {
CloseHandle(fd);
}
fd = INVALID_HANDLE_VALUE;
}
void FD::MoveFrom(FD &&o) {
Free();
fd = o.fd;
needClosed = o.needClosed;
o.fd = INVALID_HANDLE_VALUE;
o.needClosed = false;
}
bool FD::ReadAt(std::span<uint8_t> buffer, int64_t pos, int64_t &outlen, bela::error_code &ec) const {
if (!bela::io::Seek(fd, pos, ec)) {
return false;
}
DWORD dwSize = 0;
if (::ReadFile(fd, buffer.data(), static_cast<DWORD>(buffer.size()), &dwSize, nullptr) != TRUE) {
ec = bela::make_system_error_code(L"ReadFile: ");
return false;
}
outlen = static_cast<int64_t>(dwSize);
return true;
}
bool FD::ReadFull(std::span<uint8_t> buffer, bela::error_code &ec) const {
if (buffer.empty()) {
return true;
}
// auto bytes=std::as_writable_bytes(buffer);
auto p = reinterpret_cast<uint8_t *>(buffer.data());
auto len = buffer.size();
size_t total = 0;
while (total < len) {
DWORD dwSize = 0;
if (::ReadFile(fd, p + total, static_cast<DWORD>(len - total), &dwSize, nullptr) != TRUE) {
ec = bela::make_system_error_code(L"ReadFile: ");
return false;
}
if (dwSize == 0) {
ec = bela::make_error_code(ErrEOF, L"Reached the end of the file");
return false;
}
total += dwSize;
}
return true;
}
bool FD::ReadAt(std::span<uint8_t> buffer, int64_t pos, bela::error_code &ec) const {
if (!bela::io::Seek(fd, pos, ec)) {
return false;
}
return ReadFull(buffer, ec);
}
std::optional<FD> NewFile(std::wstring_view file, bela::error_code &ec) {
auto fd = CreateFileW(file.data(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (fd == INVALID_HANDLE_VALUE) {
ec = bela::make_system_error_code(L"CreateFileW() ");
return std::nullopt;
}
return std::make_optional<FD>(fd, true);
}
std::optional<FD> NewFile(std::wstring_view file, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes, HANDLE hTemplateFile, bela::error_code &ec) {
auto fd = CreateFileW(file.data(), dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition,
dwFlagsAndAttributes, hTemplateFile);
if (fd == INVALID_HANDLE_VALUE) {
ec = bela::make_system_error_code(L"CreateFileW() ");
return std::nullopt;
}
return std::make_optional<FD>(fd, true);
}
bool ReadFile(std::wstring_view file, std::wstring &out, bela::error_code &ec, uint64_t maxsize) {
auto fd = bela::io::NewFile(file, ec);
if (!fd) {
return false;
}
auto size = fd->Size(ec);
if (size == bela::SizeUnInitialized) {
return false;
}
auto maxSize = (std::min)(static_cast<size_t>(maxsize), static_cast<size_t>(size));
bela::Buffer buffer(maxSize);
if (!fd->ReadFull(buffer, maxSize, ec)) {
return false;
}
auto bv = buffer.as_bytes_view();
constexpr uint8_t utf8bom[] = {0xEF, 0xBB, 0xBF};
constexpr uint8_t utf16le[] = {0xFF, 0xFE};
constexpr uint8_t utf16be[] = {0xFE, 0xFF};
if (bv.starts_bytes_with(utf8bom)) {
out = bela::encode_into<char, wchar_t>(bv.make_string_view<char>(3));
return true;
}
if constexpr (bela::IsLittleEndian()) {
if (bv.starts_bytes_with(utf16le)) {
out = bv.make_string_view<wchar_t>(2);
return true;
}
if (bv.starts_bytes_with(utf16be)) {
auto wsv = bv.make_string_view<wchar_t>(2);
out.resize(wsv.size());
wchar_t *p = out.data();
for (size_t i = 0; i < wsv.size(); i++) {
p[i] = static_cast<wchar_t>(bela::frombe(static_cast<uint16_t>(wsv[i])));
}
return true;
}
} else {
if (bv.starts_bytes_with(utf16be)) {
out = bv.make_string_view<wchar_t>(2);
return true;
}
if (bv.starts_bytes_with(utf16le)) {
auto wsv = bv.make_string_view<wchar_t>(2);
out.resize(wsv.size());
wchar_t *p = out.data();
for (size_t i = 0; i < wsv.size(); i++) {
p[i] = bela::fromle(wsv[i]);
}
return true;
}
}
out = bela::encode_into<char, wchar_t>(bv.make_string_view<char>());
return true;
}
bool ReadLine(std::wstring_view file, std::wstring &out, bela::error_code &ec, uint64_t maxline) {
if (!ReadFile(file, out, ec, maxline)) {
return false;
}
if (auto pos = out.find_first_of(L"\r\n"); pos != std::wstring::npos) {
out.resize(pos);
}
return true;
}
bool ReadFile(std::wstring_view file, std::string &out, bela::error_code &ec, uint64_t maxsize) {
auto fd = bela::io::NewFile(file, ec);
if (!fd) {
return false;
}
auto size = fd->Size(ec);
if (size == bela::SizeUnInitialized) {
return false;
}
auto maxSize = (std::min)(static_cast<size_t>(maxsize), static_cast<size_t>(size));
bela::Buffer buffer(maxSize);
if (!fd->ReadFull(buffer, maxSize, ec)) {
return false;
}
auto bv = buffer.as_bytes_view();
constexpr uint8_t utf8bom[] = {0xEF, 0xBB, 0xBF};
constexpr uint8_t utf16le[] = {0xFF, 0xFE};
constexpr uint8_t utf16be[] = {0xFE, 0xFF};
if (bv.starts_bytes_with(utf8bom)) {
out = bv.make_string_view<char>(3);
return true;
}
if constexpr (bela::IsLittleEndian()) {
if (bv.starts_bytes_with(utf16le)) {
out = bela::encode_into<wchar_t, char>(bv.make_string_view<wchar_t>(2));
return true;
}
if (bv.starts_bytes_with(utf16be)) {
auto wsv = bv.make_string_view<wchar_t>(2);
std::wstring tempout;
tempout.resize(wsv.size());
wchar_t *p = tempout.data();
for (size_t i = 0; i < wsv.size(); i++) {
p[i] = static_cast<wchar_t>(bela::frombe(static_cast<uint16_t>(wsv[i])));
}
out = bela::encode_into<wchar_t, char>(tempout);
return true;
}
} else {
if (bv.starts_bytes_with(utf16be)) {
out = bela::encode_into<wchar_t, char>(bv.make_string_view<wchar_t>(2));
return true;
}
if (bv.starts_bytes_with(utf16le)) {
auto wsv = bv.make_string_view<wchar_t>(2);
std::wstring tempout;
tempout.resize(wsv.size());
wchar_t *p = tempout.data();
for (size_t i = 0; i < wsv.size(); i++) {
p[i] = bela::fromle(wsv[i]);
}
out = bela::encode_into<wchar_t, char>(tempout);
return true;
}
}
out = bv.make_string_view<char>();
return true;
}
bool WriteTextInternal(std::string_view bom, std::string_view text, std::wstring_view file, bela::error_code &ec) {
auto FileHandle = ::CreateFileW(file.data(), FILE_GENERIC_READ | FILE_GENERIC_WRITE, FILE_SHARE_READ, nullptr,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (FileHandle == INVALID_HANDLE_VALUE) {
ec = bela::make_system_error_code();
return false;
}
auto closer = bela::finally([&] { CloseHandle(FileHandle); });
DWORD written = 0;
if (!bom.empty()) {
if (WriteFile(FileHandle, bom.data(), static_cast<DWORD>(bom.size()), &written, nullptr) != TRUE) {
ec = bela::make_system_error_code();
return false;
}
}
written = 0;
auto p = text.data();
auto size = text.size();
while (size > 0) {
auto len = (std::min)(size, static_cast<size_t>(4096));
if (WriteFile(FileHandle, p, static_cast<DWORD>(len), &written, nullptr) != TRUE) {
ec = bela::make_system_error_code();
break;
}
size -= written;
p += written;
}
return size == 0;
}
bool WriteTextU16LE(std::wstring_view text, std::wstring_view file, bela::error_code &ec) {
if constexpr (bela::IsBigEndian()) {
constexpr uint8_t u16bebom[] = {0xFE, 0xFF};
std::string_view bom{reinterpret_cast<const char *>(u16bebom), 2};
std::wstring s(text);
for (auto &ch : s) {
ch = static_cast<uint16_t>(bela::swap16(static_cast<uint16_t>(ch)));
}
std::string_view text_{reinterpret_cast<const char *>(s.data()), s.size() * sizeof(wchar_t)};
return WriteTextInternal(bom, text_, file, ec);
}
constexpr uint8_t u16lebom[] = {0xFF, 0xFE};
std::string_view bom{reinterpret_cast<const char *>(u16lebom), 2};
std::string_view text_{reinterpret_cast<const char *>(text.data()), text.size() * sizeof(wchar_t)};
return WriteTextInternal(bom, text_, file, ec);
}
bool WriteText(std::string_view text, std::wstring_view file, bela::error_code &ec) {
return WriteTextInternal("", text, file, ec);
}
bool WriteTextAtomic(std::string_view text, std::wstring_view file, bela::error_code &ec) {
if (!bela::PathExists(file)) {
return WriteTextInternal("", text, file, ec);
}
auto lock = bela::StringCat(file, L".lock");
if (!WriteText(text, lock, ec)) {
DeleteFileW(lock.data());
return false;
}
auto old = bela::StringCat(file, L".old");
if (MoveFileW(file.data(), old.data()) != TRUE) {
ec = bela::make_system_error_code();
DeleteFileW(lock.data());
return false;
}
if (MoveFileW(lock.data(), file.data()) != TRUE) {
ec = bela::make_system_error_code();
MoveFileW(old.data(), file.data());
return false;
}
DeleteFileW(old.data());
return true;
}
} // namespace bela::io
<file_sep>/vendor/bela/test/fmt/charconv.cc
////
#include <bela/charconv.hpp>
#include <bela/str_cat.hpp>
#include <bela/terminal.hpp>
int wmain() {
const wchar_t *w = L"196.1082741";
double n;
auto r = bela::from_chars(w, w + wcslen(w), n);
const char *nums[] = {"123", "456.3", "75815278", "123456", "0x1233", "0123456", "x0111", "-78152"};
for (const auto n : nums) {
int X = 0;
if (bela::SimpleAtoi(n, &X)) {
bela::FPrintF(stderr, L"Good integer %s --> %d\n", n, X);
continue;
}
bela::FPrintF(stderr, L"Bad integer %s\n", n);
}
bela::FPrintF(stderr, L"%0.2f\n", n);
return 0;
}
<file_sep>/vendor/bela/src/belawin/pe/resource.cc
///
#include "internal.hpp"
namespace bela::pe {
// manifest
constexpr std::string_view rsrcName = ".rsrc";
std::optional<Version> File::LookupVersion(bela::error_code &ec) const {
auto dd = getDataDirectory(IMAGE_DIRECTORY_ENTRY_RESOURCE);
if (dd == nullptr) {
return std::nullopt;
}
if (dd->VirtualAddress == 0) {
return std::nullopt;
}
auto sec = getSection(rsrcName);
if (sec == nullptr) {
return std::nullopt;
}
auto offset = static_cast<int64_t>(sec->Offset);
auto N = dd->VirtualAddress - sec->VirtualAddress;
auto offsetSize = sec->Size - N;
IMAGE_RESOURCE_DIRECTORY ird;
if (!fd.ReadAt(ird, offset, ec)) {
return std::nullopt;
}
auto totalEntries = static_cast<int>(ird.NumberOfNamedEntries) + static_cast<int>(ird.NumberOfIdEntries);
if (totalEntries == 0) {
return std::nullopt;
}
IMAGE_RESOURCE_DIRECTORY_ENTRY entry;
for (auto i = 0; i < totalEntries; i++) {
if (!fd.ReadFull(entry, ec)) {
return std::nullopt;
}
// if (entry.NameIsString != 1) {
// continue;
// }
// if (entry.Name != 0x00000010) {
// }
}
return std::nullopt;
}
} // namespace bela::pe<file_sep>/vendor/bela/include/bela/types.hpp
///
#ifndef BELA_TYPES_HPP
#define BELA_TYPES_HPP
#include <cstddef>
#include <concepts>
namespace bela {
#ifndef __BELA__SSIZE_DEFINED_T
#define __BELA__SSIZE_DEFINED_T
using __bela__ssize_t = std::ptrdiff_t;
#endif
using ssize_t = __bela__ssize_t;
template <class _Ty, class... _Types>
constexpr bool is_any_of_v = // true if and only if _Ty is in _Types
std::disjunction_v<std::is_same<_Ty, _Types>...>;
template <class T>
constexpr bool is_character_v =
is_any_of_v<std::remove_cv_t<T>, char, signed char, unsigned char, wchar_t, char8_t, char16_t, char32_t>;
template <class T> constexpr bool is_wide_character_v = is_any_of_v<std::remove_cv_t<T>, wchar_t, char16_t>;
template <class T>
constexpr bool is_narrow_character_v = is_any_of_v<std::remove_cv_t<T>, char, signed char, unsigned char, char8_t>;
template <class T>
concept character = is_character_v<T>;
template <class T>
concept wide_character = is_wide_character_v<T>;
template <class T>
concept narrow_character = is_narrow_character_v<T>;
template <class T>
concept standard_layout = std::is_standard_layout_v<T>;
template <class T>
concept trivial = std::is_trivial_v<T>;
template <class T>
concept integral_superset = std::integral<T> || std::is_enum_v<T>;
// funs
template <typename T, typename K> constexpr bool FlagIsTrue(T a, K b) { return (a & static_cast<T>(b)) != 0; }
constexpr int64_t SizeUnInitialized{-1};
} // namespace bela
#endif<file_sep>/vendor/bela/src/bela/fnmatch.cc
// Origin fnmatch.cc copyright
/*
* An implementation of what I call the "Sea of Stars" algorithm for
* POSIX fnmatch(). The basic idea is that we factor the pattern into
* a head component (which we match first and can reject without ever
* measuring the length of the string), an optional tail component
* (which only exists if the pattern contains at least one star), and
* an optional "sea of stars", a set of star-separated components
* between the head and tail. After the head and tail matches have
* been removed from the input string, the components in the "sea of
* stars" are matched sequentially by searching for their first
* occurrence past the end of the previous match.
*
* - <NAME>, April 2012
*/
// FnMatch
#include <bela/fnmatch.hpp>
namespace bela {
constexpr int END = 0;
constexpr int UNMATCHABLE = -2;
constexpr int BRACKET = -3;
constexpr int QUESTION = -4;
constexpr int STAR = -5;
constexpr bool same_character_matched(wint_t wc, std::u16string_view sv) {
constexpr struct {
std::u16string_view sv;
decltype(iswalnum) *fn;
} matchers[] = {
{u"alnum", iswalnum}, {u"alpha", iswalpha}, {u"blank", iswblank}, {u"cntrl", iswcntrl},
{u"digit", iswdigit}, {u"graph", iswgraph}, {u"lower", iswlower}, {u"print", iswprint},
{u"punct", iswpunct}, {u"space", iswspace}, {u"upper", iswupper}, {u"xdigit", iswxdigit},
};
for (const auto &m : matchers) {
if (m.sv == sv) {
return m.fn(wc) != 0;
}
}
return false;
} // namespace bela
// convert UTF-16 text to UTF-32
int CharNext(const char16_t *str, size_t n, size_t *step) {
if (n == 0) {
*step = 0;
return 0;
}
char32_t ch = str[0];
if (ch >= 0xD800 && ch <= 0xDBFF) {
if (n < 2) {
*step = 1;
return -1;
}
*step = 2;
char32_t ch2 = str[1];
if (ch2 < 0xDC00 || ch2 > 0xDFFF) {
*step = 1;
return -1;
}
ch = ((ch - 0xD800) << 10) + (ch2 - 0xDC00) + 0x10000U;
return ch;
}
*step = 1;
return ch;
}
int CharUnicode(char32_t *c, const char16_t *str, size_t n) {
if (n == 0) {
return -1;
}
char32_t ch = str[0];
if (ch >= 0xD800 && ch <= 0xDBFF) {
if (n < 2) {
return -1;
}
char32_t ch2 = str[1];
if (ch2 < 0xDC00 || ch2 > 0xDFFF) {
return -1;
}
*c = ((ch - 0xD800) << 10) + (ch2 - 0xDC00) + 0x10000U;
return 2;
}
*c = ch;
return 1;
}
static int PatternNext(const char16_t *pat, size_t m, size_t *step, int flags) {
int esc = 0;
if ((m == 0U) || (*pat == 0U)) {
*step = 0;
return END;
}
*step = 1;
if (pat[0] == '\\' && (pat[1] != 0U) && (flags & fnmatch::NoEscape) == 0) {
*step = 2;
pat++;
esc = 1;
goto escaped;
}
if (pat[0] == '[') {
size_t k = 1;
if (k < m) {
if (pat[k] == '^' || pat[k] == '!') {
k++;
}
}
if (k < m) {
if (pat[k] == ']') {
k++;
}
}
for (; k < m && (pat[k] != 0U) && pat[k] != ']'; k++) {
if (k + 1 < m && (pat[k + 1] != 0U) && pat[k] == '[' && (pat[k + 1] == ':' || pat[k + 1] == '.' || pat[k + 1] == '=')) {
int z = pat[k + 1];
k += 2;
if (k < m && (pat[k] != 0U)) {
k++;
}
while (k < m && (pat[k] != 0U) && (pat[k - 1] != z || pat[k] != ']')) {
k++;
}
if (k == m || (pat[k] == 0U)) {
break;
}
}
}
if (k == m || (pat[k] == 0U)) {
*step = 1;
return '[';
}
*step = k + 1;
return BRACKET;
}
if (pat[0] == '*') {
return STAR;
}
if (pat[0] == '?') {
return QUESTION;
}
escaped:
if (pat[0] >= 0xD800 && pat[0] <= 0xDBFF) {
char32_t ch = pat[0];
if (m < 2) {
*step = 0;
return UNMATCHABLE;
}
char32_t ch2 = pat[1];
ch = ((ch - 0xD800) << 10) + (ch2 - 0xDC00) + 0x10000U;
*step = 2 + esc;
return ch;
}
return pat[0];
}
static inline int CaseFold(int k) {
int c = towupper(static_cast<wint_t>(k));
return c == k ? towlower(static_cast<wint_t>(k)) : c;
}
static int MatchBracket(const char16_t *p, int k, int kfold) {
char32_t wc;
int inv = 0;
p++;
if (*p == '^' || *p == '!') {
inv = 1;
p++;
}
if (*p == ']') {
if (k == ']') {
return static_cast<int>(static_cast<int>(inv) == 0);
}
p++;
} else if (*p == '-') {
if (k == '-') {
return static_cast<int>(static_cast<int>(inv) == 0);
}
p++;
}
wc = p[-1];
for (; *p != ']'; p++) {
if (p[0] == '-' && p[1] != ']') {
char32_t wc2;
int l = CharUnicode(&wc2, p + 1, 4);
if (l < 0) {
return 0;
}
if (wc <= wc2) {
if ((unsigned)k - wc <= wc2 - wc || (unsigned)kfold - wc <= wc2 - wc) {
return static_cast<int>(static_cast<int>(inv) == 0);
}
}
p += l - 1;
continue;
}
if (p[0] == '[' && (p[1] == ':' || p[1] == '.' || p[1] == '=')) {
const char16_t *p0 = p + 2;
int z = p[1];
p += 3;
while (p[-1] != z || p[0] != ']') {
p++;
}
auto svlen = p - 1 - p0;
if (z == ':' && svlen < 16) {
std::u16string_view sv{p0, static_cast<size_t>(svlen)};
if (same_character_matched(static_cast<wint_t>(k), sv) ||
same_character_matched(static_cast<wint_t>(kfold), sv)) {
return static_cast<int>(static_cast<int>(inv) == 0);
}
}
continue;
}
if (*p < 128U) {
wc = (unsigned char)*p;
} else {
int l = CharUnicode(&wc, p, 4);
if (l < 0) {
return 0;
}
p += l - 1;
}
if (wc == static_cast<char32_t>(k) || wc == static_cast<char32_t>(kfold)) {
return static_cast<int>(static_cast<int>(inv) == 0);
}
}
return inv;
}
static int FnMatchInternal(const char16_t *pat, size_t m, const char16_t *str, size_t n, int flags) {
const char16_t *p;
const char16_t *ptail;
const char16_t *endpat;
const char16_t *s;
const char16_t *stail;
const char16_t *endstr;
size_t pinc;
size_t sinc;
size_t tailcnt = 0;
int c;
int k;
int kfold;
if ((flags & fnmatch::Period) != 0) {
if (*str == '.' && *pat != '.') {
return 1;
}
}
for (;;) {
switch ((c = PatternNext(pat, m, &pinc, flags))) {
case UNMATCHABLE:
return 1;
case STAR:
pat++;
m--;
break;
default:
k = CharNext(str, n, &sinc);
if (k <= 0) {
return (c == END) ? 0 : 1;
}
str += sinc;
n -= sinc;
kfold = (flags & fnmatch::CaseFold) != 0 ? CaseFold(k) : k;
if (c == BRACKET) {
if (MatchBracket(pat, k, kfold) == 0) {
return 1;
}
} else if (c != QUESTION && k != c && kfold != c) {
return 1;
}
pat += pinc;
m -= pinc;
continue;
}
break;
}
endpat = pat + m;
/* Find the last * in pat and count chars needed after it */
for (p = ptail = pat; p < endpat; p += pinc) {
switch (PatternNext(p, endpat - p, &pinc, flags)) {
case UNMATCHABLE:
return 1;
case STAR:
tailcnt = 0;
ptail = p + 1;
break;
default:
tailcnt++;
break;
}
}
/* Past this point we need not check for UNMATCHABLE in pat,
* because all of pat has already been parsed once. */
endstr = str + n;
if (n < tailcnt) {
return 1;
}
/* Find the final tailcnt chars of str, accounting for UTF-8.
* On illegal sequences we may get it wrong, but in that case
* we necessarily have a matching failure anyway. */
for (s = endstr; s > str && (tailcnt != 0U); tailcnt--) {
if (s[-1] < 128U || MB_CUR_MAX == 1) {
s--;
continue;
}
while ((unsigned char)*--s - 0x80U < 0x40 && s > str) {
}
}
if (tailcnt != 0U) {
return 1;
}
stail = s;
/* Check that the pat and str tails match */
p = ptail;
for (;;) {
c = PatternNext(p, endpat - p, &pinc, flags);
p += pinc;
if ((k = CharNext(s, endstr - s, &sinc)) <= 0) {
if (c != END) {
return 1;
}
break;
}
s += sinc;
kfold = (flags & fnmatch::CaseFold) != 0 ? CaseFold(k) : k;
if (c == BRACKET) {
if (MatchBracket(p - pinc, k, kfold) == 0) {
return 1;
}
} else if (c != QUESTION && k != c && kfold != c) {
return 1;
}
}
/* We're all done with the tails now, so throw them out */
endstr = stail;
endpat = ptail;
/* Match pattern components until there are none left */
while (pat < endpat) {
p = pat;
s = str;
for (;;) {
c = PatternNext(p, endpat - p, &pinc, flags);
p += pinc;
/* Encountering * completes/commits a component */
if (c == STAR) {
pat = p;
str = s;
break;
}
k = CharNext(s, endstr - s, &sinc);
if (k == 0) {
return 1;
}
kfold = (flags & fnmatch::CaseFold) != 0 ? CaseFold(k) : k;
if (c == BRACKET) {
if (MatchBracket(p - pinc, k, kfold) == 0) {
break;
}
} else if (c != QUESTION && k != c && kfold != c) {
break;
}
s += sinc;
}
if (c == STAR) {
continue;
}
/* If we failed, advance str, by 1 char if it's a valid
* char, or past all invalid bytes otherwise. */
k = CharNext(str, endstr - str, &sinc);
if (k > 0) {
str += sinc;
} else {
for (str++; CharNext(str, endstr - str, &sinc) < 0; str++) {
/// empty
}
}
}
return 0;
}
int FnMatchInternal(std::u16string_view pattern, std::u16string_view text, int flags) {
return FnMatchInternal(pattern.data(), pattern.size(), text.data(), text.size(), flags);
}
// Thanks https://github.com/bminor/musl/blob/master/src/regex/fnmatch.c
bool FnMatch(std::u16string_view pattern, std::u16string_view text, int flags) {
if (pattern.empty() || text.empty()) {
return false;
}
if ((flags & fnmatch::PathName) != 0) {
// auto pos = text.find_first_of(u"\\/");
// auto pat = pattern;
// size_t inc = 0;
// int c = 0;
// for (;;) {
// if (c = PatternNext(pat.data(), pat.size(), &inc, flags); (c == END || c == '/')) {
// break;
// }
// pat.remove_prefix(inc);
// }
// auto p = pos == std::u16string_view::npos ? 0 : text[pos];
// if (c != p && (pos == std::u16string_view::npos || (flags & fnmatch::LeadingDir) == 0)) {
// return false;
// }
// auto pattern_ = pat.substr(inc);
// auto text_ = text.substr(pos + 1);
// if (FnMatchInternal(pattern_, text_, flags) == 0) {
// return true;
// }
// return false;
}
if ((flags & fnmatch::LeadingDir) != 0) {
if (auto pos = text.find_first_of(u"\\/"); pos != std::u16string_view::npos) {
text.remove_suffix(text.size() - pos);
}
}
return FnMatchInternal(pattern, text, flags) == 0;
}
inline std::u16string_view u16sv(std::wstring_view sv) {
return std::u16string_view{reinterpret_cast<const char16_t *>(sv.data()), sv.size()};
}
// Thanks https://github.com/bminor/musl/blob/master/src/regex/fnmatch.c
bool FnMatch(std::wstring_view pattern, std::wstring_view text, int flags) {
return FnMatch(u16sv(pattern), u16sv(text), flags);
}
} // namespace bela<file_sep>/lib/exec/elevator.cc
///
#include "execinternal.hpp"
#include <wtsapi32.h>
namespace wsudo::exec {
// bela::EqualsIgnoreCase
[[maybe_unused]] constexpr std::wstring_view WinLogonName = L"winlogon.exe";
// Get Current Process SessionID and Enable SeDebugPrivilege
bool PrepareElevate(DWORD &sid, bela::error_code &ec) {
if (!IsUserAdministratorsGroup()) {
ec = bela::make_error_code(1, L"current process not runing in administrator");
return false;
}
auto hToken = INVALID_HANDLE_VALUE;
constexpr DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
if (OpenProcessToken(GetCurrentProcess(), flags, &hToken) != TRUE) {
ec = bela::make_system_error_code(L"PrepareElevate<OpenProcessToken> ");
return false;
}
auto closer = bela::finally([&] { CloseHandle(hToken); });
DWORD Length = 0;
if (GetTokenInformation(hToken, TokenSessionId, &sid, sizeof(DWORD), &Length) != TRUE) {
ec = bela::make_system_error_code(L"PrepareElevate<GetTokenInformation> ");
return false;
}
TOKEN_PRIVILEGES tp;
LUID luid;
if (::LookupPrivilegeValueW(nullptr, SE_DEBUG_NAME, &luid) != TRUE) {
ec = bela::make_system_error_code(L"PrepareElevate<LookupPrivilegeValueW> ");
return false;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
// Enable the privilege or disable all privileges.
if (::AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), nullptr, nullptr) != TRUE) {
ec = bela::make_system_error_code(L"PrepareElevate<AdjustTokenPrivileges> ");
return false;
}
if (::GetLastError() == ERROR_NOT_ALL_ASSIGNED) {
ec = bela::make_system_error_code(L"PrepareElevate<AdjustTokenPrivileges> ");
return false;
}
return true;
}
bool PrivilegesEnableAll(HANDLE hToken) {
if (hToken == INVALID_HANDLE_VALUE) {
return false;
}
DWORD Length = 0;
GetTokenInformation(hToken, TokenPrivileges, nullptr, 0, &Length);
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
return false;
}
auto privs = (PTOKEN_PRIVILEGES)HeapAlloc(GetProcessHeap(), 0, Length);
if (privs == nullptr) {
return false;
}
auto pfree = bela::finally([&] { HeapFree(GetProcessHeap(), 0, privs); });
if (GetTokenInformation(hToken, TokenPrivileges, privs, Length, &Length) != TRUE) {
return false;
}
auto end = privs->Privileges + privs->PrivilegeCount;
for (auto it = privs->Privileges; it != end; it++) {
it->Attributes = SE_PRIVILEGE_ENABLED;
}
return (AdjustTokenPrivileges(hToken, FALSE, privs, 0, nullptr, nullptr) == TRUE);
}
bool PrivilegesEnableView(HANDLE hToken, const PrivilegeView *pv) {
if (pv == nullptr) {
return PrivilegesEnableAll(hToken);
}
for (const auto lpszPrivilege : pv->privis) {
TOKEN_PRIVILEGES tp;
LUID luid;
if (::LookupPrivilegeValueW(nullptr, lpszPrivilege, &luid) != TRUE) {
continue;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
// Enable the privilege or disable all privileges.
if (::AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), nullptr, nullptr) != TRUE) {
continue;
}
if (::GetLastError() == ERROR_NOT_ALL_ASSIGNED) {
return false;
}
}
return true;
}
bool Elevator::elevateimitate(bela::error_code &ec) {
HANDLE hExistingToken = INVALID_HANDLE_VALUE;
auto hProcess = ::OpenProcess(MAXIMUM_ALLOWED, FALSE, pid);
if (hProcess == INVALID_HANDLE_VALUE) {
ec = bela::make_system_error_code(L"Elevator::elevateimitate<OpenProcess> ");
return false;
}
auto hpdeleter = bela::finally([&] { CloseHandle(hProcess); });
if (OpenProcessToken(hProcess, MAXIMUM_ALLOWED, &hExistingToken) != TRUE) {
ec = bela::make_system_error_code(L"Elevator::elevateimitate<OpenProcessToken> ");
return false;
}
auto htdeleter = bela::finally([&] { CloseHandle(hExistingToken); });
if (DuplicateTokenEx(hExistingToken, MAXIMUM_ALLOWED, nullptr, SecurityImpersonation, TokenImpersonation, &hToken) !=
TRUE) {
ec = bela::make_system_error_code(L"Elevator::elevateimitate<DuplicateTokenEx> ");
return false;
}
return true;
}
bool LookupSystemProcess(DWORD sid, DWORD &syspid) {
PWTS_PROCESS_INFOW ppi;
DWORD count;
if (::WTSEnumerateProcessesW(WTS_CURRENT_SERVER_HANDLE, 0, 1, &ppi, &count) != TRUE) {
return false;
}
auto end = ppi + count;
for (auto it = ppi; it != end; it++) {
if (it->SessionId == sid && bela::EqualsIgnoreCase(WinLogonName, it->pProcessName) &&
IsWellKnownSid(it->pUserSid, WinLocalSystemSid) == TRUE) {
syspid = it->ProcessId;
::WTSFreeMemory(ppi);
return true;
}
}
::WTSFreeMemory(ppi);
return false;
}
bool GetCurrentSessionId(DWORD &dwSessionId) {
HANDLE hToken = INVALID_HANDLE_VALUE;
if (!OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &hToken)) {
return false;
}
DWORD Length = 0;
if (GetTokenInformation(hToken, TokenSessionId, &dwSessionId, sizeof(DWORD), &Length) != TRUE) {
CloseHandle(hToken);
return false;
}
CloseHandle(hToken);
return true;
}
// Improve self-generated permissions
bool Elevator::elevate(const PrivilegeView *pv, bela::error_code &ec) {
if (!PrepareElevate(sid, ec)) {
return false;
}
if (!LookupSystemProcess(sid, pid)) {
ec = bela::make_error_code(1, L"Elevator::elevate unable lookup winlogon process pid");
return false;
}
if (!elevateimitate(ec)) {
return false;
}
if (!PrivilegesEnableView(hToken, pv)) {
ec = bela::make_error_code(1, L"Elevator::elevate unable enable privileges: ", pv == nullptr ? L"all" : pv->dump());
return false;
}
if (SetThreadToken(nullptr, hToken) != TRUE) {
ec = bela::make_error_code(1, L"Elevator::elevate<SetThreadToken> ");
return false;
}
return true;
}
} // namespace wsudo::exec<file_sep>/vendor/bela/src/bela/memutil.cc
// ---------------------------------------------------------------------------
// Copyright (C) 2022, Bela contributors
//
// 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
//
// https://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.
//
// Includes work from abseil-cpp (https://github.com/abseil/abseil-cpp)
// with modifications.
//
// Copyright 2019 The Abseil Authors.
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ---------------------------------------------------------------------------
#include <cwctype>
// https://en.cppreference.com/w/cpp/header/cwctype
#include <bela/memutil.hpp>
namespace bela::strings_internal {
int memcasecmp(const wchar_t *s1, const wchar_t *s2, size_t len) noexcept {
for (size_t i = 0; i < len; i++) {
const auto diff = bela::ascii_tolower(s1[i]) - bela::ascii_tolower(s2[i]);
if (diff != 0) {
return static_cast<int>(diff);
}
}
return 0;
}
int memcasecmp(const char *s1, const char *s2, size_t len) noexcept {
for (size_t i = 0; i < len; i++) {
const auto diff = std::tolower(s1[i]) - std::tolower(s2[i]);
if (diff != 0) {
return static_cast<int>(diff);
}
}
return 0;
}
} // namespace bela::strings_internal
<file_sep>/vendor/bela/test/fmt/main.cc
///
#include <bela/str_cat.hpp>
#include <bela/terminal.hpp>
#include <bela/codecvt.hpp>
#include "ucwidth-wt.hpp"
int wmain(int argc, wchar_t **argv) {
constexpr std::string_view ux = "\xf0\x9f\x98\x81 UTF-8 text \xE3\x8D\xA4 --> \xF0\xA0\x83\xA3 \x41 "
"\xE7\xA0\xB4 \xE6\x99\x93"; // force encode UTF-8
constexpr std::wstring_view wx = L"Engine (\xD83D\xDEE0) 中国 \U0001F496 \x0041 \x7834 "
L"\x6653 \xD840\xDCE3";
constexpr std::wstring_view wx2 = L"Engine (🛠) 中国 💖 A 破 晓 𠃣";
constexpr std::u8string_view u8x = u8"💙 中国 \U0001F496 你爱我我爱你,蜜雪冰城甜蜜蜜";
constexpr std::u16string_view u16x = u"💙 中国 \U0001F496 你爱我我爱你,蜜雪冰城甜蜜蜜";
constexpr auto iscpp20 = __cplusplus >= 202004L;
constexpr auto u16len = bela::string_length(u16x);
constexpr auto u8len = bela::string_length(u8x);
constexpr auto wlen = bela::string_length(wx);
constexpr auto w2len = bela::string_length(wx2);
bela::FPrintF(stderr,
L"Argc: %d Arg0: \x1b[32m%s\x1b[0m W: %s UTF-8: %s "
L"__cplusplus: %d C++20: %b\n%s\n",
argc, argv[0], wx, ux, __cplusplus, iscpp20, u8x);
bela::FPrintF(stderr, L"StringLength: %d StringLength %d\n", bela::string_length(u8x), bela::string_length(u16x));
constexpr char32_t em = 0x1F603; // 😃 U+1F603
constexpr char32_t sh = 0x1F496; // 💖
constexpr char32_t blueheart = U'💙'; //💙
constexpr char32_t se = 0x1F92A; //🤪
constexpr char32_t em2 = U'中';
constexpr char32_t hammerandwrench = 0x1F6E0;
wchar_t buf0[4];
char16_t buf1[4];
char buf2[8];
char8_t buf3[8];
bela::FPrintF(stderr, L"encode_into %s [wchar_t], %s [char16_t], %s [char] %s [char8_t]\n",
bela::encode_into(sh, buf0), bela::encode_into(sh, buf1), bela::encode_into(sh, buf2),
bela::encode_into(sh, buf3));
auto s = bela::StringCat(L"Look emoji -->", em, L" U+", bela::AlphaNum(bela::Hex(em)));
bela::FPrintF(stderr, L"emoji %c %c %c %c %U %U %s P: %p\n", em, sh, blueheart, se, em, em2, s, &em);
bela::FPrintF(stderr, L"Unicode %c Width: %d \u2600 %d 中 %d ©: %d [%c] %d [%c] %d \n", em, bela::rune_width(em),
bela::rune_width(0x2600), bela::rune_width(L'中'), bela::rune_width(0xA9), 161, bela::rune_width(161),
hammerandwrench, bela::rune_width(hammerandwrench));
bela::FPrintF(stderr, L"Unicode2 %c Width: %d \u2600 %d 中 %d ©: %d [%c] %d [%c] %d\n", em,
bela::unicode::CalculateWidthInternal(em), bela::unicode::CalculateWidthInternal(0x2600),
bela::unicode::CalculateWidthInternal(L'中'), bela::unicode::CalculateWidthInternal(0xA9), 161,
bela::unicode::CalculateWidthInternal(161), hammerandwrench,
bela::unicode::CalculateWidthInternal(hammerandwrench));
bela::FPrintF(stderr, L"[%-10d]\n", argc);
bela::FPrintF(stderr, L"[%10d]\n", argc);
bela::FPrintF(stderr, L"[%010d]\n", argc);
int n = -1999;
bela::FPrintF(stderr, L"[%-10d]\n", n);
bela::FPrintF(stderr, L"[%10d]\n", n);
bela::FPrintF(stderr, L"[%010d]\n", n);
bela::FPrintF(stderr, L"[%-60d]\n", n);
bela::FPrintF(stderr, L"[%60d]\n", n);
bela::FPrintF(stderr, L"[%060d]\n", n);
int n2 = 2999;
bela::FPrintF(stderr, L"[%-10d]\n", n2);
bela::FPrintF(stderr, L"[%10d]\n", n2);
bela::FPrintF(stderr, L"[%010d]\n", n2);
double ddd = 000192.15777411;
bela::FPrintF(stderr, L"[%08.7f]\n", ddd);
long xl = 18256444;
bela::FPrintF(stderr, L"[%-16x]\n", xl);
bela::FPrintF(stderr, L"[%016X]\n", xl);
bela::FPrintF(stderr, L"[%16X]\n", xl);
bela::FPrintF(stderr, L"%%pointer: [%p]\n", (void *)argv);
bela::FPrintF(stderr, L"StringWidth %d\n",
bela::string_width<wchar_t>(LR"(cmake-3.20.5-windows-x86_64\share\vim\vimfiles\syntax\cmake.vim)"));
bela::FPrintF(stderr, L"StringWidth %d\n",
bela::string_width<char>(R"(cmake-3.20.5-windows-x86_64\share\vim\vimfiles\syntax\cmake.vim)"));
return 0;
}
<file_sep>/vendor/bela/CMakeLists.txt
# top cmake
cmake_minimum_required(VERSION 3.18)
project(bela CXX C ASM)
if(CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR AND NOT MSVC_IDE)
message(
FATAL_ERROR
"In-source builds are not allowed.
CMake would overwrite the makefiles distributed with bela.
Please create a directory and run cmake from there, passing the path
to this source directory as the last argument.
This process created the file `CMakeCache.txt' and the directory `CMakeFiles'.
Please delete them.")
endif()
option(ENABLE_TEST "Enable test" OFF)
option(BELA_ENABLE_LTO "bela enable LTO" OFF)
message(STATUS "CMAKE_ASM_COMPILER_ID ${CMAKE_ASM_COMPILER_ID}")
if(NOT (DEFINED CMAKE_CXX_STANDARD))
set(CMAKE_CXX_STANDARD 20) # /std:c++latest
endif()
if(CMAKE_CXX_STANDARD LESS 20 OR CMAKE_CXX_STANDARD STREQUAL "98")
message(FATAL_ERROR "Bela requires C++20 or later")
endif()
set(CMAKE_CXX_STANDARD_REQUIRED YES)
if("^${CMAKE_SOURCE_DIR}$" STREQUAL "^${PROJECT_SOURCE_DIR}$")
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib)
endif()
if(MSVC)
add_compile_options("-utf-8")
add_compile_options("-permissive-")
add_compile_options("-Zc:__cplusplus")
add_compile_options("-W3")
add_compile_options("-DUNICODE=1")
add_compile_options("-D_UNICODE=1")
add_compile_options("-wd26812")
endif(MSVC)
include_directories(./include)
add_subdirectory(src/bela)
add_subdirectory(src/belawin)
add_subdirectory(src/belashl)
add_subdirectory(src/belatime)
add_subdirectory(src/belaund)
add_subdirectory(src/belahash)
add_subdirectory(src/hazel)
if(ENABLE_TEST)
add_subdirectory(test)
endif()
<file_sep>/vendor/bela/include/bela/memutil.hpp
// ---------------------------------------------------------------------------
// Copyright (C) 2022, Bela contributors
//
// 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
//
// https://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.
//
// Includes work from abseil-cpp (https://github.com/abseil/abseil-cpp)
// with modifications.
//
// Copyright 2019 The Abseil Authors.
//
// 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
//
// https://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.
// ---------------------------------------------------------------------------
#ifndef BELA_MEMUTIL_HPP
#define BELA_MEMUTIL_HPP
#pragma once
#include <cstring>
#include <cstdlib>
#include <cwctype>
#include <cwchar>
#include "ascii.hpp"
namespace bela {
namespace strings_internal {
template <typename T> inline void memcopy(T *dest, const T *src, size_t n) noexcept {
if (n != 0) {
memcpy(dest, src, sizeof(T) * n);
}
}
// Like memcmp, but ignore differences in case.
int memcasecmp(const wchar_t *s1, const wchar_t *s2, size_t len) noexcept;
// Like memcmp, but ignore differences in case.
int memcasecmp(const char *s1, const char *s2, size_t len) noexcept;
} // namespace strings_internal
} // namespace bela
#endif
|
6cbd61ad6117fcb4948ded30845f5a4c8f0a59e1
|
[
"CMake",
"C++"
] | 20
|
C++
|
IMULMUL/Privexec
|
b719136f8eb630418f1ef69d04da6d0f55e12e06
|
52faac9dc3b274c2b962f89d0996064079d84ac4
|
refs/heads/master
|
<repo_name>animkaTT/redmine-api-client-php<file_sep>/lib/Redmine/Exception/CurlException.php
<?php
namespace Redmine\Exception;
class CurlException extends \RuntimeException
{
}
<file_sep>/lib/Redmine/Http/Client.php
<?php
namespace Redmine\Http;
use Redmine\Exception\BadRequestException;
use Redmine\Exception\CurlException;
use Redmine\Exception\InternalServerErrorException;
use Redmine\Response\ApiResponse;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
class Client
{
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
const METHOD_DELETE = 'DELETE';
protected $defaultHeaders;
protected $url;
public function __construct(string $url, array $defaultHeaders = [])
{
$this->url = $url;
$this->defaultHeaders = $defaultHeaders;
}
public function makeRequest(string $path, array $options = []): ApiResponse
{
$optionsResolver = new OptionsResolver();
$this->configureRequestOptions($optionsResolver);
$options = $optionsResolver->resolve($options);
$url = $this->url . $path;
if (\count($options['query'])) {
$url .= '?' . http_build_query($options['query'], '', '&');
}
$curlHandler = curl_init();
curl_setopt($curlHandler, CURLOPT_URL, $url);
curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curlHandler, CURLOPT_FAILONERROR, false);
curl_setopt($curlHandler, CURLOPT_TIMEOUT, $options['timeout']);
curl_setopt($curlHandler, CURLOPT_CONNECTTIMEOUT, 30);
$options['headers'][] = 'Content-type: application/json';
if (\in_array($options['method'], [self::METHOD_DELETE, self::METHOD_PUT], true)) {
curl_setopt($curlHandler, CURLOPT_CUSTOMREQUEST, $options['method']);
}
if (!empty($options['headers'])) {
curl_setopt($curlHandler, CURLOPT_HTTPHEADER, $options['headers']);
}
if (\in_array($options['method'], [self::METHOD_POST, self::METHOD_PUT], true)) {
curl_setopt($curlHandler, CURLOPT_POST, true);
curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $options['postFields']);
}
$responseBody = curl_exec($curlHandler);
$statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE);
$errno = curl_errno($curlHandler);
$error = curl_error($curlHandler);
curl_close($curlHandler);
if ($errno) {
throw new CurlException($error, $errno);
}
if ($statusCode >= 500) {
throw new InternalServerErrorException('Error in redmine api.', $statusCode);
}
if ($statusCode >= 400 && $statusCode < 500) {
throw new BadRequestException('Error in redmine api request: ' . $responseBody, $statusCode);
}
return new ApiResponse($statusCode, $responseBody);
}
protected function configureRequestOptions(OptionsResolver $resolver): void
{
$resolver
->setRequired([
'method',
'timeout'
])
->setDefined([
'headers',
'query',
'postFields',
'cacheLifetime'
])
->setAllowedValues(
'method',
[
static::METHOD_POST,
static::METHOD_GET,
static::METHOD_PUT,
static::METHOD_DELETE,
]
)
->setAllowedTypes('timeout', 'int')
->setAllowedTypes('headers', 'array')
->setAllowedTypes('query', 'array')
->setAllowedTypes('postFields', ['array', 'string'])
->setNormalizer('headers', function (Options $options, $value) {
return array_merge($this->defaultHeaders, $value);
})
->setDefaults([
'headers' => [],
'method' => static::METHOD_GET,
'query' => [],
'postFields' => [],
'timeout' => 30,
])
;
}
}
<file_sep>/lib/Redmine/ApiClient.php
<?php
namespace Redmine;
use Redmine\Http\Client;
use Redmine\Response\ApiResponse;
class ApiClient
{
protected $client;
public function __construct(string $url, string $apiKey)
{
if ('/' !== $url[\strlen($url) - 1]) {
$url .= '/';
}
$this->client = new Client($url, ['X-Redmine-API-Key: ' . $apiKey]);
}
public function requestGet(string $path, ?array $queryParameters = []): ApiResponse
{
return $this->client->makeRequest($path . '.json', [
'query' => $queryParameters,
]);
}
public function requestDelete(string $path, ?array $queryParameters = []): ApiResponse
{
return $this->client->makeRequest($path . '.json', [
'method' => Client::METHOD_DELETE,
'query' => $queryParameters,
]);
}
public function requestPost(string $path, array $postData = [], array $queryParameters = []): ApiResponse
{
return $this->client->makeRequest($path . '.json', [
'method' => Client::METHOD_POST,
'postFields' => json_encode($postData),
'query' => $queryParameters,
]);
}
public function requestPut(string $path, array $putData = [], array $queryParameters = []): ApiResponse
{
return $this->client->makeRequest($path . '.json', [
'method' => Client::METHOD_PUT,
'postFields' => json_encode($putData),
'query' => $queryParameters,
]);
}
}
|
3da9425566f84e04155d6089cfa09086c9a6161d
|
[
"PHP"
] | 3
|
PHP
|
animkaTT/redmine-api-client-php
|
90535ca6d0f3194636e5739b5da9253f6a9f9d4c
|
402ca97d3ae34393e8461e77b78e475a48c5d005
|
refs/heads/master
|
<repo_name>xdpsee/jinyongwuxia<file_sep>/src/Settings.js
import Storage from 'localforage'
export default {
key: {
fontSize: 'reader.font.size',
fontFamily: 'reader.font.family'
},
load (key) {
return Storage.getItem(key)
},
save (key, value) {
return Storage.setItem(key, value)
}
}
<file_sep>/src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import BookShelf from '../components/shelf/BookShelf'
import BookReader from '../components/reader/BookReader'
Vue.use(Router)
export default new Router({
mode: 'history',
scrollBehavior: (to, from, savedPosition) => {
if (savedPosition) {
return savedPosition
}
return {x: 0, y: 0}
},
routes: [
{
path: '/',
component: BookShelf
},
{
path: '/book',
component: BookReader
}
]
})
|
03f446f6396a2cfce26b5542c5066f90bbfc83ee
|
[
"JavaScript"
] | 2
|
JavaScript
|
xdpsee/jinyongwuxia
|
529c3b1c426c98b9bb6da181a00733bfa768b24c
|
9cf0a127cae7f605aafc36c378f89e17e1dfb94d
|
refs/heads/master
|
<repo_name>p-sad/Waffle<file_sep>/waffle-chai/src/matchers/misc/account.ts
import {Contract, Signer, Wallet} from 'ethers';
export type Account = Signer | Contract;
export function isAccount(account: Account): account is Contract | Wallet {
return account instanceof Contract || account instanceof Wallet;
}
export async function getAddressOf(account: Account) {
if (isAccount(account)) {
return account.address;
} else {
return account.getAddress();
}
}
<file_sep>/waffle-jest/src/matchers/bigNumber.ts
import {BigNumber} from 'ethers';
import {Numberish} from '../types';
// NOTE: Jest does not currently support overriding matchers while calling
// original implementation, therefore we have to name our matchers something
// different: https://github.com/facebook/jest/issues/6243
export const bigNumberMatchers = {
toEqBN(received: Numberish, value: Numberish) {
const pass = BigNumber.from(received).eq(value);
return pass
? {
pass: true,
message: () => `Expected "${received}" NOT to be equal ${value}`
}
: {
pass: false,
message: () => `Expected "${received}" to be equal ${value}`
};
},
toBeGtBN(received: Numberish, value: Numberish) {
const pass = BigNumber.from(received).gt(value);
return pass
? {
pass: true,
message: () =>
`Expected "${received}" NOT to be greater than ${value}`
}
: {
pass: false,
message: () => `Expected "${received}" to be greater than ${value}`
};
},
toBeLtBN(received: Numberish, value: Numberish) {
const pass = BigNumber.from(received).lt(value);
return pass
? {
pass: true,
message: () => `Expected "${received}" NOT to be less than ${value}`
}
: {
pass: false,
message: () => `Expected "${received}" to be less than ${value}`
};
},
toBeGteBN(received: Numberish, value: Numberish) {
const pass = BigNumber.from(received).gte(value);
return pass
? {
pass: true,
message: () =>
`Expected "${received}" NOT to be greater than or equal ${value}`
}
: {
pass: false,
message: () =>
`Expected "${received}" to be greater than or equal ${value}`
};
},
toBeLteBN(received: Numberish, value: Numberish) {
const pass = BigNumber.from(received).lte(value);
return pass
? {
pass: true,
message: () =>
`Expected "${received}" NOT to be less than or equal ${value}`
}
: {
pass: false,
message: () =>
`Expected "${received}" to be less than or equal ${value}`
};
}
};
<file_sep>/waffle-jest/src/index.ts
import {toBeProperAddress} from './matchers/toBeProperAddress';
import {toBeProperPrivateKey} from './matchers/toBeProperPrivateKey';
import {toBeProperHex} from './matchers/toBeProperHex';
import {bigNumberMatchers} from './matchers/bigNumber';
import {toChangeBalance} from './matchers/toChangeBalance';
import {toChangeBalances} from './matchers/toChangeBalances';
import {toBeReverted} from './matchers/toBeReverted';
import {toBeRevertedWith} from './matchers/toBeRevertedWith';
import {toHaveEmitted} from './matchers/toHaveEmitted/toHaveEmitted';
import {toHaveEmittedWith} from './matchers/toHaveEmitted/toHaveEmittedWith';
import {toBeCalledOnContract} from './matchers/calledOnContract/calledOnContract';
import {toBeCalledOnContractWith} from './matchers/calledOnContract/calledOnContractWith';
export const waffleJest = {
// misc matchers
toBeProperAddress,
toBeProperPrivateKey,
toBeProperHex,
// BigNumber matchers
...bigNumberMatchers,
// balance matchers
toChangeBalance,
toChangeBalances,
// revert matchers
toBeReverted,
toBeRevertedWith,
// emit matchers
toHaveEmitted,
toHaveEmittedWith,
// calledOnContract matchers
toBeCalledOnContract,
toBeCalledOnContractWith
};
<file_sep>/waffle-chai/test/matchers/changeTokenBalance.test.ts
import {expect, AssertionError} from 'chai';
import {MockProvider} from '@ethereum-waffle/provider';
import {BigNumber, Contract, ContractFactory} from 'ethers';
import {MOCK_TOKEN_ABI, MOCK_TOKEN_BYTECODE} from '../contracts/MockToken';
describe('INTEGRATION: changeTokenBalance matcher', () => {
const provider = new MockProvider();
const [sender, receiver] = provider.getWallets();
const contract = new Contract(receiver.address, [], provider);
const factory = new ContractFactory(MOCK_TOKEN_ABI, MOCK_TOKEN_BYTECODE, sender);
let token: Contract;
before(async () => {
token = await factory.deploy('MockToken', 'Mock', 18, 1000000000);
});
describe('Change token balance, one account', () => {
it('Should pass when transferred from is used and expected balance change is equal to an actual', async () => {
await token.approve(receiver.address, 200);
const connectedToken = token.connect(receiver);
await expect(() =>
connectedToken.transferFrom(sender.address, receiver.address, 200)
).to.changeTokenBalance(token, receiver, 200);
});
it('Should pass when expected balance change is passed as string and is equal to an actual', async () => {
await expect(() =>
token.transfer(receiver.address, 200)
).to.changeTokenBalance(token, sender, '-200');
});
it('Should pass when expected balance change is passed as int and is equal to an actual', async () => {
await expect(() =>
token.transfer(receiver.address, 200)
).to.changeTokenBalance(token, receiver, 200);
});
it('Should pass when expected balance change is passed as BN and is equal to an actual', async () => {
await expect(() =>
token.transfer(receiver.address, 200)
).to.changeTokenBalance(token, receiver, BigNumber.from(200));
});
it('Should pass on negative case when expected balance change is not equal to an actual', async () => {
await expect(() =>
token.transfer(receiver.address, 200)
).to.not.changeTokenBalance(token, receiver, BigNumber.from(300));
});
it('Should throw when expected balance change value was different from an actual', async () => {
await expect(
expect(() =>
token.transfer(receiver.address, 200)
).to.changeTokenBalance(token, sender, '-500')
).to.be.eventually.rejectedWith(
AssertionError,
`Expected "${sender.address}" to change balance by -500 wei, but it has changed by -200 wei`
);
});
it('Should throw in negative case when expected balance change value was equal to an actual', async () => {
await expect(
expect(() =>
token.transfer(receiver.address, 200)
).to.not.changeTokenBalance(token, sender, '-200')
).to.be.eventually.rejectedWith(
AssertionError,
`Expected "${sender.address}" to not change balance by -200 wei`
);
});
});
describe('Change token balance, one contract', () => {
it('Should pass when expected balance change is passed as int and is equal to an actual', async () => {
await expect(async () =>
token.transfer(receiver.address, 200)
).to.changeTokenBalance(token, contract, 200);
});
});
});
<file_sep>/waffle-jest/test/setupJest.ts
import {waffleJest} from '../src';
jest.setTimeout(10000);
expect.extend(waffleJest);
<file_sep>/waffle-jest/src/matchers/toBeProperHex.ts
export function toBeProperHex(received: string, length: number) {
const regexp = new RegExp(`^0x[0-9-a-fA-F]{${length}}$`);
const pass = regexp.test(received);
return pass
? {
pass: true,
message: () => `Expected "${received}" not to be a proper hex of length ${length}, but it was`
}
: {
pass: false,
message: () => `Expected "${received}" to be a proper hex of length ${length}`
};
}
<file_sep>/waffle-jest/test/matchers/calledOnContract/calledOnContractValidators.test.ts
import {MockProvider} from '@ethereum-waffle/provider';
import {
constants,
Contract,
ContractFactory,
getDefaultProvider
} from 'ethers';
import {CALLS_ABI, CALLS_BYTECODE} from '../../contracts/Calls';
import {validateMockProvider} from '../../../src/matchers/calledOnContract/calledOnContractValidators';
async function setup() {
const provider = new MockProvider();
const [deployer] = provider.getWallets();
const factory = new ContractFactory(CALLS_ABI, CALLS_BYTECODE, deployer);
return {contract: await factory.deploy()};
}
describe('INTEGRATION: ethCalledValidators', () => {
it('throws type error when the argument is not a contract', async () => {
expect(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
() => expect('calledFunction').toBeCalledOnContract('invalidContract')
).toThrowError('argument must be a contract');
});
it('throws type error when the argument is not a provider', async () => {
const contract = new Contract(
constants.AddressZero,
[],
getDefaultProvider()
);
expect(() =>
expect('calledFunction').toBeCalledOnContract(contract)
).toThrowError(
'calledOnContract matcher requires provider that support call history'
);
});
it('throws type error when the provided function is not a string', async () => {
const {contract} = await setup();
expect(() => expect(12).toBeCalledOnContract(contract)).toThrowError(
'function name must be a string'
);
});
it('throws type error when the provided function is not in the contract', async () => {
const {contract} = await setup();
expect(() =>
expect('notExistingFunction').toBeCalledOnContract(contract)
).toThrowError('function must exist in provided contract');
});
});
describe('UNIT: provider validation', () => {
it('No call history in provider', async () => {
expect(() => validateMockProvider(getDefaultProvider())).toThrowError(
'calledOnContract matcher requires provider that support call history'
);
});
it('Incorrect type of call history in provider', async () => {
const provider = {callHistory: 'invalidType'};
expect(() => validateMockProvider(provider)).toThrowError(
'calledOnContract matcher requires provider that support call history'
);
});
it('Correct type of call history in provider', () => {
const provider = {callHistory: []};
expect(() => validateMockProvider(provider)).not.toThrowError();
});
});
<file_sep>/waffle-chai/test/matchers/changeEtherBalance.test.ts
import {expect, AssertionError} from 'chai';
import {MockProvider} from '@ethereum-waffle/provider';
import {BigNumber, Contract} from 'ethers';
describe('INTEGRATION: changeEtherBalance matcher', () => {
const provider = new MockProvider();
const [sender, receiver] = provider.getWallets();
const contract = new Contract(receiver.address, [], provider);
describe('Transaction Callback', () => {
describe('Change balance, one account', () => {
it('Should pass when expected balance change is passed as string and is equal to an actual', async () => {
await expect(() =>
sender.sendTransaction({
to: receiver.address,
value: 200
})
).to.changeEtherBalance(sender, '-200');
});
it('Should pass when expected balance change is passed as int and is equal to an actual', async () => {
await expect(() =>
sender.sendTransaction({
to: receiver.address,
value: 200
})
).to.changeEtherBalance(receiver, 200);
});
it('Should take into account transaction fee', async () => {
await expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 1,
value: 200
})
).to.changeEtherBalance(sender, -21200, {includeFee: true});
});
it('Should ignore fee if receiver\'s wallet is being checked and includeFee was set', async () => {
await expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 1,
value: 200
})
).to.changeEtherBalance(receiver, 200, {includeFee: true});
});
it('Should take into account transaction fee by default', async () => {
await expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 420,
value: 200
})
).to.changeEtherBalance(sender, -200);
});
it('Should pass when expected balance change is passed as BN and is equal to an actual', async () => {
await expect(() =>
sender.sendTransaction({
to: receiver.address,
value: 200
})
).to.changeEtherBalance(receiver, BigNumber.from(200));
});
it('Should pass on negative case when expected balance change is not equal to an actual', async () => {
await expect(() =>
sender.sendTransaction({
to: receiver.address,
value: 200
})
).to.not.changeEtherBalance(receiver, BigNumber.from(300));
});
it('Should throw when fee was not calculated correctly', async () => {
await expect(
expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 1,
value: 200
})
).to.changeEtherBalance(sender, -200, {includeFee: true})
).to.be.eventually.rejectedWith(
AssertionError,
`Expected "${sender.address}" to change balance by -200 wei, but it has changed by -21200 wei`
);
});
it('Should throw when expected balance change value was different from an actual', async () => {
await expect(
expect(() =>
sender.sendTransaction({
to: receiver.address,
value: 200
})
).to.changeEtherBalance(sender, '-500')
).to.be.eventually.rejectedWith(
AssertionError,
`Expected "${sender.address}" to change balance by -500 wei, but it has changed by -200 wei`
);
});
it('Should throw in negative case when expected balance change value was equal to an actual', async () => {
await expect(
expect(() =>
sender.sendTransaction({
to: receiver.address,
value: 200
})
).to.not.changeEtherBalance(sender, '-200')
).to.be.eventually.rejectedWith(
AssertionError,
`Expected "${sender.address}" to not change balance by -200 wei`
);
});
});
describe('Change balance, one contract', () => {
it('Should pass when expected balance change is passed as int and is equal to an actual', async () => {
await expect(async () =>
sender.sendTransaction({
to: contract.address,
value: 200
})
).to.changeEtherBalance(contract, 200);
});
});
});
describe('Transaction Response', () => {
describe('Change balance, one account', () => {
it('Should pass when expected balance change is passed as string and is equal to an actual', async () => {
await expect(await sender.sendTransaction({
to: receiver.address,
value: 200
})
).to.changeEtherBalance(sender, '-200');
});
it('Should pass when expected balance change is passed as int and is equal to an actual', async () => {
await expect(await sender.sendTransaction({
to: receiver.address,
value: 200
})
).to.changeEtherBalance(receiver, 200);
});
it('Should pass when expected balance change is passed as BN and is equal to an actual', async () => {
await expect(await sender.sendTransaction({
to: receiver.address,
value: 200
})
).to.changeEtherBalance(sender, BigNumber.from(-200));
});
it('Should pass on negative case when expected balance change is not equal to an actual', async () => {
await expect(await sender.sendTransaction({
to: receiver.address,
value: 200
})
).to.not.changeEtherBalance(receiver, BigNumber.from(300));
});
it('Should throw when expected balance change value was different from an actual', async () => {
await expect(
expect(await sender.sendTransaction({
to: receiver.address,
value: 200
})
).to.changeEtherBalance(sender, '-500')
).to.be.eventually.rejectedWith(
AssertionError,
`Expected "${sender.address}" to change balance by -500 wei, but it has changed by -200 wei`
);
});
it('Should throw in negative case when expected balance change value was equal to an actual', async () => {
await expect(
expect(await sender.sendTransaction({
to: receiver.address,
value: 200
})
).to.not.changeEtherBalance(sender, '-200')
).to.be.eventually.rejectedWith(
AssertionError,
`Expected "${sender.address}" to not change balance by -200 wei`
);
});
});
describe('Change balance, one contract', () => {
it('Should pass when expected balance change is passed as int and is equal to an actual', async () => {
await expect(await sender.sendTransaction({
to: contract.address,
value: 200
})
).to.changeEtherBalance(contract, 200);
});
});
});
});
<file_sep>/waffle-jest/src/matchers/calledOnContract/error.ts
export class ProviderWithHistoryExpected extends Error {
constructor() {
super(
'calledOnContract matcher requires provider that support call history'
);
}
}
<file_sep>/waffle-jest/src/matchers/calledOnContract/calledOnContract.ts
import {Contract} from 'ethers';
import {
validateContract,
validateMockProvider,
validateFnName
} from './calledOnContractValidators';
export function toBeCalledOnContract(fnName: string, contract: Contract) {
validateContract(contract);
validateMockProvider(contract.provider);
if (fnName !== undefined) {
validateFnName(fnName, contract);
}
const fnSighash = contract.interface.getSighash(fnName);
const {callHistory} = contract.provider;
const pass = callHistory.some(
(call) =>
call.address === contract.address && call.data.startsWith(fnSighash)
);
return pass
? {
pass: true,
message: () => 'Expected contract function NOT to be called'
}
: {
pass: false,
message: () => 'Expected contract function to be called'
};
}
<file_sep>/waffle-jest/src/matchers/calledOnContract/calledOnContractWith.ts
import {Contract} from 'ethers';
import {
validateContract,
validateMockProvider,
validateFnName
} from './calledOnContractValidators';
export function toBeCalledOnContractWith(
fnName: string,
contract: Contract,
parameters: any[]
) {
validateContract(contract);
validateMockProvider(contract.provider);
validateFnName(fnName, contract);
const funCallData = contract.interface.encodeFunctionData(fnName, parameters);
const {callHistory} = contract.provider;
const pass = callHistory.some(
(call) => call.address === contract.address && call.data === funCallData
);
return pass
? {
pass: true,
message: () => 'Expected contract function with parameters NOT to be called'
}
: {
pass: false,
message: () => 'Expected contract function with parameters to be called'
};
}
<file_sep>/waffle-jest/test/matchers/bigNumber.test.ts
import {BigNumber} from 'ethers';
describe('UNIT: BigNumber matchers', () => {
function checkAll(
actual: number,
expected: number,
test: (
actual: number | string | BigNumber,
expected: number | string | BigNumber
) => void
) {
test(actual, expected);
test(BigNumber.from(actual), expected);
test(BigNumber.from(actual), expected.toString());
test(BigNumber.from(actual), BigNumber.from(expected));
test(actual, BigNumber.from(expected));
test(actual.toString(), BigNumber.from(expected));
}
describe('equal', () => {
it('.toEqBN', () => {
checkAll(10, 10, (a, b) => expect(a).toEqBN(b));
});
it('.not.toEqBN', () => {
checkAll(10, 11, (a, b) => expect(a).not.toEqBN(b));
});
it('throws proper message on error', () => {
expect(() => expect(BigNumber.from(10)).toEqBN(11)).toThrowError(
'Expected "10" to be equal 11'
);
});
});
describe('greater than', () => {
it('.toBeGtBN', () => {
checkAll(10, 9, (a, b) => expect(a).toBeGtBN(b));
});
it('.not.toBeGtBN', () => {
checkAll(10, 10, (a, b) => expect(a).not.toBeGtBN(b));
checkAll(10, 11, (a, b) => expect(a).not.toBeGtBN(b));
});
it('throws proper message on error', () => {
expect(() => expect(BigNumber.from(10)).toBeGtBN(11)).toThrowError(
'Expected "10" to be greater than 11'
);
});
});
describe('less than', () => {
it('.toBeLtBN', () => {
checkAll(10, 11, (a, b) => expect(a).toBeLtBN(b));
});
it('.not.to.be.lt', () => {
checkAll(10, 10, (a, b) => expect(a).not.toBeLtBN(b));
checkAll(10, 9, (a, b) => expect(a).not.toBeLtBN(b));
});
it('throws proper message on error', () => {
expect(() => expect(BigNumber.from(11)).toBeLtBN(10)).toThrowError(
'Expected "11" to be less than 10'
);
});
});
describe('greater than or equal', () => {
it('.toBeGteBN', () => {
checkAll(10, 10, (a, b) => expect(a).toBeGteBN(b));
checkAll(10, 9, (a, b) => expect(a).toBeGteBN(b));
});
it('.not.toBeGteBN', () => {
checkAll(10, 11, (a, b) => expect(a).not.toBeGteBN(b));
});
it('throws proper message on error', () => {
expect(() => expect(BigNumber.from(10)).toBeGteBN(11)).toThrowError(
'Expected "10" to be greater than or equal 11'
);
});
});
describe('less than or equal', () => {
it('.toBeLteBN', () => {
checkAll(10, 10, (a, b) => expect(a).toBeLteBN(b));
checkAll(10, 11, (a, b) => expect(a).toBeLteBN(b));
});
it('.not.toBeLteBN', () => {
checkAll(10, 9, (a, b) => expect(a).not.toBeLteBN(b));
});
it('throws proper message on error', () => {
expect(() => expect(BigNumber.from(11)).toBeLteBN(10)).toThrowError(
'Expected "11" to be less than or equal 10'
);
});
});
});
<file_sep>/waffle-jest/src/matchers/calledOnContract/calledOnContractValidators.ts
import {Contract} from 'ethers';
import {MockProvider} from '@ethereum-waffle/provider';
import {ProviderWithHistoryExpected} from './error';
import {ensure} from './utils';
export function validateContract(contract: any): asserts contract is Contract {
ensure(
contract instanceof Contract,
TypeError,
'argument must be a contract'
);
}
export function validateMockProvider(
provider: any
): asserts provider is MockProvider {
ensure(
!!provider.callHistory && provider.callHistory instanceof Array,
ProviderWithHistoryExpected
);
}
export function validateFnName(
fnName: any,
contract: Contract
): asserts fnName is string {
ensure(
typeof fnName === 'string',
TypeError,
'function name must be a string'
);
function isFunction(name: string) {
try {
return !!contract.interface.getFunction(name);
} catch (e) {
return false;
}
}
ensure(
isFunction(fnName),
TypeError,
'function must exist in provided contract'
);
}
<file_sep>/docs/release-notes/3.2.0.md
* Caching solcjs binaries which allows faster test execution on slow internet and offline
* Remove deployContract's default `gasPrice` and `gasLimit` (use etheres defaults instead)
* New matchers `changeEtherBalance` and `changeEtherBalances` to replaces `changeBalance` and add support for transaction fees by deafult.<file_sep>/waffle-chai/src/matchers/changeEtherBalance.ts
import {BigNumber, BigNumberish, providers} from 'ethers';
import {ensure} from './calledOnContract/utils';
import {Account, getAddressOf} from './misc/account';
import {BalanceChangeOptions} from './misc/balance';
export function supportChangeEtherBalance(Assertion: Chai.AssertionStatic) {
Assertion.addMethod('changeEtherBalance', function (
this: any,
account: Account,
balanceChange: BigNumberish,
options: BalanceChangeOptions
) {
const subject = this._obj;
const derivedPromise = Promise.all([
getBalanceChange(subject, account, options),
getAddressOf(account)
]).then(
([actualChange, address]) => {
this.assert(
actualChange.eq(BigNumber.from(balanceChange)),
`Expected "${address}" to change balance by ${balanceChange} wei, ` +
`but it has changed by ${actualChange} wei`,
`Expected "${address}" to not change balance by ${balanceChange} wei,`,
balanceChange,
actualChange
);
}
);
this.then = derivedPromise.then.bind(derivedPromise);
this.catch = derivedPromise.catch.bind(derivedPromise);
this.promise = derivedPromise;
return this;
});
}
export async function getBalanceChange(
transaction:
| providers.TransactionResponse
| (() => Promise<providers.TransactionResponse> | providers.TransactionResponse),
account: Account,
options?: BalanceChangeOptions
) {
ensure(account.provider !== undefined, TypeError, 'Provider not found');
let txResponse: providers.TransactionResponse;
if (typeof transaction === 'function') {
txResponse = await transaction();
} else {
txResponse = transaction;
}
const txReceipt = await txResponse.wait();
const txBlockNumber = txReceipt.blockNumber;
const balanceAfter = await account.provider.getBalance(getAddressOf(account), txBlockNumber);
const balanceBefore = await account.provider.getBalance(getAddressOf(account), txBlockNumber - 1);
if (options?.includeFee !== true && await getAddressOf(account) === txResponse.from) {
const gasPrice = txResponse.gasPrice;
const gasUsed = txReceipt.gasUsed;
const txFee = gasPrice.mul(gasUsed);
return balanceAfter.add(txFee).sub(balanceBefore);
} else {
return balanceAfter.sub(balanceBefore);
}
}
<file_sep>/waffle-chai/src/matchers/changeTokenBalance.ts
import {BigNumber, BigNumberish, Contract} from 'ethers';
import {Account, getAddressOf} from './misc/account';
export function supportChangeTokenBalance(Assertion: Chai.AssertionStatic) {
Assertion.addMethod('changeTokenBalance', function (
this: any,
token: Contract,
account: Account,
balanceChange: BigNumberish
) {
const subject = this._obj;
const derivedPromise = Promise.all([
getBalanceChange(subject, token, account),
getAddressOf(account)
]).then(
([actualChange, address]) => {
this.assert(
actualChange.eq(BigNumber.from(balanceChange)),
`Expected "${address}" to change balance by ${balanceChange} wei, ` +
`but it has changed by ${actualChange} wei`,
`Expected "${address}" to not change balance by ${balanceChange} wei,`,
balanceChange,
actualChange
);
}
);
this.then = derivedPromise.then.bind(derivedPromise);
this.catch = derivedPromise.catch.bind(derivedPromise);
this.promise = derivedPromise;
return this;
});
}
async function getBalanceChange(
transactionCall: (() => Promise<void> | void),
token: Contract,
account: Account
) {
const balanceBefore: BigNumber = await token.balanceOf(await getAddressOf(account));
await transactionCall();
const balanceAfter: BigNumber = await token.balanceOf(await getAddressOf(account));
return balanceAfter.sub(balanceBefore);
}
<file_sep>/waffle-chai/test/contracts/MockToken.ts
export const MOCK_TOKEN_SOURCE = `
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity =0.7.0;
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'SafeMath: ADD_OVERFLOW');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, 'SafeMath: SUB_UNDERFLOW');
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'SafeMath: MUL_OVERFLOW');
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: DIV_BY_ZERO');
uint256 c = a / b;
return c;
}
}
contract ERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
using SafeMath for uint256;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32
public constant
PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public nonces;
string public name;
string public symbol;
uint8 public decimals;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _totalSupply
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
_init(name);
_mint(msg.sender, _totalSupply);
}
function _init(string memory _name) internal {
uint256 chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(_name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(
address owner,
address spender,
uint256 value
) internal {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(
address from,
address to,
uint256 value
) internal {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool) {
if (allowance[from][msg.sender] != uint256(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, 'Manifold: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'Manifold: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
`;
export const MOCK_TOKEN_ABI = [
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: 'address',
name: 'owner',
type: 'address'
},
{
indexed: true,
internalType: 'address',
name: 'spender',
type: 'address'
},
{
indexed: false,
internalType: 'uint256',
name: 'value',
type: 'uint256'
}
],
name: 'Approval',
type: 'event'
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: 'address',
name: 'from',
type: 'address'
},
{
indexed: true,
internalType: 'address',
name: 'to',
type: 'address'
},
{
indexed: false,
internalType: 'uint256',
name: 'value',
type: 'uint256'
}
],
name: 'Transfer',
type: 'event'
},
{
inputs: [
{
internalType: 'address',
name: 'spender',
type: 'address'
},
{
internalType: 'uint256',
name: 'value',
type: 'uint256'
}
],
name: 'approve',
outputs: [
{
internalType: 'bool',
name: '',
type: 'bool'
}
],
stateMutability: 'nonpayable',
type: 'function'
},
{
inputs: [
{
internalType: 'address',
name: 'owner',
type: 'address'
},
{
internalType: 'address',
name: 'spender',
type: 'address'
},
{
internalType: 'uint256',
name: 'value',
type: 'uint256'
},
{
internalType: 'uint256',
name: 'deadline',
type: 'uint256'
},
{
internalType: 'uint8',
name: 'v',
type: 'uint8'
},
{
internalType: 'bytes32',
name: 'r',
type: 'bytes32'
},
{
internalType: 'bytes32',
name: 's',
type: 'bytes32'
}
],
name: 'permit',
outputs: [],
stateMutability: 'nonpayable',
type: 'function'
},
{
inputs: [
{
internalType: 'address',
name: 'to',
type: 'address'
},
{
internalType: 'uint256',
name: 'value',
type: 'uint256'
}
],
name: 'transfer',
outputs: [
{
internalType: 'bool',
name: '',
type: 'bool'
}
],
stateMutability: 'nonpayable',
type: 'function'
},
{
inputs: [
{
internalType: 'address',
name: 'from',
type: 'address'
},
{
internalType: 'address',
name: 'to',
type: 'address'
},
{
internalType: 'uint256',
name: 'value',
type: 'uint256'
}
],
name: 'transferFrom',
outputs: [
{
internalType: 'bool',
name: '',
type: 'bool'
}
],
stateMutability: 'nonpayable',
type: 'function'
},
{
inputs: [
{
internalType: 'string',
name: '_name',
type: 'string'
},
{
internalType: 'string',
name: '_symbol',
type: 'string'
},
{
internalType: 'uint8',
name: '_decimals',
type: 'uint8'
},
{
internalType: 'uint256',
name: '_totalSupply',
type: 'uint256'
}
],
stateMutability: 'nonpayable',
type: 'constructor'
},
{
inputs: [
{
internalType: 'address',
name: '',
type: 'address'
},
{
internalType: 'address',
name: '',
type: 'address'
}
],
name: 'allowance',
outputs: [
{
internalType: 'uint256',
name: '',
type: 'uint256'
}
],
stateMutability: 'view',
type: 'function'
},
{
inputs: [
{
internalType: 'address',
name: '',
type: 'address'
}
],
name: 'balanceOf',
outputs: [
{
internalType: 'uint256',
name: '',
type: 'uint256'
}
],
stateMutability: 'view',
type: 'function'
},
{
inputs: [],
name: 'decimals',
outputs: [
{
internalType: 'uint8',
name: '',
type: 'uint8'
}
],
stateMutability: 'view',
type: 'function'
},
{
inputs: [],
name: 'DOMAIN_SEPARATOR',
outputs: [
{
internalType: 'bytes32',
name: '',
type: 'bytes32'
}
],
stateMutability: 'view',
type: 'function'
},
{
inputs: [],
name: 'name',
outputs: [
{
internalType: 'string',
name: '',
type: 'string'
}
],
stateMutability: 'view',
type: 'function'
},
{
inputs: [
{
internalType: 'address',
name: '',
type: 'address'
}
],
name: 'nonces',
outputs: [
{
internalType: 'uint256',
name: '',
type: 'uint256'
}
],
stateMutability: 'view',
type: 'function'
},
{
inputs: [],
name: 'PERMIT_TYPEHASH',
outputs: [
{
internalType: 'bytes32',
name: '',
type: 'bytes32'
}
],
stateMutability: 'view',
type: 'function'
},
{
inputs: [],
name: 'symbol',
outputs: [
{
internalType: 'string',
name: '',
type: 'string'
}
],
stateMutability: 'view',
type: 'function'
},
{
inputs: [],
name: 'totalSupply',
outputs: [
{
internalType: 'uint256',
name: '',
type: 'uint256'
}
],
stateMutability: 'view',
type: 'function'
}
];
// eslint-disable-next-line max-len
export const MOCK_TOKEN_BYTECODE = '60806040523480156200001157600080fd5b5060405162000e0638038062000e06833981810160405260808110156200003757600080fd5b81019080805160405193929190846401000000008211156200005857600080<KEY>60002090<KEY>00000000000006044820152905190819003<KEY>b92915050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1<KEY>082311461020f5780637ecebe001461023557<KEY>2<KEY>455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a350505056fea2646970667358221220ee4008f11a81<KEY>38e315bbade1961d608e8328d715c0748f7f0e778e64736f6c63430007000033';
<file_sep>/waffle-jest/src/matchers/toHaveEmitted/toHaveEmittedWith.ts
import {Contract, Transaction, utils} from 'ethers';
import diff from 'jest-diff';
import {filterLogsWithTopics, compareArgs} from './utils';
export async function toHaveEmittedWith(
transaction: Transaction,
contract: Contract,
eventName: string,
expectedArgs: unknown[]
): Promise<{ pass: boolean; message: () => string }> {
const receipt = await contract.provider.getTransactionReceipt(
transaction.hash as string
);
let eventFragment: utils.EventFragment | undefined;
try {
eventFragment = contract.interface.getEvent(eventName);
} catch (e) {
// ignore error
}
// check if event is in the contract ABI
if (eventFragment === undefined) {
return {
pass: false,
message: () =>
`Expected event "${eventName}" to be emitted, but it doesn't exist in the contract. ` +
'Please make sure you\'ve compiled its latest version before running the test.'
};
}
const topic = contract.interface.getEventTopic(eventFragment);
const logs = filterLogsWithTopics(receipt.logs, topic, contract.address);
if (logs.length === 0) {
return {
pass: false,
message: () =>
`Expected event "${eventName}" to be emitted, but it wasn't`
};
}
const results = [];
for (const log of logs) {
try {
const actualArgs = contract.interface.parseLog(log).args;
const pass = compareArgs(actualArgs, expectedArgs);
results.push({
pass,
actualArgs,
expectedArgs
});
} catch {
results.push({pass: false});
}
}
// return early if there is a match for the event we are looking for
for (const res of results) {
if (res.pass === true) {
return {
pass: true,
message: () =>
`Expected specified args to NOT be emitted in any of ${logs.length} emitted "${eventName}" events`
};
}
}
// no match found, so we will return the last negative result w/ a rich diff
const lastResult = results[results.length - 1];
return {
pass: false,
message: () =>
diff(lastResult.expectedArgs, lastResult.actualArgs) ||
'The expected args do not match the received args. No diff is available.'
};
}
<file_sep>/waffle-jest/test/matchers/eventsWithArgs.test.ts
import {BigNumber, Contract, ContractFactory} from 'ethers';
import {MockProvider} from '@ethereum-waffle/provider';
import {EVENTS_ABI, EVENTS_BYTECODE} from '../contracts/Events';
// Note: We make use of Jest Snapshots here because the error output is
// a rich diff with ANSI colors generated by jest-diff and is therefore
// quite large.
describe('INTEGRATION: Events Emitted With Args', () => {
const [wallet] = new MockProvider().getWallets();
let factory: ContractFactory;
let events: Contract;
beforeEach(async () => {
factory = new ContractFactory(EVENTS_ABI, EVENTS_BYTECODE, wallet);
events = await factory.deploy();
});
describe('simple', () => {
it('proper args', async () => {
const tx = await events.emitOne();
await expect(tx).toHaveEmittedWith(events, 'One', [
BigNumber.from(1),
'One',
'0x00cfbbaf7ddb3a1476767101c12a0162e241fbad2a0162e2410cfbbaf7162123'
]);
});
it('not enough args', async () => {
const tx = await events.emitOne();
await expect(
expect(tx).toHaveEmittedWith(events, 'One', [BigNumber.from(1)])
).rejects.toThrowErrorMatchingSnapshot();
// received additional "One" and address '0x...2123'
});
it('too many args', async () => {
const tx = await events.emitOne();
await expect(
expect(tx).toHaveEmittedWith(events, 'One', [1, 2, 3, 4])
).rejects.toThrowErrorMatchingSnapshot();
// received BigNumber, string, and address
});
it('one different arg (integer)', async () => {
const tx = await events.emitOne();
await expect(
expect(tx).toHaveEmittedWith(events, 'One', [
2,
'One',
'0x00cfbbaf7ddb3a1476767101c12a0162e241fbad2a0162e2410cfbbaf7162123'
])
).rejects.toThrowErrorMatchingSnapshot();
// expected 2, received BigNumber(1)
});
it('one different arg (string number)', async () => {
const tx = await events.emitOne();
await expect(
expect(tx).toHaveEmittedWith(events, 'One', [
BigNumber.from(1),
'Two',
'0x00cfbbaf7ddb3a1476767101c12a0162e241fbad2a0162e2410cfbbaf7162123'
])
).rejects.toThrowErrorMatchingSnapshot();
// expected "Two", received "One"
});
it('one different arg (string address)', async () => {
const tx = await events.emitOne();
await expect(
expect(tx).toHaveEmittedWith(events, 'One', [
BigNumber.from(1),
'One',
'0x00cfbbaf7ddb3a1476767101c12a0162e241fbad2a0162e2410cfbbaf7162124'
])
).rejects.toThrowErrorMatchingSnapshot();
// expected '0x...2124', received '0x...2123'
});
});
describe('arrays', () => {
it('BigNumbers and bytes32', async () => {
const tx = await events.emitArrays();
await expect(tx).toHaveEmittedWith(events, 'Arrays', [
[1, 2, 3].map((x) => BigNumber.from(x)),
[
'0x00cfbbaf7ddb3a1476767101c12a0162e241fbad2a0162e2410cfbbaf7162123',
'0x00cfbbaf7ddb3a1476767101c12a0162e241fbad2a0162e2410cfbbaf7162124'
]
]);
});
it('bytes32 ends in different value', async () => {
const tx = await events.emitArrays();
await expect(
expect(tx).toHaveEmittedWith(events, 'Arrays', [
[1, 2, 3].map((x) => BigNumber.from(x)),
[
'0x00cfbbaf7ddb3a1476767101c12a0162e241fbad2a0162e2410cfbbaf7162121',
'0x00cfbbaf7ddb3a1476767101c12a0162e241fbad2a0162e2410cfbbaf7162124'
]
])
).rejects.toThrowErrorMatchingSnapshot();
// expected '0x...2121', received '0x...2123'
});
it('BigNumber received is 1, not 0', async () => {
const tx = await events.emitArrays();
await expect(
expect(tx).toHaveEmittedWith(events, 'Arrays', [
[0, 2, 3].map((x) => BigNumber.from(x)),
[
'0x00cfbbaf7ddb3a1476767101c12a0162e241fbad2a0162e2410cfbbaf7162123',
'0x00cfbbaf7ddb3a1476767101c12a0162e241fbad2a0162e2410cfbbaf7162124'
]
])
).rejects.toThrowErrorMatchingSnapshot();
// expected "0x00", received "0x01"
});
});
describe('multiples same event', () => {
it('with different args', async () => {
const tx = await events.emitOneMultipleTimes();
await expect(tx).toHaveEmittedWith(events, 'One', [
BigNumber.from(1),
'One',
'0x00cfbbaf7ddb3a1476767101c12a0162e241fbad2a0162e2410cfbbaf7162123'
]);
await expect(tx).toHaveEmittedWith(events, 'One', [
BigNumber.from(1),
'DifferentKindOfOne',
'0x0000000000000000000000000000000000000000000000000000000000000001'
]);
});
it('with different args (not found)', async () => {
const tx = await events.emitOneMultipleTimes();
await expect(
expect(tx).toHaveEmittedWith(events, 'One', [1, 2, 3, 4])
).rejects.toThrowErrorMatchingSnapshot();
// received BigNumber(1), "DifferentKindOfOne", "0x...0001"
});
});
});
<file_sep>/waffle-jest/src/types.d.ts
import {BigNumber, Wallet, Contract} from 'ethers'; // eslint-disable-line @typescript-eslint/no-unused-vars
export type Numberish = number | string | BigNumber;
declare global {
namespace jest {
interface Matchers<R> {
// misc matchers
toBeProperAddress(): R;
toBeProperPrivateKey(): R;
toBeProperHex(length: number): R;
// BigNumber matchers
toEqBN(value: Numberish): R;
toBeGtBN(value: Numberish): R;
toBeLtBN(value: Numberish): R;
toBeGteBN(value: Numberish): R;
toBeLteBN(value: Numberish): R;
// balance matchers
toChangeBalance(wallet: Wallet, balanceChange: Numberish): Promise<R>;
toChangeBalances(wallets: Wallet[], balanceChanges: Numberish[]): Promise<R>;
// revert matchers
toBeReverted(): Promise<R>;
toBeRevertedWith(revertReason: string): Promise<R>;
// emit matcher
toHaveEmitted(contract: Contract, eventName: string): Promise<R>;
toHaveEmittedWith(
contract: Contract,
eventName: string,
expectedArgs: any[]
): Promise<R>;
// calledOnContract matchers
toBeCalledOnContract(contract: Contract): R;
toBeCalledOnContractWith(contract: Contract, parameters: any[]): R;
}
}
}
export {};
<file_sep>/docs/release-notes/3.1.1.md
* Remove multiple SPDX licence during flattening
* Allow transaction receipt in balance matchers
* Skip solc download if version is already present
* Add revertsWithReason to mock contract documentation
* Fix broken markdown in waffle-cli readme
<file_sep>/docs/release-notes/3.1.2.md
* Add changeTokenBalance matcher
* Fix staticcall for calls with multiple parameters<file_sep>/waffle-jest/src/matchers/toBeProperAddress.ts
export function toBeProperAddress(received: string) {
const pass = /^0x[0-9-a-fA-F]{40}$/.test(received);
return pass
? {
pass: true,
message: () => `Expected "${received}" not to be a proper address`
}
: {
pass: false,
message: () => `Expected "${received}" to be a proper address`
};
}
<file_sep>/waffle-chai/src/matchers/changeTokenBalances.ts
import {BigNumber, BigNumberish, Contract} from 'ethers';
import {Account, getAddressOf} from './misc/account';
export function supportChangeTokenBalances(Assertion: Chai.AssertionStatic) {
Assertion.addMethod('changeTokenBalances', function (
this: any,
token: Contract,
accounts: Account[],
balanceChanges: BigNumberish[]
) {
const subject = this._obj;
const derivedPromise = Promise.all([
getBalanceChanges(subject, token, accounts),
getAddresses(accounts)
]).then(
([actualChanges, accountAddresses]) => {
this.assert(
actualChanges.every((change, ind) =>
change.eq(BigNumber.from(balanceChanges[ind]))
),
`Expected ${accountAddresses} to change balance by ${balanceChanges} wei, ` +
`but it has changed by ${actualChanges} wei`,
`Expected ${accountAddresses} to not change balance by ${balanceChanges} wei,`,
balanceChanges.map((balanceChange) => balanceChange.toString()),
actualChanges.map((actualChange) => actualChange.toString())
);
}
);
this.then = derivedPromise.then.bind(derivedPromise);
this.catch = derivedPromise.catch.bind(derivedPromise);
this.promise = derivedPromise;
return this;
});
}
function getAddresses(accounts: Account[]) {
return Promise.all(accounts.map((account) => getAddressOf(account)));
}
async function getBalances(token: Contract, accounts: Account[]) {
return Promise.all(
accounts.map(async (account) => {
return token.balanceOf(getAddressOf(account));
})
);
}
async function getBalanceChanges(
transactionCall: (() => Promise<void> | void),
token: Contract,
accounts: Account[]
) {
const balancesBefore = await getBalances(token, accounts);
await transactionCall();
const balancesAfter = await getBalances(token, accounts);
return balancesAfter.map((balance, ind) => balance.sub(balancesBefore[ind]));
}
<file_sep>/waffle-jest/src/matchers/toBeReverted.ts
export async function toBeReverted(promise: Promise<any>) {
try {
await promise;
return {
pass: false,
message: () => 'Expected transaction to be reverted'
};
} catch (error) {
const message =
error instanceof Object && 'message' in error ? error.message : JSON.stringify(error);
const isReverted = message.search('revert') >= 0;
const isThrown = message.search('invalid opcode') >= 0;
const isError = message.search('code=') >= 0;
const pass = isReverted || isThrown || isError;
if (pass) {
return {
pass: true,
message: () => 'Expected transaction NOT to be reverted'
};
} else {
return {
pass: false,
message: () =>
`Expected transaction to be reverted, but other exception was thrown: ${error}`
};
}
}
}
<file_sep>/docs/release-notes/3.1.0.md
* Introduce experimental support for Jest
* Revert breaking change from Wallet to Signer in Fixture
* Export Fixture type
<file_sep>/waffle-compiler/test/utils.ts
import {assert, expect} from 'chai';
import {insert, isDirectory, removeEmptyDirsRecursively} from '../src/utils';
import fs from 'fs-extra';
import * as path from 'path';
describe('UNIT: Utils', () => {
describe('INTEGRATION: isDirectory', () => {
it('valid directory path', () => {
expect(isDirectory('test')).to.be.true;
});
it('file path as directory path', () => {
expect(isDirectory('test/utils.ts')).to.be.false;
});
it('invalid directory path', () => {
expect(isDirectory('123')).to.be.false;
});
});
describe('INTEGRATION: removeEmptyDirsRecursively', () => {
const testDir = path.join(__dirname, 'tmp-dir');
beforeEach(() => {
assert.isFalse(fs.pathExistsSync(testDir), `${path.resolve(testDir)} should be removed before running tests`);
fs.mkdirpSync(testDir);
});
afterEach(() => {
fs.removeSync(testDir);
});
describe('when there are no files in the directory structure', () => {
it('removes an empty directory', () => {
removeEmptyDirsRecursively(testDir);
expect(fs.pathExistsSync(testDir)).to.be.false;
});
it('removes a directory with subdirs', () => {
fs.mkdirpSync(path.join(testDir, 'a/b/c'));
fs.mkdirpSync(path.join(testDir, 'a/d'));
removeEmptyDirsRecursively(testDir);
expect(fs.pathExistsSync(testDir)).to.be.false;
});
});
describe('when there are files in the directory structure', () => {
it('does not remove a non-empty directory', () => {
const file = path.join(testDir, 'file.txt');
fs.writeFileSync(file, '');
removeEmptyDirsRecursively(testDir);
expect(fs.pathExistsSync(file)).to.be.true;
});
it('does not remove a directory with a non-empty subdir', () => {
const subdir = path.join(testDir, 'subdir');
const file = path.join(testDir, 'subdir', 'file.txt');
fs.mkdirpSync(subdir);
fs.writeFileSync(file, '');
removeEmptyDirsRecursively(testDir);
expect(fs.pathExistsSync(file)).to.be.true;
});
it('removes all empty subdirs', () => {
const subdirA = path.join(testDir, 'subdirA');
const subdirB = path.join(testDir, 'subdirB');
const subdirC = path.join(testDir, 'subdirC');
const subdirCD = path.join(testDir, 'subdirC', 'subdirCD');
const fileA = path.join(testDir, 'subdirA', 'fileA.txt');
fs.mkdirpSync(subdirA);
fs.mkdirpSync(subdirB);
fs.mkdirpSync(subdirCD);
fs.writeFileSync(fileA, '');
removeEmptyDirsRecursively(testDir);
expect(fs.pathExistsSync(fileA)).to.be.true;
expect(fs.pathExistsSync(subdirB)).to.be.false;
expect(fs.pathExistsSync(subdirC)).to.be.false;
});
});
});
it('insert pastes string into another string at index', () => {
expect(insert('123789', '456', 3)).to.equal('123456789');
});
});
<file_sep>/waffle-jest/test/matchers/events.test.ts
import {Contract, ContractFactory} from 'ethers';
import {MockProvider} from '@ethereum-waffle/provider';
import {EVENTS_ABI, EVENTS_BYTECODE} from '../contracts/Events';
describe('INTEGRATION: Events Emitted', () => {
const [wallet] = new MockProvider().getWallets();
let factory: ContractFactory;
let events: Contract;
beforeEach(async () => {
factory = new ContractFactory(EVENTS_ABI, EVENTS_BYTECODE, wallet);
events = await factory.deploy();
});
it('Emit one: success', async () => {
const tx = await events.emitOne();
await expect(tx).toHaveEmitted(events, 'One');
});
it('Emit one: fail', async () => {
const tx = await events.emitOne();
await expect(
expect(tx).toHaveEmitted(events, 'Two')
).rejects.toThrowError(
'Expected event "Two" to be emitted, but it wasn\'t'
);
});
it('Emit two: success', async () => {
const tx = await events.emitTwo();
await expect(tx).toHaveEmitted(events, 'Two');
});
it('Emit two: fail', async () => {
const tx = await events.emitTwo();
await expect(
expect(tx).toHaveEmitted(events, 'One')
).rejects.toThrowError(
'Expected event "One" to be emitted, but it wasn\'t'
);
});
it('Do not emit one: fail', async () => {
const tx = await events.emitOne();
await expect(
expect(tx).not.toHaveEmitted(events, 'One')
).rejects.toThrowError(
'Expected event "One" NOT to be emitted, but it was'
);
});
it('Do not emit two: success', async () => {
const tx = await events.emitTwo();
await expect(tx).not.toHaveEmitted(events, 'One');
});
it('Emit non-existent event: fail', async () => {
const tx = await events.emitOne();
await expect(
expect(tx).toHaveEmitted(events, 'Three')
).rejects.toThrowError(
'Expected event "Three" to be emitted, but it doesn\'t exist in the contract. ' +
'Please make sure you\'ve compiled its latest version before running the test.'
);
});
});
<file_sep>/waffle-jest/src/matchers/toHaveEmitted/utils.ts
import {BigNumber, providers} from 'ethers';
export function filterLogsWithTopics(
logs: providers.Log[],
topic: any,
contractAddress: string
) {
return logs
.filter((log) => log.topics.includes(topic))
.filter(
(log) =>
log.address &&
log.address.toLowerCase() === contractAddress.toLowerCase()
);
}
export function compareArgs(actual: any, expected: any): boolean {
// if one is an array but the other is not, then fail
if (
(Array.isArray(actual) && !Array.isArray(expected)) ||
(!Array.isArray(actual) && Array.isArray(expected))
) {
return false;
}
// if they are both arrays recurse
if (Array.isArray(actual) && Array.isArray(expected)) {
if (actual.length !== expected.length) {
return false;
}
for (let i = 0; i < actual.length; i++) {
const result = compareArgs(actual[i], expected[i]);
if (result === false) return false;
}
return true;
}
// if one of them is a string, then do a string compare
const isString = (x: any) => typeof x === 'string';
if (isString(actual) || isString(expected)) {
return actual.toString() === expected.toString();
}
// compare BigNumbers
if (actual instanceof BigNumber && expected instanceof BigNumber) {
return actual.eq(expected);
}
// otherwise direct compare
return actual === expected;
}
<file_sep>/waffle-chai/src/matchers/changeBalances.ts
import {BigNumber, BigNumberish} from 'ethers';
import {getBalanceChanges} from './changeEtherBalances';
import {Account} from './misc/account';
import {getAddresses} from './misc/balance';
export function supportChangeBalances(Assertion: Chai.AssertionStatic) {
Assertion.addMethod('changeBalances', function (
this: any,
accounts: Account[],
balanceChanges: BigNumberish[]
) {
const subject = this._obj;
const derivedPromise = Promise.all([
getBalanceChanges(subject, accounts, {includeFee: true}),
getAddresses(accounts)
]).then(
([actualChanges, accountAddresses]) => {
this.assert(
actualChanges.every((change, ind) =>
change.eq(BigNumber.from(balanceChanges[ind]))
),
`Expected ${accountAddresses} to change balance by ${balanceChanges} wei, ` +
`but it has changed by ${actualChanges} wei`,
`Expected ${accountAddresses} to not change balance by ${balanceChanges} wei,`,
balanceChanges.map((balanceChange) => balanceChange.toString()),
actualChanges.map((actualChange) => actualChange.toString())
);
}
);
this.then = derivedPromise.then.bind(derivedPromise);
this.catch = derivedPromise.catch.bind(derivedPromise);
this.promise = derivedPromise;
return this;
});
}
<file_sep>/waffle-compiler/src/compileSolcjs.ts
import solc from 'solc';
import path from 'path';
import fetch from 'node-fetch';
import {ImportFile} from '@resolver-engine/imports';
import {isDirectory, isFile, removeEmptyDirsRecursively} from './utils';
import {Config} from './config';
import {getCompilerInput} from './compilerInput';
import {findImports} from './findImports';
import mkdirp from 'mkdirp';
import fs from 'fs';
import https from 'https';
const semverRegex = /^\d+\.\d+\.\d+$/;
export function compileSolcjs(config: Config) {
return async function compile(sources: ImportFile[]) {
const solc = await loadCompiler(config);
const input = getCompilerInput(sources, config.compilerOptions, 'Solidity');
const imports = findImports(sources);
const output = solc.compile(input, {imports});
return JSON.parse(output);
};
}
export async function loadCompiler({compilerVersion, cacheDirectory}: Config) {
if (isDefaultVersion(compilerVersion)) {
return solc;
}
if (isDirectory(compilerVersion)) {
return require(path.resolve(compilerVersion));
}
try {
const version = semverRegex.test(compilerVersion)
? await resolveSemverVersion(compilerVersion)
: compilerVersion;
return await loadVersion(version, cacheDirectory);
} catch (e) {
throw new Error(`Error fetching compiler version: ${compilerVersion}.`);
}
}
function isDefaultVersion(version: string) {
return version === 'default' ||
(semverRegex.test(version) && solc.version().startsWith(`${version}+`));
}
async function resolveSemverVersion(version: string) {
const releases = await fetchReleases();
const item: string = releases[version];
return item.substring('soljson-'.length, item.length - '.js'.length);
}
const VERSION_LIST_URL = 'https://solc-bin.ethereum.org/bin/list.json';
let cache: any = undefined;
async function fetchReleases() {
if (!cache) {
const res = await fetch(VERSION_LIST_URL);
const {releases} = await res.json();
cache = releases;
}
return cache;
}
async function loadVersion(version: string, cacheDirectory: string) {
const cachedSolcPath = path.resolve(cacheDirectory, 'solcjs', `${version}.js`);
if (!isFile(cachedSolcPath)) {
await cacheRemoteVersion(version, cacheDirectory);
}
return loadCachedVersion(cachedSolcPath);
}
async function cacheRemoteVersion(version: string, cacheDirectory: string) {
const solcCacheDirectory = path.resolve(cacheDirectory, 'solcjs');
if (!isDirectory(solcCacheDirectory)) {
mkdirp.sync(solcCacheDirectory);
}
const filePath = path.join(solcCacheDirectory, `${version}.js`);
const file = fs.createWriteStream(filePath);
const url = `https://solc-bin.ethereum.org/bin/soljson-${version}.js`;
await new Promise<void>((resolve, reject) => {
https.get(url, (response) => {
response.pipe(file);
file.on('finish', () => {
file.close();
resolve();
});
}).on('error', (error) => {
try {
fs.unlinkSync(filePath);
removeEmptyDirsRecursively(path.resolve(cacheDirectory));
} finally {
reject(error);
}
});
});
}
function loadCachedVersion(cachedVersionPath: string) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const solcjs = require(cachedVersionPath);
return solc.setupMethods(solcjs);
}
<file_sep>/waffle-compiler/src/shims/solc.d.ts
declare module 'solc' {
export interface SolcCompiler {
compile(sources: string, findImports: (...args: any[]) => any): any;
}
export function compile(sources: string, findImports: (...args: any[]) => any): any
export function setupMethods(solcjs: any): SolcCompiler
export function loadRemoteVersion(
version: string,
callback: (err?: Error, solc?: SolcCompiler) => void
): void;
export function version(): string;
}
<file_sep>/waffle-jest/src/matchers/toHaveEmitted/toHaveEmitted.ts
import {Contract, Transaction, utils} from 'ethers';
import {filterLogsWithTopics} from './utils';
export async function toHaveEmitted(
transaction: Transaction,
contract: Contract,
eventName: string
) {
const receipt = await contract.provider.getTransactionReceipt(
transaction.hash as string
);
let eventFragment: utils.EventFragment | undefined;
try {
eventFragment = contract.interface.getEvent(eventName);
} catch (e) {
// ignore error
}
// check if event is in the contract ABI
if (eventFragment === undefined) {
return {
pass: false,
message: () =>
`Expected event "${eventName}" to be emitted, but it doesn't exist in the contract. ` +
'Please make sure you\'ve compiled its latest version before running the test.'
};
}
const topic = contract.interface.getEventTopic(eventFragment);
const logs = filterLogsWithTopics(receipt.logs, topic, contract.address);
const pass = logs.length > 0;
if (pass) {
return {
pass: true,
message: () =>
`Expected event "${eventName}" NOT to be emitted, but it was`
};
} else {
return {
pass: false,
message: () =>
`Expected event "${eventName}" to be emitted, but it wasn't`
};
}
}
<file_sep>/waffle-jest/src/matchers/toChangeBalance.ts
import {Wallet, BigNumber} from 'ethers';
import {Numberish} from '../types';
export async function toChangeBalance(
transactionCallback: () => Promise<any>,
wallet: Wallet,
balanceChange: Numberish
) {
if (typeof transactionCallback !== 'function') {
throw new Error(
'Expect subject should be a callback returning a Promise\n' +
'e.g.: await expect(() => wallet.send({to: \'0xb\', value: 200})).toChangeBalance(\'0xa\', -200)'
);
}
const balanceBefore = await wallet.getBalance();
await transactionCallback();
const balanceAfter = await wallet.getBalance();
const actualChange = balanceAfter.sub(balanceBefore);
const pass = actualChange.eq(BigNumber.from(balanceChange));
if (pass) {
return {
pass: true,
message: () =>
`Expected "${wallet.address}" to not change balance by ${balanceChange} wei,`
};
} else {
return {
pass: false,
message: () =>
`Expected "${wallet.address}" to change balance by ${balanceChange} wei, ` +
`but it has changed by ${actualChange} wei`
};
}
}
<file_sep>/waffle-jest/test/matchers/reverted.test.ts
import {MockProvider} from '@ethereum-waffle/provider';
import {Contract, ContractFactory} from 'ethers';
import {MATCHERS_ABI, MATCHERS_BYTECODE} from '../contracts/Matchers';
describe('INTEGRATION: Matchers: reverted', () => {
const [wallet] = new MockProvider().getWallets();
let matchers: Contract;
beforeEach(async () => {
const factory = new ContractFactory(
MATCHERS_ABI,
MATCHERS_BYTECODE,
wallet
);
matchers = await factory.deploy();
});
it('Throw: success', async () => {
await expect(matchers.doThrow()).toBeReverted();
});
it('Not to revert: success', async () => {
await expect(matchers.doNothing()).not.toBeReverted();
});
it('Revert with modification: success', async () => {
await expect(matchers.doRevertAndModify()).toBeReverted();
});
it('ThrowAndModify: success', async () => {
await expect(matchers.doThrowAndModify()).toBeReverted();
});
it('Revert: success', async () => {
await expect(matchers.doRevert()).toBeReverted();
});
it('Revert: fail no exception', async () => {
await expect(
expect(matchers.doNothing()).toBeReverted()
).rejects.toThrowError('Expected transaction to be reverted');
});
it('Not to revert: fail', async () => {
await expect(
expect(matchers.doThrow()).not.toBeReverted()
).rejects.toThrowError('Expected transaction NOT to be reverted');
});
it('Revert: fail, random exception', async () => {
await expect(Promise.reject('Always reject')).not.toBeReverted();
});
it('Not to revert: fail, random exception', async () => {
await expect(
expect(Promise.reject('Always reject')).toBeReverted()
).rejects.toThrowError(
'Expected transaction to be reverted, but other exception was thrown: Always reject'
);
});
});
describe('INTEGRATION: Matchers: revertedWith', () => {
const [wallet] = new MockProvider().getWallets();
let matchers: Contract;
beforeEach(async () => {
const factory = new ContractFactory(
MATCHERS_ABI,
MATCHERS_BYTECODE,
wallet
);
matchers = await factory.deploy();
});
it('Throw: success', async () => {
await expect(matchers.doThrow()).toBeRevertedWith('');
});
it('Not to revert: success', async () => {
await expect(matchers.doNothing()).not.toBeRevertedWith('');
});
it('Revert with modification: success', async () => {
await expect(matchers.doRevertAndModify()).toBeRevertedWith('Revert cause');
});
it('ThrowAndModify: success', async () => {
await expect(matchers.doThrowAndModify()).toBeRevertedWith('');
});
it('Revert: success', async () => {
await expect(matchers.doRevert()).toBeRevertedWith('Revert cause');
});
it('Revert: fail when different message was thrown', async () => {
await expect(
expect(matchers.doRevert()).toBeRevertedWith('different message')
).rejects.toThrowError(
'Expected transaction to be reverted with different message, ' +
'but other exception was thrown: RuntimeError: VM Exception while processing transaction: revert Revert cause'
);
});
it('Revert: fail no exception', async () => {
await expect(
expect(matchers.doNothing()).toBeRevertedWith('')
).rejects.toThrowError('Expected transaction to be reverted');
});
it('Require: success', async () => {
await expect(matchers.doRequireFail()).toBeRevertedWith('Require cause');
});
it('Require: fail when no exception was thrown', async () => {
await expect(
expect(matchers.doRequireSuccess()).toBeRevertedWith('Never to be seen')
).rejects.toThrowError('Expected transaction to be reverted');
});
it('Require: fail when different message', async () => {
await expect(
expect(matchers.doRequireFail()).toBeRevertedWith('Different message')
).rejects.toThrowError(
'Expected transaction to be reverted with Different message, ' +
'but other exception was thrown: RuntimeError: VM Exception while processing transaction: revert Require cause'
);
});
it('Not to revert: fail', async () => {
await expect(
expect(matchers.doThrow()).not.toBeRevertedWith('')
).rejects.toThrowError('Expected transaction NOT to be reverted with ');
});
it('Revert: fail when same message was thrown', async () => {
await expect(matchers.doRevert()).toBeRevertedWith('Revert cause');
});
it('Not to revert: success when different message was thrown', async () => {
await expect(matchers.doRevert()).not.toBeRevertedWith('different message');
});
it('Revert: fail, random exception', async () => {
await expect(Promise.reject('Always reject')).not.toBeRevertedWith(
'Always reject'
);
});
it('Not to revert: fail, random exception', async () => {
await expect(
expect(Promise.reject('Always reject')).toBeRevertedWith('Always reject')
).rejects.toThrowError(
'Expected transaction to be reverted with Always reject, but other exception was thrown: Always reject'
);
});
});
<file_sep>/waffle-provider/src/fixtures.ts
import {providers, Wallet} from 'ethers';
import {MockProvider} from './MockProvider';
export type Fixture<T> = (wallets: Wallet[], provider: MockProvider) => Promise<T>;
interface Snapshot<T> {
fixture: Fixture<T>;
data: T;
id: string;
provider: providers.Web3Provider;
wallets: Wallet[];
}
export const loadFixture = createFixtureLoader();
export function createFixtureLoader(overrideWallets?: Wallet[], overrideProvider?: MockProvider) {
const snapshots: Snapshot<any>[] = [];
return async function load<T>(fixture: Fixture<T>): Promise<T> {
const snapshot = snapshots.find((snapshot) => snapshot.fixture === fixture);
if (snapshot) {
await snapshot.provider.send('evm_revert', [snapshot.id]);
snapshot.id = await snapshot.provider.send('evm_snapshot', []);
return snapshot.data;
} else {
const provider = overrideProvider ?? new MockProvider();
const wallets = overrideWallets ?? provider.getWallets();
const data = await fixture(wallets, provider);
const id = await provider.send('evm_snapshot', []);
snapshots.push({fixture, data, id, provider, wallets});
return data;
}
};
}
<file_sep>/docs/release-notes/3.2.1.md
* Make solcjs compilation work with versions >=0.7.2
<file_sep>/waffle-chai/test/matchers/changeTokenBalances.test.ts
import {expect, AssertionError} from 'chai';
import {MockProvider} from '@ethereum-waffle/provider';
import {Contract, ContractFactory} from 'ethers';
import {MOCK_TOKEN_ABI, MOCK_TOKEN_BYTECODE} from '../contracts/MockToken';
describe('INTEGRATION: changeTokenBalances matcher', () => {
const provider = new MockProvider();
const [sender, receiver] = provider.getWallets();
const factory = new ContractFactory(MOCK_TOKEN_ABI, MOCK_TOKEN_BYTECODE, sender);
let token: Contract;
before(async () => {
token = await factory.deploy('MockToken', 'Mock', 18, 1000000000);
});
describe('Change token balance, multiple accounts', () => {
it('Should pass when all expected balance changes are equal to actual values', async () => {
await expect(() =>
token.transfer(receiver.address, 200)
).to.changeTokenBalances(token, [sender, receiver], ['-200', 200]);
});
it('Should pass when negated and numbers don\'t match', async () => {
await expect(() =>
token.transfer(receiver.address, 200)
).to.not.changeTokenBalances(token, [sender, receiver], [-201, 200]);
await expect(() =>
token.transfer(receiver.address, 200)
).to.not.changeTokenBalances(token, [sender, receiver], [-200, 201]);
});
it('Should throw when expected balance change value was different from an actual for any wallet', async () => {
await expect(
expect(() =>
token.transfer(receiver.address, 200)
).to.changeTokenBalances(token, [sender, receiver], [-200, 201])
).to.be.eventually.rejectedWith(
AssertionError,
'Expected 0x17ec8597ff92C3F44523bDc65BF0f1bE632917ff,0x63FC2aD3d021a4D7e64323529a55a9442C444dA0 ' +
'to change balance by -200,201 wei, but it has changed by -200,200 wei'
);
await expect(
expect(() =>
token.transfer(receiver.address, 200)
).to.changeTokenBalances(token, [sender, receiver], [-201, 200])
).to.be.eventually.rejectedWith(
AssertionError,
'Expected 0x17ec8597ff92C3F44523bDc65BF0f1bE632917ff,0x63FC2aD3d021a4D7e64323529a55a9442C444dA0 ' +
'to change balance by -201,200 wei, but it has changed by -200,200 wei'
);
});
it('Should throw in negative case when expected balance changes value were equal to an actual', async () => {
await expect(
expect(() =>
token.transfer(receiver.address, 200)
).to.not.changeTokenBalances(token, [sender, receiver], [-200, 200])
).to.be.eventually.rejectedWith(
AssertionError,
'Expected 0x17ec8597ff92C3F44523bDc65BF0f1bE632917ff,0x63FC2aD3d021a4D7e64323529a55a9442C444dA0 ' +
'to not change balance by -200,200 wei'
);
});
});
});
<file_sep>/waffle-compiler/src/utils.ts
import fs from 'fs';
import path from 'path';
import {Config} from './config';
export const readFileContent = (path: string): string =>
fs.readFileSync(path).toString();
export const isFile = (filePath: string) =>
fs.existsSync(filePath) && fs.lstatSync(filePath).isFile();
export const isDirectory = (directoryPath: string) =>
fs.existsSync(path.resolve(directoryPath)) &&
fs.statSync(path.resolve(directoryPath)).isDirectory();
export const getExtensionForCompilerType = (config: Config) => {
return config.compilerType === 'dockerized-vyper' ? '.vy' : '.sol';
};
export const insert = (source: string, insertedValue: string, index: number) =>
`${source.slice(0, index)}${insertedValue}${source.slice(index)}`;
export const removeEmptyDirsRecursively = (directoryPath: string) => {
if (!isDirectory(directoryPath)) {
return;
}
let files = fs.readdirSync(directoryPath);
if (files.length > 0) {
files.forEach((file) => {
const filePath = path.join(directoryPath, file);
removeEmptyDirsRecursively(filePath);
});
// Re-evaluate files as after deleting a subdirectory we may have parent directory empty now
files = fs.readdirSync(directoryPath);
}
if (files.length === 0) {
fs.rmdirSync(directoryPath);
}
};
<file_sep>/waffle-jest/test/matchers/balance.test.ts
import {MockProvider} from '@ethereum-waffle/provider';
import {BigNumber} from 'ethers';
describe('INTEGRATION: Balance observers', () => {
const [sender, receiver] = new MockProvider().getWallets();
describe('Change balance, one account', () => {
it('Should pass when expected balance change is passed as string and is equal to an actual', async () => {
await expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 0,
value: 200
})
).toChangeBalance(sender, '-200');
});
it('Should pass when expected balance change is passed as int and is equal to an actual', async () => {
await expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 0,
value: 200
})
).toChangeBalance(receiver, 200);
});
it('Should pass when expected balance change is passed as BN and is equal to an actual', async () => {
await expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 0,
value: 200
})
).toChangeBalance(receiver, BigNumber.from(200));
});
it('Should pass on negative case when expected balance change is not equal to an actual', async () => {
await expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 0,
value: 200
})
).not.toChangeBalance(receiver, BigNumber.from(300));
});
it('Should throw when expected balance change value was different from an actual', async () => {
await expect(
expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 0,
value: 200
})
).toChangeBalance(sender, '-500')
).rejects.toThrowError(
`Expected "${sender.address}" to change balance by -500 wei, but it has changed by -200 wei`
);
});
it('Should throw in negative case when expected balance change value was equal to an actual', async () => {
await expect(
expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 0,
value: 200
})
).not.toChangeBalance(sender, '-200')
).rejects.toThrowError(
`Expected "${sender.address}" to not change balance by -200 wei`
);
});
it('Should throw when not a callback is passed to expect', async () => {
await expect(() =>
expect(1).toChangeBalance(sender, '-200')
).rejects.toThrowError(
'Expect subject should be a callback returning a Promise\n' +
'e.g.: await expect(() => wallet.send({to: \'0xb\', value: 200})).toChangeBalance(\'0xa\', -200)'
);
});
});
describe('Change balance, multiple accounts', () => {
it('Should pass when all expected balance changes are equal to actual values', async () => {
await expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 0,
value: 200
})
).toChangeBalances([sender, receiver], ['-200', 200]);
});
it('Should pass when negated and numbers don\'t match', async () => {
await expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 0,
value: 200
})
).not.toChangeBalances([sender, receiver], [-201, 200]);
await expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 0,
value: 200
})
).not.toChangeBalances([sender, receiver], [-200, 201]);
});
it('Should throw when expected balance change value was different from an actual for any wallet', async () => {
await expect(
expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 0,
value: 200
})
).toChangeBalances([sender, receiver], [-200, 201])
).rejects.toThrowError(
'Expected 0x17ec8597ff92C3F44523bDc65BF0f1bE632917ff,0x63FC2aD3d021a4D7e64323529a55a9442C444dA0 ' +
'to change balance by -200,201 wei, but it has changed by -200,200 wei'
);
await expect(
expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 0,
value: 200
})
).toChangeBalances([sender, receiver], [-201, 200])
).rejects.toThrowError(
'Expected 0x17ec8597ff92C3F44523bDc65BF0f1bE632917ff,0x63FC2aD3d021a4D7e64323529a55a9442C444dA0 ' +
'to change balance by -201,200 wei, but it has changed by -200,200 wei'
);
});
it('Should throw in negative case when expected balance changes value were equal to an actual', async () => {
await expect(
expect(() =>
sender.sendTransaction({
to: receiver.address,
gasPrice: 0,
value: 200
})
).not.toChangeBalances([sender, receiver], [-200, 200])
).rejects.toThrowError(
'Expected 0x17ec8597ff92C3F44523bDc65BF0f1bE632917ff,0x63FC2aD3d021a4D7e64323529a55a9442C444dA0 ' +
'to not change balance by -200,200 wei'
);
});
it('Should throw when not a callback is passed to expect', async () => {
expect(() =>
expect(
sender.sendTransaction({
to: receiver.address,
gasPrice: 0,
value: 200
})
).toChangeBalances([sender, receiver], ['-200', 200])
).rejects.toThrowError(
/* eslint-disable max-len */
'Expect subject should be a callback returning the Promise' +
'e.g.: await expect(() => wallet.send({to: \'0xb\', value: 200})).to.changeBalances([\'0xa\', \'0xb\'], [-200, 200])'
/* eslint-enable max-len */
);
});
});
});
<file_sep>/waffle-chai/src/matchers/changeEtherBalances.ts
import {BigNumber, BigNumberish, providers} from 'ethers';
import {getAddressOf, Account} from './misc/account';
import {BalanceChangeOptions, getAddresses, getBalances} from './misc/balance';
export function supportChangeEtherBalances(Assertion: Chai.AssertionStatic) {
Assertion.addMethod('changeEtherBalances', function (
this: any,
accounts: Account[],
balanceChanges: BigNumberish[],
options: BalanceChangeOptions
) {
const subject = this._obj;
const derivedPromise = Promise.all([
getBalanceChanges(subject, accounts, options),
getAddresses(accounts)
]).then(
([actualChanges, accountAddresses]) => {
this.assert(
actualChanges.every((change, ind) =>
change.eq(BigNumber.from(balanceChanges[ind]))
),
`Expected ${accountAddresses} to change balance by ${balanceChanges} wei, ` +
`but it has changed by ${actualChanges} wei`,
`Expected ${accountAddresses} to not change balance by ${balanceChanges} wei,`,
balanceChanges.map((balanceChange) => balanceChange.toString()),
actualChanges.map((actualChange) => actualChange.toString())
);
}
);
this.then = derivedPromise.then.bind(derivedPromise);
this.catch = derivedPromise.catch.bind(derivedPromise);
this.promise = derivedPromise;
return this;
});
}
export async function getBalanceChanges(
transaction:
| providers.TransactionResponse
| (() => Promise<providers.TransactionResponse> | providers.TransactionResponse),
accounts: Account[],
options: BalanceChangeOptions
) {
let txResponse: providers.TransactionResponse;
if (typeof transaction === 'function') {
txResponse = await transaction();
} else {
txResponse = transaction;
}
const txReceipt = await txResponse.wait();
const txBlockNumber = txReceipt.blockNumber;
const balancesAfter = await getBalances(accounts, txBlockNumber);
const balancesBefore = await getBalances(accounts, txBlockNumber - 1);
const txFees = await getTxFees(accounts, txResponse, options);
return balancesAfter.map((balance, ind) => balance.add(txFees[ind]).sub(balancesBefore[ind]));
}
async function getTxFees(
accounts: Account[],
txResponse: providers.TransactionResponse,
options: BalanceChangeOptions
) {
return Promise.all(
accounts.map(async (account) => {
if (options?.includeFee !== true && await getAddressOf(account) === txResponse.from) {
const txReceipt = await txResponse.wait();
const gasPrice = txResponse.gasPrice;
const gasUsed = txReceipt.gasUsed;
const txFee = gasPrice.mul(gasUsed);
return txFee;
}
return 0;
})
);
}
<file_sep>/waffle-jest/src/matchers/toBeProperPrivateKey.ts
export function toBeProperPrivateKey(received: string) {
const pass = /^0x[0-9-a-fA-F]{64}$/.test(received);
return pass
? {
pass: true,
message: () => `Expected "${received}" not to be a proper private key`
}
: {
pass: false,
message: () => `Expected "${received}" to be a proper private key`
};
}
<file_sep>/waffle-jest/src/matchers/toChangeBalances.ts
import {Wallet, BigNumber} from 'ethers';
import {Numberish} from '../types';
export async function toChangeBalances(
transactionCallback: () => Promise<any>,
wallets: Wallet[],
balanceChanges: Numberish[]
) {
if (typeof transactionCallback !== 'function') {
/* eslint-disable max-len */
throw new Error(
'Expect subject should be a callback returning the Promise' +
'e.g.: await expect(() => wallet.send({to: \'0xb\', value: 200})).to.changeBalances([\'0xa\', \'0xb\'], [-200, 200])'
);
/* eslint-enable max-len */
}
const balancesBefore = await Promise.all(
wallets.map((wallet) => wallet.getBalance())
);
await transactionCallback();
const balancesAfter = await Promise.all(
wallets.map((wallet) => wallet.getBalance())
);
const actualChanges = balancesAfter.map((balance, ind) =>
balance.sub(balancesBefore[ind])
);
const pass = actualChanges.every((change, ind) =>
change.eq(BigNumber.from(balanceChanges[ind]))
);
const walletsAddresses = wallets.map((wallet) => wallet.address);
if (pass) {
return {
pass: true,
message: () =>
`Expected ${walletsAddresses} to not change balance by ${balanceChanges} wei,`
};
} else {
return {
pass: false,
message: () =>
`Expected ${walletsAddresses} to change balance by ${balanceChanges} wei, ` +
`but it has changed by ${actualChanges} wei`
};
}
}
|
26d485ab8c75ac43e54fd2d168be8b7fc78388ed
|
[
"Markdown",
"TypeScript"
] | 43
|
TypeScript
|
p-sad/Waffle
|
77b35b1a38044de3995cf1d9e85ca7ee538b8420
|
4dd542fa3a1e8c9d92d803667a2cada847b4d912
|
refs/heads/master
|
<file_sep>from .parser import ParserMixin
<file_sep>import os
from .qvlibrary import QvLibrary
from .qvnote import QvNote
from .qvnotebook import QvNotebook
from ..utils import is_qvlibrary, is_qvnote, is_qvnotebook
class QvFactory(object):
@staticmethod
def create(filename):
path = os.path.join(os.getcwd(), filename)
if is_qvnote(filename):
return QvNote(path)
elif is_qvnotebook(filename):
return QvNotebook(path)
elif is_qvlibrary(filename):
return QvLibrary(path)
else:
raise Exception('not support path: %s' % filename)
<file_sep>import os
def _get_ext(filename):
filename = os.path.normpath(filename)
ext = os.path.splitext(filename)[1]
return ext
def is_qvnote(filename):
ext = _get_ext(filename)
return ext == '.qvnote'
def is_qvnotebook(filename):
ext = _get_ext(filename)
return ext == '.qvnotebook'
def is_qvlibrary(filename):
ext = _get_ext(filename)
return ext == '.qvlibrary'
<file_sep>import json
import os
import re
from datetime import datetime
import markdown
import pendulum
import pymdownx.superfences
from ..mixin import ParserMixin
from ..objects import QV_TYPES
class QvNote(ParserMixin):
type = QV_TYPES.NOTE
def __init__(self, path, parent=None):
self._parent = parent
self._path = path
with open(os.path.join(self._path, 'meta.json'), encoding='UTF-8') as f:
data = json.load(f)
self._meta = QvNoteMeta(**data)
with open(os.path.join(self._path, 'content.json'), encoding='UTF-8') as f:
data = json.load(f)
self._content = QvNoteContent(**data)
self._resources = []
resource_dir = os.path.join(self._path, 'resources')
if os.path.exists(resource_dir):
for resource_path in os.listdir(resource_dir):
self._resources.append(QvNoteResource(os.path.join(resource_dir, resource_path)))
@property
def parent(self):
return self._parent
@property
def name(self):
return self._meta.title if self._meta else ''
@property
def filename(self):
return self.name.replace(' ', '_') + '.html'
@property
def uuid(self):
return self._meta.uuid if self._meta else ''
@property
def html(self):
return self._content.html if self._content else ''
@property
def tags(self):
return self._meta.tags if self._meta else []
@property
def create_datetime(self):
return pendulum.from_timestamp(self._meta.created_at, tz='Asia/Shanghai') if self._meta else datetime.min
@property
def update_datetime(self):
return pendulum.from_timestamp(self._meta.updated_at, tz='Asia/Shanghai') if self._meta else datetime.min
@property
def resources(self):
return self._resources
def get_url(self, root='..'):
return os.path.join(root, self.parent.filename, self.filename)
def parse(self, template, output, classes=None, resources_url=None, write_file_func=None):
# parse html
html = self.html
html = self.convert_resource_url(html, resources_url if resources_url else '../resources')
html = self.convert_note_url(html)
html = self.add_html_tag_classes(html, classes)
prev_note = self.get_prev_note()
next_note = self.get_next_note()
navigator = {}
if prev_note:
navigator['prev'] = {
'name': prev_note.name,
'url' : prev_note.get_url(),
}
if next_note:
navigator['next'] = {
'name': next_note.name,
'url' : next_note.get_url(),
}
context = {
'ins' : self,
'title' : self.name,
'content' : html,
'navigator': navigator,
}
# export html file
output = self.get_output_dir(output)
write_file_func = write_file_func or self.write_file_func
write_file_func(template, output, self.filename, context, resources=self.resources)
def convert_resource_url(self, data, resource_url):
return data.replace('quiver-image-url', resource_url)
def convert_note_url(self, data):
def repl(match):
uuid = match.group(1)
qvnote = self.parent.parent.get_qvnote(uuid)
return qvnote.get_url()
p = re.compile(r'quiver-note-url/(\w{8}(?:-\w{4}){3}-\w{12})')
return p.sub(repl, data)
def add_html_tag_classes(self, html, classes):
classes = classes or {}
for key, value in classes.items():
html = html.replace('<{}>'.format(key), '<{} class="{}">'.format(key, value))
return html
def get_prev_note(self):
if self.parent.qvnotes.index(self) == 0:
return None
try:
return self.parent.qvnotes[self.parent.qvnotes.index(self) - 1]
except ValueError:
return None
except IndexError:
return None
def get_next_note(self):
try:
return self.parent.qvnotes[self.parent.qvnotes.index(self) + 1]
except ValueError:
return None
except IndexError:
return None
class QvNoteMeta(object):
def __init__(self, **kwargs):
self.created_at = kwargs.get('created_at', None)
self.tags = kwargs.get('tags', [])
self.title = kwargs.get('title', None)
self.updated_at = kwargs.get('updated_at', None)
self.uuid = kwargs.get('uuid', None)
def __repr__(self):
return json.dumps(self.__dict__)
class QvNoteContent(object):
def __init__(self, **kwargs):
self.title = kwargs.get('title', None)
self.cells = kwargs.get('cells', [])
def __repr__(self):
return json.dumps(self.__dict__)
@property
def html(self):
html = ''
for cell in self.cells:
html += getattr(self, 'parse_' + cell['type'])(cell)
return html
def parse_text(self, cell):
data = cell['data']
return "<div class='cell cell-text'>%s</div>" % data
def parse_code(self, cell):
data = '```{}\n{}\n```'.format(cell['language'], cell['data'])
return "<div class='cell cell-code'>%s</div>" % (self._markdown_to_html(data))
def parse_markdown(self, cell):
return "<div class='cell cell-markdown'>%s</div>" % self._markdown_to_html(cell['data'])
def parse_latex(self, cell):
return "<div class='cell cell-latex'>%s</div>" % self._markdown_to_html(cell['data'])
def parse_diagram(self, cell):
data = '```{}\n{}\n```'.format(cell['diagramType'], cell['data'])
return "<div class='cell cell-diagram'>%s</div>" % self._markdown_to_html(data)
def _markdown_to_html(self, data):
data = markdown.markdown(
data,
output_format='html5',
extensions=[
'pymdownx.extra',
'pymdownx.highlight',
'pymdownx.arithmatex',
'pymdownx.tilde',
'pymdownx.tasklist',
'pymdownx.magiclink',
'pymdownx.superfences',
'nl2br',
],
extension_configs={
'pymdownx.highlight': {
'noclasses' : True,
'pygments_style': 'github',
},
"pymdownx.superfences": {
"custom_fences": [
{
'name' : 'flow',
'class' : 'uml-flowchart',
'format': pymdownx.superfences.fence_code_format
},
{
'name' : 'sequence',
'class' : 'uml-sequence-diagram',
'format': pymdownx.superfences.fence_code_format
}
]
}
}
)
return data
class QvNoteResource(object):
def __init__(self, path):
self.path = path
def __repr__(self):
return json.dumps(self.__dict__)
<file_sep>from enum import IntEnum
class QV_TYPES(IntEnum):
LIBRARY = 1
NOTEBOOK = 2
NOTE = 3
<file_sep>appdirs==1.4.3
Markdown==2.6.8
markdown2==2.3.4
packaging==16.8
Pygments==2.2.0
pygments-style-github==0.4
pymdown-extensions==6.0
pyparsing==2.2.0
six==1.10.0
Jinja2==2.9.6
<file_sep>import os
from abc import ABCMeta, abstractmethod
from shutil import copy2
class ParserMixin(metaclass=ABCMeta):
@abstractmethod
def parse(self, template, output, classes=None, resources_url=None, write_file_func=None):
pass
def write_file_func(self, template, output, filename, context, resources=None):
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader(os.path.dirname(template)))
env.get_template(os.path.basename(template)).stream(context).dump(os.path.join(output, filename))
# export resources
if resources:
resources_dir = os.path.join(os.path.dirname(output), 'resources')
os.makedirs(resources_dir, exist_ok=True)
for resource in resources:
copy2(resource.path, resources_dir)
def get_output_dir(self, *args):
output_dir = os.getcwd()
for arg in args:
output_dir = os.path.join(output_dir, arg.replace(' ', '_'))
os.makedirs(output_dir, exist_ok=True)
return output_dir
<file_sep>import json
import os
from .qvnote import QvNote
from ..mixin import ParserMixin
from ..objects import QV_TYPES
from ..utils import is_qvnote
class QvNotebook(ParserMixin):
type = QV_TYPES.NOTEBOOK
def __init__(self, path, parent=None):
self._parent = parent
self._path = path
self._qvnotes = []
with open(os.path.join(self._path, 'meta.json'), encoding='UTF-8') as f:
data = json.load(f)
self._meta = QvNotebookMeta(**data)
for filename in os.listdir(self._path):
if not is_qvnote(filename):
continue
self._qvnotes.append(QvNote(os.path.join(self._path, filename), parent=self))
self._qvnotes.sort(key=lambda v: v.create_datetime)
@property
def parent(self):
return self._parent
@property
def name(self):
return self._meta.name if self._meta else ''
@property
def filename(self):
return self.name.replace(' ', '_') + '/'
@property
def html(self):
ret = '<ul>'
for qvnote in self.qvnotes:
ret += '<li><a href="{}">{}</a></li>'.format(qvnote.get_url(), qvnote.name)
ret += '</ul>'
return ret
@property
def qvnotes(self):
return self._qvnotes
def get_url(self, root='.'):
return os.path.join(root, self.filename, 'index.html')
def parse(self, template, output, classes=None, resources_url=None, write_file_func=None):
output = self.get_output_dir(output, self.name)
for qvnote in self.qvnotes:
qvnote.parse(template, output, classes, resources_url, write_file_func)
context = {
'ins' : self,
'title' : self.name,
'content': self.html,
}
write_file_func = write_file_func or self.write_file_func
write_file_func(template, output, 'index.html', context)
class QvNotebookMeta(object):
def __init__(self, **kwargs):
self.name = kwargs.get('name', None)
self.uuid = kwargs.get('uuid', None)
def __repr__(self):
return json.dumps(self.__dict__)
<file_sep>FROM python:3.6-alpine
COPY . /code
WORKDIR /code
RUN pip install -r requirement.txt --index-url http://pypi.douban.com/simple --trusted-host pypi.douban.com
CMD python3
<file_sep>#!/usr/bin/env python
import argparse
import os
import sys
from quiver2html.objects.factory import QvFactory
class StoreDict(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
ret = {}
for s in values:
key, value = s.split('=')
ret[key] = value
setattr(namespace, self.dest, ret)
# parse command args
def parse_args():
src_dir = os.path.dirname(sys.path[0])
parser = argparse.ArgumentParser(
prog='quiver2html',
description='convert quiver note/notebook/library to html.',
)
parser.add_argument(
'notes',
nargs='+',
help='.qvlibrary or .qvnotebook or .qvnote dir',
)
parser.add_argument(
'-t',
'--template',
default=src_dir + '/template/index.html',
metavar='TEMPLATE_FILE',
help='template html file',
)
parser.add_argument(
'--classes',
action=StoreDict,
nargs='+',
metavar='HTML_TAG=CLASSES',
help='add css classes to html tag'
)
parser.add_argument(
'-o',
'--output',
default='output',
metavar='OUTPUT_DIR',
help='dest output dir',
)
parser.add_argument(
'--resources_url',
metavar='RESOURCE_OUTPUT_DIR',
help='dest resource output dir',
)
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
template = args.template
output = args.output
notes = args.notes
classes = args.classes
resources_url = args.resources_url
for note in notes:
QvFactory.create(note).parse(template, output, classes=classes, resources_url=resources_url)
<file_sep># quiver2html
convert quiver library / notebook / note to html
|
fbcca24322b4a83e3a67a4cd90de37cd01b45d91
|
[
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 11
|
Python
|
pktangyue/quiver2html
|
befb2deaaba6c689fafcc84f19f74a283fa1f550
|
7f256be30d9dee9b2993f8b20097edc6ca092314
|
refs/heads/master
|
<repo_name>keawade/pathfinder-tools<file_sep>/public/js/custom/dice.js
var dice = ['4', '6', '8', '12', '20', '100']
dice.forEach(function (die) {
var btn = document.getElementById(die)
btn.addEventListener('click', roll)
// btn.click()
})
function roll (e) {
var die = Number(e.srcElement.id)
var num = Number(document.getElementById(die + '-num').value)
var total = 0
for (var i = 0; i < num; i++) {
total += Math.floor(Math.random() * die) + 1
}
document.getElementById(die + '-out').value = total
}
<file_sep>/routes/index.js
var express = require('express')
var router = module.exports = express.Router()
router.get('/', function (req, res) {
res.render('index', {
title: 'Thing!'
})
})
router.get('/charsheet', function (req, res) {
res.render('charsheet/index', {
title: 'Character Sheet'
})
})
router.get('/charsheet/sheet', function (req, res) {
res.render('charsheet/sheet', {
title: 'Character Sheet',
character: {
weapons: [1, 2, 3]
}
})
})
router.get('/dice', function (req, res) {
res.render('generators/dice', {
title: 'Dice Roller'
})
})
router.get('/names', function (req, res) {
res.render('generators/names', {
title: 'Name Generator',
elf: ['Not yet implemented.'],
dwarf: ['Not yet implemented.'],
human: ['Not yet implemented.'],
gnome: ['Not yet implemented.'],
halfelf: ['Not yet implemented.'],
halforc: ['Not yet implemented.'],
halfling: ['Not yet implemented.']
})
})
<file_sep>/models/character.js
var mongoose = require('mongoose')
var characterSchema = new mongoose.Schema({
user: String,
general: {
player: String,
character: {
name: String,
alignment: String,
classes: String,
diety: String,
homeland: String,
race: String,
size: String,
gender: String,
age: String,
height: String,
weight: String,
hair: String,
eyes: String,
languages: [String]
}
},
abilities: {
str: {
score: Number,
temp: Number
},
dex: {
score: Number,
temp: Number
},
con: {
score: Number,
temp: Number
},
int: {
score: Number,
temp: Number
},
wis: {
score: Number,
temp: Number
},
cha: {
score: Number,
temp: Number
}
},
offense: {
bab: Number,
initiative__mod: Number,
speed: {
base: Number,
armor: Number,
fly: {
speed: Number,
manueverability: String
},
swim: Number,
climb: Number,
burrow: Number
},
cmb__mod: Number,
cmb__temp: Number,
weapons: [{
name: String,
attackbonus: Number,
damage: Number,
critical: {
range: Number,
multiplier: Number
},
damage__type: String,
ammo: {
name: String,
quantity: Number
}
}]
},
defense: {
armor: {
ac__bonus: Number,
ac__shieldbonus: Number,
ac__natural: Number,
ac__deflectmod: Number
},
saves: {
fortitude: {
base: Number,
magicmod: Number,
miscmod: Number,
tempmod: Number
},
reflex: {
base: Number,
magicmod: Number,
miscmod: Number,
tempmod: Number
},
will: {
base: Number,
magicmod: Number,
miscmod: Number,
tempmod: Number
}
},
resistances: [{
resist__type: String,
resist__amount: Number
}],
immunities: [String],
cmd: {
miscmod: Number,
tempmod: Number
},
spellresistance: Number,
damagereduction: Number,
hp: {
total: Number,
current: Number,
wounds: String,
nonlethal: Number
}
},
skills: {
acrobatics: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
appraise: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
bluff: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
climb: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
craft: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
diplomacy: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
disabledevice: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
disguise: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
escapeartist: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
fly: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
handleanimal: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
heal: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
intimidate: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
knowledge: {
arcana: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
dungeoneering: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
engineering: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
geography: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
history: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
local: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
nature: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
nobility: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
planes: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
religion: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
}
},
linguistics: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
perception: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
perform: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
profession: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
ride: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
sensemotive: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
sleightofhand: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
spellcraft: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
stealth: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
survival: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
swim: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
},
usemagicdevice: {
ranks: Number,
class: Boolean,
racial: Number,
trait: Number,
misc: Number,
note: String
}
},
feats: [{
name: String,
type: String,
description: String
}],
traits: [{
name: String,
type: String,
description: String
}],
special: [{
name: String,
type: String,
description: String
}],
spells: {
test: String // TODO - Update this.
},
inventory: {
money: {
platinum: Number,
gold: Number,
silver: Number,
copper: Number
},
treasure: String,
items: {
ac__item: {
name: String,
ac__bonus: Number,
itemtype: String,
checkpenalty: Number,
spellfailure: Number,
weight: Number,
description: String
},
gear: {
name: String,
geartype: String,
location: String,
quantity: Number,
weight: Number, // per item
description: String
}
}
},
notes: String
})
var character = mongoose.model('character', characterSchema)
module.exports = character
<file_sep>/models/classes.js
var mongoose = require('mongoose')
var classesSchema = new mongoose.Schema({
temp: String
})
var classes = mongoose.model('classes', classesSchema)
module.exports = classes
|
2766b93b7ad018d39069e770fe555be7e8ecaf58
|
[
"JavaScript"
] | 4
|
JavaScript
|
keawade/pathfinder-tools
|
d32aaf221bc8f63b67514dbdef995fe41dea3830
|
e3ad4f04d95d155259aab914403501b3d58e2a86
|
refs/heads/devel
|
<file_sep>library(testthat)
library(GenomicDataCommons)
test_check("GenomicDataCommons")
<file_sep>#' Query GDC for data slices
#'
#' This function returns a BAM file representing reads overlapping
#' regions specified either as chromosomal regions or as gencode gene
#' symbols.
#'
#' @param uuid character(1) identifying the BAM file resource
#'
#' @param regions character() vector describing chromosomal regions,
#' e.g., \code{c("chr1", "chr2:10000", "chr3:10000-20000")} (all
#' of chromosome 1, chromosome 2 from position 10000 to the end,
#' chromosome 3 from 10000 to 20000).
#'
#' @param symbols character() vector of gencode gene symbols, e.g.,
#' \code{c("BRCA1", "PTEN")}
#'
#' @param destination character(1) default \code{tempfile()} file path
#' for BAM file slice
#'
#' @param overwrite logical(1) default FALSE can destination be
#' overwritten?
#'
#' @param progress logical(1) default \code{interactive()} should a
#' progress bar be used?
#'
#' @param token character(1) security token allowing access to
#' restricted data. Almost all BAM data is restricted, so a token is
#' usually required. See
#' \url{https://docs.gdc.cancer.gov/Data/Data_Security/Data_Security/#authentication-tokens}.
#'
#'
#' @param legacy logical(1) DEPRECATED; whether or not to use the "legacy"
#' archive, containing older, non-harmonized data. Slicing of unharmonized
#' legacy BAM files is not supported. See
#' \url{https://docs.gdc.cancer.gov/API/Users_Guide/BAM_Slicing/}.
#'
#'
#' @details This function uses the Genomic Data Commons "slicing" API
#' to get portions of a BAM file specified either using "regions"
#' or using HGNC gene symbols.
#'
#' @return character(1) destination to the downloaded BAM file
#'
#' @importFrom httr progress
#' @importFrom jsonlite toJSON
#'
#' @examples
#' \dontrun{
#' slicing("df80679e-c4d3-487b-934c-fcc782e5d46e",
#' regions="chr17:75000000-76000000",
#' token=gdc_token())
#'
#' # Get 10 BAM files.
#' bamfiles = files() %>%
#' filter(data_format=='BAM') %>%
#' results(size=10) %>% ids()
#'
#' # Current alignments at the GDC are to GRCh38
#' library('TxDb.Hsapiens.UCSC.hg38.knownGene')
#' all_genes = genes(TxDb.Hsapiens.UCSC.hg38.knownGene)
#'
#' first3genes = all_genes[1:3]
#' # remove strand info
#' strand(first3genes) = '*'
#'
#' # We can get our regions easily now
#' as.character(first3genes)
#'
#' # Use parallel downloads to speed processing
#' library(BiocParallel)
#' register(MulticoreParam())
#'
#' fnames = bplapply(bamfiles, slicing, overwrite = TRUE,
#' regions=as.character(first3genes))
#'
#' # 10 BAM files
#' fnames
#'
#' library(GenomicAlignments)
#' lapply(unlist(fnames), readGAlignments)
#'
#' }
#' @export
slicing <- function(uuid, regions, symbols, destination=file.path(tempdir(), paste0(uuid, '.bam')),
overwrite=FALSE, progress=interactive(), token=gdc_token(), legacy = FALSE)
{
stopifnot(is.character(uuid), length(uuid) == 1L)
stopifnot(missing(regions) || missing(symbols),
!(missing(regions) && missing(symbols)))
stopifnot(is.character(destination), length(destination) == 1L,
(overwrite && file.exists(destination)) || !file.exists(destination))
if (!missing(symbols))
body <- list(gencode=I(symbols))
else
## FIXME: validate regions
body <- list(regions=regions)
if (legacy)
.Deprecated(
msg = paste0("The 'legacy' endpoint is deprecated.\n",
"See help(\"GDC-deprecated\")")
)
response <- .gdc_post(
endpoint=sprintf("slicing/view/%s", uuid),
add_headers('Content-type'='application/json'),
write_disk(destination, overwrite),
if (progress) progress() else NULL,
body=toJSON(body), token=token, legacy = FALSE)
if (progress)
cat("\n")
destination
}
<file_sep>test_that("clinical data is structured properly", {
sizen <- 3
case_ids <- cases() |> results(size=sizen) |> ids()
clinical_data <- gdc_clinical(case_ids)
# overview of clinical results
expect_true(
is(clinical_data, "GDCClinicalList")
)
expect_true(
all(
c("demographic", "diagnoses", "exposures", "main") %in%
names(clinical_data)
)
)
expect_true(
all(
vapply(clinical_data, nrow, integer(1L)) >= sizen
)
)
expect_true(
all(
vapply(clinical_data, is.data.frame, logical(1L))
)
)
})
<file_sep>#' ncigdc: A package for computating the notorious bar statistic.
#'
#' Cool package for interfacing with NCI GDC
#'
#' @section finding data:
#'
#' \itemize{
#' \item{\code{\link{query}}}
#' \item{\code{\link{cases}}}
#' \item{\code{\link{projects}}}
#' \item{\code{\link{files}}}
#' \item{\code{\link{annotations}}}
#' \item{\code{\link{mapping}}}
#' }
#'
#' @section downloading data:
#' data
#'
#' @importFrom magrittr "%>%"
#'
#' @docType package
#' @name GenomicDataCommons
NULL
<file_sep>#' Get the entity name from a GDCQuery object
#'
#' An "entity" is simply one of the four medata endpoints.
#' \itemize{
#' \item{cases}
#' \item{projects}
#' \item{files}
#' \item{annotations}
#' }
#' All \code{\link{GDCQuery}} objects will have an entity name. This S3 method
#' is simply a utility accessor for those names.
#'
#' @param x a \code{\link{GDCQuery}} object
#'
#' @return character(1) name of an associated entity; one of
#' "cases", "files", "projects", "annotations".
#'
#' @examples
#' qcases = cases()
#' qprojects = projects()
#'
#' entity_name(qcases)
#' entity_name(qprojects)
#'
#' @export
entity_name = function(x) {
UseMethod('entity_name',x)
}
#' @rdname entity_name
#' @export
entity_name.GDCQuery = function(x) {
cls = class(x)[1]
return(substr(cls,5,nchar(cls)))
}
#' @rdname entity_name
#' @export
entity_name.GDCResults = function(x) {
cls = class(x)[1]
return(substr(cls,4,nchar(cls)-8))
}
<file_sep>#' Read a single htseq-counts result file.
#'
#' The htseq package is used extensively to count reads
#' relative to regions (see
#' \url{http://www-huber.embl.de/HTSeq/doc/counting.html}).
#' The output of htseq-count is a simple two-column table
#' that includes features in column 1 and counts in column 2.
#' This function simply reads in the data from one such file
#' and assigns column names.
#'
#' @param fname character(1), the path of the htseq-count file.
#' @param samplename character(1), the name of the sample. This will
#' become the name of the second column on the resulting
#' \code{data.frame}, making for easier merging if necessary.
#' @param ... passed to \code{\link[readr]{read_tsv})}
#' @return a two-column data frame
#'
#' @examples
#' fname = system.file(package='GenomicDataCommons',
#' 'extdata/example.htseq.counts.gz')
#' dat = readHTSeqFile(fname)
#' head(dat)
#'
#' @export
readHTSeqFile <- function(fname, samplename = 'sample', ...) {
if(!file.exists(fname))
stop(sprintf('The specified file, %s, does not exist',fname))
if(!((length(fname) == 1) & (is.character(fname))))
stop('fname must be of type character(1)')
tmp = read_tsv(fname,col_names = FALSE)
if(ncol(tmp) != 2)
stop(sprintf('%s had %d columns, expected 2 columns',fname, ncol(tmp)))
colnames(tmp) = c('feature',samplename)
tmp
}
<file_sep>#' Fetch \code{\link{GDCQuery}} metadata from GDC
#'
#' @aliases GDCResponse
#'
#' @param x a \code{\link{GDCQuery}} object
#' @param from integer index from which to start returning data
#' @param size number of records to return
#' @param ... passed to httr (good for passing config info, etc.)
#' @param response_handler a function that processes JSON (as text)
#' and returns an R object. Default is \code{\link[jsonlite]{fromJSON}}.
#'
#' @rdname response
#'
#' @return A \code{GDCResponse} object which is a list with the following
#' members:
#' \itemize{
#' \item{results}
#' \item{query}
#' \item{aggregations}
#' \item{pages}
#' }
#'
#'
#' @examples
#'
#' # basic class stuff
#' gCases = cases()
#' resp = response(gCases)
#' class(resp)
#' names(resp)
#'
#' # And results from query
#' resp$results[[1]]
#'
#' @export
response = function(x,...) {
UseMethod('response',x)
}
#' provide count of records in a \code{\link{GDCQuery}}
#'
#' @param x a \code{\link{GDCQuery}} object
#' @param ... passed to httr (good for passing config info, etc.)
#'
#' @return integer(1) representing the count of records that will
#' be returned by the current query
#'
#' @examples
#' # total number of projects
#' projects() %>% count()
#'
#' # total number of cases
#' cases() %>% count()
#'
#' @export
count = function(x,...) {
UseMethod('count',x)
}
#' @describeIn count
#'
#' @export
count.GDCQuery = function(x,...) {
resp = x %>% response(size=1)
return(resp$pages$total)
}
#' @describeIn count
#'
#' @export
count.GDCResponse = function(x,...) {
x$pages$total
}
#" (internal) prepare "results" for return
#"
#" In particular, this function sets
#" entity_ids for every element so that
#" one does not loose track of the relationships
#" given the nested nature of GDC returns
.prepareResults <- function(res,idfield) {
for(i in names(res)) {
if(inherits(res[[i]],'data.frame'))
rownames(res[[i]]) = res[[idfield]]
else
names(res[[i]]) = res[[idfield]]}
return(res)
}
#' @rdname response
#'
#' @importFrom magrittr "%>%"
#' @importFrom jsonlite fromJSON
#'
#' @export
response.GDCQuery = function(x, from = 0, size = 10, ...,
response_handler = jsonlite::fromJSON) {
body = Filter(function(z) !is.null(z),x)
body[['facets']]=paste0(body[['facets']],collapse=",")
body[['fields']]=paste0(body[['fields']],collapse=",")
body[['expand']]=paste0(body[['expand']],collapse=",")
body[['from']]=from
body[['size']]=size
body[['format']]='JSON'
body[['pretty']]='FALSE'
tmp = response_handler(httr::content(
.gdc_post(entity_name(x),body=body, token=NULL,...),
as="text", encoding = "UTF-8"))
res = tmp$data$hits
idfield = paste0(sub('s$','',entity_name(x)),'_id')
## the following code just sets names on the
structure(
list(results = .prepareResults(res,idfield),
query = x,
pages = tmp$data$pagination,
aggregations = lapply(tmp$data$aggregations,function(x) {x$buckets})),
class = c(paste0('GDC',entity_name(x),'Response'),'GDCResponse','list')
)
}
#' @rdname response
#'
#' @export
response_all = function(x,...) {
count = count(x)
return(response(x=x,size=count,from=0,...))
}
#' aggregations
#'
#' @param x a \code{\link{GDCQuery}} object
#'
#' @return a \code{list} of \code{data.frame} with one
#' member for each requested facet. The data frames
#' each have two columns, key and doc_count.
#'
#' @examples
#' library(magrittr)
#' # Number of each file type
#' res = files() %>% facet(c('type','data_type')) %>% aggregations()
#' res$type
#'
#' @importFrom magrittr "%>%"
#' @export
aggregations = function(x) {
UseMethod('aggregations',x)
}
#' @describeIn aggregations
#'
#'
#' @export
aggregations.GDCQuery = function(x) {
if(is.null(x$facets))
x = x %>% facet()
return(response(x)$aggregations)
}
#' @describeIn aggregations
#'
#'
#' @export
aggregations.GDCResponse = function(x) {
x$aggregations
}
#' results
#'
#' @param x a \code{\link{GDCQuery}} object
#' @param ... passed on to \code{\link{response}}
#'
#' @return A (typically nested) \code{list} of GDC records
#'
#' @examples
#' qcases = cases() %>% results()
#' length(qcases)
#'
#' @export
results = function(x,...) {
UseMethod('results',x)
}
#' results_all
#'
#' @param x a \code{\link{GDCQuery}} object
#'
#' @return A (typically nested) \code{list} of GDC records
#'
#' @examples
#' # details of all available projects
#' projResults = projects() %>% results_all()
#' length(projResults)
#' count(projects())
#'
#'
#' @export
results_all = function(x) {
UseMethod('results_all',x)
}
#' @describeIn results
#'
#'
#' @export
results.GDCQuery = function(x,...) {
results(response(x,...))
}
#' @describeIn results_all
#'
#'
#' @export
results_all.GDCQuery = function(x) {
results(response_all(x))
}
#' @describeIn results
#'
#'
#' @export
results.GDCResponse = function(x,...) {
structure(
x$results,
class=c(sub('Response','Results',class(x)))
)
}
#' @describeIn results_all
#'
#'
#' @export
results_all.GDCResponse = function(x) {
structure(
x$results,
class=c(sub('Response','Results',class(x)))
)
}
#' @importFrom xml2 xml_find_all
.response_warnings <- function(warnings, endpoint)
{
warnings <- vapply(warnings, as.character, character(1))
if (length(warnings) && nzchar(warnings))
warning("'", endpoint, "' query warnings:\n", .wrapstr(warnings))
NULL
}
.response_json_as_list <- function(json, endpoint)
{
type <- substr(endpoint, 1, nchar(endpoint) - 1L)
type_id <- sprintf("%s_id", type)
type_list <- sprintf("%ss_list", type)
hits <- json[["data"]][["hits"]]
names(hits) <- vapply(hits, "[[", character(1), type_id)
hits <- lapply(hits, "[[<-", type_id, NULL)
hits <- lapply(hits, lapply, unlist) # collapse field elt 'list'
class(hits) <- c(type_list, "gdc_list", "list")
hits
}
#' @importFrom stats setNames
#' @importFrom xml2 xml_find_all xml_text
.response_xml_as_data_frame <- function(xml, fields)
{
xpaths <- setNames(sprintf("/response/data/hits/item/%s", fields), fields)
columns <- lapply(xpaths, function(xpath, xml) {
nodes <- xml_find_all(xml, xpath)
vapply(nodes, xml_text, character(1))
}, xml=xml)
columns <- Filter(length, columns)
dropped <- fields[!fields %in% names(columns)]
if (length(dropped))
warning("fields not available:\n", .wrapstr(dropped))
if (length(columns)==0) {
warning("No records found. Check on filter criteria to ensure they do what you expect. ")
return(NULL)
}
if (!length(unique(lengths(columns)))) {
lens <- paste(sprintf("%s = %d", names(columns), lengths(columns)),
collapse=", ")
stop("fields are different lengths:\n", .wrapstr(lens))
}
as.data.frame(columns, stringsAsFactors=FALSE)
}
<file_sep>library(GenomicDataCommons)
library(magrittr)
context('data handling')
case_ids <- cases() |> results(size=10) |> ids()
test_that("manifest files", {
m <- manifest(files(), size = 10)
expect_identical(nrow(m), 10L)
expect_true(ncol(m) > 5)
})
test_that("write_manifest", {
m = files() %>% manifest(size=10)
tf = tempfile()
write_manifest(m, tf)
expect_true(file.exists(tf))
unlink(tf)
})
test_that("gdcdata", {
d = tempfile()
if (!dir.exists(d))
dir.create(d)
gdc_set_cache(d)
few_file_ids = files() %>%
filter( ~ cases.project.project_id == 'TCGA-SARC' &
data_type == 'Copy Number Segment' &
analysis.workflow_type == 'DNAcopy') %>% results(size=2) %>% ids()
res = gdcdata(few_file_ids)
expect_length(res, 2)
expect_named(res)
unlink(d, recursive = TRUE)
})
<file_sep>#' Start a query of GDC metadata
#'
#' The basis for all functionality in this package
#' starts with constructing a query in R. The GDCQuery
#' object contains the filters, facets, and other
#' parameters that define the returned results. A token
#' is required for accessing certain datasets.
#'
#' @aliases GDCQuery
#'
#' @param entity character vector, including one of the entities in .gdc_entities
#' @param filters a filter list, typically created using \code{\link{make_filter}}, or added
#' to an existing \code{GDCQuery} object using \code{\link{filter}}.
#' @param facets a character vector of facets for counting common values.
#' See \code{\link{available_fields}}. In general, one will not specify this parameter
#' but will use \code{\link{facet}} instead.
#' @param legacy logical(1) DEPRECATED; whether to use the "legacy" archive or
#' not.
#' @param fields a character vector of fields to return. See \code{\link{available_fields}}.
#' In general, one will not specify fields directly, but instead use \code{\link{select}}
#' @param expand a character vector of "expands" to include in returned data. See
#' \code{\link{available_expand}}
#'
#' @return An S3 object, the GDCQuery object. This is a list
#' with the following members.
#' \itemize{
#' \item{filters}
#' \item{facets}
#' \item{fields}
#' \item{expand}
#' \item{archive}
#' \item{token}
#' }
#'
#' @examples
#' qcases = query('cases')
#' # equivalent to:
#' qcases = cases()
#'
#' @export
query = function(entity,
filters=NULL,
facets=NULL,
legacy = FALSE,
expand = NULL,
fields=default_fields(entity)) {
stopifnot(entity %in% .gdc_entities)
if (legacy)
.Deprecated(
msg = paste0("The 'legacy' argument is deprecated.\n",
"See help(\"GDC-deprecated\")")
)
ret = structure(
list(
fields = fields,
filters = filters,
facets = facets,
legacy = legacy,
expand = expand),
class = c(paste0('gdc_',entity),'GDCQuery','list')
)
return(ret)
}
#' @describeIn query convenience constructor for a GDCQuery for cases
#'
#' @param ... passed through to \code{\link{query}}
#'
#' @export
cases = function(...) {return(query('cases',...))}
#' @describeIn query convenience contructor for a GDCQuery for files
#' @export
files = function(...) {return(query('files',...))}
#' @describeIn query convenience contructor for a GDCQuery for projects
#' @export
projects = function(...) {return(query('projects',...))}
#' @describeIn query convenience contructor for a GDCQuery for annotations
#' @export
annotations = function(...) {return(query('annotations',...))}
#' @describeIn query convenience contructor for a GDCQuery for ssms
#' @export
ssms = function(...) {return(query("ssms", ...))}
#' @describeIn query convenience contructor for a GDCQuery for ssm_occurrences
#' @export
ssm_occurrences = function(...) {return(query("ssm_occurrences", ...))}
#' @describeIn query convenience contructor for a GDCQuery for cnvs
#' @export
cnvs = function(...) {return(query("cnvs", ...))}
#' @describeIn query convenience contructor for a GDCQuery for cnv_occurrences
#' @export
cnv_occurrences = function(...) {return(query("cnv_occurrences", ...))}
#' @describeIn query convenience contructor for a GDCQuery for genes
#' @export
genes = function(...) {return(query("genes", ...))}
<file_sep>#' Query the GDC for current status
#'
#' @param version (optional) character(1) version of GDC
#'
#' @return List describing current status.
#'
#' @importFrom httr content
#'
#' @examples
#' status()
#'
#' @export
status <- function(version=NULL) {
response <- .gdc_get(paste(version, "status", sep="/"),archive='default')
content(response, type="application/json")
}
<file_sep>.gdc_base <- "https://api.gdc.cancer.gov"
.gdc_endpoint <-
structure(
c("status", "projects", "cases", "files", "annotations", "data",
"manifest", "slicing"), ##, submission
class="gdc_endpoints")
.gdc_parameters <-
structure(
list(format="JSON", pretty=FALSE, fields=NULL, size=10L, from=0L,
sort=NULL, filters=NULL, facets=NULL),
class="gdc_parameters")
.gdc_flat_parameters <-
structure(
c('fields','facets'),
class = "gdc_flat_params")
.gdc_entities =
structure(
c('projects','cases',"files","annotations",
"ssms", "cnvs", "ssm_occurrences", "cnv_occurrences",
"genes"),
class = "gdc_entities")
.gdc_manifest_colnames =
structure(
c("id", "file_name", "md5sum", "file_size", "state"),
class = 'gdc_manifest_colnames'
)
#' Endpoints and Parameters
#'
#' \code{endpoints()} returns available endpoints.
#'
#' @return \code{endpoints()} returns a character vector of possible
#' endpoints.
#'
#' @rdname constants
#' @examples
#' endpoints()
#' @export
endpoints <- function()
.gdc_endpoint
#' @export
print.gdc_endpoints <- function(x, ...)
.cat0("available endpoints:\n", .wrapstr(x), "\n")
#' \code{parameters()} include format (internal use only), pretty
#' (internal use only), fields, size (number of results returned),
#' from (index of rist result), sort, filters, and facets. See
#' \url{https://gdc-docs.nci.nih.gov/API/Users_Guide/Search_and_Retrieval/#query-parameters}
#'
#' @return \code{parameters()} returns a list of possible parameters
#' and their default values.
#' @keywords internal
#'
#' @rdname constants
#' @examples
#' parameters()
#' @export
parameters <- function()
.gdc_parameters
#' @export
print.gdc_parameters <- function(x, ...) {
cat("available parameters:\n")
for (nm in names(x))
.cat0(" ", nm, ": ",
if (is.null(x[[nm]])) "NULL" else x[[nm]], "\n")
}
#" (internal)
.parameter_string <- function(parameters) {
if (is.null(parameters))
return("")
stopifnot(is.list(parameters),
all(names(parameters) %in% names(.gdc_parameters)))
default <- .gdc_parameters
default[names(parameters)] <- parameters
default <- Filter(Negate(is.null), default)
string <- paste(names(default), unname(default), sep="=", collapse="&")
sprintf("?%s", string)
}
<file_sep>library(httr)
library(xml2)
pkghome <- "~/a/GenomicDataCommons"
url <-
"https://gdc-docs.nci.nih.gov/API/Users_Guide/Appendix_A_Available_Fields/"
xml = content(GET(url))
.get_field <- function(xml, xpath) {
fields <- as.character(xml_find_all(xml, xpath))
Filter(nzchar, trimws(fields))
}
.project_fields <- .get_field(xml, "//table[1]//tr/td[1]/text()")
.file_fields <- .get_field(xml, "//table[2]//tr/td[1]/text()")
.case_fields <- .get_field(xml, "//table[3]//tr/td[1]/text()")
.annotation_fields <- .get_field(xml, "//table[4]//tr/td[1]/text()")
save(.project_fields, .file_fields, .case_fields, .annotation_fields,
file=file.path(pkghome, "R", "sysdata.rda"))
<file_sep>
# GenomicDataCommons
<!-- badges: start -->
[](https://github.com/Bioconductor/GenomicDataCommons/actions)
<!-- badges: end -->
# What is the GDC?
From the [Genomic Data Commons (GDC)
website](https://gdc.nci.nih.gov/about-gdc):
The National Cancer Institute’s (NCI’s) Genomic Data Commons (GDC) is a
data sharing platform that promotes precision medicine in oncology. It
is not just a database or a tool; it is an expandable knowledge network
supporting the import and standardization of genomic and clinical data
from cancer research programs.
The GDC contains NCI-generated data from some of the largest and most
comprehensive cancer genomic datasets, including The Cancer Genome Atlas
(TCGA) and Therapeutically Applicable Research to Generate Effective
Therapies (TARGET). For the first time, these datasets have been
harmonized using a common set of bioinformatics pipelines, so that the
data can be directly compared.
As a growing knowledge system for cancer, the GDC also enables
researchers to submit data, and harmonizes these data for import into
the GDC. As more researchers add clinical and genomic data to the GDC,
it will become an even more powerful tool for making discoveries about
the molecular basis of cancer that may lead to better care for patients.
The [data model for the GDC is
complex](https://gdc.cancer.gov/developers/gdc-data-model/gdc-data-model-components),
but it worth a quick overview. The data model is encoded as a so-called
property graph. Nodes represent entities such as Projects, Cases,
Diagnoses, Files (various kinds), and Annotations. The relationships
between these entities are maintained as edges. Both nodes and edges may
have Properties that supply instance details. The GDC API exposes these
nodes and edges in a somewhat simplified set of
[RESTful](https://en.wikipedia.org/wiki/Representational_state_transfer)
endpoints.
# Quickstart
This software is available at Bioconductor.org and can be downloaded via
`BiocManager::install`.
To report bugs or problems, either [submit a new
issue](https://github.com/Bioconductor/GenomicDataCommons/issues) or
submit a `bug.report(package='GenomicDataCommons')` from within R (which
will redirect you to the new issue on GitHub).
## Installation
Installation can be achieved via Bioconductor’s `BiocManager` package.
``` r
if (!require("BiocManager"))
install.packages("BiocManager")
BiocManager::install('GenomicDataCommons')
```
``` r
library(GenomicDataCommons)
```
## Check basic functionality
``` r
status()
#> $commit
#> [1] "4dd3680528a19ed33cfc83c7d049426c97bb903b"
#>
#> $data_release
#> [1] "Data Release 34.0 - July 27, 2022"
#>
#> $status
#> [1] "OK"
#>
#> $tag
#> [1] "3.0.0"
#>
#> $version
#> [1] 1
```
## Find data
The following code builds a `manifest` that can be used to guide the
download of raw data. Here, filtering finds gene expression files
quantified as raw counts using `STAR` from ovarian cancer patients.
``` r
ge_manifest <- files() |>
filter( cases.project.project_id == 'TCGA-OV') |>
filter( type == 'gene_expression' ) |>
filter( analysis.workflow_type == 'STAR - Counts') |>
manifest(size = 5)
ge_manifest
#> id data_format access file_name
#> 1 7c69529f-2273-4dc4-b213-e84924d78bea TSV open d6472bd0-b4e2-4ed1-a892-e1702c195dc7.rna_seq.augmented_star_gene_counts.tsv
#> 2 0eff4634-f8c4-4db9-8a7c-331b21689bae TSV open 42165baf-b32c-4fc4-8b04-29c5b4e76de0.rna_seq.augmented_star_gene_counts.tsv
#> 3 7d74b4c5-6391-4b3e-95a3-020ea0869e86 TSV controlled accf08d4-a784-4908-831a-7a08d4c5f0f5.rna_seq.star_splice_junctions.tsv.gz
#> 4 dc2aeea4-3cd0-4623-92f4-bbbc962851cc TSV controlled 8ab508b9-2993-4e66-b8f9-81e32e936d4a.rna_seq.star_splice_junctions.tsv.gz
#> 5 0cf852be-d2e3-4fde-bba8-c93efae2961a TSV open 93831282-1dd1-49a3-acd7-dae2a49ca62e.rna_seq.augmented_star_gene_counts.tsv
#> submitter_id data_category acl type file_size created_datetime md5sum
#> 1 7085a70b-2f63-4402-9e53-70f091f26fcb Transcriptome Profiling open gene_expression 4254435 2021-12-13T20:53:42.329364-06:00 19d5596bba8949f4c138793608497d56
#> 2 f0d44930-b1ad-447a-86b9-27d0285954b9 Transcriptome Profiling open gene_expression 4257461 2021-12-13T20:47:24.326497-06:00 d89d71b7c028c1643d7a3ee7857d8e01
#> 3 e6473134-6d65-414c-9f52-2c25057fac7d Transcriptome Profiling phs000178 gene_expression 3109435 2021-12-13T21:03:56.008440-06:00 fb8332d6413c44a9de02a1cbe6b018aa
#> 4 f99b93a9-70cb-44f8-bd1f-4edeee4425a4 Transcriptome Profiling phs000178 gene_expression 4607701 2021-12-13T21:02:23.944851-06:00 26231bed1ef67c093d3ce2b39def81cd
#> 5 fb4d7abe-b61a-4f35-9700-605f1bc1512f Transcriptome Profiling open gene_expression 4265694 2021-12-13T20:50:55.234254-06:00 050763aabd36509f954137fbdc4eeb00
#> updated_datetime file_id data_type state experimental_strategy
#> 1 2022-01-19T14:47:28.965154-06:00 7c69529f-2273-4dc4-b213-e84924d78bea Gene Expression Quantification released RNA-Seq
#> 2 2022-01-19T14:47:07.478144-06:00 0eff4634-f8c4-4db9-8a7c-331b21689bae Gene Expression Quantification released RNA-Seq
#> 3 2022-01-19T14:01:15.621847-06:00 7d74b4c5-6391-4b3e-95a3-020ea0869e86 Splice Junction Quantification released RNA-Seq
#> 4 2022-01-19T14:01:15.621847-06:00 dc2aeea4-3cd0-4623-92f4-bbbc962851cc Splice Junction Quantification released RNA-Seq
#> 5 2022-01-19T14:47:07.036781-06:00 0cf852be-d2e3-4fde-bba8-c93efae2961a Gene Expression Quantification released RNA-Seq
```
## Download data
This code block downloads the 5 gene expression files specified in the
query above. Using multiple processes to do the download very
significantly speeds up the transfer in many cases. The following
completes in about 15 seconds.
``` r
library(BiocParallel)
register(MulticoreParam())
destdir <- tempdir()
fnames <- lapply(ge_manifest$id,gdcdata)
```
If the download had included controlled-access data, the download above
would have needed to include a `token`. Details are available in [the
authentication section below](#authentication).
## Metadata queries
Here we use a couple of ad-hoc helper functions to handle the output of
the query. See the `inst/script/README.Rmd` folder for the source.
First, create a `data.frame` from the clinical data:
``` r
expands <- c("diagnoses","annotations",
"demographic","exposures")
clinResults <- cases() |>
GenomicDataCommons::select(NULL) |>
GenomicDataCommons::expand(expands) |>
results(size=6)
demoDF <- filterAllNA(clinResults$demographic)
exposuresDF <- bindrowname(clinResults$exposures)
```
``` r
demoDF[, 1:4]
#> cause_of_death race gender ethnicity
#> 2525bfef-6962-4b7f-8e80-6186400ce624 <NA> not reported female not reported
#> 126507c3-c0d7-41fb-9093-7deed5baf431 Cancer Related not reported female not reported
#> c43ac461-9f03-44bc-be7d-3d867eb708a0 <NA> not reported female not reported
#> a59a90d9-f1b0-49dd-9c97-bcaa6ba55d44 Cancer Related not reported male not reported
#> 59122a43-606a-4669-806b-6747e0ac9985 <NA> white male not hispanic or latino
#> 4447a969-e5c8-4291-b83c-53a0f7e77cbc Cancer Related white female not hispanic or latino
```
``` r
exposuresDF[, 1:4]
#> submitter_id created_datetime alcohol_intensity pack_years_smoked
#> 2525bfef-6962-4b7f-8e80-6186400ce624 C3N-03839-EXP 2019-12-30T10:23:07.190853-06:00 Lifelong Non-Drinker NA
#> 126507c3-c0d7-41fb-9093-7deed5baf431 C3N-01518-EXP 2018-06-21T14:27:48.817254-05:00 Lifelong Non-Drinker NA
#> c43ac461-9f03-44bc-be7d-3d867eb708a0 C3N-03933-EXP 2019-03-14T08:23:14.054975-05:00 Lifelong Non-Drinker NA
#> a59a90d9-f1b0-49dd-9c97-bcaa6ba55d44 C3N-02695-EXP 2019-03-14T08:23:14.054975-05:00 Occasional Drinker 16.8
#> 59122a43-606a-4669-806b-6747e0ac9985 C3L-03642-EXP 2019-06-24T07:53:15.534197-05:00 Lifelong Non-Drinker 39.0
#> 4447a969-e5c8-4291-b83c-53a0f7e77cbc C3L-03728-EXP 2019-06-24T07:53:15.534197-05:00 Lifelong Non-Drinker NA
```
Note that the diagnoses data has multiple lines per patient:
``` r
diagDF <- bindrowname(clinResults$diagnoses)
diagDF[, 1:4]
#> ajcc_pathologic_stage created_datetime tissue_or_organ_of_origin age_at_diagnosis
#> 2525bfef-6962-4b7f-8e80-6186400ce624 Stage IIB 2019-07-22T06:40:02.183501-05:00 Head of pancreas 19956
#> 126507c3-c0d7-41fb-9093-7deed5baf431 Not Reported 2018-12-03T12:05:16.846188-06:00 Temporal lobe 26312
#> c43ac461-9f03-44bc-be7d-3d867eb708a0 Stage III 2019-03-14T10:37:34.405260-05:00 Floor of mouth, NOS 25635
#> a59a90d9-f1b0-49dd-9c97-bcaa6ba55d44 Not Reported 2019-03-14T10:37:34.405260-05:00 Floor of mouth, NOS 16652
#> 59122a43-606a-4669-806b-6747e0ac9985 Not Reported 2019-07-22T06:40:02.183501-05:00 Upper lobe, lung 23384
#> 4447a969-e5c8-4291-b83c-53a0f7e77cbc Not Reported 2019-05-07T07:41:33.411909-05:00 Frontal lobe 29326
```
# Basic design
This package design is meant to have some similarities to the
“tidyverse” approach of dplyr. Roughly, the functionality for finding
and accessing files and metadata can be divided into:
1. Simple query constructors based on GDC API endpoints.
2. A set of verbs that when applied, adjust filtering, field selection,
and faceting (fields for aggregation) and result in a new query
object (an endomorphism)
3. A set of verbs that take a query and return results from the GDC
In addition, there are auxiliary functions for asking the GDC API for
information about available and default fields, slicing BAM files, and
downloading actual data files. Here is an overview of functionality[^1].
- Creating a query
- `projects()`
- `cases()`
- `files()`
- `annotations()`
- Manipulating a query
- `filter()`
- `facet()`
- `select()`
- Introspection on the GDC API fields
- `mapping()`
- `available_fields()`
- `default_fields()`
- `grep_fields()`
- `available_values()`
- `available_expand()`
- Executing an API call to retrieve query results
- `results()`
- `count()`
- `response()`
- Raw data file downloads
- `gdcdata()`
- `transfer()`
- `gdc_client()`
- Summarizing and aggregating field values (faceting)
- `aggregations()`
- Authentication
- `gdc_token()`
- BAM file slicing
- `slicing()`
[^1]: See individual function and methods documentation for specific
details.
<file_sep>#' Set facets for a \code{\link{GDCQuery}}
#'
#' @param x a \code{\link{GDCQuery}} object
#' @param facets a character vector of fields that
#' will be used for forming aggregations (facets).
#' Default is to set facets for all default fields.
#' See \code{\link{default_fields}} for details
#'
#' @return returns a \code{\link{GDCQuery}} object,
#' with facets field updated.
#'
#' @rdname faceting
#'
#' @examples
#' # create a new GDCQuery against the projects endpoint
#' gProj = projects()
#'
#' # default facets are NULL
#' get_facets(gProj)
#'
#' # set facets and save result
#' gProjFacet = facet(gProj)
#'
#' # check facets
#' get_facets(gProjFacet)
#'
#' # and get a response, noting that
#' # the aggregations list member contains
#' # tibbles for each facet
#' str(response(gProjFacet,size=2),max.level=2)
#'
#' @export
facet = function(x,facets) {
UseMethod('facet',x)
}
#' @export
facet.GDCQuery = function(x,facets=default_fields(x)) {
x$facets = facets
return(x)
}
#' Get facets for a \code{\link{GDCQuery}}
#'
#' @rdname faceting
#'
#' @export
get_facets = function(x) {
UseMethod('get_facets',x)
}
#' @rdname faceting
#'
#' @export
get_facets.GDCQuery = function(x) {
return(x$facets)
}
<file_sep>#' Prepare GDC manifest file for bulk download
#'
#' The \code{manifest} function/method creates a manifest of files to be downloaded
#' using the GDC Data Transfer Tool. There are methods for
#' creating manifest data frames from \code{\link{GDCQuery}} objects
#' that contain file information ("cases" and "files" queries).
#'
#' @param x An \code{\link{GDCQuery}} object of subclass "gdc_files" or "gdc_cases".
#'
#' @param size The total number of records to return. Default
#' will return the usually desirable full set of records.
#'
#' @param from Record number from which to start when returning the manifest.
#'
#' @param ... passed to \code{\link[httr]{PUT}}.
#'
#' @return A \code{\link[tibble]{tibble}}, also of type "gdc_manifest", with five columns:
#' \itemize{
#' \item{id}
#' \item{filename}
#' \item{md5}
#' \item{size}
#' \item{state}
#'}
#'
#' @examples
#' gFiles = files()
#' shortManifest = gFiles %>% manifest(size=10)
#' head(shortManifest,n=3)
#'
#'
#' @export
manifest <- function(x,from=0,size=count(x),...) {
UseMethod('manifest',x)
}
#' @describeIn manifest
#'
#' @export
manifest.gdc_files <- function(x,from=0,size=count(x),...) {
.manifestCall(x=x,from=from,size=size,...)
}
#' @describeIn manifest
#'
#' @export
manifest.GDCfilesResponse <- function(x,from=0,size=count(x),...) {
.manifestCall(x=x$query,from=from,size=size,...)
}
#' @describeIn manifest
#'
#' @export
manifest.GDCcasesResponse <- function(x,from=0,size=count(x),...) {
manifest(x=x$query,from=from,size=size,...)
}
#' @importFrom readr read_tsv
.manifestCall <- function(x,from=0,size=count(x),...) {
body = Filter(function(z) !is.null(z),x)
body[['facets']]=NULL
body[['fields']]=paste0(default_fields(x),collapse=",")
body[['from']]=from
body[['size']]=size
# remove return_type for now
# body[['return_type']]='manifest'
legacy = x$legacy
if (legacy)
.Deprecated(
msg = paste0("The 'legacy' argument is deprecated.\n",
"See help(\"GDC-deprecated\")")
)
tmp <- httr::content(
.gdc_post(entity_name(x), body=body, token=NULL, ...),
as = "text", encoding = "UTF-8"
)
tmp <- jsonlite::fromJSON(tmp)[["data"]][["hits"]]
tmp[["acl"]] <- unlist(tmp[["acl"]])
if(ncol(tmp)<5) {
tmp=data.frame()
}
class(tmp) <- c('GDCManifest',class(tmp))
return(tmp)
}
#' write a manifest data.frame to disk
#'
#' The \code{\link{manifest}} method creates a data.frame
#' that represents the data for a manifest file needed
#' by the GDC Data Transfer Tool. While the file format
#' is nothing special, this is a simple helper function
#' to write a manifest data.frame to disk. It returns
#' the path to which the file is written, so it can
#' be used "in-line" in a call to \code{\link{transfer}}.
#'
#' @param manifest A data.frame with five columns, typically
#' created by a call to \code{\link{manifest}}
#'
#' @param destfile The filename for saving the manifest.
#'
#' @return character(1) the destination file name.
#'
#' @importFrom utils write.table
#'
#' @examples
#' mf = files() %>% manifest(size=10)
#' write_manifest(mf)
#'
#' @export
write_manifest <- function(manifest,destfile=tempfile()) {
stopifnot(
all(.gdc_manifest_colnames %in% colnames(manifest)),
ncol(manifest) > 5
)
write.table(manifest,file=destfile,sep="\t",
col.names=TRUE,row.names=FALSE,quote=FALSE)
destfile
}
<file_sep>.response_mapping_as_list <- function(json) {
json <- lapply(json, unlist)
structure(json, class=c("mapping_list", "gdc_list", "list"))
}
#" (internal) utility for returning _mapping json
#' @importFrom httr content
.get_mapping_json <- function(endpoint) {
valid <- .gdc_entities
stopifnot(is.character(endpoint), length(endpoint) == 1L,
endpoint %in% valid)
response <- .gdc_get(
sprintf("%s/%s", endpoint, "_mapping")
)
content(response, type="application/json")
}
#' Query GDC for available endpoint fields
#'
#' @param endpoint character(1) corresponding to endpoints for which
#' users may specify additional or alternative fields. Endpoints
#' include \dQuote{projects}, \dQuote{cases}, \dQuote{files}, and
#' \dQuote{annotations}.
#'
#' @return A data frame describing the field (field name), full (full
#' data model name), type (data type), and four additional columns
#' describing the "set" to which the fields belong--\dQuote{default},
#' \dQuote{expand}, \dQuote{multi}, and \dQuote{nested}.
#'
#' @examples
#' map <- mapping("projects")
#' head(map)
#' # get only the "default" fields
#' subset(map,defaults)
#' # And get just the text names of the "default" fields
#' subset(map,defaults)$field
#'
#' @importFrom httr content
#' @export
mapping <- function(endpoint) {
json = .get_mapping_json(endpoint)
maplist = list()
fields = data.frame(field=unlist(json[['fields']]))
mapdat = json[['_mapping']]
for(cname in names(mapdat[[1]])) {
maplist[[cname]] = as.character(sapply(mapdat,'[[',cname))
}
df = do.call(cbind,maplist)
tmpdf = as.data.frame(matrix(FALSE, ncol = 1, nrow = nrow(df)),stringsAsFactors = FALSE)
fieldtypes = c('defaults')
colnames(tmpdf) = fieldtypes
df = cbind(data.frame(df,stringsAsFactors=FALSE),tmpdf)
df = as.data.frame(merge(fields,df,by.x='field',by.y='field',all.x=TRUE),stringsAsFactors = FALSE)
df$field = as.character(df$field)
for(i in fieldtypes) {
df[df$field %in% json[[i]],i] = TRUE
}
return(df)
}
<file_sep>#' Get the ids associated with a GDC query or response
#'
#' The GDC assigns ids (in the form of uuids) to objects in its database. Those
#' ids can be used for relationships, searching on the website, and as
#' unique ids. All
#'
#' @param x A \code{\link{GDCQuery}} or \code{\link{GDCResponse}} object
#'
#' @return a character vector of all the entity ids
#'
#' @examples
#' # use with a GDC query, in this case for "cases"
#' ids(cases() %>% filter(~ project.project_id == "TCGA-CHOL"))
#' # also works for responses
#' ids(response(files()))
#' # and results
#' ids(results(cases()))
#'
#'
#' @export
ids = function(x) {
UseMethod('ids',x)
}
#' @rdname ids
#' @export
ids.GDCManifest = function(x) {
return(x[['id']])
}
#' @rdname ids
#' @export
ids.GDCQuery = function(x) {
fieldname = .id_field(x)
res = x %>% GenomicDataCommons::select(fieldname) %>%
results_all()
return(.ifNullCharacterZero(res[[fieldname]]))
}
#' @rdname ids
#' @export
ids.GDCResults = function(x) {
fieldname = .id_field(x)
res = x[[fieldname]]
return(.ifNullCharacterZero(res))
}
#' @rdname ids
#' @export
ids.GDCResponse = function(x) {
fieldname = paste0(sub('s$','',entity_name(x$query)),'_id')
res = results(x)[[fieldname]]
return(.ifNullCharacterZero(res))
}
.id_field = function(x) {
return(paste0(sub('s$','',entity_name(x)),"_id"))
}
#' get the name of the id field
#'
#' In many places in the GenomicDataCommons package,
#' the entity ids are stored in a column or a vector
#' with a specific name that corresponds to the field name
#' at the GDC. The format is the entity name (singular) "_id".
#' This generic simply returns that name from a given object.
#'
#' @param x An object representing the query or results
#' of an entity from the GDC ("cases", "files", "annotations", "projects")
#'
#' @return character(1) such as "case_id", "file_id", etc.
#'
#' @examples
#' id_field(cases())
#'
#' @export
id_field = function(x) {
UseMethod('id_field',x)
}
#' @describeIn id_field GDCQuery method
#' @export
id_field.GDCQuery = function(x) {
return(.id_field(x))
}
#' @describeIn id_field GDCResults method
#' @export
id_field.GDCResults = function(x) {
return(.id_field(x))
}
<file_sep>---
output: github_document
knit: (function(inputFile, encoding) {
rmarkdown::render(inputFile, encoding = encoding, output_dir = "../../") })
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
cache = TRUE,
out.width = "100%"
)
```
```{r,echo=FALSE,include=FALSE,eval=FALSE}
rmarkdown::render("inst/script/README.Rmd", output_dir = ".")
```
# GenomicDataCommons
<!-- badges: start -->
[](https://github.com/Bioconductor/GenomicDataCommons/actions)
<!-- badges: end -->
# What is the GDC?
From the [Genomic Data Commons (GDC) website](https://gdc.nci.nih.gov/about-gdc):
The National Cancer Institute's (NCI's) Genomic Data Commons (GDC) is
a data sharing platform that promotes precision medicine in
oncology. It is not just a database or a tool; it is an expandable
knowledge network supporting the import and standardization of genomic
and clinical data from cancer research programs.
The GDC contains NCI-generated data from some of the largest and most
comprehensive cancer genomic datasets, including The Cancer Genome
Atlas (TCGA) and Therapeutically Applicable Research to Generate
Effective Therapies (TARGET). For the first time, these datasets have
been harmonized using a common set of bioinformatics pipelines, so
that the data can be directly compared.
As a growing knowledge system for cancer, the GDC also enables
researchers to submit data, and harmonizes these data for import into
the GDC. As more researchers add clinical and genomic data to the GDC,
it will become an even more powerful tool for making discoveries about
the molecular basis of cancer that may lead to better care for
patients.
The
[data model for the GDC is complex](https://gdc.cancer.gov/developers/gdc-data-model/gdc-data-model-components),
but it worth a quick overview. The data model is encoded as a
so-called property graph. Nodes represent entities such as Projects,
Cases, Diagnoses, Files (various kinds), and Annotations. The
relationships between these entities are maintained as edges. Both
nodes and edges may have Properties that supply instance details. The
GDC API exposes these nodes and edges in a somewhat simplified set
of
[RESTful](https://en.wikipedia.org/wiki/Representational_state_transfer)
endpoints.
# Quickstart
This software is available at Bioconductor.org and can be downloaded via
`BiocManager::install`.
To report bugs or problems, either
[submit a new issue](https://github.com/Bioconductor/GenomicDataCommons/issues)
or submit a `bug.report(package='GenomicDataCommons')` from within R (which
will redirect you to the new issue on GitHub).
## Installation
Installation can be achieved via Bioconductor's `BiocManager` package.
```{r,eval=FALSE}
if (!require("BiocManager"))
install.packages("BiocManager")
BiocManager::install('GenomicDataCommons')
```
```{r,include=TRUE,results="hide",message=FALSE,warning=FALSE}
library(GenomicDataCommons)
```
## Check basic functionality
```{r}
status()
```
## Find data
The following code builds a `manifest` that can be used to guide the
download of raw data. Here, filtering finds gene expression files
quantified as raw counts using `STAR` from ovarian cancer patients.
```{r}
ge_manifest <- files() |>
filter( cases.project.project_id == 'TCGA-OV') |>
filter( type == 'gene_expression' ) |>
filter( analysis.workflow_type == 'STAR - Counts') |>
manifest(size = 5)
ge_manifest
```
## Download data
This code block downloads the `r nrow(ge_manifest)` gene expression files
specified in the query above. Using multiple processes to do the download very
significantly speeds up the transfer in many cases. The following completes in
about 15 seconds.
```{r,eval=FALSE}
library(BiocParallel)
register(MulticoreParam())
destdir <- tempdir()
fnames <- lapply(ge_manifest$id,gdcdata)
```
If the download had included controlled-access data, the download above would
have needed to include a `token`. Details are available in
[the authentication section below](#authentication).
## Metadata queries
Here we use a couple of ad-hoc helper functions to handle the output of the
query. See the `inst/script/README.Rmd` folder for the source.
```{r,echo=FALSE}
filterAllNA <- function(df) {
notallna <- vapply(df, function(x) !all(is.na(x)), logical(1L))
df[, notallna]
}
bindrowname <- function(resultList) {
if (is.data.frame(resultList))
stop("Only run this on the list type of outputs")
datadf <- dplyr::bind_rows(resultList)
rownames(datadf) <- names(resultList)
filterAllNA(datadf)
}
```
First, create a `data.frame` from the clinical data:
```{r}
expands <- c("diagnoses","annotations",
"demographic","exposures")
clinResults <- cases() |>
GenomicDataCommons::select(NULL) |>
GenomicDataCommons::expand(expands) |>
results(size=6)
demoDF <- filterAllNA(clinResults$demographic)
exposuresDF <- bindrowname(clinResults$exposures)
```
```{r}
demoDF[, 1:4]
```
```{r}
exposuresDF[, 1:4]
```
Note that the diagnoses data has multiple lines per patient:
```{r}
diagDF <- bindrowname(clinResults$diagnoses)
diagDF[, 1:4]
```
# Basic design
This package design is meant to have some similarities to the "tidyverse"
approach of dplyr. Roughly, the functionality for finding and accessing files
and metadata can be divided into:
1. Simple query constructors based on GDC API endpoints.
2. A set of verbs that when applied, adjust filtering, field selection, and
faceting (fields for aggregation) and result in a new query object (an
endomorphism)
3. A set of verbs that take a query and return results from the GDC
In addition, there are auxiliary functions for asking the GDC API for
information about available and default fields, slicing BAM files, and
downloading actual data files. Here is an overview of functionality[^1].
- Creating a query
- `projects()`
- `cases()`
- `files()`
- `annotations()`
- Manipulating a query
- `filter()`
- `facet()`
- `select()`
- Introspection on the GDC API fields
- `mapping()`
- `available_fields()`
- `default_fields()`
- `grep_fields()`
- `available_values()`
- `available_expand()`
- Executing an API call to retrieve query results
- `results()`
- `count()`
- `response()`
- Raw data file downloads
- `gdcdata()`
- `transfer()`
- `gdc_client()`
- Summarizing and aggregating field values (faceting)
- `aggregations()`
- Authentication
- `gdc_token()`
- BAM file slicing
- `slicing()`
[^1]: See individual function and methods documentation for specific details.<file_sep>#' Get clinical information from GDC
#'
#' The NCI GDC has a complex data model that allows various studies to
#' supply numerous clinical and demographic data elements. However,
#' across all projects that enter the GDC, there are
#' similarities. This function returns four data.frames associated
#' with case_ids from the GDC.
#'
#' @param case_ids a character() vector of case_ids, typically from
#' "cases" query.
#'
#' @param include_list_cols logical(1), whether to include list
#' columns in the "main" data.frame. These list columns have
#' values for aliquots, samples, etc. While these may be useful
#' for some situations, they are generally not that useful as
#' clinical annotations.
#'
#' @importFrom jsonlite fromJSON
#' @importFrom dplyr bind_rows
#' @importFrom tibble as_tibble
#'
#' @details
#' Note that these data.frames can, in general, have different numbers
#' of rows (or even no rows at all). If one wishes to combine to
#' produce a single data.frame, using the approach of left joining to
#' the "main" data.frame will yield a useful combined data.frame. We
#' do not do that directly given the potential for 1:many
#' relationships. It is up to the user to determine what the best
#' approach is for any given dataset.
#'
#'
#' @return
#' A list of four data.frames:
#' \enumerate{
#' \item main, representing basic case identification and metadata
#' (update date, etc.)
#' \item diagnoses
#' \item esposures
#' \item demographic
#' }
#'
#'
#' @examples
#' case_ids = cases() %>% results(size=10) %>% ids()
#' clinical_data = gdc_clinical(case_ids)
#'
#' # overview of clinical results
#' class(clinical_data)
#' names(clinical_data)
#' sapply(clinical_data, class)
#' sapply(clinical_data, nrow)
#'
#' # available data
#' head(clinical_data$main)
#' head(clinical_data$demographic)
#' head(clinical_data$diagnoses)
#' head(clinical_data$exposures)
#'
#' @export
gdc_clinical = function(case_ids, include_list_cols = FALSE) {
stopifnot(is.character(case_ids))
stopifnot(is.logical(include_list_cols) & length(include_list_cols)==1)
resp = cases() %>%
filter( ~ case_id %in% case_ids) %>%
expand(c("diagnoses",
"demographic",
"exposures")) %>%
response_all(response_handler = function(x) jsonlite::fromJSON(x, simplifyDataFrame = TRUE))
demographic = resp$results$demographic
demographic$case_id = rownames(demographic)
nodx <- vapply(resp$results$diagnoses, is.null, logical(1L))
if (any(nodx))
resp$results$diagnoses[nodx] <- list(data.frame())
diagnoses <- suppressMessages({
bind_rows(
lapply(resp$results$diagnoses, readr::type_convert),
.id = "case_id"
)
})
exposures = bind_rows(resp$results$exposures, .id = "case_id")
# set up main table by removing data.frame columns
cnames = setdiff(colnames(resp$results), c('exposures', 'diagnoses', 'demographic'))
main = resp$results[, cnames]
if(!include_list_cols) {
non_list_cols = names(Filter(function(cname) cname!='list', sapply(main, class)))
main = main[, non_list_cols]
}
y = list(demographic = as_tibble(demographic),
diagnoses = as_tibble(diagnoses),
exposures = as_tibble(exposures),
main = as_tibble(main))
class(y) = c('GDCClinicalList', class(y))
return(y)
}
<file_sep>---
title: "Questions and answers from over the years"
author: "<NAME>"
date: "`r format(Sys.Date(), '%A, %B %d, %Y')`"
always_allow_html: yes
output:
BiocStyle::html_document:
df_print: paged
toc_float: true
keep_md: true
abstract: >
vignette: >
%\VignetteIndexEntry{Questions and answers from over the years}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
# How could I generate a manifest file with filtering of Race and Ethnicity?
From https://support.bioconductor.org/p/9138939/.
```{r}
library(GenomicDataCommons,quietly = TRUE)
```
I made a small change to the filtering expression approach based on
changes to lazy evaluation best practices. There is now no need to
include the `~` in the filter expression. So:
```{r}
q = files() %>%
GenomicDataCommons::filter(
cases.project.project_id == 'TCGA-COAD' &
data_type == 'Aligned Reads' &
experimental_strategy == 'RNA-Seq' &
data_format == 'BAM')
```
And get a count of the results:
```{r}
count(q)
```
And the manifest.
```{r}
manifest(q)
```
Your question about race and ethnicity is a good one.
```{r}
all_fields = available_fields(files())
```
And we can grep for `race` or `ethnic` to get potential matching fields
to look at.
```{r}
grep('race|ethnic',all_fields,value=TRUE)
```
Now, we can check available values for each field to determine how to complete
our filter expressions.
```{r}
available_values('files',"cases.demographic.ethnicity")
available_values('files',"cases.demographic.race")
```
We can complete our filter expression now to limit to `white` race only.
```{r}
q_white_only = q %>%
GenomicDataCommons::filter(cases.demographic.race=='white')
count(q_white_only)
manifest(q_white_only)
```
# How can I get the number of cases with RNA-Seq data added by date to TCGA project with `GenomicDataCommons`?
- From https://support.bioconductor.org/p/9135791/
I would like to get the number of cases added (created, any logical datetime would suffice here) to the TCGA project by experiment type. I attempted to get this data via GenomicDataCommons package, but it is giving me I believe the number of files for a given experiment type rather than number cases. How can I get the number of cases for which there is RNA-Seq data?
```{r}
library(tibble)
library(dplyr)
library(GenomicDataCommons)
cases() %>%
GenomicDataCommons::filter(~ project.program.name=='TCGA' &
files.experimental_strategy=='RNA-Seq') %>%
facet(c("files.created_datetime")) %>%
aggregations() %>%
.[[1]] %>%
as_tibble() %>%
dplyr::arrange(dplyr::desc(key))
```
<file_sep>#' Return valid values for "expand"
#'
#' The GDC allows a shorthand for specifying groups
#' of fields to be returned by the metadata queries.
#' These can be specified in a \code{\link{select}}
#' method call to easily supply groups of fields.
#'
#' @param entity Either a \code{\link{GDCQuery}} object
#' or a character(1) specifying a GDC entity ('cases', 'files',
#' 'annotations', 'projects')
#'
#' @return A character vector
#'
#' @seealso See \url{https://docs.gdc.cancer.gov/API/Users_Guide/Search_and_Retrieval/#expand}
#' for details
#'
#' @examples
#' head(available_expand('files'))
#'
#' @export
available_expand <- function(entity) {
UseMethod("available_expand",entity)
}
#' @rdname available_expand
#'
#' @export
available_expand.character <- function(entity) {
json = .get_mapping_json(entity)
return(unlist(json[['expand']]))
}
#' @rdname available_expand
#'
#' @export
available_expand.GDCQuery <- function(entity) {
return(available_expand(entity_name(entity)))
}
#" (internal) check expand values
.gdcCheckExpands <- function(entity,expand) {
if(is.null(expand)) return(TRUE)
stopifnot(entity %in% .gdc_entities)
ae = available_expand(entity)
mismatches = expand[!(expand %in% ae)]
if(length(mismatches)>0)
stop(sprintf('expand specified included expands not available in %s including (%s)',entity,mismatches))
return(TRUE)
}
#' Set the \code{expand} parameter
#'
#' S3 generic to set GDCQuery expand parameter
#'
#' @param x the objects on which to set fields
#' @param expand a character vector specifying the fields
#'
#'
#' @return A \code{\link{GDCQuery}} object, with the \code{expand}
#' member altered.
#'
#' @examples
#' gProj = projects()
#' gProj$fields
#' head(available_fields(gProj))
#' default_fields(gProj)
#'
#' gProj %>%
#' select(default_fields(gProj)[1:2]) %>%
#' response() %>%
#' str(max_level=2)
#'
#' @export
expand <- function(x,expand) {
UseMethod('expand',x)
}
#' @describeIn expand set expand fields on a GDCQuery object
#' @export
expand.GDCQuery <- function(x,expand) {
.gdcCheckExpands(entity_name(x),expand)
x$expand = expand
return(x)
}
<file_sep>---
title: "The GenomicDataCommons Package"
author: "<NAME> & <NAME>"
date: "`r format(Sys.Date(), '%A, %B %d, %Y')`"
always_allow_html: yes
output:
BiocStyle::html_document:
df_print: paged
toc_float: true
abstract: >
The National Cancer Institute (NCI) has established
the [Genomic Data Commons](https://gdc.nci.nih.gov/) (GDC). The GDC
provides the cancer research community with an open and unified
repository for sharing and accessing data across numerous cancer
studies and projects via a high-performance data transfer and query
infrastructure. The *GenomicDataCommons* Bioconductor package
provides basic infrastructure for querying, accessing, and mining
genomic datasets available from the GDC. We expect that the
Bioconductor developer and the larger bioinformatics communities will
build on the *GenomicDataCommons* package to add higher-level
functionality and expose cancer genomics data to the plethora of
state-of-the-art bioinformatics methods available in Bioconductor.
vignette: >
%\VignetteIndexEntry{Introduction to Accessing the NCI Genomic Data Commons}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r init, results='hide', echo=FALSE, warning=FALSE, message=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE, message=FALSE)
BiocStyle::markdown()
```
# What is the GDC?
From the [Genomic Data Commons (GDC) website](https://gdc.cancer.gov/about-gdc):
> The National Cancer Institute's (NCI's) Genomic Data Commons (GDC) is
a data sharing platform that promotes precision medicine in
oncology. It is not just a database or a tool; it is an expandable
knowledge network supporting the import and standardization of genomic
and clinical data from cancer research programs.
> The GDC contains NCI-generated data from some of the largest and most
comprehensive cancer genomic datasets, including The Cancer Genome
Atlas (TCGA) and Therapeutically Applicable Research to Generate
Effective Therapies (TARGET). For the first time, these datasets have
been harmonized using a common set of bioinformatics pipelines, so
that the data can be directly compared.
> As a growing knowledge system for cancer, the GDC also enables
researchers to submit data, and harmonizes these data for import into
the GDC. As more researchers add clinical and genomic data to the GDC,
it will become an even more powerful tool for making discoveries about
the molecular basis of cancer that may lead to better care for
patients.
The
[data model for the GDC is complex](https://gdc.cancer.gov/developers/gdc-data-model/gdc-data-model-components),
but it worth a quick overview and a graphical representation is included here.

The
GDC API exposes these nodes and edges in a somewhat simplified set
of
[RESTful](https://en.wikipedia.org/wiki/Representational_state_transfer) endpoints.
# Quickstart
This quickstart section is just meant to show basic
functionality. More details of functionality are included further on
in this vignette and in function-specific help.
This software is available at Bioconductor.org and can be downloaded via
`BiocManager::install`.
To report bugs or problems, either
[submit a new issue](https://github.com/Bioconductor/GenomicDataCommons/issues)
or submit a `bug.report(package='GenomicDataCommons')` from within R (which
will redirect you to the new issue on GitHub).
## Installation
Installation can be achieved via Bioconductor's `BiocManager` package.
```{r install_bioc, eval=FALSE}
if (!require("BiocManager"))
install.packages("BiocManager")
BiocManager::install('GenomicDataCommons')
```
```{r libraries, message=FALSE}
library(GenomicDataCommons)
```
## Check connectivity and status
The `r Biocpkg("GenomicDataCommons")` package relies on having network
connectivity. In addition, the NCI GDC API must also be operational
and not under maintenance. Checking `status` can be used to check this
connectivity and functionality.
```{r statusQS}
GenomicDataCommons::status()
```
And to check the status in code:
```{r statusCheck}
stopifnot(GenomicDataCommons::status()$status=="OK")
```
## Find data
The following code builds a `manifest` that can be used to guide the
download of raw data. Here, filtering finds gene expression files
quantified as raw counts using `STAR` from ovarian cancer patients.
```{r manifest}
ge_manifest <- files() %>%
filter( cases.project.project_id == 'TCGA-OV') %>%
filter( type == 'gene_expression' ) %>%
filter( analysis.workflow_type == 'STAR - Counts') %>%
manifest()
head(ge_manifest)
```
## Download data
After the `r nrow(ge_manifest)` gene expression files
specified in the query above. Using multiple processes to do the download very
significantly speeds up the transfer in many cases. On a standard 1Gb
connection, the following completes in about 30 seconds. The first time the
data are downloaded, R will ask to create a cache directory (see `?gdc_cache`
for details of setting and interacting with the cache). Resulting
downloaded files will be stored in the cache directory. Future access to
the same files will be directly from the cache, alleviating multiple downloads.
```{r downloadQS, eval=FALSE}
fnames <- lapply(ge_manifest$id[1:20], gdcdata)
```
If the download had included controlled-access data, the download above would
have needed to include a `token`. Details are available in
[the authentication section below](#authentication).
## Metadata queries
### Clinical data
Accessing clinical data is a very common task. Given a set of `case_ids`,
the `gdc_clinical()` function will return a list of four `tibble`s.
- demographic
- diagnoses
- exposures
- main
```{r gdc_clinical}
case_ids = cases() %>% results(size=10) %>% ids()
clindat = gdc_clinical(case_ids)
names(clindat)
```
```{r clinData}
head(clindat[["main"]])
head(clindat[["diagnoses"]])
```
### General metadata queries
The `r Biocpkg("GenomicDataCommons")` package can access the significant
clinical, demographic, biospecimen, and annotation information
contained in the NCI GDC. The `gdc_clinical()` function will often
be all that is needed, but the API and `r Biocpkg("GenomicDataCommons")` package
make much flexibility if fine-tuning is required.
```{r metadataQS}
expands = c("diagnoses","annotations",
"demographic","exposures")
clinResults = cases() %>%
GenomicDataCommons::select(NULL) %>%
GenomicDataCommons::expand(expands) %>%
results(size=50)
str(clinResults[[1]],list.len=6)
# or listviewer::jsonedit(clinResults)
```
# Basic design
This package design is meant to have some similarities to the "hadleyverse"
approach of dplyr. Roughly, the functionality for finding and accessing files
and metadata can be divided into:
1. Simple query constructors based on GDC API endpoints.
2. A set of verbs that when applied, adjust filtering, field selection, and
faceting (fields for aggregation) and result in a new query object (an
endomorphism)
3. A set of verbs that take a query and return results from the GDC
In addition, there are exhiliary functions for asking the GDC API for
information about available and default fields, slicing BAM files, and
downloading actual data files. Here is an overview of functionality[^1].
- Creating a query
- `projects()`
- `cases()`
- `files()`
- `annotations()`
- Manipulating a query
- `filter()`
- `facet()`
- `select()`
- Introspection on the GDC API fields
- `mapping()`
- `available_fields()`
- `default_fields()`
- `grep_fields()`
- `available_values()`
- `available_expand()`
- Executing an API call to retrieve query results
- `results()`
- `count()`
- `response()`
- Raw data file downloads
- `gdcdata()`
- `transfer()`
- `gdc_client()`
- Summarizing and aggregating field values (faceting)
- `aggregations()`
- Authentication
- `gdc_token()`
- BAM file slicing
- `slicing()`
[^1]: See individual function and methods documentation for specific details.
# Usage
There are two main classes of operations when working with the NCI GDC.
1. [Querying metadata and finding data files](#querying-metadata) (e.g., finding
all gene expression quantifications data files for all colon cancer patients).
2. [Transferring raw or processed data](#datafile-access-and-download) from the
GDC to another computer (e.g., downloading raw or processed data)
Both classes of operation are reviewed in detail in the following sections.
## Querying metadata
Vast amounts of metadata about cases (patients, basically), files, projects, and
so-called annotations are available via the NCI GDC API. Typically, one will
want to query metadata to either focus in on a set of files for download or
transfer *or* to perform so-called aggregations (pivot-tables, facets, similar
to the R `table()` functionality).
Querying metadata starts with [creating a "blank" query](#creating-a-query). One
will often then want to [`filter`](#filtering) the query to limit results prior
to [retrieving results](#retrieving-results). The GenomicDataCommons package has
[helper functions for listing fields](#fields-and-values) that are available for
filtering.
In addition to fetching results, the GDC API allows
[faceting, or aggregating,](#facets-and-aggregation), useful for compiling
reports, generating dashboards, or building user interfaces to GDC data (see GDC
web query interface for a non-R-based example).
### Creating a query
A query of the GDC starts its life in R. Queries follow the four metadata
endpoints available at the GDC. In particular, there are four convenience
functions that each create `GDCQuery` objects (actually, specific subclasses of
`GDCQuery`):
- `projects()`
- `cases()`
- `files()`
- `annotations()`
```{r projectquery}
pquery = projects()
```
The `pquery` object is now an object of (S3) class, `GDCQuery` (and
`gdc_projects` and `list`). The object contains the following elements:
- fields: This is a character vector of the fields that will be returned when we
[retrieve data](#retrieving-results). If no fields are specified to, for
example, the `projects()` function, the default fields from the GDC are used
(see `default_fields()`)
- filters: This will contain results after calling the
[`filter()` method](#filtering) and will be used to filter results on
[retrieval](#retrieving-results).
- facets: A character vector of field names that will be used for
[aggregating data](#facets-and-aggregation) in a call to `aggregations()`.
- archive: One of either "default" or ["legacy"](https://gdc-portal.nci.nih.gov/legacy-archive/).
- token: A character(1) token from the GDC. See
[the authentication section](#authentication) for details, but note that, in
general, the token is not necessary for metadata query and retrieval, only for
actual data download.
Looking at the actual object (get used to using `str()`!), note that the query
contains no results.
```{r pquery}
str(pquery)
```
### Retrieving results
[[ GDC pagination documentation ]](https://docs.gdc.cancer.gov/API/Users_Guide/Search_and_Retrieval/#size-and-from)
[[ GDC sorting documentation ]](https://docs.gdc.cancer.gov/API/Users_Guide/Search_and_Retrieval/#sort)
With a query object available, the next step is to retrieve results from the
GDC. The GenomicDataCommons package. The most basic type of results we can get
is a simple `count()` of records available that satisfy the filter criteria.
Note that we have not set any filters, so a `count()` here will represent all
the project records publicly available at the GDC in the "default" archive"
```{r pquerycount}
pcount = count(pquery)
# or
pcount = pquery %>% count()
pcount
```
The `results()` method will fetch actual results.
```{r pqueryresults}
presults = pquery %>% results()
```
These results are
returned from the GDC in [JSON](http://www.json.org/) format and
converted into a (potentially nested) list in R. The `str()` method is useful
for taking a quick glimpse of the data.
```{r presultsstr}
str(presults)
```
A default of only 10 records are returned. We can use the `size` and `from`
arguments to `results()` to either page through results or to change the number
of results. Finally, there is a convenience method, `results_all()` that will
simply fetch all the available results given a query. Note that `results_all()`
may take a long time and return HUGE result sets if not used carefully. Use of a
combination of `count()` and `results()` to get a sense of the expected data
size is probably warranted before calling `results_all()`
```{r presultsall}
length(ids(presults))
presults = pquery %>% results_all()
length(ids(presults))
# includes all records
length(ids(presults)) == count(pquery)
```
Extracting subsets of
results or manipulating the results into a more conventional R data
structure is not easily generalizable. However,
the
[purrr](https://github.com/hadley/purrr),
[rlist](https://renkun.me/rlist/),
and [data.tree](https://cran.r-project.org/web/packages/data.tree/vignettes/data.tree.html) packages
are all potentially of interest for manipulating complex, nested list
structures. For viewing the results in an interactive viewer, consider the
[listviewer](https://github.com/timelyportfolio/listviewer) package.
### Fields and Values
[[ GDC `fields` documentation ]](https://docs.gdc.cancer.gov/API/Users_Guide/Search_and_Retrieval/#fields)
Central to querying and retrieving data from the GDC is the ability to specify
which fields to return, filtering by fields and values, and faceting or
aggregating. The GenomicDataCommons package includes two simple functions,
`available_fields()` and `default_fields()`. Each can operate on a character(1)
endpoint name ("cases", "files", "annotations", or "projects") or a `GDCQuery`
object.
```{r defaultfields}
default_fields('files')
# The number of fields available for files endpoint
length(available_fields('files'))
# The first few fields available for files endpoint
head(available_fields('files'))
```
The fields to be returned by a query can be specified following a similar
paradigm to that of the dplyr package. The `select()` function is a verb that
resets the fields slot of a `GDCQuery`; note that this is not quite analogous to
the dplyr `select()` verb that limits from already-present fields. We
*completely replace* the fields when using `select()` on a `GDCQuery`.
```{r selectexample}
# Default fields here
qcases = cases()
qcases$fields
# set up query to use ALL available fields
# Note that checking of fields is done by select()
qcases = cases() %>% GenomicDataCommons::select(available_fields('cases'))
head(qcases$fields)
```
Finding fields of interest is such a common operation that the
GenomicDataCommons includes the `grep_fields()` function.
See the appropriate help pages for details.
### Facets and aggregation
[[ GDC `facet` documentation ]](https://docs.gdc.cancer.gov/API/Users_Guide/Search_and_Retrieval/#facets)
The GDC API offers a feature known as aggregation or faceting. By
specifying one or more fields (of appropriate type), the GDC can
return to us a count of the number of records matching each potential
value. This is similar to the R `table` method. Multiple fields can be
returned at once, but the GDC API does not have a cross-tabulation
feature; all aggregations are only on one field at a time. Results of
`aggregation()` calls come back as a list of data.frames (actually,
tibbles).
```{r aggexample}
# total number of files of a specific type
res = files() %>% facet(c('type','data_type')) %>% aggregations()
res$type
```
Using `aggregations()` is an also easy way to learn the contents of individual
fields and forms the basis for faceted search pages.
### Filtering
[[ GDC `filtering` documentation ]](https://docs.gdc.cancer.gov/API/Users_Guide/Search_and_Retrieval/#filters-specifying-the-query)
The GenomicDataCommons package uses a form of non-standard evaluation to specify
R-like queries that are then translated into an R list. That R list is, upon
calling a method that fetches results from the GDC API, translated into the
appropriate JSON string. The R expression uses the formula interface as
suggested by <NAME> in his [vignette on non-standard evaluation](https://cran.r-project.org/web/packages/dplyr/vignettes/nse.html)
> It’s best to use a formula because a formula captures both the expression to
evaluate and the environment where the evaluation occurs. This is important if
the expression is a mixture of variables in a data frame and objects in the
local environment [for example].
For the user, these details will not be too important except to note that a
filter expression must begin with a "~".
```{r allfilesunfiltered}
qfiles = files()
qfiles %>% count() # all files
```
To limit the file type, we can refer back to the
[section on faceting](#facets-and-aggregation) to see the possible values for
the file field "type". For example, to filter file results to only
"gene_expression" files, we simply specify a filter.
```{r onlyGeneExpression}
qfiles = files() %>% filter( type == 'gene_expression')
# here is what the filter looks like after translation
str(get_filter(qfiles))
```
What if we want to create a filter based on the project ('TCGA-OVCA', for
example)? Well, we have a couple of possible ways to discover available fields.
The first is based on base R functionality and some intuition.
```{r filtAvailFields}
grep('pro',available_fields('files'),value=TRUE) %>%
head()
```
Interestingly, the project information is "nested" inside the case. We don't
need to know that detail other than to know that we now have a few potential
guesses for where our information might be in the files records. We need to
know where because we need to construct the appropriate filter.
```{r filtProgramID}
files() %>%
facet('cases.project.project_id') %>%
aggregations() %>%
head()
```
We note that `cases.project.project_id` looks like it is a good fit. We also
note that `TCGA-OV` is the correct project_id, not `TCGA-OVCA`. Note that
*unlike with dplyr and friends, the `filter()` method here **replaces** the
filter and does not build on any previous filters*.
```{r filtfinal}
qfiles = files() %>%
filter( cases.project.project_id == 'TCGA-OV' & type == 'gene_expression')
str(get_filter(qfiles))
qfiles %>% count()
```
Asking for a `count()` of results given these new filter criteria gives `r
qfiles %>% count()` results. Filters can be chained (or nested) to
accomplish the same effect as multiple `&` conditionals. The `count()`
below is equivalent to the `&` filtering done above.
```{r filtChain}
qfiles2 = files() %>%
filter( cases.project.project_id == 'TCGA-OV') %>%
filter( type == 'gene_expression')
qfiles2 %>% count()
(qfiles %>% count()) == (qfiles2 %>% count()) #TRUE
```
Generating a manifest for bulk downloads is as
simple as asking for the manifest from the current query.
```{r filtAndManifest}
manifest_df = qfiles %>% manifest()
head(manifest_df)
```
Note that we might still not be quite there. Looking at filenames, there are
suspiciously named files that might include "FPKM", "FPKM-UQ", or "counts".
Another round of `grep` and `available_fields`, looking for "type" turned up
that the field "analysis.workflow_type" has the appropriate filter criteria.
```{r filterForSTARCounts}
qfiles = files() %>% filter( ~ cases.project.project_id == 'TCGA-OV' &
type == 'gene_expression' &
access == "open" &
analysis.workflow_type == 'STAR - Counts')
manifest_df = qfiles %>% manifest()
nrow(manifest_df)
```
The GDC Data Transfer Tool can be used (from R, `transfer()` or from the
command-line) to orchestrate high-performance, restartable transfers of all the
files in the manifest. See [the bulk downloads section](bulk-downloads) for
details.
## Authentication
[[ GDC authentication documentation ]](https://docs.gdc.cancer.gov/API/Users_Guide/Search_and_Retrieval/#facets)
The GDC offers both "controlled-access" and "open" data. As of this
writing, only data stored as files is "controlled-access"; that is,
metadata accessible via the GDC is all "open" data and some files are
"open" and some are "controlled-access". Controlled-access data are
only available
after
[going through the process of obtaining access.](https://gdc.cancer.gov/access-data/obtaining-access-controlled-data)
After controlled-access to one or more datasets has been granted,
logging into the GDC web portal will allow you
to
[access a GDC authentication token](https://docs.gdc.cancer.gov/Data_Portal/Users_Guide/Authentication/#gdc-authentication-tokens),
which can be downloaded and then used to access available
controlled-access data via the GenomicDataCommons package.
The GenomicDataCommons uses authentication tokens only for downloading
data (see `transfer` and `gdcdata` documentation). The package
includes a helper function, `gdc_token`, that looks for the token to
be stored in one of three ways (resolved in this order):
1. As a string stored in the environment variable, `GDC_TOKEN`
2. As a file, stored in the file named by the environment variable,
`GDC_TOKEN_FILE`
3. In a file in the user home directory, called `.gdc_token`
As a concrete example:
```{r authenNoRun, eval=FALSE}
token = gdc_token()
transfer(...,token=token)
# or
transfer(...,token=get_token())
```
## Datafile access and download
### Data downloads via the GDC API
The `gdcdata` function takes a character vector of one or more file
ids. A simple way of producing such a vector is to produce a
`manifest` data frame and then pass in the first column, which will
contain file ids.
```{r singlefileDL}
fnames = gdcdata(manifest_df$id[1:2],progress=FALSE)
```
Note that for controlled-access data, a
GDC [authentication token](#authentication) is required. Using the
`BiocParallel` package may be useful for downloading in parallel,
particularly for large numbers of smallish files.
### Bulk downloads
The bulk download functionality is only efficient (as of v1.2.0 of the
GDC Data Transfer Tool) for relatively large files, so use this
approach only when transferring BAM files or larger VCF files, for
example. Otherwise, consider using the approach shown above, perhaps
in parallel.
```{r bulkDL, eval=FALSE}
# Requires gcd_client command-line utility to be isntalled
# separately.
fnames = gdcdata(manifest_df$id[3:10], access_method = 'client')
```
### BAM slicing
# Use Cases
## Cases
### How many cases are there per project_id?
```{r casesPerProject}
res = cases() %>% facet("project.project_id") %>% aggregations()
head(res)
library(ggplot2)
ggplot(res$project.project_id,aes(x = key, y = doc_count)) +
geom_bar(stat='identity') +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
```
### How many cases are included in all TARGET projects?
```{r casesInTCGA}
cases() %>% filter(~ project.program.name=='TARGET') %>% count()
```
### How many cases are included in all TCGA projects?
```{r casesInTARGET}
cases() %>% filter(~ project.program.name=='TCGA') %>% count()
```
### What is the breakdown of sample types in TCGA-BRCA?
```{r casesTCGABRCASampleTypes}
# The need to do the "&" here is a requirement of the
# current version of the GDC API. I have filed a feature
# request to remove this requirement.
resp = cases() %>% filter(~ project.project_id=='TCGA-BRCA' &
project.project_id=='TCGA-BRCA' ) %>%
facet('samples.sample_type') %>% aggregations()
resp$samples.sample_type
```
### Fetch all samples in TCGA-BRCA that use "Solid Tissue" as a normal.
```{r casesTCGABRCASolidNormal}
# The need to do the "&" here is a requirement of the
# current version of the GDC API. I have filed a feature
# request to remove this requirement.
resp = cases() %>% filter(~ project.project_id=='TCGA-BRCA' &
samples.sample_type=='Solid Tissue Normal') %>%
GenomicDataCommons::select(c(default_fields(cases()),'samples.sample_type')) %>%
response_all()
count(resp)
res = resp %>% results()
str(res[1],list.len=6)
head(ids(resp))
```
### Get all TCGA case ids that are female
```{r casesFemaleTCGA}
cases() %>%
GenomicDataCommons::filter(~ project.program.name == 'TCGA' &
"cases.demographic.gender" %in% "female") %>%
GenomicDataCommons::results(size = 4) %>%
ids()
```
### Get all TCGA-COAD case ids that are NOT female
```{r notFemaleTCGACOAD}
cases() %>%
GenomicDataCommons::filter(~ project.project_id == 'TCGA-COAD' &
"cases.demographic.gender" %exclude% "female") %>%
GenomicDataCommons::results(size = 4) %>%
ids()
```
### Get all TCGA cases that are missing gender
```{r missingGenderTCGA}
cases() %>%
GenomicDataCommons::filter(~ project.program.name == 'TCGA' &
missing("cases.demographic.gender")) %>%
GenomicDataCommons::results(size = 4) %>%
ids()
```
### Get all TCGA cases that are NOT missing gender
```{r notMissingGenderTCGA}
cases() %>%
GenomicDataCommons::filter(~ project.program.name == 'TCGA' &
!missing("cases.demographic.gender")) %>%
GenomicDataCommons::results(size = 4) %>%
ids()
```
## Files
### How many of each type of file are available?
```{r filesVCFCount}
res = files() %>% facet('type') %>% aggregations()
res$type
ggplot(res$type,aes(x = key,y = doc_count)) + geom_bar(stat='identity') +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
```
### Find gene-level RNA-seq quantification files for GBM
```{r filesRNAseqGeneGBM}
q = files() %>%
GenomicDataCommons::select(available_fields('files')) %>%
filter(~ cases.project.project_id=='TCGA-GBM' &
data_type=='Gene Expression Quantification')
q %>% facet('analysis.workflow_type') %>% aggregations()
# so need to add another filter
file_ids = q %>% filter(~ cases.project.project_id=='TCGA-GBM' &
data_type=='Gene Expression Quantification' &
analysis.workflow_type == 'STAR - Counts') %>%
GenomicDataCommons::select('file_id') %>%
response_all() %>%
ids()
```
## Slicing
### Get all BAM file ids from TCGA-GBM
**I need to figure out how to do slicing reproducibly in a testing environment
and for vignette building**.
```{r filesRNAseqGeneGBMforBAM}
q = files() %>%
GenomicDataCommons::select(available_fields('files')) %>%
filter(~ cases.project.project_id == 'TCGA-GBM' &
data_type == 'Aligned Reads' &
experimental_strategy == 'RNA-Seq' &
data_format == 'BAM')
file_ids = q %>% response_all() %>% ids()
```
```{r slicing10, eval=FALSE}
bamfile = slicing(file_ids[1],regions="chr12:6534405-6538375",token=gdc_token())
library(GenomicAlignments)
aligns = readGAlignments(bamfile)
```
# Troubleshooting
## SSL connection errors
* Symptom: Trying to connect to the API results in:
```
Error in curl::curl_fetch_memory(url, handle = handle) :
SSL connect error
```
* Possible solutions: The [issue
is that the GDC supports only recent security Transport Layer Security (TLS)](http://stackoverflow.com/a/42599546/459633),
so the only known fix is to upgrade the system `openssl` to version
1.0.1 or later.
* [[Mac OS]](https://github.com/Bioconductor/GenomicDataCommons/issues/35#issuecomment-284233510),
* [[Ubuntu]](http://askubuntu.com/a/434245)
* [[Centos/RHEL]](https://www.liquidweb.com/kb/update-and-patch-openssl-for-the-ccs-injection-vulnerability/).
After upgrading `openssl`, reinstall the R `curl` and `httr` packages.
# sessionInfo()
```{r sessionInfo}
sessionInfo()
```
# Developer notes
- The `S3` object-oriented programming paradigm is used.
- We have adopted a functional programming style with functions and methods that
often take an "object" as the first argument. This style lends itself to
pipeline-style programming.
- The GenomicDataCommons package uses the
[alternative request format (POST)](https://docs.gdc.cancer.gov/API/Users_Guide/Search_and_Retrieval/#alternative-request-format)
to allow very large request bodies.
<file_sep>## Running tests
```{r}
devtools::test()
```
Should also run under `R CMD BiocCheck/check`.
## Tests
A test file lives in tests/testthat/. Its name must start with test. Here’s an example of a test file from the stringr package:
```{r}
library(stringr)
context("String length")
test_that("str_length is number of characters", {
expect_equal(str_length("a"), 1)
expect_equal(str_length("ab"), 2)
expect_equal(str_length("abc"), 3)
})
test_that("str_length of factor is length of level", {
expect_equal(str_length(factor("a")), 1)
expect_equal(str_length(factor("ab")), 2)
expect_equal(str_length(factor("abc")), 3)
})
test_that("str_length of missing is missing", {
expect_equal(str_length(NA), NA_integer_)
expect_equal(str_length(c(NA, 1)), c(NA, 1))
expect_equal(str_length("NA"), 2)
})
```
Tests are organised hierarchically: expectations are grouped into tests which are organised in files:
An expectation is the atom of testing. It describes the expected result of a computation: Does it have the right value and right class? Does it produce error messages when it should? An expectation automates visual checking of results in the console. Expectations are functions that start with expect_.
A test groups together multiple expectations to test the output from a simple function, a range of possibilities for a single parameter from a more complicated function, or tightly related functionality from across multiple functions. This is why they are sometimes called unit as they test one unit of functionality. A test is created with test_that() .
A file groups together multiple related tests. Files are given a human readable name with context().
<file_sep>library(GenomicDataCommons)
library(magrittr)
context('API')
test_that("status returns correctly", {
res = status()
expect_equal(length(res), 5)
expect_equal(res$status,"OK")
})
test_that('query', {
gCases = query('cases')
expect_equal(class(gCases)[1],'gdc_cases')
expect_equal(class(gCases)[2],'GDCQuery')
expect_equal(class(gCases)[3],'list')
gFiles = query('files')
expect_equal(class(gFiles)[1],'gdc_files')
expect_equal(class(gFiles)[2],'GDCQuery')
expect_equal(class(gFiles)[3],'list')
gProjects = query('projects')
expect_equal(class(gProjects)[1],'gdc_projects')
expect_equal(class(gProjects)[2],'GDCQuery')
expect_equal(class(gProjects)[3],'list')
gAnnotations = query('annotations')
expect_equal(class(gAnnotations)[1],'gdc_annotations')
expect_equal(class(gAnnotations)[2],'GDCQuery')
expect_equal(class(gAnnotations)[3],'list')
})
test_that("cases", {
idfield = "case_id"
q = cases()
resp = q %>% response()
expect_gte(q %>% count(),1000)
expect_equal(select(q,idfield)$fields,idfield)
expect_equal(facet(q,idfield)$facets,idfield)
})
test_that("files", {
q = files()
idfield = "file_id"
resp = q %>% response()
expect_gte(q %>% count(),1000)
expect_equal(select(q,idfield)$fields,idfield)
expect_equal(facet(q,idfield)$facets,idfield)
})
test_that("annotations", {
q = annotations()
idfield = "annotation_id"
resp = q %>% response()
expect_gte(q %>% count(),1000)
expect_equal(select(q,idfield)$fields,idfield)
expect_equal(facet(q,idfield)$facets,idfield)
})
test_that("mapping", {
res = mapping('files')
expect_equal(class(res),'data.frame')
expect_equal(ncol(res), 6)
expect_equal(colnames(res),c('field','description','doc_type','full','type','defaults'))
})
test_that("projects", {
q = projects()
idfield = "project_id"
resp = q %>% response()
expect_gte(q %>% count(),35)
expect_equal(select(q,idfield)$fields,idfield)
expect_equal(facet(q,idfield)$facets,idfield)
})
<file_sep>---
title: "Working with simple somatic mutations"
author: "<NAME>"
date: "`r format(Sys.Date(), '%A, %B %d, %Y')`"
always_allow_html: yes
output:
BiocStyle::html_document:
df_print: paged
toc_float: true
abstract: >
vignette: >
%\VignetteIndexEntry{Somatic Mutation Data}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
# Background
# Workflow
```{r warning=FALSE,message=FALSE}
library(GenomicDataCommons)
library(tibble)
```
## Genes and gene details
```{r}
grep_fields('genes', 'symbol')
```
```{r}
head(available_values('genes','symbol'))
```
```{r}
tp53 = genes() |>
GenomicDataCommons::filter(symbol=='TP53') |>
results(size=10000) |>
as_tibble()
```
## ssms
```{r}
ssms() |>
GenomicDataCommons::filter(
chromosome==paste0('chr',tp53$gene_chromosome[1]) &
start_position > tp53$gene_start[1] &
end_position < tp53$gene_end[1]) |>
GenomicDataCommons::count()
```
```{r}
ssms() |>
GenomicDataCommons::filter(
consequence.transcript.gene.symbol %in% c('TP53')) |>
GenomicDataCommons::count()
```
## convert to VRanges
```{r warning=FALSE,message=FALSE}
library(VariantAnnotation)
vars = ssms() |>
GenomicDataCommons::filter(
consequence.transcript.gene.symbol %in% c('TP53')) |>
GenomicDataCommons::results_all() |>
as_tibble()
```
```{r}
vr = VRanges(seqnames = vars$chromosome,
ranges = IRanges(start=vars$start_position, width=1),
ref = vars$reference_allele,
alt = vars$tumor_allele)
```
```{r}
ssm_occurrences() |>
GenomicDataCommons::filter(
ssm.consequence.transcript.gene.symbol %in% c('TP53')) |>
GenomicDataCommons::count()
```
```{r}
var_samples = ssm_occurrences() |>
GenomicDataCommons::filter(
ssm.consequence.transcript.gene.symbol %in% c('TP53')) |>
GenomicDataCommons::expand(c('case', 'ssm', 'case.project')) |>
GenomicDataCommons::results_all() |>
as_tibble()
```
```{r}
table(var_samples$case$disease_type)
```
## OncoPrint
```{r}
fnames <- files() %>%
GenomicDataCommons::filter(
cases.project.project_id=='TCGA-SKCM' &
data_format=='maf' &
data_type=='Masked Somatic Mutation' &
analysis.workflow_type ==
'Aliquot Ensemble Somatic Variant Merging and Masking'
) %>%
results(size = 1) %>%
ids() %>%
gdcdata()
```
```{r cache=TRUE}
library(maftools)
melanoma = read.maf(maf = fnames)
```
```{r}
maftools::oncoplot(melanoma)
```
<file_sep>#' Work with gdc cache directory
#'
#' The GenomicDataCommons package will cache downloaded
#' files to minimize network and allow for
#' offline work. These functions are used to create a cache directory
#' if one does not exist, set a global option, and query that
#' option. The cache directory will default to the user "cache"
#' directory according to specifications in
#' \code{\link[rappdirs]{app_dir}}. However, the user may want to set
#' this to another direcotory with more or higher performance
#' storage.
#'
#' @return character(1) directory path that serves as
#' the base directory for GenomicDataCommons downloads.
#'
#' @details
#' The cache structure is currently just a directory with each file
#' being represented by a path constructed as:
#' CACHEDIR/UUID/FILENAME. The cached files can be manipulated
#' using standard file system commands (removing, finding,
#' etc.). In this sense, the cache sytem is minimalist in design.
#'
#' @examples
#' gdc_cache()
#' \dontrun{
#' gdc_set_cache(getwd())
#' }
#'
#' @export
gdc_cache = function()
{
cache_dir = getOption('gdc_cache',gdc_set_cache(verbose=FALSE))
if(!dir.exists(cache_dir)) {
gdc_set_cache(cache_dir)
}
return(cache_dir)
}
#' @describeIn gdc_cache (Re)set the GenomicDataCommons cache
#' directory
#'
#' @importFrom utils menu
#' @importFrom rappdirs app_dir
#'
#'
#' @param create_without_asking logical(1) specifying whether to allow
#' the function to create the cache directory without asking the
#' user first. In an interactive session, if the cache directory
#' does not exist, the user will be prompted before creation.
#'
#' @param verbose logical(1) whether or not to message the location of
#' the cache directory after creation.
#'
#' @param directory character(1) directory path, will be created
#' recursively if not present.
#'
#'
#' @return the created directory (invisibly)
#'
#' @export
gdc_set_cache = function(directory = rappdirs::app_dir(appname =
"GenomicDataCommons")$cache(),
verbose = TRUE,
create_without_asking = !interactive())
{
create_path = function(directory) {
dir.create(directory, recursive = TRUE, showWarnings =
FALSE)
}
if(is.character(directory) & length(directory)==1) {
# if directory exists, move on
if(!dir.exists(directory)) {
# if not in an interactive session, go
# ahead and create directory without user
# input.
if(create_without_asking) {
create_path(directory)
} else {
# If in an interactive environment,
# go ahead and ask user for agreement.
response = menu(c("Yes", "No"),
title=sprintf("Would you like to create a GDC Cache directory at %s", directory))
if(response == 1) {
create_path(directory)
} else {
stop("GDC Cache directory cannot be created without user agreement")
}
}
}
options('gdc_cache' = directory)
} else {
stop("directory should be a character(1)")
}
if(verbose) message("GDC Cache directory set to: ", directory)
invisible(directory)
}
<file_sep>#.unary_op <- function(left) {
# force(left)
# function(e1) {
# force(e1)
# list(op=e1,content=c(field=left,value=c(right)))
# }
#}
#' @importFrom jsonlite unbox
.binary_op <- function(sep) {
force(sep)
function(e1, e2) {
force(e1)
force(e2)
list(op=unbox(sep),content=list(field=e1,value=e2))
}
}
.missing_op <- function(sep) {
force(sep)
function(e1) {
force(e1)
list(op=unbox(sep), content = list(field = e1, value = "MISSING"))
}
}
.negate_op <- function(sep) {
force(sep)
function(op) {
force(op)
list(op = unbox(sep),
content = list(
field = op$content$field,
value = op$content$value)
)
}
}
#' @importFrom jsonlite unbox
.combine_op <- function(sep) {
force(sep)
function(e1, e2) {
force(e1)
force(e2)
return(list(op=unbox(sep),content=list(e1,e2)))
}
}
#.f_env = new.env(parent=emptyenv())
.f_env = list()
.f_env$`==` = .binary_op('=')
.f_env$`!=` = .binary_op('!=')
.f_env$`<` = .binary_op('<')
.f_env$'>' = .binary_op('>')
.f_env$'&' = .combine_op('and')
.f_env$'|' = .combine_op('or')
.f_env$`<=` = .binary_op('<=')
.f_env$'>=' = .binary_op('>=')
.f_env$'%in%' = .binary_op('in')
.f_env$'%exclude%' = .binary_op('exclude')
.f_env$`missing` = .missing_op("is")
.f_env$'!' = .negate_op("NOT")
#' Create NCI GDC filters for limiting GDC query results
#'
#' Searching the NCI GDC allows for complex filtering based
#' on logical operations and simple comparisons. This function
#' facilitates writing such filter expressions in R-like syntax
#' with R code evaluation.
#'
#' If used with available_fields, "bare" fields that are
#' named in the available_fields character vector can be used
#' in the filter expression without quotes.
#'
#' @param expr a lazy-wrapped expression or a formula RHS equivalent
#'
#' @param available_fields a character vector of the
#' additional names that will be injected into the
#' filter evaluation environment
#'
#' @return a \code{list} that represents an R version
#' of the JSON that will ultimately be used in an
#' NCI GDC search or other query.
#'
#' @importFrom rlang eval_tidy f_rhs f_env
#'
#' @export
make_filter = function(expr,available_fields) {
available_fields=as.list(available_fields)
names(available_fields)=available_fields
filt_env = c(as.list(.f_env),available_fields)
if(is_formula(expr)) {
return(rlang::eval_tidy(rlang::f_rhs(expr), data=filt_env, env = rlang::f_env(expr)))
} else {
return(rlang::eval_tidy(expr,data=filt_env))
}
}
#' Manipulating GDCQuery filters
#'
#' @name filtering
#'
#' @return A \code{\link{GDCQuery}} object with the filter
#' field replaced by specified filter expression
#'
#' @examples
#' # make a GDCQuery object to start
#' #
#' # Projects
#' #
#' pQuery = projects()
#'
#' # check for the default fields
#' # so that we can use one of them to build a filter
#' default_fields(pQuery)
#' pQuery = filter(pQuery,~ project_id == 'TCGA-LUAC')
#' get_filter(pQuery)
#'
#' #
#' # Files
#' #
#' fQuery = files()
#' default_fields(fQuery)
#'
#' fQuery = filter(fQuery,~ data_format == 'VCF')
#' # OR
#' # with recent GenomicDataCommons versions:
#' # no "~" needed
#' fQuery = filter(fQuery, data_format == 'VCF')
#'
#' get_filter(fQuery)
#'
#' fQuery = filter(fQuery,~ data_format == 'VCF'
#' & experimental_strategy == 'WXS'
#' & type == 'simple_somatic_mutation')
#'
#' files() %>% filter(~ data_format == 'VCF'
#' & experimental_strategy=='WXS'
#' & type == 'simple_somatic_mutation') %>% count()
#'
#'
#' files() %>% filter( data_format == 'VCF'
#' & experimental_strategy=='WXS'
#' & type == 'simple_somatic_mutation') %>% count()
#'
#' # Filters may be chained for the
#' # equivalent query
#' #
#' # When chained, filters are combined with logical AND
#'
#' files() %>%
#' filter(~ data_format == 'VCF') %>%
#' filter(~ experimental_strategy == 'WXS') %>%
#' filter(~ type == 'simple_somatic_mutation') %>%
#' count()
#'
#' # OR
#'
#' files() %>%
#' filter( data_format == 'VCF') %>%
#' filter( experimental_strategy == 'WXS') %>%
#' filter( type == 'simple_somatic_mutation') %>%
#' count()
#'
#' # Use str() to get a cleaner picture
#' str(get_filter(fQuery))
NULL
#' The \code{filter} is simply a safe accessor for
#' the filter element in \code{\link{GDCQuery}} objects.
#'
#' @param x the object on which to set the filter list
#' member
#' @param expr a filter expression in the form of
#' the right hand side of a formula, where bare names
#' (without quotes) are allowed if they are available
#' fields associated with the GDCQuery object, \code{x}
#'
#' @rdname filtering
#'
#' @export
filter = function(x,expr) {
UseMethod('filter',x)
}
#' @rdname filtering
#'
#' @importFrom rlang enquo is_formula
#'
#' @export
filter.GDCQuery = function(x,expr) {
filt = try({
if(rlang::is_formula(expr))
make_filter(expr,available_fields(x))
}, silent=TRUE)
if(inherits(filt, "try-error"))
filt = make_filter(enquo(expr), available_fields(x))
if(!is.null(x$filters))
x$filters=list(op="and", content=list(x$filters,filt))
else
x$filters = filt
return(x)
}
#' The \code{get_filter} is simply a safe accessor for
#' the filter element in \code{\link{GDCQuery}} objects.
#'
#' @rdname filtering
#'
#'
#' @export
get_filter = function(x) {
UseMethod('get_filter',x)
}
#' @rdname filtering
#'
#' @export
get_filter.GDCQuery = function(x) {
return(x$filters)
}
<file_sep>library(GenomicDataCommons)
context('cache_control')
cache = gdc_cache()
test_that("getting cache returns length 1 char vector", {
expect_length(gdc_cache(),1)
expect_true(is.character(gdc_cache()))
})
test_that("setting cache works", {
expect_equal(gdc_set_cache('/tmp'),'/tmp')
expect_equal(gdc_cache(),'/tmp')
})
test_that("setting cache error checking works", {
expect_error(gdc_set_cache(1))
expect_error(gdc_set_cache(c('a','b')))
})
gdc_set_cache(cache)
<file_sep>library(GenomicDataCommons)
context('readHTSeqFile')
test_that("readHTSeqFile works on example data", {
dat = readHTSeqFile(system.file(package="GenomicDataCommons",
'extdata/example.htseq.counts.gz'))
expect_equal(nrow(dat),50)
expect_equal(ncol(dat),2)
})
<file_sep>#' S3 Generic to return all GDC fields
#'
#' @param x A character(1) string ('cases','files','projects',
#' 'annotations') or an subclass of \code{\link{GDCQuery}}.
#' @return a character vector of the default fields
#'
#' @examples
#' available_fields('projects')
#' projQuery = query('projects')
#' available_fields(projQuery)
#'
#' @export
available_fields = function(x) {
UseMethod('available_fields',x)
}
#' @describeIn available_fields GDCQuery method
#' @export
available_fields.GDCQuery = function(x) {
return(mapping(entity_name(x))$field)
}
#' @describeIn available_fields character method
#' @export
available_fields.character = function(x) {
stopifnot(length(x)==1,x %in% .gdc_entities)
return(mapping(x)$field)
}
#' S3 Generic to return default GDC fields
#'
#' @param x A character string ('cases','files','projects',
#' 'annotations') or an subclass of \code{\link{GDCQuery}}.
#' @return a character vector of the default fields
#'
#' @examples
#' default_fields('projects')
#' projQuery = query('projects')
#' default_fields(projQuery)
#'
#' @export
default_fields = function(x) {
UseMethod('default_fields',x)
}
#' @describeIn default_fields character method
#' @export
default_fields.character = function(x) {
defaults=NA # just to avoid no visible binding note
stopifnot(length(x)==1,x %in% .gdc_entities)
return(subset(mapping(x),defaults)$field)
}
#' @describeIn default_fields GDCQuery method
#' @export
default_fields.GDCQuery = function(x) {
return(default_fields(entity_name(x)))
}
#' S3 generic to set GDCQuery fields
#'
#' @param x the objects on which to set fields
#' @param fields a character vector specifying the fields
#'
#'
#' @return A \code{\link{GDCQuery}} object, with the fields
#' member altered.
#'
#' @examples
#' gProj = projects()
#' gProj$fields
#' head(available_fields(gProj))
#' default_fields(gProj)
#'
#' gProj %>%
#' select(default_fields(gProj)[1:2]) %>%
#' response() %>%
#' str(max_level=2)
#'
#' @export
select <- function(x,fields) {
UseMethod('select',x)
}
#" (internal) rectify specified fields with available fields
.gdcRectifyFieldsForEntity <- function(entity,fields) {
af = available_fields(entity)
mismatches = fields[!(fields %in% af)]
if(length(mismatches)>0)
stop(sprintf('fields specified included fields not available in %s including (%s)',entity,mismatches))
fields = union(paste0(sub('s$','',entity),"_id"),fields)
return(fields)
}
#' @describeIn select set fields on a GDCQuery object
#' @export
select.GDCQuery <- function(x,fields) {
x$fields = .gdcRectifyFieldsForEntity(entity_name(x),fields)
return(x)
}
#' Find matching field names
#'
#' This utility function allows quick text-based search of available
#' fields for using \code{\link{grep}}
#'
#' @param entity one of the available gdc entities ('files','cases',...)
#' against which to gather available fields for matching
#'
#' @param pattern A regular expression that will be used
#' in a call to \code{\link{grep}}
#'
#' @param ... passed on to grep
#'
#' @param value logical(1) whether to return values as opposed
#' to indices (passed along to grep)
#'
#' @return character() vector of field names matching
#' \code{pattern}
#'
#' @examples
#' grep_fields('files','analysis')
#'
#' @export
grep_fields <- function(entity,pattern,...,value=TRUE) {
stopifnot(entity %in% .gdc_entities)
return(grep(pattern=pattern,
x=available_fields(entity),
value=TRUE,...))
}
#' Find common values for a GDC field
#'
#' @param entity character(1), a GDC entity ("cases", "files", "annotations", "projects")
#' @param field character(1), a field that is present in the entity record
#' @param legacy logical(1), DEPRECATED; use the legacy endpoint or not.
#'
#' @return character vector of the top 100 (or fewer) most frequent
#' values for a the given field
#'
#' @examples
#' available_values('files','cases.project.project_id')[1:5]
#'
#' @export
available_values <- function(entity,field,legacy=FALSE) {
stopifnot(entity %in% .gdc_entities)
if (legacy)
.Deprecated(
msg = paste0("The 'legacy' argument is deprecated.\n",
"See help(\"GDC-deprecated\")")
)
agg = query(entity) %>% facet(field) %>% aggregations()
agg[[field]]$key
}
#' S3 Generic that returns the field description text, if available
#'
#' @param entity character(1) string ('cases','files','projects',
#' 'annotations', etc.) or an subclass of \code{\link{GDCQuery}}.
#'
#' @param field character(1), the name of the field that will be used to look
#' up the description.
#'
#' @return character(1) descriptive text or character(0) if no description
#' is available.
#'
#' @examples
#' field_description('cases', 'annotations.category')
#' casesQuery = query('cases')
#' field_description(casesQuery, 'annotations.category')
#' field_description(cases(), 'annotations.category')
#'
#' @export
field_description = function(entity, field) {
UseMethod('field_description',entity)
}
#' @describeIn field_description GDCQuery method
#' @export
field_description.GDCQuery = function(entity, field) {
stopifnot(length(field)==1)
m = mapping(entity_name(entity))
return(m$description[m$field==field])
}
#' @describeIn field_description character method
#' @export
field_description.character = function(entity, field) {
stopifnot(length(entity)==1,entity %in% .gdc_entities)
stopifnot(length(field)==1)
m = mapping(entity)
return(m$description[m$field==field])
}
<file_sep>#' Bulk data download
#'
#' The GDC maintains a special tool,
#' \href{the GDC Data Transfer Tool}{https://docs.gdc.cancer.gov/Data_Transfer_Tool/Users_Guide/Getting_Started/},
#' that enables high-performance, potentially parallel, and
#' resumable downloads. The Data Transfer Tool is an external
#' program that requires separate download. Due to recent changes in the
#' GDC API, the transfer function now validates the version of the `gdc-client`
#' to ensure reliable downloads.
#'
#' @param uuids character() vector of GDC file UUIDs
#'
#' @param args character() vector specifying command-line arguments to
#' be passed to \code{gdc-client}. See \code{\link{transfer_help}} for
#' possible values. The arguments \code{--manifest}, \code{--dir},
#' and \code{--token-file} are determined by \code{manifest},
#' \code{destination_dir}, and \code{token}, respectively, and
#' should NOT be provided as elements of \code{args}.
#'
#' @param token character(1) containing security
#' token allowing access to restricted data. See
#' \url{https://gdc-docs.nci.nih.gov/API/Users_Guide/Authentication_and_Authorization/}.
#' Note that the GDC transfer tool requires a file for data
#' transfer. Therefore, this token will be written to a temporary
#' file (with appropriate permissions set).
#'
#' @param overwrite logical(1) default FALSE indicating whether
#' existing files with identical name should be over-written.
#'
#' @return character(1) directory path to which the files were
#' downloaded.
#'
#' @examples
#' \dontrun{
#' uuids = files() %>%
#' filter(access == "open") %>%
#' results() %>%
#' ids()
#' file_paths <- transfer(uuids)
#' file_paths
#' names(file_paths)
#' # and with authenication
#' # REQUIRES gdc_token
#' # destination <- transfer(uuids,token=gdc_token())
#' }
#'
#' @importFrom utils read.table
#' @export
transfer <-
function(uuids, args=character(), token=NULL, overwrite=FALSE)
{
stopifnot(is.character(uuids))
destination_dir <- gdc_cache()
manifest = files() %>%
GenomicDataCommons::filter( ~ file_id %in% uuids ) %>%
GenomicDataCommons::manifest()
manifest_file = write_manifest(manifest)
dir_arg <- sprintf("--dir %s", destination_dir)
manifest_arg <- sprintf("--manifest %s", manifest_file)
token_file = tempfile()
if (!is.null(token)) {
writeLines(token,con=token_file)
stopifnot(file.exists(token_file))
Sys.chmod(token_file,mode="600")
token <- sprintf("--token-file %s", token_file)
}
gdc_client_version_validate()
args <- paste(c("download", dir_arg, manifest_arg, args, token), collapse=" ")
system2(gdc_client(), args)
if(!is.null(token))
unlink(token_file)
filepaths <- file.path(gdc_cache(), uuids,
as.character(manifest[[2]]))
names(filepaths) = uuids
return(filepaths)
}
#' return gdc-client executable path
#'
#' This function is a convenience function to
#' find and return the path to the GDC Data Transfer
#' Tool executable assumed to be named 'gdc-client'.
#' The assumption is that the appropriate version of the
#' GDC Data Transfer Tool is a separate download available
#' from \href{the GDC website}{https://gdc.cancer.gov/access-data/gdc-data-transfer-tool}
#' and as a backup from \href{on github}{https://github.com/NCI-GDC/gdc-client}.
#'
#' @details
#' The path is checked in the following order:
#' \enumerate{
#' \item an R option("gdc_client")
#' \item an environment variable GDC_CLIENT
#' \item from the search PATH
#' \item in the current working directory
#' }
#'
#' @return character(1) the path to the gdc-client executable.
#'
#' @examples
#' # this cannot run without first
#' # downloading the GDC Data Transfer Tool
#' gdc_client = try(gdc_client(),silent=TRUE)
#'
#' @export
gdc_client = function() {
if(!is.null(getOption('gdc_client')))
if(file.exists(getOption('gdc_client')))
return(getOption('gdc_client'))
if(file.exists(Sys.getenv("GDC_CLIENT")))
return(Sys.getenv("GDC_CLIENT"))
if(!(Sys.which("gdc-client")==''))
return(Sys.which("gdc-client"))
client=dir('.',pattern='^gdc-client$',full.names=TRUE)
if(length(client)==1)
if(client=='./gdc-client')
return(client)
stop('gdc_client not found. Be sure to install the command \nline GDC client available from the GDC website.')
}
gdc_client_version <- function() {
gc_loc <- gdc_client()
vers <- system2(gc_loc, "--version", stdout = TRUE, stderr = TRUE)
vers <- gsub("^v", "", vers)
package_version(vers)
}
.GDC_COMPATIBLE_VERSION <- "1.3.0"
#' @describeIn transfer
#'
#' If you are using the 'client' option, your `gdc-client` should be
#' up-to-date (>= 1.3.0).
#'
#' @param valid_version character(1) The last known version that works for the
#' current data release for which to validate against, not typically changed
#' by the end-user.
#'
#' @export
gdc_client_version_validate <-
function(valid_version = .GDC_COMPATIBLE_VERSION)
{
client_ver <- gdc_client_version()
if (client_ver < package_version(valid_version))
stop("Update the 'gdc_client' to a version >= ", valid_version)
}
#' \code{transfer_help()} queries the the command line GDC Data
#' Transfer Tool, \code{gdc-client}, for available options to be used
#' in the \code{\link{transfer}} command.
#'
#' @describeIn transfer
#'
#' @export
transfer_help <- function() {
system2(gdc_client(), "download -h")
}
<file_sep>#" (internal) Extract header field element from httr response
#' @importFrom httr headers
.gdc_header_elt <- function(response, field, element) {
value <- headers(response)[[field]]
if (is.null(value))
stop("response header does not contain field '", field, "'")
value <- strsplit(strsplit(value, "; *")[[1L]], "= *")
key <- vapply(value, `[[`, character(1), 1L)
idx <- element == key
if (sum(idx) != 1L)
stop("response header field '", field,
"' does not contain unique element '", element, "'")
value[[which(idx)]][[2]]
}
#" (internal) Rename a file 'from' to 'to'
.gdc_file_rename <- function(from, to, overwrite) {
if (overwrite && file.exists(to))
unlink(to)
reason <- NULL
status <- withCallingHandlers({
file.rename(from, to)
}, warning=function(w) {
reason <<- conditionMessage(w)
invokeRestart("muffleWarning")
})
unlink(from)
if (!status)
stop("failed to rename downloaded file:\n",
"\n from: '", from, "'",
"\n to: '", to, "'",
"\n reason:",
"\n", .wrapstr(reason))
else if (!is.null(reason))
warning(reason) # forward non-fatal file rename warning
to
}
#" (internal) GET endpoint / uri
#' @importFrom httr GET add_headers stop_for_status
.gdc_get <-
function(endpoint, parameters=list(), legacy=FALSE, token=NULL, ..., base=.gdc_base)
{
stopifnot(is.character(endpoint), length(endpoint) == 1L)
uri <- sprintf("%s/%s", base, endpoint)
if(legacy)
.Deprecated(
msg = paste0("The 'legacy' argument is deprecated.\n",
"See help(\"GDC-deprecated\")")
)
uri <- sprintf("%s%s", uri, .parameter_string(parameters))
if(getOption('gdc.verbose',FALSE)) {
message("GET request uri:\n",uri)
}
response <- GET(uri, add_headers(`X-Auth-Token`=token),
#config = httr::config(ssl_verifypeer = FALSE),
...)
stop_for_status(response)
response
}
#" (internal) POST endpoint / uri
#' @importFrom httr POST add_headers write_disk stop_for_status
.gdc_post <-
function(endpoint, body, legacy=FALSE, token=NULL, ..., base=.gdc_base)
{
stopifnot(is.character(endpoint), length(endpoint) == 1L)
uri <- sprintf("%s/%s", base, endpoint)
if (legacy)
.Deprecated(
msg = paste0("The 'legacy' argument is deprecated.\n",
"See help(\"GDC-deprecated\")")
)
if(getOption('gdc.verbose',FALSE)) {
message("POST request uri:\n",uri)
message("POST body: ",jsonlite::toJSON(body))
}
if('fields' %in% names(body))
body[['fields']] = paste0(body[['fields']],collapse=',')
response <- POST(
uri, add_headers(
`X-Auth-Token` = token,
Accept = "application/json",
`Content-Type` = "application/json"
),
...,
#config = httr::config(ssl_verifypeer = FALSE),
body=body, encode="json")
stop_for_status(response)
}
#" (internal) Download one file from GDC, renaming to remote filename
#' @importFrom httr GET write_disk add_headers stop_for_status
.gdc_download_one <-
function(uri, destination, overwrite, progress, token=NULL, base=.gdc_base)
{
uri = sprintf('%s/%s',base,uri)
if(getOption('gdc.verbose',FALSE)) {
message("GET request uri:\n",uri)
}
if(!dir.exists(destination)) {
dir.create(destination)
}
destfile = file.path(destination, '.partial_download')
response <- GET(uri, write_disk(destfile, overwrite = TRUE),
if (progress) progress() else NULL,
add_headers(`X-Auth-Token`=token))
stop_for_status(response)
if (progress) cat("\n")
filename <- .gdc_header_elt(response, "content-disposition", "filename")
to <- file.path(destination, filename)
.gdc_file_rename(destfile, to, overwrite)
}
<file_sep>.cat0 <- function(..., sep=NULL)
cat(..., sep="")
.wrapstr <- function(x)
paste(strwrap(paste(x, collapse=", "), indent=4, exdent=4), collapse="\n")
.dir_validate_or_create <- function(destination_dir) {
stopifnot(is.character(destination_dir), length(destination_dir) == 1L,
nzchar(destination_dir))
if (!dir.exists(destination_dir)) {
if (!file.exists(destination_dir))
dir.create(destination_dir, recursive = TRUE)
else
stop("'destination_dir' exists but is not a directory")
}
}
#" (internal) return character(0) instead of NULL
#"
#" Always return a vector and not NULL.
.ifNullCharacterZero <- function(x) {
if(is.null(x))
return(character(0))
return(x)
}
<file_sep>#' @name GDC-deprecated
#'
#' @title Deprecated functionality in the `GenomicDataCommons` package
#'
#' @aliases legacy legacy.GDCQuery
#'
#' @description
#' The `legacy` endpoint was deprecated as part of the GDC API release version
#' `v3.28.0`. This means that legacy data is no longer available via the
#' GDC API.
#'
#' @details
#' This includes the S3 generic and method for setting the legacy parameter
#' (`legacy` and `legacy.GDCQuery`)
#'
#' @param x the objects on which to set fields
#'
#' @param legacy logical(1) DEPRECATED; Whether or not to use the GDC legacy
#' archives
#'
#' @return A \code{\link{GDCQuery}} object with the \code{legacy}
#' member altered.
#'
#' @seealso
#' \url{https://docs.gdc.cancer.gov/API/Release_Notes/API_Release_Notes/#v3280}
#'
#' @examples
#' qcases <- query("cases")
#'
#' legacy(qcases, legacy = FALSE)
#'
#' @export
legacy <- function(x, legacy) {
UseMethod('legacy')
}
#' @describeIn GDC-deprecated set legacy field on a GDCQuery object
#' @export
legacy.GDCQuery <- function(x, legacy) {
stopifnot(is.logical(legacy), length(legacy) == 1L, !is.na(legacy))
if (legacy)
.Deprecated(
msg = paste0("The 'legacy' argument is deprecated.\n",
"See help(\"GDC-deprecated\")")
)
return(x)
}
<file_sep>#' Read DNAcopy results into GRanges object
#'
#' @param fname The path to a DNAcopy-like file.
#' @param ... passed to \code{\link[readr]{read_tsv}}
#' @return a \code{\link[GenomicRanges]{GRanges}} object
#'
#' @importFrom readr read_tsv
#' @import GenomicRanges
#' @importFrom IRanges IRanges
#'
#' @examples
#' fname = system.file(package='GenomicDataCommons',
#' 'extdata/dnacopy.tsv.gz')
#' dnac = readDNAcopy(fname)
#' class(dnac)
#' length(dnac)
#'
#' @export
readDNAcopy <- function(fname,...) {
stopifnot(file.exists(fname))
res = read_tsv(fname,...)
stopifnot(ncol(res)==6)
return(GRanges(seqnames=res[[2]],
ranges=IRanges(start=res[[3]],end=res[[4]]),
sampleName = res[[1]],
Num_Probes = res[[5]],
value = res[[6]]))
}
<file_sep>#' return a gdc token from file or environment
#'
#' The GDC requires an auth token for downloading
#' data that are "controlled access". For example,
#' BAM files for human datasets, germline variant calls,
#' and SNP array raw data all are protected as "controlled
#' access". For these files, a GDC access token is required.
#' See the \href{details on the GDC authentication and token information}{https://docs.gdc.cancer.gov/Data_Portal/Users_Guide/Authentication/#gdc-authentication-tokens}.
#' Note that this function simply returns a string value.
#' It is possible to keep the GDC token in a variable in R
#' or to pass a string directly to the appropriate parameter.
#' This function is simply a convenience function for alternative
#' approaches to get a token from an environment variable
#' or a file.
#'
#'
#' @details
#' This function will resolve locations of the GDC token in the
#' following order:
#' \itemize{
#' \item{from the environment variable, \code{GDC_TOKEN}, expected to
#' contain the token downloaded from the GDC as a string}
#' \item{using \code{readLines} to read a file named in the environment
#' variable, \code{GDC_TOKEN_FILE}}
#' \item{using \code{readLines} to read from a file called \code{.gdc_token} in the user's
#' home directory}
#' }
#' If all of these fail, this function will return an error.
#'
#' @return character(1) (invisibly, to protect against inadvertently printing) the GDC token.
#'
#' @references \url{https://docs.gdc.cancer.gov/Data_Portal/Users_Guide/Cart/#gdc-authentication-tokens}
#'
#' @examples
#' # This will not run before a GDC token
#' # is in place.
#' token = try(gdc_token(),silent=TRUE)
#'
#'
#' @export
gdc_token <- function() {
if(Sys.getenv('GDC_TOKEN')!='') return(Sys.getenv('GDC_TOKEN'))
token_file = "~/.gdc_token"
if(Sys.getenv('GDC_TOKEN_FILE')!='')
token_file = trimws(Sys.getenv('GDC_TOKEN_FILE'))
stopifnot(file.exists(token_file))
invisible(suppressWarnings(readLines(token_file,n=1)))
}
<file_sep>## Changes in version 1.24.0
### New features
* The GDC API has deprecated the legacy endpoint (#110, @LiNk-NY)
### Bug fixes and minor improvements
* `gdc_clinical` handles `NULL` responses when diagnoses are not available for
all IDs queried (#109, @zx8754).
* Minor updates to somatic mutations vignette and unit tests.
## Changes in version 1.20.0
### New features
* `gdcdata` has an ellipses argument to download data from the legacy archive,
e.g., `legacy = TRUE` (#84, @LiNk-NY)
* `missing` (`is MISSING`) and `!missing` (`NOT MISSING`) operations implemented
for filtering queries, see vignette (#96, @LiNk-NY)
* `gdc-client` version can be validated against last known good version based on
data release (#99, @LiNk-NY)
### Bug fixes and minor improvements
* `gdc_clinical` uses `readr::type_convert` to handle columns with inconsistent
types from the API.
* update examples in documentation and vignette based on new data release
<file_sep>#' Download GDC files
#'
#' Download one or more files from GDC. Files are downloaded using the
#' UUID and renamed to the file name on the remote system. By default,
#' neither the uuid nor the file name on the remote system can exist.
#'
#' This function is appropriate for one or several files; for large
#' downloads use \code{\link{manifest}} to create a manifest for and
#' the GDC Data Transfer Tool.
#'
#' @param uuids character() of GDC file UUIDs.
#'
#' @param use_cached logical(1) default TRUE indicating that,
#' if found in the cache, the file will not be downloaded
#' again. If FALSE, all supplied uuids will be re-downloaded.
#'
#' @param progress logical(1) default TRUE in interactive sessions,
#' FALSE otherwise indicating whether a progress par should be
#' produced for each file download.
#'
#' @param access_method character(1), either 'api' or 'client'. See details.
#'
#' @param transfer_args character(1), additional arguments to pass to
#' the gdc-client command line. See \code{\link{gdc_client}} and
#' \code{\link{transfer_help}} for details.
#'
#' @param token (optional) character(1) security token allowing access
#' to restricted data. See
#' \url{https://gdc-docs.nci.nih.gov/API/Users_Guide/Authentication_and_Authorization/}.
#'
#' @param ... further arguments passed to files, particularly useful when
#' requesting \code{legacy=TRUE}
#'
#' @seealso \code{\link{manifest}} for downloading large data.
#'
#' @return a named vector with file uuids as the names and paths as
#' the value
#'
#' @details When access_method is "api", the GDC "data" endpoint is the
#' transfer mechanism used. The alternative access_method, "client", will
#' utilize the \code{gdc-client} transfer tool, which must be
#' downloaded separately and available. See
#' \code{\link{gdc_client}} for details on specifying the location
#' of the gdc-client executable.
#'
#'
#' @examples
#' # get some example file uuids
#' uuids <- files() %>%
#' filter(~ access == 'open' & file_size < 100000) %>%
#' results(size = 3) %>%
#' ids()
#'
#' # and get the data, placing it into the gdc_cache() directory
#' gdcdata(uuids, use_cached=TRUE)
#'
#' @export
gdcdata <-
function(uuids, use_cached=TRUE,
progress=interactive(), token=NULL, access_method='api',
transfer_args = character(), ...)
{
stopifnot(is.character(uuids))
uuids = trimws(uuids)
manifest = files(...) %>%
GenomicDataCommons::filter( ~ file_id %in% uuids ) %>%
GenomicDataCommons::manifest()
# files from previous downloads should have the following
# path and filenames
fs = file.path(gdc_cache(), manifest[["id"]], manifest[["file_name"]])
# Restrict new manifest to those that we need to download,
to_do_manifest = manifest[!file.exists(fs),]
# These are the uuids of the cache misses
missing_uuids = to_do_manifest[["id"]]
# And these are the cache hits
names(fs) = manifest[["id"]]
# Using API download to fetch missing uuids
endpoint <- "data"
cache_dir <- gdc_cache()
destinations <- file.path(cache_dir, missing_uuids)
if(access_method == 'api') {
uris <- sprintf("%s/%s", endpoint, missing_uuids)
value <- mapply(.gdc_download_one, uris, destinations,
MoreArgs=list(overwrite=!use_cached, progress=progress,
token=token),
SIMPLIFY=TRUE, USE.NAMES=FALSE)
names(value) <- missing_uuids
} else {
## in the future, may want to transition to
## passing the actual manifest, since we
## are going to regenerate it, anyway.
value = NULL
if(length(missing_uuids)>0)
value = transfer(missing_uuids, token = token, args = transfer_args)
}
# combine cache hits with cache misses
#
# Return vector of file file path, name=uuid
fs
}
|
6b793edcb3856fb39a00861c5068e42f34883d8c
|
[
"Markdown",
"R",
"RMarkdown"
] | 38
|
R
|
Bioconductor/GenomicDataCommons
|
007c2917f40412a3272dae41d6438ac5df284972
|
348e1879607e51dccd218229aa76746806386e17
|
refs/heads/master
|
<repo_name>Sorenfu/route_translator<file_sep>/lib/route_translator/extensions/action_controller.rb
require 'action_controller'
module ActionController
class Base
around_filter :set_locale_from_domain, :set_locale_from_url
def set_locale_from_url(&block)
I18n.with_locale params[RouteTranslator.locale_param_key], &block
end
def set_locale_from_domain
I18n.locale = extract_locale_from_tld || I18n.default_locale
end
# Get locale from top-level domain or return nil if such locale is not available
# You have to put something like:
# 127.0.0.1 application.com
# 127.0.0.1 application.it
# 127.0.0.1 application.pl
# in your /etc/hosts file to try this out locally
def extract_locale_from_tld
parsed_locale = request.host.split('.').last
I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
end
end
end
|
166b5b8f941ecdb24d8e1d92c6a91d5d352f7dbe
|
[
"Ruby"
] | 1
|
Ruby
|
Sorenfu/route_translator
|
790bb952653a1b1c0cfbdfc2e3288dc6b5f27898
|
bb34a27c863fd65c1bca2005de56382c7031fb81
|
refs/heads/master
|
<repo_name>rifqirianputra/Pokemon_PythonDex<file_sep>/Pokemon PythonDex.py
import requests
import json
controlloop = ''
while controlloop != 1:
print('===============================')
print('====The Pokemon PythonDex======')
inputpoke = input('please input Pokemon name: ').lower()
if inputpoke == 'exit':
break
else:
host = 'https://pokeapi.co/api/v2'
pokename =f'/pokemon/{inputpoke}'
pokeurl = host + pokename
data = requests.get(pokeurl)
try:
data = data.json()
# with open('poke.json','w') as dt:
# json.dump(data, dt)
# with open ('poke.json','r') as js:
# dataImport = json.load(js)
# print(data)
print((f'Pokemon Name: {inputpoke}').capitalize())
pokestat = data['stats']
print('Pokemon Stats: ')
for i in pokestat:
print(i['stat']['name'],(':'), i['base_stat'])
poketype = data['types']
print('Pokemon Type: ')
for i in poketype:
print(i['type']['name'])
pokedata = data['abilities']
print('Ability: ')
for i in pokedata:
print(i['ability']['name'])
except:
print('Pokemon not found, try again')
|
8cdf5e678cae3e6e72f9fe165d0e45e3c12d9f41
|
[
"Python"
] | 1
|
Python
|
rifqirianputra/Pokemon_PythonDex
|
22db1ee547b12d4b8e937e3e504676f240f44286
|
f512b2084bd5d279a1165cfc7d6d754dc4daacbd
|
refs/heads/master
|
<file_sep>import styled from 'styled-components'
export const ListParagraph = styled.p`
font-size: 18px;
line-height: 30px;
color: rgba(255, 255, 255, 0.75);
@media ${props => props.theme.breakpoints.md}{
font-size: 16px;
line-height: 28px;
}
@media ${props => props.theme.breakpoints.sm}{
font-size: 14px;
line-height: 22px;
}
`<file_sep>import Link from 'next/link';
import React from 'react';
import { AiFillGithub, AiFillLinkedin } from 'react-icons/ai';
import { DiCode } from 'react-icons/di';
import { Container, Div1, Div3, NavLink, SocialIcons, Span } from './HeaderStyles';
const Header = () => (
<Container>
<Div1>
<a style={{ display: "flex", alignItems: "center", color: "white" , marginBottom: "30px", marginTop: "-3px"}}>
<DiCode size="4rem"/> <Span>lucaskrms portfolio</Span>
</a>
</Div1>
<Div3>
<SocialIcons href="https://www.linkedin.com/in/lucaskermessi/">
<AiFillLinkedin size="3rem"/>
</SocialIcons>
<SocialIcons href="https://github.com/lucaskrms">
<AiFillGithub size="3rem"/>
</SocialIcons>
</Div3>
</Container>
);
export default Header;
|
c7c82c47d1db6e6c6dd64ff9f7983374b49f4269
|
[
"JavaScript"
] | 2
|
JavaScript
|
lucaskrms/portfolioReact
|
5f351b5caf953aff17a59fc8a18879653b6eb27b
|
0b97e2395413577d2ec95db4a02671a6a8a4cce9
|
refs/heads/master
|
<file_sep>//
// QuizModel.swift
// IOSBasicsFun
//
// Created by <NAME> on 9/28/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
struct QuizModel {
// Parallel arrays
private let questions: [String]
private let answers: [String]
private var currentQuestionIndex: Int
init() {
questions = ["What was the 50th State?", "What is 1 + 1?", "What percentage of nuts do squirrels lose?"]
answers = ["Hawaii", "2", "80%"]
currentQuestionIndex = -1
}
// MARK: - Access Modifiers
// use access modifiers to control access to state and behavior
// internal: accessible anywhere within the app or framework (default)
// private: accessible only within this object
// private(set): internal plus private for write (read only anywhere except for creating object)
// fileprivate: accessible only within the source file
// open: used with frameworks
// public: used with frameworks
// API: application programming interface
mutating func getNextQuestion() -> String {
currentQuestionIndex += 1
currentQuestionIndex %= questions.count
return questions[currentQuestionIndex]
}
func getCurrentAnswer() -> String {
return answers[currentQuestionIndex]
}
}
<file_sep>//
// ViewController.swift
// IOSBasicsFun
//
// Created by <NAME> on 9/23/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
// MARK: - Overview of an iOS project
// the folders are not folders, they are groups
// changes to the groups do not change on disk
// iOSBasicsFun
// - AppDelegate.swift: middleman between your app and the OS
// Rest of notes on GitHub, Gina's version
class ViewController: UIViewController {
var quizModel = QuizModel()
@IBOutlet var questionLabel: UILabel!
@IBOutlet var answerLabel: UILabel!
@IBAction func nextQuestionPressed(_ sender: UIButton) {
print("Hello from nextQuestionPressed()")
showNextQuestion()
}
@IBAction func showAnswerPressed(_ sender: UIButton) {
print("Hello from showAnswerPressed()")
answerLabel.text = quizModel.getCurrentAnswer()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print("hello from viewDidLoad()")
questionLabel.text = "Hello from viewDidLoad()"
showNextQuestion()
}
func showNextQuestion() {
questionLabel.text = quizModel.getNextQuestion()
answerLabel.text = "<Answer>"
}
}
|
aeaa09187559030693f16372959d75b65bf63099
|
[
"Swift"
] | 2
|
Swift
|
ChloeRC/IOSBasicsFun
|
2f9217f00f2de2b082e7f9879131613cc6892ed7
|
35585c261e8f94516ae62c6346f5bed35b873e4a
|
refs/heads/master
|
<file_sep>INSERT INTO NewsPost (NewsPostID, Title, Content, PostDate) VALUES(1, 'News post Title', 'Some content in this news post.', '2018-12-31');
INSERT INTO PageContent (SectionID, SectionName, ContentValue) VALUES(1, 'About', '
<h4 class="card-text">Welcome to the Rubba Duck Webshop</h4>
<hp class="card-text">This is a complete fake webshop with very poor service.</hp>
');
INSERT INTO PageContent (SectionID, SectionName, ContentValue) VALUES(2, 'Contact', '
<adress>
<h4 class="card-text">Adress</h4>
<p class="card-text">Some street Name 1, 0000 .Nowhere</p>
<h4 class="card-text">Phone</h4>
<p class="card-text">+00 00 00 00 00</p>
<h4 class="card-text">Email</h4>
<p class="card-text"><EMAIL></p>
<h5 class="card-text">CVR</h5>
<p class="card-text">??00000000??</p>
</adress>
');
INSERT INTO PageContent (SectionID, SectionName, ContentValue) VALUES(3, 'Terms', 'Some content for the terms section.');
INSERT INTO PageContent (SectionID, SectionName, ContentValue) VALUES(4, 'Privacy', 'Some content for the privacy section.');
INSERT INTO Department (DepartmentID, DepartmentName) VALUES(1, 'Shop department');
INSERT INTO Adress (AdressID, Phone, StreetName, StreetNumber, FloorNumber, PostalCode, Country) VALUES(1, '004531400042', 'Some str.', '100', 'K', '9999', 'DK');
INSERT INTO User (UserID, Email, UserPassword, FirstName, LastName, AdressID) VALUES(1, '<EMAIL>', '<PASSWORD>add9a2', 'kode', 'ord', 1);
INSERT INTO AdminUser (AdminUserID, Title, DepartmentID, UserID) VALUES (1, 'Owner', 1, 1);
INSERT INTO Orders (OrderID, OrderDate, ShipDate, TotalCost, UserID) VALUES (1, '2018-12-31', '2019-01-02', 100, 1);
INSERT INTO Brand (BrandID, BrandName, BrandDescription, BrandLogo) VALUES (1, 'That Brand', 'The brand', 'default-brand.png');
INSERT INTO Product (ProductID, ProductName, ProductDescription, Size, Color, Prize, BrandID, Stock, Sold, ProductImage) VALUES (1, 'Top mordern', 'The best is the most popular!', 1, 'Shiny', 100, 1, 14, 8, 'imgs/rubber-ducks/white/duck1.jpg');
INSERT INTO Product (ProductID, ProductName, ProductDescription, Size, Color, Prize, BrandID, Stock, Sold, ProductImage) VALUES (2, 'The classic', 'True cult status.', 1, 'White', 85, 1, 16, 0, 'imgs/rubber-ducks/white/duck22.jpg');
INSERT INTO Product (ProductID, ProductName, ProductDescription, Size, Color, Prize, BrandID, Stock, Sold, ProductImage) VALUES (3, 'Old school', 'School is out 4 ever!', 1, 'White-widdow', 65, 1, 30, 4, 'imgs/rubber-ducks/white/duck28.png');
INSERT INTO Product (ProductID, ProductName, ProductDescription, Size, Color, Prize, BrandID, Stock, Sold, ProductImage) VALUES (4, 'New age', 'The new age has dawned.', 1, 'White-darkened', 105, 1, 21, 12, 'imgs/rubber-ducks/white/duck30.jpg');
INSERT INTO Product (ProductID, ProductName, ProductDescription, Size, Color, Prize, BrandID, Stock, Sold, ProductImage) VALUES (5, 'Black', 'Dark duck', 1, 'Black', 15, 1, 10, 0, 'imgs/rubber-ducks/black/duck10.jpg');
INSERT INTO Product (ProductID, ProductName, ProductDescription, Size, Color, Prize, BrandID, Stock, Sold, ProductImage) VALUES (6, 'Creeper', 'Weird and small', 1, 'Blacker', 95, 1, 54, 65, 'imgs/rubber-ducks/black/duck19.jpg');
INSERT INTO Product (ProductID, ProductName, ProductDescription, Size, Color, Prize, BrandID, Stock, Sold, ProductImage) VALUES (7, 'Regular', 'The normal one', 1, 'Yellow', 105, 1, 3, 43, 'imgs/rubber-ducks/yellow/duck3.jpg');
INSERT INTO Product (ProductID, ProductName, ProductDescription, Size, Color, Prize, BrandID, Stock, Sold, ProductImage) VALUES (8, 'Cute', 'The cutest duck there have ever been', 1, 'Yellow-ish', 105, 1, 1, 10, 'imgs/rubber-ducks/yellow/duck6.jpg');
INSERT INTO ShoppingCart (ShoppingCartID, OrderID, ProductID) VALUES (1, 1, 1);
INSERT INTO Rating (RatingID, Score, ProductID, UserID) VALUES (1, 5, 8, 1);
INSERT INTO Category (CategoryID, ProductID, CategoryName) VALUES (1, 1, 'Misc');
INSERT INTO Offer (OfferID, ProductID, OfferName, Discount, FromDate, ToDate) VALUES (1, 4, 'Discount', 10, '2018-12-29', '2018-12-30');
INSERT INTO Offer (OfferID, ProductID, OfferName, Discount, FromDate, ToDate) VALUES (2, 3, 'Wholesale', 50, '2018-12-29', '2018-12-30');
INSERT INTO Offer (OfferID, ProductID, OfferName, Discount, FromDate, ToDate) VALUES (3, 2, 'Seasonal', 25, '2018-12-29', '2018-12-30');
INSERT INTO NewsLetter (NewsLetterID, Title, Content, NewsDate, AdminID) VALUES (1, 'The news letter is here', 'Good luck!', '2018-12-24', 1);
INSERT INTO NewsLetter (Title, Content, NewsDate, AdminID) VALUES ('The news letter is here 2', 'Good luck 2 u!', '2018-12-25', 1);
INSERT INTO PageSettings (PageSettingName, PageSettingValue) VALUES ('SiteTitle', 'Rubba Duck Shop');
INSERT INTO PageSettings (PageSettingName, PageSettingValue) VALUES ('PageLogo', 'imgs/cms-logo.png');
INSERT INTO PageSettings (PageSettingName, PageSettingValue) VALUES ('FavIcon', 'favico.svg');<file_sep><?php
class Product
{
public $ProductID;
public $ProductName;
public $ProductDescription;
public $Size;
public $Color;
public $Prize;
public $BrandID;
public $Stock;
public $Sold;
public $ProductImage;
function __construct(string $ProductName, string $ProductDescription, int $Size, string $Color, int $Prize, int $BrandID, int $Stock, int $Sold, string $ProductImage)
{
$this->ProductName = $ProductName;
$this->ProductDescription = $ProductDescription;
$this->Size = $Size;
$this->Color = $Color;
$this->Prize = $Prize;
$this->BrandID = $BrandID;
$this->Stock = $Stock;
$this->Sold = $Sold;
$this->ProductImage = $ProductImage;
}
}
?><file_sep><?php
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rubba Duck Shop</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body id="top">
<?php require_once 'includes/main-navigation.html'; ?>
<div id="contentRef" class="pt-5 mt-5 my-5">
<?php include 'includes/page-header.html'; ?>
<?php include 'includes/featured-products.html'; ?>
<?php include 'includes/about.html'; ?>
<?php include 'includes/contact.html'; ?>
</div>
<?php require_once 'includes/footer.html'; ?>
<!-- html to be replaced by a tags with $ in href attribute -->
<div id="hiddenContent">
</div>
<div id="contentSwitch">
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="js/app.js"></script>
<script src="js/controller.js"></script>
</body>
</html><file_sep>DROP DATABASE IF EXISTS dbcms;
CREATE DATABASE dbcms;
USE dbcms;
CREATE TABLE NewsPost(
NewsPostID int NOT NULL AUTO_INCREMENT,
Title varchar(255) NOT NULL,
Content TEXT NOT NULL,
PostDate DATETIME NOT NULL,
PRIMARY KEY (NewsPostID)
);
CREATE TABLE PageContent(
SectionID int NOT NULL AUTO_INCREMENT,
SectionName varchar(255) NOT NULL,
ContentValue TEXT NOT NULL,
PRIMARY KEY (SectionID)
);
CREATE TABLE Department(
DepartmentID int NOT NULL AUTO_INCREMENT,
DepartmentName varchar(255) NOT NULL,
PRIMARY KEY (DepartmentID)
);
CREATE TABLE Adress(
AdressID int NOT NULL AUTO_INCREMENT,
Phone varchar(32) NOT NULL,
StreetName varchar(64) NOT NULL,
StreetNumber varchar(16) NOT NULL,
FloorNumber varchar(8) NOT NULL,
PostalCode varchar(16) NOT NULL,
Country varchar(64) NOT NULL,
PRIMARY KEY (AdressID)
);
CREATE TABLE User(
UserID int NOT NULL AUTO_INCREMENT,
Email varchar(255) NOT NULL,
UserPassword varchar(255) NOT NULL,
FirstName varchar(128) NOT NULL,
LastName varchar(255) NOT NULL,
AdressID int NOT NULL,
PRIMARY KEY (UserID),
FOREIGN KEY (AdressID) REFERENCES Adress(AdressID)
);
CREATE TABLE AdminUser(
AdminUserID int NOT NULL AUTO_INCREMENT,
Title varchar(64) NOT NULL,
DepartmentID int NOT NULL,
UserID int NOT NULL,
PRIMARY KEY (AdminUserID),
FOREIGN KEY (DepartmentID) REFERENCES Department(DepartmentID),
FOREIGN KEY (UserID) REFERENCES User(UserID)
);
CREATE TABLE Orders(
OrderID int NOT NULL AUTO_INCREMENT,
OrderDate DATETIME NOT NULL,
ShipDate DATETIME NOT NULL,
TotalCost int NOT NULL,
UserID int NOT NULL,
PRIMARY KEY (OrderID),
FOREIGN KEY (UserID) REFERENCES User(UserID)
);
CREATE TABLE Brand(
BrandID int NOT NULL AUTO_INCREMENT,
BrandName varchar(64) NOT NULL,
BrandDescription TEXT NOT NULL,
BrandLogo varchar(255) NOT NULL,
PRIMARY KEY (BrandID)
);
CREATE TABLE Product(
ProductID int NOT NULL AUTO_INCREMENT,
ProductName varchar(128) NOT NULL,
ProductDescription TEXT NOT NULL,
Size int NOT NULL,
Color varchar(64) NOT NULL,
Prize int NOT NULL,
BrandID int NOT NULL,
Stock int NOT NULL,
Sold int NOT NULL,
ProductImage varchar(255) NOT NULL,
PRIMARY KEY (ProductID),
FOREIGN KEY (BrandID) REFERENCES Brand(BrandID)
);
CREATE TABLE ShoppingCart(
ShoppingCartID int NOT NULL AUTO_INCREMENT,
OrderID int NOT NULL,
ProductID int NOT NULL,
PRIMARY KEY (ShoppingCartID),
FOREIGN KEY (OrderID) REFERENCES Orders(OrderID),
FOREIGN KEY (ProductID) REFERENCES Product(ProductID)
);
CREATE TABLE Rating(
RatingID int NOT NULL AUTO_INCREMENT,
Score int NOT NULL,
ProductID int NOT NULL,
UserID int NOT NULL,
PRIMARY KEY (RatingID),
FOREIGN KEY (ProductID) REFERENCES Product(ProductID),
FOREIGN KEY (UserID) REFERENCES User(UserID)
);
CREATE TABLE Category(
CategoryID int NOT NULL AUTO_INCREMENT,
ProductID int NOT NULL,
CategoryName varchar(64) NOT NULL,
PRIMARY KEY(CategoryID),
FOREIGN KEY (ProductID) REFERENCES Product(ProductID)
);
CREATE TABLE Offer(
OfferID int NOT NULL AUTO_INCREMENT,
ProductID int NOT NULL,
OfferName varchar(64) NOT NULL,
Discount int NOT NULL,
FromDate DATETIME NOT NULL,
ToDate DATETIME NOT NULL,
PRIMARY KEY(OfferID),
FOREIGN KEY (ProductID) REFERENCES Product(ProductID)
);
CREATE TABLE NewsLetter(
NewsLetterID int NOT NULL AUTO_INCREMENT,
Title varchar(64) NOT NULL,
Content TEXT NOT NULL,
NewsDate DATETIME NOT NULL,
AdminID int NOT NULL,
PRIMARY KEY (NewsLetterID),
FOREIGN KEY (AdminID) REFERENCES AdminUser(AdminUserID)
);
CREATE TABLE PageSettings(
PageSettingName varchar(255) NOT NULL,
PageSettingValue TEXT NOT NULL
);<file_sep><?php
class Admin
{
public $AdminUserID;
public $Title;
public $DepartmentID;
public $UserID;
function __construct(string $Title, int $DepartmentID, int $UserID)
{
$this->Title = $Title;
$this->DepartmentID = $DepartmentID;
$this->UserID = $UserID;
}
}
?><file_sep><?php
require_once('ShopController.php');
require_once('database/AdminDatabase.php');
require_once('models/Vat.php');
require_once('models/User.php');
require_once('models/Admin.php');
require_once('models/Product.php');
require_once('models/HtmlElementClass.php');
require_once('models/NewsPost.php');
require_once('models/Order.php');
require_once('models/Adress.php');
class AdminController extends ShopController
{
function __construct(string $action, string $method, $userID, $orderID)
{
parent::__construct($action, $method, $userID, $orderID);
$this->database = new AdminDatabase();
}
function route()
{
if(isset($this->userID) === false)
{
return ['status' => 'error', 'message' => 'not logged in'];
}
else if($this->database->readAdminUser($this->userID) !== NULL)
{
return ['status' => 'error', 'message' => 'not an admin'];
}
if($this->action === 'CreateProduct')
{
if($this->method === 'post')
{
$product = new Product($_POST['productName'], $_POST['productDescription'], $_POST['size'], $_POST['color'], $_POST['prize'], $_POST['brandID'], $_POST['stock'], $_POST['sold'], $_POST['productImage']);
return $this->database->createProduct($product);
}
}
else if($this->action === 'StoreProduct')
{
if($this->method === 'post')
{
$product = new Product($_POST['productName'], $_POST['productDescription'], $_POST['size'], $_POST['color'], $_POST['prize'], $_POST['brandID'], $_POST['stock'], $_POST['sold'], $_POST['productImage']);
$product->ProductID = $_POST['productID'];
return $this->database->updateProduct($product);
}
}
else if($this->action === 'DeleteProduct')
{
if($this->method === 'post')
{
return $this->database->deleteProduct($_POST['productID']);
}
}
else if($this->action === 'CreateNewsPost')
{
if($this->method === 'post')
{
$newsPost = new NewsPost($_POST['title'], $_POST['content']);
return $this->database->createNewsPost($newsPost);
}
}
else if($this->action === 'DeleteNewsPost')
{
if($this->method === 'post')
{
return $this->database->deleteNewsPost($_POST['newsPostID']);
}
}
else if($this->action === 'UpdatePage')
{
if($this->method === 'post')
{
if($_POST['pageName'] === 'about')
{
return $this->database->updateAbout($_POST['content']);
}
else if($_POST['pageName'] === 'contact')
{
return $this->database->updateContact($_POST['content']);
}
else if($_POST['pageName'] === 'terms')
{
return $this->database->updateTerms($_POST['content']);
}
else if($_POST['pageName'] === 'privacy')
{
return $this->database->updatePrivacy($_POST['content']);
}
}
}
else if($this->action === 'UpdateSiteTitle')
{
if($this->method === 'post')
{
return $this->database->updateSiteTitle($_POST['siteTitle']);
}
}
else if($this->action === 'UpdatePageLogo')
{
if($this->method === 'post')
{
return $this->database->updatePageLogo($_POST['pageLogo']);
}
}
else if($this->action === 'UpdateFavIcon')
{
if($this->method === 'post')
{
return $this->database->updateFavIcon($_POST['favIcon']);
}
}
else if($this->action === 'CreateAdmin')
{
if($this->method === 'post')
{
$admin = new Admin($_POST['title'], $_POST['departmentID'], $_POST['userID']);
return $this->database->createAdmin($admin);
}
}
else if($this->action === 'UpdateAdmin')
{
if($this->method === 'post')
{
$admin = new Admin($_POST['title'], $_POST['departmentID'], $_POST['userID']);
$admin->AdminUserID = $_POST['adminUserID'];
return $this->database->updateAdmin($admin);
}
}
else if($this->action === 'DeleteUserAccount')
{
if($this->method === 'post')
{
$this->database->deleteAdmin($_POST['userID']);
return $this->database->deleteUser($_POST['userID']);
}
}
else
{
return parent::route();
}
}
}
<file_sep><?php
class Adress
{
public $AdressID;
public $Phone;
public $StreetName;
public $StreetNumber;
public $FloorNumber;
public $PostalCode;
public $Country;
function __construct($Phone, $StreetName, $StreetNumber, $FloorNumber, $PostalCode, $Country)
{
$this->Phone = $Phone;
$this->StreetName = $StreetName;
$this->StreetNumber = $StreetNumber;
$this->FloorNumber = $FloorNumber;
$this->PostalCode = $PostalCode;
$this->Country = $Country;
}
}
?><file_sep>var $star_rating = $('.star-rating .fa');
var SetRatingStar = function() {
return $star_rating.each(function() {
if (parseInt($star_rating.siblings('input.rating-value').val()) >= parseInt($(this).data('rating'))) {
return $(this).removeClass('fa-star-o').addClass('fa-star');
} else {
return $(this).removeClass('fa-star').addClass('fa-star-o');
}
});
};
$star_rating.on('click', function() {
$star_rating.siblings('input.rating-value').val($(this).data('rating'));
return SetRatingStar();
});
SetRatingStar();
$(document).ready(function() {
});
// When the user scrolls the page, execute myFunction
//window.onscroll = function() {myFunction()};
function myFunction() {
var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var scrolled = (winScroll / height) * 100;
document.getElementById("myBar").style.width = scrolled + "%";
}
<file_sep><?php
session_start();
if(strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) !== false)
{
$ORDER = $_SESSION['ORDER'] ?? NULL; //Setting the order id if it is created
$AUTH_USER = $_SESSION['AUTH_USER'] ?? NULL; //Setting the user id if a user is logged in.
$CONTROLLER = 'Shop';
$ACTION = 'index';
$METHOD = 'get';
if(empty($_POST) === false) //Check if it is a post request
{
$METHOD = 'post';
if(isset($_POST['action']))
{
$ACTION = $_POST['action'];
}
if(isset($_POST['controller']))
{
$CONTROLLER = $_POST['controller'];
}
}
else //If it is not post it is a get request
{
if(isset($_GET['action']))
{
$ACTION = $_GET['action'];
}
if(isset($_GET['controller']))
{
$CONTROLLER = $_GET['controller'];
}
}
$result = NULL;
if($CONTROLLER === 'Admin') //Check which controller are requested
{
require_once("AdminController.php");
$adminController = new AdminController($ACTION, $METHOD, $AUTH_USER, $ORDER);
$result = $adminController->route();
}
else if($CONTROLLER === 'Shop') //Requests from the shop
{
require_once("ShopController.php");
$shopController = new ShopController($ACTION, $METHOD, $AUTH_USER, $ORDER);
$result = $shopController->route();
}
//Return the json from the API
echo json_encode($result);
}
?><file_sep><?php
class NewsPost
{
public $NewsPostID;
public $Title;
public $Content;
public $PostDate;
function __construct(string $Title, string $Content)
{
$this->Title = $Title;
$this->Content = $Content;
}
}
?><file_sep><?php
class Vat
{
public $VatID;
public $VatValue;
function __construct(int $VatValue)
{
$this->VatValue = $VatValue;
}
}
?><file_sep><?php
class HtmlElementClass
{
public $HtmlElementClassID;
public $ElementName;
public $ClassValue;
function __construct(string $ElementName, string $ClassValue)
{
$this->ElementName = $ElementName;
$this->ClassValue = $ClassValue;
}
}
?><file_sep><?php
class Order
{
public $OrderID;
public $OrderDate;
public $ShipDate;
public $TotalCost;
public $UserID;
function __construct(string $OrderDate, string $ShipDate, int $TotalCost, int $UserID)
{
$this->OrderDate = $OrderDate;
$this->ShipDate = $ShipDate;
$this->TotalCost = $TotalCost;
$this->UserID = $UserID;
}
}
?><file_sep>$( document ).ready(function() {
$('#logout').hide();
$('#hiddenContent').hide();
//Event listener for interactions on buttons, links and forms
function registerEvents(){
$('button,a,input:submit').unbind('click');
$('button,a,input:submit').click(function(event) {
var href = event.target.attributes['href'];
if(href === undefined || (href !== undefined && href.value.charAt(0) !== '#')){
var action = null;
var parameters = [];
var method = null;
var controller = null;
switch(this.localName){
case 'button' :
case 'a' :
if(this.attributes['action'] !== undefined){
action = this.attributes['action'].value;
}
if(this.attributes['controller'] !== undefined){
controller = this.attributes['controller'].value;
}
if(this.attributes['parameter'] !== undefined){
parameters.push(this.attributes['parameter'].value);
}
break;
case 'input' :
action = this.form.attributes['action'].value;
method = this.form.attributes['method'].value;
controller = this.form.attributes['controller'].value;
for(let element = 0; element < this.form.length; element++)
{
if(this.form[element].localName === 'button')
{
continue;
}
if(this.form[element].name === undefined || this.form[element].value === undefined)
{
continue;
}
if(this.form[element].type === 'submit')
{
continue;
}
parameters[this.form[element].name] = this.form[element].value;
}
break;
default :
break;
}
let handle = {
action: action,
parameters: parameters,
method: method,
controller: controller
};
if(handle.action !== null && handle.method !== null && handle.controller !== null)
{
event.preventDefault();
sendRequest(handle);
}
else if(href !== undefined && href.value.charAt(0) === '$')
{
//ref is used to replace content on the page from href attributes on links
let ref = href.value.replace('$', '');
event.preventDefault();
handleReference(ref);
}else{
//console.log('Preventet request: ');
//console.log(event);
}
}
});
}
function createShopCartListContent(index, name, amount, prize, id){
let number = '<th scope="row">' + index + '</th>';
let n = '<td>' + name + '</td>';
let a = '<td>' + amount + '</td>';
let cost = '<td>' + (amount * prize) + ' $</td>';
let button = '<td><form action="RemoveFromCart" method="post" controller="Shop"><input type="hidden" name="ProductID" value="' + id + '"><input type="submit" class="btn btn-outline-danger" value="X"></td></form>';
let tr = '<tr>' + number + n + a + cost + button + '</tr>';
return tr;
}
function createProductCard(ref, text, title, image, prize){
let orderButton = '<div class="input-group-append"><input class="btn btn-outline-secondary" type="submit" value="Add to cart"></div>';
let option0 = '<option selected>Choose Amount</option>';
let option1 = '<option value="1">1</option>';
let option2 = '<option value="2">2</option>';
let option3 = '<option value="3">3</option>';
let select = '<select name="amount" class="custom-select" id="">' + option0 + option1 + option2 + option3 + '</select>';
let productID = '<input type="hidden" name="productID" value="' + ref + '">';
let form = '<form action="AddProductToCart" method="post" controller="Shop">' + select + orderButton + productID + '</form>';
let txt = '<p class="card-text">' + text + ' $ ' + prize + '</p>';
let heading = '<h5 class="card-title">' + title + '</h5>';
let body = '<div class="card-body">' + heading + txt + form + '</div>';
let img = '<img class="card-img-top" src="' + image + '" alt="Card image cap">';
let template = '<div class="card">' + img + body + '</div>';
return template;
}
function loadProducts(ref){
let params = [];
params[0] = ref;
let handle = {
action: 'ViewList',
parameters: params,
method: 'get',
controller: 'Shop'
};
sendRequest(handle);
}
function handleReference(ref){
if(ref === 'sale' || ref === 'merch' || ref === 'ducks'){
let refContent = $('#contentRef')[0];
let switchContent = $('#contentSwitch')[0];
let refHtml = refContent.innerHTML;
switchContent.innerHTML = refHtml;
switchContent = $('#contentSwitch').hide();
loadProducts(ref);
}else{
let refContent = $('#contentRef')[0];
let switchContent = $('#contentSwitch')[0];
let hiddenContent = $('#hiddenContent')[0];
let refHtml = switchContent.innerHTML;
switchContent.innerHTML = "";
hiddenContent.innerHTML = "";
refContent.innerHTML = refHtml;
$('#contentSwitch').hide();
$('#hiddenContent').hide();
}
}
function onSuccess(data, status, request){
console.log(data);
if(status === 'success'){
let responseObject = JSON.parse(data);
if(responseObject.message === 'siteTitle'){
let siteTitleElement = $('#siteTitle')[0];
siteTitleElement.innerText = responseObject.response.PageSettingValue;
}else if(responseObject.message === 'siteLogo'){
let siteLogoImageElement = $('#siteLogoImage')[0];
siteLogoImageElement.src = responseObject.response.PageSettingValue;
}else if(responseObject.message === 'contact'){
let contact = $('adress')[0];
let contactSection = $('#contactSection')[0];
contact.innerHTML = responseObject.response.ContentValue;
contactSection.innerHTML = responseObject.response.ContentValue;
}else if(responseObject.message === 'about'){
let about = $('#about')[0];
about.innerHTML = responseObject.response.ContentValue;
}else if(responseObject.message === 'offer'){
let offerImage = $('#' + responseObject.response.Offer.OfferName + 'Image')[0];
let offerValue = $('.' + responseObject.response.Offer.OfferName + 'Value');
for(let i = 0; i < offerValue.length; i++){
offerValue[i].innerText = responseObject.response.Offer.Discount;
}
let offerCode = $('#' + responseObject.response.Offer.OfferName + 'Code');
offerCode[0].innerText = responseObject.response.Offer.OfferName;
offerImage.src = responseObject.response.Product[0].ProductImage;
}else if(responseObject.message === 'topseller'){
let topsellersImage = $('#topsellersImage');
topsellersImage[0].src = responseObject.response.ProductImage;
let topsellersName = $('#topsellersName')[0];
topsellersName.innerText = responseObject.response.ProductName;
let topsellersPrice = $('#topsellersPrice')[0];
topsellersPrice.innerText = responseObject.response.Prize;
let topsellersDescription = $('#topsellersDescription')[0];
topsellersDescription.innerText = responseObject.response.ProductDescription;
$('#topsellersProductID')[0].value = responseObject.response.ProductID;
}else if(responseObject.message === 'highestrated'){
let topsellersImage = $('#highestratedImage');
topsellersImage[0].src = responseObject.response.ProductImage;
let highestratedName = $('#highestratedName')[0];
highestratedName.innerText = responseObject.response.ProductName;
let highestratedPrice = $('#highestratedPrice')[0];
highestratedPrice.innerText = responseObject.response.Prize;
let highestratedDescription = $('#highestratedDescription')[0];
highestratedDescription.innerText = responseObject.response.ProductDescription;
$('#highestratedProductID')[0].value = responseObject.response.ProductID;
}else if(responseObject.message === 'newinstock'){
let topsellersImage = $('#newinstockImage');
topsellersImage[0].src = responseObject.response.ProductImage;
let newinstockName = $('#newinstockName')[0];
newinstockName.innerText = responseObject.response.ProductName;
let newinstockPrice = $('#newinstockPrice')[0];
newinstockPrice.innerText = responseObject.response.Prize;
let newinstockdescription = $('#newinstockDescription')[0];
newinstockdescription.innerText = responseObject.response.ProductDescription;
$('#newinstockProductID')[0].value = responseObject.response.ProductID;
}else if(responseObject.message === 'login'){
if(responseObject.response != null){
hideLoginSignup();
}
}else if(responseObject.message === 'signup'){
hideLoginSignup();
}else if(responseObject.message === 'logout'){
$('#signUpTrigger').show();
$('#logInTrigger').show();
$('#logout').hide();
}else if(responseObject.message === 'search'){
//Not implemented in front end
}else if(responseObject.message === 'list'){
displayProductsHtml(responseObject.response);
}else if(responseObject.message === 'order'){
updateCartRequest();
}else if(responseObject.message === 'shopCartUpdate'){
hideLoginSignup();
updateCartContent(responseObject.response.order, responseObject.response.products);
}else if(responseObject.message === 'removeFromCart'){
updateCartContent(responseObject.response.order, responseObject.response.products);
updateCartRequest();
}
registerEvents();
}
}
function updateCartContent(order, products){
if(order !== null){
$('#cartCounter')[0].innerText = products.length;
let totalCostCounter = $('#cartTotalCost')[0];
totalCostCounter.innerText = 'Total Cost: $' + order.TotalCost;
let productsHtml = "";
for(let i = 0; i < products.length; i++){
productsHtml = productsHtml + createShopCartListContent(i, products[i][0].ProductName, 1, products[i][0].Prize, products[i][0].ProductID);
}
$('#shopCartListContent')[0].innerHTML = productsHtml;
}
}
function updateCartRequest(){
let handle = {
action: 'ViewOrder',
parameters: [],
method: 'get',
controller: 'Shop'
};
sendRequest(handle);
}
function displayProductsHtml(productsArray)
{
let result = "<div class='container-fluid d-flex justify-content-center'><div class='row'>";
productsArray.forEach(element => {
result = result + "<div class='col-sm-12 col-md-4 col-lg-3'>" +
createProductCard(
element.ProductID,
element.ProductDescription,
element.ProductName,
element.ProductImage,
element.Prize) + "</div>";
});
$('#contentRef')[0].innerHTML = "" + result + "</div></div>";
}
function hideLoginSignup(){
$('#signUpTrigger').hide();
$('#logInTrigger').hide();
$('#logout').show();
}
function onError(request, status, error){
console.log({
status: status,
error: error,
request: request
});
}
function sendRequest(handle){
if(handle.method === 'get'){
$.ajax({
url: "app/app.php",
type: handle.method,
data: {
controller: handle.controller,
action: handle.action,
parameter: handle.parameters[0]
},
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: onSuccess,
error: onError
});
}else{
handle.parameters['controller'] = handle.controller;
handle.parameters['action'] = handle.action;
$.ajax({
url: "app/app.php",
type: handle.method,
data: Object.assign({}, handle.parameters),
success: onSuccess,
error: onError
});
}
}
function getSiteTitle(){
let handle = {
action: 'ReadSiteTitle',
parameters: [],
method: 'get',
controller: 'Shop'
};
sendRequest(handle);
}
function getSiteLogoImage(){
let handle = {
action: 'ReadSiteLogo',
parameters: [],
method: 'get',
controller: 'Shop'
};
sendRequest(handle);
}
function getContact(){
let handle = {
action: 'ReadContact',
parameters: [],
method: 'get',
controller: 'Shop'
};
sendRequest(handle);
}
function getAbout(){
let handle = {
action: 'ReadAbout',
parameters: [],
method: 'get',
controller: 'Shop'
};
sendRequest(handle);
}
function getOffer(offerName){
let params = [];
params[0] = offerName;
let handle = {
action: 'ReadOffer',
parameters: params,
method: 'get',
controller: 'Shop'
};
sendRequest(handle);
}
function getFeaturedProduct(category){
let params = [];
params[0] = category;
let handle = {
action: 'ReadFeaturedProduct',
parameters: params,
method: 'get',
controller: 'Shop'
};
sendRequest(handle);
}
getSiteTitle();
getSiteLogoImage();
getContact();
getAbout();
getOffer('Discount');
getOffer('Wholesale');
getOffer('Seasonal');
getFeaturedProduct('topseller');
getFeaturedProduct('highestrated');
getFeaturedProduct('newinstock');
updateCartRequest();
});<file_sep>DROP PROCEDURE IF EXISTS SelectProducts;
DELIMITER $$
CREATE PROCEDURE SelectProducts()
BEGIN
SELECT * FROM Product;
END$$
DELIMITER ;
CALL SelectProducts();
DROP PROCEDURE IF EXISTS ViewOrder;
DELIMITER $$
CREATE PROCEDURE ViewOrder(IN id int)
BEGIN
SELECT * FROM Orders WHERE OrderID=id;
END$$
DELIMITER ;
CALL ViewOrder(1);
DROP VIEW IF EXISTS Admins;
CREATE VIEW Admins AS
SELECT User.Email, User.FirstName, User.LastName, AdminUser.Title
FROM User
INNER JOIN AdminUser
WHERE AdminUser.UserID=User.UserID;
SELECT * FROM Admins;
DROP VIEW IF EXISTS ProductInfo;
CREATE VIEW ProductInfo AS
SELECT Product.ProductName, Product.ProductDescription, Product.Size, Product.Color, Brand.BrandName, Brand.BrandDescription, Brand.BrandLogo
FROM Product
INNER JOIN Brand
WHERE Product.BrandID=Brand.BrandID;
SELECT * FROM ProductInfo;<file_sep><?php
require_once('models/Vat.php');
require_once('models/User.php');
require_once('models/Admin.php');
require_once('models/Product.php');
require_once('models/HtmlElementClass.php');
require_once('models/NewsPost.php');
require_once('models/Order.php');
require_once('models/Adress.php');
class ShopDatabase
{
protected $connection;
function __construct()
{
$this->connection = mysqli_connect('localhost', 'root', '', 'dbcms');
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
function readCategory($name)
{
$statement = $this->connection->prepare("SELECT * FROM Product JOIN Category ON Product.ProductID = Category.ProductID WHERE CategoryName = ?");
$statement->bind_param("s", $name);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_all(MYSQLI_ASSOC);
}
function readBrands()
{
$statement = $this->connection->prepare("SELECT * FROM Brand");
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_all(MYSQLI_ASSOC);
}
//Product
function readProduct(int $id)
{
$statement = $this->connection->prepare("SELECT * FROM Product WHERE ProductID = ?");
$statement->bind_param("i", $id);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_all(MYSQLI_ASSOC);
}
function readProducts()
{
$statement = $this->connection->prepare("SELECT * FROM Product");
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_all(MYSQLI_ASSOC);
}
function addProductToCart(int $productID, int $userID, $orderID)
{
if(isset($orderID) === false)
{
$order = new Order(date('Y-m-d'), date("Y-m-d", strtotime("0000-00-00")), 100, $userID);
$orderID = $this->createOrder($order)['OrderID'];
}
$statement = $this->connection->prepare("INSERT INTO ShoppingCart (OrderID, ProductID) VALUES(?, ?)");
$statement->bind_param("ii", $orderID, $productID);
$statement->execute();
$statement->close();
return $orderID;
}
function removeProductfromCart(int $productID, $orderID)
{
$statement = $this->connection->prepare("DELETE FROM ShoppingCart WHERE ProductID = ? AND OrderID = ?");
$statement->bind_param("ii", $productID, $orderID);
$statement->execute();
$statement->close();
return $orderID;
}
function readCart($orderID)
{
$statement = $this->connection->prepare("SELECT * FROM ShoppingCart WHERE OrderID = ?");
$statement->bind_param("i", $orderID);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_all(MYSQLI_ASSOC);
}
function readTopSeller()
{
$limit = 1;
$statement = $this->connection->prepare("SELECT * FROM Product ORDER BY Sold ASC LIMIT ?");
$statement->bind_param("i", $limit);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_all(MYSQLI_ASSOC);
}
function readHighestRated()
{
$limit = 1;
$statement = $this->connection->prepare("SELECT u.*
FROM product as u INNER JOIN
rating as p
ON u.ProductID = p.ProductID
GROUP BY u.ProductName
ORDER BY count(*) desc
LIMIT ?");
$statement->bind_param("i", $limit);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_all(MYSQLI_ASSOC);
}
function readNewInStock()
{
$limit = 1;
$statement = $this->connection->prepare("SELECT * FROM Product ORDER BY Stock DESC LIMIT ?");
$statement->bind_param("i", $limit);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_all(MYSQLI_ASSOC);
}
//Order
function createOrder(Order $order)
{
$statement = $this->connection->prepare("INSERT INTO Orders (OrderDate, ShipDate, TotalCost, UserID) VALUES(?, ?, ?, ?)");
$statement->bind_param("ssii", $order->OrderDate, $order->ShipDate, $order->TotalCost, $order->UserID);
$statement->execute();
$statement->close();
$statement = $this->connection->prepare("SELECT * FROM Orders ORDER BY OrderID DESC LIMIT 1");
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_assoc();
}
function updateOrder($id, $cost)
{
$statement = $this->connection->prepare("UPDATE Orders SET TotalCost = ? WHERE OrderID = ?");
$statement->bind_param("ii", $cost, $id);
$statement->execute();
$statement->close();
}
function readOrder(int $id)
{
$statement = $this->connection->prepare("SELECT * FROM Orders WHERE OrderID = ?");
$statement->bind_param("i", $id);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_assoc();
}
function payOrder(int $orderID)
{
$date = date("Y-m-d", strtotime("+4 day"));
$statement = $this->connection->prepare("UPDATE Orders SET ShipDate = ? WHERE OrderID = ?");
$statement->bind_param("si", $date, $orderID);
$statement->execute();
$statement->close();
}
function removeOrder(int $id)
{
$statement = $this->connection->prepare("DELETE FROM ShoppingCart WHERE OrderID = ?");
$statement->bind_param("i", $id);
$statement->execute();
$statement->close();
$statement = $this->connection->prepare("DELETE FROM Orders WHERE OrderID = ?");
$statement->bind_param("i", $id);
$statement->execute();
$statement->close();
}
//Pages
function readPage(int $id)
{
$statement = $this->connection->prepare("SELECT * FROM PageContent WHERE SectionID = ?");
$statement->bind_param("i", $id);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_assoc();
}
//Adress
function createAdress(Adress $adress)
{
$statement = $this->connection->prepare("INSERT INTO Adress (Phone, StreetName, StreetNumber, FloorNumber, PostalCode, Country) VALUES(?, ?, ?, ?, ?, ?)");
$statement->bind_param("ssssss", $adress->Phone, $adress->StreetName, $adress->StreetNumber, $adress->FloorNumber, $adress->PostalCode, $adress->Country);
$statement->execute();
$statement->close();
$statement = $this->connection->prepare("SELECT * FROM Adress ORDER BY AdressID DESC LIMIT 1");
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_assoc();
}
function updateAdress(Adress $adress)
{
$statement = $this->connection->prepare("UPDATE Adress SET Phone = ?, StreetName = ?, StreetNumber = ?, FloorNumber = ?, PostalCode = ?, Country = ? WHERE AdressID = ?");
$statement->bind_param("ssssssi", $adress->Phone, $adress->StreetName, $adress->StreetNumber, $adress->FloorNumber, $adress->PostalCode, $adress->Country, $adress->AdressID);
$statement->execute();
$statement->close();
}
//User
function createUser(User $user)
{
$pass = md5($user->UserPassword);
$statement = $this->connection->prepare("INSERT INTO User (Email, UserPassword, FirstName, LastName, AdressID) VALUES(?, ?, ?, ?, ?)");
$statement->bind_param("ssssi", $user->Email, $pass, $user->FirstName, $user->LastName, $user->AdressID);
$statement->execute();
$statement->close();
}
function readUser(int $id)
{
$statement = $this->connection->prepare("SELECT * FROM User WHERE UserID = ?");
$statement->bind_param("i", $id);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_assoc();
}
function updateUser(User $user)
{
$statement = $this->connection->prepare("UPDATE User SET Email = ?, UserPassword = ?, FirstName = ?, LastName = ?, AdressID = ? WHERE UserID = ?");
$statement->bind_param("ssssii", $user->Email, $user->UserPassword, $user->FirstName, $user->LastName, $user->AdressID, $user->UserID);
$statement->execute();
$statement->close();
}
function deleteUser(int $id)
{
$statement = $this->connection->prepare("DELETE FROM User WHERE UserID = ?");
$statement->bind_param("i", $id);
$statement->execute();
$statement->close();
}
//Search
function search(string $search)
{
$param = "%$search%";
$statement = $this->connection->prepare("SELECT * FROM Product WHERE ProductName LIKE ?");
$statement->bind_param("s", $param);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_all(MYSQLI_ASSOC);
}
//Login
function findUser($email, $pass)
{
$md5 = md5($pass);
$statement = $this->connection->prepare("SELECT * FROM User WHERE Email = ? AND UserPassword = ?");
$statement->bind_param("ss", $email, $md5);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_assoc();
}
//Site
function readSiteTitle()
{
$name = "SiteTitle";
$statement = $this->connection->prepare("SELECT * FROM pagesettings WHERE PageSettingName = ?");
$statement->bind_param("s", $name);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_assoc();
}
function readPageLogo()
{
$name = "PageLogo";
$statement = $this->connection->prepare("SELECT * FROM pagesettings WHERE PageSettingName = ?");
$statement->bind_param("s", $name);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_assoc();
}
function readContact()
{
$name = "Contact";
$statement = $this->connection->prepare("SELECT * FROM pagecontent WHERE SectionName = ?");
$statement->bind_param("s", $name);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_assoc();
}
function readAbout()
{
$name = "About";
$statement = $this->connection->prepare("SELECT * FROM pagecontent WHERE SectionName = ?");
$statement->bind_param("s", $name);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_assoc();
}
function readOffer($offerName)
{
$statement = $this->connection->prepare("SELECT * FROM offer WHERE OfferName = ?");
$statement->bind_param("s", $offerName);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_assoc();
}
function __destruct()
{
$this->connection->close();
}
}
?><file_sep><?php
require_once('ShopDatabase.php');
require_once('models/Vat.php');
require_once('models/User.php');
require_once('models/Admin.php');
require_once('models/Product.php');
require_once('models/HtmlElementClass.php');
require_once('models/NewsPost.php');
require_once('models/Order.php');
require_once('models/Adress.php');
class AdminDatabase extends ShopDatabase
{
function __construct()
{
parent::__construct(); //Connects to database
}
//NewsPost
function createNewsPost(NewsPost $NewsPost)
{
$date = date("Y-m-d");
$statement = $this->connection->prepare("INSERT INTO NewsPost (Title, Content, PostDate) VALUES(?, ?, ?)");
$statement->bind_param("sss", $NewsPost->Title, $NewsPost->Content, $date);
$statement->execute();
$statement->close();
}
function readNewsPosts()
{
$statement = $this->connection->prepare("SELECT * FROM NewsPost");
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_all(MYSQLI_ASSOC);
}
function updateNewsPost(NewsPost $NewsPost)
{
$date = date("Y-m-d");
$statement = $this->connection->prepare("UPDATE NewsPost SET Title = ?, Content = ?, PostDate = ? WHERE NewsPostID = ?");
$statement->bind_param("sssi", $NewsPost->Title, $NewsPost->Content, $date, $NewsPost->NewsPostID);
$statement->execute();
$statement->close();
}
function deleteNewsPost(int $id)
{
$statement = $this->connection->prepare("DELETE FROM NewsPost WHERE NewsPostID = ?");
$statement->bind_param("i", $id);
$statement->execute();
$statement->close();
}
//HtmlElementClass
function createHtmlElementClass(HtmlElementClass $HtmlElementClass)
{
$statement = $this->connection->prepare("INSERT INTO HtmlElementClass (ElementName, ClassValue) VALUES(?, ?)");
$statement->bind_param("ss", $HtmlElementClass->ElementName, $HtmlElementClass->ClassValue);
$statement->execute();
$statement->close();
}
function updateHtmlElementClass(HtmlElementClass $HtmlElementClass)
{
$statement = $this->connection->prepare("UPDATE HtmlElementClass SET ElementName = ?, ClassValue = ? WHERE HtmlElementClassID = ?");
$statement->bind_param("ssi", $HtmlElementClass->ElementName, $HtmlElementClass->ClassValue, $HtmlElementClass->HtmlElementClassID);
$statement->execute();
$statement->close();
}
function deleteHtmlElementClass(int $id)
{
$statement = $this->connection->prepare("DELETE FROM HtmlElementClass WHERE HtmlElementClassID = ?");
$statement->bind_param("i", $id);
$statement->execute();
$statement->close();
}
//Product
function createProduct(Product $product)
{
$statement = $this->connection->prepare("INSERT INTO Product (ProductName, ProductDescription, Size, Color, Prize, BrandID, Stock, Sold, ProductImage) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)");
$statement->bind_param("ssisiiiis", $product->ProductName, $product->ProductDescription, $product->Size, $product->Color, $product->Prize, $product->BrandID, $product->Stock, $product->Sold, $product->ProductImage);
$statement->execute();
$statement->close();
}
function readProduct(int $id)
{
$statement = $this->connection->prepare("SELECT * FROM Product WHERE ProductID = ?");
$statement->bind_param("i", $id);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_assoc();
}
function updateProduct(Product $product)
{
$statement = $this->connection->prepare("UPDATE Product SET ProductName = ?, ProductDescription = ?, Size = ?, Color = ?, Prize = ?, BrandID = ?, Stock = ?, Sold = ?, ProductImage = ? WHERE ProductID = ?");
$statement->bind_param("ssisiiiisi", $product->ProductName, $product->ProductDescription, $product->Size, $product->Color, $product->Prize, $product->BrandID, $product->Stock, $product->Sold, $product->ProductImage, $product->ProductID);
$statement->execute();
$statement->close();
}
function deleteProduct(int $id)
{
$statement = $this->connection->prepare("DELETE FROM Product WHERE ProductID = ?");
$statement->bind_param("i", $id);
$statement->execute();
$statement->close();
}
//Admin
function createAdmin(Admin $admin)
{
$statement = $this->connection->prepare("INSERT INTO AdminUser (Title, DepartmentID, UserID) VALUES(?, ?, ?)");
$statement->bind_param("sii", $admin->Title, $admin->DepartmentID, $admin->UserID);
$statement->execute();
$statement->close();
}
function readAdmin(int $id)
{
$statement = $this->connection->prepare("SELECT * FROM AdminUser WHERE AdminUserID = ?");
$statement->bind_param("i", $id);
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result->fetch_assoc();
}
function updateAdmin(Admin $admin)
{
$statement = $this->connection->prepare("UPDATE AdminUser SET Title = ?, DepartmentID = ?, UserID = ? WHERE AdminUserID = ?");
$statement->bind_param("siii", $admin->Title, $admin->DepartmentID, $admin->UserID, $admin->AdminUserID);
$statement->execute();
$statement->close();
}
function deleteAdmin(int $id)
{
$statement = $this->connection->prepare("DELETE FROM AdminUser WHERE UserID = ?");
$statement->bind_param("i", $id);
$statement->execute();
$statement->close();
}
function deleteAdminByID(int $id)
{
$statement = $this->connection->prepare("DELETE FROM AdminUser WHERE AdminUserID = ?");
$statement->bind_param("i", $id);
$statement->execute();
$statement->close();
}
//Updates
function updateSiteTitle(string $Title)
{
$statement = $this->connection->prepare("UPDATE PageSettings SET PageSettingValue = ? WHERE PageSettingName = 'SiteTitle'");
$statement->bind_param("s", $Title);
$statement->execute();
$statement->close();
}
function updatePageLogo(string $Logo)
{
$statement = $this->connection->prepare("UPDATE PageSettings SET PageSettingValue = ? WHERE PageSettingName = 'PageLogo'");
$statement->bind_param("s", $Logo);
$statement->execute();
$statement->close();
}
function updateFavIcon(string $FavIcon)
{
$statement = $this->connection->prepare("UPDATE PageSettings SET PageSettingValue = ? WHERE PageSettingName = 'FavIcon'");
$statement->bind_param("s", $FavIcon);
$statement->execute();
$statement->close();
}
//PageContent
function updateAbout(string $About)
{
$statement = $this->connection->prepare("UPDATE PageContent SET ContentValue = ? WHERE SectionName = 'About'");
$statement->bind_param("s", $About);
$statement->execute();
$statement->close();
}
function updateContact(string $Contact)
{
$statement = $this->connection->prepare("UPDATE PageContent SET ContentValue = ? WHERE SectionName = 'Contact'");
$statement->bind_param("s", $Contact);
$statement->execute();
$statement->close();
}
function updateTerms(string $Terms)
{
$statement = $this->connection->prepare("UPDATE PageContent SET ContentValue = ? WHERE SectionName = 'Terms'");
$statement->bind_param("s", $Terms);
$statement->execute();
$statement->close();
}
function updatePrivacy(string $Privacy)
{
$statement = $this->connection->prepare("UPDATE PageContent SET ContentValue = ? WHERE SectionName = 'Privacy'");
$statement->bind_param("s", $Privacy);
$statement->execute();
$statement->close();
}
function __destruct()
{
parent::__destruct();
}
}
?><file_sep><?php
require_once('database/ShopDatabase.php');
class ShopController
{
protected $database;
protected $action;
protected $method;
protected $userID;
protected $orderID;
function __construct(string $action, string $method, $userID, $orderID)
{
$this->database = new ShopDatabase();
$this->action = $action;
$this->method = $method;
$this->userID = $userID;
$this->orderID = $orderID;
}
function route()
{
if($this->action === 'ViewProduct')
{
if($this->method === 'get')
{
return $this->database->readProduct($_GET['parameter']);
}
}
else if($this->action === 'ViewPage')
{
if($this->method === 'get')
{
return $this->database->readPage($_GET['parameter']);
}
}
else if($this->action === 'AddProductToCart')
{
if($this->method === 'post')
{
if(isset($_SESSION['ORDER']) === false)
{
$now = date("Y-m-d H:i:s");
$order = new Order($now, $now, 0, $_SESSION['AUTH_USER']);
$_SESSION['ORDER'] = $this->database->createOrder($order)['OrderID'];
}
$totalCost = 0;
$shopCart = $this->database->readCart($_SESSION['ORDER']);
$products = [];
foreach($shopCart as $index => $p){
$totalCost = $totalCost + $this->database->readProduct($p['ProductID'])[0]['Prize'];
}
$productPrice = $this->database->readProduct(intval($_POST['productID']))[0]['Prize'];
for($amount = 0; $amount < intval($_POST['amount']); $amount++){
$_SESSION['ORDER'] = $this->database->addProductToCart($_POST['productID'], $this->userID, $_SESSION['ORDER']);
$totalCost = $totalCost + $productPrice;
}
$this->database->updateOrder($_SESSION['ORDER'], $totalCost);
return ['response' => $_SESSION['ORDER'], 'message' => 'order'];
}
}
else if($this->action === 'ViewOrder')
{
if($this->method === 'get')
{
if(isset($this->userID))
{
$order = $this->database->readOrder($_SESSION['ORDER']);
$shopCart = $this->database->readCart($_SESSION['ORDER']);
$products = [];
foreach($shopCart as $index => $product){
$products[] = $this->database->readProduct($product['ProductID']);
}
$result = [
'order' => $order,
'products' => $products
];
return ['response' => $result, 'message' => 'shopCartUpdate'];
}
}
}
else if($this->action === 'PayOrder')
{
if($this->method === 'post')
{
if(isset($this->userID))
{
$_SESSION['ORDER'] = NULL;
return $this->database->payOrder($_POST['orderID']);
}
}
}else if($this->action === 'RemoveFromCart'){
if($this->method === 'post'){
$shopCart = $this->database->readCart($_SESSION['ORDER']);
$products = [];
$order = $this->database->readOrder($_SESSION['ORDER']);
foreach($shopCart as $index => $product){
$products[] = $this->database->readProduct($product['ProductID']);
$this->database->removeProductfromCart($product['ProductID'], $_SESSION['ORDER']);
}
$this->database->updateOrder($_SESSION['ORDER'], 0);
$order = $this->database->readOrder($_SESSION['ORDER']);
$result = [
'order' => $order,
'products' => $products
];
return ['response' => $result, 'message' => 'removeFromCart'];
}
}
else if($this->action === 'SearchableContent')
{
if($this->method === 'post')
{
return ['response' => $this->database->search($_POST['parameter']), 'search'];
}
}
else if($this->action === 'CreateUser')
{
if($this->method === 'post')
{
$adress = new Adress($_POST['phone'], $_POST['streetName'], $_POST['streetNumber'], $_POST['floorNumber'], $_POST['postalCode'], $_POST['country']);
$adress->AdressID = $this->database->createAdress($adress)['AdressID'];
$user = new User($_POST['email'], $_POST['password'], $_POST['firstname'], $_POST['lastname'], $adress->AdressID);
return ['response' => $this->database->createUser($user), 'message' => 'signup'];
}
}
else if($this->action === 'StoreUser')
{
if($this->method === 'post')
{
$adress = new Adress($_POST['phone'], $_POST['streetName'], $_POST['streetNumber'], $_POST['floorNumber'], $_POST['postalCode'], $_POST['country']);
$adress->AdressID = $_POST['adressID'];
$this->database->updateAdress($adress);
$user = new User($_POST['email'], $_POST['password'], $_POST['firstname'], $_POST['lastname'], $adress->AdressID);
$user->UserID = $_POST['userID'];
return $this->database->updateUser($user);
}
}
else if($this->action === 'ViewUser')
{
if($this->method === 'get')
{
if(isset($this->userID))
{
return $this->database->readUser($_GET['parameter']);
}
else
{
return ['status' => 'error', 'message' => 'not logged in'];
}
}
}
else if($this->action === 'ViewList')
{
if($this->method === 'get')
{
return ['response' => $this->database->readCategory($_GET['parameter']), 'message' => 'list'];
}
}
else if($this->action === 'Login')
{
if($this->method === 'post')
{
$user = $this->database->findUser($_POST['email'], $_POST['password']);
$userID = NULL;
if(isset($user))
{
$userID = $user['UserID'];
}
$_SESSION['AUTH_USER'] = $userID;
return ['response' => $_SESSION['AUTH_USER'], 'message' => 'login'];
}
}
else if($this->action === 'Logout')
{
if($this->method === 'post')
{
$_SESSION['AUTH_USER'] = NULL;
if(isset($_SESSION['ORDER'])){
$this->database->removeOrder($_SESSION['ORDER']);
unset($_SESSION['ORDER']);
}
session_destroy();
return ['response' => NULL, 'message' => 'logout'];
}
}
else if($this->action === 'ReadSiteTitle')
{
if($this->method === 'get')
{
return ['response' => $this->database->readSiteTitle(), 'message' => 'siteTitle'];
}
}
else if($this->action === 'ReadSiteLogo')
{
if($this->method === 'get')
{
return ['response' => $this->database->readPageLogo(), 'message' => 'siteLogo'];
}
}
else if($this->action === 'ReadContact')
{
if($this->method === 'get')
{
return ['response' => $this->database->readContact(), 'message' => 'contact'];
}
}
else if($this->action === 'ReadAbout')
{
if($this->method === 'get')
{
return ['response' => $this->database->readAbout(), 'message' => 'about'];
}
}
else if($this->action === 'ReadOffer')
{
if($this->method === 'get')
{
$offer = $this->database->readOffer($_GET['parameter']);
$response = [
'Offer' => $offer,
'Product' => $this->database->readProduct($offer['ProductID'])
];
return ['response' => $response, 'message' => 'offer'];
}
}
else if($this->action === 'ReadFeaturedProduct')
{
if($this->method === 'get')
{
if($_GET['parameter'] === 'topseller')
{
return ['response' => $this->database->readTopSeller()[0], 'message' => 'topseller'];
}
else if($_GET['parameter'] === 'highestrated')
{
return ['response' => $this->database->readHighestRated()[0], 'message' => 'highestrated'];
}
else if($_GET['parameter'] === 'newinstock')
{
return ['response' => $this->database->readNewInStock()[0], 'message' => 'newinstock'];
}
}
}
else if($this->action === 'ReadFavIcon')
{
if($this->method === 'get')
{
return $this->database->updateFavIcon();
}
}
return false;
}
}<file_sep><?php
class User
{
public $UserID;
public $Email;
public $UserPassword;
public $FirstName;
public $LastName;
public $AdressID;
function __construct(string $Email, string $UserPassword, string $FirstName, string $LastName, int $AdressID)
{
$this->Email = $Email;
$this->UserPassword = md5($User<PASSWORD>);
$this->FirstName = $FirstName;
$this->LastName = $LastName;
$this->AdressID = $AdressID;
}
}
?>
|
1067fa641ebc9adb596c6e48bb037dee40a6d468
|
[
"JavaScript",
"SQL",
"PHP"
] | 19
|
SQL
|
AnnemetteBP/cms-backend
|
d52dcd7d5fad7ff6765cfcb897c42d0b5aee70bd
|
bbfb8f1794fe76578b2878f4a6bd04cec9e01176
|
refs/heads/main
|
<repo_name>RicardoJiang/ComposeFlowLayout<file_sep>/app/src/main/java/com/zj/composeflowlayout/FlowLayout.kt
package com.zj.composeflowlayout
import android.util.Log
import android.view.Gravity
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlin.math.max
@Composable
fun ComposeFlowLayout(
modifier: Modifier = Modifier,
itemSpacing: Dp = 0.dp,
lineSpacing: Dp = 0.dp,
gravity: Int = Gravity.TOP,
content: @Composable () -> Unit
) {
Layout(
modifier = modifier,
content = content
) { measurables, constraints ->
val parentWidthSize = constraints.maxWidth
var lineWidth = 0
var totalHeight = 0
var lineHeight = 0
val mAllPlaceables = mutableListOf<MutableList<Placeable>>() // 所有可放置的内容
val mLineHeight = mutableListOf<Int>() //每行的最高高度
var lineViews = mutableListOf<Placeable>() //每行放置的内容
// 测量子View,获取FlowLayout的宽高
measurables.mapIndexed { i, measurable ->
// 测量子view
val placeable = measurable.measure(constraints)
val childWidth = placeable.width
val childHeight = placeable.height
if (lineWidth + childWidth > parentWidthSize) {
mLineHeight.add(lineHeight)
mAllPlaceables.add(lineViews)
lineViews = mutableListOf()
lineViews.add(placeable)
//记录总高度
totalHeight += lineHeight
lineWidth = childWidth
lineHeight = childHeight
totalHeight += lineSpacing.toPx().toInt()
} else {
lineWidth += childWidth + if (i == 0) 0 else itemSpacing.toPx().toInt()
lineHeight = maxOf(lineHeight, childHeight)
lineViews.add(placeable)
}
if (i == measurables.size - 1) {
totalHeight += lineHeight
mLineHeight.add(lineHeight)
mAllPlaceables.add(lineViews)
}
}
layout(parentWidthSize, totalHeight) {
var topOffset = 0
var leftOffset = 0
for (i in mAllPlaceables.indices) {
lineViews = mAllPlaceables[i]
lineHeight = mLineHeight[i]
for (j in lineViews.indices) {
val child = lineViews[j]
val childWidth = child.width
val childHeight = child.height
val childTop = getItemTop(gravity, lineHeight, topOffset, childHeight)
child.placeRelative(leftOffset, childTop)
leftOffset += childWidth + itemSpacing.toPx().toInt()
}
leftOffset = 0
topOffset += lineHeight + lineSpacing.toPx().toInt()
}
}
}
}
private fun getItemTop(gravity: Int, lineHeight: Int, topOffset: Int, childHeight: Int): Int {
return when (gravity) {
Gravity.CENTER -> topOffset + (lineHeight - childHeight) / 2
Gravity.BOTTOM -> topOffset + lineHeight - childHeight
else -> topOffset
}
}
<file_sep>/app/src/main/java/com/zj/composeflowlayout/MainActivity.kt
package com.zj.composeflowlayout
import android.os.Bundle
import android.view.Gravity
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.zj.composeflowlayout.ui.theme.ComposeFlowLayoutTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeFlowLayoutTheme {
HomePage()
}
}
}
}
val topics = listOf(
"Arts & Crafts", "Beauty", "Books", "Business", "Comics", "Culinary",
"Design", "Fashion", "Film", "History", "Maths", "Music", "People", "Philosophy",
"Religion", "Social sciences", "Technology", "TV", "Writing"
)
@Composable
fun HomePage() {
Scaffold(
topBar = {
TopAppBar(
title = {
Text(text = "ComposeFowLayout")
},
actions = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(Icons.Filled.Favorite, contentDescription = null)
}
}
)
}
) { innerPadding ->
BodyContent(Modifier.padding(innerPadding))
}
}
@Composable
fun BodyContent(modifier: Modifier = Modifier) {
Row(modifier = modifier
.background(color = Color.LightGray)
.padding(16.dp),
content = {
ComposeFlowLayout(
itemSpacing = 16.dp,
lineSpacing = 16.dp,
gravity = Gravity.CENTER
) {
for (index in topics.indices) {
if (index % 3 == 1) {
Chip(modifier = Modifier.height(80.dp),text = topics[index])
} else {
Chip(text = topics[index])
}
}
}
})
}
@Composable
fun Chip(modifier: Modifier = Modifier, text: String) {
Card(
modifier = modifier,
border = BorderStroke(color = Color.Black, width = Dp.Hairline),
shape = RoundedCornerShape(8.dp)
) {
Row(
modifier = Modifier.padding(start = 8.dp, top = 4.dp, end = 8.dp, bottom = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
Box(
modifier = Modifier
.size(16.dp, 16.dp)
.background(color = MaterialTheme.colors.secondary)
)
Spacer(Modifier.width(4.dp))
Text(text = text)
}
}
}
@Preview
@Composable
fun HomePagePreview() {
ComposeFlowLayoutTheme {
HomePage()
}
}<file_sep>/README.md
# ComposeFlowLayout
Compose版FlowLayout
# 效果


# 特性
1. 自定义`Layout`,从左向右排列,超出一行则换行显示
2. 支持设置子`View`间距及行间距
3. 当子`View`高度不一致时,支持一行内居上,居中,居下对齐
# 使用
```kotlin
ComposeFlowLayout(
itemSpacing = 16.dp,
lineSpacing = 16.dp,
gravity = Gravity.CENTER
) {
for (index in topics.indices) {
if (index % 3 == 1) {
Chip(modifier = Modifier.height(80.dp),text = topics[index])
} else {
Chip(text = topics[index])
}
}
}
```
# 原理
[Compose版FlowLayout了解一下~](https://juejin.cn/post/6996661434083967013)
|
0e684eb0cff9d975b8041893e577142987190131
|
[
"Markdown",
"Kotlin"
] | 3
|
Kotlin
|
RicardoJiang/ComposeFlowLayout
|
36b6bcea92c13b2fc91f051e1b27c737922f887c
|
2802d5ad2cae176f58a3048ddd89906cee37c754
|
refs/heads/main
|
<repo_name>ShoheiNishimoto/javascript_practice<file_sep>/1-4/main.js
const tasks = [
{
content: '机を片付ける',
ganre: '掃除'
},
{
content: '牛乳を買う',
ganre: '買い物'
},
{
content: '散歩をする',
ganre: '運動'
}
]
function showTask () {
console.log ('========================');
console.log ('現在持っているのタスク一覧');
console.log ('========================');
tasks.forEach ((task, index) => {
console.log (`${index} : [内容]${task.content}、[ジャンル]${task.ganre}`);
});
}
function addTask () {
let rep = 3;
while (rep > 0) {
const newContent = prompt ('タスクを入力してください');
const newGanre = prompt ('ジャンルを入力してください');
const newObj = {};
newObj.content = newContent;
newObj.ganre = newGanre;
tasks.push (newObj);
alert ('タスクを追加しました');
showTask ();
rep --;
}
}
showTask ();
addTask ();<file_sep>/3/3/js/main.js
const addTaskBtn = document.getElementById ('addTaskBtn');
const taskTxt = document.getElementById ('taskTxt');
const taskArea = document.querySelector ('tbody');
const taskArray = [];
//追加ボタンを押した時にタスクの追加を行う
addTaskBtn.addEventListener ('click', () => {
addTask ();
showTask ();
rmTask ();
toggleStatus ();
});
//入力されたタスクをtasks配列に追加する
function addTask () {
const comment = taskTxt.value;
if (comment) {
taskArray.push ({
comment: comment,
status: 'working',
})
taskTxt.value = '';
}
}
function showTask () {
const flagment = document.createDocumentFragment ();
while (taskArea.firstChild) {
taskArea.removeChild (taskArea.firstChild);
}
for (let i = 0; i < taskArray.length; i++) {
//---------------------------------
const tr = document.createElement ('tr');
tr.setAttribute ('id', `${i}`);
if (taskArray [i].status === 'working') {
tr.classList.add ('working');
} else {
tr.classList.add ('done');
}
//id
const idTd = document.createElement ('td');
idTd.textContent = `${i}`;
tr.appendChild (idTd);
//コメント部分
const commentTd = document.createElement ('td');
commentTd.textContent = taskArray [i].comment;
tr.appendChild (commentTd);
//---------------------------------
//---------------------------------
// //statusボタン
const statusTd = document.createElement ('td');
const statusBtn = document.createElement ('button');
statusBtn.setAttribute ('id', `statusBtn${i}`);
if (taskArray [i].status === 'working') {
statusBtn.textContent = '作業中';
} else {
statusBtn.textContent = '完了';
}
statusTd.appendChild (statusBtn);
tr.append (statusTd);
//---------------------------------
//---------------------------------
// //削除ボタン
const rmTd = document.createElement ('td');
const rmBtn = document.createElement ('button');
rmBtn.setAttribute ('id', `rmBtn${i}`);
rmBtn.textContent = "削除";
rmTd.appendChild (rmBtn);
tr.append (rmTd);
//---------------------------------
//---------------------------------
// //flagmentにまとめる
flagment.appendChild (tr);
taskArea.appendChild (flagment);
//---------------------------------
}
displayToggle ();
}
//tasksに格納されたtaskの数に応じて削除用のボタンの情報を取得
function rmTask () {
const rmBtn = [];
for (let i = 0; i < taskArray.length; i ++) {
rmBtn.push (document.getElementById (`rmBtn${i}`));
}
rmBtn.forEach ((e, i) => {
e.addEventListener ('click', () => {
const tr = document.getElementById (`${i}`);
tr.remove ();
taskArray.splice (i, 1);
showTask ();
toggleStatus ()
rmTask ();
})
})
}
// //statusBtnを取得して状態切り替えのトグルを追加
function toggleStatus () {
const statusBtns = [];
for (let i = 0; i < taskArray.length; i ++) {
statusBtns.push (document.getElementById (`statusBtn${i}`));
}
statusBtns.forEach ((e, i) => {
e.addEventListener ('click', () => {
taskArray [i].status = (taskArray [i].status === 'working') ? 'done' : 'working';
showTask ();
toggleStatus ();
rmTask ();
})
})
};
function displayToggle () {
const radio = document.getElementsByName ('status');
if (radio[0].checked) {
taskArray.forEach ((e, i) => {
document.getElementById (`${i}`).classList.remove ('hidden');
})
} else if (radio[1].checked) {
taskArray.forEach ((e, i) => {
if (e.status === 'working') {
document.getElementById (`${i}`).classList.remove ('hidden');
} else {
document.getElementById (`${i}`).classList.add ('hidden');
}
})
} else if (radio[2].checked) {
taskArray.forEach ((e, i) => {
if (e.status === 'done') {
document.getElementById (`${i}`).classList.remove ('hidden');
} else {
document.getElementById (`${i}`).classList.add ('hidden');
}
})
}
}
<file_sep>/3/2/js/main.js
const addBtn = document.getElementById ('addBtn');
const text = document.getElementById ('text');
const tasks = [];
const tasksArea = document.querySelector ('tbody');
//addTaskで追加されたタスクをDOMに追加する
function showTask () {
while (tasksArea.firstChild) {
tasksArea.removeChild (tasksArea.firstChild);
}
const flagment = document.createDocumentFragment ();
for (let i = 0; i < tasks.length; i ++) {
//tr
const tr = document.createElement ('tr');
tr.setAttribute ('id', `${i}`);
//id
const id = document.createElement ('td');
id.textContent = `${i}`;
tr.appendChild (id);
//コメント部分
const comment = document.createElement ('td');
comment.textContent = tasks [i];
tr.appendChild (comment);
//statusボタン
const status = document.createElement ('td');
const statusBtn = document.createElement ('button');
statusBtn.setAttribute ('id', `statusBtn${i}`);
statusBtn.textContent = "作業中";
status.appendChild (statusBtn);
tr.append (status);
//削除ボタン
const rm = document.createElement ('td');
const rmBtn = document.createElement ('button');
rmBtn.setAttribute ('id', `rmBtn${i}`);
rmBtn.textContent = "削除";
rm.appendChild (rmBtn);
tr.append (rm);
//flagmentにまとめる
flagment.appendChild (tr);
}
//tasksAreaに追加
tasksArea.appendChild (flagment);
}
//入力されたタスクをtasks配列に追加する
function addTask () {
const newTask = text.value;
if (newTask) {
tasks.push (newTask);
text.value = '';
}
}
//tasksに格納されたtaskの数に応じて削除用のボタンの情報を取得
function rm () {
const rmBtn = [];
for (let i = 0; i < tasks.length; i ++) {
rmBtn.push(document.getElementById (`rmBtn${i}`));
}
rmBtn.forEach ((e,i) => {
e.addEventListener ('click', () => {
const tr = document.getElementById (`${i}`);
tasks.splice (i, 1);
tr.remove ();
showTask ();
rm ();
})
})
}
addBtn.addEventListener ('click', () => {
addTask ();
showTask ();
rm ();
});
<file_sep>/4/main.js
const url = 'https://opentdb.com/api.php?amount=10&type=multiple';
const title = document.getElementById ('title');
const quizLevel = document.getElementById ('quizLevel');
const text = document.getElementById ('text');
const startBtn = document.getElementById ('btn');
const btnArea = document.getElementById ('btnArea');
let quizList;
let curIndex = 0;
let correctAnswers = 0;
btn.addEventListener ('click', getQuizList);
// クイズデータの取得と1問目のクイズのセット
async function getQuizList () {
title.textContent = '取得中';
text.textContent = '少々お待ちください';
btnArea.removeChild (startBtn);
try {
const response = await fetch (url);
const json = await response.json ();
quizList = json.results;
setQuiz ();
} catch (error) {
console.log ('取得失敗' + error);
}
}
//クイズをセットする関数
function setQuiz () {
//何問目,カテゴリー,難易度をcurIndexをもとに表示
title.textContent = `問題${curIndex + 1}`;
const category = document.createElement ('p');
category.textContent = `〔ジャンル〕${quizList [curIndex].category}`;
const level = document.createElement ('p');
level.textContent = `〔難易度〕${quizList [curIndex].difficulty}`;
//quizLevelから以前のDOMを削除し新しく作成したDOMを追加
while (quizLevel.firstChild) {
quizLevel.removeChild (quizLevel.firstChild);
}
quizLevel.appendChild (category);
quizLevel.appendChild (level);
text.textContent = `${quizList [curIndex].question}`;
btnSet ();
}
//incorrectAnswerとAnswerを一つの配列にまとめてそれぞれをボタン要素のテキストとして表示させる関数
function btnSet () {
const allChoises = [];
const choices = quizList [curIndex].incorrect_answers;
allChoises.push (...choices);
const currAnswer = quizList [curIndex].correct_answer;
allChoises.push (currAnswer);
const shuffledChoices = [];
//まとめた選択肢をシャッフルしてshuffledChoicesに格納
while (allChoises.length > 0) {
n = allChoises.length;
k = Math.floor (Math.random () * n)
shuffledChoices.push (allChoises [k]);
allChoises.splice (k, 1);
}
while (btnArea.firstChild) {
btnArea.removeChild (btnArea.firstChild);
}
for (let i = 0; i < shuffledChoices.length; i++) {
const quizBtn = document.createElement ('button');
quizBtn.textContent = shuffledChoices [i];
quizBtn.setAttribute ('id', `btn${i}`);
btnArea.appendChild (quizBtn);
//回答ボタンのクリック時のイベント
const selectedBtn = document.getElementById (`btn${i}`);
selectedBtn.addEventListener ('click', function () {
if (curIndex < quizList.length - 1) {
if (this.textContent === currAnswer) {
correctAnswers ++;
curIndex ++;
} else {
curIndex ++;
}
setQuiz ();
} else {
showResult ();
}
})
}
}
//回答結果を表示
function showResult () {
while (btnArea.firstChild) {
btnArea.removeChild (btnArea.firstChild);
}
while (quizLevel.firstChild) {
quizLevel.removeChild (quizLevel.firstChild);
}
title.textContent = `あなたの正解数は${correctAnswers}です`;
text.textContent = '再度チャレンジしたい場合は下をクリック';
const finBtn = document.createElement ('button');
finBtn.textContent = 'ホームに戻る';
finBtn.setAttribute ('id', `finBtn`);
btnArea.appendChild (finBtn);
finBtn.addEventListener ('click', () => {
curIndex = 0;
correctAnswers = 0;
setQuiz ();
})
}
<file_sep>/1-3/main.js
const tasks = [
'掃除',
'買い物',
'散歩',
];
function showTask () {
console.log ('========================');
console.log ('現在持っているのタスク一覧');
console.log ('========================');
for (let i = 0; i < tasks.length; i++) {
console.log (`${i}:${tasks[i]}`);
}
}
function addTask (count) {
for (let i = 0; i < count; i++) {
const input = prompt ('タスクを入力してください');
tasks.push (input);
alert ('タスクを追加しました');
showTask ();
}
}
showTask ();
addTask (3);<file_sep>/2/main.js
const fizzNum = document.getElementById('fizzNum');
const buzzNum = document.getElementById('buzzNum');
const btn = document.getElementById('btn');
const outputArea = document.getElementById('outputArea');
function exportResult (fizz, buzz) {
while (outputArea.firstChild) {
outputArea.removeChild (outputArea.firstChild);
}
for (let i = 1; i < 100; i++) {
const p = document.createElement ('p');
p.classList.add ('added');
if (i % fizz === 0 && i % buzz === 0) {
const fizzbuzzTxt = (`FizzBuzz ${i}`);
p.textContent = fizzbuzzTxt;
outputArea.appendChild (p);
} else if (i % fizz === 0 && i % buzz !== 0) {
const fizzTxt = (`Fizz ${i}`);
p.textContent = fizzTxt;
outputArea.appendChild (p);
} else if (i % fizz !== 0 && i % buzz === 0) {
const buzzTxt = (`Buzz ${i}`);
p.textContent = buzzTxt;
outputArea.appendChild (p);
}
}
}
btn.addEventListener ('click', () => {
const regex = /^([1-9]\d*|0)$/;
const checkFizz = regex.test(fizzNum.value);
const checkBuzz = regex.test(buzzNum.value);
if (checkFizz && checkBuzz) {
exportResult (fizzNum.value, buzzNum.value);
} else {
while (outputArea.firstChild) {
outputArea.removeChild (outputArea.firstChild);
}
const p = document.createElement ('p');
p.textContent = '整数値を入力してください';
outputArea.appendChild (p);
}
});
|
2e34f737e01e2e0e1a967ad141f5ad379886525f
|
[
"JavaScript"
] | 6
|
JavaScript
|
ShoheiNishimoto/javascript_practice
|
d867b431f7b6ccd920fea14a9684f8b22d69db4c
|
8bdd8ea8455824af81aba13e8b8df14638507ed5
|
refs/heads/master
|
<file_sep>package com.teaneck_squad.demo.Controllers;
import com.sun.xml.internal.xsom.impl.Ref;
import com.teaneck_squad.demo.models.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.swing.text.AbstractDocument;
import java.util.HashMap;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private userService userService;
@RequestHeader(ContentType"application/json")
@PostMapping("")
public ResponseEntity<?> createUser(@RequestParam HashMap<String,String> userData){
if(userService.createUser(user)){
mm.put("message","User successfully created");
}else{
mm.put("message","Unable to create new user");
return new ResponseEntity<>(mm, HttpStatus.UNPROCESSABLE_ENTITY);
}
return new ResponseEntity<>(mm, HttpStatus.OK);
}
}
<file_sep>package com.teaneck_squad.demo.repositories;
import org.springframework.stereotype.Repository;
@Repository
public class CRUDRepository {
}
|
946c3a2c776e60987a367d300ca98a282d1d69e1
|
[
"Java"
] | 2
|
Java
|
NCorreia100/demo
|
5564ef6132abcbb5cfd030da497cb84ce5b33aac
|
91e5c3014c1d4cbec22997ca915f7be8e8ad664f
|
refs/heads/master
|
<file_sep>#include "yeti.h"
#include "sdp_filter.h"
#include <string.h>
#include <ctime>
#include <cstdio>
#include "log.h"
#include "AmPlugIn.h"
#include "AmArg.h"
#include "jsonArg.h"
#include "AmSession.h"
#include "AmUtils.h"
#include "AmAudioFile.h"
#include "AmMediaProcessor.h"
#include "SDPFilter.h"
#include "CallLeg.h"
#include "RegisterDialog.h"
#include "Registration.h"
#include "cdr/TrustedHeaders.h"
#include "CodecsGroup.h"
#include "Sensors.h"
#define YETI_CFG_PART "signalling"
#define YETI_CFG_DEFAULT_TIMEOUT 5000
#define YETI_DEFAULT_AUDIO_RECORDER_DIR "/var/spool/sems/record"
#define YETI_DEFAULT_LOG_DIR "/var/spool/sems/logdump"
Yeti* Yeti::_instance=0;
Yeti *Yeti::create_instance(YetiBaseParams params)
{
if(!_instance)
_instance = new Yeti(params);
return _instance;
}
Yeti& Yeti::instance() {
return *_instance;
}
Yeti::Yeti(YetiBaseParams ¶ms)
: YetiBase(params),
YetiRpc(*this),
YetiRadius(*this)
{}
Yeti::~Yeti() {
cdr_list.stop();
rctl.stop();
router.stop();
}
static int check_dir_write_permissions(const string &dir)
{
ofstream st;
string testfile = dir + "/test";
st.open(testfile.c_str(),std::ofstream::out | std::ofstream::trunc);
if(!st.is_open()){
ERROR("can't write test file in '%s' directory",dir.c_str());
return 1;
}
st.close();
std::remove(testfile.c_str());
return 0;
}
bool Yeti::read_config(){
static const char *mandatory_options[] = {
"node_id",
"cfg_urls",
0
};
AmConfigReader ycfg;
if(ycfg.loadFile(AmConfig::ModConfigPath + string(MOD_NAME ".conf"))) {
ERROR("No configuration for " MOD_NAME " present (%s)\n",
(AmConfig::ModConfigPath + string(MOD_NAME ".conf")).c_str());
return false;
}
//check mandatory options
for(const char **opt = mandatory_options; *opt;opt++){
if(!ycfg.hasParameter(*opt)){
ERROR("Missed parameter '%s'",*opt);
return false;
}
}
vector<string> urls = explode(ycfg.getParameter("cfg_urls"),",");
for(vector<string>::const_iterator url = urls.begin();
url != urls.end(); ++url)
{
string key = "cfg_url_"+*url;
if(!ycfg.hasParameter(key)){
ERROR("'%s' declared in cfg_urls but '%s' paremeter is missed",
url->c_str(),key.c_str());
return false;
}
string cfg_url = ycfg.getParameter(key);
DBG("add config url: %s",cfg_url.c_str());
cfg.add_url(cfg_url.c_str());
}
cfg.set_node_id(config.node_id = ycfg.getParameterInt("node_id"));
cfg.set_cfg_part(YETI_CFG_PART);
cfg.set_timeout(ycfg.getParameterInt("cfg_timeout",YETI_CFG_DEFAULT_TIMEOUT));
try {
DBG("fetching yeti module cfg");
cfg.load();
} catch(yeti::cfg::server_exception &e){
ERROR("can't load yeti config: %d %s",e.code,e.what());
return false;
} catch(std::exception &e){
ERROR("can't load yeti config: %s",e.what());
return false;
}
if(!cfg.hasParameter("pop_id")){
ERROR("Missed parameter 'pop_id'");
return false;
}
config.pop_id = cfg.getParameterInt("pop_id");
if(!cfg.hasParameter("routing_schema")){
ERROR("Missed parameter 'routing_schema'");
return false;
}
config.routing_schema = cfg.getParameter("routing_schema");
config.use_radius = cfg.getParameterInt("use_radius",0)==1;
config.early_100_trying = cfg.getParameterInt("early_100_trying",1)==1;
if(!cfg.hasParameter("msg_logger_dir")){
ERROR("Missed parameter 'msg_logger_dir'");
return false;
}
config.msg_logger_dir = cfg.getParameter("msg_logger_dir");
if(check_dir_write_permissions(config.msg_logger_dir))
return false;
config.audio_recorder_dir = cfg.getParameter("audio_recorder_dir",YETI_DEFAULT_AUDIO_RECORDER_DIR);
if(check_dir_write_permissions(config.audio_recorder_dir))
return false;
config.audio_recorder_compress = cfg.getParameterInt("audio_recorder_compress",1)==1;
config.log_dir = cfg.getParameter("log_dir",YETI_DEFAULT_LOG_DIR);
if(check_dir_write_permissions(config.log_dir))
return false;
return true;
}
int Yeti::onLoad() {
if(!read_config()){
return -1;
}
calls_show_limit = cfg.getParameterInt("calls_show_limit",100);
if(TrustedHeaders::instance()->configure(cfg)){
ERROR("TrustedHeaders configure failed");
return -1;
}
if (cdr_list.configure(cfg)){
ERROR("CdrList configure failed");
return -1;
}
if (router.configure(cfg)){
ERROR("SqlRouter configure failed");
return -1;
}
if(configure_filter(&router)){
ERROR("ActiveCallsFilter configure failed");
return -1;
}
if(init_radius_module(cfg)){
ERROR("radius module configure failed");
return -1;
}
if(rctl.configure(cfg)){
ERROR("ResourceControl configure failed");
return -1;
}
rctl.start();
if(CodecsGroups::instance()->configure(cfg)){
ERROR("CodecsGroups configure failed");
return -1;
}
if (CodesTranslator::instance()->configure(cfg)){
ERROR("CodesTranslator configure failed");
return -1;
}
if(Sensors::instance()->configure(cfg)){
ERROR("Sensors configure failed");
return -1;
}
if(router.run()){
ERROR("SqlRouter start failed");
return -1;
}
if(Registration::instance()->configure(cfg)){
ERROR("Registration agent configure failed");
return -1;
}
if(cdr_list.getSnapshotsEnabled()) cdr_list.start();
init_rpc();
return 0;
}
<file_sep>#pragma once
#include "yeti_rpc.h"
//#include "yeti_cc.h"
#include "yeti_base.h"
#include "yeti_radius.h"
class Yeti
: public YetiRpc,
//public YetiCC,
virtual public YetiBase,
virtual public YetiRadius,
AmObject
{
static Yeti* _instance;
bool read_config();
public:
Yeti(YetiBaseParams ¶ms);
~Yeti();
static Yeti* create_instance(YetiBaseParams params);
static Yeti& instance();
int onLoad();
};
<file_sep>#include "Cdr.h"
#include "AmUtils.h"
#include "AmSipMsg.h"
#include "log.h"
#include "CoreRpc.h"
#include "TrustedHeaders.h"
#include "jsonArg.h"
#include "sip/defs.h"
#include "sems.h"
#include "../yeti_version.h"
#include "../RTPParameters.h"
#define DTMF_EVENTS_MAX 50
static string user_agent_hdr(SIP_HDR_USER_AGENT);
static string server_hdr(SIP_HDR_SERVER);
static const char *updateAction2str(UpdateAction act)
{
switch(act) {
case Start: return "Start";
case BLegInvite: return "BlegInvite";
case Connect: return "Connect";
case BlegConnect: return "BlegConnect";
case End: return "End";
case Write: return "Write";
default: return "Unknown";
}
}
const char *DisconnectInitiator2Str(int initiator)
{
static const char *DisconnectInitiatorStr[] = {
"Database",
"TrafficSwitch",
"Destination",
"Originator",
"Undefined"
};
if(initiator < 0 || initiator > DisconnectUndefined){
return "Invalid";
}
return DisconnectInitiatorStr[initiator];
}
Cdr::Cdr()
: snapshoted(false),
sip_early_media_present(false),
trusted_hdrs_gw(false),
writed(false),
suppress(false),
inserted2list(false),
disconnect_initiator(DisconnectUndefined),
disconnect_initiator_writed(false),
aleg_reason_writed(false),
bleg_reason_writed(false),
disconnect_code(0),
disconnect_internal_reason("Unhandled sequence"),
disconnect_internal_code(0),
disconnect_rewrited_code(0),
legB_transport_protocol_id(0),
legB_remote_port(0),
legB_local_port(0),
legA_remote_port(0),
legA_local_port(0),
legA_transport_protocol_id(0),
dump_level_id(0),
time_limit(0),
attempt_num(1),
active_resources("[]"),
failed_resource_type_id(-1),
failed_resource_id(-1),
legA_bytes_recvd(0),
legB_bytes_recvd(0),
legA_bytes_sent(0),
legB_bytes_sent(0),
isup_propagation_delay(0),
audio_record_enabled(false),
is_redirected(false)
{
gettimeofday(&cdr_born_time, NULL);
timerclear(&start_time);
timerclear(&bleg_invite_time);
timerclear(&connect_time);
timerclear(&bleg_connect_time);
timerclear(&end_time);
timerclear(&sip_10x_time);
timerclear(&sip_18x_time);
TrustedHeaders::instance()->init_hdrs(trusted_hdrs);
active_resources_amarg.assertArray();
active_resources_clickhouse.assertStruct();
}
Cdr::Cdr(const Cdr& cdr,const SqlCallProfile &profile)
: Cdr()
{
//DBG("Cdr::%s(cdr = %p,profile = %p) = %p", FUNC_NAME, &cdr, &profile, this);
update_sql(profile);
attempt_num = cdr.attempt_num+1;
end_time = start_time = cdr.start_time;
legA_remote_ip = cdr.legA_remote_ip;
legA_remote_port = cdr.legA_remote_port;
legA_local_ip = cdr.legA_local_ip;
legA_local_port = cdr.legA_local_port;
orig_call_id = cdr.orig_call_id;
local_tag = cdr.local_tag;
global_tag = cdr.global_tag;
aleg_versions = cdr.aleg_versions;
msg_logger_path = cdr.msg_logger_path;
dump_level_id = cdr.dump_level_id;
legA_transport_protocol_id = cdr.legA_transport_protocol_id;
}
Cdr::Cdr(const SqlCallProfile &profile)
: Cdr()
{
update_sql(profile);
}
Cdr::~Cdr()
{
//DBG("Cdr::~Cdr() %p",this);
}
void Cdr::replace(string& s, const string& from, const string& to)
{
size_t pos = 0;
while ((pos = s.find(from, pos)) != string::npos) {
s.replace(pos, from.length(), to);
pos += s.length();
}
}
void Cdr::update_sql(const SqlCallProfile &profile)
{
DBG("Cdr::%s(SqlCallProfile)",FUNC_NAME);
trusted_hdrs_gw = profile.trusted_hdrs_gw;
outbound_proxy = profile.outbound_proxy;
dyn_fields = profile.dyn_fields;
time_limit = profile.time_limit;
dump_level_id = profile.dump_level_id;
resources = profile.resources;
}
void Cdr::update_sbc(const SBCCallProfile &profile)
{
DBG("Cdr::%s(SBCCallProfile)",FUNC_NAME);
msg_logger_path = profile.get_logger_path();
audio_record_enabled = profile.record_audio;
}
void Cdr::update(const AmSipRequest &req)
{
size_t pos1,pos2,pos;
DBG("Cdr::%s(AmSipRequest)",FUNC_NAME);
if(writed) return;
legA_transport_protocol_id = req.transport_id;
legA_remote_ip = req.remote_ip;
legA_remote_port = req.remote_port;
legA_local_ip = req.local_ip;
legA_local_port = req.local_port;
orig_call_id=req.callid;
if(findHeader(req.hdrs,user_agent_hdr,0,pos1,pos2,pos))
aleg_versions.emplace(req.hdrs.substr(pos1,pos2-pos1));
if(findHeader(req.hdrs,server_hdr,0,pos1,pos2,pos))
aleg_versions.emplace(req.hdrs.substr(pos1,pos2-pos1));
if(req.method==SIP_METH_INVITE){
const AmMimeBody *body = req.body.hasContentType(SIP_APPLICATION_ISUP);
if(body){
AmISUP isup;
if(0==isup.parse(body)){
update(isup);
}
}
}
}
void Cdr::update(const AmISUP &isup)
{
DBG("Cdr::%s(AmISUP)",FUNC_NAME);
isup_propagation_delay = isup.propagation_delay;
}
void Cdr::update(const AmSipReply &reply){
size_t pos1,pos2,pos;
DBG("Cdr::%s(AmSipReply)",FUNC_NAME);
if(writed) return;
AmLock l(*this);
if(reply.code == 200 && trusted_hdrs_gw){ //try to fill trusted headers from 200 OK reply
TrustedHeaders::instance()->parse_reply_hdrs(reply,trusted_hdrs);
}
if(reply.remote_port==0)
return; //local reply
legB_transport_protocol_id = reply.transport_id;
legB_remote_ip = reply.remote_ip;
legB_remote_port = reply.remote_port;
legB_local_ip = reply.actual_ip;
legB_local_port = reply.actual_port;
if(findHeader(reply.hdrs,server_hdr,0,pos1,pos2,pos))
bleg_versions.emplace(reply.hdrs.substr(pos1,pos2-pos1));
if(findHeader(reply.hdrs,user_agent_hdr,0,pos1,pos2,pos))
bleg_versions.emplace(reply.hdrs.substr(pos1,pos2-pos1));
if(reply.code>=100) {
if(reply.code<110) { //10x codes
if(!timerisset(&sip_10x_time)){
gettimeofday(&sip_10x_time,NULL);
}
} else if(reply.code>=180 && reply.code<190) { //18x codes
if(!timerisset(&sip_18x_time)) {
gettimeofday(&sip_18x_time,NULL);
}
if(NULL!=reply.body.hasContentType(SIP_APPLICATION_SDP)){ //18x with SDP
sip_early_media_present = true;
}
}
}
}
void Cdr::update_init_aleg(
const string &leg_local_tag,
const string &leg_global_tag,
const string &leg_orig_call_id)
{
if(writed) return;
AmLock l(*this);
local_tag = leg_local_tag;
global_tag = leg_global_tag;
orig_call_id = leg_orig_call_id;
}
void Cdr::update_init_bleg(const string &leg_term_call_id)
{
if(writed) return;
AmLock l(*this);
term_call_id = leg_term_call_id;
}
void Cdr::update(UpdateAction act)
{
DBG("Cdr::%s(act = %s)",FUNC_NAME,updateAction2str(act));
if(writed) return;
switch(act) {
case Start:
gettimeofday(&start_time, NULL);
end_time = start_time;
break;
case BLegInvite:
if(!timerisset(&bleg_invite_time))
gettimeofday(&bleg_invite_time, NULL);
break;
case Connect:
gettimeofday(&connect_time, NULL);
break;
case BlegConnect:
gettimeofday(&bleg_connect_time, NULL);
break;
case End:
if(end_time.tv_sec==start_time.tv_sec)
gettimeofday(&end_time, NULL);
break;
case Write:
writed = true;
break;
}
}
void Cdr::update(const ResourceList &rl)
{
if(rl.empty()) return;
string clickhouse_key_prefix;
cJSON *j = cJSON_CreateArray(),*i;
active_resources_amarg.clear();
active_resources_clickhouse.clear();
active_resources_clickhouse.assertStruct();
for(auto const &r: rl) {
if(!r.active) continue;
active_resources_amarg.push(AmArg());
AmArg &a = active_resources_amarg.back();
clickhouse_key_prefix = "active_resource_" + int2str(r.type);
AmArg &id_arg = active_resources_clickhouse[clickhouse_key_prefix + "_id"];
if(isArgUndef(id_arg)) id_arg = r.id;
AmArg &limit_arg = active_resources_clickhouse[clickhouse_key_prefix + "_limit"];
if(isArgUndef(limit_arg)) limit_arg = r.limit;
AmArg &used_arg = active_resources_clickhouse[clickhouse_key_prefix + "_used"];
if(isArgUndef(used_arg)) used_arg = r.takes;
i = cJSON_CreateObject();
cJSON_AddNumberToObject(i,"type",r.type);
a["type"] = r.type;
cJSON_AddNumberToObject(i,"id",r.id);
a["id"] = r.id;
cJSON_AddNumberToObject(i,"takes",r.takes);
a["takes"] = r.takes;
cJSON_AddNumberToObject(i,"limit",r.limit);
a["limit"] = r.limit;
cJSON_AddItemToArray(j,i);
}
char *s = cJSON_PrintUnformatted(j);
active_resources = s;
free(s);
cJSON_Delete(j);
}
void Cdr::update_failed_resource(const Resource &r)
{
failed_resource_type_id = r.type;
failed_resource_id = r.id;
}
void Cdr::set_start_time(const timeval &t)
{
end_time = start_time = t;
}
void Cdr::update_bleg_reason(string reason, int code)
{
DBG("Cdr::%s(reason = '%s',code = %d)",FUNC_NAME,
reason.c_str(),code); if(writed) return;
if(writed) return;
AmLock l(*this);
if(bleg_reason_writed) return;
disconnect_reason = reason;
disconnect_code = code;
bleg_reason_writed = true;
}
void Cdr::update_aleg_reason(string reason, int code)
{
DBG("Cdr::%s(reason = '%s',code = %d)",FUNC_NAME,
reason.c_str(),code);
if(writed) return;
AmLock l(*this);
disconnect_rewrited_reason = reason;
disconnect_rewrited_code = code;
aleg_reason_writed = true;
}
void Cdr::update_internal_reason(DisconnectInitiator initiator,string reason, int code)
{
DBG("Cdr[%p]::%s(initiator = %d,reason = '%s',code = %d) cdr.disconnect_initiator_writed = %d",
this,FUNC_NAME,initiator,reason.c_str(),code,disconnect_initiator_writed);
if(writed) return;
AmLock l(*this);
update(End);
if(!disconnect_initiator_writed) {
disconnect_initiator = initiator;
disconnect_internal_reason = reason;
disconnect_internal_code = code;
disconnect_initiator_writed = true;
}
if(!aleg_reason_writed) {
disconnect_rewrited_reason = reason;
disconnect_rewrited_code = code;
}
unlock();
}
void Cdr::setSuppress(bool s)
{
if(writed) return;
AmLock l(*this);
suppress = s;
}
void Cdr::refuse(const SBCCallProfile &profile)
{
if(writed) return;
AmLock l(*this);
unsigned int refuse_with_code;
string refuse_with = profile.refuse_with;
size_t spos = refuse_with.find(' ');
disconnect_initiator = DisconnectByDB;
if (spos == string::npos || spos == refuse_with.size() ||
str2i(refuse_with.substr(0, spos), refuse_with_code))
{
ERROR("can't parse refuse_with in profile");
disconnect_reason = refuse_with;
disconnect_code = 0;
} else {
disconnect_reason = refuse_with.substr(spos+1);
disconnect_code = refuse_with_code;
}
disconnect_rewrited_reason = disconnect_reason;
disconnect_rewrited_code = disconnect_code;
}
void Cdr::refuse(int code, string reason)
{
if(writed) return;
AmLock l(*this);
disconnect_code = code;
disconnect_reason = reason;
}
void Cdr::replace(ParamReplacerCtx &ctx,const AmSipRequest &req)
{
//msg_logger_path = ctx.replaceParameters(msg_logger_path,"msg_logger_path",req);
}
static string join_str_vector2(const vector<string> &v1,
const vector<string> &v2,
const string &delim)
{
std::stringstream ss;
for(vector<string>::const_iterator i = v1.begin();i!=v1.end();++i){
if(i != v1.begin())
ss << delim;
ss << *i;
}
//if(!(v1.empty()||v2.empty()))
ss << "/";
for(vector<string>::const_iterator i = v2.begin();i!=v2.end();++i){
if(i != v2.begin())
ss << delim;
ss << *i;
}
return string(ss.str());
}
#define field_name fields[i++]
#define add_str2json(value) cJSON_AddStringToObject(j,field_name,value)
#define add_num2json(value) cJSON_AddNumberToObject(j,field_name,value)
#define add_tv2json(value) \
if(timerisset(&value)) cJSON_AddNumberToObject(j,field_name,timeval2double(value)); \
else cJSON_AddNullToObject(j,field_name)
char *Cdr::serialize_rtp_stats()
{
int i = 0;
cJSON *j;
char *s;
static const char *fields[] = {
"lega_rx_payloads",
"lega_tx_payloads",
"legb_rx_payloads",
"legb_tx_payloads",
"lega_rx_bytes",
"lega_tx_bytes",
"legb_rx_bytes",
"legb_tx_bytes",
"lega_rx_decode_errs",
"lega_rx_no_buf_errs",
"lega_rx_parse_errs",
"legb_rx_decode_errs",
"legb_rx_no_buf_errs",
"legb_rx_parse_errs",
};
j = cJSON_CreateObject();
//tx/rx uploads
add_str2json(join_str_vector2(
legA_payloads.incoming,
legA_payloads.incoming_relayed,","
).c_str());
add_str2json(join_str_vector2(
legA_payloads.outgoing,
legA_payloads.outgoing_relayed,","
).c_str());
add_str2json(join_str_vector2(
legB_payloads.incoming,
legB_payloads.incoming_relayed,","
).c_str());
add_str2json(join_str_vector2(
legB_payloads.outgoing,
legB_payloads.outgoing_relayed,","
).c_str());
//tx/rx bytes
add_num2json(legA_bytes_recvd);
add_num2json(legA_bytes_sent);
add_num2json(legB_bytes_recvd);
add_num2json(legB_bytes_sent);
//tx/rx rtp errors
add_num2json(legA_stream_errors.decode_errors);
add_num2json(legA_stream_errors.out_of_buffer_errors);
add_num2json(legA_stream_errors.rtp_parse_errors);
add_num2json(legB_stream_errors.decode_errors);
add_num2json(legB_stream_errors.out_of_buffer_errors);
add_num2json(legB_stream_errors.rtp_parse_errors);
s = cJSON_PrintUnformatted(j);
cJSON_Delete(j);
return s;
}
char *Cdr::serialize_timers_data()
{
int i = 0;
cJSON *j;
char *s;
static const char *fields[] = {
"time_start",
"leg_b_time",
"time_connect",
"time_end",
"time_1xx",
"time_18x",
"time_limit",
"isup_propagation_delay"
};
j = cJSON_CreateObject();
add_tv2json(start_time);
add_tv2json(bleg_invite_time);
add_tv2json(connect_time);
add_tv2json(end_time);
add_tv2json(sip_10x_time);
add_tv2json(sip_18x_time);
add_num2json(time_limit);
add_num2json(isup_propagation_delay);
s = cJSON_PrintUnformatted(j);
cJSON_Delete(j);
return s;
}
void Cdr::add_dtmf_event(
bool aleg, int event,
struct timeval &now,
int rx_proto, int tx_proto)
{
std::queue<dtmf_event_info> &q = aleg ? dtmf_events_a2b : dtmf_events_b2a;
if(q.size() >= DTMF_EVENTS_MAX) return;
q.push(dtmf_event_info(event,now,rx_proto,tx_proto));
}
cJSON *Cdr::dtmf_event_info::serialize2json(const struct timeval *t)
{
struct timeval offset;
cJSON *j = cJSON_CreateObject();
cJSON_AddNumberToObject(j,"e",event);
cJSON_AddNumberToObject(j,"r",rx_proto);
cJSON_AddNumberToObject(j,"t",tx_proto);
timersub(&time,t,&offset);
cJSON_AddNumberToObject(j,"o",timeval2double(offset));
return j;
}
char *Cdr::serialize_dtmf_events()
{
cJSON *j, *a;
const struct timeval *t = timerisset(&connect_time) ? &connect_time : &end_time;
j = cJSON_CreateObject();
a = cJSON_CreateArray();
while(!dtmf_events_a2b.empty()){
cJSON_AddItemToArray(
a, dtmf_events_a2b.front().serialize2json(t));
dtmf_events_a2b.pop();
}
cJSON_AddItemToObject(j,"a2b",a);
a = cJSON_CreateArray();
while(!dtmf_events_b2a.empty()){
cJSON_AddItemToArray(
a, dtmf_events_b2a.front().serialize2json(t));
dtmf_events_b2a.pop();
}
cJSON_AddItemToObject(j,"b2a",a);
char *s = cJSON_PrintUnformatted(j);
cJSON_Delete(j);
return s;
}
char *Cdr::serialize_dynamic(const DynFieldsT &df) {
cJSON *j;
char *s;
j = cJSON_CreateObject();
for(auto const &f: df) {
const string &name = f.name;
const char *namep = name.c_str();
const AmArg &arg = dyn_fields[name];
switch(arg.getType()) {
case AmArg::Int:
cJSON_AddNumberToObject(j,namep,arg.asInt());
break;
case AmArg::LongLong:
cJSON_AddNumberToObject(j,namep,arg.asLongLong());
break;
case AmArg::Bool:
cJSON_AddBoolToObject(j,namep,arg.asBool());
break;
case AmArg::CStr:
cJSON_AddStringToObject(j,namep,arg.asCStr());
break;
case AmArg::Undef:
cJSON_AddNullToObject(j,namep);
break;
default:
ERROR("invoc_AmArg. unhandled AmArg type %s",
arg.t2str(arg.getType()));
cJSON_AddNullToObject(j,namep);
} //switch
} //for
s = cJSON_PrintUnformatted(j);
cJSON_Delete(j);
return s;
}
char * Cdr::serialize_versions() const
{
cJSON *j;
int i,n;
char *s;
string joined_versions;
j = cJSON_CreateObject();
cJSON_AddStringToObject(j,"core",get_sems_version());
cJSON_AddStringToObject(j,"yeti",YETI_VERSION);
if(aleg_versions.empty()) {
cJSON_AddNullToObject(j,"bleg");
} else {
n = aleg_versions.size();
joined_versions.reserve(n*32);
i = 1;
for(const auto &agent : aleg_versions) {
joined_versions += agent;
if(i++!=n) joined_versions+=", ";
}
cJSON_AddStringToObject(j,"aleg",joined_versions.c_str());
}
if(bleg_versions.empty()) {
cJSON_AddNullToObject(j,"bleg");
} else {
joined_versions.clear();
n = bleg_versions.size();
joined_versions.reserve(n*32);
i = 1;
for(const auto &agent : bleg_versions) {
joined_versions += agent;
if(i++!=n) joined_versions+=", ";
}
cJSON_AddStringToObject(j,"bleg",joined_versions.c_str());
}
s = cJSON_PrintUnformatted(j);
cJSON_Delete(j);
return s;
}
void Cdr::add_versions_to_amarg(AmArg &arg) const
{
AmArg &v = arg["versions"];
v["core"] = get_sems_version();
v["yeti"] = YETI_VERSION;
AmArg &a = v["aleg"];
a.assertArray();
for(const auto &agent : aleg_versions)
a.push(agent);
AmArg &b = v["bleg"];
b.assertArray();
for(const auto &agent : bleg_versions)
b.push(agent);
}
#undef add_str2json
#undef add_tv2json
#undef add_num2json
#undef field_name
static inline void invoc_AmArg(pqxx::prepare::invocation &invoc,const AmArg &arg)
{
short type = arg.getType();
switch(type) {
case AmArg::Int:
invoc(arg.asInt());
break;
case AmArg::LongLong:
invoc(arg.asLongLong());
break;
case AmArg::Bool:
invoc(arg.asBool());
break;
case AmArg::CStr:
invoc(arg.asCStr());
break;
case AmArg::Undef:
invoc();
break;
default:
ERROR("invoc_AmArg. unhandled AmArg type %s",arg.t2str(type));
invoc();
}
}
void Cdr::invoc(
pqxx::prepare::invocation &invoc,
AmArg &invoced_values,
const DynFieldsT &df,
bool serialize_dynamic_fields)
{
#define invoc_field(field_value)\
invoced_values.push(AmArg(field_value));\
invoc(field_value);
#define invoc_null()\
invoced_values.push(AmArg());\
invoc();
#define invoc_field_cond(field_value,condition)\
if(condition) { invoc_field(field_value); }\
else { invoc_null(); }
#define invoc_json(func) do { \
char *s = func; \
invoc_field(s); \
free(s); \
} while(0)
invoc_field(attempt_num);
invoc_field(is_last);
invoc_field_cond(legA_transport_protocol_id,legA_transport_protocol_id!=0);
invoc_field(legA_local_ip);
invoc_field(legA_local_port);
invoc_field(legA_remote_ip);
invoc_field(legA_remote_port);
invoc_field_cond(legB_transport_protocol_id,legB_transport_protocol_id!=0);
invoc_field(legB_local_ip);
invoc_field(legB_local_port);
invoc_field(legB_remote_ip);
invoc_field(legB_remote_port);
invoc_json(serialize_timers_data());
invoc_field(sip_early_media_present);
invoc_field(disconnect_code);
invoc_field(disconnect_reason);
invoc_field(disconnect_initiator);
invoc_field(disconnect_internal_code);
invoc_field(disconnect_internal_reason);
if(is_last){
invoc_field(disconnect_rewrited_code);
invoc_field(disconnect_rewrited_reason);
} else {
invoc_field(0);
invoc_field("");
}
invoc_field(orig_call_id);
invoc_field(term_call_id);
invoc_field(local_tag);
invoc_field(msg_logger_path);
invoc_field(dump_level_id);
invoc_field(audio_record_enabled);
invoc_json(serialize_rtp_stats());
invoc_field(global_tag);
invoc_field(resources);
invoc_field(active_resources);
invoc_field_cond(failed_resource_type_id, failed_resource_type_id!=-1);
invoc_field_cond(failed_resource_id, failed_resource_id!=-1);
if(dtmf_events_a2b.empty() && dtmf_events_b2a.empty()) {
invoc_null();
} else {
invoc_json(serialize_dtmf_events());
}
invoc_json(serialize_versions());
invoc_field(is_redirected);
/* invocate dynamic fields */
if(serialize_dynamic_fields){
invoc_json(serialize_dynamic(df));
} else {
for(const auto &f : df)
invoc_AmArg(invoc, dyn_fields[f.name]);
}
/* invocate trusted hdrs */
for(const auto &h : trusted_hdrs)
invoc_AmArg(invoc,h);
#undef invoc_json
#undef invoc_field_cond
#undef invoc_null
#undef invoc_field
}
template<class T>
static void join_csv(ofstream &s, const T &a)
{
if(!a.size())
return;
int n = a.size()-1;
s << ",";
for(int k = 0;k<n;k++)
s << "'" << AmArg::print(a[k]) << "',";
s << "'" << AmArg::print(a[n]) << "'";
}
void Cdr::to_csv_stream(ofstream &s, const DynFieldsT &df)
{
#define add_value(v) s << "'"<<v<< "'" << ','
#define add_json(func) do { \
char *jstr = func; \
add_value(jstr); \
free(jstr); \
} while(0)
add_value(attempt_num);
add_value(is_last);
add_value(legA_local_ip); add_value(legA_local_port);
add_value(legA_remote_ip); add_value(legA_remote_port);
add_value(legB_local_ip); add_value(legB_local_port);
add_value(legB_remote_ip); add_value(legB_remote_port);
add_value(sip_early_media_present);
add_json(serialize_timers_data());
add_value(disconnect_code); add_value(disconnect_reason);
add_value(disconnect_initiator);
add_value(disconnect_internal_code); add_value(disconnect_internal_reason);
if(is_last){
add_value(disconnect_rewrited_code);
add_value(disconnect_rewrited_reason);
} else {
add_value(0);
add_value("");
}
add_value(orig_call_id); add_value(term_call_id);
add_value(local_tag); add_value(msg_logger_path);
add_value(dump_level_id);
add_json(serialize_rtp_stats());
add_value(global_tag);
add_value(resources);
add_value(active_resources);
//dynamic fields
if(dyn_fields.size()){
s << ",";
for(DynFieldsT_const_iterator it = df.begin();
it!=df.end();++it)
{
if(it!=df.begin()) s << ",";
s << "'" << AmArg::print(dyn_fields[it->name]) << "'";
}
}
//trusted fields
join_csv(s,trusted_hdrs);
#undef add_json
#undef add_value
}
void Cdr::snapshot_info(AmArg &s, const DynFieldsT &df)
{
static char strftime_buf[64] = {0};
static struct tm tt;
#define add_field(val) s[#val] = val;
#define add_field_as(name,val) s[name] = val;
#define add_timeval_field(val) s[#val] = timerisset(&val) ? timeval2str(val) : AmArg();
add_timeval_field(cdr_born_time);
add_timeval_field(start_time);
add_timeval_field(connect_time);
localtime_r(&start_time.tv_sec,&tt);
int len = strftime(strftime_buf, sizeof strftime_buf, "%F", &tt);
s["start_date"] = string(strftime_buf,len);
add_field(legB_remote_port);
add_field(legB_local_port);
add_field(legA_remote_port);
add_field(legA_local_port);
add_field(legB_remote_ip);
add_field(legB_local_ip);
add_field(legA_remote_ip);
add_field(legA_local_ip);
add_field(orig_call_id);
add_field(term_call_id);
add_field(local_tag);
add_field(global_tag);
add_field(time_limit);
add_field(dump_level_id);
add_field_as("audio_record_enabled", audio_record_enabled ? 1 : 0);
add_field(attempt_num);
add_field(resources);
add_field(active_resources);
if(isArgStruct(active_resources_clickhouse))
for(const auto &a : *active_resources_clickhouse.asStruct())
s[a.first] = a.second;
for(const auto &d: df) {
const string &fname = d.name;
AmArg &f = dyn_fields[fname];
//cast bool to int
if(d.type_id==DynField::BOOL) {
if(!isArgBool(f)) continue;
add_field_as(fname,(f.asBool() ? 1 : 0));
continue;
}
add_field_as(fname,f);
}
#undef add_field
#undef add_field_as
#undef add_timeval_field
}
void Cdr::snapshot_info_filtered(AmArg &s, const DynFieldsT &df,
const unordered_set<string> &wanted_fields)
{
static char strftime_buf[64] = {0};
static struct tm tt;
#define filter(name)\
static const string name ## _key( #name ); \
if(wanted_fields.count( name ## _key )>0)
#define add_field(val) \
filter(val) s[ val ## _key ] = val;
#define add_field_as(name,val) \
filter(name) s[ name ## _key ] = val;
#define add_timeval_field(val) \
filter(val) s[ val ## _key ] = timerisset(&val) ? timeval2str(val) : AmArg();
add_timeval_field(cdr_born_time);
add_timeval_field(start_time);
add_timeval_field(connect_time);
localtime_r(&start_time.tv_sec,&tt);
int len = strftime(strftime_buf, sizeof strftime_buf, "%F", &tt);
s["start_date"] = string(strftime_buf,len);
add_field(legB_remote_port);
add_field(legB_local_port);
add_field(legA_remote_port);
add_field(legA_local_port);
add_field(legB_remote_ip);
add_field(legB_local_ip);
add_field(legA_remote_ip);
add_field(legA_local_ip);
add_field(orig_call_id);
add_field(term_call_id);
add_field(local_tag);
add_field(global_tag);
add_field(time_limit);
add_field(dump_level_id);
add_field_as(audio_record_enabled, audio_record_enabled ? 1 : 0);
add_field(attempt_num);
add_field(resources);
filter(active_resources) {
add_field_as(active_resources_key,active_resources);
if(isArgStruct(active_resources_clickhouse))
for(const auto &a : *active_resources_clickhouse.asStruct())
s[a.first] = a.second;
}
for(const auto &d: df) {
const string &fname = d.name;
AmArg &f = dyn_fields[fname];
//cast bool to int
if(d.type_id==DynField::BOOL) {
if(!isArgBool(f)) continue;
if(!wanted_fields.count(fname)) continue;
s[fname] = f.asBool() ? 1 : 0;
continue;
}
if(wanted_fields.count(fname))
s[fname] = f;
}
#undef add_field
#undef add_field_as
#undef add_timeval_field
#undef filter
}
void Cdr::info(AmArg &s)
{
s["dump_level"] = dump_level2str(dump_level_id);
if(dump_level_id)
s["logger_path"] = msg_logger_path;
s["internal_reason"] = disconnect_internal_reason;
s["internal_code"] = disconnect_internal_code;
s["initiator"] = DisconnectInitiator2Str(disconnect_initiator);
s["start_time"] = timeval2double(start_time);
s["connect_time"] = timeval2double(connect_time);
s["end_time"] = timeval2double(end_time);
s["10x_time"] = timeval2double(sip_10x_time);
s["18x_time"] = timeval2double(sip_18x_time);
s["resources"] = resources;
s["active_resources"] = active_resources;
}
<file_sep>#pragma once
#include "SqlRouter.h"
#include "hash/CdrList.h"
#include "resources/ResourceControl.h"
#include <yeti/yeticc.h>
#include "AmConfigReader.h"
#include <ctime>
#include "log.h"
#define YETI_ENABLE_PROFILING 1
#define YETI_CALL_DURATION_TIMER SBC_TIMER_ID_CALL_TIMERS_START
#define YETI_RINGING_TIMEOUT_TIMER (SBC_TIMER_ID_CALL_TIMERS_START+1)
#define YETI_RADIUS_INTERIM_TIMER (SBC_TIMER_ID_CALL_TIMERS_START+2)
#define YETI_FAKE_RINGING_TIMER (SBC_TIMER_ID_CALL_TIMERS_START+3)
#if YETI_ENABLE_PROFILING
#define PROF_START(var) timeval prof_start_ ## var; gettimeofday(&prof_start_ ## var,NULL);
#define PROF_END(var) timeval prof_end_ ## var; gettimeofday(&prof_end_ ## var,NULL);
#define PROF_DIFF(var) timeval prof_diff_ ## var; timersub(&prof_end_ ## var,&prof_start_ ## var,&prof_diff_ ## var);
#define PROF_PRINT(descr,var) PROF_DIFF(var); DBG("PROFILING: " descr " took %s",timeval2str_usec(prof_diff_ ## var).c_str());
#else
#define PROF_START(var) ;
#define PROF_END(var) ;
#define PROF_DIFF(var) (-1)
#define PROF_PRINT(descr,var) ;
#endif
class YetiCfgReader : public AmConfigReader, public yeti::cfg::reader {
public:
void on_key_value_param(const string &name,const string &value){
setParameter(name,value);
}
};
struct YetiBaseParams {
SqlRouter &router;
CdrList &cdr_list;
ResourceControl &rctl;
YetiBaseParams(
SqlRouter &router,
CdrList &cdr_list,
ResourceControl &rctl)
: router(router),
cdr_list(cdr_list),
rctl(rctl)
{ }
};
struct YetiBase {
YetiBase(YetiBaseParams ¶ms)
: router(params.router),
cdr_list(params.cdr_list),
rctl(params.rctl)
{ }
SqlRouter &router;
CdrList &cdr_list;
ResourceControl &rctl;
struct global_config {
int node_id;
int pop_id;
bool use_radius;
bool early_100_trying;
string routing_schema;
string msg_logger_dir;
string audio_recorder_dir;
bool audio_recorder_compress;
string log_dir;
} config;
YetiCfgReader cfg;
time_t start_time;
};
<file_sep>/*
* Copyright (C) 2010-2011 <NAME>
*
* This file is part of SEMS, a free SIP media server.
*
* SEMS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* For a license to use the SEMS software under conditions
* other than those described here, or to purchase support for this
* software, please contact iptel.org by e-mail at the following addresses:
* <EMAIL>
*
* SEMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
SBC - feature-wishlist
- accounting (MySQL DB, cassandra DB)
- RTP transcoding mode (bridging)
- overload handling (parallel call to target thresholds)
- call distribution
- select profile on monitoring in-mem DB record
*/
#include "SBC.h"
#include "SBCCallControlAPI.h"
#include "log.h"
#include "AmUtils.h"
#include "AmAudio.h"
#include "AmPlugIn.h"
#include "AmMediaProcessor.h"
#include "AmConfigReader.h"
#include "AmSessionContainer.h"
#include "AmSipHeaders.h"
#include "SBCSimpleRelay.h"
#include "RegisterDialog.h"
#include "SubscriptionDialog.h"
#include "sip/pcap_logger.h"
#include "sip/sip_parser.h"
#include "sip/sip_trans.h"
#include "HeaderFilter.h"
#include "ParamReplacer.h"
#include "SDPFilter.h"
#include "SBCCallLeg.h"
#include "AmEventQueueProcessor.h"
#include "SubscriptionDialog.h"
#include "RegisterDialog.h"
#include "RegisterCache.h"
#include <algorithm>
#include "yeti.h"
#include "SipCtrlInterface.h"
using std::map;
EXPORT_MODULE_FACTORY(SBCFactory);
DEFINE_MODULE_INSTANCE(SBCFactory, MOD_NAME);
// helper functions
void assertEndCRLF(string& s) {
if (s[s.size()-2] != '\r' ||
s[s.size()-1] != '\n') {
while ((s[s.size()-1] == '\r') ||
(s[s.size()-1] == '\n'))
s.erase(s.size()-1);
s += "\r\n";
}
}
///////////////////////////////////////////////////////////////////////////////////////////
SBCCallLeg* CallLegCreator::create(CallCtx *call_ctx)
{
return new SBCCallLeg(call_ctx, new AmSipDialog());
}
SBCCallLeg* CallLegCreator::create(SBCCallLeg* caller)
{
return new SBCCallLeg(caller);
}
SimpleRelayCreator::Relay
SimpleRelayCreator::createRegisterRelay(SBCCallProfile& call_profile,
vector<AmDynInvoke*> &cc_modules)
{
return SimpleRelayCreator::Relay(new RegisterDialog(call_profile, cc_modules),
new RegisterDialog(call_profile, cc_modules));
}
SimpleRelayCreator::Relay
SimpleRelayCreator::createSubscriptionRelay(SBCCallProfile& call_profile,
vector<AmDynInvoke*> &cc_modules)
{
return SimpleRelayCreator::Relay(new SubscriptionDialog(call_profile, cc_modules),
new SubscriptionDialog(call_profile, cc_modules));
}
SimpleRelayCreator::Relay
SimpleRelayCreator::createGenericRelay(SBCCallProfile& call_profile,
vector<AmDynInvoke*> &cc_modules)
{
return SimpleRelayCreator::Relay(new SimpleRelayDialog(call_profile, cc_modules),
new SimpleRelayDialog(call_profile, cc_modules));
}
SBCFactory::SBCFactory(const string& _app_name)
: AmSessionFactory(_app_name),
AmDynInvokeFactory(_app_name),
core_options_handling(false),
callLegCreator(new CallLegCreator()),
simpleRelayCreator(new SimpleRelayCreator())
{
}
SBCFactory::~SBCFactory() {
RegisterCache::dispose();
yeti.reset();
}
int SBCFactory::onLoad()
{
if(cfg.loadFile(AmConfig::ModConfigPath + string(MOD_NAME ".conf"))) {
ERROR("No configuration for sbc present (%s)\n",
(AmConfig::ModConfigPath + string(MOD_NAME ".conf")).c_str()
);
return -1;
}
yeti.reset(Yeti::create_instance(YetiBaseParams(router,cdr_list,rctl)));
if(yeti->onLoad()){
ERROR("yeti configuration error\n");
return -1;
}
yeti_invoke = dynamic_cast<AmDynInvoke *>(yeti.get());
registrations_enabled = cfg.getParameter("registrations_enabled","yes")=="yes";
session_timer_fact = AmPlugIn::instance()->getFactory4Seh("session_timer");
if(!session_timer_fact) {
WARN("session_timer plug-in not loaded - "
"SIP Session Timers will not be supported\n");
}
vector<string> regex_maps = explode(cfg.getParameter("regex_maps"), ",");
for (vector<string>::iterator it =
regex_maps.begin(); it != regex_maps.end(); it++) {
string regex_map_file_name = AmConfig::ModConfigPath + *it + ".conf";
RegexMappingVector v;
if (!read_regex_mapping(regex_map_file_name, "=>",
("SBC regex mapping " + *it+":").c_str(), v)) {
ERROR("reading regex mapping from '%s'\n", regex_map_file_name.c_str());
return -1;
}
regex_mappings.setRegexMap(*it, v);
INFO("loaded regex mapping '%s'\n", it->c_str());
}
core_options_handling = cfg.getParameter("core_options_handling") == "yes";
DBG("OPTIONS messages handled by the core: %s\n", core_options_handling?"yes":"no");
if (!AmPlugIn::registerApplication(MOD_NAME, this)) {
ERROR("registering " MOD_NAME " application\n");
return -1;
}
if (!AmPlugIn::registerDIInterface(MOD_NAME, this)) {
ERROR("registering " MOD_NAME " DI interface\n");
return -1;
}
// TODO: add config param for the number of threads
subnot_processor.addThreads(1);
if(registrations_enabled)
RegisterCache::instance()->start();
return 0;
}
inline void answer_100_trying(const AmSipRequest &req, CallCtx *ctx)
{
AmSipReply reply;
reply.code = 100;
reply.reason = "Connecting";
reply.tt = req.tt;
if (AmConfig::Signature.length())
reply.hdrs += SIP_HDR_COLSP(SIP_HDR_SERVER) + AmConfig::Signature + CRLF;
if(SipCtrlInterface::send(reply,string(""),ctx->early_trying_logger,NULL)){
ERROR("Could not send early 100 Trying. call-id=%s, cseq = %i\n",
req.callid.c_str(),req.cseq);
}
}
AmSession* SBCFactory::onInvite(
const AmSipRequest& req,
const string&,
const map<string,string>&)
{
ParamReplacerCtx ctx;
CallCtx *call_ctx;
timeval t;
Auth::auth_id_type auth_id = 0;
AmArg ret;
bool authorized = false;
gettimeofday(&t,NULL);
call_ctx = new CallCtx();
if(yeti->config.early_100_trying)
answer_100_trying(req,call_ctx);
auth_id = router.check_invite_auth(req,ret);
if(auth_id > 0) {
DBG("successfully authorized with id %d",auth_id);
authorized = true;
} else if(auth_id < 0) {
DBG("auth error. reply with 401");
switch(-auth_id) {
case Auth::UAC_AUTH_ERROR:
AmSipDialog::reply_error(req,
ret[0].asInt(), ret[1].asCStr(),ret[2].asCStr());
break;
default:
router.send_auth_challenge(req);
}
delete call_ctx;
return NULL;
}
PROF_START(gprof);
router.getprofiles(req,*call_ctx,auth_id);
SqlCallProfile *profile = call_ctx->getFirstProfile();
if(NULL == profile){
delete call_ctx;
throw AmSession::Exception(500, SIP_REPLY_SERVER_INTERNAL_ERROR);
}
PROF_END(gprof);
PROF_PRINT("get profiles",gprof);
Cdr *cdr = call_ctx->cdr;
if(profile->auth_required) {
delete cdr;
delete call_ctx;
if(!authorized) {
DBG("auth required for not authorized request. send auth challenge");
router.send_auth_challenge(req);
} else {
ERROR("got callprofile with auth_required "
"for already authorized request. reply internal error");
AmSipDialog::reply_error(req,500,SIP_REPLY_SERVER_INTERNAL_ERROR);
}
return NULL;
}
cdr->set_start_time(t);
ctx.call_profile = profile;
if(router.check_and_refuse(profile,cdr,req,ctx,true)) {
cdr->dump_level_id = 0; //override dump_level_id. we have no logging at this stage
if(!call_ctx->SQLexception) { //avoid to write cdr on failed getprofile()
router.write_cdr(cdr,true);
} else {
delete cdr;
}
delete call_ctx;
return NULL;
}
SBCCallLeg* leg = callLegCreator->create(call_ctx);
if(!leg) {
DBG("failed to create B2B leg");
delete cdr;
delete call_ctx;
return NULL;
}
SBCCallProfile& call_profile = leg->getCallProfile();
if (call_profile.auth_aleg_enabled) {
// adding auth handler
AmSessionEventHandlerFactory* uac_auth_f =
AmPlugIn::instance()->getFactory4Seh("uac_auth");
if (NULL == uac_auth_f) {
INFO("uac_auth module not loaded. uac auth for caller session NOT enabled.\n");
} else {
AmSessionEventHandler* h = uac_auth_f->getHandler(leg);
// we cannot use the generic AmSessionEventHandler hooks,
// because the hooks don't work in AmB2BSession
leg->setAuthHandler(h);
DBG("uac auth enabled for caller session.\n");
}
}
return leg;
}
void SBCFactory::onOoDRequest(const AmSipRequest& req)
{
DBG("processing message %s %s\n", req.method.c_str(), req.r_uri.c_str());
if (core_options_handling && req.method == SIP_METH_OPTIONS) {
DBG("processing OPTIONS in core\n");
AmSessionFactory::onOoDRequest(req);
return;
}
AmSipDialog::reply_error(req, 405, "Method Not Allowed");
return;
#if 0
if(req.max_forwards == 0) {
AmSipDialog::reply_error(req, 483, SIP_REPLY_TOO_MANY_HOPS);
return;
}
SimpleRelayCreator::Relay relay(NULL,NULL);
if(req.method == SIP_METH_REGISTER) {
if(registrations_enabled) {
relay = simpleRelayCreator->createRegisterRelay(call_profile, cc_modules);
} else {
AmSipDialog::reply_error(req,405,"Method Not Allowed");
return;
}
}
else if((req.method == SIP_METH_SUBSCRIBE) ||
(req.method == SIP_METH_REFER)){
relay = simpleRelayCreator->createSubscriptionRelay(call_profile, cc_modules);
}
else {
relay = simpleRelayCreator->createGenericRelay(call_profile, cc_modules);
}
if (call_profile.log_sip) {
relay.first->setMsgLogger(call_profile.get_logger(req));
relay.second->setMsgLogger(call_profile.get_logger(req));
}
if(SBCSimpleRelay::start(relay,req,call_profile)) {
AmSipDialog::reply_error(req, 500, SIP_REPLY_SERVER_INTERNAL_ERROR,
"", call_profile.log_sip ? call_profile.get_logger(req): NULL);
delete relay.first;
delete relay.second;
}
#endif
}
void SBCFactory::invoke(const string& method, const AmArg& args,
AmArg& ret)
{
if (method == "getRegexMapNames"){
getRegexMapNames(args,ret);
} else if (method == "setRegexMap"){
args.assertArrayFmt("u");
setRegexMap(args,ret);
} else if (method == "postControlCmd"){
args.assertArrayFmt("ss"); // at least call-ltag, cmd
postControlCmd(args,ret);
} else if(method == "_list"){
ret.push(AmArg("getRegexMapNames"));
ret.push(AmArg("setRegexMap"));
ret.push(AmArg("postControlCmd"));
ret.push(AmArg("printCallStats"));
} else if(method == "printCallStats"){
B2BMediaStatistics::instance()->getReport(args, ret);
} else
throw AmDynInvoke::NotImplemented(method);
}
void SBCFactory::getRegexMapNames(const AmArg& args, AmArg& ret) {
AmArg p;
vector<string> reg_names = regex_mappings.getNames();
for (vector<string>::iterator it=reg_names.begin();
it != reg_names.end(); it++) {
p["regex_maps"].push(*it);
}
ret.push(200);
ret.push("OK");
ret.push(p);
}
void SBCFactory::setRegexMap(const AmArg& args, AmArg& ret) {
if (!args[0].hasMember("name") || !args[0].hasMember("file") ||
!isArgCStr(args[0]["name"]) || !isArgCStr(args[0]["file"])) {
ret.push(400);
ret.push("Parameters error: expected ['name': <name>, 'file': <file name>]");
return;
}
string m_name = args[0]["name"].asCStr();
string m_file = args[0]["file"].asCStr();
RegexMappingVector v;
if (!read_regex_mapping(m_file, "=>", "SBC regex mapping", v)) {
ERROR("reading regex mapping from '%s'\n", m_file.c_str());
ret.push(401);
ret.push("Error reading regex mapping from file");
return;
}
regex_mappings.setRegexMap(m_name, v);
ret.push(200);
ret.push("OK");
}
void SBCFactory::postControlCmd(const AmArg& args, AmArg& ret) {
SBCControlEvent* evt;
if (args.size()<3) {
evt = new SBCControlEvent(args[1].asCStr());
} else {
evt = new SBCControlEvent(args[1].asCStr(), args[2]);
}
if (!AmSessionContainer::instance()->postEvent(args[0].asCStr(), evt)) {
ret.push(404);
ret.push("Not found");
} else {
ret.push(202);
ret.push("Accepted");
}
}
|
7db9b25adabe0feb7f4447b27b1dbaa07375199f
|
[
"C++"
] | 5
|
C++
|
vdedyukhin/sems-yeti
|
2566edb84fd5cfea3b3ae2a2f12f79a8fa6a07dd
|
b53133971d99694aee59370d3b640343f6402d91
|
refs/heads/lab1
|
<file_sep>package lab3.store;
import lab3.model.Wood;
public class WoodDirectory extends AbstractStore {
public Wood get(int id) {
for (Object o : arr) {
Wood wood = (Wood) o;
if (wood.getId() == id)
return wood;
}
return null;
}
public boolean add(Wood newWood) {
if (get(newWood.getId()) != null)
return false;
super.add(newWood);
return true;
}
public String toString() {
return "Каталог деревини:\n" + super.toString();
}
}
<file_sep>package lab1.tests;
import lab1.model.Timber;
import lab1.store.ProductStore;
import lab1.store.WoodDirectory;
public class TestApp {
WoodDirectory wd = new WoodDirectory();
ProductStore ps = new ProductStore();
public static void main(String[] args) {
TestApp app = new TestApp();
app.startApp();
}
private void startApp() {
ps.add(new Timber(wd.get(1), 5f, 0.5f, 0.4f));
ps.add(new Timber(wd.get(2), 10f, 0.5f, 0.4f));
ps.add(new Timber(wd.get(3), 10f, 0.5f, 0.4f));
System.out.println(wd);
System.out.println(ps);
System.out.printf("Загальна вага: %1.3f", ps.calcWeight());
}
}
<file_sep>package lab3.tests;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class TestReadFile {
public static void main(String[] args) {
JFileChooser dialog = new JFileChooser();
dialog.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "файли типу *.txt";
}
@Override
public boolean accept(File f) {
if (f != null) {
return f.isDirectory() || f.toString().endsWith(".txt");
}
return false;
}
});
dialog.showOpenDialog(null);
File f = dialog.getSelectedFile();
if (f != null) {
System.out.println(f.getName());
System.out.println(f.getAbsolutePath());
}
BufferedReader reader = null;
if (f != null) {
try {
reader = new BufferedReader(new FileReader(f));
String s;
while ((s = reader.readLine()) != null) {
System.out.println(s);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
<file_sep>package lab3.tests;
import lab3.store.WoodDirectory;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class TestRestoreObject {
public static void main(String[] args) {
WoodDirectory woodDirectory = null;
File f = new File("woodDirectory.object");
try {
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
woodDirectory = (WoodDirectory) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
if (woodDirectory != null) {
for (Object w : woodDirectory.getArr())
System.out.println(w.toString());
}
}
}
<file_sep>package lab2.tests;
import lab2.model.*;
import lab2.store.ProductStore;
import lab2.store.WoodDirectory;
public class TestApp {
WoodDirectory woodDirectory = new WoodDirectory();
ProductStore productStore = new ProductStore();
public static void main(String[] args) {
TestApp app = new TestApp();
app.startApp();
}
private void startApp() {
woodDirectory.add(new Wood(1, "Модрина", 1.1f));
woodDirectory.add(new Wood(2, "Ялина", 0.9f));
woodDirectory.add(new Wood(3, "Сосна", 0.7f));
productStore.add(new Timber(woodDirectory.get(1), 5f, 0.5f, 0.4f));
productStore.add(new Timber(woodDirectory.get(2), 10f, 0.5f, 0.4f));
productStore.add(new Timber(woodDirectory.get(3), 10f, 0.5f, 0.4f));
productStore.add(new Cylinder(woodDirectory.get(3), 10f, 0.5f));
productStore.add(new Cylinder(woodDirectory.get(2), 15f, 0.7f));
productStore.add(new Waste(10f));
productStore.add(new Waste(7f));
System.out.println(woodDirectory);
System.out.println(productStore);
System.out.printf("Загальна вага: %1.3f", calcWeight());
}
private float calcWeight() {
float fullWeight = 0;
for (Object timber : productStore.getArr()) {
fullWeight += ((IWeight) timber).weight();
}
return fullWeight;
}
}
<file_sep>package lab3.tests;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class TestFile {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
JFileChooser dialog = new JFileChooser();
dialog.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "файли типу *.txt";
}
@Override
public boolean accept(File f) {
if (f != null) {
return f.isDirectory() || f.toString().endsWith(".txt");
}
return false;
}
});
dialog.showOpenDialog(null);
File f = dialog.getSelectedFile();
if (f != null) {
System.out.println(f.getName());
System.out.println(f.getAbsolutePath());
}
try {
assert f != null;
BufferedWriter writer = new BufferedWriter(new FileWriter(f));
for (int i = 0; i < 10; i++) {
double x = Math.random();
String s = String.valueOf(x);
writer.write(s);
writer.newLine();
}
String name = "Daria ";
String group = "KN_19";
writer.write(name + group);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
4ec810dee3c8e9f77c9090e315f5b6b47fc1b77a
|
[
"Java"
] | 6
|
Java
|
Angel-88/university-Java
|
176de05b524ad1355fd0c6453b6cd2af4a922290
|
cc782899043fa6a768a7098562b6aba1ecfe63a8
|
refs/heads/main
|
<repo_name>nbgspl-github/python<file_sep>/paradigmatic/app/v1/users/controller.py
import typing as t
from paradigmatic.app.v1.core.security import get_password_hash
from fastapi import HTTPException, status, UploadFile
from . import models as user_models, schemas
def get_user(user_id: str) -> user_models.User:
user = user_models.User.objects.get(id=user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
def create_user(new_user: schemas.UserCreate) -> user_models.User:
new_user_dict = new_user.dict(exclude_unset=True)
if "password" in new_user_dict and new_user_dict["password"]:
hashed_password = get_password_hash(new_user_dict["password"])
new_user_dict["hashed_password"] = hashed_password
new_user_dict.pop("password")
new_user = user_models.User(**new_user_dict).save()
return new_user
def get_users(skip: int = 0, limit: int = 100) -> t.List[schemas.User]:
return [o.to_mongo().to_dict() for o in user_models.User.objects()[skip:limit]]
def get_user_by_email(email: str) -> user_models.User:
return user_models.User.objects(email=email).first()
def edit_user(user_id: str, user: schemas.UserEdit) -> schemas.User:
update_data = user.dict(exclude_unset=True)
if "password" in update_data:
update_data["hashed_password"] = get_password_hash(user.password)
del update_data["password"]
user_models.User.objects.get(id=user_id).update(**update_data)
return get_user(user_id)
def delete_user(user_id: str):
user = get_user(user_id)
if not user:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="User not found")
user.delete()
return True
def get_user_self_details(current_user: schemas.User) -> dict:
current_user = current_user.to_mongo().to_dict()
return current_user
def get_user_id_by_username(username=None):
if username is not None:
user_obj = user_models.User.objects.get(username=username)
return user_obj.id
all_user_objs = user_models.User.objects().all()
user_id_by_username = {}
for user in all_user_objs:
user_id_by_username[user.username] = str(user.id)
return user_id_by_username
<file_sep>/paradigmatic/app/v1/graphs/schemas.py
import typing as t
from ..custom_base_schemas import CustomBaseModel, CustomIdModel
from pydantic import BaseModel
to = t.Optional
class GraphBase(CustomBaseModel):
name: str
description: to[str]
vis_id: to[str]
class GraphEdit(BaseModel):
name: to[str]
description: to[str]
class Graph(GraphBase, CustomIdModel):
pass
class NodeBase(CustomBaseModel):
graph_id: str
label: str
description: to[str]
vis_id: to[str]
x: to[float]
y: to[float]
class NodeEdit(BaseModel):
label: to[str]
description: to[str]
x: to[float]
y: to[float]
class Node(NodeBase, CustomIdModel):
pass
class EdgeBase(CustomBaseModel):
vis_id: to[str]
label: to[str]
source_id: str
destination_id: str
class Edge(EdgeBase, CustomIdModel):
pass
class NodeDescriptionBase(CustomBaseModel):
node_id: str
user_name: str
user_recommended: bool
description: to[str]
class NodeDescription(NodeDescriptionBase, CustomIdModel):
pass
class NodeEdgeList(BaseModel):
nodes: list
edges: list
<file_sep>/paradigmatic/manage.py
import uvicorn
from app.v1.auth.routes import auth_router
from paradigmatic.app.v1.core import config
from paradigmatic.app.v1.core.auth import get_current_active_user
from paradigmatic.app.v1.core.config import API_PREFIX
from paradigmatic.app.v1.graphs.routes import graphs_router
from paradigmatic.app.v1.users.routes import users_router
from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from mongoengine import connect
app = FastAPI(
title=config.PROJECT_NAME, docs_url="/api/docs", openapi_url="/api"
)
origins = [
"http://localhost",
"http://localhost:1112",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
connect('paradigmatic', host='mongo', port=27017, username="paradigmatic", password="<PASSWORD>", authentication_source='admin')
@app.get("/api/v1")
async def root():
return {"message": "Hello World"}
# Routers
app.include_router(
users_router,
prefix=API_PREFIX,
tags=["users"],
dependencies=[Depends(get_current_active_user)],
)
app.include_router(auth_router, prefix=API_PREFIX, tags=["auth"])
app.include_router(
graphs_router,
prefix=API_PREFIX,
tags=["graphs"],
dependencies=[Depends(get_current_active_user)],
)
if __name__ == "__main__":
uvicorn.run("manage:app", host="0.0.0.0", reload=True, port=8888)
<file_sep>/paradigmatic/app/v1/users/routes.py
import logging
import typing as t
from paradigmatic.app.v1.core.auth import get_current_active_superuser, get_current_active_user
from fastapi import APIRouter, Depends, File, Request, Response, UploadFile, Form, HTTPException
from . import schemas
from .controller import (create_user, delete_user, edit_user, get_user, get_user_self_details,get_users)
users_router = r = APIRouter()
@r.get(
"/users",
response_model=t.List[schemas.User],
)
async def users_list(
response: Response,
current_user=Depends(get_current_active_superuser),
):
"""
Get all Users
"""
users = get_users()
# This is necessary for react-admin to work
response.headers["Content-Range"] = f"0-9/{len(users)}"
return users
@r.post("/users", response_model=schemas.User)
async def user_create(
request: Request,
user: schemas.UserCreate,
current_user=Depends(get_current_active_superuser)
):
"""
Create a new User
"""
return create_user(user).to_mongo().to_dict()
@r.get("/users/me", response_model=schemas.UserSelfDetailed, response_model_exclude_none=True)
async def user_me(current_user=Depends(get_current_active_user)):
"""
Get own User
"""
return get_user_self_details(current_user)
@r.get("/users/{user_id}", response_model=schemas.User)
async def user_details(
request: Request,
user_id: str,
current_user=Depends(get_current_active_superuser),
):
"""
Get any User details
"""
user = get_user(user_id)
return user.to_mongo().to_dict()
@r.put("/users/{user_id}", response_model=schemas.User)
async def user_edit(
request: Request,
user_id: str,
user: schemas.UserEdit,
current_user=Depends(get_current_active_user),
):
"""
Update existing User
"""
if str(user_id) != str(current_user.id):
raise HTTPException(
status_code=403, detail="The user doesn't have enough privileges"
)
updated_user = edit_user(user_id, user)
return updated_user.to_mongo().to_dict()
@r.delete(
"/users/{user_id}", response_model=schemas.User, response_model_exclude_none=True
)
async def user_delete(
request: Request,
user_id: str,
current_user=Depends(get_current_active_superuser),
):
"""
Delete existing User
"""
resp = delete_user(user_id)
if resp is True:
return {"success": True}
return {"success": False}
<file_sep>/paradigmatic/app/v1/graphs/models.py
import datetime
from mongoengine import Document, StringField, DateTimeField, FloatField
class Graph(Document):
vis_id = StringField()
name = StringField(max_length=50)
description = StringField()
created_at = DateTimeField(default=datetime.datetime.utcnow())
updated_at = DateTimeField(default=None)
class Node(Document):
graph_id = StringField()
vis_id = StringField()
label = StringField(max_length=50)
description = StringField()
x = FloatField()
y = FloatField()
created_at = DateTimeField(default=datetime.datetime.utcnow())
updated_at = DateTimeField(default=None)
class Edge(Document):
vis_id = StringField()
source_id = StringField(required=True)
destination_id = StringField(required=True)
label = StringField()
created_at = DateTimeField(default=datetime.datetime.utcnow())
updated_at = DateTimeField(default=None)
<file_sep>/paradigmatic/app/v1/graphs/controller.py
import copy
import datetime
import typing as t
from fastapi import HTTPException, status
from mongoengine import Q
from . import models, schemas
edge_rename_dict = {"to": "source_id", "from": "destination_id"}
def create_graph(graph: schemas.GraphBase) -> schemas.Graph:
new_graph_dict = graph.dict(by_alias=True)
new_graph = models.Graph(**new_graph_dict).save()
graph_dict = new_graph.to_mongo().to_dict()
return graph_dict
def list_graphs() -> t.List[schemas.Graph]:
all_graphs = models.Graph.objects()
return [graph.to_mongo().to_dict() for graph in all_graphs]
def get_graph(graph_id) -> schemas.Graph:
return models.Graph.objects().filter(id=graph_id).first().to_mongo().to_dict()
def create_node(node: schemas.NodeBase) -> schemas.Node:
new_node_dict = node.dict(by_alias=True)
new_node = models.Node(**new_node_dict).save()
node_dict = new_node.to_mongo().to_dict()
return node_dict
def get_node(node_vis_id: str) -> schemas.Node:
node = models.Node.objects.filter(vis_id=node_vis_id).first()
if not node:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="Object_not_found")
node_dict = node.to_mongo().to_dict()
return node_dict
def list_nodes(graph_id: str) -> schemas.NodeEdgeList:
node_objects = models.Node.objects.filter(graph_id=graph_id).all()
nodes = []
for curr_node in node_objects:
curr_dict = curr_node.to_mongo().to_dict()
curr_dict.pop("description", None)
curr_dict['_id'] = str(curr_dict['_id'])
nodes.append(curr_dict)
result = {"nodes": nodes, "edges": []}
edges = []
node_ids = [str(x["vis_id"]) for x in nodes]
edge_objects = models.Edge.objects.filter(Q(source_id__in=node_ids) or Q(destination_id__in=node_ids)).all()
for curr_edge in edge_objects:
curr_dict = curr_edge.to_mongo().to_dict()
curr_dict = bulk_rename_keys(curr_dict, reverse=True)
curr_dict['_id'] = str(curr_dict['_id'])
edges.append(curr_dict)
result["edges"] = edges
return schemas.NodeEdgeList(**result)
def update_node(node: schemas.NodeEdit, node_vis_id: str) -> schemas.Node:
object_query = models.Node.objects(vis_id=node_vis_id)
first_object = object_query.first()
if first_object is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail='node_not_found')
update_data = node.dict(exclude_unset=True)
update_data["updated_at"] = datetime.datetime.utcnow()
object_query.update(**update_data)
return object_query.first()
def delete_node(node_vis_id: str, with_subdata: bool = True):
node_query = models.Node.objects(vis_id=node_vis_id)
node_obj = node_query.first()
if not node_obj:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="Object_not_found")
if with_subdata:
source_edges = models.Edge.objects.filter(source_id=node_vis_id)
source_edges.delete()
destination_edges = models.Edge.objects.filter(destination_id=node_vis_id)
destination_edges.delete()
node_obj.delete()
return {"status": "success"}
def create_edge(new_edge_dict: dict) -> dict:
new_edge_backend = bulk_rename_keys(copy.deepcopy(new_edge_dict), edge_rename_dict)
new_edge = models.Edge(**new_edge_backend).save()
new_edge_dict["_id"] = str(new_edge.id)
return new_edge_dict
def bulk_rename_keys(user_dict, key_dict = edge_rename_dict, reverse = False):
for current_key in key_dict:
new_key = key_dict[current_key]
if reverse:
user_dict[current_key] = user_dict.pop(new_key)
else:
user_dict[new_key] = user_dict.pop(current_key)
return user_dict
def delete_edge(edge_vis_id: str):
edge_obj = models.Edge.objects(vis_id=edge_vis_id)
if not edge_obj:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="Edge_not_found")
edge_obj.delete()
return {"status": "success"}
<file_sep>/paradigmatic/app/v1/core/celery_app.py
from celery import Celery
celery_app = Celery("worker", broker="redis://redis:6379/0")
celery_app.conf.task_routes = {"paradigmatic.app.v1.tasks": "main-queue"}
<file_sep>/paradigmatic/app/v1/utils.py
import datetime
import re
from collections import defaultdict
from fastapi import HTTPException, status
from starlette.responses import FileResponse
# first item contains labels, original key forms the first label
def dict_to_list(mydict, keyname, labels=True):
new_list = []
current_dict = {}
for current_key in mydict.keys():
current_dict = mydict[current_key]
new_list.append([current_key] + list(current_dict.values()))
if labels:
labels = [keyname] + list(current_dict.keys())
new_list.insert(0, labels)
return new_list
def tuple_list_to_dict(tuple_list):
res = defaultdict(list)
for i, j in tuple_list:
res[i].append(j)
return dict(res)
def flatten_2level_list(listname):
flat_list = [item for sublist in listname for item in sublist]
return flat_list
def update_obj(object_id, object_schema, model_name, error_msg='Object_not_found'):
object_query = model_name.objects(id=object_id)
first_object = object_query.first()
if first_object is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail=error_msg)
update_data = object_schema
if not type(object_schema) == dict:
update_data = update_data.dict(exclude_unset=True)
update_data["updated_at"] = datetime.datetime.utcnow()
object_query.update(**update_data)
return object_query.first()
def rename_attribute(object_, old_attribute_name, new_attribute_name):
setattr(object_, new_attribute_name, getattr(object_, old_attribute_name))
delattr(object_, old_attribute_name) # this is not working
return object_
def rename_field(model_name, old_field_name, new_field_name):
object_list = model_name.objects().all()
all_objects = []
for obj in object_list:
renamed_obj = rename_attribute(obj, old_field_name, new_field_name)
renamed_obj.save()
all_objects.append(renamed_obj)
return all_objects
def add_field(model_name, field_name, value):
object_list = model_name.objects().all()
for obj in object_list:
setattr(obj, field_name, value)
obj.save()
return
async def app(scope, receive, send):
assert scope['type'] == 'http'
response = FileResponse('statics/favicon.ico')
await response(scope, receive, send)
def convert_username_to_ids(user_id_by_username, groups):
new_groups = []
for group in groups:
new_groups.append([user_id_by_username[username] for username in group])
return new_groups
def add_years_current_datetime(years):
c = datetime.datetime.utcnow()
n = c.replace(year=c.year + years)
return n
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
return [atoi(c) for c in re.split(r'(\d+)', text)]
def natural_sort(my_list):
return my_list.sort(key=natural_keys)
<file_sep>/paradigmatic/app/v1/tasks.py
import os
from paradigmatic.app.v1.core.celery_app import celery_app
@celery_app.task(acks_late=True)
def example_task(word: str) -> str:
return f"test task returns {word}"
dir_path = os.path.dirname(os.path.realpath(__file__))
<file_sep>/paradigmatic/app/v1/auth/routes.py
from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from app.v1.core.auth import authenticate_user, sign_up_new_user
from app.v1.core.security import (ACCESS_TOKEN_EXPIRE_MINUTES, create_access_token)
from app.v1.session import get_db
auth_router = r = APIRouter()
@r.post("/token")
async def login(
form_data: OAuth2PasswordRequestForm = Depends()
):
user = authenticate_user(form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(
minutes=ACCESS_TOKEN_EXPIRE_MINUTES
)
if user.is_superuser:
permissions = "admin"
else:
permissions = "user"
access_token = create_access_token(
data={"sub": user.email, "permissions": permissions},
expires_delta=access_token_expires,
)
return {"access_token": access_token, "token_type": "bearer"}
@r.post("/signup")
async def signup(form_data: OAuth2PasswordRequestForm = Depends()
):
user = sign_up_new_user(form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Account already exists",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(
minutes=ACCESS_TOKEN_EXPIRE_MINUTES
)
if user.is_superuser:
permissions = "admin"
else:
permissions = "user"
access_token = create_access_token(
data={"sub": user.email, "permissions": permissions},
expires_delta=access_token_expires,
)
return {"access_token": access_token, "token_type": "bearer"}
<file_sep>/paradigmatic/app/v1/session.py
# from sqlalchemy import create_engine
# from sqlalchemy.ext.declarative import declarative_base
# from sqlalchemy.orm import sessionmaker
#
# from paradigmatic.app.v1.core import config
#
# engine = create_engine(
# config.SQLALCHEMY_DATABASE_URI,
# )
# SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
#
# Base = declarative_base()
# Dependency
def get_db():
pass
# db = SessionLocal()
# try:
# yield db
# finally:
# db.close()
|
1fa2c80f6f199011555e323a4865b327821aa02a
|
[
"Python"
] | 11
|
Python
|
nbgspl-github/python
|
85b595fb18dde61d9aa844055887440e480bd3a0
|
e1bcf824f1a80ea64b0e7b1ad0d1458a42019a49
|
refs/heads/master
|
<file_sep>'use strict';
var _$ionicLoading;
var _VelovService;
var _ = require('lodash');
// Maps controller class
function MapsCtrl($ionicLoading, VelovService,$state) {
_$ionicLoading = $ionicLoading;
_VelovService = VelovService;
this.stationId = $state.params.stationId;
this.stations = [];
this.map = { center: { latitude: 45, longitude: -73 }, zoom: 8 };
this.getMarkers();
}
/**
* map created event
*/
MapsCtrl.prototype.getMarkers = function (cb) {
_VelovService.getData().then(function (result) {
this.stations = result;
if(this.stationId)
{
this.centerOnStation(this.stationId);
}
else {
this.center();
}
}.bind(this));
};
MapsCtrl.prototype.center = function(stationId){
console.log('on me');
_$ionicLoading.show({
content: 'Getting current location...',
showBackdrop: false
});
if(stationId){
this.map = { center: { latitude: station.latitude, longitude: station.longitude }, zoom: 14 };
}else{
_VelovService.getCurrentPosition().then(function(pos){
_$ionicLoading.hide();
this.map = { center: { latitude: pos.coords.latitude, longitude: pos.coords.longitude }, zoom: 14 };
}.bind(this));
}
};
/**
* Centering on current station
*/
MapsCtrl.prototype.centerOnStation = function (stationId) {
console.log(stationId);
var station = _.findWhere(this.stations, { idkey: stationId});
this.map = { center: { latitude: station.latitude, longitude: station.longitude }, zoom: 17 };
};
/**
* handle marker click
*/
MapsCtrl.prototype.onMarkerClick = function (gmarker, event, marker){
console.log('not implemented yet');
};
module.exports = MapsCtrl;<file_sep>'use strict';
var _ = require('lodash');
var _$ionicLoading;
var _VelovService;
// Maps controller class
function ListCtrl($ionicLoading, VelovService, $scope) {
_$ionicLoading = $ionicLoading;
_VelovService = VelovService;
this.position = {};
this.scope = $scope;
this.getData();
}
/**
* get data velov
*/
ListCtrl.prototype.getData = function () {
var self = this;
_$ionicLoading.show();
_VelovService.getCurrentPosition().then(function (pos) {
self.position = pos;
_VelovService.getData().then(function (stations) {
self.data = self.sortByDistance(self.position, stations);
_$ionicLoading.hide();
});
});
};
ListCtrl.prototype.sortByDistance = function (position, list) {
list.forEach(function (station) {
var loc = new google.maps.LatLng(station.latitude, station.longitude);
var myLoc = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var distance = google.maps.geometry.spherical.computeDistanceBetween(myLoc, loc);
station.distance = distance;
}, this);
return _.sortBy(list, 'distance');
};
/**
* pull to refresh
*/
ListCtrl.prototype.refresh = function (showLoading) {
var self = this;
if (showLoading) {
_$ionicLoading.show();
}
_VelovService.getCurrentPosition().then(function (pos) {
self.position = pos;
_VelovService.getData().then(function (stations) {
self.data = self.sortByDistance(self.position, stations);
if (showLoading) {
_$ionicLoading.hide();
}
else {
self.scope.$broadcast('scroll.refreshComplete');
}
});
});
};
module.exports = ListCtrl;<file_sep>'use strict';
// privates
var _ = require('lodash');
var _$http;
var _$q;
var _$cordovaGeolocation;
// Velov service class
function VelovService($http,$cordovaGeolocation,$q) {
_$http = $http;
_$cordovaGeolocation = $cordovaGeolocation;
_$q = $q;
this.data = [];
}
/**
* getData
* @return {[type]}
*/
VelovService.prototype.getData = function () {
var deferred = _$q.defer();
var url = 'https://download.data.grandlyon.com/ws/rdata/jcd_jcdecaux.jcdvelov/all.json';
_$http.get(url).then(function(result){
this.data = _.map(result.data.values, function(item){
return {
idkey: item[0],
name: item[1],
availableBikes: item[13],
availableBikeStands: item[12],
latitude: item[8],
longitude: item[9]
};
});
deferred.resolve(this.data);
}.bind(this));
return deferred.promise;
};
/**
* get
*/
VelovService.prototype.getCurrentPosition = function(){
var deferred = _$q.defer();
if (ionic.Platform.isWebView()) {
var posOptions = { timeout: 10000, enableHighAccuracy: false };
_$cordovaGeolocation.getCurrentPosition(posOptions).then(function (pos) {
deferred.resolve(pos);
}, deferred.reject);
}
else {
navigator.geolocation.getCurrentPosition(function (pos) {
console.log('position fetched');
deferred.resolve(pos);
}, deferred.reject);
}
return deferred.promise;
};
module.exports = VelovService;<file_sep>// imports
var angular = require('angular');
require('angular-sanitize');
require('ionic-framework');
require('angular-ui-router');
require('angular-animate');
require('ng-cordova');
// Application routing and startup
var Router = require('./router');
var startUp = require('./startUp');
// Application modules
require('./components/velov/velov');
require('./components/menu/menu');
// application definition
var app = angular.module('app', [
'ionic',
'app.menu',
'app.velov',
'ngCordova'
]);
// application routing configuration
app.config([
'$stateProvider',
'$urlRouterProvider',
Router
]);
app.run(startUp);<file_sep># ionic-velov
Ionic Velov station application
Requirements
------------
* npm
* gulp
* nodejs
* ionic-cli (optional)
Getting started
---------------
Install dependencies:
npm install
build:
gulp build
run project with ionic (call gulp build):
ionic serve
|
e8282119833c15d8acc09f5419555d638ccb51e1
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
tomadj/ionic-velov
|
adf59d7219d57b1f5f63bd378b069320270eaf6f
|
89b3a041f32d8ed88f1ec8d56af7362adf694af1
|
refs/heads/main
|
<file_sep>package com.bsav.siapm.utils;
public class Constants {
public enum ERole {
ROLE_PROFESSOR,
ROLE_ADMIN,
}
}
<file_sep>package com.bsav.siapm.controller.responses;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class JwtResponse {
private String token;
private final String type = "Bearer";
private String document;
private String email;
private String role;
}
<file_sep>package com.bsav.siapm.entities;
public class DatabaseConstants {
public static final String DATABASE_SCHEMA = "public";
//TABLE NAMES
public static final String TABLE_USER = "user";
public static final String TABLE_ROLE = "role";
}
|
fc524a6da2de8b56a1bbf58d3e2cb3360a9988d4
|
[
"Java"
] | 3
|
Java
|
S8Vega/siapm-backend
|
b08029391d51788f652ef0bd4e77b32b9b963e87
|
afcd74a83fa7a002f3f379938ec3b46c97705c0a
|
refs/heads/master
|
<repo_name>Kuysolov/final_project_group_6<file_sep>/src/partials/page_advantages.html
<section class="page_advantages">
<div class="container">
<div class="wrap">
<p class="subject">старая традиционная школа</p>
<!-- <div class="subject">
<h3>старая традиционная школа</h3>
<svg class="icon" width="1" height="60">
<use href="./image/sprite.svg#icon-line"></use>
</svg>
</div> -->
<h2 class="title">
Почему приходят <br />
именно к нам?
</h2>
<p class="text">
О нас говорят только хорошее. Но лучше 1 раз увидеть и
прочувствовать, чем 10 раз прочитать.
</p>
</div>
<ul class="items">
<li class="item" data-aos="zoom-in-down" data-aos-delay="150">
<h2 class="number">600</h2>
<p class="item-text">Довольных клиентов в день</p>
</li>
<li class="item" data-aos="zoom-in-down" data-aos-delay="300">
<h2 class="number">50</h2>
<p class="item-text">Наград за отличный сервис</p>
</li>
<li class="item" data-aos="zoom-in-down" data-aos-delay="400">
<h2 class="number">20</h2>
<p class="item-text">Лучших мастеров Киева</p>
</li>
<li class="item" data-aos="zoom-in-down" data-aos-delay="500">
<h2 class="number">100</h2>
<p class="item-text">Подарков постоянным клиентам</p>
<!-- <svg class="icon" width="13" height="22">
<use href="./image/sprite.svg#icon-plus.svg"></use>
</svg> -->
</li>
</ul>
</div>
</section>
<file_sep>/src/js/slider-script.js
$(".hero-container").each(function () {
var $slider = $(this);
var numberOfSlides = $slider.find(".panel").length;
$slider.find(".panel:eq(0)").addClass("_active");
$slider.find(".nav-dot:eq(0)").addClass("active");
var $activeSlide = $slider.find(".panel._active");
var $nextBtn = $slider.find(".next-button");
var $prevBtn = $slider.find(".prev-button");
$(".nav-dot").on("click", function () {
var slideToGo = $(this).data("slide");
goToSlide(slideToGo);
});
$slider.on("slide.changed", function () {
console.log("slide changed !");
$(".nav-dot").removeClass("active");
var $activeDot = $(
'.nav-dot[data-slide="' + $(".panel._active").data("slide") + '"]'
);
console.log();
$activeDot.addClass("active");
});
$nextBtn.on("click", function (event) {
nextSlide();
});
$prevBtn.on("click", function (event) {
prevSlide();
});
function nextSlide() {
$activeSlide = $slider.find(".panel._active");
var $nextSlide = $activeSlide.next(".panel");
$activeSlide.removeClass("_active");
$nextSlide.addClass("_active");
//$activeSlide = $nextSlide;
var slideIndex = $slider.find(".panel._active").index(".panel");
console.log(slideIndex);
if (slideIndex >= numberOfSlides || slideIndex <= -1) {
firstSlide();
$slider.trigger("slide.changed");
} else {
$slider.trigger("slide.changed");
}
}
function prevSlide() {
$activeSlide = $slider.find(".panel._active");
var $prevSlide = $activeSlide.prev(".panel");
$activeSlide.removeClass("_active");
$prevSlide.addClass("_active");
var slideIndex = $slider.find(".panel._active").index();
console.log(slideIndex);
if (
typeof $prevSlide === "undefined" ||
$prevSlide === null ||
$prevSlide.length == -1 ||
slideIndex <= -1
) {
lastSlide();
$slider.trigger("slide.changed");
} else {
$slider.trigger("slide.changed");
}
}
function firstSlide() {
$(".panel._active").removeClass("_active");
$slider.find(".panel:eq(0)").addClass("_active");
$activeSlide = $slider.find(".panel:eq(0)");
}
function lastSlide() {
$(".panel._active").removeClass("_active");
$slider
.find(".panel")
.eq(numberOfSlides - 1)
.addClass("_active");
}
function goToSlide(slideToGo) {
$(".panel._active").removeClass("_active");
$slider
.find(".panel")
.eq(slideToGo - 1)
.addClass("_active");
$activeSlide = $slider
.find(".panel")
.eq(slideToGo - 1)
.addClass("_active");
$slider.trigger("slide.changed");
}
});
|
1924aa46ad7775f93a4ce399f91ac938fb365910
|
[
"JavaScript",
"HTML"
] | 2
|
HTML
|
Kuysolov/final_project_group_6
|
4a4573211af373b1bd3f48694917c6e68528fd08
|
7e7ea0005a65ba99937135b3bd3afe25749d582a
|
refs/heads/master
|
<repo_name>gabrielbartoczevicz/gostack-11-challanges<file_sep>/packages/challange-06/src/config/upload.ts
import multer from 'multer';
import crypto from 'crypto';
import path from 'path';
const uploadFolder = path.resolve(__dirname, '..', '..', 'tmp');
export default {
directory: uploadFolder,
storage: multer.diskStorage({
destination: uploadFolder,
filename: (req, file, cb) => {
const hash = crypto.randomBytes(10).toString('HEX');
const fileName = `${hash}-${file.originalname}`;
return cb(null, fileName);
},
}),
};
<file_sep>/README.md
# GoStack 11 - Challanges
A repository for archiving all Rocketseat Bootcamp 11 challenges 🗄️
<file_sep>/packages/challange-06/src/services/ImportTransactionsService.ts
import csv from 'csv-parse';
import fs from 'fs';
import { In, getRepository, getCustomRepository } from 'typeorm';
import Transaction from '../models/Transaction';
import Category from '../models/Category';
import AppError from '../errors/AppError';
import TransactionsRepository from '../repositories/TransactionsRepository';
interface Request {
filePath: string;
}
interface TransactionDTO {
title: string;
type: 'income' | 'outcome';
value: number;
category?: string;
}
interface CategoryDTO {
title?: string;
}
class ImportTransactionsService {
async execute({ filePath }: Request): Promise<Transaction[]> {
const csvReadStream = fs.createReadStream(filePath);
const parser = csv({
delimiter: ',',
from_line: 2,
});
const parsedCSV = csvReadStream.pipe(parser);
const transactions: TransactionDTO[] = [];
const categories: string[] = [];
parsedCSV.on('data', async line => {
const [title, type, value, category] = line.map((cell: string) =>
cell.trim(),
);
if (!title || !type || !value) {
throw new AppError('CSV must have, at least, title, type and value');
}
transactions.push({ title, type, value, category });
categories.push(category);
});
await new Promise(resolve => parsedCSV.on('end', resolve));
const transactionsRepository = getCustomRepository(TransactionsRepository);
const categoriesRepository = getRepository(Category);
const createdCategories = await categoriesRepository.find({
where: {
title: In(categories),
},
});
const categoriesTitles = createdCategories.map((c: Category) => c.title);
const addNewCategories = categories
.filter(c => !categoriesTitles.includes(c))
.filter((value, index, self) => self.indexOf(value) === index);
const newCategories = categoriesRepository.create(
addNewCategories.map(title => ({
title,
})),
);
await categoriesRepository.save(newCategories);
const allCategories = [...newCategories, ...createdCategories];
const createdTransactions = transactionsRepository.create(
transactions.map(t => ({
title: t.title,
type: t.type,
value: t.value,
category: allCategories.find(c => c.title === t.category),
})),
);
await transactionsRepository.save(createdTransactions);
await fs.promises.unlink(filePath);
return createdTransactions;
}
}
export default ImportTransactionsService;
|
060432a8ad3efa3d3bfcf31672d40bb3f97623cc
|
[
"Markdown",
"TypeScript"
] | 3
|
TypeScript
|
gabrielbartoczevicz/gostack-11-challanges
|
ce270d7f7d9d3d8c794b3279d19cc65740c127b4
|
8b6db5b8580dce7096339aaee809914b0caa3994
|
refs/heads/master
|
<file_sep>import { Component, OnInit } from '@angular/core';
import { HomeModel } from './../shared/home-model';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
home: HomeModel;
drpStudent = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'];
minNum = 0;
maxNum = 100;
constructor() { }
ngOnInit() {
this.home=new HomeModel;
}
submitted = false;
onSubmit(): void {
this.submitted = true;
if(this.home.Score >= 91){
this.home.Grade = 'A';
}
else if(this.home.Score >= 81){
this.home.Grade = 'B';
}
else if(this.home.Score >= 71){
this.home.Grade = 'C';
}
else if(this.home.Score >= 61){
this.home.Grade = 'D';
}
else{
this.home.Grade = 'F';
}
}
clear() {
this.home = new HomeModel;
}
}<file_sep>export class HomeModel {
Student: string;
Course: string;
Score: number;
Grade: string;
}
|
efcaf8b699a5d3c657bfb87a00fbcfe2e8685817
|
[
"TypeScript"
] | 2
|
TypeScript
|
spencerdw/INFO451-Final
|
f4d0ca91072907eb4c01a23f64ee0df07265094d
|
529a19c1b755936e536374e4da2ddcbbb093209e
|
refs/heads/main
|
<repo_name>junwin/housePriceJs<file_sep>/src/app/houseprice/houseprice.component.ts
import { Component, OnInit } from '@angular/core';
import { HouseFeatures } from '../houseFeature';
import { FormsModule } from '@angular/forms';
import { Observable } from 'rxjs';
import * as tf from '@tensorflow/tfjs';
import { HousePricePreditionService } from '../house-price-predition.service';
@Component({
selector: 'app-houseprice',
templateUrl: './houseprice.component.html',
styleUrls: ['./houseprice.component.css']
})
export class HousepriceComponent implements OnInit {
constructor(private priceService: HousePricePreditionService) { }
ngOnInit(): void {
this.getFeatureTypes();
}
houseFeature: HouseFeatures = {
area: '60076',
houseType: 'SFH',
rooms: 7,
bedRooms: 3,
bedRoomsBsmt: 0,
fullBath: 2,
halfBath: 0,
approxSquFeet: 1200,
garageType: 'attached',
garageSpaces: 2,
parkingSpaces: 0
};
//housePrice: Observable<string>;
housePrice: string;
tempPrice: string;
setHousePrice(px: string) {
console.log('val', px);
this.housePrice
}
refreshPrice(): void {
this.housePrice = this.tempPrice;
//this.getPredictedPriceCall(this.housePrice);
}
/*
getPredictedPrice(): void {
this.housePrice = "0.0";
this.getPredictedPriceCall(this.tempPrice);
}
*/
getPredictedPrice(): void {
//this.housePrice = this.priceCalcService.getPrice(this.houseFeature);
var k = this.priceService.getPrice(this.houseFeature);
this.housePrice = k;
//console.log('k is', k);
}
selectHouseType(value) {
this.houseFeature.houseType = value;
}
selectHouseZipCode(value) {
this.houseFeature.area = value;
}
// used to show available House Types and Zip Codes
houseTypes: string[] = [];
houseZipCodes: string[] = [];
getFeatureTypes(): void {
this.houseTypes = this.priceService.houseTypes;
this.houseZipCodes = this.priceService.houseZipCodes;
}
}
<file_sep>/src/app/houseFeature.ts
export class HouseFeatures {
area: string;
houseType: string;
rooms: number;
bedRooms: number;
bedRoomsBsmt: number;
fullBath: number;
halfBath: number;
approxSquFeet: number;
garageType: string;
garageSpaces: number;
parkingSpaces: number;
constructor(name) {
}
}
<file_sep>/src/app/house-price-predition.service.ts
import { Injectable } from '@angular/core';
import * as tf from '@tensorflow/tfjs';
import { HouseFeatures } from './houseFeature'
@Injectable({
providedIn: 'root'
})
export class HousePricePreditionService {
constructor() { this.loadModel(); }
// Load an existing tensorflow model, the model for house prices is
// built using python and Tensorflow
model: tf.LayersModel;
async loadModel() {
// Note that a URL is required - it should point to the
// server that you are using to host the pages.
const MODEL_URL = 'assets/model.json';
this.model = await tf.loadLayersModel(MODEL_URL);
console.log(this.model.summary());
}
// use the model to predict the price of a house given it's features
getPrice(features: HouseFeatures): string {
try {
// Use tf.tidy() to clean up and unused tensors and be a good citizen
var housePredictedPrice = tf.tidy(() => {
// Get the features passed from the UI and convert them to a Javascript array
var uiFeatures = this.getFeatureArray(features);
// Tensorflow JS requires the features to be held in a 2D
// tensor (data, data shape)
var inputFeatures = tf.tensor2d(uiFeatures, [1, 38]);
// Predict the price
var result = this.model.predict(inputFeatures) as tf.Tensor2D;
// Note this is syncronous see the .data() method for an async alternative
var resultValue = result.dataSync()[0];
// Scale and round the result - the model was trained with
// price in millions
resultValue = resultValue * 1000000;
resultValue = Math.round(resultValue / 10000) * 10000;
return resultValue;
});
return housePredictedPrice.toString();
}
catch (e) {
console.log(e);
}
}
// Take a featue object populated in the UI and convert it
// to a feature array
// Uses inline Json for the example, the data used to train the model
// Had a set of zip codes and property types one hot encoded
getFeatureArray(f: HouseFeatures): Array<number> {
var featureMapJson = '{"SFH":0,"Condo":1,"Duplex":2,"Townhouse":3,"New":4,"Recent":5,"20A":6,' +
'"19A":7,"19B":8,"19C":9,"19D":10,"Pre1900":11,"Area":12,"Rooms":13,"FullBaths":14,"HalfBaths":15,' +
'"BsmtBth":16,"Beds":17,"BsmtBeds":18,"GarageSpaces":19, "60002":20,"60025":21,"60026":22,"60029":23,' +
'"60035":24,"60053":25,"60062":26,"60067":27,"60076":28,"60077":29,"60091":30,"60201":31,' +
'"60202":32,"60203":33,"60625":34,"60626":35,"60638":36,"63104":37}';
//console.log(featureMapJson);
var featureMap = JSON.parse(featureMapJson);
var features = Array(38).fill(0);
this.setFeature(featureMap, features, f.area, 1);
this.setFeature(featureMap, features, f.houseType, 1);
this.setFeature(featureMap, features, "Rooms", f.rooms);
this.setFeature(featureMap, features, "Beds", f.bedRooms);
this.setFeature(featureMap, features, "BsmtBeds", f.bedRoomsBsmt);
this.setFeature(featureMap, features, "FullBaths", f.fullBath);
this.setFeature(featureMap, features, "HalfBaths", f.halfBath);
this.setFeature(featureMap, features, "Area", f.approxSquFeet / 1000);
this.setFeature(featureMap, features, "GarageSpaces", f.garageSpaces);
return features;
}
setFeature(featureMap, features: Array<number>, name: string, value: number) {
var featureIndex = featureMap[name];
features[featureIndex] = value;
}
houseTypes: string[] = ['SFH', 'Condo', 'Duplex', 'Townhouse'];
houseZipCodes: string[] = ["60002", "60025", "60026", "60029", "60035", "60053", "60062", "60067", "60076", "60077", "60091", "60201", "60202", "60203", "60625", "60626", "60638", "63104"];
}
|
ae6f3b6b0163e7645af8ddeaafaa9ebd584092dd
|
[
"TypeScript"
] | 3
|
TypeScript
|
junwin/housePriceJs
|
0a71e8a9785005ea12a99594d8d1ea41cfaa1a98
|
8436a11852c50402a89c3d509299ae78a7fc2be0
|
refs/heads/master
|
<repo_name>cjsatuforc/R3E-Input-Monitor<file_sep>/R3E_Inputs_Monitor/preferences/model/PreferencesModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor.preferences.model
{
public class PreferencesModel
{
public GaugeType ShowGauges { get; set; } = GaugeType.CLUTCH | GaugeType.BRAKE | GaugeType.THROTTLE;
public bool AlwaysOnTop { get; set; } = false;
public byte Opacity { get; set; } = 255;
}
}
<file_sep>/R3E_Inputs_Monitor/r3e/socket/Utilities.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor.r3e.socket
{
public class Utilities
{
public static Single RpsToRpm(Single rps)
{
return rps * (60 / (2 * (Single)Math.PI));
}
public static Single MpsToKph(Single mps)
{
return mps * 3.6f;
}
public static bool IsRrreRunning()
{
return Process.GetProcessesByName("RRRE64").Length > 0 || Process.GetProcessesByName("RRRE").Length > 0; // TODO test 32-bit
}
}
}
<file_sep>/R3E_Inputs_Monitor/application/command/StartApplicationCommand.cs
using da2mvc.core.command;
using da2mvc.core.injection;
using R3E_Inputs_Monitor.preferences.command;
using R3E_Inputs_Monitor.r3e.command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor.application.command
{
class StartApplicationCommand : ICommand
{
public void Execute()
{
Injector.ExecuteCommand<LoadPreferencesCommand>();
Injector.ExecuteCommand<StartSocketCommand>();
}
}
}
<file_sep>/R3E_Inputs_Monitor/preferences/view/PreferencesView.xaml.cs
using da2mvc.core.events;
using da2mvc.framework.application.view;
using R3E_Inputs_Monitor.preferences.events;
using R3E_Inputs_Monitor.preferences.model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace R3E_Inputs_Monitor.preferences.view
{
/// <summary>
/// Logique d'interaction pour PreferencesView.xaml
/// </summary>
public partial class PreferencesView : ModalWindow, IEventDispatcher
{
public event EventHandler MvcEventHandler;
public static readonly int EVENT_PREFERENCES_CHANGED = EventId.New();
public PreferencesView(PreferencesModel model)
{
InitializeComponent();
InitializeUI(model);
}
private void InitializeUI(PreferencesModel model)
{
showClutch.IsChecked = model.ShowGauges.HasFlag(GaugeType.CLUTCH);
showBrake.IsChecked = model.ShowGauges.HasFlag(GaugeType.BRAKE);
showThrottle.IsChecked = model.ShowGauges.HasFlag(GaugeType.THROTTLE);
opacity.Value = model.Opacity;
alwaysOnTop.IsChecked = model.AlwaysOnTop;
okButton.Click += OkClickHandler;
}
private void OkClickHandler(object sender, RoutedEventArgs e)
{
GaugeType gauges = (showClutch.IsChecked == true ? GaugeType.CLUTCH : 0)
| (showBrake.IsChecked == true ? GaugeType.BRAKE : 0)
| (showThrottle.IsChecked == true ? GaugeType.THROTTLE : 0);
var args = new PreferencesChangeEventArgs(EVENT_PREFERENCES_CHANGED, gauges, alwaysOnTop.IsChecked == true, (byte)opacity.Value);
DispatchEvent(args);
DialogResult = true;
}
public void DispatchEvent(BaseEventArgs args)
{
MvcEventHandler?.Invoke(this, args);
}
}
}
<file_sep>/R3E_Inputs_Monitor/display/DisplayView.cs
using da2mvc.core.view;
using R3E_Inputs_Monitor.preferences.model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace R3E_Inputs_Monitor.display
{
public class DisplayView : FrameworkElement, IView
{
private SolidColorBrush throttleBrush;
private SolidColorBrush brakeBrush;
private SolidColorBrush clutchBrush;
private float clutch = .5f;
private float brake = .5f;
private float throttle = .5f;
private readonly PreferencesModel preferences;
public event EventHandler Disposed;
public DisplayView(PreferencesModel preferences)
{
this.preferences = preferences;
InitBrushes();
}
public void SetValues(Single clutch, Single brake, Single throttle)
{
this.clutch = clutch == -1 ? 0 : clutch;
this.brake = brake == -1 ? 0 : brake;
this.throttle = throttle == -1 ? 0 : throttle;
InvalidateVisual();
}
private void InitBrushes()
{
clutchBrush = new SolidColorBrush(Colors.Blue);
brakeBrush = new SolidColorBrush(Colors.Red);
throttleBrush = new SolidColorBrush(Colors.Green);
}
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
double clutchHeight = clutch * RenderSize.Height;
double brakeHeight = brake * RenderSize.Height;
double throttleHeight = throttle * RenderSize.Height;
double gaugeX = 0;
int numGauges = 0;
foreach (GaugeType enumValue in Enum.GetValues(typeof(GaugeType)))
{
if (preferences.ShowGauges.HasFlag(enumValue))
numGauges++;
}
double gaugeThickness = numGauges == 0 ? numGauges : RenderSize.Width / numGauges;
drawingContext.DrawRectangle(new SolidColorBrush(Color.FromArgb(preferences.Opacity, 0, 0, 0)), null, new Rect(0, 0, RenderSize.Width, RenderSize.Height));
if (preferences.ShowGauges.HasFlag(GaugeType.CLUTCH))
{
drawingContext.DrawRectangle(clutchBrush, null, new Rect(gaugeX, RenderSize.Height - clutchHeight, gaugeThickness, clutchHeight));
gaugeX += gaugeThickness;
}
if (preferences.ShowGauges.HasFlag(GaugeType.BRAKE))
{
drawingContext.DrawRectangle(brakeBrush, null, new Rect(gaugeX, RenderSize.Height - brakeHeight, gaugeThickness, brakeHeight));
gaugeX += gaugeThickness;
}
if (preferences.ShowGauges.HasFlag(GaugeType.THROTTLE))
{
drawingContext.DrawRectangle(throttleBrush, null, new Rect(gaugeX, RenderSize.Height - throttleHeight, gaugeThickness, throttleHeight));
}
}
public void Dispose()
{
Disposed?.Invoke(this, EventArgs.Empty);
}
}
}
<file_sep>/R3E_Inputs_Monitor/r3e/events/SocketEventArgs.cs
using da2mvc.core.events;
using R3E_Inputs_Monitor.r3e.socket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor.r3e.events
{
class SocketEventArgs : BaseEventArgs
{
public SocketEventArgs(int eventId, R3eApiSocket socket) : base(eventId)
{
Socket = socket;
}
public R3eApiSocket Socket { get; }
}
}
<file_sep>/R3E_Inputs_Monitor/r3e/socket/R3eApiSocket.cs
using da2mvc.core.events;
using R3E_Inputs_Monitor.r3e.events;
using R3E_Inputs_Monitor.r3e.socket.Data;
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
using System.Windows.Threading;
namespace R3E_Inputs_Monitor.r3e.socket
{
class R3eApiSocket:IEventDispatcher
{
public event EventHandler MvcEventHandler;
public static readonly int EVENT_DATA_UPDATED = EventId.New();
private DispatcherTimer timer;
public Shared Data;
private MemoryMappedFile _file;
private byte[] _buffer;
private bool Mapped
{
get { return (_file != null); }
}
public R3eApiSocket()
{
timer = new DispatcherTimer();
}
private void AttemptR3eConnection(object sender, EventArgs e)
{
if (Utilities.IsRrreRunning() && !Mapped)
{
Console.WriteLine("Found RRRE.exe, mapping shared memory...");
if (Map())
{
Console.WriteLine("Memory mapped successfully");
timer.Stop();
_buffer = new Byte[Marshal.SizeOf(typeof(Shared))];
}
}
if (Mapped)
{
StartMonitoring();
}
}
private void StartMonitoring()
{
timer.Interval = new TimeSpan(0, 0, 0, 0, 8);
timer.Tick -= AttemptR3eConnection;
timer.Tick += Monitor;
timer.Start();
}
private bool Read()
{
try
{
var _view = _file.CreateViewStream();
BinaryReader _stream = new BinaryReader(_view);
_buffer = _stream.ReadBytes(Marshal.SizeOf(typeof(Shared)));
GCHandle _handle = GCHandle.Alloc(_buffer, GCHandleType.Pinned);
Data = (Shared)Marshal.PtrToStructure(_handle.AddrOfPinnedObject(), typeof(Shared));
_handle.Free();
return true;
}
catch (Exception)
{
return false;
}
}
private void Monitor(object sender, EventArgs e)
{
if (Read())
{
DispatchEvent(new SocketEventArgs(EVENT_DATA_UPDATED, this));
//Console.WriteLine("Name: {0}", System.Text.Encoding.UTF8.GetString(_data.PlayerName).TrimEnd('\0'));
//if (_data.Gear >= -1)
//{
// Console.WriteLine("Gear: {0}", _data.Gear);
//}
//if (_data.EngineRps > -1.0f)
//{
// Console.WriteLine("RPM: {0}", Utilities.RpsToRpm(_data.EngineRps));
// Console.WriteLine("Speed: {0}", Utilities.MpsToKph(_data.CarSpeed));
//}
//Debug.WriteLine(_data.ThrottlePedal);
//Debug.WriteLine(_data.BrakePedal);
//Debug.WriteLine(_data.ClutchPedal);
//Console.WriteLine("");
}
}
private bool Map()
{
try
{
_file = MemoryMappedFile.OpenExisting(Constant.SharedMemoryName);
return true;
}
catch (FileNotFoundException)
{
return false;
}
}
public void Connect()
{
// TODO Gestion des déconnections, fin du moniroting, etc.
timer.Interval = new TimeSpan(0,0,1);
timer.Tick += AttemptR3eConnection;
timer.Start();
}
public void DispatchEvent(BaseEventArgs args)
{
MvcEventHandler?.Invoke(this, args);
}
}
}
<file_sep>/R3E_Inputs_Monitor/preferences/model/GaugeType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor.preferences.model
{
[Flags]
public enum GaugeType
{
CLUTCH = 1,
BRAKE = 2,
THROTTLE = 4,
}
}
<file_sep>/R3E_Inputs_Monitor/preferences/command/LoadPreferencesCommand.cs
using da2mvc.core.command;
using da2mvc.core.events;
using R3E_Inputs_Monitor.preferences.events;
using R3E_Inputs_Monitor.preferences.model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor.preferences.command
{
class LoadPreferencesCommand : ICommand, IEventDispatcher
{
public event EventHandler MvcEventHandler;
public static readonly int EVENT_PREFERENCES_LOADED = EventId.New();
private readonly PreferencesModel preferences;
public LoadPreferencesCommand(PreferencesModel preferences)
{
this.preferences = preferences;
}
public void Execute()
{
preferences.ShowGauges = (GaugeType)Properties.Settings.Default.showGauges;
preferences.AlwaysOnTop = Properties.Settings.Default.alwaysOnTop;
preferences.Opacity = Properties.Settings.Default.opacity;
DispatchEvent(new PreferencesModelEventArgs(EVENT_PREFERENCES_LOADED, preferences));
}
public void DispatchEvent(BaseEventArgs args)
{
MvcEventHandler?.Invoke(this, args);
}
}
}
<file_sep>/R3E_Inputs_Monitor/preferences/events/PreferencesModelEventArgs.cs
using da2mvc.core.events;
using R3E_Inputs_Monitor.preferences.model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor.preferences.events
{
class PreferencesModelEventArgs : BaseEventArgs
{
public PreferencesModelEventArgs(int eventId, PreferencesModel preferences) : base(eventId)
{
Preferences = preferences;
}
public PreferencesModel Preferences { get; }
}
}
<file_sep>/R3E_Inputs_Monitor/preferences/command/UpdatePreferencesCommand.cs
using da2mvc.core.command;
using da2mvc.core.events;
using R3E_Inputs_Monitor.preferences.events;
using R3E_Inputs_Monitor.preferences.model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor.preferences.command
{
class UpdatePreferencesCommand : ICommand, IEventDispatcher
{
public event EventHandler MvcEventHandler;
public static readonly int EVENT_PREFERENCES_UPDATED = EventId.New();
private readonly PreferencesChangeEventArgs args;
private readonly PreferencesModel preferences;
public UpdatePreferencesCommand(PreferencesChangeEventArgs args, PreferencesModel preferences)
{
this.args = args;
this.preferences = preferences;
}
public void Execute()
{
preferences.ShowGauges = args.ShowGauges;
preferences.AlwaysOnTop = args.AlwaysOnTop;
preferences.Opacity = args.Opacity;
Properties.Settings.Default.showGauges = (int)args.ShowGauges;
Properties.Settings.Default.alwaysOnTop = args.AlwaysOnTop;
Properties.Settings.Default.opacity = args.Opacity;
Properties.Settings.Default.Save();
DispatchEvent(new PreferencesModelEventArgs(EVENT_PREFERENCES_UPDATED, preferences));
}
public void DispatchEvent(BaseEventArgs args)
{
MvcEventHandler?.Invoke(this, args);
}
}
}
<file_sep>/R3E_Inputs_Monitor/Mappings.cs
using da2mvc.core.injection;
using R3E_Inputs_Monitor.display;
using R3E_Inputs_Monitor.preferences.command;
using R3E_Inputs_Monitor.preferences.model;
using R3E_Inputs_Monitor.preferences.view;
using R3E_Inputs_Monitor.r3e;
using R3E_Inputs_Monitor.r3e.socket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor
{
class Mappings
{
private static bool initialized;
public static void Initialize(MainWindow mainWindow = null)
{
if (initialized) return;
initialized = true;
if (mainWindow != null)
Injector.MapViewInstance<MainWindow, MainWindowMediator>(mainWindow);
Injector.MapType<R3eApiSocket>(true);
Injector.MapType<PreferencesModel>(true);
Injector.MapType<PreferencesView>();
Injector.MapView<DisplayView, DisplayMediator>(true);
Injector.MapCommand<MainWindow, OpenPreferencesCommand>(MainWindow.EVENT_OPEN_PREFERENCES);
Injector.MapCommand<PreferencesView, UpdatePreferencesCommand>(PreferencesView.EVENT_PREFERENCES_CHANGED);
}
}
}
<file_sep>/R3E_Inputs_Monitor/MainWindow.xaml.cs
using da2mvc.core.events;
using da2mvc.core.injection;
using da2mvc.core.view;
using R3E_Inputs_Monitor.application.command;
using R3E_Inputs_Monitor.display;
using R3E_Inputs_Monitor.r3e;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
namespace R3E_Inputs_Monitor
{
/// <summary>
/// Logique d'interaction pour MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, IEventDispatcher, IView
{
/*
* TODO
* * Right click to configure.
*
*
*/
public event EventHandler MvcEventHandler;
public event EventHandler Disposed;
public static readonly int EVENT_OPEN_PREFERENCES = EventId.New();
public MainWindow()
{
Mappings.Initialize(this);
InitializeComponent();
InitializeUI();
Injector.ExecuteCommand<StartApplicationCommand>();
MouseLeftButtonDown += LeftButtonHandler;
// Don't draw the grip if window is not focused.
Activated += ActivatedHandler;
Deactivated += DeactivatedHandler;
}
private void ActivatedHandler(object sender, EventArgs e)
{
ResizeMode = ResizeMode.CanResizeWithGrip;
}
private void DeactivatedHandler(object sender, EventArgs e)
{
ResizeMode = ResizeMode.CanResize;
}
private void LeftButtonHandler(object sender, MouseButtonEventArgs e)
{
DragMove();
}
public void DispatchEvent(BaseEventArgs args)
{
MvcEventHandler?.Invoke(this, args);
}
private void InitializeUI()
{
KeyDown += KeyDownHandler;
}
private void KeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.C && !e.IsRepeat && Keyboard.Modifiers == 0)
{
DispatchEvent(new BaseEventArgs(EVENT_OPEN_PREFERENCES));
}
else if (e.Key == Key.Escape)
Application.Current.Shutdown();
}
public void Dispose()
{
Disposed?.Invoke(this, EventArgs.Empty);
}
}
}
<file_sep>/R3E_Inputs_Monitor/preferences/command/OpenPreferencesCommand.cs
using da2mvc.core.command;
using R3E_Inputs_Monitor.preferences.view;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor.preferences.command
{
class OpenPreferencesCommand : ICommand
{
private readonly PreferencesView view;
public OpenPreferencesCommand(PreferencesView view)
{
this.view = view;
}
public void Execute()
{
if (view.ShowDialog() == true)
{
}
}
}
}
<file_sep>/R3E_Inputs_Monitor/r3e/command/StartSocketCommand.cs
using da2mvc.core.command;
using R3E_Inputs_Monitor.r3e.socket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor.r3e.command
{
class StartSocketCommand : ICommand
{
private readonly R3eApiSocket socket;
public StartSocketCommand(R3eApiSocket socket)
{
this.socket = socket;
}
public void Execute()
{
socket.Connect();
}
}
}
<file_sep>/R3E_Inputs_Monitor/display/DisplayMediator.cs
using da2mvc.core.events;
using da2mvc.core.view;
using R3E_Inputs_Monitor.preferences.command;
using R3E_Inputs_Monitor.r3e.events;
using R3E_Inputs_Monitor.r3e.socket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor.display
{
class DisplayMediator : BaseMediator<DisplayView>
{
public DisplayMediator()
{
HandleEvent<R3eApiSocket, SocketEventArgs>(R3eApiSocket.EVENT_DATA_UPDATED, SocketDataUpdated);
HandleEvent<UpdatePreferencesCommand, BaseEventArgs>(UpdatePreferencesCommand.EVENT_PREFERENCES_UPDATED, OnPreferencesUpdated);
HandleEvent<LoadPreferencesCommand, BaseEventArgs>(LoadPreferencesCommand.EVENT_PREFERENCES_LOADED, OnPreferencesUpdated);
}
private void OnPreferencesUpdated(BaseEventArgs args)
{
View.InvalidateVisual();
}
private void SocketDataUpdated(SocketEventArgs args)
{
View.SetValues(args.Socket.Data.ClutchPedal,
args.Socket.Data.BrakePedal,
args.Socket.Data.ThrottlePedal);
}
}
}
<file_sep>/R3E_Inputs_Monitor/preferences/events/PreferencesChangeEventArgs.cs
using da2mvc.core.events;
using R3E_Inputs_Monitor.preferences.model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor.preferences.events
{
class PreferencesChangeEventArgs : BaseEventArgs
{
public PreferencesChangeEventArgs(int eventId, GaugeType showGauges, bool alwaysOnTop, byte opacity) : base(eventId)
{
ShowGauges = showGauges;
AlwaysOnTop = alwaysOnTop;
Opacity = opacity;
}
public GaugeType ShowGauges { get; }
public bool AlwaysOnTop { get; }
public byte Opacity { get; }
}
}
<file_sep>/R3E_Inputs_Monitor/MainWindowMediator.cs
using da2mvc.core.view;
using R3E_Inputs_Monitor.preferences.command;
using R3E_Inputs_Monitor.preferences.events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor
{
class MainWindowMediator : BaseMediator<MainWindow>
{
public MainWindowMediator()
{
HandleEvent<UpdatePreferencesCommand, PreferencesModelEventArgs>(UpdatePreferencesCommand.EVENT_PREFERENCES_UPDATED, OnPreferencesChanged);
HandleEvent<LoadPreferencesCommand, PreferencesModelEventArgs>(LoadPreferencesCommand.EVENT_PREFERENCES_LOADED, OnPreferencesChanged);
}
private void OnPreferencesChanged(PreferencesModelEventArgs args)
{
View.Topmost = args.Preferences.AlwaysOnTop;
}
}
}
<file_sep>/README.md
# R3E-Input-Monitor
Displays in a separate window pedals values from Raceroom API.
Install application: http://vs84.evxonline.net/R3EInputMonitor_update/publish.htm
Source code depends on this DLL project: https://github.com/hiboudev/da2MVC-CSharp
<file_sep>/R3E_Inputs_Monitor/application/view/AppVIew.cs
using da2mvc.framework.application.view;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace R3E_Inputs_Monitor.application.view
{
public class AppView : AbstractAppView
{
protected override void InitializeMappings()
{
Mappings.Initialize();
}
}
}
|
0561f9b5e6cb639cd4c2a8d33647393dff8aa12d
|
[
"Markdown",
"C#"
] | 20
|
C#
|
cjsatuforc/R3E-Input-Monitor
|
fd65caa84f00ce86a8ebd1ae4bbcafcd37d4971e
|
8db7c134c715f187144701bd2725ad191484bd24
|
refs/heads/master
|
<file_sep>//Author:Xjun
#include "AntiDebug.h"
/*
* 禁止目录重定向
*/
BOOL safeWow64DisableDirectory(PVOID &arg)
{
typedef BOOL WINAPI fntype_Wow64DisableWow64FsRedirection(PVOID *OldValue);
auto pfnWow64DisableWow64FsRedirection = (fntype_Wow64DisableWow64FsRedirection*)\
GetProcAddress(GetModuleHandleA("kernel32.dll"), "Wow64DisableWow64FsRedirection");
if (pfnWow64DisableWow64FsRedirection) {
(*pfnWow64DisableWow64FsRedirection)(&arg);
return TRUE;
}
else {
return FALSE;
}
}
/*
* 恢复目录重定向
*/
BOOL safeWow64ReverDirectory(PVOID &arg)
{
typedef BOOL WINAPI fntype_Wow64RevertWow64FsRedirection(PVOID *OldValue);
auto pfnWow64RevertWow64FsRedirection = (fntype_Wow64RevertWow64FsRedirection*) \
GetProcAddress(GetModuleHandleA("kernel32.dll"), "Wow64RevertWow64FsRedirection");
if (pfnWow64RevertWow64FsRedirection) {
(*pfnWow64RevertWow64FsRedirection)(&arg);
return TRUE;
}
else {
return FALSE;
}
}
/*
* 安全取得系统真实信息
*/
VOID SafeGetNativeSystemInfo(__out LPSYSTEM_INFO lpSystemInfo)
{
if (NULL == lpSystemInfo) return;
typedef VOID(WINAPI *LPFN_GetNativeSystemInfo)(LPSYSTEM_INFO lpSystemInfo);
LPFN_GetNativeSystemInfo fnGetNativeSystemInfo = \
(LPFN_GetNativeSystemInfo)GetProcAddress(GetModuleHandleA("kernel32"), "GetNativeSystemInfo");
if (NULL != fnGetNativeSystemInfo)
{
fnGetNativeSystemInfo(lpSystemInfo);
}
else
{
GetSystemInfo(lpSystemInfo);
}
}
/*
* 触发异常,用于检测硬件断点
*/
volatile void __stdcall HardwareBreakpointRoutine(PVOID xAntiDbgClass)
{
__debugbreak();
return;
}
/*
* VECTORED_EXCEPTION_HANDLER
*/
LONG WINAPI VectoredExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo)
{
//
// 命中硬件断点,说明是
//
if (pExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_BREAKPOINT)
{
#ifdef _WIN64
XAntiDebug *antiDbg = (XAntiDebug*)pExceptionInfo->ContextRecord->Rcx;
if (pExceptionInfo->ContextRecord->Dr0 != 0 ||
pExceptionInfo->ContextRecord->Dr1 != 0 ||
pExceptionInfo->ContextRecord->Dr2 != 0 ||
pExceptionInfo->ContextRecord->Dr3 != 0)
{
antiDbg->_isSetHWBP = TRUE;
//
// 顺便把你的硬件断点给清理掉
//
pExceptionInfo->ContextRecord->Dr0 = 0;
pExceptionInfo->ContextRecord->Dr1 = 0;
pExceptionInfo->ContextRecord->Dr2 = 0;
pExceptionInfo->ContextRecord->Dr3 = 0;
}
//
// 继续执行 int3 opcode len = 1
//
pExceptionInfo->ContextRecord->Rip = pExceptionInfo->ContextRecord->Rip + 1;
#else
XAntiDebug *antiDbg = (XAntiDebug *)(*(DWORD*)(pExceptionInfo->ContextRecord->Esp + 4));
if (pExceptionInfo->ContextRecord->Dr0 != 0 ||
pExceptionInfo->ContextRecord->Dr1 != 0 ||
pExceptionInfo->ContextRecord->Dr2 != 0 ||
pExceptionInfo->ContextRecord->Dr3 != 0)
{
antiDbg->_isSetHWBP = TRUE;
//
// 顺便把你的硬件断点给清理掉
//
pExceptionInfo->ContextRecord->Dr0 = 0;
pExceptionInfo->ContextRecord->Dr1 = 0;
pExceptionInfo->ContextRecord->Dr2 = 0;
pExceptionInfo->ContextRecord->Dr3 = 0;
}
//
// 继续执行 int3 opcode len = 1
//
pExceptionInfo->ContextRecord->Eip = pExceptionInfo->ContextRecord->Eip + 1;
#endif
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
//////////////////////////////////////////////////////////////////////////
#ifdef _WIN64
#define GetProcAddress64 GetProcAddress
#define GetModuleHandle64 GetModuleHandleW
#define getMem64(dest,src,size) memcpy(dest,src,size)
#endif
#define XAD_NTDLL L"ntdll.dll"
#define XAD_PAGESIZE (0x1000)
#define XAD_MAXOPCODE (0x64)
/*
* 构造函数
*/
XAntiDebug::XAntiDebug(HMODULE moduleHandle, DWORD flags)
{
//
// 初始化私有变量
//
_initialized = FALSE;
_isArch64 = FALSE;
_isWow64 = FALSE;
_isWow64FsReDriectory = FALSE;
_pagePtr = 0;
_pageSize = 0;
_pageCrc32 = 0;
_pfnSyscall32 = NULL;
_pfnSyscall64 = NULL;
_isLoadStrongOD = FALSE;
_isSetHWBP = FALSE;
_moduleHandle = moduleHandle;
_flags = flags;
SYSTEM_INFO si;
RTL_OSVERSIONINFOW osVer;
SafeGetNativeSystemInfo(&si);
if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 ||
si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64)
{
_isArch64 = TRUE;
}
typedef LONG(__stdcall *fnRtlGetVersion)(PRTL_OSVERSIONINFOW lpVersionInformation);
fnRtlGetVersion pRtlGetVersion = (fnRtlGetVersion)GetProcAddress(GetModuleHandle("ntdll"), "RtlGetVersion");
if (pRtlGetVersion)
{
pRtlGetVersion(&osVer);
}
_major = osVer.dwMajorVersion;
_minor = osVer.dwMinorVersion;
IsWow64Process((HANDLE)-1, &_isWow64);
if (_isArch64 && _isWow64)
{
_isWow64FsReDriectory = TRUE;
}
_pageSize = si.dwPageSize;
//
// ThreadHideFromDebugger
//
typedef NTSTATUS(NTAPI* fnNtSetInformationThread)(
_In_ HANDLE ThreadHandle,
_In_ DWORD_PTR ThreadInformationClass,
_In_ PVOID ThreadInformation,
_In_ ULONG ThreadInformationLength
);
fnNtSetInformationThread pfnNtSetInformationThread = \
(fnNtSetInformationThread)GetProcAddress(GetModuleHandleW(XAD_NTDLL), "NtSetInformationThread");
if (pfnNtSetInformationThread)
{
#ifndef _DEBUG
LONG status;
pfnNtSetInformationThread((HANDLE)-2, 0x11, NULL, NULL);
//
// StrongOD 驱动处理不当
//
status = pfnNtSetInformationThread((HANDLE)-2, 0x11, (PVOID)sizeof(PVOID), sizeof(PVOID));
if (status == 0)
{
_isLoadStrongOD = TRUE;
}
#endif
}
}
/*
* 析构函数
*/
XAntiDebug::~XAntiDebug()
{
if (_pagePtr)
{
VirtualFreeEx((HANDLE)-1, reinterpret_cast<LPVOID>(_pagePtr), 0, MEM_RELEASE);
}
}
/*
* 反调试初始化
*/
XAD_STATUS XAntiDebug::XAD_Initialize()
{
//
// 防止重复初始化,造成内存泄漏
//
if (_initialized)
{
return XAD_OK;
}
if ((_flags & FLAG_CHECKSUM_NTOSKRNL) && _major >= 6)
{
//
//检测正在运行的NTOS文件路径. 因NT函数枚举出来的路径是CHAR,这里都用CHAR
//
typedef LONG(WINAPI* fnZwQuerySystemInformation)(
LONG_PTR SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength
);
CHAR sysDir[MAX_PATH];
DWORD MySystemModuleInformation = 11;
LONG status;
ULONG systemModuleSize = 0;
PVOID systemModuleBuf;
fnZwQuerySystemInformation pfnZwQuerySystemInformation;
GetSystemDirectoryA(sysDir, MAX_PATH);
pfnZwQuerySystemInformation = \
(fnZwQuerySystemInformation)GetProcAddress(GetModuleHandleW(XAD_NTDLL), "ZwQuerySystemInformation");
if (!pfnZwQuerySystemInformation)
{
return XAD_ERROR_OPENNTOS;
}
pfnZwQuerySystemInformation(MySystemModuleInformation, NULL, NULL, &systemModuleSize);
if (systemModuleSize == 0)
{
return XAD_ERROR_OPENNTOS;
}
systemModuleBuf = calloc(1, systemModuleSize);
status = pfnZwQuerySystemInformation(MySystemModuleInformation, systemModuleBuf, systemModuleSize, &systemModuleSize);
if (status != 0) //STATUS_SUCCESS
{
return XAD_ERROR_OPENNTOS;
}
//
// 这里是系统模块链表 第一个就是ntos的路径,从这里取得文件名
//
char *src = (char*)systemModuleBuf;
char *match = "\\SystemRoot\\system32\\";
size_t matchLen = strlen(match);
for (size_t i = 0; i < (systemModuleSize - matchLen); i++, src++)
{
if (strncmp(src, match, matchLen) == 0)
{
break;
}
}
src = PathFindFileNameA(src);
strcpy(_ntosPath, sysDir);
strcat(_ntosPath, "\\");
strcat(_ntosPath, src);
free(systemModuleBuf);
}
if (_flags & FLAG_CHECKSUM_CODESECTION)
{
PIMAGE_DOS_HEADER dosHead;
PIMAGE_NT_HEADERS ntHead;
PIMAGE_SECTION_HEADER secHead;
CODE_CRC32 codeSection;
if (IsBadReadPtr(_moduleHandle, sizeof(void*)) == 0)
{
dosHead = (PIMAGE_DOS_HEADER)_moduleHandle;
if (dosHead == NULL || dosHead->e_magic != IMAGE_DOS_SIGNATURE)
{
return XAD_ERROR_MODULEHANDLE;
}
ntHead = ImageNtHeader(dosHead);
if (ntHead == NULL || ntHead->Signature != IMAGE_NT_SIGNATURE)
{
return XAD_ERROR_MODULEHANDLE;
}
secHead = IMAGE_FIRST_SECTION(ntHead);
_codeCrc32.clear();
for (size_t Index = 0; Index < ntHead->FileHeader.NumberOfSections; Index++)
{
if ((secHead->Characteristics & IMAGE_SCN_MEM_EXECUTE) &&
(secHead->Characteristics & IMAGE_SCN_MEM_READ))
{
codeSection.m_va = (PVOID)((DWORD_PTR)_moduleHandle + secHead->VirtualAddress);
codeSection.m_size = secHead->Misc.VirtualSize;
codeSection.m_crc32 = crc32(codeSection.m_va, codeSection.m_size);
_codeCrc32.push_back(codeSection);
}
secHead++;
}
}
}
if (_flags & FLAG_DETECT_DEBUGGER)
{
if (_isArch64)
{
//
// 首先获取 ZwQueryInformationProcess函数地址
//
#ifndef _WIN64
InitWow64Ext();
#endif
_MyQueryInfomationProcess = (DWORD64)GetProcAddress64(GetModuleHandle64(XAD_NTDLL), "ZwQueryInformationProcess");
if (_MyQueryInfomationProcess == NULL)
{
return XAD_ERROR_NTAPI;
}
_MyQueryInfomationProcess -= (DWORD64)GetModuleHandle64(XAD_NTDLL);
}
else
{
_MyQueryInfomationProcess = (DWORD)GetProcAddress(GetModuleHandleW(XAD_NTDLL), "ZwQueryInformationProcess");
if (_MyQueryInfomationProcess == NULL)
{
return XAD_ERROR_NTAPI;
}
_MyQueryInfomationProcess -= (DWORD)GetModuleHandleW(XAD_NTDLL);
}
//
//从 ntdll 虚拟地址转换到实际文件偏移数据
//
DWORD fileOffset = 0;
if (_isArch64)
{
unsigned char pehead[XAD_PAGESIZE];
getMem64(pehead, GetModuleHandle64(XAD_NTDLL), XAD_PAGESIZE);
PIMAGE_DOS_HEADER pDosHead = (PIMAGE_DOS_HEADER)pehead;
if (pDosHead->e_magic != IMAGE_DOS_SIGNATURE)
return XAD_ERROR_FILEOFFSET;
PIMAGE_NT_HEADERS64 pNtHead = (PIMAGE_NT_HEADERS64)((ULONG_PTR)pDosHead + pDosHead->e_lfanew);
if (pNtHead->Signature != IMAGE_NT_SIGNATURE)
return XAD_ERROR_FILEOFFSET;
PIMAGE_SECTION_HEADER pSection = (PIMAGE_SECTION_HEADER)\
(sizeof(IMAGE_NT_SIGNATURE) + sizeof(IMAGE_FILE_HEADER) + pNtHead->FileHeader.SizeOfOptionalHeader + (ULONG_PTR)pNtHead);
for (size_t i = 0; i < pNtHead->FileHeader.NumberOfSections; i++)
{
if (pSection->VirtualAddress <= _MyQueryInfomationProcess &&
_MyQueryInfomationProcess <= (pSection->VirtualAddress + pSection->Misc.VirtualSize))
{
break;
}
pSection++;
}
fileOffset = (DWORD)(_MyQueryInfomationProcess - pSection->VirtualAddress + pSection->PointerToRawData);
}
else
{
PIMAGE_DOS_HEADER pDosHead = (PIMAGE_DOS_HEADER)GetModuleHandleW(XAD_NTDLL);
if (pDosHead->e_magic != IMAGE_DOS_SIGNATURE)
return XAD_ERROR_FILEOFFSET;
PIMAGE_NT_HEADERS pNtHead = (PIMAGE_NT_HEADERS)((char*)pDosHead + pDosHead->e_lfanew);
if (pNtHead->Signature != IMAGE_NT_SIGNATURE)
return XAD_ERROR_FILEOFFSET;
PIMAGE_SECTION_HEADER pSection = (PIMAGE_SECTION_HEADER)\
(sizeof(IMAGE_NT_SIGNATURE) + sizeof(IMAGE_FILE_HEADER) + pNtHead->FileHeader.SizeOfOptionalHeader + (ULONG_PTR)pNtHead);
for (size_t i = 0; i < pNtHead->FileHeader.NumberOfSections; i++)
{
if (pSection->VirtualAddress <= _MyQueryInfomationProcess &&
_MyQueryInfomationProcess <= (pSection->VirtualAddress + pSection->Misc.VirtualSize))
{
break;
}
pSection++;
}
fileOffset = (DWORD)(_MyQueryInfomationProcess - pSection->VirtualAddress + pSection->PointerToRawData);
}
if (fileOffset == 0)
{
return XAD_ERROR_FILEOFFSET;
}
//
// 读ntdll文件,使用ldasm反汇编函数头部,得出SSDT Index
//
#ifndef _WIN64
PVOID _wow64FsReDirectory;
#endif
unsigned char opcode[XAD_MAXOPCODE];
DWORD readd;
TCHAR sysDir[MAX_PATH] = { 0 };
HANDLE hFile;
GetSystemDirectory(sysDir, MAX_PATH);
_tcscat(sysDir, _T("\\ntdll.dll"));
#ifndef _WIN64
if (_isWow64FsReDriectory)
safeWow64DisableDirectory(_wow64FsReDirectory);
#endif
hFile = CreateFile(sysDir, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return XAD_ERROR_OPENNTDLL;
}
SetFilePointer(hFile, fileOffset, NULL, FILE_CURRENT);
ReadFile(hFile, opcode, XAD_MAXOPCODE, &readd, NULL);
CloseHandle(hFile);
ldasm_data ld;
unsigned char *pEip = opcode;
size_t len;
while (TRUE)
{
len = ldasm(pEip, &ld, _isArch64);
if (len == 5 && pEip[0] == 0xB8) // mov eax,xxxxxx
{
_eax = *(DWORD*)(&pEip[1]);
break;
}
pEip += len;
}
#ifndef _WIN64
if (_isWow64FsReDriectory)
safeWow64ReverDirectory(_wow64FsReDirectory);
#endif
//
// 申请内存,组合shellcode,直接调用syscall
//
unsigned char shellSysCall32[] = {
0xB8, 0x0, 0x0, 0x0, 0x0, // mov eax,NtQueryInformationProcess
0xE8, 0x3, 0x0, 0x0, 0x0, // call sysentry
0xC2, 0x14, 0x0, // ret 0x14
// sysenter:
0x8B, 0xD4, // mov edx,esp
0x0F, 0x34, // sysenter
0xC3 // retn
};
unsigned char shellSysCall64[] = {
0xB8, 0x0, 0x0, 0x0, 0x0, // mov eax,NtQueryInformationProcess
0x4C, 0x8B, 0xD1, // mov r10,rcx
0x0F, 0x05, // syscall
0xC3 // retn
};
_pagePtr = VirtualAllocEx((HANDLE)-1, 0, _pageSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (_pagePtr == NULL)
{
return XAD_ERROR_ALLOCMEM;
}
size_t random;
ULONG_PTR pSysCall;
srand(GetTickCount());
unsigned char *pRandChar = (unsigned char *)_pagePtr;
for (size_t i = 0; i < _pageSize; i++)
{
pRandChar[i] = LOBYTE(rand());
}
//
// 把代码随机拷贝在页内存当中,要检查内存页边界,防止崩溃
//
random = rand() % (_pageSize - (sizeof(shellSysCall32) + sizeof(shellSysCall64)));
memcpy(&shellSysCall32[1], &_eax, 4);
memcpy(&shellSysCall64[1], &_eax, 4);
pSysCall = (ULONG_PTR)_pagePtr + random;
_pfnSyscall32 = (fn_SysCall32)pSysCall;
memcpy((void*)pSysCall, shellSysCall32, sizeof(shellSysCall32));
pSysCall += sizeof(shellSysCall32);
_pfnSyscall64 = (fn_SysCall64)pSysCall;
memcpy((void*)pSysCall, shellSysCall64, sizeof(shellSysCall64));
_pageCrc32 = crc32(_pagePtr, _pageSize);
return XAD_OK;
}
if (_flags & FLAG_DETECT_HARDWAREBREAKPOINT)
{
// 不需要初始化
;
}
return XAD_OK;
}
/*
* 执行检测
*/
BOOL XAntiDebug::XAD_ExecuteDetect()
{
BOOL result = FALSE;
if ((_flags & FLAG_CHECKSUM_NTOSKRNL) && _major >= 6)
{
WCHAR pwszSourceFile[MAX_PATH];
SHAnsiToUnicode(_ntosPath, pwszSourceFile, MAX_PATH);
// https://docs.microsoft.com/zh-cn/windows/desktop/SecCrypto/example-c-program--verifying-the-signature-of-a-pe-file
LONG lStatus;
// Initialize the WINTRUST_FILE_INFO structure.
WINTRUST_FILE_INFO FileData;
memset(&FileData, 0, sizeof(FileData));
FileData.cbStruct = sizeof(WINTRUST_FILE_INFO);
FileData.pcwszFilePath = pwszSourceFile;
FileData.hFile = NULL;
FileData.pgKnownSubject = NULL;
/*
WVTPolicyGUID specifies the policy to apply on the file
WINTRUST_ACTION_GENERIC_VERIFY_V2 policy checks:
1) The certificate used to sign the file chains up to a root
certificate located in the trusted root certificate store. This
implies that the identity of the publisher has been verified by
a certification authority.
2) In cases where user interface is displayed (which this example
does not do), WinVerifyTrust will check for whether the
end entity certificate is stored in the trusted publisher store,
implying that the user trusts content from this publisher.
3) The end entity certificate has sufficient permission to sign
code, as indicated by the presence of a code signing EKU or no
EKU.
*/
GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
WINTRUST_DATA WinTrustData;
// Initialize the WinVerifyTrust input data structure.
// Default all fields to 0.
memset(&WinTrustData, 0, sizeof(WinTrustData));
WinTrustData.cbStruct = sizeof(WinTrustData);
// Use default code signing EKU.
WinTrustData.pPolicyCallbackData = NULL;
// No data to pass to SIP.
WinTrustData.pSIPClientData = NULL;
// Disable WVT UI.
WinTrustData.dwUIChoice = WTD_UI_NONE;
// No revocation checking.
WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE;
// Verify an embedded signature on a file.
WinTrustData.dwUnionChoice = WTD_CHOICE_FILE;
// Verify action.
WinTrustData.dwStateAction = WTD_STATEACTION_VERIFY;
// Verification sets this value.
WinTrustData.hWVTStateData = NULL;
// Not used.
WinTrustData.pwszURLReference = NULL;
// This is not applicable if there is no UI because it changes
// the UI to accommodate running applications instead of
// installing applications.
WinTrustData.dwUIContext = 0;
// Set pFile.
WinTrustData.pFile = &FileData;
// WinVerifyTrust verifies signatures as specified by the GUID
// and Wintrust_Data.
lStatus = WinVerifyTrust(NULL, &WVTPolicyGUID, &WinTrustData);
// Any hWVTStateData must be released by a call with close.
WinTrustData.dwStateAction = WTD_STATEACTION_CLOSE;
WinVerifyTrust(NULL, &WVTPolicyGUID, &WinTrustData);
if (lStatus != ERROR_SUCCESS)
{
return TRUE;
}
}
if (_flags & FLAG_CHECKSUM_CODESECTION)
{
for (size_t i = 0; i < _codeCrc32.size(); i++)
{
if (crc32(_codeCrc32[i].m_va, _codeCrc32[i].m_size) != _codeCrc32[i].m_crc32)
{
return TRUE;
}
}
}
if (_flags & FLAG_DETECT_DEBUGGER)
{
if (IsDebuggerPresent())
{
return TRUE;
}
//////////////////////////////////////////////////////////////////////////
BOOL debuging = FALSE;
CheckRemoteDebuggerPresent(GetCurrentProcess(), &debuging);
if (debuging)
{
return TRUE;
}
//////////////////////////////////////////////////////////////////////////
__try{
CloseHandle((HANDLE)0xDEADC0DE);
}
__except (EXCEPTION_EXECUTE_HANDLER){
return TRUE;
}
//////////////////////////////////////////////////////////////////////////
typedef enum _MYOBJECT_INFORMATION_CLASS
{
ObjectBasicInformation, // OBJECT_BASIC_INFORMATION
ObjectNameInformation, // OBJECT_NAME_INFORMATION
ObjectTypeInformation, // OBJECT_TYPE_INFORMATION
ObjectTypesInformation, // OBJECT_TYPES_INFORMATION
ObjectHandleFlagInformation, // OBJECT_HANDLE_FLAG_INFORMATION
ObjectSessionInformation,
ObjectSessionObjectInformation,
MaxObjectInfoClass
} MYOBJECT_INFORMATION_CLASS;
typedef struct _MYOBJECT_HANDLE_FLAG_INFORMATION
{
BOOLEAN Inherit;
BOOLEAN ProtectFromClose;
} MYOBJECT_HANDLE_FLAG_INFORMATION, *PMYOBJECT_HANDLE_FLAG_INFORMATION;
typedef NTSTATUS(WINAPI *fnNtSetInformationObject)(
_In_ HANDLE Handle,
_In_ MYOBJECT_INFORMATION_CLASS ObjectInformationClass,
_In_ PVOID ObjectInformation,
_In_ ULONG ObjectInformationLength
);
HANDLE processHandle1, processHandle2;
fnNtSetInformationObject pfnNtSetInformationObject = \
(fnNtSetInformationObject)GetProcAddress(GetModuleHandleW(XAD_NTDLL), "ZwSetInformationObject");
MYOBJECT_HANDLE_FLAG_INFORMATION objInfo = { 0 };
objInfo.Inherit = false;
objInfo.ProtectFromClose = true;
__try{
processHandle1 = GetCurrentProcess();
DuplicateHandle(processHandle1, processHandle1, processHandle1, &processHandle2, 0, FALSE, 0);
pfnNtSetInformationObject(processHandle2, ObjectHandleFlagInformation, &objInfo, sizeof(objInfo));
DuplicateHandle(processHandle1, processHandle2, processHandle1, &processHandle2, 0, FALSE, DUPLICATE_CLOSE_SOURCE);
}
__except (EXCEPTION_EXECUTE_HANDLER){
return TRUE;
}
//////////////////////////////////////////////////////////////////////////
if (_isLoadStrongOD)
{
return TRUE;
}
//////////////////////////////////////////////////////////////////////////
if (_isArch64)
{
DWORD64 processInformation;
DWORD64 returnLength;
DWORD64 status;
#ifndef _WIN64
status = X64Call(
(DWORD64)_pfnSyscall64,
5,
(DWORD64)-1,
(DWORD64)0x1E,
(DWORD64)&processInformation,
(DWORD64)8,
(DWORD64)&returnLength);
#else
status = _pfnSyscall64(
(DWORD64)-1,
(DWORD64)0x1E,
(PDWORD64)&processInformation,
(DWORD64)8,
(PDWORD64)&returnLength);
#endif
if (status != 0xC0000353) //STATUS_PORT_NOT_SET
{
return TRUE;
}
if (status == 0xC0000353 && processInformation != 0)
{
return TRUE;
}
//
// 利用内核二次覆盖的BUG来检测反调试,在利用这个漏洞之前计算一遍页面CRC
//
if (crc32(_pagePtr, _pageSize) != _pageCrc32)
{
return TRUE;
}
DWORD64 bugCheck;
#ifndef _WIN64
status = X64Call(
(DWORD64)_pfnSyscall64,
5,
(DWORD64)-1,
(DWORD64)0x1E,
(DWORD64)&bugCheck,
(DWORD64)8,
(DWORD64)&bugCheck);
#else
status = _pfnSyscall64(
(DWORD64)-1,
(DWORD64)0x1E,
(PDWORD64)&bugCheck,
(DWORD64)8,
(PDWORD64)&bugCheck);
#endif
if (status == 0xC0000353 && bugCheck != 8)
{
return TRUE;
}
}
else
{
DWORD processInformation;
DWORD returnLength;
DWORD status;
status = _pfnSyscall32(
(DWORD)-1,
(DWORD)0x1E,
&processInformation,
(DWORD)4,
&returnLength);
if (status != 0xC0000353) //STATUS_PORT_NOT_SET
{
return TRUE;
}
if (status == 0xC0000353 && processInformation != 0)
{
return TRUE;
}
//
// 利用内核二次覆盖的BUG来检测反调试,在利用这个漏洞之前计算一遍页面CRC
//
if (crc32(_pagePtr, _pageSize) != _pageCrc32)
{
return TRUE;
}
DWORD bugCheck;
status = _pfnSyscall32(
(DWORD)-1,
(DWORD)0x1E,
&bugCheck,
(DWORD)4,
&bugCheck);
if (status == 0xC0000353 && bugCheck != 4)
{
return TRUE;
}
}
}
if (_flags & FLAG_DETECT_HARDWAREBREAKPOINT)
{
//
// 方法1
//
CONTEXT ctx = { 0 };
ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
if (GetThreadContext((HANDLE)-2, &ctx))
{
if (ctx.Dr0 != 0 || ctx.Dr1 != 0 || ctx.Dr2 != 0 || ctx.Dr3 != 0)
{
return TRUE;
}
}
//
// 方法2
//
AddVectoredExceptionHandler(0, VectoredExceptionHandler);
typedef void(__stdcall *fnMakeException)(PVOID lparam);
fnMakeException pfnMakeException = (fnMakeException)HardwareBreakpointRoutine;
pfnMakeException(this);
RemoveVectoredExceptionHandler(VectoredExceptionHandler);
if (_isSetHWBP)
{
return TRUE;
}
}
return FALSE;
}<file_sep>#define _CRT_SECURE_NO_WARNINGS
#define SOURCE_IN_CP932
#include "AntiDebug/AntiDebug.h"
#include <iostream>
#include <windows.h>
#include <WinUser.h>
#include <WinBase.h>
#include <tchar.h>
#include <urlmon.h>
#pragma comment(lib, "urlmon.lib")
#pragma comment(lib,"wininet.lib")
#pragma comment(lib, "Advapi32.lib")
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <WinInet.h>
#include <iomanip>
#include <cstdio>
#include <fstream>
#include <urlmon.h>
#include <io.h>
#include <shellapi.h>
#pragma comment(lib, "Urlmon.lib")
#pragma comment(lib, "Shell32.lib")
#include <windows.h>
#include <locale.h>
#include <thread>
#include <Psapi.h>
using namespace std;
int intExit() { int a = 1, b = 0; return a / b; }
bool IsHTTPDebuggerInstalled()
{
LPVOID drivers[2048];
DWORD cbNeeded;
int cDrivers, i;
if (EnumDeviceDrivers(drivers, sizeof(drivers), &cbNeeded) && cbNeeded < sizeof(drivers))
{
TCHAR szDriver[2048];
cDrivers = cbNeeded / sizeof(drivers[0]);
for (i = 0; i < cDrivers; i++)
{
if (GetDeviceDriverBaseName(drivers[i], szDriver, sizeof(szDriver) / sizeof(szDriver[0])))
{
std::string strDriver = szDriver;
if (strDriver.find(("HttpDebug")) != std::string::npos)
return true;
}
}
}
return false;
}
void GuardTh()
{
for (;;)
{
XAD_STATUS status;
XAntiDebug antiDbg(GetModuleHandle(NULL), FLAG_DETECT_DEBUGGER | FLAG_DETECT_HARDWAREBREAKPOINT);
status = antiDbg.XAD_Initialize();
if (status != XAD_OK)
{
__asm int 0;
}
if (antiDbg.XAD_ExecuteDetect())
{
__asm int 0;
}
LPCTSTR FiddlerClass = "WindowsForms10.Window.8.app.0.2bf8098_r6_ad1";
LPCTSTR FiddlerName = "Progress Telerik Fiddler Web Debugger";
LPCTSTR HTTPDebuggerClass = "XTPMainFrame";
LPCTSTR HTTPDebuggerName = "HTTP Debugger Pro v8.20";
HWND FindNFinddler = FindWindow(NULL, FiddlerName);
HWND FindCFiddler = FindWindow(FiddlerClass, NULL);
HWND FindNHTTPDebugger = FindWindow(NULL, HTTPDebuggerName);
HWND FindCHTTPDebugger = FindWindow(HTTPDebuggerClass, NULL);
if (FindNFinddler || FindCFiddler || FindNHTTPDebugger || FindCHTTPDebugger || IsHTTPDebuggerInstalled())
{
MessageBox(NULL, "Gei ga mitsukarimashita!", "Kutsushita", MB_OK);
__asm int 0;
}
}
}
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
WaitForSingleObject(CreateThread(nullptr, 0, LPTHREAD_START_ROUTINE(GuardTh), nullptr, 0, nullptr), INFINITE);
intExit();
}
|
6cf030aac3f46555792b416180100e15f96ba066
|
[
"C++"
] | 2
|
C++
|
PubHub/Kutsushita
|
f3e04992a9a9d25971845d1dad63b5f072d50cee
|
36daea5311a790155cf786947eade51129854064
|
refs/heads/main
|
<file_sep>import { post, get} from "./config";
// index
//新版本新增接口
export const classifyImg = params => post('/api/image/index',params); //按分类返回图片列表
export const logoList = params => post('/api/logo/phoneList',params); //图片列表
export const logoCate = params => post('/api/logo/logoCate',params); //分类列表
export const homeImg = params => post('/api/logo/logoList',params); //分类列表
export const message = params => post('/api/logo/sendMessage',params); //留言板
export const phoneBanner = params => post('/api/logo/phoneBanner',params); //首页banner
export const homeVideo = params => post('/api/logo/videoList',params); //视频列表
export const login = params => post('/api/user/login',params); //登录
export const register = params => post('/api/user/register',params); //注册
export const editPass = params => post('/api/user/editPass',params); //修改密码
export const smsSend = params => post('/api/user/sendCode',params); //发送短信
export const createOrder = params => post('/api/shoot/createOrder',params); //创建摄影
export const orderList = params => post('/api/shoot/orderList',params); //用户摄影列表
export const notReceived = params => post('/api/shoot/notReceived',params); //待摄影师接单拍摄列表
export const getReceived = params => post('/api/shoot/getReceived',params); //摄影师确认接单
export const sceneList = params => post('/api/shoot/sceneList',params); //摄影师待现场确认订单列表
export const getScene = params => post('/api/shoot/getScene',params); //摄影师已现场确认待客户确认
export const getEndShoot = params => post('/api/shoot/getEndShoot',params); //客户确认完单
|
61a0b59fc672d83fe2c53eee6a7111d952e970e3
|
[
"JavaScript"
] | 1
|
JavaScript
|
FZ243477/tingzhilanMobile
|
62ae0c33ec36be504011f653e77849506e81e4ef
|
8a20e4e3f0a049cc2ef1660add99dc8f7b73d3dc
|
refs/heads/master
|
<repo_name>simuChen/TUMSHelper<file_sep>/src/libs/MailHandler.py
# -*- coding:utf-8 -*-
'''
Created on Oct 11, 2014
@author: czl
'''
import logging, time
import base64
import email
import cStringIO
import os
from smtplib import SMTP
from poplib import POP3
from libs.SocksSMTP import SocksSMTP
from libs.SocksPOP3 import SocksPOP3
from libs.utils import Field, saveFile
class MailNotifier(object):
'''
classdocs
'''
MailHeader = """To: %s
From: %s
Subject: TUMSHelpr advice
"""
AdviseMsg = """Hello, everyone
The tums site has too many task, so I couldn't post any task!!!
Please have a check. Thank you.
best regards.
"""
CompleteMsg = """Hello, everyone
I have finished the mission : %s (log record is %s).
Please have a look. Thank you.
Tasklist:
%s
best regards.
"""
def __init__(self, server, user, password, fromaddr, toaddrs):
'''
Constructor
'''
self.server = server
self.proxy = False
self.proxy_host = "127.0.0.1"
self.proxy_port = 8080
self.user = user
self.password = <PASSWORD>
self.fromaddr = fromaddr
self.toaddrs = toaddrs
def setProxy(self, proxy_host, proxy_port):
self.proxy = True
self.proxy_host = proxy_host
self.proxy_port = proxy_port
def advise(self, message):
try:
if self.proxy:
s = SocksSMTP(self.server, proxy_host=self.proxy_host, proxy_port=self.proxy_port)
else:
s = SMTP(self.server)
s.login(self.user, self.password)
header = self.MailHeader % (', '.join(self.toaddrs), self.fromaddr)
s.sendmail(self.fromaddr, self.toaddrs, header + message)
except Exception, e:
logging.info("smtp fail : %s" % e)
finally:
s.close()
class MailDownloader(object):
'''
'''
def __init__(self, server, username, password):
self.server = server
self.proxy = False
self.proxy_host = "127.0.0.1"
self.proxy_port = 8080
self.username = username
self.password = <PASSWORD>
self.targetmail = ''
self.p_attach = ''
self.p_mail = ''
def setProxy(self, proxy_host, proxy_port):
self.proxy = True
self.proxy_host = proxy_host
self.proxy_port = proxy_port
def setInfo(self, targetmail, path_mail, path_attach, path_attach_keyword):
self.targetmail = targetmail
self.p_mail = path_mail
self.p_attach = path_attach
self.p_attach_keywrod = path_attach_keyword
def __parse(self, message):
for part in message.walk():
contenttype = part.get_content_type()
filename = part.get_filename()
logging.debug('%s : %s' % (contenttype, filename))
if contenttype == 'text/plain':
content = part.get_payload(decode=True)
field = Field(content)
attachTooLarge = field.getField(r'^(GET FILE)')
if attachTooLarge :
raise Exception('attach too large.')
dateRange = field.getField(r'^Date Range +\[(.*)\]')
if dateRange is None: break
keyword = field.getField(r'^Keywords +\[(.*)\]')
# srcAddr = field.getField(r'^Source Address +\[(.*)\]')
destAddr = field.getField(r'^Dest Address +\[(.*)\]')
elif filename and contenttype == 'application/octet-stream':
attachcontent = base64.decodestring(part.get_payload())
else:
if keyword != None and keyword != "":
attachname = "%s/%s/%s %s.zip" % (destAddr[-2:], dateRange[:6], dateRange.replace(":", "")[:13], keyword)
savepath = os.path.join(self.p_attach_keywrod, attachname)
else:
attachname = "%s/%s/%s.zip" % (destAddr[-2:], dateRange[:6], dateRange.replace(":", "")[:13])
savepath = os.path.join(self.p_attach, attachname)
# print savepath
saveFile(savepath, attachcontent)
def retrMail(self):
if self.proxy:
mail = SocksPOP3(self.server, proxy_host=self.proxy_host, proxy_port=self.proxy_port)
else:
mail = POP3(self.server)
mail.user(self.username)
mail.pass_(self.password)
mailTotal = len(mail.list()[1])
logging.info("mailTotal:%d" % mailTotal)
for mailIndex in xrange(1, mailTotal + 1):
logging.info("retrieve %dth mail" % (mailIndex))
mailContent = mail.retr(mailIndex)[1]
buf = cStringIO.StringIO()
buf.write('\n'.join(mailContent))
buf.seek(0)
msg = email.message_from_file(buf)
if msg.get('From') != self.targetmail : continue
try:
self.__parse(msg)
mail.dele(mailIndex)
except Exception, e:
logging.info("[*] Exception :%s" % e)
saveMailName = 'mail_%s.eml' % time.strftime("%Y%m%d %H%M%S", time.localtime())
logging.info('[*] Save the handle mail as %s' % saveMailName)
saveFile(self.p_mail + saveMailName, buf.getvalue())
finally:
buf.close()
mail.quit()
if __name__ == "__main__":
import ConfigParser, codecs
print "begin"
logging.basicConfig(level=logging.DEBUG)
confighandler = ConfigParser.ConfigParser()
confighandler.readfp(codecs.open("../config.cgi", 'r', 'utf-8-sig'))
server = confighandler.get("advise", "server").encode('ascii', 'ignore')
user = confighandler.get("advise", "user")
passwd = confighandler.get("advise", "passwd")
advisemail = confighandler.get("advise", "advisemail").split()
mh = MailNotifier(server, user, passwd, user, advisemail)
proxy = confighandler.getboolean("advise", "proxy")
if proxy:
proxy_host = confighandler.get("advise", "proxy_host")
proxy_port = confighandler.getint("advise", "proxy_port")
mh.setProxy(proxy_host, proxy_port)
# mh.advise(MailNotifier.AdviseMsg)
# print confighandler.items("maintask")
alltask = confighandler.get("query", "alltask").split()
taskcontent = []
for taskname in alltask:
taskcontent.append("[%s]" % taskname)
for item in confighandler.items(taskname):
taskcontent.append("%s\t\t:\t%s" % item)
taskcontent.append("-"*50)
message = MailNotifier.CompleteMsg % ("config", "logfile", "\n".join(taskcontent))
mh.advise(message)
print "ok"
<file_sep>/README.md
TUMSHelper
=================
用于向TUMS网站提交查询任务
## 功能概述:
1. 通过简单的图像处理技术识别网站验证码
2. 模拟浏览器登陆验证通过
3. 模拟浏览器提交查询任务
## 所依赖的第三方包:
### 1. PIL
用于图像处理
### 2. SocksiPy
用于创建可以支持网络代理的SMTP和POP3
<file_sep>/src/libs/HttpHandler.py
# -*- coding:utf-8 -*-
'''
Created on Oct 9, 2014
@author: czl
'''
import urllib
import urllib2
import cookielib
from utils import resend
class HttpHandler(object):
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
self.cookiejar = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(self.cookiejar)
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
def getCookie(self):
return self.cookiejar
@resend(100, 10)
def get(self, url):
response = urllib2.urlopen(url)
return response
@resend(100, 10)
def post(self, url, headers, postData):
request = urllib2.Request(url,
urllib.urlencode(postData),
headers)
response = urllib2.urlopen(request)
return response
@resend(100, 10)
def downloadFile(self, url, savFilename):
webfile = self.get(url).read()
fp = open(savFilename, 'wb')
fp.write(webfile)
fp.close()
<file_sep>/src/main.py
# -*- coding:utf-8 -*-
'''
Created on Oct 9, 2014
@author: czl
'''
import logging, time
import ConfigParser, codecs
from libs.TaskHandler import TaskHandler
from libs.utils import createDirectory
from libs.QueryHandler import QueryHandler
from optparse import OptionParser
from libs.MailHandler import MailNotifier, MailDownloader
def tums_query(configfile):
createDirectory(r"./log")
logfile = 'log/tums_query %s.log' % time.strftime("%Y%m%d %H%M%S", time.localtime())
logging.basicConfig(level=logging.DEBUG,
format='%(levelname)s - %(asctime)s %(filename)s[line:%(lineno)d]\t - %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename=logfile,
filemode='w')
logging.info('Begin to Run.')
logging.info("deal with %s" % configfile)
config = ConfigParser.ConfigParser()
config.readfp(codecs.open(configfile, 'r', 'utf-8-sig'))
username = config.get("website", "username")
password = config.get("website", "<PASSWORD>")
email = config.get("query", "email")
## 设置邮件通知处理器
server = config.get("advise", "server").encode('ascii', 'ignore')
user = config.get("advise", "user")
passwd = config.get("advise", "passwd")
advisemail = config.get("advise", "advisemail").split()
mailhandler = MailNotifier(server, user, passwd, user, advisemail)
## 邮箱是否需要代理
proxy = config.getboolean("advise", "proxy")
if proxy:
proxy_host = config.get("advise", "proxy_host")
proxy_port = config.getint("advise", "proxy_port")
mailhandler.setProxy(proxy_host, proxy_port)
taskhandler = TaskHandler(username, password, mailhandler)
## 设置查询限制
islimit = config.getboolean("query", "islimit")
if islimit:
maxquery = config.getint("query", "maxquery")
limit = config.getint("query", "limit")
taskhandler.setOverload(email, maxquery, limit)
## 初始化查询任务列表
alltask = config.get("query", "alltask").split()
tasklist = []
for taskname in alltask:
state = config.getboolean(taskname, "state")
if state:
startdate = config.get(taskname, "startdate")
stopdate = config.get(taskname, "stopdate")
interval = config.getint(taskname, "interval")
tag = config.get(taskname, "tag")
content = config.get(taskname, "queryinfo")
queryinfo = []
exec("queryinfo = " + content)
keyword = config.get(taskname, "keyword")
maintask = QueryHandler(taskname, taskhandler, tag, email, startdate, stopdate, interval, queryinfo, keyword)
tasklist.append(maintask)
# taskhandler.connect()
## 循环进行查询任务提交,查询任务优先级跟在tasklist中位置有关,下标越小越高
flag = True
while flag:
flag = False
for task in tasklist:
if task.flag :
flag = True
if task.getState():
task.query()
break
else:
# 如果是当前还有任务未查询完,但查询任务的时间点已超过当前日期,
# 则睡眠等待
if flag : time.sleep(3 * 60)
## 通知查询任务完成
taskcontent = []
for taskname in alltask:
taskcontent.append("[%s]" % taskname)
for item in config.items(taskname):
taskcontent.append("%s\t\t:\t%s" % item)
taskcontent.append("-"*50)
message = MailNotifier.CompleteMsg % (configfile, logfile, "\n".join(taskcontent))
mailhandler.advise(message)
logging.info('Run end.')
def download(configfile):
'''
下载邮件附件(查询结果)
'''
createDirectory(r"./log")
logfile = 'log/download %s.log' % time.strftime("%Y%m%d %H%M%S", time.localtime())
logging.basicConfig(level=logging.DEBUG,
format='%(levelname)s - %(asctime)s %(filename)s[line:%(lineno)d]\t - %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename=logfile,
filemode='w')
logging.info('Begin to Run.')
logging.info("deal with %s" % configfile)
config = ConfigParser.ConfigParser()
config.readfp(codecs.open(configfile, 'r', 'utf-8-sig'))
aserver = config.get("attach", "aserver").encode('ascii', 'ignore')
auser = config.get("attach", "auser")
apasswd = config.get("attach", "apasswd")
maildownloader = MailDownloader(aserver, auser, apasswd)
targetmail = config.get("attach", "targetmail")
path_mail = config.get("attach", "path_mail")
path_attach = config.get("attach", "path_attach")
path_attach_keyword = config.get("attach", "path_attach_keyword")
maildownloader.setInfo(targetmail, path_mail, path_attach, path_attach_keyword)
## 邮箱是否需要代理
proxy = config.getboolean("advise", "proxy")
if proxy:
proxy_host = config.get("advise", "proxy_host")
proxy_port = config.getint("advise", "proxy_port")
maildownloader.setProxy(proxy_host, proxy_port)
maildownloader.retrMail()
logging.info('Run end.')
def check_requery(configfile):
'''
检查附件是否完整
'''
createDirectory(r"./log")
logfile = 'log/check_requery %s.log' % time.strftime("%Y%m%d %H%M%S", time.localtime())
logging.basicConfig(level=logging.DEBUG,
format='%(levelname)s - %(asctime)s %(filename)s[line:%(lineno)d]\t - %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename=logfile,
filemode='w')
logging.info('Begin to Run.')
logging.info("deal with %s" % configfile)
config = ConfigParser.ConfigParser()
config.readfp(codecs.open(configfile, 'r', 'utf-8-sig'))
username = config.get("website", "username")
password = config.get("website", "<PASSWORD>")
email = config.get("query", "email")
path_attach = config.get("attach", "path_attach")
path_attach_keyword = config.get("attach", "path_attach_keyword")
## 设置邮件通知处理器
server = config.get("advise", "server").encode('ascii', 'ignore')
user = config.get("advise", "user")
passwd = config.get("advise", "passwd")
advisemail = config.get("advise", "advisemail").split()
mailhandler = MailNotifier(server, user, passwd, user, advisemail)
## 邮箱是否需要代理
proxy = config.getboolean("advise", "proxy")
if proxy:
proxy_host = config.get("advise", "proxy_host")
proxy_port = config.getint("advise", "proxy_port")
mailhandler.setProxy(proxy_host, proxy_port)
taskhandler = TaskHandler(username, password, mailhandler)
## 设置查询限制
islimit = config.getboolean("query", "islimit")
if islimit:
maxquery = config.getint("query", "maxquery")
limit = config.getint("query", "limit")
taskhandler.setOverload(email, maxquery, limit)
## 初始化查询任务列表
alltask = config.get("query", "alltask").split()
tasklist = []
for taskname in alltask:
state = config.getboolean(taskname, "state")
if state:
startdate = config.get(taskname, "startdate")
stopdate = config.get(taskname, "stopdate")
interval = config.getint(taskname, "interval")
tag = config.get(taskname, "tag")
content = config.get(taskname, "queryinfo")
queryinfo = []
exec("queryinfo = " + content)
keyword = config.get(taskname, "keyword")
maintask = QueryHandler(taskname, taskhandler, tag, email, startdate, stopdate, interval, queryinfo, keyword)
maintask.setRequeryInfo(path_attach, path_attach_keyword)
tasklist.append(maintask)
# taskhandler.connect()
## 循环进行检查补漏,任务优先级跟在tasklist中位置有关,下标越小越高
flag = True
while flag:
flag = False
for task in tasklist:
if task.flag :
flag = True
if task.getState():
task.check()
break
else:
# 如果是当前还有任务未查询完,但查询任务的时间点已超过当前日期,
# 则睡眠等待
if flag : time.sleep(3 * 60)
for task in tasklist:
if task.taskcomplete:
logging.info("%s has been completed." % task.taskname)
## 通知查询任务完成
taskcontent = []
for taskname in alltask:
taskcontent.append("[%s]" % taskname)
for item in config.items(taskname):
taskcontent.append("%s\t\t:\t%s" % item)
taskcontent.append("-"*50)
message = MailNotifier.CompleteMsg % (configfile, logfile, "\n".join(taskcontent))
mailhandler.advise(message)
logging.info('Run end.')
def main():
print 'begin run...'
parser = OptionParser()
parser.add_option("-f", dest="config",
help="config file", metavar="FILE",
default="config.cgi")
parser.add_option("-d", dest="download", action="store_true",
help="start to download the attach file",
default=False)
parser.add_option("-r", dest="requery", action="store_true",
help="start to check an requery",
default=False)
(options, args) = parser.parse_args() # @UnusedVariable
if options.download:
download(options.config)
elif options.requery:
check_requery(options.config)
else:
tums_query(options.config)
print 'run over'
if __name__ == '__main__':
main()
<file_sep>/src/libs/ValidCodeHandler.py
# -*- coding:utf-8 -*-
'''
Created on Oct 9, 2014
@author: czl
'''
import logging
import Image, binascii
import urllib2, StringIO
class ValidCodeHandler(object):
'''
将图片验证码转化为相应的数字
1.采用CRC进行图片进行哈希
2.返回相应的数字
'''
# 初始化转换码,key为哈希值,value为对应的数字
transcode = {23 : '0',
39 : '1',
12 : '2',
1 : '3',
17 : '4',
2 : '5',
22 : '6',
15 : '7',
20 : '8',
13 : '9'}
def __init__(self):
'''
Constructor
'''
pass
def getImageValidCode(self, url, isSave=False):
while True:
webfile = urllib2.urlopen(url).read()
img = Image.open(StringIO.StringIO(webfile))
logging.debug("checkcode size is (%d, %d)" % img.size)
xLen, yLen = img.size
## 像素二分值,去掉干扰线条, 临界值为400
for xy in [(x, y) for x in xrange(xLen) for y in xrange(yLen)]:
r, g, b = img.getpixel(xy)
if r+g+b > 400:
r, g, b = (255, 255, 255)
else:
r, g, b = (0, 0, 0)
img.putpixel(xy, (r, g, b))
img = img.convert("L")
validcode = ''
try:
for i in range(4):
validcode += ValidCodeHandler.transcode[self.__getHashCode(img, i)]
if isSave:
img.save(validcode+".bmp")
except Exception, e:
logging.error("[*] Exception:%s" % e)
else:
return validcode
def __getHashCode(self, image, index):
'''
对图片进行哈希,先对相应的数字的像素进行CRC,最后模50
:param image: 图片对象
:param index: 第几个数字
'''
startPixelPerLetter = [7, 20, 33, 46]
width = 9
box = [0, 0, 0, 20]
box[0] = startPixelPerLetter[index]
box[2] = box[0] + width
# 截取相应像素区域
crc = self.__image2CRC(image.crop(tuple(box))) % 50
return crc
def __image2CRC(self, image):
xLen, yLen = image.size
crc = 0
for xy in [(x, y) for x in xrange(xLen) for y in xrange(yLen)]:
if image.getpixel(xy) == 255:
crc = binascii.crc32('1', crc) & 0xffffffff
else:
crc = binascii.crc32('0', crc) & 0xffffffff
return crc
<file_sep>/src/libs/utils.py
# -*- coding:utf-8 -*-
'''
Created on Oct 9, 2014
@author: czl
'''
import os
import re
import urllib2
import time
#a decorate function, for react again when url exception.
def resend(repeat, sleeptime):
def resend1(func):
def wrapper(*args):
rep = 0
while 1:
try:
return func(*args)
except urllib2.URLError, e:
rep += 1
if rep >= repeat: raise e
time.sleep(sleeptime)
return wrapper
return resend1
def createDirectory(dirpath):
if not os.path.exists(dirpath):
os.mkdir(dirpath)
def saveFile(filename, content, mode='wb'):
path = os.path.dirname(filename)
if not os.path.exists(path):
os.makedirs(path)
f = open(filename, mode)
f.write(content)
f.close()
# the Field type, convenience to get the special field by the re pattern.
class Field(object):
def __init__(self, content):
assert(type(content) == str)
self.content = content
def getField(self, pattern):
m = re.search(pattern, self.content, re.M)
if m is not None:
return m.group(1)<file_sep>/src/libs/SocksPOP3.py
# -*- coding:utf-8 -*-
'''
Created on Oct 20, 2014
@author: czl
'''
from poplib import POP3, POP3_PORT
from socks import socksocket, PROXY_TYPE_HTTP
class SocksPOP3(POP3):
'''
classdocs
'''
def __init__(self, host, port=POP3_PORT,
proxy_host='localhost', proxy_port=8080):
self.host = host
self.port = port
self.sock = socksocket()
self.sock.setproxy(PROXY_TYPE_HTTP, proxy_host, proxy_port)
# self.sock = socket.create_connection((host, port), timeout)
self.sock.connect((host, port))
self.file = self.sock.makefile('rb')
self._debugging = 0
self.welcome = self._getresp()
<file_sep>/src/libs/QueryHandler.py
# -*- coding:utf-8 -*-
'''
Created on Oct 11, 2014
@author: czl
'''
import time, logging
import os
import zipfile
class QueryHandler(object):
'''
classdocs
'''
# 解压时的文件名,用于检查zip文件完整性
unpackfilename = "unpack_test.txt"
def __init__(self, taskname, taskhandler, tag, email, startDate, stopDate, interval, queryinfo, keyword):
'''
Constructor
'''
self.taskname = taskname
self.flag = True
self.tag = tag
self.email = email
self.keyword = keyword
self.taskhandler = taskhandler
self.queryinfo = queryinfo
self.dg = self.__getDateGenerator(startDate, stopDate, interval)
try:
self.dg.next() # test if empty task
except Exception:
# no next item
self.flag = False
logging.info("%s has no task to query" % self.taskname)
self.taskcomplete = False
def __getDateGenerator(self, startDate, stopDate, interval, fmt='%Y-%m-%d %H:%M'):
'''
时间生产器
:param startDate:
:param stopDate:
:param interval:
:param fmt:
'''
# str -> struct_time
try:
startDate = time.strptime(startDate, fmt)
stopDate = time.strptime(stopDate, fmt)
except ValueError, e:
logging.info("%s Date Format Error : %s" % (self.taskname, e))
# struct_time -> count of seconds
startDate = int(time.mktime(startDate))
stopDate = int(time.mktime(stopDate))
for date in xrange(startDate, stopDate, interval):
date1 = time.localtime(date) # begin query time
date2 = time.localtime(date + interval - 1) # end query time
while 1:
val = (yield (date1, date2))
if val is True: break # break the loop to get next item
def __query(self, info, date1, date2):
'''
进行一个任务查询
:param info: 查询的报文信息,包括发报地址,收报地址和报文类型,如:(sendaddress, recvaddress, msgtype)
:param date1: 查询开始日期
:param date2: 查询结束日期
'''
day = time.strftime('%Y-%m-%d', date1)
hour1 = time.strftime('%H', date1)
minute1 = time.strftime('%M', date1)
hour2 = time.strftime('%H', date2)
minute2 = time.strftime('%M', date2)
logging.info('post task : %s -> %s %s %s %s' % (info[0], info[1], day, hour1, minute1))
taskData = {}
taskData['actionprocess'] = 'backmsgquery'
taskData['beginTime'] = day
taskData['beginHour'] = hour1
taskData['beginMinute'] = minute1
taskData['endHour'] = hour2
taskData['endMinute'] = minute2
taskData['tag'] = self.tag
taskData['keywordsinclude'] = self.keyword
taskData['keywordsuninclude'] = ''
taskData['pidno'] = ''
taskData['sendaddr'] = info[0]
taskData['recvaddr'] = info[1]
taskData['msgtype'] = info[2]
taskData['emailaddr'] = self.email
# logging.debug('taskData : %s' % taskData)
try:
self.taskhandler.postTask(taskData)
logging.info('post task success!')
except Exception, e:
logging.warning('task post fail: %s' % e)
def getState(self):
'''
判断是否可以进行查询
'''
if not self.flag : return False
# # 判断查询是否超出当前时间, 单位为天
cur = time.localtime(time.time())
c1 = time.strftime('%Y-%m-%d', cur)
date1, date2 = self.dg.next() # @UnusedVariable
d1 = time.strftime('%Y-%m-%d', date1)
return d1 < c1
def query(self):
date1, date2 = self.dg.next()
for info in self.queryinfo:
self.__query(info, date1, date2)
try:
self.dg.send(True) # next item
except Exception:
# no next item
self.flag = False
def setRequeryInfo(self, path_attach, path_attach_keyword):
self.p_attach = path_attach
self.p_attach_keyword = path_attach_keyword
self.taskcomplete = True
def __zipfileCheck(self, srcpath):
'''
检查压缩包附件是否完好
返回True代表压缩包已经损坏
:param srcpath:
'''
res = True
fzip = None
fw = None
try:
fzip = zipfile.ZipFile(srcpath, 'r')
nameList = fzip.namelist()
fr = fzip.open(nameList[0], 'r')
fw = open(self.unpackfilename, 'wb')
for line in fr:
fw.write(line)
res = False
except zipfile.BadZipfile, e:
logging.warning('zip file is destory: %s' % e)
finally:
if fzip: fzip.close()
if fw : fw.close()
return res
def __check(self, address, date):
'''
返回True代表需要补漏
:param address:
:param date:
'''
t = time.strftime('%Y%m%d %H%M', date)
if self.keyword == "":
filename = "%s.zip" % t
path_attch = self.p_attach
else:
filename = "%s +%s .zip" % (t, self.keyword)
path_attch = self.p_attach_keyword
path = os.path.join(path_attch, address[-2:], t[:6], filename)
logging.info("check zipfile:%s" % path)
res = False
if os.path.exists(path):
res = self.__zipfileCheck(path)
else:
logging.warning('zip file is not exists: %s' % path)
res = True
return res
def check(self):
date1, date2 = self.dg.next() # @UnusedVariable
for info in self.queryinfo:
recvaddress = info[1]
res = self.__check(recvaddress, date1)
self.taskcomplete &= not res # 设置完成标志
if res: self.__query(info, date1, date2)
try:
self.dg.send(True) # next item
except Exception:
# no next item
self.flag = False
<file_sep>/src/libs/TaskHandler.py
# -*- coding:gb2312 -*-
'''
Created on Oct 9, 2014
@author: czl
PS:由于涉及到对网页内容的处理,采用gb2312编码
'''
from HttpHandler import HttpHandler
from libs.ValidCodeHandler import ValidCodeHandler
import logging
import urllib
import re, time
from libs.MailHandler import MailNotifier
class TaskHandler(object):
'''
classdocs
'''
HOST_URL = 'http://typeb.travelsky.com/eTermServices/TypeBWeb'
VALIDIMAGE_URL = 'http://typeb.travelsky.com/eTermServices/TypeBWeb/ValidImage'
LOGIN_URL = 'http://typeb.travelsky.com/eTermServices/TypeBWeb/loginAction.do'
LOGIN_HEADERS = {
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0",
"Content-Type":"application/x-www-form-urlencoded",
"Referer":"http://typeb.travelsky.com/eTermServices/TypeBWeb/loginAction.do"
}
TASK_URL = 'http://typeb.travelsky.com/eTermServices/TypeBWeb/messageSearchAction.do'
def __init__(self, username, password, handler):
'''
Constructor
'''
self.httpHandler = HttpHandler()
self.username = username
self.password = <PASSWORD>
self.vc = ValidCodeHandler()
self.pattern = re.compile(r'<tr [^>]*>\s*<td [^>]*>([^<>]+)</td>\s*'
'<td [^>]*>([^<>]+)</td>\s*<td [^>]*>([^<>]+)</td>\s*'
'<td [^>]*>\s*([^<>]+?)\s*</td>\s*</tr>')
self.advisehandler = handler
self.checkoverload = False
self.email = ''
self.maxquery = 100
self.limit = 100
def setOverload(self, email, maxquery, limit):
self.checkoverload = True
self.email = email
self.maxquery = maxquery
self.limit = limit
def connect(self):
while True:
self.httpHandler.get(TaskHandler.HOST_URL)
code = self.vc.getImageValidCode(TaskHandler.VALIDIMAGE_URL)
loginData = {}
loginData["user.username"] = self.username
loginData["x"] = 14
loginData["y"] = 34
loginData["user.pwd"] = <PASSWORD>
loginData["validcode"] = code
response = self.httpHandler.post(TaskHandler.LOGIN_URL, TaskHandler.LOGIN_HEADERS, loginData)
content = response.read()
logging.debug(content)
if 'Type B 转报系统' in content or 'Type B Message System' in content:
logging.info("connect TypeBWeb success!")
return True
logging.info("connect TypeBWeb fail.")
def __post(self, taskData):
while True:
try:
response = self.httpHandler.get(TaskHandler.TASK_URL + "?" + urllib.urlencode(taskData))
content = response.read()
if "用户session已经过期,需要重新登陆" not in content:break
logging.warning("用户session已经过期,需要重新登陆")
self.connect()
except Exception, e:
logging.info("[*] Exception:%s" % e)
return content
def postTask(self, taskData):
taskData['提交'] = '提交'
if self.checkoverload:
count = 0
while True:
if not self.overload(): break
count += 1
# 两个小时未能提交任务,发邮件通知用户
if count % 40 == 0 : self.advisehandler.advise(MailNotifier.AdviseMsg)
time.sleep(3 * 60) # sleep 3 minutes
self.__post(taskData)
def taskState(self):
taskData = {}
taskData['actionprocess'] = 'backmsgquery_result'
content = self.__post(taskData)
## 对查询结果进行处理
res = self.pattern.findall(content)
return res
def overload(self):
res = self.taskState()
#from pprint import pprint
#pprint(res)
## 过滤掉死任务,条件:状态为"已开始查询", 且提交时间在3天以前
cur = int(time.time()) - 259200 # 3*24*60*60
livetasts = []
for task in res:
if task[3] == "已开始查询" or task[3] == "Querying":
date = time.strptime(task[2], "%Y-%m-%d %H:%M:%S")
date = int(time.mktime(date))
if date < cur :continue
livetasts.append(task)
# 当前查询数量过多
if len(livetasts) > self.maxquery : return True
# 限制自身查询量
ourtasks = [task for task in livetasts if task[1] == self.email]
if len(ourtasks) > self.limit : return True
return False
<file_sep>/src/config sample.cgi
[website]
username : abcde
password : <PASSWORD>
[advise]
server : smtp.126.com
user : <EMAIL>
passwd : <PASSWORD>
# 网络代理设置
proxy : on
proxy_host : proxy.test.com
proxy_port : 808
advisemail : <EMAIL>
<EMAIL>
[attach]
aserver : pop.126.com
auser : <EMAIL>
apasswd : <PASSWORD>
# 指定只处理的发信人,过滤掉其它邮箱,防止垃圾邮件
targetmail : <EMAIL>
# 邮件处理异常时的保存路径,方便分析改进
path_mail : ./mail/
# 附件保存路径
path_attach : F:/Data/
# 附件保存路径2, 针对有keyword的情况
path_attach_keyword : F:/Data2/
[query]
# 结果接收邮箱地址
email : <EMAIL>
# 是否限制查询过快 on/off
islimit : on
maxquery : 30
limit : 20
# 查询任务列表
alltask : task1
task2
## 任务具体内容
[task1]
# 开关 on/off
state : on
startdate : 2014-10-01 00:00
stopdate : 2014-10-01 00:00
# 每次的查询量,单位为秒
interval : 300
# 查询系统
tag : O
# 查询地址信息,注意格式
queryinfo : [['PEKRMCZ', 'BOSRI1U', 'AVS'],
['PEKRMCZ', 'HDQRI1P', 'MAS'],
['PEKRMCZ', 'HDQRI1S', 'AVS'],
['PEKRMCZ', 'MUCRI1A', 'MAS'],
['PEKRMCZ', 'SWIRI1G', 'MAS'],
['PEKRMCZ', 'TYORIJL', 'AVS']]
# 查询关键字,没有时留空
keyword :
[task2]
# 开关 on/off
state : on
startdate : 2014-10-01 00:00
stopdate : 2014-10-01 00:00
# 每次的查询量,单位为秒
interval : 300
# 查询系统
tag : O
# 查询地址信息,注意格式
queryinfo : [['PEKRMCZ', 'BOSRI1U', 'AVS'],
['PEKRMCZ', 'HDQRI1P', 'MAS'],
['PEKRMCZ', 'HDQRI1S', 'AVS'],
['PEKRMCZ', 'MUCRI1A', 'MAS'],
['PEKRMCZ', 'SWIRI1G', 'MAS'],
['PEKRMCZ', 'TYORIJL', 'AVS']]
# 查询关键字,没有时留空
keyword :
<file_sep>/src/libs/SocksSMTP.py
# -*- coding:utf-8 -*-
'''
Created on Oct 11, 2014
@author: czl
'''
from smtplib import SMTP, SMTP_PORT
from socks import socksocket, PROXY_TYPE_HTTP
from sys import stderr
class SocksSMTP(SMTP):
'''
classdocs
'''
def __init__(self, host, port=SMTP_PORT, proxy_host='localhost', proxy_port=8080):
'''
Constructor
'''
self.proxy_host = proxy_host
self.proxy_port = proxy_port
SMTP.__init__(self, host, port)
def _get_socket(self, port, host, timeout):
if self.debuglevel > 0:
print>>stderr, 'connect:', (host, port)
sock = socksocket()
sock.setproxy(PROXY_TYPE_HTTP, self.proxy_host, self.proxy_port)
sock.connect((port, host))
return sock
|
0634fa59d4bb8a694278e82967e004681794179d
|
[
"Markdown",
"Python"
] | 11
|
Python
|
simuChen/TUMSHelper
|
171a46fc5eefcc01495456acad6ff08889d19281
|
1cbdfd1cbcf851e694bf382c4fa19cb4886678f7
|
refs/heads/master
|
<repo_name>gokhanzalim/etiyaa<file_sep>/src/main/java/com/etiya/Repositories/IssuesRepository.java
package com.etiya.Repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.etiya.entities.Issues;
public interface IssuesRepository extends JpaRepository<Issues,Integer> {
}
<file_sep>/README.md
# etiyaa
Etiya application is a system that records the problems of customers and solution of problems. This project was developed using Java Spring Boot Framework. Firstly the customer is saved in the database then the product information that the customer has received is saved.Secondly, the customer's problem with the product is saved and the problem is processed. Finally, the faulty parts are repaired and operations are stored in the database.
# What's inside
This project is based on the Spring Boot project and uses these packages :
- Maven
- Spring Core
- Spring Data (Hibernate & MySQL)
- Spring MVC
- Spring Security
- Thymeleaf
- Bootstrap 4
# Installation
The project is created with Maven, so you just need to import it to your IDE and build the project to resolve the dependencies. For example,
``Usage (with eclipse or Spring Tool Suite): 1 - Clone the project 2 - Eclipse: File -> Import -> Maven -> Existing Maven Projects 3 - Run 4 - Navigate to localhost:8081 ``
# Database configuration
Create a MySQL database with the name etiya and add the credentials to `` /resources/application.properties``.
The default ones are :
```
spring.datasource.url = jdbc:mysql://localhost:3306/etiya?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
```
**Notes:** ``You can create the database by importing the database/etiya.sql file via mysql workbench or phpmyadmin.Sample data is available in the database.``
# Server configuration
Necessary adjustments can be made in `` /resources/application.properties``. This application works by default at ``localhost: 8081``
```
server.port=8081
```
# Screenshot
### Login Page

### Home Page

### Customer Record Page

### Customer List Page

### Product Form Page

### Product List Page

### Issues Form Page

### Issues List Page

### Rest Api

<file_sep>/src/main/java/com/etiya/Controllers/LoginController.java
package com.etiya.Controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* Login controller.
*/
@Controller
public class LoginController {
/**
* this method returns
* the login page
*
* @return
*/
@RequestMapping(value="/login.html")
public ModelAndView loginPage() {
ModelAndView mav = new ModelAndView();
mav.setViewName("login");
return mav;
}
}
<file_sep>/src/main/java/com/etiya/Service/CustomerServiceImpl.java
package com.etiya.Service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.etiya.Repositories.CustomerRepository;
import com.etiya.entities.Customer;
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService{
@Autowired
CustomerRepository customerRepository;
@Override
public List<Customer> getAllCustomer() {
return customerRepository.findAll();
}
@Override
public Customer getCustomerById(long id) {
return customerRepository.findById((int) id).get();
}
@Override
public void saveOrUpdate(Customer customer) {
customerRepository.save(customer);
}
@Override
public void deleteCustomer(long id) {
customerRepository.deleteById((int) id);
}
}
<file_sep>/database/etiya.sql
-- phpMyAdmin SQL Dump
-- version 4.8.4
-- https://www.phpmyadmin.net/
--
-- Anamakine: 127.0.0.1
-- Üretim Zamanı: 03 Şub 2019, 20:51:39
-- Sunucu sürümü: 10.1.37-MariaDB
-- PHP Sürümü: 7.3.0
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Veritabanı: `etiya`
--
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `authorities`
--
CREATE TABLE `authorities` (
`username` varchar(128) NOT NULL,
`authority` varchar(128) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Tablo döküm verisi `authorities`
--
INSERT INTO `authorities` (`username`, `authority`) VALUES
('etiya', 'ROLE_ADMIN'),
('gokhan', 'ROLE_ADMIN');
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `customer`
--
CREATE TABLE `customer` (
`id` int(11) NOT NULL,
`name` varchar(225) NOT NULL,
`surname` varchar(225) NOT NULL,
`address` text NOT NULL,
`phone` text NOT NULL,
`email` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Tablo döküm verisi `customer`
--
INSERT INTO `customer` (`id`, `name`, `surname`, `address`, `phone`, `email`) VALUES
(1, 'Etiya', 'etiya', 'Yıldız Teknik Üniv. Teknokent', '121231356', '<EMAIL>'),
(2, 'Duru', 'Çetin', 'İstanbul', '3224668', '<EMAIL>'),
(3, 'Mehmet', 'Doğan', 'Ankara', '2122252356', '<EMAIL>'),
(4, 'Murat', 'Soydan', 'Adana', '32225646', '<EMAIL>'),
(5, 'Yelda', 'Kekliktepe', 'İstanbul', '1212120', '<EMAIL>'),
(6, 'Gökhan', 'Zalim', 'Eyüp', '2121212121', '<EMAIL>'),
(7, 'Faruk', 'Çan', 'Göktürk Merkez Mah.', '1234565', '<EMAIL>'),
(8, 'Yılmaz', 'Durak', 'Eyüp/İstanbul', '1223321', '<EMAIL>'),
(9, 'Ekip', 'Fatih', 'Zonguldak', '53456546', '<EMAIL>'),
(10, 'Duygu', 'Mert', 'İstanbul', '2122252364', '<EMAIL>'),
(11, 'Cenk', 'Türkmen', 'Işıklar Mahallesi Girne Cad. No:25', '22221532', '<EMAIL>');
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `issues`
--
CREATE TABLE `issues` (
`id` int(11) NOT NULL,
`customer_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`type` int(11) NOT NULL,
`process_details` text NOT NULL,
`changes` text NOT NULL,
`process_date` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Tablo döküm verisi `issues`
--
INSERT INTO `issues` (`id`, `customer_id`, `product_id`, `user_id`, `type`, `process_details`, `changes`, `process_date`) VALUES
(1, 5, 8, 1, 3, 'Ariza tespit edildi', 'Lastik', '2019-02-02 00:56:27'),
(2, 5, 8, 2, 3, 'Test Edildi', 'Somun', '2019-02-02 00:56:27'),
(3, 9, 12, 1, 3, 'Genel Bakım', 'Klips', '2019-02-02 00:56:27'),
(4, 7, 5, 2, 1, 'Genel Bakım', 'Su,tesisat,kondansatör', '2019-02-02 00:56:27'),
(5, 4, 9, 1, 3, 'Temizlik Yapıldı', 'Havalandırma Filtreleri', '2019-02-07 00:00:00'),
(6, 4, 9, 2, 2, 'Bozulan parçalar onarıldı', 'elektrik tesisatı', '2019-02-07 00:59:00'),
(7, 4, 9, 1, 3, 'Arıza giderildi', 'ekran', '2019-02-08 04:59:00'),
(9, 8, 11, 1, 3, '6 Aylık Bakım Yapıldı', 'Yag,Lastik ve Raflar', '2019-02-12 14:44:00'),
(12, 10, 14, 2, 2, 'Mekanik parçalar onarıldı', 'Mikroişlemci', '2019-02-02 14:44:00'),
(22, 6, 7, 2, 1, 'Genel Bakım', 'Yag,Lastik ve Raflar', '2019-02-06 23:24:00');
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `products`
--
CREATE TABLE `products` (
`id` int(11) NOT NULL,
`product_name` text NOT NULL,
`serial_number` varchar(225) NOT NULL,
`buy_date` datetime NOT NULL,
`period` int(11) NOT NULL DEFAULT '0',
`customer_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Tablo döküm verisi `products`
--
INSERT INTO `products` (`id`, `product_name`, `serial_number`, `buy_date`, `period`, `customer_id`) VALUES
(7, 'Televizyon', '1334144600156', '2019-02-02 00:57:23', 2, 6),
(6, 'Çamaşır Makinası', '4444545', '2019-02-02 00:57:23', 3, 6),
(5, 'Televizyon', '11224555', '2019-02-02 00:57:23', 6, 7),
(8, 'Araba', '1334012532', '2019-02-02 00:57:23', 12, 5),
(9, 'Buzdolabı', '854675156', '2019-02-02 00:57:23', 6, 4),
(10, 'Televizyon', '11224555', '2019-02-02 00:57:23', 3, 8),
(11, 'Lorem Ipsum', '11224555', '2019-02-02 00:57:23', 6, 8),
(12, 'Televizyon', '2324242', '2019-02-02 00:57:23', 6, 9),
(13, 'Televizyon', '4444545', '2019-01-01 00:06:00', 12, 6),
(14, 'Kombi', '2212353566', '2019-02-24 13:24:00', 12, 10);
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(128) NOT NULL,
`password` varchar(512) NOT NULL,
`enabled` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Tablo döküm verisi `users`
--
INSERT INTO `users` (`id`, `username`, `password`, `enabled`) VALUES
(1, 'etiya', '{noop}<PASSWORD>', 1),
(2, 'gokhan', '{noop}<PASSWORD>', 1);
--
-- Dökümü yapılmış tablolar için indeksler
--
--
-- Tablo için indeksler `customer`
--
ALTER TABLE `customer`
ADD PRIMARY KEY (`id`);
--
-- Tablo için indeksler `issues`
--
ALTER TABLE `issues`
ADD PRIMARY KEY (`id`),
ADD KEY `FKcigc16s3flsg53i2sy0m37e` (`user_id`);
--
-- Tablo için indeksler `products`
--
ALTER TABLE `products`
ADD PRIMARY KEY (`id`),
ADD KEY `FKsu77w85kis17ny28x5pli9mvn` (`customer_id`);
--
-- Tablo için indeksler `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- Dökümü yapılmış tablolar için AUTO_INCREMENT değeri
--
--
-- Tablo için AUTO_INCREMENT değeri `customer`
--
ALTER TABLE `customer`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
--
-- Tablo için AUTO_INCREMENT değeri `issues`
--
ALTER TABLE `issues`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
--
-- Tablo için AUTO_INCREMENT değeri `products`
--
ALTER TABLE `products`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15;
--
-- Tablo için AUTO_INCREMENT değeri `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- Dökümü yapılmış tablolar için kısıtlamalar
--
--
-- Tablo kısıtlamaları `issues`
--
ALTER TABLE `issues`
ADD CONSTRAINT `FKcigc16s3flsg53i2sy0m37e` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/src/main/java/com/etiya/Service/ProductServiceImpl.java
package com.etiya.Service;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.etiya.Repositories.ProductRepository;
import com.etiya.entities.Product;
@Service
@Transactional
public class ProductServiceImpl implements ProductService {
@PersistenceContext
private EntityManager entityManager;
@Autowired
ProductRepository productRepository;
@Override
public List<Product> getAllProduct() {
// TODO Auto-generated method stub
return productRepository.findAll();
}
@Override
public Product getProductById(long id) {
// TODO Auto-generated method stub
return productRepository.findById((int) id).get();
}
@Override
public void saveOrUpdate(Product product) {
productRepository.save(product);
}
@Override
public void deleteProductr(long id) {
productRepository.deleteById((int) id);
}
@Override
public List<Product> findByCustomer() {
// TODO Auto-generated method stub
return productRepository.findAll();
}
}
<file_sep>/src/main/java/com/etiya/Service/ProductService.java
package com.etiya.Service;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import com.etiya.entities.Product;
public interface ProductService {
public List<Product> getAllProduct();
public Product getProductById(long id);
public void saveOrUpdate(Product product);
public void deleteProductr(long id);
@Query("SELECT * FROM products t WHERE t.customer_id = 'id'")
public List<Product> findByCustomer();
}
<file_sep>/src/main/java/com/etiya/Service/IssuesService.java
package com.etiya.Service;
import java.util.List;
import com.etiya.entities.Issues;
import com.etiya.entities.Product;
public interface IssuesService {
public List<Issues> getAllIssues();
public void saveOrUpdate(Issues issues);
}
|
d32177d84d4b6fdbbfade38aa4837bb6efd8489d
|
[
"Markdown",
"Java",
"SQL"
] | 8
|
Java
|
gokhanzalim/etiyaa
|
12ad86ca51adb8152a13cc8677b096213eac4ba2
|
df83e532026e88f93d50b017c37f27510d951883
|
refs/heads/main
|
<repo_name>azkasyafaf/pirple-java-fundamentals<file_sep>/Homework6/src/homework6/sphere.java
/*
Class Sphere
Part of Homework #6 Package
*/
package homework6;
/*
* This code written by : <NAME>
* Friday, 11 September 2020
*/
public class sphere {
private float r;
public sphere(float radius)
{
r = radius;
}
public float diameter()
{
return 2*r;
}
public double circumference()
{
return Math.PI*r;
}
public double surfaceArea()
{
return Math.PI*Math.pow(2*r, 2);
}
public double volume()
{
return (4.0/3)*Math.PI*Math.pow(r,3);
}
}
|
1ec60f436ff80ca7452b8618ad4690cb5a410ad3
|
[
"Java"
] | 1
|
Java
|
azkasyafaf/pirple-java-fundamentals
|
7c1935b09e822e8b77fad554ec3745a4371bdc74
|
abcf3f0acea70bb5f214ed63d6b3dda20f3006a7
|
refs/heads/master
|
<file_sep>export const environment = {
production: true,
firebase: {
apiKey: "<KEY>",
authDomain: "angular-crud-65322.firebaseapp.com",
databaseURL: "https://angular-crud-65322.firebaseio.com",
projectId: "angular-crud-65322",
storageBucket: "angular-crud-65322.appspot.com",
messagingSenderId: "1090795736800",
appId: "1:1090795736800:web:66172db305c14758230a85",
measurementId: "G-6TJDWY0Z4E"
}
};
<file_sep>import { Component, OnInit } from "@angular/core";
import { FirebaseService } from "./shared/services/firebase.service";
import { Router } from "@angular/router";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { MatTableDataSource, MatDialog } from "@angular/material";
import { EditUserDialogComponent } from "./pages/edit-user-dialog/edit-user-dialog.component";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnInit {
dataSource: MatTableDataSource<any>;
displayedColumns = ["fName", "lName", "age", "mobile", "action"];
userForm: FormGroup;
constructor(
public firebaseService: FirebaseService,
private router: Router,
private fb: FormBuilder,
private dialog: MatDialog
) {
this.userForm = this.fb.group({
firstName: [null, Validators.required],
lastName: [null, Validators.required],
age: [null, Validators.required],
mobile: [null, Validators.required]
});
}
ngOnInit() {
this.userForm.markAllAsTouched();
this.dataSource = new MatTableDataSource([]);
this.getUsers();
}
getUsers(): void {
this.firebaseService.getUsers().subscribe(data => {
this.dataSource.data = data;
});
}
get fieldControls() {
return this.userForm.controls;
}
construct() {
return {
firstName: this.fieldControls.firstName.value,
lastName: this.fieldControls.lastName.value,
age: this.fieldControls.age.value,
mobile: this.fieldControls.mobile.value
};
}
saveUser() {
this.firebaseService.createUser(this.construct());
this.userForm.reset();
}
deleteUserByDocId(docId: any) {
this.firebaseService.deleteUser(docId);
}
openEditUserDialog(docId: any) {
this.dialog.open(EditUserDialogComponent, { data: docId });
}
}
<file_sep>import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { AngularFireModule } from "@angular/fire";
import { AngularFirestoreModule } from "@angular/fire/firestore";
import { environment } from "src/environments/environment";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { FirebaseService } from "./shared/services/firebase.service";
import {
MatAutocompleteModule,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatCheckboxModule,
MatChipsModule,
MatDatepickerModule,
MatDialogModule,
MatExpansionModule,
MatGridListModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatNativeDateModule,
MatPaginatorModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatRadioModule,
MatRippleModule,
MatSelectModule,
MatSidenavModule,
MatSliderModule,
MatSlideToggleModule,
MatSnackBarModule,
MatSortModule,
MatTableModule,
MatTabsModule,
MatToolbarModule,
MatTooltipModule,
MatStepperModule,
MAT_DATE_LOCALE
} from "@angular/material";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { EditUserDialogComponent } from "./pages/edit-user-dialog/edit-user-dialog.component";
@NgModule({
declarations: [AppComponent, EditUserDialogComponent],
imports: [
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule,
FormsModule,
ReactiveFormsModule,
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatButtonModule,
MatInputModule,
MatSliderModule,
MatDialogModule,
MatIconModule,
MatCardModule,
MatTableModule
],
providers: [FirebaseService],
entryComponents: [EditUserDialogComponent],
bootstrap: [AppComponent]
})
export class AppModule {}
<file_sep>import { Component, OnInit, Inject } from "@angular/core";
import { FirebaseService } from "../../shared/services/firebase.service";
import { Router } from "@angular/router";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { MAT_DIALOG_DATA, MatDialogRef } from "@angular/material";
@Component({
selector: "app-edit-user",
templateUrl: "./edit-user-dialog.component.html",
styleUrls: ["./edit-user-dialog.component.scss"]
})
export class EditUserDialogComponent implements OnInit {
userForm: FormGroup;
userDetail: any;
constructor(
public firebaseService: FirebaseService,
private router: Router,
private fb: FormBuilder,
@Inject(MAT_DIALOG_DATA) public data: any,
private dialogRef: MatDialogRef<EditUserDialogComponent>
) {
this.userForm = this.fb.group({
firstName: [null, Validators.required],
lastName: [null],
age: [null],
mobile: [null]
});
}
ngOnInit() {
this.getUserDetailByDocId();
}
getUserDetailByDocId(): void {
this.firebaseService.getUserDetailByDocId(this.data).subscribe(data => {
this.userDetail = data;
this.setForm();
});
}
setForm() {
this.userForm.setValue({
firstName: this.userDetail.payload.data().firstName,
lastName: this.userDetail.payload.data().lastName,
age: this.userDetail.payload.data().age,
mobile: this.userDetail.payload.data().mobile
});
}
get fieldControls() {
return this.userForm.controls;
}
construct() {
return {
firstName: this.fieldControls.firstName.value,
lastName: this.fieldControls.lastName.value,
age: this.fieldControls.age.value,
mobile: this.fieldControls.mobile.value
};
}
updateUser() {
this.firebaseService.updateUser(this.data, this.construct());
this.dialogRef.close("SUCCESS");
}
cancel() {
this.dialogRef.close("CANCEL");
}
}
<file_sep>import { Injectable } from "@angular/core";
import { AngularFirestore } from "@angular/fire/firestore";
@Injectable({
providedIn: "root"
})
export class FirebaseService {
constructor(public db: AngularFirestore) {}
createUser(user: any) {
return this.db.collection("users").add(user);
}
getUsers() {
return this.db.collection("users").snapshotChanges();
}
getUserDetailByDocId(docId) {
return this.db
.collection("users")
.doc(docId)
.snapshotChanges();
}
updateUser(userKey, user) {
return this.db
.collection("users")
.doc(userKey)
.set(user);
}
deleteUser(docId) {
return this.db
.collection("users")
.doc(docId)
.delete();
}
}
|
066f3ae1f8ecb02316b01cd58d6fba1cbc048ec8
|
[
"TypeScript"
] | 5
|
TypeScript
|
gdurgaprasad/angular-firebase-crud
|
c4d1322a604a77ebfbebcd893b9a9fe58bf48f1b
|
f51c93d41e9b39e0da49d02a45426fbdc1bea350
|
refs/heads/master
|
<file_sep># 29° Esercizio Corso Boolean
<file_sep>$(document).ready(function () {
var baseUrl = 'http://172.16.58.3:4011/sales';
apiCallGet();
$('#submit').click(function () { // Al click del bottone
var selSalesman = $('#sel-salesman').val(); // Assegno a variabili i valori dei campi del form
var selDD = $('.dd').val();
var selMM = $('.mm').val();
var selYYYY = $('.yyyy').val();
var selDate = selDD + '/' + selMM + '/' + selYYYY; // Creo una data compatibile con quelle dell'API
var selAmount = parseInt($('#input-amount').val());
var selData = { // Creo un oggetto con i valori dei campi del form
salesman: selSalesman,
amount: selAmount,
date: selDate
};
$.ajax({ // Chiamata Post con data in ingresso l'oggetto appena creato
url: baseUrl,
method: 'POST',
data: selData,
success: function (data) {
setTimeout(function(){ apiCallGet();}, 1000); // All'interno rievoco la funzione per la chiamata GET per aggiornare i grafici
},
error: function (err) {
alert('Error');
}
});
$('#sel-salesman').val(''); // Resetto tutti i campi del form
$('.dd').val('');
$('.mm').val('');
$('#input-amount').val('');
});
function apiCallGet() {
$.ajax({
url: baseUrl,
method: 'GET',
success: function (data) {
var objectMonth = objectMonthBuilder(data); // Assegno a una variabile la funzione che restituisce un oggetto per ricavare in seguito i valori delle chiavi
createLineChart('#line-chart', objectMonth.labels, objectMonth.data);
var totalAmount = totalAmountBuilder(data); // Assegno a una variabile la funzione di costruzione Amount totale per usarla nella successiva funzione
var objectSalesman = objectSalesmanBuilder(data, totalAmount);
createPieChart('#pie-chart', objectSalesman.labels, objectSalesman.data);
var objectQuarter = objectQuarterBuilder(data);
createBarChart('#bar-chart', objectQuarter.labels, objectQuarter.data);
},
error: function (err) {
alert('errore API');
}
});
};
function totalAmountBuilder(array) { // Funzione che con un array in entrata ritorna una variabile con valore l'Amount Totale
var totalAmount = 0;
for (var i = 0; i < array.length; i++) {
var iObject = array[i];
totalAmount += parseInt(iObject.amount);
}
return totalAmount;
}
function objectMonthBuilder(array) { // Funzione che con un array in entrata crea un oggetto per ritornare due array con mesi e vendite
var objectMonth = { // Creazione oggetto con chiavi già fissate
gennaio: 0,
febbraio: 0,
marzo: 0,
aprile: 0,
maggio: 0,
giugno: 0,
luglio: 0,
agosto: 0,
settembre: 0,
ottobre: 0,
novembre: 0,
dicembre: 0,
};
for (var i = 0; i < array.length; i++) { // Ciclo sull'array GET per aggiungere a ogni mese dell'oggetto l'amount corrispondente
var iObject = array[i];
var iObjectDate = iObject.date;
var month = moment(iObjectDate, 'DD/MM/YYYY').format('MMMM');
objectMonth[month] += parseInt(iObject.amount);
}
var arrayLabels = []; // Inizializzo i due Array da utilizzare in Chart.js
var arrayData = [];
for (var key in objectMonth) { // Ciclo all'interno dell'oggetto per trasformare la coppia chiave-valore in due array da dare a Chart.js
arrayLabels.push(key); // Inserisco il nome del mese nell'arrayLabels
arrayData.push(objectMonth[key]); // Inserisco nell'arrayData la somma di tutte le vendite relative a quel mese
}
return {
labels: arrayLabels,
data: arrayData
};
};
function objectSalesmanBuilder(array, totalAmount) { // Funzione che con un array in entrata crea un oggetto per ritornare due array con venditori e vendite
var objectSalesman = {}; // Creazione oggetto vuoto
for (var i = 0; i < array.length; i++) { // Ciclo sull'array GET per aggiungere i venditori all'oggetto e il rispettivo amount per ciascuno di essi
var iObject = array[i];
var salesman = iObject.salesman;
if (objectSalesman[salesman] === undefined) {
objectSalesman[salesman] = 0;
}
objectSalesman[salesman] += parseInt(iObject.amount);
}
var arrayLabels = []; // Inizializzo i due Array da utilizzare in Chart.js
var arrayData = [];
for (var key in objectSalesman) { // Ciclo all'interno dell'oggetto per trasformare la coppia chiave-valore in due array da dare a Chart.js
arrayLabels.push(key); // Inserisco il nome del venditore nell'arrayLabels
var salesmanAmountPerc = ((objectSalesman[key] / totalAmount) * 100).toFixed(2); // Assegno a una variabile il venduto in percentuale
arrayData.push(salesmanAmountPerc); // Inserisco nell'arrayData la somma di tutte le vendite relative a quel venditore
}
return {
labels: arrayLabels,
data: arrayData
};
};
function objectQuarterBuilder(array) { // Funzione che con un array in entrata crea un oggetto per ritornare due array con mesi e vendite
var objectQuarter = {}; // Creazione oggetto vuoto
for (var i = 0; i < array.length; i++) { // Ciclo sull'array GET per aggiungere a ogni mese dell'oggetto l'amount corrispondente
var iObject = array[i];
var iObjectDate = iObject.date;
var quarter = moment(iObjectDate, 'DD/MM/YYYY').quarter();
if (objectQuarter[quarter] === undefined) {
objectQuarter[quarter] = 0;
}
objectQuarter[quarter] += parseInt(iObject.amount);
}
var arrayLabels = []; // Inizializzo i due Array da utilizzare in Chart.js
var arrayData = [];
for (var key in objectQuarter) { // Ciclo all'interno dell'oggetto per trasformare la coppia chiave-valore in due array da dare a Chart.js
arrayLabels.push(key); // Inserisco il nome del mese nell'arrayLabels
arrayData.push(objectQuarter[key]); // Inserisco nell'arrayData la somma di tutte le vendite relative a quel mese
}
return {
labels: arrayLabels,
data: arrayData
};
};
function createLineChart(id, labels, data) { // Funzione che crea un grafico tipo line dato un id di destinazione e due array labels e data
var ctx = $(id);
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Vendite Mensili',
borderColor: 'darkblue',
lineTension: 0,
data: data
}]
}
});
};
function createBarChart(id, labels, data) { // Funzione che crea un grafico tipo line dato un id di destinazione e due array labels e data
var ctx = $(id);
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Vendite Trimestrali',
backgroundColor: 'darkred',
data: data
}]
}
});
};
function createPieChart(id, labels, data) { // Funzione che crea un grafico tipo pie dato un id di destinazione e due array labels e data
var ctx = $(id);
var chart = new Chart(ctx, {
type: 'pie',
data: {
datasets: [{
data: data,
backgroundColor: ['pink', 'orange', 'lightblue', 'lightgreen']
}],
labels: labels
},
options: {
responsive: true,
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return data['labels'][tooltipItem['index']] + ': ' + data['datasets'][0]['data'][tooltipItem['index']] + '%';
}
}
}
}
});
};
});
|
c42db0e1088f6ebe85953c43b6f0ee9a29d1372a
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Luigi-Fontana/rest-chartbool
|
9e5c75c3f0ee35e6cee5aeed8d530b8cc55b76b6
|
995277a602c75d0ea0449789b6cc4d177f0c200b
|
refs/heads/master
|
<repo_name>dane-king/neo4j.client<file_sep>/kb-server/src/test/java/net/daneking/resource/AbstractResourceTest.java
package net.daneking.resource;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
public class AbstractResourceTest {
@Test
public void shouldInstantiateListIfConstructedWithNull() {
AbstractResource resource = new AbstractResource(null) {
};
assertNotNull(resource.getLinks());
}
}
<file_sep>/kb-server/src/main/java/net/daneking/document/domain/Document.java
package net.daneking.document.domain;
import javax.xml.bind.annotation.XmlRootElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@XmlRootElement()
public class Document {
protected static final Logger _logger = LoggerFactory.getLogger(Document.class);
public Document() {
}
public Document(final String identifier) {
this.identifier = identifier;
}
private String identifier;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(final String identifier) {
this.identifier = identifier;
}
}
<file_sep>/kb-server/src/integration/java/net/daneking/document/DocumentResourceIntegrationTest.java
package net.daneking.document;
import static org.junit.Assert.assertEquals;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import net.daneking.document.domain.Document;
import org.junit.Before;
import org.junit.Test;
import utils.TestSupport;
public class DocumentResourceIntegrationTest extends TestSupport<DocumentResource> {
private static final String INITIAL_ITEM_ID = "20";
@Override
@Before
public void setUp() throws Exception {
super.setUp();
addInitialItem();
}
private void addInitialItem() {
Document document = new Document(INITIAL_ITEM_ID);
final Response response = putItem(document);
}
@Test
public void shouldReturnA404WhenItemIsNotFound() {
final Response response = getItem("345");
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
@Test
public void shouldReturnA200WhenItemIsFound() {
final Response response = getItem(INITIAL_ITEM_ID.toString());
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
private Response getItem(final String id) {
final Response response = documentResource().path(id).request(MediaType.APPLICATION_JSON).get(Response.class);
return response;
}
@Test
public void shouldReturnA204WhenItemIsSaved() {
final Response response = putItem(new Document("2"));
assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus());
}
private Response putItem(final Document information) {
String path = "20";
Document entity = new Document(path);
final Response response = documentResource().path(path).request().put(Entity.json(entity));
return response;
}
protected WebTarget documentResource() {
return target("documents");
}
}
<file_sep>/neo4j.client/neo4j.rest.client/src/main/java/net/daneking/WebInitializer.java
package net.daneking;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.support.
* AbstractAnnotationConfigDispatcherServletInitializer
* #getRootConfigClasses()
*/
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.support.
* AbstractAnnotationConfigDispatcherServletInitializer
* #getServletConfigClasses()
*/
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfiguration.class };
}
/*
* (non-Javadoc)
*
* @see
* org.springframework.web.servlet.support.AbstractDispatcherServletInitializer
* #getServletMappings()
*/
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
/**
* Web layer configuration enabling Spring MVC, Spring Hateoas
* {@link EntityLinks}.
*
* @author <NAME>
*/
@Configuration
@EnableWebMvc
@ComponentScan(excludeFilters = @Filter({ Service.class, Configuration.class }))
public static class WebConfiguration extends WebMvcConfigurationSupport {
@Autowired
ApplicationContext context;
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.config.annotation.
* WebMvcConfigurationSupport
* #configureContentNegotiation(org.springframework
* .web.servlet.config.annotation.ContentNegotiationConfigurer)
*/
@Override
protected void configureContentNegotiation(final ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON);
}
@Bean
public RestOperations restOperations() {
RestTemplate rest = new RestTemplate();
// this is crucial!
rest.getMessageConverters().add(0, mappingJacksonHttpMessageConverter());
return rest;
}
@Bean
public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
// converter.setObjectMapper(myObjectMapper());
return converter;
}
/*
* @Bean public ObjectMapper myObjectMapper() { // your custom
* ObjectMapper here }
*/
}
}<file_sep>/kb-server/src/main/java/net/daneking/home/HomeResource.java
package net.daneking.home;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import net.daneking.home.activity.StartingPoint;
import net.daneking.representation.Representation;
@Path("/")
public class HomeResource {
@Context
private UriInfo uriInfo;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response home() {
Representation<String> wrappedEntity = new StartingPoint().getInitialLinks(uriInfo.getAbsolutePath().toString());
return Response.ok(wrappedEntity).build();
}
}
<file_sep>/kb-server/src/integration/java/net/daneking/home/HomeResourceTest.java
package net.daneking.home;
import static org.junit.Assert.assertEquals;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import net.daneking.representation.Link;
import net.daneking.representation.Representation;
import org.junit.Test;
import utils.TestSupport;
public class HomeResourceTest extends TestSupport<HomeResource> {
@Test
@SuppressWarnings("unchecked")
public void shouldHaveLinks() {
final Response response = getItem(Status.OK.getStatusCode());
Representation<String> homeRepresentation = response.readEntity(Representation.class);
Link selfLink = homeRepresentation.getLinkByName("self");
assertEquals(MediaType.APPLICATION_JSON, selfLink.getMediaType());
assertEquals("self", selfLink.getName());
assertEquals("http://localhost:9998/", selfLink.getUri());
}
private Response getItem(final int status) {
final Response response = getResource().request(MediaType.APPLICATION_JSON).get(Response.class);
assertEquals(status, response.getStatus());
return response;
}
protected WebTarget getResource() {
return target("/");
}
}
|
28888fd97cb322f1f8f440374df51ac85563fd5a
|
[
"Java"
] | 6
|
Java
|
dane-king/neo4j.client
|
fb90c53a80d3be9829d5bf0758364c20a49a7b18
|
70bac2e9476412202d99520454e7d003c73189b6
|
refs/heads/master
|
<repo_name>ggbggb/School<file_sep>/Service/SchoolService/School.Domain/Transaction.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class Transaction
{
[Column("TransactionPK")]
public Guid TransactionPK { get; set; }
[Column("TransactionDate")]
public DateTime TransactionDate { get; set; }
[Column("SchoolPK")]
public Guid SchoolPK { get; set; }
[Column("Description")]
[MaxLength(100)]
public string Description { get; set; }
[Column("IsCredit")]
public bool IsCredit { get; set; }
[Column("Amount")]
public decimal Amount { get; set; }
[Column("PayerContactPK")]
public Guid PayerContactPK { get; set; }
[Column("PayeeContactPK")]
public Guid PayeeContactPK { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/Parent.cs
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class Parent
{
[Column("ParentPK")]
public Guid ParentPK { get; set; }
[Column("ContactPK")]
public Guid ContactPK { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/Class.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class Class
{
[Column("ClassPK")]
public Guid ClassPK { get; set; }
[Column("Name")]
[MaxLength(30)]
public string Name { get; set; }
[Column("SchoolPK")]
public Guid SchoolPK { get; set; }
[Column("StudentMaxNo")]
public int StudentMaxNo { get; set; }
[Column("StudentNo")]
public int StudentNo { get; set; }
[Column("Teacher1PK")]
public Guid Teacher1PK { get; set; }
[Column("Teacher2PK")]
public Guid Teacher2PK { get; set; }
[Column("TuitionFee")]
public decimal TuitionFee { get; set; }
[Column("ClassLevelPK")]
public Guid ClassLevelPK { get; set; }
[Column("Description")]
[MaxLength(150)]
public string Description { get; set; }
[Column("DaysOn")]
[MaxLength(7)]
public string DaysOn { get; set; }
[Column("StartTime")]
[MaxLength(5)]
public string StartTime { get; set; }
[Column("EndTime")]
[MaxLength(5)]
public string EndTime { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/SchoolTerm.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class SchoolTerm
{
[Column("SchoolTermPK")]
public Guid SchoolTermPK { get; set; }
[Column("Description")]
[MaxLength(20)]
public string Description { get; set; }
[Column("StartDate")]
public DateTime StartDate { get; set; }
[Column("EndDate")]
public DateTime EndDate { get; set; }
[Column("SchoolPK")]
public Guid SchoolPK { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/Teacher.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class Teacher
{
[Column("TeacherPK")]
public Guid TeacherPK { get; set; }
[Column("AvailableDays")]
[MaxLength(7)]
public string AvailableDays { get; set; }
[Column("Salary")]
public decimal Salary { get; set; }
[Column("ContactPK")]
public Guid ContactPK { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/ClassLevel.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class ClassLevel
{
[Column("ClassLevelPK")]
public Guid ClassLevelPK { get; set; }
[Column("Description")]
[MaxLength(20)]
public string Description { get; set; }
[Column("SchoolPK")]
public Guid SchoolPK { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/School.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class School
{
[Column("SchoolPK")]
public Guid SchoolPK { get; set; }
[Column("Name")]
[MaxLength(50)]
public string Name { get; set; }
[Column("LocationPK")]
public Guid LocationPK { get; set; }
[Column("PrincipleUserPK")]
public Guid PrincipleUserPK { get; set; }
[Column("ContactUserPK")]
public Guid ContactUserPK { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/Creditor.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class Creditor
{
[Column("CreditorPK")]
public Guid CreditorPK { get; set; }
[Column("Name")]
[MaxLength(50)]
public string Name { get; set; }
[Column("ContactPK")]
public Guid ContactPK { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/User.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class User
{
[Column("UserPK")]
public Guid UserPK { get; set; }
[Column("LoginName")]
[MaxLength(50)]
public string LoginName { get; set; }
[Column("Password")]
[MaxLength(20)]
public string Password { get; set; }
[Column("UserRolePK")]
public Guid UserRolePK { get; set; }
[Column("RegistrationStartDate")]
public DateTime RegistrationStartDate { get; set; }
[Column("LicenseExpiryDate")]
public DateTime LicenseExpiryDate { get; set; }
[Column("CreatedDate")]
public DateTime CreatedDate { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/Student.cs
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class Student
{
[Column("StudentPK")]
public Guid StudentPK { get; set; }
[Column("ContactPK")]
public Guid ContactPK { get; set; }
[Column("Parent1PK")]
public Guid Parent1PK { get; set; }
[Column("Parent2PK")]
public Guid Parent2PK { get; set; }
[Column("PaidToDate")]
public DateTime PaidToDate { get; set; }
[Column("IsActive")]
public bool IsActive { get; set; }
[Column("IsDeleted")]
public bool IsDeleted { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/SchoolEnrolment.cs
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class SchoolEnrolment
{
[Column("SchoolEnrolmentPK")]
public Guid SchoolEnrolmentPK { get; set; }
[Column("ClassPK")]
public Guid ClassPK { get; set; }
[Column("StudentPK")]
public Guid StudentPK { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/Invoice.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class Invoice
{
[Column("InvoicePK")]
public Guid InvoicePK { get; set; }
[Column("SchoolPK")]
public Guid SchoolPK { get; set; }
[Column("InvoiceNo")]
[MaxLength(20)]
public string InvoiceNo { get; set; }
[Column("Description")]
[MaxLength(100)]
public string Description { get; set; }
[Column("DueDate")]
public DateTime DueDate { get; set; }
[Column("InvoiceFromContactPK")]
public Guid InvoiceFromContactPK { get; set; }
[Column("InvoiceToContactPK")]
public Guid InvoiceToContactPK { get; set; }
[Column("InvoiceForContactPK")]
public Guid InvoiceForContactPK { get; set; }
[Column("IsPaid")]
public bool IsPaid { get; set; }
[Column("IsDeleted")]
public bool IsDeleted { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/Location.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class Location
{
[Column("LocationPK")]
public Guid LocationPK { get; set; }
[Column("Address")]
[MaxLength(50)]
public string Address { get; set; }
[Column("Suburb")]
[MaxLength(20)]
public string Suburb { get; set; }
[Column("Postcode")]
[MaxLength(10)]
public string Postcode { get; set; }
[Column("State")]
[MaxLength(10)]
public string State { get; set; }
[Column("Country")]
[MaxLength(20)]
public string Country { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/UserRole.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class UserRole
{
[Column("UserRolePK")]
public Guid UserRolePK { get; set; }
[Column("Code")]
[MaxLength(10)]
public string Code { get; set; }
[Column("Description")]
[MaxLength(20)]
public string Description { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/Contact.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class Contact
{
[Column("ContactPK")]
public Guid ContactPK { get; set; }
[Column("Title")]
[MaxLength(10)]
public string Title { get; set; }
[Column("FirstName")]
[MaxLength(20)]
public string FirstName { get; set; }
[Column("MiddleName")]
[MaxLength(20)]
public string MiddleName { get; set; }
[Column("LastName")]
[MaxLength(20)]
public string LastName { get; set; }
[Column("DateOfBirth")]
public DateTime DateOfBirth { get; set; }
[Column("Address")]
[MaxLength(150)]
public string Address { get; set; }
[Column("Postcode")]
[MaxLength(10)]
public string Postcode { get; set; }
[Column("State")]
[MaxLength(10)]
public string State { get; set; }
[Column("Country")]
[MaxLength(20)]
public string Country { get; set; }
[Column("Phone")]
[MaxLength(20)]
public string Phone { get; set; }
[Column("Email")]
[MaxLength(50)]
public string Email { get; set; }
[Column("ContactByPhone")]
public bool ContactByPhone { get; set; }
[Column("ContactByEmail")]
public bool ContactByEmail { get; set; }
[Column("IsDeleted")]
public bool IsDeleted { get; set; }
[Column("IsActive")]
public bool IsActive { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/SchoolOpenClass.cs
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class SchoolOpenClass
{
[Column("SchoolOpenClassPK")]
public Guid SchoolOpenClassPK { get; set; }
[Column("SchoolPK")]
public Guid SchoolPK { get; set; }
[Column("SchoolTermPK")]
public Guid SchoolTermPK { get; set; }
[Column("ClassPK")]
public Guid ClassPK { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Domain/SchoolVariable.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace School.Domain
{
public class SchoolVariable
{
[Column("SchoolVariablePK")]
public Guid SchoolVariablePK { get; set; }
[Column("SchoolPK")]
public Guid SchoolPK { get; set; }
[Column("Name")]
[MaxLength(30)]
public string Name { get; set; }
[Column("Value")]
[MaxLength(30)]
public string Value { get; set; }
}
}
<file_sep>/Service/SchoolService/School.Data/SchoolContext.cs
using Microsoft.EntityFrameworkCore;
using School.Domain;
namespace School.Data
{
public class SchoolContext : DbContext
{
private const string ConnectionString = "Data Source=localhost;Initial Catelog=SchoolProjectDB";
public DbSet<Class> Classes { get; set; }
public DbSet<ClassLevel> ClassLevels { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<Creditor> Creditors { get; set; }
public DbSet<Invoice> Invoices { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<Parent> Parents { get; set; }
public DbSet<School.Domain.School> Schools { get; set; }
public DbSet<SchoolEnrolment> SchoolEnrolments { get; set; }
public DbSet<SchoolOpenClass> SchoolOpenClasses { get; set; }
public DbSet<SchoolTerm> SchoolTerms { get; set; }
public DbSet<SchoolVariable> SchoolVariables { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<Teacher> Teachers { get; set; }
public DbSet<Transaction> Transactions { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<UserRole> UserRoles { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConnectionString);
}
}
}
|
7809f7f2feb4b6ed89dc5ffb654de2302b7384c4
|
[
"C#"
] | 18
|
C#
|
ggbggb/School
|
28e4bdaf87f5e534e76fb831b295b897110db118
|
346d4077255f5c6c98909af295df139a4ab678ac
|
refs/heads/master
|
<file_sep># Express Stylus middleware
Stylus-to-CSS conversion middleware for Express to make simple magic on the fly.
It's a Stylus-version of [Express-less](https://github.com/toogle/express-less) middleware
## Installation
```bash
npm i express-stylus-middleware -S
```
## Usage
```js
const express = require("express");
const expressStylus = require("express-stylus-middleware");
const app = express();
app.use("/css", expressStylus(__dirname + "/stylus-css"));
```
Also you can use cache:
```js
app.use("/css", expressStylus(__dirname + "/stylus-css"), { cache: true });
```
And make compressed css:
```js
app.use("/css", expressStylus(__dirname + "/stylus-css", { compress: true }));
```
Additionally, you can use some Stylus's in-build options (in theory, not tested):
```
`force` Always re-compile
`compile` Custom compile function, accepting the arguments
`(str, path)`.
`firebug` Emits debug infos in the generated css that can
be used by the FireStylus Firebug plugin
`linenos` Emits comments in the generated css indicating
the corresponding stylus line
`sourcemap` Generates a sourcemap in sourcemaps v3 format
```
### Autoprefixer
Even if you don't use task runners or bundlers, you can turn on [PostCSS/Autoprefixer](https://github.com/postcss/autoprefixer):
```js
app.use("/css", expressStylus(__dirname + "/stylus-css", {
autoprefixer: true
}));
```
By default browsers option is set to `last 2 versions`. You can modify it:
```js
app.use("/css", expressStylus(__dirname + "/stylus-css", {
autoprefixer: { browsers: ['Firefox > 20']}
}));
```
You can set all [Autoprefixer options](https://github.com/postcss/autoprefixer#options) in the same way.
### Usage with express.static
You have to use `express-stylus-middleware` before `express.static`
```js
app.use('/css', expressStylus(__dirname + '/stylus-css'));
app.use(express.static('public'));
```
## Testing
```bash
npm test
```
## Licence
MIT
<file_sep>'use strict';
var express = require('express'),
request = require('supertest'),
stylus = require('../');
function finishSpec(done) {
return function (err, res) {
if (err) {
done.fail(err);
} else {
done();
}
}
}
describe('Express-stylus middleware', function() {
beforeEach(function() {
this.app = express();
this.app.use(stylus(__dirname + '/fixtures'));
});
it('should return valid CSS', function(done) {
request(this.app)
.get('/valid.css')
.expect(200)
.expect('Content-Type', /css/)
.expect(/color: #dc143c/)
.end(finishSpec(done));
});
it('should return valid CSS with autoprefix', function(done) {
this.app = express();
this.app.use(stylus(__dirname + '/fixtures', { autoprefixer: true }));
request(this.app)
.get('/valid.css')
.expect(200)
.expect('Content-Type', /css/)
.expect(/display: -ms-flexbox/)
.end(finishSpec(done));
});
it('should respond with 404 if file not found', function(done) {
request(this.app)
.get('/another.css')
.expect(404)
.end(finishSpec(done));
});
it('should respond with 500 if file is invalid', function(done) {
request(this.app)
.get('/invalid.css')
.expect(500)
.end(finishSpec(done));
});
it('should ignore methods except GET and HEAD', function(done) {
request(this.app)
.post('/valid.css')
.expect(404)
.end(finishSpec(done));
})
it('should work with cache', function (done) {
this.app = express();
this.app.use(stylus(__dirname + '/fixtures', { cache: true }));
request(this.app)
.get('/valid.css')
.expect(200)
.expect('Content-Type', /css/)
.end(finishSpec(done));
})
});
<file_sep>/*
* Express Stylus middleware
*
* Copyright (c) 2017 <NAME>
*
* This middleware is Stylus-version of Andrew A. Usenok's
* Express-less module (https://github.com/toogle/express-less)
*/
'use strict';
var fs = require('fs'),
url = require('url'),
path = require('path'),
stylus = require('stylus'),
autoprefixer = require('autoprefixer-stylus');
var cache = {};
module.exports = function(root, options) {
options = options || {};
root = root || __dirname + '/stylus';
return function(req, res, next) {
if (req.method != 'GET' && req.method != 'HEAD') {
return next();
}
var pathname = url.parse(req.url).pathname;
if (path.extname(pathname) != '.css') {
return next();
}
var src = path.join(
root,
path.dirname(pathname),
path.basename(pathname, '.css') + '.styl'
);
// Restore from cache
if (options.cache && cache[src]) {
res.set('Content-Type', 'text/css');
res.send(cache[src]);
return;
}
fs.readFile(src, function(err, data) {
if (err) return next();
var opts = {};
for (var key in options) {
if (options.hasOwnProperty(key)) {
opts[key] = options[key];
}
}
opts.paths = [
path.join(
root,
path.dirname(pathname)
)
];
opts.filename = path.basename(src);
if (options.autoprefixer){
if (typeof options.autoprefixer === "boolean"){
opts.use = [autoprefixer('last 2 versions')];
} else {
opts.use = [autoprefixer(options.autoprefixer)];
}
}
stylus.render(data.toString('utf8'), opts, function(err, css) {
if (err) {
return res.sendStatus(500);
}
// Store in cache
if (options.cache) {
cache[src] = css;
}
res.set('Content-Type', 'text/css');
res.send(css);
});
});
};
};
<file_sep>module.exports = require('./lib/express-stylus-middleware');
|
9ac924a47968c84fe8a4f940d79da41aa2ef05c9
|
[
"Markdown",
"JavaScript"
] | 4
|
Markdown
|
rodynenko/express-stylus-middleware
|
cd5be5e5e69cf925e26169c5e0b883e26e58b5fd
|
bfd5aca9ae9c833332932bb59b94bcd4003c4fdc
|
refs/heads/master
|
<repo_name>RupinderRoop/QuickChat<file_sep>/Crypto.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ChatApplication
{
class Crypto
{
public static string Encrypt(string orignal,string key)
{
using (MD5CryptoServiceProvider mdHash = new MD5CryptoServiceProvider())
{
byte[] text = UTF8Encoding.UTF8.GetBytes(orignal);
byte[] keyArray = mdHash.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider();
tds.Key = keyArray;
tds.Mode = CipherMode.ECB;
tds.Padding = PaddingMode.PKCS7;
ICryptoTransform transform = tds.CreateEncryptor();
byte[] result = transform.TransformFinalBlock(text, 0, text.Length);
string endResult = Convert.ToBase64String(result);
return endResult.ToString();
}
}
public static string Decrypt(string encText, string key)
{
using (MD5CryptoServiceProvider mdhash = new MD5CryptoServiceProvider())
{
encText = encText.Replace("\0",null);
byte[] encBytes = Convert.FromBase64String(encText);
byte[] keyArray = mdhash.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider();
tds.Key = keyArray;
tds.Mode = CipherMode.ECB;
tds.Padding = PaddingMode.PKCS7;
ICryptoTransform transform = tds.CreateDecryptor();
byte[] result = transform.TransformFinalBlock(encBytes, 0, encBytes.Length);
string orignal = UTF8Encoding.UTF8.GetString(result);
return orignal;
}
}
}
}
<file_sep>/Name.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ChatApplication
{
public partial class Name : Form
{
public Name()
{
InitializeComponent();
}
private void EnterButton_Click(object sender, EventArgs e)
{
if(NameTextBox.Text == String.Empty)
{
MessageBox.Show("Enter your name", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
MainWindow mWindow = new MainWindow();
Data.Name = NameTextBox.Text.ToString();
mWindow.Show();
this.Hide();
}
}
}
<file_sep>/README.md
# QuickChat
QuickChat is a chat application for Local Area Network written using c# and WinForm. It utilizes the TCP Socket class for communication
protocols.
```
The messages are also encrypted using System.Security.Cryptography in c#.
```
<file_sep>/MainWindow.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace ChatApplication
{
public partial class MainWindow : Form
{
Socket mySocket;
EndPoint epLocal, epRemote;
byte[] buffer;
public MainWindow()
{
InitializeComponent();
}
private void MainWindow_Load(object sender, EventArgs e)
{
TextBox.CheckForIllegalCrossThreadCalls = false;
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
mySocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
MyIPTextBox.Text = GetIPAddress();
RemoteIPTextBox.Text = GetIPAddress();
UserGroupBox.Text = Data.Name;
}
private void ConnectButton_Click(object sender, EventArgs e)
{
if(MyPortTextBox.Text == String.Empty && RemotePortTextBox.Text ==String.Empty)
{
MessageBox.Show("Some Fields are missing for creating Connection","Warning",MessageBoxButtons.OK,MessageBoxIcon.Warning);
return;
}
epLocal = new IPEndPoint(IPAddress.Parse(MyIPTextBox.Text),Convert.ToInt32(MyPortTextBox.Text));
mySocket.Bind(epLocal);
epRemote = new IPEndPoint(IPAddress.Parse(RemoteIPTextBox.Text), Convert.ToInt32(RemotePortTextBox.Text));
mySocket.Connect(epRemote);
buffer = new byte[1500];
mySocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(GetMessages), buffer);
ConnectButton.Text = "Connected";
ConnectButton.Enabled = false;
}
private void GetMessages(IAsyncResult asyncResult)
{
TextBox.CheckForIllegalCrossThreadCalls = false;
try
{
byte[] RecivedData = new byte[Data.DataLength];
RecivedData = (byte[])asyncResult.AsyncState;
ASCIIEncoding aEncoding = new ASCIIEncoding();
string RecivedMessage = aEncoding.GetString(RecivedData);
string decMessage = Crypto.Decrypt(RecivedMessage, "123");
MessageListBox.Items.Add(decMessage);
buffer = new byte[1500];
mySocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(GetMessages), buffer);
}
catch (Exception ex)
{
MessageBox.Show("Error Occured", ex.Message);
}
}
private void SendButton_Click(object sender, EventArgs e)
{
if (KeyTextBox.Text == String.Empty)
{
MessageBox.Show("Key is Required", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
try
{
string message = Crypto.Encrypt(UserGroupBox.Text + ": " + MessageTextBox.Text, KeyTextBox.Text);
byte[] messageToSend = new byte[ASCIIEncoding.ASCII.GetByteCount(message)];
ASCIIEncoding encoding = new ASCIIEncoding();
messageToSend = encoding.GetBytes(message);
mySocket.Send(messageToSend);
MessageListBox.Items.Add(UserGroupBox.Text + ": " + MessageTextBox.Text);
MessageTextBox.Text = null;
}
catch(Exception ex)
{
MessageBox.Show("Error Occured", ex.Message);
}
}
private void reloadToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Restart();
}
private string GetIPAddress()
{
IPHostEntry hostEntry;
hostEntry = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress address in hostEntry.AddressList)
if (address.AddressFamily == AddressFamily.InterNetwork)
return address.ToString();
return "127.0.0.1";
}
}
}
|
bd103873e6539b8fd551bb1857bd14c6d70cf149
|
[
"Markdown",
"C#"
] | 4
|
C#
|
RupinderRoop/QuickChat
|
8e8b92d7edb7a0e56bf0173533b99d699b4c817d
|
ce347daf6f07ee0f5b78bf34779d09782aff666c
|
refs/heads/main
|
<repo_name>luizphilippe/Cursonode<file_sep>/CursoNode/index.js
const express = require('express');
const app = express();
app.get("/", function(req,res){
res.send("Seja bem vindo ao index!")
});
app.get("/teste", function(req,res){
var requesteste = require("./teste");
res.sendFile(teste.js)
module.exports = teste;
});
app.get("/blog", function(req,res){
res.send("Bem vindo ao blog");
});
app.get("/ola/:cargo/:nome", function(req,res){
res.send(req.params);
});
app.listen(8081,function()
{
console.log("Servidor rodando na url http://localhost:8081")
});//localhost:8081
<file_sep>/CursoNode/http.js
var http = require('http')
http.createServer(function(req,res){
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end("Olá");
}).listen(8081);
console.log("Serve Started!")<file_sep>/CursoNode/teste.js
var somar = require("./soma");
var sub = require("./sub");
var multi = require("./multi");
var div = require("./div")
console.log(somar(2,4))
//console.log(sub(2,4))
//console.log(div(2,4))
//console.log(multi(10,2))
module.require = somar;
|
8cff590971723c3c8542a92a6b1e0d8668050ac8
|
[
"JavaScript"
] | 3
|
JavaScript
|
luizphilippe/Cursonode
|
b55b7f6f35e65b8dc86bba947f09996ce4be6e50
|
4eee16da784977a3978d15c9472efb404cca212b
|
refs/heads/master
|
<repo_name>prishnil/JavaScriptLabs<file_sep>/DrawTriangleTutorial1.js
const offsetMaker = function(offLen) {
let space = "";
offLen = offLen * 3;
for (var x = offLen; x > 0; x --) {
space = space + " ";
}
return space;
}
const triangleMaker = function triangleMake (offset, length) {
let freeSpace = offsetMaker (offset --);
let tri = "";
for (var y = 0; y < length; y++) {
let freeSpace = offsetMaker(offset --);
tri = tri + freeSpace;
for (var z = 0; z < ((y * 2) + 1); z++) {
tri = tri + " * ";
}
tri = tri + "\n";
}
return tri;
}
console.log (triangleMaker(20, 10));<file_sep>/Tutorial2.js
//Task 1: Reassigning Functions to Different Binding Names
let printHello = function(name) {
let hello = "Hello ";
return (hello + name);
};
console.log(printHello("Prishni"));
let printGreeting = printHello;
console.log(printGreeting("Prishni"));
//Task 2: Passing Functions as Arguments to Other Functions
let printVertical = function(word) {
for (let i = 0; i < word.length; i++) {
console.log (word[i]);
};
};
printVertical('Prishni');
let printWithSpaces = function(word) {
let finalWord = "";
for (let i = 0; i < word.length; i++) {
finalWord += (word[i] + " ");
};
console.log(finalWord);
};
printWithSpaces("Prishni");
let printInReverse = function (word) {
let finalWord = "";
for (let i = word.length - 1; i >= 0 ; i--) {
finalWord += (word[i]);
};
console.log (finalWord);
};
printInReverse("Prishni");
let genericPrinter = function (number,word) {
switch (number) {
case 1: printVertical(word);
break;
case 2: printWithSpaces(word);
break;
case 3: printInReverse(word);
break;
default:
break;
}
};
genericPrinter(1, "Prishni");
genericPrinter(2, "Prishni");
genericPrinter(3, "Prishni");
//Task 3: Returning Functions From Other Function;
let calendarName = function (letter) {
let monthName = function (monthNum) {
let monthArray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
let nameOfTheMonth = monthArray[monthNum];
return nameOfTheMonth;
};
let dayName = function (dayNum) {
let dayArray = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
let nameOfTheDay = dayArray[dayNum];
return nameOfTheDay;
};
if (letter === "m") {
return monthName;
};
if (letter === "d") {
return dayName;
};
};
let findNameOfTheDay = calendarName ('d');
console.log (findNameOfTheDay (2));
let findNameOfTheMonth = calendarName ('m');
console.log (findNameOfTheMonth(8));
//Task 4: Closures
let powerOf = function(power) {
let raiseToPower = function (base) {
let result = 1;
for (let i = 1; i <= power; i++) {
result *= base;
};
return result;
};
return raiseToPower;
};
let powerOfTwo = powerOf (2);
console.log(powerOfTwo(5));
let powerOfThree = powerOf (3);
console.log(powerOfThree(5));
let powerOfFour = powerOf(4);
console.log(powerOfFour(5));
<file_sep>/Tutorial9.js
//Task 1
(function () {
//array of grades
let arrayOfGrades = [22,34,55,98,30,44];
//function that calculates the average grade
function average() {
let n = 0, average;
for (let i = 0; i < arrayOfGrades.length; i++) {
n += arrayOfGrades[i];
}
average = n / arrayOfGrades.length;
return average;
}
//function that finds the maximum grade
function maximum() {
let temp = arrayOfGrades[0], maximum;
for (let i = 0; i < arrayOfGrades.length - 1; i++) {
temp = (temp > arrayOfGrades[i +1]) ? temp : temp = arrayOfGrades[i + 1];
}
maximum = temp;
return maximum;
}
//using console.log statements of both functions that will print when the IIFE is called
console.log(average());
console.log(maximum());
})();
//Task 2
//create a new object, gradeObject and assign what returns from the IIFE to it
let gradeObject = (function () {
//an array of grades
let arrayOfGrades = [22,34,55,98,30,44];
//function that calculates the average grade
function average() {
let n = 0;
let average;
for (let i = 0; i < arrayOfGrades.length; i++) {
n += arrayOfGrades[i];
}
average = n / arrayOfGrades.length;
return average;
}
//function that finds the maximum grade
function maximum() {
let temp = arrayOfGrades[0];
let maximum;
for (let i = 0; i < arrayOfGrades.length - 1; i++) {
temp = (temp > arrayOfGrades[i +1]) ? temp : temp = arrayOfGrades[i + 1];
}
maximum = temp;
return maximum;
}
//create an object that will have grade properties
let properties;
properties = {
//function referring to the average function
average: average(),
//function referring to the maximum function
maximum: maximum(),
};
//return the object, properties whenever the IIFE is called
return properties;
})();
//calling the maximum and average functions from outside the IIFE, and printing the output using console.log to see the results
console.log(gradeObject.average);
console.log(gradeObject.maximum);
//Task 3
//create another object, gradeObjWithMutators and assign what returns from the IIFE to it
let gradeObjWithMutators = (function () {
//an array of grades
let arrayOfGrades = [22,34,55,98,30,44];
//function that calculates the average grade
function average() {
let n = 0;
let average;
for (let i = 0; i < arrayOfGrades.length; i++) {
n += arrayOfGrades[i];
}
average = n / arrayOfGrades.length;
return average;
}
//function that finds the maximum grade
function maximum() {
let temp = arrayOfGrades[0];
let maximum;
for (let i = 0; i < arrayOfGrades.length - 1; i++) {
temp = (temp > arrayOfGrades[i +1]) ? temp : temp = arrayOfGrades[i + 1];
}
maximum = temp;
return maximum;
}
//create an object that will have grade properties
let properties;
properties = {
//function property that refers to the average function
average: average(),
//function property that refers to the maximum function
maximum: maximum(),
//getter method that returns the arrayOfGrades array
getArrayOfGrades: () => {
return arrayOfGrades
},
//setter method that can set the arrayOfGrades array
setArrayOfGrades: (gA) => {
arrayOfGrades = gA;
}
};
//return the object, properties whenever the IIFE is called
return properties;
})();
//calling the getter method and printing the return using console.log
console.log(gradeObjWithMutators.getArrayOfGrades());
//calling the setter method and sending it a new array of numbers
gradeObjWithMutators.setArrayOfGrades([45,56,72,84,66,99]);
//calling the getter method again to see the effect of calling the setter
<file_sep>/Tutorial6.js
//***************
//Task 1
//***************
class Shape {
constructor(newX, newY) {
//x and y are the private members of the shape class
let x;
let y;
this.setX = function(x) {
//to avoid assignment x coordinate to a negative number
this.x = (x > 0) ? x : 0;
};
this.getX = function() {
return this.x;
};
this.setY = function(y) {
this.y = (y > 0) ? y : 0;
};
this.getY = function () {
return this.y;
};
// pass the x and y coordinates to the private members using the methods
this.setX(newX);
this.setY(newY);
}
showPoint() {
console.log(this.getX() + ", " + this.getY());
}
//the offset for the shapes
createHorizontalOffset(offset) {
if (offset === 'undefined') {
offset = this.getX();
}
let offsetString = "";
for(let i = 1; i <= offset; i++) {
offsetString += " ";
}
return offsetString;
}
//the draw method for shapes
draw () {
let drawS = "";
for (let i = 1; i <= this.getY(); i++) {
drawS += "\n";
}
return drawS;
}
}
//test the shape class
let s = new Shape(3, 6);
s.showPoint();
//if we want to change the values of x and y
s.setX(-5);
s.setY(8);
//test the values of x and y
console.log("The new x value is: " + s.getX() + ", and the new y value is: " + s.getY());
//check if we can access the private members
console.log(s.x);
console.log(s.y);
//***************
//Task 2
//***************
//subclass square that extends from shape
class Square extends Shape {
constructor(squareX, squareY, length) {
super(squareX, squareY);
this.setLength = function (length) {
this.length = (length > 0) ? length : 1; //avoid negative number
};
this.getLength = function () {
return this.length;
};
this.setLength(length);
}
//draw method for the square
draw() {
let squ = super.draw();
for (let a = 1; a <= this.getLength(); a++) {
squ += "\n";
squ += super.createHorizontalOffset(this.getX());
for (let b = 1; b <= this.length; b++) {
squ += "* ";
}
}
console.log(squ);
}
}
//subclass triangle that extends from shape
class Triangle extends Shape {
constructor(triangleX, triangleY, height) {
super(triangleX, triangleY);
this.setHeight = function (height) {
this.height = (height > 0) ? height : 1; // avoid negative number
};
this.getHeight = function () {
return this.height;
};
this.setHeight(height);
}
//draw method for the triangle
draw () {
let tri = super.draw();
for (let a = 1; a <= this.getHeight(); a++) {
tri += "\n";
tri += super.createHorizontalOffset(this.getX() + this.getHeight() - a);
for (let b = 1; b <= (a * 2) - 1; b++) {
tri += "*";
}
}
console.log(tri);
}
}
//***************
//Task 3
//***************
//create a square object and draw it
let theSquare = new Square(2,2,4);
theSquare.draw();
//create a triangle object and draw it
let theTriangle = new Triangle(4,4,8);
theTriangle.draw();<file_sep>/Tutorial8.js
//***************
//Task 1
//***************
class Shape {
constructor(newA, newB) {
//a and b are private members of shape class
let a;
let b;
//setter method for a
this.setA = function(a) {
//avoid negative number assignment to a coordinate
this.a = (a > 0) ? a : 0;
};
//getter method for a
this.getA = function() {
return this.a;
};
//setter method for b
this.setB = function(b) {
this.b = (b > 0) ? b : 0;
};
//getter method for b
this.getB = function () {
return this.b;
};
//pass a and b to private members using the setter methods
this.setA(newA);
this.setB(newB);
}
showPoint() {
console.log(this.getA() + ", " + this.getB());
}
//method to create horizontal offset
createHorizontalOff_set(off_set) {
//if undefined
if (off_set === 'undefined') {
off_set = this.getA();
}
let off_setString = "";
//for loop to create off set
for(let i = 1; i <= off_set; i++) {
off_setString += " ";
}
return off_setString;
}
//the draw method
draw () {
let drawString = "";
//for loop that creates vertical off_set
for (let i = 1; i <= this.getB(); i++) {
drawString += "\n";
}
return drawString;
}
//method that is used to display the info of the shape
displayInfo() {
return "Shape with main points: " + this.getA() + ", " + this.getB();
}
}
//subclass called Square
class Square extends Shape {
//constructor method that also calls the constructor for the shape class using keyword super
constructor(a1, b1, length) {
super(a1, b1);
this.setLength = function (length) {
//condition for length to be greater than 0
// if not --- assign a value of 1
this.length = (length > 0) ? length : 1;
};
//getter method for square class
this.getLength = function () {
return this.length;
};
//setter method for square class
this.setLength(length);
}
//override the draw method from the shape class
draw () {
let square_shape = super.draw();
//for loop that draws the square
// uses the horizontal offset method from the super class
for (let i = 1; i <= this.getLength(); i++) {
square_shape += "\n";
square_shape += super.createHorizontalOff_set(this.getA());
for (let j = 1; j <= this.length; j++) {
square_shape += "* ";
}
}
console.log(square_shape);
}
//override the displayInfo method for square subclass
displayInfo() {
return "Square " + super.displayInfo();
}
}
//csubclass called triangle
class Triangle extends Shape {
//constructor method that also calls the constructor for the shape class using super keyword
constructor(a2, b2, height) {
super(a2, b2);
this.setHeight = function (height) {
//condition for height to be greater than 0
// if not --- assign a value of 1
this.height = (height > 0) ? height : 1;
};
//getter method for triangle class
this.getHeight = function () {
return this.height;
};
//setter method for triangle class
this.setHeight(height);
}
//override the draw method from the shape class
draw () {
let triangle_shape = super.draw();
//for loop that draws the triangle
// uses the horizontal offset method from the super class
for (let i = 1; i <= this.getHeight(); i++) {
triangle_shape += "\n";
triangle_shape += super.createHorizontalOff_set(this.getA() + this.getHeight() - i);
for (let j = 1; j <= (i * 2) - 1; j++) {
triangle_shape += "*";
}
}
console.log(triangle_shape);
}
//override the displayInfo method for triangle subclass
displayInfo() {
return "Triangle " + super.displayInfo();
}
}
//***************
//Task 2
//***************
//create an array called plainObjects
let plain_Objects = [
{a:5,b:6},
{type:'Square', a:7, b:10, length:10},
{a:8, b:9, type:'Triangle', height:50},
];
//create a function called plainObjectsToShapes
// it will create a new shape based on the properties from plainObjects and is then activated in the switch statement,
//finally, it is pushed into the array called arrayOfShapes
let plain_Objects_To_Shapes = function(data) {
let array_Of_Shapes = [];
let s;
for(let d of data) {
switch(d.type) {
case undefined:
s = new Shape(d.a, d.b);
break;
case "Square":
s = new Square(d.a, d.b, d.length);
break;
case "Triangle":
s = new Triangle(d.a, d.b, d.height);
}
array_Of_Shapes.push(s);
}
//after each iteration, the shape "s" will be pushed into the list arrayOfShapes
return array_Of_Shapes;
};
//create result list of shapes, by passing the array plainObjects into the function plainObjectsToShapes
let result = plain_Objects_To_Shapes(plain_Objects);
//display the info in the result array using the displayInfo method
for(let r of result) {
console.log(r.displayInfo());
}
//***************
//Task 3
//***************
//create result list of shapes using map method instead of plainObjectsToShapes function
result = plain_Objects.map(object => (object.type === undefined) ? new Shape(object.a, object.b):
(object.type === 'Square') ? new Square(object.a, object.y, object.length): new Triangle(object.a, object.b, object.height));
//display the info in the result array using the displayInfo method
for(let r of result) {
console.log(r.displayInfo());
}
//create shape object and draw it using draw method
let final_Shape = new Shape(5,10);
final_Shape.draw();
//create square object and draw it using draw method
let final_Square = new Square(10, 20, 30);
final_Square.draw();
//create triangle object and draw it using draw method
let final_Triangle = new Triangle(20,30,20);
final_Triangle.draw();<file_sep>/Tutorial4.js
//************************************************************************
//Task 1: Applying filter, map, and reduce function on arrays of numbers
//************************************************************************
//1 - declaring the array
let distance = [134, 6, 7, 83, 9, 1, 0, 9, 6, 17, 54, 16];
//2a - creating the long filter function for filtering elements of distance
//Create a function for checking the range between 5 and 10
let checkFunctionLong = function(distance) {
//setting the criteria to be the range between 5 and 10
return distance > 5 && distance < 10;
};
//set checkRangeLong to be the filtered distance array
let checkRangeLong = distance.filter(checkFunctionLong);
//print to console
console.log(checkRangeLong);
//2b - creating the short filter function for filtering elements of distance
//Create a function for checking the range between 5 and 10 and setting the criteria to be the range between 5 and 10
let checkFunctionShort = (distance) => { return distance > 5 && distance < 10;};
//set checkRangeShort to be the filtered distance array
let checkRangeShort = distance.filter(checkFunctionShort);
//print to console
console.log(checkRangeShort);
//3a - creating the long map function to change the meters into inches
//Create a function to change all the elements of the array to inches from meters
let transformFunctionLong = function(distance) {
//setting the transformation required to convert to inches
return distance * 39.37;
};
//set transformLong to be the filtered array in inches
let transformLong = checkRangeLong.map(transformFunctionLong);
//print to console
console.log(transformLong);
//3b - creating the short map function to change the meters into inches
//Create a function to change all the elements of the array to inches from meters
let transformFunctionShort = (distance) => { return distance * 39.37};
//set transformShort to be the filtered array in inches
let transformShort = checkRangeShort.map(transformFunctionShort);
//printing the new array
console.log(transformShort);
//4a - creating the long reduce function to find the minimum distance
//Create a function to find the minimum element
let combineFunctionLong = function (acc, val) {
//checking if acc smaller than val
if (acc < val) {
//return acc
return acc;
}
//what to do if acc is greater than val
else {
//return val
return val;
}};
//set combineLong to be the minimum value of the array in inches that is in range 5-20
let combineLong = transformLong.reduce(combineFunctionLong);
//printing the minimum distance
console.log(combineLong);
//4b - creating the short reduce function to find the minimum distance
//Create a function to find the minimum element
let combineFunctionShort = (acc,val) => {
//checking if acc smaller than val
if (acc < val) {
//return accs
return acc;
}
//what to do if acc is not greater than val
else {
//return val
return val;
}};
//set combineShort to be the minimum value of the array in inches that is in range 5-20
let combineShort = transformShort.reduce(combineFunctionShort);
//printing the minimum distance in inches
console.log(combineShort);
//5 - Solving the problem in one line
console.log(distance.filter(checkFunctionLong).map(transformFunctionLong).reduce(combineFunctionLong));
//************************************************************************
//Task 2: Applying filter, map, and reduce function on arrays of objects
//************************************************************************
//declaring the coordinates
let coordinates = [{x:5, y:6}, {x:3, y:7}, {x:8, y:0}, {x:9, y:10}, {x:15, y:4}, {x:0, y:15}];
//create a function to remove the points that lie on the axes
let newCoordinates = function(coordinates) {
//set the condition and return it
return coordinates.x !== 0 && coordinates.y !== 0;
};
//print out the array with no points on the axes
console.log(coordinates.filter(newCoordinates));
//create a function to compute the distance of each point to the origin
let coordinateDistances = function(newCoordinates) {
//computing the math to find the distances
return Math.sqrt((Math.pow(newCoordinates.x, 2)) + Math.pow(newCoordinates.y, 2));
};
//print the distances between each point and the origin to the console
console.log(coordinates.filter(newCoordinates).map(coordinateDistances));
//create a function to find the maximum distance between the origin and the point
let maximumDistance = function (acc, val) {
//checking if acc greater than val
if (acc > val) {
//return acc
return acc;
}
//what to do if acc is not greater than val
else {
//return val
return val;
}};
//print the final result of the maximum distance using a chain of filter, map and reduce
//this uses the filter method to remove the coordinates on the axes
//it then uses the map method to compute all the distance
//finally it uses the reduce method to find the maximum distance
console.log("The maximum distance using the function method is " + coordinates.filter(newCoordinates).map(coordinateDistances).reduce(maximumDistance));
//Using arrow method
////create a function to remove the points that lie on the axes using arrow method
let newCoordinatesArrow = (coordinates) => {
//set the condition and return it
return coordinates.x !== 0 && coordinates.y !== 0;
};
//create a function to compute the distance of each point to the origin using arrow method
let coordinateDistancesArrow = (newCoordinates) => {
//computing the math to find the distances
return Math.sqrt((Math.pow(newCoordinates.x, 2)) + Math.pow(newCoordinates.y, 2));
};
//create a function to find the maximum distance between the origin and the point using arrow method
let maximumDistanceArrow = (acc, val) => {
//checking if acc greater than val
if (acc > val) {
//return acc
return acc;
}
//what to do if acc is not greater than val
else {
//return val
return val;
}};
//print the final result of the maximum distance using a chain of filter, map and reduce with the arrow functions
//this uses the filter method using arrow method to remove the coordinates on the axes
//it then uses the map method using arrow method to compute all the distance
//finally it uses the reduce method using arrow method to find the maximum distance
console.log("The maximum distance using the arrow method is " + coordinates.filter(newCoordinatesArrow).map(coordinateDistancesArrow).reduce(maximumDistanceArrow));
|
540c13714b45bcaeb326580e9e443e6fffdc820f
|
[
"JavaScript"
] | 6
|
JavaScript
|
prishnil/JavaScriptLabs
|
342c205ef5bf0c0b35923548bf16fb5b467b99cb
|
a5b6ca7ca3c7b01c796caa1e44a7caebc0e07a0e
|
refs/heads/main
|
<file_sep>import { renderHook, act } from '@testing-library/react-hooks'
import { usePagination } from '../../hooks'
describe('usePagination hook', () => {
const PAGES = 3
test('hooks creates correctly with default values', () => {
const { result } = renderHook(() => usePagination({ nPages: PAGES }))
expect(result.current.nPages).toBe(PAGES)
expect(result.current.currentPage).toBe(0)
})
test('hooks creates correctly with custom start page', () => {
const { result } = renderHook(() =>
usePagination({ nPages: PAGES, startPage: 2 })
)
expect(result.current.nPages).toBe(PAGES)
expect(result.current.currentPage).toBe(2)
})
test('hooks creates correctly with overflowed start page', () => {
const { result } = renderHook(() =>
usePagination({ nPages: PAGES, startPage: 25 })
)
expect(result.current.nPages).toBe(PAGES)
expect(result.current.currentPage).toBe(0)
})
test('calling nextPage should increment currentPage', () => {
const { result } = renderHook(() => usePagination({ nPages: 3 }))
act(() => {
result.current.nextPage()
})
expect(result.current.currentPage).toBe(1)
})
test('calling previousPage should decrement currentPage', () => {
const { result } = renderHook(() =>
usePagination({ nPages: 3, startPage: 2 })
)
act(() => {
result.current.previousPage()
})
expect(result.current.currentPage).toBe(1)
})
test("calling previousPage don't decrement currentPage if currentPage == 0", () => {
const { result } = renderHook(() => usePagination({ nPages: 3 }))
act(() => {
result.current.previousPage()
})
expect(result.current.currentPage).toBe(0)
})
test("calling nextPage don't increment currentPage if currentPage == nPages - 1", () => {
const { result } = renderHook(() =>
usePagination({ nPages: 3, startPage: 2 })
)
act(() => {
result.current.nextPage()
})
expect(result.current.currentPage).toBe(2)
})
})
<file_sep>export type ImgBlock = {
title: string;
images: string[];
};
<file_sep># NextJS Carousel
A Carousel React component in a Next JS App.
## Preview
Preview the example live on [Vercel](http://nextjs-carousel.vercel.app/):
## How to run
Install the app with npm `npm install` or yarn `yarn`
Execute the app in dev mode:
```bash
yarn dev
# or
npm run dev
```
Execute tests:
```bash
yarn test
# or
npm run tests
```
## Usage
```js
<Carousel
nSlides={4}
imgBlocks={[
{
title: 'Block 1',
images: [
'https://picsum.photos/1305',
'https://picsum.photos/1306',
'https://picsum.photos/1307',
'https://picsum.photos/1308',
],
},
]}
imgSize={200}
wrapperStyle={{ marginBottom: 24 }}
width={300}
/>
```
## Component Properties
- `nSlides` Number of Carousel slides
- `imgBlocks` Array of `ImageBlock` objects. For each object it will render an image in each slide
- `imgSize` Size of the images (they are square for now)
- `wrapperStyle` Style object for wrapper container (optional)
- `width` Width of the Slider. By default, it is [`nBlocks * imgSize`]
##### LICENSE: [MIT](/LICENSE)
[nextjs-carousel]: https://github.com/Kataclan/nextjs-carousel
<file_sep>export const mockImageBlocks = [
{
title: 'First Block',
images: [
'https://picsum.photos/1301',
'https://picsum.photos/1302',
'https://picsum.photos/1303',
'https://picsum.photos/1304',
],
},
{
title: 'Second Block',
images: [
'https://picsum.photos/1305',
'https://picsum.photos/1306',
'https://picsum.photos/1307',
'https://picsum.photos/1308',
],
},
{
title: 'Third Block',
images: [
'https://picsum.photos/1309',
'https://picsum.photos/1310',
'https://picsum.photos/1311',
'https://picsum.photos/1312',
],
},
{
title: 'Fourth Block',
images: [
'https://picsum.photos/1313',
'https://picsum.photos/1314',
'https://picsum.photos/1315',
'https://picsum.photos/1316',
],
},
]
export const mockImageSrc = [
'https://picsum.photos/1',
'https://picsum.photos/2',
'https://picsum.photos/3',
'https://picsum.photos/4',
]
export const mockImgSize = 300
export const mockNSlides = 4
export const mockSlideLabels = [
'carousel-slide-0',
'carousel-slide-1',
'carousel-slide-2',
'carousel-slide-3',
]
export const mockImageTitlesSlide1 = mockImageBlocks.map(
(block) => `Slide 1 - ${block.title}`
)
export const mockImageTitlesSlide2 = mockImageBlocks.map(
(block) => `Slide 2 - ${block.title}`
)
export const mockImageTitlesSlide3 = mockImageBlocks.map(
(block) => `Slide 3 - ${block.title}`
)
export const mockImageTitlesSlide4 = mockImageBlocks.map(
(block) => `Slide 4 - ${block.title}`
)
<file_sep>import {
render,
queries,
RenderOptions,
RenderResult,
} from '@testing-library/react'
import { ReactElement } from 'react'
const customRender = (
ui: ReactElement,
options?: Omit<RenderOptions, 'queries'>
): RenderResult => render(ui, { queries: { ...queries }, ...options })
export * from '@testing-library/react'
export { customRender as render }
<file_sep>import { useState } from 'react'
const usePagination = ({
nPages,
startPage,
}: {
nPages: number
startPage?: number
}) => {
const [currentPage, setCurrentPage] = useState(
// Check if startPage is undefined or overflowed to start from 0
typeof startPage !== 'undefined' && startPage >= 0 && startPage <= nPages
? startPage
: 0
)
const nextPage = () => {
const nextPage = currentPage + 1
if (nextPage < nPages) {
setCurrentPage(nextPage)
}
}
const previousPage = () => {
const prevPage = currentPage - 1
if (prevPage >= 0) {
setCurrentPage(prevPage)
}
}
const setPage = (page: number) => {
if (page >= 0 && page < nPages) {
setCurrentPage(page)
}
}
return {
nPages,
currentPage,
previousPage,
nextPage,
setPage,
}
}
export default usePagination
|
2bd818697eabcf6336a0436cf43952c3055a4f57
|
[
"Markdown",
"TypeScript"
] | 6
|
TypeScript
|
Kataclan/nextjs-carousel
|
68f526517ef89ae0073aea34cca50891e49532dd
|
383feacf9a62f4dd722af0649a47b6b005055fb9
|
refs/heads/master
|
<repo_name>DannBlackfish/pruebaUmvel<file_sep>/src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import * as firebase from 'firebase';
import { AdministracionService } from './servicio/administracion.service'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private administracionService: AdministracionService) { }
ngOnInit(){
firebase.initializeApp({
apiKey: "<KEY>",
authDomain: "umvelprueba.firebaseapp.com"
})
}
getAllAdministracion() {
this.administracionService.getAllAdministracion()
.subscribe(todos => {
console.log(todos);
})
}
}
<file_sep>/src/app/hedear/hedear.component.ts
import { Component, OnInit } from '@angular/core';
import { AutenticacionService } from '../servicio/autenticacion.service'
import { Router, ActivatedRoute } from '@angular/router'
@Component({
selector: 'app-hedear',
templateUrl: './hedear.component.html',
styleUrls: ['./hedear.component.css']
})
export class HedearComponent implements OnInit {
constructor(private autenticacionService: AutenticacionService,
private router: Router,
private activatedRoute: ActivatedRoute) { }
ngOnInit(): void {
}
isAuth(){
return this.autenticacionService.isAuthenticated();
}
onLogout() {
this.autenticacionService.logout();
this.router.navigate(['/'])
}
}
<file_sep>/src/app/grafica/grafica.component.ts
import { Component, OnInit } from '@angular/core';
import { GraficaService } from '../servicio/grafica.service'
import { Chart } from 'chart.js'
@Component({
selector: 'app-grafica',
templateUrl: './grafica.component.html',
styleUrls: ['./grafica.component.css']
})
export class GraficaComponent implements OnInit {
chart= []
constructor(private _grafica:GraficaService) { }
ngOnInit(): void {
this._grafica.carros()
.subscribe(res => {
const marca = res['sales'].map(res => res.car_make)
const ventas = res['sales'].map(res => res.quantity)
console.log(res)
this.chart = new Chart('canvas', {
type: 'line',
data: {
labels: marca,
datasets: [
{
label: 'Quantity',
data: ventas,
backgroundColor: [
'rgba(102, 102, 204, 0.2)'
],
borderColor: [
'rgba(102, 102, 204, 1)'
],
borderWidth: 1
},
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
})
})
}
}
<file_sep>/src/app/servicio/administracion.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Administracion } from '../interfaces/administracion';
import { environment } from 'src/environments/environment';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AdministracionService {
url:string = "https://run.mocky.io/v3/d5ddf1ff-a0e2-4a7e-bbcc-e832bef6a503"
constructor(private http: HttpClient
) { }
getAllAdministracion():Observable<Administracion[]> {
let url = this.url;
return this.http.get<Administracion[]>(url)
}
// getAdministracion(id: number) {
// return this.http.get<Administracion>(`${environment.baseUrlAPI}/${id}`)
// }
// getSystems(): Observable<System[]> {
// let url = 'http://localhost:50000/...';
// console.log(url);
// return this.http.get(url)
// .map(this.extractData);
// }
// private extractData(res: Response) {
// let body = res.json();
// console.log("extraData: ");
// if (body && body.users) {
// body=body.users;
// }
// return body || []; // devolvemos un array vacio si la respuesta no tiene un array
// }
}
<file_sep>/src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { Routes, RouterModule } from '@angular/router';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http'
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { InicioComponent } from './inicio/inicio.component';
import { HedearComponent } from './hedear/hedear.component';
import { RegistroComponent } from './autenticacion/registro/registro.component';
import { AutenticacionService } from './servicio/autenticacion.service';
import { InisesComponent } from './autenticacion/inises/inises.component';
import { AdministracionService } from './servicio/administracion.service';
import { AddadmComponent } from './administracion/addadm/addadm.component';
import { GuardService } from './servicio/guard.service'
import { GraficaService } from './servicio/grafica.service';
import { GraficaComponent } from './grafica/grafica.component'
const routes: Routes = [
{ path: '', component: InicioComponent },
// { path: '**', component: InicioComponent },
{ path: 'addadm', component: AddadmComponent, canActivate: [GuardService] },
{ path: 'registro', component: RegistroComponent},
{ path: 'inises', component: InisesComponent},
{ path: 'grafica', component: GraficaComponent, canActivate: [GuardService] }
];
@NgModule({
declarations: [
AppComponent,
InicioComponent,
HedearComponent,
RegistroComponent,
InisesComponent,
AddadmComponent,
GraficaComponent
],
imports: [
BrowserModule,
AppRoutingModule,
RouterModule.forRoot(routes),
FormsModule,
ReactiveFormsModule,
HttpClientModule
],
providers: [AutenticacionService,
AdministracionService,
GuardService,
GraficaService],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/administracion/addadm/addadm.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'
import { database } from 'firebase';
import { Administracion } from '../../interfaces/administracion'
import { AdministracionService } from '../../servicio/administracion.service'
@Component({
selector: 'app-addadm',
templateUrl: './addadm.component.html',
styleUrls: ['./addadm.component.css']
})
export class AddadmComponent implements OnInit {
administracion: any
constructor(private administracionService: AdministracionService,
private router:Router) { }
ngOnInit(): void {
this.administracionService.getAllAdministracion().subscribe(data => {
this.administracion = data
console.log(data)
})
}
}
<file_sep>/src/environments/environment.prod.ts
export const environment = {
production: true,
baseUrlAPI: 'https://run.mocky.io/v3/d5ddf1ff-a0e2-4a7e-bbcc-e832bef6a503'
};
|
f15f00b3ee39470f017b97f86b64bed23a041fb9
|
[
"TypeScript"
] | 7
|
TypeScript
|
DannBlackfish/pruebaUmvel
|
f41261a79a2e0ec059990a42823c2e2f1e749db8
|
03e8adfddeae63baebb5dfd4b8455b153d5d2eff
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace FatAntelope
{
public class XTree
{
public XmlDocument Document { get; set; }
public XNode Root { get; set; }
public XTree(XmlDocument document)
{
Document = document;
Root = XNode.Build(document.DocumentElement, null);
}
}
}
|
aff611598fdb671df0953efd2ba26254d4ba60e1
|
[
"C#"
] | 1
|
C#
|
shibayan/FatAntelope
|
3b09f0a958124ed752fd2338f6a54a25da146839
|
735a8ef449c0722cc08c306f6a49878882624ab7
|
refs/heads/master
|
<file_sep><?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "login";
$id = "";
$ucid = "";
$password = "";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($servername, $username, $password, $dbname);
}
catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[1] = $_POST['ucid'];
$posts[2] = $_POST['password'];
return $posts;
}
// Insert
if(isset($_POST['insert']))
{
$data = getPosts();
$data[2]= password_hash('$password', PASSWORD_DEFAULT);
$insert_Query = "INSERT INTO `users`(`ucid`, `password`) VALUES ('$data[1]','$data[2]')";
try{
$insert_Result = mysqli_query($connect, $insert_Query);
if($insert_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Signin Succesful';
}else{
echo 'Data Not Inserted';
}
}
} catch (Exception $ex) {
echo 'Error Insert '.$ex->getMessage();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div >
<form action="login.php" method="post">
<input type="varchar" name="ucid" placeholder="Enter your UCID"><br><br>
<input type="<PASSWORD>" name="password" placeholder="Enter your <PASSWORD>"><br><br>
<input type="submit" name="insert" value="submit">
</form>
</div>
</body>
</html><file_sep><?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "login";
$id = "";
$ucid = "";
$password = "";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($servername, $username, $password, $dbname);
}
catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[1] = $_POST['ucid'];
$posts[2] = $_POST['password'];
return $posts;
}
// Insert
if(isset($_POST['insert']))
{
$data = getPosts();
$data[2]= password_hash('$password', PASSWORD_DEFAULT);
$insert_Query = "INSERT INTO `users`(`ucid`, `password`) VALUES ('$data[1]','$data[2]')";
try{
$insert_Result = mysqli_query($connect, $insert_Query);
if($insert_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Signin Succesful';
}else{
echo 'Data Not Inserted';
}
}
} catch (Exception $ex) {
echo 'Error Insert '.$ex->getMessage();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Selectors</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='http://fonts.googleapis.com/css?family=Nunito:400,300' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/base-style.css">
<link rel="stylesheet" href="css/selectors.css">
</head>
<body>
<div id="container">
<form class="form-contact br" >
<hr>
<img class="avatar rounded"src="img/logo.png" alt="Mountains">
<form class="form-login">
<label for="username">UCID:</label>
<input class=".btn" type="text" id="username" placeholder="UCID">
<label for="password">Password:</label>
<input type="<PASSWORD>" id="password" placeholder="<PASSWORD>">
<input class="btn default" type="submit" value="Login">
<a href="forgotPassword.html" target="_blank">Forgot your password?</a>
</form>
</div>
</body>
</html>
|
148b17383acf96cdbbf6e49aa2f0efbe8dc7dcc0
|
[
"PHP"
] | 2
|
PHP
|
sirox548/CS_490.github.io
|
b258c23af50af86611f568ec48d9fd29cf701378
|
5342683949e408704874c1d2acfad3ea6d083378
|
refs/heads/main
|
<file_sep>let addsheet=document.querySelector(".plus");
let sheetlist=document.querySelector(".sheet-list");
let firstsheet=document.querySelector(".sheet");
let topRow = document.querySelector(".top-row");
let str = "";
for (let i = 0; i < 26; i++) {
str += `<div class='col'>${String.fromCharCode(65 + i)}</div>`;
}
topRow.innerHTML = str;
let leftCol = document.querySelector(".left-col");
str = ""
for (let i = 0; i < 100; i++) {
str += `<div class='left-col_box'>${i + 1}</div>`
}
leftCol.innerHTML = str;
// 2d array
let grid = document.querySelector(".grid");
str = "";
for (let i = 0; i < 100; i++) {
str += `<div class="row">`
for (let j = 0; j < 26; j++) {
str += `<div class='col' rid=${i} cid=${j} contenteditable="true"></div>`;
}
str += "</div>";
}
grid.innerHTML = str;
let Allcell=document.querySelectorAll(".grid .col");
let adressbox=document.querySelector(".adress-box");
firstsheet.addEventListener("click",handleActivesheet);
addsheet.addEventListener("click",function(){
let sheetsArr=document.querySelectorAll(".sheet");
let lastSheetele=sheetsArr[sheetsArr.length-1];
let idx=lastSheetele.getAttribute("sheetIdx");
idx=Number(idx);
let Newsheet=document.createElement("div");
Newsheet.setAttribute("class","sheet");
Newsheet.setAttribute("sheetIdx",idx+1);
Newsheet.innerText=`sheet ${idx+2}`;
sheetlist.appendChild(Newsheet);
Newsheet.addEventListener("click",handleActivesheet)
})
function handleActivesheet(e){
let mysheet=e.currentTarget;
let sheetArr=document.querySelectorAll(".sheet");
sheetArr.forEach(function (sheet){
sheet.classList.remove("active-state");
})
if(!mysheet.classList[1]){
mysheet.classList.add("active-state");
}
}
console.log(Allcell.length);
for(let i=0;i<Allcell.length;i++)
{
Allcell[i].addEventListener("click",function Handlecell(){
let rid=Number(Allcell[i].getAttribute("rid"));
let cid=Number(Allcell[i].getAttribute("cid"));
let rowadrs=rid+1;
let coladrs=String.fromCharCode(cid+65);
let adress=coladrs+rowadrs;
adressbox.value=adress;
});
}
let leftbtn=document.querySelector(".left");
let centrebtn=document.querySelector(".centre");
let rightbtn=document.querySelector(".right");
leftbtn.addEventListener("click",function(){
let adress=adressbox.value;
let{rid,cid}=getridcidfromAdress(adress);
console.log(rid,cid);
let cell=document.querySelector(`.col[rid="${rid}"][cid="${cid}"]`);
cell.style.textAlign="left";
});
centrebtn.addEventListener("click",function(){
let adress=adressbox.value;
let{rid,cid}=getridcidfromAdress(adress);
console.log(rid,cid);
let cell=document.querySelector(`.col[rid="${rid}"][cid="${cid}"]`);
cell.style.textAlign="center";
});
rightbtn.addEventListener("click",function(){
let adress=adressbox.value;
let{rid,cid}=getridcidfromAdress(adress);
console.log(rid,cid);
let cell=document.querySelector(`.col[rid="${rid}"][cid="${cid}"]`);
cell.style.textAlign="right";
});
let color1=document.querySelector(".color.txt1");
color1.addEventListener("click",function(){
let adress=adressbox.value;
let{rid,cid}=getridcidfromAdress(adress);
let cell=document.querySelector(`.col[rid="${rid}"][cid="${cid}"]`);
cell.style.color=color1.value;
})
let color2=document.querySelector(".color.txt2");
color2.addEventListener("click",function(){
let adress=adressbox.value;
let{rid,cid}=getridcidfromAdress(adress);
let cell=document.querySelector(`.col[rid="${rid}"][cid="${cid}"]`);
cell.style.color=color2.value;
})
function getridcidfromAdress(adress){
let cidcch=Number(adress.charCodeAt(0));
let cid=cidcch-65;
let rid=Number(adress.slice(1))-1;
return{rid,cid};
}
let bolt=document.getElementById("bolt");
bolt.addEventListener("click",function(){
let adress=adressbox.value;
let{rid,cid}=getridcidfromAdress(adress);
let cell=document.querySelector(`.col[rid="${rid}"][cid="${cid}"]`);
cell.style.fontWeight="bold";
console.log("bolt");
})
let uti=document.getElementById("uti");
uti.addEventListener("click",function(){
let adress=adressbox.value;
let{rid,cid}=getridcidfromAdress(adress);
let cell=document.querySelector(`.col[rid="${rid}"][cid="${cid}"]`);
cell.style.textDecoration="underline";
cell.style.textDecorationColor="blue";
})
let italic=document.getElementById("italic");
italic.addEventListener("click",function(){
let adress=adressbox.value;
let{rid,cid}=getridcidfromAdress(adress);
let cell=document.querySelector(`.col[rid="${rid}"][cid="${cid}"]`);
cell.style.fontStyle="italic";
})
let size=document.querySelector(".size");
size.addEventListener("click",function(){
let adress=adressbox.value;
let{rid,cid}=getridcidfromAdress(adress);
let cell=document.querySelector(`.col[rid="${rid}"][cid="${cid}"]`);
let fsize=size.value+"px";
console.log(fsize);
cell.style.fontSize=fsize;
})
let fontfamily=document.querySelector("select#arial");
fontfamily.addEventListener("click",function(){
let adress=adressbox.value;
let{rid,cid}=getridcidfromAdress(adress);
let cell=document.querySelector(`.col[rid="${rid}"][cid="${cid}"]`);
if(fontfamily.select[name=arial].val("arial")=="arial")
{
cell.style.fontFamily="arial";
console.log("hey");
}
})
Allcell[0].click();
|
0ca4b5bba41e07f59c735c17ea580c9f30494b32
|
[
"JavaScript"
] | 1
|
JavaScript
|
ayush9090/EXCELCLONE
|
5df76724eda88b0a45f81ef6bbf44d40f999449b
|
bb8aa12f0d3e5591939a4c8feb733a37ab2dc30c
|
refs/heads/master
|
<file_sep>#include <dirent.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <string.h>
#include <stack>
using namespace std;
stack<string> PrimaryStack;
stack<string> AuxStack;
void extractWord(string word)
{
while (!PrimaryStack.empty())
{
if (PrimaryStack.top() != word)
{
AuxStack.push(PrimaryStack.top());
}
PrimaryStack.pop();
}
while (!AuxStack.empty())
{
PrimaryStack.push(AuxStack.top());
AuxStack.pop();
}
}
int main(int argc, char const *argv[])
{
string linea, termino;
string file, extension, outputfile, filter;
//My variables
int wordsCounter = 1;
bool tagHasChanged = false;
bool isAParsedFile = false;
bool isJavaScriptCode = false;
int JSLinesCounter = 1;
string currentTag = "";
//end of my variables
ifstream leer;
ofstream escribir;
DIR *dir;
struct dirent *ent;
dir = opendir(".");
ent = readdir(dir);
while ((ent != NULL))
{
if ((strcmp(ent->d_name, ".") != 0) && (strcmp(ent->d_name, "..") != 0))
{
file = ent->d_name;
size_t x = file.find(".");
extension = file.substr(x);
isAParsedFile = (file.substr(0, 7) == "Parsed_");
if (extension == ".txt")
{
if (!isAParsedFile)
{
leer.open(file.c_str());
outputfile = "Parsed_" + file;
escribir.open(outputfile.c_str());
while (getline(leer, linea))
{
stringstream renglon(linea);
if (!isJavaScriptCode)
{
while (getline(renglon, termino, ' '))
{
if (termino == "<html>")
{
escribir << "Comienzo de documento" << '\n';
tagHasChanged = true;
PrimaryStack.push("documento");
}
else if (termino == "<head>")
{
escribir << "Comienzo de cabeceras" << '\n';
tagHasChanged = true;
PrimaryStack.push("cabecera");
}
else if (termino == "<title>")
{
escribir << "Comienzo de Título" << '\n';
tagHasChanged = true;
PrimaryStack.push("titulo");
}
else if (termino == "<body>")
{
escribir << "Comienzo de cuerpo" << '\n';
tagHasChanged = true;
PrimaryStack.push("cuerpo");
}
else if (termino == "</html>")
{
escribir << "Fin de documento" << '\n';
tagHasChanged = true;
extractWord("documento");
}
else if (termino == "</head>")
{
escribir << "Fin de cabeceras" << '\n';
tagHasChanged = true;
extractWord("cabecera");
}
else if (termino == "</title>")
{
escribir << "Fin de Título" << '\n';
tagHasChanged = true;
extractWord("titulo");
}
else if (termino == "</body>")
{
escribir << "Fin de cuerpo" << '\n';
tagHasChanged = true;
extractWord("cuerpo");
}
else if (termino == "<script>")
{
escribir << "Comienzo de código en JS\n";
tagHasChanged = isJavaScriptCode = true;
PrimaryStack.push("script");
}
else
{
escribir << "Palabra # " << wordsCounter++ << " de la sección " << PrimaryStack.top() << " : " << termino << '\n';
tagHasChanged = false;
}
if (tagHasChanged)
{
wordsCounter = 1;
}
}
}
else
{
if (linea == "</script>")
{
isJavaScriptCode = false;
JSLinesCounter += 1;
extractWord("script");
escribir << "Final de código JS\n";
}
else
{
escribir << "Linea de código en JS # " << JSLinesCounter++ << " " << linea <<"\n";
}
}
}
escribir << "----------------------\n";
if (PrimaryStack.empty())
{
escribir << "El formato del documento estaba correcto";
}
else{
escribir <<"Checar etiquetas :( formato incompleto";
}
}
}
leer.close();
escribir.close();
}
ent = readdir(dir);
}
printf("\nSe hace finalizado el programa\n");
return 0;
}
|
f20552e42be4099207ff9d4d0d5c97e56a2fbd60
|
[
"C++"
] | 1
|
C++
|
royemerson97/C-HTML-Crawler
|
2d2cb48bcf338e1915b4437ea0f02552ebaf2f15
|
1e53fc505282e61ca0ca2ab7a6680f5c907b95e2
|
refs/heads/master
|
<file_sep># Sidekiq::Instrument
[](https://travis-ci.org/enova/sidekiq-instrument)
[](https://coveralls.io/github/enova/sidekiq-instrument?branch=master)
Reports job metrics using Shopify's [statsd-instrument][statsd-instrument] library, incrementing a counter for each enqueue and dequeue per job type, and timing the full runtime of your perform method.
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'sidekiq-instrument'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install sidekiq-instrument
## Usage
For now, this library assumes you have already initialized `StatsD` on your own;
the `statsd-instrument` gem may have chosen reasonable defaults for you already. If not,
a typical Rails app would just use an initializer:
```ruby
# config/initializers/statsd.rb
require 'statsd-instrument'
StatsD.prefix = 'my-app'
StatsD.backend = StatsD::Instrument::Backends::UDPBackend.new('some-server:8125')
```
Then add the client and server middlewares in your Sidekiq initializer:
```ruby
require 'sidekiq/instrument'
Sidekiq.configure_server do |config|
config.server_middleware do |chain|
chain.add Sidekiq::Instrument::ServerMiddleware
end
config.client_middleware do |chain|
chain.add Sidekiq::Instrument::ClientMiddleware
end
end
Sidekiq.configure_client do |config|
config.client_middleware do |chain|
chain.add Sidekiq::Instrument::ClientMiddleware
end
end
```
## StatsD Keys
For each job, the following metrics will be reported:
1. **shared.sidekiq._queue_._job_.enqueue**: counter incremented each time a
job is pushed onto the queue.
2. **shared.sidekiq._queue_._job_.dequeue**: counter incremented just before
worker begins performing a job.
3. **shared.sidekiq._queue_._job_.runtime**: timer of the total time spent
in `perform`, in milliseconds.
3. **shared.sidekiq._queue_._job_.error**: counter incremented each time a
job fails.
The metric names can be changed by overriding the `statsd_metric_name`
method in your worker classes.
For each queue, the following metrics will be reported:
1. **shared.sidekiq._queue_.size**: gauge of how many jobs are in the queue
1. **shared.sidekiq._queue_.latency**: gauge of how long the oldest job has been in the queue
## Worker
There is a worker, `Sidekiq::Instrument::Worker`, that submits gauges
for various interesting statistics; namely, the bulk of the information in `Sidekiq::Stats`
and the sizes of each individual queue. While the worker class is a fully valid Sidekiq worker,
you should inherit from it your own job implementation instead of using it directly:
```ruby
# app/jobs/sidekiq_stats_job.rb
class SidekiqStatsJob < Sidekiq::Instrument::Worker
METRIC_NAMES = %w[
processed
failed
]
sidekiq_options queue: :stats
end
```
In this example, we override the default stats with the ones we want reported by defining `METRIC_NAMES`.
This can be either an Array or a Hash (if you also want to map a stat to a different metric name).
You can schedule this however you see fit. A simple way is to use [sidekiq-scheduler][sidekiq-scheduler] to run it every N minutes.
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/enova/sidekiq-instrument.
## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
[statsd-instrument]: https://github.com/Shopify/statsd-instrument
[sidekiq-scheduler]: https://github.com/moove-it/sidekiq-scheduler
<file_sep>require 'sidekiq'
require 'sidekiq/api'
module Sidekiq::Instrument
class Worker
include Sidekiq::Worker
# These defaults are for compatibility with Resque's stats names
# (i.e. the metrics will reported as :processed, :workers, :pending, and :failed).
# Feel free to override.
METRIC_NAMES = {
processed: nil,
workers_size: :workers,
enqueued: :pending,
failed: nil
}
def perform
info = Sidekiq::Stats.new
self.class::METRIC_NAMES.each do |method, stat|
stat ||= method
StatsD.gauge "shared.sidekiq.stats.#{stat}", info.send(method)
end
working = Sidekiq::ProcessSet.new.select { |p| p[:busy] == 1 }.count
StatsD.gauge "shared.sidekiq.stats.working", working
info.queues.each do |name, size|
StatsD.gauge "shared.sidekiq.#{name}.size", size
end
Sidekiq::Queue.all.each do |queue|
StatsD.gauge "shared.sidekiq.#{queue.name}.latency", queue.latency
end
end
end
end
<file_sep>module Sidekiq
module Instrument
VERSION = "0.4.0"
end
end
<file_sep>module Sidekiq::Instrument
module MetricNames
def metric_name(worker, event)
if worker.respond_to?(:statsd_metric_name)
worker.send(:statsd_metric_name, event)
else
queue = worker.class.get_sidekiq_options['queue']
name = worker.class.name.gsub('::', '_')
"shared.sidekiq.#{queue}.#{name}.#{event}"
end
end
end
end
<file_sep>require 'sidekiq/instrument/mixin'
module Sidekiq::Instrument
class ServerMiddleware
include Sidekiq::Instrument::MetricNames
def call(worker, job, queue, &block)
StatsD.increment(metric_name(worker, 'dequeue'))
StatsD.measure(metric_name(worker,'runtime'), &block)
rescue StandardError => e
StatsD.increment(metric_name(worker, 'error'))
raise e
end
end
end
<file_sep>require 'sidekiq/instrument/mixin'
module Sidekiq::Instrument
class ClientMiddleware
include Sidekiq::Instrument::MetricNames
def call(worker_class, job, queue, redis_pool)
# worker_class is a const in sidekiq >= 6.x
klass = Object.const_get(worker_class.to_s)
StatsD.increment metric_name(klass.new, 'enqueue')
yield
end
end
end
<file_sep>require 'coveralls'
SimpleCov.formatters = [
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
SimpleCov.start
<file_sep>require 'sidekiq/instrument/middleware/server'
RSpec.describe Sidekiq::Instrument::ServerMiddleware do
describe '#call' do
before(:all) do
Sidekiq::Testing.server_middleware do |chain|
chain.add described_class
end
end
after(:all) do
Sidekiq::Testing.server_middleware do |chain|
chain.remove described_class
end
end
it 'increments dequeue counter' do
expect {
MyWorker.perform_async
}.to trigger_statsd_increment('shared.sidekiq.default.MyWorker.dequeue')
end
it 'measures job runtime' do
expect {
MyWorker.perform_async
}.to trigger_statsd_measure('shared.sidekiq.default.MyWorker.runtime')
end
context 'when a job fails' do
before { allow_any_instance_of(MyWorker).to receive(:perform).and_raise 'foo' }
it 'increments the failure counter' do
expect {
MyWorker.perform_async rescue nil
}.to trigger_statsd_increment('shared.sidekiq.default.MyWorker.error')
end
it 're-raises the error' do
expect { MyWorker.perform_async }.to raise_error 'foo'
end
end
end
end
<file_sep>require 'sidekiq/instrument/middleware/client'
RSpec.describe Sidekiq::Instrument::ClientMiddleware do
describe '#call' do
before(:all) do
Sidekiq.configure_client do |c|
c.client_middleware do |chain|
chain.add described_class
end
end
end
after(:all) do
Sidekiq.configure_client do |c|
c.client_middleware do |chain|
chain.remove described_class
end
end
end
context 'without statsd_metric_name' do
it 'increments the enqueue counter' do
expect {
MyWorker.perform_async
}.to trigger_statsd_increment('shared.sidekiq.default.MyWorker.enqueue')
end
end
context 'with statsd_metric_name' do
it 'increments the enqueue counter' do
expect {
MyOtherWorker.perform_async
}.to trigger_statsd_increment('my_other_worker.enqueue')
end
end
end
end
<file_sep>require 'sidekiq/instrument/worker'
RSpec.describe Sidekiq::Instrument::Worker do
describe '#perform' do
let(:worker) { described_class.new }
it 'triggers the correct default gauges' do
expect { worker.perform }.to trigger_statsd_gauge('shared.sidekiq.stats.processed')
expect { worker.perform }.to trigger_statsd_gauge('shared.sidekiq.stats.workers')
expect { worker.perform }.to trigger_statsd_gauge('shared.sidekiq.stats.pending')
expect { worker.perform }.to trigger_statsd_gauge('shared.sidekiq.stats.failed')
expect { worker.perform }.to trigger_statsd_gauge('shared.sidekiq.stats.working')
end
it 'allows overriding gauges via constant' do
stub_const("#{described_class}::METRIC_NAMES", { enqueued: nil })
expect { worker.perform }.to trigger_statsd_gauge('shared.sidekiq.stats.enqueued')
expect { worker.perform }.to trigger_statsd_gauge('shared.sidekiq.stats.working')
end
context 'when jobs in queues' do
before do
Sidekiq::Testing.disable! do
Sidekiq::Queue.all.each(&:clear)
MyWorker.perform_async
end
end
it 'gauges the size of the queues' do
expect { worker.perform }.to trigger_statsd_gauge('shared.sidekiq.default.size')
end
it 'gauges the latency of the queues' do
expect { worker.perform }.to trigger_statsd_gauge('shared.sidekiq.default.latency')
end
end
end
end
<file_sep>require "sidekiq/instrument/version"
require "sidekiq/instrument/worker"
require "sidekiq/instrument/middleware/client"
require "sidekiq/instrument/middleware/server"
module Sidekiq
module Instrument
end
end
|
2596d5d2c3c40ee7f8e0ddd8d25aaf9b9c077413
|
[
"Markdown",
"Ruby"
] | 11
|
Markdown
|
luigisbox/sidekiq-instrument
|
e455e96312261f72ee0003d646bfe1f621541a7e
|
bcfee16b687226f5cc0fe958173726843d7526f4
|
refs/heads/master
|
<repo_name>TasbirahaAthaya/EDUCATION-SYSTEM-OF-BANGLADESH<file_sep>/README.md
# EDUCATION-SYSTEM-OF-BANGLADESH
## Database Lab Project'2017
This project was done as my database management system course’s lab project which includes:
· Entity-Relationship (ER) diagram
It is about connecting the administrative hierarchy of educational institutions through oracle and also maintaining student's accounts enrolling courses in that institution.
Read **Report.docx** and **USER_Manual.doc** for detail information.
<file_sep>/profileAdmission.php
<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]-->
<!-- Mirrored from trendingtemplates.com/demos/trips/ by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 19 Apr 2016 19:19:17 GMT -->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Eiob</title>
<!-- Favicons -->
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<link rel="apple-touch-icon" href="images/apple-touch-icon.png" />
<link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png" />
<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Default Styles -->
<link href="style.css" rel="stylesheet">
<!-- Custom Styles -->
<link href="css/custom.css" rel="stylesheet">
<!-- SLIDER REVOLUTION 4.x CSS SETTINGS -->
<link href="rs-plugin/css/settings.css" rel="stylesheet">
<style>
body {
margin: 0;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 25%;
background-color: #f1f1f1;
position: fixed;
height: 100%;
overflow: auto;
}
li a {
display: block;
color: #000;
padding: 8px 0 8px 16px;
text-decoration: none;
}
li a.active {
background-color: #4CAF50;
color: white;
}
li a:hover:not(.active) {
background-color: #555;
color: white;
}
.col-sm-10{
margin-bottom: 20px;
}
</style>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<ul>
<li><a class="active" href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
<section>
<div style="margin-left:25%;padding:1px 16px;height:1000px;">
<h3>PROFILE</h3>
<?php
$username=$_POST['username'];
$Pass=$_POST['<PASSWORD>'];
?>
<form method="post" name="oracle" action="oracleAdmissionProfile.php">
<div class="form-group">
<label class="control-label col-sm-2" for="email">Fullname:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="Fullname" placeholder="Enter Fullname">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Rank</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="Rank" placeholder="Enter Rank">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Institute Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="Institute_Name" placeholder="Enter Institute Name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="Username" value="<?php echo htmlspecialchars($username); ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Gender:</label>
<div class="col-sm-10">
<input type="text"class="form-control" name="Gender" placeholder="Enter gender">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Contact no:</label>
<div class="col-sm-10">
<input type="text"class="form-control" name="Contact_no" placeholder="Enter contact no">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Email:</label>
<div class="col-sm-10">
<input type="email" class="form-control" name="Email" placeholder="Enter email">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >GRAD</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="GRAD" placeholder="GRADUATION">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >POSTGRAD</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="POSTGRAD" placeholder="POST GRADUATION">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >City:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="City" placeholder="City">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Street</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="Street" placeholder="Street">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Password:</label>
<div class="col-sm-10">
<input type="password" class="form-control" name="Password" placeholder="<?php echo htmlspecialchars($Pass); ?>">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Update</button>
</div>
</div>
</div>
</form>
</div>
</section>
</body>
</html><file_sep>/oracleFacultyProfile.php
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))(CONNECT_DATA=(SID=xe)))";
$conn=oci_connect('EducationFinal', '123',$db);
if(!$conn)
{
$e=oci_error();
trigger_error(htmlentities($e['messege'],ENT_QUOTES), E_USER_ERROR);
}
?>
<?php
$name=$_POST['Fullname'];
$rank=$_POST['Rank'];
$institute=$_POST['Institute_Name'];
$user = $_POST['n'];
echo $user;
// $username=$_POST['username'];
$gender=$_POST['Gender'];
$contact=$_POST['Contact_no'];
$email=$_POST['Email'];
$City=$_POST['City'];
$street=$_POST['Street'];
$house=$_POST['house'];
$hsc=$_POST['hsc'];
$ssc=$_POST['ssc'];
$phd=$_POST['phd'];
$Pass=$_POST['<PASSWORD>'];
$grad=$_POST['GRAD'];
$postgrad=$_POST['POSTGRAD'];
$query1="UPDATE EMPLOYEE e SET EMP_NAME='$name',EMP_RANK='$rank',EMP_PASSWORD='$<PASSWORD>',EMP_GENDER='$gender',EMP_CONTACT='$contact',
EMP_EMAIL='$email',INS_NAME='$institute',e.emp_qualification.emp_ssc='$ssc',e.emp_qualification.emp_hsc='$hsc',e.emp_qualification.emp_graduate='$grad'
,e.emp_qualification.emp_postgraduate='$postgrad',e.emp_qualification.emp_Phd='$phd',
e.address.emp_houseno='$house',e.address.emp_streetno='$street',e.address.emp_city='$City'
WHERE e.EMP_USER_NAME='$user'";
$insert = oci_parse($conn,$query1);
oci_execute($insert);
$array = oci_parse($conn, "SELECT e.emp_name as Name,e.emp_rank as Rank ,e.emp_gender as Gender, e.emp_contact as Contact,e.emp_email as Email,
e.ins_name as Institution_Name,e.emp_qualification.emp_ssc as SSC,e.emp_qualification.emp_hsc as HSC,e.emp_qualification.emp_graduate as GRAD,
e.emp_qualification.emp_postgraduate as Postgrad,e.emp_qualification.emp_phd as PhD,e.address.emp_houseno as house,e.address.emp_streetno as street,
e.address.emp_city as city from EMPLOYEE e WHERE e.EMP_USER_NAME='$user'");
oci_execute($array);
print "<table border = '1'>\n";
while ($row = oci_fetch_array($array, OCI_ASSOC + OCI_RETURN_NULLS)) {
print "<tr>\n";
foreach ($row as $item) {
print " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
print "</tr>\n";
}
print "</table>\n";
?>
<file_sep>/Eligibility.php
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))(CONNECT_DATA=(SID=xe)))";
$conn=oci_connect('EducationFinal', '123',$db);
if(!$conn)
{
$e=oci_error();
trigger_error(htmlentities($e['messege'],ENT_QUOTES), E_USER_ERROR);
}
?>
<?php
$dept=$_POST['dept_hsc'];
$ins_name=$_POST['ins_name'];
$hsc_gpa=$_POST['hsc_gpa'];
$ssc_gpa=$_POST['ssc_gpa'];
$la=$_POST['browser'];
if($la=="Engineering")
{$SQL = oci_parse($conn,"SELECT INS_NAME AS INSTITUTION,ADDMISSION_APP_DEADLINE AS APPLICATION_DEADLINE,
ADDMISSION_TEST_DEADLINE AS TEST_DEADLINE, RANKING_UGC AS RANK FROM INSTITUTION NATURAL JOIN UNIVERSITY
WHERE PREREQUISITE_DEPT='$dept' and PREREQUISITE_HSC_GPA='$hsc_gpa' ORDER BY RANKING_UGC");
}
else if ($la=="Medical")
{
$SQL = oci_parse($conn,"SELECT INS_NAME AS MEDICAL_COLLEGES FROM INSTITUTION JOIN COLLEGE USING (INS_ID) WHERE MIN_RESULT_HSC>='4.00' AND COLLEGE_CATEGORY='MED'");
}
oci_execute($SQL);
$results = array();
$numRows = oci_fetch_all($SQL, $results, null, null, OCI_FETCHSTATEMENT_BY_ROW);
if($numRows > 0){
echo "<p> <table border=1>\n";
//Print the headings
echo "<tr>\n";
foreach($results[0] as $index=>$value)
echo "<th>$index</th>\n";
echo "</tr>\n";
echo "<tr>\n";
foreach($results as $row)
{
echo "<tr>\n";
foreach($row as $index=>$value)
{
echo "<td>$value</td>\n";
}
echo "</tr>\n";
}
oci_close($conn);
} else {
echo "<tr> The search you enter is not in the database.";
}
?> <file_sep>/fac_acc_update.php
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))(CONNECT_DATA=(SID=xe)))";
$conn=oci_connect('edu', '1234',$db);
if(!$conn)
{
$e=oci_error();
trigger_error(htmlentities($e['messege'],ENT_QUOTES), E_USER_ERROR);
}
?>
<?php
$name=$_POST['Fullname'];
$rank=$_POST['Rank'];
$institute=$_POST['Institute_Name'];
$username=$_POST['Username'];
$gender=$_POST['Gender'];
$contact=$_POST['Contact_no'];
$email=$_POST['Email'];
$city=$_POST['City'];
$street=$_POST['Street'];
$Pass=$_POST['<PASSWORD>'];
$grad=$_POST['GRAD'];
$postgrad=$_POST['POSTGRAD'];
$query1 = "UPDATE EMPLOYEE SET EMP_NAME='$name',EMP_RANK='$rank',EMP_PASSWORD='$<PASSWORD>',EMP_GENDER='$gender',EMP_CONTACT='$contact',
EMP_EMAIL='$email',EMP_GRAD='$grad',EMP_POST_GRAD='$postgrad',EMP_CITY='$city',EMP_STREET='$street',INS_NAME='$institute' WHERE EMP_USER_NAME='$username'";
$insert = oci_parse($conn,$query1);
oci_execute($insert);
$array = oci_parse($conn, "SELECT *FROM EMPLOYEE");
oci_execute($array);
print "<table border = '1'>\n";
while ($row = oci_fetch_array($array, OCI_ASSOC + OCI_RETURN_NULLS)) {
print "<tr>\n";
foreach ($row as $item) {
print " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
print "</tr>\n";
}
print "</table>\n";
?>
<file_sep>/loginfac.php
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))(CONNECT_DATA=(SID=xe)))";
$conn=oci_connect('edu', '1234',$db);
if(!$conn)
{
$e=oci_error();
trigger_error(htmlentities($e['messege'],ENT_QUOTES), E_USER_ERROR);
}
?>
<?php
$username=$_POST['username'];
$Pass=$_POST['<PASSWORD>'];
$query1 = "INSERT INTO EMPLOYEE(EMP_ID,EMP_USER_NAME,EMP_PASSWORD) VALUES
(emp_sequence.nextval,'$username','$Pass') ";
$insert = oci_parse($conn,$query1);
oci_execute($insert);
$array = oci_parse($conn, "SELECT *FROM EMPLOYEE");
oci_execute($array);
print "<table border = '1'>\n";
while ($row = oci_fetch_array($array, OCI_ASSOC + OCI_RETURN_NULLS)) {
print "<tr>\n";
foreach ($row as $item) {
print " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
print "</tr>\n";
}
print "</table>\n";
?>
<file_sep>/updateSalary1.php
<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]-->
<!-- Mirrored from trendingtemplates.com/demos/trips/ by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 19 Apr 2016 19:19:17 GMT -->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Eiob</title>
<!-- Favicons -->
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<link rel="apple-touch-icon" href="images/apple-touch-icon.png" />
<link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png" />
<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Default Styles -->
<link href="style.css" rel="stylesheet">
<!-- Custom Styles -->
<link href="css/custom.css" rel="stylesheet">
<!-- SLIDER REVOLUTION 4.x CSS SETTINGS -->
<link href="rs-plugin/css/settings.css" rel="stylesheet">
<style>
table, th, td {
border-collapse: collapse;
}
th, td {
padding: 5px;
}
td{
border-bottom:1px solid black;
}
body {
margin: 0;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 25%;
background-color: #f1f1f1;
position: fixed;
height: 100%;
overflow: auto;
}
li a {
display: block;
color: #000;
padding: 8px 0 8px 16px;
text-decoration: none;
}
li a.active {
background-color: #4CAF50;
color: white;
}
li a:hover:not(.active) {
background-color: #555;
color: white;
}
.col-sm-10{
margin-bottom: 20px;
}
</style>
</head>
<body>
<body>
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))(CONNECT_DATA=(SID=xe)))";
$conn=oci_connect('EducationFinal', '123',$db);
if(!$conn)
{
$e=oci_error();
trigger_error(htmlentities($e['messege'],ENT_QUOTES), E_USER_ERROR);
}
?>
<?php
$emp_id = $_GET['emp_id'];
?>
<ul>
<li><a class="active" href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
<section>
<div style="margin-left:25%;padding:1px 16px;height:1000px;">
<h3>UPDATE SALARY</h3>
<form method="post" class="form-horizontal" role="form" action ="updatedSalary.php">
<div class="form-group">
<label class="control-label col-sm-2" >Salary</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="salary" placeholder="Enter Salary">
<input type="hidden" name="i" value="<?php echo $emp_id; ?>" />
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">UPDATE</button>
</div>
</div>
</form>
</div>
</section>
</body>
</html>
<file_sep>/Facultyaccount.php
<!DOCTYPE html>
<!--
Template Name: Academic Education V2
Author: <a href="http://www.os-templates.com/">OS Templates</a>
Author URI: http://www.os-templates.com/
Licence: Free to use under our free template licence terms
Licence URI: http://www.os-templates.com/template-terms
-->
<html>
<head>
<title>Academic Education V2</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link href="layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">
</head>
<body id="top">
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))(CONNECT_DATA=(SID=xe)))";
$conn=oci_connect('edu', '1234',$db);
if(!$conn)
{
$e=oci_error();
trigger_error(htmlentities($e['messege'],ENT_QUOTES), E_USER_ERROR);
}
?>
<?php
$username=$_POST['username'];
$Pass=$_POST['<PASSWORD>'];
?>
<!-- ################################################################################################ -->
<!-- ################################################################################################ -->
<!-- ################################################################################################ -->
<div class="wrapper row0">
<div id="topbar" class="clear">
<!-- ################################################################################################ -->
<nav>
<ul>
<h1><a href="index.html">LOGIN</a></h1>
</ul>
</nav>
<!-- ################################################################################################ -->
</div>
</div>
<!-- ################################################################################################ -->
<!-- ################################################################################################ -->
<!-- ################################################################################################ -->
<div class="wrapper row1">
<header id="header" class="clear">
<!-- ################################################################################################ -->
<div id="logo" class="fl_left">
<h1><a href="index.html">Educational Institute of Bangladesh</a></h1>
</div>
<div class="fl_right">
<form class="clear" method="post" action="#">
<fieldset>
<legend>Search:</legend>
<input type="text" value="" placeholder="Search Here">
<button class="fa fa-search" type="submit" title="Search"><em>Search</em></button>
</fieldset>
</form>
</div>
<!-- ################################################################################################ -->
</header>
</div>
<!-- ################################################################################################ -->
<!-- ################################################################################################ -->
<!-- ################################################################################################ -->
<div class="wrapper row2">
<div class="rounded">
<nav id="mainav" class="clear">
<!-- ################################################################################################ -->
<ul class="clear">
<li class="active"><a href="index.html">Home</a></li>
<li><a class="drop" href="#">Department</a>
<ul>
<li><a href="#">EECE</a></li>
<li><a href="#">CSE</a></li>
<li><a href="#">ME</a></li>
<li><a href="#">Civil</a></li>
<li><a href="#">NAME</a></li>
<li><a href="#">BME</a></li>
<li><a href="#">PME</a></li>
<li><a href="#">ARCHITECHTURE</a></li>
<li><a href="#">IPE</a></li>
</ul>
<li><a class="drop" href="#">School</a>
<ul>
<li><a href="#">Primary</a></li>
<li><a href="#">Secondary</a></li>
</ul>
<li><a class="drop" href="#">College</a>
<ul>
<li><a href="#">Higher Secondary College</a></li>
<li><a href="#">Technical College</a></li>
<li><a href="#">Medical College</a></li>
</ul>
</li>
<li><a class="drop" href="#">University</a>
<ul>
<li><a class="drop" href="#">Public</a>
<ul>
<li><a href="#">Engineering</a></li>
<li><a href="#">Others</a></li>
</ul>
</li>
<li><a class="drop" href="#">Private</a>
<ul>
<li><a href="#">Engineering</a></li>
<li><a href="#">Others</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Faculty</a></li>
<li><a href="#">Eligibility Test For University</a></li>
<!-- ################################################################################################ -->
</nav>
</div>
</div>
<!-- ################################################################################################ -->
<!-- ################################################################################################ -->
<!-- ################################################################################################ -->
<div class="wrapper row3">
<div class="rounded">
<main class="container clear">
<!-- main body -->
<!-- ################################################################################################ -->
<div class="sidebar one_third first">
<!-- ################################################################################################ -->
<h6>My Profile</h6>
<nav class="sdb_holder">
<ul>
<li class="active"><a href="#">Account</a></li>
<li><a href="#">Course Details</a></li>
<li><a href="#">Add course</a> </li>
<li><a href="#">Salary</a></li>
</ul>
</nav>
<!--sidebar ends -->
<div class="sdb_holder">
<h6>My Salary</h6>
<h3>50,000 tk<h3>
</div>
<form method="post" name="oracle" action="fac_acc_update.php">
<div class="form-group">
<label class="control-label col-sm-2" for="email">Fullname:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="Fullname" placeholder="Enter full Name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Rank</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="Rank" placeholder="Enter Rank">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Institute Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="Institute_Name" placeholder="Enter Institute Name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="Username" placeholder="<?php echo htmlspecialchars($username); ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Gender:</label>
<div class="col-sm-10">
<input type="text"class="form-control" name="Gender" placeholder="Enter gender">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Contact no:</label>
<div class="col-sm-10">
<input type="text"class="form-control" name="Contact_no" placeholder="Enter contact no">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Email:</label>
<div class="col-sm-10">
<input type="email" class="form-control" name="Email" placeholder="Enter email">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >GRAD</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="GRAD" placeholder="GRADUATION">
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >POSTGRAD</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="POSTGRAD" placeholder="POST GRADUATION">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >City:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="City" placeholder="City">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Street</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="Street" placeholder="Street">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" >Password:</label>
<div class="col-sm-10">
<input type="<PASSWORD>" class="form-control" name="Password" placeholder="<?php echo htmlspecialchars($Pass); ?>">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">save</button>
</div>
</div>
<div class="clear"></div>
</main>
</div>
</div>
<!-- ################################################################################################ -->
<!-- ################################################################################################ -->
<!-- ################################################################################################ -->
</footer>
</div>
</div>
<!-- ################################################################################################ -->
<!-- ################################################################################################ -->
<!-- ################################################################################################ -->
<div class="wrapper row5">
<div id="copyright" class="clear">
<!-- ################################################################################################ -->
<p class="fl_left">Copyright © 2016 - All Rights Reserved - </p>
<!-- ################################################################################################ -->
</div>
</div>
<!-- JAVASCRIPTS -->
<script src="layout/scripts/jquery.min.js"></script>
<script src="layout/scripts/jquery.fitvids.min.js"></script>
<script src="layout/scripts/jquery.mobilemenu.js"></script>
<script src="layout/scripts/tabslet/jquery.tabslet.min.js"></script>
</body>
</html><file_sep>/tech.php
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))(CONNECT_DATA=(SID=xe)))";
$conn=oci_connect('EducationFinal', '123',$db);
if(!$conn)
{
$e=oci_error();
trigger_error(htmlentities($e['messege'],ENT_QUOTES), E_USER_ERROR);
}
?>
<?php
$SQL = oci_parse($conn,"SELECT INS_NAME,INS_CITY,INS_STREET,INS_SEAT,INS_CONTACT,
BOARD_RESULT,
MIN_RESULT_SSC,
MIN_RESULT_HSC
FROM INSTITUTION NATURAL JOIN COLLEGE
WHERE COLLEGE_CATEGORY='Technical'");
oci_execute($SQL);
$results = array();
$numRows = oci_fetch_all($SQL, $results, null, null, OCI_FETCHSTATEMENT_BY_ROW);
if($numRows > 0){
echo "<p> <table border=1>\n";
//Print the headings
echo "<tr>\n";
foreach($results[0] as $index=>$value)
echo "<th>$index</th>\n";
echo "</tr>\n";
echo "<tr>\n";
foreach($results as $row)
{
//echo "sdvdg";
echo "<tr>\n";
foreach($row as $index=>$value)
{
//$link_address = 'accor.php?id='.$value.'';
//echo "<td><a href='".$link_address."'>$value</a><td>";
//echo "<td><a href="school.php">$value</a></td>\n";
echo "<td>$value</td>\n";
}
//echo '<td><a href="hs_info.php?ins_name='.$row["INS_NAME"].'" class="btn btn-primary btn-lg border-radius">DEPT</a></td>';
echo "</tr>\n";
}
oci_close($conn);
} else {
echo "<tr> The search you enter is not in the database.";
}
?> <file_sep>/addEmployee.php
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))(CONNECT_DATA=(SID=xe)))";
$conn=oci_connect('EducationFinal', '123',$db);
if(!$conn)
{
$e=oci_error();
trigger_error(htmlentities($e['messege'],ENT_QUOTES), E_USER_ERROR);
}
?>
<?php
$username=$_POST['username'];
$Pass=$_POST['<PASSWORD>'];
$join=$_POST['join'];
$rank=$_POST['rank'];
$query1 = "INSERT INTO EMPLOYEE(EMP_ID,EMP_USER_NAME,EMP_PASSWORD,JOINING_DATE,emp_rank) VALUES
(emp_seq.nextval,'$username','$Pass',to_date('".$join."', 'dd-mon-yy'),'$rank') ";
$insert = oci_parse($conn,$query1);
oci_execute($insert);
$array = oci_parse($conn, "SELECT e.emp_name as Name,e.emp_rank as Rank ,e.emp_password as Password,e.emp_user_name as User_name,e.emp_gender as Gender, e.emp_contact as Contact,e.emp_email as Email,
e.ins_name as Institution_Name,e.emp_qualification.emp_ssc as SSC,e.emp_qualification.emp_hsc as HSC,e.emp_qualification.emp_graduate as GRAD,
e.emp_qualification.emp_postgraduate as Postgrad,e.emp_qualification.emp_phd as PhD,e.address.emp_houseno as house,e.address.emp_streetno as street,
e.address.emp_city as city from EMPLOYEE e");
oci_execute($array);
$results = array();
$numRows = oci_fetch_all($array, $results, null, null, OCI_FETCHSTATEMENT_BY_ROW);
if($numRows > 0){
echo "<p> <table border=1>\n";
//Print the headings
echo "<tr>\n";
foreach($results[0] as $index=>$value)
echo "<th>$index</th>\n";
echo "</tr>\n";
echo "<tr>\n";
foreach($results as $row)
{
echo "<tr>\n";
foreach($row as $index=>$value)
{
//$link_address = 'uni_info.php?id='.$value.'';
//echo "<td><a href='".$link_address."'>$value</a><td>";
echo "<td>$value</td>\n";
}
echo "</tr>\n";
}
oci_close($conn);
} else {
echo "<tr> The search you enter is not in the database.";
}
?>
<file_sep>/emni.php
<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]-->
<!-- Mirrored from trendingtemplates.com/demos/trips/ by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 19 Apr 2016 19:19:17 GMT -->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Eiob</title>
<!-- Favicons -->
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<link rel="apple-touch-icon" href="images/apple-touch-icon.png" />
<link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png" />
<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Default Styles -->
<link href="style.css" rel="stylesheet">
<!-- Custom Styles -->
<link href="css/custom.css" rel="stylesheet">
<!-- SLIDER REVOLUTION 4.x CSS SETTINGS -->
<link href="rs-plugin/css/settings.css" rel="stylesheet">
<style>
body {
margin: 0;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 25%;
background-color: #f1f1f1;
position: fixed;
height: 100%;
overflow: auto;
}
li a {
display: block;
color: #000;
padding: 8px 0 8px 16px;
text-decoration: none;
}
li a.active {
background-color: #4CAF50;
color: white;
}
li a:hover:not(.active) {
background-color: #555;
color: white;
}
.col-sm-10{
margin-bottom: 20px;
}
</style>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))(CONNECT_DATA=(SID=xe)))";
$conn=oci_connect('edu', '1234',$db);
if(!$conn)
{
$e=oci_error();
trigger_error(htmlentities($e['messege'],ENT_QUOTES), E_USER_ERROR);
}
?>
<?php
echo "hjjkk";
$username=$_POST['username'];
$Pass=$_POST['password'];
echo $username;
echo $Pass;
?>
<ul>
<li><a class="active" href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</body
</html>
<file_sep>/accor.php
<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]-->
<!-- Mirrored from trendingtemplates.com/demos/trips/ by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 19 Apr 2016 19:19:17 GMT -->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Eiob</title>
<!-- Favicons -->
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<link rel="apple-touch-icon" href="images/apple-touch-icon.png" />
<link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png" />
<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Default Styles -->
<link href="style.css" rel="stylesheet">
<!-- Custom Styles -->
<link href="css/custom.css" rel="stylesheet">
<!-- SLIDER REVOLUTION 4.x CSS SETTINGS -->
<link href="rs-plugin/css/settings.css" rel="stylesheet">
<style>
button.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
button.accordion.active, button.accordion:hover {
background-color: #ddd;
}
div.panel {
padding: 0 18px;
display: none;
background-color: white;
}
div.panel.show {
display: block !important;
}
</style>
</head>
<body>
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))(CONNECT_DATA=(SID=xe)))";
$conn=oci_connect('edu', '1234',$db);
if(!$conn)
{
$e=oci_error();
trigger_error(htmlentities($e['messege'],ENT_QUOTES), E_USER_ERROR);
}
?>
<?php
$SQL = oci_parse($conn,"SELECT INS_NAME,INS_CITY,INS_STREET,INS_SEAT,INS_CONTACT,INS_PRI_PUB,UNI_TYPE,
OFFERED_DEGREE,
RANKING_UGC,
PREREQUISITE_SSC_GPA,
PREREQUISITE_HSC_GPA,
PREREQUISITE_DEPT,
ADDMISSION_APP_DEADLINE,
ADDMISSION_TEST_DEADLINE FROM INSTITUTION NATURAL JOIN UNIVERSITY
WHERE INS_PRI_PUB='Public' and UNI_TYPE='Engineering'");
oci_execute($SQL);
$results = array();
$numRows = oci_fetch_all($SQL, $results, null, null, OCI_FETCHSTATEMENT_BY_ROW);
if($numRows > 0){
echo "<p> <table border=1>\n";
//Print the headings
echo "<tr>\n";
foreach($results[0] as $index=>$value)
echo "<th>$index</th>\n";
echo "</tr>\n";
echo "<tr>\n";
foreach($results as $row)
{
echo "<tr>\n";
foreach($row as $index=>$value)
{
//$link_address = 'uni_info.php?id='.$value.'';
echo "<td>$value<td>";
//echo "<td><a href="school.php">$value</a></td>\n";
}
echo "</tr>\n";
}?>
<button class="accordion">DEPT</button>
<div class="panel">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
</script>
<?
oci_close($conn);
} else {
echo "<tr> The search you enter is not in the database.";
}
?>
</body>
</html><file_sep>/oracle.php
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))(CONNECT_DATA=(SID=xe)))";
$conn=oci_connect('EducationFinal', '123',$db);
if(!$conn)
{
$e=oci_error();
trigger_error(htmlentities($e['messege'],ENT_QUOTES), E_USER_ERROR);
}
?>
<?php
$name=$_POST['Fullname'];
$rank=$_POST['Rank'];
$institute=$_POST['Institute_Name'];
$user = $_POST['s'];
//echo $user;
// $username=$_POST['username'];
$gender=$_POST['Gender'];
$contact=$_POST['Contact_no'];
$email=$_POST['Email'];
$City=$_POST['City'];
$street=$_POST['Street'];
$house=$_POST['house'];
$hsc=$_POST['hsc'];
$ssc=$_POST['ssc'];
$phd=$_POST['phd'];
$Pass=$_POST['<PASSWORD>'];
$grad=$_POST['GRAD'];
$postgrad=$_POST['POSTGRAD'];
$query1="UPDATE EMPLOYEE e SET EMP_NAME='$name',EMP_RANK='$rank',EMP_PASSWORD='$<PASSWORD>',EMP_GENDER='$gender',EMP_CONTACT='$contact',
EMP_EMAIL='$email',INS_NAME='$institute',e.emp_qualification.emp_ssc='$ssc',e.emp_qualification.emp_hsc='$hsc',e.emp_qualification.emp_graduate='$grad'
,e.emp_qualification.emp_postgraduate='$postgrad',e.emp_qualification.emp_Phd='$phd',
e.address.emp_houseno='$house',e.address.emp_streetno='$street',e.address.emp_city='$City'
WHERE e.EMP_USER_NAME='$user'";
/*$query1 = "INSERT INTO EMPLOYEE(EMP_ID,EMP_NAME,EMP_RANK,EMP_GENDER,EMP_CONTACT,EMP_EMAIL,EMP_GRAD,EMP_POST_GRAD,EMP_CITY,
EMP_STREET,INS_NAME,EMP_ENROLMENT,EMP_DOB) VALUES
(emp_sequence.nextval,'$name','$rank','$gender','$contact','$email','$grad','$postgrad','$city','$street','$institute',
to_date('".$join."', 'dd-mon-yy'),to_date('".$birth."', 'dd-mon-yy')) ";
EMP_DOB=to_date('".$birth."', 'dd-mon-yy') */
$insert = oci_parse($conn,$query1);
oci_execute($insert);
$array = oci_parse($conn, "SELECT e.emp_name as Name,e.emp_rank as Rank ,e.emp_gender as Gender, e.emp_contact as Contact,e.emp_email as Email,
e.ins_name as Institution_Name,e.emp_qualification.emp_ssc as SSC,e.emp_qualification.emp_hsc as HSC,e.emp_qualification.emp_graduate as GRAD,
e.emp_qualification.emp_postgraduate as Postgrad,e.emp_qualification.emp_phd as PhD,e.address.emp_houseno as house,e.address.emp_streetno as street,
e.address.emp_city as city from EMPLOYEE e WHERE e.EMP_USER_NAME='$user'");
oci_execute($array);
$results = array();
$numRows = oci_fetch_all($array, $results, null, null, OCI_FETCHSTATEMENT_BY_ROW);
if($numRows > 0){
echo "<p> <table border=1>\n";
//Print the headings
echo "<tr>\n";
foreach($results[0] as $index=>$value)
echo "<th>$index</th>\n";
echo "</tr>\n";
echo "<tr>\n";
foreach($results as $row)
{
echo "<tr>\n";
foreach($row as $index=>$value)
{
//$link_address = 'uni_info.php?id='.$value.'';
//echo "<td><a href='".$link_address."'>$value</a><td>";
echo "<td>$value</td>\n";
}
echo "</tr>\n";
}
oci_close($conn);
} else {
echo "<tr> The search you enter is not in the database.";
}
?>
<file_sep>/addCourse1.php
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))(CONNECT_DATA=(SID=xe)))";
$conn=oci_connect('EducationFinal', '123',$db);
if(!$conn)
{
$e=oci_error();
trigger_error(htmlentities($e['messege'],ENT_QUOTES), E_USER_ERROR);
}
?>
<?php
$emp_id = $_POST['p'];
//echo $emp_id;
$la=$_POST['browser'];
$query1 = "INSERT INTO TEACHES(EMP_USER_NAME,CRS_ID) VALUES
('$emp_id','$la') ";
$insert = oci_parse($conn,$query1);
oci_execute($insert);
if($la=="CRS_01")
{
$query1 = "INSERT INTO TEACHES(EMP_USER_NAME,CRS_ID) VALUES
('$emp_id','$la') ";
$insert = oci_parse($conn,$query1);
oci_execute($insert);
echo $la; echo "Is added";
}
else if ($la=="CRS_02")
{
$query1 = "INSERT INTO TEACHES(EMP_USER_NAME,CRS_ID) VALUES
('$emp_id','$la') ";
$insert = oci_parse($conn,$query1);
oci_execute($insert);
echo $la; echo "Is added";}
else if ($la=="CRS_03")
{
$query1 = "INSERT INTO TEACHES(EMP_USER_NAME,CRS_ID) VALUES
('$emp_id','$la') ";
$insert = oci_parse($conn,$query1);
oci_execute($insert);
echo $la; echo "Is added";}
else if ($la=="CRS_04")
{
$query1 = "INSERT INTO TEACHES(EMP_USER_NAME,CRS_ID) VALUES
('$emp_id','$la') ";
$insert = oci_parse($conn,$query1);
oci_execute($insert);
echo $la; echo "Is added";}
else if ($la=="CRS_05")
{
$query1 = "INSERT INTO TEACHES(EMP_USER_NAME,CRS_ID) VALUES
('$emp_id','$la') ";
$insert = oci_parse($conn,$query1);
oci_execute($insert);
echo $la; echo "Is added";}
else if ($la=="CRS_06")
{
$query1 = "INSERT INTO TEACHES(EMP_USER_NAME,CRS_ID) VALUES
('$emp_id','$la') ";
$insert = oci_parse($conn,$query1);
oci_execute($insert);
echo $la; echo "Is added";}
else if ($la=="CRS_07")
{
$query1 = "INSERT INTO TEACHES(EMP_USER_NAME,CRS_ID) VALUES
('$emp_id','$la') ";
$insert = oci_parse($conn,$query1);
oci_execute($insert);
echo $la; echo "Is added";}
else if ($la=="CRS_08")
{
$query1 = "INSERT INTO TEACHES(EMP_USER_NAME,CRS_ID) VALUES
('$emp_id','$la') ";
$insert = oci_parse($conn,$query1);
oci_execute($insert);
echo $la; echo "Is added";}
else if ($la=="CRS_09")
{
$query1 = "INSERT INTO TEACHES(EMP_USER_NAME,CRS_ID) VALUES
('$emp_id','$la') ";
$insert = oci_parse($conn,$query1);
oci_execute($insert);
echo $la; echo "Is added";}
?> <file_sep>/login.php
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))(CONNECT_DATA=(SID=xe)))";
$conn=oci_connect('Education', 'oracle123',$db);
if(!$conn)
{
$e=oci_error();
trigger_error(htmlentities($e['messege'],ENT_QUOTES), E_USER_ERROR);
}
?>
<?php
$username=$_POST['username'];
$password=$_POST['<PASSWORD>'];
$role=$_POST['role'];
if ($role= 'Faculty')
{
echo "Faculty";
}
else if($role= 'Admin staff')
{
echo "anhgj";
}
else if ($role= 'Admission staff')
{
echo "afc";
}
oci_close($conn);
} else {
echo "<tr> The search you enter is not in the database.";
}
?>
|
9ea514933ef52d52926d3cd8b2febf1000c65b43
|
[
"Markdown",
"PHP"
] | 15
|
Markdown
|
TasbirahaAthaya/EDUCATION-SYSTEM-OF-BANGLADESH
|
628946a3ae9493ad430dda68edc2a6cc4f7aa5a5
|
71c31ec438cb9a56434f7edfe47c1730d282fda9
|
refs/heads/master
|
<file_sep>package fr.eservices.soaring.model;
public class Profil {
}
<file_sep>package fr.eservices.soaring.model;
public class Repas {
}
<file_sep>package fr.eservices.week402.app;
// Set this class as a configuration class,
// scan fr.eservices.week402.ctrl for components
// enable spring web mvc
public class AppConfig {
// Add a method to provide an InternalResourceViewResolver,
// put views in /WEB-INF/views
// all views would be some jsp
}
<file_sep>
import java.sql.Connection;
import java.sql.SQLException;
import org.sqlite.SQLiteDataSource;
public class App {
public static void main(String[] args) throws SQLException {
System.out.println("___ App ___");
SQLiteDataSource ds = new SQLiteDataSource();
ds.setUrl("jdbc:sqlite:data.db");
Connection conn = ds.getConnection();
// TODO : select all users.
// ...
conn.close();
}
}
|
2b5896bf87548cd26c6dc058d8d58b691b34a979
|
[
"Java"
] | 4
|
Java
|
lanaflon-cda2/java_ee_spring-16
|
12c4182f1bb8b2c6d7f67120ff800534a31cd123
|
045224fea8e32306b9a899b32dd14e550f35000e
|
refs/heads/master
|
<file_sep>package com.xxm;
import com.xxm.CommonUtil;
public class MergeSortMain {
public static void merge(int[] dataArray, int left, int mid, int right, SortType sortType) {
int[] tmp = new int[right-left+1]; // 辅助数组,归并排序
int point1 = left; // point1指向待合并数组左侧的第一个元素
int point2 = mid+1; // 指向待合并数组的右侧的第一个元素,这边mid放到左侧中,所以需要➕1
int point3 = 0; // tmp的游标
while (point1 <= mid && point2 <= right) {
// 根据sortType将小的(或大的)移动tmp数组中
if (sortType == SortType.SortType_Asc) {
tmp[point3++] = (dataArray[point1]<=dataArray[point2]) ? dataArray[point1++] : dataArray[point2++];
}
else {
tmp[point3++] = (dataArray[point1]<=dataArray[point2]) ? dataArray[point2++] : dataArray[point1++];
}
}
// 如果左边序列未检测完,将剩余元素加到合并的序列中
while (point1 <= mid) {
tmp[point3++] = dataArray[point1++];
}
// 如果右边序列未检测完,将剩余元素加到合并的序列中
while (point2 <= right) {
tmp[point3++] = dataArray[point2++];
}
// 用tmp数组覆盖dataArray数据
for (int i = 0; i < tmp.length; i++) {
dataArray[left+i] = tmp[i];
}
}
public static void mergeSort(int[] dataArray, int start, int end, SortType sortType) {
if (start < end) {
int mid = (start + end) / 2;
mergeSort(dataArray, start, mid, sortType);
mergeSort(dataArray, mid+1, end, sortType);
merge(dataArray, start, mid, end, sortType);
}
}
public static void main(String[] args) {
int[] dataArray = new int[]{6, 5, 3, 1, 8, 7, 2, 4};
System.out.println("归并排序用例");
// 升序
SortType sortType = SortType.SortType_Asc;
mergeSort(dataArray, 0, dataArray.length-1, sortType);
System.out.println("升序排序后:");
CommonUtil.printIntArrayData(dataArray);
// 降序
sortType = SortType.SortType_Desc;
mergeSort(dataArray, 0, dataArray.length-1, sortType);
System.out.println("降序排序后:");
CommonUtil.printIntArrayData(dataArray);
}
}
<file_sep># 归并排序
## 原理
归并排序是基于分治法,将待排序的元素序列分成两个长度相等的子序列,为每个字序列排序,然后再将它们合并成一个子序列。合并两个字序列的过程也就是两路归并。
## 复杂度
一种稳定的排序算法,主要问题在于不是就地排序,它需要一个与待排序数组一样大的辅助空间。由于每次划分时两个子序列长度基本一致,所以最好、最差以及平均复杂度都是nlog2n。具体nlog2n怎么推算,见算法导论,大概思想就是会比较多少层,根据层数算法时间复杂度。
## 图解排序过程

## 同快排对比
* 处理不同数组长度下执行时间:

* 时间复杂度对比

* 数组小于1000w曲线图

* 亿级数据量对比

> 参考了网络资料
> https://blog.csdn.net/qq_36442947/article/details/81612870<file_sep># DataStructureAndAlgorithm
## 语言选择
Why Java?
* C:非面向对象,写法复杂,大量内存管理代码
* C++:写法复杂,大量内存管理代码
* Java:语言丰富严谨,更多的注意力可以放到业务逻辑上,可以更关注数据结构和算法本身的逻辑细节,不必太在乎语言
归并排序
https://blog.csdn.net/qq_36442947/article/details/81612870
https://www.cnblogs.com/of-fanruice/p/7678801.html
<file_sep>package com.xxm;
/*
* 提供公共模块的一些工具函数,抽象能力模块
*
*/
public class CommonUtil {
/*
* 打印int数组元素,用每个元素值用->拼接
* @param dataArray 待打印的int数组
* @Author: xxm
*
*/
public static void printIntArrayData(int[] dataArray) {
for (int i = 0; i < dataArray.length; i++) {
System.out.print(dataArray[i]);
if (i != dataArray.length-1) {
System.out.print(" -> ");
}
}
System.out.println("");
}
/*
* 交换int数组中两个位置元素的值
* @param dataArray 待交换的int数组
* index1 交换位置1
* index2 交换位置2
* @return boolean,如果index1或者index2大于等于数组大小,index1==index2,会返回false
* @Author: xxm
*
*/
public static boolean swapTwoIntDataInArray(int[] dataArray, int index1, int index2) {
int dataArrayLength = dataArray.length;
if (index1 >= dataArrayLength || index2 >= dataArrayLength || index1 == index2) return false;
dataArray[index1] = dataArray[index1] ^ dataArray[index2];
dataArray[index2] = dataArray[index1] ^ dataArray[index2];
dataArray[index1] = dataArray[index1] ^ dataArray[index2];
return true;
}
}
<file_sep>package com.xxm;
import com.xxm.CommonUtil;
public class ShellSortMain {
public static void shellSort(int[] dataArray, SortType sortType) {
int dataArrayLength = dataArray.length;
int step = dataArrayLength / 2;
while (step > 0) {
for (int i = step; i < dataArrayLength; i++) {
int temp = dataArray[i];
int preIndex = i - step;
while (preIndex >= 0 && dataArray[preIndex] > temp) {
dataArray[preIndex + step] = dataArray[preIndex];
preIndex -= step;
}
dataArray[preIndex + step] = temp;
}
step /= 2;
}
}
public static void main(String[] args) {
int[] dataArray = new int[]{6, 5, 3, 1, 8, 7, 2, 4};
System.out.println("希尔排序用例");
// 升序
SortType sortType = SortType.SortType_Asc;
shellSort(dataArray, sortType);
System.out.println("升序排序后:");
CommonUtil.printIntArrayData(dataArray);
// 降序
sortType = SortType.SortType_Desc;
shellSort(dataArray, sortType);
System.out.println("降序排序后:");
CommonUtil.printIntArrayData(dataArray);
}
}
<file_sep># 插入排序
## 原理
## 复杂度
## 图解排序过程

> 参考了网络资料
>
|
8a76ea5cfca5c79f80a3c260cfec84a1c843edf9
|
[
"Markdown",
"Java"
] | 6
|
Java
|
xianminxiao/DataStructureAndAlgorithm
|
810be2a796ae9afd4add686ad65eac075413dd96
|
6683ad27c6eff05b66568b77a0fcb4cb19fb8b35
|
refs/heads/master
|
<file_sep>#include "configuration.h"
#include "common/config_file_parser.h"
namespace {
// Configuration file name.
const char kConfigurationFileName[] = "bpex.ini";
}
// static
Configuration* Configuration::GetInstance() {
// Magic statics.
static Configuration instance(kConfigurationFileName);
return &instance;
}
Configuration::Configuration(const std::string& file_name) {
LoadConfig();
}
void Configuration::LoadConfig() {
// Use ConfigFileParser to get all settings from configuration file.
}<file_sep>cmake_minimum_required(VERSION 3.10.2)
project (BPEX)
set (CMAKE_CXX_STANDARD 11)
include_directories(include)
#include_directories(src)
#include_directories(include/boost/)
link_directories(lib)
#set ( PROJECT_LINK_LIBS event hiredis event_core boost_program_options pthread )
file(GLOB CPP_SOURCES "src/*.cpp")
add_executable(BPEX ${CPP_SOURCES})
#target_link_libraries(BPEX ${PROJECT_LINK_LIBS} )
<file_sep>#ifndef CONFIGURATION_H_
#define CONFIGURATION_H_
#include <string>
// This class contains all settings of this application.
// It's a singleton.
class Configuration {
public:
static Configuration* GetInstance();
// Delete these 2 functions to make sure not get copies of this
// singleton accidentally.
Configuration(Configuration const&) = delete;
void operator=(Configuration const&) = delete;
private:
// Private instance to avoid instancing.
Configuration(const std::string& file_name);
~Configuration() = default;
// Load all setting from config file.
void LoadConfig();
};
#endif // CONFIGURATION_H_<file_sep>
#ifndef BPEX_H_
#define BPEX_H_
// Main class of bpex core.
class Bpex {
public:
Bpex();
~Bpex();
private:
// Load configuration, setup redis.
void Initialize();
};
#endif // BPEX_H_<file_sep>
#ifndef COMMON_CONFIG_FILE_PARSER_H_
#define COMMON_CONFIG_FILE_PARSER_H_
#include <map>
// This class used to support reading configuration from file.
class ConfigFileParser {
public:
ConfigFileParser();
ConfigFileParser(const std::string& file_name);
~ConfigFileParser();
// Read all settings from config file.
void ReadFromFile(const std::string& file_name);
// Parse and get data.
std::string GetValue(const std::string& key);
int GetInt(const std::string& key);
double GetDouble(const std::string& key);
private:
std::map<std::string, std::string> data_;
};
#endif // COMMON_CONFIG_FILE_PARSER_H_
|
9c6949f2fd2edd7775a5ff67ef483f6428b572d9
|
[
"CMake",
"C++"
] | 5
|
C++
|
larvavral/bpex_core_refactor
|
044a5903fda0de8d3242e1b95ba76cbe5c7dfeb0
|
d72c426cc02e757ea91e0f28573fc33c37ea5e5e
|
refs/heads/master
|
<repo_name>hugobarthelemy/allergo<file_sep>/app/controllers/ingredients_controller.rb
class IngredientsController < ApplicationController
before_action :set_product, only: [:edit, :destroy]
before_action :set_ingredient, only: [:edit, :destroy]
skip_after_action :verify_authorized, only: [:destroy]
def destroy
product_ingredient = ProductComponent.where(
ingredient_id: @ingredient.id,
product_id: @product.id,
amount: params[:amount]
)
product_ingredient.first.destroy
## mail to admins who check validity
action = "removed"
UserMailer.alert_admins_change(@product.id, @ingredient.id, action).deliver_now
redirect_to edit_product_path(@product)
end
private
def product_params
params.require(:product).permit(:barcode, :name, :updated_on, :manufacturer, :category, :img_url, ingredients_attributes: [:id, :iso_reference, :fr_name, :en_name, :ja_name, :_destroy])
end
def product_ingredient
params.require(:ingredient).permit(:ingredient)
end
def set_product
@product = Product.find(params[:product_id])
end
def set_ingredient
@ingredient = Ingredient.find(params[:id])
end
end
<file_sep>/app/controllers/pages_controller.rb
class PagesController < ApplicationController
skip_before_action :authenticate_user!, only: [:home, :landing]
skip_after_action :verify_authorized
def home
if params[:scanresult]
@barcode = params[:scanresult]
if @product = Product.find_by(barcode: @barcode)
redirect_to product_path(@product)
else
product = Openfoodfacts::Product.get(@barcode)
if product
product.fetch
@product = Product.create_from_api(product) # creates a product and creates ingredients if new
redirect_to product_path(@product)
else
@message = "Unknown product. Try again."
end
end
end
end
def landing
end
def allergies_allergens
@allergies = Allergy.all
@allergens = AllergyIngredient.all
end
def favorites
@user = current_user
@favorites = @user.products.all
end
end
<file_sep>/app/assets/javascripts/application.js
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require cocoon
//= require algolia/v3/algoliasearch.min
//= require hogan
//= require_tree .
$(".alert-msg").alert();
window.setTimeout(function() { $(".alert-msg").not("#no-allergy-alert").alert('close'); }, 2000);
<file_sep>/app/services/get_products_from_csv_service.rb
class GetProductsFromCsvService
require 'csv'
def self.get_codes(filename_read)
csv_options_read = {
col_sep: "\t",
row_sep: :auto,
quote_char: '"',
headers: :first_row
}
filepath_read = "../db/#{filename_read}"
# filepath_read = 'db/fr.openfoodfacts.org.products.csv' # Relative to current file
csv_options_write = {
col_sep: ',',
force_quotes: true,
quote_char: '"'
}
filepath_write = "../db/codes_from_#{filename_read}"
all_barcodes =[]
codes_array = []
start_position = 0
# TODO #
# importer dernier code du csv codes
last_code = CSV.read(filepath_write, csv_options_write).last
csv_text = File.read(filepath_read, csv_options_read)
start_position = csv_text.index(last_code.first) + 13 unless last_code.nil? || last_code.empty?
if start_position == 0
CSV.open(filepath_write, 'wb', csv_options_write) do |row|
row << ['code']
end
end
# rechercher ce code dans le big csv et donner l'index à start_position
# reprendre l'extraction
#
# ouvrir le fichier de codes
# pour chaque code chercher le produit dans l'API
# créer les objets
until csv_text.match(/\d{13}/, start_position).nil? do
barcode = csv_text.match(/\d{13}/, start_position) unless csv_text.match(/\d{13}/, start_position).nil?
codes_array << barcode.to_s unless codes_array.last == barcode.to_s
start_position = csv_text.index(/\d{13}/, start_position) + 13
puts start_position
end
CSV.open(filepath_write, 'ab', csv_options_write) do |csv|
codes_array.each do |csv_item|
csv << [csv_item]
end
end
end
def self.create_products_from_codes(filename_codes)
csv_options = {
col_sep: ',',
force_quotes: true,
quote_char: '"',
headers: :first_row
}
filepath_codes = Rails.root.join("db").join(filename_codes).to_s
CSV.foreach(filepath_codes, csv_options) do |row|
product = Openfoodfacts::Product.get(row['code'])
if product
product.fetch
Product.create_from_api(product) # creates a product and creates ingredients if new
end
end
end
end
<file_sep>/test/mailers/previews/user_mailer_preview.rb
class UserMailerPreview < ActionMailer::Preview
def alert_admins_change
@product_changed_id = Product.last.id
@ingredient_id = Ingredient.last.id
@action = "added"
end
end
<file_sep>/README.md
<!-- [](https://waffle.io/hugobarthelemy/allergo)
-->
Hi there,
Allergo Scan is a web app aiming to help you checking the products you can eat based on your food allergies.
The app is currently in beta.
http://www.allergo-scan.com/
For now, please access the app on an Android device using the Firefox browser to fully benefit from the scanning experience.
Scanning doesn't work on iOS for the moment.
<file_sep>/app/jobs/mail_product_alert_job.rb
class MailProductAlertJob < ActiveJob::Base
queue_as :default
def perform(product_changed_id, added_ingredients=[])
# Do something later
products_tracked = TrackedProduct.where(product_id: product_changed_id)
products_tracked.each do |product_tracked|
@user_id = product_tracked.user_id
UserMailer.alert(@user_id, product_changed_id, added_ingredients).deliver_later
end
end
end
<file_sep>/config/initializers/redis.rb
$redis = Redis.new
url = ENV["REDISCLOUD_URL"]
if url
Sidekiq.configure_server do |config|
config.redis = { url: url } end
Sidekiq.configure_client do |config| config.redis = { url: url }
end
$redis = Redis.new(:url => url) end
<file_sep>/app/models/product_component.rb
class ProductComponent < ActiveRecord::Base
belongs_to :ingredient
belongs_to :product
def self.create_allergen_or_trace_from_api(ingredient_api_name, new_product, amount)
if ingredient_api_name.include?(":")
ingredient_api = ingredient_api_name.split(":")
case ingredient_api[0]
when "fr"
ingredient = Ingredient.find_or_create_by(fr_name: ingredient_api[1])
when "en"
ingredient = Ingredient.find_or_create_by(en_name: ingredient_api[1])
when "ja"
ingredient = Ingredient.find_or_create_by(ja_name: ingredient_api[1])
else
### TODO ### create "world_name" for unknown language
ingredient = Ingredient.find_or_create_by(en_name: ingredient_api[1])
end
else
if ingredient = Ingredient.find_by(fr_name: ingredient_api_name)
ingredient
else
if ingredient = Ingredient.find_by(en_name: ingredient_api_name)
ingredient
else
if ingredient = Ingredient.find_by(ja_name: ingredient_api_name)
ingredient
else
### TODO ### create "world_name" for unknown language
ingredient = Ingredient.create(en_name: ingredient_api_name)
end
end
end
end
trace_or_allergen_products = ProductComponent.where(product_id: new_product.id,
ingredient_id: ingredient.id,
amount: amount
).first_or_create
end
end
<file_sep>/app/models/allergy.rb
class Allergy < ActiveRecord::Base
has_many :levels, dependent: :destroy
accepts_nested_attributes_for :levels
has_many :allergy_ingredients, dependent: :destroy
has_many :ingredients, through: :allergy_ingredients
end
<file_sep>/app/controllers/products_controller.rb
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :untrack, :track]
skip_before_action :authenticate_user!, only: [:index]
def index
@products = policy_scope(Product)
if params[:product]
@product_search = params[:product].downcase
@result = @products.where(name: @product_search)
else
@searched_words = params[:searched_words]
@products = Product.search_by_manufacturer_and_name(@searched_words)
if @products.empty?
products_from_off = Openfoodfacts::Product.search(@searched_words, locale: 'world')
products_from_off.each do |product|
product.fetch
product_full = Product.create_from_api(product) # creates a product and creates ingredients if new
@products << product_full
end
end
end
end
def new
@product = Product.new
@ingredient = Ingredient.new
authorize @product
end
def create
@product = Product.new(product_params)
@product.save
authorize @product
redirect_to product_path(@product)
end
def track
@tracked_product = TrackedProduct.new(product_id: @product.id, user_id: current_user.id).save
redirect_to product_path(@product)
authorize @product
end
def untrack
authorize @product
current_user.products.delete(@product)
redirect_to product_path(@product)
end
def show
product_eatable = false
@score_zero = @product.reviews.where(score: 0).count
@score_one = @product.reviews.where(score: 1).count
@score_two = @product.reviews.where(score: 2).count
@reviews = @product.reviews.order(updated_at: :desc)
# @product_eatable = true if allergens_in_product.empty?
@matching_allergy = allergens_in_product
# returns :
# matching_results = {
# matching_allergy_or_intolerance: => "nok" / "ok" / "alert",
# allergens_matching_allergy: => array of ingredients,
# traces_matching_allergy: traces_matching_allergy,
# allergens_matching_intolerance: allergens_matching_intolerance,
# traces_matching_intolerance: traces_matching_intolerance
# }
# # @matching_intolerance
# # @allergens_matching_allergy
# # @traces_matching_allergy
# # @allergens_matching_intolerance
# # @traces_matching_intolerance
@pictos_for_allergies_match_with_profil = pictos_for_allergies_match_with_profil
@pictos_for_allergies_no_match_with_profil = pictos_for_allergies_no_match_with_profil
@pictos_for_traces_match_with_profil = pictos_for_traces_match_with_profil
@pictos_for_traces_no_match_with_profil = pictos_for_traces_no_match_with_profil
@pictos_alert_for_trace_for_intolerant_profil = pictos_alert_for_trace_for_intolerant_profil
authorize @product
end
def edit
authorize @product
@matching_allergy = allergens_in_product
@ingredient = Ingredient.new()
@en_ingredients = []
@fr_ingredients = []
Ingredient.all.each do |ing|
@en_ingredients << ing unless ing.en_name.blank?
@fr_ingredients << ing unless ing.fr_name.blank?
end
@en_ingredients = @en_ingredients.sort_by{|ingredient| ingredient.en_name}
@fr_ingredients = @fr_ingredients.sort_by{|ingredient| ingredient.fr_name}
end
def update
ingredient_id = params[:product][:product_components][:ingredient_id]
# ingredient = Ingredient.find(ingredient_id)
product_component = ProductComponent.new(
ingredient_id: ingredient_id,
product_id: @product.id,
amount: params[:product][:amount]
)
authorize @product
if product_component.save
## mail to all users who track changed product
# MailProductAlertJob.perform_later(@product.id)
## mail to admins who check validity
action = "added"
UserMailer.alert_admins_change(@product.id, ingredient_id, action).deliver_now
redirect_to edit_product_path
else
render :edit
end
end
def allergens_in_product
matching_allergy = "nok"
matching_intolerance = "nok"
user_allergens = []
user_traces = []
product_significant_ingredients = []
product_traces = []
## adds allergens to significant ingredients if not detected automatically in ingredients
@product.allergen_ingredients.each do |allergen|
product_significant_ingredients << allergen.ingredient
end
@product.significant_ingredients.each do |significant_ingredient| #extracts all allergens contained in the product
product_significant_ingredients << significant_ingredient.ingredient
end
@product.allergen_ingredients.each do |allergens|
product_significant_ingredients << allergens.ingredient
end
product_significant_ingredients.uniq!
@product.trace_ingredients.each do |product_trace| #extracts all allergens contained in the product
product_traces << product_trace.ingredient
end
if current_user.nil?
matching_allergy = "not logged"
matching_intolerance = "not logged"
elsif current_user.real_allergies.first.nil? && current_user.intolerances.first.nil?
matching_allergy = "empty allergy profile"
matching_intolerance = "empty allergy profile"
else
current_user.real_allergies.each do |real_allergy|
real_allergy.allergy.ingredients.each do |allergy_ingredient|
user_allergens << allergy_ingredient
end
end
current_user.intolerances.each do |intolerance|
intolerance.allergy.ingredients.each do |intolerance_ingredient|
user_traces << intolerance_ingredient
end
end
end
allergens_matching_allergy = (user_allergens & product_significant_ingredients)
allergens_matching_intolerance = (user_traces & product_significant_ingredients)
traces_matching_allergy = (user_allergens & product_traces)
traces_matching_intolerance = (user_traces & product_traces)
if allergens_matching_allergy.blank? && traces_matching_allergy.blank? && allergens_matching_intolerance.blank?
# TEST : allergène en qte significative correspondant au profil allergique
# TEST : allergène en qte de trace correspondant au profil allergique
matching_allergy = "ok"
# matching_intolerance = "ok"
if traces_matching_intolerance.blank?
# TEST : allergène en qte de trace correspondant au profil d'intollerent
matching_intolerance = "ok"
else # allergène en qte de trace correspondant au profil d'intollerent
matching_intolerance = "alert"
end
end
if matching_intolerance == "nok" || matching_allergy == "nok"
matching_allergy_or_intolerance = "nok"
elsif matching_intolerance == "alert"
matching_allergy_or_intolerance = matching_intolerance
else
matching_allergy_or_intolerance = "ok"
end
######### allergies arrays ###########
allergens_matching_allergy_or_intolerance = allergens_matching_allergy + allergens_matching_intolerance
allergies_or_intolerance_activated_by_allergens = []
allergens_matching_allergy_or_intolerance.each do |ingredient|
ingredient.allergies.each do |allergy|
allergies_or_intolerance_activated_by_allergens << allergy.name
end
end
allergies_or_intolerance_activated_by_allergens.uniq!
allergies_activated_by_traces = []
traces_matching_allergy.each do |ingredient|
ingredient.allergies.each do |allergy|
allergies_activated_by_traces << allergy.name
end
end
allergies_activated_by_traces.uniq!
allergens_not_in_user_allergy = (
product_significant_ingredients - allergens_matching_allergy - allergens_matching_intolerance
)
if allergens_not_in_user_allergy == nil
allergens_not_in_user_allergy = []
end
allergies_in_product_not_in_user = []
if allergens_not_in_user_allergy != nil
allergens_not_in_user_allergy.each do |ingredient|
if (ingredient && ingredient.allergies) != nil
ingredient.allergies.each do |allergy|
allergies_in_product_not_in_user << allergy.name
end
end
end
end
allergies_in_product_not_in_user.uniq!
intolerances_activated_by_traces = []
traces_matching_intolerance.each do |ingredient|
ingredient.allergies.each do |intolerance|
intolerances_activated_by_traces << intolerance.name # case "alert"
end
end
intolerances_activated_by_traces.uniq! # case "alert"
intolerances_not_in_user = (
product_traces - traces_matching_intolerance - traces_matching_allergy
)
intolerances_in_product_not_in_user = []
if intolerances_not_in_user.first
intolerances_not_in_user.each do |ingredient|
if ingredient
ingredient.allergies.each do |intolerance|
intolerances_in_product_not_in_user << intolerance.name
end
end
end
intolerances_in_product_not_in_user.uniq!
end
matching_results = {
matching_allergy_or_intolerance: matching_allergy_or_intolerance,
allergies_or_intolerance_activated_by_allergens: allergies_or_intolerance_activated_by_allergens,
allergies_activated_by_traces: allergies_activated_by_traces,
allergies_in_product_not_in_user: allergies_in_product_not_in_user,
intolerances_activated_by_traces: intolerances_activated_by_traces,
intolerances_in_product_not_in_user: intolerances_in_product_not_in_user
}
end
private
def product_params
params.require(:product).permit(:barcode, :name, :updated_on, :manufacturer, :category, :img_url, ingredients_attributes: [:id, :iso_reference, :fr_name, :en_name, :ja_name, :_destroy])
end
def product_ingredient
params.require(:ingredient).permit(:ingredient)
end
def set_product
if params[:id]
@product = Product.find(params[:id])
else
@product = Product.find(params[:product_id])
end
end
def pictos_for_allergies_match_with_profil
pictos_for_allergies_match_with_profil = []
allergies_match_with_profil = allergens_in_product[:allergies_or_intolerance_activated_by_allergens]
allergies_match_with_profil.each do |allergy_match_with_profil|
case allergy_match_with_profil
when 'milk'
pictos_for_allergies_match_with_profil << "picto_allergies/milk_picto.png"
when 'gluten'
pictos_for_allergies_match_with_profil << "picto_allergies/gluten_picto.png"
when 'peanuts'
pictos_for_allergies_match_with_profil << "picto_allergies/peanuts_picto.png"
else
end
end
return pictos_for_allergies_match_with_profil
# return un string <%= image_tag "picto_allergies/...png" %><%= image_tag "picto_allergies/...png" %>
end
def pictos_for_allergies_no_match_with_profil
pictos_for_allergies_no_match_with_profil = []
allergies_no_match_with_profil = allergens_in_product[:allergies_in_product_not_in_user]
allergies_no_match_with_profil.each do |allergy_no_match_with_profil|
case allergy_no_match_with_profil
when 'milk'
pictos_for_allergies_no_match_with_profil << "picto_allergies/milk_picto.png"
when 'gluten'
pictos_for_allergies_no_match_with_profil << "picto_allergies/gluten_picto.png"
when 'peanuts'
pictos_for_allergies_no_match_with_profil << "picto_allergies/peanuts_picto.png"
else
end
end
return pictos_for_allergies_no_match_with_profil
end
def pictos_for_traces_match_with_profil
pictos_for_traces_match_with_profil = []
traces_match_with_profil = allergens_in_product[:allergies_activated_by_traces]
traces_match_with_profil.each do |trace_match_with_profil|
case trace_match_with_profil
when 'milk'
pictos_for_traces_match_with_profil << "picto_allergies/milk_picto.png"
when 'gluten'
pictos_for_traces_match_with_profil << "picto_allergies/gluten_picto.png"
when 'peanuts'
pictos_for_traces_match_with_profil << "picto_allergies/peanuts_picto.png"
else
end
end
return pictos_for_traces_match_with_profil
end
def pictos_for_traces_no_match_with_profil
pictos_for_traces_no_match_with_profil = []
traces_no_match_with_profil = allergens_in_product[:intolerances_in_product_not_in_user]
traces_no_match_with_profil.each do |trace_no_match_with_profil|
case trace_no_match_with_profil
when 'milk'
pictos_for_traces_no_match_with_profil << "picto_allergies/milk_picto.png"
when 'gluten'
pictos_for_traces_no_match_with_profil << "picto_allergies/gluten_picto.png"
when 'peanuts'
pictos_for_traces_no_match_with_profil << "picto_allergies/peanuts_picto.png"
else
end
end
return pictos_for_traces_no_match_with_profil
end
def pictos_alert_for_trace_for_intolerant_profil
pictos_alert_for_trace_for_intolerant_profil = []
traces_for_intolerant_profil = allergens_in_product[:intolerances_activated_by_traces]
traces_for_intolerant_profil.each do |trace_for_intolerant_profil|
case trace_for_intolerant_profil
when 'milk'
pictos_alert_for_trace_for_intolerant_profil << "picto_allergies/milk_picto.png"
when 'gluten'
pictos_alert_for_trace_for_intolerant_profil << "picto_allergies/gluten_picto.png"
when 'peanuts'
pictos_alert_for_trace_for_intolerant_profil << "picto_allergies/peanuts_picto.png"
else
end
end
return pictos_alert_for_trace_for_intolerant_profil
end
end
<file_sep>/app/controllers/allergies_controller.rb
class AllergiesController < ApplicationController
def new
@level = current_user.levels.new
authorize @level
end
def edit
@level = current_user.levels.find(params[:id])
authorize @level
end
def create
@level = current_user.levels.new(allergy_params)
authorize @level
if @level.save
redirect_to user_path(current_user), notice: "Allergy was successfully added."
else
flash[:alert] = "Allergy could not be added!"
render :new
end
end
def update
@level = Level.find(params[:id])
authorize @level
@level.allergy_level = params[:level][:allergy_level]
if @level.save
redirect_to user_path(current_user), notice: "Level was successfully added."
else
flash[:alert] = "Level could not be added!"
render :create
end
end
def destroy
level_a_suppr = current_user.levels.find(params[:id])
authorize level_a_suppr
if level_a_suppr.destroy
redirect_to user_path(current_user), notice: 'Allergy was successfully destroyed.'
else
redirect_to user_path(current_user), alert: 'Allergy could not be destroyed.'
end
end
private
def allergy_params
params.require(:level).permit(:allergy_level,
:allergy_id)
end
end
<file_sep>/app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.user_mailer.alert.subject
#
def alert_admins_change(product_changed_id, ingredient_id, action)
@greeting = "Hi"
@product_changed = Product.find(product_changed_id)
@changed_ingredients_name = Ingredient.find(ingredient_id).any_name
@action = action
@destination_email = "<EMAIL>"
@user_name = "<NAME>"
# @user_name = "#{@user.first_name} #{@user.last_name}"
mail(to: @destination_email, subject: 'Product Change Alert')
# This will render a view in `app/views/user_mailer`!
end
def alert(user_id, product_changed_id, added_ingredients=[])
@greeting = "Hi"
@product_changed = Product.find(product_changed_id)
@added_ingredients = added_ingredients
@user = User.find(user_id) # Instance variable => available in view
@user_name = "#{@user.first_name} #{@user.last_name}"
mail(to: @user.email, subject: 'Product Change Alert')
# This will render a view in `app/views/user_mailer`!
end
end
<file_sep>/db/migrate/20160720114730_add_user_ref_and_product_ref_to_scanned_product.rb
class AddUserRefAndProductRefToScannedProduct < ActiveRecord::Migration
def change
add_reference :scanned_products, :user, index: true, foreign_key: true
add_reference :scanned_products, :product, index: true, foreign_key: true
end
end
<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@level = current_user.levels.new
authorize @level
authorize @user
end
def edit
@user = User.find(current_user)
authorize @user
end
def update
@user = User.find(current_user)
authorize @user
@user.update(user_params)
redirect_to user_path(@user)
end
private
def user_params
params.require(:user).permit(:first_name,
:last_name,
:phone_number,
:email_contact)
end
end
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
require 'csv'
# case Rails.env
# when "development"
# development specific seeding code
User.destroy_all
# products and product_components destroyed for test seeding
# this is not an update of the db!
# Product.destroy_all
# ProductComponent.destroy_all
# Ingredient.destroy_all ## not destroyed between test seedings ?
AllergyIngredient.destroy_all
Allergy.destroy_all
avoine = Ingredient.create(fr_name: "flocons d'avoine", en_name: "")
seigle = Ingredient.create(fr_name: "flocons de seigle malte", en_name: "")
orge = Ingredient.create(fr_name: "farine complete d'orge", en_name: "")
epautre = Ingredient.create(fr_name: "farine complete d'epautre", en_name: "")
ble = Ingredient.create(fr_name: "farine complete de ble", en_name: "")
graisse_v = Ingredient.create(fr_name: "graisse et huile vegetales", en_name: "")
s_roux = Ingredient.create(fr_name: "sucre roux de canne", en_name: "")
dip = Ingredient.create(fr_name: "diphosphates", en_name: "")
carbo_sod = Ingredient.create(fr_name: "carbonate de sodium", en_name: "")
carbo_am = Ingredient.create(fr_name: "carbonate d'ammonium", en_name: "")
lecithines = Ingredient.create(fr_name: "lecithines", en_name: "")
oeuf = Ingredient.create(fr_name: "oeuf", en_name: "")
soja = Ingredient.create(fr_name: "soja", en_name: "")
fruits_coque = Ingredient.create(fr_name: "fruits a coques", en_name: "")
# GetProductsFromCsvService.create_products_from_codes('sample_real_codes.csv')
csv_options = {
col_sep: ',',
force_quotes: true,
quote_char: '"',
headers: :first_row
}
filepath_codes = Rails.root.join("db").join('sample_real_codes.csv').to_s
CSV.foreach(filepath_codes, csv_options) do |row|
if Product.find_by(barcode: row['code']).nil?
product = Openfoodfacts::Product.get(row['code'])
if product
product.foreachetch
Product.create_from_api(product) # creates a product and creates ingredients if new
end
end
end
ProductComponent.create(amount: 2,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: avoine.id
)
ProductComponent.create(amount: 2,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: seigle.id
)
ProductComponent.create(amount: 2,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: orge.id
)
ProductComponent.create(amount: 2,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: epautre.id
)
ProductComponent.create(amount: 2,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: ble.id
)
ProductComponent.create(amount: 2,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: seigle.id
)
ProductComponent.create(amount: 2,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: graisse_v.id
)
ProductComponent.create(amount: 2,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: s_roux.id
)
ProductComponent.create(amount: 2,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: dip.id
)
ProductComponent.create(amount: 2,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: carbo_am.id
)
ProductComponent.create(amount: 2,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: carbo_sod.id
)
ProductComponent.create(amount: 2,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: lecithines.id
)
ProductComponent.create(amount: 1,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: oeuf.id
)
ProductComponent.create(amount: 1,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: soja.id
)
ProductComponent.create(amount: 1,
product_id: Product.find_by(barcode:"3560070955589").id,
ingredient_id: fruits_coque.id
)
# seed des tables d'allergies
milk_allergy = Allergy.new(name: :milk)
milk_allergy.save!
gluten_allergy = Allergy.new(name: :gluten)
gluten_allergy.save!
peanuts_allergy = Allergy.new(name: :peanuts)
peanuts_allergy.save!
# Definition des allergènes de chaque Allergy
# MILK ALLERGY #
contains_milk_fr = Ingredient.where('fr_name ~* :name', name: 'lait')
contains_milk_fr.each do |allergen|
# allergen = Ingredient.find_by(fr_name: milky)
AllergyIngredient.create(allergy_id: milk_allergy.id, ingredient_id: allergen.id)
end
contains_milk_en = Ingredient.where('en_name ~* :name', name: 'milk')
contains_milk_en.each do |allergen|
# allergen = Ingredient.find_by(en_name: milky)
AllergyIngredient.create(allergy_id: milk_allergy.id, ingredient_id: allergen.id)
end
# PEANUT ALLERGY #
contains_peanuts_fr = Ingredient.where('fr_name ~* :name', name: 'cacahuetes')
contains_peanuts_fr.each do |allergen|
# allergen = Ingredient.find_by(fr_name: milky)
AllergyIngredient.create(allergy_id: peanuts_allergy.id, ingredient_id: allergen.id)
end
contains_peanuts_en = Ingredient.where('en_name ~* :name', name: 'peanuts')
contains_peanuts_en.each do |allergen|
# allergen = Ingredient.find_by(en_name: milky)
AllergyIngredient.create(allergy_id: peanuts_allergy.id, ingredient_id: allergen.id)
end
allergen = Ingredient.find_or_create_by(en_name: "lactoserum")
AllergyIngredient.create(allergy_id: milk_allergy.id, ingredient_id: allergen.id)
allergen = Ingredient.find_or_create_by(fr_name: "lactoserum")
AllergyIngredient.create(allergy_id: milk_allergy.id, ingredient_id: allergen.id)
# GLUTEN ALLERGENS #
Ingredient.find_or_create_by(en_name: "gluten")
Ingredient.find_or_create_by(fr_name: "gluten")
contains_gluten_en = Ingredient.where('en_name ~* :name', name: 'gluten')
contains_gluten_en.each do |allergen|
# allergen = Ingredient.find_or_create_by(en_name: "wheat")
AllergyIngredient.create(allergy_id: gluten_allergy.id, ingredient_id: allergen.id)
end
contains_gluten_fr = Ingredient.where('fr_name ~* :name', name: 'gluten')
contains_gluten_fr.each do |allergen|
# allergen = Ingredient.find_or_create_by(fr_name: "blé")
AllergyIngredient.create(allergy_id: gluten_allergy.id, ingredient_id: allergen.id)
end
contains_gluten_en = Ingredient.where('en_name ~* :name', name: 'wheat')
contains_gluten_en.each do |allergen|
# allergen = Ingredient.find_or_create_by(en_name: "wheat")
AllergyIngredient.create(allergy_id: gluten_allergy.id, ingredient_id: allergen.id)
end
contains_gluten_fr = Ingredient.where('fr_name ~* :name', name: 'blé')
contains_gluten_fr.each do |allergen|
# allergen = Ingredient.find_or_create_by(fr_name: "blé")
AllergyIngredient.create(allergy_id: gluten_allergy.id, ingredient_id: allergen.id)
end
contains_gluten_en = Ingredient.where('en_name ~* :name', name: 'rye')
contains_gluten_en.each do |allergen|
# allergen = Ingredient.find_or_create_by(en_name: "wheat")
AllergyIngredient.create(allergy_id: gluten_allergy.id, ingredient_id: allergen.id)
end
contains_gluten_fr = Ingredient.where('fr_name ~* :name', name: 'seigle')
contains_gluten_fr.each do |allergen|
# allergen = Ingredient.find_or_create_by(fr_name: "blé")
AllergyIngredient.create(allergy_id: gluten_allergy.id, ingredient_id: allergen.id)
end
contains_gluten_en = Ingredient.where('en_name ~* :name', name: 'barley')
contains_gluten_en.each do |allergen|
# allergen = Ingredient.find_or_create_by(en_name: "wheat")
AllergyIngredient.create(allergy_id: gluten_allergy.id, ingredient_id: allergen.id)
end
contains_gluten_fr = Ingredient.where('fr_name ~* :name', name: 'orge')
contains_gluten_fr.each do |allergen|
# allergen = Ingredient.find_or_create_by(fr_name: "blé")
AllergyIngredient.create(allergy_id: gluten_allergy.id, ingredient_id: allergen.id)
end
contains_gluten_en = Ingredient.where('en_name ~* :name', name: 'malt')
contains_gluten_en.each do |allergen|
# allergen = Ingredient.find_or_create_by(en_name: "wheat")
AllergyIngredient.create(allergy_id: gluten_allergy.id, ingredient_id: allergen.id)
end
contains_gluten_fr = Ingredient.where('fr_name ~* :name', name: 'malt')
contains_gluten_fr.each do |allergen|
# allergen = Ingredient.find_or_create_by(fr_name: "blé")
AllergyIngredient.create(allergy_id: gluten_allergy.id, ingredient_id: allergen.id)
end
contains_gluten_en = Ingredient.where('en_name ~* :name', name: "brewers yeast")
contains_gluten_en.each do |allergen|
# allergen = Ingredient.find_or_create_by(en_name: "wheat")
AllergyIngredient.create(allergy_id: gluten_allergy.id, ingredient_id: allergen.id)
end
contains_gluten_fr = Ingredient.where('fr_name ~* :name', name: 'levure de biere')
contains_gluten_fr.each do |allergen|
# allergen = Ingredient.find_or_create_by(fr_name: "blé")
AllergyIngredient.create(allergy_id: gluten_allergy.id, ingredient_id: allergen.id)
end
# PEANUTS ALLERGENS #
contains_peanuts_en = Ingredient.where('en_name ~* :name', name: 'peanut')
contains_peanuts_en.each do |allergen|
# allergen = Ingredient.find_or_create_by(en_name: "wheat")
AllergyIngredient.create(allergy_id: peanuts_allergy.id, ingredient_id: allergen.id)
end
contains_cacahuete_fr = Ingredient.where('fr_name ~* :name', name: 'cacahuete')
contains_cacahuete_fr.each do |allergen|
# allergen = Ingredient.find_or_create_by(fr_name: "blé")
AllergyIngredient.create(allergy_id: peanuts_allergy.id, ingredient_id: allergen.id)
end
## TODO ### in japanese
# création des users
# Hugo intollerant au lait
hugo = User.new(email: "<EMAIL>",
first_name: "Hugo",
last_name: "Barthelemy",
phone_number: "0676595703",
email_contact: "<EMAIL>",
provider: "facebook",
password: "<PASSWORD>",
uid: "10154325945005902",
picture: "http://graph.facebook.com/10154325945005902/picture?type=large",
token: "<KEY>",
token_expiry: "2016-09-17 17:55:37")
hugo.save!
level = Level.new(
allergy_level: "1",
user_id: hugo.id,
allergy_id: Allergy.where(name: :milk)[0].id)
level.save!
# <NAME> => allergique aux cacahuetes
laurent = User.new(email: "<EMAIL>",
first_name: "Laurent",
last_name: "Garnier",
phone_number: "",
password: "<PASSWORD>",
email_contact: "<EMAIL>",
picture: "http://www.kdbuzz.com/images/garnier_electrochoc.jpg")
laurent.save!
level = Level.new(
allergy_level: "2",
user_id: laurent.id,
allergy_id: Allergy.where(name: :peanuts)[0].id)
level.save!
# Laura allergique au lait et intollerante au gluten
laura = User.new(email: "<EMAIL>",
first_name: "Laura",
last_name: "Pedroni",
phone_number: "",
password: "<PASSWORD>",
email_contact: "<EMAIL>",
picture: "http://www.kdbuzz.com/images/garnier_electrochoc.jpg")
laura.save!
level = Level.new(
allergy_level: "2",
user_id: laura.id,
allergy_id: Allergy.where(name: :milk)[0].id)
level.save!
level = Level.new(
allergy_level: "1",
user_id: laura.id,
allergy_id: Allergy.where(name: :gluten)[0].id)
level.save!
# Paul intollerant au gluten
paul = User.new(email: "<EMAIL>",
first_name: "Paul",
last_name: "Gaumer",
phone_number: "",
password: "<PASSWORD>",
email_contact: "<EMAIL>",
picture: "http://www.kdbuzz.com/images/garnier_electrochoc.jpg")
paul.save!
level = Level.new(
allergy_level: "1",
user_id: paul.id,
allergy_id: Allergy.where(name: :gluten)[0].id)
level.save!
# Antoine allergique au lait
antoine = User.new(email: "<EMAIL>",
first_name: "Antoine",
last_name: "Reveau",
phone_number: "",
password: "<PASSWORD>",
email_contact: "<EMAIL>",
picture: "http://www.kdbuzz.com/images/garnier_electrochoc.jpg")
antoine.save!
level = Level.new(
allergy_level: "2",
user_id: antoine.id,
allergy_id: Allergy.where(name: :milk)[0].id)
level.save!
# Scanne product # tous les users ont scanné tous les produits
ScannedProduct.destroy_all
Product.last(8).each do |product|
User.last(4).each do |user|
ScannedProduct.create!(user_id: user.id, product_id: product.id)
end
end
# Tracked product # tous les users track tous les produits
TrackedProduct.destroy_all
Product.last(8).each do |product|
User.last(4).each do |user|
TrackedProduct.create!(user_id: user.id, product_id: product.id)
end
end
# Reviews # tous les users ont laissé un avis sur chaque produit
Review.destroy_all
Product.all.each do |product|
Review.create!(
score: [0, 1, 2].sample,
user_id: User.all.sample.id,
product_id: product.id,
content: ""
)
end
Review.create!(score: 2, user_id: User.all.sample.id, \
product_id: Product.find_by(barcode:'3017620429484').id, \
content:"Got me sick!")
Review.create!(score: 0, user_id: User.all.sample.id, \
product_id: Product.find_by(barcode:'3017620429484').id, \
content:"No problem for me")
Review.create!(score: 1, user_id: User.all.sample.id, \
product_id: Product.find_by(barcode:'3017620429484').id, \
content:"Tastes good but a lot of additives!")
Review.create!(score: 2, user_id: User.all.sample.id, \
product_id: Product.find_by(barcode:'3560070955589').id, \
content:"Not sure if all traces are indicated. Got a little sick")
Review.create!(score: 2, user_id: User.all.sample.id, \
product_id: Product.find_by(barcode:'3560070955589').id, \
content:"Good biscuits. Feel safe.")
Review.create!(score: 0, user_id: User.all.sample.id, \
product_id: Product.find_by(barcode:'3560070955589').id, \
content:"Tastes OK but still has gluten")
##############################################################################
##############################################################################
######################### SEED PRODUCTION ####################################
##############################################################################
##############################################################################
# when "production"
# laura = User.new(email: "<EMAIL>",
# first_name: "Laura",
# last_name: "Pedroni",
# phone_number: "",
# password: "<PASSWORD>",
# email_contact: "<EMAIL>",
# picture: "http://www.kdbuzz.com/images/garnier_electrochoc.jpg")
# laura.save!
# else
# end
<file_sep>/Gemfile
source 'https://rubygems.org'
ruby '2.3.1'
gem 'rails', '4.2.6'
gem 'puma'
gem 'pg'
gem 'figaro'
gem 'jbuilder', '~> 2.0'
gem 'devise'
gem 'redis'
gem 'sidekiq'
gem 'sinatra' # Dependency of sidekiq
gem 'sidekiq-failures'
gem 'omniauth-facebook'
gem 'sass-rails'
gem 'jquery-rails'
gem 'uglifier'
gem 'bootstrap-sass'
gem 'font-awesome-sass'
gem 'simple_form'
gem 'autoprefixer-rails'
gem 'pundit'
gem 'openfoodfacts'
#search:
gem 'pg_search'
gem "algoliasearch-rails"
gem 'hogan_assets'
#Add fields to form
gem "cocoon"
group :development, :test do
gem 'binding_of_caller'
gem 'better_errors'
gem 'quiet_assets'
gem 'pry-byebug'
gem 'pry-rails'
gem 'spring'
# mailer
gem "letter_opener", group: :development
end
group :development do
gem 'rails_real_favicon'
end
group :production do
gem 'rails_12factor'
end
<file_sep>/lib/tasks/update_db_from_api.rake
require 'json'
require 'open-uri'
namespace :update_db_from_api do
desc "Check Open Food Fact API for updates"
task :check_api => :environment do
last_updated_date = Product.all.order('updated_on DESC').first.updated_on.strftime(format='%Y-%m-%d')
date_today = Date.today.strftime(format='%Y-%m-%d')
api_url = "https://openfoodfacts-api.herokuapp.com/products?"
api_url_search = "#{api_url}last_edit_dates_tags="
recent_edited_products = []
(last_updated_date..date_today).each do |day|
open("api_url_search#{day}") do |stream|
recent_edited_products << JSON.parse(stream.read)
end
end
recent_edited_products.each do |api_product|
if product_in_db = Product.find_by(barcode: api_product.code)
ingredients_to_compare = api_product.ingredients.id
suppressed_ingredients = []
case api_product.lc
when "fr"
product_in_db.ingredients.each do |db_ingredient|
if ingredients_to_compare.include(db_ingredient.fr_name)
ingredients_to_compare.pop(db_ingredient.fr_name)
else
ingredients_to_compare == []
suppressed_ingredients << db_ingredient
end
end
when "en"
product_in_db.ingredients.each do |db_ingredient|
if ingredients_to_compare.include(db_ingredient.en_name)
ingredients_to_compare.pop(db_ingredient.en_name)
else
ingredients_to_compare == []
suppressed_ingredients << db_ingredient
end
end
when "ja"
product_in_db.ingredients.each do |db_ingredient|
if ingredients_to_compare.include(db_ingredient.ja_name)
ingredients_to_compare.pop(db_ingredient.ja_name)
else
ingredients_to_compare == []
suppressed_ingredients << db_ingredient
end
end
else
end
if ingredients_to_compare.first
added_ingredients = ingredients_to_compare
MailProductAlertJob.perform_later(product_in_db.id, added_ingredients)
end
else
new_product = Product.new()
end
end
end
desc "Task description"
task task_name: [:prerequisite_task, :another_task_we_depend_on] do
# All your magic here
# Any valid Ruby code is allowed
end
end
### TODO ###
# check produit updatés dans OFF
# comparer produits existants avec 2 array
# pour ingredients ajoutés =>
# voir utilisateurs qui trackent
# envoyer mail
# option : verifier si ingredient correspond à l’allergie de l'user
# ajouter à la newsboard/newsletter des allergiques à l’ingredient même si pas tracking
# pour ingredient supprimé =>
# ajouter à la newsboard/newsletter des allergiques à l’ingredient même si pas tracking
# dashboard/newsboard generale avec les modifs
<file_sep>/app/models/allergy_ingredient.rb
class AllergyIngredient < ActiveRecord::Base
belongs_to :ingredient
belongs_to :allergy
def self.define_new(allergen_name)
if allergen_name.include?(":")
allergen = allergen_name.split(":")
case allergen[0]
when "fr"
ingredient = Ingredient.find_or_create_by(fr_name: allergen[1])
when "en"
ingredient = Ingredient.find_or_create_by(en_name: allergen[1])
when "ja"
ingredient = Ingredient.find_or_create_by(ja_name: allergen[1])
else
### TODO ### create "world_name" for unknown language
ingredient = Ingredient.find_or_create_by(en_name: allergen[1])
end
AllergyIngredient.find_or_create_by(ingredient_id: ingredient.id)
else
if ingredient = Ingredient.find_by(fr_name: allergen_name)
ingredient
else
if ingredient = Ingredient.find_by(en_name: allergen_name)
ingredient
else
if ingredient = Ingredient.find_by(ja_name: allergen_name)
ingredient
else
### TODO ### create "world_name" for unknown language
ingredient = Ingredient.create(en_name: allergen_name)
end
end
end
AllergyIngredient.find_or_create_by(ingredient_id: ingredient.id)
end
end
end
<file_sep>/app/controllers/levels_controller.rb
class LevelsController < ApplicationController
end
<file_sep>/db/migrate/20160719170319_add_columns_ingredient_id_and_product_id_toingredients_products.rb
class AddColumnsIngredientIdAndProductIdToingredientsProducts < ActiveRecord::Migration
def change
add_reference :ingredients_products, :ingredient, index: true, foreign_key: true
add_reference :ingredients_products, :product, index: true, foreign_key: true
end
end
<file_sep>/app/models/ingredient.rb
class Ingredient < ActiveRecord::Base
has_many :allergy_ingredients, dependent: :destroy
has_many :product_components
has_many :allergies, through: :allergy_ingredients
include AlgoliaSearch
algoliasearch do
attribute :fr_name, :en_name
attributesToIndex ['fr_name', 'en_name']
end
def self.create_from_api(ingredient_name, lang)
case lang
when "fr"
Ingredient.find_or_create_by(fr_name: ingredient_name)
when "en"
Ingredient.find_or_create_by(en_name: ingredient_name)
when "ja"
Ingredient.find_or_create_by(ja_name: ingredient_name)
else
### TODO ### "world" name
Ingredient.find_or_create_by(en_name: ingredient_name)
end
end
def any_name
return self.en_name unless self.en_name.blank?
return self.fr_name unless self.fr_name.blank?
return self.ja_name unless self.ja_name.blank?
end
end
<file_sep>/app/models/product.rb
class Product < ActiveRecord::Base
include PgSearch
pg_search_scope :search_by_manufacturer_and_name,
:against => [:manufacturer, :name]
#:ignoring => :accents
#:using => :trigram
has_many :product_components, dependent: :destroy
has_many :significant_ingredients, -> { where "amount = 2" },
class_name: "ProductComponent"
has_many :trace_ingredients, -> { where "amount = 1" },
class_name: "ProductComponent"
has_many :allergen_ingredients, -> { where "amount = 4" },
class_name: "ProductComponent"
has_many :reviews, dependent: :destroy
has_many :scanned_products, dependent: :destroy
has_many :tracked_products, dependent: :destroy
has_many :ingredients, through: :product_components
include AlgoliaSearch
algoliasearch do
attribute :name, :manufacturer
attributesToIndex ['name', 'manufacturer']
end
accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :reviews
# permet de passer les attributs de la classe ingredient dans les params de la classe product dans le controller product
# params.require(:product).permit(:barcode, :name, :updated_on, :manufacturer, :category, ingredients_attributes: [:id, :iso_reference :fr_name :en_name :ja_name, :_destroy])
def self.create_from_api(product_api)
barcode = product_api.code
p_name = product_api.product_name
p_updated_on = product_api.last_edit_dates_tags.first.to_date
img_url = product_api.image_url
manufacturer = product_api.brands
# manufacturer = product.brands_tags
# manufacturer = manufacturer.join(',') unless manufacturer.nil?
categories = product_api.categories_tags
categories = categories.join(',') unless categories.nil?
p_ingredients = []
p_ingredients = product_api.ingredients
new_product = Product.new(
barcode:barcode,
name: p_name,
updated_on: p_updated_on,
manufacturer: manufacturer,
category: categories,
img_url: img_url
)
# new_product.save!
new_product.save!
if product_api.ingredients
product_api.ingredients.each do |ingredient|
# creation de la liste d'ingredients du produit
product_ingredient = Ingredient.create_from_api(ingredient.id, product_api.lc)
new_product.ingredients << product_ingredient
new_product.product_components.find_by(ingredient_id: product_ingredient.id).update!(amount: 2)
end
end
if product_api.allergens_tags
product_api.allergens_tags.each do |allergen|
# creation de la liste d'allergènes
AllergyIngredient.define_new(allergen)
ProductComponent.create_allergen_or_trace_from_api(allergen, new_product, 4)
end
end
if product_api.traces_tags
product_api.traces_tags.each do |trace|
ProductComponent.create_allergen_or_trace_from_api(trace, new_product, 1)
end
end
end
def compare_ingredients_from_api
### TODO ##
end
end
<file_sep>/app/models/level.rb
class Level < ActiveRecord::Base
belongs_to :user
belongs_to :allergy
validates :allergy, uniqueness: { scope: :user }
LEVELS = {
"Strong Allergy" => "2",
"Intolerance" => "1"
}
end
<file_sep>/app/assets/javascripts/track_untrack.js
// $(document).ready(function(){
// $(".track-btn").click(function(){
// $(".track-btn").hide();
// });
// });
<file_sep>/app/controllers/reviews_controller.rb
class ReviewsController < ApplicationController
before_action :find_product, only: [ :new, :create, :edit, :update ]
before_action :find_review, only: [ :edit, :update]
def new
@review = Review.new
authorize @review
end
def create
@review = @product.reviews.build(review_params)
@review.user = current_user
@review.save
authorize @review
redirect_to product_path(@product)
end
def edit
authorize @review
end
def update
@review.update(review_params)
authorize @review
redirect_to product_path(@product)
end
private
def review_params
params.require(:review).permit(:score, :content)
end
def find_product
@product = Product.find(params[:product_id])
end
def find_review
@review = Review.find(params[:id])
end
end
<file_sep>/db/migrate/20160721091605_rename_allergies_ingredients_to_allergy_ingredients.rb
class RenameAllergiesIngredientsToAllergyIngredients < ActiveRecord::Migration
def change
rename_table("allergies_ingredients", "allergy_ingredients")
end
end
<file_sep>/db/migrate/20160720114456_add_user_ref_and_product_ref_to_tracked_product.rb
class AddUserRefAndProductRefToTrackedProduct < ActiveRecord::Migration
def change
add_reference :tracked_products, :user, index: true, foreign_key: true
add_reference :tracked_products, :product, index: true, foreign_key: true
end
end
|
a26762dfb287baa8880426fe0ba76b0f31294859
|
[
"JavaScript",
"Ruby",
"Markdown"
] | 28
|
Ruby
|
hugobarthelemy/allergo
|
7d26956df42547d5e8b79894ab28e69410205b99
|
c78871edcbf9e61967f2ebd787516a8c35076521
|
refs/heads/master
|
<repo_name>DumiduM/Soap-consume<file_sep>/index.php
<?php
session_start();
$url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL";
$client = new SoapClient($url);
// $fcs = $client->__getFunctions();
// $types = $client->__getTypes();
// var_dump($fcs);
// var_dump($types);
$CountryPhone = "null";
?>
<!DOCTYPE html>
<html>
<head>
<title>Country Details</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<script>
function var setPath(name1) {
var str = "https://www.google.lk/maps/place/"+name1;
var res = str.replace(" ", "");
return str;
}
</script>
</head>
<body>
<div class="container">
<div>
<h1>Country Details</h1><br>
<form class="form-inline" action="" method="post">
<div class="form-group">
<label for="name">Country Name: </label>
<input type="text" class="form-control" id="email" placeholder="Enter country name" name="cName" style="margin-right: 12px;">
</div>
<button type="submit" name="submit" class="btn btn-default">Submit</button>
</form>
</div>
<div>
<!-- <form>
<div class="form-group">
<label for="name">ISO Code: </label>
<input type="text" class="form-control" id="email" name="cName" style="margin-right: 12px;">
</div>
<div class="form-group">
<label for="name">Name: </label>
<input type="text" class="form-control" id="email" name="cName" style="margin-right: 12px;">
</div>
<div class="form-group">
<label for="name">Capital City: </label>
<input type="text" class="form-control" id="email" name="cName" style="margin-right: 12px;">
</div>
<div class="form-group">
<label for="name">Phone Code: </label>
<input type="text" class="form-control" value="<?php echo $_SESSION["conPhone"]; ?>" id="conPhone" name="cName" style="margin-right: 12px;">
</div>
<div class="form-group">
<label for="name">Continect Code: </label>
<input type="text" class="form-control" id="email" name="cName" style="margin-right: 12px;">
</div>
<div class="form-group">
<label for="name">Currency: </label>
<input type="text" class="form-control" id="email" name="cName" style="margin-right: 12px;">
</div>
<div class="form-group">
<label for="name">Language: </label>
<input type="text" class="form-control" id="email" name="cName" style="margin-right: 12px;">
</div>
</form> -->
</div>
<?php
if(isset($_POST['submit'])){
if (!empty($_POST['cName'])){
$countryName = $_POST['cName'];
$CountryISOCode = $client -> CountryISOCode(array('sCountryName' => "$countryName"));
$CountryCode = $CountryISOCode-> CountryISOCodeResult;
// $CountryIntPhoneCode = $client -> CountryIntPhoneCode(array('sCountryISOCode' => "$CountryCode"));
// $CountryPhone = $CountryIntPhoneCode-> CountryIntPhoneCodeResult;
// $CountryIntPhoneCode = $client -> CountryIntPhoneCode(array('sCountryISOCode' => "$CountryCode"));
// $CountryPhone = $CountryIntPhoneCode-> CountryIntPhoneCodeResult;
$CountryInfo = $client -> FullCountryInfo(array('sCountryISOCode' => "$CountryCode"));
$ConCode = $CountryInfo-> FullCountryInfoResult->sISOCode;
$ConName = $CountryInfo-> FullCountryInfoResult->sName;
$ConCity = $CountryInfo-> FullCountryInfoResult->sCapitalCity;
$ConPhone = $CountryInfo-> FullCountryInfoResult->sPhoneCode;
$ConCont = $CountryInfo-> FullCountryInfoResult->sContinentCode;
$ConCurr = $CountryInfo-> FullCountryInfoResult->sCurrencyISOCode;
$ConFlag = $CountryInfo-> FullCountryInfoResult->sCountryFlag;
$ConLang = $CountryInfo-> FullCountryInfoResult->Languages->tLanguage->sISOCode;
$ConLangName = $CountryInfo-> FullCountryInfoResult->Languages->tLanguage->sName;
$CountrycurrNa = $client -> CountryCurrency(array('sCountryISOCode' => "$ConCurr"));
$ConCurrName = $CountrycurrNa-> CountryCurrencyResult->sName;
$CountrycurrNa = $client -> CountryCurrency(array('sCountryISOCode' => "$ConCurr"));
$ConCurrName = $CountrycurrNa-> CountryCurrencyResult->sName;
// echo "$ConCode";
// echo "$ConName";
// echo "$ConCity";
// echo "$ConPhone";
// echo "$ConCont";
// echo "$ConCurr";
// echo "$ConCurrName";
// echo "$ConLang";
// echo "$ConLangName";
}
else
echo "no data added";
?>
<div>
<br>
<img src="<?php echo "$ConFlag"; ?>"><br><br>
<h5><strong>ISO Code :</strong> <?php echo "$ConCode"; ?></h5>
<h5><strong>Name :</strong> <?php echo "$ConName"; ?></h5>
<h5><strong>Capital City :</strong> <?php echo "$ConCity"; ?></h5>
<h5><strong>Phone Code :</strong> <?php echo "$ConPhone"; ?></h5>
<h5><strong>Continent Code :</strong> <?php echo "$ConCont"; ?></h5>
<h5><strong>Currency ISO Code :</strong> <?php echo "$ConCurr"; ?></h5>
<h5><strong>Currency Name :</strong> <?php echo "$ConCurrName"; ?></h5>
<h5><strong>Language ISO Code :</strong> <?php echo "$ConLang"; ?></h5>
<h5><strong>Language Name :</strong> <?php echo "$ConLangName"; ?></h5>
<script>setPath("<?php echo"$ConName";?>");</script>
</div>
<?php
}
?>
<style>
strong{
color: red;
}
</style>
</div>
</body>
</html>
|
749b14f7131a2359893158f1dd71188750dcb2d6
|
[
"PHP"
] | 1
|
PHP
|
DumiduM/Soap-consume
|
50d66aa4dbb3e3f751238d4ee28991543660dd1f
|
b47b5e5f70d2baa9783877044fb6212a4edde498
|
refs/heads/master
|
<repo_name>krisuety/seq2seq_chatbot<file_sep>/README.md
# seq2seq_chatbot
## Data : [Chatbot_data for Korean](https://github.com/songys/Chatbot_data)
## Framework : Pytorch
## Model : seq2seq + Attention
## Reference : Learning Phrase Representations using RNN Encoder– Decoder for Statistical Machine Translation
## Tokenizer : split
## result

<file_sep>/predict.py
from __future__ import unicode_literals, print_function, division
from io import open
import unicodedata
import string
import re
import random
import torch
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
import warnings
import pandas as pd
warnings.filterwarnings(action='ignore')
def evaluated(encoder, decoder):
print("대화를 시작합니다.\n")
for i in range(10):
print("끝내고 싶으면 '종료'를 입력하세요\n")
inp = input()
if inp == "종료":
break
output_words, attentions = evaluate(encoder, decoder , inp)
output_sentence = ' '.join(output_words)
print('<', output_sentence)
print('')
df = pd.read_csv("ChatBotData.csv")
use_cuda = torch.cuda.is_available()
MAX_LENGTH = 20
SOS_token = 0
EOS_token = 1
UNKNOWN_token = 2
class Lang :
def __init__(self, name):
self.name = name
self.word2index = {}
self.index2word = {}
self.word2count = {0: "SOS", 1: "EOS", 2:"UNKNOWN"}
self.n_words = 3 #count SOS and EOS and UNKWON
def addSentence(self, sentence):
for word in sentence.split(' '):
self.addWord(word)
def addWord(self, word):
if word not in self.word2index:
self.word2index[word] = self.n_words
self.word2count[word] = 1
self.index2word[self.n_words] = word
self.n_words += 1
else:
self.word2count[word] += 1
def normalizeString(s):
hangul = re.compile('[^ ㄱ-ㅣ가-힣 ^☆; ^a-zA-Z.!?]+')
result = hangul.sub('', s)
return s
def readText():
inputs = df['Q']
outputs = df['A']
inputs = [normalizeString(s) for s in inputs]
outputs = [normalizeString(s) for s in outputs]
inp = Lang('input')
outp = Lang('output')
pair = []
for i in range(len(inputs)):
pair.append([inputs[i], outputs[i]])
return inp, outp, pair
def prepareData():
input_lang, output_lang, pairs = readText()
for pair in pairs:
input_lang.addSentence(pair[0])
output_lang.addSentence(pair[1])
return input_lang, output_lang, pairs
input_lang, output_lang, pairs = prepareData()
class EncoderRNN(nn.Module):
def __init__(self, input_size, hidden_size):
super(EncoderRNN, self).__init__()
self.hidden_size = hidden_size
self.embedding = nn.Embedding(input_size, hidden_size)
self.gru = nn.GRU(hidden_size, hidden_size)
def forward(self, input, hidden):
embedded = self.embedding(input).view(1, 1, -1)
output = embedded
output, hidden = self.gru(output, hidden)
return output, hidden
def initHidden(self):
result = torch.zeros(1,1, self.hidden_size)
if use_cuda:
return result.cuda()
else:
return result
class AttnDecoderRNN(nn.Module):
def __init__(self, hidden_size, output_size, dropout_p = 0.1, max_length=MAX_LENGTH):
super(AttnDecoderRNN, self).__init__()
self.hidden_size = hidden_size
self.output_size = output_size
self.dropout_p = dropout_p
self.max_length = max_length
self.embedding = nn.Embedding(self.output_size, self.hidden_size)
self.attn = nn.Linear(self.hidden_size * 2 , self.max_length)
self.attn_combine = nn.Linear(self.hidden_size*2, self.hidden_size)
self.dropout = nn.Dropout(self.dropout_p)
self.gru = nn.GRU(self.hidden_size, self.hidden_size)
self.out = nn.Linear(self.hidden_size, self.output_size)
def forward(self, input, hidden, encoder_outputs):
embedded = self.embedding(input).view(1,1,-1)
embedded = self.dropout(embedded)
attn_weights = F.softmax(self.attn(torch.cat((embedded[0], hidden[0]) , 1 )))
attn_applied = torch.bmm(attn_weights.unsqueeze(0), encoder_outputs.unsqueeze(0))
output = torch.cat((embedded[0], attn_applied[0]), 1)
output = self.attn_combine(output).unsqueeze(0)
output = F.relu(output)
output, hidden = self.gru(output, hidden)
output = F.log_softmax(self.out(output[0]))
return output, hidden, attn_weights
def initHidden(self):
result = Variable(torch.zeros(1,1,self.hidden_size))
if use_cuda:
return result.cuda()
else:
return result
def indexesFromSentence(lang, sentence):
return [lang.word2index[word] for word in sentence.split(' ')]
def variableFromSentence(lang, sentence):
indexes = indexesFromSentence(lang, sentence)
indexes.append(EOS_token)
result = torch.LongTensor(indexes).view(-1,1)
if use_cuda:
return result.cuda()
else:
return result
def variablesFromPair(pair):
input_variable = variableFromSentence(input_lang, pair[0])
target_variable = variableFromSentence(output_lang, pair[1])
return (input_variable, target_variable)
teacher_forcing_ratio = 0.5
input_lang
input_lang.index2word[1] = '모르는 단어'
input_lang.word2index['모르는 단어'] = 1
def indexesFromSentence(lang, sentence):
ls = []
for word in sentence.split(' '):
try:
ls.append(lang.word2index[word])
except:
ls.append(lang.word2index['모르는 단어'])
return ls
hidden_size = 256
encoder1 = EncoderRNN(input_lang.n_words, hidden_size)
attn_decoder1 = AttnDecoderRNN(hidden_size, output_lang.n_words, dropout_p=0.1)
if use_cuda:
encoder1 = encoder1.cuda()
attn_decoder1 = attn_decoder1.cuda()
checkpoint = torch.load(
'model.pt', map_location=lambda storage, loc: storage)
encoder_sd = checkpoint['en']
decoder_sd = checkpoint['de']
encoder1.load_state_dict(encoder_sd)
attn_decoder1.load_state_dict(decoder_sd)
encoder1.state_dict()
def evaluate(encoder, decoder, sentence, max_length=MAX_LENGTH):
input_variable = variableFromSentence(input_lang, sentence)
input_length = input_variable.size()[0]
encoder_hidden = encoder.initHidden()
encoder_outputs = torch.zeros(max_length, encoder.hidden_size)
encoder_outputs = encoder_outputs.cuda() if use_cuda else encoder_outputs
for ei in range(input_length):
encoder_output, encoder_hidden = encoder(input_variable[ei], encoder_hidden)
encoder_outputs[ei] = encoder_outputs[ei] + encoder_output[0][0]
decoder_input = torch.LongTensor([[SOS_token]])
decoder_input = decoder_input.cuda() if use_cuda else decoder_input
decoder_hidden = encoder_hidden
decoded_words = []
decoder_attentions = torch.zeros(max_length, max_length)
for di in range(max_length):
decoder_output, decoder_hidden, decoder_attention = decoder( decoder_input, decoder_hidden, encoder_outputs)
decoder_attentions[di] = decoder_attention.data
topv, topi = decoder_output.data.topk(1)
ni = topi[0][0]
if ni == EOS_token:
decoded_words.append('<EOS>')
break
else:
decoded_words.append(output_lang.index2word[ni.item()])
decoder_input = torch.LongTensor([[ni]])
decoder_input = decoder_input.cuda() if use_cuda else decoder_input
return decoded_words, decoder_attentions[:di +1]
evaluated(encoder1, attn_decoder1)
|
3345e6d8956b01c00d948b0384dc85481fb71f18
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
krisuety/seq2seq_chatbot
|
c8afd3f6105997c4fe899ad5b7fb2bcd5a4832cc
|
edd597eeb55aa209543f39e6c10bf948b012dd98
|
refs/heads/master
|
<file_sep>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <math.h>
#include <ctype.h>
#include "cs402.h"
#include <locale.h>
#include "my402list.h"
/* ----------------------- Global ----------------------- */
typedef struct tfile{
char operator[1];
char description[24];
long int timestamp;
int amount;
int balances;
char newtimestamp[15];
int amountpush;
int balancespush;
char outputamountprint[15];
char outputbalanceprint[15];
}tfilevalues;
char buf[1030];
/* ----------------------- Print() ----------------------- */
void printheadline()
{
int i;
for (i=0; i< 80; i++)
{
if (i == 0 || i == 18 || i == 45 || i == 62 ||i == 79)
fprintf(stdout, "+");
else
fprintf(stdout, "-");
}
fprintf(stdout,"\n");
}
void printheading()
{
fprintf(stdout,"| Date | Description | Amount | Balance |\n");
}
static
void printthedetails(My402List *pList)
{
//My402ListElem *elem=NULL;
//tfilevalues* ival;
//float reference,bal;
printheadline();
printheading();
printheadline();
char* timedat;
char timearray[20];
char newtime[17];
char newtime1[6];
int i;
My402ListElem *elem2= NULL;
My402ListElem *elem5= NULL;
My402ListElem *elem4= NULL;
My402ListElem *elem1=NULL;
My402ListElem *elem=NULL;
My402ListElem *elem3=NULL;
//tfilevalues* ival3;
//tfilevalues* ival4;
for (elem=My402ListFirst(pList); elem != NULL; elem=My402ListNext(pList, elem))
{
tfilevalues* ival;
memset(newtime,0,sizeof(newtime));
memset(newtime1,0,sizeof(newtime1));
ival=(tfilevalues*)(elem->obj);
timedat = ctime(&(ival->timestamp));
strcpy(timearray,timedat);
for (i=0; i <11; i++)
{
newtime[i]= timearray[i];
}
for ( i=0; i<4 ; i++ )
{
newtime1[i]=timearray[i+20];
}
strcat(newtime,newtime1);
strcpy(ival->newtimestamp,newtime);
}
int bal=0;
for (elem1=My402ListFirst(pList); elem1 != NULL; elem1=My402ListNext(pList, elem1))
{
tfilevalues* ival1;
int reference=0;
ival1=(tfilevalues*)(elem1->obj);
reference = ival1->amount;
if ((ival1->operator)[0] == '+')
bal = bal + reference;
else if ((ival1->operator)[0] == '-')
bal = bal -reference;
ival1->balances= bal;
}
// Code for terminating string \0 and printing the comma
for (elem2=My402ListFirst(pList); elem2 != NULL; elem2=My402ListNext(pList, elem2))
{
tfilevalues* ival2;
ival2=(tfilevalues*)(elem2->obj);
int localint=0;
int count =0;
int c;
for(c=0; c<strlen(ival2->description);c++)
{
if(ival2->description[c] == '\n')
ival2->description[c]='\0';
}
localint = ival2->amount;
while(localint!=0)
{
localint = localint/10;
count ++;
}
ival2->amountpush = count;
count=0;localint=ival2->balances;
while(localint!=0)
{
localint = localint/10;
count ++;
}
ival2->balancespush = count;
}
for (elem4=My402ListFirst(pList); elem4 != NULL; elem4=My402ListNext(pList, elem4))
{
tfilevalues* ival4;
ival4=(tfilevalues*)(elem4->obj);
char string[20];
char outputstring[20];
int c;
char str[5];
int dec = (ival4->amount) % 100;
memset(string,0,sizeof(string));
memset(outputstring,0,sizeof(outputstring));
sprintf(string,"%d",(ival4->amount)/100);
sprintf(str,"%02d", dec);
//fprintf(stdout, "*** %s", str);
if((strlen(string) == 4))
{ //print 2comma
for(i=0, c=0 ;i<strlen(string);i++,c++)
{
if(i == 1){
outputstring[c] = ',';
c++;
outputstring[c] = string[i];
}
else
outputstring[c] = string[i];
}
}
else if((strlen(string) == 5))
{ //print 2comma
for(i=0, c=0 ;i<strlen(string);i++,c++)
{
if(i == 2){
outputstring[c] = ',';
c++;
outputstring[c] = string[i];
}
else
outputstring[c] = string[i];
}
}
else if((strlen(string) == 6))
{ //print 2comma
for(i=0, c=0 ;i<strlen(string);i++,c++)
{
if(i == 3){
outputstring[c] = ',';
c++;
outputstring[c] = string[i];
}
else
outputstring[c] = string[i];
}
}
else if((strlen(string) > 6))
{ //print 2comma
for(i=0, c=0 ;i<strlen(string);i++,c++)
{
if(i == 1){
outputstring[c] = ',';
c++;
outputstring[c] = string[i];
}
else if(i==4){
outputstring[c] = ',';
c++;
outputstring[c] = string[i];
}
else
outputstring[c] = string[i];
}
}
else
sprintf(outputstring,"%s",string);
//printf("OUT:%s\n",outputstring);
//char *str1;
//char point[2]=".";
//str1=strcat(point,str);
//finalstr='\0';
/*
int len=strlen(outputstring)+strlen(str)+1;
ival4->outputamountprint[len]='\0';
*/
sprintf(ival4->outputamountprint,"%s%s%s",outputstring,".",str);
//finalstr=strcat(outputstring,str1);
}
for (elem5=My402ListFirst(pList); elem5 != NULL; elem5=My402ListNext(pList, elem5))
{
tfilevalues* ival5;
ival5=(tfilevalues*)(elem5->obj);
char string[15];
char outputstring[15];
int c;
char str[5];
int dec = (abs(ival5->balances)) % 100;
memset(string,0,sizeof(string));
memset(outputstring,0,sizeof(outputstring));
sprintf(string,"%d",abs(ival5->balances)/100);
sprintf(str,"%02d", dec);
if((strlen(string) == 4))
{ //print 2comma
for(i=0, c=0 ;i<strlen(string);i++,c++)
{
if(i == 1){
outputstring[c] = ',';
c++;
outputstring[c] = string[i];
}
else
outputstring[c] = string[i];
}
}
else if((strlen(string) == 5))
{ //print 2comma
for(i=0, c=0 ;i<strlen(string);i++,c++)
{
if(i == 2){
outputstring[c] = ',';
c++;
outputstring[c] = string[i];
}
else
outputstring[c] = string[i];
}
}
else if((strlen(string) == 6))
{ //print 2comma
for(i=0, c=0 ;i<strlen(string);i++,c++)
{
if(i == 3){
outputstring[c] = ',';
c++;
outputstring[c] = string[i];
}
else
outputstring[c] = string[i];
}
}
else if((strlen(string) >6))
{ //print 2comma
for(i=0, c=0 ;i<strlen(string);i++,c++)
{
if(i == 1){
outputstring[c] = ',';
c++;
outputstring[c] = string[i];
}
else if(i==4){
outputstring[c] = ',';
c++;
outputstring[c] = string[i];
}
else
outputstring[c] = string[i];
}
}
else
sprintf(outputstring,"%s",string);
//char *str1;
//char point[2]=".";
//str1=strcat(point,str);
//finalstr=strcat(outputstring,str1);
//printf("Entered");
// int len=strlen (outputstring)+strlen(str)+1;
// ival5->outputbalanceprint[len]='\0';
char finalstr[15];
sprintf(finalstr,"%s%s%s",outputstring,".",str);
strcpy(ival5->outputbalanceprint,finalstr);
//printf("Ival5==%s\n",ival5->outputbalanceprint);
}
for (elem3=My402ListFirst(pList); elem3 != NULL; elem3=My402ListNext(pList, elem3))
{
int j;
tfilevalues* ival3;
ival3=(tfilevalues*)(elem3->obj);
fprintf(stdout,"| %s ",ival3->newtimestamp);
fprintf(stdout,"| %s",ival3->description);
for(j=0; j<25-strlen(ival3->description);j++)
{
fprintf(stdout," ");
}
if ((ival3->operator)[0] == '+')
{
if ((ival3->amount)/100<= 9999999 && (ival3->amount)/100>1000000 )
{
ival3->outputamountprint[13]='\0';
fprintf(stdout,"| %13s ",ival3->outputamountprint);
}
else if (ival3->amount/100 > 9999999)
fprintf(stdout,"\?,\?\?\?,\?\?\?.\?\?");
else
{
if ((ival3->amount)/100>999 && (ival3->amount)/100<10000)
{
fprintf(stdout,"| ");
fprintf(stdout,"%13s ",ival3->outputamountprint);
}
else if ((ival3->amount)/100>9999 && (ival3->amount)/100<100000)
{
fprintf(stdout,"| ");
fprintf(stdout,"%13s ",ival3->outputamountprint);
}
else if ((ival3->amount)/100>99999 && (ival3->amount)/100<1000000)
{
fprintf(stdout,"| ");
fprintf(stdout,"%13s ",ival3->outputamountprint);
}
else if((ival3->amount)/100 <100)
{
fprintf(stdout,"| ");
fprintf(stdout,"%13s ",ival3->outputamountprint);
}
else if ((ival3->amount)/100>999999 && (ival3->amount)/100<10000000)
{
fprintf(stdout,"| ");
fprintf(stdout,"%13s ",ival3->outputamountprint);
}
else if((ival3->amount)/100 <= 999 && (ival3->amount)/100>100)
{
fprintf(stdout,"| ");
fprintf(stdout,"%13s ",ival3->outputamountprint);
}
}
}
else
{
if ((ival3->amount)/100<= 9999999 && (ival3->amount)/100>1000000 )
fprintf(stdout,"| (%12s) ",ival3->outputamountprint);
else if (ival3->amount/100 > 9999999)
fprintf(stdout,"(\?,\?\?\?,\?\?\?.\?\?)");
else
{
if ((ival3->amount)/100>999 && (ival3->amount)/100<10000)
{
fprintf(stdout,"| (");
fprintf(stdout,"%12s) ",ival3->outputamountprint);
}
else if ((ival3->amount)/100>9999 && (ival3->amount)/100<100000)
{
fprintf(stdout,"| (");
fprintf(stdout,"%12s) ",ival3->outputamountprint);
}
else if ((ival3->amount)/100>99999 && (ival3->amount)/100<1000000)
{
fprintf(stdout,"| (");
fprintf(stdout,"%12s) ",ival3->outputamountprint);
}
else if((ival3->amount)/100 <100)
{
fprintf(stdout,"| (");
fprintf(stdout,"%12s) ",ival3->outputamountprint);
}
else if ((ival3->amount)/100>999999 && (ival3->amount)/100<10000000)
{
fprintf(stdout,"| (");
fprintf(stdout,"%12s) ",ival3->outputamountprint);
}
else if((ival3->amount)/100 <= 999 && (ival3->amount)/100>100)
{
fprintf(stdout,"| (");
fprintf(stdout,"%12s) ",ival3->outputamountprint);
}
}
}
if (ival3->balances > 0)
{
//printf("balnace==%d\n",ival3->balances);
if ((ival3->balances)/100< 10000000 && (ival3->balances)/100>1000000 )
{//printf("Balance is===%s\n", ival3->outputbalanceprint);
fprintf(stdout,"| %13s ",ival3->outputbalanceprint);
}
else if (ival3->balances/100 > 9999999)
fprintf(stdout,"| \?,\?\?\?,\?\?\?.\?\? ");
else
{
if ((ival3->balances)/100>999 && (ival3->balances)/100<10000)
{
fprintf(stdout,"| ");
fprintf(stdout,"%13s ",ival3->outputbalanceprint);
}
else if ((ival3->balances)/100>9999 && (ival3->balances)/100<100000)
{
fprintf(stdout,"| ");
fprintf(stdout,"%13s ",ival3->outputbalanceprint);
}
else if ((ival3->balances)/100>99999 && (ival3->balances)/100<1000000)
{
fprintf(stdout,"| ");
fprintf(stdout,"%13s ",ival3->outputbalanceprint);
}
else if((ival3->balances)/100 <100)
{
fprintf(stdout,"| ");
fprintf(stdout,"%13s ",ival3->outputbalanceprint);
}
else if((ival3->balances)/100 <= 999 && (ival3->balances)/100>100)
{
fprintf(stdout,"| ");
// printf("Entered %14s" ,ival3->outputbalanceprint);
fprintf(stdout,"%13s ",ival3->outputbalanceprint);
}
}
}
else
{ ival3->balances=ival3->balances*(-1);
if ((ival3->balances)/100<= 9999999 && (ival3->balances)/100>=1000000 )
fprintf(stdout,"| (%12s) ",ival3->outputbalanceprint);
else if (ival3->balances/100> 9999999)
fprintf(stdout,"| (\?,\?\?\?,\?\?\?.\?\?) ");
else
{
if ((ival3->balances)/100>999 && (ival3->balances)/100<10000)
{
fprintf(stdout,"| (");
fprintf(stdout,"%12s) ",ival3->outputbalanceprint);
}
else if ((ival3->balances)/100>9999 && (ival3->balances)/100<100000)
{
fprintf(stdout,"| (");
fprintf(stdout,"%12s) ",ival3->outputbalanceprint);
}
else if ((ival3->balances)/100>99999 && (ival3->balances)/100<999999)
{
fprintf(stdout,"| (");
fprintf(stdout,"%12s) ",ival3->outputbalanceprint);
}
else if((ival3->balances)/100 <100)
{
fprintf(stdout,"| (");
fprintf(stdout,"%12s) ",ival3->outputbalanceprint);
}
else
{
fprintf(stdout,"| (");
fprintf(stdout,"%12s) ",ival3->outputbalanceprint);
}
}
}
fprintf(stdout,"|");
fprintf(stdout,"\n");
}
printheadline();
}
/* ----------------------- Sort() ----------------------- */
void timestampidentical(My402List *pList)
{
My402ListElem *elem1=NULL;
My402ListElem *elem2=NULL;
tfilevalues* ival1= NULL;
tfilevalues* ival2= NULL;
long t1,t2;
for (elem1=My402ListFirst(pList); elem1!= NULL; elem1=My402ListNext(pList, elem1)) {
ival1=(tfilevalues*)(elem1->obj);
t1= ival1->timestamp;
for (elem2=My402ListNext(pList, elem1); elem2 != NULL; elem2=My402ListNext(pList, elem2)) {
ival2=(tfilevalues*)(elem2->obj);
t2= ival2->timestamp;
if(t1==t2)
{
fprintf(stderr,"Timestamp identical in the input file. \n");
exit(1);
}
}
}
return;
}
static
void BubbleForward(My402List *pList, My402ListElem **pp_elem1, My402ListElem **pp_elem2)
/* (*pp_elem1) must be closer to First() than (*pp_elem2) */
{
My402ListElem *elem1=(*pp_elem1), *elem2=(*pp_elem2);
void *obj1=elem1->obj, *obj2=elem2->obj;
My402ListElem *elem1prev=My402ListPrev(pList, elem1);
/* My402ListElem *elem1next=My402ListNext(pList, elem1); */
/* My402ListElem *elem2prev=My402ListPrev(pList, elem2); */
My402ListElem *elem2next=My402ListNext(pList, elem2);
My402ListUnlink(pList, elem1);
My402ListUnlink(pList, elem2);
if (elem1prev == NULL) {
(void)My402ListPrepend(pList, obj2);
*pp_elem1 = My402ListFirst(pList);
} else {
(void)My402ListInsertAfter(pList, obj2, elem1prev);
*pp_elem1 = My402ListNext(pList, elem1prev);
}
if (elem2next == NULL) {
(void)My402ListAppend(pList, obj1);
*pp_elem2 = My402ListLast(pList);
} else {
(void)My402ListInsertBefore(pList, obj1, elem2next);
*pp_elem2 = My402ListPrev(pList, elem2next);
}
}
static
void BubbleSortForwardList(My402List *pList, int num_items)
{
My402ListElem *elem=NULL;
tfilevalues* cur_val;
tfilevalues* next_val;
int i=0;
timestampidentical(pList);
for (i=0; i < num_items; i++) {
int j=0, something_swapped=FALSE;
My402ListElem *next_elem=NULL;
for (elem=My402ListFirst(pList), j=0; j < num_items-i-1; elem=next_elem, j++) {
cur_val=(tfilevalues*)(elem->obj);
next_elem=My402ListNext(pList, elem);
next_val = (tfilevalues* )(next_elem->obj);
if ((cur_val->timestamp)> (next_val->timestamp)) {
BubbleForward(pList, &elem, &next_elem);
something_swapped = TRUE;
}
}
if (!something_swapped) break;
}
}
/* ----------------------- fileread() ----------------------- */
int counthenumberofdigits(long time1)
{
int countdigits=0;
while(time1 != 0)
{
time1= time1/10;
++countdigits;
}
return countdigits;
}
int fddigafdecimal(char* array)
{
int i,cnt=0;
for (i=0;i<strlen(array);i++)
{
if(array[i]!= '0')
cnt++;
}
return cnt;
}
char* removeleadingspacechar(char *descptr)
{
while(isspace(*descptr))
descptr++;
return descptr;
}
void fileread(FILE *fp)
{
My402List listform;
memset(&listform,0,sizeof(My402List));
memset(buf,0,sizeof(buf));
My402ListInit(&listform);
tfilevalues* value = NULL;
char* stringtoken =NULL;
// To include code for the command line inputs
char tab='\t';
char lsl = '\0';
char *delim;
char *lsdelim;
delim = &tab;
lsdelim = &lsl;
int numdigits;
int intpart;
//char* descptr;
char strbuf[20];
memset(strbuf,0,sizeof(strbuf));
while(fgets(buf,sizeof(buf), fp)!= NULL) // Traverses through the everyline of the function
{
value = (tfilevalues*)malloc(sizeof(tfilevalues)); // Creating a new structure for a line
int g,cnt=0;
if (strlen(buf) > 1024)
{
fprintf(stderr,"Line length in the file is greater than 1024 characters\n");
}
for(g=0;g<strlen(buf);g++)
{
if(buf[g]=='\t')
cnt++;
}
if(cnt !=3 )
{
fprintf(stderr,"Number of tabs in the file is not equal to 3\n");
exit(1);
}
//copy the transaction type from the file
stringtoken = strtok(buf,delim);
strncpy(value->operator,stringtoken,sizeof(value->operator));
if( (strcmp(stringtoken,"-") != 0) && (strcmp(stringtoken,"+") != 0)){
fprintf(stderr, "Transaction type unknown in the file .\n");
exit(1);
}
stringtoken = strtok(NULL,delim);
long time1=(long)atoi(stringtoken);
if (time1 > time(NULL))
{
fprintf(stderr, "Timestamp is bad in the file .\n");
exit(1);
}
if(strlen(stringtoken) >10){
fprintf(stderr, "Timestamp is bad in the file .\n");
exit(1);
}
value->timestamp = atol(stringtoken);
stringtoken = strtok(NULL,delim);
int amt2;
char *dec;
dec=strchr(stringtoken,'.');
dec++;
amt2=atoi(dec);
value->amount = atoi(stringtoken)*100+amt2;
if (value->amount < 0)
{
fprintf(stderr, "The transaction amount must be positive in the file .\n");
exit(1);
}
intpart = value->amount/100;
numdigits=counthenumberofdigits(intpart);
if(numdigits > 7){
fprintf(stderr, "The Integer part of amount field is not as expected(xxxxxxx.xx) in the tfile .\n");
exit(1);
}
if(strlen(strchr(stringtoken,'.')) >3){
fprintf(stderr, "The Fractional part of amount field is not as expected(xxxxxxx.xx) in the tfile .\n");
exit(1);
}
stringtoken = strtok(NULL,lsdelim);
stringtoken = removeleadingspacechar(stringtoken);
if(*stringtoken == 0){
fprintf(stderr, "Description field is blank.\n");
exit(1);
}
strncpy(value->description,stringtoken,sizeof(value->description));
My402ListAppend(&listform,value);
}
fclose(fp);
BubbleSortForwardList(&listform,listform.num_members);
printthedetails(&listform);
}
/* ----------------------- main() ----------------------- */
int main(int argc, char *argv[])
{
FILE *fp=NULL;
setlocale(LC_NUMERIC,"");
if (argc == 1)
{
fprintf(stderr, "Command unknown plese find the usage below.\n");
fprintf(stderr, "usage: warmup1 sort [tfile].\n");
return -1;
}
if ( strcmp(argv[1],"sort") != 0)
{
fprintf(stderr, "Command unknown plese find the usage below.\n");
fprintf(stderr, "usage: warmup1 sort [tfile].\n");
return -1;
}
if (argc == 3)
{
fp = fopen(argv[2], "r");
struct stat sb;
if (fp == NULL)
{
perror("Error");
return -1;
}
if (stat(argv[2], &sb) == 0 && S_ISDIR(sb.st_mode))
{
fprintf(stderr,"Error: This is a directory \n");
return -1;
}
fileread(fp);
}
if(argc == 2)
{
fileread(stdin);
}
return 0;
}
<file_sep>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <math.h>
#include <ctype.h>
#include <locale.h>
#include <pthread.h>
#include "cs402.h"
#include <signal.h>
#include <locale.h>
#include "my402list.h"
#define NUM_THREADS 5
/*Packet structure*/
typedef struct pack{
double lambda;
double rate;
long double timentsys;
long double timleasys;
long double timentQ1;
long double timleaQ1;
long double timentQ2;
long double timleaQ2;
long double timentS;
long double timleavS;
long double timinQ1;
long double timinQ2;
long double timinsys;
long double timinS;
int pid;
double mu;
int npackarr;
int numtokpack;
int totaltokens;
}packet;
/*Global variables*/
FILE *fp;
char filename[100];
char commandline[100];
int tracedriven;
double emulationtime=0;
int tokencount =0;
My402List formQ1;
My402List formQ2;
int packtid=1;
double tokenrate;
int totaltoken;
double servicetimeS;
long double timeentq1;
long double timeentq2;
int q1=1;
//Assign the default values to the tfile values given in the variable
/*Global variables for command line*/
double globallambda = 1;
double globalmu = 0.35;
double globalrate = 1.5;
int globaltotaltokens = 10;
int globalnpackarr = 20;
int globalnumtokpack =3;
int serverend;
int s1exit=0,s2exit=0;
/*Global variables for stats*/
long double averageInterarrival;
long double averagePacketService=0;
long double averageInQ1=0;
long double averageInQ2=0;
long double averageInS1=0;
long double averageInS2=0;
long double totalemualtiontime=0;
long double averageSysTime=0;
long double numdroppedpack = 0,numdroppedTok = 0;
long double averageSysTimeSqr;
double numpackservd = 0;
double numpackentrdQ1 = 0;
/*Global variable for control C*/
int cntC=0;
void setdefaultvalues(packet *pacptr)
{
pacptr->lambda = 1;
pacptr->rate = 1.5;
pacptr->mu = 0.35;
pacptr->npackarr= 20;
pacptr->numtokpack= 3;
pacptr->totaltokens= 10;
}
void Initialize(packet *pacptr)
{
pacptr->timentsys = 0.0;
pacptr->timleasys= 0.0;
pacptr->timentQ1 = 0.0;
pacptr->timleaQ1= 0.0;
pacptr->timentQ2 = 0.0;
pacptr->timleaQ2 = 0.0;
pacptr->timentS = 0.0;
pacptr->timleavS = 0.0;
pacptr->timinQ1 = 0.0;
pacptr->timinQ2 = 0.0;
pacptr->timinsys = 0.0;
pacptr->timinS = 0.0;
}
int id=0;
int tokenflag=0;
int packetexit=0;
/*global Pthread types */
pthread_t thread[NUM_THREADS];
pthread_mutex_t mutexappend;
pthread_cond_t cv;
sigset_t sig;
void *packetarrival(void *arg)
{
struct timeval tv;
long double interarrival=0;int tempflag=0;packtid =0;
if (tracedriven == 1)
{
char buf[1024];
memset(buf,0,sizeof(buf));
fp = fopen(filename,"r");
double prevtime=0;
if (fp == NULL)
{
perror("Error");
exit(1);
}
packet *pacptr = NULL;
fgets(buf,sizeof(buf),fp);
sscanf(buf,"%d",&globalnpackarr);
if(atoi(buf) == 0)
{
fprintf(stderr,"*****Aborted***** : input file is not in the right format\n");
exit(1);
}
while(fgets(buf,sizeof(buf),fp)!= NULL)
{
pacptr = (packet*)malloc(sizeof(packet));
Initialize(pacptr);
setdefaultvalues(pacptr);
packtid++;
sscanf(buf,"%lf\t%d\t%lf",&pacptr->lambda,&pacptr->numtokpack,&pacptr->mu);
pacptr->mu =(1/(pacptr->mu/1000));
pacptr->totaltokens = globaltotaltokens;
pacptr->rate= globalrate;
usleep((pacptr->lambda)*1000);
gettimeofday(&tv,NULL);
if (prevtime== 0)
{
pacptr->timentsys = ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
interarrival = pacptr->timentsys;
prevtime = pacptr->timentsys;
}
else
{
pacptr->timentsys = ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
interarrival = pacptr->timentsys-prevtime;
prevtime=pacptr->timentsys;
}
averageInterarrival += interarrival;
globalnumtokpack = pacptr->numtokpack;
pacptr->pid = packtid;
servicetimeS = (1/pacptr->mu)*1000;
pthread_mutex_lock(&mutexappend);
if(pacptr->numtokpack > pacptr->totaltokens)
{
fprintf(stdout,"%012.3Lfms: p%d arrives, needs %d tokens, inter-arrival time = %.3Lfms, dropped\n", pacptr->timentsys,pacptr->pid,pacptr->numtokpack,interarrival);
numdroppedpack++;
pthread_mutex_unlock(&mutexappend);
continue;
}
else
fprintf(stdout,"%012.3Lfms: p%d arrives, needs %d tokens, inter-arrival time = %.3Lfms\n", ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000 ,pacptr->pid,pacptr->numtokpack,interarrival);
//Append to the list
My402ListAppend(&formQ1,pacptr);
q1=1;
// Timestamp as it Enters Q1
gettimeofday(&tv,NULL);
pacptr->timentQ1 =((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000 ;
fprintf(stdout,"%012.3Lfms: p%d enters Q%d\n", ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000 ,pacptr->pid,q1);
numpackentrdQ1++;
if(pacptr->pid == globalnpackarr){
pthread_mutex_unlock(&mutexappend);
pthread_exit(NULL);
}
pthread_mutex_unlock(&mutexappend);
/*Mutex Unlocked*/
}
fclose(fp);
}
else if (tracedriven == 0)
{
// All the code is of the length
packet *pacptr = NULL;
int count = 0;
packtid=0;interarrival =(1/ globallambda)*1000;
double prevtime=0;
while(count < globalnpackarr)
{
pacptr = (packet*)malloc(sizeof(packet));
Initialize(pacptr);
count++;
packtid++;
//Copy the values of the file into variables sscanf(buf,"%lf\t%d\t%lf",&pacptr->lambda,&pacptr->numtokpack,&pacptr->mu);
pacptr->lambda = globallambda;
pacptr->numtokpack = globalnumtokpack;
pacptr->mu = globalmu;
averageInterarrival += interarrival;
if (prevtime== 0){
usleep(interarrival*1000);
gettimeofday(&tv,NULL);
pacptr->timentsys = ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
interarrival = pacptr->timentsys;
prevtime=pacptr->timentsys;
}
else
{
usleep(interarrival*1000);
gettimeofday(&tv,NULL);
pacptr->timentsys = ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
interarrival = pacptr->timentsys - prevtime;
prevtime=pacptr->timentsys;
}
globalnumtokpack = pacptr->numtokpack;
pacptr->pid = packtid;
pthread_mutex_lock(&mutexappend);
if(pacptr->numtokpack > globaltotaltokens)
{
fprintf(stdout,"%012.3Lfms: p%d arrives, needs %d tokens, inter-arrival time = %.3Lfms, dropped\n", pacptr->timentsys ,pacptr->pid,pacptr->numtokpack,interarrival);
numdroppedpack++;
tempflag =1;
pthread_mutex_unlock(&mutexappend);
continue;
}
else
fprintf(stdout,"%012.3Lfms: p%d arrives, needs %d tokens, inter-arrival time = %.3Lfms\n", ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000 ,pacptr->pid,pacptr->numtokpack,interarrival);
q1=1;
//Append to the list
My402ListAppend(&formQ1,(void*)pacptr);
// Timestamp as it Enters Q1
gettimeofday(&tv,NULL);
pacptr->timentQ1 =((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000 ;
fprintf(stdout,"%012.3Lfms: p%d enters Q%d\n", ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000 ,packtid,q1);
numpackentrdQ1++;
if(pacptr->pid == globalnpackarr){
pthread_mutex_unlock(&mutexappend);
pthread_exit(NULL);
}
pthread_mutex_unlock(&mutexappend);
}
if(tempflag ==1)
{
pthread_mutex_lock(&mutexappend);
serverend = globalnpackarr;
packetexit =1;
numdroppedpack = globalnpackarr;
pthread_cond_broadcast(&cv);
pthread_mutex_unlock(&mutexappend);
}
}
packetexit =1;
pthread_exit(NULL);
}
void *tokengenerator(void *arg)
{
// It would generate tokens at the rate of R and then it would check if the token is enough for the current packet
//packet *access= NULL;
struct timeval tv;
tokencount = 0;
My402ListElem *elem1 = NULL;
packet *packint = NULL;long double prevtime=0;long double tokeninterarrival =(1/globalrate)*1000; long double current_time=0.0;
packint =(packet*) malloc(sizeof(packet));
while (1)
{
if (prevtime== 0){
usleep(tokeninterarrival*1000);
gettimeofday(&tv,NULL);
current_time = ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
tokeninterarrival = current_time;
prevtime=current_time;
}
else
{
usleep(tokeninterarrival*1000);
gettimeofday(&tv,NULL);
current_time = ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
tokeninterarrival = current_time-prevtime;
prevtime=((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
}
if(packetexit == 1 && My402ListLength(&formQ1) ==0)
{
tokenflag = 1;
pthread_cond_broadcast(&cv);
pthread_mutex_unlock(&mutexappend);
break;
}
pthread_mutex_lock(&mutexappend);
tokencount++;
if(s1exit ==1 && s2exit ==1){
pthread_mutex_unlock(&mutexappend);
pthread_exit(NULL);}
gettimeofday(&tv,NULL);
id++;
if(tokencount <= globaltotaltokens)
fprintf(stdout,"%012.3Lfms: token t%d arrives, token bucket now has %d token\n", ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000 ,id,tokencount);
else if(tokencount > globaltotaltokens){
fprintf(stdout,"%012.3Lfms: token t%d arrives, dropped\n", ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000 ,id);
numdroppedTok++;
tokencount = globaltotaltokens;
}
struct timeval tv;
elem1 = My402ListFirst(&formQ1);
if (My402ListLength(&formQ1) !=0)
memcpy(packint,elem1->obj,sizeof(packet));
/*else {
pthread_mutex_unlock(&mutexappend);
break;
}*/
if(packint->pid > globalnpackarr /*packint->npackarr*/)
{
pthread_mutex_unlock(&mutexappend);
break;
}
if (My402ListEmpty(&formQ1) == 1)
{
pthread_mutex_unlock(&mutexappend);
continue;
}
else
{
if(tokencount < packint->numtokpack)
{
pthread_mutex_unlock(&mutexappend);
continue;
}
q1=1;
tokencount = tokencount - packint->numtokpack;
My402ListUnlink(&formQ1,elem1);
// Timestamp as it leaves Q1
gettimeofday(&tv,NULL);
packint->timleaQ1 = ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
packint->timinQ1 = packint->timleaQ1 - packint->timentQ1;
fprintf(stdout,"%012.3Lfms: p%d leaves Q%d, time in Q%d = %.3Lfms, token bucket now has %d token\n", ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000 ,packint->pid,q1,q1,packint->timinQ1,tokencount);
//Form Q2
averageInQ1 = averageInQ1 + packint->timinQ1;
q1= 2;
My402ListAppend(&formQ2,packint);
gettimeofday(&tv,NULL);
timeentq2 = ((double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
fprintf(stdout,"%012.3Lfms: p%d enters Q%d\n", ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000 ,packint->pid,q1);
if(My402ListEmpty(&formQ2)==0)
{
gettimeofday(&tv,NULL);
long double timeleaveq2 = ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
long double timeinq2= timeleaveq2 - timeentq2;
fprintf(stdout,"%012.3Lfms: p%d leaves Q%d, time in Q%d = %.3Lfms, token bucket now has %d token\n", ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000 ,packint->pid,q1,q1,timeinq2,tokencount);
averageInQ2 = averageInQ2 + timeinq2;
serverend = packint->pid;
pthread_cond_broadcast(&cv);
}
pthread_mutex_unlock(&mutexappend);
}
}
pthread_mutex_lock(&mutexappend);
tokenflag = 1;
pthread_cond_broadcast(&cv);
pthread_mutex_unlock(&mutexappend);
pthread_exit(NULL);
}
void *server1(void* arg)
{
// Functionalities that the server1 has to perform
//It has to serve the packets present in the Q1
// If Q is empty it has to sleep
//If Q is not empty it has to wake up to serve the packet
// Need to access the Q2
My402ListElem *elem = NULL;
packet *p = NULL;
p = (packet*) malloc(sizeof(packet));
int s1=1;struct timeval tv;
while(1)
{
pthread_mutex_lock(&mutexappend);
while (My402ListEmpty(&formQ2) == 1 ){
if(tokenflag == 1)
{
pthread_mutex_unlock(&mutexappend);
pthread_exit(NULL);
}
if(cntC ==1)
{
pthread_mutex_unlock(&mutexappend);
s1exit = 1;
pthread_exit(NULL);
}
if(serverend == globalnpackarr){
pthread_mutex_unlock(&mutexappend);
s1exit = 1;
pthread_exit(NULL);
}
pthread_cond_wait(&cv,&mutexappend);}
if(cntC ==1)
{
pthread_mutex_unlock(&mutexappend);
s1exit = 1;
pthread_exit(NULL);
}
elem = My402ListFirst(&formQ2);
memcpy(p,elem->obj,sizeof(packet));
gettimeofday(&tv,NULL);
p->timentS = ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
fprintf(stdout,"%012.3Lfms: p%d begins service at S%d, requesting %.3lfms of service\n",((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000,p->pid,s1,((1/p->mu)*1000));
numpackservd++;
My402ListUnlink(&formQ2,My402ListFirst(&formQ2));
pthread_mutex_unlock(&mutexappend);
usleep((1/p->mu)*1000000);
pthread_mutex_lock(&mutexappend);
gettimeofday(&tv,NULL);
p->timleavS = ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
p->timinS = p->timleavS - p->timentS;
p->timinsys = p->timleavS -p->timentsys;
fprintf(stdout,"%012.3Lfms: p%d departs from S%d, service time = %.3Lfms, time in system = %Lfms\n",((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000,p->pid,s1,p->timinS,p->timinsys);
averageInS1 = averageInS1 + p->timinS;
averageSysTime += p->timinsys;
averageSysTimeSqr += p->timinsys*p->timinsys;
if(p->pid == globalnpackarr)
{
pthread_mutex_unlock(&mutexappend);
s1exit = 1;
pthread_exit(NULL);
}
if(tokenflag ==1 &&My402ListLength(&formQ2) == 0)
{
pthread_mutex_unlock(&mutexappend);
break;
}
pthread_mutex_unlock(&mutexappend);
}
if(cntC ==1)
{
pthread_mutex_unlock(&mutexappend);
s1exit = 1;
pthread_exit(NULL);
}
s1exit = 1;
pthread_mutex_lock(&mutexappend);
pthread_cond_broadcast(&cv);
pthread_mutex_unlock(&mutexappend);
pthread_exit(NULL);
}
void *server2(void* arg)
{
// Functionalities that the server2 has to perform
//It has to serve the packets present in the Q1
// If Q is empty it has to sleep
//If Q is not empty it has to wake up to serve the packet
packet *p = NULL;
p = (packet*) malloc(sizeof(packet));
My402ListElem *elem = NULL;
int s1=2;struct timeval tv;
while(1)
{
pthread_mutex_lock(&mutexappend);
while (My402ListEmpty(&formQ2) == 1){
if(tokenflag == 1)
{
pthread_mutex_unlock(&mutexappend);
pthread_exit(NULL);
}
if(cntC ==1)
{
pthread_mutex_unlock(&mutexappend);
s2exit=1;
pthread_exit(NULL);
}
if(serverend == globalnpackarr){
pthread_mutex_unlock(&mutexappend);
s2exit=1;
pthread_exit(NULL);
}
pthread_cond_wait(&cv,&mutexappend);}
if(cntC ==1)
{
pthread_mutex_unlock(&mutexappend);
s2exit=1;
pthread_exit(NULL);
}
elem = My402ListFirst(&formQ2);
memcpy(p,elem->obj,sizeof(packet));
gettimeofday(&tv,NULL);
p->timentS = ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
fprintf(stdout,"%012.3Lfms: p%d begins service at S%d, requesting %.3lfms of service\n",((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000,p->pid,s1,(1/p->mu)*1000);
numpackservd++;
My402ListUnlink(&formQ2,elem);
pthread_mutex_unlock(&mutexappend);
usleep((1/p->mu)*1000000);
pthread_mutex_lock(&mutexappend);
gettimeofday(&tv,NULL);
p->timleavS = ((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
p->timinS = p->timleavS - p->timentS;
p->timinsys = p->timleavS -p->timentsys;
fprintf(stdout,"%012.3Lfms: p%d departs from S%d, service time = %.3Lfms, time in system = %.3Lfms\n",((long double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000,p->pid,s1,p->timinS,p->timinsys);
averageInS2 = averageInS2 + p->timinS;
averageSysTime += p->timinsys;
averageSysTimeSqr += p->timinsys*p->timinsys;
if(p->pid == globalnpackarr)
{
pthread_mutex_unlock(&mutexappend);
s2exit=1;
pthread_exit(NULL);
}
if(tokenflag ==1 &&My402ListLength(&formQ2) == 0)
{
pthread_mutex_unlock(&mutexappend);
break;
}
if(cntC ==1)
{
pthread_mutex_unlock(&mutexappend);
s2exit=1;
pthread_exit(NULL);
}
pthread_mutex_unlock(&mutexappend);
}
s2exit=1;
pthread_mutex_lock(&mutexappend);
pthread_cond_broadcast(&cv);
pthread_mutex_unlock(&mutexappend);
pthread_exit(NULL);
}
void *controlC()
{
int set;
My402ListElem *elem = NULL;
My402ListElem *elem1 = NULL;
sigwait(&sig,&set);
cntC =1;
pthread_mutex_lock(&mutexappend);
pthread_cancel(thread[0]);
pthread_cancel(thread[1]);
pthread_cond_broadcast(&cv);
for(elem = My402ListFirst(&formQ1); elem != NULL ; elem= My402ListNext(&formQ1,elem))
{
if(My402ListEmpty(&formQ1) == 1)
break;
fprintf(stdout, "\nP%d removed from Q1",((packet*)(elem->obj))->pid);
My402ListUnlink(&formQ1, elem);
}
for(elem1 = My402ListFirst(&formQ2); elem1 != NULL ; elem1= My402ListNext(&formQ2,elem1))
{
if(My402ListEmpty(&formQ2) == 1)
break;
fprintf(stdout, "\nP%d removed from Q2",((packet*)(elem1->obj))->pid);
My402ListUnlink(&formQ2, elem1);
}
fprintf(stdout, "\n");
pthread_mutex_unlock(&mutexappend);
pthread_exit(NULL);
}
void calculateStats()
{
double newnumpackets=0;
double localnpackarr=0;
localnpackarr = globalnpackarr;
newnumpackets = globalnpackarr - numdroppedpack;
if(newnumpackets ==0)
{
newnumpackets = globalnpackarr;
}
if(numpackentrdQ1 ==0)
{
numpackentrdQ1=1;
}
if(numpackservd ==0)
{
numpackservd=1;
}
if(cntC !=1)
{
averagePacketService = averageInS1 + averageInS2;
fprintf(stdout,"Statistics:\n\n");
fprintf(stdout,"\taverage packet inter-arrival time = %.6gs\n",(double)averageInterarrival/(1000*(localnpackarr)));
fprintf(stdout,"\taverage packet service time = %.6gs\n\n",(double)(averagePacketService/(1000*(newnumpackets))));
fprintf(stdout,"\taverage number of packets in Q1 = %.6g\n",(double)(averageInQ1/totalemualtiontime));
fprintf(stdout,"\taverage number of packets in Q2 = %.6g\n",(double)(averageInQ2/totalemualtiontime));
fprintf(stdout,"\taverage number of packets at S1 = %.6g\n",(double)(averageInS1/totalemualtiontime));
fprintf(stdout,"\taverage number of packets at S2 = %.6g\n\n",(double)(averageInS2/totalemualtiontime));
fprintf(stdout,"\taverage time a packet spent in system = %.6gs\n",(double)(averageSysTime/(1000*(newnumpackets))));
long double sd=0.0,var=0.0;
var = averageSysTimeSqr/(1000000*(newnumpackets)) - averageSysTime/(1000*(newnumpackets)) * averageSysTime/(1000*(newnumpackets));
if(var <0)
var= var*-1;
sd=sqrt(var);
double probpack;
double probtok;
probpack = numdroppedpack/localnpackarr;
probtok = numdroppedTok/id;
fprintf(stdout,"\tstandard deviation for time spent in system = %.6gs\n\n",(double)sd);
fprintf(stdout,"\ttoken drop probability = %.6g\n",probtok);
fprintf(stdout,"\tpacket drop probability = %.6g\n",probpack);
}
else
{
averagePacketService = averageInS1 + averageInS2;
fprintf(stdout,"Statistics:\n\n");
fprintf(stdout,"\taverage packet inter-arrival time = %.6gs\n",(double)averageInterarrival/(1000*(numpackentrdQ1)));
fprintf(stdout,"\taverage packet service time = %.6gs\n\n",(double)(averagePacketService/(1000*(numpackservd))));
fprintf(stdout,"\taverage number of packets in Q1 = %.6g\n",(double)(averageInQ1/totalemualtiontime));
fprintf(stdout,"\taverage number of packets in Q2 = %.6g\n",(double)(averageInQ2/totalemualtiontime));
fprintf(stdout,"\taverage number of packets at S1 = %.6g\n",(double)(averageInS1/totalemualtiontime));
fprintf(stdout,"\taverage number of packets at S2 = %.6g\n\n",(double)(averageInS2/totalemualtiontime));
fprintf(stdout,"\taverage time a packet spent in system = %.6gs\n",(double)(averageSysTime/(1000*(numpackservd))));
long double sd=0.0,var=0.0;
var = averageSysTimeSqr/(1000000*(numpackservd)) - averageSysTime/(1000*(numpackservd)) * averageSysTime/(1000*(numpackservd));
if(var <0)
var= var*-1;
sd=sqrt(var);
double probpack;
double probtok;
probpack = numdroppedpack/localnpackarr;
probtok = numdroppedTok/id;
fprintf(stdout,"\tstandard deviation for time spent in system = %.6gs\n\n",(double)sd);
fprintf(stdout,"\ttoken drop probability = %.6g\n",probtok);
fprintf(stdout,"\tpacket drop probability = %.6g\n",probpack);
}
}
/*The main thread for execution of the statement */
int main (int argc, char *argv[])
{
if (argc < 2 && argc >13)
{
fprintf(stderr, "Malformed command!!.. Usage --> warmup2 [-lambda lambda] [-mu mu] [-r r] [-B B] [-P P] [-n num] [-t tsfile]");
return -1;
}
FILE *fpmain;
sigemptyset(&sig);
struct stat sb;
sigaddset(&sig, SIGINT);
pthread_sigmask(SIG_BLOCK, &sig,NULL);
packet* pacptr = malloc(sizeof(packet));
setdefaultvalues(pacptr);
void *join;
//fp = fopen(argv[2], "r");
/*
*/
sprintf(commandline,"%s",*argv);
memset(&formQ1,0,sizeof(My402List));
My402ListInit(&formQ1);
/*This is the list for queue Q2*/
memset(&formQ2,0,sizeof(My402List));
My402ListInit(&formQ2);
if (argc > 1 )
{
tracedriven = 0;
int i;
for (i=1;argv[i] != NULL;i=i+2)
{
if(strcmp(argv[i],"-lambda") == 0)
{
if(argc >i+1)
{
if(argv[i+1][0] != '-')
{
sscanf(argv[i+1], "%lf", &globallambda);
if ((1/globallambda) > 10)
globallambda = 0.1;
}
else
{
fprintf(stderr, "Malformed command!!.. Usage --> warmup2 [-lambda lambda] [-mu mu] [-r r] [-B B] [-P P] [-n num] [-t tsfile]\n");
return -1;
}
}
else
{
fprintf(stderr, "Malformed command!!.. Usage --> warmup2 [-lambda lambda] [-mu mu] [-r r] [-B B] [-P P] [-n num] [-t tsfile]\n");
return -1;
}
}
else if(strcmp(argv[i],"-mu") == 0)
{
if(argc >i+1)
{
if(argv[i+1][0] != '-')
{
sscanf(argv[i+1], "%lf", &globalmu);
if ((1/globalmu) >10)
globalmu =0.1;
}
else
{
fprintf(stderr, "Malformed command!!.. Usage --> warmup2 [-lambda lambda] [-mu mu] [-r r] [-B B] [-P P] [-n num] [-t tsfile]\n");
return -1;
}
}
else
{
fprintf(stderr, "Malformed command!!.. Usage --> warmup2 [-lambda lambda] [-mu mu] [-r r] [-B B] [-P P] [-n num] [-t tsfile]\n");
return -1;
}
}
else if(strcmp(argv[i],"-r") == 0)
{
if(argc >i+1)
{
if(argv[i+1][0] != '-')
{
sscanf(argv[i+1], "%lf", &globalrate);
if ((1/globalrate) >10)
globalrate = 0.1;
}
else
{
fprintf(stderr, "Malformed command!!.. Usage --> warmup2 [-lambda lambda] [-mu mu] [-r r] [-B B] [-P P] [-n num] [-t tsfile]\n");
return -1;
}
}
else
{
fprintf(stderr, "Malformed command!!.. Usage --> warmup2 [-lambda lambda] [-mu mu] [-r r] [-B B] [-P P] [-n num] [-t tsfile]\n");
return -1;
}
}
else if(strcmp(argv[i],"-B") == 0)
{
if(argc >i+1)
{
if(argv[i+1][0] != '-')
{
globaltotaltokens = atoi(argv[i+1]);
}
else
{
fprintf(stderr, "Malformed command!!.. Usage --> warmup2 [-lambda lambda] [-mu mu] [-r r] [-B B] [-P P] [-n num] [-t tsfile]\n");
return -1;
}
}
else
{
fprintf(stderr, "Malformed command!!.. Usage --> warmup2 [-lambda lambda] [-mu mu] [-r r] [-B B] [-P P] [-n num] [-t tsfile]\n");
return -1;
}
}
else if(strcmp(argv[i],"-n") == 0)
{
if(argc >i+1)
{
if(argv[i+1][0] != '-')
{
globalnpackarr = atoi(argv[i+1]);
}
else
{
fprintf(stderr, "Malformed command!!.. Usage --> warmup2 [-lambda lambda] [-mu mu] [-r r] [-B B] [-P P] [-n num] [-t tsfile]\n");
return -1;
}
}
else
{
fprintf(stderr, "Malformed command!!.. Usage --> warmup2 [-lambda lambda] [-mu mu] [-r r] [-B B] [-P P] [-n num] [-t tsfile]\n");
return -1;
}
}
else if(strcmp(argv[i],"-P") == 0)
{
if(argc >i+1)
{
if(argv[i+1][0] != '-')
{
globalnumtokpack = atoi(argv[i+1]);
}
else
{
fprintf(stderr, "Malformed command!!.. Usage --> warmup2 [-lambda lambda] [-mu mu] [-r r] [-B B] [-P P] [-n num] [-t tsfile]\n");
return -1;
}
}
else
{
fprintf(stderr, "Malformed command!!.. Usage --> warmup2 [-lambda lambda] [-mu mu] [-r r] [-B B] [-P P] [-n num] [-t tsfile]\n");
return -1;
}
}
else if(strcmp(argv[i],"-t") == 0)
{
tracedriven =1;
if(argv[i+1] ==NULL)
{
fprintf(stderr, "File Name not specified\n");
exit(0);
}
sprintf(filename,"%s",argv[i+1]);
fpmain = fopen(filename,"r");
if (fpmain == NULL)
{
perror("Error");
exit(1);
}
sprintf(filename,"%s",argv[i+1]);
if (stat(filename, &sb) == 0 && S_ISDIR(sb.st_mode))
{
fprintf(stderr,"Error: This is a directory \n");
exit(1);
}
fclose(fpmain);
}
else
{
fprintf(stderr, "Malformed command!!.. Usage --> warmup2 [-lambda lambda] [-mu mu] [-r r] [-B B] [-P P] [-n num] [-t tsfile]\n");
return -1;
}
}
}
if(tracedriven == 1)
{
fprintf(stdout,"Emulation Parameters:\n");
fprintf(stdout,"P = %d\n",globalnpackarr);
fprintf(stdout,"r = %.2lf\n",globalrate);
fprintf(stdout,"B = %d\n",globaltotaltokens);
fprintf(stdout,"tsfile = %s\n\n",filename);
}
else if(tracedriven == 0)
{
fprintf(stdout,"Emulation Parameters:\n");
fprintf(stdout,"lambda = %.2lf\n",globallambda);
fprintf(stdout,"mu = %.2lf\n",globalmu);
fprintf(stdout,"r = %.2lf\n",globalrate);
fprintf(stdout,"B = %d\n",globaltotaltokens);
fprintf(stdout,"P = %d\n\n",globalnpackarr);
}
struct timeval tv;
gettimeofday(&tv,NULL);
emulationtime = (double)tv.tv_sec*1000000+tv.tv_usec;
//tokenrate = pacptr->rate;
//totaltoken = pacptr->totaltokens;
//Token Generator thread
pthread_create(&thread[0],0,tokengenerator,0);
//Packet arrival thread
pthread_create(&thread[1],0,packetarrival,0);
//Server1 Thread
pthread_create(&thread[2],0,server1,0);
//Server2 thread
pthread_create(&thread[3],0,server2,0);
//Monitor Thread
pthread_create(&thread[4],0,controlC,0);
fprintf(stdout,"00000000.000ms: Emulation Begins\n");
// Token Generation thread is created
//pthread_create(&thread[1],0,tokengenerator,(void *)1);
//Initialize the variables of the packet
pthread_join(thread[0],&join);
pthread_join(thread[1],&join);
pthread_join(thread[2],&join);
pthread_join(thread[3],&join);
//pthread_join(thread[4],&join);
//Create the threads for executing the sequence
gettimeofday(&tv,NULL);
totalemualtiontime = ((double)tv.tv_sec*1000000+tv.tv_usec - emulationtime)/1000;
fprintf(stdout,"%012.3Lfms: Emulation ends\n",totalemualtiontime);
calculateStats();
/*Create the thread-1 packet arrival thread*/
// Append it to the list
// Create the structure
//printf("Average Time in system %.6g ,,,,, %lf,,,,,,,%lf\n",,averageInQ1,totalemualtiontime);
return 0;
}
<file_sep>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include "cs402.h"
#include "my402list.h"
// This is the function to create an anchor which is used to reference the list... And this anchor is initialized by pointing its next and previous to itself
int My402ListInit(My402List* list)
{
list->anchor.next = list->anchor.prev = &list->anchor;
list->anchor.obj = NULL;
return 1;
}
//Function to find the length of the list
int My402ListLength(My402List* list)
{
return list->num_members;
}
// Function to find if the list is empty it returns 1 if the list is empty and 0 if list is not wmpty
int My402ListEmpty(My402List* list)
{
if (list->anchor.next == &list->anchor)
return 1;
return 0;
}
//Function to return the first element in the list
My402ListElem *My402ListFirst(My402List* list)
{
if (My402ListEmpty(list) == 1)
return NULL;
return list->anchor.next;
}
//Function to return the last element of the list
My402ListElem *My402ListLast(My402List* list)
{
if(My402ListEmpty(list) == 1)
return NULL;
else
return list->anchor.prev;
}
// Function to return the next element to the current element
My402ListElem *My402ListNext(My402List* list, My402ListElem* elem)
{
if(elem == My402ListLast(list))
return NULL;
return elem->next;// actually we need to return the next element
}
// Function to return the previous elemtn in the list
My402ListElem *My402ListPrev(My402List* list, My402ListElem* elem)
{
if(elem == My402ListFirst(list))
return NULL;
return elem->prev; // Not understading why therer is a list arguement passed to this function
}
//Function to append the a list, for this we create a list dynamically and assign links from the anchor
int My402ListAppend(My402List* list, void* obj)
{
// Create a list element
My402ListElem* elem = NULL;
My402ListElem *elemptr = NULL;
elemptr = My402ListLast(list);
elem = (My402ListElem *)malloc(sizeof(My402ListElem));
if (elem == NULL )
{
printf("OutOfMemory");
exit(-1);
}
//list->num_members = list->num_members +1;
elem->obj = obj;
// Assign links to the anchor
if (My402ListEmpty(list ) == 1)
{
list->anchor.prev = list->anchor.next = elem;
elem->next = &list->anchor;
elem->prev = &list->anchor;
list->num_members = list->num_members +1;
}
else
{
// we have to traverse till the end of the loop and then add the links
elemptr->next = elem;
elem->next = &list->anchor;
elem->prev = elemptr;
list->anchor.prev = elem;
list->num_members = list->num_members +1;
}
return 1;
}
// Function to add the node at the head just after the anchor
int My402ListPrepend(My402List* list, void* obj)
{
My402ListElem* elem = NULL;
elem = (My402ListElem *)malloc(sizeof(My402ListElem));
if (elem == NULL )
{
printf("OutOfMemory");
exit(-1);
}
//list->num_members = list->num_members +1;
elem->obj = obj;
if (My402ListEmpty(list ) == 1)
{
list->anchor.prev = list->anchor.next = elem;
elem->next = &list->anchor;
elem->prev = &list->anchor;
list->num_members = list->num_members +1;
}
else
{
My402ListElem *first= list->anchor.next;
list->anchor.next = elem;
elem->prev = &list->anchor;
elem->next=first;
first->prev=elem;
// My402ListElem* oldhead = My402ListNext(list,elem);
// oldhead->prev = elem;
list->num_members = list->num_members +1;
}
return 1;
}
void My402ListUnlink(My402List* list, My402ListElem* elem)
{
My402ListElem* temp = NULL;
My402ListElem* temp1 = NULL;
if (list->num_members == 1)
{
list->anchor.next=list->anchor.prev=&list->anchor;
free(My402ListFirst(list));
list->num_members = list->num_members -1 ;
return ;
}
else if(elem->next == &list->anchor)
{
elem->prev->next = &list->anchor;
list->anchor.prev = elem->prev;
free(elem);
list->num_members = list->num_members - 1;
return ;
}
else
{
temp = elem->prev;
temp1=elem->next;
temp->next=temp1;
temp1->prev=temp;
free(elem);
list->num_members = list->num_members - 1;
}
}
void My402ListUnlinkAll(My402List* list)
{
My402ListElem *elem=NULL;
for (elem=My402ListFirst(list);elem !=&list->anchor;elem=My402ListNext(list, elem)){
//free(elem);
//list->num_members = list->num_members - 1;
My402ListUnlink(list,elem);
}
}
int My402ListInsertAfter(My402List* list, void* obj, My402ListElem* elem)
{
if(elem == NULL)
{
My402ListAppend(list,obj);
return 1;
}
My402ListElem *newnext = elem->next;
My402ListElem* newelem = NULL;
newelem = (My402ListElem *)malloc(sizeof(My402ListElem));
if (newelem == NULL )
{
printf("OutOfMemory");
exit(-1);
}
list->num_members = list->num_members +1;
newelem->obj = obj;
newelem->next = newnext;
newelem->prev=elem;
newnext->prev = newelem;
elem->next = newelem;
return 1;
}
int My402ListInsertBefore(My402List* list, void* obj, My402ListElem* elem)
{
if(elem == NULL)
{
My402ListPrepend(list,obj);
return 1;
}
My402ListElem *newprev = elem->prev;
My402ListElem* newelem = NULL;
newelem = (My402ListElem *)malloc(sizeof(My402ListElem));
if (newelem == NULL )
{
printf("OutOfMemory");
exit(-1);
}
list->num_members = list->num_members +1;
newelem->obj = obj;
newelem->next = elem;
newelem->prev = newprev;
newprev->next = newelem;
elem->prev = newelem;
return 1;
}
My402ListElem *My402ListFind(My402List* list, void* obj)
{
My402ListElem *elem = NULL;
for (elem=My402ListFirst(list);elem != NULL;elem=My402ListNext(list, elem))
{
if (elem->obj == obj)
return elem;
}
return NULL;
}
|
9c243adb77122ca69e34dd369e89c099382f4719
|
[
"C"
] | 3
|
C
|
arcLinx/CS402
|
2e0751f427c987a50a5492b88f3d663280d93540
|
357b8b1d8552d040a7406184e8773ab7556048d3
|
refs/heads/master
|
<repo_name>yanghu/dotfiles<file_sep>/scripts/dependency_install.sh
#!/bin/bash
DOTFILES_DIR="$HOME/.dotfiles"
change_to_zsh() {
if [ "$(echo "$SHELL" | grep -c "zsh")" -eq "0" ]; then
echo "Setting shell to zsh"
chsh -s "$(which zsh)"
else
echo "zsh is already the default shell"
fi
}
create_ssh() {
mkdir -p "$HOME"/.ssh
chmod 0700 "$HOME"/.ssh
}
fonts_install() {
echo "Installing fonts..."
if ! [ -d ~/.local/share/fonts ]; then
"$DOTFILES_DIR"/fonts/install.sh
else
echo "Fonts already installed"
fi
echo "Finished fonts"
}
local_install() {
echo "Installing local packages..."
if [ "$(uname)" = "Linux" ]; then
"$DOTFILES_DIR"/scripts/apt_setup.sh
else
echo "No local packages to install..."
fi
echo "Finished installing local packages"
}
install() {
fonts_install
local_install
}
create_ssh
change_to_zsh
install
<file_sep>/zsh/settings.zsh
## ============================================================================
## Settings
## ============================================================================
# Vim mode
# bindkey -v
bindkey '^r' history-incremental-search-backward
bindkey -M "vicmd" 'k' history-substring-search-up
bindkey -M "vicmd" 'j' history-substring-search-down
# Run `bindkey -l` to see a list of modes, and `bindkey -M foo` to see a list
# of commands active in mode foo
# Move to vim escape mode
bindkey -M "viins" kj vi-cmd-mode
bindkey -M "viins" kk vi-cmd-mode
# Unmap ctrl-s as "stop flow"
stty stop undef
# Shift-tab to cycle backwards in autocompletions
bindkey '^[[Z' reverse-menu-complete
# don't autocorrect
unsetopt correctall
# Don't save duplicated entries into history
setopt hist_ignore_all_dups
# ============================================================================
# Configure Plugins
# ============================================================================
# zsh-autosuggestions
# Bind <CTRL><SPC> to accept
bindkey '^ ' autosuggest-accept
# ============================================================================
# SSH
# ============================================================================
# start agent
[ -z "$SSH_AUTH_SOCK" ] && eval "$(ssh-agent -s)"
# ============================================================================
# FZF
# ============================================================================
#[ -f /usr/share/doc/fzf/examples/key-bindings.zsh ] && source /usr/share/doc/fzf/examples/key-bindings.zsh
#[ -f /usr/share/doc/fzf/examples/completion.zsh ] && source /usr/share/doc/fzf/examples/completion.zsh
<file_sep>/.zshrc
# Path to your oh-my-zsh installation.
export ZSH=/Users/huey/.oh-my-zsh
DEFAULT_USER=huey
# Set name of the theme to load.
# Look in ~/.oh-my-zsh/themes/
# Optionally, if you set this to "random", it'll load a random theme each
# time that oh-my-zsh is loaded.
#ZSH_THEME="robbyrussell"
ZSH_THEME="agnoster"
# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"
# Uncomment the following line to use hyphen-insensitive completion. Case
# sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"
# Uncomment the following line to disable bi-weekly auto-update checks.
# DISABLE_AUTO_UPDATE="true"
# Uncomment the following line to change how often to auto-update (in days).
# export UPDATE_ZSH_DAYS=13
# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"
# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"
# Uncomment the following line to enable command auto-correction.
# ENABLE_CORRECTION="true"
# Uncomment the following line to display red dots whilst waiting for completion.
# COMPLETION_WAITING_DOTS="true"
# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"
# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# HIST_STAMPS="mm/dd/yyyy"
# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder
# Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*)
# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(git docker docker-compose)
# User configuration
export PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/texbin::/usr/local/go/bin"
export
# export MANPATH="/usr/local/man:$MANPATH"
export PYTHON_PATH=~/bin/python_files
#for docker
export DOCKER_HOST=tcp://192.168.59.103:2375
#set -x DOCKER_CERT_PATH /Users/huey/.boot2docker/certs/boot2docker-vm
unset DOCKER_TLS_VERIFY
unset DOCKER_CERT_PATH
#set -x DOCKER_TLS_VERIFY 1
#for some vim plugin
export DYLD_FORCE_FLAT_NAMESPACE=1
export GOPATH=/Users/huey/Repos/golang
source $ZSH/oh-my-zsh.sh
# You may need to manually set your language environment
# export LANG=en_US.UTF-8
# Preferred editor for local and remote sessions
if [[ -n $SSH_CONNECTION ]]; then
export EDITOR='vim'
else
export EDITOR='vim'
fi
# Compilation flags
# export ARCHFLAGS="-arch x86_64"
# ssh
# export SSH_KEY_PATH="~/.ssh/dsa_id"
# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"
alias fig="docker-compose"
# copied from .bash_aliases 2001.07.19
# -------------------------------------------------------------------
# some alias settings, just for fun
# -------------------------------------------------------------------
#alias 'today=calendar -A 0 -f ~/calendar/calendar.mark | sort'
alias 'today=calendar -A 0 -f /usr/share/calendar/calendar.mark | sort'
alias 'dus=du -sckx * | sort -nr'
alias 'adventure=emacs -batch -l dunnet'
alias 'mailsize=du -hs ~/Library/mail'
alias 'bk=cd $OLDPWD'
alias 'ttop=top -ocpu -R -F -s 2 -n30'
alias lh='ls -a | egrep "^\."'
# -------------------------------------------------------------------
# Git
# -------------------------------------------------------------------
alias ga='git add'
alias gp='git push'
alias gl='git log'
alias gs='git status'
alias gd='git diff'
alias gm='git commit -m'
alias gma='git commit -am'
alias gb='git branch'
alias gc='git checkout'
alias gra='git remote add'
alias grr='git remote rm'
alias gpu='git pull'
alias gcl='git clone'
alias gta='git tag -a -m'
alias gf='git reflog'
# -------------------------------------------------------------------
# Functions ported directly from .bashrc
# -------------------------------------------------------------------
# turn hidden files on/off in Finder
function hiddenOn() { defaults write com.apple.Finder AppleShowAllFiles YES ; }
function hiddenOff() { defaults write com.apple.Finder AppleShowAllFiles NO ; }
# postgres functions
function psqlstart() { /usr/local/pgsql/bin/pg_ctl -D /usr/local/pgsql/data -l logfile start ; }
function psqlstop() { /usr/local/pgsql/bin/pg_ctl stop ; }
# view man pages in Preview
function pman() { ps=`mktemp -t manpageXXXX`.ps ; man -t $@ > "$ps" ; open "$ps" ; }
# myIP address
function myip() {
ifconfig lo0 | grep 'inet ' | sed -e 's/:/ /' | awk '{print "lo0 : " $2}'
ifconfig en0 | grep 'inet ' | sed -e 's/:/ /' | awk '{print "en0 (IPv4): " $2 " " $3 " " $4 " " $5 " " $6}'
ifconfig en0 | grep 'inet6 ' | sed -e 's/ / /' | awk '{print "en0 (IPv6): " $2 " " $3 " " $4 " " $5 " " $6}'
ifconfig en1 | grep 'inet ' | sed -e 's/:/ /' | awk '{print "en1 (IPv4): " $2 " " $3 " " $4 " " $5 " " $6}'
ifconfig en1 | grep 'inet6 ' | sed -e 's/ / /' | awk '{print "en1 (IPv6): " $2 " " $3 " " $4 " " $5 " " $6}'
}
<file_sep>/vim_init.sh
#!/usr/bin/env bash
#this script is originated from
#http://sontek.net/blog/detail/turning-vim-into-a-modern-python-ide
#© <NAME> <<EMAIL>> 2011
#usage:
#for pydoc. use <leader>pw when cursor on a word
#for flake8, press F7
#for
#TODO: install ctags for tagbar
#http://majutsushi.github.io/tagbar/
sudo apt-get install ctags\
cmake\
python2.7\
python-dev\
build-essential
#install flake8
sudo pip install flake8
mkdir -p ~/.vim/autoload ~/.vim/bundle && \
curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim
cd ~/.vim/bundle
#sensible
git clone https://github.com/tpope/vim-sensible.git
#numbers.vim
git clone https://github.com/myusuf3/numbers.vim
#airline sattus bar. Remember to run :Helptags to generate help tags
git clone https://github.com/bling/vim-airline
vim -u NONE -c "helptags vim-airline/doc" -c q
git clone https://github.com/kien/ctrlp.vim
git clone https://github.com/easymotion/vim-easymotion
git clone https://github.com/tpope/vim-fugitive
vim -u NONE -c "helptags vim-fugitive/doc" -c q
git clone https://github.com/airblade/vim-gitgutter
git clone https://github.com/majutsushi/tagbar.git
#color
git clone https://github.com/altercation/vim-colors-solarized.git
#inde guides. default toggle mapping: <leader>ig
git clone https://github.com/nathanaelkane/vim-indent-guides.git
#syntax check. run :SyntasticInfo to see running checkers.
# with "unimpared", use "[l" and "]l" to go through errors
#lclose to close it
git clone https://github.com/scrooloose/syntastic.git
vim -u NONE -c "helptags syntastic/doc" -c q
#toggle curser for insert mode
git clone https://github.com/jszakmeister/vim-togglecursor
git clone https://github.com/ervandew/supertab.git
git clone https://github.com/SirVer/ultisnips
git clone https://github.com/honza/vim-snippets
git clone https://github.com/tpope/vim-surround.git
git clone https://github.com/Raimondi/delimitMate
# git clone https://github.com/scrooloose/nerdcommenter
# vim -u NONE -c "helptags nerdcommenter/doc" -c q
git clone https://github.com/tpope/vim-commentary.git
git clone https://github.com/tpope/vim-unimpaired.git
git clone https://github.com/sjl/gundo.vim
git clone https://github.com/xolox/vim-easytags
git clone https://github.com/xolox/vim-misc
git clone https://github.com/scrooloose/nerdtree.git
git clone https://github.com/Valloric/YouCompleteMe.git
cd YouCompleteMe
git submodule update --init --recursive
./install.sh --clang-completer --gocode-completer
#for fish shell, do this
#cat "set -x DYLD_FORCE_FLAT_NAMESPACE 1" >> ~/.config/fish/config.fish
######## Optional plugins
# git clone https://github.com/klen/python-mode.git
# git clone https://github.com/fatih/vim-go
cd ~/.vim
git submodule init
git submodule update
git submodule foreach git submodule init
git submodule foreach git submodule update
touch ~/.vimrc
mv ~/.vimrc ~/.vimrc.orig
ln -s `pwd`/.vimrc ~/.vimrc
#cp .vimrc ~/.vimrc
#mkdir -p ~/.vim/UltiSnips/
#cp ./.vim/UltiSnips/* ~/.vim/UltiSnips/
ln -s `pwd`/.vim/UltiSnips ~/.vim/UltiSnips
# Install powerline fonts fir airline (optional)
# mkdir -p ~/tmp/
# git clone https://github.com/powerline/fonts.git ~/tmp/powerline_fonts
# ~/tmp/powerline_fonts/install.sh
<file_sep>/scripts/apt_setup.sh
#!/bin/bash
# Essentials
sudo apt-get install \
cmake \
colordiff \
curl \
exuberant-ctags \
fzf \
gawk \
git \
golang \
htop \
nodejs \
npm \
perl \
python-dev \
python3-dev \
ripgrep \
shellcheck \
tmux \
tree \
vim-nox \
xclip \
zsh
echo -n "Do you want to install QMK related packages(y/n)? "
read answer
if [ "$answer" != "${answer#[Yy]}" ] ;then
echo "Installing QMK packages..."
# QMK things
sudo apt-get install \
avr-libc \
binutils-arm-none-eabi \
binutils-avr \
dfu-programmer \
dfu-util \
gcc \
gcc-arm-none-eabi \
gcc-avr \
libnewlib-arm-none-eabi \
teensy-loader-cli \
unzip \
wget \
zip
else
echo "Skipped QMK install..."
fi
<file_sep>/zsh/plugins.zsh
# Path to your oh-my-zsh installation.
export ZSH="$HOME/.oh-my-zsh"
plugins=(adb alias-tips common-aliases extract fasd history git zsh-completions)
source $ZSH/oh-my-zsh.sh
source ~/.zsh/zsh-async/async.zsh
source ~/.zsh/powerlevel10k/powerlevel10k.zsh-theme
# Base16 Shell
source ~/.config/base16-shell/base16-shell.plugin.zsh
# To customize prompt, run `p11k configure` or edit ~/.p10k.zsh.
[[ ! -f ~/.zsh/p10k.zsh ]] || source ~/.zsh/p10k.zsh
[[ ! -f ~/.p10k_local.zsh ]] || source ~/.p10k_local.zsh
<file_sep>/golang_init.sh
#install golang
sudo apt-get install golang
#install necessary tools
go get golang.org/x/tools/cmd/goimports
<file_sep>/scripts/minimal_apt_setup.sh
#!/bin/bash
# Essentials
sudo apt-get install \
colordiff \
curl \
git \
htop \
nodejs \
npm \
perl \
tmux \
tree \
vim-nox \
zsh
|
ba6dfe6470b52f0370da60c95c1bf42ed7dcda73
|
[
"Shell"
] | 8
|
Shell
|
yanghu/dotfiles
|
bfce99531002dbea7c04a5e8c84662e9950bb06e
|
bc55a6f8e409eb40380d41d5e7efee6510858a77
|
refs/heads/master
|
<file_sep># README
Clone
Usage:
bundle install
rake db:create
rake db:migrate
rails s
--------------------------
For new clones run:
rails c
$>s = Setting.new
%>s.save
<file_sep>class SettingsController < ApplicationController
def new
end
def index
end
def edit
@setting = Setting.find(params[:id])
end
def update
@setting = Setting.find(params[:id])
if @setting.update_attributes(setting_params)
flash[:success] = 'Updated Successfully'
redirect_to root_path
end
end
private
#settings_params
def setting_params
params.require(:setting).permit(:index_v,:country_v,:country_code_v,:threat_tri_v,:host_v,:threat_id_v,:risk_v,:asn_v,:asn_registry_v)
end
end
<file_sep>#require 'elasticsearch-persistence'
File.open('public/elasticsearch_cert.pem', 'w') { |file| file.write(Rails.application.secrets.PEM) }
url_key = Rails.application.secrets['URL']
puts url_key
config = {
host: url_key,
transport_options: { ssl: {
ca_file: 'public/elasticsearch_cert.pem',
}
}
}
Elasticsearch::Persistence.client = Elasticsearch::Client.new(config)
<file_sep>class SearchController < ApplicationController
require 'elasticsearch/persistence/model'
require 'elasticsearch/dsl'
def settings
end
def index
#Search.connection
#@Search = Search.search(query: { match: {country_code: params[:q]}}) unless params[:q].nil?
if !params[:q]
@Search = Search.search(query: { match: {country_code: 'eth'}})# unless params[:q].nil?
else
@Search = Search.search(query: { match: {country_code: params[:q]}}) unless params[:q].nil?
end
#byebug
end
def edit
@Search = Search.search(query:{match: {_id: params[:id]}}).first
end
def update
@s = Search.search(query:{match: {_id: params[:id]}}).first
@s.update_attributes(
threat_id: params[:threat_id],
asn_registry: params[:asn_registry],
threat_tri: params[:threat_tri].to_f,
risk: params[:risk].to_f,
country: params[:country],
asn: params[:asn]
)
# if @s.save
# #byebug
#sleep 3
flash[:success] = 'Record successfully updated!'
redirect_to search_index_path
# else
# sleep 3
# flash[:warning] = 'Something went wrong'
# redirect_to search_index_path
# end
end
def destroy
begin
@s = Search.search(query:{match: {_id: params[:id]}}).first
#@s.destroy
#
@s.destroy
flash[:success] = 'Record successfully deleted!' if @s.destroyed?
rescue
end
#sleep 3
redirect_to search_index_path
end
end
<file_sep>class Search < ApplicationRecord
#require 'elasticsearch-persistence'
include Elasticsearch::Persistence::Model
#include Elasticsearch::Model::Callbacks
include Elasticsearch::DSL
index_name 'threatdb_2017.06.10'
document_type ''
attribute :index , String , mapping: { fields: { index: {type: 'string'}}}
attribute :country , String , mapping: { fields: { country: {type: 'string'}}}
attribute :country_code , String , mapping: { fields: { country_code: {type: 'string'}}}
attribute :threat_id , String , mapping: { fields: { threat_id: {type: 'string'}}}
attribute :host , String , mapping: { fields: { host: {type: 'string'}}}
attribute :threat_tri , Float , mapping: { fields: { threat_tri: {type: 'double'}}}
attribute :risk , Float ,mapping: { fields: { risk: {type: 'float'}}}
attribute :asn , String ,mapping: { fields: { asn: {type: 'string'}}}
attribute :asn_registry , String ,mapping: { fields: { asn_registry: {type: 'string'}}}
end
|
5e502253092c7d3c0cf9b4e977581d1e03c7925b
|
[
"Markdown",
"Ruby"
] | 5
|
Markdown
|
frcake/ThreatDb
|
0260b4320e2cc72499fc61396dcdefbcfa787285
|
4236e9a79960bd94e5706c565e1e8a1fb6f47112
|
refs/heads/master
|
<file_sep>#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <signal.h>
#define ADDR (224 << (3*8)) + 7
#define MESSAGE "Hello from server!"
#define MESSAGE_LEN (strlen(MESSAGE)+1)*sizeof(char)
static int thread_abort = 0;
void hdl(int sig)
{
thread_abort = 1;
}
void* sender(void* arg)
{
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_handler = hdl;
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGINT);
act.sa_mask = set;
if(sigaction(SIGINT, &act, 0) == -1)
{
perror("sigaction:");
return NULL;
}
char* msg = (char*) malloc(MESSAGE_LEN);
if(msg == NULL)
fprintf(stderr, "Failed to allocate memory\n");
strcpy(msg, MESSAGE);
while(1)
{
if(sendto(*(((int**)arg)[0]), msg, MESSAGE_LEN, 0,
((struct sockaddr_in**)arg)[1],
sizeof(struct sockaddr_in)) == -1)
perror("send");
if(sleep(2) != 0)
fprintf(stderr, "sleep\n");
if(thread_abort)
{
free(msg);
printf("ok\n");
return NULL;
}
}
free(msg);
return NULL;
}
int main(int argc, char* argv[])
{
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if(sock == -1)
{
perror("socket");
return 1;
}
struct sockaddr_in addr = { AF_INET, htons(7777), htonl(ADDR)};
void* arg = malloc(sizeof(void*)*2);
if(arg == NULL)
{
fprintf(stderr, "Failed to allocate memory\n");
if(close(sock) == -1)
perror("close");
return 1;
}
((void**)arg)[0] = &sock;
((void**)arg)[1] = &addr;
pthread_t thread;
if(pthread_create(&thread, NULL, sender, arg) != 0)
{
fprintf(stderr, "Failed to create thread\n");
free(arg);
if(close(sock) == -1)
perror("close");
return 1;
}
if(pthread_join(thread, NULL) != 0)
{
fprintf(stderr, "Failed to join thread\n");
free(arg);
if(close(sock) == -1)
perror("close");
return 1;
}
free(arg);
if(close(sock) == -1)
{
perror("close");
return 1;
}
return 0;
}
<file_sep>all: server client
server: server.c
gcc server.c -o server -g -Wall -lpthread
client: client.c
gcc client.c -o client -g -Wall -lpthread
clear:
rm server client<file_sep>#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
#define ADDR (224 << (3*8)) + 7
static int thread_abort = 0;
void hdl(int sig)
{
thread_abort = 1;
}
void* reciver(void* arg)
{
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_handler = hdl;
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGINT);
act.sa_mask = set;
if(sigaction(SIGINT, &act, 0) == -1)
{
perror("sigaction:");
return NULL;
}
char* full_message = NULL;
size_t size_message = 0;
char buf[256];
while(1)
{
//Неблокируемое ожидание входящего потока
int sel_ret = 0;
while(sel_ret == 0)
{
fd_set set;
struct timeval tv;
FD_ZERO(&set);
FD_SET(*(((int**)arg)[0]), &set);
tv.tv_sec = 1;
tv.tv_usec = 0;
sel_ret = select(*(((int**)arg)[0])+1, &set, NULL, NULL, &tv);
if(thread_abort)
break;
}
if(thread_abort)
break;
if(sel_ret == -1)
{
fprintf(stderr, "error: select\n");
break;
}
socklen_t len = sizeof(struct sockaddr_in);
ssize_t bytes_read = recvfrom(*(((int**)arg)[0]), buf, 256, 0,
((struct sockaddr_in**)arg)[1], &len);
if(bytes_read <= 0)
{
printf("Соединение разорвано\n");
if(full_message != NULL)
free(full_message);
break;
}
if(full_message != NULL)
{
char* reallocated_memory = (char*)realloc(full_message,
sizeof(char)*(size_message+bytes_read));
if(reallocated_memory == NULL)
fprintf(stderr, "Failed to allocate memory\n");
else
{
full_message = reallocated_memory;
memcpy(full_message+size_message, buf, (size_t)bytes_read);
size_message += (size_t)bytes_read;
}
}
else
{
full_message = (char*)malloc(sizeof(char)*bytes_read);
if(full_message == NULL)
fprintf(stderr, "Failed to allocate memory\n");
size_message = bytes_read;
memcpy(full_message, buf, (size_t)bytes_read);
}
if(full_message[size_message-1] == '\0')
{
printf("%s\n", full_message);
free(full_message);
full_message = NULL;
size_message = 0;
}
}
return NULL;
}
int main(int argc, char* argv[])
{
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if(sock == -1)
{
perror("socket");
return 1;
}
//Помечаем сокет неблокируемым
if(fcntl(sock, F_SETFL, O_NONBLOCK) == -1)
perror("fcntl");
//Говорим, что хотим multicast трафик с заданого адреса
/*
Структрура существует с Linux 2.2, с Linux 1.2 существует
ip_mreq, которая совместима с этой, но не включает ifindex.
* imr_multiaddr - адрес multicast группы
* imr_address - адрес локального интерфейса
* imr_ifindex - индекс интерфейса, к которому нужно
присоединить группу, или 0 для любого
интерфейса. (?)
*/
struct ip_mreqn mr;
struct in_addr multicast_addr = { htonl(ADDR) };
mr.imr_multiaddr = multicast_addr;
struct in_addr my_addr = { htonl(INADDR_ANY) };
mr.imr_address = my_addr;
mr.imr_ifindex = 0;
setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mr, sizeof(mr));
struct sockaddr_in addr = {AF_INET, htons(7777), htonl(INADDR_ANY)};
if(bind(sock, &addr, sizeof(addr)) == -1)
{
perror("bind");
return 1;
}
void* arg = malloc(sizeof(void*)*2);
if(arg == NULL)
{
fprintf(stderr, "Failed to allocate memory\n");
if(close(sock) == -1)
perror("close");
return 1;
}
((void**)arg)[0] = &sock;
((void**)arg)[1] = &addr;
pthread_t thread;
if(pthread_create(&thread, NULL, reciver, arg) != 0)
{
fprintf(stderr, "Failed to create thread");
free(arg);
if(close(sock) == -1)
perror("close");
return 1;
}
if(pthread_join(thread, NULL) != 0)
{
fprintf(stderr, "Failed to join thread");
free(arg);
if(close(sock) == -1)
perror("close");
return 1;
}
free(arg);
if(close(sock) == -1)
perror("close");
return 0;
}
|
8cbc58446def4b0968fbad43563fc975e9a2e6bc
|
[
"C",
"Makefile"
] | 3
|
C
|
ReRandom/multicast
|
00fde6ce17550bb5036e80d0e34a35b6982e9568
|
0a4a360c1ed3090128d7b67828b51d72794ed93b
|
refs/heads/master
|
<file_sep>package com.example.ac_twitterclone;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.shashank.sony.fancytoastlib.FancyToast;
public class Login extends AppCompatActivity implements View.OnClickListener {
private ImageView imgLogin;
private EditText edtLoginEmail,edtLoginPassword;
private Button btnLogin,btnLoginSignUp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
imgLogin=findViewById(R.id.imgLogin);
edtLoginEmail=findViewById(R.id.edtLoginEmail);
edtLoginPassword=findViewById(R.id.edtLoginPassword);
btnLogin=findViewById(R.id.btnLogin);
btnLoginSignUp=findViewById(R.id.btnLoginSignUp);
btnLogin.setOnClickListener(this);
btnLoginSignUp.setOnClickListener(this);
if(ParseUser.getCurrentUser()!=null){
ParseUser.getCurrentUser().logOut();
}
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnLogin:
ParseUser.logInInBackground(edtLoginEmail.getText().toString(),
edtLoginPassword.getText().toString(), new LogInCallback() {
@Override
public void done(ParseUser user, ParseException e) {
if(user != null && e==null){
FancyToast.makeText(Login.this, user.getUsername()+ " logged in successfully", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, true).show();
transitionToSocialMedia();
}else{
FancyToast.makeText(Login.this, e.getMessage(),
FancyToast.LENGTH_LONG, FancyToast.ERROR, true).show();
}
}
});
break;
case R.id.btnLoginSignUp:
transitionToSignUpActivity();
break;
}
}
public void transitionToSignUpActivity(){
Intent intent = new Intent(Login.this, SignUp.class);
startActivity(intent);
}
private void transitionToSocialMedia(){
Intent intent = new Intent(Login.this, TwitterUsers.class);
startActivity(intent);
}
}
<file_sep>package com.example.ac_twitterclone;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
import com.shashank.sony.fancytoastlib.FancyToast;
public class SignUp extends AppCompatActivity implements View.OnClickListener {
private ImageView imgSignUp;
private EditText edtSignUpEmail,edtSignUpUsername,edtSignUpPassword;
private Button btnSignUp,btnSignUpLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgSignUp=findViewById(R.id.imgSignUp);
edtSignUpEmail=findViewById(R.id.edtSignUpEmail);
edtSignUpUsername=findViewById(R.id.edtSignUpUsername);
edtSignUpPassword=findViewById(R.id.edtSignUpPassword);
btnSignUp=findViewById(R.id.btnSignUp);
btnSignUpLogin=findViewById(R.id.btnSignUpLogin);
btnSignUp.setOnClickListener(this);
btnSignUpLogin.setOnClickListener(this);
if (ParseUser.getCurrentUser()!=null){
//ParseUser.getCurrentUser().logOut();
transitionToSocialMedia();
}
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnSignUp:
final ParseUser appUser = new ParseUser();
appUser.setEmail(edtSignUpEmail.getText().toString());
appUser.setUsername(edtSignUpUsername.getText().toString());
appUser.setPassword(edtSignUpPassword.getText().toString());
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("siging up" + edtSignUpUsername.getText().toString());
dialog.show();
appUser.signUpInBackground(new SignUpCallback() {
@Override
public void done(ParseException e) {
if(e==null){
FancyToast.makeText(SignUp.this,appUser.getUsername(),
FancyToast.LENGTH_SHORT,FancyToast.SUCCESS,true).show();
transitionToSocialMedia();
}else{
FancyToast.makeText(SignUp.this, e.getMessage(),
FancyToast.LENGTH_LONG, FancyToast.ERROR, true).show();
}
dialog.dismiss();
}
});
break;
case R.id.btnSignUpLogin:
Intent intent = new Intent(SignUp.this,Login.class);
startActivity(intent);
break;
}
}
private void transitionToSocialMedia(){
Intent intent = new Intent(SignUp.this, TwitterUsers.class);
startActivity(intent);
}
}
|
e703b6267b52470211ecfd670c7de6e9c6f29238
|
[
"Java"
] | 2
|
Java
|
ManishBansiwal29/AC-TwitterClone
|
60ab3983a3c6eef069feb51c417779d133f84515
|
a4402e69a072b237f7acecefb7b6f034c26d735e
|
refs/heads/master
|
<file_sep>package output
import (
"fmt"
"path/filepath"
"github.com/bitrise-io/go-utils/fileutil"
"github.com/bitrise-io/go-utils/pathutil"
)
func saveRawOutputToLogFile(rawXcodebuildOutput string) (string, error) {
tmpDir, err := pathutil.NormalizedOSTempDirPath("xcodebuild-output")
if err != nil {
return "", fmt.Errorf("failed to create temp dir, error: %s", err)
}
logFileName := "raw-xcodebuild-output.log"
logPth := filepath.Join(tmpDir, logFileName)
if err := fileutil.WriteStringToFile(logPth, rawXcodebuildOutput); err != nil {
return "", fmt.Errorf("failed to write xcodebuild output to file, error: %s", err)
}
return logPth, nil
}
<file_sep>package testartifact
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/pathutil"
"github.com/bitrise-io/go-utils/pretty"
"github.com/bitrise-steplib/steps-xcode-test/testartifact/testsummaries"
)
const targetScreenshotTimeFormat = "2006-01-02_03-04-05"
// UpdateScreenshotNames ...
// Screenshot_uuid.png -> TestID_start_date_time_title_uuid.png
// Screenshot_uuid.jpg -> TestID_start_date_time_title_uuid.jpg
func UpdateScreenshotNames(testSummariesPath string, attachementDir string) (bool, error) {
if exist, err := pathutil.IsPathExists(testSummariesPath); err != nil {
return false, fmt.Errorf("failed to check if file exists: %s", testSummariesPath)
} else if !exist {
return false, fmt.Errorf("no TestSummaries file found: %s", testSummariesPath)
}
testResults, err := testsummaries.New(testSummariesPath)
if err != nil {
return false, fmt.Errorf("failed to parse %s, error: %s", testSummariesPath, err)
}
log.Debugf("Test results: %s", pretty.Object(testResults))
return commitRename(createRenamePlan(testResults, attachementDir)), nil
}
func filterActivitiesWithScreenshotsFromTree(activities []testsummaries.Activity) []testsummaries.Activity {
var activitiesWithScreensots []testsummaries.Activity
for _, activity := range activities {
if len(activity.Screenshots) > 0 {
activitiesWithScreensots = append(activitiesWithScreensots, activity)
}
activitiesWithScreensots = append(activitiesWithScreensots,
filterActivitiesWithScreenshotsFromTree(activity.SubActivities)...)
}
return activitiesWithScreensots
}
func createRenamePlan(testResults []testsummaries.TestResult, attachmentDir string) map[string]string {
renameMap := make(map[string]string)
for _, testResult := range testResults {
activitiesWithScreensots := filterActivitiesWithScreenshotsFromTree(testResult.Activities)
testRenames := make(map[string]string)
for _, activity := range activitiesWithScreensots {
for _, screenshot := range activity.Screenshots {
toFileName := fmt.Sprintf("%s_%s_%s_%s%s", replaceUnsupportedFilenameCharacters(testResult.ID),
screenshot.TimeCreated.Format(targetScreenshotTimeFormat),
replaceUnsupportedFilenameCharacters(activity.Title),
activity.UUID,
filepath.Ext(screenshot.FileName))
fromFileName := filepath.Join(attachmentDir, screenshot.FileName)
if testResult.Status != "Success" {
renameMap[fromFileName] = filepath.Join(attachmentDir, "Failures", toFileName)
} else {
renameMap[fromFileName] = filepath.Join(attachmentDir, toFileName)
}
}
}
for k, v := range testRenames {
renameMap[k] = v
}
}
return renameMap
}
func commitRename(renameMap map[string]string) bool {
var succesfulRenames int
for fromFileName, toFileName := range renameMap {
if exists, err := pathutil.IsPathExists(fromFileName); err != nil {
log.Warnf("Error checking if file exists, error: ", err)
} else if !exists {
log.Infof("Screenshot file does not exists: %s", fromFileName)
continue
}
if err := os.Mkdir(filepath.Dir(toFileName), os.ModePerm); !os.IsExist(err) && err != nil {
log.Warnf("Failed to create directory: %s", filepath.Dir(toFileName))
continue
}
if err := os.Rename(fromFileName, toFileName); err != nil {
log.Warnf("Failed to rename the screenshot: %s, error: %s", fromFileName, err)
continue
}
succesfulRenames++
log.Printf("Screenshot renamed: %s => %s", filepath.Base(fromFileName), filepath.Base(toFileName))
}
return succesfulRenames > 0
}
// TODO: merge with testaddon.replaceUnsupportedFilenameCharacters
// Replaces characters '/' and ':', which are unsupported in filnenames on macOS
func replaceUnsupportedFilenameCharacters(s string) string {
s = strings.Replace(s, "/", "-", -1)
s = strings.Replace(s, ":", "-", -1)
return s
}
// Zip ...
func Zip(targetDir, targetRelPathToZip, zipPath string) error {
zipCmd := exec.Command("/usr/bin/zip", "-rTy", zipPath, targetRelPathToZip)
zipCmd.Dir = targetDir
if out, err := zipCmd.CombinedOutput(); err != nil {
return fmt.Errorf("Zip failed, out: %s, err: %#v", out, err)
}
return nil
}
<file_sep>package testsummaries
import (
"fmt"
"reflect"
"testing"
"time"
"github.com/bitrise-io/go-utils/pretty"
"github.com/bitrise-io/go-xcode/plistutil"
)
func TestTimestampToTime(t *testing.T) {
time, err := TimestampStrToTime("522675441.31045401")
wantErr := false
if (err != nil) != wantErr {
t.Errorf("TimestampStrToTime() wantErr: %v, got: %v", wantErr, err)
}
want := []int{
2017,
7,
25,
11,
37,
21,
}
got := []int{
time.Year(),
int(time.Month()),
time.Day(),
time.Hour(),
time.Minute(),
time.Second(),
}
if !reflect.DeepEqual(want, got) {
t.Errorf("TimestampStrToTime() want: %v, got: %v", want, got)
}
}
func Test_parseTestSummaries(t *testing.T) {
const testID = "ios_simple_objcTests/testExample"
const testStatus = "Success"
type args struct {
testSummariesContent plistutil.PlistData
}
tests := []struct {
name string
args args
want []TestResult
wantErr bool
}{
{
name: "Simple, single test result",
args: args{
plistutil.PlistData{
"TestableSummaries": []interface{}{
map[string]interface{}{
"Tests": []interface{}{
map[string]interface{}{
"Subtests": []interface{}{
map[string]interface{}{
"TestIdentifier": testID,
"TestStatus": testStatus,
},
},
},
},
},
},
},
},
want: []TestResult{
{
ID: testID,
Status: testStatus,
FailureInfo: nil,
Activities: nil,
},
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := parseTestSummaries(tt.args.testSummariesContent)
// t.Logf(pretty.Object(got))
if (err != nil) != tt.wantErr {
t.Errorf("parseTestSummaries() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("parseTestSummaries() = %v, want %v", pretty.Object(got), pretty.Object(tt.want))
}
})
}
}
func Test_parseFailureSummaries(t *testing.T) {
type args struct {
failureSummariesData []plistutil.PlistData
}
tests := []struct {
name string
args args
want []FailureSummary
wantErr bool
}{
{
name: "Ok case",
args: args{[]plistutil.PlistData{{
"FileName": "/tmp/ios_simple_objcUITests.m",
"LineNumber": uint64(64),
"Message": "((NO) is true) failed",
"PerformanceFailure": false,
}}},
want: []FailureSummary{{
FileName: "/tmp/ios_simple_objcUITests.m",
LineNumber: 64,
Message: "((NO) is true) failed",
IsPerformanceFailure: false,
}},
wantErr: false,
},
{
name: "Key FileName not found",
args: args{[]plistutil.PlistData{{
"LineNumber": uint64(64),
"Message": "((NO) is true) failed",
"PerformanceFailure": false,
}}},
want: nil,
wantErr: true,
},
{
name: "Key LineNumber not found",
args: args{[]plistutil.PlistData{{
"FileName": "/tmp/ios_simple_objcUITests.m",
"Message": "((NO) is true) failed",
"PerformanceFailure": false,
}}},
want: nil,
wantErr: true,
},
{
name: "Key Message not found",
args: args{[]plistutil.PlistData{{
"FileName": "/tmp/ios_simple_objcUITests.m",
"LineNumber": uint64(64),
"PerformanceFailure": false,
}}},
want: nil,
wantErr: true,
},
{
name: "Key PerformanceFailure not found",
args: args{[]plistutil.PlistData{{
"FileName": "/tmp/ios_simple_objcUITests.m",
"LineNumber": uint64(64),
"Message": "((NO) is true) failed",
}}},
want: nil,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := parseFailureSummaries(tt.args.failureSummariesData)
if (err != nil) != tt.wantErr {
t.Errorf("parseFailureSummaries() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("parseFailureSummaries() = %v, want %v", pretty.Object(got), pretty.Object(tt.want))
}
})
}
}
func Test_collectLastSubtests(t *testing.T) {
type args struct {
testsItem plistutil.PlistData
}
tests := []struct {
name string
args args
want []plistutil.PlistData
wantErr bool
}{
{
name: "Simple case",
args: args{
map[string]interface{}{
"1": "",
"Subtests": []interface{}{
map[string]interface{}{
"2": "",
"Subtests": []interface{}{
map[string]interface{}{
"3": "",
}},
}},
},
},
want: []plistutil.PlistData{map[string]interface{}{
"3": "",
}},
wantErr: false,
},
{
name: "Multiple levels",
args: args{
map[string]interface{}{
"1": "",
"Subtests": []interface{}{
map[string]interface{}{
"2": "",
"Subtests": []interface{}{
map[string]interface{}{
"3": "",
},
},
},
map[string]interface{}{
"4": "",
},
},
},
},
want: []plistutil.PlistData{
{
"3": "",
},
{
"4": "",
}},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := collectLastSubtests(tt.args.testsItem)
if (err != nil) != tt.wantErr {
t.Errorf("collectLastSubtests() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("collectLastSubtests() = %v, want %v", got, tt.want)
}
})
}
}
func Test_parseActivites(t *testing.T) {
type args struct {
activitySummariesData []plistutil.PlistData
}
tests := []struct {
name string
args args
want []Activity
wantErr bool
}{
{
name: "Simple case",
args: args{[]plistutil.PlistData{{
"Title": "Start Test",
"UUID": "CE23D189-E75A-437D-A4B5-B97F1658FC98",
"StartTimeInterval": 568123776.87169898,
}}},
want: []Activity{{
Title: "Start Test",
UUID: "CE23D189-E75A-437D-A4B5-B97F1658FC98",
Screenshots: nil,
SubActivities: nil,
}},
wantErr: false,
},
{
name: "Subactivty case",
args: args{[]plistutil.PlistData{{
"Title": "Start Test",
"UUID": "CE23D189-E75A-437D-A4B5-B97F1658FC98",
"StartTimeInterval": 568123776.87169898,
"SubActivities": []interface{}{
map[string]interface{}{
"Title": "Launch",
"UUID": "1D7E1C6A-D0A3-432F-819F-64BE07C30517",
"StartTimeInterval": 568123780.54294205,
},
},
}}},
want: []Activity{{
Title: "Start Test",
UUID: "CE23D189-E75A-437D-A4B5-B97F1658FC98",
Screenshots: nil,
SubActivities: []Activity{{
Title: "Launch",
UUID: "1D7E1C6A-D0A3-432F-819F-64BE07C30517",
Screenshots: nil,
SubActivities: nil,
}},
}},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := parseActivites(tt.args.activitySummariesData)
if (err != nil) != tt.wantErr {
t.Errorf("parseActivites() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("parseActivites() = %v, want %v", pretty.Object(got), pretty.Object(tt.want))
}
})
}
}
func Test_parseSceenshots(t *testing.T) {
const fileName = "Screenshot of main screen (ID 1)_1_A07C26DB-8E1E-46ED-90F2-981438BE0BBA.png"
const attachmentTimeStampFloat = 568123782.31287897
const activityUUIDinLegacyScreenshotName = "C02EF626-0892-4B50-9B98-70D6F2C3EFE5"
activityStartTimeForLegacyScreenshot := time.Now()
type args struct {
activitySummary plistutil.PlistData
activityUUID string
activityStartTime time.Time
}
tests := []struct {
name string
args args
want []Screenshot
wantErr bool
}{
{
name: "Attachments (new)",
args: args{
activitySummary: plistutil.PlistData{
"Title": "Start Test",
"UUID": "CE23D189-E75A-437D-A4B5-B97F1658FC98",
"StartTimeInterval": 568123776.87169898,
"Attachments": []interface{}{
map[string]interface{}{
"Filename": fileName,
"Name": "Screenshot of main screen (ID 1)",
"Timestamp": attachmentTimeStampFloat,
},
},
},
activityUUID: "C02EF626-0892-4B50-9B98-70D6F2C3EFE5",
activityStartTime: time.Time{},
},
want: []Screenshot{{
FileName: fileName,
TimeCreated: TimestampToTime(attachmentTimeStampFloat),
}},
wantErr: false,
},
{
name: "Screenhot data (legacy)",
args: args{
activitySummary: plistutil.PlistData{
"Title": "Start Test",
"UUID": "CE23D189-E75A-437D-A4B5-B97F1658FC98",
"StartTimeInterval": 568123776.87169898,
"HasScreenshotData": true,
},
activityUUID: activityUUIDinLegacyScreenshotName,
activityStartTime: activityStartTimeForLegacyScreenshot,
},
want: []Screenshot{
{
FileName: fmt.Sprintf("Screenshot_%s.%s", activityUUIDinLegacyScreenshotName, "png"),
TimeCreated: activityStartTimeForLegacyScreenshot,
},
{
FileName: fmt.Sprintf("Screenshot_%s.%s", activityUUIDinLegacyScreenshotName, "jpg"),
TimeCreated: activityStartTimeForLegacyScreenshot,
}},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := parseSceenshots(tt.args.activitySummary, tt.args.activityUUID, tt.args.activityStartTime)
if (err != nil) != tt.wantErr {
t.Errorf("parseSceenshots() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("parseSceenshots() = %v, want %v", pretty.Object(got), pretty.Object(tt.want))
}
})
}
}
<file_sep># Xcode Test for iOS
[](https://github.com/bitrise-steplib/steps-xcode-test/releases)
Runs your project's pre-defined Xcode tests on every build.
<details>
<summary>Description</summary>
This Steps runs all those Xcode tests that are included in your project.
The Step will work out of the box if your project has test targets and your Workflow has the **Deploy to Bitrise.io** Step which exports the test results and (code coverage files if needed) to the Test Reports page.
This Step does not need any code signing files since the Step deploys only the test results to [bitrise.io](https://www.bitrise.io).
### Configuring the Step
If you click into the Step, there are some required input fields whose input must be set in accordance with the Xcode configuration of the project.
The **Scheme** input field must be marked as Shared in Xcode.
### Troubleshooting
If the **Deploy to Bitrise.io** Step is missing from your Workflow, then the **Xcode Test for iOS** Step will not be able to export the test results on the Test Reports page and you won't be able to view them either.
The xcpretty output tool does not support parallel tests.
If parallel tests are enabled in your project, go to the Step's Debug section and set the **Log formatter** input's value to xcodebuild.
If the Xcode test fails with the error `Unable to find a destination matching the provided destination specifier`, then check our [system reports](https://github.com/bitrise-io/bitrise.io/tree/master/system_reports) to see if the requested simulator is on the stack or not.
If it is not, then pick a simulator that is on the stack.
### Useful links
- [About Test Reports](https://devcenter.bitrise.io/testing/test-reports/)
- [Running Xcode Tests for iOS](https://devcenter.bitrise.io/testing/running-xcode-tests/)
### Related Steps
- [Deploy to Bitrise.io](https://www.bitrise.io/integrations/steps/deploy-to-bitrise-io)
- [iOS Device Testing](https://www.bitrise.io/integrations/steps/virtual-device-testing-for-ios)
</details>
## 🧩 Get started
Add this step directly to your workflow in the [Bitrise Workflow Editor](https://devcenter.bitrise.io/steps-and-workflows/steps-and-workflows-index/).
You can also run this step directly with [Bitrise CLI](https://github.com/bitrise-io/bitrise).
## ⚙️ Configuration
<details>
<summary>Inputs</summary>
| Key | Description | Flags | Default |
| --- | --- | --- | --- |
| `project_path` | Xcode Project (`.xcodeproj`) or Workspace (`.xcworkspace`) path. The input value sets xcodebuild's `-project` or `-workspace` option. | required | `$BITRISE_PROJECT_PATH` |
| `scheme` | Xcode Scheme name. The input value sets xcodebuild's `-scheme` option. | required | `$BITRISE_SCHEME` |
| `destination` | Destination specifier describes the device to use as a destination. The input value sets xcodebuild's `-destination` option. | required | `platform=iOS Simulator,name=iPhone 8 Plus,OS=latest` |
| `test_plan` | Run tests in a specific Test Plan associated with the Scheme. Leave this input empty to run the default Test Plan or Test Targets associated with the Scheme. The input value sets xcodebuild's `-testPlan` option. | | |
| `test_repetition_mode` | Determines how the tests will repeat. Available options: - `none`: Tests will never repeat. - `until_failure`: Tests will repeat until failure or up to maximum repetitions. - `retry_on_failure`: Only failed tests will repeat up to maximum repetitions. - `up_until_maximum_repetitions`: Tests will repeat up until maximum repetitions. The input value together with Maximum Test Repetitions (`maximum_test_repetitions`) input sets xcodebuild's `-run-tests-until-failure` / `-retry-tests-on-failure` or `-test-iterations` option. | | `none` |
| `maximum_test_repetitions` | The maximum number of times a test repeats based on the Test Repetition Mode (`test_repetition_mode`). Should be more than 1 if the Test Repetition Mode is other than `none`. The input value sets xcodebuild's `-test-iterations` option. | required | `3` |
| `relaunch_tests_for_each_repetition` | If this input is set, tests will launch in a new process for each repetition. By default, tests launch in the same process for each repetition. The input value sets xcodebuild's `-test-repetition-relaunch-enabled` option. | | `no` |
| `should_retry_test_on_fail` | If this input is set, the Step will rerun the tests in the case of failed tests. Note that all the tests will be rerun, not just the ones that failed. This input is not available if you are using Xcode 13+. In that case, we recommend using the `retry_on_failure` Test Repetition Mode (`test_repetition_mode`). | required | `no` |
| `xcconfig_content` | Build settings to override the project's build settings. Build settings must be separated by newline character (`\n`). Example: ``` COMPILER_INDEX_STORE_ENABLE = NO ONLY_ACTIVE_ARCH[config=Debug][sdk=*][arch=*] = YES ``` The input value sets xcodebuild's `-xcconfig` option. | | `COMPILER_INDEX_STORE_ENABLE = NO` |
| `perform_clean_action` | | required | `no` |
| `xcodebuild_options` | | | |
| `log_formatter` | Defines how xcodebuild command's log is formatted. Available options: - `xcpretty`: The xcodebuild command's output will be prettified by xcpretty. - `xcodebuild`: Only the last 20 lines of raw xcodebuild output will be visible in the build log. The raw xcodebuild log will be exported in both cases. | required | `xcpretty` |
| `xcpretty_options` | | | `--color --report html --output "${BITRISE_DEPLOY_DIR}/xcode-test-results-${BITRISE_SCHEME}.html"` |
| `cache_level` | Defines what cache content should be automatically collected. Available options: - `none`: Disable collecting cache content. - `swift_packages`: Collect Swift PM packages added to the Xcode project. | | `swift_packages` |
| `verbose_log` | | | `no` |
| `collect_simulator_diagnostics` | | | `never` |
| `headless_mode` | In headless mode the simulator is not launched in the foreground. If this input is set, the simulator will not be visible but tests (even the screenshots) will run just like if you run a simulator in foreground. | | `yes` |
</details>
<details>
<summary>Outputs</summary>
| Environment Variable | Description |
| --- | --- |
| `BITRISE_XCODE_TEST_RESULT` | |
| `BITRISE_XCRESULT_PATH` | The path of the generated `.xcresult`. |
| `BITRISE_XCRESULT_ZIP_PATH` | The path of the zipped `.xcresult`. |
| `BITRISE_XCODE_TEST_ATTACHMENTS_PATH` | This is the path of the test attachments zip. |
| `BITRISE_XCODEBUILD_BUILD_LOG_PATH` | If `single_build` is set to false, the step runs `xcodebuild build` before the test, and exports the raw xcodebuild log. |
| `BITRISE_XCODEBUILD_TEST_LOG_PATH` | The step exports the `xcodebuild test` command output log. |
</details>
## 🙋 Contributing
We welcome [pull requests](https://github.com/bitrise-steplib/steps-xcode-test/pulls) and [issues](https://github.com/bitrise-steplib/steps-xcode-test/issues) against this repository.
For pull requests, work on your changes in a forked repository and use the Bitrise CLI to [run step tests locally](https://devcenter.bitrise.io/bitrise-cli/run-your-first-build/).
Learn more about developing steps:
- [Create your own step](https://devcenter.bitrise.io/contributors/create-your-own-step/)
- [Testing your Step](https://devcenter.bitrise.io/contributors/testing-and-versioning-your-steps/)
<file_sep>package simulator
import (
"fmt"
mockcommand "github.com/bitrise-io/go-utils/command/mocks"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"os"
"path/filepath"
"testing"
)
type testingMocks struct {
commandFactory *mockcommand.Factory
}
func Test_GivenSimulator_WhenResetLaunchServices_ThenPerformsAction(t *testing.T) {
// Given
xcodePath := "/some/path"
manager, mocks := createSimulatorAndMocks()
mocks.commandFactory.On("Create", "sw_vers", []string{"-productVersion"}, mock.Anything).Return(createCommand("11.6"))
mocks.commandFactory.On("Create", "xcode-select", []string{"--print-path"}, mock.Anything).Return(createCommand(xcodePath))
lsregister := "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"
simulatorPath := filepath.Join(xcodePath, "Applications/Simulator.app")
mocks.commandFactory.On("Create", lsregister, []string{"-f", simulatorPath}, mock.Anything).Return(createCommand(""))
// When
err := manager.ResetLaunchServices()
// Then
assert.NoError(t, err)
}
func Test_GivenSimulator_WhenBoot_ThenBootsTheRequestedSimulator(t *testing.T) {
// Given
manager, mocks := createSimulatorAndMocks()
identifier := "test-identifier"
parameters := []string{"simctl", "boot", identifier}
mocks.commandFactory.On("Create", "xcrun", parameters, mock.Anything).Return(createCommand(""))
// When
err := manager.SimulatorBoot(identifier)
// Then
assert.NoError(t, err)
mocks.commandFactory.AssertCalled(t, "Create", "xcrun", parameters, mock.Anything)
}
func Test_GivenSimulator_WhenEnableVerboseLog_ThenEnablesIt(t *testing.T) {
// Given
manager, mocks := createSimulatorAndMocks()
identifier := "test-identifier"
parameters := []string{"simctl", "logverbose", identifier, "enable"}
mocks.commandFactory.On("Create", "xcrun", parameters, mock.Anything).Return(createCommand(""))
// When
err := manager.SimulatorEnableVerboseLog(identifier)
// Then
assert.NoError(t, err)
mocks.commandFactory.AssertCalled(t, "Create", "xcrun", parameters, mock.Anything)
}
func Test_GivenSimulator_WhenCollectDiagnostics_ThenCollectsIt(t *testing.T) {
// Given
manager, mocks := createSimulatorAndMocks()
mocks.commandFactory.On("Create", "xcrun", mock.Anything, mock.Anything).Return(createCommand(""))
// When
diagnosticsOutDir, err := manager.SimulatorCollectDiagnostics()
defer func() {
// Do not forget to clen up the temp dir
_ = os.RemoveAll(diagnosticsOutDir)
}()
// Then
assert.NoError(t, err)
parameters := []string{"simctl", "diagnose", "-b", "--no-archive", fmt.Sprintf("--output=%s", diagnosticsOutDir)}
mocks.commandFactory.AssertCalled(t, "Create", "xcrun", parameters, mock.Anything)
}
func Test_GivenSimulator_WhenShutdown_ThenShutsItDown(t *testing.T) {
// Given
manager, mocks := createSimulatorAndMocks()
identifier := "test-identifier"
parameters := []string{"simctl", "shutdown", identifier}
mocks.commandFactory.On("Create", "xcrun", parameters, mock.Anything).Return(createCommand(""))
// When
err := manager.SimulatorShutdown(identifier)
// Then
assert.NoError(t, err)
mocks.commandFactory.AssertCalled(t, "Create", "xcrun", parameters, mock.Anything)
}
// Helpers
func createSimulatorAndMocks() (Manager, testingMocks) {
commandFactory := new(mockcommand.Factory)
manager := NewManager(commandFactory)
return manager, testingMocks{
commandFactory: commandFactory,
}
}
func createCommand(output string) *mockcommand.Command {
command := new(mockcommand.Command)
command.On("PrintableCommandArgs").Return("")
command.On("Run").Return(nil)
command.On("RunAndReturnExitCode").Return(0, nil)
command.On("RunAndReturnTrimmedCombinedOutput").Return(output, nil)
return command
}
<file_sep>package output
import (
"fmt"
"path/filepath"
"github.com/bitrise-io/bitrise/configs"
"github.com/bitrise-io/go-steputils/output"
"github.com/bitrise-io/go-utils/command"
"github.com/bitrise-io/go-utils/env"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/ziputil"
"github.com/bitrise-steplib/steps-xcode-test/testaddon"
)
// Exporter ...
type Exporter interface {
ExportXCResultBundle(deployDir, xcResultPath, scheme string)
ExportTestRunResult(failed bool)
ExportXcodebuildBuildLog(deployDir, xcodebuildBuildLog string) error
ExportXcodebuildTestLog(deployDir, xcodebuildTestLog string) error
ExportSimulatorDiagnostics(deployDir, pth, name string) error
}
type exporter struct {
envRepository env.Repository
logger log.Logger
testAddonExporter testaddon.Exporter
}
// NewExporter ...
func NewExporter(envRepository env.Repository, logger log.Logger, testAddonExporter testaddon.Exporter) Exporter {
return &exporter{
envRepository: envRepository,
logger: logger,
testAddonExporter: testAddonExporter,
}
}
func (e exporter) ExportTestRunResult(failed bool) {
status := "succeeded"
if failed {
status = "failed"
}
if err := e.envRepository.Set("BITRISE_XCODE_TEST_RESULT", status); err != nil {
e.logger.Warnf("Failed to export: BITRISE_XCODE_TEST_RESULT, error: %s", err)
}
}
func (e exporter) ExportXCResultBundle(deployDir, xcResultPath, scheme string) {
// export xcresult bundle
if err := e.envRepository.Set("BITRISE_XCRESULT_PATH", xcResultPath); err != nil {
e.logger.Warnf("Failed to export: BITRISE_XCRESULT_PATH, error: %s", err)
}
xcresultZipPath := filepath.Join(deployDir, filepath.Base(xcResultPath)+".zip")
if err := output.ZipAndExportOutput(xcResultPath, xcresultZipPath, "BITRISE_XCRESULT_ZIP_PATH"); err != nil {
e.logger.Warnf("Failed to export: BITRISE_XCRESULT_ZIP_PATH, error: %s", err)
}
// export xcresult for the testing addon
if addonResultPath := e.envRepository.Get(configs.BitrisePerStepTestResultDirEnvKey); len(addonResultPath) > 0 {
e.logger.Println()
e.logger.Infof("Exporting test results")
if err := e.testAddonExporter.CopyAndSaveMetadata(testaddon.AddonCopy{
SourceTestOutputDir: xcResultPath,
TargetAddonPath: addonResultPath,
TargetAddonBundleName: scheme,
}); err != nil {
e.logger.Warnf("Failed to export test results, error: %s", err)
}
}
}
func (e exporter) ExportXcodebuildBuildLog(deployDir, xcodebuildBuildLog string) error {
pth, err := saveRawOutputToLogFile(xcodebuildBuildLog)
if err != nil {
e.logger.Warnf("Failed to save the Raw Output, err: %s", err)
}
deployPth := filepath.Join(deployDir, "xcodebuild_build.log")
if err := command.CopyFile(pth, deployPth); err != nil {
return fmt.Errorf("failed to copy xcodebuild output log file from (%s) to (%s), error: %s", pth, deployPth, err)
}
if err := e.envRepository.Set("BITRISE_XCODEBUILD_BUILD_LOG_PATH", deployPth); err != nil {
e.logger.Warnf("Failed to export: BITRISE_XCODEBUILD_BUILD_LOG_PATH, error: %s", err)
}
return nil
}
func (e exporter) ExportXcodebuildTestLog(deployDir, xcodebuildTestLog string) error {
pth, err := saveRawOutputToLogFile(xcodebuildTestLog)
if err != nil {
e.logger.Warnf("Failed to save the Raw Output, error: %s", err)
}
deployPth := filepath.Join(deployDir, "xcodebuild_test.log")
if err := command.CopyFile(pth, deployPth); err != nil {
return fmt.Errorf("failed to copy xcodebuild output log file from (%s) to (%s), error: %s", pth, deployPth, err)
}
if err := e.envRepository.Set("BITRISE_XCODEBUILD_TEST_LOG_PATH", deployPth); err != nil {
e.logger.Warnf("Failed to export: BITRISE_XCODEBUILD_TEST_LOG_PATH, error: %s", err)
}
return nil
}
func (e exporter) ExportSimulatorDiagnostics(deployDir, pth, name string) error {
outputPath := filepath.Join(deployDir, name)
if err := ziputil.ZipDir(pth, outputPath, true); err != nil {
return fmt.Errorf("failed to compress simulator diagnostics result: %v", err)
}
return nil
}
<file_sep>package testsummaries
import (
"fmt"
"strconv"
"time"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/pretty"
"github.com/bitrise-io/go-xcode/plistutil"
)
// ScreenshotsType describes the screenshot attachment's type
type ScreenshotsType string
// const ...
const (
ScreenshotsLegacy ScreenshotsType = "ScreenshotsLegacy"
ScreenshotsAsAttachments ScreenshotsType = "ScreenshotsAsAttachments"
ScreenshotsNone ScreenshotsType = "ScreenshotsNone"
)
// FailureSummary describes a failed test
type FailureSummary struct {
FileName string
LineNumber uint64
Message string
IsPerformanceFailure bool
}
// Screenshot describes a screenshot attached to an Activity
type Screenshot struct {
FileName string
TimeCreated time.Time
}
// Activity describes a single xcode UI test activity
type Activity struct {
Title string
UUID string
Screenshots []Screenshot
SubActivities []Activity
}
// TestResult describes a single UI test's output
type TestResult struct {
ID string
Status string
FailureInfo []FailureSummary
Activities []Activity
}
// New parses an *_TestSummaries.plist and returns an array containing test results and screenshots
func New(testSummariesPth string) ([]TestResult, error) {
testSummariesPlistData, err := plistutil.NewPlistDataFromFile(testSummariesPth)
if err != nil {
return nil, fmt.Errorf("failed to parse TestSummaries file: %s, error: %s", testSummariesPth, err)
}
return parseTestSummaries(testSummariesPlistData)
}
func parseTestSummaries(testSummariesContent plistutil.PlistData) ([]TestResult, error) {
testableSummaries, found := testSummariesContent.GetMapStringInterfaceArray("TestableSummaries")
if !found {
return nil, fmt.Errorf("failed to parse test summaries plist, key TestableSummaries is not a string map")
}
var testResults []TestResult
for _, testableSummariesItem := range testableSummaries {
tests, found := testableSummariesItem.GetMapStringInterfaceArray("Tests")
if !found {
return nil, fmt.Errorf("failed to parse test summaries plist, key Tests is not a string map")
}
for _, testsItem := range tests {
lastSubtests, err := collectLastSubtests(testsItem)
if err != nil {
return nil, err
}
log.Debugf("lastSubtests %s", pretty.Object(lastSubtests))
for _, test := range lastSubtests {
testID, found := test.GetString("TestIdentifier")
if !found {
return nil, fmt.Errorf("key TestIdentifier not found for test")
}
testStatus, found := test.GetString("TestStatus")
if !found {
return nil, fmt.Errorf("key TestStatus not found for test")
}
var failureSummaries []FailureSummary
if testStatus == "Failure" {
failureSummariesData, found := test.GetMapStringInterfaceArray("FailureSummaries")
if !found {
return nil, fmt.Errorf("no failure summaries found for failing test")
}
failureSummaries, err = parseFailureSummaries(failureSummariesData)
if err != nil {
return nil, fmt.Errorf("failed to parse failure summaries, error: %s", err)
}
}
var activitySummaries []Activity
{
if activitySummariesData, found := test.GetMapStringInterfaceArray("ActivitySummaries"); found {
activitySummaries, err = parseActivites(activitySummariesData)
if err != nil {
return nil, fmt.Errorf("failed to parse activities, error: %s", err)
}
}
}
testResults = append(testResults, TestResult{
ID: testID,
Status: testStatus,
FailureInfo: failureSummaries,
Activities: activitySummaries,
})
}
}
}
return testResults, nil
}
func collectLastSubtests(testsItem plistutil.PlistData) ([]plistutil.PlistData, error) {
var walk func(plistutil.PlistData) []plistutil.PlistData
walk = func(item plistutil.PlistData) []plistutil.PlistData {
subtests, found := item.GetMapStringInterfaceArray("Subtests")
if !found {
return []plistutil.PlistData{item}
}
var lastSubtests []plistutil.PlistData
for _, subtest := range subtests {
last := walk(subtest)
lastSubtests = append(lastSubtests, last...)
}
return lastSubtests
}
return walk(testsItem), nil
}
func parseFailureSummaries(failureSummariesData []plistutil.PlistData) ([]FailureSummary, error) {
var failureSummaries = make([]FailureSummary, len(failureSummariesData))
for i, failureSummary := range failureSummariesData {
fileName, found := failureSummary.GetString("FileName")
if !found {
return nil, fmt.Errorf("key FileName not found for FailureSummaries: %s", pretty.Object(failureSummariesData))
}
lineNumber, found := failureSummary.GetUInt64("LineNumber")
if !found {
return nil, fmt.Errorf("key lineNumber not found for FailureSummaries: %s", pretty.Object(failureSummariesData))
}
message, found := failureSummary.GetString("Message")
if !found {
return nil, fmt.Errorf("key Message not found for FailureSummaries: %s", pretty.Object(failureSummariesData))
}
isPerformanceFailure, found := failureSummary.GetBool("PerformanceFailure")
if !found {
return nil, fmt.Errorf("key PerformanceFailure not found for FailureSummaries: %s", pretty.Object(failureSummariesData))
}
failureSummaries[i] = FailureSummary{
FileName: fileName,
LineNumber: lineNumber,
Message: message,
IsPerformanceFailure: isPerformanceFailure,
}
}
return failureSummaries, nil
}
func parseActivites(activitySummariesData []plistutil.PlistData) ([]Activity, error) {
var activities = make([]Activity, len(activitySummariesData))
for i, activity := range activitySummariesData {
title, found := activity.GetString("Title")
if !found {
return nil, fmt.Errorf("key Title not found for activity: %s", pretty.Object(activity))
}
UUID, found := activity.GetString("UUID")
if !found {
return nil, fmt.Errorf("key UUID not found for activity: %s", pretty.Object(activity))
}
timeStampFloat, found := activity.GetFloat64("StartTimeInterval")
if !found {
return nil, fmt.Errorf("key StartTimeInterval not found for activity: %s", pretty.Object(activity))
}
timeStamp := TimestampToTime(timeStampFloat)
screenshots, err := parseSceenshots(activity, UUID, timeStamp)
if err != nil {
return nil, fmt.Errorf("Screenshot invalid format, error: %s", err)
}
var subActivities []Activity
if subActivitiesData, found := activity.GetMapStringInterfaceArray("SubActivities"); found {
if subActivities, err = parseActivites(subActivitiesData); err != nil {
return nil, err
}
} else {
log.Debugf("No subactivities found for activity: %s", pretty.Object(activity))
}
activities[i] = Activity{
Title: title,
UUID: UUID,
Screenshots: screenshots,
SubActivities: subActivities,
}
}
return activities, nil
}
func parseSceenshots(activitySummary plistutil.PlistData, activityUUID string, activityStartTime time.Time) ([]Screenshot, error) {
getAttachmentType := func(item map[string]interface{}) ScreenshotsType {
_, found := item["Attachments"]
if found {
return ScreenshotsAsAttachments
}
value, found := item["HasScreenshotData"]
if found {
hasScreenshot, casted := value.(bool)
if casted && hasScreenshot {
return ScreenshotsLegacy
}
}
return ScreenshotsNone
}
switch getAttachmentType(activitySummary) {
case ScreenshotsAsAttachments:
{
attachmentsData, found := activitySummary.GetMapStringInterfaceArray("Attachments")
if !found {
return nil, fmt.Errorf("no key Attachments, or invalid format")
}
attachments := make([]Screenshot, len(attachmentsData))
for i, attachment := range attachmentsData {
filenName, found := attachment.GetString("Filename")
if !found {
return nil, fmt.Errorf("no key Filename found for attachment: %s", pretty.Object(attachment))
}
timeStampFloat, found := attachment.GetFloat64("Timestamp")
if !found {
return nil, fmt.Errorf("no key Timestamp found for attachment: %s", pretty.Object(attachment))
}
timeStamp := TimestampToTime(timeStampFloat)
attachments[i] = Screenshot{
FileName: filenName,
TimeCreated: timeStamp,
}
}
return attachments, nil
}
case ScreenshotsLegacy:
{
attachments := make([]Screenshot, 2)
for i, ext := range []string{"png", "jpg"} {
fileName := fmt.Sprintf("Screenshot_%s.%s", activityUUID, ext)
attachments[i] = Screenshot{
FileName: fileName,
TimeCreated: activityStartTime,
}
}
return attachments, nil
}
case ScreenshotsNone:
{
return nil, nil
}
default:
{
return nil, fmt.Errorf("unhandled screenshot type")
}
}
}
// TimestampStrToTime ...
func TimestampStrToTime(timestampStr string) (time.Time, error) {
timestamp, err := strconv.ParseFloat(timestampStr, 64)
if err != nil {
return time.Time{}, err
}
return TimestampToTime(timestamp), nil
}
// TimestampToTime ...
func TimestampToTime(timestamp float64) time.Time {
timestampInNanosec := int64(timestamp * float64(time.Second))
referenceDate := time.Date(2001, 1, 1, 0, 0, 0, 0, time.UTC)
return referenceDate.Add(time.Duration(timestampInNanosec))
}
<file_sep>package xcodebuild
import (
"io/ioutil"
"testing"
)
func Test_isStringFoundInOutput(t *testing.T) {
t.Log("Should NOT find")
{
searchPattern := "something"
isShouldFind := false
for _, anOutStr := range []string{
"",
"a",
"1",
"somethin",
"somethinx",
"TEST FAILED",
} {
if isFound := isStringFoundInOutput(searchPattern, anOutStr); isFound != isShouldFind {
t.Logf("Search pattern was: %s", searchPattern)
t.Logf("Input string to search in was: %s", anOutStr)
t.Fatalf("Expected (%v), actual (%v)", isShouldFind, isFound)
}
}
}
t.Log("Should find")
{
searchPattern := "search for this"
isShouldFind := true
for _, anOutStr := range []string{
"search for this",
"-search for this",
"search for this-",
"-search for this-",
} {
if isFound := isStringFoundInOutput(searchPattern, anOutStr); isFound != isShouldFind {
t.Logf("Search pattern was: %s", searchPattern)
t.Logf("Input string to search in was: %s", anOutStr)
t.Fatalf("Expected (%v), actual (%v)", isShouldFind, isFound)
}
}
}
t.Log("Should find - empty pattern - always yes")
{
searchPattern := ""
isShouldFind := true
for _, anOutStr := range []string{
"",
"a",
"1",
"TEST FAILED",
} {
if isFound := isStringFoundInOutput(searchPattern, anOutStr); isFound != isShouldFind {
t.Logf("Search pattern was: %s", searchPattern)
t.Logf("Input string to search in was: %s", anOutStr)
t.Fatalf("Expected (%v), actual (%v)", isShouldFind, isFound)
}
}
}
}
func TestIsStringFoundInOutput_timedOutRegisteringForTestingEvent(t *testing.T) {
t.Log("load sample logs")
{
}
sampleTestRunnerLog, err := loadFileContent("../_samples/xcodebuild-timed-out-registering-for-testing-event.txt")
if err != nil {
t.Fatalf("Failed to load error sample log : %s", err)
}
sampleOKBuildLog, err := loadFileContent("../_samples/xcodebuild-ok.txt")
if err != nil {
t.Fatalf("Failed to load xcodebuild-ok.txt : %s", err)
}
t.Log("Should find")
{
for _, anOutStr := range []string{
"Timed out registering for testing event accessibility notifications",
".timed out registering for testing event accessibility notifications.",
"(Timed out registering for testing event accessibility notifications)",
"aaaTimed out registering for testing event accessibility notifications... test test test",
"aaa timed out registering for testing event accessibility notificationstest",
sampleTestRunnerLog,
} {
timedOutRegisteringForTestingEventWith(t, anOutStr, true)
}
}
t.Log("Should NOT find")
{
for _, anOutStr := range []string{
"",
"accessibility",
"timed out",
sampleOKBuildLog,
} {
timedOutRegisteringForTestingEventWith(t, anOutStr, false)
}
}
}
func TestIsStringFoundInOutput_testRunnerFailedToInitializeForUITesting(t *testing.T) {
t.Log("load sample logs")
{
}
sampleTestRunnerLog, err := loadFileContent("../_samples/xcodebuild-test-runner-failed-to-initialize-for-ui-testing.txt")
if err != nil {
t.Fatalf("Failed to load error sample log : %s", err)
}
sampleOKBuildLog, err := loadFileContent("../_samples/xcodebuild-ok.txt")
if err != nil {
t.Fatalf("Failed to load xcodebuild-ok.txt : %s", err)
}
t.Log("Should find")
{
for _, anOutStr := range []string{
"test runner failed to initialize for ui testing",
"Test runner failed to initialize for ui testing.",
"Test runner failed to initialize for UI testing, test test test",
"aaaTest runner failed to initialize for UI testing... test test test",
"aaa Test runner failed to initialize for UI testingtest",
sampleTestRunnerLog,
} {
testRunnerFailedToInitializeForUITestingWith(t, anOutStr, true)
}
}
t.Log("Should NOT find")
{
for _, anOutStr := range []string{
"",
"UI testing:",
"test runner failed",
sampleOKBuildLog,
} {
testRunnerFailedToInitializeForUITestingWith(t, anOutStr, false)
}
}
}
func TestIsStringFoundInOutput_timeOutMessageIPhoneSimulator(t *testing.T) {
t.Log("load sample logs")
{
}
sampleIPhoneSimulatorLog, err := loadFileContent("../_samples/xcodebuild-iPhoneSimulator-timeout.txt")
if err != nil {
t.Fatalf("Failed to load error sample log : %s", err)
}
sampleOKBuildLog, err := loadFileContent("../_samples/xcodebuild-ok.txt")
if err != nil {
t.Fatalf("Failed to load xcodebuild-ok.txt : %s", err)
}
t.Log("Should find")
{
for _, anOutStr := range []string{
"iPhoneSimulator: Timed out waiting",
"iphoneSimulator: timed out waiting",
"iphoneSimulator: timed out waiting, test test test",
"aaaiphoneSimulator: timed out waiting, test test test",
"aaa iphoneSimulator: timed out waiting, test test test",
sampleIPhoneSimulatorLog,
} {
testIPhoneSimulatorTimeoutWith(t, anOutStr, true)
}
}
t.Log("Should NOT find")
{
for _, anOutStr := range []string{
"",
"iphoneSimulator:",
sampleOKBuildLog,
} {
testIPhoneSimulatorTimeoutWith(t, anOutStr, false)
}
}
}
func TestIsStringFoundInOutput_timeOutMessageUITest(t *testing.T) {
// load sample logs
sampleUITestTimeoutLog, err := loadFileContent("../_samples/xcodebuild-UITest-timeout.txt")
if err != nil {
t.Fatalf("Failed to load error sample log : %s", err)
}
sampleOKBuildLog, err := loadFileContent("../_samples/xcodebuild-ok.txt")
if err != nil {
t.Fatalf("Failed to load xcodebuild-ok.txt : %s", err)
}
t.Log("Should find")
{
for _, anOutStr := range []string{
"Terminating app due to uncaught exception '_XCTestCaseInterruptionException'",
"terminating app due to uncaught exception '_XCTestCaseInterruptionException'",
"aaTerminating app due to uncaught exception '_XCTestCaseInterruptionException'aa",
"aa Terminating app due to uncaught exception '_XCTestCaseInterruptionException' aa",
sampleUITestTimeoutLog,
} {
testTimeOutMessageUITestWith(t, anOutStr, true)
}
}
t.Log("Should NOT find")
{
for _, anOutStr := range []string{
"",
"Terminating app due to uncaught exception",
"_XCTestCaseInterruptionException",
sampleOKBuildLog,
} {
testTimeOutMessageUITestWith(t, anOutStr, false)
}
}
}
func TestIsStringFoundInOutput_earlyUnexpectedExit(t *testing.T) {
// load sample logs
sampleUITestEarlyUnexpectedExit1, err := loadFileContent("../_samples/xcodebuild-early-unexpected-exit_1.txt")
if err != nil {
t.Fatalf("Failed to load error sample log : %s", err)
}
sampleUITestEarlyUnexpectedExit2, err := loadFileContent("../_samples/xcodebuild-early-unexpected-exit_2.txt")
if err != nil {
t.Fatalf("Failed to load error sample log : %s", err)
}
sampleOKBuildLog, err := loadFileContent("../_samples/xcodebuild-ok.txt")
if err != nil {
t.Fatalf("Failed to load xcodebuild-ok.txt : %s", err)
}
t.Log("Should find")
{
for _, anOutStr := range []string{
"Early unexpected exit, operation never finished bootstrapping - no restart will be attempted",
"Test target ios-xcode-8.0UITests encountered an error (Early unexpected exit, operation never finished bootstrapping - no restart will be attempted)",
"aaEarly unexpected exit, operation never finished bootstrapping - no restart will be attemptedaa",
"aa Early unexpected exit, operation never finished bootstrapping - no restart will be attempted aa",
sampleUITestEarlyUnexpectedExit1,
sampleUITestEarlyUnexpectedExit2,
} {
testEarlyUnexpectedExitMessageUITestWith(t, anOutStr, true)
}
}
t.Log("Should NOT find")
{
for _, anOutStr := range []string{
"",
"Early unexpected exit, operation never finished bootstrapping",
"no restart will be attempted",
sampleOKBuildLog,
} {
testEarlyUnexpectedExitMessageUITestWith(t, anOutStr, false)
}
}
}
func TestIsStringFoundInOutput_failureAttemptingToLaunch(t *testing.T) {
// load sample logs
sampleUITestFailureAttemptingToLaunch, err := loadFileContent("../_samples/xcodebuild-failure-attempting-tolaunch.txt")
if err != nil {
t.Fatalf("Failed to load error sample log : %s", err)
}
sampleOKBuildLog, err := loadFileContent("../_samples/xcodebuild-ok.txt")
if err != nil {
t.Fatalf("Failed to load xcodebuild-ok.txt : %s", err)
}
t.Log("Should find")
{
for _, anOutStr := range []string{
"Assertion Failure: <unknown>:0: UI Testing Failure - Failure attempting to launch <XCUIApplicationImpl:",
"t = 46.77s Assertion Failure: <unknown>:0: UI Testing Failure - Failure attempting to launch <XCUIApplicationImpl: 0x608000423da0 io.bitrise.ios-xcode-8-0 at ",
"aaAssertion Failure: <unknown>:0: UI Testing Failure - Failure attempting to launch <XCUIApplicationImpl:aa",
"aa Assertion Failure: <unknown>:0: UI Testing Failure - Failure attempting to launch <XCUIApplicationImpl: aa",
sampleUITestFailureAttemptingToLaunch,
} {
testFailureAttemptingToLaunch(t, anOutStr, true)
}
}
t.Log("Should NOT find")
{
for _, anOutStr := range []string{
"",
"Assertion Failure:",
"Failure attempting to launch <XCUIApplicationImpl:",
sampleOKBuildLog,
} {
testFailureAttemptingToLaunch(t, anOutStr, false)
}
}
}
func TestIsStringFoundInOutput_failedToBackgroundTestRunner(t *testing.T) {
// load sample logs
sampleUITestFailedToBackgroundTestRunner, err := loadFileContent("../_samples/xcodebuild-failed-to-background-test-runner.txt")
if err != nil {
t.Fatalf("Failed to load error sample log : %s", err)
}
sampleOKBuildLog, err := loadFileContent("../_samples/xcodebuild-ok.txt")
if err != nil {
t.Fatalf("Failed to load xcodebuild-ok.txt : %s", err)
}
t.Log("Should find")
{
for _, anOutStr := range []string{
`Error Domain=IDETestOperationsObserverErrorDomain Code=12 "Failed to background test runner.`,
`2016-09-26 01:14:08.896 xcodebuild[1299:5953] Error Domain=IDETestOperationsObserverErrorDomain Code=12 "Failed to background test runner. If you believe this error represents a bug, please attach the log file at`,
`aaError Domain=IDETestOperationsObserverErrorDomain Code=12 "Failed to background test runner.aa`,
`aa Error Domain=IDETestOperationsObserverErrorDomain Code=12 "Failed to background test runner. aa`,
sampleUITestFailedToBackgroundTestRunner,
} {
testFailedToBackgroundTestRunner(t, anOutStr, true)
}
}
t.Log("Should NOT find")
{
for _, anOutStr := range []string{
"",
"Assertion Failure:",
"Failure attempting to launch <XCUIApplicationImpl:",
sampleOKBuildLog,
} {
testFailedToBackgroundTestRunner(t, anOutStr, false)
}
}
}
func TestIsStringFoundInOutput_failedToOpenTestRunner(t *testing.T) {
// load sample logs
sampleUITestFailedToBackgroundTestRunner, err := loadFileContent("../_samples/xcodebuild-failed-to-open-test-runner.txt")
if err != nil {
t.Fatalf("Failed to load error sample log : %s", err)
}
sampleOKBuildLog, err := loadFileContent("../_samples/xcodebuild-ok.txt")
if err != nil {
t.Fatalf("Failed to load xcodebuild-ok.txt : %s", err)
}
t.Log("Should find")
{
for _, anOutStr := range []string{
`Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open "io.bitrise.ios-simple-objcUITests.xctrunner" failed." UserInfo={BSErrorCodeDescription=RequestDenied, NSLocalizedDescription=The request to open "io.bitrise.ios-simple-objcUITests.xctrunner" failed., NSUnderlyingError=0x7fb8160bea40 {Error Domain=SBWorkspaceTransaction Code=1 "Launch failed" UserInfo={SBTransaction=SBSuspendedWorkspaceTransaction, NSLocalizedFailureReason=Launch failed}}, FBSOpenApplicationRequestID=0xf30, NSLocalizedFailureReason=The request was denied by service delegate (SBMainWorkspace).`,
`2016-09-26 01:14:08.896 xcodebuild[1299:5953] Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open "io.bitrise.ios-simple-objcUITests.xctrunner" failed." UserInfo={BSErrorCodeDescription=RequestDenied, NSLocalizedDescription=The request to open "io.bitrise.ios-simple-objcUITests.xctrunner" failed., NSUnderlyingError=0x7fb8160bea40 {Error Domain=SBWorkspaceTransaction Code=1 "Launch failed" UserInfo={SBTransaction=SBSuspendedWorkspaceTransaction, NSLocalizedFailureReason=Launch failed}}, FBSOpenApplicationRequestID=0xf30, NSLocalizedFailureReason=The request was denied by service delegate (SBMainWorkspace). If you believe this error represents a bug, please attach the result bundle at`,
`aaError Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open "io.bitrise.ios-simple-objcUITests.xctrunner" failed." UserInfo={BSErrorCodeDescription=RequestDenied, NSLocalizedDescription=The request to open "io.bitrise.ios-simple-objcUITests.xctrunner" failed., NSUnderlyingError=0x7fb8160bea40 {Error Domain=SBWorkspaceTransaction Code=1 "Launch failed" UserInfo={SBTransaction=SBSuspendedWorkspaceTransaction, NSLocalizedFailureReason=Launch failed}}, FBSOpenApplicationRequestID=0xf30, NSLocalizedFailureReason=The request was denied by service delegate (SBMainWorkspace).aa`,
`aa Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open "io.bitrise.ios-simple-objcUITests.xctrunner" failed." UserInfo={BSErrorCodeDescription=RequestDenied, NSLocalizedDescription=The request to open "io.bitrise.ios-simple-objcUITests.xctrunner" failed., NSUnderlyingError=0x7fb8160bea40 {Error Domain=SBWorkspaceTransaction Code=1 "Launch failed" UserInfo={SBTransaction=SBSuspendedWorkspaceTransaction, NSLocalizedFailureReason=Launch failed}}, FBSOpenApplicationRequestID=0xf30, NSLocalizedFailureReason=The request was denied by service delegate (SBMainWorkspace). aa`,
sampleUITestFailedToBackgroundTestRunner,
} {
testFailedToOpenTestRunner(t, anOutStr, true)
}
}
t.Log("Should NOT find")
{
for _, anOutStr := range []string{
"",
"Assertion Failure:",
"Failure attempting to launch <XCUIApplicationImpl:",
`Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open "io.bitrise.ios-simple-objcUITests.xctrunner" failed."`,
`Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 The request was denied by service delegate (SBMainWorkspace).`,
sampleOKBuildLog,
} {
testFailedToOpenTestRunner(t, anOutStr, false)
}
}
}
func TestIsStringFoundInOutput_appStateIsStillNotRunning(t *testing.T) {
// load sample logs
sampleOKBuildLog, err := loadFileContent("../_samples/xcodebuild-ok.txt")
if err != nil {
t.Fatalf("Failed to load xcodebuild-ok.txt : %s", err)
}
t.Log("Should find")
{
for _, anOutStr := range []string{
`App state is still not running active, state = XCApplicationStateNotRunning`,
`---App state is still not running active, state = XCApplicationStateNotRunning---`,
`Asdf.SchemeUITests
testThis, UI Testing Failure - '<XCUIApplicationImpl: 0x600000433440 com.this.Scheme.Target at /Users/vagrant/Library/Developer/Xcode/DerivedData/App-bfkuwgxmaiprwncotahtjjhoigbm/Build/Products/Debug-iphonesimulator/TheApp.app>' App state is still not running active, state = XCApplicationStateNotRunning
MyAppUITests.swift:32`,
} {
testIsFoundWith(t, appStateIsStillNotRunning, anOutStr, true)
}
}
t.Log("Should NOT find")
{
for _, anOutStr := range []string{
"",
`App state is still not running active, state = XCApplicationStateXXX`,
sampleOKBuildLog,
} {
testIsFoundWith(t, appStateIsStillNotRunning, anOutStr, false)
}
}
}
func TestIsStringFoundInOutput_appAccessibilityIsNotLoaded(t *testing.T) {
// load sample logs
sampleOKBuildLog, err := loadFileContent("../_samples/xcodebuild-ok.txt")
if err != nil {
t.Fatalf("Failed to load xcodebuild-ok.txt : %s", err)
}
t.Log("Should find")
{
for _, anOutStr := range []string{
`UI Testing Failure - App accessibility isn't loaded`,
`---UI Testing Failure - App accessibility isn't loaded---`,
` t = 65.80s Assertion Failure: LivescoreAppUITests.swift:23: UI Testing Failure - App accessibility isn't loaded`,
` t = 0.02s Launch com.tapdm.LiveScore.WhatsTheScore
t = 5.06s Waiting for accessibility to load
t = 65.80s Assertion Failure: LivescoreAppUITests.swift:23: UI Testing Failure - App accessibility isn't loaded
t = 65.81s Tear Down`,
} {
testIsFoundWith(t, appAccessibilityIsNotLoaded, anOutStr, true)
}
}
t.Log("Should NOT find")
{
for _, anOutStr := range []string{
"",
`UI Testing Failure`,
`App accessibility isn't loaded`,
sampleOKBuildLog,
} {
testIsFoundWith(t, appAccessibilityIsNotLoaded, anOutStr, false)
}
}
}
func testIsFoundWith(t *testing.T, searchPattern, outputToSearchIn string, isShouldFind bool) {
if isFound := isStringFoundInOutput(searchPattern, outputToSearchIn); isFound != isShouldFind {
t.Logf("Search pattern was: %s", searchPattern)
t.Logf("Input string to search in was: %s", outputToSearchIn)
t.Fatalf("Expected (%v), actual (%v)", isShouldFind, isFound)
}
}
func testRunnerFailedToInitializeForUITestingWith(t *testing.T, outputToSearchIn string, isShouldFind bool) {
testIsFoundWith(t, testRunnerFailedToInitializeForUITesting, outputToSearchIn, isShouldFind)
}
func timedOutRegisteringForTestingEventWith(t *testing.T, outputToSearchIn string, isShouldFind bool) {
testIsFoundWith(t, timedOutRegisteringForTestingEvent, outputToSearchIn, isShouldFind)
}
func testIPhoneSimulatorTimeoutWith(t *testing.T, outputToSearchIn string, isShouldFind bool) {
testIsFoundWith(t, timeOutMessageIPhoneSimulator, outputToSearchIn, isShouldFind)
}
func testTimeOutMessageUITestWith(t *testing.T, outputToSearchIn string, isShouldFind bool) {
testIsFoundWith(t, timeOutMessageUITest, outputToSearchIn, isShouldFind)
}
func testEarlyUnexpectedExitMessageUITestWith(t *testing.T, outputToSearchIn string, isShouldFind bool) {
testIsFoundWith(t, earlyUnexpectedExit, outputToSearchIn, isShouldFind)
}
func testFailureAttemptingToLaunch(t *testing.T, outputToSearchIn string, isShouldFind bool) {
testIsFoundWith(t, failureAttemptingToLaunch, outputToSearchIn, isShouldFind)
}
func testFailedToBackgroundTestRunner(t *testing.T, outputToSearchIn string, isShouldFind bool) {
testIsFoundWith(t, failedToBackgroundTestRunner, outputToSearchIn, isShouldFind)
}
func testFailedToOpenTestRunner(t *testing.T, outputToSearchIn string, isShouldFind bool) {
testIsFoundWith(t, failedToOpenTestRunner, outputToSearchIn, isShouldFind)
}
func loadFileContent(filePth string) (string, error) {
fileBytes, err := ioutil.ReadFile(filePth)
if err != nil {
return "", err
}
return string(fileBytes), nil
}
<file_sep>package step
import (
"errors"
"fmt"
"path"
"path/filepath"
"strings"
"time"
"github.com/bitrise-io/go-steputils/stepconf"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/pathutil"
"github.com/bitrise-io/go-utils/progress"
"github.com/bitrise-io/go-utils/retry"
"github.com/bitrise-io/go-xcode/destination"
"github.com/bitrise-steplib/steps-xcode-test/cache"
"github.com/bitrise-steplib/steps-xcode-test/output"
"github.com/bitrise-steplib/steps-xcode-test/simulator"
"github.com/bitrise-steplib/steps-xcode-test/xcodebuild"
"github.com/bitrise-steplib/steps-xcode-test/xcpretty"
)
const (
minSupportedXcodeMajorVersion = 6
simulatorShutdownState = "Shutdown"
)
// Input ...
type Input struct {
ProjectPath string `env:"project_path,required"`
Scheme string `env:"scheme,required"`
Destination string `env:"destination,required"`
TestPlan string `env:"test_plan"`
// Test Repetition
TestRepetitionMode string `env:"test_repetition_mode,opt[none,until_failure,retry_on_failure,up_until_maximum_repetitions]"`
MaximumTestRepetitions int `env:"maximum_test_repetitions,required"`
RelaunchTestsForEachRepetition bool `env:"relaunch_tests_for_each_repetition,opt[yes,no]"`
RetryTestsOnFailure bool `env:"should_retry_test_on_fail,opt[yes,no]"`
// xcodebuild configuration
XCConfigContent string `env:"xcconfig_content"`
PerformCleanAction bool `env:"perform_clean_action,opt[yes,no]"`
XcodebuildOptions string `env:"xcodebuild_options"`
// xcodebuild log formatting
LogFormatter string `env:"log_formatter,opt[xcpretty,xcodebuild]"`
XcprettyOptions string `env:"xcpretty_options"`
// Caching
CacheLevel string `env:"cache_level,opt[none,swift_packages]"`
// Debugging
VerboseLog bool `env:"verbose_log,opt[yes,no]"`
CollectSimulatorDiagnostics string `env:"collect_simulator_diagnostics,opt[always,on_failure,never]"`
HeadlessMode bool `env:"headless_mode,opt[yes,no]"`
// Output export
DeployDir string `env:"BITRISE_DEPLOY_DIR"`
}
type exportCondition string
const (
always = "always"
never = "never"
onFailure = "on_failure"
)
// Config ...
type Config struct {
ProjectPath string
Scheme string
TestPlan string
SimulatorID string
IsSimulatorBooted bool
XcodeMajorVersion int
TestRepetitionMode string
MaximumTestRepetitions int
RelaunchTestForEachRepetition bool
RetryTestsOnFailure bool
XCConfigContent string
PerformCleanAction bool
XcodebuildOptions string
LogFormatter string
XcprettyOptions string
CacheLevel string
CollectSimulatorDiagnostics exportCondition
HeadlessMode bool
DeployDir string
}
// XcodeTestRunner ...
type XcodeTestRunner struct {
inputParser stepconf.InputParser
logger log.Logger
xcprettyInstaller xcpretty.Installer
xcodebuild xcodebuild.Xcodebuild
simulatorManager simulator.Manager
cache cache.SwiftPackageCache
outputExporter output.Exporter
pathModifier pathutil.PathModifier
pathProvider pathutil.PathProvider
}
// NewXcodeTestRunner ...
func NewXcodeTestRunner(inputParser stepconf.InputParser, logger log.Logger, xcprettyInstaller xcpretty.Installer, xcodebuild xcodebuild.Xcodebuild, simulatorManager simulator.Manager, cache cache.SwiftPackageCache, outputExporter output.Exporter, pathModifier pathutil.PathModifier, pathProvider pathutil.PathProvider) XcodeTestRunner {
return XcodeTestRunner{
inputParser: inputParser,
logger: logger,
xcprettyInstaller: xcprettyInstaller,
xcodebuild: xcodebuild,
simulatorManager: simulatorManager,
cache: cache,
outputExporter: outputExporter,
pathModifier: pathModifier,
pathProvider: pathProvider,
}
}
// ProcessConfig ...
func (s XcodeTestRunner) ProcessConfig() (Config, error) {
var input Input
err := s.inputParser.Parse(&input)
if err != nil {
return Config{}, err
}
stepconf.Print(input)
s.logger.Println()
s.logger.EnableDebugLog(input.VerboseLog)
// validate Xcode version
xcodebuildVersion, err := s.xcodebuild.Version()
if err != nil {
return Config{}, fmt.Errorf("failed to determine Xcode version, error: %s", err)
}
s.logger.Printf("- xcodebuildVersion: %s (%s)", xcodebuildVersion.Version, xcodebuildVersion.BuildVersion)
if err := s.validateXcodeVersion(&input, int(xcodebuildVersion.MajorVersion)); err != nil {
return Config{}, err
}
// validate project path
projectPath, err := s.pathModifier.AbsPath(input.ProjectPath)
if err != nil {
return Config{}, fmt.Errorf("failed to get absolute project path, error: %s", err)
}
if filepath.Ext(projectPath) != ".xcodeproj" && filepath.Ext(projectPath) != ".xcworkspace" {
return Config{}, fmt.Errorf("invalid project file (%s), extension should be (.xcodeproj/.xcworkspace)", projectPath)
}
sim, err := s.getSimulatorForDestination(input.Destination)
if err != nil {
return Config{}, err
}
// validate test repetition related inputs
if input.TestRepetitionMode != xcodebuild.TestRepetitionNone && input.MaximumTestRepetitions < 2 {
return Config{}, fmt.Errorf("invalid number of Maximum Test Repetitions (maximum_test_repetitions): %d, should be more than 1", input.MaximumTestRepetitions)
}
if input.RelaunchTestsForEachRepetition && input.TestRepetitionMode == xcodebuild.TestRepetitionNone {
return Config{}, errors.New("Relaunch Tests for Each Repetition (relaunch_tests_for_each_repetition) cannot be used if Test Repetition Mode (test_repetition_mode) is 'none'")
}
return createConfig(input, projectPath, int(xcodebuildVersion.MajorVersion), sim), nil
}
// InstallDeps ...
func (s XcodeTestRunner) InstallDeps(xcpretty bool) error {
if !xcpretty {
return nil
}
xcprettyVersion, err := s.xcprettyInstaller.Install()
if err != nil {
return fmt.Errorf("an error occured during installing xcpretty: %s", err)
}
s.logger.Printf("- xcprettyVersion: %s", xcprettyVersion.String())
s.logger.Println()
return nil
}
// Result ...
type Result struct {
Scheme string
DeployDir string
XcresultPath string
XcodebuildBuildLog string
XcodebuildTestLog string
SimulatorDiagnosticsPath string
}
// Run ...
func (s XcodeTestRunner) Run(cfg Config) (Result, error) {
enableSimulatorVerboseLog := cfg.CollectSimulatorDiagnostics != never
launchSimulator := !cfg.IsSimulatorBooted && !cfg.HeadlessMode
if err := s.prepareSimulator(enableSimulatorVerboseLog, cfg.SimulatorID, launchSimulator); err != nil {
return Result{}, err
}
var testErr error
var testExitCode int
result, code, err := s.runTests(cfg)
if err != nil {
if code == -1 {
return result, err
}
testErr = err
testExitCode = code
}
result.SimulatorDiagnosticsPath = s.teardownSimulator(cfg.SimulatorID, cfg.CollectSimulatorDiagnostics, cfg.IsSimulatorBooted, testErr)
if testErr != nil {
s.logger.Println()
s.logger.Warnf("Xcode Test command exit code: %d", testExitCode)
s.logger.Errorf("Xcode Test command failed, error: %s", testErr)
return result, testErr
}
// Cache swift PM
if cfg.XcodeMajorVersion >= 11 && cfg.CacheLevel == "swift_packages" {
if err := s.cache.CollectSwiftPackages(cfg.ProjectPath); err != nil {
s.logger.Warnf("Failed to mark swift packages for caching, error: %s", err)
}
}
s.logger.Println()
s.logger.Infof("Xcode Test command succeeded.")
return result, nil
}
// Export ...
func (s XcodeTestRunner) Export(result Result, testFailed bool) error {
// export test run status
s.outputExporter.ExportTestRunResult(testFailed)
if result.XcresultPath != "" {
s.outputExporter.ExportXCResultBundle(result.DeployDir, result.XcresultPath, result.Scheme)
}
// export xcodebuild build log
if result.XcodebuildBuildLog != "" {
if err := s.outputExporter.ExportXcodebuildBuildLog(result.DeployDir, result.XcodebuildBuildLog); err != nil {
return err
}
}
// export xcodebuild test log
if result.XcodebuildTestLog != "" {
if err := s.outputExporter.ExportXcodebuildTestLog(result.DeployDir, result.XcodebuildTestLog); err != nil {
return err
}
}
// export simulator diagnostics log
if result.SimulatorDiagnosticsPath != "" {
diagnosticsName, err := s.simulatorManager.SimulatorDiagnosticsName()
if err != nil {
return err
}
if err := s.outputExporter.ExportSimulatorDiagnostics(result.DeployDir, result.SimulatorDiagnosticsPath, diagnosticsName); err != nil {
return err
}
}
return nil
}
func (s XcodeTestRunner) validateXcodeVersion(input *Input, xcodeMajorVersion int) error {
if xcodeMajorVersion < minSupportedXcodeMajorVersion {
return fmt.Errorf("invalid Xcode major version (%d), should not be less then min supported: %d", xcodeMajorVersion, minSupportedXcodeMajorVersion)
}
if xcodeMajorVersion < 11 && input.TestPlan != "" {
return fmt.Errorf("input Test Plan incompatible with Xcode %d, at least Xcode 11 required", xcodeMajorVersion)
}
// validate headless mode
if xcodeMajorVersion < 9 && input.HeadlessMode {
s.logger.Warnf("Headless mode is enabled but it's only available with Xcode 9.x or newer.")
input.HeadlessMode = false
}
// validate simulator diagnosis mode
if input.CollectSimulatorDiagnostics != never && xcodeMajorVersion < 10 {
s.logger.Warnf("Collecting Simulator diagnostics is not available below Xcode version 10, current Xcode version: %s", xcodeMajorVersion)
input.CollectSimulatorDiagnostics = never
}
if input.TestRepetitionMode != xcodebuild.TestRepetitionNone && xcodeMajorVersion < 13 {
return errors.New("Test Repetition Mode (test_repetition_mode) is not available below Xcode 13")
}
if input.RetryTestsOnFailure && xcodeMajorVersion > 12 {
return errors.New("Should retry tests on failure? (should_retry_test_on_fail) is not available above Xcode 12; use test_repetition_mode=retry_on_failure instead")
}
return nil
}
func (s XcodeTestRunner) getSimulatorForDestination(destinationSpecifier string) (simulator.Simulator, error) {
var sim simulator.Simulator
var osVersion string
simulatorDestination, err := destination.NewSimulator(destinationSpecifier)
if err != nil {
return simulator.Simulator{}, fmt.Errorf("invalid destination specifier: %v", err)
}
platform := strings.TrimSuffix(simulatorDestination.Platform, " Simulator")
// Retry gathering device information since xcrun simctl list can fail to show the complete device list
if err := retry.Times(3).Wait(10 * time.Second).Try(func(attempt uint) error {
var errGetSimulator error
if simulatorDestination.OS == "latest" {
simulatorDevice := simulatorDestination.Name
if simulatorDevice == "iPad" {
s.logger.Warnf("Given device (%s) is deprecated, using iPad Air (3rd generation)...", simulatorDevice)
simulatorDevice = "iPad Air (3rd generation)"
}
sim, osVersion, errGetSimulator = s.simulatorManager.GetLatestSimulatorAndVersion(platform, simulatorDevice)
} else {
normalizedOsVersion := simulatorDestination.OS
osVersionSplit := strings.Split(normalizedOsVersion, ".")
if len(osVersionSplit) > 2 {
normalizedOsVersion = strings.Join(osVersionSplit[0:2], ".")
}
osVersion = fmt.Sprintf("%s %s", platform, normalizedOsVersion)
sim, errGetSimulator = s.simulatorManager.GetSimulator(osVersion, simulatorDestination.Name)
}
if errGetSimulator != nil {
s.logger.Warnf("attempt %d to get simulator UDID failed with error: %s", attempt, errGetSimulator)
}
return errGetSimulator
}); err != nil {
return simulator.Simulator{}, fmt.Errorf("simulator UDID lookup failed: %s", err)
}
s.logger.Infof("Simulator infos")
s.logger.Printf("* simulator_name: %s, version: %s, UDID: %s, status: %s", sim.Name, osVersion, sim.ID, sim.Status)
return sim, nil
}
func (s XcodeTestRunner) prepareSimulator(enableSimulatorVerboseLog bool, simulatorID string, launchSimulator bool) error {
err := s.simulatorManager.ResetLaunchServices()
if err != nil {
s.logger.Warnf("Failed to apply simulator boot workaround, error: %s", err)
}
// Boot simulator
if enableSimulatorVerboseLog {
s.logger.Infof("Enabling Simulator verbose log for better diagnostics")
// Boot the simulator now, so verbose logging can be enabled, and it is kept booted after running tests.
if err := s.simulatorManager.SimulatorBoot(simulatorID); err != nil {
return fmt.Errorf("%v", err)
}
if err := s.simulatorManager.SimulatorEnableVerboseLog(simulatorID); err != nil {
return fmt.Errorf("%v", err)
}
s.logger.Println()
}
if launchSimulator {
s.logger.Infof("Booting simulator (%s)...", simulatorID)
if err := s.simulatorManager.LaunchSimulator(simulatorID); err != nil {
return fmt.Errorf("failed to boot simulator, error: %s", err)
}
progress.NewDefaultWrapper("Waiting for simulator boot").WrapAction(func() {
time.Sleep(60 * time.Second)
})
s.logger.Println()
}
return nil
}
func (s XcodeTestRunner) runTests(cfg Config) (Result, int, error) {
// Run build
result := Result{
Scheme: cfg.Scheme,
DeployDir: cfg.DeployDir,
}
// Run test
tempDir, err := s.pathProvider.CreateTempDir("XCUITestOutput")
if err != nil {
return result, -1, fmt.Errorf("could not create test output temporary directory: %s", err)
}
xcresultPath := path.Join(tempDir, "Test.xcresult")
var swiftPackagesPath string
if cfg.XcodeMajorVersion >= 11 {
var err error
swiftPackagesPath, err = s.cache.SwiftPackagesPath(cfg.ProjectPath)
if err != nil {
return result, -1, fmt.Errorf("failed to get Swift Packages path, error: %s", err)
}
}
testParams := createTestParams(cfg, xcresultPath, swiftPackagesPath)
testLog, exitCode, testErr := s.xcodebuild.RunTest(testParams)
result.XcresultPath = xcresultPath
result.XcodebuildTestLog = testLog
if testErr != nil || cfg.LogFormatter == xcodebuild.XcodebuildTool {
printLastLinesOfXcodebuildTestLog(testLog, testErr == nil)
}
return result, exitCode, testErr
}
func (s XcodeTestRunner) teardownSimulator(simulatorID string, simulatorDebug exportCondition, isSimulatorBooted bool, testErr error) string {
var simulatorDiagnosticsPath string
if simulatorDebug == always || (simulatorDebug == onFailure && testErr != nil) {
s.logger.Println()
s.logger.Infof("Collecting Simulator diagnostics")
diagnosticsPath, err := s.simulatorManager.SimulatorCollectDiagnostics()
if err != nil {
s.logger.Warnf("%v", err)
} else {
s.logger.Donef("Simulator diagnostics are available as an artifact (%s)", diagnosticsPath)
simulatorDiagnosticsPath = diagnosticsPath
}
}
// Shut down the simulator if it was started by the step for diagnostic logs.
if !isSimulatorBooted && simulatorDebug != never {
if err := s.simulatorManager.SimulatorShutdown(simulatorID); err != nil {
s.logger.Warnf("%v", err)
}
}
return simulatorDiagnosticsPath
}
func createConfig(input Input, projectPath string, xcodeMajorVersion int, sim simulator.Simulator) Config {
return Config{
ProjectPath: projectPath,
Scheme: input.Scheme,
TestPlan: input.TestPlan,
SimulatorID: sim.ID,
IsSimulatorBooted: sim.Status != simulatorShutdownState,
XcodeMajorVersion: xcodeMajorVersion,
TestRepetitionMode: input.TestRepetitionMode,
MaximumTestRepetitions: input.MaximumTestRepetitions,
RelaunchTestForEachRepetition: input.RelaunchTestsForEachRepetition,
RetryTestsOnFailure: input.RetryTestsOnFailure,
XCConfigContent: input.XCConfigContent,
PerformCleanAction: input.PerformCleanAction,
XcodebuildOptions: input.XcodebuildOptions,
LogFormatter: input.LogFormatter,
XcprettyOptions: input.XcprettyOptions,
CacheLevel: input.CacheLevel,
CollectSimulatorDiagnostics: exportCondition(input.CollectSimulatorDiagnostics),
HeadlessMode: input.HeadlessMode,
DeployDir: input.DeployDir,
}
}
func createTestParams(cfg Config, xcresultPath, swiftPackagesPath string) xcodebuild.TestRunParams {
testParams := xcodebuild.TestParams{
ProjectPath: cfg.ProjectPath,
Scheme: cfg.Scheme,
Destination: fmt.Sprintf("id=%s", cfg.SimulatorID),
TestPlan: cfg.TestPlan,
TestOutputDir: xcresultPath,
TestRepetitionMode: cfg.TestRepetitionMode,
MaximumTestRepetitions: cfg.MaximumTestRepetitions,
RelaunchTestsForEachRepetition: cfg.RelaunchTestForEachRepetition,
XCConfigContent: cfg.XCConfigContent,
PerformCleanAction: cfg.PerformCleanAction,
RetryTestsOnFailure: cfg.RetryTestsOnFailure,
AdditionalOptions: cfg.XcodebuildOptions,
}
return xcodebuild.TestRunParams{
TestParams: testParams,
LogFormatter: cfg.LogFormatter,
XcprettyOptions: cfg.XcprettyOptions,
RetryOnTestRunnerError: true,
RetryOnSwiftPackageResolutionError: true,
SwiftPackagesPath: swiftPackagesPath,
XcodeMajorVersion: cfg.XcodeMajorVersion,
}
}
<file_sep>package xcodebuild
import (
"github.com/bitrise-io/go-utils/command"
"github.com/bitrise-io/go-utils/fileutil"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/pathutil"
"github.com/bitrise-io/go-xcode/models"
"github.com/bitrise-io/go-xcode/utility"
"github.com/bitrise-io/go-xcode/xcconfig"
)
// Output tools ...
const (
XcodebuildTool = "xcodebuild"
XcprettyTool = "xcpretty"
)
// Test repetition modes ...
const (
TestRepetitionNone = "none"
TestRepetitionUntilFailure = "until_failure"
TestRepetitionRetryOnFailure = "retry_on_failure"
)
// Xcodebuild ....
type Xcodebuild interface {
RunTest(params TestRunParams) (string, int, error)
Version() (Version, error)
}
type xcodebuild struct {
logger log.Logger
commandFactory command.Factory
pathChecker pathutil.PathChecker
fileManager fileutil.FileManager
xcconfigWriter xcconfig.Writer
}
// NewXcodebuild ...
func NewXcodebuild(logger log.Logger, commandFactory command.Factory, pathChecker pathutil.PathChecker, fileManager fileutil.FileManager, xcconfigWriter xcconfig.Writer) Xcodebuild {
return &xcodebuild{
logger: logger,
commandFactory: commandFactory,
pathChecker: pathChecker,
fileManager: fileManager,
xcconfigWriter: xcconfigWriter,
}
}
// Version ...
type Version models.XcodebuildVersionModel
func (b *xcodebuild) Version() (Version, error) {
version, err := utility.GetXcodeVersion(b.commandFactory)
return Version(version), err
}
// TestRunParams ...
type TestRunParams struct {
TestParams TestParams
LogFormatter string
XcprettyOptions string
RetryOnTestRunnerError bool
RetryOnSwiftPackageResolutionError bool
SwiftPackagesPath string
XcodeMajorVersion int
}
// RunTest ...
func (b *xcodebuild) RunTest(params TestRunParams) (string, int, error) {
return b.runTest(params)
}
<file_sep>package testartifact
import (
"path/filepath"
"reflect"
"testing"
"time"
"github.com/bitrise-io/go-utils/pretty"
"github.com/bitrise-steplib/steps-xcode-test/testartifact/testsummaries"
)
func Test_createRenamePlan(t *testing.T) {
const attachmentDir = "/tmp/test"
const testID = "project/testSuccess()"
const activityTitle = "Start Test"
const activityUUID = "CE23D189-E75A-437D-A4B5-B97F1658FC98"
const fileName = "Screenshot of main screen (ID 1)_1_A07C26DB-8E1E-46ED-90F2-981438BE0BBA.png"
timeStamp := time.Time{}
type args struct {
testResults []testsummaries.TestResult
attachmentDir string
}
tests := []struct {
name string
args args
want map[string]string
}{
{
name: "Empty",
args: args{
testResults: []testsummaries.TestResult{
{},
},
attachmentDir: attachmentDir,
},
want: map[string]string{},
},
{
name: "Test result with screenshots",
args: args{
testResults: []testsummaries.TestResult{{
ID: testID,
Status: "Success",
FailureInfo: nil,
Activities: []testsummaries.Activity{{
Title: activityTitle,
UUID: activityUUID,
Screenshots: []testsummaries.Screenshot{{
FileName: fileName,
TimeCreated: timeStamp,
}},
}},
}},
attachmentDir: attachmentDir,
},
want: map[string]string{
filepath.Join(attachmentDir, fileName): filepath.Join(attachmentDir, "project-testSuccess()_0001-01-01_12-00-00_Start Test_CE23D189-E75A-437D-A4B5-B97F1658FC98.png"),
},
},
{
name: "Failing test result with screenshots",
args: args{
testResults: []testsummaries.TestResult{{
ID: testID,
Status: "Failure",
FailureInfo: nil,
Activities: []testsummaries.Activity{{
Title: activityTitle,
UUID: activityUUID,
Screenshots: []testsummaries.Screenshot{{
FileName: fileName,
TimeCreated: timeStamp,
}},
}},
}},
attachmentDir: attachmentDir,
},
want: map[string]string{
filepath.Join(attachmentDir, fileName): filepath.Join(attachmentDir, "Failures", "project-testSuccess()_0001-01-01_12-00-00_Start Test_CE23D189-E75A-437D-A4B5-B97F1658FC98.png"),
},
},
{
name: "Test result with subactivity screenshot",
args: args{
testResults: []testsummaries.TestResult{{
ID: testID,
Status: "Success",
FailureInfo: nil,
Activities: []testsummaries.Activity{{
Title: "Launch",
UUID: "uuid",
Screenshots: nil,
SubActivities: []testsummaries.Activity{{
Title: activityTitle,
UUID: activityUUID,
Screenshots: []testsummaries.Screenshot{{
FileName: fileName,
TimeCreated: timeStamp,
}},
SubActivities: nil,
}},
}},
}},
attachmentDir: attachmentDir,
},
want: map[string]string{
filepath.Join(attachmentDir, fileName): filepath.Join(attachmentDir, "project-testSuccess()_0001-01-01_12-00-00_Start Test_CE23D189-E75A-437D-A4B5-B97F1658FC98.png"),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := createRenamePlan(tt.args.testResults, tt.args.attachmentDir); !reflect.DeepEqual(got, tt.want) {
t.Errorf("createRenamePlan() = %v, want %v", pretty.Object(got), pretty.Object(tt.want))
}
})
}
}
<file_sep>module github.com/bitrise-steplib/steps-xcode-test
go 1.16
require (
github.com/bitrise-io/bitrise v0.0.0-20210830100501-97b6f7d7905b
github.com/bitrise-io/go-steputils v0.0.0-20210929162140-866a65a1e14a
github.com/bitrise-io/go-utils v0.0.0-20210930092040-cceb74a5ac24
github.com/bitrise-io/go-xcode v0.0.0-20211007125122-93e3a53643a2
github.com/hashicorp/go-version v1.3.0
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
github.com/stretchr/testify v1.7.0
)
<file_sep>package simulator
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/bitrise-io/go-utils/command"
"github.com/bitrise-io/go-utils/errorutil"
"github.com/bitrise-io/go-utils/log"
sim "github.com/bitrise-io/go-xcode/simulator"
)
// Simulator ...
type Simulator sim.InfoModel
// Manager ...
type Manager interface {
GetLatestSimulatorAndVersion(osName, deviceName string) (Simulator, string, error)
GetSimulator(osNameAndVersion, deviceName string) (Simulator, error)
LaunchSimulator(simulatorID string) error
ResetLaunchServices() error
SimulatorBoot(id string) error
SimulatorEnableVerboseLog(id string) error
SimulatorCollectDiagnostics() (string, error)
SimulatorShutdown(id string) error
SimulatorDiagnosticsName() (string, error)
}
type manager struct {
commandFactory command.Factory
}
// NewManager ...
func NewManager(commandFactory command.Factory) Manager {
return manager{
commandFactory: commandFactory,
}
}
func (m manager) GetLatestSimulatorAndVersion(osName, deviceName string) (Simulator, string, error) {
info, ver, err := sim.GetLatestSimulatorInfoAndVersion(osName, deviceName)
return Simulator(info), ver, err
}
func (m manager) GetSimulator(osNameAndVersion, deviceName string) (Simulator, error) {
info, err := sim.GetSimulatorInfo(osNameAndVersion, deviceName)
return Simulator(info), err
}
func (m manager) LaunchSimulator(simulatorID string) error {
return sim.BootSimulator(simulatorID)
}
// Reset launch services database to avoid Big Sur's sporadic failure to find the Simulator App
// The following error is printed when this happens: "kLSNoExecutableErr: The executable is missing"
// Details:
// - https://stackoverflow.com/questions/2182040/the-application-cannot-be-opened-because-its-executable-is-missing/16546673#16546673
// - https://ss64.com/osx/lsregister.html
func (m manager) ResetLaunchServices() error {
cmd := m.commandFactory.Create("sw_vers", []string{"-productVersion"}, nil)
macOSVersion, err := cmd.RunAndReturnTrimmedCombinedOutput()
if err != nil {
return err
}
if strings.HasPrefix(macOSVersion, "11.") { // It's Big Sur
cmd := m.commandFactory.Create("xcode-select", []string{"--print-path"}, nil)
xcodeDevDirPath, err := cmd.RunAndReturnTrimmedCombinedOutput()
if err != nil {
return err
}
simulatorAppPath := filepath.Join(xcodeDevDirPath, "Applications", "Simulator.app")
cmdString := "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"
cmd = m.commandFactory.Create(cmdString, []string{"-f", simulatorAppPath}, nil)
log.Infof("Applying launch services reset workaround before booting simulator")
_, err = cmd.RunAndReturnTrimmedCombinedOutput()
if err != nil {
return err
}
}
return nil
}
func (m manager) SimulatorBoot(id string) error {
cmd := m.commandFactory.Create("xcrun", []string{"simctl", "boot", id}, &command.Opts{
Stdout: os.Stdout,
Stderr: os.Stderr,
})
log.Donef("$ %s", cmd.PrintableCommandArgs())
exitCode, err := cmd.RunAndReturnExitCode()
if err != nil {
if errorutil.IsExitStatusError(err) {
if exitCode == 149 { // Simulator already booted
return nil
}
log.Warnf("Failed to boot Simulator, command exited with code %d", exitCode)
return nil
}
return fmt.Errorf("failed to boot Simulator, command execution failed: %v", err)
}
return nil
}
// Simulator needs to be booted to enable verbose log
func (m manager) SimulatorEnableVerboseLog(id string) error {
cmd := m.commandFactory.Create("xcrun", []string{"simctl", "logverbose", id, "enable"}, &command.Opts{
Stdout: os.Stdout,
Stderr: os.Stderr,
})
log.Donef("$ %s", cmd.PrintableCommandArgs())
if err := cmd.Run(); err != nil {
if errorutil.IsExitStatusError(err) {
log.Warnf("Failed to enable Simulator verbose logging, command exited with code %d", err)
return nil
}
return fmt.Errorf("failed to enable Simulator verbose logging, command execution failed: %v", err)
}
return nil
}
func (m manager) SimulatorCollectDiagnostics() (string, error) {
diagnosticsName, err := m.SimulatorDiagnosticsName()
if err != nil {
return "", err
}
diagnosticsOutDir, err := ioutil.TempDir("", diagnosticsName)
if err != nil {
return "", fmt.Errorf("failed to collect Simulator diagnostics, could not create temporary directory: %v", err)
}
cmd := m.commandFactory.Create("xcrun", []string{"simctl", "diagnose", "-b", "--no-archive", fmt.Sprintf("--output=%s", diagnosticsOutDir)}, &command.Opts{
Stdout: os.Stdout,
Stderr: os.Stderr,
Stdin: bytes.NewReader([]byte("\n")),
})
log.Donef("$ %s", cmd.PrintableCommandArgs())
if err := cmd.Run(); err != nil {
if errorutil.IsExitStatusError(err) {
return "", fmt.Errorf("failed to collect Simulator diagnostics: %v", err)
}
return "", fmt.Errorf("failed to collect Simulator diagnostics, command execution failed: %v", err)
}
return diagnosticsOutDir, nil
}
func (m manager) SimulatorShutdown(id string) error {
cmd := m.commandFactory.Create("xcrun", []string{"simctl", "shutdown", id}, &command.Opts{
Stdout: os.Stdout,
Stderr: os.Stderr,
})
log.Donef("$ %s", cmd.PrintableCommandArgs())
exitCode, err := cmd.RunAndReturnExitCode()
if err != nil {
if errorutil.IsExitStatusError(err) {
if exitCode == 149 { // Simulator already shut down
return nil
}
log.Warnf("Failed to shutdown Simulator, command exited with code %d", exitCode)
return nil
}
return fmt.Errorf("failed to shutdown Simulator, command execution failed: %v", err)
}
return nil
}
func (m manager) SimulatorDiagnosticsName() (string, error) {
timestamp, err := time.Now().MarshalText()
if err != nil {
return "", fmt.Errorf("failed to collect Simulator diagnostics, failed to marshal timestamp: %v", err)
}
return fmt.Sprintf("simctl_diagnose_%s.zip", strings.ReplaceAll(string(timestamp), ":", "-")), nil
}
<file_sep>package step
import (
"testing"
mocklog "github.com/bitrise-io/go-utils/log/mocks"
mockPathutil "github.com/bitrise-io/go-utils/pathutil/mocks"
mockcache "github.com/bitrise-steplib/steps-xcode-test/cache/mocks"
mocksimulator "github.com/bitrise-steplib/steps-xcode-test/simulator/mocks"
mockxcodebuild "github.com/bitrise-steplib/steps-xcode-test/xcodebuild/mocks"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
func Test_WhenTestRuns_ThenXcodebuildGetsCalled(t *testing.T) {
// Given
logger := createLogger()
xcodebuilder := new(mockxcodebuild.Xcodebuild)
xcodebuilder.On("RunTest", mock.Anything).Return("", 0, nil)
simulatorManager := new(mocksimulator.Manager)
simulatorManager.On("ResetLaunchServices").Return(nil)
cache := new(mockcache.SwiftPackageCache)
cache.On("SwiftPackagesPath", mock.Anything).Return("", nil)
pathProvider := new(mockPathutil.PathProvider)
pathProvider.On("CreateTempDir", mock.Anything).Return("tmp_dir", nil)
step := NewXcodeTestRunner(nil, logger, nil, xcodebuilder, simulatorManager, cache, nil, nil, pathProvider)
config := Config{
ProjectPath: "./project.xcodeproj",
Scheme: "Project",
XcodeMajorVersion: 13,
SimulatorID: "1234",
IsSimulatorBooted: true,
TestRepetitionMode: "none",
MaximumTestRepetitions: 0,
RelaunchTestForEachRepetition: true,
RetryTestsOnFailure: false,
LogFormatter: "xcodebuild",
PerformCleanAction: false,
CacheLevel: "",
CollectSimulatorDiagnostics: never,
HeadlessMode: true,
}
// When
_, err := step.Run(config)
// Then
require.NoError(t, err)
xcodebuilder.AssertCalled(t, "RunTest", mock.Anything)
}
func createLogger() (logger *mocklog.Logger) {
logger = new(mocklog.Logger)
logger.On("Infof", mock.Anything, mock.Anything).Return()
logger.On("Debugf", mock.Anything, mock.Anything).Return()
logger.On("Donef", mock.Anything, mock.Anything).Return()
logger.On("Printf", mock.Anything, mock.Anything).Return()
logger.On("Errorf", mock.Anything, mock.Anything).Return()
logger.On("Println").Return()
logger.On("EnableDebugLog", mock.Anything).Return()
return
}
<file_sep>package xcodebuild
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"syscall"
"time"
"github.com/bitrise-io/go-utils/command"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/progress"
cache "github.com/bitrise-io/go-xcode/xcodecache"
"github.com/kballard/go-shellquote"
)
// On performance limited OS X hosts (ex: VMs) the iPhone/iOS Simulator might time out
// while booting. So far it seems that a simple retry solves these issues.
const (
// This boot timeout can happen when running Unit Tests with Xcode Command Line `xcodebuild`.
timeOutMessageIPhoneSimulator = "iPhoneSimulator: Timed out waiting"
// This boot timeout can happen when running Xcode (7+) UI tests with Xcode Command Line `xcodebuild`.
timeOutMessageUITest = "Terminating app due to uncaught exception '_XCTestCaseInterruptionException'"
earlyUnexpectedExit = "Early unexpected exit, operation never finished bootstrapping - no restart will be attempted"
failureAttemptingToLaunch = "Assertion Failure: <unknown>:0: UI Testing Failure - Failure attempting to launch <XCUIApplicationImpl:"
failedToBackgroundTestRunner = `Error Domain=IDETestOperationsObserverErrorDomain Code=12 "Failed to background test runner.`
appStateIsStillNotRunning = `App state is still not running active, state = XCApplicationStateNotRunning`
appAccessibilityIsNotLoaded = `UI Testing Failure - App accessibility isn't loaded`
testRunnerFailedToInitializeForUITesting = `Test runner failed to initialize for UI testing`
timedOutRegisteringForTestingEvent = `Timed out registering for testing event accessibility notifications`
testRunnerNeverBeganExecuting = `Test runner never began executing tests after launching.`
failedToOpenTestRunner = `Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open.*NSLocalizedFailureReason=The request was denied by service delegate \(SBMainWorkspace\)\.`
)
var xcodeCommandEnvs = []string{"NSUnbufferedIO=YES"}
var testRunnerErrorPatterns = []string{
timeOutMessageIPhoneSimulator,
timeOutMessageUITest,
earlyUnexpectedExit,
failureAttemptingToLaunch,
failedToBackgroundTestRunner,
appStateIsStillNotRunning,
appAccessibilityIsNotLoaded,
testRunnerFailedToInitializeForUITesting,
timedOutRegisteringForTestingEvent,
testRunnerNeverBeganExecuting,
failedToOpenTestRunner,
}
// TestParams ...
type TestParams struct {
ProjectPath string
Scheme string
Destination string
TestPlan string
TestOutputDir string
TestRepetitionMode string
MaximumTestRepetitions int
RelaunchTestsForEachRepetition bool
XCConfigContent string
PerformCleanAction bool
RetryTestsOnFailure bool
AdditionalOptions string
}
func (b *xcodebuild) runXcodebuildCmd(args ...string) (string, int, error) {
var outBuffer bytes.Buffer
cmd := b.commandFactory.Create("xcodebuild", args, &command.Opts{
Stdout: &outBuffer,
Stderr: &outBuffer,
Env: xcodeCommandEnvs,
})
b.logger.Printf("$ %s", cmd.PrintableCommandArgs())
b.logger.Println()
var err error
var exitCode int
progress.SimpleProgress(".", time.Minute, func() {
exitCode, err = cmd.RunAndReturnExitCode()
})
return outBuffer.String(), exitCode, err
}
func (b *xcodebuild) runPrettyXcodebuildCmd(useStdOut bool, xcprettyArgs []string, xcodebuildArgs []string) (string, int, error) {
// build outputs:
// - write it into a buffer
// - write it into the pipe, which will be fed into xcpretty
var buildOutBuffer bytes.Buffer
pipeReader, pipeWriter := io.Pipe()
buildOutWriters := []io.Writer{pipeWriter}
buildOutWriter := CreateBufferedWriter(&buildOutBuffer, buildOutWriters...)
//
var prettyOutWriter io.Writer
if useStdOut {
prettyOutWriter = os.Stdout
}
buildCmd := b.commandFactory.Create("xcodebuild", xcodebuildArgs, &command.Opts{
Stdout: buildOutWriter,
Stderr: buildOutWriter,
Env: xcodeCommandEnvs,
})
prettyCmd := b.commandFactory.Create("xcpretty", xcprettyArgs, &command.Opts{
Stdin: pipeReader,
Stdout: prettyOutWriter,
Stderr: prettyOutWriter,
})
b.logger.Printf("$ set -o pipefail && %s | %v", buildCmd.PrintableCommandArgs(), prettyCmd.PrintableCommandArgs())
b.logger.Println()
if err := buildCmd.Start(); err != nil {
return buildOutBuffer.String(), 1, err
}
if err := prettyCmd.Start(); err != nil {
return buildOutBuffer.String(), 1, err
}
defer func() {
if err := pipeWriter.Close(); err != nil {
b.logger.Warnf("Failed to close xcodebuild-xcpretty pipe, error: %s", err)
}
if err := prettyCmd.Wait(); err != nil {
b.logger.Warnf("xcpretty command failed, error: %s", err)
}
}()
if err := buildCmd.Wait(); err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
waitStatus, ok := exitError.Sys().(syscall.WaitStatus)
if !ok {
return buildOutBuffer.String(), 1, errors.New("failed to cast exit status")
}
return buildOutBuffer.String(), waitStatus.ExitStatus(), err
}
return buildOutBuffer.String(), 1, err
}
return buildOutBuffer.String(), 0, nil
}
func (b *xcodebuild) createXcodebuildTestArgs(params TestParams) ([]string, error) {
projectFlag := "-project"
if filepath.Ext(params.ProjectPath) == ".xcworkspace" {
projectFlag = "-workspace"
}
xcodebuildArgs := []string{projectFlag, params.ProjectPath, "-scheme", params.Scheme}
if params.PerformCleanAction {
xcodebuildArgs = append(xcodebuildArgs, "clean")
}
xcodebuildArgs = append(xcodebuildArgs, "test", "-destination", params.Destination)
if params.TestPlan != "" {
xcodebuildArgs = append(xcodebuildArgs, "-testPlan", params.TestPlan)
}
xcodebuildArgs = append(xcodebuildArgs, "-resultBundlePath", params.TestOutputDir)
switch params.TestRepetitionMode {
case TestRepetitionUntilFailure:
xcodebuildArgs = append(xcodebuildArgs, "-run-tests-until-failure")
case TestRepetitionRetryOnFailure:
xcodebuildArgs = append(xcodebuildArgs, "-retry-tests-on-failure")
}
if params.TestRepetitionMode != TestRepetitionNone {
xcodebuildArgs = append(xcodebuildArgs, "-test-iterations", strconv.Itoa(params.MaximumTestRepetitions))
}
if params.RelaunchTestsForEachRepetition {
xcodebuildArgs = append(xcodebuildArgs, "-test-repetition-relaunch-enabled", "YES")
}
if params.XCConfigContent != "" {
xcconfigPath, err := b.xcconfigWriter.Write(params.XCConfigContent)
if err != nil {
return nil, err
}
xcodebuildArgs = append(xcodebuildArgs, "-xcconfig", xcconfigPath)
}
if params.AdditionalOptions != "" {
options, err := shellquote.Split(params.AdditionalOptions)
if err != nil {
return nil, fmt.Errorf("failed to parse additional options (%s), error: %s", params.AdditionalOptions, err)
}
xcodebuildArgs = append(xcodebuildArgs, options...)
}
return xcodebuildArgs, nil
}
func (b *xcodebuild) createXCPrettyArgs(options string) ([]string, error) {
var args []string
if options != "" {
options, err := shellquote.Split(options)
if err != nil {
return nil, fmt.Errorf("failed to parse additional options (%s), error: %s", options, err)
}
// get and delete the xcpretty output file, if exists
xcprettyOutputFilePath := ""
isNextOptOutputPth := false
for _, aOpt := range options {
if isNextOptOutputPth {
xcprettyOutputFilePath = aOpt
break
}
if aOpt == "--output" {
isNextOptOutputPth = true
continue
}
}
if xcprettyOutputFilePath != "" {
if isExist, err := b.pathChecker.IsPathExists(xcprettyOutputFilePath); err != nil {
b.logger.Errorf("Failed to check xcpretty output file status (path: %s), error: %s", xcprettyOutputFilePath, err)
} else if isExist {
b.logger.Warnf("=> Deleting existing xcpretty output: %s", xcprettyOutputFilePath)
if err := b.fileManager.Remove(xcprettyOutputFilePath); err != nil {
b.logger.Errorf("Failed to delete xcpretty output file (path: %s), error: %s", xcprettyOutputFilePath, err)
}
}
}
//
args = append(args, options...)
}
return args, nil
}
func (b *xcodebuild) runTest(params TestRunParams) (string, int, error) {
xcodebuildArgs, err := b.createXcodebuildTestArgs(params.TestParams)
if err != nil {
return "", 1, err
}
b.logger.Infof("Running the tests...")
var rawOutput string
var exit int
var testErr error
if params.LogFormatter == XcprettyTool {
xcprettyArgs, err := b.createXCPrettyArgs(params.XcprettyOptions)
if err != nil {
return "", 1, err
}
rawOutput, exit, testErr = b.runPrettyXcodebuildCmd(true, xcprettyArgs, xcodebuildArgs)
} else {
rawOutput, exit, testErr = b.runXcodebuildCmd(xcodebuildArgs...)
}
fmt.Println("exit: ", exit)
if testErr != nil {
return b.handleTestRunError(params, testRunResult{xcodebuildLog: rawOutput, exitCode: exit, err: testErr})
}
return rawOutput, exit, nil
}
type testRunResult struct {
xcodebuildLog string
exitCode int
err error
}
func (b *xcodebuild) cleanOutputDirAndRerunTest(params TestRunParams) (string, int, error) {
// Clean output directory, otherwise after retry test run, xcodebuild fails with `error: Existing file at -resultBundlePath "..."`
if err := b.fileManager.RemoveAll(params.TestParams.TestOutputDir); err != nil {
return "", 1, fmt.Errorf("failed to clean test output directory: %s, error: %s", params.TestParams.TestOutputDir, err)
}
return b.runTest(params)
}
func (b *xcodebuild) handleTestRunError(prevRunParams TestRunParams, prevRunResult testRunResult) (string, int, error) {
if prevRunParams.RetryOnSwiftPackageResolutionError && prevRunParams.SwiftPackagesPath != "" && isStringFoundInOutput(cache.SwiftPackagesStateInvalid, prevRunResult.xcodebuildLog) {
log.RWarnf("xcode-test", "swift-packages-cache-invalid", nil, "swift packages cache is in an invalid state")
if err := b.fileManager.RemoveAll(prevRunParams.SwiftPackagesPath); err != nil {
b.logger.Errorf("failed to remove Swift package caches, error: %s", err)
return prevRunResult.xcodebuildLog, prevRunResult.exitCode, prevRunResult.err
}
prevRunParams.RetryOnSwiftPackageResolutionError = false
return b.cleanOutputDirAndRerunTest(prevRunParams)
}
for _, errorPattern := range testRunnerErrorPatterns {
if isStringFoundInOutput(errorPattern, prevRunResult.xcodebuildLog) {
b.logger.Warnf("Automatic retry reason found in log: %s", errorPattern)
if prevRunParams.RetryOnTestRunnerError {
b.logger.Printf("Automatic retry is enabled - retrying...")
prevRunParams.TestParams.RetryTestsOnFailure = false
prevRunParams.RetryOnTestRunnerError = false
return b.cleanOutputDirAndRerunTest(prevRunParams)
}
b.logger.Errorf("Automatic retry is disabled, no more retry, stopping the test!")
return prevRunResult.xcodebuildLog, prevRunResult.exitCode, prevRunResult.err
}
}
if prevRunParams.TestParams.RetryTestsOnFailure {
b.logger.Warnf("Test run failed")
b.logger.Printf("'Should retry tests on failure?' (should_retry_test_on_fail) is enabled - retrying...")
prevRunParams.TestParams.RetryTestsOnFailure = false
prevRunParams.RetryOnTestRunnerError = false
return b.cleanOutputDirAndRerunTest(prevRunParams)
}
return prevRunResult.xcodebuildLog, prevRunResult.exitCode, prevRunResult.err
}
func isStringFoundInOutput(searchStr, outputToSearchIn string) bool {
r := regexp.MustCompile("(?i)" + searchStr)
return r.MatchString(outputToSearchIn)
}
// CreateBufferedWriter ...
func CreateBufferedWriter(buff *bytes.Buffer, writers ...io.Writer) io.Writer {
if len(writers) > 0 {
allWriters := append([]io.Writer{buff}, writers...)
return io.MultiWriter(allWriters...)
}
return io.Writer(buff)
}
<file_sep>package xcpretty
import (
"fmt"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-xcode/xcpretty"
"github.com/hashicorp/go-version"
)
// Installer ...
type Installer interface {
Install() (*version.Version, error)
}
type installer struct {
}
// NewInstaller ...
func NewInstaller() Installer {
return &installer{}
}
// Install installs and gets xcpretty version
func (i installer) Install() (*version.Version, error) {
fmt.Println()
log.Infof("Checking if output tool (xcpretty) is installed")
installed, err := xcpretty.IsInstalled()
if err != nil {
return nil, err
} else if !installed {
log.Warnf(`xcpretty is not installed`)
fmt.Println()
log.Printf("Installing xcpretty")
cmdModelSlice, err := xcpretty.Install()
if err != nil {
return nil, fmt.Errorf("failed to install xcpretty: %s", err)
}
for _, cmd := range cmdModelSlice {
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("failed to install xcpretty: %s", err)
}
}
}
xcprettyVersion, err := xcpretty.Version()
if err != nil {
return nil, fmt.Errorf("failed to determine xcpretty version: %s", err)
}
return xcprettyVersion, nil
}
<file_sep>package testaddon
import "path/filepath"
// Exporter ...
type Exporter interface {
CopyAndSaveMetadata(info AddonCopy) error
}
type exporter struct {
}
// NewExporter ...
func NewExporter() Exporter {
return &exporter{}
}
// AddonCopy ...
type AddonCopy struct {
SourceTestOutputDir string
TargetAddonPath string
TargetAddonBundleName string
}
func (e exporter) CopyAndSaveMetadata(info AddonCopy) error {
info.TargetAddonBundleName = replaceUnsupportedFilenameCharacters(info.TargetAddonBundleName)
addonPerStepOutputDir := filepath.Join(info.TargetAddonPath, info.TargetAddonBundleName)
if err := copyDirectory(info.SourceTestOutputDir, addonPerStepOutputDir); err != nil {
return err
}
if err := saveBundleMetadata(addonPerStepOutputDir, info.TargetAddonBundleName); err != nil {
return err
}
return nil
}
<file_sep>package main
import (
"os"
"github.com/bitrise-io/go-steputils/stepconf"
"github.com/bitrise-io/go-steputils/stepenv"
"github.com/bitrise-io/go-utils/command"
"github.com/bitrise-io/go-utils/env"
"github.com/bitrise-io/go-utils/fileutil"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/pathutil"
"github.com/bitrise-io/go-xcode/xcconfig"
"github.com/bitrise-steplib/steps-xcode-test/cache"
"github.com/bitrise-steplib/steps-xcode-test/output"
"github.com/bitrise-steplib/steps-xcode-test/simulator"
"github.com/bitrise-steplib/steps-xcode-test/step"
"github.com/bitrise-steplib/steps-xcode-test/testaddon"
"github.com/bitrise-steplib/steps-xcode-test/xcodebuild"
"github.com/bitrise-steplib/steps-xcode-test/xcpretty"
)
func main() {
os.Exit(run())
}
func run() int {
logger := log.NewLogger()
xcodeTestRunner := createStep(logger)
config, err := xcodeTestRunner.ProcessConfig()
if err != nil {
logger.Errorf(err.Error())
return 1
}
if err := xcodeTestRunner.InstallDeps(config.LogFormatter == xcodebuild.XcprettyTool); err != nil {
logger.Warnf("Failed to install deps: %s", err)
logger.Printf("Switching to xcodebuild for output tool")
config.LogFormatter = xcodebuild.XcodebuildTool
}
res, runErr := xcodeTestRunner.Run(config)
exportErr := xcodeTestRunner.Export(res, runErr != nil)
if runErr != nil {
logger.Errorf(runErr.Error())
return 1
}
if exportErr != nil {
logger.Errorf(exportErr.Error())
return 1
}
return 0
}
func createStep(logger log.Logger) step.XcodeTestRunner {
envRepository := env.NewRepository()
inputParser := stepconf.NewInputParser(envRepository)
xcprettyInstaller := xcpretty.NewInstaller()
commandFactory := command.NewFactory(envRepository)
pathChecker := pathutil.NewPathChecker()
pathProvider := pathutil.NewPathProvider()
fileManager := fileutil.NewFileManager()
xcconfigWriter := xcconfig.NewWriter(pathProvider, fileManager)
xcodebuilder := xcodebuild.NewXcodebuild(logger, commandFactory, pathChecker, fileManager, xcconfigWriter)
simulatorManager := simulator.NewManager(commandFactory)
swiftCache := cache.NewSwiftPackageCache()
testAddonExporter := testaddon.NewExporter()
stepenvRepository := stepenv.NewRepository(envRepository)
outputExporter := output.NewExporter(stepenvRepository, logger, testAddonExporter)
pathModifier := pathutil.NewPathModifier()
return step.NewXcodeTestRunner(inputParser, logger, xcprettyInstaller, xcodebuilder, simulatorManager, swiftCache, outputExporter, pathModifier, pathProvider)
}
<file_sep>package testaddon
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/bitrise-io/go-utils/command"
"github.com/bitrise-io/go-utils/env"
"github.com/bitrise-io/go-utils/log"
)
// Replaces characters '/' and ':', which are unsupported in filnenames on macOS
func replaceUnsupportedFilenameCharacters(s string) string {
s = strings.Replace(s, "/", "-", -1)
s = strings.Replace(s, ":", "-", -1)
return s
}
func copyDirectory(sourceBundle string, targetDir string) error {
if err := os.MkdirAll(targetDir, 0700); err != nil {
return fmt.Errorf("failed to create directory (%s), error: %s", targetDir, err)
}
// the leading `/` means to copy not the content but the whole dir
// -a means a better recursive, with symlinks handling and everything
cmd := command.NewFactory(env.NewRepository()).Create("cp", []string{"-a", sourceBundle, targetDir + "/"}, nil)
//cmd := command.New("cp", "-a", sourceBundle, targetDir+"/")
// TODO: migrate log
log.Donef("$ %s", cmd.PrintableCommandArgs())
if out, err := cmd.RunAndReturnTrimmedCombinedOutput(); err != nil {
return fmt.Errorf("copy failed, error: %s, output: %s", err, out)
}
return nil
}
func saveBundleMetadata(outputDir string, bundleName string) error {
// Save test bundle metadata
type testBundle struct {
BundleName string `json:"test-name"`
}
bytes, err := json.Marshal(testBundle{
BundleName: bundleName,
})
if err != nil {
return fmt.Errorf("could not encode metadata, error: %s", err)
}
if err = ioutil.WriteFile(filepath.Join(outputDir, "test-info.json"), bytes, 0600); err != nil {
return fmt.Errorf("failed to write file, error: %s", err)
}
return nil
}
<file_sep>package output
import (
mockenv "github.com/bitrise-io/go-utils/env/mocks"
"github.com/bitrise-io/go-utils/fileutil"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/pathutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"os"
"path/filepath"
"testing"
)
const (
xcodeTestResultKey = "BITRISE_XCODE_TEST_RESULT"
xcodebuildBuildLogPath = "BITRISE_XCODEBUILD_BUILD_LOG_PATH"
xcodebuildTestLogPath = "BITRISE_XCODEBUILD_TEST_LOG_PATH"
)
type testingMocks struct {
envRepository *mockenv.Repository
}
func Test_GivenSuccessfulTest_WhenExportingTestRunResults_ThenSetsEnvVariableToSuccess(t *testing.T) {
// Given
exporter, mocks := createSutAndMocks()
// When
exporter.ExportTestRunResult(false)
// Then
mocks.envRepository.AssertCalled(t, "Set", xcodeTestResultKey, "succeeded")
}
func Test_GivenFailedTest_WhenExportingTestRunResults_ThenSetsEnvVariableToFailure(t *testing.T) {
// Given
exporter, mocks := createSutAndMocks()
// When
exporter.ExportTestRunResult(true)
// Then
mocks.envRepository.AssertCalled(t, "Set", xcodeTestResultKey, "failed")
}
func Test_GivenBuildLog_WhenExporting_ThenCopiesItAndSetsEnvVariable(t *testing.T) {
// Given
tempDir := t.TempDir()
logPath := filepath.Join(tempDir, "xcodebuild_build.log")
defer func() {
_ = os.RemoveAll(tempDir)
}()
exporter, mocks := createSutAndMocks()
// When
err := exporter.ExportXcodebuildBuildLog(tempDir, "xcodebuild build log")
// Then
mocks.envRepository.AssertCalled(t, "Set", xcodebuildBuildLogPath, logPath)
assert.NoError(t, err)
assert.True(t, isPathExists(logPath))
}
func Test_GivenTestLog_WhenExporting_ThenCopiesItAndSetsEnvVariable(t *testing.T) {
// Given
tempDir := t.TempDir()
logPath := filepath.Join(tempDir, "xcodebuild_test.log")
exporter, mocks := createSutAndMocks()
// When
err := exporter.ExportXcodebuildTestLog(tempDir, "xcodebuild test log")
// Then
mocks.envRepository.AssertCalled(t, "Set", xcodebuildTestLogPath, logPath)
assert.NoError(t, err)
assert.True(t, isPathExists(logPath))
}
func Test_GivenSimulatorDiagnostics_WhenExporting_ThenCopiesItAndSetsEnvVariable(t *testing.T) {
// Given
name := "Simulator"
tempDir := t.TempDir()
diagnosticsDir := filepath.Join(tempDir, "diagnostics")
_ = pathutil.EnsureDirExist(diagnosticsDir)
diagnosticsFile := filepath.Join(diagnosticsDir, "simulatorDiagnostics.txt")
_ = fileutil.NewFileManager().Write(diagnosticsFile, "test-diagnostics", 0777)
exporter, _ := createSutAndMocks()
// When
err := exporter.ExportSimulatorDiagnostics(tempDir, diagnosticsDir, name)
// Then
assert.NoError(t, err)
assert.True(t, isPathExists(filepath.Join(tempDir, name+".zip")))
}
// Helpers
func createSutAndMocks() (Exporter, testingMocks) {
envRepository := new(mockenv.Repository)
envRepository.On("Set", mock.Anything, mock.Anything).Return(nil)
exporter := NewExporter(envRepository, log.NewLogger(), nil)
return exporter, testingMocks{
envRepository: envRepository,
}
}
func isPathExists(path string) bool {
isExist, _ := pathutil.NewPathChecker().IsPathExists(path)
return isExist
}
<file_sep>package step
import (
"fmt"
"github.com/bitrise-io/go-utils/colorstring"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/stringutil"
)
func printLastLinesOfXcodebuildTestLog(rawXcodebuildOutput string, isRunSuccess bool) {
const lastLines = "\nLast lines of the build log:"
if !isRunSuccess {
log.Errorf(lastLines)
} else {
log.Infof(lastLines)
}
fmt.Println(stringutil.LastNLines(rawXcodebuildOutput, 20))
if !isRunSuccess {
log.Warnf("If you can't find the reason of the error in the log, please check the xcodebuild_test.log.")
}
log.Infof(colorstring.Magenta(`
The log file is stored in $BITRISE_DEPLOY_DIR, and its full path
is available in the $BITRISE_XCODEBUILD_TEST_LOG_PATH environment variable.
If you have the Deploy to Bitrise.io step (after this step),
that will attach the file to your build as an artifact!`))
}
<file_sep>package cache
import (
xcodecache "github.com/bitrise-io/go-xcode/xcodecache"
)
// SwiftPackageCache ...
type SwiftPackageCache interface {
SwiftPackagesPath(projectPth string) (string, error)
CollectSwiftPackages(projectPath string) error
}
type cache struct {
}
// NewSwiftPackageCache ...
func NewSwiftPackageCache() SwiftPackageCache {
return &cache{}
}
func (c cache) SwiftPackagesPath(projectPth string) (string, error) {
return xcodecache.SwiftPackagesPath(projectPth)
}
func (c cache) CollectSwiftPackages(projectPath string) error {
return xcodecache.CollectSwiftPackages(projectPath)
}
|
eccfe5ce0f42793472dbe55c533459159aceb9e8
|
[
"Markdown",
"Go Module",
"Go"
] | 22
|
Go
|
godrei/steps-xcode-test
|
4ca110f00a6925f9a20726d72b74188efeec46f6
|
cc0fc7d2d53275d0b0f6b690c5d822f85a52a9fd
|
refs/heads/main
|
<repo_name>Unigmos/ImageDivisionSave<file_sep>/README.md
# ImageDivisionSave<br>
画像の分割保存を行うプログラムです。<br>
## 機能<br>
1枚の画像を切り分けて保存する
要はこんな感じ(例として横4,縦2で分割)↓<br>

分割数を変えたい場合はverticalとhorizontalの値を変更すること。<br>
## ざっくりとした仕組み<br>
分割したピクセル数の計算<br>
↓<br>
横1列分分割で保存<br>
↓↑<br>
次の行に移動する<br>
## 動かない場合<br>
・実行できない!<br>
→Python実行環境がない可能性があります。Pythonの実行環境を用意してください。<br>
・画像が参照できない!<br>
→picture_nameの値を変更してください。また、InputPictureフォルダの中に画像を挿入してください。<br>
## お問い合わせ<br>
何かございましたら「<EMAIL>」まで連絡ください。反応は非常に遅いです。<br>
### 変更履歴<br>
Ver1.0:初期バージョン<br>
Ver1.1:GUI化し使いやすくなりました。
<file_sep>/Ver1.0/ImageDivisionSave.py
from PIL import Image
#Inputする画像の名前を拡張子付きで入力
picture_name = "Test1.png"
path = Image.open('InputPicture/' + picture_name)
#分割指定
vertical = 2 #縦分割数
horizontal = 4 #横分割数
width = path.width / horizontal
height = path.height / vertical
#トリミング前の値の定義,処理
vertical_count = 1
picture_number = 1
start_y = 0 - height
end_y = 0
while(vertical >= vertical_count):
start_y += height
end_y += height
vertical_count += 1
#値の初期化
horizontal_count = 1
start_x = 0
end_x = width
while(horizontal >= horizontal_count):
crop_box = (start_x, start_y, end_x, end_y)
img = path.crop(crop_box)
img.save('OutputPicture/picture' + str(picture_number) + '.png')
start_x += width
end_x += width
horizontal_count += 1
picture_number += 1<file_sep>/Ver1.1/ImageDivisionSave.py
from PIL import Image,ImageTk,ImageOps
import tkinter
from tkinter import filedialog
#画像サイズ
image_width = 480
image_height = 270
#アプリケーション実行
app = tkinter.Tk()
app.title(u"画像分割保存")
app.geometry("550x350")
app.resizable(width = False, height = False)
#開くイベント
def file_open():
global image, path_address
name = tkinter.filedialog.askopenfilename(title = "ファイル選択", initialdir="C:/", filetypes=[("Image File","*.png;*.jpg")])
image = Image.open(name)
path_address = image
image = ImageOps.pad(image, (image_width, image_height))
image = ImageTk.PhotoImage(image = image)
image_canvas.create_image(image_width / 2, image_height / 2, image = image)
#閉じるイベント
def file_close():
image_canvas.delete("all")
#実行イベント
def execution_button_click():
#トリミング前の値の定義,処理
width = path_address.width / horizontal
height = path_address.height / vertical
vertical_count = 1
picture_number = 1
start_y = 0 - height
end_y = 0
while(vertical >= vertical_count):
start_y += height
end_y += height
vertical_count += 1
#値の初期化
horizontal_count = 1
start_x = 0
end_x = width
while(horizontal >= horizontal_count):
crop_box = (start_x, start_y, end_x, end_y)
img = path_address.crop(crop_box)
img.save('OutputPicture/picture' + str(picture_number) + '.png')
start_x += width
end_x += width
horizontal_count += 1
picture_number += 1
#分割数設定処理イベント
def division_set():
global division_set_window, vertical_entry, horizontal_entry
division_set_window = tkinter.Toplevel()
division_set_window.geometry("300x200")
division_set_window.title(u"分割数指定")
division_set_window.resizable(width = False, height = False)
division_set_window.attributes("-topmost", True)
#入力欄設定
vertical_label = tkinter.Label(division_set_window, text="縦分割数")
vertical_label.place(x=20, y=30)
vertical_entry = tkinter.Entry(division_set_window, width=30)
vertical_entry.insert(tkinter.END,u"")
vertical_entry.pack()
vertical_entry.place(x=80, y=30)
horizontal_label = tkinter.Label(division_set_window, text="横分割数")
horizontal_label.place(x=20, y=90)
horizontal_entry = tkinter.Entry(division_set_window, width=30)
horizontal_entry.insert(tkinter.END, u"")
horizontal_entry.pack()
horizontal_entry.place(x=80, y=90)
ok_button = tkinter.Button(division_set_window, text="OK", command = ok_button_click)
ok_button.place(x=130, y=150)
def ok_button_click():
global vertical, horizontal
str_vertical = vertical_entry.get()
vertical = int(str_vertical)
str_horizontal = horizontal_entry.get()
horizontal = int(str_horizontal)
division_set_window.destroy()
#メインウィンドウ処理実行ボタン
execution_button = tkinter.Button(app, text = "実行", command = execution_button_click)
execution_button.place(x = 470, y = 300)
#メニュー
menu = tkinter.Menu(app)
#ファイルの子メニュー
file = tkinter.Menu(menu, tearoff = 0)
file.add_command(label="開く", command = file_open)
file.add_command(label="閉じる", command = file_close)
file.add_separator()
file.add_command(label="終了", command = app.quit)
#設定の子メニュー
division = tkinter.Menu(menu, tearoff = 0)
division.add_command(label="分割数指定", command = division_set)
#親メニュー
menu.add_cascade(label="ファイル", menu=file)
menu.add_cascade(label="設定", menu=division)
app.config(menu=menu)
image_canvas = tkinter.Canvas(app, width = image_width, height = image_height)
image_canvas.pack()
app.mainloop()
|
c8c047fe3b208abde4d3999f1dccbe6269d5d9a6
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
Unigmos/ImageDivisionSave
|
8186c5ef3ee25c3059c13646d2b88ac488c631ee
|
929e9f429720d40ab49df08021d9718361439b57
|
refs/heads/master
|
<repo_name>ashoeb81/SFND_Lidar_Obstacle_Detection<file_sep>/src/processPointClouds.cpp
// PCL lib Functions for processing point clouds
#include <cmath>
#include "processPointClouds.h"
//constructor:
template<typename PointT>
ProcessPointClouds<PointT>::ProcessPointClouds() {}
//de-constructor:
template<typename PointT>
ProcessPointClouds<PointT>::~ProcessPointClouds() {}
template<typename PointT>
void ProcessPointClouds<PointT>::numPoints(typename pcl::PointCloud<PointT>::Ptr cloud)
{
std::cout << cloud->points.size() << std::endl;
}
template<typename PointT>
typename pcl::PointCloud<PointT>::Ptr ProcessPointClouds<PointT>::FilterCloud(
typename pcl::PointCloud<PointT>::Ptr cloud, float filterRes, Eigen::Vector4f minPoint,
Eigen::Vector4f maxPoint)
{
// Time segmentation process
auto startTime = std::chrono::steady_clock::now();
// Create the voxel-grid filtering object.
typename pcl::PointCloud<PointT>::Ptr cloud_voxfiltered (new pcl::PointCloud<PointT>());
pcl::VoxelGrid<PointT> sor;
sor.setInputCloud(cloud);
sor.setLeafSize (filterRes, filterRes, filterRes);
sor.filter(*cloud_voxfiltered);
// Create filter for limiting extent of point cloud.
pcl::CropBox<PointT> crop_box(true);
typename pcl::PointCloud<PointT>::Ptr cloud_boxfiltered (new pcl::PointCloud<PointT>());
crop_box.setInputCloud(cloud_voxfiltered);
crop_box.setMin(minPoint);
crop_box.setMax(maxPoint);
crop_box.filter(*cloud_boxfiltered);
// Create filter for removing lidar reflections from the car's roof.
pcl::CropBox<PointT> crop_roof(true);
std::vector<int> roof_indices;
crop_roof.setMin(Eigen::Vector4f(-1.5, -1.7, -1, 1));
crop_roof.setMax(Eigen::Vector4f(2.6, 1.7, -0.4, 1));
crop_roof.setInputCloud(cloud_boxfiltered);
crop_roof.filter(roof_indices);
pcl::PointIndices::Ptr inliers(new pcl::PointIndices);
for(auto index : roof_indices) {
inliers->indices.push_back(index);
}
pcl::ExtractIndices<PointT> extract;
typename pcl::PointCloud<PointT>::Ptr cloud_rooffiltered (new pcl::PointCloud<PointT>());
extract.setInputCloud(cloud_boxfiltered);
extract.setIndices(inliers);
extract.setNegative(true);
extract.filter(*cloud_rooffiltered);
auto endTime = std::chrono::steady_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
std::cout << "filtering took " << elapsedTime.count() << " milliseconds" << std::endl;
return cloud_rooffiltered;
}
template<typename PointT>
std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> ProcessPointClouds<PointT>::SeparateClouds(
pcl::PointIndices::Ptr inliers, typename pcl::PointCloud<PointT>::Ptr cloud)
{
typename pcl::PointCloud<PointT>::Ptr inliers_pcl(new pcl::PointCloud<PointT>());
typename pcl::PointCloud<PointT>::Ptr outliers_pcl(new pcl::PointCloud<PointT>());
for (int index : inliers->indices) {
inliers_pcl->points.push_back(cloud->points[index]);
}
pcl::ExtractIndices<PointT> extract;
extract.setInputCloud(cloud);
extract.setIndices(inliers);
extract.setNegative(true);
extract.filter(*outliers_pcl);
std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> segResult(
inliers_pcl, outliers_pcl);
return segResult;
}
template<typename PointT>
std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> ProcessPointClouds<PointT>::SegmentPlane(
typename pcl::PointCloud<PointT>::Ptr cloud, int maxIterations, float distanceThreshold)
{
// Time segmentation process
auto startTime = std::chrono::steady_clock::now();
// Apply RANSAC plane segmentation algorithm.
std::unordered_set<int> inlier_set = RansacPlane(cloud, maxIterations, distanceThreshold);
pcl::PointIndices::Ptr inliers(new pcl::PointIndices());
for (int index : inlier_set) {
inliers->indices.push_back(index);
}
auto endTime = std::chrono::steady_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
std::cout << "plane segmentation took " << elapsedTime.count() << " milliseconds" << std::endl;
// Extract two point clouds. One holding the ground plane and another with objects.
std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> segResult = SeparateClouds(
inliers,cloud);
return segResult;
}
template<typename PointT>
std::vector<typename pcl::PointCloud<PointT>::Ptr> ProcessPointClouds<PointT>::Clustering(
typename pcl::PointCloud<PointT>::Ptr cloud, float clusterTolerance, int minSize, int maxSize)
{
// Time clustering process
auto startTime = std::chrono::steady_clock::now();
// Push all the point cloud points into a KDTree.
KdTree* tree = new KdTree;
std::vector<std::vector<float>> points;
for (int i=0; i < cloud->points.size(); i++){
std::vector<float> p = {cloud->points[i].x, cloud->points[i].y, cloud->points[i].z};
tree->insert(p, i);
points.push_back(p);
}
// Apply euclidean clustering algorithm.
std::vector<std::vector<int>> clusters = euclideanCluster(points, tree, clusterTolerance);
// Assemble point clouds of individual clusters.
std::vector<typename pcl::PointCloud<PointT>::Ptr> cluster_clouds;
for (const auto& cluster : clusters) {
if (cluster.size() > minSize && cluster.size() < maxSize) {
typename pcl::PointCloud<PointT>::Ptr cluster_cloud(new pcl::PointCloud<PointT>);
for (int index : cluster) {
cluster_cloud->points.push_back(cloud->points[index]);
}
cluster_cloud->width = cluster_cloud->points.size();
cluster_cloud->height = 1;
cluster_cloud->is_dense = true;
cluster_clouds.push_back(cluster_cloud);
}
}
auto endTime = std::chrono::steady_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
std::cout << "clustering took "
<< elapsedTime.count() << " milliseconds and found " << clusters.size() << " clusters" << std::endl;
return cluster_clouds;
}
template<typename PointT>
Box ProcessPointClouds<PointT>::BoundingBox(typename pcl::PointCloud<PointT>::Ptr cluster)
{
// Find bounding box for one of the clusters
PointT minPoint, maxPoint;
pcl::getMinMax3D(*cluster, minPoint, maxPoint);
Box box;
box.x_min = minPoint.x;
box.y_min = minPoint.y;
box.z_min = minPoint.z;
box.x_max = maxPoint.x;
box.y_max = maxPoint.y;
box.z_max = maxPoint.z;
return box;
}
template<typename PointT>
void ProcessPointClouds<PointT>::savePcd(typename pcl::PointCloud<PointT>::Ptr cloud, std::string file)
{
pcl::io::savePCDFileASCII (file, *cloud);
std::cerr << "Saved " << cloud->points.size () << " data points to "+file << std::endl;
}
template<typename PointT>
typename pcl::PointCloud<PointT>::Ptr ProcessPointClouds<PointT>::loadPcd(std::string file)
{
typename pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT>);
if (pcl::io::loadPCDFile<PointT> (file, *cloud) == -1) //* load the file
{
PCL_ERROR ("Couldn't read file \n");
}
std::cerr << "Loaded " << cloud->points.size () << " data points from "+file << std::endl;
return cloud;
}
template<typename PointT>
std::vector<boost::filesystem::path> ProcessPointClouds<PointT>::streamPcd(std::string dataPath)
{
std::vector<boost::filesystem::path> paths(boost::filesystem::directory_iterator{dataPath}, boost::filesystem::directory_iterator{});
// sort files in accending order so playback is chronological
sort(paths.begin(), paths.end());
return paths;
}
// RANSAC Plane segmentation algorithm.
template<typename PointT>
std::unordered_set<int> ProcessPointClouds<PointT>::RansacPlane(
typename pcl::PointCloud<PointT>::Ptr cloud, int maxIterations, float distanceTol)
{
std::unordered_set<int> inliersResult;
srand(time(NULL));
// For max iterations
int iterations = 0;
while (iterations < maxIterations) {
// Randomly sample subset and fit line
std::unordered_set<int> inliers;
while (inliers.size() < 3) {
inliers.insert(std::rand() % (cloud->points.size()));
}
float x1, y1, z1, x2, y2, z2, x3, y3, z3;
auto iter = inliers.begin();
x1 = cloud->points[*iter].x;
y1 = cloud->points[*iter].y;
z1 = cloud->points[*iter].z;
iter++;
x2 = cloud->points[*iter].x;
y2 = cloud->points[*iter].y;
z2 = cloud->points[*iter].z;
iter++;
x3 = cloud->points[*iter].x;
y3 = cloud->points[*iter].y;
z3 = cloud->points[*iter].z;
// Determine Plane parameters.
float a = (y2 - y1)*(z3 - z1) - (z2 - z1)*(y3 - y1);
float b = (z2 - z1)*(x3 - x1) - (x2 - x1)*(z3 - z1);
float c = (x2 - x1)*(y3 - y1) - (y2 - y1)*(x3 - x1);
float d = -1 * (a*x1 + b*y1 + c*z1);
// Measure distance between every point and fitted line
// If distance is smaller than threshold count it as inlier
int point_index = 0;
for (const auto& point : cloud->points) {
float dist = std::fabs(a*point.x + b*point.y + c*point.z + d) / sqrtf(a*a + b*b + c*c);
if (dist < distanceTol) {
inliers.insert(point_index);
}
point_index += 1;
}
if (inliers.size() > inliersResult.size()) {
inliersResult = inliers;
}
iterations++;
}
return inliersResult;
}
template<typename PointT>
void ProcessPointClouds<PointT>::Proximity(int point_idx, const std::vector<std::vector<float>>& points,
std::vector<int>& cluster, KdTree* tree, std::unordered_set<int>& processed, float distanceTol) {
// Mark point as processed.
processed.insert(point_idx);
// Add point to cluster.
cluster.push_back(point_idx);
// Find all the neighbors
for (int neighbor_id : tree->search(points[point_idx], distanceTol)) {
if (processed.count(neighbor_id) == 0) {
Proximity(neighbor_id, points, cluster, tree, processed, distanceTol);
}
}
}
// Euclidean clustering algorithm.
template<typename PointT>
std::vector<std::vector<int>> ProcessPointClouds<PointT>::euclideanCluster(
const std::vector<std::vector<float>>& points, KdTree* tree, float distanceTol)
{
std::vector<std::vector<int>> clusters;
std::unordered_set<int> processed;
// Loop over points.
for (int i=0; i < points.size(); i++) {
// If point has not been processed.
if(processed.count(i) == 0) {
// Create a new cluster.
std::vector<int> cluster;
// Fill cluster with point and all those in proximity.
Proximity(i, points, cluster, tree, processed, distanceTol);
// Done with cluster.
clusters.push_back(cluster);
}
}
return clusters;
}<file_sep>/src/quiz/cluster/kdtree.h
/* \author <NAME> */
// Quiz on implementing kd tree
#include "../../render/render.h"
// Structure to represent node of kd tree
struct Node
{
std::vector<float> point;
int id;
Node* left;
Node* right;
Node(std::vector<float> arr, int setId)
: point(arr), id(setId), left(NULL), right(NULL)
{}
};
struct KdTree
{
Node* root;
KdTree()
: root(NULL)
{}
void insert(std::vector<float> point, int id)
{
// TODO: Fill in this function to insert a new point into the tree
// the function should create a new node and place correctly with in the root
Node* new_node = new Node(point, id);
insert_helper(root, new_node, 0);
}
void insert_helper(Node*& curr_node, Node*& new_node, int depth) {
int coordinate = depth % new_node->point.size();
if (curr_node == NULL) {
// Set new node as current leaf.
curr_node = new_node;
} else if (new_node->point[coordinate] < curr_node->point[coordinate]) {
// Insert new node in left sub-tree.
return insert_helper(curr_node->left, new_node, depth+1);
} else {
// Insert new node in right sub-tree.
return insert_helper(curr_node->right, new_node, depth+1);
}
}
// return a list of point ids in the tree that are within distance of target
std::vector<int> search(std::vector<float> target, float distanceTol)
{
std::vector<int> ids;
search_helper(root, target, ids, distanceTol, 0);
return ids;
}
bool in_box(const std::vector<float>& node_point, const std::vector<float>& target_point, float distanceTol) {
if (node_point[0] >= target_point[0] - distanceTol && node_point[0] <= target_point[0] + distanceTol) {
if (node_point[1] >= target_point[1] - distanceTol && node_point[1] <= target_point[1] + distanceTol) {
return true;
}
}
return false;
}
bool is_close(const std::vector<float>& node_point, const std::vector<float>& target_point, float distanceTol) {
float a = (node_point[0] - target_point[0]) * (node_point[0] - target_point[0]);
float b = (node_point[1] - target_point[1]) * (node_point[1] - target_point[1]);
return sqrtf(a + b) <= distanceTol;
}
void search_helper(Node*& curr_node, const std::vector<float>& target_point, std::vector<int>& ids, float distanceTol, int depth) {
// If at a leaf then return.
if (curr_node == NULL) {
return;
}
// Check if current node should be included in list.
if (in_box(curr_node->point, target_point, distanceTol))
{
if (is_close(curr_node->point, target_point, distanceTol))
{
ids.push_back(curr_node->id);
}
}
// Check which coordinate to use to determine split.
int coordinate = depth % curr_node->point.size();
if (target_point[coordinate] - distanceTol < curr_node->point[coordinate]) {
search_helper(curr_node->left, target_point, ids, distanceTol, depth+1);
}
if (target_point[coordinate] + distanceTol > curr_node->point[coordinate]) {
search_helper(curr_node->right, target_point, ids, distanceTol, depth+1);
}
}
};
|
a7d73760717ada02864011e683828cfddcdca081
|
[
"C++"
] | 2
|
C++
|
ashoeb81/SFND_Lidar_Obstacle_Detection
|
b5606651ecd70d2d8342f4bef155f7e2bea5e847
|
5f60c61206d8e3f9aa09dd853dc04a0d76fc5c81
|
refs/heads/master
|
<file_sep>function zle-keymap-select {
VIMODE="${${KEYMAP/vicmd/☭}/(main|viins)/Ⓐ }"
zle reset-prompt
}
zle -N zle-keymap-select
VIMODE="Ⓐ "
PROMPT='$fg_bold[red]%}${VIMODE}% %{$fg_bold[green]%}%p %{$fg[white]%}%c %{$fg_bold[blue]%}$(git_prompt_info)%{$fg_bold[blue]%} % %{$reset_color%}'
ZSH_THEME_GIT_PROMPT_PREFIX="git:(%{$fg[red]%}"
ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%}"
ZSH_THEME_GIT_PROMPT_DIRTY="%{$fg[blue]%}) %{$fg[yellow]%}✗%{$reset_color%}"
ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg[blue]%})"
<file_sep>require 'rubygems'
require 'hirb'
extend Hirb::Console
Hirb::View.enable
alias q exit
IRB.conf[:PROMPT_MODE] = :SIMPLE
IRB.conf[:AUTO_INDENT] = true
IRB.conf[:IRB_RC] = proc do |conf|
name = "irb: "
name = "rails: " if $0 == 'irb' && ENV['RAILS_ENV']
leader = " " * name.length
conf.prompt_i = "#{name}"
conf.prompt_s = leader + '\-" '
conf.prompt_c = leader + '\-+ '
conf.return_format = ('=' * (name.length - 2)) + "> %s\n"
end
class Object
def my_methods(include_inherited = false)
ignored_methods = include_inherited ? Object.methods : self.class.superclass.instance_methods
(self.methods - ignored_methods).sort
end
end
######### RAILS ONLY
if $0 == 'irb' && ENV['RAILS_ENV']
require 'logger'
Object.const_set(:RAILS_DEFAULT_LOGGER, Logger.new(STDOUT))
end
<file_sep># Path to your oh-my-zsh configuration.
export ZSH=$HOME/oh-my-zsh
# Set to the name theme to load.
# Look in ~/.oh-my-zsh/themes/
# export ZSH_THEME="arrow"
export ZSH_THEME="garyblessington"
# Set to this to use case-sensitive completion
# export CASE_SENSITIVE="true"
# Comment this out to disable weekly auto-update checks
# export DISABLE_AUTO_UPDATE="true"
# Uncomment following line if you want to disable colors in ls
# export DISABLE_LS_COLORS="true"
# Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*)
# Example format: plugins=(rails git textmate ruby lighthouse)
plugins=(git)
plugins=(rails)
source $ZSH/oh-my-zsh.sh
# Customize to your needs...
autoload -U compinit && compinit
autoload colors && colors
bindkey "^[" vi-cmd-mode
source ~/.zsh/exports.zsh
source ~/.zsh/history.zsh
source ~/.zsh/set_options.zsh
source ~/.zsh/completion.zsh
source ~/.zsh/aliases.zsh
unsetopt auto_name_dirs
export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init - zsh)"
<file_sep>require 'rubygems'
require 'rake'
desc "create symlinks to config files"
task :symlink do
dir = File.dirname(__FILE__)
force = true
force = force ? '-Ff' : ''
(Dir.glob('.*') - ['.git', '.', '..']).each do |file|
`ln -s #{force} #{File.join(dir, file)} #{ENV['HOME']}/#{file}`
end
#symlink
end
<file_sep>fpath=($fpath $HOME/.zsh/zsh-git)
typeset -U fpath
<file_sep>alias c="clear"
alias b="cd -"
alias ~="cd ~"
alias l="ls -alF"
# set vi mode
set -o vi
<file_sep># My aliases
alias restart='touch tmp/restart.txt'
alias devlog='tail -200 -f log/development.log'
alias testlog='tail -200 -f log/test.log'
alias c="clear"
alias b="cd -"
alias h="cd ~"
alias x="logout"
alias work="cd ~/work/"
alias gs="git status"
alias gc="git commit"
alias gcm="git add -A . && git commit -am"
alias gr="git pull --rebase"
alias gp="git push"
alias r="rails"
alias g="git"
alias m="mvim"
alias be="bundle exec"
alias pryr="pry -r ./config/environment"
function gitdays {
git log --author=laribee --reverse --since="$@ days ago" --pretty="format:%n%Cgreen%cd%n%n%s%n%b%n---------------------------------------------"
}
|
ba33c22d6c6a49f1056759dd9f7a8e95e7b9fd64
|
[
"Ruby",
"Shell"
] | 7
|
Shell
|
laribee/dotfiles
|
ac596f2c900332bef265d32eb29eae4219f1eac5
|
3e13dfb99f670ef1b11c78f8f0bac5ee866c4aa7
|
refs/heads/master
|
<file_sep>class MazeRunner
attr_accessor :mazeWalls, :mazeCells, :cell
def initialize(base, height, mazeWalls)
@base, @height, @mazeWalls = base, height, mazeWalls
@mazeCells = Array.new @base*@height, false
runMaze
end
def runMaze
@cell = MazeCell.new 0, @base, @height
cellStack = Array.new
while @cell.loc < @base*@height-1
if unvisitedNeighbors.length > 0
nextCell = unvisitedNeighbors.sample
cellStack.push @cell.loc
@mazeCells[@cell.loc] = true
@cell = nextCell
else
@cell.loc = cellStack.pop
end
displaySolvedMaze [@cell.loc]
end
cellStack.push @base*@height-1
displaySolvedMaze cellStack
end
def visited (cell = @cell )
@mazeCells[cell.loc]
end
def intactWall ( cell = @cell, dir )
@mazeWalls[cell.wallLoc dir]
end
def availableNeighbors ( cell = @cell )
n = {}
cell.neighbors.each do |dir, neighbor|
if !intactWall dir
n[dir] = neighbor
end
end
n
end
def unvisitedNeighbors ( cell = @cell )
n = Array.new
cell.neighbors.each do |dir, neighbor|
if !intactWall dir and !visited neighbor
n.push neighbor
end
end
n
end
def displaySolvedMaze pathStack
disp = ASCIIMazeDisplay.new @base, @height, @mazeWalls, pathStack
disp.display
end
end<file_sep>require './maze'
require './mazerunner'
class ASCIIMaze < Maze
def initialize(base, height, start = 0, finish = -1)
super base, height, start, finish
#@base, @height, @mazeWalls, @pathStack = base, height, mazeWalls, pathStack
@gridBase = 2*@base+1
@gridHeight = 2*@height+1
getSolution
end
def x
@loc % @gridBase
end
def y
@loc / @gridBase
end
def grid withSoln = false
gridStr = "";
wallLoc = 0
cellLoc = 0
@gridHeight.times do |j|
@gridBase.times do |i|
if (j == 0 || j == @gridHeight-1)
if (i % 2 == 0)
gridStr += '+'
else
gridStr += '-'
end
elsif (j % 2 == 0)
if (i % 2 == 0)
gridStr += '+'
else
gridStr += @mazeWalls[wallLoc] ? '-' : ' '
wallLoc += 1
end
else
if (i == 0 || i == @gridBase-1)
gridStr += '|'
elsif (i % 2 == 0)
gridStr += @mazeWalls[wallLoc] ? '|' : ' '
wallLoc += 1
else
gridStr += (withSoln and @solutionStack.member? cellLoc) ? '*' : ' '
cellLoc += 1
end
end
end
gridStr += "\n"
end
gridStr
end
def display withSoln = false
print grid withSoln
end
class << self
def run
puts "Welcome to Emma's ASCII Maze!"
print "Type command: "
args = gets.chomp.split " "
command = args.shift
while command != "quit"
case command
when "help"
print help
when "new"
case args.length
when 2
base = args[0].to_i
height = args[1].to_i
maze = self.new base, height
maze.display
when 4
base = args[0].to_i
height = args[1].to_i
start = args[2].to_i
finish = args[4].to_i
maze = self.new base, height
maze.display
else
puts "Improper number of arguments (must be 2 or 4)"
end
when "solve"
if maze.nil?
puts "You must create a maze first"
else
if args.length == 2
maze.start = args[0].to_i
maze.finish = args[1].to_i
maze.getSolution
end
maze.display true
end
when "display"
if maze.nil?
puts "You must create a maze first"
else
maze.display
end
else
puts "I don't understand"
end
print "Type command: "
args = gets.chomp.split " "
command = args.shift
end
puts "Goodbye!"
end
private
def help
<<-eos
display
displays maze, sans solution
new <base> <height> [<start> <finish>]
creates new maze
base: width of maze
height: height of maze
start (optional): start location of maze
finish (optional): finish location of maze
quit
ends program
solve [<start> <finish>]
displays maze plus solution
start (optional): start location of maze
finish (optional): finish location of maze
eos
end
end
end
ASCIIMaze.run<file_sep>class Maze
attr_accessor :start, :finish
def initialize(base, height, start = 0, finish = -1)
@base, @height, @start = base, height, start
@finish = (finish == -1) ? @base*@height - 1 : finish
@mazeWalls = Array.new(@base*(@height-1)+(@base-1)*@height, true)
@mazeCells = Array.new @base*@height, false
@solutionStack = Array.new
createMaze
#getSolution
#displayMaze
#runMaze
end
def createMaze
visitedCells = 1
totalCells = @base*@height
cellStack = Array.new
@cell = MazeCell.new rand(totalCells), @base, @height
while visitedCells < totalCells
if intactNeighbors.length > 0
nextDir = intactNeighbors.sample
knockDownWall nextDir
cellStack.push @cell.loc
nextCell = @cell.neighbor nextDir
@cell = nextCell
visitedCells += 1
else
@cell.loc = cellStack.pop
end
end
end
def allWallsIntact( cell = @cell )
check = true
cell.dirs.each do |dir|
if !@mazeWalls[cell.wallLoc dir]
check = false
end
end
check
end
def intactNeighbors( cell = @cell )
intNeighbors = Array.new
cell.neighbors.each do |dir, neighbor|
if allWallsIntact neighbor
intNeighbors << dir
end
end
intNeighbors
end
def knockDownWall ( cell = @cell, dir )
@mazeWalls[cell.wallLoc dir] = false
end
def getSolution start = @start, finish = @finish
@mazeCells = Array.new @base*@height, false
@cell = MazeCell.new start, @base, @height
@solutionStack = Array.new
while @cell.loc != finish
if unvisitedNeighbors.length > 0
nextCell = unvisitedNeighbors.sample
@solutionStack.push @cell.loc
@mazeCells[@cell.loc] = true
@cell = nextCell
else
@mazeCells[@cell.loc] = true
if @solutionStack.empty?
puts "Error!!!"
return Array.new
end
@cell.loc = @solutionStack.pop
end
end
@solutionStack.push finish
end
def visited (cell = @cell )
@mazeCells[cell.loc]
end
def intactWall ( cell = @cell, dir )
@mazeWalls[cell.wallLoc dir]
end
def availableNeighbors ( cell = @cell )
n = {}
cell.neighbors.each do |dir, neighbor|
if !intactWall dir
n[dir] = neighbor
end
end
n
end
def unvisitedNeighbors cell = @cell
n = Array.new
cell.neighbors.each do |dir, neighbor|
if !intactWall dir and !visited neighbor
n.push neighbor
end
end
n
end
end
class MazeCell
attr_accessor :loc
def initialize(loc, base, height)
@loc, @base, @height = loc, base, height
@visited = false
end
def x
@loc % @base
end
def y
@loc / @base
end
def dirs
if (x == 0)
if (y == 0)
[:south, :east]
elsif (y == @height-1)
[:north, :east]
else
[:north, :south, :east]
end
elsif (x == @base-1)
if (y == 0)
[:south, :west]
elsif (y == @height-1)
[:north, :west]
else
[:north, :south, :west]
end
else
if (y == 0)
[:south, :east, :west]
elsif (y == @height-1)
[:north, :east, :west]
else
[:north, :south, :east, :west]
end
end
end
def neighbor( dir )
neighborLoc = case dir
when :north
y>0 ? @loc-@base : -1
when :south
y<(@height-1) ? @loc+@base : -1
when :west
x>0 ? @loc-1 : -1
when :east
x<(@base-1) ? @loc+1 : -1
else
-1
end
raise TypeError, "Invalid direction #{dir} at location #{@loc}" if neighborLoc == -1
MazeCell.new neighborLoc, @base, @height
end
def neighbors
n = {}
dirs.each do |dir|
n[dir] = neighbor dir
end
n
end
def wallLoc ( dir )
wall = case dir
when :north
y>0 ? y*(@base-1)+(y-1)*@base+x : -1
when :south
y<(@height-1) ? (y+1)*(@base-1)+y*@base+x : -1
when :west
x>0 ? y*(2*@base-1)+x-1 : -1
when :east
x<(@base-1) ? y*(2*@base-1)+x : -1
else
-1
end
raise TypeError, "Invalid direction #{dir} at location #{@loc}" if wall == -1
wall
end
end<file_sep>class MazeController
end
|
4b05808e8bbd10f747fab0f7a5e9d3e0176406a1
|
[
"Ruby"
] | 4
|
Ruby
|
emmafurth/maze
|
9b1e7b08d73038d1c1b3e2271f8b24e7bd599c16
|
1850069594747acfe94826eff6b0d0d4acf0e0b6
|
refs/heads/master
|
<repo_name>Ooodim/Arvore-Binaria<file_sep>/README.md
# Arvore-Binaria
Código cujo o objetivo é contar as palavras existentes em um arquivo de texto simples utilizando Árvore Binária de Busca.
<file_sep>/BinarySearchTree/src/treepkg/Principal.java
package treepkg;
import java.io.*;
public class Principal {
public static void main(String[] args) throws IOException {
BinaryTree tree = new BinaryTree();
BufferedReader arquivoStr = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\Users\\Rodri\\workspace\\BinarySearchTree\\src\\treepkg\\ArquivoDeTeste.txt")));
String arquivo = arquivoStr.readLine();
arquivoStr.close();
String[] palavras = arquivo.split(";");
int cont = palavras.length;
//Código para verificar palavras inclusas
//for (int i = 0; i < cont; i++) {
// System.out.println(palavras[i]);
//}
for (int i = 0; i < cont; i++) {
tree.inserir(palavras[i]);
}
tree.imprimirArvore();
}
}<file_sep>/BinarySearchTree/src/treepkg/BinaryTree.java
package treepkg;
public class BinaryTree {
// Declarando raiz
private Node root;
// Verifica se a árvore está vazia
public boolean isEmpty() {
if (root == null) {
return true;
}
return false;
}
// Retorna a altura da árvore
public int getAltura() {
return getAltura(this.root);
}
private int getAltura(Node no) {
if (no == null) {
return 0;
}
int altEsq = getAltura(no.getNoEsquerda());
int altDir = getAltura(no.getNoDireita());
if (altEsq > altDir) {
return altEsq + 1;
} else {
return altDir + 1;
}
}
// Retorna a quantidade de nós da árvore
public int getQtdNode() {
return getQtdNode(root);
}
private int getQtdNode(Node no) {
if (no == null) {
return 0;
}
int qtdNodeEsq = getQtdNode(no.getNoEsquerda());
int qtdNodeDireita = getQtdNode(no.getNoDireita());
return qtdNodeEsq + qtdNodeDireita + 1;
}
// Imprime a árvore
public void imprimirArvore() {
if (this.root == null)
System.out.println("Árvore vazia");
else
imprimirArvore(this.root);
}
private void imprimirArvore(Node node) {
if (node.getNoEsquerda() != null) {
imprimirArvore(node.getNoEsquerda());
}
if (node.getNoDireita() != null) {
imprimirArvore(node.getNoDireita());
}
System.out.println("- Palavra: " + node.getPalavra() + ";");
System.out.println(" Incidência: " + node.getIncidencia() + " vez(es);");
}
// Insere um novo nó
public void inserir(String palavra) {
System.out.println("Chego aqui");
inserir(this.root, palavra);
System.out.println("Chego aqui 2");
}
public void inserir(Node node, String palavra) {
System.out.println("Chego aqui 3");
if (palavra.equals(node.getPalavra())) {
System.out.println("Chego aqui 4");
this.root.sumIncidencia();
} else {
if (this.root == null) {
System.out.println("Chego aqui 5");
this.root = new Node(palavra);
} else if ((node.getPalavra()).compareTo(palavra) == 1) {
System.out.println("Chego aqui 6");
if (node.getNoEsquerda() != null) {
System.out.println("Chego aqui 7");
inserir(node.getNoEsquerda(), palavra);
} else {
System.out.println("Chego aqui 8");
// Se nodo esquerdo estiver vazio, insere o novo nó aqui
node.setNoEsquerda(new Node(palavra));
}
// Verifica se a palavra a ser inserida é maior que o nó
// corrente da árvore, se sim vai para a subárvore direita
} else if (palavra.compareTo(node.getPalavra()) == 1) {
System.out.println("Chego aqui 9");
// Se tiver elemento no nó direito a busca continua
if (node.getNoDireita() != null) {
System.out.println("Chego aqui 10");
inserir(node.getNoDireita(), palavra);
} else {
System.out.println("Chego aqui 11");
// Se o nó direito estiver vazio, insere o novo nó aqui
node.setNoDireita(new Node(palavra));
}
}
}
}
// Removendo um nó da árvore
public Node remover(String palavra) throws Exception {
return remover(this.root, palavra);
}
private Node remover(Node node, String palavra) throws Exception {
if (this.root == null) {
throw new Exception("Árvore vazia!");
} else {
if ((node.getPalavra()).compareTo(palavra) == 1) {
node.setNoEsquerda(remover(node.getNoEsquerda(), palavra));
} else if (palavra.compareTo(node.getPalavra()) == 1) {
node.setNoDireita(remover(node.getNoDireita(), palavra));
} else if (node.getNoEsquerda() != null && node.getNoDireita() != null) {
System.out.println(" Removeu Nó " + node.getPalavra());
node.setPalavra(encontraMinimo(node.getNoDireita()).getPalavra());
node.setNoDireita(removeMinimo(node.getNoDireita()));
} else {
System.out.println(" Removeu Nó " + node.getPalavra());
node = (node.getNoEsquerda() != null) ? node.getNoEsquerda() : node.getNoDireita();
}
return node;
}
}
// Remove o menor nó
private Node removeMinimo(Node node) {
if (node == null) {
System.out.println(" ERRO");
} else if (node.getNoEsquerda() != null) {
node.setNoEsquerda(removeMinimo(node.getNoEsquerda()));
return node;
} else {
return node.getNoDireita();
}
return null;
}
// Busca o menor nó
private Node encontraMinimo(Node node) {
if (node != null) {
while (node.getNoEsquerda() != null) {
node = node.getNoEsquerda();
}
}
return node;
}
}
|
5600f448151c2fcfdbc18199a10c4647229e61ff
|
[
"Markdown",
"Java"
] | 3
|
Markdown
|
Ooodim/Arvore-Binaria
|
22aeab51d1787c2305e728e7ebba8cefcd04da40
|
2db04b0c63f1754af99d99c97d4a0e42c688cba3
|
refs/heads/master
|
<repo_name>wsaeed77/Nextgentec<file_sep>/app/Modules/Crm/Http/CustomerServiceRate.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class CustomerServiceRate extends Model
{
public function service_item()
{
return $this->belongsTo('App\Modules\Crm\Http\CustomerServiceItem');
}
}
<file_sep>/app/Http/Requests/SignUpPostRequest.php
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class SignUpPostRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
//dd($this->request->isMethod('put'));
if (Request::isMethod('put')) {
/*if(!empty(Request::input('password')))
{
'password' => '<PASSWORD>',
}*/
return [
'f_name' => 'required|max:15',
'l_name' => 'required|max:15',
'email' => 'required|email|max:255',
// 'password' => '<PASSWORD>',
];
}
if (Request::isMethod('post')) {
return [
'f_name' => 'required|max:15',
'l_name' => 'required|max:15',
'email' => 'required|email|max:255',
'password' => '<PASSWORD>',
//
];
}
}
}
<file_sep>/app/Modules/Assets/Http/Asset.php
<?php
namespace App\Modules\Assets\Http;
use Illuminate\Database\Eloquent\Model;
class Asset extends Model
{
function customer()
{
return $this->belongsTo('App\Modules\Crm\Http\Customer');
}
function location()
{
return $this->belongsTo('App\Modules\Crm\Http\CustomerLocation', 'location_id');
}
function virtual_type()
{
return $this->belongsTo('App\Modules\Assets\Http\AssetVirtualType', 'asset_virtual_type_id');
}
public function password()
{
return $this->hasOne('App\Modules\Assets\Http\KnowledgePassword', 'asset_id');
}
}
<file_sep>/app/Modules/Assets/Http/Network.php
<?php
namespace App\Modules\Assets\Http;
use Illuminate\Database\Eloquent\Model;
class Network extends Model
{
public function location()
{
return $this->belongsTo('App\Modules\Crm\Http\CustomerLocation', 'customer_location_id');
}
}
<file_sep>/app/Modules/Assets/Http/AssetVirtualType.php
<?php
namespace App\Modules\Assets\Http;
use Illuminate\Database\Eloquent\Model;
class AssetVirtualType extends Model
{
public function assets()
{
return $this->hasMany('App\Modules\Assets\Http\Asset');
}
}
<file_sep>/app/Modules/Crm/Http/Zoho.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class Zoho extends Model
{
//
protected $table = 'zoho';
}
<file_sep>/app/Modules/Assets/Http/Controllers/NetworkController.php
<?php
namespace App\Modules\Assets\Http\Controllers;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Modules\Crm\Http\Customer;
use App\Modules\Crm\Http\CustomerLocation;
use App\Modules\Assets\Http\Asset;
use App\Modules\Assets\Http\Network;
use App\Modules\Assets\Http\AssetRole;
use Datatables;
use App\Model\Role;
use App\Model\User;
use Auth;
use Mail;
use URL;
use Session;
class NetworkController extends Controller
{
public function index()
{
// Get the Customers
$customers_obj = Customer::with(['locations'])->get();
$customers = [];
if ($customers_obj->count()) {
foreach ($customers_obj as $customer) {
$customers[$customer->id]=$customer->name.'('.$customer->email_domain.')';
//dd($customer);
}
}
//dd($customer);
return view('assets::network.network_list', [ 'customers' => compact('customers'), 'locations' => '' ]);
//return "Controller Index";
}
/*
networs_list_bycustomer
*/
function networkIndex($id = null)
{
$global_date = $this->global_date;
if (!empty(Session::get('cust_id'))) {
$networks = Network::with(['location'])
->join('customer_locations', 'networks.customer_location_id', '=', 'customer_locations.id')
->select('networks.*', 'customer_locations.customer_id')
->where('customer_id', Session::get('cust_id'));
} else {
$networks = Network::with(['location']);
}
//dd($networks->get());
return Datatables::of($networks)
->addColumn('action', function ($network) {
$return = '<div class="btn-group"><button type="button" class="btn btn-xs edit "
data-toggle="modal" data-id="'.$network->id.'" id="modaal" data-target="#modal-edit-network">
<i class="fa fa-edit"></i>
</button>
<button type="button" class="btn btn-danger btn-xs" data-toggle="modal" data-id="'.$network->id.'" id="modaal" data-target="#modal_network_delete"><i class="fa fa-times-circle"></i></button></div>';
return $return;
})
->addColumn('customer', function ($network) {
if ($network->location) {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span>'.$network->location->customer->name.'</span>
</button>';
} else {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span></span>
</button>';
}
})
->editColumn('created_at', function ($network) use ($global_date) {
return date($global_date, strtotime($network->created_at));
})
->setRowId('id')
->make(true);
}
function store(Request $request)
{
//dd($request->all());
$this->validate(
$request,
[
'customer' => 'required',
'name' => 'required',
]
);
$network = new Network();
//$network->customer_id = $request->customer;
$network->customer_location_id = $request->location_index;
$network->name = $request->name;
$network->lansubnet = $request->lansubnet;
$network->langw = $request->langw;
$network->lansubnetmask = $request->lansubnetmask;
$network->wanip = $request->wanip;
$network->wangw = $request->wangw;
$network->wansubnetmask = $request->wansubnetmask;
$network->dns1 = $request->dns1;
$network->dns2 = $request->dns2;
$network->notes = $request->notes;
$network->save();
$arr['success'] = 'Network added successfully';
return json_encode($arr);
exit;
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$network = Network::with(['location','location.customer'])
->leftJoin('customer_locations', 'networks.customer_location_id', '=', 'customer_locations.id')
->select('networks.*', 'customer_locations.customer_id')
->where('networks.id', $id)
->first();
//$network = Network::with(['location','location.customer']);
//dd($network);
$arr['html_content'] = view('assets::network.show_partial', compact('network'))->render();
$arr['network_name'] = $network->name;
return json_encode($arr);
exit;
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//dd($id);
$network = Network::with(['location','location.customer'])
->leftJoin('customer_locations', 'networks.customer_location_id', '=', 'customer_locations.id')
->select('networks.*', 'customer_locations.customer_id')
->where('networks.id', $id)->first();
//dd($network);
// $arr['locations'] = $locations;
$arr['network'] = $network;
//$arr['asset_name'] = $asset->name;
return json_encode($arr);
exit;
//
}
function update(Request $request)
{
//dd($request->all());
$this->validate(
$request,
[
'customer' => 'required',
'name' => 'required',
]
);
$network = Network::find($request->id);
//$network->customer_id = $request->customer;
$network->name = $request->name;
$network->customer_location_id = $request->location_index;
$network->lansubnet = $request->lansubnet;
$network->langw = $request->langw;
$network->lansubnetmask = $request->lansubnetmask;
$network->wanip = $request->wanip;
$network->wangw = $request->wangw;
$network->wansubnetmask = $request->wansubnetmask;
$network->dns1 = $request->dns1;
$network->dns2 = $request->dns2;
$network->notes = $request->notes;
$network->save();
$arr['success'] = 'Network updated successfully';
return json_encode($arr);
exit;
}
public function deleteNetwork(Request $request)
{
$network = Network::find($request->id);
$network->delete();
$arr['success'] = 'Network deleted sussessfully';
return json_encode($arr);
exit;
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep>/app/Modules/Crm/Http/CustomerLocation.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class CustomerLocation extends Model
{
public function customer()
{
return $this->belongsTo('App\Modules\Crm\Http\Customer');
}
public function contacts()
{
return $this->hasMany('App\Modules\Crm\Http\CustomerLocationContact');
}
public function networks()
{
return $this->hasMany('App\Modules\Assets\Http\Network');
}
public function vend_cust_loc()
{
return $this->hasMany('App\Modules\Vendor\Http\VendorCustomer', 'location_id');
}
}
<file_sep>/app/Modules/Assets/Http/KnowledgePassword.php
<?php
namespace App\Modules\Assets\Http;
use Illuminate\Database\Eloquent\Model;
class KnowledgePassword extends Model
{
function customer()
{
return $this->belongsTo('App\Modules\Crm\Http\Customer');
}
function tags()
{
return $this->belongsToMany('App\Modules\Assets\Http\Tag')->withTimestamps();
}
function asset()
{
return $this->belongsTo('App\Modules\Assets\Http\Asset', 'asset_id');
}
function vendor()
{
return $this->belongsTo('App\Modules\Vendor\Http\Vendor', 'vendor_id');
}
}
<file_sep>/app/Modules/Vendor/Http/routes.php
<?php
/*
|--------------------------------------------------------------------------
| Module Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for the module.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
/*Route::group(['prefix' => 'vendor'], function() {
Route::get('/', function() {
dd('This is the Vendor module index page.');
});
});*/
Route::group(['middleware' => 'web'], function () {
Route::group(['prefix' => 'admin','middleware' => 'admin'], function () {
Route::group(['prefix' => 'vendors','middleware' => ['role:admin|manager|technician']], function () {
Route::get('/', ['as'=>'admin.vendors.index','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@index']);
Route::get('show/{id}', ['as'=>'admin.vendor.show','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@show']);
Route::get('/create', ['as'=>'admin.vendor.create','middleware' => ['permission:create_vendor'], 'uses' => 'VendorController@create']);
Route::get('/vendor_index', ['as'=>'admin.vendors.vendor_index','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@vendorsIndex']);
Route::get('/vendor_index_cust_dashboard', ['as'=>'admin.vendors.vendor_index_cust_dashboard','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@vendorsCustDashboard']);
Route::post('/store', ['as'=>'admin.vendor.store','middleware' => ['permission:create_vendor'], 'uses' => 'VendorController@store']);
Route::post('/delete', ['as'=>'admin.vendor.destroy','middleware' => ['permission:create_vendor'], 'uses' => 'VendorController@destroy']);
Route::post('/create_contact', ['as'=>'admin.vendor.create_contact','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@addContact']);
Route::get('/refresh_contacts/{id}', ['as'=>'admin.vendor.ajax.refresh_contacts','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@refreshContacts']);
Route::post('/create_customer', ['as'=>'admin.vendor.create_customer','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@addCustomer']);
Route::get('/refresh_customers/{id}', ['as'=>'admin.vendor.ajax.refresh_customers','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@refreshCustomers']);
Route::get('/refresh_vendor_info/{id}', ['as'=>'admin.vendor.ajax.refresh_vendor_info','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@refreshVendorinfo']);
Route::post('/update_info', ['as'=>'admin.vendor.update.info','middleware' => ['permission:create_vendor'], 'uses' => 'VendorController@updateInfo']);
Route::get('/edit_contact/{id}', ['as'=>'admin.vendor.edit_contact','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@editContact']);
Route::post('/update_contact', ['as'=>'admin.vendor.update.contact','middleware' => ['permission:create_vendor'], 'uses' => 'VendorController@updateContact']);
Route::post('/delete_contact', ['as'=>'admin.vendor.contact.destroy','middleware' => ['permission:create_vendor'], 'uses' => 'VendorController@destroyContact']);
Route::get('/edit_customer/{id}', ['as'=>'admin.vendor.edit_customer','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@editCustomer']);
Route::post('/update_customer', ['as'=>'admin.vendor.update.customer','middleware' => ['permission:create_vendor'], 'uses' => 'VendorController@updateCustomer']);
Route::post('/delete_customer', ['as'=>'admin.vendor.customer.destroy','middleware' => ['permission:create_vendor'], 'uses' => 'VendorController@destroyCustomer']);
Route::post('/unlink_customer', ['as'=>'admin.vendor.customer.unlink','middleware' => ['permission:create_vendor'], 'uses' => 'VendorController@unlinkCustomer']);
Route::get('search_vend_contacts', ['as'=>'admin.vendor.search.contacts','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@searchVendorContacts']);
// Ajax
Route::get('ajax_detail/{id}/{loc_id}', ['as'=>'admin.vendor.ajax_details','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@ajaxDetails']);
Route::get('/vendors_list_json', ['as'=>'admin.ajax.vendors.json','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@ajaxVendorsJson']);
Route::get('/locations_list_json/{id}', ['as'=>'admin.ajax.locations.json','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@ajaxLocationsJson']);
Route::get('/vendor_add', ['as'=>'admin.add.vendors.for.customer','middleware' => ['permission:create_vendor'], 'uses' => 'VendorController@addVendorForCustomer']);
// Ajax
Route::get('ajax_detail/{id}', ['as'=>'admin.vendor.ajax_details','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@ajaxDetails']);
Route::post('/attach_vendor', ['as'=>'admin.vendor.store.cust_selected','middleware' => ['permission:create_vendor'], 'uses' => 'VendorController@storeVendorWithCustomerSelected']);
Route::get('custs_not_attached_to_vendor/{id}', ['as'=>'admin.vendor.custs_not_attached_to_vendor','middleware' => ['permission:list_vendor'], 'uses' => 'VendorController@custsNotAttachedToVendor']);
});
});
});<file_sep>/app/Modules/Employee/Http/Controllers/EmployeeController.php
<?php
namespace App\Modules\Employee\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Modules\Employee\Http\Employee;
use App\Modules\Employee\Http\Requests\EmployeePostRequest;
use App\Model\Role;
use App\Model\User;
use Auth;
use App\Modules\Employee\Http\Leave;
use App\Services\GoogleCalendar;
use App\Services\TimeZone;
class EmployeeController extends Controller
{
private $controller = 'employee';
public function index()
{
$controller = $this->controller;
$employees = User::where('type', 'employee')->get();
$route_delete = 'admin.employee.destroy';
return view('employee::admin.index', compact('employees', 'controller', 'route_delete'));
}
public function getById($id)
{
$user = User::find($id);
return view('admin.setting.user_ajax_get', compact('user'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$roles_obj = Role::select(['id','display_name'])->get();
$manager_obj = Role::with('users')->where('name', 'manager')->first();
$managers = [];
$roles = [];
if ($manager_obj->users->count()) {
foreach ($manager_obj->users as $user) {
$managers[$user->id]=$user->f_name." ".$user->l_name;
//dd($user->id);
}
}
if ($roles_obj->count()) {
foreach ($roles_obj as $role) {
$roles[$role->id]=$role->display_name;
//dd($user->id);
}
}
$timezone = new TimeZone();
$time_zones = $timezone->timezone_list();
return view('employee::admin.add', compact('roles', 'managers', 'time_zones'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(EmployeePostRequest $request)
{
//dd(date( "Y-m-d",strtotime($request->hire_date)));
//dd($request->all());
$user = new User;
$user->f_name = $request->f_name;
$user->l_name = $request->l_name;
$user->email = $request->email;
if ($request->password) {
$user->password = bcrypt($request->password);
}
if ($request->phone) {
$user->phone = $request->phone;
}
if ($request->mobile) {
$user->mobile = $request->mobile;
}
$user->type = $request->type;
$user->save();
$employee = new Employee;
$employee->pay_type = $request->pay_type;
$employee->hire_date = date("Y-m-d", strtotime($request->hire_date));
$employee->birth_date = date("Y-m-d", strtotime($request->birth_date));
if ($request->fax) {
$employee->fax = $request->fax;
}
$employee->managed_by = $request->managed_by;
$employee->billable_rate = $request->billable_rate;
$employee->cost_rate = $request->cost_rate;
$employee->pay_rate = $request->pay_rate;
$employee->vacation_yearly = $request->vacation_yearly;
$employee->sick_days_yearly = $request->sick_days_yearly;
$employee->withholding_tax_rate = $request->withholding_tax_rate;
$employee->home_address = $request->home_address;
$employee->time_zone = $request->time_zone;
$employee->emergency_contact_name = $request->emergency_contact_name;
$employee->emergency_contact_phone = $request->emergency_contact_phone;
$employee->health_insurance = $request->health_insurance;
$employee->life_insurance = $request->life_insurance;
$employee->retirement = $request->retirement;
$user->employee()->save($employee);
if ($request->role) {
$user->attachRole($request->role);
}
return redirect()->intended('admin/employee');
}
public function ajaxStore(Request $request)
{
$this->validate(
$request,
[
'email' => 'required',
'f_name' => 'required',
'l_name' => 'required',
]
);
if ($request->password !=='') {
$this->validate(
$request,
[
'password' => '<PASSWORD>',
]
);
}
//$user = User::find($request->user_id);
$user = User::find(Auth::user()->id);
$user->f_name = $request->f_name;
$user->l_name = $request->l_name;
$user->email = $request->email;
$user->phone = $request->phone;
$user->mobile = $request->mobile;
$user->exten = $request->exten;
if ($request->password) {
$user->password = <PASSWORD>($request->password);
}
$user->save();
$arr['success'] = 'Profile updated successfully';
return json_encode($arr);
exit;
//return redirect()->intended('admin/employee');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$employee = User::where('id', $id)->with('employee', 'roles', 'leave')->first();
//$availed_leaves = Leave::where('user_id',$id)->where('status','approved')->get()->count();
$availed_leaves = Leave::where('posted_for', $id)
->where('status', 'approved')
->selectRaw('category,sum(duration) as sum,type')
->groupBy(['category','type'])->get();
$annual = [];
$sick = [];
foreach ($availed_leaves as $value) {
//dd($value);
if ($value->type=='sick') {
if ($value->category=='short') {
$sick['short'] = $value->sum/8;
}
if ($value->category=='full') {
$sick['full'] = $value->sum;
}
}
if ($value->type=='annual') {
if ($value->category=='short') {
$annual['short'] = $value->sum/8;
}
if ($value->category=='full') {
$annual['full'] = $value->sum;
}
}
}
//dd($sick);
$availed_annual_leaves = number_format((isset($annual['full'])?$annual['full']:0), 2)+ number_format((isset($annual['short'])?$annual['short']:0), 2);
$availed_sick_leaves = number_format((isset($sick['full'])?$sick['full']:0), 2)+ number_format((isset($sick['short'])?$sick['short']:0), 2);
return view('employee::employee_dashboard.show', compact('employee', 'sick_leaves', 'availed_annual_leaves', 'availed_sick_leaves', 'annual_leaves'));
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$employee = User::where('id', $id)->with('employee')->first();
$roles_obj = Role::select(['id','display_name'])->get();
$manager_obj = Role::with('users')->where('name', 'manager')->first();
//dd($employee->raise);
$managers = [];
$user_role = [];
$managers = [];
$roles = [];
if ($manager_obj->users->count()) {
foreach ($manager_obj->users as $user) {
$managers[$user->id]=$user->f_name." ".$user->l_name;
//dd($user->id);
}
}
if ($roles_obj->count()) {
foreach ($roles_obj as $role) {
$roles[$role->id]=$role->display_name;
//dd($user->id);
}
}
if ($employee->roles) {
foreach ($employee->roles as $role) {
$user_role = $role->id;
//dd($role->display_name);
}
}
$timezone = new TimeZone();
$time_zones = $timezone->timezone_list();
return view('employee::admin.edit', compact('employee', 'roles', 'user_role', 'managers', 'time_zones'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(EmployeePostRequest $request, $id)
{
$user = User::find($id);
$user->f_name = $request->f_name;
$user->l_name = $request->l_name;
$user->email = $request->email;
if ($request->password) {
$user->password = <PASSWORD>($request->password);
}
if ($request->phone) {
$user->phone = $request->phone;
}
if ($request->mobile) {
$user->mobile = $request->mobile;
}
$user->type = $request->type;
$user->save();
//$employee = Employee::where('user_id',$id)->first();
$employee = $user->employee;
$employee->pay_type = $request->pay_type;
$employee->hire_date = date("Y-m-d", strtotime($request->hire_date));
$employee->birth_date = date("Y-m-d", strtotime($request->birth_date));
if ($request->fax) {
$employee->fax = $request->fax;
}
$employee->managed_by = $request->managed_by;
$employee->billable_rate = $request->billable_rate;
$employee->cost_rate = $request->cost_rate;
$employee->pay_rate = $request->pay_rate;
$employee->vacation_yearly = $request->vacation_yearly;
$employee->sick_days_yearly = $request->sick_days_yearly;
$employee->withholding_tax_rate = $request->withholding_tax_rate;
$employee->time_zone = $request->time_zone;
$employee->home_address = $request->home_address;
$employee->health_insurance = $request->health_insurance;
$employee->life_insurance = $request->life_insurance;
$employee->retirement = $request->retirement;
$employee->emergency_contact_name = $request->emergency_contact_name;
$employee->emergency_contact_phone = $request->emergency_contact_phone;
$user->employee()->save($employee);
$user->detachRoles($user->roles);
$user->attachRole($request->role);
return redirect()->intended('admin/employee');
//return redirect()->intended('admin/user');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
//dd($id);
//dd($request->id);
$id = $request->id;
$user = User::findorFail($id);
$user->detachRoles($user->roles);
$user->employee()->delete();
$user->delete();
return redirect()->intended('admin/employee');
}
public function googleCalander()
{
$calendar = new GoogleCalendar;
$calendarId = "<EMAIL>";
$result = $calendar->get($calendarId);
$calendar->eventPost([
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => [
'dateTime' => '2015-05-28T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
],
'end' => [
'dateTime' => '2015-05-28T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
],
'recurrence' => [
'RRULE:FREQ=DAILY;COUNT=2'
],
'attendees' => [
['email' => '<EMAIL>'],
['email' => '<EMAIL>'],
],
'reminders' => [
'useDefault' => false,
'overrides' => [
['method' => 'email', 'minutes' => 24 * 60],
['method' => 'popup', 'minutes' => 10],
],
],
], $calendarId);
exit;
//return view('employee::admin.edit',compact('result'));
}
}
<file_sep>/app/Modules/Assets/Http/Tag.php
<?php
namespace App\Modules\Assets\Http;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
//
protected $fillable = ['title'];
function password()
{
return $this->belongsToMany('App\Modules\Assets\Http\KnowledgePassword')->withTimestamps();
}
}
<file_sep>/app/Services/ImapGmail.php
<?php namespace App\Services;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
class ImapGmail
{
function getMessages()
{
$hostname = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX";
$username = '<EMAIL>';
$password = '<PASSWORD>';
$inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . print_r(imap_errors()));
/* grab emails */
$emails = imap_search($inbox, 'UNSEEN');
if ($emails) {
//rsort($emails);
/* for every email... */
foreach ($emails as $email_number) {
$overview = imap_fetch_overview($inbox, $email_number, 0);
/* get header of email */
$header = imap_header($inbox, $email_number, 0);
$structure = imap_fetchstructure($inbox, $email_number);
$header_info = imap_headerinfo($inbox, $email_number);
//$header_info = imap_headers( $inbox );
//dd( $header_info);
//$mime = imap_fetchmime ($inbox, $email_number);
// $message = imap_fetchbody($inbox, $email_number,'1.HTML');
//echo '<pre>';
//print_r($structure);
// print_r( $message);
// exit;
//dd( $structure);
$attachments = [];
$files = [];
//if(isset($structure->parts) && count($structure->parts) && $structure->type==1) {
if ($structure->subtype=='MIXED') {
//echo "sadasd";exit;
for ($i = 1; $i < count($structure->parts); $i++) {
if ($structure->parts[$i]->ifparameters) {
foreach ($structure->parts[$i]->parameters as $object) {
if (strtolower($object->attribute) == 'name') {
$files[] = ['name'=>$object->value,
'mime_type' =>$structure->parts[$i]->subtype];
//$attachments[$i]['name'] = $object->value;
$attachment_binary =imap_fetchbody($inbox, $email_number, $i+1);
if ($structure->parts[$i]->encoding == 3) {
$attachment_obj = base64_decode($attachment_binary);
}
//$fh = fopen(public_path("attachments/$object->value"), "w+");
$fh = fopen(public_path("attachments/$object->value"), "w+");
fwrite($fh, $attachment_obj);
fclose($fh);
}
}
}
/* 3 = BASE64 encoding */
/*elseif($structure->parts[$i]->encoding == 4) {
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}*/
}
/*if($structure->parts[0]->subtype=='ALTERNATIVE')
$message = imap_fetchbody($inbox,$email_number, 1.1);
if($structure->parts[0]->subtype=='PLAIN')
$message = imap_fetchbody($inbox,$email_number,1);*/
$message = $this->getBody($email_number, $inbox);
//$message = $attachment_binary;
//dd( $message);
} else {
// $message = imap_fetchbody($inbox, $email_number,1);
$message = $this->getBody($email_number, $inbox);
}
$inboxMessage[] = [
'body' => $message,
'title' => $overview[0]->subject,
'revceived_date' => $overview[0]->date,
'messageSender' =>$overview[0]->from,
'messageSenderEmail' => $header->sender[0]->mailbox.'@'.$header->sender[0]->host,
'attachments' => $files,
'message_id' => $header_info->message_id
];
}
}
//print_r( $inboxMessage);
//exit;
imap_close($inbox);
return $inboxMessage;
}
function getBody($uid, $imap)
{
$body = $this->get_part($imap, $uid, "TEXT/HTML");
// if HTML body is empty, try getting text body
if ($body == "") {
$body = $this->get_part($imap, $uid, "TEXT/PLAIN");
}
return $body;
}
function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false)
{
if (!$structure) {
$structure = imap_fetchstructure($imap, $uid);
}
if ($structure) {
if ($mimetype == $this->get_mime_type($structure)) {
if (!$partNumber) {
$partNumber = 1;
}
$text = imap_fetchbody($imap, $uid, $partNumber);
switch ($structure->encoding) {
case 3:
return imap_base64($text);
case 4:
return imap_qprint($text);
default:
return $text;
}
}
// multipart
if ($structure->type == 1) {
foreach ($structure->parts as $index => $subStruct) {
$prefix = "";
if ($partNumber) {
$prefix = $partNumber . ".";
}
$data = $this->get_part($imap, $uid, $mimetype, $subStruct, $prefix . ($index + 1));
if ($data) {
return $data;
}
}
}
}
return false;
}
function get_mime_type($structure)
{
$primaryMimetype = ["TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER"];
if ($structure->subtype) {
return $primaryMimetype[(int)$structure->type] . "/" . $structure->subtype;
}
return "TEXT/PLAIN";
}
function getThread()
{
$hostname = "{imap.gmail.com:993/imap/ssl}INBOX";
$username = '<EMAIL>';
$password = '<PASSWORD>';
$inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . print_r(imap_errors()));
/* grab emails */
$emails = imap_thread($inbox);
//dd($emails);
foreach ($emails as $key => $val) {
$tree = explode('.', $key);
if ($tree[1] == 'num') {
if ($val!=0) {
$header = imap_headerinfo($inbox, $val);
echo "<ul>\n\t<li>" . $header->fromaddress . "\n";
}
} elseif ($tree[1] == 'branch') {
echo "\t</li>\n</ul>\n";
}
}
dd('end');
if ($emails) {
//rsort($emails);
/* for every email... */
foreach ($emails as $key => $email_number) {
if ($email_number==0) {
continue;
}
$overview = imap_fetch_overview($inbox, $email_number, 0);
/* get header of email */
$header = imap_header($inbox, $email_number, 0);
$structure = imap_fetchstructure($inbox, $email_number);
$header_info = imap_headerinfo($inbox, $email_number);
//$header_info = imap_headers( $inbox );
//dd( $header_info);
//$mime = imap_fetchmime ($inbox, $email_number);
// $message = imap_fetchbody($inbox, $email_number,'1.HTML');
// echo '<pre>';
//print_r($header_info);
// print_r( $message);
// exit;
//dd( $structure);
$attachments = [];
$files = [];
//if(isset($structure->parts) && count($structure->parts) && $structure->type==1) {
if ($structure->subtype=='MIXED') {
//echo "sadasd";exit;
for ($i = 1; $i < count($structure->parts); $i++) {
if ($structure->parts[$i]->ifparameters) {
foreach ($structure->parts[$i]->parameters as $object) {
if (strtolower($object->attribute) == 'name') {
$files[] = ['name'=>$object->value,
'mime_type' =>$structure->parts[$i]->subtype];
//$attachments[$i]['name'] = $object->value;
$attachment_binary =imap_fetchbody($inbox, $email_number, $i+1);
if ($structure->parts[$i]->encoding == 3) {
$attachment_obj = base64_decode($attachment_binary);
}
//$fh = fopen(public_path("attachments/$object->value"), "w+");
$fh = fopen(public_path("attachments/$object->value"), "w+");
fwrite($fh, $attachment_obj);
fclose($fh);
}
}
}
/* 3 = BASE64 encoding */
/*elseif($structure->parts[$i]->encoding == 4) {
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}*/
}
/*if($structure->parts[0]->subtype=='ALTERNATIVE')
$message = imap_fetchbody($inbox,$email_number, 1.1);
if($structure->parts[0]->subtype=='PLAIN')
$message = imap_fetchbody($inbox,$email_number,1);*/
$message = $this->getBody($email_number, $inbox);
//$message = $attachment_binary;
//dd( $message);
} else {
// $message = imap_fetchbody($inbox, $email_number,1);
$message = $this->getBody($email_number, $inbox);
}
$inboxMessage[] = [
'body' => $message,
'title' => $overview[0]->subject,
'revceived_date' => $overview[0]->date,
'messageSender' =>$overview[0]->from,
'messageSenderEmail' => $header->sender[0]->mailbox.'@'.$header->sender[0]->host,
'attachments' => $files,
'message_id' => $header_info->message_id
];
}
}
//print_r( $inboxMessage);
//exit;
imap_close($inbox);
return $inboxMessage;
}
}
<file_sep>/app/Modules/Nexpbx/Http/Device.php
<?php
namespace App\Modules\Nexpbx\Http;
use Illuminate\Database\Eloquent\Model;
class Device extends Model
{
protected $table = 'nexpbx_devices';
public function domain()
{
return $this->belongsTo('App\Modules\Nexpbx\Http\Domain', 'domain_uuid', 'domain_uuid');
}
public function location()
{
return $this->belongsTo('App\Modules\Crm\Http\CustomerLocation', 'location_id', 'id');
}
}
<file_sep>/app/Modules/Backupmanager/Http/routes.php
<?php
/*
|--------------------------------------------------------------------------
| Module Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for the module.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::group(['prefix' => 'admin','middleware' => 'admin'], function () {
Route::group(['prefix' => 'bum','middleware' => []], function () {
Route::get('/', ['as'=>'admin.backupmanager.index','middleware' => [], 'uses' => 'ProvisioningController@index']);
Route::get('/editor/{id}', ['as'=>'admin.backupmanager.editor','middleware' => [], 'uses' => 'ProvisioningController@editor']);
Route::post('/editor_save/', ['as'=>'admin.backupmanager.editor.save','middleware' => [], 'uses' => 'ProvisioningController@editorSave']);
});
});
Route::get('/getscript/{id}/{uuid}', ['as'=>'admin.backupmanager.getscript','middleware' => [], 'uses' => 'ProvisioningController@getscript']);
<file_sep>/app/Modules/Assets/Http/Controllers/AssetsController.php
<?php
namespace App\Modules\Assets\Http\Controllers;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Modules\Crm\Http\Customer;
use App\Modules\Crm\Http\CustomerLocation;
use App\Modules\Assets\Http\Asset;
use App\Modules\Assets\Http\AssetRole;
use App\Modules\Assets\Http\KnowledgePassword;
use App\Modules\Assets\Http\AssetVirtualType;
use App\Modules\Assets\Http\Tag;
use Datatables;
use App\Model\Role;
use App\Model\User;
use Auth;
use Mail;
use URL;
use Session;
class AssetsController extends Controller
{
public function index()
{
//return view('assets::index');
//return "Controller Index";
return view('assets::assets');
}
function assetsAll()
{
$global_date = $this->global_date;
if (!empty(Session::get('cust_id'))) {
$assets = Asset::with(['customer'])->where('customer_id', Session::get('cust_id'));
} else {
$assets = Asset::with(['customer']);
}
//dd($assets);
return Datatables::of($assets)
->addColumn('action', function ($asset) {
$return = '<div class="btn-group">';
$return .= '<button type="button" class="btn btn-xs edit "
data-toggle="modal" data-id="'.$asset->id.'" id="modaal" data-target="#modal-edit-asset">
<i class="fa fa-edit " ></i></button>';
$return .=' <button type="button" class="btn btn-danger btn-xs"
data-toggle="modal" data-id="'.$asset->id.'" id="modaal" data-target="#modal_assest_delete" data-type="network">
<i class="fa fa-times-circle"></i></button></div>';
$return .= '</div>';
return $return;
})
->addColumn('customer', function ($asset) {
if ($asset->customer) {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span>'.$asset->customer->name.'</span>
</button>';
} else {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span></span>
</button>';
}
})
->editColumn('created_at', function ($ticket) use ($global_date) {
return date($global_date, strtotime($ticket->created_at));
})
->setRowId('id')
->make(true);
}
function networkIndex($id = null)
{
$global_date = $this->global_date;
if (!empty(Session::get('cust_id'))) {
$assets = Asset::with(['customer'])->where('asset_type', 'network')->where('customer_id', Session::get('cust_id'));
} else {
$assets = Asset::with(['customer'])->where('asset_type', 'network');
}
//dd($assets);
return Datatables::of($assets)
->addColumn('action', function ($asset) {
$return = '<div class="btn-group">';
$return .= '<button type="button" class="btn btn-xs edit "
data-toggle="modal" data-id="'.$asset->id.'" id="modaal" data-target="#modal-edit-asset">
<i class="fa fa-edit " ></i></button>';
$return .=' <button type="button" class="btn btn-danger btn-xs"
data-toggle="modal" data-id="'.$asset->id.'" id="modaal" data-target="#modal_assest_delete" data-type="network">
<i class="fa fa-times-circle"></i></button></div>';
$return .= '</div>';
return $return;
})
->addColumn('customer', function ($asset) {
if ($asset->customer) {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span>'.$asset->customer->name.'</span>
</button>';
} else {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span></span>
</button>';
}
})
->editColumn('created_at', function ($ticket) use ($global_date) {
return date($global_date, strtotime($ticket->created_at));
})
->setRowId('id')
->make(true);
}
function gatewayIndex($id = null)
{
$global_date = $this->global_date;
if (!empty(Session::get('cust_id'))) {
$assets = Asset::with(['customer'])->where('asset_type', 'gateway')->where('customer_id', Session::get('cust_id'));
} else {
$assets = Asset::with(['customer'])->where('asset_type', 'gateway');
}
return Datatables::of($assets)
->addColumn('action', function ($asset) {
$return = '<div class="btn-group">';
$return .= '<button type="button" class="btn btn-xs edit "
data-toggle="modal" data-id="'.$asset->id.'" id="modaal" data-target="#modal-edit-asset">
<i class="fa fa-edit " ></i></button>';
$return .=' <button type="button" class="btn btn-danger btn-xs"
data-toggle="modal" data-id="'.$asset->id.'" id="modaal" data-target="#modal_assest_delete" data-type="network">
<i class="fa fa-times-circle"></i></button></div>';
$return .= '</div>';
return $return;
})
->editColumn('created_at', function ($ticket) use ($global_date) {
return date($global_date, strtotime($ticket->created_at));
})
->addColumn('customer', function ($asset) {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span>'.$asset->customer->name.'</span>
</button>';
})
->setRowId('id')
->make(true);
}
function pbxIndex($id = null)
{
$global_date = $this->global_date;
if (!empty(Session::get('cust_id'))) {
$assets = Asset::with(['customer'])->where('asset_type', 'pbx')->where('customer_id', Session::get('cust_id'));
} else {
$assets = Asset::with(['customer'])->where('asset_type', 'pbx');
}
return Datatables::of($assets)
->addColumn('action', function ($asset) {
$return = '<div class="btn-group">';
$return .= '<button type="button" class="btn btn-xs edit "
data-toggle="modal" data-id="'.$asset->id.'" id="modaal" data-target="#modal-edit-asset">
<i class="fa fa-edit " ></i></button>';
$return .=' <button type="button" class="btn btn-danger btn-xs"
data-toggle="modal" data-id="'.$asset->id.'" id="modaal" data-target="#modal_assest_delete" data-type="network">
<i class="fa fa-times-circle"></i></button></div>';
$return .= '</div>';
return $return;
})
->editColumn('created_at', function ($ticket) use ($global_date) {
return date($global_date, strtotime($ticket->created_at));
})
->addColumn('customer', function ($asset) {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span>'.$asset->customer->name.'</span>
</button>';
})
->setRowId('id')
->make(true);
}
function serverIndex($id = null)
{
$global_date = $this->global_date;
if (!empty(Session::get('cust_id'))) {
$assets = Asset::with(['customer','virtual_type'])->where('asset_type', 'server')->where('customer_id', Session::get('cust_id'));
} else {
$assets = Asset::with(['customer','virtual_type'])->where('asset_type', 'server');
}
return Datatables::of($assets)
->addColumn('action', function ($asset) {
$return = '<div class="btn-group">';
$return .= '<button type="button" class="btn btn-xs edit "
data-toggle="modal" data-id="'.$asset->id.'" id="modaal" data-target="#modal-edit-asset">
<i class="fa fa-edit " ></i></button>';
$return .=' <button type="button" class="btn btn-danger btn-xs"
data-toggle="modal" data-id="'.$asset->id.'" id="modaal" data-target="#modal_assest_delete" data-type="network">
<i class="fa fa-times-circle"></i></button></div>';
$return .= '</div>';
return $return;
})
->editColumn('created_at', function ($ticket) use ($global_date) {
return date($global_date, strtotime($ticket->created_at));
})
->addColumn('customer', function ($asset) {
if ($asset->customer) {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span>'.$asset->customer->name.'</span>
</button>';
} else {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span></span>
</button>';
}
})
->setRowId('id')
->make(true);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$customers_obj = Customer::with(['locations','locations.contacts'])->where('is_active', 1)->get();
$asset_roles_obj = AssetRole::all();
$asset_vtypes_obj = AssetVirtualType::all();
$customers = [];
if ($customers_obj->count()) {
foreach ($customers_obj as $customer) {
$customers[$customer->id]=$customer->name.'('.$customer->email_domain.')';
//dd($user->id);
}
}
$asset_roles =[];
if ($asset_roles_obj->count()) {
foreach ($asset_roles_obj as $asset_role) {
$asset_roles[ $asset_role->id]= $asset_role->title;
//dd($user->id);
}
}
$asset_v_types =[];
if ($asset_vtypes_obj->count()) {
foreach ($asset_vtypes_obj as $asset_v_type) {
$asset_v_types[ $asset_v_type->id]= $asset_v_type->title;
//dd($user->id);
}
}
return view('assets::add', compact('customers', 'asset_roles', 'asset_v_types'));
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//dd($request->all());
$this->validate(
$request,
[
'name' => 'required',
'customer' => 'required',
'asset_type' =>'required',
]
);
if ($request->asset_type == 'network') {
// dd($request->asset_type);
$this->validate(
$request,
[
//'manufacture' => 'required',
// 'model' => 'required',
]
);
$asset = new Asset();
$asset->name = $request->name;
$asset->customer_id = $request->customer;
$asset->location_id = $request->location;
$asset->mac_address = $request->mac;
$asset->manufacture = $request->manufacture;
$asset->os = $request->os;
$asset->asset_type = 'network';
$asset->model = $request->model;
$asset->ip_address = $request->ip_address;
//$asset->user_name = $request->user_name;
//$asset->password = $request->password;
$asset->is_static = $request->is_static;
$asset->static_type = $request->static_type;
$asset->notes = $request->notes;
$asset->save();
$kpass = new KnowledgePassword();
$kpass->login = $request->user_name;
$kpass->password = $request->password;
$kpass->customer_id = $request->customer;
$pass = $asset->password()->save($kpass);
$tag = Tag::firstOrCreate(['title' => 'asset']);
$pass->tags()->attach([$tag->id]);
$arr['success'] = 'Asset added sussessfully';
return json_encode($arr);
exit;
}
if ($request->asset_type == 'gateway') {
//dd('here');
$this->validate(
$request,
[
'manufacture' => 'required',
'model' => 'required',
]
);
$asset = new Asset();
$asset->name = $request->name;
$asset->customer_id = $request->customer;
$asset->location_id = $request->location;
$asset->manufacture = $request->manufacture;
$asset->asset_type = 'gateway';
$asset->model = $request->model;
$asset->lan_ip_address = $request->lan_ip_address;
$asset->wan_ip_address = $request->wan_ip_address;
//$asset->password = $request->password;
//$asset->user_name = $request->user_name;
$asset->notes = $request->notes;
$asset->save();
$kpass = new KnowledgePassword();
$kpass->login = $request->user_name;
$kpass->password = $request->password;
$kpass->customer_id = $request->customer;
$pass = $asset->password()->save($kpass);
$tag = Tag::firstOrCreate(['title' => 'asset']);
$pass->tags()->attach([$tag->id]);
$arr['success'] = 'Asset added sussessfully';
return json_encode($arr);
exit;
}
if ($request->asset_type == 'pbx') {
//dd('here');
$this->validate(
$request,
[
'manufacture' => 'required',
]
);
$asset = new Asset();
$asset->name = $request->name;
$asset->customer_id = $request->customer;
$asset->location_id = $request->location;
$asset->manufacture = $request->manufacture;
$asset->os = $request->os;
$asset->asset_type = 'pbx';
$asset->ip_address = $request->ip_address;
$asset->host_name = $request->host_name;
//$asset->user_name = $request->user_name;
//$asset->password = $request->password;
$asset->admin_gui_address = $request->admin_gui_address;
$asset->hosted = $request->hosted;
$asset->save();
$kpass = new KnowledgePassword();
$kpass->login = $request->user_name;
$kpass->password = $<PASSWORD>;
$kpass->customer_id = $request->customer;
$pass = $asset->password()->save($kpass);
$tag = Tag::firstOrCreate(['title' => 'asset']);
$pass->tags()->attach([$tag->id]);
$arr['success'] = 'Asset added sussessfully';
return json_encode($arr);
exit;
}
if ($request->asset_type == 'server') {
$asset = new Asset();
$asset->name = $request->name;
$asset->customer_id = $request->customer;
$asset->location_id = $request->location;
$asset->server_type = $request->server_type;
$asset->asset_virtual_type_id = $request->virtual_type;
$asset->asset_type = 'server';
$asset->roles = json_encode($request->roles);
$asset->ip_address = $request->ip_address;
$asset->host_name = $request->host_name;
//$asset->serial_number = $request->serial_number;
$asset->notes = $request->notes;
$asset->save();
$kpass = new KnowledgePassword();
$kpass->login = $request->user_name;
$kpass->password = <PASSWORD>;
$kpass->customer_id = $request->customer;
$pass = $asset->password()->save($kpass);
$arr['success'] = 'Asset added sussessfully';
return json_encode($arr);
exit;
}
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$asset = Asset::with(['customer','location','virtual_type'])->where('id', $id)->first();
//dd($asset);
$asset_roles_obj = AssetRole::all();
$asset_roles =[];
if ($asset_roles_obj->count()) {
foreach ($asset_roles_obj as $asset_role) {
$asset_roles[ $asset_role->id]= $asset_role->title;
//dd($user->id);
}
}
$arr['html_content_asset'] = view('assets::show_partial', compact('asset', 'asset_roles'))->render();
$arr['asset_name'] = $asset->name;
return json_encode($arr);
exit;
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$asset = Asset::with(['customer','location','virtual_type','password'])->where('id', $id)->first();
//dd($asset->password);
$cust_locations = CustomerLocation::where('customer_id', $asset->customer->id)->get();
$locations = [];
if ($cust_locations->count()) {
foreach ($cust_locations as $cust_location) {
$locations[$cust_location->id]=$cust_location->location_name;
//dd($user->id);
}
}
$customers_obj = Customer::with(['locations','locations.contacts'])->get();
$customers = [];
if ($customers_obj->count()) {
foreach ($customers_obj as $customer) {
$customers[$customer->id]=$customer->name.'('.$customer->email_domain.')';
//dd($user->id);
}
}
$asset_roles_obj = AssetRole::all();
$asset_roles =[];
if ($asset_roles_obj->count()) {
foreach ($asset_roles_obj as $asset_role) {
$asset_roles[ $asset_role->id]= $asset_role->title;
//dd($user->id);
}
}
$asset_vtypes_obj = AssetVirtualType::all();
$asset_v_types =[];
if ($asset_vtypes_obj->count()) {
foreach ($asset_vtypes_obj as $asset_v_type) {
$asset_v_types[ $asset_v_type->id]= $asset_v_type->title;
//dd($user->id);
}
}
//dd($asset);
// $arr['locations'] = $locations;
$arr['html_content_asset'] = view('assets::edit_partial', compact('asset', 'locations', 'customers', 'asset_roles', 'asset_v_types'))->render();
$arr['asset_type'] = $asset ->asset_type;
//$arr['asset_name'] = $asset->name;
return json_encode($arr);
exit;
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request)
{
$id = $request->asset_id;
//dd($request->all());
$this->validate(
$request,
['name' => 'required',
'customer' => 'required',
]
);
if ($request->asset_type == 'network') {
// dd($request->asset_type);
$this->validate(
$request,
[
// 'manufacture' => 'required',
// 'model' => 'required',
]
);
$asset = Asset::find($id);
$asset->name = $request->name;
$asset->customer_id = $request->customer;
$asset->location_id = $request->location;
$asset->manufacture = $request->manufacture;
$asset->os = $request->os;
$asset->mac_address = $request->mac;
$asset->asset_type = 'network';
$asset->model = $request->model;
$asset->ip_address = $request->ip_address;
//$asset->user_name = $request->user_name;
//$asset->password = $request->password;
$asset->is_static = $request->is_static;
$asset->static_type = $request->static_type;
$asset->notes = $request->notes;
$asset->save();
//dd($asset);
if ($asset->password) {
if ($request->user_name =='' && $request->password =='') {
$kpass = KnowledgePassword::where('customer_id', $request->customer)->where('asset_id', $id)->delete();
} else {
$kpass['login'] = $request->user_name;
$kpass['password'] = $<PASSWORD>;
$asset->password()->update($kpass);
}
} else {
if ($request->user_name !='' && $request->password !='') {
$kpass = new KnowledgePassword();
$kpass->login = $request->user_name;
$kpass->password = $<PASSWORD>;
$kpass->customer_id = $request->customer;
$pass = $asset->password()->save($kpass);
$tag = Tag::firstOrCreate(['title' => 'asset']);
$pass->tags()->attach([$tag->id]);
}
}
$arr['success'] = 'Asset added sussessfully';
return json_encode($arr);
exit;
}
if ($request->asset_type == 'gateway') {
//dd('here');
$this->validate(
$request,
[
'manufacture' => 'required',
'model' => 'required',
]
);
$asset = Asset::find($id);
$asset->name = $request->name;
$asset->customer_id = $request->customer;
$asset->location_id = $request->location;
$asset->manufacture = $request->manufacture;
$asset->asset_type = 'gateway';
$asset->model = $request->model;
$asset->lan_ip_address = $request->lan_ip_address;
$asset->wan_ip_address = $request->wan_ip_address;
//$asset->password = $request->password;
//$asset->user_name = $request->user_name;
$asset->notes = $request->notes;
$asset->save();
if ($asset->password) {
if ($request->user_name =='' && $request->password =='') {
$kpass = KnowledgePassword::where('customer_id', $request->customer)->where('asset_id', $id)->delete();
} else {
$kpass['login'] = $request->user_name;
$kpass['password'] = $request->password;
$asset->password()->update($kpass);
}
} else {
if ($request->user_name !='' && $request->password !='') {
$kpass = new KnowledgePassword();
$kpass->login = $request->user_name;
$kpass->password = $<PASSWORD>;
$kpass->customer_id = $request->customer;
$pass = $asset->password()->save($kpass);
$tag = Tag::firstOrCreate(['title' => 'asset']);
$pass->tags()->attach([$tag->id]);
}
}
$arr['success'] = 'Asset added sussessfully';
return json_encode($arr);
exit;
}
if ($request->asset_type == 'pbx') {
//dd('here');
$this->validate($request, ['manufacture' => 'required']);
$asset = Asset::find($id);
$asset->name = $request->name;
$asset->customer_id = $request->customer;
$asset->location_id = $request->location;
$asset->manufacture = $request->manufacture;
$asset->os = $request->os;
$asset->asset_type = 'pbx';
$asset->ip_address = $request->ip_address;
$asset->host_name = $request->host_name;
//$asset->user_name = $request->user_name;
//$asset->password = $request->password;
$asset->admin_gui_address = $request->admin_gui_address;
$asset->hosted = $request->hosted;
$asset->save();
if ($asset->password) {
if ($request->user_name =='' && $request->password =='') {
$kpass = KnowledgePassword::where('customer_id', $request->customer)->where('asset_id', $id)->delete();
} else {
$kpass['login'] = $request->user_name;
$kpass['password'] = $request->password;
$asset->password()->update($kpass);
}
} else {
if ($request->user_name !='' && $request->password !='') {
$kpass = new KnowledgePassword();
$kpass->login = $request->user_name;
$kpass->password = $request->password;
$kpass->customer_id = $request->customer;
$pass = $asset->password()->save($kpass);
$tag = Tag::firstOrCreate(['title' => 'asset']);
$pass->tags()->attach([$tag->id]);
}
}
$arr['success'] = 'Asset added sussessfully';
return json_encode($arr);
exit;
}
if ($request->asset_type == 'server') {
$asset = Asset::find($id);
$asset->name = $request->name;
$asset->customer_id = $request->customer;
$asset->location_id = $request->location;
$asset->server_type = $request->server_type;
//$asset->user_name = $request->user_name;
//$asset->password = $request->password;
$asset->admin_gui_address = $request->admin_gui_address;
$asset->asset_virtual_type_id = $request->virtual_type;
$asset->asset_type = 'server';
$asset->roles = json_encode($request->roles);
$asset->ip_address = $request->ip_address;
$asset->host_name = $request->host_name;
// $asset->serial_number = $request->serial_number;
$asset->notes = $request->notes;
$asset->save();
if ($asset->password) {
$kpass['login'] = $request->user_name;
$kpass['password'] = $request->password;
$asset->password()->update($kpass);
} else {
$kpass = new KnowledgePassword();
$kpass->login = $request->user_name;
$kpass->password = $request->password;
$kpass->customer_id = $request->customer;
$pass = $asset->password()->save($kpass);
$tag = Tag::firstOrCreate(['title' => 'asset']);
$pass->tags()->save([$tag->id]);
}
$arr['success'] = 'Asset added sussessfully';
return json_encode($arr);
exit;
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
function destroy(Request $request)
{
$asset = Asset::find($request->id);
if ($asset->password) {
$asset->password()->delete();
}
$asset->delete();
$arr['success'] = 'Asset deleted successfully';
return json_encode($arr);
exit;
}
}
<file_sep>/app/Modules/Vendor/Http/VendorCustomer.php
<?php
namespace App\Modules\Vendor\Http;
use Illuminate\Database\Eloquent\Model;
class VendorCustomer extends Model
{
protected $table = 'customer_vendor';
}
<file_sep>/app/Modules/Crm/Http/Controllers/FilemanagerController_bkup-21-03-2017x.php
<?php
namespace App\Modules\Crm\Http\Controllers;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
//use GuillermoMartinez\Filemanager\Filemanager;
use App\Services\FilemanagerService;
use Storage;
use File;
use URL;
use Image;
use Auth;
use Session;
use Response;
use App\Modules\Crm\Http\Customer;
class FilemanagerController extends Controller
{
public $path ;
public $folder;
public function __construct()
{
// $this->middleware('auth');
$this->setPath();
}
public function getIndex()
{
if (!empty(Session::get('cust_id'))) {
$customer = Customer::find(Session::get('cust_id'));
}
$folder = $this->folder;
return view('crm::crm.file_manager', compact('customer', 'folder'));
}
public function setPath()
{
if (!empty(Session::get('cust_id'))) {
$customer = Customer::find(Session::get('cust_id'));
if ($customer->folder!='') {
$this->path = storage_path('customer_files/'.$customer->folder);
$this->folder = $customer->folder;
//$this->path = '/../storage/customer_files/'.$customer->folder;
} else {
$uuid = $this->generateGuid();
$this->path = storage_path('customer_files/'.$uuid);
$this->folder = $uuid;
//$this->path = '../storage/customer_files/'.$uuid;
File::MakeDirectory($this->path, 0775, true);
$customer->folder = $uuid;
$customer->save();
}
}
}
public function getConnection()
{
if (!empty(Session::get('cust_id'))) {
$extra = [
"source" => $this->path,//$path,
"url" => url('/'),
"doc_root"=>'',
'c_folder' => $this->folder,
"ext" => ["jpg","jpeg","gif","png","svg","txt","pdf","odp","ods","odt","rtf","doc","docx","xls","xlsx","ppt","pptx","csv","ogv","mp4","webm","m4v","ogg","mp3","wav","zip","rar"],
"upload" => [
"number" => 5,
"overwrite" => false,
"size_max" => 10
],
"images" => [
"images_ext" => ["jpg","jpeg","gif","png"],
"resize" => ["thumbWidth" => 120,"thumbHeight" => 90]
],
];
$f = new FilemanagerService($extra);
$f->run();
}
}
public function postConnection()
{
// $item['preview'] = url(URL::route('get.user_files.thumb', ['folder' => $folder,'filename' => $thumb]));
//original Code
//$item['preview'] = $this->config['url'].$this->config['source'].'/_thumbs'.$path.$thumb;
//dd($_POST);
// echo $path = storage_path('cccc');
// Storage::disk('local')->makeDirectory('customer_files');
if (!empty(Session::get('cust_id'))) {
$extra = [
"source" => $this->path,
"url" => url('/'),
"doc_root"=>'',
'c_folder' => $this->folder,
"ext" => ["jpg","jpeg","gif","png","svg","txt","pdf","odp","ods","odt","rtf","doc","docx","xls","xlsx","ppt","pptx","csv","ogv","mp4","webm","m4v","ogg","mp3","wav","zip","rar"],
"upload" => [
"number" => 5,
"overwrite" => false,
"size_max" => 10
],
"images" => [
"images_ext" => ["jpg","jpeg","gif","png"],
"resize" => ["thumbWidth" => 120,"thumbHeight" => 90]
],
];
/*$extra = array(
"source" => url(URL::route('get.user_files.thumb', ['folder' => $this->folder])),
"url" => url('/'),
"doc_root"=>'',
'c_folder' => $this->folder,
);*/
if (isset($_POST['typeFile']) && $_POST['typeFile']=='images') {
$extra['type_file'] = 'images';
}
$f = new FilemanagerService($extra);
$f->run();
}
}
private function generateGuid()
{
$s = strtoupper(md5(uniqid(rand(), true)));
$guidText =
substr($s, 0, 8) . '-' .
substr($s, 8, 4) . '-' .
substr($s, 12, 4). '-' .
substr($s, 16, 4). '-' .
substr($s, 20);
return $guidText;
}
public function retrieveFile($folder, $filename)
{
$path = storage_path('customer_files/'.$folder.'/'.$filename);
$ext = File::extension($filename);
if ($ext=='pdf') {
//$filename = 'test.pdf';
//$path = storage_path($filename);
return Response::make(file_get_contents($path), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'"'
]);
} else {
return Image::make($path)->response();
}
}
public function retrieveThumb($folder, $filename)
{
$path = storage_path('customer_files/'.$folder.'/_thumbs/'.$filename);
return Image::make($path)->response();
}
}
<file_sep>/app/Modules/Crm/Http/CustomerServiceType.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class CustomerServiceType extends Model
{
public function service_items()
{
return $this->hasOne('App\Modules\Crm\Http\CustomerServiceItem', 'service_type_id');
}
public function delete()
{
$this->service_items()->delete();
return parent::delete();
}
}
<file_sep>/app/Modules/Crm/Resources/Views/notes/index.blade (copy).php
@extends('admin.main')
@section('content')
<section class="content-header">
<h1>
Notes
</h1>
<ol class="breadcrumb">
<li>
<i class="fa fa-dashboard"></i> <a href="/admin/dashboard">Dashboard</a>
</li>
<li class="active">
<i class="fa fa-table"></i> notes
</li>
</ol>
</section>
<section class="content">
<div class="row">
<div class="col-xs-12">
<div id="msg"></div>
<div class="nav-tabs-custom ">
<ul class="nav nav-tabs">
<li class="active"><a href="#tab_active_note" data-toggle="tab">Active</a></li>
<li><a href="#tab_acvhived_note" data-toggle="tab">Archived</a></li>
{{-- <li><a href="#tab_handson_tables" data-toggle="tab">HandsonTables</a></li> --}}
</ul>
<div class="tab-content ">
<div class="tab-pane active table-responsive" id="tab_active_note">
<table class="table table-hover" style="cursor:pointer" id="dt_active_notes_table">
<thead>
<tr>
<th></th>
<th>Subject</th>
<th>Source</th>
<th>Created By</th>
<th>Created at</th>
<th>Actions</th>
</tr>
</thead>
</table>
<script id="details-template-active" type="text/x-handlebars-template">
<div class="attachment">
<label>ID: @{{id}}</label>
<br/>
<label>Detail:</label>
<p class="filename">
@{{note}}
</p>
</div>
{{-- <label>Detail:</label>
<p class="filename">
@{{note}}
</p>
--}}
</div>
</script>
</div><!-- /.tab-pane -->
<div class="tab-pane" id="tab_acvhived_note">
<table class="table table-hover" style="cursor:pointer" id="dt_archived_notes_table">
<thead>
<tr>
<th></th>
<th>Subject</th>
<th>Source</th>
<th>Created By</th>
<th>Created at</th>
<th>Actions</th>
</tr>
</thead>
</table>
<script id="details-template-archived" type="text/x-handlebars-template">
<div class="attachment">
<label>ID: @{{id}}</label>
<br/>
<label>Detail:</label>
<p class="filename">
@{{note}}
</p>
</div>
{{-- <table class="table">
<tr>
<td>Detail:</td>
<td>@{{note}}</td>
</tr>
</table> --}}
</script>
</div><!-- /.tab-pane -->
{{-- <div class="tab-pane" id="tab_handson_tables">
<div id="htable"></div>
</div> --}}
</div><!-- /.tab-content -->
</div>
</div><!-- /.box-body -->
</div>
</div>
</section>
@include('crm::notes.ajax_edit_note_modal')
{{-- @include('crm::notes.handsontable_modal') --}}
@endsection
@section('script')
@parent
<!-- <script src="/js/jquery.dataTables.min.js"></script> -->
<script src="{{URL::asset('DataTables/datatables.min.js')}}"></script>
<script type="text/javascript" src="{{URL::asset('js/handlebars.js')}}"></script>
<script src="{{URL::asset('js/bootstrap-dialog.min.js')}}"></script>
<script src="{{URL::asset('js/bootstrap-editable.min.js')}}"></script>
<script src="{{URL::asset('js/select2.full.min.js')}}"></script>
<script src="{{URL::asset('vendor/summernote/summernote.js')}}"></script>
<script src="{{URL::asset('vendor/summernote/summernote-floats-bs.min.js')}}"></script>
<script>
var table_active ='';
var table_archive ='';
$(function() {
var template_active = Handlebars.compile($("#details-template-active").html());
var template_archived = Handlebars.compile($("#details-template-archived").html());
table_active = $('#dt_active_notes_table').DataTable({
processing: true,
serverSide: true,
bAutoWidth: false,
ajax: '{!! route('admin.crm.notes.data_index_active') !!}',
"order": [[ 4, "desc" ]],
columns: [{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": '<i class="glyphicon p glyphicon-chevron-right"></i>',
"searchable": false
},
{data: 'subject',name: 'subject'},
{data: 'source',name: 'source'},
{data: 'created_by',name: 'created_by',orderable: false,searchable: false},
{data: 'created_at',name: 'created_at'},
{data: 'actions',name: 'actions',orderable: false,searchable: false}
],
"fnDrawCallback": function(){
var paginateRow = $(this).parent().prev().children('div.dataTables_paginate');
var pageCount = Math.ceil((this.fnSettings().fnRecordsDisplay()) / this.fnSettings()._iDisplayLength);
//console.log(pageCount);
if (pageCount > 1) {
$('.dataTables_paginate').css("display", "block");
} else {
$('.dataTables_paginate').css("display", "none");
}
},
"initComplete": function( settings, json ) {
init_editable();
}
});
$('#dt_active_notes_table tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table_active.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.find('i.glyphicon').removeClass('glyphicon-chevron-down');
tr.find('i.glyphicon').addClass('glyphicon-chevron-right');
}
else {
// Open this row
row.child( template_active(row.data()) ).show();
tr.find('i.glyphicon').addClass('glyphicon-chevron-down');
tr.find('i.glyphicon').removeClass('glyphicon-chevron-right');
}
});
table_archive = $('#dt_archived_notes_table').DataTable({
processing: true,
serverSide: true,
bAutoWidth: false,
ajax: '{!! route('admin.crm.notes.data_index_archived') !!}',
"order": [[ 4, "desc" ]],
columns: [{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": '<i class="glyphicon p glyphicon-chevron-right"></i>',
"searchable": false
},
{data: 'subject',name: 'subject'},
{data: 'source',name: 'source'},
{data: 'created_by',name: 'created_by',orderable: false,searchable: false},
{data: 'created_at',name: 'created_at'},
{data: 'actions',name: 'actions',orderable: false,searchable: false}
],
"fnDrawCallback": function(){
var paginateRow = $(this).parent().prev().children('div.dataTables_paginate');
var pageCount = Math.ceil((this.fnSettings().fnRecordsDisplay()) / this.fnSettings()._iDisplayLength);
//console.log(pageCount);
if (pageCount > 1) {
$('.dataTables_paginate').css("display", "block");
} else {
$('.dataTables_paginate').css("display", "none");
}
},
"initComplete": function( settings, json ) {
init_editable();
}
});
$('#dt_archived_notes_table tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table_archive.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.find('i.glyphicon').removeClass('glyphicon-chevron-down');
tr.find('i.glyphicon').addClass('glyphicon-chevron-right');
}
else {
// Open this row
row.child( template_archived(row.data()) ).show();
tr.find('i.glyphicon').addClass('glyphicon-chevron-down');
tr.find('i.glyphicon').removeClass('glyphicon-chevron-right');
}
});
$('.multiselect').multiselect({
enableFiltering: true,
includeSelectAllOption: true,
maxHeight: 400,
dropUp: false,
buttonClass: 'form-control',
buttonWidth: '100%'
});
$('#show_customers').on('change', function(e){
$.ajax({
url:'{!! route('admin.crm.show_custs') !!}',
data:'show_custs='+$(this).val(),
type:'post',
success:function(data)
{
if(data='ok')
window.location.reload();
}
});
});
$('#modal-edit-note').on('show.bs.modal', function(e)
{
$("#note_source").select2({
data: [
{ id: 'Call', text: 'Call' },
{ id: 'Email', text: 'Email' },
{ id: 'Visit', text: 'Visit' },
{ id: 'Other', text: 'Other' }
],
minimumResultsForSearch: Infinity,
placeholder: "",
allowClear: true
});
var Id = $(e.relatedTarget).data('id');
$(e.currentTarget).find('#note_id').val(Id);
$.get('/admin/crm/notes/single/'+Id,function(response) {
//$('#location_'+loc_id).html(data_response);
$(e.currentTarget).find('#note_subject').val(response.subject);
$("#note_source").val(response.source).change();
$('#create_note_body').val(response.note);
$('#create_note_body').summernote({
callbacks: {
onImageUpload: function(files) {
//console.log(files);
// console.log($editable);
uploadImage(files[0],'note','create_note_body');
}},
lang: 'en-US',
dialogsInBody: true,
height: 200, // set editor height
minHeight: null, // set minimum height of editor
maxHeight: null, // set maximum height of editor
focus: true});
},"json");
});
$(".update_ajax_note").click(function() {
//$('#loc_tbl_'+Id).html('<img id="load_img" src="{{asset('img/loader.gif')}}" />');
//alert( "Handler for .click() called." );
$.ajax({
url: "{{ URL::route('admin.crm.ajax.note.update')}}",
//headers: {'X-CSRF-TOKEN': token},
type: 'POST',
dataType: 'json',
data:$('#note_form').serialize() ,
success: function(response){
if(response.success){
/* table_active.ajax.reload();
table_archive.ajax.reload();
init_editable();*/
$( "#close_modal_note" ).trigger( "click" );
$('<div class="alert alert-success"><ul><li>'+response.msg+'</li></ul></div>').insertBefore('#msg');
location.reload();
//alert_hide();
}
},
error: function(data){
var errors = data.responseJSON;
//console.log(errors);
var html_error = '';
$.each(errors, function (key, value)
{
html_error +='<li>'+value+'</li>';
})
$('#edit_note_errors').html(html_error);
$('#note_msg_div').removeClass('alert-success').addClass('alert-danger').show();
alert_hide();
// Render the errors with js ...
}
});
});
});
function init_editable()
{
$('.subject_editable').editable({
inputclass:'col-md-12',
name:'subject',
mode:'inline',
url: '{{URL::route('admin.crm.ajax.note.update_editable')}}'
});
var source_data = [{ id: 'Call', text: 'Call' },
{ id: 'Email', text: 'Email' },
{ id: 'Visit', text: 'Visit' },
{ id: 'Other', text: 'Other' }];
$('.source').editable({
inputclass:'col-md-12',
mode:'inline',
url: '{{URL::route('admin.crm.ajax.note.update_editable')}}',
source: source_data,
select2: {
multiple: false
}
});
}
function change_pin_note(id,value)
{
$.ajax({
url: "{{ URL::route('admin.crm.note.pin_status_change')}}",
//headers: {'X-CSRF-TOKEN': token},
type: 'POST',
dataType: 'json',
data: 'id='+id+'&pin_status='+value,
success: function(response){
if(response.success=='ok')
{
table_active.ajax.reload();
table_archive.ajax.reload();
$('<div class="alert alert-success"><ul><li>'+response.msg+'</li></ul></div>').insertBefore('#msg');
alert_hide();
}
}
});
}
function change_archive_note(id,value)
{
$.ajax({
url: "{{ URL::route('admin.crm.note.archive_status_change')}}",
//headers: {'X-CSRF-TOKEN': token},
type: 'POST',
dataType: 'json',
data: 'id='+id+'&archive_status='+value,
success: function(response){
if(response.success=='ok')
{
table_archive.ajax.reload();
table_active.ajax.reload();
init_editable();
$('<div class="alert alert-success"><ul><li>'+response.msg+'</li></ul></div>').insertBefore('#msg');
alert_hide();
}
}
});
}
function delete_note(id)
{
BootstrapDialog.show({
title: 'Delete Record',
message: 'Are you sure to delete the record?',
buttons: [{
label: 'Yes',
action: function(dialog) {
//dialog.setTitle('Title 1');
//console.log('hhh');
$.ajax({
url: "{{ URL::route('admin.crm.note.delete')}}",
//headers: {'X-CSRF-TOKEN': token},
type: 'POST',
dataType: 'json',
data: 'id='+id,
success: function(response){
// console.log(response);
if(response=='yes')
table_archive.ajax.reload();
table_active.ajax.reload();
init_editable();
$('<div class="alert alert-success"><ul><li>'+response.msg+'</li></ul></div>').insertBefore('#msg');
alert_hide();
}
});
dialog.close();
}
}, {
label: 'No',
action: function(dialog) {
flg = 'no';
dialog.close();
}
}]
});
}
</script>
@endsection
@section('styles')
<!-- <link rel="stylesheet" href="/css/jquery.dataTables.min.css"> -->
<link rel="stylesheet" href="{{URL::asset('DataTables/datatables.min.css')}}">
<link rel="stylesheet" href="{{URL::asset('css/bootstrap-dialog.min.css')}}">
<link rel="stylesheet" href="{{URL::asset('css/select2.min.css')}}">
<link rel="stylesheet" href="{{URL::asset('css/bootstrap-multiselect.css')}}">
<link rel="stylesheet" href="{{URL::asset('css/bootstrap-editable.css')}}">
<link href="{{URL::asset('vendor/summernote/summernote.css')}}" rel="stylesheet">
<style>
.bot_10px{
margin-bottom: 10px;
}
.top-10px{
top: 10px;
position: relative;
}
.attachment {
background: #f4f4f4 none repeat scroll 0 0;
border-radius: 3px;
margin-right: 15px;
padding: 10px;
}
.pin-active{
color: #000;
}
.pin-active:hover{
color: #b5bbc8;
}
.pin-disabled{
color:#b5bbc8;
}
.pin-disabled:hover{
color:#000;
}
</style>
@endsection
<file_sep>/app/Http/routes.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::group(['middleware' => 'web'], function () {
Route::get('/', 'AdminController@getLogin');
Route::get('admin/login', 'AdminController@getLogin');
Route::post('admin/login', 'AdminController@postLogin');
Route::get('admin/logout', ['as'=>'admin.logout', 'uses' => 'AdminController@getLogout']);
Route::group(['prefix' => 'admin','middleware' => 'admin'], function () {
Route::get('dashboard', ['as'=>'admin.dashboard', 'uses' => 'AdminController@showDashboard']);
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('user', 'UserController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('role', 'RoleController');
Route::post('/update', ['as'=>'admin.role.update', 'uses' => 'RoleController@update']);
Route::get('role/delete/{id}', ['as'=>'admin.role.delete', 'uses' => 'RoleController@destroy']);
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('permissions', 'PermissionsController');
Route::get('/permissions_list', ['as'=>'admin.permissions.list', 'uses' => 'PermissionsController@ajaxDataIndex']);
Route::get('permission_del_ajax/{id}', ['as'=>'admin.permissions.del_ajax', 'uses' => 'PermissionsController@ajaxDelete']);
Route::post('/update', ['as'=>'admin.permissions.update', 'uses' => 'PermissionsController@update']);
});
// Admin Settings Routing
Route::group(['prefix'=>'settings','middleware' => ['role:admin']], function () {
Route::group(['prefix'=>'general'], function () {
Route::get('system', ['as'=>'admin.setting.general.system', 'uses' => 'SettingController@system']);
Route::post('system/save', ['as'=>'admin.setting.system.save', 'uses' => 'SettingController@systemSave']);
});
Route::group(['prefix'=>'staff'], function () {
Route::get('employees', ['as'=>'admin.setting.staff.employees','middleware' => ['permission:list_employee'], 'uses' => '\App\Modules\Employee\Http\Controllers\EmployeeController@index']);
Route::get('permissions', ['as'=>'admin.setting.permissions', 'uses' => 'SettingController@permissions']);
});
Route::get('/ticketing/statuses', ['as'=>'admin.setting.ticketing.statuses', 'uses' => '\App\Modules\Crm\Http\Controllers\TicketsStatus@index']);
Route::group(['prefix'=>'crm'], function () {
/******server vitual types settings***/
Route::get('asset_server_vitual_types', ['as'=>'admin.setting.crm.assets.asset_server_virtual_types','middleware' => ['permission:edit_customer'], 'uses' => 'SettingController@assetServerVTypesSettingsDisplay']);
Route::get('/list_server_virtual_types', ['as'=>'admin.setting.crm.assets.list_server_virtual_types','middleware' => ['permission:list_assets'], 'uses' => 'SettingController@listServerVirtualTypes']);
Route::post('/delete_server_virtual_type', ['as'=>'admin.setting.crm.assets.delete_server_virtual_type','middleware' => ['permission:list_assets'], 'uses' => 'SettingController@destroyServerVirtualType']);
Route::post('/create_server_virtual_type', ['as'=>'admin.setting.crm.assets.create_server_virtual_type','middleware' => ['permission:list_assets'], 'uses' => 'SettingController@createServerVirtualType']);
/******server roles settings***/
Route::get('asset_server_roles', ['as'=>'admin.setting.crm.assets.asset_server_roles','middleware' => ['permission:edit_customer'], 'uses' => 'SettingController@assetServerRoleSettingsDisplay']);
Route::get('/list_server_roles', ['as'=>'admin.setting.crm.assets.list_server_roles','middleware' => ['permission:list_assets'], 'uses' => 'SettingController@listServerRoles']);
Route::post('/delete_server_role', ['as'=>'admin.setting.crm.assets.delete_server_role','middleware' => ['permission:list_assets'], 'uses' => 'SettingController@destroyServerRole']);
Route::post('/create_server_role', ['as'=>'admin.setting.crm.assets.create_server_role','middleware' => ['permission:list_assets'], 'uses' => 'SettingController@createServerRole']);
/*****gmail settings***/
Route::get('gmail', ['as'=>'admin.setting.crm.integration.gmail','middleware' => ['permission:edit_customer'], 'uses' => 'SettingController@gmailSettingsDisplay']);
Route::post('/gmail_api_update', ['as'=>'admin.setting.crm.integration.gmail_api_update', 'uses' => 'SettingController@gmailApiUpdate']);
Route::get('/google_auth', ['as'=>'admin.setting.crm.integration.google_auth', 'uses' => 'SettingController@googleAuth']);
Route::post('/imap_store', ['as'=>'admin.setting.crm.integration.imap_store', 'uses' => 'SettingController@imapStore']);
Route::get('/imap', ['as'=>'admin.setting.crm.integration.imap', 'uses' => 'SettingController@imap']);
Route::post('/smtp_store', ['as'=>'admin.setting.crm.integration.smtp_store', 'uses' => 'SettingController@smtpStore']);
Route::get('/smtp', ['as'=>'admin.setting.crm.integration.smtp', 'uses' => 'SettingController@smtp']);
Route::get('slack', ['as'=>'admin.setting.crm.integration.slack','middleware' => ['permission:edit_customer'], 'uses' => 'SettingController@slackSettingsDisplay']);
Route::post('/slack_store', ['as'=>'admin.setting.crm.integration.slack_store','middleware' => ['permission:edit_customer'], 'uses' => 'SettingController@slackStore']);
Route::get('/slack_token_request', ['as'=>'admin.setting.crm.slack_token_request', 'uses' => 'SettingController@slackTokenRequest']);
Route::get('zoho', ['as'=>'admin.setting.crm.integration.zoho','middleware' => ['permission:edit_customer'], 'uses' => 'SettingController@zohoSettingsDisplay']);
Route::post('/zoho_store', ['as'=>'admin.setting.crm.integration.zoho_store','middleware' => ['permission:edit_customer'], 'uses' => 'SettingController@zohoStore']);
Route::get('/zoho_reset_token', ['as'=>'admin.setting.crm.integration.zoho_reset_token','middleware' => ['permission:edit_customer'], 'uses' => 'SettingController@resetAuthToken']);
Route::get('billingperiods', ['as'=>'admin.setting.crm.billingperiods', 'uses' => 'SettingController@billingPeriods']);
Route::post('billingperiods/delete', ['as'=>'admin.setting.crm.billingperiods.delete', 'uses' => 'SettingController@deleteBillingPeriod']);
Route::post('billingperiods/create', ['as'=>'admin.setting.crm.billingperiods.create','middleware' => ['permission:customer_billing_add'], 'uses' => 'SettingController@createBillingPeriod']);
Route::get('defaultrates', ['as'=>'admin.setting.crm.defaultrates', 'uses' => 'SettingController@defaultRates']);
Route::post('defaultrates/create', ['as'=>'admin.setting.crm.defaultrates.create','middleware' => ['permission:edit_customer'], 'uses' => 'SettingController@createDefaultRate']);
Route::post('defaultrates/delete', ['as'=>'admin.setting.crm.defaultrates.delete','middleware' => ['permission:delete_customer'], 'uses' => 'SettingController@deleteDefaultRate']);
Route::get('servicetypes', ['as'=>'admin.setting.crm.servicetypes', 'uses' => 'SettingController@serviceTypes']);
Route::post('servicetypes/create', ['as'=>'admin.setting.crm.servicetypes.create','middleware' => ['permission:edit_customer'], 'uses' => 'SettingController@createServiceType']);
Route::post('servicetypes/delete', ['as'=>'admin.setting.crm.servicetypes.delete','middleware' => ['permission:delete_customer'], 'uses' => 'SettingController@deleteServiceType']);
});
});
Route::group(['prefix'=>'settings','middleware' => ['role:admin|manager|technician']], function () {
Route::get('/', ['as'=>'admin.setting.all', 'uses' => 'SettingController@index']);
// Exit admin panel
Route::get('/exit', ['as'=>'admin.setting.exit', function () {
session(['panel' => 'agent']);
return redirect('admin/dashboard');
}]);
Route::post('/update_email_data', ['as'=>'admin.setting.update_email_data', 'uses' => 'SettingController@updateEmailData']);
Route::get('get_email_data', ['as'=>'admin.setting.get_email_data', 'uses' => 'SettingController@getEmailData']);
Route::post('/update_email_signature', ['as'=>'admin.setting.update_email_signature', 'uses' => 'SettingController@updateEmailSignature']);
Route::get('get_email_signature', ['as'=>'admin.setting.get_email_signature', 'uses' => 'SettingController@getEmailSignature']);
Route::get('get_user_devices', ['as'=>'admin.setting.get_user_devices', 'uses' => 'SettingController@getUserDevices']);
Route::get('delete_user_device/{id}', ['as'=>'admin.setting.delete_user_device', 'uses' => 'SettingController@deleteUserDevice']);
/****no longer been used***/
//Route::get('/imap', ['as'=>'admin.setting.imap', 'uses' => 'SettingController@imap']);
//Route::post('/imap_store', ['as'=>'admin.setting.imap_store', 'uses' => 'SettingController@imapStore']);
//Route::get('/smtp', ['as'=>'admin.setting.smtp', 'uses' => 'SettingController@smtp']);
// Route::post('/smtp_store', ['as'=>'admin.setting.smtp_store', 'uses' => 'SettingController@smtpStore']);
//Route::post('/gmail_api_update', ['as'=>'admin.setting.gmail_api_update', 'uses' => 'SettingController@gmailApiUpdate']);
//Route::get('/google_auth', ['as'=>'admin.setting.google_auth', 'uses' => 'SettingController@googleAuth']);
// Route::get('/slack_get', ['as'=>'admin.setting.slack_get', 'uses' => 'SlackController@getForm']);
//Route::post('/slack_store', ['as'=>'admin.setting.slack_store', 'uses' => 'SlackController@slackStore']);
Route::post('/tel_fax_update', ['as'=>'admin.setting.tel_fax_update', 'uses' => 'SettingController@telFaxUpdate']);
Route::get('/ajax/listroles', ['as'=>'admin.roles.ajax.list', 'uses' => 'RoleController@ajaxDataIndex']);
// Delete these no longer used
Route::post('/time_zone_update', ['as'=>'admin.setting.time_zone_update', 'uses' => 'SettingController@timeZoneUpdate']);
Route::post('update_date_time', ['as'=>'admin.setting.update_date_time', 'uses' => 'SettingController@updateDateTime']);
Route::get('/get_date_time', ['as'=>'admin.setting.get_date_time', 'uses' => 'SettingController@getDateTime']);
});
});
Route::get('/image/{folder}/{filename}', ['as'=>'get.image', 'uses' => 'ImageController@retrieveImage']);
Route::post('/image', ['as'=>'upload.image', 'uses' => 'ImageController@imageUpload']);
Route::get('/get_token', ['as'=>'get_token', 'uses' => 'SettingController@getToken']);
Route::get('/send_mail', ['as'=>'send_mail', 'uses' => 'TestEmailController@sendEmail']);
Route::get('/get_slack_token', ['as'=>'admin.setting.get_slack_token', 'uses' => 'SlackController@getToken']);
});
Route::group(['middleware' => ['api'],'prefix' => 'api'], function () {
Route::post('register', 'APIController@register');
Route::post('login', 'APIController@login');
Route::group(['middleware' => 'jwt-auth'], function () {
Route::post('get_user_details', 'APIController@get_user_details');
});
});<file_sep>/app/Modules/Crm/Http/CustomerAppointment.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class CustomerAppointment extends Model
{
/* public function assigned_tickets()
{
return $this->hasMany('App\Modules\Crm\Http\Ticket','created_by');
}*/
}
<file_sep>/public/phpmyadmin/libraries/php-gettext/gettext.php
../../../php/php-gettext/gettext.php<file_sep>/app/Modules/Crm/Http/Response.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class Response extends Model
{
public function responder()
{
return $this->belongsTo('App\Model\User', 'responder_id');
}
}
<file_sep>/app/Http/routes--.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
// Route::get('/', function () {
// return view('welcome');
// });
//Route::get('admin/dashboard','AdminController@showDashboard');
/*Route::get('admin', array('uses' => 'AdminController@showLogin'));*/
Route::get('/', 'AdminController@getLogin');
//Route::get('login', 'AdminController@getLogin');
Route::get('admin/login', 'AdminController@getLogin');
Route::post('admin/login', 'AdminController@postLogin');
//Route::get('admin/register', 'AdminController@getRegister');
//Route::post('admin/register', 'AdminController@postRegister');
Route::get('admin/logout', 'AdminController@getLogout');
Route::group(['prefix' => 'admin','middleware' => 'admin'], function () {
Route::get('dashboard', ['as'=>'admin.dashboard', 'uses' => 'AdminController@showDashboard']);
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('user', 'UserController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('role', 'RoleController');
Route::post('/update', ['as'=>'admin.role.update', 'uses' => 'RoleController@update']);
Route::get('role/delete/{id}', ['as'=>'admin.role.delete', 'uses' => 'RoleController@destroy']);
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('permissions', 'PermissionsController');
Route::get('/permissions_list', ['as'=>'admin.permissions.list', 'uses' => 'PermissionsController@ajaxDataIndex']);
Route::get('permission_del_ajax/{id}', ['as'=>'admin.permissions.del_ajax', 'uses' => 'PermissionsController@ajaxDelete']);
Route::post('/update', ['as'=>'admin.permissions.update', 'uses' => 'PermissionsController@update']);
});
/*
Route::group(['prefix'=>'config','middleware' => ['role:admin']], function(){
Route::get('/imap', ['as'=>'admin.config.imap', 'uses' => 'ConfigController@imap']);
Route::post('/imap_store', ['as'=>'admin.config.imap_store', 'uses' => 'ConfigController@imapStore']);
Route::get('/smtp', ['as'=>'admin.config.smtp', 'uses' => 'ConfigController@smtp']);
Route::post('/smtp_store', ['as'=>'admin.config.smtp_store', 'uses' => 'ConfigController@smtpStore']);
});*/
Route::group(['prefix'=>'settings','middleware' => ['role:admin']], function () {
Route::get('/all', ['as'=>'admin.setting.all', 'uses' => 'SettingController@index']);
Route::post('/update_email_data', ['as'=>'admin.setting.update_email_data', 'uses' => 'SettingController@updateEmailData']);
Route::get('get_email_data', ['as'=>'admin.setting.get_email_data', 'uses' => 'SettingController@getEmailData']);
Route::post('update_date_time', ['as'=>'admin.setting.update_date_time', 'uses' => 'SettingController@updateDateTime']);
Route::get('/get_date_time', ['as'=>'admin.setting.get_date_time', 'uses' => 'SettingController@getDateTime']);
Route::get('/imap', ['as'=>'admin.setting.imap', 'uses' => 'SettingController@imap']);
Route::post('/imap_store', ['as'=>'admin.setting.imap_store', 'uses' => 'SettingController@imapStore']);
Route::get('/smtp', ['as'=>'admin.setting.smtp', 'uses' => 'SettingController@smtp']);
Route::post('/smtp_store', ['as'=>'admin.setting.smtp_store', 'uses' => 'SettingController@smtpStore']);
Route::post('/gmail_api_update', ['as'=>'admin.setting.gmail_api_update', 'uses' => 'SettingController@gmailApiUpdate']);
});
Route::get('/image/{folder}/{filename}', ['as'=>'admin.get.image', 'uses' => 'ImageController@retrieveImage']);
Route::post('/image', ['as'=>'admin.upload.image', 'uses' => 'ImageController@imageUpload']);
});
Route::get('/get_token', ['as'=>'get_token', 'uses' => 'SettingController@getToken']);
/*Route::get('/get_token', ['as'=>'get_token', function(){
$request = Request::all();
dd($request['code']);
//dd($request->all());
}
]);*/
/*Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/register', 'Auth\AuthController@getRegister');
Route::post('auth/register', 'Auth\AuthController@postRegister');
Route::get('auth/logout', 'Auth\AuthController@getLogout');*/
<file_sep>/app/Modules/Crm/Http/routes_bkup-21-03-2017.php
<?php
/*
|--------------------------------------------------------------------------
| Module Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for the module.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
/*Route::group(['prefix' => 'crm'], function() {
Route::get('/', function() {
dd('This is the Crm module index page.');
});
});*/
Route::get('/user_files/{folder}/_thumb/{filename}', ['as'=>'get.user_files.thumb', 'uses' => 'FilemanagerController@retrieveThumb']);
Route::get('/user_files/{folder}/{filename}', ['as'=>'get.user_files.file', 'uses' => 'FilemanagerController@retrieveFile']);
Route::group(['prefix' => 'admin','middleware' => 'admin'], function () {
Route::group(['prefix' => 'crm','middleware' => ['role:admin|manager|technician']], function () {
Route::controller('/filemanager', 'FilemanagerController');
//Connection
Route::get('/ajax_get_active_customers', ['as'=>'admin.crm.ajax_get_active_customers','middleware' => ['permission:list_customer'], 'uses' => 'CrmController@listAjaxActiveCustomers']);
Route::get('/', ['as'=>'admin.crm.index','middleware' => ['permission:list_customer'], 'uses' => 'CrmController@index']);
Route::post('/show_custs', ['as'=>'admin.crm.show_custs','middleware' => ['permission:list_customer'], 'uses' => 'CrmController@setSessionShowCusts']);
Route::get('/data_index', ['as'=>'admin.crm.data_index','middleware' => ['permission:list_customer'], 'uses' => 'CrmController@ajaxDataIndex']);
Route::get('create', ['as'=>'admin.crm.create','middleware' => ['permission:add_customer'], 'uses' => 'CrmController@create']);
Route::post('/', ['as'=>'admin.crm.store','middleware' => ['permission:add_customer'], 'uses' => 'CrmController@store']);
Route::get('edit/{id}', ['as'=>'admin.crm.edit','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@edit']);
Route::get('show/{id}', ['as'=>'admin.crm.show','middleware' => ['permission:view_customer_detail'], 'uses' => 'CrmController@show']);
Route::delete('delete', ['as'=>'admin.crm.destroy','middleware' => ['permission:delete_customer'], 'uses' => 'CrmController@destroy']);
Route::put('/{id}', ['as'=>'admin.crm.update','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@update']);
Route::post('/ajax_data_load', ['as'=>'admin.crm.ajax.load_items','middleware' => ['permission:add_customer'], 'uses' => 'CrmController@ajaxDataLoad']);
Route::post('/ajax_add_product_tag', ['as'=>'admin.crm.ajax.add_p_tag','middleware' => ['permission:add_customer'], 'uses' => 'CrmController@ajaxAddProductTag']);
Route::get('/ajax_contacts_list/{id}', ['middleware' => ['permission:add_customer'], 'uses' => 'CrmController@ajaxGetSelectContacts']);
Route::get('search_customers', ['as'=>'admin.crm.search.customers','middleware' => ['permission:list_customer'], 'uses' => 'CrmController@searchCustomers']);
Route::get('search_locations', ['as'=>'admin.crm.search.locations','middleware' => ['permission:list_customer'], 'uses' => 'CrmController@searchLocations']);
Route::get('search_cust_contacts', ['as'=>'admin.crm.ajax.search.cust.contacts','middleware' => ['permission:list_customer'], 'uses' => 'CrmController@searchLocationContacts']);
/********************************************************* Customer info *****************************/
Route::get('/ajax_load_customer_info/{id}', ['as'=>'admin.crm.ajax.load_customer_info','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxLoadInfo']);
Route::post('/ajax_update_customer_info', ['as'=>'admin.crm.ajax.update_customer_info','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxUpdateInfo']);
Route::get('/ajax_refresh_info/{id}', ['as'=>'admin.crm.ajax.refresh_info','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxRefreshInfo']);
Route::post('/ajax_customers_contacts', ['as'=>'admin.crm.ajax.get_contacts','middleware' => ['permission:edit_customer'], 'uses' => 'TicketController@ajaxGetContacts']);
/********************************************************* Customer info *****************************/
/********************************************************* Locations *****************************/
Route::post('/ajax_load_location', ['as'=>'admin.crm.ajax.load_location','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxLoadLocation']);
Route::post('/ajax_update_location', ['as'=>'admin.crm.ajax.update_location','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxUpdateLocation']);
Route::post('/ajax_add_location', ['as'=>'admin.crm.ajax.add_location','middleware' => ['permission:add_customer'], 'uses' => 'CrmController@ajaxAddLocation']);
Route::get('/ajax_get_locations_list/{id}', ['as'=>'admin.crm.ajax.get_locations_list','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxGetLocationsList']);
Route::get('/ajax_list_locations/{id}', ['as'=>'admin.crm.ajax.list_locations','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxListLocation']);
Route::post('/ajax_del_location', ['as'=>'admin.crm.ajax.del_location','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxDeleteLocation']);
/********************************************************* Locations *****************************/
/********************************************************* contacts *****************************/
Route::post('/ajax_load_contact', ['as'=>'admin.crm.ajax.load_contact','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxLoadContact']);
Route::post('/ajax_update_contact', ['as'=>'admin.crm.ajax.update_contact','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxUpdateContact']);
Route::get('/ajax_refresh_contacts/{id}', ['as'=>'admin.crm.ajax.refresh_contacts','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxRefreshContacts']);
Route::post('/ajax_add_contact', ['as'=>'admin.crm.ajax.add_contact','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxAddContact']);
Route::post('/ajax_del_contact', ['as'=>'admin.crm.ajax.del_contact','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxDeleteContact']);
Route::get('/ajax_click_call/{id}', ['as'=>'admin.crm.ajax.click_call','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxClicktoCall']);
/********************************************************* contacts *****************************/
/********************************************************* service items *****************************/
Route::get('/list_service_items/{id}', ['as'=>'admin.crm.ajax.list_service_item','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxListServiceItem']);
Route::post('/ajax_load_service_item', ['as'=>'admin.crm.ajax.load_service_item','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxLoadServiceItem']);
Route::post('/ajax_update_service_item', ['as'=>'admin.crm.ajax.update_service_item','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxUpdateServiceItem']);
Route::get('/load_new_service_item/{id}', ['as'=>'admin.crm.ajax.load_new_service_item','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxLoadNewServiceItem']);
Route::post('/add_service_item', ['as'=>'admin.crm.ajax.add_service_item','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxAddServiceItem']);
Route::get('/ajax_del_sitem/{id}/{cid}', ['as'=>'admin.crm.ajax.del_sitem','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxDeleteServiceItem']);
/********************************************************* service items *****************************/
/********************************************************* rates *****************************/
Route::get('/list_rates/{id}', ['as'=>'admin.crm.ajax.list_rate','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxListRate']);
Route::get('/ajax_load_rate/{id}', ['as'=>'admin.crm.ajax.get_load_rate','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxLoadRate']);
Route::post('/ajax_update_rate', ['as'=>'admin.crm.ajax.update_rate','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxUpdateRate']);
Route::post('/ajax_add_rate', ['as'=>'admin.crm.ajax.add_rate','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxAddRate']);
Route::get('/ajax_del_rate/{id}/{sid}', ['as'=>'admin.crm.ajax.del_rate','middleware' => ['permission:edit_customer'], 'uses' => 'CrmController@ajaxDeleteRate']);
/********************************************************* rates *****************************/
/********************************************************* Ajax *****************************/
Route::get('/ajax_get_select_contacts/{id}', ['as'=>'admin.crm.ajax.get_select_contacts','middleware' => ['permission:edit_customer'], 'uses' => 'AjaxController@getSelect2Contacts']);
Route::get('/ajax_get_select_locations/{id}', ['as'=>'admin.crm.ajax.get_select_locations','middleware' => ['permission:edit_customer'], 'uses' => 'AjaxController@getSelect2Locations']);
Route::get('/ajax_get_select_techs', ['as'=>'admin.crm.ajax.get_select_techs','middleware' => ['permission:edit_customer'], 'uses' => 'AjaxController@getSelect2Techs']);
Route::post('/save_customer', ['as'=>'admin.crm.customer_save','middleware' => ['permission:edit_customer'], 'uses' => 'AjaxController@updateCustomer']);
Route::group(['prefix' => 'ticket'], function () {
Route::get('ajax_get_select_statuses', ['as'=>'admin.ticket.get_select_statuses','middleware' => ['permission:list_ticket'], 'uses' => 'AjaxController@getSelect2Statuses']);
Route::get('ajax_get_select_service_items/{id}', ['as'=>'admin.ticket.get_select_service_items','middleware' => ['permission:list_ticket'], 'uses' => 'AjaxController@getSelect2ServiceItems']);
});
Route::group(['prefix' => 'note'], function () {
Route::get('get_list/{id}', ['as'=>'admin.crm.note.list','middleware' => ['permission:list_note'], 'uses' => 'AjaxController@getCustomerNotes']);
Route::post('create', ['as'=>'admin.crm.note.create','middleware' => ['permission:create_note'], 'uses' => 'AjaxController@createCustomerNote']);
Route::get('handsontable', ['as'=>'admin.crm.note.handsontable', 'uses' => 'AjaxController@displayDataHtable']);
//Route::post('handsontable_save', ['as'=>'admin.crm.note.handsontable_save', 'uses' => 'AjaxController@saveDataHtable']);
});
Route::post('send_email', ['as'=>'admin.crm.email.send','middleware' => ['permission:create_note'], 'uses' => 'AjaxController@sendEmails']);
Route::post('add_ticket', ['as'=>'admin.crm.add.ticket','middleware' => ['permission:create_note'], 'uses' => 'TicketController@addTicket']);
Route::group(['prefix' => 'appointment'], function () {
Route::post('post_event', ['as'=>'admin.crm.appointment.post','middleware' => ['permission:create_note'], 'uses' => 'AppointmentController@postEvent']);
Route::post('update_event', ['as'=>'admin.crm.appointment.update','middleware' => ['permission:create_note'], 'uses' => 'AppointmentController@updateEvent']);
Route::post('delete_event', ['as'=>'admin.crm.appointment.delete','middleware' => ['permission:create_note'], 'uses' => 'AppointmentController@deleteEvent']);
Route::get('/get_appointment_by_id/{id}', ['as'=>'admin.crm.appointment.get_by_id','middleware' => ['permission:create_note'], 'uses' => 'AppointmentController@getAppointmentById']);
Route::get('edit/{id}/{cust_id}', ['as'=>'admin.crm.appointment.edit','middleware' => ['permission:create_note'], 'uses' => 'AppointmentController@editEvent']);
Route::get('/get_event_by_id/{id}', ['as'=>'admin.crm.appointment.get_event_by_id','middleware' => ['permission:create_note'], 'uses' => 'AppointmentController@getEventById']);
});
/*****************************Notes*************************/
Route::group(['prefix' => 'notes'], function () {
Route::get('/', ['as'=>'admin.crm.notes.index','middleware' => ['permission:list_notes'], 'uses' => 'NotesController@index']);
Route::get('/single/{id}', ['as'=>'admin.crm.note.single','middleware' => ['permission:list_notes'], 'uses' => 'NotesController@getNote']);
Route::get('/notes_dt_index_active', ['as'=>'admin.crm.notes.data_index_active','middleware' => ['permission:list_notes'], 'uses' => 'NotesController@DtIndexActive']);
Route::get('/notes_dt_index_archived', ['as'=>'admin.crm.notes.data_index_archived','middleware' => ['permission:list_notes'], 'uses' => 'NotesController@DtIndexArchived']);
Route::post('pin_status_change', ['as'=>'admin.crm.note.pin_status_change','middleware' => ['permission:create_note'], 'uses' => 'NotesController@changePinStatus']);
Route::post('archive_status_change', ['as'=>'admin.crm.note.archive_status_change','middleware' => ['permission:create_note'], 'uses' => 'NotesController@changeArchiveStatus']);
Route::post('delete', ['as'=>'admin.crm.note.delete','middleware' => ['permission:create_note'], 'uses' => 'NotesController@delete']);
Route::post('update_editable', ['as'=>'admin.crm.ajax.note.update_editable','middleware' => ['permission:create_note'], 'uses' => 'NotesController@updateEditable']);
Route::post('update_note', ['as'=>'admin.crm.ajax.note.update','middleware' => ['permission:create_note'], 'uses' => 'NotesController@updateNote']);
Route::get('notes_json/{type}', ['as'=>'admin.crm.notes.json','middleware' => ['permission:list_notes'], 'uses' => 'NotesController@getNotesJson']);
Route::post('save_excel', ['as'=>'admin.crm.ajax.note.save_excel','middleware' => ['permission:create_note'], 'uses' => 'NotesController@saveDataExcel']);
Route::post('update_excel', ['as'=>'admin.crm.ajax.note.update_excel','middleware' => ['permission:create_note'], 'uses' => 'NotesController@updateDataExcel']);
Route::get('excel_notes_json/{type}', ['as'=>'admin.crm.excel.notes.json','middleware' => ['permission:list_notes'], 'uses' => 'NotesController@getExcelNotesJson']);
Route::get('get_excel_note/{id}', ['as'=>'admin.crm.excel.get.note','middleware' => ['permission:list_notes'], 'uses' => 'NotesController@getExcelData']);
});
/********************************End Notes****************/
/********************************************************* Angular *****************************/
Route::group(['prefix' => 'api/v1/contacts'], function () {
Route::get('/{id}', ['middleware' => ['permission:view_customer_detail'], 'uses' => 'CrmController@angularList']);
//Route::post('create', ['as'=>'admin.crm.note.create','middleware' => ['permission:create_note'], 'uses' => 'AjaxController@createCustomerNote']);
});
/********************************************************* Angular *****************************/
/********************************************************* Zoho *****************************/
Route::group(['prefix' => 'api/v1/invoices'], function () {
Route::get('/{id}/{status?}', ['as'=>'admin.crm.api.invoices','middleware' => ['permission:zoho_view_invoices'], 'uses' => 'ZohoController@apiGetInvoices']);
});
Route::group(['prefix' => 'api/v1/recurringinvoices'], function () {
Route::get('/{id}/{status?}', ['as'=>'admin.crm.api.recurringinvoices','middleware' => ['permission:zoho_view_invoices'], 'uses' => 'ZohoController@apiGetRecurringInvoices']);
});
Route::group(['prefix' => 'api/v1/accountstanding'], function () {
Route::get('/{id}', ['as'=>'admin.crm.api.accountstanding','middleware' => ['permission:zoho_admin'], 'uses' => 'ZohoController@apiGetCustomerStanding']);
});
Route::get('/ajax_customer_export_zoho/{id}', ['as'=>'admin.crm.ajax.customer_export_zoho','middleware' => ['permission:edit_customer'], 'uses' => 'ZohoController@ajaxExportContact']);
Route::get('/zoho_credentials', ['as'=>'admin.crm.zoho_credentials','middleware' => ['permission:edit_customer'], 'uses' => 'ZohoController@getForm']);
Route::post('/zoho_store', ['as'=>'admin.crm.zoho_store','middleware' => ['permission:edit_customer'], 'uses' => 'ZohoController@zohoStore']);
Route::get('/zoho_reset_token', ['as'=>'admin.crm.zoho_reset_token','middleware' => ['permission:edit_customer'], 'uses' => 'ZohoController@resetAuthToken']);
Route::get('/zoho_get_contacts', ['as'=>'admin.crm.zoho_get_contacts','middleware' => ['permission:edit_customer'], 'uses' => 'ZohoController@getContacts']);
Route::get('/zoho_get_expenses/{id}', ['as'=>'admin.crm.zoho_get_expenses','middleware' => ['permission:edit_customer'], 'uses' => 'ZohoController@getExpense']);
/********************************************************* Zoho *****************************/
//default rates
Route::get('/list_default_rates', ['as'=>'admin.crm.default_rates', 'uses' => 'DefaultRates@index']);
Route::get('/add_default_rate', ['as'=>'admin.crm.default_rate.add','middleware' => ['permission:edit_customer'], 'uses' => 'DefaultRates@create']);
Route::post('/add_default_rate', ['as'=>'admin.crm.default_rate.store','middleware' => ['permission:edit_customer'], 'uses' => 'DefaultRates@store']);
Route::get('rate_delete/{id}', ['as'=>'admin.crm.default_rate.destroy','middleware' => ['permission:delete_customer'], 'uses' => 'DefaultRates@destroy']);
Route::group(['prefix' => 'ticket'], function () {
Route::get('/', ['as'=>'admin.ticket.index','middleware' => ['permission:list_ticket'], 'uses' => 'TicketController@index']);
//Route::get('/by_cust_id/{id}', ['as'=>'admin.ticket.index_by_cust_id','middleware' => ['permission:list_ticket'], 'uses' => 'TicketController@index']);
Route::get('/ajax_ticket/{id}', ['as'=>'admin.ticket.ajax_ticket','middleware' => ['permission:list_ticket'], 'uses' => 'TicketController@ajaxGetTicketById']);
Route::post('/', ['as'=>'admin.ticket.index_post','middleware' => ['permission:list_ticket'], 'uses' => 'TicketController@index']);
//Route::get('/data_index', ['as'=>'admin.ticket.data_index','middleware' => ['permission:list_ticket'], 'uses' => 'TicketController@ajaxDataIndex']);
//Route::get('/data_index_by_cust/{id}', ['as'=>'admin.ticket.data_index_by_cust','middleware' => ['permission:list_ticket'], 'uses' => 'TicketController@ajaxDataIndex']);
Route::get('create', ['as'=>'admin.ticket.create','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@create']);
Route::post('create', ['as'=>'admin.ticket.store','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@store']);
Route::get('list_own', ['as'=>'admin.ticket.list_own','middleware' => ['permission:list_assigned_ticket'], 'uses' => 'TicketController@listOwn']);
Route::get('show/{id}', ['as'=>'admin.ticket.show','middleware' => ['permission:list_ticket'], 'uses' => 'TicketController@show']);
Route::get('ajax_get_service_items/{id}', ['as'=>'admin.ticket.ajax_get_service_items','middleware' => ['permission:create_ticket'], 'uses' => 'CrmController@ajaxGetServiceItems']);
Route::post('upload', ['as'=>'admin.ticket.upload','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@ajaxUploadImage']);
Route::post('ajax_del_img', ['as'=>'admin.ticket.ajax_del_img','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@ajaxDeleteImage']);
Route::post('add_response', ['as'=>'admin.ticket.add_response','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@addResponse']);
Route::get('getEmails', ['as'=>'admin.ticket.get_emails','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@readGmail']);
Route::delete('delete', ['as'=>'admin.ticket.destroy','middleware' => ['permission:customer_service_type_delete'], 'uses' => 'TicketController@destroy']);
Route::post('/multi_delete', ['as'=>'admin.crm.ajax.ticket_multi_delete','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@destroyMultiple']);
//Route::post('/',['as'=>'admin.ticket.store','middleware' => ['permission:customer_service_type_add'], 'uses' => 'TicketController@store']);
Route::post('assign_users', ['as'=>'admin.crm.ajax.ticket_assign_users','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@ajaxAssignUsers']);
Route::post('assign_multi_users', ['as'=>'admin.crm.ajax.multi_ticket_assign_users','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@ajaxAssignUsersMultiple']);
Route::get('delete_user_assigned/{uid}/{tid}', ['as'=>'admin.crm.ajax.ticket_delete_assigned_user','middleware' => ['permission:customer_service_type_delete'], 'uses' => 'TicketController@ajaxDeleteAssignedUser']);
Route::get('delete_customer_assigned/{tid}', ['as'=>'admin.crm.ajax.ticket_delete_assigned_customer','middleware' => ['permission:customer_service_type_delete'], 'uses' => 'TicketController@ajaxDeleteAssignedCustomer']);
Route::post('status_priority', ['as'=>'admin.crm.ajax.ticket_priority_status','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@ajaxUpdateStatusPriority']);
Route::post('update_title', ['as'=>'admin.crm.ajax.update_title','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@ajaxUpdateTitle']);
Route::post('multi_status', ['as'=>'admin.crm.ajax.multi_ticket_status','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@ajaxUpdateStatusMultiple']);
Route::post('multi_priority', ['as'=>'admin.crm.ajax.multi_ticket_priority','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@ajaxUpdatePriorityMultiple']);
Route::post('assign_customer', ['as'=>'admin.crm.ajax.ticket_assign_customer','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@ajaxAssignCustomer']);
Route::get('search_tickets', ['as'=>'admin.crm.ajax.search.tickets','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@searchTickets']);
});
Route::group(['prefix' => 'ticketstatus'], function () {
Route::get('/', ['as'=>'admin.ticket.status.index','middleware' => ['permission:list_ticket_status'], 'uses' => 'TicketsStatus@index']);
Route::get('create', ['as'=>'admin.ticket.status.create','middleware' => ['permission:create_ticket_status'], 'uses' => 'TicketsStatus@create']);
Route::get('edit/{id}', ['as'=>'admin.ticket.status.edit','middleware' => ['permission:create_ticket_status'], 'uses' => 'TicketsStatus@edit']);
//Route::post('create', ['as'=>'admin.ticket.store','middleware' => ['permission:create_ticket'], 'uses' => 'TicketController@store']);
Route::post('store', ['as'=>'admin.ticket.status.store','middleware' => ['permission:create_ticket_status'], 'uses' => 'TicketsStatus@store']);
Route::post('/update', ['as'=>'admin.ticket.status.update','middleware' => ['permission:create_ticket_status'], 'uses' => 'TicketsStatus@update']);
Route::get('/status_list', ['as'=>'admin.tickets.status.list', 'uses' => 'TicketsStatus@index']);
Route::get('delete_ticket_status/{id}', ['as'=>'admin.tickets.status.delete', 'middleware' => ['permission:delete_ticket_status'],'uses' => 'TicketsStatus@ajaxDelete']);
});
Route::group(['prefix' => 'service'], function () {
Route::get('/', ['as'=>'admin.service_item.index','middleware' => ['permission:customer_service_type_list'], 'uses' => 'ServiceItemsController@index']);
Route::get('create', ['as'=>'admin.service_item.create','middleware' => ['permission:customer_service_type_add'], 'uses' => 'ServiceItemsController@create']);
Route::get('delete/{id}', ['as'=>'admin.service_item.destroy','middleware' => ['permission:customer_service_type_delete'], 'uses' => 'ServiceItemsController@destroy']);
Route::post('/', ['as'=>'admin.service_item.store','middleware' => ['permission:customer_service_type_add'], 'uses' => 'ServiceItemsController@store']);
});
Route::group(['prefix' => 'billing'], function () {
Route::get('/', ['as'=>'admin.billing.index','middleware' => ['permission:customer_billing_list'], 'uses' => 'BillingPeriodsController@index']);
//Route::get('create', ['as'=>'admin.billing.create','middleware' => ['permission:customer_billing_add'], 'uses' => 'BillingPeriodsController@create']);
Route::get('delete/{id}', ['as'=>'admin.billing.destroy','middleware' => ['permission:customer_billing_delete'], 'uses' => 'BillingPeriodsController@destroy']);
Route::post('/', ['as'=>'admin.billing.store','middleware' => ['permission:customer_billing_add'], 'uses' => 'BillingPeriodsController@store']);
});
// Calendar
Route::group(['prefix' => 'calendar'], function () {
Route::get('eventlist', ['as'=>'admin.crm.calendar.eventlist','middleware' => ['permission:view_customer_detail'], 'uses' => 'CrmController@ajaxCalGetEvents']);
});
Route::get('contacts_by_loc/{loc_id}', ['as'=>'admin.crm.contacts_by_loc','middleware' => ['permission:customer_service_type_add'], 'uses' => 'TicketController@getContactsByLoc']);
});
//Route::resource('/crm','EmployeeController');
//Route::resource('/raise','RaiseController');
//Route::get('calander','EmployeeController@googleCalander');
});
<file_sep>/app/Modules/Vendor/Http/Controllers/VendorController.php
<?php
namespace App\Modules\Vendor\Http\Controllers;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Modules\Crm\Http\Customer;
use App\Modules\Crm\Http\CustomerLocation;
use Datatables;
use App\Modules\Vendor\Http\Vendor;
use App\Modules\Vendor\Http\VendorContact;
use App\Modules\Vendor\Http\VendorCustomer;
//use App\Modules\Vendor\Http\VendorCustomerLocation;
use App\Modules\Assets\Http\KnowledgePassword;
use App\Modules\Assets\Http\Tag;
use App\Model\Role;
use App\Model\User;
use Illuminate\Support\Facades\DB;
use Auth;
use Mail;
use URL;
use Session;
use App\Model\Config;
class VendorController extends Controller
{
public function index()
{
$customers_obj = Customer::with(['locations','locations.contacts'])->where('is_active', 1)->get();
//$asset_roles_obj = AssetRole::all();
$customers = [];
if ($customers_obj->count()) {
foreach ($customers_obj as $customer) {
$customers[$customer->id]=$customer->name.'('.$customer->email_domain.')';
//dd($user->id);
}
}
//dd($locations);
return view('vendor::index', compact('customers'));
//return "Controller Index";
}
function vendorsIndex($id = null)
{
$global_date = $this->global_date;
if (!empty(Session::get('cust_id'))) {
$vendors = Vendor::with(['customers'])->whereHas('customers', function ($query) {
$query->where('customer_id', Session::get('cust_id'));
});
} else {
$vendors = Vendor::orderBy('created_at', 'desc')->get();
//dd($vendors);
}
//dd($vendors->get());
return Datatables::of($vendors)
->addColumn('action', function ($vendor) {
if (!empty(Session::get('cust_id'))) {
$return = '<div class="btn-group">';
if (!empty(Session::get('cust_id'))) {
$return .= '<button type="button" class="btn btn-xs edit "
data-toggle="modal" data-id="'.Session::get('cust_id').'" data-vendor_id="'.$vendor->id.'"id="modaal" data-target="#modal-edit-customer">
<i class="fa fa-edit " ></i></button>';
} else {
$return .= '<button type="button" class="btn btn-xs edit "
data-toggle="modal" data-id="'.$vendor->id.'" id="modaal" data-target="#modal-edit-customer">
<i class="fa fa-edit " ></i></button>';
}
$return .=' <button type="button" class="btn btn-danger btn-xs"
data-toggle="modal" data-id="'.$vendor->customers[0]->pivot->id.'" id="modaal" data-target="#modal_vendor_customer_unlink">
<i class="fa fa-times-circle"></i></button></div>';
$return .= '</div>';
return $return;
}
})
->editColumn('created_at', function ($vendor) use ($global_date) {
return date($global_date, strtotime($vendor->created_at));
})
->addColumn('customer', function ($vendor) use ($global_date) {
$return ='';
foreach ($vendor->customers as $customer) {
$return .=' <button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span>'.$customer->name.'</span>
</button>';
}
return $return ;
})
->setRowId('id')
->make(true);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$customers_obj = Customer::with(['locations','locations.contacts'])->where('is_active', 1)->get();
//$asset_roles_obj = AssetRole::all();
$customers = [];
if ($customers_obj->count()) {
foreach ($customers_obj as $customer) {
$customers[$customer->id]=$customer->name.'('.$customer->email_domain.')';
//dd($user->id);
}
}
return view('vendor::add', compact('customers'));
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//dd($request->all());
//dd(json_decode($request->cust_arr));
$contact_arr = json_decode($request->contact_arr);
$cust_arr = json_decode($request->cust_arr);
$business_hours_arr = json_decode($request->business_hours);
//dd(count($contact_arr));
if ($request->vendor_flag=='add') {
$this->validate(
$request,
[
'name' => 'required',
//'customer' => 'required',
]
);
$vendor = new Vendor;
$vendor->name = $request->name ;
$vendor->phone_number = $request->phone ;
$vendor->dailing_instructions = $request->dialing_instructions ;
$vendor->website = $request->website;
$vendor->zip = $request->zip ;
$vendor->address = $request->address ;
$vendor->city = $request->city ;
$vendor->state = $request->state ;
$vendor->business_hours = $request->business_hours ;
$vendor->save();
/*
$kpass = new KnowledgePassword();
$kpass->login = $request->user_name;
$kpass->password = $<PASSWORD>;
$kpass->customer_id = $request->customer;
$asset->password()->save($kpass);*/
if (count($contact_arr)>0) {
foreach ($contact_arr as $contact) {
$vandor_contact = new VendorContact;
$vandor_contact->f_name = $contact->f_name;
$vandor_contact->l_name = $contact->l_name;
$vandor_contact->email = $contact->email;
$vandor_contact->title = $contact->title_;
$vandor_contact->phone = $contact->contact_phone;
$vandor_contact->mobile = $contact->contact_mobile;
$vendor->contacts()->save($vandor_contact);
}
}
foreach ($cust_arr as $customer) {
$customer_ = Customer::with(['vendors'])->where('id', $customer->customer_selected_id)->first();
//$customer->vendors()->detach();
$vendor_customer = [];
$vendor_customer['auth_contact_name']= $customer->auth_name;
$vendor_customer['phone_number'] = $customer->phone;
$vendor_customer['account_number'] = $customer->account_num;
$vendor_customer['portal_url'] = $customer->portal_url;
//$vendor_customer['portal_username'] = $customer->username;
//$vendor_customer['portal_password'] = $<PASSWORD>;
$vendor_customer['notes'] = $customer->notes;
//$vandor_customer->customer_id = $customer->customer_selected_id;
$vendor_cust_arr = [];
$vendor_cust_arr[$vendor->id] = $vendor_customer;
//$vandor_customer->customer_id = $customer->customer_selected_id;
//dd($vendor_customer);
/*$vpass = new KnowledgePassword();
$vpass->login = $customer->user_name;
$vpass->password = $<PASSWORD>;
$vpass->customer_id = $customer->customer_selected_id;
$vendor->password()->save($vpass);*/
$customer_->vendors()->attach($vendor_cust_arr);
//}
//$vendor->customers()->attach($customer->customer_selected_id,$vendor_customer);
}
}
if ($request->vendor_flag=='attach') {
$vendor = Vendor::find($request->vendor_id);
//$vendor_ids = explode(',', $request->vendor_id);
if (count($contact_arr)>0) {
foreach ($contact_arr as $contact) {
$vandor_contact = new VendorContact;
$vandor_contact->f_name = $contact->f_name;
$vandor_contact->l_name = $contact->l_name;
$vandor_contact->email = $contact->email;
$vandor_contact->title = $contact->title_;
$vandor_contact->phone = $contact->contact_phone;
$vandor_contact->mobile = $contact->contact_mobile;
$vendor->contacts()->save($vandor_contact);
}
}
foreach ($cust_arr as $customer) {
$customer_ = Customer::with(['vendors'])->where('id', $customer->customer_selected_id)->first();
//$customer->vendors()->detach($vendor);
$vendor_customer = [];
$vendor_customer['auth_contact_name']= $customer->auth_name;
$vendor_customer['phone_number'] = $customer->phone;
$vendor_customer['account_number'] = $customer->account_num;
$vendor_customer['portal_url'] = $customer->portal_url;
$vendor_customer['portal_username'] = $customer->username;
$vendor_customer['portal_password'] = $<PASSWORD>;
$vendor_customer['notes'] = $customer->notes;
//$vandor_customer->customer_id = $customer->customer_selected_id;
$vendor_cust_arr = [];
$vendor_cust_arr[$request->vendor_id] = $vendor_customer;
/*$vpass = new KnowledgePassword();
$vpass->login = $customer->user_name;
$vpass->password = $<PASSWORD>;
$vpass->customer_id = $customer->customer_selected_id;
$vendor->password()->save($vpass);*/
$customer_->vendors()->attach($vendor_cust_arr);
}
}
$arr['success'] = 'yes';
$arr['msg'] = 'Vendor added successfully';
return json_encode($arr);
//return redirect()->route('admin.vendors.index');
//
}
public function destroy(Request $request)
{
$id = $request->vendor_id;
$vendor = Vendor::where('id', $id)->first();
$vendor->contacts()->delete();
$vendor->customers()->detach();
// $customer->locations()->delete();
$vendor->delete();
return redirect()->route('admin.vendors.index');
}
function updateInfo(Request $request)
{
$this->validate(
$request,
[
'name' => 'required',
//'customer' => 'required',
]
);
$business_hours_arr = json_decode($request->business_hours);
$vendor = Vendor::find($request->vendor_id);
$vendor->name = $request->name ;
$vendor->phone_number = $request->phone ;
$vendor->dailing_instructions = $request->dialing_instructions ;
$vendor->website = $request->website;
$vendor->zip = $request->zip ;
$vendor->address = $request->address ;
$vendor->city = $request->city ;
$vendor->state = $request->state ;
$vendor->business_hours = $request->business_hours ;
$vendor->save();
$arr['success'] = 'Vendor info updated successfully';
return json_encode($arr);
exit;
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//dd( $dd );
$date_format = Config::where('title', 'date_format')->first();
// $vendor = Vendor::with(['customers'=>function($query){
// $query->join('customer_locations','')->wherePivot('location_id','=','customer_locations.id');
// },'contacts'])->where('id',$id)->first();
//$vendor = Vendor::with(['customers','customers.locations.vend_cust_loc','contacts'])->where('id',$id)->get();
$vendor = Vendor::with(['customers'])->where('id', $id)->first();
//dd($vendor);
$customers_obj = Customer::with(['locations','locations.contacts'])->where('is_active', 1)->get();
//$asset_roles_obj = AssetRole::all();
$customers = [];
if ($customers_obj->count()) {
foreach ($customers_obj as $customer) {
$customers[$customer->id]=$customer->name.'('.$customer->email_domain.')';
//dd($user->id);
}
}
//
return view('vendor::show', compact('vendor', 'date_format', 'customers'));
}
public function ajaxDetails($id)
{
$cusid = Session::get('cust_id');
/*$vendor = DB::table('customer_vendor AS cv')
->select(DB::raw('cv.customer_id, cv.vendor_id, v.id, v.name as v_name,
v.phone_number as v_phone, v.dailing_instructions as v_dialins, v.website as v_website,
v.address as v_address, v.city as v_city, v.state as v_state, v.zip as v_zip,
v.business_hours as v_hours, cv.location_id, l.id, cv.auth_contact_name as cv_name,
cv.phone_number as cv_phone, cv.account_number as cv_acctnum, cv.portal_url as cv_portal,
cv.portal_username as cv_username, cv.portal_password as cv_pass, cv.notes, l.location_name,
l.address as location_address, l.city as location_city, l.state as location_state,
l.zip as location_zip, l.phone as location_phone'))
->join('vendors AS v', 'cv.vendor_id', '=', 'v.id')
->join('customer_locations as l', 'cv.location_id', '=', 'l.id')
->where('cv.customer_id','=',$cusid)->first();*/
/* $vendor = DB::table('customer_vendor AS cv')
->select('cv.*')
->join('vendors AS v', 'cv.vendor_id', '=', 'v.id')
->join('customer_locations as l', 'cv.location_id', '=', 'l.id')
->where('cv.customer_id','=',$cusid)->first();*/
// $vendor = Vendor::with(
// ['customers'=>
// function($query) use($cusid) {
// $query->wherePivot('customer_id','=',$cusid);
// },
// 'vend_cust_loc',
// 'password'=>
// function($query) use($cusid) {
// $query->where('customer_id','=',$cusid);
// }
// ])->where('id',$id)->first();
$vendor = Vendor::with('vendorCustomerLocations.customer', 'vendorCustomerLocations.location')->where('id', $id)->first();
if (count($vendor->vendorCustomerLocations->first()->customer->where('id', $cusid))) {
$customer = $vendor->vendorCustomerLocations->first()->customer->where('id', $cusid)->first();
} else {
$customer = null;
}
$location = $vendor->vendorCustomerLocations->first()->location;
return view('vendor::detail_partial', compact('customer', 'location', 'vendor'));
}
public function addContact(Request $request)
{
$this->validate(
$request,
[
'f_name' => 'required',
//'customer' => 'required',
]
);
$vandor_contact = new VendorContact;
$vandor_contact->vendor_id = $request->vendor_id;
$vandor_contact->f_name = $request->f_name;
$vandor_contact->l_name = $request->l_name;
$vandor_contact->email = $request->email;
$vandor_contact->title = $request->title;
$vandor_contact->phone = $request->contact_phone;
$vandor_contact->mobile = $request->contact_mobile;
$vandor_contact->save();
$arr['success'] = 'Contact Added successfully';
return json_encode($arr);
exit;
}
function editContact($id)
{
$contact = VendorContact::find($id);
$arr['contact'] = $contact;
return json_encode($arr);
exit;
}
public function updateContact(Request $request)
{
$this->validate(
$request,
[
'f_name' => 'required',
//'customer' => 'required',
]
);
$vandor_contact = VendorContact::find($request->cntct_id);
$vandor_contact->vendor_id = $request->vendor_id;
$vandor_contact->f_name = $request->f_name;
$vandor_contact->l_name = $request->l_name;
$vandor_contact->email = $request->email;
$vandor_contact->title = $request->title;
$vandor_contact->phone = $request->contact_phone;
$vandor_contact->mobile = $request->contact_mobile;
$vandor_contact->save();
$arr['success'] = 'Contact updated successfully';
return json_encode($arr);
exit;
}
function destroyContact(Request $request)
{
$contact = VendorContact::find($request->contact_id);
$contact->delete();
$arr['success'] = 'Contact deleted successfully';
return json_encode($arr);
exit;
}
public function addCustomer(Request $request)
{
$this->validate(
$request,
[
'customer_id' => 'required',
//'customer' => 'required',
]
);
$vendor_customer = new VendorCustomer;
$vendor_customer->auth_contact_name = $request->auth_contact_name;
$vendor_customer->vendor_id = $request->vendor_id;
$vendor_customer->customer_id = $request->customer_id;
$vendor_customer->location_id = $request->customer_location_id;
$vendor_customer->phone_number = $request->cust_phone;
$vendor_customer->account_number = $request->account_number;
$vendor_customer->portal_url = $request->portal_url;
$vendor_customer->portal_username = $request->cust_user_name;
$vendor_customer->portal_password = $<PASSWORD>;
$vendor_customer->notes = $request->customer_notes;
$vendor_customer->save();
$arr['success'] = 'Customer Added successfully';
return json_encode($arr);
exit;
}
function editCustomer($id)
{
$customer_vendor = VendorCustomer::where('vendor_id', $id)->where('customer_id', Session::get('cust_id'))->first();
//dd($customer_vendor);
$vendor = Vendor::find($customer_vendor->vendor_id)->password()->where('customer_id', $customer_vendor->customer_id)->first();
// dd($vendor);
$arr['customer'] = $customer_vendor;
$arr['vendor'] = $vendor;
return json_encode($arr);
exit;
}
public function updateCustomer(Request $request)
{
// dd($request->all());
$this->validate(
$request,
[
'customer_id' => 'required',
//'customer' => 'required',
]
);
$vendor_customer = VendorCustomer::where('customer_id', $request->customer_id)->where('vendor_id', $request->vendor_id)->first();
$vendor_customer->auth_contact_name = $request->auth_contact_name;
$vendor_customer->vendor_id = $request->vendor_id;
$vendor_customer->customer_id = $request->customer_id;
$vendor_customer->phone_number = $request->cust_phone;
$vendor_customer->location_id = $request->customer_location_id;
$vendor_customer->account_number = $request->account_number;
$vendor_customer->portal_url = $request->portal_url;
//$vendor_customer->portal_username = $request->cust_user_name;
//$vendor_customer->portal_password = $request->cust_password;
$vendor_customer->notes = $request->customer_notes;
$vendor_customer->save();
/************************** password update*******************/
$kpass = KnowledgePassword::where('customer_id', $request->customer_id)->where('vendor_id', $request->vendor_id)->first();
if ($kpass) {
if ($request->cust_user_name !='' && $request->cust_password!='') {
$kpass->login = $request->cust_user_name;
$kpass->password = $request->cust_password;
$kpass->update();
} else {
$kpass->delete();
}
} else {
$tag = Tag::firstOrCreate(['title' => 'vendor']);
$kpass = new KnowledgePassword();
$kpass->login = $request->cust_user_name;
$kpass->password = $request->cust_password;
$kpass->customer_id = $request->customer_id;
$kpass->vendor_id = $request->vendor_id;
//password atttachment with vendor
$kpass->save();
//tags attachment with password
$kpass->tags()->sync([$tag->id]);
}
/************************** password update*******************/
$arr['success'] = 'Customer Updated successfully';
return json_encode($arr);
exit;
}
function destroyCustomer(Request $request)
{
$customer = VendorCustomer::find($request->customer_id);
$customer->delete();
$arr['success'] = 'Customer deleted successfully';
return json_encode($arr);
exit;
}
function unlinkCustomer(Request $request)
{
$customer = VendorCustomer::find($request->id);
//dd( $customer);
$pass = KnowledgePassword::where('customer_id', $customer->customer_id)->where('vendor_id', $customer->vendor_id)->first();
/*dd($pass);*/
if ($pass) {
$pass->delete();
}
$customer->delete();
$arr['success'] = 'Customer unlinked successfully';
return json_encode($arr);
exit;
}
function refreshContacts($id)
{
$vendor = Vendor::with(['contacts'])->where('id', $id)->first();
$date_format = Config::where('title', 'date_format')->first();
return view('vendor::show.contact.ajax_refresh_contacts', compact('vendor', 'date_format'))->render();
}
function refreshCustomers($id)
{
$vendor = Vendor::with(['customers'])->where('id', $id)->first();
$date_format = Config::where('title', 'date_format')->first();
return view('vendor::show.customer.ajax_refresh_customers', compact('vendor', 'date_format'))->render();
}
function refreshVendorinfo($id)
{
$vendor = Vendor::find($id);
$date_format = Config::where('title', 'date_format')->first();
$data['vendor_left_info'] = view('vendor::show.info.vendor_top_left_info', compact('vendor', 'date_format'))->render();
$data['vendor_right_info'] = view('vendor::show.info.vendor_top_right_info', compact('vendor', 'date_format'))->render();
$data['business_hours'] = html_entity_decode($vendor->business_hours);
return $data;
}
function searchVendorContacts(Request $request)
{
if ($request->v_contact) {
$vendors_contacts = Vendor::with(['contacts'=>function ($query) use ($request) {
$query->where('f_name', 'like', '%'.$request->v_contact.'%')->orWhere('l_name', 'like', '%'.$request->v_contact.'%');
}])->get();
//dd($vendors_contacts);
$vendors = Vendor::where('name', 'like', '%'.$request->v_contact.'%')->get();
$contacts = [];
foreach ($vendors_contacts as $vendor_contacts) {
foreach ($vendor_contacts->contacts as $vend_contact) {
$contacts[] = ['id'=>$vendor_contacts->id,
'vend_contact'=>$vend_contact->f_name.' '.$vend_contact->l_name.' ('.$vendor_contacts->name.')'];
}
}
foreach ($vendors as $vendor) {
$contacts[] = ['id'=>$vendor->id,
'vend_contact'=>$vendor->name];
}
echo json_encode([
"status" => true,
"error" => null,
"data" => [
"vend_contacts" => $contacts
]
]);
} else {
echo json_encode([
"status" => true,
"error" => null,
"data" => [
"vend_contacts" => []
]
]);
}
}
function addVendorForCustomer()
{
$customers_obj = Customer::with(['locations','locations.contacts'])->where('is_active', 1)->get();
$customers = [];
if ($customers_obj->count()) {
foreach ($customers_obj as $customer) {
$customers[$customer->id]=$customer->name.'('.$customer->email_domain.')';
//dd($user->id);
}
}
$current_customer = false;
$current_customer_locations = [];
$current_selected_vendors =[];
if (!empty(Session::get('cust_id'))) {
$current_customer = Customer::with(['locations','locations.contacts','vendors'])->where('is_active', 1)->where('id', Session::get('cust_id'))->first();
if ($current_customer == null) {
dd("Customer is marked inactive, please activate the customer.");
}
//$json = '[';
if ($current_customer->vendors) {
foreach ($current_customer->vendors as $c_vendor) {
//$json.='{id:'.$c_vendor->id.', text:'.$c_vendor->name.'},';
$current_selected_vendors[] =['id'=>$c_vendor->id,
'text'=>$c_vendor->name];
}
}
if ($current_customer->locations) {
foreach ($current_customer->locations as $c_loc) {
//$json.='{id:'.$c_vendor->id.', text:'.$c_vendor->name.'},';
$current_customer_locations[$c_loc->id] = $c_loc->location_name;
}
}
//$json = rtrim($json,',');
//$json .= ']';
/* echo '<pre>';
print_r( $current_selected_vendors);*/
// $current_selected_vendors = json_encode($current_selected_vendors,true) ;
$current_selected_vendors = $current_customer->vendors;
/* echo '<pre>';
print_r( $current_selected_vendors);
exit;*/
//dd( $current_customer_locations );
}
$vendor_records = Vendor::all();
//$vendors = [];
$not_selected_vendors = [];
if ($vendor_records->count()) {
foreach ($vendor_records as $vendor) {
/*foreach($current_customer->vendors as $c_vendor)
{
if($vendor->id != $c_vendor->id)
$not_selected_vendors[] =['id'=>$vendor->id,
'text'=>$vendor->name];
}*/
$vendors[$vendor->id]=$vendor->name;
//dd($user->id);
}
}
return view('vendor::add_vendor_for_customer', compact('customers', 'vendors', 'current_customer_locations', 'current_selected_vendors'));
}
function ajaxVendorsJson(Request $request)
{
//dd($request->all());
$vendors_list = Vendor::where('name', 'like', '%'.$request->q.'%')->get();
$current_customer = false;
if (!empty(Session::get('cust_id'))) {
$current_customer = Customer::with(['locations','locations.contacts','vendors'])->where('is_active', 1)->where('id', Session::get('cust_id'))->first();
}
$vendors = [];
foreach ($vendors_list as $vendor) {
$vendor_arr['id']=$vendor->id;
$vendor_arr['text'] = $vendor->name;
$vendor_arr['disabled']=false;
if ($current_customer) {
foreach ($current_customer->vendors as $c_vendor) {
if ($c_vendor->id == $vendor->id) {
$vendor_arr['disabled']=true;
$vendor_arr['text'] = $vendor->name.' <b>(Already attached)</b>';
}
}
}
$vendors[] = $vendor_arr;
}
return json_encode(["vendors" => $vendors,
//"selected_vendors" => $selected_vendors
]);
//return ['items'=>json_encode($vendors)];
}
public function storeVendorWithCustomerSelected(Request $request)
{
//dd($request->all());
//dd(json_decode($request->cust_arr));
if ($request->vendor_flag=='add') {
$this->validate(
$request,
[
'name' => 'required',
//'customer' => 'required',
]
);
}
//$contact_arr = json_decode($request->contact_arr);
//$cust_arr = json_decode($request->cust_arr);
$business_hours_arr = json_decode($request->business_hours);
if ($request->vendor_flag=='add') {
$customer = Customer::with(['vendors'])->where('id', $request->customer_selected_id)->first();
$vendor = new Vendor;
$vendor->name = $request->name ;
$vendor->phone_number = $request->phone ;
$vendor->dailing_instructions = $request->dialing_instructions ;
$vendor->website = $request->website;
$vendor->zip = $request->zip ;
$vendor->address = $request->address ;
$vendor->city = $request->city ;
$vendor->state = $request->state ;
$vendor->business_hours = $request->business_hours ;
$vendor->save();
//$vendor_ids = explode(',', $request->vendor_id);
$vendor_customer = [];
$vendor_customer['auth_contact_name']= $request->auth_contact_name;
$vendor_customer['phone_number'] = $request->cust_phone;
$vendor_customer['location_id'] = $request->customer_location_id;
$vendor_customer['account_number'] = $request->account_number;
$vendor_customer['portal_url'] = $request->portal_url;
//$vendor_customer['portal_username'] = $request->cust_user_name;
//$vendor_customer['portal_password'] = $request->cust_password;
$vendor_customer['notes'] = $request->customer_notes;
/********************tag attachment**************************/
$tag = Tag::firstOrCreate(['title' => 'vendor']);
$kpass = new KnowledgePassword();
$kpass->login = $request->cust_user_name;
$kpass->password = $<PASSWORD>;
$kpass->customer_id = $request->customer_selected_id;
//password atttachment with vendor
$pass = $vendor->password()->save($kpass);
//tags attachment with password
$pass->tags()->attach([$tag->id]);
/****************************************************/
$customer->vendors()->attach($vendor->id, $vendor_customer);
}
if ($request->vendor_flag=='attach') {
$customer = Customer::with(['vendors'])->where('id', $request->customer_selected_id)->first();
//$customer->vendors()->detach();
//$vendor_ids = explode(',', $request->vendor_id);
$vendor_customer = [];
$vendor_customer['auth_contact_name']= $request->auth_contact_name;
$vendor_customer['phone_number'] = $request->cust_phone;
$vendor_customer['account_number'] = $request->account_number;
$vendor_customer['location_id'] = $request->customer_location_id;
$vendor_customer['portal_url'] = $request->portal_url;
//$vendor_customer['portal_username'] = $request->cust_user_name;
//$vendor_customer['portal_password'] = $request->cust_password;
$vendor_customer['notes'] = $request->customer_notes;
/********************tag attachment**************************/
$tag = Tag::firstOrCreate(['title' => 'vendor']);
$vendor = Vendor::find($request->vendor_id);
$kpass = new KnowledgePassword();
$kpass->login = $request->cust_user_name;
$kpass->password = $request->cust_password;
$kpass->customer_id = $request->customer_selected_id;
//password atttachment with vendor
$pass = $vendor->password()->save($kpass);
//tags attachment with password
$pass->tags()->attach([$tag->id]);
/****************************************************/
/*$each_cust_arr=[];
foreach ($vendor_ids as $vendor) {
$each_cust_arr[$vendor] = $vendor_customer;
}*/
$customer->vendors()->attach($request->vendor_id, $vendor_customer);
}
$arr['success'] = 'Vendor(s) attached successfully';
return json_encode($arr);
exit;
//
}
function custsNotAttachedToVendor($v_id)
{
$customers = Customer::where('is_active', 1)->get();
$vendors = VendorCustomer::where('vendor_id', $v_id)->get();
$unattached_customers = [];
foreach ($customers as $customer) {
$cust_arr['id'] = $customer->id;
$cust_arr['name'] = $customer->name;
$cust_arr['disabled'] = false;
foreach ($vendors as $vendor) {
if ($vendor->customer_id == $customer->id) {
$cust_arr['name'] = $customer->name.'(Already Selected)';
$cust_arr['disabled'] = true;
}
}
$unattached_customers[]= $cust_arr;
}
// dd($unattached_customers);
return json_encode(['customers'=>$unattached_customers]);
}
}
<file_sep>/app/Model/User.php
<?php
namespace App\Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Zizaco\Entrust\Traits\EntrustUserTrait;
/*class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract*/
class User extends Model implements
AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
//use EntrustUserTrait; // add this trait to your user model
use Authenticatable, Authorizable, CanResetPassword, EntrustUserTrait {
EntrustUserTrait::can as may;
EntrustUserTrait::can insteadof Authorizable;
}
//use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
public function employee()
{
return $this->hasOne('App\Modules\Employee\Http\Employee');
}
public function raise()
{
return $this->hasMany('App\Modules\Employee\Http\Raise');
}
public function leave()
{
return $this->hasMany('App\Modules\Employee\Http\Leave', 'posted_for');
}
public function created_tickets()
{
return $this->hasMany('App\Modules\Crm\Http\Ticket', 'created_by');
}
public function assigned_tickets()
{
return $this->belongsToMany('App\Modules\Crm\Http\Ticket')->withTimestamps();
}
public function roles()
{
return $this->belongsToMany('App\Model\Role');
}
public function device_extentions()
{
return $this->hasMany('App\Modules\UserDevicesExtention');
}
}
<file_sep>/app/Modules/Crm/Http/Controllers/ServiceItemsController.php
<?php
namespace App\Modules\Crm\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use App\Modules\Crm\Http\CustomerServiceType;
use Auth;
class ServiceItemsController extends Controller
{
public function index()
{
//$controller = $this->controller;
$service_items = CustomerServiceType::all();
$route_delete = 'admin.service_item.destroy';
if (\Request::ajax()) {
return view('crm::service_item.ajax_index', compact('service_items'))->render();
}
return view('crm::service_item.index', compact('service_items', 'route_delete'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('crm::service_item.add');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate(
$request,
[
'title' => 'required|unique:customer_service_types|max:15',
'description' => 'required|max:15',
]
);
$service_item = new CustomerServiceType();
$service_item->title = $request->title;
$service_item->description = $request->description;
$service_item->save();
$arr['success'] = 'Service item added successfully';
return $arr;
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//$id = $request->id;
$service_item = CustomerServiceType::findorFail($id);
$service_item->delete();
$arr['success'] = 'Service item deleted successfully';
return $arr;
}
}
<file_sep>/app/Modules/Crm/Http/CustomerNote.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class CustomerNote extends Model
{
public function customer()
{
return $this->belongsTo('App\Modules\Crm\Http\Customer', 'customer_id');
}
public function entered_by()
{
return $this->belongsTo('App\Model\User', 'created_by');
}
}
<file_sep>/public/phpmyadmin/js/jquery/jquery-ui-1.8.16.custom.js
../../../javascript/jquery-ui/jquery-ui.min.js<file_sep>/config/google.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Client ID
|--------------------------------------------------------------------------
|
| The Client ID can be found in the OAuth Credentials under Service Account
|
*/
//'client_id' => '103776567733546219685',
'client_id' => '266413717450-b22fsfe2gots8qsmqrrjvfks7ndt03qr.apps.googleusercontent.com',
/*
|--------------------------------------------------------------------------
| Service account name
|--------------------------------------------------------------------------
|
| The Service account name is the Email Address that can be found in the
| OAuth Credentials under Service Account
|
*/
'service_account_name' => '<EMAIL>',
//'service_account_name' => '<EMAIL>',
/*
|--------------------------------------------------------------------------
| Calendar ID
|--------------------------------------------------------------------------
|
| This is the Calender ID which is shared with all employees.
|
*/
'calendar_id' => '<EMAIL>',
//'calendar_id' => '<EMAIL>',
/*
|--------------------------------------------------------------------------
| Key file location
|--------------------------------------------------------------------------
|
| This is the location of the .p12 file from the Laravel root directory
|
*/
//'key_file_location' => '/resources/assets/NexgenCRM-a540e98d3159.p12',
'key_file_location' => '/resources/assets/google-calander.p12',
/*
|--------------------------------------------------------------------------
| gmail configuration
|--------------------------------------------------------------------------
|
|
|
*/
'email_address' => '<EMAIL>',
'application_name' => 'nexgentec',
'credentials_path' => '/resources/assets/gmail_token.json',
];
<file_sep>/app/Modules/Assets/Http/AssetRole.php
<?php
namespace App\Modules\Assets\Http;
use Illuminate\Database\Eloquent\Model;
class AssetRole extends Model
{
}
<file_sep>/app/Modules/Crm/Http/CustomerServiceItem.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class CustomerServiceItem extends Model
{
public function rates()
{
return $this->hasMany('App\Modules\Crm\Http\CustomerServiceRate');
}
public function service_type()
{
return $this->belongsTo('App\Modules\Crm\Http\CustomerServiceType');
}
public function billing_period()
{
return $this->belongsTo('App\Modules\Crm\Http\CustomerBillingPeriod');
}
protected static function boot()
{
parent::boot();
static::deleting(function ($serviceitem) {
// before delete() method call this
$serviceitem->rates()->delete();
});
}
}
<file_sep>/app/Modules/Crm/Http/Controllers/ZohoController.php
<?php
namespace App\Modules\Crm\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use App\Modules\Crm\Http\Customer;
use App\Modules\Crm\Http\CustomerServiceType;
use App\Modules\Crm\Http\CustomerBillingPeriod;
use App\Modules\Crm\Http\CustomerServiceItem;
use App\Modules\Crm\Http\CustomerServiceRate;
use App\Modules\Crm\Http\CustomerLocation;
use App\Modules\Crm\Http\Invoice;
use App\Modules\Crm\Http\CustomerLocationContact;
use App\Modules\Crm\Http\Zoho;
use App\Model\Role;
use App\Model\User;
use Auth;
use App\Model\Config;
use Session;
class ZohoController extends Controller
{
private $customer;
private $zoho_contacts;
//public $zoho_unimported_contacts=[];
public function import()
{
$route_delete = 'admin.crm.destroy';
return view('crm::crm.import', compact('route_delete'));
}
function ajaxExportContact($id)
{
$customer_data = Customer::with(['locations','locations.contacts'])->where('id', $id)->first();
//dd($customer_data->locations);
$contacts = [];
$billing_address = [];
foreach ($customer_data->locations as $location) {
if ($location->default) {
$billing_address = [
"address" => $location->address,
"city" => $location->city,
"state" => $location->state,
"zip" => $location->zip,
"country" => $location->country];
}
foreach ($location->contacts as $contact) {
$contacts[] = [
"first_name"=>$contact->f_name,
"last_name"=>$contact->l_name,
"email"=>$contact->email,
"phone"=>$contact->phone,
"mobile"=>$contact->mobile,
"is_primary_contact"=>($contact->is_poc)?true:''];
}
}
//$zoho = Zoho::first();
$zoho_auth_token = Config::where('key', 'auth_token')->where('title', 'zoho')->first();
$ch = curl_init();
$post["contact_name"]= $customer_data->name;
$post["company_name"]= $customer_data->email_domain;
$post['contact_persons'] = $contacts;
$post['billing_address'] = $billing_address;
$data = [
'authtoken' => $zoho_auth_token->value,
'JSONString' => json_encode($post)
];
$url = 'https://invoice.zoho.com/api/v3/contacts';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result_curl = curl_exec($curl);
$result = json_decode($result_curl);
if ($result->code==0) {
$customer_to_update = Customer::find($id);
$customer_to_update->zohoid = $result->contact->contact_id;
$customer_to_update->save();
// $customer_to_update->zohoid =
$arr['success'] = 'Exported customer to Zoho invoice successfully.';
} else {
$arr['error'] = 'Error occured.' ;
$arr['error_msg'] = $result->message;
}
return json_encode($arr);
}
function getForm()
{
//$zoho = Config::where('title','zoho')->get();
$zoho = Config::where('title', 'zoho')->get();
foreach ($zoho as $value) {
if ($value->key=='email') {
$zoho_arr['email'] = $value->value;
}
if ($value->key=='password') {
$zoho_arr['password'] = $value->value;
}
if ($value->key=='auth_token') {
$zoho_arr['auth_token'] = $value->value;
}
}
return view('crm::zoho.add', compact('zoho_arr'))->render();
}
function getZohoContacts()
{
$zoho_auth_token = Config::where('key', 'auth_token')->where('title', 'zoho')->first();
$data = [
'authtoken' => $zoho_auth_token->value
];
$url = 'https://invoice.zoho.com/api/v3/contacts?authtoken='.$zoho_auth_token->value;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result_curl = curl_exec($curl);
$result = json_decode($result_curl);
// dd($result);
//return $result;
$this->zoho_contacts = $result->contacts;
$zoho_unimported_contacts =[];
foreach ($this->zoho_contacts as $contact) {
if (!Customer::where('zohoid', $contact->contact_id)->first()) {
$zoho_unimported_contacts[] = $contact;
//$url = 'https://invoice.zoho.com/api/v3/contacts/'.$contact->contact_id.'?authtoken='.$zoho->auth_token;
// dd($this->zoho_unimported_contacts);
}
}
//dd($zoho_unimported_contacts);
//$return['view'] = view('crm::zoho.unimported_contacts_partial',compact('zoho_unimported_contacts'))->render();
Session::put('unimported_zoho_contacts', $zoho_unimported_contacts);
$return['success']= 'ok';
return json_encode($return);
//dd($result);
// $contacts =[];
// foreach($result->contacts as $contact) {
//
// }
}
function listZohoUnimportedContacts()
{
//dd(Session::get('unimported_zoho_contacts'));
$zoho_unimported_contacts = Session::get('unimported_zoho_contacts');
return view('crm::zoho.unimported_list', compact('zoho_unimported_contacts'));
}
function importSelectedContacts(Request $request)
{
$zoho_auth_token = Config::where('key', 'auth_token')->where('title', 'zoho')->first();
$data = [
'authtoken' => $zoho_auth_token->value
];
$zoho_unimported_contacts = Session::get('unimported_zoho_contacts');
$selected_ids = explode(',', $request->selected_id);
// dd($selected_ids);
foreach ($zoho_unimported_contacts as $contact_) {
if (in_array($contact_->contact_id, $selected_ids)) {
$url = 'https://invoice.zoho.com/api/v3/contacts/'.$contact_->contact_id.'?authtoken='.$zoho_auth_token->value;
$curl_detail = curl_init($url);
curl_setopt($curl_detail, CURLOPT_RETURNTRANSFER, 1);
$result_curl_detail = curl_exec($curl_detail);
$contact_r = json_decode($result_curl_detail);
$contact = $contact_r->contact;
/*echo '<pre>';
print_r($contact);*/
//dd($contact);
$customer = new Customer;
$customer->name = $contact->contact_name;
// $customer->main_phone = $contact->phone;
$customer->email_domain = $contact->company_name;
$customer->customer_since = date("Y-m-d", strtotime($contact->created_time));
$customer->zohoid = $contact->contact_id;
$customer->is_active = ($contact->status=='active')? 1 : 0;
//$customer->is_taxable = $contact->taxable;
$customer->created_at = date('Y-m-d', strtotime($contact->created_time));
$customer->updated_at = date('Y-m-d', strtotime($contact->last_modified_time));
$customer->save();
$billing_address = $contact->billing_address;
$shipping_address = $contact->shipping_address;
if ($billing_address->city!='') {
$location_obj = new CustomerLocation;
$location_obj->location_name = $billing_address->city;
$location_obj->address = $billing_address->address;
$location_obj->country = $billing_address->country;
$location_obj->city = $billing_address->city;
$location_obj->zip = $billing_address->zip;
$location_obj->phone = $billing_address->fax;
$location_obj->customer_id = $customer->id;
$location_obj->default =1;
$location_obj->save();
}
if ($shipping_address->city!='') {
$location_obj = new CustomerLocation;
$location_obj->location_name = $shipping_address->city;
$location_obj->address = $shipping_address->address;
$location_obj->country = $shipping_address->country;
$location_obj->city = $shipping_address->city;
$location_obj->zip = $shipping_address->zip;
$location_obj->phone = $shipping_address->fax;
$location_obj->customer_id = $customer->id;
$location_obj->default =0;
$location_obj->save();
}
if ($shipping_address->city=='' && $billing_address->city=='') {
$location_obj = new CustomerLocation;
$location_obj->location_name = 'location';
$location_obj->customer_id = $customer->id;
$location_obj->default =0;
$location_obj->save();
}
foreach ($contact->contact_persons as $contact_) {
$contact_obj = new CustomerLocationContact;
$contact_obj->f_name = $contact_->first_name;
$contact_obj->l_name = $contact_->last_name;
$contact_obj->email = $contact_->email;
//$contact_obj->title = $contact->title_;
$phone = explode('-', $contact_->phone);
$contact_obj->phone = '('. $phone[1].')'.' '.$phone[2].'-'.$phone[3];
//$contact_obj->phone = $contact_->phone;
$contact_obj->mobile = $contact_->mobile;
$contact_obj->is_poc = $contact_->is_primary_contact?1:0;
$contact_obj->customer_location_id = $location_obj->id;
$contact_obj->save();
}
}
}
$arr['success'] = 'Imported customers from Zoho invoice successfully.Page will be refreshed in a while.';
return json_encode($arr);
exit;
}
function getContacts()
{
//$zoho = Zoho::first();
$zoho_auth_token = Config::where('key', 'auth_token')->where('title', 'zoho')->first();
$data = [
'authtoken' => $zoho_auth_token->value
];
$url = 'https://invoice.zoho.com/api/v3/contacts?authtoken='.$zoho_auth_token->value;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result_curl = curl_exec($curl);
$result = json_decode($result_curl);
// dd($result);
$contacts =[];
foreach ($result->contacts as $contact_) {
if (!Customer::where('zohoid', $contact_->contact_id)->first()) {
$url = 'https://invoice.zoho.com/api/v3/contacts/'.$contact_->contact_id.'?authtoken='.$zoho->auth_token;
$curl_detail = curl_init($url);
curl_setopt($curl_detail, CURLOPT_RETURNTRANSFER, 1);
$result_curl_detail = curl_exec($curl_detail);
$contact = json_decode($result_curl_detail);
$customer = new Customer;
$customer->name = $contact->contact_name;
// $customer->main_phone = $contact->phone;
$customer->email_domain = $contact->company_name;
$customer->customer_since = date("Y-m-d", strtotime($contact->created_time));
$customer->zohoid = $contact->contact_id;
$customer->is_active = ($contact->status=='active')? 1 : 0;
//$customer->is_taxable = $contact->taxable;
$customer->created_at = date('Y-m-d', strtotime($contact->created_time));
$customer->updated_at = date('Y-m-d', strtotime($contact->last_modified_time));
$customer->save();
$billing_address = $contact->billing_address;
$shipping_address = $contact->shipping_address;
if ($billing_address->city!='') {
$location_obj = new CustomerLocation;
$location_obj->location_name = $billing_address->city;
$location_obj->address = $billing_address->address;
$location_obj->country = $billing_address->country;
$location_obj->city = $billing_address->city;
$location_obj->zip = $billing_address->zip;
$location_obj->phone = $billing_address->fax;
$location_obj->customer_id = $customer->id;
$location_obj->default =1;
$location_obj->save();
}
if ($shipping_address->city!='') {
$location_obj = new CustomerLocation;
$location_obj->location_name = $shipping_address->city;
$location_obj->address = $shipping_address->address;
$location_obj->country = $shipping_address->country;
$location_obj->city = $shipping_address->city;
$location_obj->zip = $shipping_address->zip;
$location_obj->phone = $shipping_address->fax;
$location_obj->customer_id = $customer->id;
$location_obj->default =0;
$location_obj->save();
}
if ($shipping_address->city=='' && $billing_address->city=='') {
$location_obj = new CustomerLocation;
$location_obj->location_name = 'location';
$location_obj->customer_id = $customer->id;
$location_obj->default =0;
$location_obj->save();
}
foreach ($contact->contact_persons as $contact_) {
$contact_obj = new CustomerLocationContact;
$contact_obj->f_name = $contact_->first_name;
$contact_obj->l_name = $contact_->last_name;
$contact_obj->email = $contact_->email;
//$contact_obj->title = $contact->title_;
$phone = explode('-', $contact_->phone);
$contact_obj->phone = '('. $phone[1].')'.' '.$phone[2].'-'.$phone[3];
//$contact_obj->phone = $contact_->phone;
$contact_obj->mobile = $contact_->mobile;
$contact_obj->is_poc = $contact_->is_primary_contact?1:0;
$contact_obj->customer_location_id = $location_obj->id;
$contact_obj->save();
}
}
}
$arr['success'] = 'Imported customers from Zoho invoice successfully.Page will be refreshed in a while.';
return json_encode($arr);
exit;
exit;
}
function getExpense($cust_id)
{
//$zoho = Zoho::first();
$zoho_auth_token = Config::where('key', 'auth_token')->where('title', 'zoho')->first();
$url = 'https://invoice.zoho.com/api/v3/expenses?authtoken='.$zoho_auth_token->value.'&customer_id='.$cust_id;
$curl = curl_init($url);
// curl_setopt($curl, CURLOPT_POST, true);
//curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result_curl = curl_exec($curl);
$result = json_decode($result_curl);
$expense_dates = [];
foreach ($result->expenses as $expense) {
$expense_dates[] = $expense->date;
}
dd($result);
}
private function zohocurl($path, $params)
{
//$zoho = Zoho::first();
$zoho_auth_token = Config::where('key', 'auth_token')->where('title', 'zoho')->first();
$url = 'https://invoice.zoho.com/api/v3/'.$path.'?authtoken='.trim($zoho_auth_token->value);
foreach ($params as $paramkey => $paramvalue) {
$url .= '&'.$paramkey.'='.$paramvalue;
}
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
return json_decode(curl_exec($curl));
}
/**
* Zoho List all invoices
*
* @param int $cust_id Id of the customer to lookup
* @param string $status Search invoices by invoice status.
* Allowed Values: sent, draft, overdue, paid,
* void, unpaid, partially_paid and viewed
* @return json Invoices
*/
private function getInvoices($cust_id, $status)
{
$this->customer = Customer::with('invoices')->where('id', $cust_id)->first();
$curlParams = [
'customer_id' => $this->customer['zohoid'],
'status' => $status
];
return $this->zohocurl('invoices', $curlParams)->invoices;
}
/**
* Zoho List all recurring invoices
*
* @param int $cust_id Id of the customer to lookup
* @param string $status Search invoices by invoice status.
* Allowed Values: active, stopped and expired
* @return json Invoices
*/
private function getRecurringInvoices($cust_id, $status)
{
$customer = Customer::with('invoices')->where('id', $cust_id)->first();
return $this->zohocurl('recurringinvoices', ['customer_id' => $customer['zohoid']]);
}
/**
* Zoho Get Invoice
*
* @param int $zoho_id Id of the invoice
* @return json Invoice
*/
private function getInvoice($zoho_id)
{
return $this->zohocurl('invoices/'.$zoho_id, ['accept' => 'json']);
}
function importInvoices($cust_id)
{
$customer = Customer::with('invoices')->where('id', $cust_id)->first();
$curlData = $this->zohocurl('invoices', ['customer_id' => $customer['zohoid'], 'per_page' => '100']);
$continue = true;
$page = 2;
$qty = 0;
// Handle first page and any more pages
while ($continue) {
foreach ($curlData->invoices as $invoice) {
$invoice_obj = Invoice::firstOrNew(['zohoid' => $invoice->invoice_id]);
$invoice_obj->zohoid = $invoice->invoice_id;
$invoice_obj->status = $invoice->status;
$invoice_obj->invoice_number = $invoice->invoice_number;
$invoice_obj->reference_number = $invoice->reference_number;
$invoice_obj->date = $invoice->date;
$invoice_obj->due_date = $invoice->due_date;
$invoice_obj->due_days = $invoice->due_days;
$invoice_obj->currency_code = $invoice->currency_code;
$invoice_obj->total = $invoice->total;
$invoice_obj->balance = $invoice->balance;
$invoice_obj->created_time = $invoice->created_time;
$invoice_obj->last_modified_time = $invoice->last_modified_time;
$invoice_obj->is_emailed = $invoice->is_emailed;
$invoice_obj->reminders_sent = $invoice->reminders_sent;
$invoice_obj->last_reminder_sent_date = $invoice->last_reminder_sent_date;
$invoice_obj->payment_expected_date = $invoice->payment_expected_date;
$invoice_obj->last_payment_date = $invoice->last_payment_date;
$invoice_obj->customer_id = $cust_id;
$invoice_obj->save();
$qty++;
}
$continue = $curlData->page_context->has_more_page;
$curlData = $this->zohocurl('invoices', ['customer_id' => $customer['zohoid'], 'per_page' => '100', 'page' => $page]);
}
$result = [
'success' => 'Invoices imported',
'quantity' => $qty
];
return json_encode($result);
}
/**
* API v1 Zoho List all invoices
*/
function apiGetInvoices($cust_id, $status = null)
{
$invoices = $this->getInvoices($cust_id, $status);
$return = [];
$i=0;
foreach ($invoices as $invoice) {
if ($status == 'unpaid' && $invoice->status != 'paid') {
$return[$i]['invoice_number'] = $invoice->invoice_number;
$return[$i]['due_days'] = $invoice->due_days;
$return[$i]['status'] = $invoice->status;
$return[$i]['balance'] = '$' . number_format($invoice->balance, 2);
$return[$i]['total'] = '$' . number_format($invoice->total, 2);
$return[$i]['zohoId'] = $invoice->invoice_id;
// Get the invoice URL for printing
$invoice = $this->getInvoice($invoice->invoice_id);
$return[$i]['url'] = $invoice->invoice->invoice_url;
$i++;
}
}
return json_encode($return);
}
/**
* API v1 Zoho List all recurring invoices
*/
function apiGetRecurringInvoices($cust_id, $status = 'active')
{
$result = $this->getRecurringInvoices($cust_id, $status);
$recInv = $result->recurring_invoices;
$return = [];
$i=0;
foreach ($recInv as $invoice) {
$return[$i]['totalAmt'] = '$' . number_format($invoice->total, 2);
$return[$i]['name'] = $invoice->recurrence_name;
$return[$i]['status'] = $invoice->status;
$return[$i]['zohoId'] = $invoice->recurring_invoice_id;
$return[$i]['autoBill'] = $invoice->is_autobill_enabled;
$i++;
}
return json_encode($return);
}
function apiGetCustomerStanding($cust_id)
{
$unpaid_invoices = $this->getInvoices($cust_id, 'unpaid');
$result = [
'credit_limit_standing' => null,
'credit_limit_used' => null,
'qty_overdue' => 0,
'qty_waiting' => 0,
'amt_overdue' => 0,
'amt_waiting' => 0,
'waiting' => [],
'overdue' => []
];
foreach ($unpaid_invoices as $invoice) {
if ($invoice->status == 'overdue') {
$overdue = [
'invoice_number' => $invoice->invoice_number,
'due_days' => $invoice->due_days
];
array_push($result['overdue'], $overdue);
$result['qty_overdue']++;
$result['amt_overdue'] += $invoice->balance;
}
if ($invoice->status == 'sent') {
$waiting = [
'invoice_number' => $invoice->invoice_number,
'due_days' => $invoice->due_days
];
array_push($result['waiting'], $waiting);
$result['qty_waiting']++;
$result['amt_waiting'] += $invoice->balance;
}
}
if ($this->customer->credit_limit != 0) {
$result['credit_limit_standing'] = 'good';
$amt_unpaid = $result['amt_overdue'] + $result['amt_waiting'];
$result['credit_limit_used'] = number_format($amt_unpaid / $this->customer->credit_limit * 100, 0) . '%';
if (($amt_unpaid / $this->customer->credit_limit) >= .75) {
$result['credit_limit_standing'] = 'warning';
}
if (($amt_unpaid / $this->customer->credit_limit) >= 1) {
$result['credit_limit_standing'] = 'overlimit';
}
}
return json_encode($result);
}
}
<file_sep>/public/phpmyadmin/js/jquery/jquery-1.6.2.js
../../../javascript/jquery/jquery.min.js<file_sep>/app/Modules/Backupmanager/Http/Controllers/ProvisioningController.php
<?php
namespace App\Modules\Backupmanager\Http\Controllers;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Modules\Backupmanager\Http\Script;
class ProvisioningController extends Controller
{
public function index()
{
$scripts = Script::paginate(15);
//dd($scripts);
return view('backupmanager::index', compact('scripts'));
}
public function editor(Request $request)
{
$script = Script::with(['scriptBody'])->where('id', $request->id)->first();
return view('backupmanager::editor', compact('script'));
}
/* Save functionality for ACE editor */
public function editorSave(Request $request)
{
$script = Script::with(['scriptBody'])->find($request->id);
$script['scriptBody']['script'] = $request->script;
if ($script->push()) {
$arr['success'] = true;
} else {
$arr['success'] = false;
}
return json_encode($arr);
}
/* Retreive a script for execution */
public function getScript(Request $request)
{
if (strlen($request->uuid) != 36) {
die();
}
$script = Script::with(['scriptBody'])->where('id', $request->id)->first();
if (strlen($script->uuid) != 36 || $script->uuid != $request->uuid) {
die();
}
\Httpauth::secure();
$config = ['username' => 'admin', 'password' => '<PASSWORD>'];
\Httpauth::make($config)->secure();
}
}
<file_sep>/app/Http/Middleware/EntrustAbility.php
<?php
namespace App\Http\Middleware;
/**
* This file is part of Entrust,
* a role & permission management solution for Laravel.
*
* @license MIT
* @package Zizaco\Entrust
*/
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Entrust;
class EntrustAbility
{
protected $auth;
/**
* Creates a new instance of the middleware.
*
* @param Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param Closure $next
* @param $roles
* @param $permissions
* @param bool $validateAll
* @return mixed
*/
public function handle($request, Closure $next, $roles, $permissions, $validateAll = false)
{
$roles = explode('|', $roles);
$permissions = explode('|', $permissions);
// check for edit-profile permission
if (in_array("edit-profile", $permissions) /*&& Entrust::may('edit-profile')*/) {
// get route information
$route = $request->route();
$paramNames = $route->parameterNames();
$id = null;
if (!empty($paramNames) && isset($paramNames[0])) {
$id = $request->route()->getParameter($paramNames[0]);
}
// check user
if (!is_null($id) && $id == $request->user()->id) {
return $next($request);
}
}
if ($this->auth->guest() || !$request->user()->ability($roles, $permissions, ['validate_all' => $validateAll])) {
return response('Forbidden: You are not authorized to access this resource.', 403);
}
return $next($request);
}
}
<file_sep>/app/Modules/Crm/Http/Controllers/TicketController (copy).php
<?php
namespace App\Modules\Crm\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use App\Modules\Crm\Http\Customer;
use App\Modules\Crm\Http\Employee;
use App\Modules\Crm\Http\Ticket;
use App\Modules\Crm\Http\Attachment;
use App\Modules\Crm\Http\Response;
use App\Services\GoogleGmail;
use App\Services\ImapGmail;
use App\Modules\Crm\Http\CustomerServiceType;
use App\Modules\Crm\Http\CustomerBillingPeriod;
use App\Modules\Crm\Http\CustomerServiceItem;
use App\Modules\Crm\Http\CustomerServiceRate;
use App\Modules\Crm\Http\CustomerLocation;
use App\Modules\Crm\Http\CustomerLocationContact;
use App\Model\Config;
use App\Model\Role;
use App\Model\User;
use Auth;
use Mail;
use URL;
class TicketController extends Controller
{
public function index()
{
$tickets = Ticket::with(['responses','assigned_to','entered_by','customer','location','service_item'])->paginate(10);
//dd($tickets);
return view('crm::ticket.index',compact('tickets'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$customers_obj = Customer::with(['locations','locations.contacts'])->get();
$customers = [];
if($customers_obj->count())
{
foreach($customers_obj as $customer) {
$customers[$customer->id]=$customer->name.'('.$customer->email_domain.')';
//dd($user->id);
}
}
$managers_obj = Role::with('users')->where('name','manager')->orWhere('name','technician')->get();
// dd($managers_obj);
$users = [];
$roles = [];
//if ($manager->users->count())
//$managers = $manager->users;
if($managers_obj->count())
{
foreach($managers_obj as $manager_obj) {
foreach($manager_obj->users as $user) {
$users[$user->id]=$user->f_name." ".$user->l_name.'('.$manager_obj->name.')';
//dd($user->id);
}
}
}
return view('crm::ticket.add',compact('customers','users'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//dd($request->all());
$this->validate($request,
[
'customer_id' => 'required',
'title'=>'required',
'body'=>'required',
]);
$ticket = new Ticket;
$ticket->customer_id = $request->customer_id;
$ticket->location_id= $request->location;
$ticket->service_item_id= $request->service_item;
$ticket->title= $request->title;
$ticket->created_by= Auth::user()->id;
$ticket->body= $request->body;
$ticket->status= 'new';
$ticket->priority= $request->priority;
$ticket->save();
foreach ($request->users as $user) {
# code...
if(!$user=='')
$ticket->assigned_to()->attach($user);
}
//$customer->service_items()->save($service_item);
return redirect()->intended('admin/crm/ticket');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$ticket = Ticket::where('id',$id)->with(['responses','assigned_to','attachments','entered_by','customer','location','service_item','responses.responder'])->first();
//dd($tickets[0]->created_by);
//dd($ticket);
$managers_obj = Role::with('users')->where('name','manager')->orWhere('name','technician')->get();
// dd($managers_obj);
$users = [];
$roles = [];
//if ($manager->users->count())
//$managers = $manager->users;
if($managers_obj->count())
{
foreach($managers_obj as $manager_obj) {
foreach($manager_obj->users as $user) {
$users[$user->id]=$user->f_name." ".$user->l_name.' ('.$manager_obj->name.')';
//dd($user->id);
}
}
}
$assigned_users = [];
foreach($ticket->assigned_to as $assigned) {
$assigned_users[]=$assigned->id;
//dd($user->id);
}
//dd($assigned_users);
return view('crm::ticket.show',compact('ticket','users','assigned_users'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
$id = $request->id;
$ticket = Ticket::where('id',$id)->with(['responses','assigned_to','attachments','entered_by','customer','location','service_item','responses.responder'])->first();
$ticket->responses()->delete();
$ticket->attachments()->delete();
$ticket->assigned_to()->delete();
$ticket->delete();
//Session::flash('flash_message', 'User successfully deleted!');
return redirect()->intended('admin/crm/ticket');
}
function addResponse(Request $request)
{
$site_path = URL::to('/');
//dd($request->all());
$pattern = '/\/ckfinder/';
$replacement = $site_path.'/ckfinder';
$body = $request->body;
//preg_match( $pattern, $body, $output_array);
//dd($output_array);
$response_body = preg_replace($pattern, $replacement, $body);
//src="/ckfinder
//dd($vv);
$response = new Response;
$response->ticket_id = $request->ticket_id;
$response->body = htmlentities($response_body);
$response->responder_id = Auth::user()->id;
$response->save();
$responses_ = Response::with(['responder'])->where('ticket_id',$request->ticket_id)->orderBy('created_at', 'desc')->get();
$responses =[];
foreach ($responses_ as $response) {
$responses[]=['name'=>$response->responder->f_name,
'body'=>html_entity_decode($response->body),
'response_time' => date('d/m/Y h:i A',strtotime($response->created_at))
];
}
$arr['success'] = 'Response Added successfully';
$arr['responses'] = $responses;
$ticket = Ticket::find($request->ticket_id);
$smtp_arr = Config::where('title','smtp')->get();
$smtp =[];
foreach ($smtp_arr as $value) {
if($value->key=='server_address')
$server_address = $value->value;
if($value->key=='gmail_address')
$gmail_address = $value->value;
if($value->key=='gmail_password')
$password = $value->value;
if($value->key=='port')
$port= $value->value;
}
config(['mail.driver' => 'smtp',
'mail.host' => $server_address,
'mail.port' => $port,
'mail.encryption' => 'ssl',
'mail.username' => $gmail_address,
'mail.password' => $password]);
if($ticket->type=='email' && $ticket->email!='')
{
$envelope["from"]=$gmail_address ;
$envelope["to"] = $ticket->email;
$envelope["in_reply_to"] = "56F1532<EMAIL>";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html;' . "\r\n";
$headers .= 'From: '.Auth::user()->f_name.' '.Auth::user()->l_name.'<'.$gmail_address.'>'." \r\n" .
//'Reply-To: <'.$gmail_address.'>'. "\r\n" .
// 'Subject: '.$ticket->title."\r\n".
'To: '.$ticket->email."\r\n".
'In-Reply-To:'.$ticket->gmail_msg_id. "\r\n" .
'References:'.$ticket->gmail_msg_id. "\r\n" .
//'threadId:1543e7f8d480bc92'. "\r\n" .
'Return-Path:<'.$gmail_address.">\r\n" .
'X-Mailer: PHP/' . phpversion();
//imap_mail ( $ticket->email , $ticket->title ,$response_body,$headers);
$strRawMessage = "";
$boundary = uniqid(rand(), true);
$subjectCharset = $charset = 'utf-8';
$strRawMessage .= 'To: ' . $this->encodeRecipients(" <" . $ticket->email . ">") . "\r\n";
$strRawMessage .= 'From: '. $this->encodeRecipients(Auth::user()->f_name.' '.Auth::user()->l_name ." <" . $gmail_address . ">") . "\r\n";
$strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($ticket->title) . "?=\r\n";
$strRawMessage .= 'MIME-Version: 1.0' . "\r\n";
$strRawMessage .='In-Reply-To:'.$ticket->gmail_msg_id. "\r\n" ;
$strRawMessage .='References:'.$ticket->gmail_msg_id. "\r\n" ;
$strRawMessage .= 'Content-type: Multipart/Alternative; boundary="' . $boundary . '"' . "\r\n";
$strRawMessage .= "\r\n--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
$strRawMessage .= $response_body. "\r\n";
/* $mimeMessage = "MIME-Version: 1.0\r\n";
$mimeMessage .= 'From: '.Auth::user()->f_name.' '.Auth::user()->l_name.'<'.$gmail_address.'>'."\r\n";
$mimeMessage .= "To: <".$ticket->email.">\r\n";
$mimeMessage .= "Subject: =?utf-8?B?".base64_encode($ticket->title)."?=\r\n";
$mimeMessage .= "Date: ".date(DATE_RFC2822)."\r\n";
$mimeMessage .= "Content-Type: multipart/mixed; boundary=test\r\n\r\n";
$mimeMessage .= "--test\r\n";
$mimeMessage .='Message-ID:'.$ticket->gmail_msg_id. "\r\n" ;
$mimeMessage .='In-Reply-To:'.$ticket->gmail_msg_id. "\r\n" ;
$mimeMessage .='References:'.$ticket->gmail_msg_id. "\r\n" ;
//$mimeMessage .='threadId:1543e7f8d480bc92'. "\r\n" ;
$mimeMessage .= "Content-Type: text/plain; charset=UTF-8\r\n";
$mimeMessage .= "Content-Transfer-Encoding: base64\r\n\r\n";
$mimeMessage .= $response_body."\r\n";
//rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
//$mimeMessageEncoded = base64url_encode($mimeMessage);
$mimeMessageEncoded = rtrim(strtr(base64_encode($mimeMessage), '+/', '-_'), '=');*/
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
//$gmail = new GoogleGmail();
//$gmail->send_mail($mime,'15452dee85caef8d');
//exit;
Mail::send('crm::ticket.email.response', array('firstname'=>$ticket->sender_name,'body'=>$response_body), function($message) use ($ticket,$gmail_address){
$swiftMessage = $message->getSwiftMessage();
$headers = $swiftMessage->getHeaders();
$headers->addTextHeader('In-Reply-To', $ticket->gmail_msg_id);
$headers->addTextHeader('References', $ticket->gmail_msg_id);
$message->to($ticket->email,$ticket->sender_name)->subject($ticket->title)->from($gmail_address,Auth::user()->f_name.' '.Auth::user()->l_name);
});
}
return json_encode($arr);
exit;
//dd($responses);
//return
}
function encodeRecipients($recipient){
$recipientsCharset = 'utf-8';
if (preg_match("/(.*)<(.*)>/", $recipient, $regs)) {
$recipient = '=?' . $recipientsCharset . '?B?'.base64_encode($regs[1]).'?= <'.$regs[2].'>';
}
return $recipient;
}
function ajaxAssignUsers(Request $request)
{
//dd($request->all());
$this->validate($request,
[
'users' => 'required',
]);
$ticket = Ticket::find($request->id);
//$ticket->customer_id = $request->customer_id;
//$ticket->location_id= $request->location;
//$ticket->service_item_id= $request->service_item;
//$ticket->title= $request->title;
//$ticket->created_by= Auth::user()->id;
//$ticket->body= $request->body;
//$ticket->status= 'new';
//$ticket->priority= $request->priority;
$ticket->save();
$ticket->assigned_to()->detach();
foreach ($request->users as $user) {
# code...
if(!$user=='')
{
$ticket->assigned_to()->attach($user);
}
}
//$customer->service_items()->save($service_item);
//return redirect()->intended('admin/crm/ticket');
$ticket_ = Ticket::where('id',$request->id)->with(['assigned_to'])->first();
$managers_obj = Role::with('users')->where('name','manager')->orWhere('name','technician')->get();
// dd($ticket_->assigned_to);
$users = [];
if($managers_obj->count())
{
foreach($managers_obj as $manager_obj) {
foreach($manager_obj->users as $user) {
//if($user->id == )
$users[$user->id]=$user->f_name." ".$user->l_name.' ('.$manager_obj->name.')';
//dd($user->id);
}
}
}
$assigned_users = [];
if($ticket_->assigned_to->count()!=0)
{
foreach($ticket_->assigned_to as $key=>$assigned) {
//dd($assigned);
$assigned_users[$assigned->id]=$users[$assigned->id];
}
}
//dd($ticket_);
$arr['success'] = 'Assigned Users to ticket sussessfully';
$arr['assigned_users'] = $assigned_users;
$arr['ticket_id'] = $request->id;
return json_encode($arr);
exit;
}
function ajaxUpdateStatusPriority(Request $request)
{
// dd($request->all());
$ticket_ = Ticket::find($request->id);
//$ticket->customer_id = $request->customer_id;
//$ticket->location_id= $request->location;
//$ticket->service_item_id= $request->service_item;
//$ticket->title= $request->title;
//$ticket->created_by= Auth::user()->id;
//$ticket->body= $request->body;
$ticket_->status= $request->status;
$ticket_->priority= $request->priority;
$ticket_->save();
$ticket = Ticket::where('id',$request->id)->first();
$btn_class = '';
if($ticket->priority == 'low')
$btn_class = 'bg-gray';
if($ticket->priority == 'normal')
$btn_class = 'bg-blue';
if($ticket->priority == 'high')
$btn_class = 'bg-green';
if($ticket->priority == 'urgent')
$btn_class = 'bg-yellow';
if($ticket->priority == 'critical')
$btn_class = 'bg-red';
$arr['success'] = 'Changed status/priority sussessfully';
$arr['btn_class_priority'] = $btn_class;
$arr['ticket'] = $ticket;
$arr['ticket_id'] = $request->id;
return json_encode($arr);
exit;
}
function ajaxDeleteAssignedUser($t_id,$u_id)
{
$ticket = Ticket::find($t_id);
$ticket->assigned_to()->detach([$u_id]);
$ticket_ = Ticket::where('id',$t_id)->with(['assigned_to'])->first();
$managers_obj = Role::with('users')->where('name','manager')->orWhere('name','technician')->get();
// dd($ticket_->assigned_to);
$users = [];
if($managers_obj->count())
{
foreach($managers_obj as $manager_obj) {
foreach($manager_obj->users as $user) {
//if($user->id == )
$users[$user->id]=$user->f_name." ".$user->l_name.' ('.$manager_obj->name.')';
//dd($user->id);
}
}
}
$assigned_users = [];
if($ticket_->assigned_to->count()!=0)
{
foreach($ticket_->assigned_to as $key=>$assigned) {
//dd($assigned);
$assigned_users[$assigned->id]=$users[$assigned->id];
}
}
//dd($ticket_);
$arr['success'] = 'Employee successfully detached';
$arr['assigned_users'] = $assigned_users;
$arr['ticket_id'] = $t_id;
return json_encode($arr);
}
function readGmail()
{
//dd(url('/'));
//$gmail = new GoogleGmail();
$gmail = new ImapGmail();
$emails = $gmail->getMessages();
// dd($emails);
foreach ($emails as $email) {
$body =$email['body'];
$customer_email = $email['messageSenderEmail'];
$customer = Customer::where('email_domain',$customer_email)->first();
//dd($customer);
if($customer)
{
$customer_id = $customer->id;
}
$ticket = new Ticket;
if($customer)
$ticket->customer_id = $customer_id;//$request->customer_id;
else
{
$ticket->email = $customer_email;
$ticket->sender_name = $email['messageSender'];
}
//$ticket->location_id= $request->location;
//$ticket->service_item_id= $request->service_item;
$ticket->gmail_msg_id = $email['message_id'];
$ticket->title= $email['title'];
//$ticket->created_by= 4;//Auth::user()->id;
$ticket->body= $body;
$ticket->type= 'email';
$ticket->status= 'new';
$ticket->priority= 'low';
$ticket->save();
if($email['attachments'])
{
foreach ($email['attachments'] as $attachment) {
// $body .= urlencode('<a href="'.url('/')."/attachments/$attachment".'" data-lightbox="$attachment"><img src="'.url('/')."/attachments/$attachment".'" /> </a>');
$new_attachment = new Attachment;
$new_attachment->name = $attachment['name'];
$new_attachment->type = $attachment['mime_type'];
$ticket->attachments()->save($new_attachment);
}
}
}
$arr['success'] = 'Tickets added sussessfully from email';
//$arr['html_content_rates'] = view('crm::crm.rate.ajax_refresh_service_item_rates',compact('service_items'))->render();
return json_encode($arr);
exit;
}
}
<file_sep>/app/Modules/Crm/Resources/Views/crm/ajax_functions.blade(Fully_Functional).php
<script type="text/javascript">
function dynamic_data(id)
{
$('#load_img').show();
$.ajax({
url: "{{ URL::route('admin.crm.ajax.load_items')}}",
//headers: {'X-CSRF-TOKEN': token},
type: 'POST',
dataType: 'html',
data: 'id='+id,
success: function(response){
//alert('fff');
//console.log(response);
$('#dynamic_data').html(response);
$('#load_img').hide();
$('#rates').show();
/* $('#msgs').html(response.success);
$('#msg_div').removeClass('alert-danger').addClass('alert-success').show();*/
//
$('#subview.multiselect').multiselect({
enableFiltering: true,
includeSelectAllOption: true,
maxHeight: 400,
dropUp: false,
buttonClass: 'form-control'
});
$('.datepicker').datepicker();
}
});
}
function save_temporary_rate()
{
// alert($('input[name="temp_amount"]').val());
$('#load_img_rate').show();
$('#default_rate')
.append($("<option></option>")
.attr("value",$('input[name="temp_rate_title"]').val()+'|'+$('input[name="temp_amount"]').val())
.text($('input[name="temp_rate_title"]').val()+' ($'+$('input[name="temp_amount"]').val()+')'));
$('#default_rate').multiselect('rebuild');
$('#additional_rate')
.append($("<option></option>")
.attr("value",$('input[name="temp_rate_title"]').val()+'|'+$('input[name="temp_amount"]').val())
.text($('input[name="temp_rate_title"]').val()+' ($'+$('input[name="temp_amount"]').val()+')'));
$('#additional_rate').multiselect('rebuild');
$('#load_img_rate').hide();
$('#rate_form').hide();
$('#rate_alert').show('slow', function() {
$('#rate_alert').html('Rate added successfully.');
alert_hide();
});
}
/********************* Location step***************/
var loc_arr = [];
//first click on add location
function add_location()
{
var location = new Object();
if($('input[name="location_name"]').val()=='')
{
$('input[name="location_name"]').after('<label id="location_name-error" class="error" for="location_name">This field is required.</label>');
return false;
}
else
{
//populate location object with value
location={
location_name: $('input[name="location_name"]').val(),
address: $('input[name="address"]').val(),
country: $('input[name="country"]').val(),
city: $('input[name="city"]').val(),
zip: $('input[name="zip"]').val(),
loc_main_phone: $('input[name="loc_main_phone"]').val(),
default_: $('input[name="default"]').val()
};
//push the new item in array
loc_arr.push(location);
//default value for index_ is 0
index_ = 0;
//if array have elements, set the index at end
if(loc_arr.length !=0)
index_ = loc_arr.length-1;
//location panel append at the end
$('#location_labels').append('<div class="form-group col-lg-4" id="panel_'+index_+'"><div class="panel panel-green" ><div class="panel-heading"><h3 class="panel-title pull-left">'+location.location_name+'</h3><a href="javascript:;" class="btn btn-success pull-left" onclick="load_loc_obj('+index_+')"><i class="fa fa-pencil"></i></a><a href="javascript:;" class="btn btn-success pull-right" onclick="pop_loc_obj('+index_+')"><i class="fa fa-times-circle"></i></a><div class="clearfix"></div></div><div class="panel-body"><label>Address:</label>'+location.address+'<br><label>Country:</label>'+location.country+'<br><label>City:</label>'+location.city+'<br><label>Zip:</label>'+location.zip+'<br><label>Main phone:</label>'+location.loc_main_phone+'<br></div></div></div>');
//reset the form input values.
$('#location_inputs').find('input[type="text"]').val('');
}
}
//on click edit btn at panel right it loads the location object values in form
function load_loc_obj(id)
{
var location_data =loc_arr[id];
$('input[name="location_name"]').val(location_data.location_name);
$('input[name="address"]').val( location_data.address);
$('input[name="country"]').val(location_data.country);
$('input[name="city"]').val(location_data.city);
$('input[name="zip"]').val(location_data.zip);
$('input[name="loc_main_phone"]').val(location_data.loc_main_phone);
$('input[name="default"]').val(location_data.default_);
// change the button value to save location and call the func save_location
$('#add_loc_btn').html('');
$('#add_loc_btn').append('<a href="javascript:;" onclick="save_location('+id+')" class="btn btn-lg btn-success btn-block">Save Location</a>');
}
//on click delete btn at panel right it deletes the location object from objects array.
function pop_loc_obj(id)
{
//delete the item
loc_arr.splice(id, 1);
$('#panel_'+id).remove();
$('#location_inputs').find('input[type="text"]').val('');
}
//Save the edited location to objects array.
function save_location(id)
{
//delete the old object from array
loc_arr.splice(id, 1);
//add the edited data and reset the form
add_location();
// remove the panel also
$('#panel_'+id).remove();
// reset the button to add new location.
$('#add_loc_btn').html('');
$('#add_loc_btn').append('<a href="javascript:;" onclick="add_location()" class="btn btn-lg btn-success btn-block">Add Location</a>');
$('#location_inputs').find('input[type="text"]').val('');
}
/*********************End Location step***************/
/*********************Contacts step***************/
function populate_loc_contact()
{
$('#cnt_location').empty();
if(loc_arr.length>0)
{
$.each(loc_arr,function(index, el) {
//console.log(el);
$('#cnt_location').append($("<option></option>")
.attr("value",index)
.text( el.location_name));
});
$('#cnt_location').multiselect('rebuild');
$('#contact_inputs').find('input[type="text"]','input[type="email"]').prop('disabled', false);
}
else
{
alert('please go to preivious step and add location first');
$('#contact_inputs').find('input[type="text"]','input[type="email"]').prop('disabled', true);
}
}
var cntct_arr = [];
//first click on add location
function add_contact()
{
var contact = new Object();
if($('input[name="f_name"]').val()=='' || $('input[name="email"]').val()=='')
{
if($('input[name="f_name"]').val()=='')
$('input[name="f_name"]').after('<label id="f_name-error" class="error" for="f_name">This field is required.</label>');
if($('input[name="email"]').val()=='')
$('input[name="email"]').after('<label id="email-error" class="error" for="email">This field is required.</label>');
return false;
}
else
{
//populate contact object with value
contact={
f_name: $('input[name="f_name"]').val(),
l_name: $('input[name="l_name"]').val(),
email: $('input[name="email"]').val(),
title_: $('input[name="title"]').val(),
contact_phone: $('input[name="contact_phone"]').val(),
contact_mobile: $('input[name="contact_mobile"]').val(),
contact_location: $('#cnt_location option:selected').text(),
contact_location_index: $('#cnt_location').val()
};
//push the new item in array
cntct_arr.push(contact);
//default value for index_ is 0
indexx = 0;
//if array have elements, set the index at end
if(cntct_arr.length !=0)
indexx = cntct_arr.length-1;
//location panel append at the end
$('#contact_labels').append('<div class="form-group col-lg-4" id="panel_ct_'+indexx+'"><div class="panel panel-green" ><div class="panel-heading"><h3 class="panel-title pull-left">'+contact.f_name+' '+contact.l_name+'</h3><a href="javascript:;" class="btn btn-success pull-left" onclick="load_cntct_obj('+indexx+')"><i class="fa fa-pencil"></i></a><a href="javascript:;" class="btn btn-success pull-right" onclick="pop_cntct_obj('+indexx+')"><i class="fa fa-times-circle"></i></a><div class="clearfix"></div></div><div class="panel-body"><label>Email:</label>'+contact.email+'<br><label>Title:</label>'+contact.title_+'<br><label>Phone:</label>'+contact.contact_phone+'<br><label>Mobile:</label>'+contact.contact_mobile+'<br><label>Location:</label>'+contact.contact_location+'<br></div></div></div>');
//reset the form input values.
$('#contact_inputs').find('input[type="text"]').val('');
//$('#cnt_email').val('');
}
}
//on click edit btn at panel right it loads the location object values in form
function load_cntct_obj(id)
{
var contact_data =cntct_arr[id];
$('input[name="f_name"]').val(contact_data.f_name);
$('input[name="l_name"]').val(contact_data.l_name);
$('input[name="email"]').val(contact_data.email);
$('input[name="title"]').val(contact_data.title_);
$('input[name="contact_phone"]').val(contact_data.contact_phone);
$('input[name="contact_mobile"]').val(contact_data.contact_mobile);
//$('#cnt_location option[value="'+contact_data.contact_location_index+'"]').attr("selected", "selected");
$('option[value="'+contact_data.contact_location_index+'"]', $('#cnt_location')).prop('selected', true);
$('#cnt_location').multiselect('refresh');
//$('#cnt_location').val(contact_data);
// change the button value to save location and call the func save_location
$('#add_cntct_btn').html('');
$('#add_cntct_btn').append('<a href="javascript:;" onclick="save_contact('+id+')" class="btn btn-lg btn-success btn-block">Save Contact</a>');
}
function pop_cntct_obj(id)
{
//delete the item
cntct_arr.splice(id, 1);
$('#panel_ct_'+id).remove();
$('#contact_inputs').find('input[type="text"]').val('');
}
//Save the edited location to objects array.
function save_contact(id)
{
//delete the old object from array
cntct_arr.splice(id, 1);
//add the edited data and reset the form
add_contact();
// remove the panel also
$('#panel_ct_'+id).remove();
// reset the button to add new location.
$('#add_cntct_btn').html('');
$('#add_cntct_btn').append('<a href="javascript:;" onclick="add_contact()" class="btn btn-lg btn-success btn-block">Add Location</a>');
$('#contact_inputs').find('input[type="text"]').val('');
}
/*********************End Contacts step***************/
</script><file_sep>/app/Modules/Backupmanager/Http/Script.php
<?php
namespace App\Modules\Backupmanager\Http;
use Illuminate\Database\Eloquent\Model;
class Script extends Model
{
protected $table = 'backupmanager_scripts';
public function scriptBody()
{
return $this->hasOne('App\Modules\Backupmanager\Http\ScriptBody', 'id', 'script_body_id');
}
}
<file_sep>/app/Http/Controllers/Controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Model\Config;
class Controller extends BaseController
{
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
public $global_date;
public $global_time;
public $global_phone_number_mask;
public $global_mobile_number_mask;
public $global_fax_number_mask;
public $time_zone;
public $user;
function __construct()
{
$global_date = Config::where('title', 'date_format')->first();
$global_time = Config::where('title', 'time_format')->first();
$global_phone_number_mask = Config::where('key', 'telephone')->first();
$global_mobile_number_mask = Config::where('key', 'mobile')->first();
$global_fax_number_mask = Config::where('key', 'fax')->first();
$global_time_zone = Config::where('key', 'system_timezone')->first();
if ($global_time_zone) {
$this->time_zone = $global_time_zone->value;
} else {
$this->time_zone = 'America/New_York';
}
//dd($global_time_zone->value);
if ($global_date) {
$this->global_date = $global_date->key;
} else {
$this->global_date = 'm/d/Y';
}
if ($global_phone_number_mask) {
$this->global_phone_number_mask = $global_phone_number_mask->value;
} else {
$this->global_phone_number_mask = '(999) 999-9999';
}
if ($global_mobile_number_mask) {
$this->global_mobile_number_mask = $global_mobile_number_mask->value;
} else {
$this->global_mobile_number_mask = '(999) 999-9999';
}
if ($global_fax_number_mask) {
$this->global_fax_number_mask = $global_fax_number_mask->value;
} else {
$this->global_fax_number_mask = '(999) 999-9999';
}
\View::share('global_date', $this->global_date);
\View::share('global_time', $global_time);
\View::share('js_global_date', $global_date->value);
\View::share('global_time_zone', $this->time_zone);
\View::share('global_phone_number_mask', $this->global_phone_number_mask);
\View::share('global_mobile_number_mask', $this->global_mobile_number_mask);
\View::share('global_fax_number_mask', $this->global_fax_number_mask);
}
}
<file_sep>/app/Console/Commands/ReadGmail.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Services\GoogleGmail;
use App\Modules\Crm\Http\Customer;
use App\Modules\Crm\Http\Ticket;
use App\Modules\Crm\Http\Response;
use App\Modules\Crm\Http\Attachment;
use App\Events\updateGoogleAuthToken;
use App\Model\Config;
use Auth;
use Mail;
use Event;
use App\Modules\Crm\Http\TicketStatus;
class ReadGmail extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'gmail:read';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Read and store GMAIL emails';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$gmail = new GoogleGmail();
$threads = $gmail->getThreads();
// dd($threads);
foreach ($threads as $key => $thread) {
//dd();
foreach ($thread as $email) {
//dd($email);
$body =$email['body'];
if ($key==$email['messageId']) {
$chk_ticket = Ticket::where('gmail_msg_id', $email['gmail_msg_id'])->first();
if (!$chk_ticket) {
$customer_email = $email['messageSenderEmail'];
$customer = Customer::where('email_domain', $customer_email)->first();
//dd($customer);
if ($customer) {
$customer_id = $customer->id;
}
$ticket = new Ticket;
if ($customer) {
$ticket->customer_id = $customer_id;//$request->customer_id;
} else {
$ticket->email = $customer_email;
$ticket->sender_name = $email['messageSender'];
}
//$ticket->location_id= $request->location;
//$ticket->service_item_id= $request->service_item;
$ticket->gmail_msg_id = $email['gmail_msg_id'];
$ticket->entered_date= date('Y-m-d', strtotime($email['revceived_date']));
$ticket->entered_time = date('h:i:s', strtotime($email['revceived_date']));
$ticket->title= $email['title'];
//$ticket->created_by= 4;//Auth::user()->id;
$ticket->body= $body;
$ticket->type= 'email';
$ticket->thread_id= $key;
$status = TicketStatus::where('title', 'new')->first();
$ticket->ticket_status_id = $status->id;
$ticket->priority= 'normal';
$ticket->save();
$ticket_id = $ticket->id;
if ($email['attachments']) {
foreach ($email['attachments'] as $attachment) {
// $body .= urlencode('<a href="'.url('/')."/attachments/$attachment".'" data-lightbox="$attachment"><img src="'.url('/')."/attachments/$attachment".'" /> </a>');
$new_attachment = new Attachment;
$new_attachment->name = $attachment['name'];
$new_attachment->type = $attachment['mime_type'];
$ticket->attachments()->save($new_attachment);
}
}
}
} else {
if ($chk_ticket) {
$ticket_id = $chk_ticket->id;
}
//check if gmial_msg_id exist, it means its customer earlier reply/response to our/employee reponse.
$check_response_already_exist = Response::where('gmail_msg_id', $email['gmail_msg_id'])->first();
if (!$check_response_already_exist) {
//check if response_id exist, it means that its response and already exist in database.
$chk_reponse_by_id = Response::find($email['response_id']);
if (!$chk_reponse_by_id) {
$_ticket = Ticket::where('thread_id', $key)->first();
$status = TicketStatus::where('title', 'open')->first();
$_ticket->ticket_status_id= $status->id;
$_ticket->save();
$response = new Response;
$response->ticket_id = $ticket_id;
$response->body = $body;
$response->sender_type = 'customer';
$response->entered_date = date('Y-m-d', strtotime($email['revceived_date']));
$response->entered_time = date(' h:i:s', strtotime($email['revceived_date']));
$response->gmail_msg_id = $email['gmail_msg_id'];
$response->save();
}
}
}
}
}
//$arr['success'] = 'Tickets added sussessfully from email';
//$arr['html_content_rates'] = view('crm::crm.rate.ajax_refresh_service_item_rates',compact('service_items'))->render();
// return json_encode($arr)
//dd('lll-here');
/* $smtp_arr = Config::where('title','smtp')->get();
$smtp =[];
foreach ($smtp_arr as $value) {
if($value->key=='server_address')
$server_address = $value->value;
if($value->key=='gmail_address')
$gmail_address = $value->value;
if($value->key=='gmail_password')
$password = $value->value;
if($value->key=='port')
$port= $value->value;
}
config(['mail.driver' => 'smtp',
'mail.host' => $server_address,
'mail.port' => $port,
'mail.encryption' => 'ssl',
'mail.username' => $gmail_address,
'mail.password' => $password]);
Mail::send('crm::ticket.email.response', array('firstname'=>'asad','body'=>'cronjob email from 172.16.17.32'), function($message) use($gmail_address) {
$message->to('<EMAIL>','adnan')->subject('cronjob test')->from($gmail_address,'cronjob');
});
*/
echo 'done';
exit;
}
}
<file_sep>/app/Modules/Crm/Resources/Views/ticket/show.blade_backup.php
@extends('admin.main')
@section('content')
<section class="content-header">
<h1>
Ticket Detail
{{-- <small>preview of simple tables</small> --}}
</h1>
<ol class="breadcrumb">
<li>
<i class="fa fa-dashboard"></i> <a href="/admin/dashboard">Dashboard</a>
</li>
<li>
<i class="fa fa-pencil-square-o"></i> <a href=" {{ URL::route('admin.ticket.index')}}">Tickets</a>
</li>
<li class="active">
<i class="fa fa-table"></i> {{$ticket->title}}
</li>
</ol>
</section>
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="col-xs-6 pull-right">
{{-- <a href=" {{ URL::route('admin.ticket.create')}}" class="btn btn-primary pull-right"><i class="fa fa-plus"></i> Add Response</a>
<a href=" {{ URL::route('admin.ticket.create')}}" class="btn btn-primary pull-right margin-right10"><i class="fa fa-edit"></i> Edit</a> --}}
{{-- <a href=" {{ URL::route('admin.ticket.create')}}" class="btn btn-primary pull-right"> Add Response</a> --}}
</div>
</div>
<div class="col-xs-12">
<div class="col-xs-6">
<div id="msg"></div>
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Ticket Detail</h3>
</div><!-- /.box-header -->
<div class="box-body">
<dl class="dl-horizontal">
<dt>Title</dt>
<dd>{{$ticket->title}}</dd>
<br/>
<dt>Description</dt>
<dd><?php echo urldecode($ticket->body);?></dd>
</dl>
</div><!-- /.box-body -->
@if($ticket->attachments)
<div class="box-header with-border top-border bot_10px">
<h3 class="box-title">Attachments</h3>
</div><!-- /.box-header -->
<div class="box-body">
<dl class="dl-horizontal">
@foreach($ticket->attachments as $attachment)
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 ff">
@if(basename($attachment->type)=='pdf')
<img class="img-responsive" src="{{url('/')."/img/pdf.jpg"}}" />
<div class="overlay" style="display:none">
<a class="btn btn-md btn-primary iframe" href="{{url('/')."/attachments/$attachment->name"}}">
<i class="fa fa-eye"></i>
</a>
</div>
@else
<img class="img-responsive" src="{{url('/')."/attachments/$attachment->name"}}" />
<div class="overlay" style="display:none">
<a class="btn btn-md btn-primary fancybox" href="{{url('/')."/attachments/$attachment->name"}}">
<i class="fa fa-eye"></i>
</a>
</div>
@endif
</div>
@endforeach
</dl>
<div class="clearfix"></div>
</div><!-- /.box-body -->
@endif
<div class="box-header with-border top-border bot_10px">
<h3 class="box-title">Responses</h3>
</div>
<div class="box-footer box-comments" id="responses_div">
@foreach($ticket->responses as $response)
<div class="box-comment">
<!-- User image -->
<img alt="user image" src="{{ URL::asset('img/avatar2.png')}}" class="img-circle img-sm">
<div class="comment-text">
<span class="username">
{{ $response->responder->f_name }}
<span class="text-muted pull-right">{{ date('d/m/Y h:i A',strtotime($response->created_at)) }}</span>
</span><!-- /.username -->
{!! html_entity_decode($response->body) !!}
</div><!-- /.comment-text -->
</div><!-- /.box-comment -->
@endforeach
</div>
<div class="box-footer">
<div class="box-header with-border top-border bot_10px">
<h3 class="box-title">Add response</h3>
</div>
<form action="#" method="POST" id="response_form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="ticket_id" value="{{ $ticket->id }}">
<div class="form-group col-lg-12">
{!! Form::textarea('body',null, ['placeholder'=>"Ticket descriptions",'class'=>"form-control textarea",'id'=>'description','rows'=>3]) !!}
</div>
</form>
<div class="col-lg-12">
<div class="form-group col-lg-6 pull-right">
<a class="btn btn-lg btn-info pull-right" onclick="addResponse()" >Save</a>
</div>
</div>
</div>
</div><!-- /.box -->
</div>
<div class="col-xs-6">
<div id="msg_info"></div>
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Info</h3>
</div><!-- /.box-header -->
<div class="box-body">
<dl class="dl-horizontal info">
<dt>Customer Info</dt>
<dd>
<button type="button" class="btn bg-gray-active btn-sm">
<span>
@if($ticket->customer)
<i class="fa fa-user"></i> {{ $ticket->customer->name }}
@elseif($ticket->email)
<i class="fa fa-envelope"></i> {{ $ticket->email }}@endif
</span>
</button>
@if($ticket->location)
<button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-map-marker"></i>
<span>{{ $ticket->location->location_name }}</span>
</button>
@endif
@if($ticket->location)
<button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-gears"></i>
<span>{{ $ticket->service_item->title }}</span>
</button>
@endif
<a class="pull-right btn btn-lg" href="javascript:;" data-target="#modal-edit-assign-users" id="modaal" data-id="{{$ticket->id}}" data-toggle="modal"><i class="fa fa-pencil"></i></a>
</dd>
<dt>Assigned Users</dt>
<dd >
<div id="assigned_users" class="pull-left">
@if($ticket->assigned_to)
@foreach($ticket->assigned_to as $employee)
<p class="btn bg-gray-active btn-sm">
<i class="fa fa-user"></i>
<span>{{ $users[$employee->id] }}</span>
<a class="btn btn-xs" href="javascript:;" data-target="#modal-delete-assign-user" id="modaal" data-uid="{{$employee->id}}" data-tid="{{$ticket->id}}" data-toggle="modal"><i class="fa fa-times"></i></a>
</p>
@endforeach
@endif
</div>
<a class="pull-right btn btn-lg" href="javascript:;" data-target="#modal-edit-assign-users" id="modaal" data-id="{{$ticket->id}}"
data-toggle="modal"><i class="fa fa-pencil"></i></a>
</dd>
<?php
$btn_class = '';
if ($ticket->priority == 'low') {
$btn_class = 'bg-gray';
}
if ($ticket->priority == 'normal') {
$btn_class = 'bg-blue';
}
if ($ticket->priority == 'high') {
$btn_class = 'bg-green';
}
if ($ticket->priority == 'urgent') {
$btn_class = 'bg-yellow';
}
if ($ticket->priority == 'critical') {
$btn_class = 'bg-red';
}
?>
<dt>Priority</dt>
<dd id="priority">
<button type="button" class="btn {{$btn_class}} btn-sm">
<span>{{$ticket->priority}}</span>
</button>
<a class="pull-right btn btn-lg" href="javascript:;" data-target="#modal-edit-priority-status" id="modaal" data-id="{{$ticket->id}}"
data-toggle="modal"><i class="fa fa-pencil"></i></a>
</dd>
<dt>Status</dt>
<dd id="status">
<button type="button" class="btn bg-gray-active btn-sm">
<span>{{$ticket->status}}</span>
</button>
<a class="pull-right btn btn-lg" href="javascript:;" data-target="#modal-edit-priority-status" id="modaal" data-id="{{$ticket->id}}"
data-toggle="modal"><i class="fa fa-pencil"></i></a>
</dd>
</dl>
</div><!-- /.box-body -->
</div><!-- /.box -->
</div>
</div>
</div>
</section>
@include('crm::ticket.edit_assigned_users_modal')
@include('crm::ticket.delete_modal_assign_user')
@include('crm::ticket.edit_priority_status_modal')
@endsection
@section('script')
<script type="text/javascript" src="/js/form_elements.js"></script>
<script src="/ckeditor/ckeditor.js"></script>
<script src="/ckeditor/config.js"></script>
<script src="/fancybox/jquery.fancybox.js?v=2.1.5"></script>
<script>
$(document).ready(function()
{
CKEDITOR.replace( 'description', {
filebrowserBrowseUrl: '/ckfinder/ckfinder.html',
filebrowserUploadUrl: '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files'
} );
$('.fancybox').fancybox();
$("a.iframe").fancybox({
'type': 'iframe'
});
$('.ff').hover(function() {
$(this).addClass('bb');
$(this).children('img').css({ opacity: 0.8 });
$(this).children('.overlay').show();
}, function() {
/* Stuff to do when the mouse leaves the element */
$(this).removeClass('bb');
$(this).children('img').css({ opacity:1 });
$(this).children('.overlay').hide();
});
/* $('.multiselect').multiselect({
enableFiltering: true,
includeSelectAllOption: true,
maxHeight: 400,
dropUp: false,
buttonClass: 'form-control'
});
*/
} );
function addResponse()
{
for ( instance in CKEDITOR.instances )
CKEDITOR.instances[instance].updateElement();
//{{URL::route('admin.ticket.add_response')}}
$.ajax({
url: "{{ URL::route('admin.ticket.add_response')}}",
//headers: {'X-CSRF-TOKEN': token},
type: 'POST',
dataType: 'json',
data: $('#response_form').serialize(),
success: function(response){
$('#msg').html('<div class="alert alert-success"><ul><li>'+response.success+'</li></ul></div>');
$('#msg').removeClass('alert-danger').addClass('alert-success').show();
//location.reload();
var html_response ='' ;
$.each(response.responses,function(index,response_data) {
html_response += '<div class="box-comment"><img alt="user image" src="{{ URL::asset('img/avatar2.png')}}" class="img-circle img-sm"><div class="comment-text"><span class="username">'+response_data.name+'<span class="text-muted pull-right">'+response_data.response_time+'</span></span>'+response_data.body+'</div></div>';
});
$('#responses_div').html(html_response);
alert_hide();
}
});
}
</script>
@endsection
@section('styles')
<link href="{{URL::asset('css/bootstrap-multiselect.css')}}" rel="stylesheet" />
<link rel="stylesheet" href="/css/bootstrap3-wysihtml5.min.css">
<link rel="stylesheet" href="/fancybox/jquery.fancybox.css?v=2.1.5">
<link rel="stylesheet" href="/fancybox/helpers/jquery.fancybox-buttons.css?v=1.0.5">
<style>
.info>dd, .info>dt {
line-height: 3;
}
.top-border {
border-top: 1px solid #f4f4f4;
}
.top-10px{
top: 10px;
}
.bot_10px{
margin-bottom: 10px;
}
.margin-right10{
margin-right: 10px;
}
.bb {
background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0;
opacity: 1;
cursor: pointer;
overflow: visible;
}
.box .overlay > .btn, .overlay-wrapper .overlay > .btn {
color: #000;
font-size: 30px;
left: 50%;
margin-left: -15px;
margin-top: -15px;
position: absolute;
top: 50%;
}
</style>
@endsection
<file_sep>/app/Modules/Crm/Http/Controllers/AppointmentController.php
<?php
namespace App\Modules\Crm\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Modules\Crm\Http\Customer;
use App\Modules\Crm\Http\Product;
use App\Modules\Crm\Http\CustomerServiceType;
use App\Modules\Crm\Http\DefaultRate;
use App\Modules\Crm\Http\CustomerBillingPeriod;
use App\Modules\Crm\Http\CustomerServiceItem;
use App\Modules\Crm\Http\CustomerServiceRate;
use App\Modules\Crm\Http\CustomerLocation;
use App\Modules\Crm\Http\CustomerNote;
use App\Modules\Crm\Http\Invoice;
use App\Modules\Crm\Http\Country;
use App\Services\GoogleCalendar;
use App\Modules\Crm\Http\CustomerLocationContact;
use App\Modules\Crm\Http\CustomerAppointment;
use App\Model\Config;
use App\Model\Role;
use App\Model\User;
use Auth;
use URL;
use Datatables;
use Session;
class AppointmentController extends Controller
{
function postEvent(Request $request)
{
$panctuality[0] = 'As scheduled' ;
$panctuality[1] = '1 Hour Window' ;
$panctuality[2] = '2 Hour Window' ;
$panctuality[3] = '3 Hour Window' ;
$panctuality[4] = 'Same Day' ;
$panctuality[5] = 'Tentative' ;
$location = CustomerLocation::find($request->location_index);
$technician = User::find($request->employee_index);
$contact = CustomerLocationContact::find($request->contact_index);
$service = CustomerServiceItem::find($request->appointment_against) ;
$timeframe = ' ± '.$request->timeframe;
if ($request->timeframe==4) {
$timeframe = 'SDY';
}
if ($request->timeframe==5) {
$timeframe = 'TTV';
}
$date_arr = explode(',', $request->calander_data);
$calendar = new GoogleCalendar;
$description = 'Location : '.$location->location_name;
$description .= ' Technician : '.$technician->f_name.' '.$technician->l_name;
$description .= ' Contact : '.$contact->f_name.' '.$contact->l_name;
$description .= ' Punctuality : '.$panctuality[$request->timeframe];
if ($service) {
$description .= ' Against : '.$service->title;
}
$description .= ' Start time : '.date("H:i:s", strtotime($date_arr[0]));
$description .= ' End time : '.date("H:i:s", strtotime($date_arr[1]));
$description .= ' Notes : '.$request->notes;
$startDateTime = new \DateTime($date_arr[0], new \DateTimeZone($this->time_zone));
$start = $startDateTime->format(\DateTime::ISO8601);
$endDateTime = new \DateTime($date_arr[1], new \DateTimeZone($this->time_zone));
$end = $endDateTime->format(\DateTime::ISO8601);
$post = $calendar->eventPost([
'summary' => html_entity_decode('@'.$technician->f_name.' '.$timeframe.' '.$request->appointment_title),
'location' => $location->address.' '.$location->city.' '.$location->state.' '.$location->zip,
'visibility' => 'private',
'description' => $description,
'start' => [
'dateTime' => $start,
'timeZone' => $this->time_zone,
],
'end' => [
'dateTime' => $end,
'timeZone' => $this->time_zone,
],
'reminders' => [
'useDefault' => false,
'overrides' => [
['method' => 'email', 'minutes' => 24 * 60],
['method' => 'popup', 'minutes' => 10],
],
],
]);
//dd($post);
$appointment = new CustomerAppointment;
$appointment->customer_id = Session::get('cust_id');
$appointment->created_by = Auth::user()->id;
$appointment->customer_location_id = $location->id;
$appointment->technician_id = $technician->id;
$appointment->customer_location_contact_id = $contact->id;
$appointment->title = $request->appointment_title;
$appointment->panctuality = $request->timeframe;
$appointment->notes = $request->notes;
$appointment->event_date = date('Y-m-d', strtotime($date_arr[0]));
if ($service) {
$appointment->customer_service_item_id = $service->id;
}
$appointment->event_id_google = $post->id;
$appointment->save();
$arr['success'] ='yes';
$arr['msg'] = 'Appointment posted to google calendar successfully';
return json_encode($arr);
exit;
}
function updateEvent(Request $request)
{
//dd($request->all());
$event_id = $request->google_event_id;
$panctuality[0] = 'As scheduled' ;
$panctuality[1] = '1 Hour Window' ;
$panctuality[2] = '2 Hour Window' ;
$panctuality[3] = '3 Hour Window' ;
$panctuality[4] = 'Same Day' ;
$panctuality[5] = 'Tentative' ;
$location = CustomerLocation::find($request->location_index);
$technician = User::find($request->employee_index);
$contact = CustomerLocationContact::find($request->contact_index);
$service = CustomerServiceItem::find($request->appointment_against) ;
$timeframe = ' ± '.$request->timeframe;
if ($request->timeframe==4) {
$timeframe = 'SDY';
}
if ($request->timeframe==5) {
$timeframe = 'TTV';
}
$date_arr = explode(',', $request->calander_data);
$startDateTime = new \DateTime($date_arr[0], new \DateTimeZone($this->time_zone));
$start = $startDateTime->format(\DateTime::ISO8601);
$endDateTime = new \DateTime($date_arr[1], new \DateTimeZone($this->time_zone));
$end = $endDateTime->format(\DateTime::ISO8601);
$calendar = new GoogleCalendar;
$description = 'Location : '.$location->location_name;
$description .= ' Technician : '.$technician->f_name.' '.$technician->l_name;
$description .= ' Contact : '.$contact->f_name.' '.$contact->l_name;
$description .= ' Punctuality : '.$panctuality[$request->timeframe];
if ($service) {
$description .= ' Against : '.$service->title;
}
$description .= ' Start time : '.date("H:i:s", strtotime($date_arr[0]));
$description .= ' End time : '.date("H:i:s", strtotime($date_arr[1]));
$description .= ' Notes : '.$request->notes;
$post = $calendar->eventUpdate($event_id, [
'summary' => html_entity_decode('@'.$technician->f_name.' '.$timeframe.' '.$request->appointment_title),
'location' => $location->address.' '.$location->city.' '.$location->state.' '.$location->zip,
'visibility' => 'private',
'description' => $description,
'start' => [
'dateTime' => $start,
'timeZone' => $this->time_zone,
],
'end' => [
'dateTime' => $end,
'timeZone' => $this->time_zone,
],
'reminders' => [
'useDefault' => false,
'overrides' => [
['method' => 'email', 'minutes' => 24 * 60],
['method' => 'popup', 'minutes' => 10],
],
],
]);
$appointment = CustomerAppointment::where('event_id_google', $event_id)->first();
$appointment->created_by = Auth::user()->id;
$appointment->customer_location_id = $location->id;
$appointment->technician_id = $technician->id;
$appointment->customer_location_contact_id = $contact->id;
$appointment->title = $request->appointment_title;
$appointment->panctuality = $request->timeframe;
$appointment->notes = $request->notes;
$appointment->event_date = date('Y-m-d', strtotime($date_arr[0]));
if ($service) {
$appointment->customer_service_item_id = $service->id;
}
$appointment->event_id_google = $post->id;
$appointment->save();
$arr['success'] ='yes';
$arr['msg'] = 'Appointment posted to google calendar successfully';
return json_encode($arr);
exit;
}
function getAppointmentById($id)
{
$appointment = CustomerAppointment::where('event_id_google', $id)->first();
return json_encode($appointment);
exit;
}
function getEventById($id)
{
$calendar = new GoogleCalendar;
$event = $calendar->event($id);
$arr[] = ['title'=>html_entity_decode($event->getSummary()),
'start'=>$event->start->getDatetime(),
'end'=>$event->end->getDatetime()];
return json_encode($arr);
exit;
}
function editEvent($id, $cust_id)
{
return View('admin.appointment_edit', compact('id', 'cust_id'));
}
function deleteEvent(Request $request)
{
$eve_id = $request->event_id;
// $app_id = $request->app_id;
$calendar = new GoogleCalendar;
$event = $calendar->eventDelete($eve_id);
CustomerAppointment::where('event_id_google', $eve_id)->delete();
$arr['success']='yes';
return json_encode($arr);
exit;
}
}
<file_sep>/app/Modules/Assets/Http/Controllers/KnowledgeController.php
<?php
namespace App\Modules\Assets\Http\Controllers;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Modules\Crm\Http\Customer;
use App\Modules\Crm\Http\CustomerLocation;
use App\Modules\Assets\Http\Asset;
use App\Modules\Assets\Http\KnowledgePassword;
use App\Modules\Assets\Http\KnowledgeProcedure;
use App\Modules\Assets\Http\KnowledgeSerialNumber;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\View;
use App\Modules\Assets\Http\Tag;
use Datatables;
use App\Model\Role;
use App\Model\User;
use Auth;
use Mail;
use URL;
use Session;
class KnowledgeController extends Controller
{
public function index()
{
$customers_obj = Customer::with(['locations','locations.contacts'])->where('is_active', 1)->get();
$customers = [];
if ($customers_obj->count()) {
foreach ($customers_obj as $customer) {
$customers[$customer->id]=$customer->name.'('.$customer->email_domain.')';
//dd($user->id);
}
}
return view('assets::knowledge.index', compact('customers'));
//return "Controller Index";
}
function passwordsList()
{
$customers_obj = Customer::with(['locations','locations.contacts'])->get();
$customers = [];
if ($customers_obj->count()) {
foreach ($customers_obj as $customer) {
$customers[$customer->id]=$customer->name.'('.$customer->email_domain.')';
//dd($user->id);
}
}
$tag_records = Tag::all();
$tags =[];
foreach ($tag_records as $tag) {
$tags[$tag->id]=$tag->title;
//dd($user->id);
}
return view('assets::knowledge.passwords_list', compact('customers', 'tags'));
}
function passwordsIndex($id = null)
{
$global_date = $this->global_date;
if (!empty(Session::get('cust_id'))) {
$passwords = KnowledgePassword::with(['customer','tags','asset','vendor'])->where('knowledge_passwords.customer_id', Session::get('cust_id'))->select('knowledge_passwords.*');
} else {
$passwords = KnowledgePassword::with(['customer','tags','asset'])->selectRaw('distinct knowledge_passwords.*');
}
//dd($passwords);
return Datatables::of($passwords)
->addColumn('action', function ($password) {
$return = '<div class="btn-group">';
$return .= '<button type="button" class="btn btn-xs edit "
data-toggle="modal" data-id="'.$password->id.'" id="modaal" data-target="#modal-edit-knowledge-pass">
<i class="fa fa-edit " ></i></button>';
$return .=' <button type="button" class="btn btn-danger btn-xs"
data-toggle="modal" data-id="'.$password->id.'" id="modaal" data-target="#modal_password_delete">
<i class="fa fa-times-circle"></i></button></div>';
$return .= '</div>';
return $return;
})
->addColumn('customer', function ($password) {
if ($password->customer) {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span>'.$password->customer->name.'</span>
</button> ';
} else {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span></span>
</button>';
}
})
->addColumn('hashtags', function ($password) {
$return = '';
if ($password->tags) {
foreach ($password->tags as $tag) {
$return .='<button class="btn bg-gray-active btn-sm" type="button">
# <span>'.$tag->title.'</span>
</button> ';
}
}
return $return;
})
->addColumn('device', function ($password) {
$return = '';
if ($password->asset) {
$return .='<a class="btn btn-primary btn-sm" type="button" data-toggle="modal" data-id="'.$password->asset->id.'" id="modaal" data-target="#modal-show-asset">
<i class="fa fa-eye"></i> <span>'.$password->asset->name.'</span>
</a> ';
}
if ($password->vendor) {
$return .='<a class="btn btn-primary btn-sm" type="button" data-toggle="modal" data-vendor-id="'.$password->vendor_id.'" id="modaal" data-target="#modal-vendor-detatil">
<i class="fa fa-eye"></i> <span>'.$password->vendor->name.'</span>
</a> ';
}
return $return;
})
->editColumn('created_at', function ($password) use ($global_date) {
return date($global_date, strtotime($password->created_at));
})
->setRowId('id')
->make(true);
}
function proceduresList()
{
$customers_obj = Customer::with(['locations','locations.contacts'])->get();
$customers = [];
if ($customers_obj->count()) {
foreach ($customers_obj as $customer) {
$customers[$customer->id]=$customer->name.'('.$customer->email_domain.')';
//dd($user->id);
}
}
return view('assets::knowledge.procedures_list', compact('customers'));
}
/**
* [proceduresIndex description]
* @param int $id ID of the customer, if ID is 0 show unassigned procedures
*/
function proceduresIndex($id = null)
{
$global_date = $this->global_date;
if (!empty($id) || $id == 0) {
$procedures = KnowledgeProcedure::with(['customer'])->where('customer_id', $id);
} else {
$procedures = KnowledgeProcedure::with(['customer']);
}
return Datatables::of($procedures)
->addColumn('action', function ($procedure) {
$return = '<div class="btn-group"><button type="button" class="btn btn-xs edit "
data-toggle="modal" data-id="'.$procedure->id.'" id="modaal" data-target="#modal-edit-knowledge-procedure">
<i class="fa fa-edit"></i>
</button>
<a class="btn btn-xs btn-default" href="'.URL::route('admin.knowledge.procedure.detail', $procedure->id).'" target="_blank" ><i class="fa fa-eye"></i></a>
<button type="button" class="btn btn-danger btn-xs" data-toggle="modal" data-id="'.$procedure->id.'" id="modaal" data-target="#modal_procedure_delete"><i class="fa fa-times-circle"></i></button></div>';
return $return;
})
->editColumn('created_at', function ($procedure) use ($global_date) {
return date($global_date, strtotime($procedure->created_at));
})
->addColumn('customer', function ($procedure) {
if ($procedure->customer) {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i><span>'.$procedure->customer->name.'</span>
</button>';
} else {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i><span></span></button>';
}
})->make(true);
}
function serialnumberList()
{
$customers_obj = Customer::with(['locations','locations.contacts'])->get();
$customers = [];
if ($customers_obj->count()) {
foreach ($customers_obj as $customer) {
$customers[$customer->id]=$customer->name.'('.$customer->email_domain.')';
//dd($user->id);
}
}
return view('assets::knowledge.serial_numbers_list', compact('customers'));
}
function serialnumberIndex($id = null)
{
$global_date = $this->global_date;
if (!empty(Session::get('cust_id'))) {
$serial_numbers = KnowledgeSerialNumber::with(['customer'])->where('customer_id', Session::get('cust_id'));
} else {
$serial_numbers = KnowledgeSerialNumber::with(['customer']);
}
return Datatables::of($serial_numbers)
->addColumn('action', function ($serial_number) {
$return = '<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-id="'.$serial_number->id.'" id="modaal" data-target="#modal-edit-serial-number">
<i class="fa fa-pencil"></i> Edit
</button>
<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-id="'.$serial_number->id.'" id="modaal" data-target="#modal-show-knowledge" data-type="serial_number">
<i class="fa fa-eye"></i> View
</button>
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-id="'.$serial_number->id.'" id="modaal" data-target="#modal_serial_delete">
<i class="fa fa-times-circle"></i> Delete
</button>';
return $return;
})
->editColumn('created_at', function ($serial_number) use ($global_date) {
return date($global_date, strtotime($serial_number->created_at));
})
->addColumn('customer', function ($serial_number) {
if ($serial_number->customer) {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span>'.$serial_number->customer->name.'</span>
</button>';
} else {
return '<button class="btn bg-gray-active btn-sm" type="button">
<i class="fa fa-user"></i>
<span></span>
</button>';
}
})
->make(true);
}
public function storePassword(Request $request)
{
//dd($request->all());
$this->validate(
$request,
[
// 'system' => 'required',
'login' => 'required',
'password' => '<PASSWORD>',
]
);
$password = new KnowledgePassword();
if ($request->customer) {
$password->customer_id = $request->customer;
}
$password->login = $request->login;
$password->password = $request->password;
$password->notes = $request->notes;
$password->save();
$password->tags()->sync($request->tags);
$arr['success'] = 'Password added sussessfully';
return json_encode($arr);
exit;
}
function storePasswordTag(Request $request)
{
$this->validate(
$request,
[
'tag' => 'required',
]
);
$tag = new Tag();
$tag->title = $request->tag;
$tag->save();
$arr['success'] = 'Tag added sussessfully';
return json_encode($arr);
exit;
}
function getTags()
{
$tag_records = Tag::all();
foreach ($tag_records as $tag) {
$tags[]=['id'=>$tag->id,
'text'=>$tag->title];
//dd($user->id);
}
return json_encode($tags);
exit;
}
public function editPassword($id)
{
$password = KnowledgePassword::with(['customer','tags'])->where('id', $id)->first();
$arr['password'] = $<PASSWORD>;
return json_encode($arr);
exit;
}
public function updatePassword(Request $request)
{
//dd($request->all());
$id = $request->id;
$this->validate(
$request,
[
'login' => 'required',
'password' => '<PASSWORD>',
]
);
$password = KnowledgePassword::find($id);
//$password->system = $request->system;
if ($request->customer) {
$password->customer_id = $request->customer;
}
$password->login = $request->login;
$password->password = $request->password;
$password->notes = $request->notes;
$password->save();
if ($request->tags) {
$password->tags()->sync($request->tags);
}
$arr['success'] = 'Password added sussessfully';
return json_encode($arr);
exit;
}
public function storeProcedure(Request $request)
{
//dd($request->all());
$this->validate(
$request,
[
'title' => 'required',
]
);
$procedure = new KnowledgeProcedure();
$procedure->title = $request->title;
if ($request->customer) {
$procedure->customer_id = $request->customer;
}
$procedure->procedure = $request->procedure;
$procedure->image_dir = session('imageId');
$procedure->save();
$arr['success'] = 'Procedure added sussessfully';
// Make the image directory
$img_dir = storage_path('image_upload/knowledge/'.$procedure->image_dir);
if (!File::exists($img_dir)) {
File::makeDirectory($img_dir);
}
// Destroy the session variable for the image storage directory
session()->forget('imageId');
return json_encode($arr);
exit;
}
public function editProcedure($id)
{
$procedure = KnowledgeProcedure::with(['customer'])->where('id', $id)->first();
$arr['procedure'] = $procedure;
return json_encode($arr);
exit;
}
public function updateProcedure(Request $request)
{
$id = $request->id;
//dd($request->all());
$this->validate(
$request,
[
'title' => 'required',
]
);
$procedure = KnowledgeProcedure::find($id);
$procedure->title = $request->title;
$procedure->customer_id = $request->customer;
$procedure->procedure = $request->procedure;
$procedure->image_dir = $request->image_dir;
$procedure->save();
$arr['success'] = 'Procedure updated sussessfully';
// Destroy the session variable for the image storage directory
session()->forget('imageId');
return json_encode($arr);
exit;
}
public function storeSerialNumber(Request $request)
{
//dd($request->all());
$this->validate(
$request,
[
'title' => 'required',
'serial_number' => 'required'
]
);
$password = new KnowledgeSerialNumber();
$password->title = $request->title;
if ($request->customer) {
$password->customer_id = $request->customer;
}
$password->serial_number = $request->serial_number;
$password->notes = $request->notes;
$password->save();
$arr['success'] = 'Serial number added sussessfully';
return json_encode($arr);
exit;
}
public function editSerialNumber($id)
{
$serial_number = KnowledgeSerialNumber::with(['customer'])->where('id', $id)->first();
$arr['serial_number'] = $serial_number;
return json_encode($arr);
exit;
}
public function updateSerialNumber(Request $request)
{
$id = $request->id;
//dd($request->all());
$this->validate(
$request,
[
'title' => 'required',
'serial_number' => 'required'
]
);
$password = KnowledgeSerialNumber::find($id);
$password->title = $request->title;
if ($request->customer) {
$password->customer_id = $request->customer;
}
$password->serial_number = $request->serial_number;
$password->notes = $request->notes;
$password->save();
$arr['success'] = 'Serial number updated sussessfully';
return json_encode($arr);
exit;
}
function procedureDetail($id)
{
$procedure = KnowledgeProcedure::with(['customer'])->where('id', $id)->first();
return view('assets::knowledge.show_procedure', compact('procedure'));
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($type, $id)
{
if ($type=='procedure') {
$procedure = KnowledgeProcedure::with(['customer'])->where('id', $id)->first();
$type = 'procedure';
$arr['html_content'] = view('assets::knowledge.show_partial', compact('procedure', 'type'))->render();
//$arr['content'] = $procedure;
$arr['type'] = $type;
}
if ($type=='serial_number') {
$serial_number = KnowledgeSerialNumber::with(['customer'])->where('id', $id)->first();
$type = 'serial_number';
$arr['html_content'] = view('assets::knowledge.show_partial', compact('serial_number', 'type'))->render();
//$arr['content'] = $serial_number;
$arr['type'] = $type;
}
return json_encode($arr);
exit;
//
}
public function ajaxDetails($id)
{
$cusid = Session::get('cust_id');
$password = KnowledgePassword::with(['customer','tags'])
->where('id', $id)->first();
return view('assets::knowledge.detail_partial', compact('password'));
}
public function deletePassword(Request $request)
{
$password = KnowledgePassword::find($request->id);
if ($password->vendor_id !='') {
$arr['error'] = "Password can not be deleted, it is associated with Vendor ID # $password->vendor_id.";
} elseif ($password->asset_id !='') {
$arr['error'] = "Password can not be deleted, it is associated with Asset ID # $password->asset_id.";
} else {
$password->delete();
$arr['success'] = 'Password deleted sussessfully';
}
return json_encode($arr);
exit;
}
public function deleteProcedure(Request $request)
{
$procedure = KnowledgeProcedure::find($request->id);
$path = storage_path('image_upload/knowledge/'.$procedure->image_dir);
if (!empty($procedure->image_dir)) {
if (File::deleteDirectory($path)) {
$procedure->delete();
$arr['success'] = 'Procedure deleted sussessfully';
return json_encode($arr);
}
}
return '{"success":"There was an error deleting the procedure."}';
exit;
}
public function deleteSerialNumber(Request $request)
{
//
$serial_number = KnowledgeSerialNumber::find($request->id);
$serial_number->delete();
$arr['success'] = 'Serial number deleted sussessfully';
return json_encode($arr);
exit;
}
private function generateGuid()
{
$s = strtoupper(md5(uniqid(rand(), true)));
$guidText =
substr($s, 0, 8) . '-' .
substr($s, 8, 4) . '-' .
substr($s, 12, 4). '-' .
substr($s, 16, 4). '-' .
substr($s, 20);
return $guidText;
}
/**
* Returns a unique ID used for generating an image storage directory
* specific to a procedure. This way when the procedure is deleted we
* can delete all the associated images.
*
* @return [type] [description]
*/
public function getImageDirUniqid()
{
$id = uniqid();
if (empty(session('imageId'))) {
session(['imageId' => $id]);
return json_encode(['imageId' => $id]);
} else {
return json_encode(['imageId' => session('imageId')]);
}
}
public function storeImage(Request $request)
{
$allowed = ['png', 'jpg', 'gif'];
$rules = [
'file' => 'required|image|mimes:jpeg,jpg,png,gif'
];
if (!empty($request->image_dir)) {
if ($request->hasFile('file')) {
$image_dir = $request->image_dir;
$file = $request->file('file');
if (!in_array($file->guessExtension(), $allowed) &&
session('imageId') != $image_dir) {
return '{"error":"Invalid File type"}';
} else {
$guid = $this->generateGuid();
$fileName = $guid .'.'. $file->guessExtension();
$path = storage_path('image_upload/knowledge/'.$image_dir);
// Make image folder if it does not exist
if (Storage::MakeDirectory($path, 0775, true)) {
if ($file->move($path, $fileName)) {
$url = parse_url(URL::route('admin.knowledge.get.image', ['filename' => $fileName, 'folder' => $image_dir ]), PHP_URL_PATH);
//$url = url($purl);
return json_encode([
'url' => $url,
'dir' => $image_dir,
'id' => $fileName
], JSON_UNESCAPED_SLASHES);
exit;
}
} else {
return '{"error":"There was an error saving the file"}';
}
}
} else {
return '{"error":"Invalid File type"}';
}
} else {
return '{"error":"Unable to upload file"}';
}
}
public function retrieveImage($folder, $filename)
{
$path = storage_path('image_upload/knowledge/'.$folder.'/'.$filename);
return Image::make($path)->response();
}
public function deleteImage($folder, $filename)
{
$path = storage_path('image_upload/knowledge/'.$folder.'/'.$filename);
if (File::delete($path)) {
return '{"status":"success"}';
}
return '{"status":"error"}';
}
}
<file_sep>/app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\SignUpPostRequest;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use App\Model\User;
use App\Model\Role;
use Auth;
class UserController extends Controller
{
//private $admin = 1;
private $controller = 'user';
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
/* $timezone_identifiers = \DateTimeZone::listIdentifiers();
echo '<pre>';
print_r($timezone_identifiers);
exit;*/
$controller = $this->controller;
//$users = User::where('role_id','<>',$this->admin)->get();
$users = User::get();
return view('admin.users.index', compact('users', 'controller'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$roles = Role::select(['id','display_name'])->get();
return view('admin.users.add', compact('roles'));
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(SignUpPostRequest $request)
{
//dd($request->all());
$user = new User;
$user->f_name = $request->f_name;
$user->l_name = $request->l_name;
$user->email = $request->email;
$user->password = <PASSWORD>($request->password);
$user->save();
if ($request->role) {
$user->attachRole($request->role);
}
//role
return redirect()->intended('admin/user');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//$user = User::where('id',$id)->where('role_id','<>',$this->admin)->first();
$user = User::find($id);
$roles = Role::select(['id','display_name'])->get();
//dd($user->roles);
if ($user->roles) {
foreach ($user->roles as $role) {
$user_role = $role->id;
}
}
return view('admin.users.add', compact('user', 'roles', 'user_role'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(SignUpPostRequest $request, $id)
{
//$flight = App\Flight::find(1);
$user = User::find($id);
$user->f_name = $request->f_name;
$user->l_name = $request->l_name;
$user->email = $request->email;
if (!empty($request->password)) {
$user->password = <PASSWORD>($request->password);
}
$user->detachRoles($user->roles);
if ($request->role) {
$user->attachRole($request->role);
}
$user->save();
return redirect()->intended('admin/user');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
//dd($id);
//dd($request->id);
$id = $request->id;
$user = User::findorFail($id);
$user->detachRoles($user->roles);
$user->delete();
//Session::flash('flash_message', 'User successfully deleted!');
return redirect()->intended('admin/user');
}
}
<file_sep>/app/Modules/Assets/Http/knowledgePasswordTag.php
<?php
namespace App\Modules\Assets\Http;
use Illuminate\Database\Eloquent\Model;
class KnowledgePasswordTag extends Model
{
//
}
<file_sep>/app/Modules/Vendor/Http/Vendor.php
<?php
namespace App\Modules\Vendor\Http;
use Illuminate\Database\Eloquent\Model;
class Vendor extends Model
{
public function customers()
{
return $this->belongsToMany('App\Modules\Crm\Http\Customer')->withTimestamps()
->withPivot('id', 'auth_contact_name', 'phone_number', 'account_number', 'portal_url', 'notes', 'location_id');
}
public function contacts()
{
return $this->hasMany('App\Modules\Vendor\Http\VendorContact');
}
public function vend_cust_loc()
{
return $this->belongsToMany('App\Modules\Crm\Http\CustomerLocation', 'customer_vendor', 'vendor_id', 'location_id');
}
public function location()
{
return $this->belongsToMany('App\Modules\Crm\Http\CustomerLocation', 'customer_vendor', 'vendor_id', 'location_id');
}
public function password()
{
return $this->hasOne('App\Modules\Assets\Http\KnowledgePassword', 'vendor_id');
}
//cascading password delete with vendor delete
/*protected static function boot() {
parent::boot();
static::deleting(function($vendor) { // before delete() method call this
$vendor->password()->delete();
// do the rest of the cleanup...
});
}*/
}
<file_sep>/public/phpmyadmin/libraries/php-gettext/streams.php
../../../php/php-gettext/streams.php<file_sep>/app/Modules/Employee/Http/Leave.php
<?php
namespace App\Modules\Employee\Http;
use Illuminate\Database\Eloquent\Model;
class Leave extends Model
{
public function poster()
{
return $this->belongsTo('App\Model\User', 'posted_by');
}
public function applicant()
{
return $this->belongsTo('App\Model\User', 'posted_for');
}
public function action_taker()
{
return $this->belongsTo('App\Model\User', 'action_taken_by');
}
public function user()
{
return $this->belongsTo('App\Model\User', 'posted_for');
}
}
<file_sep>/app/Console/Commands/PendingLeaveNotification.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Modules\Employee\Http\Employee;
use App\Modules\Employee\Http\Leave;
use App\Model\Config;
use Auth;
use Mail;
class PendingLeaveNotification extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'email:leavenotify';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$leaves = Leave::where('status', 'pending')->with(['user', 'user.roles'])->get();
//dd($leaves[0]->user->roles);
//$gmail_address='<EMAIL>';
$smtp_arr = Config::where('title', 'smtp')->get();
$email_body='wasdasdasdasdasd';
$smtp =[];
foreach ($smtp_arr as $value) {
if ($value->key=='server_address') {
$server_address = $value->value;
}
if ($value->key=='gmail_address') {
$gmail_address = $value->value;
}
if ($value->key=='gmail_password') {
$password = $value->value;
}
if ($value->key=='port') {
$port= $value->value;
}
}
config(['mail.driver' => 'smtp',
'mail.host' => $server_address,
'mail.port' => $port,
'mail.encryption' => 'ssl',
'mail.username' => $gmail_address,
'mail.password' => <PASSWORD>,
'mail.from' =>['address'=>$gmail_address,'name'=>'Nexgentec']]);
Mail::send('crm::ticket.email.response', ['body'=>$email_body], function ($message) use ($gmail_address) {
/* $swiftMessage = $message->getSwiftMessage();
$headers = $swiftMessage->getHeaders();
$headers->addTextHeader('In-Reply-To', $ticket->gmail_msg_id);
$headers->addTextHeader('References', $ticket->gmail_msg_id);*/
// $message->getHeaders()->addTextHeader('In-Reply-To', $ticket->gmail_msg_id);
// $message->getHeaders()->addTextHeader('References', $ticket->gmail_msg_id);
// $message->getHeaders()->addTextHeader('response_id', $response->id);
$message->from(trim($gmail_address), 'waqas saeed');
$message->to('<EMAIL>', 'waqas saeed');
$message->subject('pending email notification');
});
}
}
<file_sep>/app/Listeners/refreshGoogleAuthToken.php
<?php
namespace App\Listeners;
use App\Events\updateGoogleAuthToken;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Model\Config;
use App\Services\GoogleGmail;
class refreshGoogleAuthToken
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param updateGoogleAuthToken $event
* @return void
*/
public function handle(updateGoogleAuthToken $event)
{
//
$google_auth_arr = Config::where('title', 'google_auth')->get();
$google_auth =[];
foreach ($google_auth_arr as $value) {
if ($value->key=='gmail_auth_client_id') {
$google_auth['gmail_auth_client_id'] = $value->value;
}
if ($value->key=='gmail_auth_client_secret') {
$google_auth['gmail_auth_client_secret'] = $value->value;
}
}
$file_path = base_path('resources/assets');
$file['client_id'] = $google_auth['gmail_auth_client_id'];
$file['client_secret'] = $google_auth['gmail_auth_client_secret'];
$file['redirect_uris'] = [\URL::route('get_token')];
$str_to_json['web'] = $file;
// dd($file);
//dd($file_path."client_secret.json");
try {
//file_put_contents($file_path."client_secret.json", json_encode($file);
$myfile = fopen($file_path."/client_secret.json", "w") or die("Unable to open file!");
fwrite($myfile, json_encode($str_to_json, JSON_UNESCAPED_SLASHES));
fclose($myfile);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
$gmail = new GoogleGmail('reset');
//dd($response);
return compact("gmail");
}
}
<file_sep>/app/Modules/Crm/Http/CustomerLocationContact.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class CustomerLocationContact extends Model
{
public function location()
{
return $this->belongsTo('App\Modules\Crm\Http\CustomerLocation');
}
}
<file_sep>/app/Modules/Crm/Http/Product.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $table = 'products';
public function assigned_tickets()
{
return $this->belongsToMany('App\Modules\Crm\Http\Customer');
}
}
<file_sep>/app/Http/Controllers/TestEmailController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Model\Config;
use App\Services\GoogleGmail;
use App\Services\ImapGmail;
use URL;
use Mail;
use Auth;
class TestEmailController extends Controller
{
function sendEmail()
{
$smtp_arr = Config::where('title', 'smtp')->get();
$smtp =[];
foreach ($smtp_arr as $value) {
if ($value->key=='server_address') {
$server_address = $value->value;
}
if ($value->key=='gmail_address') {
$gmail_address = $value->value;
}
if ($value->key=='gmail_password') {
$password = $value->value;
}
if ($value->key=='port') {
$port= $value->value;
}
}
config(['mail.driver' => 'smtp',
'mail.host' => $server_address,
'mail.port' => $port,
'mail.encryption' => 'ssl',
'mail.username' => $gmail_address,
'mail.password' => $<PASSWORD>,
'mail.from' =>['address'=>$gmail_address,'name'=>'Nexgentec']
]);
//echo '<pre>';
//dd(config('mail'));
Mail::send('crm::ticket.email.response', ['body'=>'just test test email, by clicking test email button on show ticket page.'], function ($m) use ($gmail_address) {
$m->from($gmail_address, 'Nexgentec');
$m->to('<EMAIL>', '<NAME>')->subject('Your Reminder!');
});
dd(Mail::failures());
/* if( count(Mail::failures()) > 0 ) {
echo "There was one or more failures. They were: <br />";
foreach(Mail::failures() as $failure) {
echo " - $failure <br />";
}
} else {
echo "No errors, all sent successfully!";
}*/
}
}
<file_sep>/app/Modules/Employee/Http/Raise.php
<?php
namespace App\Modules\Employee\Http;
use Illuminate\Database\Eloquent\Model;
class Raise extends Model
{
protected $table = 'raises';
/* public function raise()
{
return $this->hasMany('App\Modules\Employee\Http\Raise');
}*/
}
<file_sep>/app/Modules/Crm/Http/Controllers/TicketsStatus.php
<?php
namespace App\Modules\Crm\Http\Controllers;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Modules\Crm\Http\TicketStatus;
use App\Modules\Crm\Http\Ticket;
class TicketsStatus extends Controller
{
public function index()
{
$statuses = TicketStatus::all();
//dd($statuses);
if (\Request::ajax()) {
return view('crm::ticketstatus.ajax_index', compact('statuses'))->render();
}
return view('crm::settings.ticketstatus.index', compact('statuses'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('crm::ticketstatus.add');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate(
$request,
[
'title'=>'required',
]
);
$status = new TicketStatus;
$status->title = $request->title;
$status->color_code = $request->color_code;
$status->save();
$arr['success'] = 'Status added successfully';
return json_encode($arr);
exit;
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$status = TicketStatus::find($id);
//return view('crm::ticketstatus.add',compact('status'));
$arr['status'] = $status ;
//$arr['success'] = 'Status updated successfully';
return json_encode($arr);
exit;
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request)
{
$id = $request->status_id;
//dd($request->all());
$status = TicketStatus::find($id);
$this->validate(
$request,
[
'title'=>'required',
]
);
$status->title = $request->title;
$status->color_code = $request->color_code;
$status->save();
$arr['success'] = 'Status updated successfully';
return json_encode($arr);
exit;
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function ajaxDelete(Request $request)
{
$status = TicketStatus::find($request->id);
//dd($status);
//$status->tickets()->sync($id);
foreach ($status->tickets as $ticket) {
$ticket = Ticket::find($ticket->id);
$ticket->ticket_status_id = null;
$ticket->save();
# code...
}
$status->delete();
$arr['success'] = 'Status deleted successfully';
return json_encode($arr);
exit;
}
}
<file_sep>/app/Modules/Crm/Database/2015_12_31_143140_contacts.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Contacts extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('customer_location_contacts', function (Blueprint $table) {
$table->increments('id');
$table->integer('customer_location_id');
$table->date('created_at');
$table->date('updated_at');
$table->string('f_name', 15);
$table->string('l_name', 15);
$table->string('title', 20);
$table->string('email', 30);
$table->string('phone', 15);
$table->string('mobile', 15);
$table->tinyInteger('is_poc');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('customer_location_contacts');
}
}
<file_sep>/app/Modules/Crm/Resources/Views/ticket/index.blade (backup without datatables).php
@extends('admin.main')
@section('content')
<section class="content-header">
<h1>
Tickets
{{-- <small>preview of simple tables</small> --}}
</h1>
<ol class="breadcrumb">
<li>
<i class="fa fa-dashboard"></i> <a href="/admin/dashboard">Dashboard</a>
</li>
<li class="active">
<i class="fa fa-table"></i> Tickets
</li>
</ol>
</section>
<section class="content">
<div class="row">
<div class="col-xs-12">
<div id="msg"></div>
<a href=" {{ URL::route('admin.ticket.create')}}" class="btn btn-primary pull-right"> Create New Ticket</a>
<a href="javascript:;" onclick="import_emails()" class="btn btn-primary pull-left"> <i class="fa fa-download"></i> Import Emails</a>
<img id="load_img_z" src="{{asset('img/loader.gif')}}" style="display:none" />
<div class="clearfix"></div>
<div class="box">
<div class="box-header">
<h3 class="box-title">Tickets listing</h3>
</div><!-- /.box-header -->
<div class="box-body table-responsive no-padding">
<table class="table table-hover">
<tr>
<th>ID</th>
<th>Title</th>
<th>Created By</th>
<th>Customer info</th>
<th>Created on</th>
<th>Status</th>
<th>Assigned to</th>
<th>Priority</th>
<th>Actions</th>
</tr>
@foreach($tickets as $ticket)
<tr>
<td>{{ $ticket->id }}.</td>
<td>{{ $ticket->title }}</td>
<td>@if($ticket->entered_by){{ $ticket->entered_by->f_name }}
@elseif($ticket->type =='email') <button type="button" class="btn bg-gray-active btn-sm">
<span>{{'system'}}</span>
</button>
@endif</td>
<td>
<button type="button" class="btn bg-gray-active btn-sm">
<span>
@if($ticket->customer)
<i class="fa fa-user"></i> {{ $ticket->customer->name }}
@elseif($ticket->email)
<i class="fa fa-envelope"></i> {{ $ticket->email }}@endif</span>
</button>
@if($ticket->location)
<button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-map-marker"></i>
<span>{{ $ticket->location->location_name }}</span>
</button>
@endif
@if($ticket->service_item)
<button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-gears"></i>
<span>{{ $ticket->service_item->title }}</span>
</button>
@endif
</td>
<td>{{ date('d/m/Y',strtotime($ticket->created_at)) }}</td>
<td><button type="button" class="btn bg-gray-active btn-sm">
<span>{{$ticket->status}}</span>
</button>
</td>
<td>
@if($ticket->assigned)
@foreach($ticket->assigned_to as $employee)
<button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-user"></i>
<span>{{ $employee->f_name }}</span>
</button>
@endforeach
@endif
</td>
<?php
//$btn_class = '';
//if($ticket->priority == 'low')
$btn_class = 'bg-gray';
if($ticket->priority == 'normal')
$btn_class = 'bg-blue';
if($ticket->priority == 'high')
$btn_class = 'bg-green';
if($ticket->priority == 'urgent')
$btn_class = 'bg-yellow';
if($ticket->priority == 'critical')
$btn_class = 'bg-red';
?>
<td><button type="button" class="btn {{$btn_class}} btn-sm">
<span>{{$ticket->priority}}</span>
</button>
</td>
<td>
<a href="{{ URL::route('admin.ticket.show',$ticket->id)}}" class="btn btn-sm btn-primary"><i class="fa fa-eye"></i> View</a>
<button type="button" class="btn btn-danger btn-sm"
data-toggle="modal" data-id="{{$ticket->id}}" id="modaal" data-target="#modal-delete-ticket">
<i class="fa fa-times-circle"></i>
Delete
</button>
</td>
</tr>
@endforeach
{{-- <tr>
<td>183</td>
<td><NAME></td>
<td>11-7-2014</td>
<td><span class="label label-success">Approved</span></td>
<td>Bacon ipsum dolor sit amet salami venison chicken flank fatback doner.</td>
</tr> --}}
</table>
<div class="col-xs-12">
{!! $tickets->render() !!}
</div>
</div><!-- /.box-body -->
</div><!-- /.box -->
</div>
</div>
</section>
@include('crm::ticket.delete_modal')
@endsection
@section('script')
<script>
function import_emails()
{
//console.log(id);
$('#load_img_z').show();
$.get(APP_URL+'/admin/crm/ticket/getEmails',function( response ) {
//console.log(response);
if(response.success)
{
$('#msg').html('<div class="alert alert-success"><ul><li>'+response.success+'</li></ul></div>');
$('#load_img_z').hide();
}
if(response.error)
{
$('#msg').html('<div class="alert alert-danger"><ul><li>'+response.error_msg+'</li></ul></div>');
$('#load_img_z').hide();
}
//$('#service_items_table').html(response.html_contents);
},"json"
);
alert_hide();
//setTimeout("location.reload(true);",10000);
}
$(function () {
$('.pagination').addClass('pull-right');
});
</script>
@endsection<file_sep>/app/Modules/Employee/Http/Controllers/RaiseController.php
<?php
namespace App\Modules\Employee\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use App\Modules\Employee\Http\Employee;
use App\Modules\Employee\Http\Requests\RaisePostRequest;
use App\Model\Role;
use App\Model\User;
use App\Modules\Employee\Http\Raise;
class RaiseController extends Controller
{
private $controller = 'raise';
public function index()
{
$controller = $this->controller;
$employees = User::where('type', 'employee')->get();
return view('employee::admin.index', compact('employees', 'controller'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(RaisePostRequest $request)
{
$raise = new Raise;
$raise->effective_date = date("Y-m-d", strtotime($request->effective_date));
$raise->old_pay = $request->old_pay;
$raise->new_pay = $request->new_pay;
$raise->user_id = $request->user_id;
$raise->notes = $request->notes;
$raise->save();
//return redirect()->intended('admin/employee');
$arr['success'] = 'Record added sussessfully';
echo json_encode($arr);
exit;
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(EmployeePostRequest $request, $id)
{
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
//dd($id);
//dd($request->id);
$id = $request->id;
$raise = Raise::findorFail($id);
$raise->delete();
//Session::flash('flash_message', 'User successfully deleted!');
//return redirect()->intended('admin/employee');
$arr['success'] = 'Record Deleted sussessfully';
echo json_encode($arr);
exit;
}
private function timezone_list()
{
static $timezones = null;
if ($timezones === null) {
$timezones = [];
$offsets = [];
$now = new \DateTime();
foreach (\DateTimeZone::listIdentifiers(\DateTimeZone::PER_COUNTRY, 'US') as $timezone) {
$now->setTimezone(new \DateTimeZone($timezone));
$offsets[] = $offset = $now->getOffset();
$timezones[$timezone] = '(' . $this->format_GMT_offset($offset) . ') ' . $this->format_timezone_name($timezone);
}
array_multisort($offsets, $timezones);
}
return $timezones;
}
private function format_GMT_offset($offset)
{
$hours = intval($offset / 3600);
$minutes = abs(intval($offset % 3600 / 60));
return 'GMT' . ($offset ? sprintf('%+03d:%02d', $hours, $minutes) : '');
}
private function format_timezone_name($name)
{
$name = str_replace('/', ', ', $name);
$name = str_replace('_', ' ', $name);
$name = str_replace('St ', 'St. ', $name);
return $name;
}
}
<file_sep>/app/Modules/Crm/Http/TicketStatus.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class TicketStatus extends Model
{
public function tickets()
{
return $this->hasMany('App\Modules\Crm\Http\Ticket');
}
}
<file_sep>/app/Services/FilemanagerService.php
<?php
namespace App\Services;
use GuillermoMartinez\Filemanager\Filemanager;
use URL;
class FilemanagerService extends Filemanager
{
private $config;
private $c_folder;
private $fileDetails = [
"urlfolder" => '',
"filename" => "",
"filetype" => "",
"isdir" => false,
"lastmodified" => "",
"previewfull" => "",
"preview" => "",
"size" => "",
];
function __construct($filemanager)
{
$this->c_folder = $filemanager['c_folder'];
$this->config = $filemanager;
parent::__construct($filemanager);
}
public function fileInfo($file, $path)
{
//dd($path);
if ($file->isReadable()) {
$item = $this->fileDetails;
$item["filename"] = $file->getFilename();
$item["filetype"] = $file->getExtension();
$item["lastmodified"] = $file->getMTime();
$item["size"] = $file->getSize();
if ($file->isDir()) {
$item["filetype"] = '';
$item["isdir"] = true;
$item["urlfolder"] = $path.$item["filename"].'/';
$item['preview'] = '';
} elseif ($file->isFile()) {
$thumb = $this->createThumb($file, $path);
$folder = $this->c_folder;
if ($thumb) {
$item['preview'] = url(URL::route('get.user_files.thumb', ['folder' => $folder,'filename' => $path.$thumb]));
//original Code
//$item['preview'] = $this->config['url'].$this->config['source'].'/_thumbs'.$path.$thumb;
}
$item['previewfull'] = url(URL::route('get.user_files.file', ['folder' => $folder,'filename' => $path.$item["filename"]]));
//original Code
//$item['previewfull'] = $this->config['url'].$this->config['source'].$path.$item["filename"];
//dd(URL::route('get.user_files.thumb', ['folder' => $folder,'filename' => $path.$thumb]));
}
return $item;
} else {
return ;
}
}
public function upload($file, $path)
{
if ($this->validExt($file->getClientOriginalName())) {
//echo $this->getMaxUploadFileSize();
//exit;
if ($file->getClientSize() > ($this->getMaxUploadFileSize() * 1024 * 1024)) {
$result = ["query"=>"BE_UPLOAD_FILE_SIZE_NOT_SERVER","params"=>[$file->getClientSize()]];
$this->setInfo(["msg"=>$result]);
if ($this->config['debug']) {
$this->_log(__METHOD__." - file size no permitido server: ".$file->getClientSize());
}
return ;
} elseif ($file->getClientSize() > ($this->config['upload']['size_max'] * 1024 * 1024)) {
$result = ["query"=>"BE_UPLOAD_FILE_SIZE_NOT_PERMITIDO","params"=>[$file->getClientSize()]];
$this->setInfo(["msg"=>$result]);
if ($this->config['debug']) {
$this->_log(__METHOD__." - file size no permitido: ".$file->getClientSize());
}
return ;
} else {
if ($file->isValid()) {
$dir = $this->getFullPath().$path;
$namefile = $file->getClientOriginalName();
//dd($namefile);
$namefile = $this->clearNameFile($namefile);
$ext = $this->getExtension($namefile);
//$nametemp = $namefile;
$nametemp = $this->removeExtension($namefile) . '_' .time(). '.' . $ext ;
if ($this->config["upload"]["overwrite"] ==false) {
$i=0;
while (true) {
$pathnametemp = $dir.$nametemp;
if (file_exists($pathnametemp)) {
$i++;
//$nametemp = $this->removeExtension( $namefile ) . '_' . $i . '.' . $ext ;
$nametemp = $this->removeExtension($namefile) . '_' .time(). '.' . $ext ;
} else {
break;
}
}
}
$file->move($dir, $nametemp);
$file = new \SplFileInfo($dir.$nametemp);
return $file;
}
}
} else {
if ($this->config['debug']) {
$this->_log(__METHOD__." - file extension no permitido: ".$file->getExtension());
}
}
}
}
<file_sep>/config/settings.php
<?php
return [
'clicktocallurl' => 'https://ngvoip.us/app/click_to_call/click_to_call.php?username=netpro25&password=<PASSWORD>&src_cid_name=NGDialout&src_cid_number=3522243866&dest_cid_name=NexgenTec&dest_cid_number=3522243866&auto_answer=true&rec=false&ringback=us-ring'
];
<file_sep>/app/Http/Controllers/PermissionsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Model\Permission;
use Datatables;
use URL;
class PermissionsController extends Controller
{
private $controller = 'permissions';
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$controller = $this->controller;
//$permissions = Permission::select(['id','name','display_name','description','created_at'])->paginate(10);;
if (\Request::ajax()) {
return view('admin.permissions.ajax_index', compact('controller'))->render();
}
return view('admin.permissions.index', compact('controller'));
}
public function ajaxDataIndex()
{
$global_date = $this->global_date;
//$controller = $this->controller;
$permissions =Permission::select(['id','name','display_name','description','created_at']);
return Datatables::of($permissions)
->addColumn('action', function ($permission) {
$return = '<div class="btn-group"> <button type="button" class="btn btn-xs"
data-toggle="modal" data-id="'.$permission->id.'" id="modaal" data-target="#modal-edit-permission">
<i class="fa fa-edit"></i>
</button>
<button type="button" class="btn btn-danger btn-xs"
data-toggle="modal" data-id="'.$permission->id.'" id="modaal" data-target="#modal-delete-permission-ajax">
<i class="fa fa-times-circle"></i>
</button></div>';
return $return;
})
->editColumn('created_at', function ($permission) use ($global_date) {
return date($global_date, strtotime($permission->created_at));
})
->make(true);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.permissions.add');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|unique:permissions|max:50',
'display_name' => 'required',
'description' => 'required',
]);
$permission = new Permission();
$permission->name = $request->name;
$permission->display_name = $request->display_name; // optional
$permission->description = $request->description; // optional
$permission->save();
//print_r($request->all()); die('asdas');
return redirect()->route('admin.setting.permissions');
//$arr['success'] = 'Permission created successfully';
//return json_encode($arr);
exit;
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$permission = Permission::where('id', $id)->where('id', $id)->first();
//dd($permission);
//echo $user->name;
//exit;
//return view('admin.permissions.add',compact('permission'));
$arr['permission'] = $permission;
return json_encode($arr);
exit;
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request)
{
$id = $request->permission_id_edit;
$this->validate($request, [
'name' => 'required|max:50|unique:permissions,name,'.$id,
'display_name' => 'required',
'description' => 'required',
]);
$permission = Permission::find($id);
$permission->name = $request->name;
$permission->display_name = $request->display_name; // optional
$permission->description = $request->description; // optional
$permission->save();
//return redirect()->route('admin.permissions.index');
$arr['success'] = 'Permission updated successfully';
return json_encode($arr);
exit;
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
//dd($id);
//dd($request->id);
$id = $request->id;
$permission = Permission::findorFail($id);
$permission->delete();
//Session::flash('flash_message', 'User successfully deleted!');
return redirect()->intended('admin/permissions');
}
public function ajaxDelete($id)
{
//dd($id);
//dd($request->id);
//$id = $request->id;
$permission = Permission::findorFail($id);
$permission->delete();
//Session::flash('flash_message', 'User successfully deleted!');
//return redirect()->intended('admin/permissions');
$arr['success'] = 'Permission deleted successfully';
return json_encode($arr);
exit;
}
}
<file_sep>/app/Modules/Vendor/Http/VendorCustomerLocation.php
<?php
namespace App\Modules\Vendor\Http;
use Illuminate\Database\Eloquent\Model;
class VendorCustomerLocation extends Model
{
protected $table = 'customer_vendor';
public function vendor()
{
return $this->belongsTo('App\Modules\Vendor\Http\Vendor', 'vendor_id');
}
public function customer()
{
return $this->belongsTo('App\Modules\Crm\Http\Customer', 'customer_id');
}
public function location()
{
return $this->belongsTo('App\Modules\Crm\Http\CustomerLocation', 'location_id');
}
}
<file_sep>/app/Listeners/CalculateNewLeavesPosted.php
<?php
namespace App\Listeners;
use App\Events\countNewLeaves;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Modules\Employee\Http\Leave;
class CalculateNewLeavesPosted
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param countNewLeaves $event
* @return void
*/
public function handle(countNewLeaves $event)
{
$leaves_count = Leave::where('status', 'pending')->where('google_post', 0)->count();
return $leaves_count;
}
}
<file_sep>/app/Services/TimeZone.php
<?php namespace App\Services;
class TimeZone
{
public function timezone_list()
{
static $timezones = null;
if ($timezones === null) {
$timezones = [];
$offsets = [];
$now = new \DateTime();
foreach (\DateTimeZone::listIdentifiers(\DateTimeZone::PER_COUNTRY, 'US') as $timezone) {
$now->setTimezone(new \DateTimeZone($timezone));
$offsets[] = $offset = $now->getOffset();
$timezones[$timezone] = '(' . $this->format_GMT_offset($offset) . ') ' . $this->format_timezone_name($timezone);
}
array_multisort($offsets, $timezones);
}
return $timezones;
}
private function format_GMT_offset($offset)
{
$hours = intval($offset / 3600);
$minutes = abs(intval($offset % 3600 / 60));
return 'GMT' . ($offset ? sprintf('%+03d:%02d', $hours, $minutes) : '');
}
private function format_timezone_name($name)
{
$name = str_replace('/', ', ', $name);
$name = str_replace('_', ' ', $name);
$name = str_replace('St ', 'St. ', $name);
return $name;
}
}
<file_sep>/app/Modules/Nexpbx/Http/Domain.php
<?php
namespace App\Modules\Nexpbx\Http;
use Illuminate\Database\Eloquent\Model;
class Domain extends Model
{
protected $table = 'nexpbx_domains';
public function devices()
{
return $this->hasmany('App\Modules\Nexpbx\Http\Device', 'domain_uuid', 'domain_uuid');
}
public function customer()
{
return $this->belongsTo('App\Modules\Crm\Http\Customer');
}
}
<file_sep>/app/Modules/Nexpbx/Http/routes.php
<?php
/*
|--------------------------------------------------------------------------
| Module Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for the module.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::group(['middleware' => 'web'], function () {
Route::group(['prefix' => 'admin','middleware' => 'admin'], function () {
Route::group(['prefix' => 'nexpbx','middleware' => []], function () {
Route::get('/', ['as'=>'admin.nexpbx.index','middleware' => [], 'uses' => 'DeviceController@index']);
Route::get('/dtdevices', ['as'=>'admin.nexpbx.dt_devices','middleware' => [], 'uses' => 'DeviceController@dt_devices']);
Route::get('/locations_list_json/{id}', ['as'=>'admin.nexpbx.ajax.locations.json','middleware' => [], 'uses' => 'DeviceController@ajaxLocationsJson']);
Route::get('/customer_list_json/', ['as'=>'admin.nexpbx.ajax.customers.json','middleware' => [], 'uses' => 'DeviceController@ajaxCustomersJson']);
Route::post('/assign_customer', ['as'=>'admin.nexpbx.assign.customer','middleware' => ['permission:create_vendor'], 'uses' => 'DeviceController@assignCustomer']);
Route::get('/assets/', ['as'=>'admin.assets.nexpbx','middleware' => [], 'uses' => 'DeviceController@nexpbxDevices']);
Route::get('/nexpbx_cust_list', ['as'=>'admin.nexpbx.customer.json','middleware' => ['permission:list_vendor'], 'uses' => 'DeviceController@ajaxCustomerNexpbx']);
Route::get('/nexpbx_domain_devices/{id}', ['as'=>'admin.nexpbx.domain.devices','middleware' => ['permission:list_vendor'], 'uses' => 'DeviceController@DomainDevices']);
Route::get('/nexpbx_cust_device_list/{domain_uuid}', ['as'=>'admin.nexpbx.customer.devices.json','middleware' => ['permission:list_vendor'], 'uses' => 'DeviceController@ajaxCustomerDevices']);
Route::get('/assign_devices', ['as'=>'admin.nexpbx.assign.devices','middleware' => ['permission:list_vendor'], 'uses' => 'DeviceController@assign_devices']);
Route::post('/remove_device/', ['as'=>'admin.nexpbx.remove.device','middleware' => ['permission:list_vendor'], 'uses' => 'DeviceController@remove_device']);
Route::get('/change_type/{id}/{value}', ['as'=>'admin.nexpbx.change.type','middleware' => ['permission:list_vendor'], 'uses' => 'DeviceController@change_type']);
Route::get('/change_location/{id}/{value}', ['as'=>'admin.nexpbx.change.location','middleware' => ['permission:list_vendor'], 'uses' => 'DeviceController@change_location']);
Route::get('/ajax_device_detail/{id}', ['as'=>'admin.nexpbx.device.detail','middleware' => ['permission:list_vendor'], 'uses' => 'DeviceController@device_detail']);
Route::post('/update_notes', ['as'=>'admin.nexpbx.update.notes','middleware' => ['permission:list_vendor'], 'uses' => 'DeviceController@updateNotes']);
});
});
});<file_sep>/app/Modules/Crm/Resources/Views/ticket/add.blade (backup-with-fileajaxupload-ckeditor+finder).php
@extends('admin.main')
@section('content')
<section class="content-header">
<h1>
Add Ticket
{{-- <small>preview of simple tables</small> --}}
</h1>
<ol class="breadcrumb">
<li>
<i class="fa fa-dashboard"></i> <a href="/admin/dashboard">Dashboard</a>
</li>
<li >
<a href="{{ URL::route('admin.ticket.index')}}"> <i class="fa fa-table"></i> Tickets</a>
</li>
<li class="active">
<i class="fa fa-table"></i> Add Ticket
</li>
</ol>
</section>
<section class="content">
<div class="row">
<div class="col-xs-12">
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="clearfix"></div>
<div class="box">
<div class="box-header with-border">
<h3 class="box-title ">Customer Detail</h3>
</div>
<?php $rand1 = rand(0,500);
$rand2 = rand(501,999);
$rand = $rand1.$rand2;?>
{!! Form::open(['route' => 'admin.ticket.store','method'=>'POST','id'=>'form_validate']) !!}
<div class="box-body">
<input type="hidden" name="rand" value="<?php echo $rand; ?>">
<div class="col-lg-12">
<div class="form-group col-lg-6">
<label>Customer</label>
{!! Form::select('customer_id', $customers,'',['class'=>'form-control multiselect','placeholder' => 'Pick a Customer','onChange'=>'load_service_items(this.value)'])!!}
</div>
<div class="form-group col-lg-6">
<label>Service Item</label>
<?php $service_items = [];?>
{!! Form::select('service_item', $service_items,'',['class'=>'form-control multiselect','placeholder' => 'Pick a Service item', 'id'=>'service_items'])!!}
</div>
<div class="form-group col-lg-6">
<label>Location</label>
<?php $locations = [];?>
{!! Form::select('location', $locations,'',['class'=>'form-control multiselect','placeholder' => 'Pick a Location', 'id'=>'locations'])!!}
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="box-header with-border top-border bot_10px">
<h3 class="box-title">Ticket Detail</h3>
</div>
<div class="box-body">
<div class="col-lg-12">
<div class="form-group col-lg-6">
<label>Title</label>
{!! Form::input('text','title',null, ['placeholder'=>"Title",'class'=>"form-control"]) !!}
</div>
<div class="form-group col-lg-6">
<label>Assign Users</label>
{!! Form::select('users[]', $users,'',['class'=>'form-control multiselect','placeholder' => 'Assign Users', 'id'=>'users','multiple'=>''])!!}
</div>
</div>
<div class="col-lg-12">
<div class="form-group col-lg-12">
<label>Description</label>
{!! Form::textarea('body',null, ['placeholder'=>"Ticket descriptions",'class'=>"form-control textarea",'id'=>'description','rows'=>10]) !!}
</div>
</div>
<div class="col-lg-12">
<div class="form-group col-lg-1">
<label>Priority</label>
</div>
<div class="form-group col-lg-1">
<div class="radio">
<label>
<input type="radio" checked="" value="low" id="low" name="priority">
<button type="button" class="btn bg-gray btn-xs">
<span>Low</span>
</button>
</label>
</div>
</div>
<div class="form-group col-lg-1">
<div class="radio">
<label>
<input type="radio" value="normal" id="normal" name="priority">
<button type="button" class="btn bg-blue btn-xs">
<span>Normal</span>
</button>
</label>
</div>
</div>
<div class="form-group col-lg-1">
<div class="radio">
<label>
<input type="radio" value="high" id="high" name="priority">
<button type="button" class="btn bg-green btn-xs">
<span>High</span>
</button>
</label>
</div>
</div>
<div class="form-group col-lg-1">
<div class="radio">
<label>
<input type="radio" value="urgent" id="urgent" name="priority">
<button type="button" class="btn bg-yellow btn-xs">
<span>Urgent</span>
</button>
</label>
</div>
</div>
<div class="form-group col-lg-2">
<div class="radio">
<label>
<input type="radio" value="critical" id="critical" name="priority">
<button type="button" class="btn bg-red btn-xs">
<span>Critical</span>
</button>
</label>
</div>
</div>
</div>
<div class="col-lg-12">
<div class="form-group col-lg-6 pull-right">
<button class="btn btn-lg btn-info pull-right" type="submit">Save</button>
</div>
</div>
</div>
{!! Form::close() !!}
<div class="box-header with-border top-border bot_10px">
<h3 class="box-title">Attatch Images</h3>
</div>
<div class="box-body">
<div class="col-lg-12">
<form action="{{URL::route('admin.ticket.upload')}}" class="dropzone" id="my-awesome-dropzone" method="POST">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<input type="hidden" name="rand" value="<?php echo $rand; ?>">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
@endsection
@section('script')
<script type="text/javascript" src="/js/form_elements.js"></script>
{{-- <script src="/js/bootstrap3-wysihtml5.all.min.js"></script> --}}
<script src="/ckeditor/ckeditor.js"></script>
<script src="/ckeditor/config.js"></script>
<script src="/js/dropzone.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('.multiselect').multiselect({
enableFiltering: true,
includeSelectAllOption: true,
maxHeight: 400,
dropUp: false,
buttonClass: 'form-control',
onChange: function(option, checked, select) {
//alert($('#multiselect').val());
}
});
$('.datepicker').datepicker();
//$(".textarea").wysihtml5();
//CKEDITOR.replace('description');
CKEDITOR.replace( 'description', {
filebrowserBrowseUrl: '/ckfinder/ckfinder.html',
filebrowserUploadUrl: '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files'
} );
Dropzone.options.myAwesomeDropzone = {
init: function() {
this.on("addedfile", function(file) {
// Create the remove button
var removeButton = Dropzone.createElement('<button class="btn btn-sm relative left-15px btn-danger top-10px" ><i class="fa fa-times-circle"></i> Delete</button>');
// Capture the Dropzone instance as closure.
var _this = this;
// Listen to the click event
removeButton.addEventListener("click", function(e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
_this.removeFile(file);
// If you want to the delete the file on the server as well,
// you can do the AJAX request here.
$.ajax({
url: "{{ URL::route('admin.ticket.ajax_del_img')}}",
//headers: {'X-CSRF-TOKEN': token},
type: 'POST',
dataType: 'json',
data:'file='+ file.name+'&rand='+'<?php echo $rand; ?>',
success: function(response){
}
});
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
}
};
});
function load_service_items(c_id)
{
//console.log('ff');
$.get('/admin/crm/ticket/ajax_get_service_items/'+c_id,function(response ) {
//console.log(data_response);
var service_items = response.service_items;
$.each(service_items,function(index, service_item) {
//console.log(el);
$('#service_items').append($("<option></option>")
.attr("value",service_item.id)
.text( service_item.title));
});
$('#service_items').multiselect('rebuild');
var locations = response.locations;
$.each(locations,function(index, location) {
//console.log(el);
$('#locations').append($("<option></option>")
.attr("value",location.id)
.text( location.location_name));
});
$('#locations').multiselect('rebuild');
},"json"
);
}
</script>
@endsection
@section('styles')
<link href="/css/bootstrap-multiselect.css" rel="stylesheet" />
<link rel="stylesheet" href="/css/bootstrap3-wysihtml5.min.css">
<link rel="stylesheet" href="/css/dropzone.css">
<style>
.top-border {
border-top: 1px solid #f4f4f4;
}
.top-10px{
top: 10px;
}
.bot_10px{
margin-bottom: 10px;
}
.relative{
position: relative;
}
.left-15px{
left: 15px;
}
.dropzone {
background: white none repeat scroll 0 0;
border: 2px solid rgba(0, 0, 0, 0.3);
min-height: 150px;
padding: 54px;
}
.dropzone {
background: white none repeat scroll 0 0;
border: 2px dashed #0087f7;
border-radius: 5px;
}
</style>
@endsection<file_sep>/app/Modules/Nexpbx/Http/Controllers/DeviceController.php
<?php
namespace App\Modules\Nexpbx\Http\Controllers;
//use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use App\Modules\Nexpbx\Http\Device;
use App\Modules\Nexpbx\Http\Domain;
use Illuminate\Http\Request;
// use Illuminate\Support\Facades\DB;
use App\Modules\Crm\Http\Customer;
use App\Modules\Crm\Http\CustomerLocation;
use App\Model\Config;
// use App\Model\Role;
// use App\Model\User;
// use Auth;
// use URL;
use Datatables;
use Session;
class DeviceController extends Controller
{
function index()
{
$customers=Customer::where('is_active', 1)
->orderBy('name', 'desc')
->get();
$enabled_customers=[];
foreach ($customers as $cus) {
$enabled_customers[$cus['id']]=$cus['name'];
}
$current_customer_locations=[];
return view('nexpbx::devices.index', compact('enabled_customers', 'current_customer_locations'));
}
// Datatables Device list
function dt_devices()
{
$domains = Domain::with(['customer'])->where('customer_id', 0);
$date_format = Config::where('title', 'date_format')->first();
return Datatables::of($domains)
// ->editColumn('device_template', function ($device) {
// $array = explode("/", $device->device_template);
// return ucfirst($array[0]).' '.strtoupper($array[1]);
// })
->setRowId('id')
->make(true);
//return view('nexpbx::devices.index');
}
function ajaxLocationsJson($customer_id)
{
$data['locations'] = CustomerLocation::where('customer_id', $customer_id)
// ->whereNotIn('id', function($query) use($vendor_id){
// $query->select('location_id')
// ->from(with(new VendorCustomer)->getTable())
// ->where('vendor_id', $vendor_id);
// })
->get();
return json_encode($data);
exit;
}
function ajaxCustomersJson($value = '')
{
$customers=Customer::where('is_active', 1)
->orderBy('name', 'desc')
->get();
$enabled_customers=[];
foreach ($customers as $cus) {
$enabled_customers[$cus['id']]=$cus['name'];
}
return json_encode($enabled_customers);
exit;
}
function assignCustomer(Request $request)
{
$domains=explode(',', $request->selected_domains);
foreach ($domains as $id) {
$domain= Domain::find($id);
$domain->customer_id=$request->assigning_custumers;
$domain->location_id=$request->cust_location;
$domain->save();
}
$arr['success'] = 'yes';
$request->session()->flash('status', 'Domains successfully assigned to Customer!');
return json_encode($arr);
//$device= Device::find();
}
function assign_devices()
{
$current_customer_locations = CustomerLocation::where('customer_id', Session::get('cust_id'))
// ->whereNotIn('id', function($query) use($vendor_id){
// $query->select('location_id')
// ->from(with(new VendorCustomer)->getTable())
// ->where('vendor_id', $vendor_id);
// })
->get();
$locations=[];
foreach ($current_customer_locations as $loc) {
$locations[$loc['id']]=$loc['location_name'];
}
$devices = Domain::with(['customer'])->where('customer_id', 0)->get();
return view('nexpbx::assign_devices', compact('locations', 'devices'));
}
function remove_device(Request $request)
{
if ($request->id) {
$domain= Domain::find($request->id);
$domain->customer_id=0;
$domain->save();
$arr['success'] = 'yes';
} else {
$arr['success'] = false;
}
return json_encode($arr);
}
function change_type($id, $value)
{
if ($id) {
$device= Device::find($id);
$device->device_type=$value;
$device->save();
$arr['success'] = 'yes';
} else {
$arr['success'] = false;
}
return json_encode($arr);
}
function change_location($id, $value)
{
if ($id) {
$device= Device::find($id);
$device->location_id=$value;
$device->save();
$arr['success'] = 'yes';
} else {
$arr['success'] = false;
}
return json_encode($arr);
}
function nexpbxDevices(Request $request)
{
return view('nexpbx::customer_devices');
}
function ajaxCustomerNexpbx()
{
// $customers_obj = Device::with(['customer'])->where('customer_id',Session::get('cust_id'))->get();
$global_date = $this->global_date;
if (!empty(Session::get('cust_id'))) {
$devices = Domain::with(['customer','devices'])->where('customer_id', Session::get('cust_id'))->get();
}
return Datatables::of($devices)
->addColumn('location', function ($device) {
$location = CustomerLocation::find($device->location_id);
if ($location) {
return $location->location_name;
} else {
return '------';
}
})
->editColumn('created_at', function ($device) use ($global_date) {
return date($global_date, strtotime($device->created_at));
})
->editColumn('device_type', function ($device) {
$return= '<select>';
if (is_null($device->device_type)) {
$return .= '<option selected value="">Select type</option>';
} else {
if ($device->device_type=='BYOD') {
}
$return .= '<option selected value="">Select type</option>';
return $device->device_type;
}
$return='<option value="BYOD">BYOD</option>';
$return='<option value="Leased">Leased</option>';
$return .= '</select>';
return $return;
})
->addColumn('action', function ($device) {
if (!empty(Session::get('cust_id'))) {
$return = '<div class="btn-group">';
$return .=' <button type="button" class="btn btn-danger btn-xs"
data-toggle="modal" data-id="'.$device->id.'" id="modaal" data-target="#modal_device_remove">
<i class="fa fa-times-circle"></i></button></div>';
$return .= '</div>';
$return .= '</div>';
return $return;
}
})
->setRowId('id')
->make(true);
}
function DomainDevices($id)
{
$domain = Domain::where('domain_uuid', $id)->first();
$domain_name = $domain->domain_name;
return view('nexpbx::customer_domain_devices', compact('id', 'domain_name'));
}
function ajaxCustomerDevices($domain_uuid)
{
// $customers_obj = Device::with(['customer'])->where('customer_id',Session::get('cust_id'))->get();
$global_date = $this->global_date;
if (!empty(Session::get('cust_id'))) {
$devices = Device::with(['domain'])->where('domain_uuid', $domain_uuid) ->get();
}
return Datatables::of($devices)
->addColumn('location', function ($device) {
$locations = CustomerLocation::where('customer_id', Session::get('cust_id'))->get();
$return = '<select class="form-control input-sm" onchange="change_location('.$device->id.',this.value)">';
$return .= '<option value="">Select Location</option>';
foreach ($locations as $key => $location) {
$selected=($device->Location_id==$location->id)?"selected":"";
$return .='<option '.$selected.' value="'.$location->id.'">'.$location->location_name.'</option>';
}
$return .= '</select>';
return $return;
})
->editColumn('created_at', function ($device) use ($global_date) {
return date($global_date, strtotime($device->created_at));
})
->editColumn('device_vendor', function ($device) {
return ucfirst($device->device_vendor);
})
->editColumn('device_type', function ($device) {
$return= '<select class="form-control input-sm" onchange="change_type('.$device->id.',this.value)">';
if (is_null($device->device_type)) {
$return .= '<option selected value="">Select type</option>';
$return .='<option value="BYOD">BYOD</option>';
$return .='<option value="Leased">Leased</option>';
} else {
$return .= '<option value="">Select type</option>';
if ($device->device_type=='BYOD') {
$return .='<option selected value="BYOD">BYOD</option>';
$return .='<option value="Leased">Leased</option>';
} else if ($device->device_type=='Leased') {
$return .='<option value="BYOD">BYOD</option>';
$return .='<option selected value="Leased">Leased</option>';
}
}
$return .= '</select>';
return $return;
})
->addColumn('action', function ($device) {
if (!empty(Session::get('cust_id'))) {
$return = '<div class="btn-group">';
$return .=' <button type="button" class="btn btn-danger btn-xs"
data-toggle="modal" data-id="'.$device->id.'" id="modaal" data-target="#modal_device_remove">
<i class="fa fa-times-circle"></i></button></div>';
$return .= '</div>';
$return .= '</div>';
return $return;
}
})
->setRowId('id')
->make(true);
}
function device_detail($id)
{
$device = Device::where('id', $id)->first();
$model = strtoupper(explode('/', $device->device_template)[1]);
return view('nexpbx::devices.detail_partial', compact('device', 'model'));
}
function updateNotes(Request $request)
{
$device=Device::find($request->device_id);
$device->notes=$request->device_notes;
if ($device->save()) {
$arr['success'] = 'yes';
} else {
$arr['success'] = false;
}
return json_encode($arr);
}
}
<file_sep>/app/Modules/Employee/Http/Controllers/LeaveController.php
<?php
namespace App\Modules\Employee\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use App\Modules\Employee\Http\Employee;
use App\Modules\Employee\Http\Leave;
use App\Modules\Employee\Http\Requests\LeavePostRequest;
use App\Services\GoogleCalendar;
use App\Model\Role;
use App\Model\User;
use Auth;
use App\Model\Config;
use Datatables;
use Session;
class LeaveController extends Controller
{
private $controller = 'leave';
public function index($id = null)
{
//dd(Auth::user());
$controller = $this->controller;
$route_delete = 'employee.leave.destroy';
// $leaves = Leave::where('user_id',Auth::user()->id)->with(['user'])->get();
if ($id) {
return view('employee::leave.list_own_leaves', compact('controller', 'route_delete'));
} else {
return view('employee::leave.list_all_leaves', compact('controller', 'route_delete'));
}
}
public function allListLeaves($id = null)
{
//dd($request);
$date_format = Config::where('title', 'date_format')->first();
if ($id) {
$leaves = Leave::where('posted_for', $id)->with(['poster','applicant','action_taker','poster.roles'])->select('leaves.*', 'users.f_name', 'users.l_name')
->join('users', 'leaves.posted_for', '=', 'users.id');
} else {
$leaves = Leave::with(['poster','applicant','action_taker','poster.roles'])->select('leaves.*', 'users.f_name', 'users.l_name')
->join('users', 'leaves.posted_for', '=', 'users.id')->where('leaves.posted_for', '!=', Auth::user()->id);
}
return Datatables::of($leaves)
->editColumn('start_date', function ($leave) use ($date_format) {
return date($date_format->key, strtotime($leave->start_date));
})
/* ->editColumn('type', function ($leave) {
return $leave->type;
})*/
->editColumn('end_date', function ($leave) use ($date_format) {
return date($date_format->key, strtotime($leave->end_date));
})
->editColumn('category', function ($leave) {
if ($leave->category=='short') {
return '<span class="badge bg-blue">Short</span>';
} else {
return '<span class="badge bg-blue">Full Day</span>';
}
})
->editColumn('created_at', function ($leave) use ($date_format) {
return date($date_format->key, strtotime($leave->created_at));
})
->editColumn('posted_by', function ($leave) {
if ($leave->posted_by== $leave->posted_for) {
return '<button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-user"></i>
<span>'.$leave->poster->f_name.' '.$leave->poster->l_name.'</span>
</button>';
} else {
return '<button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-user"></i>
<span>'.$leave->poster->f_name.' '.$leave->poster->l_name.' ('.$leave->poster->roles[0]->name.')</span>
</button>';
}
})
->addColumn('days', function ($leave) {
if ($leave->category=='full') {
return '<span class="badge bg-blue">'.$leave->duration.'</span>';
} else {
return '---';
}
})
->addColumn('applicant', function ($leave) {
return '<button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-user"></i>
<span>'.$leave->applicant->f_name.' '.$leave->applicant->l_name.'</span>
</button>';
})
->addColumn('hours', function ($leave) {
if ($leave->category=='short') {
return '<span class="badge bg-blue">'.$leave->duration.'</span>';
} else {
return '---';
}
})
->editColumn('status', function ($leave) {
if ($leave->status == 'pending') {
return '<button class="btn btn-sm btn-warning" type="button">Pending</button>';
}
if ($leave->status == 'approved') {
return '<button class="btn btn-sm btn-success" type="button">Approved</button>';
}
if ($leave->status == 'rejected') {
return '<button class="btn btn-sm btn-danger" type="button">Rejected</button>';
}
})
->addColumn('action', function ($leave) use ($id) {
$return = '';
/* <img id="load_img" src="{{asset('img/loader.gif')}}" style="display:none" />*/
if ($leave->status=='pending' && !isset($id)) {
$return ='<button type="button" class="btn btn-success btn-sm" data-id="'.$leave->id.'" id="approve'.$leave->id.'" onclick="approve('.$leave->id.')">
Approve
</button>';
$return .= ' <button type="button" class="btn btn-danger btn-sm" data-id="'.$leave->id.'" id="modaal-hide'.$leave->id.'" data-toggle="modal" data-target="#modal-reject">
<i class="fa fa-times-circle"></i>
Reject
</button>';
}
if ($leave->status!='approved') {
$return .= ' <button type="button" class="btn btn-danger btn-sm"
data-toggle="modal" data-id="'.$leave->id.'" id="modaal" data-target="#modal-delete">
<i class="fa fa-times-circle"></i>
Delete
</button>';
}
return $return;
})
->setRowId('id')
->make(true);
}
public function dashboardListLeaves($id)
{
$date_format = Config::where('title', 'date_format')->first();
$leaves = Leave::where('posted_for', $id)
->with(['poster','applicant','action_taker','poster.roles'])
->select('leaves.*', 'users.f_name', 'users.l_name')
->join('users', 'leaves.posted_by', '=', 'users.id');
return Datatables::of($leaves)
->editColumn('start_date', function ($leave) use ($date_format) {
return date($date_format->key, strtotime($leave->start_date));
})
->editColumn('end_date', function ($leave) use ($date_format) {
return date($date_format->key, strtotime($leave->end_date));
})
->editColumn('category', function ($leave) {
if ($leave->category=='short') {
return '<span class="badge bg-blue">Short</span>';
} else {
return '<span class="badge bg-blue">Full Day</span>';
}
})
->editColumn('created_at', function ($leave) use ($date_format) {
return date($date_format->key, strtotime($leave->created_at));
})
->editColumn('posted_by', function ($leave) {
if ($leave->posted_by== $leave->posted_for) {
return '<button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-user"></i>
<span>'.$leave->poster->f_name.' '.$leave->poster->l_name.'</span>
</button>';
} else {
return '<button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-user"></i>
<span>'.$leave->poster->f_name.' '.$leave->poster->l_name.' ('.$leave->poster->roles[0]->name.')</span>
</button>';
}
})
->addColumn('days', function ($leave) {
if ($leave->category=='full') {
return '<span class="badge bg-blue">'.$leave->duration.'</span>';
} else {
return '---';
}
})
->addColumn('hours', function ($leave) {
if ($leave->category=='short') {
return '<span class="badge bg-blue">'.$leave->duration.'</span>';
} else {
return '---';
}
})
->editColumn('status', function ($leave) {
if ($leave->status == 'pending') {
return '<button class="btn btn-sm btn-warning" type="button">Pending</button>';
}
if ($leave->status == 'approved') {
return '<button class="btn btn-sm btn-success" type="button">Approved</button>';
}
if ($leave->status == 'rejected') {
return '<button class="btn btn-sm btn-danger" type="button">Rejected</button>';
}
})
->setRowId('id')
->make(true);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('employee::leave.add');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate(
$request,
[
'category' => 'required',
'type' => 'required',
]
);
if ($request->category=='full') {
$this->validate(
$request,
[
'duration' => 'required',
]
);
$duration_arr = explode('-', $request->duration);
///$start_date = $duration_arr[0];
//$end_date = $duration_arr[1];
$start_date =date('Y-m-d', strtotime($duration_arr[0]));
$end_date = date('Y-m-d', strtotime($duration_arr[1]));
$diff =date_diff(date_create($start_date), date_create($end_date));
if ($diff->days==0) {
$duration = 1;
} else {
$duration = $diff->days;
}
}
if ($request->category=='short') {
$this->validate(
$request,
[
'duration_short' => 'required',
'date' =>'required'
]
);
$start_date =date('Y-m-d', strtotime($request->date));
$end_date = date('Y-m-d', strtotime($request->date));
$duration = $request->duration_short;
}
$leave = new Leave();
$leave->posted_by = Auth::user()->id;
$leave->posted_for = Auth::user()->id;
$leave->status = 'pending';
if ($request->category=='full') {
$leave->start_date = $start_date;
$leave->end_date = $end_date;
}
if ($request->category=='short') {
$leave->start_date = $start_date;
$leave->end_date = $end_date;
}
//$leave->poster_comments = $request->
//$leave->approver_comments = $request->
$leave->type = $request->type;
$leave->category = $request->category;
$leave->duration = $duration;
//dd($leave);
$leave->save();
// $arr['success'] = 'Leave added successfully';
//return json_encode($arr);
// exit;
$request->session()->put('success', 'Leave added successfully!');
return redirect()->intended('admin/employee/leave');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
//dd($id);
//dd($request->id);
$id = $request->id;
$leave = Leave::findorFail($id);
$leave->delete();
//Session::flash('flash_message', 'User successfully deleted!');
return redirect()->intended('admin/employee/leave');
}
function listLeaves()
{
$leaves = Leave::all();
//dd($leaves);
$route_delete = 'employee.leave.destroy';
return view('employee::leave.index_all_leaves', compact('leaves', 'route_delete'));
}
function listPendingLeaves()
{
$leaves = Leave::where('status', 'pending')->with(['user', 'user.roles'])->get();
//dd($leaves[0]->user->roles);
$route_delete = 'employee.leave.destroy';
return view('employee::leave.index_all_leaves', compact('leaves', 'route_delete'));
}
function listRejectedLeaves()
{
$leaves = Leave::where('status', 'rejected')->with(['user', 'user.roles'])->get();
//dd($leaves);
$route_delete = 'employee.leave.destroy';
return view('employee::leave.index_all_leaves', compact('leaves', 'route_delete'));
}
function showCalendar()
{
$calendar = new GoogleCalendar;
//$result = $calendar->get();
$events_result = $calendar->eventList();
//dd($events_result);
$events_arr = [];
//while(true) {
foreach ($events_result->getItems() as $event) {
// dd($event);
//$calendar->eventDelete($event->getId());
if ($event->start->getDatetime()!=null) {
$events_arr[] = ['title'=>html_entity_decode($event->getSummary()),
'start'=>$event->start->getDatetime(),
'end'=>$event->end->getDatetime(),
'description'=>$event->getDescription(),
'id'=>$event->getId()];
} else {
$events_arr[] = ['title'=>html_entity_decode($event->getSummary()),
'start'=>$event->start->getDate(),
'end'=>$event->end->getDate(),
'description'=>$event->getDescription(),
'id'=>$event->getId()];
}
}
$events = json_encode($events_arr);
return view('employee::leave.calendar', compact('events', 'route_delete'));
}
public function postCalander(Request $request)
{
// dd($request->all());
$leave = Leave::where('id', $request->leave_id)->with('user.employee')->first();
$calendar = new GoogleCalendar;
$post = $calendar->eventPost([
'summary' => $leave->user->f_name.' '.$leave->user->l_name.'('.$leave->user->roles[0]->display_name.') Leave: '.$leave->type.' ('.$leave->category.')',
'location' => '',
'visibility' => 'private',
'description' => $leave->comments,
'start' => [
'date' => $leave->start_date,
'timeZone' => $leave->user->employee->time_zone,
],
'end' => [
'date' => $leave->end_date,
'timeZone' => $leave->user->employee->time_zone,
],
'attendees' => [
['email' => $leave->user->email],
['email' => Auth::user()->email],
],
'reminders' => [
'useDefault' => false,
'overrides' => [
['method' => 'email', 'minutes' => 24 * 60],
['method' => 'popup', 'minutes' => 10],
],
],
]);
//dd($post->id);
if ($post) {
$leave_update = Leave::where('id', $request->leave_id)->first();
$leave_update->status = 'approved';
$leave_update->google_post = 1;
$leave_update->google_id = $post->id;
$leave_update->action_taken_by = Auth::user()->id;
$leave_update->save();
}
$arr['success'] = 'Leave approved and posted to google calendar successfully';
return json_encode($arr);
exit;
//exit;
//return redirect()->intended('admin/employee/leave/calendar');
}
function rejectLeave(Request $request)
{
//dd($request->all());
$leave_update = Leave::where('id', $request->id)->first();
$leave_update->status = 'rejected';
$leave_update->approved_by = Auth::user()->id;
$leave_update->save();
$arr['success'] = 'Leave rejected successfully';
return json_encode($arr);
exit;
//return redirect()->intended('admin/employee/leave/pending_leaves');
}
function postLeaveForEmployee(Request $request)
{
$this->validate(
$request,
[
'category' => 'required',
'type' => 'required',
]
);
if ($request->category=='full') {
$this->validate(
$request,
[
'duration' => 'required',
]
);
$duration_arr = explode('-', $request->duration);
///$start_date = $duration_arr[0];
//$end_date = $duration_arr[1];
$start_date =date('Y-m-d', strtotime($duration_arr[0]));
$end_date = date('Y-m-d', strtotime($duration_arr[1]));
$diff =date_diff(date_create($start_date), date_create($end_date));
if ($diff->days==0) {
$duration = 1;
} else {
$duration = $diff->days;
}
}
if ($request->category=='short') {
$this->validate(
$request,
[
'duration_short' => 'required',
]
);
$start_date =date('Y-m-d', strtotime($request->date));
$end_date = date('Y-m-d', strtotime($request->date));
$duration = $request->duration_short;
}
$leave = new Leave();
if (Auth::user()->id == $request->employee_id) {
$leave->posted_by = $request->employee_id;
} else {
$leave->posted_by = $request->posted_by;
$leave->posted_for = $request->employee_id;
}
if (Auth::user()->id != $request->employee_id && isset($request->status)) {
$leave->status = $request->status;
$leave->action_taken_by = Auth::user()->id;
} else {
$leave->status = 'pending';
}
if ($request->category=='full') {
$leave->start_date = $start_date;
$leave->end_date = $end_date;
}
if ($request->category=='short') {
$leave->start_date = $start_date;
$leave->end_date = $end_date;
}
//$leave->poster_comments = $request->
//$leave->approver_comments = $request->
$leave->type = $request->type;
$leave->category = $request->category;
$leave->duration = $duration;
$leave->save();
$arr['success'] = 'Leave added successfully';
return json_encode($arr);
exit;
}
}
<file_sep>/app/Modules/Crm/Database/2015_12_31_125449_customers.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Customers extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
//$table->integer('user_id');
$table->string('name', 50);
$table->date('created_at');
$table->date('updated_at');
$table->date('customer_since');
$table->string('email_domain', 50);
$table->string('main_phone', 15);
//$table->text('comments');
//$table->enum('type', ['annual', 'sick']);
//$table->enum('status', ['pending','approved','rejected']);
$table->tinyInteger('is_taxable');
$table->tinyInteger('is_active');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('customers');
}
}
<file_sep>/app/Modules/Crm/Http/CustomerBillingPeriod.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class CustomerBillingPeriod extends Model
{
//
public function customer()
{
return $this->belongsTo('App\Modules\Crm\Http\Customer');
}
public function service_item()
{
return $this->hasOne('App\Modules\Crm\Http\CustomerServiceItem');
}
}
<file_sep>/app/Services/GoogleGmail.php
<?php namespace App\Services;
error_reporting(E_ALL);
ini_set('display_errors', '1');
use Illuminate\Support\Facades\Cache;
//use Illuminate\Support\Facades\Config;
use App\Model\Config;
class GoogleGmail
{
protected $client;
protected $service;
protected $user = 'me';
//protected $credentialsPath;
protected $scopes ;
public $auth_url;
function __construct($flag = null, $token = null)
{
$auth_key = Config::where('key', 'gmail_auth_client_id')->first();
$auth_secret = Config::where('key', 'gmail_auth_client_secret')->first();
$redirect_uri = Config::where('key', 'redirect_uri')->first();
$this->scopes = implode(' ', [ \Google_Service_Gmail::GMAIL_READONLY, \Google_Service_Gmail::GMAIL_COMPOSE,\Google_Service_Gmail::GMAIL_SEND]);
$this->client = new \Google_Client();
$this->client->setApplicationName(\Config::get('google.application_name'));
$this->client->setScopes($this->scopes);
$this->client->setClientId($auth_key->value);
$this->client->setClientSecret($auth_secret->value);
$this->client->setRedirectUri($redirect_uri->value);
//$this->client->setAuthConfigFile(base_path() .Config::get('google.client_secret_path'));
$this->client->setAccessType('offline');
if ($flag=='reset') {
// $client->setApprovalPrompt('auto');
$this->client->setPrompt('consent');
//$client->revokeToken($accessToken);
$this->auth_url = $this->client->createAuthUrl();
//dd(json_decode($this->auth_url));
return true;
}
if ($flag=='token_reset' && isset($token)) {
$returnedAccessToken = $this->client->authenticate($token);
//$accessToken = $this->client->getAccessToken();
//dd($accessToken);
//if(!file_exists(dirname($credentialsPath))) {
// mkdir(dirname($credentialsPath), 0700, true);
//}
$file_path = base_path('resources/assets');
$file = $file_path."/gmail_token.json";
file_put_contents($file, $returnedAccessToken);
//echo ("Credentials saved to ==>".$credentialsPath);
return true;
}
$credentialsPath = base_path() .\Config::get('google.credentials_path');
// dd($credentialsPath);
if (file_exists($credentialsPath)) {
//echo 'hhhh';
//exit;
//echo $credentialsPath;
$accessToken = file_get_contents($credentialsPath);
$google_token= json_decode($accessToken);
// dd($google_token->refresh_token);
//$this->client->setAccessToken($accessToken);
$this->client->refreshToken($google_token->refresh_token);
$this->client->setAccessToken($accessToken);
$this->service = new \Google_Service_Gmail($this->client);
}
}
/*function setCredentials()
{
$this->scopes = implode(' ', array( \Google_Service_Gmail::GMAIL_READONLY, \Google_Service_Gmail::GMAIL_COMPOSE,\Google_Service_Gmail::GMAIL_SEND));
$this->client = new \Google_Client();
$this->client->setApplicationName(Config::get('google.application_name'));
$this->client->setScopes($this->scopes);
$this->client->setAuthConfigFile(base_path() .Config::get('google.client_secret_path'));
$this->client->setAccessType('offline');
//$credentialsPath = base_path() .Config::get('google.credentials_path');
//$key_file_location = base_path() . Config::get('google.credentials_path');
// Request authorization from the user.
$authUrl = $this->client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
//return $authUrl;
//exit;
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $this->client->authenticate($authCode);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, $accessToken);
printf("Credentials saved to %s\n", $credentialsPath);
$this->client->setAccessToken($accessToken);
$this->service = new \Google_Service_Gmail($this->client);
}*/
function getMessages()
{
$list = $this->service->users_messages->listUsersMessages($this->user, ['maxResults' => 10,'labelIds'=>'INBOX','q'=>'is:unread']);
//echo '<pre>';
$messageList = $list->getMessages();
$inboxMessage = [];
//dd($messageList);
foreach ($messageList as $mlist) {
$optParamsGet2['format'] = 'full';
//$optParamsGet2['labelIds'] = 'INBOX';
$single_message = $this->service->users_messages->get($this->user, $mlist->id, $optParamsGet2);
/**************************************** new code*********************/
$payload = $single_message->getPayload();
$parts = $payload->getParts();
// With no attachment, the payload might be directly in the body, encoded.
$body = $payload->getBody();
$FOUND_BODY = false;
if (!$FOUND_BODY) {
foreach ($parts as $part) {
if ($part['parts'] && !$FOUND_BODY) {
foreach ($part['parts'] as $p) {
if ($p['parts'] && count($p['parts']) > 0) {
foreach ($p['parts'] as $y) {
if (($y['mimeType'] === 'text/html') && $y['body']) {
$FOUND_BODY = decodeBody($y['body']->data);
break;
}
}
} else if (($p['mimeType'] === 'text/html') && $p['body']) {
$FOUND_BODY = decodeBody($p['body']->data);
break;
}
}
}
if ($FOUND_BODY) {
break;
}
}
}
if ($FOUND_BODY && count($parts) > 1) {
$images_linked = [];
foreach ($parts as $part) {
if ($part['filename']) {
array_push($images_linked, $part);
} else {
if ($part['parts']) {
foreach ($part['parts'] as $p) {
if ($p['parts'] && count($p['parts']) > 0) {
foreach ($p['parts'] as $y) {
if (($y['mimeType'] === 'text/html') && $y['body']) {
array_push($images_linked, $y);
}
}
} else if (($p['mimeType'] !== 'text/html') && $p['body']) {
array_push($images_linked, $p);
}
}
}
}
}
// special case for the wdcid...
preg_match_all('/wdcid(.*)"/Uims', $FOUND_BODY, $wdmatches);
if (count($wdmatches)) {
$z = 0;
foreach ($wdmatches[0] as $match) {
$z++;
if ($z > 9) {
$FOUND_BODY = str_replace($match, 'image0' . $z . '@', $FOUND_BODY);
} else {
$FOUND_BODY = str_replace($match, 'image00' . $z . '@', $FOUND_BODY);
}
}
}
preg_match_all('/src="cid:(.*)"/Uims', $FOUND_BODY, $matches);
if (count($matches)) {
$search = [];
$replace = [];
// let's trasnform the CIDs as base64 attachements
foreach ($matches[1] as $match) {
foreach ($images_linked as $img_linked) {
foreach ($img_linked['headers'] as $img_lnk) {
if ($img_lnk['name'] === 'Content-ID' || $img_lnk['name'] === 'Content-Id' || $img_lnk['name'] === 'X-Attachment-Id') {
if ($match === str_replace('>', '', str_replace('<', '', $img_lnk->value))
|| explode("@", $match)[0] === explode(".", $img_linked->filename)[0]
|| explode("@", $match)[0] === $img_linked->filename) {
$search = "src=\"cid:$match\"";
$mimetype = $img_linked->mimeType;
$attachment = $gmail->users_messages_attachments->get('me', $mlist->id, $img_linked['body']->attachmentId);
$data64 = strtr($attachment->getData(), ['-' => '+', '_' => '/']);
$replace = "src=\"data:" . $mimetype . ";base64," . $data64 . "\"";
$FOUND_BODY = str_replace($search, $replace, $FOUND_BODY);
}
}
}
}
}
}
}
// If we didn't find the body in the last parts,
// let's loop for the first parts (text-html only)
if (!$FOUND_BODY) {
foreach ($parts as $part) {
if ($part['body'] && $part['mimeType'] === 'text/html') {
$FOUND_BODY = decodeBody($part['body']->data);
break;
}
}
}
// With no attachment, the payload might be directly in the body, encoded.
if (!$FOUND_BODY) {
$FOUND_BODY = decodeBody($body['data']);
}
// Last try: if we didn't find the body in the last parts,
// let's loop for the first parts (text-plain only)
if (!$FOUND_BODY) {
foreach ($parts as $part) {
if ($part['body']) {
$FOUND_BODY = decodeBody($part['body']->data);
break;
}
}
}
if (!$FOUND_BODY) {
$FOUND_BODY = '(No message)';
}
// Finally, print the message ID and the body
dd($message_id . ": " . $FOUND_BODY);
/**************************************** End new code*********************/
$message_id = $mlist->id;
$headers = $single_message->getPayload()->getHeaders();
$snippet = htmlentities($single_message->getSnippet());
//var_dump( $single_message);
$message_sender_email ='';
foreach ($headers as $single) {
if ($single->getName() == 'Subject') {
$message_subject = $single->getValue();
} else if ($single->getName() == 'Date') {
$message_date = $single->getValue();
$message_date = date('M jS Y h:i A', strtotime($message_date));
} else if ($single->getName() == 'From') {
$message_sender_email = htmlentities($single->getValue());
$message_sender= $single->getValue();
$message_sender = str_replace('"', '', $message_sender);
} else if ($single->getName() == 'X-Sender-Id') {
$message_sender_email = $single->getValue();
//$message_sender = str_replace('"', '', $message_sender);
}
}
$files = [];
foreach ($single_message->getPayload()->getParts() as $part) {
if ($part->filename && $part->filename!='') {
//echo $part->getMimeType();
$data = $this->service->users_messages_attachments->get('me', $mlist->id, $part->getBody()->getAttachmentId());
$file_name = $part->getFilename();
$data1 = strtr($data->getData(), ['-' => '+', '_' => '/']);
$fh = fopen(public_path("attachments/$file_name"), "w+");
//fwrite($fh, base64_decode($data->data));
fwrite($fh, base64_decode(utf8_encode($data1)));
fclose($fh);
$files[] = ['name'=>$file_name,
'mime_type' =>$part->mimeType];
}
}
//$sss = explode('<', $message_sender);
preg_match("/<(.*)>/", $message_sender_email, $output_array);
//dd($regularExpression);
$inboxMessage[] = [
'messageId' => $message_id,
'body' => $snippet,
'title' => $message_subject,
'revceived_date' => $message_date,
'messageSender' => $message_sender,
'messageSenderEmail' => $output_array[1],
'attachments' => $files
];
}
echo '<pre>';
print_r($inboxMessage);
exit;
//return $inboxMessage;
/*echo '<pre>';
print_r($inboxMessage);
exit;*/
}
function send_mail($mime, $threadId)
{
$message = new \Google_Service_Gmail_Message();
$message->setThreadId($threadId);
$message->setRaw($mime);
$this->service->users_messages->send('me', $message);
}
function getThreads()
{
//$url = "https://www.googleapis.com/gmail/v1/users/me/threads/key=<KEY>";
// dd($this->service);
$threads =[];
$threads_msgs =[];
$threadsResponse = $this->service->users_threads->listUsersThreads('me', ['maxResults' => 10,'labelIds'=>'INBOX','q'=>'is:unread']);
if ($threadsResponse->getThreads()) {
$threads = array_merge($threads, $threadsResponse->getThreads());
//$pageToken = $threadsResponse->getNextPageToken();
}
//dd($threads);
//echo '<pre>';
foreach ($threads as $thread) {
// print 'Thread with ID: ' . $thread->getId() . '<br/>';
$thread = $this->service->users_threads->get('me', $thread->getId(), ['format'=>'full']);
$messages = $thread->getMessages();
//dd($messages);
foreach ($messages as $mlist) {
/**************************************** new code*********************/
$optParamsGet2['format'] = 'full';
//$optParamsGet2['labelIds'] = 'INBOX';
$single_message = $this->service->users_messages->get($this->user, $mlist->id, $optParamsGet2);
$payload = $single_message->getPayload();
$parts = $payload->getParts();
// With no attachment, the payload might be directly in the body, encoded.
$body = $payload->getBody();
$FOUND_BODY = false;
if (!$FOUND_BODY) {
foreach ($parts as $part) {
if ($part['parts'] && !$FOUND_BODY) {
foreach ($part['parts'] as $p) {
if ($p['parts'] && count($p['parts']) > 0) {
foreach ($p['parts'] as $y) {
if (($y['mimeType'] === 'text/html') && $y['body']) {
$FOUND_BODY = $this->decodeBody($y['body']->data);
break;
}
}
} else if (($p['mimeType'] === 'text/html') && $p['body']) {
$FOUND_BODY = $this->decodeBody($p['body']->data);
break;
}
}
}
if ($FOUND_BODY) {
break;
}
}
}
if ($FOUND_BODY && count($parts) > 1) {
$images_linked = [];
foreach ($parts as $part) {
if ($part['filename']) {
array_push($images_linked, $part);
} else {
if ($part['parts']) {
foreach ($part['parts'] as $p) {
if ($p['parts'] && count($p['parts']) > 0) {
foreach ($p['parts'] as $y) {
if (($y['mimeType'] === 'text/html') && $y['body']) {
array_push($images_linked, $y);
}
}
} else if (($p['mimeType'] !== 'text/html') && $p['body']) {
array_push($images_linked, $p);
}
}
}
}
}
// special case for the wdcid...
preg_match_all('/wdcid(.*)"/Uims', $FOUND_BODY, $wdmatches);
if (count($wdmatches)) {
$z = 0;
foreach ($wdmatches[0] as $match) {
$z++;
if ($z > 9) {
$FOUND_BODY = str_replace($match, 'image0' . $z . '@', $FOUND_BODY);
} else {
$FOUND_BODY = str_replace($match, 'image00' . $z . '@', $FOUND_BODY);
}
}
}
preg_match_all('/src="cid:(.*)"/Uims', $FOUND_BODY, $matches);
if (count($matches)) {
$search = [];
$replace = [];
// let's trasnform the CIDs as base64 attachements
foreach ($matches[1] as $match) {
foreach ($images_linked as $img_linked) {
foreach ($img_linked['headers'] as $img_lnk) {
if ($img_lnk['name'] === 'Content-ID' || $img_lnk['name'] === 'Content-Id' || $img_lnk['name'] === 'X-Attachment-Id') {
if ($match === str_replace('>', '', str_replace('<', '', $img_lnk->value))
|| explode("@", $match)[0] === explode(".", $img_linked->filename)[0]
|| explode("@", $match)[0] === $img_linked->filename) {
$search = "src=\"cid:$match\"";
$mimetype = $img_linked->mimeType;
$attachment = $this->service->users_messages_attachments->get('me', $mlist->id, $img_linked['body']->attachmentId);
$data64 = strtr($attachment->getData(), ['-' => '+', '_' => '/']);
$replace = "src=\"data:" . $mimetype . ";base64," . $data64 . "\"";
$FOUND_BODY = str_replace($search, $replace, $FOUND_BODY);
}
}
}
}
}
}
}
// If we didn't find the body in the last parts,
// let's loop for the first parts (text-html only)
if (!$FOUND_BODY) {
foreach ($parts as $part) {
if ($part['body'] && $part['mimeType'] === 'text/html') {
$FOUND_BODY = $this->decodeBody($part['body']->data);
break;
}
}
}
// With no attachment, the payload might be directly in the body, encoded.
if (!$FOUND_BODY) {
$FOUND_BODY = $this->decodeBody($body['data']);
}
// Last try: if we didn't find the body in the last parts,
// let's loop for the first parts (text-plain only)
if (!$FOUND_BODY) {
foreach ($parts as $part) {
if ($part['body']) {
$FOUND_BODY = $this->decodeBody($part['body']->data);
break;
}
}
}
if (!$FOUND_BODY) {
$FOUND_BODY = '(No message)';
}
// Finally, print the message ID and the body
//dd( $FOUND_BODY);
/**************************************** End new code*********************/
//dd($mlist);
$message_id = $mlist->id;
$headers = $mlist->getPayload()->getHeaders();
$snippet = htmlentities($mlist->getSnippet());
//echo '<pre>';
//print_r( $headers);
//var_dump( $mlist);
$message_sender_email ='';
$response_id = '';
foreach ($headers as $single) {
//dd($single);
if ($single->getName() == 'Subject') {
$message_subject = $single->getValue();
} else if ($single->getName() == 'Message-ID') {
$gmail_msg_id = $single->getValue();
} else if ($single->getName() == 'response_id') {
$response_id = $single->getValue();
} else if ($single->getName() == 'Date') {
$message_date = $single->getValue();
// $message_date = date('M jS Y h:i A', strtotime($message_date)+(5*60*60));
$message_date = date('M jS Y h:i A', strtotime($message_date));
} else if ($single->getName() == 'From') {
$message_sender_email = htmlentities($single->getValue());
$message_sender= $single->getValue();
$message_sender = str_replace('"', '', $message_sender);
} else if ($single->getName() == 'X-Sender-Id') {
$message_sender_email = $single->getValue();
//$message_sender = str_replace('"', '', $message_sender);
}
}
$files = [];
foreach ($mlist->getPayload()->getParts() as $part) {
if ($part->filename && $part->filename!='') {
//echo $part->getMimeType();
$data = $this->service->users_messages_attachments->get('me', $mlist->id, $part->getBody()->getAttachmentId());
$file_name = $part->getFilename();
$data1 = strtr($data->getData(), ['-' => '+', '_' => '/']);
$fh = fopen(public_path("attachments/$file_name"), "w+");
//fwrite($fh, base64_decode($data->data));
fwrite($fh, base64_decode(utf8_encode($data1)));
fclose($fh);
$files[] = ['name'=>$file_name,
'mime_type' =>$part->mimeType];
}
}
//$sss = explode('<', $message_sender);
preg_match("/<(.*)>/", $message_sender_email, $output_array);
//dd($regularExpression);
$threads_msgs[$thread->getId()][] = [
'messageId' => $message_id,
'gmail_msg_id' => $gmail_msg_id,
//'body' => $snippet,
'body' => $FOUND_BODY,
'title' => $message_subject,
'revceived_date' => date('Y-m-d H:i:s', strtotime($message_date)),
'messageSender' => $message_sender,
'response_id' => $response_id,
'messageSenderEmail' => $output_array[1],
'attachments' => $files
];
}
}
//exit;
//dd($threads_msgs);
return $threads_msgs;
exit;
}
function decodeBody($body)
{
$rawData = $body;
$sanitizedData = strtr($rawData, '-_', '+/');
$decodedMessage = base64_decode($sanitizedData);
if (!$decodedMessage) {
$decodedMessage = false;
}
return $decodedMessage;
}
function modifyEmail()
{
$modify = new \Google_Service_Gmail_ModifyThreadRequest();
$modify->setRemoveLabelIds(["UNREAD"]);
$message = $this->service->users_threads->modify('me', 20, $modify);
}
}
<file_sep>/app/Http/Controllers/SlackController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Model\Config;
use App\Model\User;
use Auth;
use SlackApi;
use Redirect;
use URL;
class SlackController extends Controller
{
function getForm()
{
//$zoho = Config::where('title','zoho')->get();
$slack_record = Config::where('title', 'slack')->get();
$slack_arr=[];
foreach ($slack_record as $value) {
if ($value->key=='client_id') {
$slack_arr['client_id'] = $value->value;
}
if ($value->key=='secret') {
$slack_arr['secret'] = $value->value;
}
if ($value->key=='redirect_uri') {
$slack_arr['redirect_uri'] = $value->value;
}
if ($value->key=='channel') {
$slack_arr['channel'] = $value->value;
}
if ($value->key=='access_token') {
$slack_arr['access_token'] = $value->value;
}
}
//dd($zoho_arr);
//$zoho = Zoho::first();
return view('admin.setting.slack.add', compact('slack_arr'))->render();
}
function slackStore(Request $request)
{
//$id = $request->zoho_id;
$this->validate(
$request,
[
'client_id' => 'required',
'secret' => 'required',
'redirect_uri' => 'required',
//'channel' => 'required',
]
);
//dd($request->all());
$slack_client_id = Config::where('key', 'client_id')->where('title', 'slack')->first();
$slack_client_id->value = $request->client_id;
$slack_client_id->save();
$slack_secret = Config::where('key', 'secret')->where('title', 'slack')->first();
$slack_secret->value = $request->secret;
$slack_secret->save();
$slack_redirect = Config::where('key', 'redirect_uri')->where('title', 'slack')->first();
$slack_redirect->value = $request->redirect_uri;
$slack_redirect->save();
if ($request->channel) {
$slack_channel = Config::where('key', 'channel')->where('title', 'slack')->first();
$slack_channel->value = $request->channel;
$slack_channel->save();
}
if ($request->access_token) {
$slack_access_token = Config::where('key', 'access_token')->where('title', 'slack')->first();
$slack_access_token->value = $request->access_token;
$slack_access_token->save();
}
//return view('crm::zoho.add',compact('zoho'))->with('status', 'saved');
$arr['success'] = 'Slack credentials updated successfully';
return json_encode($arr);
exit;
}
function slackTokenRequest()
{
$slack_client_id = Config::where('key', 'client_id')->where('title', 'slack')->first();
/*$url = SlackApi::get('oauth.authorize',['client_id'=>$slack_client_id,
'redirect_uri'=>$slack_redirect]);
dd($url);*/
$url = 'https://slack.com/oauth/authorize?scope=incoming-webhook&client_id='.$slack_client_id->value.'&scope='.htmlentities('chat:write:user');
$return['url'] = $url;
// return Redirect::to($url);
return json_encode($return);
}
function getToken(Request $request)
{
//dd($request->all());
$slack_client_id = Config::where('key', 'client_id')->where('title', 'slack')->first();
$slack_secret = Config::where('key', 'secret')->where('title', 'slack')->first();
$slack_redirect = Config::where('key', 'redirect_uri')->where('title', 'slack')->first();
/*$url = "https://slack.com/api/oauth.access?client_id={$slack_client_id->value}&client_secret={$slack_secret->value}&code=$request->code";*/
//dd($url);
//echo $url;
if ($request->code) {
$response = SlackApi::post('oauth.access', ['client_secret'=>$slack_secret->value,'client_id'=>$slack_client_id->value,
'code'=>$request->code]);
/*if($response->ok)
{
$slack_access_token = Config::where('key','access_token')->where('title','slack')->first();
$slack_access_token->value = $response->access_token;
$slack_access_token->save();
}*/
echo 'Please copy the access token and paste in access token field and click the Update botton.<br/>';
dd('access_token ==> '.$response->access_token);
//return Redirect::to(URL::route('admin.setting.all'));
//dd('Access token reset successfully.');
}
}
}
<file_sep>/app/Modules/Crm/Http/Controllers/TicketController.php
<?php
namespace App\Modules\Crm\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use App\Modules\Crm\Http\Customer;
use App\Modules\Crm\Http\Employee;
use App\Modules\Crm\Http\Ticket;
use App\Modules\Crm\Http\GmailEmailLog;
use App\Modules\Crm\Http\TicketStatus;
use App\Modules\Crm\Http\Attachment;
use App\Modules\Crm\Http\Response;
use App\Services\GoogleGmail;
use App\Services\ImapGmail;
use App\Modules\Crm\Http\CustomerServiceType;
use App\Modules\Crm\Http\CustomerBillingPeriod;
use App\Modules\Crm\Http\CustomerServiceItem;
use App\Modules\Crm\Http\CustomerServiceRate;
use App\Modules\Crm\Http\CustomerLocation;
use App\Modules\Crm\Http\CustomerLocationContact;
use App\Model\Config;
use App\Model\Role;
use App\Model\User;
use Auth;
use Mail;
use URL;
use Session;
use Datatables;
use SlackApi;
use SlackChat;
class TicketController extends Controller
{
public function index(Request $request)
{
//dd($id);
if (!empty(Session::get('cust_id'))) {
$tickets_qry = Ticket::with(['responses','entered_by','customer','location','service_item','status','customer_contact'])->where('customer_id', Session::get('cust_id'));
} else {
$tickets_qry = Ticket::with(['responses','entered_by','customer','location','service_item','status','customer_contact']);
}
if ($request->filter=='clear') {
Session::forget('arr_input');
}
$paginate = 5;
if ($request->filter == 'yes' || (Session::has('arr_input') && count(Session::get('arr_input'))>0)) {
if ($request->filter=='yes') {
Session::put('arr_input', $request->all());
}
if (!empty(Session::get('arr_input.customer'))) {
$tickets_qry->where('customer_id', '=', Session::get('arr_input.customer'));
}
if (!empty(Session::get('arr_input.per_page'))) {
$paginate = Session::get('arr_input.per_page');
}
if (Session::has('arr_input.sort')) {
if (Session::get('arr_input.sort')=='created_at_asc') {
$tickets_qry->orderBy('tickets.created_at', 'asc');
}
if (Session::get('arr_input.sort')=='updated_at') {
$tickets_qry->orderBy('tickets.updated_at', 'desc');
}
if (Session::get('arr_input.sort') =='created_at_desc') {
$tickets_qry->orderBy('tickets.created_at', 'desc');
}
if (Session::has('arr_input.sort')=='priority') {
$tickets_qry->orderBy('tickets.priority', 'asc');
}
}
if (Session::has('arr_input.priority') && count(Session::get('arr_input.priority'))>0) {
foreach (Session::get('arr_input.priority') as $priority => $on) {
$tickets_qry->orWhere('tickets.priority', $priority);
//echo $priority.'<br/>';
}
}
if (!empty(Session::get('arr_input.assigned_to'))) {
$tickets_qry->whereHas('assigned_to', function ($query) {
$query->where('user_id', Session::get('arr_input.assigned_to'));
});
}
} else {
$tickets_qry->orderBy('tickets.created_at', 'desc');
}
$tickets = $tickets_qry->paginate($paginate);
$customers_obj = Customer::with(['locations','locations.contacts'])->get();
$customers = [];
if ($customers_obj->count()) {
foreach ($customers_obj as $customer) {
$customers[$customer->id]=$customer->name.'('.$customer->email_domain.')';
//dd($user->id);
}
}
$users_obj = Role::with('users')->where('name', 'manager')->orWhere('name', 'technician')->get();
$users=[];
if ($users_obj->count()) {
foreach ($users_obj as $user_obj) {
foreach ($user_obj->users as $user) {
$users[$user->id]=$user->f_name." ".$user->l_name.' ('.$user_obj->name.')';
//dd($user->id);
}
}
}
$statuses_ = TicketStatus::all();
$statuses = [];
if ($statuses_->count()) {
foreach ($statuses_ as $status) {
$statuses[$status->id]=$status->title;
//dd($user->id);
}
}
return view('crm::ticket.index.index', compact('tickets', 'customers', 'users', 'statuses'));
}
public function ajaxDataIndex($id = null)
{
//$controller = $this->controller;
$global_date = $this->global_date;
if ($id!='') {
$tickets = Ticket::with(['responses','assigned_to','entered_by','customer','location','service_item','status'])->where('customer_id', $id);
} else {
$tickets = Ticket::with(['responses','assigned_to','entered_by','customer','location','service_item','status']);
}
return Datatables::of($tickets)
->addColumn('created_by', function ($ticket) {
if ($ticket->entered_by) {
$return = $ticket->entered_by->f_name;
} elseif ($ticket->type =='email') {
$return = '<button type="button" class="btn bg-gray-active btn-sm">
<span>system</span>
</button>';
}
return $return;
})
->addColumn('customer_info', function ($ticket) {
$return = '<button type="button" class="btn bg-gray-active btn-sm">
<span>';
if ($ticket->customer) {
$return .= '<i class="fa fa-user"></i>'. $ticket->customer->name;
} elseif ($ticket->email) {
$return .= '<i class="fa fa-envelope"></i>'.$ticket->email;
}
$return .='</span></button>';
if ($ticket->location) {
$return .= ' <button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-map-marker"></i>
<span>'.$ticket->location->location_name.'</span>
</button>';
}
if ($ticket->service_item) {
$return .= ' <button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-gears"></i>
<span>'.$ticket->service_item->title.'</span>
</button>';
}
return $return;
})
->addColumn('assigned_to', function ($ticket) {
//$customer->locations //loop
$return = '';
if ($ticket->assigned) {
foreach ($ticket->assigned_to as $employee) {
$return .= '<button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-user"></i>
<span>'.$employee->f_name.'</span>
</button>';
}
}
return $return;
})
->editColumn('created_at', function ($ticket) use ($global_date) {
return date($global_date, strtotime($ticket->created_at));
})
->editColumn('priority', function ($ticket) {
$btn_class = 'bg-gray';
if ($ticket->priority == 'normal') {
$btn_class = 'bg-blue';
}
if ($ticket->priority == 'high') {
$btn_class = 'bg-green';
}
if ($ticket->priority == 'urgent') {
$btn_class = 'bg-yellow';
}
if ($ticket->priority == 'critical') {
$btn_class = 'bg-red';
}
$return = '<button type="button" class="btn '.$btn_class.' btn-sm">
<span>'.$ticket->priority.'</span>
</button>';
return $return;
})
->editColumn('status', function ($ticket) {
$return ='<button type="button" class="btn btn-sm" style="background-color:'.$ticket->status->color_code.'">
<span>'.$ticket->status->title.'</span>
</button>';
return $return;
})
->setRowId('id')
->make(true);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$customers_obj = Customer::with(['locations','locations.contacts'])->get();
$customers = [];
if ($customers_obj->count()) {
foreach ($customers_obj as $customer) {
$customers[$customer->id]=$customer->name.'('.$customer->email_domain.')';
//dd($user->id);
}
}
$managers_obj = Role::with('users')->where('name', 'manager')->orWhere('name', 'technician')->get();
$users = [];
$roles = [];
if ($managers_obj->count()) {
foreach ($managers_obj as $manager_obj) {
foreach ($manager_obj->users as $user) {
$users[$user->id]=$user->f_name." ".$user->l_name.'('.$manager_obj->name.')';
//dd($user->id);
}
}
}
$statuses_ = TicketStatus::all();
$statuses = [];
if ($statuses_->count()) {
foreach ($statuses_ as $status) {
$statuses[$status->id]=$status->title;
//dd($user->id);
}
}
return view('crm::ticket.add', compact('users', 'statuses'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$slack_channel = Config::where('key', 'channel')->where('title', 'slack')->first();
$slack_access_token = Config::where('key', 'access_token')->where('title', 'slack')->first();
config(['services.slack.token' => $slack_access_token->value]);
//customer contact is text field but with magic suggest it adds an array, throwing exception upon validation, so modifyig it, i.e assigning the aaray value to customer_contact
$request->merge(['customer_contact' => $request->customer_contact[0]]);
//saving customer_contact value in session to display upon validation in blade.
$request->session()->put('cust_cont', $request->customer_contact);
$validator = \Validator::make(\Request::all(), [
'customer_contact' => 'required',
'title'=>'required',
'body'=>'required',
'status'=>'required',
]);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput(\Request::except('customer_contact'));
}
$ids = explode('_', $request->customer_contact);
$customer_id = $ids[2];
$location_id = $ids[1];
$customer_contact_id = $ids[0];
// dd( $ids);
$ticket = new Ticket;
$ticket->customer_location_contact_id = $customer_contact_id;
$ticket->customer_id = $customer_id;
$ticket->location_id= $location_id;
$ticket->service_item_id= $request->service_item;
$ticket->title= $request->title;
$ticket->created_by= Auth::user()->id;
$ticket->entered_date = date("Y-m-d");
$ticket->entered_time = date('h:i:s');
$ticket->body= $request->body;
$ticket->ticket_status_id= $request->status;
$ticket->priority= $request->priority;
$ticket->save();
foreach ($request->users as $user) {
# code...
if (!$user=='') {
$ticket->assigned_to()->attach($user);
}
}
$status = TicketStatus::find($ticket->ticket_status_id);
$slack_msg = 'New ticket #'.$ticket->id.': '.$ticket->title.'<br/>';
$slack_msg .= 'Description'.'<br/>';
$slack_msg .= $ticket->body;
$slack_msg .= 'Priority : '.$ticket->priority.'<br/>';
$slack_msg .= 'Status : '.$status->title.'<br/>';
$response = SlackChat::message($slack_channel->value, $slack_msg);
//dd( $response);
//$customer->service_items()->save($service_item);
return redirect()->intended('admin/crm/ticket');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$ticket = Ticket::where('id', $id)->with(['assigned_to','attachments','entered_by','customer','location','service_item','customer_contact','entered_by.roles'])->first();
$responses_result= Response::where('ticket_id', $id)->with(['responder'])->orderBy('entered_date', 'asc')->orderBy('entered_time', 'asc')->get();
$responses = [];
foreach ($responses_result as $response) {
$responses[$response->entered_date][] = $response;
# code...
}
$managers_obj = Role::with('users')->where('name', 'manager')->orWhere('name', 'technician')->get();
$users = [];
$roles = [];
if ($managers_obj->count()) {
foreach ($managers_obj as $manager_obj) {
foreach ($manager_obj->users as $user) {
$users[$user->id]=$user->f_name." ".$user->l_name.' ('.$manager_obj->name.')';
//dd($user->id);
}
}
}
//dd($users);
$assigned_users = [];
//dd($ticket->assigned_to);
foreach ($ticket->assigned_to as $assigned) {
$assigned_users[]=$assigned->email;
//dd($user->id);
}
$customers_records = Customer::where('is_active', 1)->get();
$customers = [];
foreach ($customers_records as $customer) {
$customers[$customer->id]=$customer->name.' <'.$customer->email_domain.'>';
}
//dd($assigned_users);
$customer_assigned = '';
if ($ticket->customer) {
$customer_assigned = $ticket->customer->id;
}
$tickets = [];
$tickets_ = Ticket::where('id', '<>', $id)->get();
// dd($tickets_);
foreach ($tickets_ as $ticket_) {
$tickets[$ticket_->id] = $ticket_->id.'. '.$ticket_->title;
}
$statuses_ = TicketStatus::all();
$status_arr = [];
if ($statuses_->count()) {
foreach ($statuses_ as $status) {
$obj = new \stdClass();
$obj->id = $status->id;
$obj->text = $status->title;
$status_arr[] = $obj;
}
}
$statuses = $status_arr;
//var_dump($statuses);
//exit;
$smtp_arr = Config::where('title', 'smtp')->get();
$smtp =[];
foreach ($smtp_arr as $value) {
if ($value->key=='server_address') {
$server_address = $value->value;
}
if ($value->key=='gmail_address') {
$gmail_address = $value->value;
}
if ($value->key=='gmail_password') {
$password = $value->value;
}
if ($value->key=='port') {
$port= $value->value;
}
}
return view('crm::ticket.show.show', compact('ticket', 'users', 'assigned_users', 'responses', 'customers', 'customer_assigned', 'tickets', 'statuses', 'gmail_address'));
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroyMultiple(Request $request)
{
//dd($request->all());
$ids_arr = explode(',', $request->ids);
foreach ($ids_arr as $id) {
# code...
$ticket = Ticket::where('id', $id)->with(['responses','assigned_to','attachments','entered_by','customer','location','service_item','responses.responder'])->first();
$ticket->responses()->delete();
$ticket->attachments()->delete();
$ticket->assigned_to()->delete();
$ticket->delete();
}
return 'yes';
}
public function destroy(Request $request)
{
$id = $request->id;
$ticket = Ticket::where('id', $id)->with(['responses','assigned_to','attachments','entered_by','customer','location','service_item','responses.responder'])->first();
$ticket->responses()->delete();
$ticket->attachments()->delete();
$ticket->assigned_to()->delete();
$ticket->delete();
//Session::flash('flash_message', 'User successfully deleted!');
return redirect()->intended('admin/crm/ticket');
}
function addResponse(Request $request)
{
if ($request->original_ticket !='') {
$original_ticket_record = Ticket::where('id', $request->original_ticket)->first();
}
if ($request->original_ticket !='') {
// dd('ff');
$body .= '<p>Its duplicate of <a href="'.URL::route('admin.ticket.show', $request->original_ticket).'">'.$original_ticket_record->title.'</a>';
}
$response_body = $request->body;
//src="/ckfinder
//dd($vv);
$flag = $request->response_flag;
$response = new Response;
$response->ticket_id = $request->ticket_id;
$response->body = htmlentities($response_body);
$response->responder_id = Auth::user()->id;
$response->entered_date = date("Y-m-d");
$response->entered_time = date('h:i:s');
if ($flag == 'note') {
$response->response_type = 'note';
}
$response->save();
$ticket = Ticket::where('id', $request->ticket_id)->with(['assigned_to','attachments','entered_by','customer','location','service_item'])->first();
if ($request->original_ticket !='') {
$ticket->status = 'closed';
$ticket->save();
}
$responses_result= Response::where('ticket_id', $request->ticket_id)->with(['responder'])->orderBy('entered_date', 'asc')->get();
$responses = [];
foreach ($responses_result as $response) {
$responses[$response->entered_date][] = $response;
# code...
}
$arr['success'] = 'Response Added successfully';
$smtp_arr = Config::where('title', 'smtp')->get();
$smtp =[];
foreach ($smtp_arr as $value) {
if ($value->key=='server_address') {
$server_address = $value->value;
}
if ($value->key=='gmail_address') {
$gmail_address = $value->value;
}
if ($value->key=='gmail_password') {
$password = $value->value;
}
if ($value->key=='port') {
$port= $value->value;
}
}
config(['mail.driver' => 'smtp',
'mail.host' => $server_address,
'mail.port' => $port,
'mail.encryption' => 'ssl',
'mail.username' => $gmail_address,
'mail.password' => $<PASSWORD>,
'mail.from' =>['address'=>$gmail_address,'name'=>'Nexgentec']]);
//dd(config('mail'));
$bcc =[];
$cc = [];
if ($flag =='reply') {
$bcc = $request->bcc;
$cc = $request->cc;
}
if ($ticket->type=='email' && $ticket->email!='' && $flag =='reply') {
$variables = ["firstname"=>$ticket->sender_name,"lastname"=>"","response"=>$response_body];
$email_body = Auth::user()->email_template;
foreach ($variables as $key => $value) {
$email_body = str_replace('%'.$key.'%', $value, $email_body);
}
//echo $string;
Mail::send('crm::ticket.email.response', ['body'=>$email_body], function ($message) use ($ticket, $gmail_address, $response, $bcc, $cc) {
/* $swiftMessage = $message->getSwiftMessage();
$headers = $swiftMessage->getHeaders();
$headers->addTextHeader('In-Reply-To', $ticket->gmail_msg_id);
$headers->addTextHeader('References', $ticket->gmail_msg_id);*/
$message->getHeaders()->addTextHeader('In-Reply-To', $ticket->gmail_msg_id);
$message->getHeaders()->addTextHeader('References', $ticket->gmail_msg_id);
$message->getHeaders()->addTextHeader('response_id', $response->id);
if (count($bcc)>0) {
foreach ($bcc as $key => $bcc_email) {
$message->bcc(trim($bcc_email), $name = null);
}
}
if (count($cc)>0) {
foreach ($cc as $key => $cc_email) {
$message->cc(trim($cc_email), $name = null);
}
}
$message->from(trim($gmail_address), Auth::user()->f_name.' '.Auth::user()->l_name);
$message->to(trim($ticket->email), $ticket->sender_name);
$message->subject($ticket->title);
});
if (count(Mail::failures()) > 0) {
echo "There was one or more failures. They were: <br />";
foreach (Mail::failures() as $failure) {
echo " - $failure <br />";
}
}
}
if ($ticket->type=='ticket' && $flag =='reply') {
$variables = ["firstname"=>$ticket->customer_contact->f_name,"lastname"=>$ticket->customer_contact->l_name,"response"=>$response_body];
$email_body = Auth::user()->email_template;
foreach ($variables as $key => $value) {
$email_body = str_replace('%'.$key.'%', $value, $email_body);
}
//echo $string;
Mail::send('crm::ticket.email.response', ['body'=>$email_body], function ($message) use ($ticket, $gmail_address, $response, $bcc, $cc, $request) {
if (count($bcc)>0) {
foreach ($bcc as $key => $bcc_email) {
$message->bcc(trim($bcc_email), $name = null);
}
}
if (count($cc)>0) {
foreach ($cc as $key => $cc_email) {
$message->cc(trim($cc_email), $name = null);
}
}
$message->to(trim($request->to_email), $ticket->customer_contact->f_name.' '.$ticket->customer_contact->l_name)->subject($ticket->title)->from(trim($gmail_address), Auth::user()->f_name.' '.Auth::user()->l_name);
});
if (count(Mail::failures()) > 0) {
echo "There was one or more failures. They were: <br />";
foreach (Mail::failures() as $failure) {
echo " - $failure <br />";
}
}
}
$view = view('crm::ticket.ajax_ticket_timeline', compact('ticket', 'responses'));
$arr['html_content'] = (string) $view;
return json_encode($arr);
exit;
//dd($responses);
//return
}
function ajaxAssignCustomer(Request $request)
{
//dd($request->all());
$this->validate(
$request,
[
'customer_contact' => 'required',
]
);
$ids = explode('|', $request->customer_contact[0]);
$customer_id = $ids[2];
$location_id = $ids[1];
$customer_contact_id = $ids[0];
$ticket = Ticket::find($request->id);
$ticket->customer_id = $customer_id;
$ticket->location_id= $location_id;
$ticket->customer_location_contact_id = $customer_contact_id;
$ticket->save();
$arr['success'] = 'Changed customer contact sussessfully';
return json_encode($arr);
exit;
}
function ajaxGetTicketById($id)
{
$ticket = Ticket::where('id', $id)->with(['assigned_to','status','attachments','entered_by','customer','location','service_item','customer_contact'])->first();
$arr['ticket'] = $ticket;
return json_encode($arr);
exit;
}
function ajaxAssignUsersMultiple(Request $request)
{
//dd($request->all());
$this->validate(
$request,
[
'users' => 'required',
]
);
$tickets = explode(',', $request->ids);
foreach ($tickets as $ticket_id) {
$ticket = Ticket::find($ticket_id);
$ticket->assigned_to()->detach();
//dd($request->users);
foreach ($request->users as $key => $user) {
# code...
if (!$user=='') {
$ticket->assigned_to()->attach($user);
}
}
$ticket_ = Ticket::where('id', $ticket_id)->with(['assigned_to'])->first();
$managers_obj = Role::with('users')->where('name', 'manager')->orWhere('name', 'technician')->get();
// dd($ticket_->assigned_to);
$users = [];
if ($managers_obj->count()) {
foreach ($managers_obj as $manager_obj) {
foreach ($manager_obj->users as $user) {
//if($user->id == )
$users[$user->id]=$user->f_name." ".$user->l_name.' ('.$manager_obj->name.')';
//dd($user->id);
}
}
}
$assigned_users = [];
if ($ticket_->assigned_to->count()!=0) {
foreach ($ticket_->assigned_to as $key => $assigned) {
//dd($assigned);
$assigned_users[$assigned->id]=$users[$assigned->id];
}
}
}
//dd($ticket_);
$arr['success'] = 'Assigned Users to tickets sussessfully';
//$arr['assigned_users'] = $assigned_users;
//$arr['ticket_id'] = $request->id;
return json_encode($arr);
exit;
}
function ajaxAssignUsers(Request $request)
{
//dd($request->all());
$this->validate(
$request,
[
'users' => 'required',
]
);
$ticket = Ticket::find($request->id);
$ticket->assigned_to()->detach();
//dd($request->users);
foreach ($request->users as $key => $user) {
# code...
if (!$user=='') {
$ticket->assigned_to()->attach($user);
}
}
$ticket_ = Ticket::where('id', $request->id)->with(['assigned_to'])->first();
$managers_obj = Role::with('users')->where('name', 'manager')->orWhere('name', 'technician')->get();
// dd($ticket_->assigned_to);
$users = [];
if ($managers_obj->count()) {
foreach ($managers_obj as $manager_obj) {
foreach ($manager_obj->users as $user) {
//if($user->id == )
$users[$user->id]=$user->f_name." ".$user->l_name.' ('.$manager_obj->name.')';
//dd($user->id);
}
}
}
$assigned_users = [];
if ($ticket_->assigned_to->count()!=0) {
foreach ($ticket_->assigned_to as $key => $assigned) {
//dd($assigned);
$assigned_users[$assigned->id]=$users[$assigned->id];
}
}
//dd($ticket_);
$arr['success'] = 'Assigned Users to ticket sussessfully';
$arr['assigned_users'] = $assigned_users;
$arr['ticket_id'] = $request->id;
return json_encode($arr);
exit;
}
function ajaxUpdateStatusMultiple(Request $request)
{
/*$this->validate($request,
[
'users' => 'required',
]);*/
if ($request->multi_status_ids) {
$tickets = explode(',', $request->multi_status_ids);
foreach ($tickets as $ticket_id) {
$ticket = Ticket::find($ticket_id);
$ticket->ticket_status_id = $request->status;
//$ticket->priority= $request->priority;
$ticket->save();
}
}
$arr['success'] = 'Changed status sussessfully';
return json_encode($arr);
exit;
}
function ajaxUpdatePriorityMultiple(Request $request)
{
if ($request->multi_priority_ids) {
$tickets = explode(',', $request->multi_priority_ids);
foreach ($tickets as $ticket_id) {
$ticket = Ticket::find($ticket_id);
$ticket->priority= $request->priority;
$ticket->save();
}
}
$arr['success'] = 'Changed priority sussessfully';
return json_encode($arr);
exit;
}
function ajaxUpdateTitle(Request $request)
{
//dd($request->all());
if ($request->name=='change_title') {
$ticket_ = Ticket::find($request->pk);
$ticket_->title= $request->value;
$ticket_->save();
}
return 'ok';
exit;
}
function ajaxUpdateStatusPriority(Request $request)
{
//dd($request->all());
if ($request->name=='ticket_priority') {
$ticket_ = Ticket::find($request->pk);
$ticket_->priority= $request->value;
$ticket_->save();
}
if ($request->name=='ticket_status') {
$ticket_ = Ticket::find($request->pk);
$ticket_->ticket_status_id = $request->value;
$ticket_->save();
}
return 'ok';
exit;
}
function ajaxDeleteAssignedUser($t_id, $u_id)
{
$ticket = Ticket::find($t_id);
$ticket->assigned_to()->detach([$u_id]);
$ticket_ = Ticket::where('id', $t_id)->with(['assigned_to'])->first();
$managers_obj = Role::with('users')->where('name', 'manager')->orWhere('name', 'technician')->get();
// dd($ticket_->assigned_to);
$users = [];
if ($managers_obj->count()) {
foreach ($managers_obj as $manager_obj) {
foreach ($manager_obj->users as $user) {
//if($user->id == )
$users[$user->id]=$user->f_name." ".$user->l_name.' ('.$manager_obj->name.')';
//dd($user->id);
}
}
}
$assigned_users = [];
if ($ticket_->assigned_to->count()!=0) {
foreach ($ticket_->assigned_to as $key => $assigned) {
//dd($assigned);
$assigned_users[$assigned->id]=$users[$assigned->id];
}
}
//dd($ticket_);
$arr['success'] = 'Employee successfully detached';
$arr['assigned_users'] = $assigned_users;
$arr['ticket_id'] = $t_id;
return json_encode($arr);
}
function ajaxDeleteAssignedCustomer($t_id)
{
$ticket = Ticket::find($t_id);
$ticket->customer_id = 0;
$ticket->save();
$ticket_ = Ticket::where('id', $t_id)->with(['customer'])->first();
//dd($ticket_);
$arr['success'] = 'Customer detached from ticket sussessfully';
$arr['customer_assigned'] = '';
$arr['ticket_id'] = $t_id;
return json_encode($arr);
exit;
}
function readGmail()
{
$gmail = new GoogleGmail();
//$emails = $gmail->getMessages();0
$threads = $gmail->getThreads();
foreach ($threads as $key => $thread) {
//dd();
foreach ($thread as $email) {
//dd($email);
$already_imported=GmailEmailLog::where('gmail_msg_id', $email['gmail_msg_id'])->count();
$body =$email['body'];
if (!$already_imported) {
if ($key==$email['messageId']) {
//dd($key);
$chk_ticket = Ticket::where('gmail_msg_id', $email['gmail_msg_id'])->first();
//dd($chk_ticket);
if (!$chk_ticket) {
$customer_email = $email['messageSenderEmail'];
$customer = Customer::where('email_domain', $customer_email)->first();
if ($customer) {
$customer_id = $customer->id;
}
$ticket = new Ticket;
if ($customer) {
$ticket->customer_id = $customer_id;//$request->customer_id;
} else {
$ticket->email = $customer_email;
$ticket->sender_name = $email['messageSender'];
}
$email_log= new GmailEmailLog;
$email_log->gmail_msg_id=$email['gmail_msg_id'];
$email_log->save();
$ticket->gmail_msg_id = $email['gmail_msg_id'];
$ticket->entered_date= date('Y-m-d', strtotime($email['revceived_date']));
$ticket->entered_time = date('h:i:s', strtotime($email['revceived_date']));
$ticket->title= $email['title'];
$ticket->body= $body;
$ticket->type= 'email';
$ticket->thread_id= $key;
$status = TicketStatus::where('title', 'new')->first();
$ticket->ticket_status_id = $status->id;
$ticket->priority= 'normal';
//dd($ticket);
$ticket->save();
$ticket_id = $ticket->id;
if ($email['attachments']) {
foreach ($email['attachments'] as $attachment) {
// $body .= urlencode('<a href="'.url('/')."/attachments/$attachment".'" data-lightbox="$attachment"><img src="'.url('/')."/attachments/$attachment".'" /> </a>');
$new_attachment = new Attachment;
$new_attachment->name = $attachment['name'];
$new_attachment->type = $attachment['mime_type'];
$ticket->attachments()->save($new_attachment);
}
}
}
} else {
if ($chk_ticket) {
$ticket_id = $chk_ticket->id;
}
//check if gmial_msg_id exist, it means its customer earlier reply/response to our/employee reponse.
$check_response_already_exist = Response::where('gmail_msg_id', $email['gmail_msg_id'])->first();
if (!$check_response_already_exist) {
//check if response_id exist, it means that its response and already exist in database.
$chk_reponse_by_id = Response::find($email['response_id']);
if (!$chk_reponse_by_id) {
$_ticket = Ticket::where('thread_id', $key)->first();
$status = TicketStatus::where('title', 'open')->first();
$_ticket->ticket_status_id= $status->id;
$_ticket->save();
$response = new Response;
$response->ticket_id = $ticket_id;
$response->body = $body;
$response->sender_type = 'customer';
$response->entered_date = date('Y-m-d', strtotime($email['revceived_date']));
$response->entered_time = date(' h:i:s', strtotime($email['revceived_date']));
$email_log= new GmailEmailLog;
$email_log->gmail_msg_id=$email['gmail_msg_id'];
$email_log->save();
$response->gmail_msg_id = $email['gmail_msg_id'];
$response->save();
}
}
}
}
}
}
$arr['success'] = 'Tickets added sussessfully from email';
return json_encode($arr);
exit;
}
function ajaxGetContacts(Request $request)
{
//dd($request->customer_contact);
$name = $request->customer_contact;
if (!empty(Session::get('cust_id'))) {
$customers = Customer::with(['locations.contacts'=>function ($query) use ($name) {
$query->where('f_name', 'like', '%'.$name.'%')->orWhere('l_name', 'like', '%'.$name.'%');
}])->where('is_active', 1)->where('id', Session::get('cust_id'))->get();
} else {
$customers = Customer::with(['locations.contacts'=>function ($query) use ($name) {
$query->where('f_name', 'like', '%'.$name.'%')->orWhere('l_name', 'like', '%'.$name.'%');
}])->where('is_active', 1)->get();
}
$contacts = [];
foreach ($customers as $customer) {
foreach ($customer->locations as $location) {
if (count($location->contacts)>0) {
foreach ($location->contacts as $contact) {
$contacts [] = ['id'=>$contact->id.'_'.$location->id.'_'.$customer->id,
'name'=>$contact->f_name.' '.$contact->l_name,
'customer'=>$customer->name,
'location'=> $location->location_name,
'country' =>$location->country,
'city'=>$location->city];
}
}
}
# code...
}
return json_encode($contacts);
}
function searchTickets(Request $request)
{
if ($request->ticket) {
$tickets_result = Ticket::with('customer')->where('title', 'like', '%'.$request->ticket.'%')->orWhere('body', 'like', '%'.$request->ticket.'%')->get();
$tickets = [];
foreach ($tickets_result as $ticket) {
$ticket_arr['id'] = $ticket->id;
if ($ticket->customer) {
$ticket_arr['ticket_title'] = $ticket->title.' ('.$ticket->customer->name.')';
}
if ($ticket->type =='email') {
$ticket_arr['ticket_title'] = $ticket->title.' ('.$ticket->email.')';
}
$tickets[] = $ticket_arr;
}
echo json_encode([
"status" => true,
"error" => null,
"data" => [
"tickets" => $tickets
]
]);
} else {
echo json_encode([
"status" => true,
"error" => null,
"data" => [
"tickets" => []
]
]);
}
}
function getContactsByLoc($loc_id)
{
$location = CustomerLocation::with('contacts')->where('id', $loc_id)->first();
//dd($location);
$loc_contacts = [];
foreach ($location->contacts as $contact) {
$loc_contacts[]= ['id'=>$contact->id,
'text'=>$contact->f_name.' '.$contact->l_name];
}
return json_encode($loc_contacts);
exit;
}
public function addTicket(Request $request)
{
//dd($request->all());
$slack_channel = Config::where('key', 'channel')->where('title', 'slack')->first();
$slack_access_token = Config::where('key', 'access_token')->where('title', 'slack')->first();
config(['services.slack.token' => $slack_access_token->value]);
//$slack_msg = 'New ticket created :'.$ticket->title;
$this->validate(
$request,
[
'ticket_location_contact' => 'required',
'ticket_subject'=>'required',
'ticket_status'=>'required',
]
);
$customer_id = Session::get('cust_id');
$location_id = $request->ticket_location;
$customer_contact_id = $request->ticket_location_contact;
// dd( $ids);
$ticket = new Ticket;
$ticket->customer_location_contact_id = $customer_contact_id;
$ticket->customer_id = $customer_id;
$ticket->location_id= $location_id;
$ticket->service_item_id= $request->ticket_service_item;
$ticket->title= $request->ticket_subject;
$ticket->created_by= Auth::user()->id;
$ticket->entered_date = date("Y-m-d");
$ticket->entered_time = date('h:i:s');
$ticket->body= $request->notes;
$ticket->ticket_status_id= $request->ticket_status;
$ticket->priority= $request->ticket_priority;
$ticket->save();
foreach ($request->ticket_assign as $user) {
# code...
if (!$user=='') {
$ticket->assigned_to()->attach($user);
}
}
$status = TicketStatus::find($ticket->ticket_status_id);
$slack_msg = 'New ticket #'.$ticket->id.': '.$ticket->title.'<br/>';
$slack_msg .= 'Description'.'<br/>';
$slack_msg .= $ticket->body;
$slack_msg .= 'Priority : '.$ticket->priority.'<br/>';
$slack_msg .= 'Status : '.$status->title.'<br/>';
$response = SlackChat::message($slack_channel->value, $slack_msg);
//dd( $response);
//$customer->service_items()->save($service_item);
return json_encode(['success'=>'yes']);
//return redirect()->intended('admin/crm/ticket');
}
}
<file_sep>/app/Modules/Crm/Database/Migrations/2016_03_09_145105_tickets.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Tickets extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tickets', function (Blueprint $table) {
$table->increments('id');
$table->integer('customer_id');
$table->integer('created_by');
$table->date('created_at');
$table->date('updated_at');
$table->integer('location_id');
$table->integer('service_item_id');
$table->string('title', 15);
$table->text('body');
$table->enum('status', ['open','closed','pending']);
$table->enum('priority', ['low','normal','high']);
});
Schema::create('attachments', function (Blueprint $table) {
$table->increments('id');
$table->integer('ticket_id');
$table->date('created_at');
$table->date('updated_at');
$table->string('name', 256);
$table->string('type', 100);
});
Schema::create('responses', function (Blueprint $table) {
$table->increments('id');
$table->integer('ticket_id');
$table->dateTime('created_at');
$table->date('updated_at');
$table->integer('responder_id');
$table->text('body');
});
Schema::create('ticket_user', function (Blueprint $table) {
$table->integer('ticket_id');
$table->integer('user_id');
$table->dateTime('created_at');
$table->date('updated_at');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
/*Schema::drop('tickets');
Schema::drop('responses');
Schema::drop('ticket_user');
Schema::drop('attachments');*/
}
}
<file_sep>/app/Modules/Vendor/Http/VendorContact.php
<?php
namespace App\Modules\Vendor\Http;
use Illuminate\Database\Eloquent\Model;
class VendorContact extends Model
{
public function contacts()
{
return $this->belongsTo('App\Modules\Vendor\Http\Vendor');
}
}
<file_sep>/app/Modules/Crm/Http/Attachment.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class Attachment extends Model
{
public function ticket()
{
return $this->belongsTo('App\Modules\Crm\Http\Ticket', 'location_id');
}
}
<file_sep>/public/phpmyadmin/js/jquery/jquery.event.drag-2.0.js
../../../javascript/jquery-event-drag/jquery.event.drag.min.js<file_sep>/app/Modules/Crm/Http/Customer.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
//
public function service_items()
{
return $this->hasMany('App\Modules\Crm\Http\CustomerServiceItem');
}
/* public function billing_periods()
{
return $this->hasMany('App\Modules\Crm\Http\CustomerBillingPeriod');
}*/
public function locations()
{
return $this->hasMany('App\Modules\Crm\Http\CustomerLocation');
}
public function tickets()
{
return $this->hasMany('App\Modules\Crm\Http\Ticket');
}
public function default_rates()
{
return $this->hasMany('App\Modules\Crm\Http\DefaultRate');
}
public function assets()
{
return $this->hasMany('App\Modules\Assets\Http\Asset');
}
public function notes()
{
return $this->hasMany('App\Modules\Crm\Http\CustomerNote');
}
public function vendors()
{
return $this->belongsToMany('App\Modules\Vendor\Http\Vendor', 'customer_vendor', 'customer_id', 'vendor_id')->withTimestamps()
->withPivot('id', 'location_id', 'auth_contact_name', 'phone_number', 'account_number', 'portal_url', 'notes');
}
public function products()
{
return $this->belongsToMany('App\Modules\Crm\Http\Product');
}
public function invoices()
{
return $this->hasMany('App\Modules\Crm\Http\Invoice');
}
public function vend_cust_loc1()
{
return $this->belongsToMany('App\Modules\Crm\Http\CustomerLocation', 'customer_vendor', 'id', 'location_id');
}
public function domain()
{
return $this->hasOne('App\Modules\Nexpbx\Http\Domain');
}
}
<file_sep>/app/Modules/Crm/Database/2016_01_18_153513_service_items.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ServiceItems extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('customer_service_items', function (Blueprint $table) {
$table->increments('id');
$table->integer('customer_id');
$table->date('created_at');
$table->date('updated_at');
$table->integer('service_type_id');
$table->string('title', 15);
$table->integer('billing_period_id');
$table->integer('default_rate_id');
$table->date('start_date');
$table->date('end_date');
$table->tinyInteger('is_active');
$table->tinyInteger('is_default');
$table->text('comments');
$table->decimal('unit_price', 5);
$table->integer('quantity');
$table->decimal('estimate', 5);
$table->integer('estimated_hours');
$table->enum('bill_for', ['actual_hours','project_estimate']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('customer_service_items');
}
}
<file_sep>/app/Modules/Crm/Http/Ticket.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class Ticket extends Model
{
//
public function responses()
{
return $this->hasMany('App\Modules\Crm\Http\Response');
}
public function attachments()
{
return $this->hasMany('App\Modules\Crm\Http\Attachment');
}
/* public function billing_periods()
{
return $this->hasMany('App\Modules\Crm\Http\CustomerBillingPeriod');
}*/
public function assigned_to()
{
return $this->belongsToMany('App\Model\User')->withTimestamps();
}
public function entered_by()
{
return $this->belongsTo('App\Model\User', 'created_by');
}
public function location()
{
return $this->belongsTo('App\Modules\Crm\Http\CustomerLocation', 'location_id');
}
public function service_item()
{
return $this->belongsTo('App\Modules\Crm\Http\CustomerServiceItem', 'service_item_id');
}
public function customer_contact()
{
return $this->belongsTo('App\Modules\Crm\Http\CustomerLocationContact', 'customer_location_contact_id');
}
public function customer()
{
return $this->belongsTo('App\Modules\Crm\Http\Customer');
}
public function status()
{
return $this->belongsTo('App\Modules\Crm\Http\TicketStatus', 'ticket_status_id');
}
}
<file_sep>/app/Modules/Crm/Http/Controllers/NotesController.php
<?php
namespace App\Modules\Crm\Http\Controllers;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Modules\Crm\Http\Customer;
use App\Modules\Crm\Http\CustomerNote;
use App\Model\Config;
use App\Model\Role;
use App\Model\User;
use Auth;
use URL;
use Datatables;
use Session;
class NotesController extends Controller
{
function index()
{
return view('crm::notes.index');
}
function getNote($id)
{
$note = CustomerNote::find($id);
return json_encode($note);
}
function updateNote(Request $request)
{
//dd($request->all());
$this->validate(
$request,
[
'subject' => 'required',
'source' =>'required',
'note' =>'required'
]
);
$note = CustomerNote::find($request->note_id);
$note->subject = $request->subject;
$note->source = $request->source;
$note->note = $request->note;
$note->save();
return json_encode(['success'=>'ok','msg'=>'Record updated successfully.']);
}
function changePinStatus(Request $request)
{
//dd($request->all());
$id = $request->id;
$pin_status = $request->pin_status;
$note = CustomerNote::find($id);
if ($pin_status == 'pin_in') {
$note->pinned = 1;
}
if ($pin_status == 'pin_out') {
$note->pinned = 0;
}
$note->save();
$arr['success'] ='ok';
$arr['msg'] ='Record updated successfully';
return json_encode($arr);
exit;
}
function changeArchiveStatus(Request $request)
{
//dd($request->all());
$id = $request->id;
$archive_status = $request->archive_status;
$note = CustomerNote::find($id);
if ($archive_status == 'archive_in') {
$note->archived = 1;
$note->pinned = 0;
}
if ($archive_status == 'archive_out') {
$note->archived = 0;
}
$note->save();
$arr['success'] ='ok';
$arr['msg'] ='Record updated successfully';
return json_encode($arr);
exit;
}
function delete(Request $request)
{
//dd($request->all());
$id = $request->id;
$note = CustomerNote::find($id);
$note->delete();
$arr['success'] ='ok';
$arr['msg'] ='Record deleted successfully';
return json_encode($arr);
exit;
}
function updateEditable(Request $request)
{
//dd($request->all());
$id = $request->pk;
$name = $request->name;
$value = $request->value;
$note = CustomerNote::find($id);
if ($name=='subject') {
$note->subject = $value;
$note->save();
}
if ($name=='source') {
$note->source = $value;
$note->save();
}
if ($name=='note') {
$note->note = $value;
$note->save();
}
}
function getNotesJson($type)
{
$global_date = $this->global_date;
if ($type=='archived') {
$archived = 1;
}
if ($type=='active') {
$archived = 0;
}
if (!empty(Session::get('cust_id'))) {
$notes = CustomerNote::with(['entered_by','customer'])->where('customer_id', Session::get('cust_id'))->orderBy('pinned', 'desc')->orderBy('updated_at', 'desc')->where('archived', $archived)->where('type', 'simple')->get();
} else {
$notes = CustomerNote::with(['entered_by','customer'])->orderBy('pinned', 'desc')->orderBy('updated_at', 'desc')->where('archived', $archived)->where('type', 'simple')->get();
}
//dd($notes);
$notes_arr =[];
foreach ($notes as $note) {
$btn = ' <a data-target="#modal-edit-note" id="modaal" data-id="'.$note->id.'" data-toggle="modal"><span class="fa fa-edit pin-active"></span></a>';
if ($note->pinned) {
$btn .= ' <a onclick="change_pin_note('.$note->id.',\'pin_out\')"><span class="fa fa-thumb-tack pin-active"></span></a>';
} else {
$btn .= ' <a onclick="change_pin_note('.$note->id.',\'pin_in\')"><span class="fa fa-thumb-tack pin-disabled"></span></a>';
}
if ($note->archived) {
$btn .= ' <a onclick="change_archive_note('.$note->id.',\'archive_out\')"><i class="fa fa-archive pin-active"></i></a>';
} else {
$btn .= ' <a onclick="change_archive_note('.$note->id.',\'archive_in\')"><i class="fa fa-archive pin-disabled"></i></a>';
}
$btn .= ' <a onclick="delete_note('.$note->id.')"><span class="fa fa-close pin-disabled"></span></a>';
$btn .= ' <a data-target="#modal-edit-htable" id="modaal" data-id="'.$note->id.'" data-toggle="modal"><span class="fa fa-eye"></span></a>';
$notes_arr[] = [
'id' => $note->id,
'subject' => '<a data-pk="'.$note->id.'" data-value="'.$note->subject.'" class="subject_editable">'.$note->subject.'</a>',
'source' => '<button type="button" data-type="select2" data-pk="'.$note->id.'" class="btn bg-gray-active btn-sm source" id="source" data-value="'.$note->source.'"><span>'.$note->source.'</span></button>',
'created_by' => $note->entered_by->f_name.' '.$note->entered_by->l_name,
'created_at' => date($global_date, strtotime($note->created_at)),
'detail' => $note->note,
'actions' => ['options'=>['classes'=>'action_td'],
'value'=>$btn]];
}
return json_encode($notes_arr);
}
function getExcelNotesJson($type)
{
$global_date = $this->global_date;
if ($type=='archived') {
$archived = 1;
}
if ($type=='active') {
$archived = 0;
}
if (!empty(Session::get('cust_id'))) {
$notes = CustomerNote::with(['entered_by','customer'])->where('customer_id', Session::get('cust_id'))->orderBy('pinned', 'desc')->orderBy('updated_at', 'desc')->where('archived', $archived)->where('type', 'excel')->get();
} else {
$notes = CustomerNote::with(['entered_by','customer'])->orderBy('pinned', 'desc')->orderBy('updated_at', 'desc')->where('archived', $archived)->where('type', 'excel')->get();
}
//dd($notes);
$notes_arr =[];
foreach ($notes as $note) {
$btn = ' <a data-target="#modal-show-edit-excel-note" id="modaal" data-id="'.$note->id.'" data-toggle="modal"><span class="fa fa-edit pin-active"></span></a>';
if ($note->pinned) {
$btn .= ' <a onclick="change_pin_note('.$note->id.',\'pin_out\')"><span class="fa fa-thumb-tack pin-active"></span></a>';
} else {
$btn .= ' <a onclick="change_pin_note('.$note->id.',\'pin_in\')"><span class="fa fa-thumb-tack pin-disabled"></span></a>';
}
if ($note->archived) {
$btn .= ' <a onclick="change_archive_note('.$note->id.',\'archive_out\')"><i class="fa fa-archive pin-active"></i></a>';
} else {
$btn .= ' <a onclick="change_archive_note('.$note->id.',\'archive_in\')"><i class="fa fa-archive pin-disabled"></i></a>';
}
$btn .= ' <a onclick="delete_note('.$note->id.')"><span class="fa fa-close pin-disabled"></span></a>';
$btn .= ' <a data-target="#modal-show-edit-excel-note" id="modaal" class="view_edit_ht" data-id="'.$note->id.'" data-toggle="modal"><span class="fa fa-eye"></span></a>';
$notes_arr[] = [
'id' => $note->id,
'created_by' => $note->entered_by->f_name.' '.$note->entered_by->l_name,
'created_at' => date($global_date, strtotime($note->created_at)),
'actions' => ['options'=>['classes'=>'action_td'],
'value'=>$btn]];
}
return json_encode($notes_arr);
}
function saveDataExcel(Request $request)
{
//dd($request->all());
$note_obj = new CustomerNote;
$note_obj->customer_id = $request->customer_id;
$note_obj->type = 'excel';
$note_obj->json_data = $request->htdata;
$note_obj->created_by = Auth::user()->id;
if ($note_obj->save()) {
$arr['success'] = 'yes';
return json_encode($arr);
}
exit;
dd(json_encode($request->htdata));
}
function updateDataExcel(Request $request)
{
$id = $request->excel_id;
$note_obj = CustomerNote::find($id);
$note_obj->type = 'excel';
$note_obj->json_data = $request->htdata;
if ($note_obj->save()) {
$arr['success'] = 'yes';
return json_encode($arr);
}
exit;
dd(json_encode($request->htdata));
}
function getExcelData($id)
{
$excel_data = CustomerNote::find($id);
$excel_data_arr['data'] = json_decode($excel_data->json_data);
return(json_encode($excel_data_arr));
}
}
<file_sep>/app/Modules/Crm/Http/Controllers/CrmController.php
<?php
namespace App\Modules\Crm\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Modules\Crm\Http\Customer;
use App\Modules\Crm\Http\Product;
use App\Modules\Crm\Http\CustomerServiceType;
use App\Modules\Crm\Http\DefaultRate;
use App\Modules\Crm\Http\CustomerBillingPeriod;
use App\Modules\Crm\Http\CustomerServiceItem;
use App\Modules\Crm\Http\CustomerServiceRate;
use App\Modules\Crm\Http\CustomerLocation;
use App\Modules\Crm\Http\CustomerNote;
use App\Modules\Crm\Http\Invoice;
use App\Modules\Crm\Http\Country;
use App\Services\GoogleCalendar;
use App\Services\Browser;
use App\Modules\Crm\Http\CustomerLocationContact;
use App\Model\Config;
use App\Model\Role;
use App\Model\User;
use App\Model\UserDevice;
use Auth;
use URL;
use Datatables;
use Cookie;
use Session;
class CrmController extends Controller
{
private $hourly = 'hourly';
private $flate_fee = 'flate fee';
private $project = 'project';
public function index()
{
$route_delete = 'admin.crm.destroy';
return view('crm::crm.index', compact('route_delete'));
}
function setSessionShowCusts(Request $request)
{
if ($request->show_custs) {
Session::put('show_custs', $request->show_custs);
}
return 'ok';
}
public function ajaxDataIndex()
{
$date_format = Config::where('title', 'date_format')->first();
if (!empty(Session::get('show_custs'))) {
if (Session::get('show_custs')=='all') {
$customers = Customer::with(['locations','locations.contacts']);
}
if (Session::get('show_custs')=='active') {
$customers = Customer::with(['locations','locations.contacts'])->where('is_active', 1);
}
if (Session::get('show_custs')=='disabled') {
$customers = Customer::with(['locations','locations.contacts'])->where('is_active', 0);
}
} else {
$customers = Customer::with(['locations','locations.contacts']);
}
return Datatables::of($customers)
->addColumn('contact', function ($customer) {
//$customer->locations //loop
$return = '';
foreach ($customer->locations as $location) {
foreach ($location->contacts as $contact) {
if ($contact->is_poc) {
$return .=' <button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-user"></i>
<span>'.$contact->f_name.' '.$contact->l_name.'</span>
</button>
<button type="button" class="btn bg-gray-active btn-sm">
<i class="fa fa-phone"></i>
<span>'.$contact->phone.'</span>
</button>';
}
}
}
return $return;
})
->editColumn('created_at', function ($customer) use ($date_format) {
return date($date_format->key, strtotime($customer->created_at));
})
->addColumn('locations', function ($customer) {
return '<button type="button" class="btn bg-gray-active btn-sm">
<span>'.count($customer->locations).'</span>
</button>';
})
->addColumn('status', function ($customer) {
if ($customer->is_active) {
return '<button type="button" class="btn bg-green-active btn-sm">
<span>Active</span>
</button>';
} else {
return '<button type="button" class="btn bg-gray-active btn-sm">
<span>Disable</span>
</button>';
}
})
->setRowId('id')
->make(true);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$def_rates_ = DefaultRate::all();
$def_rates = [];
foreach ($def_rates_ as $def_rate) {
$def_rates[$def_rate->title.'|'.$def_rate->amount] =$def_rate->title.' ($'.$def_rate->amount.')';
}
$service_items = CustomerServiceType::all();
$service_types = [];
foreach ($service_items as $service_item) {
$service_types[$service_item->id] =$service_item->title;
}
$countries_ = Country::all();
$countries = [];
foreach ($countries_ as $country) {
$countries[$country->name] =$country->name;
}
$billing_periods = CustomerBillingPeriod::all();
$billing_arr = [];
foreach ($billing_periods as $billing_period) {
$billing_arr[$billing_period->id] =$billing_period->title;
}
$date_format = Config::where('title', 'date_format')->first();
$time_format = Config::where('title', 'time_format')->first();
return view('crm::crm.add', compact('service_types', 'billing_arr', 'countries', 'def_rates', 'date_format', 'time_format'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$service_items = CustomerServiceType::all();
$service_types = [];
foreach ($service_items as $service_item) {
$service_types[$service_item->id] =$service_item->title;
}
//1st step
$customer = new Customer;
$customer->name = $request->customer_name;
$customer->main_phone = $request->phone;
$customer->email_domain = $request->email_domain;
$customer->customer_since = date("Y-m-d", strtotime($request->customer_since));
$customer->is_active = $request->active;
$customer->is_taxable = $request->taxable;
$customer->folder = $this->generateGuid();
$customer->save();
//2nd step
$service_item = new CustomerServiceItem;
$service_item->service_type_id = $request->service_type_id;
$service_item->title = $request->service_item_name;
$service_item->start_date = date("Y-m-d", strtotime($request->start_date));
$service_item->end_date = date("Y-m-d", strtotime($request->end_date));
$service_item->is_active = $request->service_active;
if (isset($request->service_default)) {
$service_item->is_default = $request->service_default;
} else {
$service_item->is_default =0;
}
//if flate fee
if (strtolower($service_types[$request->service_type_id])==$this->hourly || strtolower($service_types[$request->service_type_id])== $this->flate_fee) {
$service_item->billing_period_id = $request->billing_period_id;
}
if (strtolower($service_types[$request->service_type_id])==$this->flate_fee) {
$service_item->unit_price = $request->unit_price;
$service_item->quantity = $request->quantity;
}
if (strtolower($service_types[$request->service_type_id])==$this->project) {
$service_item->estimate = $request->project_estimate;
$service_item->estimated_hours = $request->estimated_hours;
$service_item->bill_for = $request->bill_for;
}
//$service_item->save();
$service_item->comments = $request->description_invoicing;
$customer->service_items()->save($service_item);
if ($request->default_rate) {
$rate = new CustomerServiceRate;
$default_rate_arr = explode('|', $request->default_rate);
$default_rate_title = $default_rate_arr[0];
$default_rate_amount = $default_rate_arr[1];
$rate->title = $default_rate_title;
$rate->amount = $default_rate_amount;
$rate->status = 1;
$service_item->rates()->save($rate);
}
if ($request->additional_rates) {
foreach ($request->additional_rates as $additional_rate) {
$additional_rate_obj = new CustomerServiceRate;
$additional_rates_arr = explode('|', $additional_rate);
/*$additional_rates[] = ['amount'=>$additional_rates_arr[1],
'title'=>$additional_rates_arr[0]];*/
$additional_rate_obj->title = $additional_rates_arr[0];
$additional_rate_obj->amount = $additional_rates_arr[1];
$additional_rate_obj->status = 1;
$service_item->rates()->save($additional_rate_obj);
}
}
$contacts_arr = json_decode($request->cntct_obj);
$locations_arr = json_decode($request->loc_obj);
//dd($locations_arr);
$flag_default = true;
foreach ($locations_arr as $location) {
$location_obj = new CustomerLocation;
$location_obj->location_name = $location->location_name;
$location_obj->address = $location->address;
$location_obj->country = $location->country;
$location_obj->state = $location->state;
$location_obj->city = $location->city;
$location_obj->zip = $location->zip;
$location_obj->phone = $location->loc_main_phone;
$location_obj->back_line_phone = $location->back_line_phone;
$location_obj->primary_fax = $location->primary_fax;
$location_obj->secondary_fax = $location->secondary_fax;
if ($location->default_) {
if ($flag_default) {
$location_obj->default = $location->default_;
$flag_default = false;
} else {
$location_obj->default = 0;
}
} else {
$location_obj->default = 0;
}
$customer->locations()->save($location_obj);
$flag_poc = true;
foreach ($contacts_arr as $contact) {
if ($contact->contact_location_index == $location->loc_id) {
$contact_obj = new CustomerLocationContact;
$contact_obj->f_name = $contact->f_name;
$contact_obj->l_name = $contact->l_name;
$contact_obj->email = $contact->email;
$contact_obj->title = $contact->title_;
$contact_obj->phone = $contact->contact_phone;
$contact_obj->mobile = $contact->contact_mobile;
if ($contact->contact_poc==1) {
if ($flag_poc) {
$contact_obj->is_poc = $contact->contact_poc;
$flag_poc = false;
} else {
$contact_obj->is_poc = 0 ;
}
} else {
$contact_obj->is_poc = $contact->contact_poc;
}
$location_obj->contacts()->save($contact_obj);
}
}
}
return redirect()->intended('admin/crm');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id, Request $request)
{
$customer = Customer::with(['service_items','locations','locations.contacts','service_items.rates',
'service_items.service_type', 'products', 'notes','notes.entered_by','invoices' => function ($query) {
$query->where('status', '!=', 'paid');
}])
->where('id', $id)
->first();
$countries_ = Country::all();
$countries = [];
foreach ($countries_ as $country) {
$countries[$country->name] =$country->name;
}
//Global default rates application wise
$def_rates_ = DefaultRate::all();
$def_rates = [];
foreach ($def_rates_ as $def_rate) {
$def_rates[$def_rate->title.'|'.$def_rate->amount] =$def_rate->title.' ($'.$def_rate->amount.') (global)';
}
// Customer specific rates saved with service items
foreach ($customer->service_items as $service_item) {
foreach ($service_item->rates as $rate) {
if ($rate->is_default==1 && $rate->status==1) {
$def_rates[$rate->title.'|'.$rate->amount] =$rate->title.' ($'.$rate->amount.')';
}
}
}
//rates for additional rates dropdown
$additional_rates = [];
foreach ($customer->service_items as $service_item) {
foreach ($service_item->rates as $rate) {
if ($rate->is_default==0 && $rate->status==1) {
$additional_rates[$rate->title.'|'.$rate->amount] =$rate->title.' ($'.$rate->amount.')';
}
}
}
$customer->invoices->overdue = 0;
$customer->invoices->waiting = 0;
foreach ($customer->invoices as $invoice) {
if ($invoice->status == 'overdue') {
$customer->invoices->overdue += $invoice->balance;
}
if ($invoice->status == 'sent') {
$customer->invoices->waiting += $invoice->balance;
}
}
// unset admin panel session key
Session::forget('panel');
Session::put('cust_id', $id);
Session::put('customer_name', $customer->name);
$products_db = Product::all();
$products = [];
foreach ($products_db as $product) {
$products[$product->id] =$product->name;
}
$assigned_products=[];
foreach ($customer->products as $product) {
$assigned_products[] =$product->id;
}
$device_extention=[];
$device_extention['saved']=0;
$device_extention['extention']='';
$data=UserDevice::where('cookie_id', Cookie::get('nexgen_device'))->first();
if (count($data)>0) {
$device_extention['saved']=1;
$device_extention['extention']=$data->extention;
}
$employee = User::find(Auth::user()->id);
$email_signature = $employee->email_signature;
return view('crm::crm.show', compact(
'customer',
'service_types',
'countries',
'def_rates',
'additional_rates',
'products',
'assigned_products',
'email_signature',
'device_extention'
));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
$id = $request->customer_del_id;
$customer = Customer::with(['service_items','locations','locations.contacts','service_items.rates','service_items.service_type'])->where('id', $id)->first();
foreach ($customer->locations as $location) {
$location->contacts()->delete();
}
$customer->locations()->delete();
foreach ($customer->service_items as $service_item) {
$service_item->rates()->delete();
}
$customer->service_items()->delete();
$customer->delete();
//Session::flash('flash_message', 'User successfully deleted!');
return redirect()->intended('admin/crm');
}
function ajaxAddProductTag(Request $request)
{
$customer = Customer::find($request->customer_id_for_tag);
$customer->products()->sync($request->products);
$return['success'] = 'ok';
// $return['p_tags'] = 'Product added successfully';
return (json_encode($return));
}
function ajaxDataLoad(Request $request)
{
$hourly = $this->hourly;
$flate_fee = $this->flate_fee;
$project = $this->project;
$service_item = CustomerServiceType::find($request->id);
$billing_periods = CustomerBillingPeriod::all();
$billing_arr = [];
foreach ($billing_periods as $billing_period) {
$billing_arr[$billing_period->id] =$billing_period->title;
}
return view('crm::crm.service_item.ajax_service_item', compact('service_item', 'billing_periods', 'billing_arr', 'hourly', 'flate_fee', 'project'))->render();
}
function ajaxLoadLocation(Request $request)
{
$location = CustomerLocation::find($request->id)->toJson();
return $location;
}
function ajaxListLocation($customer_id)
{
$locations = CustomerLocation::where('customer_id', $customer_id)->get();
return view('crm::crm.location.ajax_refresh_locations', compact('locations', 'customer_id'))->render();
exit;
}
function ajaxUpdateLocation(Request $request)
{
$this->validate(
$request,
[
'location_name' => 'required',
]
);
//dd($request->all());
$location_obj = CustomerLocation::find($request->loc_id);
$customer_id = $location_obj->customer_id;
$location_obj->location_name = $request->location_name;
$location_obj->address = $request->address;
$location_obj->country = $request->country;
$location_obj->state = $request->state;
$location_obj->city = $request->city;
$location_obj->zip = $request->zip;
$location_obj->alarm_code = $request->alarm_code;
$location_obj->door_code = $request->door_code;
$location_obj->notes = $request->notes;
$location_obj->phone = $request->loc_main_phone;
$location_obj->back_line_phone = $request->back_line_phone;
$location_obj->primary_fax = $request->primary_fax;
$location_obj->secondary_fax = $request->secondary_fax;
if ($request->default) {
CustomerLocation::where('customer_id', $customer_id)->update(['default'=>0]);
$location_obj->default = $request->default;
}
$location_obj->save();
$arr['success'] = 'Location updated successfully';
return json_encode($arr);
exit;
}
function ajaxLoadContact(Request $request)
{
//echo $request->id;
$data['contact'] = CustomerLocationContact::find($request->cntct_id);
//echo $data['contact'];
$data['locations'] = CustomerLocation::where('customer_id', $request->customer_id)->get();
return json_encode($data);
exit;
}
function ajaxUpdateContact(Request $request)
{
$this->validate(
$request,
[
'f_name' => 'required',
]
);
//dd($request->all());
$contact_obj = CustomerLocationContact::find($request->cntct_id);
$contact_obj->f_name = $request->f_name;
$contact_obj->l_name = $request->l_name;
$contact_obj->customer_location_id = $request->location_index;
$contact_obj->email = $request->email;
$contact_obj->address = $request->address;
$contact_obj->country = $request->country;
$contact_obj->state = $request->state;
$contact_obj->city = $request->city;
$contact_obj->zip = $request->zip;
$contact_obj->title = $request->title;
$contact_obj->phone = $request->contact_phone;
$contact_obj->phone_ext = $request->phone_ext;
$contact_obj->mobile = $request->contact_mobile;
if ($request->primary_poc) {
$cust_loc = CustomerLocation::find($request->location_index);
$cust_locations = CustomerLocation::where('customer_id', $cust_loc->customer_id)->get();
foreach ($cust_locations as $customer_loc) {
CustomerLocationContact::where('customer_location_id', $customer_loc->id)->update(['is_poc'=>0]);
}
$contact_obj->is_poc = 1;
}
$contact_obj->save();
$arr['success'] = 'Contact updated sussessfully';
return json_encode($arr);
exit;
}
function ajaxRefreshContacts($customer_id)
{
$customer = Customer::with(['locations','locations.contacts'])->where('id', $customer_id)->first();
return view('crm::crm.contact.ajax_refresh_location_contacts', compact('customer'))->render();
exit;
}
function ajaxLoadInfo($id)
{
$customer = Customer::find($id);
$data['customer_name'] = $customer->name;
$data['phone'] = $customer->main_phone;
$data['email_domain'] = $customer->email_domain;
$data['customer_since'] = date('m/d/Y', strtotime($customer->customer_since));
$data['credit_limit'] = $customer->credit_limit;
$data['is_taxable'] = $customer->is_taxable;
$data['is_active'] = $customer->is_active;
return json_encode($data);
//return json_encode($data);
exit;
}
function ajaxUpdateInfo(Request $request)
{
$this->validate(
$request,
[
'customer_name' => 'required',
]
);
$customer = Customer::find($request->c_id);
$customer->name = $request->customer_name;
$customer->main_phone = $request->phone;
$customer->email_domain = $request->email_domain;
$customer->customer_since = date("Y-m-d", strtotime($request->customer_since));
$customer->credit_limit = $request->credit_limit;
$customer->is_active = $request->active;
if ($request->taxable) {
$customer->is_taxable = 1;
} else {
$customer->is_taxable = 0;
}
$customer->save();
$arr['success'] = 'Customer info updated successfully';
return json_encode($arr);
exit;
}
function ajaxRefreshInfo($id)
{
$customer = Customer::find($id);
$view = view('crm::crm.info.ajax_refresh_info', compact('customer'));
$data['html_content'] =(string) $view;
$data['h1_title'] = $customer->name;
return json_encode($data);
exit;
}
function ajaxAddLocation(Request $request)
{
$this->validate(
$request,
[
'location_name' => 'required',
]
);
$location_obj = new CustomerLocation;
$location_obj->location_name = $request->location_name;
$location_obj->address = $request->address;
$location_obj->country = $request->country;
$location_obj->state = $request->state;
$location_obj->city = $request->city;
$location_obj->zip = $request->zip;
$location_obj->phone = $request->loc_main_phone;
$location_obj->alarm_code = $request->alarm_code;
$location_obj->door_code = $request->door_code;
$location_obj->notes = $request->notes;
$location_obj->back_line_phone = $request->back_line_phone;
$location_obj->primary_fax = $request->primary_fax;
$location_obj->secondary_fax = $request->secondary_fax;
if ($request->default) {
$location_obj->default = 1;
} else {
$location_obj->default =0;
}
$location_obj->customer_id = $request->customer_id;
$location_obj->save();
$customer_id = $request->new_loc_customer_id;
$arr['success'] = 'Location added successfully';
return json_encode($arr);
exit;
}
function ajaxDeleteLocation(Request $request)
{
$location = CustomerLocation::find($request->id);
$location->delete();
$arr['success'] = 'Location removed.';
return json_encode($arr);
exit;
}
// Old function
function ajaxGetLocationsList($cust_id)
{
$data['locations'] = CustomerLocation::where('customer_id', $cust_id)->get();
return json_encode($data);
exit;
}
function ajaxAddContact(Request $request)
{
// dd($request->all());
$this->validate(
$request,
[
'f_name' => 'required',
]
);
//dd($request->all());
$contact_obj = new CustomerLocationContact;
$contact_obj->f_name = $request->f_name;
$contact_obj->l_name = $request->l_name;
$contact_obj->customer_location_id = $request->location_index;
$contact_obj->email = $request->email;
$contact_obj->title = $request->title;
$contact_obj->phone = $request->contact_phone;
$contact_obj->phone_ext = $request->phone_ext;
$contact_obj->mobile = $request->contact_mobile;
$contact_obj->address = $request->address;
$contact_obj->country = $request->country;
$contact_obj->state = $request->state;
$contact_obj->city = $request->city;
$contact_obj->zip = $request->zip;
if ($request->primary_poc) {
$contact_obj->is_poc = 1;
} else {
$contact_obj->is_poc = 0;
}
$contact_obj->save();
$arr['success'] = 'Contact Added sussessfully';
return json_encode($arr);
exit;
}
function ajaxListServiceItem($customer_id)
{
$service_items = CustomerServiceItem::with(['rates','service_type'])->where('customer_id', $customer_id)->get();
return view('crm::crm.service_item.ajax_refresh_service_items', compact('service_items', 'customer_id'))->render();
exit;
}
function ajaxLoadServiceItem(Request $request)
{
$service_item = CustomerServiceItem::where('id', $request->srvc_item_id)->with(['rates','service_type','billing_period'])->first();
$service_items = CustomerServiceType::all();
$hourly = $this->hourly;
$flate_fee = $this->flate_fee;
$project = $this->project;
$billing_periods = CustomerBillingPeriod::all();
$service_types = [];
foreach ($service_items as $service_item_obj) {
$service_types[$service_item_obj->id] =$service_item_obj->title;
}
$billing_arr = [];
foreach ($billing_periods as $billing_period) {
$billing_arr[$billing_period->id] =$billing_period->title;
}
$view = view('crm::crm.service_item.ajax_load_service_item', compact('service_item', 'service_types', 'hourly', 'flate_fee', 'project', 'billing_arr'))->render();
$arr['view_srvc_itm'] = (string) $view;
return json_encode($arr);
exit;
}
function ajaxUpdateServiceItem(Request $request)
{
//dd($request->all());
$service_items = CustomerServiceType::all();
$service_types = [];
foreach ($service_items as $service_item) {
$service_types[$service_item->id] =$service_item->title;
}
$service_item = CustomerServiceItem::find($request->service_item_id);
$service_item->service_type_id = $request->service_type_id;
$service_item->title = $request->service_item_name;
$service_item->start_date = date("Y-m-d", strtotime($request->start_date));
$service_item->end_date = date("Y-m-d", strtotime($request->end_date));
$service_item->is_active = $request->service_active;
if ($request->service_default) {
$service_item->is_default = 1;
} else {
$service_item->is_default =0;
}
//if flate fee
if (strtolower($service_types[$request->service_type_id])==$this->hourly || strtolower($service_types[$request->service_type_id])== $this->flate_fee) {
$service_item->billing_period_id = $request->billing_period_id;
}
if (strtolower($service_types[$request->service_type_id])==$this->flate_fee) {
$service_item->unit_price = $request->unit_price;
$service_item->quantity = $request->quantity;
}
if (strtolower($service_types[$request->service_type_id])==$this->project) {
$service_item->estimate = $request->project_estimate;
$service_item->estimated_hours = $request->estimated_hours;
$service_item->bill_for = $request->bill_for;
}
//$service_item->save();
//$service_item->comments = $request->description_invoicing;
$customer_id = $service_item->customer_id;
$service_item->save();
CustomerServiceRate::where('customer_service_item_id', $request->service_item_id)->delete();
//$billing_period->delete();
//Session::flash('flash_message', 'User successfully deleted!');
$rate = new CustomerServiceRate;
$default_rate_arr = explode('|', $request->default_rate);
$default_rate_title = $default_rate_arr[0];
$default_rate_amount = $default_rate_arr[1];
$rate->title = $default_rate_title;
$rate->amount = $default_rate_amount;
$rate->is_default = 1;
$rate->status = 1;
$service_item->rates()->save($rate);
if ($request->additional_rates) {
foreach ($request->additional_rates as $additional_rate) {
$additional_rate_obj = new CustomerServiceRate;
$additional_rates_arr = explode('|', $additional_rate);
/*$additional_rates[] = ['amount'=>$additional_rates_arr[1],
'title'=>$additional_rates_arr[0]];*/
$additional_rate_obj->title = $additional_rates_arr[0];
$additional_rate_obj->amount = $additional_rates_arr[1];
$additional_rate_obj->status =1;
$service_item->rates()->save($additional_rate_obj);
}
}
$arr['success'] = 'Service Type Updated sussessfully';
return json_encode($arr);
exit;
}
function ajaxListRate($customer_id)
{
$service_items = CustomerServiceItem::with(['rates','service_type'])->where('customer_id', $customer_id)->get();
return view('crm::crm.rate.ajax_refresh_service_item_rates', compact('service_items'))->render();
exit;
}
function ajaxLoadRate($id)
{
$rate = CustomerServiceRate::find($id);
return json_encode($rate);
exit;
}
function ajaxUpdateRate(Request $request)
{
$rate = CustomerServiceRate::find($request->rate_id);
$rate->title = $request->title;
$rate->amount = $request->amount;
if ($request->default) {
$rate->is_default = 1;
} else {
$rate->is_default=0;
}
if ($request->status) {
$rate->status = 1;
} else {
$rate->status = 0;
}
$rate->save();
$service_item_id = $request->servc_item_id_rate;
$service_item = CustomerServiceItem::find($service_item_id);
$customer_id = $service_item->customer_id;
$service_items = CustomerServiceItem::with(['rates','service_type'])->where('customer_id', $customer_id)->get();
$arr['html_content_rates'] = view('crm::crm.rate.ajax_refresh_service_item_rates', compact('service_items'))->render();
$arr['success'] = 'Service Type rate Updated sussessfully';
return json_encode($arr);
exit;
}
function ajaxAddRate(Request $request)
{
//dd($request->all());
$service_item_id = $request->servc_item_id_new_rate;
//dd($service_item_id );
$rate = new CustomerServiceRate;
$rate->title = $request->title;
$rate->amount = $request->amount;
$rate->customer_service_item_id = $service_item_id;
if ($request->default) {
//dd('lll');
$rate->is_default = 1;
/*$change_rate = CustomerServiceRate::where('customer_service_item_id',$service_item_id)->first();
$change_rate->is_default = 0;
$change_rate->save();*/
} else {
$rate->is_default=0;
}
if ($request->status) {
$rate->status = 1;
} else {
$rate->status = 0;
}
$rate->save();
$service_item = CustomerServiceItem::find($service_item_id);
$customer_id = $service_item->customer_id;
$service_items = CustomerServiceItem::with(['rates','service_type'])->where('customer_id', $customer_id)->get();
//$rates = CustomerServiceRate::where('customer_service_item_id',$service_item_id)->get();
$arr['success'] = 'Service Type rate Added sussessfully';
$arr['html_content_rates'] = view('crm::crm.rate.ajax_refresh_service_item_rates', compact('service_items'))->render();
return json_encode($arr);
exit;
}
function ajaxLoadNewServiceItem($cust_id)
{
$hourly = $this->hourly;
$flate_fee = $this->flate_fee;
$project = $this->project;
$service_types_arr = CustomerServiceType::all();
$service_types = [];
foreach ($service_types_arr as $service_type_obj) {
$service_types[$service_type_obj->id] =$service_type_obj->title;
}
$arr['service_types'] = $service_types;
return json_encode($arr);
exit;
//dd($cust_id);
}
function ajaxAddServiceItem(Request $request)
{
$this->validate(
$request,
[
'service_type_id' => 'required',
'default_rate' =>'required'
]
);
$service_types_data = CustomerServiceType::all();
$service_types = [];
foreach ($service_types_data as $service_item) {
$service_types[$service_item->id] =$service_item->title;
}
$service_item = new CustomerServiceItem;
$service_item->service_type_id = $request->service_type_id;
$service_item->title = $request->service_item_name;
$service_item->start_date = date("Y-m-d", strtotime($request->start_date));
$service_item->end_date = date("Y-m-d", strtotime($request->end_date));
$service_item->customer_id = $request->customer_id_new_service_item;
$service_item->is_active = $request->service_active;
if (isset($request->service_default)) {
$service_item->is_default = $request->service_default;
} else {
$service_item->is_default =0;
}
//if flate fee
if (strtolower($service_types[$request->service_type_id]) ==$this->hourly || strtolower($service_types[$request->service_type_id])== $this->flate_fee) {
$service_item->billing_period_id = $request->billing_period_id;
}
if (strtolower($service_types[$request->service_type_id]) ==$this->flate_fee) {
$service_item->unit_price = $request->unit_price;
$service_item->quantity = $request->quantity;
}
if (strtolower($service_types[$request->service_type_id]) ==$this->project) {
$service_item->estimate = $request->project_estimate;
$service_item->estimated_hours = $request->estimated_hours;
$service_item->bill_for = $request->bill_for;
}
$service_item->save();
$rate = new CustomerServiceRate;
$default_rate_arr = explode('|', $request->default_rate);
$default_rate_title = $default_rate_arr[0];
$default_rate_amount = $default_rate_arr[1];
$rate->title = $default_rate_title;
$rate->amount = $default_rate_amount;
$rate->is_default = 1;
$rate->status = 1;
$service_item->rates()->save($rate);
if ($request->additional_rates) {
foreach ($request->additional_rates as $additional_rate) {
$additional_rate_obj = new CustomerServiceRate;
$additional_rates_arr = explode('|', $additional_rate);
$additional_rate_obj->title = $additional_rates_arr[0];
$additional_rate_obj->amount = $additional_rates_arr[1];
$additional_rate_obj->status =1;
$service_item->rates()->save($additional_rate_obj);
}
}
$customer_id = $request->customer_id_new_service_item;
$service_items = CustomerServiceItem::with(['rates','service_type'])->where('customer_id', $request->customer_id_new_service_item)->get();
$arr['html_content_rates'] = view('crm::crm.rate.ajax_refresh_service_item_rates', compact('service_items'))->render();
$arr['html_contents'] = view('crm::crm.service_item.ajax_refresh_service_items', compact('service_items', 'customer_id'))->render();
$arr['success'] = 'Service Item added sussessfully';
return json_encode($arr);
exit;
}
function ajaxDeleteContact(Request $request)
{
$contact = CustomerLocationContact::find($request->id);
$contact->delete();
$arr['success'] = 'Contact deleted sussessfully';
return json_encode($arr);
exit;
}
function ajaxDeleteRate($rate_id, $service_item_id)
{
//dd($service_item_id );
$rate = CustomerServiceRate::find($rate_id);
$rate->delete();
$service_item = CustomerServiceItem::find($service_item_id);
$customer_id = $service_item->customer_id;
$service_items = CustomerServiceItem::with(['rates','service_type'])->where('customer_id', $customer_id)->get();
$arr['success'] = 'Service Type rate Deleted sussessfully';
$arr['html_content_rates'] = view('crm::crm.rate.ajax_refresh_service_item_rates', compact('service_items'))->render();
return json_encode($arr);
exit;
}
// Click to call functionality
function ajaxClicktoCall($number, $exten, $customer_id, $save)
{
$browser = new Browser();
if ($save == 'true') {
$saved_devices = UserDevice::where('user_id', Auth::user()->id)->count();
$update=1;
if (Cookie::get('nexgen_device')) {
$count=UserDevice::where('cookie_id', Cookie::get('nexgen_device'))->count();
if ($count==0) {
Cookie::forget('nexgen_device');
} else {
$update = 0;
}
}
//check if devices are less then 5 for a specific user
if ($saved_devices < 5 && $update == 1) {
$cookie_id = MD5($browser->getUserAgent().time());
Cookie::queue("nexgen_device", $cookie_id, 2147483647);
$device = new UserDevice;
$device->user_id = Auth::user()->id;
$device->extention = $exten;
$device->brower_name = $browser->getBrowser();
$device->operating_system = $browser->getPlatform();
$device->cookie_id = $cookie_id;
$device->save();
}
}
$customer=Customer::find($customer_id);
$number = preg_replace('/[^\d]/', '', $number);
$url = 'https://ng.ngvoip.us/app/click_to_call/click_to_call.php?username=netpro25&password=<PASSWORD>&src_cid_name='.urlencode($customer->name).'&src_cid_number='.$number.'&dest_cid_name=NexgenTec&dest_cid_number=3522243866&auto_answer=true&rec=false&ringback=us-ring&src='.$exten .'&dest='.$number;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_exec($ch);
}
function ajaxDeleteServiceItem($s_id, $customer_id)
{
//dd($service_item_id );
CustomerServiceItem::where('id', $s_id)->delete();
CustomerServiceRate::where('customer_service_item_id', $s_id)->delete();
$service_items = CustomerServiceItem::with(['rates','service_type'])->where('customer_id', $customer_id)->get();
$arr['html_contents'] = view('crm::crm.service_item.ajax_refresh_service_items', compact('service_items', 'customer_id'))->render();
$arr['success'] = 'Service Item deleted sussessfully';
return json_encode($arr);
exit;
}
function ajaxGetServiceItems($c_id)
{
$customer = Customer::with(['service_items','locations','service_items.rates','service_items.service_type'])->where('id', $c_id)->first();
$arr['locations'] = $customer->locations;
$arr['service_items'] = $customer->service_items;
return json_encode($arr);
exit;
}
/**
* Return calendar events
*/
function ajaxCalGetEvents(Request $request)
{
$calendar = new GoogleCalendar;
$events_result = $calendar->eventList($request->start, $request->end);
$events_arr = [];
foreach ($events_result->getItems() as $event) {
if ($event->start->getDatetime()!=null) {
$events_arr[] = ['title'=>$event->getSummary(),
'start'=>$event->start->getDatetime(),
'end'=>$event->end->getDatetime()];
} else {
$events_arr[] = ['title'=>$event->getSummary(),
'start'=>$event->start->getDate(),
'end'=>$event->end->getDate()];
}
}
return json_encode($events_arr);
exit;
}
// Angular
function angularList($id = null)
{
if ($id == null) {
return Customer::with(['contacts'])->orderBy('id', 'asc')->get();
} else {
dd($this->show($id));
}
}
function searchCustomers(Request $request)
{
//dd($request->all());
if ($request->cust) {
$customers_result = Customer::with(['locations','locations.contacts'])->where('name', 'like', '%'.$request->cust.'%')->get();
$customers = [];
foreach ($customers_result as $customer) {
$customers[] = ['id'=>$customer->id,'cust_name'=>$customer->name];
}
echo json_encode([
"status" => true,
"error" => null,
"data" => [
"customers" => $customers
]
]);
} else {
echo json_encode([
"status" => true,
"error" => null,
"data" => [
"customers" => []
]
]);
}
}
function searchLocations(Request $request)
{
//dd($request->all());
if ($request->loc) {
$locations_result = CustomerLocation::with('customer')->where('location_name', 'like', '%'.$request->loc.'%')->get();
$locations = [];
foreach ($locations_result as $location) {
//dd($location->customer);
$locations[] = ['id'=>$location->customer->id,
'loc_name'=>$location->location_name.' ('.$location->customer->name.')'];
}
echo json_encode([
"status" => true,
"error" => null,
"data" => [
"locations" => $locations
]
]);
} else {
echo json_encode([
"status" => true,
"error" => null,
"data" => [
"locations" => []
]
]);
}
}
function searchLocationContacts(Request $request)
{
//dd($request->all());
if ($request->c_contact) {
$locations_result = CustomerLocation::with(['customer','contacts'=>function ($query) use ($request) {
$query->where('f_name', 'like', '%'.$request->c_contact.'%')->orWhere('l_name', 'like', '%'.$request->c_contact.'%');
}])->get();
$contacts = [];
foreach ($locations_result as $location) {
foreach ($location->contacts as $loc_contact) {
$contacts[] = ['id'=>$location->customer->id,
'cust_contact'=>$loc_contact->f_name.' '.$loc_contact->l_name.' ('.$location->customer->name.')'];
}
//dd($location->customer);
}
echo json_encode([
"status" => true,
"error" => null,
"data" => [
"cust_contacts" => $contacts
]
]);
} else {
echo json_encode([
"status" => true,
"error" => null,
"data" => [
"cust_contacts" => []
]
]);
}
}
function listAjaxActiveCustomers()
{
$customers = Customer::where('is_active', 1)->get();
return json_encode(['customers'=>$customers]);
}
private function generateGuid()
{
$s = strtoupper(md5(uniqid(rand(), true)));
$guidText =
substr($s, 0, 8) . '-' .
substr($s, 8, 4) . '-' .
substr($s, 12, 4). '-' .
substr($s, 16, 4). '-' .
substr($s, 20);
return $guidText;
}
}
<file_sep>/app/Modules/Crm/Http/Invoice.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
protected $guarded = ['id'];
public function customer()
{
return $this->belongsTo('App\Modules\Crm\Http\Customer', 'customer_id');
}
}
<file_sep>/public/phpmyadmin/js/codemirror/lib/codemirror.js
../../../../javascript/codemirror/codemirror.js<file_sep>/app/Modules/Crm/Database/2015_12_31_140505_locations.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Locations extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('customer_locations', function (Blueprint $table) {
$table->increments('id');
$table->integer('customer_id');
$table->date('created_at');
$table->date('updated_at');
$table->string('location_name', 150);
$table->string('address', 400);
$table->string('country', 30);
$table->string('city', 30);
$table->string('state', 30);
$table->integer('zip');
$table->string('phone', 15);
$table->tinyInteger('default');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('customer_locations');
}
}
<file_sep>/app/Modules/Employee/Http/routes.php
<?php
/*
|--------------------------------------------------------------------------
| Module Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for the module.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::group(['middleware' => 'web'], function () {
Route::group(['prefix' => 'admin','middleware' => 'admin'], function () {
Route::group(['prefix' => 'employee','middleware' => ['role:admin|manager|technician']], function () {
Route::get('/', ['as'=>'admin.employee.index','middleware' => ['permission:list_employee'], 'uses' => 'EmployeeController@index']);
Route::get('create', ['as'=>'admin.employee.create','middleware' => ['permission:add_employee'], 'uses' => 'EmployeeController@create']);
Route::post('/', ['as'=>'admin.employee.store','middleware' => ['permission:add_employee'], 'uses' => 'EmployeeController@store']);
Route::post('/ajax_update', ['as'=>'admin.employee.ajax_store','middleware' => [], 'uses' => 'EmployeeController@ajaxStore']);
Route::get('/get_user/{id}', ['as'=>'admin.employee.get_ajax_user','middleware' => ['permission:list_employee'], 'uses' => 'EmployeeController@getById']);
Route::get('edit/{id}', ['as'=>'admin.employee.edit','middleware' => ['permission:edit_employee'], 'uses' => 'EmployeeController@edit']);
Route::delete('delete', ['as'=>'admin.employee.destroy','middleware' => ['permission:delete_employee'], 'uses' => 'EmployeeController@destroy']);
Route::put('/{id}', ['as'=>'admin.employee.update','middleware' => ['permission:edit_employee'], 'uses' => 'EmployeeController@update']);
Route::get('show/{id}', ['as'=>'admin.employee.show','middleware' => ['permission:edit_employee'], 'uses' => 'EmployeeController@show']);
/*********************************************** Leaves*****************************/
Route::group(['prefix' => 'leave'], function () {
Route::get('/create', ['as'=>'employee.leave.create','middleware' => ['permission:post_leave'], 'uses' => 'LeaveController@create']);
Route::delete('/delete', ['as'=>'employee.leave.destroy','middleware' => ['permission:delete_leave'], 'uses' => 'LeaveController@destroy']);
Route::get('/pending_leaves', ['as'=>'admin.leave.pending','middleware' => ['permission:list_leaves'], 'uses' => 'LeaveController@listPendingLeaves']);
Route::get('/rejected_leaves', ['as'=>'admin.leave.rejected','middleware' => ['permission:list_leaves'], 'uses' => 'LeaveController@listRejectedLeaves']);
Route::get('/calendar', ['as'=>'admin.leave.calendar','middleware' => ['permission:list_leaves'], 'uses' => 'LeaveController@showCalendar']);
Route::post('/post_leave_for_employee', ['as'=>'admin.leave.post_leave_for_employee','middleware' => ['permission:post_leave_for_employee'], 'uses' => 'LeaveController@postLeaveForEmployee']);
Route::get('/{id}', ['as'=>'employee.leave.own.index','middleware' => ['permission:list_own_leaves'], 'uses' => 'LeaveController@index']);
Route::get('/', ['as'=>'employee.leave.index','middleware' => ['permission:list_leaves'], 'uses' => 'LeaveController@index']);
Route::post('/', ['as'=>'employee.leave.store','middleware' => ['permission:post_leave'], 'uses' => 'LeaveController@store']);
});
/*********************************************** Leaves*****************************/
Route::group(['prefix' => 'leave'], function () {
//dd('fff');
Route::post('/postToCalendar', ['as'=>'admin.leave.posttocalendar','middleware' => ['permission:approve_leave'], 'uses' => 'LeaveController@postCalander']);
Route::post('/rejectLeave', ['as'=>'admin.leave.reject_leave','middleware' => ['permission:reject_leave'], 'uses' => 'LeaveController@rejectLeave']);
});
});
Route::group(['prefix' => 'leave'], function () {
Route::get('/list_leaves/{id}', ['as'=>'admin.leave.list_leaves','middleware' => ['permission:list_leaves'], 'uses' => 'LeaveController@dashboardListLeaves']);
Route::get('/list_all_leaves', ['as'=>'admin.leave.list_all_leaves','middleware' => ['permission:list_leaves'], 'uses' => 'LeaveController@allListLeaves']);
Route::get('/list_own_leaves/{id}', ['as'=>'admin.leave.list_own_leaves','middleware' => ['permission:list_own_leaves'], 'uses' => 'LeaveController@allListLeaves']);
});
Route::resource('/raise', 'RaiseController');
Route::get('calander', 'EmployeeController@googleCalander');
});
});<file_sep>/public/phpmyadmin/js/jquery/jquery.tablesorter.js
../../../javascript/jquery-tablesorter/jquery.tablesorter.min.js<file_sep>/nexpbx.cron.php
<?php
/****connection settings for mysql db****/
// Connect to NexPBX Mysql
$servername_mysql = "localhost";
$username_mysql = "nexpbx";
$database_mysql = "ncm";
$password_mysql = "<PASSWORD>";
/****connection settings for pg db****/
// Connect to NexPBX pg
$servername_pg = "jax1.ngvoip.us";
$database_pg = "fusionpbx";
$username_pg = "ngcrm";
$password_pg = "<PASSWORD>";
//ini_set('display_errors', 'On');
//ini_set('display_startup_errors', 1);
//error_reporting(1);
/*
*creates an array containing differnece in both devices arrays
*/
function devices_difference($array1, $array2)
{
$devices_mysql_uuid=array_column($array2, 'device_uuid');
foreach($array1 as $key => $value)
{
if(in_array($value['device_uuid'], $devices_mysql_uuid )){
foreach ($array2 as $key2 => $value2) {
if($value['device_uuid']==$value2['device_uuid'] ){
$diff=array_diff($value, $value2);
if(!empty($diff)){
$diff['device_uuid']=$value2['device_uuid'];
$diff['new']=0;
$difference[$value['device_uuid']] = $diff;
}
}
}
}else{
$value['new']=1;
$difference[$value['device_uuid']]=$value;
}
}
return !isset($difference) ? 0 : $difference;
}
/*
*creates an array containing differnece in both domains arrays
*/
function domains_difference($array1, $array2)
{
$domain_mysql_uuid=array_column($array2, 'domain_uuid');
foreach($array1 as $key => $value)
{
if(in_array($value['domain_uuid'], $domain_mysql_uuid )){
foreach ($array2 as $key2 => $value2) {
if($value['domain_uuid']==$value2['domain_uuid'] ){
$diff=array_diff($value, $value2);
if(!empty($diff)){
$diff['domain_uuid']=$value2['domain_uuid'];
$diff['new']=0;
$difference[$value['domain_uuid']] = $diff;
}
}
}
}else{
$value['new']=1;
$difference[$value['domain_uuid']]=$value;
}
}
return !isset($difference) ? 0 : $difference;
}
// Connect to NexPBX Postgres
$conn_postgres = pg_connect("host=".$servername_pg." dbname=".$database_pg." user=".$username_pg." password=".$<PASSWORD>)
or die('Could not connect: ' . pg_last_error());
// Create connection
$conn = new mysqli($servername_mysql, $username_mysql, $password_mysql,$database_mysql);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch mysql Domains
$sql = "SELECT domain_uuid,domain_parent_uuid, domain_name,domain_enabled,domain_description FROM nexpbx_domains";
$result = $conn->query($sql);
$domains_mysql=mysqli_fetch_all($result,MYSQLI_ASSOC);
//single arrays of domain_uuid from mysql
$domain_uuid_mysql=array_column($domains_mysql, 'domain_uuid');
// Fetch Pg Domains
$domain_query = pg_query($conn_postgres, "SELECT v_domains.domain_uuid, v_domains.domain_parent_uuid, v_domains.domain_name, v_domains.domain_enabled,
v_domains.domain_description FROM v_domains");
if (!$domain_query) {
echo "An error occurred.\n";
exit;
}
$domains_pg = pg_fetch_all($domain_query);
$sql = array();
/****Synscronize domains starts*****/
$difference=domains_difference($domains_pg, $domains_mysql);
$insert_query=0;
$update_query=0;
if(!empty($difference)){
foreach ($difference as $row_diff) {
if($row_diff['new']==1){
$sql[] = '("'.$row_diff['domain_uuid'].'", "'.$row_diff['domain_parent_uuid'].'","'.$row_diff['domain_name'].'", "'.$row_diff['domain_enabled'].'", "'.$row_diff['domain_description'].'","'.date("Y-m-d H:i:s").'","'.date("Y-m-d H:i:s").'")';
$insert_query=1;
}elseif($row_diff['new']==0){
$update_sql='';
$update=0;
if(isset($row_diff['domain_parent_uuid'])){
$update_sql .= 'domain_parent_uuid="'.$row_diff['domain_parent_uuid'].'" ,';
$update=1;
}
if(isset($row_diff['domain_name'])){
$update_sql .= 'domain_name="'.$row_diff['domain_name'].'" ,';
$update=1;
}
if(isset($row_diff['domain_enabled'])){
$update_sql .= 'domain_enabled="'.$row_diff['domain_enabled'].'" ,';
$update=1;
}
if(isset($row_diff['domain_description'])){
$update_sql .= 'domain_description="'.$row_diff['domain_description'].'" ,';
$update=1;
}
$update_sql='Update nexpbx_domains SET '.$update_sql.' updated_at="'.date("Y-m-d H:i:s").'" WHERE domain_uuid="'.$row_diff['domain_uuid'].'"';
mysqli_query($conn,$update_sql);
$update_query=1;
}
}
if($insert_query==1){
$insert_sql = "INSERT INTO nexpbx_domains (domain_uuid,domain_parent_uuid,domain_name,domain_enabled,domain_description,created_at,updated_at) VALUES ".implode(',', $sql);
if(mysqli_query($conn,$insert_sql)){
echo "Domain records inserted \n";
}else{
echo "Domain not inserted \n";
}
}
if($update_query==1){
echo "Domain records updated successfully \n";
}
}else{
echo "Domains Already Upto Date \n";
}
/****Synscronize domains ends*****/
/****Synscronize devices starts*****/
// Devices
$device_query = pg_query($conn_postgres, "SELECT v_devices.device_uuid, v_devices.domain_uuid, v_devices.device_mac_address, v_devices.device_label,
v_devices.device_vendor, v_devices.device_model, v_devices.device_enabled, v_devices.device_template, v_devices.device_description,
v_devices.device_provisioned_date, v_devices.device_provisioned_ip FROM v_devices");
if (!$device_query) {
echo "An error occurred.\n";
exit;
}
$devices_pg = pg_fetch_all($device_query);
pg_free_result($device_query);
// Select all devices from mysql db table
$sql = "SELECT device_uuid,domain_uuid, device_mac_address,device_label,device_vendor,device_model,device_enabled,device_template,device_description,device_provisioned_date,device_provisioned_ip,device_type FROM nexpbx_devices";
$result = $conn->query($sql);
$devices_mysql=mysqli_fetch_all($result,MYSQLI_ASSOC);
$difference=devices_difference($devices_pg, $devices_mysql);
$deleted=devices_difference($devices_mysql, $devices_pg);
$sql_deveices=array();
$insert_query_device=0;
$update_query_device=0;
if(!empty($deleted)){
foreach ($deleted as $key => $value) {
if($value['new']=1){
$delete_sql='DELETE FROM nexpbx_devices WHERE device_uuid="'.$value['device_uuid'].'"';
if(mysqli_query($conn,$delete_sql)){
echo "Devices deleted successfully \n";
}else{
echo "Devices not deleted (Error) \n";
}
}
}
}
if(!empty($difference)){
foreach ($difference as $row_diff) {
if($row_diff['new']==1){
$sql_deveices[] = '("'.$row_diff['device_uuid'].'", "'.$row_diff['domain_uuid'].'","'.$row_diff['device_mac_address'].'", "'.$row_diff['device_label'].'", "'.$row_diff['device_vendor'].'", "'.$row_diff['device_model'].'", "'.$row_diff['device_enabled'].'", "'.$row_diff['device_template'].'", "'.$row_diff['device_description'].'", "'.$row_diff['device_provisioned_date'].'", "'.$row_diff['device_provisioned_ip'].'","'.date("Y-m-d H:i:s").'","'.date("Y-m-d H:i:s").'")';
$insert_query_device=1;
}elseif($row_diff['new']==0){
$update_sql='';
$update=0;
if(isset($row_diff['domain_uuid'])){
$update_sql .= 'domain_uuid="'.$row_diff['domain_uuid'].'" ,';
$update_sql .= 'Location_id= 0 ,';
$update=1;
}
if(isset($row_diff['device_mac_address'])){
$update_sql .= 'device_mac_address="'.$row_diff['device_mac_address'].'" ,';
$update=1;
}
if(isset($row_diff['device_label'])){
$update_sql .= 'device_label="'.$row_diff['device_label'].'" ,';
$update=1;
}
if(isset($row_diff['device_vendor'])){
$update_sql .= 'device_vendor="'.$row_diff['device_vendor'].'" ,';
$update=1;
}
if(isset($row_diff['device_model'])){
$update_sql .= 'device_model="'.$row_diff['device_model'].'" ,';
$update=1;
}
if(isset($row_diff['device_template'])){
$update_sql .= 'device_template="'.$row_diff['device_template'].'" ,';
$update=1;
}
if(isset($row_diff['device_description'])){
$update_sql .= 'device_description="'.$row_diff['device_description'].'" ,';
$update=1;
}
if(isset($row_diff['device_provisioned_date'])){
$update_sql .= 'device_provisioned_date="'.$row_diff['device_provisioned_date'].'" ,';
$update=1;
}
if(isset($row_diff['device_provisioned_ip'])){
$update_sql .= 'device_provisioned_ip="'.$row_diff['device_provisioned_ip'].'" ,';
$update=1;
}
if(isset($row_diff['device_enabled'])){
$update_sql .= 'device_enabled="'.$row_diff['device_enabled'].'" ,';
$update=1;
}
if($update==1){
$update_sql='Update nexpbx_devices SET '.$update_sql.' updated_at="'.date("Y-m-d H:i:s").'" WHERE device_uuid="'.$row_diff['device_uuid'].'"';
mysqli_query($conn,$update_sql);
$update_query_device=1;
}
}
}
if($insert_query_device==1){
$insert_sql = "INSERT INTO nexpbx_devices (device_uuid,domain_uuid, device_mac_address,device_label,device_vendor,device_model,device_enabled,device_template,device_description,device_provisioned_date,device_provisioned_ip,created_at,updated_at) VALUES ".implode(',', $sql_deveices);
if(mysqli_query($conn,$insert_sql)){
echo "Devices records inserted \n";
}else{
echo "Devices not inserted (Error) \n" . mysqli_error($conn);
}
}
if($update_query_device==1){
echo "Devices records updated successfully \n";
}
}else{
echo "Devices already upto date \n";
}
/****Synscronize devices ends*****/
// Closing connection
pg_close($conn_postgres);
?>
<file_sep>/app/Http/Controllers/ImageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Storage;
use File;
use URL;
use Image;
class ImageController extends Controller
{
function imageUpload(Request $request)
{
$allowed = ['png', 'jpg', 'gif'];
$rules = [
'file' => 'required|image|mimes:jpeg,jpg,png,gif'
];
if (!empty($request->image_dir)) {
if ($request->hasFile('image')) {
$image_dir = $request->image_dir;
$file = $request->file('image');
if (!in_array($file->guessExtension(), $allowed)) {
return '{"error":"Invalid File type"}';
} else {
$guid = $this->generateGuid();
$fileName = $guid .'.'. $file->guessExtension();
$path = storage_path('image_upload/'.$image_dir);
// Make image folder if it does not exist
if (Storage::MakeDirectory($path, 0775, true)) {
if ($file->move($path, $fileName)) {
$url = url(URL::route('get.image', ['folder' => $image_dir,'filename' => $fileName]));
return json_encode([
'url' => $url,
'dir' => $image_dir,
'id' => $fileName
]);
exit;
}
} else {
return '{"error":"There was an error saving the file"}';
}
}
} else {
return '{"error":"Invalid File type"}';
}
} else {
return '{"error":"Unable to upload file"}';
}
}
private function generateGuid()
{
$s = strtoupper(md5(uniqid(rand(), true)));
$guidText =
substr($s, 0, 8) . '-' .
substr($s, 8, 4) . '-' .
substr($s, 12, 4). '-' .
substr($s, 16, 4). '-' .
substr($s, 20);
return $guidText;
}
public function retrieveImage($folder, $filename)
{
$path = storage_path('image_upload/'.$folder.'/'.$filename);
return Image::make($path)->response();
}
}
<file_sep>/app/Services/GoogleCalendar.php
<?php namespace App\Services;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
class GoogleCalendar
{
protected $client;
protected $service;
protected $event;
protected $calendarId;
function __construct()
{
/* Get config variables */
$client_id = Config::get('google.client_id');
$this->calendarId = Config::get('google.calendar_id');
$service_account_name = Config::get('google.service_account_name');
$key_file_location = base_path() . Config::get('google.key_file_location');
$this->client = new \Google_Client();
$this->client->setApplicationName("google-calander");
$this->service = new \Google_Service_Calendar($this->client);
/* If we have an access token */
if (Cache::has('service_token')) {
$this->client->setAccessToken(Cache::get('service_token'));
}
$key = file_get_contents($key_file_location);
/* Add the scopes you need */
$scopes = ['https://www.googleapis.com/auth/calendar'];
$cred = new \Google_Auth_AssertionCredentials(
$service_account_name,
$scopes,
$key
);
$this->client->setAssertionCredentials($cred);
if ($this->client->getAuth()->isAccessTokenExpired()) {
$this->client->getAuth()->refreshTokenWithAssertion($cred);
}
Cache::forever('service_token', $this->client->getAccessToken());
}
public function get()
{
$results = $this->service->calendars->get($this->calendarId);
return($results);
}
function eventPost($data)
{
$event = new \Google_Service_Calendar_Event($data);
$event = $this->service->events->insert($this->calendarId, $event);
//printf('Event created: %s\n', $event->htmlLink);
if ($event) {
return $event;
}
}
function eventList($startDate = null, $endDate = null)
{
$params = [];
if (isset($startDate)) {
$params['timeMin'] = $startDate . 'T00:00:00-05:00';
}
if (isset($endDate)) {
$params['timeMax'] = $endDate . 'T23:59:59-05:00';
}
$events = $this->service->events->listEvents($this->calendarId, $params);
return $events;
}
function event($id)
{
$event = $this->service->events->get($this->calendarId, $id);
return $event;
}
function eventDelete($event_id)
{
$this->service->events->delete($this->calendarId, $event_id);
//$events = $this->service->events->listEvents($this->calendarId);
return true;
}
function eventUpdate($eventId, $data)
{
$event = $this->service->events->get($this->calendarId, $eventId);
$event->setSummary($data['summary']);
$event->setLocation($data['location']);
$event->setDescription($data['description']);
$event->start->setDatetime($data['start']['dateTime']);
$event->start->setTimezone($data['start']['timeZone']);
$event->end->setDatetime($data['end']['dateTime']);
$event->end->setTimezone($data['end']['timeZone']);
//$event->setAttendees($data['attendees']);
$updatedEvent = $this->service->events->update($this->calendarId, $event->getId(), $event);
// Print the updated date.
//return $updatedEvent->getUpdated();
return $updatedEvent;
//return true;
}
}
<file_sep>/app/Modules/Nexpbx/Database/Seeds/NexpbxDatabaseSeeder.php
<?php
namespace App\Modules\Nexpbx\Database\Seeds;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class NexpbxDatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Model::unguard();
// $this->call('App\ModulesNexpbx\Database\Seeds\FoobarTableSeeder');
}
}
<file_sep>/public/phpmyadmin/js/jquery/jquery.mousewheel.js
../../../javascript/jquery-mousewheel/jquery.mousewheel.min.js<file_sep>/app/Http/Controllers/SettingController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Services\GoogleGmail;
use App\Model\Config;
use App\Modules\Employee\Http\Employee;
use App\Model\User;
use App\Model\UserDevice;
use App\Services\TimeZone;
// Used By crmBilling function
use App\Modules\Crm\Http\DefaultRate;
use App\Modules\Crm\Http\CustomerBillingPeriod;
use App\Modules\Crm\Http\CustomerServiceType;
use App\Modules\Assets\Http\AssetRole;
use App\Modules\Assets\Http\AssetVirtualType;
use Datatables;
use Auth;
use Cookie;
class SettingController extends Controller
{
/*
Billing CRM Settings
*/
public function defaultRates(Request $request)
{
//$request->session()->put('panel', 'admin');
$defaultRates = DefaultRate::all();
return view('crm::settings.defaultrates.index', compact('defaultRates'))->render();
}
public function createDefaultRate(Request $request)
{
//$request->session()->put('panel', 'admin');
$this->validate($request, [
'title' => 'required',
'amount' => 'required',
]);
$rate = new DefaultRate;
$rate->title = $request->title;
$rate->amount = $request->amount;
$rate->save();
$arr['success'] = 'Rate created successfully';
return json_encode($arr);
exit;
}
public function deleteDefaultRate(Request $request)
{
//$request->session()->put('panel', 'admin');
$rate = DefaultRate::find($request->id);
$rate->delete();
$arr['success'] = 'Rate deleted successfully';
return json_encode($arr);
exit;
}
public function billingPeriods(Request $request)
{
//$request->session()->put('panel', 'admin');
$billingPeriods = CustomerBillingPeriod::all();
return view('crm::settings.billingperiods.index', compact('billingPeriods'))->render();
}
public function deleteBillingPeriod(Request $request)
{
$request->session()->put('panel', 'admin');
$id = $request->id;
$billing_period = CustomerBillingPeriod::findorFail($id);
$billing_period->delete();
$arr['success'] = 'Billing period deleted successfully';
return json_encode($arr);
exit;
}
public function createBillingPeriod(Request $request)
{
//$request->session()->put('panel', 'admin');
$this->validate($request, [
'title' => 'required|unique:customer_billing_periods|max:15',
'description' => 'required',
]);
$billing_period = new CustomerBillingPeriod();
$billing_period->title = $request->title;
$billing_period->description = $request->description;
$billing_period->save();
$arr['success'] = 'Billing period created successfully';
return json_encode($arr);
exit;
}
public function serviceTypes(Request $request)
{
//$request->session()->put('panel', 'admin');
$serviceItems = CustomerServiceType::all();
return view('crm::settings.servicetypes.index', compact('serviceItems'))->render();
}
public function deleteServiceType(Request $request)
{
//$request->session()->put('panel', 'admin');
$service_item = CustomerServiceType::findorFail($request->id);
$service_item->delete();
$arr['success'] = 'Service item deleted successfully';
return $arr;
}
public function createServiceType(Request $request)
{
$this->validate($request, [
'title' => 'required|unique:customer_service_types|max:15',
'description' => 'required|max:15',
]);
$service_item = new CustomerServiceType();
$service_item->title = $request->title;
$service_item->description = $request->description;
$service_item->save();
$arr['success'] = 'Service item added successfully';
return $arr;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
function index(Request $request)
{
$request->session()->put('panel', 'admin');
$user = \Auth::user();
// $timezone = new TimeZone();
// $time_zones = $timezone->timezone_list();
//
// $request->session()->put('panel', 'admin');
return view('crm::settings.index', compact('user'));
}
function permissions(Request $request)
{
//$request->session()->put('panel', 'admin');
$user = \Auth::user();
//$request->session()->put('panel', 'admin');
return view('admin.setting.permissions', compact('user'));
}
public function imap()
{
$imap = Config::where('title', 'imap')->get();
//dd($imap);
$imap_email ='';
$imap_password = '';
foreach ($imap as $value) {
if ($value->key=='email') {
$imap_email = $value->value;
}
if ($value->key=='password') {
$imap_password = $value->value;
}
}
//dd($imap_email);
//return view('admin.config.imap',compact('imap_email','imap_password'));
$arr['imap_email'] = $imap_email;
$arr['imap_password'] = $<PASSWORD>;
return $arr;
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function imapStore(Request $request)
{
$this->validate(
$request,
[
'gmail_email' => 'required',
'gmail_password'=>'<PASSWORD>',
]
);
$imap = Config::where('key', 'email')->where('title', 'imap')->first();
$imap->value = $request->gmail_email;
$imap->save();
$imap = Config::where('key', 'password')->where('title', 'imap')->first();
$imap->value = $request->gmail_password;
$imap->save();
$arr['success'] = 'IMAP credentials updated successfully';
//$arr['imap_password'] = $imap_password;
return $arr;
//return redirect()->intended('admin/config/imap')->with('success', 'Gmail credentials updated Successfully!');
}
public function smtp()
{
$smtp_arr = Config::where('title', 'smtp')->get();
$arr =[];
foreach ($smtp_arr as $value) {
if ($value->key=='server_address') {
$arr['server_address'] = $value->value;
}
if ($value->key=='gmail_address') {
$arr['gmail_address'] = $value->value;
}
if ($value->key=='gmail_password') {
$arr['password'] = $value->value;
}
if ($value->key=='port') {
$arr['port'] = $value->value;
}
}
$imap = Config::where('title', 'imap')->get();
//dd($imap);
$imap_email ='';
$imap_password = '';
foreach ($imap as $value) {
if ($value->key=='email') {
$imap_email = $value->value;
}
if ($value->key=='password') {
$imap_password = $value->value;
}
}
//dd($imap_email);
//return view('admin.config.imap',compact('imap_email','imap_password'));
$arr['imap_email'] = $imap_email;
$arr['imap_password'] = $imap_password;
//dd($imap_email);
// return view('admin.config.smtp',compact('smtp'));
return $arr;
}
public function googleAuth()
{
$google_auth_arr = Config::where('title', 'google_auth')->get();
$google_auth =[];
foreach ($google_auth_arr as $value) {
if ($value->key=='gmail_auth_client_id') {
$google_auth['gmail_auth_client_id'] = $value->value;
}
if ($value->key=='gmail_auth_client_secret') {
$google_auth['gmail_auth_client_secret'] = $value->value;
}
if ($value->key=='redirect_uri') {
$google_auth['redirect_uri'] = $value->value;
}
}
//dd($imap_email);
// return view('admin.config.smtp',compact('smtp'));
//dd($google_auth);
return $google_auth;
}
public function smtpStore(Request $request)
{
//dd($request->all());
$this->validate(
$request,
[
'gmail_email' => 'required',
'gmail_password'=>'<PASSWORD>',
'server_address' => 'required',
'smtp_address'=>'required',
'smtp_password' => '<PASSWORD>',
'smtp_port'=>'required',
]
);
$smtp = Config::where('key', 'server_address')->where('title', 'smtp')->first();
$smtp->value = $request->server_address;
$smtp->save();
$smtp = Config::where('key', 'gmail_address')->where('title', 'smtp')->first();
$smtp->value = $request->smtp_address;
$smtp->save();
$smtp = Config::where('key', 'gmail_password')->where('title', 'smtp')->first();
$smtp->value = $request->smtp_password;
$smtp->save();
$smtp = Config::where('key', 'port')->where('title', 'smtp')->first();
$smtp->value = $request->smtp_port;
$smtp->save();
$imap = Config::where('key', 'email')->where('title', 'imap')->first();
$imap->value = $request->gmail_email;
$imap->save();
$imap = Config::where('key', 'password')->where('title', 'imap')->first();
$imap->value = $request->gmail_password;
$imap->save();
$arr['success'] = 'IMAP and SMTP credentials updated successfully';
//$arr['imap_password'] = $imap_<PASSWORD>;
//$arr['imap_password'] = $imap_<PASSWORD>;
return $arr;
// return redirect()->intended('admin/config/smtp')->with('success', 'SMTP Gmail credentials updated Successfully!');
}
function updateEmailData(Request $request)
{
//dd($request->all());
$employee = User::find(Auth::user()->id);
$employee->email_template = $request->email_template;
$employee->save();
// if()
/* $intro_email = Config::where('title','intro_email')->first();
$intro_email->value = $request->intro;
$intro_email->save();
*/
$arr['success'] = 'Email template updated successfully';
return json_encode($arr);
exit;
}
function updateEmailSignature(Request $request)
{
//dd($request->all());
$employee = User::find(Auth::user()->id);
$employee->email_signature = $request->email_signature;
$employee->save();
// if()
$arr['success'] = 'Email signature updated successfully.';
return json_encode($arr);
exit;
}
public function zohoSettingsDisplay()
{
$zoho = Config::where('title', 'zoho')->get();
foreach ($zoho as $value) {
if ($value->key=='email') {
$zoho_arr['email'] = $value->value;
}
if ($value->key=='password') {
$zoho_arr['password'] = $value->value;
}
if ($value->key=='auth_token') {
$zoho_arr['auth_token'] = $value->value;
}
}
//return view('crm::zoho.add',compact('zoho_arr'))->render();
return view('crm::settings.integrations.zoho_display', compact('zoho_arr'));
}
function zohoStore(Request $request)
{
//dd($request->all());
//$id = $request->zoho_id;
$this->validate(
$request,
[
'email' => 'required',
'password' => '<PASSWORD>',
]
);
//dd($request->all());
$zoho_email = Config::where('key', 'email')->where('title', 'zoho')->first();
$zoho_email->value = $request->email;
$zoho_email->save();
$zoho_pass = Config::where('key', 'password')->where('title', 'zoho')->first();
$zoho_pass->value = $request->password;
$zoho_pass->save();
$zoho_token = Config::where('key', 'auth_token')->where('title', 'zoho')->first();
$zoho_token->value = $request->token;
$zoho_token->save();
$arr['success'] = 'Zoho credentials updated successfully';
return json_encode($arr);
exit;
}
function telFaxUpdate(Request $request)
{
$tel = Config::where('key', 'telephone')->first();
$mob = Config::where('key', 'mobile')->first();
$fax = Config::where('key', 'fax')->first();
if ($tel) {
$tel->value= $request->telephone;
$tel->save();
} else {
$tel = new Config;
$tel->title = 'telephone_number';
$tel->value = $request->telephone;
$tel->key = 'telephone';
$tel->save();
}
if ($mob) {
$mob->value= $request->mobile;
$mob->save();
} else {
$mob = new Config;
$mob->title = 'mobile_number';
$mob->value = $request->mobile;
$mob->key = 'mobile';
$mob->save();
}
if ($fax) {
$fax->value= $request->fax;
$fax->save();
} else {
$fax = new Config;
$fax->title = 'fax_number';
$fax->value = $request->fax;
$fax->key = 'fax';
$fax->save();
}
$arr['success'] = 'Tel/Mobile/Fax numbers updated successfully';
return json_encode($arr);
exit;
}
function updateDateTime(Request $request)
{
//dd($request->all());
if ($request->date_format) {
$date = Config::where('title', 'date_format')->first();
if ($date) {
//dd('jj');
$date_format_arr = explode('|', $request->date_format);
$date_format_key = $date_format_arr[1];
$date_format_value = $date_format_arr[0];
$date->key = $date_format_key ;
$date->value = $date_format_value ;
$date->save();
} else {
$date_format_arr = explode('|', $request->date_format);
$date_format_key = $date_format_arr[1];
$date_format_value = $date_format_arr[0];
$date = new Config;
$date->title = 'date_format';
$date->value = $date_format_value;
$date->key = $date_format_key;
$date->save();
}
}
if ($request->time_format) {
$time = Config::where('title', 'time_format')->first();
if ($time) {
$time->value = $request->time_format;
$time->save();
} else {
$time = new Config;
$time->title = 'time_format';
$time->value = $request->time_format;
$time->key = 'time_format';
$time->save();
}
}
//$intro_email->save();
$arr['success'] = 'Date/Time format updated successfully';
return json_encode($arr);
exit;
}
public function getDateTime()
{
$date = Config::where('title', 'date_format')->first();
$time = Config::where('title', 'time_format')->first();
$arr['config_date'] = $date->value.'|'.$date->key;
$arr['config_time'] = $time->value;
return json_encode($arr);
exit;
}
public function slackSettingsDisplay()
{
$slack = Config::where('title', 'slack')->get();
foreach ($slack as $value) {
if ($value->key=='client_id') {
$slack_arr['client_id'] = $value->value;
}
if ($value->key=='secret') {
$slack_arr['secret'] = $value->value;
}
if ($value->key=='channel') {
$slack_arr['channel'] = $value->value;
}
if ($value->key=='redirect_uri') {
$slack_arr['redirect_uri'] = $value->value;
}
if ($value->key=='access_token') {
$slack_arr['access_token'] = $value->value;
}
}
//return view('crm::zoho.add',compact('zoho_arr'))->render();
return view('crm::settings.integrations.slack_display', compact('slack_arr'));
}
function slackStore(Request $request)
{
//$id = $request->zoho_id;
$this->validate(
$request,
[
'client_id' => 'required',
'secret' => 'required',
'redirect_uri' => 'required',
//'channel' => 'required',
]
);
//dd($request->all());
$slack_client_id = Config::where('key', 'client_id')->where('title', 'slack')->first();
$slack_client_id->value = $request->client_id;
$slack_client_id->save();
$slack_secret = Config::where('key', 'secret')->where('title', 'slack')->first();
$slack_secret->value = $request->secret;
$slack_secret->save();
$slack_redirect = Config::where('key', 'redirect_uri')->where('title', 'slack')->first();
$slack_redirect->value = $request->redirect_uri;
$slack_redirect->save();
if ($request->channel) {
$slack_channel = Config::where('key', 'channel')->where('title', 'slack')->first();
$slack_channel->value = $request->channel;
$slack_channel->save();
}
if ($request->access_token) {
$slack_access_token = Config::where('key', 'access_token')->where('title', 'slack')->first();
$slack_access_token->value = $request->access_token;
$slack_access_token->save();
}
//return view('crm::zoho.add',compact('zoho'))->with('status', 'saved');
$arr['success'] = 'Slack credentials updated successfully';
return json_encode($arr);
exit;
}
function slackTokenRequest()
{
$slack_client_id = Config::where('key', 'client_id')->where('title', 'slack')->first();
$url = 'https://slack.com/oauth/authorize?scope=incoming-webhook&client_id='.$slack_client_id->value.'&scope='.htmlentities('chat:write:user');
$return['url'] = $url;
return json_encode($return);
}
public function gmailSettingsDisplay()
{
$smtp_arr = Config::where('title', 'smtp')->get();
$smtp =[];
foreach ($smtp_arr as $value) {
if ($value->key=='server_address') {
$gmail['server_address'] = $value->value;
}
if ($value->key=='gmail_address') {
$gmail['gmail_address'] = $value->value;
}
if ($value->key=='gmail_password') {
$gmail['password'] = $value->value;
}
if ($value->key=='port') {
$gmail['port'] = $value->value;
}
}
$imap = Config::where('title', 'imap')->get();
//dd($imap);
$imap_email ='';
$imap_password = '';
foreach ($imap as $value) {
if ($value->key=='email') {
$imap_email = $value->value;
}
if ($value->key=='password') {
$imap_password = $value->value;
}
}
//dd($imap_email);
//return view('admin.config.imap',compact('imap_email','imap_password'));
$gmail['imap_email'] = $imap_email;
$gmail['imap_password'] = $imap_password;
$google_auth_arr = Config::where('title', 'google_auth')->get();
$google_auth =[];
foreach ($google_auth_arr as $value) {
if ($value->key=='gmail_auth_client_id') {
$gmail['gmail_auth_client_id'] = $value->value;
}
if ($value->key=='gmail_auth_client_secret') {
$gmail['gmail_auth_client_secret'] = $value->value;
}
if ($value->key=='redirect_uri') {
$gmail['redirect_uri'] = $value->value;
}
}
//return view('crm::zoho.add',compact('zoho_arr'))->render();
return view('crm::settings.integrations.gmail_display', compact('gmail'));
}
function resetAuthToken()
{
//dd($id);
$zoho_email = Config::where('title', 'zoho')->where('key', 'email')->first();
$zoho_pass = Config::where('title', 'zoho')->where('key', 'password')->first();
//dd($zoho_email);
$url = 'https://accounts.zoho.com/apiauthtoken/nb/create?SCOPE=ZohoInvoice/invoiceapi&EMAIL_ID='.$zoho_email->value.'&PASSWORD='.$<PASSWORD>->value;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
// dd($result);
$arr['msg'] = $result;
return json_encode($arr);
exit;
}
function assetServerRoleSettingsDisplay()
{
return view('crm::settings.assets.asset_server_role_display');
}
function listServerRoles()
{
$global_date = $this->global_date;
$roles = AssetRole::all();
//dd($roles);
return Datatables::of($roles)
->addColumn('action', function ($role) {
$return = '<div class="btn-group"><button type="button" class="btn btn-danger btn-xs"
data-toggle="modal" data-id="'.$role->id.'" id="modaal" data-target="#modal-delete-asset-server-role">
<i class="fa fa-times-circle"></i>
</button></div>';
return $return;
})
->editColumn('created_at', function ($role) use ($global_date) {
return date($global_date, strtotime($role->created_at));
})
->make(true);
}
function destroyServerRole(Request $request)
{
$role = AssetRole::find($request->id);
$role->delete();
$arr['success'] = 'Server role deleted sussessfully';
return json_encode($arr);
exit;
//return true;
}
function createServerRole(Request $request)
{
$this->validate(
$request,
[
'title' => 'required|unique:asset_roles',
]
);
//$role = AssetRole::where('title',$role)->get();
$new_role = new AssetRole();
$new_role->title = $request->title;
$new_role->save();
$arr['success'] = 'Server role added sussessfully';
return json_encode($arr);
exit;
}
function listServerVirtualTypes()
{
$global_date = $this->global_date;
$vtypes = AssetVirtualType::all();
//dd($roles);
return Datatables::of($vtypes)
->addColumn('action', function ($vtype) {
$return = '<div class="btn-group"><button type="button" class="btn btn-danger btn-xs"
data-toggle="modal" data-id="'.$vtype->id.'" id="modaal" data-target="#modal-delete-asset-server-v-type">
<i class="fa fa-times-circle"></i>
</button></div>';
return $return;
})
->editColumn('created_at', function ($vtype) use ($global_date) {
return date($global_date, strtotime($vtype->created_at));
})
->make(true);
}
function destroyServerVirtualType(Request $request)
{
$vtype = AssetVirtualType::find($request->id);
$vtype->delete();
$arr['success'] = 'Server virtual type deleted sussessfully';
return json_encode($arr);
exit;
//return true;
}
function createServerVirtualType(Request $request)
{
$this->validate(
$request,
[
'title' => 'required|unique:asset_virtual_types',
]
);
//$role = AssetRole::where('title',$role)->get();
$vtype = new AssetVirtualType();
$vtype->title = $request->title;
$vtype->save();
$arr['success'] = 'Server virtual type added sussessfully';
return json_encode($arr);
exit;
}
function system(Request $request)
{
//$request->session()->put('panel', 'admin');
$user = \Auth::user();
$timezone = new TimeZone();
$time_zones = $timezone->timezone_list();
$sys_date_fmt = Config::where('title', 'date_format')->first();
$sys_time_fmt = Config::where('title', 'time_format')->first();
//$request->session()->put('panel', 'admin');
return view('admin.setting.system', compact('user', 'time_zones', 'sys_date_fmt', 'sys_time_fmt'));
}
function assetServerVTypesSettingsDisplay()
{
return view('crm::settings.assets.asset_server_v_types_display');
}
function systemSave(Request $request)
{
// Save the date format
$date_format_arr = explode('|', $request->date_format);
$date_format_key = $date_format_arr[1];
$date_format_value = $date_format_arr[0];
if (!$this->saveConfigSetting('date_format', $date_format_key, $date_format_value)) {
return json_encode(['result' => 'fail']);
}
// Save the time format
if (!$result = $this->saveConfigSetting('time_format', '', $request->time_format)) {
return json_encode(['result' => 'fail']);
}
// Save the time zone format
if (!$this->saveConfigSetting('system_timezone', 'timezone', $request->time_zone)) {
return json_encode(['result' => 'fail']);
}
// Save the telephone format
if (!$this->saveConfigSetting('telephone_number', 'telephone', $request->telephone)) {
return json_encode(['result' => 'fail']);
}
return json_encode(['result' => 'success']);
}
private function saveConfigSetting($title, $key, $value)
{
$config = Config::where('title', $title)->first();
// Let's create the setting if it does not exist already
if (!$config) {
$config = new Config;
$config->title = $title;
}
$config->key = $key;
$config->value = $value;
return $config->save();
}
function getEmailData()
{
$employee = User::find(Auth::user()->id);
$arr['email_template'] = $employee->email_template;
return json_encode($arr);
exit;
}
function getUserDevices()
{
$devices = UserDevice::where('user_id', Auth::user()->id)->get();
return json_encode($devices);
exit;
}
function deleteUserDevice($id)
{
$device = UserDevice::find($id);
if ($device->cookie_id==Cookie::get('nexgen_device')) {
Cookie::forget('nexgen_device');
}
$device->delete();
$arr['success'] = 'Device extention deleted successfully';
return json_encode($arr);
exit;
}
function getEmailSignature()
{
$employee = User::find(Auth::user()->id);
$arr['email_signature'] = $employee->email_signature;
return json_encode($arr);
exit;
}
function gmailApiUpdate(Request $request)
{
$this->validate(
$request,
[
'gmail_auth_client_id' => 'required',
'gmail_auth_client_secret'=>'required',
'redirect_uri'=>'required',
]
);
$auth_key = Config::where('key', 'gmail_auth_client_id')->first();
$auth_key->value = $request->gmail_auth_client_id;
$auth_key->save();
$auth_secret = Config::where('key', 'gmail_auth_client_secret')->first();
$auth_secret->value = $request->gmail_auth_client_secret;
$auth_secret->save();
$redirect_uri = Config::where('key', 'redirect_uri')->first();
$redirect_uri->value = $request->redirect_uri;
$redirect_uri->save();
//$gmail = new GoogleGmail('new');
/*$file_path = base_path('resources/assets');
$file['client_id'] = $request->gmail_auth_client_id;
$file['client_secret'] = $request->gmail_auth_client_secret;
//$file['redirect_uris'] = [\URL::route('get_token')];
$file['redirect_uris'] = ['http://crm.ng2.us/get_token'];
$str_to_json['web'] = $file;
// dd($file);
//dd($file_path."client_secret.json");
try
{
//file_put_contents($file_path."client_secret.json", json_encode($file);
$myfile = fopen($file_path."/client_secret.json", "w") or die("Unable to open file!");
fwrite($myfile, json_encode($str_to_json,JSON_UNESCAPED_SLASHES));
fclose($myfile);
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
*/
$gmail = new GoogleGmail('reset');
//dd($gmail->auth_url);
return compact("gmail");
// dd('done');
}
function getToken(Request $request)
{
$code = $request->all();
//dd($request->all());
$token = $code['code'].'#';
$set = new GoogleGmail('token_reset', $token);
if ($set) {
dd('credentials updated successfully');
}
//dd( $token);
}
}
<file_sep>/app/Model/Role.php
<?php namespace App\Model;
use Zizaco\Entrust\EntrustRole;
use Illuminate\Database\Eloquent\Model;
class Role extends EntrustRole
{
//name "admin", "owner", "employee".
//display_name "User Administrator", "Project Owner", "Widget Co. Employee".
//discription
protected $fillable = ['name','display_name','description'];
}
<file_sep>/app/Http/Controllers/RoleController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Model\Role;
use App\Model\Permission;
use Datatables;
class RoleController extends Controller
{
private $controller = 'role';
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$controller = $this->controller;
$roles = Role::select(['id','name','display_name','description','created_at'])->get();
if (\Request::ajax()) {
return view('admin.roles.ajax_index', compact('roles', 'controller'))->render();
}
return view('admin.roles.index', compact('roles', 'controller'));
}
public function ajaxDataIndex()
{
$global_date = $this->global_date;
$roles = Role::select(['id','name','display_name','description','created_at']);
return Datatables::of($roles)
->addColumn('action', function ($role) {
$return = '<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-id="'.$role->id.'" id="modaal" data-target="#modal-edit-role">
<i class="fa fa-pencil"></i>Edit</button><button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-id="'.$role->id.'" id="modaal" data-target="#modal-delete-role">
<i class="fa fa-times-circle"></i>Delete</button>';
return $return;
})
->editColumn('created_at', function ($permission) use ($global_date) {
return date($global_date, strtotime($permission->created_at));
})
->make(true);
}
public function create()
{
$permissions = Permission::select(['id','display_name'])->get();
//return view('admin.roles.add',compact('permissions'));
$arr['permissions'] = $permissions ;
//$arr['success'] = 'Status updated successfully';
return json_encode($arr);
exit;
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//dd($request->all());
$this->validate($request, [
'name' => 'required|unique:roles|max:50',
'display_name' => 'required',
'description' => 'required',
]);
$role = new Role();
$role->name = $request->name;
$role->display_name = $request->display_name; // optional
$role->description = $request->description; // optional
$role->save();
if ($request->permissions) {
$role->attachPermissions($request->permissions);
}
//print_r($request->all()); die('asdas');
//return redirect()->route('admin.role.index');
$arr['success'] = 'Role added successfully';
return json_encode($arr);
exit;
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$role = Role::where('id', $id)->first();
foreach ($role->perms as $perm) {
$selected_perms[]=$perm->id;
}
$permissions = Permission::select(['id','display_name'])->get();
//return view('admin.roles.add',compact('role','permissions','selected_perms'));
$arr['permissions'] = $permissions ;
$arr['role'] = $role ;
$arr['selected_perms'] = $selected_perms ;
//$arr['success'] = 'Status updated successfully';
return json_encode($arr);
exit;
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request)
{
$id = $request->role_id;
$this->validate($request, [
'name' => 'required|max:50|unique:roles,name,'.$id,
'display_name' => 'required',
'description' => 'required',
]);
$role = Role::find($id);
$role->name = $request->name;
$role->display_name = $request->display_name; // optional
$role->description = $request->description; // optional
$role->save();
//detach all permissions from role
$role->perms()->sync([]);
//detach all users
//$role->users()->sync([]);
if ($request->permissions) {
$role->attachPermissions($request->permissions);
}
// return redirect()->route('admin.role.index');
$arr['success'] = 'Role updated successfully';
return json_encode($arr);
exit;
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//dd($id);
//dd($request->id);
//$id = $request->id;
$role = Role::findorFail($id);
$role->perms()->sync([]);
$role->users()->sync([]);
$role->delete();
//Session::flash('flash_message', 'User successfully deleted!');
//return redirect()->intended('admin/role');
$arr['success'] = 'Role deleted successfully';
return json_encode($arr);
exit;
}
}
<file_sep>/app/Model/Permission.php
<?php
namespace App\Model;
use Zizaco\Entrust\EntrustPermission;
class Permission extends EntrustPermission
{
//name "admin", "owner", "employee".
//display_name "User Administrator", "Project Owner", "Widget Co. Employee".
//discription
protected $fillable = ['name','display_name','description'];
}
<file_sep>/app/Modules/Crm/Http/Controllers/AjaxController.php
<?php
namespace App\Modules\Crm\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Modules\Crm\Http\TicketStatus;
use App\Modules\Crm\Http\Customer;
use App\Modules\Crm\Http\CustomerLocation;
use App\Modules\Crm\Http\CustomerNote;
use App\Modules\Crm\Http\CustomerLocationContact;
use App\Modules\Crm\Http\CustomerServiceItem;
use App\Model\Role;
use App\Model\User;
use App\Model\Config;
use Auth;
use Datatables;
use Mail;
class AjaxController extends Controller
{
// Select2 Get Ticket Statuses List
function getSelect2Statuses()
{
$statuses_ = TicketStatus::select('title as text', 'id');
return json_encode($statuses_->get());
exit;
}
// Select2 Get Customer Locations List
function getSelect2Locations($cust_id)
{
$data = CustomerLocation::where('customer_id', $cust_id)->select('id', 'location_name as text')->get();
return json_encode($data);
exit;
}
// Select2 Get Customer Contacts List
function getSelect2Contacts($cust_id)
{
$contacts = CustomerLocationContact::
leftJoin('customer_locations', 'customer_location_contacts.customer_location_id', '=', 'customer_locations.id')
->select(DB::raw('CONCAT(f_name, " ", l_name) AS text'), 'customer_location_contacts.id as id')
->where('customer_id', $cust_id);
return json_encode($contacts->get());
exit;
}
// Select2 Get Technicians List
function getSelect2Techs()
{
$techs = Role::
rightJoin('role_user', 'role_user.role_id', '=', 'roles.id')
->rightJoin('users', 'role_user.user_id', '=', 'users.id')
->select(DB::raw('CONCAT(f_name, " ", l_name) AS text'), 'users.id as id');
return json_encode($techs->get());
exit;
}
// Select2 Get Service Items List
function getSelect2ServiceItems($cust_id)
{
$contacts = CustomerServiceItem::
select('title as text', 'id')
->where('customer_id', $cust_id);
return json_encode($contacts->get());
exit;
}
// Get Customer Notes in JSON
function getCustomerNotes($cust_id)
{
$notes = CustomerNote::where('customer_id', $cust_id)->get();
foreach ($notes as &$note) {
$string = preg_replace("/[\r\n]{2,}/", " ", strip_tags($note['note']));
$note['note'] = $this->shortenString(rtrim($string), 15);
}
return json_encode($notes);
exit;
}
private function shortenString($sentence, $count = 10)
{
preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches);
return $matches[0];
}
// Create Customer Note in JSON
function createCustomerNote(Request $request)
{
$this->validate($request, [
'customer_id' => 'required',
'subject' => 'required',
'note' => 'required'
]);
//dd($request->all());
$note_obj = new CustomerNote;
$note_obj->customer_id = $request->customer_id;
$note_obj->subject = $request->subject;
$note_obj->source = $request->source;
$note_obj->note = $request->note;
$note_obj->archived = 0;
$note_obj->created_by = Auth::user()->id;
if ($note_obj->save()) {
$arr['success'] = 'Note added successfully';
return json_encode($arr);
}
exit;
}
function updateCustomer(Request $request)
{
dd($request->all());
$customer = Customer::findOrFail($request->pk);
$name = $request->get('name');
$value = $request->get('value');
if (is_array($value)) {
$value = $value[0];
}
$customer->{$name} = $value;
$customer->save();
$arr['success'] = 'Customer info updated successfully';
return json_encode($arr);
exit;
}
function sendEmails(Request $request)
{
//dd($request->all());
$smtp_arr = Config::where('title', 'smtp')->get();
$smtp =[];
foreach ($smtp_arr as $value) {
if ($value->key=='server_address') {
$server_address = $value->value;
}
if ($value->key=='gmail_address') {
$gmail_address = $value->value;
}
if ($value->key=='gmail_password') {
$password = $value->value;
}
if ($value->key=='port') {
$port= $value->value;
}
}
config(['mail.driver' => 'smtp',
'mail.host' => $server_address,
'mail.port' => $port,
'mail.encryption' => 'ssl',
'mail.username' => $gmail_address,
'mail.password' => $<PASSWORD>,
'mail.from' =>['address'=>$gmail_address,'name'=>'Nexgentec']]);
$cc = $request->cc;
$to = $request->to;
$body = $request->email_body;
//$body .= $email_signature;
Mail::send('crm::ticket.email.response', ['body'=>$body], function ($message) use ($request, $gmail_address, $to, $cc) {
if (count($cc)>0) {
foreach ($cc as $key => $cc_email) {
$message->cc(trim($cc_email), $name = null);
}
}
//$headers->addTextHeader('References', $ticket->gmail_msg_id);
$message->from(trim($gmail_address), Auth::user()->f_name.' '.Auth::user()->l_name);
if (count($to)>0) {
foreach ($to as $key => $to_email) {
//$message->cc(trim($to_email), $name = null);
$message->to(trim($to_email), $name = null);
}
}
//$message->to(trim($ticket->email),$ticket->sender_name);
$message->subject($request->email_subject);
});
return json_encode(['success'=>'yes']);
exit;
}
function displayDataHtable()
{
return view('crm::notes.handsontable');
}
}
<file_sep>/app/Modules/Assets/Http/routes.php
<?php
/*
|--------------------------------------------------------------------------
| Module Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for the module.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::group(['middleware' => 'web'], function () {
Route::group(['prefix' => 'admin','middleware' => 'admin'], function () {
Route::group(['prefix' => 'assets','middleware' => ['role:admin|manager|technician']], function () {
Route::get('/', ['as'=>'admin.assets.index','middleware' => ['permission:list_assets'], 'uses' => 'AssetsController@index']);
Route::get('/create', ['as'=>'admin.assets.create','middleware' => ['permission:create_asset'], 'uses' => 'AssetsController@create']);
Route::post('/store', ['as'=>'admin.assets.store','middleware' => ['permission:create_asset'], 'uses' => 'AssetsController@store']);
Route::post('/update', ['as'=>'admin.assets.update','middleware' => ['permission:create_asset'], 'uses' => 'AssetsController@update']);
Route::get('/show/{id}', ['as'=>'admin.assets.show','middleware' => ['permission:create_asset'], 'uses' => 'AssetsController@show']);
Route::get('/edit/{id}', ['as'=>'admin.assets.show','middleware' => ['permission:create_asset'], 'uses' => 'AssetsController@edit']);
Route::post('/delete', ['as'=>'admin.assets.delete','middleware' => ['permission:create_asset'], 'uses' => 'AssetsController@destroy']);
Route::get('/assets_all', ['as'=>'admin.assets.all','middleware' => ['permission:list_assets'], 'uses' => 'AssetsController@assetsAll']);
Route::get('/network_index', ['as'=>'admin.assets.network_index','middleware' => ['permission:list_assets'], 'uses' => 'AssetsController@networkIndex']);
Route::get('/gateway_index', ['as'=>'admin.assets.gateway_index','middleware' => ['permission:list_assets'], 'uses' => 'AssetsController@gatewayIndex']);
Route::get('/pbx_index', ['as'=>'admin.assets.pbx_index','middleware' => ['permission:list_assets'], 'uses' => 'AssetsController@pbxIndex']);
Route::get('/server_index', ['as'=>'admin.assets.server_index','middleware' => ['permission:list_assets'], 'uses' => 'AssetsController@serverIndex']);
Route::get('/network_index_bycustomer/{id}', ['as'=>'admin.assets.network_index_by_cust','middleware' => ['permission:list_assets'], 'uses' => 'AssetsController@networkIndex']);
Route::get('/gateway_index_bycustomer/{id}', ['as'=>'admin.assets.gateway_index_by_cust','middleware' => ['permission:list_assets'], 'uses' => 'AssetsController@gatewayIndex']);
Route::get('/pbx_index_bycustomer/{id}', ['as'=>'admin.assets.pbx_index_by_cust','middleware' => ['permission:list_assets'], 'uses' => 'AssetsController@pbxIndex']);
Route::get('/server_index_bycustomer/{id}', ['as'=>'admin.assets.server_index_by_cust','middleware' => ['permission:list_assets'], 'uses' => 'AssetsController@serverIndex']);
});
Route::group(['prefix' => 'knowledge','middleware' => ['role:admin|manager|technician']], function () {
Route::get('/', ['as'=>'admin.knowledge.all','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@index']);
Route::get('/passwords_list', ['as'=>'admin.knowledge.passwords.list','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@passwordsList']);
Route::get('/passwords', ['as'=>'admin.knowledge.passwords','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@passwordsIndex']);
Route::get('/passwords_bycustomer/{id}', ['as'=>'admin.knowledge.passwords_by_cust','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@passwordsIndex']);
Route::post('/password', ['as'=>'admin.knowledge.store.password','middleware' => ['permission:add_knowledge'], 'uses' => 'KnowledgeController@storePassword']);
Route::post('/password_tag', ['as'=>'admin.knowledge.store.password.tag','middleware' => ['permission:add_knowledge'], 'uses' => 'KnowledgeController@storePasswordTag']);
Route::get('/tags', ['as'=>'admin.knowledge.get.tags','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@getTags']);
Route::get('/edit/password/{id}', ['as'=>'admin.knowledge.edit.password','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@editPassword']);
Route::post('/update/password', ['as'=>'admin.knowledge.update.password','middleware' => ['permission:add_knowledge'], 'uses' => 'KnowledgeController@updatePassword']);
Route::post('/delete/password', ['as'=>'admin.knowledge.delete.password','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@deletePassword']);
Route::get('/procedures_list', ['as'=>'admin.knowledge.procedures.list','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@proceduresList']);
Route::get('/procedure_detail/{id}', ['as'=>'admin.knowledge.procedure.detail','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@procedureDetail']);
Route::get('/procedures', ['as'=>'admin.knowledge.procedures','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@proceduresIndex']);
// Procedure Image Handling
Route::get('/image', ['as'=>'admin.knowledge.get.uniqid','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@getImageDirUniqid']);
Route::post('/image', ['as'=>'admin.knowledge.upload.image','middleware' => ['permission:add_knowledge'], 'uses' => 'KnowledgeController@storeImage']);
Route::get('/image/{folder}/{filename}', ['as'=>'admin.knowledge.get.image','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@retrieveImage']);
Route::get('/image/del/{folder}/{filename}', ['as'=>'admin.knowledge.del.image','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@deleteImage']);
Route::get('/procedures_bycustomer', ['as'=>'admin.knowledge.procedures_by_cust','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@proceduresIndex']);
Route::post('/procedure', ['as'=>'admin.knowledge.store.procedure','middleware' => ['permission:add_knowledge'], 'uses' => 'KnowledgeController@storeProcedure']);
Route::get('/edit/procedure/{id}', ['as'=>'admin.knowledge.edit.procedure','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@editProcedure']);
Route::post('/update/procedure', ['as'=>'admin.knowledge.update.procedure','middleware' => ['permission:add_knowledge'], 'uses' => 'KnowledgeController@updateProcedure']);
Route::post('/delete/procedure', ['as'=>'admin.knowledge.delete.procedure','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@deleteProcedure']);
Route::get('/serial_numbers_list', ['as'=>'admin.knowledge.serial_numbers.list','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@serialnumberList']);
Route::get('/serial_numbers', ['as'=>'admin.knowledge.serial_numbers','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@serialnumberIndex']);
Route::get('/serial_numbers_bycustomer/{id}', ['as'=>'admin.knowledge.serial_numbers_by_cust','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@serialnumberIndex']);
Route::post('/serial_number', ['as'=>'admin.knowledge.store.serial_number','middleware' => ['permission:add_knowledge'], 'uses' => 'KnowledgeController@storeSerialNumber']);
Route::get('/edit/serial_number/{id}', ['as'=>'admin.knowledge.edit.serial_number','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@editSerialNumber']);
Route::post('/update/serial_number', ['as'=>'admin.knowledge.update.serial_number','middleware' => ['permission:add_knowledge'], 'uses' => 'KnowledgeController@updateSerialNumber']);
Route::post('/delete/serial_number', ['as'=>'admin.knowledge.delete.serial','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@deleteSerialNumber']);
Route::get('/type/{type}/{id}', ['as'=>'admin.knowledge.show','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@show']);
Route::get('/networks', ['as'=>'admin.knowledge.networks','middleware' => ['permission:view_knowledge'], 'uses' => 'NetworkController@Index']);
Route::get('/networs_list', ['as'=>'admin.knowledge.networks.list','middleware' => ['permission:view_knowledge'], 'uses' => 'NetworkController@networkIndex']);
Route::get('/networs_list_bycustomer/{id}', ['as'=>'admin.knowledge.networks_list_by_cust','middleware' => ['permission:view_knowledge'], 'uses' => 'NetworkController@networkIndex']);
Route::post('/network', ['as'=>'admin.knowledge.store.network','middleware' => ['permission:add_knowledge'], 'uses' => 'NetworkController@store']);
Route::get('/network/{id}', ['as'=>'admin.knowledge.show.network','middleware' => ['permission:add_knowledge'], 'uses' => 'NetworkController@show']);
Route::get('/edit/network/{id}', ['as'=>'admin.knowledge.edit.network','middleware' => ['permission:view_knowledge'], 'uses' => 'NetworkController@edit']);
Route::post('/update/network', ['as'=>'admin.knowledge.update.network','middleware' => ['permission:add_knowledge'], 'uses' => 'NetworkController@update']);
Route::post('/delete/network', ['as'=>'admin.knowledge.delete.network','middleware' => ['permission:view_knowledge'], 'uses' => 'NetworkController@deleteNetwork']);
// Ajax
Route::get('ajax_detail/{id}', ['as'=>'admin.knowledge.ajax_details','middleware' => ['permission:view_knowledge'], 'uses' => 'KnowledgeController@ajaxDetails']);
// Ajax
});
});
});<file_sep>/resources/views/admin/script_global_search.blade (full-working).php
$.typeahead({
input: '.js-typeahead-input',
minLength: 1,
order: "asc",
dynamic: true,
delay: 500,
backdrop: {
"background-color": "#fff"
},
group: true,
/*template: "@{{display}}, <small><em>@{{group}}</em></small>",*/
dropdownFilter: "All",
template: function (query, item) {
var color = "#777";
/*if (item.status === "owner") {
color = "#ff1493";
}*/
if(item.group=='location')
{
//console.log(item);
return '<span class="row">' +
'<span class="username">@{{loc_name}} <small style="color: ' + color + ';">(@{{group}})</small></span>' +
"</span>";
}
if(item.group=='customer')
{
//console.log(item);
return '<span class="row">' +
'<span class="username">@{{cust_name}} <small style="color: ' + color + ';">(@{{group}})</small></span>' +
"</span>";
}
if(item.group=='ticket')
{
//console.log(item);
return '<span class="row">' +
'<span class="username">@{{ticket_title}} <small style="color: ' + color + ';">(@{{group}})</small></span>' +
"</span>";
}
},
emptyTemplate: "no result for @{{query}}",
source: {
customer: {
display: "cust_name",
href: "{{URL::route('admin.crm.index')}}/show/@{{id}}",
ajax: function (query) {
return {
type: "GET",
url: "{{URL::route('admin.crm.search.customers')}}",
path: "data.customers",
data: {
cust: "@{{query}}"
},
callback: {
done: function (data) {
//console.log(data);
/*for (var i = 0; i < data.customers.length; i++) {
data.customers[i].status = 'contributor';
}*/
return data;
}
}
}
}
},
location:{
display: "loc_name",
href: "{{URL::route('admin.crm.index')}}/show/@{{id}}",
ajax: function (query) {
return {
type: "GET",
url: "{{URL::route('admin.crm.search.locations')}}",
path: "data.locations",
data: {
loc: "@{{query}}"
},
callback: {
done: function (data) {
//console.log(data);
/*for (var i = 0; i < data.customers.length; i++) {
data.customers[i].status = 'contributor';
}*/
return data;
}
}
}
}
},
ticket:{
display: "ticket_title",
href: "{{URL::route('admin.ticket.index')}}/show/@{{id}}",
ajax: function (query) {
return {
type: "GET",
url: "{{URL::route('admin.crm.ajax.search.tickets')}}",
path: "data.tickets",
{{-- dataType: 'json', --}}
data: {
ticket: "@{{query}}"
},
callback: {
done: function (data) {
console.log(data);
/*for (var i = 0; i < data.customers.length; i++) {
data.customers[i].status = 'contributor';
}*/
return data;
}
}
}
}
}
},
callback: {
onClick: function (node, a, item, event) {
// You can do a simple window.location of the item.href
//alert(JSON.stringify(item));
},
onSendRequest: function (node, query) {
//console.log('request is sent')
},
onReceiveRequest: function (node, query) {
//console.log('request is received')
},
onResult: function (node, query, obj, objCount) {
//console.log(objCount)
var text = "";
if (query !== "") {
text = objCount + ' elements matching "' + query + '"';
}
$('.js-result-container').text(text);
}
},
debug: true
});<file_sep>/app/Http/Controllers/AdminController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\SignUpPostRequest;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use App\Model\User;
use Auth;
use Event;
use App\Events\countNewLeaves;
use App\Events\updateGoogleAuthToken;
use App\Services\GoogleCalendar;
use Session;
use App\Modules\Crm\Http\CustomerAppointment;
class AdminController extends Controller
{
//private $admin = 1;
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
private $admin = 1;
/**
* Setup the layout used by the controller.
*/
public function __construct()
{
}
public function getRegister()
{
return view('admin.register');
}
public function postRegister(SignUpPostRequest $request)
{
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = <PASSWORD>($request->password);
$user->save();
return redirect()->intended('admin/dashboard');
}
public function getLogin()
{
// If logged in redirect
if (Auth::check()) {
return redirect()->intended('admin/dashboard');
}
// Not logged in
return view('admin.login');
}
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => '<PASSWORD>',
]);
if (Auth::attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
if (Auth::user()->hasRole('admin')) {
$leaves_count = Event::fire(new countNewLeaves());
//Event::fire(new updateGoogleAuthToken());
Session::forget('leaves_posted_count');
Session::put('leaves_posted_count', $leaves_count[0]);
}
//dd($leaves_count);
return redirect()->intended('admin/dashboard');
} else {
return redirect()->intended('admin/login');
}
}
public function showDashboard()
{
/*$calendar = new GoogleCalendar;
$events_result = $calendar->eventList();
$events_arr = [];
foreach ($events_result->getItems() as $event)
{
//dd($event->organizer);
//$calendar->eventDelete($event->getId());
if($event->start->getDatetime()!=NULL)
{
$events_arr[] = ['title'=>$event->getSummary(),
'start'=>$event->start->getDatetime(),
'end'=>$event->end->getDatetime()];
}
else
{
$events_arr[] = ['title'=>$event->getSummary(),
'start'=>$event->start->getDate(),
'end'=>$event->end->getDate()];
}
}
$events = json_encode($events_arr);*/
$calendar = new GoogleCalendar;
//$result = $calendar->get();
$events_result = $calendar->eventList();
//dd($events_result);
$events_arr = [];
//while(true) {
foreach ($events_result->getItems() as $event) {
// dd($event);
//$calendar->eventDelete($event->getId());
$event_row = CustomerAppointment::where('event_id_google', $event->getId())->first();
//dd($event_row);
if (!$event_row) {
$event_row='';
}
if ($event->start->getDatetime()!=null) {
$events_arr[] = ['title'=>html_entity_decode($event->getSummary()),
'start'=>$event->start->getDatetime(),
'end'=>$event->end->getDatetime(),
'description'=>$event->getDescription(),
'id'=>$event->getId(),
'event_row'=>$event_row];
} else {
$events_arr[] = ['title'=>html_entity_decode($event->getSummary()),
'start'=>$event->start->getDate(),
'end'=>$event->end->getDate(),
'description'=>$event->getDescription(),
'id'=>$event->getId(),
'event_row'=>$event_row];
}
}
$events = json_encode($events_arr);
///dd($events_arr);
session()->forget('cust_id');
session()->forget('customer_name');
return View('admin.dashboard', compact('events'));
}
public function doLogout()
{
Auth::logout(false); // log the user out of our application
return Redirect::to('admin'); // redirect the user to the login screen
}
public function profile()
{
}
public function listUsers()
{
$user = User::where('role_id', '<>', $this->admin)->get();
//$role = $user->role;
/*foreach($user as $usr)
{
echo $usr->name;
}*/
//exit;
return view('admin.users', ['users' => $user]);
}
public function addUser()
{
return view('admin.add_user');
}
public function postAddUser(SignUpPostRequest $request)
{
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = <PASSWORD>($request-><PASSWORD>);
$user->role_id = 2;
$user->save();
return redirect()->intended('admin/users');
}
}
<file_sep>/app/Modules/Employee/Http/Requests/LeavePostRequest.php
<?php
namespace App\Modules\Employee\Http\Requests;
use App\Http\Requests\Request;
class LeavePostRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
//dd($this->request->isMethod('put'));
if (Request::isMethod('put')) {
/*if(!empty(Request::input('password')))
{
'password' => '<PASSWORD>',
}*/
return [
'start_date' => 'required',
'end_date' => 'required',
'type' => 'required',
// 'password' => '<PASSWORD>',
];
}
if (Request::isMethod('post')) {
return [
'start_date' => 'required',
'title' => 'required|max:15',
'end_date' => 'required',
'type' => 'required',
// 'password' => '<PASSWORD>',
];
}
}
public function messages()
{
return [
'start_date.required' => 'Start date is required',
'end_date.required' => 'End date is required',
'type.required' => 'Leave type is required',
];
}
}
<file_sep>/app/Modules/Crm/Http/DefaultRate.php
<?php
namespace App\Modules\Crm\Http;
use Illuminate\Database\Eloquent\Model;
class DefaultRate extends Model
{
}
|
48d7d4d8a6015c08a532379dca937f9794f2f571
|
[
"JavaScript",
"PHP"
] | 107
|
PHP
|
wsaeed77/Nextgentec
|
9ca6a0d071d93d15ad10760b330a351f1b2fb93b
|
f573b42f9f11c52fa21c1dafc8baf847aecf4edc
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VariableCompare
{
class Program
{
static void Main(string[] args)
{
CharCompareString();
Console.ReadLine();
}
private static void CharCompareString()
{
string strReciveData = "/12345678901234567890>";
Console.WriteLine("{0}和{1}的strReciveData[0]比较结果为{2}", '/', strReciveData, '/' == strReciveData[0]);
Console.WriteLine("字符串{0}和{1}的strReciveData[0]比较结果为{2}", "/", strReciveData, '/' == strReciveData[0]);
Console.WriteLine("{0}和{1}的strReciveData[22-1]比较结果为{2}", '>', strReciveData, '>' == strReciveData[22 - 1]);
}
}
}
|
e2952afe7285781deda70c0e4e36b8521d05c7de
|
[
"C#"
] | 1
|
C#
|
wuzuqiang/VariableCompare
|
9782f30048dabb757bdada1b663c75e4aa9101cb
|
921cd11efdd7c6efc83562d12af9c2b2e1ee3cd9
|
refs/heads/main
|
<file_sep># Finance-Control-App
|
6c3a6d2dae5d525580d58c4b6af297731a328cad
|
[
"Markdown"
] | 1
|
Markdown
|
enrico-secco/Finance-Control-App
|
2e8b44089f38d3583ea6e805ca23210dbe06e33a
|
c85611ce6cc2238b5fd86e577ea87a11ef3e9c98
|
refs/heads/main
|
<file_sep>package first;
public class duyuru {
protected int id;
protected String Baslik;
protected String icerik;
protected String date;
public duyuru() {
}
public duyuru(int id) {
this.id = id;
}
public duyuru(int id,String Baslik, String icerik) {
this.id = id;
this.Baslik = Baslik;
this.icerik = icerik;
}
public duyuru(int id, String Baslik) {
this.id = id;
this.Baslik = Baslik;
}
public duyuru(int id,String Baslik, String icerik, String date) {
this.id = id;
this.Baslik = Baslik;
this.icerik = icerik;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBaslik() {
return Baslik;
}
public void setBaslik(String Baslik) {
this.Baslik = Baslik;
}
public String geticerik() {
return icerik;
}
public void seticerik(String icerik) {
this.icerik = icerik;
}
public String getdate() {
return date;
}
public void setdate(String date) {
this.date = date;
}
}
<file_sep># Dizi/Film İnceleme
## Proje Aşamaları
Proje Login sayfası ile açılmaktadır. Login sayfasında, E-Mail ve şifre ile giriş yapılabilen bir ekran bulunmaktadır. Eğer kullanıcı sisteme kayıtlı ise bu alanları dolduracak ve “LOGIN” butonuna basarak sisteme giriş yapabilecektir. Kullanıcı sisteme kayıtlı değil ise “SIGN IN” butonuna tıklayarak sisteme kayıt olabileceği ekrana yönlendirilecektir. Kullanıcı, sistemde kayıtlı olan şifresini unutması durumunda ise “Forget Password” diyerek şifre yenilemesi için gerekli maili kendisine gönderilmesini sağlayacaktır.
Sistem üzerinde admin ve kullanıcı olmak üzere iki ayrı panel bulunmaktadır. Admin, kullanıcılar için içerik ekleyip, düzenleyip, silerken kullanıcılar bu içerikleri görüntüleyebilmektedir.
## Kullanıcı Paneli Ekran Görüntüleri






## Admin Paneli Ekran Görüntüleri







<file_sep>package first;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
public class Database {
private String jdbcURL;
private String jdbcUsername;
private String jdbcPassword;
private Connection jdbcConnection;
public void start() {
this.jdbcURL = "jdbc:mysql://localhost:3306/first?useUnicode=yes&characterEncoding=UTF-8&useLegacyDatetimeCode=false&serverTimezone=Turkey";
this.jdbcUsername = "root";
this.jdbcPassword = "<PASSWORD>";
}
protected void connect() throws SQLException {
if (jdbcConnection == null || jdbcConnection.isClosed()) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new SQLException(e);
}
jdbcConnection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
}
}
protected void disconnect() throws SQLException {
if (jdbcConnection != null && !jdbcConnection.isClosed()) {
jdbcConnection.close();
}
}
public boolean insertDuyuru(duyuru duyuru) throws SQLException {
String sql = "INSERT INTO duyuru (id,Baslik, icerik, date) VALUES (?,?, ?, ?)";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, duyuru.getId());
statement.setString(2, duyuru.getBaslik());
statement.setString(3, duyuru.geticerik());
statement.setString(4, duyuru.getdate());
boolean rowInserted = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowInserted;
}
public boolean inserticerik(icerik iceriks) throws SQLException {
String sql = "INSERT INTO icerik (id,Baslik, icerik, YapimYili, Oyuncular,Tur, Kategori, Gorsel, Yazar) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?)";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, iceriks.getId());
statement.setString(2, iceriks.getBaslik());
statement.setString(3, iceriks.geticerik());
statement.setString(4, iceriks.getYapimYili());
statement.setString(5, iceriks.getOyuncular());
statement.setString(6, iceriks.getTur());
statement.setString(7, iceriks.getKategori());
statement.setString(8, iceriks.getGorsel());
statement.setString(9, iceriks.getYazar());
boolean rowInserted = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowInserted;
}
public boolean insertTur(tur tur) throws SQLException {
String sql = "INSERT INTO tur(id,TurAdi) VALUES (?,?)";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, tur.getId());
statement.setString(2, tur.getTurAdi());
boolean rowInserted = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowInserted;
}
public boolean insertKategori(kategori kategori) throws SQLException {
String sql = "INSERT INTO kategori(id,KategoriAdi) VALUES (?,?)";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, kategori.getId());
statement.setString(2, kategori.getKategoriAdi());
boolean rowInserted = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowInserted;
}
public login getkayit(String email) throws SQLException {
login user = null;
String sql = "SELECT * FROM login WHERE id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, email);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String emaili = resultSet.getString("email");
String pas = resultSet.getString("pass");
String yetki = resultSet.getString("yetki");
int id = resultSet.getInt("id");
user = new login(emaili,pas,yetki,id);
}
resultSet.close();
statement.close();
return user;
}
public login getkayit2(String email) throws SQLException {
login user = null;
String sql = "SELECT * FROM login WHERE email = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, email);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String emaili = resultSet.getString("email");
String pas = resultSet.getString("pass");
String yetki = resultSet.getString("yetki");
int id = resultSet.getInt("id");
user = new login(emaili,pas,yetki,id);
}
resultSet.close();
statement.close();
return user;
}
public boolean kayit(login log) throws SQLException {
String sql = "INSERT INTO login (email,pass,yetki) VALUES (?,?,?)";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1,log.getEmail());
statement.setString(2, log.getPass());
statement.setString(3,"0");
boolean rowInserted = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowInserted;
}
public login getlogin(String email,String pass) throws SQLException {
login user = null;
String sql = "SELECT * FROM login WHERE email = ? && pass=?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, email);
statement.setString(2, pass);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String emaili = resultSet.getString("email");
String pas = resultSet.getString("pass");
String yetki = resultSet.getString("yetki");
int id = resultSet.getInt("id");
user = new login(email,pas,yetki,id);
}
resultSet.close();
statement.close();
return user;
}
public login getmail(String email) throws SQLException {
login user = null;
String sql = "SELECT * FROM login WHERE email = ? ";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, email);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String emaili = resultSet.getString("email");
int id = resultSet.getInt("id");
user = new login(email,id);
}
resultSet.close();
statement.close();
return user;
}
public List<login> loginara(String emaila) throws SQLException {
List<login> listBook = new ArrayList<>();
String sql = "SELECT * FROM login WHERE email like ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, "%"+emaila+"%");
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String email = resultSet.getString("email");
String pass = resultSet.getString("pass");
login book = new login(id, email,pass);
listBook.add(book);
}
resultSet.close();
statement.close();
disconnect();
return listBook;
}
public List<kategori> kategoriara (String emaila) throws SQLException {
List<kategori> listBook = new ArrayList<>();
String sql = "SELECT * FROM kategori WHERE KategoriAdi like ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, "%"+emaila+"%");
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String kategoriadi = resultSet.getString("KategoriAdi");
kategori book = new kategori(id, kategoriadi);
listBook.add(book);
}
resultSet.close();
statement.close();
disconnect();
return listBook;
}
public List<duyuru> duyuruara (String emaila) throws SQLException {
List<duyuru> listBook = new ArrayList<>();
String sql = "SELECT * FROM duyuru WHERE Baslik like ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, "%"+emaila+"%");
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String Baslik = resultSet.getString("Baslik");
duyuru book = new duyuru(id, Baslik);
listBook.add(book);
}
resultSet.close();
statement.close();
disconnect();
return listBook;
}
public List<login> mailara(String emaila) throws SQLException {
List<login> listBook = new ArrayList<>();
String sql = "SELECT * FROM login WHERE email like ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, "%"+emaila+"%");
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String email = resultSet.getString("email");
String pass = resultSet.getString("pass");
login book = new login(id, email, pass);
listBook.add(book);
}
resultSet.close();
statement.close();
disconnect();
return listBook;
}
public List<icerik> icerikara(String searchin) throws SQLException{
List<icerik> listBook = new ArrayList<>();
String sql = "SELECT * FROM icerik WHERE Baslik like ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, "%"+searchin+"%");
ResultSet resultSet = statement.executeQuery();
while(resultSet.next()) {
int id = resultSet.getInt("id");
String Baslik = resultSet.getString("Baslik");
String icerik = resultSet.getString("icerik");
String YapimYili = resultSet.getString("YapimYili");
String Oyuncular = resultSet.getString("Oyuncular");
String Kategori = resultSet.getString("Kategori");
String Tur = resultSet.getString("Tur");
String Gorsel = resultSet.getString("Gorsel");
String Yazar = resultSet.getString("Yazar");
icerik book = new icerik(id, Baslik, icerik, YapimYili,Oyuncular, Kategori, Tur, Gorsel, Yazar);
listBook.add(book);
}
resultSet.close();
statement.close();
disconnect();
return listBook;
}
public List<login> listAllLogin() throws SQLException {
List<login> listBook = new ArrayList<>();
String sql = "SELECT * FROM login";
connect();
Statement statement = jdbcConnection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String email = resultSet.getString("email");
String pass = resultSet.getString("pass");
login book = new login(id, email,pass);
listBook.add(book);
}
resultSet.close();
statement.close();
disconnect();
return listBook;
}
public List<duyuru> listAllDuyurus() throws SQLException {
List<duyuru> listBook = new ArrayList<>();
String sql = "SELECT * FROM duyuru ORDER BY id DESC";
connect();
Statement statement = jdbcConnection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String Baslik = resultSet.getString("Baslik");
String icerik = resultSet.getString("icerik");
String date = resultSet.getString("date");
duyuru book = new duyuru(id, Baslik,icerik,date);
listBook.add(book);
}
resultSet.close();
statement.close();
disconnect();
return listBook;
}
public List<icerik> listAlliceriks() throws SQLException {
List<icerik> listBook = new ArrayList<>();
String sql = "SELECT * FROM icerik";
connect();
Statement statement = jdbcConnection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String Baslik = resultSet.getString("Baslik");
String icerik = resultSet.getString("icerik");
String YapimYili = resultSet.getString("YapimYili");
String Oyuncular = resultSet.getString("Oyuncular");
String Tur = resultSet.getString("Tur");
String Kategori = resultSet.getString("Kategori");
String Gorsel = resultSet.getString("Gorsel");
String Yazar = resultSet.getString("Yazar");
icerik book = new icerik(id,Baslik,icerik,YapimYili, Oyuncular,Tur,Kategori,Gorsel,Yazar);
listBook.add(book);
}
resultSet.close();
statement.close();
disconnect();
return listBook;
}
public List<icerik> listAlliceriksFilm() throws SQLException {
List<icerik> listBook = new ArrayList<>();
String sql = "SELECT * FROM icerik WHERE Kategori='Film' ORDER BY id DESC";
connect();
Statement statement = jdbcConnection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String Baslik = resultSet.getString("Baslik");
String icerik = resultSet.getString("icerik");
String YapimYili = resultSet.getString("YapimYili");
String Oyuncular = resultSet.getString("Oyuncular");
String Tur = resultSet.getString("Tur");
String Kategori = resultSet.getString("Kategori");
String Gorsel = resultSet.getString("Gorsel");
String Yazar = resultSet.getString("Yazar");
icerik book = new icerik(id,Baslik,icerik,YapimYili, Oyuncular,Tur,Kategori,Gorsel,Yazar);
listBook.add(book);
}
resultSet.close();
statement.close();
disconnect();
return listBook;
}
public List<icerik> listAlliceriksDizi() throws SQLException {
List<icerik> listBook = new ArrayList<>();
String sql = "SELECT * FROM icerik WHERE Kategori='Dizi' ORDER BY id DESC ";
connect();
Statement statement = jdbcConnection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String Baslik = resultSet.getString("Baslik");
String icerik = resultSet.getString("icerik");
String YapimYili = resultSet.getString("YapimYili");
String Oyuncular = resultSet.getString("Oyuncular");
String Tur = resultSet.getString("Tur");
String Kategori = resultSet.getString("Kategori");
String Gorsel = resultSet.getString("Gorsel");
String Yazar = resultSet.getString("Yazar");
icerik book = new icerik(id,Baslik,icerik,YapimYili, Oyuncular,Tur,Kategori,Gorsel,Yazar);
listBook.add(book);
}
resultSet.close();
statement.close();
disconnect();
return listBook;
}
public List<tur> listAllTurs() throws SQLException {
List<tur> listBook = new ArrayList<>();
String sql = "SELECT * FROM tur";
connect();
Statement statement = jdbcConnection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String TurAdi = resultSet.getString("TurAdi");
tur book = new tur(id, TurAdi);
listBook.add(book);
}
resultSet.close();
statement.close();
disconnect();
return listBook;
}
public List<kategori> listAllKategoris() throws SQLException {
List<kategori> listBook = new ArrayList<>();
String sql = "SELECT * FROM kategori";
connect();
Statement statement = jdbcConnection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String KategoriAdi = resultSet.getString("KategoriAdi");
kategori book = new kategori(id, KategoriAdi);
listBook.add(book);
}
resultSet.close();
statement.close();
disconnect();
return listBook;
}
public boolean deleteUser(login user) throws SQLException {
String sql = "DELETE FROM login where id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, user.getId());
boolean rowDeleted = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowDeleted;
}
public boolean deleteduyuru(duyuru duyuru) throws SQLException {
String sql = "DELETE FROM duyuru where id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, duyuru.getId());
boolean rowDeleted = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowDeleted;
}
public boolean deleteicerik(icerik icerik) throws SQLException {
String sql = "DELETE FROM icerik where id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, icerik.getId());
boolean rowDeleted = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowDeleted;
}
public boolean deleteTur(tur tur) throws SQLException {
String sql = "DELETE FROM tur where id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, tur.getId());
boolean rowDeleted = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowDeleted;
}
public boolean deleteKategori(kategori kategori) throws SQLException {
String sql = "DELETE FROM kategori where id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, kategori.getId());
boolean rowDeleted = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowDeleted;
}
public boolean updateUser(login user) throws SQLException {
String sql = "UPDATE login SET email = ?, pass = ?";
sql += " WHERE id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, user.getEmail());
statement.setString(2, user.getPass());
statement.setInt(3, user.getId());
boolean rowUpdated = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowUpdated;
}
public boolean updateduyuru(duyuru duyuru) throws SQLException {
String sql = "UPDATE duyuru SET Baslik = ?, icerik = ?";
sql += " WHERE id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, duyuru.getBaslik());
statement.setString(2, duyuru.geticerik());
statement.setInt(3, duyuru.getId());
boolean rowUpdated = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowUpdated;
}
public boolean updateTur(tur tur) throws SQLException {
String sql = "UPDATE tur SET TurAdi = ?";
sql += " WHERE id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, tur.getTurAdi());
statement.setInt(2, tur.getId());
boolean rowUpdated = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowUpdated;
}
public boolean updateicerik(icerik icerik) throws SQLException {
String sql = "UPDATE icerik SET Baslik = ?, icerik = ?, YapimYili = ?, Oyuncular = ?, Tur = ?, Kategori = ?, Gorsel = ?, Yazar = ?";
sql += " WHERE id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, icerik.getBaslik());
statement.setString(2, icerik.geticerik());
statement.setString(3, icerik.getYapimYili());
statement.setString(4, icerik.getOyuncular());
statement.setString(5, icerik.getTur());
statement.setString(6, icerik.getKategori());
statement.setString(7, icerik.getGorsel());
statement.setString(8, icerik.getYazar());
statement.setInt(9, icerik.getId());
boolean rowUpdated = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowUpdated;
}
public boolean updateKategori(kategori kategori) throws SQLException {
String sql = "UPDATE kategori SET KategoriAdi = ?";
sql += " WHERE id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, kategori.getKategoriAdi());
statement.setInt(2, kategori.getId());
boolean rowUpdated = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowUpdated;
}
public login getUser(int id) throws SQLException {
login user = null;
String sql = "SELECT * FROM login WHERE id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String email = resultSet.getString("email");
String pass = resultSet.getString("pass");
user = new login(id,email, pass);
}
resultSet.close();
statement.close();
return user;
}
public duyuru getduyuru(int id) throws SQLException {
duyuru duyuru = null;
String sql = "SELECT * FROM duyuru WHERE id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String Baslik = resultSet.getString("Baslik");
String icerik = resultSet.getString("icerik");
duyuru = new duyuru(id,Baslik, icerik);
}
resultSet.close();
statement.close();
return duyuru;
}
public icerik geticerik(int id) throws SQLException {
icerik iceriks = null;
String sql = "SELECT * FROM icerik WHERE id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String Baslik = resultSet.getString("Baslik");
String icerik = resultSet.getString("icerik");
String YapimYili = resultSet.getString("YapimYili");
String Oyuncular = resultSet.getString("Oyuncular");
String Tur = resultSet.getString("Tur");
String Kategori = resultSet.getString("Kategori");
String Gorsel = resultSet.getString("Gorsel");
String Yazar = resultSet.getString("Yazar");
iceriks = new icerik(id,Baslik,icerik,YapimYili, Oyuncular,Tur,Kategori,Gorsel,Yazar);
}
resultSet.close();
statement.close();
return iceriks;
}
public tur getTur(int id) throws SQLException {
tur tur = null;
String sql = "SELECT * FROM tur WHERE id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String TurAdi = resultSet.getString("TurAdi");
tur = new tur(id, TurAdi);
}
resultSet.close();
statement.close();
return tur;
}
public kategori getKategori(int id) throws SQLException {
kategori kategori = null;
String sql = "SELECT * FROM kategori WHERE id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String KategoriAdi = resultSet.getString("KategoriAdi");
kategori = new kategori(id, KategoriAdi);
}
resultSet.close();
statement.close();
return kategori;
}
public List<login> sifredegistir(String emaila) throws SQLException {
List<login> listBook = new ArrayList<>();
String sql = "SELECT * FROM login WHERE email=?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, emaila);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
String email = resultSet.getString("email");
String pas = resultSet.getString("pass");
String yetki = resultSet.getString("yetki");
int id = resultSet.getInt("id");
login book = new first.login(email,pas,yetki,id);
listBook.add(book);
}
resultSet.close();
statement.close();
disconnect();
return listBook;
}
public boolean updatesifrek(login user) throws SQLException {
String sql = "UPDATE login SET pass=?";
sql += " WHERE id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, user.getPass());
statement.setInt(2, user.getId());
boolean rowUpdated = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowUpdated;
}
public login yetkibak(String email) throws SQLException {
login user = null;
String sql = "SELECT * FROM login WHERE email = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, email);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String emaili = resultSet.getString("email");
String pas = resultSet.getString("pass");
String yetki = resultSet.getString("yetki");
int id = resultSet.getInt("id");
user = new first.login(emaili,pas,yetki,id);
}
resultSet.close();
statement.close();
return user;
}
public boolean yetkiupdate(login user) throws SQLException {
System.out.print(user.getId());
String sql = "UPDATE login SET yetki = ?";
sql += " WHERE id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, "1");
statement.setInt(2, user.getId());
boolean rowUpdated = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowUpdated;
}
public boolean yetkiupdate1(login user) throws SQLException {
System.out.print(user.getId());
String sql = "UPDATE login SET yetki = ?";
sql += " WHERE id = ?";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setString(1, "0");
statement.setInt(2, user.getId());
boolean rowUpdated = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowUpdated;
}
public List<login> yetkilist() throws SQLException {
List<login> listBook = new ArrayList<>();
String sql = "SELECT * FROM login";
connect();
Statement statement = jdbcConnection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
String email = resultSet.getString("email");
String pas = resultSet.getString("pass");
String yetki = resultSet.getString("yetki");
int id = resultSet.getInt("id");
login book = new first.login(email,pas,yetki,id);
listBook.add(book);
}
resultSet.close();
statement.close();
disconnect();
return listBook;
}
}
<file_sep>package first;
public class tur {
protected int id;
protected String TurAdi;
public tur() {
}
public tur(int id) {
this.id = id;
}
public tur(int id, String TurAdi) {
// TODO Auto-generated constructor stub
this.id=id;
this.TurAdi=TurAdi;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTurAdi() {
return TurAdi;
}
public void setTurAdi(String TurAdi) {
this.TurAdi = TurAdi;
}
}
<file_sep>package first;
public class kategori {
protected int id;
protected String KategoriAdi;
public kategori() {
}
public kategori(int id) {
this.id = id;
}
public kategori(int id, String KategoriAdi) {
// TODO Auto-generated constructor stub
this.id=id;
this.KategoriAdi=KategoriAdi;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getKategoriAdi() {
return KategoriAdi;
}
public void setKategoriAdi(String KategoriAdi) {
this.KategoriAdi = KategoriAdi;
}
}
<file_sep>package first;
public class login {
protected String email,pass,yetki;
protected int id;
public login() {
}
public login(String email, String pass,String yetki,int id) {
this.email = email;
this.pass = pass;
this.yetki=yetki;
this.id=id;
}
public login(String email, int id) {
this.email=email;
this.id=id;
}
public login(int id, String email,String pass ) {
this.email=email;
this.id=id;
this.pass=pass;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getyetki() {
return yetki;
}
public void setyetki(String yetki) {
this.yetki = yetki;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
|
08db53bfce0fd9e07d52b2d67fd6e43734264f39
|
[
"Markdown",
"Java"
] | 6
|
Java
|
GamzeeBabayigit/DiziFilmInceleme
|
15268ce2629ed1aa3b7aec0c7c209637e6de0eb3
|
caf3bdc79e8538c09d25bd0bd545fe7b3badbf67
|
refs/heads/master
|
<file_sep><?php
use frontend\assets\AppAsset;
use yii\bootstrap\Nav;
use yii\helpers\Html;
use yii\web\User;
AppAsset::register($this); ?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport"/>
<title>
ITSTUDIOBLOG - The knowledge about information technology and programming.
</title>
<link type="image/png" rel="icon" href="<?= Yii::$app->homeUrl ?>images/favicon.png"/>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<header class="blue-grey lighten-1">
<div class="container position-relative">
<div class="single-logo">
<a href="index-2.html">
<img alt="logo" src="<?= Yii::$app->homeUrl ?>images/logo.png"/>
</a>
<h6 class="white-text">
<em>
where sharing knowledge of information technology and programming.
</em>
</h6>
</div>
<div class="menu-icon">
<a class="white-text" data-activates="nav-mobile" href="#">
<i class="mdi-navigation-menu">
</i>
</a>
</div>
<nav class="menu-with-button">
<ul id="nav-mobile" class="side-nav" style="left: -250px;">
<?php if (Yii::$app->controller->id == 'java'):?>
<li class="active">
<?= Html::a('Java', ['/java/']) ?>
</li>
<?php else: ?>
<li>
<?= Html::a('Java', ['/java']) ?>
</li>
<?php endif ?>
<?php if (Yii::$app->controller->id == 'android'):?>
<li class="active">
<?= Html::a('Android', ['/android/']) ?>
</li>
<?php else: ?>
<li>
<?= Html::a('Android', ['/android/']) ?>
</li>
<?php endif ?>
<?php if (Yii::$app->controller->id == 'php'):?>
<li class="active">
<?= Html::a('PHP', ['/php/']) ?>
</li>
<?php else: ?>
<li>
<?= Html::a('PHP', ['/php/']) ?>
</li>
<?php endif ?>
<?php if (Yii::$app->controller->id == 'yii'):?>
<li class="active">
<?= Html::a('Yii', ['/yii/']) ?>
</li>
<?php else: ?>
<li>
<?= Html::a('Yii', ['/yii/']) ?>
</li>
<?php endif ?>
<?php if (Yii::$app->controller->id == 'document'):?>
<li class="active">
<?= Html::a('Document', ['/document/']) ?>
</li>
<?php else: ?>
<li>
<?= Html::a('Document', ['/document/']) ?>
</li>
<?php endif ?>
<?php if (Yii::$app->controller->id == 'contact'):?>
<li class="active">
<?= Html::a('Contact', ['/contact/']) ?>
</li>
<?php else: ?>
<li>
<?= Html::a('Contact', ['/contact/']) ?>
</li>
<?php endif ?>
<?php if(Yii::$app->user->getIsGuest()): ?>
<?php if (Yii::$app->controller->id == 'login'):?>
<li class="active">
<?= Html::a('Login', ['/login/']) ?>
</li>
<?php else: ?>
<li>
<?= Html::a('Login', ['/login/']) ?>
</li>
<?php endif ?>
<?php endif ?>
</ul>
</nav>
</div>
</header>
<div class="main-content">
<div class="container">
<ul class="categories-list">
<?php if (Yii::$app->controller->id == 'java'):?>
<li>
<?= Html::a('Java', ['/java/'], ['class' => 'active']) ?>
</li>
<?php else: ?>
<li>
<?= Html::a('Java', ['/java']) ?>
</li>
<?php endif ?>
<?php if (Yii::$app->controller->id == 'android'):?>
<li>
<?= Html::a('Android', ['/android/'], ['class' => 'active']) ?>
</li>
<?php else: ?>
<li>
<?= Html::a('Android', ['/android/']) ?>
</li>
<?php endif ?>
<?php if (Yii::$app->controller->id == 'php'):?>
<li>
<?= Html::a('PHP', ['/php/'], ['class' => 'active']) ?>
</li>
<?php else: ?>
<li>
<?= Html::a('PHP', ['/php/']) ?>
</li>
<?php endif ?>
<?php if (Yii::$app->controller->id == 'yii'):?>
<li>
<?= Html::a('Yii', ['/yii/'], ['class' => 'active']) ?>
</li>
<?php else: ?>
<li>
<?= Html::a('Yii', ['/yii/']) ?>
</li>
<?php endif ?>
<?php if (Yii::$app->controller->id == 'document'):?>
<li>
<?= Html::a('Document', ['/document/'], ['class' => 'active']) ?>
</li>
<?php else: ?>
<li>
<?= Html::a('Document', ['/document/']) ?>
</li>
<?php endif ?>
</ul>
<?= $content ?>
</div>
</div>
<div class="contacts blue-grey lighten-4 center">
<div class="container">
<div class="row">
<div class="col s12 m4">
<a target="_blank" href="http://facebook.com">
FACEBOOK
</a>
</div>
<div class="col s12 m4 margin-top-s-16">
<a target="_blank" href="http://plus.google.com">
GOOGLE PLUS
</a>
</div>
<div class="col s12 m4 margin-top-s-16">
<a target="_blank" href="http://pinterest.com">
YOUTUBE
</a>
</div>
</div>
<div class="row margin-top-32">
<form class="col s10 offset-s1 m8 offset-m2" method="post">
<div class="row">
<div class="input-field col s12">
<input id="newsletter-email" class="validate" type="email"/>
<label for="newsletter-email">
Subscribe to the newsletter
</label>
</div>
</div>
</form>
</div>
</div>
</div>
<footer class="white center">
<div class="container">
<div class="row">
<div class="col s12">
<p>
Develope by
<?= Html::a('LINQ', ['/about/']) ?>
</p>
</div>
</div>
<a class="back-to-top btn-floating btn-large waves-effect waves-light blue-grey darken-1" href="#header"><i class="mdi-navigation-expand-less"></i></a>
</div>
</footer>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
<file_sep><div class="row">
<div class="col s12 m5 l4">
<img class="responsive-img" src="<?= Yii::$app->homeUrl ?>images/about.jpg" alt="Self portrait">
<ul class="icon-list">
<li>
<i class="small mdi-communication-call blue-grey-text text-darken-1"></i>
<span>+351 912 345 968</span>
</li>
<li>
<i class="small mdi-communication-email blue-grey-text text-darken-1"></i>
<span><a href="mailto:<EMAIL>"><EMAIL></a></span>
</li>
<li>
<i class="small mdi-maps-place blue-grey-text text-darken-1"></i>
<span>Braga, Portugal</span>
</li>
<li>
<i class="small mdi-social-people-outline blue-grey-text text-darken-1"></i>
<span><a href="http://facebook.com" target="_blank">facebook</a></span>
</li>
<li>
<i class="small mdi-social-people-outline blue-grey-text text-darken-1"></i>
<span><a href="http://twitter.com" target="_blank">twitter</a></span>
</li>
</ul>
</div>
<div class="col s12 m7 l8 margin-top-s-32">
<ul class="tabs">
<li class="tab col s4">
<a class="active" href="#whoami">WHO AM I</a>
</li>
<li class="tab col s4">
<a href="#work">WORK</a>
</li>
<li class="tab col s4">
<a href="#hobbies">HOBBIES</a>
</li>
</ul>
<div id="whoami" class="col s12 margin-bottom-32">
<blockquote>
"Start by doing what's necessary; then do what's possible; and suddenly you are doing the impossible."<br>
<b>- <NAME></b>
</blockquote>
<h6><b>BUT WHO AM I?</b></h6>
<p>My name is Gertrudes and I love to write Web related stuff. Lorem ipsum dolor sit amet, consectetur adipisicing elit.Voluptatem nesciunt veniam mollitia sunt quidem ullam sequi modi hic magnam voluptate inventore, ratione.</p>
<p>I've also had an amazing year:</p>
<div class="row horizontal-panels">
<div class="col s12 l4 center">
<i class="mdi-content-create"></i>
<h6><b>50 ARTICLES</b></h6>
</div>
<div class="col s12 l4 center">
<i class="mdi-hardware-keyboard-voice"></i>
<h6><b>23 PODCASTS</b></h6>
</div>
<div class="col s12 l4 center">
<i class="mdi-action-grade"></i>
<h6><b>3 AWARDS</b></h6>
</div>
</div>
<p>As you can see I've been busy this year, but I'd love to get a message from you, so please contact me using the form bellow.</p>
</div>
<div id="work" class="col s12 margin-bottom-32">
<p>I've worked in a lot of things but the most interesting area was without a doubt Web Design. Nam quis venenatis nisl. Etiam suscipit, odio in dictum semper, nunc nisl laoreet quam, nec imperdiet neque nunc a nunc.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quaerat blanditiis ullam, impedit, tempore corporis officia quae! Enim, rerum autem voluptatum tempore quisquam facilis impedit laborum, excepturi ullam unde, voluptatibus quasi!</p>
<p>I've also received tons of awards:</p>
<ul class="icon-list">
<li>
<i class="mdi-social-school small blue-grey-text text-darken-1"></i>
<span><b>(2014)</b> Most views on a single post</span>
</li>
<li>
<i class="mdi-social-school small blue-grey-text text-darken-1"></i>
<span><b>(2014)</b> Best UI/UX Blog Template</span>
</li>
<li>
<i class="mdi-social-school small blue-grey-text text-darken-1"></i>
<span><b>(2013)</b> Best Blog</span>
</li>
</ul>
</div>
<div id="hobbies" class="col s12 margin-bottom-32">
<p>Apart from the web business and pation that I have, I also do other things. I love to spend time with my family, but that is not a hobby, so, more on my hobbies down bellow.</p>
<p>This is what I'm up to when I'm not working:</p>
<div class="row vertical-panels">
<div class="col s12">
<i class="mdi-device-airplanemode-on"></i>
<h6><b>TRAVELING</b></h6>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. At esse necessitatibus exercitationem provident possimus totam nemo.</p>
</div>
<div class="col s12">
<i class="mdi-image-camera"></i>
<h6><b>PHOTOGRAPHY</b></h6>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. At esse necessitatibus exercitationem provident possimus totam nemo.</p>
</div>
<div class="col s12">
<i class="mdi-hardware-headset"></i>
<h6><b>MUSIC</b></h6>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. At esse necessitatibus exercitationem provident possimus totam nemo.</p>
</div>
</div>
</div>
</div>
</div>
<div class="row center margin-top-32">
<div class="col s12">
<div class="white padding-32">
<p>If you are interested in me you can download my resume</p>
<a class="btn waves-effect waves-light blue-grey darken-1 white-text" href="#">Download my Resume</a>
</div>
</div>
</div>
<div class="row margin-top-64">
<div class="col s12">
<h3>Contact me</h3>
<form id="theme-contact" method="post" role="form" action="mail.php">
<div class="row">
<div class="input-field col s6">
<input id="contact-first-name" name="contact-first-name" type="text" class="validate" required>
<label for="contact-first-name">First Name</label>
</div>
<div class="input-field col s6">
<input id="contact-last-name" name="contact-last-name" type="text" class="validate" required>
<label for="contact-last-name">Last Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="contact-email" name="contact-email" type="email" class="validate" required>
<label for="contact-email">Email</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="contact-subject" name="contact-subject" type="text" class="validate" required>
<label for="contact-subject">Subject</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<textarea id="contact-message" name="contact-message" class="materialize-textarea" required></textarea>
<label for="contact-message">Message</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<button class="btn waves-effect waves-light blue-grey darken-1" type="submit" name="action">Submit</button>
</div>
</div>
</form>
<div id="theme-form-messages"></div>
</div>
</div><file_sep><?php
namespace common\models;
use common\models\Category;
use Yii;
/**
* This is the model class for table "Post".
*
* @property integer $id
* @property string $title
* @property string $thumb
* @property integer $category
* @property string $date
* @property integer $view
* @property string $content
*
* @property Comment $comment
*/
class Post extends \yii\db\ActiveRecord
{
public $thumbFile;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'Post';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title', 'content', 'category'], 'required', 'message' => 'Please fill in!'],
[['thumbFile'], 'file', 'extensions' => 'jpg, gif, png'],
[['content'], 'string'],
[['title'], 'string', 'max' => 200],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Title',
'thumb' => 'Thumb',
'category' => 'Category',
'date' => 'Date',
'view' => 'View',
'content' => 'Content',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getComment()
{
return $this->hasOne(Comment::className(), ['id' => 'id']);
}
//Relationship with Category.
public function getCategory0(){
return $this->hasOne(Category::className(), ['category' => 'id']);
}
}
<file_sep><div class="row">
<div class="col s12">
<img class="responsive-img full-width-img" src="<?= yii::$app->homeUrl ?>images/library.jpg" alt="library">
<h1 class="post-title">How to be successful on the web</h1>
<span class="post-date">23 Fev. 2015</span>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sodales lobortis nunc. Duis aliquam lacus eu dui facilisis molestie. Donec in massa ac mi venenatis volutpat. Nunc vitae finibus velit, sit amet aliquam nisl. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in eleifend nisl, sed sodales sem. Donec eget justo lobortis, scelerisque nunc vel, elementum nisl. In iaculis sem dolor, sed blandit dolor placerat at. Donec condimentum est a posuere vulputate.</p>
<ul class="icon-list-small">
<li>
<i class="mdi-action-done blue-grey-text text-darken-1"></i>
<span>item number 1</span>
</li>
<li>
<i class="mdi-action-done blue-grey-text text-darken-1"></i>
<span>item number 2</span>
</li>
<li>
<i class="mdi-action-done blue-grey-text text-darken-1"></i>
<span>item number 3</span>
</li>
</ul>
<p>Vivamus imperdiet erat et feugiat pulvinar. Phasellus vel purus egestas, molestie sem a, venenatis nulla. In cursus nisi elit, ac mollis justo malesuada non. Nulla felis justo, tempus vel dignissim eu, finibus id felis. Proin lectus sapien, tempus ut finibus ornare, congue ut risus. Proin lacinia vitae nibh ac mattis. Ut posuere neque et arcu gravida tristique. Cras fermentum, magna et pellentesque porta, velit tellus cursus felis, sit amet cursus elit arcu sit amet risus.</p>
<blockquote>
"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae error, tempora. Repudiandae consequuntur nostrum eaque commodi obcaecati, voluptatem neque dolores dolore id. Rerum deserunt nisi sed, odit, provident quibusdam cum."
</blockquote>
<p>Aenean sed massa odio. Sed ac ligula ut velit elementum finibus. Fusce vitae justo ac diam ullamcorper ultrices a ut libero. Nulla sed vestibulum tortor. Sed aliquet lorem at magna fermentum efficitur. Donec condimentum nunc sed nisi imperdiet blandit. Duis metus ipsum, lacinia id dolor a, porttitor aliquet mauris. Donec sit amet accumsan augue</p>
<h5>Another heading</h5>
<p>Iaculis rutrum ex. Phasellus pulvinar, sapien eu lacinia egestas, tellus odio suscipit quam, id dictum lectus diam a augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed a augue fringilla, pulvinar enim id, fringilla elit. Curabitur ex lectus, eleifend at rutrum non, tincidunt ut ante. Sed finibus facilisis ipsum non efficitur. Praesent varius mi mauris, ut rutrum eros euismod quis. Praesent malesuada commodo egestas. Fusce non volutpat elit, at rutrum nisl.</p>
</div>
<div class="col s12 margin-top-32">
<div class="post-info">
<span>
<i class="mdi-action-favorite red-text text-lighten-1"></i>
<a href="#">3</a>
</span>
<span>
<i class="mdi-social-share"></i>
<a href="#">Facebook</a>
<a href="#">Google Plus</a>
<a href="#">Twitter</a>
</span>
</div>
</div>
<div class="col s12 comments">
<h3>Comments</h3>
<form id="theme-comment" method="post" role="form">
<div class="row">
<div class="input-field col s6">
<input id="comment-first-name" name="comment-first-name" type="text" class="validate" required>
<label for="comment-first-name">First Name</label>
</div>
<div class="input-field col s6">
<input id="comment-last-name" name="comment-last-name" type="text" class="validate" required>
<label for="comment-last-name">Last Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="comment-email" name="comment-email" type="email" class="validate" required>
<label for="comment-email">Email</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<textarea id="comment-message" name="comment-message" class="materialize-textarea" required></textarea>
<label for="comment-message">Message</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<button class="btn waves-effect waves-light blue-grey darken-1" type="submit" name="action">Submit</button>
</div>
</div>
</form>
<div class="card-panel grey lighten-5 z-depth-1">
<div class="row">
<div class="col s3 m2 l1">
<img src="<?= yii::$app->homeUrl ?>images/user1.jpg" alt="" class="circle responsive-img">
</div>
<div class="col s8 m10 l11">
<h6 class="comment-name"><b><NAME></b></h6>
<span class="comment-date">25 Fev. 2015</span>
<p>I think this is an excellent article. The ideas behind it are concise and steps to achieve the success are completely true. Great article!</p>
</div>
</div>
</div>
<div class="card-panel grey lighten-5 z-depth-1">
<div class="row">
<div class="col s3 m2 l1">
<img src="<?= yii::$app->homeUrl ?>images/user2.jpg" alt="" class="circle responsive-img">
</div>
<div class="col s8 m10 l11">
<h6 class="comment-name"><b><NAME></b></h6>
<span class="comment-date">24 Fev. 2015</span>
<p>What an amazing article. I just wished this article was written a few months ago. It would've been very helpful for me.</p>
</div>
</div>
</div>
</div>
</div><file_sep><?php
namespace frontend\controllers;
use yii\web\Controller;
use common\models\Post;
class JavaController extends Controller
{
//Showing index.
public function actionIndex()
{
$model = new Post();
$posts = $model->find()->all();
$featurePost = $model->find()->orderBy(['view' => SORT_DESC])->one();
return $this->render('index', ['posts' => $posts, 'featurePost' => $featurePost]);
}
//Showing Post
public function actionPost($id){
return $this->render('post');
}
}
<file_sep><?php
use yii\helpers\Html;
?>
<div class="row">
<div class="col s12">
<div class="flat-card">
<img class="responsive-img full-width-img" alt="library" src="<?= Yii::$app->homeUrl . $featurePost['thumb']?>" />
<div class="flat-card-content">
<h4 class="card-title">
<?= $featurePost['title'] ?>
</h4>
<p>
<?= substr($featurePost['content'], 0, 100) ?>
</p>
</div>
<div class="flat-card-links">
<span>
<i class="mdi-image-remove-red-eye red-text text-lighten-1"></i>
<?= $featurePost['view'] ?>
</span>
<span>
<i class="mdi-editor-mode-edit brown-text text-lighten-1"></i>
<?php $postDate = $featurePost['date']?>
<?= date('d M, Y', strtotime($postDate)) ?>
</span>
<?= Html::a('READ MORE', ['/java/post/' . $featurePost['id']]) ?>
</div>
</div>
</div>
<div class="clearfix">
</div>
<?php foreach ($posts as $post):?>
<!--Post-item-->
<div class="col s12 m6 margin-top-32">
<div class="flat-card">
<img class="responsive-img full-width-img" alt="color pencils" src="<?= Yii::$app->homeUrl . $post['thumb']?>" />
<div class="flat-card-content">
<h4 class="card-title"><?= $post['title'] ?></h4>
<p>
<?= substr($post['content'], 0, 100) ?>
</p>
</div>
<div class="flat-card-links">
<span>
<i class="mdi-action-favorite red-text text-lighten-1"></i>
<?= $post['view'] ?>
</span>
<span>
<i class="mdi-editor-mode-edit brown-text text-lighten-1"></i>
<?php $postDate = $post['date']?>
<?= date('d M, Y', strtotime($postDate)) ?>
</span>
<?= Html::a('READ MORE', ['/java/post/' . $post['id']]) ?>
</div>
</div>
</div>
<!--./Post-item-->
<?php endforeach; ?>
</div>
<div class="row">
<div class="col s12">
<ul class="pagination">
<li class="disabled">
<a href="#">
<i class="mdi-navigation-chevron-left"></i>
</a>
</li>
<li class="active">
<a href="#">1</a>
</li>
<li>
<a href="#">2</a>
</li>
<li>
<a href="#">3</a>
</li>
<li>
<a href="#">
<i class="mdi-navigation-chevron-right"></i>
</a>
</li>
</ul>
</div>
</div>
|
f29dd730f50649b9b41915b7005a2e96857afa68
|
[
"PHP"
] | 6
|
PHP
|
roanvanbao/itstudio
|
a8b35224d0f36d33763582ae3c5aabacd556bbd8
|
d128b6b2adbda6743ff44e46bbc30b64dcb3e418
|
refs/heads/master
|
<repo_name>pulkitaggarwl/aml-deploy<file_sep>/code/entrypoint.sh
#!/bin/sh
set -e
ls -la code
python /code/main.py
|
837f65459d16ab0b47be9201a5757419401fd517
|
[
"Shell"
] | 1
|
Shell
|
pulkitaggarwl/aml-deploy
|
64a209a354e2e687592a05eccb0dec7fb3c5301c
|
8cb8aba4d9a6e9ea091146aa1f3c086f89ae2449
|
refs/heads/master
|
<file_sep>package sg.edu.nus.se26pt03.photolearn.DAL;
import java.util.Date;
/**
* Created by <NAME> on 3/10/2018.
* Restructured by MyatMin on 12/3/2018.
*/
public class LearningSessionDAO extends BaseDAO {
private Date CourseDate;
private String CourseName;
private String CourseCode;
private int ModuleNumber;
private String CreatedBy;
private Date Timestamp;
public Date getCourseDate() {
return CourseDate;
}
public void setCourseDate(Date courseDate) {
CourseDate = courseDate;
}
public String getCourseName() {
return CourseName;
}
public void setCourseName(String courseName) {
CourseName = courseName;
}
public String getCourseCode() {
return CourseCode;
}
public void setCourseCode(String courseCode) {
CourseCode = courseCode;
}
public int getModuleNumber() {
return ModuleNumber;
}
public void setModuleNumber(int moduleNumber) {
ModuleNumber = moduleNumber;
}
public String getCreatedBy() {
return CreatedBy;
}
public void setCreatedBy(String createdBy) {
CreatedBy = createdBy;
}
public Date getTimestamp() {
return Timestamp;
}
public void setTimestamp(Date timestamp) {
Timestamp = timestamp;
}
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.application;
public enum Action {
CREATED,
SELECTED,
EDITED,
DELETED
}<file_sep>package sg.edu.nus.se26pt03.photolearn.DAL;
import com.google.firebase.database.Exclude;
/**
* Created by MyatMin on 12/3/18.
*/
public class BaseDAO {
protected String Id;
@Exclude
public String getId() {
return Id;
}
@Exclude
public void setId(String id) {
Id = id;
}
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.application;
/**
* Created by <NAME> on 3/10/2018.
*/
public enum UserMode {
TRAINER,
PARTICIPENT
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.BAL;
import java.util.Date;
/**
* Created by <NAME> on 7/3/2018.
*/
public class LearningItem extends Item {
private String GPS;
public void playAudio() {
//read content
}
public void displayPhoto(){
}
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.database;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import sg.edu.nus.se26pt03.photolearn.DAL.QuizTitleDAO;
import sg.edu.nus.se26pt03.photolearn.utility.ConstHelper;
/**
* Created by yijie on 2018/3/11.
* Restructured by MyatMin on 3/12/2018.
*/
public class QuizTitleRepo extends BaseRepo<QuizTitleDAO> {
public QuizTitleRepo() {
super(QuizTitleDAO.class);
mDatabaseRef = mDatabaseRef.child(ConstHelper.REF_QUIZ_TITLES);
}
public Collection<QuizTitleDAO> getAllByLearningSessionID(final String learningSessionID) {
final List<QuizTitleDAO> result = new ArrayList<>();
mDatabaseRef.addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//use the onDataChange() method to read a static snapshot of the contents at a given path
// Get Post object and use the values to update the UI
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
QuizTitleDAO quizTitleDAO = getValue(childDataSnapshot);
if (quizTitleDAO.getLearningSessionId().equals(learningSessionID)) {
result.add(quizTitleDAO);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
}
});
return result;
}
public Collection<QuizTitleDAO> getAllByCreator(final String uid) {
final List<QuizTitleDAO> result = new ArrayList<>();
mDatabaseRef.addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//use the onDataChange() method to read a static snapshot of the contents at a given path
// Get Post object and use the values to update the UI
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
QuizTitleDAO quizTitleDAO = getValue(childDataSnapshot);
if (quizTitleDAO.getCreatedBy().equals(uid)) {
result.add(quizTitleDAO);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
}
});
return result;
}
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.BAL;
import java.util.Date;
/**
* Created by <NAME> on 3/10/2018.
*/
public class Item {
private int id;
private int titleId;
private String photoURL;
private String content;
private int createdBy;
private Date timestamp;
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.DAL;
import java.util.Date;
/**
* Created by <NAME> on 3/10/2018.
* Restructured by MyatMin on 12/3/2018.
*/
public class LearningItemDAO extends BaseDAO {
private String LearningTitleId;
private String PhotoURL;
private String Content;
private String Latitude;
private String Longitude;
private String CreatedBy;
private Date Timestamp;
public String getLearningTitleId() {
return LearningTitleId;
}
public void setLearningTitleId(String learningTitleId) {
LearningTitleId = learningTitleId;
}
public String getPhotoURL() {
return PhotoURL;
}
public void setPhotoURL(String photoURL) {
PhotoURL = photoURL;
}
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
public String getLatitude() {
return Latitude;
}
public void setLatitude(String latitude) {
Latitude = latitude;
}
public String getLongitude() {
return Longitude;
}
public void setLongitude(String longitude) {
Longitude = longitude;
}
public String getCreatedBy() {
return CreatedBy;
}
public void setCreatedBy(String createdBy) {
CreatedBy = createdBy;
}
public Date getTimestamp() {
return Timestamp;
}
public void setTimestamp(Date timestamp) {
Timestamp = timestamp;
}
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.BAL;
import java.util.Date;
/**
* Created by <NAME> on 7/3/2018.
*/
public class User {
private int id;
private String loginId;
private String loginSource;
private Date lastLoginDate;
private Date timestamp;
public void SignIn() {
}
public void SingOut() {
}
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.DAL;
import java.util.Date;
/**
* Created by <NAME> on 3/10/2018.
* Restructured by MyatMin on 12/3/2018.
*/
public class UserDAO extends BaseDAO {
private String LoginId;
private String LoginSource;
private Date LastLoginDate;
private Date Timestamp;
public String getLoginId() {
return LoginId;
}
public void setLoginId(String loginId) {
LoginId = loginId;
}
public String getLoginSource() {
return LoginSource;
}
public void setLoginSource(String loginSource) {
LoginSource = loginSource;
}
public Date getLastLoginDate() {
return LastLoginDate;
}
public void setLastLoginDate(Date lastLoginDate) {
LastLoginDate = lastLoginDate;
}
public Date getTimestamp() {
return Timestamp;
}
public void setTimestamp(Date timestamp) {
Timestamp = timestamp;
}
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.application;
import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
/**
* Created by MyatMin on 10/3/18.
*/
public class AppFragment extends Fragment {
public AppEventListener mAppEventListener;
public LearningEventListener mLearningEventListener;
public interface AppEventListener {
void onModeChanged(UserMode userMode, AccessMode accessMode);
void onLoggedIn();
}
public interface LearningEventListener {
void onLearningSessionReaction(Action action);
void onLearningTitleReaction(Action action);
void onLearningItemReaction(Action action);
void onQuizTitleReaction(Action action);
void onQuizItemReaction(Action action);
void onQuizAnswerReaction(Action action);
}
protected void setFragment(int id,Fragment fragment) {
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
fragmentTransaction.replace(id, fragment);
fragmentTransaction.commit();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
Activity activity;
Fragment fragment;
if (context instanceof Activity)
{
activity = (Activity) context;
if (activity instanceof AppEventListener) mAppEventListener = (AppEventListener) activity;
if (activity instanceof LearningEventListener) mLearningEventListener = (LearningEventListener) activity;
}
if (getParentFragment() != null) {
fragment = getParentFragment();
if (fragment instanceof AppEventListener) mAppEventListener = (AppEventListener) getParentFragment();
if (fragment instanceof LearningEventListener) mLearningEventListener = (LearningEventListener) getParentFragment();
}
}
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import sg.edu.nus.se26pt03.photolearn.R;
import sg.edu.nus.se26pt03.photolearn.application.Action;
import sg.edu.nus.se26pt03.photolearn.application.AppFragment;
/**
* Created by MyatMin on 08/3/18.
*/
public class LearningSessionListFragment extends AppFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_learning_session_list, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FloatingActionButton floatingActionButton = view.findViewById(R.id.fab_addlearningsession);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mLearningEventListener.onLearningSessionReaction(Action.SELECTED);
}
});
}
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.BAL;
/**
* Created by chen_ on 7/3/2018.
*/
public class QuizOption {
private int id;
private String content;
private boolean isAnswer;
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.fragment;
import android.animation.ArgbEvaluator;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import sg.edu.nus.se26pt03.photolearn.R;
import sg.edu.nus.se26pt03.photolearn.application.Action;
import sg.edu.nus.se26pt03.photolearn.application.AppFragment;
/**
* Created by MyatMin on 08/3/18.
*/
public class HomeFragment extends AppFragment implements AppFragment.LearningEventListener {
private static final String ARG_TITLE = "Title";
private String mTitle;
public HomeFragment() {}
public static HomeFragment newInstance(String Title) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_TITLE, Title);
fragment.setArguments(args);
return fragment;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (getArguments() != null) {
mTitle = getArguments().getString(ARG_TITLE);
}
setTitle(mTitle, false);
setFragment(R.id.fl_main, new LearningSessionListFragment());
}
public void setTitle(String Title, boolean BackStackInd) {
Toolbar toolbar = this.getView().findViewById(R.id.toolbar);
toolbar.setTitle(Title);
if (BackStackInd) toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
@Override
public void onLearningSessionReaction(Action action) {
switch (action) {
case SELECTED:
setFragment(R.id.fl_main, new LearningSessionFragment());
}
mLearningEventListener.onLearningSessionReaction(action);
}
@Override
public void onLearningTitleReaction(Action action) {
}
@Override
public void onLearningItemReaction(Action action) {
}
@Override
public void onQuizTitleReaction(Action action) {
}
@Override
public void onQuizItemReaction(Action action) {
}
@Override
public void onQuizAnswerReaction(Action action) {
}
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.activity;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import java.security.PrivateKey;
import sg.edu.nus.se26pt03.photolearn.R;
import sg.edu.nus.se26pt03.photolearn.application.AccessMode;
import sg.edu.nus.se26pt03.photolearn.application.Action;
import sg.edu.nus.se26pt03.photolearn.application.UserMode;
import sg.edu.nus.se26pt03.photolearn.fragment.HomeFragment;
import sg.edu.nus.se26pt03.photolearn.fragment.LoginFragment;
import sg.edu.nus.se26pt03.photolearn.application.AppFragment;
public class MainActivity extends AppCompatActivity implements AppFragment.AppEventListener, AppFragment.LearningEventListener {
private HomeFragment homeFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.fl_main) != null) {
if (savedInstanceState != null) {
return;
}
setFragment(new LoginFragment());
}
}
@Override
public void onModeChanged(UserMode userMode, AccessMode accessMode) {
Log.d("Trigger", "onModeChanged");
}
@Override
public void onLoggedIn() {
homeFragment= HomeFragment.newInstance("Welcome to PhotoLearn");
setFragment(homeFragment);
}
protected void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fl_main, fragment);
fragmentTransaction.commit();
}
@Override
public void onLearningSessionReaction(Action action) {
switch (action) {
case SELECTED:
homeFragment.setTitle("Learning Session 1", true);
break;
}
}
@Override
public void onLearningTitleReaction(Action action) {
}
@Override
public void onLearningItemReaction(Action action) {
}
@Override
public void onQuizTitleReaction(Action action) {
}
@Override
public void onQuizItemReaction(Action action) {
}
@Override
public void onQuizAnswerReaction(Action action) {
}
//
// public void sendMessage(View view) {
// Intent intent = new Intent(this, DisplayMessageActivity.class);
// EditText editText = (EditText) findViewById(R.id.editText);
// String message = editText.getText().toString();
// intent.putExtra(EXTRA_MESSAGE, message);
// startActivity(intent);
// }
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.adapter;
/**
* Created by MyatMin on 10/3/18.
*/
public class LearningSessionListAdapter {
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.database;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import sg.edu.nus.se26pt03.photolearn.DAL.QuizOptionDAO;
import sg.edu.nus.se26pt03.photolearn.utility.ConstHelper;
/**
* Created by yijie on 2018/3/11.
* Restructured by MyatMin on 3/12/2018.
*/
public class QuizOptionRepo extends BaseRepo<QuizOptionDAO> {
public QuizOptionRepo() {
super(QuizOptionDAO.class);
mDatabaseRef = mDatabaseRef.child(ConstHelper.REF_QUIZ_OPTIONS);
}
public Collection<QuizOptionDAO> getAllByQuizItemID(final String quizItemId) {
final List<QuizOptionDAO> result = new ArrayList<>();
mDatabaseRef.addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//use the onDataChange() method to read a static snapshot of the contents at a given path
// Get Post object and use the values to update the UI
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
QuizOptionDAO quizOptionDAO = getValue(childDataSnapshot);
if (quizOptionDAO.getQuizItemId().equals(quizItemId)) {
result.add(quizOptionDAO);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
}
});
return result;
}
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.database;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import sg.edu.nus.se26pt03.photolearn.DAL.QuizAnswerOptionDAO;
import sg.edu.nus.se26pt03.photolearn.utility.ConstHelper;
/**
* Created by yijie on 2018/3/11.
*/
public class QuizAnswerOptionRepo extends BaseRepo<QuizAnswerOptionDAO> {
public QuizAnswerOptionRepo() {
super(QuizAnswerOptionDAO.class);
mDatabaseRef = mDatabaseRef.child(ConstHelper.REF_QUIZ_ANSWER_OPTIONS);
}
public Collection<QuizAnswerOptionDAO> getAllByQuizAnswerID(final String quizAnswerId) {
final List<QuizAnswerOptionDAO> result = new ArrayList<>();
mDatabaseRef.addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//use the onDataChange() method to read a static snapshot of the contents at a given path
// Get Post object and use the values to update the UI
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
QuizAnswerOptionDAO quizAnswerOptionDAO = getValue(childDataSnapshot);
if (quizAnswerOptionDAO.getQuizAnswerId().equals(quizAnswerId)) {
result.add(quizAnswerOptionDAO);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
}
});
return result;
}
}
<file_sep>package sg.edu.nus.se26pt03.photolearn.database;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import sg.edu.nus.se26pt03.photolearn.DAL.LearningSessionDAO;
import sg.edu.nus.se26pt03.photolearn.utility.ConstHelper;
/**
* Created by yijie on 2018/3/11.
* Restructured by MyatMin on 3/12/2018.
*/
public class LearningSessionRepo extends BaseRepo<LearningSessionDAO> {
public LearningSessionRepo() {
super(LearningSessionDAO.class);
mDatabaseRef = mDatabaseRef.child(ConstHelper.REF_LEARNING_SESSIONS);
}
public Collection<LearningSessionDAO> getAllByCreator(final String uid) {
final List<LearningSessionDAO> result = new ArrayList<>();
mDatabaseRef.addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//use the onDataChange() method to read a static snapshot of the contents at a given path
// Get Post object and use the values to update the UI
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
LearningSessionDAO learningSessionDAO = getValue(childDataSnapshot);
if (learningSessionDAO.getCreatedBy().equals(uid)) {
result.add(learningSessionDAO);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
}
});
return result;
}
}
|
3f52ea23ec4c5fe72d41ad3a82e2976bba64a67a
|
[
"Java"
] | 19
|
Java
|
CN075/PhotoLearn_V1
|
4277e96cb428ad6b7ed2d3b42c4b313e5f21877f
|
2b91dad69f70e32886f6fc538773ce26c270fc93
|
refs/heads/master
|
<file_sep>REACT_APP_API_URL="http://localhost:3900/api"
|
c8b4b946d22b6695522f3b8c1c90e762fdb7cf81
|
[
"Shell"
] | 1
|
Shell
|
zestsystem/moviehut
|
af9bf8e2d5aa4afd0392f2006402072e059678fb
|
9676cbaa2066d07500362ad003545529ecfbcceb
|
refs/heads/master
|
<file_sep>torchvision>=0.3.0
pretrainedmodels==0.7.4
efficientnet-pytorch>=0.6.3
<file_sep>"""
BSD 3-Clause License
Copyright (c) <NAME> 2016,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* 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.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import torch
from torch import nn
from torch.nn import functional as F
__all__ = ["DeepLabV3Decoder"]
class DeepLabV3Decoder(nn.Sequential):
def __init__(self, in_channels, out_channels=256, atrous_rates=(12, 24, 36)):
super().__init__(
ASPP(in_channels, out_channels, atrous_rates),
nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(),
)
self.out_channels = out_channels
def forward(self, *features):
return super().forward(features[-1])
class ASPPConv(nn.Sequential):
def __init__(self, in_channels, out_channels, dilation):
modules = [
nn.Conv2d(in_channels, out_channels, 3, padding=dilation, dilation=dilation, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU()
]
super(ASPPConv, self).__init__(*modules)
class ASPPPooling(nn.Sequential):
def __init__(self, in_channels, out_channels):
super(ASPPPooling, self).__init__(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(in_channels, out_channels, 1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU())
def forward(self, x):
size = x.shape[-2:]
for mod in self:
x = mod(x)
return F.interpolate(x, size=size, mode='bilinear', align_corners=False)
class ASPP(nn.Module):
def __init__(self, in_channels, out_channels, atrous_rates):
super(ASPP, self).__init__()
modules = []
modules.append(nn.Sequential(
nn.Conv2d(in_channels, out_channels, 1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU()))
rate1, rate2, rate3 = tuple(atrous_rates)
modules.append(ASPPConv(in_channels, out_channels, rate1))
modules.append(ASPPConv(in_channels, out_channels, rate2))
modules.append(ASPPConv(in_channels, out_channels, rate3))
modules.append(ASPPPooling(in_channels, out_channels))
self.convs = nn.ModuleList(modules)
self.project = nn.Sequential(
nn.Conv2d(5 * out_channels, out_channels, 1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(),
nn.Dropout(0.5))
def forward(self, x):
res = []
for conv in self.convs:
res.append(conv(x))
res = torch.cat(res, dim=1)
return self.project(res)
<file_sep>from .unet import Unet
from .linknet import Linknet
from .fpn import FPN
from .pspnet import PSPNet
from .deeplabv3 import DeepLabV3
from .pan import PAN
from . import encoders
from . import utils
from .__version__ import __version__
<file_sep>from .model import DeepLabV3<file_sep>from typing import Optional, Union
from .decoder import FPNDecoder
from ..base import SegmentationModel, SegmentationHead, ClassificationHead
from ..encoders import get_encoder
class FPN(SegmentationModel):
"""FPN_ is a fully convolution neural network for image semantic segmentation
Args:
encoder_name: name of classification model (without last dense layers) used as feature
extractor to build segmentation model.
encoder_depth: number of stages used in decoder, larger depth - more features are generated.
e.g. for depth=3 encoder will generate list of features with following spatial shapes
[(H,W), (H/2, W/2), (H/4, W/4), (H/8, W/8)], so in general the deepest feature will have
spatial resolution (H/(2^depth), W/(2^depth)]
encoder_weights: one of ``None`` (random initialization), ``imagenet`` (pre-training on ImageNet).
decoder_pyramid_channels: a number of convolution filters in Feature Pyramid of FPN_.
decoder_segmentation_channels: a number of convolution filters in segmentation head of FPN_.
decoder_merge_policy: determines how to merge outputs inside FPN.
One of [``add``, ``cat``]
decoder_dropout: spatial dropout rate in range (0, 1).
in_channels: number of input channels for model, default is 3.
classes: a number of classes for output (output shape - ``(batch, classes, h, w)``).
activation (str, callable): activation function used in ``.predict(x)`` method for inference.
One of [``sigmoid``, ``softmax2d``, callable, None]
upsampling: optional, final upsampling factor
(default is 4 to preserve input -> output spatial shape identity)
aux_params: if specified model will have additional classification auxiliary output
build on top of encoder, supported params:
- classes (int): number of classes
- pooling (str): one of 'max', 'avg'. Default is 'avg'.
- dropout (float): dropout factor in [0, 1)
- activation (str): activation function to apply "sigmoid"/"softmax" (could be None to return logits)
Returns:
``torch.nn.Module``: **FPN**
.. _FPN:
http://presentations.cocodataset.org/COCO17-Stuff-FAIR.pdf
"""
def __init__(
self,
encoder_name: str = "resnet34",
encoder_depth: int = 5,
encoder_weights: Optional[str] = "imagenet",
decoder_pyramid_channels: int = 256,
decoder_segmentation_channels: int = 128,
decoder_merge_policy: str = "add",
decoder_dropout: float = 0.2,
in_channels: int = 3,
classes: int = 1,
activation: Optional[str] = None,
upsampling: int = 4,
aux_params: Optional[dict] = None,
):
super().__init__()
self.encoder = get_encoder(
encoder_name,
in_channels=in_channels,
depth=encoder_depth,
weights=encoder_weights,
)
self.decoder = FPNDecoder(
encoder_channels=self.encoder.out_channels,
encoder_depth=encoder_depth,
pyramid_channels=decoder_pyramid_channels,
segmentation_channels=decoder_segmentation_channels,
dropout=decoder_dropout,
merge_policy=decoder_merge_policy,
)
self.segmentation_head = SegmentationHead(
in_channels=self.decoder.out_channels,
out_channels=classes,
activation=activation,
kernel_size=1,
upsampling=upsampling,
)
if aux_params is not None:
self.classification_head = ClassificationHead(
in_channels=self.encoder.out_channels[-1], **aux_params
)
else:
self.classification_head = None
self.name = "fpn-{}".format(encoder_name)
self.initialize()
<file_sep>from typing import Optional, Union
from .decoder import PANDecoder
from ..encoders import get_encoder
from ..base import SegmentationModel
from ..base import SegmentationHead, ClassificationHead
class PAN(SegmentationModel):
""" Implementation of _PAN (Pyramid Attention Network).
Currently works with shape of input tensor >= [B x C x 128 x 128] for pytorch <= 1.1.0
and with shape of input tensor >= [B x C x 256 x 256] for pytorch == 1.3.1
Args:
encoder_name: name of classification model (without last dense layers) used as feature
extractor to build segmentation model.
encoder_weights: one of ``None`` (random initialization), ``imagenet`` (pre-training on ImageNet).
encoder_dilation: Flag to use dilation in encoder last layer.
Doesn't work with [``*ception*``, ``vgg*``, ``densenet*``] backbones, default is True.
decoder_channels: Number of ``Conv2D`` layer filters in decoder blocks
in_channels: number of input channels for model, default is 3.
classes: a number of classes for output (output shape - ``(batch, classes, h, w)``).
activation: activation function to apply after final convolution;
One of [``sigmoid``, ``softmax``, ``logsoftmax``, ``identity``, callable, None]
upsampling: optional, final upsampling factor
(default is 4 to preserve input -> output spatial shape identity)
aux_params: if specified model will have additional classification auxiliary output
build on top of encoder, supported params:
- classes (int): number of classes
- pooling (str): one of 'max', 'avg'. Default is 'avg'.
- dropout (float): dropout factor in [0, 1)
- activation (str): activation function to apply "sigmoid"/"softmax" (could be None to return logits)
Returns:
``torch.nn.Module``: **PAN**
.. _PAN:
https://arxiv.org/abs/1805.10180
"""
def __init__(
self,
encoder_name: str = "resnet34",
encoder_weights: str = "imagenet",
encoder_dilation: bool = True,
decoder_channels: int = 32,
in_channels: int = 3,
classes: int = 1,
activation: Optional[Union[str, callable]] = None,
upsampling: int = 4,
aux_params: Optional[dict] = None
):
super().__init__()
self.encoder = get_encoder(
encoder_name,
in_channels=in_channels,
depth=5,
weights=encoder_weights,
)
if encoder_dilation:
self.encoder.make_dilated(
stage_list=[5],
dilation_list=[2]
)
self.decoder = PANDecoder(
encoder_channels=self.encoder.out_channels,
decoder_channels=decoder_channels,
)
self.segmentation_head = SegmentationHead(
in_channels=decoder_channels,
out_channels=classes,
activation=activation,
kernel_size=3,
upsampling=upsampling
)
if aux_params is not None:
self.classification_head = ClassificationHead(
in_channels=self.encoder.out_channels[-1], **aux_params
)
else:
self.classification_head = None
self.name = "pan-{}".format(encoder_name)
self.initialize()
|
4a0c0b6deec8f4af50d1804f3e30bb24e6a2043e
|
[
"Python",
"Text"
] | 6
|
Text
|
hktxt/segmentation_models.pytorch
|
e687eb3fd625d3c735ee8de6d5ad050789f2564f
|
9f762add41ce8197414e4300b1ed96363d1cfdab
|
refs/heads/master
|
<file_sep>function NoSignature() {
return {
sign: function(request) {}
};
}
function GeekieSignV1(apiKey) {
return {
sign: function(request) {
var signatureHeaders = {
"X-App-Id": apiKey.credentials["client_id"],
"X-Signature": CryptoJS.HmacMD5(
(
request.method.toUpperCase()
+ CryptoJS.SHA1(request.body).toString()
+ request.path_qs
+ apiKey.credentials["client_id"]
),
apiKey.credentials["shared_secret"]
).toString()
};
$.extend(request.autoHeaders, signatureHeaders);
}
};
}
function GeekieSignV2(apiKey) {
return {
sign: function(request) {
var now = new Date().toISOString();
console.log(now);
var signatureHeaders = {
"X-Geekie-Requested-At": now,
"X-Geekie-Signature": CryptoJS.HmacSHA1(
(
request.method.toUpperCase() + " " + request.path_qs + "\n"
+ now + "\n"
+ CryptoJS.SHA1(request.body).toString() + "\n"
),
apiKey.credentials["api_key"]
).toString()
};
$.extend(request.autoHeaders, signatureHeaders);
}
};
}
function LoggedUserAuth(apiKey) {
return {
sign: function(request) {
console.log(apiKey);
var cookie = apiKey.credentials["session_cookie"];
try {
var accessToken = pickle.loads(atob(cookie.slice(40)))[2].access_token;
} catch (e) {
window.alert("Cookie inválido");
return;
}
var signatureHeaders = {
"Authorization": "Bearer: " + accessToken
};
$.extend(request.autoHeaders, signatureHeaders);
}
};
}<file_sep># api-explorer
Chrome App/Extensions for Exploring our APIs
<file_sep>window.alert = bootbox.alert;
function main(storageInfo) {
var inputHttpEditor = ace.edit("input-http-editor");
inputHttpEditor.setTheme("ace/theme/chrome");
inputHttpEditor.setOptions({
maxLines: 100,
highlightActiveLine: false,
highlightGutterLine: false,
showPrintMargin: false
});
inputHttpEditor.getSession().setUseWrapMode(true);
var inputAutoHeadersEditor = ace.edit("input-auto-headers");
inputAutoHeadersEditor.setTheme("ace/theme/chrome");
inputAutoHeadersEditor.setOptions({
maxLines: 100,
highlightActiveLine: false,
highlightGutterLine: false,
showPrintMargin: false
});
inputAutoHeadersEditor.getSession().setUseWrapMode(true);
var inputBodyEditor = ace.edit("input-body-editor");
inputBodyEditor.setTheme("ace/theme/chrome");
inputBodyEditor.setOptions({maxLines: 10000});
inputBodyEditor.getSession().setMode("ace/mode/json");
inputBodyEditor.getSession().setUseWrapMode(true);
var outputHttpEditor = ace.edit("output-http-editor");
outputHttpEditor.setTheme("ace/theme/monokai");
outputHttpEditor.setOptions({
maxLines: 100,
highlightActiveLine: false,
highlightGutterLine: false,
showPrintMargin: false
});
outputHttpEditor.getSession().setUseWrapMode(true);
var outputBodyEditor = ace.edit("output-body-editor");
outputBodyEditor.setTheme("ace/theme/monokai");
outputBodyEditor.setOptions({maxLines: Infinity, showPrintMargin: false});
outputBodyEditor.getSession().setMode("ace/mode/json");
outputBodyEditor.getSession().setUseWrapMode(true);
var editors = [inputHttpEditor, inputAutoHeadersEditor, inputBodyEditor,
outputHttpEditor, outputBodyEditor];
editors.forEach(function applyGlobalConfig(editor) {
editor.$blockScrolling = Infinity;
editor.renderer.setShowGutter(false);
});
editors.forEach(function(editor) {
editor.on("change", saveServerState);
});
[inputBodyEditor, inputHttpEditor].forEach(function(editor) {
editor.on("change", function() {
if (window.maySaveServerState) {
inputAutoHeadersEditor.setValue("");
}
});
});
[inputAutoHeadersEditor, outputHttpEditor, outputBodyEditor].forEach(function(editor) {
editor.setReadOnly(true);
editor.getSession().setUseWorker(false);
editor.textInput.getElement().tabIndex = -1;
editor.renderer.$cursorLayer.element.style.opacity = 0;
});
function saveServerState() {
if (window.maySaveServerState) {
var info = {};
info[serverSelect.getValue()] = {
inputHttpEditor: inputHttpEditor.getValue(),
inputBodyEditor: inputBodyEditor.getValue(),
outputHttpEditor: outputHttpEditor.getValue(),
outputBodyEditor: outputBodyEditor.getValue(),
inputAutoHeadersEditor: inputAutoHeadersEditor.getValue(),
url: $(".selectize-container .editable-input").text()
};
storageInfo[serverSelect.getValue()] = info[serverSelect.getValue()];
chrome.storage.local.set(info);
}
}
$("#input-editor").resizable({
handles: "e",
autoHide: false,
minWidth: 200,
maxWidth: 1000,
stop: function(event, ui) {
var outputEditor = $(this).next();
outputEditor.css("left", $(this).outerWidth(true) + "px");
editors.forEach(function(editor) {
editor.resize();
});
}
});
$("#endpoint").selectize({
createOnBlur: true,
selectOnTab: true,
addPrecedence: true,
loadThrottle: null,
preload: "focus",
valueField: "url",
labelField: "url",
searchField: "url",
sortField: [{field: "timestamp", direction: "desc"}, {field: "path_qs", direction: "asc"}],
load: function(query, callback) {
this.clearOptions();
if (!window.serverSelect.getValue()) {
callback();
}
var server = window.serverList.getServer(window.serverSelect.getValue());
if (this.historyMode) {
return callback(server.requestHistory.map(function(item) {
item = $.extend({}, item);
item.path_qs = item.url.split(" ").slice(1).join(" ");
item.url = item.method + " " + item.url + ";t=" + item.timestamp;
return item;
}));
}
return callback(server.getEndpoints(query).map(function(item) {
item = $.extend({}, item);
item.path_qs = item.url.split(" ").slice(1).join(" ");
item.timestamp = 0; // not history mode
return item;
}));
},
createFilter: function(url) {
return url.match(/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS) (\/.*)$/i);
},
create: function(url) {
var match = url.match(/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS) (\/.*)$/i);
if (!match) {
return false;
}
return {url: url};
},
render: {
item: function(item, escape) {
return "<div class='noneditable-input'>" + escape(item.url) + "</div>";
},
option: function(item, escape) {
var url = item.url;
if (url.indexOf(";t=") >= 0) {
url = url.substring(0, url.lastIndexOf(";t="));
}
return "<div class='endpoint-option'><div class='endpoint-url'>" +
"<span class='method'>" + url.split(" ")[0] + "</span> " +
"<span class='url'>" + escape(url.split(" ").slice(1).join(" ")) + "</span>" +
"</div>" +
"<div class='endpoint-description'>" + (
item.description ? escape(item.description) : (
item.timestamp ? new Date(item.timestamp).toString() : "(do histórico)"
)
) + "</div></div>";
},
},
onChange: function(value) {
var url = this.getValue();
if (!url) {
return;
}
if (url.indexOf(";t=") >= 0) {
setURL(url.substring(0, url.lastIndexOf(";t=")));
var historyEntry = this.options[url];
inputHttpEditor.setValue(Object.keys(historyEntry.headers).map(function(key) {
return key + ": " + historyEntry.headers[key];
}).join("\n"), -1);
inputBodyEditor.setValue(historyEntry.body, -1);
} else {
setURL(url);
}
},
onDropdownOpen: function() {
$(".selectize-container .noneditable-input").show();
$(".selectize-container .editable-input").hide();
},
onDropdownClose: function() {
this.historyMode = false;
$(".selectize-container .noneditable-input").hide();
$(".selectize-container .editable-input").show();
}
});
$(".selectize-container .editable-input").on("blur", function() {
var url = $.trim($(this).text().replace("\xa0", " "));
var match = url.match(/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS) (\/.*)$/i);
if (!match) {
url = $("#endpoint")[0].selectize.getValue();
}
setURL(url);
}).on("keydown", function(e) {
if (e.which == 13 /* ENTER */) {
$(this).trigger("blur");
return false;
}
});
function setURL(url) {
if (!url) {
$(".selectize-container .editable-input").empty();
return;
}
$(".selectize-container .editable-input")
.empty()
.append($("<span class='method'>").text(url.split(" ")[0]))
.append(" ")
.append($("<span class='url'>").text(url.split(" ").slice(1).join(" ")));
if (window.maySaveServerState) {
inputAutoHeadersEditor.setValue("", -1);
saveServerState();
}
if (/^(PUT|POST|PATCH)/i.test(url)) {
$(".if-http-input-body").css("visibility", "visible");
} else {
$(".if-http-input-body").css("visibility", "hidden");
}
}
$(".btn.show-history").on("click", function() {
var selectize = $("#endpoint")[0].selectize;
selectize.historyMode = true;
selectize.focus();
});
window.serverList.whenServerListAvailable(function(serverList) {
var $select = $("#server-host").selectize({
valueField: "url",
labelField: "url",
searchField: "url",
dropdownParent: "body",
options: serverList,
render: {
item: function(item, escape) {
return "<div class='server-item'><span class='api'>" + (
item.api ? escape(ServerList.getApiDisplayName(item.api)) :
escape("<API desconhecida>")
) + "</span>\n<span class='url'>" + escape(item.url) + "</span></div>";
},
option: function(item, escape) {
return "<div class='server-option'><span class='api'>" + (
item.api ? escape(ServerList.getApiDisplayName(item.api)) :
escape("<API desconhecida>")
) + "</span>\n<span class='url'>" + escape(item.url) + "</span></div>";
}
},
createFilter: function(url) {
info = ServerList.identifyServer(url);
if (!info.ok) {
return false;
}
return !window.serverList.alreadyHas(url);
},
create: function(url) {
info = ServerList.identifyServer(url);
if (!info.ok) {
window.alert("URL inválida");
}
return window.serverList.addServer(new Server({url: url}));
},
onChange: function(value) {
window.maySaveServerState = false;
var serverState = storageInfo[value] || {
inputHttpEditor: "Accept: */*",
inputAutoHeadersEditor: "",
inputBodyEditor: "{}",
outputHttpEditor: "",
outputBodyEditor: "",
url: "GET /path/to/endpoint"
};
inputHttpEditor.setValue(serverState.inputHttpEditor, -1);
inputAutoHeadersEditor.setValue(serverState.inputAutoHeadersEditor, -1);
inputBodyEditor.setValue(serverState.inputBodyEditor, -1);
outputHttpEditor.setValue(serverState.outputHttpEditor, -1);
outputBodyEditor.setValue(serverState.outputBodyEditor, -1);
setURL(serverState.url);
chrome.storage.local.set({lastServer: value});
$(".btn.forget-credentials").hide();
window.maySaveServerState = true;
}
});
window.serverSelect = $select[0].selectize;
window.serverSelect.setValue(
storageInfo.lastServer ||
window.serverSelect.options[Object.keys(window.serverSelect.options)[0]].url
);
});
$(".send-request").on("click", function() {
var server = window.serverList.getServer(window.serverSelect.getValue());
if (!server) {
window.alert("Nenhum servidor selecionado");
return;
}
var url = $(".selectize-container .editable-input").text().replace("\xa0", " ");
var requestParser = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS) (\/.*)$/i;
if (!requestParser.exec(url)) {
window.alert("Requisição inválida\n\nPrimeira linha deve conter algo " +
"como GET /organizations/321313213/who-am-i");
return;
}
var inputHttp = inputHttpEditor.getValue();
var inputHttpLines = inputHttp.replace("\r", "").split("\n");
var requestTarget = requestParser.exec(url);
var request = {
method: requestTarget[1].toUpperCase(),
url: (server.url + (server.url.endsWith("/") ? "": "/") + requestTarget[2].substring(1)),
path_qs: requestTarget[2],
headers: {},
autoHeaders: {},
body: ["PUT", "PATCH", "POST"].indexOf(requestTarget[1].toUpperCase()) >= 0 ?
inputBodyEditor.getValue() : ""
};
var invalidHeaders = [];
inputHttpLines.filter(function (line) {
return $.trim(line).length;
}).forEach(function (headerLine) {
var sep = headerLine.indexOf(":");
if (sep <= 0) {
return invalidHeaders.push(headerLine);
}
var headerName = $.trim(headerLine.substring(0, sep));
if (!headerName.length) {
return invalidHeaders.push(headerLine);
}
var headerValue = $.trim(headerLine.substring(sep + 1));
if (!headerValue.length) {
return invalidHeaders.push(headerLine);
}
request.headers[headerName] = headerValue;
});
if (invalidHeaders.length) {
window.alert("Headers inválidos\n\n" + invalidHeaders.join("\n"));
return;
}
sendRequest(server, request);
});
var sendRequest = function(server, request) {
outputHttpEditor.setValue("Aguarde...", -1);
outputBodyEditor.setValue("", -1);
$(".btn.forget-credentials").hide();
server.getSigningFunction(request, window.userInputService, function(signingFunction) {
signingFunction.sign(request);
server.send(request, function(response) {
var responseHttpInfo = response.statusLine + "\n\n" + response.headers;
var limitLines = function(body) {
var lines = body.split("\n");
var limit = 10000;
if (lines.length > limit) {
return (lines.slice(0, limit).join("\n")
+ "\n\n(...) output limited to " + limit + " lines");
}
return body;
};
outputHttpEditor.setValue(responseHttpInfo, -1);
try {
var json = JSON.parse(response.body);
outputBodyEditor.setValue(limitLines(JSON.stringify(json, null, 4)), -1);
} catch(e) {
outputBodyEditor.setValue(limitLines(response.body), -1);
}
var autoHeaders = Object.keys(request.autoHeaders).map(function(key) {
return key + ": " + request.autoHeaders[key];
}).join("\n");
inputAutoHeadersEditor.setValue(autoHeaders, -1);
$(".btn.forget-credentials").show()
.off("click")
.one("click", function() {
server.eraseAuthInfo(request);
$(".btn.forget-credentials").hide();
sendRequest(server, request);
});
});
});
};
}
window.userInputService = {
getApiKeyCredentials: function(options, callback) {
var modal = $("[data-signature-method='" + options.kind + "']");
modal.modal();
modal.modal("show");
modal.find("[data-bind='server-url']").text(options.scopeUrlPrefix);
modal.find("input[name], textarea").val("");
modal.find(".btn-primary").one("click", function() {
modal.modal("hide");
var credentials = {};
var errors = false;
modal.find("input[name], textarea").toArray().forEach(function(input) {
var name = $(input).attr("name");
var value = $.trim($(input).val());
if (!value) {
errors = true;
}
credentials[name] = value;
});
if (errors) {
window.alert("Todos os campos são de preenchimento obrigatório");
} else {
callback(credentials);
}
});
}
};
$(function() {
chrome.storage.local.get(null, function(storageInfo) {
main(storageInfo);
});
});<file_sep>chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('index.html', {
'innerBounds': {
'minWidth': 768,
'minHeight': 400
}
});
});<file_sep>function ServerList(serverList) {
this._servers = [];
this._initDone = false;
this._initCallbacks = [];
this.init = function() {
var list = this;
$.ajax({
url: "https://geekie.s3.amazonaws.com/api-explorer/directory.json",
type: "GET",
dataType: "json",
success: function(apiDirectory) {
window.apiDirectory = apiDirectory;
apiDirectory.forEach(function(api) { apiDirectory[api.id] = api; });
chrome.storage.sync.get(["serverList"], function(items) {
items.serverList = items.serverList || [];
if (!items.serverList.length) {
items.serverList.push(new Server({url: "http://api.geekielab.com.br/"}));
}
list._servers = items.serverList.map(function(server) {
return new Server(server);
});
list._initDone = true;
list._initCallbacks.forEach(function(callback) {
callback(list._servers);
});
});
}
});
};
this.whenServerListAvailable = function(callback) {
if (this._initDone) {
callback(this._servers);
} else {
this._initCallbacks.push(callback);
}
};
this.addServer = function(server) {
this._servers.push(server);
return server;
};
this.save = function() {
chrome.storage.sync.set({"serverList": this._servers.map(function(server) {
return server.toJson();
})});
};
this.getServer = function(url) {
var servers = this._servers.filter(function(server) {
return server.url.startsWith(url) || url.startsWith(server.url);
});
if (servers.length) {
return servers[0];
}
return null;
};
this.alreadyHas = function(url) {
return !!this.getServer(url);
};
}
ServerList.identifyServer = function(serverUri) {
if (!serverUri.endsWith("/")) {
serverUri += "/";
}
var validPattern = /https?:\/\/[a-z-.]+(:\d{2,5})?\/(api\/(v\d\/)?)?/;
if (!validPattern.test(serverUri)) {
return {ok: false};
}
var matchingApis = apiDirectory.filter(function(api) {
return api.knownServers.indexOf(serverUri) >= 0;
});
if (matchingApis.length == 1) {
return {ok: true, api: matchingApis[0].id};
} else {
return {ok: true, api: undefined};
}
};
ServerList.getApiDisplayName = function(api) {
return apiDirectory[api].displayName || "<API desconhecida>";
};
function Server(options) {
var info = ServerList.identifyServer(options.url);
var server = this;
this.url = options.url;
if (!this.url.endsWith("/")) {
this.url += "/";
}
this.apiKeys = options.apiKeys || [];
this.api = info.api;
this.signatureMethod = info.signatureMethod;
this.requestHistory = [];
chrome.storage.local.get([server.url + "_history"], function(items) {
server.requestHistory = items[server.url + "_history"] || [];
});
this.toJson = function() {
return {url: this.url, apiKeys: this.apiKeys};
};
this.getSigningFunction = function(request, userInputService, callback) {
if (this.api == "swag" && (
request.path_qs.startsWith("/api/v1") || request.path_qs.startsWith("/api/v2"))
) {
return this.getApiKey({
"kind": "logged-user",
scope: {},
scopeUrlPrefix: this.url + "*",
userInputService: userInputService,
callback: function(apiKey) {
callback(LoggedUserAuth(apiKey));
}
});
}
if (this.api != "extapi") {
return this.getApiKey({
kind: "geekie-sign-v1",
scope: {},
scopeUrlPrefix: this.url + "*",
userInputService: userInputService,
callback: function(apiKey) {
callback(GeekieSignV1(apiKey));
}
});
}
else {
var organizationInfo = /^\/organizations\/(\d+)\//.exec(request.path_qs);
if (!organizationInfo) {
return callback(NoSignature());
}
return this.getApiKey({
kind: "geekie-sign-v2",
scope: {organization_id: organizationInfo[1]},
scopeUrlPrefix: this.url + "organizations/"+ organizationInfo[1] + "/*",
userInputService: userInputService,
callback: function(apiKey) {
callback(GeekieSignV2(apiKey));
}
});
}
};
this.getApiKey = function(options) {
var matchingKey = this.matchingApiKey(options);
if (matchingKey) {
return options.callback(matchingKey);
}
options.userInputService.getApiKeyCredentials(options, function(credentials) {
var apiKey = {
kind: options.kind,
scope: options.scope,
credentials: credentials
};
this.apiKeys.push(apiKey);
window.serverList.save();
options.callback(apiKey);
}.bind(this));
};
this.matchingApiKey = function(options) {
console.log(options);
var matchingKeys = this.apiKeys.filter(function(apiKey) {
console.log("match kind=" + options.kind);
if (apiKey.kind != options.kind) {
return false;
}
for (var key in options.scope) {
console.log("match scope" + key + "=" + options.scope[key]);
if (apiKey.scope[key] != options.scope[key]) {
return false;
}
}
return true;
});
if (matchingKeys.length) {
return matchingKeys[0];
}
return null;
};
this.eraseAuthInfo = function(request) {
if (this.api == "swag" && (
request.path_qs.startsWith("/api/v1") || request.path_qs.startsWith("/api/v2"))
) {
return this.eraseApiKey({
kind: "logged-user",
scope: {}
});
}
if (this.api != "extapi") {
return this.eraseApiKey({
kind: "geekie-sign-v1",
scope: {},
});
}
else {
var organizationInfo = /^\/organizations\/(\d+)\//.exec(request.path_qs);
if (!organizationInfo) {
return;
}
return this.eraseApiKey({
kind: "geekie-sign-v2",
scope: {organization_id: organizationInfo[1]},
});
}
};
this.eraseApiKey = function(options) {
var matchingKey = this.matchingApiKey(options);
if (matchingKey) {
this.apiKeys.splice(this.apiKeys.indexOf(matchingKey), 1);
window.serverList.save();
}
};
this.send = function(request, callback) {
// set default content-type
var isJson = false;
try {
JSON.parse(request.body);
isJson = true;
} catch(e) {}
var hasContentHeaderSet = false;
Object.keys(request.headers).forEach(function(headerName) {
if (headerName.toLowerCase() == "content-type") {
hasContentHeaderSet = true;
}
});
if (isJson && !hasContentHeaderSet) {
request.autoHeaders["Content-Type"] = "application/json";
}
var timestamp = new Date();
var server = this;
$.ajax({
type: request.method,
headers: $.extend({}, request.autoHeaders, request.headers),
url: request.url,
data: request.body,
complete: function(jqXhr) {
server.addHistoryEntry({
method: request.method,
url: request.path_qs,
timestamp: timestamp.getTime(),
headers: request.headers,
body: request.body
});
callback({
statusLine: jqXhr.status + " " + jqXhr.statusText,
headers: jqXhr.getAllResponseHeaders(),
body: jqXhr.responseText
});
}
});
};
this.addHistoryEntry = function(entry) {
var key = this.url + "_history";
var server = this;
chrome.storage.local.get([key], function(info) {
server.requestHistory = info[key] || server.requestHistory;
server.requestHistory.unshift(entry);
info[key] = server.requestHistory;
chrome.storage.local.set(info);
});
};
this.getEndpoints = function(query) {
var endpointsList = apiDirectory[this.api].endpoints.slice();
// merge history
var keys = {};
endpointsList.forEach(function(endpoint) {
keys[endpoint.method + " " + endpoint.url] = true;
});
this.requestHistory.forEach(function(entry) {
var key = entry.method + " " + entry.url;
if (!keys.hasOwnProperty(key)) {
keys[key] = true;
endpointsList.push(entry);
}
});
var matches = [];
var method = /^GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS/i.exec(query);
if (method) {
method = method[0].toUpperCase();
query = query.substring(method.length + 1);
endpointsList = endpointsList.filter(function(endpoint) {
return endpoint.method == method;
});
}
var path = query;
if (path.startsWith("/")) {
path = path.substring(1);
}
if (path.endsWith("/")) {
path = path.substring(0, path.length - 1);
}
endpointsList.forEach(function(endpoint) {
if (!path || endpoint.url.indexOf(path) >= 0) {
return matches.push({url: endpoint.method + " " + endpoint.url,
description: endpoint.description});
}
var queryParts = path.split("/");
var myParts = endpoint.url.substring(1).split("/");
var matchedParts = [];
if (queryParts.length > myParts.length) {
return;
}
for (var i = 0; i < queryParts.length; ++i) {
if (!queryParts[i].length) {
return;
}
if (queryParts[i] == myParts[i]) {
matchedParts.push(queryParts[i]);
}
else if (myParts[i].startsWith(":")) {
if (queryParts[i].length > 0) {
matchedParts.push(queryParts[i]);
} else {
return;
}
}
else if (myParts[i].startsWith(queryParts[i]) && i == queryParts.length - 1) {
matchedParts.push(queryParts[i]);
} else {
return;
}
}
for (; i < myParts.length; ++i) {
matchedParts.push(myParts[i]);
}
return matches.push({
url: endpoint.method + " /" + matchedParts.join("/"),
description: endpoint.description
});
});
return matches;
};
}
var serverList = new ServerList();
serverList.init();
|
7fc99dc5ab007f0559e4179267dd592f784abc5a
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
projetoeureka/api-explorer
|
c1129bf34fb43149fa36bcb0bc219a13f8a03913
|
4477f72ca6a7292306600e2ed2d0fb4f0a15a132
|
refs/heads/master
|
<repo_name>MrHoseongLee/Queueing-Simulation<file_sep>/visualization.js
class Person {
constructor(type, x, y) {
this.type = type
this.x = x
this.y = y
this.target_x = -1e7
this.target_y = 0
}
setTarget(x, y) {
this.target_x = x
this.target_y = y
}
gotoTarget() {
this.x = this.target_x
this.y = this.target_y
}
updatePos(percent) {
if(this.target_x >= -1e7 && this.target_x < -1e3) {
const dx = - this.x - boxSize
this.x = this.x + dx * percent
} else {
const dx = this.target_x - this.x
const dy = this.target_y - this.y
this.x = this.x + dx * percent
this.y = this.y + dy * percent
}
}
}
var speed = 900
var intervalCount = 0
const boxSize = 50
const timePerStep = 1000
function start() {
const input = textBox.value.split(/[\n\r]+/)
wrapper.style.display = 'block'
timeText.style.display = 'inline'
speedSlider.style.display = 'inline'
speedSlider.value = speed / 30
title.style.display = 'none'
textBox.style.display = 'none'
startButton.style.display = 'none'
textBox.value = ""
const data = input[0].split(' ')
customers = Array(data[0])
employees = Array(data[1])
atms = Array(data[2])
height = 100 * (data[1] * 1 + data[2] * 1 + 2) - boxSize
const employee_line_y = 50 * (data[1] * 1 + 1)
const atm_line_y = employee_line_y * 2 + 50 * (data[2] * 1 + 0.5)
let employee_line_x = innerWidth * 9 / 10 - boxSize * 5
let atm_line_x = innerWidth * 9 / 10 - boxSize * 5
canvas.height = height
let employee_line = 0
let atm_line = 0
c = canvas.getContext('2d')
for(let i=0; i < data[0]; ++i) {
customers[i] = new Person(0, -1e7, 0)
}
for(let i=0; i < data[1]; ++i) {
employees[i] = new Person(1, innerWidth * 9 / 10 - boxSize / 2, (i + 1) * 100)
}
for(let i=0; i < data[2]; ++i) {
atms[i] = new Person(2, innerWidth * 9 / 10, (i + 2 + data[1] * 1) * 100)
}
let i = 1
function step() {
speed = speedSlider.value * 30
const data = input[i].split(' ')
const eventType = data[1] * 1
const customerID = data[2] * 1
if(eventType == 0) {
if(customers[customerID].x < 0) {
customers[customerID].x = 0
customers[customerID].y = height / 2
}
customers[customerID].setTarget(employee_line_x - employee_line * boxSize * 2, employee_line_y)
++employee_line
}
if(eventType == 1) {
if(customers[customerID].x < 0) {
customers[customerID].x = 0
customers[customerID].y = height / 2
}
customers[customerID].setTarget(atm_line_x - atm_line * boxSize * 2, atm_line_y)
++atm_line
}
if(eventType == 2) {
const employeeID = data[3] * 1
customers[customerID].setTarget(employee_line_x + boxSize * 2, employees[employeeID].y)
for(let j=0; j < customers.length; ++j) {
if((customers[j].y == employee_line_y || customers[j].y == height / 2) && customers[j].target_y == employee_line_y
&& customers[j].x != employee_line_x + boxSize * 2 && customers[j].target_x != employee_line_x + boxSize * 2) {
customers[j].target_x += boxSize * 2
}
}
--employee_line
}
if(eventType == 3) {
const atmID = data[3] * 1
customers[customerID].setTarget(atm_line_x + boxSize * 2, atms[atmID].y - boxSize / 2)
for(let j=0; j < customers.length; ++j) {
if((customers[j].y == atm_line_y || customers[j].y == height / 2) && customers[j].target_y == atm_line_y
&& customers[j].x != atm_line_x + boxSize * 2 && customers[j].target_x != atm_line_x + boxSize * 2) {
customers[j].target_x += boxSize * 2
}
}
--atm_line
}
if(eventType == 4) {
customers[customerID].target_x = -1e7
}
if(eventType == 5) {
customers[customerID].target_x = -1e7
for(let j=0; j < customers.length; ++j) {
if((customers[j].y == employee_line_y || customers[j].y == height / 2) && customers[j].target_y == employee_line_y
&& customers[j].x < customers[customerID].x) {
customers[j].target_x += boxSize * 2
}
}
--employee_line
}
if(eventType == 6) {
customers[customerID].target_x = -1e7
for(let j=0; j < customers.length; ++j) {
if((customers[j].y == atm_line_y || customers[j].y == height / 2) && customers[j].target_y == atm_line_y
&& customers[j].x < customers[customerID].x) {
customers[j].target_x += boxSize * 2
}
}
--atm_line
}
if(i < input.length - 1 && data[0] * 1 != input[i+1].split(' ')[0] * 1) {
intervalCount = 0
const interval = setInterval(animate, 30)
setTimeout(function(){
clearInterval(interval);
for(let j=0; j < customers.length; ++j) {
customers[j].gotoTarget()
}
++i;
step();
}, speed)
} else {
if (i < input.length - 1) {
++i
step()
}
}
if(i == input.length - 1) {
const interval = setInterval(animate, 30)
setTimeout(function(){
clearInterval(interval);
for(let j=0; j < customers.length; ++j) {
customers[j].gotoTarget()
}
}, speed)
}
if(data[0] * 1 % 60 >= 10) {
timeText.innerHTML = "" + (Math.floor(data[0] * 1 / 60)) + ":" + (data[0] * 1 % 60)
} else {
timeText.innerHTML = "" + (Math.floor(data[0] * 1 / 60)) + ":0" + (data[0] * 1 % 60)
}
}
for(let i=0; i < employees.length; ++i) {
c.beginPath()
c.arc(employees[i].x, employees[i].y, boxSize / 2, 0, 2*Math.PI)
c.fillStyle = 'rgb(68, 114, 196)'
c.fill()
}
for(let i=0; i < atms.length; ++i) {
c.fillStyle = 'rgb(112, 173, 71)'
c.fillRect(atms[i].x - boxSize, atms[i].y - boxSize, boxSize, boxSize)
}
step()
/*
title.style.display = 'block'
textBox.style.display = 'inline'
startButton.style.display = 'block'
*/
}
function animate() {
c.clearRect(0, 0, 9 / 10 * innerWidth - boxSize, height)
for(let i=0; i < customers.length; ++i) {
if((customers[i].target_x > 0 && customers[i].target_y > 0) || (customers[i].target_x < 0 && customers[i].x > 0)) {
customers[i].updatePos(intervalCount*30/speed)
if(customers[i].x > 0) {
c.beginPath()
c.arc(customers[i].x, customers[i].y, boxSize / 2, 0, 2*Math.PI)
c.fillStyle = 'rgb(237, 125, 49)'
c.fill()
}
}
}
intervalCount += 1
}
const title = document.getElementById("title")
const textBox = document.getElementById("input_logs")
textBox.value = ""
const startButton = document.getElementById("start")
const canvas = document.querySelector("canvas")
const wrapper = document.getElementById("wrapper")
const timeText = document.getElementById("time")
const speedSlider = document.getElementById("speed")
wrapper.style.display = 'none'
timeText.style.display = 'none'
speedSlider.style.display = 'none'
var c
var height
var customers
var employees
var atms
canvas.width = window.innerWidth
startButton.setAttribute("onClick", "javascript: start();")
|
b29ea1725366dff963bb6c82bcf8a2af7d864425
|
[
"JavaScript"
] | 1
|
JavaScript
|
MrHoseongLee/Queueing-Simulation
|
75e5df520351244b5bfec5663bd38ab7d09c12ae
|
0cccbbc6269bea35bef95ea90085f35d31736e3c
|
refs/heads/master
|
<file_sep>import React, { useEffect, useState } from 'react';
import Charts from './Visualization/Charts';
import ProgressiveBar from './Visualization/ProgressiveBar';
import {getDataGlobally} from '../api/fetchData';
const ParentVisualization = ({country}) => {
const [globalData, setGlobalData] = useState({});
// get data
useEffect(() => {
const fetchAPI = async()=>{
// fetch data globally
setGlobalData(await getDataGlobally(country));
}
fetchAPI();
}, [country]);
const dataArray = []
const valueArray = []
Object.keys(globalData).map(data=>{
return(
dataArray.push(data) &&
valueArray.push(globalData[data].value)
)
})
return (
<div className="Visualization">
<Charts dataArray={dataArray} valueArray={valueArray} />
<ProgressiveBar valueArray={valueArray} />
</div>
);
}
export default ParentVisualization;
<file_sep>
// fetch data country wise
const url = "https://covid19.mathdro.id/api";
export const getDataCountry = async() =>{
try{
const countryApi = await fetch(`${url}/countries`);
const countryResponse = await countryApi.json();
const countryItemsArray = countryResponse["countries"];
return countryItemsArray;
}
catch(error){
return error;
}
}
// fetch data globally
export const getDataGlobally = async(country) => {
let changeableUrl = url;
if(country){
changeableUrl = `${url}/countries/${country}`;
}
try{
const globallyApi = await fetch(changeableUrl);
const globallyResponse = await globallyApi.json();
delete globallyResponse["countryDetail"]
delete globallyResponse["dailyTimeSeries"]
delete globallyResponse["dailySummary"]
delete globallyResponse["image"]
delete globallyResponse["source"]
delete globallyResponse["countries"]
delete globallyResponse["lastUpdate"]
return globallyResponse;
}
catch(error){
return error;
}
}<file_sep>import React, { useEffect, useState } from "react";
import { makeStyles } from "@material-ui/core/styles";
import InputLabel from "@material-ui/core/InputLabel";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";
import {getDataCountry} from '../api/fetchData';
const useStyles = makeStyles(theme => ({
mainSelectDiv: {
Width: "100%"
},
formControl: {
minWidth: "50%",
margin: "5px 25%"
},
mainHeading: {
textAlign : "center"
}
}));
const SelectOption = ({handleCountry}) => {
const classes = useStyles();
const [fetchData, setFetchData] = useState({});
const [country, setCountry] = useState("");
useEffect(() => {
// fetch data country wise
const fetchAPI = async() =>{
setFetchData(await getDataCountry());
}
fetchAPI();
}, []);
const handleChange = (event) => {
if(event.target.value==="globalData"){
setCountry(event.target.value);
}
else{
setCountry(event.target.value);
}
};
handleCountry(country)
return (
<div className={classes.mainSelectDiv}>
<h2 className={classes.mainHeading}>
{country ? country.toUpperCase()+" CASES RECORDS" : "GLOBAL CASES RECORDS"}
</h2>
<FormControl variant="outlined" className={classes.formControl}>
<InputLabel htmlFor="outlined-country-native-simple">
Select Country
</InputLabel>
<Select
native
value= {country}
onChange={handleChange}
>
<option aria-label="None" value=""/>
<option value="">GLOBAL RECORDS</option>
{Object.keys(fetchData).map((dataObj, index) => {
return (
<option value={fetchData[dataObj].name} key={index}>
{fetchData[dataObj].name}
</option>
);
})}
</Select>
</FormControl>
</div>
);
};
export default SelectOption;
<file_sep>import React from "react";
import { CircularProgressbar, buildStyles } from "react-circular-progressbar";
import "react-circular-progressbar/dist/styles.css";
const ProgressiveBar = ({valueArray}) => {
const recoveredRate = parseInt((valueArray[1]/valueArray[0]) * 100);
const deathRate = parseInt((valueArray[2]/valueArray[0]) * 100);
return (
<div className="mainProgressBar">
<div className="progressBar" >
<CircularProgressbar value={recoveredRate}
text={`${recoveredRate}%`}
styles={buildStyles({
pathTransitionDuration: 0.8,
textColor: '#4ccc4c',
pathColor: '#4ccc4c',
trailColor: '#d6d6d6',
})}
/>
<h4 style={{textAlign:"center",color:"#4ccc4c"}}>Recovered Rate</h4>
</div>
<div className="progressBar">
<CircularProgressbar value={deathRate}
text={`${deathRate}%`}
styles={buildStyles({
pathTransitionDuration: 0.8,
textColor: '#f13333',
pathColor: '#f13333',
trailColor: '#d6d6d6',
})}
/>
<h4 style={{textAlign:"center",color:"#f13333"}}>Fartile Rate</h4>
</div>
</div>
);
};
export default ProgressiveBar;
<file_sep>import React, { useState } from 'react';
import './App.css';
import Cards from './Components/Cards';
import SelectOption from './Components/SelectOption';
import ParentVisualization from './Components/parentVisualization';
function App() {
const [countryChange, setcountryChange] = useState("")
const HandleCountryValue = (country) =>{
setcountryChange(country)
}
return (
<>
<Cards country = {countryChange} />
<SelectOption handleCountry= {HandleCountryValue}/>
<ParentVisualization country = {countryChange} />
</>
);
}
export default App;
|
266d081559663fd55ed3b708c3ac14f27e667b4a
|
[
"JavaScript"
] | 5
|
JavaScript
|
SajeerJabri/covid-19-app-reactjs
|
d884c27c90008a1a7f4cbb4ff4af016623f0b77e
|
f0021d94b74b2f6f19656bec7cc704a89b36a0a9
|
refs/heads/master
|
<repo_name>VictorVonFrankenstein/steeme<file_sep>/testDeploy.sh
yarn build
aws s3 sync build/ s3://steeme.com/
|
f4a2d3f3bd4e51f428ea889928d5a4103d8b0311
|
[
"Shell"
] | 1
|
Shell
|
VictorVonFrankenstein/steeme
|
671257caec45ba52fbc17c2a13df81ab7628ef1c
|
88f2a55afa892b4790eec4a9691dceea5219f362
|
refs/heads/master
|
<file_sep>package com.example.j.notificationwithalarmmanagerexample;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Context context = this;
switch (item.getItemId()) {
case R.id.action_5:
NotificationUtils.scheduleNotification(context, "Scheduled Notification 1", "5 second delay", 5000);
return true;
case R.id.action_10:
NotificationUtils.scheduleNotification(context, "Scheduled Notification 2", "10 second delay", 10000);
return true;
case R.id.action_30:
NotificationUtils.scheduleNotification(context, "Scheduled Notification 3", "30 second delay", 30000);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
<file_sep>package com.example.j.notificationwithalarmmanagerexample;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.support.v7.app.NotificationCompat;
/**
* Created by J on 10/08/2017.
*/
public class NotificationUtils {
public static void scheduleNotification(Context context, String title, String content, int delay) {
int id_of_notification = 1;
Notification notification = generateNotification(context, title, content);
Intent notificationIntent = new Intent(context, NotificationPublisher.class);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, id_of_notification);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
long futureInMillis = SystemClock.elapsedRealtime() + delay;
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
// To cancel an alarm - pass the pending intent to cancel
//alarmManager.cancel(pendingIntent);
}
public static Notification generateNotification(Context context, String title, String content) {
Intent intent = new Intent(context, NotificationClickActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0,intent,0);
return new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(content)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentIntent(pIntent)
.setAutoCancel(true)
.build();
}
}
|
c8b1f529d98a880771daa370db9c6ec313b9aae7
|
[
"Java"
] | 2
|
Java
|
jasonbutwell/Android_AlarmManager_with_Notification
|
075ca35a6b05d0de8e68571d29b13820b8fe5eb8
|
9ca8b79d11f8097aaed4ff911ac3d3e51abea652
|
refs/heads/master
|
<file_sep>package com.meizhenhao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author 梅真好
* @company 京东商城(上海)
* @create 2019-01-08 15:07
*/
@Controller
@RequestMapping("/hi")
public class HiController {
@RequestMapping("/say")
public String say(Model model) {
model.addAttribute("username","张三");
return "say";
}
}
<file_sep># SpringMVCByIDEA
使用IDEA搭建SpringMVC项目的详细过程
|
d260cb833cb78256962f7dc8fa46214720a60bd4
|
[
"Markdown",
"Java"
] | 2
|
Java
|
meizhenhao/SpringMVCByIDEA
|
b426c735547105d65df9bfc897491951c15e701a
|
98af9de2c59cbf8543759eea86658e079dfc9fdd
|
refs/heads/master
|
<file_sep>package com.hust.jackeyang.weatherapp.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.hust.jackeyang.weatherapp.R;
import com.hust.jackeyang.weatherapp.db.WeatherDB;
import com.hust.jackeyang.weatherapp.util.HttpCallbackListener;
import com.hust.jackeyang.weatherapp.util.HttpUtil;
import com.hust.jackeyang.weatherapp.util.Utility;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jackeyang on 2016/6/20.
*/
public class ProvinceActivity extends Activity {
private ProgressDialog progressDialog = null;
private TextView title = null;
private ListView listView = null;
private ArrayAdapter<String> adapter = null;
private WeatherDB weatherDB;
private List<String> dataList = new ArrayList<>();
private List<String> provinceList = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.area_layout);
View empty_view = LayoutInflater.from(this).inflate(R.layout.listview_empty_view, null,
false);
listView = (ListView) findViewById(R.id.list_view);
listView.setEmptyView(empty_view);
title = (TextView) findViewById(R.id.txt_title);
weatherDB = WeatherDB.getInstance(getApplicationContext());
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String province = dataList.get(i);
CityActivity.actionStart(ProvinceActivity.this,province);
}
});
queryProvinces();
}
private void queryProvinces() {
provinceList = weatherDB.loadProvinces();
if (provinceList.size() > 0) {
dataList.clear();
for (String province : provinceList) {
dataList.add(province);
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
title.setText(getString(R.string.main_title));
}else{
queryFromServer(Utility.AREAINFO_ADDR);
}
}
private void queryFromServer(String address) {
showProgressDialog();
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
boolean result = Utility.handleAreaInfoResponse(weatherDB,response);
if (result) {
// 通过runOnUiThread()方法回到主线程处理逻辑
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
//重新查询省份信息
queryProvinces();
}
});
}
}
@Override
public void onError(Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(ProvinceActivity.this,"加载失败",Toast.LENGTH_SHORT).show();
}
});
}
});
}
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.loading));
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
private void closeProgressDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.cancel();
}
}
}
<file_sep># WeatherApp
this is used for querying weather from http://www.heweather.com/my/service
<file_sep>package com.hust.jackeyang.weatherapp.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.hust.jackeyang.weatherapp.R;
import com.hust.jackeyang.weatherapp.db.WeatherDB;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jackeyang on 2016/6/20.
*/
public class CityActivity extends Activity {
public static void actionStart(Context context, String province) {
Intent intent = new Intent(context, CityActivity.class);
intent.putExtra("province", province);
context.startActivity(intent);
}
String province = null;
TextView title = null;
ListView list = null;
List<String> city_list_data = new ArrayList<>();
List<String> cityList = null;
ArrayAdapter<String> adapter = null;
WeatherDB weatherDB = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.area_layout);
this.weatherDB = WeatherDB.getInstance(getApplicationContext());
this.title = (TextView) findViewById(R.id.txt_title);
this.list = (ListView) findViewById(R.id.list_view);
province = getIntent().getStringExtra("province");
this.title.setText(province);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, city_list_data);
this.list.setAdapter(adapter);
this.list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
WeatherActivity.actionStart(CityActivity.this,city_list_data.get(i));
}
});
queryCities();
}
private void queryCities() {
cityList = weatherDB.loadCities(province);
if (cityList.size() > 0) {
city_list_data.clear();
for (String city : cityList) {
city_list_data.add(city);
}
adapter.notifyDataSetChanged();
}
}
}
<file_sep>package com.hust.jackeyang.weatherapp.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.hust.jackeyang.weatherapp.R;
import com.hust.jackeyang.weatherapp.db.WeatherDB;
import com.hust.jackeyang.weatherapp.mode.Now;
import com.hust.jackeyang.weatherapp.mode.Weather;
import com.hust.jackeyang.weatherapp.util.HttpCallbackListener;
import com.hust.jackeyang.weatherapp.util.HttpUtil;
import com.hust.jackeyang.weatherapp.util.Utility;
/**
* Created by jackeyang on 2016/6/21.
*/
public class WeatherActivity extends Activity {
private String city = null;
private String code = null;
WeatherDB weatherDB = null;
Weather weatherInfo = null;
ImageView imageView = null;
TextView txt_desc = null;
TextView txt_publish_time = null;
TextView txt_city_title = null;
TextView txt_temperature = null;
TextView txt_wind = null;
Button btn_refresh = null;
private ProgressDialog progressDialog = null;
public static void actionStart(Context context, String city) {
Intent intent = new Intent(context, WeatherActivity.class);
intent.putExtra("city", city);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_weather);
this.city = getIntent().getStringExtra("city");
init();
queryWeather(city);
}
private void init() {
this.weatherDB = WeatherDB.getInstance(getApplicationContext());
this.imageView = (ImageView) findViewById(R.id.imageView);
this.txt_desc = (TextView) findViewById(R.id.txt_desc);
this.txt_publish_time = (TextView) findViewById(R.id.publish_time);
this.txt_city_title = (TextView) findViewById(R.id.txt_title);
this.txt_temperature = (TextView) findViewById(R.id.temperature);
this.txt_wind = (TextView) findViewById(R.id.wind);
this.btn_refresh = (Button) findViewById(R.id.refresh);
txt_city_title.setText(city);
}
private void showWeatherInfo(Weather weatherInfo) {
String updateTime = weatherInfo.getBasic().getUpdate().loc;
txt_publish_time.setText(updateTime);
String temperature = weatherInfo.getNow().getTmp();
txt_temperature.setText("现在气温:" + temperature + "度");
String windInfo = getWindInfo(weatherInfo.getNow().getWind());
txt_wind.setText(windInfo);
String desc = weatherInfo.getNow().getCond().txt;
txt_desc.setText(desc);
}
/**
* 请求天气数据
* @param city
*/
private void queryWeather(String city) {
if (!TextUtils.isEmpty(city)) {
showProgressDialog();
HttpUtil.sendHttpRequest(assembleAdder(city), new HttpCallbackListener() {
@Override
public void onFinish(String response) {
weatherInfo = Utility.handleWeatherInfoResponse(response);
//获取天气代码
code = weatherInfo.getNow().getCond().code;
//根据天气代码加载天气图标
loadWeatherIcon(imageView);
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
showWeatherInfo(weatherInfo);
}
});
}
@Override
public void onError(Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(WeatherActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
private void loadWeatherIcon(ImageView imageView) {
String icon_url = weatherDB.loadIconURL(code);
if (!TextUtils.isEmpty(icon_url)) {
HttpUtil.downLoadIcon(icon_url,imageView);
} else {
queryWeatherIconFromServer();
}
}
/**
* 完成天气代码的下载和保存
*/
private void queryWeatherIconFromServer() {
HttpUtil.sendHttpRequest(Utility.WEATHER_CODE_ADDR, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
boolean result = Utility.handleWeatherCodeResponse(weatherDB,response);
if (result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
loadWeatherIcon(imageView);
}
});
}
}
@Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
private String assembleAdder(String city) {
String address;
String city_ID = weatherDB.loadID(city);
address = Utility.WEATHER_ADDR + city_ID + "&key=" + Utility.KEY;
return address;
}
private String getWindInfo(Now.Wind wind) {
StringBuilder sb = new StringBuilder("");
sb.append(wind.dir).append(" ").append(wind.sc).append("级").append("\n").append("风速:")
.append(wind.spd);
return sb.toString();
}
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.loading));
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
private void closeProgressDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.cancel();
}
}
}
|
0956fc24fc864d3c8af30a04c7c28bf894f050ff
|
[
"Markdown",
"Java"
] | 4
|
Java
|
jackeyang/WeatherApp
|
e7217844e1276ece21c2e2b44f8f9e502c74b6dd
|
3f3350ee140e10971ca70f4a49e0d773db0d61fa
|
refs/heads/master
|
<file_sep>import android.content.Context
import android.net.ConnectivityManager
import android.util.Log
import com.camilink.alexgps.R
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.HttpURLConnection
import java.net.URL
class AppUtils {
companion object {
val TAG = "LEL"
fun checkInternet(c: Context): Boolean {
val conMgr = c.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val netInfo = conMgr.getActiveNetworkInfo()
if (netInfo != null && netInfo.isConnected()) {
//Log.i("checkInternet", "netInfo connected");
try {
val urlc = (URL(c.getString(R.string.util_serverConnTestUrl)).openConnection()) as HttpURLConnection
urlc.setRequestProperty("User-Agent", "Test")
urlc.setRequestProperty("Connection", "close")
urlc.setConnectTimeout(3000) //choose your own timeframe
urlc.setReadTimeout(4000) //choose your own timeframe
urlc.connect()
//Log.i("checkInternet", "Response is " + (urlc.getResponseCode()) + "");
return (urlc.getResponseCode() === 200)
} catch (e: IOException) {
//Log.i("checkInternet", "no Internet");
return (false) //connectivity exists, but no internet.
}
} else {
//Log.i("checkInternet", "netInfo NOT connected");
return false
}
}
fun makeUrlConnection(urls: String, postParams: String): String {
var result = ""
Log.d(TAG, "makeUrlConnection: URL:" + urls)
Log.d(TAG, "makeUrlConnection: postParams: " + postParams)
try {
val urlToRequest = URL(urls)
val urlConnection = urlToRequest.openConnection() as HttpURLConnection
urlConnection.setDoOutput(true)
urlConnection.setRequestMethod("POST")
//urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//urlConnection.setRequestProperty("Content-Type", "application/form-data");
//urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setConnectTimeout(30000)
urlConnection.setReadTimeout(30000)
urlConnection.setFixedLengthStreamingMode(
postParams.toByteArray().size)
val out = PrintWriter(urlConnection.getOutputStream())
out.print(postParams)
out.close()
Log.d(TAG, "makeUrlConnection: resCode: " + urlConnection.getResponseCode())
val inp = BufferedReader(
InputStreamReader(urlConnection.getInputStream()))
var inputLine: String
val response = StringBuilder()
inputLine = inp.readLine()
while (inputLine != null) {
response.append(inputLine)
inputLine = inp.readLine()
}
inp.close()
//print result
result = response.toString()
} catch (e: IOException) {
e.printStackTrace()
}
Log.d(TAG, "makeUrlConnection: result: " + result)
return result
}
}
}<file_sep>package com.camilink.alexgps
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.os.AsyncTask
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.activity_main.*
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.EasyPermissions
import android.location.LocationManager
import android.support.v4.content.ContextCompat
import android.util.Log
import android.telephony.TelephonyManager
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
companion object {
const val MY_PERMISSIONS_REQUEST_FINE_LOCATION_AND_PHONE = 1
const val TAG = "Acc"
}
var url: String = ""
var httpProt: String = ""
var port: Int = 0
lateinit var mContext: MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mContext = this@MainActivity
val httpArr = arrayOf("http://", "https://")
val httAdapter = ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, httpArr)
httAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item)
urlSp.adapter = httAdapter
}
fun onSendInfoClk(v: View?) {
onSendInfoClk()
}
@AfterPermissionGranted(MY_PERMISSIONS_REQUEST_FINE_LOCATION_AND_PHONE)
fun onSendInfoClk() {
val perms = arrayOf(Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION)
Log.d(TAG, "Granted: " + (ContextCompat.checkSelfPermission(mContext, perms[0]) == PackageManager.PERMISSION_GRANTED))
if (EasyPermissions.hasPermissions(this, *perms)) {
Log.d(TAG, "PermGranted... Sending")
sendInfo()
} else {
Log.d(TAG, "PermDenied... Asking")
EasyPermissions.requestPermissions(this, "Por favor añada los permisos",
MY_PERMISSIONS_REQUEST_FINE_LOCATION_AND_PHONE, *perms)
}
}
@SuppressLint("StaticFieldLeak")
fun sendInfo() {
url = urlTiet.text.toString()
if (url != "") {
httpProt = urlSp.selectedItem.toString()
port = portTiet.text.toString().toInt()
object : AsyncTask<Void, Int, Void?>() {
var thereIsInternet: Boolean = false
var postParams = ""
var resCode = 0
var result = ""
override fun onPreExecute() {
super.onPreExecute()
loadingTv.text = getText(R.string.util_checkInternet)
dataLl.visibility = View.GONE
loadingLl.visibility = View.VISIBLE
}
override fun onProgressUpdate(vararg values: Int?) {
super.onProgressUpdate(*values)
if (values[0] == 1) {
loadingTv.text = "Enviando información..."
} else if (values[0] == 2) {
postParamsEt.setText(postParams)
}
}
@SuppressLint("MissingPermission")
override fun doInBackground(vararg p0: Void): Void? {
thereIsInternet = AppUtils.checkInternet(mContext)
if (thereIsInternet) {
publishProgress(1)
var imei = ""
var phoneNumber = ""
val mTelephony = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (mTelephony.deviceId != null) {
imei = mTelephony.deviceId
phoneNumber = mTelephony.line1Number ?: ""
}
var keyword = "001"
val timestamp1 = SimpleDateFormat("yyMMddhhmmss").format(Date())
val timestamp2 = ""
val gpsActive = "F"//"L" if not active
val gpsActive2 = if (gpsActive == "F") "A" else "V"
val locationManager: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
val locationProvider = LocationManager.NETWORK_PROVIDER
val lastKnownLocation = locationManager.getLastKnownLocation(locationProvider)
val latVal = Math.abs(lastKnownLocation?.latitude ?: 0.toDouble())
val latOri = if (latVal >= 0) "N" else "S"
val lonVal = Math.abs(lastKnownLocation?.longitude ?: 0.toDouble())
val lonOri = if (lonVal >= 0) "E" else "W"
val speed = lastKnownLocation?.speed ?: 0.toFloat()
val direction = "0"
val altitude = lastKnownLocation?.altitude ?: 0.toDouble()
val accState = ""
val doorState = ""
val oilState1 = ""
val oilState2 = ""
val tempState = ""
postParams = "imei:" + imei +
"," + keyword +
"," + timestamp1 +
"," + phoneNumber +
"," + gpsActive +
"," + timestamp2 +
"," + gpsActive2 +
"," + latVal +
"," + latOri +
"," + lonVal +
"," + lonOri +
"," + speed +
"," + direction +
"," + altitude +
"," + accState +
"," + doorState +
"," + oilState1 +
"," + oilState2 +
"," + tempState + ";"
Log.d(TAG, postParams)
publishProgress(2)
val s = DatagramSocket()
val local = InetAddress.getByName(
//httpProt +
url)
val msg_length = postParams.length
val message = postParams.toByteArray()
val p = DatagramPacket(message, msg_length, local, port)
s.send(p)
}
return null
}
override fun onPostExecute(resu: Void?) {
super.onPostExecute(resu)
resCodeEt.setText("" + resCode)
responseEt.setText(result)
dataLl.visibility = View.VISIBLE
loadingLl.visibility = View.GONE
}
}.execute()
} else {
urlTiet.error = "Ingrese una URL"
}
}
}
|
ee51bfec55233e870349f74a084b6ab64521089a
|
[
"Kotlin"
] | 2
|
Kotlin
|
Camilink94/AlexGPSTest
|
cc84f66336fc662837f27fa753e8d22654076460
|
c3a8ce26582a47473a4a241dd1d16a45df6942ea
|
refs/heads/master
|
<file_sep>using System.Web.Mvc;
using BindingFun.ViewModels;
namespace BindingFun.Views
{
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new ViewModelBase() {Title = "Programming ASP.NET MVC"};
return View(model);
}
}
}
<file_sep>using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using RpcStyle.Common;
namespace RpcStyle
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ApiConfig.Setup(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}<file_sep>using FatFreeIoC.ViewModels.Home;
namespace FatFreeIoC.Services.Abstractions
{
public interface IHomeService
{
IndexViewModel GetIndexViewModel();
}
}<file_sep>using System.Web.Mvc;
public class FakeResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
return;
}
}<file_sep>using System.Web.Mvc;
using RpcStyle.ViewModels;
namespace RpcStyle.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new ViewModelBase();
return View(model);
}
}
}
<file_sep>using System;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
public class OptionalAuthenticationAttribute : FilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
var page = filterContext.ActionDescriptor.ActionName;
if (DateTime.Now.Millisecond % 2 == 0)
{
filterContext.Result = new HttpUnauthorizedResult();
return;
}
else
{
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
}
}<file_sep>using System;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
public class FormsAuthenticationAttribute : FilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
var user = filterContext.HttpContext.User;
if (user == null || !user.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Simplest.Models.Dto;
namespace Simplest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult News()
{
var client = new WebClient();
//client.Headers.Add("Accept", "text/xml");
var content = client.DownloadString("http://localhost:25708/api/news");
var serializer = new JavaScriptSerializer();
var listOfNews = serializer.Deserialize<IList<News>>(content);
return View(listOfNews);
}
}
}
<file_sep>using System;
using System.Diagnostics.Contracts;
using System.Web.Mvc;
using BindingFun.ViewModels.Binding;
namespace BindingFun.Controllers
{
public class BindingController : Controller
{
public ActionResult Repeat(String text, Int32 number)
{
//Contract.Requires<ArgumentException>(text.Length > 0);
//Contract.Requires<ArgumentException>(number > 0 && number < 10);
var model = new RepeatViewModel { Number = number, Text = text };
return View(model);
}
public ActionResult RepeatNull(String text, Int32? number)
{
var model = new RepeatViewModel { Number = number.GetValueOrDefault(), Text = text };
return View("repeat", model);
}
public ActionResult RepeatDefault(String text, Int32 number = 4)
{
var model = new RepeatViewModel { Number = number, Text = text };
return View("repeat", model);
}
public ActionResult RepeatWithPrecedence(String text, Int32 number = 20)
{
var model = new RepeatViewModel { Number = number, Text = text };
return View("repeat", model);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace BasicApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[OptionalAuthentication]
public ActionResult Index1()
{
// This method requires login only under certain runtime conditions.
return View();
}
//[Authorize]
[FormsAuthentication(Order = 1)]
[AddEmailAuthentication(Order = 2)]
public ActionResult Index2()
{
// This method requires requires login and first time also email
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
//protected override void OnAuthentication(System.Web.Mvc.Filters.AuthenticationContext filterContext)
//{
// var page = filterContext.ActionDescriptor.ActionName;
// if (page.ToLower() == "index1") //&& DateTime.Now.Millisecond % 2 == 0)
// {
// filterContext.Result = Index1();
// return;
// }
// base.OnAuthentication(filterContext);
//}
//protected override void OnAuthenticationChallenge(System.Web.Mvc.Filters.AuthenticationChallengeContext filterContext)
//{
// base.OnAuthenticationChallenge(filterContext);
//}
}
}<file_sep>using System.Web.Mvc;
using BookSamples.Components.Factories;
namespace FatFreeIoC.Common
{
public class ControllerConfig
{
public static void RegisterFactory(ControllerBuilder builder)
{
var factory = new UnityControllerFactory();
builder.SetControllerFactory(factory);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using FatFree.ViewModels.Shared;
namespace FatFree.ViewModels.Home
{
public class IndexViewModel : ViewModelBase
{
public String MessageFormat { get; set; }
public String Today { get; set; }
public IList<FeaturedDate> FeaturedDates { get; set; }
}
}<file_sep>using System.Collections.Generic;
using System.Web.Mvc;
using BookSamples.Components.Filters.Axpect;
namespace BookSamples.Components.Filters
{
public class DynamicLoadingFilterProvider : IFilterProvider
{
public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
return AxpectFramework.LoadFromConfigurationAsFilter(actionDescriptor);
}
}
}<file_sep>using System;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
namespace AnyProvider.Framework
{
public static class OpenIdRelyingPartyExtensions
{
public static Boolean IsValid(this OpenIdRelyingParty relyingParty, String url)
{
Identifier id;
var result = Identifier.TryParse(url, out id);
return result;
}
}
}<file_sep>using System;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
public class AddEmailAuthenticationAttribute : FilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
var user = filterContext.HttpContext.User;
if (user != null && user.Identity.IsAuthenticated)
{
var helper = new UrlHelper(filterContext.RequestContext);
var url = helper.Action("Contact", "Home");
filterContext.Result = new RedirectResult(url);
}
}
}<file_sep>using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.Mvc;
using EmbRes.ViewModels;
namespace EmbRes.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new ViewModelBase();
return View(model);
}
public Object Image(String name)
{
var bits = (Bitmap) HttpContext.GetGlobalResourceObject("AllResources", name);
Response.ContentType = "image/jpeg";
if (bits == null)
return null;
bits.Save(Response.OutputStream, ImageFormat.Jpeg);
return bits;
}
}
}
<file_sep>using System;
using System.Web.Mvc;
using BindingFun.ViewModels.Date;
using BookSamples.Components.Binders;
namespace BindingFun.Controllers
{
public class DateController : Controller
{
[HttpGet]
[ActionName("Editor")]
public ActionResult EditorForGet()
{
var model = new EditorViewModel();
return View(model);
}
[HttpPost]
[ActionName("Editor")]
public ActionResult EditorForPost(
[ModelBinder(typeof(DateModelBinder))]DateTime theDate)
{
// Local model-binder takes precedence over other matching binders
// defined in global.asax.
var model = new EditorViewModel();
if (theDate != default(DateTime))
{
model.DefaultDate = theDate;
model.TimeToToday = DateTime.Today.AddMonths(4).Subtract(theDate);
}
return View(model);
}
}
}
|
3e39e4947b0a92429ef470a201195deb6fee9f1a
|
[
"C#"
] | 17
|
C#
|
bradleyparlungun/mvc3
|
f66c89f7e69276e878c209ec752a9ead0dc6c9ad
|
a651c03fd1c9f6982d5d79d9fa944ddebfabead1
|
refs/heads/master
|
<repo_name>vinayak1986/hackerrank<file_sep>/bitwise_and.py
# The previous version of the code was fixed to address the code timeout issue in the first version.
# It ended up failing basic test cases on hackerrank. This version combines the approaches from
# the previous versions - looping through a in reverse and exiting the loop on a condition.
# The maximum possible value of k less than k is k - 1 and if we see this value in any a & b
# evaluation, we exit the inner loops and add the value to the final results list. If it is
# not encountered, we find the maximum of the other 'valid' (a & b less than k) values.
# This version passed all basic and hidden test cases on hackerrank and is the final submission.
if __name__ == '__main__':
t = int(input())
results = []
for t_itr in range(t):
found = 0
nk = input().split()
n = int(nk[0])
k = int(nk[1])
valid_a_and_b = []
for a in range(n - 1, 0, -1):
for b in range(a + 1, n + 1):
if (a & b) == k - 1:
results.append(str(a & b))
found = 1
break
if (a & b) < k:
valid_a_and_b.append((a & b))
if found == 1:
break
if not found:
results.append(str(max(valid_a_and_b)))
print('\n'.join(results))
<file_sep>/second_lowest.py
full_list = []
score_list = []
lowest_names = []
for _ in range(int(input())):
name = input()
score = float(input())
full_list.append([name, score])
score_list.append(score)
score_list = list(set(score_list))
score_list.sort()
second_lowest = score_list[1]
for score in full_list:
if score[1] == second_lowest:
lowest_names.append(score[0])
lowest_names.sort()
print("\n".join(lowest_names))
<file_sep>/nested_logic.py
# We check the conditions for no fine first - if the actual date of return
# is earlier than the expected date. If these are not met, we proceed to
# check for late returns and levy an appropriate fine as determined by
# the delay period.
if __name__ == "__main__":
actual_date = input().split(' ')
expected_date = input().split(' ')
actual_day, actual_month, actual_year = int(actual_date[0]), int(actual_date[1]), int(actual_date[2])
expected_day, expected_month, expected_year = int(expected_date[0]), int(expected_date[1]), int(expected_date[2])
if actual_year < expected_year:
fine = 0
elif (actual_year == expected_year) and (actual_month < expected_month):
fine = 0
elif (actual_month == expected_month) and (actual_day <= expected_day):
fine = 0
elif (actual_year == expected_year) and (actual_month == expected_month) and (actual_day > expected_day):
fine = (actual_day - expected_day) * 15
elif (actual_year == expected_year) and (actual_month > expected_month):
fine = (actual_month - expected_month) * 500
else:
fine = 10000
print(fine)
<file_sep>/README.md
March 19, 2019
The first commit has the initial versions of bitwise_and.py, second_lowest.py and exception.py.
March 19, 2019
Modified bitwise_and.py to fix the code timeout issue with the previous version. The previous version was inefficient
as it looped through all possible combinations of a and b to find valid values of (a & b < k) and then evaluated
the maximum of the running list to add to the results list. It passed the basic test cases as they involved small
numbers. It failed to scle up to the complete test cases due to its limitations.
March 19, 2019
Modified bitwise_and.py to fix the previous issues.
March 19, 2019
Added nested_logic.py
March 20, 2019
Added running_time.py
<file_sep>/running_time.py
# Check if a series of numbers are prime or not. We check for divisibility of
# numbers from 2 till n - 1 with n. If any of them is fully divisible, the number
# is not prime.
# The first version used a brute-force method to check for divisibility with all
# numbers. There are more efficient techniques available. The code has been
# re-written to implement the logic detailed here:
# https://en.wikipedia.org/wiki/Primality_test
def is_prime(num):
if num <= 3:
return num > 1
elif (num % 2 == 0) or (num % 3 == 0):
return False
i = 5
while i * i <= num:
if (num % i == 0) or (num % (i + 2) == 0):
return False
i = i + 6
return True
if __name__ == "__main__":
results = []
t = int(input())
for _ in range(t):
num = int(input())
if not is_prime(num):
results.append('Not prime')
else:
results.append('Prime')
print('\n'.join(results))
|
bfbd60118699ac064da8f960feb3632fdbccafe2
|
[
"Markdown",
"Python"
] | 5
|
Python
|
vinayak1986/hackerrank
|
c903a047cf3c52371b1901d1599e4e6826664726
|
402cca339fd899c656dae3f420cf1819f3953683
|
refs/heads/main
|
<repo_name>viranca/CS4240_Deep_Learning_Project<file_sep>/influence-aware-memory_Original_Work/Pipfile
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[packages]
glob2 = "==0.7"
pytest = "==5.2.1"
click = "==7.0"
statsmodels = "==0.10.1"
pandas = "==0.25.1"
colorama = "==0.4.1"
matplotlib = "==3.1.1"
networkx = "==2.3"
seaborn = "==0.9.0"
cloudpickle = "==1.2.2"
numpy = "==1.17.2"
filelock = "==3.0.12"
joblib = "==0.13.2"
opencv-python = "==4.1.1.26"
tensorflow = "==1.14.0"
scipy = "==1.3.1"
tqdm = "==4.36.1"
PyYAML = "==5.3.1"
Retro = "==2.9.0"
baselines = {path = "./baselines"}
sacred = "*"
pymongo = "*"
sshtunnel = "*"
gym = {extras = ["atari"], version = "*"}
pyqt5 = "==5.9.2"
gast = "==0.2.2"
jupyter = "*"
sklearn = "*"
scikit-image = "*"
scikit-learn = "==0.21.1"
[dev-packages]
[requires]
python_version = "3.7"
<file_sep>/influence-aware-memory_Original_Work/environments/warehouse/warehouse.py
from environments.warehouse.item import Item
from environments.warehouse.robot import Robot
from environments.warehouse.utils import *
import numpy as np
import copy
import random
from gym import spaces
import time
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import networkx as nx
import csv
class Warehouse(object):
"""
warehouse environment
"""
ACTIONS = {0: 'UP',
1: 'DOWN',
2: 'LEFT',
3: 'RIGHT'}
def __init__(self, seed, parameters):
# parameters = read_parameters('warehouse')
# parameters = parse_arguments()
self.n_columns = 7
self.n_rows = 7
self.n_robots_row = 1
self.n_robots_column = 1
self.distance_between_shelves = 6
self.robot_domain_size = [7, 7]
self.prob_item_appears = 0.05
# The learning robot
self.learning_robot_id = 0
self.max_episode_length = 100
self.render_bool = False
self.render_delay = 0.5
self.obs_type = 'vector'
self.items = []
self.img = None
# self.reset()
self.max_waiting_time = 8
self.total_steps = 0
self.parameters = parameters
self.reset()
self.seed(seed)
############################## Override ###############################
def reset(self):
"""
Resets the environment's state
"""
self.robot_id = 0
self._place_robots()
self.item_id = 0
self.items = []
self._add_items()
obs = self._get_observation()
if self.parameters['num_frames'] > 1:
self.prev_obs = np.zeros(self.parameters['obs_size']-len(obs))
obs = np.append(obs, self.prev_obs)
self.prev_obs = np.copy(obs)
self.episode_length = 0
return obs
def step(self, action):
"""
Performs a single step in the environment.
"""
self._robots_act([action])
self._increase_item_waiting_time()
reward = self._compute_reward(self.robots[self.learning_robot_id])
self._remove_items()
self._add_items()
obs = self._get_observation()
if self.parameters['num_frames'] > 1:
obs = np.append(obs, self.prev_obs[:-len(obs)])
self.prev_obs = np.copy(obs)
# Check whether learning robot is done
# done = self.robots[self.learning_robot_id].done
self.total_steps += 1
self.episode_length += 1
done = (self.max_episode_length <= self.episode_length)
if self.render_bool:
self.render(self.render_delay)
return obs, reward, done, []
@property
def observation_space(self):
return None
@property
def action_space(self):
"""
Returns A gym dict containing the number of action choices for all the
agents in the environment
"""
n_actions = spaces.Discrete(len(self.ACTIONS))
action_dict = {robot.get_id:n_actions for robot in self.robots}
action_space = spaces.Dict(action_dict)
action_space.n = 4
return action_space
def render(self, delay=0.0):
"""
Renders the environment
"""
bitmap = self._get_state()
position = self.robots[self.learning_robot_id].get_position
bitmap[position[0], position[1], 1] += 1
im = bitmap[:, :, 0] - 2*bitmap[:, :, 1]
if self.img is None:
fig,ax = plt.subplots(1)
self.img = ax.imshow(im, vmin=-2, vmax=1)
for robot_id, robot in enumerate(self.robots):
domain = robot.get_domain
y = domain[0]
x = domain[1]
color = 'k'
linestyle='-'
linewidth=2
rect1 = patches.Rectangle((x+0.5, y+0.5), self.robot_domain_size[0]-2,
self.robot_domain_size[1]-2, linewidth=linewidth,
edgecolor=color, linestyle=linestyle,
facecolor='none')
rect2 = patches.Rectangle((x-0.48, y-0.48), self.robot_domain_size[0]-0.02,
self.robot_domain_size[1]-0.02, linewidth=3,
edgecolor=color, linestyle=linestyle,
facecolor='none')
self.img.axes.get_xaxis().set_visible(False)
self.img.axes.get_yaxis().set_visible(False)
ax.add_patch(rect1)
ax.add_patch(rect2)
else:
self.img.set_data(im)
plt.pause(delay)
plt.draw()
def close(self):
pass
def seed(self, seed=None):
if seed is not None:
np.random.seed(seed)
######################### Private Functions ###########################
def _place_robots(self):
"""
Sets robots initial position at the begining of every episode
"""
self.robots = []
domain_rows = np.arange(0, self.n_rows, self.robot_domain_size[0]-1)
domain_columns = np.arange(0, self.n_columns, self.robot_domain_size[1]-1)
for i in range(self.n_robots_row):
for j in range(self.n_robots_column):
robot_domain = [domain_rows[i], domain_columns[j],
domain_rows[i+1], domain_columns[j+1]]
robot_position = [robot_domain[0] + self.robot_domain_size[0]//2,
robot_domain[1] + self.robot_domain_size[1]//2]
self.robots.append(Robot(self.robot_id, robot_position,
robot_domain))
self.robot_id += 1
def _add_items(self):
"""
Add new items to the designated locations in the environment which
need to be collected by the robots
"""
item_columns = np.arange(0, self.n_columns)
item_rows = np.arange(0, self.n_rows, self.distance_between_shelves)
item_locs = None
if len(self.items) > 0:
item_locs = [item.get_position for item in self.items]
for row in item_rows:
for column in item_columns:
loc = [row, column]
loc_free = True
if item_locs is not None:
loc_free = loc not in item_locs
if np.random.uniform() < self.prob_item_appears and loc_free:
self.items.append(Item(self.item_id, loc))
self.item_id += 1
item_rows = np.arange(0, self.n_rows)
item_columns = np.arange(0, self.n_columns, self.distance_between_shelves)
if len(self.items) > 0:
item_locs = [item.get_position for item in self.items]
for row in item_rows:
for column in item_columns:
loc = [row, column]
loc_free = True
if item_locs is not None:
loc_free = loc not in item_locs
if np.random.uniform() < self.prob_item_appears and loc_free:
self.items.append(Item(self.item_id, loc))
self.item_id += 1
def _get_state(self):
"""
Generates a 3D bitmap: First layer shows the location of every item.
Second layer shows the location of the robots.
"""
state_bitmap = np.zeros([self.n_rows, self.n_columns, 2], dtype=np.int)
for item in self.items:
item_pos = item.get_position
state_bitmap[item_pos[0], item_pos[1], 0] = 1 #item.get_waiting_time
for robot in self.robots:
robot_pos = robot.get_position
state_bitmap[robot_pos[0], robot_pos[1], 1] = 1
return state_bitmap
def _get_observation(self):
"""
Generates the individual observation for every robot given the current
state and the robot's designated domain.
"""
state = self._get_state()
observation = self.robots[self.learning_robot_id].observe(state, self.obs_type)
return observation
def _robots_act(self, actions):
"""
All robots take an action in the environment.
"""
for action,robot in zip(actions, self.robots):
robot.act(action)
def _compute_reward(self, robot):
"""
Computes reward for the learning robot.
"""
reward = 0
robot_pos = robot.get_position
robot_domain = robot.get_domain
for item in self.items:
item_pos = item.get_position
if robot_pos[0] == item_pos[0] and robot_pos[1] == item_pos[1]:
reward += 1
return reward
def _remove_items(self):
"""
Removes items collected by robots. Robots collect items by steping on
them
"""
for robot in self.robots:
robot_pos = robot.get_position
for item in self.items:
item_pos = item.get_position
if robot_pos[0] == item_pos[0] and robot_pos[1] == item_pos[1]:
self.items.remove(item)
elif item.get_waiting_time >= self.max_waiting_time:
self.items.remove(item)
def _increase_item_waiting_time(self):
"""
Increases items waiting time
"""
for item in self.items:
item.increase_waiting_time()
<file_sep>/influence-aware-memory_Original_Work/environments/warehouse/item.py
from numpy import ndarray
class Item():
"""
A task on the factory floor
"""
ID = 1 # to generate new task ids
def __init__(self, item_id, pos:ndarray):
"""
Initializes the item, places it at (0,0)
"""
self._pos = pos
self._id = item_id
self._waiting_time = 0
@property
def get_id(self):
"""
returns the task identifier
"""
return self._id
@property
def get_position(self):
"""
@return: (x,y) tuple with task position
"""
return self._pos
@property
def get_waiting_time(self):
"""
returns item's waiting time
"""
return self._waiting_time
def increase_waiting_time(self):
"""
increases item's waiting time by one
"""
self._waiting_time += 1
<file_sep>/influence-aware-memory_Original_Work/experimentor.py
import os
import tensorflow as tf
from PPO.PPOcontroller import PPOcontroller
from environments.vectorized_environment import VectorizedEnvironment
import argparse
import yaml
import time
import sacred
from sacred.observers import MongoObserver
import pymongo
from sshtunnel import SSHTunnelForwarder
class Experimentor(object):
"""
Creates experimentor object to store interact with the environment and
the agent and log results.
"""
def __init__(self, parameters, _run, seed):
"""
Initializes the experiment by extracting the parameters
@param parameters a dictionary with many obligatory elements
<ul>
<li> "env_type" (SUMO, atari, grid_world),
<li> algorithm (DQN, PPO)
<li> maximum_time_steps
<li> maximum_episode_time
<li> skip_frames
<li> save_frequency
<li> step
<li> episodes
and more TODO
</ul>
@param logger TODO what is it exactly? It must have the function
log_scalar(key, stat_mean, self.step[factor_i])
"""
self.parameters = parameters
self.path = self.generate_path(self.parameters)
self.generate_env(seed)
self.generate_controller(self.env.action_space(), _run)
self.train_frequency = self.parameters["train_frequency"]
tf.reset_default_graph()
def generate_path(self, parameters):
"""
Generate a path to store e.g. logs, models and plots. Check if
all needed subpaths exist, and if not, create them.
"""
path = self.parameters['name']
result_path = os.path.join("results", path)
model_path = os.path.join("models", path)
if not os.path.exists(result_path):
os.makedirs(result_path)
if not os.path.exists(model_path):
os.makedirs(model_path)
return path
def generate_env(self, seed):
"""
Create environment container that will interact with SUMO
"""
self.env = VectorizedEnvironment(self.parameters, seed)
def generate_controller(self, actionmap, run):
"""
Create controller that will interact with agents
"""
if self.parameters['algorithm'] == 'PPO':
self.controller = PPOcontroller(self.parameters, actionmap, run)
def print_results(self, info, n_steps=0):
"""
Prints results to the screen.
"""
if self.parameters['env_type'] == 'atari':
print(("Train step {} of {}".format(self.step,
self.maximum_time_steps)))
print(("-"*30))
print(("Episode {} ended after {} steps.".format(
self.controller.episodes,
info['l'])))
print(("- Total reward: {}".format(info['r'])))
print(("-"*30))
else:
print(("Train step {} of {}".format(self.step,
self.maximum_time_steps)))
print(("-"*30))
print(("Episode {} ended after {} steps.".format(
self.controller.episodes,
n_steps)))
print(("- Total reward: {}".format(info)))
print(("-"*30))
def run(self):
"""
Runs the experiment.
"""
self.maximum_time_steps = int(self.parameters["max_steps"])
print(self.maximum_time_steps)
self.step = max(self.parameters["iteration"], 0)
# reset environment
step_output = self.env.reset()
reward = 0
n_steps = 0
start = time.time()
while self.step < self.maximum_time_steps:
# Select the action to perform
get_actions_output = self.controller.get_actions(step_output)
# Increment step
self.controller.increment_step()
self.step += 1
# Get new state and reward given actions a
next_step_output = self.env.step(get_actions_output['action'],
step_output['obs'])
if self.parameters['mode'] == 'train':
# Store experiences in buffer.
self.controller.add_to_memory(step_output, next_step_output,
get_actions_output)
# Estimate the returns using value function when time
# horizon has been reached
self.controller.bootstrap(next_step_output)
if self.step % self.train_frequency == 0 and \
self.controller.full_memory():
self.controller.update()
step_output = next_step_output
if self.parameters['env_type'] == 'atari' and 'episode' in next_step_output['info'][0].keys():
end = time.time()
# print('Time: ', end - start)
start = end
self.print_results(next_step_output['info'][0]['episode'])
elif self.parameters['env_type'] != 'atari':
reward += next_step_output['reward'][0]
n_steps += 1
if next_step_output['done'][0]:
end = time.time()
# print('Time: ' , end - start)
start = end
self.print_results(reward, n_steps)
reward = 0
n_steps = 0
self.controller.write_summary()
# Tensorflow only stores a limited number of networks.
self.controller.save_graph()
self.env.close()
def get_parameters():
parser = argparse.ArgumentParser(description='RL')
parser.add_argument('--config', default=None, help='config file')
parser.add_argument('--scene', default=None, help='scene')
parser.add_argument('--flicker', action='store_true', help='flickering game')
args = parser.parse_args()
return args
def read_parameters(config_file):
with open(config_file) as file:
parameters = yaml.load(file, Loader=yaml.FullLoader)
return parameters['parameters']
def add_mongodb_observer():
"""
connects the experiment instance to the mongodb database
"""
# MONGO_HOST = 'TUD-tm2'
# MONGO_DB = 'influence-aware-memory'
# PKEY = '~/.ssh/id_rsa'
# global server
# try:
# print("Trying to connect to mongoDB '{}'".format(MONGO_DB))
# server = SSHTunnelForwarder(
# MONGO_HOST,
# ssh_pkey=PKEY,
# remote_bind_address=('127.0.0.1', 27017)
# )
# server.start()
# DB_URI = 'mongodb://localhost:{}/influence-aware-memory'.format(server.local_bind_port)
# # pymongo.MongoClient('127.0.0.1', server.local_bind_port)
# ex.observers.append(MongoObserver.create(DB_URI, db_name=MONGO_DB, ssl=False))
# print("Added MongoDB observer on {}.".format(MONGO_DB))
# except pymongo.errors.ServerSelectionTimeoutError as e:
# print(e)
print("ONLY FILE STORAGE OBSERVER ADDED")
from sacred.observers import FileStorageObserver
ex.observers.append(FileStorageObserver.create('saved_runs'))
ex = sacred.Experiment('influence-aware-memory')
ex.add_config('configs/default.yaml')
add_mongodb_observer()
@ex.automain
def main(parameters, seed, _run):
exp = Experimentor(parameters, _run, seed)
exp.run()
<file_sep>/influence-aware-memory_Original_Work/environments/warehouse/robot.py
import numpy as np
import networkx as nx
import random
class Robot():
"""
A robot on the warehouse
"""
ACTIONS = {'UP': 0,
'DOWN': 1,
'LEFT': 2,
'RIGHT': 3}
def __init__(self, robot_id, robot_position, robot_domain):
"""
@param pos tuple (x,y) with initial robot position.
Initializes the robot
"""
self._id = robot_id
self._pos = robot_position
self._robot_domain = robot_domain
self.items_collected = 0
self.done = False
self._graph = None
self._action_space = 4
self._action_mapping = {(-1, 0): self.ACTIONS.get('UP'),
(1, 0): self.ACTIONS.get('DOWN'),
(0, -1): self.ACTIONS.get('LEFT'),
(0, 1): self.ACTIONS.get('RIGHT')}
@property
def get_id(self):
"""
returns the robot identifier
"""
return self._id
@property
def get_position(self):
"""
@return: (x,y) array with current robot position
"""
return self._pos
@property
def get_domain(self):
return self._robot_domain
def observe(self, state, obs_type):
"""
Retrieve observation from envrionment state
"""
observation = state[self._robot_domain[0]: self._robot_domain[2]+1,
self._robot_domain[1]: self._robot_domain[3]+1, :]
if obs_type == 'image':
robot_loc = np.zeros_like(observation[:, :, 1])
robot_loc[self._pos[0] - self._robot_domain[0], self._pos[1] - self._robot_domain[1]] = 1
observation = observation[:,:,0] + -1*robot_loc
else:
item_vec = np.concatenate((observation[[0,-1], :, 0].flatten(),
observation[1:-1, [0,-1], 0].flatten()))
robot_loc = np.zeros_like(observation[:, :, 1])
robot_loc[self._pos[0] - self._robot_domain[0], self._pos[1] - self._robot_domain[1]] = 1
robot_loc = robot_loc.flatten()
observation = np.concatenate((robot_loc, item_vec))
return observation
def act(self, action):
"""
Take an action
"""
if action == 0:
new_pos = [self._pos[0] - 1, self._pos[1]]
if action == 1:
new_pos = [self._pos[0] + 1, self._pos[1]]
if action == 2:
new_pos = [self._pos[0], self._pos[1] - 1]
if action == 3:
new_pos = [self._pos[0], self._pos[1] + 1]
self.set_position(new_pos)
def set_position(self, new_pos):
"""
@param new_pos: an array (x,y) with the new robot position
"""
if self._robot_domain[0] <= new_pos[0] <= self._robot_domain[2] and \
self._robot_domain[1] <= new_pos[1] <= self._robot_domain[3]:
self._pos = new_pos
def select_random_action(self):
action = random.randint(0, self._action_space - 1)
return action
def select_naive_action(self, obs):
"""
Make one step towards the closest item
"""
if self._graph is None:
self._graph = self._create_graph(obs)
self._path_dict = dict(nx.all_pairs_dijkstra_path(self._graph))
path = self._path_to_closest_item(obs)
if path is None or len(path) < 2:
action = random.randint(0, self._action_space - 1)
else:
action = self._get_first_action(path)
return action
def _create_graph(self, obs):
"""
Creates a graph of robot's domain in the warehouse. Nodes are cells in
the robot's domain and edges represent the possible transitions.
"""
graph = nx.Graph()
for index, _ in np.ndenumerate(obs):
cell = np.array(index)
graph.add_node(tuple(cell))
for neighbor in self._neighbors(cell):
graph.add_edge(tuple(cell), tuple(neighbor))
return graph
def _neighbors(self, cell):
return [cell + [0, 1], cell + [0, -1], cell + [1, 0], cell + [-1, 0]]
def _path_to_closest_item(self, obs):
"""
Calculates the distance of every item in the robot's domain, finds the
closest item and returns the path to that item.
"""
min_distance = len(obs[:,0]) + len(obs[0,:])
closest_item_path = None
robot_pos = (self._pos[0]-self._robot_domain[0], self._pos[1]-self._robot_domain[1])
for index, item in np.ndenumerate(obs):
if item == 1:
path = self._path_dict[robot_pos][index]
distance = len(path) - 1
if distance < min_distance:
min_distance = distance
closest_item_path = path
return closest_item_path
def _get_first_action(self, path):
"""
Get first action to take in a given path
"""
delta = tuple(np.array(path[1]) - np.array(path[0]))
action = self._action_mapping.get(delta)
return action
<file_sep>/influence-aware-memory_Original_Work/model.py
import tensorflow as tf
import os
from networks import Networks as net
import tensorflow.contrib.layers as c_layers
import numpy as np
class Model(object):
"""
Creates a model object which can be used by any deep reinforcement learning
algorithm to configure the neural network architecture of choice.
"""
def __init__(self, parameters, num_actions):
self.act_size = num_actions
self.convolutional = parameters['convolutional']
self.recurrent = parameters['recurrent']
self.fully_connected = parameters['fully_connected']
self.influence = parameters['influence']
self.learning_rate = parameters['learning_rate']
self.max_step = parameters['max_steps']
self.graph = tf.Graph()
self.sess = tf.Session(graph=self.graph)
def initialize_graph(self):
"""
Initializes the weights in the Tensorflow graph
"""
with self.graph.as_default():
self.saver = tf.train.Saver()
init = tf.global_variables_initializer()
self.sess.run(init)
def save_graph(self, time_step):
"""
Retrieve network weights to store them.
"""
with self.graph.as_default():
file_name = os.path.join('models', self.parameters['name'],
'network')
print("Saving networks...")
self.saver.save(self.sess, file_name, time_step)
print("Saved!")
def load_graph(self):
"""
Load pretrained network weights.
"""
with self.graph.as_default():
self.saver = tf.train.Saver()
checkpoint_dir = os.path.join('models', self.parameters['name'])
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
self.saver.restore(self.sess, ckpt.model_checkpoint_path)
def build_main_model(self):
"""
Builds neural network model to approximate policy and value functions
"""
if self.parameters['obs_type'] == 'image':
self.observation = tf.placeholder(shape=[None,
self.parameters["frame_height"],
self.parameters["frame_width"],
self.parameters["num_frames"]],
dtype=tf.float32, name='observation')
else:
self.observation = tf.placeholder(shape=[None, self.parameters['obs_size']],
dtype=tf.float32, name='observation')
# normalize input
if self.parameters['env_type'] == 'atari':
self.observation = tf.cast(self.observation, tf.float32) / 255.
if self.convolutional:
self.feature_vector = net.cnn(self.observation,
self.parameters["num_conv_layers"],
self.parameters["num_filters"],
self.parameters["kernel_sizes"],
self.parameters["strides"],
tf.nn.relu, False, 'cnn')
network_input = c_layers.flatten(self.feature_vector)
else:
self.feature_vector = self.observation
network_input = self.feature_vector
if self.fully_connected:
hidden = net.fcn(network_input, self.parameters["num_fc_layers"],
self.parameters["num_fc_units"],
tf.nn.relu, 'fcn')
if self.recurrent:
self.prev_action = tf.placeholder(shape=[None], dtype=tf.int32,
name='prev_action')
self.prev_action_onehot = c_layers.one_hot_encoding(self.prev_action,
self.act_size)
# network_input = tf.concat([network_input, self.prev_action_onehot], axis=1)
c_in = tf.placeholder(tf.float32, [None,
self.parameters['num_rec_units']],
name='c_state')
h_in = tf.placeholder(tf.float32, [None,
self.parameters['num_rec_units']],
name='h_state')
self.seq_len = tf.placeholder(shape=None, dtype=tf.int32,
name='sequence_length')
self.state_in = tf.contrib.rnn.LSTMStateTuple(c_in, h_in)
hidden, self.state_out = net.rnn(network_input, self.state_in,
self.parameters['num_rec_units'],
self.seq_len,
'rnn')
self.hidden = hidden
def build_influence_model(self):
"""
Builds influence model
"""
def manual_dpatch(hidden):
"""
"""
inf_hidden = []
if self.parameters['obs_type'] == 'image':
for predictor in range(self.parameters['inf_num_predictors']):
center = np.array(self.parameters['inf_box_center'][predictor])
height = self.parameters['inf_box_height'][predictor]
width = self.parameters['inf_box_width'][predictor]
predictor_hidden = hidden[:, center[0]: center[0] + height,
center[1]: center[1] + width, :]
predictor_hidden = c_layers.flatten(predictor_hidden)
inf_hidden.append(predictor_hidden)
inf_hidden = tf.stack(inf_hidden, axis=1)
hidden_size = inf_hidden.get_shape().as_list()[2]*self.parameters['inf_num_predictors']
inf_hidden = tf.reshape(inf_hidden, shape=[-1, hidden_size])
else:
for predictor in range(self.parameters['inf_num_predictors']):
predictor_hidden = hidden[:, self.parameters['dset'][predictor]]
inf_hidden.append(predictor_hidden)
inf_hidden = tf.stack(inf_hidden, axis=1)
return inf_hidden
def automatic_dpatch(hidden):
"""
"""
if self.parameters['obs_type'] == 'image':
shape = hidden.get_shape().as_list()
num_regions = shape[1]*shape[2]
hidden = tf.reshape(hidden, [-1, num_regions, shape[3]])
inf_hidden = net.fcn(hidden, 1, self.parameters["inf_num_predictors"],
None, 'fcn_auto_dset')
# for predictor in range(self.parameters['inf_num_predictors']):
# name = "weights"+str(predictor)
# weights = tf.get_variable(name, shape=(num_regions,1), dtype=tf.dtypes.float32,
# initializer=tf.ones_initializer, trainable=True)
# softmax_weights = tf.contrib.distributions.RelaxedOneHotCategorical(0.1, weights)
# softmax_weights = tf.reshape(softmax_weights,[num_regions,1])
# softmax_weights = tf.nn.softmax(weights, axis=0)
# inf_hidden.append(tf.reduce_sum(softmax_weights*hidden, axis=1))
# inf_hidden = tf.stack(inf_hidden, axis=1)
hidden_size = inf_hidden.get_shape().as_list()[2]*self.parameters['inf_num_predictors']
inf_hidden = tf.reshape(inf_hidden, shape=[-1, hidden_size])
else:
inf_hidden = net.fcn(hidden, 1, self.parameters["inf_num_predictors"],
None, 'fcn_auto_dset')
# shape = hidden.get_shape().as_list()
# num_variables = shape[1]
# for predictor in range(self.parameters['inf_num_predictors']):
# name = "weights"+str(predictor)
# weights = tf.get_variable(name, shape=(1, num_variables), dtype=tf.dtypes.float32,
# initializer=tf.ones_initializer, trainable=True)
# softmax_weights = tf.nn.softmax(weights, axis=0)
# inf_hidden.append(tf.reduce_sum(softmax_weights*hidden, axis=1))
# inf_hidden = tf.stack(inf_hidden, axis=1)
return inf_hidden#, softmax_weights
def attention(hidden_conv, inf_hidden):
"""
"""
shape = hidden_conv.get_shape().as_list()
num_regions = shape[1]*shape[2]
hidden_conv = tf.reshape(hidden_conv, [-1, num_regions, shape[3]])
inf_hidden_vec = []
for head in range(self.parameters['num_heads']):
linear_conv = net.fcn(hidden_conv, 1,
self.parameters['num_att_units'], None,
'att', 'att1_'+str(head))
linear_hidden = net.fcn(inf_hidden, 1,
self.parameters['num_att_units'], None,
'att', 'att2_'+str(head))
context = tf.nn.tanh(linear_conv + tf.expand_dims(linear_hidden, 1))
attention_weights = net.fcn(context, 1, [1], None, 'att', 'att3_'+str(head))
attention_weights = tf.nn.softmax(attention_weights, axis=1)
d_patch = tf.reduce_sum(attention_weights*hidden_conv, axis=1)
inf_hidden_vec.append(tf.concat([d_patch, tf.reshape(attention_weights, shape=[-1, num_regions])], axis=1))
inf_hidden = tf.concat(inf_hidden_vec, axis=1)
return inf_hidden
def unroll(iter, state, hidden_states):#, softmax_weights):
"""
"""
hidden = tf.cond(self.update_bool,
lambda: tf.gather_nd(self.feature_vector,
self.indices+iter),
lambda: self.feature_vector)
inf_prev_action = tf.cond(self.update_bool,
lambda: tf.gather_nd(self.inf_prev_action,
self.indices+iter),
lambda: self.inf_prev_action)
inf_hidden = state.h
if self.parameters['attention']:
inf_hidden = attention(hidden, inf_hidden)
elif self.parameters['automatic_dpatch']:
inf_hidden = automatic_dpatch(hidden)
else:
inf_hidden = manual_dpatch(hidden)
inf_prev_action_onehot = c_layers.one_hot_encoding(inf_prev_action,
self.act_size)
# inf_hidden = tf.concat([inf_hidden, inf_prev_action_onehot], axis=1)
inf_hidden, state = net.rnn(inf_hidden, state,
self.parameters['inf_num_rec_units'],
self.inf_seq_len, 'inf_rnn')
hidden_states = hidden_states.write(iter, inf_hidden)
iter += 1
return [iter, state, hidden_states]#, softmax_weights]
def condition(iter, state, hidden_states):#, softmax_weights):
return tf.less(iter, self.n_iterations)
inf_c = tf.placeholder(tf.float32,
[None, self.parameters['inf_num_rec_units']],
name='inf_c_state')
inf_h = tf.placeholder(tf.float32,
[None, self.parameters['inf_num_rec_units']],
name='inf_h_state')
self.inf_state_in = tf.contrib.rnn.LSTMStateTuple(inf_c, inf_h)
self.inf_seq_len = tf.placeholder(tf.int32, None,
name='inf_sequence_length')
self.n_iterations = tf.placeholder(tf.int32, None,
name='n_iterations')
self.inf_prev_action = tf.placeholder(shape=[None], dtype=tf.int32,
name='inf_prev_action')
size = self.parameters['batch_size']*self.parameters['num_workers']
self.indices = np.arange(0, size, self.parameters['inf_seq_len'])
self.indices = tf.constant(np.reshape(self.indices, [-1, 1]),
dtype=tf.int32)
self.update_bool = tf.placeholder(tf.bool, [], name='update_bool')
# outputs of the loop cant change size, thus we need to initialize
# the hidden states vector and overwrite with new values
hidden_states = tf.TensorArray(dtype=tf.float32, size=self.n_iterations)
# softmax_weights = np.zeros((49, 1), dtype='f')
# Unroll the RNN to fetch intermediate internal states and compute
# attention weights
_, self.inf_state_out, hidden_states = tf.while_loop(condition,
unroll,
[0,
self.inf_state_in,
hidden_states])
# softmax_weights])
self.inf_hidden = hidden_states.stack()
self.inf_hidden = tf.reshape(tf.transpose(self.inf_hidden,
perm=[1,0,2]),
[-1, self.parameters['inf_num_rec_units']])
def build_optimizer(self):
"""
"""
raise NotImplementedError
def evaluate_policy(self):
"""
"""
raise NotImplementedError
def evaluate_value(self):
"""
"""
raise NotImplementedError
def increment_step(self):
"""
"""
self.sess.run(self.increment)
def get_current_step(self):
"""
"""
return self.sess.run(self.step)
<file_sep>/influence-aware-memory_Original_Work/environments/worker.py
import multiprocessing
import multiprocessing.connection
from baselines.common.atari_wrappers import make_atari, wrap_deepmind
from baselines import bench
from environments.warehouse.warehouse import Warehouse
from environments.sumo.LoopNetwork import LoopNetwork
import os
def worker_process(remote: multiprocessing.connection.Connection, parameters,
worker_id, seed):
"""
This function is used as target by each of the threads in the multiprocess
to build environment instances and define the commands that can be executed
by each of the workers.
"""
# The Atari wrappers are now imported from openAI baselines
# https://github.com/openai/baselines
log_dir = './log'
if parameters['env_type'] == 'atari':
env = make_atari(parameters['scene'])
env = bench.Monitor(
env,
os.path.join(log_dir, str(worker_id)),
allow_early_resets=False)
env = wrap_deepmind(env, True)
if parameters['env_type'] == 'warehouse':
env = Warehouse(seed, parameters)
if parameters['env_type'] == 'sumo':
env = LoopNetwork(parameters, seed)
while True:
cmd, data = remote.recv()
if cmd == 'step':
obs, reward, done, info = env.step(data)
if done:
obs = env.reset()
remote.send((obs, reward, done, info))
elif cmd == 'reset':
remote.send(env.reset())
elif cmd == 'action_space':
remote.send(env.action_space.n)
elif cmd == 'close':
remote.close()
break
else:
raise NotImplementedError
class Worker(object):
"""
Creates workers (actors) and starts single parallel threads in the
multiprocess. Commands can be send and outputs received by calling
child.send() and child.recv() respectively
"""
def __init__(self, parameters, worker_id, seed):
self.child, parent = multiprocessing.Pipe()
self.process = multiprocessing.Process(target=worker_process,
args=(parent, parameters,
worker_id, seed))
self.process.start()
<file_sep>/influence-aware-memory_Original_Work/environments/__init__.py
__all__ = ["SUMO_environment", "atari_environment", "grid_world_environment"]
<file_sep>/influence-aware-memory_Original_Work/networks.py
import tensorflow as tf
class Networks(object):
"""
Creates a network object that can be used to add different neural network
architectures to the Tensroflow graph. These are: Fully connected,
convolutional and recurrent neural networks.
"""
def fcn(input, num_fc_layers, num_fc_units, activation, scope='fcn',
name='fc_{}'):
"""
Builds a fully connected neural network
"""
with tf.variable_scope(scope):
hidden = input
for i in range(num_fc_layers):
hidden = tf.layers.dense(hidden, num_fc_units[i],
activation=activation,
use_bias=False,
name=name.format(i))
return hidden
def cnn(input, num_conv_layers, n_filters, kernel_sizes, strides,
activation, reuse, scope='cnn'):
"""
Builds a 2D convolutional neural network
"""
with tf.variable_scope(scope):
conv = input
# TODO: add this to parameters
for i in range(num_conv_layers):
conv = tf.layers.conv2d(conv, n_filters[i],
kernel_size=kernel_sizes[i],
strides=strides[i],
padding='valid',
activation=activation, reuse=reuse,
name='conv_{}'.format(i))
output = conv
return output
def rnn(input, state_in, num_rec_units, seq_len, scope='rnn'):
"""
Builds an LSTM recurrent neural network
"""
# TODO: find out how to generate a multiple layer LSTM network
with tf.variable_scope(scope):
s_size = input.get_shape().as_list()[1]
input = tf.reshape(input, shape=[-1, seq_len, s_size])
lstm_cell = tf.contrib.rnn.BasicLSTMCell(num_rec_units)
output, hidden_state = tf.nn.dynamic_rnn(lstm_cell, input,
initial_state=state_in,
dtype=tf.float32,
sequence_length=seq_len)
output = tf.reshape(output, [-1, num_rec_units])
return output, hidden_state
<file_sep>/influence-aware-memory_Original_Work/README.md
# Influence-aware Memory
Source code accompanying the paper "Influence-aware Memory Architectures for Deep Reinforcement Learning"
## Requirements
[Singularity](https://sylabs.io/docs/)
## Installation
Build Singularity container
```
sudo singularity build influence-aware-memory.sif influence-aware-memory.def
```
## Training models
```
singularity run influence-aware-memory.sif python experimentor.py with <path_to_config_file>
```
#### Example: Warehouse - IAM-manual
```
singularity run influence-aware-memory.sif python experimentor.py with ./configs/warehouse/IAM_manual.yaml
```
<file_sep>/influence-aware-memory_Original_Work/environments/sumo/LoopNetwork.py
from .SumoGymAdapter import SumoGymAdapter
import copy
class LoopNetwork(SumoGymAdapter):
__DEFAULT_PARAMETERS = {
'scene': 'loop_network_dumb',
'box_bottom_corner': [9, 9], #[10, 12],
'box_top_corner': [68, 68], #[66, 68],
'y_t': 6, # Yellow (traffic light) time
'resolutionInPixelsPerMeterX': 0.25,
'resolutionInPixelsPerMeterY': 0.25,
'car_tm': 6,
'state_type': 'ldm_state', # The type of state to use as input for the network. ('bin' (Position Matrix), 'bin_light' (Position Light Matrix), 'value' (Value Matrix))
'scaling_factor': 10,
'fast': False,
'speed_dev': 0.0, # Can be used to vary the speeds of cars, according to a normal distribution with mean 1 and standard deviation speed_dev (SUMOs default is 0.1)
'car_pr': 1.0,
'route_segments': ['L67 L68 L61 L62 L63 L64 L65 L66 L67 L68 L61 L62 L63 L64 L65 L66 L67 L68 L61 L62 L63 L64 L65 L66 L67 L68 L61 L62 L63 L64 L65 L66 L67 L68 L61 L62',
'L63 L64 L65 L66 L67 L68 L61 L62 L63 L64 L65 L66 L67 L68 L61 L62 L63 L64 L65 L66 L67 L68 L61 L62 L63 L64 L65 L66 L67 L68 L61 L62 L63 L64 L65 L66 L67 L68 L61 L62 L63 L64 L65 L66'],
'route_starts': [],
'route_ends': [],
'route_max_segments': 1,
'route_min_segments': 1,
'local_rewards': False,
'waiting_penalty': False,
'reward_type': 'waiting_time',
'lightPositions': {},#{"0": ((37.5,44.16), (39.2,44.16), (32.5,37.5), (32.5,39.16))},
'traffic_lights': False
}
def __init__(self, parameters, seed):
_parameters = copy.deepcopy(self._DEFAULT_PARAMETERS) # load default parameters of SUMOGymAdapter
_parameters.update(self.__DEFAULT_PARAMETERS) # load default parameters of GridSumoEnv
_parameters.update(parameters) # load parameters given by the user
super().__init__(_parameters, seed)
<file_sep>/influence-aware-memory_Original_Work/buffer.py
import numpy as np
import random
import pickle
class Buffer(dict):
"""
Dictionary to store transitions in.
"""
# NOTE: The replay memory is modified so that transitions are stored in a
# dictionary.
def __init__(self, parameters, act_size, separate=False):
"""
Initialize the memory with the right size.
"""
self.memory_size = parameters['memory_size']
self.batch_size = parameters['batch_size']
if parameters['influence']:
self.seq_len = parameters['inf_seq_len']
elif parameters['recurrent']:
self.seq_len = parameters['seq_len']
else:
self.seq_len = 1
def __getitem__(self, key):
if key not in self.keys():
self[key] = list()
return super(Buffer, self).__getitem__(key)
def sample(self, batch_size):
"""
Sample a batch from the dataset. This can be implemented in
different ways.
"""
raise NotImplementedError
def get_latest_entry(self):
"""
Retrieve the entry that has been added last. This can differ
between sequence en non-sequence samplers.
"""
raise NotImplementedError
def full(self):
"""
Check whether the replay memory has been filled.
"""
# TODO: returns are only calculated either when time horizon is reached
# or when the episode is over. When that happens all fields in replay_
# memory
# are the same size
# This means replay memory could
if 'returns' not in self.keys():
return False
else:
return len(self['returns']) >= self.memory_size
def store(self, path):
"""
Store the necessary information to recreate the replay memory.
"""
with open(path + 'buffer.pkl', 'wb') as f:
pickle.dump(self.buffer, f, pickle.HIGHEST_PROTOCOL)
def load(self, path):
"""
Load a stored replay memory.
"""
with open(path + 'replay_memory.pkl', 'rb') as f:
self.buffer = pickle.load(f)
def empty(self):
for key in self.keys():
self[key] = []
class SerialSampling(Buffer):
"""
Batches of experiences are sampled in a series one after the other.
This ensures all experiences are used the same number of times. Valid for
sequences or single experiences.
"""
def __init__(self, parameters, act_size):
"""
This is an instance of a plain Replay Memory object. It does not
need more information than its super class.
"""
super().__init__(parameters, act_size)
def sample(self, b, n_sequences, keys=None):
"""
"""
batch = {}
if keys is None:
keys = self.keys()
for key in keys:
batch[key] = []
for s in range(n_sequences):
start = s*self.seq_len + b*self.batch_size
end = (s+1)*self.seq_len + b*self.batch_size
batch[key].extend(self[key][start:end])
# permut dimensions workers-batch to mantain sequence order
axis = np.arange(np.array(batch[key]).ndim)
axis[0], axis[1] = axis[1], axis[0]
batch[key] = np.transpose(batch[key], axis)
return batch
def shuffle(self):
"""
"""
n = len(self['returns'])
# Only include complete sequences
# seq_len = 8
indices = np.arange(0, n - n % self.seq_len, self.seq_len)
random.shuffle(indices)
for key in self.keys():
shuffled_memory = []
for i in indices:
shuffled_memory.extend(self[key][i:i+self.seq_len])
self[key] = shuffled_memory
def get_last_entries(self, t, keys=None):
"""
"""
if keys is None:
keys = self.keys()
batch = {}
for key in keys:
batch[key] = self[key][-t:]
return batch
def zero_padding(self, missing, worker):
for key in self.keys():
if key not in ['advantages', 'returns']:
padding = np.zeros_like(self[key][-1])
for i in range(missing):
self[key].append(padding)
<file_sep>/influence-aware-memory_Original_Work/environments/warehouse/test.py
from warehouse import Warehouse
import numpy as np
warehouse = Warehouse()
warehouse.reset()
#################### Test _place_robots function ######################
for robot in warehouse.robots:
assert robot._robot_domain[0] <= robot.get_position[0] <= robot._robot_domain[2] and \
robot._robot_domain[1] <= robot.get_position[1] <= robot._robot_domain[3], \
'place robots test: failed. Robot {} is not within its designated domain'.format(robot.id)
print('place robots test: passed')
###################### Test _add_items function #######################
item_rows = np.arange(0, warehouse.n_rows, warehouse.distance_between_shelves)
for item in warehouse.items:
assert item.get_position[0] in item_rows, \
'add items test: failed. Item {} is not on a shelf'.format(item.id)
warehouse._add_items()
print('add items test: passed')
###################### Test remove_items function #####################
warehouse = Warehouse()
warehouse.reset()
pos = warehouse.items[0].get_position
warehouse.robots[0]._pos = pos
warehouse._remove_items()
state = warehouse._get_state()
assert state[pos[0],pos[1], 0] == 0, 'remove items test: failed'
print('remove items test: passed')
################### Test compute rewards function #####################
warehouse = Warehouse()
warehouse.reset()
learning_robot_id = warehouse.learning_robot_id
pos = warehouse.items[0].get_position
robot = warehouse.robots[learning_robot_id]
robot._pos = pos
n_items = robot.items_collected
reward = warehouse._compute_reward(robot)
assert reward == 1, 'compute rewards test: failed. Wrong reward'
assert robot.items_collected > n_items, \
'compute rewards: failed'
warehouse = Warehouse()
warehouse.reset()
robot = warehouse.robots[learning_robot_id]
pos = warehouse.items[0].get_position
robot._pos = pos
for i in range(warehouse.max_n_items):
warehouse._compute_reward(robot)
assert robot.done == True, \
'compute rewards test: failed. Agent is not done after max_n_items were collected'
print('compute rewards test: passed')
####################### Test action fucntion ##########################
warehouse = Warehouse()
warehouse.reset()
# action 0
initial_positions = []
for robot in warehouse.robots:
initial_positions.append(robot.get_position)
actions = dict(enumerate(np.zeros(len(warehouse.robots), dtype=np.int)))
warehouse.step(actions)
for robot, initial_position in zip(warehouse.robots, initial_positions):
assert robot.get_position[1] - 1 == initial_position[1], "action test: failed"
# action 1
initial_positions = []
for robot in warehouse.robots:
initial_positions.append(robot.get_position)
actions = dict(enumerate(np.ones(len(warehouse.robots), dtype=np.int)))
warehouse.step(actions)
for robot, initial_position in zip(warehouse.robots, initial_positions):
assert robot.get_position[1] + 1 == initial_position[1], "action test: failed"
# action 2
initial_positions = []
for robot in warehouse.robots:
initial_positions.append(robot.get_position)
actions = dict(enumerate(2*np.ones(len(warehouse.robots), dtype=np.int)))
warehouse.step(actions)
for robot, initial_position in zip(warehouse.robots, initial_positions):
assert robot.get_position[0] + 1 == initial_position[0], "action test: failed"
# action 3
initial_positions = []
for robot in warehouse.robots:
initial_positions.append(robot.get_position)
actions = dict(enumerate(3*np.ones(len(warehouse.robots), dtype=np.int)))
warehouse.step(actions)
for robot, initial_position in zip(warehouse.robots, initial_positions):
assert robot.get_position[0] - 1 == initial_position[0], "action test: failed"
print('action test: passed')
######################## Test action space #############################
warehouse = Warehouse()
warehouse.reset()
print(warehouse.action_space)
############################ Test graph ###############################
robot = warehouse.robots[1]
graph = warehouse._create_graph(robot)
breakpoint()
<file_sep>/influence-aware-memory_Original_Work/controller.py
import os
import tensorflow as tf
import numpy as np
class Controller(object):
"""
Controller object that interacts with all the agents in the system,
runs the coordination algorithms (in the multi-agent case), gets
agent's actions, passes the environment signals to the agents.
"""
def __init__(self, parameters: dict, action_map: dict, run):
"""
@param parameters a dictionary with all kinds of options for the run.
@param action_map a dict with factor index numbers (in the factorgraph) as keys
and a list of allowed actions as values
@param logger
"""
# Initialize all factor objects here
self.parameters = parameters
self.num_actions = {}
self.step = {}
tf.reset_default_graph()
self.step = 0
summary_path = 'summaries/' + self.parameters['name'] + '_' + \
self.parameters['scene'] + '_' + str(self.parameters['flicker'])
if not os.path.exists(summary_path):
os.makedirs(summary_path)
self.summary_writer = tf.summary.FileWriter(summary_path)
self.run = run
def get_actions(self, step_output, ip=None):
"""
Get each factor's action based on its local observation. Append the given
state to the factor's replay memory.
"""
evaluate_policy_output = {}
evaluate_policy_output.update(self.model.evaluate_policy(step_output['obs'],
step_output['prev_action']))
return evaluate_policy_output
def update(self):
"""
Sample a batch from the replay memory (if it is completely filled) and
use it to update the models.
"""
raise NotImplementedError
def full_memory(self):
"""
Check if the replay memories are filled.
"""
return self.buffer.full()
def save_graph(self):
"""
Store all the networks and replay memories.
"""
if self.step % self.parameters['save_frequency'] == 0:
# Create factor path if it does not exist.
path = os.path.join('models', self.parameters['name'],
self.parameters['scene'],
str(self.parameters['flicker']))
if not os.path.exists(path):
os.makedirs(path)
self.model.save_graph(self.step)
# TODO: replay memory
def store_memory(self, path):
# Create factor path if it does not exist.
path = os.path.join(os.environ['APPROXIMATOR_HOME'], path)
if not os.path.exists(path):
os.makedirs(path)
# Store the replay memory
self.buffer.store(path)
def increment_step(self):
self.model.increment_step()
self.step = self.model.get_current_step()
def write_summary(self):
"""
Saves training statistics to Tensorboard.
"""
if self.step % self.parameters['summary_frequency'] == 0 and \
self.parameters['tensorboard']:
summary = tf.Summary()
for key in self.stats.keys():
if len(self.stats[key]) > 0:
stat_mean = float(np.mean(self.stats[key]))
summary.value.add(tag='{}'.format(key), simple_value=stat_mean)
self.run.log_scalar('{}'.format(key), stat_mean, self.step)
self.stats[key] = []
self.summary_writer.add_summary(summary, self.step)
self.summary_writer.flush()
<file_sep>/influence-aware-memory_Original_Work/PPO/PPOmodel.py
import tensorflow as tf
import tensorflow.contrib.layers as c_layers
from networks import Networks as net
from model import Model
import numpy as np
import time
class PPOmodel(Model):
"""
Creates a PPOmodel object which builds a graph in Tensorflow that consists
of the neural network model and the set of operations to optimize the
network using Proximal Policy Optimization https://arxiv.org/abs/1707.06347.
It also contains methods that call Tensorflow for inference and to update
the model.
"""
def __init__(self, parameters, num_actions):
super().__init__(parameters, num_actions)
self.parameters = parameters
self.beta = parameters['beta']
self.epsilon = parameters['epsilon']
with self.graph.as_default():
self.step = tf.Variable(0, name="global_step",
trainable=False, dtype=tf.int32)
self.increment = tf.assign(self.step,
tf.add(self.step, 1))
self.build_main_model()
if self.influence:
self.build_influence_model()
self.build_actor_critic()
self.build_ppo_optimizer()
self.reset_state_in()
if self.parameters['load']:
self.load_graph()
else:
self.initialize_graph()
self.forward_pass_times = []
self.backward_pass_times = []
def build_actor_critic(self):
"""
Adds actor and critic heads to Tensorflow graph
"""
if self.influence:
hidden = tf.concat([self.hidden, self.inf_hidden], axis=1)
else:
hidden = self.hidden
self.logits = tf.layers.dense(hidden, self.act_size,
activation=None, use_bias=False,
kernel_initializer=
c_layers.variance_scaling_initializer(
factor=0.01))
self.action_probs = tf.nn.softmax(self.logits, name="action_probs")
self.action = tf.reduce_sum(tf.multinomial(self.logits, 1), axis=1)
self.action = tf.identity(self.action, name="action")
self.value = tf.reduce_sum(tf.layers.dense(hidden, 1, activation=None),
axis=1)
self.value = tf.identity(self.value, name="value_estimate")
self.entropy = -tf.reduce_sum(self.action_probs
* tf.log(self.action_probs + 1e-10),
axis=1)
self.action_holder = tf.placeholder(shape=[None], dtype=tf.int32,
name='action_holder')
self.actions_onehot = c_layers.one_hot_encoding(self.action_holder,
self.act_size)
self.old_action_probs = tf.placeholder(shape=[None, self.act_size],
dtype=tf.float32,
name='old_probs')
self.action_prob = tf.reduce_sum(self.action_probs*self.actions_onehot,
axis=1)
self.old_action_prob = tf.reduce_sum(self.old_action_probs
* self.actions_onehot, axis=1)
def build_ppo_optimizer(self):
"""
Adds optimization operations to Tensorflow graph
"""
decay_epsilon = tf.train.polynomial_decay(self.parameters["epsilon"],
self.step,
self.parameters["max_steps"],
1e-5, power=1.0)
# Ignore sequence padding
self.mask_input = tf.placeholder(shape=[None], dtype=tf.float32,
name='masks')
self.masks = tf.cast(self.mask_input, tf.int32)
# Value function optimizer
self.returns = tf.placeholder(shape=[None], dtype=tf.float32,
name='return')
self.old_values = tf.placeholder(shape=[None], dtype=tf.float32,
name='old_values')
clipped_value_estimate = self.old_values + \
tf.clip_by_value(self.value - self.old_values, -decay_epsilon,
decay_epsilon)
v1 = tf.squared_difference(self.returns, self.value)
v2 = tf.squared_difference(self.returns, clipped_value_estimate)
self.value_loss = tf.reduce_mean(tf.dynamic_partition(tf.maximum(v1, v2),
self.masks, 2)[1])
# Policy optimizer
self.advantages = tf.placeholder(shape=[None], dtype=tf.float32,
name='advantages')
importance = self.action_prob / (self.old_action_prob + 1e-10)
p1 = importance * self.advantages
p2 = tf.clip_by_value(importance, 1.0 - decay_epsilon,
1.0 + decay_epsilon) * self.advantages
self.policy_loss = -tf.reduce_mean(tf.dynamic_partition(tf.minimum(p1, p2),
self.masks, 2)[1])
# Entropy bonus
self.entropy_bonus = tf.reduce_mean(tf.dynamic_partition(self.entropy,
self.masks, 2)[1])
decay_beta = tf.train.polynomial_decay(self.parameters["beta"],
self.step,
self.parameters["max_steps"],
1e-2, power=1.0)
# Loss function
self.loss = self.policy_loss + self.parameters['c1']*self.value_loss - \
decay_beta*self.entropy_bonus
self.learning_rate = tf.train.polynomial_decay(self.parameters["learning_rate"],
self.step,
self.parameters["max_steps"],
1e-10, power=1.0)
optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)
self.update = optimizer.minimize(self.loss)
def evaluate_policy(self, observation, prev_action):
"""
Evaluates policy given current observation and previous action
"""
feed_dict = {self.observation: observation}
run_dict = {'action': self.action, 'value': self.value,
'action_probs': self.action_probs, 'entropy': self.entropy,
'learning_rate': self.learning_rate, 'hidden_x': self.hidden}
if self.recurrent:
feed_dict[self.state_in] = self.state_in_value
feed_dict[self.seq_len] = 1
feed_dict[self.prev_action] = prev_action
run_dict['state_out'] = self.state_out
if self.influence:
feed_dict[self.inf_state_in] = self.inf_state_in_value
feed_dict[self.inf_seq_len] = 1
feed_dict[self.n_iterations] = 1
feed_dict[self.inf_prev_action] = prev_action
feed_dict[self.update_bool] = False
run_dict['inf_state_out'] = self.inf_state_out
start = time.time()
output_list = self.sess.run(list(run_dict.values()),
feed_dict=feed_dict)
end = time.time()
self.forward_pass_times.append(end-start)
output_dict = dict(zip(list(run_dict.keys()), output_list))
if self.recurrent:
output_dict['state_in'] = self.state_in_value
self.state_in_value = output_dict['state_out']
if self.influence:
output_dict['inf_state_in'] = self.inf_state_in_value
self.inf_state_in_value = output_dict['inf_state_out']
return output_dict
def evaluate_value(self, observation, prev_action):
"""
Evaluates value given current observation and previous action
"""
feed_dict = {self.observation: observation}
run_dict = {'value': self.value}
if self.recurrent:
feed_dict[self.state_in] = self.state_in_value
feed_dict[self.seq_len] = 1
feed_dict[self.prev_action] = prev_action
if self.influence:
feed_dict[self.inf_state_in] = self.inf_state_in_value
feed_dict[self.inf_seq_len] = 1
feed_dict[self.n_iterations] = 1
feed_dict[self.inf_prev_action] = prev_action
feed_dict[self.update_bool] = False
output_list = self.sess.run(list(run_dict.values()),
feed_dict=feed_dict)
output_dict = dict(zip(list(run_dict.keys()), output_list))
return output_dict
def update_model(self, batch):
"""
Updates model using experiences stored in buffer
"""
if self.parameters['obs_type'] == 'image':
obs = np.reshape(batch['obs'], [-1, self.parameters['frame_height'],
self.parameters['frame_width'],
self.parameters['num_frames']])
else:
obs = np.reshape(batch['obs'], [-1, self.parameters['obs_size']])
feed_dict = {self.observation: obs,
self.returns: np.reshape(batch['returns'], -1),
self.old_values: np.reshape(batch['values'], -1),
self.old_action_probs: np.reshape(batch['action_probs'],
[-1, self.act_size]),
self.advantages: np.reshape(batch['advantages'], -1),
self.action_holder: np.reshape(batch['actions'], -1),
self.mask_input: np.reshape(batch['masks'], -1)}
if self.recurrent:
start_sequence_idx = np.arange(0, np.shape(batch['states_in'])[1],
self.parameters['seq_len'])
state_in = np.array(batch['states_in'])[:, start_sequence_idx, :, :]
c_in = np.reshape(state_in[:, :, 0, :],
[-1, self.parameters['num_rec_units']])
h_in = np.reshape(state_in[:, :, 1, :],
[-1, self.parameters['num_rec_units']])
state_in = (c_in, h_in)
feed_dict[self.state_in] = state_in
feed_dict[self.seq_len] = self.parameters['seq_len']
feed_dict[self.prev_action] = np.reshape(batch['prev_actions'], -1)
if self.influence:
start_sequence_idx = np.arange(0, np.shape(batch['inf_states_in'])[1],
self.parameters['inf_seq_len'])
state_in = np.array(batch['inf_states_in'])[:,
start_sequence_idx, :, :]
c_in = np.reshape(state_in[:, :, 0, :],
[-1, self.parameters['inf_num_rec_units']])
h_in = np.reshape(state_in[:, :, 1, :],
[-1, self.parameters['inf_num_rec_units']])
inf_state_in = (c_in, h_in)
feed_dict[self.inf_state_in] = inf_state_in
feed_dict[self.inf_seq_len] = 1
feed_dict[self.n_iterations] = self.parameters['inf_seq_len']
feed_dict[self.inf_prev_action] = np.reshape(batch['inf_prev_actions'], -1)
feed_dict[self.update_bool] = True
run_dict = {'value_loss': self.value_loss,
'policy_loss': self.policy_loss,
'loss': self.loss,
'update': self.update,
'learning_rate': self.learning_rate}
# 'softmax_weights': self.softmax_weights}
start = time.time()
output_list = self.sess.run(list(run_dict.values()),
feed_dict=feed_dict)
output_dict = dict(zip(list(run_dict.keys()), output_list))
end = time.time()
self.backward_pass_times.append(end-start)
# breakpoint()
# print(np.max(output_dict['softmax_weights']))
# print(np.argmax(output_dict['softmax_weights']))
return output_dict
def reset_state_in(self, worker=None):
"""
Initialize internal state of recurrent networks to zero
"""
if worker is None:
if self.recurrent:
c_init = np.zeros((self.parameters['num_workers'],
self.parameters['num_rec_units']),
np.float32)
h_init = np.zeros((self.parameters['num_workers'],
self.parameters['num_rec_units']),
np.float32)
self.state_in_value = (c_init, h_init)
if self.influence:
c_init = np.zeros((self.parameters['num_workers'],
self.parameters['inf_num_rec_units']),
np.float32)
h_init = np.zeros((self.parameters['num_workers'],
self.parameters['inf_num_rec_units']),
np.float32)
self.inf_state_in_value = (c_init, h_init)
else:
if self.recurrent:
c_init = np.zeros(self.parameters['num_rec_units'],
np.float32)
h_init = np.zeros(self.parameters['num_rec_units'],
np.float32)
self.state_in_value[0][worker] = c_init
self.state_in_value[1][worker] = h_init
if self.influence:
c_init = np.zeros(self.parameters['inf_num_rec_units'],
np.float32)
h_init = np.zeros(self.parameters['inf_num_rec_units'],
np.float32)
self.inf_state_in_value[0][worker] = c_init
self.inf_state_in_value[1][worker] = h_init
<file_sep>/influence-aware-memory_Original_Work/PPO/PPOcontroller.py
from controller import Controller
from PPO.PPOmodel import PPOmodel
from buffer import SerialSampling
import numpy as np
class PPOcontroller(Controller):
"""
Creates PPOController object and can be used to add new experiences to the
buffer, calculate advantages and returns and update the agent's policy.
"""
def __init__(self, parameters, action_map, run):
self.parameters = parameters
self.num_actions = action_map
self.model = PPOmodel(self.parameters,
self.num_actions)
self.buffer = SerialSampling(self.parameters,
self.num_actions)
self.cumulative_rewards = 0
self.episode_step = 0
self.episodes = 0
self.t = 0
self.stats = {"cumulative_rewards": [],
"episode_length": [],
"value": [],
"learning_rate": [],
"entropy": [],
"policy_loss": [],
"value_loss": []}
super().__init__(self.parameters, action_map, run)
if self.parameters['influence']:
self.seq_len = self.parameters['inf_seq_len']
elif self.parameters['recurrent']:
self.seq_len = self.parameters['seq_len']
else:
self.seq_len = 1
def add_to_memory(self, step_output, next_step_output, get_actions_output):
"""
Append the last transition to buffer and to stats
"""
self.buffer['obs'].append(step_output['obs'])
self.buffer['rewards'].append(next_step_output['reward'])
self.buffer['dones'].append(next_step_output['done'])
self.buffer['actions'].append(get_actions_output['action'])
self.buffer['values'].append(get_actions_output['value'])
self.buffer['action_probs'].append(get_actions_output['action_probs'])
# This mask is added so we can ignore experiences added when
# zero-padding incomplete sequences
self.buffer['masks'].append([1]*self.parameters['num_workers'])
self.cumulative_rewards += next_step_output['reward'][0]
self.episode_step += 1
self.stats['value'].append(get_actions_output['value'][0])
self.stats['entropy'].append(get_actions_output['entropy'][0])
self.stats['learning_rate'].append(get_actions_output['learning_rate'])
# Note: States out is used when updating the network to feed the
# initial state of a sequence. In PPO this internal state will not
# differ that much from the current one. However for DQN we might
# rather set the initial state as zeros like in Jinke's
# implementation
if self.parameters['recurrent']:
self.buffer['states_in'].append(
np.transpose(get_actions_output['state_in'], (1,0,2)))
self.buffer['prev_actions'].append(step_output['prev_action'])
if self.parameters['influence']:
self.buffer['inf_states_in'].append(
np.transpose(get_actions_output['inf_state_in'], (1,0,2)))
self.buffer['inf_prev_actions'].append(step_output['prev_action'])
if next_step_output['done'][0] and self.parameters['env_type'] != 'atari':
self.episodes += 1
self.stats['cumulative_rewards'].append(self.cumulative_rewards)
self.stats['episode_length'].append(self.episode_step)
self.cumulative_rewards = 0
self.episode_step = 0
if self.parameters['env_type'] == 'atari' and 'episode' in next_step_output['info'][0].keys():
# The line below is due to live episodes in the openai baselines atari_wrapper
self.episodes += 1
self.stats['cumulative_rewards'].append(next_step_output['info'][0]['episode']['r'])
self.stats['episode_length'].append(self.episode_step)
self.cumulative_rewards = 0
self.episode_step = 0
if self.parameters['recurrent'] or self.parameters['influence']:
for worker, done in enumerate(next_step_output['done']):
if done and self.parameters['num_workers'] != 1:
# reset worker's internal state
self.model.reset_state_in(worker)
# zero padding incomplete sequences
remainder = len(self.buffer['masks']) % self.seq_len
# NOTE: we need to zero-pad all workers to keep the
# same buffer dimensions even though only one of them has
# reached the end of the episode.
if remainder != 0:
missing = self.seq_len - remainder
self.buffer.zero_padding(missing, worker)
self.t += missing
# NETWORK ARCHITECTURE ANALYSIS
# if self.parameters['analyze_hidden']:
# # write to file
# obs_flatten = np.ndarray.flatten(step_output['obs'][0])
# with open('analysis/observation3.txt', 'a') as obs_file:
# np.savetxt(obs_file, obs_flatten.reshape(1, obs_flatten.shape[0]), delimiter=',')
# hidden_x = get_actions_output['hidden_x'][0]
# with open('analysis/hidden_x.txt', 'a') as hidden_file:
# np.savetxt(hidden_file, hidden_x.reshape(1, hidden_x.shape[0]), delimiter=',')
# hidden_memory = np.concatenate(np.transpose(get_actions_output['inf_state_in'], (1,0,2))[0])
# hidden_memory = hidden_memory[:hidden_memory.shape[0]//2]
# with open('analysis/hidden_d.txt', 'a') as hidden_file:
# np.savetxt(hidden_file, hidden_memory.reshape(1, hidden_memory.shape[0]), delimiter=',')
def bootstrap(self, next_step_output):
"""
Computes GAE and returns for a given time horizon
"""
# TODO: consider the case where the episode is over because the maximum
# number of steps in an episode has been reached.
self.t += 1
if self.t >= self.parameters['time_horizon']:
evaluate_value_output = self.model.evaluate_value(
next_step_output['obs'],
next_step_output['prev_action'])
next_value = evaluate_value_output['value']
batch = self.buffer.get_last_entries(self.t, ['rewards', 'values',
'dones'])
advantages = self._compute_advantages(np.array(batch['rewards']),
np.array(batch['values']),
np.array(batch['dones']),
next_value,
self.parameters['gamma'],
self.parameters['lambda'])
self.buffer['advantages'].extend(advantages)
returns = advantages + batch['values']
self.buffer['returns'].extend(returns)
self.t = 0
def update(self):
"""
Runs multiple epoch of mini-batch gradient descent to update the model
using experiences stored in buffer.
"""
policy_loss = 0
value_loss = 0
n_sequences = self.parameters['batch_size'] // self.seq_len
n_batches = self.parameters['memory_size'] // \
self.parameters['batch_size']
import time
start = time.time()
for e in range(self.parameters['num_epoch']):
self.buffer.shuffle()
for b in range(n_batches):
batch = self.buffer.sample(b, n_sequences)
update_model_output = self.model.update_model(batch)
policy_loss += update_model_output['policy_loss']
value_loss += update_model_output['value_loss']
self.buffer.empty()
self.stats['policy_loss'].append(np.mean(policy_loss))
self.stats['value_loss'].append(np.mean(value_loss))
end = time.time()
print('Time Update: ', end-start)
def _compute_advantages(self, rewards, values, dones, last_value, gamma,
lambd):
"""
Calculates advantages using genralized advantage estimation (GAE)
"""
last_advantage = 0
advantages = np.zeros((self.parameters['time_horizon'],
self.parameters['num_workers']),
dtype=np.float32)
for t in reversed(range(self.parameters['time_horizon'])):
mask = 1.0 - dones[t, :]
last_value = last_value*mask
last_advantage = last_advantage*mask
delta = rewards[t, :] + gamma*last_value - values[t, :]
last_advantage = delta + gamma*lambd*last_advantage
advantages[t, :] = last_advantage
last_value = values[t, :]
return advantages<file_sep>/influence-aware-memory_Original_Work/environments/vectorized_environment.py
from environments.worker import Worker
import multiprocessing as mp
import numpy as np
import random
class VectorizedEnvironment(object):
"""
Creates multiple instances of an environment to run in parallel.
Each of them contains a separate worker (actor) all of them following
the same policy
"""
def __init__(self, parameters, seed):
print('cpu count', mp.cpu_count())
if parameters['num_workers'] < mp.cpu_count():
self.num_workers = parameters['num_workers']
else:
self.num_workers = mp.cpu_count()
# Random seed needs to be set different for each worker (seed + worker_id). Otherwise multiprocessing takes
# the current system time, which is the same for all workers!
self.workers = [Worker(parameters, worker_id, seed + worker_id) for worker_id in range(self.num_workers)]
self.parameters = parameters
self.env = parameters['env_type']
def reset(self):
"""
Resets each of the environment instances
"""
for worker in self.workers:
worker.child.send(('reset', None))
output = {'obs': [], 'prev_action': []}
for worker in self.workers:
obs = worker.child.recv()
if self.env == 'atari':
stacked_obs = np.zeros((self.parameters['frame_height'],
self.parameters['frame_width'],
self.parameters['num_frames']))
stacked_obs[:, :, 0] = obs[:, :, 0]
obs = stacked_obs
output['obs'].append(obs)
output['prev_action'].append(-1)
return output
def step(self, actions, prev_stacked_obs):
"""
Takes an action in each of the enviroment instances
"""
for worker, action in zip(self.workers, actions):
worker.child.send(('step', action))
output = {'obs': [], 'reward': [], 'done': [], 'prev_action': [],
'info': []}
i = 0
for worker in self.workers:
obs, reward, done, info = worker.child.recv()
if self.parameters['flicker']:
p = 0.5
prob_flicker = random.uniform(0, 1)
if prob_flicker > p:
obs = np.zeros_like(obs)
if self.env == 'atari':
new_stacked_obs = np.zeros((self.parameters['frame_height'],
self.parameters['frame_width'],
self.parameters['num_frames']))
new_stacked_obs[:, :, 0] = obs[:, :, 0]
new_stacked_obs[:, :, 1:] = prev_stacked_obs[i][:, :, :-1]
obs = new_stacked_obs
output['obs'].append(obs)
output['reward'].append(reward)
output['done'].append(done)
output['info'].append(info)
i += 1
output['prev_action'] = actions
return output
def action_space(self):
"""
Returns the dimensions of the environment's action space
"""
self.workers[0].child.send(('action_space', None))
action_space = self.workers[0].child.recv()
return action_space
def close(self):
"""
Closes each of the threads in the multiprocess
"""
for worker in self.workers:
worker.child.send(('close', None))
<file_sep>/influence-aware-memory_Original_Work/PPO/__init__.py
__all__ = ["PPOcontroller", "PPOmodel"]
<file_sep>/collect-results/visualize.py
from visualization import plot_util as pu
import matplotlib as mpl
# mpl.style.use('seaborn')
# LOG_DIRS = 'logs/halfcheetah'
# Uncomment below to see the effect of the timit limits flag
# FNN (warehouse)
# LOG_DIRS = 'results-taylan/ware/fnn/results/1_8' # FNN result 8 cores VIR
# LOG_DIRS = 'ware/fnn/results/2' # FNN result 1 core VIR
# CNN (pong)
# LOG_DIRS = 'results-taylan/pong/cnn/results/2' # CNN result 8 cores TAY
# FNN + RNN (warehouse, series)
# LOG_DIRS = 'ware/fnn/results/1' # FNN result 8 cores VIR
# LOG_DIRS = 'ware/fnn/results/2' # FNN result 1 core VIR
# FNN + RNN (warehouse, parallel)
# LOG_DIRS = 'results-taylan/ware/fnnrnnp/results/1' # FNN result 8 cores TAY
# LOG_DIRS = 'results-taylan/ware/fnnrnnp/results/2' # FNN result 1 core TAY
# CNN + RNN (pong, series)
# LOG_DIRS = 'results-kevin/pong/CNNRNN/results/1' # CNN + RNN Series result 8
# cores KEV
# CNN + RNN (pong, parallel)
# LOG_DIRS = 'results-taylan/pong/cnn/results/1' # CNN + RNN Parallel result 8
# cores
# TAY
selected_env = 'ware'
if selected_env == 'ware':
color = ['red', 'firebrick', 'green', 'chartreuse', 'black', 'blue',
'royalblue']
elif selected_env =='pong':
color = ['red','green','blue']
# GROUPED UP
# LOG_DIRS = 'results-taylan/ware/fnnrnnp/results/1'
if selected_env=='ware':
LOG_DIRS = 'together/ware'
else:
LOG_DIRS = 'together/pong'
# LOG_DIRS = 'together_cores_seperated/ware'
results = pu.load_results(LOG_DIRS)
fig = pu.plot_results(results, average_group=True, split_fn=lambda _: '',
shaded_std=False,COLORS=color,select_env=selected_env,
xlabel='Steps', ylabel='Average Reward',legend_outside=True)
#%%
import matplotlib.pyplot as plt
import matplotlib
if selected_env == 'ware':
fig = matplotlib.pyplot.gcf()
plt.gcf().subplots_adjust(bottom=0.15,top=0.9,left=0.15,right=0.7)
fig.set_size_inches(30, 30)
plt.savefig('plot_ware.png', dpi=150)
elif selected_env == 'pong':
fig = matplotlib.pyplot.gcf()
plt.gcf().subplots_adjust(bottom=0.15,top=0.9,left=0.15, right=0.3)
fig.set_size_inches(30, 30)
plt.savefig('plot_pong.png', dpi=150)
else:
pass
# LOG_DIRS = 'results-taylan/ware/rnn/results/1_1' # FNN result 8 cores VIR
# LOG_DIRS2 = 'results-taylan/ware/rnn/results/1_8' # FNN result 8 cores VIR
#
# results = pu.load_results(LOG_DIRS)
# results2 = pu.load_results(LOG_DIRS2)
#
# fig1, ax1 = pu.plot_results(results, average_group=True,
# split_fn=lambda _:
# '',
# shaded_std=True,shaded_err=True,
# legend_outside=True, xlabel='Steps',
# ylabel='Average Reward')
# fig2, ax2 = pu.plot_results(results, average_group=True,
# split_fn=lambda _:
# '',
# shaded_std=True,shaded_err=True,
# legend_outside=True, xlabel='Steps',
# ylabel='Average Reward')
# plt.show()
# # plt.plot(results)
# x = LOG_DIRS.split('/')
# filename = x[1]
# # L = fig.legend()
# # L.get_texts()[0].set_text('FNN (1 core)')
# fig.legend(labels=['FNN (8 core)', 'FNN (1 core)'], bbox_to_anchor=(0.9,0.2), loc="lower right", bbox_transform=fig.transFigure)
#
# plt.savefig('plot_ware.png', dpi=300, bbox_inches='tight')
# plt.show()
|
b73c087a0d8f568832c9fbec5e726b57657bacf8
|
[
"TOML",
"Python",
"Markdown"
] | 19
|
TOML
|
viranca/CS4240_Deep_Learning_Project
|
1177c217657726c04071ec600d8aff8b762852da
|
c19f77833959ca4616660d03da402b43b804c88a
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.