branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>// VPlayerSniper.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
#include <vector>
using namespace std;
const int IMG_MAX_SIZE_X = 800;
const int IMG_MAX_SIZE_Y = 600;
const int MAX_RECTS = 100;
int screen_sizeX = 0;
int screen_sizeY = 0;
BYTE screenshot_32b_img[IMG_MAX_SIZE_X * IMG_MAX_SIZE_Y * 4];
BYTE scr8b[IMG_MAX_SIZE_X*IMG_MAX_SIZE_Y];
BYTE scr8b_prev[IMG_MAX_SIZE_X*IMG_MAX_SIZE_Y];
BYTE scr8b_diff[IMG_MAX_SIZE_X*IMG_MAX_SIZE_Y];
RECT rects[MAX_RECTS];
vector<RECT> player_candidates;
RECT playerR;
SIZE calc_stretched_size(int orig_w, int orig_h, int max_w, int max_h)
{
SIZE sz;
if (orig_h < orig_w)
{
float k = (float)max_w / orig_w;
sz.cx = max_w;
sz.cy = (int)((float)max_h * k);
}
else
{
float k = (float)max_h / orig_h;
sz.cy = max_h;
sz.cx = (int)((float)max_w * k);
}
return sz;
}
void write_32b_window_pixels(const HWND window, const SIZE max_size, BYTE *screenshot_32b_img)
{
RECT window_rect;
HDC hScreen = GetDC(window);
GetWindowRect(window, &window_rect);
//SIZE stretched_size = calc_stretched_size(window_rect.right - window_rect.left,
//window_rect.bottom - window_rect.top, max_size.cx, max_size.cy);
HDC hdcMem = CreateCompatibleDC(hScreen);
HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, max_size.cx, max_size.cy);
HGDIOBJ hOld = SelectObject(hdcMem, hBitmap);
StretchBlt(hdcMem, 0, 0, max_size.cx, max_size.cy, hScreen, 0, 0,
window_rect.right - window_rect.left, window_rect.bottom - window_rect.top, SRCCOPY | CAPTUREBLT);
//BitBlt(hdcMem, 0, 0, stretched_size.cx, stretched_size.cy, hScreen, 0, 0, SRCCOPY);
SelectObject(hdcMem, hOld);
BITMAPINFOHEADER bmi = { 0 };
bmi.biSize = sizeof(BITMAPINFOHEADER);
bmi.biPlanes = 1;
bmi.biBitCount = 32;
bmi.biWidth = max_size.cx;
bmi.biHeight = -max_size.cy;
bmi.biCompression = BI_RGB;
bmi.biSizeImage = 0;// 3 * ScreenX * ScreenY;
//if (screenshot_24b_img && (screen_sizeX != size_x || screen_sizeY != size_y))
// free(screenshot_24b_img);
//screenshot_24b_img = (BYTE*)malloc(4 * size_x * size_y);
GetDIBits(hdcMem, hBitmap, 0, max_size.cy, screenshot_32b_img, (BITMAPINFO*)&bmi, DIB_RGB_COLORS);
ReleaseDC(GetDesktopWindow(), hScreen);
DeleteDC(hdcMem);
DeleteObject(hBitmap);
}
void Test_save_bmp_32(TCHAR *path, BYTE *pixels)
{
BITMAPINFOHEADER bmi = { 0 };
bmi.biSize = sizeof(BITMAPINFOHEADER);
bmi.biPlanes = 1;
bmi.biBitCount = 32;
bmi.biWidth = IMG_MAX_SIZE_X;
bmi.biHeight = -IMG_MAX_SIZE_Y;
bmi.biCompression = BI_RGB;
bmi.biSizeImage = 0;// 3 * ScreenX * ScreenY;
DWORD dwBmpSize = ((IMG_MAX_SIZE_X * 32 + 31) / 32) * 4 *
IMG_MAX_SIZE_Y;
DWORD dwSizeofDIB = dwBmpSize + sizeof(BITMAPFILEHEADER) +
sizeof(BITMAPINFOHEADER);
BITMAPFILEHEADER bmfh;
bmfh.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) +
(DWORD)sizeof(BITMAPINFOHEADER);
//Size of the file
bmfh.bfSize = dwSizeofDIB;
//bfType must always be BM for Bitmaps
bmfh.bfType = 0x4D42; //BM
HANDLE hFile = CreateFile(path,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwBytesWritten = 0;
WriteFile(hFile, (LPSTR)&bmfh, sizeof(BITMAPFILEHEADER), &dwBytesWritten, NULL);
WriteFile(hFile, (LPSTR)&bmi, sizeof(BITMAPINFOHEADER), &dwBytesWritten, NULL);
WriteFile(hFile, (LPSTR)pixels, dwBmpSize, &dwBytesWritten, NULL);
CloseHandle(hFile);
}
void Test_save_bmp_8(TCHAR *path, BYTE *pixels_8b)
{
static BYTE pixels32[IMG_MAX_SIZE_X * IMG_MAX_SIZE_Y * 4];
memset(pixels32, 0, IMG_MAX_SIZE_X * IMG_MAX_SIZE_Y * 4);
for (int x = 0; x < IMG_MAX_SIZE_X; x++)
{
for (int y = 0; y < IMG_MAX_SIZE_Y; y++)
{
pixels32[(y*IMG_MAX_SIZE_X + x) * 4 + 0] = pixels_8b[y*IMG_MAX_SIZE_X + x];
pixels32[(y*IMG_MAX_SIZE_X + x) * 4 + 1] = pixels_8b[y*IMG_MAX_SIZE_X + x];
pixels32[(y*IMG_MAX_SIZE_X + x) * 4 + 2] = pixels_8b[y*IMG_MAX_SIZE_X + x];
}
}
Test_save_bmp_32(path, pixels32);
}
void get_wnd_32b_screenshot(HWND wnd, BYTE *pixels)
{
memset(pixels, 0, IMG_MAX_SIZE_X * IMG_MAX_SIZE_Y * 4);
write_32b_window_pixels(wnd, { IMG_MAX_SIZE_X, IMG_MAX_SIZE_Y }, pixels);
}
void conv_pixels_32b_to_8b(BYTE *pixels_32b, BYTE *pixels_8b)
{
for (int x = 0; x < IMG_MAX_SIZE_X; x++)
{
for (int y = 0; y < IMG_MAX_SIZE_Y; y++)
{
pixels_8b[y*IMG_MAX_SIZE_X + x] =
(pixels_32b[(y*IMG_MAX_SIZE_X + x) * 4 + 0] +
pixels_32b[(y*IMG_MAX_SIZE_X + x) * 4 + 1] +
pixels_32b[(y*IMG_MAX_SIZE_X + x) * 4 + 2]) / 3;
}
}
}
void calc_8b_pixels_diff(const BYTE *new_pixels, const BYTE *old_pixels, BYTE *diff_pixels)
{
for (int x = 0; x < IMG_MAX_SIZE_X; x++)
{
for (int y = 0; y < IMG_MAX_SIZE_Y; y++)
{
diff_pixels[y*IMG_MAX_SIZE_X + x] = new_pixels[y*IMG_MAX_SIZE_X + x] ^ old_pixels[y*IMG_MAX_SIZE_X + x];
}
}
}
bool point_in_rect(const POINT &p, const RECT &r)
{
return p.x >= r.left && p.x <= r.right && p.y >= r.top && p.y <= r.bottom;
}
bool rects_intersected(const RECT &lr, const RECT &rr)
{
return point_in_rect(POINT{ lr.left, lr.top }, rr) ||
point_in_rect(POINT{ lr.right, lr.top }, rr) ||
point_in_rect(POINT{ lr.left, lr.bottom }, rr) ||
point_in_rect(POINT{ lr.right, lr.bottom }, rr);
}
//returns rects
//rects can be dispensing in array
void calc_diff_rects(BYTE *diff_pixels, int r, RECT *rects)
{
for (int x = 0; x < IMG_MAX_SIZE_X; x++)
{
for (int y = 0; y < IMG_MAX_SIZE_Y; y++)
{
if (diff_pixels[y*IMG_MAX_SIZE_X + x] > 0)
{
RECT rect;
while (1)
{
}
}
}
}
}
int main()
{
int i = 0;
RECT zero_rect;
memset(&zero_rect, 0, sizeof(RECT));
Sleep(5000);
memset(scr8b_prev, 0, sizeof(scr8b_prev));
while (1)
{
//TODO: speed check. if not anought frame rate then stop detection.
get_wnd_32b_screenshot(GetDesktopWindow(), screenshot_32b_img);
conv_pixels_32b_to_8b(screenshot_32b_img, scr8b);
calc_8b_pixels_diff(scr8b, scr8b_prev, scr8b_diff);
memcpy(scr8b_prev, scr8b, sizeof(scr8b_prev));
//Test_save_bmp_8(L"C:\\temp\\src0001.bmp", scr8b_diff);
calc_diff_rects(scr8b_diff, 4, rects);
//printf("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
for (int j = 0; j < IMG_MAX_SIZE_X*IMG_MAX_SIZE_Y; j++)
{
if (0 == memcmp(&rects[j], &zero_rect, sizeof(RECT)))
{
continue;
}
printf("%ix%i\n", rects[j].left, rects[j].top);
}
//update_player_candidates(diff_rects, player_candidates);
//update_player_rect(player_candidates, playerR);
if (i > 100)
break;
Sleep(500);
}
return 0;
}
|
795e699e10e46976d0e73b4e5ca156225b7b4499
|
[
"C++"
] | 1
|
C++
|
katasonov/VPlayerSniper
|
ce0627bb6472752884836e741d94a786192e2aca
|
4a7625216ae3620e2d9d0b82a56a610121a72e89
|
refs/heads/master
|
<file_sep>#include "types.h"
#include "fcntl.h"
#include "stat.h"
#include "user.h"
int main(int argc, char **argv)
{
int pid;
pid = fork();
if (pid < 0)
{
printf(2, "Fork error\n");
exit();
}
else if (!pid)
{
printf(1, "Child: %s\n", argv[1]);
// int j = 0;
// for (int i = 0; i < 100000000; i++)
// {
// j++;
// j--;
// j++;
// }
if (exec(argv[1], argv + 1) < 0)
{
printf(2, "Exec failed\n");
exit();
}
}
else
{
int wtime, rtime;
int pid1 = waitx(&wtime, &rtime);
printf(1, "Time-> Name: %s PID: %d wtime: %d rtime: %d\n\n", argv[1], pid1, wtime, rtime);
exit();
}
}<file_sep>#include "types.h"
#include "user.h"
int main(int argc, char **argv)
{
if(argc < 3){
printf(1, "Invalid number of arguments\n");
exit();
}
int priority = atoi(argv[1]);
int pid = atoi(argv[2]);
if (set_priority(priority, pid) < 0)
{
printf(1, "Error\n");
}
exit();
}<file_sep># Assignment 5 - XV6 Report
## `waitx`
This is a modification of the pre-existing wait function. It calculates rtime by incrementing it each time ticks is incremented and wtime is calculated by
```c
*wtime = p->etime - (p->ctime + p->rtime + p->iotime);
```
Here etime is the exit time of the process, ctime is creation time, rtime is run time and iotime is the time used in doing I/O operations.
## `time`
This is a simple user defined function which can be used to check waitx system call.
## `ps`
This is used to get info of the active processes. It is implemented in **myps** function in proc.c. It returns the status, r_time, n_runs, time spent in each queue and current queue number (in the case of MLFQ).
## `set_priority`
This is a system call used to change the priority of processes in case of PBS scheduler.
## `setPriority`
This is a user defined function which can be used to change the priority of background processes in PBS scheduler. It employes **set_priority** system call in background.
## `benchmark`
This is a user defined function which can be used to check the various schduling algorithms. It uses fork and creates child processes and prints when they end. It can be modified for checking.
## Scheduling Algorithms
### `FCFS`
It selects the processes based on the creation time. The process which is runnable and has the minimum creation time is selected by the CPU.
### `PBS`
It selects the processes based on the priority. The process which is runnable and has the highest priority (lowest value) is selected by the CPU.
### `MLFQ`
The scheduler has been implemented as mentioned in the assignment pdf.
Scheduler Details:
1. Create five priority queues, with the highest priority being number as 0 and the bottom queue with the lowest priority as 4.
2. Assign a suitable value for 1 tick of CPU timer.
3. The time-slice for priority 0 should be 1 timer tick. The times-slice for priority 1 is 2 timer ticks; for priority 2, it is 4 timer ticks; for priority 3, it is 8 timer ticks; for priority 4, it is 16 timer ticks.
Procedure:
1. On the initiation of a process, push it to the end of the highest priority queue.
2. The highest priority queue should be running always, if not empty.
3. If the process completes, it leaves the system.
4. If the process uses the complete time slice assigned for its current priority queue, it is preempted and inserted at the end of the next lower level queue.
5. If a process voluntarily relinquishes control of the CPU, it leaves the queuing network, and when the process becomes ready again after the I/O, it is inserted
at the tail of the same queue, from which it is relinquished earlier
6. A round-robin scheduler should be used for processes at the lowest priority queue.
7. To prevent starvation, aging is implemented.
### Report
This was calculated by running 4 processes under similar conditions in different algorithms.
***RR***
|Process|Run Time|Waiting Time|
|-------|--------|------------|
|P0|31|92|
|P1|31|93|
|P2|32|96|
|P3|31|94|
***FCFS***
|Process|Run Time|Waiting Time|
|-------|--------|------------|
|P0|31|1|
|P1|33|32|
|P2|31|64|
|P3|31|96|
***PBS***
Priority of P1 = Priority of P3
Priority of P0 = Priority of P2
Priority of P2 > P1
|Process|Run Time|Waiting Time|
|-------|--------|------------|
|P0|30|32|
|P2|32|32|
|P1|31|96|
|P3|32|95|
***MLFQ***
|Process|Run Time|Waiting Time|
|-------|--------|------------|
|P3|31|84|
|P0|33|88|
|P1|32|92|
|P2|32|96|
The waiting time for the FCFS is lowest as it does not waste time to choose process and directly takes the process with lowest creation time. It is less than waiting time of PBS due to pre-emption of PBS which causes CPU to lose valuable time by choosing process again and again. The waiting time of MLFQ is high becuase a lot of time is spent in choosing processes, aging, demoting etc. The waiting time of RR is high due to continuous process change which causes CPU to reduce effeciency.
>MLFQ can be exploited by the programmer by adding a small I/O burst with frequency less than the time slice of the queue. This will cause the process to be removed from the queue and be added back to the same queue again (highest priority). This will result in that process to be in the same queue again and again and be finished with the highest priority (in the highest queue).
## Queue Changes in MLFQ
<file_sep>#include "types.h"
#include "user.h"
int main(int argc, char **argv)
{
if (myps() < 0)
{
printf(1, "Error\n");
exit();
}
exit();
}<file_sep>#include "types.h"
#include "user.h"
int number_of_processes = 10;
int main(int argc, char *argv[])
{
int j;
for (j = 0; j < number_of_processes; j++)
{
int pid = fork();
if (pid < 0)
{
printf(1, "Fork failed\n");
continue;
}
if (pid == 0)
{
volatile int i;
// for (volatile int k = 0; k < number_of_processes; k++)
for (volatile int k = 0; k < 10; k++)
{
// if (k <= j)
// // if (j % 2 == 0)
// {
sleep(20); //io time
// }
// else
// {
for (i = 0; i < (int)1e7; i++)
{
; //cpu time
}
// }
}
printf(1, "\nProcess: %d with PID: %d Finished\n\n\n", j, getpid());
// myps(); // To Print comparison report
exit();
}
else
{
;
// set_priority(100 - (20 + j), pid); // will only matter for PBS, comment it out if not implemented yet (better priorty for more IO intensive jobs)
#if SCHEDULER == SCHED_PBS
set_priority(80 + j % 2, pid); // will only matter for PBS, comment it out if not implemented yet (better priorty for more IO intensive jobs)
#endif
}
}
for (j = 0; j < number_of_processes + 5; j++)
{
wait();
// int wtime, rtime;
// int pid1 = waitx(&wtime, &rtime);
// printf(1, "Time-> Name: %s wtime: %d rtime: %d\n\n", argv[1], wtime, rtime);
}
exit();
}
|
cf3f88d82fd5154f7780f353e8e7193f86429aff
|
[
"Markdown",
"C"
] | 5
|
C
|
shreygupta2809/Modified-XV6
|
cf27b1849d355aac1cc168cdc11d79b7ff500fce
|
f7eff1c4cd32f4a305dbfdfcaf171cd7ad38194e
|
refs/heads/master
|
<repo_name>yupitsme0/bmo<file_sep>/extensions/ProductDashboard/web/js/summary.js
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0.
*/
YUI({
base: 'js/yui3/',
combine: false
}).use("datatable", "datatable-sort", function (Y) {
var column_defs = [
{ key: 'name', label: 'Name', sortable: true },
{ key: 'count', label: 'Count', sortable: true },
{ key: 'percentage', label: 'Percentage', sortable: true, allowHTML: true,
formatter: '<div class="percentage"><div class="bar" style="width:{value}%"></div><div class="percent">{value}%</div></div>' },
{ key: 'link', label: 'Link', allowHTML: true }
];
var bugsCountDataTable = new Y.DataTable({
columns: column_defs,
data: PD.summary.bug_counts
}).render('#bug_counts');
var statusCountsDataTable = new Y.DataTable({
columns: column_defs,
data: PD.summary.status_counts
}).render('#status_counts');
var priorityCountsDataTable = new Y.DataTable({
columns: column_defs,
data: PD.summary.priority_counts
}).render('#priority_counts');
var severityCountsDataTable = new Y.DataTable({
columns: column_defs,
data: PD.summary.severity_counts
}).render('#severity_counts');
var assigneeCountsDataTable = new Y.DataTable({
columns: column_defs,
data: PD.summary.assignee_counts
}).render('#assignee_counts');
});
<file_sep>/extensions/MozProjectReview/web/js/moz_project_review.js
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0.
*/
var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var MPR = {
required_fields: {
"initial_questions": {
"short_desc": "Please enter a value for project or feature name in the initial questions section",
"cc": "Please enter a value for points of contact in the initial questions section",
"key_initiative": "Please select a value for key initiative in the initial questions section",
"release_date": "Please enter a value for release date in the initial questions section",
"project_status": "Please select a value for project status in the initial questions section",
"mozilla_data": "Please select a value for mozilla data in the initial questions section",
"separate_party": "Please select a value for separate party in the initial questions section"
},
"finance_questions": {
"finance_purchase_vendor": "Please enter a value for vendor in the finance questions section",
"finance_purchase_what": "Please enter a value for what in the finance questions section",
"finance_purchase_why": "Please enter a value for why in the finance questions section",
"finance_purchase_risk": "Please enter a value for risk in the finance questions section",
"finance_purchase_alternative": "Please enter a value for alternative in the finance questions section",
"finance_purchase_inbudget": "Please enter a value for in budget in the finance questions section",
"finance_purchase_urgency": "Please select a value for urgency in the finance questions section",
"finance_purchase_cost": "Please enter a value for total cost in the finance questions section"
},
"legal_questions": {
"legal_priority": "Please select a value for priority in the legal questions section",
"legal_timeframe": "Please select a value for timeframe in the legal questions section",
"legal_help_from_legal": "Please describe the help needed from the Legal department"
},
"legal_sow_questions": {
"legal_sow_vendor_name": "Please enter a value for SOW legal vendor name",
"legal_sow_vendor_address": "Please enter a value for SOW vendor address",
"legal_sow_vendor_email": "Please enter a value for SOW vendor email for notices",
"legal_sow_vendor_mozcontact": "Please enter a value for SOW Mozilla contact",
"legal_sow_vendor_contact": "Please enter a value for SOW vendor contact and email address",
"legal_sow_vendor_services": "Please enter a value for SOW vendor services description",
"legal_sow_vendor_deliverables": "Please enter a value for SOW vendor deliverables description",
"legal_sow_start_date": "Please enter a value for SOW vendor start date",
"legal_sow_end_date": "Please enter a value for SOW vendor end date",
"legal_sow_vendor_payment": "Please enter a value for SOW vendor payment amount",
"legal_sow_vendor_payment_basis": "Please enter a value for SOW vendor payment basis",
"legal_sow_vendor_payment_schedule": "Please enter a value for SOW vendor payment schedule",
"legal_sow_vendor_total_max": "Please enter a value for SOW vendor maximum total to be paid",
"legal_sow_vendor_product_line": "Please enter a value for SOW vendor product line"
},
"data_compliance_questions": {
"data_comp_request_type": "Please select a value for the data compliance request type",
"data_comp_area": "Please select a value for the data compliance area",
"data_comp_desc": "Please enter a value for the data compliance description",
"data_comp_handling_change": "Please select a value for the data compliance handling change",
"data_comp_practice_change": "Please select a value for the data compliance practice change"
}
},
select_inputs: [
'key_initiative',
'project_status',
'mozilla_data',
'separate_party',
'relationship_type',
'data_access',
'vendor_cost',
'po_needed',
'sec_affects_products',
'legal_priority',
'legal_sow_vendor_product_line',
'legal_vendor_services_where',
'finance_purchase_urgency'
],
init: function () {
// Bind the updateSections function to each of the inputs desired
for (var i = 0, l = this.select_inputs.length; i < l; i++) {
Event.on(this.select_inputs[i], 'change', MPR.updateSections);
}
MPR.updateSections();
},
fieldValue: function (id) {
var field = Dom.get(id);
if (!field) return '';
if (field.type == 'text'
|| field.type == 'textarea')
{
return field.value;
}
return field.options[field.selectedIndex].value;
},
updateSections: function () {
// Sections that will be hidden/shown based on the input values
// Start out as all false except for initial questions which is always visible
var page_sections = {
initial_questions: true,
key_initiative_other_row: false,
initial_separate_party_questions: false,
finance_questions: false,
po_needed_row: false,
legal_questions: false,
legal_sow_questions: false,
legal_vendor_single_country: false,
legal_vendor_services_where_row: false,
sec_review_questions: false,
data_compliance_questions: false,
};
if (MPR.fieldValue('key_initiative') == 'Other') {
page_sections.key_initiative_other_row = true;
}
if (MPR.fieldValue('mozilla_data') == 'Yes') {
page_sections.legal_questions = true;
page_sections.data_compliance_questions = true;
page_sections.sec_review_questions = true;
}
if (MPR.fieldValue('separate_party') == 'Yes') {
page_sections.initial_separate_party_questions = true;
if (MPR.fieldValue('relationship_type')
&& MPR.fieldValue('relationship_type') != 'Hardware Purchase')
{
page_sections.legal_questions = true;
}
if (MPR.fieldValue('relationship_type') == 'Vendor/Services'
|| MPR.fieldValue('relationship_type') == 'Firefox Distribution/Bundling')
{
page_sections.legal_sow_questions = true;
page_sections.legal_vendor_services_where_row = true;
}
if (MPR.fieldValue('relationship_type') == 'Hardware Purchase') {
page_sections.finance_questions = true;
}
if (MPR.fieldValue('data_access') == 'Yes') {
page_sections.legal_questions = true;
page_sections.sec_review_questions = true;
page_sections.data_compliance_questions = true;
}
if (MPR.fieldValue('vendor_cost') == '<= $25,000') {
page_sections.po_needed_row = true;
}
if (MPR.fieldValue('po_needed') == 'Yes') {
page_sections.finance_questions = true;
}
if (MPR.fieldValue('vendor_cost') == '> $25,000') {
page_sections.finance_questions = true;
}
}
if (MPR.fieldValue('legal_vendor_services_where') == 'A single country') {
page_sections.legal_vendor_single_country = true;
}
// Toggle the individual page_sections
for (section in page_sections) {
MPR.toggleShowSection(section, page_sections[section]);
}
},
toggleShowSection: function (section, show) {
if (show) {
Dom.removeClass(section, 'bz_default_hidden');
}
else {
Dom.addClass(section ,'bz_default_hidden');
}
},
validateAndSubmit: function () {
var alert_text = '';
var section = '';
for (section in this.required_fields) {
if (!Dom.hasClass(section, 'bz_default_hidden')) {
var field = '';
for (field in MPR.required_fields[section]) {
if (!MPR.isFilledOut(field)) {
alert_text += this.required_fields[section][field] + "\n";
}
}
}
}
// Special case checks
if (MPR.fieldValue('relationship_type') == 'Vendor/Services'
&& MPR.fieldValue('legal_vendor_services_where') == '')
{
alert_text += "Please select a value for vendor services where\n";
}
if (MPR.fieldValue('relationship_type') == 'Vendor/Services'
&& MPR.fieldValue('legal_vendor_services_where') == 'A single country'
&& MPR.fieldValue('legal_vendor_single_country') == '')
{
alert_text += "Please select a value for vendor services where single country\n";
}
if (MPR.fieldValue('key_initiative') == 'Other') {
if (!MPR.isFilledOut('key_initiative_other')) {
alert_text += "Please enter a value for key initiative in the initial questions section\n";
}
}
if (MPR.fieldValue('separate_party') == 'Yes') {
if (!MPR.isFilledOut('relationship_type')) {
alert_text += "Please select a value for type of relationship\n";
}
if (!MPR.isFilledOut('data_access')) {
alert_text += "Please select a value for data access\n";
}
if (!MPR.isFilledOut('vendor_cost')) {
alert_text += "Please select a value for vendor cost\n";
}
}
if (MPR.fieldValue('vendor_cost') == '<= $25,000'
&& MPR.fieldValue('po_needed') == '')
{
alert_text += "Please select whether a PO is needed or not\n";
}
if (alert_text) {
alert(alert_text);
return false;
}
return true;
},
//Takes a DOM element id and makes sure that it is filled out
isFilledOut: function (elem_id) {
var str = MPR.fieldValue(elem_id);
return str.length > 0 ? true : false;
}
};
Event.onDOMReady(function () {
MPR.init();
});
<file_sep>/extensions/BugModal/web/comments.js
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0. */
$(function() {
'use strict';
// comment collapse/expand
function toggleChange(spinner, forced) {
var spinnerID = spinner.attr('id');
var id = spinnerID.substring(spinnerID.indexOf('-') + 1);
var activitySelector = $('#view-toggle-cc').data('shown') === '1' ? '.activity' : '.activity:not(.cc-only)';
// non-comment toggle
if (spinnerID.substr(0, 1) == 'a') {
var changeSet = spinner.parents('.change-set');
if (forced == 'hide') {
changeSet.find(activitySelector).hide();
changeSet.find('.gravatar').css('width', '16px').css('height', '16px');
$('#ar-' + id).hide();
spinner.text('+');
}
else if (forced == 'show' || forced == 'reset') {
changeSet.find(activitySelector).show();
changeSet.find('.gravatar').css('width', '32px').css('height', '32px');
$('#ar-' + id).show();
spinner.text('-');
}
else {
changeSet.find(activitySelector).slideToggle('fast', function() {
$('#ar-' + id).toggle();
if (changeSet.find(activitySelector + ':visible').length) {
changeSet.find('.gravatar').css('width', '32px').css('height', '32px');
spinner.text('-');
}
else {
changeSet.find('.gravatar').css('width', '16px').css('height', '16px');
spinner.text('+');
}
});
}
return;
}
// find the "real spinner", which is the one on the non-default-collapsed block
var realSpinner = $('#cs-' + id);
var defaultCollapsed = realSpinner.data('ch');
if (defaultCollapsed === undefined) {
defaultCollapsed = spinner.attr('id').substring(0, 4) === 'ccs-';
realSpinner.data('ch', defaultCollapsed);
}
if (forced === 'reset') {
forced = defaultCollapsed ? 'hide' : 'show';
}
// comment toggle
if (forced === 'hide') {
if (defaultCollapsed) {
$('#ch-' + id).hide();
$('#cc-' + id).show();
}
$('#ct-' + id).hide();
if (BUGZILLA.user.id !== 0)
$('#ctag-' + id).hide();
$('#c' + id).find(activitySelector).hide();
$('#c' + id).find('.comment-tags').hide();
$('#c' + id).find('.comment-tags').hide();
$('#c' + id).find('.gravatar').css('width', '16px').css('height', '16px');
$('#cr-' + id).hide();
realSpinner.text('+');
}
else if (forced == 'show') {
if (defaultCollapsed) {
$('#cc-' + id).hide();
$('#ch-' + id).show();
}
$('#ct-' + id).show();
if (BUGZILLA.user.id !== 0)
$('#ctag-' + id).show();
$('#c' + id).find(activitySelector).show();
$('#c' + id).find('.comment-tags').show();
$('#c' + id).find('.comment-tags').show();
$('#c' + id).find('.gravatar').css('width', '32px').css('height', '32px');
$('#cr-' + id).show();
realSpinner.text('-');
}
else {
$('#ct-' + id).slideToggle('fast', function() {
$('#c' + id).find(activitySelector).toggle();
if ($('#ct-' + id + ':visible').length) {
$('#c' + id).find('.comment-tags').show();
realSpinner.text('-');
$('#cr-' + id).show();
if (BUGZILLA.user.id !== 0)
$('#ctag-' + id).show();
$('#c' + id).find('.gravatar').css('width', '32px').css('height', '32px');
if (defaultCollapsed) {
$('#cc-' + id).hide();
$('#ch-' + id).show();
}
}
else {
$('#c' + id).find('.comment-tags').hide();
realSpinner.text('+');
$('#cr-' + id).hide();
if (BUGZILLA.user.id !== 0)
$('#ctag-' + id).hide();
$('#c' + id).find('.gravatar').css('width', '16px').css('height', '16px');
if (defaultCollapsed) {
$('#ch-' + id).hide();
$('#cc-' + id).show();
}
}
});
}
}
$('.change-spinner')
.click(function(event) {
event.preventDefault();
toggleChange($(this));
});
// view and tag menus
$('#view-reset')
.click(function() {
$('.change-spinner:visible').each(function() {
toggleChange($(this), 'reset');
});
});
$('#view-collapse-all')
.click(function() {
$('.change-spinner:visible').each(function() {
toggleChange($(this), 'hide');
});
});
$('#view-expand-all')
.click(function() {
$('.change-spinner:visible').each(function() {
toggleChange($(this), 'show');
});
});
$('#view-comments-only')
.click(function() {
$('.change-spinner:visible').each(function() {
toggleChange($(this), this.id.substr(0, 3) === 'cs-' ? 'show' : 'hide');
});
});
$('#view-toggle-cc')
.click(function() {
var that = $(this);
var item = $('.context-menu-item.hover');
if (that.data('shown') === '1') {
that.data('shown', '0');
item.text('Show CC Changes');
$('.cc-only').hide();
}
else {
that.data('shown', '1');
item.text('Hide CC Changes');
$('.cc-only').show();
}
});
$('#view-toggle-treeherder')
.click(function() {
var that = $(this);
console.log(that.data('userid'));
var item = $('.context-menu-item.hover');
if (that.data('hidden') === '1') {
that.data('hidden', '0');
item.text('Hide Treeherder Comments');
$('.ca-' + that.data('userid')).show();
}
else {
that.data('hidden', '1');
item.text('Show Treeherder Comments');
$('.ca-' + that.data('userid')).hide();
}
});
$.contextMenu({
selector: '#view-menu-btn',
trigger: 'left',
items: $.contextMenu.fromMenu($('#view-menu'))
});
function updateTagsMenu() {
var tags = [];
$('.comment-tags').each(function() {
$.each(tagsFromDom($(this)), function() {
var tag = this.toLowerCase();
if (tag in tags) {
tags[tag]++;
}
else {
tags[tag] = 1;
}
});
});
var tagNames = Object.keys(tags);
tagNames.sort();
var btn = $('#comment-tags-btn');
if (tagNames.length === 0) {
btn.hide();
return;
}
btn.show();
var menuItems = [
{ name: 'Reset', tag: '' },
"--"
];
$.each(tagNames, function(key, value) {
menuItems.push({ name: value + ' (' + tags[value] + ')', tag: value });
});
$.contextMenu('destroy', '#comment-tags-btn');
$.contextMenu({
selector: '#comment-tags-btn',
trigger: 'left',
items: menuItems,
callback: function(key, opt) {
var tag = opt.commands[key].tag;
if (tag === '') {
$('.change-spinner:visible').each(function() {
toggleChange($(this), 'reset');
});
return;
}
var firstComment = false;
$('.change-spinner:visible').each(function() {
var that = $(this);
var commentTags = tagsFromDom(that.parents('.comment').find('.comment-tags'));
var hasTag = $.inArrayIn(tag, commentTags) >= 0;
toggleChange(that, hasTag ? 'show' : 'hide');
if (hasTag && !firstComment) {
firstComment = that;
}
});
if (firstComment)
$.scrollTo(firstComment);
}
});
}
//
// anything after this point is only executed for logged in users
//
if (BUGZILLA.user.id === 0) return;
// comment tagging
function taggingError(commentNo, message) {
$('#ctag-' + commentNo + ' .comment-tags').append($('#ctag-error'));
$('#ctag-error-message').text(message);
$('#ctag-error').show();
}
function deleteTag(event) {
event.preventDefault();
$('#ctag-error').hide();
var that = $(this);
var comment = that.parents('.comment');
var commentNo = comment.data('no');
var commentID = comment.data('id');
var tag = that.parent('.comment-tag').contents().filter(function() {
return this.nodeType === 3;
}).text();
var container = that.parents('.comment-tags');
// update ui
that.parent('.comment-tag').remove();
renderTags(commentNo, tagsFromDom(container));
// update bugzilla
bugzilla_ajax(
{
url: 'rest/bug/comment/' + commentID + '/tags',
type: 'PUT',
data: { remove: [ tag ] },
hideError: true
},
function(data) {
renderTags(commentNo, data);
},
function(message) {
taggingError(commentNo, message);
}
);
}
$('.comment-tag a').click(deleteTag);
function tagsFromDom(commentTagsDiv) {
return commentTagsDiv
.find('.comment-tag')
.contents()
.filter(function() { return this.nodeType === 3; })
.map(function() { return $(this).text(); })
.toArray();
}
function renderTags(commentNo, tags) {
cancelRefresh();
var root = $('#ctag-' + commentNo + ' .comment-tags');
root.find('.comment-tag').remove();
$.each(tags, function() {
var span = $('<span/>').addClass('comment-tag').text(this);
if (BUGZILLA.user.can_tag) {
span.prepend($('<a>x</a>').click(deleteTag));
}
root.append(span);
});
$('#ctag-' + commentNo + ' .comment-tags').append($('#ctag-error'));
}
var refreshXHR;
function refreshTags(commentNo, commentID) {
cancelRefresh();
refreshXHR = bugzilla_ajax(
{
url: 'rest/bug/comment/' + commentID + '?include_fields=tags',
hideError: true
},
function(data) {
refreshXHR = false;
renderTags(commentNo, data.comments[commentID].tags);
},
function(message) {
refreshXHR = false;
taggingError(commentNo, message);
}
);
}
function cancelRefresh() {
if (refreshXHR) {
refreshXHR.abort();
refreshXHR = false;
}
}
$('#ctag-add')
.devbridgeAutocomplete({
serviceUrl: function(query) {
return 'rest/bug/comment/tags/' + encodeURIComponent(query);
},
params: {
Bugzilla_api_token: (BUGZILLA.api_token ? BUGZILLA.api_token : '')
},
deferRequestBy: 250,
minChars: 3,
tabDisabled: true,
autoSelectFirst: true,
triggerSelectOnValidInput: false,
transformResult: function(response) {
response = $.parseJSON(response);
return {
suggestions: $.map(response, function(tag) {
return { value: tag };
})
};
},
formatResult: function(suggestion, currentValue) {
// disable <b> wrapping of matched substring
return suggestion.value.htmlEncode();
}
})
.keydown(function(event) {
if (event.which === 27) {
event.preventDefault();
$('#ctag-close').click();
}
else if (event.which === 13) {
event.preventDefault();
$('#ctag-error').hide();
var ctag = $('#ctag');
var newTags = $('#ctag-add').val().trim().split(/[ ,]/);
var commentNo = ctag.data('commentNo');
var commentID = ctag.data('commentID');
$('#ctag-close').click();
// update ui
var tags = tagsFromDom($(this).parents('.comment-tags'));
var dirty = false;
var addTags = [];
$.each(newTags, function(index, value) {
if ($.inArrayIn(value, tags) == -1)
addTags.push(value);
});
if (addTags.length === 0)
return;
// validate
try {
$.each(addTags, function(index, value) {
if (value.length < BUGZILLA.constant.min_comment_tag_length) {
throw 'Comment tags must be at least ' +
BUGZILLA.constant.min_comment_tag_length + ' characters.';
}
if (value.length > BUGZILLA.constant.max_comment_tag_length) {
throw 'Comment tags cannot be longer than ' +
BUGZILLA.constant.min_comment_tag_length + ' characters.';
}
});
} catch(ex) {
taggingError(commentNo, ex);
return;
}
Array.prototype.push.apply(tags, addTags);
tags.sort();
renderTags(commentNo, tags);
// update bugzilla
bugzilla_ajax(
{
url: 'rest/bug/comment/' + commentID + '/tags',
type: 'PUT',
data: { add: addTags },
hideError: true
},
function(data) {
renderTags(commentNo, data);
},
function(message) {
taggingError(commentNo, message);
refreshTags(commentNo, commentID);
}
);
}
});
$('#ctag-close')
.click(function(event) {
event.preventDefault();
$('#ctag').hide().data('commentNo', '');
});
$('.tag-btn')
.click(function(event) {
event.preventDefault();
var that = $(this);
var commentNo = that.data('no');
var commentID = that.data('id');
var ctag = $('#ctag');
$('#ctag-error').hide();
// toggle -> hide
if (ctag.data('commentNo') === commentNo) {
ctag.hide().data('commentNo', '');
window.focus();
return;
}
ctag.data('commentNo', commentNo);
ctag.data('commentID', commentID);
// kick off a refresh of the tags
refreshTags(commentNo, commentID);
// expand collapsed comments
if ($('#ct-' + commentNo + ':visible').length === 0) {
$('#cs-' + commentNo + ', #ccs-' + commentNo).click();
}
// move, show, and focus tagging ui
ctag.prependTo('#ctag-' + commentNo + ' .comment-tags').show();
$('#ctag-add').val('').focus();
});
$('.close-btn')
.click(function(event) {
event.preventDefault();
$('#' + $(this).data('for')).hide();
});
updateTagsMenu();
});
<file_sep>/extensions/MyDashboard/web/js/query.js
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0.
*/
if (typeof(MyDashboard) == 'undefined') {
var MyDashboard = {};
}
// Main query code
YUI({
base: 'js/yui3/',
combine: false,
groups: {
gallery: {
combine: false,
base: 'js/yui3/',
patterns: { 'gallery-': {} }
}
}
}).use("node", "datatable", "datatable-sort", "datatable-message", "json-stringify",
"datatable-datasource", "datasource-io", "datasource-jsonschema", "cookie",
"gallery-datatable-row-expansion-bmo", "handlebars", "escape", function(Y) {
var counter = 0,
bugQueryTable = null,
bugQuery = null,
lastChangesQuery = null,
lastChangesCache = {},
default_query = "assignedbugs";
// Grab last used query name from cookie or use default
var query_cookie = Y.Cookie.get("my_dashboard_query");
if (query_cookie) {
var cookie_value_found = 0;
Y.one("#query").get("options").each( function() {
if (this.get("value") == query_cookie) {
this.set('selected', true);
default_query = query_cookie;
cookie_value_found = 1;
}
});
if (!cookie_value_found) {
Y.Cookie.set("my_dashboard_query", "");
}
}
var bugQuery = new Y.DataSource.IO({ source: 'jsonrpc.cgi' });
bugQuery.plug(Y.Plugin.DataSourceJSONSchema, {
schema: {
resultListLocator: "result.result.bugs",
resultFields: ["bug_id", "changeddate", "changeddate_fancy",
"bug_status", "short_desc", "changeddate_api" ],
metaFields: {
description: "result.result.description",
heading: "result.result.heading",
buffer: "result.result.buffer",
mark_read: "result.result.mark_read"
}
}
});
bugQuery.on('error', function(e) {
try {
var response = Y.JSON.parse(e.data.responseText);
if (response.error)
e.error.message = response.error.message;
} catch(ex) {
// ignore
}
});
var bugQueryCallback = {
success: function(e) {
if (e.response) {
Y.one('#query_count_refresh').removeClass('bz_default_hidden');
Y.one("#query_container .query_description").setHTML(e.response.meta.description);
Y.one("#query_container .query_heading").setHTML(e.response.meta.heading);
Y.one("#query_bugs_found").setHTML(
'<a href="buglist.cgi?' + e.response.meta.buffer +
'" target="_blank">' + e.response.results.length + ' bugs found</a>');
bugQueryTable.set('data', e.response.results);
var mark_read = e.response.meta.mark_read;
if (mark_read) {
Y.one('#query_markread').setHTML( mark_read );
Y.one('#bar_markread').removeClass('bz_default_hidden');
Y.one('#query_markread_text').setHTML( mark_read );
Y.one('#query_markread').removeClass('bz_default_hidden');
}
else {
Y.one('#bar_markread').addClass('bz_default_hidden');
Y.one('#query_markread').addClass('bz_default_hidden');
}
Y.one('#query_markread_text').addClass('bz_default_hidden');
}
},
failure: function(o) {
if (o.error) {
alert("Failed to load bug list from Bugzilla:\n\n" + o.error.message);
} else {
alert("Failed to load bug list from Bugzilla.");
}
}
};
var updateQueryTable = function(query_name) {
if (!query_name) return;
counter = counter + 1;
lastChangesCache = {};
Y.one('#query_count_refresh').addClass('bz_default_hidden');
bugQueryTable.set('data', []);
bugQueryTable.render("#query_table");
bugQueryTable.showMessage('loadingMessage');
var bugQueryParams = {
version: "1.1",
method: "MyDashboard.run_bug_query",
id: counter,
params: { query : query_name,
Bugzilla_api_token : (BUGZILLA.api_token ? BUGZILLA.api_token : '')
}
};
bugQuery.sendRequest({
request: Y.JSON.stringify(bugQueryParams),
cfg: {
method: "POST",
headers: { 'Content-Type': 'application/json' }
},
callback: bugQueryCallback
});
};
var updatedFormatter = function(o) {
return '<span title="' + Y.Escape.html(o.value) + '">' +
Y.Escape.html(o.data.changeddate_fancy) + '</span>';
};
lastChangesQuery = new Y.DataSource.IO({ source: 'jsonrpc.cgi' });
lastChangesQuery.plug(Y.Plugin.DataSourceJSONSchema, {
schema: {
resultListLocator: "result.results",
resultFields: ["last_changes"],
}
});
lastChangesQuery.on('error', function(e) {
try {
var response = Y.JSON.parse(e.data.responseText);
if (response.error)
e.error.message = response.error.message;
} catch(ex) {
// ignore
}
});
bugQueryTable = new Y.DataTable({
columns: [
{ key: Y.Plugin.DataTableRowExpansion.column_key, label: ' ', sortable: false },
{ key: "bug_id", label: "Bug", allowHTML: true, sortable: true,
formatter: '<a href="show_bug.cgi?id={value}" target="_blank">{value}</a>' },
{ key: "changeddate", label: "Updated", formatter: updatedFormatter,
allowHTML: true, sortable: true },
{ key: "bug_status", label: "Status", sortable: true },
{ key: "short_desc", label: "Summary", sortable: true },
],
});
var last_changes_source = Y.one('#last-changes-template').getHTML(),
last_changes_template = Y.Handlebars.compile(last_changes_source);
var stub_source = Y.one('#last-changes-stub').getHTML(),
stub_template = Y.Handlebars.compile(stub_source);
bugQueryTable.plug(Y.Plugin.DataTableRowExpansion, {
uniqueIdKey: 'bug_id',
template: function(data) {
var bug_id = data.bug_id;
var lastChangesCallback = {
success: function(e) {
if (e.response) {
var last_changes = e.response.results[0].last_changes;
last_changes['bug_id'] = bug_id;
lastChangesCache[bug_id] = last_changes;
Y.one('#last_changes_stub_' + bug_id).setHTML(last_changes_template(last_changes));
}
},
failure: function(o) {
if (o.error) {
alert("Failed to load last changes from Bugzilla:\n\n" + o.error.message);
} else {
alert("Failed to load last changes from Bugzilla.");
}
}
};
if (!lastChangesCache[bug_id]) {
var lastChangesParams = {
version: "1.1",
method: "MyDashboard.run_last_changes",
params: {
bug_id: data.bug_id,
changeddate_api: data.changeddate_api,
Bugzilla_api_token : (BUGZILLA.api_token ? BUGZILLA.api_token : '')
}
};
lastChangesQuery.sendRequest({
request: Y.JSON.stringify(lastChangesParams),
cfg: {
method: "POST",
headers: { 'Content-Type': 'application/json' }
},
callback: lastChangesCallback
});
return stub_template({bug_id: bug_id});
}
else {
return last_changes_template(lastChangesCache[bug_id]);
}
}
});
bugQueryTable.plug(Y.Plugin.DataTableSort);
bugQueryTable.plug(Y.Plugin.DataTableDataSource, {
datasource: bugQuery
});
// Initial load
Y.on("contentready", function (e) {
updateQueryTable(default_query);
}, "#query_table");
Y.one('#query').on('change', function(e) {
var index = e.target.get('selectedIndex');
var selected_value = e.target.get("options").item(index).getAttribute('value');
updateQueryTable(selected_value);
Y.Cookie.set("my_dashboard_query", selected_value, { expires: new Date("January 12, 2025") });
});
Y.one('#query_refresh').on('click', function(e) {
var query_select = Y.one('#query');
var index = query_select.get('selectedIndex');
var selected_value = query_select.get("options").item(index).getAttribute('value');
updateQueryTable(selected_value);
});
Y.one('#query_markread').on('click', function(e) {
var data = bugQueryTable.data;
var bug_ids = [];
Y.one('#query_markread').addClass('bz_default_hidden');
Y.one('#query_markread_text').removeClass('bz_default_hidden');
for (var i = 0, l = data.size(); i < l; i++) {
bug_ids.push(data.item(i).get('bug_id'));
}
YAHOO.bugzilla.bugUserLastVisit.update(bug_ids);
YAHOO.bugzilla.bugInterest.unmark(bug_ids);
});
Y.one('#query_buglist').on('click', function(e) {
var data = bugQueryTable.data;
var ids = [];
for (var i = 0, l = data.size(); i < l; i++) {
ids.push(data.item(i).get('bug_id'));
}
var url = 'buglist.cgi?bug_id=' + ids.join('%2C');
window.open(url, '_blank');
});
});
<file_sep>/extensions/ProductDashboard/web/js/components.js
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0.
*/
YUI({
base: 'js/yui3/',
combine: false
}).use("datatable", "datatable-sort", "escape", function(Y) {
if (typeof PD.updated_recently != 'undefined') {
var columns = [
{ key:"id", label:"ID", sortable:true, allowHTML: true,
formatter: '<a href="show_bug.cgi?id={value}" target="_blank">{value}</a>' },
{ key:"bug_status", label:"Status", sortable:true },
{ key:"version", label:"Version", sortable:true },
{ key:"component", label:"Component", sortable:true },
{ key:"severity", label:"Severity", sortable:true },
{ key:"summary", label:"Summary", sortable:false },
];
var updatedRecentlyDataTable = new Y.DataTable({
columns: columns,
data: PD.updated_recently
});
updatedRecentlyDataTable.render("#updated_recently");
if (typeof PD.past_due != 'undefined') {
var pastDueDataTable = new Y.DataTable({
columns: columns,
data: PD.past_due
});
pastDueDataTable.render('#past_due');
}
}
if (typeof PD.component_counts != 'undefined') {
var summary_url = '<a href="page.cgi?id=productdashboard.html&product=' +
encodeURIComponent(PD.product_name) + '&bug_status=' +
encodeURIComponent(PD.bug_status) + '&tab=components';
var columns = [
{ key:"name", label:"Name", sortable:true, allowHTML: true,
formatter: function (o) {
return summary_url + '&component=' +
encodeURIComponent(o.value) + '">' +
Y.Escape.html(o.value) + '</a>'
}
},
{ key:"count", label:"Count", sortable:true },
{ key:"percentage", label:"Percentage", sortable:false, allowHTML: true,
formatter: '<div class="percentage"><div class="bar" style="width:{value}%"></div><div class="percent">{value}%</div></div>' },
{ key:"link", label:"Link", sortable:false, allowHTML: true }
];
var componentsDataTable = new Y.DataTable({
columns: columns,
data: PD.component_counts
});
componentsDataTable.render("#component_counts");
columns[0].formatter = function (o) {
return summary_url + '&version=' +
encodeURIComponent(o.value) + '">' +
Y.Escape.html(o.value) + '</a>';
};
var versionsDataTable = new Y.DataTable({
columns: columns,
data: PD.version_counts
});
versionsDataTable.render('#version_counts');
if (typeof PD.milestone_counts != 'undefined') {
columns[0].formatter = function (o) {
return summary_url + '&target_milestone=' +
encodeURIComponent(o.value) + '">' +
Y.Escape.html(o.value) + '</a>';
};
var milestonesDataTable = new Y.DataTable({
columns: columns,
data: PD.milestone_counts
});
milestonesDataTable.render('#milestone_counts');
}
}
});
<file_sep>/js/account.js
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0. */
$(function() {
function make_password_strength($password) {
return function(event) {
var password = $password.val();
var missing_features = {"upper": true, "lower": true, "numbers": true, "symbols": true, "length12": true};
var features = [],
charset = 0,
score = 0,
min_features = 3;
$("#password-meter").show();
$("#password-meter-label").show();
if (password.match(/[A-Z]/)) {
delete missing_features.upper;
features.push("upper");
charset += 26;
}
if (password.match(/[a-z]/)) {
delete missing_features.lower;
features.push("lower");
charset += 26;
}
if (password.match(/[0-9]/)) {
delete missing_features.numbers;
features.push("numbers");
charset += 10;
}
if (password.match(/[^A-Za-z0-9]/)) {
delete missing_features.symbols;
features.push("symbols");
charset += 30; // there are 30-32 typable characters on a keyboard.
}
if (password.length > 12) {
delete missing_features.length12;
features.push("length12");
}
$("#password-features li").removeClass("feature-ok");
features.forEach(function(name) {
$("#password-feature-" + name).addClass("feature-ok");
});
var entropy = Math.floor(Math.log(charset) * (password.length / Math.log(2)));
if (entropy) {
score = entropy/128;
}
$password.get(0).setCustomValidity("");
if (features.length < min_features) {
$("#password-msg")
.text("Password does not meet requirements")
.attr("class", "password-bad");
$password.get(0).setCustomValidity($("#password-msg").text());
}
else if (password.length < 8) {
$("#password-msg")
.text("Password is too short")
.attr("class", "password-bad");
$password.get(0).setCustomValidity($("#password-msg").text());
}
else {
$("#password-msg")
.text("Password meets requirements")
.attr("class", "password-good");
$password.get(0).setCustomValidity("");
}
if (entropy < 60) {
$("#password-meter")
.removeClass("meter-good meter-ok")
.addClass("meter-bad");
}
else if (entropy >= 120) {
$("#password-meter")
.removeClass("meter-bad meter-ok")
.addClass("meter-good");
}
else if (entropy > 60) {
$("#password-meter")
.removeClass("meter-bad meter-good")
.addClass("meter-ok");
}
if (score === 0) {
score = 0.01;
$("#password-meter")
.removeClass("meter-good meter-ok")
.addClass("meter-bad");
}
$("#password-meter").width(Math.max(0, Math.min($password.width()+10, Math.ceil(($password.width()+10) * score))));
};
}
function make_password_confirm($password1, $password2) {
return function (event) {
if ($password1.val() != $password2.val()) {
$password2.get(0).setCustomValidity("Does not match previous password");
}
else {
$password2.get(0).setCustomValidity("");
}
};
}
var password1_sel, password2_sel;
var complexity = $("#password-features").data("password-complexity");
var page = $("#password-features").data("password-page");
var check_password_strength, check_password_confirm;
if (page == "account") {
$("#new_password1, #new_password2, #new_login_name").change(function() {
$("#old_password").attr("required", true);
});
}
if (complexity == "bmo") {
if (page == "confirm") {
password1_sel = "#passwd1";
password2_sel = "#passwd2";
}
else {
password1_sel = <PASSWORD>";
password2_sel = <PASSWORD>";
}
$("#password-features").show();
check_password_strength = make_password_strength($(password1_sel));
check_password_confirm = make_password_confirm($(password1_sel), $(password2_sel));
$(password1_sel).on("input", check_password_strength);
$(password1_sel).on("focus", check_password_strength);
$(password1_sel).on("blur", check_password_confirm);
$(password1_sel).on("change", check_password_confirm);
$(password2_sel).on("input", check_password_confirm);
}
else {
$("#password-features").hide();
}
// account disabling
$('#account-disable-toggle')
.click(function(event) {
event.preventDefault();
var that = $(this);
if (that.data('open')) {
$('#account-disable-spinner').html('▸');
$('#account-disable').hide();
that.data('open', false);
}
else {
$('#account-disable-spinner').html('▾');
$('#account-disable').show();
that.data('open', true);
}
});
$('#account-disable-confirm')
.click(function(event) {
$('#account-disable-button').prop('disabled', !$(this).is(':checked'));
})
.prop('checked', false);
$('#account-disable-button')
.click(function(event) {
$('#account_disable').val('1');
document.userprefsform.submit();
});
$(window).on('pageshow', function() {
$('#account_disable').val('');
});
// forgot password
$('#forgot-password')
.click(function(event) {
event.preventDefault();
$('#forgot-form').submit();
});
// mfa
$('#mfa-select-totp')
.click(function(event) {
event.preventDefault();
$('#mfa').val('TOTP');
$('#mfa-select').hide();
$('#update').attr('disabled', true);
$('#mfa-totp-enable-code').attr('required', true);
$('#mfa-confirm').show();
$('.mfa-api-blurb').show();
$('#mfa-enable-shared').show();
$('#mfa-enable-totp').show();
$('#mfa-totp-throbber').show();
$('#mfa-totp-issued').hide();
var url = 'rest/user/mfa/totp/enroll' +
'?Bugzilla_api_token=' + encodeURIComponent(BUGZILLA.api_token);
$.ajax({
"url": url,
"contentType": "application/json",
"processData": false
})
.done(function(data) {
$('#mfa-totp-throbber').hide();
var iframe = $('#mfa-enable-totp-frame').contents();
iframe.find('#qr').attr('src', 'data:image/png;base64,' + data.png);
iframe.find('#secret').text(data.secret32);
$('#mfa-totp-issued').show();
$('#mfa-password').focus();
$('#update').attr('disabled', false);
})
.error(function(data) {
$('#mfa-totp-throbber').hide();
if (data.statusText === 'abort')
return;
var message = data.responseJSON ? data.responseJSON.message : 'Unexpected Error';
console.log(message);
});
});
$('#mfa-select-duo')
.click(function(event) {
event.preventDefault();
$('#mfa').val('Duo');
$('#mfa-select').hide();
$('#update').attr('disabled', false);
$('#mfa-duo-user').attr('required', true);
$('#mfa-confirm').show();
$('.mfa-api-blurb').show();
$('#mfa-enable-shared').show();
$('#mfa-enable-duo').show();
$('#mfa-password').focus();
});
$('#mfa-disable')
.click(function(event) {
event.preventDefault();
$('.mfa-api-blurb, .mfa-buttons').hide();
$('#mfa-disable-container, #mfa-auth-container').show();
$('#mfa-confirm').show();
$('#mfa-password').focus();
$('#update').attr('disabled', false);
$('.mfa-protected').hide();
$(this).hide();
});
$('#mfa-recovery')
.click(function(event) {
event.preventDefault();
$('.mfa-api-blurb, .mfa-buttons').hide();
$('#mfa-recovery-container, #mfa-auth-container').show();
$('#mfa-password').focus();
$('#update').attr('disabled', false).val('Generate Printable Recovery Codes');
$('#mfa-action').val('recovery');
$(this).hide();
});
var totp_popup;
$('#mfa-totp-apps, #mfa-totp-text')
.click(function(event) {
event.preventDefault();
totp_popup = $('#' + $(this).attr('id') + '-popup').bPopup({
speed: 100,
followSpeed: 100,
modalColor: '#444'
});
});
$('.mfa-totp-popup-close')
.click(function(event) {
event.preventDefault();
totp_popup.close();
});
if ($('#mfa-action').length) {
$('#update').attr('disabled', true);
}
// api-key
$('#apikey-toggle-revoked')
.click(function(event) {
event.preventDefault();
$('.apikey_revoked.bz_tui_hidden').removeClass('bz_tui_hidden');
if ($('.apikey_revoked').is(':visible')) {
$('.apikey_revoked').hide();
$(this).text('Show Revoked Keys');
}
else {
$('.apikey_revoked').show();
$(this).text('Hide Revoked Keys');
}
});
$('#new_key')
.change(function(event) {
if ($(this).is(':checked')) {
$('#new_description').focus();
}
});
});
<file_sep>/docs/en/rst/integrating/auth-delegation.rst
.. _auth-delegation:
Authentication Delegation via API Keys
######################################
Bugzilla provides a mechanism for web apps to request (with the user's consent)
an API key. API keys allow the web app to perform any action as the user and are as
a result very powerful. Because of this power, this feature is disabled by default.
Authentication Flow
-------------------
The authentication process begins by directing the user to th the Bugzilla site's auth.cgi.
For the sake of this example, our application's URL is `http://app.example.org`
and the Bugzilla site is `http://bugzilla.mozilla.org`.
1. Provide a link or redirect the user to `http://bugzilla.mozilla.org/auth.cgi?callback=http://app.example.org/callback&description=app%description`
2. Assuming the user is agreeable, the following will happen:
1. Bugzilla will issue a POST request to `http://app.example.org/callback`
with a the request body data being a JSON object with keys `client_api_key` and `client_api_login`.
2. The callback, when responding to the POST request must return a JSON object with a key `result`. This result
is intended to be a unique token used to identify this transaction.
3. Bugzilla will then cause the useragent to redirect (using a GET request) to `http://app.example.org/callback`
with additional query string parameters `client_api_login` and `callback_result`.
4. At this point, the consumer now has the api key and login information. Be sure to compare the `callback_result` to whatever result was initially sent back
to Bugzilla.
3. Finally, you should check that the API key and login are valid, using the :ref:`rest_user_whoami` REST
resource.
Your application should take measures to ensure when receiving a user at your
callback URL that you previously redirected them to Bugzilla. The simplest method would be ensuring the callback url always has the
hostname and path you specified, with only the query string parameters varying.
The description should include the name of your application, in a form that will be recognizable to users.
This description is used in the :ref:`API Keys tab <api-keys>` in the Preferences page.
The API key passed to the callback will be valid until the user revokes it.
<file_sep>/extensions/MyDashboard/web/js/flags.js
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0.
*/
// Flag tables
YUI({
base: 'js/yui3/',
combine: false
}).use("node", "datatable", "datatable-sort", "json-stringify", "escape",
"datatable-datasource", "datasource-io", "datasource-jsonschema", function(Y) {
// Common
var counter = 0;
var dataSource = {
requestee: null,
requester: null
};
var dataTable = {
requestee: null,
requester: null
};
var updateFlagTable = function(type) {
if (!type) return;
counter = counter + 1;
var callback = {
success: function(e) {
if (e.response) {
Y.one('#' + type + '_count_refresh').removeClass('bz_default_hidden');
Y.one("#" + type + "_flags_found").setHTML(
e.response.results.length + ' flags found');
dataTable[type].set('data', e.response.results);
}
},
failure: function(o) {
if (o.error) {
alert("Failed to load flag list from Bugzilla:\n\n" + o.error.message);
} else {
alert("Failed to load flag list from Bugzilla.");
}
}
};
var json_object = {
version: "1.1",
method: "MyDashboard.run_flag_query",
id: counter,
params: { type : type,
Bugzilla_api_token : (BUGZILLA.api_token ? BUGZILLA.api_token : '')
}
};
var stringified = Y.JSON.stringify(json_object);
Y.one('#' + type + '_count_refresh').addClass('bz_default_hidden');
dataTable[type].set('data', []);
dataTable[type].render("#" + type + "_table");
dataTable[type].showMessage('loadingMessage');
dataSource[type].sendRequest({
request: stringified,
cfg: {
method: "POST",
headers: { 'Content-Type': 'application/json' }
},
callback: callback
});
};
var loadBugList = function(type) {
if (!type) return;
var data = dataTable[type].data;
var ids = [];
for (var i = 0, l = data.size(); i < l; i++) {
ids.push(data.item(i).get('bug_id'));
}
var url = 'buglist.cgi?bug_id=' + ids.join('%2C');
window.open(url, '_blank');
};
var bugLinkFormatter = function(o) {
var bug_closed = "";
if (o.data.bug_status == 'RESOLVED' || o.data.bug_status == 'VERIFIED') {
bug_closed = "bz_closed";
}
return '<a href="show_bug.cgi?id=' + encodeURIComponent(o.value) +
'" target="_blank" ' + 'title="' + Y.Escape.html(o.data.bug_status) + ' - ' +
Y.Escape.html(o.data.bug_summary) + '" class="' + Y.Escape.html(bug_closed) +
'">' + o.value + '</a>';
};
var updatedFormatter = function(o) {
return '<span title="' + Y.Escape.html(o.value) + '">' +
Y.Escape.html(o.data.updated_fancy) + '</span>';
};
var requesteeFormatter = function(o) {
return o.value
? Y.Escape.html(o.value)
: '<i>anyone</i>';
};
var flagNameFormatter = function(o) {
if (parseInt(o.data.attach_id)
&& parseInt(o.data.is_patch)
&& MyDashboard.splinter_base)
{
return '<a href="' + MyDashboard.splinter_base +
(MyDashboard.splinter_base.indexOf('?') == -1 ? '?' : '&') +
'bug=' + encodeURIComponent(o.data.bug_id) +
'&attachment=' + encodeURIComponent(o.data.attach_id) +
'" target="_blank" title="Review this patch">' +
Y.Escape.html(o.value) + '</a>';
}
else {
return Y.Escape.html(o.value);
}
};
// Requestee
dataSource.requestee = new Y.DataSource.IO({ source: 'jsonrpc.cgi' });
dataSource.requestee.on('error', function(e) {
try {
var response = Y.JSON.parse(e.data.responseText);
if (response.error)
e.error.message = response.error.message;
} catch(ex) {
// ignore
}
});
dataTable.requestee = new Y.DataTable({
columns: [
{ key: "requester", label: "Requester", sortable: true },
{ key: "type", label: "Flag", sortable: true,
formatter: flagNameFormatter, allowHTML: true },
{ key: "bug_id", label: "Bug", sortable: true,
formatter: bugLinkFormatter, allowHTML: true },
{ key: "updated", label: "Updated", sortable: true,
formatter: updatedFormatter, allowHTML: true }
],
strings: {
emptyMessage: 'No flag data found.',
}
});
dataTable.requestee.plug(Y.Plugin.DataTableSort);
dataTable.requestee.plug(Y.Plugin.DataTableDataSource, {
datasource: dataSource.requestee
});
dataSource.requestee.plug(Y.Plugin.DataSourceJSONSchema, {
schema: {
resultListLocator: "result.result.requestee",
resultFields: ["requester", "type", "attach_id", "is_patch", "bug_id",
"bug_status", "bug_summary", "updated", "updated_fancy"]
}
});
dataTable.requestee.render("#requestee_table");
Y.one('#requestee_refresh').on('click', function(e) {
updateFlagTable('requestee');
});
Y.one('#requestee_buglist').on('click', function(e) {
loadBugList('requestee');
});
// Requester
dataSource.requester = new Y.DataSource.IO({ source: 'jsonrpc.cgi' });
dataSource.requester.on('error', function(e) {
try {
var response = Y.JSON.parse(e.data.responseText);
if (response.error)
e.error.message = response.error.message;
} catch(ex) {
// ignore
}
});
dataTable.requester = new Y.DataTable({
columns: [
{ key:"requestee", label:"Requestee", sortable:true,
formatter: requesteeFormatter, allowHTML: true },
{ key:"type", label:"Flag", sortable:true,
formatter: flagNameFormatter, allowHTML: true },
{ key:"bug_id", label:"Bug", sortable:true,
formatter: bugLinkFormatter, allowHTML: true },
{ key: "updated", label: "Updated", sortable: true,
formatter: updatedFormatter, allowHTML: true }
],
strings: {
emptyMessage: 'No flag data found.',
}
});
dataTable.requester.plug(Y.Plugin.DataTableSort);
dataTable.requester.plug(Y.Plugin.DataTableDataSource, {
datasource: dataSource.requester
});
dataSource.requester.plug(Y.Plugin.DataSourceJSONSchema, {
schema: {
resultListLocator: "result.result.requester",
resultFields: ["requestee", "type", "attach_id", "is_patch", "bug_id",
"bug_status", "bug_summary", "updated", "updated_fancy"]
}
});
// Initial load
Y.on("contentready", function (e) {
updateFlagTable("requestee");
}, "#requestee_table");
Y.on("contentready", function (e) {
updateFlagTable("requester");
}, "#requester_table");
Y.one('#requester_refresh').on('click', function(e) {
updateFlagTable('requester');
});
Y.one('#requester_buglist').on('click', function(e) {
loadBugList('requester');
});
});
<file_sep>/extensions/GuidedBugEntry/web/js/products.js
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0. */
/* Product-specifc configuration for guided bug entry
*
* related: array of product names which will also be searched for duplicates
* version: function which returns a version (eg. detected from UserAgent)
* support: string which is displayed at the top of the duplicates page
* secgroup: the group to place confidential bugs into
* defaultComponent: the default compoent to select. Defaults to 'General'
* noComponentSelection: when true, the default component will always be
* used. Defaults to 'false';
* detectPlatform: when true the platform and op_sys will be set from the
* browser's user agent. when false, these will be set to All
*/
var products = {
"addons.mozilla.org": {
l10n: true
},
"Firefox": {
related: [ "Core", "Toolkit" ],
version: function() {
var re = /Firefox\/(\d+)\.(\d+)/i;
var match = re.exec(navigator.userAgent);
if (match) {
var maj = match[1];
var min = match[2];
if (maj * 1 >= 5) {
return maj + " Branch";
} else {
return maj + "." + min + " Branch";
}
} else {
return false;
}
},
defaultComponent: "Untriaged",
noComponentSelection: true,
detectPlatform: true,
l10n: true,
support:
'If you are new to Firefox or Bugzilla, please consider checking ' +
'<a href="http://support.mozilla.org/">' +
'<img src="extensions/GuidedBugEntry/web/images/sumo.png" width="16" height="16" align="absmiddle">' +
' <b>Firefox Help</b></a> instead of creating a bug.'
},
"Firefox for Android": {
related: [ "Core", "Toolkit" ],
detectPlatform: true,
l10n: true,
support:
'If you are new to Firefox or Bugzilla, please consider checking ' +
'<a href="http://support.mozilla.org/">' +
'<img src="extensions/GuidedBugEntry/web/images/sumo.png" width="16" height="16" align="absmiddle">' +
' <b>Firefox Help</b></a> instead of creating a bug.'
},
"SeaMonkey": {
related: [ "Core", "Toolkit", "MailNews Core" ],
detectPlatform: true,
l10n: true,
version: function() {
var re = /SeaMonkey\/(\d+)\.(\d+)/i;
var match = re.exec(navigator.userAgent);
if (match) {
var maj = match[1];
var min = match[2];
return "SeaMonkey " + maj + "." + min + " Branch";
} else {
return false;
}
}
},
"Calendar": {
l10n: true
},
"Camino": {
related: [ "Core", "Toolkit" ],
detectPlatform: true
},
"Core": {
detectPlatform: true
},
"Thunderbird": {
related: [ "Core", "Toolkit", "MailNews Core" ],
detectPlatform: true,
l10n: true,
defaultComponent: "Untriaged",
componentFilter : function(components) {
var index = -1;
for (var i = 0, l = components.length; i < l; i++) {
if (components[i].name == 'General') {
index = i;
break;
}
}
if (index != -1) {
components.splice(index, 1);
}
return components;
}
},
"Marketplace": {
l10n: true
},
"Penelope": {
related: [ "Core", "Toolkit", "MailNews Core" ]
},
"Bugzilla": {
support:
'Please use <a href="http://landfill.bugzilla.org/">Bugzilla Landfill</a> to file "test bugs".'
},
"bugzilla.mozilla.org": {
related: [ "Bugzilla" ],
support:
'Please use <a href="http://landfill.bugzilla.org/">Bugzilla Landfill</a> to file "test bugs".'
}
};
<file_sep>/extensions/BMO/web/js/edituser_menu.js
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0. */
function show_usermenu(id, email, show_edit) {
var items = [
{
name: "Profile",
callback: function () {
var href = "user_profile?login=" + encodeURIComponent(email);
window.open(href, "_blank");
}
},
{
name: "Activity",
callback: function () {
var href = "page.cgi?id=user_activity.html&action=run&from=-14d&who=" + encodeURIComponent(email);
window.open(href, "_blank");
}
},
{
name: "Mail",
callback: function () {
var href = "mailto:" + encodeURIComponent(email);
window.open(href, "_blank");
}
}
];
if (show_edit) {
items.push({
name: "Edit",
callback: function () {
var href = "editusers.cgi?action=edit&userid=" + id;
window.open(href, "_blank");
}
});
}
$.contextMenu({
selector: ".vcard_" + id,
trigger: "left",
items: items
});
}
<file_sep>/docs/en/rst/api/core/v1/comment.rst
Comments
========
.. _rest_comments:
Get Comments
------------
This allows you to get data about comments, given a bug ID or comment ID.
**Request**
To get all comments for a particular bug using the bug ID or alias:
.. code-block:: text
GET /rest/bug/(id_or_alias)/comment
To get a specific comment based on the comment ID:
.. code-block:: text
GET /rest/bug/comment/(comment_id)
=============== ======== ======================================================
name type description
=============== ======== ======================================================
**id_or_alias** mixed A single integer bug ID or alias.
**comment_id** int A single integer comment ID.
new_since datetime If specified, the method will only return comments
*newer* than this time. This only affects comments
returned from the ``ids`` argument. You will always be
returned all comments you request in the
``comment_ids`` argument, even if they are older than
this date.
=============== ======== ======================================================
**Response**
.. code-block:: js
{
"bugs": {
"35": {
"comments": [
{
"time": "2000-07-25T13:50:04Z",
"text": "test bug to fix problem in removing from cc list.",
"bug_id": 35,
"count": 0,
"attachment_id": null,
"is_private": false,
"tags": [],
"creator": "<EMAIL>",
"creation_time": "2000-07-25T13:50:04Z",
"id": 75
}
]
}
},
"comments": {}
}
Two items are returned:
``bugs`` This is used for bugs specified in ``ids``. This is an object,
where the keys are the numeric IDs of the bugs, and the value is
a object with a single key, ``comments``, which is an array of comments.
(The format of comments is described below.)
Any individual bug will only be returned once, so if you specify an ID
multiple times in ``ids``, it will still only be returned once.
``comments`` Each individual comment requested in ``comment_ids`` is
returned here, in a object where the numeric comment ID is the key,
and the value is the comment. (The format of comments is described below.)
A "comment" as described above is a object that contains the following items:
============= ======== ========================================================
name type description
============= ======== ========================================================
id int The globally unique ID for the comment.
bug_id int The ID of the bug that this comment is on.
attachment_id int If the comment was made on an attachment, this will be
the ID of that attachment. Otherwise it will be null.
count int The number of the comment local to the bug. The
Description is 0, comments start with 1.
text string The actual text of the comment.
creator string The login name of the comment's author.
time datetime The time (in Bugzilla's timezone) that the comment was
added.
creation_time datetime This is exactly same as the ``time`` key. Use this
field instead of ``time`` for consistency with other
methods including :ref:`rest_single_bug` and
:ref:`rest_attachments`.
For compatibility, ``time`` is still usable. However,
please note that ``time`` may be deprecated and removed
in a future release.
is_private boolean ``true`` if this comment is private (only visible to a
certain group called the "insidergroup"), ``false``
otherwise.
============= ======== ========================================================
**Errors**
This method can throw all the same errors as :ref:`rest_single_bug`. In addition,
it can also throw the following errors:
* 110 (Comment Is Private)
You specified the id of a private comment in the "comment_ids"
argument, and you are not in the "insider group" that can see
private comments.
* 111 (Invalid Comment ID)
You specified an id in the "comment_ids" argument that is invalid--either
you specified something that wasn't a number, or there is no comment with
that id.
.. _rest_add_comment:
Create Comments
---------------
This allows you to add a comment to a bug in Bugzilla.
**Request**
To create a comment on a current bug.
.. code-block:: text
POST /rest/bug/(id)/comment
.. code-block:: js
{
"ids" : [123,..],
"comment" : "This is an additional comment",
"is_private" : false
}
``ids`` is optional in the data example above and can be used to specify adding
a comment to more than one bug at the same time.
=========== ======= ===========================================================
name type description
=========== ======= ===========================================================
**id** int The ID or alias of the bug to append a comment to.
ids array List of integer bug IDs to add the comment to.
**comment** string The comment to append to the bug. If this is empty
or all whitespace, an error will be thrown saying that you
did not set the ``comment`` parameter.
is_private boolean If set to true, the comment is private, otherwise it is
assumed to be public.
work_time double Adds this many hours to the "Hours Worked" on the bug.
If you are not in the time tracking group, this value will
be ignored.
=========== ======= ===========================================================
**Response**
.. code-block:: js
{
"id" : 789
}
==== ==== =================================
name type description
==== ==== =================================
id int ID of the newly-created comment.
==== ==== =================================
**Errors**
* 54 (Hours Worked Too Large)
You specified a "work_time" larger than the maximum allowed value of
"99999.99".
* 100 (Invalid Bug Alias)
If you specified an alias and there is no bug with that alias.
* 101 (Invalid Bug ID)
The id you specified doesn't exist in the database.
* 109 (Bug Edit Denied)
You did not have the necessary rights to edit the bug.
* 113 (Can't Make Private Comments)
You tried to add a private comment, but don't have the necessary rights.
* 114 (Comment Too Long)
You tried to add a comment longer than the maximum allowed length
(65,535 characters).
* 140 (Markdown Disabled)
You tried to set the "is_markdown" flag to true but the Markdown feature
is not enabled.
.. _rest_search_comment_tags:
Search Comment Tags
-------------------
Searches for tags which contain the provided substring.
**Request**
To search for comment tags:
.. code-block:: text
GET /rest/bug/comment/tags/(query)
Example:
.. code-block:: text
GET /rest/bug/comment/tags/spa
========= ====== ====================================================
name type description
========= ====== ====================================================
**query** string Only tags containg this substring will be returned.
limit int If provided will return no more than ``limit`` tags.
Defaults to ``10``.
========= ====== ====================================================
**Response**
.. code-block:: js
[
"spam"
]
An array of matching tags.
**Errors**
This method can throw all of the errors that :ref:`rest_single_bug` throws, plus:
* 125 (Comment Tagging Disabled)
Comment tagging support is not available or enabled.
.. _rest_update_comment_tags:
Update Comment Tags
-------------------
Adds or removes tags from a comment.
**Request**
To update the tags comments attached to a comment:
.. code-block:: text
PUT /rest/bug/comment/(comment_id)/tags
Example:
.. code-block:: js
{
"comment_id" : 75,
"add" : ["spam", "bad"]
}
============== ===== ====================================
name type description
============== ===== ====================================
**comment_id** int The ID of the comment to update.
add array The tags to attach to the comment.
remove array The tags to detach from the comment.
============== ===== ====================================
**Response**
.. code-block:: js
[
"bad",
"spam"
]
An array of strings containing the comment's updated tags.
**Errors**
This method can throw all of the errors that :ref:`rest_single_bug` throws, plus:
* 125 (Comment Tagging Disabled)
Comment tagging support is not available or enabled.
* 126 (Invalid Comment Tag)
The comment tag provided was not valid (eg. contains invalid characters).
* 127 (Comment Tag Too Short)
The comment tag provided is shorter than the minimum length.
* 128 (Comment Tag Too Long)
The comment tag provided is longer than the maximum length.
.. _rest_render_comment:
Render Comment
--------------
Returns the HTML rendering of the provided comment text.
**Request**
.. code-block:: text
POST /rest/bug/comment/render
Example:
.. code-block:: js
{
"id" : 2345,
"text" : "This issue has been fixed in bug 1234."
}
============== ====== ================================================
name type description
============== ====== ================================================
**text** string Comment text to render.
id int The ID of the bug to render the comment against.
============== ====== =================================================
**Response**
.. code-block:: js
{
"html" : "This issue has been fixed in <a class=\"bz_bug_link
bz_status_RESOLVED bz_closed\" title=\"RESOLVED FIXED - some issue that was fixed\" href=\"show_bug.cgi?id=1234\">bug 1234</a>."
]
==== ====== ===================================
name type description
==== ====== ===================================
html string Text containing the HTML rendering.
==== ====== ===================================
**Errors**
This method can throw all of the errors that :ref:`rest_single_bug` throws.
<file_sep>/docs/en/rst/administering/parameters.rst
.. _parameters:
Parameters
##########
Bugzilla is configured by changing various parameters, accessed
from the :guilabel:`Parameters` link, which is found on the Administration
page. The parameters are divided into several categories,
accessed via the menu on the left.
.. _param-required-settings:
Required Settings
=================
The core required parameters for any Bugzilla installation are set
here. :param:`urlbase` is always required; the other parameters should be
set, or it must be explicitly decided not to
set them, before the new Bugzilla installation starts to be used.
urlbase
Defines the fully qualified domain name and web
server path to this Bugzilla installation.
For example, if the Bugzilla query page is
:file:`http://www.foo.com/bugzilla/query.cgi`,
the :param:`urlbase` should be set
to :paramval:`http://www.foo.com/bugzilla/`.
ssl_redirect
If enabled, Bugzilla will force HTTPS (SSL) connections, by
automatically redirecting any users who try to use a non-SSL
connection. Also, when this is enabled, Bugzilla will send out links
using :param:`sslbase` in emails instead of :param:`urlbase`.
sslbase
Defines the fully qualified domain name and web
server path for HTTPS (SSL) connections to this Bugzilla installation.
For example, if the Bugzilla main page is
:file:`https://www.foo.com/bugzilla/index.cgi`,
the :param:`sslbase` should be set
to :paramval:`https://www.foo.com/bugzilla/`.
cookiepath
Defines a path, relative to the web document root, that Bugzilla
cookies will be restricted to. For example, if the
:param:`urlbase` is set to
:file:`http://www.foo.com/bugzilla/`, the
:param:`cookiepath` should be set to
:paramval:`/bugzilla/`. Setting it to :paramval:`/` will allow all sites
served by this web server or virtual host to read Bugzilla cookies.
.. _param-general:
General
=======
maintainer
Email address of the person
responsible for maintaining this Bugzilla installation.
The address need not be that of a valid Bugzilla account.
utf8
Use UTF-8 (Unicode) encoding for all text in Bugzilla. Installations where
this parameter is set to :paramval:`off` should set it to :paramval:`on` only
after the data has been converted from existing legacy character
encodings to UTF-8, using the
:file:`contrib/recode.pl` script.
.. note:: If you turn this parameter from :paramval:`off` to :paramval:`on`,
you must re-run :file:`checksetup.pl` immediately afterward.
shutdownhtml
If there is any text in this field, this Bugzilla installation will
be completely disabled and this text will appear instead of all
Bugzilla pages for all users, including Admins. Used in the event
of site maintenance or outage situations.
announcehtml
Any text in this field will be displayed at the top of every HTML
page in this Bugzilla installation. The text is not wrapped in any
tags. For best results, wrap the text in a ``<div>``
tag. Any style attributes from the CSS can be applied. For example,
to make the text green inside of a red box, add ``id=message``
to the ``<div>`` tag.
upgrade_notification
Enable or disable a notification on the homepage of this Bugzilla
installation when a newer version of Bugzilla is available. This
notification is only visible to administrators. Choose :paramval:`disabled`
to turn off the notification. Otherwise, choose which version of
Bugzilla you want to be notified about: :paramval:`development_snapshot` is the
latest release from the master branch, :paramval:`latest_stable_release` is the most
recent release available on the most recent stable branch, and
:paramval:`stable_branch_release` is the most recent release on the branch
this installation is based on.
.. _param-administrative-policies:
Administrative Policies
=======================
This page contains parameters for basic administrative functions.
Options include whether to allow the deletion of bugs and users,
and whether to allow users to change their email address.
allowbugdeletion
The pages to edit products and components can delete all associated bugs when you delete a product (or component). Since that is a pretty scary idea, you have to turn on this option before any such deletions will ever happen.
allowemailchange
Users can change their own email address through the preferences. Note that the change is validated by emailing both addresses, so switching this option on will not let users use an invalid address.
allowuserdeletion
The user editing pages are capable of letting you delete user accounts. Bugzilla will issue a warning in case you'd run into inconsistencies when you're about to do so, but such deletions still remain scary. So, you have to turn on this option before any such deletions will ever happen.
last_visit_keep_days
This option controls how many days Bugzilla will remember that users have visited specific bugs.
.. _param-user-authentication:
User Authentication
===================
This page contains the settings that control how this Bugzilla
installation will do its authentication. Choose what authentication
mechanism to use (the Bugzilla database, or an external source such
as LDAP), and set basic behavioral parameters. For example, choose
whether to require users to login to browse bugs, the management
of authentication cookies, and the regular expression used to
validate email addresses. Some parameters are highlighted below.
auth_env_id
Environment variable used by external authentication system to store a unique identifier for each user. Leave it blank if there isn't one or if this method of authentication is not being used.
auth_env_email
Environment variable used by external authentication system to store each user's email address. This is a required field for environmental authentication. Leave it blank if you are not going to use this feature.
auth_env_realname
Environment variable used by external authentication system to store the user's real name. Leave it blank if there isn't one or if this method of authentication is not being used.
user_info_class
Mechanism(s) to be used for gathering a user's login information. More than one may be selected. If the first one returns nothing, the second is tried, and so on. The types are:
* :paramval:`CGI`: asks for username and password via CGI form interface.
* :paramval:`Env`: info for a pre-authenticated user is passed in system environment variables.
user_verify_class
Mechanism(s) to be used for verifying (authenticating) information gathered by user_info_class. More than one may be selected. If the first one cannot find the user, the second is tried, and so on. The types are:
* :paramval:`DB`: Bugzilla's built-in authentication. This is the most common choice.
* :paramval:`RADIUS`: RADIUS authentication using a RADIUS server. Using this method requires additional parameters to be set. Please see :ref:`param-radius` for more information.
* :paramval:`LDAP`: LDAP authentication using an LDAP server. Using this method requires additional parameters to be set. Please see :ref:`param-ldap` for more information.
rememberlogin
Controls management of session cookies.
* :paramval:`on` - Session cookies never expire (the user has to login only once per browser).
* :paramval:`off` - Session cookies last until the users session ends (the user will have to login in each new browser session).
* :paramval:`defaulton`/:paramval:`defaultoff` - Default behavior as described above, but user can choose whether Bugzilla will remember their login or not.
requirelogin
If this option is set, all access to the system beyond the front page will require a login. No anonymous users will be permitted.
webservice_email_filter
Filter email addresses returned by the WebService API depending on if the user is logged in or not. This works similarly to how the web UI currently filters email addresses. If requirelogin is enabled, then this parameter has no effect as users must be logged in to use Bugzilla anyway.
emailregexp
Defines the regular expression used to validate email addresses
used for login names. The default attempts to match fully
qualified email addresses (i.e. '<EMAIL>') in a slightly
more restrictive way than what is allowed in RFC 2822.
Another popular value to put here is :paramval:`^[^@]+`, which means 'local usernames, no @ allowed.'
emailregexpdesc
This description is shown to the user to explain which email addresses are allowed by the :param:`emailregexp` param.
emailsuffix
This is a string to append to any email addresses when actually sending mail to that address. It is useful if you have changed the :param:`emailregexp` param to only allow local usernames, but you want the mail to be delivered to <EMAIL>.
createemailregexp
This defines the (case-insensitive) regexp to use for email addresses that are permitted to self-register. The default (:paramval:`.*`) permits any account matching the emailregexp to be created. If this parameter is left blank, no users will be permitted to create their own accounts and all accounts will have to be created by an administrator.
password_complexity
Set the complexity required for passwords. In all cases must the passwords be at least 6 characters long.
* :paramval:`no_constraints` - No complexity required.
* :paramval:`mixed_letters` - Passwords must contain at least one UPPER and one lower case letter.
* :paramval:`letters_numbers` - Passwords must contain at least one UPPER and one lower case letter and a number.
* :paramval:`letters_numbers_specialchars` - Passwords must contain at least one letter, a number and a special character.
password_check_on_login
If set, Bugzilla will check that the password meets the current complexity rules and minimum length requirements when the user logs into the Bugzilla web interface. If it doesn't, the user would not be able to log in, and will receive a message to reset their password.
auth_delegation
If set, Bugzilla will allow other websites to request API keys from its own users. See :ref:`auth-delegation`.
.. _param-attachments:
Attachments
===========
This page allows for setting restrictions and other parameters
regarding attachments to bugs. For example, control size limitations
and whether to allow pointing to external files via a URI.
allow_attachment_display
If this option is on, users will be able to view attachments from their browser, if their browser supports the attachment's MIME type. If this option is off, users are forced to download attachments, even if the browser is able to display them.
If you do not trust your users (e.g. if your Bugzilla is public), you should either leave this option off, or configure and set the :param:`attachment_base` parameter (see below). Untrusted users may upload attachments that could be potentially damaging if viewed directly in the browser.
attachment_base
When the :param:`allow_attachment_display` parameter is on, it is possible for a malicious attachment to steal your cookies or perform an attack on Bugzilla using your credentials.
If you would like additional security on attachments to avoid this, set this parameter to an alternate URL for your Bugzilla that is not the same as :param:`urlbase` or :param:`sslbase`. That is, a different domain name that resolves to this exact same Bugzilla installation.
Note that if you have set the :param:`cookiedomain` parameter, you should set :param:`attachment_base` to use a domain that would not be matched by :param:`cookiedomain`.
For added security, you can insert ``%bugid%`` into the URL, which will be replaced with the ID of the current bug that the attachment is on, when you access an attachment. This will limit attachments to accessing only other attachments on the same bug. Remember, though, that all those possible domain names (such as 1234.your.domain.com) must point to this same Bugzilla instance. To set this up you need to investigate wildcard DNS.
allow_attachment_deletion
If this option is on, administrators will be able to delete the contents
of attachments (i.e. replace the attached file with a 0 byte file),
leaving only the metadata.
maxattachmentsize
The maximum size (in kilobytes) of attachments to be stored in the database. If a file larger than this size is attached to a bug, Bugzilla will look at the :param:`maxlocalattachment` parameter to determine if the file can be stored locally on the web server. If the file size exceeds both limits, then the attachment is rejected. Setting both parameters to 0 will prevent attaching files to bugs.
Some databases have default limits which prevent storing larger attachments in the database. E.g. MySQL has a parameter called `max_allowed_packet <http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html>`_, whose default varies by distribution. Setting :param:`maxattachmentsize` higher than your current setting for this value will produce an error.
maxlocalattachment
The maximum size (in megabytes) of attachments to be stored locally on the web server. If set to a value lower than the :param:`maxattachmentsize` parameter, attachments will never be kept on the local filesystem.
Whether you use this feature or not depends on your environment. Reasons to store some or all attachments as files might include poor database performance for large binary blobs, ease of backup/restore/browsing, or even filesystem-level deduplication support. However, you need to be aware of any limits on how much data your webserver environment can store. If in doubt, leave the value at 0.
Note that changing this value does not affect any already-submitted attachments.
.. _param-bug-change-policies:
Bug Change Policies
===================
Set policy on default behavior for bug change events. For example,
choose which status to set a bug to when it is marked as a duplicate,
and choose whether to allow bug reporters to set the priority or
target milestone. Also allows for configuration of what changes
should require the user to make a comment, described below.
duplicate_or_move_bug_status
When a bug is marked as a duplicate of another one, use this bug status.
letsubmitterchoosepriority
If this is on, then people submitting bugs can choose an initial priority for that bug. If off, then all bugs initially have the default priority selected here.
letsubmitterchoosemilestone
If this is on, then people submitting bugs can choose the Target Milestone for that bug. If off, then all bugs initially have the default milestone for the product being filed in.
musthavemilestoneonaccept
If you are using Target Milestone, do you want to require that the milestone be set in order for a user to set a bug's status to IN_PROGRESS?
commenton*
All these fields allow you to dictate what changes can pass
without comment and which must have a comment from the
person who changed them. Often, administrators will allow
users to add themselves to the CC list, accept bugs, or
change the Status Whiteboard without adding a comment as to
their reasons for the change, yet require that most other
changes come with an explanation.
Set the "commenton" options according to your site policy. It
is a wise idea to require comments when users resolve, reassign, or
reopen bugs at the very least.
.. note:: It is generally far better to require a developer comment
when resolving bugs than not. Few things are more annoying to bug
database users than having a developer mark a bug "fixed" without
any comment as to what the fix was (or even that it was truly
fixed!)
noresolveonopenblockers
This option will prevent users from resolving bugs as FIXED if
they have unresolved dependencies. Only the FIXED resolution
is affected. Users will be still able to resolve bugs to
resolutions other than FIXED if they have unresolved dependent
bugs.
.. _param-bugfields:
Bug Fields
==========
The parameters in this section determine the default settings of
several Bugzilla fields for new bugs and whether
certain fields are used. For example, choose whether to use the
:field:`Target Milestone` field or the :field:`Status Whiteboard` field.
useclassification
If this is on, Bugzilla will associate each product with a specific
classification. But you must have :group:`editclassification` permissions
enabled in order to edit classifications.
usetargetmilestone
Do you wish to use the :field:`Target Milestone` field?
useqacontact
This allows you to define an email address for each component,
in addition to that of the default assignee, that will be sent
carbon copies of incoming bugs.
usestatuswhiteboard
This defines whether you wish to have a free-form, overwritable field
associated with each bug. The advantage of the :field:`Status Whiteboard`
is that it can be deleted or modified with ease and provides an
easily searchable field for indexing bugs that have some trait in
common.
use_see_also
Do you wish to use the :field:`See Also` field? It allows you mark bugs
in other bug tracker installations as being related. Disabling this field
prevents addition of new relationships, but existing ones will continue to
appear.
defaultpriority
This is the priority that newly entered bugs are set to.
defaultseverity
This is the severity that newly entered bugs are set to.
defaultplatform
This is the platform that is preselected on the bug entry form.
You can leave this empty; Bugzilla will then use the platform that the
browser is running on as the default.
defaultopsys
This is the operating system that is preselected on the bug entry form.
You can leave this empty; Bugzilla will then use the operating system
that the browser reports to be running on as the default.
collapsed_comment_tags
A comma-separated list of tags which, when applied to comments, will
cause them to be collapsed by default.
.. _param-dependency-graphs:
Graphs
======
Bugzilla can draw graphs of bug-dependency relationships, using a tool called
:file:`dot` (from the `GraphViz project <http://graphviz.org/>`_) or a web
service called Web Dot. This page allows you to set the location of the binary
or service. If no Web Dot server or binary is specified, then dependency
graphs will be disabled.
webdotbase
You may set this parameter to any of the following:
* A complete file path to :command:`dot` (part of GraphViz), which will
generate the graphs locally.
* A URL prefix pointing to an installation of the Web Dot package, which
will generate the graphs remotely.
* A blank value, which will disable dependency graphing.
The default value is blank. We recommend using a local install of
:file:`dot`. If you change this value to a web service, make certain that
the Web Dot server can read files from your Web Dot directory. On Apache
you do this by editing the :file:`.htaccess` file; for other systems the
needed measures may vary. You can run :command:`checksetup.pl` to
recreate the :file:`.htaccess` file if it has been lost.
font_file
You can specify the full path to a TrueType font file which will be used
to display text (labels, legends, ...) in charts and graphical reports.
To support as many languages as possible, we recommend to specify a
TrueType font such as Unifont which supports all printable characters in
the Basic Multilingual Plane. If you leave this parameter empty, a default
font will be used, but its support is limited to English characters only
and so other characters will be displayed incorrectly.
.. _param-group-security:
Group Security
==============
Bugzilla allows for the creation of different groups, with the
ability to restrict the visibility of bugs in a group to a set of
specific users. Specific products can also be associated with
groups, and users restricted to only see products in their groups.
Several parameters are described in more detail below. Most of the
configuration of groups and their relationship to products is done
on the :guilabel:`Groups` and :guilabel:`Product` pages of the
:guilabel:`Administration` area.
The options on this page control global default behavior.
For more information on Groups and Group Security, see
:ref:`groups`.
makeproductgroups
Determines whether or not to automatically create groups
when new products are created. If this is on, the groups will be
used for querying bugs.
.. todo:: This is spectacularly unclear. I have no idea what makeproductgroups
does - can someone explain it to me? Convert this item into a bug on checkin.
chartgroup
The name of the group of users who can use the 'New Charts' feature. Administrators should ensure that the public categories and series definitions do not divulge confidential information before enabling this for an untrusted population. If left blank, no users will be able to use New Charts.
insidergroup
The name of the group of users who can see/change private comments and attachments.
timetrackinggroup
The name of the group of users who can see/change time tracking information.
querysharegroup
The name of the group of users who are allowed to share saved
searches with one another. For more information on using
saved searches, see :ref:`saved-searches`.
comment_taggers_group
The name of the group of users who can tag comments. Setting this to empty disables comment tagging.
debug_group
The name of the group of users who can view the actual SQL query generated when viewing bug lists and reports. Do not expose this information to untrusted users.
usevisibilitygroups
If selected, user visibility will be restricted to members of
groups, as selected in the group configuration settings.
Each user-defined group can be allowed to see members of selected
other groups.
For details on configuring groups (including the visibility
restrictions) see :ref:`edit-groups`.
or_groups
Define the visibility of a bug which is in multiple groups. If
this is on (recommended), a user only needs to be a member of one
of the bug's groups in order to view it. If it is off, a user
needs to be a member of all the bug's groups. Note that in either
case, a user's role on the bug (e.g. reporter), if any, may also
affect their permissions.
.. _param-ldap:
LDAP
====
LDAP authentication is a module for Bugzilla's plugin
authentication architecture. This page contains all the parameters
necessary to configure Bugzilla for use with LDAP authentication.
The existing authentication
scheme for Bugzilla uses email addresses as the primary user ID and a
password to authenticate that user. All places within Bugzilla that
require a user ID (e.g assigning a bug) use the email
address. The LDAP authentication builds on top of this scheme, rather
than replacing it. The initial log-in is done with a username and
password for the LDAP directory. Bugzilla tries to bind to LDAP using
those credentials and, if successful, tries to map this account to a
Bugzilla account. If an LDAP mail attribute is defined, the value of this
attribute is used; otherwise, the :param:`emailsuffix` parameter is appended to
the LDAP username to form a full email address. If an account for this address
already exists in the Bugzilla installation, it will log in to that account.
If no account for that email address exists, one is created at the time
of login. (In this case, Bugzilla will attempt to use the "displayName"
or "cn" attribute to determine the user's full name.) After
authentication, all other user-related tasks are still handled by email
address, not LDAP username. For example, bugs are still assigned by
email address and users are still queried by email address.
.. warning:: Because the Bugzilla account is not created until the first time
a user logs in, a user who has not yet logged is unknown to Bugzilla.
This means they cannot be used as an assignee or QA contact (default or
otherwise), added to any CC list, or any other such operation. One
possible workaround is the :file:`bugzilla_ldapsync.rb`
script in the :file:`contrib`
directory. Another possible solution is fixing :bug:`201069`.
Parameters required to use LDAP Authentication:
user_verify_class (in the Authentication section)
If you want to list :paramval:`LDAP` here,
make sure to have set up the other parameters listed below.
Unless you have other (working) authentication methods listed as
well, you may otherwise not be able to log back in to Bugzilla once
you log out.
If this happens to you, you will need to manually edit
:file:`data/params.json` and set :param:`user_verify_class` to
:paramval:`DB`.
LDAPserver
This parameter should be set to the name (and optionally the
port) of your LDAP server. If no port is specified, it assumes
the default LDAP port of 389.
For example: :paramval:`ldap.company.com`
or :paramval:`ldap.company.com:3268`
You can also specify a LDAP URI, so as to use other
protocols, such as LDAPS or LDAPI. If the port was not specified in
the URI, the default is either 389 or 636 for 'LDAP' and 'LDAPS'
schemes respectively.
.. note:: In order to use SSL with LDAP, specify a URI with "ldaps://".
This will force the use of SSL over port 636.
For example, normal LDAP :paramval:`ldap://ldap.company.com`, LDAP over
SSL :paramval:`ldaps://ldap.company.com`, or LDAP over a UNIX
domain socket :paramval:`ldapi://%2fvar%2flib%2fldap_sock`.
LDAPstarttls
Whether to require encrypted communication once a normal LDAP connection
is achieved with the server.
LDAPbinddn [Optional]
Some LDAP servers will not allow an anonymous bind to search
the directory. If this is the case with your configuration you
should set the :param:`LDAPbinddn` parameter to the user account Bugzilla
should use instead of the anonymous bind.
Ex. :paramval:`cn=default,cn=user:password`
LDAPBaseDN
The location in
your LDAP tree that you would like to search for email addresses.
Your uids should be unique under the DN specified here.
Ex. :paramval:`ou=People,o=Company`
LDAPuidattribute
The attribute
which contains the unique UID of your users. The value retrieved
from this attribute will be used when attempting to bind as the
user to confirm their password.
Ex. :paramval:`uid`
LDAPmailattribute
The name of the
attribute which contains the email address your users will enter
into the Bugzilla login boxes.
Ex. :paramval:`mail`
LDAPfilter
LDAP filter to AND with the LDAPuidattribute for filtering the list of
valid users.
.. _param-radius:
RADIUS
======
RADIUS authentication is a module for Bugzilla's plugin
authentication architecture. This page contains all the parameters
necessary for configuring Bugzilla to use RADIUS authentication.
.. note:: Most caveats that apply to LDAP authentication apply to RADIUS
authentication as well. See :ref:`param-ldap` for details.
Parameters required to use RADIUS Authentication:
user_verify_class (in the Authentication section)
If you want to list :paramval:`RADIUS` here,
make sure to have set up the other parameters listed below.
Unless you have other (working) authentication methods listed as
well, you may otherwise not be able to log back in to Bugzilla once
you log out.
If this happens to you, you will need to manually edit
:file:`data/params.json` and set :param:`user_verify_class` to
:paramval:`DB`.
RADIUS_server
The name (and optionally the port) of your RADIUS server.
RADIUS_secret
The RADIUS server's secret.
RADIUS_NAS_IP
The NAS-IP-Address attribute to be used when exchanging data with your
RADIUS server. If unspecified, 127.0.0.1 will be used.
RADIUS_email_suffix
Bugzilla needs an email address for each user account.
Therefore, it needs to determine the email address corresponding
to a RADIUS user.
Bugzilla offers only a simple way to do this: it can concatenate
a suffix to the RADIUS user name to convert it into an email
address.
You can specify this suffix in the :param:`RADIUS_email_suffix` parameter.
If this simple solution does not work for you, you'll
probably need to modify
:file:`Bugzilla/Auth/Verify/RADIUS.pm` to match your
requirements.
.. _param-email:
Email
=====
This page contains all of the parameters for configuring how
Bugzilla deals with the email notifications it sends. See below
for a summary of important options.
mail_delivery_method
This is used to specify how email is sent, or if it is sent at
all. There are several options included for different MTAs,
along with two additional options that disable email sending.
:paramval:`Test` does not send mail, but instead saves it in
:file:`data/mailer.testfile` for later review.
:paramval:`None` disables email sending entirely.
mailfrom
This is the email address that will appear in the "From" field
of all emails sent by this Bugzilla installation. Some email
servers require mail to be from a valid email address; therefore,
it is recommended to choose a valid email address here.
use_mailer_queue
In a large Bugzilla installation, updating bugs can be very slow because Bugzilla sends all email at once. If you enable this parameter, Bugzilla will queue all mail and then send it in the background. This requires that you have installed certain Perl modules (as listed by :file:`checksetup.pl` for this feature), and that you are running the :file:`jobqueue.pl` daemon (otherwise your mail won't get sent). This affects all mail sent by Bugzilla, not just bug updates.
smtpserver
The SMTP server address, if the :param:`mail_delivery_method`
parameter is set to :paramval:`SMTP`. Use :paramval:`localhost` if you have a local MTA
running; otherwise, use a remote SMTP server. Append ":" and the port
number if a non-default port is needed.
smtp_username
Username to use for SASL authentication to the SMTP server. Leave
this parameter empty if your server does not require authentication.
smtp_password
Password to use for SASL authentication to the SMTP server. This
parameter will be ignored if the :param:`smtp_username`
parameter is left empty.
smtp_ssl
Enable SSL support for connection to the SMTP server.
smtp_debug
This parameter allows you to enable detailed debugging output.
Log messages are printed the web server's error log.
whinedays
Set this to the number of days you want to let bugs go
in the CONFIRMED state before notifying people they have
untouched new bugs. If you do not plan to use this feature, simply
do not set up the :ref:`whining cron job <installation-whining>` described
in the installation instructions, or set this value to "0" (never whine).
globalwatchers
This allows you to define specific users who will
receive notification each time any new bug in entered, or when
any existing bug changes, subject to the normal groupset
permissions. It may be useful for sending notifications to a
mailing list, for instance.
.. _param-querydefaults:
Query Defaults
==============
This page controls the default behavior of Bugzilla in regards to
several aspects of querying bugs. Options include what the default
query options are, what the "My Bugs" page returns, whether users
can freely add bugs to the quip list, and how many duplicate bugs are
needed to add a bug to the "most frequently reported" list.
quip_list_entry_control
Controls how easily users can add entries to the quip list.
* :paramval:`open` - Users may freely add to the quip list, and their entries will immediately be available for viewing.
* :paramval:`moderated` - Quips can be entered but need to be approved by a moderator before they will be shown.
* :paramval:`closed` - No new additions to the quips list are allowed.
mybugstemplate
This is the URL to use to bring up a simple 'all of my bugs' list
for a user. %userid% will get replaced with the login name of a
user. Special characters must be URL encoded.
defaultquery
This is the default query that initially comes up when you access
the advanced query page. It's in URL-parameter format.
search_allow_no_criteria
When turned off, a query must have some criteria specified to limit the number of bugs returned to the user. When turned on, a user is allowed to run a query with no criteria and get all bugs in the entire installation that they can see. Turning this parameter on is not recommended on large installations.
default_search_limit
By default, Bugzilla limits searches done in the web interface to returning only this many results, for performance reasons. (This only affects the HTML format of search results—CSV, XML, and other formats are exempted.) Users can click a link on the search result page to see all the results.
Usually you should not have to change this—the default value should be acceptable for most installations.
max_search_results
The maximum number of bugs that a search can ever return. Tabular and graphical reports are exempted from this limit, however.
.. _param-shadowdatabase:
Shadow Database
===============
This page controls whether a shadow database is used. If your Bugzilla is
not large, you will not need these options.
A standard large database setup involves a single master server and a pool of
read-only slaves (which Bugzilla calls the "shadowdb"). Queries which are not
updating data can be directed to the slave pool, removing the load/locking
from the master, freeing it up to handle writes. Bugzilla will switch to the
shadowdb when it knows it doesn't need to update the database (e.g. when
searching, or displaying a bug to a not-logged-in user).
Bugzilla does not make sure the shadowdb is kept up to date, so, if you use
one, you will need to set up replication in your database server.
If your shadowdb is on a different machine, specify :param:`shadowdbhost`
and :param:`shadowdbport`. If it's on the same machine, specify
:param:`shadowdbsock`.
shadowdbhost
The host the shadow database is on.
shadowdbport
The port the shadow database is on.
shadowdbsock
The socket used to connect to the shadow database, if the host is the
local machine.
shadowdb
The database name of the shadow database.
.. _admin-memcached:
Memcached
=========
memcached_servers
If this option is set, Bugzilla will integrate with `Memcached
<http://www.memcached.org/>`_. Specify one or more servers, separated by
spaces, using hostname:port notation (for example:
:paramval:`127.0.0.1:11211`).
memcached_namespace
Specify a string to prefix each key on Memcached.
.. _admin-usermatching:
User Matching
=============
The settings on this page control how users are selected and queried
when adding a user to a bug. For example, users need to be selected
when assigning the bug, adding to the CC list, or
selecting a QA contact. With the :param:`usemenuforusers` parameter, it is
possible to configure Bugzilla to
display a list of users in the fields instead of an empty text field.
If users are selected via a text box, this page also
contains parameters for how user names can be queried and matched
when entered.
usemenuforusers
If this option is set, Bugzilla will offer you a list to select from (instead of a text entry field) where a user needs to be selected. This option should not be enabled on sites where there are a large number of users.
ajax_user_autocompletion
If this option is set, typing characters in a certain user fields
will display a list of matches that can be selected from. It is
recommended to only turn this on if you are using mod_perl;
otherwise, the response will be irritatingly slow.
maxusermatches
Provide no more than this many matches when a user is searched for.
If set to '1', no users will be displayed on ambiguous
matches. This is useful for user-privacy purposes. A value of zero
means no limit.
confirmuniqueusermatch
Whether a confirmation screen should be displayed when only one user matches a search entry.
.. _admin-advanced:
Advanced
========
cookiedomain
Defines the domain for Bugzilla cookies. This is typically left blank.
If there are multiple hostnames that point to the same webserver, which
require the same cookie, then this parameter can be utilized. For
example, If your website is at
``https://bugzilla.example.com/``, setting this to
:paramval:`.example.com/` will also allow
``attachments.example.com/`` to access Bugzilla cookies.
inbound_proxies
When inbound traffic to Bugzilla goes through a proxy, Bugzilla thinks that the IP address of the proxy is the IP address of every single user. If you enter a comma-separated list of IPs in this parameter, then Bugzilla will trust any ``X-Forwarded-For`` header sent from those IPs, and use the value of that header as the end user's IP address.
proxy_url
If this Bugzilla installation is behind a proxy, enter the proxy
information here to enable Bugzilla to access the Internet. Bugzilla
requires Internet access to utilize the
:param:`upgrade_notification` parameter. If the
proxy requires authentication, use the syntax:
:paramval:`http://user:pass@proxy_url/`.
strict_transport_security
Enables the sending of the Strict-Transport-Security header along with HTTP responses on SSL connections. This adds greater security to your SSL connections by forcing the browser to always access your domain over SSL and never accept an invalid certificate. However, it should only be used if you have the :param:`ssl_redirect` parameter turned on, Bugzilla is the only thing running on its domain (i.e., your :param:`urlbase` is something like :paramval:`http://bugzilla.example.com/`), and you never plan to stop supporting SSL.
* :paramval:`off` - Don't send the Strict-Transport-Security header with requests.
* :paramval:`this_domain_only` - Send the Strict-Transport-Security header with all requests, but only support it for the current domain.
* :paramval:`include_subdomains` - Send the Strict-Transport-Security header along with the includeSubDomains flag, which will apply the security change to all subdomains. This is especially useful when combined with an :param:`attachment_base` that exists as (a) subdomain(s) under the main Bugzilla domain.
<file_sep>/extensions/ProdCompSearch/web/js/prod_comp_search.js
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0. */
// Product and component search to file a new bug
$(function() {
'use strict';
function hideNotifications(target) {
var id = '#' + $(target).prop('id');
var that = $(id);
if (that.data('counter') === 0)
that.removeClass('autocomplete-running');
$(id + '-no_results').hide();
$(id + '-too_many_results').hide();
$(id + '-error').hide();
}
function searchComplete(query, suggestions) {
var that = $(this);
var id = '#' + that.prop('id');
that.data('counter', that.data('counter') - 1);
hideNotifications(this);
if (document.activeElement != this)
that.devbridgeAutocomplete('hide');
if (that.data('error')) {
searchError.call(that[0], null, null, null, that.data('error'));
that.data('error', '');
}
if (suggestions.length === 0) {
$(id + '-no_results').show();
$(document).trigger('pcs:no_results', [ that ]);
}
else if (suggestions.length > that.data('max_results')) {
$(id + '-too_many_results').show();
$(document).trigger('pcs:too_many_results', [ that ]);
}
else {
$(document).trigger('pcs:results', [ that, suggestions ]);
}
}
function searchError(q, jqXHR, textStatus, errorThrown) {
var that = $(this);
that.data('counter', that.data('counter') - 1);
hideNotifications(this);
if (errorThrown !== 'abort') {
$('#' + that.attr('id') + '-error').show();
console.log(errorThrown);
}
}
$('.prod_comp_search')
.each(function() {
var that = $(this);
that.devbridgeAutocomplete({
serviceUrl: function(query) {
return 'rest/prod_comp_search/' + encodeURIComponent(query);
},
params: {
Bugzilla_api_token: (BUGZILLA.api_token ? BUGZILLA.api_token : ''),
limit: (that.data('max_results') + 1)
},
deferRequestBy: 250,
minChars: 3,
maxHeight: 500,
tabDisabled: true,
autoSelectFirst: true,
triggerSelectOnValidInput: false,
width: '',
transformResult: function(response) {
response = $.parseJSON(response);
if (response.error) {
that.data('error', response.message);
return { suggestions: [] };
}
return {
suggestions: $.map(response.products, function(dataItem) {
if (dataItem.component) {
return {
value: dataItem.product + ' :: ' + dataItem.component,
data : dataItem
};
}
else {
return {
value: dataItem.product,
data : dataItem
};
}
})
};
},
formatResult: function(suggestion, currentValue) {
var value = (suggestion.data.component ? suggestion.data.component : suggestion.data.product);
var escaped = value.htmlEncode();
if (suggestion.data.component) {
return '- ' + escaped;
}
else {
return '<b>' + escaped + '</b>';
}
return suggestion.data.component ? '- ' + escaped : escaped;
},
beforeRender: function(container) {
container.css('min-width', that.outerWidth() - 2 + 'px');
},
onSearchStart: function(params) {
var that = $(this);
params.match = $.trim(params.match);
that.addClass('autocomplete-running');
that.data('counter', that.data('counter') + 1);
that.data('error', '');
hideNotifications(this);
},
onSearchComplete: searchComplete,
onSearchError: searchError,
onSelect: function(suggestion) {
var that = $(this);
if (that.data('ignore-select'))
return;
var params = [];
if (that.data('format'))
params.push('format=' + encodeURIComponent(that.data('format')));
if (that.data('cloned_bug_id'))
params.push('cloned_bug_id=' + encodeURIComponent(that.data('cloned_bug_id')));
params.push('product=' + encodeURIComponent(suggestion.data.product));
if (suggestion.data.component)
params.push('component=' + encodeURIComponent(suggestion.data.component));
var url = that.data('script_name') + '?' + params.join('&');
if (that.data('anchor_component') && suggestion.data.component)
url += "#" + encodeURIComponent(suggestion.data.component);
document.location.href = url;
}
});
})
.data('counter', 0);
});
<file_sep>/docs/en/rst/integrating/apis.rst
.. _api-list:
APIs
####
Bugzilla has a number of APIs that you can call in your code to extract
information from and put information into Bugzilla. Some are deprecated and
will soon be removed. Which one to use? Short answer: the
:ref:`REST WebService API v1 <apis>`
should be used for all new integrations, but keep an eye out for version 2,
coming soon.
The APIs currently available are as follows:
Ad-Hoc APIs
===========
Various pages on Bugzilla are available in machine-parseable formats as well
as HTML. For example, bugs can be downloaded as XML, and buglists as CSV.
CSV is useful for spreadsheet import. There should be links on the HTML page
to alternate data formats where they are available.
XML-RPC
=======
Bugzilla has an `XML-RPC API
<http://www.bugzilla.org/docs/tip/en/html/api/Bugzilla/WebService/Server/XMLRPC.html>`_.
This will receive no further updates and will be removed in a future version
of Bugzilla.
Endpoint: :file:`/xmlrpc.cgi`
JSON-RPC
========
Bugzilla has a `JSON-RPC API
<http://www.bugzilla.org/docs/tip/en/html/api/Bugzilla/WebService/Server/JSONRPC.html>`_.
This will receive no further updates and will be removed in a future version
of Bugzilla.
Endpoint: :file:`/jsonrpc.cgi`
REST
====
Bugzilla has a :ref:`REST API <apis>` which is the currently-recommended API
for integrating with Bugzilla. The current REST API is version 1. It is stable,
and so will not be changed in a backwardly-incompatible way.
**This is the currently-recommended API for new development.**
Endpoint: :file:`/rest`
BzAPI/BzAPI-Compatible REST
===========================
The first ever REST API for Bugzilla was implemented using an external proxy
called `BzAPI <https://wiki.mozilla.org/Bugzilla:BzAPI>`_. This became popular
enough that a BzAPI-compatible shim on top of the (native) REST API has been
written, to allow code which used the BzAPI API to take advantage of the
speed improvements of direct integration without needing to be rewritten.
The shim is an extension which you would need to install in your Bugzilla.
Neither BzAPI nor this BzAPI-compatible API shim will receive any further
updates, and they should not be used for new code.
REST v2
=======
The future of Bugzilla's APIs is version 2 of the REST API, which will take
the best of the current REST API and the BzAPI API. It is still under
development.
<file_sep>/docs/en/rst/api/core/v1/bug.rst
Bugs
====
The REST API for creating, changing, and getting the details of bugs.
This part of the Bugzilla REST API allows you to file new bugs in Bugzilla and
to get information about existing bugs.
.. _rest_single_bug:
Get Bug
-------
Gets information about particular bugs in the database.
**Request**
To get information about a particular bug using its ID or alias:
.. code-block:: text
GET /rest/bug/(id_or_alias)
You can also use :ref:`rest_search_bugs` to return more than one bug at a time
by specifying bug IDs as the search terms.
.. code-block:: text
GET /rest/bug?id=12434,43421
================ ===== ======================================================
name type description
================ ===== ======================================================
**id_or_alias** mixed An integer bug ID or a bug alias string.
================ ===== ======================================================
**Response**
.. code-block:: js
{
"faults": [],
"bugs": [
{
"assigned_to_detail": {
"id": 2,
"real_name": "<NAME>",
"name": "<EMAIL>",
"email": "<EMAIL>"
},
"flags": [
{
"type_id": 11,
"modification_date": "2014-09-28T21:03:47Z",
"name": "blocker",
"status": "?",
"id": 2906,
"setter": "<EMAIL>",
"creation_date": "2014-09-28T21:03:47Z"
}
],
"resolution": "INVALID",
"id": 35,
"qa_contact": "",
"version": "1.0",
"status": "RESOLVED",
"creator": "<EMAIL>",
"cf_drop_down": "---",
"summary": "test bug",
"last_change_time": "2014-09-23T19:12:17Z",
"platform": "All",
"url": "",
"classification": "Unclassified",
"cc_detail": [
{
"id": 786,
"real_name": "<NAME>",
"name": "<EMAIL>",
"email": "<EMAIL>"
},
],
"priority": "P1",
"is_confirmed": true,
"creation_time": "2000-07-25T13:50:04Z",
"assigned_to": "<EMAIL>",
"flags": [],
"alias": [],
"cf_large_text": "",
"groups": [],
"op_sys": "All",
"cf_bug_id": null,
"depends_on": [],
"is_cc_accessible": true,
"is_open": false,
"cf_qa_list_4": "---",
"keywords": [],
"cc": [
"<EMAIL>",
],
"see_also": [],
"deadline": null,
"is_creator_accessible": true,
"whiteboard": "",
"dupe_of": null,
"target_milestone": "---",
"cf_mulitple_select": [],
"component": "SaltSprinkler",
"severity": "critical",
"cf_date": null,
"product": "FoodReplicator",
"creator_detail": {
"id": 28,
"real_name": "hello",
"name": "<EMAIL>",
"email": "<EMAIL>"
},
"cf_free_text": "",
"blocks": []
}
]
}
``bugs`` (array) Each bug object contains information about the bugs with valid
ids containing the following items:
These fields are returned by default or by specifying ``_default`` in
``include_fields``.
===================== ======== ================================================
name type description
===================== ======== ================================================
actual_time double The total number of hours that this bug has
taken so far. If you are not in the time-tracking
group, this field will not be included in the
return value.
alias array The unique aliases of this bug. An empty array
will be returned if this bug has no aliases.
assigned_to string The login name of the user to whom the bug is
assigned.
assigned_to_detail object An object containing detailed user information
for the assigned_to. To see the keys included
in the user detail object, see below.
blocks array The IDs of bugs that are "blocked" by this bug.
cc array The login names of users on the CC list of this
bug.
cc_detail array Array of objects containing detailed user
information for each of the cc list members.
To see the keys included in the user detail
object, see below.
classification string The name of the current classification the bug
is in.
component string The name of the current component of this bug.
creation_time datetime When the bug was created.
creator string The login name of the person who filed this bug
(the reporter).
creator_detail object An object containing detailed user information
for the creator. To see the keys included in the
user detail object, see below.
deadline string The day that this bug is due to be completed, in
the format ``YYYY-MM-DD``.
depends_on array The IDs of bugs that this bug "depends on".
dupe_of int The bug ID of the bug that this bug is a
duplicate of. If this bug isn't a duplicate of
any bug, this will be null.
estimated_time double The number of hours that it was estimated that
this bug would take. If you are not in the
time-tracking group, this field will not be
included in the return value.
flags array An array of objects containing the information
about flags currently set for the bug. Each flag
objects contains the following items
groups array The names of all the groups that this bug is in.
id int The unique numeric ID of this bug.
is_cc_accessible boolean If true, this bug can be accessed by members of
the CC list, even if they are not in the groups
the bug is restricted to.
is_confirmed boolean ``true`` if the bug has been confirmed. Usually
this means that the bug has at some point been
moved out of the ``UNCONFIRMED`` status and into
another open status.
is_open boolean ``true`` if this bug is open, ``false`` if it
is closed.
is_creator_accessible boolean If ``true``, this bug can be accessed by the
creator of the bug, even if they are not a
member of the groups the bug is restricted to.
keywords array Each keyword that is on this bug.
last_change_time datetime When the bug was last changed.
op_sys string The name of the operating system that the bug
was filed against.
platform string The name of the platform (hardware) that the bug
was filed against.
priority string The priority of the bug.
product string The name of the product this bug is in.
qa_contact string The login name of the current QA Contact on the
bug.
qa_contact_detail object An object containing detailed user information
for the qa_contact. To see the keys included in
the user detail object, see below.
remaining_time double The number of hours of work remaining until work
on this bug is complete. If you are not in the
time-tracking group, this field will not be
included in the return value.
resolution string The current resolution of the bug, or an empty
string if the bug is open.
see_also array The URLs in the See Also field on the bug.
severity string The current severity of the bug.
status string The current status of the bug.
summary string The summary of this bug.
target_milestone string The milestone that this bug is supposed to be
fixed by, or for closed bugs, the milestone that
it was fixed for.
update_token string The token that you would have to pass to the
``process_bug.cgi`` page in order to update this
bug. This changes every time the bug is updated.
This field is not returned to logged-out users.
url string A URL that demonstrates the problem described in
the bug, or is somehow related to the bug report.
version string The version the bug was reported against.
whiteboard string The value of the "status whiteboard" field on
the bug.
===================== ======== ================================================
Custom fields:
Every custom field in this installation will also be included in the
return value. Most fields are returned as strings. However, some field types have
different return values.
Normally custom fields are returned by default similar to normal bug fields or
you can specify only custom fields by using ``_custom`` in ``include_fields``.
Extra fields:
These fields are returned only by specifying ``_extra`` or the field name in
``include_fields``.
==== ===== ====================================================================
name type description
==== ===== ====================================================================
tags array Each array item is a tag name. Note that tags are
personal to the currently logged in user and are not the same as
comment tags.
==== ===== ====================================================================
User object:
========= ====== ==============================================================
name type description
========= ====== ==============================================================
id int The user ID for this user.
real_name string The 'real' name for this user, if any.
name string The user's Bugzilla login.
email string The user's email address. Currently this is the same value as
the name.
========= ====== ==============================================================
Flag object:
================= ======== ====================================================
name type description
================= ======== ====================================================
id int The ID of the flag.
name string The name of the flag.
type_id int The type ID of the flag.
creation_date datetime The timestamp when this flag was originally created.
modification_date datetime The timestamp when the flag was last modified.
status string The current status of the flag.
setter string The login name of the user who created or last
modified the flag.
requestee string The login name of the user this flag has been
requested to be granted or denied. Note, this field
is only returned if a requestee is set.
================= ======== ====================================================
Custom field object:
You can specify to only return custom fields by specifying ``_custom`` or the
field name in ``include_fields``.
* Bug ID Fields: (int)
* Multiple-Selection Fields: (array of strings)
* Date/Time Fields: (datetime)
**Errors**
* 100 (Invalid Bug Alias)
If you specified an alias and there is no bug with that alias.
* 101 (Invalid Bug ID)
The bug_id you specified doesn't exist in the database.
* 102 (Access Denied)
You do not have access to the bug_id you specified.
.. _rest_history:
Bug History
-----------
Gets the history of changes for particular bugs in the database.
**Request**
To get the history for a specific bug ID:
.. code-block:: text
GET /rest/bug/(id)/history
To get the history for a bug since a specific date:
.. code-block:: text
GET /rest/bug/(id)/history?new_since=YYYY-MM-DD
========= ======== ============================================================
name type description
========= ======== ============================================================
**id** mixed An integer bug ID or alias.
new_since datetime A datetime timestamp to only show history since.
========= ======== ============================================================
**Response**
.. code-block:: js
{
"bugs": [
{
"alias": [],
"history": [
{
"when": "2014-09-23T19:12:17Z",
"who": "<EMAIL>",
"changes": [
{
"added": "P1",
"field_name": "priority",
"removed": "P2"
},
{
"removed": "blocker",
"field_name": "severity",
"added": "critical"
}
]
},
{
"when": "2014-09-28T21:03:47Z",
"who": "<EMAIL>",
"changes": [
{
"added": "blocker?",
"removed": "",
"field_name": "flagtypes.name"
}
]
}
],
"id": 35
}
]
}
``bugs`` (array) Bug objects each containing the following items:
======= ===== =================================================================
name type description
======= ===== =================================================================
id int The numeric ID of the bug.
alias array The unique aliases of this bug. An empty array will be returned
if this bug has no aliases.
history array An array of History objects.
======= ===== =================================================================
History object:
======= ======== ==============================================================
name type description
======= ======== ==============================================================
when datetime The date the bug activity/change happened.
who string The login name of the user who performed the bug change.
changes array An array of Change objects which contain all the changes that
happened to the bug at this time (as specified by ``when``).
======= ======== ==============================================================
Change object:
============= ====== ==========================================================
name type description
============= ====== ==========================================================
field_name string The name of the bug field that has changed.
removed string The previous value of the bug field which has been
deleted by the change.
added string The new value of the bug field which has been added
by the change.
attachment_id int The ID of the attachment that was changed.
This only appears if the change was to an attachment,
otherwise ``attachment_id`` will not be present in this
object.
============= ====== ==========================================================
**Errors**
Same as :ref:`rest_single_bug`.
.. _rest_search_bugs:
Search Bugs
-----------
Allows you to search for bugs based on particular criteria.
**Request**
To search for bugs:
.. code-block:: text
GET /rest/bug
Unless otherwise specified in the description of a parameter, bugs are
returned if they match *exactly* the criteria you specify in these
parameters. That is, we don't match against substrings--if a bug is in
the "Widgets" product and you ask for bugs in the "Widg" product, you
won't get anything.
Criteria are joined in a logical AND. That is, you will be returned
bugs that match *all* of the criteria, not bugs that match *any* of
the criteria.
Each parameter can be either the type it says, or a list of the types
it says. If you pass an array, it means "Give me bugs with *any* of
these values." For example, if you wanted bugs that were in either
the "Foo" or "Bar" products, you'd pass:
.. code-block:: text
GET /rest/bug?product=Foo&product=Bar
Some Bugzillas may treat your arguments case-sensitively, depending
on what database system they are using. Most commonly, though, Bugzilla is
not case-sensitive with the arguments passed (because MySQL is the
most-common database to use with Bugzilla, and MySQL is not case sensitive).
In addition to the fields listed below, you may also use criteria that
is similar to what is used in the Advanced Search screen of the Bugzilla
UI. This includes fields specified by ``Search by Change History`` and
``Custom Search``. The easiest way to determine what the field names are and what
format Bugzilla expects is to first construct your query using the
Advanced Search UI, execute it and use the query parameters in they URL
as your query for the REST call.
================ ======== =====================================================
name type description
================ ======== =====================================================
alias array The unique aliases of this bug. An empty array will
be returned if this bug has no aliases.
assigned_to string The login name of a user that a bug is assigned to.
component string The name of the Component that the bug is in. Note
that if there are multiple Components with the same
name, and you search for that name, bugs in *all*
those Components will be returned. If you don't want
this, be sure to also specify the ``product`` argument.
count_only boolean If set to true, an object with a single key called
"bug_count" will be returned which is the number of
bugs that matched the search.
creation_time datetime Searches for bugs that were created at this time or
later. May not be an array.
creator string The login name of the user who created the bug. You
can also pass this argument with the name
``reporter``, for backwards compatibility with
older Bugzillas.
id int The numeric ID of the bug.
last_change_time datetime Searches for bugs that were modified at this time
or later. May not be an array.
limit int Limit the number of results returned. If the limit
is more than zero and higher than the maximum limit
set by the administrator, then the maximum limit will
be used instead. If you set the limit equal to zero,
then all matching results will be returned instead.
offset int Used in conjunction with the ``limit`` argument,
``offset`` defines the starting position for the
search. For example, given a search that would
return 100 bugs, setting ``limit`` to 10 and
``offset`` to 10 would return bugs 11 through 20
from the set of 100.
op_sys string The "Operating System" field of a bug.
platform string The Platform (sometimes called "Hardware") field of
a bug.
priority string The Priority field on a bug.
product string The name of the Product that the bug is in.
quicksearch string Search for bugs using quicksearch syntax.
resolution string The current resolution--only set if a bug is closed.
You can find open bugs by searching for bugs with an
empty resolution.
severity string The Severity field on a bug.
status string The current status of a bug (not including its
resolution, if it has one, which is a separate field
above).
summary string Searches for substrings in the single-line Summary
field on bugs. If you specify an array, then bugs
whose summaries match *any* of the passed substrings
will be returned. Note that unlike searching in the
Bugzilla UI, substrings are not split on spaces. So
searching for ``foo bar`` will match "This is a foo
bar" but not "This foo is a bar". ``['foo', 'bar']``,
would, however, match the second item.
tags string Searches for a bug with the specified tag. If you
specify an array, then any bugs that match *any* of
the tags will be returned. Note that tags are
personal to the currently logged in user.
target_milestone string The Target Milestone field of a bug. Note that even
if this Bugzilla does not have the Target Milestone
field enabled, you can still search for bugs by
Target Milestone. However, it is likely that in that
case, most bugs will not have a Target Milestone set
(it defaults to "---" when the field isn't enabled).
qa_contact string The login name of the bug's QA Contact. Note that
even if this Bugzilla does not have the QA Contact
field enabled, you can still search for bugs by QA
Contact (though it is likely that no bug will have a
QA Contact set, if the field is disabled).
url string The "URL" field of a bug.
version string The Version field of a bug.
whiteboard string Search the "Status Whiteboard" field on bugs for a
substring. Works the same as the ``summary`` field
described above, but searches the Status Whiteboard
field.
================ ======== =====================================================
**Response**
The same as :ref:`rest_single_bug`.
**Errors**
If you specify an invalid value for a particular field, you just won't
get any results for that value.
* 1000 (Parameters Required)
You may not search without any search terms.
.. _rest_create_bug:
Create Bug
----------
This allows you to create a new bug in Bugzilla. If you specify any
invalid fields, an error will be thrown stating which field is invalid.
If you specify any fields you are not allowed to set, they will just be
set to their defaults or ignored.
You cannot currently set all the items here that you can set on enter_bug.cgi.
The WebService interface may allow you to set things other than those listed
here, but realize that anything undocumented here may likely change in the
future.
**Request**
To create a new bug in Bugzilla.
.. code-block:: text
POST /rest/bug
.. code-block:: js
{
"product" : "TestProduct",
"component" : "TestComponent",
"version" : "unspecified",
"summary" : "'This is a test bug - please disregard",
"alias" : "SomeAlias",
"op_sys" : "All",
"priority" : "P1",
"rep_platform" : "All"
}
Some params must be set, or an error will be thrown. These params are
marked in **bold**.
Some parameters can have defaults set in Bugzilla, by the administrator.
If these parameters have defaults set, you can omit them. These parameters
are marked (defaulted).
Clients that want to be able to interact uniformly with multiple
Bugzillas should always set both the params marked required and those
marked (defaulted), because some Bugzillas may not have defaults set
for (defaulted) parameters, and then this method will throw an error
if you don't specify them.
================== ======= ====================================================
name type description
================== ======= ====================================================
**product** string The name of the product the bug is being filed
against.
**component** string The name of a component in the product above.
**summary** string A brief description of the bug being filed.
**version** string A version of the product above; the version the
bug was found in.
description string (defaulted) The initial description for this bug.
Some Bugzilla installations require this to not be
blank.
op_sys string (defaulted) The operating system the bug was
discovered on.
platform string (defaulted) What type of hardware the bug was
experienced on.
priority string (defaulted) What order the bug will be fixed in by
the developer, compared to the developer's other
bugs.
severity string (defaulted) How severe the bug is.
alias array One or more brief aliases for the bug that can be
used instead of a bug number when accessing this bug.
Must be unique in all of this Bugzilla.
assigned_to string A user to assign this bug to, if you don't want it
to be assigned to the component owner.
cc array An array of usernames to CC on this bug.
comment_is_private boolean If set to true, the description is private,
otherwise it is assumed to be public.
groups array An array of group names to put this bug into. You
can see valid group names on the Permissions tab of
the Preferences screen, or, if you are an
administrator, in the Groups control panel. If you
don't specify this argument, then the bug will be
added into all the groups that are set as being
"Default" for this product. (If you want to avoid
that, you should specify ``groups`` as an empty
array.)
qa_contact string If this installation has QA Contacts enabled, you
can set the QA Contact here if you don't want to
use the component's default QA Contact.
status string The status that this bug should start out as. Note
that only certain statuses can be set on bug
creation.
resolution string If you are filing a closed bug, then you will have
to specify a resolution. You cannot currently
specify a resolution of ``DUPLICATE`` for new
bugs, though. That must be done with
:ref:`rest_update_bug`.
target_milestone string A valid target milestone for this product.
flags array Flags objects to add to the bug. The object format
is described in the Flag object below.
keywords array One or more valid keywords to add to this bug.
dependson array One or more valid bug ids that this bug depends on.
blocked array One or more valid bug ids that this bug blocks.
================== ======= ====================================================
Flag object:
To create a flag, at least the ``status`` and the ``type_id`` or ``name`` must
be provided. An optional requestee can be passed if the flag type is requestable
to a specific user.
========= ====== ==============================================================
name type description
========= ====== ==============================================================
name string The name of the flag type.
type_id int The internal flag type ID.
status string The flags new status (i.e. "?", "+", "-" or "X" to clear flag).
requestee string The login of the requestee if the flag type is requestable
to a specific user.
========= ====== ==============================================================
In addition to the above parameters, if your installation has any custom
fields, you can set them just by passing in the name of the field and
its value as a string.
**Response**
.. code-block:: js
{
"id" : 12345
}
==== ==== ======================================
name type description
==== ==== ======================================
id int This is the ID of the newly-filed bug.
==== ==== ======================================
**Errors**
* 51 (Invalid Object)
You specified a field value that is invalid. The error message will have
more details.
* 103 (Invalid Alias)
The alias you specified is invalid for some reason. See the error message
for more details.
* 104 (Invalid Field)
One of the drop-down fields has an invalid value, or a value entered in a
text field is too long. The error message will have more detail.
* 105 (Invalid Component)
You didn't specify a component.
* 106 (Invalid Product)
Either you didn't specify a product, this product doesn't exist, or
you don't have permission to enter bugs in this product.
* 107 (Invalid Summary)
You didn't specify a summary for the bug.
* 116 (Dependency Loop)
You specified values in the "blocks" or "depends_on" fields
that would cause a circular dependency between bugs.
* 120 (Group Restriction Denied)
You tried to restrict the bug to a group which does not exist, or which
you cannot use with this product.
* 129 (Flag Status Invalid)
The flag status is invalid.
* 130 (Flag Modification Denied)
You tried to request, grant, or deny a flag but only a user with the required
permissions may make the change.
* 131 (Flag not Requestable from Specific Person)
You can't ask a specific person for the flag.
* 133 (Flag Type not Unique)
The flag type specified matches several flag types. You must specify
the type id value to update or add a flag.
* 134 (Inactive Flag Type)
The flag type is inactive and cannot be used to create new flags.
* 504 (Invalid User)
Either the QA Contact, Assignee, or CC lists have some invalid user
in them. The error message will have more details.
.. _rest_update_bug:
Update Bug
----------
Allows you to update the fields of a bug. Automatically sends emails
out about the changes.
**Request**
To update the fields of a current bug.
.. code-block:: text
PUT /rest/bug/(id_or_alias)
.. code-block:: js
{
"ids" : [35],
"status" : "IN_PROGRESS",
"keywords" : {
"add" : ["funny", "stupid"]
}
}
The params to include in the PUT body as well as the returned data format,
are the same as below. You can specify the ID or alias of the bug to update
either in the URL path and/or in the ``ids`` param. You can use both and they
will be combined so you can edit more than one bug at a time.
=============== ===== =========================================================
name type description
=============== ===== =========================================================
**id_or_alias** mixed An integer bug ID or alias.
**ids** array The IDs or aliases of the bugs that you want to modify.
=============== ===== =========================================================
All following fields specify the values you want to set on the bugs you are
updating.
===================== ======= =================================================
name type description
===================== ======= =================================================
alias object These specify the aliases of a bug that can be
used instead of a bug number when acessing this
bug. To set these, you should pass an object as
the value. The object may contain the following
items:
* ``add`` (array) Aliases to add to this field.
* ``remove`` (array) Aliases to remove from this
field. If the aliases are not already in the
field, they will be ignored.
* ``set`` (array) An exact set of aliases to set
this field to, overriding the current value.
If you specify ``set``, then ``add`` and
``remove`` will be ignored.
You can only set this if you are modifying a
single bug. If there is more than one bug
specified in ``ids``, passing in a value for
``alias`` will cause an error to be thrown.
For backwards compatibility, you can also
specify a single string. This will be treated as
if you specified the set key above.
assigned_to string The full login name of the user this bug is
assigned to.
blocks object (Same as ``depends_on`` below)
depends_on object These specify the bugs that this bug blocks or
depends on, respectively. To set these, you
should pass an object as the value. The object
may contain the following items:
* ``add`` (array) Bug IDs to add to this field.
* ``remove`` (array) Bug IDs to remove from this
field. If the bug IDs are not already in the
field, they will be ignored.
* ``set`` (array of) An exact set of bug IDs to
set this field to, overriding the current
value. If you specify ``set``, then ``add``
and ``remove`` will be ignored.
cc object The users on the cc list. To modify this field,
pass an object, which may have the following
items:
* ``add`` (array) User names to add to the CC
list. They must be full user names, and an
error will be thrown if you pass in an invalid
user name.
* ``remove`` (array) User names to remove from
the CC list. They must be full user names, and
an error will be thrown if you pass in an
invalid user name.
is_cc_accessible boolean Whether or not users in the CC list are allowed
to access the bug, even if they aren't in a group
that can normally access the bug.
comment object A comment on the change. The object may contain
the following items:
* ``body`` (string) The actual text of the
comment. For compatibility with the parameters
to :ref:`rest_add_comment`, you can also call
this field ``comment``, if you want.
* ``is_private`` (boolean) Whether the comment is
private or not. If you try to make a comment
private and you don't have the permission to,
an error will be thrown.
comment_is_private object This is how you update the privacy of comments
that are already on a bug. This is a object,
where the keys are the ``int`` ID of comments
(not their count on a bug, like #1, #2, #3, but
their globally-unique ID, as returned by
:ref:`rest_comments` and the value is a
``boolean`` which specifies whether that comment
should become private (``true``) or public
(``false``).
The comment IDs must be valid for the bug being
updated. Thus, it is not practical to use this
while updating multiple bugs at once, as a single
comment ID will never be valid on multiple bugs.
component string The Component the bug is in.
deadline date The Deadline field is a date specifying when the
bug must be completed by, in the format
``YYYY-MM-DD``.
dupe_of int The bug that this bug is a duplicate of. If you
want to mark a bug as a duplicate, the safest
thing to do is to set this value and *not* set
the ``status`` or ``resolution`` fields. They will
automatically be set by Bugzilla to the
appropriate values for duplicate bugs.
estimated_time double The total estimate of time required to fix the
bug, in hours. This is the *total* estimate, not
the amount of time remaining to fix it.
flags array An array of Flag change objects. The items needed
are described below.
groups object The groups a bug is in. To modify this field,
pass an object, which may have the following
items:
* ``add`` (array) The names of groups to add.
Passing in an invalid group name or a group
that you cannot add to this bug will cause an
error to be thrown.
* ``remove`` (array) The names of groups to
remove. Passing in an invalid group name or a
group that you cannot remove from this bug
will cause an error to be thrown.
keywords object Keywords on the bug. To modify this field, pass
an object, which may have the following items:
* ``add`` (array) The names of keywords to add
to the field on the bug. Passing something that
isn't a valid keyword name will cause an error
to be thrown.
* ``remove`` (array) The names of keywords to
remove from the field on the bug. Passing
something that isn't a valid keyword name will
cause an error to be thrown.
* ``set`` (array) An exact set of keywords to set
the field to, on the bug. Passing something
that isn't a valid keyword name will cause an
error to be thrown. Specifying ``set``
overrides ``add`` and ``remove``.
op_sys string The Operating System ("OS") field on the bug.
platform string The Platform or "Hardware" field on the bug.
priority string The Priority field on the bug.
product string The name of the product that the bug is in. If
you change this, you will probably also want to
change ``target_milestone``, ``version``, and
``component``, since those have different legal
values in every product.
If you cannot change the ``target_milestone``
field, it will be reset to the default for the
product, when you move a bug to a new product.
You may also wish to add or remove groups, as
which groups are
valid on a bug depends on the product. Groups
that are not valid in the new product will be
automatically removed, and groups which are
mandatory in the new product will be automaticaly
added, but no other automatic group changes will
be done.
.. note::
Users can only move a bug into a product if
they would normally have permission to file
new bugs in that product.
qa_contact string The full login name of the bug's QA Contact.
is_creator_accessible boolean Whether or not the bug's reporter is allowed
to access the bug, even if they aren't in a group
that can normally access the bug.
remaining_time double How much work time is remaining to fix the bug,
in hours. If you set ``work_time`` but don't
explicitly set ``remaining_time``, then the
``work_time`` will be deducted from the bug's
``remaining_time``.
reset_assigned_to boolean If true, the ``assigned_to`` field will be
reset to the default for the component that the
bug is in. (If you have set the component at the
same time as using this, then the component used
will be the new component, not the old one.)
reset_qa_contact boolean If true, the ``qa_contact`` field will be reset
to the default for the component that the bug is
in. (If you have set the component at the same
time as using this, then the component used will
be the new component, not the old one.)
resolution string The current resolution. May only be set if you
are closing a bug or if you are modifying an
already-closed bug. Attempting to set the
resolution to *any* value (even an empty or null
string) on an open bug will cause an error to be
thrown.
.. note::
If you change the ``status`` field to an open
status, the resolution field will automatically
be cleared, so you don't have to clear it
manually.
see_also object The See Also field on a bug, specifying URLs to
bugs in other bug trackers. To modify this field,
pass an object, which may have the following
items:
* ``add`` (array) URLs to add to the field. Each
URL must be a valid URL to a bug-tracker, or
an error will be thrown.
* ``remove`` (array) URLs to remove from the
field. Invalid URLs will be ignored.
severity string The Severity field of a bug.
status string The status you want to change the bug to. Note
that if a bug is changing from open to closed,
you should also specify a ``resolution``.
summary string The Summary field of the bug.
target_milestone string The bug's Target Milestone.
url string The "URL" field of a bug.
version string The bug's Version field.
whiteboard string The Status Whiteboard field of a bug.
work_time double The number of hours worked on this bug as part
of this change.
If you set ``work_time`` but don't explicitly
set ``remaining_time``, then the ``work_time``
will be deducted from the bug's ``remaining_time``.
===================== ======= =================================================
You can also set the value of any custom field by passing its name as
a parameter, and the value to set the field to. For multiple-selection
fields, the value should be an array of strings.
Flag change object:
The following values can be specified. At least the ``status`` and one of
``type_id``, ``id``, or ``name`` must be specified. If a ``type_id`` or
``name`` matches a single currently set flag, the flag will be updated unless
``new`` is specified.
========== ======= ============================================================
name type description
========== ======= ============================================================
name string The name of the flag that will be created or updated.
type_id int The internal flag type ID that will be created or updated.
You will need to specify the ``type_id`` if more than one
flag type of the same name exists.
**status** string The flags new status (i.e. "?", "+", "-" or "X" to clear a
flag).
requestee string The login of the requestee if the flag type is requestable
to a specific user.
id int Use ID to specify the flag to be updated. You will need to
specify the ``id`` if more than one flag is set of the same
name.
new boolean Set to true if you specifically want a new flag to be
created.
========== ======= ============================================================
**Response**
.. code-block:: js
{
"bugs" : [
{
"alias" : [],
"changes" : {
"keywords" : {
"added" : "funny, stupid",
"removed" : ""
},
"status" : {
"added" : "IN_PROGRESS",
"removed" : "CONFIRMED"
}
},
"id" : 35,
"last_change_time" : "2014-09-29T14:25:35Z"
}
]
}
``bugs`` (array) This points to an array of objects with the following items:
================ ======== =====================================================
name type description
================ ======== =====================================================
id int The ID of the bug that was updated.
alias array The aliases of the bug that was updated, if this bug
has any alias.
last_change_time datetime The exact time that this update was done at, for
this bug. If no update was done (that is, no fields
had their values changed and no comment was added)
then this will instead be the last time the bug was
updated.
changes object The changes that were actually done on this bug. The
keys are the names of the fields that were changed,
and the values are an object with two keys:
* ``added`` (string) The values that were added to
this field, possibly a comma-and-space-separated
list if multiple values were added.
* ``removed`` (string) The values that were removed
from this field, possibly a
comma-and-space-separated list if multiple values
were removed.
================ ======== =====================================================
Currently, some fields are not tracked in changes: ``comment``,
``comment_is_private``, and ``work_time``. This means that they will not
show up in the return value even if they were successfully updated.
This may change in a future version of Bugzilla.
**Errors**
This method can throw all the same errors as :ref:`rest_single_bug`, plus:
* 129 (Flag Status Invalid)
The flag status is invalid.
* 130 (Flag Modification Denied)
You tried to request, grant, or deny a flag but only a user with the required
permissions may make the change.
* 131 (Flag not Requestable from Specific Person)
You can't ask a specific person for the flag.
* 132 (Flag not Unique)
The flag specified has been set multiple times. You must specify the id
value to update the flag.
* 133 (Flag Type not Unique)
The flag type specified matches several flag types. You must specify
the type id value to update or add a flag.
* 134 (Inactive Flag Type)
The flag type is inactive and cannot be used to create new flags.
* 140 (Markdown Disabled)
You tried to set the "is_markdown" flag of the "comment" to true but Markdown feature is
not enabled.
* 601 (Invalid MIME Type)
You specified a "content_type" argument that was blank, not a valid
MIME type, or not a MIME type that Bugzilla accepts for attachments.
* 603 (File Name Not Specified)
You did not specify a valid for the "file_name" argument.
* 604 (Summary Required)
You did not specify a value for the "summary" argument.
<file_sep>/extensions/Splinter/web/splinter.js
// Splinter - patch review add-on for Bugzilla
// By <NAME> <<EMAIL>>
// Copyright 2009, Red Hat, Inc.
// Licensed under MPL 1.1 or later, or GPL 2 or later
// http://git.fishsoup.net/cgit/splinter
// Converted to YUI by <NAME> <<EMAIL>>
YAHOO.namespace('Splinter');
var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var Splinter = YAHOO.Splinter;
var Element = YAHOO.util.Element;
Splinter.domCache = {
cache : [0],
expando : 'data' + new Date(),
data : function (elem) {
var cacheIndex = elem[Splinter.domCache.expando];
var nextCacheIndex = Splinter.domCache.cache.length;
if (!cacheIndex) {
cacheIndex = elem[Splinter.domCache.expando] = nextCacheIndex;
Splinter.domCache.cache[cacheIndex] = {};
}
return Splinter.domCache.cache[cacheIndex];
}
};
Splinter.Utils = {
assert : function(condition) {
if (!condition) {
throw new Error("Assertion failed");
}
},
assertNotReached : function() {
throw new Error("Assertion failed: should not be reached");
},
strip : function(string) {
return (/^\s*([\s\S]*?)\s*$/).exec(string)[1];
},
lstrip : function(string) {
return (/^\s*([\s\S]*)$/).exec(string)[1];
},
rstrip : function(string) {
return (/^([\s\S]*?)\s*$/).exec(string)[1];
},
formatDate : function(date, now) {
if (now == null) {
now = new Date();
}
var daysAgo = (now.getTime() - date.getTime()) / (24 * 60 * 60 * 1000);
if (daysAgo < 0 && now.getDate() != date.getDate()) {
return date.toLocaleDateString();
} else if (daysAgo < 1 && now.getDate() == date.getDate()) {
return date.toLocaleTimeString();
} else if (daysAgo < 7 && now.getDay() != date.getDay()) {
return ['Sun', 'Mon','Tue','Wed','Thu','Fri','Sat'][date.getDay()] + " " + date.toLocaleTimeString();
} else {
return date.toLocaleDateString();
}
},
preWrapLines : function(el, text) {
while ((m = Splinter.LINE_RE.exec(text)) != null) {
var div = document.createElement("div");
div.className = "pre-wrap";
div.appendChild(document.createTextNode(m[1].length == 0 ? " " : m[1]));
el.appendChild(div);
}
},
isDigits : function (str) {
return str.match(/^[0-9]+$/);
}
};
Splinter.Bug = {
TIMEZONES : {
CEST: '200',
CET: '100',
BST: '100',
GMT: '000',
UTC: '000',
EDT: '-400',
EST: '-500',
CDT: '-500',
CST: '-600',
MDT: '-600',
MST: '-700',
PDT: '-700',
PST: '-800'
},
parseDate : function(d) {
var m = /^\s*(\d+)-(\d+)-(\d+)\s+(\d+):(\d+)(?::(\d+))?\s+(?:([A-Z]{3,})|([-+]\d{3,}))\s*$/.exec(d);
if (!m) {
return null;
}
var year = parseInt(m[1], 10);
var month = parseInt(m[2] - 1, 10);
var day = parseInt(m[3], 10);
var hour = parseInt(m[4], 10);
var minute = parseInt(m[5], 10);
var second = m[6] ? parseInt(m[6], 10) : 0;
var tzoffset = 0;
if (m[7]) {
if (m[7] in Splinter.Bug.TIMEZONES) {
tzoffset = Splinter.Bug.TIMEZONES[m[7]];
}
} else {
tzoffset = parseInt(m[8], 10);
}
var unadjustedDate = new Date(Date.UTC(m[1], m[2] - 1, m[3], m[4], m[5]));
// 430 => 4:30. Easier to do this computation for only positive offsets
var sign = tzoffset < 0 ? -1 : 1;
tzoffset *= sign;
var adjustmentHours = Math.floor(tzoffset/100);
var adjustmentMinutes = tzoffset - adjustmentHours * 100;
return new Date(unadjustedDate.getTime() -
sign * adjustmentHours * 3600000 -
sign * adjustmentMinutes * 60000);
},
_formatWho : function(name, email) {
if (name && email) {
return name + " <" + email + ">";
} else if (name) {
return name;
} else {
return email;
}
}
};
Splinter.Bug.Attachment = function(bug, id) {
this._init(bug, id);
};
Splinter.Bug.Attachment.prototype = {
_init : function(bug, id) {
this.bug = bug;
this.id = id;
}
};
Splinter.Bug.Comment = function(bug) {
this._init(bug);
};
Splinter.Bug.Comment.prototype = {
_init : function(bug) {
this.bug = bug;
},
getWho : function() {
return Splinter.Bug._formatWho(this.whoName, this.whoEmail);
}
};
Splinter.Bug.Bug = function() {
this._init();
};
Splinter.Bug.Bug.prototype = {
_init : function() {
this.attachments = [];
this.comments = [];
},
getAttachment : function(attachmentId) {
var i;
for (i = 0; i < this.attachments.length; i++) {
if (this.attachments[i].id == attachmentId) {
return this.attachments[i];
}
}
return null;
},
getReporter : function() {
return Splinter.Bug._formatWho(this.reporterName, this.reporterEmail);
}
};
Splinter.Dialog = function() {
this._init.apply(this, arguments);
};
Splinter.Dialog.prototype = {
_init: function(prompt) {
this.buttons = [];
this.dialog = new YAHOO.widget.SimpleDialog('dialog', {
width: "300px",
fixedcenter: true,
visible: false,
modal: true,
draggable: false,
close: false,
hideaftersubmit: true,
constraintoviewport: true
});
this.dialog.setHeader(prompt);
},
addButton : function (label, callback, isdefault) {
this.buttons.push({ text : label,
handler : function () { this.hide(); callback(); },
isDefault : isdefault });
this.dialog.cfg.queueProperty("buttons", this.buttons);
},
show : function () {
this.dialog.render(document.body);
this.dialog.show();
}
};
Splinter.Patch = {
ADDED : 1 << 0,
REMOVED : 1 << 1,
CHANGED : 1 << 2,
NEW_NONEWLINE : 1 << 3,
OLD_NONEWLINE : 1 << 4,
FILE_START_RE : new RegExp(
'^(?:' + // start of optional header
'(?:Index|index|===|RCS|diff)[^\\n]*\\n' + // header
'(?:(?:copy|rename) from [^\\n]+\\n)?' + // git copy/rename from
'(?:(?:copy|rename) to [^\\n]+\\n)?' + // git copy/rename to
')*' + // end of optional header
'\\-\\-\\-[ \\t]*(\\S+).*\\n' + // --- line
'\\+\\+\\+[ \\t]*(\\S+).*\\n' + // +++ line
'(?=@@)', // @@ line
'mg'
),
HUNK_START1_RE: /^@@[ \t]+-(\d+),(\d+)[ \t]+\+(\d+),(\d+)[ \t]+@@(.*)\n/mg, // -l,s +l,s
HUNK_START2_RE: /^@@[ \t]+-(\d+),(\d+)[ \t]+\+(\d+)[ \t]+@@(.*)\n/mg, // -l,s +l
HUNK_START3_RE: /^@@[ \t]+-(\d+)[ \t]+\+(\d+),(\d+)[ \t]+@@(.*)\n/mg, // -l +l,s
HUNK_START4_RE: /^@@[ \t]+-(\d+)[ \t]+\+(\d+)[ \t]+@@(.*)\n/mg, // -l +l
HUNK_RE : /((?:(?!--- )[ +\\-].*(?:\n|$)|(?:\n|$))*)/mg,
GIT_BINARY_RE : /^diff --git a\/(\S+).*\n(?:(new|deleted) file mode \d+\n)?(?:index.*\n)?GIT binary patch\n(delta )?/mg,
_cleanIntro : function(intro) {
var m;
intro = Splinter.Utils.strip(intro) + "\n\n";
// Git: remove binary diffs
var binary_re = /^(?:diff --git .*\n|literal \d+\n)(?:.+\n)+\n/mg;
m = binary_re.exec(intro);
while (m) {
intro = intro.substr(m.index + m[0].length);
binary_re.lastIndex = 0;
m = binary_re.exec(intro);
}
// Git: remove leading 'From <commit_id> <date>'
m = /^From\s+[a-f0-9]{40}.*\n/.exec(intro);
if (m) {
intro = intro.substr(m.index + m[0].length);
}
// Git: remove 'diff --stat' output from the end
m = /^---\n(?:^\s.*\n)+\s+\d+\s+files changed.*\n?(?!.)/m.exec(intro);
if (m) {
intro = intro.substr(0, m.index);
}
return Splinter.Utils.strip(intro);
}
};
Splinter.Patch.Hunk = function(oldStart, oldCount, newStart, newCount, functionLine, text) {
this._init(oldStart, oldCount, newStart, newCount, functionLine, text);
};
Splinter.Patch.Hunk.prototype = {
_init : function(oldStart, oldCount, newStart, newCount, functionLine, text) {
var rawlines = text.split("\n");
if (rawlines.length > 0 && Splinter.Utils.strip(rawlines[rawlines.length - 1]) == "") {
rawlines.pop(); // Remove trailing element from final \n
}
this.oldStart = oldStart;
this.oldCount = oldCount;
this.newStart = newStart;
this.newCount = newCount;
this.functionLine = Splinter.Utils.strip(functionLine);
this.comment = null;
var lines = [];
var totalOld = 0;
var totalNew = 0;
var currentStart = -1;
var currentOldCount = 0;
var currentNewCount = 0;
// A segment is a series of lines added/removed/changed with no intervening
// unchanged lines. We make the classification of Patch.ADDED/Patch.REMOVED/Patch.CHANGED
// in the flags for the entire segment
function startSegment() {
if (currentStart < 0) {
currentStart = lines.length;
}
}
function endSegment() {
if (currentStart >= 0) {
if (currentOldCount > 0 && currentNewCount > 0) {
var j;
for (j = currentStart; j < lines.length; j++) {
lines[j][2] &= ~(Splinter.Patch.ADDED | Splinter.Patch.REMOVED);
lines[j][2] |= Splinter.Patch.CHANGED;
}
}
currentStart = -1;
currentOldCount = 0;
currentNewCount = 0;
}
}
var i;
for (i = 0; i < rawlines.length; i++) {
var line = rawlines[i];
var op = line.substr(0, 1);
var strippedLine = line.substring(1);
var noNewLine = 0;
if (i + 1 < rawlines.length && rawlines[i + 1].substr(0, 1) == '\\') {
noNewLine = op == '-' ? Splinter.Patch.OLD_NONEWLINE : Splinter.Patch.NEW_NONEWLINE;
}
if (op == ' ') {
endSegment();
totalOld++;
totalNew++;
lines.push([strippedLine, strippedLine, 0]);
} else if (op == '-') {
totalOld++;
startSegment();
lines.push([strippedLine, null, Splinter.Patch.REMOVED | noNewLine]);
currentOldCount++;
} else if (op == '+') {
totalNew++;
startSegment();
if (currentStart + currentNewCount >= lines.length) {
lines.push([null, strippedLine, Splinter.Patch.ADDED | noNewLine]);
} else {
lines[currentStart + currentNewCount][1] = strippedLine;
lines[currentStart + currentNewCount][2] |= Splinter.Patch.ADDED | noNewLine;
}
currentNewCount++;
}
}
// git mail-formatted patches end with --\n<git version> like a signature
// This is troublesome since it looks like a subtraction at the end
// of last hunk of the last file. Handle this specifically rather than
// generically stripping excess lines to be kind to hand-edited patches
if (totalOld > oldCount &&
lines[lines.length - 1][1] == null &&
lines[lines.length - 1][0].substr(0, 1) == '-')
{
lines.pop();
currentOldCount--;
if (currentOldCount == 0 && currentNewCount == 0) {
currentStart = -1;
}
}
endSegment();
this.lines = lines;
},
iterate : function(cb) {
var i;
var oldLine = this.oldStart;
var newLine = this.newStart;
for (i = 0; i < this.lines.length; i++) {
var line = this.lines[i];
cb(this.location + i, oldLine, line[0], newLine, line[1], line[2], line);
if (line[0] != null) {
oldLine++;
}
if (line[1] != null) {
newLine++;
}
}
}
};
Splinter.Patch.File = function(filename, status, extra, hunks) {
this._init(filename, status, extra, hunks);
};
Splinter.Patch.File.prototype = {
_init : function(filename, status, extra, hunks) {
this.filename = filename;
this.status = status;
this.extra = extra;
this.hunks = hunks;
this.fileReviewed = false;
var l = 0;
var i;
for (i = 0; i < this.hunks.length; i++) {
var hunk = this.hunks[i];
hunk.location = l;
l += hunk.lines.length;
}
},
// A "location" is just a linear index into the lines of the patch in this file
getLocation : function(oldLine, newLine) {
var i;
for (i = 0; i < this.hunks.length; i++) {
var hunk = this.hunks[i];
if (oldLine != null && hunk.oldStart > oldLine) {
continue;
}
if (newLine != null && hunk.newStart > newLine) {
continue;
}
if ((oldLine != null && oldLine < hunk.oldStart + hunk.oldCount) ||
(newLine != null && newLine < hunk.newStart + hunk.newCount))
{
var location = -1;
hunk.iterate(function(loc, oldl, oldText, newl, newText, flags) {
if ((oldLine == null || oldl == oldLine) &&
(newLine == null || newl == newLine))
{
location = loc;
}
});
if (location != -1) {
return location;
}
}
}
throw "Bad oldLine,newLine: " + oldLine + "," + newLine;
},
getHunk : function(location) {
var i;
for (i = 0; i < this.hunks.length; i++) {
var hunk = this.hunks[i];
if (location >= hunk.location && location < hunk.location + hunk.lines.length) {
return hunk;
}
}
throw "Bad location: " + location;
},
toString : function() {
return "Splinter.Patch.File(" + this.filename + ")";
}
};
Splinter.Patch.Patch = function(text) {
this._init(text);
};
Splinter.Patch.Patch.prototype = {
// cf. parsing in Review.Review.parse()
_init : function(text) {
// Canonicalize newlines to simplify the following
if (/\r/.test(text)) {
text = text.replace(/(\r\n|\r|\n)/g, "\n");
}
this.files = [];
var m = Splinter.Patch.FILE_START_RE.exec(text);
var bm = Splinter.Patch.GIT_BINARY_RE.exec(text);
if (m == null && bm == null)
throw "Not a patch";
this.intro = m == null ? '' : Splinter.Patch._cleanIntro(text.substring(0, m.index));
// show binary files in the intro
if (bm && this.intro.length)
this.intro += "\n\n";
while (bm != null) {
if (bm[2]) {
// added or deleted file
this.intro += bm[2].charAt(0).toUpperCase() + bm[2].slice(1) + ' Binary File: ' + bm[1] + "\n";
} else {
// delta
this.intro += 'Modified Binary File: ' + bm[1] + "\n";
}
bm = Splinter.Patch.GIT_BINARY_RE.exec(text);
}
while (m != null) {
// git shows a diff between a/foo/bar.c and b/foo/bar.c or between
// a/foo/bar.c and /dev/null for removals and the reverse for
// additions.
var filename;
var status = undefined;
var extra = undefined;
if (/^a\//.test(m[1]) && /^b\//.test(m[2])) {
filename = m[2].substring(2);
status = Splinter.Patch.CHANGED;
} else if (/^a\//.test(m[1]) && /^\/dev\/null/.test(m[2])) {
filename = m[1].substring(2);
status = Splinter.Patch.REMOVED;
} else if (/^\/dev\/null/.test(m[1]) && /^b\//.test(m[2])) {
filename = m[2].substring(2);
status = Splinter.Patch.ADDED;
// Handle non-git cases as well
} else if (!/^\/dev\/null/.test(m[1]) && /^\/dev\/null/.test(m[2])) {
filename = m[1];
status = Splinter.Patch.REMOVED;
} else if (/^\/dev\/null/.test(m[1]) && !/^\/dev\/null/.test(m[2])) {
filename = m[2];
status = Splinter.Patch.ADDED;
} else {
filename = m[1];
}
// look for rename/copy
if (/^diff /.test(m[0])) {
// possibly git
var lines = m[0].split(/\n/);
for (var i = 0, il = lines.length; i < il && !extra; i++) {
var line = lines[i];
if (line != '' && !/^(?:diff|---|\+\+\+) /.test(line)) {
if (/^copy from /.test(line))
extra = 'copied from ' + m[1].substring(2);
if (/^rename from /.test(line))
extra = 'renamed from ' + m[1].substring(2);
}
}
} else if (/^=== renamed /.test(m[0])) {
// bzr
filename = m[2];
extra = 'renamed from ' + m[1];
}
var hunks = [];
var pos = Splinter.Patch.FILE_START_RE.lastIndex;
while (true) {
var found = false;
var oldStart, oldCount, newStart, newCount, context;
// -l,s +l,s
var re = Splinter.Patch.HUNK_START1_RE;
re.lastIndex = pos;
var m2 = re.exec(text);
if (m2 != null && m2.index == pos) {
oldStart = parseInt(m2[1], 10);
oldCount = parseInt(m2[2], 10);
newStart = parseInt(m2[3], 10);
newCount = parseInt(m2[4], 10);
context = m2[5];
found = true;
}
if (!found) {
// -l,s +l
re = Splinter.Patch.HUNK_START2_RE;
re.lastIndex = pos;
m2 = re.exec(text);
if (m2 != null && m2.index == pos) {
oldStart = parseInt(m2[1], 10);
oldCount = parseInt(m2[2], 10);
newStart = parseInt(m2[3], 10);
newCount = 1;
context = m2[4];
found = true;
}
}
if (!found) {
// -l +l,s
re = Splinter.Patch.HUNK_START3_RE;
re.lastIndex = pos;
m2 = re.exec(text);
if (m2 != null && m2.index == pos) {
oldStart = parseInt(m2[1], 10);
oldCount = 1;
newStart = parseInt(m2[2], 10);
newCount = parseInt(m2[3], 10);
context = m2[4];
found = true;
}
}
if (!found) {
// -l +l
re = Splinter.Patch.HUNK_START4_RE;
re.lastIndex = pos;
m2 = re.exec(text);
if (m2 != null && m2.index == pos) {
oldStart = parseInt(m2[1], 10);
oldCount = 1;
newStart = parseInt(m2[2], 10);
newCount = 1;
context = m2[3];
found = true;
}
}
if (!found)
break;
pos = re.lastIndex;
Splinter.Patch.HUNK_RE.lastIndex = pos;
var m3 = Splinter.Patch.HUNK_RE.exec(text);
if (m3 == null || m3.index != pos) {
break;
}
pos = Splinter.Patch.HUNK_RE.lastIndex;
hunks.push(new Splinter.Patch.Hunk(oldStart, oldCount, newStart, newCount, context, m3[1]));
}
if (status === undefined) {
// For non-Git we use assume patch was generated non-zero
// context and just look at the patch to detect added/removed.
// Bzr actually says added/removed in the diff, but SVN/CVS
// don't
if (hunks.length == 1 && hunks[0].oldCount == 0) {
status = Splinter.Patch.ADDED;
} else if (hunks.length == 1 && hunks[0].newCount == 0) {
status = Splinter.Patch.REMOVED;
} else {
status = Splinter.Patch.CHANGED;
}
}
this.files.push(new Splinter.Patch.File(filename, status, extra, hunks));
Splinter.Patch.FILE_START_RE.lastIndex = pos;
m = Splinter.Patch.FILE_START_RE.exec(text);
}
},
getFile : function(filename) {
var i;
for (i = 0; i < this.files.length; i++) {
if (this.files[i].filename == filename) {
return this.files[i];
}
}
return null;
}
};
Splinter.Review = {
_removeFromArray : function(a, element) {
var i;
for (i = 0; i < a.length; i++) {
if (a[i] === element) {
a.splice(i, 1);
return;
}
}
},
_noNewLine : function(flags, flag) {
return ((flags & flag) != 0) ? "\n\\ No newline at end of file" : "";
},
_lineInSegment : function(line) {
return (line[2] & (Splinter.Patch.ADDED | Splinter.Patch.REMOVED | Splinter.Patch.CHANGED)) != 0;
},
_compareSegmentLines : function(a, b) {
var op1 = a[0];
var op2 = b[0];
if (op1 == op2) {
return 0;
} else if (op1 == ' ') {
return -1;
} else if (op2 == ' ') {
return 1;
} else {
return op1 == '-' ? -1 : 1;
}
},
FILE_START_RE : /^:::[ \t]+(\S+)[ \t]*\n/mg,
HUNK_START_RE : /^@@[ \t]+(?:-(\d+),(\d+)[ \t]+)?(?:\+(\d+),(\d+)[ \t]+)?@@.*\n/mg,
HUNK_RE : /((?:(?!@@|:::).*\n?)*)/mg,
REVIEW_RE : /^\s*review\s+of\s+attachment\s+(\d+)\s*:\s*/i
};
Splinter.Review.Comment = function(file, location, type, comment) {
this._init(file, location, type, comment);
};
Splinter.Review.Comment.prototype = {
_init : function(file, location, type, comment) {
this.file = file;
this.type = type;
this.location = location;
this.comment = comment;
},
getHunk : function() {
return this.file.patchFile.getHunk(this.location);
},
getInReplyTo : function() {
var i;
var hunk = this.getHunk();
var line = hunk.lines[this.location - hunk.location];
for (i = 0; i < line.reviewComments.length; i++) {
var comment = line.reviewComments[i];
if (comment === this) {
return null;
}
if (comment.type == this.type) {
return comment;
}
}
return null;
},
remove : function() {
var hunk = this.getHunk();
var line = hunk.lines[this.location - hunk.location];
Splinter.Review._removeFromArray(this.file.comments, this);
Splinter.Review._removeFromArray(line.reviewComments, this);
}
};
Splinter.Review.File = function(review, patchFile) {
this._init(review, patchFile);
};
Splinter.Review.File.prototype = {
_init : function(review, patchFile) {
this.review = review;
this.patchFile = patchFile;
this.comments = [];
},
addComment : function(location, type, comment) {
var hunk = this.patchFile.getHunk(location);
var line = hunk.lines[location - hunk.location];
comment = new Splinter.Review.Comment(this, location, type, comment);
if (line.reviewComments == null) {
line.reviewComments = [];
}
line.reviewComments.push(comment);
var i;
for (i = 0; i <= this.comments.length; i++) {
if (i == this.comments.length ||
this.comments[i].location > location ||
(this.comments[i].location == location && this.comments[i].type > type)) {
this.comments.splice(i, 0, comment);
break;
} else if (this.comments[i].location == location &&
this.comments[i].type == type) {
throw "Two comments at the same location";
}
}
return comment;
},
getComment : function(location, type) {
var i;
for (i = 0; i < this.comments.length; i++) {
if (this.comments[i].location == location &&
this.comments[i].type == type)
{
return this.comments[i];
}
}
return null;
},
toString : function() {
var str = "::: " + this.patchFile.filename + "\n";
var first = true;
var i;
for (i = 0; i < this.comments.length; i++) {
if (first) {
first = false;
} else {
str += '\n';
}
var comment = this.comments[i];
var hunk = comment.getHunk();
// Find the range of lines we might want to show. That's everything in the
// same segment as the commented line, plus up two two lines of non-comment
// diff before.
var contextFirst = comment.location - hunk.location;
if (Splinter.Review._lineInSegment(hunk.lines[contextFirst])) {
while (contextFirst > 0 && Splinter.Review._lineInSegment(hunk.lines[contextFirst - 1])) {
contextFirst--;
}
}
var j;
for (j = 0; j < 5; j++) {
if (contextFirst > 0 && !Splinter.Review._lineInSegment(hunk.lines[contextFirst - 1])) {
contextFirst--;
}
}
// Now get the diff lines (' ', '-', '+' for that range of lines)
var patchOldStart = null;
var patchNewStart = null;
var patchOldLines = 0;
var patchNewLines = 0;
var unchangedLines = 0;
var patchLines = [];
function addOldLine(oldLine) {
if (patchOldLines == 0) {
patchOldStart = oldLine;
}
patchOldLines++;
}
function addNewLine(newLine) {
if (patchNewLines == 0) {
patchNewStart = newLine;
}
patchNewLines++;
}
hunk.iterate(function(loc, oldLine, oldText, newLine, newText, flags) {
if (loc >= hunk.location + contextFirst && loc <= comment.location) {
if ((flags & (Splinter.Patch.ADDED | Splinter.Patch.REMOVED | Splinter.Patch.CHANGED)) == 0) {
patchLines.push('> ' + oldText + Splinter.Review._noNewLine(flags, Splinter.Patch.OLD_NONEWLINE | Splinter.Patch.NEW_NONEWLINE));
addOldLine(oldLine);
addNewLine(newLine);
unchangedLines++;
} else {
if ((comment.type == Splinter.Patch.REMOVED
|| comment.type == Splinter.Patch.CHANGED)
&& oldText != null)
{
patchLines.push('> -' + oldText +
Splinter.Review._noNewLine(flags, Splinter.Patch.OLD_NONEWLINE));
addOldLine(oldLine);
}
if ((comment.type == Splinter.Patch.ADDED
|| comment.type == Splinter.Patch.CHANGED)
&& newText != null)
{
patchLines.push('> +' + newText +
Splinter.Review._noNewLine(flags, Splinter.Patch.NEW_NONEWLINE));
addNewLine(newLine);
}
}
}
});
// Sort them into global order ' ', '-', '+'
patchLines.sort(Splinter.Review._compareSegmentLines);
// Completely blank context isn't useful so remove it; however if we are commenting
// on blank lines at the start of a segment, we have to leave something or things break
while (patchLines.length > 1 && patchLines[0].match(/^\s*$/)) {
patchLines.shift();
patchOldStart++;
patchNewStart++;
patchOldLines--;
patchNewLines--;
unchangedLines--;
}
if (comment.type == Splinter.Patch.CHANGED) {
// For a CHANGED comment, we have to show the the start of the hunk - but to save
// in length we can trim unchanged context before it
if (patchOldLines + patchNewLines - unchangedLines > 5) {
var toRemove = Math.min(unchangedLines, patchOldLines + patchNewLines - unchangedLines - 5);
patchLines.splice(0, toRemove);
patchOldStart += toRemove;
patchNewStart += toRemove;
patchOldLines -= toRemove;
patchNewLines -= toRemove;
unchangedLines -= toRemove;
}
str += '@@ -' + patchOldStart + ',' + patchOldLines + ' +' + patchNewStart + ',' + patchNewLines + ' @@\n';
// We will use up to 10 lines more:
// 5 old lines or 4 old lines and a "... <N> more ... " line
// 5 new lines or 4 new lines and a "... <N> more ... " line
var patchRemovals = patchOldLines - unchangedLines;
var showPatchRemovals = patchRemovals > 5 ? 4 : patchRemovals;
var patchAdditions = patchNewLines - unchangedLines;
var showPatchAdditions = patchAdditions > 5 ? 4 : patchAdditions;
j = 0;
while (j < unchangedLines + showPatchRemovals) {
str += "> " + patchLines[j] + "\n";
j++;
}
if (showPatchRemovals < patchRemovals) {
str += "> ... " + (patchRemovals - showPatchRemovals) + " more ...\n";
j += patchRemovals - showPatchRemovals;
}
while (j < unchangedLines + patchRemovals + showPatchAdditions) {
str += "> " + patchLines[j] + "\n";
j++;
}
if (showPatchAdditions < patchAdditions) {
str += "> ... " + (patchAdditions - showPatchAdditions) + " more ...\n";
j += patchAdditions - showPatchAdditions;
}
} else {
// We limit Patch.ADDED/Patch.REMOVED comments strictly to 5 lines after the header
if (patchOldLines + patchNewLines - unchangedLines > 5) {
var toRemove = patchOldLines + patchNewLines - unchangedLines - 5;
patchLines.splice(0, toRemove);
patchOldStart += toRemove;
patchNewStart += toRemove;
patchOldLines -= toRemove;
patchNewLines -= toRemove;
}
if (comment.type == Splinter.Patch.REMOVED) {
str += '@@ -' + patchOldStart + ',' + patchOldLines + ' @@\n';
} else {
str += '@@ +' + patchNewStart + ',' + patchNewLines + ' @@\n';
}
str += patchLines.join("\n") + "\n";
}
str += "\n" + comment.comment + "\n";
}
return str;
}
};
Splinter.Review.Review = function(patch, who, date) {
this._init(patch, who, date);
};
Splinter.Review.Review.prototype = {
_init : function(patch, who, date) {
this.date = null;
this.patch = patch;
this.who = who;
this.date = date;
this.intro = null;
this.files = [];
var i;
for (i = 0; i < patch.files.length; i++) {
this.files.push(new Splinter.Review.File(this, patch.files[i]));
}
},
// cf. parsing in Patch.Patch._init()
parse : function(text) {
Splinter.Review.FILE_START_RE.lastIndex = 0;
var m = Splinter.Review.FILE_START_RE.exec(text);
var intro;
if (m != null) {
this.setIntro(text.substr(0, m.index));
} else{
this.setIntro(text);
return;
}
while (m != null) {
var filename = m[1];
var file = this.getFile(filename);
if (file == null) {
throw "Review.Review refers to filename '" + filename + "' not in reviewed Patch.";
}
var pos = Splinter.Review.FILE_START_RE.lastIndex;
while (true) {
Splinter.Review.HUNK_START_RE.lastIndex = pos;
var m2 = Splinter.Review.HUNK_START_RE.exec(text);
if (m2 == null || m2.index != pos) {
break;
}
pos = Splinter.Review.HUNK_START_RE.lastIndex;
var oldStart, oldCount, newStart, newCount;
if (m2[1]) {
oldStart = parseInt(m2[1], 10);
oldCount = parseInt(m2[2], 10);
} else {
oldStart = oldCount = null;
}
if (m2[3]) {
newStart = parseInt(m2[3], 10);
newCount = parseInt(m2[4], 10);
} else {
newStart = newCount = null;
}
var type;
if (oldStart != null && newStart != null) {
type = Splinter.Patch.CHANGED;
} else if (oldStart != null) {
type = Splinter.Patch.REMOVED;
} else if (newStart != null) {
type = Splinter.Patch.ADDED;
} else {
throw "Either old or new line numbers must be given";
}
var oldLine = oldStart;
var newLine = newStart;
Splinter.Review.HUNK_RE.lastIndex = pos;
var m3 = Splinter.Review.HUNK_RE.exec(text);
if (m3 == null || m3.index != pos) {
break;
}
pos = Splinter.Review.HUNK_RE.lastIndex;
var rawlines = m3[1].split("\n");
if (rawlines.length > 0 && rawlines[rawlines.length - 1].match('^/s+$')) {
rawlines.pop(); // Remove trailing element from final \n
}
var commentText = null;
var lastSegmentOld = 0;
var lastSegmentNew = 0;
var i;
for (i = 0; i < rawlines.length; i++) {
var line = rawlines[i];
var count = 1;
if (i < rawlines.length - 1 && rawlines[i + 1].match(/^\.\.\. \d+\s+/)) {
var m3 = /^\.\.\. (\d+)\s+/.exec(rawlines[i + 1]);
count += parseInt(m3[1], 10);
i += 1;
}
// The check for /^$/ is because if Bugzilla is line-wrapping it also
// strips completely whitespace lines
if (line.match(/^>\s+/) || line.match(/^$/)) {
oldLine += count;
newLine += count;
lastSegmentOld = 0;
lastSegmentNew = 0;
} else if (line.match(/^(> )?-/)) {
oldLine += count;
lastSegmentOld += count;
} else if (line.match(/^(> )?\+/)) {
newLine += count;
lastSegmentNew += count;
} else if (line.match(/^\\/)) {
// '\ No newline at end of file' - ignore
} else {
if (console)
console.log("WARNING: Bad content in hunk: " + line);
if (line != 'NaN more ...') {
// Tack onto current comment even thou it's invalid
if (commentText == null) {
commentText = line;
} else {
commentText += "\n" + line;
}
}
}
if ((oldStart == null || oldLine == oldStart + oldCount) &&
(newStart == null || newLine == newStart + newCount))
{
commentText = rawlines.slice(i + 1).join("\n");
break;
}
}
if (commentText == null) {
if (console)
console.log("WARNING: No comment found in hunk");
commentText = "";
}
var location;
try {
if (type == Splinter.Patch.CHANGED) {
if (lastSegmentOld >= lastSegmentNew) {
oldLine--;
}
if (lastSegmentOld <= lastSegmentNew) {
newLine--;
}
location = file.patchFile.getLocation(oldLine, newLine);
} else if (type == Splinter.Patch.REMOVED) {
oldLine--;
location = file.patchFile.getLocation(oldLine, null);
} else if (type == Splinter.Patch.ADDED) {
newLine--;
location = file.patchFile.getLocation(null, newLine);
}
} catch(e) {
if (console)
console.error(e);
location = 0;
}
file.addComment(location, type, Splinter.Utils.strip(commentText));
}
Splinter.Review.FILE_START_RE.lastIndex = pos;
m = Splinter.Review.FILE_START_RE.exec(text);
}
},
setIntro : function (intro) {
intro = Splinter.Utils.strip(intro);
this.intro = intro != "" ? intro : null;
},
getFile : function (filename) {
var i;
for (i = 0; i < this.files.length; i++) {
if (this.files[i].patchFile.filename == filename) {
return this.files[i];
}
}
return null;
},
// Making toString() serialize to our seriaization format is maybe a bit sketchy
// But the serialization format is designed to be human readable so it works
// pretty well.
toString : function () {
var str = '';
if (this.intro != null) {
str += Splinter.Utils.strip(this.intro);
str += '\n';
}
var first = this.intro == null;
var i;
for (i = 0; i < this.files.length; i++) {
var file = this.files[i];
if (file.comments.length > 0) {
if (first) {
first = false;
} else {
str += '\n';
}
str += file.toString();
}
}
return str;
}
};
Splinter.ReviewStorage = {};
Splinter.ReviewStorage.LocalReviewStorage = function() {
this._init();
};
Splinter.ReviewStorage.LocalReviewStorage.available = function() {
// The try is a workaround for
// https://bugzilla.mozilla.org/show_bug.cgi?id=517778
// where if cookies are disabled or set to ask, then the first attempt
// to access the localStorage property throws a security error.
try {
return 'localStorage' in window && window.localStorage != null;
} catch (e) {
return false;
}
};
Splinter.ReviewStorage.LocalReviewStorage.prototype = {
_init : function() {
var reviewInfosText = localStorage.splinterReviews;
if (reviewInfosText == null) {
this._reviewInfos = [];
} else {
this._reviewInfos = YAHOO.lang.JSON.parse(reviewInfosText);
}
},
listReviews : function() {
return this._reviewInfos;
},
_reviewPropertyName : function(bug, attachment) {
return 'splinterReview_' + bug.id + '_' + attachment.id;
},
loadDraft : function(bug, attachment, patch) {
var propertyName = this._reviewPropertyName(bug, attachment);
var reviewText = localStorage[propertyName];
if (reviewText != null) {
var review = new Splinter.Review.Review(patch);
review.parse(reviewText);
return review;
} else {
return null;
}
},
_findReview : function(bug, attachment) {
var i;
for (i = 0 ; i < this._reviewInfos.length; i++) {
if (this._reviewInfos[i].bugId == bug.id && this._reviewInfos[i].attachmentId == attachment.id) {
return i;
}
}
return -1;
},
_updateOrCreateReviewInfo : function(bug, attachment, props) {
var reviewIndex = this._findReview(bug, attachment);
var reviewInfo;
var nowTime = Date.now();
if (reviewIndex >= 0) {
reviewInfo = this._reviewInfos[reviewIndex];
this._reviewInfos.splice(reviewIndex, 1);
} else {
reviewInfo = {
bugId: bug.id,
bugShortDesc: bug.shortDesc,
attachmentId: attachment.id,
attachmentDescription: attachment.description,
creationTime: nowTime
};
}
reviewInfo.modificationTime = nowTime;
for (var prop in props) {
reviewInfo[prop] = props[prop];
}
this._reviewInfos.push(reviewInfo);
localStorage.splinterReviews = YAHOO.lang.JSON.stringify(this._reviewInfos);
},
_deleteReviewInfo : function(bug, attachment) {
var reviewIndex = this._findReview(bug, attachment);
if (reviewIndex >= 0) {
this._reviewInfos.splice(reviewIndex, 1);
localStorage.splinterReviews = YAHOO.lang.JSON.stringify(this._reviewInfos);
}
},
saveDraft : function(bug, attachment, review, extraProps) {
var propertyName = this._reviewPropertyName(bug, attachment);
if (!extraProps) {
extraProps = {};
}
extraProps.isDraft = true;
this._updateOrCreateReviewInfo(bug, attachment, extraProps);
localStorage[propertyName] = "" + review;
},
deleteDraft : function(bug, attachment, review) {
var propertyName = this._reviewPropertyName(bug, attachment);
this._deleteReviewInfo(bug, attachment);
delete localStorage[propertyName];
},
draftPublished : function(bug, attachment) {
var propertyName = this._reviewPropertyName(bug, attachment);
this._updateOrCreateReviewInfo(bug, attachment, { isDraft: false });
delete localStorage[propertyName];
}
};
Splinter.saveDraftNoticeTimeoutId = null;
Splinter.navigationLinks = {};
Splinter.reviewers = {};
Splinter.savingDraft = false;
Splinter.UPDATE_ATTACHMENT_SUCCESS = /<title>\s*Changes\s+Submitted/;
Splinter.LINE_RE = /(?!$)([^\r\n]*)(?:\r\n|\r|\n|$)/g;
Splinter.displayError = function (msg) {
var el = new Element(document.createElement('p'));
el.appendChild(document.createTextNode(msg));
Dom.get('error').appendChild(Dom.get(el));
Dom.setStyle('error', 'display', 'block');
};
Splinter.publishReview = function () {
Splinter.saveComment();
Splinter.theReview.setIntro(Dom.get('myComment').value);
if (Splinter.reviewStorage) {
Splinter.reviewStorage.draftPublished(Splinter.theBug,
Splinter.theAttachment);
}
var publish_form = Dom.get('publish');
var publish_token = Dom.get('publish_token');
var publish_attach_id = Dom.get('publish_attach_id');
var publish_attach_desc = Dom.get('publish_attach_desc');
var publish_attach_filename = Dom.get('publish_attach_filename');
var publish_attach_contenttype = Dom.get('publish_attach_contenttype');
var publish_attach_ispatch = Dom.get('publish_attach_ispatch');
var publish_attach_isobsolete = Dom.get('publish_attach_isobsolete');
var publish_attach_isprivate = Dom.get('publish_attach_isprivate');
var publish_attach_status = Dom.get('publish_attach_status');
var publish_review = Dom.get('publish_review');
publish_token.value = Splinter.theAttachment.token;
publish_attach_id.value = Splinter.theAttachment.id;
publish_attach_desc.value = Splinter.theAttachment.description;
publish_attach_filename.value = Splinter.theAttachment.filename;
publish_attach_contenttype.value = Splinter.theAttachment.contenttypeentry;
publish_attach_ispatch.value = Splinter.theAttachment.isPatch;
publish_attach_isobsolete.value = Splinter.theAttachment.isObsolete;
publish_attach_isprivate.value = Splinter.theAttachment.isPrivate;
// This is a "magic string" used to identify review comments
if (Splinter.theReview.toString()) {
var comment = "Review of attachment " + Splinter.theAttachment.id + ":\n" +
"-----------------------------------------------------------------\n\n" +
Splinter.theReview.toString();
publish_review.value = comment;
}
if (Splinter.theAttachment.status
&& Dom.get('attachmentStatus').value != Splinter.theAttachment.status)
{
publish_attach_status.value = Dom.get('attachmentStatus').value;
}
publish_form.submit();
};
Splinter.doDiscardReview = function () {
if (Splinter.theAttachment.status) {
Dom.get('attachmentStatus').value = Splinter.theAttachment.status;
}
Dom.get('myComment').value = '';
Dom.setStyle('emptyCommentNotice', 'display', 'block');
var i;
for (i = 0; i < Splinter.theReview.files.length; i++) {
while (Splinter.theReview.files[i].comments.length > 0) {
Splinter.theReview.files[i].comments[0].remove();
}
}
Splinter.updateMyPatchComments();
Splinter.updateHaveDraft();
Splinter.saveDraft();
};
Splinter.discardReview = function () {
var dialog = new Splinter.Dialog("Really discard your changes?");
dialog.addButton('No', function() {}, true);
dialog.addButton('Yes', Splinter.doDiscardReview, false);
dialog.show();
};
Splinter.haveDraft = function () {
if (Splinter.readOnly) {
return false;
}
if (Splinter.theAttachment.status && Dom.get('attachmentStatus').value != Splinter.theAttachment.status) {
return true;
}
if (Dom.get('myComment').value != '') {
return true;
}
var i;
for (i = 0; i < Splinter.theReview.files.length; i++) {
if (Splinter.theReview.files[i].comments.length > 0) {
return true;
}
}
for (i = 0; i < Splinter.thePatch.files.length; i++) {
if (Splinter.thePatch.files[i].fileReviewed) {
return true;
}
}
if (Splinter.flagChanged == 1) {
return true;
}
return false;
};
Splinter.updateHaveDraft = function () {
clearTimeout(Splinter.updateHaveDraftTimeoutId);
Splinter.updateHaveDraftTimeoutId = null;
if (Splinter.haveDraft()) {
Dom.get('publishButton').removeAttribute('disabled');
Dom.get('cancelButton').removeAttribute('disabled');
Dom.setStyle('haveDraftNotice', 'display', 'block');
} else {
Dom.get('publishButton').setAttribute('disabled', 'true');
Dom.get('cancelButton').setAttribute('disabled', 'true');
Dom.setStyle('haveDraftNotice', 'display', 'none');
}
};
Splinter.queueUpdateHaveDraft = function () {
if (Splinter.updateHaveDraftTimeoutId == null) {
Splinter.updateHaveDraftTimeoutId = setTimeout(Splinter.updateHaveDraft, 0);
}
};
Splinter.hideSaveDraftNotice = function () {
clearTimeout(Splinter.saveDraftNoticeTimeoutId);
Splinter.saveDraftNoticeTimeoutId = null;
Dom.setStyle('saveDraftNotice', 'display', 'none');
};
Splinter.saveDraft = function () {
if (Splinter.reviewStorage == null) {
return;
}
clearTimeout(Splinter.saveDraftTimeoutId);
Splinter.saveDraftTimeoutId = null;
Splinter.savingDraft = true;
Splinter.replaceText(Dom.get('saveDraftNotice'), "Saving Draft...");
Dom.setStyle('saveDraftNotice', 'display', 'block');
clearTimeout(Splinter.saveDraftNoticeTimeoutId);
setTimeout(Splinter.hideSaveDraftNotice, 3000);
if (Splinter.currentEditComment) {
Splinter.currentEditComment.comment = Splinter.Utils.strip(Dom.get("commentEditor").getElementsByTagName("textarea")[0].value);
// Messy, we don't want the empty comment in the saved draft, so remove it and
// then add it back.
if (!Splinter.currentEditComment.comment) {
Splinter.currentEditComment.remove();
}
}
Splinter.theReview.setIntro(Dom.get('myComment').value);
var draftSaved = false;
if (Splinter.haveDraft()) {
var filesReviewed = {};
for (var i = 0; i < Splinter.thePatch.files.length; i++) {
var file = Splinter.thePatch.files[i];
if (file.fileReviewed) {
filesReviewed[file.filename] = true;
}
}
Splinter.reviewStorage.saveDraft(Splinter.theBug, Splinter.theAttachment, Splinter.theReview,
{ 'filesReviewed' : filesReviewed });
draftSaved = true;
} else {
Splinter.reviewStorage.deleteDraft(Splinter.theBug, Splinter.theAttachment, Splinter.theReview);
}
if (Splinter.currentEditComment && !Splinter.currentEditComment.comment) {
Splinter.currentEditComment = Splinter.currentEditComment.file.addComment(Splinter.currentEditComment.location,
Splinter.currentEditComment.type, "");
}
Splinter.savingDraft = false;
if (draftSaved) {
Splinter.replaceText(Dom.get('saveDraftNotice'), "Saved Draft");
} else {
Splinter.hideSaveDraftNotice();
}
};
Splinter.replaceText = function (el, text) {
while(el.firstChild) el.removeChild(el.firstChild);
el.appendChild(document.createTextNode(text));
}
Splinter.queueSaveDraft = function () {
if (Splinter.saveDraftTimeoutId == null) {
Splinter.saveDraftTimeoutId = setTimeout(Splinter.saveDraft, 10000);
}
};
Splinter.flushSaveDraft = function () {
if (Splinter.saveDraftTimeoutId != null) {
Splinter.saveDraft();
}
};
Splinter.ensureCommentArea = function (row) {
var file = Splinter.domCache.data(row).patchFile;
var colSpan = file.status == Splinter.Patch.CHANGED ? 5 : 2;
if (!row.nextSibling || row.nextSibling.className != "comment-area") {
var tr = new Element(document.createElement('tr'));
Dom.addClass(tr, 'comment-area');
var td = new Element(document.createElement('td'));
Dom.setAttribute(td, 'colspan', colSpan);
td.appendTo(tr);
Dom.insertAfter(tr, row);
}
return row.nextSibling.firstChild;
};
Splinter.getTypeClass = function (type) {
switch (type) {
case Splinter.Patch.ADDED:
return "comment-added";
case Splinter.Patch.REMOVED:
return "comment-removed";
case Splinter.Patch.CHANGED:
return "comment-changed";
}
return null;
};
Splinter.getSeparatorClass = function (type) {
switch (type) {
case Splinter.Patch.ADDED:
return "comment-separator-added";
case Splinter.Patch.REMOVED:
return "comment-separator-removed";
}
return null;
};
Splinter.getReviewerClass = function (review) {
var reviewerIndex;
if (review == Splinter.theReview) {
reviewerIndex = 0;
} else {
reviewerIndex = (Splinter.reviewers[review.who] - 1) % 5 + 1;
}
return "reviewer-" + reviewerIndex;
};
Splinter.addCommentDisplay = function (commentArea, comment) {
var review = comment.file.review;
var separatorClass = Splinter.getSeparatorClass(comment.type);
if (separatorClass) {
var div = new Element(document.createElement('div'));
Dom.addClass(div, separatorClass);
Dom.addClass(div, Splinter.getReviewerClass(review));
div.appendTo(commentArea);
}
var commentDiv = new Element(document.createElement('div'));
Dom.addClass(commentDiv, 'comment');
Dom.addClass(commentDiv, Splinter.getTypeClass(comment.type));
Dom.addClass(commentDiv, Splinter.getReviewerClass(review));
Event.addListener(Dom.get(commentDiv), 'dblclick', function () {
Splinter.saveComment();
Splinter.insertCommentEditor(commentArea, comment.file.patchFile,
comment.location, comment.type);
});
var commentFrame = new Element(document.createElement('div'));
Dom.addClass(commentFrame, 'comment-frame');
commentFrame.appendTo(commentDiv);
var reviewerBox = new Element(document.createElement('div'));
Dom.addClass(reviewerBox, 'reviewer-box');
reviewerBox.appendTo(commentFrame);
var commentText = new Element(document.createElement('div'));
Dom.addClass(commentText, 'comment-text');
Splinter.Utils.preWrapLines(commentText, comment.comment);
commentText.appendTo(reviewerBox);
commentDiv.appendTo(commentArea);
if (review != Splinter.theReview) {
var reviewInfo = new Element(document.createElement('div'));
Dom.addClass(reviewInfo, 'review-info');
var reviewer = new Element(document.createElement('div'));
Dom.addClass(reviewer, 'reviewer');
reviewer.appendChild(document.createTextNode(review.who));
reviewer.appendTo(reviewInfo);
var reviewDate = new Element(document.createElement('div'));
Dom.addClass(reviewDate, 'review-date');
reviewDate.appendChild(document.createTextNode(Splinter.Utils.formatDate(review.date)));
reviewDate.appendTo(reviewInfo);
var reviewInfoBottom = new Element(document.createElement('div'));
Dom.addClass(reviewInfoBottom, 'review-info-bottom');
reviewInfoBottom.appendTo(reviewInfo);
reviewInfo.appendTo(reviewerBox);
}
comment.div = commentDiv;
};
Splinter.saveComment = function () {
var comment = Splinter.currentEditComment;
if (!comment) {
return;
}
var commentEditor = Dom.get('commentEditor');
var commentArea = commentEditor.parentNode;
var reviewFile = comment.file;
var hunk = comment.getHunk();
var line = hunk.lines[comment.location - hunk.location];
var value = Splinter.Utils.strip(commentEditor.getElementsByTagName('textarea')[0].value);
if (value != "") {
comment.comment = value;
Splinter.addCommentDisplay(commentArea, comment);
} else {
comment.remove();
}
if (line.reviewComments.length > 0) {
commentEditor.parentNode.removeChild(commentEditor);
var commentEditorSeparator = Dom.get('commentEditorSeparator');
if (commentEditorSeparator) {
commentEditorSeparator.parentNode.removeChild(commentEditorSeparator);
}
} else {
var parentToRemove = commentArea.parentNode;
commentArea.parentNode.parentNode.removeChild(parentToRemove);
}
Splinter.currentEditComment = null;
Splinter.saveDraft();
Splinter.queueUpdateHaveDraft();
};
Splinter.cancelComment = function (previousText) {
Dom.get("commentEditor").getElementsByTagName("textarea")[0].value = previousText;
Splinter.saveComment();
};
Splinter.deleteComment = function () {
Dom.get('commentEditor').getElementsByTagName('textarea')[0].value = "";
Splinter.saveComment();
};
Splinter.insertCommentEditor = function (commentArea, file, location, type) {
Splinter.saveComment();
var reviewFile = Splinter.theReview.getFile(file.filename);
var comment = reviewFile.getComment(location, type);
if (!comment) {
comment = reviewFile.addComment(location, type, "");
Splinter.queueUpdateHaveDraft();
}
var previousText = comment.comment;
var typeClass = Splinter.getTypeClass(type);
var separatorClass = Splinter.getSeparatorClass(type);
var nodes = Dom.getElementsByClassName('reviewer-0', 'div', commentArea);
var i;
for (i = 0; i < nodes.length; i++) {
if (separatorClass && Dom.hasClass(nodes[i], separatorClass)) {
nodes[i].parentNode.removeChild(nodes[i]);
}
if (Dom.hasClass(nodes[i], typeClass)) {
nodes[i].parentNode.removeChild(nodes[i]);
}
}
if (separatorClass) {
var commentEditorSeparator = new Element(document.createElement('div'));
commentEditorSeparator.set('id', 'commentEditorSeparator');
Dom.addClass(commentEditorSeparator, separatorClass);
commentEditorSeparator.appendTo(commentArea);
}
var commentEditor = new Element(document.createElement('div'));
Dom.setAttribute(commentEditor, 'id', 'commentEditor');
Dom.addClass(commentEditor, typeClass);
commentEditor.appendTo(commentArea);
var commentEditorInner = new Element(document.createElement('div'));
Dom.setAttribute(commentEditorInner, 'id', 'commentEditorInner');
commentEditorInner.appendTo(commentEditor);
var commentTextFrame = new Element(document.createElement('div'));
Dom.setAttribute(commentTextFrame, 'id', 'commentTextFrame');
commentTextFrame.appendTo(commentEditorInner);
var commentTextArea = new Element(document.createElement('textarea'));
Dom.setAttribute(commentTextArea, 'id', 'commentTextArea');
Dom.setAttribute(commentTextArea, 'tabindex', 1);
commentTextArea.appendChild(document.createTextNode(previousText));
commentTextArea.appendTo(commentTextFrame);
Event.addListener('commentTextArea', 'keydown', function (e) {
if (e.which == 13 && e.ctrlKey) {
Splinter.saveComment();
} else if (e.which == 27) {
var comment = Dom.get('commentTextArea').value;
if (previousText == comment || comment == '') {
Splinter.cancelComment(previousText);
}
} else {
Splinter.queueSaveDraft();
}
});
Event.addListener('commentTextArea', 'focusin', function () { Dom.addClass(commentEditor, 'focused'); });
Event.addListener('commentTextArea', 'focusout', function () { Dom.removeClass(commentEditor, 'focused'); });
Dom.get(commentTextArea).focus();
var commentEditorLeftButtons = new Element(document.createElement('div'));
commentEditorLeftButtons.set('id', 'commentEditorLeftButtons');
commentEditorLeftButtons.appendTo(commentEditorInner);
var commentCancel = new Element(document.createElement('input'));
commentCancel.set('id','commentCancel');
commentCancel.set('type', 'button');
commentCancel.set('value', 'Cancel');
Dom.setAttribute(commentCancel, 'tabindex', 4);
commentCancel.appendTo(commentEditorLeftButtons);
Event.addListener('commentCancel', 'click', function () { Splinter.cancelComment(previousText); });
if (previousText) {
var commentDelete = new Element(document.createElement('input'));
commentDelete.set('id','commentDelete');
commentDelete.set('type', 'button');
commentDelete.set('value', 'Delete');
Dom.setAttribute(commentDelete, 'tabindex', 3);
commentDelete.appendTo(commentEditorLeftButtons);
Event.addListener('commentDelete', 'click', Splinter.deleteComment);
}
var commentEditorRightButtons = new Element(document.createElement('div'));
commentEditorRightButtons.set('id', 'commentEditorRightButtons');
commentEditorRightButtons.appendTo(commentEditorInner);
var commentSave = new Element(document.createElement('input'));
commentSave.set('id','commentSave');
commentSave.set('type', 'button');
commentSave.set('value', 'Save');
Dom.setAttribute(commentSave, 'tabindex', 2);
commentSave.appendTo(commentEditorRightButtons);
Event.addListener('commentSave', 'click', Splinter.saveComment);
var clear = new Element(document.createElement('div'));
Dom.addClass(clear, 'clear');
clear.appendTo(commentEditorInner);
Splinter.currentEditComment = comment;
};
Splinter.insertCommentForRow = function (clickRow, clickType) {
var file = Splinter.domCache.data(clickRow).patchFile;
var clickLocation = Splinter.domCache.data(clickRow).patchLocation;
var row = clickRow;
var location = clickLocation;
var type = clickType;
Splinter.saveComment();
var commentArea = Splinter.ensureCommentArea(row);
Splinter.insertCommentEditor(commentArea, file, location, type);
};
Splinter.EL = function (element, cls, text, title) {
var e = document.createElement(element);
if (text != null) {
e.appendChild(document.createTextNode(text));
}
if (cls) {
e.className = cls;
}
if (title) {
Dom.setAttribute(e, 'title', title);
}
return e;
};
Splinter.textTD = function (cls, text, title) {
if (text == "") {
return Splinter.EL("td", cls, "\u00a0", title);
}
var m = text.match(/^(.*?)(\s+)$/);
if (m) {
var td = Splinter.EL("td", cls, m[1], title);
td.insertBefore(Splinter.EL("span", cls + " trailing-whitespace", m[2], title), null);
return td;
} else {
return Splinter.EL("td", cls, text, title);
}
}
Splinter.getElementPosition = function (element) {
var left = element.offsetLeft;
var top = element.offsetTop;
var parent = element.offsetParent;
while (parent && parent != document.body) {
left += parent.offsetLeft;
top += parent.offsetTop;
parent = parent.offsetParent;
}
return [left, top];
};
Splinter.scrollToElement = function (element) {
var windowHeight;
if ('innerHeight' in window) { // Not IE
windowHeight = window.innerHeight;
} else { // IE
windowHeight = document.documentElement.clientHeight;
}
var pos = Splinter.getElementPosition(element);
var yCenter = pos[1] + element.offsetHeight / 2;
window.scrollTo(0, yCenter - windowHeight / 2);
};
Splinter.onRowDblClick = function (e) {
var file = Splinter.domCache.data(this).patchFile;
var type;
if (file.status == Splinter.Patch.CHANGED) {
var pos = Splinter.getElementPosition(this);
var delta = e.pageX - (pos[0] + this.offsetWidth/2);
if (delta < - 20) {
type = Splinter.Patch.REMOVED;
} else if (delta < 20) {
// CHANGED comments disabled due to breakage
// type = Splinter.Patch.CHANGED;
type = Splinter.Patch.ADDED;
} else {
type = Splinter.Patch.ADDED;
}
} else {
type = file.status;
}
Splinter.insertCommentForRow(this, type);
};
Splinter.appendPatchTable = function (type, maxLine, parentDiv) {
var fileTableContainer = new Element(document.createElement('div'));
Dom.addClass(fileTableContainer, 'file-table-container');
fileTableContainer.appendTo(parentDiv);
var fileTable = new Element(document.createElement('table'));
Dom.addClass(fileTable, 'file-table');
fileTable.appendTo(fileTableContainer);
var colQ = new Element(document.createElement('colgroup'));
colQ.appendTo(fileTable);
var col1, col2;
if (type != Splinter.Patch.ADDED) {
col1 = new Element(document.createElement('col'));
Dom.addClass(col1, 'line-number-column');
Dom.setAttribute(col1, 'span', '1');
col1.appendTo(colQ);
col2 = new Element(document.createElement('col'));
Dom.addClass(col2, 'old-column');
Dom.setAttribute(col2, 'span', '1');
col2.appendTo(colQ);
}
if (type == Splinter.Patch.CHANGED) {
col1 = new Element(document.createElement('col'));
Dom.addClass(col1, 'middle-column');
Dom.setAttribute(col1, 'span', '1');
col1.appendTo(colQ);
}
if (type != Splinter.Patch.REMOVED) {
col1 = new Element(document.createElement('col'));
Dom.addClass(col1, 'line-number-column');
Dom.setAttribute(col1, 'span', '1');
col1.appendTo(colQ);
col2 = new Element(document.createElement('col'));
Dom.addClass(col2, 'new-column');
Dom.setAttribute(col2, 'span', '1');
col2.appendTo(colQ);
}
if (type == Splinter.Patch.CHANGED) {
Dom.addClass(fileTable, 'file-table-changed');
}
if (maxLine >= 1000) {
Dom.addClass(fileTable, "file-table-wide-numbers");
}
var tbody = new Element(document.createElement('tbody'));
tbody.appendTo(fileTable);
return tbody;
};
Splinter.appendPatchHunk = function (file, hunk, tableType, includeComments, clickable, tbody, filter) {
hunk.iterate(function(loc, oldLine, oldText, newLine, newText, flags, line) {
if (filter && !filter(loc)) {
return;
}
var tr = document.createElement("tr");
var oldStyle = "";
var newStyle = "";
if ((flags & Splinter.Patch.CHANGED) != 0) {
oldStyle = newStyle = "changed-line";
} else if ((flags & Splinter.Patch.REMOVED) != 0) {
oldStyle = "removed-line";
} else if ((flags & Splinter.Patch.ADDED) != 0) {
newStyle = "added-line";
}
var title = "Double click the line to add a review comment";
if (tableType != Splinter.Patch.ADDED) {
if (oldText != null) {
tr.appendChild(Splinter.EL("td", "line-number", oldLine.toString(), title));
tr.appendChild(Splinter.textTD("old-line " + oldStyle, oldText, title));
oldLine++;
} else {
tr.appendChild(Splinter.EL("td", "line-number"));
tr.appendChild(Splinter.EL("td", "old-line"));
}
}
if (tableType == Splinter.Patch.CHANGED) {
tr.appendChild(Splinter.EL("td", "line-middle"));
}
if (tableType != Splinter.Patch.REMOVED) {
if (newText != null) {
tr.appendChild(Splinter.EL("td", "line-number", newLine.toString(), title));
tr.appendChild(Splinter.textTD("new-line " + newStyle, newText, title));
newLine++;
} else if (tableType == Splinter.Patch.CHANGED) {
tr.appendChild(Splinter.EL("td", "line-number"));
tr.appendChild(Splinter.EL("td", "new-line"));
}
}
if (!Splinter.readOnly && clickable) {
Splinter.domCache.data(tr).patchFile = file;
Splinter.domCache.data(tr).patchLocation = loc;
Event.addListener(tr, 'dblclick', Splinter.onRowDblClick);
}
tbody.appendChild(tr);
if (includeComments && line.reviewComments != null) {
var k;
for (k = 0; k < line.reviewComments.length; k++) {
var commentArea = Splinter.ensureCommentArea(tr);
Splinter.addCommentDisplay(commentArea, line.reviewComments[k]);
}
}
});
};
Splinter.addPatchFile = function (file) {
var fileDiv = new Element(document.createElement('div'));
Dom.addClass(fileDiv, 'file');
fileDiv.appendTo(Dom.get('splinter-files'));
file.div = fileDiv;
var statusString;
switch (file.status) {
case Splinter.Patch.ADDED:
statusString = " (new file)";
break;
case Splinter.Patch.REMOVED:
statusString = " (removed)";
break;
case Splinter.Patch.CHANGED:
statusString = "";
break;
}
var fileLabel = new Element(document.createElement('div'));
Dom.addClass(fileLabel, 'file-label');
fileLabel.appendTo(fileDiv);
var fileCollapseLink = new Element(document.createElement('a'));
Dom.addClass(fileCollapseLink, 'file-label-collapse');
fileCollapseLink.appendChild(document.createTextNode('[-]'));
Dom.setAttribute(fileCollapseLink, 'href', 'javascript:void(0);')
Dom.setAttribute(fileCollapseLink, 'onclick', "Splinter.toggleCollapsed('" +
encodeURIComponent(file.filename) + "');");
Dom.setAttribute(fileCollapseLink, 'title', 'Click to expand or collapse this file table');
fileCollapseLink.appendTo(fileLabel);
var fileLabelName = new Element(document.createElement('span'));
Dom.addClass(fileLabelName, 'file-label-name');
fileLabelName.appendChild(document.createTextNode(file.filename));
fileLabelName.appendTo(fileLabel);
var fileLabelStatus = new Element(document.createElement('span'));
Dom.addClass(fileLabelStatus, 'file-label-status');
fileLabelStatus.appendChild(document.createTextNode(statusString));
fileLabelStatus.appendTo(fileLabel);
if (!Splinter.readOnly) {
var fileReviewed = new Element(document.createElement('span'));
Dom.addClass(fileReviewed, 'file-review');
Dom.setAttribute(fileReviewed, 'title', 'Indicates that a review has been completed for this file. ' +
'This is for personal tracking purposes only and has no effect ' +
'on the published review.');
fileReviewed.appendTo(fileLabel);
var fileReviewedInput = new Element(document.createElement('input'));
Dom.setAttribute(fileReviewedInput, 'type', 'checkbox');
Dom.setAttribute(fileReviewedInput, 'id', 'file-review-checkbox-' + encodeURIComponent(file.filename));
Dom.setAttribute(fileReviewedInput, 'onchange', "Splinter.toggleFileReviewed('" +
encodeURIComponent(file.filename) + "');");
if (file.fileReviewed) {
Dom.setAttribute(fileReviewedInput, 'checked', 'true');
}
fileReviewedInput.appendTo(fileReviewed);
var fileReviewedLabel = new Element(document.createElement('label'));
Dom.addClass(fileReviewedLabel, 'file-review-label')
Dom.setAttribute(fileReviewedLabel, 'for', 'file-review-checkbox-' + encodeURIComponent(file.filename));
fileReviewedLabel.appendChild(document.createTextNode(' Reviewed'));
fileReviewedLabel.appendTo(fileReviewed);
}
if (file.extra) {
var extraContainer = new Element(document.createElement('div'));
Dom.addClass(extraContainer, 'file-extra-container');
var extraMargin = new Element(document.createElement('span'));
Dom.addClass(extraMargin, 'file-label-collapse');
extraMargin.appendChild(document.createTextNode('\u00a0\u00a0\u00a0'));
extraMargin.appendTo(extraContainer);
var extraLabel = new Element(document.createElement('span'));
Dom.addClass(extraLabel, 'file-label-extra');
extraLabel.appendChild(document.createTextNode(file.extra));
extraLabel.appendTo(extraContainer);
extraContainer.appendTo(fileLabel);
}
if (file.hunks.length == 0)
return;
var lastHunk = file.hunks[file.hunks.length - 1];
var lastLine = Math.max(lastHunk.oldStart + lastHunk.oldCount - 1,
lastHunk.newStart + lastHunk.newCount - 1);
var tbody = Splinter.appendPatchTable(file.status, lastLine, fileDiv);
var i;
for (i = 0; i < file.hunks.length; i++) {
var hunk = file.hunks[i];
if (hunk.oldStart > 1) {
var hunkHeader = Splinter.EL("tr", "hunk-header");
tbody.appendChild(hunkHeader);
hunkHeader.appendChild(Splinter.EL("td")); // line number column
var hunkCell = Splinter.EL(
"td",
"hunk-cell",
"Lines " + hunk.oldStart + '-' +
Math.max(hunk.oldStart + hunk.oldCount - 1, hunk.newStart + hunk.newCount - 1) +
"\u00a0\u00a0" + hunk.functionLine
);
hunkCell.colSpan = file.status == Splinter.Patch.CHANGED ? 4 : 1;
hunkHeader.appendChild(hunkCell);
}
Splinter.appendPatchHunk(file, hunk, file.status, true, true, tbody);
}
};
Splinter.appendReviewComment = function (comment, parentDiv) {
var commentDiv = Splinter.EL("div", "review-patch-comment");
Event.addListener(commentDiv, 'click', function() {
Splinter.showPatchFile(comment.file.patchFile);
if (comment.file.review == Splinter.theReview) {
// Immediately start editing the comment again
var commentDivParent = Dom.getAncestorByClassName(comment.div, 'comment-area');
var commentArea = commentDivParent.getElementsByTagName('td')[0];
Splinter.insertCommentEditor(commentArea, comment.file.patchFile, comment.location, comment.type);
Splinter.scrollToElement(Dom.get('commentEditor'));
} else {
// Just scroll to the comment, don't start a reply yet
Splinter.scrollToElement(Dom.get(comment.div));
}
});
var inReplyTo = comment.getInReplyTo();
if (inReplyTo) {
var div = new Element(document.createElement('div'));
Dom.addClass(div, Splinter.getReviewerClass(inReplyTo.file.review));
div.appendTo(commentDiv);
var reviewerBox = new Element(document.createElement('div'));
Dom.addClass(reviewerBox, 'reviewer-box');
Splinter.Utils.preWrapLines(reviewerBox, inReplyTo.comment);
reviewerBox.appendTo(div);
var reviewPatchCommentText = new Element(document.createElement('div'));
Dom.addClass(reviewPatchCommentText, 'review-patch-comment-text');
Splinter.Utils.preWrapLines(reviewPatchCommentText, comment.comment);
reviewPatchCommentText.appendTo(commentDiv);
} else {
var hunk = comment.getHunk();
var lastLine = Math.max(hunk.oldStart + hunk.oldCount- 1,
hunk.newStart + hunk.newCount- 1);
var tbody = Splinter.appendPatchTable(comment.type, lastLine, commentDiv);
Splinter.appendPatchHunk(comment.file.patchFile, hunk, comment.type, false, false, tbody,
function(loc) {
return (loc <= comment.location && comment.location - loc < 5);
});
var tr = new Element(document.createElement('tr'));
var td = new Element(document.createElement('td'));
td.appendTo(tr);
td = new Element(document.createElement('td'));
Dom.addClass(td, 'review-patch-comment-text');
Splinter.Utils.preWrapLines(td, comment.comment);
td.appendTo(tr);
tr.appendTo(tbody);
}
parentDiv.appendChild(commentDiv);
};
Splinter.appendReviewComments = function (review, parentDiv) {
var i;
for (i = 0; i < review.files.length; i++) {
var file = review.files[i];
if (file.comments.length == 0) {
continue;
}
parentDiv.appendChild(Splinter.EL("div", "review-patch-file", file.patchFile.filename));
var firstComment = true;
var j;
for (j = 0; j < file.comments.length; j++) {
if (firstComment) {
firstComment = false;
} else {
parentDiv.appendChild(Splinter.EL("div", "review-patch-comment-separator"));
}
Splinter.appendReviewComment(file.comments[j], parentDiv);
}
}
};
Splinter.updateMyPatchComments = function () {
var myPatchComments = Dom.get("myPatchComments");
Splinter.replaceText(myPatchComments, '');
Splinter.appendReviewComments(Splinter.theReview, myPatchComments);
if (Dom.getChildren(myPatchComments).length > 0) {
Dom.setStyle(myPatchComments, 'display', 'block');
} else {
Dom.setStyle(myPatchComments, 'display', 'none');
}
};
Splinter.selectNavigationLink = function (identifier) {
var navigationLinks = Dom.getElementsByClassName('navigation-link');
var i;
for (i = 0; i < navigationLinks.length; i++) {
Dom.removeClass(navigationLinks[i], 'navigation-link-selected');
}
Dom.addClass(Splinter.navigationLinks[identifier], 'navigation-link-selected');
};
Splinter.addNavigationLink = function (identifier, title, callback, selected) {
var navigationDiv = Dom.get('navigation');
if (Dom.getChildren(navigationDiv).length > 0) {
navigationDiv.appendChild(document.createTextNode(' | '));
}
var navigationLink = new Element(document.createElement('a'));
Dom.addClass(navigationLink, 'navigation-link');
Dom.setAttribute(navigationLink, 'href', 'javascript:void(0);');
Dom.setAttribute(navigationLink, 'id', 'switch-' + encodeURIComponent(identifier));
Dom.setAttribute(navigationLink, 'title', identifier);
navigationLink.appendChild(document.createTextNode(title));
navigationLink.appendTo(navigationDiv);
// FIXME: Find out why I need to use an id here instead of just passing
// navigationLink to Event.addListener()
Event.addListener('switch-' + encodeURIComponent(identifier), 'click', function () {
if (!Dom.hasClass(this, 'navigation-link-selected')) {
callback();
}
});
if (selected) {
Dom.addClass(navigationLink, 'navigation-link-selected');
}
Splinter.navigationLinks[identifier] = navigationLink;
};
Splinter.showOverview = function () {
Splinter.selectNavigationLink('__OVERVIEW__');
Dom.setStyle('overview', 'display', 'block');
Dom.getElementsByClassName('file', 'div', '', function (node) {
Dom.setStyle(node, 'display', 'none');
});
if (!Splinter.readOnly)
Splinter.updateMyPatchComments();
};
Splinter.showAllFiles = function () {
Splinter.selectNavigationLink('__ALL__');
Dom.setStyle('overview', 'display', 'none');
Dom.setStyle('file-collapse-all', 'display', 'block');
var i;
for (i = 0; i < Splinter.thePatch.files.length; i++) {
var file = Splinter.thePatch.files[i];
if (!file.div) {
Splinter.addPatchFile(file);
} else {
Dom.setStyle(file.div, 'display', 'block');
}
}
}
Splinter.toggleCollapsed = function (filename, display) {
filename = decodeURIComponent(filename);
var i;
for (i = 0; i < Splinter.thePatch.files.length; i++) {
var file = Splinter.thePatch.files[i];
if (!filename || filename == file.filename) {
var fileTableContainer = file.div.getElementsByClassName('file-table-container')[0];
var fileExtraContainer = file.div.getElementsByClassName('file-extra-container')[0];
var fileCollapseLink = file.div.getElementsByClassName('file-label-collapse')[0];
if (!display) {
display = Dom.getStyle(fileTableContainer, 'display') == 'block' ? 'none' : 'block';
}
Dom.setStyle(fileTableContainer, 'display', display);
Dom.setStyle(fileExtraContainer, 'display', display);
Splinter.replaceText(fileCollapseLink, (display == 'block' ? '[-]' : '[+]'));
}
}
}
Splinter.toggleFileReviewed = function (filename) {
var checkbox = Dom.get('file-review-checkbox-' + filename);
if (checkbox) {
filename = decodeURIComponent(filename);
for (var i = 0; i < Splinter.thePatch.files.length; i++) {
var file = Splinter.thePatch.files[i];
if (file.filename == filename) {
file.fileReviewed = checkbox.checked;
Splinter.saveDraft();
Splinter.queueUpdateHaveDraft();
// Strike through file names to show review was completed
var fileNavLink = Dom.get('switch-' + encodeURIComponent(filename));
if (file.fileReviewed) {
Dom.addClass(fileNavLink, 'file-reviewed-nav');
}
else {
Dom.removeClass(fileNavLink, 'file-reviewed-nav');
}
}
}
}
}
Splinter.showPatchFile = function (file) {
Splinter.selectNavigationLink(file.filename);
Dom.setStyle('overview', 'display', 'none');
Dom.setStyle('file-collapse-all', 'display', 'none');
Dom.getElementsByClassName('file', 'div', '', function (node) {
Dom.setStyle(node, 'display', 'none');
});
if (file.div) {
Dom.setStyle(file.div, 'display', 'block');
} else {
Splinter.addPatchFile(file);
}
};
Splinter.addFileNavigationLink = function (file) {
var basename = file.filename.replace(/.*\//, "");
Splinter.addNavigationLink(file.filename, basename, function() {
Splinter.showPatchFile(file);
});
};
Splinter.start = function () {
Dom.setStyle('attachmentInfo', 'display', 'block');
Dom.setStyle('navigationContainer', 'display', 'block');
Dom.setStyle('overview', 'display', 'block');
Dom.setStyle('splinter-files', 'display', 'block');
Dom.setStyle('attachmentStatusSpan', 'display', 'none');
if (Splinter.thePatch.intro) {
Splinter.Utils.preWrapLines(Dom.get('patchIntro'), Splinter.thePatch.intro);
} else {
Dom.setStyle('patchIntro', 'display', 'none');
}
Splinter.addNavigationLink('__OVERVIEW__', "Overview", Splinter.showOverview, true);
Splinter.addNavigationLink('__ALL__', "All Files", Splinter.showAllFiles, false);
var i;
for (i = 0; i < Splinter.thePatch.files.length; i++) {
Splinter.addFileNavigationLink(Splinter.thePatch.files[i]);
}
var navigation = Dom.get('navigation');
var haveDraftNotice = new Element(document.createElement('div'));
Dom.setAttribute(haveDraftNotice, 'id', 'haveDraftNotice');
haveDraftNotice.appendChild(document.createTextNode('Draft'));
haveDraftNotice.appendTo(navigation);
var clear = new Element(document.createElement('div'));
Dom.addClass(clear, 'clear');
clear.appendTo(navigation);
var numReviewers = 0;
for (i = 0; i < Splinter.theBug.comments.length; i++) {
var comment = Splinter.theBug.comments[i];
var m = Splinter.Review.REVIEW_RE.exec(comment.text);
if (m && parseInt(m[1], 10) == Splinter.attachmentId) {
var review = new Splinter.Review.Review(Splinter.thePatch, comment.getWho(), comment.date);
review.parse(comment.text.substr(m[0].length));
var reviewerIndex;
if (review.who in Splinter.reviewers) {
reviewerIndex = Splinter.reviewers[review.who];
} else {
reviewerIndex = ++numReviewers;
Splinter.reviewers[review.who] = reviewerIndex;
}
var reviewDiv = new Element(document.createElement('div'));
Dom.addClass(reviewDiv, 'review');
Dom.addClass(reviewDiv, Splinter.getReviewerClass(review));
reviewDiv.appendTo(Dom.get('oldReviews'));
var reviewerBox = new Element(document.createElement('div'));
Dom.addClass(reviewerBox, 'reviewer-box');
reviewerBox.appendTo(reviewDiv);
var reviewer = new Element(document.createElement('div'));
Dom.addClass(reviewer, 'reviewer');
reviewer.appendChild(document.createTextNode(review.who));
reviewer.appendTo(reviewerBox);
var reviewDate = new Element(document.createElement('div'));
Dom.addClass(reviewDate, 'review-date');
reviewDate.appendChild(document.createTextNode(Splinter.Utils.formatDate(review.date)));
reviewDate.appendTo(reviewerBox);
var reviewInfoBottom = new Element(document.createElement('div'));
Dom.addClass(reviewInfoBottom, 'review-info-bottom');
reviewInfoBottom.appendTo(reviewerBox);
var reviewIntro = new Element(document.createElement('div'));
Dom.addClass(reviewIntro, 'review-intro');
Splinter.Utils.preWrapLines(reviewIntro, review.intro? review.intro : "");
reviewIntro.appendTo(reviewerBox);
Dom.setStyle('oldReviews', 'display', 'block');
Splinter.appendReviewComments(review, reviewerBox);
}
}
// We load the saved draft or create a new review *after* inserting the existing reviews
// so that the ordering comes out right.
if (Splinter.reviewStorage) {
Splinter.theReview = Splinter.reviewStorage.loadDraft(Splinter.theBug, Splinter.theAttachment, Splinter.thePatch);
if (Splinter.theReview) {
var storedReviews = Splinter.reviewStorage.listReviews();
Dom.setStyle('restored', 'display', 'block');
for (i = 0; i < storedReviews.length; i++) {
if (storedReviews[i].bugId == Splinter.theBug.id &&
storedReviews[i].attachmentId == Splinter.theAttachment.id)
{
Splinter.replaceText(Dom.get("restoredLastModified"), Splinter.Utils.formatDate(new Date(storedReviews[i].modificationTime)));
// Restore file reviewed checkboxes
if (storedReviews[i].filesReviewed) {
for (var j = 0; j < Splinter.thePatch.files.length; j++) {
var file = Splinter.thePatch.files[j];
if (storedReviews[i].filesReviewed[file.filename]) {
file.fileReviewed = true;
// Strike through file names to show that review was completed
var fileNavLink = Dom.get('switch-' + encodeURIComponent(file.filename));
Dom.addClass(fileNavLink, 'file-reviewed-nav');
}
}
}
}
}
}
}
if (!Splinter.theReview) {
Splinter.theReview = new Splinter.Review.Review(Splinter.thePatch);
}
if (Splinter.theReview.intro) {
Dom.setStyle('emptyCommentNotice', 'display', 'none');
}
if (!Splinter.readOnly) {
var myComment = Dom.get('myComment');
myComment.value = Splinter.theReview.intro ? Splinter.theReview.intro : "";
Event.addListener(myComment, 'focus', function () {
Dom.setStyle('emptyCommentNotice', 'display', 'none');
});
Event.addListener(myComment, 'blur', function () {
if (myComment.value == '') {
Dom.setStyle('emptyCommentNotice', 'display', 'block');
}
});
Event.addListener(myComment, 'keydown', function () {
Splinter.queueSaveDraft();
Splinter.queueUpdateHaveDraft();
});
Splinter.updateMyPatchComments();
Splinter.queueUpdateHaveDraft();
Event.addListener("publishButton", "click", Splinter.publishReview);
Event.addListener("cancelButton", "click", Splinter.discardReview);
} else {
Dom.setStyle('haveDraftNotice', 'display', 'none');
}
};
Splinter.newPageUrl = function (newBugId, newAttachmentId) {
var newUrl = Splinter.configBase;
if (newBugId != null) {
newUrl += (newUrl.indexOf("?") < 0) ? "?" : "&";
newUrl += "bug=" + escape("" + newBugId);
if (newAttachmentId != null) {
newUrl += "&attachment=" + escape("" + newAttachmentId);
}
}
return newUrl;
};
Splinter.showNote = function () {
var noteDiv = Dom.get("note");
if (noteDiv && Splinter.configNote) {
Splinter.replaceText(noteDiv, Splinter.configNote);
Dom.setStyle(noteDiv, 'display', 'block');
}
};
Splinter.showEnterBug = function () {
Splinter.showNote();
Event.addListener("enterBugGo", "click", function () {
var newBugId = Splinter.Utils.strip(Dom.get("enterBugInput").value);
document.location = Splinter.newPageUrl(newBugId);
});
Dom.setStyle('enterBug', 'display', 'block');
if (!Splinter.reviewStorage) {
return;
}
var storedReviews = Splinter.reviewStorage.listReviews();
if (storedReviews.length == 0) {
return;
}
var i;
var reviewData = [];
for (i = storedReviews.length - 1; i >= 0; i--) {
var reviewInfo = storedReviews[i];
var modificationDate = Splinter.Utils.formatDate(new Date(reviewInfo.modificationTime));
var extra = reviewInfo.isDraft ? "(draft)" : "";
reviewData.push([
reviewInfo.bugId,
reviewInfo.bugId + ":" + reviewInfo.attachmentId,
reviewInfo.attachmentDescription,
modificationDate,
extra
]);
}
var attachLink = function (elLiner, oRecord, oColumn, oData) {
var splitResult = oData.split(':', 2);
elLiner.innerHTML = "<a href=\"" + Splinter.newPageUrl(splitResult[0], splitResult[1]) +
"\">" + splitResult[1] + "</a>";
};
var bugLink = function (elLiner, oRecord, oColumn, oData) {
elLiner.innerHTML = "<a href=\"" + Splinter.newPageUrl(oData) +
"\">" + oData + "</a>";
};
var attachDesc = function (elLiner, oRecord, oColumn, oData) {
Splinter.replaceText(elLiner, oData);
};
dsConfig = {
responseType: YAHOO.util.DataSource.TYPE_JSARRAY,
responseSchema: { fields:["bug_id","attachment_id", "description", "date", "extra"] }
};
var columnDefs = [
{ key: "bug_id", label: "Bug", formatter: bugLink },
{ key: "attachment_id", label: "Attachment", formatter: attachLink },
{ key: "description", label: "Description", formatter: attachDesc },
{ key: "date", label: "Date" },
{ key: "extra", label: "Extra" }
];
var dataSource = new YAHOO.util.LocalDataSource(reviewData, dsConfig);
var dataTable = new YAHOO.widget.DataTable("chooseReviewTable", columnDefs, dataSource);
Dom.setStyle('chooseReview', 'display', 'block');
};
Splinter.showChooseAttachment = function () {
var drafts = {};
var published = {};
if (Splinter.reviewStorage) {
var storedReviews = Splinter.reviewStorage.listReviews();
var j;
for (j = 0; j < storedReviews.length; j++) {
var reviewInfo = storedReviews[j];
if (reviewInfo.bugId == Splinter.theBug.id) {
if (reviewInfo.isDraft) {
drafts[reviewInfo.attachmentId] = 1;
} else {
published[reviewInfo.attachmentId] = 1;
}
}
}
}
var attachData = [];
var i;
for (i = 0; i < Splinter.theBug.attachments.length; i++) {
var attachment = Splinter.theBug.attachments[i];
if (!attachment.isPatch || attachment.isObsolete) {
continue;
}
var href = Splinter.newPageUrl(Splinter.theBug.id, attachment.id);
var date = Splinter.Utils.formatDate(attachment.date);
var status = (attachment.status && attachment.status != 'none') ? attachment.status : '';
var extra = '';
if (attachment.id in drafts) {
extra = '(draft)';
} else if (attachment.id in published) {
extra = '(published)';
}
attachData.push([ attachment.id, attachment.description, attachment.date, extra ]);
}
var attachLink = function (elLiner, oRecord, oColumn, oData) {
elLiner.innerHTML = "<a href=\"" + Splinter.newPageUrl(Splinter.theBug.id, oData) +
"\">" + oData + "</a>";
};
var attachDesc = function (elLiner, oRecord, oColumn, oData) {
Splinter.replaceText(elLiner, oData);
};
dsConfig = {
responseType: YAHOO.util.DataSource.TYPE_JSARRAY,
responseSchema: { fields:["id","description","date", "extra"] }
};
var columnDefs = [
{ key: "id", label: "ID", formatter: attachLink },
{ key: "description", label: "Description", formatter: attachDesc },
{ key: "date", label: "Date" },
{ key: "extra", label: "Extra" }
];
var dataSource = new YAHOO.util.LocalDataSource(attachData, dsConfig);
var dataTable = new YAHOO.widget.DataTable("chooseAttachmentTable", columnDefs, dataSource);
Dom.setStyle('chooseAttachment', 'display', 'block');
};
Splinter.quickHelpToggle = function () {
var quickHelpShow = Dom.get('quickHelpShow');
var quickHelpContent = Dom.get('quickHelpContent');
var quickHelpToggle = Dom.get('quickHelpToggle');
if (quickHelpContent.style.display == 'none') {
quickHelpContent.style.display = 'block';
quickHelpShow.style.display = 'none';
} else {
quickHelpContent.style.display = 'none';
quickHelpShow.style.display = 'block';
}
};
Splinter.init = function () {
Splinter.showNote();
if (Splinter.ReviewStorage.LocalReviewStorage.available()) {
Splinter.reviewStorage = new Splinter.ReviewStorage.LocalReviewStorage();
}
if (Splinter.theBug == null) {
Splinter.showEnterBug();
return;
}
Splinter.replaceText(Dom.get("bugId"), Splinter.theBug.id);
Dom.get("bugLink").setAttribute('href', Splinter.configBugUrl + "show_bug.cgi?id=" + Splinter.theBug.id);
Splinter.replaceText(Dom.get("bugShortDesc"), Splinter.theBug.shortDesc);
Splinter.replaceText(Dom.get("bugReporter"), Splinter.theBug.getReporter());
Splinter.replaceText(Dom.get("bugCreationDate"), Splinter.Utils.formatDate(Splinter.theBug.creationDate));
Dom.setStyle('bugInfo', 'display', 'block');
if (Splinter.attachmentId) {
Splinter.theAttachment = Splinter.theBug.getAttachment(Splinter.attachmentId);
if (Splinter.theAttachment == null) {
Splinter.displayError("Attachment " + Splinter.attachmentId + " is not an attachment to bug " + Splinter.theBug.id);
}
else if (!Splinter.theAttachment.isPatch) {
Splinter.displayError("Attachment " + Splinter.attachmentId + " is not a patch");
Splinter.theAttachment = null;
}
}
if (Splinter.theAttachment == null) {
Splinter.showChooseAttachment();
} else {
Splinter.replaceText(Dom.get("attachId"), Splinter.theAttachment.id);
Dom.get("attachLink").setAttribute('href', Splinter.configBugUrl + "attachment.cgi?id=" + Splinter.theAttachment.id);
Splinter.replaceText(Dom.get("attachDesc"), Splinter.theAttachment.description);
Splinter.replaceText(Dom.get("attachCreator"), Splinter.Bug._formatWho(Splinter.theAttachment.whoName, Splinter.theAttachment.whoEmail));
Splinter.replaceText(Dom.get("attachDate"), Splinter.Utils.formatDate(Splinter.theAttachment.date));
Splinter.replaceText(Dom.get("attachComment"), Splinter.attachmentComment);
var warnings = [];
if (Splinter.theAttachment.isObsolete)
warnings.push('OBSOLETE');
if (Splinter.theAttachment.isCRLF)
warnings.push('WINDOWS PATCH');
if (warnings.length > 0)
Splinter.replaceText(Dom.get("attachWarning"), warnings.join(', '));
Dom.setStyle('attachInfo', 'display', 'block');
Dom.setStyle('quickHelpShow', 'display', 'block');
document.title = "Patch Review of Attachment " + Splinter.theAttachment.id +
" for Bug " + Splinter.theBug.id;
Splinter.thePatch = new Splinter.Patch.Patch(Splinter.theAttachment.data);
if (Splinter.thePatch != null) {
Splinter.start();
}
}
};
YAHOO.util.Event.addListener(window, 'load', Splinter.init);
<file_sep>/js/instant-search.js
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0. */
var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
Event.onDOMReady(function() {
YAHOO.bugzilla.instantSearch.onInit();
if (YAHOO.bugzilla.instantSearch.getContent().length >= 4) {
YAHOO.bugzilla.instantSearch.doSearch(YAHOO.bugzilla.instantSearch.getContent());
} else {
YAHOO.bugzilla.instantSearch.reset();
}
Dom.get('content').focus();
});
YAHOO.bugzilla.instantSearch = {
counter: 0,
dataTable: null,
dataTableColumns: null,
elContent: null,
elList: null,
currentSearchQuery: '',
currentSearchProduct: '',
onInit: function() {
YAHOO.util.Connect.setDefaultPostHeader('application/json; charset=UTF-8');
this.elContent = Dom.get('content');
this.elList = Dom.get('results');
Event.addListener(this.elContent, 'keyup', this.onContentKeyUp);
Event.addListener(Dom.get('product'), 'change', this.onProductChange);
},
setLabels: function(labels) {
this.dataTableColumns = [
{ key: "id", label: labels.id, formatter: this.formatId },
{ key: "summary", label: labels.summary, formatter: "text" },
{ key: "component", label: labels.component, formatter: "text" },
{ key: "status", label: labels.status, formatter: this.formatStatus },
];
},
initDataTable: function() {
var dataSource = new YAHOO.util.XHRDataSource("jsonrpc.cgi");
dataSource.connTimeout = 15000;
dataSource.connMethodPost = true;
dataSource.connXhrMode = "cancelStaleRequests";
dataSource.maxCacheEntries = 3;
dataSource.responseSchema = {
resultsList : "result.bugs",
metaFields : { error: "error", jsonRpcId: "id" }
};
// DataSource can't understand a JSON-RPC error response, so
// we have to modify the result data if we get one.
dataSource.doBeforeParseData =
function(oRequest, oFullResponse, oCallback) {
if (oFullResponse.error) {
oFullResponse.result = {};
oFullResponse.result.bugs = [];
if (console)
console.error("JSON-RPC error:", oFullResponse.error);
}
return oFullResponse;
};
dataSource.subscribe('dataErrorEvent',
function() {
YAHOO.bugzilla.instantSearch.currentSearchQuery = '';
}
);
this.dataTable = new YAHOO.widget.DataTable(
'results',
this.dataTableColumns,
dataSource,
{
initialLoad: false,
MSG_EMPTY: 'No matching bugs found.',
MSG_ERROR: 'An error occurred while searching for bugs, please try again.'
}
);
},
formatId: function(el, oRecord, oColumn, oData) {
el.innerHTML = '<a href="show_bug.cgi?id=' + oData + '" target="_blank">' + oData + '</a>';
},
formatStatus: function(el, oRecord, oColumn, oData) {
var resolution = oRecord.getData('resolution');
var bugStatus = display_value('bug_status', oData);
if (resolution) {
el.innerHTML = bugStatus + ' ' + display_value('resolution', resolution);
} else {
el.innerHTML = bugStatus;
}
},
reset: function() {
Dom.addClass(this.elList, 'hidden');
this.elList.innerHTML = '';
this.currentSearchQuery = '';
this.currentSearchProduct = '';
},
onContentKeyUp: function(e) {
clearTimeout(YAHOO.bugzilla.instantSearch.lastTimeout);
YAHOO.bugzilla.instantSearch.lastTimeout = setTimeout(function() {
YAHOO.bugzilla.instantSearch.doSearch(YAHOO.bugzilla.instantSearch.getContent()) },
600);
},
onProductChange: function(e) {
YAHOO.bugzilla.instantSearch.doSearch(YAHOO.bugzilla.instantSearch.getContent());
},
doSearch: function(query) {
if (query.length < 4)
return;
// don't query if we already have the results (or they are pending)
var product = Dom.get('product').value;
if (YAHOO.bugzilla.instantSearch.currentSearchQuery == query &&
YAHOO.bugzilla.instantSearch.currentSearchProduct == product)
return;
YAHOO.bugzilla.instantSearch.currentSearchQuery = query;
YAHOO.bugzilla.instantSearch.currentSearchProduct = product;
// initialise the datatable as late as possible
YAHOO.bugzilla.instantSearch.initDataTable();
try {
// run the search
Dom.removeClass(YAHOO.bugzilla.instantSearch.elList, 'hidden');
YAHOO.bugzilla.instantSearch.dataTable.showTableMessage(
'Searching... ' +
'<img src="extensions/GuidedBugEntry/web/images/throbber.gif"' +
' width="16" height="11">',
YAHOO.widget.DataTable.CLASS_LOADING
);
var jsonObject = {
version: "1.1",
method: "Bug.possible_duplicates",
id: ++YAHOO.bugzilla.instantSearch.counter,
params: {
product: YAHOO.bugzilla.instantSearch.getProduct(),
summary: query,
limit: 20,
include_fields: [ "id", "summary", "status", "resolution", "component" ],
Bugzilla_api_token : (BUGZILLA.api_token ? BUGZILLA.api_token : '')
}
};
YAHOO.bugzilla.instantSearch.dataTable.getDataSource().sendRequest(
YAHOO.lang.JSON.stringify(jsonObject),
{
success: YAHOO.bugzilla.instantSearch.onSearchResults,
failure: YAHOO.bugzilla.instantSearch.onSearchResults,
scope: YAHOO.bugzilla.instantSearch.dataTable,
argument: YAHOO.bugzilla.instantSearch.dataTable.getState()
}
);
} catch(err) {
if (console)
console.error(err.message);
}
},
onSearchResults: function(sRequest, oResponse, oPayload) {
YAHOO.bugzilla.instantSearch.dataTable.onDataReturnInitializeTable(sRequest, oResponse, oPayload);
},
getContent: function() {
var content = YAHOO.lang.trim(this.elContent.value);
// work around chrome bug
if (content == YAHOO.bugzilla.instantSearch.elContent.getAttribute('placeholder')) {
return '';
} else {
return content;
}
},
getProduct: function() {
var result = [];
var name = Dom.get('product').value;
result.push(name);
if (products[name] && products[name].related) {
for (var i = 0, n = products[name].related.length; i < n; i++) {
result.push(products[name].related[i]);
}
}
return result;
}
};
<file_sep>/extensions/Push/web/admin.js
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0. */
var Dom = YAHOO.util.Dom;
function toggle_options(visible, name) {
var rows = Dom.getElementsByClassName(name + '_tr');
for (var i = 0, l = rows.length; i < l; i++) {
if (visible) {
Dom.removeClass(rows[i], 'hidden');
} else {
Dom.addClass(rows[i], 'hidden');
}
}
}
function reset_to_defaults() {
if (!push_defaults) return;
for (var id in push_defaults) {
var el = Dom.get(id);
if (!el) continue;
if (el.nodeName == 'INPUT') {
el.value = push_defaults[id];
} else if (el.nodeName == 'SELECT') {
for (var i = 0, l = el.options.length; i < l; i++) {
if (el.options[i].value == push_defaults[id]) {
el.options[i].selected = true;
break;
}
}
}
}
}
|
147682d900db5be4834f9bc8b5a4af6eeff8a2d5
|
[
"JavaScript",
"reStructuredText"
] | 18
|
JavaScript
|
yupitsme0/bmo
|
806f97062f7b45516d7b564b5f943d7353cbd946
|
f5bbe2a65c74fcb88ca2a2b26865d3a51a74d3f6
|
refs/heads/master
|
<file_sep>GO := go
pkgs = $(shell $(GO) list ./...)
all: format build test
test:
@echo ">> running tests"
@$(GO) test $(pkgs) -cover
bench:
@echo ">> running benchmarks"
@$(GO) test $(pkgs) -bench=.
vtest:
@echo ">> running verbose tests"
@$(GO) test $(pkgs) -v -chatty
format:
@echo ">> formatting code"
@$(GO) fmt $(pkgs)
vet:
@echo ">> vetting code"
@$(GO) vet $(pkgs)
build:
@echo ">> building binaries"
@$(GO) build $(pkgs)
.PHONY: all test bench vtest format vet build
<file_sep># A very thin functional reactive programming layer over Go's CSP primitives
Disclaimer: I just wanted to write an Rx-Layer for Go. I don't think that you need an abstraction like this in Go code. Even though I tried to make it as idiomatic as possible. I still think, that the implementation is interesting (to read), but if you want to use or extend this code, you are on your own. No bugfixes or pull requests. Use at your own risk.
```go
package daisychain
import "fmt"
func Example() {
//Create an Observable that emits 0..9 ints
o1 := Create(
Just(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
)
//Create another Observable by composition
o2 := Create(
// o1 emits 0..9!
o1,
// map adds 1 to each number
Map(func(ev Event) Event {
return ev.(int) + 1
}),
// skips 1..5
Skip(5),
// takes 6,7,8
Take(3),
// filters even numbers: 6,8
Filter(func(ev Event) bool {
return ev.(int)%2 == 0
}),
// sums 6 and 8
Reduce(func(ev1, ev2 Event) Event {
return ev1.(int) + ev2.(int)
}, 0),
)
//Subscribe to an Observable to execute it
SubscribeAndWait(o2, nil /*onNext*/, nil /*onError*/, onComplete)
//Output:
// 14
}
func onComplete(ev Event) {
fmt.Println(ev)
}
```
<file_sep>package daisychain
import (
"fmt"
"sync"
"time"
)
var Trace bool = false
var TRACE = func(prefix string, ev Event) {
//set var Trace=true
}
func trace() {
if !Trace {
return
}
var seq int
TRACE = func(prefix string, ev Event) {
fmt.Printf("%s: %d -> %s, %#v, (type:%T)\n", time.Now(), seq, prefix, ev, ev)
seq++
}
}
type Event interface{}
// CompleteEvent indicates that no more Events will be send.
type CompleteEvent struct {
Event
}
// Complete creates a new Event of type CompleteEvent.
func Complete() Event {
return CompleteEvent{}
}
// IsCompleteEvent returns true if ev is a CompleteEvent.
func IsCompleteEvent(ev Event) bool {
_, isCompleteEvent := ev.(CompleteEvent)
return isCompleteEvent
}
// IsErrorEvent returns true if ev is a CompleteEvent.
func IsErrorEvent(ev Event) bool {
_, isErrorEvent := ev.(ErrorEvent)
return isErrorEvent
}
// ErrorEvent indicates an Error.
type ErrorEvent struct {
Event
msg string
}
// Error creates a new Event of type ErrorEvent.
func Error(msg string) Event {
return ErrorEvent{msg: msg}
}
type Observable interface {
Observe(Observer)
}
type ObservableFunc func(Observer)
// Observe method implements the Observable interface on the fly.
func (o ObservableFunc) Observe(obs Observer) {
o(obs)
}
type Observer interface {
Next(ev Event)
}
type ObserverFunc func(Event)
// Next method implements the Observer interface on the fly.
func (o ObserverFunc) Next(ev Event) {
o(ev)
}
type Operator func(Observable) Observable
type MapFunc func(Event) Event
func Map(mapfn MapFunc) Operator {
return OperatorFunc(func(obs Observer, cur, last Event) Event {
var next Event
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(cur)
} else {
next = mapfn(cur)
obs.Next(next)
}
return next
}, "Map()", nil)
}
type FlatMapFunc func(ev Event) Observable
func FlatMap(flatmapfn FlatMapFunc) Operator {
var wg sync.WaitGroup
return OperatorFunc(func(obs Observer, cur, last Event) Event {
var next Event
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
TRACE("FlatMap()", "WAITING...")
wg.Wait()
obs.Next(cur)
} else {
TRACE("FlatMap()", "SPAWNING")
wg.Add(1)
o := flatmapfn(cur)
onNext := func(ev Event) {
next = ev
obs.Next(next)
}
onEvent := func(ev Event) {
TRACE("FlatMap()", "DONE")
wg.Done()
}
Subscribe(o, onNext, onEvent, onEvent)
}
return next
}, "FlatMap()", nil)
}
type ReduceFunc func(left, right Event) Event
func Scan(reducefn ReduceFunc, init Event) Operator {
return OperatorFunc(func(obs Observer, cur, last Event) Event {
var next Event
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(cur)
} else {
next = reducefn(last, cur)
obs.Next(next)
}
return next
}, "Scan()", init)
}
func Reduce(reducefn ReduceFunc, init Event) Operator {
return OperatorFunc(func(obs Observer, cur, last Event) Event {
var next Event
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(last)
obs.Next(cur)
} else {
next = reducefn(last, cur)
}
return next
}, "Reduce()", init)
}
func Skip(n int) Operator {
var count int
return OperatorFunc(func(obs Observer, cur, last Event) Event {
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(cur)
} else {
if count == n {
obs.Next(cur)
} else {
count += 1
}
}
return cur
}, "Skip()", nil)
}
func Take(n int) Operator {
var count int
return OperatorFunc(func(obs Observer, cur, last Event) Event {
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(cur)
} else {
if count < n {
obs.Next(cur)
count += 1
}
}
return cur
}, "Take()", nil)
}
type FilterFunc func(Event) bool
func Filter(filterfn FilterFunc) Operator {
return OperatorFunc(func(obs Observer, cur, last Event) Event {
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(cur)
} else {
if ok := filterfn(cur); ok {
obs.Next(cur)
}
}
return cur
}, "Filter()", nil)
}
// ToVector collects all events until Complete and the returns an Event
// that can be cast to []Event containing all collected events.
func ToVector() Operator {
var events []Event
return OperatorFunc(func(obs Observer, cur, _ Event) Event {
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(events)
obs.Next(cur)
} else {
events = append(events, cur)
}
return cur
}, "ToVector()", nil)
}
type KeyFunc func(ev Event) string
// ToMap collects all events until Complete and the returns an Event
// that can be cast to map[string][]Event containing all collected events
// grouped by the result of KeyFunc.
func ToMap(keyfn KeyFunc) Operator {
events := make(map[string][]Event)
return OperatorFunc(func(obs Observer, cur, _ Event) Event {
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(events)
obs.Next(cur)
} else {
key := keyfn(cur)
events[key] = append(events[key], cur)
}
return cur
}, "ToMap()", nil)
}
// Distinct emits each event only the first time it occurs based on the
// result of KeyFunc. Two events are equal, if KeyFunc returns the same
// result for them.
func Distinct(keyfn KeyFunc) Operator {
seen := make(map[string]struct{})
return OperatorFunc(func(obs Observer, cur, last Event) Event {
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(cur)
} else {
key := keyfn(cur)
if _, exists := seen[key]; !exists {
obs.Next(cur)
seen[key] = struct{}{}
}
}
return cur
}, "Distinct()", nil)
}
func Count() Operator {
var counter int64
return OperatorFunc(func(obs Observer, cur, _ Event) Event {
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(counter)
obs.Next(cur)
} else {
counter++
}
return cur
}, "Count()", nil)
}
type ZipFunc func(evs ...Event) Event
// Zip works ONLY, if all event streams emit the same number of events
func Zip(zipfunc ZipFunc, oo ...Observable) Operator {
var receiver []chan Event
var onNext, onEnd func(ev Event)
for _, o := range oo {
output := make(chan Event)
onNext = func(ev Event) {
output <- ev
}
onEnd = func(ev Event) {
//output <- ev //FIXME(SR): Always post last ev?
close(output)
}
receiver = append(receiver, output)
Subscribe(o, onNext, onEnd, onEnd)
}
realize := func(receiver ...chan Event) []Event {
var result []Event
for _, r := range receiver {
result = append(result, func() Event { return <-r }())
}
return result
}
return OperatorFunc(func(obs Observer, cur, _ Event) Event {
head := []Event{cur}
tail := realize(receiver...)
args := append(head, tail...)
for _, a := range args {
if IsCompleteEvent(a) || IsErrorEvent(a) {
obs.Next(Complete())
return cur
}
}
obs.Next(zipfunc(args...))
return cur
}, "Zip()", nil)
}
type DebugFunc func(obs Observer, cur, last Event)
func Debug(debugfn DebugFunc) Operator {
return OperatorFunc(func(obs Observer, cur, last Event) Event {
debugfn(obs, cur, last)
obs.Next(cur)
return cur
}, "DEBUG()", nil)
}
type BodyFunc func(obs Observer, cur, last Event) Event
func OperatorFunc(do BodyFunc, name string, init Event) Operator {
return func(o Observable) Observable {
return ObservableFunc(func(obs Observer) {
input := make(chan Event, 10)
//FIXME(SR): Buffering is needed to make Zip() work...
//input := make(chan Event)
msg := fmt.Sprintf("Opening channel for %s", name)
TRACE(msg, input)
go func() {
last := init
TRACE("Starting", name)
for ev := range input {
last = do(obs, ev, last)
TRACE(name, last)
}
TRACE("Closing", name)
}()
o.Observe(ObserverFunc(func(ev Event) {
TRACE("EVENT", ev)
input <- ev
//if IsCompleteEvent(ev) || IsErrorEvent(ev) {
if IsCompleteEvent(ev) { //FIXME(SR): Is there always a complete after an error?
TRACE("Closing channel", input)
close(input)
}
}))
})
}
}
func closeIfOpen(input chan Event) {
if input != nil {
close(input)
}
}
func callIfNotNil(onEvent ObserverFunc, ev Event) {
if onEvent != nil {
onEvent(ev)
}
}
func Subscribe(o Observable, onNext, onError, onComplete ObserverFunc) {
trace()
var last Event
o.Observe(ObserverFunc(func(ev Event) {
TRACE("Subscribe:", ev)
switch ev.(type) {
case CompleteEvent:
callIfNotNil(onComplete, last)
case ErrorEvent:
callIfNotNil(onError, ev)
default:
last = ev
callIfNotNil(onNext, ev)
}
}))
}
func SubscribeAndWait(o Observable, onNext, onError, onComplete ObserverFunc) {
trace()
var wg sync.WaitGroup
var last Event
wg.Add(1)
o.Observe(ObserverFunc(func(ev Event) {
TRACE("SubscribeAndWait:", ev)
switch ev.(type) {
case CompleteEvent:
callIfNotNil(onComplete, last)
wg.Done()
case ErrorEvent:
callIfNotNil(onError, ev)
default:
last = ev
callIfNotNil(onNext, ev)
}
}))
wg.Wait()
}
func Cache(o Observable) Observable {
var evts []Event
oo := Create(
o,
ToVector(),
)
onComplete := func(ev Event) {
evts = ev.([]Event)
}
SubscribeAndWait(oo, nil, nil, onComplete)
return ObservableFunc(func(obs Observer) {
evts := evts
for _, ev := range evts {
obs.Next(ev)
}
obs.Next(Complete())
})
}
func build(o Observable, ops ...Operator) Observable {
var chained Observable = o
for _, op := range ops {
chained = op(chained)
}
return chained
}
func Create(o Observable, ops ...Operator) Observable {
TRACE("Create", o)
return build(o, ops...)
}
func Just(evts ...Event) Observable {
return ObservableFunc(func(obs Observer) {
for _, ev := range evts {
TRACE("Just", ev)
obs.Next(ev)
}
obs.Next(Complete())
})
}
func From(evts ...Event) Observable {
return ObservableFunc(func(obs Observer) {
for _, ev := range evts {
TRACE("From", ev)
obs.Next(ev)
}
})
}
func Empty() Observable {
return ObservableFunc(func(obs Observer) {
obs.Next(Complete())
})
}
<file_sep>package daisychain
import (
"flag"
"math/rand"
"testing"
"time"
)
var CHATTY = func() (result bool) {
flag.BoolVar(&result, "chatty", false, "For more debug output use -chatty")
flag.Parse()
return
}()
func debug(t *testing.T) {
if !CHATTY {
return
}
var seq int
TRACE = func(prefix string, ev Event) {
t.Logf("%s: %d -> %s, \t%v, \t%T", time.Now(), seq, prefix, ev, ev)
seq++
}
}
func print(t *testing.T, prefix string) func(Event) {
return func(ev Event) {
t.Logf("%s: %#v (%T)", prefix, ev, ev)
}
}
type obj struct {
v int
}
func (this obj) add(other obj) obj {
return obj{this.v + other.v}
}
var testNils []Event = []Event{nil, nil, nil}
var testNumbers []Event = []Event{0, 1, 2, 3, 4, 5}
var testStrings []Event = []Event{"a", "b", "c", "d", "e", "f"}
var testObjects []Event = []Event{obj{0}, obj{1}, obj{2}}
func randMillies() int {
return rand.Intn(10)
}
func randSleep() {
time.Sleep(time.Duration(randMillies() * int(time.Millisecond)))
}
func TestStresstest(t *testing.T) {
t.Skip("Slow test...")
ints := make(chan int)
go func() {
for i := 0; i < 1000; i++ {
ints <- i
}
close(ints)
}()
o := Create(
ObservableFunc(func(obs Observer) {
for i := range ints {
obs.Next(i)
}
obs.Next(Complete())
}),
Map(func(ev Event) Event {
randSleep()
return ev
}),
Scan(func(left, right Event) Event {
randSleep()
return left.(int) + 1
}, 0),
FlatMap(func(ev Event) Observable {
return Just(ev)
}),
Reduce(func(left, right Event) Event {
randSleep()
return left.(int) + 1
}, 0),
)
SubscribeAndWait(o, nil, nil, func(ev Event) {
t.Log(ev.(int))
})
}
func TestAnon(t *testing.T) {
var item struct {
foo string
bar string
}
o := Create(
ObservableFunc(func(obs Observer) {
item.foo = "foo"
item.bar = "bar"
obs.Next(item)
obs.Next(Complete())
}),
)
SubscribeAndWait(o, nil, nil, func(ev Event) {
if s, ok := ev.(struct {
foo string
bar string
}); !ok {
t.Errorf("Expected: %#v, Got: %#v (%T)", ev, s, s)
}
})
}
func TestEmpty(t *testing.T) {
SubscribeAndWait(Empty(), nil, nil, func(ev Event) {
if ev != nil {
t.Error("Expected: nil, Got:", ev)
}
})
}
func TestMap(t *testing.T) {
debug(t)
var tests = []struct {
input []Event
mapfn MapFunc
check func(ev Event)
}{
{
testNils,
func(ev Event) Event {
if _, ok := ev.(int); !ok {
return nil
}
return 999
},
func(ev Event) {
if ev != nil {
t.Error("Expected: nil, Got:", ev)
}
},
},
{
testNumbers,
func(ev Event) Event { return ev.(int) * 2 },
func(ev Event) {
if n, ok := ev.(int); !(ok && n == 10) {
t.Error("Expected: 10, Got:", n)
}
},
},
{
testStrings,
func(ev Event) Event { return ev.(string) + "oo" },
func(ev Event) {
if s, ok := ev.(string); !(ok && s == "foo") {
t.Error("Expected: foo, Got:", s)
}
},
},
{
testObjects,
func(ev Event) Event { return obj{ev.(obj).v + 1000} },
func(ev Event) {
if o, ok := ev.(obj); !(ok && o.v == 1002) {
t.Error("Expected: 1002, Got:", o.v)
}
},
},
}
for _, test := range tests {
o := Create(
Just(test.input...),
Map(test.mapfn),
)
SubscribeAndWait(o, nil, nil, func(ev Event) {
test.check(ev)
})
}
}
func TestScan(t *testing.T) {
debug(t)
var tests = []struct {
input []Event
reducefn ReduceFunc
init Event
check func(ev Event)
}{
{
testNils,
func(ev1, ev2 Event) Event {
if _, ok := ev1.(int); !ok {
return nil
}
return 999
},
nil,
func(ev Event) {
if ev != nil {
t.Error("Expected: nil, Got:", ev)
}
},
},
{
testNumbers,
func(ev1, ev2 Event) Event { return ev1.(int) + ev2.(int) },
0,
func(ev Event) {
if n, ok := ev.(int); !(ok && n == 15) {
t.Error("Expected: 15, Got:", n)
}
},
},
{
testStrings,
func(ev1, ev2 Event) Event { return ev1.(string) + ev2.(string) },
"",
func(ev Event) {
if s, ok := ev.(string); !(ok && s == "abcdef") {
t.Error("Expected: abcdef, Got:", s)
}
},
},
{
testObjects,
func(ev1, ev2 Event) Event { return ev1.(obj).add(ev2.(obj)) },
obj{},
func(ev Event) {
if o, ok := ev.(obj); !(ok && o.v == 3) {
t.Error("Expected: 6, Got:", o.v)
}
},
},
}
for _, test := range tests {
o := Create(
Just(test.input...),
Scan(test.reducefn, test.init),
)
SubscribeAndWait(o, nil, nil, func(ev Event) {
test.check(ev)
})
}
}
func TestFlatMap(t *testing.T) {
debug(t)
o := Create(
Just(1, 2, 3, 4, 5),
FlatMap(func(ev Event) Observable {
randSleep()
return Create(
Just(ev, ev),
)
}),
Reduce(func(ev1, ev2 Event) Event {
return ev1.(int) + ev2.(int)
}, 0),
)
SubscribeAndWait(o, print(t, "Next"), print(t, "Error"), func(ev Event) {
if n, ok := ev.(int); !(ok && n == 30) {
t.Error("Expected: 30, Got:", n)
}
})
}
func TestSkip(t *testing.T) {
debug(t)
o := Create(
Just(1, 2, 3, 4, 5),
Skip(3),
Reduce(func(ev1, ev2 Event) Event {
return ev1.(int) + ev2.(int)
}, 0),
)
SubscribeAndWait(o, print(t, "Next"), print(t, "Error"), func(ev Event) {
if n, ok := ev.(int); !(ok && n == 9) {
t.Error("Expected: 9, Got:", n)
}
})
}
func TestTake(t *testing.T) {
debug(t)
o := Create(
Just(1, 2, 3, 4, 5),
Take(3),
Reduce(func(ev1, ev2 Event) Event {
return ev1.(int) + ev2.(int)
}, 0),
)
SubscribeAndWait(o, print(t, "Next"), print(t, "Error"), func(ev Event) {
if n, ok := ev.(int); !(ok && n == 6) {
t.Error("Expected: 6, Got:", n)
}
})
}
func TestToVector(t *testing.T) {
debug(t)
o := Create(
Just(1, 2, 3, 4, 5),
ToVector(),
)
SubscribeAndWait(o, print(t, "Next"), print(t, "Error"), func(ev Event) {
if n, ok := ev.([]Event); !(ok && len(n) == 5) {
t.Error("Expected: 5, Got:", n)
}
})
}
func TestToMap(t *testing.T) {
debug(t)
o := Create(
Just(1, 2, 3, 4, 5),
ToMap(func(ev Event) string {
if ev.(int)%2 == 0 {
return "even"
}
return "odd"
}),
)
SubscribeAndWait(o, print(t, "Next"), print(t, "Error"), func(ev Event) {
if n, ok := ev.(map[string][]Event); !(ok && len(n) == 2) {
t.Error("Expected: 2, Got:", n)
}
})
}
func TestDistinctAndCount(t *testing.T) {
debug(t)
o := Create(
Just("a", "b", "a", "b", "c"),
Distinct(func(ev Event) string {
return ev.(string)
}),
Count(),
)
SubscribeAndWait(o, print(t, "Next"), print(t, "Error"), func(ev Event) {
if n, ok := ev.(int64); !(ok && n == 3) {
t.Error("Expected: 3, Got:", n)
}
})
}
func TestMapInternals(t *testing.T) {
input := ObservableFunc(func(obs Observer) {
obs.Next(1)
obs.Next(2)
obs.Next(3)
obs.Next(Complete())
})
mapOp := Map(func(ev Event) Event {
return ev.(int) * 10
})
output := mapOp(input)
SubscribeAndWait(output, func(ev Event) {
t.Log(ev)
}, nil, nil)
}
func TestZipInternals(t *testing.T) {
input := ObservableFunc(func(obs Observer) {
obs.Next(1)
obs.Next(2)
obs.Next(3)
obs.Next(Complete())
})
zipOp := Zip(func(evs ...Event) Event {
return evs[0].(int)
})
output := zipOp(input)
SubscribeAndWait(output, func(ev Event) {
t.Log(ev)
}, nil, nil)
}
func TestZip(t *testing.T) {
debug(t)
o1 := Create(
Just(1, 2, 3),
Map(func(ev Event) Event {
return ev
}),
)
o2 := Create(
Just(4, 5, 6),
Map(func(ev Event) Event {
return ev
}),
)
o := Create(
Just(10, 20, 30),
Zip(func(evs ...Event) Event {
var sum int
for _, ev := range evs {
sum += ev.(int)
}
return sum
}, o1, o2),
Scan(func(ev1, ev2 Event) Event {
return ev1.(int) + ev2.(int)
}, 0),
)
expected := [3]int{15, 42, 81}
var got [3]int
var gotLast int
var i int
SubscribeAndWait(o, func(ev Event) {
got[i] = ev.(int)
i += 1
}, nil, func(ev Event) {
gotLast = ev.(int)
})
if expected != got {
t.Errorf("Expected: %v, Got: %v", expected, got)
}
if expected[len(expected)-1] != gotLast {
t.Errorf("Expected: %v, Got: %v", expected[len(expected)-1], gotLast)
}
}
func TestAll(t *testing.T) {
debug(t)
o := Create(
Just(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
Map(func(ev Event) Event {
return ev.(int) * ev.(int)
}),
Scan(func(ev1, ev2 Event) Event {
return ev1.(int) + ev2.(int)
}, 0),
Filter(func(ev Event) bool {
return ev.(int) > 20
}),
Map(func(ev Event) Event {
return ev.(int) + 10000
}),
// Debug(func(obs Observer, cur, last Event) {
// t.Logf("DEBUG0 %#v, cur:%#v, last:%#v", obs, cur, last)
// }),
)
SubscribeAndWait(o, print(t, "Next"), print(t, "Error"), print(t, "Completed"))
}
func TestCreate(t *testing.T) {
debug(t)
o := Create(
ObservableFunc(func(obs Observer) {
for _, n := range []int{10, 20, 30} {
obs.Next(n)
}
obs.Next(Complete())
}),
)
SubscribeAndWait(o, print(t, "Next"), print(t, "Error"), func(ev Event) {
if n, ok := ev.(int); !(ok && n == 30) {
t.Error("Expected: 30, Got:", n)
}
})
}
func TestSubscribe(t *testing.T) {
debug(t)
o := Create(
Just(11, 22, 33),
)
Subscribe(o, print(t, "Next"), print(t, "Error"), func(ev Event) {
if n, ok := ev.(int); !(ok && n == 33) {
t.Error("Expected: 33, Got:", n)
}
})
SubscribeAndWait(o, print(t, "Next"), print(t, "Error"), func(ev Event) {
if n, ok := ev.(int); !(ok && n == 33) {
t.Error("Expected: 33, Got:", n)
}
})
}
func TestJust(t *testing.T) {
debug(t)
o := Create(
Just(1, 2, 3),
)
SubscribeAndWait(o, func(ev Event) {
t.Log(ev)
}, nil, nil)
}
func TestComposition(t *testing.T) {
debug(t)
o1 := Create(
Just(2, 3, 5, 7, 11),
Map(func(ev Event) Event {
return ev.(int) + 1
}),
)
o2 := Create(
o1,
Scan(func(ev1, ev2 Event) Event {
return ev1.(int) + ev2.(int)
}, 0),
)
SubscribeAndWait(o2, print(t, "Next"), print(t, "Error"), func(ev Event) {
if n, ok := ev.(int); !(ok && n == 33) {
t.Error("Expected: 33, Got:", n)
}
})
}
func TestReduce(t *testing.T) {
debug(t)
o := Create(
Just(1, 2, 3),
Reduce(func(ev1, ev2 Event) Event {
return ev1.(int) + ev2.(int)
}, 0),
)
SubscribeAndWait(o, print(t, "Next"), print(t, "Error"), func(ev Event) {
if n, ok := ev.(int); !(ok && n == 6) {
t.Error("Expected: 6, Got:", n)
}
})
}
func addInts(upto int) Observable {
return Create(
ObservableFunc(func(obs Observer) {
for i := 0; i < upto; i++ {
obs.Next(i)
}
obs.Next(Complete())
}),
Scan(func(ev1, ev2 Event) Event {
return ev1.(int) + ev2.(int)
}, 0),
)
}
func benchmarkAdd(i int, b *testing.B) {
o := addInts(i)
for n := 0; n < b.N; n++ {
SubscribeAndWait(o, nil, nil, nil)
}
}
func BenchmarkAdd10(b *testing.B) { benchmarkAdd(10, b) }
func BenchmarkAdd1000(b *testing.B) { benchmarkAdd(1000, b) }
func BenchmarkAdd1000000(b *testing.B) { benchmarkAdd(1000000, b) }
<file_sep>package daisychain
import "fmt"
func Example() {
//Create an Observable that emits 0..9 ints
o1 := Create(
Just(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
)
//Create another Observable by composition
o2 := Create(
// o1 emits 0..9!
o1,
// add 1 to each number
Map(func(ev Event) Event {
return ev.(int) + 1
}),
// skip 1..5
Skip(5),
// take 6,7,8
Take(3),
// filter even numbers: 6,8
Filter(func(ev Event) bool {
return ev.(int)%2 == 0
}),
// sum of 6 and 8
Reduce(func(ev1, ev2 Event) Event {
return ev1.(int) + ev2.(int)
}, 0),
)
//Subscribe to an Observable to execute it
SubscribeAndWait(o2, nil /*onNext*/, nil /*onError*/, onComplete)
//Output:
// 14
}
func onComplete(ev Event) {
fmt.Println(ev)
}
|
09d7877d6e2054ef3898fdd594792ddb97f48e70
|
[
"Markdown",
"Makefile",
"Go"
] | 5
|
Makefile
|
Bhanditz/daisychain
|
2d8e6bfbc21a5b646c016dd4b5cfedd16ee629c7
|
36772d57c1ea6871d026fcc6e0ea4e6aeb1bfc11
|
refs/heads/master
|
<repo_name>adricadar/tabcloser<file_sep>/background.js
(function() {
var intervalCheck = 60000;
var ONE_MINUTE = 60 * 1000;
var tabLifetime = 60 * 24; // 1 day
chrome.storage.local.get(['minutes', 'hours', 'days', 'intervalCheck'], (res) => {
tabLifetime = Number.parseInt(res.minutes) + Number.parseInt(res.hours) * 60 + Number.parseInt(res.days) * 60 * 24;
intervalCheck = res.intervalCheck * ONE_MINUTE;
});
function contains(tabsMetadata, tabId) {
var found = false;
for(var i = 0; i < tabsMetadata.length; i++) {
if (tabsMetadata[i].id == tabId) {
found = true;
break;
}
}
return found;
};
function indexOf(tabsMeta, tabId) {
for (var i = 0; i < tabsMeta.length; i++) {
if (tabsMeta[i].id === tabId) {
return i;
}
}
return -1;
}
function TabMetadata(id, startDate) {
var self = this;
self.id = id;
self.startDate = startDate;
return this;
};
function TabStorage() {
var self = this;
var tabsMetadata = "tabsMetadata";
self.get = function(onCall) {
chrome.storage.local.get(tabsMetadata, function (tabs) {
var tabsMeta = tabs[tabsMetadata] || [];
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
onCall(tabsMeta);
}
});
};
self.set = function(newTab) {
self.get(function(tabsMeta) {
tabsMeta.push(newTab);
chrome.storage.local.set({ tabsMetadata: tabsMeta }, onSet);
});
};
self.setAll = function(tabsMeta) {
chrome.storage.local.set({ tabsMetadata: tabsMeta }, onSet);
};
self.remove = function(tabId) {
self.get(function(tabsMeta) {
var index = indexOf(tabsMeta, tabId);
if(index >= 0) {
tabsMeta.splice(index, 1);
}
self.setAll(tabsMeta);
});
};
self.removeAll = function(tabIds) {
self.get(function(tabsMeta) {
for(var tabId of tabIds) {
var index = indexOf(tabsMeta, tabId);
if(index >= 0) {
tabsMeta.splice(index, 1);
}
}
self.setAll(tabsMeta);
});
};
self.updateAll = function(tabIds) {
self.get(function (tabsMeta) {
for(var tabId of tabIds) {
var index = indexOf(tabsMeta, tabId);
if(index >= 0) {
var oldDate = tabsMeta[index].startDate;
self.remove(tabId);
tabsMeta[index].startDate = Date.now();
self.set(tabsMeta[index]);
console.log("updated: " + tabId + " - " + oldDate + " - " + tabsMeta[index].startDate);
}
}
});
};
function onSet() {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
console.log("tab added");
}
};
return self;
}
var tabStorage = new TabStorage();
function updateTab(tabId) {
tabStorage.updateAll([tabId]);
}
browser.tabs.onUpdated.addListener(updateTab);
browser.tabs.onCreated.addListener(function(tab) {
if(browser.tabs.TAB_ID_NONE != tab.id) {
var newTab = new TabMetadata(tab.id, Date.now());
//chrome.storage.local.clear();
tabStorage.set(newTab);
}
});
browser.tabs.onRemoved.addListener(function(tabId) {
tabStorage.remove(tabId);
});
function removeTabs(tabsMetadata) {
console.log(tabsMetadata);
var oldTabMetas = tabsMetadata.filter(function(tabMetadata){
var difference = Date.now() - tabMetadata.startDate;
return Math.round(difference / ONE_MINUTE) > tabLifetime;
});
browser.tabs.query({ pinned: false }, function(tabs) {
var oldTabs = tabs.filter(function (tab) {
return contains(oldTabMetas, tab.id);
});
var oldTabIds = oldTabs.map(function(tab) {
return tab.id;
});
console.log(oldTabIds);
browser.tabs.remove(oldTabIds);
});
};
function updateTabs() {
browser.tabs.query({ active: true }, function(tabs) {
var tabIds = tabs.map(function(tab) {
return tab.id;
});
tabStorage.updateAll(tabIds);
});
browser.tabs.query({ pinned: true }, function(tabs) {
var tabIds = tabs.map(function(tab) {
return tab.id;
});
tabStorage.updateAll(tabIds);
});
};
setInterval(function(){
console.log("hello background");
console.log("tabLifetime: " + tabLifetime + " minutes");
updateTabs();
tabStorage.get(removeTabs);
}, intervalCheck);
function handleClick() {
chrome.runtime.openOptionsPage();
}
chrome.browserAction.onClicked.addListener(handleClick);
})();
|
03302ab369187ab954b01916df5961bf31afb40b
|
[
"JavaScript"
] | 1
|
JavaScript
|
adricadar/tabcloser
|
f758c430949e862b8d637c207eb783676a28bf59
|
04c263c1e193237aac991db935806324c6252f80
|
refs/heads/master
|
<file_sep>export * from './angular-datepickr.module';<file_sep># angular datepicker
A datepicker for angular 5
<file_sep>import { Component, OnInit, OnChanges, Input, EventEmitter, Output, HostListener, SimpleChanges } from '@angular/core';
import * as moment from 'moment';
import { IDay, DayMode } from './datepicker.base';
import { AngularDatepickerOptions } from 'datepicker-options';
@Component({
selector: 'datepicker-component',
templateUrl: 'datepicker.component.html',
styleUrls: ['./datepicker.component.scss']
})
export class DatepickerComponent implements OnInit, OnChanges {
@Input() min: Date = new Date('1900/01/01 00:00:00');
@Input() max: Date = new Date('2099/12/31 23:59:59');
@Input() minYear: number = 1900;
@Input() maxYear: number = 2099;
@Input() titleFormat: string = 'y年mm月dd日';
@Input() format: string = 'y-mm-dd hh:ii:ss';
@Input('value') currentDate: Date = new Date();
@Output() valueChange: EventEmitter<string> = new EventEmitter();
@HostListener('document:click', ['$event']) hideCalendar(event) {
if(!event.target.closest('.datepicker') && !this.hasElementByClass(event.path, 'datepicker__calendar')) {
this.calendarVisible = false;
}
}
title: string = '-';
day_list: Array<IDay> = [];
year_list: Array<number> = [];
month_list: Array<number> = [];
hour_list: Array<number> = [];
minute_list: Array<number> = [];
second_list: Array<number> = [];
currentYear: number;
currentMonth: number;
currentDay: number;
currentHour: number;
currentMinute: number;
currentSecond: number;
hasTime: boolean = true;
calendarVisible: boolean = false;
gridMode: DayMode = DayMode.Day;
constructor(opts: AngularDatepickerOptions) {
this.min = opts.min;
this.max = opts.max;
this.maxYear = opts.maxYear;
this.minYear = opts.minYear;
this.format = opts.format;
this.titleFormat = opts.titleFormat
}
ngOnInit() {
this.refresh();
this.initMonths();
this.initYears();
if (this.hasTime) {
this.initHours();
this.initMinutes();
this.initSeconds();
}
this.output();
}
ngOnChanges(changes: SimpleChanges) {
if (changes.format) {
this.hasTime = changes.format.currentValue.indexOf('h') > 0;
}
if (changes.currentDate) {
this.currentDate = this.parseDate(changes.currentDate.currentValue);
}
if (changes.min) {
this.min = this.parseDate(changes.min.currentValue);
if (!this.hasTime) {
this.min.setHours(23, 59, 59, 999);
} else {
this.min.setMilliseconds(999);
}
if (this.min >= this.currentDate) {
// 加一天
this.currentDate = new Date(this.min.getTime() + 86400000);
}
}
if (changes.max) {
this.max = this.parseDate(changes.max.currentValue);
if (!this.hasTime) {
this.max.setHours(0, 0, 0, 0);
}
}
this.refresh();
}
/**
* 转化date
* @param date
*/
parseDate(date: any): Date {
if (!date) {
return new Date();
}
if (typeof date == 'number') {
return new Date(date * 1000);
}
if (typeof date == 'string') {
return new Date(date);
}
return date;
}
/**
* 验证Date
* @param date
*/
checkDate(date: Date): boolean {
let min = this.min;
if (min && date <= min) {
return false;
}
let max = this.max;
return !max || date < max;
}
/**
* 刷新变化部分
*/
refresh() {
this.hasTime = this.format.indexOf('h') > 0;
this.refreshCurrent();
this.initDays();
}
refreshCurrent() {
this.currentYear = this.currentDate.getFullYear();
this.currentMonth = this.currentDate.getMonth() + 1;
this.currentDay = this.currentDate.getDate();
if (this.hasTime) {
this.currentHour = this.currentDate.getHours();
this.currentMinute = this.currentDate.getMinutes();
this.currentSecond = this.currentDate.getSeconds();
}
this.title = this.formatDate(this.currentDate, this.titleFormat);
}
initHours() {
this.hour_list = [];
for (let i = 0; i < 24; i++) {
this.hour_list.push(i);
}
}
initMinutes() {
this.minute_list = [];
for (let i = 0; i < 60; i++) {
this.minute_list.push(i);
}
}
initSeconds() {
this.second_list = [];
for (let i = 0; i < 60; i++) {
this.second_list.push(i);
}
}
initMonths() {
this.month_list = [];
for (let i = 1; i < 13; i++) {
this.month_list.push(i);
}
}
initYears() {
this.year_list = [];
for(let i = this.minYear; i <= this.maxYear; i++) {
this.year_list.push(i);
}
}
initDays() {
this.day_list = this.getDaysOfMonth(this.currentMonth, this.currentYear);
}
toggleYear() {
this.gridMode = this.gridMode == DayMode.Year ? DayMode.Day : DayMode.Year;
}
toggleTime() {
this.gridMode = this.gridMode == DayMode.Hour ? DayMode.Day : DayMode.Hour;
}
private getDaysOfMonth(m: number, y: number): Array<IDay> {
let days = [];
let [f, c] = this.getFirtAndLastOfMonth(y, m);
let i: number;
if (f > 0) {
let yc = this.getLastOfMonth(y, m - 1);
for (i = yc - f + 2; i <= yc; i ++) {
days.push({
disable: true,
val: i
});
}
}
for (i = 1; i <= c; i ++) {
days.push({
disable: false,
val: i
});
}
if (f + c < 43) {
let l = 42 - f - c + 1;
for (i = 1; i <= l; i ++) {
days.push({
disable: true,
val: i
});
}
}
return days;
}
/**
* 获取月中最后一天
* @param y
* @param m
*/
private getLastOfMonth(y: number, m: number): number {
let date = new Date(y, m, 0);
return date.getDate();
}
/**
* 获取第一天和最后一天
* @param y
* @param m
*/
private getFirtAndLastOfMonth(y: number, m: number): [number, number] {
let date = new Date(y, m, 0);
let count = date.getDate();
date.setDate(1);
return [date.getDay(), count];
}
/**
* 上一年
*/
previousYear() {
this.changeYear(this.currentYear - 1);
}
/**
* 下一年
*/
nextYear() {
this.changeYear(this.currentYear + 1);
}
/**
* 上月
*/
previousMonth() {
this.changeMonth(this.currentMonth - 1);
}
/**
* 下月
*/
nextMonth() {
this.changeMonth(this.currentMonth + 1);
}
applyCurrent() {
this.currentDate.setFullYear(this.currentYear, this.currentMonth, this.currentDay);
if (this.hasTime) {
this.currentDate.setHours(this.currentHour, this.currentMinute, this.currentSecond);
}
this.title = this.formatDate(this.currentDate, this.titleFormat);
}
changeYear(year: number) {
this.currentYear = year;
this.initDays();
this.applyCurrent();
}
changeMonth(month: number) {
this.currentMonth = month;
this.initDays();
this.applyCurrent();
}
changeDay(day: IDay) {
let date = new Date(this.currentDate.getTime());
if (day.disable) {
if (day.val < 15) {
date.setMonth(date.getMonth() + 1);
} else {
date.setMonth(date.getMonth() - 1);
}
}
date.setDate(day.val);
if (!this.checkDate(date)) {
return;
}
this.currentDate = date;
this.refreshCurrent();
if (!this.hasTime) {
this.enterChange();
return;
}
}
changeHour(hour: number) {
this.currentHour = hour;
}
changeMinute(minute: number) {
this.currentMinute = minute;
}
changeSecond(second: number) {
this.currentSecond = second;
}
/**
* 确认改变
*/
enterChange() {
this.applyCurrent();
if (!this.checkDate(this.currentDate)) {
return;
}
this.output();
this.calendarVisible = false;
}
output() {
this.valueChange.emit(this.formatDate(this.currentDate, this.format));
}
showCalendar() {
this.calendarVisible = true;
this.refresh();
}
/**
* 格式化日期
*/
public formatDate(date: Date, fmt: string = 'y年mm月dd日'): string {
let o = {
"y+": date.getFullYear(),
"m+": date.getMonth() + 1, //月份
"d+": date.getDate(), //日
"h+": date.getHours(), //小时
"i+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
for (let k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt;
}
hasElementByClass(path: Array<Element>, className: string): boolean {
let hasClass = false;
for (let i = 0; i < path.length; i++) {
const item = path[i];
if (!item || !item.className) {
continue;
}
hasClass = item.className.indexOf(className) >= 0;
if (hasClass) {
return true;
}
}
return hasClass;
}
}<file_sep>import { Injectable } from '@angular/core';
@Injectable()
export class AngularDatepickerOptions {
min: Date = new Date('1900/01/01 00:00:00');
max: Date = new Date('2099/12/31 23:59:59');
minYear: number = 1900;
maxYear: number = 2099;
titleFormat: string = 'y年mm月dd日';
format: string = 'y-mm-dd hh:ii:ss';
}<file_sep>interface IDay {
disable: boolean,
selected: boolean,
val: number
};
enum DayMode {
Day = 0,
Year = 1,
Hour = 2
};
export {
IDay,
DayMode
};
<file_sep>import { AngularDatepickerOptions } from "datepicker-options";
import { ModuleWithProviders, NgModule } from "@angular/core";
import { DatepickerComponent } from "datepicker.component";
@NgModule({
imports: [
],
declarations: [
DatepickerComponent,
],
providers: [],
exports: [
DatepickerComponent,
]
})
export class AngularDatepickerModule {
static forRoot(config: AngularDatepickerOptions): ModuleWithProviders {
return {
ngModule: AngularDatepickerModule,
providers: [
{ provide: AngularDatepickerOptions, useValue: config }
]
};
}
}
|
869d25ca026769cc928b330085e608c2df14f71d
|
[
"Markdown",
"TypeScript"
] | 6
|
TypeScript
|
zx648383079/angular-datepicker
|
0f3d52dd54f1c9539498cbc052d55168a354f0ee
|
3440c675b90d3b1f8962e06e1154aaffe5e30955
|
refs/heads/master
|
<repo_name>n30nl1ght/angular1-vorlage<file_sep>/src/app/main/main.router.js
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/welcome');
$stateProvider
.state('welcome', {
url: '/welcome',
templateUrl: 'template/welcome.html'
})
.state('about', {
url: '/about',
templateUrl: 'template/about.html'
})
.state('service', {
url: '/service',
templateUrl: 'template/service.html'
});
});<file_sep>/README.md
#Vorlage für Angular 1.5.x
##Eingesetzte Frameworks
- Angular 1.5.x
- Bootstrap 4.0.0-alpha.4
##Installation
1. ```git clone https://github.com/n30nl1ght/angular1-vorlage.git```
2. ```npm install```
3. ```npm start```
###Author
[n30nl1ght](https://github.com/n30nl1ght)
|
e9893b46a764140c146f21576bd9ebac90ebc253
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
n30nl1ght/angular1-vorlage
|
61d213a569e34625b4f3074076a751634c263b57
|
b5aa5fda956b13bfb28af80c529bb8acceeb1daa
|
refs/heads/master
|
<file_sep>'use strict'
var mongoose = require('mongoose');
var _ = require('lodash');
var fs = require('fs');
var rl = require('readline');
var iconv = require('iconv-lite');
var glob = require('glob');
mongoose.connect('docker/locations');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error'));
var file = '/Users/marcelofelix/Downloads/eDNE_Master_1509/Delimitado/LOG_LOGRADOURO_AC.TXT';
var base = {
correiosId: Number,
parentLocationId: Number,
operation: String
}
var Location = mongoose.model('locations', _.assign(base, {
uf: String,
name: String,
zip: String,
status: String,
type: String,
abbreviation: String,
cityId: String,
oldZip: String
}));
var Street = mongoose.model('street', _.assign(base, {
startNeighborhoodId: Number,
finalNeighborhoodId: Number,
name: String,
complement: String,
zip: String,
type: String,
typeIsAPrefixOfTheName: Boolean,
abbreviation: String,
oldZipCode: String
}));
glob('/Users/marcelofelix/Downloads/eDNE_Master_1509/Delimitado/**/*.TXT',
function(err, files) {
files.forEach(function(f) {
if (f.indexOf('LOG_LOGRADOURO') > -1) {
console.log(f);
rl.createInterface({
input: fs.createReadStream(f)
.pipe(iconv.decodeStream('ISO-8859-1'))
})
.on('line', function(data) {
var value = data.split('@');
new Street({
correiosId: value[0],
parentLocationId: value[2],
startNeighborhoodId: value[3],
finalNeighborhoodId: value[4],
name: value[5],
complement: value[6],
zip: value[7],
type: value[8],
typeIsAPrefixOfTheName: value[9],
abbreviation: value[10],
operation: value[11],
oldZipCode: value[12]
}).save(function(error) {
console.log('Saving');
if (error)
console.log(error);
});
})
.on('end', function() {
console.log('Fim');
});
};
})
});
|
f7d74f82132db907ae2b4d6828cbb26bd4fd6b73
|
[
"JavaScript"
] | 1
|
JavaScript
|
marcelofelix/dne
|
82d7a14c70f04a8bff116240ecbe9d37e914c451
|
09b58ef53620abaefacf6c9497356feb606d3c2c
|
refs/heads/master
|
<file_sep># jQuery Flickr Set
Display flickr sets using a template.
## Usage
<script src="js/jquery.flickrset.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
// Change <ul id="gallery1"></ul> and <ul id="gallery2"></ul> into flickr galleries
$('#gallery1,#gallery2').flickrSet({
// Use an array; same thing can be done with the template
'flickrSet': ['123456789123456', '123456789456123'],
'flickrKey': '<KEY>',
'template': '<li><a href="{{image_b}}" title="{{title}}"><img src="{{image_s}}" alt="{{title}}" /></a></li>'
}, function(data) {
// CALL AFTER FLICKR LOADED
});
});
</script>
## License
jquery.flickrset.js is offered under an [MIT license](http://www.opensource.org/licenses/mit-license.php).
## Copyright
2011 <NAME>, [dontkry.com](http://dontkry.com)
If you found this release useful please let the author know! Follow on [Twitter](http://twitter.com/kyletyoung)
<file_sep>/**
* jQuery FlickrSet
* Display Flickr Photo Sets in a given template
*
* @author <NAME> <kyle at dontkry.com>
* @copyright 2011 <NAME>
* @license MIT license <http://www.opensource.org/licenses/mit-license.php>
*
* Inspired by <NAME>, http://www.newmediacampaigns.com/page/jquery-flickr-plugin
* and J.P. Given (http://johnpatrickgiven.com)
*
*/
(function($) {
$.fn.flickrSet = function(args, callback) {
var defaults = {
'flickrSet': null,
'flickrKey': null,
'template': '<a href="{{image_b}}" title="{{title}}"><img src="{{image_s}}" alt="{{title}}" /></a>',
'limit': 100
}
settings = jQuery.extend({}, defaults, args);
if (settings.flickrKey === null || settings.flickrSet === null) {
alert('You must pass an API key and a Flickr setID');
return;
}
return $(this).each(function(key){
var $container = $(this);
var container = this;
var set = null;
if ($.isArray(settings.flickrSet)) {
set = settings.flickrSet[key];
} else {
set = settings.flickrSet;
}
$.getJSON("http://api.flickr.com/services/rest/?format=json&method=flickr.photosets.getPhotos&photoset_id=" + set + "&api_key=" + settings.flickrKey + "&jsoncallback=?", function(data) {
$.each(data.photoset.photo, function(i, item) {
if (i < settings.limit) {
// Add Image Sizes
// http://www.flickr.com/services/api/misc.urls.html
item['image_s'] = 'http://farm' + item.farm + '.' + 'static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret +'_s.jpg'; // 75x75
item['image_t'] = 'http://farm' + item.farm + '.' + 'static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret +'_t.jpg'; // 100
item['image_m'] = 'http://farm' + item.farm + '.' + 'static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret +'_m.jpg'; // 240
item['image'] = 'http://farm' + item.farm + '.' + 'static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret +'.jpg'; // 500
item['image_z'] = 'http://farm' + item.farm + '.' + 'static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret +'.jpg'; // 640
item['image_b'] = 'http://farm' + item.farm + '.' + 'static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret +'_b.jpg'; // 1024
// TODO: Hold on original, need to find out if gif, png, or jpg.
//item['image_o'] = 'http://farm' + item.farm + '.' + 'static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret +'_o.jpg'; // ORIGINAL
// Use Template
var template = null;
if ($.isArray(settings.template)) {
template = settings.template[i];
} else {
template = settings.template;
}
for(var key in item){
var rgx = new RegExp('{{' + key + '}}', 'g');
template = template.replace(rgx, item[key]);
}
$container.append(template);
}
});
if($.isFunction(callback)){
callback.call(container, data);
}
});
});
}
})(jQuery);
|
6b97776740cbd4a5358d9860ade536b5a24a278a
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
shama/jquery.flickrset.js
|
4774a1f7ca376fd3216c034bb976a68e39d4f51a
|
a8c301e69b804cf117037904257ac60bad64c197
|
refs/heads/master
|
<repo_name>SkyzohKey/node-nano-rpc<file_sep>/ReadMe.md
# RaiBlocks NodeJS RPC Client
[](https://www.npmjs.com/package/node-raiblocks-rpc)
[](https://app.fossa.io/projects/git%2Bgithub.com%2FSkyzohKey%2Fnode-raiblocks-rpc?ref=badge_small) [](https://badge.fury.io/js/node-raiblocks-rpc)
RaiBlocks RPC client written with NodeJS.
It produces JSON objects or strings as output, wrapped in native promises.
All RPC calls are defined here:
https://github.com/clemahieu/raiblocks/wiki/RPC-protocol
## [Become a patron](https://www.patreon.com/bePatron?u=2330345) ~ [Donate](#donations)
#### Table of Contents
* [Getting Started](#getting-started)
* [Examples](#examples)
* [Promise-wrapped responses](#promise-wrapped-responses)
* [Methods Names](#methods-names)
* [Arguments](#arguments)
* [Returned value](#returned-value)
* [Testing](#testing)
* [Possible future features](#possible-future-features)
* [Donations](#donations)
* [License (MIT)](#license)
## Getting Started
1. Install the npm package:
```bash
$ yarn add node-raiblocks-rpc
# or
$ npm install node-raiblocks-rpc --save
```
2. Require the RPC client into your project:
```js
const RaiClient = require('node-raiblocks-rpc');
const NODE_ADDRESS = 'http://[urltonode|iptonode]:port';
/**
* decodeJSON is an optional boolean argument.
* When set to true (default), the JSON string response is
* parsed into a JSON object. Otherwise the string is returned.
*/
const client = new RaiClient(NODE_ADDRESS [, decodeJSON]);
```
3. Use methods attached to `client` to send RPC calls:
### Examples
Head to the [`examples.js`](examples.js) file for even more!
```js
const client = new RaiClient(NODE_ADDRESS [, decodeJSON]);
// Some methods do not require arguments:
client
.block_count()
.then(count => {
console.log(count);
/**
* {
* "count": "1826834",
* "unchecked": "3385205"
* }
*/
})
.catch(e => {
// Deal with your errors here.
});
// Some methods require arguments:
client
.account_balance("xrb_mySuperAddress")
.then(balance => {
console.log(balance);
/**
* {
* "balance": "325586539664609129644855132177",
* "pending": "2309370929000000000000000000000000"
* }
*/
})
.catch(e => {
// Deal with your errors here.
});
```
### Promise-wrapped responses
All method calls return native NodeJS promises. You need to use the
`then()` / `catch()` pattern shown above. If the call was succesful,
the data will be passed to `then()`, otherwise the error will be passed
to `catch()`.
### Methods Names
The method calls are the same as the original RPC actions defined
on the RaiBlocks wiki.
(See https://github.com/clemahieu/raiblocks/wiki/RPC-protocol)
Example1: on the RaiBlocks wiki `account_balance` is called with `account`.
For the NodeJS client, the method is `account_balance` and the argument is the account string.
### Arguments
The arguments to use for those methods are detailed in the inline documentation of
the `index.js`. There are the same as those mentioned in the Monero documentation:
https://github.com/clemahieu/raiblocks/wiki/RPC-protocol
### Returned value
If you havent specified any `decodeJSON` argument when you
instantiated `RaiClient`, by default the returned data will already be parsed
into a JSON object for you. Otherwise you will receive the original JSON string
returned by the RaiBlocks network.
## Testing
Testing is done with `mocha`, `chai` and `chai-as-promised` to test promises.
To run the tests:
```bash
$ yarn test
# or
$ npm run test
```
The tests are located in the `lib/tests.js` file. They perform actual API calls to the RaiBlocks network through a local node. In order to prevent the tests from failing because of a timeout, tests are run with a `timeout` option of 100s. Tests can still fail if the local node is too slow.
If you want to just run one set of test (i.e a `describe` block), for let's say the `account_balance()` function, you can do so with this command:
```bash
$ ./node_modules/mocha/bin/mocha --grep [functionNameHere] --timeout 10000
```
For example, if you want to test `account_balance`:
```bash
$ ./node_modules/mocha/bin/mocha --grep account_balance --timeout 10000
```
You can be even more specific by adding `only` to the individual tests. Example for `account_balance()`:
```diff
describe("RaiClient.account_balance()", done => {
+ it.only("should retrieve account balance", () => {
- it("should retrieve account balanve", () => {
expect(client.account_balance(WALLET_ADDRESS))
.to.eventually.contain('"balance"')
.and.to.eventually.contain('"pending"')
.notify(done);
});
});
```
## Possible future features
* Caching of some responses
* First with javascript objects
* Then with some external db, like Redis or SQLLite
* Make the library Isomorphic, i.e work in web-browsers as well
* Make the method calls also support callbacks
* Setup automated testing with travis. Will need first to build a mock object for RaiBlocks to have deterministic tests
## Donations
I currently work on this project during my free-time, but also during my work-time. As I'm my own boss, I take work time to work on personnal projects that I really believes in. But during this time, I don't win any money. I'm not doing that for money.
Anyway, if you consider support me, you can pay me a pack of Monster's cans for moore productive coding, :D.
I accept donations in form of RaiBlocks, Monero, Bitcoin, Etherum & IntenseCoin. You can also Patreon me !
[](https://www.patreon.com/bePatron?u=2330345)
```
1. Monero (XMR): 47XpVhUHahViCZHuZPc2Z6ivLraidX7AxbM8b2StdPcQGwjDGY14eqj9ippW7Pdrqj9d2y4xvwChzePQAqG1NvqQ775FKxg
2. Bitcoin (BTC/XBT): 18BqyV9mNbFLi5HNNnfUprnPJyJDFP59Xh
3. Etherum (ETH): 0x56E3273D42B40d47E122fF62108dEDC974A4206e
4. RaiBlocks (XRB): xrb_1ezazq8dkyashxeorb6kwncoc1imodd36yfetsje1ase71joy3qsnk8papku
4. IntenseCoin (ITNS): iz5F814eDfX7gbUucu17E5YUBGADYGLDRhMfKQjfXwv9S1UDPaJKcgEiUUWm9vDeJ7JVcPWo7kZRmTFtcVcssc1h28zguw8iE
```
If you wish to support me, but doesn't have money for, you can still message me on Wire and give me some free hugs! :D
* Wire handle: **@SkyzohKey**
## License
You can find an in-depth analysis of the dependencies license on [FOSSA](https://app.fossa.io/reports/c98c4d73-3c54-4bdb-b804-678f37c429fd)
This project is licensed under [The MIT License](LICENSE).
[](https://app.fossa.io/projects/git%2Bgithub.com%2FSkyzohKey%2Fnode-raiblocks-rpc?ref=badge_large)
<file_sep>/examples.js
const RaiClient = require("./lib");
const RAI_ADDRESS =
"xrb_3t6k35gi95xu6tergt6p69ck76ogmitsa8mnijtpxm9fkcm736xtoncuohr3";
const client = new RaiClient("http://127.0.0.1:7076");
const handleErrors = e => {
console.log("\nError: " + e.message);
};
client
.account_balance(RAI_ADDRESS)
.then(account => console.log("Account balance:", account))
.catch(this.handleErrors);
client
.block_count()
.then(count => console.log("Block count:", count))
.catch(this.handleErrors);
//client.stop().then(() => console.log("Node stopped. Exiting..."));
|
4bf9919eea332bf149eb8c292d0225f32edf27e6
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
SkyzohKey/node-nano-rpc
|
721e3a7bc844a3be9fefb6a9e1f55a31f6f20e52
|
fc9c1832687c3a696ef35762045844d0b4eff10d
|
refs/heads/master
|
<repo_name>deanvucic/diplomaticacademy<file_sep>/dfata_theme/dist/js/script.js
/**
* Accordion behaviour.
*/
(function($, Drupal, window, document, undefined) {
Drupal.behaviors.dfata_content_accordion = {
attach: function(context, settings) {
// Initialise the accordion for the Page Content paragraph bundle.
if ($.fn.accordion) {
$('.field-name-field-page-content').find('.field-items').accordion({
header: ".field-name-field-title",
autoHeight: false,
active: false
})
}
}
};
})(jQuery, Drupal, this, this.document);
/**
* External Link detector.
*/
(function($, Drupal, window, document, undefined) {
var current_domain = '';
var domainRe = /https?:\/\/((?:[\w\d-]+\.)+[\w\d]{2,})/i;
function domain(url) {
var arr = domainRe.exec(url);
return (arr !== null) ? arr[1] : current_domain;
}
function isExternalRegexClosure(url) {
return current_domain !== domain(url);
}
Drupal.behaviors.dfata_theme_external_links = {
attach: function(context, settings) {
// Get current domain.
current_domain = domain(location.href);
// Find all links and apply a rel if external.
$('a', context).each(function() {
var $this = $(this);
if (isExternalRegexClosure($this.attr('href'))) {
$this.attr('rel', 'external');
}
})
}
};
})(jQuery, Drupal, this, this.document);
/**
* Mobile Menu.
*/
(function($, Drupal, window, document, undefined) {
var $widget = null;
var $button = null;
var $nav_wrapper = null;
var menu_toggle_enabled = false;
function menu_bar_resize() {
var w = window.innerWidth || document.documentElement.clientWidth;
if (w >= tablet_breakpoint && menu_toggle_enabled) {
// Desktop.
menu_toggle_enabled = false;
$widget.removeClass('menu-toggle');
$button.detach();
}
else if (w < tablet_breakpoint && !menu_toggle_enabled) {
// Mobile.
menu_toggle_enabled = true;
$widget.addClass('menu-toggle');
$nav_wrapper.prepend($button);
}
}
function toggle_menu(e) {
if (menu_toggle_enabled) {
var was_open = $widget.hasClass('menu-open');
$widget.toggleClass('menu-open');
if (was_open) {
$widget.attr('aria-hidden', 'true');
$button.removeClass('menu-open').attr('aria-expanded', 'false');
}
else {
$widget.attr('aria-hidden', 'false');
$button.addClass('menu-open').attr('aria-expanded', 'true');
}
}
e.stopPropagation();
return false;
}
Drupal.behaviors.dfata_theme_menu = {
attach: function(context, settings) {
$widget = $('#mobile-nav', context);
if ($widget.length > 0) {
$button = $('<button class="mobile-expand-menu" aria-controls="' + $widget.attr('id') + '" aria-expanded="false">Toggle menu navigation</button>');
$nav_wrapper = $('#nav');
$button.unbind('click', toggle_menu).bind('click', toggle_menu);
$(window).unbind('resize', menu_bar_resize).bind('resize', menu_bar_resize);
menu_bar_resize();
}
}
};
})(jQuery, Drupal, this, this.document);
/**
* Global variables.
*/
var desktop_breakpoint = 1200;
var large_tablet_breakpoint = 1024;
var tablet_breakpoint = 768;
var mobile_breakpoint = 420;
var desktop_column = 1170;
/**
* govCMS general bootstrapping.
*/
(function($, Drupal, window, document, undefined) {
Drupal.behaviors.dfata_theme = {
attach: function(context, settings) {
// Object Fit Polyfill for IE. Used on News Teaser Images.
objectFitImages();
}
};
})(jQuery, Drupal, this, this.document);
/**
* Header Search Field.
*/
(function($, Drupal, window, document, undefined) {
var $widget = null;
var $button = null;
var $logo_wrapper = null;
var search_toggle_enabled = false;
function search_bar_resize() {
var w = window.innerWidth || document.documentElement.clientWidth;
if (w >= tablet_breakpoint && search_toggle_enabled) {
// Desktop.
search_toggle_enabled = false;
$widget.removeClass('search-toggle');
$button.detach();
}
else if (w < tablet_breakpoint && !search_toggle_enabled) {
// Mobile.
search_toggle_enabled = true;
$widget.addClass('search-toggle');
$logo_wrapper.after($button);
}
}
function toggle_search(e) {
if (search_toggle_enabled) {
var was_open = $widget.hasClass('search-open');
$widget.toggleClass('search-open');
if (was_open) {
$widget.attr('aria-hidden', 'true');
$button.removeClass('search-open').attr('aria-expanded', 'false');
}
else {
$widget.attr('aria-hidden', 'false');
$button.addClass('search-open').attr('aria-expanded', 'true');
}
}
e.stopPropagation();
return false;
}
Drupal.behaviors.dfata_theme_search = {
attach: function(context, settings) {
$widget = $('header .search-form-widget', context);
if ($widget.length > 0) {
$button = $('<button class="mobile-expand-search" aria-controls="' + $widget.attr('id') + '" aria-expanded="false">Toggle search form</button>');
$logo_wrapper = $('.logo-wrapper .header-title');
$button.unbind('click', toggle_search).bind('click', toggle_search);
$(window).unbind('resize', search_bar_resize).bind('resize', search_bar_resize);
search_bar_resize();
}
}
};
})(jQuery, Drupal, this, this.document);
/**
* Side Bar Menu.
*/
(function($, Drupal, window, document, undefined) {
var $widget = null;
var is_menu_desktop = true;
// =========================================================
// DESKTOP TOGGLES
// =========================================================
function toggle_button_click(e) {
var $button = $(e.currentTarget);
var $menu = $button.parent().children('ul.menu');
var was_closed = $button.hasClass('menu-closed');
if (was_closed) {
$menu.removeClass('menu-closed').attr('aria-hidden', 'false');
$button.removeClass('menu-closed').attr('aria-expanded', 'true').attr('title', 'Collapse menu');
}
else {
$menu.addClass('menu-closed').attr('aria-hidden', 'true');
$button.addClass('menu-closed').attr('aria-expanded', 'false').attr('title', 'Expand menu');
}
}
function add_toggle_buttons() {
// Only add buttons to first level of menu items.
$widget.find('.menu-block-wrapper > ul > li').each(function(idx) {
var $list_item = $(this);
var $sub_menu = $list_item.children('ul.menu');
if ($sub_menu.length > 0) {
var $button = $('<button class="sidebar-toggle-menu" aria-controls="' + $sub_menu.attr('id') + '" aria-expanded="true" title="Collapse menu">Toggle sub menu</button>');
$sub_menu.attr('id', 'sidebar-submenu-' + idx);
$list_item.children('a').after($button);
$button.unbind('click', toggle_button_click).bind('click', toggle_button_click);
}
});
}
function remove_toggle_buttons() {
// Clean up any elements and attributes created.
$widget.find('.sidebar-toggle-menu').remove();
$widget.find('[id^=sidebar-submenu]').removeAttr('id').removeAttr('aria-hidden').removeClass('menu-closed');
}
// =========================================================
// MOBILE ACCORDION
// =========================================================
function enable_mobile_accordion() {
var display_text = $widget.children('h2').html();
var $content = $widget.children('.content');
$content.attr('id', 'sidebar-menu-content');
var $button = $('<button aria-controls="sidebar-menu-content" aria-expanded="false">' + display_text + '</button>');
$widget.children('h2').html($button);
$button.unbind('click', sidebar_accordion_button_click).bind('click', sidebar_accordion_button_click);
}
function disable_mobile_accordion() {
var display_text = $widget.children('h2').children('button').html();
$widget.children('h2').empty().html(display_text);
$widget.children('.content').removeAttr('id').removeClass('showing');
}
function sidebar_accordion_button_click(e) {
var $button = $(e.currentTarget);
var was_showing = $button.hasClass('showing');
if (was_showing) {
$button.removeClass('showing').attr('aria-expanded', 'false');
$widget.children('.content').removeClass('showing');
}
else {
$button.addClass('showing').attr('aria-expanded', 'true');
$widget.children('.content').addClass('showing');
}
}
// =========================================================
// RESPONSIVE
// =========================================================
function side_menu_responsive() {
var w = window.innerWidth || document.documentElement.clientWidth;
// Mobile (No toggles).
if (w < large_tablet_breakpoint && is_menu_desktop) {
// Disable menu toggles.
is_menu_desktop = false;
remove_toggle_buttons();
enable_mobile_accordion();
}
// Desktop (Toggles).
else if (w >= large_tablet_breakpoint && !is_menu_desktop) {
is_menu_desktop = true;
add_toggle_buttons();
disable_mobile_accordion();
}
}
Drupal.behaviors.dfata_theme_sidebar = {
attach: function(context, settings) {
$widget = $('#block-menu-block-govcms-menu-block-sidebar', context);
if ($widget.length > 0) {
add_toggle_buttons();
$(window).unbind('resize', side_menu_responsive).bind('resize', side_menu_responsive);
side_menu_responsive();
}
}
};
})(jQuery, Drupal, this, this.document);
/**
* Home page slider.
* An implementation of the Owl Carousel with custom controls.
*/
(function($, Drupal, window, document, undefined) {
function isDesktop() {
if ($('.mobile-expand-menu').is(':visible')) {
return false;
}
else {
return true;
}
}
Drupal.behaviors.front_page_news_carousel = {
attach: function(context, settings) {
// Init Owl Carousel
var owl = $(".view-latest-news.view-display-id-block_1 .view-content");
owl.owlCarousel({
singleItem: true,
autoPlay: 5000,
transitionStyle: 'fade',
addClassActive: true,
mouseDrag: false,
items: 1,
autoHeight: true,
afterUpdate: function() {
grabTitles();
}
});
// Pause on Item Click
$('.owl-controls').find('.owl-pagination').click(function() {
owl.trigger('owl.stop');
$(".owl-pause").hide();
$(".owl-play").show();
});
// Create Pause and play Buttons
$('.news-information').append(
'<span class="owl-pause"></span><span style="display:none;" class="owl-play"></span>');
// Functions to handle pause/play behaviour
$(".owl-pause").click(function() {
owl.trigger('owl.stop');
$('.owl-pause').hide();
$(".owl-play").show();
});
$(".owl-play").click(function() {
owl.trigger('owl.play', 5000);
$('.owl-play').hide();
$(".owl-pause").show();
});
function grabTitles() {
if (isDesktop()) {
// Grab the Carousel Titles and place them into pagination inside a wrapper div
var titles = [];
$('.news-information h3').each(function(index) {
titles[index] = $(this).text();
});
$('.owl-page').each(function(index) {
$(this).html('<div class="carousel-desk-title">' + titles[index] + '</div>');
});
}
}
grabTitles();
}
};
})(jQuery, Drupal, this, this.document);
/**
* Text Resize.
*/
(function($, Drupal, window, document, undefined) {
function increase_font() {
$('html').addClass('large-fonts').trigger('font-size-change');
return false;
}
function decrease_font() {
$('html').removeClass('large-fonts').trigger('font-size-change');
return false;
}
Drupal.behaviors.dfata_theme_text_resize = {
attach: function(context, settings) {
$widget = $('.block-govcms-text-resize', context);
if ($widget.length > 0) {
$widget.find('.font-large').unbind('click', increase_font).bind('click', increase_font);
$widget.find('.font-small, a.reset').unbind('click', decrease_font).bind('click', decrease_font);
}
}
};
})(jQuery, Drupal, this, this.document);
/**
* Webform.js
*/
(function($, Drupal, window, document, undefined) {
var $grid_components = null;
var is_overflowing = null;
// Apply a class to grid element if table exceeds overflow width.
function component_grid_resize() {
for (var i = 0; i < $grid_components.length; i++) {
var $grid = $($grid_components[i]);
var $table = $grid.find('.webform-grid');
var has_overflow = $grid.width() < $table.width();
if (has_overflow && !is_overflowing) {
is_overflowing = true;
$grid.addClass('is-overflowing');
}
else if (!has_overflow && is_overflowing) {
is_overflowing = false;
$grid.removeClass('is-overflowing');
}
}
}
Drupal.behaviors.dfata_theme_webform = {
attach: function(context, settings) {
// Flip the order of radio checkboxes with labels.
// UI Kit styling only works if the label appears after.
$('.webform-grid-option > .form-type-radio', context).each(function() {
var $this = $(this);
$this.append($this.children('label'));
});
// Grid overflow - check on resize.
$grid_components = $('.webform-component-grid');
$(window).unbind('resize', component_grid_resize);
if ($grid_components.length > 0) {
component_grid_resize();
$(window).bind('resize', component_grid_resize);
}
}
};
})(jQuery, Drupal, this, this.document);
<file_sep>/dfata_theme/src/js/slider.js
/**
* Home page slider.
* An implementation of the Owl Carousel with custom controls.
*/
(function($, Drupal, window, document, undefined) {
function isDesktop() {
if ($('.mobile-expand-menu').is(':visible')) {
return false;
}
else {
return true;
}
}
Drupal.behaviors.front_page_news_carousel = {
attach: function(context, settings) {
// Init Owl Carousel
var owl = $(".view-latest-news.view-display-id-block_1 .view-content");
owl.owlCarousel({
singleItem: true,
autoPlay: 5000,
transitionStyle: 'fade',
addClassActive: true,
mouseDrag: false,
items: 1,
autoHeight: true,
afterUpdate: function() {
grabTitles();
}
});
// Pause on Item Click
$('.owl-controls').find('.owl-pagination').click(function() {
owl.trigger('owl.stop');
$(".owl-pause").hide();
$(".owl-play").show();
});
// Create Pause and play Buttons
$('.news-information').append(
'<span class="owl-pause"></span><span style="display:none;" class="owl-play"></span>');
// Functions to handle pause/play behaviour
$(".owl-pause").click(function() {
owl.trigger('owl.stop');
$('.owl-pause').hide();
$(".owl-play").show();
});
$(".owl-play").click(function() {
owl.trigger('owl.play', 5000);
$('.owl-play').hide();
$(".owl-pause").show();
});
function grabTitles() {
if (isDesktop()) {
// Grab the Carousel Titles and place them into pagination inside a wrapper div
var titles = [];
$('.news-information h3').each(function(index) {
titles[index] = $(this).text();
});
$('.owl-page').each(function(index) {
$(this).html('<div class="carousel-desk-title">' + titles[index] + '</div>');
});
}
}
grabTitles();
}
};
})(jQuery, Drupal, this, this.document);
|
0266ab73bc12f26b2509a981b7970dfd5f86a2db
|
[
"JavaScript"
] | 2
|
JavaScript
|
deanvucic/diplomaticacademy
|
e0225546dfe8048eb72c5947df15072e150e79eb
|
862a9f8c595af7bf1e35c07bc2b68d2e89480fce
|
refs/heads/master
|
<file_sep>/*Escuela Colombiana de ingenieria
En este programa se desarrolla el problema planteado por el profesor en la guia de laboratorio #4 en donde dadas dos matrices en formato .csv se realizan ciertas operaciones indicadas por el ususario ingresadas como argumento del programa.
Autor: <NAME>
Materia: ALSE-2
version 1.0
Septiembre 2020
*/
#include <stdio.h> //inclusion de librerias a usar
#include <string.h>
#include <stdlib.h>
#define MIN_ARG 4
#define MAX_ARG 6
#define MAX_FILE_SIZE 100
#define MAX 100
#define MAX_COL 10
#define MAX_FIL 10
void mostrar_ayuda();
void mostrar_version();
void suma_mat(float Matriz_A[MAX][MAX],float Matriz_B[MAX][MAX],float Matriz_C[MAX][MAX],int fa,int ca,int fb,int cb);
void rest_mat(float Matriz_A[MAX][MAX],float Matriz_B[MAX][MAX],float Matriz_C[MAX][MAX],int fa,int ca,int fb,int cb);
void paso_a_matriz(char buffer[MAX],float matriz[MAX][MAX],long int tam,int* fil,int* col);
void ciclo1 (char cad2[MAX], float matriz1[MAX][MAX],int longc2, int* col);
void ciclo2 (char cad2[MAX], float matriz[MAX][MAX],int longc2,int fil);
void cambio_a_matriz(char* argv[MAX],char buffer1[MAX],char buffer2[MAX],int fil[MAX],int col[MAX]);
void main (int argc, char *argv[MAX])
{
int bandera_1 = 0; //bandera utilizada para validar si el numero de argumentos es correcto
char buffer1[MAX];
char buffer2[MAX];
//long tam_matriz_a = 0, tam_matriz_b = 0;
//FILE *matr_a;
//FILE *matr_b;
float Matriz_A[MAX_COL][MAX_FIL], Matriz_B[MAX_COL][MAX_FIL], Matriz_C[MAX_COL][MAX_FIL], Matriz_D[MAX_COL][MAX_FIL];
int fa= 0,ca=0, fb=0, cb=0, i=0, j=0, k=0, bandera=0;
int fil[MAX],col[MAX];
if (argc != MIN_ARG && argc != MAX_ARG) //valida si el numero de argumentos es correcto o no
{
printf("\n¡¡¡Error!!! Se requieren como minimo cuatro argumentos y como maximo seis argumentos, intente nuevamente.\n\n");
bandera_1 = 1;
//si el numero de argumentos es incorrecto cambia el valor de la bandera por 1
}
if (bandera_1 == 0) //si el valor de la bandera no cambio, realiza el resto del programa
{
if (strcmp(argv[1],"--help") == 0 )
mostrar_ayuda();
else
{
if (strcmp(argv[1],"-v") == 0)
mostrar_version();
else
{
if ((strcmp(argv[1],"-r") == 0)/*||(strcmp(argv[1],"-a"))*/)
{
printf("HSHDUWHSUWHS");
cambio_a_matriz(argv,buffer1,buffer2,fil,col);
}
else
{
if (strcmp(argv[4],"-w") == 0)
{
printf("guardar nuevo");
}
//else
//printf("\nError en la eleccion de la operacion, el argumento ingresado no hace parte de las opciones.\n\n");
}
}
}
//fclose(matr_a);
//fclose(matr_b);
}
}
void mostrar_ayuda()
{
printf("\nLas opciones para seleccionar una funcion son:\n");
printf("\t-v (Muestra la version, autores y fecha)\n\t-t (Indica la transpuesta de las matrices)\n\t-a (Realiza la suma de las dos matrices)\n\t-r (Resta las dos matrices)\n\t-w (El resultado de la operación se guarda en un archivo con formato .CSV\n\t Se debe agregar ruta y nombre de donde se guardará el archivo)\n\n");
}
void mostrar_version()
{
printf("\n\tVersion: 1.0\n\tAutor: <NAME>\n\tFecha de desarrollo: Septiembre 2020\n\n");
}
void cambio_a_matriz(char* argv[MAX],char buffer1[MAX],char buffer2[MAX],int fil[MAX],int col[MAX])
{
long int tam_matriz_a =0, tam_matriz_b=0;
FILE *matr_a;
FILE *matr_b;
float ma1[MAX][MAX],ma2[MAX][MAX],ma3[MAX][MAX];
matr_a=fopen(argv[2],"r");
matr_b=fopen(argv[3],"r");
//printf("NEJNDUEHDUEDUJEIDJWIJDIWJDIWJD");
fseek(matr_a,0,SEEK_END);
tam_matriz_a=ftell(matr_a);
rewind(matr_a);
fseek(matr_b,0,SEEK_END);
tam_matriz_b=ftell(matr_b);
rewind(matr_b);
fread(buffer1, 1, tam_matriz_a, matr_a);
fread(buffer2, 1, tam_matriz_b, matr_b);
strcat(buffer1,"\0");
strcat(buffer2,"\0");
paso_a_matriz(buffer1,ma1,tam_matriz_a,&fil[0],&col[0]);
paso_a_matriz(buffer2,ma2,tam_matriz_b,&fil[1],&col[1]);
//if (strcmp(argv[1],"-a") == 0)
// {
// suma_mat(ma1,ma2,ma3,fil[0],col[0],fil[1],col[1]);
// }
// else
// {
// if (strcmp(argv[1],"-r") == 0)
// {
// rest_mat(ma1,ma2,ma3,fil[0],col[0],fil[1],col[1]);
// }
// else
// {
// if (strcmp(argv[1],"-t") == 0)
// {
// //mostrar_transpuesta();
// }
// }
// }
}
void paso_a_matriz(char buffer[MAX],float matriz[MAX][MAX],long int tam,int* fil,int* col)
{
int cont=0,i=1,j=0,longc1=0,longc2=0,longi1=0, longi=0,cont_fil=0,cont_col=0,longitot=0;
char *dir_simb1=0,*dir_simb2=0,*dir_simb3=0,*dir_simb4=0,*dir_1=0,*dir_2=0, *dir_3=0, *dir_4=0;
char cad1[MAX],cad2[MAX],numero1[MAX], numero[MAX];
float matriz1[MAX][MAX];
dir_1=buffer;
dir_simb1=strchr(buffer,'\n');
longc1=dir_simb1-buffer;
strncpy(cad1,buffer,longc1);
ciclo1(cad1,matriz,longc1,col);
while(longitot<tam-longc1)
{
dir_2=buffer+longc1+1;
dir_simb2=strchr(dir_2,'\n');
longc2=dir_simb2-dir_2;
strncpy(cad2,dir_2,longc2);
longitot=longc1;
longc1=longc1+1+longc2;
ciclo2(cad2,matriz,longc2,i);
*fil=i+1;
i++;
}
}
void ciclo1 (char cad2[MAX], float matriz1[MAX][MAX],int longc2, int* col)
{
int cont=0,longi=0,j=0;
char *dir_4=0,*dir_simb4=0;
char numero[MAX];
while(cont<longc2)
{
dir_4=cad2+longi;
dir_simb4=strchr(dir_4,';');
longi=dir_simb4-cad2;
strncpy(numero,dir_4,longi);
matriz1[0][j]=atof(numero);
j++;
longi=longi+1;
cont=longi;
}
*col=j;
}
void ciclo2 (char cad2[MAX], float matriz[MAX][MAX],int longc2,int fil)
{
int cont=0,longi=0,j=0;
char *dir_4=0,*dir_simb4=0;
char numero[MAX];
while(cont<longc2)
{
dir_4=cad2+longi;
dir_simb4=strchr(dir_4,';');
longi=dir_simb4-cad2;
strncpy(numero,dir_4,longi);
matriz[fil][j]=atof(numero);
j++;
longi=longi+1;
cont=longi;
}
}
void suma_mat(float Matriz_A[MAX][MAX],float Matriz_B[MAX][MAX],float Matriz_C[MAX][MAX],int fa,int ca,int fb,int cb)
{
int i=0, j=0;
for(i=0;i<fa;i++)
{
for(j=0;j<ca;j++)
{
Matriz_C[i][j]=Matriz_A[i][j]+Matriz_B[i][j];
}
}
printf("\n\n\tEl resultado de la suma de la matriz A con la matriz B es\n\n");
for(i=0;i<fa;i++)
{
for(j=0;j<ca;j++)
{
printf("%.3f\t",Matriz_C[i][j]);
}
printf("\n");
}
}
void rest_mat(float Matriz_A[MAX][MAX],float Matriz_B[MAX][MAX],float Matriz_C[MAX][MAX],int fa,int ca,int fb,int cb)
{
int i=0, j=0;
for(i=0;i<fa;i++)
{
for(j=0;j<ca;j++)
{
Matriz_C[i][j]=Matriz_A[i][j]-Matriz_B[i][j];
}
}
printf("\n\n\tEl resultado de la resta de la matriz A con la matriz B es\n\n");
for(i=0;i<fa;i++)
{
for(j=0;j<ca;j++)
{
printf("%.3f\t",Matriz_C[i][j]);
}
printf("\n");
}
}
|
43add02a85ea7caf4a9d0c3866b8ab9835af545e
|
[
"C"
] | 1
|
C
|
sergioq3/lab4_alse_operaciones_grupo8
|
1f7bb904c9485277f9fdcc9a06149568d8852193
|
99ff81239eff00c49834380d1b441f4d7394a79b
|
refs/heads/master
|
<repo_name>edwordguo/oracleConnect<file_sep>/src/main/java/com/huawei/utils/JDBCUtils.java
package com.huawei.utils;
/**
* @author rango
* @date 2019/3/11 22:20
*/
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/*
操作JDBC的工具类
*/
public class JDBCUtils {
//1. 构造方法私有.
private JDBCUtils() {
}
//2. 定义成员变量, 记录配置文件的信息.
private static String driverClass;
private static String url;
private static String username;
private static String password;
//3. 定义方法, 读取配置文件的信息, 并且赋值给变量.
public static void readConfig() {
try {
Properties pp = new Properties();
// pp.load(new FileReader("jdbc.properties"));
//String path = JDBCUtils.class.getClassLoader().getResource("jdbc.properties").getPath();
InputStream is = Thread.currentThread().getClass().getResourceAsStream("/jdbc.properties");
// System.out.println(path);
//FileInputStream in = new FileInputStream("路径是"+path);
pp.load(is);
//prop.getProperty("username");
driverClass = pp.getProperty("driverClass");
url = pp.getProperty("url");
username = pp.getProperty("username");
password = pp.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}
//4. 在静态代码块中, 完成注册驱动的动作.
static {
try {
//调用读取配置文件的方法.
readConfig();
Class.forName(driverClass);
System.out.println("注册驱动");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//5. 对我提供一个方法, 用来获取连接对象.
public static Connection getConnection() {
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//6. 释放资源.
public static void release(Connection conn, Statement stat, ResultSet rs) {
try {
if (rs != null) {
rs.close();
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stat != null) {
stat.close();
stat = null;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public static void release(Connection conn, Statement stat) {
try {
if (stat != null) {
stat.close();
stat = null;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
<file_sep>/src/main/java/com/huawei/post/MainPost.java
package com.huawei.post;
import com.sun.deploy.net.HttpRequest;
/**
* @author rango
* @date 2019/3/16 9:11
*/
public class MainPost {
public static void main(String[] args) {
//发送 GET 请求
// String s= HttpPost.sendGet("http://localhost:80/Home/RequestString", "key=123&v=456");
// System.out.println(s);
//发送 POST 请求
String sr=HttpPost.sendPost("http://write.blog.csdn.net/postedit","");
System.out.println(sr);
}
}
|
be46eb3ab2f354dde41d834546f3e74cd26e24e9
|
[
"Java"
] | 2
|
Java
|
edwordguo/oracleConnect
|
89383792e58e2af439f016b1cb810dae1d4f13d8
|
24b6c4f7ac391679645d330c913383ab91088a67
|
refs/heads/master
|
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::post('mess', 'MessController@store')->name('mess.store');
Route::get('mess', 'MessController@index')->name('mess.index');
Route::get('mess/create', 'MessController@create')->name('mess.create');
Route::get('mess/mess/{id}', 'MessController@show')->name('mess.show');
Route::get('mess/ushow', 'MessController@ushow')->name('mess.ushow');
Route::match(['put', 'patch'], 'mess/{mess}', 'MessController@markAsViewed')->name('mess.markAsViewed');
Route::get('mess/chat', 'MessController@chat')->name('mess.chat');
Route::get('chat/{request_id}', 'ChatController@index')->name('chat.index');
Route::get('chat/user/{request_id}', 'ChatController@user')->name('chat.user');
Route::post('chat/send-message', 'ChatController@sendMessage')->name('chat.send-message');<file_sep><?php
namespace App\Http\Controllers;
use App\Models\Chat;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Auth;
class ChatController extends Controller
{
protected $chat;
public function __construct()
{
$this->middleware('auth');
$this->chat = new Chat();
}
public function index($request_id)
{
if (Gate::allows('adminAction')){
$manager = true;
$messages = $this->chat->getChatMessages($request_id);
return view('chat.index')->with([
'request_id' => $request_id,
'messages' => $messages,
'manager' => $manager
]);
} else {
return redirect('/home')->with('error', 'You cannot view manager chat.');
}
}
public function user($request_id)
{
$manager = false;
$messages = $this->chat->getChatMessages($request_id);
return view('chat.index')->with([
'request_id' => $request_id,
'messages' => $messages,
'manager' => $manager
]);
}
public function sendMessage(Request $request)
{
$data = $request->all();
$isManager = Auth::user()->id == 1 ?? 0;
$this->chat::create([
'request_id' => $request->request_id,
'text' => $request->message,
'isManager' => $isManager
]);
return response()->json([
'status' => 'success',
'data' => [
'message' => $request->message,
'isManager' => $isManager ]
], 200);
}
}
<file_sep><?php
namespace App\Repositories;
use App\Models\Messages;
class MessRepository implements IMessRepository
{
protected $mess;
public function __construct(Messages $mess)
{
$this->mess = $mess;
}
public function storeMess(array $data, $userId, $filePath) : Messages
{
$newMess = new Messages();
$newMess->user_id = $userId;
$newMess->theme = $data['messageTheme'];
$newMess->message = $data['message'];
$newMess->file = array_key_exists('file', $data) == true ? null : $filePath;
$newMess->save();
return $newMess;
}
public function getMessById($messId)
{
return Messages::find($messId);
}
public function getAllMess()
{
return Messages::paginate(5);
}
public function markAsViewed($messId)
{
$mess= Messages::find($messId);
$mess->isViewed = true;
$mess->save();
}
public function getLatestUserMess($userId){
$mess = Messages::where('user_id', $userId)
->orderBy('created_at', 'desc')
->paginate(5);
return $mess;
}
public function getLastUserMessage($userId) {
return Messages::where(['user_id' => $userId])->orderBy('created_at', 'desc')->first();
}
}<file_sep><?php
namespace App\Repositories;
interface IMessRepository{
public function storeMess(array $data, $userId, $filePath);
public function getMessById($messId);
public function getAllMess();
public function markAsViewed($messId);
public function getLatestUserMess($userId);
public function getLastUserMessage($userId);
}<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Chat extends Model
{
const SEND_USER = 0;
const SEND_MANAGER = 1;
protected $table = 'chats';
protected $fillable = [
'request_id',
'text',
'isManager'
];
public function message()
{
return $this->belongsTo('App\Models\Messages', 'request_id');
}
public function getChatMessages($request_id)
{
return self::where(['request_id' => $request_id])->get();
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreMess;
use App\Mail\AdminMail;
use App\Models\Messages;
use App\Models\Chat;
use App\Repositories\MessRepository;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
class MessController extends Controller
{
protected $chat;
protected $messRepository;
public function __construct(MessRepository $messRepository)
{
$this->middleware('auth');
$this->chat = new Chat();
$this->messRepository = $messRepository;
}
public function index()
{
if(Gate::allows('adminAction')){
$allMess = $this->messRepository->getAllMess();
return view('mess.indexmess')->with(['mess' => $allMess]);
} else {
return redirect('/home')->with('error', 'You cannot view all mess');
}
}
public function create()
{
return view('mess.createmess');
}
public function store(StoreMess $request)
{
if(Gate::allows('makeMess')){
$mess = $this->messRepository->storeMess($request->input(), Auth::id(), $this->getFileNameToStore($request));
Mail::to("<EMAIL>")->send(new AdminMail($mess));
return redirect('/home')->with('success', 'Заявка отправлена');
}
else
return redirect('/home')->with('error', 'Заявку можно отправлять не чаще чем 1 раз в 5 минут.');
}
private function getFileNameToStore(StoreMess $request){
if ($request->hasFile('file')){
$filenameWithExt = $request->file('file')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('file')->getClientOriginalExtension();
$filenameToStore = $filename . '_' . time() . '.' . $extension;
$path = $request->file('file')->storeAs('public/files', $filenameToStore);
}
else
$filenameToStore = null;
return $filenameToStore;
}
public function show($id)
{
if(Gate::allows('adminAction')){
$mess = $this->messRepository->getMessById($id);
return view('mess.showmess', ['mess' => $mess]);
} else {
return redirect('/home')->with('error', 'You can not view this mess!');
}
}
public function markAsViewed(Request $request, $messId)
{
if(Gate::allows('adminAction')){
$this->messRepository->markAsViewed($messId);
$this->chat::create([
'request_id' => $messId,
'text' => 'Ваша заявка была просмотрена! Ожидайте ответа.',
'isManager' => Chat::SEND_MANAGER
]);
return redirect()->route('mess.index')->with('success', 'Сообщение отмечено прочитанным');
}
else
return redirect('/home')->with('error', 'You cannot perform this action');
}
public function ushow()
{
if(!Gate::allows('adminAction')){
$mess = $this->messRepository->getLatestUserMess(Auth::user()->id);
return view('mess.ushowmess', ['mess' => $mess]);
}
}
}<file_sep>-- phpMyAdmin SQL Dump
-- version 4.7.7
-- https://www.phpmyadmin.net/
--
-- Хост: 127.0.0.1:3307
-- Время создания: Янв 21 2019 г., 15:27
-- Версия сервера: 5.6.38
-- Версия PHP: 7.1.12
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 */;
--
-- База данных: `cubex`
--
-- --------------------------------------------------------
--
-- Структура таблицы `messages`
--
CREATE TABLE `messages` (
`id` int(10) UNSIGNED NOT NULL,
`user_id` int(10) UNSIGNED NOT NULL,
`theme` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`message` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`file` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`isViewed` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;
--
-- Дамп данных таблицы `messages`
--
INSERT INTO `messages` (`id`, `user_id`, `theme`, `message`, `file`, `created_at`, `updated_at`, `isViewed`) VALUES
(1, 2, 'ljhu', 'lkjhj', NULL, '2019-01-17 16:37:39', '2019-01-21 09:15:32', 1),
(2, 3, 'egergerg', 'fgbrbtrbtrb', NULL, '2019-01-18 14:38:49', '2019-01-18 14:39:58', 1),
(3, 2, 'sdfg', 'sdfg', NULL, '2019-01-18 16:28:42', '2019-01-18 16:37:05', 1),
(4, 3, 'dfvdfv', 'dfvdfv', NULL, '2019-01-21 09:25:49', '2019-01-21 09:25:49', 0),
(5, 3, 'dfvdfv', 'dfvdfv', NULL, '2019-01-21 09:26:55', '2019-01-21 09:26:55', 0),
(6, 3, 'dfvdfv', 'dfvdfv', NULL, '2019-01-21 09:27:19', '2019-01-21 09:42:28', 1),
(7, 3, 'fdgdfgdf', 'gdfgd', NULL, '2019-01-21 09:41:30', '2019-01-21 09:41:30', 0);
-- --------------------------------------------------------
--
-- Структура таблицы `migrations`
--
CREATE TABLE `migrations` (
`id` int(10) UNSIGNED NOT NULL,
`migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;
--
-- Дамп данных таблицы `migrations`
--
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES
(1, '2014_10_12_000000_create_users_table', 1),
(2, '2014_10_12_100000_create_password_resets_table', 1),
(3, '2019_01_17_112346_create_messages_table', 1);
-- --------------------------------------------------------
--
-- Структура таблицы `password_resets`
--
CREATE TABLE `password_resets` (
`email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;
-- --------------------------------------------------------
--
-- Структура таблицы `users`
--
CREATE TABLE `users` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`email_verified_at` timestamp NULL DEFAULT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`isAdmin` tinyint(1) NOT NULL DEFAULT '0',
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;
--
-- Дамп данных таблицы `users`
--
INSERT INTO `users` (`id`, `name`, `email`, `email_verified_at`, `password`, `isAdmin`, `remember_token`, `created_at`, `updated_at`) VALUES
(1, 'user1', '<EMAIL>', NULL, '$2y$10$opUYzKRKXijst6n1h0Crs.EIOdx3zjC1DaLTwYJr0QeARiRn5u2B.', 1, 'hlEjTiuZjgTdPlFrZb5PLA0A9LsXpd50m8QeNDBdOcQI4WeRsVCvrgFW2HYe', '2019-01-17 16:33:30', '2019-01-17 16:33:30'),
(2, 'guy1', '<EMAIL>', NULL, '$2y$10$7/py7ytt4pzvz3naKD0Ac.Ez.DAIm3fYISXsakxySif5bhuC/f4EW', 0, 'jz1qepOgzAU<PASSWORD>KLAfLnFfRyKQcIyio<PASSWORD>', '2019-01-17 16:35:02', '2019-01-17 16:35:02'),
(3, 'guy2', '<EMAIL>', NULL, '$2y$10$LGvBOIrO9YgLVo6lrezDKepjs6ubPSBVjjNcxatqn3ZbND9PdphSm', 0, 'hownk0B0DhVpcFTDr04Hh8tDyzPt0A45Rxv5AJ5ZwfKKpUqtUOMZ3CZLOnwa', '2019-01-18 14:38:40', '2019-01-18 14:38:40');
--
-- Индексы сохранённых таблиц
--
--
-- Индексы таблицы `messages`
--
ALTER TABLE `messages`
ADD PRIMARY KEY (`id`),
ADD KEY `messages_user_id_foreign` (`user_id`);
--
-- Индексы таблицы `migrations`
--
ALTER TABLE `migrations`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `password_resets`
--
ALTER TABLE `password_resets`
ADD KEY `password_resets_email_index` (`email`);
--
-- Индексы таблицы `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `users_email_unique` (`email`);
--
-- AUTO_INCREMENT для сохранённых таблиц
--
--
-- AUTO_INCREMENT для таблицы `messages`
--
ALTER TABLE `messages`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT для таблицы `migrations`
--
ALTER TABLE `migrations`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT для таблицы `users`
--
ALTER TABLE `users`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- Ограничения внешнего ключа сохраненных таблиц
--
--
-- Ограничения внешнего ключа таблицы `messages`
--
ALTER TABLE `messages`
ADD CONSTRAINT `messages_user_id_foreign` 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><?php
namespace App\Providers;
use App\Models\Messages;
use App\Repositories\MessRepository;
use DateTime;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('adminAction', function ($user) {
return $user->isAdmin;
});
Gate::define('makeMess', function ($user) {
$messRepository = new MessRepository(new Messages());
$latestMess = $messRepository->getLastUserMessage($user->id);
if($latestMess != null){
$dateTimestamp1 = new DateTime($latestMess->created_at);
$now = new DateTime();
$canMakeMess = $dateTimestamp1->diff($now);
$canMakeMess = ($canMakeMess->format('%i%') < 5) ? false : true;
return $canMakeMess;
}
else
return true;
});
}
}<file_sep><?php
namespace App\Mail;
use App\Models\Messages;
use Illuminate\Mail\Mailable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Storage;
class AdminMail extends Mailable
{
protected $mess;
public function __construct(Messages $mess)
{
$this->mess = $mess;
}
public function build()
{
$mail = $this->from('<EMAIL>', $this->mess->user->name)
->to('<EMAIL>')
->subject('You have new message '.$this->mess->user->name)
->view('emails.AdminMail')
->with(['theme' => $this->mess->theme,
'content' => $this->mess->message,
'createdAt' => $this->mess->created_at,
'userName' => $this->mess->user->name]);
if (!empty($this->mess->file))
$mail->attach(public_path('storage/files/'.$this->mess->file));
return $mail;
}
}
|
7d4e463eb05a548d3b47c75a4f1b2e3fd7acb5c0
|
[
"SQL",
"PHP"
] | 9
|
PHP
|
dinkavov/cubexTest
|
9fbd80a84a7121f8ec5f724601094cc2bad83564
|
a97472683ec48063961dc035dfbe721c7f5dff11
|
refs/heads/master
|
<file_sep>
import java.util.Date;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author treinamento
*/
public class Pedido {
private String numero;
private Date data;
private ItemPedido[] itensPedido;
private Pessoa pessoa;
public String getNumero() {
return this.numero;
}
public Date getData() {
return this.data;
}
public void setNumero(String numero) {
this.numero = numero;
}
public void setData(Date data) {
this.data = data;
}
public ItemPedido[] getItensPedido() {
return itensPedido;
}
public void setItensPedido(ItemPedido[] itensPedido) {
this.itensPedido = itensPedido;
}
public Pessoa getPessoa() {
return pessoa;
}
public void setPessoa(Pessoa pessoa) {
this.pessoa = pessoa;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author treinamento
*/
public class Pessoa {
private String nome;
private String rg;
private String cpf;
private String telefone;
private String enderco;
private Pedido[] pedidos;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getRg() {
return rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getEnderco() {
return enderco;
}
public void setEnderco(String enderco) {
this.enderco = enderco;
}
public Pedido[] getPedidos() {
return pedidos;
}
public void setPedidos(Pedido[] pedidos) {
this.pedidos = pedidos;
}
}
<file_sep>AJTF 86
======
Repositório das aulas de Academia Java Turma 86
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author treinamento
*/
public abstract class FormatadorRecibo {
public abstract String gerarRecibo(String cliente,
double valor,
String data,
String motivo);
}
|
922eba07b76b0ff409c006a2523d90a5be7a1ba9
|
[
"Markdown",
"Java"
] | 4
|
Java
|
lapavila/ajtf86
|
e1d746aa71d0bbe1bc1357d2f300df16b46b79a3
|
6bde81d1c49d14a56b77e8f04ecc9ab05eb585d9
|
refs/heads/master
|
<repo_name>Antiproton7/VisualDisplacement<file_sep>/README.md
# VisualDisplacement
OpenCV LK flow point displacement Tracker
<file_sep>/SparseOptical VDT.py
'''
Using LK sparse optical flow to compute real-world displacements for tracked points.
User commands:
G rab locations of tracked points
P ause/ resume the video feed
M (when paused) opens and closes the measurement frame
When in measure mode, LMB adds a point to measure
RMB clears measure point
eXit, saving video
E xport deltas to CSVy
Options are set in Settings.cfg
'''
import numpy as np
import tkinter
from tkinter import filedialog
import cv2
from csv import writer
from collections import deque
from Utils import detectBestPoint,cropCenter#, plotgraph
import Config
root = tkinter.Tk() #File open dialog
root.withdraw()
# Parameters for lucas kanade optical flow
lk_params = dict( winSize = (8,8),
maxLevel = 2,
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 5, 0.03))
class VDT:
def __init__(self, video_src):
self.cap = cv2.VideoCapture(video_src)
self.tracks = []
self.snapshots=[]
self.MeasurePts=deque(maxlen=2)
self.mask=0
self.frame=0
self.frame_gray=0
self.pTemplates=[]
self.maxes=[]
def mouseClick(self,event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
newTrack=deque(maxlen=Config.opts['track_len'])
self.snapshots.append(deque(maxlen=50)) #add new point track to snapshots
x,y=detectBestPoint(self.frame_gray,x, y,10) #find a good point near where the user clicked
newTrack.append((x,y))
self.tracks.append(newTrack)
pointTemplate=cropCenter(self.frame_gray,x,y,15)
self.pTemplates.append(pointTemplate)
self.maxes.append((0,0))
Npts=len(self.tracks)
print ("Added point" + str(Npts-1))
def CSVexport(self,output):
with open('TrackData.csv', 'wb') as f:
CSVwriter = writer(f)
CSVwriter.writerow(['Point displacements (Dx,Dy)','mode='+str(Config.opts['deltaMode'])])
CSVwriter.writerows(output)
def displaceMap(self,deltaP,deltaT,correction,distance,FOV,RES,FPS):
FOV=np.deg2rad(FOV)
bFactor=distance*np.sin(FOV)/np.cos(FOV/2.0)
deltaReal=bFactor/RES*deltaP*correction
deltaReal=tuple([round(i,1) for i in deltaReal]) #truncate values
deltaDisplay= str(deltaReal) #stringify
dist=np.linalg.norm(deltaReal) #compute magnitude of dispalcement vector
speed=dist*FPS/deltaT
return deltaReal,deltaDisplay,speed
def reattach(self,lastPoint,searchDist,template):
x,y=lastPoint
x=int(x)
y=int(y)
d=searchDist
region=self.frame_gray[y-d:y+d, x-d:x+d] #crop to ROI
res = cv2.matchTemplate(region,template,cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if max_val>0.92:
w, h = template.shape[::-1]
x,y=(max_loc[0]+w/2,max_loc[0]+h/2) #compute middle of the region since we detect the corner?
x,y=int(lastPoint[0]-d+x),int(lastPoint[1]-d+y)
self.mask=cv2.circle(self.mask, (x,y), 10, (0,0, 255), 2) #red point to show the found location
newCenter=detectBestPoint(self.frame_gray,x,y,5)
print ("Found Point",newCenter)
return newCenter
else:
return False
def grabPoints(self,mode):
displacements=[]
speeds=[]
prev_point=(0,0)
prev_framePos=0
framePos=self.cap.get(cv2.CAP_PROP_POS_FRAMES) #get frame index
for tr,snp in zip(self.tracks,self.snapshots):
snp.append((framePos,tr[-1])) #append latest video position and point to the snapshot for each track
deltaRow=[]
speedRow=[]
(firstFrame,(firstPoint))=snp[0]
for frameIDX,point in snp:
deltaP=0
if not mode: #initial offset
self.mask=cv2.circle(self.mask,(firstPoint),8,(0,255,0),1)
self.mask=cv2.line(self.mask, (firstPoint),(point), (0,255,0), 3)
deltaP=np.subtract(point,firstPoint)
deltaT=frameIDX-firstFrame
elif mode: #continous delta
self.mask=cv2.circle(self.mask,(prev_point),8,(0,255,0),1)
self.mask = cv2.line(self.mask, (prev_point),(point), (0,255,100), 2)
deltaP=np.subtract(point,prev_point)
deltaT=frameIDX-prev_framePos
if point!=firstPoint:
deltaReal,deltaDisplay,speed=self.displaceMap(deltaP,deltaT,**Config.cam_prms)
displayPoint=(int(point[0]),int(point[1]))
displayPoint=tuple(np.add(displayPoint,(2,-25)))
self.mask=cv2.putText(self.mask, "D"+deltaDisplay, displayPoint, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), lineType=cv2.LINE_AA) #display point readout
speedRow.append(round(speed,1))
deltaRow.append(deltaReal)
prev_point=point
prev_framePos=frameIDX
displacements.append(deltaRow)
speeds.append(speedRow)
print ("Displacements (mm)")
print('\n'.join([' '.join([ str(tup) for tup in row]) for row in displacements]))
print ("Speeds (mm/s)")
print('\n'.join([''.join(['%5s' % spd for spd in row]) for row in speeds]))
return displacements,speeds
def measure(self,event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
overlay=np.zeros_like(self.frame)#create drawing mask
self.MeasurePts.append((x, y))
for i in self.MeasurePts:
x,y=i
cv2.circle(overlay, (x, y), 5, (255,0, 0), 5) #draw a circle to mark the point
if len(self.MeasurePts)>1:
loc=self.MeasurePts
delta=np.subtract(loc[1],loc[0])
_real,deltaDisplay,norm=self.displaceMap(delta,Config.cam_prms["FPS"],**Config.cam_prms)
print (deltaDisplay, norm)
cv2.putText(overlay,"Dx,Dy:"+deltaDisplay+ " Norm:"+ str(round(norm,1)), (x,y), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), lineType=cv2.LINE_AA)
cv2.arrowedLine(overlay,loc[0],loc[1],(255,255,255),thickness=3) #normLine
Xpoint=(loc[1][0],loc[0][1])
cv2.arrowedLine(overlay,loc[0],Xpoint,(0,255,0),thickness=3) #XLine
cv2.arrowedLine(overlay,Xpoint,loc[1],(0,0,255),thickness=3) #YLine
visM=cv2.add(self.frame,overlay)
cv2.imshow("frame",visM)
elif event== cv2.EVENT_RBUTTONDOWN:
self.MeasurePts.clear()
cv2.imshow("frame",self.frame)
def run(self):
paused=False
fourcc=cv2.VideoWriter_fourcc(*'FMP4') #codec
downScale=Config.opts["downScale"]
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) #contrast-limited histogram equalization
#Take first frame
_ret, self.frame = self.cap.read()
Config.cam_prms['RES']=np.array([self.cap.get(3)*downScale,self.cap.get(4)*downScale]) #set resolution based on input video and apply downscaling
Config.cam_prms['FPS']=self.cap.get(cv2.CAP_PROP_FPS)
self.out = cv2.VideoWriter("Tracked.avi",fourcc, Config.cam_prms['FPS'], tuple( [int(i) for i in Config.cam_prms['RES']]))
self.frame=cv2.resize(self.frame, (0,0), fx=downScale, fy=downScale) #resize the image
self.mask=np.zeros_like(self.frame)
Config.cam_prms['distance']=int(input("Enter camera distance (mm): "))
print ("Select points to track")
cv2.namedWindow('frame')
cv2.setMouseCallback('frame', self.mouseClick)
lostPoints=[]
while True:
while paused: #paused subroutine halts video feed
cv2.imshow('frame',vis) #show the last frame
k = cv2.waitKey(0)
if k==ord('p'):
paused=False
elif k==ord('m'):
cv2.setMouseCallback('frame', self.measure)
cv2.putText(self.frame, "Select two points to measure, Rightclick to clear", (30, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), lineType=cv2.LINE_AA)
cv2.imshow("frame",vis)
cv2.waitKey(0) #press any key to exit measure mode
cv2.setMouseCallback('frame', self.mouseClick)
videoRead,self.frame = self.cap.read() #get next video frame
if not videoRead: #detect end of video
break
timer = cv2.getTickCount() #for computing FPS
self.frame = cv2.undistort(self.frame, Config.distortComp['Cmtx'], Config.distortComp['distortion']) #Lens distortion compensation
self.frame=cv2.resize(self.frame, (0,0), fx=downScale, fy=downScale) #resize the image to make it more managable for processing
self.frame_gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
if Config.opts['useCLAHE']:
frame_track= clahe.apply(self.frame_gray) #histogram equalization to boost contrast
else: frame_track=self.frame_gray
vis = self.frame.copy()
if len(self.tracks) > 0: #wait for us to have points before we try to track them
#occlCount=[]
p0 = np.float32([tr[-1] for tr in self.tracks]).reshape(-1, 1, 2)
p1, st, _err = cv2.calcOpticalFlowPyrLK(self.prev_gray, frame_track, p0, None, **lk_params) #compute optical flow
p0r, _st, _err = cv2.calcOpticalFlowPyrLK(frame_track, self.prev_gray, p1, None, **lk_params) #back-track to make sure points are nice
d = abs(p0-p0r).reshape(-1, 2).max(-1)
good = d < 1 # Select good pnts
for idx, (tr, (x, y),good_flag) in enumerate(zip(self.tracks, p1.reshape(-1, 2),good)):
if not good_flag: #skips over badly tracked points
print ("Lost "+"P"+str(idx))
a=idx
if idx in lostPoints: #handles multiple point loss on same frame avoiding bugs with re-enumeration
a=idx+1
lostPoints.append((a,self.pTemplates[idx],x,y,self.snapshots[idx])) #last seen point and all its data
del self.snapshots[idx] #delete snapshots associated with these points to avoid breaking measurments due to reindexing
del self.tracks[idx] #delete track
continue
tr.append((x, y)) #add good points to track
cv2.circle(vis, (x, y), 4, (0,255, 0), -1) #mark good points with filled green circle
cv2.putText(vis, "P"+str(idx), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), lineType=cv2.LINE_AA) #display point index
window=Config.opts['speedWindow']
if len(tr)>2*window and (tr[-window]!=tr[-1]):
diff=np.subtract(tr[-1],tr[-window]) #compute the speed of the point over the last n frames, length determined by window
_thing,_curD,curS=self.displaceMap(diff,window,**Config.cam_prms)
meme=np.add(tr[-1],tr[-2*window])
accel=np.linalg.norm(np.subtract(meme,np.multiply(tr[-window],2.0)))/(np.power(window,2)) #2nd order backwards finite difference
accel*=Config.cam_prms['FPS'] #convert from mm/frame to mm/s
if curS>1.1:
cv2.putText(vis, "S:"+str(round(curS,1)), (x, int(y+10)), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), lineType=cv2.LINE_AA) #print current speed
v,a=self.maxes[idx]
if curS>v:
v=curS
if accel>a:
a=accel
self.maxes[idx]=(v,a)#maxes
cv2.polylines(vis, [np.int32(tr) for tr in self.tracks], False, (255,255, 255),thickness=3) #draw a path behind the point
"""if lostPoints: #check if empty
for m,(index,template,x,y,snapshots) in enumerate(lostPoints):
cv2.circle(vis, (x, y), 4, (0,0, 255), -1) #mark bad points with filled red circle
newCenter=self.reattach((x,y),60,template) #attempt to re-detect lost points based on template matching
if newCenter:
newTrack=deque(maxlen=Config.opts['track_len'])
newTrack.append((x,y))
self.tracks.insert(index,newTrack) #re-add the lost points at their original position
self.snapshots.insert(index,snapshots) #re-add the snapshots stored for this point.
del lostPoints[m]
"""
self.prev_gray = frame_track
vis=cv2.rectangle(vis,(15,5),(100,30),(0,0,0),-1)
fps = round(cv2.getTickFrequency() / (cv2.getTickCount() - timer),1)
vis=cv2.putText(vis, "FPS"+str(fps),(20,20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), lineType=cv2.LINE_AA) #display FPS
vis=cv2.add(vis,self.mask)
cv2.imshow('frame',vis)
self.out.write(vis) #output videoxs
k = cv2.waitKey(1)
if k ==ord('x'):
print("Max speed, Max Accel")
print(self.maxes)
break #exit the program
elif k==ord('g'):
self.mask=np.zeros_like(self.frame)
deltas,speeds=self.grabPoints(Config.opts['deltaMode']) #Grabs points and computes displacements
elif k==ord('p'):
paused=True
elif k==ord('h'):
plotgraph(self.tracks)
elif k==ord('e'):
self.CSVexport(deltas) #export displacements to CSV
self.out.release() #cleanup, very important
self.cap.release()
def main():
try:
video_src = filedialog.askopenfilename(title = "Select video file",filetypes = (("Video Toast","*.mp4"),("all files","*.*")))
except:
video_src = 0
print(__doc__)
VDT(video_src).run()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
<file_sep>/Utils.py
import cv2
import numpy as np
import matplotlib as mplot
# params for ShiTomasi corner detection
feature_params = dict(qualityLevel = 0.05,
minDistance = 7,
blockSize = 7 )
def white_balance(img):
result = cv2.cvtColor(img, cv.COLOR_BGR2LAB)
avg_a = np.average(result[:, :, 1])
avg_b = np.average(result[:, :, 2])
result[:, :, 1] = result[:, :, 1] - ((avg_a - 128) * (result[:, :, 0] / 255.0) * 1.1)
result[:, :, 2] = result[:, :, 2] - ((avg_b - 128) * (result[:, :, 0] / 255.0) * 1.1)
result = cv2.cvtColor(result, cv.COLOR_LAB2BGR)
return result
def detectBestPoint(img_gray,x,y,radius):
msk=np.zeros_like(img_gray)
msk=cv2.circle(msk,(x,y),radius,(255,0,0),-1)
points=cv2.goodFeaturesToTrack(img_gray, mask = msk, maxCorners=1,**feature_params) #select best Shi-Tomasi point in radius around click
#self.frame=cv2.circle(self.frame, (x,y), 2, (0,0, 255), -1) #blue is click point
if points is not None:
x,y=points[0,0,:2]
#self.frame=cv2.circle(self.frame, (x,y), 2, (255,0, 0), -1) #red is best point
#cv2.imshow("Click Ref",self.frame)
#cv2.waitKey(1)
return (x,y)
else:
return False
def maskMaker(img,x,y,typ,size,invert):
mask = np.zeros_like(img)
if typ=="Circle":
mask=cv2.circle(mask,(x,y),size,255,-1)
elif typ=="Square":
mask=cv2.rectangle(mask,(x+size/2,y+size/2),(x-size/2,y-size/2),255,-1)
if invert:
mask=np.invert(mask)
return mask
def cropCenter(img,x,y,size):
x=int(x)
y=int(y)
img=img[y-size:y+size,x-size:x+size]
return img
"""def plotgraph(dataPoints,window):
for tr in dataPoints:
for index, point in enumerate(tr):
deltaP=np.subtract(,firstPoint)"""<file_sep>/Misc/Post_Trigger.py
import numpy as np
import cv2
from collections import deque
class App:
def __init__(self, video_src):
self.cap = cv2.VideoCapture(video_src)
self.fourcc=cv2.VideoWriter_fourcc(*'FMP4') #codec
self.buffer=deque(maxlen=300) #frame buffer, don't set this above 15000
self.RES=() #output resolution
def mouseClick(self,event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
print "Click"
def postCapture(self,buffer):
self.cap.release()
out = cv2.VideoWriter('output.avi',self.fourcc, 30, self.RES)
for frame in buffer:
out.write(frame)
out.release
cv2.destroyAllWindows()
def run(self):
cv2.namedWindow('frame')
cv2.setMouseCallback('frame', self.mouseClick)
frame_width = int(self.cap.get(3))
frame_height = int(self.cap.get(4))
self.RES=(frame_width,frame_height)
while True:
_ret,self.frame = self.cap.read()
cv2.imshow('frame',self.frame)
k = cv2.waitKey(1)
self.buffer.append(self.frame)
if k ==ord('x'):
self.postCapture(self.buffer)
break
self.cap.release()
def main():
#import sys
try:
video_src = 0
except:
video_src = 0
print(__doc__)
App(video_src).run()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
<file_sep>/Misc/UI-Eye.py
import cv2 as cv
import numpy as np
from glob2 import glob
from matplotlib import pyplot as plt
from tkinter import filedialog
img_mask = 'Demos/UI/headrest*.png' # default
search_path=filedialog.askopenfilename(title = "Select search image",filetypes = (("Image Toast","*.png"),("all files","*.*")),initialdir="Demos/UI")
template = cv.imread(search_path) #do not compress template otherwise color space is skewed
chans=cv.split(template)
colors = ("b", "g", "r")
templateChans=[]
for (chan, color) in zip(chans, colors):
hist = cv.calcHist([chan], [0], None, [256], [0, 256])/(chan.size)
templateChans.append(hist)
# plot the histogram
#plt.plot(hist, color = color)
#plt.xlim([0, 256])
#plt.show()
template = cv.cvtColor(template, cv.COLOR_BGR2GRAY)
#hist_Template = cv.calcHist([template], [0], None, [265], [0, 256])
#plt.figure()
img_names = glob(img_mask)
def checkImage(fn):
colorMatch=True
img = cv.imread(fn)
#print("Processing...",fn)
if img is None:
print("Failed to load", fn)
return None
vis = img.copy()
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
w, h = template.shape[::-1]
# Apply template Matching
res = cv.matchTemplate(img,template,cv.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
if (max_val>0.9):
mask=np.zeros_like(img)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv.rectangle(mask,top_left, bottom_right, 255, -1)
chans=cv.split(vis)
plt.title("%s" % fn)
diffs=[]
for (chan, color,tempHist) in zip(chans, colors,templateChans):
hist = cv.calcHist([chan], [0], mask, [256], [0, 256])/(cv.countNonZero(mask))
diff=abs(hist-tempHist)
plt.plot(diff, color = color)
diffs.append(diff)
match=not any(t>.1 for t in diff)
plt.xlim([0, 256])
colorMatch=match and colorMatch
#plt.show()
#print ("Colormatch:",colorMatch)
cv.rectangle(vis,top_left, bottom_right, (0,255,0), 5)
print("Found template in %s" % fn)
else:
print ("Template not found %s" % fn)
cv.putText(vis, "Template not found", (30, 100), cv.FONT_HERSHEY_SIMPLEX, 4, (255, 255, 255), lineType=cv.LINE_AA, thickness=6)
if not colorMatch:
print ("Color Match Failed %s" % fn)
cv.putText(vis, "Wrong Color", (30, 100), cv.FONT_HERSHEY_SIMPLEX, 4, (255, 255, 255), lineType=cv.LINE_AA, thickness=6)
return vis
threadn = 1#cv.getNumberOfCPUs()
print("Run with %d threads..." % threadn)
from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(threadn)
if threadn==1:
detections=[checkImage(i) for i in img_names]
cv.waitKey(1000)
#detections = pool.map(checkImage, img_names)
cv.namedWindow("Results")
for i in detections:
i=cv.resize(i, (0,0), fx=0.5, fy=0.5) #resize the image
cv.imshow("Results",i)
cv.waitKey(0)<file_sep>/Config.py
import numpy as np
inputFile="SJ5000XCalibration.npz"
npzfile = np.load(inputFile) #load camera parameters
#Run Options
opts={
"deltaMode":0,
"speedWindow":3,
"downScale":0.8,
"useCLAHE":1,
"track_len":100,
}
cam_prms = {
"correction":.91,#correction factor experimentally observed
"FOV":np.array([170,70]),
}
distortComp={
'Cmtx':npzfile['Cmtx'],
'distortion':npzfile['distortion'] #parameters computed using calibrate.py
}
|
d0bd5f47381edc6a3c2198a92500f6aae632c509
|
[
"Markdown",
"Python"
] | 6
|
Markdown
|
Antiproton7/VisualDisplacement
|
13106297891ff14f9a14bc3b8118c6df9c3a25be
|
47a8f33d749d8b32b94b20d6b8dc5a02ffe08a6c
|
refs/heads/main
|
<file_sep><?php
namespace IfWrong\ParamsIO;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\MessageBag;
trait ValidateParamsIO
{
/**
* 验证器
* @var Validator
*/
protected $validator = null;
/**
* validator验证规则
* @var array
*/
protected $rules = [];
/**
* validator错误信息
* @var array
*/
protected $messages = [];
/**
* 入餐错误
* @return MessageBag
*/
public function errors()
{
return $this->getValidator()->errors();
}
/**
* 验证是否成功
* @return bool
*/
public function fails()
{
return $this->getValidator()->fails();
}
/**
* 获取待验证数据
* @return mixed
*/
abstract public function getData();
/**
* 实现获取验证规则
* @return mixed
*/
abstract public function getRules();
/**
* 获取消息
* @return mixed
*/
abstract public function getMessages();
/**
* 生成验证器
* @return \Illuminate\Contracts\Validation\Validator|Validator
*/
public function getValidator()
{
$validator = $this->validator;
if (is_null($validator)) {
$validator = $this->validator = Validator::make($this->getData(), $this->getRules(), $this->getMessages());
}
return $validator;
}
}
<file_sep># params-io
## 简介
laravel复杂控制器终结者。我们先说下使用控制器过程中的痛点
##### 1.请求中的参数可能并不完全是你实际使用的参数,各种条件性赋值,破坏原始变量
##### 2.打印函数输入、输出及中间调用日志
##### 3.控制器逻辑冗长,完全面向过程,流程看不懂,只要是个人就看不懂(因为只有机器能懂,还有写这个逻辑的怪胎,它不算人)
##### 4.版本快速迭代,多版本控制代码融合在一起
##### 5.函数入参验证
##### 6.函数参数设置太多,有些是必填,有些是默认就OK,但是因为顺序设置不合理,导致默认的参数也要手动填写下,后续想扩展下也费劲
##### 7.控制器入参多,只能在使用的地方找定义,该函数到底需要几个参数,没人讲的清楚。就算有文档也可能更新不及时,程序和代码有出入
具体请查看技术文档 https://www.yuque.com/gtgyongchuangtianya60/omp7g3
<file_sep><?php
namespace IfWrong\ParamsIO;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
/**
* 类参数IO
* Class ParamsIO
*
*/
class ParamsIO
{
use ValidateParamsIO;
/**
* 日志tag
*
* @var string
*/
protected $logTag = '';
/**
* 自定义mget忽略属性
*
* @var array
*/
protected $except = [
'camelKey',
'greedy',
'logTag',
'except',
'validator',
'rules',
'messages',
];
/**
* 初始化的时候没有定义的属性是否保存
* @var bool
*/
protected $greedy = true;
/**
* 将字段转化为驼峰形式
* @var bool
*/
protected $camelKey = true;
/**
* ParamsIO constructor.
*
* @param null|self|array $props
* @param $logTag
*/
public function __construct($props = null, $logTag = '')
{
if ($logTag) {
$this->logTag = $logTag;
}
if ($props) {
if ($this->greedy) {
$dst = is_array($props) ? ($this->camelKey ? $this->camelKeys($props) : $props) : $props->mget();
} else {
$keys = $this->keys();
if (is_array($props)) {
$dst = Arr::only(($this->camelKey ? $this->camelKeys($props) : $props), $keys);
} else {
$dst = $props->mget($keys);
}
}
$this->mset($dst, $this->camelKey);
}
}
/**
* 将key设置为驼峰类型
* @param array $vals
* @return array
*/
public function camelKeys($vals = [])
{
$newVals = [];
foreach ($vals as $key => $val) {
$newKey = Str::camel($key);
$newVals[$newKey] = $val;
}
return $newVals;
}
/**
* 批量获取属性
*
* @param array $keys
* @return array
*/
public function mget($keys = [], $except = [])
{
$except = array_merge($this->except, $except);
$vals = [];
if (is_array($keys)) {
if (!$keys) {
$keys = array_keys(get_object_vars($this));
}
$keys = array_diff($keys, $except);
foreach ($keys as $key) {
$val = $this->getAttr($key);
if (!is_null($val)) {
$vals[$key] = $val;
}
}
}
return $vals;
}
/**
* 获取可用的keys
* @param array $except
* @return array
*/
public function keys($except = [])
{
$except = array_merge($this->except, $except);
$keys = array_keys(get_object_vars($this));
return array_diff($keys, $except);
}
/**
* 获取属性
*
* @param $key
* @return array|mixed
*/
protected function getAttr($key)
{
$method = $this->getAttrMethodName($key);
if (method_exists($this, $method)) {
return $this->$method();
} else {
return data_get($this, $key);
}
}
/**
* 获取动态属性的方法名
* @param $key
* @return string
*/
protected function getAttrMethodName($key)
{
return sprintf('get%sAttr', ucfirst($key));
}
/**
* 批量设置属性
*
* @param array $vals
* @param bool $camelKey
*/
public function mset($vals = [], $camelKey = true)
{
if (is_array($vals)) {
if ($camelKey) {
$vals = $this->camelKeys($vals);
}
foreach ($vals as $key => $val) {
data_set($this, $key, $val);
}
$extraKeys = array_diff($this->keys(), array_keys($vals));
foreach ($extraKeys as $extraKey) {
$method = $this->getAttrMethodName($extraKey);
if (method_exists($this, $method)) {
data_set($this, $extraKey, $this->$method());
}
}
}
}
/**
* 输入参数打印
*
* @param array $input
* @param string $message
*/
public function in($input = [], $message = 'In')
{
if ($input) {
$input = is_array($input) ? $input : [$input];
} else {
$input = $this->mget();
}
$this->info($message, $input);
}
/**
* 打印日志
*
* @param $message
* @param array $context
*/
public function info($message, $context = [])
{
$context = is_array($context) ? $context : [$context];
Log::info($this->logTag . '|' . $message, $context);
}
/**
* 打印错误日志
*
* @param $message
* @param array $context
*/
public function error($message, $context = [])
{
$context = is_array($context) ? $context : [$context];
Log::error($this->logTag . '|' . $message, $context);
}
/**
* 输出参数打印
*
* @param array $output
* @param string $message
* @return array[]|bool
*/
public function out($output = [], $message = 'Out')
{
$output = is_array($output) ? $output : [$output];
$this->info($message, $output);
return $output;
}
/**
* 返回待验证数据
*
* @return array
*/
public function getData()
{
return $this->mget();
}
/**
* 获取验证规则
*
* @return array
*/
public function getRules()
{
return $this->rules;
}
/**
* 获取验证消息
*
* @return array
*/
public function getMessages()
{
return $this->messages;
}
/**
* @param $key
* @return array|mixed
*/
public function __get($key)
{
return $this->getAttr($key);
}
/**
* @param $key
* @param $val
*/
public function __set($key, $val)
{
data_set($this, $key, $val);
}
}
|
ac1c36c7486b971daabadfcc1a620dcdfa7e22e6
|
[
"Markdown",
"PHP"
] | 3
|
PHP
|
ifwrong/params-io
|
a18b3dda1ac49a4047db6a0c908df1ae090aaab9
|
8e1907c825288177f09590b8a270f1c1d0c5335e
|
refs/heads/main
|
<repo_name>cotte06/Log-In-master<file_sep>/README.md
# Log-In
This is a simple iOS login screen written in Swift 5. It has the classic email & password format.
# Prerequisites
Make sure you have cocoapods installed on your computer, and if you don't you can just copy the following line in terminal and run it :
```
$ sudo gem install cocoapods
```
# Installation and configuration
First, you need to clone this repository, in order to fetch the code.
```
$ https://github.com/cotte06/Log-In.git
```
In order to compile your code, you need to install the dependencies first (in our case, the Firebase pods). You can simply do this by running the following command in Terminal (cd in your corresponding file) :
```
$ pod install
```
Once the pods were installed properly, open Prueba.xcworkspace with Xcode and run the project.
# Built With
* [FireBase](https://firebase.google.com/?gclid=CjwKCAiA8Jf-BRB-EiwAWDtEGm6r6p4VbtpdMEfbC7MSYJN2Ftdp0o46YdClOS6cBCFRyzjAF2BLIhoCPMUQAvD_BwE) - User database
<file_sep>/Prueba/ConfigurationViewController.swift
//
// ConfigurationViewController.swift
// Prueba
//
// Created by <NAME> on 28-09-20.
//
import UIKit
class ConfigurationViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
<file_sep>/Prueba/ResetPasswordViewController.swift
//
// ResetPasswordViewController.swift
// Prueba
//
// Created by <NAME> on 29-09-20.
//
import UIKit
import Firebase
class ResetPasswordViewController: UIViewController {
@IBOutlet var emailAddressTextfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tableViewTapped))
view.addGestureRecognizer(tapGesture)
}
@IBAction func resetPasswordButtonPressed(_ sender: UIButton) {
Auth.auth().sendPasswordReset(withEmail: emailAddressTextfield.text!) { (error) in
if error != nil{
let alert = UIAlertController(title: "Invalid email address.", message: "Try again!", preferredStyle: .alert)
let accion = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(accion)
self.present(alert, animated: true, completion: nil)
}
else {
let alert = UIAlertController(title: "We have sent you a new password to your email!", message: "", preferredStyle: .alert)
self.present(alert, animated: true, completion: nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
self.dismiss(animated: true, completion: nil)
}
self.dismiss(animated: true, completion: nil)
}
}
}
@objc func tableViewTapped() {
view.endEditing(true)
}
}
|
335d1ab4b768592544d3313ee996b77df2a0ea67
|
[
"Markdown",
"Swift"
] | 3
|
Markdown
|
cotte06/Log-In-master
|
c35dd6fca793dd6b4cfe5c5a64e61a2238618c3b
|
1103ba10635fbe7650d2c7d6b5970e20f09fe02b
|
refs/heads/master
|
<repo_name>gmerritt/model-elements<file_sep>/src/main/java/edu/berkeley/path/model_elements/JsonHandler.java
/**
* Copyright (c) 2012 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
*/
package edu.berkeley.path.model_elements;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericContainer;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;
/**
* Read and write model elements objects from/to .json files.
* @author amoylan
*/
public class JsonHandler {
public static <T extends GenericContainer> void writeToFile(T obj, String filename) throws IOException {
Schema schema = obj.getSchema();
FileOutputStream file = new FileOutputStream(new File(filename));
Encoder e = new EncoderFactory().jsonEncoder(schema, file);
DatumWriter<T> writer = new SpecificDatumWriter<T>(schema);
writer.write(obj, e);
e.flush();
file.close();
}
/**
* Read a model elements object from the specified .json file
* @param <T> Model elements type read, e.g. Network or Link
* @param schema Avro schema. Should be T.SCHEMA$
* @param filename .json file to read from
* @return Model elements object of type T
* @throws IOException
*/
public static <T extends GenericContainer> T readFromFile(Schema schema, String filename) throws IOException {
// Joel's trick: Tell Avro to create model_elements classes instead of model_elements_base classes
Schema.Parser parser = new Schema.Parser();
String schemaStr = schema.toString().replaceFirst(
"\"namespace\":\"edu.berkeley.path.model_elements_base\"",
"\"namespace\":\"edu.berkeley.path.model_elements\"");
Schema schemaForReading = parser.parse(schemaStr);
DatumReader<T> reader = new SpecificDatumReader<T>(schemaForReading);
FileInputStream file = new FileInputStream(new File(filename));
Decoder decoder = new DecoderFactory().jsonDecoder(schemaForReading, file);
T obj = reader.read(null, decoder);
file.close();
return(obj);
}
// A few special cases to read easily from a directory:
public static Network readNetworkFromDirectory(String directory) throws IOException {
Network network = readFromFile(Network.SCHEMA$, directory + "/Network.json");
network.resolveReferences();
return network;
}
public static DemandMap readDemandMapFromDirectory(String directory) throws IOException {
return readFromFile(DemandMap.SCHEMA$, directory + "/DemandMap.json");
}
public static SplitRatioMap readSplitRatioMapFromDirectory(String directory) throws IOException {
return readFromFile(SplitRatioMap.SCHEMA$, directory + "/SplitRatioMap.json");
}
public static FDMap readFDMapFromDirectory(String directory) throws IOException {
return readFromFile(FDMap.SCHEMA$, directory + "/FDMap.json");
}
public static FreewayContextConfig readFreewayContextConfigFromDirectory(String directory) throws IOException {
return readFromFile(FreewayContextConfig.SCHEMA$, directory + "/FreewayContextConfig.json");
}
}
|
a910764479b936aee0a5768ed6587fd30a9c54bb
|
[
"Java"
] | 1
|
Java
|
gmerritt/model-elements
|
94eacff520429bca9353c7c8dfc013deb93c759e
|
9d0b7af15f47a66f011d3934c4676ffb2f520568
|
refs/heads/master
|
<file_sep>
var merchArr =
[
{product: "Finger Toothbrush", description: "A helping hand to a nicer smile.", price: 1.11},
{product: "Barry Manilow's Greatest Hits Collection Vol 1", description: "Music the way it should be! Reminisce the past glory as your ship to happiness has sailed.", price: 39.57},
{product: "Ramen Oreos", description: "The overly used cliche 'East Meets West' comes to life as Nabisco has infused the savory flavors of the Far East sandwiched between two chocolate wafers. Dip that in your sake.", price: 8.88},
{product: "Woof Washer 360", description: "Wash your dirty stinky mutt in minutes! Water and dog not included." , price: 9.29},
{product: "Sauna Pants", description: "Is it hot in here? Indeed. It's my pants. Look cool while losing weight.", price: 2.33},
{product: "Hug Me Pillow", description: "No more lonely nights as you snuggle with your best friend. And it will never walk out on you.", price: 599.99}
];
//calculate subtotal price
var subTotalPrice = merchArr.reduce((a, b) => a + b.price, 0);
// add sub-total to end of merchArr
merchArr.push({product: "Subtotal",description: "",price: subTotalPrice});
// make container to hold header img/label
var headerBox = document.createElement('div');
headerBox.id = 'header';
document.body.appendChild(headerBox);
// create container for cart img
var cartImg = document.createElement('img');
cartImg.className ='cart';
cartImg.id='cartImg';
cartImg.src = 'images/cart.svg';
// create container for cart label
var cartLabel = document.createElement('h2');
cartLabel.className='cart';
cartLabel.id='cartLabel';
cartLabel.innerHTML='Shopping Cart';
// place img & label in header container
headerBox.appendChild(cartImg);
headerBox.appendChild(cartLabel);
//make array to hold image links
//last link is a blank image to keep the Subtotal in the correct place
// there has to be a better way...
var imgArray = [
'https://images.pet-supermarket.co.uk/images/w_400/product/I9210278/Kokoba-Finger-Toothbrush-Set-for-Dogs',
'https://img.discogs.com/Jf8fMcTNG9qZtcHcZaMwFZ6Wi1Q=/fit-in/600x600/filters:strip_icc():format(jpeg):mode_rgb():quality(90)/discogs-images/R-2382962-1360331108-2121.jpeg.jpg',
'https://cdn.trendhunterstatic.com/phpthumbnails/253/253437/253437_1_230c.jpeg',
'https://images-na.ssl-images-amazon.com/images/I/51AF%2BqomYPL.jpg',
'http://www.saunatimes.com/wp-content/uploads/sauna-pants1.jpg',
'https://images.prod.meredith.com/product/20459cbcb9c409ca83fb28a33c9ddf91/1518828691340/l/hug-me-decorative-throw-pillow-gray-17-x17',
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQIAAABvCAMAAAAwjD5SAAAAA1BMVEX///+nxBvIAAAAM0lEQVR4nO3BMQEAAADCoPVPbQsvoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICrAXBNAAEknkf6AAAAAElFTkSuQmCC'
];
//what's best practice for the last "subtotal" spot?
for (var i=0; i<merchArr.length; i++) {
// make merch class to hold all info on a product
var merchBox = document.createElement('div');
merchBox.className = 'merch'
document.body.appendChild(merchBox);
// make prodContent class to hold img, name, and desc
var prodContent = document.createElement('div');
prodContent.className = 'prodContent';
merchBox.appendChild(prodContent);
// make prodImg to hold images.
var imgBox = document.createElement('img');
imgBox.className = 'prodImg';
prodContent.appendChild(imgBox);
imgBox.src = imgArray[i];
// make prodAndDesc class to hold Product & Description
var prodAndDescBox = document.createElement('div');
prodAndDescBox.className = 'prodDesc';
prodContent.appendChild(prodAndDescBox);
// append product to prodAndDesc class
var productBox = document.createElement('div');
productBox.className = 'product';
productBox.innerHTML = merchArr[i].product;
prodAndDescBox.appendChild(productBox);
// append desc to prodAndDesc class
var descriptionBox = document.createElement('div');
descriptionBox.className = 'description';
descriptionBox.innerHTML = merchArr[i].description;
prodAndDescBox.appendChild(descriptionBox);
// append price to merch class
var priceBox = document.createElement('p');
priceBox.className = 'price';
priceBox.id = 'price'+(i+1);
priceBox.innerHTML = '$'+merchArr[i].price;
merchBox.appendChild(priceBox);
}
// bold the subtotal price
document.getElementsByClassName('price')[merchArr.length-1].style.fontWeight='bold';
// hide empty images
|
2205557d661ca480504086ea67224bf1d7d233b9
|
[
"JavaScript"
] | 1
|
JavaScript
|
lukefiorio/shopping-cart
|
3050930e560353830f43c1b646105e1f3da71a30
|
c6fcfc2724e0a714c3f38e86ff0c3f7149ff24c5
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BrookingsIndoorTrainingSystem.Models
{
public class FundsModel
{
public int id { get; set; }
public double Concessions { get; set; }
public double Equipment { get; set; }
public double Space { get; set; }
public double BITS { get; set; }
}
}<file_sep>using BrookingsIndoorTrainingSystem.Models;
using BrookingsIndoorTrainingSystem.Services.Access;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using System.IO;
namespace BrookingsIndoorTrainingSystem.Controllers
{
public class HomeController : Controller
{
//Shelby's string
public string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=BITS_DB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
//+++++++++++++++++ Home pages Controllers +++++++++++++++++++++++++++++++++
public ActionResult Index()
{
// Initalize Cart
GlobalConcessionsCartModel.cart = new List<ConcessionsModel>();
GlobalConcessionsCartModel.total = 0;
bool result;
string sqlCreateDBQuery;
try
{
SqlConnection tmpConn = new SqlConnection(@"Server=(localdb)\MSSQLLocalDB;");
sqlCreateDBQuery = "SELECT database_id FROM sys.databases WHERE Name = 'BITS_DB'";
using (tmpConn)
{
using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
{
tmpConn.Open();
object resultObj = sqlCmd.ExecuteScalar();
int databaseID = 0;
if (resultObj != null)
{
int.TryParse(resultObj.ToString(), out databaseID);
}
tmpConn.Close();
result = (databaseID > 0);
}
}
}
catch (Exception ex)
{
result = false;
}
if (!result)
{
String str;
SqlConnection myConn = new SqlConnection(@"Server=(localdb)\MSSQLLocalDB;");//Integrated security=SSPI;database=master
str = "CREATE DATABASE BITS_DB";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
myConn.Close();
myConn.Open();
myCommand.CommandText = System.IO.File.ReadAllText(@"C:\Users\Shelby\source\repos\BrookingsIndoorTrainingSystem\Services\Queries\Startup.sql");
myCommand.ExecuteNonQuery();
myConn.Close();
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return View();
}
public ActionResult About()
{
ViewBag.Message = "This is the about page";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "This is the contact page";
return View();
}
//+++++++++++ Equipment Controllers +++++++++++++++++++++++++++++++
public ActionResult EquipmentView()
{
return View("EquipmentView");
}
// equipment add item view
public ActionResult EquipmentAddItemView()
{
return View("EquipmentAddItemView");
}
// equipment Remove item view
public ActionResult EquipmentRemoveItemView()
{
return View("EquipmentRemoveItemView");
}
// equipment Update
public ActionResult EquipmentMoveItemView()
{
return View("EquipmentMoveItemView");
}
// equipment Rent item view
public ActionResult EquipmentRentItemView()
{
return View("EquipmentRentItemView");
}
// ++++++ SPACES Controllers +++++++++++++++++++++++++++++++++++++++++++++++
public ActionResult SpaceView()
{
return View("SpaceView");
}
// Added space soccer view - <NAME>
public ActionResult SpaceSoccerView()
{
return View("SpaceSoccerView");
}
// Go to Track page
public ActionResult SpaceTrackView()
{
return View("SpaceTrackView");
}
// Go to Batting Cage page
public ActionResult SpaceBattingView()
{
return View("SpaceBattingView");
}
// +++++ Concessions Controllers +++++++++++++++++++++++++++++++++++++++++++
public ActionResult ConcessionsView()
{
return View("ConcessionsView");
}
public ActionResult ConcessionsUpdateLocationView(ConcessionsModel concessionsModel)
{
return View("ConcessionsUpdateLocation");
}
// ++ Added <NAME>
// Go to Concessions Add item page
public ActionResult ConcessionsUpdateLocation(string itemName, int id)
{
ViewBag.itemName = itemName;
ViewBag.id = id;
return View();
}
public ActionResult ConcessionsMoveItem(ConcessionsModel item, string itemName, int id)
{
int current_amount;
string queryString;
bool success = true;
queryString = "SELECT * FROM ConcessionsTable WHERE Id = @id";
using (SqlConnection connection = new SqlConnection(connectionString))
{
//here is where we connect to the database and perform the SQL command
SqlCommand command = new SqlCommand(queryString, connection);
//thesee statements replace the @itemName and @itemAmount in the queryString with their appropriate variables
command.Parameters.Add("@id", System.Data.SqlDbType.Int).Value = id;
//basically a test to make sure it worked, and catch exception
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
reader.Read();
current_amount = (int)reader["Item_Amount"];
connection.Close();
connection.Open();
command.CommandText = "SELECT * FROM ConcessionsTable WHERE Item_Name = @itemName1";
command.Parameters.Add("@itemName1", System.Data.SqlDbType.VarChar, 50).Value = itemName;
string location;
double itemPrice=0;
bool exists;
exists = false;
int existingID = 0;
reader = command.ExecuteReader();
while(reader.Read())
{
location = (string)reader["Item_Loc"];
itemPrice = (double)reader["Item_Price"];
if (location == item.itemLoc)
{
exists = true;
existingID = (int)reader["Id"];
break;
}
}
connection.Close();
connection.Open();
if(exists)
{
if (item.itemAmount == current_amount)
{
// Change the SQL Command and execute
command.CommandText = "DELETE FROM ConcessionsTable WHERE Id = @id2;";
command.Parameters.Add("@id2", System.Data.SqlDbType.Int).Value = id;
command.ExecuteNonQuery();
command.CommandText = "UPDATE ConcessionsTable SET Item_Amount += @itemAmount WHERE Id = @existingID";
command.Parameters.Add("@itemAmount", System.Data.SqlDbType.Int).Value = item.itemAmount;
command.Parameters.Add("@existingID", System.Data.SqlDbType.Int).Value = existingID;
command.ExecuteNonQuery();
}
else if (item.itemAmount < current_amount && item.itemAmount > 0)
{
command.CommandText = "UPDATE ConcessionsTable SET Item_Amount += @itemAmount WHERE Id = @existingID";
command.Parameters.Add("@itemAmount", System.Data.SqlDbType.Int).Value = item.itemAmount;
command.Parameters.Add("@existingID", System.Data.SqlDbType.Int).Value = existingID;
command.ExecuteNonQuery();
command.CommandText = "UPDATE ConcessionsTable SET Item_Amount -= @itemAmount2 WHERE Id = @id2";
command.Parameters.Add("@itemAmount2", System.Data.SqlDbType.Int).Value = item.itemAmount;
command.Parameters.Add("@id2", System.Data.SqlDbType.Int).Value = id;
command.ExecuteNonQuery();
}
else
{
success = false;
ViewBag.Error = "Error: Amount to be moved must be positive and less than or equal to the current amount.\nCurrent amount: " + current_amount.ToString();
}
}
else
{
if (item.itemAmount == current_amount)
{
// Change the SQL Command and execute
command.CommandText = "UPDATE ConcessionsTable SET Item_Loc = @itemLoc WHERE Id = @id2";
command.Parameters.Add("@itemLoc", System.Data.SqlDbType.VarChar, 50).Value = item.itemLoc;
command.Parameters.Add("@id2", System.Data.SqlDbType.Int).Value = id;
command.ExecuteNonQuery();
}
else if (item.itemAmount < current_amount && item.itemAmount > 0)
{
command.CommandText = "INSERT INTO ConcessionsTable values(@iN, @iA, @iL, @iP)";
command.Parameters.Add("@iN", System.Data.SqlDbType.VarChar, 50).Value = itemName;
command.Parameters.Add("@iA", System.Data.SqlDbType.Int).Value = item.itemAmount;
command.Parameters.Add("@iL", System.Data.SqlDbType.VarChar, 50).Value = item.itemLoc;
command.Parameters.Add("@iP", System.Data.SqlDbType.Float).Value = itemPrice;
command.ExecuteNonQuery();
command.CommandText = "UPDATE ConcessionsTable SET Item_Amount -= @itemAmount WHERE Id = @id2";
command.Parameters.Add("@itemAmount", System.Data.SqlDbType.Int).Value = item.itemAmount;
command.Parameters.Add("@id2", System.Data.SqlDbType.Int).Value = id;
command.ExecuteNonQuery();
}
else
{
success = false;
ViewBag.Error = "Error: Amount to be moved must be positive and less than or equal to the current amount.";
ViewBag.Error2 = "Current amount: " + current_amount.ToString();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
if (success)
return View("ConcessionsView");
else
{
ViewBag.itemName = itemName;
ViewBag.id = id;
return View("ConcessionsUpdateLocation");
}
}
public ActionResult ConcessionsAddItemView(string itemName, int id)
{
ViewBag.itemName = itemName;
ViewBag.id = id;
return View();
}
// Go to Concessions remove item page
public ActionResult ConcessionsRemoveItemView(string itemName, int id)
{
ViewBag.itemName = itemName;
ViewBag.id = id;
//StorageView();
return View("ConcessionsRemoveItemView");
}
public ActionResult ConcessionsAddItem(ConcessionsModel item, string itemName, int id)
{
string queryString;
bool success = true;
//this is the SQL statement to update our item amount. @itemAmount and @itemName are replaced using the function following
if (item.itemAmount > 0 && item.itemAmount <= 500)
{
queryString = "UPDATE ConcessionsTable SET Item_Amount += @itemAmount WHERE Id = @id2";
using (SqlConnection connection = new SqlConnection(connectionString))
{
//here is where we connect to the database and perform the SQL command
SqlCommand command = new SqlCommand(queryString, connection);
//thesee statements replace the @itemName and @itemAmount in the queryString with their appropriate variables
command.Parameters.Add("@id2", System.Data.SqlDbType.Int).Value = id;
command.Parameters.Add("@itemAmount", System.Data.SqlDbType.Int).Value = item.itemAmount;
//basically a test to make sure it worked, and catch exception
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
else
{
success = false;
}
if (success)
{
return View("ConcessionsView");
}
else
{
ViewBag.Error = "Error: Item amount must be a positive integer less than 500.";
ViewBag.itemName = itemName;
ViewBag.id = id;
return View("ConcessionsAddItemView");
}
}
public ActionResult ConcessionsRemoveItem(ConcessionsModel item, string itemName, int id)
{
string queryString2;
string queryString1;
bool success = true;
//this is the SQL statement to update our item amount. @itemAmount and @itemName are replaced using the function following
if (item.itemAmount > 0)
{
queryString1 = "Select Item_Amount FROM ConcessionsTable WHERE Id = @id1";
queryString2 = "UPDATE ConcessionsTable SET Item_Amount -= @itemAmount WHERE Id = @id2";
using (SqlConnection connection = new SqlConnection(connectionString))
{
//here is where we connect to the database and perform the SQL command
SqlCommand command = new SqlCommand(queryString1, connection);
command.Parameters.Add("@id1", System.Data.SqlDbType.Int).Value = id;
//basically a test to make sure it worked, and catch exception
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
reader.Read();
int current_val = (int)reader["Item_Amount"];
if (current_val < item.itemAmount)
{
success = false;
ViewBag.Error = "Error: Cannot remove more than current value. Current value is: " + current_val;
}
if(success)
{
connection.Close();
connection.Open();
command.CommandText = queryString2;
//thesee statements replace the @itemName and @itemAmount in the queryString with their appropriate variables
command.Parameters.Add("@id2", System.Data.SqlDbType.Int).Value = id;
command.Parameters.Add("@itemAmount", System.Data.SqlDbType.Int).Value = item.itemAmount;
command.ExecuteNonQuery();
connection.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
else
{
ViewBag.Error = "Error: Item amount must be a positive integer.";
success = false;
}
if (success)
{
return View("ConcessionsView");
}
else
{
ViewBag.itemName = itemName;
ViewBag.id = id;
return View("ConcessionsRemoveItemView");
}
}
//public ActionResult ConcessionsUpdateItemLoc(ConcessionsModel concessionsModel)
//{
// DataAcess dataAccess = new DataAcess();
// concessionsModel.itemName = "Sodas";
// Boolean success = dataAccess.MoveConcessionItem(concessionsModel);
// if (success)
// return View("StorageView");
// return View("ConcessionsView");
//}
// GET: /concessionsTable/
public ActionResult StorageView()
{
//this is used to connect to the database
//Shelby's string
string sql = "SELECT * FROM ConcessionsTable";
var model = new List<ConcessionsModel>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
var item = new ConcessionsModel();
item.id = (int)rdr["Id"];
item.itemName = (string)rdr["Item_Name"];
item.itemAmount = (int)rdr["Item_Amount"];
item.itemLoc = (string)rdr["Item_Loc"];
item.itemPrice = (double)rdr["Item_Price"];
model.Add(item);
}
}
return View(model);
}
public ActionResult ConcessionsEditItemView(string itemName, int id)
{
ViewBag.itemName = itemName;
ViewBag.id = id;
return View();
}
public ActionResult ConcessionsMakeSaleView()
{
string sql = "SELECT * FROM ConcessionsTable";
var model = new List<ConcessionsModel>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
var item = new ConcessionsModel();
item.id = (int)rdr["Id"];
item.itemName = (string)rdr["Item_Name"];
item.itemAmount = (int)rdr["Item_Amount"];
item.itemLoc = (string)rdr["Item_Loc"];
item.itemPrice = (double)rdr["Item_Price"];
model.Add(item);
}
}
return View(model);
}
public ActionResult ConcessionsCartView()
{
var model = GlobalConcessionsCartModel.cart;
return View(model);
}
public ActionResult ConcessionsCartAddItemView(string itemName, int id, double itemPrice)
{
ViewBag.itemName = itemName;
ViewBag.id = id;
ViewBag.itemPrice = itemPrice;
return View();
}
public ActionResult ConcessionsCartAddItem(ConcessionsModel item, string itemName, int id, double itemPrice)
{
string queryString1;
string queryString;
bool success = true;
//this is the SQL statement to update our item amount. @itemAmount and @itemName are replaced using the function following
if (item.itemAmount > 0)
{
queryString1 = "Select Item_Amount FROM ConcessionsTable WHERE Id = @id1";
using (SqlConnection connection = new SqlConnection(connectionString))
{
//here is where we connect to the database and perform the SQL command
SqlCommand command = new SqlCommand(queryString1, connection);
command.Parameters.Add("@id1", System.Data.SqlDbType.Int).Value = id;
//basically a test to make sure it worked, and catch exception
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
reader.Read();
int current_val = (int)reader["Item_Amount"];
if (current_val < item.itemAmount)
{
ViewBag.Error = "Error: There is not enough of that item";
ConcessionsCartAddItemView(itemName, id, item.itemPrice);
return View("ConcessionsCartAddItemView");
}
connection.Close();
if (success)
{
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
queryString = "UPDATE ConcessionsTable SET Item_Amount -= @itemAmount WHERE Id = @id";
//here is where we connect to the database and perform the SQL command
SqlCommand command = new SqlCommand(queryString, connection);
//thesee statements replace the @itemName and @itemAmount in the queryString with their appropriate variables
command.Parameters.Add("@id", System.Data.SqlDbType.Int).Value = id;
command.Parameters.Add("@itemAmount", System.Data.SqlDbType.Int).Value = item.itemAmount;
//basically a test to make sure it worked, and catch exception
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
reader.Read();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
ViewBag.Error = "";
GlobalConcessionsCartModel.cart.Add(item);
GlobalConcessionsCartModel.total += itemPrice*item.itemAmount;
ConcessionsCartView();
return View("ConcessionsCartView");
}
else
{
ViewBag.Error = "Error: Can not add negative item amounts";
ConcessionsCartAddItemView(itemName, id, item.itemPrice);
return View("ConcessionsCartAddItemView");
}
}
public ActionResult ConcessionsCartRemoveItem(string itemName, int id)
{
for (int i = 0; i < GlobalConcessionsCartModel.cart.Count; i++)
{
// if it is List<String>
if (GlobalConcessionsCartModel.cart[i].id == id)
{
string queryString;
bool success = true;
//this is the SQL statement to update our item amount. @itemAmount and @itemName are replaced using the function following
queryString = "UPDATE ConcessionsTable SET Item_Amount += @itemAmount WHERE Id = @id";
using (SqlConnection connection = new SqlConnection(connectionString))
{
//here is where we connect to the database and perform the SQL command
SqlCommand command = new SqlCommand(queryString, connection);
//thesee statements replace the @itemName and @itemAmount in the queryString with their appropriate variables
command.Parameters.Add("@id", System.Data.SqlDbType.Int).Value = id;
command.Parameters.Add("@itemAmount", System.Data.SqlDbType.Int).Value = GlobalConcessionsCartModel.cart[i].itemAmount;
//basically a test to make sure it worked, and catch exception
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
GlobalConcessionsCartModel.total -= GlobalConcessionsCartModel.cart[i].itemPrice * GlobalConcessionsCartModel.cart[i].itemAmount;
GlobalConcessionsCartModel.cart.RemoveAt(i);
}
}
ConcessionsCartView();
return View("ConcessionsCartView");
}
public ActionResult ConcessionsClearCart()
{
// Update Funds Database
FundsAddtoFunds(GlobalConcessionsCartModel.total, "Concessions");
for (int i = 0; i < GlobalConcessionsCartModel.cart.Count;)
{
GlobalConcessionsCartModel.cart.RemoveAt(i);
}
GlobalConcessionsCartModel.total = 0;
ConcessionsMakeSaleView();
return View("ConcessionsMakeSaleView");
}
// ++++++++++++++++++++++++++++ FUNDS Controllers ++++++++++++++++++++++++++ //
public ActionResult FundsMakePaymentView(string itemName)
{
ViewBag.itemName = itemName;
return View();
}
public ActionResult FundsView()
{
string sql = "SELECT * FROM Funds";
var model = new FundsModel();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
var item = new FundsModel();
item.id = (int)rdr["Id"];
item.Concessions = (double)rdr["Concessions"];
item.BITS = (double)rdr["BITS"];
item.Equipment = (double)rdr["Equipment"];
item.Space = (double)rdr["Space"];
model = item;
}
}
return View(model);
}
public ActionResult FundsUpdateConcesssionsView(double funds)
{
var model = new FundsModel();
model.Concessions = funds;
return View(model);
}
public ActionResult FundsUpdateEquipmentView(double funds)
{
var model = new FundsModel();
model.Equipment = funds;
return View(model);
}
public ActionResult FundsUpdateSpaceView(double funds)
{
var model = new FundsModel();
model.Space = funds;
return View(model);
}
public ActionResult FundsUpdate(FundsModel funds, string location)
{
string queryString3 = "";
string queryString2 = "";
string queryString1 = "";
bool success = true;
double amount = 0;
if (location == "Concessions")
{
amount = funds.Concessions;
queryString2 = "UPDATE Funds SET Concessions = @Amount WHERE Id = 1";
}
else if (location == "Equipment")
{
amount = funds.Equipment;
queryString2 = "UPDATE Funds SET Equipment = @Amount WHERE Id = 1";
}
else if (location == "Space")
{
amount = funds.Space;
queryString2 = "UPDATE Funds SET Space = @Amount WHERE Id = 1";
}
//this is the SQL statement to update our item amount. @itemAmount and @itemName are replaced using the function following
if (amount > 0)
{
queryString1 = "SELECT * FROM Funds";
queryString3 = "UPDATE Funds SET BITS += @difference WHERE Id = 1";
using (SqlConnection connection = new SqlConnection(connectionString))
{
//here is where we connect to the database and perform the SQL command
SqlCommand command = new SqlCommand(queryString1, connection);
//thesee statements replace the @itemName and @itemAmount in the queryString with their appropriate variables
//basically a test to make sure it worked, and catch exception
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
reader.Read();
double current = (double)reader[location];
double difference;
difference = current - amount;
connection.Close();
connection.Open();
command.CommandText = queryString3;
command.Parameters.Add("@difference", System.Data.SqlDbType.Float).Value = difference;
command.ExecuteNonQuery();
connection.Close();
connection.Open();
command.CommandText = queryString2;
command.Parameters.Add("@Amount", System.Data.SqlDbType.Float).Value = amount;
command.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
success = true;
}
else
{
success = false;
}
FundsView();
return View("FundsView");
}
public void FundsAddtoFunds(double amount, string location)
{
// Get old amount
double oldAmount = 0;
string sql = "SELECT * FROM Funds";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
oldAmount = (double)rdr["Concessions"];
}
}
// Get old amount
// Get new amount
double newAmount = oldAmount + amount;
// Update new amount
FundsModel funds = new FundsModel();
funds.Concessions = newAmount;
FundsUpdate(funds, location);
}
public ActionResult ScheduleUpdateEmployeeView(int Id, string Dates, string Monday, string Tuesday, string Wednesday, string Thursday, string Friday, string Saturday)
{
ScheduleModel employee = new ScheduleModel();
ViewBag.Id = Id;
ViewBag.Dates = Dates;
employee.Id = Id;
employee.Dates = Dates;
employee.Monday = Monday;
employee.Tuesday = Tuesday;
employee.Wednesday = Wednesday;
employee.Thursday = Thursday;
employee.Friday = Friday;
employee.Saturday = Saturday;
return View(employee);
}
// ++++++++++++++++++++++++++++ FUNDS Controllers ++++++++++++++++++++++++++ //
public ActionResult ScheduleEmployeeView()
{
string sql = "SELECT * FROM Schedule";
var model = new List<ScheduleModel>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
var item = new ScheduleModel();
item.Id = (int)rdr["Id"];
item.Dates = (string)rdr["Dates"];
item.Monday = (string)rdr["Monday"];
item.Tuesday = (string)rdr["Tuesday"];
item.Wednesday = (string)rdr["Wednesday"];
item.Thursday = (string)rdr["Thursday"];
item.Friday = (string)rdr["Friday"];
item.Saturday = (string)rdr["Saturday"];
model.Add(item);
}
}
return View(model);
}
public ActionResult UpdateSchedule(ScheduleModel employee, int Id, string Dates)
{
string queryString = "UPDATE Schedule SET Monday = @mon, Tuesday = @tues, Wednesday = @wed, Thursday = @thurs, Friday = @fri, Saturday = @sat WHERE Id = @id";
employee.Id = Id;
employee.Dates = Dates;
using (SqlConnection connection = new SqlConnection(connectionString))
{
//here is where we connect to the database and perform the SQL command
SqlCommand command = new SqlCommand(queryString, connection);
//thesee statements replace the @itemName and @itemAmount in the queryString with their appropriate variables
command.Parameters.Add("@id", System.Data.SqlDbType.Int).Value = employee.Id;
command.Parameters.Add("@mon", System.Data.SqlDbType.VarChar, 50).Value = employee.Monday;
command.Parameters.Add("@tues", System.Data.SqlDbType.VarChar, 50).Value = employee.Tuesday;
command.Parameters.Add("@wed", System.Data.SqlDbType.VarChar, 50).Value = employee.Wednesday;
command.Parameters.Add("@thurs", System.Data.SqlDbType.VarChar, 50).Value = employee.Thursday;
command.Parameters.Add("@fri", System.Data.SqlDbType.VarChar, 50).Value = employee.Friday;
command.Parameters.Add("@sat", System.Data.SqlDbType.VarChar, 50).Value = employee.Saturday;
//basically a test to make sure it worked, and catch exception
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
ScheduleEmployeeView();
return View("ScheduleEmployeeView");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BrookingsIndoorTrainingSystem.Models
{
public class ConcessionsModel
{
public int id { get; set; }
public string itemName { get; set; }
public int itemAmount { get; set; }
public string itemLoc { get; set; }
public double itemPrice { get; set; }
}
//public class ConcessionsMakeSaleModel
//{
// public List<ConcessionsModel> ConcessionsList { get; set; }
// public List<ConcessionsMakeSaleCartModel> ConcessionsCartList { get; set; }
//}
//public class ConcessionsMakeSaleCartModel
//{
// public string itemName { get; set; }
// public int itemAmount { get; set; }
// public string itemLoc { get; set; }
//}
public static class GlobalConcessionsCartModel
{
public static double total { get; set; }
public static List<ConcessionsModel> cart { get; set; }
}
}<file_sep>using BrookingsIndoorTrainingSystem.Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace BrookingsIndoorTrainingSystem.Services.Access
{
public class DataAcess
{
//this is used to connect to the database
//Shelby's string
public string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=BITS_DB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
//
public bool ConcessionsAddItemAmount(ConcessionsModel item)
{
string queryString;
bool success = true;
//this is the SQL statement to update our item amount. @itemAmount and @itemName are replaced using the function following
if(item.itemAmount > 0)
{
queryString = "UPDATE ConcessionsTable SET Item_Amount += @itemAmount WHERE Item_Name = @itemName";
using (SqlConnection connection = new SqlConnection(connectionString))
{
//here is where we connect to the database and perform the SQL command
SqlCommand command = new SqlCommand(queryString, connection);
//thesee statements replace the @itemName and @itemAmount in the queryString with their appropriate variables
command.Parameters.Add("@itemName", System.Data.SqlDbType.VarChar, 50).Value = item.itemName;
command.Parameters.Add("@itemAmount", System.Data.SqlDbType.Int).Value = item.itemAmount;
//basically a test to make sure it worked, and catch exception
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
success = true;
}
else
{
success = false;
}
return success;
}
public bool ConcessionsRemoveItemAmount(ConcessionsModel item)
{
string queryString;
bool success = true;
//this is the SQL statement to update our item amount. @itemAmount and @itemName are replaced using the function following
if (item.itemAmount > 0)
{
queryString = "UPDATE ConcessionsTable SET Item_Amount -= @itemAmount WHERE Item_Name = @itemName";
using (SqlConnection connection = new SqlConnection(connectionString))
{
//here is where we connect to the database and perform the SQL command
SqlCommand command = new SqlCommand(queryString, connection);
//thesee statements replace the @itemName and @itemAmount in the queryString with their appropriate variables
command.Parameters.Add("@itemName", System.Data.SqlDbType.VarChar, 50).Value = item.itemName;
command.Parameters.Add("@itemAmount", System.Data.SqlDbType.Int).Value = item.itemAmount;
//basically a test to make sure it worked, and catch exception
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
success = true;
}
else
{
success = false;
}
return success;
}
public bool MoveConcessionItem(ConcessionsModel item)
{
bool success = true;
string queryString = "UPDATE ConcessionsTable SET Item_Loc = @itemLoc WHERE Item_Name = @itemName";
using (SqlConnection connection = new SqlConnection(connectionString))
{
//here is where we connect to the database and perform the SQL command
SqlCommand command = new SqlCommand(queryString, connection);
//thesee statements replace the @itemName and @itemAmount in the queryString with their appropriate variables
command.Parameters.Add("@itemName", System.Data.SqlDbType.VarChar, 50).Value = item.itemName;
command.Parameters.Add("@itemLoc", System.Data.SqlDbType.Int).Value = item.itemLoc;
//basically a test to make sure it worked, and catch exception
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
success = true;
return success;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BrookingsIndoorTrainingSystem.Models
{
public class EquipmentModel
{
public string itemName { get; set; }
public int itemAmount { get; set; }
public string itemLoc { get; set; }
}
}
|
01abc7ec7cba1f041da5c206be2986fe64d706ce
|
[
"C#"
] | 5
|
C#
|
KerkFleet/BrookingsIndoorTrainingSystem
|
3221b8af4cc4def3c6308e6302d617f956c30834
|
2c50a58c0af6189d2dac67aad70bdc249f544aed
|
refs/heads/master
|
<repo_name>Luminations/kompetenzhoe<file_sep>/animalKingdomManiaFightClub/src/com/company/Cyborgs/Reptiles/Iguana.java
package com.company.Cyborgs.Reptiles;
/**
* Created by fraser on 1/20/17.
*/
public class Iguana extends Reptile{
/**
* sets variable to custom variables according to iguana statistics
*/
public Iguana(){
health = 200;
regenerationRate = 17;
power = 2;
name = "Iguana";
}
}
<file_sep>/animalKingdomManiaFightClub/src/com/company/JUnitTests/ReptileTest.java
import com.company.Cyborgs.Reptiles.Crocodile;
import com.company.Cyborgs.Reptiles.Iguana;
import com.company.Mamals.Lion;
/**
* Created by fraser on 1/27/17.
*/
public class ReptileTest {
@org.junit.Test
public void exterminate() throws Exception {
Crocodile crocodile = new Crocodile();
Lion lion = new Lion();
Iguana iguana = new Iguana();
crocodile.exterminate(lion);
iguana.exterminate(crocodile);
org.junit.Assert.assertTrue(lion.health == 0);
org.junit.Assert.assertTrue(crocodile.health != 0);
}
}<file_sep>/animalKingdomManiaFightClub/src/com/company/JUnitTests/AnimalTest.java
import com.company.Cyborgs.Reptiles.Iguana;
import com.company.Mamals.Lion;
import org.junit.Assert;
/**
* Created by fraser on 1/27/17.
*/
public class AnimalTest {
@org.junit.Test
public void fight() throws Exception {
Lion lion = new Lion();
Iguana iguana = new Iguana();
int i = iguana.health;
lion.Fight(iguana);
Assert.assertTrue(i > iguana.health);
}
@org.junit.Test
public void regenerate() throws Exception {
Lion lion = new Lion();
int i = lion.health;
lion.Regenerate();
Assert.assertTrue(lion.health > i);
}
}<file_sep>/animalKingdomManiaFightClub/src/com/company/Mamals/RedPanda.java
package com.company.Mamals;
/**
* Created by fraser on 1/20/17.
*/
public class RedPanda extends Mammal{
public RedPanda(){
health = 200;
regenerationRate = 24;
power = 3;
name = "<NAME>";
}
}
<file_sep>/sudoku/src/com/company/Coordination.java
package com.company;
/**
* Created by fraser on 1/17/17.
*/
public class Coordination {
public int x;
public int y;
public Coordination(int x, int y){
this.x = x;
this.y = y;
}
}
<file_sep>/animalKingdomManiaFightClub/src/com/company/Animal.java
package com.company;
/**
* is supposed to represent wild animals
*/
public abstract class Animal {
public int power;
public int health;
public int regenerationRate;
public String name;
/**
* sets variable to custom variables according to animal statistics
*/
public Animal(){
health = 0;
regenerationRate = 0;
name = "default name";
}
/**
* suptracts health from the animal acording to this's power
* @param animal ataccked animal witch lives goes down
*/
public void Fight(Animal animal){
animal.health = animal.health - this.power;
}
/**
* increeses the health of this animal by its regenerationRate
*/
public void Regenerate(){
health = health + regenerationRate;
}
}
|
2ddec0c307ea5f872056f4a66a60f70dbf12e6ec
|
[
"Java"
] | 6
|
Java
|
Luminations/kompetenzhoe
|
2b7aad563992498b27e6a75c4899a138fb4c9dba
|
dadc775fb093f2b61a24c0f48e551a2e01ede471
|
refs/heads/master
|
<file_sep>package main
import (
"flag"
"fmt"
"net/http"
"os"
)
/* TODO
Timestamp to know the latest entry
Index show latest entry
cool if minified js and css
super cool if I could have a better editor
or auto reloading
maybe with hashsums?
Logging Middleware
*/
var (
configFile string
config Conf
)
func init() {
flag.StringVar(&configFile, "c", "", "set the config file to use. (without this set the server will not start)\nExp: webServer -c config/dev.json")
}
func usage(message string) {
fmt.Printf("%s\nUsage:\n", message)
flag.PrintDefaults()
os.Exit(0)
}
func main() {
flag.Parse()
if configFile == "" {
usage("Didn't get a proper config file")
}
var err error
config, err = NewConfig(configFile)
if err != nil {
fatalError("failed to read config during init", err)
}
initParserGlobals()
initHandlerGlobals()
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
http.HandleFunc("/", rootHandler)
http.HandleFunc("/view/", makeHandler(viewHandler))
if config.Environment == "dev" {
http.HandleFunc("/edit/", makeHandler(editHandler))
http.HandleFunc("/save/", makeHandler(saveHandler))
}
info(fmt.Sprintf("Listening at localhost%s", config.Port))
err = http.ListenAndServe(config.Port, nil)
if err != nil {
fatalError("failed to initalize server", err)
}
}
<file_sep>package main
import (
"encoding/json"
"os"
)
type Conf struct {
Port string
Environment string
}
func NewConfig(configFile string) (Conf, error) {
infof("using config file:", configFile)
file, _ := os.Open(configFile)
defer file.Close()
decoder := json.NewDecoder(file)
config := Conf{}
err := decoder.Decode(&config)
if err != nil {
return Conf{}, err
}
return config, nil
}
<file_sep>package main
import "log"
// TODO: take format string
func debug(input string) {
log.Printf("[DEBUG] %s\n", input)
}
func debugf(input string, info interface{}) {
log.Printf("[DEBUG] %s %v\n", input, info)
}
func fatalError(input string, err error) {
log.Fatalf("[FATAL] %s: %s\n", input, err)
}
func info(info string) {
log.Printf("[INFO] %s\n", info)
}
func infof(input string, info interface{}) {
log.Printf("[INFO] %s %v\n", input, info)
}
func warning(input string, b string) {
log.Printf("[WARNING] %s: %s\n", input, b)
}
func warningError(input string, err error) {
log.Printf("[ERROR] %s: %s\n", input, err)
}
func warningLn(input string) {
log.Printf("[WARNING] %s\n", input)
}
<file_sep>package main
import (
"strings"
)
/*********************************************************************************************************************
_ _ _ _ | | _____ _ _____ _ __
| | | |___ ___| |___ _ _|_|___ | __ |___ _| | | |___ ___| |_ _ _ ___ | | ___ ___ ___ _ _ ___ ___ ___ ___
| | | | -_|_ -| | -_| | | |_ -| | __ -| .'| . | | | | | .'| _| '_| | | . | | |__| .'| | . | | | . | .'| . | -_|
|_____|___|___|_|___|_ | |___| |_____|__,|___| |_|_|_|__,|_| |_,_|___| _| |_____|__,|_|_|_ |___|_ |__,|_ |___|
|___| |_| |___| |___| |___|
**********************************************************************************************************************
[INPUT]
!This is a heading
This is a paragraph with a *bold* word in it.
It should be seperated from the next paragraph.
This is another paragraph with an _italic_
word in it. It should be seperated from the previous
paragraph.
;END OF ARTICLE;
!This is a new Blog Header
That has some *bold* info in it\! Isn't that really cool
[TOKENIZED REPRESENTATION]
(ARTICLE,
(PARAGRAPH,
(HEADING, This is a Heading)
ENDOFPARAGRAPH)
(PARAGRAPH
(PLAIN, this is another paragraph with an)
(ITALIC, italic)
(PLAIN, word in it)
ENDOFPARAGRAPH)
ENDOFARTICLE)
(ARTICLE,
(PARAGRAPH,
(HEADING, This is an new Blog Header)
ENDOFPARAGRAPH)
(PARAGRAPH
(PLAIN, That has some)
(BOLD, bold)
(PLAIN, info in it)
(PLAIN, !)
(PLAIN, isn't that really cool)
ENDOFPARAGRAPH)
ENDOFARTICLE)
[PARSED HTML]
<arcticle class="blog_article">
<p class="blog_paragraph">
This is a paragraph with a <b>bold</b> word in it. It should be seperated
from the next paragraph
</p>
<p class="blog_paragraph">
This is another paragraph with an <i>italic</i> word in it. It should be sperated
from the previous paragraph.
</p>
</article>
*/
/*
TODO:
[FEATURE] Links
[FEATURE] Images
[FEATURE] Youtube viddies, etc...
[FEATURE] Date
*/
type Token struct {
v []byte
t int
}
const (
PLAIN int = iota
BOLD
CODE
ENDOFARTICLE
ENDOFPARAGRAPH
HEADING
ITALIC
LINKSTART
LINKEND
LINKTEXTSTART
LINKTEXTEND
PLAINNEXT
QUOTE
ILLEGAL
)
var symbols map[byte]int
func initParserGlobals() {
symbols = make(map[byte]int)
symbols['*'] = BOLD
symbols[':'] = CODE
symbols['!'] = HEADING
symbols[';'] = ENDOFARTICLE
symbols['\n'] = ENDOFPARAGRAPH
symbols['_'] = ITALIC
symbols['<'] = LINKSTART
symbols['>'] = LINKEND
symbols['('] = LINKTEXTSTART
symbols[')'] = LINKTEXTEND
symbols['\\'] = PLAINNEXT
symbols['#'] = QUOTE
}
func isSpecial(b byte) (ret bool) {
return (b == '*' || b == '_' || b == '<' || b == '>' || b == '(' || b == ')' || b == '#' || b == ':' || b == '!' || b == ';')
}
// isNextPlain is for when you need to use a normally special character
// in a senctance.
func isNextPlain(b byte) (ret bool) {
return b == '\\'
}
func isNewline(b byte) (ret bool) {
return b == '\n'
}
func isPlain(b byte) (ret bool) {
return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b == '.') || (b == ',') || (b == '\'') || (b >= '0' && b <= '9') || (b == ' ')
}
func lex(inputStream *strings.Reader) []Token {
b, err := inputStream.ReadByte()
var tokStream []Token
var treatAsPlain bool
for {
var bs []byte
if isPlain(b) {
var tok Token
tok.t = PLAIN
for isPlain(b) {
bs = append(bs, b)
b, _ = inputStream.ReadByte()
}
tok.v = bs
tokStream = append(tokStream, tok)
} else if isNewline(b) {
var tok Token
tok.t = symbols[b]
b, err = inputStream.ReadByte()
if err != nil && err.Error() != "EOF" {
warningError("ENDOFPARAGRAPH", err)
break
}
tokStream = append(tokStream, tok)
} else if isNextPlain(b) {
var tok Token
tok.t = PLAIN
b, err = inputStream.ReadByte()
if err != nil {
warningError("NEXTPLAIN", err)
break
}
bs = append(bs, b)
tok.v = bs
tokStream = append(tokStream, tok)
b, _ = inputStream.ReadByte()
} else if isSpecial(b) {
var tok Token
tok.t = symbols[b]
b, err = inputStream.ReadByte()
if err != nil {
warningError("SPECIAL", err)
break
}
for isPlain(b) || isNextPlain(b) || treatAsPlain {
if treatAsPlain == true {
treatAsPlain = false
}
// NOTE:
// this is to include the case where a special symbol is the whole line
// i.e. quote
if isNewline(b) {
break
}
if isNextPlain(b) {
treatAsPlain = true
b, err = inputStream.ReadByte()
if err != nil {
if err.Error() != "EOF" {
warningError("PLAIN", err)
}
}
}
bs = append(bs, b)
b, err = inputStream.ReadByte()
if err != nil {
if err.Error() != "EOF" {
warningError("PLAIN", err)
}
}
}
tok.v = bs
tokStream = append(tokStream, tok)
b, err = inputStream.ReadByte()
if err != nil && err.Error() != "EOF" {
warningError("SPECIAL", err)
}
} else {
if b == '\x00' {
b, err = inputStream.ReadByte()
if err != nil && err.Error() != "EOF" {
warningError("UNWANTED", err)
}
break
}
warning("UNWANTED", string(b))
b, err = inputStream.ReadByte()
if err != nil {
break
}
}
}
return tokStream
}
func destorySlashR(input string) string {
bs := []byte(input)
var output []byte
for _, b := range bs {
if b == '\r' {
continue
}
output = append(output, b)
}
return string(output)
}
func parseToHtml(input string) string {
input = destorySlashR(input)
tokStream := lex(strings.NewReader(input))
var tokStreamIndex int
var end bool
running := "<article class=\"blog_article\">"
for !end {
if tokStreamIndex >= 1 {
running = running + "<article class=\"blog_article\">"
}
for !end {
running = running + "\n<p class=\"blog_article_paragraph\">\n"
for {
if tokStreamIndex >= len(tokStream) {
end = true
break
}
tok := tokStream[tokStreamIndex]
running = running
if tok.t == ENDOFPARAGRAPH {
break
}
if tok.t == ENDOFARTICLE {
tokStreamIndex++
goto ARTICLE_END
}
if tok.t == BOLD {
running = running + "<b>" + string(tok.v) + "</b>"
tokStreamIndex++
continue
}
if tok.t == ITALIC {
running = running + "<i>" + string(tok.v) + "</i>"
tokStreamIndex++
continue
}
if tok.t == QUOTE {
running = running + "<p class=\"quote\">" + string(tok.v) + "</p>"
tokStreamIndex++
continue
}
if tok.t == CODE {
running = running + "<pre>" + string(tok.v) + "</pre>"
tokStreamIndex++
continue
}
if tok.t == HEADING {
running = running + "<h2 class=\"blog_article_heading\">" + string(tok.v) + "</h2>"
tokStreamIndex++
continue
}
running = running + string(tok.v)
tokStreamIndex++
}
running = running + "\n</p>\n"
tokStreamIndex++
if tokStreamIndex > len(tokStream)-1 {
end = true
break
}
if tokStream[tokStreamIndex].t == ENDOFARTICLE {
tokStreamIndex++
break
}
}
ARTICLE_END:
running = running + "\n</article>\n"
}
return running
}
<file_sep>package main
import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"regexp"
"strings"
)
var (
templates *template.Template
validPath *regexp.Regexp
)
func getLinks() (links []string) {
dir, _ := ioutil.ReadDir("./data")
for _, file := range dir {
a := strings.Split(file.Name(), ".")
links = append(links, a[0])
}
return
}
func getFileNames(dir string, reg string) (fileNames []string) {
d, err := ioutil.ReadDir(dir)
if err != nil {
fatalError("when reading template dir this error occured", err)
}
if len(dir) <= 0 {
err = fmt.Errorf("could not find directory \"%s\"", dir)
fatalError("when reading template dir this error occured", err)
}
// if somethings slips in like a stray data file or a .swp
validFileName := regexp.MustCompile(reg)
for _, f := range d {
m := validFileName.FindStringSubmatch(f.Name())
if m != nil {
fileName := fmt.Sprintf("%s/%s", dir, f.Name())
fileNames = append(fileNames, fileName)
}
}
return
}
func initHandlerGlobals() {
templateFiles := getFileNames("template", "^[^.]+$|.(tmpl)$")
dataFiles := getFileNames("data", "^[^.]+$|.(wbml)$")
info(fmt.Sprintf("Template files loaded: %q", templateFiles))
info(fmt.Sprintf("Bad Markup files loaded: %q", dataFiles))
templates = template.New("main")
templates.Funcs(map[string]interface{}{
"CallTemplate": func(name string, data interface{}) (ret template.HTML, err error) {
buf := bytes.NewBuffer([]byte{})
err = templates.ExecuteTemplate(buf, name, data)
ret = template.HTML(buf.String())
return
},
})
templates = template.Must(templates.ParseFiles(templateFiles...))
for _, dataFile := range dataFiles {
dat, err := ioutil.ReadFile(fmt.Sprintf("%s", dataFile))
if err != nil {
fatalError(fmt.Sprintf("during the initial read of data file[%s]", dataFile), err)
}
title := strings.Split(dataFile, ".")
d := parseToHtml(string(dat))
templates, err = templates.New(title[0]).Parse(d)
if err != nil {
fatalError(fmt.Sprintf("during the initial parse of data file[%s]", dataFile), err)
}
}
if config.Environment == "dev" {
validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9_]+)$")
} else {
validPath = regexp.MustCompile("^/(view)/([a-zA-Z0-9_]+)$")
}
}
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
err := templates.ExecuteTemplate(w, fmt.Sprintf("%s.tmpl", tmpl), p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// render template and render view template may be redundent
func renderViewTemplate(w http.ResponseWriter, p *Page) {
err := templates.ExecuteTemplate(w, "base.tmpl", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
m := validPath.FindStringSubmatch(r.URL.Path)
if m == nil {
http.NotFound(w, r)
return
}
fn(w, r, m[2])
}
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
// this is so things like "localhost:8080/smeg" don't resolve to root
validRootPath := regexp.MustCompile("^/$")
m := validRootPath.FindStringSubmatch(r.URL.Path)
if m == nil {
http.NotFound(w, r)
return
}
if config.Environment == "dev" {
renderTemplate(w, "index_dev", &Page{"Index", nil, getLinks()})
} else {
renderTemplate(w, "index", &Page{"Index", nil, getLinks()})
}
}
func editHandler(w http.ResponseWriter, r *http.Request, title string) {
p, err := LoadPage(title)
if err != nil {
p = &Page{title, nil, getLinks()}
}
renderTemplate(w, "edit", p)
}
func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
body := r.FormValue("body")
p := &Page{title, []byte(body), getLinks()}
err := p.Save()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
initHandlerGlobals()
http.Redirect(w, r, "/view/"+title, http.StatusFound)
}
func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
p, err := LoadPage(title)
if err != nil {
http.NotFound(w, r)
return
}
renderViewTemplate(w, p)
}
<file_sep>package main
import (
"fmt"
"strings"
"testing"
)
// TODO pass in testing.T for logging
func printTokens(tokStream []Token) {
for _, tok := range tokStream {
var typ string
switch tok.t {
case PLAIN:
typ = "PLAIN"
case BOLD:
typ = "BOLD"
case ITALIC:
typ = "ITALICS"
case LINKSTART:
typ = "LINKSTART"
case LINKEND:
typ = "LINKEND"
case LINKTEXTSTART:
typ = "LINKTEXTSTART"
case LINKTEXTEND:
typ = "LINKTEXTEND"
case QUOTE:
typ = "QUOTE"
case CODE:
typ = "CODE"
case HEADING:
typ = "HEADING"
case PLAINNEXT:
typ = "PLAINNEXT"
case ENDOFARTICLE:
typ = "ENDOFARTICLE"
case ENDOFPARAGRAPH:
typ = "ENDOFPARAGRAPH"
}
fmt.Printf("\t[%s]%s\n", typ, string(tok.v))
}
fmt.Printf("\n")
}
/*
var testPattern string = `this is some plain jane text
this is some *bold* text
this is some _italicized_ text
this is a <http://localhost:8080/view/format>(link)
# this is quoted text
: this is some code\(\)
`
*/
// TODO add links (above)
var testPattern string = `! An article heading
A paragraph with plain jane text
A paragraph with *bold* text
A paragraph with _italicized_ text
# this is quoted text
: this is some code\(\)
\!\#\:\(\)
;ENDOFARTICLE;
!New Article
`
func TestLex(t *testing.T) {
initParserGlobals()
tokStream := lex(strings.NewReader(testPattern))
printTokens(tokStream)
}
func TestParse(t *testing.T) {
initParserGlobals()
ret := parseToHtml(testPattern)
t.Logf("%s\n", ret)
}
<file_sep>package main
import (
"fmt"
"io/ioutil"
)
type Page struct {
Title string
Body []byte
Links []string
}
func (p *Page) Save() error {
return ioutil.WriteFile(fmt.Sprintf("data/%s.wbml", p.Title), p.Body, 0600)
}
func LoadPage(title string) (*Page, error) {
body, err := ioutil.ReadFile(fmt.Sprintf("data/%s.wbml", title))
if err != nil {
return nil, err
}
return &Page{title, body, getLinks()}, nil
}
<file_sep>window.addEventListener('load', function() {
var createPageInputElement = document.getElementById('dev_create_page_input');
var createPageButtonElement = document.getElementById('dev_create_page_button');
createPageButtonElement.onclick = function(){
window.location.assign("/edit/" + createPageInputElement.value);
return false;
}
});
<file_sep># webServer
my blog's webserver
|
25007a6981cf53c5d535bcec3ec003106a2a0334
|
[
"JavaScript",
"Go",
"Markdown"
] | 9
|
Go
|
wesleyParriott/webServer
|
3c2bf78a42086e451185e2669ea7da4953e9e377
|
7b38983979917e9abce81dfc935a5a2f1ec97ede
|
refs/heads/master
|
<repo_name>Swifty-Sousa/Spotify-Filter<file_sep>/spotifilter.py
#Author: <NAME>
#hackcu V project
#$https://open.spotify.com/user/dlu950yaxcioasmyl8zq38tle?si=npAstWIzSl-1Ptxh20p9_g
#required imports
import spotipy
import spotipy.util as util
from keys import CLIENT_ID, CLIENT_SECRET
import sys
import json
import time
#authenticator for app, authenticates client
#print(json.dumps(VAR, sort_keys=True, indent=4))
#this is the username
USER= "dlu950yaxcioasmyl8zq38tle?si=npAstWIzSl-1Ptxh20p9_g"
def auth():
username= "dlu950yaxcioasmyl8zq38tle?si=npAstWIzSl-1Ptxh20p9_g"
scope= "user-read-currently-playing user-modify-playback-state playlist-read-private playlist-modify-private"
token =util.prompt_for_user_token(USER, scope, client_id= CLIENT_ID, client_secret= CLIENT_SECRET, redirect_uri= "http://google.com/")
spo= spotipy.Spotify(auth=token)
return spo
def get_curr_song(spo):
user=spo.current_user()
song_data= spo.current_user_playing_track()
#print(json.dumps(user, sort_keys=True, indent=4))
#print(json.dumps(song_data, sort_keys=True, indent=4))
#print(song_data["item"]["name"])
#print(song_data["item"]["album"]["artists"][0]["name"])
#print(json.dumps(song_data, sort_keys=True, indent=4))
song_name= song_data["item"]["name"]
song_art= song_data["item"]["album"]["artists"][0]["name"]
#print(song_name)
#print(song_art)
return [song_name, song_art]
#retruns playlist data
def play_data(spo):
play_lists= spo.current_user_playlists()
#print(json.dumps(play_lists["items"][0], sort_keys=True, indent=4))
for i in range(0, len(play_lists["items"])):
if play_lists["items"][i]["name"] == "Blocked_Songs":
play_id= play_lists["items"][i]["id"]
play_uri= play_lists["items"][i]["uri"]
#print(play_uri)
#print(json.dumps(play_lists["items"][i], sort_keys=True, indent=4))
#print(play_id)
track_list=spo.user_playlist_tracks(play_uri.split(':')[2], play_uri.split(':')[4])
#ßprint(track_list)
tracks=track_list["items"]
#print(json.dumps(tracks[0], sort_keys=True, indent=4))
#print(tracks[0]["track"]["name"])
Tracks=[]
for i in range(0,len(tracks)):
Tracks.append([tracks[i]["track"]["name"], tracks[i]["track"]["artists"][0]["name"]])
#print(tracks[i]["track"]["name"])
#print(tracks[i]["track"]["artists"][0]["name"])
return Tracks
#asyc function to controll unit
def execute(spo, blocked_tracks):
current_song=spo.current_user_playing_track()
holder=get_curr_song(spo)
for i in range(0,len(blocked_tracks)):
#print(blocked_tracks[i][0] + ", "+ blocked_tracks[i][1])
if blocked_tracks[i]==current_song:
spo.next_track()
execute(spo, blocked_tracks)
return
while holder==get_curr_song(spo):
time.sleep(1)
execute(spo, blocked_tracks)
#main controller
def main():
spo=auth()
print(json.dumps(spo.current_user_playing_track(), sort_keys=True, indent=4))
#test2(spo)
blocked_tracks=play_data(spo)
execute(spo,blocked_tracks)
main()<file_sep>/tests/test.py
import os
def main():
a=["a","b","c"]
os.system("g++ -std=c++11 test.cpp")
a=input(os.system("./a.out"))
print("recived number")
print(a)
main()
|
babde163bbee344d1b2e1485caf33db610759f72
|
[
"Python"
] | 2
|
Python
|
Swifty-Sousa/Spotify-Filter
|
fb9d09d50530260aff1be985ace08fed14c12abf
|
e346be0a656a7f55b1dca61d3a397465d51e294f
|
refs/heads/master
|
<repo_name>tymo77/battleship-game<file_sep>/original_version/Battleship.py
from random import randint
import winsound
##Board Setup
board = []
quit=False
print("Welcome to Battleship\n")
print("X\'s correspond to places you have fired. O\'s are places you have not fired. *\'s are hits")
size=int(input("What size board would you like? 2->2x2, 3->3x3 etc...\n"))
for x in range(size):
board.append(["O"] * size)
def print_board(board):
print("-"*(len(board)*2-1))
for row in board:
print(" ".join(row))
print("-"*(len(board)*2-1))
print("Let's play Battleship!")
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
print (ship_row+1)
print (ship_col+1)
##Turns
turn=0;
#loop runs while there is no quit signal
while quit==False:
#label turn number and initialize guesses
print("\nTurn", turn+1)
guess_row=""
guess_col=""
#request first guess and check for quit
guess_row = input("Guess Row: ")
if guess_row=="q" or guess_col=="q":
quit=True
break
#request second guess and check for quit
guess_col = input("Guess Col: ")
if guess_row=="q" or guess_col=="q":
quit=True
break
#convert each to integer and check each for data type
try:
guess_col=int(guess_col)-1
except:
print("Guess an integer or q to quit. Try Again.")
guess_col = int(input("Guess Col: "))-1
try:
guess_row=int(guess_row)-1
except:
print("Guess an integer or q to quit. Try Again.")
guess_row = int(input("Guess Row: "))-1
winsound.PlaySound("C:\\Users\\Tyler\\fire.wav",winsound.SND_FILENAME)
#check hit mit or repeat and return results
if guess_row == ship_row and guess_col == ship_col:
winsound.PlaySound("C:\\Users\\Tyler\\hit.wav", winsound.SND_ALIAS)
print("Congratulations! You sunk my battleship!")
board[guess_row][guess_col] = "*"
print_board(board)
break
else:
if (guess_row < 0 or guess_row > size-1) or (guess_col < 0 or guess_col > size-1):
print("Oops, that's not even in the ocean.")
elif(board[guess_row][guess_col] == "X"):
print("You guessed that one already.")
else:
winsound.PlaySound("C:\\Users\\Tyler\\miss.wav", winsound.SND_ALIAS)
print("You missed my battleship!")
board[guess_row][guess_col] = "X"
turn=turn+1
print_board(board)
#close game window
input("press ENTER to exit")<file_sep>/random_ships.py
#functions for picking random ship positions
from random import randint
from random import shuffle
def random_orientation():
return randint(0,1)
def determ_ship_space(length,size):
poss_ship_space=[]
orient=random_orientation()
if orient==0:
for x in range(size):
poss_ship_space.append(["@"]*(size-length+1))
else:
for x in range((size-length+1)):
poss_ship_space.append(["@"]*size)
start_row=random_row(poss_ship_space)
start_col=random_col(poss_ship_space)
ship_space=[]
for i in range(length):
if orient==0:
ship_space.append([start_row,start_col+i])
if orient==1:
ship_space.append([start_row+i,start_col])
return ship_space
def random_row(ship_space):
return randint(0, len(ship_space) - 1)
def random_col(ship_space):
return randint(0, len(ship_space[0]) - 1)
def convert_to_tuple_array(array_of_list_pairs):
temp=[]
for pair in array_of_list_pairs:
temp.append(tuple(pair));
return temp
def convert_to_array_array(array_of_tuples):
temp=[]
for pair in array_of_tuples:
temp.append(list(pair));
return temp
def place_n_ships(lengths,size):
no_ships=len(lengths);
ship_spaces=[]; #ship_spaces is the place where all the selected ships and their addresses wait
level_counter=[0]*no_ships; #intialize the counter for each level
total_count=0; #intialize the total count
ship_index=0; #the ship index is the current level of the search tree where the full depth is no_ships
shuffle(lengths)
while True:
print(total_count)
level_counter[ship_index]+=1;
total_count+=1;
#randomly pick a ship placement for ship
ship_space_guess=determ_ship_space(lengths[ship_index],size);
ship_space_guess=convert_to_tuple_array(ship_space_guess);
all_ship_spaces=sum(ship_spaces,[]);
#check if it fits
if set(ship_space_guess).isdisjoint(all_ship_spaces):
#add to list and move to next ship
ship_spaces.append(ship_space_guess);
if ship_index == no_ships-1:
break
else:
ship_index+=1;
else:
if total_count>=10000:
print("total count exceeded")
break
if level_counter[ship_index]>=100:
level_counter[ship_index]=0;
ship_index-=1;
ship_spaces.pop(ship_index);
#if not, try again
return ship_spaces
<file_sep>/battleship.py
##Board Setup
board = []
quit=False
from random import randint
import winsound
from random_ships import *
#welcome
print("Welcome to Battleship 2.0\n")
print("X\'s correspond to places you have fired. O\'s are places you have not fired. *\'s are hits")
#get board and snip sizes with error handling for ship length fitting and integer type
while True:
try:
default_game=str(input('Default Game? (Y/N)\n'))
if default_game=="Y" or default_game=="y":
default_game=True;
break
elif default_game=="N" or default_game=="n":
default_game=False;
break
else:
print("\n(Y/N)?");
except:
print("\nplay default game with default ships? (Y/N)");
if default_game==True:
ship_lengths=[2,3,3,4,5];
size=10;
else:
while True:
try:
size=int(input("What size board would you like? 2->2x2, 3->3x3 etc...\n"))
if size>0:
break
else:
print("\nboard size must be an integer greater than 0")
except:
print("\nboard size must be an integer greater than 0")
size=0
while True:
try:
no_ships=int(input('how many ships do you want?\n'))
if no_ships>0:
break
else:
print("\nyou must input a number of ships")
except:
print("\nnumber must be an integer")
no_ships=1;
ship_lengths=[0]*no_ships;
for ship in range(no_ships):
while True:
try:
ship_length=int(input('how long do you want ship '+str(ship+1)+'?\n'));
if ship_length<=size and sum(ship_lengths)<=size**2 and ship_length>=0:
ship_lengths[ship]=ship_length;
break
else:
print("\nyou must select a ship length that fits: %i or less" %size)
print("\nenter 0 to ignore this ship")
except:
print("\nship length must be an integer")
ship_length=0
while min(ship_lengths)<=0:
ship_lengths.remove(0);
print(ship_lengths)
#build board
for x in range(size):
board.append(["O"] * size)
#function for printing board from memory
def print_board(board):
guide=""
for n in range(1,len(board[0])+1):
guide=guide+str(n)+" "
print(" "+guide)
print(" "+"-"*(len(board)*2-1))
n=1
for row in board:
print(str(n)+"|"+str(" ".join(row))+"|")
n=n+1
print(" "+"-"*(len(board)*2-1))
#start game, get ship position, print position
print("\nLet's play Battleship!\n")
print_board(board)
ship_space=place_n_ships(ship_lengths,size)
print(ship_space)
##Turns
turn=0;
#loop runs while there is no quit signal
while quit==False:
#check for win condition
if sum(ship_space,[])==[]:
winsound.PlaySound("media\\sink.wav", winsound.SND_ALIAS)
print("Congratulations you sunk my fleet!")
break
#label turn number and initialize guesses
print("\nTurn", turn+1)
guess_row=""
guess_col=""
#request first guess and check for quit
guess_row = input("Guess Row: ")
if guess_row=="q" or guess_col=="q":
quit=True
break
#request second guess and check for quit
guess_col = input("Guess Col: ")
if guess_row=="q" or guess_col=="q":
quit=True
break
#convert each to integer and translate to code index and check each for data type
try:
guess_row=int(guess_row)-1
except:
print("Guess an integer or q to quit. Try Again.")
guess_row = int(input("Guess Row: "))-1
try:
guess_col=int(guess_col)-1
except:
print("Guess an integer or q to quit. Try Again.")
guess_col = int(input("Guess Col: "))-1
winsound.PlaySound("media\\fire.wav",winsound.SND_FILENAME)
#check hit miss or repeat and return resultsship
try:
sum(ship_space,[]).remove((guess_row,guess_col))
winsound.PlaySound("media\\hit.wav", winsound.SND_ALIAS)
print("You hit my ship!")
board[guess_row][guess_col] = "*";
for i in range(len(ship_space)):
if not set(ship_space[i]).isdisjoint(set([(guess_row,guess_col)])):
ship_space[i].remove((guess_row,guess_col));
except:
if (guess_row < 0 or guess_row > size-1) or (guess_col < 0 or guess_col > size-1):
print("Oops, that's not even in the ocean.")
elif(board[guess_row][guess_col] == "X"):
print("You guessed that one already and missed.")
elif(board[guess_row][guess_col] == "*"):
print("You guessed that one already and hit.")
else:
winsound.PlaySound("media\\miss.wav", winsound.SND_ALIAS)
print("You missed my battleship!")
board[guess_row][guess_col] = "X"
turn=turn+1
print_board(board)
#close game window
input("press ENTER to exit")<file_sep>/README.md
# battleship-game
Script written to expand the simple game of battleship introduced in the codeacademy.com lessons on python.
%run battleship.py - runs game
still in early stages
buggy WIP
intended eventual end use-is as a fun, customizable battleship game that enables the PvP, PvCOM and COMvCOM
COMvCOM may allow for testing battleship strategies through mass-computational methods
|
53c2ead1969157d7f2c185e26f80b3c4efa489fc
|
[
"Markdown",
"Python"
] | 4
|
Python
|
tymo77/battleship-game
|
13966e4694cef88afc9bc45b87e4055e9d557253
|
d627de857d5779d42997e245dd715738b71dcea8
|
refs/heads/master
|
<file_sep>require 'test_helper'
class RegisterWebhooksForActiveShopsTest < ActiveJob::TestCase
def setup
@shop_1 = shops(:regular_shop)
@shop_2 = shops(:second_shop)
end
def job
@job ||= ::RegisterWebhooksForActiveShops.new
end
test "RegisterWebhooksForActiveShops registers webhooks for all existing shops" do
ShopifyApp::WebhooksManagerJob.expects(:perform_now).with(
shop_domain: @shop_1.shopify_domain,
shop_token: @shop_1.shopify_token,
webhooks: ShopifyApp.configuration.webhooks
).once
ShopifyApp::WebhooksManagerJob.expects(:perform_now).with(
shop_domain: @shop_2.shopify_domain,
shop_token: @shop_2.shopify_token,
webhooks: ShopifyApp.configuration.webhooks
).once
job.perform_now
end
end
<file_sep>class AppUninstalledJob < ActiveJob::Base
def perform(args)
shop = Shop.find_by(shopify_domain: args[:shop_domain])
mark_shop_as_uninstalled(shop)
end
private
def mark_shop_as_uninstalled(shop)
shop.uninstall! if shop
end
end
<file_sep>module ShopLifecycleTestHelper
def assert_uninstalls(shopify_domain, &block)
assert_difference 'Shop.count', -1, "one shop should have been uninstalled", &block
assert_nil Shop.find_by(shopify_domain: shopify_domain), "shop #{shopify_domain} is still installed"
end
def assert_installed(shopify_domain)
assert_not_nil Shop.find_by(shopify_domain: shopify_domain)
end
def assert_no_installation_change
assert_difference 'Shop.count', 0 do
yield
end
end
end
<file_sep>require 'test_helper'
require 'helpers/shop_lifecycle_test_helper'
class ShopTest < ActiveSupport::TestCase
def setup
@shop_1 = shops(:regular_shop)
@shop_2 = shops(:second_shop)
end
test "#uninstall marks the shop as uninstalled" do
@shop_1.uninstall
assert_nil Shop.find_by(shopify_domain: @shop_1.shopify_domain)
assert_equal @shop_2, Shop.find_by(shopify_domain: @shop_2.shopify_domain)
end
test "#uninstall! marks the shop as uninstalled" do
@shop_1.uninstall!
assert_nil Shop.find_by(shopify_domain: @shop_1.shopify_domain)
assert_equal @shop_2, Shop.find_by(shopify_domain: @shop_2.shopify_domain)
end
end
<file_sep>require 'test_helper'
require 'helpers/shop_lifecycle_test_helper'
class AppUninstalledJobTest < ActiveJob::TestCase
include ShopLifecycleTestHelper
def setup
@shop_1 = shops(:regular_shop)
@shop_2 = shops(:second_shop)
end
def job
@job ||= ::AppUninstalledJob.new
end
test "AppUninstalledJob marks the shop as uninstalled from the app" do
assert_uninstalls @shop_1.shopify_domain do
job.perform(shop_domain: @shop_1.shopify_domain)
end
assert_installed @shop_2.shopify_domain
end
test "AppUninstalledJob does nothing for non-existent shop" do
assert_no_installation_change do
job.perform(shop_domain: 'example.myshopify.com')
end
end
end
<file_sep>class RegisterWebhooksForActiveShops < ApplicationJob
queue_as :default
def perform
register_webhooks_for_active_shops
end
private
def register_webhooks_for_active_shops
Shop.find_each do |shop|
ShopifyApp::WebhooksManagerJob.perform_now(
shop_domain: shop.shopify_domain,
shop_token: shop.shopify_token,
webhooks: ShopifyApp.configuration.webhooks
)
end
end
end
<file_sep># App Bridge Authentication
A demo app created using Rails, React, and App Bridge for the Shopify tutorial [Build a Shopify app with Rails, React, and App Bridge](https://shopify.dev/tutorials/build-rails-react-app-that-uses-app-bridge-authentication).
## Quick Start
To run this app locally, you can clone this repository and do the following.
1. Create a `.env` file to specify this app's `API key` and `API secret key` app credentials that can be found in the Shopify Partners dashboard.
```
SHOPIFY_API_KEY=<The API key app credential specified in the Shopify Partners dashboard>
SHOPIFY_API_SECRET=<The API secret key app credential specified in the Shopify Partners dashboard>
APP_URL=<The app URL specified in the Shopify Partners dashboard>
```
> __Note:__ If you do not have an API key or an API secret key, see the following sections of the [Build a Shopify App with Node and React](https://shopify.dev/tutorials/build-a-shopify-app-with-node-and-react/embed-your-app-in-shopify#get-a-shopify-api-key) guide.
>
>> **Important**: This guide names its API secret key environment variable `SHOPIFY_API_SECRET_KEY` rather than `SHOPIFY_API_SECRET`. The Shopify App gem uses the latter.
>
> 1. [Expose your dev environment](https://shopify.dev/tutorials/build-a-shopify-app-with-node-and-react/embed-your-app-in-shopify#expose-your-dev-environment)
> 2. [Get a Shopify API Key and Shopify API secret key](https://shopify.dev/tutorials/build-a-shopify-app-with-node-and-react/embed-your-app-in-shopify#get-a-shopify-api-key)
> 3. [Add the Shopify API Key and Shopify API secret key](https://shopify.dev/tutorials/build-a-shopify-app-with-node-and-react/embed-your-app-in-shopify#add-the-shopify-api-key)
2. Run the following to install the required dependencies.
```console
$ bundle install
$ yarn install
$ rails db:migrate
```
3. Ensure ngrok is running on port `3000`.
```console
$ ngrok http 3000
```
> __Note:__ This port number is arbitrary - you may choose to specify the port number you plan to listen to this app on.
4. Run the following to start the app.
```console
$ rails s
```
5. Install and open this app on a shop. Requests to authenticated resources, like the `GraphqlController`, should now be secured with an `Authorization: Bearer <session token>` header.
![App dashboard][s1]
_**Above:** Example text received from a protected `/graphql` endpoint_
![App requests][s2]
_**Above:** Requests made to the protected `/graphql` endpoint are automatically
authorized using a JWT token_
[//]: # "Links"
[s1]: ./app/assets/images/screenshot-1.png
[s2]: ./app/assets/images/screenshot-2.png
|
6501621f33c7a13945deb273b8beee1bcc3e0a4a
|
[
"Markdown",
"Ruby"
] | 7
|
Ruby
|
Shopify/next-gen-auth-app-demo
|
6b8ab262614b1f2549dd73482743d3b9c8ddf0d3
|
89f540837087bf82238f9112f343afe609e869c8
|
refs/heads/master
|
<file_sep>"""
Dijkstra's algorithm
"""
from collections import defaultdict
class Graph:
nodes = set()
edges = defaultdict(list)
distances = dict()
def add_edge(self, a, b, distance):
self.nodes.add(a)
self.nodes.add(b)
self.edges[a].append(b)
self.edges[b].append(a)
self.distances[(a, b)] = distance
self.distances[(b, a)] = distance
def dijkstra(graph, source):
dist = dict()
prev = dict()
dist[source] = 0
nodes = g.nodes.copy()
titleline = ' '.join(sorted(nodes - set([source])))
print(r'\begin{tabular}{cc' + 'c' * len(nodes) + '}')
print('\t' +
'step & visited & ' + titleline.strip().replace(
' ', ' & ')
+ r'\\\hline')
for node in nodes:
if not node == source:
dist[node] = g.distances.get((node, source), 99999)
prev[node] = source if dist[node] < 99999 else None
while nodes:
u = min(nodes)
nodes.remove(u)
for neighbour in g.edges[u]:
alt = dist[u] + g.distances[(u, neighbour)]
if alt < dist[neighbour]:
dist[neighbour] = alt
prev[neighbour] = u
visited = sorted(g.nodes - nodes)
step = len(visited)
table = ''
for node in sorted(g.nodes - set([source])):
if prev[node]:
table += '{},{} & '.format(
dist[node], prev[node])
else:
table += '{} & '.format(dist[node])
table = table.replace('99999', r'$\inf$')
print('\t{} & {} & '.format(step, ''.join(visited))
+ table + r'\\')
print(r'\end{tabular}')
return (dist, prev)
if __name__ == '__main__':
g = Graph()
g.add_edge('t', 'u', 2)
g.add_edge('t', 'v', 4)
g.add_edge('t', 'y', 7)
g.add_edge('u', 'v', 3)
g.add_edge('u', 'w', 3)
g.add_edge('v', 'w', 3)
g.add_edge('v', 'x', 3)
g.add_edge('v', 'y', 8)
g.add_edge('w', 'x', 6)
g.add_edge('x', 'y', 6)
g.add_edge('x', 'z', 8)
g.add_edge('y', 'z', 12)
print(r'\subsection{from x}')
dijkstra(g, 'x')
print(r'\subsection{from t}')
dijkstra(g, 't')
print(r'\subsection{from v}')
dijkstra(g, 'v')<file_sep>#include <stdio.h>
#include <stdlib.h>
#define BILLETES 5
int denom[] = {200,100,50,20,10};
int solucion[BILLETES];
int main ()
{
int i, devolucion;
printf("devolucion: ");
scanf ("%d",&devolucion);
//inicializacion de vector solucion
for (i = 0; i < BILLETES; i++){
solucion[i] =0;
}
//-- bucle voraz
for (i = 0; i < BILLETES; i++){
while (devolucion >= denom[i])
{
solucion[i]++;
devolucion-= denom[i];
}
//-- fin del bucle voraz
}
if (devolucion!=0) // !0
printf ("No hay Billetes para devolver\n");
else
//mostramos la solucion
for (i = 0; i < BILLETES; i++)
if (solucion[i])
printf ("%d Billetes de %d\n", solucion[i], denom[i]);
system ("pause");
return 0;
}
<file_sep><!DOCTYPE html>
<html>
<head>
<title>PROBLEMA DE LA MOCHILA</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
<link rel="stylesheet" href="centrar.css">
<script>
/*Funcion de Capturar, Almacenar datos y Limpiar campos*/
$(document).ready(function(){
$('#boton-guardar').click(function(){
/*Captura de datos escrito en los inputs*/
var cap = document.getElementById("capacidadtxt").value;
/*Guardando los datos en el LocalStorage*/
localStorage.setItem("Capacidad", cap);
/*Limpiando los campos o inputs*/
document.getElementById("capacidadtxt").value = "";
});
});
/*Funcion Cargar y Mostrar datos*/
$(document).ready(function(){
$('#boton-cargar').click(function(){
/*Obtener datos almacenados*/
var capacidad = localStorage.getItem("Capacidad");
/*Mostrar datos almacenados*/
document.getElementById("capacidad").innerHTML = capacidad;
});
});
</script>
</head>
<body>
<header>
<center><div class="container">
<h1>
<br>
<strong>
PROBLEMA DE LA MOCHILA
</strong>
</br>
</h1>
</div></center>
</header>
<center><p1>Capacidad de la mochila</p1>
<input type="text" placeholder="Capacidad" id="capacidadtxt"> <br> <br>
<button id="boton-guardar">Guardar</button><br>
<hr />
Capacidad:
<label type="text" id="capacidad"></label><br>
<button id="boton-cargar">
Cargar elementos
</button>
</center>
<hr />
<center>
<form method="POST" action="moch.php">
<?php
if(isset($_POST['Siguiente']))
$cantidad=$_POST['nvalor'];
for ($i=1; $i<=$cantidad; $i++) { ?>
<label for="peso[]">Peso: </label>
<input type="text" name="peso[]"><br>
<label for="valor[]">Valor: </label>
<input type="text" name="valor[]"><br>
<?php } ?>
<input type="submit" name="Siguiente" value = "Siguiente">
</form>
<br>
</center>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="submit" name="" value="resultado" id="boton1" onclick = "evaluar();">
</body>
</html>
<?php
function mostrarTexto($texto) {
echo "<strong>El texto a mostrar es el siguiente: </strong>";
echo $texto;
}
mostrarTexto("Me gusta mucho la web de aprenderaprogramar.com");
//Fin de declaración de funciones
$array_peso = array(12, 12, 23, 14, 25,11);
$array_ganancia=array(20, 20, 40, 50, 60,22);
$numero_objetos=count($array_peso);
echo "$numero_objetos";
$capacidad=200;
function evaluar ($capacidad, $array_peso, $array_ganancia, $numero_objetos){
for ($i=1; $i <= $numero_objetos; $i++) {
if ($array_peso[$i] > $capacidad) {
$array_ganancia[$i] = 0;
}
$array_poblacion[$i] = sprintf('%1$0'.$numero_objetos.'b',$i);
echo "<tr><td>".$array_peso[$i]."</td> <td>".$array_ganancia[$i]."</td><td>".$array_poblacion[$i]."</td></tr>";
@$suma = $suma + $array_ganancia[$i];
}
echo"</table></div>";
$porcentaje = 100/$suma;
for ($i=1; $i <= $numero_objetos; $i++) {
$array_porcentaje[$i] = $porcentaje * $array_ganancia[$i];
}
for($j=1; $j<=2; $j++){
$random = rand(0, 100);
echo"<script> alert('Ruleta:".$random."');</script>";
$suma2 = 0;
for ($i=1; $i <= $numero_objetos; $i++) {
if ($array_ganancia[$i] == 0) {
}
else{
$suma2 = $suma2 + $array_porcentaje[$i];
if ($random <= $suma2) {
$array_elegido[$j] = $array_poblacion[$i];
break;
}
else{
}
}
}
}
?>
<div id='resultados'>
<div id="elegidos">
<h3> Elegidos</h3>
<?php
for($j=1; $j<=2; $j++){
echo"<p>".$array_elegido[$j]."</p>";
}
$genes = preg_split('//', $array_elegido[1], -1, PREG_SPLIT_NO_EMPTY);
$genes2 = preg_split('//', $array_elegido[2], -1, PREG_SPLIT_NO_EMPTY);
$aux = $genes[2];
$genes[2] = $genes2[2];
$genes2 = $aux;
echo"<p>Optimo:</p>";
foreach ($genes as $key) {
echo"".$key."";
}
echo"</div></div>";
}
?><file_sep>#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
class Nodo
{
public:
int nro;
Nodo *sgte;
};
typedef Nodo *Tlista;
class Lista
{
private:
int nro;
int valor;
int pos;
public:
Lista(int=0, int=0, int=0);
void InsertarInicio(Tlista &lista, int=0);
void InsertarFinal(Tlista &lista, int=0);
int InsertarAntesDespues();
void InsertarElemento(Tlista &lista, int=0, int=0);
void BuscarElemento(Tlista lista, int=0);
void ReportarLista(Tlista lista);
void EliminarElemento(Tlista &lista, int=0);
void EliminarRepetidos(Tlista &lista, int=0);
void OrdenarLista(Tlista lista);
void menu();
};
Lista::Lista(int _nro, int _valor, int _pos)
{
nro= _nro;
valor= _valor;
pos= _pos;
}
void Lista::OrdenarLista(Tlista lista){
Tlista actual , siguiente;
int t;
actual = lista;
while(actual->sgte != NULL)
{
siguiente = actual->sgte;
while(siguiente!=NULL)
{
if(actual->nro > siguiente->nro)
{
t = siguiente->nro;
siguiente->nro = actual->nro;
actual->nro = t;
}
siguiente = siguiente->sgte;
}
actual = actual->sgte;
siguiente = actual->sgte;
}
}
void Lista::InsertarInicio(Tlista &lista, int valor)
{
Tlista q;
q= new(Nodo);
q->nro= valor;
q->sgte= lista;
lista= q;
system("cls");
}
void Lista::InsertarFinal(Tlista &lista, int valor){
Tlista t, q= new(Nodo);
q->nro= valor;
q->sgte= NULL;
if(lista==NULL)
lista=q;
else
{
t= lista;
while(t->sgte != NULL)
t= t->sgte;
t->sgte= q;
}
system("cls");
}
int Lista::InsertarAntesDespues(){
int op, band;
cout<<"\n\t 1. Antes de la pocision \n\t 2. Despues de la posicion \n\t Opcion: ";
cin>>op;
if(op==1)
band= -1;
else
band= 0;
return band;
system("cls");
}
void Lista::InsertarElemento(Tlista &lista, int valor, int pos){
Tlista q, t;
int i;
q= new(Nodo);
q->nro= valor;
if(pos == 1)
{
q->sgte= lista;
lista= q;
}
else
{
int x= InsertarAntesDespues();
t= lista;
for(i=1; t!=NULL; i++)
{
if(i == pos+x)
{
q->sgte= t->sgte;
t->sgte= q;
return;
}
t= t->sgte;
}
}
cout<<"\t Error, posicion no encontrada"<<endl;
system("cls");
}
void Lista::BuscarElemento(Tlista lista, int valor){
Tlista q= lista;
int i=1, band=0;
while(q != NULL)
{
if(q->nro == valor)
{
cout<<"\n Encontrada en posicion "<<i<<endl;
band= 1;
}
q= q->sgte;
i++;
}
if(band == 0)
cout<<"\n Numero no encontrado "<<endl;
getch();
system("cls");
}
void Lista::ReportarLista(Tlista lista){
int i= 0;
while(lista != NULL)
{
cout<<' '<<i+1<<") "<<lista->nro<<endl;
lista= lista->sgte;
i++;
}
getch();
system("cls");
}
void Lista::EliminarElemento(Tlista &lista, int valor){
Tlista p, ant;
p= lista;
if(lista != NULL){
while(p != NULL){
if(p->nro == valor){
if(p == lista){
lista = lista->sgte;
system("cls");
}
else{
ant->sgte= p->sgte;
}
delete(p);
return;
}
ant = p;
p= p->sgte;
system("cls");
}
}
else
cout<<"\n Lista Vacia"<<endl;
getch();
system("cls");
}
void Lista::EliminarRepetidos(Tlista &lista, int valor){
Tlista q, ant;
q= lista;
ant= lista;
while(q != NULL)
{
if(q->nro == valor)
{
if(q == lista)
{
lista= lista->sgte;
delete(q);
q= lista;
}
else
{
ant->sgte= q->sgte;
delete(q);
q= ant->sgte;
}
}
else
{
ant= q;
q= q->sgte;
}
}
cout<<"\n Valores eliminados"<<endl;
}
void Lista::menu(){
cout<<"\n\t Lista enlazada simple \n\n";
cout<<" 1. Insertar al Inicio\n";
cout<<" 2. Insertar al Final\n";
cout<<" 3. Insertar en una posicion\n";
cout<<" 4. Reportar lista\n";
cout<<" 5. Buscar elemento\n";
cout<<" 6. Eliminar elemento 'v'\n";
cout<<" 7. Eliminar elementos con valor 'v'\n";
cout<<" 8. Ordenar elementos\n";
cout<<" 9. Salir\n";
cout<<" Ingrese una opcion: ";
}
int main(){
Tlista lista= NULL;
Lista list;
int op, dato ,_pos;
do{
list.menu();
cin>>op;
switch(op){
case 1:
cout<<"\n Numero a insertar: ";
cin>>dato;
list.InsertarInicio(lista,dato);
break;
case 2:
cout<<"\n Numero a insertar: ";
cin>>dato;
list.InsertarFinal(lista, dato);
break;
case 3:
cout<<"\n Numero a insertar: ",
cin>>dato;
list.InsertarElemento(lista, dato, _pos);
break;
case 4:
cout<<"\n Mostrando Lista\n";
list.ReportarLista(lista);
break;
case 5:
cout<<"\n Valor a buscar: ";
cin>>dato;
list.BuscarElemento(lista,dato);
break;
case 6:
cout<<"\n Valor a eliminar: ";
cin>>dato;
list.EliminarElemento(lista, dato);
break;
case 7:
cout<<"\n Valor repetido a eliminar: ";
cin>>dato;
list.EliminarRepetidos(lista, dato);
break;
case 8:
cout<<"\nLista ordenada: ";
list.OrdenarLista(lista);
cout<<"\n\n";
system("pause");
system("cls");
}
}while(op!=9);
system("pause");
return 0;
}
<file_sep>import sys
"""
Skeleton for dijkstra.py. Based on code originally written by <NAME>.
Brought to you by wikinotes.ca.
"""
# Based on the original HeapNode class, only modified slightly
class HeapNode:
def __init__(self, vertex, edge, value=sys.maxint):
"""
Each heap node represents a vertex, has a value (i.e. the
shortest distance between it and the set of found vertices),
and points to an edge in the graph that corresponds to the
value above.
"""
self.vertex = vertex
self.value = value
self.edge = edge
self.path = []
def __repr__(self):
return "(vertex: %d, val: %d, edge: %s)" % (self.vertex, self.value, self.edge)
# Helper class - not part of original
class Graph:
def __init__(self, edges):
self.edges = edges
# Based on the original HeapSwap() method
def swap_heap_elements(self, i, j):
i_index = self.heap[i].vertex
j_index = self.heap[j].vertex
# Because swapping variables in python doesn't require temp vars <3
self.pointers[i_index], self.pointers[j_index] = self.pointers[j_index], self.pointers[i_index]
self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
# Implement this method
def get_right_child(self, i):
"""
Returns the index of the right child of an element in the heap
(identified by its index)
"""
pass
# Implement this method
def get_left_child(self, i):
"""
Returns the index of the left child of an element in the heap.
If there is no parent, returns None
"""
pass
# Implement this method
def get_parent(self, i):
"""
Returns the index of the parent of an element in the heap. The list
is 0-indexed. If there is no parent, returns None
"""
pass
# Implement this method
def heapify_up(self, i):
"""
If the value at the index is smaller than the value of the parent,
swap the two. Keeps going recursively.
"""
pass
# Helper method, not part of original
def is_valid_index(self, i):
if i < 0 or i >= len(self.heap):
return False
else:
return True
# Helper method, not part of original
def get_min_child(self, i):
right = self.get_right_child(i)
left = self.get_left_child(i)
if self.is_valid_index(left):
left_value = self.heap[left].value
if self.is_valid_index(right):
right_value = self.heap[right].value
return right if right_value < left_value else left
else:
# There only is a left child. Return the left child
return left
else:
# No children
return None
# Implement this
def heapify_down(self, i):
"""
If the value at the index s greater than either of its children,
swap as necessary. Keeps going recursively.
"""
pass
# Implement this
def remove_heap_min(self):
"""
Removes the minimum element of the heap (don't forget the change
the pointer to it to None
"""
pass
# Implement this method
def heap_insert(self, node):
"""
Inserts a new element into the heap, respecting the min-heap
property. May need an index parameter - or maybe not?
No, it doesn't. Incidentally these heap methods would be more
fitting as instance methods on a Heap class but whatever too late.
"""
pass
# Implement this method
def decrease_value(self, i, new_value):
"""
Changes the value of a node to the new value (which must be lower
than the previous value), respecting the min-heap property etc.
"""
pass
# Based on the original MakeHeap() method
def make_heap(self):
"""
Initialises the heap by making a heap node for each vertex and
inserting each heap node into the heap. Called in get_distances()
"""
self.heap = []
self.pointers = [] # set here because it's only used for the heap
self.nodes = [] # keep track of them here because the heap is modified
for i in xrange(self.num_nodes):
node = HeapNode(i, self.cheap_edges[i], value=self.values[i])
self.nodes.append(node)
self.pointers.append(i)
self.heap_insert(node)
# Based on the original InitValues() method
def init_values(self):
"""
Initialises the values and cheap edges lists for the heap. Called
in get_distances
"""
# First initialise all the lists etc and calculate the number of nodes
self.num_nodes = len(self.edges)
self.distances = [sys.maxint] * self.num_nodes
self.cheap_edges = [0] * self.num_nodes
self.values = [0] * self.num_nodes
for i in xrange(self.num_nodes):
if i == self.start:
self.values[i] = 0
else:
min_value = sys.maxint # sigh
min_edge = []
for edge in self.edges[self.start]:
if edge[1] == i:
# edge[2] is the value
if edge[2] < min_value:
min_value = edge[2]
min_edge = edge
self.values[i] = min_value
self.cheap_edges[i] = min_edge
self.distances[self.start] = 0
# Implement this method
def decrement_adjacent_edges(self, node):
"""
Checks all edges adjacent to the given vertex. For each edge that
leads to a vertex found in the heap, we calculate the cost of
reaching that vertex through the cheapest path from the starting
vertex to the given vertex plus the new edge etc.
If this value is less than the current value of the heap node,
we decrease the value of the node and record the new cheap edge
as the node's edge
"""
pass
# Implement this method
def get_distances(self, start):
"""
This is where you do the Dijkstra stuff.
Gets the shortest path from the start node to every other.
Returns a tuple of lists: the first is the list of the distances.
The second list is a list of lists, each of which shows the path.
"""
return ([], [])
# Only run this if called through `python dijkstra.py`
# That way you can test it more easily etc
if __name__ == '__main__':
filename = sys.argv[1]
start = int(sys.argv[2])
f = open(filename)
num_nodes = int(f.readline()) # Not actually necessary (see len(edges))
# Back to using eval because linux is running an old version of Python...
edges = eval(f.readline())
f.close()
# Create a Graph object with the given edges
graph = Graph(edges)
# Print out the distance of the shortest path to every vertex from start
# Then, print out the paths taken
# This returns a tuple - the distances, and the parents
distances, paths = graph.get_distances(start)
print distances
for path in paths:
print path
<file_sep>#include<conio.h>
#include<iostream>
using namespace std;
int main(){
int bill[]={10,20,50,100,200};
int nbill[]={10,10,10,10,10};
int ent[]={0,0,0,0,0};
int ntipos =5;
int saldo;
saldo=70;
ntipos=5;
int isaldo;
do{
isaldo = saldo;
for(int i=ntipos-1;i>=0;i--){
if (saldo >=bill[i])
if (nbill[i]>0){
saldo=saldo-bill[i];
nbill[i]--;
ent[i]++;
break;
}
}
}while(saldo>0 && isaldo != saldo);
if (isaldo ==saldo){
cout<<"no se puede emitir ese monto";
}
else if (saldo==0){
for (int i=0;i<ntipos;i++){
cout<<"array"<<ent[i]<<endl;
}
}
}
<file_sep><!DOCTYPE html>
<html>
<head>
<title>PROBLEMA DE LA MOCHILA</title>
<meta charset="utf-8">
<meta name="viejport" content="jidth=device-jidth, initial-scale=1, shrink-to-fit=no">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
<link rel="stylesheet" href="centrar.css">
</head>
<header><div class="container">
<h1>
<br>
<strong>
PROBLEMA DE LA MOCHILA
</strong>
</br>
</h1>
</div></header>
<body>
</body>
</html>
<script>
/*Funcion de Capturar, Almacenar datos y Limpiar campos*/
$(document).ready(function(){
$('#boton-guardar').click(function(){
/*Captura de datos escrito en los inputs*/
var cap = document.getElementById("capacidadtxt").value;
/*Guardando los datos en el LocalStorage*/
localStorage.setItem("Capacidad", cap);
/*Limpiando los campos o inputs*/
document.getElementById("capacidadtxt").value = "";
});
});
/*Funcion Cargar y Mostrar datos*/
$(document).ready(function(){
$('#boton-cargar').click(function(){
/*Obtener datos almacenados*/
var capacidad = localStorage.getItem("Capacidad");
/*Mostrar datos almacenados*/
document.getElementById("capacidad").innerHTML = capacidad;
});
});
</script>
<hr />
Capacidad:
<label type="text" id="capacidad"></label><br>
<button id="boton-cargar">
Cargar elementos
</button>
</center>
<hr />
<script>
var capacidad = localStorage.getItem("Capacidad");
</script>
<?php
$nvalor = 6;
$valor = array(60, 100, 120,130,200,33);
$peso = array(10, 20, 30,40,50,12);
//$capacidad = "capacidad";
$result = mochila($capacidad, $peso, $valor, $nvalor);
//$nvalor=$_POST['nvalor'];
//$capacidad=$_POST['capacidad'];
//$valor=(array)$_POST['valor[]'];
//$peso=(array)$_POST['peso[]'];
//$capacidad=$_POST['capacidad'];
function mochila($capacidad, $peso, $valor, $nvalor)
{
$K = array();
for ($i = 0; $i <= $nvalor; ++$i)
{
for ($j = 0; $j <= $capacidad; ++$j)
{
if ($i == 0 || $j == 0)
$K[$i][$j] = 0;
else if ($peso[$i - 1] <= $j)
$K[$i][$j] = max($valor[$i-1] + $K[$i-1][$j- $peso[$i-1]], $K[$i-1][$j]);
else
$K[$i][$j] = $K[$i-1][$j];
}
}
return $K[$nvalor][$capacidad];
}
echo'<br>';
echo '<div class="center"> Valor máximo obtenido: '. $result.' </div>';
//echo "$result";
?>
|
2eac1094ff0443b45a517a247e81a06dea04e0ac
|
[
"Python",
"C++",
"PHP"
] | 8
|
Python
|
omaxpower/Analisis-de-algoritmos
|
ce7ce4231700f57d93ecdd16ff5292187c187605
|
c65043840f92534b2474ffb4fdac3f4a086fc1b8
|
refs/heads/main
|
<file_sep>for i in range(0,10):
for j in range(2,3):
if i % j == 0:
break
else:
print(i)<file_sep>"# PAs"
<file_sep>empty_list = []
city_list = ["Oakland", "Atlanta", "New York City", "Seattle", "Memphis", "Miami", "Boston", "Los Angeles", "Denver", "New Orleans"]
print(city_list)
city_list[0] = "San Francisco"
city_list[2] = "Brooklyn"
city_list[7] = "Hollywood"
city_list[5] = "Tampa"
print(city_list)
sports_list = ["Basketball", "Soccer", "Football", "Hockey", "Track and Field", "Baseball", "Tennis",]
print(sports_list)
print(sports_list[5])
print(sports_list[0])
city_list.sort(key=len)
print(city_list)<file_sep>foods = {"chicken":1.59, "beef":1.99, "cheese":1.00, "milk":2.50}
NBA_players = {"<NAME>": 23 , "<NAME>": 25, "<NAME>" : 24,
"<NAME>": 30, "<NAME>": 0, "<NAME>": 23 }
chicken_price = foods["chicken"]
print(chicken_price)
beef_price = foods["beef"]
print(beef_price)
cheese_price = foods["cheese"]
print(cheese_price)
milk_price = foods["milk"]
print(milk_price)
james_num = NBA_players["<NAME>"]
print(james_num)
shoes = {"Jordan_13": 1, "Yeezy": 8, "Foamposite": 10, "Air Max":
5, "SB Dunk": 4}
def food_total(food1, food2):
total = food1 + food2
return total
print( food_total(foods["chicken"], foods["beef"]))
def food_total(food1, food2):
total = food1 - food2
return total
print( food_total(foods["milk"], foods["cheese"]))
def restock(shoe, num):
shoes[shoe] = shoes[shoe] * num
stock = shoes
return stock
print( restock("Air Max", 4) )
def clearance_sale(shoe, num):
shoes[shoe] = shoes[shoe] / num
stock=shoes
return stock
print( clearance_sale("SB Dunk", 5))
def players_mean(player1, player2, player3, player4, player5, player6):
mean = player1 + player2 + player3 + player4 + player5 + player6 / 6
return mean
print( players_mean("<NAME>", "<NAME>", "<NAME>",
"<NAME>", "<NAME>", "<NAME>") )
|
21a7b1a4b195c776614246e937f67e27c6b5f9f8
|
[
"Markdown",
"Python"
] | 4
|
Python
|
A-m-a-r-e/PAs
|
ea120e26486ad33bdb0ad7cce4b0995648afc8b9
|
d5af590c311363d70842678a4c5390583f3be1ea
|
refs/heads/master
|
<file_sep># Contribute
## Resources
- [Coding Standards](http://learn.bevry.me/community/coding-standards)
- [Documentation Guidelines](http://learn.bevry.me/community/documentation-guidelines)
- [Support Guidelines](http://learn.bevry.me/community/support-guidelines)
## Development
For developers and contributors
1. Fork project and clone your fork
2. Install global dependencies
``` bash
npm install -g coffee-script
```
**Note**: You will need coffee-script for Docpad (v6). This plugin doesn't need it.
3. Install local dependencies
``` bash
npm run our:setup
```
4. Compile project
``` bash
npm run our:compile
```
5. Run tests
``` bash
npm run our:test
```
## Publishing
For project maintainers
1. Update meta files with latest information
``` bash
npm run our:release:prepare
```
2. Add a changelog entry to `HISTORY.md` with change information
```
v2.0.0 April 17, 2013
- Something that changes
```
3. Update `version` entry in `package.json` with new version number
4. Commit changes
``` bash
git commit -a -m "A message about what changed"
```
5. Publish new version
``` bash
npm run our:release
npm publish
```
<file_sep>const path = require('path');
const packJson = require('../package.json');
// Export plugin
module.exports = function (BasePlugin) {
// Define plugin
return class ApiPlugin extends BasePlugin {
constructor (opts) {
super(opts);
this.apis = [];
}
get name () {
return 'api';
}
get initialConfig () {
return {
cfgSrc: []
};
}
docpadReady () {
// Error types
const DPA_CONFIG_ERROR = 'DPAConfigError';
const DPA_SRC_ERROR = 'DPASrcError';
// Get docpad object and rootPath
const docpad = this.docpad;
const rootPath = docpad.getConfig().rootPath;
let configSrc, configJson;
for (configSrc of this.config.cfgSrc) {
try {
// Variables inside try block.
let jsSrc;
const api = {};
// Load config file.
configJson = require(path.join(rootPath, configSrc));
// Check if baseApiUrl is set.
if (!configJson.baseApiUrl) {
const dpaError = new Error('No baseApiUrl set in config file.\n\tIn ' + path.join(rootPath, configSrc));
dpaError.name = DPA_CONFIG_ERROR;
throw dpaError;
}
api.baseApiUrl = configJson.baseApiUrl;
// Check if there's any source set.
if (!configJson.src || configJson.src.length === 0) {
const dpaError = new Error('The src parameter is\'nt properly configured.\n\tIn ' + path.join(rootPath, configSrc));
dpaError.name = DPA_CONFIG_ERROR;
throw dpaError;
}
api.src = [];
for (jsSrc of configJson.src) {
try {
api.src.push(require(path.join(rootPath, jsSrc)));
}
catch (err) {
const dpaError = new Error(err.name + ': ' + err.message + '\n\tIn ' + path.join(rootPath, jsSrc));
dpaError.name = DPA_SRC_ERROR;
throw dpaError;
}
}
// When all configuration is ok, insert in apis array.
this.apis.push(api);
}
catch (err) {
docpad.log('error', 'Api - ' + err.name + ': ' + err.message);
}
}
docpad.log('info', 'Api - Loaded files: ' + this.apis.length);
}
serverExtend (opts) {
// Extract server from options.
const {server} = opts;
const apis = this.apis;
let func, api;
// Default route.
server.get('/engine/version', (req, res) =>
res.json({
name: packJson.name,
dev: packJson.author,
version: packJson.version
})
);
// Go to custom API routes.
for (api of apis) {
for (func of api.src) {
func(opts, api.baseApiUrl);
}
}
}
};
};
<file_sep>'use strict';
// Test our plugin using DocPad's testers
var path = require('path');
require('docpad').require('testers').test({
testerName: 'api plugin common test',
testerClass: 'ServerTester',
pluginPath: path.join(__dirname, '..'),
pluginName: 'api',
autoExit: 'safe'
}, {
plugins: {
api: {
cfgSrc: ['testapi1/dpaconfig.json']
}
}
});<file_sep>'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var path = require('path');
var packJson = require('../package.json');
// Export plugin
module.exports = function (BasePlugin) {
// Define plugin
return function (_BasePlugin) {
_inherits(ApiPlugin, _BasePlugin);
function ApiPlugin(opts) {
_classCallCheck(this, ApiPlugin);
var _this = _possibleConstructorReturn(this, (ApiPlugin.__proto__ || Object.getPrototypeOf(ApiPlugin)).call(this, opts));
_this.apis = [];
return _this;
}
_createClass(ApiPlugin, [{
key: 'docpadReady',
value: function docpadReady() {
// Error types
var DPA_CONFIG_ERROR = 'DPAConfigError';
var DPA_SRC_ERROR = 'DPASrcError';
// Get docpad object and rootPath
var docpad = this.docpad;
var rootPath = docpad.getConfig().rootPath;
var configSrc = void 0,
configJson = void 0;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.config.cfgSrc[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
configSrc = _step.value;
try {
// Variables inside try block.
var jsSrc = void 0;
var api = {};
// Load config file.
configJson = require(path.join(rootPath, configSrc));
// Check if baseApiUrl is set.
if (!configJson.baseApiUrl) {
var dpaError = new Error('No baseApiUrl set in config file.\n\tIn ' + path.join(rootPath, configSrc));
dpaError.name = DPA_CONFIG_ERROR;
throw dpaError;
}
api.baseApiUrl = configJson.baseApiUrl;
// Check if there's any source set.
if (!configJson.src || configJson.src.length === 0) {
var _dpaError = new Error('The src parameter is\'nt properly configured.\n\tIn ' + path.join(rootPath, configSrc));
_dpaError.name = DPA_CONFIG_ERROR;
throw _dpaError;
}
api.src = [];
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = configJson.src[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
jsSrc = _step2.value;
try {
api.src.push(require(path.join(rootPath, jsSrc)));
} catch (err) {
var _dpaError2 = new Error(err.name + ': ' + err.message + '\n\tIn ' + path.join(rootPath, jsSrc));
_dpaError2.name = DPA_SRC_ERROR;
throw _dpaError2;
}
}
// When all configuration is ok, insert in apis array.
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
this.apis.push(api);
} catch (err) {
docpad.log('error', 'Api - ' + err.name + ': ' + err.message);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
docpad.log('info', 'Api - Loaded files: ' + this.apis.length);
}
}, {
key: 'serverExtend',
value: function serverExtend(opts) {
// Extract server from options.
var server = opts.server;
var apis = this.apis;
var func = void 0,
api = void 0;
// Default route.
server.get('/engine/version', function (req, res) {
return res.json({
name: packJson.name,
dev: packJson.author,
version: packJson.version
});
});
// Go to custom API routes.
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = apis[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
api = _step3.value;
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = api.src[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
func = _step4.value;
func(opts, api.baseApiUrl);
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
}
}, {
key: 'name',
get: function get() {
return 'api';
}
}, {
key: 'initialConfig',
get: function get() {
return {
cfgSrc: []
};
}
}]);
return ApiPlugin;
}(BasePlugin);
};<file_sep># Código de conducta para los proyectos de UnivUnix.
## Introducción
En este texto se van a declarar unas "normas", porque parece que se ha perdido el sentido común en los proyectos de software libre y porque el CoC provisto por Github no me gusta (ambiguo, con excesiva burocracia).
TLDR: Si uno no sabe comportarse como una persona dentro de la sociedad, no sé qué pinta aquí.
## Declaraciones
**1. Se evalúa el código, no a la persona:** Nadie nace sabiendo. Todos cometeremos errores a la hora de presentar informes ("Issues") y contribuciones ("Pull request"). Si se cierran dichos informes o contribuciones, serán exclusivamente por motivos técnicos o de desarrollo del proyecto que, naturalmente, se explicarán.
**2. Lo que haga uno fuera de aquí no es de nuestra incumbencia:** Nos da igual lo que digas o pienses por Twitter, por Facebook o por tam-tam. No vamos a juzgarte por ello. Si opinas sobre temas relevantes al proyecto y sin utilizar insultos gratuitos no vamos a tener ningún problema contigo.
**3. UnivUnix no representa las opiniones de sus integrantes, participantes o usuarios.**
## Conclusión.
Los proyectos de UnivUnix no se van a convertir en 1984 Github edition pero tampoco se permitirá ninguna acción o comentario irrelevante al proyecto, donde se pedirá a la persona o personas en cuestión que cesen esas acciones. Si hacen caso omiso y/o se detectan intentos de sabotaje del proyecto, se tomarán las medidas oportunas.
Como dijo <NAME>:
> Yo he venido aquí a hablar de mi libro y no a hablar de lo que opine el personal, que me da lo mismo, porque para eso tengo mi columna y mi opinión diaria.
*Redactado por @Aglezabad el día 20 de Julio de 2017.*
<file_sep># Api Plugin for [DocPad](http://docpad.org)
**~~Due to the closing of Docpad project in 1/2/2018, this plugin won't receive any extra feature. Only critical bugs will be solved.~~ Benjamin said that Docpad will get updates, but he will work as a side-project. We will add features if it's necessary.**
<!-- BADGES/ -->
<span class="badge-travisci"><a href="http://travis-ci.org/UnivUnix/docpad-plugin-api" title="Check this project's build status on TravisCI"><img src="https://img.shields.io/travis/UnivUnix/docpad-plugin-api/master.svg" alt="Travis CI Build Status" /></a></span>
<span class="badge-npmversion"><a href="https://npmjs.org/package/docpad-plugin-api" title="View this project on NPM"><img src="https://img.shields.io/npm/v/docpad-plugin-api.svg" alt="NPM version" /></a></span>
<span class="badge-npmdownloads"><a href="https://npmjs.org/package/docpad-plugin-api" title="View this project on NPM"><img src="https://img.shields.io/npm/dm/docpad-plugin-api.svg" alt="NPM downloads" /></a></span>
<span class="badge-daviddm"><a href="https://david-dm.org/UnivUnix/docpad-plugin-api" title="View the status of this project's dependencies on DavidDM"><img src="https://img.shields.io/david/UnivUnix/docpad-plugin-api.svg" alt="Dependency Status" /></a></span>
<span class="badge-daviddmdev"><a href="https://david-dm.org/UnivUnix/docpad-plugin-api#info=devDependencies" title="View the status of this project's development dependencies on DavidDM"><img src="https://img.shields.io/david/dev/UnivUnix/docpad-plugin-api.svg" alt="Dev Dependency Status" /></a></span>
<!-- /BADGES -->
## How to use the plugin
First, create your API. You have to use Javascript as language
and you can use NodeJS or ExpressJS methods and objects.
Each Javascript file must have this structure:
```javascript
// Each module.exports MUST BE a function with these two arguments
module.exports = function (opts, baseApiUrl){
// The ExpressJS server is an attribute of opts.
var server = opts.server
// You can use ExpressJS functions (version 3.x)
server.get(baseApiUrl + '/test', function (req, res, next) {
return res.json({
test: 'OK'
})
})
server.get('/bbbb', function (req, res, next) {
var err = new Error()
next(err)
})
}
```
Second, you need to create the api configuration file. It's in JSON format.
This is the new step for newer versions, because you can set different apis using multiple configuration files.
You can name it as you want. In my case, I call it "dpaconfig.json"
```javascript
{
"baseApiUrl": "/testone",
"src": [
"testapi1/src/test11.js",
"testapi1/src/test12.js"
]
}
```
Notes about dbaconfig.json file:
* It's required to set the baseApiUrl and src variables.
* The src routes have to be relative to Docpad website root folder (the same level as docpad configuration file).
Finally, set the route of each dpaconfig file in Docpad configuration file.
```coffee-script
plugins:
api:
cfgSrc: [
'testapi1/dpaconfig.json',
'testapi2/dpaconfig.json',
'testapi0/dpaconfig.json'
]
```
Notes about configuration:
*You have to set relative routes using Docpad root folder as base.
And we're done. Enjoy your custom api without refactoring to ExpressJS.
<!-- INSTALL/ -->
<h2>Install</h2>
Install this DocPad plugin by entering <code>docpad install api</code> into your terminal.
<!-- /INSTALL -->
<!-- HISTORY/ -->
<h2>History</h2>
<a href="https://github.com/UnivUnix/docpad-plugin-api/blob/master/HISTORY.md#files">Discover the release history by heading on over to the <code>HISTORY.md</code> file.</a>
<!-- /HISTORY -->
<!-- CONTRIBUTE/ -->
<h2>Contribute</h2>
<a href="https://github.com/UnivUnix/docpad-plugin-api/blob/master/CONTRIBUTING.md#files">Discover how you can contribute by heading on over to the <code>CONTRIBUTING.md</code> file.</a>
<!-- /CONTRIBUTE -->
<!-- BACKERS/ -->
<h2>Backers</h2>
<h3>Maintainers</h3>
These amazing people are maintaining this project:
<ul><li><a href="http://univunix.com"><NAME></a></li></ul>
<h3>Sponsors</h3>
No sponsors yet! Will you be the first?
<h3>Contributors</h3>
These amazing people have contributed code to this project:
<ul><li><a href="http://univunix.com"><NAME></a> — <a href="https://github.com/UnivUnix/docpad-plugin-api/commits?author=Aglezabad" title="View the GitHub contributions of Ángel González on repository UnivUnix/docpad-plugin-api">view contributions</a></li>
<li><a href="http://balupton.com"><NAME></a> — <a href="https://github.com/UnivUnix/docpad-plugin-api/commits?author=balupton" title="View the GitHub contributions of <NAME>upton on repository UnivUnix/docpad-plugin-api">view contributions</a></li>
<li><a href="http://mdm.cc"><NAME></a> — <a href="https://github.com/UnivUnix/docpad-plugin-api/commits?author=mikeumus" title="View the GitHub contributions of <NAME> on repository UnivUnix/docpad-plugin-api">view contributions</a></li>
<li><a href="http://robloach.net"><NAME></a> — <a href="https://github.com/UnivUnix/docpad-plugin-api/commits?author=RobLoach" title="View the GitHub contributions of <NAME> on repository UnivUnix/docpad-plugin-api">view contributions</a></li>
<li><a href="https://github.com/vsopvsop">vsopvsop</a> — <a href="https://github.com/UnivUnix/docpad-plugin-api/commits?author=vsopvsop" title="View the GitHub contributions of vsopvsop on repository UnivUnix/docpad-plugin-api">view contributions</a></li>
<li><a href="http://www.procesozombie.com/">fer2d2</a> — <a href="https://github.com/UnivUnix/docpad-plugin-api/commits?author=fer2d2" title="View the GitHub contributions of fer2d2 on repository UnivUnix/docpad-plugin-api">view contributions</a></li></ul>
<a href="https://github.com/UnivUnix/docpad-plugin-api/blob/master/CONTRIBUTING.md#files">Discover how you can contribute by heading on over to the <code>CONTRIBUTING.md</code> file.</a>
<!-- /BACKERS -->
<!-- LICENSE/ -->
<h2>License</h2>
Unless stated otherwise all works are:
<ul><li>Copyright © <a href="http://univunix.com">UnivUnix</a></li></ul>
and licensed under:
<ul><li><a href="http://spdx.org/licenses/MIT.html">MIT License</a></li></ul>
<!-- /LICENSE -->
<file_sep>## History
## v2.3.0 2017 August 2
- Moving api files loading system to docpadReady event. Alpha version.
## v2.2.2 2017 May 4
- Version marked as stable.
## v2.2.1 2017 April 15
- New api loading system. You can use multiple isolated apis. (Sorry for breaking changes)
- Added new version due to errors in npm registry.
## v2.2.0 2017 April 3
- Conversion from Coffeescript to ES6 (ES5 included through Babel)
## v2.1.5 2017 March 6
- Load multiple API Javascript files and configurable API base URL
## v2.0.1 2017 February 28
- We can load our custom API file written as NodeJS module (in Javascript using ExpressJS functions)
## v2.0.0 2017 February 27
- First version (experimental, not stable)
|
15d780a5e92ed1763ed3e0f1477e7ec54239aaef
|
[
"Markdown",
"JavaScript"
] | 7
|
Markdown
|
UnivUnix/docpad-plugin-api
|
955b42699292993e2c045aa425742cdb0e222e03
|
d1e765e0d425d3567f4638eb0bc543eab6ed820f
|
refs/heads/main
|
<file_sep>package com.example
import arrow.core.Either
import arrow.core.Left
import arrow.core.Right
import io.ktor.application.Application
import io.ktor.application.call
import io.ktor.http.HttpStatusCode
import io.ktor.response.respond
import io.ktor.response.respondText
import io.ktor.routing.get
import io.ktor.routing.routing
import java.util.concurrent.ConcurrentHashMap
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
/**
* A sort of data store kind of thing.
* */
object DataStore {
private val map: MutableMap<String, String> = ConcurrentHashMap()
fun put(key: String, value: String) {
map[key] = value
}
fun get(key: String): String? {
return map[key]
}
}
@Suppress("unused") // Referenced in application.conf
fun Application.module() {
// Bootstrap the datastore with some well known values.
repeat(10) { i -> DataStore.put("key-$i", "value-$i") }
routing {
// F for functional handling
get("/f/store/{key}") {
val key = call.parameters["key"] ?: ""
when (val result = functionalHandler(key)) {
is Either.Left -> call.respond(HttpStatusCode.NotFound)
is Either.Right -> call.respondText(result.b)
}
}
// E for regular exception handling
get("/e/store/{key}") {
try {
val key = call.parameters["key"] ?: ""
val result = DataStore.get(key)
requireNotNull(result)
call.respondText(result)
} catch (ex: Exception) {
call.respond(HttpStatusCode.NotFound)
}
}
}
}
data class SimpleError(val msg: String)
private fun functionalHandler(key: String): Either<SimpleError, String> {
val result = DataStore.get(key)
return if (result != null) {
Right(result)
} else {
Left(SimpleError("Key $key does not exist."))
}
}
<file_sep># cost-of-exceptions
A practical example to assert the cost of exception handling in a web application
<file_sep>rootProject.name = "exception-cost"
<file_sep>val logback_version: String by project
val ktor_version: String by project
val kotlin_version: String by project
plugins {
application
kotlin("jvm") version "1.4.21"
id("org.jetbrains.kotlin.kapt") version "1.4.21"
id("org.jlleitschuh.gradle.ktlint") version "9.4.1"
}
group = "com.example"
version = "0.0.1-SNAPSHOT"
application {
mainClassName = "io.ktor.server.netty.EngineMain"
}
repositories {
mavenLocal()
jcenter()
maven { url = uri("https://kotlin.bintray.com/ktor") }
}
val arrow_version = "0.11.0"
dependencies {
implementation("io.arrow-kt:arrow-core:$arrow_version")
implementation("io.arrow-kt:arrow-syntax:$arrow_version")
kapt("io.arrow-kt:arrow-meta:$arrow_version")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version")
implementation("io.ktor:ktor-server-netty:$ktor_version")
implementation("ch.qos.logback:logback-classic:$logback_version")
implementation("io.ktor:ktor-server-core:$ktor_version")
testImplementation("io.ktor:ktor-server-tests:$ktor_version")
}
kotlin.sourceSets["main"].kotlin.srcDirs("src")
kotlin.sourceSets["test"].kotlin.srcDirs("test")
sourceSets["main"].resources.srcDirs("resources")
sourceSets["test"].resources.srcDirs("testresources")
|
47dca356435f5b7da7c3326af75e27be7b6ff69f
|
[
"Markdown",
"Kotlin"
] | 4
|
Kotlin
|
felix19350/cost-of-exceptions
|
7c162804ca415a82e58bf2173d37bd0f4320628a
|
83305fb54fda948549c419295a769a96d3b5b793
|
refs/heads/master
|
<file_sep>package db
import "context"
type DB interface {
DeleteOne(ctx context.Context, collection string, filter map[string]interface{}) (int64, error)
Delete(ctx context.Context, collection string, filter map[string]interface{}) (deleteCount int64, err error)
SelectOne(ctx context.Context, collection string, filter, projection map[string]interface{}, out interface{}) (err error)
Select(ctx context.Context, collection string, filter, projection map[string]interface{}, results interface{}) (err error)
InsertOne(ctx context.Context, collection string, item map[string]interface{}) (err error)
UpdateOne(ctx context.Context, collection string, where map[string]interface{}, item map[string]interface{}) error
}
<file_sep>package def
import (
"context"
"github.com/amine-khemissi/skeleton/def/delete"
"github.com/amine-khemissi/skeleton/def/read"
"github.com/amine-khemissi/skeleton/def/update"
"github.com/amine-khemissi/skeleton/def/write"
)
type Service interface {
Write(ctx context.Context, req write.Request) (write.Response, error)
Update(ctx context.Context, req update.Request) (update.Response, error)
Read(ctx context.Context, req read.Request) (read.Response, error)
Delete(ctx context.Context, request delete.Request) (delete.Response, error)
}
<file_sep>package transportwrite
import (
"context"
"net/http"
"github.com/amine-khemissi/skeleton/def/write"
"github.com/amine-khemissi/skeleton/backbone/endpointimpl"
"github.com/amine-khemissi/skeleton/def"
"github.com/go-kit/kit/endpoint"
)
type ep struct {
}
func (e ep) GetRequest() interface{} {
return &write.Request{}
}
func NewEndpoint() endpointimpl.EndpointImpl {
return &ep{}
}
func (e ep) MakeEndpoint(svc interface{}) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(*write.Request)
return svc.(def.Service).Write(ctx, *req)
}
}
func (e ep) GetVerb() string {
return http.MethodPost
}
func (e ep) GetPath() string {
return "/person"
}
<file_sep>package doc
import (
"reflect"
"github.com/amine-khemissi/skeleton/backbone/endpointimpl"
)
var gGenerator Generator
type Generator interface {
Register(impl endpointimpl.EndpointImpl)
NewEndpoint() endpointimpl.EndpointImpl
}
type generator struct {
doc map[string]map[string]interface{}
}
func (g *generator) Register(impl endpointimpl.EndpointImpl) {
g.doc[impl.GetPath()][impl.GetVerb()] = ""
for i := 0; i < reflect.TypeOf(impl.GetRequest()).Elem().NumField(); i++ {
fld := reflect.TypeOf(impl.GetRequest()).Elem().Field(i)
//todo : remove _ and replace it by elt
_, found := fld.Tag.Lookup("json")
if !found {
continue
}
// todo : create requestBody object and populate it
}
// todo: populate the responses associated
}
func (g *generator) NewEndpoint() endpointimpl.EndpointImpl {
return g
}
func NewGenerator() Generator {
if gGenerator == nil {
gGenerator = &generator{
doc: map[string]map[string]interface{}{},
}
}
return gGenerator
}
<file_sep>FROM alpine:3.12.1
CMD mkdir /app
COPY bin/svc /app/svc
RUN ls -la /app/
ENTRYPOINT ["/app/svc","-config-file","/app/config.json"]<file_sep>package endpointimpl
import (
"github.com/go-kit/kit/endpoint"
)
type EndpointImpl interface {
MakeEndpoint(svc interface{}) endpoint.Endpoint
GetVerb() string
GetPath() string
GetRequest() interface{}
}
<file_sep>package mongo
import (
"context"
"net/http"
"github.com/amine-khemissi/skeleton/backbone/config"
"github.com/amine-khemissi/skeleton/backbone/db"
"github.com/amine-khemissi/skeleton/backbone/errorsklt"
"github.com/amine-khemissi/skeleton/backbone/logger"
"github.com/mitchellh/mapstructure"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type mongoConf struct {
URI string `json:"URI"`
DatabaseName string `json:"databaseName"`
}
func New(ctx context.Context) db.DB {
tmp, isMSI := config.Instance().Get("database", "mongo").(map[string]interface{})
if !isMSI {
logger.Instance().Fatal(ctx, "failed to parse mongo conf, reason: expected json object")
}
logger.Instance().Debug(ctx, "extracted mongo conf", tmp)
var conf mongoConf
if err := mapstructure.Decode(tmp, &conf); err != nil {
logger.Instance().Fatal(ctx, "failed to parse mongo conf, reason:", err.Error())
}
// Set client options
clientOptions := options.Client().ApplyURI(conf.URI)
// Connect to MongoDB
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
logger.Instance().Fatal(ctx, "failed to ping mongo db", conf.URI)
}
// Check the connection
if err = client.Ping(ctx, nil); err != nil {
logger.Instance().Fatal(ctx, err)
}
logger.Instance().Info(ctx, "Connected to mongo:", conf.URI, ",database:", conf.DatabaseName)
return &wrapper{
db: client.Database(conf.DatabaseName),
}
}
type wrapper struct {
db *mongo.Database
}
func (w *wrapper) SelectOne(ctx context.Context, collection string, filter, projection map[string]interface{}, out interface{}) (err error) {
opt := options.FindOne()
opt.Projection = projection
result := w.db.Collection(collection).FindOne(ctx, filter, opt)
if result.Err() != nil {
return errorsklt.WithCode(errorsklt.Stack(result.Err(), "failed to select one result", filter, "in collection", collection), http.StatusInternalServerError)
}
if err := result.Decode(out); err != nil {
return errorsklt.WithCode(errorsklt.Stack(err, "failed to decode one result with filter", filter, "in collection", collection), http.StatusInternalServerError)
}
return nil
}
func (w *wrapper) Select(ctx context.Context, collection string, filter, projection map[string]interface{}, results interface{}) (err error) {
opt := options.Find()
opt.Projection = projection
cursor, err := w.db.Collection(collection).Find(ctx, filter, opt)
if err != nil {
return errorsklt.WithCode(errorsklt.Stack(err, "failed to select", filter, "in collection", collection), http.StatusInternalServerError)
}
if err := cursor.All(ctx, results); err != nil {
return errorsklt.WithCode(errorsklt.Stack(err, "failed to parse cursor for filter", filter, "in collection", collection), http.StatusInternalServerError)
}
return nil
}
func (w *wrapper) Delete(ctx context.Context, collection string, filter map[string]interface{}) (int64, error) {
deleteResult, err := w.db.Collection(collection).DeleteMany(ctx, filter)
if err != nil {
return 0, errorsklt.WithCode(errorsklt.Stack(err, "failed to delete with filter", filter, "in collection", collection), http.StatusInternalServerError)
}
return deleteResult.DeletedCount, nil
}
func (w *wrapper) DeleteOne(ctx context.Context, collection string, filter map[string]interface{}) (int64, error) {
deleteResult, err := w.db.Collection(collection).DeleteOne(ctx, filter)
if err != nil {
return 0, errorsklt.WithCode(errorsklt.Stack(err, "failed to delete one with filter", filter, "in collection", collection), http.StatusInternalServerError)
}
return deleteResult.DeletedCount, nil
}
func (w *wrapper) InsertOne(ctx context.Context, collection string, item map[string]interface{}) error {
//todo check how can I use the insertResult
_, err := w.db.Collection(collection).InsertOne(ctx, item)
if err != nil {
return errorsklt.WithCode(errorsklt.Stack(err, "failed to insert one element in collection", collection), http.StatusInternalServerError)
}
return nil
}
func (w *wrapper) UpdateOne(ctx context.Context, collection string, where map[string]interface{}, item map[string]interface{}) error {
logger.Instance().Debug(ctx, collection, where, map[string]interface{}{"$set": item})
_, err := w.db.Collection(collection).UpdateOne(ctx, where, map[string]interface{}{"$set": item})
if err != nil {
return errorsklt.WithCode(errorsklt.Stack(err, "failed to update one element in collection", collection), http.StatusInternalServerError)
}
return nil
}
<file_sep>## Goal
The goal of the repository is to ease the development of micro services in golang with a code base already setup in order to focus on application level
## Important:
This is an alpha version, it contains several shortcuts in order to accelerate the devlopment, but clearly it is not production ready
<file_sep>package header
import (
"context"
"sync"
)
type headersType int
const (
headersKey headersType = iota
)
type headers struct {
locker *sync.Mutex
values map[string]string
}
func (h *headers) Add(k string, v string) {
h.locker.Lock()
defer h.locker.Unlock()
h.values[k] = v
}
func newHeaders() *headers {
return &headers{
locker: &sync.Mutex{},
values: map[string]string{},
}
}
func Add(ctx context.Context, k string, v string) context.Context {
h, isHeaders := ctx.Value(headersKey).(*headers)
if h == nil || !isHeaders {
h = newHeaders()
}
h.Add(k, v)
return context.WithValue(ctx, headersKey, h)
}
func Get(ctx context.Context, k string) string {
h, isHeaders := ctx.Value(headersKey).(*headers)
if h == nil || !isHeaders {
h = newHeaders()
}
return h.values[k]
}
func GetAll(ctx context.Context) map[string]string {
h, isHeaders := ctx.Value(headersKey).(*headers)
if h == nil || !isHeaders {
h = newHeaders()
}
return h.values
}
<file_sep>package transport
import (
"bytes"
"fmt"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/gorilla/mux"
"github.com/stretchr/testify/require"
)
type w struct {
}
func (w w) Header() http.Header {
return map[string][]string{}
}
func (w w) Write(out []byte) (int, error) {
fmt.Println(string(out))
return 0, nil
}
func (w w) WriteHeader(statusCode int) {
fmt.Println("statusCode", statusCode)
}
type h struct {
t *testing.T
}
func (h *h) ServeHTTP(w http.ResponseWriter, r *http.Request) {
t := h.t
type TestStruct struct {
Id uint64 `json:"-" path:"id"`
Male bool `json:"-" qs:"male"`
Age int `json:"age"`
Name string `json:"name"`
Session string `json:"-" header:"session-id"`
}
decodedReq, err := decodeRequest(&TestStruct{}, r)
assert.NoError(t, err)
tStruct := decodedReq.(*TestStruct)
assert.Equal(t, "john", tStruct.Name)
assert.Equal(t, 18, tStruct.Age)
assert.Equal(t, true, tStruct.Male)
assert.Equal(t, "123456789", tStruct.Session)
assert.Equal(t, uint64(42), tStruct.Id)
}
func TestDecodeRequest(t *testing.T) {
b := bytes.NewBufferString(`{"name":"john","age":18}`)
router := mux.NewRouter()
router.Methods(http.MethodGet).Path("/persons/{id}").Headers("session-id", "").Handler(&h{t})
r, err := http.NewRequest(http.MethodGet, "http://what.com/persons/42?male=true", b)
require.NoError(t, err)
r.Header.Add("session-id", "123456789")
router.ServeHTTP(&w{}, r)
}
<file_sep>package doc
import (
"context"
"net/http"
"github.com/go-kit/kit/endpoint"
)
func (g *generator) GetRequest() interface{} {
return &struct {
}{}
}
func (g *generator) MakeEndpoint(svc interface{}) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
return g.doc, nil
}
}
func (g *generator) GetVerb() string {
return http.MethodGet
}
func (g *generator) GetPath() string {
return "/_internal/doc"
}
<file_sep>package transportdelete
import (
"context"
"net/http"
"github.com/amine-khemissi/skeleton/backbone/endpointimpl"
"github.com/amine-khemissi/skeleton/def"
"github.com/amine-khemissi/skeleton/def/delete"
"github.com/go-kit/kit/endpoint"
)
type ep struct {
}
func (e ep) GetRequest() interface{} {
return &delete.Request{}
}
func NewEndpoint() endpointimpl.EndpointImpl {
return &ep{}
}
func (e ep) MakeEndpoint(svc interface{}) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(*delete.Request)
return svc.(def.Service).Delete(ctx, *req)
}
}
func (e ep) GetVerb() string {
return http.MethodDelete
}
func (e ep) GetPath() string {
return "/person/{clientID}"
}
<file_sep>package read
import (
"context"
"github.com/amine-khemissi/skeleton/backbone/db"
"github.com/amine-khemissi/skeleton/backbone/errorsklt"
"github.com/amine-khemissi/skeleton/backbone/logger"
"github.com/amine-khemissi/skeleton/def/delete"
)
func Delete(ctx context.Context, instance db.DB, req delete.Request) (delete.Response, error) {
logger.Instance().Debug(ctx, "delete ", req.ClientID)
item := map[string]interface{}{
"ID": req.ClientID,
}
var resp delete.Response
nbDeleted, err := instance.DeleteOne(ctx, "people", item)
if err != nil {
return delete.Response{}, errorsklt.Stack(err, "failed to delete person", req.ClientID)
}
logger.Instance().Debug(ctx, "deleted ", nbDeleted, "items")
return resp, nil
}
<file_sep>package delete
type Request struct {
ClientID string `json:"-" path:"clientID"`
}
type Response struct {
}
<file_sep>build:
@CGO_ENABLED=0 go build -o bin/svc main/main.go
up: build
@docker-compose up --remove-orphans --build web
stop:
@docker-compose stop
<file_sep>module github.com/amine-khemissi/skeleton
go 1.14
require (
github.com/go-kit/kit v0.10.0
github.com/google/uuid v1.0.0
github.com/gorilla/mux v1.7.3
github.com/mitchellh/mapstructure v1.1.2
github.com/stretchr/testify v1.6.1
go.mongodb.org/mongo-driver v1.4.2
)
<file_sep>package config
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"sync"
"time"
)
type Config interface {
Get(moduleName, keyName string) interface{}
isExpired() bool
}
func init() {
configFile = flag.String("config-file", "config.json", "path to config file")
go reloadConf(&locker)
}
var configFile *string
var gConf Config
var locker sync.Mutex
type config struct {
Content map[string]map[string]interface{} `json:","`
lastUpdate time.Time
l *sync.Mutex
}
func (c *config) Get(moduleName, keyName string) interface{} {
c.l.Lock()
defer c.l.Unlock()
keys, moduleExist := c.Content[moduleName]
if !moduleExist {
panic(fmt.Sprintln("module", moduleName, "not found"))
}
val, keyExist := keys[keyName]
if !keyExist {
panic(fmt.Sprintln(moduleName, "::", keyName, "not found"))
}
return val
}
func Instance() Config {
locker.Lock()
defer locker.Unlock()
if gConf == nil {
gConf = loadConf(&locker)
}
return gConf
}
func (c config) isExpired() bool {
fi, err := os.Stat(*configFile)
if err != nil {
panic(err)
}
if c.lastUpdate.After(fi.ModTime()) {
return false
}
return true
}
func loadConf(l *sync.Mutex) Config {
fmt.Println("need to reload conf")
tmp := &config{
l: l,
}
bts, err := ioutil.ReadFile(*configFile)
if err != nil {
panic(err)
}
if errUnmarshall := json.Unmarshal(bts, &tmp.Content); errUnmarshall != nil {
panic(errUnmarshall)
}
tmp.lastUpdate = time.Now()
fmt.Println("conf reloaded")
return tmp
}
func reloadConf(l *sync.Mutex) {
for {
time.Sleep(3 * time.Second)
if gConf != nil && !gConf.isExpired() {
continue
}
l.Lock()
gConf = loadConf(l)
l.Unlock()
}
}
<file_sep>package errorsklt
import (
"encoding/json"
"fmt"
"net/http"
)
type InternalErr struct {
Stack []string `json:"reasons"`
Code int `json:"code"`
}
func (err *InternalErr) Error() string {
bts, _ := json.Marshal(err)
return string(bts)
}
func New(code int, args ...interface{}) error {
return &InternalErr{
Code: code,
Stack: []string{fmt.Sprint(args)},
}
}
func Stack(err error, args ...interface{}) error {
typedErr, ok := err.(*InternalErr)
if ok {
typedErr.Stack = append(typedErr.Stack, fmt.Sprint(args))
return typedErr
}
return &InternalErr{
Code: http.StatusInternalServerError,
Stack: []string{err.Error(), fmt.Sprint(args)},
}
}
func WithCode(err error, code int) error {
typedErr, ok := err.(*InternalErr)
if ok {
typedErr.Code = code
return typedErr
}
return &InternalErr{
Code: code,
Stack: []string{err.Error()},
}
}
<file_sep>package transport
import (
"context"
"encoding/json"
"net/http"
"reflect"
"strconv"
"github.com/amine-khemissi/skeleton/backbone/errorsklt"
"github.com/gorilla/mux"
)
func DecodeRequest(request interface{}) func(ctx context.Context, r *http.Request) (interface{}, error) {
return func(ctx context.Context, r *http.Request) (interface{}, error) {
return decodeRequest(request, r)
}
}
func decodeRequest(request interface{}, r *http.Request) (interface{}, error) {
var err error
if err := json.NewDecoder(r.Body).Decode(&request); err != nil && err.Error() != "EOF" {
return nil, err
}
request, err = decodePath(request, r)
if err != nil {
return nil, errorsklt.Stack(err, "failed to decode path")
}
request, err = decodeQueryString(request, r)
if err != nil {
return nil, errorsklt.Stack(err, "failed to decode query string")
}
request, err = decodeHeader(request, r)
if err != nil {
return nil, errorsklt.Stack(err, "failed to decode header")
}
return request, nil
}
func decodePath(request interface{}, r *http.Request) (interface{}, error) {
for i := 0; i < reflect.TypeOf(request).Elem().NumField(); i++ {
fld := reflect.TypeOf(request).Elem().Field(i)
elt, found := fld.Tag.Lookup("path")
if !found {
continue
}
vars := mux.Vars(r)
if err := decodeScalar(fld.Type.Kind(), vars[elt], reflect.ValueOf(request).Elem().Field(i).Addr()); err != nil {
return nil, errorsklt.Stack(err, "failed to decode scalar", vars[elt])
}
}
return request, nil
}
func decodeQueryString(request interface{}, r *http.Request) (interface{}, error) {
for i := 0; i < reflect.TypeOf(request).Elem().NumField(); i++ {
fld := reflect.TypeOf(request).Elem().Field(i)
elt, found := fld.Tag.Lookup("qs")
if !found {
continue
}
qs := r.URL.Query().Get(elt)
if err := decodeScalar(fld.Type.Kind(), qs, reflect.ValueOf(request).Elem().Field(i)); err != nil {
return nil, errorsklt.Stack(err, "failed to decode scalar", qs)
}
}
return request, nil
}
func decodeHeader(request interface{}, r *http.Request) (interface{}, error) {
for i := 0; i < reflect.TypeOf(request).Elem().NumField(); i++ {
fld := reflect.TypeOf(request).Elem().Field(i)
tag, found := fld.Tag.Lookup("header")
if !found {
continue
}
if err := decodeScalar(fld.Type.Kind(), r.Header.Get(tag), reflect.ValueOf(request).Elem().Field(i)); err != nil {
return nil, errorsklt.Stack(err, "failed to decode scalar", tag)
}
}
return request, nil
}
func decodeScalar(kind reflect.Kind, input string, v reflect.Value) error {
v = reflect.Indirect(v)
switch kind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i, err := strconv.ParseInt(input, 10, 64)
if err != nil {
return errorsklt.New(http.StatusBadRequest, "failed to parse int64", err.Error())
}
v.SetInt(i)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
i, err := strconv.ParseUint(input, 10, 64)
if err != nil {
return errorsklt.New(http.StatusBadRequest, "failed to parse int64", err.Error())
}
v.SetUint(i)
case reflect.String:
v.SetString(input)
case reflect.Bool:
b, err := strconv.ParseBool(input)
if err != nil {
return errorsklt.New(http.StatusBadRequest, "failed to parse bool", err.Error())
}
v.SetBool(b)
case reflect.Float32, reflect.Float64:
f, err := strconv.ParseFloat(input, 64)
if err != nil {
return errorsklt.New(http.StatusBadRequest, "failed to parse float64", err.Error())
}
v.SetFloat(f)
default:
return errorsklt.New(http.StatusBadRequest, "unsupported type", kind.String())
}
return nil
}
<file_sep>package read
import (
"context"
"github.com/amine-khemissi/skeleton/backbone/db"
"github.com/amine-khemissi/skeleton/backbone/errorsklt"
"github.com/amine-khemissi/skeleton/backbone/logger"
"github.com/amine-khemissi/skeleton/def/read"
)
func Read(ctx context.Context, instance db.DB, req read.Request) (read.Response, error) {
logger.Instance().Debug(ctx, "read ", req.ClientID)
item := map[string]interface{}{
"ID": req.ClientID,
}
var resp read.Response
if err := instance.SelectOne(ctx, "people", item, map[string]interface{}{
"name": true,
"age": true,
}, &resp); err != nil {
return read.Response{}, errorsklt.Stack(err, "failed to select person", req.ClientID)
}
return resp, nil
}
<file_sep>package update
import (
"context"
"github.com/amine-khemissi/skeleton/backbone/db"
"github.com/amine-khemissi/skeleton/backbone/errorsklt"
"github.com/amine-khemissi/skeleton/backbone/logger"
"github.com/amine-khemissi/skeleton/def/update"
)
func Update(ctx context.Context, instance db.DB, req update.Request) (update.Response, error) {
logger.Instance().Debug(ctx, "Update", req.Name, req.Age)
where := map[string]interface{}{
"ID": req.ClientID,
}
item := map[string]interface{}{}
if req.Age != 0 {
item["age"] = req.Age
}
if req.Name != "" {
item["name"] = req.Name
}
if err := instance.UpdateOne(ctx, "people", where, item); err != nil {
return update.Response{}, errorsklt.Stack(err, "failed to update person", req.ClientID)
}
return update.Response{}, nil
}
<file_sep>package server
import (
"flag"
"log"
"net/http"
"github.com/amine-khemissi/skeleton/backbone/config"
"github.com/amine-khemissi/skeleton/backbone/endpointimpl"
"github.com/amine-khemissi/skeleton/backbone/transport"
httptransport "github.com/go-kit/kit/transport/http"
"github.com/gorilla/mux"
)
type Server interface {
Run()
Register(impl endpointimpl.EndpointImpl)
}
func init() {
flag.Parse()
}
func New(svc interface{}) Server {
s := &srv{
r: mux.NewRouter(),
svc: svc,
}
http.Handle("/", s.r)
s.Register(config.NewEndpoint())
return s
}
type srv struct {
r *mux.Router
svc interface{}
}
func (s *srv) Register(impl endpointimpl.EndpointImpl) {
implHandler := httptransport.NewServer(
impl.MakeEndpoint(s.svc),
transport.DecodeRequest(impl.GetRequest()),
genericEncoder,
httptransport.ServerErrorEncoder(genericErrorEncoder),
httptransport.ServerBefore(addContextID),
)
s.r.Methods(impl.GetVerb()).Path(impl.GetPath()).Handler(implHandler)
}
func (s *srv) Run() {
log.Fatal(http.ListenAndServe(":8080", nil))
}
<file_sep>package logger
import (
"context"
"fmt"
"io"
"os"
"sync"
"time"
"github.com/amine-khemissi/skeleton/backbone/header"
"github.com/amine-khemissi/skeleton/backbone/config"
)
func init() {
go reloadLogger(&lock)
}
var gLogger Logger
var lock = sync.Mutex{}
type Logger interface {
Debug(ctx context.Context, args ...interface{})
Info(ctx context.Context, args ...interface{})
Warn(ctx context.Context, args ...interface{})
Error(ctx context.Context, args ...interface{})
Fatal(ctx context.Context, args ...interface{})
init()
}
type Level int
const (
Debug Level = iota
Info
Warning
Error
Fatal
)
var str2Level = map[string]Level{
"debug": Debug,
"info": Info,
"warning": Warning,
"error": Error,
"fatal": Fatal,
}
func (l Level) ToString() string {
for k, v := range str2Level {
if v == l {
return k
}
}
return ""
}
const (
moduleName = "logger"
levelKey = "level"
destinationKey = "destination"
)
type logger struct {
min Level
dstName string
dst io.Writer
release func()
l *sync.Mutex
}
func (l *logger) Debug(ctx context.Context, args ...interface{}) {
l.log(ctx, Debug, args)
}
func (l *logger) Info(ctx context.Context, args ...interface{}) {
l.log(ctx, Info, args)
}
func (l *logger) Warn(ctx context.Context, args ...interface{}) {
l.log(ctx, Warning, args)
}
func (l *logger) Error(ctx context.Context, args ...interface{}) {
l.log(ctx, Error, args)
}
func (l *logger) Fatal(ctx context.Context, args ...interface{}) {
l.log(ctx, Fatal, args)
}
func (l *logger) log(ctx context.Context, level Level, args []interface{}) {
lock.Lock()
defer lock.Unlock()
if l.min > level {
return
}
content := fmt.Sprint("[", header.Get(ctx, header.ContextID), "]", "[", time.Now().UTC(), "][", level.ToString(), "]") + fmt.Sprintln(args...)
l.dst.Write([]byte(content))
if level == Fatal {
panic(content)
}
}
func Instance() Logger {
lock.Lock()
defer lock.Unlock()
if gLogger == nil {
gLogger = loadLogger(&lock)
gLogger.init()
}
return gLogger
}
func loadLogger(l *sync.Mutex) *logger {
logLevelStr, isString := config.Instance().Get(moduleName, levelKey).(string)
if !isString {
panic(fmt.Sprintln("expected", moduleName, "::", levelKey, "to be a string"))
}
logLevel, isLevel := str2Level[logLevelStr]
if !isLevel {
panic(fmt.Sprintln("unknown", moduleName, "::", levelKey, "value:", logLevelStr))
}
logDst, isString := config.Instance().Get(moduleName, destinationKey).(string)
if !isString {
panic(fmt.Sprintln("expected", moduleName, "::", destinationKey, "to be a string"))
}
tmpLogger := &logger{
min: logLevel,
dstName: logDst,
l: l,
}
return tmpLogger
}
func (l *logger) init() {
f, err := os.OpenFile(l.dstName,
os.O_APPEND|os.O_CREATE|os.O_WRONLY,
0644)
if err != nil {
panic(err)
}
l.dst = f
l.release = func() {
f.Close()
}
}
func reloadLogger(l *sync.Mutex) {
for {
time.Sleep(3 * time.Second)
tmpLogger := loadLogger(l)
if gLogger != nil &&
gLogger.(*logger).dstName == tmpLogger.dstName &&
gLogger.(*logger).min == tmpLogger.min {
continue
}
tmpLogger.init()
lock.Lock()
gLogger.(*logger).release()
gLogger = tmpLogger
lock.Unlock()
}
}
<file_sep>package update
type Request struct {
ClientID string `json:"-" path:"clientID"`
Name string `json:"name"`
Age int `json:"age"`
}
type Response struct {
}
<file_sep>package main
import (
"context"
transportupdate "github.com/amine-khemissi/skeleton/endpoints/update/transport"
transportdelete "github.com/amine-khemissi/skeleton/endpoints/delete/transport"
transportread "github.com/amine-khemissi/skeleton/endpoints/read/transport"
"github.com/amine-khemissi/skeleton/backbone/logger"
"github.com/amine-khemissi/skeleton/backbone/server"
"github.com/amine-khemissi/skeleton/endpoints"
transportwrite "github.com/amine-khemissi/skeleton/endpoints/write/transport"
)
/* todo :
- check other todos
- add middleware chaining
- add doc generation
- db driver : check other methods are working
- err response encoder to be implemented
- add ContentType int the response and the request and change marshalling process accordingly
*/
func main() {
ctx := context.Background()
logger.Instance().Debug(ctx, "starting service")
srv := server.New(endpoints.New(ctx))
srv.Register(transportwrite.NewEndpoint())
srv.Register(transportread.NewEndpoint())
srv.Register(transportdelete.NewEndpoint())
srv.Register(transportupdate.NewEndpoint())
srv.Run()
}
<file_sep>package endpoints
import (
"context"
"github.com/amine-khemissi/skeleton/backbone/db"
"github.com/amine-khemissi/skeleton/backbone/db/mongo"
"github.com/amine-khemissi/skeleton/def"
"github.com/amine-khemissi/skeleton/def/delete"
"github.com/amine-khemissi/skeleton/def/read"
"github.com/amine-khemissi/skeleton/def/update"
"github.com/amine-khemissi/skeleton/def/write"
delete2 "github.com/amine-khemissi/skeleton/endpoints/delete"
read2 "github.com/amine-khemissi/skeleton/endpoints/read"
update2 "github.com/amine-khemissi/skeleton/endpoints/update"
write2 "github.com/amine-khemissi/skeleton/endpoints/write"
)
type stringService struct {
DBInstance db.DB
}
func (s *stringService) Write(ctx context.Context, req write.Request) (write.Response, error) {
return write2.Write(ctx, s.DBInstance, req)
}
func (s *stringService) Update(ctx context.Context, req update.Request) (update.Response, error) {
return update2.Update(ctx, s.DBInstance, req)
}
func (s *stringService) Read(ctx context.Context, req read.Request) (read.Response, error) {
return read2.Read(ctx, s.DBInstance, req)
}
func (s *stringService) Delete(ctx context.Context, req delete.Request) (delete.Response, error) {
return delete2.Delete(ctx, s.DBInstance, req)
}
func New(ctx context.Context) def.Service {
return &stringService{
DBInstance: mongo.New(ctx),
}
}
<file_sep>package read
type Request struct {
ClientID string `json:"-" path:"clientID"`
}
type Response struct {
Name string `json:"name,omitempty"`
Age int `json:"age,omitempty"`
}
<file_sep>package config
import (
"context"
"net/http"
"github.com/amine-khemissi/skeleton/backbone/endpointimpl"
"github.com/go-kit/kit/endpoint"
)
type ep struct {
}
type Request struct {
}
func (e ep) GetRequest() interface{} {
return &struct {
}{}
}
func NewEndpoint() endpointimpl.EndpointImpl {
return &ep{}
}
func (e ep) MakeEndpoint(svc interface{}) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
return gConf.(*config).Content, nil
}
}
func (e ep) GetVerb() string {
return http.MethodGet
}
func (e ep) GetPath() string {
return "/_internal/config"
}
<file_sep>version: "3.3"
services:
mongodb:
image: 'mongo:4.4'
container_name: 'mongodb'
volumes:
- ./conf/mongod.conf:/etc/mongod.conf
ports:
- "27017-27019:27017-27019"
web:
build: .
container_name: 'skeleton'
# command: /app/svc
volumes:
- ./conf/config.json:/app/config.json
ports:
- "8080:8080"
depends_on:
- mongodb
testsvc:
image: centos
container_name: testsvc
depends_on:
- mongodb
command: sleep 1000
<file_sep>package header
const (
ContextID = "x-context-id"
)
<file_sep>package write
type Request struct {
Name string `json:"name"`
Age int `json:"age"`
}
type Response struct {
ClientID string `json:"clientID"`
}
<file_sep>package transportread
import (
"context"
"net/http"
"github.com/amine-khemissi/skeleton/def/read"
"github.com/amine-khemissi/skeleton/backbone/endpointimpl"
"github.com/amine-khemissi/skeleton/def"
"github.com/go-kit/kit/endpoint"
)
type ep struct {
}
func (e ep) GetRequest() interface{} {
return &read.Request{}
}
func NewEndpoint() endpointimpl.EndpointImpl {
return &ep{}
}
func (e ep) MakeEndpoint(svc interface{}) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(*read.Request)
return svc.(def.Service).Read(ctx, *req)
}
}
func (e ep) GetVerb() string {
return http.MethodGet
}
func (e ep) GetPath() string {
return "/person/{clientID}"
}
<file_sep>package server
import (
"context"
"net/http"
"github.com/amine-khemissi/skeleton/backbone/header"
"github.com/google/uuid"
)
func addContextID(ctx context.Context, r *http.Request) context.Context {
return header.Add(ctx, header.ContextID, uuid.New().String())
}
<file_sep>package write
import (
"context"
"crypto/md5"
"fmt"
"strconv"
"github.com/amine-khemissi/skeleton/backbone/db"
"github.com/amine-khemissi/skeleton/backbone/errorsklt"
"github.com/amine-khemissi/skeleton/backbone/logger"
"github.com/amine-khemissi/skeleton/def/write"
)
func Write(ctx context.Context, instance db.DB, req write.Request) (write.Response, error) {
logger.Instance().Debug(ctx, "Write", req.Name, req.Age)
hash := fmt.Sprintf("%x", md5.Sum([]byte(req.Name+strconv.Itoa(req.Age))))
item := map[string]interface{}{
"ID": hash,
"name": req.Name,
"age": req.Age,
}
if err := instance.InsertOne(ctx, "people", item); err != nil {
return write.Response{}, errorsklt.Stack(err, "failed to insert new person")
}
return write.Response{
ClientID: hash,
}, nil
}
<file_sep>package server
import (
"context"
"encoding/json"
"net/http"
"github.com/amine-khemissi/skeleton/backbone/header"
"github.com/amine-khemissi/skeleton/backbone/errorsklt"
)
func encodeHeaders(ctx context.Context, w http.ResponseWriter) {
for k, v := range header.GetAll(ctx) {
w.Header().Add(k, v)
}
}
func genericEncoder(ctx context.Context, w http.ResponseWriter, response interface{}) error {
encodeHeaders(ctx, w)
return json.NewEncoder(w).Encode(response)
}
func genericErrorEncoder(ctx context.Context, err error, w http.ResponseWriter) {
encodeHeaders(ctx, w)
skltErr, isSkltErr := err.(*errorsklt.InternalErr)
if isSkltErr {
w.WriteHeader(skltErr.Code)
bts, _ := json.Marshal(skltErr.Stack)
w.Write(bts)
return
}
w.WriteHeader(http.StatusInternalServerError)
bts, _ := json.Marshal(err)
w.Write(bts)
}
|
3dca6c20762c84b8faf76faa84c6dd0557086c2a
|
[
"YAML",
"Markdown",
"Makefile",
"Go",
"Go Module",
"Dockerfile"
] | 35
|
Go
|
amine-khemissi/skeleton
|
30a46895dc973c8fc996b5231f48bd0ddb562362
|
59ddb8b2ae55eba4c97cdf59572a5b7f1eda74f2
|
refs/heads/master
|
<repo_name>indie21/navmesh<file_sep>/navi.go
package navmesh
import (
"errors"
"math/rand"
. "github.com/spate/vectormath"
)
var (
ERROR_TRIANGLELIST_ILLEGAL = errors.New("triangle list illegal")
)
type TriangleList struct {
Vertices []Point3
Triangles [][3]int32 // triangles
}
type BorderList struct {
Indices []int32 // 2pt as border
}
type Path struct {
Line []Point3
}
type NavMesh struct{}
// 从P1处随机偏移一个到(min, max)的长度。
func spinOffset(p1, p2 Point3, min, max float32) Point3 {
var v1 Vector3
P3Sub(&v1, &p2, &p1)
if v1.Length() < min {
return p1
}
if v1.Length() < max {
max = v1.Length()
}
V3Normalize(&v1, &v1)
V3ScalarMul(&v1, &v1, rand.Float32()*(max-min)+min)
V3AddP3(&v1, &v1, &p1)
P3MakeFromV3(&p1, &v1)
return p1
}
func (nm *NavMesh) Route(list TriangleList, start, end *Point3) (*Path, error) {
r := Path{}
// 计算临边
border := nm.create_border(list.Triangles)
// 目标点
vertices := append(list.Vertices, *end)
border = append(border, int32(len(vertices))-1, int32(len(vertices))-1)
// 第一个可视区域
line_start := start
last_vis_left, last_vis_right, last_p_left, last_p_right := nm.update_vis(start, vertices, border, 0, 1)
var res Vector3
for k := 2; k <= len(border)-2; k += 2 {
cur_vis_left, cur_vis_right, p_left, p_right := nm.update_vis(line_start, vertices, border, k, k+1)
V3Cross(&res, last_vis_left, cur_vis_right)
if res.Z > 0 { // 左拐点
line_start = &vertices[border[last_p_left]]
r.Line = append(r.Line, *line_start)
// 找到一条不共点的边作为可视区域
i := 2 * (last_p_left/2 + 1)
for ; i <= len(border)-2; i += 2 {
if border[last_p_left] != border[i] && border[last_p_left] != border[i+1] {
last_vis_left, last_vis_right, last_p_left, last_p_right = nm.update_vis(line_start, vertices, border, i, i+1)
break
}
}
k = i
continue
}
V3Cross(&res, last_vis_right, cur_vis_left)
if res.Z < 0 { // 右拐点
line_start = &vertices[border[last_p_right]]
r.Line = append(r.Line, *line_start)
// 找到一条不共点的边
i := 2 * (last_p_right/2 + 1)
for ; i <= len(border)-2; i += 2 {
if border[last_p_right] != border[i] && border[last_p_right] != border[i+1] {
last_vis_left, last_vis_right, last_p_left, last_p_right = nm.update_vis(line_start, vertices, border, i, i+1)
break
}
}
k = i
continue
}
V3Cross(&res, last_vis_left, cur_vis_left)
if res.Z < 0 {
last_vis_left = cur_vis_left
last_p_left = p_left
}
V3Cross(&res, last_vis_right, cur_vis_right)
if res.Z > 0 {
last_vis_right = cur_vis_right
last_p_right = p_right
}
}
return &r, nil
}
func (nm *NavMesh) create_border(list [][3]int32) []int32 {
var border []int32
for k := 0; k < len(list)-1; k++ {
for _, i := range list[k] {
for _, j := range list[k+1] {
if i == j {
border = append(border, i)
}
}
}
}
return border
}
// 按一定的比例随机收缩,可以让点有一定的变化.
func (nm *NavMesh) shrink_border(list []int32, vertices []Point3, rate float32) (nBorder []int32, nVertices []Point3) {
nVertices = make([]Point3, len(list))
nBorder = make([]int32, len(list))
for k := 0; k < len(list); k += 2 {
// if vertices[list[k]] == vertices[list[k+1]] {
// nBorder[k] = int32(k)
// nBorder[k+1] = int32(k + 1)
// nVertices[k] = vertices[list[k]]
// nVertices[k+1] = vertices[list[k+1]]
// break
// }
//1.计算两点中点.
//2.计算当前中点到上下两点的向量.
//3.对向量大小进行减小后重新计算上线两点。
mx := (vertices[list[k]].X + vertices[list[k+1]].X) / 2
my := (vertices[list[k]].Y + vertices[list[k+1]].Y) / 2
mp := Point3{X: mx, Y: my, Z: 0}
var m1v, m2v Vector3
P3Sub(&m1v, &vertices[list[k]], &mp)
P3Sub(&m2v, &vertices[list[k+1]], &mp)
var m1v2, m2v2 Vector3
m1v2 = Vector3{
X: m1v.X * rate,
Y: m1v.Y * rate,
Z: m1v.Z * rate,
}
m2v2 = Vector3{
X: m2v.X * rate,
Y: m2v.Y * rate,
Z: m2v.Z * rate,
}
var n1, n2 Point3
P3AddV3(&n1, &mp, &m1v2)
P3AddV3(&n2, &mp, &m2v2)
// fmt.Printf("old %v %v\n", vertices[list[k]], vertices[list[k+1]])
// fmt.Printf("mid %v %v\n", mp, mp)
// fmt.Printf("vec %v %v\n", m1v, m2v)
// fmt.Printf("v2c %v %v\n", m1v2, m2v2)
// fmt.Printf("new %v %v\n\n", n1, n2)
nBorder[k] = int32(k)
nBorder[k+1] = int32(k + 1)
nVertices[k] = n1
nVertices[k+1] = n2
}
return
}
func (nm *NavMesh) update_vis(v0 *Point3, vertices []Point3, indices []int32, i1, i2 int) (l, r *Vector3, left, right int) {
var left_vec, right_vec, res Vector3
P3Sub(&left_vec, &vertices[indices[i1]], v0)
P3Sub(&right_vec, &vertices[indices[i2]], v0)
V3Cross(&res, &left_vec, &right_vec)
if res.Z > 0 {
return &right_vec, &left_vec, i2, i1
} else {
return &left_vec, &right_vec, i1, i2
}
}
func (nm *NavMesh) RouteWithRandOffset(list TriangleList,
start, end *Point3,
min, max float32) (*Path, error) {
if min > max {
max, min = min, max
}
r := Path{}
// 计算临边
border := nm.create_border(list.Triangles)
// 将临边进行一定收缩变换.
// vertices := list.Vertices
border, vertices := nm.shrink_border(border, list.Vertices, 0.6+0.4*rand.Float32())
// 目标点
vertices = append(vertices, *end)
border = append(border, int32(len(vertices))-1, int32(len(vertices))-1)
// 第一个可视区域
line_start := *start
last_vis_left, last_vis_right, last_p_left, last_p_right := nm.update_vis(start, vertices, border, 0, 1)
var res Vector3
for k := 2; k <= len(border)-2; k += 2 {
cur_vis_left, cur_vis_right, p_left, p_right := nm.update_vis(
&line_start, vertices, border, k, k+1)
V3Cross(&res, last_vis_left, cur_vis_right)
if res.Z > 0 { // 左拐点
line_start = vertices[border[last_p_left]]
r.Line = append(r.Line, line_start)
// 找到一条不共点的边作为可视区域
i := 2 * (last_p_left/2 + 1)
for ; i <= len(border)-2; i += 2 {
if border[last_p_left] != border[i] && border[last_p_left] != border[i+1] {
last_vis_left, last_vis_right, last_p_left, last_p_right = nm.update_vis(&line_start, vertices, border, i, i+1)
break
}
}
k = i
continue
}
V3Cross(&res, last_vis_right, cur_vis_left)
if res.Z < 0 { // 右拐点
line_start = vertices[border[last_p_right]]
r.Line = append(r.Line, line_start)
// 找到一条不共点的边
i := 2 * (last_p_right/2 + 1)
for ; i <= len(border)-2; i += 2 {
if border[last_p_right] != border[i] && border[last_p_right] != border[i+1] {
last_vis_left, last_vis_right, last_p_left, last_p_right = nm.update_vis(&line_start, vertices, border, i, i+1)
break
}
}
k = i
continue
}
V3Cross(&res, last_vis_left, cur_vis_left)
if res.Z < 0 {
last_vis_left = cur_vis_left
last_p_left = p_left
}
V3Cross(&res, last_vis_right, cur_vis_right)
if res.Z > 0 {
last_vis_right = cur_vis_right
last_p_right = p_right
}
}
return &r, nil
}
|
10af8a372d3bcd960885a31d4398168370c18e50
|
[
"Go"
] | 1
|
Go
|
indie21/navmesh
|
2efe6d21499806e0d552551e7cd87fbdeb56affa
|
8cf384b30ec160ef5fe332503fa82054714aa51c
|
refs/heads/master
|
<repo_name>bigtunacan/node<file_sep>/learnyounode/sync_io.js
var fs = require('fs')
var fileBuffer = fs.readFileSync(process.argv[2])
var fileBuffer.toString().split('\n')
<file_sep>/expressworks/app.js
// Require libraries
var express = require('express');
var path = require('path');
var fs = require('fs');
// Config
var app = express();
app.set('view engine', 'jade');
app.set('views', path.join(__dirname, 'templates'));
app.use(express.urlencoded())
// app.use(express.static(process.argv[3] || path.join(__dirname, 'public')))
app.use(express.static(path.join(__dirname, 'public')))
app.use(require('stylus').middleware(path.join(__dirname + 'public')))
app.get('/books', function(req, res){
var fileName = process.argv[3];
var fileString = fs.readFile(fileName, function(err, contents){
res.json(JSON.parse(contents));
});
});
// Command line arguments go into process.argv[]
// First 2 args are 'node', '/path/to/program.js'
// app.set('views', process.argv[3]);
app.get('/search', function(req, res){
res.send(req.query);
});
app.put('/message/:id', function(req, res){
var id = req.params.id;
var str = require('crypto')
.createHash('sha1')
.update(new Date().toDateString().toString() + id)
.digest('hex')
res.send(str);
});
// app.get('/home', function(req, res){
// res.render('index', {date: new Date().toDateString()});
// })
// app.post('/form', function(req, res){
// res.send(req.body.str.split('').reverse().join(''))
// })
app.listen(process.argv[2]);
<file_sep>/codeschool/app.js
var makeRequest = require('./make_request.js');
makeRequest("Here's looking at you, kid");
|
2ed36844e05e7f473f2815f3316d81398634de58
|
[
"JavaScript"
] | 3
|
JavaScript
|
bigtunacan/node
|
be49899c68d6438285621af3b5647eb75a1f221b
|
1ab29ccf67f8c64c1e746434d8731acbad450537
|
refs/heads/master
|
<repo_name>andrena/pipeline-demo-application<file_sep>/README.md
# Continuous Delivery and Jenkins Pipeline Demo
This is a demo project to be used to demonstrate how to quickly build a Continuous Delivery Pipeline with [Jenkins Pipeline Plugin](https://github.com/jenkinsci/pipeline-plugin/blob/master/TUTORIAL.md). This project is a fork of [cloudfoundry-samples/pong_matcher_spring](https://github.com/cloudfoundry-samples/pong_matcher_spring) as an example application written in java.
Also related:
- [Short presentation](presentation.pptx)
- [Pipeline-Demo-Jenkins-Docker](https://github.com/tanderer/pipeline-demo-jenkins-docker) - How to setup a Jenkins with Docker to run this demo
- [Acceptance Tests for the application](https://github.com/tanderer/pipeline-demo-acceptance)
<file_sep>/SETUP.md
# Continuous Delivery with Jenkins Pipeline
* Explain a bit about Jenkins Pipeline
* Fork the Repository of the application (https://github.com/cloudfoundry-samples/pong_matcher_spring.git)
* Add a Jenkinsfile
* Maven build
## Order Jenkinsfile
* echo
* stage
* node
* Commit-Stage git / maven
* versioning (methods?)
* junit / findbugs
* deploy to test (methods?)
* acceptance-test with docker
* parallel manual step
* b/g deployment (external file? load?)
### Intro
- Create Jenkins pipeline job
Edit pipeline inline
```
stage("Stage A") {
node {
echo "Hello A"
}
}
stage ("Stage B") {
node {
echo ("Hello B")
}
}
```
### CI-Build
Switch to Jenkinsfile
Select git repo `<EMAIL>:thomasanderer/pipeline-demo.git`
`Jenkinsfile`
```
node {
stage('CI-Build') {
def mvnHome = tool 'M3'
git url: '<EMAIL>:thomasanderer/pipeline-demo.git'
sh "${mvnHome}/bin/mvn -B verify"
junit 'target/surefire-reports/**.xml'
}
}
```
Goto IntelliJ
```
node {
stage ('CI-Build') {
def mvnHome = tool 'M3'
git url: '<EMAIL>:thomasanderer/pipeline-demo.git'
sh "${mvnHome}/bin/mvn -B verify"
junit 'target/surefire-reports/**.xml'
step([$class: 'FindBugsPublisher', canComputeNew: false, defaultEncoding: '', excludePattern: '', healthy: '', includePattern: '', pattern: '**/findbugs.xml', unHealthy: ''])
stash includes: "manifest.yml, target/pong-matcher-spring-${version}.jar", name: 'artifacts'
}
}
```
extract method
### Automatic Versioning
```
private void versioning(mvnHome) {
sh """
echo "MVN=`${mvnHome}/bin/mvn -q -Dexec.executable="echo" -Dexec.args='\${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec`" > version.properties
echo "COMMIT=`git rev-parse --short HEAD`" >> version.properties
echo "TIMESTAMP=`date +\"%Y%M%d_%H%M%S\"`" >> version.properties
"""
def pomVersion = readProperties file: 'version.properties'
echo "Pom-Version=$pomVersion"
def version = "${pomVersion['MVN']}-${pomVersion['TIMESTAMP']}_${pomVersion['COMMIT']}"
echo "Automated version: ${version}"
sh "${mvnHome}/bin/mvn versions:set -DnewVersion=\"${version}\""
pushPomBuildTag(version)
return version
}
private void pushPomBuildTag(version) {
sh """
git add pom.xml
git commit -m "versioning $version"
git tag BUILD_$version
git push origin BUILD_$version
"""
}
private void executeCiBuild(mvnHome, version) {
sh "${mvnHome}/bin/mvn -B verify"
junit 'target/surefire-reports/**.xml'
step([$class: 'FindBugsPublisher', canComputeNew: false, defaultEncoding: '', excludePattern: '', healthy: '', includePattern: '', pattern: '**/findbugs.xml', unHealthy: ''])
stash includes: "manifest.yml, target/pong-matcher-spring-${version}.jar", name: 'artifacts'
}
```
refactor to
```
def version = ""
node {
def mvnHome = tool 'M3'
stage('Checkout') {
git url: '<EMAIL>:thomasanderer/pipeline-demo.git'
}
stage('Versioning') {
version = versioning(mvnHome)
}
stage('CI-Build') {
executeCiBuild(mvnHome, version)
}
}
```
### Acceptance tests - Deploy
```
stage('Acceptance') {
deployToCf(version)
}
private void deployToCf(version) {
node {
unstash name: 'artifacts'
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: '<PASSWORD>', passwordVariable: '<PASSWORD>', usernameVariable: 'CF_USERNAME']]) {
sh """
cf login -a https://api.aws.ie.a9s.eu -o thomas_rauner_andrena_de -s test -u $CF_USERNAME -p $CF_PASSWORD
set +e
cf create-service a9s-postgresql postgresql-single-small mysql
set -e
cf push -n cf-demo-andrena-test -p \"target/pong-matcher-spring-${version}.jar\"
"""
}
}
}
```
### Acceptance tests - Run
```
stage('Acceptance') {
deployToCf(version)
runAcceptanceTest()
}
private void runAcceptanceTest() {
node {
def testHost = "http://cf-demo-andrena-test.aws.ie.a9sapp.eu"
git url: '<EMAIL>:thomasanderer/pongmatcher-acceptance-fixed.git'
sh """#/bin/bash -ex
docker build -t pong-matcher-acceptance .
docker run --name acceptance --rm -e \"HOST=$testHost\" pong-matcher-acceptance
"""
}
}
```
### Parallel Manual tests
```
stage('Acceptance') {
deployToCf(version)
parallel automated: {
runAcceptanceTest()
}, manual: {
manualAcceptanceCheck()
}
}
private void manualAcceptanceCheck() {
node {
input("Manual acceptance tests successfully?")
}
}
```
### Blue-Green-Deploy to Production
```
node {
stage('Production') {
unstash name: 'artifacts'
deployer = load 'Deploy.Jenkinsfile'
blueGreenDeploy("cf-demo-andrena-prod", version, "target/pong-matcher-spring-${version}.jar", "cf-demo-andrena-prod")
}
}
```
## Links
### Continuous Delivery
### Jenkins Pipeline
* [https://github.com/jenkinsci/pipeline-plugin/blob/master/TUTORIAL.md](Jenkins Pipeline Tutorial)
<file_sep>/src/main/resources/db/migration/V1__match_request.sql
CREATE TABLE match_request (
id BIGSERIAL PRIMARY KEY,
uuid VARCHAR(255) NOT NULL,
requester_id VARCHAR(255) NOT NULL,
CONSTRAINT unique_uuid UNIQUE (uuid)
);
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<groupId>io.pivotal</groupId>
<artifactId>pong-matcher-spring</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<!-- code_snippet gsg-spring-s3 start -->
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4.1211.jre7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<!-- code_snippet gsg-spring-s3 end -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>3.0.4</version>
<configuration>
<!--
Enables analysis which takes more memory but finds more bugs.
If you run out of memory, changes the value of the effort element
to 'Low'.
-->
<effort>Max</effort>
<!-- Reports all bugs (other values are medium and max) -->
<threshold>Low</threshold>
<!-- Produces XML report -->
<xmlOutput>true</xmlOutput>
<failOnError>false</failOnError>
<!-- TODO: remove-->
<!-- Configures the directory in which the XML report is created -->
<findbugsXmlOutputDirectory>${project.build.directory}/findbugs</findbugsXmlOutputDirectory>
</configuration>
<executions>
<!--
Ensures that FindBugs inspects source code when project is compiled.
-->
<execution>
<id>analyze-compile</id>
<phase>compile</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
|
7b532cab3ad68901729963900ae108f08b27d9b0
|
[
"Markdown",
"SQL",
"Maven POM"
] | 4
|
Markdown
|
andrena/pipeline-demo-application
|
83deb4b0649500fb1950cea4bc7f54690e56004a
|
3f4ac72203a6e1cd9b47fa2bfc29f9fa75216ed0
|
refs/heads/main
|
<repo_name>saieshwar/PersonalBudget_BackEnd<file_sep>/routes/expenseRoute.js
const express = require("express");
const auth = require("../middleware/auth");
const router = express.Router();
const expense = require("../models/expenseModel");
//post expense
router.post("/", auth, async(req,res) => {
try{
const {title,related_value, month, year} = req.body;
if(!title || !related_value || !month || !year)
return res.status(400).json({ msg: "All details should be entered" });
if(!title)
return res.status(400).json({ msg: "Title should been entered" });
const expenseData = new expense ({
title,related_value,month,year,
userId : req.user,
});
const expenseSaveData = await expenseData.save();
res.json(expenseSaveData);
}catch(err){
res.status(500).json({error: err.message});
}
});
//get
router.get("/",auth,async(req,res) => {
res.json(await expense.find({userId: req.user}));
})
module.exports = router;<file_sep>/models/budgetModel.js
const mongoose = require("mongoose");
const budgetSchema = new mongoose.Schema({
title : {
type: String,
require: true
},
related_value : {
type: Number,
required: true
},
Color : {
type: String,
required: true
},
userId: {
type: String,
required: true
}
});
function isHexColor(s) {
return /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(s)
}
module.exports = mongoose.model("budget", budgetSchema);<file_sep>/routes/budgetRoute.js
const express = require("express");
const auth = require("../middleware/auth");
const router = express.Router();
const budget = require("../models/budgetModel");
//post details
router.post("/", auth, async(req,res) => {
try{
const {title,related_value, Color} = req.body;
if(!title || !related_value || !Color)
return res.status(400).json({ msg: "All details should be entered" });
if(isNaN(related_value)){
return res.status(400).json({ msg: "Related value should be number" });
}
if(!title)
return res.status(400).json({ msg: "Title should been entered" });
const budgetData = new budget({
title,related_value,Color,
userId : req.user,
});
const saveData = await budgetData.save();
res.json(saveData);
}catch(err){
res.status(500).json({error: err.message});
}
});
//Get
router.get("/",auth,async(req,res) => {
res.json(await budget.find({userId: req.user}));
})
module.exports = router;<file_sep>/mongo-insert.test.js
const mongoose = require('mongoose');
const budgetModel = require('./models/budgetModel');
const UserModel = require('./models/userModel');
const expenseModel=require('./models/expenseModel');
const userData = { email: 'T<PASSWORD>on', password:'<PASSWORD>',displayName:'n<PASSWORD>g' };
let user_id='';
describe('User Model Test', () => {
// It's just so easy to connect to the MongoDB Memory Server
// By using mongoose.connect
beforeAll(async () => {
await mongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true, useCreateIndex: true }, (err) => {
if (err) {
console.error(err);
process.exit(1);
}
});
});
it('create & save user successfully', async () => {
const validUser = new UserModel(userData);
const savedUser = await validUser.save();
// Object Id should be defined when successfully saved to MongoDB.
user_id=savedUser._id;
expect(savedUser._id).toBeDefined();
expect(savedUser.email).toBe(userData.email);
});
it('save budget successfully', async () => {
const budgetData={title:'Youtube',related_value:55,Color: "#000000",userId:user_id};
const budget=new budgetModel(budgetData);
const savedBudget = await budget.save();
expect(savedBudget._id).toBeDefined();
expect(savedBudget.title).toBe(budgetData.title);
});
it('save expense successfully', async () => {
const expenseData={title:'Youtube',month:'01',year:'2020',related_value:55,userId:user_id};
const expense=new expenseModel(expenseData);
const savedExpense = await expense.save();
expect(savedExpense._id).toBeDefined();
expect(savedExpense.title).toBe(expenseData.title);
});
})
|
39468d21dbc65b3c5e3389d92e075ac90c476fc8
|
[
"JavaScript"
] | 4
|
JavaScript
|
saieshwar/PersonalBudget_BackEnd
|
f4b95451a5cae7bc1885c375815709e8c8c60c7e
|
824832a7aae277b45816bf431fbc99eab758edf0
|
refs/heads/master
|
<file_sep><?php
class Blog extends CI_Controller{
public function add(){
$this->load->model('authenticate');
$data['users'] = $this->authenticate->getData();
$this->load->view("blog/add.php",$data);
}
}<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
</head>
<body>
<h1>Blog Add</h1>
<table>
<?php
foreach($users as $user):?>
<tr>
<td><?php echo $user['first_name']; ?></td>
<td><?php echo $user['last_name']; ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html><file_sep><?php
function test(){
echo "ABC Helper function";
}<file_sep><?php
class Authenticate extends CI_Model{
public function getData(){
$this->load->helper('abc');
test();
$this->load->database();
$query = $this->db->query("Select * from users");
return $query->result_array();
/*return [
['name' => 'Vishal' ,'last_name' => 'Bhardwaj'],
['name' => 'Bishal' ,'last_name' => 'Kumar'],
];*/
}
}
|
34fedb794a2a84de075e298e946af475e0384f32
|
[
"PHP"
] | 4
|
PHP
|
vishalji1986/codeIgniter1-3.1.6
|
2590798646a7e12921b4570b3c43bc30f9957bb7
|
8d16ff39565901a0fb975399dd2884bf5883ec0c
|
refs/heads/main
|
<file_sep>import Head from 'next/head'
import Image from 'next/image'
import Link from 'next/link'
import styles from '../styles/Home.module.css'
export default function Home() {
return (
<>
<Head>
<title>Shahadat | Home</title>
<meta name="keywords" content="Shahadat"></meta>
</Head>
<div>
<h1 className={styles.title}>Homepage</h1>
<p className={styles.text}>
Argentina striker Lionel Messi will leave Barcelona despite both parties having reached an agreement over a new contract, the La Liga club said on Thursday, citing economic and structural obstacles to the renewal of deal. "Despite FC Barcelona and Lionel Messi having reached an agreement and the clear intention of both parties to sign a new contract today, this cannot happen because of financial and structural obstacles (Spanish La Liga regulations)," Barca said in a statement.
</p>
<p className={styles.text}>
rgentina striker Lionel Messi will leave Barcelona despite both parties having reached an agreement over a new contract, the La Liga club said on Thursday, citing economic and structural obstacles to the renewal of deal. "Despite FC Barcelona and Lionel Messi having reached an agreement and the clear intention of both parties to sign a new contract today, this cannot happen because of financial and structural obstacles (Spanish La Liga regulations)," Barca said in a statement.
</p>
<Link href="/shahadat">
<a className={styles.btn}>
See Shahadat's Profile
</a>
</Link>
</div>
</>
)
}
<file_sep>import styles from '../../styles/Jobs.module.css'
import Link from 'next/link'
export const getStaticProps = async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await res.json();
return {
props: { friends: data }
}
}
const Shahadats = ({friends}) => {
console.log(friends)
return (
<div>
<h1>All About Friends</h1>
{friends.map(friend => (
<Link href={'/shahadat/' + friend.id} key={friend.id}>
<a className={styles.single}>
<h3>{ friend.name }</h3>
</a>
</Link>
))}
</div>
);
}
export default Shahadats;<file_sep>const Footer = () => {
return (
<footer>
Copyright 2021. @Shahadat
</footer>
);
}
export default Footer;<file_sep>import Head from "next/head";
const About = () => {
return (
<>
<Head>
<title>Shahadat | About</title>
<meta name="keywords" content="Shahadat"></meta>
</Head>
<div>
<h1>About</h1>
<p>
<NAME> will leave Barcelona despite both parties having reached an agreement over a new contract, the La Liga club said on Thursday, citing economic and structural obstacles to the renewal of deal. "Despite FC Barcelona and Lionel Messi having reached an agreement and the clear intention of both parties to sign a new contract today, this cannot happen because of financial and structural obstacles (Spanish La Liga regulations)," Barca said in a statement.
</p>
<p>
<NAME> will leave Barcelona despite both parties having reached an agreement over a new contract, the La Liga club said on Thursday, citing economic and structural obstacles to the renewal of deal. "Despite FC Barcelona and Lionel Messi having reached an agreement and the clear intention of both parties to sign a new contract today, this cannot happen because of financial and structural obstacles (Spanish La Liga regulations)," Barca said in a statement.
</p>
</div>
</>
);
}
export default About;
|
a04199eafb1d8706e506d36702a36b4159342cd7
|
[
"JavaScript"
] | 4
|
JavaScript
|
mdshahadathossain-13/nextjs-first-app
|
62d479ff45aa87ca157dd66304792931aea43bd0
|
75b23e960a5be9be149dfbc2e2ad0a0cf3dfd9aa
|
refs/heads/master
|
<file_sep>class PokemonsController < ApplicationController
#hi
end
|
eed352ab8d2fea512a6d98fc411ab34fd281252e
|
[
"Ruby"
] | 1
|
Ruby
|
Cashman1396/js-rails-as-api-pokemon-teams-project-new-onl01-seng-pt-012120
|
e0998aae690f55d7ac71144e51171e9752e9ff58
|
715c373997f231a948697ecfc9524731e3461078
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IDELanguages
{
public class CSharpLabel : IDELib.IComponent
{
public override string Build()
{
return $"<Label Height='{Height}' Width='{Width}' Margin='{Left} {Top} 0 0' >{Content}</Label>";
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IDELib;
namespace IDELanguages
{
public class HTMLFactory : IDELib.ComponentFactory
{
public HTMLFactory()
{
base.LanguageName = "HTML";
}
public override void Execute()
{
string fullCode = $"<!DOCTYPE html><html><head><title>My generated HTML</title></head><body></body>{ComponentFactory.BuildAll(Components)}</html>";
ComponentFactory.Write(fullCode, "Compiled.html");
string currentDir = Environment.CurrentDirectory;
DirectoryInfo directory = new DirectoryInfo(
Path.GetFullPath(Path.Combine(currentDir, @"..\..\" + "Compiled.html")));
System.Diagnostics.Process.Start(directory.ToString());
}
public override void InstantiateAvailableComponents()
{
base.AvailableComponents = new List<IComponent> { new HTMLButton(), new HTMLDiv(), new HTMLParagraph(), new HTMLTextInput() };
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IDELib
{
abstract public class ComponentFactory
{
public ComponentFactory(){
LanguageName = "Default Language Name";
Components = new List<IComponent>();
}
public string LanguageName { get; set; }
public List<IComponent> Components { get; set; }
public List<IComponent> AvailableComponents { get; set; }
abstract public void InstantiateAvailableComponents();
public static string BuildAll(List<IComponent> list) {
string BuiltComponents = "";
foreach (IComponent component in list)
{
BuiltComponents += component.Build();
}
return BuiltComponents;
}
abstract public void Execute();
public static void Write(string content, string filename)
{
string currentDir = Environment.CurrentDirectory;
DirectoryInfo directory = new DirectoryInfo(
Path.GetFullPath(Path.Combine(currentDir, @"..\..\" + filename)));
using (StreamWriter outputFile = new StreamWriter(directory.ToString()))
{
outputFile.WriteLine(content);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IDELib;
namespace IDELanguages
{
public class Language : IDELib.IGenericLanguage
{
public Language()
{
LanguageFactories = InstaniateLanguages();
}
public List<string> LanguagesSupported { get; set; }
public List<ComponentFactory> LanguageFactories { get; set; }
public List<ComponentFactory> InstaniateLanguages()
{
List<ComponentFactory> languages = new List<ComponentFactory> { new CSharpFactory(), new HTMLFactory() };
LanguagesSupported = new List<string>();
foreach (ComponentFactory language in languages)
{
LanguagesSupported.Add(language.LanguageName);
}
return languages;
}
}
}
<file_sep>using IDELanguages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tester
{
class Program
{
public static void Main(string[] args)
{
HTMLFactory factory = new HTMLFactory();
HTMLButton button1 = new HTMLButton
{
Width = 100,
Height = 200,
Top = 10,
Left = 5,
Content = "Content"
};
factory.Components.Add(button1);
factory.Execute();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IDELib;
namespace IDELanguages
{
public class CSharpFactory : ComponentFactory
{
public CSharpFactory()
{
base.LanguageName = "C#";
}
public override void Execute()
{
string fullCode = $"<Window x:Class='IDE.MainWindow' xmlns = 'http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns: x = 'http://schemas.microsoft.com/winfx/2006/xaml'xmlns: d = 'http://schemas.microsoft.com/expression/blend/2008' xmlns: mc = 'http://schemas.openxmlformats.org/markup-compatibility/2006' xmlns: local = 'clr-namespace:IDE'mc: Ignorable = 'd' Title = 'FactoryPattern- GUIBuilder9000' Height = '350' Width = '700' ><Grid>{ComponentFactory.BuildAll(Components)}</Grid></Window>";
}
public override void InstantiateAvailableComponents()
{
base.AvailableComponents = new List<IComponent> { new CSharpButton(), new CSharpLabel() };
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IDELanguages
{
public class CSharpButton : IDELib.IComponent
{
public override string Build()
{
return $"<Button Height='{Height}' Width='{Width}' Margin='{Left} {Top} 0 0' >{Content}</Button>";
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IDELib
{
abstract public class IComponent
{
public string Content { get; set; }
public double Height { get; set; }
public double Width { get; set; }
public double Top { get; set; }
public double Left { get; set; }
abstract public string Build();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IDELib
{
public interface IGenericLanguage
{
/// <summary>
/// Contains all supported libraries for the user to output.
/// </summary>
List<string> LanguagesSupported { get; set; }
/// <summary>
/// Instansiates all supported languages.
/// </summary>
/// <returns>The list of instaniated languages.</returns>
List<ComponentFactory> InstaniateLanguages();
List<ComponentFactory> LanguageFactories { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IDELanguages
{
public class HTMLButton : IDELib.IComponent
{
public override string Build()
{
return $"<button style='position:absolute;top:{Top}px;left:{Left}px;width:{Width}px;height:{Height}px;'>{Content}</button>";
}
}
}
<file_sep>using IDELanguages;
using IDELib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace IDE
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
IGenericLanguage IGL = new Language();
ComponentFactory CF;
public MainWindow()
{
InitializeComponent();
foreach (string languageName in IGL.LanguagesSupported )
{
SelectLanguageCB.Items.Add(languageName);
}
}
private void ContinueBtnClicked(object sender, RoutedEventArgs e)
{
SelectLanguageSP.Visibility = Visibility.Hidden;
GUIBuilderSP.Visibility = Visibility.Visible;
for (int i = 0; i < SelectLanguageCB.Items.Count; i++)
{
if (SelectLanguageCB.Items[i] == SelectLanguageCB.SelectedValue)
{
CF = IGL.LanguageFactories[i];
}
}
}
private void CreatComponentBtnClicked(object sender, RoutedEventArgs e)
{
string width = WidthTB.Text;
string height = HeightTB.Text;
string leftAlign = LeftAlignTB.Text;
string topAlign = TopAlignTB.Text;
}
}
}
|
06332376e255f623c96ec05345885126a167bf53
|
[
"C#"
] | 11
|
C#
|
Goldragon747/IDE
|
66760499603335c6dc93c073477da54d84885df7
|
8b0a0f49656c2940c1eb7657d314bcb1bb5771b7
|
refs/heads/master
|
<file_sep>require 'test_helper'
class TimeEntryTest < ActiveSupport::TestCase
should "not be able to delete locked entries" do
entry = TimeEntry.find_by_status( TimeEntry::LOCKED )
entry.destroy
assert_nothing_raised { TimeEntry.find(entry.id) }
end
should "find 1 time_entry on day 1. july, 2009" do
entries = TimeEntry.on_day( Date.new(2009,7,1) )
assert_equal entries.size, 1
end
should "find no billed time_entries" do
entries = TimeEntry.billed(true)
assert_equal entries.size, 0
end
should "find 2 time_entries between 1st and 2nd of july, 2009" do
entries = TimeEntry.between( Date.new(2009,7,1), Date.new(2009,7,2) )
assert_equal entries.size, 2
end
should "find hours for activity" do
entries = TimeEntry.for_activity(activities(:timeflux_development).id)
assert_operator entries.size, :>, 0
assert_equal entries.size, activities(:timeflux_development).time_entries.size
end
should "find Bob´s hours" do
entries = TimeEntry.for_user(users(:bob).id)
assert_operator entries.size, :>, 0
assert_equal entries.size, users(:bob).time_entries.size
end
end<file_sep>class Department < ActiveRecord::Base
has_many :users
validates_presence_of :internal_id, :name
validates_uniqueness_of :internal_id, :name
end
<file_sep>class Billing
def initialize(customers, date)
@customers = customers
@from = date.at_beginning_of_month
@to = date.at_end_of_month
end
def billing_report_data
data = []
customer_total=0
@customers.each do |customer|
projects_data = []
customer.projects.sort.each do |project|
time_entries = TimeEntry.billed(false).between(@from,@to).for_project(project).include_users.include_hour_types.all
unless time_entries.empty?
project_total = 0
entries = []
time_entries.group_by(&:user).each do |user,group1|
group1.group_by(&:hour_type).each do |type,group2|
sum = 0
group2.each{|e| sum += e.hours}
entries << [user,"#{type.name}",sum]
project_total += sum
end
end
projects_data << [project, project_total, entries]
customer_total += project_total
end
end
data << [customer.name, customer_total, projects_data]
end
data
end
end
|
056347d45510ff9ffabc675f3af171b4e84583d7
|
[
"Ruby"
] | 3
|
Ruby
|
stigkj/TimeFlux
|
92743aca3c6cd88368a5f684ce96104b878f1086
|
c0c57c6c788d6d6f226dc614c7f8b5f6890d5419
|
refs/heads/master
|
<file_sep>#write your code here
def countdown(n)
while n > 0
if n == 1
puts "#{n} SECOND!"
n -= 1
else
puts "#{n} SECONDS!"
n -= 1
end
"HAPPY NEW YEAR!"
end
end
def countdown_with_sleep(n)
while n > 0
if n == 1
puts "#{n} SECOND!"
sleep(1)
n -= 1
else
puts "#{n} SECONDS!"
sleep(1)
n -= 1
end
end
end
countdown_with_sleep(5)
countdown(10)
|
bba8f6e7237e5a484fa71a2bd84e38274f18e8e7
|
[
"Ruby"
] | 1
|
Ruby
|
NolanHughes/countdown-to-midnight-v-000
|
dce1eebcdc4d043e42897963f86d225f1e47dc77
|
52b9b46590de7c91770c32c4a5f352034ad50645
|
refs/heads/master
|
<repo_name>kxnst/lab<file_sep>/lab3.1/Classes/IDrive.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace lab3._1.Classes
{
interface IDrive
{
public void Drive();
}
}
<file_sep>/lab3.1/Classes/IStudy.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace lab3._1.Classes
{
interface IStudy
{
public void Study();
}
}
<file_sep>/lab3.1/Classes/ITeach.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace lab3._1.Classes
{
interface ITeach
{
public void Teach();
}
}
|
57ddd50330d528e0254cce71166553f249d8e698
|
[
"C#"
] | 3
|
C#
|
kxnst/lab
|
42cb6fba49cf7952d28f432d709c0475810436b9
|
c84744a7f6ab43b107e081c1d792e58ab96b0f43
|
refs/heads/master
|
<file_sep><?php
namespace Pucene\Components\Metadata;
use Pucene\Components\Metadata\Driver\DriverInterface;
class MetadataFactory implements MetadataFactoryInterface
{
/**
* @var DriverInterface
*/
private $driver;
public function __construct(DriverInterface $driver)
{
$this->driver = $driver;
}
public function getAllClassNames(): array
{
return $this->driver->getAllClassNames();
}
public function getMetadataForClass(string $className): ?ClassMetadataInterface
{
$metadata = null;
foreach ($this->getClassHierarchy($className) as $class) {
$metadata = $this->merge($metadata, $this->loadClassMetadata($class));
}
return $metadata;
}
protected function loadClassMetadata(\ReflectionClass $class): ?ClassMetadataInterface
{
return $this->driver->loadMetadataForClass($class);
}
/**
* @return \ReflectionClass[]
*/
private function getClassHierarchy(string $className): array
{
$classes = [];
$reflection = new \ReflectionClass($className);
do {
$classes[] = $reflection;
$reflection = $reflection->getParentClass();
} while (false !== $reflection);
return array_reverse($classes, false);
}
protected function merge(?ClassMetadataInterface $a, ?ClassMetadataInterface $b): ?ClassMetadataInterface
{
if (!$a && !$b) {
return null;
} elseif (!$a) {
return $b;
} elseif (!$b) {
return $a;
}
foreach ($b->getProperties() as $name => $propertyMetadata) {
if (!$a->hasProperty($name)) {
$a->addProperty($propertyMetadata);
}
}
foreach ($b->getResources() as $resource) {
$a->addResource($resource);
}
return $a;
}
}
<file_sep><?php
namespace Pucene\Tests\Components\Metadata\Unit;
use PHPUnit\Framework\TestCase;
use Pucene\Components\Metadata\Cache\CacheResource;
use Pucene\Components\Metadata\ClassMetadataInterface;
use Pucene\Components\Metadata\Driver\DriverInterface;
use Pucene\Components\Metadata\MetadataFactory;
use Pucene\Components\Metadata\PropertyMetadataInterface;
class MetadataFactoryTest extends TestCase
{
/**
* @var DriverInterface
*/
private $driver;
/**
* @var MetadataFactory
*/
private $metadataFactory;
protected function setUp()
{
$this->driver = $this->prophesize(DriverInterface::class);
$this->metadataFactory = new MetadataFactory($this->driver->reveal());
}
public function testGetMetadataForClass()
{
$metadata = $this->prophesize(ClassMetadataInterface::class);
$this->driver->loadMetadataForClass(new \ReflectionClass(A::class))->willReturn($metadata->reveal());
$result = $this->metadataFactory->getMetadataForClass(A::class);
$this->assertEquals($metadata->reveal(), $result);
}
public function testGetMetadataForClassWithHierarchy()
{
$metadataA = $this->prophesize(ClassMetadataInterface::class);
$this->driver->loadMetadataForClass(new \ReflectionClass(A::class))->willReturn($metadataA->reveal());
$this->driver->loadMetadataForClass(new \ReflectionClass(B::class))->willReturn(null);
$propertyA = $this->prophesize(PropertyMetadataInterface::class);
$metadataA->getProperties()->willReturn(['propertyA' => $propertyA->reveal()]);
$metadataC = $this->prophesize(ClassMetadataInterface::class);
$this->driver->loadMetadataForClass(new \ReflectionClass(C::class))->willReturn($metadataC->reveal());
$propertyC = $this->prophesize(PropertyMetadataInterface::class);
$propertyC->getName()->willReturn('propertyC');
$metadataC->getProperties()->willReturn(['propertyC' => $propertyC->reveal()]);
$metadataA->hasProperty('propertyC')->shouldBeCalled();
$metadataA->addProperty($propertyC->reveal())->shouldBeCalled();
$resource = $this->prophesize(CacheResource::class);
$metadataC->getResources()->willReturn([$resource->reveal()]);
$metadataA->addResource($resource->reveal())->shouldBeCalled();
$result = $this->metadataFactory->getMetadataForClass(C::class);
$this->assertEquals($metadataA->reveal(), $result);
}
}
class A
{
public $propertyA;
}
class B extends A
{
}
class C extends B
{
public $propertyC;
}
<file_sep><?php
namespace Pucene\Tests\Components\Metadata\Unit\Driver;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Pucene\Components\Metadata\ClassMetadata;
use Pucene\Components\Metadata\Driver\DriverChain;
use Pucene\Components\Metadata\Driver\DriverInterface;
use Pucene\Tests\Components\Metadata\Unit\A;
use Pucene\Tests\Components\Metadata\Unit\B;
class DriverChainTest extends TestCase
{
public function testLoadMetadataForClass()
{
$driverA = $this->prophesize(DriverInterface::class);
$driverB = $this->prophesize(DriverInterface::class);
$metadata = $this->prophesize(ClassMetadata::class);
$driverA->loadMetadataForClass(new \ReflectionClass(A::class))->willReturn($metadata->reveal());
$driverB->loadMetadataForClass(Argument::any())->shouldNotBeCalled($metadata->reveal());
$chain = new DriverChain([$driverA->reveal(), $driverB->reveal()]);
$result = $chain->loadMetadataForClass(new \ReflectionClass(A::class));
$this->assertEquals($metadata->reveal(), $result);
}
public function testGetAllClassNames()
{
$driverA = $this->prophesize(DriverInterface::class);
$driverB = $this->prophesize(DriverInterface::class);
$driverA->getAllClassNames()->willReturn([A::class]);
$driverB->getAllClassNames()->willReturn([B::class]);
$chain = new DriverChain([$driverA->reveal(), $driverB->reveal()]);
$result = $chain->getAllClassNames();
$this->assertEquals([A::class, B::class], $result);
}
}
<file_sep><?php
namespace Pucene\Components\Metadata\Cache;
use Psr\SimpleCache\CacheInterface as PsrCache;
use Pucene\Components\Metadata\ClassMetadata;
use Pucene\Components\Metadata\ClassMetadataInterface;
class Cache implements CacheInterface
{
/**
* @var PsrCache
*/
private $cache;
public function __construct(PsrCache $cache)
{
$this->cache = $cache;
}
public function fetch(string $className): ?ClassMetadataInterface
{
if (!$this->cache->has($className)) {
return null;
}
/** @var ClassMetadata $metadata */
$metadata = unserialize($this->cache->get($className));
foreach ($metadata->getResources() as $resource) {
if (!$resource->isFresh()) {
return null;
}
}
return $metadata;
}
public function save(string $className, ClassMetadataInterface $metadata): ClassMetadataInterface
{
$this->cache->set($className, serialize($metadata));
return $metadata;
}
}
<file_sep><?php
namespace Pucene\Components\Metadata;
use Pucene\Components\Metadata\Cache\CacheInterface;
use Pucene\Components\Metadata\Driver\DriverInterface;
class CachableMetadataFactory extends MetadataFactory
{
/**
* @var CacheInterface
*/
private $cache;
/**
* @var array
*/
private $loadedMetadata = [];
public function __construct(CacheInterface $cache, DriverInterface $driver)
{
parent::__construct($driver);
$this->cache = $cache;
}
public function getMetadataForClass(string $className): ?ClassMetadataInterface
{
if (array_key_exists($className, $this->loadedMetadata)) {
return $this->loadedMetadata[$className];
}
return $this->loadedMetadata[$className] = parent::getMetadataForClass($className);
}
protected function loadClassMetadata(\ReflectionClass $class): ?ClassMetadataInterface
{
$metadata = $this->cache->fetch($class->getName());
if ($metadata) {
return $metadata;
}
$metadata = parent::loadClassMetadata($class);
if ($metadata) {
$this->cache->save($class->getName(), $metadata);
}
return $metadata;
}
}
<file_sep><?php
namespace Pucene\Tests\Components\ODM\Functional\Metadata\Driver;
use Doctrine\Common\Annotations\AnnotationReader;
use PHPUnit\Framework\TestCase;
use Pucene\Components\Metadata\Driver\FileLocator;
use Pucene\Components\ODM\Metadata\ClassMetadata;
use Pucene\Components\ODM\Metadata\Driver\AnnotationDriver;
use Pucene\Tests\AppBundle\Document\ArticleDocument;
class AnnotationDriverTest extends TestCase
{
public function testLoadMetadataForClass()
{
$locator = new FileLocator(
['Pucene\\Tests\\AppBundle\\Document' => __DIR__ . '/../../../../AppBundle/Document']
);
$reader = new AnnotationReader();
$driver = new AnnotationDriver($reader, $locator);
/** @var ClassMetadata $metadata */
$metadata = $driver->loadMetadataForClass(new \ReflectionClass(ArticleDocument::class));
$this->assertEquals(ArticleDocument::class, $metadata->getName());
$this->assertEquals('article', $metadata->getType());
$titleProperty = $metadata->getProperty('title');
$this->assertEquals('title', $titleProperty->getName());
$this->assertEquals('string', $titleProperty->getType());
$this->assertEquals($metadata->getIdProperty()->getName(), 'id');
}
public function testGetAllClassNames()
{
$locator = new FileLocator(
['Pucene\\Tests\\AppBundle\\Document' => __DIR__ . '/../../../../AppBundle/Document']
);
$reader = new AnnotationReader();
$driver = new AnnotationDriver($reader, $locator);
$this->assertEquals([ArticleDocument::class], $driver->getAllClassNames());
}
}
<file_sep><?php
namespace Pucene\Tests\Components\ODM\Functional\Repository;
use PHPUnit\Framework\TestCase;
use Pucene\Component\Client\IndexInterface;
use Pucene\Component\QueryBuilder\Search;
use Pucene\Components\ODM\Metadata\ClassMetadata;
use Pucene\Components\ODM\Metadata\IdPropertyMetadata;
use Pucene\Components\ODM\Metadata\PropertyMetadata;
use Pucene\Components\ODM\ObjectManagerInterface;
use Pucene\Components\ODM\Repository\ObjectRepository;
use Pucene\Components\ODM\Search\DocumentIterator;
use Pucene\Tests\AppBundle\Document\ArticleDocument;
class ObjectRepositoryTest extends TestCase
{
public function testIndex()
{
$index = $this->prophesize(IndexInterface::class);
$objectManager = $this->prophesize(ObjectManagerInterface::class);
$objectManager->getIndex()->willReturn($index->reveal());
$repository = new ObjectRepository($this->getClassMetadata(), $objectManager->reveal());
$article = new ArticleDocument('Pucene is awesome', '123-123-123');
$index->index(['title' => 'Pucene is awesome'], 'article', '123-123-123')->shouldBeCalled()->willReturn(
[
'_id' => '123-123-123',
'_type' => 'article',
'_index' => 'test',
'_score' => 1,
'_source' => [
'title' => 'Pucene is awesome',
],
]
);
$repository->index($article);
}
public function testIndexNoId()
{
$index = $this->prophesize(IndexInterface::class);
$objectManager = $this->prophesize(ObjectManagerInterface::class);
$objectManager->getIndex()->willReturn($index->reveal());
$repository = new ObjectRepository($this->getClassMetadata(), $objectManager->reveal());
$article = new ArticleDocument('Pucene is awesome', null);
$index->index(['title' => 'Pucene is awesome'], 'article', null)->shouldBeCalled()->willReturn(
[
'_id' => '123-123-123',
'_type' => 'article',
'_index' => 'test',
'_score' => 1,
'_source' => [
'title' => 'Pucene is awesome',
],
]
);
$repository->index($article);
$this->assertEquals('123-123-123', $article->getId());
}
public function testFind()
{
$index = $this->prophesize(IndexInterface::class);
$objectManager = $this->prophesize(ObjectManagerInterface::class);
$objectManager->getIndex()->willReturn($index->reveal());
$index->get('article', '123-123-123')->willReturn(
[
'_id' => '123-123-123',
'_type' => 'article',
'_index' => 'test',
'_score' => 1,
'_source' => [
'title' => 'Pucene is awesome',
],
]
);
$repository = new ObjectRepository($this->getClassMetadata(), $objectManager->reveal());
$object = $repository->find('123-123-123');
$this->assertNotNull($object);
$this->assertInstanceOf(ArticleDocument::class, $object);
$this->assertEquals('Pucene is awesome', $object->getTitle());
}
public function testCreateSearch()
{
$objectManager = $this->prophesize(ObjectManagerInterface::class);
$search = $this->prophesize(Search::class);
$objectManager->createSearch()->willReturn($search->reveal());
$repository = new ObjectRepository($this->getClassMetadata(), $objectManager->reveal());
$this->assertEquals($search->reveal(), $repository->createSearch());
}
public function testExecute()
{
$index = $this->prophesize(IndexInterface::class);
$objectManager = $this->prophesize(ObjectManagerInterface::class);
$objectManager->getIndex()->willReturn($index->reveal());
$repository = new ObjectRepository($this->getClassMetadata(), $objectManager->reveal());
$search = new Search();
$index->search($search, 'article')->willReturn(
[
'hits' => [
'total' => 10,
'hits' => [
[
'_id' => '123-123-123',
'_type' => 'article',
'_index' => 'test',
'_score' => 1,
'_source' => [
'title' => 'Pucene is awesome',
],
],
[
'_id' => '123-456-789',
'_type' => 'article',
'_index' => 'test',
'_score' => 1,
'_source' => [
'title' => 'Pucene is really awesome',
],
],
],
],
]
);
$result = $repository->execute($search);
$this->assertInstanceOf(DocumentIterator::class, $result);
$this->assertEquals(2, $result->count());
$this->assertEquals(2, count($result));
$this->assertEquals(10, $result->total());
$result = iterator_to_array($result);
$this->assertInstanceOf(ArticleDocument::class, $result[0]);
$this->assertEquals('123-123-123', $result[0]->getId());
$this->assertEquals('Pucene is awesome', $result[0]->getTitle());
$this->assertInstanceOf(ArticleDocument::class, $result[1]);
$this->assertEquals('123-456-789', $result[1]->getId());
$this->assertEquals('Pucene is really awesome', $result[1]->getTitle());
}
protected function getClassMetadata(): ClassMetadata
{
$metadata = new ClassMetadata('article', ArticleDocument::class);
$metadata->addProperty(new PropertyMetadata('string', $metadata, 'title'));
$metadata->setIdProperty(new IdPropertyMetadata($metadata, 'id'));
return $metadata;
}
}
<file_sep><?php
namespace Pucene\Tests\Components\Metadata\Unit;
use PHPUnit\Framework\TestCase;
use Pucene\Components\Metadata\CachableMetadataFactory;
use Pucene\Components\Metadata\Cache\CacheInterface;
use Pucene\Components\Metadata\ClassMetadataInterface;
use Pucene\Components\Metadata\Driver\DriverInterface;
use Pucene\Components\Metadata\MetadataFactory;
class CachableMetadataFactoryTest extends TestCase
{
/**
* @var CacheInterface
*/
private $cache;
/**
* @var DriverInterface
*/
private $driver;
/**
* @var MetadataFactory
*/
private $metadataFactory;
protected function setUp()
{
$this->cache = $this->prophesize(CacheInterface::class);
$this->driver = $this->prophesize(DriverInterface::class);
$this->metadataFactory = new CachableMetadataFactory($this->cache->reveal(), $this->driver->reveal());
}
public function testGetMetadataForClass()
{
$metadata = $this->prophesize(ClassMetadataInterface::class);
$this->driver->loadMetadataForClass(new \ReflectionClass(A::class))->willReturn($metadata->reveal());
$this->cache->fetch(A::class)->willReturn(null);
$this->cache->save(A::class, $metadata->reveal())->shouldBeCalled();
$result = $this->metadataFactory->getMetadataForClass(A::class);
$this->assertEquals($metadata->reveal(), $result);
}
public function testGetMetadataForClassContains()
{
$metadata = $this->prophesize(ClassMetadataInterface::class);
$this->driver->loadMetadataForClass(new \ReflectionClass(A::class))->shouldNotBeCalled();
$this->cache->fetch(A::class)->willReturn($metadata->reveal());
$this->cache->save(A::class, $metadata->reveal())->shouldNotBeCalled();
$result = $this->metadataFactory->getMetadataForClass(A::class);
$this->assertEquals($metadata->reveal(), $result);
}
public function testGetMetadataForClassWithHierarchy()
{
$metadataA = $this->prophesize(ClassMetadataInterface::class);
$metadataA->getProperties()->willReturn([]);
$metadataA->getResources()->willReturn([]);
$this->driver->loadMetadataForClass(new \ReflectionClass(A::class))->willReturn($metadataA->reveal());
$metadataB = $this->prophesize(ClassMetadataInterface::class);
$metadataB->getProperties()->willReturn([]);
$metadataB->getResources()->willReturn([]);
$this->driver->loadMetadataForClass(new \ReflectionClass(B::class))->shouldNotBeCalled();
$this->cache->fetch(A::class)->willReturn(null);
$this->cache->save(A::class, $metadataA->reveal())->shouldBeCalled();
$this->cache->fetch(B::class)->willReturn($metadataB->reveal());
$result = $this->metadataFactory->getMetadataForClass(B::class);
$this->assertEquals($metadataA->reveal(), $result);
}
}
<file_sep><?php
namespace Pucene\Components\Metadata\Driver;
class FileLocator implements FileLocatorInterface
{
/**
* @var array
*/
private $dirs;
/**
* @param string[] $directories
*/
public function __construct(array $directories)
{
$this->dirs = $directories;
}
public function findFileForClass(\ReflectionClass $class, string $extension): ?string
{
foreach ($this->dirs as $prefix => $dir) {
if ('' !== $prefix && 0 !== strpos($class->getNamespaceName(), $prefix)) {
continue;
}
$len = '' === $prefix ? 0 : strlen($prefix) + 1;
$path = $dir . '/' . str_replace('\\', '.', substr($class->name, $len)) . '.' . $extension;
if (file_exists($path)) {
return $path;
}
}
return null;
}
public function findAllClasses(string $extension): array
{
$classes = [];
foreach ($this->dirs as $prefix => $dir) {
$directoryIterator = new \RecursiveDirectoryIterator($dir);
$iterator = new \RecursiveIteratorIterator($directoryIterator, \RecursiveIteratorIterator::LEAVES_ONLY);
$namespacePrefix = '' !== $prefix ? $prefix . '\\' : '';
foreach ($iterator as $file) {
$fileName = $file->getBasename('.' . $extension);
if ($fileName === $file->getBasename()) {
continue;
}
$classes[] = $namespacePrefix . str_replace('.', '\\', $fileName);
}
}
return $classes;
}
}
<file_sep><?php
namespace ODM\Unit\Converter;
use PHPUnit\Framework\TestCase;
use Pucene\Components\Metadata\ClassMetadataInterface;
use Pucene\Components\Metadata\PropertyMetadataInterface;
use Pucene\Components\ODM\Converter\ObjectToArrayConverter;
use Pucene\Tests\AppBundle\Document\ArticleDocument;
class ObjectToArrayConverterTest extends TestCase
{
public function testConvert()
{
$metadata = $this->prophesize(ClassMetadataInterface::class);
$metadata->getName(ArticleDocument::class);
$property = $this->prophesize(PropertyMetadataInterface::class);
$metadata->getProperties()->willReturn([$property->reveal()]);
$object = $this->prophesize(ArticleDocument::class);
$property->getName()->willReturn('title');
$property->getValue($object->reveal())->willReturn('test')->shouldBeCalled();
$converter = new ObjectToArrayConverter();
$this->assertEquals(['title' => 'test'], $converter->convert($object->reveal(), $metadata->reveal()));
}
}
<file_sep><?php
namespace Pucene\Tests\Components\Metadata\Unit;
use PHPUnit\Framework\TestCase;
use Pucene\Components\Metadata\ClassMetadata;
use Pucene\Components\Metadata\PropertyMetadata;
class PropertyMetadataTest extends TestCase
{
public function testGetClass()
{
$class = $this->prophesize(ClassMetadata::class);
$class->getName()->willReturn(A::class);
$metadata = new PropertyMetadata($class->reveal(), 'propertyA');
$this->assertEquals($class->reveal(), $metadata->getClass());
}
public function testGetName()
{
$class = $this->prophesize(ClassMetadata::class);
$class->getName()->willReturn(A::class);
$metadata = new PropertyMetadata($class->reveal(), 'propertyA');
$this->assertEquals('propertyA', $metadata->getName());
}
public function testGetValue()
{
$class = $this->prophesize(ClassMetadata::class);
$class->getName()->willReturn(A::class);
$metadata = new PropertyMetadata($class->reveal(), 'propertyA');
$aObject = new A();
$aObject->propertyA = 'test';
$this->assertEquals('test', $metadata->getValue($aObject));
}
public function testSetValue()
{
$class = $this->prophesize(ClassMetadata::class);
$class->getName()->willReturn(A::class);
$metadata = new PropertyMetadata($class->reveal(), 'propertyA');
$aObject = new A();
$metadata->setValue($aObject, 'test');
$this->assertEquals('test', $aObject->propertyA);
}
}
<file_sep><?php
namespace Pucene\Components\ODM;
use Pucene\Component\Client\ClientInterface;
use Pucene\Component\Client\IndexInterface;
use Pucene\Component\QueryBuilder\Search;
use Pucene\Components\Metadata\MetadataFactoryInterface;
use Pucene\Components\ODM\Metadata\ClassMetadata;
use Pucene\Components\ODM\Repository\ObjectRepository;
use Pucene\Components\ODM\Repository\ObjectRepositoryInterface;
class ObjectManager implements ObjectManagerInterface
{
/**
* @var ClientInterface
*/
private $client;
/**
* @var MetadataFactoryInterface
*/
private $metadataFactory;
/**
* @var string
*/
private $indexName;
public function __construct(ClientInterface $client, MetadataFactoryInterface $metadataFactory, string $indexName)
{
$this->client = $client;
$this->metadataFactory = $metadataFactory;
$this->indexName = $indexName;
}
public function create(): void
{
if ($this->client->exists($this->indexName)) {
return;
}
$classNames = $this->metadataFactory->getAllClassNames();
$mappings = [];
foreach ($classNames as $className) {
/** @var ClassMetadata $metadata */
$metadata = $this->metadataFactory->getMetadataForClass($className);
$mappings[$metadata->getType()] = $metadata->getMapping();
}
$this->client->create($this->indexName, ['mappings' => $mappings]);
}
public function delete(): void
{
if (!$this->client->exists($this->indexName)) {
return;
}
$this->client->delete($this->indexName);
}
public function createRepository(string $documentClass): ObjectRepositoryInterface
{
$metadata = $this->metadataFactory->getMetadataForClass($documentClass);
return new ObjectRepository($metadata, $this);
}
public function createSearch(): Search
{
return new Search();
}
public function getIndex(): IndexInterface
{
if (!$this->client->exists($this->indexName)) {
$this->create();
}
return $this->client->get($this->indexName);
}
}
<file_sep><?php
namespace Pucene\Components\Metadata;
interface PropertyMetadataInterface
{
public function getClass(): ClassMetadataInterface;
public function getName(): string;
/**
* @param mixed $object
*
* @return mixed
*/
public function getValue($object);
/**
* @param mixed $object
* @param mixed $value
*/
public function setValue($object, $value): void;
}
<file_sep><?php
namespace Pucene\Components\Metadata\Cache;
use Pucene\Components\Metadata\ClassMetadataInterface;
interface CacheInterface
{
public function fetch(string $className): ?ClassMetadataInterface;
public function save(string $className, ClassMetadataInterface $metadata): ClassMetadataInterface;
}
<file_sep><?php
namespace Pucene\Components\ODM\Metadata\Driver;
use Doctrine\Common\Annotations\Reader;
use Pucene\Components\Metadata\ClassMetadataInterface;
use Pucene\Components\Metadata\Driver\FileDriver;
use Pucene\Components\Metadata\Driver\FileLocatorInterface;
use Pucene\Components\Metadata\PropertyMetadataInterface;
use Pucene\Components\ODM\Annotation\Document;
use Pucene\Components\ODM\Annotation\Id;
use Pucene\Components\ODM\Annotation\Property;
use Pucene\Components\ODM\Metadata\ClassMetadata;
use Pucene\Components\ODM\Metadata\IdPropertyMetadata;
use Pucene\Components\ODM\Metadata\PropertyMetadata;
class AnnotationDriver extends FileDriver
{
/**
* @var Reader
*/
private $reader;
public function __construct(Reader $reader, FileLocatorInterface $locator)
{
parent::__construct($locator);
$this->reader = $reader;
}
protected function loadMetadataFromFile(\ReflectionClass $class, string $file): ?ClassMetadataInterface
{
$name = $class->name;
$type = null;
foreach ($this->reader->getClassAnnotations($class) as $annotation) {
if ($annotation instanceof Document) {
$type = $annotation->type;
}
}
$metadata = new ClassMetadata($type, $class->getName());
foreach ($class->getProperties() as $property) {
if ($property->class !== $name || (isset($property->info) && $property->info['class'] !== $name)) {
continue;
}
$property = $this->loadPropertyMetadata($property, $metadata);
if ($property instanceof PropertyMetadata) {
$metadata->addProperty($property);
continue;
}
$metadata->setIdProperty($property);
}
return $metadata;
}
protected function getExtension(): string
{
return 'php';
}
private function loadPropertyMetadata(
\ReflectionProperty $property,
ClassMetadata $metadata
): PropertyMetadataInterface {
$type = null;
foreach ($this->reader->getPropertyAnnotations($property) as $annotation) {
if ($annotation instanceof Property) {
$type = $annotation->type;
} elseif ($annotation instanceof Id) {
return new IdPropertyMetadata($metadata, $property->getName());
}
}
return new PropertyMetadata($type, $metadata, $property->getName());
}
}
<file_sep><?php
namespace Pucene\Components\Metadata\Driver;
use Pucene\Components\Metadata\ClassMetadataInterface;
final class DriverChain implements DriverInterface
{
/**
* @var DriverInterface[]
*/
private $drivers;
/**
* @param DriverInterface[] $drivers
*/
public function __construct(array $drivers = [])
{
$this->drivers = $drivers;
}
public function loadMetadataForClass(\ReflectionClass $class): ?ClassMetadataInterface
{
foreach ($this->drivers as $driver) {
if (null !== $metadata = $driver->loadMetadataForClass($class)) {
return $metadata;
}
}
return null;
}
public function getAllClassNames(): array
{
$classes = [];
foreach ($this->drivers as $driver) {
$driverClasses = $driver->getAllClassNames();
if (!empty($driverClasses)) {
$classes = array_merge($classes, $driverClasses);
}
}
return $classes;
}
}
<file_sep><?php
namespace Pucene\Components\Metadata\Driver;
use Pucene\Components\Metadata\ClassMetadataInterface;
interface DriverInterface
{
public function loadMetadataForClass(\ReflectionClass $class): ?ClassMetadataInterface;
/**
* @return string[]
*/
public function getAllClassNames(): array;
}
<file_sep><?php
namespace Pucene\Components\ODM\Metadata;
use Pucene\Components\Metadata\PropertyMetadata as BaseMetadata;
class IdPropertyMetadata extends BaseMetadata
{
}
<file_sep><?php
namespace Pucene\Components\ODM\Repository;
use Pucene\Component\QueryBuilder\Search;
use Pucene\Components\ODM\Converter\ArrayToObjectConverter;
use Pucene\Components\ODM\Converter\ObjectToArrayConverter;
use Pucene\Components\ODM\Metadata\ClassMetadata;
use Pucene\Components\ODM\ObjectManagerInterface;
use Pucene\Components\ODM\Search\DocumentIterator;
class ObjectRepository implements ObjectRepositoryInterface
{
/**
* @var ClassMetadata
*/
private $metadata;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
public function __construct(ClassMetadata $metadata, ObjectManagerInterface $objectManager)
{
$this->metadata = $metadata;
$this->objectManager = $objectManager;
}
public function createSearch(): Search
{
return $this->objectManager->createSearch();
}
public function execute(Search $search): DocumentIterator
{
$result = $this->objectManager->getIndex()->search($search, $this->metadata->getType());
return new DocumentIterator($result, $this->metadata, new ArrayToObjectConverter());
}
public function find(string $id)
{
$result = $this->objectManager->getIndex()->get($this->metadata->getType(), $id);
$converter = new ArrayToObjectConverter();
return $converter->convert($result['_source'], $this->metadata);
}
public function index($object): void
{
$objectToArrayConverter = new ObjectToArrayConverter();
$result = $this->objectManager->getIndex()->index(
$objectToArrayConverter->convert($object, $this->metadata),
$this->metadata->getType(),
$this->metadata->getIdProperty()->getValue($object)
);
$this->metadata->getIdProperty()->setValue($object, $result['_id']);
}
}
<file_sep><?php
namespace Pucene\Components\Metadata\Cache;
abstract class CacheResource
{
/**
* @var \DateTimeImmutable
*/
protected $createdAt;
public function __construct(\DateTimeImmutable $createdAt = null)
{
$this->createdAt = $createdAt ?: new \DateTimeImmutable();
}
abstract public function isFresh(): bool;
}
<file_sep><?php
namespace Pucene\Components\ODM\Repository;
use Pucene\Component\QueryBuilder\Search;
use Pucene\Components\ODM\Search\DocumentIterator;
interface ObjectRepositoryInterface
{
public function createSearch(): Search;
public function execute(Search $search): DocumentIterator;
public function find(string $id);
public function index($object): void;
}
<file_sep><?php
namespace Pucene\Tests\Components\Metadata\Unit\Cache;
use PHPUnit\Framework\TestCase;
use Psr\SimpleCache\CacheInterface;
use Pucene\Components\Metadata\Cache\Cache;
use Pucene\Components\Metadata\Cache\CacheResource;
use Pucene\Components\Metadata\ClassMetadata;
use Pucene\Tests\Components\Metadata\Unit\A;
class CacheTest extends TestCase
{
public function testFetch()
{
$resource = $this->prophesize(CacheResource::class);
$resource->isFresh()->willReturn(true);
$metadata = new ClassMetadata(A::class);
$metadata->addResource($resource->reveal());
$psrCache = $this->prophesize(CacheInterface::class);
$psrCache->has(A::class)->willReturn(true);
$psrCache->get(A::class)->willReturn(serialize($metadata));
$cache = new Cache($psrCache->reveal());
$result = $cache->fetch(A::class);
$this->assertEquals($metadata->getName(), $result->getName());
}
public function testFetchNotFresh()
{
$resource = $this->prophesize(CacheResource::class);
$resource->isFresh()->willReturn(false);
$metadata = new ClassMetadata(A::class);
$metadata->addResource($resource->reveal());
$psrCache = $this->prophesize(CacheInterface::class);
$psrCache->has(A::class)->willReturn(true);
$psrCache->get(A::class)->willReturn(serialize($metadata));
$cache = new Cache($psrCache->reveal());
$result = $cache->fetch(A::class);
$this->assertNull($result);
}
public function testFetchNotExists()
{
$psrCache = $this->prophesize(CacheInterface::class);
$psrCache->has(A::class)->willReturn(false);
$cache = new Cache($psrCache->reveal());
$result = $cache->fetch(A::class);
$this->assertNull($result);
}
public function testSave()
{
$metadata = new ClassMetadata(A::class);
$psrCache = $this->prophesize(CacheInterface::class);
$psrCache->set(A::class, serialize($metadata));
$cache = new Cache($psrCache->reveal());
$result = $cache->save(A::class, $metadata);
$this->assertEquals($metadata, $result);
}
}
<file_sep># Pucene ODM
[](https://scrutinizer-ci.com/g/pucene/odm)
[](https://scrutinizer-ci.com/g/odm/pucene/)
[](https://travis-ci.org/pucene/odm)
[](https://circleci.com/gh/pucene/odm/tree/master)
[](https://styleci.io/repos/124761850)
Object-Document Mapping for pucene.
<file_sep><?php
namespace Pucene\Components\Metadata\Cache;
class FileCacheResource extends CacheResource
{
/**
* @var string
*/
private $path;
public function __construct(string $path, \DateTimeImmutable $createdAt = null)
{
parent::__construct($createdAt);
$this->path = $path;
}
public function isFresh(): bool
{
if (!file_exists($this->path)) {
return false;
}
return $this->createdAt->getTimestamp() < filemtime($this->path);
}
}
<file_sep><?php
namespace Pucene\Components\ODM\Metadata;
use Pucene\Components\Metadata\ClassMetadata as BaseMetadata;
class ClassMetadata extends BaseMetadata
{
/**
* @var string
*/
private $type;
/**
* @var IdPropertyMetadata
*/
private $idProperty;
public function __construct(string $type, string $name, array $properties = [], array $resources = [])
{
parent::__construct($name, $properties, $resources);
$this->type = $type;
}
public function getType(): string
{
return $this->type;
}
public function setIdProperty(IdPropertyMetadata $property): void
{
$this->idProperty = $property;
}
public function getIdProperty(): IdPropertyMetadata
{
return $this->idProperty;
}
public function getMapping(): array
{
$result = [];
foreach ($this->getProperties() as $property) {
$result[$property->getName()] = ['type' => $property->getType()];
}
return $result;
}
}
<file_sep><?php
namespace Pucene\Components\Metadata\Driver;
interface FileLocatorInterface
{
public function findFileForClass(\ReflectionClass $class, string $extension): ?string;
/**
* @return string[]
*/
public function findAllClasses(string $extension): array;
}
<file_sep><?php
namespace Pucene\Components\ODM\Search;
use Pucene\Components\ODM\Converter\ArrayToObjectConverter;
use Pucene\Components\ODM\Metadata\ClassMetadata;
class DocumentIterator extends \IteratorIterator implements \Countable
{
/**
* @var ClassMetadata
*/
private $metadata;
/**
* @var ArrayToObjectConverter
*/
private $converter;
/**
* @var int
*/
private $count;
/**
* @var int
*/
private $total;
public function __construct(array $data, ClassMetadata $metadata, ArrayToObjectConverter $converter)
{
parent::__construct(new \ArrayObject($data['hits']['hits']));
$this->metadata = $metadata;
$this->converter = $converter;
$this->count = count($data['hits']['hits']);
$this->total = $data['hits']['total'];
}
public function current()
{
$data = parent::current();
$document = $this->converter->convert($data['_source'], $this->metadata);
$this->metadata->getIdProperty()->setValue($document, $data['_id']);
return $document;
}
public function count()
{
return $this->count;
}
public function total()
{
return $this->total;
}
}
<file_sep><?php
namespace Pucene\Components\ODM;
use Pucene\Component\Client\IndexInterface;
use Pucene\Component\QueryBuilder\Search;
use Pucene\Components\ODM\Repository\ObjectRepositoryInterface;
interface ObjectManagerInterface
{
public function create(): void;
public function delete(): void;
public function createRepository(string $documentClass): ObjectRepositoryInterface;
public function createSearch(): Search;
public function getIndex(): IndexInterface;
}
<file_sep><?php
namespace Pucene\Tests\Components\Metadata\Unit\Cache;
use PHPUnit\Framework\TestCase;
use Pucene\Components\Metadata\Cache\FileCacheResource;
class FileCacheResourceTest extends TestCase
{
public function testIsFresh()
{
$path = __DIR__ . '/FileCacheResourceTest.php';
$resource = new FileCacheResource($path, new \DateTimeImmutable('@' . (filemtime($path) + 3)));
$this->assertFalse($resource->isFresh());
}
public function testIsNotFresh()
{
$path = __DIR__ . '/FileCacheResourceTest.php';
$resource = new FileCacheResource($path, new \DateTimeImmutable('@' . (filemtime($path) - 3)));
$this->assertTrue($resource->isFresh());
}
}
<file_sep><?php
namespace Pucene\Tests\Components\Metadata\Unit;
use PHPUnit\Framework\TestCase;
use Pucene\Components\Metadata\Cache\CacheResource;
use Pucene\Components\Metadata\ClassMetadata;
use Pucene\Components\Metadata\PropertyMetadataInterface;
class ClassMetadataTest extends TestCase
{
public function testGetName()
{
$metadata = new ClassMetadata(self::class);
$this->assertEquals(self::class, $metadata->getName());
}
public function testGetProperty()
{
$property = $this->prophesize(PropertyMetadataInterface::class);
$metadata = new ClassMetadata(self::class, ['test' => $property->reveal()]);
$this->assertEquals($property->reveal(), $metadata->getProperty('test'));
}
public function testGetProperties()
{
$property = $this->prophesize(PropertyMetadataInterface::class);
$metadata = new ClassMetadata(self::class, ['test' => $property->reveal()]);
$this->assertEquals(['test' => $property->reveal()], $metadata->getProperties());
}
public function testAddProperty()
{
$metadata = new ClassMetadata(self::class);
$property = $this->prophesize(PropertyMetadataInterface::class);
$property->getName()->willReturn('test');
$metadata->addProperty($property->reveal());
$this->assertEquals(['test' => $property->reveal()], $metadata->getProperties());
}
public function testGetResources()
{
$resource = $this->prophesize(CacheResource::class);
$metadata = new ClassMetadata(self::class, [], [$resource->reveal()]);
$this->assertEquals([$resource->reveal()], $metadata->getResources());
}
public function testAddResource()
{
$metadata = new ClassMetadata(self::class);
$resource = $this->prophesize(CacheResource::class);
$metadata->addResource($resource->reveal());
$this->assertEquals([$resource->reveal()], $metadata->getResources());
}
}
<file_sep><?php
namespace Pucene\Tests\Components\ODM\Unit\Metadata\Driver;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Pucene\Components\Metadata\ClassMetadataInterface;
use Pucene\Components\Metadata\PropertyMetadataInterface;
use Pucene\Components\ODM\Converter\ArrayToObjectConverter;
use Pucene\Tests\AppBundle\Document\ArticleDocument;
class ArrayToObjectConverterTest extends TestCase
{
public function testConvert()
{
$converter = new ArrayToObjectConverter();
$metadata = $this->prophesize(ClassMetadataInterface::class);
$metadata->getName(ArticleDocument::class);
$property = $this->prophesize(PropertyMetadataInterface::class);
$metadata->getProperties()->willReturn([$property->reveal()]);
$object = $this->prophesize(ArticleDocument::class);
$metadata->createInstance()->willReturn($object->reveal())->shouldBeCalled();
$property->getName()->willReturn('title');
$property->setValue($object->reveal(), 'test')->shouldBeCalled();
$result = $converter->convert(['title' => 'test'], $metadata->reveal());
$this->assertEquals($object->reveal(), $result);
}
public function testConvertNoDataForProperty()
{
$converter = new ArrayToObjectConverter();
$metadata = $this->prophesize(ClassMetadataInterface::class);
$metadata->getName(ArticleDocument::class);
$property = $this->prophesize(PropertyMetadataInterface::class);
$metadata->getProperties()->willReturn([$property->reveal()]);
$object = $this->prophesize(ArticleDocument::class);
$metadata->createInstance()->willReturn($object->reveal())->shouldBeCalled();
$property->getName()->willReturn('title');
$property->setValue(Argument::cetera())->shouldNotBeCalled();
$result = $converter->convert([], $metadata->reveal());
$this->assertEquals($object->reveal(), $result);
}
}
<file_sep><?php
namespace Pucene\Components\ODM\Converter;
use Pucene\Components\Metadata\ClassMetadataInterface;
class ObjectToArrayConverter
{
/**
* @param mixed $object
*/
public function convert($object, ClassMetadataInterface $metadata): array
{
$data = [];
foreach ($metadata->getProperties() as $property) {
$data[$property->getName()] = $property->getValue($object);
}
return $data;
}
}
<file_sep><?php
namespace Pucene\Components\Metadata;
class PropertyMetadata implements PropertyMetadataInterface
{
/**
* @var ClassMetadataInterface
*/
private $class;
/**
* @var string
*/
private $name;
public function __construct(ClassMetadataInterface $class, string $name)
{
$this->class = $class;
$this->name = $name;
}
public function getClass(): ClassMetadataInterface
{
return $this->class;
}
public function getName(): string
{
return $this->name;
}
/**
* @param mixed $object
*
* @return mixed
*/
public function getValue($object)
{
return $this->getReflection()->getValue($object);
}
/**
* @param mixed $object
* @param mixed $value
*/
public function setValue($object, $value): void
{
$this->getReflection()->setValue($object, $value);
}
private function getReflection(): \ReflectionProperty
{
$reflection = new \ReflectionProperty($this->class->getName(), $this->name);
$reflection->setAccessible(true);
return $reflection;
}
}
<file_sep><?php
namespace Pucene\Components\ODM\Annotation;
/**
* @Annotation
* @Target("PROPERTY")
*/
final class Id
{
}
<file_sep><?php
namespace Pucene\Components\ODM\Metadata;
use Pucene\Components\Metadata\ClassMetadataInterface;
use Pucene\Components\Metadata\PropertyMetadata as BaseMetadata;
class PropertyMetadata extends BaseMetadata
{
/**
* @var string
*/
private $type;
public function __construct(string $type, ClassMetadataInterface $class, string $name)
{
parent::__construct($class, $name);
$this->type = $type;
}
public function getType(): string
{
return $this->type;
}
}
<file_sep><?php
namespace Pucene\Tests\Components\ODM\Unit\Metadata\Driver;
use Doctrine\Common\Annotations\AnnotationReader;
use PHPUnit\Framework\TestCase;
use Pucene\Components\Metadata\Driver\FileLocatorInterface;
use Pucene\Components\ODM\Annotation\Document;
use Pucene\Components\ODM\Annotation\Property;
use Pucene\Components\ODM\Metadata\Driver\AnnotationDriver;
use Pucene\Tests\Components\Metadata\Unit\A;
class AnnotationDriverTest extends TestCase
{
public function testLoadMetadataForClass()
{
$class = new \ReflectionClass(A::class);
$locator = $this->prophesize(FileLocatorInterface::class);
$reader = $this->prophesize(AnnotationReader::class);
$locator->findFileForClass($class, 'php')->willReturn('A.php');
$document = new Document(['value' => 'article']);
$reader->getClassAnnotations($class)->willReturn([$document]);
$property = new Property(['value' => 'string']);
$reader->getPropertyAnnotations(new \ReflectionProperty(A::class, 'propertyA'))->willReturn([$property]);
$driver = new AnnotationDriver($reader->reveal(), $locator->reveal());
$metadata = $driver->loadMetadataForClass($class);
$this->assertEquals(A::class, $metadata->getName());
$this->assertEquals('article', $metadata->getType());
$result = $metadata->getProperty('propertyA');
$this->assertEquals('propertyA', $result->getName());
$this->assertEquals('string', $result->getType());
}
public function testGetAllClassNames()
{
$locator = $this->prophesize(FileLocatorInterface::class);
$reader = $this->prophesize(AnnotationReader::class);
$locator->findAllClasses('php')->willReturn([A::class]);
$driver = new AnnotationDriver($reader->reveal(), $locator->reveal());
$this->assertEquals([A::class], $driver->getAllClassNames());
}
}
<file_sep><?php
namespace Pucene\Components\ODM\Annotation;
/**
* @Annotation
* @Target("CLASS")
*/
final class Document
{
/**
* @var string
*/
public $type;
public function __construct(array $values)
{
if (!\is_string($values['value'])) {
throw new \RuntimeException('"value" must be a string.');
}
$this->type = $values['value'];
}
}
<file_sep><?php
namespace Pucene\Components\Metadata;
interface MetadataFactoryInterface
{
/**
* Returns the gathered metadata for the given class name.
*
* If the drivers return instances of MergeableClassMetadata, these will be
* merged prior to returning. Otherwise, all metadata for the inheritance
* hierarchy will be returned as ClassHierarchyMetadata unmerged.
*
* If no metadata is available, null is returned.
*/
public function getMetadataForClass(string $className): ?ClassMetadataInterface;
public function getAllClassNames(): array;
}
<file_sep><?php
namespace Pucene\Components\ODM\Converter;
use Pucene\Components\Metadata\ClassMetadataInterface;
class ArrayToObjectConverter
{
/**
* @return mixed
*/
public function convert(array $data, ClassMetadataInterface $metadata)
{
$object = $metadata->createInstance();
foreach ($metadata->getProperties() as $property) {
if (!array_key_exists($property->getName(), $data)) {
continue;
}
$property->setValue($object, $data[$property->getName()]);
}
return $object;
}
}
<file_sep><?php
namespace Pucene\Tests\Components\Metadata\Unit\Driver;
use PHPUnit\Framework\TestCase;
use Pucene\Components\Metadata\ClassMetadata;
use Pucene\Components\Metadata\Driver\FileDriver;
use Pucene\Components\Metadata\Driver\FileLocatorInterface;
use Pucene\Tests\Components\Metadata\Unit\A;
class FileDriverTest extends TestCase
{
public function testLoadMetadataForClass()
{
$fileLocator = $this->prophesize(FileLocatorInterface::class);
$fileLocator->findFileForClass(new \ReflectionClass(A::class), 'php')->willReturn('/A.php');
$metadata = $this->prophesize(ClassMetadata::class);
$driver = $this->getMockForAbstractClass(FileDriver::class, [$fileLocator->reveal()]);
$driver->expects($this->any())
->method('loadMetadataFromFile')
->with(new \ReflectionClass(A::class), '/A.php')
->willReturn($metadata->reveal());
$driver->expects($this->any())
->method('getExtension')
->willReturn('php');
$this->assertEquals($metadata->reveal(), $driver->loadMetadataForClass(new \ReflectionClass(A::class)));
}
public function testGetAllClassNames()
{
$fileLocator = $this->prophesize(FileLocatorInterface::class);
$fileLocator->findAllClasses('php')->willReturn([A::class]);
$driver = $this->getMockForAbstractClass(FileDriver::class, [$fileLocator->reveal()]);
$driver->expects($this->any())
->method('getExtension')
->willReturn('php');
$this->assertEquals([A::class], $driver->getAllClassNames());
}
}
<file_sep><?php
namespace Pucene\Tests\Components\ODM\Functional\Repository;
use Doctrine\Common\Annotations\AnnotationReader;
use PHPUnit\Framework\TestCase;
use Pucene\Component\Client\ClientInterface;
use Pucene\Component\Client\IndexInterface;
use Pucene\Component\QueryBuilder\Search;
use Pucene\Components\Metadata\Driver\FileLocator;
use Pucene\Components\Metadata\MetadataFactory;
use Pucene\Components\Metadata\MetadataFactoryInterface;
use Pucene\Components\ODM\Metadata\ClassMetadata;
use Pucene\Components\ODM\Metadata\Driver\AnnotationDriver;
use Pucene\Components\ODM\ObjectManager;
use Pucene\Components\ODM\Repository\ObjectRepository;
use Pucene\Tests\AppBundle\Document\ArticleDocument;
class ObjectManagerTest extends TestCase
{
public function testCreate()
{
$client = $this->prophesize(ClientInterface::class);
$objectManager = new ObjectManager($client->reveal(), $this->getMetadataFactory(), 'test');
$client->exists('test')->shouldBeCalled()->willReturn(false);
$client->create('test', ['mappings' => ['article' => ['title' => ['type' => 'string']]]])->shouldBeCalled();
$objectManager->create();
}
public function testDelete()
{
$client = $this->prophesize(ClientInterface::class);
$objectManager = new ObjectManager($client->reveal(), $this->getMetadataFactory(), 'test');
$client->exists('test')->shouldBeCalled()->willReturn(true);
$client->delete('test')->shouldBeCalled();
$objectManager->delete();
}
public function testCreateRepository()
{
$client = $this->prophesize(ClientInterface::class);
$objectManager = new ObjectManager($client->reveal(), $this->getMetadataFactory(), 'test');
$repository = $objectManager->createRepository(ArticleDocument::class);
$this->assertInstanceOf(ObjectRepository::class, $repository);
$reflectionProperty = new \ReflectionProperty($repository, 'metadata');
$reflectionProperty->setAccessible(true);
$metadata = $reflectionProperty->getValue($repository);
$reflectionProperty = new \ReflectionProperty($repository, 'objectManager');
$reflectionProperty->setAccessible(true);
$innerObjectManager = $reflectionProperty->getValue($repository);
$this->assertInstanceOf(ClassMetadata::class, $metadata);
$this->assertEquals(ArticleDocument::class, $metadata->getName());
$this->assertEquals($objectManager, $innerObjectManager);
}
public function testCreateSearch()
{
$client = $this->prophesize(ClientInterface::class);
$objectManager = new ObjectManager($client->reveal(), $this->getMetadataFactory(), 'test');
$this->assertInstanceOf(Search::class, $objectManager->createSearch());
}
public function testGetIndex()
{
$index = $this->prophesize(IndexInterface::class);
$client = $this->prophesize(ClientInterface::class);
$objectManager = new ObjectManager($client->reveal(), $this->getMetadataFactory(), 'test');
$client->exists('test')->shouldBeCalled()->willReturn(true);
$client->get('test')->shouldBeCalled()->willReturn($index->reveal());
$this->assertEquals($index->reveal(), $objectManager->getIndex());
}
public function testGetIndexNotExists()
{
$index = $this->prophesize(IndexInterface::class);
$client = $this->prophesize(ClientInterface::class);
$objectManager = new ObjectManager($client->reveal(), $this->getMetadataFactory(), 'test');
$client->exists('test')->shouldBeCalled()->willReturn(false);
$client->create('test', ['mappings' => ['article' => ['title' => ['type' => 'string']]]])
->shouldBeCalled()
->willReturn($index->reveal());
$client->get('test')->shouldBeCalled()->willReturn($index->reveal());
$this->assertEquals($index->reveal(), $objectManager->getIndex());
}
protected function getMetadataFactory(): MetadataFactoryInterface
{
$dirs = ['Pucene\Tests\AppBundle\Document' => __DIR__ . '/../../AppBundle/Document'];
return new MetadataFactory(new AnnotationDriver(new AnnotationReader(), new FileLocator($dirs)));
}
}
<file_sep><?php
namespace Pucene\Components\Metadata;
use Pucene\Components\Metadata\Cache\CacheResource;
class ClassMetadata implements ClassMetadataInterface
{
/**
* @var string
*/
private $name;
/**
* @var PropertyMetadataInterface[]
*/
private $properties;
/**
* @var CacheResource[]
*/
private $resources;
/**
* @param PropertyMetadataInterface[] $properties
* @param CacheResource[] $resources
*/
public function __construct(string $name, array $properties = [], array $resources = [])
{
$this->name = $name;
$this->properties = $properties;
$this->resources = $resources;
}
public function getName(): string
{
return $this->name;
}
/**
* @return PropertyMetadataInterface[]
*/
public function getProperties(): array
{
return $this->properties;
}
public function getProperty(string $name): PropertyMetadataInterface
{
return $this->properties[$name];
}
public function hasProperty(string $name): bool
{
return array_key_exists($name, $this->properties);
}
public function addProperty(PropertyMetadataInterface $property): void
{
$this->properties[$property->getName()] = $property;
}
/**
* @return CacheResource[]
*/
public function getResources(): array
{
return $this->resources;
}
public function addResource(CacheResource $resource): void
{
$this->resources[] = $resource;
}
public function createInstance()
{
return $this->getReflection()->newInstanceWithoutConstructor();
}
private function getReflection(): \ReflectionClass
{
return new \ReflectionClass($this->name);
}
}
<file_sep><?php
namespace Pucene\Components\Metadata;
use Pucene\Components\Metadata\Cache\CacheResource;
interface ClassMetadataInterface
{
public function getName(): string;
/**
* @return PropertyMetadataInterface[]
*/
public function getProperties(): array;
public function getProperty(string $name): PropertyMetadataInterface;
public function hasProperty(string $name): bool;
public function addProperty(PropertyMetadataInterface $property): void;
/**
* @return CacheResource[]
*/
public function getResources(): array;
public function addResource(CacheResource $resource): void;
/**
* @return mixed
*/
public function createInstance();
}
<file_sep><?php
namespace Pucene\Tests\AppBundle\Document;
use Pucene\Components\ODM\Annotation\Document;
use Pucene\Components\ODM\Annotation\Id;
use Pucene\Components\ODM\Annotation\Property;
/**
* @Document("article")
*/
class ArticleDocument
{
/**
* @var string
*
* @Id
*/
private $id;
/**
* @var string
*
* @Property("string")
*/
private $title;
public function __construct(string $title, ?string $id)
{
$this->title = $title;
$this->id = $id;
}
public function getId(): ?string
{
return $this->id;
}
public function getTitle(): string
{
return $this->title;
}
}
|
4b78d8093b1bf52ae6ae31169bd3a5ac6fa918f1
|
[
"Markdown",
"PHP"
] | 44
|
PHP
|
pucene/odm
|
e2cfe67ea55ef6f65fa340a9eff42c03c68848c7
|
a07afcc35e7f8c4e447427f6208f61cce4af420f
|
refs/heads/master
|
<file_sep>require 'json'
require 'webrick'
class Session
# find the cookie for this app
# deserialize the cookie into a hash
def initialize(req)
find_cookie(req)
end
def find_cookie(req)
@cookie_hash = {}
req.cookies.each do |cookie|
if cookie.name == '_rails_lite_app'
@cookie_hash = JSON.parse(cookie.value)
end
end
end
def [](key)
@cookie_hash[key]
end
def []=(key, val)
@cookie_hash[key] = val
end
# serialize the hash into json and save in a cookie
# add to the responses cookies
def store_session(res)
new_cookie = WEBrick::Cookie.new("_rails_lite_app", @cookie_hash.to_json)
res.cookies << new_cookie
end
end
# Write a helper class, Session in rails_lite/session.rb, which is passed the WEBrick::HTTPRequest on
# initialization. It should iterate through the cookies, looking for the one named '_rails_lite_app'.
# If this cookie has been set before, it should use JSON to deserialize the value and store this in an ivar;
# else it should store {}.
# Provide methods #[] and #[]= that will modify the session content; in this way the Session is Hash-like. Finally, write a method store_session(response) that will make a new cookie named '_rails_lite_app', set the value to the JSON serialized content of the hash, and add this cookie to response.cookies.<file_sep>require 'uri'
class Params
# use your initialize to merge params from
# 1. query string
# 2. post body
# 3. route params
def initialize(req, route_params = {})
@params = {}
@permitted_keys = []
set_route_params(route_params)
parse_www_encoded_form(req.query_string) unless req.query_string.nil?
parse_www_encoded_form(req.body) unless req.body.nil?
end
def set_route_params(route_params)
route_params.each do |key, value|
@params[key] = value
end
end
def [](key)
@params[key]
end
def permit(*keys)
@permitted_keys += keys
end
def require(key)
raise AttributeNotFoundError if @params[key].nil?
end
def permitted?(key)
@permitted_keys.include?(key)
end
def to_s
end
class AttributeNotFoundError < ArgumentError; end;
private
# { "user" => { "address" => { "street" => "main", "zip" => "89436" } } }
def parse_www_encoded_form(www_encoded_form)
array_of_hashes = []
ary = URI::decode_www_form(www_encoded_form)
ary.each do |elem|
keys = parse_key(elem.first)
array_of_hashes << hash_nest(keys, elem.last)
end
hash_merge(array_of_hashes)
end
def hash_merge(array_of_hashes)
array_of_hashes.each do |hash|
deep_merge(@params, hash)
end
end
def deep_merge(hash1, hash2)
deep_hash = {}
if hash1.keys.first != hash2.keys.first
hash1[hash2.keys.first] = hash2[hash2.keys.first]
return hash1
else
deep_hash[hash1.keys.first] = deep_merge(hash1[hash1.keys.first], hash2[hash2.keys.first])
end
return deep_hash
end
# we have ['user', 'address', 'street']
def hash_nest(keys, value)
hasher = {}
if keys.length == 1
hasher[keys.first] = value
return hasher
else
last_key = keys.shift
hasher[last_key] = hash_nest(keys, value)
return hasher
end
end
# this should return an array
# user[address][street] should return ['user', 'address', 'street']
def parse_key(key)
key.scan(/\w+/)
end
end
<file_sep>require 'json'
require 'webrick'
class Flash
def initialize(req, res)
find_flash(req)
@flash_now_hash = {}
@res = res
end
def find_flash(req)
@flash_hash = {}
cookie = req.cookies.select { |cookie| cookie.name == '_rails_lite_flash' }
p cookie
unless cookie.first.nil?
@flash_hash = JSON.parse(cookie.first.value)
@flash_hash["received"] = true
end
end
def [](key)
if @flash_hash.empty?
store_flash(@res)
p "WE MADE IT HERE"
#@flash_now_hash[key]
else
@flash_hash[key]
end
end
def []=(key,value)
@flash_hash[key] = value if @flash_hash["received"] == true
@flash_now_hash[key] = value
end
def store_flash(res)
new_cookie = WEBrick::Cookie.new("_rails_lite_flash", @flash_hash.to_json)
res.cookies << new_cookie
end
end
|
e2bfbd3177b06cdf1604b54409b2f5dade1d2aea
|
[
"Ruby"
] | 3
|
Ruby
|
rsahai91/rails_lite
|
6b1048b03c87310c330eabe8a52086b43a9e06b1
|
aa5086c247f8f81d723c917f5338e6bf613b9235
|
refs/heads/master
|
<file_sep>// -----------------------------------------------------------------------
// <copyright file="ReadOnlySession.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Core
{
using System;
using System.Collections.Generic;
using System.Data;
using MicroLite.Dialect;
using MicroLite.Logging;
using MicroLite.Mapping;
using MicroLite.Query;
/// <summary>
/// The default implementation of <see cref="IReadOnlySession" />.
/// </summary>
internal class ReadOnlySession : IReadOnlySession, IIncludeSession, IAdvancedReadOnlySession
{
protected static readonly ILog Log = LogManager.GetCurrentClassLog();
private readonly IConnectionManager connectionManager;
private readonly Queue<Include> includes = new Queue<Include>();
private readonly IObjectBuilder objectBuilder;
private readonly Queue<SqlQuery> queries = new Queue<SqlQuery>();
private readonly ISessionFactory sessionFactory;
private bool disposed;
internal ReadOnlySession(
ISessionFactory sessionFactory,
IConnectionManager connectionManager,
IObjectBuilder objectBuilder)
{
this.sessionFactory = sessionFactory;
this.connectionManager = connectionManager;
this.objectBuilder = objectBuilder;
}
public IAdvancedReadOnlySession Advanced
{
get
{
return this;
}
}
public IIncludeSession Include
{
get
{
return this;
}
}
public ISessionFactory SessionFactory
{
get
{
return this.sessionFactory;
}
}
public ITransaction Transaction
{
get
{
return this.ConnectionManager.CurrentTransaction;
}
}
protected IConnectionManager ConnectionManager
{
get
{
return this.connectionManager;
}
}
protected ISqlDialect SqlDialect
{
get
{
return this.sessionFactory.SqlDialect;
}
}
public IIncludeMany<T> All<T>() where T : class, new()
{
var sqlQuery = (new SelectSqlBuilder(this.SqlDialect.SqlCharacters, "*"))
.From(typeof(T))
.ToSqlQuery();
var include = this.Include.Many<T>(sqlQuery);
return include;
}
public ITransaction BeginTransaction()
{
return this.BeginTransaction(IsolationLevel.ReadCommitted);
}
public ITransaction BeginTransaction(IsolationLevel isolationLevel)
{
this.ThrowIfDisposed();
return this.ConnectionManager.BeginTransaction(isolationLevel);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
public void ExecutePendingQueries()
{
try
{
if (this.SqlDialect.SupportsBatchedQueries)
{
this.ExecuteQueriesCombined();
}
else
{
this.ExecuteQueriesIndividually();
}
}
catch (MicroLiteException)
{
// Don't re-wrap MicroLite exceptions
throw;
}
catch (Exception e)
{
Log.TryLogError(e.Message, e);
throw new MicroLiteException(e.Message, e);
}
finally
{
this.includes.Clear();
this.queries.Clear();
}
}
public IList<T> Fetch<T>(SqlQuery sqlQuery)
{
var include = this.Include.Many<T>(sqlQuery);
this.ExecutePendingQueries();
return include.Values;
}
IInclude<T> IIncludeSession.Single<T>(object identifier)
{
this.ThrowIfDisposed();
if (identifier == null)
{
throw new ArgumentNullException("identifier");
}
var objectInfo = ObjectInfo.For(typeof(T));
var sqlQuery = (new SelectSqlBuilder(this.SqlDialect.SqlCharacters, "*"))
.From(objectInfo.ForType)
.Where(objectInfo.TableInfo.IdentifierColumn).IsEqualTo(identifier)
.ToSqlQuery();
var include = this.Include.Single<T>(sqlQuery);
return include;
}
IInclude<T> IIncludeSession.Single<T>(SqlQuery sqlQuery)
{
this.ThrowIfDisposed();
if (sqlQuery == null)
{
throw new ArgumentNullException("sqlQuery");
}
var include = new IncludeSingle<T>();
this.includes.Enqueue(include);
this.queries.Enqueue(sqlQuery);
return include;
}
T IReadOnlySession.Single<T>(object identifier)
{
var include = this.Include.Single<T>(identifier);
this.ExecutePendingQueries();
return include.Value;
}
T IReadOnlySession.Single<T>(SqlQuery sqlQuery)
{
var include = this.Include.Single<T>(sqlQuery);
this.ExecutePendingQueries();
return include.Value;
}
public IIncludeMany<T> Many<T>(SqlQuery sqlQuery)
{
this.ThrowIfDisposed();
if (sqlQuery == null)
{
throw new ArgumentNullException("sqlQuery");
}
var include = new IncludeMany<T>();
this.includes.Enqueue(include);
this.queries.Enqueue(sqlQuery);
return include;
}
public PagedResult<T> Paged<T>(SqlQuery sqlQuery, PagingOptions pagingOptions)
{
this.ThrowIfDisposed();
if (sqlQuery == null)
{
throw new ArgumentNullException("sqlQuery");
}
if (pagingOptions == PagingOptions.None)
{
throw new MicroLiteException(Messages.Session_PagingOptionsMustNotBeNone);
}
var countSqlQuery = this.SqlDialect.CountQuery(sqlQuery);
var pagedSqlQuery = this.SqlDialect.PageQuery(sqlQuery, pagingOptions);
var includeCount = this.Include.Scalar<int>(countSqlQuery);
var includeMany = this.Include.Many<T>(pagedSqlQuery);
this.ExecutePendingQueries();
var page = (pagingOptions.Offset / pagingOptions.Count) + 1;
return new PagedResult<T>(page, includeMany.Values, pagingOptions.Count, includeCount.Value);
}
#if !NET_3_5
public IList<dynamic> Projection(SqlQuery sqlQuery)
{
return this.Fetch<dynamic>(sqlQuery);
}
#endif
public IInclude<T> Scalar<T>(SqlQuery sqlQuery)
{
this.ThrowIfDisposed();
if (sqlQuery == null)
{
throw new ArgumentNullException("sqlQuery");
}
var include = new IncludeScalar<T>();
this.includes.Enqueue(include);
this.queries.Enqueue(sqlQuery);
return include;
}
protected void Dispose(bool disposing)
{
if (disposing && !this.disposed)
{
this.ConnectionManager.Dispose();
Log.TryLogDebug(Messages.Session_Disposed);
this.disposed = true;
}
}
protected void ThrowIfDisposed()
{
if (this.disposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
}
private void ExecuteQueriesCombined()
{
var sqlQuery = this.queries.Count == 1 ? this.queries.Peek() : this.SqlDialect.Combine(this.queries);
using (var command = this.ConnectionManager.CreateCommand())
{
try
{
this.SqlDialect.BuildCommand(command, sqlQuery);
using (var reader = command.ExecuteReader())
{
do
{
var include = this.includes.Dequeue();
include.BuildValue(reader, this.objectBuilder);
}
while (reader.NextResult());
}
}
finally
{
this.connectionManager.CommandCompleted(command);
}
}
}
private void ExecuteQueriesIndividually()
{
do
{
using (var command = this.ConnectionManager.CreateCommand())
{
try
{
var sqlQuery = this.queries.Dequeue();
this.SqlDialect.BuildCommand(command, sqlQuery);
using (var reader = command.ExecuteReader())
{
var include = this.includes.Dequeue();
include.BuildValue(reader, this.objectBuilder);
}
}
finally
{
this.connectionManager.CommandCompleted(command);
}
}
}
while (this.queries.Count > 0);
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="SqlDialect.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Dialect
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using MicroLite.FrameworkExtensions;
using MicroLite.Mapping;
/// <summary>
/// The base class for implementations of <see cref="ISqlDialect" />.
/// </summary>
public abstract class SqlDialect : ISqlDialect
{
private static readonly Regex orderByRegex = new Regex("(?<=ORDER BY)(.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
private static readonly Regex selectRegexGreedy = new Regex("SELECT(.+)(?=FROM)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
private static readonly Regex selectRegexLazy = new Regex("SELECT(.+?)(?=FROM)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
private static readonly Regex tableNameRegexGreedy = new Regex("(?<=FROM)(.+)(?=WHERE)|(?<=FROM)(.+)(?=ORDER BY)|(?<=FROM)(.+)(?=WHERE)?|(?<=FROM)(.+)(?=ORDER BY)?", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
private static readonly Regex tableNameRegexLazy = new Regex("(?<=FROM)(.+?)(?=WHERE)|(?<=FROM)(.+?)(?=ORDER BY)|(?<=FROM)(.+?)(?=WHERE)?|(?<=FROM)(.+?)(?=ORDER BY)?", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
private static readonly Regex whereRegex = new Regex("(?<=WHERE)(.+)(?=ORDER BY)|(?<=WHERE)(.+)(?=ORDER BY)?", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
private readonly SqlCharacters sqlCharacters;
/// <summary>
/// Initialises a new instance of the <see cref="SqlDialect"/> class.
/// </summary>
/// <param name="sqlCharacters">The SQL characters.</param>
protected SqlDialect(SqlCharacters sqlCharacters)
{
this.sqlCharacters = sqlCharacters;
}
/// <summary>
/// Gets the SQL characters for the SQL dialect.
/// </summary>
public SqlCharacters SqlCharacters
{
get
{
return this.sqlCharacters;
}
}
/// <summary>
/// Gets a value indicating whether this SqlDialect supports batched queries.
/// </summary>
public virtual bool SupportsBatchedQueries
{
get
{
return true;
}
}
/// <summary>
/// Gets the select identity string.
/// </summary>
protected abstract string SelectIdentityString
{
get;
}
/// <summary>
/// Builds the command using the values in the specified SqlQuery.
/// </summary>
/// <param name="command">The command to build.</param>
/// <param name="sqlQuery">The SQL query containing the values for the command.</param>
/// <exception cref="MicroLiteException">Thrown if the number of arguments does not match the number of parameter names.</exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "SqlQuery.CommandText is the parameterised query.")]
public virtual void BuildCommand(IDbCommand command, SqlQuery sqlQuery)
{
var parameterNames = this.sqlCharacters.SupportsNamedParameters
? SqlUtility.GetParameterNames(sqlQuery.CommandText)
: Enumerable.Range(0, sqlQuery.Arguments.Count).Select(c => "Parameter" + c.ToString(CultureInfo.InvariantCulture)).ToArray();
if (parameterNames.Count != sqlQuery.Arguments.Count)
{
throw new MicroLiteException(Messages.SqlDialect_ArgumentsCountMismatch.FormatWith(parameterNames.Count.ToString(CultureInfo.InvariantCulture), sqlQuery.Arguments.Count.ToString(CultureInfo.InvariantCulture)));
}
command.CommandText = this.GetCommandText(sqlQuery.CommandText);
command.CommandTimeout = sqlQuery.Timeout;
command.CommandType = this.GetCommandType(sqlQuery.CommandText);
this.AddParameters(command, sqlQuery, parameterNames);
}
/// <summary>
/// Combines the specified SQL queries into a single SqlQuery.
/// </summary>
/// <param name="sqlQueries">The SQL queries to be combined.</param>
/// <returns>
/// The combined <see cref="SqlQuery" />.
/// </returns>
/// <exception cref="System.ArgumentNullException">Thrown if sqlQueries is null.</exception>
public virtual SqlQuery Combine(IEnumerable<SqlQuery> sqlQueries)
{
if (sqlQueries == null)
{
throw new ArgumentNullException("sqlQueries");
}
int argumentsCount = 0;
var sqlBuilder = new StringBuilder(sqlQueries.Sum(s => s.CommandText.Length));
foreach (var sqlQuery in sqlQueries)
{
argumentsCount += sqlQuery.Arguments.Count;
var commandText = SqlUtility.RenumberParameters(sqlQuery.CommandText, argumentsCount);
sqlBuilder.AppendLine(commandText + this.sqlCharacters.StatementSeparator);
}
var combinedQuery = new SqlQuery(sqlBuilder.ToString(0, sqlBuilder.Length - 3), sqlQueries.SelectMany(s => s.Arguments).ToArray());
combinedQuery.Timeout = sqlQueries.Max(s => s.Timeout);
return combinedQuery;
}
/// <summary>
/// Creates an SqlQuery to count the number of records which would be returned by the specified SqlQuery.
/// </summary>
/// <param name="sqlQuery">The SQL query.</param>
/// <returns>
/// An <see cref="SqlQuery" /> to count the number of records which would be returned by the specified SqlQuery.
/// </returns>
public virtual SqlQuery CountQuery(SqlQuery sqlQuery)
{
var qualifiedTableName = this.ReadTableName(sqlQuery.CommandText);
var whereValue = this.ReadWhereClause(sqlQuery.CommandText);
var whereClause = !string.IsNullOrEmpty(whereValue) ? " WHERE " + whereValue : string.Empty;
return new SqlQuery("SELECT COUNT(*) FROM " + qualifiedTableName + whereClause, sqlQuery.Arguments.ToArray());
}
/// <summary>
/// Creates an SqlQuery with the specified statement type for the specified instance.
/// </summary>
/// <param name="statementType">Type of the statement.</param>
/// <param name="instance">The instance to generate the SqlQuery for.</param>
/// <returns>
/// The created <see cref="SqlQuery" />.
/// </returns>
/// <exception cref="System.NotSupportedException">Thrown if the StatementType is not supported.</exception>
public virtual SqlQuery CreateQuery(StatementType statementType, object instance)
{
var forType = instance.GetType();
var objectInfo = ObjectInfo.For(forType);
switch (statementType)
{
case StatementType.Delete:
var identifierValue = objectInfo.GetIdentifierValue(instance);
return this.CreateQuery(StatementType.Delete, forType, identifierValue);
case StatementType.Insert:
var insertValues = new List<object>(objectInfo.TableInfo.Columns.Count);
var insertSqlBuilder = this.CreateSql(statementType, objectInfo);
insertSqlBuilder.Append(" VALUES (");
foreach (var column in objectInfo.TableInfo.Columns)
{
if (objectInfo.TableInfo.IdentifierStrategy == IdentifierStrategy.DbGenerated
&& column.ColumnName.Equals(objectInfo.TableInfo.IdentifierColumn))
{
continue;
}
if (column.AllowInsert)
{
insertSqlBuilder.Append(this.sqlCharacters.GetParameterName(insertValues.Count));
insertSqlBuilder.Append(", ");
var value = objectInfo.GetPropertyValueForColumn(instance, column.ColumnName);
insertValues.Add(value);
}
}
insertSqlBuilder.Remove(insertSqlBuilder.Length - 2, 2);
insertSqlBuilder.Append(")");
if (objectInfo.TableInfo.IdentifierStrategy == IdentifierStrategy.DbGenerated)
{
insertSqlBuilder.Append(this.sqlCharacters.StatementSeparator);
insertSqlBuilder.Append(this.SelectIdentityString);
}
return new SqlQuery(insertSqlBuilder.ToString(), insertValues.ToArray());
case StatementType.Update:
var updateValues = new List<object>(objectInfo.TableInfo.Columns.Count);
var updateSqlBuilder = this.CreateSql(StatementType.Update, objectInfo);
foreach (var column in objectInfo.TableInfo.Columns)
{
if (column.AllowUpdate
&& !column.ColumnName.Equals(objectInfo.TableInfo.IdentifierColumn))
{
updateSqlBuilder.AppendFormat(
" {0} = {1},",
this.sqlCharacters.EscapeSql(column.ColumnName),
this.sqlCharacters.GetParameterName(updateValues.Count));
var value = objectInfo.GetPropertyValueForColumn(instance, column.ColumnName);
updateValues.Add(value);
}
}
updateSqlBuilder.Remove(updateSqlBuilder.Length - 1, 1);
updateSqlBuilder.AppendFormat(
" WHERE {0} = {1}",
this.sqlCharacters.EscapeSql(objectInfo.TableInfo.IdentifierColumn),
this.sqlCharacters.GetParameterName(updateValues.Count));
updateValues.Add(objectInfo.GetIdentifierValue(instance));
return new SqlQuery(updateSqlBuilder.ToString(), updateValues.ToArray());
default:
throw new NotSupportedException(Messages.SqlDialect_StatementTypeNotSupported);
}
}
/// <summary>
/// Creates an SqlQuery with the specified statement type for the specified type and identifier.
/// </summary>
/// <param name="statementType">Type of the statement.</param>
/// <param name="forType">The type of object to create the query for.</param>
/// <param name="identifier">The identifier of the instance to create the query for.</param>
/// <returns>
/// The created <see cref="SqlQuery" />.
/// </returns>
/// <exception cref="System.NotSupportedException">Thrown if the StatementType is not supported.</exception>
public virtual SqlQuery CreateQuery(StatementType statementType, Type forType, object identifier)
{
switch (statementType)
{
case StatementType.Delete:
var objectInfo = ObjectInfo.For(forType);
var sqlBuilder = this.CreateSql(statementType, objectInfo);
sqlBuilder.AppendFormat(
" WHERE {0} = {1}",
this.sqlCharacters.EscapeSql(objectInfo.TableInfo.IdentifierColumn),
this.sqlCharacters.GetParameterName(0));
return new SqlQuery(sqlBuilder.ToString(), identifier);
default:
throw new NotSupportedException(Messages.SqlDialect_StatementTypeNotSupported);
}
}
/// <summary>
/// Creates an SqlQuery to page the records which would be returned by the specified SqlQuery based upon the paging options.
/// </summary>
/// <param name="sqlQuery">The SQL query.</param>
/// <param name="pagingOptions">The paging options.</param>
/// <returns>
/// A <see cref="SqlQuery" /> to return the paged results of the specified query.
/// </returns>
public abstract SqlQuery PageQuery(SqlQuery sqlQuery, PagingOptions pagingOptions);
/// <summary>
/// Adds the parameters.
/// </summary>
/// <param name="command">The command.</param>
/// <param name="sqlQuery">The SQL query.</param>
/// <param name="parameterNames">The parameter names.</param>
protected virtual void AddParameters(IDbCommand command, SqlQuery sqlQuery, IList<string> parameterNames)
{
for (int i = 0; i < parameterNames.Count; i++)
{
var parameterName = parameterNames[i];
var parameter = command.CreateParameter();
parameter.Direction = ParameterDirection.Input;
parameter.ParameterName = parameterName;
parameter.Value = sqlQuery.Arguments[i] ?? DBNull.Value;
command.Parameters.Add(parameter);
}
}
/// <summary>
/// Appends the name of the table.
/// </summary>
/// <param name="sqlBuilder">The SQL builder.</param>
/// <param name="objectInfo">The object info.</param>
protected void AppendTableName(StringBuilder sqlBuilder, IObjectInfo objectInfo)
{
var schema = !string.IsNullOrEmpty(objectInfo.TableInfo.Schema)
? objectInfo.TableInfo.Schema
: string.Empty;
if (!string.IsNullOrEmpty(schema))
{
sqlBuilder.Append(this.sqlCharacters.LeftDelimiter);
sqlBuilder.Append(schema);
sqlBuilder.Append(this.sqlCharacters.RightDelimiter);
sqlBuilder.Append('.');
}
sqlBuilder.Append(this.sqlCharacters.LeftDelimiter);
sqlBuilder.Append(objectInfo.TableInfo.Name);
sqlBuilder.Append(this.sqlCharacters.RightDelimiter);
}
/// <summary>
/// Gets the command text.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <returns>The actual command text.</returns>
protected virtual string GetCommandText(string commandText)
{
return commandText;
}
/// <summary>
/// Gets the type of the command.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <returns>The CommandType for the specified command text.</returns>
protected virtual CommandType GetCommandType(string commandText)
{
return CommandType.Text;
}
/// <summary>
/// Reads the order by clause from the specified command text excluding the ORDER BY keyword.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <returns>The columns in the order by list.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Intentionally left as an instance method so that it's easily discoverable from subclasses.")]
protected string ReadOrderBy(string commandText)
{
return orderByRegex.Match(commandText).Groups[0].Value.Replace(Environment.NewLine, string.Empty).Trim();
}
/// <summary>
/// Reads the select clause from the specified command text including the SELECT keyword.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <returns>The columns in the select list.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Intentionally left as an instance method so that it's easily discoverable from subclasses.")]
protected string ReadSelectList(string commandText)
{
string selectList;
selectList = selectRegexLazy.Match(commandText).Groups[0].Value.Replace(Environment.NewLine, string.Empty).Trim();
if (selectList.Length == 0)
{
selectList = selectRegexGreedy.Match(commandText).Groups[0].Value.Replace(Environment.NewLine, string.Empty).Trim();
}
return selectList;
}
/// <summary>
/// Reads the name of the table the sql query is targeting.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <returns>The name of the table the sql query is targeting.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Intentionally left as an instance method so that it's easily discoverable from subclasses.")]
protected string ReadTableName(string commandText)
{
string tableName;
tableName = tableNameRegexLazy.Match(commandText).Groups[0].Value.Replace(Environment.NewLine, string.Empty).Trim();
if (tableName.Length == 0)
{
tableName = tableNameRegexGreedy.Match(commandText).Groups[0].Value.Replace(Environment.NewLine, string.Empty).Trim();
}
return tableName;
}
/// <summary>
/// Reads the where clause from the specified command text excluding the WHERE keyword.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <returns>The where clause without the WHERE keyword.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Intentionally left as an instance method so that it's easily discoverable from subclasses.")]
protected string ReadWhereClause(string commandText)
{
return whereRegex.Match(commandText).Groups[0].Value.Replace(Environment.NewLine, string.Empty).Trim();
}
private StringBuilder CreateSql(StatementType statementType, IObjectInfo objectInfo)
{
var sqlBuilder = new StringBuilder(capacity: 120);
switch (statementType)
{
case StatementType.Delete:
sqlBuilder.Append("DELETE FROM ");
this.AppendTableName(sqlBuilder, objectInfo);
break;
case StatementType.Insert:
sqlBuilder.Append("INSERT INTO ");
this.AppendTableName(sqlBuilder, objectInfo);
sqlBuilder.Append(" (");
foreach (var column in objectInfo.TableInfo.Columns)
{
if (objectInfo.TableInfo.IdentifierStrategy == IdentifierStrategy.DbGenerated
&& column.ColumnName.Equals(objectInfo.TableInfo.IdentifierColumn))
{
continue;
}
if (column.AllowInsert)
{
sqlBuilder.Append(this.sqlCharacters.EscapeSql(column.ColumnName));
sqlBuilder.Append(", ");
}
}
sqlBuilder.Remove(sqlBuilder.Length - 2, 2);
sqlBuilder.Append(")");
break;
case StatementType.Update:
sqlBuilder.Append("UPDATE ");
this.AppendTableName(sqlBuilder, objectInfo);
sqlBuilder.Append(" SET");
break;
}
return sqlBuilder;
}
}
}<file_sep>namespace MicroLite.Tests.Integration.Delete
{
using Xunit;
public class WhenDeletingAnUnknownInstance : IntegrationTest
{
private readonly bool deleted;
public WhenDeletingAnUnknownInstance()
{
this.deleted = this.Session.Delete(new Customer
{
CustomerId = 1
});
}
[Fact]
public void DeleteShouldReturnFalse()
{
Assert.False(this.deleted);
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="IObjectBuilder.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Core
{
using System.Data;
using MicroLite.Mapping;
/// <summary>
/// The interface for a class which builds an object instance from the values in a <see cref="IDataReader"/>.
/// </summary>
internal interface IObjectBuilder
{
/// <summary>
/// Builds an instance of the specified type, populating it with the values in the specified data reader.
/// </summary>
/// <typeparam name="T">The type of object to be built.</typeparam>
/// <param name="objectInfo">The <see cref="IObjectInfo"/> for the type to be built.</param>
/// <param name="reader">The <see cref="IDataReader"/> containing the values to populate the object with.</param>
/// <returns>The new instance populated with the values from the <see cref="IDataReader"/>.</returns>
/// <exception cref="MicroLiteException">Thrown if there is an exception setting a property value.</exception>
T BuildInstance<T>(IObjectInfo objectInfo, IDataReader reader);
}
}<file_sep>namespace MicroLite.Tests.Mapping
{
using System;
using System.Dynamic;
using MicroLite.Mapping;
using Xunit;
public class ExpandoObjectInfoTests
{
[Fact]
public void CreateInstance()
{
var objectInfo = new ExpandoObjectInfo();
var instance = objectInfo.CreateInstance();
Assert.IsType<ExpandoObject>(instance);
}
[Fact]
public void DefaultIdentifierValueThrowsNotSupportedException()
{
var objectInfo = new ExpandoObjectInfo();
var exception = Assert.Throws<NotSupportedException>(() => objectInfo.DefaultIdentifierValue);
Assert.Equal(exception.Message, Messages.ExpandoObjectInfo_NotSupportedReason);
}
[Fact]
public void ForTypeReturnsExpandoObject()
{
var objectInfo = new ExpandoObjectInfo();
Assert.Equal(typeof(ExpandoObject), objectInfo.ForType);
}
[Fact]
public void GetIdentifierValueThrowsNotSupportedException()
{
var objectInfo = new ExpandoObjectInfo();
var exception = Assert.Throws<NotSupportedException>(() => objectInfo.GetIdentifierValue(new ExpandoObject()));
Assert.Equal(exception.Message, Messages.ExpandoObjectInfo_NotSupportedReason);
}
[Fact]
public void GetPropertyValueForColumnThrowsNotSupportedException()
{
var objectInfo = new ExpandoObjectInfo();
var exception = Assert.Throws<NotSupportedException>(() => objectInfo.GetPropertyValueForColumn(new ExpandoObject(), "foo"));
Assert.Equal(exception.Message, Messages.ExpandoObjectInfo_NotSupportedReason);
}
[Fact]
public void GetPropertyValueThrowsNotSupportedException()
{
var objectInfo = new ExpandoObjectInfo();
var exception = Assert.Throws<NotSupportedException>(() => objectInfo.GetPropertyValue(new ExpandoObject(), "foo"));
Assert.Equal(exception.Message, Messages.ExpandoObjectInfo_NotSupportedReason);
}
[Fact]
public void HasDefaultIdentifierValueThrowsNotSupportedException()
{
var objectInfo = new ExpandoObjectInfo();
var exception = Assert.Throws<NotSupportedException>(() => objectInfo.HasDefaultIdentifierValue(new ExpandoObject()));
Assert.Equal(exception.Message, Messages.ExpandoObjectInfo_NotSupportedReason);
}
[Fact]
public void SetPropertyValueForColumnSetsPropertyValue()
{
var objectInfo = new ExpandoObjectInfo();
var instance = (dynamic)objectInfo.CreateInstance();
objectInfo.SetPropertyValueForColumn(instance, "Id", 12345);
objectInfo.SetPropertyValueForColumn(instance, "Name", "<NAME>");
Assert.Equal(12345, instance.Id);
Assert.Equal("<NAME>", instance.Name);
}
[Fact]
public void SetPropertyValueForColumnSetsPropertyValueToNullIfPassedDBNull()
{
var objectInfo = new ExpandoObjectInfo();
var instance = (dynamic)objectInfo.CreateInstance();
objectInfo.SetPropertyValueForColumn(instance, "Name", DBNull.Value);
Assert.Null(instance.Name);
}
[Fact]
public void SetPropertyValueThrowsNotSupportedException()
{
var objectInfo = new ExpandoObjectInfo();
var exception = Assert.Throws<NotSupportedException>(() => objectInfo.SetPropertyValue(new ExpandoObject(), "Name", "foo"));
Assert.Equal(exception.Message, Messages.ExpandoObjectInfo_NotSupportedReason);
}
[Fact]
public void TableInfoThrowsNotSupportedException()
{
var objectInfo = new ExpandoObjectInfo();
var exception = Assert.Throws<NotSupportedException>(() => objectInfo.TableInfo);
Assert.Equal(exception.Message, Messages.ExpandoObjectInfo_NotSupportedReason);
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="ObjectBuilder.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Core
{
using System;
using System.Data;
using MicroLite.Logging;
using MicroLite.Mapping;
/// <summary>
/// The default implementation of <see cref="IObjectBuilder"/>.
/// </summary>
internal sealed class ObjectBuilder : IObjectBuilder
{
private static readonly ILog log = LogManager.GetCurrentClassLog();
public T BuildInstance<T>(IObjectInfo objectInfo, IDataReader reader)
{
log.TryLogDebug(Messages.ObjectBuilder_CreatingInstance, objectInfo.ForType.FullName);
var instance = (T)objectInfo.CreateInstance();
for (int i = reader.FieldCount - 1; i >= 0; i--)
{
var columnName = reader.GetName(i);
try
{
objectInfo.SetPropertyValueForColumn(instance, columnName, reader[i]);
}
catch (Exception e)
{
log.TryLogError(e.Message, e);
throw new MicroLiteException(e.Message, e);
}
}
return instance;
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="IConnectionManager.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Core
{
using System;
using System.Data;
/// <summary>
/// The interface for a class which manages an IDbConnection.
/// </summary>
internal interface IConnectionManager : IDisposable
{
/// <summary>
/// Gets the current transaction or null if no transaction has been started.
/// </summary>
ITransaction CurrentTransaction
{
get;
}
/// <summary>
/// Begins the transaction with the specified isolation level.
/// </summary>
/// <param name="isolationLevel">The isolation level to use for the transaction.</param>
/// <returns>An <see cref="ITransaction"/> with the specified <see cref="IsolationLevel"/>.</returns>
ITransaction BeginTransaction(IsolationLevel isolationLevel);
/// <summary>
/// Called when the command is completed to free any resources which are no longer needed.
/// </summary>
/// <param name="command">The completed command.</param>
void CommandCompleted(IDbCommand command);
/// <summary>
/// Creates a new IDbCommand for the managed connection which will be enlisted in the active transaction.
/// </summary>
/// <returns>The IDbCommand for the connection.</returns>
IDbCommand CreateCommand();
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="SqlUtility.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
/// <summary>
/// A utility class containing useful methods for manipulating Sql.
/// </summary>
public static class SqlUtility
{
private static readonly char[] parameterIdentifiers = new[] { '@', ':', '?' };
private static readonly Regex parameterRegex = new Regex(@"((@|:)[\w]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
/// <summary>
/// Gets the position of the first parameter in the specified command text.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <returns>The position of the first parameter in the command text or -1 if no parameters are found.</returns>
public static int GetFirstParameterPosition(string commandText)
{
if (commandText == null)
{
throw new ArgumentNullException("commandText");
}
var firstParameterPosition = commandText.IndexOfAny(parameterIdentifiers, 0);
return firstParameterPosition;
}
/// <summary>
/// Gets the parameter names from the specified command text.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <returns>The parameter names in the command text.</returns>
public static IList<string> GetParameterNames(string commandText)
{
if (commandText == null)
{
throw new ArgumentNullException("commandText");
}
return new HashSet<string>(parameterRegex.Matches(commandText).Cast<Match>().Select(x => x.Value)).ToList();
}
/// <summary>
/// Re-numbers the parameters in the SQL based upon the total number of arguments.
/// </summary>
/// <param name="sql">The SQL.</param>
/// <param name="totalArgumentCount">The total number of arguments.</param>
/// <returns>The re-numbered SQL</returns>
public static string RenumberParameters(string sql, int totalArgumentCount)
{
var parameterNames = GetParameterNames(sql);
if (parameterNames.Count == 0)
{
return sql;
}
var argsAdded = 0;
var parameterPrefix = parameterNames.First().Substring(0, 2);
var predicateReWriter = new StringBuilder(sql);
foreach (var parameterName in parameterNames.OrderByDescending(n => n))
{
var newParameterName = parameterPrefix + (totalArgumentCount - ++argsAdded).ToString(CultureInfo.InvariantCulture);
predicateReWriter.Replace(parameterName, newParameterName);
}
return predicateReWriter.ToString();
}
}
}<file_sep>namespace MicroLite.Tests.Core
{
using System.Data;
using MicroLite.Core;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="ConnectionManager"/> class.
/// </summary>
public class ConnectionManagerTests
{
public class WhenCallingBeginTransactionAndThereIsAnActiveTransaction
{
private readonly ITransaction transaction1;
private readonly ITransaction transaction2;
public WhenCallingBeginTransactionAndThereIsAnActiveTransaction()
{
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.BeginTransaction(It.IsAny<IsolationLevel>())).Returns(new Mock<IDbTransaction>().Object);
var connectionManager = new ConnectionManager(mockConnection.Object);
this.transaction1 = connectionManager.BeginTransaction(IsolationLevel.ReadCommitted);
this.transaction2 = connectionManager.BeginTransaction(IsolationLevel.ReadCommitted);
}
[Fact]
public void TheActiveTransactionIsReturnedEachTime()
{
Assert.Same(transaction1, transaction2);
}
}
public class WhenCallingBeginTransactionWithAnIsolationLevel
{
private readonly IsolationLevel isolationLevel = IsolationLevel.Chaos;
private readonly Mock<IDbConnection> mockConnection = new Mock<IDbConnection>();
private readonly ITransaction transaction;
public WhenCallingBeginTransactionWithAnIsolationLevel()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.IsolationLevel).Returns(this.isolationLevel);
this.mockConnection.Setup(x => x.BeginTransaction(this.isolationLevel)).Returns(mockTransaction.Object);
var connectionManager = new ConnectionManager(this.mockConnection.Object);
this.transaction = connectionManager.BeginTransaction(this.isolationLevel);
}
[Fact]
public void TheSpecifiedIsolationLevelIsUsed()
{
Assert.Equal(this.isolationLevel, this.transaction.IsolationLevel);
}
}
public class WhenCallingCommandCompletedAndThereIsATransaction
{
private readonly Mock<IDbConnection> mockConnection = new Mock<IDbConnection>();
public WhenCallingCommandCompletedAndThereIsATransaction()
{
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.Connection).Returns(mockConnection.Object);
mockCommand.Setup(x => x.Transaction).Returns(new Mock<IDbTransaction>().Object);
var connectionManager = new ConnectionManager(this.mockConnection.Object);
connectionManager.CommandCompleted(mockCommand.Object);
}
[Fact]
public void TheConnectionShouldNotBeClosed()
{
this.mockConnection.Verify(x => x.Close(), Times.Never());
}
}
public class WhenCallingCommandCompletedAndThereIsNoTransaction
{
private readonly Mock<IDbConnection> mockConnection = new Mock<IDbConnection>();
public WhenCallingCommandCompletedAndThereIsNoTransaction()
{
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.Connection).Returns(mockConnection.Object);
var connectionManager = new ConnectionManager(this.mockConnection.Object);
connectionManager.CommandCompleted(mockCommand.Object);
}
[Fact]
public void TheConnectionShouldBeClosed()
{
this.mockConnection.Verify(x => x.Close(), Times.Once());
}
}
public class WhenCallingCreateCommandAndTheConnectionIsClosed
{
private readonly IDbCommand command;
private readonly Mock<IDbConnection> mockConnection = new Mock<IDbConnection>();
public WhenCallingCreateCommandAndTheConnectionIsClosed()
{
this.mockConnection.Setup(x => x.State).Returns(ConnectionState.Closed);
this.mockConnection.Setup(x => x.CreateCommand()).Returns(new Mock<IDbCommand>().Object);
var connectionManager = new ConnectionManager(this.mockConnection.Object);
this.command = connectionManager.CreateCommand();
}
[Fact]
public void TheCommandShouldBeCreated()
{
this.mockConnection.Verify(x => x.CreateCommand(), Times.Once());
}
[Fact]
public void TheCommandShouldBeReturned()
{
Assert.NotNull(this.command);
}
[Fact]
public void TheConnectionShouldBeOpened()
{
this.mockConnection.Verify(x => x.Open(), Times.Once());
}
}
public class WhenCallingCreateCommandAndThereIsACurrentTransaction
{
private readonly IDbCommand command;
private readonly Mock<IDbCommand> mockCommand = new Mock<IDbCommand>();
private readonly Mock<IDbConnection> mockConnection = new Mock<IDbConnection>();
private readonly IDbTransaction transaction = new Mock<IDbTransaction>().Object;
public WhenCallingCreateCommandAndThereIsACurrentTransaction()
{
this.mockCommand.SetupProperty(x => x.Transaction);
this.mockConnection.Setup(x => x.State).Returns(ConnectionState.Open);
this.mockConnection.Setup(x => x.BeginTransaction(It.IsAny<IsolationLevel>())).Returns(this.transaction);
this.mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var connectionManager = new ConnectionManager(this.mockConnection.Object);
connectionManager.BeginTransaction(IsolationLevel.ReadCommitted);
this.command = connectionManager.CreateCommand();
}
[Fact]
public void TheCommandShouldBeCreated()
{
this.mockConnection.Verify(x => x.CreateCommand(), Times.Once());
}
[Fact]
public void TheCommandShouldBeReturned()
{
Assert.NotNull(this.command);
}
[Fact]
public void TheTransactionShouldBeSetOnTheCommand()
{
Assert.Equal(this.transaction, this.command.Transaction);
}
}
public class WhenCallingCreateCommandAndThereIsNoCurrentTransaction
{
private readonly IDbCommand command;
private readonly Mock<IDbCommand> mockCommand = new Mock<IDbCommand>();
private readonly Mock<IDbConnection> mockConnection = new Mock<IDbConnection>();
public WhenCallingCreateCommandAndThereIsNoCurrentTransaction()
{
this.mockConnection.Setup(x => x.State).Returns(ConnectionState.Open);
this.mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var connectionManager = new ConnectionManager(this.mockConnection.Object);
this.command = connectionManager.CreateCommand();
}
[Fact]
public void TheCommandShouldBeCreated()
{
this.mockConnection.Verify(x => x.CreateCommand(), Times.Once());
}
[Fact]
public void TheCommandShouldBeReturned()
{
Assert.NotNull(this.command);
}
[Fact]
public void TheTransactionShouldNotBeSetOnTheCommand()
{
this.mockCommand.VerifySet(x => x.Transaction = It.IsAny<IDbTransaction>(), Times.Never());
}
}
public class WhenConstructed
{
private readonly ConnectionManager connectionManager = new ConnectionManager(new Mock<IDbConnection>().Object);
[Fact]
public void TheCurrentTransactionShouldBeNull()
{
Assert.Null(this.connectionManager.CurrentTransaction);
}
}
public class WhenDisposed
{
private readonly Mock<IDbConnection> mockConnection = new Mock<IDbConnection>();
private readonly Mock<IDbTransaction> mockTransaction = new Mock<IDbTransaction>();
public WhenDisposed()
{
this.mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
this.mockConnection.Setup(x => x.BeginTransaction(It.IsAny<IsolationLevel>())).Returns(this.mockTransaction.Object);
using (var connectionManager = new ConnectionManager(this.mockConnection.Object))
{
connectionManager.BeginTransaction(IsolationLevel.ReadCommitted);
}
}
[Fact]
public void TheConnectionShouldBeClosed()
{
this.mockConnection.Verify(x => x.Close(), Times.Once());
}
[Fact]
public void TheConnectionShouldBeDisposed()
{
this.mockConnection.Verify(x => x.Dispose(), Times.Once());
}
[Fact]
public void TheTransactionShouldBeDisposed()
{
this.mockTransaction.Verify(x => x.Dispose(), Times.Once());
}
}
}
}<file_sep>namespace MicroLite.Tests.Dialect
{
using System;
using System.Data;
using MicroLite.Dialect;
using MicroLite.Mapping;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="MySqlDialect"/> class.
/// </summary>
public class MySqlDialectTests : IDisposable
{
public MySqlDialectTests()
{
// The tests in this suite all use attribute mapping for the test.
ObjectInfo.MappingConvention = new AttributeMappingConvention();
}
private enum CustomerStatus
{
Inactive = 0,
Active = 1
}
public void Dispose()
{
// Reset the mapping convention after tests have run.
ObjectInfo.MappingConvention = new ConventionMappingConvention(ConventionMappingSettings.Default);
}
[Fact]
public void InsertQueryForDbGeneratedInstance()
{
var customer = new Customer
{
Created = DateTime.Now,
DateOfBirth = new System.DateTime(1975, 9, 18),
Name = "<NAME>",
Status = CustomerStatus.Active
};
var sqlDialect = new MySqlDialect();
var sqlQuery = sqlDialect.CreateQuery(StatementType.Insert, customer);
Assert.Equal("INSERT INTO `Customers` (`Created`, `DoB`, `Name`, `StatusId`) VALUES (@p0, @p1, @p2, @p3);SELECT LAST_INSERT_ID()", sqlQuery.CommandText);
Assert.Equal(customer.Created, sqlQuery.Arguments[0]);
Assert.Equal(customer.DateOfBirth, sqlQuery.Arguments[1]);
Assert.Equal(customer.Name, sqlQuery.Arguments[2]);
Assert.Equal((int)customer.Status, sqlQuery.Arguments[3]);
}
[Fact]
public void PageNonQualifiedQuery()
{
var sqlQuery = new SqlQuery("SELECT CustomerId, Name, DoB, StatusId FROM Customers");
var sqlDialect = new MySqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT CustomerId, Name, DoB, StatusId FROM Customers LIMIT @p0,@p1", paged.CommandText);
Assert.Equal(0, paged.Arguments[0]);////, "The first argument should be the number of records to skip");
Assert.Equal(25, paged.Arguments[1]);////, "The second argument should be the number of records to return");
}
[Fact]
public void PageNonQualifiedWildcardQuery()
{
var sqlQuery = new SqlQuery("SELECT * FROM Customers");
var sqlDialect = new MySqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT * FROM Customers LIMIT @p0,@p1", paged.CommandText);
Assert.Equal(0, paged.Arguments[0]);////, "The first argument should be the number of records to skip");
Assert.Equal(25, paged.Arguments[1]);////, "The second argument should be the number of records to return");
}
[Fact]
public void PageWithMultiWhereAndMultiOrderByMultiLine()
{
var sqlQuery = new SqlQuery(@"SELECT
""CustomerId"",
""Name"",
""DoB"",
""StatusId""
FROM
""Customers""
WHERE
(""StatusId"" = @p0 AND ""DoB"" > @p1)
ORDER BY
""Name"" ASC,
""DoB"" ASC", new object[] { CustomerStatus.Active, new DateTime(1980, 01, 01) });
var sqlDialect = new MySqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT \"CustomerId\", \"Name\", \"DoB\", \"StatusId\" FROM \"Customers\" WHERE (\"StatusId\" = @p0 AND \"DoB\" > @p1) ORDER BY \"Name\" ASC, \"DoB\" ASC LIMIT @p2,@p3", paged.CommandText);
Assert.Equal(sqlQuery.Arguments[0], paged.Arguments[0]);////, "The first argument should be the first argument from the original query");
Assert.Equal(sqlQuery.Arguments[1], paged.Arguments[1]);////, "The second argument should be the second argument from the original query");
Assert.Equal(0, paged.Arguments[2]);////, "The third argument should be the number of records to skip");
Assert.Equal(25, paged.Arguments[3]);////, "The fourth argument should be the number of records to return");
}
[Fact]
public void PageWithNoWhereButOrderBy()
{
var sqlQuery = new SqlQuery("SELECT \"CustomerId\", \"Name\", \"DoB\", \"StatusId\" FROM \"Customers\" ORDER BY \"CustomerId\" ASC");
var sqlDialect = new MySqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT \"CustomerId\", \"Name\", \"DoB\", \"StatusId\" FROM \"Customers\" ORDER BY \"CustomerId\" ASC LIMIT @p0,@p1", paged.CommandText);
Assert.Equal(0, paged.Arguments[0]);////, "The first argument should be the number of records to skip");
Assert.Equal(25, paged.Arguments[1]);////, "The second argument should be the number of records to return");
}
[Fact]
public void PageWithNoWhereOrOrderByFirstResultsPage()
{
var sqlQuery = new SqlQuery("SELECT\"CustomerId\",\"Name\",\"DoB\",\"StatusId\" FROM \"Customers\"");
var sqlDialect = new MySqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT\"CustomerId\",\"Name\",\"DoB\",\"StatusId\" FROM \"Customers\" LIMIT @p0,@p1", paged.CommandText);
Assert.Equal(0, paged.Arguments[0]);////, "The first argument should be the number of records to skip");
Assert.Equal(25, paged.Arguments[1]);////, "The second argument should be the number of records to return");
}
[Fact]
public void PageWithNoWhereOrOrderBySecondResultsPage()
{
var sqlQuery = new SqlQuery("SELECT\"CustomerId\",\"Name\",\"DoB\",\"StatusId\" FROM \"Customers\"");
var sqlDialect = new MySqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 2, resultsPerPage: 25));
Assert.Equal("SELECT\"CustomerId\",\"Name\",\"DoB\",\"StatusId\" FROM \"Customers\" LIMIT @p0,@p1", paged.CommandText);
Assert.Equal(25, paged.Arguments[0]);////, "The first argument should be the number of records to skip");
Assert.Equal(25, paged.Arguments[1]);////, "The second argument should be the number of records to return");
}
[Fact]
public void PageWithWhereAndOrderBy()
{
var sqlQuery = new SqlQuery("SELECT\"CustomerId\",\"Name\",\"DoB\",\"StatusId\" FROM \"Customers\" WHERE\"StatusId\" = @p0 ORDER BY\"Name\" ASC", CustomerStatus.Active);
var sqlDialect = new MySqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT\"CustomerId\",\"Name\",\"DoB\",\"StatusId\" FROM \"Customers\" WHERE\"StatusId\" = @p0 ORDER BY\"Name\" ASC LIMIT @p1,@p2", paged.CommandText);
Assert.Equal(sqlQuery.Arguments[0], paged.Arguments[0]);////, "The first argument should be the first argument from the original query");
Assert.Equal(0, paged.Arguments[1]);////, "The second argument should be the number of records to skip");
Assert.Equal(25, paged.Arguments[2]);////, "The third argument should be the number of records to return");
}
[Fact]
public void PageWithWhereAndOrderByMultiLine()
{
var sqlQuery = new SqlQuery(@"SELECT
""CustomerId"",
""Name"",
""DoB"",
""StatusId""
FROM
""Customers""
WHERE
""StatusId"" = @p0
ORDER BY
""Name"" ASC", new object[] { CustomerStatus.Active });
var sqlDialect = new MySqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT\"CustomerId\",\"Name\",\"DoB\",\"StatusId\" FROM \"Customers\" WHERE\"StatusId\" = @p0 ORDER BY\"Name\" ASC LIMIT @p1,@p2", paged.CommandText);
Assert.Equal(sqlQuery.Arguments[0], paged.Arguments[0]);////, "The first argument should be the first argument from the original query");
Assert.Equal(0, paged.Arguments[1]);////, "The second argument should be the number of records to skip");
Assert.Equal(25, paged.Arguments[2]);////, "The third argument should be the number of records to return");
}
[Fact]
public void PageWithWhereButNoOrderBy()
{
var sqlQuery = new SqlQuery("SELECT\"CustomerId\",\"Name\",\"DoB\",\"StatusId\" FROM \"Customers\" WHERE\"StatusId\" = @p0", CustomerStatus.Active);
var sqlDialect = new MySqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT\"CustomerId\",\"Name\",\"DoB\",\"StatusId\" FROM \"Customers\" WHERE\"StatusId\" = @p0 LIMIT @p1,@p2", paged.CommandText);
Assert.Equal(sqlQuery.Arguments[0], paged.Arguments[0]);////, "The first argument should be the first argument from the original query");
Assert.Equal(0, paged.Arguments[1]);////, "The second argument should be the number of records to skip");
Assert.Equal(25, paged.Arguments[2]);////, "The third argument should be the number of records to return");
}
[MicroLite.Mapping.Table("Customers")]
private class Customer
{
public Customer()
{
}
[MicroLite.Mapping.Column("Created", allowInsert: true, allowUpdate: false)]
public DateTime Created
{
get;
set;
}
[MicroLite.Mapping.Column("DoB")]
public DateTime DateOfBirth
{
get;
set;
}
[MicroLite.Mapping.Column("CustomerId")]
[MicroLite.Mapping.Identifier(IdentifierStrategy.DbGenerated)]
public int Id
{
get;
set;
}
[MicroLite.Mapping.Column("Name")]
public string Name
{
get;
set;
}
[MicroLite.Mapping.Column("StatusId")]
public CustomerStatus Status
{
get;
set;
}
[MicroLite.Mapping.Column("Updated", allowInsert: false, allowUpdate: true)]
public DateTime? Updated
{
get;
set;
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="ITypeConverter.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.TypeConverters
{
using System;
/// <summary>
/// The interface for a class which can convert between property type values and database values.
/// </summary>
public interface ITypeConverter
{
/// <summary>
/// Determines whether this type converter can convert values for the specified property type.
/// </summary>
/// <param name="propertyType">The type of the property value to be converted.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified property type; otherwise, <c>false</c>.
/// </returns>
bool CanConvert(Type propertyType);
/// <summary>
/// Converts the specified database value into an instance of the property type.
/// </summary>
/// <param name="value">The database value to be converted.</param>
/// <param name="propertyType">The property type to convert to.</param>
/// <returns>An instance of the specified property type containing the specified value.</returns>
object ConvertFromDbValue(object value, Type propertyType);
/// <summary>
/// Converts the specified property value into an instance of the database value.
/// </summary>
/// <param name="value">The property value to be converted.</param>
/// <param name="propertyType">The property type to convert from.</param>
/// <returns>An instance of the corresponding database type for the property type containing the property value.</returns>
object ConvertToDbValue(object value, Type propertyType);
}
}<file_sep>namespace MicroLite.Tests.Configuration
{
using System;
using MicroLite.Configuration;
using MicroLite.Logging;
using MicroLite.Mapping;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="ConfigureExtensions"/> class.
/// </summary>
public class ConfigureExtensionsTests
{
public class WhenCallingSetLogResolver : IDisposable
{
private readonly Func<string, ILog> resolver = (s) =>
{
return null;
};
public WhenCallingSetLogResolver()
{
// Ensure that the GetLogger method is cleared before each test.
LogManager.GetLogger = null;
var configureExtensions = new ConfigureExtensions();
configureExtensions.SetLogResolver(this.resolver);
}
public void Dispose()
{
// Ensure that the GetLogger method is cleared after all tests have been run.
LogManager.GetLogger = null;
}
[Fact]
public void TheLogManagerGetLoggerMethodShouldBeSet()
{
Assert.Same(this.resolver, LogManager.GetLogger);
}
}
public class WhenCallingSetMappingConvention : IDisposable
{
private readonly IMappingConvention mappingConvention = new Mock<IMappingConvention>().Object;
public WhenCallingSetMappingConvention()
{
// Ensure that the MappingConvention is cleared before each test.
ObjectInfo.MappingConvention = null;
var configureExtensions = new ConfigureExtensions();
configureExtensions.SetMappingConvention(this.mappingConvention);
}
public void Dispose()
{
// Ensure that the MappingConvention is set to the default after all tests have been run.
ObjectInfo.MappingConvention = new AttributeMappingConvention();
}
[Fact]
public void TheObjectInfoMappingConventionShouldBeSet()
{
Assert.Same(this.mappingConvention, ObjectInfo.MappingConvention);
}
}
public class WhenCallingSetMappingConventionAndTheMappingConventionIsNull
{
[Fact]
public void AnArgumentNullExceptionShouldBeThrown()
{
var configureExtensions = new ConfigureExtensions();
var exception = Assert.Throws<ArgumentNullException>(() => configureExtensions.SetMappingConvention(null));
Assert.Equal("mappingConvention", exception.ParamName);
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="CollectionExtensions.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.FrameworkExtensions
{
using System;
using System.Collections.Generic;
internal static class CollectionExtensions
{
internal static void Each<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
{
action(item);
}
}
internal static IEnumerable<T> Reverse<T>(this IList<T> source)
{
for (int i = source.Count - 1; i >= 0; i--)
{
yield return source[i];
}
}
}
}<file_sep>namespace MicroLite.Tests.Integration
{
using System;
public class Invoice
{
public DateTime Created
{
get;
set;
}
public string CreatedBy
{
get;
set;
}
public int CustomerId
{
get;
set;
}
public int InvoiceId
{
get;
set;
}
public int Number
{
get;
set;
}
public DateTime? PaymentProcessed
{
get;
set;
}
public DateTime? PaymentReceived
{
get;
set;
}
public InvoiceStatus Status
{
get;
set;
}
public decimal Total
{
get;
set;
}
}
}<file_sep>namespace MicroLite.Tests.Query
{
using MicroLite.Query;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="SqlBuilder"/> class.
/// </summary>
public class SqlBuilderTests
{
[Fact]
public void ExecuteReuturnsNewBuilderOnEachCall()
{
var sqlBuilder1 = SqlBuilder.Execute("GetCustomerInvoices");
var sqlBuilder2 = SqlBuilder.Execute("GetCustomerInvoices");
Assert.NotSame(sqlBuilder1, sqlBuilder2);
}
[Fact]
public void SelectReuturnsNewBuilderOnEachCall()
{
var sqlBuilder1 = SqlBuilder.Select("*");
var sqlBuilder2 = SqlBuilder.Select("*");
Assert.NotSame(sqlBuilder1, sqlBuilder2);
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="IHavingOrOrderBy.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Query
{
/// <summary>
/// The interface which specifies the having method in the fluent sql builder syntax.
/// </summary>
public interface IHavingOrOrderBy : IHideObjectMethods, IOrderBy
{
/// <summary>
/// Specifies the having clause for the query.
/// </summary>
/// <param name="predicate">The predicate.</param>
/// <param name="value">The argument value.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IOrderBy Having(string predicate, object value);
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="GuidGenerator.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite
{
using System;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading;
/// <summary>
/// A class for generating guids using our comb implementation.
/// </summary>
/// <remarks>
/// Loosely based upon <NAME>'s implementation <![CDATA[http://www.developmentalmadness.com/archive/2010/10/13/sequential-guid-algorithm-ndash-improving-the-algorithm.aspx]]>
/// </remarks>
internal static class GuidGenerator
{
private static readonly NetworkInterfaceType[] ignoredInterfaceTypes = new[] { NetworkInterfaceType.Loopback, NetworkInterfaceType.Tunnel };
// This call is quite slow so we do it once.
private static readonly byte[] nicBytes = NetworkInterface
.GetAllNetworkInterfaces()
.Where(ix => !ignoredInterfaceTypes.Contains(ix.NetworkInterfaceType))
.OrderBy(ix => ix.OperationalStatus)
.ThenByDescending(ix => ix.Speed)
.First()
.GetPhysicalAddress()
.GetAddressBytes();
private static long sequentialCounter = 0;
/// <summary>
/// Creates a new Guid using our comb implementation.
/// </summary>
/// <returns>A new Guid.</returns>
internal static Guid CreateComb()
{
return CreateComb(DateTime.UtcNow);
}
/// <summary>
/// Creates a new Guid using our comb implementation.
/// </summary>
/// <param name="dateTime">The date time to use as the seed for the guid.</param>
/// <returns>A new Guid</returns>
internal static Guid CreateComb(DateTime dateTime)
{
var increment = Interlocked.Increment(ref sequentialCounter);
byte[] tickBytes = BitConverter.GetBytes(dateTime.Ticks + increment);
var guidBytes = new byte[16];
guidBytes[0] = (byte)dateTime.Month;
guidBytes[1] = (byte)dateTime.Day;
guidBytes[2] = (byte)dateTime.Hour;
guidBytes[3] = (byte)dateTime.Minute;
guidBytes[4] = (byte)dateTime.Second;
guidBytes[5] = nicBytes[3];
guidBytes[6] = nicBytes[4];
guidBytes[7] = nicBytes[5];
guidBytes[8] = tickBytes[1];
guidBytes[9] = tickBytes[0];
guidBytes[10] = tickBytes[7];
guidBytes[11] = tickBytes[6];
guidBytes[12] = tickBytes[5];
guidBytes[13] = tickBytes[4];
guidBytes[14] = tickBytes[3];
guidBytes[15] = tickBytes[2];
return new Guid(guidBytes);
}
}
}<file_sep>using System;
using System.Xml.Linq;
using MicroLite.TypeConverters;
using Xunit;
namespace MicroLite.Tests.TypeConverters
{
public class TypeConverterTests
{
private enum Status
{
Default = 0,
New = 1
}
public class WhenCallingForWithATypeOfEnum
{
[Fact]
public void TheEnumTypeConverterIsReturned()
{
var typeConverter = TypeConverter.For(typeof(Status));
Assert.IsType<EnumTypeConverter>(typeConverter);
}
}
public class WhenCallingForWithATypeOfInt
{
[Fact]
public void TheObjectTypeConverterIsReturned()
{
var typeConverter = TypeConverter.For(typeof(int));
Assert.IsType<ObjectTypeConverter>(typeConverter);
}
}
public class WhenCallingForWithATypeOfXDocument
{
[Fact]
public void TheXDocumentTypeConverterIsReturned()
{
var typeConverter = TypeConverter.For(typeof(XDocument));
Assert.IsType<XDocumentTypeConverter>(typeConverter);
}
}
public class WhenCallingResolveActualTypeWithNullType
{
[Fact]
public void AnArgumentNullExceptionIsThrown()
{
Assert.Throws<ArgumentNullException>(() => TypeConverter.ResolveActualType(null));
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="TableInfo.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Mapping
{
using System;
using System.Collections.Generic;
using System.Linq;
using MicroLite.FrameworkExtensions;
using MicroLite.Logging;
/// <summary>
/// A class which contains information about a database table .
/// </summary>
[System.Diagnostics.DebuggerDisplay("{Schema}.{Name}")]
public sealed class TableInfo
{
private static readonly ILog log = LogManager.GetCurrentClassLog();
private readonly IList<ColumnInfo> columns;
private readonly string identifierColumn;
private readonly string identifierProperty;
private readonly IdentifierStrategy identifierStrategy;
private readonly string name;
private readonly string schema;
/// <summary>
/// Initialises a new instance of the <see cref="TableInfo"/> class.
/// </summary>
/// <param name="columns">The columns that are mapped for the table.</param>
/// <param name="identifierStrategy">The identifier strategy used by the table.</param>
/// <param name="name">The name of the table.</param>
/// <param name="schema">The name of the schema the table exists within.</param>
/// <exception cref="ArgumentNullException">Thrown if columns or name are null.</exception>
/// <exception cref="MicroLiteException">Thrown if no identifier column is specified.</exception>
public TableInfo(
IList<ColumnInfo> columns,
IdentifierStrategy identifierStrategy,
string name,
string schema)
{
if (columns == null)
{
throw new ArgumentNullException("columns");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
this.identifierStrategy = identifierStrategy;
this.name = name;
this.schema = schema;
this.ValidateColumns(columns);
this.columns = new System.Collections.ObjectModel.ReadOnlyCollection<ColumnInfo>(columns);
var identifierColumnInfo = columns.Single(c => c.IsIdentifier);
this.identifierColumn = identifierColumnInfo.ColumnName;
this.identifierProperty = identifierColumnInfo.PropertyInfo.Name;
}
/// <summary>
/// Gets the columns that are mapped for the table.
/// </summary>
public IList<ColumnInfo> Columns
{
get
{
return this.columns;
}
}
/// <summary>
/// Gets the name of the column that is the table identifier column (primary key).
/// </summary>
public string IdentifierColumn
{
get
{
return this.identifierColumn;
}
}
/// <summary>
/// Gets the name of the property that is the object identifier property mapped to the table identifier column.
/// </summary>
public string IdentifierProperty
{
get
{
return this.identifierProperty;
}
}
/// <summary>
/// Gets the identifier strategy used by the table.
/// </summary>
public IdentifierStrategy IdentifierStrategy
{
get
{
return this.identifierStrategy;
}
}
/// <summary>
/// Gets the name of the table.
/// </summary>
public string Name
{
get
{
return this.name;
}
}
/// <summary>
/// Gets the name of the schema the table exists within.
/// </summary>
public string Schema
{
get
{
return this.schema;
}
}
private void ValidateColumns(IEnumerable<ColumnInfo> mappedColumns)
{
var duplicatedColumn = mappedColumns
.GroupBy(c => c.ColumnName)
.Select(x => new
{
Key = x.Key,
Count = x.Count()
})
.FirstOrDefault(x => x.Count > 1);
if (duplicatedColumn != null)
{
log.TryLogFatal(Messages.TableInfo_ColumnMappedMultipleTimes, duplicatedColumn.Key);
throw new MicroLiteException(Messages.TableInfo_ColumnMappedMultipleTimes.FormatWith(duplicatedColumn.Key));
}
if (!mappedColumns.Any(c => c.IsIdentifier))
{
log.TryLogFatal(Messages.TableInfo_NoIdentifierColumn, this.schema, this.name);
throw new MicroLiteException(Messages.TableInfo_NoIdentifierColumn.FormatWith(this.schema, this.name));
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="StringExtensions.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.FrameworkExtensions
{
using System.Globalization;
internal static class StringExtensions
{
internal static string FormatWith(this string value, params string[] args)
{
return string.Format(CultureInfo.InvariantCulture, value, args);
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="LogExtensions.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Logging
{
using System;
using System.Diagnostics;
/// <summary>
/// Extension methods for the <see cref="ILog"/> interface to simplify writing to the log since there is no
/// guarantee that an <see cref="ILog"/> is in use.
/// </summary>
public static class LogExtensions
{
private static readonly bool debuggerAttached = Debugger.IsAttached;
/// <summary>
/// Writes the message to the log as a debug statement.
/// </summary>
/// <param name="log">The log to write to.</param>
/// <param name="message">The message to be logged.</param>
/// <param name="formatArgs">The format args.</param>
public static void TryLogDebug(this ILog log, string message, params string[] formatArgs)
{
if (log != null)
{
if (formatArgs != null && formatArgs.Length > 0)
{
log.Debug(message, formatArgs);
}
else
{
log.Debug(message);
}
}
}
/// <summary>
/// Writes the message to the log as an error.
/// </summary>
/// <param name="log">The log to write to.</param>
/// <param name="message">The message to be logged.</param>
/// <param name="formatArgs">The format args.</param>
public static void TryLogError(this ILog log, string message, params string[] formatArgs)
{
if (log != null)
{
if (formatArgs != null && formatArgs.Length > 0)
{
log.Error(message, formatArgs);
}
else
{
log.Error(message);
}
}
if (debuggerAttached)
{
Trace.TraceError(message, formatArgs);
}
}
/// <summary>
/// Writes the message to the log as an error along with the exception that occurred.
/// </summary>
/// <param name="log">The log to write to.</param>
/// <param name="message">The message to be logged.</param>
/// <param name="exception">The exception that occurred.</param>
public static void TryLogError(this ILog log, string message, Exception exception)
{
if (log != null)
{
log.Error(message, exception);
}
if (debuggerAttached)
{
Trace.TraceError(message);
}
}
/// <summary>
/// Writes the message to the log as fatal.
/// </summary>
/// <param name="log">The log to write to.</param>
/// <param name="message">The message to be logged.</param>
/// <param name="formatArgs">The format args.</param>
public static void TryLogFatal(this ILog log, string message, params string[] formatArgs)
{
if (log != null)
{
if (formatArgs != null && formatArgs.Length > 0)
{
log.Fatal(message, formatArgs);
}
else
{
log.Fatal(message);
}
}
if (debuggerAttached)
{
Trace.TraceError(message, formatArgs);
}
}
/// <summary>
/// Writes the message to the log as fatal along with the exception that occurred.
/// </summary>
/// <param name="log">The log to write to.</param>
/// <param name="message">The message to be logged.</param>
/// <param name="exception">The exception that occurred.</param>
public static void TryLogFatal(this ILog log, string message, Exception exception)
{
if (log != null)
{
log.Fatal(message, exception);
}
if (debuggerAttached)
{
Trace.TraceError(message);
}
}
/// <summary>
/// Writes the message to the log as information.
/// </summary>
/// <param name="log">The log to write to.</param>
/// <param name="message">The message to be logged.</param>
/// <param name="formatArgs">The format args.</param>
public static void TryLogInfo(this ILog log, string message, params string[] formatArgs)
{
if (log != null)
{
if (formatArgs != null && formatArgs.Length > 0)
{
log.Info(message, formatArgs);
}
else
{
log.Info(message);
}
}
}
/// <summary>
/// Writes the message to the log as a warning.
/// </summary>
/// <param name="log">The log to write to.</param>
/// <param name="message">The message to be logged.</param>
/// <param name="formatArgs">The format args.</param>
public static void TryLogWarn(this ILog log, string message, params string[] formatArgs)
{
if (log != null)
{
if (formatArgs != null && formatArgs.Length > 0)
{
log.Warn(message, formatArgs);
}
else
{
log.Warn(message);
}
}
if (debuggerAttached)
{
Trace.TraceWarning(message, formatArgs);
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="SqlCharacters.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite
{
using System;
using System.Globalization;
using System.Linq;
/// <summary>
/// A class containing the SQL characters for an SQL Dialect.
/// </summary>
public abstract class SqlCharacters
{
private static SqlCharacters empty;
private static SqlCharacters msSql;
private static SqlCharacters mySql;
private static SqlCharacters postgreSql;
private static SqlCharacters sqlite;
/// <summary>
/// Gets an Empty set of SqlCharacters.
/// </summary>
public static SqlCharacters Empty
{
get
{
return empty ?? (empty = new EmptySqlCharacters());
}
}
/// <summary>
/// Gets the SqlCharacters for MS SQL.
/// </summary>
public static SqlCharacters MsSql
{
get
{
return msSql ?? (msSql = new MsSqlCharacters());
}
}
/// <summary>
/// Gets the SqlCharacters for MySql.
/// </summary>
public static SqlCharacters MySql
{
get
{
return mySql ?? (mySql = new MySqlCharacters());
}
}
/// <summary>
/// Gets the SqlCharacters for PostgreSql.
/// </summary>
public static SqlCharacters PostgreSql
{
get
{
return postgreSql ?? (postgreSql = new PostgreSqlCharacters());
}
}
/// <summary>
/// Gets the SqlCharacters for SQLite.
/// </summary>
public static SqlCharacters SQLite
{
get
{
return sqlite ?? (sqlite = new SQLiteCharacters());
}
}
/// <summary>
/// Gets the left delimiter character.
/// </summary>
public virtual string LeftDelimiter
{
get
{
return "\"";
}
}
/// <summary>
/// Gets the wildcard for use in like statements.
/// </summary>
public virtual string LikeWildcard
{
get
{
return "%";
}
}
/// <summary>
/// Gets the right delimiter character.
/// </summary>
public virtual string RightDelimiter
{
get
{
return "\"";
}
}
/// <summary>
/// Gets the wildcard for use in select statements.
/// </summary>
public virtual string SelectWildcard
{
get
{
return "*";
}
}
/// <summary>
/// Gets the SQL parameter.
/// </summary>
public virtual string SqlParameter
{
get
{
return "?";
}
}
/// <summary>
/// Gets the character used to separate SQL statements.
/// </summary>
public virtual string StatementSeparator
{
get
{
return ";";
}
}
/// <summary>
/// Gets a value indicating whether SQL parameters are named.
/// </summary>
public virtual bool SupportsNamedParameters
{
get
{
return false;
}
}
/// <summary>
/// Escapes the specified SQL using the left and right delimiters.
/// </summary>
/// <param name="sql">The SQL to be escaped.</param>
/// <returns>The escaped SQL.</returns>
public string EscapeSql(string sql)
{
if (sql == null)
{
throw new ArgumentNullException("sql");
}
if (this.IsEscaped(sql))
{
return sql;
}
var sqlPieces = sql.Split('.');
#if NET_3_5
return string.Join(".", sqlPieces.Select(s => this.LeftDelimiter + s + this.RightDelimiter).ToArray());
#else
return string.Join(".", sqlPieces.Select(s => this.LeftDelimiter + s + this.RightDelimiter));
#endif
}
/// <summary>
/// Gets the name of the parameter for the specified position.
/// </summary>
/// <param name="position">The parameter position.</param>
/// <returns>The nape of the parameter for the specified position.</returns>
public string GetParameterName(int position)
{
if (this.SupportsNamedParameters)
{
return this.SqlParameter + "p" + position.ToString(CultureInfo.InvariantCulture);
}
return this.SqlParameter;
}
/// <summary>
/// Determines whether the specified SQL is escaped.
/// </summary>
/// <param name="sql">The SQL to check.</param>
/// <returns>
/// <c>true</c> if the specified SQL is escaped; otherwise, <c>false</c>.
/// </returns>
public bool IsEscaped(string sql)
{
if (string.IsNullOrEmpty(sql))
{
return false;
}
return sql.StartsWith(this.LeftDelimiter, StringComparison.Ordinal) && sql.EndsWith(this.RightDelimiter, StringComparison.Ordinal);
}
private sealed class EmptySqlCharacters : SqlCharacters
{
public override string LeftDelimiter
{
get
{
return string.Empty;
}
}
public override string RightDelimiter
{
get
{
return string.Empty;
}
}
}
private sealed class MsSqlCharacters : SqlCharacters
{
public override string LeftDelimiter
{
get
{
return "[";
}
}
public override string RightDelimiter
{
get
{
return "]";
}
}
public override string SqlParameter
{
get
{
return "@";
}
}
public override bool SupportsNamedParameters
{
get
{
return true;
}
}
}
private sealed class MySqlCharacters : SqlCharacters
{
public override string LeftDelimiter
{
get
{
return "`";
}
}
public override string RightDelimiter
{
get
{
return "`";
}
}
public override string SqlParameter
{
get
{
return "@";
}
}
public override bool SupportsNamedParameters
{
get
{
return true;
}
}
}
private sealed class PostgreSqlCharacters : SqlCharacters
{
public override string SqlParameter
{
get
{
return ":";
}
}
public override bool SupportsNamedParameters
{
get
{
return true;
}
}
}
private sealed class SQLiteCharacters : SqlCharacters
{
public override string SqlParameter
{
get
{
return "@";
}
}
public override bool SupportsNamedParameters
{
get
{
return true;
}
}
}
}
}<file_sep>namespace MicroLite.Tests.Integration
{
using System;
public class Customer
{
public int CustomerId
{
get;
set;
}
public DateTime DateOfBirth
{
get;
set;
}
public string EmailAddress
{
get;
set;
}
public string Forename
{
get;
set;
}
public CustomerStatus Status
{
get;
set;
}
public string Surname
{
get;
set;
}
}
}<file_sep>using System;
using MicroLite.TypeConverters;
using Xunit;
namespace MicroLite.Tests.TypeConverters
{
public class ObjectTypeConverterTests
{
private enum Status
{
Default = 0,
New = 1
}
public class WhenCallingCanConvertWithATypeWhichIsAnEnum
{
[Fact]
public void TrueShouldBeReturned()
{
// Although an exlicit type converter exists for enums, ObjectTypeConverter should not discriminate against any type.
// This is so we don't have to modify it to ignore types for which there is a specific converter.
var typeConverter = new ObjectTypeConverter();
Assert.True(typeConverter.CanConvert(typeof(Status)));
}
}
public class WhenCallingCanConvertWithATypeWhichIsAnInt
{
[Fact]
public void TrueShouldBeReturned()
{
var typeConverter = new ObjectTypeConverter();
Assert.True(typeConverter.CanConvert(typeof(int)));
}
}
public class WhenCallingCanConvertWithATypeWhichIsANullableInt
{
[Fact]
public void TrueShouldBeReturned()
{
var typeConverter = new ObjectTypeConverter();
Assert.True(typeConverter.CanConvert(typeof(int?)));
}
}
public class WhenCallingConvertFromDbValueAndPropertyTypeIsNull
{
[Fact]
public void AnArgumentNullExceptionShouldBeThrown()
{
var typeConverter = new ObjectTypeConverter();
var exception = Assert.Throws<ArgumentNullException>(() => typeConverter.ConvertFromDbValue(1, null));
Assert.Equal("propertyType", exception.ParamName);
}
}
public class WhenCallingConvertFromDbValueForANullableIntWithANonNullValue
{
private object result;
private ITypeConverter typeConverter = new ObjectTypeConverter();
public WhenCallingConvertFromDbValueForANullableIntWithANonNullValue()
{
this.result = typeConverter.ConvertFromDbValue(1, typeof(int?));
}
[Fact]
public void TheCorrectValueShouldBeReturned()
{
Assert.Equal(1, this.result);
}
}
public class WhenCallingConvertFromDbValueForANullableIntWithANullValue
{
private object result;
private ITypeConverter typeConverter = new ObjectTypeConverter();
public WhenCallingConvertFromDbValueForANullableIntWithANullValue()
{
this.result = typeConverter.ConvertFromDbValue(DBNull.Value, typeof(int?));
}
[Fact]
public void NullShouldBeReturned()
{
Assert.Null(this.result);
}
}
public class WhenCallingConvertFromDbValueWithAByteAndATypeOfInt
{
private object result;
private ITypeConverter typeConverter = new ObjectTypeConverter();
public WhenCallingConvertFromDbValueWithAByteAndATypeOfInt()
{
this.result = typeConverter.ConvertFromDbValue((byte)1, typeof(int));
}
[Fact]
public void TheCorrectValueShouldBeReturned()
{
Assert.Equal(1, this.result);
}
[Fact]
public void TheResultShouldBeUpCast()
{
Assert.IsType<int>(this.result);
}
}
public class WhenCallingConvertFromDbValueWithALongAndATypeOfInt
{
private object result;
private ITypeConverter typeConverter = new ObjectTypeConverter();
public WhenCallingConvertFromDbValueWithALongAndATypeOfInt()
{
this.result = typeConverter.ConvertFromDbValue((long)1, typeof(int));
}
[Fact]
public void TheCorrectValueShouldBeReturned()
{
Assert.Equal(1, this.result);
}
[Fact]
public void TheResultShouldBeDownCast()
{
Assert.IsType<int>(this.result);
}
}
public class WhenCallingConvertToDbValue
{
private object result;
private ITypeConverter typeConverter = new ObjectTypeConverter();
private string value = "Foo";
public WhenCallingConvertToDbValue()
{
this.result = this.typeConverter.ConvertToDbValue(value, typeof(string));
}
[Fact]
public void TheSameValueShouldBeReturned()
{
Assert.Same(this.value, this.result);
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="ConnectionManager.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Core
{
using System.Data;
using MicroLite.Logging;
/// <summary>
/// The default implementation of <see cref="IConnectionManager"/>.
/// </summary>
internal sealed class ConnectionManager : IConnectionManager
{
private static readonly ILog log = LogManager.GetCurrentClassLog();
private IDbConnection connection;
private ITransaction currentTransaction;
internal ConnectionManager(IDbConnection connection)
{
this.connection = connection;
}
public ITransaction CurrentTransaction
{
get
{
return this.currentTransaction;
}
}
public ITransaction BeginTransaction(IsolationLevel isolationLevel)
{
if (this.currentTransaction == null || !this.currentTransaction.IsActive)
{
log.TryLogDebug(Messages.ConnectionManager_BeginTransactionWithIsolationLevel, isolationLevel.ToString());
this.connection.Open();
var dbTransaction = this.connection.BeginTransaction(isolationLevel);
this.currentTransaction = new AdoTransaction(dbTransaction);
}
return this.currentTransaction;
}
public void CommandCompleted(IDbCommand command)
{
if (command.Transaction == null)
{
log.TryLogDebug(Messages.ConnectionManager_ClosingConnection);
command.Connection.Close();
}
}
public IDbCommand CreateCommand()
{
if (this.connection.State == ConnectionState.Closed)
{
log.TryLogDebug(Messages.ConnectionManager_OpeningConnection);
this.connection.Open();
}
log.TryLogDebug(Messages.ConnectionManager_CreatingCommand);
var command = this.connection.CreateCommand();
if (this.currentTransaction != null)
{
log.TryLogDebug(Messages.ConnectionManager_EnlistingInTransaction);
this.currentTransaction.Enlist(command);
}
return command;
}
public void Dispose()
{
if (this.connection != null)
{
this.connection.Close();
this.connection.Dispose();
this.connection = null;
}
if (this.currentTransaction != null)
{
this.currentTransaction.Dispose();
this.currentTransaction = null;
}
}
}
}<file_sep>namespace MicroLite.Tests.Dialect
{
using System;
using System.Data;
using MicroLite.Dialect;
using MicroLite.FrameworkExtensions;
using MicroLite.Mapping;
using MicroLite.Query;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="MsSqlDialect"/> class.
/// </summary>
public class MsSqlDialectTests : IDisposable
{
public MsSqlDialectTests()
{
// The tests in this suite all use attribute mapping for the test.
ObjectInfo.MappingConvention = new AttributeMappingConvention();
SqlBuilder.SqlCharacters = null;
}
private enum CustomerStatus
{
Inactive = 0,
Active = 1
}
/// <summary>
/// Issue #6 - The argument count check needs to cater for the same argument being used twice.
/// </summary>
[Fact]
public void BuildCommandForSqlQueryWithSqlTextWhichUsesSameParameterTwice()
{
var sqlQuery = new SqlQuery(
"SELECT * FROM [Table] WHERE [Table].[Id] = @p0 AND [Table].[Value1] = @p1 OR @p1 IS NULL",
new object[] { 100, "hello" });
using (var command = new System.Data.SqlClient.SqlCommand())
{
var sqlDialect = new MsSqlDialect();
sqlDialect.BuildCommand(command, sqlQuery);
Assert.Equal(sqlQuery.CommandText, command.CommandText);
Assert.Equal(CommandType.Text, command.CommandType);
Assert.Equal(2, command.Parameters.Count);
var parameter1 = (IDataParameter)command.Parameters[0];
Assert.Equal(ParameterDirection.Input, parameter1.Direction);
Assert.Equal("@p0", parameter1.ParameterName);
Assert.Equal(sqlQuery.Arguments[0], parameter1.Value);
var parameter2 = (IDataParameter)command.Parameters[1];
Assert.Equal(ParameterDirection.Input, parameter2.Direction);
Assert.Equal("@p1", parameter2.ParameterName);
Assert.Equal(sqlQuery.Arguments[1], parameter2.Value);
}
}
[Fact]
public void BuildCommandForSqlQueryWithStoredProcedureWithoutParameters()
{
var sqlQuery = new SqlQuery("EXEC GetTableContents");
using (var command = new System.Data.SqlClient.SqlCommand())
{
var sqlDialect = new MsSqlDialect();
sqlDialect.BuildCommand(command, sqlQuery);
// The command text should only contain the stored procedure name.
Assert.Equal("GetTableContents", command.CommandText);
Assert.Equal(CommandType.StoredProcedure, command.CommandType);
Assert.Equal(0, command.Parameters.Count);
}
}
[Fact]
public void BuildCommandForSqlQueryWithStoredProcedureWithParameters()
{
var sqlQuery = new SqlQuery(
"EXEC GetTableContents @identifier, @Cust_Name",
new object[] { 100, "hello" });
using (var command = new System.Data.SqlClient.SqlCommand())
{
var sqlDialect = new MsSqlDialect();
sqlDialect.BuildCommand(command, sqlQuery);
// The command text should only contain the stored procedure name.
Assert.Equal("GetTableContents", command.CommandText);
Assert.Equal(CommandType.StoredProcedure, command.CommandType);
Assert.Equal(2, command.Parameters.Count);
var parameter1 = (IDataParameter)command.Parameters[0];
Assert.Equal("@identifier", parameter1.ParameterName);
Assert.Equal(sqlQuery.Arguments[0], parameter1.Value);
var parameter2 = (IDataParameter)command.Parameters[1];
Assert.Equal("@Cust_Name", parameter2.ParameterName);
Assert.Equal(sqlQuery.Arguments[1], parameter2.Value);
}
}
[Fact]
public void BuildCommandThrowsMicroLiteExceptionForParameterCountMismatch()
{
var sqlQuery = new SqlQuery(
"SELECT * FROM [Table] WHERE [Table].[Id] = @p0 AND [Table].[Value] = @p1",
new object[] { 100 });
using (var command = new System.Data.SqlClient.SqlCommand())
{
var sqlDialect = new MsSqlDialect();
var exception = Assert.Throws<MicroLiteException>(
() => sqlDialect.BuildCommand(command, sqlQuery));
Assert.Equal(Messages.SqlDialect_ArgumentsCountMismatch.FormatWith("2", "1"), exception.Message);
}
}
public void Dispose()
{
// Reset the mapping convention after tests have run.
ObjectInfo.MappingConvention = new ConventionMappingConvention(ConventionMappingSettings.Default);
SqlBuilder.SqlCharacters = null;
}
[Fact]
public void InsertQueryForIdentityInstance()
{
var customer = new Customer
{
Created = DateTime.Now,
DateOfBirth = new System.DateTime(1975, 9, 18),
Name = "<NAME>",
Status = CustomerStatus.Active
};
var sqlDialect = new MsSqlDialect();
var sqlQuery = sqlDialect.CreateQuery(StatementType.Insert, customer);
Assert.Equal("INSERT INTO [Sales].[Customers] ([Created], [DoB], [Name], [StatusId]) VALUES (@p0, @p1, @p2, @p3);SELECT SCOPE_IDENTITY()", sqlQuery.CommandText);
Assert.Equal(customer.Created, sqlQuery.Arguments[0]);
Assert.Equal(customer.DateOfBirth, sqlQuery.Arguments[1]);
Assert.Equal(customer.Name, sqlQuery.Arguments[2]);
Assert.Equal((int)customer.Status, sqlQuery.Arguments[3]);
}
/// <summary>
/// Issue #206 - Session.Paged errors if the query includes a sub query
/// </summary>
[Fact]
public void PagedQueryWithoutSubQuery()
{
SqlBuilder.SqlCharacters = SqlCharacters.MsSql;
var sqlQuerySingleLevel = SqlBuilder
.Select("*").From(typeof(Customer))
.Where("Name LIKE @p0", "Fred%")
.ToSqlQuery();
MsSqlDialect msSqlDialect = new MsSqlDialect();
SqlQuery pageQuerySingleLevel = msSqlDialect.PageQuery(sqlQuerySingleLevel, PagingOptions.ForPage(page: 2, resultsPerPage: 10));
Assert.Equal("SELECT [Created], [DoB], [CustomerId], [Name], [StatusId], [Updated] FROM (SELECT [Created], [DoB], [CustomerId], [Name], [StatusId], [Updated], ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber FROM [Sales].[Customers] WHERE (Name LIKE @p0)) AS [Customers] WHERE (RowNumber >= @p1 AND RowNumber <= @p2)", pageQuerySingleLevel.CommandText);
Assert.Equal("Fred%", pageQuerySingleLevel.Arguments[0]);
Assert.Equal(11, pageQuerySingleLevel.Arguments[1]);
Assert.Equal(20, pageQuerySingleLevel.Arguments[2]);
}
/// <summary>
/// Issue #206 - Session.Paged errors if the query includes a sub query
/// </summary>
[Fact]
public void PagedQueryWithSubQuery()
{
SqlBuilder.SqlCharacters = SqlCharacters.MsSql;
var sqlQuerySubQuery = SqlBuilder
.Select("*")
.From(typeof(Customer))
.Where("Name LIKE @p0", "Fred%")
.AndWhere("SourceId").In(new SqlQuery("SELECT SourceId FROM Source WHERE Status = @p0", 1))
.ToSqlQuery();
MsSqlDialect msSqlDialect = new MsSqlDialect();
SqlQuery pageQuerySubQuery = msSqlDialect.PageQuery(sqlQuerySubQuery, PagingOptions.ForPage(page: 2, resultsPerPage: 10));
Assert.Equal("SELECT [Created], [DoB], [CustomerId], [Name], [StatusId], [Updated] FROM (SELECT [Created], [DoB], [CustomerId], [Name], [StatusId], [Updated], ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber FROM [Sales].[Customers] WHERE (Name LIKE @p0) AND ([SourceId] IN (SELECT SourceId FROM Source WHERE Status = @p1))) AS [Customers] WHERE (RowNumber >= @p2 AND RowNumber <= @p3)", pageQuerySubQuery.CommandText);
Assert.Equal("Fred%", pageQuerySubQuery.Arguments[0]);
Assert.Equal(1, pageQuerySubQuery.Arguments[1]);
Assert.Equal(11, pageQuerySubQuery.Arguments[2]);
Assert.Equal(20, pageQuerySubQuery.Arguments[3]);
}
[Fact]
public void PageNonQualifiedQuery()
{
var sqlQuery = new SqlQuery("SELECT CustomerId, Name, DoB, StatusId FROM Customers");
var sqlDialect = new MsSqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT CustomerId, Name, DoB, StatusId FROM (SELECT CustomerId, Name, DoB, StatusId, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber FROM Customers) AS Customers WHERE (RowNumber >= @p0 AND RowNumber <= @p1)", paged.CommandText);
Assert.Equal(1, paged.Arguments[0]);////, "The first argument should be the start row number");
Assert.Equal(25, paged.Arguments[1]);////, "The second argument should be the end row number");
}
[Fact]
public void PageNonQualifiedWildcardQuery()
{
var sqlQuery = new SqlQuery("SELECT * FROM Customers");
var sqlDialect = new MsSqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT * FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber FROM Customers) AS Customers WHERE (RowNumber >= @p0 AND RowNumber <= @p1)", paged.CommandText);
Assert.Equal(1, paged.Arguments[0]);////, "The first argument should be the start row number");
Assert.Equal(25, paged.Arguments[1]);////, "The second argument should be the end row number");
}
[Fact]
public void PageWithMultiWhereAndMultiOrderByMultiLine()
{
var sqlQuery = new SqlQuery(@"SELECT
[Customers].[CustomerId],
[Customers].[Name],
[Customers].[DoB],
[Customers].[StatusId]
FROM
[Sales].[Customers]
WHERE
([Customers].[StatusId] = @p0 AND [Customers].[DoB] > @p1)
ORDER BY
[Customers].[Name] ASC,
[Customers].[DoB] ASC", new object[] { CustomerStatus.Active, new DateTime(1980, 01, 01) });
var sqlDialect = new MsSqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId] FROM (SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId], ROW_NUMBER() OVER(ORDER BY [Customers].[Name] ASC, [Customers].[DoB] ASC) AS RowNumber FROM [Sales].[Customers] WHERE ([Customers].[StatusId] = @p0 AND [Customers].[DoB] > @p1)) AS [Customers] WHERE (RowNumber >= @p2 AND RowNumber <= @p3)", paged.CommandText);
Assert.Equal(sqlQuery.Arguments[0], paged.Arguments[0]);////, "The first argument should be the first argument from the original query");
Assert.Equal(sqlQuery.Arguments[1], paged.Arguments[1]);////, "The second argument should be the second argument from the original query");
Assert.Equal(1, paged.Arguments[2]);////, "The third argument should be the start row number");
Assert.Equal(25, paged.Arguments[3]);////, "The fourth argument should be the end row number");
}
[Fact]
public void PageWithNoWhereButOrderBy()
{
var sqlQuery = new SqlQuery("SELECT [CustomerId], [Name], [DoB], [StatusId] FROM [dbo].[Customers] ORDER BY [CustomerId] ASC");
var sqlDialect = new MsSqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT [CustomerId], [Name], [DoB], [StatusId] FROM (SELECT [CustomerId], [Name], [DoB], [StatusId], ROW_NUMBER() OVER(ORDER BY [CustomerId] ASC) AS RowNumber FROM [dbo].[Customers]) AS [Customers] WHERE (RowNumber >= @p0 AND RowNumber <= @p1)", paged.CommandText);
Assert.Equal(1, paged.Arguments[0]);////, "The first argument should be the start row number");
Assert.Equal(25, paged.Arguments[1]);////, "The second argument should be the end row number");
}
[Fact]
public void PageWithNoWhereOrOrderByFirstResultsPage()
{
var sqlQuery = new SqlQuery("SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId] FROM [Sales].[Customers]");
var sqlDialect = new MsSqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId] FROM (SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId], ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber FROM [Sales].[Customers]) AS [Customers] WHERE (RowNumber >= @p0 AND RowNumber <= @p1)", paged.CommandText);
Assert.Equal(1, paged.Arguments[0]);////, "The first argument should be the start row number");
Assert.Equal(25, paged.Arguments[1]);////, "The second argument should be the end row number");
}
[Fact]
public void PageWithNoWhereOrOrderBySecondResultsPage()
{
var sqlQuery = new SqlQuery("SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId] FROM [Sales].[Customers]");
var sqlDialect = new MsSqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 2, resultsPerPage: 25));
Assert.Equal("SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId] FROM (SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId], ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber FROM [Sales].[Customers]) AS [Customers] WHERE (RowNumber >= @p0 AND RowNumber <= @p1)", paged.CommandText);
Assert.Equal(26, paged.Arguments[0]);////, "The first argument should be the start row number");
Assert.Equal(50, paged.Arguments[1]);////, "The second argument should be the end row number");
}
[Fact]
public void PageWithWhereAndOrderBy()
{
var sqlQuery = new SqlQuery("SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId] FROM [Sales].[Customers] WHERE [Customers].[StatusId] = @p0 ORDER BY [Customers].[Name] ASC", CustomerStatus.Active);
var sqlDialect = new MsSqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId] FROM (SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId], ROW_NUMBER() OVER(ORDER BY [Customers].[Name] ASC) AS RowNumber FROM [Sales].[Customers] WHERE [Customers].[StatusId] = @p0) AS [Customers] WHERE (RowNumber >= @p1 AND RowNumber <= @p2)", paged.CommandText);
Assert.Equal(sqlQuery.Arguments[0], paged.Arguments[0]);////, "The first argument should be the first argument from the original query");
Assert.Equal(1, paged.Arguments[1]);////, "The second argument should be the start row number");
Assert.Equal(25, paged.Arguments[2]);////, "The third argument should be the end row number");
}
[Fact]
public void PageWithWhereAndOrderByMultiLine()
{
var sqlQuery = new SqlQuery(@"SELECT
[Customers].[CustomerId],
[Customers].[Name],
[Customers].[DoB],
[Customers].[StatusId]
FROM
[Sales].[Customers]
WHERE
[Customers].[StatusId] = @p0
ORDER BY
[Customers].[Name] ASC", new object[] { CustomerStatus.Active });
var sqlDialect = new MsSqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId] FROM (SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId], ROW_NUMBER() OVER(ORDER BY [Customers].[Name] ASC) AS RowNumber FROM [Sales].[Customers] WHERE [Customers].[StatusId] = @p0) AS [Customers] WHERE (RowNumber >= @p1 AND RowNumber <= @p2)", paged.CommandText);
Assert.Equal(sqlQuery.Arguments[0], paged.Arguments[0]);////, "The first argument should be the first argument from the original query");
Assert.Equal(1, paged.Arguments[1]);////, "The second argument should be the start row number");
Assert.Equal(25, paged.Arguments[2]);////, "The third argument should be the end row number");
}
[Fact]
public void PageWithWhereButNoOrderBy()
{
var sqlQuery = new SqlQuery("SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId] FROM [Sales].[Customers] WHERE [Customers].[StatusId] = @p0", CustomerStatus.Active);
var sqlDialect = new MsSqlDialect();
var paged = sqlDialect.PageQuery(sqlQuery, PagingOptions.ForPage(page: 1, resultsPerPage: 25));
Assert.Equal("SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId] FROM (SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId], ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber FROM [Sales].[Customers] WHERE [Customers].[StatusId] = @p0) AS [Customers] WHERE (RowNumber >= @p1 AND RowNumber <= @p2)", paged.CommandText);
Assert.Equal(sqlQuery.Arguments[0], paged.Arguments[0]);////, "The first argument should be the first argument from the original query");
Assert.Equal(1, paged.Arguments[1]);////, "The second argument should be the start row number");
Assert.Equal(25, paged.Arguments[2]);////, "The third argument should be the end row number");
}
public class WhenCallingCombine
{
private readonly SqlQuery combinedQuery;
private readonly SqlQuery sqlQuery1;
private readonly SqlQuery sqlQuery2;
public WhenCallingCombine()
{
this.sqlQuery1 = new SqlQuery("SELECT [Column1], [Column2], [Column3] FROM [dbo].[Table1] WHERE [Column1] = @p0 AND [Column2] > @p1", "Foo", 100);
this.sqlQuery1.Timeout = 38;
this.sqlQuery2 = new SqlQuery("SELECT [Column_1], [Column_2] FROM [dbo].[Table_2] WHERE ([Column_1] = @p0 OR @p0 IS NULL) AND [Column_2] < @p1", "Bar", -1);
this.sqlQuery2.Timeout = 42;
var sqlDialect = new MsSqlDialect();
this.combinedQuery = sqlDialect.Combine(new[] { this.sqlQuery1, this.sqlQuery2 });
}
[Fact]
public void TheCombinedArgumentsShouldContainTheFirstArgumentOfTheFirstQuery()
{
Assert.Equal(this.sqlQuery1.Arguments[0], this.combinedQuery.Arguments[0]);
}
[Fact]
public void TheCombinedArgumentsShouldContainTheFirstArgumentOfTheSecondQuery()
{
Assert.Equal(this.sqlQuery2.Arguments[0], this.combinedQuery.Arguments[2]);
}
[Fact]
public void TheCombinedArgumentsShouldContainTheNumberOfArgumentsInTheSourceQueries()
{
Assert.Equal(this.sqlQuery1.Arguments.Count + this.sqlQuery2.Arguments.Count, this.combinedQuery.Arguments.Count);
}
[Fact]
public void TheCombinedArgumentsShouldContainTheSecondArgumentOfTheFirstQuery()
{
Assert.Equal(this.sqlQuery1.Arguments[1], this.combinedQuery.Arguments[1]);
}
[Fact]
public void TheCombinedArgumentsShouldContainTheSecondArgumentOfTheSecondQuery()
{
Assert.Equal(this.sqlQuery2.Arguments[1], this.combinedQuery.Arguments[3]);
}
[Fact]
public void TheCombinedCommandTextShouldBeSeparatedUsingTheSelectSeparator()
{
Assert.Equal(
"SELECT [Column1], [Column2], [Column3] FROM [dbo].[Table1] WHERE [Column1] = @p0 AND [Column2] > @p1;\r\nSELECT [Column_1], [Column_2] FROM [dbo].[Table_2] WHERE ([Column_1] = @p2 OR @p2 IS NULL) AND [Column_2] < @p3",
this.combinedQuery.CommandText);
}
[Fact]
public void TheTimeoutShouldBeSetToTheLongestTimeoutOfTheSourceQueries()
{
Assert.Equal(this.sqlQuery2.Timeout, this.combinedQuery.Timeout);
}
}
/// <summary>
/// Issue #90 - Re-Writing parameters should not happen if the query is a stored procedure.
/// </summary>
public class WhenCallingCombineAndAnSqlQueryIsForAStoredProcedure
{
private readonly SqlQuery combinedQuery;
private readonly SqlQuery sqlQuery1;
private readonly SqlQuery sqlQuery2;
public WhenCallingCombineAndAnSqlQueryIsForAStoredProcedure()
{
this.sqlQuery1 = new SqlQuery("SELECT [Column1], [Column2], [Column3] FROM [dbo].[Table1] WHERE [Column1] = @p0 AND [Column2] > @p1", "Foo", 100);
this.sqlQuery2 = new SqlQuery("EXEC CustomersByStatus @StatusId", 2);
var sqlDialect = new MsSqlDialect();
this.combinedQuery = sqlDialect.Combine(new[] { this.sqlQuery1, this.sqlQuery2 });
}
[Fact]
public void TheParameterNamesForTheStoredProcedureShouldNotBeRenamed()
{
Assert.Equal(
"SELECT [Column1], [Column2], [Column3] FROM [dbo].[Table1] WHERE [Column1] = @p0 AND [Column2] > @p1;\r\nEXEC CustomersByStatus @StatusId",
this.combinedQuery.CommandText);
}
}
public class WhenCallingCombineAndTheSourceQueriesIsNull
{
[Fact]
public void AnArgumentNullExceptionShouldBeThrown()
{
var sqlDialect = new MsSqlDialect();
var exception = Assert.Throws<ArgumentNullException>(() => sqlDialect.Combine(null));
Assert.Equal("sqlQueries", exception.ParamName);
}
}
[MicroLite.Mapping.Table(schema: "Sales", name: "Customers")]
private class Customer
{
public Customer()
{
}
[MicroLite.Mapping.Column("Created", allowInsert: true, allowUpdate: false)]
public DateTime Created
{
get;
set;
}
[MicroLite.Mapping.Column("DoB")]
public DateTime DateOfBirth
{
get;
set;
}
[MicroLite.Mapping.Column("CustomerId")]
[MicroLite.Mapping.Identifier(IdentifierStrategy.DbGenerated)]
public int Id
{
get;
set;
}
[MicroLite.Mapping.Column("Name")]
public string Name
{
get;
set;
}
[MicroLite.Mapping.Column("StatusId")]
public CustomerStatus Status
{
get;
set;
}
[MicroLite.Mapping.Column("Updated", allowInsert: false, allowUpdate: true)]
public DateTime? Updated
{
get;
set;
}
}
}
}<file_sep>namespace MicroLite.Tests.Mapping
{
using System;
using System.Linq;
using System.Reflection;
using MicroLite.Mapping;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="ConventionMappingConvention"/> class.
/// </summary>
public class ConventionMappingConventionTests
{
private enum CustomerStatus
{
Inactive = 0,
Active = 1
}
public class WhenCallingCreateObjectInfoAndTypeIsNull
{
[Fact]
public void AnArgumentNullExceptionIsThrown()
{
var mappingConvention = new ConventionMappingConvention(new ConventionMappingSettings());
var exception = Assert.Throws<ArgumentNullException>(
() => mappingConvention.CreateObjectInfo(null));
Assert.Equal("forType", exception.ParamName);
}
}
public class WhenNotUsingDefaultSettings
{
private readonly IObjectInfo objectInfo;
public WhenNotUsingDefaultSettings()
{
var mappingConvention = new ConventionMappingConvention(new ConventionMappingSettings
{
AllowInsert = (PropertyInfo propertyInfo) =>
{
return propertyInfo.Name != "Updated";
},
AllowUpdate = (PropertyInfo propertyInfo) =>
{
return propertyInfo.Name != "Created";
},
IdentifierStrategy = IdentifierStrategy.Assigned,
Ignore = (PropertyInfo propertyInfo) =>
{
return propertyInfo.Name == "NonPersistedValue";
},
TableSchema = "Sales",
UsePluralClassNameForTableName = false
});
this.objectInfo = mappingConvention.CreateObjectInfo(typeof(Customer));
}
[Fact]
public void AgeInYearsShouldNotBeMapped()
{
Assert.False(this.objectInfo.TableInfo.Columns.Any(x => x.ColumnName == "AgeInYears"));
}
[Fact]
public void TheCreatedColumnShouldAllowInsert()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Created").AllowInsert);
}
[Fact]
public void TheCreatedColumnShouldNotAllowUpdate()
{
Assert.False(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Created").AllowUpdate);
}
[Fact]
public void TheCreatedPropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "Created"));
}
[Fact]
public void TheDateOfBirthColumnShouldAllowInsert()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "DateOfBirth").AllowInsert);
}
[Fact]
public void TheDateOfBirthColumnShouldAllowUpdate()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "DateOfBirth").AllowUpdate);
}
[Fact]
public void TheDateOfBirthColumnShouldBeSet()
{
Assert.Equal(typeof(Customer).GetProperty("DateOfBirth"), this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "DateOfBirth").PropertyInfo);
}
[Fact]
public void TheDateOfBirthColumnShouldNotBeIdentifier()
{
Assert.False(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "DateOfBirth").IsIdentifier);
}
[Fact]
public void TheDateOfBirthPropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "DateOfBirth"));
}
[Fact]
public void TheIdColumnShouldAllowInsert()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Id").AllowInsert);
}
[Fact]
public void TheIdColumnShouldBeSet()
{
Assert.Equal(typeof(Customer).GetProperty("Id"), this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Id").PropertyInfo);
}
[Fact]
public void TheIdColumnShouldNotAllowUpdate()
{
Assert.False(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Id").AllowUpdate);
}
[Fact]
public void TheIdentifierColumnShouldBeSet()
{
Assert.Equal("Id", this.objectInfo.TableInfo.IdentifierColumn);
}
[Fact]
public void TheIdentifierPropertyShouldBeSet()
{
Assert.Equal("Id", this.objectInfo.TableInfo.IdentifierProperty);
}
[Fact]
public void TheIdentifierStrategyShouldBeSet()
{
Assert.Equal(IdentifierStrategy.Assigned, this.objectInfo.TableInfo.IdentifierStrategy);
}
[Fact]
public void TheIdPropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "Id"));
}
[Fact]
public void TheIdShouldBeIdentifier()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Id").IsIdentifier);
}
[Fact]
public void TheNameColumnShouldAllowInsert()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Name").AllowInsert);
}
[Fact]
public void TheNameColumnShouldAllowUpdate()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Name").AllowUpdate);
}
[Fact]
public void TheNameColumnShouldBeSet()
{
Assert.Equal(typeof(Customer).GetProperty("Name"), this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Name").PropertyInfo);
}
[Fact]
public void TheNameColumnShouldNotBeIdentifier()
{
Assert.False(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Name").IsIdentifier);
}
[Fact]
public void TheNamePropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "Name"));
}
[Fact]
public void TheNonPersistedValuePropertyShouldNotBeMapped()
{
Assert.Null(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "NonPersistedValue"));
}
[Fact]
public void ThereShouldBe6Columns()
{
Assert.Equal(6, this.objectInfo.TableInfo.Columns.Count());
}
[Fact]
public void TheSchemaShouldBeSet()
{
Assert.Equal("Sales", this.objectInfo.TableInfo.Schema);
}
[Fact]
public void TheStatusColumnShouldAllowInsert()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "CustomerStatusId").AllowInsert);
}
[Fact]
public void TheStatusColumnShouldAllowUpdate()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "CustomerStatusId").AllowUpdate);
}
[Fact]
public void TheStatusColumnShouldBeSet()
{
Assert.Equal(typeof(Customer).GetProperty("Status"), this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "CustomerStatusId").PropertyInfo);
}
[Fact]
public void TheStatusColumnShouldNotBeIdentifier()
{
Assert.False(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "CustomerStatusId").IsIdentifier);
}
[Fact]
public void TheStatusPropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "CustomerStatusId"));
}
[Fact]
public void TheTableNameShouldNotBePluralized()
{
Assert.Equal("Customer", this.objectInfo.TableInfo.Name);
}
[Fact]
public void TheUpdatedColumnShouldAllowUpdate()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Updated").AllowUpdate);
}
[Fact]
public void TheUpdatedColumnShouldNotAllowInsert()
{
Assert.False(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Updated").AllowInsert);
}
[Fact]
public void TheUpdatedPropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "Updated"));
}
}
public class WhenTheClassIdentifierIsPrefixedWithTheClassName
{
private readonly IObjectInfo objectInfo;
public WhenTheClassIdentifierIsPrefixedWithTheClassName()
{
var mappingConvention = new ConventionMappingConvention(new ConventionMappingSettings
{
IdentifierStrategy = IdentifierStrategy.Assigned,
UsePluralClassNameForTableName = false
});
this.objectInfo = mappingConvention.CreateObjectInfo(typeof(Invoice));
}
[Fact]
public void TheIdentifierColumnShouldBeSet()
{
Assert.Equal("InvoiceId", this.objectInfo.TableInfo.IdentifierColumn);
}
[Fact]
public void TheIdentifierPropertyShouldBeSet()
{
Assert.Equal("InvoiceId", this.objectInfo.TableInfo.IdentifierProperty);
}
[Fact]
public void TheInvoiceIdPropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "InvoiceId"));
}
[Fact]
public void TheInvoiceIdShouldBeIdentifier()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "InvoiceId").IsIdentifier);
}
}
public class WhenTheResolveIdentifierColumnNameFunctionIsOverridden
{
private readonly IObjectInfo objectInfo;
public WhenTheResolveIdentifierColumnNameFunctionIsOverridden()
{
var mappingConvention = new ConventionMappingConvention(new ConventionMappingSettings
{
IdentifierStrategy = IdentifierStrategy.Assigned,
ResolveIdentifierColumnName = (PropertyInfo propertyInfo) =>
{
return propertyInfo.DeclaringType.Name + "Id";
},
UsePluralClassNameForTableName = false
});
this.objectInfo = mappingConvention.CreateObjectInfo(typeof(Customer));
}
[Fact]
public void TheIdentifierColumnShouldBeSet()
{
Assert.Equal("CustomerId", this.objectInfo.TableInfo.IdentifierColumn);
}
[Fact]
public void TheIdentifierPropertyShouldBeSet()
{
Assert.Equal("Id", this.objectInfo.TableInfo.IdentifierProperty);
}
[Fact]
public void TheIdPropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "CustomerId"));
}
[Fact]
public void TheIdShouldBeIdentifier()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "CustomerId").IsIdentifier);
}
}
public class WhenUsingDefaultSettings
{
private readonly IObjectInfo objectInfo;
public WhenUsingDefaultSettings()
{
var mappingConvention = new ConventionMappingConvention(ConventionMappingSettings.Default);
this.objectInfo = mappingConvention.CreateObjectInfo(typeof(Customer));
}
[Fact]
public void AgeInYearsShouldNotBeMapped()
{
Assert.False(this.objectInfo.TableInfo.Columns.Any(x => x.ColumnName == "AgeInYears"));
}
[Fact]
public void TheCreatedColumnShouldAllowInsert()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Created").AllowInsert);
}
[Fact]
public void TheCreatedColumnShouldAllowUpdate()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Created").AllowUpdate);
}
[Fact]
public void TheCreatedPropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "Created"));
}
[Fact]
public void TheDateOfBirthColumnShouldAllowInsert()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "DateOfBirth").AllowInsert);
}
[Fact]
public void TheDateOfBirthColumnShouldAllowUpdate()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "DateOfBirth").AllowUpdate);
}
[Fact]
public void TheDateOfBirthColumnShouldBeSet()
{
Assert.Equal(typeof(Customer).GetProperty("DateOfBirth"), this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "DateOfBirth").PropertyInfo);
}
[Fact]
public void TheDateOfBirthColumnShouldNotBeIdentifier()
{
Assert.False(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "DateOfBirth").IsIdentifier);
}
[Fact]
public void TheDateOfBirthPropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "DateOfBirth"));
}
[Fact]
public void TheIdColumnShouldAllowInsert()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Id").AllowInsert);
}
[Fact]
public void TheIdColumnShouldBeSet()
{
Assert.Equal(typeof(Customer).GetProperty("Id"), this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Id").PropertyInfo);
}
[Fact]
public void TheIdColumnShouldNotAllowUpdate()
{
Assert.False(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Id").AllowUpdate);
}
[Fact]
public void TheIdentifierColumnShouldBeSet()
{
Assert.Equal("Id", this.objectInfo.TableInfo.IdentifierColumn);
}
[Fact]
public void TheIdentifierPropertyShouldBeSet()
{
Assert.Equal("Id", this.objectInfo.TableInfo.IdentifierProperty);
}
[Fact]
public void TheIdentifierStrategyShouldBeSet()
{
Assert.Equal(IdentifierStrategy.DbGenerated, this.objectInfo.TableInfo.IdentifierStrategy);
}
[Fact]
public void TheIdPropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "Id"));
}
[Fact]
public void TheIdShouldBeIdentifier()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Id").IsIdentifier);
}
[Fact]
public void TheNameColumnShouldAllowInsert()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Name").AllowInsert);
}
[Fact]
public void TheNameColumnShouldAllowUpdate()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Name").AllowUpdate);
}
[Fact]
public void TheNameColumnShouldBeSet()
{
Assert.Equal(typeof(Customer).GetProperty("Name"), this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Name").PropertyInfo);
}
[Fact]
public void TheNameColumnShouldNotBeIdentifier()
{
Assert.False(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Name").IsIdentifier);
}
[Fact]
public void TheNamePropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "Name"));
}
[Fact]
public void TheNonPersistedValuePropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "NonPersistedValue"));
}
[Fact]
public void ThereShouldBe7Columns()
{
Assert.Equal(7, this.objectInfo.TableInfo.Columns.Count());
}
[Fact]
public void TheSchemaShouldNotBeSet()
{
Assert.Null(this.objectInfo.TableInfo.Schema);
}
[Fact]
public void TheStatusColumnShouldAllowInsert()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "CustomerStatusId").AllowInsert);
}
[Fact]
public void TheStatusColumnShouldAllowUpdate()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "CustomerStatusId").AllowUpdate);
}
[Fact]
public void TheStatusColumnShouldBeSet()
{
Assert.Equal(typeof(Customer).GetProperty("Status"), this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "CustomerStatusId").PropertyInfo);
}
[Fact]
public void TheStatusColumnShouldNotBeIdentifier()
{
Assert.False(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "CustomerStatusId").IsIdentifier);
}
[Fact]
public void TheStatusPropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "CustomerStatusId"));
}
[Fact]
public void TheTableNameShouldBePluralized()
{
Assert.Equal("Customers", this.objectInfo.TableInfo.Name);
}
[Fact]
public void TheUpdatedColumnShouldAllowInsert()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Updated").AllowInsert);
}
[Fact]
public void TheUpdatedColumnShouldAllowUpdate()
{
Assert.True(this.objectInfo.TableInfo.Columns.Single(x => x.ColumnName == "Updated").AllowUpdate);
}
[Fact]
public void TheUpdatedPropertyShouldBeMapped()
{
Assert.NotNull(this.objectInfo.TableInfo.Columns.SingleOrDefault(x => x.ColumnName == "Updated"));
}
}
private class Customer
{
public Customer()
{
}
public int AgeInYears
{
get
{
return DateTime.Today.Year - this.DateOfBirth.Year;
}
}
public DateTime Created
{
get;
set;
}
public DateTime DateOfBirth
{
get;
set;
}
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
public string NonPersistedValue
{
get;
set;
}
public CustomerStatus Status
{
get;
set;
}
public DateTime Updated
{
get;
set;
}
}
private class Invoice
{
public int InvoiceId
{
get;
set;
}
}
}
}<file_sep>namespace MicroLite.Tests.Core
{
using System.Linq;
using MicroLite.Listeners;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="ListenerCollection"/> class.
/// </summary>
public class ListenerCollectionTests
{
public class WhenCallingAdd
{
private readonly ListenerCollection collection = new ListenerCollection();
private readonly TestListener listener = new TestListener();
public WhenCallingAdd()
{
this.collection.Add(this.listener);
}
[Fact]
public void TheCollectionShouldContainTheAddedInstance()
{
var typeConverter = this.collection.SingleOrDefault(t => t == this.listener);
Assert.NotNull(typeConverter);
}
}
public class WhenCallingClear
{
private readonly ListenerCollection collection = new ListenerCollection();
public WhenCallingClear()
{
this.collection.Clear();
}
[Fact]
public void TheCollectionShouldBeEmpty()
{
Assert.Equal(0, this.collection.Count);
}
}
public class WhenCallingCopyTo
{
private readonly IListener[] array;
private readonly ListenerCollection collection = new ListenerCollection();
public WhenCallingCopyTo()
{
this.array = new IListener[collection.Count];
collection.CopyTo(this.array, 0);
}
[Fact]
public void TheItemsInTheArrayShouldMatchTheItemsInTheCollection()
{
for (int i = 0; i < collection.Count; i++)
{
Assert.Same(this.array[i], this.collection.Skip(i).First());
}
}
}
public class WhenCallingRemove
{
private readonly ListenerCollection collection = new ListenerCollection();
private IListener listenerToRemove;
public WhenCallingRemove()
{
listenerToRemove = this.collection.OfType<DbGeneratedListener>().Single();
this.collection.Remove(listenerToRemove);
}
[Fact]
public void TheListenerShouldBeRemoved()
{
Assert.False(this.collection.Contains(listenerToRemove));
}
}
public class WhenCallingTheConstructor
{
private readonly ListenerCollection collection = new ListenerCollection();
[Fact]
public void ConstructorRegistersAssignedListener()
{
var listener = this.collection.OfType<AssignedListener>().SingleOrDefault();
Assert.NotNull(listener);
}
[Fact]
public void ConstructorRegistersDbGeneratedListener()
{
var listener = this.collection.OfType<DbGeneratedListener>().SingleOrDefault();
Assert.NotNull(listener);
}
[Fact]
public void ConstructorRegistersGuidCombListener()
{
var listener = this.collection.OfType<GuidCombListener>().SingleOrDefault();
Assert.NotNull(listener);
}
[Fact]
public void ConstructorRegistersGuidListener()
{
var listener = this.collection.OfType<GuidListener>().SingleOrDefault();
Assert.NotNull(listener);
}
[Fact]
public void TheCollectionShouldNotBeReadOnly()
{
Assert.False(this.collection.IsReadOnly);
}
[Fact]
public void ThereShouldBe4RegisteredListeners()
{
Assert.Equal(4, this.collection.Count);
}
}
public class WhenEnumerating
{
private readonly ListenerCollection collection = new ListenerCollection();
private readonly IListener listener1 = new TestListener();
private readonly IListener listener2 = new TestListener();
public WhenEnumerating()
{
collection.Clear();
collection.Add(new TestListener());
listener1 = collection.Single();
listener2 = collection.Single();
}
[Fact]
public void TheSameInstanceShouldBeReturned()
{
Assert.Same(listener1, listener2);
}
}
private class TestListener : Listener
{
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="ObjectInfo.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Mapping
{
using System;
using System.Collections.Generic;
#if !NET_3_5
using System.Dynamic;
#endif
using System.Linq;
using MicroLite.FrameworkExtensions;
using MicroLite.Logging;
using MicroLite.TypeConverters;
/// <summary>
/// The class which describes a type and the table it is mapped to.
/// </summary>
[System.Diagnostics.DebuggerDisplay("ObjectInfo for {ForType}")]
public sealed class ObjectInfo : IObjectInfo
{
private static readonly ILog log = LogManager.GetCurrentClassLog();
private static IMappingConvention mappingConvention = new ConventionMappingConvention(ConventionMappingSettings.Default);
private static IDictionary<Type, IObjectInfo> objectInfos = new Dictionary<Type, IObjectInfo>
{
#if !NET_3_5
{ typeof(ExpandoObject), new ExpandoObjectInfo() },
{ typeof(object), new ExpandoObjectInfo() } // If the generic argument <dynamic> is used (in ISession.Fetch for example), typeof(T) will return object.
#endif
};
private readonly Type forType;
private readonly Dictionary<string, IPropertyAccessor> propertyAccessors; // key is property name.
private readonly TableInfo tableInfo;
/// <summary>
/// Initialises a new instance of the <see cref="ObjectInfo"/> class.
/// </summary>
/// <param name="forType">The type the object info relates to.</param>
/// <param name="tableInfo">The table info.</param>
/// <exception cref="ArgumentNullException">Thrown if forType or tableInfo are null.</exception>
public ObjectInfo(Type forType, TableInfo tableInfo)
{
if (forType == null)
{
throw new ArgumentNullException("forType");
}
if (tableInfo == null)
{
throw new ArgumentNullException("tableInfo");
}
log.TryLogDebug(Messages.ObjectInfo_MappingTypeToTable, forType.FullName, tableInfo.Schema, tableInfo.Name);
this.forType = forType;
this.tableInfo = tableInfo;
this.propertyAccessors = new Dictionary<string, IPropertyAccessor>(this.tableInfo.Columns.Count);
foreach (var columnInfo in this.tableInfo.Columns)
{
log.TryLogDebug(Messages.ObjectInfo_MappingColumnToProperty, forType.Name, columnInfo.PropertyInfo.Name, columnInfo.ColumnName);
this.propertyAccessors.Add(columnInfo.PropertyInfo.Name, PropertyAccessor.Create(columnInfo.PropertyInfo));
if (columnInfo.IsIdentifier && columnInfo.PropertyInfo.PropertyType.IsValueType)
{
this.DefaultIdentifierValue = (ValueType)Activator.CreateInstance(columnInfo.PropertyInfo.PropertyType);
}
}
}
/// <summary>
/// Gets an object containing the default value for the type of identifier used by the type.
/// </summary>
public object DefaultIdentifierValue
{
get;
private set;
}
/// <summary>
/// Gets type the object info relates to.
/// </summary>
public Type ForType
{
get
{
return this.forType;
}
}
/// <summary>
/// Gets the table info for the type the object info relates to.
/// </summary>
public TableInfo TableInfo
{
get
{
return this.tableInfo;
}
}
internal static IMappingConvention MappingConvention
{
get
{
return ObjectInfo.mappingConvention;
}
set
{
ObjectInfo.mappingConvention = value;
}
}
/// <summary>
/// Gets the object info for the specified type.
/// </summary>
/// <param name="forType">The type to get the object info for.</param>
/// <returns>The <see cref="ObjectInfo"/> for the specified <see cref="Type"/>.</returns>
/// <exception cref="ArgumentNullException">Thrown if forType is null.</exception>
/// <exception cref="MicroLiteException">Thrown if the specified type cannot be used with MicroLite.</exception>
public static IObjectInfo For(Type forType)
{
if (forType == null)
{
throw new ArgumentNullException("forType");
}
IObjectInfo objectInfo;
if (!objectInfos.TryGetValue(forType, out objectInfo))
{
VerifyType(forType);
log.TryLogDebug(Messages.ObjectInfo_CreatingObjectInfo, forType.FullName);
objectInfo = ObjectInfo.MappingConvention.CreateObjectInfo(forType);
var newObjectInfos = new Dictionary<Type, IObjectInfo>(objectInfos);
newObjectInfos[forType] = objectInfo;
objectInfos = newObjectInfos;
}
log.TryLogDebug(Messages.ObjectInfo_RetrievingObjectInfo, forType.FullName);
return objectInfo;
}
/// <summary>
/// Creates a new instance of the type.
/// </summary>
/// <returns>A new instance of the type.</returns>
public object CreateInstance()
{
return Activator.CreateInstance(this.forType);
}
/// <summary>
/// Gets the property value for the object identifier.
/// </summary>
/// <param name="instance">The instance to retrieve the value from.</param>
/// <returns>The value of the identifier property.</returns>
/// <exception cref="ArgumentNullException">Thrown if instance is null.</exception>
/// <exception cref="MicroLiteException">Thrown if the instance is not of the correct type.</exception>
public object GetIdentifierValue(object instance)
{
this.VerifyInstanceIsCorrectTypeForThisObjectInfo(instance);
var value = this.GetPropertyValueForColumn(instance, this.TableInfo.IdentifierColumn);
return value;
}
/// <summary>
/// Gets the property value for the specified property on the specified instance.
/// </summary>
/// <param name="instance">The instance to retrieve the value from.</param>
/// <param name="propertyName">Name of the property to get the value for.</param>
/// <returns>The value of the property.</returns>
public object GetPropertyValue(object instance, string propertyName)
{
this.VerifyInstanceIsCorrectTypeForThisObjectInfo(instance);
IPropertyAccessor propertyAccessor;
if (!this.propertyAccessors.TryGetValue(propertyName, out propertyAccessor))
{
log.TryLogError(Messages.ObjectInfo_UnknownProperty, this.ForType.Name, propertyName);
throw new MicroLiteException(Messages.ObjectInfo_UnknownProperty.FormatWith(this.ForType.Name, propertyName));
}
log.TryLogDebug(Messages.ObjectInfo_GettingPropertyValue, this.ForType.Name, propertyName);
var value = propertyAccessor.GetValue(instance);
return value;
}
/// <summary>
/// Gets the property value from the specified instance and converts it to the correct type for the specified column.
/// </summary>
/// <param name="instance">The instance to retrieve the value from.</param>
/// <param name="columnName">Name of the column to get the value for.</param>
/// <returns>The column value of the property.</returns>
/// <exception cref="ArgumentNullException">Thrown if instance is null.</exception>
/// <exception cref="MicroLiteException">Thrown if the instance is not of the correct type.</exception>
public object GetPropertyValueForColumn(object instance, string columnName)
{
this.VerifyInstanceIsCorrectTypeForThisObjectInfo(instance);
var columnInfo = this.TableInfo.Columns.SingleOrDefault(c => c.ColumnName == columnName);
if (columnInfo == null)
{
log.TryLogError(Messages.ObjectInfo_ColumnNotMapped, columnName, this.ForType.Name);
throw new MicroLiteException(Messages.ObjectInfo_ColumnNotMapped.FormatWith(columnName, this.ForType.Name));
}
log.TryLogDebug(Messages.ObjectInfo_GettingPropertyValueForColumn, this.ForType.Name, columnInfo.PropertyInfo.Name, columnName);
var value = this.propertyAccessors[columnInfo.PropertyInfo.Name].GetValue(instance);
var typeConverter = TypeConverter.For(columnInfo.PropertyInfo.PropertyType);
var converted = typeConverter.ConvertToDbValue(value, columnInfo.PropertyInfo.PropertyType);
return converted;
}
/// <summary>
/// Determines whether the specified instance has the default identifier value.
/// </summary>
/// <param name="instance">The instance.</param>
/// <returns>
/// <c>true</c> if the instance has the default identifier value; otherwise, <c>false</c>.
/// </returns>
public bool HasDefaultIdentifierValue(object instance)
{
this.VerifyInstanceIsCorrectTypeForThisObjectInfo(instance);
var identifierValue = this.GetPropertyValue(instance, this.TableInfo.IdentifierProperty);
bool hasDefaultIdentifier = object.Equals(identifierValue, this.DefaultIdentifierValue);
return hasDefaultIdentifier;
}
/// <summary>
/// Sets the property value for the specified property on the specified instance to the specified value.
/// </summary>
/// <param name="instance">The instance to set the property value on.</param>
/// <param name="propertyName">Name of the property to set the value for.</param>
/// <param name="value">The value to be set.</param>
/// <exception cref="ArgumentNullException">Thrown if instance is null.</exception>
/// <exception cref="MicroLiteException">Thrown if the instance is not of the correct type.</exception>
public void SetPropertyValue(object instance, string propertyName, object value)
{
this.VerifyInstanceIsCorrectTypeForThisObjectInfo(instance);
IPropertyAccessor propertyAccessor;
if (!this.propertyAccessors.TryGetValue(propertyName, out propertyAccessor))
{
log.TryLogError(Messages.ObjectInfo_UnknownProperty, this.ForType.Name, propertyName);
throw new MicroLiteException(Messages.ObjectInfo_UnknownProperty.FormatWith(this.ForType.Name, propertyName));
}
log.TryLogDebug(Messages.IObjectInfo_SettingPropertyValue, this.ForType.Name, propertyName);
propertyAccessor.SetValue(instance, value);
}
/// <summary>
/// Sets the property value of the property mapped to the specified column after converting it to the correct type for the property.
/// </summary>
/// <param name="instance">The instance to set the property value on.</param>
/// <param name="columnName">The name of the column the property is mapped to.</param>
/// <param name="value">The value from the database column to set the property to.</param>
/// <exception cref="ArgumentNullException">Thrown if instance is null.</exception>
/// <exception cref="MicroLiteException">Thrown if the instance is not of the correct type.</exception>
public void SetPropertyValueForColumn(object instance, string columnName, object value)
{
this.VerifyInstanceIsCorrectTypeForThisObjectInfo(instance);
var columnInfo = this.TableInfo.Columns.SingleOrDefault(c => c.ColumnName == columnName);
if (columnInfo == null)
{
log.TryLogError(Messages.ObjectInfo_UnknownColumn, this.ForType.Name, columnName);
throw new MicroLiteException(Messages.ObjectInfo_UnknownColumn.FormatWith(this.ForType.Name, columnName));
}
var typeConverter = TypeConverter.For(columnInfo.PropertyInfo.PropertyType);
var converted = typeConverter.ConvertFromDbValue(value, columnInfo.PropertyInfo.PropertyType);
log.TryLogDebug(Messages.IObjectInfo_SettingPropertyValue, this.ForType.Name, columnInfo.PropertyInfo.Name);
this.propertyAccessors[columnInfo.PropertyInfo.Name].SetValue(instance, converted);
}
private static void VerifyType(Type forType)
{
string message = null;
if (!forType.IsClass)
{
message = Messages.ObjectInfo_TypeMustBeClass.FormatWith(forType.Name);
}
else if (forType.IsAbstract)
{
message = Messages.ObjectInfo_TypeMustNotBeAbstract.FormatWith(forType.Name);
}
else if (forType.GetConstructor(Type.EmptyTypes) == null)
{
message = Messages.ObjectInfo_TypeMustHaveDefaultConstructor.FormatWith(forType.Name);
}
if (message != null)
{
log.TryLogFatal(message);
throw new MicroLiteException(message);
}
}
private void VerifyInstanceIsCorrectTypeForThisObjectInfo(object instance)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
if (instance.GetType() != this.ForType)
{
log.TryLogError(Messages.ObjectInfo_TypeMismatch, instance.GetType().Name, this.ForType.Name);
throw new MicroLiteException(Messages.ObjectInfo_TypeMismatch.FormatWith(instance.GetType().Name, this.ForType.Name));
}
}
}
}<file_sep>namespace MicroLite.Tests.Core
{
using System.Collections.Generic;
using System.Data;
using MicroLite.Core;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="IncludeScalar<T>"/> class.
/// </summary>
public class IncludeScalarTests
{
private enum Status
{
New = 0,
Saved = 1
}
/// <summary>
/// Issue #172 - Cannot use Session.Include.Scalar to return an enum
/// </summary>
public class ForAnEnumTypeWhenBuildValueHasBeenCalledAndThereAreNoResults
{
private IncludeScalar<Status> include = new IncludeScalar<Status>();
private Mock<IDataReader> mockReader = new Mock<IDataReader>();
public ForAnEnumTypeWhenBuildValueHasBeenCalledAndThereAreNoResults()
{
this.mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { false }).Dequeue);
this.include.BuildValue(this.mockReader.Object, new Mock<IObjectBuilder>().Object);
}
[Fact]
public void HasValueShouldBeFalse()
{
Assert.False(this.include.HasValue);
}
[Fact]
public void TheDataReaderShouldBeRead()
{
this.mockReader.VerifyAll();
}
[Fact]
public void ValueShouldBeDefaultValue()
{
Assert.Equal(default(Status), this.include.Value);
}
}
/// <summary>
/// Issue #172 - Cannot use Session.Include.Scalar to return an enum
/// </summary>
public class ForAnEnumTypeWhenBuildValueHasBeenCalledAndThereIsOneResult
{
private IncludeScalar<Status> include = new IncludeScalar<Status>();
private Mock<IDataReader> mockReader = new Mock<IDataReader>();
public ForAnEnumTypeWhenBuildValueHasBeenCalledAndThereIsOneResult()
{
this.mockReader.Setup(x => x.FieldCount).Returns(1);
this.mockReader.Setup(x => x[0]).Returns(1);
this.mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
this.include.BuildValue(this.mockReader.Object, new Mock<IObjectBuilder>().Object);
}
[Fact]
public void HasValueShouldBeTrue()
{
Assert.True(this.include.HasValue);
}
[Fact]
public void TheDataReaderShouldBeRead()
{
this.mockReader.VerifyAll();
}
[Fact]
public void ValueShouldBeSetToTheResult()
{
Assert.Equal(Status.Saved, this.include.Value);
}
}
public class ForAReferenceTypeWhenBuildValueHasBeenCalledAndThereAreNoResults
{
private IncludeScalar<string> include = new IncludeScalar<string>();
private Mock<IDataReader> mockReader = new Mock<IDataReader>();
public ForAReferenceTypeWhenBuildValueHasBeenCalledAndThereAreNoResults()
{
this.mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { false }).Dequeue);
this.include.BuildValue(this.mockReader.Object, new Mock<IObjectBuilder>().Object);
}
[Fact]
public void HasValueShouldBeFalse()
{
Assert.False(this.include.HasValue);
}
[Fact]
public void TheDataReaderShouldBeRead()
{
this.mockReader.VerifyAll();
}
[Fact]
public void ValueShouldBeNull()
{
Assert.Null(this.include.Value);
}
}
public class ForAReferenceTypeWhenBuildValueHasBeenCalledAndThereIsOneResult
{
private IncludeScalar<string> include = new IncludeScalar<string>();
private Mock<IDataReader> mockReader = new Mock<IDataReader>();
public ForAReferenceTypeWhenBuildValueHasBeenCalledAndThereIsOneResult()
{
this.mockReader.Setup(x => x.FieldCount).Returns(1);
this.mockReader.Setup(x => x[0]).Returns("Foo");
this.mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
this.include.BuildValue(this.mockReader.Object, new Mock<IObjectBuilder>().Object);
}
[Fact]
public void HasValueShouldBeTrue()
{
Assert.True(this.include.HasValue);
}
[Fact]
public void TheDataReaderShouldBeRead()
{
this.mockReader.VerifyAll();
}
[Fact]
public void ValueShouldBeSetToTheResult()
{
Assert.Equal("Foo", this.include.Value);
}
}
public class ForAReferenceTypeWhenBuildValueHasNotBeenCalled
{
private IncludeScalar<string> include = new IncludeScalar<string>();
public ForAReferenceTypeWhenBuildValueHasNotBeenCalled()
{
}
[Fact]
public void HasValueShouldBeFalse()
{
Assert.False(this.include.HasValue);
}
[Fact]
public void ValueShouldBeNull()
{
Assert.Null(this.include.Value);
}
}
public class ForAValueTypeWhenBuildValueHasBeenCalledAndThereAreNoResults
{
private IncludeScalar<int> include = new IncludeScalar<int>();
private Mock<IDataReader> mockReader = new Mock<IDataReader>();
public ForAValueTypeWhenBuildValueHasBeenCalledAndThereAreNoResults()
{
this.mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { false }).Dequeue);
this.include.BuildValue(this.mockReader.Object, new Mock<IObjectBuilder>().Object);
}
[Fact]
public void HasValueShouldBeFalse()
{
Assert.False(this.include.HasValue);
}
[Fact]
public void TheDataReaderShouldBeRead()
{
this.mockReader.VerifyAll();
}
[Fact]
public void ValueShouldBeDefaultValue()
{
Assert.Equal(0, this.include.Value);
}
}
public class ForAValueTypeWhenBuildValueHasBeenCalledAndThereIsOneResult
{
private IncludeScalar<int> include = new IncludeScalar<int>();
private Mock<IDataReader> mockReader = new Mock<IDataReader>();
public ForAValueTypeWhenBuildValueHasBeenCalledAndThereIsOneResult()
{
this.mockReader.Setup(x => x.FieldCount).Returns(1);
this.mockReader.Setup(x => x[0]).Returns(10);
this.mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
this.include.BuildValue(this.mockReader.Object, new Mock<IObjectBuilder>().Object);
}
[Fact]
public void HasValueShouldBeTrue()
{
Assert.True(this.include.HasValue);
}
[Fact]
public void TheDataReaderShouldBeRead()
{
this.mockReader.VerifyAll();
}
[Fact]
public void ValueShouldBeSetToTheResult()
{
Assert.Equal(10, this.include.Value);
}
}
public class ForAValueTypeWhenBuildValueHasNotBeenCalled
{
private IncludeScalar<int> include = new IncludeScalar<int>();
public ForAValueTypeWhenBuildValueHasNotBeenCalled()
{
}
[Fact]
public void HasValueShouldBeFalse()
{
Assert.False(this.include.HasValue);
}
[Fact]
public void ValueShouldBeDefaultValue()
{
Assert.Equal(0, this.include.Value);
}
}
public class WhenTheDataReaderContainsMultipleColumns
{
private IncludeScalar<int> include = new IncludeScalar<int>();
private Mock<IDataReader> mockReader = new Mock<IDataReader>();
public WhenTheDataReaderContainsMultipleColumns()
{
this.mockReader.Setup(x => x.FieldCount).Returns(2);
this.mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, true }).Dequeue);
}
[Fact]
public void BuildValueShouldThrowAMicroLiteException()
{
var exception = Assert.Throws<MicroLiteException>(() => include.BuildValue(mockReader.Object, null));
Assert.Equal(Messages.IncludeScalar_MultipleColumns, exception.Message);
}
}
public class WhenTheDataReaderContainsMultipleResults
{
private IncludeScalar<int> include = new IncludeScalar<int>();
private Mock<IDataReader> mockReader = new Mock<IDataReader>();
public WhenTheDataReaderContainsMultipleResults()
{
this.mockReader.Setup(x => x.FieldCount).Returns(1);
this.mockReader.Setup(x => x[0]).Returns(10);
this.mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, true }).Dequeue);
}
[Fact]
public void BuildValueShouldThrowAMicroLiteException()
{
var exception = Assert.Throws<MicroLiteException>(() => include.BuildValue(mockReader.Object, null));
Assert.Equal(Messages.IncludeSingle_SingleResultExpected, exception.Message);
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="TypeConverterCollection.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.TypeConverters
{
using System.Collections.Generic;
/// <summary>
/// The class which contains the ITypeConverters used by the MicroLite ORM framework.
/// </summary>
/// <remarks>The collection acts in the same way as a stack, the last converter added is the first used if it handles the type.</remarks>
public sealed class TypeConverterCollection : ICollection<ITypeConverter>
{
private readonly Stack<ITypeConverter> converters = new Stack<ITypeConverter>();
/// <summary>
/// Initialises a new instance of the <see cref="TypeConverterCollection"/> class.
/// </summary>
public TypeConverterCollection()
{
this.converters.Push(new ObjectTypeConverter());
this.converters.Push(new EnumTypeConverter());
this.converters.Push(new XDocumentTypeConverter());
}
/// <summary>
/// Gets the number of type converters contained in the collection.
/// </summary>
public int Count
{
get
{
return this.converters.Count;
}
}
/// <summary>
/// Gets a value indicating whether the collection is read-only.
/// </summary>
/// <returns>true if the collection is read-only; otherwise, false.</returns>
public bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Adds the specified type converter to the collection of type converters which can be used by MicroLite.
/// </summary>
/// <param name="item">The type converter to be added.</param>
public void Add(ITypeConverter item)
{
this.converters.Push(item);
}
/// <summary>
/// Removes all items from the collection.
/// </summary>
public void Clear()
{
this.converters.Clear();
}
/// <summary>
/// Determines whether the collection contains the specified type converter.
/// </summary>
/// <param name="item">The object to locate in the collection.</param>
/// <returns>
/// true if the item exists in the collection; otherwise, false.
/// </returns>
public bool Contains(ITypeConverter item)
{
return this.converters.Contains(item);
}
/// <summary>
/// Copies the items in the collection to the specified one dimension array at the specified index.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="arrayIndex">Index of the array.</param>
public void CopyTo(ITypeConverter[] array, int arrayIndex)
{
this.converters.CopyTo(array, arrayIndex);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<ITypeConverter> GetEnumerator()
{
return this.converters.GetEnumerator();
}
/// <summary>
/// Removes the specified type converter from the collection.
/// </summary>
/// <param name="item">The type converter to be removed.</param>
/// <returns>
/// true if <paramref name="item" /> was successfully removed from the collection; otherwise, false. This method also returns false if <paramref name="item" /> is not found in the original collection.
/// </returns>
public bool Remove(ITypeConverter item)
{
var existing = this.converters.ToArray();
this.converters.Clear();
bool removed = false;
foreach (var typeConverter in existing)
{
if (typeConverter == item)
{
removed = true;
}
else
{
this.converters.Push(typeConverter);
}
}
return removed;
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}<file_sep>namespace MicroLite.Tests.Core
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using MicroLite.Core;
using MicroLite.Dialect;
using MicroLite.Mapping;
using MicroLite.Query;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="ReadOnlySession"/> class.
/// </summary>
public class ReadOnlySessionTests : IDisposable
{
public ReadOnlySessionTests()
{
SqlBuilder.SqlCharacters = null;
}
[Fact]
public void AdvancedReturnsSameSessionByDifferentInterface()
{
var session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
var advancedSession = session.Advanced;
Assert.Same(session, advancedSession);
}
[Fact]
public void AllCreatesASelectAllQueryExecutesAndReturnsResults()
{
var mockReader = new Mock<IDataReader>();
mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
var reader = mockReader.Object;
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteReader()).Returns(reader);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockObjectBuilder = new Mock<IObjectBuilder>();
mockObjectBuilder.Setup(x => x.BuildInstance<Customer>(It.IsAny<ObjectInfo>(), reader)).Returns(new Customer());
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.SqlCharacters).Returns(SqlCharacters.Empty);
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, SqlBuilder.Select("*").From(typeof(Customer)).ToSqlQuery()));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
mockObjectBuilder.Object);
var customers = session.All<Customer>();
session.ExecutePendingQueries();
Assert.Equal(1, customers.Values.Count);
mockReader.VerifyAll();
mockCommand.VerifyAll();
mockConnectionManager.VerifyAll();
mockObjectBuilder.VerifyAll();
mockSqlDialect.VerifyAll();
}
[Fact]
public void BeginTransactionCallsConnectionManagerBeginTransactionWithReadCommitted()
{
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.BeginTransaction(IsolationLevel.ReadCommitted));
var session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object);
session.BeginTransaction();
mockConnectionManager.VerifyAll();
}
[Fact]
public void BeginTransactionWithIsolationLevelCallsConnectionManagerBeginTransactionWithIsolationLevel()
{
var isolationLevel = IsolationLevel.Chaos;
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.BeginTransaction(isolationLevel));
var session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object);
session.BeginTransaction(isolationLevel);
mockConnectionManager.VerifyAll();
}
[Fact]
public void BeginTransactionWithIsolationLevelThrowsObjectDisposedExceptionIfDisposed()
{
var session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.BeginTransaction(IsolationLevel.ReadCommitted));
}
public void Dispose()
{
SqlBuilder.SqlCharacters = null;
}
[Fact]
public void DisposeDisposesConnectionManager()
{
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.Dispose());
var session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object);
using (session)
{
}
mockConnectionManager.VerifyAll();
}
[Fact]
public void FetchExecutesAndReturnsResults()
{
var sqlQuery = new SqlQuery("");
var mockReader = new Mock<IDataReader>();
mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
var reader = mockReader.Object;
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteReader()).Returns(reader);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockObjectBuilder = new Mock<IObjectBuilder>();
mockObjectBuilder.Setup(x => x.BuildInstance<Customer>(It.IsAny<ObjectInfo>(), reader)).Returns(new Customer());
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, sqlQuery));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
mockObjectBuilder.Object);
var customers = session.Fetch<Customer>(sqlQuery);
Assert.Equal(1, customers.Count);
mockReader.VerifyAll();
mockCommand.VerifyAll();
mockConnectionManager.VerifyAll();
mockObjectBuilder.VerifyAll();
mockSqlDialect.VerifyAll();
}
[Fact]
public void FetchThrowsArgumentNullExceptionForNullSqlQuery()
{
var session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
var exception = Assert.Throws<ArgumentNullException>(() => session.Fetch<Customer>(null));
Assert.Equal("sqlQuery", exception.ParamName);
}
[Fact]
public void FetchThrowsObjectDisposedExceptionIfDisposed()
{
var session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.Fetch<Customer>(null));
}
[Fact]
public void IncludeReturnsSameSessionByDifferentInterface()
{
var session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
var includeSession = session.Include;
Assert.Same(session, includeSession);
}
[Fact]
public void IncludeScalarSqlQueryExecutesAndReturnsResult()
{
var sqlQuery = new SqlQuery("");
var mockReader = new Mock<IDataReader>();
mockReader.Setup(x => x.FieldCount).Returns(1);
mockReader.Setup(x => x[0]).Returns(10);
mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
var reader = mockReader.Object;
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteReader()).Returns(reader);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, sqlQuery));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object);
var includeScalar = session.Include.Scalar<int>(sqlQuery);
session.ExecutePendingQueries();
Assert.Equal(10, includeScalar.Value);
mockReader.VerifyAll();
mockCommand.VerifyAll();
mockConnectionManager.VerifyAll();
mockSqlDialect.VerifyAll();
}
[Fact]
public void IncludeScalarThrowsArgumentNullExceptionForNullSqlQuery()
{
var session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
SqlQuery sqlQuery = null;
var exception = Assert.Throws<ArgumentNullException>(() => session.Include.Scalar<int>(sqlQuery));
Assert.Equal("sqlQuery", exception.ParamName);
}
[Fact]
public void IncludeScalarThrowsObjectDisposedExceptionIfDisposed()
{
var session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.Include.Scalar<int>(new SqlQuery("")));
}
[Fact]
public void MicroLiteExceptionsCaughtByExecutePendingQueriesShouldNotBeWrappedInAnotherMicroLiteException()
{
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildCommand(It.IsAny<IDbCommand>(), It.IsAny<SqlQuery>())).Throws<MicroLiteException>();
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(new Mock<IDbCommand>().Object);
var session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object);
// We need at least 1 queued query otherwise we will get an exception when doing queries.Dequeue() instead.
session.Include.Scalar<int>(new SqlQuery(""));
var exception = Assert.Throws<MicroLiteException>(() => session.ExecutePendingQueries());
Assert.IsNotType<MicroLiteException>(exception.InnerException);
}
[Fact]
public void PagedExecutesAndReturnsResultsForFirstPageWithOnePerPage()
{
var sqlQuery = new SqlQuery("SELECT * FROM TABLE");
var countQuery = new SqlQuery("SELECT COUNT(*) FROM TABLE");
var pagedQuery = new SqlQuery("SELECT * FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber FROM Customers) AS Customers");
var combinedQuery = new SqlQuery("SELECT COUNT(*) FROM TABLE;SELECT * FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber FROM Customers) AS Customers");
var mockReader = new Mock<IDataReader>();
mockReader.Setup(x => x.FieldCount).Returns(1);
mockReader.Setup(x => x[0]).Returns(1000); // Simulate 1000 records in the count query
mockReader.Setup(x => x.NextResult()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false, true, false }).Dequeue);
var reader = mockReader.Object;
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteReader()).Returns(reader);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockObjectBuilder = new Mock<IObjectBuilder>();
mockObjectBuilder.Setup(x => x.BuildInstance<Customer>(It.IsAny<ObjectInfo>(), reader)).Returns(new Customer());
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.SupportsBatchedQueries).Returns(true);
mockSqlDialect.Setup(x => x.CountQuery(sqlQuery)).Returns(countQuery);
mockSqlDialect.Setup(x => x.PageQuery(sqlQuery, PagingOptions.ForPage(1, 1))).Returns(pagedQuery);
mockSqlDialect.Setup(x => x.Combine(It.Is<IEnumerable<SqlQuery>>(c => c.Contains(countQuery) && c.Contains(pagedQuery)))).Returns(combinedQuery);
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, combinedQuery));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
mockObjectBuilder.Object);
var page = session.Paged<Customer>(sqlQuery, PagingOptions.ForPage(1, 1));
Assert.Equal(1, page.Page);
Assert.Equal(1, page.Results.Count);
mockReader.VerifyAll();
mockCommand.VerifyAll();
mockConnectionManager.VerifyAll();
mockObjectBuilder.VerifyAll();
mockSqlDialect.VerifyAll();
}
[Fact]
public void PagedExecutesAndReturnsResultsForFirstPageWithTwentyFivePerPage()
{
var sqlQuery = new SqlQuery("SELECT * FROM TABLE");
var countQuery = new SqlQuery("SELECT COUNT(*) FROM TABLE");
var pagedQuery = new SqlQuery("SELECT * FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber FROM Customers) AS Customers");
var combinedQuery = new SqlQuery("SELECT COUNT(*) FROM TABLE;SELECT * FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber FROM Customers) AS Customers");
var mockReader = new Mock<IDataReader>();
mockReader.Setup(x => x.FieldCount).Returns(1);
mockReader.Setup(x => x[0]).Returns(1000); // Simulate 1000 records in the count query
mockReader.Setup(x => x.NextResult()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false, true, false }).Dequeue);
var reader = mockReader.Object;
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteReader()).Returns(reader);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockObjectBuilder = new Mock<IObjectBuilder>();
mockObjectBuilder.Setup(x => x.BuildInstance<Customer>(It.IsAny<ObjectInfo>(), reader)).Returns(new Customer());
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.SupportsBatchedQueries).Returns(true);
mockSqlDialect.Setup(x => x.CountQuery(sqlQuery)).Returns(countQuery);
mockSqlDialect.Setup(x => x.PageQuery(sqlQuery, PagingOptions.ForPage(1, 25))).Returns(pagedQuery);
mockSqlDialect.Setup(x => x.Combine(It.Is<IEnumerable<SqlQuery>>(c => c.Contains(countQuery) && c.Contains(pagedQuery)))).Returns(combinedQuery);
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, combinedQuery));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
mockObjectBuilder.Object);
var page = session.Paged<Customer>(sqlQuery, PagingOptions.ForPage(1, 25));
Assert.Equal(1, page.Page);
Assert.Equal(1, page.Results.Count);
mockReader.VerifyAll();
mockCommand.VerifyAll();
mockConnectionManager.VerifyAll();
mockObjectBuilder.VerifyAll();
mockSqlDialect.VerifyAll();
}
[Fact]
public void PagedExecutesAndReturnsResultsForTenthPageWithTwentyFivePerPage()
{
var sqlQuery = new SqlQuery("SELECT * FROM TABLE");
var countQuery = new SqlQuery("SELECT COUNT(*) FROM TABLE");
var pagedQuery = new SqlQuery("SELECT * FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber FROM Customers) AS Customers");
var combinedQuery = new SqlQuery("SELECT COUNT(*) FROM TABLE;SELECT * FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber FROM Customers) AS Customers");
var mockReader = new Mock<IDataReader>();
mockReader.Setup(x => x.FieldCount).Returns(1);
mockReader.Setup(x => x[0]).Returns(1000); // Simulate 1000 records in the count query
mockReader.Setup(x => x.NextResult()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false, true, false }).Dequeue);
var reader = mockReader.Object;
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteReader()).Returns(reader);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockObjectBuilder = new Mock<IObjectBuilder>();
mockObjectBuilder.Setup(x => x.BuildInstance<Customer>(It.IsAny<ObjectInfo>(), reader)).Returns(new Customer());
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.SupportsBatchedQueries).Returns(true);
mockSqlDialect.Setup(x => x.CountQuery(sqlQuery)).Returns(countQuery);
mockSqlDialect.Setup(x => x.PageQuery(sqlQuery, PagingOptions.ForPage(10, 25))).Returns(pagedQuery);
mockSqlDialect.Setup(x => x.Combine(It.Is<IEnumerable<SqlQuery>>(c => c.Contains(countQuery) && c.Contains(pagedQuery)))).Returns(combinedQuery);
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, combinedQuery));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
mockObjectBuilder.Object);
var page = session.Paged<Customer>(sqlQuery, PagingOptions.ForPage(10, 25));
Assert.Equal(10, page.Page);
Assert.Equal(1, page.Results.Count);
mockReader.VerifyAll();
mockCommand.VerifyAll();
mockConnectionManager.VerifyAll();
mockObjectBuilder.VerifyAll();
mockSqlDialect.VerifyAll();
}
[Fact]
public void PagedThrowsArgumentNullExceptionForNullSqlQuery()
{
IReadOnlySession session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
var exception = Assert.Throws<ArgumentNullException>(() => session.Paged<Customer>(null, PagingOptions.ForPage(1, 25)));
Assert.Equal("sqlQuery", exception.ParamName);
}
[Fact]
public void PagedThrowsObjectDisposedExceptionIfDisposed()
{
IReadOnlySession session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.Paged<Customer>(null, PagingOptions.ForPage(1, 25)));
}
[Fact]
public void ProjectionExecutesAndReturnsResults()
{
var sqlQuery = new SqlQuery("");
var mockReader = new Mock<IDataReader>();
mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
var reader = mockReader.Object;
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteReader()).Returns(reader);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockObjectBuilder = new Mock<IObjectBuilder>();
mockObjectBuilder.Setup(x => x.BuildInstance<dynamic>(It.IsAny<IObjectInfo>(), reader)).Returns(new ExpandoObject());
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, sqlQuery));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
mockObjectBuilder.Object);
var results = session.Projection(sqlQuery);
Assert.Equal(1, results.Count);
mockReader.VerifyAll();
mockCommand.VerifyAll();
mockConnectionManager.VerifyAll();
mockObjectBuilder.VerifyAll();
mockSqlDialect.VerifyAll();
}
[Fact]
public void ProjectionThrowsArgumentNullExceptionForNullSqlQuery()
{
var session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
var exception = Assert.Throws<ArgumentNullException>(() => session.Projection(null));
Assert.Equal("sqlQuery", exception.ParamName);
}
[Fact]
public void ProjectionThrowsMicroLiteExceptionIfExecuteReaderThrowsException()
{
var sqlQuery = new SqlQuery("");
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteReader()).Throws<InvalidOperationException>();
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(new Mock<ISqlDialect>().Object);
var session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object);
var exception = Assert.Throws<MicroLiteException>(() => session.Projection(sqlQuery));
Assert.NotNull(exception.InnerException);
Assert.Equal(exception.InnerException.Message, exception.Message);
// Command should still be disposed.
mockCommand.Verify(x => x.Dispose());
}
[Fact]
public void ProjectionThrowsObjectDisposedExceptionIfDisposed()
{
var session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.Projection(null));
}
[Fact]
public void SessionFactoryPassedToConstructorIsExposed()
{
var mockSessionFactory = new Mock<ISessionFactory>();
var sessionFactory = mockSessionFactory.Object;
var session = new ReadOnlySession(
sessionFactory,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
Assert.Same(sessionFactory, session.Advanced.SessionFactory);
}
[Fact]
public void SingleIdentifierExecutesAndReturnsNull()
{
object identifier = 100;
var mockReader = new Mock<IDataReader>();
mockReader.Setup(x => x.Read()).Returns(false);
var reader = mockReader.Object;
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteReader()).Returns(reader);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.SqlCharacters).Returns(SqlCharacters.Empty);
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, It.Is<SqlQuery>(s => s.Arguments[0] == identifier)));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
IReadOnlySession session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object);
var customer = session.Single<Customer>(identifier);
Assert.Null(customer);
mockReader.VerifyAll();
mockCommand.VerifyAll();
mockConnectionManager.VerifyAll();
mockSqlDialect.VerifyAll();
}
[Fact]
public void SingleIdentifierExecutesAndReturnsResult()
{
object identifier = 100;
var mockReader = new Mock<IDataReader>();
mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
var reader = mockReader.Object;
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteReader()).Returns(reader);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockObjectBuilder = new Mock<IObjectBuilder>();
mockObjectBuilder.Setup(x => x.BuildInstance<Customer>(It.IsAny<ObjectInfo>(), reader)).Returns(new Customer());
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.SqlCharacters).Returns(SqlCharacters.Empty);
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, It.Is<SqlQuery>(s => s.Arguments[0] == identifier)));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
IReadOnlySession session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
mockObjectBuilder.Object);
var customer = session.Single<Customer>(identifier);
Assert.NotNull(customer);
mockReader.VerifyAll();
mockCommand.VerifyAll();
mockConnectionManager.VerifyAll();
mockObjectBuilder.VerifyAll();
mockSqlDialect.VerifyAll();
}
[Fact]
public void SingleIdentifierThrowsArgumentNullExceptionForNullIdentifier()
{
IReadOnlySession session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
object identifier = null;
var exception = Assert.Throws<ArgumentNullException>(() => session.Single<Customer>(identifier));
Assert.Equal("identifier", exception.ParamName);
}
[Fact]
public void SingleIdentifierThrowsObjectDisposedExceptionIfDisposed()
{
IReadOnlySession session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.Single<Customer>(1));
}
[Fact]
public void SingleSqlQueryExecutesAndReturnsNull()
{
var sqlQuery = new SqlQuery("");
var mockReader = new Mock<IDataReader>();
mockReader.Setup(x => x.Read()).Returns(false);
var reader = mockReader.Object;
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteReader()).Returns(reader);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, sqlQuery));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
IReadOnlySession session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object);
var customer = session.Single<Customer>(sqlQuery);
Assert.Null(customer);
mockReader.VerifyAll();
mockCommand.VerifyAll();
mockConnectionManager.VerifyAll();
}
[Fact]
public void SingleSqlQueryExecutesAndReturnsResult()
{
var sqlQuery = new SqlQuery("");
var mockReader = new Mock<IDataReader>();
mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
var reader = mockReader.Object;
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteReader()).Returns(reader);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockObjectBuilder = new Mock<IObjectBuilder>();
mockObjectBuilder.Setup(x => x.BuildInstance<Customer>(It.IsAny<ObjectInfo>(), reader)).Returns(new Customer());
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, sqlQuery));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
IReadOnlySession session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
mockObjectBuilder.Object);
var customer = session.Single<Customer>(sqlQuery);
Assert.NotNull(customer);
mockReader.VerifyAll();
mockCommand.VerifyAll();
mockConnectionManager.VerifyAll();
mockObjectBuilder.VerifyAll();
}
[Fact]
public void SingleSqlQueryThrowsArgumentNullExceptionForNullSqlQuery()
{
IReadOnlySession session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
SqlQuery sqlQuery = null;
var exception = Assert.Throws<ArgumentNullException>(() => session.Single<Customer>(sqlQuery));
Assert.Equal("sqlQuery", exception.ParamName);
}
[Fact]
public void SingleSqlQueryThrowsObjectDisposedExceptionIfDisposed()
{
IReadOnlySession session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.Single<Customer>(new SqlQuery("")));
}
[Fact]
public void TransactionReturnsConnectionManagerCurrentTransaction()
{
var transaction = new Mock<ITransaction>().Object;
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CurrentTransaction).Returns(transaction);
var session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object);
Assert.Same(transaction, session.Transaction);
}
public class WhenCallingPagedUsingPagingOptionsNone
{
[Fact]
public void AMicroLiteExceptionIsThrown()
{
var session = new ReadOnlySession(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object);
var exception = Assert.Throws<MicroLiteException>(() => session.Paged<Customer>(new SqlQuery(""), PagingOptions.None));
Assert.Equal(Messages.Session_PagingOptionsMustNotBeNone, exception.Message);
}
}
public class WhenExecutingMultipleQueriesAndTheSqlDialectUsedDoesNotSupportBatching
{
private Mock<ISqlDialect> mockSqlDialect = new Mock<ISqlDialect>();
public WhenExecutingMultipleQueriesAndTheSqlDialectUsedDoesNotSupportBatching()
{
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(() =>
{
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteReader()).Returns(() =>
{
var mockReader = new Mock<IDataReader>();
mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
return mockReader.Object;
});
return mockCommand.Object;
});
var mockObjectBuilder = new Mock<IObjectBuilder>();
mockObjectBuilder.Setup(x => x.BuildInstance<Customer>(It.IsAny<ObjectInfo>(), It.IsAny<IDataReader>())).Returns(new Customer());
mockSqlDialect.Setup(x => x.SupportsBatchedQueries).Returns(false);
mockSqlDialect.Setup(x => x.SqlCharacters).Returns(SqlCharacters.Empty);
mockSqlDialect.Setup(x => x.BuildCommand(It.IsAny<IDbCommand>(), It.Is<SqlQuery>(s => s.Arguments[0] == (object)1)));
mockSqlDialect.Setup(x => x.BuildCommand(It.IsAny<IDbCommand>(), It.Is<SqlQuery>(s => s.Arguments[0] == (object)2)));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
IReadOnlySession session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
mockObjectBuilder.Object);
var includeCustomer = session.Include.Single<Customer>(2);
var customer = session.Single<Customer>(1);
}
[Fact]
public void TheSqlDialectShouldBuildTwoIDbCommands()
{
this.mockSqlDialect.Verify(x => x.BuildCommand(It.IsAny<IDbCommand>(), It.IsAny<SqlQuery>()), Times.Exactly(2));
}
[Fact]
public void TheSqlDialectShouldNotCombineTheQueries()
{
this.mockSqlDialect.Verify(x => x.Combine(It.IsAny<IEnumerable<SqlQuery>>()), Times.Never());
}
}
public class WhenExecutingMultipleQueriesAndTheSqlDialectUsedSupportsBatching
{
private Mock<ISqlDialect> mockSqlDialect = new Mock<ISqlDialect>();
public WhenExecutingMultipleQueriesAndTheSqlDialectUsedSupportsBatching()
{
var mockReader = new Mock<IDataReader>();
mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteReader()).Returns(mockReader.Object);
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockObjectBuilder = new Mock<IObjectBuilder>();
mockObjectBuilder.Setup(x => x.BuildInstance<Customer>(It.IsAny<ObjectInfo>(), It.IsAny<IDataReader>())).Returns(new Customer());
mockSqlDialect.Setup(x => x.SupportsBatchedQueries).Returns(true);
mockSqlDialect.Setup(x => x.SqlCharacters).Returns(SqlCharacters.Empty);
mockSqlDialect.Setup(x => x.BuildCommand(It.IsAny<IDbCommand>(), It.Is<SqlQuery>(s => s.Arguments[0] == (object)2 && s.Arguments[1] == (object)1)));
mockSqlDialect.Setup(x => x.Combine(It.IsAny<IEnumerable<SqlQuery>>())).Returns(new SqlQuery("", 2, 1));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
IReadOnlySession session = new ReadOnlySession(
mockSessionFactory.Object,
mockConnectionManager.Object,
mockObjectBuilder.Object);
var includeCustomer = session.Include.Single<Customer>(2);
var customer = session.Single<Customer>(1);
}
[Fact]
public void TheSqlDialectShouldBuildOneIDbCommand()
{
this.mockSqlDialect.Verify(x => x.BuildCommand(It.IsAny<IDbCommand>(), It.IsAny<SqlQuery>()), Times.Once());
}
[Fact]
public void TheSqlDialectShouldCombineTheQueries()
{
this.mockSqlDialect.Verify(x => x.Combine(It.IsAny<IEnumerable<SqlQuery>>()), Times.Once());
}
}
[MicroLite.Mapping.Table("dbo", "Customers")]
private class Customer
{
[MicroLite.Mapping.Column("CustomerId")]
[MicroLite.Mapping.Identifier(MicroLite.Mapping.IdentifierStrategy.DbGenerated)]
public int Id
{
get;
set;
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="ExpandoObjectInfo.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Mapping
{
#if !NET_3_5
using System;
using System.Collections.Generic;
using System.Dynamic;
using MicroLite.Logging;
[System.Diagnostics.DebuggerDisplay("ObjectInfo for {ForType}")]
internal sealed class ExpandoObjectInfo : IObjectInfo
{
private static readonly Type forType = typeof(ExpandoObject);
private static readonly ILog log = LogManager.GetCurrentClassLog();
public object DefaultIdentifierValue
{
get
{
throw new NotSupportedException(Messages.ExpandoObjectInfo_NotSupportedReason);
}
}
public Type ForType
{
get
{
return forType;
}
}
public TableInfo TableInfo
{
get
{
throw new NotSupportedException(Messages.ExpandoObjectInfo_NotSupportedReason);
}
}
public object CreateInstance()
{
return new ExpandoObject();
}
public object GetIdentifierValue(object instance)
{
throw new NotSupportedException(Messages.ExpandoObjectInfo_NotSupportedReason);
}
public object GetPropertyValue(object instance, string propertyName)
{
throw new NotSupportedException(Messages.ExpandoObjectInfo_NotSupportedReason);
}
public object GetPropertyValueForColumn(object instance, string columnName)
{
throw new NotSupportedException(Messages.ExpandoObjectInfo_NotSupportedReason);
}
public bool HasDefaultIdentifierValue(object instance)
{
throw new NotSupportedException(Messages.ExpandoObjectInfo_NotSupportedReason);
}
public void SetPropertyValue(object instance, string propertyName, object value)
{
throw new NotSupportedException(Messages.ExpandoObjectInfo_NotSupportedReason);
}
public void SetPropertyValueForColumn(object instance, string columnName, object value)
{
var dictionary = (IDictionary<string, object>)instance;
log.TryLogDebug(Messages.IObjectInfo_SettingPropertyValue, this.ForType.Name, columnName);
dictionary.Add(columnName, value == DBNull.Value ? null : value);
}
}
#endif
}<file_sep>namespace MicroLite.Tests.Core
{
using System.Data.Common;
using MicroLite.Core;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="SessionFactory"/> class.
/// </summary>
public class SessionFactoryTests
{
public class WhenCallingOpenReadOnlySession
{
private readonly Mock<DbConnection> mockConnection = new Mock<DbConnection>();
private readonly Mock<DbProviderFactory> mockFactory = new Mock<DbProviderFactory>();
private readonly SessionFactoryOptions options;
private readonly IReadOnlySession readOnlySession;
private readonly SessionFactory sessionFactory;
public WhenCallingOpenReadOnlySession()
{
this.mockConnection.SetupProperty(x => x.ConnectionString);
this.mockFactory.Setup(x => x.CreateConnection()).Returns(mockConnection.Object);
this.options = new SessionFactoryOptions
{
ConnectionString = "Data Source=localhost;Initial Catalog=TestDB;",
ProviderFactory = mockFactory.Object,
SqlDialectType = typeof(MicroLite.Dialect.MsSqlDialect)
};
this.sessionFactory = new SessionFactory(this.options);
this.readOnlySession = this.sessionFactory.OpenReadOnlySession();
}
[Fact]
public void ANewConnectionShouldBeCreated()
{
this.mockFactory.Verify(x => x.CreateConnection(), Times.Once());
}
[Fact]
public void TheConnectionStringShouldBeSetOnTheConnection()
{
this.mockConnection.VerifySet(x => x.ConnectionString = this.options.ConnectionString, Times.Once());
}
[Fact]
public void TheSessionFactoryShouldBePassed()
{
Assert.Same(this.sessionFactory, this.readOnlySession.Advanced.SessionFactory);
}
}
public class WhenCallingOpenSession
{
private readonly Mock<DbConnection> mockConnection = new Mock<DbConnection>();
private readonly Mock<DbProviderFactory> mockFactory = new Mock<DbProviderFactory>();
private readonly SessionFactoryOptions options;
public WhenCallingOpenSession()
{
this.mockConnection.SetupProperty(x => x.ConnectionString);
this.mockFactory.Setup(x => x.CreateConnection()).Returns(mockConnection.Object);
this.options = new SessionFactoryOptions
{
ConnectionString = "Data Source=localhost;Initial Catalog=TestDB;",
ProviderFactory = mockFactory.Object,
SqlDialectType = typeof(MicroLite.Dialect.MsSqlDialect)
};
var sessionFactory = new SessionFactory(this.options);
sessionFactory.OpenSession();
}
[Fact]
public void ANewConnectionShouldBeCreated()
{
this.mockFactory.Verify(x => x.CreateConnection(), Times.Once());
}
[Fact]
public void TheConnectionStringShouldBeSetOnTheConnection()
{
this.mockConnection.VerifySet(x => x.ConnectionString = this.options.ConnectionString, Times.Once());
}
}
public class WhenCallingReadOnlySessionMultipleTimes
{
private readonly Mock<DbConnection> mockConnection = new Mock<DbConnection>();
private readonly Mock<DbProviderFactory> mockFactory = new Mock<DbProviderFactory>();
private readonly SessionFactoryOptions options;
private readonly IReadOnlySession session1;
private readonly IReadOnlySession session2;
public WhenCallingReadOnlySessionMultipleTimes()
{
this.mockConnection.SetupProperty(x => x.ConnectionString);
this.mockFactory.Setup(x => x.CreateConnection()).Returns(mockConnection.Object);
this.options = new SessionFactoryOptions
{
ConnectionString = "Data Source=localhost;Initial Catalog=TestDB;",
ProviderFactory = mockFactory.Object,
SqlDialectType = typeof(MicroLite.Dialect.MsSqlDialect)
};
var sessionFactory = new SessionFactory(this.options);
this.session1 = sessionFactory.OpenReadOnlySession();
this.session2 = sessionFactory.OpenReadOnlySession();
}
[Fact]
public void ANewSessionShouldBeOpenedEachTime()
{
Assert.NotSame(this.session1, this.session2);
}
}
public class WhenCallingSessionMultipleTimes
{
private readonly Mock<DbConnection> mockConnection = new Mock<DbConnection>();
private readonly Mock<DbProviderFactory> mockFactory = new Mock<DbProviderFactory>();
private readonly SessionFactoryOptions options;
private readonly ISession session1;
private readonly ISession session2;
public WhenCallingSessionMultipleTimes()
{
this.mockConnection.SetupProperty(x => x.ConnectionString);
this.mockFactory.Setup(x => x.CreateConnection()).Returns(mockConnection.Object);
this.options = new SessionFactoryOptions
{
ConnectionString = "Data Source=localhost;Initial Catalog=TestDB;",
ProviderFactory = mockFactory.Object,
SqlDialectType = typeof(MicroLite.Dialect.MsSqlDialect)
};
var sessionFactory = new SessionFactory(this.options);
this.session1 = sessionFactory.OpenSession();
this.session2 = sessionFactory.OpenSession();
}
[Fact]
public void ANewSessionShouldBeOpenedEachTime()
{
Assert.NotSame(this.session1, this.session2);
}
}
public class WhenCreated
{
private readonly SessionFactoryOptions options = new SessionFactoryOptions
{
ConnectionName = "Northwind",
SqlDialectType = typeof(MicroLite.Dialect.MsSqlDialect)
};
private readonly SessionFactory sessionFactory;
public WhenCreated()
{
this.sessionFactory = new SessionFactory(this.options);
}
[Fact]
public void ConnectionNameReturnsConnectionNameFromOptions()
{
Assert.Equal(this.options.ConnectionName, this.sessionFactory.ConnectionName);
}
[Fact]
public void SqlDialectReturnsSqlDialectFromOptions()
{
Assert.IsType(options.SqlDialectType, sessionFactory.SqlDialect);
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="DbEncryptedStringTypeConverter.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.TypeConverters
{
using System;
using System.IO;
using System.Security.Cryptography;
using MicroLite.Infrastructure;
/// <summary>
/// An ITypeConverter which can encrypt and decrypt the stored database value.
/// </summary>
public sealed class DbEncryptedStringTypeConverter : TypeConverter
{
private const char Separator = '@';
private readonly ISymmetricAlgorithmProvider algorithmProvider;
/// <summary>
/// Initialises a new instance of the <see cref="DbEncryptedStringTypeConverter"/> class.
/// </summary>
/// <param name="algorithmProvider">The symmetric algorithm provider to be used.</param>
public DbEncryptedStringTypeConverter(ISymmetricAlgorithmProvider algorithmProvider)
{
if (algorithmProvider == null)
{
throw new ArgumentNullException("algorithmProvider");
}
this.algorithmProvider = algorithmProvider;
}
/// <summary>
/// Determines whether this type converter can convert values for the specified property type.
/// </summary>
/// <param name="propertyType">The type of the property value to be converted.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified property type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type propertyType)
{
return propertyType == typeof(DbEncryptedString);
}
/// <summary>
/// Converts the specified database value into an instance of the property type.
/// </summary>
/// <param name="value">The database value to be converted.</param>
/// <param name="propertyType">The property type to convert to.</param>
/// <returns>
/// An instance of the specified property type containing the specified value.
/// </returns>
public override object ConvertFromDbValue(object value, Type propertyType)
{
if (value == DBNull.Value)
{
return (DbEncryptedString)null;
}
var stringValue = (string)value;
if (string.IsNullOrEmpty(stringValue))
{
return (DbEncryptedString)stringValue;
}
return (DbEncryptedString)this.Decrypt(stringValue);
}
/// <summary>
/// Converts the specified property value into an instance of the database value.
/// </summary>
/// <param name="value">The property value to be converted.</param>
/// <param name="propertyType">The property type to convert from.</param>
/// <returns>
/// An instance of the corresponding database type for the property type containing the property value.
/// </returns>
public override object ConvertToDbValue(object value, Type propertyType)
{
if (value == null || string.IsNullOrEmpty(value.ToString()))
{
return value;
}
return this.Encrypt(value.ToString());
}
private string Decrypt(string cipherText)
{
var parts = cipherText.Split(Separator);
if (parts.Length != 2)
{
throw new MicroLiteException(Messages.DbEncryptedStringTypeConverter_CipherTextInvalid);
}
byte[] cipherBytes = Convert.FromBase64String(parts[0]);
byte[] ivBytes = Convert.FromBase64String(parts[1]);
using (var algorithm = this.algorithmProvider.CreateAlgorithm())
{
algorithm.IV = ivBytes;
var decryptor = algorithm.CreateDecryptor();
MemoryStream memoryStream = null;
CryptoStream cryptoStream = null;
try
{
memoryStream = new MemoryStream(cipherBytes);
cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
memoryStream = null;
using (var streamReader = new StreamReader(cryptoStream))
{
cryptoStream = null;
return streamReader.ReadToEnd();
}
}
finally
{
if (memoryStream != null)
{
memoryStream.Dispose();
}
if (cryptoStream != null)
{
cryptoStream.Dispose();
}
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Ignored for now, it shouldn't blow up and the suggested fix means we can't then access the memory stream!")]
private string Encrypt(string clearText)
{
byte[] cipherBytes = null;
byte[] ivBytes;
using (var algorithm = this.algorithmProvider.CreateAlgorithm())
{
algorithm.GenerateIV();
ivBytes = algorithm.IV; // should we use the IV bytes from the previous value if one exists?
var encryptor = algorithm.CreateEncryptor();
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
using (var streamWriter = new StreamWriter(cryptoStream))
{
streamWriter.Write(clearText);
}
cipherBytes = memoryStream.ToArray();
}
}
}
return Convert.ToBase64String(cipherBytes) + Separator + Convert.ToBase64String(ivBytes);
}
}
}<file_sep>namespace MicroLite.Tests.TypeConverters
{
using System.Linq;
using MicroLite.TypeConverters;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="TypeConverterCollection"/> class.
/// </summary>
public class TypeConverterCollectionTests
{
public class WhenCallingAdd
{
private readonly TypeConverterCollection collection = new TypeConverterCollection();
private readonly TestTypeConverter typeConverter = new TestTypeConverter();
public WhenCallingAdd()
{
this.collection.Add(this.typeConverter);
}
[Fact]
public void TheCollectionShouldContainTheAddedInstance()
{
var typeConverter = this.collection.SingleOrDefault(t => t == this.typeConverter);
Assert.NotNull(typeConverter);
}
}
public class WhenCallingClear
{
private readonly TypeConverterCollection collection = new TypeConverterCollection();
public WhenCallingClear()
{
this.collection.Clear();
}
[Fact]
public void TheCollectionShouldBeEmpty()
{
Assert.Equal(0, this.collection.Count);
}
}
public class WhenCallingCopyTo
{
private readonly ITypeConverter[] array;
private readonly TypeConverterCollection collection = new TypeConverterCollection();
public WhenCallingCopyTo()
{
this.array = new ITypeConverter[collection.Count];
collection.CopyTo(this.array, 0);
}
[Fact]
public void TheItemsInTheArrayShouldMatchTheItemsInTheCollection()
{
for (int i = 0; i < collection.Count; i++)
{
Assert.Same(this.array[i], this.collection.Skip(i).First());
}
}
}
public class WhenCallingRemove
{
private readonly TypeConverterCollection collection = new TypeConverterCollection();
private ITypeConverter typeConverterToRemove;
public WhenCallingRemove()
{
typeConverterToRemove = this.collection.OfType<ObjectTypeConverter>().Single();
this.collection.Remove(typeConverterToRemove);
}
[Fact]
public void TheTypeConverterShouldBeRemoved()
{
Assert.False(this.collection.Contains(typeConverterToRemove));
}
}
public class WhenCallingTheConstructor
{
private readonly TypeConverterCollection collection = new TypeConverterCollection();
[Fact]
public void ConstructorRegistersEnumTypeConverter()
{
var typeConverter = this.collection.OfType<EnumTypeConverter>().SingleOrDefault();
Assert.NotNull(typeConverter);
}
[Fact]
public void ConstructorRegistersObjectTypeConverter()
{
var typeConverter = this.collection.OfType<ObjectTypeConverter>().SingleOrDefault();
Assert.NotNull(typeConverter);
}
[Fact]
public void ConstructorRegistersXDocumentTypeConverter()
{
var typeConverter = this.collection.OfType<XDocumentTypeConverter>().SingleOrDefault();
Assert.NotNull(typeConverter);
}
[Fact]
public void TheCollectionShouldNotBeReadOnly()
{
Assert.False(this.collection.IsReadOnly);
}
[Fact]
public void ThereShouldBe3RegisteredTypeConverters()
{
Assert.Equal(3, this.collection.Count);
}
}
public class WhenEnumerating
{
private readonly TypeConverterCollection collection = new TypeConverterCollection();
private readonly ITypeConverter typeConverter1 = new TestTypeConverter();
private readonly ITypeConverter typeConverter2 = new TestTypeConverter();
public WhenEnumerating()
{
collection.Clear();
collection.Add(new TestTypeConverter());
typeConverter1 = collection.Single();
typeConverter2 = collection.Single();
}
[Fact]
public void TheSameInstanceShouldBeReturned()
{
Assert.Same(typeConverter1, typeConverter2);
}
}
private class TestTypeConverter : ITypeConverter
{
public bool CanConvert(System.Type propertyType)
{
throw new System.NotImplementedException();
}
public object ConvertFromDbValue(object value, System.Type propertyType)
{
throw new System.NotImplementedException();
}
public object ConvertToDbValue(object value, System.Type propertyType)
{
throw new System.NotImplementedException();
}
}
}
}<file_sep>namespace MicroLite.Tests.Core
{
using System;
using System.Data;
using MicroLite.Core;
using MicroLite.Dialect;
using MicroLite.Listeners;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="Session"/> class.
/// </summary>
public class SessionTests
{
private enum CustomerStatus
{
Inactive = 0,
Active = 1
}
[Fact]
public void AdvancedReturnsSameSessionByDifferentInterface()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
var advancedSession = session.Advanced;
Assert.Same(session, advancedSession);
}
[Fact]
public void DeleteInstanceInvokesListeners()
{
var customer = new Customer();
var sqlQuery = new SqlQuery("");
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Delete, customer)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
int counter = 0;
var mockListener1 = new Mock<IListener>();
mockListener1.Setup(x => x.AfterDelete(customer, 1)).Callback(() => Assert.Equal(6, ++counter));
mockListener1.Setup(x => x.BeforeDelete(customer)).Callback(() => Assert.Equal(1, ++counter));
mockListener1.Setup(x => x.BeforeDelete(customer, sqlQuery)).Callback(() => Assert.Equal(3, ++counter));
var mockListener2 = new Mock<IListener>();
mockListener2.Setup(x => x.AfterDelete(customer, 1)).Callback(() => Assert.Equal(5, ++counter));
mockListener2.Setup(x => x.BeforeDelete(customer)).Callback(() => Assert.Equal(2, ++counter));
mockListener2.Setup(x => x.BeforeDelete(customer, sqlQuery)).Callback(() => Assert.Equal(4, ++counter));
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new[] { mockListener1.Object, mockListener2.Object });
session.Delete(customer);
mockListener1.VerifyAll();
}
[Fact]
public void DeleteInstanceReturnsFalseIfNoRecordsDeleted()
{
var customer = new Customer();
var sqlQuery = new SqlQuery("");
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Delete, customer)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(0);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
Assert.False(session.Delete(customer));
mockSqlDialect.VerifyAll();
mockConnectionManager.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void DeleteInstanceReturnsTrueIfRecordDeleted()
{
var customer = new Customer();
var sqlQuery = new SqlQuery("");
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Delete, customer)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
Assert.True(session.Delete(customer));
mockSqlDialect.VerifyAll();
mockConnectionManager.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void DeleteInstanceThrowsArgumentNullExceptionForNullInstance()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
var exception = Assert.Throws<ArgumentNullException>(() => session.Delete(null));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void DeleteInstanceThrowsMicroLiteExceptionIfExecuteNonQueryThrowsException()
{
var customer = new Customer();
var sqlQuery = new SqlQuery("");
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Delete, customer)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Throws<InvalidOperationException>();
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
var exception = Assert.Throws<MicroLiteException>(() => session.Delete(customer));
Assert.NotNull(exception.InnerException);
Assert.Equal(exception.InnerException.Message, exception.Message);
// Command should still be disposed.
mockCommand.VerifyAll();
}
[Fact]
public void DeleteInstanceThrowsObjectDisposedExceptionIfDisposed()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.Delete(new Customer()));
}
[Fact]
public void DeleteTypeByIdentifierReturnsFalseIfNoRecordsDeleted()
{
var type = typeof(Customer);
var identifier = 1234;
var sqlQuery = new SqlQuery("");
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Delete, type, identifier)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(0);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
Assert.False(session.Delete(type, identifier));
mockSqlDialect.VerifyAll();
mockConnectionManager.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void DeleteTypeByIdentifierReturnsTrueIfRecordDeleted()
{
var type = typeof(Customer);
var identifier = 1234;
var sqlQuery = new SqlQuery("");
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Delete, type, identifier)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
Assert.True(session.Delete(type, identifier));
mockSqlDialect.VerifyAll();
mockConnectionManager.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void DeleteTypeByIdentifierThrowsArgumentNullExceptionForNullIdentifier()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
var exception = Assert.Throws<ArgumentNullException>(() => session.Delete(typeof(Customer), null));
Assert.Equal("identifier", exception.ParamName);
}
[Fact]
public void DeleteTypeByIdentifierThrowsArgumentNullExceptionForNullType()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
var exception = Assert.Throws<ArgumentNullException>(() => session.Delete(null, 1234));
Assert.Equal("type", exception.ParamName);
}
[Fact]
public void DeleteTypeByIdentifierThrowsMicroLiteExceptionIfExecuteNonQueryThrowsException()
{
var type = typeof(Customer);
var identifier = 1234;
var sqlQuery = new SqlQuery("");
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Delete, type, identifier)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Throws<InvalidOperationException>();
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
var exception = Assert.Throws<MicroLiteException>(() => session.Delete(type, identifier));
Assert.NotNull(exception.InnerException);
Assert.Equal(exception.InnerException.Message, exception.Message);
// Command should still be disposed.
mockCommand.VerifyAll();
}
[Fact]
public void DeleteTypeByIdentifierThrowsObjectDisposedExceptionIfDisposed()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.Delete(typeof(Customer), 1234));
}
[Fact]
public void ExecuteBuildsAndExecutesCommandNotInTransaction()
{
var sqlQuery = new SqlQuery("");
var result = 1;
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(result);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, sqlQuery));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
Assert.Equal(result, session.Execute(sqlQuery));
mockConnectionManager.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void ExecuteDoesNotOpenOrCloseConnectionWhenInTransaction()
{
var sqlQuery = new SqlQuery("");
var result = 1;
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(result);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, sqlQuery));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
Assert.Equal(result, session.Execute(sqlQuery));
mockConnectionManager.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void ExecuteScalarBuildsAndExecutesCommand()
{
var sqlQuery = new SqlQuery("");
var result = new object();
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteScalar()).Returns(result);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, sqlQuery));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
Assert.Equal(result, session.ExecuteScalar<object>(sqlQuery));
mockConnectionManager.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void ExecuteScalarDoesNotOpenOrCloseConnectionWhenInTransaction()
{
var sqlQuery = new SqlQuery("");
var result = new object();
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.State).Returns(ConnectionState.Open);
mockConnection.Setup(x => x.Open());
mockConnection.Setup(x => x.Close());
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteScalar()).Returns(result);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, sqlQuery));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
Assert.Equal(result, session.ExecuteScalar<object>(sqlQuery));
mockConnectionManager.VerifyAll();
mockCommand.VerifyAll();
mockConnection.Verify(x => x.Open(), Times.Never());
mockConnection.Verify(x => x.Close(), Times.Never());
}
[Fact]
public void ExecuteScalarThrowsArgumentNullExceptionForNullSqlQuery()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
var exception = Assert.Throws<ArgumentNullException>(() => session.ExecuteScalar<object>(null));
Assert.Equal("sqlQuery", exception.ParamName);
}
[Fact]
public void ExecuteScalarThrowsObjectDisposedExceptionIfDisposed()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.ExecuteScalar<int>(new SqlQuery("SELECT")));
}
[Fact]
public void ExecuteScalarUsesTypeConvertersToResolveResultType()
{
var sqlQuery = new SqlQuery("");
var result = (byte)1;
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteScalar()).Returns(result);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildCommand(mockCommand.Object, sqlQuery));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
Assert.Equal((CustomerStatus)result, session.ExecuteScalar<CustomerStatus>(sqlQuery));
mockConnectionManager.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void ExecuteThrowsArgumentNullExceptionForNullSqlQuery()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
var exception = Assert.Throws<ArgumentNullException>(() => session.Execute(null));
Assert.Equal("sqlQuery", exception.ParamName);
}
[Fact]
public void ExecuteThrowsObjectDisposedExceptionIfDisposed()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.Execute(new SqlQuery("SELECT")));
}
[Fact]
public void InsertBuildsAndExecutesQuery()
{
var customer = new Customer();
var sqlQuery = new SqlQuery("");
object identifier = 23543;
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Insert, customer)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteScalar()).Returns(identifier);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
session.Insert(customer);
mockSqlDialect.VerifyAll();
mockConnectionManager.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void InsertInvokesListeners()
{
var customer = new Customer();
var sqlQuery = new SqlQuery("");
object identifier = 23543;
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Insert, customer)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteScalar()).Returns(identifier);
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
int counter = 0;
var mockListener1 = new Mock<IListener>();
mockListener1.Setup(x => x.AfterInsert(customer, identifier)).Callback(() => Assert.Equal(6, ++counter));
mockListener1.Setup(x => x.BeforeInsert(customer)).Callback(() => Assert.Equal(1, ++counter));
mockListener1.Setup(x => x.BeforeInsert(customer, sqlQuery)).Callback(() => Assert.Equal(3, ++counter));
var mockListener2 = new Mock<IListener>();
mockListener2.Setup(x => x.AfterInsert(customer, identifier)).Callback(() => Assert.Equal(5, ++counter));
mockListener2.Setup(x => x.BeforeInsert(customer)).Callback(() => Assert.Equal(2, ++counter));
mockListener2.Setup(x => x.BeforeInsert(customer, sqlQuery)).Callback(() => Assert.Equal(4, ++counter));
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new[] { mockListener1.Object, mockListener2.Object });
session.Insert(customer);
mockListener1.VerifyAll();
}
[Fact]
public void InsertOrUpdateInsertsInstanceIfIdentifierIsNotSet()
{
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(new Mock<IDbCommand>().Object);
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(It.IsAny<StatementType>(), It.IsAny<object>())).Returns(new SqlQuery(""));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockListener = new Mock<IListener>();
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new[] { mockListener.Object });
var customer = new Customer
{
Id = 0
};
session.InsertOrUpdate(customer);
mockListener.Verify(x => x.BeforeInsert(customer), Times.Once());
mockListener.Verify(x => x.BeforeUpdate(customer), Times.Never());
}
[Fact]
public void InsertOrUpdateThrowsArgumentNullExceptionForNullInstance()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
var exception = Assert.Throws<ArgumentNullException>(() => session.InsertOrUpdate(null));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void InsertOrUpdateUpdatesInstanceIfIdentifierIsNotSet()
{
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(new Mock<IDbCommand>().Object);
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(It.IsAny<StatementType>(), It.IsAny<object>())).Returns(new SqlQuery(""));
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockListener = new Mock<IListener>();
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new[] { mockListener.Object });
var customer = new Customer
{
Id = 1242
};
session.InsertOrUpdate(customer);
mockListener.Verify(x => x.BeforeInsert(customer), Times.Never());
mockListener.Verify(x => x.BeforeUpdate(customer), Times.Once());
}
[Fact]
public void InsertThrowsArgumentNullExceptionForNullInstance()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
var exception = Assert.Throws<ArgumentNullException>(() => session.Insert(null));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void InsertThrowsMicroLiteExceptionIfExecuteScalarThrowsException()
{
var customer = new Customer();
var sqlQuery = new SqlQuery("");
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Insert, customer)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteScalar()).Throws<InvalidOperationException>();
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
var exception = Assert.Throws<MicroLiteException>(() => session.Insert(customer));
Assert.NotNull(exception.InnerException);
Assert.Equal(exception.InnerException.Message, exception.Message);
// Command should still be disposed.
mockCommand.VerifyAll();
}
[Fact]
public void InsertThrowsObjectDisposedExceptionIfDisposed()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.Insert(new Customer()));
}
[Fact]
public void UpdateBuildsAndExecutesQuery()
{
var customer = new Customer();
var sqlQuery = new SqlQuery("");
var rowsAffected = 1;
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Update, customer)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(rowsAffected);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
session.Update(customer);
mockSqlDialect.VerifyAll();
mockConnectionManager.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void UpdateInvokesListeners()
{
var customer = new Customer();
var sqlQuery = new SqlQuery("");
var rowsAffected = 1;
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Update, customer)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(rowsAffected);
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
int counter = 0;
var mockListener1 = new Mock<IListener>();
mockListener1.Setup(x => x.AfterUpdate(customer, 1)).Callback(() => Assert.Equal(6, ++counter));
mockListener1.Setup(x => x.BeforeUpdate(customer)).Callback(() => Assert.Equal(1, ++counter));
mockListener1.Setup(x => x.BeforeUpdate(customer, sqlQuery)).Callback(() => Assert.Equal(3, ++counter));
var mockListener2 = new Mock<IListener>();
mockListener2.Setup(x => x.AfterUpdate(customer, 1)).Callback(() => Assert.Equal(5, ++counter));
mockListener2.Setup(x => x.BeforeUpdate(customer)).Callback(() => Assert.Equal(2, ++counter));
mockListener2.Setup(x => x.BeforeUpdate(customer, sqlQuery)).Callback(() => Assert.Equal(4, ++counter));
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new[] { mockListener1.Object, mockListener2.Object });
session.Update(customer);
mockListener1.VerifyAll();
}
[Fact]
public void UpdateReturnsFalseIfNoRecordsUpdated()
{
var customer = new Customer();
var sqlQuery = new SqlQuery("");
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Update, customer)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(0);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
Assert.False(session.Update(customer));
mockSqlDialect.VerifyAll();
mockConnectionManager.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void UpdateReturnsTrueIfRecordUpdated()
{
var customer = new Customer();
var sqlQuery = new SqlQuery("");
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Update, customer)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1);
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
Assert.True(session.Update(customer));
mockSqlDialect.VerifyAll();
mockConnectionManager.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void UpdateThrowsArgumentNullExceptionForNullInstance()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
var exception = Assert.Throws<ArgumentNullException>(() => session.Update(null));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void UpdateThrowsMicroLiteExceptionIfExecuteNonQueryThrowsException()
{
var customer = new Customer();
var sqlQuery = new SqlQuery("");
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.CreateQuery(StatementType.Update, customer)).Returns(sqlQuery);
var mockSessionFactory = new Mock<ISessionFactory>();
mockSessionFactory.Setup(x => x.SqlDialect).Returns(mockSqlDialect.Object);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Throws<InvalidOperationException>();
mockCommand.As<IDisposable>().Setup(x => x.Dispose());
var mockConnectionManager = new Mock<IConnectionManager>();
mockConnectionManager.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var session = new Session(
mockSessionFactory.Object,
mockConnectionManager.Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
var exception = Assert.Throws<MicroLiteException>(() => session.Update(customer));
Assert.NotNull(exception.InnerException);
Assert.Equal(exception.InnerException.Message, exception.Message);
// Command should still be disposed.
mockCommand.VerifyAll();
}
[Fact]
public void UpdateThrowsObjectDisposedExceptionIfDisposed()
{
var session = new Session(
new Mock<ISessionFactory>().Object,
new Mock<IConnectionManager>().Object,
new Mock<IObjectBuilder>().Object,
new IListener[0]);
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.Update(new Customer()));
}
[MicroLite.Mapping.Table("dbo", "Customers")]
private class Customer
{
[MicroLite.Mapping.Column("CustomerId")]
[MicroLite.Mapping.Identifier(MicroLite.Mapping.IdentifierStrategy.DbGenerated)]
public int Id
{
get;
set;
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="DbGeneratedListener.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Listeners
{
using System;
using MicroLite.Logging;
using MicroLite.Mapping;
/// <summary>
/// The implementation of <see cref="IListener"/> for setting the instance identifier value if
/// <see cref="IdentifierStrategy"/>.DbGenerated is used.
/// </summary>
public sealed class DbGeneratedListener : Listener
{
private static readonly ILog log = LogManager.GetCurrentClassLog();
/// <summary>
/// Invoked after the SqlQuery to insert the record for the instance has been executed.
/// </summary>
/// <param name="instance">The instance which has been inserted.</param>
/// <param name="executeScalarResult">The execute scalar result.</param>
public override void AfterInsert(object instance, object executeScalarResult)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
if (executeScalarResult == null)
{
throw new ArgumentNullException("executeScalarResult");
}
var objectInfo = ObjectInfo.For(instance.GetType());
if (objectInfo.TableInfo.IdentifierStrategy == IdentifierStrategy.DbGenerated)
{
log.TryLogDebug(Messages.IListener_SettingIdentifierValue, objectInfo.ForType.FullName, executeScalarResult.ToString());
objectInfo.SetPropertyValueForColumn(instance, objectInfo.TableInfo.IdentifierColumn, executeScalarResult);
}
}
/// <summary>
/// Invoked before the SqlQuery to delete the record from the database is created.
/// </summary>
/// <param name="instance">The instance to be deleted.</param>
/// <exception cref="MicroLiteException">Thrown if the identifier value for the object has not been set.</exception>
public override void BeforeDelete(object instance)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
var objectInfo = ObjectInfo.For(instance.GetType());
if (objectInfo.TableInfo.IdentifierStrategy == IdentifierStrategy.DbGenerated)
{
if (objectInfo.HasDefaultIdentifierValue(instance))
{
throw new MicroLiteException(Messages.IListener_IdentifierNotSetForDelete);
}
}
}
/// <summary>
/// Invoked before the SqlQuery to insert the record into the database is created.
/// </summary>
/// <param name="instance">The instance to be inserted.</param>
/// <exception cref="MicroLiteException">Thrown if the identifier value for the object has already been set.</exception>
public override void BeforeInsert(object instance)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
var objectInfo = ObjectInfo.For(instance.GetType());
if (objectInfo.TableInfo.IdentifierStrategy == IdentifierStrategy.DbGenerated)
{
if (!objectInfo.HasDefaultIdentifierValue(instance))
{
throw new MicroLiteException(Messages.IListener_IdentifierSetForInsert);
}
}
}
/// <summary>
/// Invoked before the SqlQuery to update the record in the database is created.
/// </summary>
/// <param name="instance">The instance to be updated.</param>
/// <exception cref="MicroLiteException">Thrown if the identifier value for the object has not been set.</exception>
public override void BeforeUpdate(object instance)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
var objectInfo = ObjectInfo.For(instance.GetType());
if (objectInfo.TableInfo.IdentifierStrategy == IdentifierStrategy.DbGenerated)
{
if (objectInfo.HasDefaultIdentifierValue(instance))
{
throw new MicroLiteException(Messages.IListener_IdentifierNotSetForUpdate);
}
}
}
}
}<file_sep>namespace MicroLite.Tests.Integration
{
public enum CustomerStatus
{
Active = 0,
Suspended = 1,
Closed = 2,
}
}<file_sep>namespace MicroLite.Tests.Core
{
using System;
using System.Data;
using MicroLite.Core;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="AdoTransaction"/> class.
/// </summary>
public class AdoTransactionTests
{
/// <summary>
/// Issue #56 - Calling Commit more than once should throw an InvalidOperationException.
/// </summary>
[Fact]
public void CallingCommitTwiceShouldResultInInvalidOperationExceptionBeingThrown()
{
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.Close());
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(mockConnection.Object);
var transaction = new AdoTransaction(mockTransaction.Object);
transaction.Commit();
var exception = Assert.Throws<InvalidOperationException>(() => transaction.Commit());
Assert.Equal(Messages.Transaction_Completed, exception.Message);
}
/// <summary>
/// Issue #58 - Calling RollBack if Committed successfully should throw an InvalidOperationException.
/// </summary>
[Fact]
public void CallingRollBackIfCommittedShouldResultInInvalidOperationExceptionBeingThrown()
{
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.Close());
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(mockConnection.Object);
var transaction = new AdoTransaction(mockTransaction.Object);
transaction.Commit();
var exception = Assert.Throws<InvalidOperationException>(() => transaction.Rollback());
Assert.Equal(Messages.Transaction_Completed, exception.Message);
}
/// <summary>
/// Issue #57 - Calling RollBack more than once should throw an InvalidOperationException.
/// </summary>
[Fact]
public void CallingRollBackTwiceShouldResultInInvalidOperationExceptionBeingThrown()
{
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.Close());
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(mockConnection.Object);
var transaction = new AdoTransaction(mockTransaction.Object);
transaction.Rollback();
var exception = Assert.Throws<InvalidOperationException>(() => transaction.Rollback());
Assert.Equal(Messages.Transaction_Completed, exception.Message);
}
[Fact]
public void CommitCallsDbConnectionClose()
{
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.Close());
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(mockConnection.Object);
var transaction = new AdoTransaction(mockTransaction.Object);
transaction.Commit();
mockConnection.VerifyAll();
}
[Fact]
public void CommitCallsDbTransactionCommit()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
mockTransaction.Setup(x => x.Commit());
var transaction = new AdoTransaction(mockTransaction.Object);
transaction.Commit();
mockTransaction.VerifyAll();
}
[Fact]
public void CommitCallsDbTransactionCommitAndReThrowsExceptionIfCommitFails()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
mockTransaction.Setup(x => x.Commit()).Throws<InvalidOperationException>();
var transaction = new AdoTransaction(mockTransaction.Object);
var exception = Assert.Throws<MicroLiteException>(() => transaction.Commit());
Assert.IsType<InvalidOperationException>(exception.InnerException);
Assert.Equal(exception.Message, exception.InnerException.Message);
}
[Fact]
public void CommitSetsIsActiveToFalse()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
var transaction = new AdoTransaction(mockTransaction.Object);
transaction.Commit();
Assert.False(transaction.IsActive);
}
[Fact]
public void CommitSetsWasCommittedToTrue()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
var transaction = new AdoTransaction(mockTransaction.Object);
transaction.Commit();
Assert.True(transaction.WasCommitted);
}
[Fact]
public void CommitThrowsObjectDisposedExceptionIfDisposed()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
var transaction = new AdoTransaction(mockTransaction.Object);
using (transaction)
{
}
Assert.Throws<ObjectDisposedException>(() => transaction.Commit());
}
/// <summary>
/// Issue #48 - This SqlTransaction has completed; it is no longer usable. thrown by Transaction.Dispose.
/// </summary>
/// <remarks>
/// This was because dispose also called rollback if the transaction was not committed.
/// </remarks>
[Fact]
public void DisposeDoesNotRollbackDbTransactionIfAlreadyRolledback()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
mockTransaction.Setup(x => x.Rollback());
using (var transaction = new AdoTransaction(mockTransaction.Object))
{
// Explicitly roll back the transaction.
transaction.Rollback();
}
mockTransaction.Verify(x => x.Rollback(), Times.Once());
}
[Fact]
public void DisposeDoesNotRollbackDbTransactionIfCommittedAndDisposesDbTransaction()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
mockTransaction.Setup(x => x.Dispose());
mockTransaction.Setup(x => x.Rollback());
using (var transaction = new AdoTransaction(mockTransaction.Object))
{
transaction.Commit();
}
mockTransaction.Verify(x => x.Dispose(), Times.Once());
mockTransaction.Verify(x => x.Rollback(), Times.Never());
}
[Fact]
public void DisposeRollsbackDbTransactionIfNotCommitedAndDisposesDbTransaction()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
mockTransaction.Setup(x => x.Dispose());
mockTransaction.Setup(x => x.Rollback());
using (var transaction = new AdoTransaction(mockTransaction.Object))
{
}
mockTransaction.VerifyAll();
}
/// <summary>
/// This reverts the behaviour of #55 but without breaking the logic that caused #55 initially.
/// </summary>
[Fact]
public void DisposeRollsbackDbTransactionIfNotCommitedFaulted()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
mockTransaction.Setup(x => x.Commit()).Throws<InvalidOperationException>();
using (var transaction = new AdoTransaction(mockTransaction.Object))
{
// Commit the transaction so that it faults.
Assert.Throws<MicroLiteException>(() => transaction.Commit());
}
mockTransaction.Verify(x => x.Rollback(), Times.Once());
}
[Fact]
public void EnlistDoesNotSetTransactionOnDbCommandIfCommitted()
{
var mockCommand = new Mock<IDbCommand>();
mockCommand.SetupProperty(x => x.Transaction);
var command = mockCommand.Object;
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
var transaction = new AdoTransaction(mockTransaction.Object);
transaction.Commit();
transaction.Enlist(command);
Assert.Null(command.Transaction);
}
[Fact]
public void EnlistDoesNotSetTransactionOnDbCommandIfRolledBack()
{
var mockCommand = new Mock<IDbCommand>();
mockCommand.SetupProperty(x => x.Transaction);
var command = mockCommand.Object;
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
var transaction = new AdoTransaction(mockTransaction.Object);
transaction.Rollback();
transaction.Enlist(command);
Assert.Null(command.Transaction);
}
[Fact]
public void EnlistSetsTransactionOnDbCommandIfNotCommitted()
{
var mockCommand = new Mock<IDbCommand>();
mockCommand.SetupProperty(x => x.Transaction);
var command = mockCommand.Object;
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
var dbTransaction = mockTransaction.Object;
var transaction = new AdoTransaction(mockTransaction.Object);
transaction.Enlist(command);
Assert.Same(dbTransaction, command.Transaction);
}
[Fact]
public void EnlistThrowsArgumentNullExceptionForNullDbCommand()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
var transaction = new AdoTransaction(mockTransaction.Object);
var exception = Assert.Throws<ArgumentNullException>(() => transaction.Enlist(null));
Assert.Equal("command", exception.ParamName);
}
[Fact]
public void IsolationLevelReurnsTransactionIsolationLevel()
{
var mockDbTransaction = new Mock<IDbTransaction>();
mockDbTransaction.Setup(x => x.IsolationLevel).Returns(IsolationLevel.Chaos);
var dbTransaction = mockDbTransaction.Object;
var transaction = new AdoTransaction(dbTransaction);
Assert.Equal(dbTransaction.IsolationLevel, transaction.IsolationLevel);
}
[Fact]
public void RollbackCallsDbConnectionClose()
{
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.Close());
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(mockConnection.Object);
var transaction = new AdoTransaction(mockTransaction.Object);
transaction.Rollback();
mockConnection.VerifyAll();
}
[Fact]
public void RollbackCallsDbTransactionRollback()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
mockTransaction.Setup(x => x.Rollback());
var transaction = new AdoTransaction(mockTransaction.Object);
transaction.Rollback();
mockTransaction.VerifyAll();
}
[Fact]
public void RollbackCallsDbTransactionRollbackAndReThrowsExceptionIfRollbackFails()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
mockTransaction.Setup(x => x.Rollback()).Throws<InvalidOperationException>();
var transaction = new AdoTransaction(mockTransaction.Object);
var exception = Assert.Throws<MicroLiteException>(() => transaction.Rollback());
Assert.IsType<InvalidOperationException>(exception.InnerException);
Assert.Equal(exception.Message, exception.InnerException.Message);
}
[Fact]
public void RollbackSetsIsActiveToFalse()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
var transaction = new AdoTransaction(mockTransaction.Object);
transaction.Rollback();
Assert.False(transaction.IsActive);
}
[Fact]
public void RollbackSetsWasRolledBackToTrue()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
var transaction = new AdoTransaction(mockTransaction.Object);
transaction.Rollback();
Assert.True(transaction.WasRolledBack);
}
[Fact]
public void RollbackThrowsObjectDisposedExceptionIfDisposed()
{
var mockTransaction = new Mock<IDbTransaction>();
mockTransaction.Setup(x => x.Connection).Returns(new Mock<IDbConnection>().Object);
var transaction = new AdoTransaction(mockTransaction.Object);
using (transaction)
{
}
Assert.Throws<ObjectDisposedException>(() => transaction.Rollback());
}
}
}<file_sep>namespace MicroLite.Infrastructure.Web.Tests
{
using System.Data;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="SessionManager"/> class.
/// </summary>
public class SessionManagerTests
{
public class WhenCallingOnActionExecutedAndManageTransactionIsFalse
{
private readonly Mock<IReadOnlySession> mockSession = new Mock<IReadOnlySession>();
public WhenCallingOnActionExecutedAndManageTransactionIsFalse()
{
var sessionManager = new SessionManager();
sessionManager.OnActionExecuted(this.mockSession.Object, manageTransaction: false, hasException: false);
}
[Fact]
public void TheSessionShouldBeDisposed()
{
this.mockSession.Verify(x => x.Dispose(), Times.Once());
}
[Fact]
public void TheTransactionShouldNotBeCommitted()
{
this.mockSession.Verify(x => x.Transaction.Commit(), Times.Never());
}
[Fact]
public void TheTransactionShouldNotBeRolledBack()
{
this.mockSession.Verify(x => x.Transaction.Rollback(), Times.Never());
}
}
public class WhenCallingOnActionExecutedWithAnActiveBackManagedTransactionAndHasExceptionIsTrue
{
private readonly Mock<IReadOnlySession> mockSession = new Mock<IReadOnlySession>();
public WhenCallingOnActionExecutedWithAnActiveBackManagedTransactionAndHasExceptionIsTrue()
{
this.mockSession.Setup(x => x.Transaction.WasRolledBack).Returns(false);
var sessionManager = new SessionManager();
sessionManager.OnActionExecuted(this.mockSession.Object, manageTransaction: true, hasException: true);
}
[Fact]
public void TheSessionShouldBeDisposed()
{
this.mockSession.Verify(x => x.Dispose(), Times.Once());
}
[Fact]
public void TheTransactionShouldNotBeCommitted()
{
this.mockSession.Verify(x => x.Transaction.Commit(), Times.Never());
}
[Fact]
public void TheTransactionShouldNotBeRolledBack()
{
this.mockSession.Verify(x => x.Transaction.Rollback(), Times.Once());
}
}
public class WhenCallingOnActionExecutedWithAnActiveManagedTransactionAndHasExceptionIsFalse
{
private readonly Mock<IReadOnlySession> mockSession = new Mock<IReadOnlySession>();
public WhenCallingOnActionExecutedWithAnActiveManagedTransactionAndHasExceptionIsFalse()
{
this.mockSession.Setup(x => x.Transaction.IsActive).Returns(true);
var sessionManager = new SessionManager();
sessionManager.OnActionExecuted(this.mockSession.Object, manageTransaction: true, hasException: false);
}
[Fact]
public void TheSessionShouldBeDisposed()
{
this.mockSession.Verify(x => x.Dispose(), Times.Once());
}
[Fact]
public void TheTransactionShouldBeCommitted()
{
this.mockSession.Verify(x => x.Transaction.Commit(), Times.Once());
}
[Fact]
public void TheTransactionShouldNotBeRolledBack()
{
this.mockSession.Verify(x => x.Transaction.Rollback(), Times.Never());
}
}
public class WhenCallingOnActionExecutedWithAnCompletedManagedTransactionAndHasExceptionIsFalse
{
private readonly Mock<IReadOnlySession> mockSession = new Mock<IReadOnlySession>();
public WhenCallingOnActionExecutedWithAnCompletedManagedTransactionAndHasExceptionIsFalse()
{
this.mockSession.Setup(x => x.Transaction.IsActive).Returns(false);
var sessionManager = new SessionManager();
sessionManager.OnActionExecuted(this.mockSession.Object, manageTransaction: true, hasException: false);
}
[Fact]
public void TheSessionShouldBeDisposed()
{
this.mockSession.Verify(x => x.Dispose(), Times.Once());
}
[Fact]
public void TheTransactionShouldNotBeCommitted()
{
this.mockSession.Verify(x => x.Transaction.Commit(), Times.Never());
}
[Fact]
public void TheTransactionShouldNotBeRolledBack()
{
this.mockSession.Verify(x => x.Transaction.Rollback(), Times.Never());
}
}
public class WhenCallingOnActionExecutedWithARolledBackManagedTransactionAndHasExceptionIsTrue
{
private readonly Mock<IReadOnlySession> mockSession = new Mock<IReadOnlySession>();
public WhenCallingOnActionExecutedWithARolledBackManagedTransactionAndHasExceptionIsTrue()
{
this.mockSession.Setup(x => x.Transaction.WasRolledBack).Returns(true);
var sessionManager = new SessionManager();
sessionManager.OnActionExecuted(this.mockSession.Object, manageTransaction: true, hasException: true);
}
[Fact]
public void TheSessionShouldBeDisposed()
{
this.mockSession.Verify(x => x.Dispose(), Times.Once());
}
[Fact]
public void TheTransactionShouldNotBeCommitted()
{
this.mockSession.Verify(x => x.Transaction.Commit(), Times.Never());
}
[Fact]
public void TheTransactionShouldNotBeRolledBack()
{
this.mockSession.Verify(x => x.Transaction.Rollback(), Times.Never());
}
}
public class WhenCallingOnActionExecutingAndManageTransactionIsFalse
{
private readonly Mock<IReadOnlySession> mockSession = new Mock<IReadOnlySession>();
public WhenCallingOnActionExecutingAndManageTransactionIsFalse()
{
var sessionManager = new SessionManager();
sessionManager.OnActionExecuting(this.mockSession.Object, manageTransaction: false, isolationLevel: null);
}
[Fact]
public void ATransactionShouldNotBeStarted()
{
this.mockSession.Verify(x => x.BeginTransaction(), Times.Never());
}
[Fact]
public void ATransactionWithSpecifiedIsolationLevelShouldNotBeStarted()
{
this.mockSession.Verify(x => x.BeginTransaction(It.IsAny<IsolationLevel>()), Times.Never());
}
}
public class WhenCallingOnActionExecutingAndManageTransactionIsTrue
{
private readonly Mock<IReadOnlySession> mockSession = new Mock<IReadOnlySession>();
public WhenCallingOnActionExecutingAndManageTransactionIsTrue()
{
var sessionManager = new SessionManager();
sessionManager.OnActionExecuting(this.mockSession.Object, manageTransaction: true, isolationLevel: null);
}
[Fact]
public void ATransactionShouldBeStarted()
{
this.mockSession.Verify(x => x.BeginTransaction(), Times.Once());
}
[Fact]
public void ATransactionWithSpecifiedIsolationLevelShouldNotBeStarted()
{
this.mockSession.Verify(x => x.BeginTransaction(It.IsAny<IsolationLevel>()), Times.Never());
}
}
public class WhenCallingOnActionExecutingAndManageTransactionIsTrueAndAnIsolationLevelIsSpecified
{
private readonly IsolationLevel isolationLevel = IsolationLevel.Chaos;
private readonly Mock<IReadOnlySession> mockSession = new Mock<IReadOnlySession>();
public WhenCallingOnActionExecutingAndManageTransactionIsTrueAndAnIsolationLevelIsSpecified()
{
var sessionManager = new SessionManager();
sessionManager.OnActionExecuting(this.mockSession.Object, manageTransaction: true, isolationLevel: this.isolationLevel);
}
[Fact]
public void ATransactionShouldNotBeStarted()
{
this.mockSession.Verify(x => x.BeginTransaction(), Times.Never());
}
[Fact]
public void ATransactionWithSpecifiedIsolationLevelShouldBeStarted()
{
this.mockSession.Verify(x => x.BeginTransaction(It.IsAny<IsolationLevel>()), Times.Once());
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="Session.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Core
{
using System;
using System.Data;
using MicroLite.FrameworkExtensions;
using MicroLite.Listeners;
using MicroLite.Logging;
using MicroLite.Mapping;
using MicroLite.TypeConverters;
/// <summary>
/// The default implementation of <see cref="ISession"/>.
/// </summary>
internal sealed class Session : ReadOnlySession, ISession, IAdvancedSession
{
private readonly IListener[] listeners;
internal Session(
ISessionFactory sessionFactory,
IConnectionManager connectionManager,
IObjectBuilder objectBuilder,
IListener[] listeners)
: base(sessionFactory, connectionManager, objectBuilder)
{
this.listeners = listeners;
Log.TryLogDebug(Messages.Session_Created);
}
public new IAdvancedSession Advanced
{
get
{
return this;
}
}
public bool Delete(object instance)
{
this.ThrowIfDisposed();
if (instance == null)
{
throw new ArgumentNullException("instance");
}
this.listeners.Each(l => l.BeforeDelete(instance));
var sqlQuery = this.SqlDialect.CreateQuery(StatementType.Delete, instance);
this.listeners.Each(l => l.BeforeDelete(instance, sqlQuery));
var rowsAffected = this.Execute(sqlQuery);
this.listeners.Reverse().Each(l => l.AfterDelete(instance, rowsAffected));
return rowsAffected == 1;
}
public bool Delete(Type type, object identifier)
{
this.ThrowIfDisposed();
if (type == null)
{
throw new ArgumentNullException("type");
}
if (identifier == null)
{
throw new ArgumentNullException("identifier");
}
var sqlQuery = this.SqlDialect.CreateQuery(StatementType.Delete, type, identifier);
var rowsAffected = this.Execute(sqlQuery);
return rowsAffected == 1;
}
public int Execute(SqlQuery sqlQuery)
{
this.ThrowIfDisposed();
if (sqlQuery == null)
{
throw new ArgumentNullException("sqlQuery");
}
try
{
using (var command = this.ConnectionManager.CreateCommand())
{
this.SqlDialect.BuildCommand(command, sqlQuery);
var result = command.ExecuteNonQuery();
this.ConnectionManager.CommandCompleted(command);
return result;
}
}
catch (Exception e)
{
Log.TryLogError(e.Message, e);
throw new MicroLiteException(e.Message, e);
}
}
public T ExecuteScalar<T>(SqlQuery sqlQuery)
{
this.ThrowIfDisposed();
if (sqlQuery == null)
{
throw new ArgumentNullException("sqlQuery");
}
try
{
using (var command = this.ConnectionManager.CreateCommand())
{
this.SqlDialect.BuildCommand(command, sqlQuery);
var result = command.ExecuteScalar();
this.ConnectionManager.CommandCompleted(command);
var resultType = typeof(T);
var typeConverter = TypeConverter.For(resultType);
var converted = (T)typeConverter.ConvertFromDbValue(result, resultType);
return converted;
}
}
catch (Exception e)
{
Log.TryLogError(e.Message, e);
throw new MicroLiteException(e.Message, e);
}
}
public void Insert(object instance)
{
this.ThrowIfDisposed();
if (instance == null)
{
throw new ArgumentNullException("instance");
}
this.listeners.Each(l => l.BeforeInsert(instance));
var sqlQuery = this.SqlDialect.CreateQuery(StatementType.Insert, instance);
this.listeners.Each(l => l.BeforeInsert(instance, sqlQuery));
var identifier = this.ExecuteScalar<object>(sqlQuery);
this.listeners.Reverse().Each(l => l.AfterInsert(instance, identifier));
}
public void InsertOrUpdate(object instance)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
var objectInfo = ObjectInfo.For(instance.GetType());
if (objectInfo.HasDefaultIdentifierValue(instance))
{
this.Insert(instance);
}
else
{
this.Update(instance);
}
}
public bool Update(object instance)
{
this.ThrowIfDisposed();
if (instance == null)
{
throw new ArgumentNullException("instance");
}
this.listeners.Each(l => l.BeforeUpdate(instance));
var sqlQuery = this.SqlDialect.CreateQuery(StatementType.Update, instance);
this.listeners.Each(l => l.BeforeUpdate(instance, sqlQuery));
var rowsAffected = this.Execute(sqlQuery);
this.listeners.Reverse().Each(l => l.AfterUpdate(instance, rowsAffected));
return rowsAffected == 1;
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="ObjectTypeConverter.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.TypeConverters
{
using System;
using System.Globalization;
/// <summary>
/// An ITypeConverter which can uses Convert.ChangeType.
/// </summary>
/// <remarks>
/// It is the default ITypeConverter used if no suitable specific implementation exists.
/// </remarks>
public sealed class ObjectTypeConverter : TypeConverter
{
/// <summary>
/// Determines whether this type converter can convert values for the specified property type.
/// </summary>
/// <param name="propertyType">The type of the property value to be converted.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified property type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type propertyType)
{
return true;
}
/// <summary>
/// Converts the specified database value into an instance of the property type.
/// </summary>
/// <param name="value">The database value to be converted.</param>
/// <param name="propertyType">The property type to convert to.</param>
/// <returns>
/// An instance of the specified property type containing the specified value.
/// </returns>
/// <exception cref="System.ArgumentNullException">thrown if propertyType is null.</exception>
public override object ConvertFromDbValue(object value, Type propertyType)
{
if (propertyType == null)
{
throw new ArgumentNullException("propertyType");
}
if (value == null || value == DBNull.Value)
{
return null;
}
if (propertyType.IsValueType && propertyType.IsGenericType)
{
ValueType converted = (ValueType)value;
return converted;
}
else
{
var converted = System.Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture);
return converted;
}
}
/// <summary>
/// Converts the specified property value into an instance of the database value.
/// </summary>
/// <param name="value">The property value to be converted.</param>
/// <param name="propertyType">The property type to convert from.</param>
/// <returns>
/// An instance of the corresponding database type for the property type containing the property value.
/// </returns>
public override object ConvertToDbValue(object value, Type propertyType)
{
return value;
}
}
}<file_sep>MicroLite ORM Framework
=========
MicroLite is a small lightweight or "micro" object relational mapping (ORM) framework written in C# for the Microsoft .NET framework.
It currently supports Microsoft SQL Server, SQLite, PostgreSQL and MySql and offers a number of advantages over other micro ORM frameworks:
* It only references the .NET base class libraries (no dependencies outside the .NET framework itself).
* It is built for .NET 3.5 client profile, .NET 4.0 client profile and .NET 4.5.
* It provides extension points for Logging frameworks, Mapping Conventions, Session Listeners, Type Converters and SQL Dialects.
* It is easily managed by IOC containers.
* It is easy to test code which uses it.
To find out more, head over to the [Wiki](https://github.com/TrevorPilley/MicroLite/wiki) and see how easy it is to use!
[](http://ndepend.com/)<file_sep>// -----------------------------------------------------------------------
// <copyright file="ListenerCollection.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Listeners
{
using System;
using System.Collections.Generic;
/// <summary>
/// The class which contains the IListeners used by the MicroLite ORM framework.
/// </summary>
public sealed class ListenerCollection : ICollection<IListener>
{
private readonly Stack<IListener> listeners = new Stack<IListener>();
/// <summary>
/// Initialises a new instance of the <see cref="ListenerCollection"/> class.
/// </summary>
public ListenerCollection()
{
this.listeners.Push(new DbGeneratedListener());
this.listeners.Push(new AssignedListener());
this.listeners.Push(new GuidListener());
this.listeners.Push(new GuidCombListener());
}
/// <summary>
/// Gets the number of listeners contained in the collection.
/// </summary>
public int Count
{
get
{
return this.listeners.Count;
}
}
/// <summary>
/// Gets a value indicating whether the collection is read-only.
/// </summary>
/// <returns>true if the collection is read-only; otherwise, false.</returns>
public bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Adds the IListener to the collection.
/// </summary>
/// <typeparam name="T">The type of <see cref="IListener"/> to add.</typeparam>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "The syntax is accepted practice for registering types.")]
[Obsolete("This method has been replaced by Add(IListener).", error: false)]
public void Add<T>()
where T : IListener, new()
{
var listener = new T();
this.Add(listener);
}
/// <summary>
/// Adds the specified listener to the collection of listeners which can be used by MicroLite.
/// </summary>
/// <param name="item">The listener to be added.</param>
public void Add(IListener item)
{
this.listeners.Push(item);
}
/// <summary>
/// Removes all items from the collection.
/// </summary>
public void Clear()
{
this.listeners.Clear();
}
/// <summary>
/// Determines whether the collection contains the specified listener.
/// </summary>
/// <param name="item">The object to locate in the collection.</param>
/// <returns>
/// true if the item exists in the collection; otherwise, false.
/// </returns>
public bool Contains(IListener item)
{
return this.listeners.Contains(item);
}
/// <summary>
/// Copies the items in the collection to the specified one dimension array at the specified index.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="arrayIndex">Index of the array.</param>
public void CopyTo(IListener[] array, int arrayIndex)
{
this.listeners.CopyTo(array, arrayIndex);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<IListener> GetEnumerator()
{
return this.listeners.GetEnumerator();
}
/// <summary>
/// Removes the specified listener from the collection.
/// </summary>
/// <param name="item">The listener to be removed.</param>
/// <returns>
/// true if <paramref name="item" /> was successfully removed from the collection; otherwise, false. This method also returns false if <paramref name="item" /> is not found in the original collection.
/// </returns>
public bool Remove(IListener item)
{
var existing = this.listeners.ToArray();
this.listeners.Clear();
bool removed = false;
foreach (var listener in existing)
{
if (listener == item)
{
removed = true;
}
else
{
this.listeners.Push(listener);
}
}
return removed;
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="PropertyAccessor.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Mapping
{
using System;
using System.Reflection;
internal static class PropertyAccessor
{
internal static IPropertyAccessor Create(PropertyInfo propertyInfo)
{
var propertyAccessor = (IPropertyAccessor)Activator.CreateInstance(
typeof(PropertyAccessorImpl<,>).MakeGenericType(propertyInfo.DeclaringType, propertyInfo.PropertyType),
propertyInfo);
return propertyAccessor;
}
[System.Diagnostics.DebuggerDisplay("PropertyAccessor for {propertyInfo.Name}")]
private sealed class PropertyAccessorImpl<TObject, TValue> : IPropertyAccessor
{
private readonly Func<TObject, TValue> getMethod;
private readonly Action<TObject, TValue> setMethod;
public PropertyAccessorImpl(PropertyInfo propertyInfo)
{
MethodInfo getMethodInfo = propertyInfo.GetGetMethod(nonPublic: true);
MethodInfo setMethodInfo = propertyInfo.GetSetMethod(nonPublic: true);
this.getMethod = (Func<TObject, TValue>)Delegate.CreateDelegate(typeof(Func<TObject, TValue>), getMethodInfo);
this.setMethod = (Action<TObject, TValue>)Delegate.CreateDelegate(typeof(Action<TObject, TValue>), setMethodInfo);
}
public object GetValue(object instance)
{
object value = this.getMethod((TObject)instance);
return value;
}
public void SetValue(object instance, object value)
{
if (value == DBNull.Value)
{
return;
}
this.setMethod((TObject)instance, (TValue)value);
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="ConfigurationExtensions.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Configuration
{
using System;
using MicroLite.Mapping;
/// <summary>
/// Extensions for the MicroLite configuration.
/// </summary>
public static class ConfigurationExtensions
{
/// <summary>
/// Specifies the name of the connection string in the app config and that the MsSqlDialect should be used.
/// </summary>
/// <param name="configureConnection">The interface to configure connections.</param>
/// <param name="connectionName">The name of the connection string in the app config.</param>
/// <returns>The next step in the fluent configuration.</returns>
/// <exception cref="System.ArgumentNullException">Thrown if connectionName is null.</exception>
/// <exception cref="MicroLiteException">Thrown if the connection is not found in the app config.</exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "ForMs", Justification = "For MS, not Forms.")]
public static ICreateSessionFactory ForMsSqlConnection(this IConfigureConnection configureConnection, string connectionName)
{
if (configureConnection == null)
{
throw new ArgumentNullException("configureConnection");
}
return configureConnection.ForConnection(connectionName, "MicroLite.Dialect.MsSqlDialect");
}
/// <summary>
/// Specifies the name of the connection string in the app config and that the MySqlDialect should be used.
/// </summary>
/// <param name="configureConnection">The interface to configure connections.</param>
/// <param name="connectionName">The name of the connection string in the app config.</param>
/// <returns>The next step in the fluent configuration.</returns>
/// <exception cref="System.ArgumentNullException">Thrown if connectionName is null.</exception>
/// <exception cref="MicroLiteException">Thrown if the connection is not found in the app config.</exception>
public static ICreateSessionFactory ForMySqlConnection(this IConfigureConnection configureConnection, string connectionName)
{
if (configureConnection == null)
{
throw new ArgumentNullException("configureConnection");
}
return configureConnection.ForConnection(connectionName, "MicroLite.Dialect.MySqlDialect");
}
/// <summary>
/// Specifies the name of the connection string in the app config and that the PostgreSqlDialect should be used.
/// </summary>
/// <param name="configureConnection">The interface to configure connections.</param>
/// <param name="connectionName">The name of the connection string in the app config.</param>
/// <returns>The next step in the fluent configuration.</returns>
/// <exception cref="System.ArgumentNullException">Thrown if connectionName is null.</exception>
/// <exception cref="MicroLiteException">Thrown if the connection is not found in the app config.</exception>
public static ICreateSessionFactory ForPostgreSqlConnection(this IConfigureConnection configureConnection, string connectionName)
{
if (configureConnection == null)
{
throw new ArgumentNullException("configureConnection");
}
return configureConnection.ForConnection(connectionName, "MicroLite.Dialect.PostgreSqlDialect");
}
/// <summary>
/// Specifies the name of the connection string in the app config and that the SQLiteDialect should be used.
/// </summary>
/// <param name="configureConnection">The interface to configure connections.</param>
/// <param name="connectionName">The name of the connection string in the app config.</param>
/// <returns>The next step in the fluent configuration.</returns>
/// <exception cref="System.ArgumentNullException">Thrown if connectionName is null.</exception>
/// <exception cref="MicroLiteException">Thrown if the connection is not found in the app config.</exception>
public static ICreateSessionFactory ForSQLiteConnection(this IConfigureConnection configureConnection, string connectionName)
{
if (configureConnection == null)
{
throw new ArgumentNullException("configureConnection");
}
return configureConnection.ForConnection(connectionName, "MicroLite.Dialect.SQLiteDialect");
}
/// <summary>
/// Configures the MicroLite ORM Framework to use the default attribute based mapping.
/// </summary>
/// <param name="configureExtensions">The interface to configure extensions.</param>
/// <returns>The configure extensions.</returns>
public static IConfigureExtensions WithAttributeBasedMapping(
this IConfigureExtensions configureExtensions)
{
if (configureExtensions == null)
{
throw new ArgumentNullException("configureExtensions");
}
configureExtensions.SetMappingConvention(new AttributeMappingConvention());
return configureExtensions;
}
/// <summary>
/// Configures the MicroLite ORM Framework to use convention based mapping instead of the default
/// attribute based mapping.
/// </summary>
/// <param name="configureExtensions">The interface to configure extensions.</param>
/// <param name="settings">The settings for the convention mapping.</param>
/// <returns>The configure extensions.</returns>
public static IConfigureExtensions WithConventionBasedMapping(
this IConfigureExtensions configureExtensions,
ConventionMappingSettings settings)
{
if (configureExtensions == null)
{
throw new ArgumentNullException("configureExtensions");
}
if (settings == null)
{
throw new ArgumentNullException("settings");
}
configureExtensions.SetMappingConvention(new ConventionMappingConvention(settings));
return configureExtensions;
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="SessionFactoryOptions.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Core
{
using System;
using System.Data.Common;
/// <summary>
/// The class used to hold the options for configuring a session factory.
/// </summary>
internal sealed class SessionFactoryOptions
{
/// <summary>
/// Gets or sets the connection name.
/// </summary>
internal string ConnectionName
{
get;
set;
}
/// <summary>
/// Gets or sets the connection string.
/// </summary>
internal string ConnectionString
{
get;
set;
}
/// <summary>
/// Gets or sets the provider factory.
/// </summary>
internal DbProviderFactory ProviderFactory
{
get;
set;
}
/// <summary>
/// Gets or sets the type of SqlDialect for the connection.
/// </summary>
internal Type SqlDialectType
{
get;
set;
}
}
}<file_sep>namespace MicroLite.Tests.Integration
{
using System;
using MicroLite.Configuration;
using MicroLite.Mapping;
public abstract class IntegrationTest : IDisposable
{
private static readonly ISessionFactory sessionFactory;
private ISession session;
private ITransaction transaction;
static IntegrationTest()
{
Configure
.Extensions()
.WithConventionBasedMapping(ConventionMappingSettings.Default);
sessionFactory = Configure
.Fluently()
.ForConnection("SQLiteInMemory", "MicroLite.Dialect.SQLiteDialect")
.CreateSessionFactory();
}
protected ISession Session
{
get
{
if (this.session == null)
{
this.session = sessionFactory.OpenSession();
// When used In-Memory, SQLite will re-set the database when the connection is closed.
// Since MicroLite only holds on to the connection during the scope of a transaction, we need to open
// one here and manage it at this level.
// It does mean that we can't do any transactional tests and that it shouldn't be managed by individual tests.
this.transaction = this.session.BeginTransaction();
this.CreateDatabase();
}
return this.session;
}
}
public void Dispose()
{
if (this.transaction != null)
{
this.transaction.Commit();
this.transaction.Dispose();
this.transaction = null;
}
if (this.session != null)
{
this.session.Dispose();
this.session = null;
}
}
private void CreateDatabase()
{
this.session.Advanced.Execute(new SqlQuery(@"CREATE TABLE Customers (
CustomerId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
DateOfBirth TEXT NOT NULL,
EmailAddress TEXT,
Forename TEXT NOT NULL,
CustomerStatusId INTEGER NOT NULL,
Surname TEXT NOT NULL
);"));
this.session.Advanced.Execute(new SqlQuery(@"CREATE TABLE Invoices (
InvoiceId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
Created DATETIME NOT NULL,
CreatedBy TEXT NOT NULL,
CustomerId INTEGER NOT NULL,
Number INTEGER NOT NULL,
PaymentProcessed DATETIME,
PaymentReceived DATETIME,
InvoiceStatusId INTEGER NOT NULL,
Total REAL NOT NULL
);"));
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="IAndOrOrderBy.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Query
{
/// <summary>
/// The interface which specifies the and/or methods to extend the where clause in the fluent sql builder syntax.
/// </summary>
public interface IAndOrOrderBy : IHideObjectMethods, IGroupBy, IOrderBy, IToSqlQuery
{
/// <summary>
/// Adds a column as an AND to the where clause of the query.
/// </summary>
/// <param name="columnName">The column name to use in the where clause.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IWhereSingleColumn AndWhere(string columnName);
/// <summary>
/// Adds a predicate as an AND to the where clause of the query.
/// </summary>
/// <param name="predicate">The predicate.</param>
/// <param name="args">The args.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IAndOrOrderBy AndWhere(string predicate, params object[] args);
/// <summary>
/// Adds a column as an OR to the where clause of the query.
/// </summary>
/// <param name="columnName">The column name to use in the where clause.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IWhereSingleColumn OrWhere(string columnName);
/// <summary>
/// Adds a predicate as an OR to the where clause of the query.
/// </summary>
/// <param name="predicate">The predicate.</param>
/// <param name="args">The args.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IAndOrOrderBy OrWhere(string predicate, params object[] args);
}
}<file_sep>namespace MicroLite.Tests.Core
{
using System;
using System.Data;
using MicroLite.Core;
using MicroLite.Mapping;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="ObjectBuilder"/> class.
/// </summary>
public class ObjectBuilderTests : IDisposable
{
public ObjectBuilderTests()
{
// The tests in this suite all use attribute mapping for the test.
ObjectInfo.MappingConvention = new AttributeMappingConvention();
}
private enum CustomerStatus
{
Inactive = 0,
Active = 1
}
/// <summary>
/// Issue #8 - ObjectBuilder throws exception converting DBNull to nullable ValueType.
/// </summary>
[Fact]
public void BuildInstancePropertyValueIsSetToNullForNullableInt()
{
var mockDataReader = new Mock<IDataReader>();
mockDataReader.Setup(x => x.FieldCount).Returns(1);
mockDataReader.Setup(x => x.GetName(0)).Returns("ReferredById");
mockDataReader.Setup(x => x[0]).Returns(DBNull.Value);
var objectBuilder = new ObjectBuilder();
var customer = objectBuilder.BuildInstance<Customer>(ObjectInfo.For(typeof(Customer)), mockDataReader.Object);
Assert.Null(customer.ReferredById);
}
/// <summary>
/// Issue #19 - Null strings in a column result in empty strings in the property
/// </summary>
[Fact]
public void BuildInstancePropertyValueIsSetToNullIdReaderValueIsDBNull()
{
var mockDataReader = new Mock<IDataReader>();
mockDataReader.Setup(x => x.FieldCount).Returns(1);
mockDataReader.Setup(x => x.GetName(0)).Returns("Name");
mockDataReader.Setup(x => x[0]).Returns(DBNull.Value);
var objectBuilder = new ObjectBuilder();
var customer = objectBuilder.BuildInstance<Customer>(ObjectInfo.For(typeof(Customer)), mockDataReader.Object);
Assert.Null(customer.Name);
}
/// <summary>
/// Issue #7 - ObjectBuilder throws exception converting int to nullable int.
/// </summary>
[Fact]
public void BuildInstancePropertyValueIsSetToValueForNullableInt()
{
var mockDataReader = new Mock<IDataReader>();
mockDataReader.Setup(x => x.FieldCount).Returns(1);
mockDataReader.Setup(x => x.GetName(0)).Returns("ReferredById");
mockDataReader.Setup(x => x[0]).Returns((int?)1235);
var objectBuilder = new ObjectBuilder();
var customer = objectBuilder.BuildInstance<Customer>(ObjectInfo.For(typeof(Customer)), mockDataReader.Object);
Assert.Equal(1235, customer.ReferredById);
}
[Fact]
public void BuildInstancePropertyValuesAreSetCorrectly()
{
var mockDataReader = new Mock<IDataReader>();
mockDataReader.Setup(x => x.FieldCount).Returns(4);
mockDataReader.Setup(x => x.GetName(0)).Returns("CustomerId");
mockDataReader.Setup(x => x.GetName(1)).Returns("Name");
mockDataReader.Setup(x => x.GetName(2)).Returns("DoB");
mockDataReader.Setup(x => x.GetName(3)).Returns("StatusId");
mockDataReader.Setup(x => x[0]).Returns(123242);
mockDataReader.Setup(x => x[1]).Returns("<NAME>");
mockDataReader.Setup(x => x[2]).Returns(new DateTime(1980, 7, 13));
mockDataReader.Setup(x => x[3]).Returns(1);
var objectBuilder = new ObjectBuilder();
var customer = objectBuilder.BuildInstance<Customer>(ObjectInfo.For(typeof(Customer)), mockDataReader.Object);
Assert.Equal(new DateTime(1980, 7, 13), customer.DateOfBirth);
Assert.Equal(123242, customer.Id);
Assert.Equal("<NAME>", customer.Name);
Assert.Equal(CustomerStatus.Active, customer.Status);
}
[Fact]
public void BuildInstanceThrowsMicroLiteExceptionIfUnableToSetProperty()
{
var mockDataReader = new Mock<IDataReader>();
mockDataReader.Setup(x => x.FieldCount).Returns(1);
mockDataReader.Setup(x => x.GetName(0)).Returns("DoB");
mockDataReader.Setup(x => x[0]).Returns("foo");
var objectBuilder = new ObjectBuilder();
var exception = Assert.Throws<MicroLiteException>(
() => objectBuilder.BuildInstance<Customer>(ObjectInfo.For(typeof(Customer)), mockDataReader.Object));
Assert.NotNull(exception.InnerException);
Assert.Equal(exception.InnerException.Message, exception.Message);
}
public void Dispose()
{
// Reset the mapping convention after tests have run.
ObjectInfo.MappingConvention = new ConventionMappingConvention(ConventionMappingSettings.Default);
}
[MicroLite.Mapping.Table("Sales", "Customers")]
private class Customer
{
public Customer()
{
}
[MicroLite.Mapping.Column("DoB")]
public DateTime DateOfBirth
{
get;
set;
}
[MicroLite.Mapping.Column("CustomerId")]
[MicroLite.Mapping.Identifier(MicroLite.Mapping.IdentifierStrategy.DbGenerated)]
public int Id
{
get;
set;
}
[MicroLite.Mapping.Column("Name")]
public string Name
{
get;
set;
}
[MicroLite.Mapping.Column("ReferredById")]
public int? ReferredById
{
get;
set;
}
[MicroLite.Mapping.Column("StatusId")]
public CustomerStatus Status
{
get;
set;
}
}
}
}<file_sep>namespace MicroLite.Tests
{
using System;
using System.Collections.Generic;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="SqlUtility"/> class.
/// </summary>
public class SqlUtilityTests
{
[Fact]
public void GetFirstParameterPositionThrowsArgumentNullExceptionForNullCommandText()
{
Assert.Throws<ArgumentNullException>(() => SqlUtility.GetFirstParameterPosition(null));
}
[Fact]
public void GetFirstParameterPositionWithAtParameters()
{
var position = SqlUtility.GetFirstParameterPosition("SELECT * FROM TABLE WHERE Column1 = @p0 AND Column2 = @p1");
Assert.Equal(36, position);
}
[Fact]
public void GetFirstParameterPositionWithColonParameters()
{
var position = SqlUtility.GetFirstParameterPosition("SELECT * FROM TABLE WHERE Column1 = :p0 AND Column2 = :p1");
Assert.Equal(36, position);
}
[Fact]
public void GetFirstParameterPositionWithNoParameters()
{
var position = SqlUtility.GetFirstParameterPosition("SELECT * FROM TABLE");
Assert.Equal(-1, position);
}
[Fact]
public void GetFirstParameterPositionWithQuestionMarkParameters()
{
var position = SqlUtility.GetFirstParameterPosition("SELECT * FROM TABLE WHERE Column1 = ? AND Column2 = ?");
Assert.Equal(36, position);
}
[Fact]
public void GetParameterNamesThrowsArgumentNullExceptionForNullCommandText()
{
Assert.Throws<ArgumentNullException>(() => SqlUtility.GetParameterNames(null));
}
[Fact]
public void GetParameterNamesWithAtPrefix()
{
var parameterNames = SqlUtility.GetParameterNames("SELECT * FROM TABLE WHERE Col1 = @p0 AND (Col2 = @p1 OR @p1 IS NULL)");
Assert.Equal(2, parameterNames.Count);
Assert.Equal(new List<string> { "@p0", "@p1" }, parameterNames);
}
[Fact]
public void GetParameterNamesWithColonPrefix()
{
var parameterNames = SqlUtility.GetParameterNames("SELECT * FROM TABLE WHERE Col1 = :p0 AND (Col2 = :p1 OR :p1 IS NULL)");
Assert.Equal(2, parameterNames.Count);
Assert.Equal(new List<string> { ":p0", ":p1" }, parameterNames);
}
[Fact]
public void ReNumberParametersNoExistingArguments()
{
var commandText = SqlUtility.RenumberParameters("(Column1 = @p0 OR @p0 IS NULL) AND Column2 = @p1", totalArgumentCount: 2);
Assert.Equal("(Column1 = @p0 OR @p0 IS NULL) AND Column2 = @p1", commandText);
}
[Fact]
public void ReNumberParametersWithExistingArguments()
{
var commandText = SqlUtility.RenumberParameters("(Column1 = @p0 OR @p0 IS NULL) AND Column2 = @p1", totalArgumentCount: 4);
Assert.Equal("(Column1 = @p2 OR @p2 IS NULL) AND Column2 = @p3", commandText);
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="SQLiteDialect.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Dialect
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// The implementation of <see cref="ISqlDialect"/> for SQLite.
/// </summary>
internal sealed class SQLiteDialect : SqlDialect
{
/// <summary>
/// Initialises a new instance of the <see cref="SQLiteDialect"/> class.
/// </summary>
/// <remarks>Constructor needs to be public so that it can be instantiated by SqlDialectFactory.</remarks>
public SQLiteDialect()
: base(SqlCharacters.SQLite)
{
}
/// <summary>
/// Gets the select identity string.
/// </summary>
protected override string SelectIdentityString
{
get
{
return "SELECT last_insert_rowid()";
}
}
public override SqlQuery PageQuery(SqlQuery sqlQuery, PagingOptions pagingOptions)
{
List<object> arguments = new List<object>(sqlQuery.Arguments.Count + 2);
arguments.AddRange(sqlQuery.Arguments);
arguments.Add(pagingOptions.Offset);
arguments.Add(pagingOptions.Count);
var sqlBuilder = new StringBuilder(sqlQuery.CommandText);
sqlBuilder.Replace(Environment.NewLine, string.Empty);
sqlBuilder.Append(" LIMIT ");
sqlBuilder.Append(this.SqlCharacters.GetParameterName(arguments.Count - 2));
sqlBuilder.Append(',');
sqlBuilder.Append(this.SqlCharacters.GetParameterName(arguments.Count - 1));
return new SqlQuery(sqlBuilder.ToString(), arguments.ToArray());
}
}
}<file_sep>namespace MicroLite.Tests.Core
{
using System;
using MicroLite.Listeners;
using Xunit;
/// <summary>
/// Unit tests for the <see cref="DbGeneratedListener"/> class.
/// </summary>
public class DbGeneratedListenerTests
{
[Fact]
public void AfterInsertSetsIdentifierValue()
{
var customer = new Customer();
decimal scalarResult = 4354;
var listener = new DbGeneratedListener();
listener.AfterInsert(customer, scalarResult);
Assert.Equal(Convert.ToInt32(scalarResult), customer.Id);
}
[Fact]
public void AfterInsertThrowsArgumentNullExceptionForNullExecuteScalarResult()
{
var listener = new DbGeneratedListener();
var exception = Assert.Throws<ArgumentNullException>(() => listener.AfterInsert(new Customer(), null));
Assert.Equal("executeScalarResult", exception.ParamName);
}
[Fact]
public void AfterInsertThrowsArgumentNullExceptionForNullInstance()
{
var listener = new DbGeneratedListener();
var exception = Assert.Throws<ArgumentNullException>(() => listener.AfterInsert(null, 1));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void BeforeDeleteDoesNotThrowIfIdentifierSet()
{
var customer = new Customer
{
Id = 1242534
};
var listener = new DbGeneratedListener();
listener.BeforeDelete(customer);
}
[Fact]
public void BeforeDeleteThrowsArgumentNullExceptionForNullInstance()
{
var listener = new DbGeneratedListener();
var exception = Assert.Throws<ArgumentNullException>(() => listener.BeforeDelete(null));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void BeforeDeleteThrowsMicroLiteExceptionIfIdentifierNotSet()
{
var customer = new Customer
{
Id = 0
};
var listener = new DbGeneratedListener();
var exception = Assert.Throws<MicroLiteException>(() => listener.BeforeDelete(customer));
Assert.Equal(Messages.IListener_IdentifierNotSetForDelete, exception.Message);
}
[Fact]
public void BeforeInsertDoesNotThrowIfIdentifierNotSet()
{
var customer = new Customer
{
Id = 0
};
var listener = new DbGeneratedListener();
listener.BeforeInsert(customer);
}
[Fact]
public void BeforeInsertThrowsArgumentNullExceptionForNullInstance()
{
var listener = new DbGeneratedListener();
var exception = Assert.Throws<ArgumentNullException>(() => listener.BeforeInsert(null));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void BeforeInsertThrowsMicroLiteExceptionIfIdentifierAlreadySet()
{
var customer = new Customer
{
Id = 1242534
};
var listener = new DbGeneratedListener();
var exception = Assert.Throws<MicroLiteException>(() => listener.BeforeInsert(customer));
Assert.Equal(Messages.IListener_IdentifierSetForInsert, exception.Message);
}
[Fact]
public void BeforeUpdateDoesNotThrowIfIdentifierSet()
{
var customer = new Customer
{
Id = 1242534
};
var listener = new DbGeneratedListener();
listener.BeforeUpdate(customer);
}
[Fact]
public void BeforeUpdateThrowsArgumentNullExceptionForNullInstance()
{
var listener = new DbGeneratedListener();
var exception = Assert.Throws<ArgumentNullException>(() => listener.BeforeUpdate(null));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void BeforeUpdateThrowsMicroLiteExceptionIfIdentifierNotSet()
{
var customer = new Customer
{
Id = 0
};
var listener = new DbGeneratedListener();
var exception = Assert.Throws<MicroLiteException>(() => listener.BeforeUpdate(customer));
Assert.Equal(Messages.IListener_IdentifierNotSetForUpdate, exception.Message);
}
[MicroLite.Mapping.Table("Sales", "Customers")]
private class Customer
{
[MicroLite.Mapping.Column("CustomerId")]
[MicroLite.Mapping.Identifier(MicroLite.Mapping.IdentifierStrategy.DbGenerated)]
public int Id
{
get;
set;
}
}
[MicroLite.Mapping.Table("Sales", "Customers")]
private class CustomerWithAssigned
{
[MicroLite.Mapping.Column("CustomerId")]
[MicroLite.Mapping.Identifier(MicroLite.Mapping.IdentifierStrategy.Assigned)]
public int Id
{
get;
set;
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="AttributeMappingConvention.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Mapping
{
using System;
using System.Collections.Generic;
using System.Reflection;
using MicroLite.FrameworkExtensions;
using MicroLite.Logging;
/// <summary>
/// The implementation of <see cref="IMappingConvention"/> which uses attributes to map tables and columns
/// to types and properties only maps if an attribute is present (opt-in).
/// </summary>
internal sealed class AttributeMappingConvention : IMappingConvention
{
private static readonly ILog log = LogManager.GetCurrentClassLog();
public IObjectInfo CreateObjectInfo(Type forType)
{
if (forType == null)
{
throw new ArgumentNullException("forType");
}
var tableAttribute = forType.GetAttribute<TableAttribute>(inherit: false);
if (tableAttribute == null)
{
log.TryLogFatal(Messages.AttributeMappingConvention_NoTableAttribute, forType.FullName);
throw new MicroLiteException(Messages.AttributeMappingConvention_NoTableAttribute.FormatWith(forType.FullName));
}
var identifierStrategy = MicroLite.Mapping.IdentifierStrategy.DbGenerated;
var columns = CreateColumnInfos(forType, ref identifierStrategy);
var tableInfo = new TableInfo(columns, identifierStrategy, tableAttribute.Name, tableAttribute.Schema);
return new ObjectInfo(forType, tableInfo);
}
private static List<ColumnInfo> CreateColumnInfos(Type forType, ref IdentifierStrategy identifierStrategy)
{
var properties = forType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
var columns = new List<ColumnInfo>(properties.Length);
foreach (var property in properties)
{
if (!property.CanRead || !property.CanWrite)
{
log.TryLogDebug(Messages.MappingConvention_PropertyNotGetAndSet, forType.Name, property.Name);
continue;
}
var columnAttribute = property.GetAttribute<ColumnAttribute>(inherit: true);
if (columnAttribute == null)
{
log.TryLogInfo(Messages.AttributeMappingConvention_IgnoringProperty, forType.FullName, property.Name);
continue;
}
var identifierAttribute = property.GetAttribute<IdentifierAttribute>(inherit: true);
if (identifierAttribute != null)
{
identifierStrategy = identifierAttribute.IdentifierStrategy;
}
var columnInfo = new ColumnInfo(
columnName: columnAttribute.Name,
propertyInfo: property,
isIdentifier: identifierAttribute != null,
allowInsert: columnAttribute.AllowInsert,
allowUpdate: columnAttribute.AllowUpdate);
columns.Add(columnInfo);
}
return columns;
}
}
}<file_sep>namespace MicroLite.Tests.Dialect
{
using System;
using System.Data;
using MicroLite.Dialect;
using MicroLite.Mapping;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="SqlDialect"/> class.
/// </summary>
public class SqlDialectTests : IDisposable
{
public SqlDialectTests()
{
// The tests in this suite all use attribute mapping for the test.
ObjectInfo.MappingConvention = new AttributeMappingConvention();
}
private enum CustomerStatus
{
Inactive = 0,
Active = 1
}
[Fact]
public void BuildCommandForSqlQueryWithSqlText()
{
var sqlQuery = new SqlQuery(
"SELECT * FROM [Table] WHERE [Table].[Id] = ? AND [Table].[Value1] = ? AND [Table].[Value2] = ?",
new object[] { 100, "hello", null });
using (var command = new System.Data.OleDb.OleDbCommand())
{
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
mockSqlDialect.Object.BuildCommand(command, sqlQuery);
Assert.Equal(sqlQuery.CommandText, command.CommandText);
Assert.Equal(CommandType.Text, command.CommandType);
Assert.Equal(3, command.Parameters.Count);
var parameter1 = (IDataParameter)command.Parameters[0];
Assert.Equal(ParameterDirection.Input, parameter1.Direction);
Assert.Equal("Parameter0", parameter1.ParameterName);
Assert.Equal(sqlQuery.Arguments[0], parameter1.Value);
var parameter2 = (IDataParameter)command.Parameters[1];
Assert.Equal(ParameterDirection.Input, parameter2.Direction);
Assert.Equal("Parameter1", parameter2.ParameterName);
Assert.Equal(sqlQuery.Arguments[1], parameter2.Value);
var parameter3 = (IDataParameter)command.Parameters[2];
Assert.Equal(ParameterDirection.Input, parameter3.Direction);
Assert.Equal("Parameter2", parameter3.ParameterName);
Assert.Equal(DBNull.Value, parameter3.Value);
}
}
[Fact]
public void BuildCommandSetsDbCommandTimeoutToSqlQueryTime()
{
var sqlQuery = new SqlQuery("SELECT * FROM [Table]");
sqlQuery.Timeout = 42; // Use an oddball time which shouldn't be a default anywhere.
using (var command = new System.Data.OleDb.OleDbCommand())
{
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
mockSqlDialect.Object.BuildCommand(command, sqlQuery);
Assert.Equal(sqlQuery.Timeout, command.CommandTimeout);
}
}
[Fact]
public void CountQueryNoWhereOrOrderBy()
{
var sqlQuery = new SqlQuery("SELECT CustomerId, Name, DoB, StatusId FROM Customers");
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
var countQuery = mockSqlDialect.Object.CountQuery(sqlQuery);
Assert.Equal("SELECT COUNT(*) FROM Customers", countQuery.CommandText);
Assert.Equal(0, countQuery.Arguments.Count);
}
[Fact]
public void CountQueryWithNoWhereButOrderBy()
{
var sqlQuery = new SqlQuery("SELECT [CustomerId], [Name], [DoB], [StatusId] FROM [dbo].[Customers] ORDER BY [CustomerId] ASC");
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
var countQuery = mockSqlDialect.Object.CountQuery(sqlQuery);
Assert.Equal("SELECT COUNT(*) FROM [dbo].[Customers]", countQuery.CommandText);
Assert.Equal(0, countQuery.Arguments.Count);
}
[Fact]
public void CountQueryWithWhereAndOrderBy()
{
var sqlQuery = new SqlQuery("SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId] FROM [Sales].[Customers] WHERE [Customers].[StatusId] = ? ORDER BY [Customers].[Name] ASC", CustomerStatus.Active);
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
var countQuery = mockSqlDialect.Object.CountQuery(sqlQuery);
Assert.Equal("SELECT COUNT(*) FROM [Sales].[Customers] WHERE [Customers].[StatusId] = ?", countQuery.CommandText);
Assert.Equal(sqlQuery.Arguments[0], countQuery.Arguments[0]);////, "The first argument should be the first argument from the original query");
}
[Fact]
public void CountQueryWithWhereButNoOrderBy()
{
var sqlQuery = new SqlQuery("SELECT [Customers].[CustomerId], [Customers].[Name], [Customers].[DoB], [Customers].[StatusId] FROM [Sales].[Customers] WHERE [Customers].[StatusId] = ?", CustomerStatus.Active);
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
var countQuery = mockSqlDialect.Object.CountQuery(sqlQuery);
Assert.Equal("SELECT COUNT(*) FROM [Sales].[Customers] WHERE [Customers].[StatusId] = ?", countQuery.CommandText);
Assert.Equal(sqlQuery.Arguments[0], countQuery.Arguments[0]);////, "The first argument should be the first argument from the original query");
}
[Fact]
public void CreateQueryForInstanceThrowsNotSupportedExceptionForStatementTypeBatch()
{
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
var exception = Assert.Throws<NotSupportedException>(
() => mockSqlDialect.Object.CreateQuery(System.Data.StatementType.Batch, new Customer()));
Assert.Equal(Messages.SqlDialect_StatementTypeNotSupported, exception.Message);
}
[Fact]
public void CreateQueryForInstanceThrowsNotSupportedExceptionForStatementTypeSelect()
{
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
var exception = Assert.Throws<NotSupportedException>(
() => mockSqlDialect.Object.CreateQuery(System.Data.StatementType.Select, new Customer()));
Assert.Equal(Messages.SqlDialect_StatementTypeNotSupported, exception.Message);
}
[Fact]
public void CreateQueryForTypeThrowsNotSupportedExceptionForStatementTypeBatch()
{
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
var exception = Assert.Throws<NotSupportedException>(
() => mockSqlDialect.Object.CreateQuery(System.Data.StatementType.Batch, typeof(Customer), 1223));
Assert.Equal(Messages.SqlDialect_StatementTypeNotSupported, exception.Message);
}
[Fact]
public void CreateQueryForTypeThrowsNotSupportedExceptionForStatementTypeInsert()
{
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
var exception = Assert.Throws<NotSupportedException>(
() => mockSqlDialect.Object.CreateQuery(System.Data.StatementType.Insert, typeof(Customer), 1223));
Assert.Equal(Messages.SqlDialect_StatementTypeNotSupported, exception.Message);
}
[Fact]
public void CreateQueryForTypeThrowsNotSupportedExceptionForStatementTypeUpdate()
{
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
var exception = Assert.Throws<NotSupportedException>(
() => mockSqlDialect.Object.CreateQuery(System.Data.StatementType.Update, typeof(Customer), 1223));
Assert.Equal(Messages.SqlDialect_StatementTypeNotSupported, exception.Message);
}
[Fact]
public void DeleteQueryForInstance()
{
var customer = new Customer
{
Id = 122672
};
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
var sqlQuery = mockSqlDialect.Object.CreateQuery(StatementType.Delete, customer);
Assert.Equal("DELETE FROM \"Customers\" WHERE \"CustomerId\" = ?", sqlQuery.CommandText);
Assert.Equal(customer.Id, sqlQuery.Arguments[0]);
}
[Fact]
public void DeleteQueryForTypeByIdentifier()
{
object identifier = 239845763;
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
var sqlQuery = mockSqlDialect.Object.CreateQuery(StatementType.Delete, typeof(Customer), identifier);
Assert.Equal("DELETE FROM \"Customers\" WHERE \"CustomerId\" = ?", sqlQuery.CommandText);
Assert.Equal(identifier, sqlQuery.Arguments[0]);
}
public void Dispose()
{
// Reset the mapping convention after tests have run.
ObjectInfo.MappingConvention = new ConventionMappingConvention(ConventionMappingSettings.Default);
}
/// <summary>
/// Issue #11 - Identifier property value should be included on insert for IdentifierStrategy.Assigned.
/// </summary>
[Fact]
public void InsertQuery()
{
var customer = new Customer
{
Created = DateTime.Now,
DateOfBirth = new System.DateTime(1975, 9, 18),
Id = 134875,
Name = "<NAME>",
Status = CustomerStatus.Active,
};
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
var sqlQuery = mockSqlDialect.Object.CreateQuery(StatementType.Insert, customer);
Assert.Equal("INSERT INTO \"Customers\" (\"Created\", \"DoB\", \"CustomerId\", \"Name\", \"StatusId\") VALUES (?, ?, ?, ?, ?)", sqlQuery.CommandText);
Assert.Equal(customer.Created, sqlQuery.Arguments[0]);
Assert.Equal(customer.DateOfBirth, sqlQuery.Arguments[1]);
Assert.Equal(customer.Id, sqlQuery.Arguments[2]);
Assert.Equal(customer.Name, sqlQuery.Arguments[3]);
Assert.Equal((int)customer.Status, sqlQuery.Arguments[4]);
}
[Fact]
public void SqlCharactersPassedToConstructorAreExposed()
{
var mockSqlDialect = new Mock<SqlDialect>(SqlCharacters.MsSql);
mockSqlDialect.CallBase = true;
Assert.Same(SqlCharacters.MsSql, mockSqlDialect.Object.SqlCharacters);
}
[Fact]
public void SupportsBatchedQueriesReturnsTrueByDefault()
{
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
Assert.True(mockSqlDialect.Object.SupportsBatchedQueries);
}
[Fact]
public void UpdateQuery()
{
var customer = new Customer
{
DateOfBirth = new System.DateTime(1975, 9, 18),
Id = 134875,
Name = "<NAME>",
Status = CustomerStatus.Active,
Updated = DateTime.Now
};
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
var sqlQuery = mockSqlDialect.Object.CreateQuery(StatementType.Update, customer);
Assert.Equal("UPDATE \"Customers\" SET \"DoB\" = ?, \"Name\" = ?, \"StatusId\" = ?, \"Updated\" = ? WHERE \"CustomerId\" = ?", sqlQuery.CommandText);
Assert.Equal(customer.DateOfBirth, sqlQuery.Arguments[0]);
Assert.Equal(customer.Name, sqlQuery.Arguments[1]);
Assert.Equal((int)customer.Status, sqlQuery.Arguments[2]);
Assert.Equal(customer.Updated, sqlQuery.Arguments[3]);
Assert.Equal(customer.Id, sqlQuery.Arguments[4]);
}
public class WhenCallingCombine
{
private readonly SqlQuery combinedQuery;
private readonly SqlQuery sqlQuery1;
private readonly SqlQuery sqlQuery2;
public WhenCallingCombine()
{
this.sqlQuery1 = new SqlQuery("SELECT \"Column1\", \"Column2\", \"Column3\" FROM \"Table1\" WHERE \"Column1\" = ? AND \"Column2\" > ?", "Foo", 100);
this.sqlQuery1.Timeout = 38;
this.sqlQuery2 = new SqlQuery("SELECT \"Column1\", \"Column2\" FROM \"Table2\" WHERE (\"Column1\" = ? OR ? IS NULL) AND \"Column2\" < ?", "Bar", -1);
this.sqlQuery2.Timeout = 42;
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
this.combinedQuery = mockSqlDialect.Object.Combine(new[] { this.sqlQuery1, this.sqlQuery2 });
}
[Fact]
public void TheCombinedArgumentsShouldContainTheFirstArgumentOfTheFirstQuery()
{
Assert.Equal(this.sqlQuery1.Arguments[0], this.combinedQuery.Arguments[0]);
}
[Fact]
public void TheCombinedArgumentsShouldContainTheFirstArgumentOfTheSecondQuery()
{
Assert.Equal(this.sqlQuery2.Arguments[0], this.combinedQuery.Arguments[2]);
}
[Fact]
public void TheCombinedArgumentsShouldContainTheNumberOfArgumentsInTheSourceQueries()
{
Assert.Equal(this.sqlQuery1.Arguments.Count + this.sqlQuery2.Arguments.Count, this.combinedQuery.Arguments.Count);
}
[Fact]
public void TheCombinedArgumentsShouldContainTheSecondArgumentOfTheFirstQuery()
{
Assert.Equal(this.sqlQuery1.Arguments[1], this.combinedQuery.Arguments[1]);
}
[Fact]
public void TheCombinedArgumentsShouldContainTheSecondArgumentOfTheSecondQuery()
{
Assert.Equal(this.sqlQuery2.Arguments[1], this.combinedQuery.Arguments[3]);
}
[Fact]
public void TheCombinedCommandTextShouldBeSeparatedUsingTheSelectSeparator()
{
Assert.Equal(
"SELECT \"Column1\", \"Column2\", \"Column3\" FROM \"Table1\" WHERE \"Column1\" = ? AND \"Column2\" > ?;\r\nSELECT \"Column1\", \"Column2\" FROM \"Table2\" WHERE (\"Column1\" = ? OR ? IS NULL) AND \"Column2\" < ?",
this.combinedQuery.CommandText);
}
[Fact]
public void TheTimeoutShouldBeSetToTheLongestTimeoutOfTheSourceQueries()
{
Assert.Equal(this.sqlQuery2.Timeout, this.combinedQuery.Timeout);
}
}
public class WhenCallingCombineAndTheSourceQueriesIsNull
{
[Fact]
public void AnArgumentNullExceptionShouldBeThrown()
{
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var mockSqlDialect = new Mock<SqlDialect>(mockSqlCharacters.Object);
mockSqlDialect.CallBase = true;
var exception = Assert.Throws<ArgumentNullException>(() => mockSqlDialect.Object.Combine(null));
Assert.Equal("sqlQueries", exception.ParamName);
}
}
[MicroLite.Mapping.Table("Customers")]
private class Customer
{
public Customer()
{
}
[MicroLite.Mapping.Column("Created", allowInsert: true, allowUpdate: false)]
public DateTime Created
{
get;
set;
}
[MicroLite.Mapping.Column("DoB")]
public DateTime DateOfBirth
{
get;
set;
}
[MicroLite.Mapping.Column("CustomerId")]
[MicroLite.Mapping.Identifier(MicroLite.Mapping.IdentifierStrategy.Assigned)]
public int Id
{
get;
set;
}
[MicroLite.Mapping.Column("Name")]
public string Name
{
get;
set;
}
[MicroLite.Mapping.Column("StatusId")]
public CustomerStatus Status
{
get;
set;
}
[MicroLite.Mapping.Column("Updated", allowInsert: false, allowUpdate: true)]
public DateTime? Updated
{
get;
set;
}
}
}
}<file_sep>namespace MicroLite.Tests.Integration
{
public enum InvoiceStatus
{
Raised = 0,
PaymentReceived = 1,
Paid = 2
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="XDocumentTypeConverter.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.TypeConverters
{
using System;
using System.Xml.Linq;
/// <summary>
/// An ITypeConverter which can convert an XDocument to and from the stored database value of either an xml or string column.
/// </summary>
public sealed class XDocumentTypeConverter : TypeConverter
{
/// <summary>
/// Determines whether this type converter can convert values for the specified property type.
/// </summary>
/// <param name="propertyType">The type of the property value to be converted.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified property type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type propertyType)
{
return propertyType == typeof(XDocument);
}
/// <summary>
/// Converts the specified database value into an instance of the property type.
/// </summary>
/// <param name="value">The database value to be converted.</param>
/// <param name="propertyType">The property type to convert to.</param>
/// <returns>
/// An instance of the specified property type containing the specified value.
/// </returns>
public override object ConvertFromDbValue(object value, Type propertyType)
{
if (value == null || value == DBNull.Value)
{
return null;
}
var document = XDocument.Parse(value.ToString());
return document;
}
/// <summary>
/// Converts the specified property value into an instance of the database value.
/// </summary>
/// <param name="value">The property value to be converted.</param>
/// <param name="propertyType">The property type to convert from.</param>
/// <returns>
/// An instance of the corresponding database type for the property type containing the property value.
/// </returns>
public override object ConvertToDbValue(object value, Type propertyType)
{
if (value == null)
{
return value;
}
var document = (XDocument)value;
var xml = document.ToString(SaveOptions.DisableFormatting);
return xml;
}
}
}<file_sep>namespace MicroLite.Tests.Mapping
{
using MicroLite.Mapping;
using MicroLite.Mapping.Inflection;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="ConventionMappingSettings"/> class.
/// </summary>
public class ConventionMappingSettingsTests
{
public class WhenConstructed
{
private readonly ConventionMappingSettings settings = new ConventionMappingSettings();
[Fact]
public void TheAllowInsertFunctionShouldBeSet()
{
Assert.NotNull(this.settings.AllowInsert);
}
[Fact]
public void TheAllowUpdateFunctionShouldBeSet()
{
Assert.NotNull(this.settings.AllowUpdate);
}
[Fact]
public void TheIdentifierStrategyIsSetToDbGenerated()
{
Assert.Equal(IdentifierStrategy.DbGenerated, this.settings.IdentifierStrategy);
}
[Fact]
public void TheIgnoreFunctionShouldBeSet()
{
Assert.NotNull(this.settings.Ignore);
}
[Fact]
public void TheInflectionServiceShoulBeDefaultToTheEnglishInflectionService()
{
Assert.IsType<EnglishInflectionService>(this.settings.InflectionService);
}
[Fact]
public void TheIsIdentifierFunctionShouldBeSet()
{
Assert.NotNull(this.settings.IsIdentifier);
}
[Fact]
public void TheResolveColumnNameFunctionShouldBeSet()
{
Assert.NotNull(this.settings.ResolveColumnName);
}
[Fact]
public void TheResolveIdentifierColumnNameFunctionShouldBeSet()
{
Assert.NotNull(this.settings.ResolveIdentifierColumnName);
}
[Fact]
public void TheTableSchemIsSetToNull()
{
Assert.Null(this.settings.TableSchema);
}
[Fact]
public void UsePluralClassNameForTableNameIsSetToTrue()
{
Assert.True(this.settings.UsePluralClassNameForTableName);
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="ISessionFactory.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite
{
using MicroLite.Dialect;
/// <summary>
/// The interface which specifies the factory options for creating <see cref="ISession"/>s.
/// </summary>
public interface ISessionFactory : IHideObjectMethods
{
/// <summary>
/// Gets the name of the connection used by the session factory.
/// </summary>
string ConnectionName
{
get;
}
/// <summary>
/// Gets the SQL dialect used by the session factory.
/// </summary>
ISqlDialect SqlDialect
{
get;
}
/// <summary>
/// Opens a new read only session to the database.
/// </summary>
/// <returns>A new read only session instance.</returns>
IReadOnlySession OpenReadOnlySession();
/// <summary>
/// Opens a new session to the database.
/// </summary>
/// <returns>A new session instance.</returns>
ISession OpenSession();
}
}<file_sep>namespace MicroLite.Tests
{
using System;
using Moq;
using Xunit;
public class SqlCharactersTests
{
[Fact]
public void DefaultPropertyValues()
{
var mockSqlCharacters = new Mock<SqlCharacters>();
mockSqlCharacters.CallBase = true;
var sqlCharacters = mockSqlCharacters.Object;
Assert.Equal("\"", sqlCharacters.LeftDelimiter);
Assert.Equal("%", sqlCharacters.LikeWildcard);
Assert.Equal("\"", sqlCharacters.RightDelimiter);
Assert.Equal("*", sqlCharacters.SelectWildcard);
Assert.Equal("?", sqlCharacters.SqlParameter);
Assert.Equal(";", sqlCharacters.StatementSeparator);
Assert.Equal(false, sqlCharacters.SupportsNamedParameters);
}
[Fact]
public void EmptyDoesNotExcapeValue()
{
Assert.Equal("Name", SqlCharacters.Empty.EscapeSql("Name"));
}
[Fact]
public void EmptyEscapeSqlThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => SqlCharacters.Empty.EscapeSql(null));
}
[Fact]
public void EmptyGetParameterNameReturnsCorrectValue()
{
Assert.Equal("?", SqlCharacters.Empty.GetParameterName(0));
}
[Fact]
public void MsSqlDoesNotDoubleEscape()
{
Assert.Equal("[Name]", SqlCharacters.MsSql.EscapeSql("[Name]"));
}
[Fact]
public void MsSqlEscapeSqlThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => SqlCharacters.MsSql.EscapeSql(null));
}
[Fact]
public void MsSqlEscapesQualifiedColumnSqlCorrectly()
{
Assert.Equal("[Table].[Column]", SqlCharacters.MsSql.EscapeSql("Table.Column"));
}
[Fact]
public void MsSqlEscapesSqlCorrectly()
{
Assert.Equal("[Name]", SqlCharacters.MsSql.EscapeSql("Name"));
}
[Fact]
public void MsSqlGetParameterNameReturnsCorrectValue()
{
Assert.Equal("@p0", SqlCharacters.MsSql.GetParameterName(0));
}
[Fact]
public void MsSqlIsEscapedReturnsFalseIfNotEscaped()
{
Assert.False(SqlCharacters.MsSql.IsEscaped("Name"));
}
[Fact]
public void MsSqlIsEscapedReturnsTrueIfEscaped()
{
Assert.True(SqlCharacters.MsSql.IsEscaped("[Name]"));
}
[Fact]
public void MySqlDoesNotDoubleEscape()
{
Assert.Equal("`Name`", SqlCharacters.MySql.EscapeSql("`Name`"));
}
[Fact]
public void MySqlEscapeSqlThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => SqlCharacters.MySql.EscapeSql(null));
}
[Fact]
public void MySqlEscapesQualifiedColumnSqlCorrectly()
{
Assert.Equal("`Table`.`Column`", SqlCharacters.MySql.EscapeSql("Table.Column"));
}
[Fact]
public void MySqlEscapesSqlCorrectly()
{
Assert.Equal("`Name`", SqlCharacters.MySql.EscapeSql("Name"));
}
[Fact]
public void MySqlGetParameterNameReturnsCorrectValue()
{
Assert.Equal("@p0", SqlCharacters.MySql.GetParameterName(0));
}
[Fact]
public void MySqlIsEscapedReturnsFalseIfNotEscaped()
{
Assert.False(SqlCharacters.MySql.IsEscaped("Name"));
}
[Fact]
public void MySqlIsEscapedReturnsTrueIfEscaped()
{
Assert.True(SqlCharacters.MySql.IsEscaped("`Name`"));
}
[Fact]
public void PostgreSqlDoesNotDoubleEscape()
{
Assert.Equal("\"Name\"", SqlCharacters.PostgreSql.EscapeSql("\"Name\""));
}
[Fact]
public void PostgreSqlEscapeSqlThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => SqlCharacters.PostgreSql.EscapeSql(null));
}
[Fact]
public void PostgreSqlEscapesQualifiedColumnSqlCorrectly()
{
Assert.Equal("\"Table\".\"Column\"", SqlCharacters.PostgreSql.EscapeSql("Table.Column"));
}
[Fact]
public void PostgreSqlEscapesSqlCorrectly()
{
Assert.Equal("\"Name\"", SqlCharacters.PostgreSql.EscapeSql("Name"));
}
[Fact]
public void PostgreSqlGetParameterNameReturnsCorrectValue()
{
Assert.Equal(":p0", SqlCharacters.PostgreSql.GetParameterName(0));
}
[Fact]
public void PostgreSqlIsEscapedReturnsFalseIfNotEscaped()
{
Assert.False(SqlCharacters.PostgreSql.IsEscaped("Name"));
}
[Fact]
public void PostgreSqlIsEscapedReturnsTrueIfEscaped()
{
Assert.True(SqlCharacters.PostgreSql.IsEscaped("\"Name\""));
}
[Fact]
public void SQLiteDoesNotDoubleEscape()
{
Assert.Equal("\"Name\"", SqlCharacters.SQLite.EscapeSql("\"Name\""));
}
[Fact]
public void SQLiteEscapeSqlThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => SqlCharacters.SQLite.EscapeSql(null));
}
[Fact]
public void SQLiteEscapesQualifiedColumnSqlCorrectly()
{
Assert.Equal("\"Table\".\"Column\"", SqlCharacters.SQLite.EscapeSql("Table.Column"));
}
[Fact]
public void SQLiteEscapesSqlCorrectly()
{
Assert.Equal("\"Name\"", SqlCharacters.SQLite.EscapeSql("Name"));
}
[Fact]
public void SQLiteGetParameterNameReturnsCorrectValue()
{
Assert.Equal("@p0", SqlCharacters.SQLite.GetParameterName(0));
}
[Fact]
public void SQLiteIsEscapedReturnsFalseIfNotEscaped()
{
Assert.False(SqlCharacters.SQLite.IsEscaped("Name"));
}
[Fact]
public void SQLiteIsEscapedReturnsTrueIfEscaped()
{
Assert.True(SqlCharacters.SQLite.IsEscaped("\"Name\""));
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="IConfigureConnection.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Configuration
{
/// <summary>
/// The interface which specifies the options for configuring the connection in the fluent configuration
/// of the MicroLite ORM framework.
/// </summary>
public interface IConfigureConnection : IHideObjectMethods
{
/// <summary>
/// Specifies the name of the connection string in the app config and the sql dialect to be used.
/// </summary>
/// <param name="connectionName">The name of the connection string in the app config.</param>
/// <param name="sqlDialect">The name of the sql dialect to use for the connection.</param>
/// <returns>The next step in the fluent configuration.</returns>
/// <exception cref="System.ArgumentNullException">Thrown if connectionName is null.</exception>
/// <exception cref="MicroLiteException">Thrown if the connection is not found in the app config.</exception>
/// <exception cref="System.NotSupportedException">Thrown if the provider name or sql dialect is not supported.</exception>
ICreateSessionFactory ForConnection(string connectionName, string sqlDialect);
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="IObjectInfo.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Mapping
{
using System;
/// <summary>
/// The interface for a class which describes a type and the table it is mapped to.
/// </summary>
public interface IObjectInfo
{
/// <summary>
/// Gets an object containing the default value for the type of identifier used by the type.
/// </summary>
/// <exception cref="NotSupportedException">Thrown if the object info does not support Insert, Update or Delete.</exception>
object DefaultIdentifierValue
{
get;
}
/// <summary>
/// Gets type the object info relates to.
/// </summary>
Type ForType
{
get;
}
/// <summary>
/// Gets the table info for the type the object info relates to.
/// </summary>
/// <exception cref="NotSupportedException">Thrown if the object info does not support Insert, Update or Delete.</exception>
TableInfo TableInfo
{
get;
}
/// <summary>
/// Creates a new instance of the type.
/// </summary>
/// <returns>A new instance of the type.</returns>
object CreateInstance();
/// <summary>
/// Gets the property value for the object identifier.
/// </summary>
/// <param name="instance">The instance to retrieve the value from.</param>
/// <returns>The value of the identifier property.</returns>
/// <exception cref="NotSupportedException">Thrown if the object info does not support Insert, Update or Delete.</exception>
object GetIdentifierValue(object instance);
/// <summary>
/// Gets the property value for the specified property on the specified instance.
/// </summary>
/// <param name="instance">The instance to retrieve the value from.</param>
/// <param name="propertyName">Name of the property to get the value for.</param>
/// <returns>The value of the property.</returns>
/// <exception cref="NotSupportedException">Thrown if the object info does not support Insert, Update or Delete.</exception>
object GetPropertyValue(object instance, string propertyName);
/// <summary>
/// Gets the property value from the specified instance and converts it to the correct type for the specified column.
/// </summary>
/// <param name="instance">The instance to retrieve the value from.</param>
/// <param name="columnName">Name of the column to get the value for.</param>
/// <returns>The column value of the property.</returns>
/// <exception cref="NotSupportedException">Thrown if the object info does not support Insert, Update or Delete.</exception>
object GetPropertyValueForColumn(object instance, string columnName);
/// <summary>
/// Determines whether the specified instance has the default identifier value.
/// </summary>
/// <param name="instance">The instance.</param>
/// <returns>
/// <c>true</c> if the instance has the default identifier value; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="NotSupportedException">Thrown if the object info does not support Insert, Update or Delete.</exception>
bool HasDefaultIdentifierValue(object instance);
/// <summary>
/// Sets the property value for the specified property on the specified instance to the specified value.
/// </summary>
/// <param name="instance">The instance to set the property value on.</param>
/// <param name="propertyName">Name of the property to set the value for.</param>
/// <param name="value">The value to be set.</param>
/// <exception cref="NotSupportedException">Thrown if the object info does not support Insert, Update or Delete.</exception>
void SetPropertyValue(object instance, string propertyName, object value);
/// <summary>
/// Sets the property value of the property mapped to the specified column after converting it to the correct type for the property.
/// </summary>
/// <param name="instance">The instance to set the property value on.</param>
/// <param name="columnName">The name of the column the property is mapped to.</param>
/// <param name="value">The value from the database column to set the property to.</param>
void SetPropertyValueForColumn(object instance, string columnName, object value);
}
}<file_sep>namespace MicroLite.Tests.Configuration
{
using System;
using MicroLite.Configuration;
using MicroLite.Mapping;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="ConfigurationExtensions"/> class.
/// </summary>
public class ConfigurationExtensionsTests
{
public class WhenCallingForMsSqlConnection
{
private readonly Mock<IConfigureConnection> mockConfigureConnection = new Mock<IConfigureConnection>();
public WhenCallingForMsSqlConnection()
{
ConfigurationExtensions.ForMsSqlConnection(this.mockConfigureConnection.Object, "TestConnection");
}
[Fact]
public void SetMappingConventionIsCalledWithAnInstanceOfAttributeMappingConvention()
{
this.mockConfigureConnection.Verify(x => x.ForConnection("TestConnection", "MicroLite.Dialect.MsSqlDialect"), Times.Once());
}
}
public class WhenCallingForMsSqlConnectionAndTheConfigureConnectionIsNull
{
[Fact]
public void AnArgumentNullExceptionIsThrown()
{
var exception = Assert.Throws<ArgumentNullException>(() => ConfigurationExtensions.ForMsSqlConnection(null, "TestConnection"));
Assert.Equal("configureConnection", exception.ParamName);
}
}
public class WhenCallingForMySqlConnection
{
private readonly Mock<IConfigureConnection> mockConfigureConnection = new Mock<IConfigureConnection>();
public WhenCallingForMySqlConnection()
{
ConfigurationExtensions.ForMySqlConnection(this.mockConfigureConnection.Object, "TestConnection");
}
[Fact]
public void SetMappingConventionIsCalledWithAnInstanceOfAttributeMappingConvention()
{
this.mockConfigureConnection.Verify(x => x.ForConnection("TestConnection", "MicroLite.Dialect.MySqlDialect"), Times.Once());
}
}
public class WhenCallingForMySqlConnectionAndTheConfigureConnectionIsNull
{
[Fact]
public void AnArgumentNullExceptionIsThrown()
{
var exception = Assert.Throws<ArgumentNullException>(() => ConfigurationExtensions.ForMySqlConnection(null, "TestConnection"));
Assert.Equal("configureConnection", exception.ParamName);
}
}
public class WhenCallingForPostgreSqlConnection
{
private readonly Mock<IConfigureConnection> mockConfigureConnection = new Mock<IConfigureConnection>();
public WhenCallingForPostgreSqlConnection()
{
ConfigurationExtensions.ForPostgreSqlConnection(this.mockConfigureConnection.Object, "TestConnection");
}
[Fact]
public void SetMappingConventionIsCalledWithAnInstanceOfAttributeMappingConvention()
{
this.mockConfigureConnection.Verify(x => x.ForConnection("TestConnection", "MicroLite.Dialect.PostgreSqlDialect"), Times.Once());
}
}
public class WhenCallingForPostgreSqlConnectionAndTheConfigureConnectionIsNull
{
[Fact]
public void AnArgumentNullExceptionIsThrown()
{
var exception = Assert.Throws<ArgumentNullException>(() => ConfigurationExtensions.ForPostgreSqlConnection(null, "TestConnection"));
Assert.Equal("configureConnection", exception.ParamName);
}
}
public class WhenCallingForSQLiteConnection
{
private readonly Mock<IConfigureConnection> mockConfigureConnection = new Mock<IConfigureConnection>();
public WhenCallingForSQLiteConnection()
{
ConfigurationExtensions.ForSQLiteConnection(this.mockConfigureConnection.Object, "TestConnection");
}
[Fact]
public void SetMappingConventionIsCalledWithAnInstanceOfAttributeMappingConvention()
{
this.mockConfigureConnection.Verify(x => x.ForConnection("TestConnection", "MicroLite.Dialect.SQLiteDialect"), Times.Once());
}
}
public class WhenCallingForSQLiteConnectionAndTheConfigureConnectionIsNull
{
[Fact]
public void AnArgumentNullExceptionIsThrown()
{
var exception = Assert.Throws<ArgumentNullException>(() => ConfigurationExtensions.ForSQLiteConnection(null, "TestConnection"));
Assert.Equal("configureConnection", exception.ParamName);
}
}
public class WhenCallingWithAttributeBasedMapping
{
private readonly Mock<IConfigureExtensions> mockConfigureExtensions = new Mock<IConfigureExtensions>();
public WhenCallingWithAttributeBasedMapping()
{
ConfigurationExtensions.WithAttributeBasedMapping(this.mockConfigureExtensions.Object);
}
[Fact]
public void SetMappingConventionIsCalledWithAnInstanceOfAttributeMappingConvention()
{
this.mockConfigureExtensions.Verify(x => x.SetMappingConvention(It.IsAny<AttributeMappingConvention>()), Times.Once());
}
}
public class WhenCallingWithAttributeBasedMappingAndTheConfigureExtensionsIsNull
{
[Fact]
public void AnArgumentNullExceptionIsThrown()
{
var exception = Assert.Throws<ArgumentNullException>(() => ConfigurationExtensions.WithAttributeBasedMapping(null));
Assert.Equal("configureExtensions", exception.ParamName);
}
}
public class WhenCallingWithConventionBasedMapping
{
private readonly Mock<IConfigureExtensions> mockConfigureExtensions = new Mock<IConfigureExtensions>();
public WhenCallingWithConventionBasedMapping()
{
ConfigurationExtensions.WithConventionBasedMapping(this.mockConfigureExtensions.Object, new ConventionMappingSettings());
}
[Fact]
public void SetMappingConventionIsCalledWithAnInstanceOfConventionMappingConvention()
{
this.mockConfigureExtensions.Verify(x => x.SetMappingConvention(It.IsAny<ConventionMappingConvention>()), Times.Once());
}
}
public class WhenCallingWithConventionBasedMappingAndTheConfigureExtensionsIsNull
{
[Fact]
public void AnArgumentNullExceptionIsThrown()
{
var exception = Assert.Throws<ArgumentNullException>(() => ConfigurationExtensions.WithConventionBasedMapping(null, new ConventionMappingSettings()));
Assert.Equal("configureExtensions", exception.ParamName);
}
}
public class WhenCallingWithConventionBasedMappingAndTheSettingsAreNull
{
[Fact]
public void AnArgumentNullExceptionIsThrown()
{
var exception = Assert.Throws<ArgumentNullException>(() => ConfigurationExtensions.WithConventionBasedMapping(new Mock<IConfigureExtensions>().Object, null));
Assert.Equal("settings", exception.ParamName);
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="TypeConverter.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.TypeConverters
{
using System;
using System.Linq;
/// <summary>
/// The base class for any implementation of <see cref="ITypeConverter"/>.
/// </summary>
public abstract class TypeConverter : ITypeConverter
{
private static readonly TypeConverterCollection collection = new TypeConverterCollection();
/// <summary>
/// Gets the type converter collection which contains all type converters registered with the MicroLite ORM framework.
/// </summary>
public static TypeConverterCollection Converters
{
get
{
return collection;
}
}
/// <summary>
/// Gets the <see cref="ITypeConverter"/> for the specified type.
/// </summary>
/// <param name="type">The type to get the converter for.</param>
/// <returns>The <see cref="ITypeConverter"/> for the specified type.</returns>
public static ITypeConverter For(Type type)
{
return Converters.First(c => c.CanConvert(type));
}
/// <summary>
/// Resolves the actual type. If the type is generic (as it would be for a nullable struct) it returns the inner type.
/// </summary>
/// <param name="type">The type to resolve.</param>
/// <returns>The actual type.</returns>
public static Type ResolveActualType(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
return type.IsGenericType ? type.GetGenericArguments()[0] : type;
}
/// <summary>
/// Determines whether this type converter can convert values for the specified property type.
/// </summary>
/// <param name="propertyType">The type of the property value to be converted.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified property type; otherwise, <c>false</c>.
/// </returns>
public abstract bool CanConvert(Type propertyType);
/// <summary>
/// Converts the specified database value into an instance of the property type.
/// </summary>
/// <param name="value">The database value to be converted.</param>
/// <param name="propertyType">The property type to convert to.</param>
/// <returns>
/// An instance of the specified property type containing the specified value.
/// </returns>
public abstract object ConvertFromDbValue(object value, Type propertyType);
/// <summary>
/// Converts the specified property value into an instance of the database value.
/// </summary>
/// <param name="value">The property value to be converted.</param>
/// <param name="propertyType">The property type to convert from.</param>
/// <returns>
/// An instance of the corresponding database type for the property type containing the property value.
/// </returns>
public abstract object ConvertToDbValue(object value, Type propertyType);
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="AdoTransaction.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Core
{
using System;
using System.Data;
using MicroLite.Logging;
/// <summary>
/// The an implementation of <see cref="ITransaction"/> which manages an ADO transaction.
/// </summary>
[System.Diagnostics.DebuggerDisplay("Transaction - Active:{IsActive}, Committed:{WasCommitted}, RolledBack:{WasRolledBack}")]
internal sealed class AdoTransaction : ITransaction
{
private static readonly ILog log = LogManager.GetCurrentClassLog();
private readonly IsolationLevel isolationLevel;
private bool committed;
private IDbConnection connection;
private bool disposed;
private bool failed;
private bool rolledBack;
private IDbTransaction transaction;
/// <summary>
/// Initialises a new instance of the <see cref="AdoTransaction"/> class.
/// </summary>
/// <param name="transaction">The transaction.</param>
/// <remarks>This is to enable easier unit testing only, all production code should call Transaction.Begin().</remarks>
internal AdoTransaction(IDbTransaction transaction)
{
this.transaction = transaction;
this.connection = transaction.Connection;
this.isolationLevel = transaction.IsolationLevel;
}
public bool IsActive
{
get
{
return !this.committed && !this.rolledBack && !this.failed;
}
}
public IsolationLevel IsolationLevel
{
get
{
return this.isolationLevel;
}
}
public bool WasCommitted
{
get
{
return this.committed;
}
}
public bool WasRolledBack
{
get
{
return this.rolledBack;
}
}
public void Commit()
{
this.ThrowIfDisposed();
this.ThrowIfNotActive();
try
{
log.TryLogDebug(Messages.Transaction_Committing);
this.transaction.Commit();
log.TryLogDebug(Messages.Transaction_Committed);
this.committed = true;
this.connection.Close();
}
catch (Exception e)
{
this.failed = true;
log.TryLogError(e.Message, e);
throw new MicroLiteException(e.Message, e);
}
}
public void Dispose()
{
if (!this.disposed)
{
if (this.IsActive)
{
log.TryLogWarn(Messages.Transaction_DisposedUncommitted);
this.Rollback();
}
else if (this.failed && !this.rolledBack)
{
log.TryLogWarn(Messages.Transaction_RollingBackFailedCommit);
this.Rollback();
}
this.transaction.Dispose();
this.transaction = null;
this.connection = null;
log.TryLogDebug(Messages.Transaction_Disposed);
this.disposed = true;
}
}
public void Enlist(IDbCommand command)
{
if (command == null)
{
throw new ArgumentNullException("command");
}
if (this.IsActive)
{
log.TryLogDebug(Messages.Transaction_EnlistingCommand);
command.Transaction = this.transaction;
}
}
public void Rollback()
{
this.ThrowIfDisposed();
this.ThrowIfRolledBackOrCommitted();
try
{
log.TryLogDebug(Messages.Transaction_RollingBack);
this.transaction.Rollback();
log.TryLogDebug(Messages.Transaction_RolledBack);
this.rolledBack = true;
this.connection.Close();
}
catch (Exception e)
{
this.failed = true;
log.TryLogError(e.Message, e);
throw new MicroLiteException(e.Message, e);
}
}
private void ThrowIfDisposed()
{
if (this.disposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
}
private void ThrowIfNotActive()
{
if (!this.IsActive)
{
throw new InvalidOperationException(Messages.Transaction_Completed);
}
}
private void ThrowIfRolledBackOrCommitted()
{
if (this.rolledBack || this.committed)
{
throw new InvalidOperationException(Messages.Transaction_Completed);
}
}
}
}<file_sep>using System;
using System.Xml.Linq;
using MicroLite.TypeConverters;
using Xunit;
namespace MicroLite.Tests.TypeConverters
{
public class XDocumentTypeConverterTests
{
public class WhenCallingCanConvertTypeOfXDocument
{
[Fact]
public void TrueShouldBeReturned()
{
var typeConverter = new XDocumentTypeConverter();
Assert.True(typeConverter.CanConvert(typeof(XDocument)));
}
}
public class WhenCallingConvertFromDbValueAndTheValueIsNotNull
{
private object result;
private ITypeConverter typeConverter = new XDocumentTypeConverter();
private string value = "<customer><name>fred</name></customer>";
public WhenCallingConvertFromDbValueAndTheValueIsNotNull()
{
this.result = typeConverter.ConvertFromDbValue(value, typeof(XDocument));
}
[Fact]
public void TheResultShouldBeAnXDocument()
{
Assert.IsType<XDocument>(this.result);
}
[Fact]
public void TheResultShouldContainTheSpecifiedValue()
{
Assert.Equal(
XDocument.Parse(this.value).ToString(SaveOptions.DisableFormatting),
((XDocument)this.result).ToString(SaveOptions.DisableFormatting));
}
}
public class WhenCallingConvertFromDbValueAndTheValueIsNull
{
private object result;
private ITypeConverter typeConverter = new XDocumentTypeConverter();
public WhenCallingConvertFromDbValueAndTheValueIsNull()
{
this.result = typeConverter.ConvertFromDbValue(DBNull.Value, typeof(XDocument));
}
[Fact]
public void TheResultShouldBeNull()
{
Assert.Null(this.result);
}
}
public class WhenCallingConvertToDbValueAndTheValueIsNotNull
{
private object result;
private ITypeConverter typeConverter = new XDocumentTypeConverter();
private XDocument value = XDocument.Parse("<customer><name>fred</name></customer>");
public WhenCallingConvertToDbValueAndTheValueIsNotNull()
{
this.result = typeConverter.ConvertToDbValue(value, typeof(XDocument));
}
[Fact]
public void TheResultShouldBeAString()
{
Assert.IsType<string>(this.result);
}
[Fact]
public void TheResultShouldContainTheSpecifiedValue()
{
Assert.Equal(this.value.ToString(SaveOptions.DisableFormatting), this.result);
}
}
public class WhenCallingConvertToDbValueAndTheValueIsNull
{
private object result;
private ITypeConverter typeConverter = new XDocumentTypeConverter();
public WhenCallingConvertToDbValueAndTheValueIsNull()
{
this.result = typeConverter.ConvertToDbValue(null, typeof(XDocument));
}
[Fact]
public void TheResultShouldBeNull()
{
Assert.Null(this.result);
}
}
}
}<file_sep>namespace MicroLite.Tests.Mapping
{
using System;
using System.Collections.ObjectModel;
using MicroLite.FrameworkExtensions;
using MicroLite.Mapping;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="TableInfo"/> class.
/// </summary>
public class TableInfoTests
{
[Fact]
public void ConstructorSetsPropertyValues()
{
var columns = new ReadOnlyCollection<ColumnInfo>(new[]
{
new ColumnInfo("Name", typeof(Customer).GetProperty("Name"), false, true, true),
new ColumnInfo("CustomerId", typeof(Customer).GetProperty("Id"), true, true, true)
});
var identifierStrategy = IdentifierStrategy.Guid;
var name = "Customers";
var schema = "Sales";
var tableInfo = new TableInfo(columns, identifierStrategy, name, schema);
Assert.Equal(columns, tableInfo.Columns);
Assert.Equal(columns[1].ColumnName, tableInfo.IdentifierColumn);
Assert.Equal(columns[1].PropertyInfo.Name, tableInfo.IdentifierProperty);
Assert.Equal(identifierStrategy, tableInfo.IdentifierStrategy);
Assert.Equal(name, tableInfo.Name);
Assert.Equal(schema, tableInfo.Schema);
}
[Fact]
public void ConstructorThrowsArgumentNullExceptionForNullColumns()
{
var exception = Assert.Throws<ArgumentNullException>(
() => new TableInfo(columns: null, identifierStrategy: IdentifierStrategy.DbGenerated, name: "Customers", schema: "Sales"));
Assert.Equal("columns", exception.ParamName);
}
[Fact]
public void ConstructorThrowsArgumentNullExceptionForNullName()
{
var exception = Assert.Throws<ArgumentNullException>(
() => new TableInfo(columns: new ColumnInfo[0], identifierStrategy: IdentifierStrategy.DbGenerated, name: null, schema: "Sales"));
Assert.Equal("name", exception.ParamName);
}
[Fact]
public void ConstructorThrowsMicroLiteExceptionIfMultipleColumnsWithSameName()
{
var columns = new[]
{
new ColumnInfo("Name", typeof(Customer).GetProperty("Name"), false, true, true),
new ColumnInfo("Name", typeof(Customer).GetProperty("Name"), false, true, true)
};
var exception = Assert.Throws<MicroLiteException>(
() => new TableInfo(columns: columns, identifierStrategy: IdentifierStrategy.DbGenerated, name: "Customers", schema: "Sales"));
Assert.Equal(Messages.TableInfo_ColumnMappedMultipleTimes.FormatWith("Name"), exception.Message);
}
[Fact]
public void ConstructorThrowsMicroLiteExceptionIfNoColumnsAreIdentifierColumn()
{
var columns = new[]
{
new ColumnInfo("Name", typeof(Customer).GetProperty("Name"), false, true, true)
};
var exception = Assert.Throws<MicroLiteException>(
() => new TableInfo(columns: columns, identifierStrategy: IdentifierStrategy.DbGenerated, name: "Customers", schema: "Sales"));
Assert.Equal(Messages.TableInfo_NoIdentifierColumn.FormatWith("Sales", "Customers"), exception.Message);
}
private class Customer
{
public Customer()
{
}
public Guid Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="SqlBuilder.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Query
{
using System.Collections.Generic;
using System.Text;
using MicroLite.Dialect;
/// <summary>
/// A helper class for building an <see cref="SqlQuery" />.
/// </summary>
[System.Diagnostics.DebuggerDisplay("{innerSql}")]
public abstract class SqlBuilder : IToSqlQuery
{
private readonly List<object> arguments = new List<object>();
private readonly StringBuilder innerSql = new StringBuilder(capacity: 120);
/// <summary>
/// Gets or sets the SQL characters.
/// </summary>
/// <remarks>If no specific SqlCharacters are specified, SqlCharacters.Empty will be used.</remarks>
public static SqlCharacters SqlCharacters
{
get;
set;
}
/// <summary>
/// Gets the arguments currently added to the sql builder.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Justification = "Allowed in this instance, we want to make use of AddRange.")]
protected List<object> Arguments
{
get
{
return this.arguments;
}
}
/// <summary>
/// Gets the inner sql the sql builder.
/// </summary>
protected StringBuilder InnerSql
{
get
{
return this.innerSql;
}
}
/// <summary>
/// Species the name of the procedure to be executed.
/// </summary>
/// <param name="procedure">The name of the stored procedure.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <remarks>If the stored procedure has no parameters, call .ToSqlQuery() otherwise add the parameters (see the WithParameter method).</remarks>
/// <example>
/// <code>
/// var query = SqlBuilder.Execute("CustomersOver50").ToSqlQuery();
/// </code>
/// </example>
public static IWithParameter Execute(string procedure)
{
return new StoredProcedureSqlBuilder(procedure);
}
/// <summary>
/// Creates a new query which selects the specified columns.
/// </summary>
/// <param name="columns">The columns to be included in the query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// Option 1, don't enter any column names, this is generally used if you want to just call a function such as Count.
/// <code>
/// var query = SqlBuilder.Select()...
/// </code>
/// </example>
/// <example>
/// Option 2, enter specific column names.
/// <code>
/// var query = SqlBuilder.Select("Name", "DoB")...
/// </code>
/// </example>
/// <example>
/// Option 3, enter * followed by a table name
/// <code>
/// var query = SqlBuilder.Select("*").From("Customers")...
///
/// // SELECT * FROM Customers
/// // will be generated
/// </code>
/// </example>
/// <example>
/// Option 4, enter * followed by a type in From, all mapped columns will be specified in the SQL.
/// <code>
/// var query = SqlBuilder.Select("*").From(typeof(Customer))...
///
/// // SELECT CustomerId, Name, DoB FROM Customers
/// // will be generated
/// </code>
/// </example>
public static IFunctionOrFrom Select(params string[] columns)
{
var sqlCharacters = SqlBuilder.SqlCharacters ?? SqlCharacters.Empty;
return new SelectSqlBuilder(sqlCharacters, columns);
}
/// <summary>
/// Creates a <see cref="SqlQuery"/> from the values specified.
/// </summary>
/// <returns>The created <see cref="SqlQuery"/>.</returns>
/// <remarks>This method is called to return an SqlQuery once query has been defined.</remarks>
public SqlQuery ToSqlQuery()
{
return new SqlQuery(this.innerSql.ToString(), this.arguments.ToArray());
}
}
}<file_sep>namespace MicroLite.Tests.Core
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Xml.Linq;
using MicroLite.Core;
using MicroLite.Mapping;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="IncludeMany<T>"/> class.
/// </summary>
public class IncludeManyTests
{
private enum CustomerStatus
{
Disabled = 0,
Active = 1
}
public class WhenBuildValueHasBeenCalledAndThereAreNoResults
{
private IncludeMany<Customer> include = new IncludeMany<Customer>();
private Mock<IObjectBuilder> mockObjectBuilder = new Mock<IObjectBuilder>();
private Mock<IDataReader> mockReader = new Mock<IDataReader>();
public WhenBuildValueHasBeenCalledAndThereAreNoResults()
{
this.mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { false }).Dequeue);
var reader = this.mockReader.Object;
this.mockObjectBuilder.Setup(x => x.BuildInstance<Customer>(It.IsAny<ObjectInfo>(), reader));
this.include.BuildValue(this.mockReader.Object, this.mockObjectBuilder.Object);
}
[Fact]
public void HasValueShouldBeFalse()
{
Assert.False(this.include.HasValue);
}
[Fact]
public void TheDataReaderShouldBeRead()
{
this.mockReader.VerifyAll();
}
[Fact]
public void TheObjectBuilderShouldNotBuildAnyObjects()
{
this.mockObjectBuilder.Verify(
x => x.BuildInstance<Customer>(It.IsAny<ObjectInfo>(), It.IsAny<IDataReader>()),
Times.Never(),
"If the first call to IDataReader.Read() returns false, we should not try and create an object.");
}
[Fact]
public void ValuesShouldBeEmpty()
{
Assert.Empty(this.include.Values);
}
}
public class WhenBuildValueHasBeenCalledAndThereAreResults
{
private IncludeMany<Customer> include = new IncludeMany<Customer>();
private Mock<IObjectBuilder> mockObjectBuilder = new Mock<IObjectBuilder>();
private Mock<IDataReader> mockReader = new Mock<IDataReader>();
public WhenBuildValueHasBeenCalledAndThereAreResults()
{
this.mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
var reader = this.mockReader.Object;
this.mockObjectBuilder.Setup(x => x.BuildInstance<Customer>(It.IsAny<ObjectInfo>(), reader)).Returns(new Customer());
this.include.BuildValue(reader, this.mockObjectBuilder.Object);
}
[Fact]
public void HasValueShouldBeTrue()
{
Assert.True(this.include.HasValue);
}
[Fact]
public void TheDataReaderShouldBeRead()
{
this.mockReader.VerifyAll();
}
[Fact]
public void TheObjectBuilderShouldBeCalled()
{
this.mockObjectBuilder.VerifyAll();
}
[Fact]
public void ValuesShouldNotBeEmpty()
{
Assert.NotEmpty(this.include.Values);
}
}
public class WhenBuildValueHasNotBeenCalled
{
private IncludeMany<Customer> include = new IncludeMany<Customer>();
public WhenBuildValueHasNotBeenCalled()
{
}
[Fact]
public void HasValueShouldBeFalse()
{
Assert.False(this.include.HasValue);
}
[Fact]
public void ValuesShouldBeEmpty()
{
Assert.Empty(this.include.Values);
}
}
public class WhenTheTypeIsAGuid
{
private IncludeMany<Guid> include = new IncludeMany<Guid>();
private Mock<IObjectBuilder> mockObjectBuilder = new Mock<IObjectBuilder>();
private Mock<IDataReader> mockReader = new Mock<IDataReader>();
public WhenTheTypeIsAGuid()
{
this.mockReader.Setup(x => x[0]).Returns(new Guid("97FE0200-8F79-4C3B-8CD4-BE97705868EC"));
this.mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
var reader = this.mockReader.Object;
this.include.BuildValue(reader, this.mockObjectBuilder.Object);
}
[Fact]
public void HasValueShouldBeTrue()
{
Assert.True(this.include.HasValue);
}
[Fact]
public void TheDataReaderShouldBeRead()
{
this.mockReader.VerifyAll();
}
[Fact]
public void TheObjectBuilderShouldNotBeUsed()
{
this.mockObjectBuilder.Verify(x => x.BuildInstance<Guid>(It.IsAny<IObjectInfo>(), It.IsAny<IDataReader>()), Times.Never());
}
[Fact]
public void ValuesShouldContainTheResultOfTheTypeConversion()
{
Assert.Equal(Guid.Parse("97FE0200-8F79-4C3B-8CD4-BE97705868EC"), this.include.Values[0]);
}
[Fact]
public void ValuesShouldNotBeEmpty()
{
Assert.NotEmpty(this.include.Values);
}
}
public class WhenTheTypeIsAnEnum
{
private IncludeMany<CustomerStatus> include = new IncludeMany<CustomerStatus>();
private Mock<IObjectBuilder> mockObjectBuilder = new Mock<IObjectBuilder>();
private Mock<IDataReader> mockReader = new Mock<IDataReader>();
public WhenTheTypeIsAnEnum()
{
this.mockReader.Setup(x => x[0]).Returns(1);
this.mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
var reader = this.mockReader.Object;
this.include.BuildValue(reader, this.mockObjectBuilder.Object);
}
[Fact]
public void HasValueShouldBeTrue()
{
Assert.True(this.include.HasValue);
}
[Fact]
public void TheDataReaderShouldBeRead()
{
this.mockReader.VerifyAll();
}
[Fact]
public void TheObjectBuilderShouldNotBeUsed()
{
this.mockObjectBuilder.Verify(x => x.BuildInstance<CustomerStatus>(It.IsAny<IObjectInfo>(), It.IsAny<IDataReader>()), Times.Never());
}
[Fact]
public void ValuesShouldContainTheResultOfTheTypeConversion()
{
Assert.Equal(CustomerStatus.Active, this.include.Values[0]);
}
[Fact]
public void ValuesShouldNotBeEmpty()
{
Assert.NotEmpty(this.include.Values);
}
}
public class WhenTheTypeIsAnXDocument
{
private IncludeMany<XDocument> include = new IncludeMany<XDocument>();
private Mock<IObjectBuilder> mockObjectBuilder = new Mock<IObjectBuilder>();
private Mock<IDataReader> mockReader = new Mock<IDataReader>();
public WhenTheTypeIsAnXDocument()
{
this.mockReader.Setup(x => x[0]).Returns("<xml><element>text</element></xml>");
this.mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
var reader = this.mockReader.Object;
this.include.BuildValue(reader, this.mockObjectBuilder.Object);
}
[Fact]
public void HasValueShouldBeTrue()
{
Assert.True(this.include.HasValue);
}
[Fact]
public void TheDataReaderShouldBeRead()
{
this.mockReader.VerifyAll();
}
[Fact]
public void TheObjectBuilderShouldNotBeUsed()
{
this.mockObjectBuilder.Verify(x => x.BuildInstance<XDocument>(It.IsAny<IObjectInfo>(), It.IsAny<IDataReader>()), Times.Never());
}
[Fact]
public void ValuesShouldContainTheResultOfTheTypeConversion()
{
Assert.Equal(XDocument.Parse("<xml><element>text</element></xml>").ToString(SaveOptions.DisableFormatting), this.include.Values[0].ToString(SaveOptions.DisableFormatting));
}
[Fact]
public void ValuesShouldNotBeEmpty()
{
Assert.NotEmpty(this.include.Values);
}
}
public class WhenTheTypeIsAString
{
private IncludeMany<string> include = new IncludeMany<string>();
private Mock<IObjectBuilder> mockObjectBuilder = new Mock<IObjectBuilder>();
private Mock<IDataReader> mockReader = new Mock<IDataReader>();
public WhenTheTypeIsAString()
{
this.mockReader.Setup(x => x[0]).Returns("Foo");
this.mockReader.Setup(x => x.Read()).Returns(new Queue<bool>(new[] { true, false }).Dequeue);
var reader = this.mockReader.Object;
this.include.BuildValue(reader, this.mockObjectBuilder.Object);
}
[Fact]
public void HasValueShouldBeTrue()
{
Assert.True(this.include.HasValue);
}
[Fact]
public void TheDataReaderShouldBeRead()
{
this.mockReader.VerifyAll();
}
[Fact]
public void TheObjectBuilderShouldNotBeUsed()
{
this.mockObjectBuilder.Verify(x => x.BuildInstance<string>(It.IsAny<IObjectInfo>(), It.IsAny<IDataReader>()), Times.Never());
}
[Fact]
public void ValuesShouldContainTheResultOfTheTypeConversion()
{
Assert.Equal("Foo", this.include.Values[0]);
}
[Fact]
public void ValuesShouldNotBeEmpty()
{
Assert.NotEmpty(this.include.Values);
}
}
[MicroLite.Mapping.Table("Customers")]
private class Customer
{
[MicroLite.Mapping.Column("CustomerId")]
[MicroLite.Mapping.Identifier(MicroLite.Mapping.IdentifierStrategy.DbGenerated)]
public int Id
{
get;
set;
}
}
}
}<file_sep>namespace MicroLite.Tests.Logging
{
using System;
using MicroLite.Logging;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="LogExtensions"/> class.
/// </summary>
public class LogExtensionsTests
{
[Fact]
public void TryLogDebugWithArgs()
{
var message = "Some log message";
var args = new[] { "foo" };
var mockLog = new Mock<ILog>();
mockLog.Setup(x => x.Debug(message, args));
mockLog.Object.TryLogDebug(message, args);
mockLog.VerifyAll();
}
[Fact]
public void TryLogDebugWithoutArgs()
{
var message = "Some log message";
var mockLog = new Mock<ILog>();
mockLog.Setup(x => x.Debug(message));
mockLog.Object.TryLogDebug(message);
mockLog.VerifyAll();
}
[Fact]
public void TryLogErrorWithArgs()
{
var message = "Some log message";
var args = new[] { "foo" };
var mockLog = new Mock<ILog>();
mockLog.Setup(x => x.Error(message, args));
mockLog.Object.TryLogError(message, args);
mockLog.VerifyAll();
}
[Fact]
public void TryLogErrorWithException()
{
var message = "Some log message";
var exception = new Exception();
var mockLog = new Mock<ILog>();
mockLog.Setup(x => x.Error(message, exception));
mockLog.Object.TryLogError(message, exception);
mockLog.VerifyAll();
}
[Fact]
public void TryLogErrorWithoutArgs()
{
var message = "Some log message";
var mockLog = new Mock<ILog>();
mockLog.Setup(x => x.Error(message));
mockLog.Object.TryLogError(message);
mockLog.VerifyAll();
}
[Fact]
public void TryLogFatalWithArgs()
{
var message = "Some log message";
var args = new[] { "foo" };
var mockLog = new Mock<ILog>();
mockLog.Setup(x => x.Fatal(message, args));
mockLog.Object.TryLogFatal(message, args);
mockLog.VerifyAll();
}
[Fact]
public void TryLogFatalWithException()
{
var message = "Some log message";
var exception = new Exception();
var mockLog = new Mock<ILog>();
mockLog.Setup(x => x.Fatal(message, exception));
mockLog.Object.TryLogFatal(message, exception);
mockLog.VerifyAll();
}
[Fact]
public void TryLogFatalWithoutArgs()
{
var message = "Some log message";
var mockLog = new Mock<ILog>();
mockLog.Setup(x => x.Fatal(message));
mockLog.Object.TryLogFatal(message);
mockLog.VerifyAll();
}
[Fact]
public void TryLogInfoWithArgs()
{
var message = "Some log message";
var args = new[] { "foo" };
var mockLog = new Mock<ILog>();
mockLog.Setup(x => x.Info(message, args));
mockLog.Object.TryLogInfo(message, args);
mockLog.VerifyAll();
}
[Fact]
public void TryLogInfoWithoutArgs()
{
var message = "Some log message";
var mockLog = new Mock<ILog>();
mockLog.Setup(x => x.Info(message));
mockLog.Object.TryLogInfo(message);
mockLog.VerifyAll();
}
[Fact]
public void TryLogWarnWithArgs()
{
var message = "Some log message";
var args = new[] { "foo" };
var mockLog = new Mock<ILog>();
mockLog.Setup(x => x.Warn(message, args));
mockLog.Object.TryLogWarn(message, args);
mockLog.VerifyAll();
}
[Fact]
public void TryLogWarnWithoutArgs()
{
var message = "Some log message";
var mockLog = new Mock<ILog>();
mockLog.Setup(x => x.Warn(message));
mockLog.Object.TryLogWarn(message);
mockLog.VerifyAll();
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="IOrderBy.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Query
{
/// <summary>
/// The interface which specifies the order by method in the fluent sql builder syntax.
/// </summary>
public interface IOrderBy : IHideObjectMethods, IToSqlQuery
{
/// <summary>
/// Orders the results of the query by the specified columns in ascending order.
/// </summary>
/// <param name="columns">The columns to order by.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IOrderBy OrderByAscending(params string[] columns);
/// <summary>
/// Orders the results of the query by the specified columns in descending order.
/// </summary>
/// <param name="columns">The columns to order by.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IOrderBy OrderByDescending(params string[] columns);
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="IncludeScalar.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Core
{
using System;
using System.Data;
using MicroLite.TypeConverters;
/// <summary>
/// The default implementation of <see cref="IInclude<T>"/> for scalar results.
/// </summary>
/// <typeparam name="T">The type of object to be included.</typeparam>
internal sealed class IncludeScalar<T> : Include, IInclude<T>
{
private static readonly Type resultType = typeof(T);
private T value;
public T Value
{
get
{
return this.value;
}
}
internal override void BuildValue(IDataReader reader, IObjectBuilder objectBuilder)
{
if (reader.Read())
{
if (reader.FieldCount != 1)
{
throw new MicroLiteException(Messages.IncludeScalar_MultipleColumns);
}
var typeConverter = TypeConverter.For(resultType);
this.value = (T)typeConverter.ConvertFromDbValue(reader[0], resultType);
this.HasValue = true;
if (reader.Read())
{
throw new MicroLiteException(Messages.IncludeSingle_SingleResultExpected);
}
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="IIncludeMany.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite
{
using System.Collections.Generic;
/// <summary>
/// The interface for including a multiple results.
/// </summary>
/// <typeparam name="T">The type of object to be included.</typeparam>
public interface IIncludeMany<T>
{
/// <summary>
/// Gets a value indicating whether this include has a value.
/// </summary>
bool HasValue
{
get;
}
/// <summary>
/// Gets the included values.
/// </summary>
/// <value>
/// Values will be in one of the following states:
/// - If the overall query has not been executed the value will be an empty collection.
/// - If the query yielded no results, it will be an empty collection; otherwise it will contain the results of the query.
/// </value>
IList<T> Values
{
get;
}
}
}<file_sep>namespace MicroLite.Tests.Mapping
{
using System;
using MicroLite.FrameworkExtensions;
using MicroLite.Mapping;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="ObjectInfo"/> class.
/// </summary>
public class ObjectInfoTests : IDisposable
{
public ObjectInfoTests()
{
ObjectInfo.MappingConvention = new AttributeMappingConvention();
}
private enum CustomerStatus
{
Inactive = 0,
Active = 1
}
[Fact]
public void ConstructorThrowsArgumentNullExceptionForNullForTableInfo()
{
var exception = Assert.Throws<ArgumentNullException>(
() => new ObjectInfo(typeof(CustomerWithIntegerIdentifier), null));
Assert.Equal("tableInfo", exception.ParamName);
}
[Fact]
public void ConstructorThrowsArgumentNullExceptionForNullForType()
{
var exception = Assert.Throws<ArgumentNullException>(
() => new ObjectInfo(null, null));
Assert.Equal("forType", exception.ParamName);
}
[Fact]
public void CreateInstance()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var instance = objectInfo.CreateInstance();
Assert.IsType<CustomerWithIntegerIdentifier>(instance);
}
[Fact]
public void DefaultIdentifierValueIsSetCorrectlyForGuid()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithGuidIdentifier));
Assert.Equal(Guid.Empty, objectInfo.DefaultIdentifierValue);
}
[Fact]
public void DefaultIdentifierValueIsSetCorrectlyForInteger()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
Assert.Equal(0, objectInfo.DefaultIdentifierValue);
}
[Fact]
public void DefaultIdentifierValueIsSetCorrectlyForString()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithStringIdentifier));
Assert.Null(objectInfo.DefaultIdentifierValue);
}
public void Dispose()
{
ObjectInfo.MappingConvention = new ConventionMappingConvention(ConventionMappingSettings.Default);
}
[Fact]
public void ForReturnsExpandoObjectInfoForTypeOfDynamic()
{
var objectInfo = ObjectInfoHelper<dynamic>();
Assert.IsType<ExpandoObjectInfo>(objectInfo);
}
[Fact]
public void ForReturnsSameObjectInfoForSameType()
{
var forType = typeof(CustomerWithIntegerIdentifier);
var objectInfo1 = ObjectInfo.For(forType);
var objectInfo2 = ObjectInfo.For(forType);
Assert.Same(objectInfo1, objectInfo2);
}
[Fact]
public void ForThrowsArgumentNullExceptonForNullForType()
{
var exception = Assert.Throws<ArgumentNullException>(() => ObjectInfo.For(null));
Assert.Equal("forType", exception.ParamName);
}
[Fact]
public void ForThrowsMicroLiteExceptionIfAbstractClass()
{
var exception = Assert.Throws<MicroLiteException>(
() => ObjectInfo.For(typeof(AbstractCustomer)));
Assert.Equal(
Messages.ObjectInfo_TypeMustNotBeAbstract.FormatWith(typeof(AbstractCustomer).Name),
exception.Message);
}
[Fact]
public void ForThrowsMicroLiteExceptionIfNoDefaultConstructor()
{
var exception = Assert.Throws<MicroLiteException>(
() => ObjectInfo.For(typeof(CustomerWithNoDefaultConstructor)));
Assert.Equal(
Messages.ObjectInfo_TypeMustHaveDefaultConstructor.FormatWith(typeof(CustomerWithNoDefaultConstructor).Name),
exception.Message);
}
[Fact]
public void ForThrowsMicroLiteExceptionIfNotClass()
{
var exception = Assert.Throws<MicroLiteException>(
() => ObjectInfo.For(typeof(CustomerStruct)));
Assert.Equal(
Messages.ObjectInfo_TypeMustBeClass.FormatWith(typeof(CustomerStruct).Name),
exception.Message);
}
[Fact]
public void ForTypeReturnsTypePassedToConstructor()
{
var forType = typeof(CustomerWithIntegerIdentifier);
var objectInfo = ObjectInfo.For(forType);
Assert.Equal(forType, objectInfo.ForType);
}
[Fact]
public void GetIdentifierValueReturnsPropertyValue()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var customer = new CustomerWithIntegerIdentifier
{
Id = 122323
};
var identifierValue = (int)objectInfo.GetIdentifierValue(customer);
Assert.Equal(customer.Id, identifierValue);
}
[Fact]
public void GetIdentifierValueThrowsArgumentNullExceptionForNullInstance()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var exception = Assert.Throws<ArgumentNullException>(() => objectInfo.GetIdentifierValue(null));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void GetIdentifierValueThrowsMicroLiteExceptionIfInstanceIsIncorrectType()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var exception = Assert.Throws<MicroLiteException>(
() => objectInfo.GetIdentifierValue(new CustomerWithGuidIdentifier()));
Assert.Equal(
string.Format(Messages.ObjectInfo_TypeMismatch, typeof(CustomerWithGuidIdentifier).Name, objectInfo.ForType.Name),
exception.Message);
}
[Fact]
public void GetPropertyValueForColumnConvertsPropertyValueToDbValue()
{
var instance = new CustomerWithIntegerIdentifier
{
Status = CustomerStatus.Active
};
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var value = objectInfo.GetPropertyValueForColumn(instance, "StatusId");
Assert.Equal(1, value);
}
[Fact]
public void GetPropertyValueForColumnThrowsArgumentNullExceptionForNullInstance()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var exception = Assert.Throws<ArgumentNullException>(() => objectInfo.GetPropertyValueForColumn(null, "Name"));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void GetPropertyValueForColumnThrowsMicroLiteExceptionIfInstanceIsIncorrectType()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var exception = Assert.Throws<MicroLiteException>(
() => objectInfo.GetPropertyValueForColumn(new CustomerWithGuidIdentifier(), "Name"));
Assert.Equal(
string.Format(Messages.ObjectInfo_TypeMismatch, typeof(CustomerWithGuidIdentifier).Name, objectInfo.ForType.Name),
exception.Message);
}
[Fact]
public void GetPropertyValueForColumnThrowsMicroLiteExceptionIfInvalidColumnName()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var exception = Assert.Throws<MicroLiteException>(
() => objectInfo.GetPropertyValueForColumn(new CustomerWithIntegerIdentifier(), "UnknownColumn"));
Assert.Equal(
string.Format(Messages.ObjectInfo_ColumnNotMapped, "UnknownColumn", objectInfo.ForType.Name),
exception.Message);
}
[Fact]
public void GetPropertyValueReturnsPropertyValue()
{
var instance = new CustomerWithIntegerIdentifier
{
Status = CustomerStatus.Active
};
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var value = objectInfo.GetPropertyValue(instance, "Status");
Assert.Equal(CustomerStatus.Active, value);
}
[Fact]
public void GetPropertyValueThrowsArgumentNullExceptionForNullInstance()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var exception = Assert.Throws<ArgumentNullException>(() => objectInfo.GetPropertyValue(null, "Name"));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void GetPropertyValueThrowsMicroLiteExceptionIfInstanceIsIncorrectType()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var exception = Assert.Throws<MicroLiteException>(
() => objectInfo.GetPropertyValue(new CustomerWithGuidIdentifier(), "Name"));
Assert.Equal(
string.Format(Messages.ObjectInfo_TypeMismatch, typeof(CustomerWithGuidIdentifier).Name, objectInfo.ForType.Name),
exception.Message);
}
[Fact]
public void GetPropertyValueThrowsMicroLiteExceptionIfInvalidPropertyName()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var exception = Assert.Throws<MicroLiteException>(
() => objectInfo.GetPropertyValue(new CustomerWithIntegerIdentifier(), "UnknownProperty"));
Assert.Equal(
string.Format(Messages.ObjectInfo_UnknownProperty, objectInfo.ForType.Name, "UnknownProperty"),
exception.Message);
}
[Fact]
public void HasDefaultIdentifierValueThrowsArgumentNullExceptionForNullInstance()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var exception = Assert.Throws<ArgumentNullException>(() => objectInfo.HasDefaultIdentifierValue(null));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void HasDefaultIdentifierValueThrowsMicroLiteExceptionIfInstanceIsIncorrectType()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var instance = new CustomerWithGuidIdentifier();
var exception = Assert.Throws<MicroLiteException>(
() => objectInfo.HasDefaultIdentifierValue(instance));
Assert.Equal(
string.Format(Messages.ObjectInfo_TypeMismatch, typeof(CustomerWithGuidIdentifier).Name, objectInfo.ForType.Name),
exception.Message);
}
[Fact]
public void HasDefaultIdentifierValueWhenIdentifierIsGuid()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithGuidIdentifier));
var customer = new CustomerWithGuidIdentifier();
customer.Id = Guid.Empty;
Assert.True(objectInfo.HasDefaultIdentifierValue(customer));
customer.Id = Guid.NewGuid();
Assert.False(objectInfo.HasDefaultIdentifierValue(customer));
}
[Fact]
public void HasDefaultIdentifierValueWhenIdentifierIsInteger()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var customer = new CustomerWithIntegerIdentifier();
customer.Id = 0;
Assert.True(objectInfo.HasDefaultIdentifierValue(customer));
customer.Id = 123;
Assert.False(objectInfo.HasDefaultIdentifierValue(customer));
}
[Fact]
public void HasDefaultIdentifierValueWhenIdentifierIsString()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithStringIdentifier));
var customer = new CustomerWithStringIdentifier();
customer.Id = null;
Assert.True(objectInfo.HasDefaultIdentifierValue(customer));
customer.Id = "AFIK";
Assert.False(objectInfo.HasDefaultIdentifierValue(customer));
}
[Fact]
public void SetPropertyValueForColumnSetsPropertyValue()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var instance = new CustomerWithIntegerIdentifier();
objectInfo.SetPropertyValueForColumn(instance, "StatusId", 1);
Assert.Equal(CustomerStatus.Active, instance.Status);
}
[Fact]
public void SetPropertyValueForColumnThrowsAnExceptionForUnknownColumn()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var instance = new CustomerWithIntegerIdentifier();
var exception = Assert.Throws<MicroLiteException>(() => objectInfo.SetPropertyValueForColumn(instance, "UnknownColumn", 1));
Assert.Equal(
string.Format(Messages.ObjectInfo_UnknownColumn, objectInfo.ForType.Name, "UnknownColumn"),
exception.Message);
}
[Fact]
public void SetPropertyValueForColumnThrowsArgumentNullExceptionForNullInstance()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var exception = Assert.Throws<ArgumentNullException>(() => objectInfo.SetPropertyValueForColumn(null, "StatusId", 1));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void SetPropertyValueForColumnThrowsMicroLiteExceptionIfInstanceIsIncorrectType()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var instance = new CustomerWithGuidIdentifier();
var exception = Assert.Throws<MicroLiteException>(
() => objectInfo.SetPropertyValueForColumn(instance, "StatusId", 1));
Assert.Equal(
string.Format(Messages.ObjectInfo_TypeMismatch, typeof(CustomerWithGuidIdentifier).Name, objectInfo.ForType.Name),
exception.Message);
}
[Fact]
public void SetPropertyValueSetsPropertyValue()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var instance = new CustomerWithIntegerIdentifier();
objectInfo.SetPropertyValue(instance, "Status", CustomerStatus.Active);
Assert.Equal(CustomerStatus.Active, instance.Status);
}
[Fact]
public void SetPropertyValueThrowsAnExceptionForUnknownProperty()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var instance = new CustomerWithIntegerIdentifier();
var exception = Assert.Throws<MicroLiteException>(() => objectInfo.SetPropertyValue(instance, "UnknownProperty", CustomerStatus.Active));
Assert.Equal(
string.Format(Messages.ObjectInfo_UnknownProperty, objectInfo.ForType.Name, "UnknownProperty"),
exception.Message);
}
[Fact]
public void SetPropertyValueThrowsArgumentNullExceptionForNullInstance()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var exception = Assert.Throws<ArgumentNullException>(() => objectInfo.SetPropertyValue(null, "Status", CustomerStatus.Active));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void SetPropertyValueThrowsMicroLiteExceptionIfInstanceIsIncorrectType()
{
var objectInfo = ObjectInfo.For(typeof(CustomerWithIntegerIdentifier));
var instance = new CustomerWithGuidIdentifier();
var exception = Assert.Throws<MicroLiteException>(
() => objectInfo.SetPropertyValue(instance, "Status", CustomerStatus.Active));
Assert.Equal(
string.Format(Messages.ObjectInfo_TypeMismatch, typeof(CustomerWithGuidIdentifier).Name, objectInfo.ForType.Name),
exception.Message);
}
/// <summary>
/// A helper method required because you can't do typeof(dynamic).
/// </summary>
private static IObjectInfo ObjectInfoHelper<T>()
{
var objectInfo = ObjectInfo.For(typeof(T));
return objectInfo;
}
private struct CustomerStruct
{
}
private abstract class AbstractCustomer
{
}
[MicroLite.Mapping.Table("Sales", "Customers")]
private class CustomerWithGuidIdentifier
{
[MicroLite.Mapping.Column("CustomerId")]
[MicroLite.Mapping.Identifier(IdentifierStrategy.Assigned)] // Don't use default or we can't prove we read it correctly.
public Guid Id
{
get;
set;
}
}
[MicroLite.Mapping.Table("Sales", "Customers")]
private class CustomerWithIntegerIdentifier
{
public CustomerWithIntegerIdentifier()
{
}
public int AgeInYears
{
get
{
return DateTime.Today.Year - this.DateOfBirth.Year;
}
}
[MicroLite.Mapping.Column("CreditLimit")]
public Decimal? CreditLimit
{
get;
set;
}
[MicroLite.Mapping.Column("DoB")]
public DateTime DateOfBirth
{
get;
set;
}
[MicroLite.Mapping.Column("CustomerId")]
[MicroLite.Mapping.Identifier(IdentifierStrategy.Assigned)] // Don't use default or we can't prove we read it correctly.
public int Id
{
get;
set;
}
[MicroLite.Mapping.Column("Name")]
public string Name
{
get;
set;
}
[MicroLite.Mapping.Column("StatusId")]
public CustomerStatus Status
{
get;
set;
}
}
private class CustomerWithNoDefaultConstructor
{
public CustomerWithNoDefaultConstructor(string foo)
{
}
}
private class CustomerWithNoIdentifier
{
}
[MicroLite.Mapping.Table("Sales", "Customers")]
private class CustomerWithStringIdentifier
{
[MicroLite.Mapping.Column("CustomerId")]
[MicroLite.Mapping.Identifier(IdentifierStrategy.Assigned)]
public string Id
{
get;
set;
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="EnumTypeConverter.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.TypeConverters
{
using System;
using System.Globalization;
/// <summary>
/// An ITypeConverter which can convert Enum values to and from database values.
/// </summary>
/// <remarks>It ensures that the database value is converted to and from the underlying storage type of the Enum to allow for db columns being byte, short, integer or long.</remarks>
public sealed class EnumTypeConverter : TypeConverter
{
/// <summary>
/// Determines whether this type converter can convert values for the specified property type.
/// </summary>
/// <param name="propertyType">The type of the property value to be converted.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified property type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type propertyType)
{
var actualType = TypeConverter.ResolveActualType(propertyType);
return actualType.IsEnum;
}
/// <summary>
/// Converts the specified database value into an instance of the property type.
/// </summary>
/// <param name="value">The database value to be converted.</param>
/// <param name="propertyType">The property type to convert to.</param>
/// <returns>
/// An instance of the specified property type containing the specified value.
/// </returns>
public override object ConvertFromDbValue(object value, Type propertyType)
{
if (value == null || value == DBNull.Value)
{
return null;
}
var enumType = TypeConverter.ResolveActualType(propertyType);
var enumStorageType = Enum.GetUnderlyingType(enumType);
var underlyingValue = System.Convert.ChangeType(value, enumStorageType, CultureInfo.InvariantCulture);
var enumValue = Enum.ToObject(enumType, underlyingValue);
return enumValue;
}
/// <summary>
/// Converts the specified property value into an instance of the database value.
/// </summary>
/// <param name="value">The property value to be converted.</param>
/// <param name="propertyType">The property type to convert from.</param>
/// <returns>
/// An instance of the corresponding database type for the property type containing the property value.
/// </returns>
public override object ConvertToDbValue(object value, Type propertyType)
{
if (value == null)
{
return value;
}
var enumType = TypeConverter.ResolveActualType(propertyType);
var enumStorageType = Enum.GetUnderlyingType(enumType);
var underlyingValue = System.Convert.ChangeType(value, enumStorageType, CultureInfo.InvariantCulture);
return underlyingValue;
}
}
}<file_sep>namespace MicroLite.Tests.Integration.Select
{
using System;
using Xunit;
public class WhenSelectingAKnownIdentifier : IntegrationTest
{
private readonly Customer customer;
public WhenSelectingAKnownIdentifier()
{
this.Session.Insert(new Customer
{
DateOfBirth = DateTime.Today,
EmailAddress = "<EMAIL>",
Forename = "Joe",
Status = CustomerStatus.Active,
Surname = "Bloggs"
});
this.customer = this.Session.Single<Customer>(1);
}
[Fact]
public void TheExpectedValuesShouldBeReturned()
{
Assert.Equal(1, this.customer.CustomerId);
Assert.Equal(DateTime.Today, this.customer.DateOfBirth);
Assert.Equal("<EMAIL>", this.customer.EmailAddress);
Assert.Equal("Joe", this.customer.Forename);
Assert.Equal(CustomerStatus.Active, this.customer.Status);
Assert.Equal("Bloggs", this.customer.Surname);
}
}
}<file_sep>namespace MicroLite.Tests
{
using System;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="GuidGenerator"/> class.
/// </summary>
public class GuidGeneratorTests
{
public class WhenCallingCreateComb
{
private readonly Guid guid1 = GuidGenerator.CreateComb();
private readonly Guid guid2 = GuidGenerator.CreateComb();
[Fact]
public void EachGuidReturnedShouldBeUnique()
{
Assert.NotEqual(this.guid1, this.guid2);
}
[Fact]
public void TheGuidShouldNotBeAnEmptyGuid()
{
Assert.NotEqual(Guid.Empty, this.guid1);
Assert.NotEqual(Guid.Empty, this.guid2);
}
}
public class WhenCallingCreateCombUsingTheSameSeed
{
private readonly Guid guid1;
private readonly Guid guid2;
public WhenCallingCreateCombUsingTheSameSeed()
{
var dateTime = DateTime.Now;
this.guid1 = GuidGenerator.CreateComb(dateTime);
this.guid2 = GuidGenerator.CreateComb(dateTime);
}
[Fact]
public void EachGuidReturnedShouldBeUnique()
{
Assert.NotEqual(this.guid1, this.guid2);
}
[Fact]
public void TheGuidShouldNotBeAnEmptyGuid()
{
Assert.NotEqual(Guid.Empty, this.guid1);
Assert.NotEqual(Guid.Empty, this.guid2);
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="SessionManager.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Infrastructure.Web
{
using System.Data;
/// <summary>
/// The default implementation of <see cref="ISessionManager"/>.
/// </summary>
/// <remarks>
/// Important that this class remains thread safe as it can exist as a singleton in the MVC and WebAPI extensions
/// when the action filter is registered in global filters.
/// </remarks>
public sealed class SessionManager : ISessionManager
{
/// <summary>
/// Called when the action has been executed.
/// </summary>
/// <param name="session">The session used for the request.</param>
/// <param name="manageTransaction">A value indicating whether the transaction is managed by the session manager.</param>
/// <param name="hasException">A value indicating whether there was an exception during execution.</param>
public void OnActionExecuted(IReadOnlySession session, bool manageTransaction, bool hasException)
{
if (session != null)
{
if (manageTransaction && session.Transaction != null)
{
if (hasException)
{
if (!session.Transaction.WasRolledBack)
{
session.Transaction.Rollback();
}
}
else
{
if (session.Transaction.IsActive)
{
session.Transaction.Commit();
}
}
}
session.Dispose();
}
}
/// <summary>
/// Called when when the action is executing.
/// </summary>
/// <param name="session">The session used for the request.</param>
/// <param name="manageTransaction">A value indicating whether the transaction is managed by the session manager.</param>
/// <param name="isolationLevel">The optional isolation level of the managed transaction.</param>
public void OnActionExecuting(IReadOnlySession session, bool manageTransaction, IsolationLevel? isolationLevel)
{
if (session != null)
{
if (manageTransaction)
{
if (isolationLevel.HasValue)
{
session.BeginTransaction(isolationLevel.Value);
}
else
{
session.BeginTransaction();
}
}
}
}
}
}<file_sep>namespace MicroLite.Tests.Query
{
using System;
using MicroLite.Query;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="StoredProcedureSqlBuilder"/> class.
/// </summary>
public class StoredProcedureSqlBuilderTests
{
[Fact]
public void Execute()
{
var sqlBuilder = new StoredProcedureSqlBuilder("GetCustomerInvoices");
var sqlQuery = sqlBuilder
.WithParameter("@CustomerId", 7633245)
.WithParameter("@StartDate", DateTime.Today.AddMonths(-3))
.WithParameter("@EndDate", DateTime.Today)
.ToSqlQuery();
Assert.Equal(3, sqlQuery.Arguments.Count);
Assert.Equal(7633245, sqlQuery.Arguments[0]);
Assert.Equal(DateTime.Today.AddMonths(-3), sqlQuery.Arguments[1]);
Assert.Equal(DateTime.Today, sqlQuery.Arguments[2]);
Assert.Equal("EXEC GetCustomerInvoices @CustomerId, @StartDate, @EndDate", sqlQuery.CommandText);
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="ISessionManager.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Infrastructure.Web
{
using System.Data;
/// <summary>
/// The interface for a class which manages a session during the action execution context of a web request.
/// </summary>
public interface ISessionManager
{
/// <summary>
/// Called when the action has been executed.
/// </summary>
/// <param name="session">The session used for the request.</param>
/// <param name="manageTransaction">A value indicating whether the transaction is managed by the session manager.</param>
/// <param name="hasException">A value indicating whether there was an exception during execution.</param>
void OnActionExecuted(IReadOnlySession session, bool manageTransaction, bool hasException);
/// <summary>
/// Called when when the action is executing.
/// </summary>
/// <param name="session">The session used for the request.</param>
/// <param name="manageTransaction">A value indicating whether the transaction is managed by the session manager.</param>
/// <param name="isolationLevel">The optional isolation level of the managed transaction.</param>
void OnActionExecuting(IReadOnlySession session, bool manageTransaction, IsolationLevel? isolationLevel);
}
}<file_sep>using System;
using MicroLite.TypeConverters;
using Xunit;
namespace MicroLite.Tests.TypeConverters
{
public class EnumTypeConverterTests
{
private enum ByteEnumStatus : byte
{
Default = 0,
New = 1
}
private enum IntEnumStatus
{
Default = 0,
New = 1
}
public class WhenCallingCanConvertWithATypeWhichIsAnEnum
{
[Fact]
public void TrueShouldBeReturned()
{
var typeConverter = new EnumTypeConverter();
Assert.True(typeConverter.CanConvert(typeof(IntEnumStatus)));
}
}
public class WhenCallingCanConvertWithATypeWhichIsANullableEnum
{
[Fact]
public void TrueShouldBeReturned()
{
var typeConverter = new EnumTypeConverter();
Assert.True(typeConverter.CanConvert(typeof(IntEnumStatus?)));
}
}
public class WhenCallingCanConvertWithATypeWhichIsNotAnEnum
{
[Fact]
public void FalseShouldBeReturned()
{
var typeConverter = new EnumTypeConverter();
Assert.False(typeConverter.CanConvert(typeof(int)));
}
}
public class WhenCallingConvertFromDbValueForANullableEnumWithANonNullValue
{
private object result;
private ITypeConverter typeConverter = new EnumTypeConverter();
public WhenCallingConvertFromDbValueForANullableEnumWithANonNullValue()
{
this.result = typeConverter.ConvertFromDbValue(1, typeof(IntEnumStatus?));
}
[Fact]
public void TheCorrectEnumValueShouldBeReturned()
{
Assert.Equal(IntEnumStatus.New, this.result);
}
}
public class WhenCallingConvertFromDbValueForANullableEnumWithANullableValue
{
private object result;
private ITypeConverter typeConverter = new EnumTypeConverter();
public WhenCallingConvertFromDbValueForANullableEnumWithANullableValue()
{
this.result = typeConverter.ConvertFromDbValue(DBNull.Value, typeof(IntEnumStatus?));
}
[Fact]
public void TheResultShouldBeNull()
{
Assert.Null(this.result);
}
}
public class WhenCallingConvertFromDbValueWithAByte
{
private object result;
private ITypeConverter typeConverter = new EnumTypeConverter();
public WhenCallingConvertFromDbValueWithAByte()
{
this.result = typeConverter.ConvertFromDbValue((byte)1, typeof(IntEnumStatus));
}
[Fact]
public void TheCorrectEnumValueShouldBeReturned()
{
Assert.Equal(IntEnumStatus.New, this.result);
}
}
public class WhenCallingConvertFromDbValueWithALong
{
private object result;
private ITypeConverter typeConverter = new EnumTypeConverter();
public WhenCallingConvertFromDbValueWithALong()
{
this.result = typeConverter.ConvertFromDbValue((long)1, typeof(IntEnumStatus));
}
[Fact]
public void TheCorrectEnumValueShouldBeReturned()
{
Assert.Equal(IntEnumStatus.New, this.result);
}
}
public class WhenCallingConvertFromDbValueWithAnInt
{
private object result;
private ITypeConverter typeConverter = new EnumTypeConverter();
public WhenCallingConvertFromDbValueWithAnInt()
{
this.result = typeConverter.ConvertFromDbValue((int)1, typeof(IntEnumStatus));
}
[Fact]
public void TheCorrectEnumValueShouldBeReturned()
{
Assert.Equal(IntEnumStatus.New, this.result);
}
}
public class WhenCallingConvertToDbValueForAnEnumWithByteStorage
{
private object result;
private ITypeConverter typeConverter = new EnumTypeConverter();
private ByteEnumStatus value = ByteEnumStatus.New;
public WhenCallingConvertToDbValueForAnEnumWithByteStorage()
{
this.result = this.typeConverter.ConvertToDbValue(value, typeof(ByteEnumStatus));
}
[Fact]
public void TheResultShouldBeAnInteger()
{
Assert.IsType<byte>(this.result);
}
}
public class WhenCallingConvertToDbValueForAnEnumWithIntStorage
{
private object result;
private ITypeConverter typeConverter = new EnumTypeConverter();
private IntEnumStatus value = IntEnumStatus.New;
public WhenCallingConvertToDbValueForAnEnumWithIntStorage()
{
this.result = this.typeConverter.ConvertToDbValue(value, typeof(IntEnumStatus));
}
[Fact]
public void TheResultShouldBeAnInteger()
{
Assert.IsType<int>(this.result);
}
}
public class WhenCallingConvertToDbValueForANullableEnum
{
private object result;
private ITypeConverter typeConverter = new EnumTypeConverter();
private IntEnumStatus? value = null;
public WhenCallingConvertToDbValueForANullableEnum()
{
this.result = this.typeConverter.ConvertToDbValue(value, typeof(IntEnumStatus?));
}
[Fact]
public void TheResultShouldBeNull()
{
Assert.Null(this.result);
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="TypeExtensions.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.FrameworkExtensions
{
using System;
using System.Xml.Linq;
internal static class TypeExtensions
{
internal static bool IsNotEntityAndConvertible(this Type type)
{
return type.IsPrimitive || type.IsEnum || type.IsValueType || type == typeof(string) || type == typeof(XDocument);
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="Include.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Core
{
using System.Data;
/// <summary>
/// The base class for include implementations.
/// </summary>
internal abstract class Include
{
/// <summary>
/// Gets or sets a value indicating whether this include has a value.
/// </summary>
public bool HasValue
{
get;
protected set;
}
/// <summary>
/// Builds the included value from the results in the data reader using the supplied object builder.
/// </summary>
/// <param name="reader">The <see cref="IDataReader"/> containing the results.</param>
/// <param name="objectBuilder">The object builder to use to build the included value.</param>
internal abstract void BuildValue(IDataReader reader, IObjectBuilder objectBuilder);
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="IWhereSingleColumn.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Query
{
/// <summary>
/// The interface which specifies the where in method in the fluent sql builder syntax.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "OrIn", Justification = "In this case we mean OR/IN.")]
public interface IWhereSingleColumn : IHideObjectMethods
{
/// <summary>
/// Uses the specified arguments to filter the column.
/// </summary>
/// <param name="lower">The inclusive lower value.</param>
/// <param name="upper">The inclusive upper value.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IAndOrOrderBy Between(object lower, object upper);
/// <summary>
/// Uses the specified arguments to filter the column.
/// </summary>
/// <param name="args">The arguments to filter the column.</param>
/// <returns>The next step in the fluent sql builder.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "In", Justification = "The method is to specify an In list.")]
IAndOrOrderBy In(params object[] args);
/// <summary>
/// Uses the specified SqlQuery as a sub query to filter the column.
/// </summary>
/// <param name="subQuery">The sub query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "In", Justification = "The method is to specify an In list.")]
IAndOrOrderBy In(SqlQuery subQuery);
/// <summary>
/// Specifies that the specified column contains a value which is equal to the specified comparisonValue.
/// </summary>
/// <param name="comparisonValue">The value to compare with.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IAndOrOrderBy IsEqualTo(object comparisonValue);
/// <summary>
/// Specifies that the specified column contains a value which is greater than the specified comparisonValue.
/// </summary>
/// <param name="comparisonValue">The value to compare with.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IAndOrOrderBy IsGreaterThan(object comparisonValue);
/// <summary>
/// Specifies that the specified column contains a value which is greater than or equal to the specified comparisonValue.
/// </summary>
/// <param name="comparisonValue">The value to compare with.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IAndOrOrderBy IsGreaterThanOrEqualTo(object comparisonValue);
/// <summary>
/// Specifies that the specified column contains a value which is less than the specified comparisonValue.
/// </summary>
/// <param name="comparisonValue">The value to compare with.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IAndOrOrderBy IsLessThan(object comparisonValue);
/// <summary>
/// Specifies that the specified column contains a value which is less than or equal to the specified comparisonValue.
/// </summary>
/// <param name="comparisonValue">The value to compare with.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IAndOrOrderBy IsLessThanOrEqualTo(object comparisonValue);
/// <summary>
/// Specifies that the specified column contains a value which is like the specified comparisonValue.
/// </summary>
/// <param name="comparisonValue">The value to compare with.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IAndOrOrderBy IsLike(object comparisonValue);
/// <summary>
/// Specifies that the specified column contains a value which is not equal to the specified comparisonValue.
/// </summary>
/// <param name="comparisonValue">The value to compare with.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IAndOrOrderBy IsNotEqualTo(object comparisonValue);
/// <summary>
/// Specifies that the specified column contains a value which is not null.
/// </summary>
/// <returns>The next step in the fluent sql builder.</returns>
IAndOrOrderBy IsNotNull();
/// <summary>
/// Specifies that the specified column contains a value which is null.
/// </summary>
/// <returns>The next step in the fluent sql builder.</returns>
IAndOrOrderBy IsNull();
/// <summary>
/// Uses the specified arguments to filter the column.
/// </summary>
/// <param name="args">The arguments to filter the column.</param>
/// <returns>The next step in the fluent sql builder.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "In", Justification = "The method is to specify an In list.")]
IAndOrOrderBy NotIn(params object[] args);
/// <summary>
/// Uses the specified SqlQuery as a sub query to filter the column.
/// </summary>
/// <param name="subQuery">The sub query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "In", Justification = "The method is to specify an In list.")]
IAndOrOrderBy NotIn(SqlQuery subQuery);
}
}<file_sep>namespace MicroLite.Tests.Integration.Insert
{
using System;
using Xunit;
public class WhenInsertingANewlyCreatedInstance : IntegrationTest
{
private readonly Customer customer;
public WhenInsertingANewlyCreatedInstance()
{
this.customer = new Customer
{
DateOfBirth = DateTime.Today,
EmailAddress = "<EMAIL>",
Forename = "Joe",
Surname = "Bloggs",
Status = CustomerStatus.Active
};
this.Session.Insert(this.customer);
}
[Fact]
public void TheIdentifierShouldBeSet()
{
Assert.NotEqual(0, this.customer.CustomerId);
}
}
}<file_sep>namespace MicroLite.Tests.Integration.Delete
{
using System;
using Xunit;
public class WhenDeletingAKnownIdentifier : IntegrationTest
{
private readonly bool deleted;
public WhenDeletingAKnownIdentifier()
{
var customer = new Customer
{
DateOfBirth = DateTime.Today,
EmailAddress = "<EMAIL>",
Forename = "Joe",
Surname = "Bloggs",
Status = CustomerStatus.Active
};
this.Session.Insert(customer);
this.deleted = this.Session.Advanced.Delete(typeof(Customer), customer.CustomerId);
}
[Fact]
public void DeleteShouldReturnTrue()
{
Assert.True(this.deleted);
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="IFunctionOrFrom.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Query
{
/// <summary>
/// The interface which specifies the from method or function in the fluent sql builder syntax.
/// </summary>
public interface IFunctionOrFrom : IHideObjectMethods, IFrom
{
/// <summary>
/// Selects the average value in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IFunctionOrFrom Average(string columnName);
/// <summary>
/// Selects the average value in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <param name="columnAlias">The alias in the result set for the calculated column.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IFunctionOrFrom Average(string columnName, string columnAlias);
/// <summary>
/// Selects the number of records which match the specified filter.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IFunctionOrFrom Count(string columnName);
/// <summary>
/// Selects the number of records which match the specified filter.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <param name="columnAlias">The alias in the result set for the calculated column.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IFunctionOrFrom Count(string columnName, string columnAlias);
/// <summary>
/// Selects the maximum value in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IFunctionOrFrom Max(string columnName);
/// <summary>
/// Selects the maximum value in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <param name="columnAlias">The alias in the result set for the calculated column.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IFunctionOrFrom Max(string columnName, string columnAlias);
/// <summary>
/// Selects the minimum value in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IFunctionOrFrom Min(string columnName);
/// <summary>
/// Selects the minimum value in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <param name="columnAlias">The alias in the result set for the calculated column.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IFunctionOrFrom Min(string columnName, string columnAlias);
/// <summary>
/// Selects the sum of the values in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IFunctionOrFrom Sum(string columnName);
/// <summary>
/// Selects the sum of the values in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <param name="columnAlias">The alias in the result set for the calculated column.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IFunctionOrFrom Sum(string columnName, string columnAlias);
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="MsSqlDialect.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Dialect
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
/// <summary>
/// The implementation of <see cref="ISqlDialect"/> for MsSql server.
/// </summary>
internal sealed class MsSqlDialect : SqlDialect
{
/// <summary>
/// Initialises a new instance of the <see cref="MsSqlDialect"/> class.
/// </summary>
/// <remarks>Constructor needs to be public so that it can be instantiated by SqlDialectFactory.</remarks>
public MsSqlDialect()
: base(SqlCharacters.MsSql)
{
}
/// <summary>
/// Gets the select identity string.
/// </summary>
protected override string SelectIdentityString
{
get
{
return "SELECT SCOPE_IDENTITY()";
}
}
public override SqlQuery Combine(IEnumerable<SqlQuery> sqlQueries)
{
if (sqlQueries == null)
{
throw new ArgumentNullException("sqlQueries");
}
int argumentsCount = 0;
var sqlBuilder = new StringBuilder(sqlQueries.Sum(s => s.CommandText.Length));
foreach (var sqlQuery in sqlQueries)
{
argumentsCount += sqlQuery.Arguments.Count;
var commandText = sqlQuery.CommandText.StartsWith("EXEC", StringComparison.OrdinalIgnoreCase)
? sqlQuery.CommandText
: SqlUtility.RenumberParameters(sqlQuery.CommandText, argumentsCount);
sqlBuilder.AppendLine(commandText + this.SqlCharacters.StatementSeparator);
}
var combinedQuery = new SqlQuery(sqlBuilder.ToString(0, sqlBuilder.Length - 3), sqlQueries.SelectMany(s => s.Arguments).ToArray());
combinedQuery.Timeout = sqlQueries.Max(s => s.Timeout);
return combinedQuery;
}
public override SqlQuery PageQuery(SqlQuery sqlQuery, PagingOptions pagingOptions)
{
int fromRowNumber = pagingOptions.Offset + 1;
int toRowNumber = pagingOptions.Offset + pagingOptions.Count;
List<object> arguments = new List<object>(sqlQuery.Arguments.Count + 2);
arguments.AddRange(sqlQuery.Arguments);
arguments.Add(fromRowNumber);
arguments.Add(toRowNumber);
var selectStatement = this.ReadSelectList(sqlQuery.CommandText);
var qualifiedTableName = this.ReadTableName(sqlQuery.CommandText);
var position = qualifiedTableName.LastIndexOf(".", StringComparison.OrdinalIgnoreCase) + 1;
var tableName = position > 0 ? qualifiedTableName.Substring(position, qualifiedTableName.Length - position) : qualifiedTableName;
var whereValue = this.ReadWhereClause(sqlQuery.CommandText);
var whereClause = !string.IsNullOrEmpty(whereValue) ? " WHERE " + whereValue : string.Empty;
var orderByValue = this.ReadOrderBy(sqlQuery.CommandText);
var orderByClause = "ORDER BY " + (!string.IsNullOrEmpty(orderByValue) ? orderByValue : "(SELECT NULL)");
var sqlBuilder = new StringBuilder(sqlQuery.CommandText.Length * 2);
sqlBuilder.Append(selectStatement);
sqlBuilder.Append(" FROM");
sqlBuilder.AppendFormat(CultureInfo.InvariantCulture, " ({0}, ROW_NUMBER() OVER({1}) AS RowNumber FROM {2}{3}) AS {4}", selectStatement, orderByClause, qualifiedTableName, whereClause, tableName);
sqlBuilder.AppendFormat(CultureInfo.InvariantCulture, " WHERE (RowNumber >= {0} AND RowNumber <= {1})", this.SqlCharacters.GetParameterName(arguments.Count - 2), this.SqlCharacters.GetParameterName(arguments.Count - 1));
return new SqlQuery(sqlBuilder.ToString(), arguments.ToArray());
}
protected override string GetCommandText(string commandText)
{
if (commandText.StartsWith("EXEC", StringComparison.OrdinalIgnoreCase) && !commandText.Contains(this.SqlCharacters.StatementSeparator))
{
var firstParameterPosition = SqlUtility.GetFirstParameterPosition(commandText);
if (firstParameterPosition > 4)
{
return commandText.Substring(4, firstParameterPosition - 4).Trim();
}
else
{
return commandText.Substring(4, commandText.Length - 4).Trim();
}
}
return base.GetCommandText(commandText);
}
protected override CommandType GetCommandType(string commandText)
{
if (commandText.StartsWith("EXEC", StringComparison.OrdinalIgnoreCase) && !commandText.Contains(this.SqlCharacters.StatementSeparator))
{
return CommandType.StoredProcedure;
}
return base.GetCommandType(commandText);
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="FluentConfiguration.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Configuration
{
using System;
using System.Configuration;
using System.Data.Common;
using System.Linq;
using MicroLite.Core;
using MicroLite.Dialect;
using MicroLite.FrameworkExtensions;
using MicroLite.Logging;
/// <summary>
/// The class used to configure the MicroLite ORM framework using the fluent API.
/// </summary>
internal sealed class FluentConfiguration : IConfigureConnection, ICreateSessionFactory
{
private static readonly object locker = new object();
private readonly ILog log = LogManager.GetCurrentClassLog();
private readonly SessionFactoryOptions options = new SessionFactoryOptions();
/// <summary>
/// Creates the session factory for the configured connection.
/// </summary>
/// <returns>
/// The session factory for the specified connection.
/// </returns>
public ISessionFactory CreateSessionFactory()
{
lock (locker)
{
var sessionFactory =
Configure.SessionFactories.SingleOrDefault(s => s.ConnectionName == this.options.ConnectionName);
if (sessionFactory == null)
{
this.log.TryLogDebug(Messages.FluentConfiguration_CreatingSessionFactory, this.options.ConnectionName);
sessionFactory = new SessionFactory(this.options);
MicroLite.Query.SqlBuilder.SqlCharacters = sessionFactory.SqlDialect.SqlCharacters;
Configure.SessionFactories.Add(sessionFactory);
}
return sessionFactory;
}
}
/// <summary>
/// Specifies the name of the connection string in the app config and the sql dialect to be used.
/// </summary>
/// <param name="connectionName">The name of the connection string in the app config.</param>
/// <param name="sqlDialect">The name of the sql dialect to use for the connection.</param>
/// <returns>The next step in the fluent configuration.</returns>
/// <exception cref="System.ArgumentNullException">Thrown if connectionName is null.</exception>
/// <exception cref="MicroLiteException">Thrown if the connection is not found in the app config.</exception>
/// <exception cref="System.NotSupportedException">Thrown if the provider name or sql dialect is not supported.</exception>
public ICreateSessionFactory ForConnection(string connectionName, string sqlDialect)
{
if (connectionName == null)
{
throw new ArgumentNullException("connectionName");
}
this.log.TryLogDebug(Messages.FluentConfiguration_ReadingConnection, connectionName);
var configSection = ConfigurationManager.ConnectionStrings[connectionName];
if (configSection == null)
{
this.log.TryLogFatal(Messages.FluentConfiguration_ConnectionNotFound, connectionName);
throw new MicroLiteException(Messages.FluentConfiguration_ConnectionNotFound.FormatWith(connectionName));
}
var sqlDialectType = this.GetSqlDialectType(sqlDialect);
try
{
this.options.ConnectionName = configSection.Name;
this.options.ConnectionString = configSection.ConnectionString;
this.options.ProviderFactory = DbProviderFactories.GetFactory(configSection.ProviderName);
this.options.SqlDialectType = sqlDialectType;
return this;
}
catch (Exception e)
{
this.log.TryLogFatal(e.Message, e);
throw new MicroLiteException(e.Message, e);
}
}
private Type GetSqlDialectType(string sqlDialect)
{
var sqlDialectType = Type.GetType(sqlDialect, throwOnError: false);
if (sqlDialectType == null)
{
this.log.TryLogFatal(Messages.FluentConfiguration_DialectNotSupported.FormatWith(sqlDialect));
throw new NotSupportedException(Messages.FluentConfiguration_DialectNotSupported.FormatWith(sqlDialect));
}
if (!typeof(ISqlDialect).IsAssignableFrom(sqlDialectType))
{
this.log.TryLogFatal(Messages.FluentConfiguration_DialectMustImplementISqlDialect.FormatWith(sqlDialect));
throw new NotSupportedException(Messages.FluentConfiguration_DialectMustImplementISqlDialect.FormatWith(sqlDialect));
}
return sqlDialectType;
}
}
}<file_sep>namespace MicroLite.Tests.Mapping
{
using MicroLite.Mapping;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="PropertyAccessor"/> class.
/// </summary>
public class PropertyAccessorTests
{
private enum CustomerStatus
{
Active = 0,
Disabled = 1,
Suspended = 2
}
public class WhenCallingGetValueForAnEnum
{
private readonly Customer customer = new Customer
{
Status = CustomerStatus.Suspended
};
private readonly object value;
public WhenCallingGetValueForAnEnum()
{
var propertyInfo = typeof(Customer).GetProperty("Status");
var propertyAccessor = PropertyAccessor.Create(propertyInfo);
this.value = propertyAccessor.GetValue(this.customer);
}
[Fact]
public void TheValueShouldBeAnEnum()
{
Assert.IsType<CustomerStatus>(this.value);
}
[Fact]
public void TheValueShouldBeReturned()
{
Assert.Equal(this.customer.Status, this.value);
}
}
public class WhenCallingGetValueForANullableValueTypeWithANonNullValue
{
private readonly Customer customer = new Customer
{
LastInvoice = 100
};
private readonly object value;
public WhenCallingGetValueForANullableValueTypeWithANonNullValue()
{
var propertyInfo = typeof(Customer).GetProperty("LastInvoice");
var propertyAccessor = PropertyAccessor.Create(propertyInfo);
this.value = propertyAccessor.GetValue(this.customer);
}
[Fact]
public void TheValueShouldBeReturned()
{
Assert.Equal(100, this.customer.LastInvoice);
}
}
public class WhenCallingGetValueForANullableValueTypeWithANullValue
{
private readonly Customer customer = new Customer
{
LastInvoice = null
};
private readonly object value;
public WhenCallingGetValueForANullableValueTypeWithANullValue()
{
var propertyInfo = typeof(Customer).GetProperty("LastInvoice");
var propertyAccessor = PropertyAccessor.Create(propertyInfo);
this.value = propertyAccessor.GetValue(this.customer);
}
[Fact]
public void TheValueShouldBeReturned()
{
Assert.Null(this.customer.LastInvoice);
}
}
public class WhenCallingGetValueForAReferenceType
{
private readonly Customer customer = new Customer
{
Name = "<NAME>"
};
private readonly object value;
public WhenCallingGetValueForAReferenceType()
{
var propertyInfo = typeof(Customer).GetProperty("Name");
var propertyAccessor = PropertyAccessor.Create(propertyInfo);
this.value = propertyAccessor.GetValue(this.customer);
}
[Fact]
public void TheValueShouldBeReturned()
{
Assert.Equal(this.customer.Name, this.value);
}
}
public class WhenCallingSetValueForAnEnum
{
private readonly Customer customer = new Customer();
public WhenCallingSetValueForAnEnum()
{
var propertyInfo = typeof(Customer).GetProperty("Status");
var propertyAccessor = PropertyAccessor.Create(propertyInfo);
propertyAccessor.SetValue(this.customer, CustomerStatus.Suspended);
}
[Fact]
public void ThePropertyShouldBeSet()
{
Assert.Equal(CustomerStatus.Suspended, this.customer.Status);
}
}
public class WhenCallingSetValueForANullableStructWithNonNull
{
private readonly Customer customer = new Customer();
public WhenCallingSetValueForANullableStructWithNonNull()
{
var propertyInfo = typeof(Customer).GetProperty("LastInvoice");
var propertyAccessor = PropertyAccessor.Create(propertyInfo);
propertyAccessor.SetValue(this.customer, 100);
}
[Fact]
public void ThePropertyShouldBeSet()
{
Assert.Equal(100, this.customer.LastInvoice);
}
}
public class WhenCallingSetValueForANullableStructWithNull
{
private readonly Customer customer = new Customer
{
LastInvoice = 100
};
public WhenCallingSetValueForANullableStructWithNull()
{
var propertyInfo = typeof(Customer).GetProperty("LastInvoice");
var propertyAccessor = PropertyAccessor.Create(propertyInfo);
propertyAccessor.SetValue(this.customer, null);
}
[Fact]
public void ThePropertyShouldBeSet()
{
Assert.Null(this.customer.LastInvoice);
}
}
public class WhenCallingSetValueForAReferenceType
{
private readonly Customer customer = new Customer();
public WhenCallingSetValueForAReferenceType()
{
var propertyInfo = typeof(Customer).GetProperty("Name");
var propertyAccessor = PropertyAccessor.Create(propertyInfo);
propertyAccessor.SetValue(this.customer, "<NAME>");
}
[Fact]
public void ThePropertyShouldBeSet()
{
Assert.Equal("<NAME>", this.customer.Name);
}
}
private class Customer
{
private string name;
private bool nameSet;
public int Id
{
get;
set;
}
public int? LastInvoice
{
get;
set;
}
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
this.nameSet = true;
}
}
public bool NameSet
{
get
{
return this.nameSet;
}
}
public CustomerStatus Status
{
get;
set;
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="IGroupBy.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Query
{
/// <summary>
/// The interface which specifies the group by method in the fluent sql builder syntax.
/// </summary>
public interface IGroupBy : IHideObjectMethods
{
/// <summary>
/// Groups the results of the query by the specified columns.
/// </summary>
/// <param name="columns">The columns to group by.</param>
/// <returns>The next step in the fluent sql builder.</returns>
IHavingOrOrderBy GroupBy(params string[] columns);
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="SessionFactory.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Core
{
using System;
using System.Data;
using System.Linq;
using MicroLite.Dialect;
using MicroLite.Listeners;
using MicroLite.Logging;
/// <summary>
/// The default implementation of <see cref="ISessionFactory"/>.
/// </summary>
[System.Diagnostics.DebuggerDisplay("SessionFactory for {ConnectionName} using {sessionFactoryOptions.SqlDialectType.Name}")]
internal sealed class SessionFactory : ISessionFactory
{
private static readonly ILog log = LogManager.GetCurrentClassLog();
private readonly object locker = new object();
private readonly IObjectBuilder objectBuilder = new ObjectBuilder();
private readonly SessionFactoryOptions sessionFactoryOptions;
private readonly ISqlDialect sqlDialect;
internal SessionFactory(SessionFactoryOptions sessionFactoryOptions)
{
this.sessionFactoryOptions = sessionFactoryOptions;
this.sqlDialect = (ISqlDialect)Activator.CreateInstance(sessionFactoryOptions.SqlDialectType);
}
public string ConnectionName
{
get
{
return this.sessionFactoryOptions.ConnectionName;
}
}
public ISqlDialect SqlDialect
{
get
{
return this.sqlDialect;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This method is provided to create and return an ISession for the caller to use, it should not dispose of it, that is the responsibility of the caller.")]
public IReadOnlySession OpenReadOnlySession()
{
var connection = this.GetNewConnectionWithConnectionString();
log.TryLogDebug(Messages.SessionFactory_CreatingReadOnlySession, this.ConnectionName, this.sessionFactoryOptions.SqlDialectType.Name);
return new ReadOnlySession(
this,
new ConnectionManager(connection),
this.objectBuilder);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This method is provided to create and return an ISession for the caller to use, it should not dispose of it, that is the responsibility of the caller.")]
public ISession OpenSession()
{
var connection = this.GetNewConnectionWithConnectionString();
log.TryLogDebug(Messages.SessionFactory_CreatingSession, this.ConnectionName, this.sessionFactoryOptions.SqlDialectType.Name);
return new Session(
this,
new ConnectionManager(connection),
this.objectBuilder,
Listener.Listeners.ToArray());
}
private IDbConnection GetNewConnectionWithConnectionString()
{
IDbConnection connection;
lock (this.locker)
{
connection = this.sessionFactoryOptions.ProviderFactory.CreateConnection();
}
connection.ConnectionString = this.sessionFactoryOptions.ConnectionString;
return connection;
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="IPropertyAccessor.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Mapping
{
internal interface IPropertyAccessor
{
object GetValue(object instance);
void SetValue(object instance, object value);
}
}<file_sep>namespace MicroLite.Tests.Integration.Delete
{
using Xunit;
public class WhenDeletingAnUnknownIdentifier : IntegrationTest
{
private readonly bool deleted;
public WhenDeletingAnUnknownIdentifier()
{
this.deleted = this.Session.Advanced.Delete(typeof(Customer), 1);
}
[Fact]
public void DeleteShouldReturnFalse()
{
Assert.False(this.deleted);
}
}
}<file_sep>namespace MicroLite.Tests.Core
{
using System;
using MicroLite.Listeners;
using MicroLite.Mapping;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="AssignedListener"/> class.
/// </summary>
public class AssignedListenerTests : IDisposable
{
public AssignedListenerTests()
{
// The tests in this suite all use attribute mapping for the test.
ObjectInfo.MappingConvention = new AttributeMappingConvention();
}
[Fact]
public void BeforeDeleteDoesNotThrowIfIdentifierSet()
{
var customer = new Customer
{
Id = 1242534
};
var listener = new AssignedListener();
listener.BeforeDelete(customer);
}
[Fact]
public void BeforeDeleteThrowsArgumentNullExceptionForNullInstance()
{
var listener = new AssignedListener();
var exception = Assert.Throws<ArgumentNullException>(() => listener.BeforeDelete(null));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void BeforeDeleteThrowsMicroLiteExceptionIfIdentifierNotSet()
{
var customer = new Customer
{
Id = 0
};
var listener = new AssignedListener();
var exception = Assert.Throws<MicroLiteException>(() => listener.BeforeDelete(customer));
Assert.Equal(Messages.IListener_IdentifierNotSetForDelete, exception.Message);
}
[Fact]
public void BeforeInsertDoesNotThrowIfIdentifierSet()
{
var customer = new Customer
{
Id = 1234
};
var listener = new AssignedListener();
listener.BeforeInsert(customer);
}
[Fact]
public void BeforeInsertThrowsArgumentNullExceptionForNullInstance()
{
var listener = new AssignedListener();
var exception = Assert.Throws<ArgumentNullException>(() => listener.BeforeInsert(null));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void BeforeInsertThrowsMicroLiteExceptionIfIdentifierNotSet()
{
var customer = new Customer
{
Id = 0
};
var listener = new AssignedListener();
var exception = Assert.Throws<MicroLiteException>(() => listener.BeforeInsert(customer));
Assert.Equal(Messages.AssignedListener_IdentifierNotSetForInsert, exception.Message);
}
[Fact]
public void BeforeUpdateDoesNotThrowIfIdentifierSet()
{
var customer = new Customer
{
Id = 1242534
};
var listener = new AssignedListener();
listener.BeforeUpdate(customer);
}
[Fact]
public void BeforeUpdateThrowsArgumentNullExceptionForNullInstance()
{
var listener = new AssignedListener();
var exception = Assert.Throws<ArgumentNullException>(() => listener.BeforeUpdate(null));
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void BeforeUpdateThrowsMicroLiteExceptionIfIdentifierNotSet()
{
var customer = new Customer
{
Id = 0
};
var listener = new AssignedListener();
var exception = Assert.Throws<MicroLiteException>(() => listener.BeforeUpdate(customer));
Assert.Equal(Messages.IListener_IdentifierNotSetForUpdate, exception.Message);
}
public void Dispose()
{
// Reset the mapping convention after tests have run.
ObjectInfo.MappingConvention = new ConventionMappingConvention(ConventionMappingSettings.Default);
}
[MicroLite.Mapping.Table("Sales", "Customers")]
private class Customer
{
[MicroLite.Mapping.Column("CustomerId")]
[MicroLite.Mapping.Identifier(MicroLite.Mapping.IdentifierStrategy.Assigned)]
public int Id
{
get;
set;
}
}
}
}<file_sep>namespace MicroLite.Tests.Query
{
using System;
using MicroLite.Dialect;
using MicroLite.Mapping;
using MicroLite.Query;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="SelectSqlBuilder"/> class.
/// </summary>
public class SelectSqlBuilderTests : IDisposable
{
public SelectSqlBuilderTests()
{
ObjectInfo.MappingConvention = new AttributeMappingConvention();
}
/// <summary>
/// Issue #223 - SqlBuilder Between is not appending AND or OR
/// </summary>
[Fact]
public void BetweenShouldAppendOperandIfItIsAnAdditionalPredicate()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column2").In("Opt1", "Opt2")
.AndWhere("Column3").Between(1, 10)
.ToSqlQuery();
Assert.Equal("SELECT Column1 FROM Table WHERE (Column2 IN (?, ?)) AND (Column3 BETWEEN ? AND ?)", sqlQuery.CommandText);
Assert.Equal(4, sqlQuery.Arguments.Count);
Assert.Equal("Opt1", sqlQuery.Arguments[0]);
Assert.Equal("Opt2", sqlQuery.Arguments[1]);
Assert.Equal(1, sqlQuery.Arguments[2]);
Assert.Equal(10, sqlQuery.Arguments[3]);
}
public void Dispose()
{
ObjectInfo.MappingConvention = new ConventionMappingConvention(ConventionMappingSettings.Default);
}
[Fact]
public void GroupByAppendsColumnsCorrectlyForMultipleColumns()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "CustomerId");
var sqlQuery = sqlBuilder.From("Customer")
.GroupBy("CustomerId", "Created")
.ToSqlQuery();
Assert.Equal("SELECT CustomerId FROM Customer GROUP BY CustomerId, Created", sqlQuery.CommandText);
}
[Fact]
public void GroupByThrowsArgumentNullException()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "CustomerId");
Assert.Throws<ArgumentNullException>(() => sqlBuilder.From("Customer").GroupBy(null));
}
[Fact]
public void InThrowArgumentNullExceptionForNullArgs()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty);
var exception = Assert.Throws<ArgumentNullException>(() => sqlBuilder.From("").Where("").In((object[])(object[])null));
Assert.Equal("args", exception.ParamName);
}
[Fact]
public void InThrowArgumentNullExceptionForNullSqlQuery()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty);
var exception = Assert.Throws<ArgumentNullException>(() => sqlBuilder.From("").Where("").In((SqlQuery)null));
Assert.Equal("subQuery", exception.ParamName);
}
[Fact]
public void NotInThrowsArgumentNullExceptionForNullArgs()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "CustomerId");
Assert.Throws<ArgumentNullException>(() => sqlBuilder.From("Customer").Where("Column").NotIn((object[])null));
}
[Fact]
public void NotInThrowsArgumentNullExceptionForNullSqlQuery()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "CustomerId");
Assert.Throws<ArgumentNullException>(() => sqlBuilder.From("Customer").Where("Column").NotIn((SqlQuery)null));
}
[Fact]
public void OrderByAscendingThrowsArgumentNullException()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "CustomerId");
Assert.Throws<ArgumentNullException>(() => sqlBuilder.From("Customer").OrderByAscending(null));
}
[Fact]
public void OrderByDescendingThrowsArgumentNullException()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "CustomerId");
Assert.Throws<ArgumentNullException>(() => sqlBuilder.From("Customer").OrderByDescending(null));
}
[Fact]
public void SelectAverage()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty);
var sqlQuery = sqlBuilder
.Average("Total")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT AVG(Total) AS Total FROM Invoices WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectAverageWithAlias()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty);
var sqlQuery = sqlBuilder
.Average("Total", columnAlias: "AverageTotal")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT AVG(Total) AS AverageTotal FROM Invoices WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectAverageWithOtherColumn()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "CustomerId");
var sqlQuery = sqlBuilder
.Average("Total")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.GroupBy("CustomerId")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT CustomerId, AVG(Total) AS Total FROM Invoices WHERE (CustomerId = @p0) GROUP BY CustomerId", sqlQuery.CommandText);
}
[Fact]
public void SelectAverageWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql);
var sqlQuery = sqlBuilder
.Average("Total")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT AVG([Total]) AS Total FROM [Invoices] WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
/// <summary>
/// Issue #221 - SqlBuilder does not allow chaining multiple function calls.
/// </summary>
[Fact]
public void SelectChainingMultipleFunctions()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.Count("Column2", "Col2")
.Max("Column3", "Col3")
.From("Table")
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT Column1, COUNT(Column2) AS Col2, MAX(Column3) AS Col3 FROM Table", sqlQuery.CommandText);
}
[Fact]
public void SelectCount()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty);
var sqlQuery = sqlBuilder
.Count("CustomerId")
.From(typeof(Customer))
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT COUNT(CustomerId) AS CustomerId FROM Sales.Customers", sqlQuery.CommandText);
}
[Fact]
public void SelectCountWithAlias()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty);
var sqlQuery = sqlBuilder
.Count("CustomerId", columnAlias: "CustomerCount")
.From(typeof(Customer))
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT COUNT(CustomerId) AS CustomerCount FROM Sales.Customers", sqlQuery.CommandText);
}
[Fact]
public void SelectCountWithOtherColumn()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "ServiceId");
var sqlQuery = sqlBuilder
.Count("CustomerId")
.From(typeof(Customer))
.GroupBy("ServiceId")
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT ServiceId, COUNT(CustomerId) AS CustomerId FROM Sales.Customers GROUP BY ServiceId", sqlQuery.CommandText);
}
[Fact]
public void SelectCountWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql);
var sqlQuery = sqlBuilder
.Count("CustomerId")
.From(typeof(Customer))
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT COUNT([CustomerId]) AS CustomerId FROM [Sales].[Customers]", sqlQuery.CommandText);
}
[Fact]
public void SelectFromOrderByAscending()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1", "Column2");
var sqlQuery = sqlBuilder
.From("Table")
.OrderByAscending("Column1", "Column2")
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT Column1, Column2 FROM Table ORDER BY Column1, Column2 ASC", sqlQuery.CommandText);
}
/// <summary>
/// Issue #93 - SqlBuilder produces invalid Sql if OrderBy is called multiple times.
/// </summary>
[Fact]
public void SelectFromOrderByAscendingThenDescending()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1", "Column2");
var sqlQuery = sqlBuilder
.From("Table")
.OrderByAscending("Column1")
.OrderByDescending("Column2")
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT Column1, Column2 FROM Table ORDER BY Column1 ASC, Column2 DESC", sqlQuery.CommandText);
}
[Fact]
public void SelectFromOrderByAscendingWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1", "Column2");
var sqlQuery = sqlBuilder
.From("Table")
.OrderByAscending("Column1", "Column2")
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT [Column1], [Column2] FROM [Table] ORDER BY [Column1], [Column2] ASC", sqlQuery.CommandText);
}
[Fact]
public void SelectFromOrderByDescending()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1", "Column2");
var sqlQuery = sqlBuilder
.From("Table")
.OrderByDescending("Column1", "Column2")
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT Column1, Column2 FROM Table ORDER BY Column1, Column2 DESC", sqlQuery.CommandText);
}
/// <summary>
/// Issue #93 - SqlBuilder produces invalid Sql if OrderBy is called multiple times.
/// </summary>
[Fact]
public void SelectFromOrderByDescendingThenAscending()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1", "Column2");
var sqlQuery = sqlBuilder
.From("Table")
.OrderByDescending("Column1")
.OrderByAscending("Column2")
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT Column1, Column2 FROM Table ORDER BY Column1 DESC, Column2 ASC", sqlQuery.CommandText);
}
[Fact]
public void SelectFromOrderByDescendingWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1", "Column2");
var sqlQuery = sqlBuilder
.From("Table")
.OrderByDescending("Column1", "Column2")
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT [Column1], [Column2] FROM [Table] ORDER BY [Column1], [Column2] DESC", sqlQuery.CommandText);
}
[Fact]
public void SelectFromSpecifyingColumnsAndTableName()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1", "Column2");
var sqlQuery = sqlBuilder
.From("Table")
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT Column1, Column2 FROM Table", sqlQuery.CommandText);
}
[Fact]
public void SelectFromSpecifyingColumnsAndTableNameWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1", "Column2");
var sqlQuery = sqlBuilder
.From("Table")
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT [Column1], [Column2] FROM [Table]", sqlQuery.CommandText);
}
[Fact]
public void SelectFromSpecifyingColumnsAndType()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Name", "DoB");
var sqlQuery = sqlBuilder
.From(typeof(Customer))
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT Name, DoB FROM Sales.Customers", sqlQuery.CommandText);
}
[Fact]
public void SelectFromSpecifyingColumnsAndTypeWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Name", "DoB");
var sqlQuery = sqlBuilder
.From(typeof(Customer))
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT [Name], [DoB] FROM [Sales].[Customers]", sqlQuery.CommandText);
}
[Fact]
public void SelectFromSpecifyingWildcardAndTableName()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "*");
var sqlQuery = sqlBuilder
.From("Table")
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT * FROM Table", sqlQuery.CommandText);
}
[Fact]
public void SelectFromSpecifyingWildcardAndTableNameWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "*");
var sqlQuery = sqlBuilder
.From("Table")
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT * FROM [Table]", sqlQuery.CommandText);
}
[Fact]
public void SelectFromSpecifyingWildcardAndType()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "*");
var sqlQuery = sqlBuilder
.From(typeof(Customer))
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT DoB, CustomerId, Name FROM Sales.Customers", sqlQuery.CommandText);
}
[Fact]
public void SelectFromSpecifyingWildcardAndTypeWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "*");
var sqlQuery = sqlBuilder
.From(typeof(Customer))
.ToSqlQuery();
Assert.Empty(sqlQuery.Arguments);
Assert.Equal("SELECT [DoB], [CustomerId], [Name] FROM [Sales].[Customers]", sqlQuery.CommandText);
}
[Fact]
public void SelectFromWhere()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1", "Column2");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1 = @p0", "Foo")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("Foo", sqlQuery.Arguments[0]);
Assert.Equal("SELECT Column1, Column2 FROM Table WHERE (Column1 = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectFromWhereAnd()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1", "Column2");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1 = @p0", "Foo")
.AndWhere("Column2 = @p0", "Bar")
.ToSqlQuery();
Assert.Equal(2, sqlQuery.Arguments.Count);
Assert.Equal("Foo", sqlQuery.Arguments[0]);
Assert.Equal("Bar", sqlQuery.Arguments[1]);
Assert.Equal("SELECT Column1, Column2 FROM Table WHERE (Column1 = @p0) AND (Column2 = @p1)", sqlQuery.CommandText);
}
[Fact]
public void SelectFromWhereComplex()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1", "Column2", "Column3");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1 = @p0 OR @p0 IS NULL", "Foo")
.AndWhere("Column2 BETWEEN @p0 AND @p1", DateTime.Today.AddDays(-1), DateTime.Today)
.OrWhere("Column3 IN (@p0, @p1, @p2, @p3)", 1, 2, 3, 4)
.ToSqlQuery();
Assert.Equal(7, sqlQuery.Arguments.Count);
Assert.Equal("Foo", sqlQuery.Arguments[0]);
Assert.Equal(DateTime.Today.AddDays(-1), sqlQuery.Arguments[1]);
Assert.Equal(DateTime.Today, sqlQuery.Arguments[2]);
Assert.Equal(1, sqlQuery.Arguments[3]);
Assert.Equal(2, sqlQuery.Arguments[4]);
Assert.Equal(3, sqlQuery.Arguments[5]);
Assert.Equal(4, sqlQuery.Arguments[6]);
Assert.Equal("SELECT Column1, Column2, Column3 FROM Table WHERE (Column1 = @p0 OR @p0 IS NULL) AND (Column2 BETWEEN @p1 AND @p2) OR (Column3 IN (@p3, @p4, @p5, @p6))", sqlQuery.CommandText);
}
[Fact]
public void SelectFromWhereOr()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1", "Column2");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1 = @p0", "Foo")
.OrWhere("Column2 = @p0", "Bar")
.ToSqlQuery();
Assert.Equal(2, sqlQuery.Arguments.Count);
Assert.Equal("Foo", sqlQuery.Arguments[0]);
Assert.Equal("Bar", sqlQuery.Arguments[1]);
Assert.Equal("SELECT Column1, Column2 FROM Table WHERE (Column1 = @p0) OR (Column2 = @p1)", sqlQuery.CommandText);
}
[Fact]
public void SelectMax()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty);
var sqlQuery = sqlBuilder
.Max("Total")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT MAX(Total) AS Total FROM Invoices WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectMaxWithAlias()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty);
var sqlQuery = sqlBuilder
.Max("Total", columnAlias: "MaxTotal")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT MAX(Total) AS MaxTotal FROM Invoices WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectMaxWithOtherColumn()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "CustomerId");
var sqlQuery = sqlBuilder
.Max("Total")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT CustomerId, MAX(Total) AS Total FROM Invoices WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectMaxWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql);
var sqlQuery = sqlBuilder
.Max("Total")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT MAX([Total]) AS Total FROM [Invoices] WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectMin()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty);
var sqlQuery = sqlBuilder
.Min("Total")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT MIN(Total) AS Total FROM Invoices WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectMinWithAlias()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty);
var sqlQuery = sqlBuilder
.Min("Total", columnAlias: "MinTotal")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT MIN(Total) AS MinTotal FROM Invoices WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectMinWithOtherColumn()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "CustomerId");
var sqlQuery = sqlBuilder
.Min("Total")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT CustomerId, MIN(Total) AS Total FROM Invoices WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectMinWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql);
var sqlQuery = sqlBuilder
.Min("Total")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT MIN([Total]) AS Total FROM [Invoices] WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectSum()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty);
var sqlQuery = sqlBuilder
.Sum("Total")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT SUM(Total) AS Total FROM Invoices WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectSumWithAlias()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty);
var sqlQuery = sqlBuilder
.Sum("Total", columnAlias: "SumTotal")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT SUM(Total) AS SumTotal FROM Invoices WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectSumWithOtherColumn()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "CustomerId");
var sqlQuery = sqlBuilder
.Sum("Total")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT CustomerId, SUM(Total) AS Total FROM Invoices WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectSumWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql);
var sqlQuery = sqlBuilder
.Sum("Total")
.From(typeof(Invoice))
.Where("CustomerId = @p0", 1022)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1022, sqlQuery.Arguments[0]);
Assert.Equal("SELECT SUM([Total]) AS Total FROM [Invoices] WHERE (CustomerId = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereAndWhereInArgs()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column2 = ?", "FOO")
.AndWhere("Column1")
.In(1, 2, 3)
.ToSqlQuery();
Assert.Equal(4, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal(1, sqlQuery.Arguments[1]);
Assert.Equal(2, sqlQuery.Arguments[2]);
Assert.Equal(3, sqlQuery.Arguments[3]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column2 = ?) AND (Column1 IN (?, ?, ?))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereAndWhereInArgsWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column2 = @p0", "FOO")
.AndWhere("Column1").In(1, 2, 3)
.ToSqlQuery();
Assert.Equal(4, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal(1, sqlQuery.Arguments[1]);
Assert.Equal(2, sqlQuery.Arguments[2]);
Assert.Equal(3, sqlQuery.Arguments[3]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE (Column2 = @p0) AND ([Column1] IN (@p1, @p2, @p3))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereAndWhereInSqlQuery()
{
var subQuery = new SqlQuery("SELECT Id FROM Table WHERE Column = ?", 1024);
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column2 = ?", "FOO")
.AndWhere("Column1").In(subQuery)
.ToSqlQuery();
Assert.Equal(2, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal(1024, sqlQuery.Arguments[1]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column2 = ?) AND (Column1 IN (SELECT Id FROM Table WHERE Column = ?))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereAndWhereInSqlQueryWithSqlCharacters()
{
var subQuery = new SqlQuery("SELECT Id FROM Table WHERE Column = @p0", 1024);
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column2 = @p0", "FOO")
.AndWhere("Column1").In(subQuery)
.ToSqlQuery();
Assert.Equal(2, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal(1024, sqlQuery.Arguments[1]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE (Column2 = @p0) AND ([Column1] IN (SELECT Id FROM Table WHERE Column = @p1))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereAndWhereNotInArgsWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column2 = @p0", "FOO")
.AndWhere("Column1").NotIn(1, 2, 3)
.ToSqlQuery();
Assert.Equal(4, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal(1, sqlQuery.Arguments[1]);
Assert.Equal(2, sqlQuery.Arguments[2]);
Assert.Equal(3, sqlQuery.Arguments[3]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE (Column2 = @p0) AND ([Column1] NOT IN (@p1, @p2, @p3))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereAndWhereNotInSqlQuery()
{
var subQuery = new SqlQuery("SELECT Id FROM Table WHERE Column = ?", 1024);
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column2 = ?", "FOO")
.AndWhere("Column1").NotIn(subQuery)
.ToSqlQuery();
Assert.Equal(2, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal(1024, sqlQuery.Arguments[1]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column2 = ?) AND (Column1 NOT IN (SELECT Id FROM Table WHERE Column = ?))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereBetweenUsing()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.Between(1, 10)
.ToSqlQuery();
Assert.Equal(2, sqlQuery.Arguments.Count);
Assert.Equal(1, sqlQuery.Arguments[0]);
Assert.Equal(10, sqlQuery.Arguments[1]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column1 BETWEEN ? AND ?)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereBetweenUsingWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.Between(1, 10)
.ToSqlQuery();
Assert.Equal(2, sqlQuery.Arguments.Count);
Assert.Equal(1, sqlQuery.Arguments[0]);
Assert.Equal(10, sqlQuery.Arguments[1]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE ([Column1] BETWEEN @p0 AND @p1)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsEqualTo()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsEqualTo("FOO")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column1 = ?)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsEqualToWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsEqualTo("FOO")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE ([Column1] = @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsGreaterThan()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsGreaterThan("FOO")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column1 > ?)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsGreaterThanOrEqualTo()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsGreaterThanOrEqualTo("FOO")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column1 >= ?)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsGreaterThanOrEqualToWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsGreaterThanOrEqualTo("FOO")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE ([Column1] >= @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsGreaterThanWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsGreaterThan("FOO")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE ([Column1] > @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsLessThan()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsLessThan("FOO")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column1 < ?)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsLessThanOrEqualTo()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsLessThanOrEqualTo("FOO")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column1 <= ?)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsLessThanOrEqualToWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsLessThanOrEqualTo("FOO")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE ([Column1] <= @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsLessThanWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsLessThan("FOO")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE ([Column1] < @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsLike()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsLike("FOO")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column1 LIKE ?)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsLikeWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsLike("FOO")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE ([Column1] LIKE @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsNotEqualTo()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsNotEqualTo("FOO")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column1 <> ?)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsNotEqualToWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsNotEqualTo("FOO")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE ([Column1] <> @p0)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsNotNull()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsNotNull()
.ToSqlQuery();
Assert.Equal(0, sqlQuery.Arguments.Count);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column1 IS NOT NULL)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsNotNullWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsNotNull()
.ToSqlQuery();
Assert.Equal(0, sqlQuery.Arguments.Count);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE ([Column1] IS NOT NULL)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsNull()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsNull()
.ToSqlQuery();
Assert.Equal(0, sqlQuery.Arguments.Count);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column1 IS NULL)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereColumnIsNullWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.IsNull()
.ToSqlQuery();
Assert.Equal(0, sqlQuery.Arguments.Count);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE ([Column1] IS NULL)", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereGroupByHavingOrderBy()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "CustomerId");
var sqlQuery = sqlBuilder
.Sum("Total")
.From("Invoices")
.Where("OrderDate > @p0", new DateTime(2000, 1, 1))
.GroupBy("Total")
.Having("SUM(Total) > @p0", 10000M)
.OrderByDescending("OrderDate")
.ToSqlQuery();
Assert.Equal(2, sqlQuery.Arguments.Count);
Assert.Equal(new DateTime(2000, 1, 1), sqlQuery.Arguments[0]);
Assert.Equal(10000M, sqlQuery.Arguments[1]);
Assert.Equal("SELECT CustomerId, SUM(Total) AS Total FROM Invoices WHERE (OrderDate > @p0) GROUP BY Total HAVING SUM(Total) > @p1 ORDER BY OrderDate DESC", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereGroupByOrderBy()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "CustomerId");
var sqlQuery = sqlBuilder
.Sum("Total")
.From("Invoices")
.Where("OrderDate > @p0", new DateTime(2000, 1, 1))
.GroupBy("Total")
.OrderByDescending("OrderDate")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(new DateTime(2000, 1, 1), sqlQuery.Arguments[0]);
Assert.Equal("SELECT CustomerId, SUM(Total) AS Total FROM Invoices WHERE (OrderDate > @p0) GROUP BY Total ORDER BY OrderDate DESC", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereGroupByOrderByWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "CustomerId");
var sqlQuery = sqlBuilder
.Sum("Total")
.From("Invoices")
.Where("OrderDate > @p0", new DateTime(2000, 1, 1))
.GroupBy("Total")
.OrderByDescending("OrderDate")
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(new DateTime(2000, 1, 1), sqlQuery.Arguments[0]);
Assert.Equal("SELECT [CustomerId], SUM([Total]) AS Total FROM [Invoices] WHERE (OrderDate > @p0) GROUP BY [Total] ORDER BY [OrderDate] DESC", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereInArgs()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.In(1, 2, 3)
.ToSqlQuery();
Assert.Equal(3, sqlQuery.Arguments.Count);
Assert.Equal(1, sqlQuery.Arguments[0]);
Assert.Equal(2, sqlQuery.Arguments[1]);
Assert.Equal(3, sqlQuery.Arguments[2]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column1 IN (?, ?, ?))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereInArgsWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.In(1, 2, 3)
.ToSqlQuery();
Assert.Equal(3, sqlQuery.Arguments.Count);
Assert.Equal(1, sqlQuery.Arguments[0]);
Assert.Equal(2, sqlQuery.Arguments[1]);
Assert.Equal(3, sqlQuery.Arguments[2]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE ([Column1] IN (@p0, @p1, @p2))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereInSqlQuery()
{
var subQuery = new SqlQuery("SELECT Id FROM Table WHERE Column = @p0", 1024);
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.In(subQuery)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1024, sqlQuery.Arguments[0]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column1 IN (SELECT Id FROM Table WHERE Column = @p0))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereNotInArgs()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1")
.NotIn(1, 2, 3)
.ToSqlQuery();
Assert.Equal(3, sqlQuery.Arguments.Count);
Assert.Equal(1, sqlQuery.Arguments[0]);
Assert.Equal(2, sqlQuery.Arguments[1]);
Assert.Equal(3, sqlQuery.Arguments[2]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column1 NOT IN (?, ?, ?))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereNotInArgsWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1").NotIn(1, 2, 3)
.ToSqlQuery();
Assert.Equal(3, sqlQuery.Arguments.Count);
Assert.Equal(1, sqlQuery.Arguments[0]);
Assert.Equal(2, sqlQuery.Arguments[1]);
Assert.Equal(3, sqlQuery.Arguments[2]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE ([Column1] NOT IN (@p0, @p1, @p2))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereNotInSqlQuery()
{
var subQuery = new SqlQuery("SELECT Id FROM Table WHERE Column = @p0", 1024);
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column1").NotIn(subQuery)
.ToSqlQuery();
Assert.Equal(1, sqlQuery.Arguments.Count);
Assert.Equal(1024, sqlQuery.Arguments[0]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column1 NOT IN (SELECT Id FROM Table WHERE Column = @p0))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereOrWhereInArgs()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column2 = ?", "FOO")
.OrWhere("Column1")
.In(1, 2, 3)
.ToSqlQuery();
Assert.Equal(4, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal(1, sqlQuery.Arguments[1]);
Assert.Equal(2, sqlQuery.Arguments[2]);
Assert.Equal(3, sqlQuery.Arguments[3]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column2 = ?) OR (Column1 IN (?, ?, ?))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereOrWhereInArgsWithSqlCharacters()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column2 = @p0", "FOO")
.OrWhere("Column1").In(1, 2, 3)
.ToSqlQuery();
Assert.Equal(4, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal(1, sqlQuery.Arguments[1]);
Assert.Equal(2, sqlQuery.Arguments[2]);
Assert.Equal(3, sqlQuery.Arguments[3]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE (Column2 = @p0) OR ([Column1] IN (@p1, @p2, @p3))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereOrWhereInSqlQuery()
{
var subQuery = new SqlQuery("SELECT Id FROM Table WHERE Column = ?", 1024);
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column2 = ?", "FOO")
.OrWhere("Column1")
.In(subQuery)
.ToSqlQuery();
Assert.Equal(2, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal(1024, sqlQuery.Arguments[1]);
Assert.Equal("SELECT Column1 FROM Table WHERE (Column2 = ?) OR (Column1 IN (SELECT Id FROM Table WHERE Column = ?))", sqlQuery.CommandText);
}
[Fact]
public void SelectWhereOrWhereInSqlQueryWithSqlCharacters()
{
var subQuery = new SqlQuery("SELECT Id FROM Table WHERE Column = @p0", 1024);
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.MsSql, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column2 = @p0", "FOO")
.OrWhere("Column1")
.In(subQuery)
.ToSqlQuery();
Assert.Equal(2, sqlQuery.Arguments.Count);
Assert.Equal("FOO", sqlQuery.Arguments[0]);
Assert.Equal(1024, sqlQuery.Arguments[1]);
Assert.Equal("SELECT [Column1] FROM [Table] WHERE (Column2 = @p0) OR ([Column1] IN (SELECT Id FROM Table WHERE Column = @p1))", sqlQuery.CommandText);
}
/// <summary>
/// Issue #224 - SqlBuilder SingleColumn predicates not appending AND or OR
/// </summary>
[Fact]
public void SingleColumnPredicatesShouldAppendOperand()
{
var sqlBuilder = new SelectSqlBuilder(SqlCharacters.Empty, "Column1");
var sqlQuery = sqlBuilder
.From("Table")
.Where("Column2").In("Opt1", "Opt2")
.AndWhere("Column3").IsEqualTo(1)
.AndWhere("Column4").IsGreaterThan(2)
.AndWhere("Column5").IsGreaterThanOrEqualTo(3)
.AndWhere("Column6").IsLessThan(4)
.AndWhere("Column7").IsLessThanOrEqualTo(5)
.AndWhere("Column8").IsLike("%J")
.AndWhere("Column9").IsNotEqualTo(6)
.AndWhere("Column10").IsNotNull()
.AndWhere("Column11").IsNull()
.ToSqlQuery();
Assert.Equal(@"SELECT Column1 FROM Table WHERE (Column2 IN (?, ?)) AND (Column3 = ?) AND (Column4 > ?) AND (Column5 >= ?) AND (Column6 < ?) AND (Column7 <= ?) AND (Column8 LIKE ?) AND (Column9 <> ?) AND (Column10 IS NOT NULL) AND (Column11 IS NULL)", sqlQuery.CommandText);
}
[MicroLite.Mapping.Table(schema: "Sales", name: "Customers")]
private class Customer
{
public Customer()
{
}
[MicroLite.Mapping.Column("DoB")]
public DateTime DateOfBirth
{
get;
set;
}
[MicroLite.Mapping.Column("CustomerId")]
[MicroLite.Mapping.Identifier(MicroLite.Mapping.IdentifierStrategy.DbGenerated)]
public int Id
{
get;
set;
}
[MicroLite.Mapping.Column("Name")]
public string Name
{
get;
set;
}
}
[MicroLite.Mapping.Table(name: "Invoices")]
private class Invoice
{
public Invoice()
{
}
[MicroLite.Mapping.Column("CustomerId")]
public int CustomerId
{
get;
set;
}
[MicroLite.Mapping.Column("InvoiceId")]
[MicroLite.Mapping.Identifier(MicroLite.Mapping.IdentifierStrategy.DbGenerated)]
public int Id
{
get;
set;
}
[MicroLite.Mapping.Column("Total")]
public decimal Total
{
get;
set;
}
}
}
}<file_sep>namespace MicroLite.Tests.Integration.Delete
{
using System;
using Xunit;
public class WhenDeletingAKnownInstance : IntegrationTest
{
private readonly bool deleted;
public WhenDeletingAKnownInstance()
{
var customer = new Customer
{
DateOfBirth = DateTime.Today,
EmailAddress = "<EMAIL>",
Forename = "Joe",
Surname = "Bloggs",
Status = CustomerStatus.Active
};
this.Session.Insert(customer);
this.deleted = this.Session.Delete(customer);
}
[Fact]
public void DeleteShouldReturnTrue()
{
Assert.True(this.deleted);
}
}
}<file_sep>namespace MicroLite.Tests
{
using Xunit;
public class DbEncryptedStringTests
{
public class WhenCallingEqualsWithAnotherDbEncryptedStringAsAnObjectContainingTheSameValue
{
[Fact]
public void TrueShouldBeReturned()
{
var value = "12334552233";
var dbEncryptedString = (DbEncryptedString)value;
var other = (object)(DbEncryptedString)value;
Assert.True(dbEncryptedString.Equals(other));
}
}
public class WhenCallingEqualsWithAnotherDbEncryptedStringContainingADifferentValue
{
[Fact]
public void FalseShouldBeReturned()
{
var value = "12334552233";
var dbEncryptedString = (DbEncryptedString)value;
var other = (DbEncryptedString)"sdifjsdjfosdfj";
Assert.False(dbEncryptedString.Equals(other));
}
}
public class WhenCallingEqualsWithAnotherDbEncryptedStringContainingNoValue
{
[Fact]
public void TrueShouldBeReturned()
{
var value = "12334552233";
var dbEncryptedString = (DbEncryptedString)value;
var other = (DbEncryptedString)string.Empty;
Assert.False(dbEncryptedString.Equals(other));
}
}
public class WhenCallingEqualsWithAnotherDbEncryptedStringContainingNull
{
[Fact]
public void TrueShouldBeReturned()
{
var value = "12334552233";
var dbEncryptedString = (DbEncryptedString)value;
var other = (DbEncryptedString)(string)null;
Assert.False(dbEncryptedString.Equals(other));
}
}
public class WhenCallingEqualsWithAnotherDbEncryptedStringContainingTheSameValue
{
[Fact]
public void TrueShouldBeReturned()
{
var value = "12334552233";
var dbEncryptedString = (DbEncryptedString)value;
var other = (DbEncryptedString)value;
Assert.True(dbEncryptedString.Equals(other));
}
}
public class WhenCallingEqualsWithANullDbEncryptedString
{
[Fact]
public void FalseShouldBeReturned()
{
var value = "12334552233";
var dbEncryptedString = (DbEncryptedString)value;
DbEncryptedString other = null;
Assert.False(dbEncryptedString.Equals(other));
}
}
public class WhenCallingGetHashCode
{
[Fact]
public void TheHashCodeOfTheInnerStringShouldBeReturned()
{
var value = "12334552233";
var dbEncryptedString = (DbEncryptedString)value;
Assert.Equal(value.GetHashCode(), dbEncryptedString.GetHashCode());
}
}
public class WhenCastFromAnEmptyString
{
private DbEncryptedString encryptedString;
private string source = string.Empty;
public WhenCastFromAnEmptyString()
{
this.encryptedString = this.source;
}
[Fact]
public void TheValueShouldBeEmpty()
{
string actual = this.encryptedString;
Assert.Equal(this.source, actual);
}
}
public class WhenCastFromANullString
{
private DbEncryptedString encryptedString;
private string source = null;
public WhenCastFromANullString()
{
this.encryptedString = this.source;
}
[Fact]
public void TheValueShouldBeNull()
{
string actual = this.encryptedString;
Assert.Null(actual);
}
}
public class WhenCastFromAString
{
private DbEncryptedString encryptedString;
private string source = "foo";
public WhenCastFromAString()
{
this.encryptedString = this.source;
}
[Fact]
public void TheValueShouldMatch()
{
string actual = this.encryptedString;
Assert.Equal(this.source, actual);
}
}
}
}<file_sep>namespace MicroLite.Tests.Integration.Update
{
using System;
using Xunit;
public class WhenUpdatingAnExistingInstance : IntegrationTest
{
private readonly Customer customer;
public WhenUpdatingAnExistingInstance()
{
this.Session.Insert(new Customer
{
DateOfBirth = DateTime.Today,
EmailAddress = "<EMAIL>",
Forename = "Joe",
Status = CustomerStatus.Active,
Surname = "Bloggs"
});
this.Session.Update(new Customer
{
CustomerId = 1,
DateOfBirth = new DateTime(2000, 6, 20),
EmailAddress = "<EMAIL>",
Forename = "John",
Status = CustomerStatus.Suspended,
Surname = "Smith"
});
this.customer = this.Session.Single<Customer>(1);
}
[Fact]
public void TheUpdatedValuesShouldBeReturned()
{
Assert.Equal(new DateTime(2000, 6, 20), this.customer.DateOfBirth);
Assert.Equal("<EMAIL>", this.customer.EmailAddress);
Assert.Equal("John", this.customer.Forename);
Assert.Equal(CustomerStatus.Suspended, this.customer.Status);
Assert.Equal("Smith", this.customer.Surname);
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="AssignedListener.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Listeners
{
using System;
using MicroLite.Mapping;
/// <summary>
/// The implementation of <see cref="IListener"/> for checking the instance identifier value if
/// <see cref="IdentifierStrategy"/>.Assigned is used.
/// </summary>
public sealed class AssignedListener : Listener
{
/// <summary>
/// Invoked before the SqlQuery to delete the record from the database is created.
/// </summary>
/// <param name="instance">The instance to be deleted.</param>
/// <exception cref="MicroLiteException">Thrown if the identifier value for the object has not been set.</exception>
public override void BeforeDelete(object instance)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
var objectInfo = ObjectInfo.For(instance.GetType());
if (objectInfo.TableInfo.IdentifierStrategy == IdentifierStrategy.Assigned)
{
if (objectInfo.HasDefaultIdentifierValue(instance))
{
throw new MicroLiteException(Messages.IListener_IdentifierNotSetForDelete);
}
}
}
/// <summary>
/// Invoked before the SqlQuery to insert the record into the database is created.
/// </summary>
/// <param name="instance">The instance to be inserted.</param>
/// <exception cref="MicroLiteException">Thrown if the identifier value for the object has not been set.</exception>
public override void BeforeInsert(object instance)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
var objectInfo = ObjectInfo.For(instance.GetType());
if (objectInfo.TableInfo.IdentifierStrategy == IdentifierStrategy.Assigned)
{
if (objectInfo.HasDefaultIdentifierValue(instance))
{
throw new MicroLiteException(Messages.AssignedListener_IdentifierNotSetForInsert);
}
}
}
/// <summary>
/// Invoked before the SqlQuery to update the record in the database is created.
/// </summary>
/// <param name="instance">The instance to be updated.</param>
/// <exception cref="MicroLiteException">Thrown if the identifier value for the object has not been set.</exception>
public override void BeforeUpdate(object instance)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
var objectInfo = ObjectInfo.For(instance.GetType());
if (objectInfo.TableInfo.IdentifierStrategy == IdentifierStrategy.Assigned)
{
if (objectInfo.HasDefaultIdentifierValue(instance))
{
throw new MicroLiteException(Messages.IListener_IdentifierNotSetForUpdate);
}
}
}
}
}<file_sep>namespace MicroLite.Tests.TypeConverters
{
using System;
using System.Security.Cryptography;
using System.Text;
using MicroLite.Infrastructure;
using MicroLite.TypeConverters;
using Moq;
using Xunit;
public class DbEncryptedStringTypeConverterTests
{
public class WhenCallingCanConvertWithDbEncryptedString
{
[Fact]
public void TrueShouldBeReturned()
{
var typeConverter = new DbEncryptedStringTypeConverter(new Mock<ISymmetricAlgorithmProvider>().Object);
Assert.True(typeConverter.CanConvert(typeof(DbEncryptedString)));
}
}
public class WhenCallingConvertFromDbValueAndTheValueDoesntHaveAnAtSign
{
[Fact]
public void AMicroLiteExceptionShouldBeThrown()
{
var typeConverter = new DbEncryptedStringTypeConverter(new Mock<ISymmetricAlgorithmProvider>().Object);
var exception = Assert.Throws<MicroLiteException>(() => typeConverter.ConvertFromDbValue("foo", typeof(DbEncryptedString)));
Assert.Equal(Messages.DbEncryptedStringTypeConverter_CipherTextInvalid, exception.Message);
}
}
public class WhenCallingConvertFromDbValueWithAnEmptyValue
{
private DbEncryptedString result;
public WhenCallingConvertFromDbValueWithAnEmptyValue()
{
var typeConverter = new DbEncryptedStringTypeConverter(new Mock<ISymmetricAlgorithmProvider>().Object);
this.result = (DbEncryptedString)typeConverter.ConvertFromDbValue(string.Empty, typeof(DbEncryptedString));
}
[Fact]
public void TheDbEncryptedStringShouldContainAnEmptyString()
{
Assert.Equal(string.Empty, this.result.ToString());
}
}
public class WhenCallingConvertFromDbValueWithDbNull
{
private DbEncryptedString result;
public WhenCallingConvertFromDbValueWithDbNull()
{
var typeConverter = new DbEncryptedStringTypeConverter(new Mock<ISymmetricAlgorithmProvider>().Object);
this.result = (DbEncryptedString)typeConverter.ConvertFromDbValue(DBNull.Value, typeof(DbEncryptedString));
}
[Fact]
public void TheDbEncryptedStringShouldBeNull()
{
Assert.Equal(null, this.result);
}
}
public class WhenCallingConvertToDbValue
{
private readonly string encrypted;
private readonly DbEncryptedString source = "7622 8765 9902 0924";
private DbEncryptedStringTypeConverter typeConverter;
public WhenCallingConvertToDbValue()
{
var mockAlgorithmProvider = new Mock<ISymmetricAlgorithmProvider>();
mockAlgorithmProvider.Setup(x => x.CreateAlgorithm()).Returns(() =>
{
var algorithm = SymmetricAlgorithm.Create("AesManaged");
algorithm.Key = Encoding.ASCII.GetBytes("bru$3atheM-pey+=!a5ebr7d6Tru@E?4");
return algorithm;
});
this.typeConverter = new DbEncryptedStringTypeConverter(mockAlgorithmProvider.Object);
this.encrypted = (string)this.typeConverter.ConvertToDbValue(this.source, typeof(DbEncryptedString));
}
[Fact]
public void TheResultShouldBeDecryptedBackToTheOriginalValueByConveryFromDbValue()
{
var actual = this.typeConverter.ConvertFromDbValue(this.encrypted, typeof(DbEncryptedString));
Assert.Equal(source.ToString(), actual.ToString());
}
[Fact]
public void TheResultShouldContainTheIVAfterAnAtSign()
{
Assert.Contains("@", this.encrypted);
}
[Fact]
public void TheResultShouldNotMatchTheInput()
{
Assert.NotEqual(source.ToString(), encrypted);
}
}
public class WhenCallingConvertToDbValueWithAnEmptyValue
{
private string result;
public WhenCallingConvertToDbValueWithAnEmptyValue()
{
var typeConverter = new DbEncryptedStringTypeConverter(new Mock<ISymmetricAlgorithmProvider>().Object);
this.result = (string)typeConverter.ConvertToDbValue(string.Empty, typeof(DbEncryptedString));
}
[Fact]
public void TheStringShouldContainNull()
{
Assert.Equal(string.Empty, this.result);
}
}
public class WhenCallingConvertToDbValueWithNull
{
private string result;
public WhenCallingConvertToDbValueWithNull()
{
var typeConverter = new DbEncryptedStringTypeConverter(new Mock<ISymmetricAlgorithmProvider>().Object);
this.result = (string)typeConverter.ConvertToDbValue(null, typeof(DbEncryptedString));
}
[Fact]
public void TheStringShouldContainNull()
{
Assert.Equal((string)null, this.result);
}
}
public class WhenConstructedWithANullISymmetricAlgorithmProvider
{
[Fact]
public void AnArgumentNullExceptionShouldBeThrown()
{
var exception = Assert.Throws<ArgumentNullException>(() => new DbEncryptedStringTypeConverter(null));
Assert.Equal("algorithmProvider", exception.ParamName);
}
}
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="ISqlDialect.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Dialect
{
using System;
using System.Collections.Generic;
using System.Data;
/// <summary>
/// The interface for a class which builds an <see cref="SqlQuery"/> for a object instance.
/// </summary>
public interface ISqlDialect
{
/// <summary>
/// Gets the SQL characters for the SQL dialect.
/// </summary>
SqlCharacters SqlCharacters
{
get;
}
/// <summary>
/// Gets a value indicating whether this SqlDialect supports batched queries.
/// </summary>
bool SupportsBatchedQueries
{
get;
}
/// <summary>
/// Builds the command using the values in the specified SqlQuery.
/// </summary>
/// <param name="command">The command to build.</param>
/// <param name="sqlQuery">The SQL query containing the values for the command.</param>
void BuildCommand(IDbCommand command, SqlQuery sqlQuery);
/// <summary>
/// Combines the specified SQL queries into a single SqlQuery.
/// </summary>
/// <param name="sqlQueries">The SQL queries to be combined.</param>
/// <returns>The combined <see cref="SqlQuery" />.</returns>
SqlQuery Combine(IEnumerable<SqlQuery> sqlQueries);
/// <summary>
/// Creates an SqlQuery to count the number of records which would be returned by the specified SqlQuery.
/// </summary>
/// <param name="sqlQuery">The SQL query.</param>
/// <returns>An <see cref="SqlQuery"/> to count the number of records which would be returned by the specified SqlQuery.</returns>
SqlQuery CountQuery(SqlQuery sqlQuery);
/// <summary>
/// Creates an SqlQuery with the specified statement type for the specified instance.
/// </summary>
/// <param name="statementType">Type of the statement.</param>
/// <param name="instance">The instance to generate the SqlQuery for.</param>
/// <returns>The created <see cref="SqlQuery"/>.</returns>
/// <exception cref="NotSupportedException">Thrown if the statement type is not supported.</exception>
SqlQuery CreateQuery(StatementType statementType, object instance);
/// <summary>
/// Creates an SqlQuery with the specified statement type for the specified type and identifier.
/// </summary>
/// <param name="statementType">Type of the statement.</param>
/// <param name="forType">The type of object to create the query for.</param>
/// <param name="identifier">The identifier of the instance to create the query for.</param>
/// <returns>The created <see cref="SqlQuery" />.</returns>
/// <exception cref="NotSupportedException">Thrown if the statement type is not supported.</exception>
SqlQuery CreateQuery(StatementType statementType, Type forType, object identifier);
/// <summary>
/// Creates an SqlQuery to page the records which would be returned by the specified SqlQuery based upon the paging options.
/// </summary>
/// <param name="sqlQuery">The SQL query.</param>
/// <param name="pagingOptions">The paging options.</param>
/// <returns>
/// A <see cref="SqlQuery" /> to return the paged results of the specified query.
/// </returns>
SqlQuery PageQuery(SqlQuery sqlQuery, PagingOptions pagingOptions);
}
}<file_sep>// -----------------------------------------------------------------------
// <copyright file="SelectSqlBuilder.cs" company="MicroLite">
// Copyright 2012 - 2013 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Query
{
using System;
using System.Linq;
using MicroLite.Dialect;
using MicroLite.Mapping;
[System.Diagnostics.DebuggerDisplay("{InnerSql}")]
internal sealed class SelectSqlBuilder : SqlBuilder, IFrom, IFunctionOrFrom, IWhereOrOrderBy, IAndOrOrderBy, IGroupBy, IOrderBy, IWhereSingleColumn, IHavingOrOrderBy
{
private readonly SqlCharacters sqlCharacters;
private bool addedOrder = false;
private bool addedWhere = false;
private string operand;
private string whereColumnName;
internal SelectSqlBuilder(SqlCharacters sqlCharacters, params string[] columns)
{
this.sqlCharacters = sqlCharacters;
this.AddColumns(columns);
}
/// <summary>
/// Adds a column as an AND to the where clause of the query.
/// </summary>
/// <param name="columnName">The column name to use in the where clause.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// This method allows us to specify a column to be used with the BETWEEN or IN keywords which is added to the query as an AND.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("LastName = @p0", "Smith")
/// .AndWhere("DateRegistered")
/// ...
/// </code>
/// </example>
public IWhereSingleColumn AndWhere(string columnName)
{
this.operand = " AND";
this.whereColumnName = this.sqlCharacters.EscapeSql(columnName);
return this;
}
/// <summary>
/// Adds a predicate as an AND to the where clause of the query.
/// </summary>
/// <param name="predicate">The predicate.</param>
/// <param name="args">The args.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// Adds the an additional predicate to the query as an AND.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("FirstName = @p0", "John")
/// .AndWhere("LastName = @p0", "Smith") // Each time, the parameter number relates to the individual method call.
/// .ToSqlQuery();
/// </code>
/// Would generate SELECT {Columns} FROM Customers WHERE (FirstName = @p0) AND (LastName = @p1)
/// @p0 would be John
/// @p1 would be Smith
/// </example>
/// <example>
/// Additionally, we could construct the query as follows:
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("FirstName = @p0 AND LastName = @p1", "John", "Smith")
/// .ToSqlQuery();
/// </code>
/// Would generate SELECT {Columns} FROM Customers WHERE (FirstName = @p0 AND LastName = @p1)
/// @p0 would be John
/// @p1 would be Smith
/// </example>
public IAndOrOrderBy AndWhere(string predicate, params object[] args)
{
this.AppendPredicate(" AND ({0})", predicate, args);
return this;
}
/// <summary>
/// Selects the average value in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// A simple query to find the average order total for a customer. By default, the result will be aliased as the column name.
/// <code>
/// var sqlQuery = SqlBuilder
/// .Select()
/// .Average("Total")
/// .From(typeof(Invoice))
/// .Where("CustomerId = @p0", 1022)
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT AVG(Total) AS Total FROM Invoices WHERE (CustomerId = @p0)
/// </example>
public IFunctionOrFrom Average(string columnName)
{
return this.Average(columnName, columnName);
}
/// <summary>
/// Selects the average value in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <param name="columnAlias">The alias in the result set for the calculated column.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// A simple query to find the average order total for a customer. We can specify a custom column alias if required.
/// <code>
/// var sqlQuery = SqlBuilder
/// .Select()
/// .Average("Total", columnAlias: "AverageTotal")
/// .From(typeof(Invoice))
/// .Where("CustomerId = @p0", 1022)
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT AVG(Total) AS AverageTotal FROM Invoices WHERE (CustomerId = @p0)
/// </example>
public IFunctionOrFrom Average(string columnName, string columnAlias)
{
if (this.InnerSql.Length > 7)
{
this.InnerSql.Append(", ");
}
this.InnerSql.AppendFormat("AVG({0}) AS {1}", this.sqlCharacters.EscapeSql(columnName), columnAlias);
return this;
}
/// <summary>
/// Uses the specified Arguments to filter the column.
/// </summary>
/// <param name="lower">The inclusive lower value.</param>
/// <param name="upper">The inclusive upper value.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// This method allows us to specify that a column is filtered with the results being between the 2 specified values.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("DateRegistered")
/// .Between(new DateTime(2000, 1, 1), new DateTime(2009, 12, 31))
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT {Columns} FROM Customers WHERE (DateRegistered BETWEEN @p0 AND @p1)
/// </example>
public IAndOrOrderBy Between(object lower, object upper)
{
if (!string.IsNullOrEmpty(this.operand))
{
this.InnerSql.Append(this.operand);
}
this.AppendPredicate(
" (" + this.whereColumnName + " BETWEEN {0})",
this.sqlCharacters.GetParameterName(0) + " AND " + this.sqlCharacters.GetParameterName(1),
new[] { lower, upper });
return this;
}
/// <summary>
/// Selects the number of records which match the specified filter.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// A simple query to find the number of customers. By default, the result will be aliased as the column name.
/// <code>
/// var sqlQuery = SqlBuilder
/// .Select()
/// .Count("CustomerId")
/// .From(typeof(Customer))
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT COUNT(CustomerId) AS CustomerId FROM Customers
/// </example>
public IFunctionOrFrom Count(string columnName)
{
return this.Count(columnName, columnName);
}
/// <summary>
/// Selects the number of records which match the specified filter.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <param name="columnAlias">The alias in the result set for the calculated column.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// A simple query to find the number of customers. We can specify a custom column alias if required.
/// <code>
/// var sqlQuery = SqlBuilder
/// .Select()
/// .Count("CustomerId", columnAlias: "CustomerCount")
/// .From(typeof(Customer))
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT COUNT(CustomerId) AS CustomerCount FROM Customers
/// </example>
public IFunctionOrFrom Count(string columnName, string columnAlias)
{
if (this.InnerSql.Length > 7)
{
this.InnerSql.Append(", ");
}
this.InnerSql.AppendFormat("COUNT({0}) AS {1}", this.sqlCharacters.EscapeSql(columnName), columnAlias);
return this;
}
/// <summary>
/// Specifies the table to perform the query against.
/// </summary>
/// <param name="table">The name of the table.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// <code>
/// var query = SqlBuilder.Select("Col1", "Col2").From("Customers")... // Add remainder of query
/// </code>
/// </example>
public IWhereOrOrderBy From(string table)
{
this.InnerSql.Append(" FROM ");
this.InnerSql.Append(this.sqlCharacters.EscapeSql(table));
return this;
}
/// <summary>
/// Specifies the type to perform the query against.
/// </summary>
/// <param name="forType">The type of object the query relates to.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// If the select criteria is * then all mapped columns will be used in the select list instead, otherwise the specified columns will be used.
/// <code>
/// var query = SqlBuilder.Select("Col1", "Col2").From(typeof(Customer))... // Add remainder of query
/// </code>
/// </example>
public IWhereOrOrderBy From(Type forType)
{
var objectInfo = ObjectInfo.For(forType);
IFrom select = this;
if (this.InnerSql.Length > 7 && this.InnerSql[7].CompareTo('*') == 0)
{
#if NET_3_5
this.InnerSql.Length = 0;
#else
this.InnerSql.Clear();
#endif
this.AddColumns(objectInfo.TableInfo.Columns.Select(c => c.ColumnName).ToArray());
}
return !string.IsNullOrEmpty(objectInfo.TableInfo.Schema)
? select.From(objectInfo.TableInfo.Schema + "." + objectInfo.TableInfo.Name)
: select.From(objectInfo.TableInfo.Name);
}
/// <summary>
/// Groups the results of the query by the specified columns.
/// </summary>
/// <param name="columns">The columns to group by.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// <code>
/// var sqlQuery = SqlBuilder
/// .Select("CustomerId")
/// .Max("Total")
/// .From(typeof(Invoice))
/// .GroupBy("CustomerId")
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT CustomerId, MAX(Total) AS Total FROM Invoices GROUP BY CustomerId
/// </example>
public IHavingOrOrderBy GroupBy(params string[] columns)
{
if (columns == null)
{
throw new ArgumentNullException("columns");
}
this.InnerSql.Append(" GROUP BY ");
for (int i = 0; i < columns.Length; i++)
{
if (i > 0)
{
this.InnerSql.Append(", ");
}
this.InnerSql.Append(this.sqlCharacters.EscapeSql(columns[i]));
}
return this;
}
/// <summary>
/// Specifies the having clause for the query.
/// </summary>
/// <param name="predicate">The predicate.</param>
/// <param name="value">The argument value.</param>
/// <returns>
/// The next step in the fluent sql builder.
/// </returns>
/// <example>
/// <code>
/// var sqlQuery = SqlBuilder
/// .Select("CustomerId")
/// .Max("Total")
/// .From(typeof(Invoice))
/// .GroupBy("CustomerId")
/// .Having("MAX(Total) > @p0", 10000M)
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT CustomerId, MAX(Total) AS Total FROM Invoices GROUP BY CustomerId HAVING MAX(Total) > @p0
/// </example>
public IOrderBy Having(string predicate, object value)
{
this.AppendPredicate(" HAVING {0}", predicate, value);
return this;
}
/// <summary>
/// Uses the specified Arguments to filter the column.
/// </summary>
/// <param name="args">The Arguments to filter the column.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// This method allows us to specify that a column is filtered with the results being in the specified values.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("Column1")
/// .In("X", "Y", "Z")
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT {Columns} FROM Customers WHERE (Column1 IN (@p0, @p1, @p2))
/// </example>
public IAndOrOrderBy In(params object[] args)
{
if (args == null)
{
throw new ArgumentNullException("args");
}
if (!string.IsNullOrEmpty(this.operand))
{
this.InnerSql.Append(this.operand);
}
#if NET_3_5
var predicate = string.Join(", ", Enumerable.Range(0, args.Length).Select(i => this.sqlCharacters.GetParameterName(i)).ToArray());
#else
var predicate = string.Join(", ", Enumerable.Range(0, args.Length).Select(i => this.sqlCharacters.GetParameterName(i)));
#endif
this.AppendPredicate(" (" + this.whereColumnName + " IN ({0}))", predicate, args);
return this;
}
/// <summary>
/// Uses the specified SqlQuery as a sub query to filter the column.
/// </summary>
/// <param name="subQuery">The sub query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// This method allows us to specify that a column is filtered with the results being in the specified values.
/// <code>
/// var customerQuery = SqlBuilder
/// .Select("CustomerId")
/// .From(typeof(Customer))
/// .Where("Age > @p0", 40)
/// .ToSqlQuery();
///
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Invoice))
/// .Where("CustomerId")
/// .In(customerQuery)
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT {Columns} FROM Invoices WHERE (CustomerId IN (SELECT CustomerId FROM Customers WHERE Age > @p0))
/// </example>
public IAndOrOrderBy In(SqlQuery subQuery)
{
if (subQuery == null)
{
throw new ArgumentNullException("subQuery");
}
if (!string.IsNullOrEmpty(this.operand))
{
this.InnerSql.Append(this.operand);
}
this.AppendPredicate(" (" + this.whereColumnName + " IN ({0}))", subQuery.CommandText, subQuery.Arguments.ToArray());
return this;
}
/// <summary>
/// Uses the specified argument to filter the column.
/// </summary>
/// <param name="comparisonValue">The value to compare with.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// This method allows us to specify that a column is filtered with the results being equal to the specified comparisonValue.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("DateRegistered")
/// .IsEqualTo(new DateTime(2000, 1, 1))
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT {Columns} FROM Customers WHERE (DateRegistered = @p0)
/// </example>
public IAndOrOrderBy IsEqualTo(object comparisonValue)
{
if (!string.IsNullOrEmpty(this.operand))
{
this.InnerSql.Append(this.operand);
}
this.AppendPredicate(" (" + this.whereColumnName + " = {0})", this.sqlCharacters.GetParameterName(0), comparisonValue);
return this;
}
/// <summary>
/// Uses the specified argument to filter the column.
/// </summary>
/// <param name="comparisonValue">The value to compare with.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// This method allows us to specify that a column is filtered with the results being greater than the specified comparisonValue.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("DateRegistered")
/// .IsGreaterThan(new DateTime(2000, 1, 1))
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT {Columns} FROM Customers WHERE (DateRegistered > @p0)
/// </example>
public IAndOrOrderBy IsGreaterThan(object comparisonValue)
{
if (!string.IsNullOrEmpty(this.operand))
{
this.InnerSql.Append(this.operand);
}
this.AppendPredicate(" (" + this.whereColumnName + " > {0})", this.sqlCharacters.GetParameterName(0), comparisonValue);
return this;
}
/// <summary>
/// Uses the specified argument to filter the column.
/// </summary>
/// <param name="comparisonValue">The value to compare with.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// This method allows us to specify that a column is filtered with the results being greater than or equal to the specified comparisonValue.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("DateRegistered")
/// .IsGreaterThanOrEqualTo(new DateTime(2000, 1, 1))
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT {Columns} FROM Customers WHERE (DateRegistered >= @p0)
/// </example>
public IAndOrOrderBy IsGreaterThanOrEqualTo(object comparisonValue)
{
if (!string.IsNullOrEmpty(this.operand))
{
this.InnerSql.Append(this.operand);
}
this.AppendPredicate(" (" + this.whereColumnName + " >= {0})", this.sqlCharacters.GetParameterName(0), comparisonValue);
return this;
}
/// <summary>
/// Uses the specified argument to filter the column.
/// </summary>
/// <param name="comparisonValue">The value to compare with.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// This method allows us to specify that a column is filtered with the results being less than the specified comparisonValue.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("DateRegistered")
/// .IsLessThan(new DateTime(2000, 1, 1))
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT {Columns} FROM Customers WHERE (DateRegistered <!--<--> @p0)
/// </example>
public IAndOrOrderBy IsLessThan(object comparisonValue)
{
if (!string.IsNullOrEmpty(this.operand))
{
this.InnerSql.Append(this.operand);
}
this.AppendPredicate(" (" + this.whereColumnName + " < {0})", this.sqlCharacters.GetParameterName(0), comparisonValue);
return this;
}
/// <summary>
/// Uses the specified argument to filter the column.
/// </summary>
/// <param name="comparisonValue">The value to compare with.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// This method allows us to specify that a column is filtered with the results being less than or equal to the specified comparisonValue.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("DateRegistered")
/// .IsLessThanOrEqualTo(new DateTime(2000, 1, 1))
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT {Columns} FROM Customers WHERE (DateRegistered <!--<-->= @p0)
/// </example>
public IAndOrOrderBy IsLessThanOrEqualTo(object comparisonValue)
{
if (!string.IsNullOrEmpty(this.operand))
{
this.InnerSql.Append(this.operand);
}
this.AppendPredicate(" (" + this.whereColumnName + " <= {0})", this.sqlCharacters.GetParameterName(0), comparisonValue);
return this;
}
/// <summary>
/// Uses the specified argument to filter the column.
/// </summary>
/// <param name="comparisonValue">The value to compare with.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// This method allows us to specify that a column is filtered with the results being like the specified comparisonValue.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("DateRegistered")
/// .IsLike(new DateTime(2000, 1, 1))
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT {Columns} FROM Customers WHERE (DateRegistered LIKE @p0)
/// </example>
public IAndOrOrderBy IsLike(object comparisonValue)
{
if (!string.IsNullOrEmpty(this.operand))
{
this.InnerSql.Append(this.operand);
}
this.AppendPredicate(" (" + this.whereColumnName + " LIKE {0})", this.sqlCharacters.GetParameterName(0), comparisonValue);
return this;
}
/// <summary>
/// Uses the specified argument to filter the column.
/// </summary>
/// <param name="comparisonValue">The value to compare with.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// This method allows us to specify that a column is filtered with the results not being equal to the specified comparisonValue.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("DateRegistered")
/// .IsNotEqualTo(new DateTime(2000, 1, 1))
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT {Columns} FROM Customers WHERE (DateRegistered <!--<>--> @p0)
/// </example>
public IAndOrOrderBy IsNotEqualTo(object comparisonValue)
{
if (!string.IsNullOrEmpty(this.operand))
{
this.InnerSql.Append(this.operand);
}
this.AppendPredicate(" (" + this.whereColumnName + " <> {0})", this.sqlCharacters.GetParameterName(0), comparisonValue);
return this;
}
/// <summary>
/// Specifies that the specified column contains a value which is not null.
/// </summary>
/// <returns>
/// The next step in the fluent sql builder.
/// </returns>
public IAndOrOrderBy IsNotNull()
{
if (!string.IsNullOrEmpty(this.operand))
{
this.InnerSql.Append(this.operand);
}
this.InnerSql.AppendFormat(" ({0} IS NOT NULL)", this.whereColumnName);
return this;
}
/// <summary>
/// Specifies that the specified column contains a value which is null.
/// </summary>
/// <returns>
/// The next step in the fluent sql builder.
/// </returns>
public IAndOrOrderBy IsNull()
{
if (!string.IsNullOrEmpty(this.operand))
{
this.InnerSql.Append(this.operand);
}
this.InnerSql.AppendFormat(" ({0} IS NULL)", this.whereColumnName);
return this;
}
/// <summary>
/// Selects the maximum value in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// A simple query to find the max order total for a customer. By default, the result will be aliased as the column name.
/// <code>
/// var sqlQuery = SqlBuilder
/// .Select()
/// .Max("Total")
/// .From(typeof(Invoice))
/// .Where("CustomerId = @p0", 1022)
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT MAX(Total) AS Total FROM Invoices WHERE (CustomerId = @p0)
/// </example>
public IFunctionOrFrom Max(string columnName)
{
return this.Max(columnName, columnName);
}
/// <summary>
/// Selects the maximum value in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <param name="columnAlias">The alias in the result set for the calculated column.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// A simple query to find the max order total for a customer. We can specify a custom column alias if required.
/// <code>
/// var sqlQuery = SqlBuilder
/// .Select()
/// .Max("Total", columnAlias: "MaxTotal")
/// .From(typeof(Invoice))
/// .Where("CustomerId = @p0", 1022)
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT MAX(Total) AS MaxTotal FROM Invoices WHERE (CustomerId = @p0)
/// </example>
public IFunctionOrFrom Max(string columnName, string columnAlias)
{
if (this.InnerSql.Length > 7)
{
this.InnerSql.Append(", ");
}
this.InnerSql.AppendFormat("MAX({0}) AS {1}", this.sqlCharacters.EscapeSql(columnName), columnAlias);
return this;
}
/// <summary>
/// Selects the minimum value in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// A simple query to find the min order total for a customer. By default, the result will be aliased as the column name.
/// <code>
/// var sqlQuery = SqlBuilder
/// .Select()
/// .Min("Total")
/// .From(typeof(Invoice))
/// .Where("CustomerId = @p0", 1022)
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT MIN(Total) AS Total FROM Invoices WHERE (CustomerId = @p0)
/// </example>
public IFunctionOrFrom Min(string columnName)
{
return this.Min(columnName, columnName);
}
/// <summary>
/// Selects the minimum value in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <param name="columnAlias">The alias in the result set for the calculated column.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// A simple query to find the min order total for a customer. We can specify a custom column alias if required.
/// <code>
/// var sqlQuery = SqlBuilder
/// .Select()
/// .Min("Total", columnAlias: "MinTotal")
/// .From(typeof(Invoice))
/// .Where("CustomerId = @p0", 1022)
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT MIN(Total) AS MinTotal FROM Invoices WHERE (CustomerId = @p0)
/// </example>
public IFunctionOrFrom Min(string columnName, string columnAlias)
{
if (this.InnerSql.Length > 7)
{
this.InnerSql.Append(", ");
}
this.InnerSql.AppendFormat("MIN({0}) AS {1}", this.sqlCharacters.EscapeSql(columnName), columnAlias);
return this;
}
/// <summary>
/// Uses the specified Arguments to filter the column.
/// </summary>
/// <param name="args">The Arguments to filter the column.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// This method allows us to specify that a column is filtered with the results being in the specified values.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("Column1")
/// .NotIn("X", "Y", "Z")
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT {Columns} FROM Customers WHERE (Column1 NOT IN (@p0, @p1, @p2))
/// </example>
public IAndOrOrderBy NotIn(params object[] args)
{
if (args == null)
{
throw new ArgumentNullException("args");
}
if (!string.IsNullOrEmpty(this.operand))
{
this.InnerSql.Append(this.operand);
}
#if NET_3_5
var predicate = string.Join(", ", Enumerable.Range(0, args.Length).Select(i => this.sqlCharacters.GetParameterName(i)).ToArray());
#else
var predicate = string.Join(", ", Enumerable.Range(0, args.Length).Select(i => this.sqlCharacters.GetParameterName(i)));
#endif
this.AppendPredicate(" (" + this.whereColumnName + " NOT IN ({0}))", predicate, args);
return this;
}
/// <summary>
/// Uses the specified SqlQuery as a sub query to filter the column.
/// </summary>
/// <param name="subQuery">The sub query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// This method allows us to specify that a column is filtered with the results being in the specified values.
/// <code>
/// var customerQuery = SqlBuilder
/// .Select("CustomerId")
/// .From(typeof(Customer))
/// .Where("Age > @p0", 40)
/// .ToSqlQuery();
///
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Invoice))
/// .Where("CustomerId")
/// .NotIn(customerQuery)
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT {Columns} FROM Invoices WHERE (CustomerId NOT IN (SELECT CustomerId FROM Customers WHERE Age > @p0))
/// </example>
public IAndOrOrderBy NotIn(SqlQuery subQuery)
{
if (subQuery == null)
{
throw new ArgumentNullException("subQuery");
}
if (!string.IsNullOrEmpty(this.operand))
{
this.InnerSql.Append(this.operand);
}
this.AppendPredicate(" (" + this.whereColumnName + " NOT IN ({0}))", subQuery.CommandText, subQuery.Arguments.ToArray());
return this;
}
/// <summary>
/// Orders the results of the query by the specified columns in ascending order.
/// </summary>
/// <param name="columns">The columns to order by.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .OrderByAscending("CustomerId")
/// .ToSqlQuery();
/// </code>
/// Would generate SELECT [Columns] FROM Customers ORDER BY CustomerId ASC
/// </example>
public IOrderBy OrderByAscending(params string[] columns)
{
this.AddOrder(columns, " ASC");
return this;
}
/// <summary>
/// Orders the results of the query by the specified columns in descending order.
/// </summary>
/// <param name="columns">The columns to order by.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .OrderByDescending("CustomerId")
/// .ToSqlQuery();
/// </code>
/// Would generate SELECT [Columns] FROM Customers ORDER BY CustomerId DESC
/// </example>
public IOrderBy OrderByDescending(params string[] columns)
{
this.AddOrder(columns, " DESC");
return this;
}
/// <summary>
/// Adds a column as an OR to the where clause of the query.
/// </summary>
/// <param name="columnName">The column name to use in the where clause.</param>
/// <returns>The next step in the fluent sql builder.</returns>
public IWhereSingleColumn OrWhere(string columnName)
{
this.operand = " OR";
this.whereColumnName = this.sqlCharacters.EscapeSql(columnName);
return this;
}
/// <summary>
/// Adds a predicate as an OR to the where clause of the query.
/// </summary>
/// <param name="predicate">The predicate.</param>
/// <param name="args">The args.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// Adds the an additional predicate to the query as an OR.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("LastName = @p0", "Smith")
/// .OrWhere("LastName = @p0", "Smithson") // Each time, the parameter number relates to the individual method call.
/// .ToSqlQuery();
/// </code>
/// Would generate SELECT [Columns] FROM Customers WHERE (LastName = @p0) OR (LastName = @p1)
/// @p0 would be Smith
/// @p1 would be Smithson
/// </example>
/// <example>
/// Additionally, we could construct the query as follows:
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("LastName = @p0 OR LastName = @p1", "Smith", "Smithson")
/// .ToSqlQuery();
/// </code>
/// Would generate SELECT [Columns] FROM Customers WHERE (LastName = @p0 OR LastName = @p1)
/// @p0 would be Smith
/// @p1 would be Smithson
/// </example>
public IAndOrOrderBy OrWhere(string predicate, params object[] args)
{
this.AppendPredicate(" OR ({0})", predicate, args);
return this;
}
/// <summary>
/// Selects the sum of the values in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// A simple query to find the total order total for a customer. By default, the result will be aliased as the column name.
/// <code>
/// var sqlQuery = SqlBuilder
/// .Select()
/// .Sum("Total")
/// .From(typeof(Invoice))
/// .Where("CustomerId = @p0", 1022)
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT SUM(Total) AS Total FROM Invoices WHERE (CustomerId = @p0)
/// </example>
public IFunctionOrFrom Sum(string columnName)
{
return this.Sum(columnName, columnName);
}
/// <summary>
/// Selects the sum of the values in the specified column.
/// </summary>
/// <param name="columnName">The column to query.</param>
/// <param name="columnAlias">The alias in the result set for the calculated column.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// A simple query to find the total order total for a customer. We can specify a custom column alias if required.
/// <code>
/// var sqlQuery = SqlBuilder
/// .Select()
/// .Sum("Total", columnAlias: "SumTotal")
/// .From(typeof(Invoice))
/// .Where("CustomerId = @p0", 1022)
/// .ToSqlQuery();
/// </code>
/// Will generate SELECT SUM(Total) AS SumTotal FROM Invoices WHERE (CustomerId = @p0)
/// </example>
public IFunctionOrFrom Sum(string columnName, string columnAlias)
{
if (this.InnerSql.Length > 7)
{
this.InnerSql.Append(", ");
}
this.InnerSql.AppendFormat("SUM({0}) AS {1}", this.sqlCharacters.EscapeSql(columnName), columnAlias);
return this;
}
/// <summary>
/// Specifies the where clause for the query.
/// </summary>
/// <param name="columnName">The column name to use in the where clause.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// This method allows us to specify a column to be used with the BETWEEN or IN keywords.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("DateRegistered")
/// ...
/// </code>
/// </example>
public IWhereSingleColumn Where(string columnName)
{
this.whereColumnName = this.sqlCharacters.EscapeSql(columnName);
if (!this.addedWhere)
{
this.InnerSql.Append(" WHERE");
this.addedWhere = true;
}
return this;
}
/// <summary>
/// Specifies the where clause for the query.
/// </summary>
/// <param name="predicate">The predicate.</param>
/// <param name="args">The args.</param>
/// <returns>The next step in the fluent sql builder.</returns>
/// <example>
/// Adds the first predicate to the query.
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("LastName = @p0", "Smith")
/// .ToSqlQuery();
/// </code>
/// Would generate SELECT [Columns] FROM Customers WHERE (LastName = @p0)
/// </example>
/// <example>
/// You can refer to the same parameter multiple times
/// <code>
/// var query = SqlBuilder
/// .Select("*")
/// .From(typeof(Customer))
/// .Where("LastName = @p0 OR @p0 IS NULL", lastName)
/// .ToSqlQuery();
/// </code>
/// Would generate SELECT [Columns] FROM Customers WHERE (LastName = @p0 OR @p0 IS NULL)
/// </example>
public IAndOrOrderBy Where(string predicate, params object[] args)
{
this.AppendPredicate(" WHERE ({0})", predicate, args);
this.addedWhere = true;
return this;
}
private void AddColumns(string[] columns)
{
this.InnerSql.Append("SELECT ");
if (columns != null)
{
if (columns.Length == 1 && columns[0] == "*")
{
this.InnerSql.Append("*");
}
else
{
for (int i = 0; i < columns.Length; i++)
{
if (i > 0)
{
this.InnerSql.Append(", ");
}
this.InnerSql.Append(this.sqlCharacters.EscapeSql(columns[i]));
}
}
}
}
private void AddOrder(string[] columns, string direction)
{
if (columns == null)
{
throw new ArgumentNullException("columns");
}
this.InnerSql.Append(!this.addedOrder ? " ORDER BY " : ", ");
for (int i = 0; i < columns.Length; i++)
{
if (i > 0)
{
this.InnerSql.Append(", ");
}
this.InnerSql.Append(this.sqlCharacters.EscapeSql(columns[i]));
}
this.InnerSql.Append(direction);
this.addedOrder = true;
}
private void AppendPredicate(string appendFormat, string predicate, params object[] args)
{
this.Arguments.AddRange(args);
var renumberedPredicate = SqlUtility.RenumberParameters(predicate, this.Arguments.Count);
this.InnerSql.AppendFormat(appendFormat, renumberedPredicate);
}
}
}<file_sep>namespace MicroLite.Tests.Configuration
{
using System;
using MicroLite.Configuration;
using MicroLite.FrameworkExtensions;
using MicroLite.Query;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="FluentConfiguration"/> class.
/// </summary>
public class FluentConfigurationTests
{
public class WhenCallingCreateSessionFactory : IDisposable
{
private readonly ISessionFactory sessionFactory;
public WhenCallingCreateSessionFactory()
{
this.ResetExternalDependencies();
var fluentConfiguration = new FluentConfiguration();
this.sessionFactory = fluentConfiguration.ForConnection("SqlConnection", "MicroLite.Dialect.MsSqlDialect").CreateSessionFactory();
}
public void Dispose()
{
this.ResetExternalDependencies();
}
[Fact]
public void TheSessionFactoryShouldBeAddedToTheSessionFactoriesProperty()
{
Assert.Contains(this.sessionFactory, Configure.SessionFactories);
}
[Fact]
public void TheSqlCharactersPropertyOnSqlBuilderShouldBeSet()
{
Assert.Equal(this.sessionFactory.SqlDialect.SqlCharacters, SqlBuilder.SqlCharacters);
}
private void ResetExternalDependencies()
{
Configure.SessionFactories.Clear();
SqlBuilder.SqlCharacters = null;
}
}
public class WhenCallingCreateSessionFactoryMultipleTimesForTheSameConnection : IDisposable
{
private readonly ISessionFactory sessionFactory1;
private readonly ISessionFactory sessionFactory2;
public WhenCallingCreateSessionFactoryMultipleTimesForTheSameConnection()
{
Configure.SessionFactories.Clear();
var fluentConfiguration = new FluentConfiguration();
this.sessionFactory1 = fluentConfiguration.ForConnection("SqlConnection", "MicroLite.Dialect.MsSqlDialect").CreateSessionFactory();
this.sessionFactory2 = fluentConfiguration.ForConnection("SqlConnection", "MicroLite.Dialect.MsSqlDialect").CreateSessionFactory();
}
public void Dispose()
{
Configure.SessionFactories.Clear();
}
[Fact]
public void TheSameSessionFactoryShouldBeReturned()
{
Assert.Same(this.sessionFactory1, this.sessionFactory2);
}
}
public class WhenCallingForConnectionAndTheConnectionNameDoesNotExistInTheAppConfig
{
[Fact]
public void AMicroLiteExceptionShouldBeThrown()
{
var fluentConfiguration = new FluentConfiguration();
var exception = Assert.Throws<MicroLiteException>(() => fluentConfiguration.ForConnection("TestDB", "MicroLite.Dialect.MsSqlDialect"));
Assert.Equal(Messages.FluentConfiguration_ConnectionNotFound.FormatWith("TestDB"), exception.Message);
}
}
public class WhenCallingForConnectionAndTheConnectionNameIsNull
{
[Fact]
public void AnArgumentNullExceptionShouldBeThrown()
{
var fluentConfiguration = new FluentConfiguration();
var exception = Assert.Throws<ArgumentNullException>(() => fluentConfiguration.ForConnection(null, "MicroLite.Dialect.MsSqlDialect"));
Assert.Equal(exception.ParamName, "connectionName");
}
}
public class WhenCallingForConnectionAndTheProviderInTheAppConfigIsNotSupported
{
[Fact]
public void AMicroLiteExceptionShouldBeThrown()
{
var fluentConfiguration = new FluentConfiguration();
Assert.Throws<MicroLiteException>(
() => fluentConfiguration.ForConnection("ConnectionWithInvalidProviderName", "MicroLite.Dialect.MsSqlDialect"));
}
}
public class WhenCallingForConnectionAndTheSqlDialectDoesNotImplementISqlDialect
{
[Fact]
public void AMicroLiteExceptionShouldBeThrown()
{
var fluentConfiguration = new FluentConfiguration();
var exception = Assert.Throws<NotSupportedException>(
() => fluentConfiguration.ForConnection("SqlConnection", "MicroLite.SqlQuery"));
Assert.Equal(Messages.FluentConfiguration_DialectMustImplementISqlDialect.FormatWith("MicroLite.SqlQuery"), exception.Message);
}
}
public class WhenCallingForConnectionAndTheSqlDialectIsNotSupported
{
[Fact]
public void AMicroLiteExceptionShouldBeThrown()
{
var fluentConfiguration = new FluentConfiguration();
var exception = Assert.Throws<NotSupportedException>(
() => fluentConfiguration.ForConnection("SqlConnection", "MicroLite.Dialect.DB2"));
Assert.Equal(Messages.FluentConfiguration_DialectNotSupported.FormatWith("MicroLite.Dialect.DB2"), exception.Message);
}
}
}
}<file_sep>namespace MicroLite.Tests.Integration.Select
{
using Xunit;
public class WhenSelectingAnUnknownIdentifier : IntegrationTest
{
private readonly Customer customer;
public WhenSelectingAnUnknownIdentifier()
{
this.customer = this.Session.Single<Customer>(12345);
}
[Fact]
public void SingleShouldReturnNull()
{
Assert.Null(this.customer);
}
}
}
|
846bb97430c973167d728dbd1bbb4560e743c9c7
|
[
"Markdown",
"C#"
] | 106
|
C#
|
DavidSteele/MicroLite
|
c280e602fd37e97aaec76d8f9ebf7e26334bf560
|
10e5e37d1efb83e145749c90cf703e94858150e3
|
refs/heads/master
|
<repo_name>meowmeowcomputers/react-form-app<file_sep>/src/App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import {BrowserRouter, Route, Link, Switch}
from 'react-router-dom';
import { Provider } from 'react-redux';
import store from './store';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import MyForm from './myform';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {red700} from 'material-ui/styles/colors';
const theme = getMuiTheme({
palette: {primary1Color: red700}
});
const NoMatch = ({ location }) => (
<div>
<h3>Page not found: {location.pathname}</h3>
</div>
)
const Home = () => (<h2>Home</h2>)
class App extends Component {
render() {
return (
// <div className="App">
// <div className="App-header">
// <img src={logo} className="App-logo" alt="logo" />
// </div>
//
// </div>
<Provider store={store}>
<MuiThemeProvider muiTheme={theme}>
<div>
<BrowserRouter>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/form">Form</Link></li>
</ul>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/form" component={MyForm}/>
<Route component={NoMatch}/>
</Switch>
</div>
</BrowserRouter>
</div>
</MuiThemeProvider>
</Provider>
);
}
}
export default App;
|
1162827f3fed0e4e65f1b3c28d11047483c7ee41
|
[
"JavaScript"
] | 1
|
JavaScript
|
meowmeowcomputers/react-form-app
|
7f83ffe36b7da098dab94bbfea5be0e6d46fbccb
|
a83f79d4f7cfe5c830cd45ae6eb90f7b7afb7a44
|
refs/heads/master
|
<repo_name>vikbert/vagrant-sf-rest<file_sep>/Vagrantfile
$hostname = "vagrant"
Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.hostname = $hostname
# Uncomment the next line if you want a DHCP address
# config.vm.network "public_network"
config.vm.network "private_network", ip: "172.28.128.30"
config.vm.network "forwarded_port", guest: 80, host: 8080
config.vm.network "forwarded_port", guest: 3306, host: 6033
config.vm.synced_folder ".", "/vagrant", id: "vagrant-root",
owner: "vagrant",
group: "www-data",
mount_options: ["dmode=775,fmode=775"]
config.vm.provider "virtualbox" do |vb|
vb.memory = 1024
end
config.vm.provision "shell", path: "./scripts/bootstrap.sh"
end
<file_sep>/scripts/bootstrap.sh
#!/usr/bin/env bash
echo "Installing LAMP stack"
# reconf. locale
sudo dpkg-reconfigure locales
sudo apt-get update -y
debconf-set-selections <<< 'mysql-server-5.5 mysql-server/root_password password root'
debconf-set-selections <<< 'mysql-server-5.5 mysql-server/root_password_again password root'
sudo apt-get install -y apache2 libapache2-mod-php5 php5 php5-mysql mysql-server php5-xdebug
echo "LAMP installed succesed!"
# MySQL server
echo "Stopping MySQL service"
sudo service mysql stop
sudo sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/my.cnf
echo "Starting MySQL service"
sudo service mysql start
echo "use mysql;update user set host='%' where user='root' and host='#{$hostname}';flush privileges;" | mysql -uroot -proot
echo "MySQL configured succesed! root@localhost password: <PASSWORD>"
# Web folder - shared folder
sudo rm -rf /var/www/html
sudo ln -s /vagrant /var/www/html
echo "shared folder linked succesed! /vagarnt -> /var/www/html"
# apache2 & vhost
sudo cp /vagrant/scripts/000-default.conf /etc/apache2/sites-available/000-default.conf
echo "ServerName localhost" >> /etc/apache2/apache2.conf
a2enmod rewrite
sudo service apache2 restart
#sudo cat > /etc/php5/mods-available/xdebug.ini << EOF
#zend_extension=xdebug.so
#xdebug.remote_enable=On
#xdebug.remote_connect_back=On
#xdebug.remote_autostart=Off
#xdebug.remote_log=/tmp/xdebug.log
#EOF
# Tooling
#
#
# curl: command client for URLs
# php5-curl: php module for curl
# httpie: human friendly client for URLs
#
sudo apt-get install -y curl php5-curl redis-server php5-redis
# composer
php -r "readfile('https://getcomposer.org/installer');" | php
sudo mv composer.phar /usr/local/bin/composer
sudo apt-get install -y git
sudo service apache2 restart
sudo service redis-server restart
echo "Bootstap install done. Browser the test page on: http://172.28.128.30"<file_sep>/mac_install.sh
#!/usr/bin/env bash
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew update
brew install caskroom/cask/brew-cask
brew cask install virtualbox
brew cask install vagrant
vagrant up
<file_sep>/scripts/enable_ssl.sh
#! /bin/bash
# enable ssl on apache
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/apache.key -out /etc/ssl/certs/apache.crt
sudo a2enmode ssl
sudo service apache2 restart<file_sep>/scripts/install_php_56.sh
#! /bin/bash
# !!! Interactive mode to enter MySQL db passwort
sudo apt-get install phpmyadmin
# update php to V5.6
sudo add-apt-repository ppa:ondrej/php5-5.6
sudo apt-get install -y python-software-properties
sudo apt-get install -y php5
<file_sep>/scripts/set_permission.sh
#! /bin/bash
sudo mkdir -p /var/cache/core
sudo mkdir -p /var/log/core
sudo chown -R vagrant:www-data /var/cache/core
sudo chown -R vagrant:www-data /var/log/core
<file_sep>/scripts/install_dev_tools.sh
#! /bin/bash
# !!! Interactive mode to enter MySQL db passwort
#sudo apt-get install phpmyadmin
# extra tools
sudo apt-get install -y git multitail httpie
|
162fccd27a9b49d9ef52b512f225caec2d576392
|
[
"Ruby",
"Shell"
] | 7
|
Ruby
|
vikbert/vagrant-sf-rest
|
b39c8e2a82f413d4f1316525a25995bb53ef74b2
|
3a24535ac18953fcb53ca52feb782f641c93ae3e
|
refs/heads/master
|
<file_sep><?php
include "Circle.php";
include "Comparable.php";
class ComparableCircle implements Comparable
{
public $circle1;
public $circle2;
public function __construct($_circle1,$_circle2)
{
$this->circle1 = $_circle1;
$this->circle2 = $_circle2;
}
public function comparableTo()
{
$radius1 = $this->circle1->getRadius();
$radius2 = $this->circle2->getRadius();
if ($radius1>$radius2) {
return 1;
}
if ($radius1<$radius2) {
return -1;
} else {
return 0;
}
}
}
<file_sep><?php
include "ComparableCircle.php";
$circleOne = new Circle(8, "circleOne");
$circleTwo = new Circle(2, "circleTwo");
$hinhtron = new ComparableCircle($circleOne,$circleTwo);
echo $hinhtron->comparableTo();
<file_sep><?php
interface Comparable
{
public function comparableTo();
}
|
e7de139c8cb87282488d4fe60d256850642e3e85
|
[
"PHP"
] | 3
|
PHP
|
vanlinh1211/SS5_TH_Comparable2
|
167b899e7536b1c17c75e732a0d5fbcdcaae2e9c
|
c5fbe1cfe274540a4e51e2390ae644ec37b4a9d7
|
refs/heads/main
|
<file_sep>package com.bawei.s1dirsir.model;
import com.bawei.s1dirsir.Api;
import com.bawei.s1dirsir.bean.JsonBean;
import com.bawei.s1dirsir.contract.FoodContract;
import com.bw.mvp.model.BaseModel;
import com.bw.net.RetrofitFactory;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/*
* @ClassName FoodModel
* @Description TODO
* @Author 康泽林
* @Date 2021/9/3 15:15
* @Version 1.0
*/
public class FoodModel extends BaseModel implements FoodContract.FoodModel {
@Override
public void getFood(Observer<JsonBean> observer) {
RetrofitFactory.getRetrofitFactory().createRetrofit().create(Api.class)
.getJson()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
}
<file_sep>package com.bawei.logger.common;
/*
* @ClassName LoggerLevel
* @Description TODO
* @Author 海
* @Date 2021/9/13 19:52
* @Version 1.0
*/
public enum LoggerLevel {
Verbose(1),Debug(2),Info(3),Warn(4),Error(5);
private int value=0;
LoggerLevel(int _value){
this.value=_value;
}
}<file_sep>package com.bw.database.user;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.blankj.utilcode.util.Utils;
/**
* @package:com.bw.database.user
* @fileName:GreenDaoManager
* @date on:2021/9/11 8:22
* @another:HG
* @email:<EMAIL>
*/
public class GreenDaoManager {
private static volatile GreenDaoManager greenDaoManager;
private static DaoMaster daoMaster;
private static DaoSession daoSession;
private static DaoMaster.DevOpenHelper user;
private static UserDao userDao;
private Context context;
public static GreenDaoManager getGreenDaoManager() {
if(greenDaoManager==null){
synchronized (GreenDaoManager.class){
if(greenDaoManager==null){
greenDaoManager = new GreenDaoManager();
}
}
}
return greenDaoManager;
}
public void init(Context context){
this.context = context;
}
public static DaoMaster getDaoMaster() {
if(daoMaster==null){
user = new DaoMaster.DevOpenHelper(Utils.getApp(), "user");
SQLiteDatabase writableDatabase = user.getWritableDatabase();
daoMaster = new DaoMaster(writableDatabase);
}
return daoMaster;
}
public static DaoSession getDaoSession() {
if(daoSession==null){
if(daoMaster==null){
daoMaster = getDaoMaster();
}
daoSession = daoMaster.newSession();
}
return daoSession;
}
public static UserDao getUserDao(){
userDao = daoSession.getUserDao();
return userDao ;
}
}
<file_sep>package com.bw.net.retrofit;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
/**
* @package:com.bw.net.retrofit
* @fileName:CustomGsonConverterFactory
* @date on:2021/9/9 8:59
* @another:HG
* @email:<EMAIL>
*/
public class CustomGsonConverterFactory extends Converter.Factory {
public static CustomGsonConverterFactory create(){
return new CustomGsonConverterFactory();
}
@Override
public Converter<ResponseBody,?>responseBodyConverter(Type type, Annotation[]annotations, Retrofit retrofit){
return new CustomResponseBodyConverter<>();
}
@Override
public Converter<?, RequestBody>requestBodyConverter(Type type,Annotation[]parameterAnnotations,Annotation[]mothodAnnotations,Retrofit retrofit){
return new CustomRequestBodyConverter<>();
}
}
<file_sep>package com.bawei.s1dirsir.inject;
import com.bawei.s1dirsir.activity.MainActivity;
import dagger.Component;
/*
* @ClassName ActivityComment
* @Description TODO
* @Author 康泽林
* @Date 2021/9/12 19:58
* @Version 1.0
*/
@Component(modules = FoodModule.class)
public interface ActivityComment {
void inject(MainActivity mainActivity);
}
<file_sep>package com.bawei.log;
import android.util.Log;
/*
* @ClassName XLogImpl
* @Description TODO
* @Author 海
* @Date 2021/9/11 8:29
* @Version 1.0
*/
public class XLogImpl implements ILog{
static {
System.loadLibrary("marsxlog");
//System.loadLibrary("native-lib");
}
@Override
public void print(int level, String tag, String msg) {
switch (level){
case LogConstant.VERBOSE:
Log.v("",LogHelper.formatXLog(level,tag,msg));
break;
case LogConstant.DEBUG:
Log.d("",LogHelper.formatXLog(level,tag,msg));
break;
case LogConstant.WARN:
Log.w("",LogHelper.formatXLog(level,tag,msg));
break;
case LogConstant.ERROR:
Log.e("",LogHelper.formatXLog(level,tag,msg));
break;
case LogConstant.ASSERT:
break;
default:
break;
}
}
@Override
public void setWriteFile(boolean isWrite) {
}
} <file_sep>package com.bawei.log;
import android.content.Context;
import java.util.logging.LogManager;
/*
* @ClassName RuntimeEnv
* @Description TODO
* @Author 海
* @Date 2021/9/11 8:24
* @Version 1.0
*/
public class RuntimeEnv {
/**
* 调试用的标志
*/
private static final String TAG = RuntimeEnv.class.getSimpleName();
/**
* 运行时的Application 类型的Context
*/
public static Context appContext = null;
/**
* 进程名 子进程将按照 主进程_子进程 显示
*/
public static String procName = "";
/**
* 包名
*/
public static String packageName = "";
/**
* 应用名称
*/
public static String appName = "";
private static final int MY_PERMISSIONS_REQUEST_WRITE_STORE = 1;
/***
* 获取当前运行的类的方法 和行数
* @return
*/
public static String getCurrentMethodName() {
StackTraceElement element = getCallLogManagerStackTrace();
if (element != null){
String methodName = element.getMethodName();
int lineNumber = element.getLineNumber();
return methodName + "() " + lineNumber;
}
return null;
}
/***
* 获取当前运行的类的方法 和行数
* @return
*/
public static String getCurrentMethodName2() {
StackTraceElement element = getCallLogManagerStackTrace();
if (element != null){
String methodName = element.getMethodName();
return methodName;
}
return null;
}
/***
* 获取当前运行的类的行数
* @return
*/
public static int getCurrentLineNumber() {
StackTraceElement element = getCallLogManagerStackTrace();
if (element != null){
return element.getLineNumber();
}
return -1;
}
/**
* 获取当前运行的Class
* @return
*/
public static String getCurrentClassName() {
StackTraceElement element = getCallLogManagerStackTrace();
if (element != null){
String clazz = element.getClassName();
//去最后一个即 类的简名
if (clazz.contains(".")){
String strArray[] = clazz.split("\\.");
clazz = strArray[strArray.length -1];
}
return clazz;
}
return null;
}
/**
* 获取当前运行的Class
* @return
*/
public static String getCurrentFileName() {
StackTraceElement element = getCallLogManagerStackTrace();
if (element != null){
String fileName = element.getFileName();
return fileName;
}
return null;
}
/**
* 获取调用LogManager的调用栈
* @return
*/
private static StackTraceElement getCallLogManagerStackTrace(){
int level = 0;
//LogManager的全限定名称
String clazzName = LogManager.class.getCanonicalName();
//方法数组
String array[] = new String[]{"v","d","i","w","e"};
StackTraceElement[] stacks = new Throwable().getStackTrace();
//依次寻找,找到LogManager的上一级
for (level = 0 ;level < stacks.length;level++){
String method = stacks[level].getMethodName();
if (clazzName.equals(stacks[level].getClassName()) && (method.equals(array[0])
|| method.equals(array[1]) || method.equals(array[2])
|| method.equals(array[3]) || method.equals(array[4]))){
break;
}
}
//返回上一级的调用栈
if (stacks.length > (level + 1)){
return stacks[level +1];
}
return null;
}
} <file_sep>package com.bw.mvp.presenter;
import com.bw.mvp.model.IModel;
import com.bw.mvp.view.IView;
import javax.inject.Inject;
public class BasePresenter<M extends IModel,V extends IView> implements IPresenter {
protected M model;
protected V view;
@Inject
public BasePresenter(M model, V view) {
this.model = model;
this.view = view;
}
@Override
public void Destory() {
if (model != null){
model.Destory();
model = null;
}
if (view != null){
view = null;
}
}
}
<file_sep>package com.bawei.arouter.base
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.PersistableBundle
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.arouter.constants.ConfigConstants
import com.bawei.arouter.R
//@Route(path = ConfigConstants)
class KotlinTestActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onCreate(savedInstanceState, persistentState)
//注入ARouter
ARouter.getInstance().inject(this)
}
}<file_sep>apply from:"gradles/Version.gradle"
ext{
url=[
debug:"http://172.16.17.32:8080/",
release:"http://172.16.17.32:8080/",
testServerUrl:"http://172.16.17.32:8080/"
]
}<file_sep>package com.bawei.s1dirsir.adapter;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
/**
* @package:com.example.s1dirsir.adapter
* @fileName:FragmentAdapter
* @date on:2021/9/13 20:18
* @another:HG
* @email:<EMAIL>
*/
public class FragmentAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment>list;
public FragmentAdapter(@NonNull @NotNull FragmentManager fm, ArrayList<Fragment> list) {
super(fm);
this.list = list;
}
@NonNull
@NotNull
@Override
public Fragment getItem(int position) {
return list.get(position);
}
@Override
public int getCount() {
return list.size();
}
}
<file_sep>package com.bw.net.retrofit;
import androidx.lifecycle.LiveData;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Retrofit;
/**
* @package:com.bw.net.retrofit
* @fileName:LiveDataCallAdapterFactory
* @date on:2021/9/9 9:08
* @another:HG
* @email:<EMAIL>
*/
public class LiveDataCallAdapterFactory extends CallAdapter.Factory {
public static LiveDataCallAdapterFactory create(){
return new LiveDataCallAdapterFactory();
}
@Override
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
if(!(returnType instanceof ParameterizedType)){
throw new IllegalArgumentException("要求返回值必须是可参数化的(支持泛型)");
}
Class<?> returnTypeClazz = CallAdapter.Factory.getRawType(returnType);
if(returnTypeClazz!= LiveData.class&&returnTypeClazz!= Call.class){
throw new IllegalArgumentException("返回值类型必须是LiveData或者是Call");
}
Type t = CallAdapter.Factory.getParameterUpperBound(0, (ParameterizedType) returnType);
if(returnTypeClazz==Call.class){
return new DefaultCallAdapter<>(t);
}else if(returnTypeClazz==LiveData.class){
return new LiveDataCallAdapter<>(t);
}
return new DefaultCallAdapter<>(t);
}
}
<file_sep>package com.bawei.arouter.base
import android.app.Application
import com.alibaba.android.arouter.BuildConfig
import com.alibaba.android.arouter.launcher.ARouter
/*
* @ClassName App
* @Description TODO
* @Author 海
* @Date 2021/9/9 9:53
* @Version 1.0
*/
class App : Application() {
override fun onCreate() {
super.onCreate()
// 初始化阿里巴巴路由框架
if (BuildConfig.DEBUG){ // 这两行必须写在init之前,否则这些配置在init过程中将无效
// 日志开启
ARouter.openLog()
// 调试模式开启,如果在install run模式下运行,则必须开启调试模式
ARouter.openDebug()
}
// 尽可能早,推荐在Application中初始化
ARouter.init(this)
}
}<file_sep>package com.bw.net.retrofit;
import java.lang.reflect.Type;
import retrofit2.Call;
import retrofit2.CallAdapter;
/**
* @package:com.bw.net.retrofit
* @fileName:DefaultCallAdapter
* @date on:2021/9/9 9:06
* @another:HG
* @email:<EMAIL>
*/
public class DefaultCallAdapter<R>implements CallAdapter<R,Object> {
Type mType = null;
public DefaultCallAdapter(Type mType) {
this.mType = mType;
}
@Override
public Type responseType() {
return mType;
}
@Override
public Object adapt(Call<R> call) {
return call;
}
}
<file_sep>package com.bw.mvp.view;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.bw.mvp.presenter.IPresenter;
import javax.inject.Inject;
public abstract class BaseActivty<P extends IPresenter> extends AppCompatActivity implements IActivity,IView{
@Inject
protected P p;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(bindLayout());
immersive();
initView();
initData();
showLoading();
}
@Override
public void immersive() {
getSupportActionBar().hide();
View decorView = getWindow().getDecorView();
int option = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
decorView.setSystemUiVisibility(option);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (p != null){
p.Destory();
p = null;
}
}
}
<file_sep>include ':Mvp'
include ':Utils'
rootProject.name = "S1DirSir"
include ':app'
include ':Net'
include ':ARouter'
include ':SpFrame'
include ':Database'
include ':Log'
include ':Logger'
include ':classfiymodule'
include ':shoppingcaremodule'
<file_sep>package com.bw.mvp.view;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.bw.mvp.presenter.IPresenter;
import javax.inject.Inject;
public abstract class BaseFragment<P extends IPresenter> extends Fragment implements IActivity, IView, IFragment {
@Inject
protected P p;
private View inflate;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
inflate = inflater.inflate(bindLayout(), container, false);
return inflate;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initView();
}
@Override
public void onResume() {
super.onResume();
initData();
showLoading();
}
@Override
public <T extends View> T findViewById(int id) {
return inflate.findViewById(id);
}
@Override
public void onDestroy() {
super.onDestroy();
if (p != null){
p.Destory();
p = null;
}
}
}
<file_sep>package com.bw.mvp.model;
public class BaseModel implements IModel {
@Override
public void Destory() {
}
}
<file_sep>package com.bw.net.retrofit;
import com.bw.net.protocol.BaseRespEntry;
import com.bw.net.protocol.TokenRespEntry;
import com.google.gson.Gson;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Converter;
/**
* @package:com.bw.net.retrofit
* @fileName:CustomResponseBodyConverter
* @date on:2021/9/9 9:05
* @another:HG
* @email:<EMAIL>
*/
public class CustomResponseBodyConverter<T>implements Converter<ResponseBody,T> {
@Override
public T convert(ResponseBody value) throws IOException {
String jsonContent = value.string();
if(jsonContent.contains("access_")){
return (T)new Gson().fromJson(jsonContent, TokenRespEntry.class);
}
BaseRespEntry entry = new Gson().fromJson(jsonContent, BaseRespEntry.class);
return (T) entry;
}
}
<file_sep>package com.bawei.log;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
* @ClassName LogHelper
* @Description TODO
* @Author 海
* @Date 2021/9/11 8:19
* @Version 1.0
*/
public class LogHelper {
public static String formatLog(int level, String tag, String msg){
//例:2021-09-11 10.22.23.445
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String time = sf.format(new Date());
String preTAG = LogConstant.V;
switch (level) {
case LogConstant.VERBOSE:
preTAG = LogConstant.V;
break;
case LogConstant.DEBUG:
preTAG = LogConstant.D;
break;
case LogConstant.INFO:
preTAG = LogConstant.I;
break;
case LogConstant.WARN:
preTAG = LogConstant.W;
break;
case LogConstant.ERROR:
preTAG = LogConstant.E;
break;
case LogConstant.ASSERT:
preTAG = LogConstant.A;
break;
default:
break;
}
//打印进程ID 线程ID 当前类 当前方法
StringBuilder builder = new StringBuilder();
builder.append(time).append(" ")
.append(preTAG).append(" ")
.append(android.os.Process.myPid()).append("|")
.append(android.os.Process.myTid()).append("[")
.append( RuntimeEnv.getCurrentFileName()).append("->")
.append(RuntimeEnv.getCurrentMethodName()).append("]")
.append("[").append(tag).append("]").append(msg);
return builder.toString();
}
public static String formatXLog(int level, String tag, String msg){
// 时间格式 2017-8-26 23.22.23.445
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String time = sf.format(new Date());
String preTAG = LogConstant.V;
switch (level) {
case LogConstant.VERBOSE:
preTAG = LogConstant.V;
break;
case LogConstant.DEBUG:
preTAG = LogConstant.D;
break;
case LogConstant.INFO:
preTAG = LogConstant.I;
break;
case LogConstant.WARN:
preTAG = LogConstant.W;
break;
case LogConstant.ERROR:
preTAG = LogConstant.E;
break;
case LogConstant.ASSERT:
preTAG = LogConstant.A;
break;
default:
break;
}
//打印进程ID 线程ID 当前类 当前方法
StringBuilder builder = new StringBuilder();
builder.append("[")
.append(RuntimeEnv.getCurrentFileName()).append("->")
.append(RuntimeEnv.getCurrentMethodName()).append("]")
.append("[").append(tag).append("] ").append(msg);
return builder.toString();
}
} <file_sep>package com.bawei.arouter.constants
import com.alibaba.android.arouter.BuildConfig
/*
* When I wrote this, only God and I understood what I was doing
* Now, God only knows
* 写这段代码的时候,只有上帝和我知道它是干嘛的
* 现在,只有上帝知道
* @ClassName ConfigConstants
* @Description TODO
* @Author 海
* @Date 2021/9/15 20:24
* @Version 1.0
*/
object ConfigConstants {
const val IS_DEBUG = BuildConfig.DEBUG
const val TAG = "TAG"
const val PATH = "path"
//存储是否登录的
const val SP_IS_LOGIN = "sp_is_login"
private const val BASE_PATH = "/base/path/"
//登录
const val LOGIN_PATH = BASE_PATH + "login"
//不需要登录的activity
const val FIRST_PATH = BASE_PATH + "first"
//登录登录的actvity
const val SECOND_PATH = BASE_PATH + "second"
}
<file_sep>package com.bawei.s1dirsir.activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import androidx.viewpager.widget.ViewPager;
import com.bawei.s1dirsir.R;
import com.bawei.s1dirsir.adapter.GuidanceAdapter;
import com.bw.mvp.view.BaseActivty;
import java.util.ArrayList;
public class GuidanceActivity extends BaseActivty {
private ViewPager vp;
private Button btnTiao;
private ArrayList<Integer> integers;
@Override
public int bindLayout() {
return R.layout.activity_zhuye;
}
@Override
public void initView() {
vp = (ViewPager) findViewById(R.id.vp);
btnTiao = (Button) findViewById(R.id.btn_tiao);
}
@Override
public void initData() {
integers = new ArrayList<>();
integers.add(R.drawable.a11);
integers.add(R.drawable.a22);
integers.add(R.drawable.a33);
}
@Override
public void showLoading() {
GuidanceAdapter guidanceAdapter = new GuidanceAdapter(this, integers);
vp.setAdapter(guidanceAdapter);
btnTiao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(GuidanceActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}<file_sep>package com.bawei.s1dirsir.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import com.bawei.s1dirsir.R;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* @ClassName Zhuadarpter
* @Description TODO
* @Author 梁波
* @Date 2021/9/14 9:16
* @Version 1.0
*/
public class GuidanceAdapter extends PagerAdapter {
List<Integer> integers;
private Context context;
public GuidanceAdapter(Context context,List<Integer> integers) {
this.context = context;
this.integers = integers;
}
@Override
public int getCount() {
return integers.size();
}
@Override
public boolean isViewFromObject(@NonNull @NotNull View view, @NonNull @NotNull Object object) {
return view == object;
}
@NonNull
@NotNull
@Override
public Object instantiateItem(@NonNull @NotNull ViewGroup container, int position) {
View inflate = View.inflate(context, R.layout.zhuitem, null);
ImageView imageView = inflate.findViewById(R.id.zhu_im);
imageView.setImageResource(integers.get(position));
container.addView(inflate);
return inflate;
}
@Override
public void destroyItem(@NonNull @NotNull ViewGroup container, int position, @NonNull @NotNull Object object) {
container.removeView((View) object);
}
}
<file_sep>package com.bawei.arouter.interceptor
import android.content.Context
import android.util.Log
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Interceptor
import com.alibaba.android.arouter.facade.callback.InterceptorCallback
import com.alibaba.android.arouter.facade.template.IInterceptor
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.arouter.constants.ConfigConstants
/*
* @ClassName GlobalInterceptor
* @Description TODO
* @Author 海
* @Date 2021/9/9 9:31
* @Version 1.0
*/
//定义一个拦截器,需要name随便写一个即可
@Interceptor(name = "login", priority = 9)
class GlobalInterceptor : IInterceptor{
private var context: Context? = null
override fun process(postcard: Postcard?, callback: InterceptorCallback?) {
val path = postcard!!.path
val isLogin = true
//首先判断路径是否匹配 如果匹配上就需要跳转到登录
if (path == ConfigConstants.SECOND_PATH) {
if (isLogin) {
callback!!.onContinue(postcard)
} else {
//被拦击去到登录页面
ARouter.getInstance().build(ConfigConstants.LOGIN_PATH).navigation()
//callback.onInterrupt(null);
}
} else { //路径不匹配说明该模块不需要登录
callback!!.onContinue(postcard)
}
}
override fun init(context: Context?) {
Log.i("TAG", "init: 路由登录拦截器初始化成功");
}
}<file_sep>package com.bawei.s1dirsir.activity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.bawei.s1dirsir.adapter.FragmentAdapter;
import com.bawei.s1dirsir.fragment.MainFragment;
import com.bawei.s1dirsir.fragment.MessageFragment;
import com.bawei.s1dirsir.fragment.MyFragment;
import com.bawei.s1dirsir.fragment.ShopCarFragment;
import com.bawei.s1dirsir.inject.DaggerActivityComment;
import com.bawei.s1dirsir.presenter.FoodPersenter;
import com.bw.mvp.view.BaseActivty;
import com.bawei.s1dirsir.R;
import com.bawei.s1dirsir.bean.JsonBean;
import com.bawei.s1dirsir.contract.FoodContract;
import com.bawei.s1dirsir.fragment.ClassFragment;
import com.bawei.s1dirsir.inject.FoodModule;
import java.util.ArrayList;
public class MainActivity extends BaseActivty<FoodPersenter> implements FoodContract.FoodView,BottomNavigationBar.OnTabSelectedListener{
private ViewPager vp;
private BottomNavigationBar bar;
private final ArrayList<Fragment>list = new ArrayList<>();
@Override
public int bindLayout() {
return R.layout.activity_main;
}
@Override
public void initView() {
vp = (ViewPager) findViewById(R.id.vp);
bar = (BottomNavigationBar) findViewById(R.id.bar);
}
@Override
public void initData() {//DaggerActivityComment
DaggerActivityComment.builder().foodModule(new FoodModule(this)).build().inject(this);
p.initFood();
list.add(new MainFragment());
list.add(new ClassFragment());
list.add(new ShopCarFragment());
list.add(new MessageFragment());
list.add(new MyFragment());
FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), list);
vp.setAdapter(fragmentAdapter);
bar.setTabSelectedListener(this)
.setMode(BottomNavigationBar.MODE_FIXED)
.setActiveColor("#ff6600")
.setInActiveColor("#cccccc")
.setBarBackgroundColor("#ffffff");
bar.addItem(new BottomNavigationItem(R.drawable.image_main,"主页"))
.addItem(new BottomNavigationItem(R.drawable.image_class,"分类"))
.addItem(new BottomNavigationItem(R.drawable.image_shopcar,"购物车"))
.addItem(new BottomNavigationItem(R.drawable.image_message,"消息"))
.addItem(new BottomNavigationItem(R.drawable.image_my,"我的"))
.initialise();
vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
switch (position){
case 0:
bar.selectTab(0);
break;
case 1:
bar.selectTab(1);
break;
case 2:
bar.selectTab(2);
break;
case 3:
bar.selectTab(3);
break;
case 4:
bar.selectTab(4);
break;
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
@Override
public void showLoading() {
}
@Override
public void showFood(JsonBean jsonBean) {
// Toast.makeText(this, jsonBean.toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void onTabSelected(int position) {
vp.setCurrentItem(position);
}
@Override
public void onTabUnselected(int position) {
}
@Override
public void onTabReselected(int position) {
}
}<file_sep>package com.bawei.arouter
import android.util.Log
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.callback.NavigationCallback
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.arouter.constants.ConfigConstants
/*
* When I wrote this, only God and I understood what I was doing
* Now, God only knows
* 写这段代码的时候,只有上帝和我知道它是干嘛的
* 现在,只有上帝知道
* @ClassName LoginCallbackImpl
* @Description TODO
* @Author 海
* @Date 2021/9/16 8:10
* @Version 1.0
*/
class LoginNavigationCallbackImpl : NavigationCallback {
//找到了
override fun onFound(postcard: Postcard?) {}
//找不到
override fun onLost(postcard: Postcard?) {}
//跳转成功
override fun onArrival(postcard: Postcard?) {}
override fun onInterrupt(postcard: Postcard) {
val path = postcard.path
Log.i("TAG", "onInterrupt: $path")
val bundle = postcard.extras
// 被登录拦截了下来了
// 需要调转到登录页面,把参数跟被登录拦截下来的路径传递给登录页面,登录成功后再进行跳转被拦截的页面
ARouter.getInstance().build(ConfigConstants.LOGIN_PATH)
.with(bundle)
.withString(ConfigConstants.PATH, path)
.navigation()
}
}
|
24b837a6d5ba12cd5be334c125c88aa226a097ae
|
[
"Java",
"Kotlin",
"Gradle"
] | 26
|
Java
|
liangboold/S1DirSir
|
cc17c4ad9a840f5516face057489e94ba0e75d44
|
c661c8398d0feb8cf488cea7cfafa3b2a041bbe0
|
refs/heads/master
|
<repo_name>tulth/kinesis-teensy<file_sep>/firmware/test/src/kinesis_teensy_test.cpp
#include <stdbool.h>
#include <stdint.h>
#include <WProgram.h>
// #include <usb_dev.h>
// #include <usb_serial.h>
#include <core_pins.h>
extern "C" int main(void)
{
elapsedMillis blinkMilliSecElapsed;
// usb_init();
PORTC_PCR5 |= PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1); /* LED */
GPIOC_PDDR |= (1<<5); /* gpio data direction reg, for led bit */
blinkMilliSecElapsed = 0;
while (1) {
if (blinkMilliSecElapsed > 100) {
GPIOC_PTOR = (1<<5); // gpio toggle reg, for led bit
blinkMilliSecElapsed = 0;
}
yield();
}
}
// // int __assert_func(const char *fn, long line)
// void __assert(const char *, int, const char *)
// {
// usb_serial_write("assert fail! halting!\n", 21);
// while (1) { ; }
// }
<file_sep>/firmware/test/program.sh
#!/bin/bash
set -e
#teensy-loader-cli --mcu=mk20dx256 -v -s -w $@
teensy-loader-cli --mcu=mk20dx256 -v -s -w ./build/kinesis_teensy_test.hex
|
0acf30a9cf146955b4057e1ebf1cd09390cd3aa9
|
[
"C++",
"Shell"
] | 2
|
C++
|
tulth/kinesis-teensy
|
bf4f2f9534b956fe4c8ccc39bc961e08e81d0ac5
|
400a5f11373a06555a4ae1b0f87d09d15762657d
|
refs/heads/master
|
<file_sep>// Package azcertcache implements an autocert.Cache to store certificate data within an Azure Blob Storage container
//
// See https://godoc.org/golang.org/x/crypto/acme/autocert
package azcertcache
import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/Azure/azure-storage-blob-go/azblob"
"golang.org/x/crypto/acme/autocert"
)
func isNotFound(err error) bool {
if err != nil {
if azError, ok := err.(azblob.ResponseError); ok {
return azError.Response().StatusCode == http.StatusNotFound
}
}
return false
}
// ErrEmptyContainerName is returned when given container name is empty
var ErrEmptyContainerName = errors.New("containerName must not be empty")
// Making sure that we're adhering to the autocert.Cache interface.
var _ autocert.Cache = (*Cache)(nil)
// Cache provides an Azure Blob Storage backend to the autocert cache.
type Cache struct {
containerURL azblob.ContainerURL
}
// New creates an cache instance that can be used with autocert.Cache.
// It returns any errors that could happen while connecting to Azure Blob Storage.
func New(accountName, accountKey, containerName string) (*Cache, error) {
return NewWithEndpoint(accountName, accountKey, containerName, fmt.Sprintf("https://%s.blob.core.windows.net", accountName))
}
// NewWithEndpoint creates an cache instance that can be used with autocert.Cache.
// Endpoint can be used to target a different environment that is not Azure
// It returns any errors that could happen while connecting to Azure Blob Storage.
func NewWithEndpoint(accountName, accountKey, containerName, endpointURL string) (*Cache, error) {
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
return nil, err
}
if strings.TrimSpace(containerName) == "" {
return nil, ErrEmptyContainerName
}
pipeline := azblob.NewPipeline(credential, azblob.PipelineOptions{})
endpoint, _ := url.Parse(endpointURL)
serviceURL := azblob.NewServiceURL(*endpoint, pipeline)
containerURL := serviceURL.NewContainerURL(containerName)
// Use GetAccountInfo to contact Azure endpoint and check the credential
// Returns "AuthenticationFailed" if credential is bad
_, err = containerURL.GetAccountInfo(context.Background())
if err != nil {
return nil, err
}
return &Cache{
containerURL: containerURL,
}, nil
}
// DeleteContainer based on current configured container
func (c *Cache) DeleteContainer(ctx context.Context) error {
_, err := c.containerURL.Delete(ctx, azblob.ContainerAccessConditions{})
if isNotFound(err) {
return nil
}
return err
}
// CreateContainer based on current configured container
func (c *Cache) CreateContainer(ctx context.Context) error {
_, err := c.containerURL.Create(ctx, azblob.Metadata{}, azblob.PublicAccessNone)
return err
}
// Get returns a certificate data for the specified key.
// If there's no such key, Get returns ErrCacheMiss.
func (c *Cache) Get(ctx context.Context, key string) ([]byte, error) {
blobURL := c.containerURL.NewBlockBlobURL(key)
get, err := blobURL.Download(ctx, 0, 0, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
if isNotFound(err) {
return nil, autocert.ErrCacheMiss
}
if err != nil {
return nil, err
}
reader := get.Body(azblob.RetryReaderOptions{})
defer reader.Close()
data := &bytes.Buffer{}
data.ReadFrom(reader)
return data.Bytes(), nil
}
// Put stores the data in the cache under the specified key.
func (c *Cache) Put(ctx context.Context, key string, data []byte) error {
blobURL := c.containerURL.NewBlockBlobURL(key)
_, err := blobURL.Upload(
ctx, bytes.NewReader(data),
azblob.BlobHTTPHeaders{
ContentType: "application/x-pem-file",
},
azblob.Metadata{},
azblob.BlobAccessConditions{},
azblob.DefaultAccessTier,
nil, // blobTagsMap
azblob.ClientProvidedKeyOptions{},
azblob.ImmutabilityPolicyOptions{},
)
return err
}
// Delete removes a certificate data from the cache under the specified key.
// If there's no such key in the cache, Delete returns nil.
func (c *Cache) Delete(ctx context.Context, key string) error {
blobURL := c.containerURL.NewBlockBlobURL(key)
_, err := blobURL.Delete(ctx, azblob.DeleteSnapshotsOptionNone, azblob.BlobAccessConditions{})
if isNotFound(err) {
return nil
}
return err
}
<file_sep>[](https://godoc.org/github.com/goenning/azcertcache) [](https://goreportcard.com/report/github.com/goenning/azcertcache)
# azcertcache
[Azure Blob Storage](https://azure.microsoft.com/en-us/services/storage/blobs/) cache for [acme/autocert](https://godoc.org/golang.org/x/crypto/acme/autocert) written in Go.
## Example
```go
containerName := "autocertcache"
cache, err := azcertcache.New("<account name>", "<account key>", containerName)
if err != nil {
// Handle error
}
m := autocert.Manager{
Prompt: autocert.AcceptTOS,
Cache: cache,
}
s := &http.Server{
Addr: ":https",
TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},
}
s.ListenAndServeTLS("", "")
```
## Performance
This is just a reminder that autocert has an internal in-memory cache that is used before quering this long-term cache.
So you don't need to worry about your Azure Blob Storage instance being hit many times just to get the same certificate. It should only do once per process+key.
## Thanks
Inspired by https://github.com/danilobuerger/autocert-s3-cache
## License
MIT<file_sep>module github.com/goenning/azcertcache
go 1.15
require (
github.com/Azure/azure-storage-blob-go v0.15.0
github.com/stretchr/testify v1.7.2
golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e
)
require (
github.com/google/uuid v1.3.0 // indirect
github.com/mattn/go-ieproxy v0.0.6 // indirect
golang.org/x/net v0.0.0-20220607020251-c690dde0001d // indirect
)
<file_sep>package azcertcache_test
import (
"context"
"fmt"
"io/ioutil"
"strings"
"testing"
"github.com/Azure/azure-storage-blob-go/azblob"
"github.com/stretchr/testify/assert"
"golang.org/x/crypto/acme/autocert"
"github.com/goenning/azcertcache"
)
// NOTE: replace account name and key with your own Azure storage credential
const accountName = "devstoreaccount1"
const accountKey = "<KEY>
// Bad account key encoded in base64 that would fail the authentication check
const badAccountKey = "<KEY> // base64: "badcredential"
func newCache(t *testing.T, containerPrefix string, accountKey string) (*azcertcache.Cache, error) {
// Append test name after the container prefix to make them different.
// This avoids "ContainerBeingDeleted" error when creating new containers
// in different unit tests.
containerName := fmt.Sprintf("%s-%s", containerPrefix, t.Name())
// Sanitize: container names must only contain lower case, numbers, or hyphens
containerName = strings.ToLower(containerName)
containerName = strings.Replace(containerName, "_", "", -1)
endpointURL := fmt.Sprintf("https://%s.blob.core.windows.net", accountName)
cache, err := azcertcache.NewWithEndpoint(accountName, accountKey, containerName, endpointURL)
if err != nil {
// Failed to create new blob storage endpoint. Return the error
return nil, err
}
err = cache.CreateContainer(context.Background())
assert.Nil(t, err)
t.Cleanup(func() {
err = cache.DeleteContainer(context.Background())
assert.Nil(t, err)
})
return cache, nil
}
func TestNew(t *testing.T) {
cache, err := newCache(t, "testcontainer", accountKey)
assert.NotNil(t, cache)
assert.Nil(t, err)
}
func TestNew_BadCredential(t *testing.T) {
// Sanity check that badAccountKey isn't the same as the actual key
assert.NotEqual(t, accountKey, badAccountKey)
cache, err := newCache(t, "testcontainer", badAccountKey)
assert.Nil(t, cache)
assert.NotNil(t, err)
stgErr, _ := err.(azblob.StorageError)
assert.Equal(t, stgErr.ServiceCode(), azblob.ServiceCodeAuthenticationFailed)
}
func TestGet_UnkownKey(t *testing.T) {
cache, _ := newCache(t, "testcontainer", accountKey)
assert.NotNil(t, cache)
data, err := cache.Get(context.Background(), "my-key")
assert.Equal(t, err, autocert.ErrCacheMiss)
assert.Equal(t, len(data), 0)
}
func TestGet_AfterPut(t *testing.T) {
cache, _ := newCache(t, "testcontainer", accountKey)
assert.NotNil(t, cache)
actual, _ := ioutil.ReadFile("./LICENSE")
err := cache.Put(context.Background(), "my-key", actual)
assert.Nil(t, err)
data, err := cache.Get(context.Background(), "my-key")
assert.Nil(t, err)
assert.Equal(t, data, actual)
}
func TestGet_AfterDelete(t *testing.T) {
cache, _ := newCache(t, "testcontainer", accountKey)
assert.NotNil(t, cache)
actual := []byte{1, 2, 3, 4}
err := cache.Put(context.Background(), "my-key", actual)
assert.Nil(t, err)
err = cache.Delete(context.Background(), "my-key")
assert.Nil(t, err)
data, err := cache.Get(context.Background(), "my-key")
assert.Equal(t, err, autocert.ErrCacheMiss)
assert.Equal(t, len(data), 0)
}
func TestDelete_UnkownKey(t *testing.T) {
cache, _ := newCache(t, "testcontainer", accountKey)
assert.NotNil(t, cache)
var err error
err = cache.Delete(context.Background(), "my-key1")
assert.Nil(t, err)
err = cache.Delete(context.Background(), "other-key")
assert.Nil(t, err)
err = cache.Delete(context.Background(), "hello-world")
assert.Nil(t, err)
}
func TestPut_Overwrite(t *testing.T) {
cache, _ := newCache(t, "testcontainer", accountKey)
assert.NotNil(t, cache)
data1 := []byte{1, 2, 3, 4}
err := cache.Put(context.Background(), "thekey", data1)
assert.Nil(t, err)
data, _ := cache.Get(context.Background(), "thekey")
assert.Equal(t, data, data1)
data2 := []byte{5, 6, 7, 8}
err = cache.Put(context.Background(), "thekey", data2)
assert.Nil(t, err)
data, _ = cache.Get(context.Background(), "thekey")
assert.Equal(t, data, data2)
}
func TestDifferentContainer(t *testing.T) {
cache1, _ := newCache(t, "testcontainer1", accountKey)
cache2, _ := newCache(t, "testcontainer2", accountKey)
input := []byte{1, 2, 3, 4}
err := cache1.Put(context.Background(), "thekey.txt", input)
assert.Nil(t, err)
data, err := cache1.Get(context.Background(), "thekey.txt")
assert.Equal(t, data, input)
assert.Nil(t, err)
data, err = cache2.Get(context.Background(), "thekey.txt")
assert.Equal(t, len(data), 0)
assert.Equal(t, err, autocert.ErrCacheMiss)
}
func TestGet_CancelledContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
cache, _ := newCache(t, "testcontainer", accountKey)
assert.NotNil(t, cache)
data, err := cache.Get(ctx, "my-key")
assert.NotNil(t, err)
assert.Equal(t, len(data), 0)
}
|
90b28e8efe72121eca814a096221fb92c08e859c
|
[
"Markdown",
"Go Module",
"Go"
] | 4
|
Go
|
goenning/azcertcache
|
7020cbfca7c7626cf13b5e53fe2a5cca35eb067e
|
579c67fe21d59afe580e2e2bc11a013e0eda9b1f
|
refs/heads/master
|
<repo_name>viljaste/push2gitlab<file_sep>/push2gitlab.sh
#!/usr/bin/env bash
WORKING_DIR="$(pwd)"
hash git 2> /dev/null
if [ "${?}" -ne 0 ]; then
echo "push2gitlab: git command not found."
exit 1
fi
hash jq 2> /dev/null
if [ "${?}" -ne 0 ]; then
echo "push2gitlab: jq command not found."
exit 1
fi
help() {
cat << EOF
push2gitlab: Usage: push2gitlab [SOURCE] <GITLAB_URL> <NAMESPACE> <PROJECT_NAME> <TOKEN>
EOF
exit 1
}
if [ "${1}" == "-h" ] || [ "${1}" == "--help" ]; then
help
fi
unknown_command() {
echo "push2gitlab: Unknown command. See 'push2gitlab --help'"
exit 1
}
if [ "${#}" -lt 4 ] || [ "${#}" -gt 5 ]; then
unknown_command
fi
SOURCE="${WORKING_DIR}"
if [ "${#}" -gt 4 ]; then
SOURCE="${1}"
fi
if [ ! -d "${SOURCE}" ]; then
echo "push2gitlab: Source directory doesn't exist: ${SOURCE}"
exit 1
fi
cd "${SOURCE}"
git status > /dev/null 2>&1
if [ "${?}" -ne 0 ]; then
echo "push2gitlab: Invalid repository."
exit 1
fi
GITLAB_URL="${1}"
NAMESPACE="${2}"
PROJECT_NAME="${3}"
TOKEN="${4}"
if [ "${#}" -gt 4 ]; then
GITLAB_URL="${2}"
NAMESPACE="${3}"
PROJECT_NAME="${4}"
TOKEN="${5}"
fi
NAMESPACES_URL="${GITLAB_URL}/api/v3/groups?private_token=${TOKEN}"
PROJECTS_URL="${GITLAB_URL}/api/v3/projects?private_token=${TOKEN}"
PROJECTS_ALL_URL="${GITLAB_URL}/api/v3/projects?private_token=${TOKEN}&page=1&per_page=100"
NAMESPACES=$(curl -skX GET -H 'Content-Type: application/json' "${NAMESPACES_URL}")
if [ -z "${NAMESPACES}" ]; then
echo "push2gitlab: Namespaces not found."
exit 1
fi
NAMESPACE_ID=$(echo "${NAMESPACES}" | jq ".[] | select(.name == \"${NAMESPACE}\")" | jq '.id')
if [ -z "${NAMESPACE_ID}" ]; then
echo "push2gitlab: Namespace not found: ${NAMESPACE}"
exit 1
fi
RPOJECT_EXISTS=$(curl -skX GET -H 'Content-Type: application/json' "${PROJECTS_ALL_URL}" | jq ".[] | select(.namespace.id == ${NAMESPACE_ID} and .name == \"${PROJECT_NAME}\")")
if [ -n "${RPOJECT_EXISTS}" ]; then
echo "push2gitlab: Project ${PROJECT_NAME} already exists in ${NAMESPACE} namespace."
exit 1
fi
REMOTE_URL=$(curl -skX POST -H 'Content-Type: application/json' "${PROJECTS_URL}" -d "{ \"name\": \"${PROJECT_NAME}\", \"namespace_id\": \"${NAMESPACE_ID}\" }" | jq '.ssh_url_to_repo' | sed 's/^"//' | sed 's/"$//')
git push --mirror "${REMOTE_URL}"
cd "${WORKING_DIR}"
<file_sep>/README.md
# push2gitlab
Pushes Git repository to Gitlab.
## Usage
push2gitlab [SOURCE] <GITLAB_URL> <NAMESPACE> <PROJECT_NAME> <TOKEN>
## Install
TMP="$(mktemp -d)" \
&& git clone http://git.simpledrupalcloud.com/simpledrupalcloud/push2gitlab.git "${TMP}" \
&& sudo cp "${TMP}/push2gitlab.sh" /usr/local/bin/push2gitlab \
&& sudo chmod +x /usr/local/bin/push2gitlab
## License
**MIT**
|
ab523c779905af608f5b43a85da125f9802e74d3
|
[
"Markdown",
"Shell"
] | 2
|
Shell
|
viljaste/push2gitlab
|
1f3bc620d6d66da0fcc6c5d9ff763cc2ee51cff7
|
2f2cd919e304e4e4fb30d21c655af033b30571b3
|
refs/heads/master
|
<repo_name>himani2100/LexAndCup<file_sep>/A4Parser.java
//----------------------------------------------------
// The following code was generated by CUP v0.10k
// Tue Mar 12 14:37:46 EDT 2019
//----------------------------------------------------
/** CUP v0.10k generated parser.
* @version Tue Mar 12 14:37:46 EDT 2019
*/
public class A4Parser extends java_cup.runtime.lr_parser {
/** Default constructor. */
public A4Parser() {super();}
/** Constructor which sets the default scanner. */
public A4Parser(java_cup.runtime.Scanner s) {super(s);}
/** Production table. */
protected static final short _production_table[][] =
unpackFromStrings(new String[] {
"\000\067\000\002\035\003\000\002\002\004\000\002\003" +
"\004\000\002\034\003\000\002\034\003\000\002\034\003" +
"\000\002\004\004\000\002\004\002\000\002\005\011\000" +
"\002\005\010\000\002\006\004\000\002\006\002\000\002" +
"\010\005\000\002\010\002\000\002\007\004\000\002\013" +
"\006\000\002\032\004\000\002\032\002\000\002\016\003" +
"\000\002\016\003\000\002\016\003\000\002\016\003\000" +
"\002\016\003\000\002\016\003\000\002\014\005\000\002" +
"\014\004\000\002\015\006\000\002\015\006\000\002\017" +
"\005\000\002\033\003\000\002\033\003\000\002\012\011" +
"\000\002\012\003\000\002\011\007\000\002\011\011\000" +
"\002\020\011\000\002\021\011\000\002\023\004\000\002" +
"\022\005\000\002\022\005\000\002\022\002\000\002\024" +
"\004\000\002\025\005\000\002\025\005\000\002\025\002" +
"\000\002\031\003\000\002\031\003\000\002\031\005\000" +
"\002\031\006\000\002\026\005\000\002\026\005\000\002" +
"\027\004\000\002\027\002\000\002\030\005\000\002\030" +
"\002" });
/** Access to production table. */
public short[][] production_table() {return _production_table;}
/** Parse-action table. */
protected static final short[][] _action_table =
unpackFromStrings(new String[] {
"\000\163\000\010\032\012\033\010\034\006\001\002\000" +
"\004\002\001\001\002\000\004\002\165\001\002\000\006" +
"\010\ufffc\015\ufffc\001\002\000\006\010\017\015\016\001" +
"\002\000\006\010\ufffd\015\ufffd\001\002\000\012\002\ufffa" +
"\032\012\033\010\034\006\001\002\000\006\010\ufffe\015" +
"\ufffe\001\002\000\012\002\ufffa\032\012\033\010\034\006" +
"\001\002\000\004\002\uffff\001\002\000\004\002\ufffb\001" +
"\002\000\004\017\161\001\002\000\004\015\020\001\002" +
"\000\004\017\021\001\002\000\012\020\ufff6\032\012\033" +
"\010\034\006\001\002\000\004\015\160\001\002\000\006" +
"\020\ufff4\022\154\001\002\000\004\020\025\001\002\000" +
"\004\014\027\001\002\000\012\002\ufff9\032\ufff9\033\ufff9" +
"\034\ufff9\001\002\000\024\005\037\006\035\007\031\011" +
"\036\014\027\015\040\032\012\033\010\034\006\001\002" +
"\000\030\005\uffec\006\uffec\007\uffec\011\uffec\012\uffec\013" +
"\uffec\014\uffec\015\uffec\032\uffec\033\uffec\034\uffec\001\002" +
"\000\004\017\146\001\002\000\030\005\uffee\006\uffee\007" +
"\uffee\011\uffee\012\uffee\013\uffee\014\uffee\015\uffee\032\uffee" +
"\033\uffee\034\uffee\001\002\000\030\005\uffea\006\uffea\007" +
"\uffea\011\uffea\012\uffea\013\uffea\014\uffea\015\uffea\032\uffea" +
"\033\uffea\034\uffea\001\002\000\030\005\uffed\006\uffed\007" +
"\uffed\011\uffed\012\uffed\013\uffed\014\uffed\015\uffed\032\uffed" +
"\033\uffed\034\uffed\001\002\000\010\015\060\016\063\017" +
"\066\001\002\000\004\017\127\001\002\000\004\017\121" +
"\001\002\000\004\031\057\001\002\000\004\015\054\001" +
"\002\000\030\005\uffe1\006\uffe1\007\uffe1\011\uffe1\012\uffe1" +
"\013\uffe1\014\uffe1\015\uffe1\032\uffe1\033\uffe1\034\uffe1\001" +
"\002\000\026\005\037\006\035\007\031\011\036\013\ufff0" +
"\014\027\015\040\032\012\033\010\034\006\001\002\000" +
"\030\005\uffef\006\uffef\007\uffef\011\uffef\012\uffef\013\uffef" +
"\014\uffef\015\uffef\032\uffef\033\uffef\034\uffef\001\002\000" +
"\030\005\uffeb\006\uffeb\007\uffeb\011\uffeb\012\uffeb\013\uffeb" +
"\014\uffeb\015\uffeb\032\uffeb\033\uffeb\034\uffeb\001\002\000" +
"\026\005\uffe3\006\uffe3\007\uffe3\011\uffe3\013\uffe3\014\uffe3" +
"\015\uffe3\032\uffe3\033\uffe3\034\uffe3\001\002\000\026\005" +
"\uffe4\006\uffe4\007\uffe4\011\uffe4\013\uffe4\014\uffe4\015\uffe4" +
"\032\uffe4\033\uffe4\034\uffe4\001\002\000\026\005\037\006" +
"\035\007\031\011\036\013\ufff0\014\027\015\040\032\012" +
"\033\010\034\006\001\002\000\004\013\052\001\002\000" +
"\032\002\ufff2\005\ufff2\006\ufff2\007\ufff2\011\ufff2\012\ufff2" +
"\013\ufff2\014\ufff2\015\ufff2\032\ufff2\033\ufff2\034\ufff2\001" +
"\002\000\004\013\ufff1\001\002\000\006\021\056\031\057" +
"\001\002\000\030\005\uffe8\006\uffe8\007\uffe8\011\uffe8\012" +
"\uffe8\013\uffe8\014\uffe8\015\uffe8\032\uffe8\033\uffe8\034\uffe8" +
"\001\002\000\030\005\uffe9\006\uffe9\007\uffe9\011\uffe9\012" +
"\uffe9\013\uffe9\014\uffe9\015\uffe9\032\uffe9\033\uffe9\034\uffe9" +
"\001\002\000\012\004\062\015\060\016\063\017\066\001" +
"\002\000\026\017\111\020\uffd3\021\uffd3\022\uffd3\023\uffd3" +
"\024\uffd3\025\uffd3\026\uffd3\027\uffd3\030\uffd3\001\002\000" +
"\020\020\uffd9\021\uffd9\022\uffd9\023\103\024\104\027\uffd9" +
"\030\uffd9\001\002\000\004\021\101\001\002\000\024\020" +
"\uffd4\021\uffd4\022\uffd4\023\uffd4\024\uffd4\025\uffd4\026\uffd4" +
"\027\uffd4\030\uffd4\001\002\000\004\021\100\001\002\000" +
"\024\020\uffd5\021\uffd5\022\uffd5\023\uffd5\024\uffd5\025\073" +
"\026\071\027\uffd5\030\uffd5\001\002\000\010\015\060\016" +
"\063\017\066\001\002\000\004\020\070\001\002\000\024" +
"\020\uffd2\021\uffd2\022\uffd2\023\uffd2\024\uffd2\025\uffd2\026" +
"\uffd2\027\uffd2\030\uffd2\001\002\000\010\015\060\016\063" +
"\017\066\001\002\000\020\020\uffd8\021\uffd8\022\uffd8\023" +
"\uffd8\024\uffd8\027\uffd8\030\uffd8\001\002\000\010\015\060" +
"\016\063\017\066\001\002\000\024\020\uffd5\021\uffd5\022" +
"\uffd5\023\uffd5\024\uffd5\025\073\026\071\027\uffd5\030\uffd5" +
"\001\002\000\020\020\uffd6\021\uffd6\022\uffd6\023\uffd6\024" +
"\uffd6\027\uffd6\030\uffd6\001\002\000\024\020\uffd5\021\uffd5" +
"\022\uffd5\023\uffd5\024\uffd5\025\073\026\071\027\uffd5\030" +
"\uffd5\001\002\000\020\020\uffd7\021\uffd7\022\uffd7\023\uffd7" +
"\024\uffd7\027\uffd7\030\uffd7\001\002\000\030\005\uffe7\006" +
"\uffe7\007\uffe7\011\uffe7\012\uffe7\013\uffe7\014\uffe7\015\uffe7" +
"\032\uffe7\033\uffe7\034\uffe7\001\002\000\030\005\uffe6\006" +
"\uffe6\007\uffe6\011\uffe6\012\uffe6\013\uffe6\014\uffe6\015\uffe6" +
"\032\uffe6\033\uffe6\034\uffe6\001\002\000\014\020\uffdc\021" +
"\uffdc\022\uffdc\027\uffdc\030\uffdc\001\002\000\010\015\060" +
"\016\063\017\066\001\002\000\010\015\060\016\063\017" +
"\066\001\002\000\020\020\uffd9\021\uffd9\022\uffd9\023\103" +
"\024\104\027\uffd9\030\uffd9\001\002\000\014\020\uffdb\021" +
"\uffdb\022\uffdb\027\uffdb\030\uffdb\001\002\000\020\020\uffd9" +
"\021\uffd9\022\uffd9\023\103\024\104\027\uffd9\030\uffd9\001" +
"\002\000\014\020\uffda\021\uffda\022\uffda\027\uffda\030\uffda" +
"\001\002\000\012\015\060\016\063\017\066\020\uffcd\001" +
"\002\000\006\020\uffcb\022\115\001\002\000\004\020\114" +
"\001\002\000\024\020\uffd1\021\uffd1\022\uffd1\023\uffd1\024" +
"\uffd1\025\uffd1\026\uffd1\027\uffd1\030\uffd1\001\002\000\010" +
"\015\060\016\063\017\066\001\002\000\004\020\uffce\001" +
"\002\000\006\020\uffcb\022\115\001\002\000\004\020\uffcc" +
"\001\002\000\010\015\060\016\063\017\066\001\002\000" +
"\004\022\123\001\002\000\004\004\124\001\002\000\004" +
"\020\125\001\002\000\004\021\126\001\002\000\030\005" +
"\uffde\006\uffde\007\uffde\011\uffde\012\uffde\013\uffde\014\uffde" +
"\015\uffde\032\uffde\033\uffde\034\uffde\001\002\000\010\015" +
"\060\016\063\017\066\001\002\000\006\027\141\030\140" +
"\001\002\000\004\020\132\001\002\000\024\005\037\006" +
"\035\007\031\011\036\014\027\015\040\032\012\033\010" +
"\034\006\001\002\000\026\005\uffe0\006\uffe0\007\uffe0\011" +
"\uffe0\013\uffe0\014\uffe0\015\uffe0\032\uffe0\033\uffe0\034\uffe0" +
"\001\002\000\030\005\uffe4\006\uffe4\007\uffe4\011\uffe4\012" +
"\135\013\uffe4\014\uffe4\015\uffe4\032\uffe4\033\uffe4\034\uffe4" +
"\001\002\000\024\005\037\006\035\007\031\011\036\014" +
"\027\015\040\032\012\033\010\034\006\001\002\000\026" +
"\005\uffdf\006\uffdf\007\uffdf\011\uffdf\013\uffdf\014\uffdf\015" +
"\uffdf\032\uffdf\033\uffdf\034\uffdf\001\002\000\030\005\uffe2" +
"\006\uffe2\007\uffe2\011\uffe2\012\uffe2\013\uffe2\014\uffe2\015" +
"\uffe2\032\uffe2\033\uffe2\034\uffe2\001\002\000\010\015\060" +
"\016\063\017\066\001\002\000\010\015\060\016\063\017" +
"\066\001\002\000\004\020\uffcf\001\002\000\004\020\uffd0" +
"\001\002\000\004\021\145\001\002\000\030\005\uffe5\006" +
"\uffe5\007\uffe5\011\uffe5\012\uffe5\013\uffe5\014\uffe5\015\uffe5" +
"\032\uffe5\033\uffe5\034\uffe5\001\002\000\004\015\147\001" +
"\002\000\004\022\150\001\002\000\004\004\151\001\002" +
"\000\004\020\152\001\002\000\004\021\153\001\002\000" +
"\030\005\uffdd\006\uffdd\007\uffdd\011\uffdd\012\uffdd\013\uffdd" +
"\014\uffdd\015\uffdd\032\uffdd\033\uffdd\034\uffdd\001\002\000" +
"\010\032\012\033\010\034\006\001\002\000\004\020\ufff7" +
"\001\002\000\006\020\ufff4\022\154\001\002\000\004\020" +
"\ufff5\001\002\000\006\020\ufff3\022\ufff3\001\002\000\012" +
"\020\ufff6\032\012\033\010\034\006\001\002\000\004\020" +
"\163\001\002\000\004\014\027\001\002\000\012\002\ufff8" +
"\032\ufff8\033\ufff8\034\ufff8\001\002\000\004\002\000\001" +
"\002" });
/** Access to parse-action table. */
public short[][] action_table() {return _action_table;}
/** <code>reduce_goto</code> table. */
protected static final short[][] _reduce_table =
unpackFromStrings(new String[] {
"\000\163\000\012\003\003\005\010\034\006\035\004\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\002\001\001\000\002\001\001\000\010\004\013\005" +
"\012\034\006\001\001\000\002\001\001\000\010\004\014" +
"\005\012\034\006\001\001\000\002\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\010\006\023\007\022\034\021\001\001\000\002\001" +
"\001\000\004\010\154\001\001\000\002\001\001\000\004" +
"\013\025\001\001\000\002\001\001\000\030\011\045\012" +
"\046\013\043\014\031\015\033\016\041\017\027\020\044" +
"\021\032\033\042\034\040\001\001\000\002\001\001\000" +
"\002\001\001\000\002\001\001\000\002\001\001\000\002" +
"\001\001\000\010\023\143\024\060\031\064\001\001\000" +
"\002\001\001\000\002\001\001\000\002\001\001\000\004" +
"\015\054\001\001\000\002\001\001\000\032\011\045\012" +
"\046\013\043\014\031\015\033\016\041\017\027\020\044" +
"\021\032\032\050\033\047\034\040\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\032\011\045\012\046\013\043\014\031\015\033\016" +
"\041\017\027\020\044\021\032\032\052\033\047\034\040" +
"\001\001\000\002\001\001\000\002\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\010\023\063\024\060\031\064\001\001\000\002\001" +
"\001\000\004\022\101\001\001\000\002\001\001\000\002" +
"\001\001\000\002\001\001\000\004\025\071\001\001\000" +
"\010\023\066\024\060\031\064\001\001\000\002\001\001" +
"\000\002\001\001\000\004\031\075\001\001\000\002\001" +
"\001\000\004\031\073\001\001\000\004\025\074\001\001" +
"\000\002\001\001\000\004\025\076\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\006\024\106\031\064\001\001\000\006\024\104\031" +
"\064\001\001\000\004\022\105\001\001\000\002\001\001" +
"\000\004\022\107\001\001\000\002\001\001\000\012\023" +
"\111\024\060\027\112\031\064\001\001\000\004\030\115" +
"\001\001\000\002\001\001\000\002\001\001\000\010\023" +
"\116\024\060\031\064\001\001\000\002\001\001\000\004" +
"\030\117\001\001\000\002\001\001\000\010\023\121\024" +
"\060\031\064\001\001\000\002\001\001\000\002\001\001" +
"\000\002\001\001\000\002\001\001\000\002\001\001\000" +
"\012\023\127\024\060\026\130\031\064\001\001\000\002" +
"\001\001\000\002\001\001\000\030\011\045\012\133\013" +
"\043\014\031\015\033\016\041\017\027\020\044\021\032" +
"\033\132\034\040\001\001\000\002\001\001\000\002\001" +
"\001\000\026\011\135\012\136\013\043\014\031\015\033" +
"\016\041\017\027\020\044\021\032\034\040\001\001\000" +
"\002\001\001\000\002\001\001\000\010\023\142\024\060" +
"\031\064\001\001\000\010\023\141\024\060\031\064\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\002\001\001\000\002\001\001\000\002\001\001\000" +
"\002\001\001\000\002\001\001\000\002\001\001\000\002" +
"\001\001\000\006\007\155\034\021\001\001\000\002\001" +
"\001\000\004\010\156\001\001\000\002\001\001\000\002" +
"\001\001\000\010\006\161\007\022\034\021\001\001\000" +
"\002\001\001\000\004\013\163\001\001\000\002\001\001" +
"\000\002\001\001" });
/** Access to <code>reduce_goto</code> table. */
public short[][] reduce_table() {return _reduce_table;}
/** Instance of action encapsulation class. */
protected CUP$A4Parser$actions action_obj;
/** Action encapsulation object initializer. */
protected void init_actions()
{
action_obj = new CUP$A4Parser$actions(this);
}
/** Invoke a user supplied parse action. */
public java_cup.runtime.Symbol do_action(
int act_num,
java_cup.runtime.lr_parser parser,
java.util.Stack stack,
int top)
throws java.lang.Exception
{
/* call code in generated class */
return action_obj.CUP$A4Parser$do_action(act_num, parser, stack, top);
}
/** Indicates start state. */
public int start_state() {return 0;}
/** Indicates start production. */
public int start_production() {return 1;}
/** <code>EOF</code> Symbol index. */
public int EOF_sym() {return 0;}
/** <code>error</code> Symbol index. */
public int error_sym() {return 1;}
}
/** Cup generated class to encapsulate user supplied action code.*/
class CUP$A4Parser$actions {
private final A4Parser parser;
/** Constructor */
CUP$A4Parser$actions(A4Parser parser) {
this.parser = parser;
}
/** Method with the actual generated action code. */
public final java_cup.runtime.Symbol CUP$A4Parser$do_action(
int CUP$A4Parser$act_num,
java_cup.runtime.lr_parser CUP$A4Parser$parser,
java.util.Stack CUP$A4Parser$stack,
int CUP$A4Parser$top)
throws java.lang.Exception
{
/* Symbol object for return from actions */
java_cup.runtime.Symbol CUP$A4Parser$result;
/* select the action based on the action number */
switch (CUP$A4Parser$act_num)
{
/*. . . . . . . . . . . . . . . . . . . .*/
case 54: // ActualParam ::=
{
String RESULT = null;
RESULT="";
CUP$A4Parser$result = new java_cup.runtime.Symbol(22/*ActualParam*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 53: // ActualParam ::= COMMA Expr ActualParam
{
String RESULT = null;
int exleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int exright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String ex = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int apleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int apright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String ap = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = ", " + ex + ap;
CUP$A4Parser$result = new java_cup.runtime.Symbol(22/*ActualParam*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 52: // ActualParams ::=
{
String RESULT = null;
RESULT="";
CUP$A4Parser$result = new java_cup.runtime.Symbol(21/*ActualParams*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 51: // ActualParams ::= Expr ActualParam
{
String RESULT = null;
int exleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int exright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String ex = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int apleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int apright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String ap = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = ex + ap + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(21/*ActualParams*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 50: // BoolExpr ::= Expr NOTEQUAL Expr
{
String RESULT = null;
int exleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left;
int exright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).right;
String ex = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).value;
int ex2left = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int ex2right = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String ex2 = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = ex +" != " + ex2;
CUP$A4Parser$result = new java_cup.runtime.Symbol(20/*BoolExpr*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 49: // BoolExpr ::= Expr EQUAL Expr
{
String RESULT = null;
int exleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left;
int exright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).right;
String ex = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).value;
int ex2left = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int ex2right = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String ex2 = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = ex +" == " + ex2;
CUP$A4Parser$result = new java_cup.runtime.Symbol(20/*BoolExpr*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 48: // PrimaryExpr ::= ID LEBRAC ActualParams RIGBRAC
{
String RESULT = null;
int ileft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-3)).left;
int iright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-3)).right;
Object i = (Object)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-3)).value;
int apleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int apright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String ap = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
RESULT = i+"(" +ap +")";
CUP$A4Parser$result = new java_cup.runtime.Symbol(23/*PrimaryExpr*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-3)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 47: // PrimaryExpr ::= LEBRAC Expr RIGBRAC
{
String RESULT = null;
int exleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int exright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String ex = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
RESULT = "("+ ex +")";
CUP$A4Parser$result = new java_cup.runtime.Symbol(23/*PrimaryExpr*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 46: // PrimaryExpr ::= ID
{
String RESULT = null;
int ileft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int iright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
Object i = (Object)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = i + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(23/*PrimaryExpr*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 45: // PrimaryExpr ::= NUMBER
{
String RESULT = null;
int nleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int nright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
Object n = (Object)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = n + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(23/*PrimaryExpr*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 44: // MultiExprOps ::=
{
String RESULT = null;
RESULT="";
CUP$A4Parser$result = new java_cup.runtime.Symbol(19/*MultiExprOps*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 43: // MultiExprOps ::= DIVIDE PrimaryExpr MultiExprOps
{
String RESULT = null;
int peleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int peright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String pe = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int meoleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int meoright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String meo = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = "/" + pe + meo;
CUP$A4Parser$result = new java_cup.runtime.Symbol(19/*MultiExprOps*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 42: // MultiExprOps ::= MULT PrimaryExpr MultiExprOps
{
String RESULT = null;
int peleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int peright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String pe = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int meoleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int meoright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String meo = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = "*" + pe + meo;
CUP$A4Parser$result = new java_cup.runtime.Symbol(19/*MultiExprOps*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 41: // MultiExpr ::= PrimaryExpr MultiExprOps
{
String RESULT = null;
int peleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int peright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String pe = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int meoleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int meoright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String meo = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = pe + meo + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(18/*MultiExpr*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 40: // ExprOps ::=
{
String RESULT = null;
RESULT="";
CUP$A4Parser$result = new java_cup.runtime.Symbol(16/*ExprOps*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 39: // ExprOps ::= PLUS MultiExpr ExprOps
{
String RESULT = null;
int meleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int meright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String me = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int eoleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int eoright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String eo = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = "+" + me + eo + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(16/*ExprOps*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 38: // ExprOps ::= MINUS MultiExpr ExprOps
{
String RESULT = null;
int meleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int meright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String me = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int eoleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int eoright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String eo = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = "-" + me + eo + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(16/*ExprOps*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 37: // Expr ::= MultiExpr ExprOps
{
String RESULT = null;
int meleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int meright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String me = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int eoleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int eoright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String eo = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = me + eo + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(17/*Expr*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 36: // ReadStmt ::= READ LEBRAC ID COMMA QUOTATIONS RIGBRAC SCOLON
{
String RESULT = null;
int ileft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).left;
int iright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).right;
Object i = (Object)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).value;
int qleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left;
int qright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).right;
Object q = (Object)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).value;
RESULT = "$br = new BufferedReader(new FileReader(" + q + "));\n" + i + " = new Integer($br.readLine()).intValue();\n$br.close();";
CUP$A4Parser$result = new java_cup.runtime.Symbol(15/*ReadStmt*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-6)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 35: // WriteStmt ::= WRITE LEBRAC Expr COMMA QUOTATIONS RIGBRAC SCOLON
{
String RESULT = null;
int exleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).left;
int exright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).right;
String ex = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).value;
int qleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left;
int qright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).right;
Object q = (Object)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).value;
RESULT = "$bw = new BufferedWriter(new FileWriter(" + q +"));\n$bw.write(\"\"+ ("+ex+"));\n$bw.close();";
CUP$A4Parser$result = new java_cup.runtime.Symbol(14/*WriteStmt*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-6)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 34: // unmdstmt ::= IF LEBRAC BoolExpr RIGBRAC mdstmt ELSE unmdstmt
{
String RESULT = null;
int beleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).left;
int beright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).right;
String be = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).value;
int mleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left;
int mright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).right;
String m = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).value;
int umleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int umright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String um = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = "if( " + be + ")\n" + m +" else " + um;
CUP$A4Parser$result = new java_cup.runtime.Symbol(7/*unmdstmt*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-6)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 33: // unmdstmt ::= IF LEBRAC BoolExpr RIGBRAC _Statement
{
String RESULT = null;
int beleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left;
int beright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).right;
String be = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).value;
int _sleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int _sright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String _s = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = "if( " + be + ")\n" + _s;
CUP$A4Parser$result = new java_cup.runtime.Symbol(7/*unmdstmt*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 32: // mdstmt ::= Other
{
String RESULT = null;
int oleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int oright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String o = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = o + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(8/*mdstmt*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 31: // mdstmt ::= IF LEBRAC BoolExpr RIGBRAC mdstmt ELSE mdstmt
{
String RESULT = null;
int beleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).left;
int beright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).right;
String be = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).value;
int mleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left;
int mright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).right;
String m = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).value;
int dleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int dright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String d = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = "if( " + be + ")\n" + m +" else " + d;
CUP$A4Parser$result = new java_cup.runtime.Symbol(8/*mdstmt*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-6)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 30: // _Statement ::= unmdstmt
{
String RESULT = null;
int umleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int umright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String um = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = um + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(25/*_Statement*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 29: // _Statement ::= mdstmt
{
String RESULT = null;
int mleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int mright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String m = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = m + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(25/*_Statement*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 28: // ReturnStmt ::= RETURN Expr SCOLON
{
String RESULT = null;
int exleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int exright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String ex = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
RESULT = "return " + ex +";";
CUP$A4Parser$result = new java_cup.runtime.Symbol(13/*ReturnStmt*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 27: // AssignStmt ::= ID COLEQUAL QUOTATIONS SCOLON
{
String RESULT = null;
int ileft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-3)).left;
int iright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-3)).right;
Object i = (Object)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-3)).value;
int qleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int qright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
Object q = (Object)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
RESULT = i + "= " + q +";";
CUP$A4Parser$result = new java_cup.runtime.Symbol(11/*AssignStmt*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-3)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 26: // AssignStmt ::= ID COLEQUAL Expr SCOLON
{
String RESULT = null;
int ileft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-3)).left;
int iright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-3)).right;
Object i = (Object)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-3)).value;
int exleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int exright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String ex = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
RESULT = i + "= " + ex +";";
CUP$A4Parser$result = new java_cup.runtime.Symbol(11/*AssignStmt*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-3)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 25: // LocalVarDecl ::= Type AssignStmt
{
String RESULT = null;
int hleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int hright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String h = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int asleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int asright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String as = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = h + as + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(10/*LocalVarDecl*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 24: // LocalVarDecl ::= Type ID SCOLON
{
String RESULT = null;
int hleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left;
int hright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).right;
String h = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).value;
int ileft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int iright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
Object i = (Object)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
RESULT = h + i + ";";
CUP$A4Parser$result = new java_cup.runtime.Symbol(10/*LocalVarDecl*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 23: // Other ::= ReadStmt
{
String RESULT = null;
int rtleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int rtright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String rt = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = rt + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(12/*Other*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 22: // Other ::= WriteStmt
{
String RESULT = null;
int wsleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int wsright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String ws = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = ws + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(12/*Other*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 21: // Other ::= ReturnStmt
{
String RESULT = null;
int rsleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int rsright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String rs = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = rs + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(12/*Other*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 20: // Other ::= AssignStmt
{
String RESULT = null;
int asleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int asright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String as = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = as + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(12/*Other*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 19: // Other ::= LocalVarDecl
{
String RESULT = null;
int lvleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int lvright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String lv = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = lv;
CUP$A4Parser$result = new java_cup.runtime.Symbol(12/*Other*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 18: // Other ::= Block
{
String RESULT = null;
int bleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int bright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String b = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = b;
CUP$A4Parser$result = new java_cup.runtime.Symbol(12/*Other*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 17: // Statement ::=
{
String RESULT = null;
RESULT="";
CUP$A4Parser$result = new java_cup.runtime.Symbol(24/*Statement*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 16: // Statement ::= _Statement Statement
{
String RESULT = null;
int _sleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int _sright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String _s = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int sleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int sright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String s = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = "\n" + _s + s + "\n";
CUP$A4Parser$result = new java_cup.runtime.Symbol(24/*Statement*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 15: // Block ::= BEGIN _Statement Statement END
{
String RESULT = null;
int _sleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left;
int _sright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).right;
String _s = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).value;
int sleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int sright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String s = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
RESULT = "{\n" + _s + "\n" + s +"\n}";
CUP$A4Parser$result = new java_cup.runtime.Symbol(9/*Block*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-3)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 14: // FormalParam ::= Type ID
{
String RESULT = null;
int hleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int hright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String h = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int ileft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int iright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
Object i = (Object)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = h + i + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(5/*FormalParam*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 13: // _FormalParams ::=
{
String RESULT = null;
RESULT="";
CUP$A4Parser$result = new java_cup.runtime.Symbol(6/*_FormalParams*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 12: // _FormalParams ::= COMMA FormalParam _FormalParams
{
String RESULT = null;
int fleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int fright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String f = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int pleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int pright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String p = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = ", " + f + p;
CUP$A4Parser$result = new java_cup.runtime.Symbol(6/*_FormalParams*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 11: // FormalParams ::=
{
String RESULT = null;
RESULT="";
CUP$A4Parser$result = new java_cup.runtime.Symbol(4/*FormalParams*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 10: // FormalParams ::= FormalParam _FormalParams
{
String RESULT = null;
int fleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int fright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String f = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int pleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int pright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String p = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = f + p + "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(4/*FormalParams*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 9: // MethodDecl ::= Type ID LEBRAC FormalParams RIGBRAC Block
{
String RESULT = null;
int hleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-5)).left;
int hright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-5)).right;
String h = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-5)).value;
int ileft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).left;
int iright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).right;
Object i = (Object)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).value;
int fleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left;
int fright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).right;
String f = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).value;
int bleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int bright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String b = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = "static"+ h + i + "("+ f + ")throws Exception " + b + "\n";
CUP$A4Parser$result = new java_cup.runtime.Symbol(3/*MethodDecl*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-5)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 8: // MethodDecl ::= Type MAIN ID LEBRAC FormalParams RIGBRAC Block
{
String RESULT = null;
int hleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-6)).left;
int hright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-6)).right;
String h = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-6)).value;
int ileft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).left;
int iright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).right;
Object i = (Object)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-4)).value;
int fleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).left;
int fright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).right;
String f = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-2)).value;
int bleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int bright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String b = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = "public static void main (String[] args) throws Exception" + b + "\n";
CUP$A4Parser$result = new java_cup.runtime.Symbol(3/*MethodDecl*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-6)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 7: // _Program ::=
{
String RESULT = null;
RESULT = "";
CUP$A4Parser$result = new java_cup.runtime.Symbol(2/*_Program*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 6: // _Program ::= MethodDecl _Program
{
String RESULT = null;
int dleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int dright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String d = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int gleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int gright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String g = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = d + g+"";
CUP$A4Parser$result = new java_cup.runtime.Symbol(2/*_Program*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 5: // Type ::= STRING
{
String RESULT = null;
RESULT = " String ";
CUP$A4Parser$result = new java_cup.runtime.Symbol(26/*Type*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 4: // Type ::= REAL
{
String RESULT = null;
RESULT = " double ";
CUP$A4Parser$result = new java_cup.runtime.Symbol(26/*Type*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 3: // Type ::= INT
{
String RESULT = null;
RESULT = " int ";
CUP$A4Parser$result = new java_cup.runtime.Symbol(26/*Type*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 2: // Program ::= MethodDecl _Program
{
String RESULT = null;
int dleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int dright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String d = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
int gleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int gright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String g = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT= d+g+"";
CUP$A4Parser$result = new java_cup.runtime.Symbol(1/*Program*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 1: // $START ::= ExtraNonTerminal EOF
{
Object RESULT = null;
int start_valleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left;
int start_valright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).right;
String start_val = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).value;
RESULT = start_val;
CUP$A4Parser$result = new java_cup.runtime.Symbol(0/*$START*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
/* ACCEPT */
CUP$A4Parser$parser.done_parsing();
return CUP$A4Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 0: // ExtraNonTerminal ::= Program
{
String RESULT = null;
int gleft = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left;
int gright = ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right;
String g = (String)((java_cup.runtime.Symbol) CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).value;
RESULT = "import java.io.*;\npublic class A4\n{\nstatic BufferedReader $br;\nstatic BufferedWriter $bw;\n" + g + "\n}";
CUP$A4Parser$result = new java_cup.runtime.Symbol(27/*ExtraNonTerminal*/, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$A4Parser$stack.elementAt(CUP$A4Parser$top-0)).right, RESULT);
}
return CUP$A4Parser$result;
/* . . . . . .*/
default:
throw new Exception(
"Invalid action number found in internal parse table");
}
}
}
<file_sep>/Assignment5/A5Sym.java
public class A5Sym
{
public static final int QUOTATIONS = 1;
public static final int INT = 2;
public static final int REAL = 3;
public static final int STRING = 4;
public static final int WRITE = 5;
public static final int RETURN = 6;
public static final int READ = 7;
public static final int MAIN = 8;
public static final int IF = 9;
public static final int ELSE = 10;
public static final int END = 11;
public static final int BEGIN = 12;
public static final int ID = 13;
public static final int NUMBER = 14;
public static final int LEBRAC = 15;
public static final int RIGBRAC = 16;
public static final int SCOLON = 17;
public static final int COMMA = 18;
public static final int ERROR = 19;
public static final int PLUS = 20;
public static final int MINUS = 21;
public static final int DIVIDE = 22;
public static final int MULT = 23;
public static final int NOTEQUAL = 24;
public static final int EQUAL = 25;
public static final int COLEQUAL = 26;
public static final int EOF = 27;
}
<file_sep>/A4Symbol.java
//----------------------------------------------------
// The following code was generated by CUP v0.10k
// Tue Mar 12 14:37:46 EDT 2019
//----------------------------------------------------
/** CUP generated class containing symbol constants. */
public class A4Symbol {
/* terminals */
public static final int READ = 5;
public static final int ELSE = 8;
public static final int PLUS = 17;
public static final int INT = 24;
public static final int EQUAL = 22;
public static final int NOTEQUAL = 21;
public static final int END = 9;
public static final int RETURN = 4;
public static final int IF = 7;
public static final int WRITE = 3;
public static final int ID = 11;
public static final int SCOLON = 15;
public static final int BEGIN = 10;
public static final int STRING = 26;
public static final int COMMA = 16;
public static final int QUOTATIONS = 2;
public static final int MULT = 20;
public static final int EOF = 0;
public static final int NUMBER = 12;
public static final int DIVIDE = 19;
public static final int LEBRAC = 13;
public static final int MAIN = 6;
public static final int COLEQUAL = 23;
public static final int MINUS = 18;
public static final int error = 1;
public static final int RIGBRAC = 14;
public static final int REAL = 25;
}
|
45441aa64ad66e028447e3a309df17ee105bd9e2
|
[
"Java"
] | 3
|
Java
|
himani2100/LexAndCup
|
225952290ce4ca616a5a7d56353f0b340ae14f63
|
8731ac52f86c6ce184645b7a4ff5482f69a14f0c
|
refs/heads/master
|
<file_sep>## Demo
La aplicación puede verse desde el siguient enlace: [deployed app](https://xenodochial-jennings-fdbaf9.netlify.com/)
## Si se desea instalar localmente
### Clona el repositorio
Clona este repositorio en tu máquina local
```bash
git clone <EMAIL>:sergiocrol/dobcn-react.git
```
### installation
Install the dependencies
```
npm install
```
### run app
Start the application, and will be running on port 3000
```
gatsby serve
```
## Tecnologías
Para desarrollar esta aplicación se ha hecho uso de Gatsby, un framework basado en React.
Alternativamente podría haberse desarrollado con React puro, haciendo frente a los problemas de SEO mediante librerías como React Router y Helmet.
## Desafíos y soluciones
Debido a que en en momento de realizar la aplicación no tenía acceso a la REST API proporcionada para la construcción de la app; tuve que realizar scraping de la web principal. Para ello he construído una REST API que obtiene los datos de la web mencionada, los guarda en la base de datos, y los retorna en formato JSON cuando es llamada por una aplicación desde frontend.
Puede verse la REST API en el siguiente enlace:
[REST API](https://github.com/sergiocrol/dobcn-back)
## Git
[Repository Link](https://github.com/sergiocrol/dobcn-react)
## Deployment
[Deployment Link](https://xenodochial-jennings-fdbaf9.netlify.com/)
## Author
[<NAME>](https://github.com/sergiocrol)
<file_sep>import React, { Component } from "react";
import Layout from "../components/Layout";
import SEO from "../components/SEO";
import ProductCard from "../components/Product-card";
import logo from "../images/logo.svg";
class HomePage extends Component {
state = {
loading: true,
lang: 'es',
products: [],
filters: []
}
componentDidMount() {
const { lang } = this.state;
fetch(`https://dobcn-api.herokuapp.com/products/all/${lang}`)
.then(response => {
return response.json();
})
.then(json => {
this.setState({
products: json,
loading: false
})
})
}
filterFunction = (nam) => {
let newFilters = [...this.state.filters];
if (newFilters.includes(nam)) {
newFilters = newFilters.filter(el => el !== nam);
} else {
newFilters.push(nam);
}
return newFilters;
}
filterProduct = event => {
let newFilter = [];
const name = event.target.name;
if (name === "mantener-recuperar-redensificar") {
const elements = (event.target.name).split('-');
elements.forEach(el => {
const n = this.filterFunction(el);
newFilter = [...n]
})
} else {
newFilter = this.filterFunction(name);
}
this.setState({
filters: newFilter
})
}
changeLanguage = (event) => {
const lang = event.target.value;
fetch(`https://dobcn-api.herokuapp.com/products/all/${lang}`)
.then(response => {
return response.json();
})
.then(json => {
this.setState({
lang,
products: json,
loading: false
})
})
}
render() {
const { loading, products, filters } = this.state;
return (
<Layout>
<SEO title="Catálogo" />
<section className="index-header">
<select onChange={(event) => { this.changeLanguage(event) }} id="lang">
<option value="es">Español</option>
<option value="en">English</option>
<option value="pt">Português</option>
</select>
<img src={logo} alt="epaplus logo" />
<p>Salud científicamente probada</p>
<div className="triangle"></div>
</section>
<section className="index-description">
<h2>Nuestra gama de productos</h2>
<p>Soluciones para el cuidado de articulaciones, bienestar digestivo, un sueño reparador, y para reforzar el sistema inmunitario</p>
</section>
<section className="index-main">
<section className="filter-box">
<div className="filter-box-container">
<a className={`filter-button ${filters.includes('redensificar') ? 'active' : ''}`} name="mantener-recuperar-redensificar" onClick={(event) => { this.filterProduct(event) }}>Articulaciones y huesos</a>
<a className={`filter-button ${filters.includes('digestcare') ? 'active' : ''}`} name="digestcare" onClick={(event) => { this.filterProduct(event) }}>Aparato digestivo</a>
<a className={`filter-button ${filters.includes('immuncare') ? 'active' : ''}`} name="immuncare" onClick={(event) => { this.filterProduct(event) }}>Sistema inmunitario</a>
<a className={`filter-button ${filters.includes('sleepcare') ? 'active' : ''}`} name="sleepcare" onClick={(event) => { this.filterProduct(event) }}>Sueño y descanso</a>
<a className={`filter-button ${filters.includes('vigorcare') ? 'active' : ''}`} name="vigorcare" onClick={(event) => { this.filterProduct(event) }}>Vigor sexual</a>
<a className={`filter-button ${filters.includes('vitalcare') ? 'active' : ''}`} name="vitalcare" onClick={(event) => { this.filterProduct(event) }}>Vitalidad y energia</a>
</div>
</section>
<div className="index-main-container">
{
loading ?
<h1 className="loading">cargango...</h1>
: products.map(product => {
return (
(filters.length === 0 || filters.includes(product.family)) ?
<ProductCard key={product._id} product={product} /> :
null
)
}
)
}
</div>
</section>
</Layout>
);
}
}
export default HomePage;
<file_sep>import { Link } from "gatsby"
import PropTypes from "prop-types"
import React from "react"
const Header = ({ siteTitle }) => (
<header className="header ">
<div className="header-container">
<Link to="/home/">
<img src="https://sandbox5.dobcn.com/hiring/sergio/wp-content/themes/epaplus/assets/images/epaplus.png" alt="Epaplus logo" />
</Link>
</div>
</header>
)
Header.propTypes = {
siteTitle: PropTypes.string,
}
Header.defaultProps = {
siteTitle: ``,
}
export default Header
<file_sep>module.exports = {
siteMetadata: {
title: "Catálogo productos Epaplus complementos alimenticios",
description: "Catálogo productos Epaplus complementos alimenticios para el cuidado de articulaciones, cuidado digestivo, conciliar sueño, reforzar sistema inmunitario",
author: "@sergiocrol",
},
plugins: [
"gatsby-plugin-react-helmet",
"gatsby-plugin-sass"
],
}
|
371b72de584a392831e7ea9553c86f5f7b333450
|
[
"Markdown",
"JavaScript"
] | 4
|
Markdown
|
sergiocrol/dobcn-react
|
77305a82ce68e76fc510acbbd56929f187a65c58
|
d3aecd9b39eba60e42b4ed513eafaea05864dda4
|
refs/heads/master
|
<file_sep>const request = require('supertest')
const setupDatabase = require('../fixtures/db')
beforeEach(setupDatabase)
test('Should send hello world message', async () => {
const response = await request(app)
.get('/')
.send()
.expect(200)
expect(response.body).toBe('Hello world.')
})<file_sep>/** Express helps with http requests. */
const express = require('express');
/** Logger to log all the errors and infos */
/** Utilize the auth middleware modules. */
const auth = require('../middleware/auth');
/** Import express router to have multi-page applications. */
const router = new express.Router();
/** Import service for restriction */
const service = require('../services/restrictions_service');
/** Hello world endpoint to serve as an example. */
router.get('/restrictions', auth, async(req, res, next) => {
try {
res.json(await service.getRestrictions(req.body));
} catch (err) {
logger.error('Error at restriction Get');
logger.error(err);
res.json({error: err});
}
next();
});
router.post('/restrictions', auth, async(req, res, next) => {
try {
res.json(await service.postRestrictions(req.body));
} catch (err) {
logger.error('Error at restriction Post');
logger.error(err);
res.json({error: err});
}
next();
});
module.exports = router;
<file_sep>/** Express helps with http requests. */
const express = require('express');
/** Logger to log all the errors and infos */
/** Utilize the auth middleware modules. */
const auth = require('../middleware/auth');
/** Import express router to have multi-page applications. */
const router = new express.Router();
/** Import booking serivce */
const service = require('../services/bookings_service');
router.get('/bookings', auth, async(req, res, next) => {
try {
res.json(await service.getBookings(req.query));
} catch (err) {
logger.error('Error getting bookings');
logger.error(err);
res.json({error: err});
}
next();
});
router.get('/booking', auth, async(req, res, next) => {
try {
res.json(await service.getBooking(req.query));
} catch (err) {
logger.error('Error getting booking');
logger.error(err);
res.json({error: err});
}
next();
});
router.post('/booking', auth, async(req, res, next) => {
try {
res.json(await service.postBooking(req.body));
} catch (err) {
logger.error('Error at post booking');
logger.error(err);
res.json({error: err});
}
next();
});
router.delete('/booking', auth, async(req, res, next) => {
try {
res.json(await service.deleteBooking(req.body));
} catch (err) {
logger.error('Error at delete booking');
logger.error(err);
res.json({error: err});
}
next();
});
router.delete('/bookings', auth, async(req, res, next) => {
try {
res.json(await service.deleteBookings(req.body));
} catch (err) {
logger.error('Error at delete booking');
logger.error(err);
res.json({error: err});
}
next();
});
module.exports = router;
<file_sep>
require('dotenv').config();
// Application insight config
// Do not run on if it's not defined
if (process.env.applicationInsightsInstrumentation !== undefined) {
const appInsights = require("applicationinsights");
appInsights.setup(process.env.APPINSIGHTS_INSTRUMENTATIONKEY)
.setAutoDependencyCorrelation(true)
.setAutoCollectRequests(true)
.setAutoCollectPerformance(true, true)
.setAutoCollectExceptions(true)
.setAutoCollectDependencies(true)
.setAutoCollectConsole(true)
.setUseDiskRetryCaching(true)
.setSendLiveMetrics(false)
.start();
}
/** Require package.json to expose the app name for the logger */
const packageJson = require(`./package.json`);
//Standard server setup.
/**
* Require morgan so we can capture and log request and response headers
*/
const morgan = require('morgan');
/** Custom Morgan format */
morgan(function (tokens, req, res) {
return [
tokens.method(req, res),
tokens.url(req, res),
tokens.status(req, res),
tokens.res(req, res, 'content-length'), '-',
tokens['response-time'](req, res), 'ms',
tokens.component(`${packageJson.name}`),
tokens.appShortName(`${packageJson.appShortName}`),
tokens.appLongName(`${packageJson.appLongName}`),
tokens.host(`${os.hostname()}`)
].join(' ')
})
<file_sep>require('dotenv').config();
const JiraClient = require('jira-connector');
var jira = new JiraClient({
host: 'jira.zzz.ca',
basic_auth: {
username: process.env.JIRA_USER,
password: process.env.JIRA_PASS,
},
});
async function postFeedback(feedback) {
return await jira.issue.createIssue({
fields: {
project: {
key: 'DBT',
},
summary: 'Desk Booking Tool - Feedback',
description: feedback.feedback,
issuetype: { name: 'Problem' },
},
});
}
module.exports = {
postFeedback,
};
<file_sep>/** Import floor model */
const Floors = require('../models/floors.model');
/** Import FS for reading file streams */
const fs = require('fs');
/**
* gets floors: will always return array so get floor with [0] when querying one
* @param {*} info params for floor
*/
async function getFloors(info) {
return await Floors.find(info, function(err) {
if (err) console.log('error trying to get floor');
});
}
/**
* posts floorplans from the frontend
* @param {*} info contains the floor name, office name, width, and height of the view when buildingthe floor
* @param {*} file for the image
* This receives JS FormData from the frontend to handle the image file, so all arrays need to be parsed before
* making mongo call
*/
async function postFloorFrontend(info, file) {
const d = JSON.parse(info.desks);
const data = {
floor: info.floor,
office: info.office,
height: info.height,
width: info.width,
desks: d,
image: {data: fs.readFileSync(file.path), contentType: 'image/jpeg'},
};
return await Floors.create(data, function(err) {
if (err) console.log('error trying to create floor');
});
}
/**
* posts floor
* @param {*} info
* @param {*} file for the image
* This is for posting a floor through Postman/directly through the API so nothing needs to be parsed
*/
async function postFloor(info, file) {
const data = {
...info,
image: {data: fs.readFileSync(file.path), contentType: 'image/jpeg'},
};
return await Floors.create(data, function(err) {
if (err) console.log('error trying to create floor');
});
}
/**
* update a desk's bookable status
* @param {*} info
*/
async function updateDesk(info) {
const query = {
'office': info.office,
'floor': info.floor,
'desks.name': info.desk,
};
const newValues = {
name: info.desk,
bookable: info.bookable,
x: info.x,
y: info.y,
};
return await Floors.updateOne(
query,
{
$set: {
'desks.$': newValues,
},
},
function(err) {
if (err) console.log('error trying to get booking');
},
);
}
/**
* delete a floor with given params: empty object will clear the DB
* @param {*} info
*/
async function deleteFloor(info) {
return await Floors.deleteMany(info, function(err) {
if (err) console.log('error trying to delete floor');
});
}
module.exports = {
getFloors,
postFloor,
updateDesk,
deleteFloor,
postFloorFrontend,
};
<file_sep>require('dotenv').config();
/** Express helps with http requests. */
const express = require('express');
/** Obtaining the router to be used as the middleware by express app. */
const port = process.env.PORT || 3000;
/** Allows the use of express funcitons. */
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
// Local imports.
const restrictionsRouter = require('./src/routers/restrictions_router');
const bookingsRouter = require('./src/routers/bookings_router');
const floorsRouter = require('./src/routers/floors_router');
const feedbackRouter = require('./src/routers/feedback_router');
const DB = require('./src/db');
/** Middleware. */
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(restrictionsRouter, bookingsRouter, floorsRouter, feedbackRouter);
/** Runs the server to listen on a specific port number from HTTP requests. */
logger.info('Starting server..');
app.listen(port, () => {
logger.info(`server running on port ${port}`);
});
/** connect to mongoose. */
try {
DB.connect();
DB.checkConnection();
} catch (err) {
logger.error(err);
}
<file_sep>/** Imports mongoose */
const mongoose = require('mongoose');
/** Creates the userFav schema */
const bookingSchema = new mongoose.Schema({
office: String,
floor: String,
date: Date,
desk: String,
name: String,
email: String,
});
/** Creates the mongoose model for userFav */
const Bookings = mongoose.model('Bookings', bookingSchema);
module.exports = Bookings;
<file_sep>/** Import Bookings model */
const Bookings = require('../models/bookings.model');
/**
* gets restrictions
* @param {*} info
*/
async function getBooking(info) {
return await Bookings.findOne(info, function(err) {
if (err) console.log('error trying to get booking');
});
}
/**
* get bookings
* @param {*} info
*/
async function getBookings(info) {
return await Bookings.find(info, function(err) {
if (err) console.log('error trying to get bookings');
});
}
/**
* add new bookings
* @param {*} info
*/
async function postBooking(info) {
return await Bookings.create(info, function(err) {
if (err) console.log(err);
});
}
/**
* delete bookings
* @param {*} info
*/
async function deleteBooking(info) {
return await Bookings.deleteOne(info, function(err) {
if (err) console.log(err);
});
}
/**
* delete all the bookings
* @param {*} info
*/
async function deleteBookings(info) {
return await Bookings.deleteMany(info, function(err) {
if (err) console.log(err);
});
}
module.exports = {
getBooking,
getBookings,
postBooking,
deleteBooking,
deleteBookings,
};
<file_sep>/** Imports mongoose */
const mongoose = require('mongoose');
/** Creates the userFav schema */
const restrictionSchema = new mongoose.Schema({
continuous: Number,
ahead: Number,
});
/** Creates the mongoose model for userFav */
const Restrictions = mongoose.model('Restrictions', restrictionSchema);
module.exports = Restrictions;
<file_sep># desk-booking-tool-back
Backend for the desk booking tool
Frontend is in a second repository along with an extended description
<file_sep>/** Express helps with http requests. */
const express = require('express');
/** Logger to log all the errors and infos */
/** Utilize the auth middleware modules. */
const auth = require('../middleware/auth');
/** Import express router to have multi-page applications. */
const router = new express.Router();
/** Imports for image handleing */
const multer = require('multer');
/** Import Mutler for handleing form data */
const upload = multer({dest: 'uploads/'});
/** Import floor service */
const service = require('../services/floors_service');
router.get('/floors', auth, async(req, res, next) => {
try {
res.json(await service.getFloors(req.query));
} catch (err) {
logger.error('Error fetching floors');
logger.error(err);
res.json({error: err});
}
next();
});
router.post('/floors', upload.single('image'), async(req, res, next) => {
try {
res.json(await service.postFloor(req.body, req.file));
} catch (err) {
logger.error('Error creating floor');
logger.error(err);
res.json({error: err});
}
next();
});
router.post(
'/floorsFrontend',
upload.single('image'),
async(req, res, next) => {
try {
res.json(await service.postFloorFrontend(req.body, req.file));
} catch (err) {
logger.error('Error creating floor');
logger.error(err);
res.json({error: err});
}
next();
},
);
router.put('/floors', auth, async(req, res, next) => {
try {
res.json(await service.updateDesk(req.body));
} catch (err) {
logger.error('Error updating desk');
logger.error(err);
res.json({error: err});
}
next();
});
router.delete('/floors', auth, async(req, res, next) => {
try {
res.json(await service.deleteFloor(req.body));
} catch (err) {
logger.error('Error updating desk');
logger.error(err);
res.json({error: err});
}
next();
});
module.exports = router;
<file_sep>/** Import restrictions Model */
const Restrictions = require('../models/restrictions.model');
/**
* get restrictions
*/
async function getRestrictions() {
return await Restrictions.find({});
}
/**
* does thing
* @param {*} body ..
*/
async function postRestrictions(body) {
const newData = {
continuous: body.continuous,
ahead: body.ahead,
};
// return await Restrictions.findOneAndDelete({'ahead': 4});
Restrictions.findOneAndUpdate(
{},
newData,
{upsert: true, useFindAndModify: false},
function(err, doc) {
if (err) console.log('error trying to update restriction');
},
);
}
module.exports = {
getRestrictions,
postRestrictions,
};
|
96c237614a05cca4011e4e23085e121c53390cf7
|
[
"JavaScript",
"Markdown"
] | 13
|
JavaScript
|
chindrisadrian/desk-booking-tool-back
|
ec06d54b36a1429e8d6577070457452c0d4b018c
|
28813ab1914ae815082eee16490fe283731588cc
|
refs/heads/master
|
<repo_name>tecolotedev/Clone-Instagram-Backend<file_sep>/src/helpers/verfifyToken.js
const jwt = require('jsonwebtoken');
const verifyToken = (Authorization)=>{
try{
return jwt.verify(Authorization,process.env.JWTSECRET)
}catch(e){
return null;
}
}
module.exports = {verifyToken};<file_sep>/src/routes/user.js
const express = require('express');
const router = express.Router();
const multer = require('multer');
const PostModel = require('../Models/PostsModel');
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
const UserModel = require('../Models/UserModel');
//Create new user by email and password manually
router.post('/signup-users',async (req,res)=>{
const {email,name,username,password} = req.body;
//-------------verify if email is already in database
UserModel.findByEmail(email,(err,Item)=>{
if(err)return res.json({ok:false,message:'Error 500'});
if(Item)return res.json({ok:false,message:'email is already in db'});
//-------------------if email not in db--------------
const user = new UserModel(email,username,name,password);
user.save((err,data)=>{
if(err)return res.json({ok:false,message:"user can't be saved"});
res.json({ok:true,user:data.user,token:data.token});
})
});
});
router.put('/upload-post',upload.single('newPost'),async(req,res)=>{
const {email,description} = req.body;
let user = await UserModel.makePost(req.file.buffer,req.file.originalname,email,description);
const token = await UserModel.tokenization(user);
res.json({ok:true,posts:user.posts,token});
});
router.post('/posts',async(req,res)=>{
const {postsID} = req.body;
const posts = await PostModel.getPosts(postsID);
res.json({ok:true,posts})
});
router.delete('/users',(req,res)=>{
});
module.exports = router;
<file_sep>/src/routes/sesions.js
const express = require('express');
const router = express.Router();
const UserModel = require('../Models/UserModel');
const axios = require('axios');
const {verifyToken} = require('../helpers/verfifyToken');
//Get one user by email and password
router.post('/loggin',(req,res)=>{
const {email,password} = req.body;
UserModel.findByEmail(email,async(err,Item)=>{
if(err)return res.json({ok:false,message:'Error 404'});
if(!Item) return res.json({ok:false,message:'wrong data'}); //wrong email
if(Item.authentication==='google')return res.json({ok:false,message:'This account is logged via google'});
const match = await UserModel.compare(password,Item.password);
delete Item.password;//delete password after using
if(!match) return res.json({ok:false,message:'wrong data'}); //wrong password
const user = Item;
const token = UserModel.tokenization(Item);
res.json({ok:true,user,token});
});
});
//Create new user by google autentication
router.post('/loggin-google',(req,res)=>{
const {idtoken} = req.headers;
console.log(idtoken)
let verifyToken = `https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${idtoken}`;
axios.get(verifyToken)
.then(async data=>{
const {email,name,picture} = data.data;
UserModel.findByEmail(email,async (err,Item)=>{
const user = Item;
delete user.password;
const token = await UserModel.tokenization(user);
res.json({ok:true,user,token});
if(err) return console.log(err);
if(Item) return console.log('user already in db');
const newUser = new UserModel(email,name,name,'','google');
newUser.save((err,data)=>{
if(err)console.log(err);
});
});
})
.catch(e=>{
res.json({ok:false});
//console.log(e);
});
});
router.get('/verify-token',(req,res)=>{
const {authorization} = req.headers;
let valid = verifyToken(authorization);
if(!valid) return res.json({ok:false,message:'invalid token please signup'});
delete valid.exp;
delete valid.iat;
let user = valid;
res.json({ok:true,user})
});
module.exports = router;<file_sep>/src/build/precache-manifest.c0257ee7265fe3422273912dd28812e8.js
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "501e4849d4b32671444900f6ccda0c04",
"url": "/index.html"
},
{
"revision": "2e9c4130a365a7488427",
"url": "/static/css/2.04ff9426.chunk.css"
},
{
"revision": "cecb3519f3b485ae372a",
"url": "/static/css/main.d155e41c.chunk.css"
},
{
"revision": "2e9c4130a365a7488427",
"url": "/static/js/2.82aa3ded.chunk.js"
},
{
"revision": "3453b8997016469371284a28c0e873e2",
"url": "/static/js/2.82aa3ded.chunk.js.LICENSE.txt"
},
{
"revision": "cecb3519f3b485ae372a",
"url": "/static/js/main.1ed39545.chunk.js"
},
{
"revision": "9b4e396c183e42c1fa5c",
"url": "/static/js/runtime-main.09b85ec0.js"
}
]);<file_sep>/src/Models/PostsModel.js
const AWS = require('aws-sdk');
const { v4: uuidv4 } = require('uuid');
const dynamoClient = new AWS.DynamoDB.DocumentClient();
class PostModel{
constructor(description,fileLink){
this.description = description;
this.fileLink = fileLink;
this.tablename='posts';
};
async save(){
let id = uuidv4();
const paramsPut = {
TableName:this.tablename,
Item:{
"id":id,
"fileLink":this.fileLink,
"description":this.description,
"comments":[],
"shared":[],
"likes":[]
}
}
try{
const data = await dynamoClient.put(paramsPut).promise();
//console.log('data',data)
if(data)return id;
}catch(e){
console.log('error en post model',e);
}
}
static async getPosts(postsID){
const Keys = postsID.map(id=>{
return{
id
}
});
var params = {
RequestItems: {
'posts': {
Keys
}
}
};
const data = await dynamoClient.batchGet(params).promise();
return data.Responses.posts;
}
}
module.exports = PostModel;<file_sep>/src/index.js
require('dotenv').config();
const express = require('express');
const path = require('path');
const app = express();
var cors = require('cors')
//--------------------------SDK AWS--------------------
const AWS = require('aws-sdk');
AWS.config.update({region:'us-east-1'});
//--------------------------MiddleWares----------------------------
//app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'build')));//activate static files
//--------------------------Server Project React--------------------
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
//--------------------------Routing----------------------------------
app.use(require('./routes/index.routes.js'));
//--------------------------Cofig port-------------------------------
const port = process.env.PORT || 5000;
app.listen(port,()=>{
console.log(`Server online on port ${port}`);
});
|
3e7f495b973a3e2f94442de1f69fe758860360c4
|
[
"JavaScript"
] | 6
|
JavaScript
|
tecolotedev/Clone-Instagram-Backend
|
a33c59241322ed7eefe7e36369a69cfc36a37300
|
07aab9929734e95ab3f9169e92a4aabf68183264
|
refs/heads/master
|
<file_sep>//arrays for lower capital letters, lower case letters, numbers, and symbols
const capChar = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
const lowChar = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
const num =['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
const sym = ['!', '@', '#', '$', '%', '^', '&', '*', '=', '-'];
//Where our responses will be stored
let passLength = 0;
let totalChar = [];
let confirmChar = 0;
let officialPassword = 0;
//function for password length
function passwordLengthFunctionPrompt(){
passLength = prompt("How long is your password? \n (Must be between 8 to 128 characters)");
let numLength = parseInt(passLength);
numLength = passLength;
if(passLength < 8 || passLength > 128){
alert("Invalid response!! Please choose a number between 8 and 128!")
passwordLengthFunctionPrompt();
}else{
alert("You chose " + passLength);
}
}
// passwordLengthFunctionPrompt();
// console.log(passLength);
//function for confirm questions
function confirmQuestions(){
const hasUpperCase = confirm("Does it contain upper case letters?");
const hasLowerCase = confirm("Does it contain lower case letters?");
const hasNumbers = confirm("Does it contain numbers?");
const hasSymbols = confirm("Does it contain special symbols?");
//if statements for the confirm questions
if (hasUpperCase){
const upperArray = totalChar.concat(capChar);
totalChar = upperArray;
};
if(hasLowerCase){
const lowerArray = totalChar.concat(lowChar);
totalChar = lowerArray;
};
if(hasNumbers){
const numArray = totalChar.concat(num);
totalChar = numArray;
};
if(hasSymbols){
const symbolArray = totalChar.concat(sym);
totalChar = symbolArray;
};
//for loop for randomizing the variables
for(let i = 0; i < passLength; i++){
confirmChar = Math.floor(Math.random()* totalChar.length);
officialPassword += totalChar[confirmChar];
};
//where the password is going to be inserted
document.getElementById("password").value = officialPassword;
};
// confirmQuestions();
// console.log(totalChar);
//Now to start code by clicking Generate button
const btnGenerate = document.getElementById('generate');
btnGenerate.onclick = function (){
passwordLengthFunctionPrompt();
confirmQuestions();
}
//Now to copy the password
const newPasswordText = document.getElementById("password");
const btnCopy = document.getElementById('copy');
btnCopy.onclick = function(){
newPasswordText.select();
document.execCommand("copy");
alert("copied!");
}
// const results = document.querySelector("#result");
// const howLong = prompt("How long is your password? \n (Must be between 8 to 128 characters)");
// if(howLong >= 8 && howLong <= 128){
// const capLett = confirm ("Does it contain upper case letters?");
// const capChar = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
// const capLength = capChar.length;
// const randChar = capChar[Math.floor(Math.random() * capLength)]
// console.log(randChar)
// //the random capital letter is working!!!;
// if(capLett){
// const lowLett = confirm("Does it contain lower case letters?");
// const lowChar = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
// const lowLength = lowChar.length;
// const randLow = lowChar[Math.floor(Math.random()* lowLength)];
// console.log(randLow);
// //random low letter is working!!!
// if(lowLett){
// const numQues = confirm("Does it contain numeric characters?");
// const num =['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
// const numLength = num.length;
// const randNum = num[Math.floor(Math.random() * numLength)];
// console.log(randNum);
// //random number working!!
// if(numQues){
// const symbolQues = confirm("Does it contain symbols??");
// const symbols = ['!', '@', '#', '$', '%', '^', '&', '*', '=', '-'];
// const symLength = symbols.length;
// const randSym = symbols[Math.floor(Math.random()) * symLength];
// console.log(randSym);
// //random symbols working!!!
// }
// }
// }
// }else{
// alert("Please enter the appropriate amount of characters!");
// }
// const numLength = num.length;
// for (i = 0; i < numLength; i++){
// console.log(i);
// if
// }
// const capChar = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
// const lowChar = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
// const num =['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
// const sym = ['!', '@', '#', '$', '%', '^', '&', '*', '=', '-'];
// const charCount = prompt("How long is your password? (Must be between 8 to 128 characters)");
// const capLett = confirm("Does it contain upper case letters?");
// const lowLet = confirm("Does it Contain lower case letters?");
// const numQues = confirm("Does it contain numeric characters?");
// const specSym = confirm("Does it contain special symbols?");
//im gonna come back to this and put a pin in it since it can be regraded; I just need to go over for loops it statements and strings again.
//once i get those thigns down I think I can do it
//I didn't wanna cheat and copy and paste something i found on the internet especially since i didnt
//understand it.
|
564afe5d32567f23d974d399f30a091e19d41c37
|
[
"JavaScript"
] | 1
|
JavaScript
|
Blinkjuan82/PASSWORD-GENERATOR
|
a3381e5193358669ace70fcf29abe93e2f830064
|
3f850cee03ddd6429ee9e947f8060d0fe69f0749
|
refs/heads/master
|
<repo_name>peternycander/xmlpub<file_sep>/main.js
var http = require('http');
var fs = require('fs');
var express = require('express');
var app = express();
var connect = require('connect');
var session = require('express-session');
var schedules = require('./server_modules/schedules.js');
var sets = require('./server_modules/sets.js');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public_html'));
app.put('/sets', sets.add);
app.get('/sets', sets.get);
app.put('/schedules', schedules.add);
app.get('/schedules/:scheduleId', schedules.get);
app.get('/schedules', schedules.getAll);
app.get('/excel/:scheduleId', schedules.getExcelFile);
app.get('/print/:scheduleId', schedules.getPrinterFriendly);
var httpServer = http.createServer(app);
httpServer.listen(8080);
<file_sep>/public_html/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" href="main.css">
<title>De-shrimpify</title>
</head>
<body>
<div class="header">
<h1><a href="/">De-shrimpify</a></h1>
<ul class="crumbs">
<li><a href="my_schedules.html" >My Schedules</a></li>
<li><a href="new_schedule.html">New Schedule</a></li>
</ul>
<div class="fb-login-button login-button" data-max-rows="1" data-size="medium" data-show-faces="false" data-auto-logout-link="false"></div>
</div>
<div class="welcome-message">
<p>Ever wanted to start working out at the gym, but never had the discipline to keep it up? Now you can de-shrimpify your body with
our new service, de-shrimpify! It's totally free; just sign in with facebook to get started!</p>
<p class="manager">- <NAME></p>
</div>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="main.js"></script>
</body>
</html>
<file_sep>/setup.sql
DROP DATABASE xmlpub;
CREATE DATABASE xmlpub;
use xmlpub;
CREATE TABLE schedules
(
scheduleID int NOT NULL AUTO_INCREMENT,
userID varchar(255),
name varchar(255),
numDays int,
PRIMARY KEY (scheduleID)
);
CREATE TABLE exercises
(
exerciseID int NOT NULL AUTO_INCREMENT,
scheduleID int,
day varchar(255),
exercise varchar(1000),
description varchar(1000),
PRIMARY KEY (exerciseID)
);
CREATE TABLE sets
(
id int NOT NULL AUTO_INCREMENT,
exerciseID int,
time varchar(255),
comment varchar(1000),
PRIMARY KEY (id)
);
<file_sep>/server_modules/sets.js
var db = require('mysql');
var config = require('../config.json');
var pool = db.createPool({
connectionLimit: 10,
host : 'localhost',
user : config.username,
password : <PASSWORD>.password,
database : 'xmlpub'
});
function update(req, res) {
console.log('updating some shit');
var set = req.param('set');
if (set.comment === undefined) {
res.sendStatus(400);
return;
}
set.comment = set.comment || '';
console.log(set.comment);
pool.getConnection(function(err, connection) {
connection.query('UPDATE sets SET comment = ? where id = ?',
[set.comment, set.id],
function(err, rows, fields) {
connection.release();
if (err) {
res.sendStatus(400);
throw err;
}
res.sendStatus(201);
});
});
}
exports.add = function(req, res) {
var set = req.param('set');
if(set.id) {
update(req, res);
return;
}
if (set.exerciseId === undefined || set.time === undefined) {
res.sendStatus(400);
return;
}
set.comment = set.comment || '';
pool.getConnection(function(err, connection) {
connection.query('INSERT INTO sets (exerciseID, time, comment) VALUES(?, ?, ?);',
[set.exerciseId, set.time, set.comment],
function(err, rows, fields) {
connection.release();
if (err) {
res.sendStatus(400);
throw err;
}
res.sendStatus(201);
});
});
}
exports.get = function(req, res) {
var exerciseId = req.param('exerciseId');
if (exerciseId === undefined) {
res.sendStatus(400);
return;
}
pool.getConnection(function(err, connection) {
connection.query('SELECT * FROM sets WHERE exerciseId=?', [exerciseId], function(err, rows, fields) {
connection.release();
if(err) {
res.sendStatus(400);
throw err;
}
console.log(rows);
res.send(rows);
});
});
}<file_sep>/public_html/main.js
var deshrimpify = deshrimpify || {};
window.fbAsyncInit = function() {
FB.init({
appId : '805769692819041',
xfbml : true,
version : 'v2.2'
});
FB.Event.subscribe("xfbml.render", function () {
var event = new CustomEvent("fbload", { "detail": "Facebook loaded" });
document.dispatchEvent(event);
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
deshrimpify.getLoginStatus = function(callback) {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
if(callback)
callback(response.authResponse);
}
else {
FB.login();
}
});
}
$(document).ready(function() {});
$.put = function(url, data, success, dataType) {
return $.ajax({
type: "PUT",
url: url,
data: data,
success: success,
dataType: dataType
});
};
$.delete = function(url, data, success, dataType) {
return $.ajax({
type: "DELETE",
url: url,
data: data,
success: success,
dataType: dataType
});
};
<file_sep>/public_html/scheduleCreator.js
var deshrimpify = deshrimpify || {};
deshrimpify.scheduleCreator = deshrimpify.scheduleCreator || {};
deshrimpify.scheduleCreator.addExercise = function () {
$('#newExercise').parent().parent().before(['<tr>',
'<td><input type="text" /></th>',
'<td><input type="text" /></th>',
'</tr>'].join("\n"));
}
deshrimpify.scheduleCreator.switchToDay = function (day) {
var currentDay = deshrimpify.scheduleCreator.currentDay;
deshrimpify.scheduleCreator.days[currentDay] = $('#newSchedule').clone(); //Save old day
if(deshrimpify.scheduleCreator.days[day] !== undefined) { //new day
$('#newSchedule').empty();
$('#newSchedule').replaceWith(deshrimpify.scheduleCreator.days[day]);
$('#newExercise').click(deshrimpify.scheduleCreator.addExercise);
} else {
$('#newSchedule').empty();
$('#newSchedule').html(['<tr>',
'<th>Exercise</th>',
'<th style="width: 300px">Description</th>',
'</tr>',
'<tr>',
'<td><button id="newExercise">Add exercise...</button></td>',
'<td><button id="saveSchedule">Save Schedule</button></td>',
'</tr>'].join('\n'));
$('#newExercise').click(deshrimpify.scheduleCreator.addExercise);
$('#saveSchedule').click(deshrimpify.scheduleCreator.sendToServer);
}
deshrimpify.scheduleCreator.currentDay = day;
}
deshrimpify.scheduleCreator.newSchedule = function () {
var container = $('.schedule-creator')[0];
$(container).empty();
deshrimpify.scheduleCreator.currentDay = "Monday";
deshrimpify.scheduleCreator.days = {"Monday" : {}};
$(container).append(['<ul class="schedule-pager">',
'<li><a class="active">Monday</a></li>',
'<li><a>Tuesday</a></li>',
'<li><a>Wednesday</a></li>',
'<li><a>Thursday</a></li>',
'<li><a>Friday</a></li>',
'<li><a>Saturday</a></li>',
'<li><a>Sunday</a></li>',
'</ul>'].join('\n'));
$(container).append(['<select class="schedule-dropdown">',
'<option>Monday</option>',
'<option>Tuesday</option>',
'<option>Wednesday</option>',
'<option>Thursday</option>',
'<option>Friday</option>',
'<option>Saturday</option>',
'<option>Sunday</option>',
'</select>'].join('\n'));
$(container).append(['<table id="newSchedule" class="schedule">',
'<tr>',
'<th>Exercise</th>',
'<th style="width: 300px">Description</th>',
'</tr>',
'<tr>',
'<td><button id="newExercise">Add exercise...</button></td>',
'<td><button id="saveSchedule">Save Schedule</button></td>',
'</tr>',
'</table>'].join('\n'));
$('#newExercise').click(deshrimpify.scheduleCreator.addExercise);
$('#saveSchedule').click(deshrimpify.scheduleCreator.sendToServer);
$('.schedule-pager a').click(function () {
$('.schedule-pager .active').removeClass('active');
$(this).addClass('active');
deshrimpify.scheduleCreator.switchToDay($(this).html());
});
$('.schedule-dropdown').change(function () {
console.log(this.value);
deshrimpify.scheduleCreator.switchToDay(this.value+"");
});
}
deshrimpify.scheduleCreator.sendToServer = function () {
var schedule = deshrimpify.scheduleCreator.exportToJson();
deshrimpify.getLoginStatus(checkStatus);
function checkStatus(info) {
var id = info.userID;
$.put('/schedules', {userId: id, schedule: schedule}, afterInsertion);
}
function afterInsertion(e) {
console.log(e)
}
}
deshrimpify.scheduleCreator.exportToJson = function () {
var currentDay = deshrimpify.scheduleCreator.currentDay;
deshrimpify.scheduleCreator.days[currentDay] = $('#newSchedule').clone();
var exported = {};
Object.keys(deshrimpify.scheduleCreator.days).forEach(addToExport);
function addToExport(day) {
exported[day] = {};
var schedule = deshrimpify.scheduleCreator.days[day];
var values = schedule.find('input');
for(var i = 0; i < values.length; i+= 2) {
if(values[i] === undefined || values[i+1] === undefined)
break;
exported[day][values[i].value] = {"description": values[i+1].value};
}
}
return exported;
}<file_sep>/public_html/scheduleViewer.js
var deshrimpify = deshrimpify || {};
deshrimpify.scheduleViewer = deshrimpify.scheduleViewer || {};
deshrimpify.scheduleViewer.addSet = function (ex, id) {
$('[id="newSet'+ex+'"]').parent().parent().after('<tr exercise="'+id+'" name="newSet" style="font-size: 0.8em"><td>'+new Date().toDateString()+'</td><td><input type="test"></td><td style="background-color:white"><button onclick="$(this).parent().parent().remove()">Remove</button></td></tr>');
}
deshrimpify.scheduleViewer.exportSets = function (ex) {
var currentDay = deshrimpify.scheduleViewer.currentDay;
deshrimpify.scheduleViewer.days[currentDay] = $('#viewedSchedule').clone();
Object.keys(deshrimpify.scheduleViewer.days).forEach(addToExport);
Object.keys(deshrimpify.scheduleViewer.days).forEach(addOldToExport);
function addToExport(day) {
var schedule = deshrimpify.scheduleViewer.days[day];
var values = $(schedule).find('[name="newSet"]');
for(var i = 0; i < values.length; i++) {
var time = $($(values[i]).find('td')[0]).html();
if($($(values[i]).find('td')[1]).children()[0]) {
var comment = $($(values[i]).find('td')[1]).children()[0].value;
} else {
var comment = $($(values[i]).find('td')[1]).html();
}
var exId = $(values[i]).attr('exercise');
$.put('/sets', {set: {time: time, comment: comment, exerciseId: exId}}, exportFinished);
}
}
function addOldToExport(day) {
var schedule = deshrimpify.scheduleViewer.days[day];
var values = $(schedule).find('[name="oldSet"]');
for(var i = 0; i < values.length; i++) {
$.put('/sets', {set: {id: $(values[i]).attr('setId'), comment: values[i].value}});
}
}
function exportFinished() {
deshrimpify.scheduleViewer.reloadCurent();
}
}
deshrimpify.scheduleViewer.reloadCurent = function() {
deshrimpify.getLoginStatus(checkStatus);
function checkStatus(info) {
var userId= info.userID;
$.get('/schedules/'+deshrimpify.scheduleViewer.currentId, {userId: userId}, function (resp) {
deshrimpify.scheduleViewer.displayIn($('.schedule-container'), resp);
});
}
}
deshrimpify.scheduleViewer.switchToDay = function (day) {
var currentDay = deshrimpify.scheduleViewer.currentDay;
deshrimpify.scheduleViewer.days[currentDay] = $('#viewedSchedule').clone(); //Save old day
$('#viewedSchedule').replaceWith(deshrimpify.scheduleViewer.days[day]);
deshrimpify.scheduleViewer.currentDay = day;
if(!$('#saveSchedule').length)
$('#viewedSchedule').append('<tr><td><button id="saveSchedule">Save</button></td></tr>');
$('#saveSchedule').click(deshrimpify.scheduleViewer.exportSets);
}
deshrimpify.scheduleViewer.displayIn = function (node, sdl) {
deshrimpify.scheduleViewer.currentId = sdl.id;
var schedule = sdl.days;
var days = Object.keys(schedule);
$(node).empty();
$(node).append('<div class="download-buttons"><a class="download-btn" href="/excel/'+sdl.id+'">Excel</a><a class="download-btn" href="print/'+sdl.id+'">Print</a>')
$(node).append(getPager(days));
$(node).append(getDropDown(days));
$('.schedule-pager a').click(function () {
$('.schedule-pager .active').removeClass('active');
$(this).addClass('active');
deshrimpify.scheduleViewer.switchToDay($(this).html());
});
$('.schedule-dropdown').change(function () {
$('.schedule-pager .active').removeClass('active');
$(this).addClass('active');
deshrimpify.scheduleViewer.switchToDay(this.value);
});
deshrimpify.scheduleViewer.days = {};
days.forEach(generatePage);
finalize();
function generatePage(day, i) {
var page =['<table id="viewedSchedule" class="schedule">',
'<tr>',
'<th>Exercise</th>',
'<th style="width: 300px">Description</th>',
'</tr>'].join("\n");
var daily = schedule[day];
var exercises = Object.keys(daily);
exercises.forEach(appendExercise);
page += '</table>';
deshrimpify.scheduleViewer.days[day] = page;
function appendExercise(exercise, i) {
page += ('<tr ' + ((i+1) % 2 !== 0 ? '' : 'class="alt"')+ '>');
page += '<td>'+exercise+'</td>';
page += '<td>'+daily[exercise].description+'</td>';
page += '<td style="background-color:white"><button id="newSet'+exercise+'" onclick="deshrimpify.scheduleViewer.addSet(\''+exercise+'\', \''+daily[exercise].id+'\')">Add Set...</button></td>',
page += '</tr>';
daily[exercise].sets.forEach(insertSet);
function insertSet(set) {
page += '<tr style="font-size: 0.8em"><td style="margin-left:3.5em">'+set.time+'</td><td><input name="oldSet" setId="'+set.id+'" type="text" value="'+set.comment+'"></input></td></tr>';
}
}
}
function finalize() {
deshrimpify.scheduleViewer.currentDay = days[0];
$(node).append(deshrimpify.scheduleViewer.days[days[0]]);
$($(node).find('table')).append('<tr><td><button id="saveSchedule">Save</button></td></tr>');
$('#saveSchedule').click(deshrimpify.scheduleViewer.exportSets);
}
function getDropDown(days) {
var dropdown = '<select class="schedule-dropdown">';
days.forEach(appendDay);
function appendDay(day, i) {
if(i === 0)
dropdown += '<option>'+day+'</option>';
else
dropdown += '<option>'+day+'</option>';
}
dropdown + '</select>'
return dropdown;
}
function getPager(days) {
var pager = '<ul class="schedule-pager">';
days.forEach(appendDay);
function appendDay(day, i) {
if(i === 0)
pager += '<li><a class="active">'+day+'</a></li>';
else
pager += '<li><a>'+day+'</a></li>';
}
return pager;
}
}
deshrimpify.scheduleViewer.buildList = function(node) {
deshrimpify.getLoginStatus(checkStatus);
var userId;
function checkStatus(info) {
userId= info.userID;
$.get('/schedules', {userId: userId}, insertAll);
}
function insertAll(response) {
$.get('/schedules/'+response.schedules[0], {userId: userId}, function (resp) {
deshrimpify.scheduleViewer.displayIn($('.schedule-container'), resp);
});
response.schedules.forEach(insert);
function insert(id, i) {
$('.schedule-list-dropdown').append('<option>'+id+'</option>');
if(i == 0) {
$(node).append('<p class="active">'+id+'</p>');
} else {
$(node).append('<p>'+id+'</p>');
}
}
$('.schedule-list-dropdown').change(function () {
$.get('/schedules/'+this.value, {userId: userId}, function (resp) {
deshrimpify.scheduleViewer.displayIn($('.schedule-container'), resp);
});
});
$('.schedule-list p').click(function () {
$('.schedule-list .active').removeClass('active');
$(this).addClass('active');
$.get('/schedules/'+$(this).html(), {userId: userId}, function (resp) {
deshrimpify.scheduleViewer.displayIn($('.schedule-container'), resp);
});
});
}
}
|
d34713e5f55502a19c5c1716c0c999accab713f5
|
[
"JavaScript",
"SQL",
"HTML"
] | 7
|
JavaScript
|
peternycander/xmlpub
|
7349edd45fd25cfdf45982ddb05499648197a19c
|
b0379849cd56a79c00b848d043e68717b26e84b4
|
refs/heads/master
|
<repo_name>ReptarAzar/chrome-extension<file_sep>/background.js
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(activeTab)
{
var newURL = "http://socialcode.dev/"; // todo: add post/[post-id]
chrome.tabs.create({ url: newURL });
});
<file_sep>/content.js
// so friendly :)
// console.log("Hello from your SocialCode Chrome extension!");
// get the first link
// var firstHref = $("a[href^='http']").eq(0).attr("href");
// drop it in the console
// console.log(firstHref);
// get the current url so we can pass it to the new tab
var currentURL = window.location.path;
console.log(currentURL);
<file_sep>/README.md
## Setup
- Go to `chrome://extensions/`
- Check developer mode
- Click `Load unpacked extension...`
- Upload this whole repo
*Blam.* Should look like this with a little SocialCode icon in the top right.

* * *
(well done)

|
69846f19fbb426d792db118b31cec7c4137c93fa
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
ReptarAzar/chrome-extension
|
06b3ed5a429e73a28857abcf92470d95a4d73ada
|
f6aa20110c82b36b3d750fde0cdd64f38fd98897
|
refs/heads/master
|
<repo_name>sftcore/gifgal<file_sep>/README.md
Gif Video Gallery
================================
**The setup:**
`apt-get install unzip`
Compile [FFmpeg](https://trac.ffmpeg.org/wiki/UbuntuCompilationGuide) on Ubuntu
install [redis](https://www.digitalocean.com/community/articles/how-to-install-and-use-redis)
install virtualenv
`apt-get install python-virtualenv`
install git
clone git repo
cd to project dir
`cd /root/projects/gif-gallery`
create virtual environment
`virtualenv env`
`sudo apt-get install python-dev`
`source env/bin/activate`
install python dependencies
`pip install -r requirements.txt`
initialize django db
`python manage.py syncdb`
create `gallery_start`
```bash
#!/bin/bash
NAME="gallery_web" # Name of the application
DJANGODIR=/root/projects/gif-gallery # Django project directory
echo "Starting $NAME as `whoami`"
# Activate the virtual environment
cd $DJANGODIR
source ./env/bin/activate
export PATH=$PATH:/root/bin
exec python manage.py runserver 0.0.0.0:8000
```
create `gallery_worker_start`
```bash
#!/bin/bash
NAME="gallery_worker"
DJANGODIR=/root/projects/gif-gallery
echo "Starting $NAME as `whoami`"
# Activate the virtual environment
cd $DJANGODIR
source ./env/bin/activate
export PATH=$PATH:/root/bin
exec python worker.py
```
make scripts executable
```bash
sudo chmod a+x gallery_worker_start
sudo chmod a+x gallery_start
```
install Supervisor
`sudo apt-get install supervisor`
configure Supervisor to run django app and worker
`nano /etc/supervisor/conf.d/gallery.conf`
```bash
[program:gallery]
command = /root/projects/gif-gallery/gallery_start
user = root
stdout_logfile = /root/projects/gif-gallery/supervisor.log
redirect_stderr = true
```
`nano /etc/supervisor/conf.d/gallery_worker.conf`
```bash
[program:gallery_worker]
command = /root/projects/gif-gallery/gallery_worker_start
user = root
stdout_logfile = /root/projects/gif-gallery/supervisor.log
redirect_stderr = true
```
reread configuration files and update to start the apps
`sudo supervisorctl reread`
`sudo supervisorctl update`<file_sep>/requirements.txt
moviepy
numpy
youtube-dl
PIL
django
redis
rq
django-embed-video
requests
django-settings<file_sep>/gif_gallery/models.py
from django.db import models
from embed_video.fields import EmbedVideoField
from django.db.models.signals import post_save
from django.dispatch import receiver
import django_settings
class GifVideo(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
video = EmbedVideoField()
gif_uri = models.CharField(max_length=255, blank=True)
display = models.BooleanField(default=True)
minimum_price = models.FloatField(
default=lambda: django_settings.get('minimum_price'))
first_inflection_point = models.IntegerField(
default=lambda: django_settings.get('first_inflection_point'))
second_inflection_point = models.IntegerField(
default=lambda: django_settings.get('second_inflection_point'))
price_at_second_inflection_point = models.FloatField(
default=lambda: django_settings.get('price_at_second_inflection_point'))
rate_of_growth = models.FloatField(
default=lambda: django_settings.get('rate_of_growth'))
def __unicode__(self):
return self.title
__original_video = None
def __init__(self, *args, **kwargs):
super(GifVideo, self).__init__(*args, **kwargs)
self.__original_video = self.video
def save(self, force_insert=False, force_update=False, *args, **kwargs):
video_changed = self.video != self.__original_video
super(GifVideo, self).save(force_insert, force_update, *args, **kwargs)
self.__original_video = self.video
if video_changed:
self.enqueue_gif_job()
def enqueue_gif_job(self):
from rq import Queue
from worker import conn, listen
q = Queue(listen[0], connection=conn)
from utils import gen_gif
job = q.enqueue_call(
func=gen_gif,
args=(self.pk,),
timeout=1200,
result_ttl=86400) # result expires after 1 day
def calc_price(self, view_count):
P1 = self.minimum_price
V1 = self.first_inflection_point
V2 = self.second_inflection_point
P2 = self.price_at_second_inflection_point
S = self.rate_of_growth
if view_count < V1:
price = P1
elif view_count >= V1 and view_count < V2:
price = P1 + ((P2 - P1)/(V2 - V1)) * (view_count - V1)
else:
price = P2 + S * (view_count - V2)
return price
class Float(django_settings.db.Model):
value = models.FloatField()
class Meta:
abstract = True # it's IMPORTANT - it need to be abstract
django_settings.register(Float)
<file_sep>/gif_gallery/forms.py
from django import forms
from django_settings.forms import SettingForm as SettingFormBase
from gif_gallery.models import GifVideo
class SettingForm(SettingFormBase):
apply_to_exists = forms.BooleanField(required=False, label='Apply to all existing videos')
def save(self, *args, **kwargs):
if self.cleaned_data['apply_to_exists'] and hasattr(GifVideo(), self.instance.name):
GifVideo.objects.all().update(**{self.instance.name: self.cleaned_data['value']})
return super(SettingForm, self).save(*args, **kwargs)
<file_sep>/gif_gallery/admin.py
from django.contrib import admin
from django_settings.admin import SettingAdmin as SettingAdminBase
from models import GifVideo
import django_settings.models
from . import forms
class GifVideoAdmin(admin.ModelAdmin):
model = GifVideo
readonly_fields = ('gif_uri',)
list_display = ('title', 'video', 'display', 'gif_uri')
class SettingAdmin(SettingAdminBase):
form = forms.SettingForm
# Register your models here.
admin.site.register(GifVideo, GifVideoAdmin)
admin.site.unregister(django_settings.models.Setting)
admin.site.register(django_settings.models.Setting, SettingAdmin)<file_sep>/utils.py
import os
import urlparse
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gallery.settings')
from moviepy.editor import VideoFileClip
from gif_gallery.models import GifVideo
import youtube_dl
import requests
def gen_gif(gif_video_id):
gif_video = GifVideo.objects.get(pk=gif_video_id)
vid = download_video(gif_video.video)
clip = VideoFileClip(vid).subclip((0, 0), (0, 5)).resize((320, 240))
clip.to_gif(
"./gif_gallery/static/gif_gallery/gifs/{}.gif".format(vid),
program='ffmpeg',
fps=5)
gif_video.gif_uri = '{}.gif'.format(vid)
gif_video.save()
os.remove(vid)
def download_video(url):
# formats_id - video quality:
# 133 - 240p mp4
# 134 - 360p mp4
# 160 - 192p mp4
ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s', 'format': '133/134/160/best'})
# Add all the available extractors
ydl.add_default_info_extractors()
result = ydl.extract_info(url)
if 'entries' in result:
# Can be a playlist or a list of videos
video = result['entries'][0]
else:
# Just a video
video = result
return video['id']
def get_view_count(url):
ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s'})
ydl.add_default_info_extractors()
result = ydl.extract_info(url, download=False)
if 'entries' in result:
# Can be a playlist or a list of videos
video = result['entries'][0]
else:
# Just a video
video = result
return video['view_count']
def get_view_count_api(url):
video_id = youtube_video_id_from_url(url)
API_URL = 'http://gdata.youtube.com/feeds/api/videos/{}?v=2&alt=jsonc'
r = requests.get(API_URL.format(video_id), timeout=10.0)
data = r.json()
if 'data' in data:
return data['data']['viewCount']
def youtube_video_id_from_url(url):
parsed = urlparse.urlparse(url)
return urlparse.parse_qs(parsed.query)['v'][0]
<file_sep>/gif_gallery/views.py
from django.http import HttpResponse
from django.shortcuts import render
from models import GifVideo
from utils import get_view_count_api
def index(request):
videos = GifVideo.objects.filter(display=True)
return render(request, 'gif_gallery/index.html', {'videos': videos})
def details(request, pk):
video = GifVideo.objects.get(pk=pk)
view_count = get_view_count_api(video.video)
video.view_count = view_count
video.price = video.calc_price(view_count)
return render(request, 'gif_gallery/details.html', {'v': video})
<file_sep>/worker.py
import os
import redis
from rq import Worker, Queue, Connection
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gallery.settings')
listen = ['gif_gallery']
redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')
conn = redis.from_url(redis_url)
if __name__ == '__main__':
with Connection(conn):
worker = Worker(map(Queue, listen))
worker.work()
|
3b14e3d27a8be092e5160999fe359f4356c644bb
|
[
"Markdown",
"Python",
"Text"
] | 8
|
Markdown
|
sftcore/gifgal
|
f6fe9699f18fac1ced99a204c5c36db248626bbc
|
f874e69a5ecbd093c26cfc229acdff9e33ae6478
|
refs/heads/master
|
<repo_name>mstefarov/ClassicWorld.Net<file_sep>/ClassicWorldTest/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using ClassicWorld_NET;
namespace ClassicWorldTest {
public partial class Form1 : Form {
bool Loaded = false;
ClassicWorld Map;
public Form1() {
InitializeComponent();
}
private void btnLoad_Click(object sender, EventArgs e) {
var Result = openMap.ShowDialog();
if (Result == DialogResult.OK) {
Stopwatch Timer = new Stopwatch();
Timer.Start();
Map = new ClassicWorld(openMap.FileName);
Map.Load();
Timer.Stop();
lblTime.Text = "Time: " + Timer.Elapsed.TotalSeconds.ToString();
Loaded = true;
}
}
private void btnSave_Click(object sender, EventArgs e) {
var Result = saveMap.ShowDialog();
if (Result == DialogResult.OK) {
if (Loaded) {
Stopwatch Timer = new Stopwatch();
Timer.Start();
Map.Save(saveMap.FileName);
Timer.Stop();
lblTime.Text = "Time: " + Timer.Elapsed.TotalSeconds.ToString();
} else {
// -- Create a map and save it.
Stopwatch Timer = new Stopwatch();
Timer.Start();
Map = new ClassicWorld(128, 128, 128);
Map.MapName = "New Map!";
Map.Save(saveMap.FileName);
Timer.Stop();
lblTime.Text = "Time: " + Timer.Elapsed.TotalSeconds.ToString();
}
}
}
}
}
|
c4e225e4605db9d4df84db03d0ad92627f6219b8
|
[
"C#"
] | 1
|
C#
|
mstefarov/ClassicWorld.Net
|
c96e8b687b60895ef085b4c2876ab72bc1948450
|
41283b9deca9e059e4ca0fee7bc8f1f14beb99c8
|
refs/heads/master
|
<file_sep>import time
from datetime import date
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from django_countries.fields import CountryField
from rest_framework_jwt.settings import api_settings
from timezone_field import TimeZoneField
from seedorf.utils.email import send_mail
from seedorf.utils.firebase import get_firebase_link
from seedorf.utils.models import BasePropertiesModel
def get_avatar_upload_directory(instance, filename):
# TODO: Test for files names with non latin characters
return f"users/{instance.uuid}/avatars/{filename}"
def max_value_year_of_birth(value):
return MaxValueValidator(date.today().year)(value)
def min_value_year_of_birth(value):
return MinValueValidator(date.today().year - 100)(value)
class User(AbstractUser, BasePropertiesModel):
name = models.CharField(blank=True, default="", max_length=255, null=False, verbose_name=_("Name of User"))
def __str__(self):
return f"{self.email}"
def get_absolute_url(self):
return reverse("users:detail", kwargs={"uuid": self.uuid})
def create_magic_link(self):
try:
# if there is a current active link, delete it
self.magic_link.delete()
except MagicLoginLink.DoesNotExist:
pass
magic_link = MagicLoginLink(user=self)
magic_link.create_token()
magic_link.set_short_link()
magic_link.save()
return magic_link
class Meta:
ordering = ("-created_at",)
@property
def initials(self):
return "".join(i[0] for i in self.name.split()).upper()[0:2]
class UserProfile(BasePropertiesModel):
GENDER_MALE = "MALE"
GENDER_FEMALE = "FEMALE"
GENDER_OTHER = "OTHER"
GENDER_NOT_SPECIFIED = "NOT_SPECIFIED"
GENDERS = (
(GENDER_MALE, _("Male")),
(GENDER_FEMALE, _("Female")),
(GENDER_OTHER, _("Other")),
(GENDER_NOT_SPECIFIED, _("Not Specified")),
)
user = models.OneToOneField(
"users.User",
blank=False,
null=False,
on_delete=models.CASCADE,
related_name="profile",
verbose_name=_("Profile"),
)
sports = models.ManyToManyField(
"sports.Sport", blank=True, related_name="followers", verbose_name=_("Favourite Sports")
)
spots = models.ManyToManyField(
"spots.Spot", blank=True, related_name="followers", verbose_name=_("Favourite Spots")
)
gender = models.CharField(
blank=False, choices=GENDERS, default=GENDER_NOT_SPECIFIED, max_length=25, null=False, verbose_name=_("Gender")
)
year_of_birth = models.PositiveSmallIntegerField(
blank=True,
verbose_name=_("Year of Birth"),
null=True,
validators=[min_value_year_of_birth, max_value_year_of_birth],
)
avatar = models.ImageField(
blank=True, null=True, upload_to=get_avatar_upload_directory, verbose_name=_("Avatar Image")
)
language = models.CharField(
blank=False, choices=settings.LANGUAGES, default="en", max_length=25, null=False, verbose_name=_("Languages")
)
timezone = TimeZoneField(blank=False, default="Europe/Amsterdam", null=False, verbose_name=_("Timezone"))
country = CountryField(blank=True, null=False, verbose_name=_("Country"))
bio = models.TextField(blank=True, default="", null=False, verbose_name=_("Bio"))
class Meta:
ordering = ("-created_at",)
def __str__(self):
return f"{self.user.email}"
# # is_under_age
# # company
# # two_factor_authentication
# # plan
# # blocks
# # emails
# # followers
class MagicLoginLink(BasePropertiesModel):
user = models.OneToOneField(
"users.User",
blank=False,
null=False,
on_delete=models.CASCADE,
related_name="magic_link",
verbose_name=_("Magic login link"),
)
token = models.TextField(blank=False, null=False, verbose_name=_("Token"), unique=True)
short_link = models.CharField(blank=False, null=False, max_length=50, verbose_name=_("Link"))
def create_token(self):
jwt_payload = {"email": self.user.email, "name": self.user.name, "iat": int(time.time())}
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
self.token = jwt_encode_handler(jwt_payload)
def set_short_link(self):
self.short_link = get_firebase_link(f"magic_link_login?token={self.token}")
def mail(self):
context = {"name": self.user.name, "action_url": str(self)}
send_mail(
to=self.user.email,
template_prefix="MagicLoginLink",
subject=_("Login"),
language=self.user.profile.language,
context=context,
)
def __str__(self):
return f"{self.short_link}"
<file_sep>import factory
from ..models import Sport
class SportFactory(factory.django.DjangoModelFactory):
category = factory.Iterator(Sport.SPORTS, getter=lambda c: c[0])
name = factory.Faker("word")
description = factory.Faker("text")
class Meta:
model = Sport
<file_sep>require('../../node_modules/bootstrap-sweetalert/dev/sweetalert.es6.js');
<file_sep>from django.contrib import admin
from .models import Spot, SpotAmenity, SpotImage, SpotOpeningTime
class SpotOpeningTimeAdmin(admin.StackedInline):
model = SpotOpeningTime
class SpotImageAdmin(admin.StackedInline):
model = SpotImage
class SpotAmenityAdmin(admin.StackedInline):
model = SpotAmenity
class SpotAdmin(admin.ModelAdmin):
search_fields = ["name"]
readonly_fields = ("uuid", "created_at", "modified_at", "deleted_at")
list_display = ("name", "owner", "is_verified", "is_permanently_closed", "is_public", "is_temporary", "modified_at")
list_filter = ("sports__category", "is_verified", "is_public")
inlines = [SpotImageAdmin, SpotOpeningTimeAdmin, SpotAmenityAdmin]
fieldsets = (
(
None,
{
"fields": (
"uuid",
"name",
"slug",
"owner",
"address",
"description",
"logo",
"homepage_url",
"is_verified",
"is_permanently_closed",
"is_public",
"is_temporary",
"establishment_date",
"closure_date",
"sports",
)
},
),
("Audit", {"classes": ("collapse",), "fields": ("created_at", "modified_at", "deleted_at")}),
)
admin.site.register(Spot, SpotAdmin)
<file_sep>const path = require('path')
const glob = require('glob')
// -------------------------------------------------------------------------------
// Config
const env = require('gulp-environment')
process.env.NODE_ENV = env.current.name
const conf = (() => {
const _conf = require('./build-config')
return require('deepmerge').all([{}, _conf.base || {}, _conf[process.env.NODE_ENV] || {}])
})()
conf.buildPath = path.resolve(__dirname, conf.buildPath)
// -------------------------------------------------------------------------------
// Modules
const gulp = require('gulp')
const webpack = require('webpack')
const sass = require('gulp-sass')
const gutil = require('gulp-util')
const autoprefixer = require('gulp-autoprefixer')
const rename = require('gulp-rename')
const replace = require('gulp-replace')
const gulpIf = require('gulp-if')
const sourcemaps = require('gulp-sourcemaps')
const del = require('del')
const runSequence = require('run-sequence').use(gulp)
// -------------------------------------------------------------------------------
// Utilities
function getSrc(...src) {
return src.concat(conf.exclude.map(d => `!${d}/**/*`))
}
// -------------------------------------------------------------------------------
// Clean build directory
gulp.task('clean', function() {
return del([conf.buildPath], { force: true })
})
// -------------------------------------------------------------------------------
// Build css
gulp.task('build:css', function() {
return gulp
.src(getSrc('**/*.scss', '!**/_*.scss'), { base: '.' })
.pipe(gulpIf(conf.sourcemaps, sourcemaps.init()))
.pipe(sass({
outputStyle: conf.minify ? 'compressed' : 'nested'
}).on('error', sass.logError))
.pipe(gulpIf(conf.sourcemaps, sourcemaps.write()))
.pipe(gulpIf(conf.sourcemaps, sourcemaps.init({ loadMaps: true })))
.pipe(autoprefixer({
browsers: [ '> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1', 'ie > 9' ]
}))
.pipe(gulpIf(conf.sourcemaps, sourcemaps.write()))
.pipe(gulp.dest(conf.buildPath))
})
// -------------------------------------------------------------------------------
// Build js
gulp.task('build:js', function(cb) {
setTimeout(function() {
webpack(require('./webpack.config'), (err, stats) => {
if (err) {
gutil.log(gutil.colors.gray('Webpack error:'), gutil.colors.red(err.stack || err))
if (err.details) gutil.log(gutil.colors.gray('Webpack error details:'), err.details)
return cb()
}
const info = stats.toJson()
if (stats.hasErrors()) {
info.errors.forEach(e => gutil.log(gutil.colors.gray('Webpack compilation error:'), gutil.colors.red(e)))
}
if (stats.hasWarnings()) {
info.warnings.forEach(w => gutil.log(gutil.colors.gray('Webpack compilation warning:'), gutil.colors.yellow(w)))
}
// Print log
gutil.log(stats.toString({
colors: gutil.colors.supportsColor,
hash: false,
timings: false,
chunks: false,
chunkModules: false,
modules: false,
children: true,
version: true,
cached: false,
cachedAssets: false,
reasons: false,
source: false,
errorDetails: false
}))
cb()
})
}, 1)
})
// -------------------------------------------------------------------------------
// Build fonts
const FONT_TASKS = [
{ name: 'fontawesome', path: 'node_modules/@fortawesome/fontawesome-free/webfonts/*' },
{ name: 'linearicons', path: 'node_modules/linearicons/dist/web-font/fonts/*' },
{ name: 'pe-icon-7-stroke', path: 'node_modules/pixeden-stroke-7-icon/pe-icon-7-stroke/fonts/*' },
{ name: 'open-iconic', path: 'node_modules/open-iconic/font/fonts/*' },
{ name: 'ionicons', path: 'node_modules/ionicons/dist/fonts/*' }
].reduce(function(tasks, font) {
const taskName = `build:fonts:${font.name}`
gulp.task(taskName, () =>
gulp.src(font.path).pipe(gulp.dest(path.join(conf.buildPath, 'fonts', font.name)))
)
return tasks.concat([taskName])
}, [])
// Copy linearicons' style.css
FONT_TASKS.push('build:fonts:linearicons:css')
gulp.task('build:fonts:linearicons:css', function() {
return gulp
.src('node_modules/linearicons/dist/web-font/style.css')
.pipe(replace(/'fonts\//g, '\'linearicons/'))
.pipe(rename({ basename: 'linearicons' }))
.pipe(gulp.dest(path.join(conf.buildPath, 'fonts')))
})
gulp.task('build:fonts', FONT_TASKS)
// -------------------------------------------------------------------------------
// Copy
gulp.task('build:copy', function() {
return gulp
.src(getSrc('**/*.png', '**/*.gif', '**/*.jpg', '**/*.jpeg', '**/*.svg', '**/*.swf', '**/*.eot', '**/*.ttf', '**/*.woff', '**/*.woff2', '**/*.mp4', '**/*.mp3'), { base: '.' })
.pipe(gulp.dest(conf.buildPath))
})
// -------------------------------------------------------------------------------
// Watch
gulp.task('watch', function() {
gulp.watch(getSrc('**/*.scss', '!fonts/**/*.scss'), ['build:css'])
gulp.watch(getSrc('fonts/**/*.scss'), ['build:css', 'build:fonts'])
gulp.watch(getSrc('**/*.@(js|es6)'), ['build:js'])
gulp.watch(getSrc('**/*.png', '**/*.gif', '**/*.jpg', '**/*.jpeg', '**/*.svg', '**/*.swf'), ['build:copy'])
})
// -------------------------------------------------------------------------------
// Build
gulp.task('build', function(cb) {
runSequence.apply(runSequence, (conf.cleanBuild ? ['clean'] : []).concat([
['build:css', 'build:js', 'build:fonts', 'build:copy'],
cb
]))
})
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-05-02 08:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("games", "0001_initial")]
operations = [
migrations.AlterField(
model_name="game",
name="end_time",
field=models.DateTimeField(
blank=True, help_text="End time of the game in UTC.", null=True, verbose_name="End Time (UTC)"
),
),
migrations.AlterField(
model_name="game",
name="rsvp_close_time",
field=models.DateTimeField(
blank=True,
help_text="UTC time after that RSVPs will no longer be accepted, though organizers may close RSVPs earlier",
null=True,
verbose_name="RSVP Close Time (UTC)",
),
),
migrations.AlterField(
model_name="game",
name="rsvp_open_time",
field=models.DateTimeField(
blank=True,
help_text="UTC time before that RSVPs will no longer be accepted, though organizers may close RSVPs earlier",
null=True,
verbose_name="RSVP Open Time (UTC)",
),
),
migrations.AlterField(
model_name="game",
name="start_time",
field=models.DateTimeField(
blank=True, help_text="Start time of the game in UTC.", null=True, verbose_name="Start Time (UTC)"
),
),
]
<file_sep>import Quill from '../../node_modules/quill/dist/quill.js';
export { Quill };
<file_sep>import * as Flow from '../../node_modules/@flowjs/flow.js/src/flow.js';
export { Flow };
<file_sep>require('../../node_modules/bootstrap-duallistbox/src/jquery.bootstrap-duallistbox.js');
<file_sep>from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from django.utils.translation import ugettext_lazy as _
from .models import User, UserProfile
class SportySpotsUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = User
class SportySpotsUserCreationForm(UserCreationForm):
error_message = UserCreationForm.error_messages.update(
{"duplicate_username": _("This username has already been taken.")}
)
class Meta(UserCreationForm.Meta):
model = User
def clean_username(self):
username = self.cleaned_data["username"]
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages["duplicate_username"])
class UserProfileInline(admin.StackedInline):
model = UserProfile
@admin.register(User)
class SportySpotsUserAdmin(AuthUserAdmin):
form = SportySpotsUserChangeForm
add_form = SportySpotsUserCreationForm
fieldsets = (("User Profile", {"fields": ("uuid", "name")}),) + AuthUserAdmin.fieldsets
list_display = ("username", "email", "name", "is_superuser")
readonly_fields = ("uuid", "created_at", "modified_at")
search_fields = ["name"]
inlines = [UserProfileInline]
<file_sep>require('../../node_modules/nestable/jquery.nestable.js');
<file_sep>from django.apps import AppConfig
class ReactionsConfig(AppConfig):
name = "seedorf.reactions"
verbose_name = "Reactions"
<file_sep>var MarkdownCls = require('../../node_modules/markdown/lib/markdown.js');
var markdown = {
Markdown: MarkdownCls,
parse: MarkdownCls.parse,
toHTML: MarkdownCls.toHTML,
toHTMLTree: MarkdownCls.toHTMLTree,
renderJsonML: MarkdownCls.renderJsonML
};
export { markdown };
<file_sep>// Add onHover event for dropdowns
(function($) {
if (!$ || !$.fn) return
const SELECTOR = '[data-toggle=dropdown][data-trigger=hover]'
const TIMEOUT = 150
function openDropdown($i) {
let t = $i.data('dd-timeout')
if (t) {
clearTimeout(t)
t = null
$i.data('dd-timeout', t)
}
if ($i.attr('aria-expanded') !== 'true') $i.dropdown('toggle')
}
function closeDropdown($i) {
let t = $i.data('dd-timeout')
if (t) clearTimeout(t)
t = setTimeout(() => {
let t2 = $i.data('dd-timeout')
if (t2) {
clearTimeout(t2)
t2 = null
$i.data('dd-timeout', t2)
}
if ($i.attr('aria-expanded') === 'true') $i.dropdown('toggle')
}, TIMEOUT)
$i.data('dd-timeout', t)
}
$(function() {
$('body')
.on('mouseenter', `${SELECTOR}, ${SELECTOR} ~ .dropdown-menu`, function() {
const $toggle = $(this).hasClass('dropdown-toggle') ? $(this) : $(this).prev('.dropdown-toggle')
const $dropdown = $(this).hasClass('dropdown-menu') ? $(this) : $(this).next('.dropdown-menu')
if (window.getComputedStyle($dropdown[0], null).getPropertyValue('position') === 'static') return
// Set hovered flag
if ($(this).is(SELECTOR)) {
$(this).data('hovered', true)
}
openDropdown(
$(this).hasClass('dropdown-toggle') ? $(this) : $(this).prev('.dropdown-toggle')
)
})
.on('mouseleave', `${SELECTOR}, ${SELECTOR} ~ .dropdown-menu`, function() {
const $toggle = $(this).hasClass('dropdown-toggle') ? $(this) : $(this).prev('.dropdown-toggle')
const $dropdown = $(this).hasClass('dropdown-menu') ? $(this) : $(this).next('.dropdown-menu')
if (window.getComputedStyle($dropdown[0], null).getPropertyValue('position') === 'static') return
// Remove hovered flag
if ($(this).is(SELECTOR)) {
$(this).data('hovered', false)
}
closeDropdown(
$(this).hasClass('dropdown-toggle') ? $(this) : $(this).prev('.dropdown-toggle')
)
})
.on('hide.bs.dropdown', function(e) {
if ($(this).find(SELECTOR).data('hovered')) e.preventDefault()
})
})
})(window.jQuery)
<file_sep>require('../../node_modules/bootstrap-sortable/Scripts/bootstrap-sortable.js');
<file_sep>from django.conf import settings
from hashids import Hashids
class HashSlugMixin:
"""
NOTE: Updating the secret key would break all bookmarks
NOTE: All objects of different classes with the same id will have the same hashid
NOTE: Maybe its a better idea not to expose the ids via api or not enable retrieval of objects by id via api
NOTE: Maybe only enable retrieval of objects using uuid
"""
hasher = Hashids(salt=settings.SECRET_KEY, min_length=6)
@property
def hash_slug(self):
return self.hasher.encode(self.id)
def reverse_hash_slug(self, hash_slug):
return self.hasher.decode(hash_slug)
<file_sep>from django_filters import rest_framework as filters
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from seedorf.utils.regex import UUID as REGEX_UUID
from .filters import GameFilter, RsvpStatusFilter
from .models import Game, RsvpStatus
from .serializers import GameSerializer, RsvpStatusNestedSerializer
class GameViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows games to be viewed or edited.
"""
queryset = Game.objects.filter(deleted_at=None).order_by("-start_time")
serializer_class = GameSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
permission_classes = (IsAuthenticatedOrReadOnly,)
filter_backends = (filters.DjangoFilterBackend,)
filter_class = GameFilter
class GameRsvpStatusNestedViewset(viewsets.ModelViewSet):
"""
API endpoint that allows game RSVPs to be viewed or edited.
"""
serializer_class = RsvpStatusNestedSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
permission_classes = (IsAuthenticatedOrReadOnly,)
filter_backends = (filters.DjangoFilterBackend,)
filter_class = RsvpStatusFilter
def get_queryset(self):
return RsvpStatus.objects.filter(game__uuid=self.kwargs["game_uuid"])
<file_sep>FROM tutum/nginx
RUN rm /etc/nginx/sites-enabled/default
ADD ./compose/production/nginx/sites-enabled/ /etc/nginx/sites-enabled
EXPOSE 80
<file_sep>import urllib
import requests
from django.conf import settings
def get_firebase_link(app_link, unguessable=True, **kwargs):
# REF: https://firebase.google.com/docs/reference/dynamic-links/link-shortener
# REF: https://firebase.google.com/docs/dynamic-links/create-manually
firebase_url = f"https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key={settings.FIREBASE_WEB_API_KEY}"
long_dynamic_link_base = "https://sportyspots.page.link/?"
long_dynamic_link_args = {
"link": f"https://app.sportyspots.com/{app_link}",
"apn": "com.sportyspots.android",
"ibi": "com.sportyspots.ios",
"afl": "https://play.google.com/store/apps/details?id=com.sportyspots.android",
"ifl": "https://itunes.apple.com/nl/app/sportyspots/id1391625376",
"ofl": "https://www.sportyspots.com",
}
long_dynamic_link_args.update(kwargs)
long_dynamic_link_url = long_dynamic_link_base + urllib.parse.urlencode(long_dynamic_link_args)
post_body = {
"longDynamicLink": long_dynamic_link_url,
"suffix": {"option": "UNGUESSABLE" if unguessable else "SHORT"},
}
result = requests.post(firebase_url, json=post_body)
return result.json()["shortLink"]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-04-29 19:27
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import django_countries.fields
import seedorf.users.models
import timezone_field.fields
import uuid
class Migration(migrations.Migration):
dependencies = [("sports", "0001_initial"), ("spots", "0001_initial"), ("users", "0001_initial")]
operations = [
migrations.CreateModel(
name="UserProfile",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("uuid", models.UUIDField(default=uuid.uuid4, editable=False, verbose_name="Unique Identifier")),
(
"created_at",
models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name="Created At"),
),
("modified_at", models.DateTimeField(auto_now=True, verbose_name="Modified At")),
("deleted_at", models.DateTimeField(blank=True, editable=False, null=True, verbose_name="Deleted At")),
(
"gender",
models.CharField(
choices=[
("MALE", "Male"),
("FEMALE", "Female"),
("OTHER", "Other"),
("NOT_SPECIFIED", "Not Specified"),
],
default="NOT_SPECIFIED",
max_length=25,
verbose_name="Gender",
),
),
(
"year_of_birth",
models.PositiveSmallIntegerField(
blank=True,
null=True,
validators=[
seedorf.users.models.min_value_year_of_birth,
seedorf.users.models.max_value_year_of_birth,
],
verbose_name="Year of Birth",
),
),
(
"avatar",
models.ImageField(
blank=True,
upload_to=seedorf.users.models.get_avatar_upload_directory,
verbose_name="Avatar Image",
),
),
(
"language",
models.CharField(
choices=[("en", "English"), ("nl", "Dutch")],
default="en",
max_length=25,
verbose_name="Languages",
),
),
("timezone", timezone_field.fields.TimeZoneField(default="Europe/Amsterdam", verbose_name="Timezone")),
("country", django_countries.fields.CountryField(blank=True, max_length=2, verbose_name="Country")),
("bio", models.TextField(blank=True, default="", verbose_name="Bio")),
(
"sports",
models.ManyToManyField(
related_name="followers", to="sports.Sport", verbose_name="Favourite Sports"
),
),
(
"spots",
models.ManyToManyField(related_name="followers", to="spots.Spot", verbose_name="Favourite Spots"),
),
],
options={"abstract": False},
),
migrations.AddField(
model_name="user",
name="created_at",
field=models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name="Created At"),
),
migrations.AddField(
model_name="user",
name="deleted_at",
field=models.DateTimeField(blank=True, editable=False, null=True, verbose_name="Deleted At"),
),
migrations.AddField(
model_name="user", name="modified_at", field=models.DateTimeField(auto_now=True, verbose_name="Modified At")
),
migrations.AddField(
model_name="user",
name="uuid",
field=models.UUIDField(default=uuid.uuid4, editable=False, verbose_name="Unique Identifier"),
),
migrations.AlterField(
model_name="user",
name="name",
field=models.CharField(blank=True, default="", max_length=255, verbose_name="Name of User"),
),
migrations.AddField(
model_name="userprofile",
name="user",
field=models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="profile",
to=settings.AUTH_USER_MODEL,
verbose_name="Profile",
),
),
]
<file_sep># Generated by Django 2.1.2 on 2019-03-29 13:43
from django.db import migrations
import wagtail.core.blocks
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [("cms", "0002_create_homepage")]
operations = [
migrations.AlterField(
model_name="pagehome",
name="body",
field=wagtail.core.fields.StreamField(
[
(
"hero_header",
wagtail.core.blocks.StructBlock(
[
("heading", wagtail.core.blocks.CharBlock(default="")),
("sub_heading", wagtail.core.blocks.CharBlock(default="")),
]
),
),
(
"icon_banner",
wagtail.core.blocks.StructBlock(
[
(
"background",
wagtail.core.blocks.ChoiceBlock(
choices=[
("bg-white", "white"),
("bg-lightest", "gray"),
("bg-yellow", "yellow"),
("bg-transparent", "transparent"),
]
),
),
("title", wagtail.core.blocks.CharBlock()),
("description", wagtail.core.blocks.TextBlock()),
(
"icon",
wagtail.core.blocks.ChoiceBlock(
choices=[
("lnr-home", "lnr-home"),
("lnr-apartment", "lnr-apartment"),
("lnr-pencil", "lnr-pencil"),
("lnr-magic-wand", "lnr-magic-wand"),
("lnr-drop", "lnr-drop"),
("lnr-lighter", "lnr-lighter"),
("lnr-poop", "lnr-poop"),
("lnr-sun", "lnr-sun"),
("lnr-moon", "lnr-moon"),
("lnr-cloud", "lnr-cloud"),
("lnr-cloud-upload", "lnr-cloud-upload"),
("lnr-cloud-download", "lnr-cloud-download"),
("lnr-cloud-sync", "lnr-cloud-sync"),
("lnr-cloud-check", "lnr-cloud-check"),
("lnr-database", "lnr-database"),
("lnr-lock", "lnr-lock"),
("lnr-cog", "lnr-cog"),
("lnr-trash", "lnr-trash"),
("lnr-dice", "lnr-dice"),
("lnr-heart", "lnr-heart"),
("lnr-star", "lnr-star"),
("lnr-star-half", "lnr-star-half"),
("lnr-star-empty", "lnr-star-empty"),
("lnr-flag", "lnr-flag"),
("lnr-envelope", "lnr-envelope"),
("lnr-paperclip", "lnr-paperclip"),
("lnr-inbox", "lnr-inbox"),
("lnr-eye", "lnr-eye"),
("lnr-printer", "lnr-printer"),
("lnr-file-empty", "lnr-file-empty"),
("lnr-file-add", "lnr-file-add"),
("lnr-enter", "lnr-enter"),
("lnr-exit", "lnr-exit"),
("lnr-graduation-hat", "lnr-graduation-hat"),
("lnr-license", "lnr-license"),
("lnr-music-note", "lnr-music-note"),
("lnr-film-play", "lnr-film-play"),
("lnr-camera-video", "lnr-camera-video"),
("lnr-camera", "lnr-camera"),
("lnr-picture", "lnr-picture"),
("lnr-book", "lnr-book"),
("lnr-bookmark", "lnr-bookmark"),
("lnr-user", "lnr-user"),
("lnr-users", "lnr-users"),
("lnr-shirt", "lnr-shirt"),
("lnr-store", "lnr-store"),
("lnr-cart", "lnr-cart"),
("lnr-tag", "lnr-tag"),
("lnr-phone-handset", "lnr-phone-handset"),
("lnr-phone", "lnr-phone"),
("lnr-pushpin", "lnr-pushpin"),
("lnr-map-marker", "lnr-map-marker"),
("lnr-map", "lnr-map"),
("lnr-location", "lnr-location"),
("lnr-calendar-full", "lnr-calendar-full"),
("lnr-keyboard", "lnr-keyboard"),
("lnr-spell-check", "lnr-spell-check"),
("lnr-screen", "lnr-screen"),
("lnr-smartphone", "lnr-smartphone"),
("lnr-tablet", "lnr-tablet"),
("lnr-laptop", "lnr-laptop"),
("lnr-laptop-phone", "lnr-laptop-phone"),
("lnr-power-switch", "lnr-power-switch"),
("lnr-bubble", "lnr-bubble"),
("lnr-heart-pulse", "lnr-heart-pulse"),
("lnr-construction", "lnr-construction"),
("lnr-pie-chart", "lnr-pie-chart"),
("lnr-chart-bars", "lnr-chart-bars"),
("lnr-gift", "lnr-gift"),
("lnr-diamond", "lnr-diamond"),
("lnr-linearicons", "lnr-linearicons"),
("lnr-dinner", "lnr-dinner"),
("lnr-coffee-cup", "lnr-coffee-cup"),
("lnr-leaf", "lnr-leaf"),
("lnr-paw", "lnr-paw"),
("lnr-rocket", "lnr-rocket"),
("lnr-briefcase", "lnr-briefcase"),
("lnr-bus", "lnr-bus"),
("lnr-car", "lnr-car"),
("lnr-train", "lnr-train"),
("lnr-bicycle", "lnr-bicycle"),
("lnr-wheelchair", "lnr-wheelchair"),
("lnr-select", "lnr-select"),
("lnr-earth", "lnr-earth"),
("lnr-smile", "lnr-smile"),
("lnr-sad", "lnr-sad"),
("lnr-neutral", "lnr-neutral"),
("lnr-mustache", "lnr-mustache"),
("lnr-alarm", "lnr-alarm"),
("lnr-bullhorn", "lnr-bullhorn"),
("lnr-volume-high", "lnr-volume-high"),
("lnr-volume-medium", "lnr-volume-medium"),
("lnr-volume-low", "lnr-volume-low"),
("lnr-volume", "lnr-volume"),
("lnr-mic", "lnr-mic"),
("lnr-hourglass", "lnr-hourglass"),
("lnr-undo", "lnr-undo"),
("lnr-redo", "lnr-redo"),
("lnr-sync", "lnr-sync"),
("lnr-history", "lnr-history"),
("lnr-clock", "lnr-clock"),
("lnr-download", "lnr-download"),
("lnr-upload", "lnr-upload"),
("lnr-enter-down", "lnr-enter-down"),
("lnr-exit-up", "lnr-exit-up"),
("lnr-bug", "lnr-bug"),
("lnr-code", "lnr-code"),
("lnr-link", "lnr-link"),
("lnr-unlink", "lnr-unlink"),
("lnr-thumbs-up", "lnr-thumbs-up"),
("lnr-thumbs-down", "lnr-thumbs-down"),
("lnr-magnifier", "lnr-magnifier"),
("lnr-cross", "lnr-cross"),
("lnr-menu", "lnr-menu"),
("lnr-list", "lnr-list"),
("lnr-chevron-up", "lnr-chevron-up"),
("lnr-chevron-down", "lnr-chevron-down"),
("lnr-chevron-left", "lnr-chevron-left"),
("lnr-chevron-right", "lnr-chevron-right"),
("lnr-arrow-up", "lnr-arrow-up"),
("lnr-arrow-down", "lnr-arrow-down"),
("lnr-arrow-left", "lnr-arrow-left"),
("lnr-arrow-right", "lnr-arrow-right"),
("lnr-move", "lnr-move"),
("lnr-warning", "lnr-warning"),
("lnr-question-circle", "lnr-question-circle"),
("lnr-menu-circle", "lnr-menu-circle"),
("lnr-checkmark-circle", "lnr-checkmark-circle"),
("lnr-cross-circle", "lnr-cross-circle"),
("lnr-plus-circle", "lnr-plus-circle"),
("lnr-circle-minus", "lnr-circle-minus"),
("lnr-arrow-up-circle", "lnr-arrow-up-circle"),
("lnr-arrow-down-circle", "lnr-arrow-down-circle"),
("lnr-arrow-left-circle", "lnr-arrow-left-circle"),
("lnr-arrow-right-circle", "lnr-arrow-right-circle"),
("lnr-chevron-up-circle", "lnr-chevron-up-circle"),
("lnr-chevron-down-circle", "lnr-chevron-down-circle"),
("lnr-chevron-left-circle", "lnr-chevron-left-circle"),
("lnr-chevron-right-circle", "lnr-chevron-right-circle"),
("lnr-crop", "lnr-crop"),
("lnr-frame-expand", "lnr-frame-expand"),
("lnr-frame-contract", "lnr-frame-contract"),
("lnr-layers", "lnr-layers"),
("lnr-funnel", "lnr-funnel"),
("lnr-text-format", "lnr-text-format"),
("lnr-text-format-remove", "lnr-text-format-remove"),
("lnr-text-size", "lnr-text-size"),
("lnr-bold", "lnr-bold"),
("lnr-italic", "lnr-italic"),
("lnr-underline", "lnr-underline"),
("lnr-strikethrough", "lnr-strikethrough"),
("lnr-highlight", "lnr-highlight"),
("lnr-text-align-left", "lnr-text-align-left"),
("lnr-text-align-center", "lnr-text-align-center"),
("lnr-text-align-right", "lnr-text-align-right"),
("lnr-text-align-justify", "lnr-text-align-justify"),
("lnr-line-spacing", "lnr-line-spacing"),
("lnr-indent-increase", "lnr-indent-increase"),
("lnr-indent-decrease", "lnr-indent-decrease"),
("lnr-pilcrow", "lnr-pilcrow"),
("lnr-direction-ltr", "lnr-direction-ltr"),
("lnr-direction-rtl", "lnr-direction-rtl"),
("lnr-page-break", "lnr-page-break"),
("lnr-sort-alpha-asc", "lnr-sort-alpha-asc"),
("lnr-sort-amount-asc", "lnr-sort-amount-asc"),
("lnr-hand", "lnr-hand"),
("lnr-pointer-up", "lnr-pointer-up"),
("lnr-pointer-right", "lnr-pointer-right"),
("lnr-pointer-down", "lnr-pointer-down"),
("lnr-pointer-left", "lnr-pointer-left"),
]
),
),
]
),
),
(
"video_banner",
wagtail.core.blocks.StructBlock(
[
(
"background",
wagtail.core.blocks.ChoiceBlock(
choices=[
("bg-white", "white"),
("bg-lightest", "gray"),
("bg-yellow", "yellow"),
("bg-transparent", "transparent"),
]
),
),
("title", wagtail.core.blocks.CharBlock(default="", required=False)),
("description", wagtail.core.blocks.TextBlock(default="")),
("youtube_video_id", wagtail.core.blocks.CharBlock(default="")),
]
),
),
(
"app_description",
wagtail.core.blocks.StructBlock(
[
(
"background",
wagtail.core.blocks.ChoiceBlock(
choices=[
("bg-white", "white"),
("bg-lightest", "gray"),
("bg-yellow", "yellow"),
("bg-transparent", "transparent"),
]
),
),
("title", wagtail.core.blocks.CharBlock(default="", required=False)),
("description", wagtail.core.blocks.TextBlock(default="")),
]
),
),
(
"app_features",
wagtail.core.blocks.StructBlock(
[
(
"background",
wagtail.core.blocks.ChoiceBlock(
choices=[
("bg-white", "white"),
("bg-lightest", "gray"),
("bg-yellow", "yellow"),
("bg-transparent", "transparent"),
]
),
),
("title", wagtail.core.blocks.CharBlock(default="", required=False)),
("description", wagtail.core.blocks.TextBlock(default="")),
]
),
),
(
"app_stores",
wagtail.core.blocks.StructBlock(
[
(
"background",
wagtail.core.blocks.ChoiceBlock(
choices=[
("bg-white", "white"),
("bg-lightest", "gray"),
("bg-yellow", "yellow"),
("bg-transparent", "transparent"),
]
),
),
("title", wagtail.core.blocks.CharBlock(default="", required=False)),
("description", wagtail.core.blocks.TextBlock(default="")),
]
),
),
(
"newsletter",
wagtail.core.blocks.StructBlock(
[
(
"background",
wagtail.core.blocks.ChoiceBlock(
choices=[
("bg-white", "white"),
("bg-lightest", "gray"),
("bg-yellow", "yellow"),
("bg-transparent", "transparent"),
]
),
),
("title", wagtail.core.blocks.CharBlock(default="", required=False)),
("description", wagtail.core.blocks.TextBlock(default="")),
]
),
),
(
"press",
wagtail.core.blocks.StructBlock(
[
(
"background",
wagtail.core.blocks.ChoiceBlock(
choices=[
("bg-white", "white"),
("bg-lightest", "gray"),
("bg-yellow", "yellow"),
("bg-transparent", "transparent"),
]
),
),
("title", wagtail.core.blocks.CharBlock(default="", required=False)),
("description", wagtail.core.blocks.TextBlock(default="")),
]
),
),
(
"stats",
wagtail.core.blocks.StructBlock(
[
(
"background",
wagtail.core.blocks.ChoiceBlock(
choices=[
("bg-white", "white"),
("bg-lightest", "gray"),
("bg-yellow", "yellow"),
("bg-transparent", "transparent"),
]
),
),
("title", wagtail.core.blocks.CharBlock(default="", required=False)),
("description", wagtail.core.blocks.TextBlock(default="")),
]
),
),
(
"team",
wagtail.core.blocks.StructBlock(
[
(
"background",
wagtail.core.blocks.ChoiceBlock(
choices=[
("bg-white", "white"),
("bg-lightest", "gray"),
("bg-yellow", "yellow"),
("bg-transparent", "transparent"),
]
),
),
("title", wagtail.core.blocks.CharBlock(default="", required=False)),
("description", wagtail.core.blocks.TextBlock(default="")),
]
),
),
(
"user_quotes",
wagtail.core.blocks.StructBlock(
[
(
"background",
wagtail.core.blocks.ChoiceBlock(
choices=[
("bg-white", "white"),
("bg-lightest", "gray"),
("bg-yellow", "yellow"),
("bg-transparent", "transparent"),
]
),
),
("title", wagtail.core.blocks.CharBlock(default="", required=False)),
("description", wagtail.core.blocks.TextBlock(default="")),
]
),
),
(
"contact",
wagtail.core.blocks.StructBlock(
[
(
"background",
wagtail.core.blocks.ChoiceBlock(
choices=[
("bg-white", "white"),
("bg-lightest", "gray"),
("bg-yellow", "yellow"),
("bg-transparent", "transparent"),
]
),
),
("title", wagtail.core.blocks.CharBlock(default="", required=False)),
("description", wagtail.core.blocks.TextBlock(default="")),
]
),
),
(
"icon_features_promo",
wagtail.core.blocks.StructBlock(
[
(
"background",
wagtail.core.blocks.ChoiceBlock(
choices=[
("bg-white", "white"),
("bg-lightest", "gray"),
("bg-yellow", "yellow"),
("bg-transparent", "transparent"),
]
),
),
("title", wagtail.core.blocks.CharBlock()),
("description", wagtail.core.blocks.TextBlock()),
]
),
),
],
blank=True,
null=True,
),
)
]
<file_sep>from datetime import datetime, timedelta
import pendulum
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django_fsm import TransitionNotAllowed
from rest_framework import serializers
from seedorf.sports.models import Sport
from seedorf.spots.models import Spot
from seedorf.users.serializers import UserSerializer
from .models import Game, RsvpStatus
class RsvpStatusNestedSerializer(serializers.ModelSerializer):
# NOTE: User is readonly as it is get/set direct from the request
# TODO: Only the logged in user can create an rsvp for himself/ herself
# TODO: Check if the game is invite only and see if the user was invited
# TODO: Check if the game max users count has been reached.
user = UserSerializer(read_only=True, many=False, required=False)
class Meta:
model = RsvpStatus
fields = ("uuid", "status", "user", "created_at", "modified_at")
read_only_fields = ("uuid", "user", "created_at", "modified_at")
def validate_status(self, status: str) -> str:
if not self.instance:
if status not in [
RsvpStatus.STATUS_ACCEPTED,
RsvpStatus.STATUS_ATTENDING,
RsvpStatus.STATUS_DECLINED,
RsvpStatus.STATUS_INTERESTED,
]:
raise serializers.ValidationError(
_("Only Accepted, Attending, Declined and Interested statuses are allowed while creating RSVP")
)
return status
def create(self, validated_data):
if self.context["view"].basename == "game-rsvps":
game_uuid = self.context["view"].kwargs["game_uuid"]
game = Game.objects.get(uuid=game_uuid)
user = self.context["request"].user
status = validated_data["status"]
rsvp = RsvpStatus.objects.create(game=game, user=user)
rsvp.transition_status(status)
rsvp.save()
return rsvp
return {}
def update(self, instance, validated_data):
if self.context["view"].basename == "game-rsvps":
game_uuid = self.context["view"].kwargs["game_uuid"]
game = Game.objects.get(uuid=game_uuid)
user = self.context["request"].user
status = validated_data["status"]
try:
rsvp = RsvpStatus.objects.get(game__uuid=game_uuid, user__uuid=user.uuid)
except RsvpStatus.DoesNotExist:
raise serializers.ValidationError(_("Invalid game."))
if rsvp.user.uuid != user.uuid:
raise serializers.ValidationError(_("Invalid user."))
try:
rsvp.transition_status(status)
except TransitionNotAllowed:
raise serializers.ValidationError(_("State transition not allowed"))
rsvp.save()
return rsvp
class GameSportNestedSerializer(serializers.ModelSerializer):
uuid = serializers.UUIDField(required=True)
class Meta:
model = Sport
fields = ("uuid", "category", "name", "description", "created_at", "modified_at")
read_only_fields = ("category", "name", "description", "created_at", "modified_at")
def create(self, validated_data):
if self.context["view"].basename == "game-sport":
game_uuid = self.context["view"].kwargs["game_uuid"]
game = Game.objects.get(uuid=game_uuid)
sport_uuid = validated_data["uuid"]
try:
sport = Sport.objects.get(uuid=str(sport_uuid))
except Sport.DoesNotExist:
raise serializers.ValidationError(_("Sport not found"))
# if the game already has a spot assigned, then check if the sport being assigned belongs to the spot
if game.spot:
spot = Spot.objects.filter(sports__uuid=sport_uuid).first()
if not spot or game.spot.uuid != spot.uuid:
raise serializers.ValidationError(
_("Invalid Sport. Sport being assigned is not associated with the game spot")
)
game.sport = sport
game.save()
return sport
return {}
class GameSpotNestedSerializer(serializers.ModelSerializer):
uuid = serializers.UUIDField(required=True)
class Meta:
model = Spot
fields = (
"uuid",
"name",
"owner",
"logo",
"homepage_url",
"is_verified",
"is_permanently_closed",
"is_temporary",
"establishment_date",
"closure_date",
"address",
"created_at",
"modified_at",
)
read_only_fields = (
"name",
"owner",
"logo",
"homepage_url",
"is_verified",
"is_permanently_closed",
"is_temporary",
"establishment_date",
"closure_date",
"address",
"created_at",
"modified_at",
)
def create(self, validated_data):
if self.context["view"].basename == "game-spot":
game_uuid = self.context["view"].kwargs["game_uuid"]
game = Game.objects.get(uuid=game_uuid)
spot_uuid = validated_data["uuid"]
try:
spot = Spot.objects.get(uuid=str(spot_uuid))
except Spot.DoesNotExist:
raise serializers.ValidationError(_("Spot not found."))
# if the game already has a spot assigned, then check if the sport being assinged belongs to the spot
if game.sport:
sport = Sport.objects.filter(spots__uuid=spot_uuid).first()
if not sport or game.sport.uuid != sport.uuid:
raise serializers.ValidationError(
_("Invalid Spot. Spot being assigned doesnt have the already " "associated sport")
)
game.spot = spot
game.save()
return spot
return {}
class GameSerializer(serializers.ModelSerializer):
organizer = UserSerializer(read_only=True, many=False)
sport = GameSportNestedSerializer(read_only=True, many=False)
spot = GameSpotNestedSerializer(read_only=True, many=False)
rsvps = RsvpStatusNestedSerializer(source="attendees", read_only=True, many=True)
class Meta:
model = Game
fields = (
"uuid",
"name",
"description",
"start_time",
"start_timezone",
"end_time",
"end_timezone",
"rsvp_open_time",
"rsvp_close_time",
"rsvp_closed",
"invite_mode",
"status",
"capacity",
"show_remaining",
"is_listed",
"is_shareable",
"is_featured",
"created_at",
"modified_at",
"organizer",
"sport",
"spot",
"rsvps",
"share_link",
"chatkit_room_id",
)
read_only_fields = ("uuid", "created_at", "modified_at", "share_link", "chatkit_room_id")
@staticmethod
def validate_start_time(start_time: datetime) -> datetime:
now = timezone.now()
if start_time < now:
raise serializers.ValidationError(_("Start time cannot be in the past"))
if start_time < now + timedelta(minutes=15):
raise serializers.ValidationError(_("Start time should be atleast 15 minutes from now"))
return start_time
@staticmethod
def validate_end_time(end_time: datetime) -> datetime:
now = timezone.now()
if end_time < now:
raise serializers.ValidationError(_("End time cannot be in the past"))
return end_time
@staticmethod
def validate_rsvp_open_time(rsvp_open_time: datetime) -> datetime:
# now = timezone.now()
# if rsvp_open_time < now:
# raise serializers.ValidationError(_("RSVP open time cannot be in the past"))
return rsvp_open_time
@staticmethod
def validate_rsvp_close_time(rsvp_close_time: datetime) -> datetime:
now = timezone.now()
if rsvp_close_time < now:
raise serializers.ValidationError(_("RSVP close time cannot be in the past"))
return rsvp_close_time
def validate_rsvp_closed(self, rsvp_closed: datetime) -> datetime:
# Validation conditions while creating a game
if not self.instance:
if rsvp_closed:
raise serializers.ValidationError(_("RSVP closed cannot be set while creating a game"))
return rsvp_closed
def validate_status(self, status: str) -> str:
# Validation conditions while creating a game
if not self.instance:
if status != Game.STATUS_DRAFT:
raise serializers.ValidationError(_("Game can only be created in DRAFT status"))
else:
if status in [Game.STATUS_STARTED, Game.STATUS_ENDED]:
raise serializers.ValidationError(
_("Status Started and Status Ended are set automatically by the system and cannot be set manually")
)
return status
def validate(self, data):
if not self.instance:
start_time = data.get("start_time", False) and pendulum.instance(data["start_time"])
end_time = data.get("end_time", False) and pendulum.instance(data["end_time"])
rsvp_open_time = data.get("rsvp_open_time", False) and pendulum.instance(data["rsvp_open_time"])
rsvp_close_time = data.get("rsvp_close_time", False) and pendulum.instance(data["rsvp_close_time"])
else:
start_time = data.get("start_time", False) or self.instance.start_time
end_time = data.get("end_time", False) or self.instance.end_time
start_time = pendulum.instance(start_time)
end_time = pendulum.instance(end_time)
rsvp_open_time = data.get("rsvp_open_time", False) or self.instance.rsvp_open_time
rsvp_close_time = data.get("rsvp_close_time", False) or self.instance.rsvp_close_time
rsvp_open_time = rsvp_open_time and pendulum.instance(rsvp_open_time)
rsvp_close_time = rsvp_close_time and pendulum.instance(rsvp_close_time)
if start_time and end_time and end_time < start_time:
raise serializers.ValidationError({"end_time": [_("End time cannot be before start time.")]})
if start_time and end_time and end_time.diff(start_time).in_hours() > 12:
raise serializers.ValidationError({"end_time": [_("Game cannot be greater than 12 hours long.")]})
rsvp_open_time_limit = pendulum.now("UTC").subtract(hours=12)
# only check when rsvp_open_time is being set
if data.get("rsvp_open_time") and rsvp_open_time < rsvp_open_time_limit:
raise serializers.ValidationError(
{"rsvp_open_time": [_("RSVP open time cannot be more than 12 hours in the past.")]}
)
if rsvp_open_time and rsvp_open_time > start_time:
raise serializers.ValidationError({"rsvp_open_time": [_("RSVP open time cannot be after start time.")]})
rsvp_close_time_limit = start_time.add(hours=12)
if rsvp_close_time and rsvp_close_time > rsvp_close_time_limit:
raise serializers.ValidationError(
{"rsvp_close_time": [_("RSVP close time cannot be more than 12 hours after start time.")]}
)
if rsvp_open_time and rsvp_close_time and rsvp_close_time < rsvp_open_time:
raise serializers.ValidationError(
{"rsvp_close_time": [_("RSVP close time cannot be before RSVP open time.")]}
)
return data
def create(self, validated_data) -> Game:
user = self.context["request"].user
if not validated_data.get("rsvp_open_time", False):
validated_data["rsvp_open_time"] = timezone.now()
if not validated_data.get("rsvp_close_time", False):
validated_data["rsvp_close_time"] = validated_data["start_time"] + timedelta(minutes=-15)
game = Game.objects.create(organizer=user, **validated_data)
return game
def update(self, instance: Game, validated_data) -> Game:
status = validated_data.pop("status", None)
for k, v in validated_data.items():
setattr(instance, k, v)
if status and status != instance.status:
try:
instance.transition_status(status)
except TransitionNotAllowed:
raise serializers.ValidationError(_("State transition not allowed"))
instance.save()
return instance
<file_sep>import scrapy
from urllib.parse import urlparse, parse_qs, urljoin
from ..items import Spot
class PlayAdvisorSpider(scrapy.Spider):
name = "play_advisor"
start_urls = [
"https://playadvisor.co/zoeken/?_sft_speelplektype=sport-fitness&_sf_s=&_sft_land=nederland",
]
def parse(self, response):
for spot in response.css("article"):
item = Spot()
item["id"] = spot.css("article::attr(id)").re_first(r"post-(\d*)")
item["label"] = spot.css("article header.entry-header h2.entry-title a::text").get()
item["sports"] = spot.xpath("@class").re(r"speelplektype-(\S*)")
# Get additional details
spot_detail_url = spot.css("article header.entry-header h2.entry-title a::attr(href)").get()
request = scrapy.Request(spot_detail_url, callback=self.parse_spot_details,)
request.meta["item"] = item
yield request
# Paginate over search results
next_page = response.css("nav .nav-links a.next::attr(href)").get()
if next_page is not None:
yield response.follow(next_page, self.parse)
def parse_spot_details(self, response):
item = response.meta["item"]
# Add lat and lng
# REF: href="https://maps.google.com?daddr=51.9419762,5.8667076"
google_maps_url = response.css("div#speelplek-location > a::attr(href)").get()
parsed_google_maps_url = urlparse(google_maps_url)
parsed_query_string = parse_qs(parsed_google_maps_url.query)
daddr = parsed_query_string["daddr"][0]
lat, lng = daddr.split(",")
item["lat"] = lat
item["lng"] = lng
# Add images
item["images"] = list()
main_image_url = response.css("div.post-thumb img::attr(src)").get()
item["images"].append(main_image_url)
gallery_images_urls = response.css("div.gallery-image img::attr(src)").getall()
item["images"].extend(gallery_images_urls)
# Add spot address
item["attributes"] = list()
address = response.css("div#speelplek-location p::text").get() or ""
city = response.css("div#speelplek-location p a::text").get() or ""
item["attributes"].append({"attribute_name": "formatted_address", "value": f"{address} {city}"})
# REF: https://playadvisor.co/speelplek/outdoor-fitness-toestellen/skatebaan-in-burgemeester-t-veldpark/?_sft_speelplektype=sport-fitness&_sf_s&_sft_land=nederland
item["attributes"].append(
{"attribute_name": "url", "value": urljoin(response.url, urlparse(response.url).path),}
)
yield item
<file_sep>from django.contrib import admin
from .models import Address
class AddressAdmin(admin.ModelAdmin):
search_fields = ("uuid", "formatted_address", "spot__name")
list_display = ("uuid", "formatted_address", "lat", "lng")
readonly_fields = ("uuid", "created_at", "modified_at", "deleted_at")
fieldsets = (
(None, {"fields": ("uuid", "formatted_address", "lat", "lng", "point")}),
("Raw Data", {"fields": ("geocoder_service", "raw_address", "raw_geocoder_response")}),
("Google Codes", {"fields": ("plus_global_code", "plus_local_code")}),
("Audit", {"classes": ("collapse",), "fields": ("created_at", "modified_at", "deleted_at")}),
)
admin.site.register(Address, AddressAdmin)
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-04-29 19:27
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Address",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("uuid", models.UUIDField(default=uuid.uuid4, editable=False, verbose_name="Unique Identifier")),
(
"created_at",
models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name="Created At"),
),
("modified_at", models.DateTimeField(auto_now=True, verbose_name="Modified At")),
("deleted_at", models.DateTimeField(blank=True, editable=False, null=True, verbose_name="Deleted At")),
(
"raw_address",
models.CharField(
blank=True, default="", help_text="Complete address", max_length=1024, verbose_name="Address"
),
),
(
"raw_geocoder_response",
django.contrib.postgres.fields.jsonb.JSONField(
blank=True,
help_text="Raw api response from the geocoder service. e.g. google maps",
null=True,
verbose_name="Raw Geocoder Response",
),
),
(
"geocoder_service",
models.CharField(
choices=[
("google", "Google"),
("bing", "Bing"),
("open_street_maps", "Open Street Maps"),
("here", "Here Maps"),
("manual", "Manual"),
],
default="manual",
help_text="Geocoder used to convert raw address into latlong coordinates.",
max_length=25,
null=True,
verbose_name="Geocoder",
),
),
(
"formatted_address",
models.CharField(
blank=True,
help_text="Formatted address returned by the geocoding service",
max_length=1024,
verbose_name="Formatted Address",
),
),
(
"lat",
models.DecimalField(
blank=True, decimal_places=15, max_digits=18, null=True, verbose_name="Latitude"
),
),
(
"lng",
models.DecimalField(
blank=True, decimal_places=15, max_digits=18, null=True, verbose_name="Longtiude"
),
),
(
"plus_global_code",
models.CharField(blank=True, max_length=255, null=True, verbose_name="Google Plus Global Code"),
),
(
"plus_local_code",
models.CharField(blank=True, max_length=255, null=True, verbose_name="Google Plus Local Code"),
),
],
options={"verbose_name": "Address", "verbose_name_plural": "Addresses"},
)
]
<file_sep>from django.utils.translation import ugettext_lazy as _
from wagtail.core.blocks import StreamBlock, CharBlock, StructBlock, ChoiceBlock, TextBlock
from .block_choices import LINEAR_ICON_CHOICES, Background
class HeroHeaderBlock(StructBlock):
heading = CharBlock(default="")
sub_heading = CharBlock(default="")
class Meta:
classname = ""
label = _("Hero Header")
icon = "doc-empty"
template = "cms/blocks/block_hero_header.html"
class IconBannerBlock(StructBlock):
background = ChoiceBlock(
choices=[(choice.value, choice.name) for choice in Background], default=Background.white.value
)
title = CharBlock()
description = TextBlock()
icon = ChoiceBlock(choices=LINEAR_ICON_CHOICES)
class Meta:
classname = ""
label = _("Icon Banner")
icon = "placeholder"
template = "cms/blocks/block_banner_icon.html"
class IconFeaturesPromoBlock(StructBlock):
background = ChoiceBlock(
choices=[(choice.value, choice.name) for choice in Background], default=Background.white.value
)
title = CharBlock()
description = TextBlock()
class Meta:
classname = ""
label = _("Icon Features Promo")
icon = "placeholder"
template = "cms/blocks/block_icon_features_promo.html"
class VideoBannerBlock(StructBlock):
background = ChoiceBlock(
choices=[(choice.value, choice.name) for choice in Background], default=Background.white.value
)
title = CharBlock(default="", required=False)
description = TextBlock(default="")
youtube_video_id = CharBlock(default="")
class Meta:
classname = ""
label = _("Video Banner")
icon = "media"
template = "cms/blocks/block_banner_video.html"
class AppDescriptionBlock(StructBlock):
background = ChoiceBlock(
choices=[(choice.value, choice.name) for choice in Background], default=Background.white.value
)
title = CharBlock(default="", required=False)
description = TextBlock(default="")
class Meta:
classname = ""
label = _("App Description Block")
icon = "media"
template = "cms/blocks/block_app_description.html"
class AppFeaturesBlock(StructBlock):
background = ChoiceBlock(
choices=[(choice.value, choice.name) for choice in Background], default=Background.white.value
)
title = CharBlock(default="", required=False)
description = TextBlock(default="")
class Meta:
classname = ""
label = _("App Features Block")
icon = "media"
template = "cms/blocks/block_app_features.html"
class AppStoresBlock(StructBlock):
background = ChoiceBlock(
choices=[(choice.value, choice.name) for choice in Background], default=Background.white.value
)
title = CharBlock(default="", required=False)
description = TextBlock(default="")
class Meta:
classname = ""
label = _("App Stores Block")
icon = "media"
template = "cms/blocks/block_app_stores.html"
class ContactBlock(StructBlock):
background = ChoiceBlock(
choices=[(choice.value, choice.name) for choice in Background], default=Background.white.value
)
title = CharBlock(default="", required=False)
description = TextBlock(default="")
class Meta:
classname = ""
label = _("Contact Block")
icon = "media"
template = "cms/blocks/block_contact.html"
class NewsletterBlock(StructBlock):
background = ChoiceBlock(
choices=[(choice.value, choice.name) for choice in Background], default=Background.white.value
)
title = CharBlock(default="", required=False)
description = TextBlock(default="")
class Meta:
classname = ""
label = _("Newsletter Block")
icon = "media"
template = "cms/blocks/block_newsletter.html"
class PressBlock(StructBlock):
background = ChoiceBlock(
choices=[(choice.value, choice.name) for choice in Background], default=Background.white.value
)
title = CharBlock(default="", required=False)
description = TextBlock(default="")
class Meta:
classname = ""
label = _("Press Block")
icon = "media"
template = "cms/blocks/block_press.html"
class StatsBlock(StructBlock):
background = ChoiceBlock(
choices=[(choice.value, choice.name) for choice in Background], default=Background.white.value
)
title = CharBlock(default="", required=False)
description = TextBlock(default="")
class Meta:
classname = ""
label = _("Stats Block")
icon = "media"
template = "cms/blocks/block_stats.html"
class TeamBlock(StructBlock):
background = ChoiceBlock(
choices=[(choice.value, choice.name) for choice in Background], default=Background.white.value
)
title = CharBlock(default="", required=False)
description = TextBlock(default="")
class Meta:
classname = ""
label = _("Team Block")
icon = "media"
template = "cms/blocks/block_team.html"
class UserQuotesBlock(StructBlock):
background = ChoiceBlock(
choices=[(choice.value, choice.name) for choice in Background], default=Background.white.value
)
title = CharBlock(default="", required=False)
description = TextBlock(default="")
class Meta:
classname = ""
label = _("User Quotes Block")
icon = "media"
template = "cms/blocks/block_user_quotes.html"
class PageHomeStreamBlock(StreamBlock):
hero_header = HeroHeaderBlock()
icon_banner = IconBannerBlock()
video_banner = VideoBannerBlock()
app_description = AppDescriptionBlock()
app_features = AppFeaturesBlock()
app_stores = AppStoresBlock()
newsletter = NewsletterBlock()
press = PressBlock()
stats = StatsBlock()
team = TeamBlock()
user_quotes = UserQuotesBlock()
contact = ContactBlock()
icon_features_promo = IconFeaturesPromoBlock()
<file_sep>from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.translation import ugettext_lazy as _
from seedorf.utils.models import BasePropertiesModel
class ReactionsManager(models.Manager):
use_for_related_fields = True
def likes(self):
return self.get_queryset().filter(reaction=Reaction.LIKE)
def dislikes(self):
return self.get_queryset().filter(reaction=Reaction.DISLIKE)
def like_count(self):
return self.get_queryset().filter(reaction=Reaction.LIKE).count()
def dislike_count(self):
return self.get_queryset().filter(reaction=Reaction.DISLIKE).count()
def spots(self):
return self.get_queryset().filter(content_type__model="spots").order_by("-spot_reactions__created_at")
def sports(self):
return self.get_queryset().filter(content_type__model="sports").order_by("-sport_reactions__created_at")
class Reaction(BasePropertiesModel):
DISLIKE = "dislike"
LIKE = "like"
REACTIONS = ((DISLIKE, _("Dislike")), (LIKE, _("Like")))
reaction = models.CharField(blank=False, choices=REACTIONS, null=False, max_length=50, verbose_name=_("Reaction"))
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_("User"))
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
objects = ReactionsManager()
class Meta:
ordering = ("-created_at",)
<file_sep>import copy
from django.core.exceptions import ValidationError
from django.core.validators import BaseValidator
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _
from jsonschema import validate
@deconstructible
class AllowedKeysValidator(object):
"""A validator designed for HStore to restrict keys."""
messages = {"invalid_keys": _("Some keys were invalid: %(keys)s")}
strict = False
def __init__(self, keys, messages=None):
self.keys = set(keys)
if messages is not None:
self.messages = copy.copy(self.messages)
self.messages.update(messages)
def __call__(self, value):
keys = set(value.keys())
disallowed_keys = keys - self.keys
if disallowed_keys:
raise ValidationError(
self.messages["invalid_keys"], code="invalid_keys", params={"keys": ", ".join(disallowed_keys)}
)
def __eq__(self, other):
return (
isinstance(other, self.__class__)
and self.keys == other.keys
and self.messages == other.messages
and self.strict == other.strict
)
def __ne__(self, other):
return not (self == other)
class JSONSchemaValidator(BaseValidator):
def compare(self, a, b):
return validate(a, b)
<file_sep>require('../../../../node_modules/bootstrap-table/src/extensions/filter/bootstrap-table-filter.js');
<file_sep># Generated by Django 2.1.3 on 2018-11-17 13:12
from django.db import migrations, models
import seedorf.users.models
class Migration(migrations.Migration):
dependencies = [("users", "0004_auto_20180618_1608")]
operations = [
migrations.AlterField(
model_name="user",
name="last_name",
field=models.CharField(blank=True, max_length=150, verbose_name="<NAME>"),
),
migrations.AlterField(
model_name="userprofile",
name="avatar",
field=models.ImageField(
blank=True,
null=True,
upload_to=seedorf.users.models.get_avatar_upload_directory,
verbose_name="Avatar Image",
),
),
]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-06-02 21:10
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("users", "0002_auto_20180429_1927")]
operations = [
migrations.AlterModelOptions(name="user", options={"ordering": ("-created_at",)}),
migrations.AlterModelOptions(name="userprofile", options={"ordering": ("-created_at",)}),
]
<file_sep>from rest_framework import viewsets
from rest_framework import mixins
from seedorf.sports.models import Sport
from seedorf.sports.serializers import SportSerializer
from seedorf.spots.models import Spot
from seedorf.spots.serializers import SpotSerializer
from seedorf.utils.permissions import IsOwnerOrReadOnly
from seedorf.utils.regex import UUID as REGEX_UUID
from .models import User, UserProfile
from .serializers import UserProfileSerializer, UserSerializer
class UserViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by("-date_joined")
serializer_class = UserSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
permission_classes = (IsOwnerOrReadOnly,)
class UserProfileNestedViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows user profile to be viewed or edited.
"""
serializer_class = UserProfileSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
permission_classes = (IsOwnerOrReadOnly,)
def get_queryset(self):
user_uuid = self.kwargs["user_uuid"]
return UserProfile.objects.filter(user__uuid=user_uuid)
# TODO: Fix avatar image creation
# @action(methods=['post'], detail=True, permission_classes=[IsOwnerOrReadOnly])
# def avatar(self, request, user_uuid=None, uuid=None):
# try:
# file = request.data['file']
# except KeyError:
# raise ParseError('Request has no resource file attached')
# user_profile = UserProfile.objects.create(image=file, ....)
class UserProfileSportNestedViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users sports to be viewed or edited.
"""
serializer_class = SportSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
permission_classes = (IsOwnerOrReadOnly,)
def get_queryset(self):
profile_uuid = self.kwargs["profile_uuid"]
return Sport.objects.filter(followers__uuid=profile_uuid)
class UserProfileSpotNestedViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users spots to be viewed or edited.
"""
serializer_class = SpotSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
permission_classes = (IsOwnerOrReadOnly,)
def get_queryset(self):
profile_uuid = self.kwargs["profile_uuid"]
return Spot.objects.filter(followers__uuid=profile_uuid)
class GameUserNestedViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows nested users to be viewed or edited.
"""
serializer_class = UserSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
def get_queryset(self):
game_uuid = self.kwargs["game_uuid"]
return User.objects.filter(game_organizers__uuid=game_uuid)
<file_sep># Generated by Django 2.1.2 on 2019-04-24 09:43
from django.db import migrations, models
def set_share_links(apps, schema_editor):
Game = apps.get_model("games", "Game")
for game in Game.objects.all():
# triggers signal to set share_link
game.save()
class Migration(migrations.Migration):
dependencies = [("games", "0012_update_game_default_ordering")]
operations = [
migrations.AddField(
model_name="game",
name="share_link",
field=models.URLField(
default="https://www.change.me",
help_text="Shareable link (app/web) to this game.",
max_length=80,
verbose_name="Shareable link",
),
preserve_default=False,
),
migrations.RunPython(set_share_links),
]
<file_sep>require('../../node_modules/jquery.growl/javascripts/jquery.growl.js');
<file_sep>import Dropzone from '../../node_modules/dropzone/dist/dropzone.js';
Dropzone.autoDiscover = false;
// Extend Dropzone default options
Dropzone.prototype.defaultOptions.previewTemplate = `
<div class="dz-preview dz-file-preview">
<div class="dz-details">
<div class="dz-thumbnail">
<img data-dz-thumbnail>
<span class="dz-nopreview">No preview</span>
<div class="dz-success-mark"></div>
<div class="dz-error-mark"></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<div class="progress"><div class="progress-bar progress-bar-primary" role="progressbar" aria-valuemin="0" aria-valuemax="100" data-dz-uploadprogress></div></div>
</div>
<div class="dz-filename" data-dz-name></div>
<div class="dz-size" data-dz-size></div>
</div>
</div>`;
export { Dropzone };
<file_sep># Generated by Django 2.1.2 on 2018-12-07 20:23
import django.core.validators
from django.db import migrations, models
import django.utils.timezone
import django_fsm
class Migration(migrations.Migration):
dependencies = [("games", "0007_auto_20181207_2023")]
operations = [
migrations.AlterField(
model_name="game",
name="capacity",
field=models.PositiveSmallIntegerField(
blank=True,
null=True,
validators=[
django.core.validators.MinValueValidator(limit_value=2),
django.core.validators.MaxValueValidator(limit_value=50),
],
verbose_name="Capacity",
),
),
migrations.AlterField(
model_name="game",
name="description",
field=models.TextField(
blank=True, default="", help_text="Description of the game.", verbose_name="Description"
),
),
migrations.AlterField(
model_name="game",
name="is_featured",
field=models.BooleanField(
default=False, help_text="If this game is featured.", verbose_name="Is featured?"
),
),
migrations.AlterField(
model_name="game", name="name", field=models.CharField(blank=True, default="", max_length=255)
),
migrations.AlterField(
model_name="game",
name="status",
field=django_fsm.FSMField(
choices=[
("canceled", "Canceled"),
("completed", "Completed"),
("draft", "Draft"),
("ended", "Ended"),
("live", "Live"),
("planned", "Planned"),
("updated", "Updated"),
("started", "Started"),
],
default="draft",
max_length=25,
protected=True,
verbose_name="Status",
),
),
migrations.AlterField(
model_name="rsvpstatus",
name="status",
field=django_fsm.FSMField(
choices=[
("accepted", "Accepted"),
("attending", "Attending"),
("checked_in", "Checked In"),
("declined", "Declined"),
("interested", "Interested"),
("invited", "Invited"),
("unknown", "Unknown"),
],
default="unknown",
max_length=25,
null=True,
protected=True,
verbose_name="Status",
),
),
]
<file_sep>require('../../node_modules/fullcalendar/dist/fullcalendar.js');
<file_sep>from allauth.account.adapter import DefaultAccountAdapter
from allauth.exceptions import ImmediateHttpResponse
from allauth.socialaccount import signals
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from allauth.socialaccount.models import SocialLogin
from django.conf import settings
from django.contrib.auth import login
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from rest_auth.utils import jwt_encode
from seedorf.users.models import User
from seedorf.utils.email import send_mail
from seedorf.utils.firebase import get_firebase_link
class AccountAdapter(DefaultAccountAdapter):
def is_open_for_signup(self, request):
return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True)
def send_confirmation_mail(self, request, emailconfirmation, signup):
user = request.user
magic_url = str(user.create_magic_link())
context = {"name": emailconfirmation.email_address.user.name, "action_url": magic_url}
send_mail(
to=emailconfirmation.email_address.email,
template_prefix="SignupConfirmEmail",
subject=_("Welcome to SportySpots."),
language=request.user.profile.language,
context=context,
)
def get_login_redirect_url(self, request):
# This happens after OAuth
token = jwt_encode(request.user)
return get_firebase_link("login?token=" + token)
def save_user(self, request, user, form, commit=True):
"""
Saves a new `User` instance using information provided in the
signup form.
"""
from allauth.account.utils import user_username, user_email, user_field
data = form.cleaned_data
name = data.get("name")
email = data.get("email")
username = data.get("username")
user_email(user, email)
user_username(user, username)
if name:
user_field(user, "name", name)
if "password1" in data:
user.set_password(data["<PASSWORD>"])
else:
user.set_unusable_password()
self.populate_username(request, user)
# user.profile.language = data.get("language", "en")
if commit:
# Ability not to commit makes it easier to derive from
# this adapter by adding
user.save()
request.user = user
return user
class SocialAccountAdapter(DefaultSocialAccountAdapter):
def connect_by_email(self, request, sociallogin):
email_address = sociallogin.email_addresses[0].email
user = User.objects.get(email=email_address)
# user found with this email address, connect social account to this user.
login(request, user, "allauth.account.auth_backends.AuthenticationBackend")
sociallogin.connect(request, request.user)
signals.social_account_added.send(sender=SocialLogin, request=request, sociallogin=sociallogin)
raise ImmediateHttpResponse(HttpResponseRedirect(get_firebase_link("login?token=" + jwt_encode(user))))
def pre_social_login(self, request, sociallogin):
if sociallogin.user.pk:
return # user logged in normally
else:
try:
self.connect_by_email(request, sociallogin)
except User.DoesNotExist:
if sociallogin.state["process"] == "login":
# user wants to login, but is not yet registered
raise ImmediateHttpResponse(HttpResponseRedirect(get_firebase_link("social_login_not_registered")))
def is_open_for_signup(self, request, sociallogin):
return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True)
<file_sep>import time
import jwt
import requests
from django.conf import settings
class ChatkitClient:
"""
https://pusher.com/docs/chatkit/reference/api
https://pusher.com/docs/chatkit/reference/api#endpoints
https://pusher.com/docs/chatkit/authentication#token-provider-generate-a-token
"""
def __init__(
self,
instance_id: str,
key_id: str,
key_secret: str,
base_url: str = "https://us1.pusherplatform.io/services/chatkit/v3",
jwt_expiration_time: int = 60 * 60 * 24 * 1, # seems to be maximum
):
self.instance_id = instance_id
self.key_id = key_id
self.key_secret = key_secret
self.jwt_expiration_time = jwt_expiration_time
self.base_url = base_url
self.token = None
def create_token(self, user_id=None, super_user=False):
claims = {
"instance": self.instance_id,
"iss": f"api_keys/{self.key_id}",
"iat": int(time.time()),
"exp": int(time.time()) + self.jwt_expiration_time,
"su": super_user,
}
if user_id:
claims["sub"] = user_id
return jwt.encode(claims, self.key_secret, algorithm="HS256").decode("utf-8")
# create a JWT token for admin not associated with a user. Cannot create rooms.
def create_admin_token(self):
return self.create_token(user_id=None, super_user=True)
# create an admin JWT token for readonly user
def create_admin_readonly_user_token(self):
return self.create_token(user_id="readonly", super_user=True)
def headers(self):
assert self.token, "Token needs to be set"
return {"Authorization": f"Bearer {self.token}"}
def get(self, url):
response = requests.get(url=f"{self.base_url}/{self.instance_id}/{url}", headers=self.headers())
if 200 < response.status_code < 300:
return response.json()
response.raise_for_status()
def delete(self, url):
response = requests.delete(url=f"{self.base_url}/{self.instance_id}/{url}", headers=self.headers())
if 200 < response.status_code < 300:
return response.json()
response.raise_for_status()
def post(self, url, data):
response = requests.post(url=f"{self.base_url}/{self.instance_id}/{url}", json=data, headers=self.headers())
if 200 < response.status_code < 300:
return response.json()
response.raise_for_status()
def put(self, url, data):
response = requests.put(url=f"{self.base_url}/{self.instance_id}/{url}", json=data, headers=self.headers())
if 200 < response.status_code < 300:
return response.json()
response.raise_for_status()
def get_user(self, user_id: str):
return self.get(f"users/{user_id}")
def list_users(self):
return self.get("users")
def create_user(self, user_id: str, name: str = "NA", avatar_url: str = None, custom_data: object = None):
data = {"id": user_id, "name": name, "custom_data": custom_data or {}}
if avatar_url:
data["avatar_url"] = avatar_url
return self.post("users", data)
def update_user(self, user_id: str, name: str, avatar_url: str = None, custom_data: object = None):
data = {"name": name, "custom_data": custom_data or {}}
if avatar_url:
data["avatar_url"] = avatar_url
return self.put(f"users/{user_id}", data)
def delete_user(self, user_id: str):
return self.delete(f"users/{user_id}")
def create_room(self, name: str, private: bool = False, custom_data: dict = None, user_ids: list = None):
"""
Create a Chatkit room.
:param name: name of the room
:param private: can not be listed/joined if true
:param custom_data: room custom data
:param user_ids: user ids to add as members (the owner of the token is auto added)
:return: { 'created_at': '2019-05-01T11:21:26Z',
'created_by_id': 'readonly',
'id': '19400196',
'member_user_ids': ['readonly'],
'name': 'test room',
'private': False,
'updated_at': '2019-05-01T11:21:26Z'
}
"""
data = {
# A room name must be no longer than 60 characters.
"name": name[:59],
"private": private,
"custom_data": custom_data or {},
"user_ids": user_ids or [],
}
return self.post("rooms", data)
def create_client():
return ChatkitClient(
settings.CHATKIT_SETTINGS["INSTANCE_ID"],
settings.CHATKIT_SETTINGS["KEY_ID"],
settings.CHATKIT_SETTINGS["KEY_SECRET"],
)
<file_sep>import * as bootbox from '../../node_modules/bootbox/bootbox.js';
export { bootbox };
<file_sep>require('../../node_modules/datatables.net/js/jquery.dataTables.js');
require('../../node_modules/datatables.net-bs4/js/dataTables.bootstrap4.js');
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-04-29 19:27
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("contenttypes", "0002_remove_content_type_name"),
]
operations = [
migrations.CreateModel(
name="Reaction",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("uuid", models.UUIDField(default=uuid.uuid4, editable=False, verbose_name="Unique Identifier")),
(
"created_at",
models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name="Created At"),
),
("modified_at", models.DateTimeField(auto_now=True, verbose_name="Modified At")),
("deleted_at", models.DateTimeField(blank=True, editable=False, null=True, verbose_name="Deleted At")),
(
"reaction",
models.CharField(
choices=[("dislike", "Dislike"), ("like", "Like")], max_length=50, verbose_name="Reaction"
),
),
("object_id", models.PositiveIntegerField()),
(
"content_type",
models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="contenttypes.ContentType"),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name="User"
),
),
],
options={"abstract": False},
)
]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-09-05 12:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("spots", "0004_auto_20180602_2110")]
operations = [
migrations.AlterField(
model_name="spot",
name="sports",
field=models.ManyToManyField(blank=True, related_name="spots", to="sports.Sport", verbose_name="Sports"),
)
]
<file_sep>import os
import tempfile
from PIL import Image
from django.urls import reverse
from rest_framework.test import APITestCase
from seedorf.locations.tests.factories import AddressFactory
from seedorf.sports.tests.factories import SportFactory
from seedorf.spots.tests.factories import SpotFactory, SpotImageFactory
from seedorf.users.tests.factories import SuperUserFactory
class SpotAPIViewTest(APITestCase):
def setUp(self):
user = SuperUserFactory()
self.client.force_authenticate(user=user)
def test_spot_list_retrieve(self):
spot_1 = SpotFactory(name="spot 1")
spot_2 = SpotFactory(name="spot 2")
url = reverse("spot-list")
response = self.client.get(url, format="json")
self.assertEqual(200, response.status_code)
self.assertEqual(response.data["count"], 2)
self.assertEqual(len(response.data["results"]), 2)
def test_spot_detail_retrieve(self):
spot = SpotFactory(name="spot 1")
url = reverse("spot-detail", kwargs={"uuid": str(spot.uuid)})
response = self.client.get(url, format="json")
self.assertEqual(200, response.status_code)
self.assertEqual(response.data["address"]["uuid"], str(spot.address.uuid))
self.assertTrue(response.data["sports"])
self.assertEqual(response.data["name"], "spot 1")
self.assertEqual(response.data["slug"], "spot-1")
self.assertNotEqual(response.data["description"], "")
self.assertEqual(response.data["is_temporary"], False)
self.assertEqual(response.data["is_public"], True)
self.assertEqual(response.data["is_permanently_closed"], False)
self.assertTrue(response.data["is_verified"])
self.assertNotEqual(response.data["homepage_url"], "")
self.assertNotEqual(response.data["logo"], "")
self.assertNotEqual(response.data["owner"], "")
self.assertIsNone(response.data["establishment_date"])
self.assertIsNone(response.data["closure_date"])
self.assertIsNotNone(response.data["created_at"])
self.assertIsNotNone(response.data["modified_at"])
self.assertIsNone(response.data["deleted_at"])
def test_spot_creation(self):
url = reverse("spot-list")
data = {"name": "spot 1", "description": "test description"}
response = self.client.post(url, data, format="json")
self.assertEqual(201, response.status_code)
self.assertEqual(response.data["address"], None)
self.assertEqual(response.data["sports"], [])
self.assertEqual(response.data["name"], "spot 1")
self.assertEqual(response.data["slug"], "spot-1")
self.assertEqual(response.data["description"], "test description")
self.assertEqual(response.data["closure_date"], None)
self.assertEqual(response.data["establishment_date"], None)
self.assertEqual(response.data["is_temporary"], False)
self.assertEqual(response.data["is_public"], True)
self.assertEqual(response.data["is_permanently_closed"], False)
self.assertEqual(response.data["is_verified"], False)
self.assertEqual(response.data["homepage_url"], "")
self.assertEqual(response.data["logo"], None)
self.assertEqual(response.data["owner"], "")
self.assertEqual(response.data["deleted_at"], None)
def test_spot_update(self):
spot = SpotFactory(name="spot-1")
url = reverse("spot-detail", kwargs={"uuid": str(spot.uuid)})
data = {"name": "spot-2", "owner": "test owner", "description": "test description"}
response = self.client.put(url, data, format="json")
self.assertEqual(200, response.status_code)
self.assertEqual(response.data["name"], "spot-2")
# Make sure that the slug is not updated
self.assertEqual(response.data["slug"], "spot-1")
self.assertEqual(response.data["owner"], "test owner")
self.assertEqual(response.data["description"], "test description")
def test_address_create(self):
spot = SpotFactory()
url = reverse("spot-address-list", kwargs={"spot_uuid": str(spot.uuid)})
data = {"lat": 52.0, "lng": 24.7, "raw_address": "1234 Amsterdam"}
response = self.client.post(url, data, format="json")
self.assertEqual(201, response.status_code)
self.assertEqual(response.data["lat"], "52.000000000000000")
self.assertEqual(response.data["lng"], "24.700000000000000")
self.assertEqual(response.data["raw_address"], "1234 Amsterdam")
def test_address_update(self):
address = AddressFactory(raw_address="1234 Amsterdam")
spot = SpotFactory(address=address)
url = reverse("spot-address-detail", kwargs={"spot_uuid": str(spot.uuid), "uuid": str(address.uuid)})
data = {"raw_address": "4321 Amsterdam"}
response = self.client.put(url, data, format="json")
self.assertEqual(200, response.status_code)
self.assertTrue(response.data["raw_address"], "4321 Amsterdam")
def test_sport_assign(self):
spot = SpotFactory(sports=None)
sport = SportFactory()
url = reverse("spot-sports-list", kwargs={"spot_uuid": str(spot.uuid)})
data = {"uuid": str(sport.uuid)}
response = self.client.post(url, data, format="json")
self.assertEqual(201, response.status_code)
def test_image_create(self):
spot = SpotFactory()
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp_file:
image = Image.new("RGB", (100, 100), "#ddd")
image.save(tmp_file, format="JPEG")
tmp_file.close()
url = reverse(
"spot-sport-images-list",
kwargs={"sport_uuid": str(str(spot.sports.all()[0].uuid)), "spot_uuid": str(spot.uuid)},
)
with open(tmp_file.name, "rb") as photo:
data = {"image": photo}
response = self.client.post(url, data, format="multipart")
self.assertEqual(201, response.status_code)
os.remove(tmp_file.name)
def test_image_update(self):
spot = SpotFactory()
spot_image = SpotImageFactory(spot=spot, sport=spot.sports.all()[0])
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp_file:
image = Image.new("RGB", (100, 100), "#ddd")
image.save(tmp_file, format="JPEG")
tmp_file.close()
url = reverse(
"spot-sport-images-detail",
kwargs={
"sport_uuid": str(str(spot.sports.all()[0].uuid)),
"spot_uuid": str(spot.uuid),
"uuid": str(spot_image.uuid),
},
)
with open(tmp_file.name, "rb") as photo:
data = {"image": photo}
response = self.client.put(url, data, format="multipart")
self.assertEqual(200, response.status_code)
os.remove(tmp_file.name)
<file_sep>from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.utils.translation import ugettext_lazy as _
from nece.models import TranslationModel
from seedorf.utils.models import BasePropertiesModel
class Sport(BasePropertiesModel, TranslationModel):
# TODO: Enable users to create their own games ?
# TODO: Set is a flag is_staff_created to distinguish between staff created and user created sports
# Predefined Values
BASKETBALL = "basketball"
BEACH_VOLLEYBALL = "beach_volleyball"
BOOTCAMP = "bootcamp"
BOULES = "boules"
FITNESS = "fitness"
OTHERS = "others"
SKATING = "skating"
SOCCER = "soccer"
TENNIS = "tennis"
TABLE_TENNIS = "table_tennis"
SPORTS = (
(BASKETBALL, _("Basketball")),
(BEACH_VOLLEYBALL, _("Beach Volleyball")),
(BOOTCAMP, _("Bootcamp")),
(BOULES, _("Boules")),
(FITNESS, _("Fitness")),
(OTHERS, _("Others")),
(SKATING, _("Skating")),
(SOCCER, _("Soccer")),
(TENNIS, _("Tennis")),
(TABLE_TENNIS, _("Table Tennis")),
)
# Instance Fields
category = models.CharField(
blank=False,
choices=SPORTS,
default=OTHERS,
help_text=_("Name of the main category of the sport (e.g. Soccer)."),
max_length=50,
null=False,
verbose_name=_("Sport Category"),
)
name = models.CharField(
blank=False,
help_text=_("Name of the sub category of the sport (e.g. Soccer 5x5)."),
max_length=255,
null=False,
unique=True,
verbose_name=_("Sport Name"),
)
description = models.TextField(
blank=True, default="", max_length=4096, null=False, verbose_name=_("Sport Description")
)
# Generic Relations
reaction = GenericRelation("reactions.Reaction", blank=True, null=True, related_query_name="sport_reactions")
class Meta:
verbose_name = _("Sport")
verbose_name_plural = _("Sports")
ordering = ("-created_at",)
translatable_fields = ("name", "description")
def __str__(self):
return f"{self.category} : {self.name}"
<file_sep>import * as Masonry from '../../node_modules/masonry-layout/dist/masonry.pkgd.js';
export { Masonry };
<file_sep>require('../../node_modules/tableexport.jquery.plugin/tableExport.js');
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-05-13 08:20
from __future__ import unicode_literals
from django.db import migrations, models
import seedorf.spots.models
class Migration(migrations.Migration):
dependencies = [("spots", "0002_auto_20180513_0752")]
operations = [
migrations.AlterField(
model_name="spotimage",
name="image",
field=models.ImageField(max_length=512, upload_to=seedorf.spots.models.get_images_upload_directory),
)
]
<file_sep>require('../../node_modules/morris.js/morris.js');
<file_sep>from django.contrib import admin
from .models import Reaction
admin.site.register(Reaction)
<file_sep>from datetime import timedelta
from uuid import uuid4
from django.urls import reverse
from django.utils import timezone
from rest_framework.test import APITestCase
from seedorf.games.models import Game, RsvpStatus
from seedorf.sports.models import Sport
from seedorf.sports.tests.factories import SportFactory
from seedorf.spots.models import Spot
from seedorf.spots.tests.factories import SpotFactory
from seedorf.users.tests.factories import UserFactory
from .factories import GameFactory, RsvpStatusFactory
from django.core import mail
from unittest.mock import patch
def mock_get_firebase_link(app_link, unguessable=True, **kwargs):
return f"https://mock.link/{app_link[0:10]}"
def mock_create_chatkit_room_for_game(game: Game):
game.chatkit_room_id = 123
game.save()
@patch("seedorf.games.models.get_firebase_link", mock_get_firebase_link)
@patch("seedorf.games.signals.create_chatkit_room_for_game", mock_create_chatkit_room_for_game)
class GameAPIViewTest(APITestCase):
def setUp(self):
self.user = UserFactory()
self.client.force_authenticate(user=self.user)
def test_game_create(self):
url = reverse("game-list")
now = timezone.now()
rsvp_open_time = now + timedelta(days=1)
rsvp_close_time = now + timedelta(days=1, hours=8)
start_time = now + timedelta(days=2)
end_time = now + timedelta(days=2, hours=8)
data = {
"name": "test game",
"rsvp_open_time": rsvp_open_time,
"rsvp_close_time": rsvp_close_time,
"start_time": start_time,
"end_time": end_time,
}
response = self.client.post(url, data, format="json")
self.assertEqual(201, response.status_code)
self.assertTrue(self.user.email, response.data["organizer"]["email"])
self.assertIsNone(response.data["sport"])
self.assertIsNone(response.data["spot"])
self.assertListEqual(response.data["rsvps"], [])
self.assertEqual(response.data["status"], "draft")
self.assertIn("https://mock.link/games/", response.data["share_link"])
self.assertEqual(response.data["chatkit_room_id"], 123)
def test_game_create_set_status_error(self):
url = reverse("game-list")
now = timezone.now()
rsvp_open_time = now + timedelta(days=1)
rsvp_close_time = now + timedelta(days=1, hours=8)
start_time = now + timedelta(days=2)
end_time = now + timedelta(days=2, hours=8)
data = {
"name": "<NAME>",
"rsvp_open_time": rsvp_open_time,
"rsvp_close_time": rsvp_close_time,
"start_time": start_time,
"end_time": end_time,
"status": Game.STATUS_PLANNED,
}
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
self.assertIn("status", response.data.keys())
def test_game_create_start_time_past_error(self):
url = reverse("game-list")
now = timezone.now()
start_time = now + timedelta(days=-1)
end_time = now + timedelta(days=2, hours=8)
data = {"name": "<NAME>", "start_time": start_time, "end_time": end_time}
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
self.assertIn("start_time", response.data.keys())
def test_game_create_end_time_past_error(self):
url = reverse("game-list")
now = timezone.now()
start_time = now + timedelta(days=1)
end_time = now + timedelta(days=-2, hours=8)
data = {"name": "<NAME>", "start_time": start_time, "end_time": end_time}
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
self.assertIn("end_time", response.data.keys())
def test_game_create_rsvp_open_time_past_error(self):
url = reverse("game-list")
now = timezone.now()
rsvp_open_time = now + timedelta(days=-13)
rsvp_close_time = now + timedelta(days=1, hours=8)
start_time = now + timedelta(days=2)
end_time = now + timedelta(days=2, hours=8)
data = {
"name": "<NAME>",
"rsvp_open_time": rsvp_open_time,
"rsvp_close_time": rsvp_close_time,
"start_time": start_time,
"end_time": end_time,
}
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
self.assertIn("rsvp_open_time", response.data.keys())
def test_game_create_rsvp_close_time_past_error(self):
url = reverse("game-list")
now = timezone.now()
rsvp_open_time = now + timedelta(days=1)
rsvp_close_time = now + timedelta(days=-1, hours=8)
start_time = now + timedelta(days=2)
end_time = now + timedelta(days=2, hours=8)
data = {
"name": "<NAME>",
"rsvp_open_time": rsvp_open_time,
"rsvp_close_time": rsvp_close_time,
"start_time": start_time,
"end_time": end_time,
}
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
self.assertIn("rsvp_close_time", response.data.keys())
def test_game_create_rsvp_close_set_error(self):
url = reverse("game-list")
now = timezone.now()
rsvp_open_time = now + timedelta(days=1)
rsvp_close_time = now + timedelta(days=1, hours=8)
start_time = now + timedelta(days=2)
end_time = now + timedelta(days=2, hours=8)
data = {
"name": "<NAME>",
"rsvp_open_time": rsvp_open_time,
"rsvp_close_time": rsvp_close_time,
"start_time": start_time,
"end_time": end_time,
"rsvp_closed": True,
}
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
self.assertIn("rsvp_closed", response.data.keys())
def test_game_create_end_time_before_start_time_error(self):
url = reverse("game-list")
now = timezone.now()
start_time = now + timedelta(days=2)
end_time = now + timedelta(days=1, hours=12)
data = {"name": "<NAME>", "start_time": start_time, "end_time": end_time}
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
def test_game_create_end_time_greater_than_twevle_hours_after_start_time_error(self):
url = reverse("game-list")
now = timezone.now()
start_time = now + timedelta(days=2)
end_time = now + timedelta(days=2, hours=14)
data = {"name": "<NAME>", "start_time": start_time, "end_time": end_time}
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
def test_game_create_rsvp_open_time_after_start_time_error(self):
url = reverse("game-list")
now = timezone.now()
rsvp_open_time = now + timedelta(days=2, hours=2)
start_time = now + timedelta(days=2)
end_time = now + timedelta(days=2, hours=8)
data = {"name": "<NAME>", "rsvp_open_time": rsvp_open_time, "start_time": start_time, "end_time": end_time}
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
def test_game_create_rsvp_close_time_after_start_time_error(self):
url = reverse("game-list")
now = timezone.now()
rsvp_close_time = now + timedelta(days=2, hours=13)
start_time = now + timedelta(days=2)
end_time = now + timedelta(days=2, hours=8)
data = {"name": "<NAME>", "rsvp_close_time": rsvp_close_time, "start_time": start_time, "end_time": end_time}
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
def test_game_create_rsvp_close_time_before_rsvp_open_time_error(self):
url = reverse("game-list")
now = timezone.now()
rsvp_open_time = now + timedelta(days=1, hours=8)
rsvp_close_time = now + timedelta(days=1)
start_time = now + timedelta(days=2)
end_time = now + timedelta(days=2, hours=8)
data = {
"name": "<NAME>",
"rsvp_open_time": rsvp_open_time,
"rsvp_close_time": rsvp_close_time,
"start_time": start_time,
"end_time": end_time,
}
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
self.assertIn("rsvp_close_time", response.data.keys())
def test_empty_sport_assign(self):
game = GameFactory()
url = reverse("game-sport-list", kwargs={"game_uuid": str(game.uuid)})
response = self.client.post(url, {}, format="json")
self.assertEqual(400, response.status_code)
def test_nonexistent_sport_assign(self):
uuid = uuid4()
game = GameFactory()
data = {"uuid": str(uuid)}
url = reverse("game-sport-list", kwargs={"game_uuid": str(game.uuid)})
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
def test_invalid_sport_assign(self):
game = GameFactory()
sport = SportFactory()
data = {"uuid": str(sport.uuid)}
url = reverse("game-sport-list", kwargs={"game_uuid": str(game.uuid)})
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
def test_valid_sport_assign(self):
game = GameFactory(sport=None)
sport = Sport.objects.filter(spots__uuid=game.spot.uuid).first()
data = {"uuid": str(sport.uuid)}
url = reverse("game-sport-list", kwargs={"game_uuid": str(game.uuid)})
response = self.client.post(url, data, format="json")
self.assertEqual(201, response.status_code)
self.assertEqual(str(sport.uuid), response.data["uuid"])
updated_game = Game.objects.get(uuid=game.uuid)
self.assertEqual(sport.uuid, updated_game.sport.uuid)
def test_empty_spot_assign(self):
game = GameFactory()
url = reverse("game-spot-list", kwargs={"game_uuid": str(game.uuid)})
response = self.client.post(url, {}, format="json")
self.assertEqual(400, response.status_code)
def test_nonexistant_spot_assign(self):
uuid = uuid4()
game = GameFactory()
data = {"uuid": str(uuid)}
url = reverse("game-spot-list", kwargs={"game_uuid": str(game.uuid)})
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
def test_invalid_spot_assign(self):
game = GameFactory()
spot = SpotFactory()
data = {"uuid": str(spot.uuid)}
url = reverse("game-spot-list", kwargs={"game_uuid": str(game.uuid)})
response = self.client.post(url, data, format="json")
self.assertEqual(400, response.status_code)
def test_set_status_planned(self):
game = GameFactory()
data = {"status": "planned"}
url = reverse("game-detail", kwargs={"uuid": str(game.uuid)})
response = self.client.patch(url, data, format="json")
self.assertEqual(200, response.status_code)
# test emails
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, "Your activity details")
def test_valid_spot_assign(self):
game = GameFactory()
spot = Spot.objects.filter(sports__uuid=game.sport.uuid).first()
data = {"uuid": str(spot.uuid)}
url = reverse("game-spot-list", kwargs={"game_uuid": str(game.uuid)})
response = self.client.post(url, data, format="json")
self.assertEqual(201, response.status_code)
self.assertEqual(str(spot.uuid), response.data["uuid"])
updated_game = Game.objects.get(uuid=game.uuid)
self.assertEqual(spot.uuid, updated_game.spot.uuid)
def test_user_rsvp_initial(self):
game = GameFactory()
data = {"status": RsvpStatus.STATUS_ACCEPTED}
url = reverse("game-rsvps-list", kwargs={"game_uuid": str(game.uuid)})
response = self.client.post(url, data, format="json")
self.assertEqual(201, response.status_code)
def test_user_rsvp_update(self):
rsvp = RsvpStatusFactory(user=self.user)
data = {"status": RsvpStatus.STATUS_ATTENDING}
url = reverse("game-rsvps-detail", kwargs={"game_uuid": str(rsvp.game.uuid), "uuid": str(rsvp.uuid)})
response = self.client.put(url, data, format="json")
self.assertEqual(200, response.status_code)
def test_user_rsvp_error(self):
rsvp = RsvpStatusFactory()
data = {"status": RsvpStatus.STATUS_ATTENDING}
url = reverse("game-rsvps-detail", kwargs={"game_uuid": str(rsvp.game.uuid), "uuid": str(rsvp.uuid)})
response = self.client.put(url, data, format="json")
self.assertEqual(400, response.status_code)
<file_sep>from .prd import * # noqa
MEDIA_URL = "https://sportyspots-stg.s3.amazonaws.com/"
CORS_ORIGIN_WHITELIST = [
"https://training.sportyspots.com",
"http://localhost:8000",
"http://localhost:8080",
"http://127.0.0.1:8000" "http://127.0.0.1:8080",
] + CORS_ORIGIN_WHITELIST
<file_sep>from django_filters import rest_framework as filters
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from seedorf.games.serializers import GameSportNestedSerializer
from seedorf.spots.serializers import SpotSportNestedSerializer
from seedorf.users.serializers import UserSportNestedSerializer
from seedorf.utils.permissions import IsAdminOrReadOnly
from seedorf.utils.regex import UUID as REGEX_UUID
from .models import Sport
from .serializers import SportSerializer
class SportFilter(filters.FilterSet):
class Meta:
model = Sport
strict = True
fields = {"category": ["exact"], "name": ["exact", "icontains"], "description": ["icontains"]}
class SportViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows all sports to be viewed.
"""
queryset = Sport.objects.filter(deleted_at=None)
serializer_class = SportSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
permission_classes = (IsAdminOrReadOnly,)
filter_backends = (filters.DjangoFilterBackend,)
filter_class = SportFilter
class SpotSportsNestedViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows sports available at a spot to be viewed.
"""
serializer_class = SpotSportNestedSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
permission_classes = (IsAuthenticatedOrReadOnly,)
http_method_names = ("options", "head", "get", "post")
def get_queryset(self):
return Sport.objects.filter(spots__uuid__in=[self.kwargs["spot_uuid"]])
class GameSportNestedViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows a sport associated with a game to be viewed.
"""
serializer_class = GameSportNestedSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
permission_classes = (IsAuthenticatedOrReadOnly,)
http_method_names = ("options", "head", "get", "post")
def get_queryset(self):
return Sport.objects.filter(sport_games__uuid=self.kwargs["game_uuid"])
class UserSportNestedViewSet(viewsets.ModelViewSet):
"""
API endpoint that shows sports followed by a user.
"""
serializer_class = UserSportNestedSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
permission_classes = (IsAuthenticatedOrReadOnly,)
http_method_names = ("options", "head", "get", "post")
def get_queryset(self):
return Sport.objects.filter(followers__user__uuid__exact=self.kwargs["user_uuid"])
<file_sep>from django.utils.translation import ugettext_lazy as _
from wagtail.core.models import Page
from wagtail.core.fields import StreamField
from wagtail.admin.edit_handlers import StreamFieldPanel
from .blocks import PageHomeStreamBlock
class PageHome(Page):
# page fields
body = StreamField(PageHomeStreamBlock(), blank=True, null=True)
# wagtail fields
template = "cms/page_home.html"
# page hierarchy
parent_page_types = ["wagtailcore.Page"]
# subpage_types = ["cms.PageGeneric",]
# panels
content_panels = Page.content_panels + [StreamFieldPanel("body")]
# NOTE: Allow creation of only one PageHome
# REF: https://stackoverflow.com/questions/37167863/limit-homepage-via-parent-page-types-to-be-only-available-as-direct-child-of-roo # noqa
@classmethod
def can_create_at(cls, parent: Page) -> bool:
return super(PageHome, cls).can_create_at(parent) and not cls.objects.exists()
class Meta:
verbose_name = _("homepage")
verbose_name_plural = _("homepages")
<file_sep>from django.utils.translation import ugettext_lazy as _
from rest_auth.utils import jwt_encode
from rest_framework import permissions, status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status
from seedorf.users.models import User, MagicLoginLink
@api_view()
def registration_null_view(request):
return Response(status=status.HTTP_400_BAD_REQUEST)
@api_view()
@permission_classes((permissions.AllowAny,))
def registration_status_view(request):
return Response(_("Email account is activated"))
@api_view(["POST"])
@permission_classes((permissions.AllowAny,))
def create_magic_link_view(request):
try:
user = User.objects.get(email__iexact=request.data["email"])
except User.DoesNotExist:
return Response(_("Email not registered"), status=status.HTTP_404_NOT_FOUND)
user.create_magic_link()
user.magic_link.mail()
return Response(_("Email sent"), status=status.HTTP_201_CREATED)
@api_view(["GET", "POST"])
@permission_classes((permissions.AllowAny,))
def confirm_magic_link_view(request):
token = request.data.get("token")
try:
magic_link = MagicLoginLink.objects.get(token=token)
except MagicLoginLink.DoesNotExist:
return Response(_("Invalid token"), status=status.HTTP_400_BAD_REQUEST)
return Response({"token": jwt_encode(magic_link.user)})
<file_sep>window.paceOptions = { startOnPageLoad: false }
import * as Pace from 'pace-js/pace.js'
function appendStylesheets() {
if (document.getElementById('pace-js-stylesheets')) return
const style = document.createElement('style')
style.type = 'text/css'
style.id = 'pace-js-stylesheets'
style.innerHTML = `
.pace {
display: block !important;
}
.page-loader {
display: none;
position: fixed;
height: 2px;
overflow: hidden;
top: 0;
left: 0;
right: 0;
z-index: 999999;
}
.page-loader div {
position: absolute;
top: 0;
bottom: 0;
transform: translate3d(0, 0, 0);
}
.pace-running:not(.pace-done) .page-loader {
display: block;
}
.pace-running:not(.pace-done) .page-loader div {
animation-duration: 1.2s;
animation-name: pageLoaderAnimation;
animation-iteration-count: infinite;
animation-timing-function: ease-in-out;
}
.turbolinks-progress-bar {
visibility: hidden !important;
}
[dir=rtl] .pace-running:not(.pace-done) .page-loader div,
[dir=rtl].pace-running:not(.pace-done) .page-loader div {
animation-name: pageLoaderAnimationRTL;
}
@-webkit-keyframes pageLoaderAnimation {
0% { right: 100%; left: 0; }
40% { right: 0; left: 0; }
60% { left: 0; right: 0; }
100% { left: 100%; right: 0; }
}
@keyframes pageLoaderAnimation {
0% { right: 100%; left: 0; }
40% { right: 0; left: 0; }
60% { left: 0; right: 0; }
100% { left: 100%; right: 0; }
}
@-webkit-keyframes pageLoaderAnimationRTL {
0% { left: 100%; right: 0; }
40% { left: 0; right: 0; }
60% { right: 0; left: 0; }
100% { right: 100%; left: 0; }
}
@keyframes pageLoaderAnimationRTL {
0% { left: 100%; right: 0; }
40% { left: 0; right: 0; }
60% { right: 0; left: 0; }
100% { right: 100%; left: 0; }
}
`
document.querySelector('head').appendChild(style)
}
appendStylesheets()
Pace.start()
// Ensure that Pace.js will be hidden on page loaded
function hidePaceLoader() {
setTimeout(function() {
Pace.stop()
}, 3000)
}
if (document.readyState === 'complete') hidePaceLoader()
else document.addEventListener('DOMContentLoaded', hidePaceLoader)
<file_sep># Generated by Django 2.1.2 on 2019-03-09 23:56
from django.db import migrations
import django_fsm
class Migration(migrations.Migration):
dependencies = [("games", "0009_unprotect_game_status")]
operations = [
migrations.AlterField(
model_name="rsvpstatus",
name="status",
field=django_fsm.FSMField(
choices=[
("accepted", "Accepted"),
("attending", "Attending"),
("checked_in", "Checked In"),
("declined", "Declined"),
("interested", "Interested"),
("invited", "Invited"),
("unknown", "Unknown"),
],
default="unknown",
max_length=25,
null=True,
verbose_name="Status",
),
)
]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-04-29 19:27
from __future__ import unicode_literals
import datetime
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import django_extensions.db.fields
import seedorf.spots.models
import seedorf.spots.validators
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [("sports", "0001_initial"), ("locations", "0001_initial")]
operations = [
migrations.CreateModel(
name="Spot",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("uuid", models.UUIDField(default=uuid.uuid4, editable=False, verbose_name="Unique Identifier")),
(
"created_at",
models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name="Created At"),
),
("modified_at", models.DateTimeField(auto_now=True, verbose_name="Modified At")),
("deleted_at", models.DateTimeField(blank=True, editable=False, null=True, verbose_name="Deleted At")),
("name", models.CharField(max_length=255, verbose_name="Name")),
(
"slug",
django_extensions.db.fields.AutoSlugField(
blank=True, editable=False, populate_from="name", unique=True, verbose_name="Slug"
),
),
("owner", models.CharField(blank=True, default="", max_length=255, verbose_name="Owner")),
("description", models.TextField(blank=True, default="", max_length=4096, verbose_name="Description")),
(
"logo",
models.ImageField(
blank=True,
max_length=255,
upload_to=seedorf.spots.models.get_logo_upload_directory,
verbose_name="Logo",
),
),
(
"homepage_url",
models.URLField(
blank=True,
help_text="Where can we find out more about this spot ?",
max_length=500,
verbose_name="Homepage URL",
),
),
(
"is_verified",
models.BooleanField(default=False, help_text="Is this Spot verfified by the SportySpots team ?"),
),
(
"is_permanently_closed",
models.BooleanField(default=False, help_text="Is this Spot permanently closed ?"),
),
("is_public", models.BooleanField(default=True, help_text="Is this Spot a public spot ?")),
(
"is_temporary",
models.BooleanField(default=False, help_text="Is this spot temporary (e.g. for a special event) ?"),
),
("establishment_date", models.DateField(blank=True, null=True)),
("closure_date", models.DateField(blank=True, null=True)),
(
"address",
models.OneToOneField(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="spot",
to="locations.Address",
verbose_name="Address",
),
),
("sports", models.ManyToManyField(related_name="spots", to="sports.Sport", verbose_name="Sports")),
],
options={"verbose_name": "Spot", "verbose_name_plural": "Spots", "ordering": ("-created_at",)},
),
migrations.CreateModel(
name="SpotAmenity",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("uuid", models.UUIDField(default=uuid.uuid4, editable=False, verbose_name="Unique Identifier")),
(
"created_at",
models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name="Created At"),
),
("modified_at", models.DateTimeField(auto_now=True, verbose_name="Modified At")),
("deleted_at", models.DateTimeField(blank=True, editable=False, null=True, verbose_name="Deleted At")),
(
"data",
django.contrib.postgres.fields.jsonb.JSONField(
validators=[
seedorf.spots.validators.AllowedKeysValidator(
[
"INDOOR",
"OUTDOOR",
"WIDTH",
"BREADTH",
"SIZE",
"HAS_FLOODLIGHTS",
"SURFACE",
"LOCATION",
"FENCE",
"FIELD_MARKINGS",
"SOCCER_GOALS_ONE_SIDED",
"SOCCER_GOALS_BOTH_SIDED",
"SOCCER_GOALS_SIZE",
"BASKETBALL_POLE_ONE_SIDED",
"BASKETBALL_POLE_BOTH_SIDED",
"MULTISPORT_FIELD",
]
)
]
),
),
(
"sport",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="amenities",
to="sports.Sport",
verbose_name="Sport",
),
),
(
"spot",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="amenities",
to="spots.Spot",
verbose_name="Spot",
),
),
],
options={"verbose_name": "Spot Amenity", "verbose_name_plural": "Spot Amenities"},
),
migrations.CreateModel(
name="SpotImage",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("uuid", models.UUIDField(default=uuid.uuid4, editable=False, verbose_name="Unique Identifier")),
(
"created_at",
models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name="Created At"),
),
("modified_at", models.DateTimeField(auto_now=True, verbose_name="Modified At")),
("deleted_at", models.DateTimeField(blank=True, editable=False, null=True, verbose_name="Deleted At")),
("image", models.ImageField(upload_to=seedorf.spots.models.get_images_upload_directory)),
(
"is_flagged",
models.BooleanField(
default=False, editable=False, help_text="Is this image marked as offensive/ non-relevant ?"
),
),
(
"is_user_submitted",
models.BooleanField(
default=True, editable=False, help_text="Is this image submitted by the user ?"
),
),
(
"sport",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="images",
to="sports.Sport",
verbose_name="Sport",
),
),
(
"spot",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="images",
to="spots.Spot",
verbose_name="Spot",
),
),
],
options={"verbose_name": "Spot Image", "verbose_name_plural": "Spot Images", "ordering": ("-created_at",)},
),
migrations.CreateModel(
name="SpotOpeningTime",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("uuid", models.UUIDField(default=uuid.uuid4, editable=False, verbose_name="Unique Identifier")),
(
"created_at",
models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name="Created At"),
),
("modified_at", models.DateTimeField(auto_now=True, verbose_name="Modified At")),
("deleted_at", models.DateTimeField(blank=True, editable=False, null=True, verbose_name="Deleted At")),
(
"day",
models.CharField(
choices=[
("MONDAY", "Monday"),
("TUESDAY", "Tuesday"),
("WEDNESDAY", "Wednesday"),
("THURSDAY", "Thursday"),
("FRIDAY", "Friday"),
("SATURDAY", "Saturday"),
("SUNDAY", "Sunday"),
],
max_length=25,
),
),
("start_time", models.TimeField(default=datetime.time(0, 0))),
("end_time", models.TimeField(default=datetime.time(23, 59, 59, 999999))),
("is_closed", models.BooleanField(default=False)),
(
"sport",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="opening_times",
to="sports.Sport",
verbose_name="Sport",
),
),
(
"spot",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="opening_times",
to="spots.Spot",
verbose_name="Spot",
),
),
],
options={"verbose_name": "Spot Opening Time", "verbose_name_plural": "Spot Opening Times"},
),
]
<file_sep>import * as Mapael from '../../node_modules/jquery-mapael/js/jquery.mapael.js';
export { Mapael };
<file_sep>from allauth.account.views import confirm_email as registration_confirm_email
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, re_path
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from graphene_django.views import GraphQLView
from rest_framework.documentation import include_docs_urls
from rest_framework.permissions import AllowAny
from rest_framework.schemas import get_schema_view as drf_get_schema_view
from rest_framework_jwt.views import refresh_jwt_token, verify_jwt_token
from rest_framework_nested import routers
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.core import urls as wagtail_urls
from wagtail.documents import urls as wagtaildocs_urls
from push_notifications.api.rest_framework import APNSDeviceAuthorizedViewSet, GCMDeviceAuthorizedViewSet
from seedorf.chatkit.views import ChatkitView
from seedorf.core.views import apple_app_site_association
from seedorf.games.views import GameDetailView, GameListView
from seedorf.games.viewsets import GameRsvpStatusNestedViewset, GameViewSet
from seedorf.graphql.schema import schema
from seedorf.sports.viewsets import GameSportNestedViewSet, SportViewSet, SpotSportsNestedViewSet
from seedorf.spots.viewsets import (
GameSpotNestedViewSet,
SpotAddressNestedViewSet,
SpotSportAmenitesNestedViewSet,
SpotSportImagesNestedViewSet,
SpotSportOpeningTimesNestedViewSet,
SpotViewSet,
)
from seedorf.users.views import (
confirm_magic_link_view,
create_magic_link_view,
registration_null_view,
registration_status_view,
)
from seedorf.users.viewsets import (
GameUserNestedViewSet,
UserProfileNestedViewSet,
UserProfileSportNestedViewSet,
UserProfileSpotNestedViewSet,
UserViewSet,
)
drf_schema_view = drf_get_schema_view(title="SportySpots API")
schema_view = get_schema_view(
openapi.Info(
title="SportySpots API",
default_version="v1",
description="SportySpots API description",
terms_of_service="https://www.sportyspots.com/policies/terms/",
contact=openapi.Contact(email="<EMAIL>"),
license=openapi.License(name="MIT License"),
),
validators=["flex", "ssv"],
public=True,
permission_classes=(AllowAny,),
)
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
# Sport urls
# ------------------------------------------------------------------------------
# /api/sports/
router.register(r"sports", SportViewSet)
# User urls
# ------------------------------------------------------------------------------
# /api/users/
router.register(r"users", UserViewSet)
users_router = routers.NestedDefaultRouter(router, r"users", lookup="user")
users_router.register(r"device/apns", APNSDeviceAuthorizedViewSet, base_name="user-ios-push-notification")
users_router.register(r"device/fcm", GCMDeviceAuthorizedViewSet, base_name="user-fcm-push-notification")
# /api/users/<uuid>/profile
users_router.register(r"profile", UserProfileNestedViewSet, base_name="user-profile")
users_profile_router = routers.NestedDefaultRouter(users_router, r"profile", lookup="profile")
# /api/users/<uuid>/profile/<uuid>/sports/
users_profile_router.register(r"sports", UserProfileSportNestedViewSet, base_name="user-profile-sports")
# /api/users/<uuid>/profile/<uuid>/spots/
users_profile_router.register(r"spots", UserProfileSpotNestedViewSet, base_name="user-profile-spots")
# Spots urls
# ------------------------------------------------------------------------------
# /api/spots/
router.register(r"spots", SpotViewSet)
spots_router = routers.NestedDefaultRouter(router, r"spots", lookup="spot")
# /api/spots/<uuid>/address
spots_router.register(r"address", SpotAddressNestedViewSet, base_name="spot-address")
# /api/spots/<uuid>/sports
spots_router.register(r"sports", SpotSportsNestedViewSet, base_name="spot-sports")
# /api/spots/<uuid>/sports/<uuid>/images
spot_sports_images_router = routers.NestedDefaultRouter(spots_router, r"sports", lookup="sport")
spot_sports_images_router.register(r"images", SpotSportImagesNestedViewSet, base_name="spot-sport-images")
# /api/spots/<uuid>sports/<uuid>/amenities
spot_sports_amenities_router = routers.NestedDefaultRouter(spots_router, r"sports", lookup="sport")
spot_sports_amenities_router.register(r"amenities", SpotSportAmenitesNestedViewSet, base_name="spot-sport-amenities")
# /api/spots/<uuid>/sports/<uuid>/opening-times
spot_sports_opening_times_router = routers.NestedDefaultRouter(spots_router, r"sports", lookup="sport")
spot_sports_opening_times_router.register(
r"opening-times", SpotSportOpeningTimesNestedViewSet, base_name="spot-sport-opening-times"
)
# Game urls
# ------------------------------------------------------------------------------
# /api/games/
router.register(r"games", GameViewSet)
games_router = routers.NestedDefaultRouter(router, r"games", lookup="game")
# /api/games/<uuid>/organizer
games_router.register(r"organizer", GameUserNestedViewSet, base_name="game-organizer")
# /api/games/<uuid>/rsvps
games_router.register(r"rsvps", GameRsvpStatusNestedViewset, base_name="game-rsvps")
# /api/games/<uuid>/sport
games_router.register(r"sport", GameSportNestedViewSet, base_name="game-sport")
# /api/games/<uuid>/spot
games_router.register(r"spot", GameSpotNestedViewSet, base_name="game-spot")
urlpatterns = [
# Django Admin, use {% url 'admin:index' %}
# ------------------------------------------------------------------------------
path(settings.ADMIN_URL, admin.site.urls),
# SportySpots Static Web Frontend
# ------------------------------------------------------------------------------
path("dashboard/", TemplateView.as_view(template_name="pages/dashboard_home.html")),
path("register/", TemplateView.as_view(template_name="pages/login_register.html")),
path("login/", TemplateView.as_view(template_name="pages/login_register.html")),
path("password-reset/", TemplateView.as_view(template_name="pages/password_reset.html")),
path("confirm-email/", TemplateView.as_view(template_name="pages/confirm_email.html")),
path("games/<uuid:uuid>/", GameDetailView.as_view(), name="web-game-detail"),
path("games/", GameListView.as_view(), name="web-game-list"),
# Wagtail
# ------------------------------------------------------------------------------
path("cms/", include(wagtailadmin_urls)),
path("documents/", include(wagtaildocs_urls)),
path("pages/", include(wagtail_urls)),
# Anymail
# ------------------------------------------------------------------------------
path("anymail/", include("anymail.urls")),
# Authentication / Registration
# ------------------------------------------------------------------------------
# REF: https://github.com/blakey22/rest_email_signup
path(
"api/auth/registration/email-verification-sent/", registration_null_view, name="account_email_verification_sent"
),
re_path(
r"^api/auth/registration/confirm-email/(?P<key>[-:\w]+)/$",
registration_confirm_email,
name="account_confirm_email",
),
path("api/auth/registration/status/", registration_status_view, name="account_confirm_status"),
path("api/auth/create-magic-link/", csrf_exempt(create_magic_link_view), name="account_create_magic_link"),
path("api/auth/confirm-magic-link/", csrf_exempt(confirm_magic_link_view), name="account_confirm_magic_link"),
re_path(
r"^api/auth/password-reset/confirm/"
r"(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[<KEY>/$",
registration_null_view,
name="password_reset_confirm",
),
path("api/auth/token-refresh/", refresh_jwt_token, name="token-refesh"),
path("api/auth/token-verify/", verify_jwt_token, name="token-verify"),
path("api/auth/", include("rest_auth.urls")),
path(
"api/auth/registration/",
include(("rest_auth.registration.urls", "rest_auth.registration"), namespace="rest-auth-registration"),
),
# AllAuth
# ------------------------------------------------------------------------------
path("api/accounts/", include("allauth.urls")),
# Chatkit authentication
# ------------------------------------------------------------------------------
path("api/chatkit/auth/", ChatkitView.as_view(), name="chatkit_auth"),
# REST API
# ------------------------------------------------------------------------------
path("api/", include(router.urls), name="api-core"),
path("api/", include(users_router.urls), name="api-users"),
path("api/", include(spots_router.urls), name="api-spots"),
path("api/", include(games_router.urls), name="api-games"),
path("api/", include(users_profile_router.urls), name="api-user-profile"),
path("api/", include(spot_sports_images_router.urls), name="api-spot-sports-images"),
path("api/", include(spot_sports_amenities_router.urls), name="api-spot-sports-amenities"),
path("api/", include(spot_sports_opening_times_router.urls), name="api-spot-sports-opening-times"),
# GraphQL API
# ------------------------------------------------------------------------------
path("graphql", csrf_exempt(GraphQLView.as_view(graphiql=True, schema=schema)), name="graphql"),
# TODO: Choose one of the api documentation tools below
# DRF schema
# ------------------------------------------------------------------------------
path("schema/", drf_schema_view),
path("docs/", include_docs_urls(title="SportySpots API Docs", permission_classes=(AllowAny,))),
# Swagger
# ------------------------------------------------------------------------------
re_path(r"^swagger(?P<format>\.json|\.yaml)$", schema_view.without_ui(cache_timeout=None), name="schema-json"),
path("swagger/", schema_view.with_ui("swagger", cache_timeout=None), name="schema-swagger-ui"),
path("redoc/", schema_view.with_ui("redoc", cache_timeout=None), name="schema-redoc"),
# Apple ios deeplinking - app site association
# ------------------------------------------------------------------------------
path("apple-app-site-association/?", apple_app_site_association, name="apple-app-site-association"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
# This allows the error pages to be debugged during development, just visit
# these url in browser to see how these error pages look like.
urlpatterns += [
path("400/", TemplateView.as_view(template_name="400.html")),
path("403/", TemplateView.as_view(template_name="403_csrf.html")),
path("404/", TemplateView.as_view(template_name="404.html")),
path("500/", TemplateView.as_view(template_name="500.html")),
]
if "debug_toolbar" in settings.INSTALLED_APPS:
import debug_toolbar
urlpatterns = [url(r"^__debug__/", include(debug_toolbar.urls))] + urlpatterns
# If non of the above matches, pass it on to wagtail
urlpatterns += [re_path(r"", include(wagtail_urls))]
<file_sep>import factory
from seedorf.users.models import User, UserProfile
from seedorf.sports.tests.factories import SportFactory
from seedorf.spots.tests.factories import SpotFactory
from django.db.models.signals import post_save
class UserFactory(factory.django.DjangoModelFactory):
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
name = factory.LazyAttribute(lambda o: "{} {}".format(o.first_name.lower(), o.last_name.lower()))
username = factory.LazyAttribute(lambda o: "{}.{}".format(o.first_name.lower(), o.last_name.lower()))
email = factory.LazyAttribute(lambda o: <EMAIL>".format(o.first_name.lower(), o.last_name.lower()))
password = factory.PostGenerationMethodCall("set_password", "<PASSWORD>")
is_staff = False
# profile = factory.PostGeneration(lambda obj, create, extracted, **kwargs: UserProfileFactory.create(user=obj))
@factory.post_generation
def groups(self, create, extracted, **kwargs):
"""
USAGE: UserFactory.create(groups=(group1, group2, group3))
"""
if not create:
# Simple build, do nothing.
return
if extracted:
# A list of groups were passed in, use them
for group in extracted:
self.groups.add(group)
class Meta:
model = User
django_get_or_create = ("email",)
class StaffUserFactory(UserFactory):
is_staff = True
class SuperUserFactory(UserFactory):
is_superuser = True
@factory.django.mute_signals(post_save)
class UserProfileFactory(factory.django.DjangoModelFactory):
user = factory.SubFactory(UserFactory)
gender = factory.Iterator(UserProfile.GENDERS, getter=lambda g: g[0])
year_of_birth = 1980
avatar = factory.django.ImageField()
country = "NL"
bio = factory.Faker("text")
class Meta:
model = UserProfile
@factory.post_generation
def sports(self, create, extracted, **kwargs):
# REF: http://factoryboy.readthedocs.io/en/latest/recipes.html#simple-many-to-many-relationship
if not create:
# Simple build, do nothing.
return
if extracted:
# A list of sports were passed in, use them
for sport in extracted:
self.sports.add(sport)
else:
sport = SportFactory()
self.sports.add(sport)
@factory.post_generation
def spots(self, create, extracted, **kwargs):
# REF: http://factoryboy.readthedocs.io/en/latest/recipes.html#simple-many-to-many-relationship
if not create:
# Simple build, do nothing.
return
if extracted:
# A list of sports were passed in, use them
for spot in extracted:
self.spots.add(spot)
else:
spot = SpotFactory()
self.spots.add(spot)
<file_sep>{% load static wagtailcore_tags i18n %}
<div class="landing-block {{ value.background }}">
<div class="container px-3">
<div class="col-md-10 col-lg-8 col-xl-7 text-center p-0 mx-auto">
<h1 class="display-4">
The Sporty Crew
</h1>
<div class="lead pb-3 mt-4 mb-5">
Lorem ipsum dolor sit amet, ad eam consul vituperata. Cum assum inimicus an, his ne liber aeterno debitis. Te
his iudico tollit efficiendi.
</div>
</div>
<div class="row text-center">
<div class="col-sm-6 col-lg-6 p-4">
<img src="{% static 'images/avatars/1.png' %}" class="ui-w-120 rounded-circle mb-4" alt="">
<h5 class="font-weight-bold mb-2"><NAME></h5>
<div class="text-light small mb-3">Creative director</div>
<div class="">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent condimentum maximus lectus eget auctor.
</div>
</div>
<div class="col-sm-6 col-lg-6 p-4">
<img src="{% static 'images/avatars/2.png' %}" class="ui-w-120 rounded-circle mb-4" alt="">
<h5 class="font-weight-bold mb-2"><NAME></h5>
<div class="text-light small mb-3">Customer support</div>
<div class="">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent condimentum maximus lectus eget auctor.
</div>
</div>
<div class="col-sm-6 col-lg-6 p-4">
<img src="{% static 'images/avatars/3.png' %}" class="ui-w-120 rounded-circle mb-4" alt="">
<h5 class="font-weight-bold mb-2"><NAME></h5>
<div class="text-light small mb-3">CEO & Design</div>
<div class="">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent condimentum maximus lectus eget auctor.
</div>
</div>
<div class="col-sm-6 col-lg-6 p-4">
<img src="{% static 'images/avatars/4.png' %}" class="ui-w-120 rounded-circle mb-4" alt="">
<h5 class="font-weight-bold mb-2"><NAME></h5>
<div class="text-light small mb-3">Senior engineer</div>
<div class="">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent condimentum maximus lectus eget auctor.
</div>
</div>
</div>
</div>
</div>
<file_sep>from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.measure import D
from django.contrib.gis.db.models.functions import Distance
from django_filters import rest_framework as filters
from seedorf.sports.models import Sport
from .models import Spot
class SpotFilter(filters.FilterSet):
sports__ids = filters.ModelMultipleChoiceFilter(field_name="sports", queryset=Sport.objects.all())
distance = filters.CharFilter(field_name="address__point", method="filter_by_distance")
class Meta:
model = Spot
strict = True
fields = {
"sports__category": ["exact"],
# 'sports__uuid': ['exact', ],
"name": ["exact", "icontains"],
"owner": ["exact", "icontains"],
"is_verified": ["exact"],
"is_permanently_closed": ["exact"],
"is_public": ["exact"],
"is_temporary": ["exact"],
}
# REF: https://django-filter.readthedocs.io/en/master/ref/filters.html#method
@staticmethod
def filter_by_distance(queryset, name, value):
# TODO: Validate distance is integer, and the lat and lng values are valid
radius, lat, lng = value.split(":")
# REF: https://docs.djangoproject.com/en/2.0/ref/contrib/gis/db-api/#distance-lookups
ref_location = GEOSGeometry(f"POINT({lng} {lat})", srid=4326)
lookup = f"{name}__distance_lte"
qs = queryset.filter(**{lookup: (ref_location, D(m=int(radius)))}).annotate(
distance=Distance("address__point", ref_location)
)
return qs
<file_sep>import * as Swiper from '../../node_modules/swiper/dist/js/swiper.js';
export { Swiper };
<file_sep>import * as numeral from '../../node_modules/numeral/numeral.js';
require('../../node_modules/numeral/locales.js');
export { numeral };
<file_sep>#!/usr/bin/env bash
${ENV:?"Please set ENV non-empty"}
set -o errexit
set -o pipefail
set -o nounset
if [ "$ENV" == "dev" ]
then
set -o xtrace
rm -f './celerybeat.pid'
celery -A seedorf.taskapp beat -l INFO
elif [ "$ENV" == "prd" ]
then
celery -A seedorf.taskapp beat -l INFO
else
echo "Invalid ENV variable"
exit
fi
<file_sep>from django.views.generic import DetailView, ListView
from django_filters.views import FilterView
from datetime import timedelta
from django.utils import timezone
from .filters import GameWebFilter
from .models import Game
# REF: https://www.caktusgroup.com/blog/2018/10/18/filtering-and-pagination-django/
class FilteredListView(ListView):
filterset_class = None
def get_queryset(self):
# Get the queryset however you usually would. For example:
queryset = super().get_queryset()
# Then use the query parameters and the queryset to
# instantiate a filterset and save it as an attribute
# on the view instance for later.
self.filterset = self.filterset_class(self.request.GET, queryset=queryset)
# Return the filtered queryset
return self.filterset.qs.distinct()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# Pass the filterset to the template - it provides the form.
context["filterset"] = self.filterset
return context
class GameDetailView(DetailView):
model = Game
slug_field = "uuid"
slug_url_kwarg = "uuid"
template_name = "pages/website_game_detail.html"
class GameListView(FilteredListView):
model = Game
context_object_name = "games"
template_name = "pages/website_game_list.html"
filterset_class = GameWebFilter
paginate_by = 5
queryset = Game.objects.filter(
status__in=[
Game.STATUS_PLANNED,
Game.STATUS_LIVE,
Game.STATUS_STARTED,
Game.STATUS_CANCELED,
Game.STATUS_COMPLETED,
],
start_time__gte=timezone.now() - timedelta(hours=1),
)
<file_sep>#!/usr/bin/env bash
${ENV:?"Please set ENV non-empty"}
set -o errexit
set -o pipefail
set -o nounset
if [ "$ENV" == "dev" ]
then
set -o xtrace
fi
celery -A seedorf.taskapp worker -l INFO
<file_sep>import * as Chart from '../../node_modules/chart.js/dist/Chart.js';
export { Chart };
<file_sep># Generated by Django 2.1.2 on 2019-03-04 19:57
from django.db import migrations, models
import seedorf.users.models
class Migration(migrations.Migration):
dependencies = [("users", "0006_magicloginlink")]
operations = [
migrations.AlterField(
model_name="magicloginlink",
name="token",
field=models.CharField(default="dummy", max_length=32, unique=True, verbose_name="Token"),
)
]
<file_sep>from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from seedorf.locations.serializers import AddressSerializer
from seedorf.sports.models import Sport
from seedorf.sports.serializers import SportSerializer
from .models import Spot, SpotAmenity, SpotImage, SpotOpeningTime
class AmenitySerializer(serializers.ModelSerializer):
class Meta:
model = SpotAmenity
fields = ("uuid", "data", "created_at", "modified_at")
read_only_fields = ("uuid", "created_at", "modified_at")
def create(self, validated_data):
spot_uuid = self.context["view"].kwargs["spot_uuid"]
sport_uuid = self.context["view"].kwargs["sport_uuid"]
spot = Spot.objects.get(uuid=spot_uuid)
sport = Sport.objects.get(uuid=sport_uuid)
amenity = SpotAmenity.objects.create(spot=spot, sport=sport, **validated_data)
return amenity
class OpeningTimeSerializer(serializers.ModelSerializer):
class Meta:
model = SpotOpeningTime
fields = ("uuid", "day", "start_time", "end_time", "is_closed", "created_at", "modified_at")
read_only_fields = ("uuid", "created_at", "modified_at")
def create(self, validated_data):
spot_uuid = self.context["view"].kwargs["spot_uuid"]
sport_uuid = self.context["view"].kwargs["sport_uuid"]
spot = Spot.objects.get(uuid=spot_uuid)
sport = Sport.objects.get(uuid=sport_uuid)
opening_time = SpotOpeningTime.objects.create(spot=spot, sport=sport, **validated_data)
return opening_time
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = SpotImage
fields = ("uuid", "image", "is_flagged", "is_user_submitted", "created_at", "modified_at")
read_only_fields = ("uuid", "created_at", "modified_at")
def create(self, validated_data):
spot_uuid = self.context["view"].kwargs["spot_uuid"]
sport_uuid = self.context["view"].kwargs["sport_uuid"]
spot = Spot.objects.get(uuid=spot_uuid)
sport = Sport.objects.get(uuid=sport_uuid)
image = SpotImage.objects.create(spot=spot, sport=sport, **validated_data)
return image
class SpotSportNestedSerializer(serializers.ModelSerializer):
uuid = serializers.UUIDField(required=True)
amenities = serializers.SerializerMethodField()
opening_times = serializers.SerializerMethodField()
images = serializers.SerializerMethodField()
class Meta:
model = Sport
fields = (
"uuid",
"category",
"name",
"description",
"amenities",
"opening_times",
"images",
"created_at",
"modified_at",
)
read_only_fields = (
"category",
"name",
"description",
"amenities",
"opening_times",
"images",
"created_at",
"modified_at",
)
def create(self, validated_data):
spot_uuid = self.context["view"].kwargs["spot_uuid"]
spot = Spot.objects.get(uuid=spot_uuid)
sport_uuid = validated_data["uuid"]
try:
sport = Sport.objects.get(uuid=sport_uuid)
except Sport.DoesNotExist:
raise serializers.ValidationError(_("Invalid Sport"))
spot.sports.clear()
spot.sports.add(sport)
return sport
@staticmethod
def get_spot_uuid(context):
if context["view"].basename in ["spot", "user"]:
spot_uuid = context["spot_uuid"]
elif context["view"].basename == "spot-sports":
spot_uuid = context["view"].kwargs["spot_uuid"]
return spot_uuid
def get_images(self, obj):
spot_uuid = self.get_spot_uuid(self.context)
images = SpotImage.objects.filter(sport__uuid=obj.uuid, spot__uuid=spot_uuid)
return ImageSerializer(images, many=True, context={"request": self.context["request"]}).data
def get_opening_times(self, obj):
spot_uuid = self.get_spot_uuid(self.context)
opening_times = SpotOpeningTime.objects.filter(sport__uuid=obj.uuid, spot__uuid=spot_uuid)
return OpeningTimeSerializer(opening_times, many=True).data
def get_amenities(self, obj):
spot_uuid = self.get_spot_uuid(self.context)
amenities = SpotAmenity.objects.filter(sport__uuid=obj.uuid, spot__uuid=spot_uuid)
return AmenitySerializer(amenities, many=True).data
class SpotSerializer(serializers.ModelSerializer):
# TODO: is_verified can only be set by staff, currently its is covered by IsAdminOrReadOnly permission
# TODO: is_permanently_closed can only be set by staff, currently is covered by IsAdminOrReadOnly permission
address = serializers.SerializerMethodField()
sports = SportSerializer(many=True, required=False)
class Meta:
model = Spot
fields = (
"uuid",
"address",
"sports",
"name",
"slug",
"owner",
"description",
"logo",
"homepage_url",
"is_verified",
"is_permanently_closed",
"is_public",
"is_temporary",
"establishment_date",
"closure_date",
"created_at",
"modified_at",
"deleted_at",
)
read_only_fields = ("uuid", "created_at", "modified_at")
def create(self, validated_data):
spot = Spot.objects.create(**validated_data)
return spot
def update(self, instance, validated_data):
for k, v in validated_data.items():
setattr(instance, k, v)
instance.save()
return instance
def get_address(self, obj):
if obj.address is None:
return None
else:
return AddressSerializer(obj.address, many=False, read_only=True, context=self.context).data
<file_sep>from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
def send_mail(to, template_prefix, subject="", language="en", context=None):
html_template = get_template(f"emails/{template_prefix}-{language}.html")
text_template = get_template(f"emails/{template_prefix}-{language}.txt")
email_plain_text = text_template.render(context if context else {})
email_html = html_template.render(context if context else {})
msg = EmailMultiAlternatives(
subject=subject,
body=email_plain_text,
from_email="SportySpots <<EMAIL>>",
to=[f"{to}"],
reply_to=["SportySpots <<EMAIL>>"],
)
msg.attach_alternative(email_html, "text/html")
# Optional Anymail extensions:
# msg.tags = ["activation"]
# msg.track_clicks = True
# msg.track_opens = True
# Send it:
msg.send()
<file_sep># seedorf
[](https://travis-ci.org/SportySpots/seedorf) [](https://greenkeeper.io/) [](https://pyup.io/repos/github/SportySpots/seedorf/) [](https://pyup.io/repos/github/SportySpots/seedorf/)
## Introduction
Find sporty spots and sporty people near you.
:License: MIT
## Requirements
* python = 3.6.4
* pipenv = 11.7.2
* docker =
* docker-compose =
* postgresql = 9.6.8
* terraform = v0.11.3
* git-crypt = 0.6.0
## Settings
Moved to settings_.
[settings](http://cookiecutter-django.readthedocs.io/en/latest/settings.html)
## Git Crypt
### Install
```bash
$ brew install git-crypt
```
### Introduction
Git crypt is used encrypt the sensitive data (e.g. *.tfstate). The files encrypted by git-crypt are defined in .gitattributes
### Generate a new GPG key
[Github Article](https://help.github.com/articles/generating-a-new-gpg-key/)
### Adding new contributors
```bash
$ gpg --list-secret-keys --keyid-format LONG
/Users/hubot/.gnupg/secring.gpg
------------------------------------
sec 4096R/3AA5C34371567BD2 2016-03-10 [expires: 2017-03-10]
uid Hubot
ssb 4096R/42B317FD4BA89E7A 2016-03-10
$ git-crypt add-gpg-user --trusted 3AA5C34371567BD2
```
### Decrypting
```bash
$ cd seedorf
$ git-crypt unlock
```
## Terraform
### Settings
Define the following environment variables
```bash
$ export TF_VAR_aws_root_access_key_id=XXX
$ export TF_VAR_aws_root_access_key_secret=XXX
```
### Initialize
Initialize terraform to download AWS provider plugin
```bash
$ cd terraform
$ terraform init
```
### Commands
## AWS Planning
### VPC by Region
| Region | CIDR | Start IP | End IP | Max IPs | Env |
|--------------|--------------|-----------|---------------|---------|-----|
| eu-central-1 | 10.0.0.0/16 | 10.0.0.0 | 10.0.255.255 | 65536 | PRD |
| eu-central-1 | 10.1.0.0/16 | 10.1.0.0 | 10.1.255.255 | 65536 | STG |
| eu-central-1 | 10.2.0.0/16 | 10.2.0.0 | 10.2.255.255 | 65536 | TST |
| eu-central-1 | 10.3.0.0/16 | 10.3.0.0 | 10.3.255.255 | 65536 | DEV |
| eu-west-1 | 10.10.0.0/16 | 10.10.0.0 | 10.10.255.255 | 65536 | PRD |
| eu-west-1 | 10.11.0.0/16 | 10.11.0.0 | 10.11.255.255 | 65536 | STG |
| eu-west-1 | 10.12.0.0/16 | 10.12.0.0 | 10.12.255.255 | 65536 | TST |
| eu-west-1 | 10.13.0.0/16 | 10.13.0.0 | 10.13.255.255 | 65536 | DEV |
### VPC Subnet by Availability Zone
| Region | Availability Zone | CIDR | Start IP | End IP | Total IPs | Env |
|--------------|-------------------|-------------- |----------- |------------- |-----------|-----|
| eu-central-1 | eu-central-1a | 10.0.0.0/20 | 10.0.0.0 | 10.0.15.255 | 4096 | PRD |
| eu-central-1 | eu-central-1b | 10.0.16.0/20 | 10.0.16.0 | 10.0.31.255 | 4096 | PRD |
| eu-central-1 | eu-central-1c | 10.0.32.0/20 | 10.0.32.0 | 10.0.47.255 | 4096 | PRD |
| eu-central-1 | eu-central-1a | 10.1.0.0/20 | 10.1.0.0 | 10.1.15.255 | 4096 | STG |
| eu-central-1 | eu-central-1b | 10.1.16.0/20 | 10.1.16.0 | 10.1.31.255 | 4096 | STG |
| eu-central-1 | eu-central-1c | 10.1.32.0/20 | 10.1.32.0 | 10.1.47.255 | 4096 | STG |
| eu-central-1 | eu-central-1a | 10.2.0.0/20 | 10.2.0.0 | 10.2.15.255 | 4096 | TST |
| eu-central-1 | eu-central-1b | 10.2.16.0/20 | 10.2.16.0 | 10.2.31.255 | 4096 | TST |
| eu-central-1 | eu-central-1c | 10.2.32.0/20 | 10.2.32.0 | 10.2.47.255 | 4096 | TST |
| eu-central-1 | eu-central-1a | 10.3.0.0/20 | 10.3.0.0 | 10.3.15.255 | 4096 | DEV |
| eu-central-1 | eu-central-1b | 10.3.16.0/20 | 10.3.16.0 | 10.3.31.255 | 4096 | DEV |
| eu-central-1 | eu-central-1c | 10.3.32.0/20 | 10.3.32.0 | 10.3.47.255 | 4096 | DEV |
| eu-west-1 | eu-west-1a | 10.10.0.0/20 | 10.10.0.0 | 10.10.15.255 | 4096 | PRD |
| eu-west-1 | eu-west-1b | 10.10.16.0/20 | 10.10.16.0 | 10.10.31.255 | 4096 | PRD |
| eu-west-1 | eu-west-1c | 10.10.32.0/20 | 10.10.32.0 | 10.10.47.255 | 4096 | PRD |
| eu-west-1 | eu-west-1a | 10.11.0.0/20 | 10.11.0.0 | 10.11.15.255 | 4096 | STG |
| eu-west-1 | eu-west-1b | 10.11.16.0/20 | 10.11.16.0 | 10.11.31.255 | 4096 | STG |
| eu-west-1 | eu-west-1c | 10.11.32.0/20 | 10.11.32.0 | 10.11.47.255 | 4096 | STG |
| eu-west-1 | eu-west-1a | 10.12.0.0/20 | 10.12.0.0 | 10.12.15.255 | 4096 | TST |
| eu-west-1 | eu-west-1b | 10.12.16.0/20 | 10.12.16.0 | 10.12.31.255 | 4096 | TST |
| eu-west-1 | eu-west-1c | 10.12.32.0/20 | 10.12.32.0 | 10.12.47.255 | 4096 | TST |
| eu-west-1 | eu-west-1a | 10.13.0.0/20 | 10.13.0.0 | 10.13.15.255 | 4096 | DEV |
| eu-west-1 | eu-west-1b | 10.13.16.0/20 | 10.13.16.0 | 10.13.31.255 | 4096 | DEV |
| eu-west-1 | eu-west-1c | 10.13.32.0/20 | 10.13.32.0 | 10.13.47.255 | 4096 | DEV |
## Docker
### Commands
Build and run local docker compose setup
```bash
$ docker-compose -f docker_compose_local.yml up -d
```
Stop setup
```bash
$ docker-compose -f docker_compose_local.yml down
```
Create superuser
```bash
$ docker-compose -f docker_compose_local.yml run --rm django python manage.py createsuperuser --username admin --email <EMAIL>
```
Create Sports Fixtures
```bash
$ docker-compose --file docker_compose_local.yml run --rm django ./manage.py loaddata seedorf/sports/fixtures/sports.json
```
Find AWS ECR repository Uri
```bash
$ aws ecr describe-repositories | jq '.repositories | .[] | .repositoryUri'
```
Create production image for ECR
```bash
$ docker build -t sportyspots --build-arg GIT_COMMIT=$(git log -1 --format="%H") -f compose/production/django/Dockerfile .
```
Tag image with AWS Uri
```bash
$ docker tag sportyspots XXXXXX.dkr.ecr.eu-central-1.amazonaws.com/sportyspots
```
Get login token from ecr if required
```bash
$ $(aws ecr get-login --no-include-email)
```
### Django Frontend URLs'
#### API Docs
http://127.0.0.1:8000/docs
#### Django Admin
http://127.0.0.1:8000/admin
#### Django API
http://127.0.0.1:8000/api
#### Mailhog
http://127.0.0.1:8025/
## Basic Commands
### Setting Up Your Users
* To create a **normal user account**, just go to Sign Up and fill out the form. Once you submit it, you'll see a "Verify Your E-mail Address" page. Go to your console to see a simulated email verification message. Copy the link into your browser. Now the user's email should be verified and ready to go.
* To create an **superuser account**, use this command::
```bash
$ python manage.py createsuperuser
```
For convenience, you can keep your normal user logged in on Chrome and your superuser logged in on Firefox (or similar), so that you can see how the site behaves for both kinds of users.
### Test coverage
To run the tests, check your test coverage, and generate an HTML coverage report::
```bash
$ coverage run manage.py test
$ coverage html
$ open htmlcov/index.html
```
### Running test
```bash
$ PIPENV_DOTENV_LOCATION=.env.test pipenv run ./manage.py test
```
### Running tests with py.test
```bash
$ PIPENV_DOTENV_LOCATION=.env.test pipenv run pytest
```
## Live reloading and Sass CSS compilation
Moved to `Live reloading and SASS compilation`_.
[Live reloading and SASS compilation](http://cookiecutter-django.readthedocs.io/en/latest/live-reloading-and-sass-compilation.html)
### Celery
This app comes with Celery.
To run a celery worker:
```bash
cd seedorf
celery -A seedorf.taskapp worker -l info
```
Please note: For Celery's import magic to work, it is important *where* the celery commands are run. If you are in the same folder with *manage.py*, you should be right.
### Email Server
In development, it is often nice to be able to see emails that are being sent from your application. For that reason local SMTP server `MailHog`_ with a web interface is available as docker container.
[mailhog](https://github.com/mailhog/MailHog)
Container mailhog will start automatically when you will run all docker containers.
Please check `cookiecutter-django Docker documentation`_ for more details how to start all containers.
With MailHog running, to view messages that are sent by your application, open your browser and go to ``http://127.0.0.1:8025``
### Sentry
Sentry is an error logging aggregator service. You can sign up for a free account at https://sentry.io/signup/?code=cookiecutter or download and host it yourself.
The system is setup with reasonable defaults, including 404 logging and integration with the WSGI application.
You must set the DSN url in production.
## Deployment
The following details how to deploy this application.
### Docker
See detailed `cookiecutter-django Docker documentation`_.
[cookiecutter-django Docker documentation](http://cookiecutter-django.readthedocs.io/en/latest/deployment-with-docker.html)
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-06-18 16:08
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("users", "0003_auto_20180602_2110")]
operations = [
migrations.AlterField(
model_name="userprofile",
name="sports",
field=models.ManyToManyField(
blank=True, related_name="followers", to="sports.Sport", verbose_name="Favourite Sports"
),
),
migrations.AlterField(
model_name="userprofile",
name="spots",
field=models.ManyToManyField(
blank=True, related_name="followers", to="spots.Spot", verbose_name="Favourite Spots"
),
),
]
<file_sep>"""
Django settings for seedorf project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import datetime
import environ
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse_lazy
ROOT_DIR = environ.Path(__file__) - 3 # (seedorf/config/settings/base.py - 3 = seedorf/)
APPS_DIR = ROOT_DIR.path("seedorf")
# Load operating system environment variables and then prepare to use them
env = environ.Env()
# .env file, should load only in development environment
READ_DOT_ENV_FILE = env.bool("DJANGO_READ_DOT_ENV_FILE", default=False)
if READ_DOT_ENV_FILE:
# Operating System Environment variables have precedence over variables defined in the .env file,
# that is to say variables from the .env files will only be used if not defined
# as environment variables.
env_file = str(ROOT_DIR.path(".env"))
print(f"Loading : {env_file}")
env.read_env(env_file)
print("The .env file has been loaded. See base.py for more information")
# APP CONFIGURATION
# ------------------------------------------------------------------------------
DJANGO_APPS = [
# Default Django apps:
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.messages",
"django.contrib.staticfiles",
"django.contrib.humanize",
# Admin
"django.contrib.admin",
# Additional support for Full text search, JSONB Field, HSTORE Field
"django.contrib.postgres",
"django.contrib.gis",
]
THIRD_PARTY_APPS = [
"rest_framework",
"rest_framework_gis",
# http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
"rest_framework.authtoken",
"rest_auth",
"rest_auth.registration",
"allauth",
"allauth.account",
"allauth.socialaccount",
"allauth.socialaccount.providers.google",
"allauth.socialaccount.providers.facebook",
"crispy_forms",
"graphene_django",
# solr/elastic-search
"haystack",
"django_filters",
"django_countries",
"timezone_field",
"corsheaders",
"drf_yasg",
# wagtail
"wagtail.contrib.forms",
"wagtail.contrib.redirects",
"wagtail.embeds",
"wagtail.sites",
"wagtail.users",
"wagtail.snippets",
"wagtail.documents",
"wagtail.images",
"wagtail.search",
"wagtail.admin",
"wagtail.core",
"modelcluster",
"taggit",
# push notifications
"push_notifications",
]
# Apps specific for this project go here.
LOCAL_APPS = [
"seedorf.cms.apps.CmsConfig",
"seedorf.core.apps.CoreConfig",
"seedorf.users.apps.UsersConfig",
"seedorf.games.apps.GamesConfig",
"seedorf.locations.apps.LocationsConfig",
"seedorf.sports.apps.SportsConfig",
"seedorf.spots.apps.SpotsConfig",
"seedorf.reactions.apps.ReactionsConfig",
"seedorf.chatkit.apps.ChatkitConfig",
]
# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
# https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1
# CSRF CONFIGURATION
# ------------------------------------------------------------------------------
CSRF_COOKIE_SECURE = env.bool("DJANGO_CSRF_COOKIE_SECURE", default=True)
CSRF_TRUSTED_ORIGINS = env.list("DJANGO_CSRF_TRUSTED_ORIGINS", default=[".sportyspots.com"])
CSRF_COOKIE_DOMAIN = env.str("DJANGO_CSRF_COOKIE_DOMAIN", default="sportyspots.com")
CSRF_USE_SESSIONS = env.bool("DJANGO_CSRF_USE_SESSIONS", default=False)
# HEADERS CONFIGURATION
# ------------------------------------------------------------------------------
USE_X_FORWARDED_HOST = env.bool("DJANGO_USE_X_FORWARDED_HOST", default=False)
# MIDDLEWARE CONFIGURATION
# ------------------------------------------------------------------------------
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"wagtail.core.middleware.SiteMiddleware",
"wagtail.contrib.redirects.middleware.RedirectMiddleware",
]
CORS_ORIGIN_WHITELIST = ["https://sportyspots.com", "https://www.sportyspots.com", "https://api.sportyspots.com"]
CORS_ORIGIN_REGEX_WHITELIST = [
r"^https://neeskens-.*\.now\.sh$",
]
# MIGRATIONS CONFIGURATION
# ------------------------------------------------------------------------------
MIGRATION_MODULES = {"sites": "seedorf.contrib.sites.migrations"}
# DEBUG
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = env.bool("DJANGO_DEBUG", False)
# FIXTURE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS
FIXTURE_DIRS = (str(APPS_DIR.path("fixtures")),)
# EMAIL CONFIGURATION
# ------------------------------------------------------------------------------
EMAIL_BACKEND = env("DJANGO_EMAIL_BACKEND", default="django.core.mail.backends.smtp.EmailBackend")
# MANAGER CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins
ADMINS = [("Admin - SportySpots", "<EMAIL>")]
# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers
MANAGERS = ADMINS
# DATABASE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
# Uses django-environ to accept uri format
# See: https://django-environ.readthedocs.io/en/latest/#supported-types
DATABASES = {"default": env.db("DATABASE_URL", default="postgis:///seedorf")}
DATABASES["default"]["ENGINE"] = "django.contrib.gis.db.backends.postgis"
DATABASES["default"]["ATOMIC_REQUESTS"] = True
# GENERAL CONFIGURATION
# ------------------------------------------------------------------------------
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = "UTC"
# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
LANGUAGE_CODE = "en-us"
LANGUAGES = (("en", _("English")), ("nl", _("Dutch")), ("es", _("Spanish")))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
USE_I18N = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
USE_L10N = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
USE_TZ = True
# TEMPLATE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#templates
TEMPLATES = [
{
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND
"BACKEND": "django.template.backends.django.DjangoTemplates",
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
"DIRS": [str(APPS_DIR.path("templates"))],
"OPTIONS": {
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
"debug": DEBUG,
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders
# https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types
"loaders": ["django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader"],
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
# Your stuff: custom template context processors go here
],
"libraries": {"seedorf": "seedorf.utils.templatetags.tags"},
},
}
]
# See: http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs
CRISPY_TEMPLATE_PACK = "bootstrap4"
# STATIC FILE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = str(ROOT_DIR("staticfiles"))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = "/static/"
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = [str(APPS_DIR.path("static"))]
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
# MEDIA CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = str(APPS_DIR("media"))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = "/media/"
# URL Configuration
# ------------------------------------------------------------------------------
ROOT_URLCONF = "config.urls"
# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = "config.wsgi.application"
# SLUGLIFIER
# ------------------------------------------------------------------------------
AUTOSLUG_SLUGIFY_FUNCTION = "slugify.slugify"
# CELERY
# ------------------------------------------------------------------------------
INSTALLED_APPS += ["seedorf.taskapp.celery.CeleryConfig"]
CELERY_BROKER_URL = env("CELERY_BROKER_URL", default="django://")
if CELERY_BROKER_URL == "django://":
CELERY_RESULT_BACKEND = "redis://"
else:
CELERY_RESULT_BACKEND = CELERY_BROKER_URL
# django-compressor
# ------------------------------------------------------------------------------
INSTALLED_APPS += ["compressor"]
STATICFILES_FINDERS += ["compressor.finders.CompressorFinder"]
# i18n nece settings
# REF: https://github.com/tatterdemalion/django-nece
# ------------------------------------------------------------------------------
TRANSLATIONS_DEFAULT = "en_us"
TRANSLATIONS_MAP = {"en": "en_us", "nl": "nl_nl"}
# Haystack - Elasticsearch / Solr Integration
# ------------------------------------------------------------------------------
HAYSTACK_CONNECTIONS = {"default": {"ENGINE": "haystack.backends.simple_backend.SimpleEngine"}}
# AUTHENTICATION/ AUTHORIZATION Settings -------------------------------------------------------------------------------
# Location of root django.contrib.admin URL, use {% url 'admin:index' %}
ADMIN_URL = "admin/"
LOGIN_URL = "rest-auth:rest_login"
# Custom User Model
AUTH_USER_MODEL = "users.User"
# PASSWORD STORAGE SETTINGS
# ------------------------------------------------------------------------------
# See https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django
PASSWORD_HASHERS = [
"django.contrib.auth.hashers.Argon2PasswordHasher",
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
"django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
"django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
"django.contrib.auth.hashers.BCryptPasswordHasher",
]
# PASSWORD VALIDATION
# https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
# ------------------------------------------------------------------------------
AUTH_PASSWORD_VALIDATORS = [
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
# AUTHENTICATION CONFIGURATION
# ------------------------------------------------------------------------------
AUTHENTICATION_BACKENDS = [
# django
"django.contrib.auth.backends.ModelBackend",
# allauth
"allauth.account.auth_backends.AuthenticationBackend",
]
# Django Rest Framework
# REF: http://www.django-rest-framework.org/api-guide/settings/
# ------------------------------------------------------------------------------
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_jwt.authentication.JSONWebTokenAuthentication",
"rest_framework.authentication.BasicAuthentication",
"rest_framework.authentication.SessionAuthentication",
),
"DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticatedOrReadOnly"],
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
"PAGE_SIZE": 20,
}
# JWT Authentication
# REF: http://getblimp.github.io/django-rest-framework-jwt/
# ------------------------------------------------------------------------------
JWT_AUTH = {
"JWT_ALGORITHM": "HS256",
"JWT_ALLOW_REFRESH": False,
"JWT_AUDIENCE": None,
"JWT_AUTH_COOKIE": None,
"JWT_AUTH_HEADER_PREFIX": "JWT",
"JWT_DECODE_HANDLER": "rest_framework_jwt.utils.jwt_decode_handler",
"JWT_ENCODE_HANDLER": "rest_framework_jwt.utils.jwt_encode_handler",
"JWT_EXPIRATION_DELTA": datetime.timedelta(days=365),
"JWT_GET_USER_SECRET_KEY": None,
"JWT_ISSUER": None,
"JWT_LEEWAY": 0,
"JWT_PAYLOAD_GET_USER_ID_HANDLER": "rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler",
"JWT_PAYLOAD_HANDLER": "seedorf.utils.auth.jwt_payload_handler",
"JWT_PRIVATE_KEY": None,
"JWT_PUBLIC_KEY": None,
"JWT_REFRESH_EXPIRATION_DELTA": datetime.timedelta(days=365),
"JWT_RESPONSE_PAYLOAD_HANDLER": "rest_framework_jwt.utils.jwt_response_payload_handler",
"JWT_SECRET_KEY": env("DJANGO_SECRET_KEY"),
"JWT_VERIFY": True,
"JWT_VERIFY_EXPIRATION": True,
}
# Django Rest Auth
# REF: https://django-rest-auth.readthedocs.io/en/latest/configuration.html
# ------------------------------------------------------------------------------
REST_AUTH_SERIALIZERS = {
"LOGIN_SERIALIZER": "rest_auth.serializers.LoginSerializer",
"TOKEN_SERIALIZER": "rest_auth.serializers.TokenSerializer",
"JWT_SERIALIZER": "rest_auth.serializers.JWTSerializer",
"USER_DETAILS_SERIALIZER": "seedorf.users.serializers.UserSerializer",
"PASSWORD_RESET_SERIALIZER": "rest_auth.serializers.PasswordResetSerializer",
"PASSWORD_RESET_CONFIRM_SERIALIZER": "rest_auth.serializers.PasswordResetConfirmSerializer",
"PASSWORD_CHANGE_SERIALIZER": "rest_auth.serializers.PasswordChangeSerializer",
}
REST_AUTH_REGISTER_SERIALIZERS = {"REGISTER_SERIALIZER": "seedorf.users.serializers.RegisterSerializer"}
REST_AUTH_TOKEN_MODEL = "rest_framework.authtoken.models"
REST_AUTH_TOKEN_CREATOR = "rest_auth.utils.default_create_token"
REST_SESSION_LOGIN = True
REST_USE_JWT = True
OLD_PASSWORD_FIELD_ENABLED = False
LOGOUT_ON_PASSWORD_CHANGE = True
# Allauth settings
# REF: https://django-allauth.readthedocs.io/en/latest/configuration.html
# ------------------------------------------------------------------------------
ACCOUNT_ADAPTER = "seedorf.users.adapters.AccountAdapter"
ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = False
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = reverse_lazy("account_confirm_status")
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = reverse_lazy("account_confirm_status")
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3
ACCOUNT_EMAIL_CONFIRMATION_HMAC = True
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "optional"
ACCOUNT_EMAIL_SUBJECT_PREFIX = "[SportySpots]"
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https"
ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN = 180
ACCOUNT_EMAIL_MAX_LENGTH = 254
ACCOUNT_FORMS = {
"add_email": "allauth.account.forms.AddEmailForm",
"change_password": "allauth.account.forms.ChangePasswordForm",
"disconnect": "allauth.socialaccount.forms.DisconnectForm",
"login": "allauth.account.forms.LoginForm",
"reset_password": "<PASSWORD>",
"reset_password_from_key": "allauth.account.forms.ResetPasswordKeyForm",
"set_password": "<PASSWORD>",
"signup": "allauth.account.forms.SignupForm",
}
ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5
ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 300
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False
ACCOUNT_LOGOUT_ON_GET = False
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = False
ACCOUNT_LOGIN_ON_PASSWORD_RESET = False
ACCOUNT_LOGOUT_REDIRECT_URL = "/"
ACCOUNT_PASSWORD_INPUT_RENDER_VALUE = False
ACCOUNT_PRESERVE_USERNAME_CASING = False
ACCOUNT_SESSION_REMEMBER = None
ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE = False
ACCOUNT_SIGNUP_FORM_CLASS = None
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = True
ACCOUNT_TEMPLATE_EXTENSION = "html"
ACCOUNT_USERNAME_BLACKLIST = []
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USER_MODEL_EMAIL_FIELD = "email"
ACCOUNT_USER_MODEL_USERNAME_FIELD = "username"
ACCOUNT_USERNAME_MIN_LENGTH = 1
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_USERNAME_VALIDATORS = None
ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True)
SOCIALACCOUNT_ADAPTER = "seedorf.users.adapters.SocialAccountAdapter"
SOCIALACCOUNT_AUTO_SIGNUP = True
SOCIALACCOUNT_EMAIL_REQUIRED = ACCOUNT_EMAIL_REQUIRED
SOCIALACCOUNT_EMAIL_VERIFICATION = ACCOUNT_EMAIL_VERIFICATION
SOCIALACCOUNT_FORMS = {}
SOCIALACCOUNT_QUERY_EMAIL = ACCOUNT_EMAIL_REQUIRED
SOCIALACCOUNT_STORE_TOKENS = True
SOCIALACCOUNT_PROVIDERS = {
"google": {"SCOPE": ["profile", "email"], "AUTH_PARAMS": {"access_type": "online"}},
"facebook": {"METHOD": "oauth2", "SCOPE": ["email"], "FIELDS": ["id", "email", "name", "first_name", "last_name"]},
}
# graphene djang extra settings
# REF: https://github.com/eamigo86/graphene-django-extras
# ------------------------------------------------------------------------------
GRAPHENE_DJANGO_EXTRAS = {
"DEFAULT_PAGINATION_CLASS": "graphene_django_extras.paginations.LimitOffsetGraphqlPagination",
"DEFAULT_PAGE_SIZE": 20,
"MAX_PAGE_SIZE": 50,
"CACHE_ACTIVE": False,
"CACHE_TIMEOUT": 300, # seconds
}
# Firebase
# ------------------------------------------------------------------------------
FIREBASE_WEB_API_KEY = env.str("FIREBASE_WEB_API_KEY")
# Wagtail
# REF: http://docs.wagtail.io/en/v2.4/getting_started/integrating_into_django.html
# ------------------------------------------------------------------------------
WAGTAIL_SITE_NAME = "SportySpots"
# Push Notifications
# REF: https://github.com/jazzband/django-push-notifications
# REF: https://stackoverflow.com/a/19421406 (Generate APS Push Certificate)
# REF: Test APS Push Certificate
# curl -d '{"aps":{"alert":"This is a test notification"}}' --cert SportySpotsApsPushCertificate.pem -H "apns-topic: com.sportyspots.ios" --http2 https://api.development.push.apple.com/3/device/YourDeviceToken
# ------------------------------------------------------------------------------
PUSH_NOTIFICATIONS_SETTINGS = {
"FCM_API_KEY": env.str("FCM_API_KEY", default=""),
"APNS_USE_SANDBOX": env.bool("APNS_USE_SANDBOX", True),
"APNS_CERTIFICATE": ROOT_DIR.path("ansible/settings/SportySpotsApsPushCertificate.pem"),
"APNS_TOPIC": "com.sportyspots.ios",
}
# Pusher ChatKit
# ------------------------------------------------------------------------------
CHATKIT_SETTINGS = {
"INSTANCE_ID": env.str("CHATKIT_INSTANCE_ID", default=""), # uuid4 string
"KEY_ID": env.str("CHATKIT_KEY_ID", default=""), # uuid4 string
"KEY_SECRET": env.str("CHATKIT_KEY_SECRET", default=""), # ~45 chars string
}
# Used to generate absolute URLS (for firebase links)
WEB_ROOT_URL = env.str("WEB_ROOT_URL", default="https://www.sportyspots.com")
<file_sep># -*- coding: utf-8 -*-
import scrapy
import json
from ..items import Spot
legend = dict()
legend["SPORT_OPENBAAR_SKATE"] = [
"_php/haal_objecten.php?TABEL=SPORT_OPENBAAR&SELECT=SKATE&SELECTIEKOLOM=SELECTIE",
"SPORT_OPENBAAR",
"SKATE",
"SELECTIE",
"Skate",
]
legend["SPORT_OPENBAAR_TENNIS"] = [
"_php/haal_objecten.php?TABEL=SPORT_OPENBAAR&SELECT=TENNIS&SELECTIEKOLOM=SELECTIE",
"SPORT_OPENBAAR",
"TENNIS",
"SELECTIE",
"Tennis",
]
legend["SPORT_OPENBAAR_BASKETBALL"] = [
"_php/haal_objecten.php?TABEL=SPORT_OPENBAAR&SELECT=BASKETBAL&SELECTIEKOLOM=SELECTIE",
"SPORT_OPENBAAR",
"BASKETBAL",
"SELECTIE",
"Basketbal",
]
legend["SPORT_OPENBAAR_VOETBALL"] = [
"_php/haal_objecten.php?TABEL=SPORT_OPENBAAR&SELECT=VOETBAL&SELECTIEKOLOM=SELECTIE",
"SPORT_OPENBAAR",
"VOETBAL",
"SELECTIE",
"Voetbal",
]
legend["SPORT_OPENBAAR_JEUDEBOL"] = [
"_php/haal_objecten.php?TABEL=SPORT_OPENBAAR&SELECT=JEUDEBOULES&SELECTIEKOLOM=SELECTIE",
"SPORT_OPENBAAR",
"JEUDEBOULES",
"SELECTIE",
"Jeu de boules",
]
legend["SPORT_OPENBAAR_FITNESS"] = [
"_php/haal_objecten.php?TABEL=SPORT_OPENBAAR&SELECT=FITNESS&SELECTIEKOLOM=SELECTIE",
"SPORT_OPENBAAR",
"FITNESS",
"SELECTIE",
"Fitness / Bootcamp",
]
legend["SPORT_OPENBAAR_BEACHVOLLEY"] = [
"_php/haal_objecten.php?TABEL=SPORT_OPENBAAR&SELECT=BEACHVOLLEY&SELECTIEKOLOM=SELECTIE",
"SPORT_OPENBAAR",
"BEACHVOLLEY",
"SELECTIE",
"Beachvolley",
]
legend["SPORT_OPENBAAR_OVERIG"] = [
"_php/haal_objecten.php?TABEL=SPORT_OPENBAAR&SELECT=OVERIG&SELECTIEKOLOM=SELECTIE",
"SPORT_OPENBAAR",
"OVERIG",
"SELECTIE",
"Overig",
]
# legend['FUNCTIEKAART_S01'] = ['_php/haal_objecten.php?TABEL=FUNCTIEKAART&SELECT=S01&SELECTIEKOLOM=FUNCTIE2_ID','FUNCTIEKAART','S01','FUNCTIE2_ID','Stadion - IJsbaan - Tribunegebouw bij sportbaan']
# legend['FUNCTIEKAART_S02'] = ['_php/haal_objecten.php?TABEL=FUNCTIEKAART&SELECT=S02&SELECTIEKOLOM=FUNCTIE2_ID','FUNCTIEKAART','S02','FUNCTIE2_ID','Zwembad']
# legend['FUNCTIEKAART_S03'] = ['_php/haal_objecten.php?TABEL=FUNCTIEKAART&SELECT=S03&SELECTIEKOLOM=FUNCTIE2_ID','FUNCTIEKAART','S03','FUNCTIE2_ID','Sporthal - Tennishal - Sportzaal - Klimhal']
# legend['FUNCTIEKAART_S04'] = ['_php/haal_objecten.php?TABEL=FUNCTIEKAART&SELECT=S04&SELECTIEKOLOM=FUNCTIE2_ID','FUNCTIEKAART','S04','FUNCTIE2_ID','Sportschool - Fitness - Yogaruimte']
# legend['FUNCTIEKAART_S05'] = ['_php/haal_objecten.php?TABEL=FUNCTIEKAART&SELECT=S05&SELECTIEKOLOM=FUNCTIE2_ID','FUNCTIEKAART','S05','FUNCTIE2_ID','Kleinschalige bebouwing op sportterrein, golfterrein, manege']
# legend['FUNCTIEKAART_S06'] = ['_php/haal_objecten.php?TABEL=FUNCTIEKAART&SELECT=S06&SELECTIEKOLOM=FUNCTIE2_ID','FUNCTIEKAART','S06','FUNCTIE2_ID','Watersportgebouw']
# legend[''] = ['_php/haal_objecten.php?TABEL=HOOFDGROENSTRUCTUUR&SELECT=SPORTPARK&SELECTIEKOLOM=SELECTIE','HOOFDGROENSTRUCTUUR','SPORTPARK','SELECTIE','Sportpark']
# legend[''] = ['_php/haal_objecten.php?TABEL=STADSDELEN_LIJN','STADSDELEN_LIJN','','','STADSDELEN_LIJN']
class AmsterdamOpenApiSpider(scrapy.Spider):
name = "amsterdam_open_api"
allowed_domains = ["maps.amsterdam.nl"]
DOMAIN = "https://maps.amsterdam.nl"
def parse(self, response):
pass
def create_urls(self):
urls = []
for key, value in legend.items():
urls.append(f"{self.DOMAIN}/{value[0]}")
return urls
def start_requests(self):
urls = self.create_urls()
for url in urls:
yield scrapy.Request(url=url, callback=self.parse_spots)
def parse_spots(self, response):
api_response = json.loads(response.body_as_unicode())
for spot in api_response:
item = Spot()
item["id"] = spot["VOLGNR"]
item["label"] = spot["LABEL"]
item["lat"] = spot["LATMAX"]
item["lng"] = spot["LNGMAX"]
item["sports"] = []
item["sports"].append(spot["SELECTIE"])
request = scrapy.Request(
f"https://maps.amsterdam.nl/_php/haal_info.php?VOLGNR={spot['VOLGNR']}&THEMA=sport&TABEL=SPORT_OPENBAAR",
callback=self.parse_spot_details,
)
request.meta["item"] = item
yield request
@staticmethod
def parse_spot_details(response):
item = response.meta["item"]
rows = response.css("tr")
item["attributes"] = list()
for row in rows:
field = row.css("td.veld::text").extract()[0]
if field == "\xa0":
value = row.css("img::attr(src)").extract()[0]
item["images"] = []
item["images"].append(value)
else:
value = row.css(".waarde::text").extract()[0]
if field == "Omschrijving":
item["description"] = value
else:
item["attributes"].append({"attribute_name": field, "value": value})
yield item
<file_sep>import random
from datetime import timedelta
import factory
from django.utils import timezone
from seedorf.spots.tests.factories import SpotFactory
from seedorf.users.tests.factories import UserFactory
from ..models import Game, RsvpStatus
class GameFactory(factory.django.DjangoModelFactory):
organizer = factory.SubFactory(UserFactory)
spot = factory.SubFactory(SpotFactory)
sport = factory.LazyAttribute(lambda o: o.spot.sports.all()[0])
name = factory.Faker("word")
invite_mode = factory.Iterator(Game.INVITE_MODES, getter=lambda d: d[0])
status = factory.Iterator(Game.STATUSES, getter=lambda d: d[0])
capacity = random.randint(2, 10)
show_remaining = factory.Faker("pybool")
is_listed = factory.Faker("pybool")
is_shareable = factory.Faker("pybool")
is_featured = factory.Faker("pybool")
# params to generate items in the past or in the future
now = timezone.now()
# by default the game is created in the future
rsvp_open_time = factory.LazyAttribute(lambda o: o.now + timedelta(days=2, hours=2))
rsvp_close_time = factory.LazyAttribute(lambda o: o.now + timedelta(days=2, hours=4))
start_time = factory.LazyAttribute(lambda o: o.now + timedelta(days=4, hours=2))
end_time = factory.LazyAttribute(lambda o: o.now + timedelta(days=4, hours=4))
class Meta:
model = Game
exclude = ("now",)
class Params:
past = factory.Trait(
rsvp_open_time=factory.LazyAttribute(lambda o: o.now - timedelta(days=4, hours=4)),
rsvp_close_time=factory.LazyAttribute(lambda o: o.now - timedelta(days=4, hours=2)),
start_time=factory.LazyAttribute(lambda o: o.now - timedelta(days=2, hours=4)),
end_time=factory.LazyAttribute(lambda o: o.now - timedelta(days=2, hours=2)),
)
class GameListedFactory(GameFactory):
is_listed = True
class GameShareableFactory(GameFactory):
is_shareable = True
class GameFeaturedFactory(GameFactory):
is_featured = True
class RsvpStatusFactory(factory.django.DjangoModelFactory):
user = factory.SubFactory(UserFactory)
game = factory.SubFactory(GameFactory)
class Meta:
model = RsvpStatus
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-05-13 07:52
from __future__ import unicode_literals
from django.db import migrations, models
import django_extensions.db.fields
import seedorf.spots.models
class Migration(migrations.Migration):
dependencies = [("spots", "0001_initial")]
operations = [
migrations.AlterField(
model_name="spot",
name="homepage_url",
field=models.URLField(
blank=True,
help_text="Where can we find out more about this spot ?",
max_length=512,
verbose_name="Homepage URL",
),
),
migrations.AlterField(
model_name="spot",
name="logo",
field=models.ImageField(
blank=True,
max_length=512,
upload_to=seedorf.spots.models.get_logo_upload_directory,
verbose_name="Logo",
),
),
migrations.AlterField(
model_name="spot", name="name", field=models.CharField(max_length=512, verbose_name="Name")
),
migrations.AlterField(
model_name="spot",
name="owner",
field=models.CharField(blank=True, default="", max_length=512, verbose_name="Owner"),
),
migrations.AlterField(
model_name="spot",
name="slug",
field=django_extensions.db.fields.AutoSlugField(
blank=True, editable=False, max_length=512, populate_from="name", unique=True, verbose_name="Slug"
),
),
]
<file_sep>require('../../node_modules/jquery-validation/dist/jquery.validate.js');
require('../../node_modules/jquery-validation/dist/additional-methods.js');
<file_sep>import * as toastr from '../../node_modules/toastr/toastr.js';
export { toastr };
<file_sep>import graphene
from graphene_django.debug import DjangoDebug
from seedorf.games.schema import Query as GamesQuery
from seedorf.locations.schema import Query as LocationsQuery
from seedorf.sports.schema import Query as SportsQuery
from seedorf.spots.schema import Query as SpotsQuery
from seedorf.users.schema import Query as UsersQuery
class Query(LocationsQuery, SportsQuery, SpotsQuery, GamesQuery, UsersQuery, graphene.ObjectType):
debug = graphene.Field(DjangoDebug, name="debug")
schema = graphene.Schema(query=Query, auto_camelcase=False)
<file_sep>require('../../node_modules/bootstrap-select/js/bootstrap-select.js');
<file_sep>from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from .models import User, UserProfile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
@receiver(post_save, sender=User)
def create_or_update_chatkit_user(sender, instance, created, **kwargs):
try:
from seedorf.chatkit.client import create_client
client = create_client()
client.token = client.create_admin_token()
user_uuid = str(instance.uuid)
user_name = instance.name
user_avatar = instance.profile.avatar.url if instance.profile.avatar else None
if created:
client.create_user(user_uuid, user_name, user_avatar)
else:
client.update_user(user_uuid, user_name, user_avatar)
except Exception:
pass
@receiver(post_delete, sender=User)
def delete_chatkit_user(sender, instance, **kwargs):
try:
from seedorf.chatkit.client import create_client
client = create_client()
client.token = client.create_admin_token()
client.delete_user(str(instance.uuid))
except Exception:
pass
<file_sep>require('../../../../node_modules/bootstrap-table/src/extensions/mobile/bootstrap-table-mobile.js');
<file_sep>FROM mdillon/postgis:9.6
COPY ./compose/local/postgres/backup.sh /usr/local/bin/backup
RUN chmod +x /usr/local/bin/backup
COPY ./compose/local/postgres/restore.sh /usr/local/bin/restore
RUN chmod +x /usr/local/bin/restore
COPY ./compose/local/postgres/list-backups.sh /usr/local/bin/list-backups
RUN chmod +x /usr/local/bin/list-backups
<file_sep>require('../../node_modules/bootstrap-tour/build/js/bootstrap-tour.js');
<file_sep>from django.apps import AppConfig
class ChatkitConfig(AppConfig):
name = "seedorf.chatkit"
verbose_name = "Chatkit"
<file_sep>const path = require('path')
const glob = require('glob')
// -------------------------------------------------------------------------------
// Config
const conf = (() => {
const _conf = require('./build-config')
return require('deepmerge').all([{}, _conf.base || {}, _conf[process.env.NODE_ENV] || {}])
})()
conf.buildPath = path.resolve(__dirname, conf.buildPath)
// -------------------------------------------------------------------------------
// Modules
const webpack = require('webpack')
const StringReplacePlugin = require('string-replace-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
// -------------------------------------------------------------------------------
// Custom template
const ConcatSource = require('webpack-sources').ConcatSource
class CustomTemplatePlugin {
apply(compilation) {
const { mainTemplate, chunkTemplate } = compilation;
const onRenderWithEntry = (source, chunk, hash) => {
return new ConcatSource(`
(function(r,f) {
var a=f();
if(typeof a!=='object')return;
var e=[typeof module==='object'&&typeof module.exports==='object'?module.exports:null,typeof window!=='undefined'?window:null,r&&r!==window?r:null];
for(var i in a){e[0]&&(e[0][i]=a[i]);e[1]&&i!=='__esModule'&&(e[1][i] = a[i]);e[2]&&(e[2][i]=a[i]);}
})(this,function(){
return `, source, `;
});`)
};
for (const template of [mainTemplate, chunkTemplate]) {
template.hooks.renderWithEntry.tap(
'CustomTemplatePlugin',
onRenderWithEntry
);
}
mainTemplate.hooks.globalHashPaths.tap("CustomTemplatePlugin", paths => {
return paths;
});
mainTemplate.hooks.hash.tap("CustomTemplatePlugin", hash => {
hash.update('CustomTemplatePlugin');
hash.update('2');
});
}
}
class CustomLibraryTemplatePlugin {
apply(compiler) {
compiler.hooks.thisCompilation.tap('CustomLibraryTemplatePlugin', compilation => {
new CustomTemplatePlugin().apply(compilation);
});
}
}
// -------------------------------------------------------------------------------
// Build config
const webpackConfig = {
target: 'web',
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
// Collect entries
entry: (glob.sync(`!(${conf.exclude.join('|')})/**/!(_)*.@(js|es6)`) || [])
.reduce((entries, file) => {
entries[file.replace(/\.(?:js|es6)$/, '')] = `./${file.replace(/\\/g, '/')}`
return entries
}, {}),
output: {
path: conf.buildPath,
filename: '[name].js'
},
module: {
rules: [{
test: /(?:\.es6|\.es6\.js)$|(?:node_modules(?:\\|\/)bootstrap(?:\\|\/)js(?:\\|\/)src(?:\\|\/)\w+\.js$)|(?:bootstrap-sweetalert(?:\/|\\)dev.+?\.js)$|(?:bootstrap-slider\.js)$|(?:popper\.js)$/,
use: [
{
loader: 'babel-loader',
options: {
presets: [['@babel/preset-env', {
targets: 'last 2 versions, ie >= 10'
}]],
plugins: ['@babel/plugin-transform-destructuring', '@babel/plugin-proposal-object-rest-spread', '@babel/plugin-transform-template-literals'],
babelrc: false
}
}
]
}, {
test: /\.css$/,
use: [{
loader: 'style-loader',
options: {
hmr: false
}
}, {
loader: 'css-loader',
options: {
minimize: true
}
}]
}, {
test: /\.scss$/,
use: [{
loader: 'style-loader',
options: {
hmr: false
}
}, {
loader: 'css-loader',
options: {
minimize: true
}
}, {
loader: 'sass-loader'
}]
}, {
test: /\.html$/,
use: [{
loader: 'html-loader',
options: {
minimize: true
}
}]
}, { // Remove imports
test: /node_modules(?:\\|\/)bootstrap(?:\\|\/)js(?:\\|\/)src(?:\\|\/)\w+\.js$/,
use: {
loader: StringReplacePlugin.replace({
replacements: [{
pattern: /import.+?from\s+['"](.+?)['"];?\n/ig,
replacement: (m, $1) => $1.toLowerCase() !== './tooltip' ? '' : 'import Tooltip from \'./tooltip\'\n'
}]
})
}
}, { // Fix flot.resize plugin
test: /node_modules.+jquery\.flot\.resize\.js$/,
use: {
loader: StringReplacePlugin.replace({
replacements: [{
pattern: /\(\s*jQuery\s*,\s*this\s*\)/ig,
replacement: () => '(jQuery,window)'
}]
})
}
}, { // Fix markdown plugin
test: /node_modules(?:\\|\/)markdown(?:\\|\/).+\.js$/,
use: {
loader: StringReplacePlugin.replace({
replacements: [{
pattern: /if \(typeof define !== 'function'\) \{ var define = require\('amdefine'\)\(module\) \}/ig,
replacement: () => ''
}]
})
}
}]
},
plugins: [
new webpack.DefinePlugin({
'process.env': process.env.NODE_ENV
}),
new webpack.IgnorePlugin(/codemirror/),
new CustomLibraryTemplatePlugin()
],
externals: {
'jquery': 'window.jQuery',
'moment': 'window.moment',
'datatables.net': '$.fn.dataTable',
'spin.js': 'window.Spinner',
'jsdom': 'window.jsdom',
'd3': 'window.d3',
'eve': 'window.eve',
'velocity': 'window.Velocity',
'hammer': 'window.Hammer',
'raphael': 'window.Raphael',
'jquery-mapael': 'window.Mapael',
'pace': '"pace-progress"',
// blueimp-file-upload plugin
'canvas-to-blob': 'window.blueimpDataURLtoBlob',
'blueimp-tmpl': 'window.blueimpTmpl',
'load-image': 'window.blueimpLoadImage',
'load-image-meta': 'null',
'load-image-scale': 'null',
'load-image-exif': 'null',
'jquery-ui/ui/widget': 'null',
'./jquery.fileupload': 'null',
'./jquery.fileupload-process': 'null',
'./jquery.fileupload-image': 'null',
'./jquery.fileupload-video': 'null',
'./jquery.fileupload-validate': 'null',
// blueimp-gallery plugin
'./blueimp-helper': 'window.jQuery',
'./blueimp-gallery': 'window.blueimpGallery',
'./blueimp-gallery-video': 'window.blueimpGallery'
}
}
// -------------------------------------------------------------------------------
// Sourcemaps
if (conf.sourcemaps) {
webpackConfig.devtool = conf.devtool
}
// -------------------------------------------------------------------------------
// Minify
// Minifies sources by default in production mode
if (process.env.NODE_ENV !== 'production' && conf.minify) {
webpackConfig.plugins.push(
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: conf.sourcemaps,
parallel: true
})
)
}
module.exports = webpackConfig
<file_sep>from django.contrib import admin
from .models import Sport
class SportAdmin(admin.ModelAdmin):
readonly_fields = ("uuid", "created_at", "modified_at", "deleted_at")
fields = ("uuid", "category", "name", "description", "translations", "created_at", "modified_at", "deleted_at")
list_display = ("uuid", "category", "name")
list_filter = ("category",)
admin.site.register(Sport, SportAdmin)
<file_sep>require('../../node_modules/block-ui/jquery.blockUI.js');
<file_sep>require('../../../node_modules/jquery-mapael/js/maps/world_countries.js');
<file_sep>from django.apps import AppConfig
class GamesConfig(AppConfig):
name = "seedorf.games"
verbose_name = "Games"
def ready(self):
from . import signals
<file_sep>require('../../../../node_modules/bootstrap-table/src/extensions/export/bootstrap-table-export.js');
<file_sep>import * as Spinner from '../../node_modules/spin.js/spin.js';
export { Spinner };
<file_sep>// Make vegas responsive
//
const fnVegas = $.fn.vegas;
$.fn.vegas = function(...args) {
const result = fnVegas.apply(this, args);
if (args[0] === undefined || typeof args[0] === 'object') {
this.each(function() {
if (this.tagName.toUpperCase() === 'BODY' || !this._vegas) { return; }
$(this).css('height', '');
});
}
return result;
};
<file_sep>import * as d3 from '../../node_modules/d3/dist/d3.js';
export { d3 };
<file_sep>import eve from '../../node_modules/eve-raphael/eve.js';
export { eve }
<file_sep># Generated by Django 2.1.2 on 2019-05-01 11:34
from django.db import migrations, models
def create_chatkit_rooms(apps, schema_editor):
from seedorf.chatkit.client import create_client
client = create_client()
client.token = client.create_admin_readonly_user_token()
Game = apps.get_model("games", "Game")
for game in Game.objects.all():
room = client.create_room(name=f"game/{str(game.uuid)}")
game.chatkit_room_id = int(room["id"])
game.save()
def create_chatkit_users(apps, schema_editor):
from seedorf.chatkit.client import create_client
client = create_client()
client.token = client.create_admin_token()
User = apps.get_model("users", "User")
for user in User.objects.all():
user_uuid = str(user.uuid)
user_name = user.name
user_avatar = user.profile.avatar.url if user.profile.avatar else None
client.create_user(user_uuid, user_name, user_avatar)
class Migration(migrations.Migration):
dependencies = [("games", "0014_game_chatkit_room_id")]
operations = [migrations.RunPython(create_chatkit_rooms), migrations.RunPython(create_chatkit_users)]
<file_sep>from django.apps import AppConfig
class SpotsConfig(AppConfig):
name = "seedorf.spots"
verbose_name = "Spots"
<file_sep># -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class Spot(scrapy.Item):
id = scrapy.Field(serializer=int)
label = scrapy.Field(serializer=str)
description = scrapy.Field(serializer=str)
lat = scrapy.Field()
lng = scrapy.Field()
sports = scrapy.Field(default=[])
images = scrapy.Field(default=[])
attributes = scrapy.Field()
SPORT_MAPPING_SPORTYSPOTS = {
"fitness": "7d5cac64-e9aa-4889-9f3c-803bcc93462c",
"beachvolley": "672e593a-ac57-432a-b718-63d26074db1c",
"basketball": "0619c38d-4b21-4663-ba23-b49f682f50a2",
"soccer": "2e9c614d-632f-4386-a9f5-0d514cb56c15",
"jeudeboules": "327bee89-789c-4e18-9a50-1f01c2d36a2f",
"skate": "3662531a-957c-4eef-974e-7d4a09d428ea",
"tennis": "8ef143ce-22d5-4155-9e3a-8d2b5d5fdd5c",
"others": "512a417f-f8fd-4637-b1ed-860747c60799",
}
SPORT_MAPPING_AMSTERDAM_OPEN_API = {
"FITNESS": "fitness",
"BEACHVOLLEY": "beachvolley",
"BASKETBAL": "basketball",
"VOETBAL": "soccer",
"JEUDEBOULES": "jeudeboules",
"SKATE": "skate",
"TENNIS": "tennis",
"OVERIG": "others",
}
SPORT_MAPPING_OPEN_STREET_MAPS = {
"9pin": None,
"10pin": None,
"american_football": None,
"aikido": None,
"archery": None,
"athletics": None,
"australian_football": None,
"badminton": None,
"bandy": None,
"baseball": None,
"basketball": "basketball",
"beachvolleyball": "beachvolleyball",
"billiards": None,
"bmx": None,
"bobsleigh": None,
"boules": None,
"bowls": None,
"boxing": None,
"bullfighting": None,
"canadian_football": None,
"canoe": None,
"chess": None,
"cliff_diving": None,
"climbing": None,
"climbing_adventure": None,
"cockfighting": None,
"cricket": None,
"crossfit": None,
"croquet": None,
"curling": None,
"cycling": None,
"darts": None,
"dog_racing": None,
"equestrian": None,
"fencing": None,
"field_hockey": None,
"free_flying": None,
"futsal": None,
"gaelic_games": None,
"golf": None,
"gymnastics": None,
"handball": None,
"hapkido": None,
"horseshoes": None,
"horse_racing": None,
"ice_hockey": None,
"ice_skating": None,
"ice_stock": None,
"judo": None,
"karate": None,
"karting": None,
"kitesurfing": None,
"korfball": None,
"krachtbal": None,
"lacrosse": None,
"martial_arts": None,
"model_aerodrome": None,
"motocross": None,
"motor": None,
"multi": None,
"netball": None,
"obstacle_course": None,
"orienteering": None,
"paddle_tennis": None,
"padel": None,
"parachuting": None,
"pelota": None,
"racquet": None,
"rc_car": None,
"roller_skating": None,
"rowing": None,
"rugby_league": None,
"rugby_union": None,
"running": None,
"sailing": None,
"scuba_diving": None,
"shooting": None,
"skateboard": None,
"soccer": None,
"sumo": None,
"surfing": None,
"swimming": None,
"table_tennis": None,
"table_soccer": None,
"taekwondo": None,
"tennis": None,
"toboggan": None,
"volleyball": None,
"water_polo": None,
"water_ski": None,
"weightlifting": None,
"wrestling": None,
"yoga": None,
}
SPORT_MAPPING_PLAY_ADVISOR = {}
<file_sep># Generated by Django 2.1.3 on 2018-11-17 13:12
import django.core.validators
from django.db import migrations, models
import django.utils.timezone
import django_fsm
class Migration(migrations.Migration):
dependencies = [("games", "0005_auto_20180613_1027")]
operations = [
migrations.AlterField(
model_name="game",
name="start_time",
field=models.DateTimeField(
default=django.utils.timezone.now,
help_text="Start time of the game in UTC.",
verbose_name="Start Time (UTC)",
),
preserve_default=False,
)
]
<file_sep>from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from seedorf.utils.models import BasePropertiesModel
class Organization(BasePropertiesModel):
name = models.CharField(blank=False, max_length=255, null=False, verbose_name=_("Name"))
homepage_url = models.URLField(
blank=True,
help_text=_("Where can we find out more about this organization ?"),
max_length=500,
null=False,
verbose_name=_("Homepage URL"),
)
members = models.ManyToManyField(
settings.AUTH_USER_MODEL, through="Membership", through_fields=("organization", settings.AUTH_USER_MODEL)
)
class Meta:
ordering = ("-created_at",)
class Membership(models.Model):
ROLE_OWNER = "owner"
ROLE_MEMBER = "member"
ROLES = ((ROLE_OWNER, _("Owner")), (ROLE_MEMBER, _("Member")))
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
member = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
role = models.CharField(
choices=ROLES,
default=ROLE_MEMBER,
help_text=_("Persons role within the organization."),
max_length=25,
null=True,
)
<file_sep>require('../../node_modules/bootstrap-material-datetimepicker/js/bootstrap-material-datetimepicker.js');
require('./_extension.es6');
<file_sep>import pytz
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.urls import reverse
from django.utils.translation import ugettext as _
from django_fsm import FSMField, transition
from django.utils import timezone
from seedorf.utils.email import send_mail
from seedorf.utils.firebase import get_firebase_link
from seedorf.utils.models import BasePropertiesModel
class Game(BasePropertiesModel):
"""
TODO: Validation
No game can be created on non-verified spots
No game can be created outside of the establishment date and closure date of a temporary spot
No game can be created on permanently closed spots
TODO: Add language to game
"""
# Predefined Values
# When the organizer cancels the event
STATUS_CANCELED = "canceled"
# When the organizer confirms the game took place
STATUS_COMPLETED = "completed"
# When the game is in the planning phase / draft
STATUS_DRAFT = "draft"
# When the system sets the state automatically based on end time
STATUS_ENDED = "ended"
# When the organizer confirms manually the game is live
STATUS_LIVE = "live"
# When the game is planned
STATUS_PLANNED = "planned"
# When a planned game is updated
STATUS_UPDATED = "updated"
# When the system sets the state automatically based on start time
STATUS_STARTED = "started"
STATUSES = (
(STATUS_CANCELED, _("Canceled")),
(STATUS_COMPLETED, _("Completed")),
(STATUS_DRAFT, _("Draft")),
(STATUS_ENDED, _("Ended")),
(STATUS_LIVE, _("Live")),
(STATUS_PLANNED, _("Planned")),
(STATUS_UPDATED, _("Updated")),
(STATUS_STARTED, _("Started")),
)
# The organizer needs to approve the participation
INVITE_MODE_APPROVAL = "approval"
# Participants can join the activity only if they have an invite from the organizer
INVITE_MODE_INVITE_ONLY = "invite_only"
# Everyone can join the activity.
INVITE_MODE_OPEN = "open"
INVITE_MODES = (
(INVITE_MODE_APPROVAL, _("Approval")),
(INVITE_MODE_INVITE_ONLY, _("Invite Only")),
(INVITE_MODE_OPEN, _("Open")),
)
# TODO: Translations of the timezones
TIMEZONES = [(tz, _(tz)) for tz in pytz.common_timezones]
# Foreign Keys
organizer = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="game_organizers",
verbose_name=_("Organizer"),
help_text=_("Organizer of the activity. An activity can have only one organizer."),
)
sport = models.ForeignKey(
"sports.Sport",
on_delete=models.CASCADE,
related_name="sport_games",
verbose_name=_("Sport"),
null=True,
help_text=_("Sport for which the activity is created. An activity can have only one sport associated with it."),
)
spot = models.ForeignKey(
"spots.Spot",
on_delete=models.CASCADE,
related_name="spot_games",
verbose_name=_("Spot"),
null=True,
help_text=_("Spot on which the activity is created. An activity can hanve only one spot associated with it."),
)
# Instance Fields
# TODO: Maybe auto generate the game name based on the organizer, e.g. Soccer with Sam at Oosterpark
name = models.CharField(
blank=True,
default="",
max_length=255,
null=False,
help_text=_(
"Name of the activity. The name can be an empty string. The name can be maximum 255 characters. "
"The name is not localized in the language of the user or location of the activity."
),
)
description = models.TextField(
blank=True, default="", help_text=_("Description of the game."), null=False, verbose_name=_("Description")
)
# TODO: Evaluate if start_time / end_time could be replaced by DateTimeRangeField
# REF: https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/#datetimerangefield
start_time = models.DateTimeField(
blank=False, help_text=_("Start time of the game in UTC."), null=False, verbose_name=_("Start Time (UTC)")
)
end_time = models.DateTimeField(
blank=False, help_text=_("End time of the game in UTC."), null=False, verbose_name=_("End Time (UTC)")
)
rsvp_open_time = models.DateTimeField(
blank=True,
help_text=_("UTC time before which RSVPs will not be accepted."),
null=True,
verbose_name=_("RSVP Open Time (UTC)"),
)
rsvp_close_time = models.DateTimeField(
blank=True,
help_text=_("UTC time after which RSVPs will not be accepted, though organizers may close RSVPs earlier"),
null=True,
verbose_name=_("RSVP Close Time (UTC)"),
)
rsvp_closed = models.BooleanField(
blank=False,
default=False,
help_text=_("Are RSVPs closed for the activity ?"),
null=False,
verbose_name=_("RSVP Closed"),
)
start_timezone = models.CharField(
blank=False,
choices=TIMEZONES,
default=pytz.UTC.zone,
help_text=_("Timezone of the start time of the activity."),
max_length=50,
null=False,
verbose_name=_("Start Time Timezone"),
)
end_timezone = models.CharField(
blank=False,
choices=TIMEZONES,
default=pytz.UTC.zone,
help_text=_("Timezone of the end time of the activity."),
max_length=50,
null=False,
verbose_name=_("End Time Timezone"),
)
invite_mode = models.CharField(
blank=False,
choices=INVITE_MODES,
default=INVITE_MODE_OPEN,
help_text=_("An activity can be open for everyone to join or based on organizers approval or is invite only."),
max_length=25,
null=False,
verbose_name=_("Invite Mode"),
)
status = FSMField(
blank=False,
choices=STATUSES,
default=STATUS_DRAFT,
max_length=25,
null=False,
protected=False,
verbose_name=_("Status"),
)
capacity = models.PositiveSmallIntegerField(
blank=True,
null=True,
validators=[MinValueValidator(limit_value=2), MaxValueValidator(limit_value=50)],
help_text=_(
"Maximum number of participants that can attend the activity. "
"The minimum number of attendees is 2 and the maximum number is 50."
),
verbose_name=_("Capacity"),
)
show_remaining = models.BooleanField(
blank=False,
default=True,
help_text=_("Show No. of Remaining Participants Required."),
null=False,
verbose_name=_("Show Remaining"),
)
is_listed = models.BooleanField(
blank=False,
default=True,
help_text=_("Is this activity is publicly viewable ?"),
null=False,
verbose_name=_("Is Listed ?"),
)
is_shareable = models.BooleanField(
blank=False,
default=True,
help_text=_("Should this activity show the social sharing buttons ?"),
null=False,
verbose_name=_("Is Shareable ?"),
)
is_featured = models.BooleanField(
blank=False,
default=False,
help_text=_("Is this activity featured."),
null=False,
verbose_name=_("Is featured ?"),
)
share_link = models.URLField(
blank=False,
null=False,
help_text=_("Shareable link (app/web) to this game."),
max_length=80,
verbose_name=_("Shareable link"),
)
# TODO: Move chatkit to its own model
chatkit_room_id = models.IntegerField(
blank=True, null=True, help_text=_("ChatKit room ID."), verbose_name=_("ChatKit room ID")
)
class Meta:
verbose_name = _("Activity")
verbose_name_plural = _("Activities")
ordering = ("start_time",)
def __str__(self):
return f"{self.name}"
@property
def started(self):
now = timezone.now()
return now > self.start_time
@property
def ended(self):
now = timezone.now()
return now > self.end_time
@property
def required_attendees(self):
rsvp_attendees = self.attendees.filter(status=RsvpStatus.STATUS_ATTENDING).count()
if self.capacity:
return self.capacity - rsvp_attendees
return None
def get_absolute_url(self):
return reverse("game-detail", args=[str(self.uuid)])
def create_share_link(self):
try:
image_url = self.spot.images.first().image.url
except AttributeError:
image_url = settings.WEB_ROOT_URL + settings.STATIC_URL + "images/sportyspots-logo.png"
web_game_url = settings.WEB_ROOT_URL + reverse("web-game-detail", kwargs={"uuid": self.uuid})
return get_firebase_link(
f"games/{self.uuid}",
unguessable=False,
st=self.name,
sd=self.description or self.name,
si=image_url,
ofl=web_game_url,
afl=web_game_url,
ifl=web_game_url,
)
def send_organizer_confirmation_mail(self):
context = {
"name": self.organizer.name,
# TODO: Fix game url hardcoding
"action_url": f"https://www.sportyspots.com/games/{self.uuid}",
}
send_mail(
self.organizer.email,
template_prefix="CreateActivityConfirmation",
subject=_("Your activity details"),
language=self.organizer.profile.language,
context=context,
)
def send_attendees_update_email(self, message):
pass
def send_attendees_cancellation_email(self):
# TODO: Abstract email sending so that default fields are added
attendees = [
rsvp_status.user for rsvp_status in RsvpStatus.objects.filter(game=self, status=RsvpStatus.STATUS_ATTENDING)
]
if len(attendees) > 0:
for attendee in attendees:
context = {
"name": attendee.name,
"invite_sender_name": self.organizer.name,
# TODO: Fix game url hardcoding
"action_url": f"https://www.sportyspots.com/games/{self.uuid}",
}
send_mail(
to=attendee.email,
template_prefix="CancelledGame",
subject=_("Activity has been cancelled."),
language=attendee.profile.language,
context=context,
)
def transition_status(self, status):
if status == Game.STATUS_CANCELED:
self.transition_status_canceled()
elif status == Game.STATUS_COMPLETED:
self.transition_status_completed()
elif status == Game.STATUS_ENDED:
self.transition_status_ended()
elif status == Game.STATUS_LIVE:
self.transition_status_live()
elif status == Game.STATUS_PLANNED:
self.transition_status_planned()
elif status == Game.STATUS_UPDATED:
self.transition_status_updated()
elif status == Game.STATUS_STARTED:
self.transition_status_started()
@transition(
field=status,
source=[STATUS_DRAFT, STATUS_UPDATED],
target=STATUS_PLANNED,
permission=lambda instance, user: instance.organizer.uuid == user.uuid,
)
def transition_status_planned(self):
self.send_organizer_confirmation_mail()
@transition(
field=status,
source=STATUS_PLANNED,
target=STATUS_UPDATED,
permission=lambda instance, user: instance.organizer.uuid == user.uuid,
)
def transition_status_updated(self):
self.send_attendees_update_email()
@transition(
field=status,
source=STATUS_PLANNED,
target=STATUS_STARTED,
permission=lambda instance, user: instance.organizer.uuid == user.uuid,
)
def transition_status_started(self):
pass
@transition(
field=status,
source=[STATUS_PLANNED, STATUS_STARTED],
target=STATUS_LIVE,
permission=lambda instance, user: instance.organizer.uuid == user.uuid,
)
def transition_status_live(self):
pass
@transition(
field=status,
source=[STATUS_LIVE, STATUS_STARTED],
target=STATUS_UPDATED,
permission=lambda instance, user: instance.organizer.uuid == user.uuid,
)
def transition_status_ended(self):
pass
@transition(
field=status,
source=[STATUS_STARTED, STATUS_LIVE, STATUS_ENDED],
target=STATUS_COMPLETED,
permission=lambda instance, user: instance.organizer.uuid == user.uuid,
)
def transition_status_completed(self):
pass
@transition(
field=status,
source=[STATUS_DRAFT, STATUS_PLANNED, STATUS_STARTED, STATUS_LIVE],
target=STATUS_CANCELED,
permission=lambda instance, user: instance.organizer.uuid == user.uuid,
)
def transition_status_canceled(self):
self.send_attendees_cancellation_email()
class RsvpStatus(BasePropertiesModel):
"""
TODO:
Define State Machine to handle RSVP Status Transitions
"""
# Predefined Values
# When the user is invited, and he/she accepts.
STATUS_ACCEPTED = "accepted"
# When the user signs up for an open event
STATUS_ATTENDING = "attending"
STATUS_CHECKED_IN = "checked_in"
STATUS_DECLINED = "declined"
STATUS_INTERESTED = "interested"
STATUS_INVITED = "invited"
STATUS_UNKNOWN = "unknown"
STATUS = (
(STATUS_ACCEPTED, _("Accepted")),
(STATUS_ATTENDING, _("Attending")),
(STATUS_CHECKED_IN, _("Checked In")),
(STATUS_DECLINED, _("Declined")),
(STATUS_INTERESTED, _("Interested")),
(STATUS_INVITED, _("Invited")),
(STATUS_UNKNOWN, _("Unknown")),
)
# Foreign Keys
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
blank=False,
null=False,
on_delete=models.CASCADE,
related_name="rsvp_statuses",
verbose_name=_("Player"),
)
game = models.ForeignKey(
"games.Game",
blank=False,
null=False,
on_delete=models.CASCADE,
related_name="attendees",
verbose_name=_("Game"),
)
# Instance Fields
status = FSMField(
blank=False,
choices=STATUS,
default=STATUS_UNKNOWN,
max_length=25,
null=True,
protected=False,
verbose_name=_("Status"),
)
class Meta:
verbose_name = _("RSVP Status")
verbose_name_plural = _("RSVP Statuses")
ordering = ("-created_at",)
# TODO: should we track the whole RSVP historic/audit log changes per user in the same table or
# in a different table
unique_together = (("user", "game"),)
def __str__(self):
return f"{self.game.name} : { self.user.name}"
def send_user_confirmation_mail(self):
# TODO: Send the game details e.g. time, name, type of sport
# TODO: Create ICS file for calendar
context = {
"invite_sender_name": self.game.organizer.name,
"name": self.user.name,
# TODO: Fix game url hardcoding
"action_url": f"https://www.sportyspots.com/games/{self.game.uuid}",
}
send_mail(
to=self.user.email,
template_prefix="ConfirmationAttendance",
subject=_("Game on! You're attending!"),
language=self.user.profile.language,
context=context,
)
def transition_status(self, status: str):
if status == self.STATUS_ACCEPTED:
self.accept()
elif status == self.STATUS_ATTENDING:
self.attend()
elif status == self.STATUS_CHECKED_IN:
self.check_in()
elif status == self.STATUS_DECLINED:
self.decline()
elif status == self.STATUS_INTERESTED:
self.interested()
elif status == self.STATUS_INVITED:
self.invite()
elif status == self.STATUS_UNKNOWN:
pass
@transition(
field=status,
source=[STATUS_UNKNOWN, STATUS_INVITED, STATUS_INTERESTED],
target=STATUS_ACCEPTED,
permission=lambda instance, user: instance.user.uuid == user.uuid,
)
def accept(self):
# TODO: Send the organizer a confirmation email
# TODO: Send the user a confirmation email
pass
@transition(
field=status,
source=[STATUS_UNKNOWN, STATUS_DECLINED],
target=STATUS_ATTENDING,
permission=lambda instance, user: instance.user.uuid == user.uuid,
)
def attend(self):
# TODO: Do not send a confirmation email to organizer
self.send_user_confirmation_mail()
@transition(
field=status,
source=STATUS_ATTENDING,
target=STATUS_CHECKED_IN,
permission=lambda instance, user: instance.user.uuid == user.uuid,
)
def check_in(self):
pass
@transition(
field=status,
source=[STATUS_UNKNOWN, STATUS_INVITED, STATUS_ACCEPTED, STATUS_INTERESTED, STATUS_ATTENDING],
target=STATUS_DECLINED,
permission=lambda instance, user: instance.user.uuid == user.uuid,
)
def decline(self):
pass
@transition(
field=status,
source=STATUS_UNKNOWN,
target=STATUS_INTERESTED,
permission=lambda instance, user: instance.user.uuid == user.uuid,
)
def interested(self):
pass
@transition(
field=status,
source=STATUS_UNKNOWN,
target=STATUS_INVITED,
permission=lambda instance, user: instance.user.uuid == user.uuid,
)
def invite(self):
# TODO: Send the invitee an email, notification
pass
<file_sep>import graphene
from graphene_django.types import DjangoObjectType
from seedorf.sports.schema import SportType
from seedorf.spots.schema import SpotType
from .models import User, UserProfile
class UserProfileType(DjangoObjectType):
sports = graphene.List(SportType)
spots = graphene.List(SpotType)
class Meta:
model = UserProfile
exclude_fields = ("user",)
def resolve_avatar(self, info, **kwargs):
# the default is to send a relative url (str(self.avatar)), but we want a full URL
try:
return self.avatar.url
except ValueError:
# if no avatar has been set yet
return None
def resolve_sports(self, info, **kwargs):
return self.sports.all()
def resolve_spots(self, info, **kwargs):
return self.spots.all()
class UserType(DjangoObjectType):
profile = graphene.Field(UserProfileType)
sports = graphene.List(SportType)
spots = graphene.List(SpotType)
class Meta:
model = User
exclude_fields = ("password",)
def resolve_profile(self, info, **kwargs):
return self.profile
def resolve_sports(self, info, **kwargs):
return self.profile.sports.all()
def resolver_spots(self, info, **kwargs):
return self.profile.spots.all()
class Query(object):
user = graphene.Field(UserType, email=graphene.String(), uuid=graphene.UUID(), id=graphene.ID())
users = graphene.List(UserType)
def resolve_user(self, args, **kwargs):
uuid = kwargs.get("uuid")
user_id = kwargs.get("id")
email = kwargs.get("email")
if uuid is not None:
return User.objects.filter(uuid=uuid).first()
if user_id is not None:
return User.objects.filter(id=user_id).first()
if email is not None:
return User.objects.filter(email=email).first()
return None
def resolve_users(self, args, **kwargs):
return User.objects.all()
<file_sep>import * as dragula from '../../node_modules/dragula/dragula.js';
export { dragula };
<file_sep>const TIMEOUT = 150
class MegaDropdown {
constructor(element, options = {}) {
this._onHover = options.trigger === 'hover' || element.getAttribute('data-trigger') === 'hover'
this._container = this._findParent(element, 'mega-dropdown')
if (!this._container) return
this._menu = this._container.querySelector('.dropdown-toggle ~ .dropdown-menu')
if (!this._menu) return
element.setAttribute('aria-expanded', 'false')
this._el = element
this._bindEvents()
}
open() {
if (this._timeout) {
clearTimeout(this._timeout)
this._timeout = null
}
if (this._focusTimeout) {
clearTimeout(this._focusTimeout)
this._focusTimeout = null
}
if (this._el.getAttribute('aria-expanded') !== 'true') {
this._triggerEvent('show')
this._container.classList.add('show')
this._menu.classList.add('show')
this._el.setAttribute('aria-expanded', 'true')
this._el.focus()
this._triggerEvent('shown')
}
}
close(force) {
if (this._timeout) {
clearTimeout(this._timeout)
this._timeout = null
}
if (this._focusTimeout) {
clearTimeout(this._focusTimeout)
this._focusTimeout = null
}
if (this._onHover && !force) {
this._timeout = setTimeout(() => {
if (this._timeout) {
clearTimeout(this._timeout)
this._timeout = null
}
this._close()
}, TIMEOUT)
} else {
this._close()
}
}
toggle() {
this._el.getAttribute('aria-expanded') === 'true' ?
this.close(true) :
this.open()
}
destroy() {
this._unbindEvents()
this._el = null
if (this._timeout) {
clearTimeout(this._timeout)
this._timeout = null
}
if (this._focusTimeout) {
clearTimeout(this._focusTimeout)
this._focusTimeout = null
}
}
_close() {
if (this._el.getAttribute('aria-expanded') === 'true') {
this._triggerEvent('hide')
this._container.classList.remove('show')
this._menu.classList.remove('show')
this._el.setAttribute('aria-expanded', 'false')
this._triggerEvent('hidden')
}
}
_bindEvents() {
this._elClickEvnt = (e) => {
e.preventDefault()
this.toggle()
}
this._el.addEventListener('click', this._elClickEvnt)
this._bodyClickEvnt = (e) => {
if (!this._container.contains(e.target) && this._container.classList.contains('show')) {
this.close(true)
}
}
document.body.addEventListener('click', this._bodyClickEvnt, true)
this._menuClickEvnt = (e) => {
if (e.target.classList.contains('mega-link')) {
this.close(true)
}
}
this._menu.addEventListener('click', this._menuClickEvnt, true)
this._focusoutEvnt = (e) => {
if (this._focusTimeout) {
clearTimeout(this._focusTimeout)
this._focusTimeout = null
}
if (this._el.getAttribute('aria-expanded') !== 'true') return
this._focusTimeout = setTimeout(() => {
if (
document.activeElement.tagName.toUpperCase() !== 'BODY' &&
this._findParent(document.activeElement, 'mega-dropdown') !== this._container
) {
this.close(true)
}
}, 100)
}
this._container.addEventListener('focusout', this._focusoutEvnt, true)
if (this._onHover) {
this._enterEvnt = (e) => {
if (window.getComputedStyle(this._menu, null).getPropertyValue('position') === 'static') return
this.open()
}
this._leaveEvnt = (e) => {
if (window.getComputedStyle(this._menu, null).getPropertyValue('position') === 'static') return
this.close()
}
this._el.addEventListener('mouseenter', this._enterEvnt)
this._menu.addEventListener('mouseenter', this._enterEvnt)
this._el.addEventListener('mouseleave', this._leaveEvnt)
this._menu.addEventListener('mouseleave', this._leaveEvnt)
}
}
_unbindEvents() {
if (this._elClickEvnt) {
this._el.removeEventListener('click', this._elClickEvnt)
this._elClickEvnt = null
}
if (this._bodyClickEvnt) {
document.body.removeEventListener('click', this._bodyClickEvnt, true)
this._bodyClickEvnt = null
}
if (this._menuClickEvnt) {
this._menu.removeEventListener('click', this._menuClickEvnt, true)
this._menuClickEvnt = null
}
if (this._focusoutEvnt) {
this._container.removeEventListener('focusout', this._focusoutEvnt, true)
this._focusoutEvnt = null
}
if (this._enterEvnt) {
this._el.removeEventListener('mouseenter', this._enterEvnt)
this._menu.removeEventListener('mouseenter', this._enterEvnt)
this._enterEvnt = null
}
if (this._leaveEvnt) {
this._el.removeEventListener('mouseleave', this._leaveEvnt)
this._menu.removeEventListener('mouseleave', this._leaveEvnt)
this._leaveEvnt = null
}
}
_findParent(el, cls) {
if (el.tagName.toUpperCase() === 'BODY') return null
el = el.parentNode
while (el.tagName.toUpperCase() !== 'BODY' && !el.classList.contains(cls)) {
el = el.parentNode
}
return el.tagName.toUpperCase() !== 'BODY' ? el : null
}
_triggerEvent(event) {
if (document.createEvent) {
let customEvent
if (typeof(Event) === 'function') {
customEvent = new Event(event)
} else {
customEvent = document.createEvent('Event')
customEvent.initEvent(event, false, true)
}
this._container.dispatchEvent(customEvent)
} else {
this._container.fireEvent('on' + event, document.createEventObject())
}
}
}
export { MegaDropdown }
<file_sep>import random
import factory
from seedorf.locations.tests.factories import AddressFactory
from seedorf.sports.tests.factories import SportFactory
from seedorf.spots.models import Spot, SpotAmenity, SpotImage, SpotOpeningTime
class SpotFactory(factory.django.DjangoModelFactory):
address = factory.SubFactory(AddressFactory)
name = factory.Faker("name")
owner = factory.Faker("name")
description = factory.Faker("text")
logo = factory.django.ImageField()
homepage_url = factory.Faker("url")
is_verified = True
establishment_date = factory.Maybe(
"is_permanently_closed", yes_declaration=factory.Faker("past_date", start_date="-60d"), no_declaration=None
)
closure_date = factory.Maybe(
"is_permanently_closed", yes_declaration=factory.Faker("past_date", start_date="-30d"), no_declaration=None
)
@factory.post_generation
def sports(self, create, extracted, **kwargs):
# REF: http://factoryboy.readthedocs.io/en/latest/recipes.html#simple-many-to-many-relationship
if not create:
# Simple build, do nothing.
return
if extracted:
# A list of sports were passed in, use them
for sport in extracted:
self.sports.add(sport)
else:
sport = SportFactory()
self.sports.add(sport)
class Meta:
model = Spot
class SpotImageFactory(factory.django.DjangoModelFactory):
spot = factory.SubFactory(SpotFactory)
sport = factory.LazyAttribute(lambda o: random.choice(o.spot.sports.all()))
image = factory.django.ImageField()
class Meta:
model = SpotImage
class SpotOpeningTimeFactory(factory.django.DjangoModelFactory):
spot = factory.SubFactory(SpotFactory)
sport = factory.LazyAttribute(lambda o: random.choice(o.spot.sports.all()))
day = factory.Iterator(SpotOpeningTime.DAYS, getter=lambda d: d[0])
class Meta:
model = SpotOpeningTime
class SpotAmenityFactory(factory.Factory):
spot = factory.SubFactory(SpotFactory)
sport = factory.LazyAttribute(lambda o: random.choice(o.spot.sports.all()))
data = factory.Dict({"SURFACE": "hard", "FENCE": True})
class Meta:
model = SpotAmenity
<file_sep>from django.contrib import admin
from .models import Game, RsvpStatus
class RsvpStatusAdmin(admin.TabularInline):
model = RsvpStatus
class GameAdmin(admin.ModelAdmin):
readonly_fields = ("uuid", "created_at", "modified_at", "deleted_at")
list_display = ("uuid", "name", "sport", "status", "start_time", "end_time")
list_filter = ("status", "invite_mode")
search_fields = ("uuid", "name", "sport__name", "spot__name")
inlines = [RsvpStatusAdmin]
fieldsets = (
(
None,
{
"fields": (
"uuid",
"name",
"organizer",
"sport",
"spot",
"status",
"capacity",
"description",
"share_link",
"chatkit_room_id",
)
},
),
(
"Activity Time",
{"classes": ("expand",), "fields": ("start_time", "start_timezone", "end_time", "end_timezone")},
),
("RSVP Time", {"classes": ("collapse",), "fields": ("rsvp_open_time", "rsvp_close_time", "rsvp_closed")}),
(
"Visibility",
{"classes": ("collapse",), "fields": ("show_remaining", "is_listed", "is_shareable", "is_featured")},
),
("Audit", {"classes": ("collapse",), "fields": ("created_at", "modified_at", "deleted_at")}),
)
admin.site.register(Game, GameAdmin)
<file_sep>require('../../node_modules/bootstrap-maxlength/src/bootstrap-maxlength.js');
<file_sep>import * as Clipboard from '../../node_modules/clipboard/dist/clipboard.js';
export { Clipboard };
<file_sep>import json
import graphene
from django.contrib.gis.db import models
from graphene_django.converter import convert_django_field
from graphene_django.types import DjangoObjectType
from .models import Address
# REF: https://github.com/graphql-python/graphene-django/issues/390
class GeoJSON(graphene.Scalar):
@classmethod
def serialize(cls, value):
return json.loads(value.geojson)
@convert_django_field.register(models.PointField)
def convert_field_to_geojson(field, registry=None):
return graphene.Field(GeoJSON, description=field.help_text, required=not field.null)
class AddressType(DjangoObjectType):
class Meta:
model = Address
class Query(object):
address = graphene.Field(AddressType, uuid=graphene.UUID())
addresses = graphene.List(AddressType)
def resolve_address(self, args, **kwargs):
uuid = kwargs.get("uuid")
if uuid is not None:
return Address.objects.filter(uuid=uuid).first()
return None
def resolve_addresses(self, args, **kwargs):
return Address.objects.all()
<file_sep>import datetime
from django.contrib.contenttypes.fields import GenericRelation
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_extensions.db.fields import AutoSlugField
from seedorf.utils.models import BasePropertiesModel
from .validators import AllowedKeysValidator
def get_logo_upload_directory(instance, filename):
# file will be uploaded to MEDIA_ROOT/spots/<uuid>/logo/<filename>
# TODO: Test for files names with non latin characters
# TODO: Upload files to CDN
return f"spots/{instance.uuid}/logo/{filename}"
def get_images_upload_directory(instance, filename):
# file will be uploaded to MEDIA_ROOT/spots/<uuid>/images/<filename>
# TODO: Test for files names with non latin characters
# TODO: Upload files to CDN
return f"spots/{instance.uuid}/images/{filename}"
class Spot(BasePropertiesModel):
# Foreign Keys
# TODO: Validation there can be only one non-permanently closed spot at an address
address = models.OneToOneField(
"locations.Address",
blank=True,
null=True,
related_name="spot",
on_delete=models.CASCADE,
verbose_name=_("Address"),
)
sports = models.ManyToManyField("sports.Sport", blank=True, related_name="spots", verbose_name=_("Sports"))
# Instance Fields
name = models.CharField(blank=False, max_length=512, null=False, verbose_name=_("Name"))
slug = AutoSlugField(
blank=True, editable=True, max_length=512, populate_from="name", unique=True, verbose_name=_("Slug")
)
owner = models.CharField(blank=True, default="", max_length=512, null=False, verbose_name=_("Owner"))
description = models.TextField(blank=True, default="", max_length=4096, null=False, verbose_name=_("Description"))
logo = models.ImageField(
blank=True, max_length=512, null=False, upload_to=get_logo_upload_directory, verbose_name=_("Logo")
)
homepage_url = models.URLField(
blank=True,
help_text=_("Where can we find out more about this spot ?"),
max_length=512,
null=False,
verbose_name=_("Homepage URL"),
)
is_verified = models.BooleanField(
blank=False, default=False, help_text=_("Is this Spot verfified by the SportySpots team ?"), null=False
)
is_permanently_closed = models.BooleanField(
blank=False, default=False, help_text=_("Is this Spot permanently closed ?"), null=False
)
is_public = models.BooleanField(blank=False, default=True, help_text=_("Is this Spot a public spot ?"))
# TODO: We need a cron job to set temporary spots are permanently closed
# TODO: We need to validate if the spot is temporary, then it must have a establishment date and closure date
is_temporary = models.BooleanField(
blank=False, default=False, help_text=_("Is this spot temporary (e.g. for a special event) ?"), null=False
)
establishment_date = models.DateField(blank=True, null=True)
# NOTE: Closure date can be in the future, incase of temporary events
closure_date = models.DateField(blank=True, null=True)
# Generic Keys
reaction = GenericRelation("reactions.Reaction", related_query_name="spot_reactions")
class Meta:
verbose_name = _("Spot")
verbose_name_plural = _("Spots")
ordering = ("-created_at",)
def __str__(self):
return f"{self.name}"
class SpotImage(BasePropertiesModel):
# Foreign Keys
spot = models.ForeignKey(
"spots.Spot", blank=False, null=False, on_delete=models.CASCADE, related_name="images", verbose_name=_("Spot")
)
sport = models.ForeignKey(
"sports.Sport",
blank=False,
null=False,
on_delete=models.CASCADE,
related_name="images",
verbose_name=_("Sport"),
)
# Instance Fields
image = models.ImageField(blank=False, max_length=512, null=False, upload_to=get_images_upload_directory)
is_flagged = models.BooleanField(
default=False, editable=False, help_text=_("Is this image marked as offensive/ non-relevant ?")
)
is_user_submitted = models.BooleanField(
default=True, editable=False, help_text=_("Is this image submitted by the user ?")
)
class Meta:
verbose_name = _("Spot Image")
verbose_name_plural = _("Spot Images")
ordering = ("-created_at",)
def __str__(self):
return f"{self.spot.name} : {self.sport.name}"
class SpotOpeningTime(BasePropertiesModel):
"""
TODO: Validation
A spot can have multiple opening times during a day
A spot can be closed for the whole day or for the certain time in a day
A spot can be closed yearly for a certain days like public holidays
A spot can be closed for certain times of the year
A spot can be closed can be closed on special adhoc days
"""
DAY_MONDAY = "MONDAY"
DAY_TUESDAY = "TUESDAY"
DAY_WEDNESDAY = "WEDNESDAY"
DAY_THURSDAY = "THURSDAY"
DAY_FRIDAY = "FRIDAY"
DAY_SATURDAY = "SATURDAY"
DAY_SUNDAY = "SUNDAY"
DAYS = (
(DAY_MONDAY, _("Monday")),
(DAY_TUESDAY, _("Tuesday")),
(DAY_WEDNESDAY, _("Wednesday")),
(DAY_THURSDAY, _("Thursday")),
(DAY_FRIDAY, _("Friday")),
(DAY_SATURDAY, _("Saturday")),
(DAY_SUNDAY, _("Sunday")),
)
spot = models.ForeignKey(
"spots.Spot",
blank=False,
null=False,
on_delete=models.CASCADE,
related_name="opening_times",
verbose_name=_("Spot"),
)
sport = models.ForeignKey(
"sports.Sport",
blank=False,
null=False,
on_delete=models.CASCADE,
related_name="opening_times",
verbose_name=_("Sport"),
)
day = models.CharField(blank=False, choices=DAYS, max_length=25, null=False)
start_time = models.TimeField(blank=False, default=datetime.time(0, 0, 0, 0))
end_time = models.TimeField(blank=False, default=datetime.time(23, 59, 59, 999999))
is_closed = models.BooleanField(blank=False, default=False)
class Meta:
verbose_name = _("Spot Opening Time")
verbose_name_plural = _("Spot Opening Times")
ordering = ("-created_at",)
def __str__(self):
return f"{self.spot.name} : {self.sport.name}"
AMENITIES_TYPE_SCHEMA = {
"INDOOR": {"type": "boolean"},
"OUTDOOR": {"type": "boolean"},
"WIDTH": {"type": "integer"},
"BREADTH": {"type": "integer"},
"SIZE": {"type": "integer"},
"HAS_FLOODLIGHTS": {"type": "boolean"},
"SURFACE": {"type": "string"},
"LOCATION": {"type": "string", "allowed": [""]},
"FENCE": {"type": "boolean"},
"FIELD_MARKINGS": {"type": "boolean"},
"SOCCER_GOALS_ONE_SIDED": {"type": "boolean"},
"SOCCER_GOALS_BOTH_SIDED": {"type": "boolean"},
"SOCCER_GOALS_SIZE": {"type": "string", "allowed": [""]},
"BASKETBALL_POLE_ONE_SIDED": {"type": "boolean"},
"BASKETBALL_POLE_BOTH_SIDED": {"type": "boolean"},
"MULTISPORT_FIELD": {"type": "boolean"},
}
class SpotAmenity(BasePropertiesModel):
# Foreign Keys
spot = models.ForeignKey(
"spots.Spot",
blank=False,
null=False,
on_delete=models.CASCADE,
related_name="amenities",
verbose_name=_("Spot"),
)
sport = models.ForeignKey(
"sports.Sport",
blank=False,
null=False,
on_delete=models.CASCADE,
related_name="amenities",
verbose_name=_("Sport"),
)
# Instance Fields
data = JSONField(validators=[AllowedKeysValidator(list(AMENITIES_TYPE_SCHEMA.keys()))])
class Meta:
verbose_name = _("Spot Amenity")
verbose_name_plural = _("Spot Amenities")
ordering = ("-created_at",)
def __str__(self):
return f"{self.spot.name} : {self.sport.name}"
<file_sep>from rest_framework import serializers
from seedorf.spots.models import Spot
from .models import Address
class AddressSerializer(serializers.ModelSerializer):
class Meta:
model = Address
fields = ("uuid", "lat", "lng", "raw_address", "formatted_address", "created_at", "modified_at")
read_only_fields = ("created_at", "modified_at")
def create(self, validated_data):
spot_uuid = self.context["view"].kwargs["spot_uuid"]
spot = Spot.objects.get(uuid=spot_uuid)
address = Address.objects.create(**validated_data)
spot.address = address
spot.save()
return address
<file_sep>require('../../../node_modules/jquery-mapael/js/maps/france_departments.js');
<file_sep>import graphene
from graphene_django_extras import DjangoFilterPaginateListField, DjangoObjectType, LimitOffsetGraphqlPagination
from .models import Sport
from .viewsets import SportFilter
class SportType(DjangoObjectType):
class Meta:
model = Sport
class Query(object):
sport = graphene.Field(SportType, uuid=graphene.UUID())
sports = DjangoFilterPaginateListField(
SportType, filterset_class=SportFilter, pagination=LimitOffsetGraphqlPagination()
)
@staticmethod
def resolve_sport(args, **kwargs):
uuid = kwargs.get("uuid")
if uuid is not None:
return Sport.objects.filter(uuid=uuid).first()
return None
@staticmethod
def resolve_sports(args, **kwargs):
return Sport.objects.all()
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-05-23 09:46
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("games", "0002_auto_20180502_0816")]
operations = [
migrations.AddField(
model_name="game",
name="description",
field=models.TextField(blank=True, help_text="Description of the game.", verbose_name="Description"),
)
]
<file_sep>const originalPicker = $.fn.bootstrapMaterialDatePicker;
$.fn.bootstrapMaterialDatePicker = function (...args) {
this.each(function() {
const newInstance = !$.data(this, 'plugin_bootstrapMaterialDatePicker');
originalPicker.apply($(this), args);
if (newInstance) {
const $template = $('body').find(`> #${$.data(this, 'plugin_bootstrapMaterialDatePicker').name}`);
// Add animation
$template.addClass('animated fadeIn')
// Styling buttons
$template.find('.dtp-btn-now,.dtp-btn-clear,.dtp-btn-cancel').addClass('btn-default btn-sm');
$template.find('.dtp-btn-ok').addClass('btn-primary btn-sm');
}
});
return this;
};
<file_sep>require('../../node_modules/bootstrap-tagsinput/dist/bootstrap-tagsinput.js');
require('./_extension.es6');
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-06-02 21:10
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("spots", "0003_auto_20180513_0820")]
operations = [
migrations.AlterModelOptions(
name="spotamenity",
options={
"ordering": ("-created_at",),
"verbose_name": "Spot Amenity",
"verbose_name_plural": "Spot Amenities",
},
),
migrations.AlterModelOptions(
name="spotopeningtime",
options={
"ordering": ("-created_at",),
"verbose_name": "Spot Opening Time",
"verbose_name_plural": "Spot Opening Times",
},
),
]
<file_sep>// Fix input position calculation
//
const tagsinputBuild = $.fn.tagsinput.Constructor.prototype.build;
const tagsinputDestroy = $.fn.tagsinput.Constructor.prototype.destroy;
$.fn.tagsinput.Constructor.prototype.build = function(options) {
if (options && options.typeahead) {
$.extend(options.typeahead, {
minLength: 1,
afterSelect: () => {
this.$input[0].value = '';
this.$input.data('typeahead').lookup('');
}
});
}
const result = tagsinputBuild.call(this, options);
const re = /<|>/g;
this.$inpWidth = $('<div class="bootstrap-tagsinput-input" style="position:absolute;z-index:-101;top:-9999px;opacity:0;white-space:nowrap;"></div>');
$('<div style="position:absolute;width:0;height:0;z-index:-100;opacity:0;overflow:hidden;"></div>').append(this.$inpWidth).prependTo(this.$container);
const getWidth = val => Math.ceil(this.$inpWidth.html((val || '').replace(re, '#')).outerWidth() + 12) + 'px';
this.$input[0].style.width = getWidth();
this.$input.on('keydown keyup focusout', function() {
this.style.width = getWidth(this.value);
if (this.value.length < 1 && options && options.typeahead) {
$(this).data('typeahead').lookup('');
}
});
this.$input.on('paste', function() {
setTimeout($.proxy(function() { this.style.width = getWidth(this.value); }, this), 100);
});
return result;
};
$.fn.tagsinput.Constructor.prototype.destroy = function() {
this.$input.off('keydown keyup focusout paste change');
return tagsinputDestroy.call(this);
};
// Re-initialize [data-role=tagsinput]
$(function() {
$('input[data-role=tagsinput], select[multiple][data-role=tagsinput]').tagsinput('destroy');
$('input[data-role=tagsinput], select[multiple][data-role=tagsinput]').tagsinput();
});
<file_sep># Generated by Django 2.1.2 on 2019-03-09 23:49
from django.db import migrations
import django_fsm
class Migration(migrations.Migration):
dependencies = [("games", "0008_auto_20181207_2123")]
operations = [
migrations.AlterField(
model_name="game",
name="status",
field=django_fsm.FSMField(
choices=[
("canceled", "Canceled"),
("completed", "Completed"),
("draft", "Draft"),
("ended", "Ended"),
("live", "Live"),
("planned", "Planned"),
("updated", "Updated"),
("started", "Started"),
],
default="draft",
max_length=25,
verbose_name="Status",
),
)
]
<file_sep>import jwt
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from .client import create_client
class ChatkitView(APIView):
permission_classes = (AllowAny,)
@staticmethod
def post(request, *args, **kwargs):
if request.user.is_authenticated:
user_uuid = str(request.user.uuid)
else:
user_uuid = "readonly"
client = create_client()
token = client.create_token(user_uuid)
claims = jwt.decode(token, verify=False)
return Response(
{
"access_token": token,
"user_id": user_uuid,
"token_type": "access_token",
"expires_in": str(claims["exp"]),
}
)
<file_sep>import base64
import hashlib
import pytz
import six
from allauth.account import app_settings as allauth_settings
from allauth.account.adapter import get_adapter
from allauth.account.utils import setup_user_email
from allauth.utils import email_address_exists
from django.conf import settings
from django.contrib.auth.models import Group
from django.core.files.base import ContentFile
from django.core.validators import EmailValidator
from django.utils.translation import ugettext_lazy as _
from django_countries.serializers import CountryFieldMixin
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from seedorf.sports.models import Sport
from seedorf.sports.serializers import SportSerializer
from seedorf.spots.serializers import SpotSerializer
from .models import User, UserProfile
class TimezoneField(serializers.Field):
def to_representation(self, obj):
return six.text_type(obj)
def to_internal_value(self, data):
try:
return pytz.timezone(str(data))
except pytz.exceptions.UnknownTimeZoneError:
raise serializers.ValidationError(_("Unknown timezone"))
class Base64ImageField(serializers.ImageField):
def to_internal_value(self, data):
# data looks like 'data:image/jpeg;base64,asdakhgf'
base64_str = data.split(",")[1]
content = base64.b64decode(base64_str)
content_hash = hashlib.sha1(content).hexdigest()
data = ContentFile(content, name=content_hash + ".jpg")
return super(Base64ImageField, self).to_internal_value(data)
class UserSportNestedSerializer(serializers.ModelSerializer):
uuid = serializers.UUIDField(required=True)
class Meta:
model = Sport
fields = ("uuid", "category", "name", "description", "created_at", "modified_at")
read_only_fields = ("uuid", "category", "name", "description", "created_at", "modified_at")
def create(self, validated_data):
if self.context["view"].basename == "user-sport":
user_uuid = self.context["view"].kwargs["user_uuid"]
user = User.objects.get(uuid=user_uuid)
sport_uuid = validated_data["uuid"]
try:
sport = Sport.objects.get(uuid=str(sport_uuid))
except Sport.DoesNotExist:
raise serializers.ValidationError(_("Invalid sport"))
user.sports.add(sport)
user.save()
return sport
return {}
class UserProfileSerializer(CountryFieldMixin, serializers.ModelSerializer):
sports = SportSerializer(read_only=True, many=True, required=False)
spots = SpotSerializer(read_only=True, many=True, required=False)
timezone = TimezoneField(required=False)
avatar = Base64ImageField(required=False)
# spots = serializers.SerializerMethodField()
# sports = serializers.SerializerMethodField()
class Meta:
model = UserProfile
fields = (
"uuid",
"sports",
"spots",
"gender",
"avatar",
"year_of_birth",
"language",
"timezone",
"country",
"bio",
)
read_only_fields = ("uuid", "sports", "spots", "created_at", "modified_at")
def create(self, validated_data):
# NOTE: Only the user himself can update his profile
user = self.context["request"].user
validated_data["user"] = user
profile = UserProfile.objects.create(**validated_data)
profile.save()
return profile
def update(self, instance, validated_data):
# NOTE: We disallow nested object creation, hence pop out (ignore) related objects
validated_data.pop("spots", None)
validated_data.pop("sports", None)
for k, v in validated_data.items():
setattr(instance, k, v)
instance.save()
return instance
# def get_spots(self, obj):
# spots = obj.spots.all()
# self.context["user_uuid"] = obj.uuid
# return UserProfileSpotNestedSerializer(spots, many=True, read_only=True, context=self.context).data
#
# def get_sports(self, obj):
# sports = obj.sports.all()
# self.context["user_uuid"] = obj.uuid
# return UserProfileSportNestedSerializer(sports, many=True, read_only=True, context=self.context).data
# class UserProfileSportNestedSerializer(NestedHyperlinkedModelSerializer):
# uuid = serializers.UUIDField(required=True)
#
# class Meta:
# model = Sport
# fields = ('uuid', 'category', 'name', 'description', 'created_at', 'modified_at')
# read_only_fields = ('category', 'name', 'description', 'created_at', 'modified_at',)
#
# def create(self, validated_data):
# user_uuid = self.context['view'].kwargs['user_uuid']
# user = User.objects.get(uuid=user_uuid)
#
# sport_uuid = validated_data['uuid']
# try:
# sport = Sport.objects.get(uuid=str(sport_uuid))
# except Sport.DoesNotExist:
# raise serializers.ValidationError(_('Sport not found'))
#
# # if the game already has a spot assigned, then check if the sport being assinged belongs to the spot
# if game.spot:
# spot = Spot.objects.filter(sports__uuid=sport_uuid).first()
# if not spot or game.spot.uuid != spot.uuid:
# raise serializers.ValidationError(_('Invalid Sport. Sport being assigned is not associated with the'
# ' game spot'))
#
# game.sport = sport
# game.save()
#
# return sport
class UserSerializer(serializers.ModelSerializer):
profile = UserProfileSerializer(many=False, required=False)
class Meta:
model = User
fields = (
"uuid",
"name",
"email",
"is_staff",
"is_active",
"date_joined",
"profile",
"created_at",
"modified_at",
"groups",
)
read_only_fields = ("uuid", "is_staff", "is_active", "date_joined", "created_at", "modified_at", "groups")
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ("name",)
class RegisterSerializer(serializers.Serializer):
name = serializers.CharField(required=False)
language = serializers.CharField(default="en", required=False)
email = serializers.EmailField(
required=True, validators=[EmailValidator(), UniqueValidator(queryset=User.objects.all())]
)
password1 = serializers.CharField(required=False, write_only=True)
password2 = serializers.CharField(required=False, write_only=True)
@staticmethod
def validate_email(email):
email = get_adapter().clean_email(email)
if allauth_settings.UNIQUE_EMAIL:
if email and email_address_exists(email):
raise serializers.ValidationError(_("A user is already registered with this e-mail address."))
return email
@staticmethod
def validate_password1(password):
if password:
return get_adapter().clean_password(password)
# set a random password, if the password is empty
return User.objects.make_random_password()
@staticmethod
def validate_language(language):
languages_codes = [language[0] for language in settings.LANGUAGES]
if language in languages_codes:
return language
return "en"
def validate(self, data):
if data.get("password1") != data.get("password2"):
raise serializers.ValidationError(_("The two password fields didn't match."))
return data
def get_cleaned_data(self):
return {
# Force email to be the username
"username": self.validated_data.get("email", ""),
"email": self.validated_data.get("email", ""),
"password1": self.validated_data.get("password1", ""),
"name": self.validated_data.get("name", ""),
"language": self.validated_data.get("language", "en"),
}
def save(self, request):
self.cleaned_data = self.get_cleaned_data()
adapter = get_adapter()
user = adapter.new_user(request)
user_instance = adapter.save_user(request, user, self)
setup_user_email(request, user_instance, [])
# force set the language on user profile
user_instance.profile.language = self.cleaned_data["language"]
user_instance.profile.save()
return user
<file_sep>import * as textMaskAddons from '../../node_modules/text-mask-addons/dist/textMaskAddons.js';
export { textMaskAddons };
<file_sep>require('../../node_modules/smartwizard/dist/js/jquery.smartWizard.js');
<file_sep>require('../../node_modules/pwstrength-bootstrap/dist/pwstrength-bootstrap.js');
<file_sep>#!/usr/bin/env bash
${ENV:?"Please set ENV non-empty"}
set -o errexit
set -o pipefail
set -o nounset
if [ "$ENV" == "dev" ]
then
set -o xtrace
python manage.py migrate
python manage.py runserver_plus 0.0.0.0:8000
elif [ "$ENV" == "prd" ]
then
python /app/manage.py collectstatic --noinput
python /app/manage.py migrate
/usr/local/bin/gunicorn config.wsgi -w 4 -b 0.0.0.0:8000 --chdir=/app
else
echo "Invalid ENV variable"
exit
fi
<file_sep># Generated by Django 2.2b1 on 2019-03-14 11:39
from django.db import migrations, models
import django.db.models.deletion
import wagtail.core.blocks
import wagtail.core.fields
class Migration(migrations.Migration):
initial = True
dependencies = [("wagtailcore", "0041_group_collection_permissions_verbose_name_plural")]
operations = [
migrations.CreateModel(
name="PageHome",
fields=[
(
"page_ptr",
models.OneToOneField(
auto_created=True,
on_delete=django.db.models.deletion.CASCADE,
parent_link=True,
primary_key=True,
serialize=False,
to="wagtailcore.Page",
),
),
(
"body",
wagtail.core.fields.StreamField(
[
(
"hero_header",
wagtail.core.blocks.StructBlock(
[
("heading", wagtail.core.blocks.CharBlock(default="")),
("sub_heading", wagtail.core.blocks.CharBlock(default="")),
]
),
)
],
blank=True,
null=True,
),
),
],
options={"verbose_name": "homepage", "verbose_name_plural": "homepages"},
bases=("wagtailcore.page",),
)
]
<file_sep>import * as vanillaTextMask from '../../node_modules/vanilla-text-mask/dist/vanillaTextMask.js';
export { vanillaTextMask };
<file_sep>require('../../node_modules/jquery-knob/js/jquery.knob.js');
<file_sep>import jwt
from django.conf import settings
from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework_jwt.settings import api_settings
from unittest.mock import patch
from seedorf.sports.tests.factories import SportFactory
from seedorf.spots.tests.factories import SpotFactory
from seedorf.users.models import User, UserProfile
from seedorf.users.adapters import AccountAdapter
from .factories import UserFactory, UserProfileFactory
class UserListAPIViewTest(APITestCase):
url = reverse("user-list")
def test_user_list(self):
response = self.client.get(self.url)
self.assertEqual(405, response.status_code)
class UserUpdateAPIViewTest(APITestCase):
def test_user_list(self):
user = UserFactory(name="test")
self.client.force_authenticate(user=user)
url = reverse("user-detail", kwargs={"uuid": str(user.uuid)})
user_data = {"name": "test1"}
response = self.client.patch(url, data=user_data)
self.assertEqual(200, response.status_code)
self.assertEqual(response.data["name"], user_data["name"])
class UserRegistrationAPIViewTest(APITestCase):
url = reverse("rest-auth-registration:rest_register")
def test_user_creation_without_password(self):
user_data = {"name": "test create name", "email": "<EMAIL>"}
with patch.object(AccountAdapter, "send_confirmation_mail", return_value=None), patch.object(
AccountAdapter, "get_login_redirect_url", return_value=""
):
response = self.client.post(self.url, user_data)
self.assertEqual(201, response.status_code)
self.assertTrue("token" in response.data)
user = User.objects.get(email=user_data["email"])
decoded_token = jwt.decode(response.data["token"], settings.SECRET_KEY, algorithms=["HS256"])
response_user = response.data["user"]
# Token contains the defined keys
self.assertTrue({"user_id", "uuid", "email", "username", "exp"}.issubset(decoded_token))
self.assertEqual(response_user["name"], user_data["name"])
# Token has a the user with the right uuid
self.assertEqual(decoded_token["uuid"], str(user.uuid))
self.assertEqual(response_user["email"], user_data["email"])
self.assertEqual(user.username, user_data["email"])
self.assertFalse(response_user["is_staff"])
self.assertTrue(response_user["is_active"])
self.assertFalse(response_user["groups"])
# user profile
response_user_profile = response_user["profile"]
self.assertFalse(response_user_profile["sports"])
self.assertFalse(response_user_profile["spots"])
self.assertEqual(response_user_profile["gender"], UserProfile.GENDER_NOT_SPECIFIED)
self.assertIsNone(response_user_profile["year_of_birth"])
self.assertIsNone(response_user_profile["avatar"])
self.assertEqual(response_user_profile["language"], "en")
self.assertEqual(response_user_profile["timezone"], "Europe/Amsterdam")
self.assertEqual(response_user_profile["country"], "")
self.assertEqual(response_user_profile["bio"], "")
def test_user_creation_with_unsupported_language(self):
user_data = {"name": "test create name", "email": "<EMAIL>", "language": "xx"}
with patch.object(AccountAdapter, "send_confirmation_mail", return_value=None), patch.object(
AccountAdapter, "get_login_redirect_url", return_value=""
):
response = self.client.post(self.url, user_data)
response_user = response.data["user"]
response_user_profile = response_user["profile"]
self.assertEqual(201, response.status_code)
self.assertTrue("token" in response.data)
self.assertEqual(response_user_profile["language"], "en")
def test_user_creation_with_supported_language(self):
user_data = {"name": "<NAME>", "email": "<EMAIL>", "language": "nl"}
with patch.object(AccountAdapter, "send_confirmation_mail", return_value=None), patch.object(
AccountAdapter, "get_login_redirect_url", return_value=""
):
response = self.client.post(self.url, user_data)
response_user = response.data["user"]
response_user_profile = response_user["profile"]
self.assertEqual(201, response.status_code)
self.assertTrue("token" in response.data)
self.assertEqual(response_user_profile["language"], "nl")
def test_user_creation_with_password(self):
user_data = {
"name": "<NAME>",
"email": "<EMAIL>",
"password1": "<PASSWORD>",
"password2": "<PASSWORD>",
}
with patch.object(AccountAdapter, "send_confirmation_mail", return_value=None), patch.object(
AccountAdapter, "get_login_redirect_url", return_value=""
):
response = self.client.post(self.url, user_data)
self.assertEqual(201, response.status_code)
self.assertTrue("token" in response.data)
user = User.objects.get(email=user_data["email"])
decoded_token = jwt.decode(response.data["token"], settings.SECRET_KEY, algorithms=["HS256"])
response_user = response.data["user"]
# Token contains the defined keys
self.assertTrue({"user_id", "uuid", "email", "username", "exp"}.issubset(decoded_token))
self.assertEqual(response_user["name"], user_data["name"])
# Token has a the user with the right uuid
self.assertEqual(decoded_token["uuid"], str(user.uuid))
self.assertEqual(response_user["email"], user_data["email"])
self.assertEqual(user.username, user_data["email"])
self.assertFalse(response_user["is_staff"])
self.assertTrue(response_user["is_active"])
self.assertFalse(response_user["groups"])
# user profile
response_user_profile = response_user["profile"]
self.assertFalse(response_user_profile["sports"])
self.assertFalse(response_user_profile["spots"])
self.assertEqual(response_user_profile["gender"], UserProfile.GENDER_NOT_SPECIFIED)
self.assertIsNone(response_user_profile["year_of_birth"])
self.assertIsNone(response_user_profile["avatar"])
self.assertEqual(response_user_profile["language"], "en")
self.assertEqual(response_user_profile["timezone"], "Europe/Amsterdam")
self.assertEqual(response_user_profile["country"], "")
self.assertEqual(response_user_profile["bio"], "")
def test_duplicate_user_creation(self):
"""
Test to verify that duplicate user creation is forbidden
"""
UserFactory(username="test", email="<EMAIL>")
user_data = {
"username": "test",
"email": "<EMAIL>",
"password1": "<PASSWORD>",
"password2": "<PASSWORD>",
}
response = self.client.post(self.url, user_data)
self.assertEqual(400, response.status_code)
class UserProfileAPIViewTest(APITestCase):
# TODO: Write test to test Avatar creation
def test_user_profile_creation(self):
user = UserFactory(username="test", email="<EMAIL>")
self.client.force_authenticate(user=user)
url = reverse("user-profile-detail", kwargs={"user_uuid": str(user.uuid), "uuid": str(user.profile.uuid)})
response = self.client.get(url)
self.assertEqual(200, response.status_code)
self.assertEqual(response.data["sports"], [])
self.assertEqual(response.data["spots"], [])
self.assertEqual(response.data["gender"], UserProfile.GENDER_NOT_SPECIFIED)
self.assertEqual(response.data["year_of_birth"], None)
self.assertEqual(response.data["avatar"], None)
self.assertEqual(response.data["language"], "en")
self.assertEqual(response.data["timezone"], "Europe/Amsterdam")
self.assertEqual(response.data["country"], "")
self.assertEqual(response.data["bio"], "")
self.assertCountEqual(
["uuid", "sports", "spots", "gender", "year_of_birth", "avatar", "language", "timezone", "country", "bio"],
response.data.keys(),
)
def test_user_profile_edit(self):
sport = SportFactory()
spot = SpotFactory(sports=[sport])
user = UserFactory(username="test", email="<EMAIL>")
self.client.force_authenticate(user=user)
url = reverse("user-profile-detail", kwargs={"user_uuid": str(user.uuid), "uuid": str(user.profile.uuid)})
user_profile_data = {"year_of_birth": 1981}
response = self.client.put(url, user_profile_data)
self.assertEqual(200, response.status_code)
self.assertEqual(response.data["year_of_birth"], 1981)
def test_user_profile_sport_retrieve(self):
sport = SportFactory()
spot = SpotFactory(sports=[sport])
user_profile = UserProfileFactory.create(spots=[spot], sports=[sport])
self.client.force_authenticate(user=user_profile.user)
url = reverse(
"user-profile-sports-list",
kwargs={"user_uuid": str(user_profile.user.uuid), "profile_uuid": str(user_profile.uuid)},
)
response = self.client.get(url)
self.assertEqual(200, response.status_code)
response_sport = response.data["results"][0]
self.assertEqual(response_sport["uuid"], str(sport.uuid))
self.assertEqual(response_sport["category"], sport.category)
self.assertEqual(response_sport["description"], sport.description)
self.assertEqual(response_sport["name"], sport.name)
def test_user_profile_spot_retrieve(self):
sport = SportFactory()
spot = SpotFactory(sports=[sport])
user_profile = UserProfileFactory.create(spots=[spot], sports=[sport])
self.client.force_authenticate(user=user_profile.user)
url = reverse(
"user-profile-spots-list",
kwargs={"user_uuid": str(user_profile.user.uuid), "profile_uuid": str(user_profile.uuid)},
)
response = self.client.get(url)
self.assertEqual(200, response.status_code)
response_spot = response.data["results"][0]
self.assertEqual(response_spot["uuid"], str(spot.uuid))
self.assertCountEqual(
[
"uuid",
"address",
"sports",
"name",
"slug",
"owner",
"description",
"logo",
"homepage_url",
"is_verified",
"is_permanently_closed",
"is_public",
"is_temporary",
"establishment_date",
"closure_date",
"created_at",
"modified_at",
"deleted_at",
],
response_spot.keys(),
)
def mock_get_firebase_link(app_link, unguessable=True, **kwargs):
return f"https://mock.link/{app_link[0:10]}"
@patch("seedorf.users.models.get_firebase_link", mock_get_firebase_link)
@patch("seedorf.users.models.time.time", lambda: 12345)
class UserMagicLinkAPIViewTest(APITestCase):
def test_create_magic_link(self):
user = UserFactory(name="test", email="<EMAIL>")
url = reverse("account_create_magic_link")
body = {"email": user.email}
response = self.client.post(url, data=body)
self.assertEqual(201, response.status_code)
self.assertEqual(str(response.data), "Email sent")
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
decoded_jwt = jwt_decode_handler(user.magic_link.token)
expected_decoded_jwt = {"email": user.email, "name": user.name, "iat": 12345}
self.assertDictEqual(expected_decoded_jwt, decoded_jwt)
def test_confirm_magic_link(self):
user = UserFactory(name="test", email="<EMAIL>")
user.create_magic_link()
url = reverse("account_confirm_magic_link")
body = {"token": user.magic_link.token}
response = self.client.post(url, data=body)
self.assertEqual(200, response.status_code)
self.assertTrue("token" in response.data)
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
decoded_jwt = jwt_decode_handler(response.data["token"])
self.assertEqual(str(user.uuid), decoded_jwt["uuid"])
# Create Token Manually
# from rest_framework_jwt.settings import api_settings
#
# jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
# jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
#
# payload = jwt_payload_handler(user)
# token = jwt_encode_handler(payload)
<file_sep>require('../../../../node_modules/bootstrap-table/src/extensions/print/bootstrap-table-print.js');
<file_sep>require('../../node_modules/cropper/dist/cropper.common.js');
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-06-17 11:25
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.gis.geos import Point
def set_points(apps, schema_editor):
Address = apps.get_model("locations", "Address")
for address in Address.objects.all():
if address.lat and address.lng:
address.point = Point(x=float(address.lng), y=float(address.lat), srid=4326)
address.save()
class Migration(migrations.Migration):
dependencies = [("locations", "0003_address_point")]
operations = [migrations.RunPython(set_points)]
<file_sep># Generated by Django 2.1.2 on 2019-05-01 11:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("games", "0013_game_share_link")]
operations = [
migrations.AddField(
model_name="game",
name="chatkit_room_id",
field=models.IntegerField(
blank=True, null=True, help_text="ChatKit room ID.", verbose_name="ChatKit room ID"
),
preserve_default=False,
)
]
<file_sep>from django.apps import AppConfig
class SportsConfig(AppConfig):
name = "seedorf.sports"
verbose_name = "Sports"
<file_sep># Generated by Django 2.1.2 on 2018-12-07 20:23
import django.core.validators
from django.db import migrations, models
import django.utils.timezone
import django_fsm
class Migration(migrations.Migration):
dependencies = [("games", "0006_auto_20181117_1312")]
operations = [
migrations.AlterField(
model_name="game",
name="end_time",
field=models.DateTimeField(
default=django.utils.timezone.now,
help_text="End time of the game in UTC.",
verbose_name="End Time (UTC)",
),
preserve_default=False,
)
]
<file_sep>// Extend sparkline plugin to handle resizing
//
// Inline id generator
function getUniqueId(){let t=(Math.floor(25*Math.random())+10).toString(36)+"_";t+=(new Date).getTime().toString(36)+"_";do t+=Math.floor(35*Math.random()).toString(36);while(t.length<32);return t;}
// Defaults
const DEFAULT_BAR_SPACING = '2px';
// Definition
//
class SparklineExt {
constructor(element, values, config) {
this.uniqueId = getUniqueId();
this.element = element;
this.$parent = $(element.parentNode);
this.update(values, config);
this._setListeners();
}
// public
update(values, config) {
if (values !== null) {
this._values = values;
}
if (config !== null) {
// Set defaults
if (config.width === '100%' && (config.type === 'bar' || config.type === 'tristate') && typeof config.barSpacing === 'undefined') {
config.barSpacing = DEFAULT_BAR_SPACING;
}
this.config = config;
}
// Copy config
const _config = $.extend(true, {}, this.config);
if (_config.width === '100%') {
if (_config.type === 'bar' || _config.type === 'tristate') {
_config.barWidth = this._getBarWidth(this.$parent, this._values.length, _config.barSpacing);
} else {
_config.width = Math.floor(this.$parent.width());
}
}
$(this.element).sparkline(this._values, _config);
}
destroy() {
this._unsetListeners();
$(this.element)
.removeData('sparklineExt')
.removeData('_jqs_mhandler')
.removeData('_jqs_vcanvas')
.off()
.find('canvas').remove();
}
// private
_getBarWidth($parent, barsCount, spacer) {
const width = $parent.width();
const span = parseInt(spacer, 10) * (barsCount - 1);
return Math.floor((width - span) / barsCount);
}
_setListeners() {
$(window).on(`resize.sparklineExt.${this.uniqueId}`, () => {
if (this.config.width !== '100%') { return; }
// Copy config
const _config = $.extend(true, {}, this.config);
if (_config.type === 'bar' || _config.type === 'tristate') {
_config.barWidth = this._getBarWidth(this.$parent, this._values.length, _config.barSpacing);
} else {
_config.width = Math.floor(this.$parent.width());
}
$(this.element).sparkline(this._values, _config);
});
}
_unsetListeners() {
$(window).off(`resize.sparklineExt.${this.uniqueId}`);
}
// static
static _parseArgs(element, args) {
let values;
let config;
if (Object.prototype.toString.call(args[0]) === '[object Array]' || args[0] === 'html' || args[0] === null) {
values = args[0];
config = args[1] || null;
} else {
config = args[0] || null;
}
if ((values === 'html' || values === undefined) && values !== null) {
values = element.getAttribute('values');
if (values === undefined || values === null) {
values = $(element).html();
}
values = values.replace(/(^\s*<!--)|(-->\s*$)|\s+/g, '').split(',');
}
if (!values || Object.prototype.toString.call(values) !== '[object Array]' || values.length === 0) {
values = null;
}
return { values, config };
}
static _jQueryInterface(...args) {
return this.each(function() {
let data = $(this).data('sparklineExt');
const method = (args[0] === 'update' || args[0] === 'destroy') ? args[0] : null;
const { values, config } = SparklineExt._parseArgs(this, method ? args.slice(1) : args);
if (!data) {
data = new SparklineExt(this, values || [], config || {});
$(this).data('sparklineExt', data);
} else if (values) {
data.update(values, config);
}
if (method === 'update') {
data.update(values, config);
} else if (method === 'destroy') {
data.destroy();
}
});
}
}
// jQuery
//
$.fn.sparkline2 = SparklineExt._jQueryInterface;
$.fn.sparkline2.Constructor = SparklineExt;
$.fn.sparkline2.noConflict = function() {
$.fn.sparkline2 = JQUERY_NO_CONFLICT;
return SparklineExt._jQueryInterface;
};
<file_sep>require('../../../node_modules/jquery-mapael/js/maps/usa_states.js');
<file_sep>require('../../node_modules/jstree/dist/jstree.js');
<file_sep>[[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"
[packages]
"argon2-cffi" = "==19.2.0"
"boto3" = "==1.10.5"
"psycopg2" = "==2.7.3.1"
apistar = "==0.7.2"
awesome-slugify = "==1.6.5"
celery = "==4.3.0"
cerberus = "==1.3.2"
colorama = "==0.4.1"
coreapi = "==2.3.3"
django = "==2.2.6"
django-allauth = "==0.40.0"
django-anymail = "==7.0.0"
django-cities = "==0.5.0.6"
django-compressor = "==2.3"
django-cors-headers = "==3.1.1"
django-countries = "==5.5"
django-crispy-forms = "==1.8.0"
django-environ = "==0.4.5"
django-extensions = "==2.2.5"
django-filter = "==2.2.0"
django-fsm = "==2.6.1"
django-fsm-admin = "==1.2.4"
django-fsm-log = "==1.6.2"
django-guardian = "==2.1.0"
django-haystack = "==2.8.1"
django-redis = "==4.10.0"
django-rest-auth = "==0.9.5"
django-rest-swagger = "==2.2.0"
django-storages = "==1.7.2"
django-timezone-field = "==3.1"
djangorestframework = "==3.10.3"
djangorestframework-gis = "==0.14"
djangorestframework-jwt = "==1.11.0"
drf-extensions = "==0.5.0"
drf-nested-routers = "==0.91"
drf-writable-nested = "==0.5.1"
drf-yasg = "==1.17.0"
gevent = "==1.4.0"
gunicorn = "==19.9.0"
hashids = "==1.2.0"
jsonschema = "==3.1.1"
markdown = "==3.1.1"
nece = "==0.8.2"
pillow = "==6.2.1"
pygments = "==2.4.2"
python-json-logger = "==0.1.11"
pytz = "==2019.3"
raven = "==6.10.0"
rcssmin = "==1.0.6"
redis = "==3.3.11"
rules = "==2.1"
structlog = "==19.2.0"
wheel = "==0.33.6"
whitenoise = "==4.1.4"
# REF: https://github.com/eamigo86/graphene-django-extras/pull/42
# REF: https://github.com/eamigo86/graphene-django-extras/issues/43
#graphene-django-extras = {editable = true, git = "https://github.com/eamigo86/graphene-django-extras.git"}
#graphene-django-extras = {editable = true,git = "https://github.com/sportyspots/graphene-django-extras.git"}
graphene-django-extras = "==0.4.8"
# REF: https://github.com/flavors/django-graphql-geojson/issues/1
#graphene-django = { git = "https://github.com/graphql-python/graphene-django.git@master" }
graphene-django = "==2.6.0"
"iso8601" = "*"
pendulum = "==2.0.5"
wagtail = "==2.6.3"
# NOTE: Forced dependency because of pipenv installation errors
sqlparse = "==0.3.0"
django-push-notifications = "==1.6.1"
kombu = "==4.5.0"
[dev-packages]
"flake8" = "==3.7.9"
ansible = "==2.6.4"
awscli = "==1.16.269"
black = "==19.10b0"
coreapi = "==2.3.3"
coreapi-cli = "==1.0.9"
coverage = "==4.5.4"
django-coverage-plugin = "==1.6.0"
django-debug-toolbar = "==2.0"
django-test-plus = "==1.3.1"
docopt = "==0.6.2"
fabric = "==2.5.0"
factory-boy = "==2.12.0"
googlemaps = "==3.1.4"
ipdb = "==0.12.2"
mock = "==3.0.5"
pytest-django = "==3.6.0"
requests = "==2.22.0"
scrapy = "==1.8.0"
sphinx = "==2.2.1"
werkzeug = "==0.16.0"
# awsebcli = "*"
# NOTE: Disable pytest-sugar till the following issues are fixed
# REF: https://github.com/pydanny/cookiecutter-django/pull/1472
# REF: https://github.com/pytest-dev/pytest/issues/3170
# pytest-sugar = "==0.9.0"
[requires]
python_version = "3.6"
[pipenv]
"allow_prereleases" = true
<file_sep>import * as Raphael from '../../node_modules/raphael/dev/raphael.amd.js';
export { Raphael };
<file_sep>FROM python:3.6.4
# TODO: see below, for non-root user
# REF: https://github.com/docker-library/redis/blob/master/4.0/Dockerfile
# REF: https://github.com/docker-library/postgres/blob/master/10/Dockerfile
#The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build
# command using the --build-arg <varname>=<value> flag.
#The ENV instruction sets the environment variable <key> to the value <value>.
#The environment variables set using ENV will persist when a container is run from the resulting image.
# git log -1 --format="%H"
ARG GIT_COMMIT=unknown
# Use label schema to annotate the Dockerfile (http://label-schema.org/rc1/)
LABEL org.label-schema.schema-version="1.0.0-rc.1" \
org.label-schema.name="sportyspots" \
org.label-schema.description="Discover sporty spots near you." \
org.label-schema.vcs-url="https://github.com/SportySpots/seedorf" \
org.label-schema.version="0.1.0" \
org.label-schema.vcs-ref=$GIT_COMMIT \
org.label-schema.build-date="2017-07-01T00:00:00.00Z" \
org.label-schema.vendor="SportySpots" \
org.label-schema.url="https://sportyspots.com" \
org.label-schema.usage="N/A e.g.:/usr/doc/app-usage.txt" \
org.label-schema.docker.cmd="docker run -d -p 8000:8000 -v config.json:/etc/config.json myapp" \
org.label-schema.docker.cmd.devel="docker run -d -p 8000:8000 -e ENV=DEV myapp" \
org.label-schema.docker.cmd.test="docker run sportyspots" \
org.label-schema.docker.debug="docker exec -it sportyspots /bin/bash" \
org.label-schema.docker.cmd.help="docker exec -it sportyspots /bin/bash --help" \
org.label-schema.docker.params="NO_THREADS=integer number of threads to launch"
ENV DEBIAN_FRONTEND=noninteractive \
PYTHONUNBUFFERED=1
RUN groupadd -r django \
&& useradd -r -g django django
RUN apt-get update \
&& apt-get install --assume-yes --quiet --no-install-recommends \
binutils \
libproj-dev \
proj-bin \
proj-data \
python3-pyproj \
gdal-bin \
python-gdal \
libgeoip1 \
libgeos-dev \
&& rm --recursive --force /var/lib/apt/lists/* \
&& apt-get --assume-yes autoclean
# Pipfile.lock has to be pulled and installed here, otherwise caching won't work
COPY Pipfile.lock /Pipfile.lock
RUN pip install --upgrade pip && \
pip install pipenv==9.0.2 && \
pipenv install --deploy --system --three --ignore-pipfile
COPY ./compose/local/django/entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
RUN chown django /entrypoint.sh
COPY ./compose/local/django/start.sh /start.sh
RUN chmod +x /start.sh
RUN chown django /start.sh
COPY ./compose/local/django/celery/worker/start.sh /start-celeryworker.sh
RUN chmod +x /start-celeryworker.sh
COPY ./compose/local/django/celery/beat/start.sh /start-celerybeat.sh
RUN chmod +x /start-celerybeat.sh
COPY . /app
RUN chown -R django /app
USER django
WORKDIR /app
EXPOSE 8000
VOLUME ["/app"]
CMD ["/start.sh"]
ENTRYPOINT ["/entrypoint.sh"]
<file_sep>from django.db.models import Q
from django_filters import rest_framework as filters
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework_gis.filters import DistanceToPointFilter
from seedorf.games.serializers import GameSpotNestedSerializer
from seedorf.locations.models import Address
from seedorf.locations.serializers import AddressSerializer
from seedorf.utils.permissions import IsAdminOrReadOnly
from seedorf.utils.regex import UUID as REGEX_UUID
from .filters import SpotFilter
from .models import Spot, SpotAmenity, SpotImage, SpotOpeningTime
from .serializers import AmenitySerializer, ImageSerializer, OpeningTimeSerializer, SpotSerializer
class SpotViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows spots to be viewed or edited.
"""
queryset = Spot.objects.filter(deleted_at=None)
serializer_class = SpotSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
# TODO: In the future, every user can create an adhoc spot
permission_classes = (IsAdminOrReadOnly,)
distance_filter_field = "address__point"
distance_filter_convert_meters = True
filter_backends = (filters.DjangoFilterBackend, DistanceToPointFilter)
filter_class = SpotFilter
class SpotAddressNestedViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows spot address to be viewed or edited.
"""
serializer_class = AddressSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
# TODO: In the future, every user can create an adhoc spot
permission_classes = (IsAdminOrReadOnly,)
def get_queryset(self):
spot_uuid = self.kwargs["spot_uuid"]
return Address.objects.filter(spot__uuid=spot_uuid)
class SpotSportOpeningTimesNestedViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows spot opening times to be viewed or edited
"""
serializer_class = OpeningTimeSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
permission_classes = (IsAdminOrReadOnly,)
def get_queryset(self):
spot_uuid = self.kwargs["spot_uuid"]
sport_uuid = self.kwargs["sport_uuid"]
return SpotOpeningTime.objects.filter(spot__uuid=spot_uuid, sport__uuid=sport_uuid)
class SpotSportAmenitesNestedViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows spot amenities belonging to a sport to be viewed or edited
"""
serializer_class = AmenitySerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
permission_classes = (IsAdminOrReadOnly,)
def get_queryset(self):
spot_uuid = self.kwargs["spot_uuid"]
sport_uuid = self.kwargs["sport_uuid"]
return SpotAmenity.objects.filter(spot__uuid=spot_uuid, sport__uuid=sport_uuid)
class SpotSportImagesNestedViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows images of a sport on a spot to be viewed or edited
"""
serializer_class = ImageSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
permission_classes = (IsAdminOrReadOnly,)
def get_queryset(self):
spot_uuid = self.kwargs["spot_uuid"]
sport_uuid = self.kwargs["sport_uuid"]
spot = Q(spot__uuid=spot_uuid)
sport = Q(sport__uuid=sport_uuid)
return SpotImage.objects.filter(sport & spot)
class GameSpotNestedViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows nested spot to be viewed or edited per game.
"""
serializer_class = GameSpotNestedSerializer
lookup_field = "uuid"
lookup_value_regex = REGEX_UUID
# TODO: In the future, every user can create an adhoc spot
permission_classes = (IsAuthenticatedOrReadOnly,)
def get_queryset(self):
game_uuid = self.kwargs["game_uuid"]
return Spot.objects.filter(spot_games__uuid=game_uuid)
<file_sep>require('../../node_modules/fullcalendar/dist/locale-all.js');
<file_sep># Generated by Django 2.1.2 on 2019-03-09 23:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("users", "0007_alter_magicloginlink")]
operations = [
migrations.AlterField(
model_name="userprofile",
name="language",
field=models.CharField(
choices=[("en", "English"), ("nl", "Dutch"), ("es", "Spanish")],
default="en",
max_length=25,
verbose_name="Languages",
),
)
]
<file_sep>import uuid
import warnings
from calendar import timegm
from datetime import datetime
from rest_framework_jwt.compat import get_username, get_username_field
from rest_framework_jwt.settings import api_settings
def jwt_payload_handler(user):
username_field = get_username_field()
username = get_username(user)
warnings.warn("The following fields will be removed in the future: " "`email` and `user_id`. ", DeprecationWarning)
payload = {
"user_id": user.pk,
"uuid": str(user.uuid),
"username": username,
"exp": datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA,
}
if hasattr(user, "email"):
payload["email"] = user.email
if isinstance(user.pk, uuid.UUID):
payload["user_id"] = str(user.pk)
payload[username_field] = username
# Include original issued at time for a brand new token,
# to allow token refresh
if api_settings.JWT_ALLOW_REFRESH:
payload["orig_iat"] = timegm(datetime.utcnow().utctimetuple())
if api_settings.JWT_AUDIENCE is not None:
payload["aud"] = api_settings.JWT_AUDIENCE
if api_settings.JWT_ISSUER is not None:
payload["iss"] = api_settings.JWT_ISSUER
return payload
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-06-17 11:14
from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("locations", "0002_auto_20180602_2110")]
operations = [
migrations.AddField(
model_name="address",
name="point",
field=django.contrib.gis.db.models.fields.PointField(
help_text="Lat/Lng Point", null=True, srid=4326, verbose_name="Location"
),
)
]
<file_sep>from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from seedorf.chatkit.client import create_client
from seedorf.games.models import Game
@receiver(pre_save, sender=Game)
def update_share_link(sender, instance: Game, **kwargs):
try:
instance.share_link = instance.create_share_link()
except Exception as e:
pass
def create_chatkit_room_for_game(game: Game):
client = create_client()
client.token = client.create_admin_readonly_user_token()
room = client.create_room(name=f"game/{str(game.uuid)}")
game.chatkit_room_id = int(room["id"])
game.save()
@receiver(post_save, sender=Game)
def create_chatkit_room(sender, instance: Game, created, **kwargs):
if created:
create_chatkit_room_for_game(instance)
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-04-29 19:27
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.utils.timezone
import nece.managers
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Sport",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("uuid", models.UUIDField(default=uuid.uuid4, editable=False, verbose_name="Unique Identifier")),
(
"created_at",
models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name="Created At"),
),
("modified_at", models.DateTimeField(auto_now=True, verbose_name="Modified At")),
("deleted_at", models.DateTimeField(blank=True, editable=False, null=True, verbose_name="Deleted At")),
("translations", django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True)),
(
"category",
models.CharField(
choices=[
("basketball", "Basketball"),
("beach_volleyball", "Beach Volleyball"),
("bootcamp", "Bootcamp"),
("boules", "Boules"),
("fitness", "Fitness"),
("others", "Others"),
("skating", "Skating"),
("soccer", "Soccer"),
("tennis", "Tennis"),
],
default="others",
help_text="Name of the main category of the sport (e.g. Soccer).",
max_length=50,
verbose_name="Sport Category",
),
),
(
"name",
models.CharField(
help_text="Name of the sub category of the sport (e.g. Soccer 5x5).",
max_length=255,
unique=True,
verbose_name="Sport Name",
),
),
(
"description",
models.TextField(blank=True, default="", max_length=4096, verbose_name="Sport Description"),
),
],
options={"verbose_name": "Sport", "verbose_name_plural": "Sports", "ordering": ("category", "name")},
bases=(models.Model, nece.managers.TranslationMixin),
)
]
<file_sep>from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.measure import D
from django_filters import rest_framework as filters
from django.utils import timezone
from datetime import timedelta
from .models import Game, RsvpStatus
class GameWebFilter(filters.FilterSet):
location = filters.CharFilter(field_name="spot__address__point", method="filter_by_distance")
class Meta:
model = Game
fields = {"sport__category": ["exact"], "start_time": ["gte"]}
# @property
# def qs(self):
# start_time = timezone.now() - timedelta(hours=1)
# parent = super().qs
# return parent.filter(start_time__gte=start_time)
# REF: https://django-filter.readthedocs.io/en/master/ref/filters.html#method
@staticmethod
def filter_by_distance(queryset, name, value):
# TODO: Validate distance is integer, and the lat and lng values are valid
distance, lat, lng = value.split(":")
# REF: https://docs.djangoproject.com/en/2.0/ref/contrib/gis/db-api/#distance-lookups
ref_location = GEOSGeometry(f"POINT({lng} {lat})", srid=4326)
lookup = f"{name}__distance_lte"
qs = queryset.filter(**{lookup: (ref_location, D(m=int(distance)))})
return qs
class GameFilter(filters.FilterSet):
distance = filters.CharFilter(field_name="spot__address__point", method="filter_by_distance")
class Meta:
model = Game
fields = {
"organizer__uuid": ["exact"],
"sport__uuid": ["exact"],
"sport__category": ["exact"],
"spot__uuid": ["exact"],
"spot__name": ["exact", "icontains"],
"name": ["exact", "icontains"],
"start_time": ["lte", "gte"],
"end_time": ["lte", "gte"],
"rsvp_open_time": ["lte", "gte"],
"rsvp_close_time": ["lte", "gte"],
"rsvp_closed": ["exact"],
"status": ["exact"],
"invite_mode": ["exact"],
"capacity": ["lte", "gte"],
"show_remaining": ["exact"],
"is_listed": ["exact"],
"is_shareable": ["exact"],
"is_featured": ["exact"],
}
# REF: https://django-filter.readthedocs.io/en/master/ref/filters.html#method
@staticmethod
def filter_by_distance(queryset, name, value):
# TODO: Validate distance is integer, and the lat and lng values are valid
distance, lat, lng = value.split(":")
# REF: https://docs.djangoproject.com/en/2.0/ref/contrib/gis/db-api/#distance-lookups
ref_location = GEOSGeometry(f"POINT({lng} {lat})", srid=4326)
lookup = f"{name}__distance_lte"
return queryset.filter(**{lookup: (ref_location, D(m=int(distance)))})
class RsvpStatusFilter(filters.FilterSet):
class Meta:
model = RsvpStatus
fields = {"game__uuid": ["exact"], "user__uuid": ["exact"], "status": ["exact"]}
<file_sep>from rest_framework import serializers
from .models import Sport
class SportSerializer(serializers.ModelSerializer):
class Meta:
model = Sport
fields = ("uuid", "category", "name", "description", "created_at", "modified_at")
read_only_fields = ("uuid", "category", "created_at", "modified_at")
<file_sep>$(function() {
// Navbar
//
var navbarScrollThreshold = 20;
var navbarBreakpoint = 992;
// Custom classes that will be applied depending on page scrollTop value
var navbarCustomClasses = {
// when user is on the top of the page
default: {},
// when page scrollTop value > navbarScrollThreshold
alt: {}
};
// Set custom classes depending on landing variant
if ($('html').hasClass('landing-1') || $('html').hasClass('landing-3')) {
navbarCustomClasses = {
default: {
variant: 'bg-white',
classes: 'pt-lg-4'
},
alt: {
variant: 'bg-white',
classes: 'py-1'
}
};
} else if ($('html').hasClass('landing-2') || $('html').hasClass('landing-4')) {
navbarCustomClasses = {
default: {
variant: 'navbar-dark',
classes: 'pt-lg-4'
},
alt: {
variant: 'bg-dark',
classes: 'py-1'
}
};
}
// Navbar scroll behaviour
//
var $navbar = $('.landing-navbar');
var $navbarCollapse = $('#landing-navbar-collapse');
$(document).on('scroll', function(e) {
var scrollTop = $(document).scrollTop();
if (scrollTop > navbarScrollThreshold && !$navbar.hasClass('landing-navbar-alt')) {
$navbar
.addClass('landing-navbar-alt')
.removeClass(navbarCustomClasses.default.variant + ' ' + navbarCustomClasses.default.classes)
.addClass(navbarCustomClasses.alt.variant + ' ' + navbarCustomClasses.alt.classes)
.find('> div')
.removeClass('container-fluid')
.addClass('container');
} else if (scrollTop <= navbarScrollThreshold && $navbar.hasClass('landing-navbar-alt')) {
$navbar.removeClass('landing-navbar-alt')
.addClass(navbarCustomClasses.default.classes)
.removeClass(navbarCustomClasses.alt.classes)
.find('> div')
.addClass('container-fluid')
.removeClass('container');
}
});
$navbarCollapse.on('show.bs.collapse hidden.bs.collapse', function(e) {
if ($navbar.hasClass('landing-navbar-alt')) return;
$navbar[e.type === 'show' ? 'removeClass' : 'addClass'](
navbarCustomClasses.default.variant
);
$navbar[e.type === 'show' ? 'addClass' : 'removeClass'](
navbarCustomClasses.alt.variant
);
});
$(window).on('resize', function() {
if ($navbar.hasClass('landing-navbar-alt')) return;
var sm = $(this).outerWidth() < navbarBreakpoint;
var alt = $navbar.hasClass(navbarCustomClasses.alt.variant);
if (sm && !alt && $navbarCollapse.hasClass('show')) {
$navbar
.removeClass(navbarCustomClasses.default.variant)
.addClass(navbarCustomClasses.alt.variant);
} else if (!sm && alt) {
$navbar
.removeClass(navbarCustomClasses.alt.variant)
.addClass(navbarCustomClasses.default.variant);
}
});
// Anchor links
//
$('body').on('click', '.anchor-link', function(e) {
e.preventDefault();
$("html, body").stop().animate({
scrollTop: Math.round($(this.getAttribute('href')).offset().top) + 'px'
}, 500);
});
// Main slider
//
$('#landing-slider').each(function() {
new Swiper(this, {
autoHeight: true,
speed: 1000,
followFinger: false,
threshold: 50,
preventClicks: true,
navigation: {
nextEl: '#landing-slider-next',
prevEl: '#landing-slider-prev'
}
});
});
$('#landing-slider-parallax').each(function() {
new Swiper(this, {
parallax: true,
autoHeight: true,
speed: 1000,
followFinger: false,
threshold: 50,
preventClicks: true,
autoplay: true,
navigation: {
nextEl: '#landing-slider-next',
prevEl: '#landing-slider-prev'
},
pagination:{
el: '.swiper-pagination',
clickable: true,
}
});
});
// Introducing video
//
plyr.default.setup(document.querySelectorAll(".plyr-video"));
$('#landing-video').each(function() {
plyr.setup(this, {
tooltips: {
controls: false,
seek: true
}
})[0];
});
// App preview
//
$('#landing-preview-slider').each(function() {
new Swiper(this, {
slidesPerView: 3,
spaceBetween: 0,
threshold: 50,
speed: 400,
centeredSlides: true,
slideToClickedSlide: true,
breakpoints: {
992: {
slidesPerView: 1,
spaceBetween: 20
}
},
pagination: {
el: '.swiper-pagination',
clickable: true
}
});
});
// Reviews
//
$('#landing-testimonials-slider').each(function() {
new Swiper(this, {
navigation: {
nextEl: '#landing-testimonials-slider-next',
prevEl: '#landing-testimonials-slider-prev'
}
});
});
// Logos
//
$('#landing-logos-slider').each(function() {
new Swiper(this, {
slidesPerView: 8,
spaceBetween: 30,
breakpoints: {
1200: {
slidesPerView: 7,
},
992: {
slidesPerView: 6,
spaceBetween: 20,
},
768: {
slidesPerView: 4,
spaceBetween: 10,
},
576: {
spaceBetween: 0,
},
480: {
slidesPerView: 3
},
380: {
slidesPerView: 2
}
},
navigation: {
nextEl: '#landing-logos-slider-next',
prevEl: '#landing-logos-slider-prev'
}
});
});
});
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-06-02 21:10
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("games", "0003_game_description")]
operations = [
migrations.AlterModelOptions(
name="game", options={"ordering": ("-created_at",), "verbose_name": "Game", "verbose_name_plural": "Games"}
)
]
<file_sep>import factory
from ..models import Address
class AddressFactory(factory.django.DjangoModelFactory):
raw_address = factory.Faker("address")
lat = factory.Faker("latitude")
lng = factory.Faker("longitude")
class Meta:
model = Address
<file_sep># Generated by Django 2.1.2 on 2019-01-09 15:45
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import seedorf.users.models
import uuid
class Migration(migrations.Migration):
dependencies = [("users", "0005_auto_20181117_1312")]
operations = [
migrations.CreateModel(
name="MagicLoginLink",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("uuid", models.UUIDField(default=uuid.uuid4, editable=False, verbose_name="Unique Identifier")),
(
"created_at",
models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name="Created At"),
),
("modified_at", models.DateTimeField(auto_now=True, verbose_name="Modified At")),
("deleted_at", models.DateTimeField(blank=True, editable=False, null=True, verbose_name="Deleted At")),
("token", models.CharField(default="<PASSWORD>", max_length=32, verbose_name="Token")),
("short_link", models.CharField(max_length=50, verbose_name="Link")),
(
"user",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="magic_link",
to=settings.AUTH_USER_MODEL,
verbose_name="Magic login link",
),
),
],
options={"abstract": False},
)
]
<file_sep>import * as Ladda from '../../node_modules/ladda/js/ladda.js';
export { Ladda };
<file_sep>import uuid
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from hashids import Hashids
class BasePropertiesModel(models.Model):
uuid = models.UUIDField(
blank=False, default=uuid.uuid4, editable=False, null=False, verbose_name=_("Unique Identifier")
)
created_at = models.DateTimeField(
blank=False, default=timezone.now, editable=False, null=False, verbose_name=_("Created At")
)
modified_at = models.DateTimeField(
auto_now=True, blank=False, editable=False, null=False, verbose_name=_("Modified At")
)
deleted_at = models.DateTimeField(blank=True, editable=False, null=True, verbose_name=_("Deleted At"))
@property
def hash_slug(self):
hasher = Hashids(salt=settings.SECRET_KEY, min_length=6)
return hasher.encode(self.id)
@classmethod
def reverse_hash_slug(cls, hash_slug):
hasher = Hashids(salt=settings.SECRET_KEY, min_length=6)
return hasher.decode(hash_slug)
class Meta:
abstract = True
<file_sep>import style from './_theme-settings/_theme-settings.scss'
import markup from './_theme-settings/_theme-settings.html'
import themeItemMarkup from './_theme-settings/_theme-settings-theme-item.html'
import bgItemMarkup from './_theme-settings/_theme-settings-bg-item.html'
const AVAILABLE_THEMES = [
{ name: 'theme-air', title: 'Air', colors: { primary: '#3c97fe', navbar: '#f8f8f8', sidenav: '#f8f8f8' } },
{ name: 'theme-corporate', title: 'Corporate', colors: { primary: '#26B4FF', navbar: '#fff', sidenav: '#2e323a' } },
{ name: 'theme-cotton', title: 'Сotton', colors: { primary: '#e84c64', navbar: '#ffffff', sidenav: '#ffffff' } },
{ name: 'theme-gradient', title: 'Gradient', colors: { primary: '#775cdc', navbar: '#ffffff', sidenav: 'linear-gradient(to top, #4e54c8, #8c55e4)' } },
{ name: 'theme-paper', title: 'Paper', colors: { primary: '#17b3a3', navbar: '#ffffff', sidenav: '#ffffff' } },
{ name: 'theme-shadow', title: 'Shadow', colors: { primary: '#7b83ff', navbar: '#f8f8f8', sidenav: '#ececf9' } },
{ name: 'theme-soft', title: 'Soft', colors: { primary: '#1cbb84', navbar: '#39517b', sidenav: '#ffffff' } },
{ name: 'theme-sunrise', title: 'Sunrise', colors: { primary: '#fc5a5c', navbar: '#222222', sidenav: '#ffffff' } },
{ name: 'theme-twitlight', title: 'Twitlight', colors: { primary: '#4c84ff', navbar: '#343c44', sidenav: '#3f4853' } },
{ name: 'theme-vibrant', title: 'Vibrant', colors: { primary: '#fc5a5c', navbar: '#f8f8f8', sidenav: '#222222' } },
]
const DEFAULT_THEME = 1
const CSS_FILENAME_PATTERN = '%name%.css'
const CONTROLS = [ 'rtl', 'material', 'layoutPosition', 'layoutNavbarFixed', 'layoutFooterFixed', 'layoutReversed', 'navbarBg', 'sidenavBg', 'footerBg', 'themes' ]
const NAVBAR_BGS = [ 'navbar-theme', 'primary', 'primary-dark navbar-dark', 'primary-darker navbar-dark', 'secondary', 'secondary-dark navbar-dark', 'secondary-darker navbar-dark', 'success', 'success-dark navbar-dark', 'success-darker navbar-dark', 'info', 'info-dark navbar-dark', 'info-darker navbar-dark', 'warning', 'warning-dark navbar-light', 'warning-darker navbar-light', 'danger', 'danger-dark navbar-dark', 'danger-darker navbar-dark', 'dark', 'white', 'light', 'lighter' ]
const DEFAULT_NAVBAR_BG = 'navbar-theme'
const SIDENAV_BGS = [ 'sidenav-theme', 'primary', 'primary-dark sidenav-dark', 'primary-darker sidenav-dark', 'secondary', 'secondary-dark sidenav-dark', 'secondary-darker sidenav-dark', 'success', 'success-dark sidenav-dark', 'success-darker sidenav-dark', 'info', 'info-dark sidenav-dark', 'info-darker sidenav-dark', 'warning', 'warning-dark sidenav-light', 'warning-darker sidenav-light', 'danger', 'danger-dark sidenav-dark', 'danger-darker sidenav-dark', 'dark', 'white', 'light', 'lighter' ]
const DEFAULT_SIDENAV_BG = 'sidenav-theme'
const FOOTER_BGS = [ 'footer-theme', 'primary', 'primary-dark footer-dark', 'primary-darker footer-dark', 'secondary', 'secondary-dark footer-dark', 'secondary-darker footer-dark', 'success', 'success-dark footer-dark', 'success-darker footer-dark', 'info', 'info-dark footer-dark', 'info-darker footer-dark', 'warning', 'warning-dark footer-light', 'warning-darker footer-light', 'danger', 'danger-dark footer-dark', 'danger-darker footer-dark', 'dark', 'white', 'light', 'lighter' ]
const DEFAULT_FOOTER_BG = 'footer-theme'
class ThemeSettings {
constructor({ cssPath, themesPath, cssFilenamePattern, controls, sidenavBgs, defaultSidenavBg, navbarBgs, defaultNavbarBg, footerBgs, defaultFooterBg, availableThemes, defaultTheme, pathResolver, onSettingsChange }) {
if (this._ssr) return
if (!window.layoutHelpers) throw new Error('window.layoutHelpers required.')
this.settings = {}
this.settings.cssPath = cssPath
this.settings.themesPath = themesPath
this.settings.cssFilenamePattern = cssFilenamePattern || CSS_FILENAME_PATTERN
this.settings.navbarBgs = navbarBgs || NAVBAR_BGS
this.settings.defaultNavbarBg = defaultNavbarBg || DEFAULT_NAVBAR_BG
this.settings.sidenavBgs = sidenavBgs || SIDENAV_BGS
this.settings.defaultSidenavBg = defaultSidenavBg || DEFAULT_SIDENAV_BG
this.settings.footerBgs = footerBgs || FOOTER_BGS
this.settings.defaultFooterBg = defaultFooterBg || DEFAULT_FOOTER_BG
this.settings.availableThemes = availableThemes || AVAILABLE_THEMES
this.settings.defaultTheme = this.settings.availableThemes[typeof defaultTheme !== 'undefined' ? defaultTheme : DEFAULT_THEME]
this.settings.controls = controls || CONTROLS
this.pathResolver = pathResolver || (p => p)
this.settings.onSettingsChange = () => {}
this._loadSettings()
this._listeners = []
this._controls = {}
this._initDirection()
this._initStyle()
this._initTheme()
this.setLayoutPosition(this.settings.layoutPosition, false)
this.setLayoutNavbarFixed(this.settings.layoutNavbarFixed, false)
this.setLayoutFooterFixed(this.settings.layoutFooterFixed, false)
this.setLayoutReversed(this.settings.layoutReversed, false)
this._setup()
this._waitForNavs()
}
setRtl(rtl) {
if (!this._hasControls('rtl')) return
this._setSetting('Rtl', String(rtl))
window.location.reload()
}
setMaterial(material) {
if (!this._hasControls('material')) return
this._setSetting('Material', String(material))
window.location.reload()
}
setTheme(themeName, updateStorage = true, cb = null) {
if (!this._hasControls('themes')) return
let allowedTheme = false
for (let i = 0, l = this.settings.availableThemes.length; i < l; i++) {
if (this.settings.availableThemes[i].name === themeName) allowedTheme = true
}
if (!allowedTheme) return
this.settings.theme = this._getThemeByFile(themeName)
if (updateStorage) this._setSetting('Theme', themeName)
const themeUrl = this.pathResolver(
this.settings.themesPath + this.settings.cssFilenamePattern.replace('%name%', themeName + (this.settings.material ? '-material' : ''))
)
this._loadStylesheets(
{ [themeUrl]: document.querySelector('.theme-settings-theme-css') },
cb || (() => {})
)
if (updateStorage) this.settings.onSettingsChange(this.settings)
}
setLayoutPosition(pos, updateStorage = true) {
if (!this._hasControls('layoutPosition')) return
if (pos !== 'static' && pos !== 'static-offcanvas' && pos !== 'fixed' && pos !== 'fixed-offcanvas') return
this.settings.layoutPosition = pos
if (updateStorage) this._setSetting('LayoutPosition', pos)
window.layoutHelpers.setPosition(
pos === 'fixed' || pos === 'fixed-offcanvas',
pos === 'static-offcanvas' || pos === 'fixed-offcanvas'
)
if (updateStorage) this.settings.onSettingsChange(this.settings)
}
setLayoutNavbarFixed(fixed, updateStorage = true) {
if (!this._hasControls('layoutNavbarFixed')) return
this.settings.layoutNavbarFixed = fixed
if (updateStorage) this._setSetting('FixedNavbar', fixed)
window.layoutHelpers.setNavbarFixed(fixed)
if (updateStorage) this.settings.onSettingsChange(this.settings)
}
setLayoutFooterFixed(fixed, updateStorage = true) {
if (!this._hasControls('layoutFooterFixed')) return
this.settings.layoutFooterFixed = fixed
if (updateStorage) this._setSetting('FixedFooter', fixed)
window.layoutHelpers.setFooterFixed(fixed)
if (updateStorage) this.settings.onSettingsChange(this.settings)
}
setLayoutReversed(reversed, updateStorage = true) {
if (!this._hasControls('layoutReversed')) return
this.settings.layoutReversed = reversed
if (updateStorage) this._setSetting('LayoutReversed', reversed)
window.layoutHelpers.setReversed(reversed)
if (updateStorage) this.settings.onSettingsChange(this.settings)
}
setNavbarBg(bg, updateStorage = true, _container = document) {
if (!this._hasControls('navbarBg')) return
if (this.settings.navbarBgs.indexOf(bg) === -1) return
this.settings.navbarBg = bg
if (updateStorage) this._setSetting('NavbarBg', bg)
const navbar = _container.querySelector('.layout-navbar.navbar, .layout-navbar .navbar')
if (!navbar) return
navbar.className = navbar.className.replace(/^bg\-[^ ]+| bg\-[^ ]+/ig, '')
navbar.classList.remove('navbar-light')
navbar.classList.remove('navbar-dark')
const classes = bg.split(' ')
navbar.classList.add(`bg-${classes[0]}`)
for (let i = 1, l = classes.length; i < l; i++) navbar.classList.add(classes[i])
if (updateStorage) this.settings.onSettingsChange(this.settings)
}
setSidenavBg(bg, updateStorage = true, _container = document) {
if (!this._hasControls('sidenavBg')) return
if (this.settings.sidenavBgs.indexOf(bg) === -1) return
this.settings.sidenavBg = bg
if (updateStorage) this._setSetting('SidenavBg', bg)
const sidenav = _container.querySelector('.layout-sidenav.sidenav, .layout-sidenav .sidenav, .layout-sidenav-horizontal.sidenav, .layout-sidenav-horizontal .sidenav')
if (!sidenav) return
sidenav.className = sidenav.className.replace(/^bg\-[^ ]+| bg\-[^ ]+/ig, '')
sidenav.classList.remove('sidenav-light')
sidenav.classList.remove('sidenav-dark')
let classes = bg.split(' ')
if (sidenav.classList.contains('sidenav-horizontal')) {
classes = classes.join(' ').replace(' sidenav-dark', '').replace(' sidenav-light', '').split(' ')
classes[0] = classes[0].replace(/-darke?r?$/, '')
}
sidenav.classList.add(`bg-${classes[0]}`)
for (let i = 1, l = classes.length; i < l; i++) sidenav.classList.add(classes[i])
if (updateStorage) this.settings.onSettingsChange(this.settings)
}
setFooterBg(bg, updateStorage = true, _container = document) {
if (!this._hasControls('footerBg')) return
if (this.settings.footerBgs.indexOf(bg) === -1) return
this.settings.footerBg = bg
if (updateStorage) this._setSetting('FooterBg', bg)
const footer = _container.querySelector('.layout-footer.footer, .layout-footer .footer')
if (!footer) return
footer.className = footer.className.replace(/^bg\-[^ ]+| bg\-[^ ]+/ig, '')
footer.classList.remove('footer-light')
footer.classList.remove('footer-dark')
const classes = bg.split(' ')
footer.classList.add(`bg-${classes[0]}`)
for (let i = 1, l = classes.length; i < l; i++) footer.classList.add(classes[i])
if (updateStorage) this.settings.onSettingsChange(this.settings)
}
update() {
if (this._ssr) return
const hasNavbar = !!document.querySelector('.layout-navbar')
const hasSidenav = !!document.querySelector('.layout-sidenav')
const hasHorizontalSidenav = !!document.querySelector('.layout-sidenav-horizontal.sidenav, .layout-sidenav-horizontal .sidenav')
const isLayout1 = !!document.querySelector('.layout-wrapper.layout-1')
const hasFooter = !!document.querySelector('.layout-footer')
if (this._controls.layoutReversed) {
if (!hasSidenav) {
this._controls.layoutReversed.setAttribute('disabled', 'disabled')
this._controls.layoutReversedW.classList.add('disabled')
} else {
this._controls.layoutReversed.removeAttribute('disabled')
this._controls.layoutReversedW.classList.remove('disabled')
}
}
if (this._controls.layoutNavbarFixed) {
if (!hasNavbar) {
this._controls.layoutNavbarFixed.setAttribute('disabled', 'disabled')
this._controls.layoutNavbarFixedW.classList.add('disabled')
} else {
this._controls.layoutNavbarFixed.removeAttribute('disabled')
this._controls.layoutNavbarFixedW.classList.remove('disabled')
}
}
if (this._controls.layoutFooterFixed) {
if (!hasFooter) {
this._controls.layoutFooterFixed.setAttribute('disabled', 'disabled')
this._controls.layoutFooterFixedW.classList.add('disabled')
} else {
this._controls.layoutFooterFixed.removeAttribute('disabled')
this._controls.layoutFooterFixedW.classList.remove('disabled')
}
}
if (this._controls.layoutPosition) {
if (!hasSidenav) {
this._controls.layoutPosition.querySelector('[value="static-offcanvas"]').setAttribute('disabled', 'disabled')
this._controls.layoutPosition.querySelector('[value="fixed-offcanvas"]').setAttribute('disabled', 'disabled')
} else {
this._controls.layoutPosition.querySelector('[value="static-offcanvas"]').removeAttribute('disabled')
this._controls.layoutPosition.querySelector('[value="fixed-offcanvas"]').removeAttribute('disabled')
}
if ((!hasNavbar && !hasSidenav) || (!hasSidenav && !isLayout1)) {
this._controls.layoutPosition.setAttribute('disabled', 'disabled')
} else {
this._controls.layoutPosition.removeAttribute('disabled')
}
}
if (this._controls.navbarBgWInner) {
if (!hasNavbar) {
this._controls.navbarBgWInner.setAttribute('disabled', 'disabled')
} else {
this._controls.navbarBgWInner.removeAttribute('disabled')
}
}
if (this._controls.sidenavBgWInner) {
const items = Array.prototype.slice.call(document.querySelectorAll('.theme-settings-sidenavBg-inner .theme-settings-bg-item'))
if (!hasSidenav && !hasHorizontalSidenav) {
items.forEach(item => {
item.classList.add('disabled')
item.querySelector('input').setAttribute('disabled', 'disabled')
})
} else {
items.forEach(item => {
item.classList.remove('disabled')
item.querySelector('input').removeAttribute('disabled')
})
if (hasHorizontalSidenav) items.forEach(item => {
if (!/-darke?r?/.test(item.className) || /bg-dark/.test(item.className)) return
item.classList.add('disabled')
item.querySelector('input').setAttribute('disabled', 'disabled')
})
}
}
if (this._controls.footerBgWInner) {
if (!hasFooter) {
this._controls.footerBgWInner.setAttribute('disabled', 'disabled')
} else {
this._controls.footerBgWInner.removeAttribute('disabled')
}
}
}
updateNavbarBg(_container = document) {
this.setNavbarBg(this.settings.navbarBg, false, _container)
}
updateSidenavBg(_container = document) {
this.setSidenavBg(this.settings.sidenavBg, false, _container)
}
updateFooterBg(_container = document) {
this.setFooterBg(this.settings.footerBg, false, _container)
}
clearLocalStorage() {
if (this._ssr) return
this._setSetting('Theme', '')
this._setSetting('Rtl', '')
this._setSetting('Material', '')
this._setSetting('LayoutReversed', '')
this._setSetting('FixedNavbar', '')
this._setSetting('FixedFooter', '')
this._setSetting('LayoutPosition', '')
this._setSetting('NavbarBg', '')
this._setSetting('SidenavBg', '')
this._setSetting('FooterBg', '')
}
destroy() {
if (this._ssr) return
this._cleanup()
this.settings = null
this.container.parentNode.removeChild(this.container)
this.container = null
}
_loadSettings() {
const cl = document.documentElement.classList
const rtl = this._getSetting('Rtl')
const material = this._getSetting('Material')
const reversed = this._getSetting('LayoutReversed')
const fixedNavbar = this._getSetting('FixedNavbar')
const fixedFooter = this._getSetting('FixedFooter')
const navbarBg = this._getSetting('NavbarBg')
const sidenavBg = this._getSetting('SidenavBg')
const footerBg = this._getSetting('FooterBg')
const lPosition = this._getSetting('LayoutPosition')
let position
if (lPosition !== '' && ['static', 'static-offcanvas', 'fixed', 'fixed-offcanvas'].indexOf(lPosition) !== -1) {
position = lPosition
} else if (cl.contains('layout-offcanvas')) {
position = 'static-offcanvas'
} else if (cl.contains('layout-fixed')) {
position = 'fixed'
} else if (cl.contains('layout-fixed-offcanvas')) {
position = 'fixed-offcanvas'
} else {
position = 'static'
}
// Set settings
this.settings.rtl = rtl !== '' ? rtl === 'true' : document.documentElement.getAttribute('dir') === 'rtl'
this.settings.material = material !== '' ? material === 'true' : cl.contains('material-style')
this.settings.layoutPosition = position
this.settings.layoutReversed = reversed !== '' ? reversed === 'true' : cl.contains('layout-reversed')
this.settings.layoutNavbarFixed = fixedNavbar !== '' ? fixedNavbar === 'true' : cl.contains('layout-navbar-fixed')
this.settings.layoutFooterFixed = fixedFooter !== '' ? fixedFooter === 'true' : cl.contains('layout-footer-fixed')
this.settings.navbarBg = this.settings.navbarBgs.indexOf(navbarBg) !== -1 ? navbarBg : this.settings.defaultNavbarBg
this.settings.sidenavBg = this.settings.sidenavBgs.indexOf(sidenavBg) !== -1 ? sidenavBg : this.settings.defaultSidenavBg
this.settings.footerBg = this.settings.footerBgs.indexOf(footerBg) !== -1 ? footerBg : this.settings.defaultFooterBg
this.settings.theme = this._getThemeByFile(this._getSetting('Theme'))
// Filter options depending on available controls
if (!this._hasControls('rtl')) this.settings.rtl = document.documentElement.getAttribute('dir') === 'rtl'
if (!this._hasControls('material')) this.settings.material = cl.contains('material-style')
if (!this._hasControls('layoutPosition')) this.settings.layoutPosition = null
if (!this._hasControls('layoutReversed')) this.settings.layoutReversed = null
if (!this._hasControls('layoutNavbarFixed')) this.settings.layoutNavbarFixed = null
if (!this._hasControls('layoutFooterFixed')) this.settings.layoutFooterFixed = null
if (!this._hasControls('navbarBg')) this.settings.navbarBg = null
if (!this._hasControls('sidenavBg')) this.settings.sidenavBg = null
if (!this._hasControls('footerBg')) this.settings.footerBg = null
if (!this._hasControls('themes')) this.settings.theme = null
}
_setup(_container = document) {
this._cleanup()
this.container = this._getElementFromString(markup)
// Open btn
//
const openBtn = this.container.querySelector('.theme-settings-open-btn')
const openBtnCb = () => {
this.container.classList.add('theme-settings-open')
this.update()
if (this._updateInterval) clearInterval(this._updateInterval)
this._updateInterval = setInterval(() => {
this.update()
}, 1000)
}
openBtn.addEventListener('click', openBtnCb)
this._listeners.push([ openBtn, 'click', openBtnCb ])
// Close btn
//
const closeBtn = this.container.querySelector('.theme-settings-close-btn')
const closeBtnCb = () => {
this.container.classList.remove('theme-settings-open')
if (this._updateInterval) {
clearInterval(this._updateInterval)
this._updateInterval = null
}
}
closeBtn.addEventListener('click', closeBtnCb)
this._listeners.push([ closeBtn, 'click', closeBtnCb ])
// RTL
//
const rtlW = this.container.querySelector('.theme-settings-rtl')
if (!this._hasControls('rtl')) {
rtlW.parentNode.removeChild(rtlW)
} else {
const rtl = rtlW.querySelector('input')
if (this.settings.rtl) rtl.setAttribute('checked', 'checked')
const rtlCb = e => {
this._loadingState(true)
this.setRtl(e.target.checked)
}
rtl.addEventListener('change', rtlCb)
this._listeners.push([ rtl, 'change', rtlCb ])
}
// Material
//
const materialW = this.container.querySelector('.theme-settings-material')
if (!this._hasControls('material')) {
materialW.parentNode.removeChild(materialW)
} else {
const material = materialW.querySelector('input')
if (this.settings.material) material.setAttribute('checked', 'checked')
const materialCb = e => {
this._loadingState(true)
this.setMaterial(e.target.checked)
}
material.addEventListener('change', materialCb)
this._listeners.push([ material, 'change', materialCb ])
}
// Layout wrapper
//
const layoutW = this.container.querySelector('.theme-settings-layout')
if (!this._hasControls('layoutPosition layoutNavbarFixed layoutFooterFixed layoutReversed', true)) {
layoutW.parentNode.removeChild(layoutW)
} else {
// Position
//
const layoutPositionW = this.container.querySelector('.theme-settings-layoutPosition')
if (!this._hasControls('layoutPosition')) {
layoutPositionW.parentNode.removeChild(layoutPositionW)
} else {
this._controls.layoutPosition = layoutPositionW.querySelector('select')
this._controls.layoutPosition.value = this.settings.layoutPosition
const layoutPositionCb = e => this.setLayoutPosition(e.target.value)
this._controls.layoutPosition.addEventListener('change', layoutPositionCb)
this._listeners.push([ this._controls.layoutPosition, 'change', layoutPositionCb ])
}
// Navbar
//
this._controls.layoutNavbarFixedW = this.container.querySelector('.theme-settings-layoutNavbarFixed')
if (!this._hasControls('layoutNavbarFixed')) {
this._controls.layoutNavbarFixedW.parentNode.removeChild(this._controls.layoutNavbarFixedW)
} else {
this._controls.layoutNavbarFixed = this._controls.layoutNavbarFixedW.querySelector('input')
if (this.settings.layoutNavbarFixed) this._controls.layoutNavbarFixed.setAttribute('checked', 'checked')
const layoutNavbarFixedCb = e => this.setLayoutNavbarFixed(e.target.checked)
this._controls.layoutNavbarFixed.addEventListener('change', layoutNavbarFixedCb)
this._listeners.push([ this._controls.layoutNavbarFixed, 'change', layoutNavbarFixedCb ])
}
// Footer
//
this._controls.layoutFooterFixedW = this.container.querySelector('.theme-settings-layoutFooterFixed')
if (!this._hasControls('layoutFooterFixed')) {
this._controls.layoutFooterFixedW.parentNode.removeChild(this._controls.layoutFooterFixedW)
} else {
this._controls.layoutFooterFixed = this._controls.layoutFooterFixedW.querySelector('input')
if (this.settings.layoutFooterFixed) this._controls.layoutFooterFixed.setAttribute('checked', 'checked')
const layoutFooterFixedCb = e => this.setLayoutFooterFixed(e.target.checked)
this._controls.layoutFooterFixed.addEventListener('change', layoutFooterFixedCb)
this._listeners.push([ this._controls.layoutFooterFixed, 'change', layoutFooterFixedCb ])
}
// Reversed
//
this._controls.layoutReversedW = this.container.querySelector('.theme-settings-layoutReversed')
if (!this._hasControls('layoutReversed')) {
this._controls.layoutReversedW.parentNode.removeChild(this._controls.layoutReversedW)
} else {
this._controls.layoutReversed = this._controls.layoutReversedW.querySelector('input')
if (this.settings.layoutReversed) this._controls.layoutReversed.setAttribute('checked', 'checked')
const layoutReversedCb = e => this.setLayoutReversed(e.target.checked)
this._controls.layoutReversed.addEventListener('change', layoutReversedCb)
this._listeners.push([ this._controls.layoutReversed, 'change', layoutReversedCb ])
}
}
// Navbar Bg
//
const navbarBgW = this.container.querySelector('.theme-settings-navbarBg')
if (!this._hasControls('navbarBg')) {
navbarBgW.parentNode.removeChild(navbarBgW)
} else {
this._controls.navbarBgWInner = navbarBgW.querySelector('.theme-settings-navbarBg-inner')
this.settings.navbarBgs.forEach(bg => {
const bgItem = this._getElementFromString(bgItemMarkup)
const control = bgItem.querySelector('input')
bgItem.classList.add(`bg-${bg.split(' ')[0]}`)
control.name = 'theme-settings-navbarBg-input'
control.value = bg
if (this.settings.navbarBg === bg) {
control.setAttribute('checked', 'checked')
bgItem.classList.add('active')
}
const cb = e => {
const items = this._controls.navbarBgWInner.querySelectorAll('.theme-settings-bg-item')
for (let i = 0, l = items.length; i < l; i++) items[i].classList.remove('active')
e.target.parentNode.classList.add('active')
this.setNavbarBg(e.target.value)
}
control.addEventListener('change', cb)
this._listeners.push([ control, 'change', cb ])
this._controls.navbarBgWInner.appendChild(bgItem)
})
}
// Sidenav Bg
//
const sidenavBgW = this.container.querySelector('.theme-settings-sidenavBg')
if (!this._hasControls('sidenavBg')) {
sidenavBgW.parentNode.removeChild(sidenavBgW)
} else {
this._controls.sidenavBgWInner = sidenavBgW.querySelector('.theme-settings-sidenavBg-inner')
this.settings.sidenavBgs.forEach(bg => {
const bgItem = this._getElementFromString(bgItemMarkup)
const control = bgItem.querySelector('input')
bgItem.classList.add(`bg-${bg.split(' ')[0]}`)
control.name = 'theme-settings-sidenavBg-input'
control.value = bg
if (this.settings.sidenavBg === bg) {
control.setAttribute('checked', 'checked')
bgItem.classList.add('active')
}
const cb = e => {
const items = this._controls.sidenavBgWInner.querySelectorAll('.theme-settings-bg-item')
for (let i = 0, l = items.length; i < l; i++) items[i].classList.remove('active')
e.target.parentNode.classList.add('active')
this.setSidenavBg(e.target.value)
}
control.addEventListener('change', cb)
this._listeners.push([ control, 'change', cb ])
this._controls.sidenavBgWInner.appendChild(bgItem)
})
}
// Footer Bg
//
const footerBgW = this.container.querySelector('.theme-settings-footerBg')
if (!this._hasControls('footerBg')) {
footerBgW.parentNode.removeChild(footerBgW)
} else {
this._controls.footerBgWInner = footerBgW.querySelector('.theme-settings-footerBg-inner')
this.settings.footerBgs.forEach(bg => {
const bgItem = this._getElementFromString(bgItemMarkup)
const control = bgItem.querySelector('input')
bgItem.classList.add(`bg-${bg.split(' ')[0]}`)
control.name = 'theme-settings-footerBg-input'
control.value = bg
if (this.settings.footerBg === bg) {
control.setAttribute('checked', 'checked')
bgItem.classList.add('active')
}
const cb = e => {
const items = this._controls.footerBgWInner.querySelectorAll('.theme-settings-bg-item')
for (let i = 0, l = items.length; i < l; i++) items[i].classList.remove('active')
e.target.parentNode.classList.add('active')
this.setFooterBg(e.target.value)
}
control.addEventListener('change', cb)
this._listeners.push([ control, 'change', cb ])
this._controls.footerBgWInner.appendChild(bgItem)
})
}
// Themes
//
const themesW = this.container.querySelector('.theme-settings-themes')
if (!this._hasControls('themes')) {
themesW.parentNode.removeChild(themesW)
} else {
const themesWInner = this.container.querySelector('.theme-settings-themes-inner')
// SETUP THEMES
this.settings.availableThemes.forEach(theme => {
const themeItem = this._getElementFromString(themeItemMarkup)
const control = themeItem.querySelector('input')
themeItem.querySelector('.theme-settings-theme-name').innerHTML = theme.title
control.value = theme.name
if (this.settings.theme.name === theme.name) {
control.setAttribute('checked', 'checked')
}
themeItem.querySelector('.theme-settings-theme-colors').innerHTML = `
<span style="background: ${theme.colors.primary}"></span>
<span style="background: ${theme.colors.navbar}"></span>
<span style="background: ${theme.colors.sidenav}"></span>
`
const cb = e => {
if (this._loading) return
this._loading = true
this._loadingState(true, true)
this.setTheme(e.target.value, true, () => {
this._loading = false
this._loadingState(false, true)
})
}
control.addEventListener('change', cb)
this._listeners.push([ control, 'change', cb ])
themesWInner.appendChild(themeItem)
})
}
// Append container
if (_container === document) {
if (_container.body) {
_container.body.appendChild(this.container)
} else {
window.addEventListener('DOMContentLoaded', () => _container.body.appendChild(this.container))
}
} else {
_container.appendChild(this.container)
}
}
_initDirection() {
if (this._hasControls('rtl')) document.documentElement.setAttribute('dir', this.settings.rtl ? 'rtl' : 'ltr')
}
_initStyle() {
if (!this._hasControls('material')) return
const material = this.settings.material
this._insertStylesheet('theme-settings-bootstrap-css', this.pathResolver(
this.settings.cssPath + this.settings.cssFilenamePattern.replace('%name%', 'bootstrap' + (material ? '-material' : ''))
))
this._insertStylesheet('theme-settings-appwork-css', this.pathResolver(
this.settings.cssPath + this.settings.cssFilenamePattern.replace('%name%', 'appwork' + (material ? '-material' : ''))
))
this._insertStylesheet('theme-settings-colors-css', this.pathResolver(
this.settings.cssPath + this.settings.cssFilenamePattern.replace('%name%', 'colors' + (material ? '-material' : ''))
))
document.documentElement.classList.remove(material ? 'default-style' : 'material-style')
document.documentElement.classList.add(material ? 'material-style' : 'default-style')
if (material && window.attachMaterialRipple) {
if (document.body) {
window.attachMaterialRipple()
} else {
window.addEventListener('DOMContentLoaded', () => window.attachMaterialRipple())
}
}
}
_initTheme() {
if (this._hasControls('themes')) {
this._insertStylesheet('theme-settings-theme-css', this.pathResolver(
this.settings.themesPath + this.settings.cssFilenamePattern.replace('%name%', this.settings.theme.name + (this.settings.material ? '-material' : ''))
))
}
}
_insertStylesheet(className, href) {
const curLink = document.querySelector(`.${className}`)
if (typeof document.documentMode === 'number' && document.documentMode < 11) {
if (!curLink) return
if (href === curLink.getAttribute('href')) return
const link = document.createElement('link')
link.setAttribute('rel', 'stylesheet')
link.setAttribute('type', 'text/css')
link.className = className
link.setAttribute('href', href)
curLink.parentNode.insertBefore(link, curLink.nextSibling)
} else {
document.write(`<link rel="stylesheet" type="text/css" href="${href}" class="${className}">`)
}
curLink.parentNode.removeChild(curLink)
}
_loadStylesheets(stylesheets, cb) {
const paths = Object.keys(stylesheets)
const count = paths.length
let loaded = 0
function loadStylesheet(path, curLink, _cb) {
const link = document.createElement('link')
link.setAttribute('href', path)
link.setAttribute('rel', 'stylesheet')
link.setAttribute('type', 'text/css')
link.className = curLink.className
const sheet = 'sheet' in link ? 'sheet' : 'styleSheet'
const cssRules = 'sheet' in link ? 'cssRules' : 'rules'
let timeoutId, intervalId
timeoutId = setTimeout(function() {
clearInterval(intervalId)
clearTimeout(timeoutId)
curLink.parentNode.removeChild(link)
_cb(false, path);
}, 15000 )
intervalId = setInterval(function() {
try {
if (link[sheet] && link[sheet][cssRules].length) {
clearInterval(intervalId)
clearTimeout(timeoutId)
curLink.parentNode.removeChild(curLink)
_cb(true)
}
} catch(e) {
console.error(e)
} finally {}
}, 10)
curLink.parentNode.insertBefore(link, curLink.nextSibling)
}
for (let i = 0; i < paths.length; i++) {
loadStylesheet(paths[i], stylesheets[paths[i]], function(success, errPath) {
if (!success) {
if (console && typeof console.error === 'function') { console.error('Error occured while loading stylesheets!'); }
alert('Error occured while loading stylesheets!');
console.log(errPath)
}
if (++loaded >= count) {
cb()
}
})
}
}
_loadingState(enable, themes) {
this.container.classList[enable ? 'add' : 'remove'](`theme-settings-loading${themes ? '-theme' : ''}`)
}
_waitForNavs() {
this._addObserver(
'.layout-navbar.navbar, .layout-navbar .navbar',
node => {
return node && node.classList && node.classList.contains('layout-navbar') && (
node.classList.contains('navbar') || node.querySelector('.navbar')
)
},
() => this.setNavbarBg(this.settings.navbarBg, false)
)
this._addObserver(
'.layout-sidenav.sidenav, .layout-sidenav .sidenav, .layout-sidenav-horizontal.sidenav, .layout-sidenav-horizontal .sidenav',
node => {
return node && node.classList && (
(node.classList.contains('layout-sidenav') || node.classList.contains('layout-sidenav-horizontal')) && (
node.classList.contains('sidenav') || node.querySelector('.sidenav')
)
)
},
() => this.setSidenavBg(this.settings.sidenavBg, false)
)
this._addObserver(
'.layout-footer.footer, .layout-footer .footer',
node => {
return node && node.classList && node.classList.contains('layout-footer') && (
node.classList.contains('footer') || node.querySelector('.footer')
)
},
() => this.setFooterBg(this.settings.footerBg, false)
)
if (!document.body && ((this._observers && this._observers.length) || (this._intervals && this._intervals.length))) {
const loadCb = () => {
this._clearObservers()
this.setNavbarBg(this.settings.navbarBg, false)
this.setSidenavBg(this.settings.sidenavBg, false)
this.setFooterBg(this.settings.footerBg, false)
window.removeEventListener('load', loadCb)
}
window.addEventListener('load', loadCb)
}
}
_addObserver(selector, condition, cb) {
if (!this._observers) this._observers = []
if (!this._intervals) this._intervals = []
let _observer;
let _interval;
if (document.querySelector(selector)) {
cb.call(this)
} else if (!document.body) {
if (typeof MutationObserver !== 'undefined') {
_observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (!mutation.addedNodes) return
for (let i = 0; i < mutation.addedNodes.length; i++) {
let node = mutation.addedNodes[i]
if (condition.call(this, node)) {
_observer.disconnect()
this._observers.splice(this._observers.indexOf(_observer), 1)
_observer = null
cb.call(this)
break
}
}
})
})
this._observers.push(_observer)
_observer.observe(document.documentElement, {
childList: true, subtree: true, attributes: false, characterData: false
})
} else {
_interval = setInterval(() => {
if (document.querySelector(selector)) {
clearInterval(_interval)
this._intervals.splice(this._intervals.indexOf(_interval), 1)
_interval = null
cb.call(this)
}
}, 10)
this._intervals.push(_interval)
}
}
}
_clearObservers() {
if (this._observers && this._observers.length) {
for (let i = 0, l = this._observers.length; i < l; i++) {
this._observers[i].disconnect()
}
}
if (this._intervals && this._intervals.length) {
for (let j = 0, k = this._intervals.length; j < k; j++) {
clearInterval(this._intervals[j])
}
}
this._observers = null
this._intervals = null
}
_getElementFromString(str) {
const wrapper = document.createElement('div')
wrapper.innerHTML = str
return wrapper.firstChild
}
_getSetting(key) {
let result = null
try { result = localStorage.getItem(`themeSettings${key}`) } catch (e) {}
return String(result || '')
}
_setSetting(key, val) {
try { localStorage.setItem(`themeSettings${key}`, String(val)) } catch (e) {}
}
_getThemeByFile(themeName) {
let theme = null
for (let i = 0, l = this.settings.availableThemes.length; i < l; i++) {
if (this.settings.availableThemes[i].name === themeName) theme = this.settings.availableThemes[i]
}
return theme || this.settings.defaultTheme
}
_removeListeners() {
for (let i = 0, l = this._listeners.length; i < l; i++) {
this._listeners[i][0].removeEventListener(this._listeners[i][1], this._listeners[i][2])
}
}
_cleanup() {
this._removeListeners()
this._listeners = []
this._controls = {}
this._clearObservers()
if (this._updateInterval) {
clearInterval(this._updateInterval)
this._updateInterval = null
}
}
get _ssr() {
return typeof window === 'undefined'
}
_hasControls(controls, oneOf = false) {
return controls.split(' ').reduce((result, control) => {
if (this.settings.controls.indexOf(control) !== -1) {
if (oneOf || result !== false) result = true
} else {
if (!oneOf || result !== true) result = false
}
return result
}, null)
}
}
export { ThemeSettings }
<file_sep>require('../../node_modules/vegas/src/vegas.js');
require('./_extension.es6');
<file_sep># Ansible
Install to vagrant box by running:
$ ansible-galaxy install -r requirements.yml --ignore-errors
$ ansible-playbook -e database_dump=[path to db dump] -i development mijnstroom.yml
## Requirements
Ansible assumes a pre-installed Ubuntu server 16.04 LTS box with the following options:
- LVM encryption of HD (password needs to be manually inserted on every boot)
- Install security updates automatically
- Install openssh server
## Setup
Install external roles
```bash
$ ansible-galaxy install -r requirements.yml --ignore-errors
```
List all hosts for a particular inventory
```bash
$ ansible -i inventories/dev all --list-hosts
```
Dry run playbook
```bash
$ ansible-playbook -i inventories/dev playbook_site.yml --check
```
Run playbook
```bash
$ ansible-playbook -i inventories/dev playbook_site.yml
```
Encrypt String
```bash
$ ansible-vault encrypt_string 'string_to_encrypt' --name 'django_sentry_dsn'
```
Decrypt String
```bash
echo '$ANSIBLE_VAULT;1.1;AES256
37396335643234373123623238366363386561333030623363646438353364663766636437346636
6566613238346334373263613161623334393762396530620a303465353435346633643862303930
30313766333662353830383036363532316130383639346233666139653862643336373134313966
3832373939326530620a353034236465363839383835626265353132383834623632643639393935
38376663303736383838323539353833666666633665616433386630333165653161363632383966
3337353236646134646633633164353265373437336434303134' | tr -d ' ' | ansible-vault decrypt && echo
```
<file_sep>import style from 'node-waves/dist/waves.css'
import Waves from 'node-waves/dist/waves.js'
function isElementWithRipple(el) {
const cls = (el.className || '').split(' ')
return (
cls.indexOf('btn') !== -1 ||
cls.indexOf('page-link') !== -1 ||
cls.indexOf('dropdown-item') !== -1 ||
(
el.tagName &&
el.tagName.toUpperCase() === 'A' &&
el.parentNode.tagName.toUpperCase() === 'LI'
&& (
el.parentNode.parentNode.className.indexOf('dropdown-menu') !== -1 ||
el.parentNode.parentNode.className.indexOf('pagination') !== -1
)
)
)
}
function getElementWithRipple(target) {
if (typeof target.className.indexOf !== 'function' || target.className.indexOf('waves-effect') !== -1) return null
if (isElementWithRipple(target)) return target
let el = target.parentNode
while (el.tagName.toUpperCase() !== 'BODY' && el.className.indexOf('waves-effect') === -1) {
if (isElementWithRipple(el)) return el
el = el.parentNode
}
return null
}
function attachWaves(e) {
if (e.button === 2) return
const el = getElementWithRipple(e.target)
el && Waves.attach(el)
}
function attachMaterialRipple() {
if (typeof window === 'undefined') return
if (typeof document['documentMode'] === 'number' && document['documentMode'] < 11) return
document.body.addEventListener('mousedown', attachWaves, false)
if ('ontouchstart' in window) document.body.addEventListener('touchstart', attachWaves, false)
Waves.init({ duration: 500 })
}
function attachMaterialRippleOnLoad() {
if (document.body) {
attachMaterialRipple()
} else {
window.addEventListener('DOMContentLoaded', function windowOnLoad() {
attachMaterialRipple()
window.removeEventListener('DOMContentLoaded', windowOnLoad)
})
}
}
function detachMaterialRipple() {
if (typeof window === 'undefined' || !document.body) return
if (typeof document['documentMode'] === 'number' && document['documentMode'] < 11) return
document.body.removeEventListener('mousedown', attachWaves, false)
if ('ontouchstart' in window) document.body.removeEventListener('touchstart', attachWaves, false)
Waves.calm('.waves-effect')
}
export { attachMaterialRipple, attachMaterialRippleOnLoad, detachMaterialRipple }
<file_sep>import graphene
from graphene_django_extras import DjangoFilterPaginateListField, DjangoObjectType, LimitOffsetGraphqlPagination
from seedorf.users.schema import UserType
from .models import Game, RsvpStatus
from .viewsets import GameFilter, RsvpStatusFilter
class GameType(DjangoObjectType):
# NOTE: To break game <-> spot circular dependency
# REF: https://github.com/graphql-python/graphene/issues/522#issuecomment-324066522
spot = graphene.Field("seedorf.spots.schema.SpotType")
organizer = graphene.Field(UserType)
class Meta:
model = Game
@property
def spots_class(self):
return self._meta.fields["spots"].type
class RsvpStatusType(DjangoObjectType):
user = graphene.Field(UserType)
class Meta:
model = RsvpStatus
class Query(object):
game = graphene.Field(GameType, uuid=graphene.UUID())
games = DjangoFilterPaginateListField(
GameType, pagination=LimitOffsetGraphqlPagination(), filterset_class=GameFilter
)
rsvp_status = graphene.Field(RsvpStatusType, uuid=graphene.UUID())
rsvp_statuses = DjangoFilterPaginateListField(
RsvpStatusType, pagination=LimitOffsetGraphqlPagination(), filterset_class=RsvpStatusFilter
)
@staticmethod
def resolve_game(args, info, **kwargs):
uuid = kwargs.get("uuid")
if uuid is not None:
return Game.objects.get(uuid=uuid)
return None
@staticmethod
def resolve_games(args, **kwargs):
return Game.objects.all()
@staticmethod
def resolve_rsvp_status(args, **kwargs):
uuid = kwargs.get("uuid")
if uuid is not None:
return RsvpStatus.objects.filter(uuid=uuid).first()
return None
@staticmethod
def resolve_rsvp_statuses(args, **kwargs):
return RsvpStatus.objects.all()
<file_sep># Generated by Django 2.2b1 on 2019-03-13 09:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("users", "0008_add_language_spanish")]
operations = [
migrations.AlterField(
model_name="magicloginlink", name="token", field=models.TextField(unique=True, verbose_name="Token")
)
]
<file_sep># Generated by Django 2.1.2 on 2019-03-29 13:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("sports", "0002_auto_20180602_2110")]
operations = [
migrations.AlterField(
model_name="sport",
name="category",
field=models.CharField(
choices=[
("basketball", "Basketball"),
("beach_volleyball", "Beach Volleyball"),
("bootcamp", "Bootcamp"),
("boules", "Boules"),
("fitness", "Fitness"),
("others", "Others"),
("skating", "Skating"),
("soccer", "Soccer"),
("tennis", "Tennis"),
("table_tennis", "Table Tennis"),
],
default="others",
help_text="Name of the main category of the sport (e.g. Soccer).",
max_length=50,
verbose_name="Sport Category",
),
)
]
<file_sep>import scrapy
from urllib.parse import urlparse, parse_qs, urljoin
import json
from ..items import Spot
class PlayAdvisorSpider(scrapy.Spider):
name = "open_street_maps"
def start_requests(self):
# REF: https://wiki.openstreetmap.org/wiki/NL:Kaartelementen#Sports
# REF: https://wiki.openstreetmap.org/wiki/Key:sport
sports = [
"9pin",
"10pin",
"american_football",
"aikido",
"archery",
"athletics",
"australian_football",
"badminton",
"bandy",
"baseball",
"basketball",
"beachvolleyball",
"billiards",
"bmx",
"bobsleigh",
"boules",
"bowls",
"boxing",
"bullfighting",
"canadian_football",
"canoe",
"chess",
"cliff_diving",
"climbing",
"climbing_adventure",
"cockfighting",
"cricket",
"crossfit",
"croquet",
"curling",
"cycling",
"darts",
"dog_racing",
"equestrian",
"fencing",
"field_hockey",
"free_flying",
"futsal",
"gaelic_games",
"golf",
"gymnastics",
"handball",
"hapkido",
"horseshoes",
"horse_racing",
"ice_hockey",
"ice_skating",
"ice_stock",
"judo",
"karate",
"karting",
"kitesurfing",
"korfball",
"krachtbal",
"lacrosse",
"martial_arts",
"model_aerodrome",
"motocross",
"motor",
"multi",
"netball",
"obstacle_course",
"orienteering",
"paddle_tennis",
"padel",
"parachuting",
"pelota",
"racquet",
"rc_car",
"roller_skating",
"rowing",
"rugby_league",
"rugby_union",
"running",
"sailing",
"scuba_diving",
"shooting",
"skateboard",
"soccer",
"sumo",
"surfing",
"swimming",
"table_tennis",
"table_soccer",
"taekwondo",
"tennis",
"toboggan",
"volleyball",
"water_polo",
"water_ski",
"weightlifting",
"wrestling",
"yoga",
]
for sport in sports:
yield scrapy.FormRequest(
url="https://overpass-api.de/api/interpreter",
method="POST",
formdata={
"data": f"""[out:json];
area["ISO3166-1"="NL"][admin_level=2];
node
[leisure=pitch][sport={sport}]
(area);
out;
"""
},
callback=self.parse,
)
def parse(self, response):
api_response = json.loads(response.body_as_unicode())
spots = api_response["elements"]
for spot in spots:
item = Spot()
item["id"] = spot["id"]
item["label"] = spot["tags"].get("name", "")
item["description"] = spot["tags"].get("description", "")
item["lat"] = spot["lat"]
item["lng"] = spot["lon"]
item["sports"] = [
spot["tags"]["sport"],
]
yield item
<file_sep>from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
from django.contrib.postgres.fields import JSONField
from django.utils.translation import ugettext_lazy as _
from seedorf.utils.models import BasePropertiesModel
class Address(BasePropertiesModel):
GEOCODER_GOOGLE_MAPS = "google"
GEOCODER_BING = "bing"
GEOCODER_OSM = "open_street_maps"
GEOCODER_HERE = "here"
GEOCODER_MANUAL = "manual"
GEOCODERS = (
(GEOCODER_GOOGLE_MAPS, _("Google")),
(GEOCODER_BING, _("Bing")),
(GEOCODER_OSM, _("Open Street Maps")),
(GEOCODER_HERE, _("Here Maps")),
(GEOCODER_MANUAL, _("Manual")),
)
raw_address = models.CharField(
blank=True, default="", help_text=_("Complete address"), max_length=1024, null=False, verbose_name=_("Address")
)
raw_geocoder_response = JSONField(
blank=True,
help_text=_("Raw api response from the geocoder service. e.g. google maps"),
null=True,
verbose_name=_("Raw Geocoder Response"),
)
geocoder_service = models.CharField(
blank=False,
choices=GEOCODERS,
default=GEOCODER_MANUAL,
help_text=_("Geocoder used to convert raw address into latlong coordinates."),
max_length=25,
null=True,
verbose_name=_("Geocoder"),
)
formatted_address = models.CharField(
blank=True,
help_text=_("Formatted address returned by the geocoding service"),
max_length=1024,
null=False,
verbose_name=_("Formatted Address"),
)
lat = models.DecimalField(blank=True, decimal_places=15, max_digits=18, null=True, verbose_name=_("Latitude"))
lng = models.DecimalField(blank=True, decimal_places=15, max_digits=18, null=True, verbose_name=_("Longtiude"))
point = models.PointField(spatial_index=True, help_text=_("Lat/Lng Point"), null=True, verbose_name=_("Location"))
# TODO: https://plus.codes/
plus_global_code = models.CharField(
blank=True, max_length=255, null=True, verbose_name=_("Google Plus Global Code")
)
plus_local_code = models.CharField(blank=True, max_length=255, null=True, verbose_name=_("Google Plus Local Code"))
# location_type = None # REF: Google Maps https://developers.google.com/maps/documentation/geocoding/start
# viewport = None # REF: Google Maps https://developers.google.com/maps/documentation/geocoding/start
# types = None # REF: Google Maps https://developers.google.com/maps/documentation/geocoding/start
# city = None # REF: Maybe use django-cities
# country = None # REF: Maybe use django-cities
# utc_offset= None # REF: Maybe use django-cities
class Meta:
verbose_name = _("Address")
verbose_name_plural = _("Addresses")
ordering = ("-created_at",)
def __str__(self):
return f"{self.formatted_address}"
def save(self, *args, **kwargs):
self.point = Point(x=float(self.lng), y=float(self.lat), srid=4326)
super().save(*args, **kwargs)
<file_sep>import Popper from '../../node_modules/popper.js/dist/popper.js';
// Required to enable animations on dropdowns/tooltips/popovers
Popper.Defaults.modifiers.computeStyle.gpuAcceleration = false;
export { Popper };
<file_sep>require('../../node_modules/jquery-idletimer/dist/idle-timer.js');
<file_sep>require('../../../../node_modules/bootstrap-table/src/extensions/cookie/bootstrap-table-cookie.js');
<file_sep>require('../../node_modules/jquery-sparkline/jquery.sparkline.js');
require('./_extension.es6');
<file_sep>import * as autosize from '../../node_modules/autosize/dist/autosize.js';
export { autosize };
<file_sep>require('../../node_modules/select2/dist/js/select2.full.js');
<file_sep>from django.db import transaction
from django.db.utils import IntegrityError
from test_plus.test import TestCase
from . import factories
from ..models import Sport
class TestSport(TestCase):
def setUp(self):
self.sport_soccer = factories.SportFactory(name="soccer", category=Sport.SOCCER)
def test__str__(self):
self.assertEqual(self.sport_soccer.__str__(), "soccer : soccer")
class TestSportUniqueness(TestCase):
"""
NOTE: To avoid TransactionManagementError, we need to inherit from TransactionTestCase
REF: https://stackoverflow.com/a/24589930/7574302
"""
def setUp(self):
self.sport_soccer = factories.SportFactory(category=Sport.SOCCER, name="soccer")
def test_unique_name(self):
with transaction.atomic(), self.assertRaises(IntegrityError):
Sport.objects.create(category=Sport.SOCCER, name="soccer")
<file_sep>from django.http import HttpResponse
file = """{
"applinks": {
"apps": [],
"details": [
{
"appID": "FD94WWSEG4.com.sportyspots.ios",
"paths": [ "/games/*" ]
}
]
}
}"""
def apple_app_site_association(request):
response = HttpResponse(file, content_type="application/json")
response["Content-Disposition"] = 'attachment; filename="apple-app-site-association"'
return response
<file_sep>require('../../node_modules/bootstrap-datepicker/dist/js/bootstrap-datepicker.js');
<file_sep>import graphene
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from graphene_django.types import DjangoObjectType
from graphene_django_extras import DjangoFilterPaginateListField
from graphene_django_extras.paginations import LimitOffsetGraphqlPagination
from seedorf.locations.schema import AddressType
from seedorf.sports.schema import SportType
from .models import Spot, SpotAmenity, SpotImage, SpotOpeningTime
from .viewsets import SpotFilter
class SpotImageType(DjangoObjectType):
class Meta:
model = SpotImage
def resolve_image(self, info, **kwargs):
if self.image:
return f"{settings.MEDIA_URL}{self.image}"
else:
return ""
class SpotAmenityType(DjangoObjectType):
class Meta:
model = SpotAmenity
class SpotOpeningTimeType(DjangoObjectType):
class Meta:
model = SpotOpeningTime
class SpotType(DjangoObjectType):
sports = graphene.List(SportType)
games = graphene.List("seedorf.games.schema.GameType")
address = graphene.Field(AddressType)
class Meta:
description = _("Type definition for a single spot")
model = Spot
exclude_fields = ("spot_games",)
def resolve_sports(self, info, **kwargs):
return self.sports.all()
def resolve_games(self, info, **kwargs):
return self.spot_games.all()
class Query(graphene.ObjectType):
spot = graphene.Field(SpotType, uuid=graphene.UUID())
spots = DjangoFilterPaginateListField(
SpotType, filterset_class=SpotFilter, pagination=LimitOffsetGraphqlPagination()
)
def resolve_spot(self, info, **kwargs):
uuid = kwargs.get("uuid")
if uuid is not None:
return Spot.objects.filter(uuid=uuid).first()
return None
<file_sep>from fabric import task
from invoke import run as local
from invoke.exceptions import Failure
@task
def pull_database(c):
# REF: pipenv run fab --identity ansible/ssh_keys/private/aws_lightsail_ssh_sportyspots_admin.key --hosts <EMAIL> --echo pull-database
# NOTE: Fabric transperantly converts the underscores in task names to dashes
local("dropdb --if-exists seedorf")
local("createdb seedorf")
try:
local("createuser --login --superuser --createdb ubuntu")
except Failure:
pass
local_dump = local("mktemp")
remote_dump = c.run("mktemp")
pg_dump = c.run(f"pg_dump seedorf | gzip > {remote_dump.stdout.strip()}")
if pg_dump.ok:
try:
# Explicitly use scp since we don't allow sftp subsystem on our servers
local(
f"scp -i ansible/ssh_keys/private/aws_lightsail_ssh_sportyspots_admin.key <EMAIL>}:{remote_dump.stdout.strip()} {local_dump.stdout.strip()}"
)
local(f"gunzip -c {local_dump.stdout.strip()} | psql seedorf")
finally:
c.run(f"rm {remote_dump.stdout.strip()}")
local(f"rm {local_dump.stdout.strip()}")
|
761442df47845984e777a342a9c17beaff112835
|
[
"HTML",
"JavaScript",
"Markdown",
"TOML",
"Python",
"Dockerfile",
"Shell"
] | 179
|
Python
|
SportySpots/seedorf
|
3f09c720ea8df0d1171022b68b494c2758f75d44
|
8dcd80c0b3bd794cd09354740dbf15628f20dfee
|
refs/heads/master
|
<file_sep># Description
Implementation of a simple SoC with embedded [RISC-V](https://github.com/ucb-bar/zscale) processor.
# Used Parts
- [Altera Cyclone II FPGA Starter Development Kit](http://www.terasic.com.tw/cgi-bin/page/archive.pl?Language=English&CategoryNo=53&No=83).
# Status
Work in progress.
<file_sep>#define REG32(x) (*(unsigned int volatile *)(x))
#define LEDR 0x40001020
void main(void) {
REG32(LEDR) = 0x155;
for (;;);
}
<file_sep># Generate memory image from assembly file
RISCV_PREFIX=riscv64-unknown-elf-
RISCV_GCC = $(RISCV_PREFIX)gcc -m32 -march=RV32IM
RISCV_GCC_OPTS = -O2 -static
RISCV_LINK = $(RISCV_GCC) -T zscale.ld
RISCV_LINK_OPTS = -nostdlib -nostartfiles
RISCV_OBJDUMP = $(RISCV_PREFIX)objdump
.PHONY: copy clean
copy: leds.mif
cp $< ../sim/rom.mif
cp $< ../syn/rom.mif
%.mif: %.dump
perl objdump2mif.pl $< > $@
%.dump: %.elf
$(RISCV_OBJDUMP) -d $< > $@
%.elf: %.o crt.o
$(RISCV_LINK) $^ -o $@ $(RISCV_LINK_OPTS)
%.o: %.c
$(RISCV_GCC) $(RISCV_GCC_OPTS) -c $< -o $@
%.o: %.S
$(RISCV_GCC) $(RISCV_GCC_OPTS) -c $< -o $@
clean:
rm -f *.o *.elf *.dump *.mif
<file_sep>/* Altera DE1 Development and Education board */
#ifndef __CII_DE1_H__
#include <stdint.h>
#define REG32(x) (*(uint32_t volatile *)(x))
/* LEDs */
#define HEX 0x80000000
#define LEDG 0x80000010
#define LEDR 0x80000020
/* keys and switches */
#define KEY 0x80001000
#define SW 0x80001010
#endif
|
14acdf281a89259bbb157881627fe1dfc3cdeca1
|
[
"Markdown",
"C",
"Makefile"
] | 4
|
Markdown
|
pbing/zscale_system
|
ab69149e773ee343ff485e332d19dcb8d0265507
|
8367f50616097a72adcf985c56416f9b7f0e65e9
|
refs/heads/master
|
<repo_name>manueljakob1986/Diploma-thesis<file_sep>/README.md
Diploma-thesis
==============
Here you can find the Matlab and Java code for my Diploma Thesis:
"Methodology for Site Selection for Route-Based Traffic Network Optimizations
And Relative Costs of Implementation: Numerical Studies"
------
Folders:
1.) SO DTA with partial compliance implementation (Matlab code)
2.) UE DTA implementation (Matlab and Java code)
_________
<NAME>, TU Darmstadt and UC Berkeley Applied Mathematics Graduate Student<file_sep>/UE DTA implementation/CTM_Network_Loads/com/relteq/sirius/simulator/SiriusMath.java
package com.relteq.sirius.simulator;
import java.util.ArrayList;
public final class SiriusMath {
private static final double EPSILON = (double) 1e-4;
public static Double [] zeros(int n){
Double [] answ = new Double [n];
for(int i=0;i<n;i++)
answ[i] = 0.0;
return answ;
}
public static Double sum(Double [] V){
Double answ = 0d;
for(int i=0;i<V.length;i++)
if(V[i]!=null)
answ += V[i];
return answ;
}
public static Double [] times(Double [] V,double a){
Double [] answ = new Double [V.length];
for(int i=0;i<V.length;i++)
answ[i] = a*V[i];
return answ;
}
public static int ceil(double a){
return (int) Math.ceil(a-SiriusMath.EPSILON);
}
public static int floor(double a){
return (int) Math.floor(a+SiriusMath.EPSILON);
}
public static int round(double a){
return (int) Math.round(a);
}
public static boolean any (boolean [] x){
for(int i=0;i<x.length;i++)
if(x[i])
return true;
return false;
}
public static boolean all (boolean [] x){
for(int i=0;i<x.length;i++)
if(!x[i])
return false;
return true;
}
public static boolean[] not(boolean [] x){
boolean [] y = x.clone();
for(int i=0;i<y.length;i++)
y[i] = !y[i];
return y;
}
public static int count(boolean [] x){
int s = 0;
for(int i=0;i<x.length;i++)
if(x[i])
s++;
return s;
}
public static ArrayList<Integer> find(boolean [] x){
ArrayList<Integer> r = new ArrayList<Integer>();
for(int i=0;i<x.length;i++)
if(x[i])
r.add(i);
return r;
}
public static boolean isintegermultipleof(Double A,Double a){
if(A.isInfinite())
return true;
if(A==0)
return true;
if(a==0)
return false;
boolean result;
result = SiriusMath.equals( SiriusMath.round(A/a) , A/a );
result &= A/a>0;
return result;
}
public static boolean equals(double a,double b){
return Math.abs(a-b) < SiriusMath.EPSILON;
}
public static boolean greaterthan(double a,double b){
return a > b + SiriusMath.EPSILON;
}
public static boolean greaterorequalthan(double a,double b){
return !lessthan(a,b);
}
public static boolean lessthan(double a,double b){
return a < b - SiriusMath.EPSILON;
}
public static boolean lessorequalthan(double a,double b){
return !greaterthan(a,b);
}
// greatest common divisor of two integers
public static int gcd(int p, int q) {
if (q == 0) {
return p;
}
return gcd(q, p % q);
}
}
<file_sep>/UE DTA implementation/CTM_Network_Loads/com/relteq/sirius/simulator/Runner.java
/* Copyright (c) 2012, Relteq Systems, Inc. All rights reserved.
This source is subject to the following copyright notice:
http://relteq.com/COPYRIGHT_RelteqSystemsInc.txt
*/
package com.relteq.sirius.simulator;
final class Runner {
private static String configfilename;
private static String outputfileprefix;
private static double timestart;
private static double timeend;
private static double outdt;
private static int numRepetitions;
public static void main(String[] args) {
long time = System.currentTimeMillis();
// process input parameters
if(!parseInput(args)){
SiriusErrorLog.printErrorMessage();
return;
}
// load configuration file ................................
Scenario scenario = ObjectFactory.createAndLoadScenario(configfilename);
// check if it loaded
if(SiriusErrorLog.haserror()){
SiriusErrorLog.printErrorMessage();
return;
}
// run scenario ...........................................
try {
scenario.run(outputfileprefix,timestart,timeend,outdt,numRepetitions);
} catch (SiriusException e) {
e.printStackTrace();
}
System.out.println("done in " + (System.currentTimeMillis()-time));
}
private static boolean parseInput(String[] args){
if(args.length<1){
String str;
str = "Usage:" + "\n";
str += "-----\n" + "\n";
str += "args[0]: Configuration file name. (required)\n";
str += "args[1]: Output file name.\n";
str += "args[2]: Start time [seconds after midnight]." + "\n";
str += " Defailt: Minimum start time of all demand profiles." + "\n";
str += "args[3]: Duration [seconds]." + "\n";
str += " Defailt: 86,400 seconds." + "\n";
str += "args[4]: Output sampling time [seconds]." + "\n";
str += " Default: 300 seconds." + "\n";
str += "args[5]: Number of simulations." + "\n";
str += " Default: 1." + "\n";
str += "\nSimulation modes:" + "\n";
str += "----------------\n" + "\n";
str += "Normal mode: Simulation runs in normal mode when the start time equals " +
"the time stamp of the initial density profile. In this mode, the initial density state" +
" is taken from the initial density profile, and the simulated state is written to the output file.\n" + "\n";
str += "Warmup mode: Warmup is executed whenever the start time (st) does not equal the time stamp " +
"of the initial density profile (tsidp). The purpose of a warmup simulation is to compute the state of the scenario " +
"at st. If st<tsidp, then the warmup run will start with zero density at the earliest times stamp of all " +
"demand profiles and run to st. If st>tsidn, then the warmup will start at tsidn with the given initial " +
"density profile and run to st. The simulation state is not written in warmup mode. The output is a configuration " +
"file with the state at st contained in the initial density profile." + "\n";
SiriusErrorLog.addErrorMessage(str);
return false;
}
// Configuration file name
configfilename = args[0];
// Output file name
if(args.length>1)
outputfileprefix = args[1];
else
outputfileprefix = "output";
// Start time [seconds after midnight]
if(args.length>2){
timestart = Double.parseDouble(args[2]);
timestart = SiriusMath.round(timestart*10.0)/10.0; // round to the nearest decisecond
}
else
timestart = Defaults.TIME_INIT;
// Duration [seconds]
if(args.length>3)
timeend = timestart + Double.parseDouble(args[3]);
else
timeend = timestart + Defaults.DURATION;
// Output sampling time [seconds]
if(args.length>4){
outdt = Double.parseDouble(args[4]);
outdt = SiriusMath.round(outdt*10.0)/10.0; // round to the nearest decisecond
}
else
outdt = Defaults.OUT_DT;
// Number of simulations
if(args.length>5){
numRepetitions = Integer.parseInt(args[5]);
}
else
numRepetitions = 1;
return true;
}
}
<file_sep>/UE DTA implementation/CTM_Network_Loads/com/relteq/sirius/simulator/InitialDensityProfile.java
/* Copyright (c) 2012, Relteq Systems, Inc. All rights reserved.
This source is subject to the following copyright notice:
http://relteq.com/COPYRIGHT_RelteqSystemsInc.txt
*/
package com.relteq.sirius.simulator;
final class InitialDensityProfile extends com.relteq.sirius.jaxb.InitialDensityProfile {
protected Scenario myScenario;
protected Double [][] initial_density; // [veh/mile] indexed by link and type
protected Link [] link; // ordered array of references
protected Integer [] vehicletypeindex; // index of vehicle types into global list
protected double timestamp;
/////////////////////////////////////////////////////////////////////
// populate / reset / validate / update
/////////////////////////////////////////////////////////////////////
protected void populate(Scenario myScenario){
int i;
this.myScenario = myScenario;
// allocate
int numLinks = getDensity().size();
initial_density = new Double [numLinks][];
link = new Link [numLinks];
vehicletypeindex = myScenario.getVehicleTypeIndices(getVehicleTypeOrder());
// copy profile information to arrays in extended object
for(i=0;i<numLinks;i++){
com.relteq.sirius.jaxb.Density density = getDensity().get(i);
link[i] = myScenario.getLinkWithCompositeId(density.getNetworkId(),density.getLinkId());
Double1DVector D = new Double1DVector(density.getContent(),":");
initial_density[i] = D.getData();
}
// round to the nearest decisecond
if(getTstamp()!=null)
timestamp = SiriusMath.round(getTstamp().doubleValue()*10.0)/10.0;
else
timestamp = 0.0;
}
protected boolean validate() {
int i;
// check that all vehicle types are accounted for
if(vehicletypeindex.length!=myScenario.getNumVehicleTypes()){
SiriusErrorLog.addErrorMessage("Demand profile list of vehicle types does not match that of settings.");
return false;
}
// check that vehicle types are valid
for(i=0;i<vehicletypeindex.length;i++){
if(vehicletypeindex[i]<0){
SiriusErrorLog.addErrorMessage("Bad vehicle type name.");
return false;
}
}
// check that links are valid
for(i=0;i<link.length;i++){
if(link[i]==null){
SiriusErrorLog.addErrorMessage("Bad link id");
return false;
}
}
// check size of data
for(i=0;i<link.length;i++){
if(initial_density[i].length!=vehicletypeindex.length){
SiriusErrorLog.addErrorMessage("Wrong number of data points.");
return false;
}
}
// check that values are between 0 and jam density
int j;
Double sum;
Double x;
for(i=0;i<initial_density.length;i++){
if(link[i].issource) // does not apply to source links
continue;
sum = 0.0;
for(j=0;j<vehicletypeindex.length;j++){
x = initial_density[i][j];
if(x<0 || x.isNaN()){
SiriusErrorLog.addErrorMessage("Invalid initial density.");
return false;
}
sum += x;
}
if(sum>link[i].getDensityJamInVPMPL()){
SiriusErrorLog.addErrorMessage("Initial density exceeds jam density.");
return false;
}
}
return true;
}
protected void reset() {
}
protected void update() {
}
/////////////////////////////////////////////////////////////////////
// public API
/////////////////////////////////////////////////////////////////////
public Double [] getDensityForLinkIdInVeh(String network_id,String linkid){
Double [] d = SiriusMath.zeros(myScenario.getNumVehicleTypes());
for(int i=0;i<link.length;i++){
if(link[i].getId().equals(linkid) && link[i].myNetwork.getId().equals(network_id)){
for(int j=0;j<vehicletypeindex.length;j++)
d[vehicletypeindex[j]] = initial_density[i][j]*link[i].getLengthInMiles();
return d;
}
}
return d;
}
}
|
8da7b87662a50dc68215ddae7ca0f03a9983806d
|
[
"Markdown",
"Java"
] | 4
|
Markdown
|
manueljakob1986/Diploma-thesis
|
565f0cca2438d08f102c69f7142ba71108678a26
|
68fca4af2460c4c34da27585a130d388d51db636
|
refs/heads/main
|
<file_sep>import pygame
import speech_recognition;
import pyttsx3
import vlc
import sys
import time
"""
Spch
ImgSpch
Video
"""
music_dictionary = {
"how deep is your love" : {
"type" : "Video",
"caption": "Video",
"video": "Music.mp4"
}
,
"instrumental music" : {
"type" : "Video",
"caption": "Aaj Jaane ki Jid na Karo - Instrumental",
"video": "SitarJaaneKiJid.mp4"
}
,
"most played songs":{
"type": "Spch",
"text": "Despacito, Shape of you are the worlds most played songs",
"caption": "Most Popular Song"
}
,
"types of western music":{
"type": "ImgSpch",
"text": "Rock, hip-hop, pop, and country, are some types of western music",
"pic": "typesofmusic.png",
"caption": "Types of Music"
}
,
"famous band":{
"type": "ImgSpch",
"text": "The Beatles was the most famous band",
"pic": "Thebeatles.jpg",
"caption": "The Beatles"
}
,
"most awards":{
"type": "ImgSpch",
"text": "The UD band have won the most awards which is 22",
"pic": "udBand.jpg",
"caption": "Most awards won by a band"
}
,
"famous singers":{
"type": "ImgSpch",
"text": "The most famous ones are <NAME>, <NAME> and <NAME>",
"pic": "michaeljackson.jpg",
"caption": "Famous singers"
}
,
"easiest instrument":{
"type": "ImgSpch",
"text": "The easiest instrument to learn is piano and the hardest is violin",
"pic": "piano.jpg",
"caption": "Easiest instrument"
}
,
"benefits of music":{
"type": "ImgSpch",
"text": "The benefit of music is that it's calming and soothing",
"pic": "MusicBenefits.jpeg",
"caption": "Benefits of music"
}
,
"indian music":{
"type": "ImgSpch",
"text": "It consists of Gazal, Raga, Thumri",
"pic": "indian music.jpg",
"caption": "Indian Music"
}
,
"mozart":{
"type": "Spch",
"text": "Mozart was a child prodigy, born in salsburg Austria. His full name is <NAME>. Some of his fammous compositions are The Marriage of Figaro, <NAME> and the Jupiter Symphony",
"caption": "Mozart"
}
,
"beethoven":{
"type": "Spch",
"text": "Beethoven was born in bonn Germany, his full name is <NAME>, some of his fammous compositions are Septet, Moonlight Sonata, <NAME>",
"caption": "Beethoven"
}
,
"styles":{
"type": "ImgSpch",
"text": "There are many types of styles but the most used ones are waltz, swing, jazz and dance",
"pic": "styles.png",
"caption": "Styles"
}
,
"tone":{
"type": "Spch",
"text": "Traditionally in Western music, a musical tone is a steady periodic sound. A musical tone is characterized by its duration, pitch, intensity, and timbre.",
"caption": "Tone"
}
}
# set width and height of screen
screen_dimensions = (900,600)
# location of text on screen
textlocation = (50,500)
def executeCommand(command):
commandType = music_dictionary[command]["type"]
if commandType == "ImgSpch":
commandText = music_dictionary[command]["text"]
commandPic = music_dictionary[command]["pic"]
commandCaption = music_dictionary[command]["caption"]
setScreenImg(commandPic, commandCaption)
time.sleep(1)
if commandText:
setScreenText (commandText, textlocation)
sayText (commandText)
time.sleep(2)
elif commandType == "Spch":
commandText = music_dictionary[command]["text"]
commandCaption = music_dictionary[command]["caption"]
if commandText:
setScreenText (commandText, textlocation)
pygame.display.set_caption(commandCaption)
sayText (commandText)
time.sleep(2)
elif commandType == "Video":
commandVid = music_dictionary[command]["video"]
commandCaption = music_dictionary[command]["caption"]
pygame.display.set_caption(commandCaption)
mediaplayer = vlc.MediaPlayer()
media = vlc.Media(commandVid)
mediaplayer.set_media(media)
# start playing video
mediaplayer.play()
time.sleep(20)
mediaplayer.stop()
# end of function executeCommand
def setScreenText (displaytext, location = (0,0)):
# set font
font = pygame.font.SysFont("Calibri", 22)
# set text
text = font.render(displaytext, True,(255,255,255),(0,0,0))
# display text
screen.blit(text, location)
pygame.display.update()
def setScreenImg(img, caption = "Welcome to Carollexa!", location = (0,0)):
screen.fill((0,0,0))
# set caption
pygame.display.set_caption(caption)
# loading image
screenimg = pygame.image.load(img)
screenimg = pygame.transform.scale(screenimg, screen_dimensions)
# set location of image on screen
screen.blit(screenimg, location)
pygame.display.update()
def sayText(text):
engine.say(text)
engine.runAndWait()
# set screen
pygame.init()
screen = pygame.display.set_mode(screen_dimensions)
engine=pyttsx3.init()
setScreenImg ("background.png")
setScreenText ("Welcome to Carollexa. Press \"s\" to interact, and \"q\" to quit.", (50,50))
sayText("Please wait while the app initializes. Press S to interact, and Q to quit")
isQuit = False
while isQuit == False:
try:
for event in pygame.event.get():
pygame.display.update()
time.sleep(.25)
# check if user wants to quit
if (event.type == pygame.QUIT):
sayText('Have a good day!')
isQuit = True
break
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
recognizer=speech_recognition.Recognizer();
with speech_recognition.Microphone() as source:
recognizer.adjust_for_ambient_noise(source)
sayText("How may I help you?")
audio=recognizer.listen(source)
#Convert Voice Commands to Text
command=recognizer.recognize_google(audio).lower()
sayText("You said: "+command)
bIsCommand = False
for keyword in music_dictionary:
if keyword in command:
bIsCommand = True
executeCommand(keyword)
if bIsCommand == False:
sayText("Unrecognized command")
setScreenImg("background.png")
setScreenText ("Welcome to Carollexa. Press \"s\" to interact, and \"q\" to quit.", (50,50))
elif event.key == pygame.K_q: #activate=="q":
sayText('Have a good day!')
isQuit = True
break
else:
sayText('I did not understand the command')
#Stop Taking Voice Commands
except speech_recognition.UnknownValueError:
sayText("I did not understand the audio")
except speech_recognition.RequestError as e:
sayText("Could not request results; {0}".format(e))
except KeyboardInterrupt:
break
# end while isQuit == False
pygame.quit()
sys.exit()
|
59ae73ae2d6b4980ab9893ed8100fdcd78f28390
|
[
"Python"
] | 1
|
Python
|
nm-github-web/Carollexa
|
eae39eefb1b3a973834af80572ab9f549c0597e5
|
8bd4123d0351e03635d76701118f31d60c1f2fbe
|
refs/heads/master
|
<repo_name>fatso83/shared-header-solution<file_sep>/README.md
# Demo: shared header component
To avoid flickering when going from one screen to another in a single-page app, it is useful to try and keep as much of the DOM intact as possible, basically common hierarcies, especially if a sub-tree is moderately expensive to render. One such example could be a `<Header>` component in an app: shared by many, but is on the outside of each screen for performance. [Stack overflow question on this topic](https://stackoverflow.com/q/47196930/200987).
There are two issues that is interesting to ponder:
1. How can we dynamically update the header along with the screen component - which is rendered elsewhere?
2. How can we pass event handlers to the header when it is located further up the hierarcy?
This demo tries to answer how to do both of these things. The first issue is basically solved using React Router: by having a router section in the header as well as in the screen component, we can update them both in sync with changes in the url. The problem of event handlers involves a bit more thinking, but is quite easy to solve in practice: we pass an object into both DOM hierarcies and mutate it to set new event handlers. The interface of such a shared object could be as simple as props we set a la `obj.myHandler = fooMyHandler`, but in our demo we have been a bit more fancy, ensuring the event handler name is recognized and that it actually expects an event as the parameter.
## Try it out
Check out [the running demo](https://fatso83.github.io/shared-header-solution/) or `npm start`
<file_sep>/src/App.js
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import React from "react";
import logo from "./logo.svg";
import "./App.css";
// This object exposes the header event handler API and
// can be passed down to sub-components to change what will
// happen in the header when that component has been mounted
const headerController = (() => {
// our list of handlers
const handlers = {
handleButtonClick() {},
handleInputFocus() {}
};
// the api we will expose to our clients; a setter (used by the non-header-components) and the handlers (used by the header)
const api = {
setHeaderHandler(name, fn) {
if (!fn || fn.length < 1) {
throw new TypeError(
"An event handler needs to be supplied: function(event) {...}"
);
}
if (!(name in handlers)) {
throw new TypeError("Unknown event handler supplied");
}
handlers[name] = fn;
}
};
// expose our handlers, but use a layer in-between
// This is to make it possible to directly reference a handler in the components
// while at the same time being sure that a change in the handler config will be reflected
for (const handler of Object.keys(handlers)) {
api[handler] = e => handlers[handler](e);
}
// Ensure no mutation will take place
return Object.freeze(api);
})();
function App() {
return (
<div className="App">
<Router basename={process.env.PUBLIC_URL}>
<Header controls={headerController} />
<Route path="/bar" render={() => <Bar controls={headerController} />} />
<Route path="/foo" render={() => <Foo controls={headerController} />} />
<Route path="/" exact render={() => <Link to="/bar">Go to bar</Link>} />
</Router>
<p>This is the end, my friend</p>
</div>
);
}
function Header({ controls: c }) {
return (
<header className="App-header">
<Link to="/">
<img src={logo} className="App-logo" alt="logo" />
</Link>
<Route
path="/bar"
render={() => (
<p>
BarHeader
<button onClick={c.handleButtonClick}>Click me!</button>
</p>
)}
/>
<Route
path="/foo"
render={() => (
<>
<p>FooHeader</p>
<input onFocus={e => c.handleInputFocus(e)} />
</>
)}
/>
<Route path="/" exact render={() => `La-${"la-".repeat(10)}la`} />
</header>
);
}
class Bar extends React.PureComponent {
constructor(props) {
super(props);
const { setHeaderHandler } = props.controls;
setHeaderHandler("handleButtonClick", event => {
alert("This is Barta!");
event.preventDefault();
});
setHeaderHandler("handleInputFocus", event => {
event.preventDefault();
});
}
render() {
return <Link to="/foo">Please focus!", said the Bar-tender</Link>;
}
}
let size = 10;
let addToggle = true;
function Foo(props) {
const { setHeaderHandler } = props.controls;
setHeaderHandler("handleInputFocus", event => {
const inputField = event.target;
inputField.value = "A Fooz pedal!";
inputField.style.border = "dashed 3px green";
// increase the font size on every event
const makeBig = e => {
size = addToggle ? size + 10 : size - 10;
e.target.style.fontSize = size + "px";
if (size > 50) addToggle = false;
if (size < 11) addToggle = true;
};
const removeMakeBig = () => {
inputField.removeEventListener("keyup", makeBig);
};
inputField.addEventListener("keyup", makeBig);
inputField.addEventListener("blur", removeMakeBig, { once: true }); // auto-cleanup
});
return <Link to="/">"I AM focused!", said the Foo-baller</Link>;
}
export default App;
|
75f07c0ac8ca8cf8885ce5690b01e030cac2d29c
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
fatso83/shared-header-solution
|
dbcddbbb426dd93ee5941e75e4bd523a3be9f374
|
6f23faa5190ef5a3098f3a074a04b74b0c3dc4e1
|
refs/heads/master
|
<file_sep>package com.hugoltsp.places.usecase;
import com.hugoltsp.places.data.db.mongo.document.Place;
import com.hugoltsp.places.data.db.mongo.repository.PlaceRepository;
import com.hugoltsp.places.domain.api.PlacesApiException;
import com.hugoltsp.places.domain.usecase.UpdatePlaceUseCaseDomain;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Slf4j
@Service
@AllArgsConstructor
public class UpdatePlaceUseCase {
private final PlaceRepository repository;
public void update(UpdatePlaceUseCaseDomain updatePlace) {
updatePlace.getCurrentPlace().map(place -> update(place, updatePlace)).ifPresentOrElse(repository::save, () -> {
throw new PlacesApiException("Could not find a place to update for the given id.");
});
}
private Place update(Place place, UpdatePlaceUseCaseDomain updatePlace) {
log.info("Updating place [{}], with content [{}]", place.getId(), updatePlace);
validate(updatePlace);
if (differsFrom(updatePlace.getCity(), place.getCity())) {
place.setCity(updatePlace.getCity());
}
if (differsFrom(updatePlace.getName(), place.getName())) {
place.setName(updatePlace.getName());
}
if (differsFrom(updatePlace.getState(), place.getState())) {
place.setState(updatePlace.getState());
}
return place;
}
private void validate(UpdatePlaceUseCaseDomain place) {
if (repository.findByNameAndCityAndState(place.getName(), place.getCity(), place.getState())
.map(Place::getId)
.filter(id -> !id.equals(place.getId()))
.isPresent()) {
throw new PlacesApiException("There's already a place with the same name city and state");
}
}
private boolean differsFrom(String value, String placeValue) {
return StringUtils.hasText(value) && !value.equals(placeValue);
}
}
<file_sep>version: '3.3'
services:
places-api:
image: hltspires/places-api
ports:
- 8080:8080
networks:
- places-api-network
depends_on:
- mongo
environment:
- SPRING_DATA_MONGODB_HOST=mongo
mongo:
image:
mongo:4.0.13
ports:
- 27017:27017
networks:
- places-api-network
volumes:
- data:/data/db
mongo-express:
image: mongo-express
ports:
- 8081:8081
networks:
- places-api-network
networks:
places-api-network:
volumes:
data:
driver: local<file_sep>package com.hugoltsp.places.infra;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.hugoltsp.places.domain.api.PlacesApiException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.stream.Collectors;
@Slf4j
@RestControllerAdvice
public class PlaceApiExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<?> exception(Exception e) {
log.error("Error.", e);
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
@ExceptionHandler(PlacesApiException.class)
public ResponseEntity<?> placesApiException(PlacesApiException e) {
log.error("Error.", e);
return ResponseEntity.badRequest().body(ErrorResponse.newErrorResponse(e.getMessage()));
}
@Override
protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
return ResponseEntity.badRequest()
.body(ex.getBindingResult()
.getFieldErrors()
.stream()
.map(ErrorResponse::newErrorResponse)
.collect(Collectors.toList()));
}
@Data
@AllArgsConstructor
@JsonInclude(Include.NON_NULL)
public static class ErrorResponse {
private final String field;
private final String message;
public static ErrorResponse newErrorResponse(FieldError fieldError) {
return new ErrorResponse(fieldError.getField(), fieldError.getDefaultMessage());
}
public static ErrorResponse newErrorResponse(String error) {
return new ErrorResponse(null, error);
}
}
}
<file_sep>package com.hugoltsp.places.usecase;
import com.hugoltsp.places.data.db.mongo.document.Place;
import com.hugoltsp.places.data.db.mongo.repository.PlaceRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.stereotype.Service;
import java.util.List;
@Slf4j
@Service
@AllArgsConstructor
public class FindPlaceByNameUseCase {
private final PlaceRepository repository;
public List<Place> find(String name) {
val places = repository.findByNameOrderByName(name);
log.info("Found [{}] places", places.size());
return places;
}
}
<file_sep>package com.hugoltsp.places.domain.api;
import lombok.Data;
@Data
public class UpdatePlaceRequest {
private String name;
private String city;
private String state;
}<file_sep>package com.hugoltsp.places.presenter.api;
import com.hugoltsp.places.presenter.mapper.UpdatePlaceUseCaseInputMapper;
import com.hugoltsp.places.usecase.UpdatePlaceUseCase;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
@SpringBootTest(classes = MockServletContext.class)
class UpdatePlaceControllerTest {
static final String URL = "/place";
@Mock
UpdatePlaceUseCase updatePlaceUseCase;
@Mock
UpdatePlaceUseCaseInputMapper updatePlaceUseCaseInputMapper;
MockMvc mockMvc;
@BeforeEach
public void setup() {
this.mockMvc = standaloneSetup(new UpdatePlaceController(updatePlaceUseCase, updatePlaceUseCaseInputMapper)).build();
}
@Test
void update_should_return_2xx() throws Exception {
//GIVEN
String anyJson = "{\n" +
"\t\"name\": \"<NAME>\",\n" +
"\t\"city\": \"Belo Horizonte\",\n" +
"\t\"state\": \"MG\"\n" +
"}";
//WHEN
mockMvc.perform(put(URL + "/" + "123")
.content(anyJson)
.contentType(APPLICATION_JSON))
.andExpect(status().isOk());
//THEN
verify(updatePlaceUseCaseInputMapper).map(any(), any());
}
}<file_sep>package com.hugoltsp.places.usecase;
import com.hugoltsp.places.data.db.mongo.document.Place;
import com.hugoltsp.places.data.db.mongo.repository.PlaceRepository;
import com.hugoltsp.places.domain.usecase.CreatePlaceUseCaseDomain;
import com.hugoltsp.places.domain.api.PlacesApiException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.stereotype.Service;
@Slf4j
@Service
@AllArgsConstructor
public class CreatePlaceUseCase {
private final PlaceRepository repository;
public Place create(CreatePlaceUseCaseDomain newPlace) {
log.info("Creating place [{}]", newPlace);
validate(newPlace);
return repository.save(createPlace(newPlace));
}
private Place createPlace(CreatePlaceUseCaseDomain newPlace) {
val place = new Place();
place.setState(newPlace.getState());
place.setCity(newPlace.getCity());
place.setName(newPlace.getName());
return place;
}
private void validate(CreatePlaceUseCaseDomain newPlace) {
if (repository.findByNameAndCityAndState(newPlace.getName(), newPlace.getCity(), newPlace.getState()).isPresent()) {
throw new PlacesApiException("There's already a place pointing to the same address.");
}
}
}
<file_sep>package com.hugoltsp.places.domain.usecase;
import com.hugoltsp.places.data.db.mongo.document.Place;
import lombok.Data;
import java.util.Optional;
@Data
public class UpdatePlaceUseCaseDomain {
private final Optional<Place> currentPlace;
private final String id;
private final String name;
private final String city;
private final String state;
}
<file_sep>package com.hugoltsp.places.data.db.mongo.repository;
import com.hugoltsp.places.data.db.mongo.document.Place;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
import java.util.Optional;
public interface PlaceRepository extends CrudRepository<Place, String> {
Optional<Place> findByNameAndCityAndState(String name, String city, String state);
List<Place> findByNameOrderByName(String name);
}
<file_sep>#### how to build & run
run mvn `mvn install` in the solution folder in order to build and run all the unit tests,
and then run `java -jar target/places-api-0.0.1.jar`, or simply use `mvn spring-boot:run`, that should do as well.
### alternatively you can use docker-compose to pull and fire up the whole application
if you prefer to use docker, just run `docker-compose up`, there's already an image
based on this application on dockerhub so you won't need to build anything if you choose this alternative.
### testing
you can use swagger or import the `places-api.postman_collection.json` postman collection
file, it has a few request samples that you can use to play around with the application.
I've also included a Mongo Express container on the compose.yml in order to peek the persisted data.
* swagger -> http://localhost:8080/swagger-ui.html
* mongo express -> http://localhost:8081
### tools used
* SdkMan
* Java 11 (Zulu11.35+15-CA)
* Apache Maven 3.6.0
* MongoDB
* Mongo Express
* Docker version 1.13.1, build 092cba3
* Deepin 15.11 OS
cheers :)<file_sep>package com.hugoltsp.places.domain.usecase;
import lombok.Data;
@Data
public class CreatePlaceUseCaseDomain {
private final String name;
private final String city;
private final String state;
}
<file_sep>package com.hugoltsp.places.presenter.mapper;
import com.hugoltsp.places.domain.usecase.CreatePlaceUseCaseDomain;
import com.hugoltsp.places.domain.api.CreatePlaceRequest;
import org.springframework.stereotype.Component;
@Component
public class CreatePlaceUseCaseInputMapper {
public CreatePlaceUseCaseDomain map(CreatePlaceRequest request) {
return new CreatePlaceUseCaseDomain(request.getName(), request.getCity(), request.getState());
}
}
<file_sep>package com.hugoltsp.places.domain.api;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public class PlaceResponse {
private final String id;
private final String name;
private final String state;
private final String city;
private final String slug;
}
<file_sep>package com.hugoltsp.places.usecase;
import com.hugoltsp.places.data.db.mongo.document.Place;
import com.hugoltsp.places.data.db.mongo.repository.PlaceRepository;
import com.hugoltsp.places.domain.api.PlacesApiException;
import com.hugoltsp.places.domain.usecase.CreatePlaceUseCaseDomain;
import lombok.val;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*;
@SpringBootTest
class CreatePlaceUseCaseTest {
@InjectMocks
CreatePlaceUseCase subject;
@Mock
PlaceRepository repository;
@Captor
ArgumentCaptor<Place> captor;
@Test
void should_create_a_new_place() {
// GIVEN
val newPlace = new CreatePlaceUseCaseDomain(
"Big Kahuna",
"São Paulo",
"SP"
);
// WHEN
subject.create(newPlace);
// THEN
verify(repository).findByNameAndCityAndState(newPlace.getName(), newPlace.getCity(), newPlace.getState());
verify(repository).save(captor.capture());
assertThat(newPlace.getCity()).isEqualTo(captor.getValue().getCity());
assertThat(newPlace.getName()).isEqualTo(captor.getValue().getName());
assertThat(newPlace.getState()).isEqualTo(captor.getValue().getState());
}
@Test
void should_throw_exception_when_place_conflicts_with_existing_one() {
// GIVEN
val newPlace = new CreatePlaceUseCaseDomain(
"Big Kahuna",
"São Paulo",
"SP"
);
// WHEN
when(repository.findByNameAndCityAndState(newPlace.getName(), newPlace.getCity(), newPlace.getState()))
.thenReturn(Optional.of(new Place()));
// THEN
assertThrows(PlacesApiException.class, () -> subject.create(newPlace));
verify(repository, never()).save(any());
}
}
|
f6c38b84b298d1712427e0fcb18be1b09a3e2afc
|
[
"Markdown",
"Java",
"YAML"
] | 14
|
Java
|
hugoltsp/quero-ser-clickbus
|
0a4069e8401f0822e581db26c008df07795396a7
|
89e962843de88e0fe54feaff96172fa639fe27aa
|
refs/heads/master
|
<file_sep>import React from 'react'
import {storiesOf} from '@storybook/react'
import Dropdown from '.'
const items = [
{id: 'all', value: 'All time'},
{id: 'last', value: 'Last month'},
{id: 'yes', value: 'Yesterday'},
]
storiesOf('Dropdown', module)
.add('default', () => (
<Dropdown items={items} selectedItem={'all'} />
))
<file_sep>export const GET_OFFERS_REQUEST = 'GET_OFFERS_REQUEST'
export const getOffersRequest = () => ({
type: GET_OFFERS_REQUEST,
})
export const GET_OFFERS_SUCCESS = 'GET_OFFERS_SUCCESS'
export const getOffersSuccess = offers => ({
type: GET_OFFERS_SUCCESS,
payload: { offers },
})
export const GET_OFFERS_FAIL = 'GET_OFFERS_FAIL'
export const getOffersFail = err => ({
type: GET_OFFERS_FAIL,
payload: { err },
})
export const GET_USER_OFFERS_REQUEST = 'GET_USER_OFFERS_REQUEST'
export const getUserOffersRequest = () => ({
type: GET_USER_OFFERS_REQUEST,
})
export const GET_USER_OFFERS_SUCCESS = 'GET_USER_OFFERS_SUCCESS'
export const getUserOffersSuccess = offers => ({
type: GET_USER_OFFERS_SUCCESS,
payload: { offers },
})
export const GET_USER_OFFERS_FAIL = 'GET_USER_OFFERS_FAIL'
export const getUserOffersFail = err => ({
type: GET_USER_OFFERS_FAIL,
payload: { err },
})
export const TRACK_OFFER_REQUEST = 'TRACK_OFFER_REQUEST'
export const trackOfferRequest = offerId => ({
type: TRACK_OFFER_REQUEST,
payload: { offerId },
})
export const TRACK_OFFER_SUCCESS = 'TRACK_OFFER_SUCCESS'
export const trackOfferSuccess = () => ({
type: TRACK_OFFER_SUCCESS,
})
export const TRACK_OFFER_FAIL = 'TRACK_OFFER_FAIL'
export const trackOfferFail = err => ({
type: TRACK_OFFER_FAIL,
payload: { err },
})
export const COMPLETE_OFFER_REQUEST = 'COMPLETE_OFFER_REQUEST'
export const completeOfferRequest = offerId => ({
type: COMPLETE_OFFER_REQUEST,
payload: { offerId },
})
export const COMPLETE_OFFER_SUCCESS = 'COMPLETE_OFFER_SUCCESS'
export const completeOfferSuccess = () => ({
type: COMPLETE_OFFER_SUCCESS,
})
export const COMPLETE_OFFER_FAIL = 'COMPLETE_OFFER_FAIL'
export const completeOfferFail = err => ({
type: COMPLETE_OFFER_FAIL,
payload: { err },
})
export const CANCEL_OFFER_REQUEST = 'CANCEL_OFFER_REQUEST'
export const cancelOfferRequest = offerId => ({
type: CANCEL_OFFER_REQUEST,
payload: { offerId },
})
export const CANCEL_OFFER_SUCCESS = 'CANCEL_OFFER_SUCCESS'
export const cancelOfferSuccess = () => ({
type: CANCEL_OFFER_SUCCESS,
})
export const CANCEL_OFFER_FAIL = 'CANCEL_OFFER_FAIL'
export const cancelOfferFail = err => ({
type: CANCEL_OFFER_FAIL,
payload: { err },
})
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, size } from 'styled-theme'
import SimplePopup from '../SimplePopup'
const Title = styled.h3`
font-size: ${size('textSubtitle')};
color: ${palette('text', 0)};
`
const Text = styled.p`
font-size: ${size('textTitle')};
color: ${palette('text', 0)};
line-height: 20px;
`
const Item = styled.span`
color: ${palette('main', 0)};
`
const Retailer = styled.span`
font-weight :bold;
`
const ShoppingItemMobilePopup = ({ onClose, title, retailer }) => {
return (
<SimplePopup onClose={onClose}>
<Title>You can win:</Title>
<Text><Item>{title}</Item> which was bought from <Retailer>{retailer}</Retailer></Text>
</SimplePopup>
)
}
ShoppingItemMobilePopup.propTypes = {
onClose: PropTypes.func,
title: PropTypes.string,
retailer: PropTypes.string,
}
export default ShoppingItemMobilePopup
<file_sep>import { take, put, call, fork } from 'redux-saga/effects'
import fetch from '../../services/api'
import {
GET_NEW_NOTIFICATIONS_AMOUNT_REQUEST, getNewNotificationsAmountSuccess, getNewNotificationsAmountFail,
GET_NOTIFICATIONS_REQUEST, getNotificationsSuccess, getNotificationsFail,
MARK_NOTIFICATIONS_AS_READ_REQUEST, markNotificationsAsReadSuccess, markNotificationsAsReadFail,
} from './actions'
export function* getNewNotificationsAmount() {
try {
const { NotifsCount } = yield call(fetch, { endpoint: 'notification/getnewsitenotifscount' })
yield put(getNewNotificationsAmountSuccess(NotifsCount))
} catch (e) {
yield put(getNewNotificationsAmountFail(e))
}
}
export function* watchGetNewNotificationsAmount() {
while (true) {
yield take(GET_NEW_NOTIFICATIONS_AMOUNT_REQUEST)
yield call(getNewNotificationsAmount)
}
}
export function* getNotifications(data) {
try {
const { Notifications } = yield call(fetch, { endpoint: 'notification/getsitenotifs', data })
yield put(getNotificationsSuccess(Notifications))
} catch (e) {
yield put(getNotificationsFail(e))
}
}
export function* watchGetNotifications() {
while (true) {
const { payload } = yield take(GET_NOTIFICATIONS_REQUEST)
yield call(getNotifications, payload)
}
}
export function* markNotificationsAsRead(data) {
try {
const result = yield call(fetch, { endpoint: 'notification/marksitenotifsasread', isPost: true, data })
yield put(markNotificationsAsReadSuccess(result))
} catch (e) {
yield put(markNotificationsAsReadFail(e))
}
}
export function* watchMarkNotificationsAsRead() {
while (true) {
const { payload } = yield take(MARK_NOTIFICATIONS_AS_READ_REQUEST)
yield call(markNotificationsAsRead, payload)
}
}
export default function* () {
yield fork(watchGetNewNotificationsAmount)
yield fork(watchGetNotifications)
yield fork(watchMarkNotificationsAsRead)
}
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, size, font } from 'styled-theme'
import { ButtonMain, UsersDone } from 'components'
const Holder = styled.div`
background-color: ${palette('grey', 0)};
padding: 30px 30px 10px;
border-radius: 3px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
height: 350px;
max-width: 500px;
`
const Image = styled.img`
width: 95px;
height: 95px;
border-radius: 50%;
overflow: hidden;
outline: none;
`
const Title = styled.h2`
font-family: ${font('main')};
font-size: ${size('textTitle')};
`
const Description = styled.p`
font-family: ${font('main')};
font-size: ${size('textParagraph')};
`
const OfferPanel = ({ id, image, title, description, usersDone, usersDoneTotal, earnAmount, currency = 'pts', onOfferClick }) => {
const earnBtnText = currency === 'pts' ? `${earnAmount} ${currency}` : `${currency}${earnAmount}`
const onClick = () => onOfferClick({ id, image, title, description })
return (
<Holder>
<Image src={image} />
<Title>{title}</Title>
<Description>{description}</Description>
<ButtonMain onClick={onClick}>Earn {earnBtnText}</ButtonMain>
<UsersDone users={usersDone} totalAmount={usersDoneTotal} />
</Holder>
)
}
OfferPanel.propTypes = {
id: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
description: PropTypes.string,
usersDone: PropTypes.array,
usersDoneTotal: PropTypes.number,
earnAmount: PropTypes.number.isRequired,
currency: PropTypes.string,
onOfferClick: PropTypes.func.isRequired,
}
export default OfferPanel
<file_sep>export const shadows = {
wide: 'box-shadow: 1px 2px 6px -1px rgba(0,0,0,0.4);',
wideGreen: 'box-shadow: 1px 2px 6px -1px rgba(17, 119, 20, 0.4);',
tiny: 'box-shadow: 1px 1px 1px rgba(0,0,0,0.2);',
}
<file_sep>import React, { Component } from 'react'
import PageTemplate from '../../templates/PageTemplate'
import PageDummy from '../../atoms/PageDummy'
class ActivitiesPage extends Component {
/* eslint-disable no-underscore-dangle */
componentDidMount() {
if (window._DGPublic && window._DGPublic.openWidgetView) {
window.setTimeout(() => {
window._DGPublic.openWidgetView('activities')
}, 600)
}
}
componentWillUnmount() {
if (window._DGPublic && window._DGPublic.closeWidget) {
window._DGPublic.closeWidget()
}
}
render() {
return (
<PageTemplate>
<PageDummy />
</PageTemplate>
)
}
}
export default ActivitiesPage
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { font, size, palette } from 'styled-theme'
const Holder = styled.div`
width: 100%;
height: 42px;
border-bottom: 1px solid ${palette('grey', 2)};
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: flex-end;
`
const itemCSS = css`
color: ${palette('text', 0)};
border-bottom: 4px solid transparent;
`
const activeItemCSS = css`
color: ${palette('main', 0)};
border-bottom: 4px solid ${palette('main', 0)};
`
const Item = styled.div`
font-family: ${font('main')};
font-size: ${size('textRegular')};
font-weight: 400;
cursor: pointer;
padding: 0 15px;
line-height: 32px;
transition: border-bottom 0.3s ease;
${props => props.isActive ? activeItemCSS : itemCSS};
`
Item.propTypes = {
isActive: PropTypes.bool,
}
const FilterHorizontalList = ({ className, items, activeItemID, onItemClick }) => {
const reactItems = items.map((item) => {
const { id, value } = item
const onClick = () => onItemClick(id)
return (
<Item isActive={id === activeItemID} onClick={onClick} key={id}>{value}</Item>
)
})
return (
<Holder className={className}>
{reactItems}
</Holder>
)
}
FilterHorizontalList.propTypes = {
className: PropTypes.string,
items: PropTypes.arrayOf(PropTypes.shape(
{
id: PropTypes.string,
value: PropTypes.string,
},
)).isRequired,
activeItemID: PropTypes.string.isRequired,
onItemClick: PropTypes.func.isRequired,
}
export default FilterHorizontalList
<file_sep>import {
IS_USER_AUTHORIZED,
EXTERNAL_PROFILE_UPDATE,
getUserRequest,
} from './actions'
export default store => next => (action) => {
const { payload, type } = action
if (type === IS_USER_AUTHORIZED) {
return next({
...action,
payload: {
isUserAuthorized: window._DGPublic.isAuthorized(),
},
})
}
if (type === EXTERNAL_PROFILE_UPDATE && window._DGPublic.isAuthorized()) {
store.dispatch(getUserRequest())
}
return next(action)
}
<file_sep>import styled from 'styled-components'
import PropTypes from 'prop-types'
import { imagesPath } from '../../../config'
function getLogoPath(props) {
if (props.white) return `${imagesPath}/logo_white.png`
return `${imagesPath}/logo.png`
}
const Logo = styled.img.attrs({
src: props => getLogoPath(props),
})`
height: auto;
max-width: 100%;
`
Logo.propTypes = {
white: PropTypes.bool,
}
export default Logo
<file_sep>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { fromGeneral } from 'store/selectors'
import { VideoOfferPopup } from 'components'
import { videoOfferClose } from 'store/actions'
import { getURLParameter } from '../../services/helpers'
let playbackInterval
const youtubeShortRXP = /youtu\.be\/([^?]+)/
class VideoOfferPopupContainer extends Component {
constructor(props) {
super(props)
this.onPlayerReady = this.onPlayerReady.bind(this)
this.onPlayerStateChange = this.onPlayerStateChange.bind(this)
this.onPlayerError = this.onPlayerError.bind(this)
this.state = {
shownInterval: 0,
player: null,
startTime: null,
lastPauseTime: null,
pausesDuration: 0,
}
}
componentDidMount() {
const { videoOffer: { url } } = this.props
this.startingPlayer(url)
}
componentWillUnmount() {
if (this.playbackInterval) window.clearInterval(this.playbackInterval)
}
onPlayerError(e) {
window.console.log(e)
// this.closePopup();
}
onPlayerReady(e) {
// const { popup, trackActions } = this.props
// // e.target.playVideo();
// trackActions.postTrackOffer(popup.earnId)
}
onPlayerStateChange(e) {
const { videoOffer } = this.props
const { player } = this.state
const { startTime, lastPauseTime, pausesDuration } = this.state
const watchedDuration = Date.now() - startTime - pausesDuration
if (e.data === 0) {
// Video has finished
if (player.getDuration) {
if (player.getDuration() * 1000 > watchedDuration + 2000) {
// Video was forwarded
window.console.warn('You need to watch the full video to get points')
} else {
// Video normally watched and completed
// trackActions.postCompleteOffer(popup.earnId)
window.console.info('Completing an offer here')
}
} else {
// trackActions.postCompleteOffer(popup.earnId)
window.console.info('Completing an offer here')
}
this.closePopup()
} else if (e.data === 1) {
// Video is playing
if (!startTime) this.setState({ startTime: Date.now() })
if (lastPauseTime) {
this.setState({
pausesDuration: pausesDuration + (Date.now() - lastPauseTime),
})
}
// this.setState({
// betweenPauses: (new Date()).getTime()
// });
this.videoInterval()
} else if (e.data === 2) {
// Video is paused
this.setState({ lastPauseTime: Date.now() })
// fullDuration += ((new Date()).getTime() - betweenPauses);
// this.setState({fullDuration});
if (this.playbackInterval) clearInterval(this.playbackInterval)
}
}
startingPlayer(videoUrl) {
let videoID = getURLParameter('v', videoUrl)
if (!videoID) {
videoID = videoUrl.match(youtubeShortRXP)
if (videoID.length) videoID = videoID[1]
}
this.setState({
player: new YT.Player('video-offer', {
height: '300',
width: '100%',
videoId: videoID,
playerVars: {
controls: 0,
rel: 0,
enablejsapi: 1,
origin: window.document.origin,
fs: 0,
modestbranding: 1, // player that does not show a YouTube logo
},
events: {
onReady: this.onPlayerReady,
onStateChange: this.onPlayerStateChange,
onError: this.onPlayerError,
},
}),
})
window.setTimeout(() => {
window.player = this.state.player
}, 300)
}
closePopup() {
const { player } = this.state
player.destroy()
this.setState({
shownInterval: 0,
player: null,
})
this.props.videoOfferClose()
if (this.playbackInterval) window.clearInterval(this.playbackInterval)
}
videoInterval() {
const { player } = this.state
if (player.getDuration && player.getCurrentTime) {
this.playbackInterval = setInterval(() => {
this.setState({
shownInterval: Math.floor(player.getDuration() - player.getCurrentTime()),
})
}, 1000)
}
}
render() {
return (
<VideoOfferPopup
onClose={this.props.videoOfferClose}
/>
)
}
}
VideoOfferPopupContainer.propTypes = {
videoOfferClose: PropTypes.func,
videoOffer: PropTypes.object,
}
const mapStateToProps = state => ({
videoOffer: fromGeneral.getVideoOffer(state),
})
const mapDispatchToProps = dispatch => ({
videoOfferClose: () => dispatch(videoOfferClose()),
})
export default connect(mapStateToProps, mapDispatchToProps)(VideoOfferPopupContainer)
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { font, palette, size } from 'styled-theme'
import { iconsPath } from '../../../config'
const Select = styled.select`
font-family: ${font('main')};
font-size: ${size('textSubtitle')};
color: ${palette('main', 0)};
border: none;
background: url('${iconsPath}/icon-caret-double.svg') no-repeat;
background-position: right center;
padding-right: 15px;
outline: none;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
`
const Dropdown = ({ className, items, onChange, selectedItem }) => {
const options = items.map(item => (
<option
key={item.id || item.value}
value={item.id || item.value}
>{item.value}</option>
))
return <Select className={className} onChange={onChange} value={selectedItem}>{options}</Select>
}
Dropdown.propTypes = {
className: PropTypes.string,
items: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string,
value: PropTypes.string.isRequired,
})).isRequired,
onChange: PropTypes.func.isRequired,
selectedItem: PropTypes.string,
}
export default Dropdown
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, size } from 'styled-theme'
import { ContainerLimited, ProfileElementAuthorized, HeaderMobile } from 'components'
import MenuItemNotifications from './MenuItemNotifications'
import MenuItemSearch from './MenuItemSearch'
import NotificationsContainer from '../../../containers/NotificationsContainer'
import SideMenu from '../../organisms/SideMenu'
import { iconsPath } from '../../../config'
import { fadeIn } from '../../themes/keyframes'
const HEADER_HEIGHT = 115
const SIDE_MARGIN = 24
const Logo = styled.img`
width: auto;
display: inline-block;
max-height: 100%;
max-width: 90%;
cursor: pointer;
`
const LogoHolder = styled.div`
padding-bottom: 20px;
`
const MenuItem = styled.div`
font-size: ${size('menuItems')};
text-transform: uppercase;
font-weight: 900;
padding: 0 15px 20px;
color: ${palette('main', 0)};
cursor: pointer;
transition: border-bottom 0.2s ease;
border-bottom: 4px solid ${props => props.isActive ? palette('main', 0) : 'transparent'};
&:hover {
border-bottom: 4px solid ${palette('main', 2)};
}
`
MenuItem.propTypes = {
isActive: PropTypes.bool,
}
const SignInItem = styled(MenuItem)`
padding-bottom: 0;
transition: opacity 0.3s ease;
&:hover {
border-bottom: 4px solid transparent;
opacity: 0.6;
}
`
const Menu = styled.div`
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
padding: 0;
margin: 0;
list-style: none;
& > * {
margin-left: ${SIDE_MARGIN}px;
}
`
const HeaderOuter = styled.header`
background-color: ${palette('grey', 0)};
box-shadow: 2px 0 5px rgba(0,0,0,0.4);
width: 100%;
position: relative;
z-index: 16000;
`
const DesktopHeader = styled.div`
display: flex;
flex-direction: row;
align-items: flex-end;
justify-content: space-between;
height: ${HEADER_HEIGHT}px;
position: relative;
${size('mobileMediaQuery')} {
display: none;
}
`
const RightItemsHolder = styled.div`
display: flex;
flex-direction: row;
justify-content: flex-end;
align-items: flex-end;
padding-bottom: 26px;
& > *:not(:last-child) {
margin-right: ${SIDE_MARGIN}px;
}
`
const LeftItemsHolder = styled.div`
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: flex-end;
`
const NotificationsPanel = styled(NotificationsContainer)`
position: absolute;
top: 100%;
right: 0;
`
const ShowMoreMenuItem = styled.div`
position: relative;
width: 60px;
height: 45px;
background: url('${iconsPath}/icon-caret-down-rounded.svg') no-repeat center;
background-size: 32px;
background-position-x: center;
background-position-y: -4px;
cursor: pointer;
margin-left: 10px;
border-bottom: 4px solid ${props => props.isActive ? palette('main', 0) : 'transparent'};
&:hover {
border-bottom: 4px solid ${palette('main', 2)};
& > * {
display: block;
}
}
`
const ShowMoreDropDown = styled.div`
display: none;
position: absolute;
background-color: ${palette('grey', 0)};
padding: 14px 30px 5px;
border-radius: 8px;
top: 0;
left: 50%;
transform: translate(-50%, 63px);
box-shadow: 2px 3px 6px rgba(0,0,0,0.3);
animation: ${fadeIn} 0.3s ease forwards 1;
&:before {
content: '';
position: absolute;
top: 0;
left: 50%;
transform: translate(-50%, -50%) rotateZ(45deg);
width: 20px;
height: 20px;
border-radius: 4px;
background-color: ${palette('grey', 0)};
}
&:after {
content: '';
position: absolute;
top: -20px;
height: 30px;
width: 100%;
left: 0;
}
& > * {
font-size: 16px;
padding: 10px 0 4px;
display: inline-block;
margin-bottom: 9px;
}
`
const MENU_ITEMS = [
{ name: 'Dashboard', link: '/' },
{ name: 'Shop', link: 'shop', isMainHeader: true, isMobileHeader: true },
{ name: 'Play', link: 'play', isMainHeader: true, isMobileHeader: true },
{ name: 'Earn', link: 'earn', isMainHeader: true, isMobileHeader: true },
{ name: 'Earn points', link: 'earn' },
{ name: 'Collect', link: 'collect' },
{ name: 'Draws', link: 'draws' },
{ name: 'Leaderboard', link: 'leaderboard' },
{ name: 'Score Predictor', link: 'score-predictor' },
// { name: 'Activities', link: 'activities' },
]
const DROPDOWN_MENU_ITEMS = [
{ name: 'Earn points', link: 'earn' },
{ name: 'Collect', link: 'collect' },
{ name: 'Draws', link: 'draws' },
{ name: 'Activities', link: 'activities' },
{ name: 'Leaderboard', link: 'leaderboard' },
{ name: 'Score Predictor', link: 'score-predictor' },
]
const getMenuItems = ({ activeMenuItem, onMenuItemClick, isDesktop }) => (
MENU_ITEMS.filter(item => isDesktop ? item.isMainHeader : item.isMobileHeader).map(item => (
<MenuItem
key={item.name}
isActive={activeMenuItem === item.link}
onClick={() => {
onMenuItemClick(item.link)
}}
>{item.name}</MenuItem>),
)
)
const getMenuDropDownItems = ({ activeMenuItem, onMenuItemClick }) => (
DROPDOWN_MENU_ITEMS.map(item => (
<MenuItem
key={item.name}
isActive={activeMenuItem === item.link}
onClick={() => {
onMenuItemClick(item.link)
}}
>{item.name}</MenuItem>),
)
)
const Header = ({
brandLogo,
userAuthorized: user,
activeMenuItem,
onMenuItemClick,
onMobileMenuOpen,
onMobileMenuClose,
isMobileMenuOpened,
unreadNotifications,
onNotificationsClick,
isNotificationsPopupShown,
isUserAuthorized,
}) => {
const userElement = user ? (
<ProfileElementAuthorized
name={user.name}
image={user.image}
points={user.points}
credits={user.credits}
onMenuItemClick={onMenuItemClick}
/>
) : null
const onLogoClick = () => onMenuItemClick('/')
const notifications = isNotificationsPopupShown && (
<NotificationsPanel />
)
const notificationElement = (
<MenuItemNotifications
counter={unreadNotifications}
onClick={onNotificationsClick}
/>
)
const desktopRightHolder = isUserAuthorized ? (
<RightItemsHolder>
<MenuItemSearch />
{notificationElement}
{userElement}
</RightItemsHolder>
) : (
<RightItemsHolder>
<MenuItemSearch />
<SignInItem
onClick={() => {
onMenuItemClick('profile')
}}
>Sign In</SignInItem>
</RightItemsHolder>
)
const desktopHeader = () => (
<DesktopHeader>
<LeftItemsHolder>
<LogoHolder>
<Logo src={brandLogo} onClick={onLogoClick} />
</LogoHolder>
<Menu>
{getMenuItems({ activeMenuItem, onMenuItemClick, isDesktop: true })}
<ShowMoreMenuItem>
<ShowMoreDropDown>
{getMenuDropDownItems({ activeMenuItem, onMenuItemClick })}
</ShowMoreDropDown>
</ShowMoreMenuItem>
</Menu>
</LeftItemsHolder>
{desktopRightHolder}
</DesktopHeader>
)
const mobileHeader = () => (
<HeaderMobile
notificationIcon={notificationElement}
onMenuClick={onMobileMenuOpen}
menuItems={getMenuItems({ activeMenuItem, onMenuItemClick })}
/>
)
return (
<HeaderOuter>
<ContainerLimited>
{desktopHeader()}
{mobileHeader()}
{notifications}
</ContainerLimited>
{isMobileMenuOpened && (
<SideMenu
onMenuClose={onMobileMenuClose}
user={user}
menuItems={MENU_ITEMS.filter(item => !item.isMobileHeader)}
onMenuItemClick={onMenuItemClick}
isUserAuthorized={isUserAuthorized}
/>
)}
</HeaderOuter>
)
}
Header.propTypes = {
brandLogo: PropTypes.string,
userAuthorized: PropTypes.object,
activeMenuItem: PropTypes.string,
onMenuItemClick: PropTypes.func,
onMobileMenuOpen: PropTypes.func.isRequired,
onMobileMenuClose: PropTypes.func.isRequired,
isMobileMenuOpened: PropTypes.bool,
unreadNotifications: PropTypes.number,
onNotificationsClick: PropTypes.func,
isNotificationsPopupShown: PropTypes.bool,
isUserAuthorized: PropTypes.bool,
}
export default Header
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, size } from 'styled-theme'
import Dropdown from '../../atoms/Dropdown'
const HEIGHT = 50
const Wrapper = styled.div`
text-align: center;
`
const Holder = styled.div`
display: inline-flex;
flex-direction: row;
justify-content: center;
align-items: center;
height: ${HEIGHT}px;
border: 1px solid ${palette('grey', 1)};
border-radius: 4px;
width: 100%;
max-width: 600px;
`
const CategoriesHolder = styled.div`
padding: 0 10px;
flex-grow: 1;
height: 100%;
background-color: ${palette('grey', 0)};
display: flex;
align-items: center;
justify-content: center;
`
const Categories = styled(Dropdown)`
min-width: 90%;
`
const Search = styled.input.attrs({
placeholder: 'Search for retailer..',
})`
background-color: rgba(255,255,255,0.7);
box-sizing: border-box;
height: ${HEIGHT}px;
line-height: ${HEIGHT}px;
border: none;
outline: none;
border-left: 1px solid ${palette('grey', 1)};
padding: 0 10px;
width: 80%;
font-size: ${size('textRegular')};
transition: background-color 0.3s ease;
&:focus {
background-color: ${palette('grey', 0)};
}
::placeholder {
color: ${palette('main', 0)};
font-size: 16px;
}
`
const RetailerSearch = ({
className,
categories,
selectedCategory,
onCategoryChange,
onSearch,
searchValue,
}) => {
return (
<Wrapper>
<Holder className={className}>
<CategoriesHolder>
<Categories
items={categories}
selectedItem={selectedCategory}
onChange={onCategoryChange}
/>
</CategoriesHolder>
<Search value={searchValue} onChange={onSearch} />
</Holder>
</Wrapper>
)
}
RetailerSearch.propTypes = {
className: PropTypes.string,
categories: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string,
value: PropTypes.string.isRequired,
})).isRequired,
selectedCategory: PropTypes.string,
onCategoryChange: PropTypes.func.isRequired,
onSearch: PropTypes.func.isRequired,
searchValue: PropTypes.string,
}
export default RetailerSearch
<file_sep>import React from 'react'
import styled from 'styled-components'
import { storiesOf } from '@storybook/react'
import DashboardPanel from '.'
const SomeBody = styled.div``
const FooterElement = styled.div``
const Footer = () => {
return (
<FooterElement>
This is footer
</FooterElement>
)
}
storiesOf('Dashboard Panel', module)
.add('default', () => (
<DashboardPanel
style={{minHeight: '500px'}}
title={'Some header'}
footer={<Footer />}
>
<SomeBody>This is body!!!</SomeBody>
</DashboardPanel>
))
<file_sep>import {
GET_DRAWS_REQUEST,
GET_DRAWS_SUCCESS,
GET_DRAWS_FAIL,
} from './actions'
import { initialState } from './selectors'
const userNormalizer = user => ({
id: user.UserId,
name: user.UserName,
image: user.ImageUrl,
})
export default (state = initialState, { type, payload }) => {
switch (type) {
case GET_DRAWS_REQUEST:
return {
...state,
isLoading: true,
}
case GET_DRAWS_SUCCESS:
return {
...state,
isLoading: false,
draws: payload.draws.map(draw => ({
id: draw.DrawId,
startDate: draw.StartDate,
endDate: draw.EndDate,
isDrawn: draw.IsDrawn,
minLevel: draw.MinimalUserLevel,
title: draw.Prize.Title,
description: draw.Prize.Description,
image: draw.Prize.ImageUrl,
winner: draw.Winner ? userNormalizer(draw.Winner) : null,
playersCount: draw.TotalPlayersCount,
recentPlayers: draw.RecentPlayers.map(user => userNormalizer(user)),
})),
}
case GET_DRAWS_FAIL:
return {
...state,
isLoading: false,
error: payload.err,
}
default:
return { ...state }
}
}
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import DashboardPanel from '../../molecules/DashboardPanel'
import SimplePanelFooter from '../../atoms/SimplePanelFooter'
const WinnnerAvatarsHolder = styled.div`
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
align-items: flex-start;
`
const DashboardAllWinnersPanel = ({ className, winners, onClose }) => {
const footer = <SimplePanelFooter onClick={onClose}>Close</SimplePanelFooter>
return (
<DashboardPanel className={className} title={'All winners'} footer={footer}>
<WinnnerAvatarsHolder>{winners}</WinnnerAvatarsHolder>
</DashboardPanel>
)
}
DashboardAllWinnersPanel.propTypes = {
className: PropTypes.string,
winners: PropTypes.array,
onClose: PropTypes.func.isRequired,
}
export default DashboardAllWinnersPanel
<file_sep>import {
GET_ALL_ACTIVITIES_REQUEST, GET_ALL_ACTIVITIES_SUCCESS, GET_ALL_ACTIVITIES_FAIL,
GET_PERSONAL_ACTIVITIES_REQUEST, GET_PERSONAL_ACTIVITIES_SUCCESS, GET_PERSONAL_ACTIVITIES_FAIL,
} from './actions'
import { initialState } from './selectors'
export default (state = initialState, { type, payload }) => {
switch (type) {
case GET_ALL_ACTIVITIES_REQUEST:
case GET_PERSONAL_ACTIVITIES_REQUEST:
return {
...state,
isLoading: true,
}
case GET_ALL_ACTIVITIES_SUCCESS:
case GET_PERSONAL_ACTIVITIES_SUCCESS:
return {
...state,
isLoading: false,
activities: payload.activities.map(act => ({
...act,
id: act.Id,
date: act.Date,
outflow: act.Direction.toLowerCase() === 'outflow',
type: act.ActivityType,
})).sort((a, b) => new Date(b.date) - new Date(a.date)),
}
case GET_ALL_ACTIVITIES_FAIL:
case GET_PERSONAL_ACTIVITIES_FAIL:
return {
...state,
isLoading: false,
error: payload.err,
}
default:
return { ...state }
}
}
<file_sep>const items = [
{
image: 'https://picsum.photos/200?image=15',
title: 'Cool red phone',
price: 256,
retailer: 'Apple.com',
points: 125,
odds: '1/32',
id: 'a1',
},
{
image: 'https://picsum.photos/200?image=16',
title: 'Light bulbs which are always turned on',
price: 28,
retailer: 'LightBulbs',
points: 30,
odds: '3/7',
id: 'a2',
},
{
image: 'https://picsum.photos/200?image=17',
title: 'Cool red phone',
price: 24,
retailer: 'Apple.com',
points: 15,
odds: '1/3',
id: 'a3',
},
{
image: 'https://picsum.photos/200?image=18',
title: 'Light bulbs which are always turned on',
price: 735,
retailer: 'LightBulbs',
points: 157,
odds: '1/24',
id: 'a4',
},
{
image: 'https://picsum.photos/200?image=19',
title: 'Cool red phone',
price: 256,
retailer: 'Apple.com',
points: 125,
odds: '1/32',
id: 'a5',
},
{
image: 'https://picsum.photos/200?image=20',
title: 'Light bulbs which are always turned on',
price: 15,
retailer: 'LightBulbs',
points: 30,
odds: '1/14',
id: 'a6',
},
{
image: 'https://picsum.photos/200?image=21',
title: 'Cool red phone',
price: 256,
retailer: 'Apple.com',
points: 125,
odds: '1/32',
id: 'a7',
},
{
image: 'https://picsum.photos/200?image=22',
title: 'Light bulbs which are always turned on',
price: 15,
retailer: 'LightBulbs',
points: 30,
odds: '1/14',
id: 'a8',
},
]
export default items
<file_sep>import {
initialState,
} from './selectors'
import {
OFFER_POPUP_OPEN,
OFFER_POPUP_CLOSE,
VIDEO_OFFER_OPEN,
VIDEO_OFFER_CLOSE,
SIDE_MENU_OPEN,
SIDE_MENU_CLOSE,
} from './actions'
export default (state = initialState, { type, payload = {} }) => {
switch (type) {
case OFFER_POPUP_OPEN:
return {
...state,
offerPopup: {
title: payload.title,
image: payload.image,
description: payload.description,
url: payload.url,
details: payload.details,
},
}
case OFFER_POPUP_CLOSE:
return {
...state,
offerPopup: null,
}
case VIDEO_OFFER_OPEN:
return {
...state,
videoOffer: {
url: payload.url,
},
}
case VIDEO_OFFER_CLOSE:
return {
...state,
videoOffer: null,
}
case SIDE_MENU_OPEN:
return {
...state,
isSideMenuOpened: true,
}
case SIDE_MENU_CLOSE:
return {
...state,
isSideMenuOpened: false,
}
default:
return { ...state }
}
}
<file_sep>import styled from 'styled-components'
import { palette, size } from 'styled-theme'
const WinProductsButton = styled.button`
-webkit-appearance: none;
cursor: pointer;
text-transform: uppercase;
background: ${palette('buttonGradient', 0)};
background: -moz-linear-gradient(top, ${palette('buttonGradient', 0)} 0%, ${palette('buttonGradient', 1)} 100%);
background: -webkit-gradient(left top, left bottom, color-stop(0%, ${palette('buttonGradient', 0)}), color-stop(100%, ${palette('buttonGradient', 1)}));
background: -webkit-linear-gradient(top, ${palette('buttonGradient', 0)} 0%, ${palette('buttonGradient', 1)} 100%);
background: -o-linear-gradient(top, ${palette('buttonGradient', 0)} 0%, ${palette('buttonGradient', 1)} 100%);
background: -ms-linear-gradient(top, ${palette('buttonGradient', 0)} 0%, ${palette('buttonGradient', 1)} 100%);
background: linear-gradient(to bottom, ${palette('buttonGradient', 0)} 0%, ${palette('buttonGradient', 1)} 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='${palette('buttonGradient', 0)}', endColorstr='${palette('buttonGradient', 1)}', GradientType=0 );
height: 100%;
border-radius: 6px;
font-size: ${size('textRegular')};
color: ${palette('grey', 0)};
width: 100%;
outline: 0;
border: 0;
border-bottom: 5px solid ${palette('buttonGradient', 2)};
transition: background 0.2s ease,
border-bottom 0.2s ease;
&:hover {
background: ${palette('buttonGradient', 1)};
background: -moz-linear-gradient(top, ${palette('buttonGradient', 1)} 0%, ${palette('buttonGradient', 1)} 100%);
background: -webkit-gradient(left top, left bottom, color-stop(0%, ${palette('buttonGradient', 1)}), color-stop(100%, ${palette('buttonGradient', 1)}));
background: -webkit-linear-gradient(top, ${palette('buttonGradient', 1)} 0%, ${palette('buttonGradient', 1)} 100%);
background: -o-linear-gradient(top, ${palette('buttonGradient', 1)} 0%, ${palette('buttonGradient', 1)} 100%);
background: -ms-linear-gradient(top, ${palette('buttonGradient', 1)} 0%, ${palette('buttonGradient', 1)} 100%);
background: linear-gradient(to bottom, ${palette('buttonGradient', 1)} 0%, ${palette('buttonGradient', 1)} 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='${palette('buttonGradient', 1)}', endColorstr='${palette('buttonGradient', 1)}', GradientType=0 );
border-bottom: 0 solid ${palette('buttonGradient', 2)};
}
&:active {
background: ${palette('buttonGradient', 2)};
background: -moz-linear-gradient(top, ${palette('buttonGradient', 2)} 0%, ${palette('buttonGradient', 2)} 100%);
background: -webkit-gradient(left top, left bottom, color-stop(0%, ${palette('buttonGradient', 2)}), color-stop(100%, ${palette('buttonGradient', 2)}));
background: -webkit-linear-gradient(top, ${palette('buttonGradient', 2)} 0%, ${palette('buttonGradient', 2)} 100%);
background: -o-linear-gradient(top, ${palette('buttonGradient', 2)} 0%, ${palette('buttonGradient', 2)} 100%);
background: -ms-linear-gradient(top, ${palette('buttonGradient', 2)} 0%, ${palette('buttonGradient', 2)} 100%);
background: linear-gradient(to bottom, ${palette('buttonGradient', 2)} 0%, ${palette('buttonGradient', 2)} 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='${palette('buttonGradient', 2)}', endColorstr='${palette('buttonGradient', 2)}', GradientType=0 );
border-bottom: 0 solid ${palette('buttonGradient', 2)};
}
${size('mobileMediaQuery')} {
box-sizing: border-box;
padding: 6px 12px;
margin-bottom: 4px;
}
`
export default WinProductsButton
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, size, font } from 'styled-theme'
import NotificationItem from './NotificationItem'
const Holder = styled.div`
max-width: 400px;
width: 100%;
max-height: 400px;
background-color: ${palette('grey', 0)};
box-shadow: 1px 1px 4px rgba(0,0,0,0.3);
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
`
const ItemsList = styled.div`
flex-grow: 1;
overflow-y: auto;
width: 100%;
`
const Footer = styled.div`
background-color: ${palette('grey', 0)};
border-top: 1px solid ${palette('grey', 2)};
font-size: ${size('textRegular')};
color: ${palette('main', 0)};
line-height: 30px;
width: 100%;
text-align: center;
cursor: pointer;
`
const Empty = styled.div`
color: ${palette('text', 0)};
font-size: ${size('textRegular')};
padding: 30px 0;
`
const NotificationsPanel = ({ className, notifications, onMarkAllAsRead, onMarkItemAsRead, onItemClick, isLoading }) => {
const noText = isLoading ? 'Loading...' : 'Currently you have no notifications'
const noNotifications = <Empty>{noText}</Empty>
const footer = notifications.some(item => item.isUnread) && (
<Footer onClick={onMarkAllAsRead}>Mark all as read</Footer>
)
const notificationPanels = notifications.map(item => (
<NotificationItem key={item.id} {...item} onClick={onItemClick} onMarkAsRead={onMarkItemAsRead} />
))
return (
<Holder className={className}>
{
notifications.length > 0
? (
<ItemsList>
{notificationPanels}
</ItemsList>
)
: noNotifications
}
{footer}
</Holder>
)
}
NotificationsPanel.propTypes = {
className: PropTypes.string,
notifications: PropTypes.array,
onMarkAllAsRead: PropTypes.func,
onMarkItemAsRead: PropTypes.func,
onItemClick: PropTypes.func,
isLoading: PropTypes.bool,
}
export default NotificationsPanel
<file_sep>import { take, put, call, fork } from 'redux-saga/effects'
import { eventChannel } from 'redux-saga'
import fetch from '../../services/api'
import {
GET_USER_REQUEST, getUserSuccess, getUserFail,
externalSignIn, externalSignOut, externalProfileUpdate,
} from './actions'
export function* getUser() {
try {
const profile = yield call(fetch, { endpoint: 'user/me' })
yield put(getUserSuccess(profile))
} catch (e) {
yield put(getUserFail(e))
}
}
export function* watchGetUser() {
while (true) {
yield take(GET_USER_REQUEST)
yield call(getUser)
}
}
const listenToPostMessage = () => {
return eventChannel((dispatch) => {
window.addEventListener('message', (ev) => {
if (ev.origin === window.location.origin && ev.data.fromWidget) {
if (ev.data.fromWidget === 'in') {
// sign in was done in the widget
dispatch(externalSignIn())
} else if (ev.data.fromWidget === 'out') {
// sign out was done in the widget
dispatch(externalSignOut())
} else if (ev.data.fromWidget === 'update') {
// profile info was changed in the widget, retrieving new info
dispatch(externalProfileUpdate())
}
}
})
return () => {
}
})
}
export function* watchPostMessageListen() {
const channel = yield call(listenToPostMessage)
while (true) {
const action = yield take(channel)
yield put(action)
}
}
export default function* () {
yield fork(watchPostMessageListen)
yield fork(watchGetUser)
}
<file_sep>export const initialState = { categories: [], retailers: [], error: null, isCategoriesLoading: false, isRetailersLoading: false }
export const getCashbackCategories = (state = initialState) => state.categories
export const getCashbackRetailers = (state = initialState) => state.retailers
<file_sep>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { libsPath, imagesPath } from '../../../config'
import Wheel from './Wheel'
import getSpinWheelSettings from './wheel-settings'
import Spin2WinWheel from './Spin2WinWheel'
import { absoluteMiddleCSS } from '../../themes/style-snippets'
import { ctaCircularGradient, lightGreyCircularGradient } from '../../themes/gradients'
const requiredPlugins = [
'https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.2/TweenMax.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.2/utils/Draggable.min.js',
`${libsPath}/ThrowPropsPlugin.min.js`,
'https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/plugins/TextPlugin.min.js',
]
const tweenMaxIsLoaded = (callback) => {
// if (window.TweenMax && callback) callback()
const interval = window.setInterval(() => {
if (window.TweenMax) {
window.clearInterval(interval)
if (callback) {
window.setTimeout(callback, 1000)
}
}
}, 200)
}
// const wheelSettings = {
// 'colorArray': [
// '#364C62',
// '#F1C40F',
// '#E67E22',
// '#E74C3C',
// '#ECF0F1',
// '#95A5A6',
// '#16A085',
// '#27AE60',
// '#2980B9',
// '#8E44AD',
// '#2C3E50',
// '#F39C12',
// '#D35400',
// '#C0392B',
// '#BDC3C7',
// '#1ABC9C',
// '#2ECC71',
// '#E87AC2',
// '#3498DB',
// '#9B59B6',
// '#7F8C8D',
// ],
//
// 'segmentValuesArray': [
// {
// 'probability': 50,
// 'type': 'image',
// 'value': 'https://picsum.photos/200?image=10',
// text: 'Main Prize',
// wheelTextOffsetY: 30,
// 'win': true,
// 'resultText': 'You won a holiday!',
// 'userData': {
// 'score': 1000000
// },
// mainPrize: true,
// },
// {
// 'probability': 0,
// 'type': 'image',
// 'value': 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/35984/tip_sqr.svg',
// text: 'prize title',
// wheelTextOffsetY: 30,
// wheelImageSize: 120,
// 'win': false,
// 'resultText': 'NOBODY LIKES A SQUARE :(',
// 'userData': { 'score': 0 },
// },
// {
// 'probability': 0,
// 'type': 'image',
// 'value': 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/35984/tip_oct.svg',
// 'win': false,
// 'resultText': 'LOSE WITH AN OCTAGON!',
// 'userData': { 'score': 0 },
// },
// {
// 'probability': 0,
// 'type': 'image',
// 'value': 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/35984/tip_triangle.svg',
// 'win': true,
// 'resultText': 'A TRIANGLE MEANS A PRIZE!',
// 'userData': { 'score': 40 },
// },
// {
// 'probability': 0,
// 'type': 'image',
// 'value': 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/35984/tip_circle.svg',
// 'win': false,
// 'resultText': 'A CIRCLE IS A WINNER!',
// 'userData': { 'score': 0 },
// },
// {
// 'probability': 0,
// 'type': 'image',
// 'value': 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/35984/tip_hex.svg',
// 'win': false,
// 'resultText': 'A HEXAGON IS A LOSE',
// 'userData': { 'score': 0 },
// },
// {
// 'probability': 50,
// 'type': 'string',
// 'value': 'LOSE ALL',
// 'win': false,
// 'resultText': 'YOU LOSE EVERYTHING!',
// 'userData': { 'score': 2 },
// },
// ],
//
// 'svgWidth': 720,
// 'svgHeight': 800,
// 'wheelStrokeColor': '#D0BD0C',
// 'wheelStrokeWidth': 18,
// 'wheelSize': 700,
// 'wheelTextOffsetY': 80,
// 'wheelTextColor': '#EDEDED',
// 'wheelTextSize': '1.6em',
// 'wheelImageOffsetY': 40,
// 'wheelImageSize': 100,
// 'centerCircleSize': 0,
// 'centerCircleStrokeColor': '#F1DC15',
// 'centerCircleStrokeWidth': 12,
// 'centerCircleFillColor': '#EDEDED',
// 'segmentStrokeColor': '#E2E2E2',
// 'segmentStrokeWidth': 4,
// 'centerX': 360,
// 'centerY': 400,
// 'hasShadows': false,
// 'numSpins': 4,
// 'spinDestinationArray': [],
// 'minSpinDuration': 6,
// 'gameOverText': 'I HOPE YOU ENJOYED SPIN2WIN WHEEL.<br>NOW GO AND <a href=\'https://codecanyon.net/item/spin2win-wheel-spin-it-2-win-it/16337656?ref=chrisgannon\'>BUY IT!</a> :)',
// 'invalidSpinText': 'INVALID SPIN. PLEASE SPIN AGAIN.',
// 'introText': 'YOU HAVE TO<br>SPIN IT <span style=\'color:#F282A9;\'>2</span> WIN IT!',
// 'hasSound': true,
// 'gameId': '9a0232ec06bc431114e2a7f3aea03bbe2164f1aa',
// 'clickToSpin': true,
// 'spinDirection': 'ccw',
//
// spinSound: `${audioPath}/tick.mp3`,
// }
const WheelSVG = styled(Wheel)`
width: 100%;
height: 100%;
position: relative;
z-index: 5;
margin-top: -64px;
`
const PADDING = 26
const getWheelHolderCSS = (size) => {
if (size) {
return css`
width: ${size}px;
height: ${size}px;
`
}
return css `
width: 490px;
height: 490px;
`
}
const WheelHolder = styled.div`
${props => getWheelHolderCSS(props.size)};
display: flex;
align-items: center;
justify-content: center;
padding: 0 ${PADDING}px;
box-sizing: border-box;
border-radius: 50%;
position: relative;
${ctaCircularGradient};
`
WheelHolder.propTypes = {
size: PropTypes.number,
}
const WheelBackground = styled.div`
${absoluteMiddleCSS};
width: calc(100% - ${(PADDING * 2) + 12}px);
height: calc(100% - ${(PADDING * 2) + 12}px);
border-radius: 50%;
z-index: 1;
${lightGreyCircularGradient};
`
class WinWheelSVG extends Component {
constructor(props) {
super(props)
this.scripts = []
requiredPlugins.forEach((src) => {
const script = document.createElement('script')
script.src = src
this.scripts.push(script)
})
this.scripts.forEach(script => document.body.appendChild(script))
this.onWinCallback = this.onWinCallback.bind(this)
}
componentDidMount() {
this.props.onRef(this)
tweenMaxIsLoaded(() => {
this.onWinWheelUpdate()
})
}
componentWillReceiveProps(nextProps) {
const { winWheelItems: w1 } = this.props
const w2 = nextProps.winWheelItems
if (w1.length && w2.length) {
if (w1[0].id !== w2[0].id) {
this.onWinWheelUpdate(w2)
}
}
}
componentWillUnmount() {
this.scripts.forEach(script => document.body.removeChild(script))
}
onWheelSpin(segmetToWin) {
this.wheel.start(segmetToWin)
}
onWinWheelUpdate(winItems) {
const { winWheelItems } = this.props
const mainPrizeFrame = `${imagesPath}/main_prize_frame_overlay.svg`
const mainPrizeFrameOnTop = true
Spin2WinWheel.reset()
this.wheel = new Spin2WinWheel()
this.wheel.init({
data: getSpinWheelSettings({
segments: winItems || winWheelItems,
mainPrizeFrame,
mainPrizeFrameOnTop,
}),
onResult: this.onWinCallback,
onError: err => console.log('onError:', err),
})
}
onWinCallback(segment) {
this.props.onWheelSpinComplete(segment)
}
render() {
const { className, size } = this.props
return (
<WheelHolder className={className} size={size}>
<WheelBackground />
<WheelSVG />
</WheelHolder>
)
}
}
WinWheelSVG.propTypes = {
className: PropTypes.string,
size: PropTypes.number,
winWheelItems: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
text: PropTypes.string,
image: PropTypes.string,
}),
),
onRef: PropTypes.func.isRequired,
onWheelSpinComplete: PropTypes.func.isRequired,
}
export default WinWheelSVG
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { size, palette } from 'styled-theme'
const HEADER_HEIGHT = 60
const MenuBtnLine = styled.div`
width: 100%;
height: 4px;
background-color: ${palette('main', 0)};
border-radius: 3px;
`
const HeaderHolder = styled.div`
position: relative;
height: ${HEADER_HEIGHT}px;
flex-direction: row;
justify-content: space-between;
align-items: center;
display: none;
${size('mobileMediaQuery')} {
display: flex;
}
`
const MenuBtn = styled.div`
width: 40px;
height: 40px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
padding: 8px 6px;
`
const MenuItemsHolder = styled.div`
display: flex;
flex-grow: 1;
justify-content: space-around;
margin: 0 10px -5px;
& > * {
padding: 0 5px;
}
`
const HeaderMobile = ({ notificationIcon, onMenuClick, menuItems }) => {
return (
<HeaderHolder>
<MenuBtn onClick={onMenuClick}>
<MenuBtnLine />
<MenuBtnLine />
<MenuBtnLine />
</MenuBtn>
<MenuItemsHolder>{menuItems}</MenuItemsHolder>
{notificationIcon}
</HeaderHolder>
)
}
HeaderMobile.propTypes = {
notificationIcon: PropTypes.node,
onMenuClick: PropTypes.func.isRequired,
menuItems: PropTypes.array,
}
export default HeaderMobile
<file_sep>const merge = require('lodash/merge')
const script = document.getElementById('main-app')
const scriptSrc = script && script.getAttribute('src')
const basePath = scriptSrc ? scriptSrc.substring(0, scriptSrc.lastIndexOf('/')) : '.'
const apiKey = window.apiKey || '431F8A01-D40A-4369-A730-2FFAA93FB2EA'
const apiPrefix = window.apiPrefix || 'http://spr-api-test.cloudapp.net/core/v1/'
const config = {
all: {
env: process.env.NODE_ENV || 'development',
isDev: process.env.NODE_ENV !== 'production',
basename: process.env.PUBLIC_PATH,
isBrowser: typeof window !== 'undefined',
apiUrl: 'https://jsonplaceholder.typicode.com',
iconsPath: `${basePath}/images/icons`,
imagesPath: `${basePath}/images`,
videosPath: `${basePath}/video`,
audioPath: `${basePath}/audio`,
libsPath: `${basePath}/lib`,
xdmTunnel: `${apiPrefix}xdm/tunnel`,
apiKey,
apiPrefix,
basePath,
},
test: {},
development: {},
production: {
apiUrl: 'https://jsonplaceholder.typicode.com',
},
}
module.exports = merge(config.all, config[config.all.env])
<file_sep>export const initialState = {}
export const isActive = (state = initialState) => state.isActive
export const getFoundationUrl = (state = initialState) => state.foundationUrl
<file_sep>import { IFRAME_MESSAGE_SEND, GET_APP_SUCCESS } from './actions'
const middleware = store => next => (action) => {
const { payload, type } = action
if (type === IFRAME_MESSAGE_SEND) {
const { message } = payload
window.parent.postMessage(JSON.stringify(message), '*')
}
if (type === GET_APP_SUCCESS) {
const { app } = payload
return next({
...action,
payload: {
app: {
title: app.AppTitle,
foundation: app.FoundationName,
foundationUrl: app.FoundationRewardsSiteUrl,
isActive: app.IsActive,
},
},
})
}
return next(action)
}
export default middleware
<file_sep>import {
GET_NEW_NOTIFICATIONS_AMOUNT_REQUEST, GET_NEW_NOTIFICATIONS_AMOUNT_SUCCESS, GET_NEW_NOTIFICATIONS_AMOUNT_FAIL,
GET_NOTIFICATIONS_REQUEST, GET_NOTIFICATIONS_SUCCESS, GET_NOTIFICATIONS_FAIL,
MARK_NOTIFICATIONS_AS_READ_REQUEST, MARK_NOTIFICATIONS_AS_READ_SUCCESS, MARK_NOTIFICATIONS_AS_READ_FAIL,
} from './actions'
import { initialState } from './selectors'
export default (state = initialState, { type, payload = {} }) => {
switch (type) {
case GET_NOTIFICATIONS_REQUEST:
return {
...state,
isLoading: true,
}
case GET_NEW_NOTIFICATIONS_AMOUNT_SUCCESS:
return {
...state,
unread: payload.amount,
}
case GET_NOTIFICATIONS_SUCCESS:
return {
...state,
notifications: payload.notifications.map(n => ({
...n,
id: n.Id,
isUnread: !n.IsRead,
date: n.Date,
type: n.NotificationType,
})),
isLoading: false,
}
case GET_NOTIFICATIONS_FAIL:
return {
...state,
error: payload.err,
isLoading: false,
}
case MARK_NOTIFICATIONS_AS_READ_SUCCESS:
return {
...state,
}
default:
return {
...state,
}
}
}
<file_sep>var SCREEN_WIDTH = window.innerWidth,
SCREEN_HEIGHT = window.innerHeight,
mousePos = {
x: 400,
y: 300,
},
// create canvas
canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
particles = [],
rockets = [],
MAX_PARTICLES = 400,
colorCode = 0
function clearCanvas(canvasHolder = {}) {
// clear canvas
// context.fillStyle = 'rgba(0, 0, 0, 0.01)'
context.fillStyle = 'transparent'
context.fillRect(
0,
0,
canvasHolder.innerWidth || canvasHolder.clientWidth || SCREEN_WIDTH,
canvasHolder.innerHeight || canvasHolder.clientHeight || SCREEN_HEIGHT,
)
}
function totalClearCanvas(canvasHolder = {}) {
context.clearRect(
0,
0,
canvasHolder.innerWidth || canvasHolder.clientWidth || SCREEN_WIDTH,
canvasHolder.innerHeight || canvasHolder.clientHeight || SCREEN_HEIGHT,
)
}
let canvasHolder = null
function checkCanvasSizeOnResize() {
if (canvasHolder) {
canvas.width = canvasHolder.innerWidth || canvasHolder.clientWidth
canvas.height = canvasHolder.innerHeight || canvasHolder.clientHeight
clearCanvas(canvasHolder)
}
}
function onWindowResizeStart(holder) {
canvasHolder = holder
window.addEventListener('resize', checkCanvasSizeOnResize)
}
function onWindowResizeStop() {
window.removeEventListener('resize', checkCanvasSizeOnResize)
canvasHolder = null
}
function loop() {
// update screen size
// if (SCREEN_WIDTH != window.innerWidth) {
// canvas.width = SCREEN_WIDTH = window.innerWidth
// }
// if (SCREEN_HEIGHT != window.innerHeight) {
// canvas.height = SCREEN_HEIGHT = window.innerHeight
// }
// if (canvasHolder) {
// canvas.width = canvasHolder.innerWidth || canvasHolder.clientWidth
// canvas.height = canvasHolder.innerHeight || canvasHolder.clientHeight
// }
clearCanvas()
const existingRockets = []
for (let i = 0; i < rockets.length; i++) {
// update and render
rockets[i].update()
rockets[i].render(context)
// calculate distance with Pythagoras
const distance = Math.sqrt(Math.pow(mousePos.x - rockets[i].pos.x, 2) + Math.pow(mousePos.y - rockets[i].pos.y, 2))
// random chance of 1% if rockets is above the middle
const randomChance = rockets[i].pos.y < ((SCREEN_HEIGHT * 2) / 3) ? (Math.random() * 100 <= 1) : false
/* Explosion rules
- 80% of screen
- going down
- close to the mouse
- 1% chance of random explosion
*/
if (rockets[i].pos.y < SCREEN_HEIGHT / 5 || rockets[i].vel.y >= 0 || distance < 50 || randomChance) {
rockets[i].explode()
} else {
existingRockets.push(rockets[i])
}
}
rockets = existingRockets
var existingParticles = []
for (var i = 0; i < particles.length; i++) {
particles[i].update()
// render and save particles that can be rendered
if (particles[i].exists()) {
particles[i].render(context)
existingParticles.push(particles[i])
}
}
// update array with existing particles - old particles should be garbage collected
particles = existingParticles
while (particles.length > MAX_PARTICLES) {
particles.shift()
}
}
function Particle(pos) {
this.pos = {
x: pos ? pos.x : 0,
y: pos ? pos.y : 0,
}
this.vel = {
x: 0,
y: 0,
}
this.shrink = 0.99
this.size = 2
this.resistance = 1
this.gravity = 0
this.flick = false
this.alpha = 1
this.fade = 0
this.color = 0
}
Particle.prototype.update = function () {
// apply resistance
this.vel.x *= this.resistance
this.vel.y *= this.resistance
// gravity down
this.vel.y += this.gravity
// update position based on speed
this.pos.x += this.vel.x
this.pos.y += this.vel.y
// shrink
this.size *= this.shrink
// fade out
this.alpha -= this.fade
}
Particle.prototype.render = function (c) {
if (!this.exists()) {
return
}
c.save()
c.globalCompositeOperation = 'lighter'
var x = this.pos.x,
y = this.pos.y,
r = this.size / 2
var gradient = c.createRadialGradient(x, y, 0.1, x, y, r)
gradient.addColorStop(0.1, 'rgba(255,255,255,' + this.alpha + ')')
gradient.addColorStop(0.8, 'hsla(' + this.color + ', 100%, 50%, ' + this.alpha + ')')
gradient.addColorStop(1, 'hsla(' + this.color + ', 100%, 50%, 0.1)')
c.fillStyle = gradient
c.beginPath()
c.arc(this.pos.x, this.pos.y, this.flick ? Math.random() * this.size : this.size, 0, Math.PI * 2, true)
c.closePath()
c.fill()
c.restore()
}
Particle.prototype.exists = function () {
return this.alpha >= 0.1 && this.size >= 1
}
function Rocket(x) {
Particle.apply(this, [{
x: x,
y: SCREEN_HEIGHT,
}])
this.explosionColor = 0
}
Rocket.prototype = new Particle()
Rocket.prototype.constructor = Rocket
Rocket.prototype.explode = function () {
var count = (Math.random() * 10) + 80
for (var i = 0; i < count; i++) {
var particle = new Particle(this.pos)
var angle = Math.random() * Math.PI * 2
// emulate 3D effect by using cosine and put more particles in the middle
var speed = Math.cos((Math.random() * Math.PI) / 2) * 20
particle.vel.x = Math.cos(angle) * speed
particle.vel.y = Math.sin(angle) * speed
particle.size = 7
particle.gravity = 0.25
particle.resistance = 0.9
particle.shrink = (Math.random() * 0.05) + 0.93
particle.flick = true
particle.color = this.explosionColor
particles.push(particle)
}
}
Rocket.prototype.render = function (c) {
if (!this.exists()) {
return
}
c.save()
c.globalCompositeOperation = 'lighter'
var x = this.pos.x,
y = this.pos.y,
r = this.size / 2
var gradient = c.createRadialGradient(x, y, 0.1, x, y, r)
gradient.addColorStop(0.1, 'rgba(255, 255, 255 ,' + this.alpha + ')')
// gradient.addColorStop(1, 'rgba(0, 0, 0, ' + this.alpha + ')')
gradient.addColorStop(1, 'rgba(0, 0, 0, ' + 0.03 + ')')
c.fillStyle = gradient
c.beginPath()
c.arc(this.pos.x, this.pos.y, this.flick ? Math.random() * this.size / 2 + this.size / 2 : this.size, 0, Math.PI * 2, true)
c.closePath()
c.fill()
c.restore()
}
function launchFrom(x) {
if (rockets.length < 10) {
const rocket = new Rocket(x)
rocket.explosionColor = Math.floor((Math.random() * 360) / 10) * 10
rocket.vel.y = (Math.random() * -3) - 8
rocket.vel.x = (Math.random() * 6) - 5
rocket.size = 6
rocket.shrink = 0.999
rocket.gravity = 0.01
rockets.push(rocket)
}
}
function launch() {
const xPos = Math.floor(Math.random() * ((document.body.clientWidth / 2) + 10)) + ((document.body.clientWidth / 2) - 10)
launchFrom(xPos)
}
function launchWithDelay(init) {
const singleRocketTime = 5000
const rocketAmount = Math.floor(Math.random() * 1) + 2
let alreadyLaunched = 0
if (init) launch()
const seriesInterval = setInterval(() => {
if (alreadyLaunched >= rocketAmount) {
clearInterval(seriesInterval)
totalClearCanvas()
setTimeout(launchWithDelay, 300)
} else {
launch()
alreadyLaunched += 1
}
}, singleRocketTime)
}
let loopInterval
export function startFireworks({ holder = document.body, width, height }) {
holder.appendChild(canvas)
canvas.width = width || holder.innerWidth || holder.clientWidth
canvas.height = height || holder.innerHeight || holder.clientHeight
launchWithDelay(true)
loopInterval = setInterval(loop, 1000 / 70)
onWindowResizeStart(holder)
}
export function stopFireworks() {
clearInterval(loopInterval)
onWindowResizeStop()
}
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { size, palette, font } from 'styled-theme'
const Holder = styled.div`
width: 100%;
height: 100%;
background-color: ${palette('grey', 0)};
border-radius: 2px;
box-shadow: 1px 1px 3px rgba(0,0,0,0.2);
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: flex-start;
text-align: left;
padding: 0 20px;
box-sizing: border-box;
position: relative;
overflow: hidden;
`
const Title = styled.h3`
font-family: ${font('main')};
font-size: ${size('textTitle')};
color: ${palette('text', 0)};
margin: 0;
padding: 0 10px;
box-sizing: border-box;
height: 60px;
line-height: 60px;
width: 100%;
border-bottom: 1px solid ${palette('grey', 2)};
flex-shrink: 0;
font-weight: 400;
`
const Body = styled.div`
flex-grow: 1;
width: 100%;
height: 100%;
`
const Footer = styled.div`
flex-shrink: 0;
height: 80px;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
width: 100%;
`
const DashboardPanel = ({ className, title, children, footer }) => {
return (
<Holder className={className}>
<Title>{title}</Title>
<Body>{children}</Body>
<Footer>{footer}</Footer>
</Holder>
)
}
DashboardPanel.propTypes = {
className: PropTypes.string,
title: PropTypes.string,
children: PropTypes.node,
footer: PropTypes.node,
}
export default DashboardPanel
<file_sep>import styled from 'styled-components'
import { palette, font, size } from 'styled-theme'
const SimplePanelFooter = styled.div`
font-family: ${font('main')};
color: ${palette('text', 0)};
font-size: ${size('textRegular')};
text-align: center;
cursor: pointer;
`
export default SimplePanelFooter
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { palette, size, font } from 'styled-theme'
import { AvatarCircular } from 'components'
import { imagesPath } from '../../../config'
const getTextColorCSS = ({isPrimary, lightSkin} = {}) => {
if (isPrimary && lightSkin) return css`color: ${palette('grey', 0)};`
if (isPrimary) return css`color: ${palette('text', 0)};`
if (lightSkin) return css`color: ${palette('grey', 2)};`
return css`color: ${palette('main', 0)};`
}
const AvatarCircularRestyled = styled(AvatarCircular)`
transition: opacity 0.2s ease;
&:hover {
opacity: 0.6;
}
`
const AvatarHolder = styled.div`
display: flex;
flex-direction: row;
align-items: flex-end;
justify-content: flex-start;
cursor: pointer;
`
const InfoHolder = styled.div`
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
margin-left: 10px;
`
const BottomInfoHolder = styled.div`
display: flex;
flex-direction: row;
justify-content: space-around;
`
const AvatarText = styled.h4`
font-family: ${font('main')};
font-size: ${size('menuItemsProfile')};
margin: 0;
padding: 0;
line-height: 18px;
${props => getTextColorCSS(props)};
transition: opacity 0.2s ease;
&:hover {
opacity: 0.6;
}
& + & {
margin-left: 4px;
}
`
const ProfileElementAuthorized = ({ className, name, image, points, credits, onMenuItemClick, lightSkin }) => {
const onUserClick = () => onMenuItemClick('profile')
const onPointsClick = () => onMenuItemClick('points')
const onCreditsClick = () => onMenuItemClick('credits')
return (
<AvatarHolder className={className}>
<AvatarCircularRestyled big image={image} onClick={onUserClick} />
<InfoHolder>
<AvatarText lightSkin={lightSkin} isPrimary onClick={onUserClick}>{name}</AvatarText>
<BottomInfoHolder>
<AvatarText lightSkin={lightSkin} onClick={onCreditsClick}>{credits} credits</AvatarText>
<AvatarText lightSkin={lightSkin}>|</AvatarText>
<AvatarText lightSkin={lightSkin} onClick={onPointsClick}>{points} points</AvatarText>
</BottomInfoHolder>
</InfoHolder>
</AvatarHolder>
)
}
ProfileElementAuthorized.propTypes = {
className: PropTypes.string,
name: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
points: PropTypes.number.isRequired,
credits: PropTypes.number.isRequired,
onMenuItemClick: PropTypes.func,
lightSkin: PropTypes.bool,
}
ProfileElementAuthorized.defaultProps = {
image: `${imagesPath}/face_temp.jpg`,
}
export default ProfileElementAuthorized
<file_sep>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { WinnersPanel } from 'components'
const TIME_FILTERS = [
{ id: 'all', value: 'All time' },
{ id: 'last_month', value: 'Last month' },
]
const RANK_FILTERS = [
{ id: 'highest', value: 'Highest' },
{ id: 'lowest', value: 'Lowest' },
]
const WINNERS = [
{ id: '1', image: 'https://picsum.photos/200?image=10' },
{ id: '2', image: 'https://picsum.photos/200?image=11' },
{ id: '3', image: 'https://picsum.photos/200?image=12' },
{ id: '4', image: 'https://picsum.photos/200?image=13' },
{ id: '5', image: 'https://picsum.photos/200?image=14' },
{ id: '6', image: 'https://picsum.photos/200?image=15' },
{ id: '7', image: 'https://picsum.photos/200?image=16' },
{ id: '8', image: 'https://picsum.photos/200?image=17' },
{ id: '9', image: 'https://picsum.photos/200?image=18' },
{ id: '10', image: 'https://picsum.photos/200?image=19' },
{ id: '11', image: 'https://picsum.photos/200?image=20' },
{ id: '12', image: 'https://picsum.photos/200?image=21' },
{ id: '13', image: 'https://picsum.photos/200?image=22' },
{ id: '14', image: 'https://picsum.photos/200?image=23' },
{ id: '15', image: 'https://picsum.photos/200?image=24' },
{ id: '16', image: 'https://picsum.photos/200?image=25' },
{ id: '17', image: 'https://picsum.photos/200?image=26' },
{ id: '18', image: 'https://picsum.photos/200?image=27' },
{ id: '19', image: 'https://picsum.photos/200?image=28' },
{ id: '20', image: 'https://picsum.photos/200?image=29' },
]
class DashboardWinnersContainer extends Component {
constructor(props) {
super(props)
this.state = {
selectedTimeFilter: TIME_FILTERS[0].id,
selectedRankFilter: RANK_FILTERS[0].id,
selectedWinnerId: null,
allWinnersShown: false,
}
this.onTimeFilterChange = this.onTimeFilterChange.bind(this)
this.onRankFilterChange = this.onRankFilterChange.bind(this)
this.onWinnerClick = this.onWinnerClick.bind(this)
this.onWinnerPanelClose = this.onWinnerPanelClose.bind(this)
this.onShowAllWinners = this.onShowAllWinners.bind(this)
this.onHideAllWinnersPanel = this.onHideAllWinnersPanel.bind(this)
}
onTimeFilterChange(ev) {
this.setState({ selectedTimeFilter: ev.target.value })
}
onRankFilterChange(ev) {
this.setState({ selectedRankFilter: ev.target.value })
}
onShowAllWinners() {
this.setState({ allWinnersShown: true })
}
onHideAllWinnersPanel() {
this.setState({ allWinnersShown: false })
}
onWinnerClick(winner) {
this.setState({ selectedWinnerId: winner })
}
onWinnerPanelClose() {
this.setState({ selectedWinnerId: null })
}
render() {
const { selectedTimeFilter, selectedRankFilter, selectedWinnerId, allWinnersShown } = this.state
return (
<WinnersPanel
timeFilters={TIME_FILTERS}
onTimeFilterChange={this.onTimeFilterChange}
selectedTimeFilter={selectedTimeFilter}
rankFilters={RANK_FILTERS}
onRankFilterChange={this.onRankFilterChange}
selectedRankFilter={selectedRankFilter}
winnersWheelTitle={'All time winners'}
usersAmount={340}
friendsWinnersPercent={70}
connectionsWinnersPercent={92}
friendsWinnersAmount={42}
connectionsWinnersAmount={118}
allWinnersAmount={160}
winners={WINNERS}
onWinnerClick={this.onWinnerClick}
selectedWinnerId={selectedWinnerId}
onWinnerPanelClose={this.onWinnerPanelClose}
onHideAllWinners={this.onHideAllWinnersPanel}
onShowAllWinners={this.onShowAllWinners}
allWinnersShown={allWinnersShown}
/>
)
}
}
export default DashboardWinnersContainer
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { font, size, palette } from 'styled-theme'
import { DashboardPanel, FilterHorizontalList } from 'components'
import ActivityItem from './ActivityItem'
import DashboardUserContainer from '../../../containers/DashboardUserContainer'
import { panelSlideUp } from '../../themes/keyframes'
const Footer = styled.div`
font-family: ${font('main')};
color: ${palette('text', 0)};
font-size: ${size('textRegular')};
text-align: center;
cursor: pointer;
`
const ItemsHolder = styled.div`
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
padding-top: 20px;
`
const InsideDashboardUserContainer = styled(DashboardUserContainer)`
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow-y: auto;
animation: ${panelSlideUp} 0.3s ease forwards 1;
z-index: 10;
`
const ActivitiesPanel = ({
filters, activeFilterID, onFilterClick,
onShowMoreClick,
onUserClick, selectedUserId, onUserPanelClose,
activities, userSelfImage, userSelfId,
}) => {
const footer = (
<Footer onClick={onShowMoreClick}>Show more activities</Footer>
)
const activityItems = activities.map(act => (
<ActivityItem
key={act.id}
onUserClick={onUserClick}
userSelfImage={userSelfImage}
userSelfId={userSelfId}
activity={act}
/>
))
return (
<DashboardPanel title={'Activities'} footer={footer}>
<FilterHorizontalList items={filters} onItemClick={onFilterClick} activeItemID={activeFilterID} />
<ItemsHolder>{activityItems}</ItemsHolder>
{selectedUserId && (
<InsideDashboardUserContainer
selectedUserId={selectedUserId}
onPanelClose={onUserPanelClose}
/>
)}
</DashboardPanel>
)
}
ActivitiesPanel.propTypes = {
filters: PropTypes.arrayOf(PropTypes.shape(
{
id: PropTypes.string,
value: PropTypes.string,
},
)).isRequired,
activeFilterID: PropTypes.string.isRequired,
onFilterClick: PropTypes.func.isRequired,
onShowMoreClick: PropTypes.func.isRequired,
selectedUserId: PropTypes.string.isRequired,
onUserClick: PropTypes.func.isRequired,
onUserPanelClose: PropTypes.func.isRequired,
activities: PropTypes.array,
userSelfImage: PropTypes.string,
userSelfId: PropTypes.string,
}
export default ActivitiesPanel
<file_sep>import React from 'react'
import { storiesOf } from '@storybook/react'
import WinnersWheel from '.'
storiesOf('Winners Wheel', module)
.add('default', () => (
<WinnersWheel
amount={1257}
primaryPercent={80}
secondaryPercent={90}
title={'All time winners'}
/>
))
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { palette, font, size } from 'styled-theme'
import PageTemplate from '../../templates/PageTemplate'
import ContainerLimited from '../../atoms/ContainerLimited'
import DashboardActivitiesContainer from '../../../containers/DashboardActivitiesContainer'
import DashboardWinnersContainer from '../../../containers/DashboardWinnersContainer'
import DashboardDrawsContainer from '../../../containers/DashboardDrawsContainer'
import DashboardActionsContainer from '../../../containers/DashboardActionsContainer'
const PageWrapper = styled.div`
background-color: ${palette('main', 0)};
padding-top: 50px;
${size('mobileMediaQuery')} {
padding-top: 0;
}
`
const Row = styled.div`
display: flex;
flex-direction: row;
justify-content: flex-start;
max-height: 70vh;
&:not(:first-child) {
margin-top: 10px;
}
& > *:not(:first-child) {
margin-left: 10px;
}
${size('mobileMediaQuery')} {
flex-direction: column;
max-height: none;
& > *:not(:first-child) {
margin-left: 0;
}
& > * {
margin-top: 10px;
margin-left: 0;
}
}
${size('smallLaptopMediaQuery')} {
max-height: none;
}
`
const getColOrderCSS = order => `order: ${order};`
const OneThirdCol = styled.div`
flex-grow: 1;
width: 100%;
display: flex;
flex-direction: column;
justify-content: space-between;
& > *:not(:first-child) {
margin-top: 10px;
}
${size('mobileMediaQuery')} {
${props => props.mobileOrder && getColOrderCSS(props.mobileOrder)};
}
`
OneThirdCol.propTypes = {
mobileOrder: PropTypes.number,
}
const FullHeightCol = styled.div`
height: 100%;
position: relative;
`
const HalfHeightCol = styled.div`
height: 100%;
`
const DashboardPage = () => {
return (
<PageTemplate>
<PageWrapper>
<ContainerLimited>
<Row>
<OneThirdCol mobileorder={0}>
<FullHeightCol>
<DashboardActivitiesContainer />
</FullHeightCol>
</OneThirdCol>
<OneThirdCol mobileOrder={-1}>
<FullHeightCol>
<DashboardWinnersContainer />
</FullHeightCol>
</OneThirdCol>
<OneThirdCol>
<HalfHeightCol>
<DashboardDrawsContainer />
</HalfHeightCol>
<HalfHeightCol>
<DashboardActionsContainer />
</HalfHeightCol>
</OneThirdCol>
</Row>
</ContainerLimited>
</PageWrapper>
</PageTemplate>
)
}
export default DashboardPage
<file_sep>import React from 'react'
import { storiesOf } from '@storybook/react'
import WinWheel from '.'
const onRef = () => {}
/**
*
class Parent extends React.Component {
onClick = () => {
this.child.method() // do stuff
}
render() {
return (
<div>
<Child onRef={ref => (this.child = ref)} />
<button onClick={this.onClick}>Child.method()</button>
</div>
);
}
}
*/
const items = [
{ text: 'Segment 1', image: './icon.png', id: '0' },
{ text: 'Segment 2', image: './icon.png', id: '1' },
{ text: 'Segment 3', image: './icon.png', id: '2' },
{ text: 'Segment 4', image: './icon.png', id: '3' },
{ text: 'Segment 5', image: './icon.png', id: '4' },
{ text: 'Segment 6', image: './icon.png', id: '5' },
]
storiesOf('Winner Wheel', module)
.add('default', () => (
<WinWheel winWheelItems={items} onRef={onRef} onWheelSpinStart={onRef} />
))
<file_sep>import styled from 'styled-components'
import { palette } from 'styled-theme'
const PageDummy = styled.div`
width: 100%;
height: calc(100vh - 283px);
background-color: ${palette('main', 0)};
display: flex;
align-items: center;
justify-content: center;
font-size: 50px;
color: ${palette('grey', 0)};
font-weight: 100;
`
export default PageDummy
<file_sep>const items = [
{
text: 'Super Prize',
image: 'https://picsum.photos/200?image=23',
id: 'b0',
},
{
text: 'Just a prize',
image: 'https://picsum.photos/200?image=24',
id: 'b1',
},
{
text: 'Not bad prize',
image: 'https://picsum.photos/200?image=25',
id: 'b2',
},
{
text: 'So-so prize',
image: 'https://picsum.photos/200?image=26',
id: 'b3',
},
{
text: 'Not the best prize',
image: 'https://picsum.photos/200?image=27',
id: 'b4',
},
{
text: 'Better find sth else',
image: 'https://picsum.photos/200?image=28',
id: 'b5',
},
{
text: 'So-so prize',
image: 'https://picsum.photos/200?image=29',
id: 'b6',
},
{
text: 'Not the best prize',
image: 'https://picsum.photos/200?image=30',
id: 'b7',
},
{
text: 'Better find sth else',
image: 'https://picsum.photos/200?image=31',
id: 'b8',
},
]
export default items
<file_sep>import React from 'react'
import styled from 'styled-components'
import { palette } from 'styled-theme'
import { spinner } from '../../themes/keyframes'
const border = '12px'
const size = 60
const Spinner = styled.div`
position: absolute;
top: 50%;
left: 50%;
width: ${size}px;
height: ${size}px;
transform: translate(-50%, -50%);
border-radius: 50%;
border-top: ${border} solid ${palette('primary', 0)};
border-left: ${border} solid ${palette('primary', 0)};
border-bottom: ${border} solid ${palette('primary', 0)};
border-right: ${border} solid ${palette('primary', 3)};
animation: ${spinner} 1s linear forwards infinite;
`
const Holder = styled.div`
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 50;
background-color: #ffffff;
`
const FetchingLocal = () => {
return (<Holder><Spinner /></Holder>)
}
export default FetchingLocal
<file_sep>import React from 'react'
import { storiesOf } from '@storybook/react'
import Fireworks from '.'
storiesOf('Fireworks', module)
.add('default', () => (<Fireworks />))
<file_sep>export const initialState = { isLoading: false, unread: 0, notifications: [] }
export const getUnreadNotificationsAmount = (state = initialState) => state.unread
export const getNotifications = (state = initialState) => state.notifications
export const isNotificationsLoading = (state = initialState) => state.isLoading
<file_sep>import styled from 'styled-components'
import { palette, font, size } from 'styled-theme'
import { lightGreyGradient } from '../../themes/gradients'
import { absoluteMiddleCSS } from '../../themes/style-snippets'
const PlayBtn = styled.div`
cursor: pointer;
width: 96px;
height: 96px;
border-radius: 50%;
box-shadow: 0 0 5px rgba(0,0,0,0.4);
${lightGreyGradient};
${absoluteMiddleCSS};
transition: transform 0.25s ease,
box-shadow 0.2s ease;
&:after {
content: 'play';
text-transform: uppercase;
background-color: ${palette('main', 0)};
width: 74px;
height: 74px;
border-radius: 50%;
text-align: center;
line-height: 74px;
color: ${palette('grey', 0)};
font-family: ${font('main')};
font-size: ${size('menuItems')};
${absoluteMiddleCSS};
box-shadow: inset 0 0 9px ${palette('main', 1)};
transition: text-shadow 0.25s ease,
box-shadow 0.25s ease,
opacity 0.25s ease,
background-color 0.25s ease;
}
&:hover {
transform: translate(-50%, -50%) scale(1.03);
&:after {
box-shadow: inset 0 0 1px ${palette('main', 1)};
text-shadow: 0 0 3px ${palette('grey', 0)};
opacity: 0.9;
}
}
&:active {
transform: translate(-50%, -49%) scale(1);
box-shadow: 0 0 3px rgba(0,0,0,0.5);
&:after {
background-color: ${palette('main', 1)};
opacity: 1;
}
}
`
export default PlayBtn
<file_sep>import styled, { css } from 'styled-components'
import PropTypes from 'prop-types'
import { size } from 'styled-theme'
const noPaddingCSS = css`
${size('mobileMediaQuery')} {
padding: 0;
}
`
const ContainerLimited = styled.div`
max-width: 1080px;
max-height: 100%;
margin: 0 auto;
padding: 0 10px;
position: relative;
${props => props.noMobilePadding && noPaddingCSS};
`
ContainerLimited.propTypes = {
noMobilePadding: PropTypes.bool,
}
export default ContainerLimited
<file_sep>import React from 'react'
import { storiesOf } from '@storybook/react'
import ButtonMain from '.'
storiesOf('ButtonMain', module)
.add('default', () => (<ButtonMain>Earn £3 easily</ButtonMain>))
<file_sep>import isMobile from 'ismobilejs'
const createCenteredWindow = (title, w, h) => {
/* eslint-disable no-nested-ternary */
const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left
const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top
const width = window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width)
const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height
const left = ((width / 2) - (w / 2)) + dualScreenLeft
const top = ((height / 2) - (h / 2)) + dualScreenTop
return window.open('', title, `menubar=no,location=no,resizable=no,scrollbars=yes,status=no, width=${w}, height=${h}, top=${top}, left=${left}`)
}
export const WindowCentered = ({ url, title = '_blank', w = 460, h = 340, onClose, _win }) => {
let fbWindow
if (_win) fbWindow = _win
else fbWindow = createCenteredWindow(title, w, h)
fbWindow.location.href = url
if (window.focus) fbWindow.focus()
const windowCheckCloseInterval = window.setInterval(() => {
if (fbWindow.closed) {
clearInterval(windowCheckCloseInterval)
fbWindow = null
if (onClose) onClose()
}
}, 50)
}
export const isSafari = () => {
const ua = navigator.userAgent
const iOS = !!ua.match(/iP(ad|hone|od)/i)
const webkit = !!ua.match(/WebKit/i)
const iOSSafari = iOS && webkit && !ua.match(/CriOS/i) && !ua.match(/OPiOS/i)
const isOpera = (!!window.opr && !!window.opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0
const isChrome = !!window.chrome && !!window.chrome.webstore
return isMobile.any ? iOSSafari : Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 || (!isChrome && !isOpera && window.webkitAudioContext !== undefined)
}
export const randomIntFromInterval = (min, max) => (Math.floor(Math.random() * ((max - min) + 1)) + min)
export const numToFixed = (num, fixed) => {
if (num === null || num === undefined || isNaN(num)) return new Error('NUM is not a number')
if (fixed && fixed < 0) return num
const parts = String(num).split('.')
if (parts.length === 1) return Number(parts[0]).toFixed(fixed)
if (fixed === 0) return String(parts[0])
return `${parts[0]}.${parts[1].substring(0, fixed)}`
}
export const splitCapitalsJoinSpaces = text => text.split(/(?=[A-Z])/).join(' ')
export const getURLParameter = (name, url = window.location.href) => {
const newName = name.replace(/[\[\]]/g, '\\$&')
const regex = new RegExp(`[?&]${newName}(=([^&#]*)|&|#|$)`)
const results = regex.exec(url)
if (!results) return null
if (!results[2]) return ''
return decodeURIComponent(results[2].replace(/\+/g, ' '))
}
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, font, size } from 'styled-theme'
const Holder = styled.div`
display: flex;
flex-direction: column;
transition: opacity 0.2s ease;
align-items: center;
text-align: center;
cursor: pointer;
&:hover {
opacity: 0.7;
}
`
const Title = styled.h3`
margin: 0;
padding: 0;
font-family: ${font('main')};
font-size: ${size('textParagraph')};
color: ${palette('text', 0)};
`
const Image = styled.img`
display: inline-block;
width: 40px;
height: auto;
margin-bottom: 6px;
`
const Badge = ({ id, title, image, onClick }) => {
const onBadgeClick = () => onClick(id)
return (
<Holder onClick={onBadgeClick}>
<Image src={image} />
<Title>{title}</Title>
</Holder>
)
}
Badge.propTypes = {
id: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired,
}
export default Badge
<file_sep>import React from 'react'
import { storiesOf } from '@storybook/react'
import UsersDone from '.'
const users = [
{
id: '0',
image: 'https://static.rewarded.club/content/main/assets/images/default-profile.png'
},
{
id: '1',
image: 'https://static.rewarded.club/content/main/assets/images/default-profile.png'
},
]
const users2 = [
{
id: '0',
image: 'https://static.rewarded.club/content/main/assets/images/default-profile.png'
},
{
id: '1',
image: 'https://static.rewarded.club/content/main/assets/images/default-profile.png'
},
{
id: '3',
image: 'https://static.rewarded.club/content/main/assets/images/default-profile.png'
},
]
storiesOf('UsersDone', module)
.add('default', () => (<UsersDone users={users} totalAmount={users.length} />))
.add('empty', () => (<UsersDone />))
.add('many', () => (<UsersDone users={users2} totalAmount={315} />))
.add('column', () => (<UsersDone users={users2} totalAmount={315} column />))
<file_sep>// https://github.com/diegohaz/arc/wiki/Example-app
import 'react-hot-loader/patch'
import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { BrowserRouter } from 'react-router-dom'
import { basename } from 'config'
import configureStore from 'store/configure'
import App from 'components/App'
const store = configureStore({})
const launchWhenWidgetReady = (callback) => {
const interval = window.setInterval(() => {
if (window._DGPublic && window._DGPublic.getAccessToken) {
window.clearInterval(interval)
// not launching app if in an iframe cuz of open-id auth
if (callback && window.parent === window) callback()
}
}, 100)
}
const renderApp = () => (
<Provider store={store}>
<BrowserRouter basename={basename}>
<App />
</BrowserRouter>
</Provider>
)
const root = document.getElementById('app')
// remove wrapping launchWhenWidgetReady method when works without widget
// launchWhenWidgetReady(() => {
// render(renderApp(), root)
// })
render(renderApp(), root)
if (module.hot) {
module.hot.accept('components/App', () => {
require('components/App')
render(renderApp(), root)
})
// launchWhenWidgetReady(() => {
// module.hot.accept('components/App', () => {
// require('components/App')
// render(renderApp(), root)
// })
// })
}
<file_sep>import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { palette, size, font } from 'styled-theme'
import { ctaGradient } from '../../themes/gradients'
const mainCSS = css`
${ctaGradient};
color: ${palette('grey', 0)};
&:hover {
background: ${palette('main', 1)};
}
`
const invertedCSS = css`
background-color: ${palette('grey', 0)};
color: ${palette('main', 0)};
transition: background-color 0.3s ease;
&:hover {
background: ${palette('grey', 2)};
}
`
const ButtonMain = styled.div`
display: inline-block;
cursor: pointer;
font-family: ${font('main')};
text-align: center;
font-size: ${size('text-regular')};
text-shadow: 1px 1px 3px rgba(0,0,0,0.4);
padding: 12px 24px;
border-radius: 4px;
${props => props.inverted ? invertedCSS : mainCSS};
`
ButtonMain.propTypes = {
inverted: PropTypes.bool,
}
export default ButtonMain
<file_sep>import React from 'react'
import { storiesOf } from '@storybook/react'
import AvatarCircular from '.'
storiesOf('AvatarCircular', module)
.add('default', () => (<AvatarCircular />))
.add('big', () => (<AvatarCircular big />))
.add('small', () => (<AvatarCircular small />))
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { palette, size, font } from 'styled-theme'
import isMobile from 'ismobilejs'
import WinProductsImage from './WinProductsImage'
import WinProductsButton from './WinProductsButton'
import WinProductsMoreButton from './WinProductsMoreButton'
const ROW_HEIGHT = 60
const CELL_WIDTH = { width: '15%' }
const Table = styled.div`
font-family: ${font('main')};
width: 100%;
background-color: ${palette('grey', 0)};
font-size: ${size('textRegular')};
text-transform: uppercase;
`
const Head = styled.div`
background-color: ${palette('main', 1)};
color: ${palette('grey', 0)};
line-height: 50px;
font-weight: 400;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
padding: 0 10px;
text-align: center;
${size('mobileMediaQuery')} {
margin-bottom: 10px;
}
`
const CellHead = styled.div`
&:first-child {
width: 30%;
text-align: left;
justify-content: flex-start;
}
&:last-child {
width: 24%;
justify-content: flex-end;
}
${size('mobileMediaQuery')} {
&:last-child, &:first-child { width: 25%; }
width: 25%;
}
`
const TableBody = styled.div`
padding: 0 10px 1px;
${size('mobileMediaQuery')} {
padding: 0;
}
`
const tableRowSelectedCSS = css`
color: ${palette('grey', 0)};
background-color: ${palette('main', 2)};
`
const TableRow = styled.div`
background-color: ${palette('grey', 1)};
height: ${ROW_HEIGHT}px;
margin: 10px 0;
border-radius: 6px;
overflow: hidden;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
color: ${palette('text', 0)};
${props => props.isSelected && tableRowSelectedCSS};
`
TableRow.propTypes = {
isSelected: PropTypes.bool,
}
const mobileRowSelectedCSS = css`
color: ${palette('grey', 0)};
background-color: ${palette('main', 2)};
& > *:last-child {
color: ${palette('main', 0)};
}
`
const MobileRow = styled.div`
display: flex;
flex-direction: column;
width: 100%;
border-bottom: 1px solid ${palette('grey', 2)};
${props => props.isSelected && mobileRowSelectedCSS};
`
MobileRow.propTypes = {
isSelected: PropTypes.bool,
}
const MobileRowTop = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
width: 100%;
box-sizing: border-box;
padding: 5px 10px;
& > * {
width: 20% !important;
&:first-child { width: 20% !important; }
&:last-child { width: 30% !important; }
}
`
const Cell = styled.div`
display: flex;
flex-direction: row;
align-items: center;
height: 100%;
text-align: center;
justify-content: center;
&:first-child {
width: 30%;
text-align: left;
justify-content: flex-start;
}
&:last-child {
width: 24%;
justify-content: center;
}
`
function getProductRows({ items, onItemClick, shoppedItemSelected, onMobileItemGetInfoClick }) {
return items.map((item) => {
const itemClick = () => {
onItemClick(item.id)
}
const isSelected = item.id === shoppedItemSelected.id
const onMobileRowClick = (ev) => {
if (ev.target.nodeName !== 'BUTTON') {
onMobileItemGetInfoClick(item)
}
}
return !isMobile.any ? (
<TableRow key={item.id} isSelected={isSelected}>
<Cell>
<WinProductsImage isSelected={isSelected} src={item.image} size={ROW_HEIGHT} /> {item.title}
</Cell>
<Cell style={CELL_WIDTH}>£{item.price}</Cell>
<Cell style={CELL_WIDTH}>{item.retailer}</Cell>
<Cell style={CELL_WIDTH}>{item.points}</Cell>
<Cell>
{isSelected
? `${item.odds} to win`
: (<WinProductsButton onClick={itemClick}>{item.odds} to win</WinProductsButton>)
}
</Cell>
</TableRow>
) : (
<MobileRow key={item.id} isSelected={isSelected} onClick={onMobileRowClick}>
<MobileRowTop>
<Cell>
<WinProductsImage isSelected={isSelected} src={item.image} size={ROW_HEIGHT} />
</Cell>
<Cell>£{item.price}</Cell>
<Cell>{item.points}</Cell>
<Cell>
{isSelected
? `${item.odds} to win`
: (<WinProductsButton onClick={itemClick}>{item.odds} to win</WinProductsButton>)
}
</Cell>
</MobileRowTop>
</MobileRow>
)
})
}
const MAX_ITEMS_WITHOUT_MORE_BTN = 5
const WinProductsTable = ({ className, items, onItemClick, onGetMoreItemsClick, shoppedItemSelected, onMobileItemGetInfoClick }) => {
const headerDesktop = (
<Head>
<CellHead>Product</CellHead>
<CellHead style={CELL_WIDTH}>Price</CellHead>
<CellHead style={CELL_WIDTH}>Retailer</CellHead>
<CellHead style={CELL_WIDTH}>Points</CellHead>
<CellHead>Odds</CellHead>
</Head>
)
const headerMobile = (
<Head>
<CellHead>Product</CellHead>
<CellHead>Price</CellHead>
<CellHead>Points</CellHead>
<CellHead>Odds</CellHead>
</Head>
)
return (
<Table className={className}>
{!isMobile.any ? headerDesktop : headerMobile}
<TableBody>
{getProductRows({ items, onItemClick, shoppedItemSelected, onMobileItemGetInfoClick })}
</TableBody>
{(items.length <= MAX_ITEMS_WITHOUT_MORE_BTN)
&& <WinProductsMoreButton onClick={onGetMoreItemsClick} />}
</Table>
)
}
WinProductsTable.propTypes = {
className: PropTypes.string,
items: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
retailer: PropTypes.string.isRequired,
odds: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
points: PropTypes.number.isRequired,
}),
).isRequired,
onItemClick: PropTypes.func.isRequired,
onGetMoreItemsClick: PropTypes.func.isRequired,
shoppedItemSelected: PropTypes.object,
onMobileItemGetInfoClick: PropTypes.func,
}
export default WinProductsTable
<file_sep>import { keyframes } from 'styled-components'
export const pinRotationOnSpin = keyframes`
from {
transform: rotateZ(0deg);
}
to {
transform: rotateZ(-18deg);
}
`
export const fadeIn = keyframes`
from {
opacity: 0;
}
to {
opacity: 1;
}
`
export const fadeOut = keyframes`
from {
opacity: 1;
}
to {
opacity: 0;
}
`
export const spinner = keyframes`
from {
transform: translate(-50%, -50%) rotateZ(0deg);
}
to {
transform: translate(-50%, -50%) rotateZ(359deg);
}
`
export const winWheelReveal = keyframes`
from {
transform: translate(-50%, 10%);
}
to {
transform: translate(-50%, -50%);
}
`
export const winWheelHide = keyframes`
from {
transform: translate(-50%, -50%);
}
to {
transform: translate(-50%, 10%);
}
`
export const prizeBadgeReveal = keyframes`
from {
transform: translate(-50%, 100%) rotateZ(0);
}
to {
transform: translate(-50%, 5%) rotateZ(720deg);
}
`
export const rightCardSlideIn = keyframes`
from {
opacity: 0;
transform: translate(170%, -50%) rotate(480deg);
}
to {
opacity: 1;
transform: translate(0, 0) rotate(0deg);
}
`
export const leftCardSlideIn = keyframes`
from {
opacity: 0;
transform: translate(-170%, -50%) rotate(-480deg);
}
to {
opacity: 1;
transform: translate(0, 0) rotate(0deg);
}
`
export const panelSlideUp = keyframes`
from {
transform: translateY(120%);
}
to {
transform: translateY(0);
}
`
export const notificationTooltipShow = keyframes`
from {
opacity: 0;
transform: translate(12px, -100%) rotateZ(90deg);
}
to {
opacity: 1;
transform: translate(0, -50%) rotateZ(0);
}
`
export const badgeAppear = keyframes`
from {
transform: translate(-50%, -50%) rotateZ(720deg) scale(0.1);
top: 100%;
}
to {
transform: translate(-50%, -50%) rotateZ(0) scale(1);
top: 50%;
}
`
export const sideMenuReveal = keyframes`
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
`
<file_sep>import React from 'react'
import { storiesOf } from '@storybook/react'
import SideMenu from '.'
import { imagesPath } from '../../../config'
const onMenuItemClick = (item) => {
window.console.info('clicked', item)
}
const onMenuClose = () => {
window.console.info('Menu closed')
}
const authorizedUser = {
name: '<NAME>',
image: `${imagesPath}/face_temp.jpg`,
points: 32,
credits: 74,
}
const menuItems = [
{ name: 'Dashboard', link: '/' },
{ name: 'Shop', link: 'shop' },
{ name: 'Play', link: 'play' },
{ name: 'Earn', link: 'earn' },
{ name: 'Draws', link: 'draws' },
{ name: 'Activities', link: 'activities' },
{ name: 'Collect', link: 'collect' },
]
storiesOf('Side Menu', module)
.add('default', () => (
<SideMenu
onMenuItemClick={onMenuItemClick}
menuItems={menuItems}
user={authorizedUser}
onMenuClose={onMenuClose}
/>
))
<file_sep>export const OFFER_POPUP_OPEN = 'OFFER_POPUP_OPEN'
export const offerPopupOpen = ({ title, image, description, url, details }) => ({
type: OFFER_POPUP_OPEN,
payload: {
title, image, description, url, details,
},
})
export const OFFER_POPUP_CLOSE = 'OFFER_POPUP_CLOSE'
export const offerPopupClose = () => ({
type: OFFER_POPUP_CLOSE,
})
export const VIDEO_OFFER_OPEN = 'VIDEO_OFFER_OPEN'
export const videoOfferOpen = ({ url }) => ({
type: VIDEO_OFFER_OPEN,
payload: {
url
},
})
export const VIDEO_OFFER_CLOSE = 'VIDEO_OFFER_CLOSE'
export const videoOfferClose = () => ({
type: VIDEO_OFFER_CLOSE,
})
export const SIDE_MENU_OPEN = 'SIDE_MENU_OPEN'
export const sideMenuOpen = () => ({
type: SIDE_MENU_OPEN,
})
export const SIDE_MENU_CLOSE = 'SIDE_MENU_CLOSE'
export const sideMenuClose = () => ({
type: SIDE_MENU_CLOSE,
})
<file_sep>const offers = [
{
id: '0',
image: 'https://picsum.photos/200?image=0',
title: 'Amazing offer to win sth',
description: 'Etiam sed porta eros, a tristique odio. Suspendisse neque velit, laoreet a nunc quis, hendrerit convallis nibh. Integer et est a urna vulputate varius. Interdum et malesuada fames ac ante ipsum primis in faucibus.',
earnAmount: 1.4,
usersDone: [],
usersDoneTotal: 0,
},
{
id: '1',
image: 'https://picsum.photos/200?image=1',
title: 'Another cool offer to win sth',
description: 'Etiam sed porta eros, a tristique odio. Suspendisse neque velit, laoreet a nunc quis, hendrerit convallis nibh. Integer et est a urna vulputate varius. Interdum et malesuada fames ac ante ipsum primis in faucibus.',
earnAmount: 12,
usersDone: [
{
image: 'https://picsum.photos/200?image=2',
id: '11',
},
],
usersDoneTotal: 1,
},
{
id: '3',
image: 'https://picsum.photos/200?image=3',
title: 'Download an app offer',
description: 'Etiam sed porta eros, a tristique odio. Suspendisse neque velit, laoreet a nunc quis, hendrerit convallis nibh. Integer et est a urna vulputate varius. Interdum et malesuada fames ac ante ipsum primis in faucibus.',
earnAmount: 5.3,
odds: '3/8',
usersDone: [
{
image: 'https://picsum.photos/200?image=4',
id: '12',
},
{
image: 'https://picsum.photos/200?image=5',
id: '13',
},
{
image: 'https://picsum.photos/200?image=6',
id: '14',
},
],
usersDoneTotal: 18,
},
{
id: '4',
image: 'https://picsum.photos/200?image=7',
title: 'Watch video offer',
description: 'Etiam sed porta eros, a tristique odio. Suspendisse neque velit, laoreet a nunc quis, hendrerit convallis nibh. Integer et est a urna vulputate varius. Interdum et malesuada fames ac ante ipsum primis in faucibus.',
earnAmount: 7.7,
odds: '1/6',
usersDone: [
{
image: 'https://picsum.photos/200?image=8',
id: '15',
},
{
image: 'https://picsum.photos/200?image=9',
id: '16',
},
],
usersDoneTotal: 2,
},
{
id: '5',
image: 'https://picsum.photos/200?image=10',
title: 'Share somewhere offer',
description: 'Etiam sed porta eros, a tristique odio. Suspendisse neque velit, laoreet a nunc quis, hendrerit convallis nibh. Integer et est a urna vulputate varius. Interdum et malesuada fames ac ante ipsum primis in faucibus.',
earnAmount: 6.9,
usersDone: [],
usersDoneTotal: 0,
},
{
id: '6',
image: 'https://picsum.photos/200?image=11',
title: 'And the last offer in the list',
description: 'Etiam sed porta eros, a tristique odio. Suspendisse neque velit, laoreet a nunc quis, hendrerit convallis nibh. Integer et est a urna vulputate varius. Interdum et malesuada fames ac ante ipsum primis in faucibus.',
earnAmount: 0.2,
usersDone: [
{
image: 'https://picsum.photos/200?image=12',
id: '17',
},
{
image: 'https://picsum.photos/200?image=13',
id: '18',
},
{
image: 'https://picsum.photos/200?image=14',
id: '19',
},
],
usersDoneTotal: 254,
},
]
export default offers
<file_sep>export const initialState = { isLoading: false, offers: [], error: null }
export const getOffers = (state = initialState) => state.offers
export const isOffersLoading = (state = initialState) => state.isLoading
export const getVideoOffer = (state = initialState) => state.offers.filter(o => o.group === 'watch').sort((a, b) => b.playersCount - a.playersCount)[0]
<file_sep>import React, { Component } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { DashboardUserPanel } from 'components'
import { imagesPath } from '../../config'
const BADGES = [
{
id: '22',
image: `${imagesPath}/badges/assistant.svg`,
title: 'badge #1',
description: 'This is some description on how to obtain this badge',
},
{
id: '33',
image: `${imagesPath}/badges/expert.svg`,
title: 'badge #2',
description: 'This is some description on how to obtain this badge',
},
{
id: '44',
image: `${imagesPath}/badges/friendly.svg`,
title: 'badge #3',
description: 'This is some description on how to obtain this badge',
},
{
id: '55',
image: `${imagesPath}/badges/geek.svg`,
title: 'badge #4',
description: 'This is some description on how to obtain this badge',
},
{
id: '66',
image: `${imagesPath}/badges/guru.svg`,
title: 'badge #5',
description: 'This is some description on how to obtain this badge',
},
]
class DashboardUserContainer extends Component {
constructor(props) {
super(props)
this.state = {
openedBadgeId: null,
}
this.onBadgeClick = this.onBadgeClick.bind(this)
this.onBadgePanelClose = this.onBadgePanelClose.bind(this)
}
onBadgeClick(id) {
this.setState({ openedBadgeId: id })
}
onBadgePanelClose() {
this.setState({ openedBadgeId: null })
}
render() {
const { className, selectedUserId, onPanelClose } = this.props
const { openedBadgeId } = this.state
return (
<DashboardUserPanel
className={className}
id={'addw123412'}
name={'<NAME>'}
image={'https://picsum.photos/200?image=75'}
levelImage={'https://picsum.photos/200?image=78'}
levelTitle={'Cool level'}
levelDescription={''}
friendsAmount={35}
pointsAmount={23}
badges={BADGES}
onBadgeClick={this.onBadgeClick}
onBadgePanelClose={this.onBadgePanelClose}
openedBadgeId={openedBadgeId}
drawsEntered={4}
drawsWon={2}
creditsWon={35}
connectionsAmount={57}
joinDate={'25/05/2018'}
onClose={onPanelClose}
/>
)
}
}
DashboardUserContainer.propTypes = {
className: PropTypes.string.isRequired,
selectedUserId: PropTypes.string.isRequired,
onPanelClose: PropTypes.func.isRequired,
}
export default DashboardUserContainer
<file_sep>const { middleware: thunkMiddleware } = require('redux-saga-thunk')
const req = require.context('.', true, /\.\/.+\/middleware\.js$/)
const middlewares = req.keys()
.map(key => req(key).default)
.concat([
thunkMiddleware,
])
if (process.env.NODE_ENV === 'development') {
const { logger } = require('redux-logger')
middlewares.push(logger)
}
module.exports = middlewares
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { palette, font, size } from 'styled-theme'
import DashboardPanel from '../../molecules/DashboardPanel'
import ButtonMain from '../../atoms/ButtonMain'
import SimplePanelFooter from '../../atoms/SimplePanelFooter'
import Badge from '../../molecules/Badge'
import BadgePopup from '../../organisms/BadgePopup'
import { absoluteMiddleCSS } from '../../themes/style-snippets'
const AVATAR_SIZE = 64
const BASE_PADDING = 16
const Wrapper = styled.div`
display: flex;
flex-direction: column;
padding-top: ${(BASE_PADDING * 2) + (AVATAR_SIZE / 4)}px;
`
const baseHolderCenterCSS = css`
align-items: center;
text-align: center;
`
const baseHolderLeftCSS = css`
align-items: flex-start;
text-align: left;
`
const BaseHolder = styled.div`
display: flex;
flex-direction: column;
padding: ${BASE_PADDING - 4}px ${BASE_PADDING}px;
margin: 6px 0;
${props => props.leftAligned ? baseHolderLeftCSS : baseHolderCenterCSS};
`
BaseHolder.propTypes = {
leftAligned: PropTypes.bool,
}
const BadgesHolder = styled.div`
display: flex;
flex-direction: row;
flex-wrap: wrap;
padding: ${BASE_PADDING}px;
margin: 8px 0;
${baseHolderLeftCSS};
& > * {
margin-right: 5px;
margin-bottom: 5px;
}
`
const ButtonsHolder = styled.div`
display: flex;
align-items: center;
justify-content: space-around;
padding: ${BASE_PADDING}px;
`
const TopImagesHolder = styled.div`
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
margin-top: -${(AVATAR_SIZE / 2) + BASE_PADDING}px;
margin-bottom: 20px;
& > * {
margin: 0 10px;
}
`
const AvatarHolder = styled.div`
position: relative;
width: ${AVATAR_SIZE}px;
height: ${AVATAR_SIZE}px;
border-radius: 50%;
overflow: hidden;
box-sizing: border-box;
border: 3px solid ${palette('grey', 0)};
box-shadow: 1px 1px 5px rgba(0,0,0,0.4);
`
const Avatar = styled.img`
display: block;
max-width: 100%;
height: auto;
${absoluteMiddleCSS};
`
const getCircImageSize = props => props.inline ? 28 : AVATAR_SIZE
const CircularImage = styled.img`
width: ${props => getCircImageSize(props)}px;
height: ${props => getCircImageSize(props)}px;
border-radius: 50%;
overflow: hidden;
${props => props.inline && 'margin-right: 10px;'}
`
CircularImage.propTypes = {
inline: PropTypes.bool,
}
const Title = styled.h3`
margin: 0;
padding: 0;
display: flex;
align-items: center;
color: ${palette('text', 0)};
font-weight: 400;
font-size: ${size('textTitle')};
`
const Subtitle = styled.h5`
margin: 10px 0 0;
padding: 0;
color: ${palette('main', 0)};
font-weight: 400;
font-size: ${size('textSubtitle')};
`
const Text = styled.p`
margin: 0;
padding: 0;
color: ${palette('text', 0)};
font-weight: 400;
font-size: ${size('textSubtitle')};
line-height: 22px;
`
const Highlighted = styled.span`
color: ${palette('main', 0)};
`
const DashboardUserPanel = ({
className,
id,
name,
image,
levelImage,
levelTitle,
levelDescription,
friendsAmount,
pointsAmount,
badges,
onBadgeClick,
onBadgePanelClose,
openedBadgeId,
drawsEntered,
drawsWon,
creditsWon,
connectionsAmount,
joinDate,
onClose,
}) => {
const footer = (
<SimplePanelFooter onClick={onClose}>Close</SimplePanelFooter>
)
const friendsSection = friendsAmount > 0 ? (
<Subtitle>{friendsAmount} friend{friendsAmount > 1 ? 's' : ''}</Subtitle>
) : null
const pointsSection = pointsAmount > 0 ? (
<BaseHolder>
<Title>
<CircularImage inline src={'https://picsum.photos/200?image=94'} alt={'points'} /> {pointsAmount}
point{pointsAmount > 1 ? 's' : ''}
</Title>
</BaseHolder>
) : null
const badgeElements = badges.map(badge => <Badge key={badge.id} onClick={onBadgeClick} {...badge} />)
const badgesSection = badges && badges.length > 0 ? <BadgesHolder leftAligned>{badgeElements}</BadgesHolder> : null
const openedBadge = openedBadgeId && badges.find(badge => badge.id === openedBadgeId)
const openedBadgePopup = openedBadge && (
<BadgePopup
image={openedBadge.image}
title={openedBadge.title}
description={openedBadge.description}
onClose={onBadgePanelClose}
/>
)
return (
<DashboardPanel className={className} footer={footer} title={name}>
<Wrapper>
<BaseHolder>
<TopImagesHolder>
<AvatarHolder>
<Avatar src={image} alt={name} />
</AvatarHolder>
<CircularImage src={levelImage} alt={levelTitle} />
</TopImagesHolder>
<Title>{name}</Title>
{friendsSection}
</BaseHolder>
{pointsSection}
<ButtonsHolder>
<ButtonMain>Follow</ButtonMain>
<ButtonMain>Add to friends</ButtonMain>
</ButtonsHolder>
{badgesSection}
<BaseHolder leftAligned>
<Text>Draws entered: <Highlighted>{drawsEntered}</Highlighted></Text>
<Text>Draws won: <Highlighted>{drawsWon}</Highlighted></Text>
<Text>Credits won: <Highlighted>{creditsWon}</Highlighted></Text>
<Text>Mutual friends: <Highlighted>{connectionsAmount}</Highlighted></Text>
<Text>Joined: <Highlighted>{joinDate}</Highlighted></Text>
</BaseHolder>
</Wrapper>
{openedBadgePopup}
</DashboardPanel>
)
}
DashboardUserPanel.propTypes = {
className: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
levelImage: PropTypes.string,
levelTitle: PropTypes.string,
levelDescription: PropTypes.string,
friendsAmount: PropTypes.number,
pointsAmount: PropTypes.number,
badges: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string,
image: PropTypes.string,
title: PropTypes.string,
description: PropTypes.string,
})),
onBadgeClick: PropTypes.func.isRequired,
onBadgePanelClose: PropTypes.func.isRequired,
openedBadgeId: PropTypes.string,
drawsEntered: PropTypes.number,
drawsWon: PropTypes.number,
creditsWon: PropTypes.number,
connectionsAmount: PropTypes.number,
joinDate: PropTypes.string,
onClose: PropTypes.func.isRequired,
}
export default DashboardUserPanel
<file_sep>import React from 'react'
import { storiesOf } from '@storybook/react'
import PlayIncreaseModule from '.'
const onClickPlay = () => console.log('CLICKED play')
const onClickMinus = () => console.log('CLICKED minus')
const onClickPlus = () => console.log('CLICKED plus')
storiesOf('Play Increase Module', module)
.add('default', () => (
<PlayIncreaseModule
betAmount={1}
progressPercent={75}
currency={'£'}
onPlayBtnClick={onClickPlay}
onMinusButtonClick={onClickMinus}
onPlusButtonClick={onClickPlus}
/>
))
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, font, size } from 'styled-theme'
import PageTemplate from '../../templates/PageTemplate'
import ContainerLimited from '../../atoms/ContainerLimited'
import RetailerSearch from '../../molecules/RetailerSearch'
import RetailerItem from '../../molecules/RetailerItem'
const MAX = 800
const Wrapper = styled.div`
background-color: ${palette('main', 0)};
padding: 30px 0;
`
const ItemsPanelHolder = styled.div`
text-align: center;
`
const ItemPanelSeparator = styled.div`
position: relative;
`
const ItemsPanelTitle = styled.h4`
position: relative;
display: inline-block;
z-index: 5;
font-size: ${size('menuItems')};
color: ${palette('grey', 0)};
background-color: ${palette('main', 0)};
padding: 4px 10px;
`
const ItemsPanelLine = styled.div`
width: 100%;
height: 1px;
background-color: ${palette('grey', 0)};
position: absolute;
top: 50%;
z-index: 1;
opacity: 0.5;
`
const ItemsPanelList = styled.div`
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
align-items: flex-start;
& > * {
margin: 15px 5px;
}
`
const Container = styled(ContainerLimited)`
max-width: ${MAX}px;
`
const ItemsPanel = ({ title, children }) => {
return (
<ItemsPanelHolder>
<ItemPanelSeparator>
<ItemsPanelLine />
<ItemsPanelTitle>{title}</ItemsPanelTitle>
</ItemPanelSeparator>
<ItemsPanelList>{children}</ItemsPanelList>
</ItemsPanelHolder>
)
}
ItemsPanel.propTypes = {
title: PropTypes.string.isRequired,
children: PropTypes.node,
}
const RetailersPage = ({
items,
userId,
categories,
selectedCategory,
onCategoryChange,
onSearch,
searchValue,
}) => {
const featuredItems = items.filter(item => item.isFeatured)
const featuredItemsPanel = featuredItems && featuredItems.length > 0 && (
<ItemsPanel title={'Featured retailers'}>
{featuredItems.map(item => <RetailerItem key={item.id} {...item} />)}
</ItemsPanel>
)
const otherItems = items.filter(item => !item.isFeatured)
const otherItemsPanel = otherItems && otherItems.length > 0 && (
<ItemsPanel title={'Retailers'}>
{otherItems.map(item => <RetailerItem key={item.id} {...item} userId={userId} />)}
</ItemsPanel>
)
return (
<PageTemplate>
<Wrapper>
<Container>
<RetailerSearch
searchValue={searchValue}
onSearch={onSearch}
categories={categories}
selectedCategory={selectedCategory}
onCategoryChange={onCategoryChange}
/>
{featuredItemsPanel}
{otherItemsPanel}
</Container>
</Wrapper>
</PageTemplate>
)
}
RetailersPage.propTypes = {
userId: PropTypes.string,
items: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string,
image: PropTypes.string.isRequired,
cashbackUrl: PropTypes.string.isRequired,
url: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
comissionValue: PropTypes.number,
comissionType: PropTypes.string,
isFeatured: PropTypes.bool,
})),
categories: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string,
value: PropTypes.string.isRequired,
})).isRequired,
selectedCategory: PropTypes.string,
onCategoryChange: PropTypes.func.isRequired,
onSearch: PropTypes.func.isRequired,
searchValue: PropTypes.string,
}
export default RetailersPage
<file_sep>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { getCashbackCategoriesRequest, getCashbackRetailersRequest } from 'store/actions'
import { fromCashback, fromUser } from 'store/selectors'
import { imagesPath } from '../../config'
import RetailersPage from '../../components/pages/RetailersPage'
const USER_ID = 'user-id'
const TAKE = 50
const html = window.document.querySelector('html')
class RetailersPageContainer extends Component {
constructor(props) {
super(props)
this.state = {
selectedCategory: 'all',
searchValue: '',
skip: 0,
}
this.onCategoryChange = this.onCategoryChange.bind(this)
this.onSearch = this.onSearch.bind(this)
this.onLazyScroll = this.onLazyScroll.bind(this)
this.searchTimeout = null
}
componentDidMount() {
this.props.getCategories()
this.props.getRetailers()
window.addEventListener('scroll', this.onLazyScroll)
}
componentWillUnmount() {
window.removeEventListener('scroll', this.onLazyScroll)
}
onListUpdate() {
const { selectedCategory, searchValue, skip } = this.state
this.props.getRetailers({
categoryId: selectedCategory === 'all' ? undefined : selectedCategory,
query: searchValue || undefined,
skip,
take: TAKE,
})
}
onLazyScroll() {
if (html.clientHeight + html.scrollTop >= html.scrollHeight) {
this.setState({ skip: this.state.skip += TAKE }, this.onListUpdate)
}
}
onCategoryChange(ev) {
const categoryId = ev.target.value
this.setState({ selectedCategory: categoryId, skip: 0 }, this.onListUpdate)
}
onSearch(ev) {
this.setState({ searchValue: ev.target.value, skip: 0 })
if (this.searchTimeout) {
window.clearTimeout(this.searchTimeout)
}
this.searchTimeout = window.setTimeout(() => {
this.onListUpdate()
}, 500)
}
render() {
const { searchValue, selectedCategory } = this.state
const { categories, retailers, userId = '' } = this.props
const affiliateReadyRetailers = retailers.map(ret => ({
...ret,
cashbackUrl: ret.cashbackUrl.replace(/\[TID]/g, userId),
}))
return (
<RetailersPage
userId={USER_ID}
items={affiliateReadyRetailers}
categories={categories}
selectedCategory={selectedCategory}
onCategoryChange={this.onCategoryChange}
onSearch={this.onSearch}
searchValue={searchValue}
/>
)
}
}
RetailersPageContainer.propTypes = {
categories: PropTypes.array,
retailers: PropTypes.array,
getCategories: PropTypes.func,
getRetailers: PropTypes.func,
userId: PropTypes.string,
}
const mapStateToProps = state => ({
categories: fromCashback.getCashbackCategories(state),
retailers: fromCashback.getCashbackRetailers(state),
userId: fromUser.getProfileInfo(state).id,
})
const mapDispatchToProps = dispatch => ({
getCategories: () => dispatch(getCashbackCategoriesRequest()),
getRetailers: params => dispatch(getCashbackRetailersRequest(params || {})),
})
export default connect(mapStateToProps, mapDispatchToProps)(RetailersPageContainer)
<file_sep>import { take, put, call, fork } from 'redux-saga/effects'
import fetch from '../../services/api'
import {
GET_DRAWS_REQUEST, getDrawsSuccess, getDrawsFail,
} from './actions'
export function* getDraws(data) {
try {
const { Draws } = yield call(fetch, { endpoint: 'draw/getdraws', data })
yield put(getDrawsSuccess(Draws))
} catch (e) {
yield put(getDrawsFail(e))
}
}
export function* watchGetDraws() {
while (true) {
const { payload } = yield take(GET_DRAWS_REQUEST)
yield call(getDraws, payload)
}
}
export default function* () {
yield fork(watchGetDraws)
}
<file_sep>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import {
sideMenuOpen,
sideMenuClose,
checkIfUserAuthorized,
getUserRequest,
getNewNotificationsAmountRequest,
} from 'store/actions'
import { fromGeneral, fromUser, fromNotifications } from 'store/selectors'
import { Header } from 'components'
import { imagesPath } from '../../config'
class HeaderContainer extends Component {
constructor(props) {
super(props)
const { pathname } = props.location
this.state = {
menu: pathname.replace('/', ''),
isNotificationsPopupShown: false,
}
this.onMenuItemClick = this.onMenuItemClick.bind(this)
this.onNotificationsClick = this.onNotificationsClick.bind(this)
}
componentDidMount() {
window.setTimeout(() => {
this.props.checkIfUserAuthorized()
}, 3000)
}
componentWillReceiveProps(nextProps) {
if (!this.props.isUserAuthorized && nextProps.isUserAuthorized) {
this.props.getUser()
}
if (nextProps.isUserAuthorized && !this.unreadNotificationsInterval) {
this.props.getUnreadNotifications()
this.unreadNotificationsInterval = window.setInterval(() => {
this.props.getUnreadNotifications()
}, 20000)
}
if (!nextProps.isUserAuthorized && this.unreadNotificationsInterval) {
window.clearInterval(this.unreadNotificationsInterval)
}
}
onMenuItemClick(menu) {
this.setState({ menu })
this.props.history.push(menu)
}
onNotificationsClick() {
this.setState({ isNotificationsPopupShown: !this.state.isNotificationsPopupShown })
}
render() {
const { isNotificationsPopupShown } = this.state
const {
isSideMenuOpened,
sideMenuOpen,
sideMenuClose,
isUserAuthorized,
userProfile,
unreadNotifications,
} = this.props
return (
<Header
brandLogo={`${imagesPath}/logo.png`}
userAuthorized={userProfile}
onMenuItemClick={this.onMenuItemClick}
activeMenuItem={this.state.menu}
unreadNotifications={unreadNotifications}
onNotificationsClick={this.onNotificationsClick}
isNotificationsPopupShown={isNotificationsPopupShown}
onMobileMenuOpen={sideMenuOpen}
onMobileMenuClose={sideMenuClose}
isMobileMenuOpened={isSideMenuOpened}
isUserAuthorized={isUserAuthorized}
/>
)
}
}
HeaderContainer.propTypes = {
history: PropTypes.object,
location: PropTypes.objectOf(PropTypes.shape({
pathname: PropTypes.string,
})),
isSideMenuOpened: PropTypes.bool,
sideMenuOpen: PropTypes.func.isRequired,
sideMenuClose: PropTypes.func.isRequired,
isUserAuthorized: PropTypes.bool,
checkIfUserAuthorized: PropTypes.func,
getUser: PropTypes.func,
userProfile: PropTypes.object,
unreadNotifications: PropTypes.number,
getUnreadNotifications: PropTypes.func,
}
const mapStateToProps = state => ({
isSideMenuOpened: fromGeneral.isSideMenuOpened(state),
isUserAuthorized: fromUser.isUserAuthorized(state),
userProfile: fromUser.getProfileInfo(state),
unreadNotifications: fromNotifications.getUnreadNotificationsAmount(state),
})
const mapDispatchToProps = dispatch => ({
sideMenuOpen: () => dispatch(sideMenuOpen()),
sideMenuClose: () => dispatch(sideMenuClose()),
checkIfUserAuthorized: () => dispatch(checkIfUserAuthorized()),
getUser: () => dispatch(getUserRequest()),
getUnreadNotifications: () => dispatch(getNewNotificationsAmountRequest()),
})
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(HeaderContainer))
<file_sep># Win What You Buy
User engagement service which works in conjunction with browser extension or partnership with big retailers.
Which help us track user purchases and instead of giving back the cashback use it as part of the game, converting to currency,
which can be used to win free stuff.
### Stack
* ES6
* React, Redux, Sagas
* Styled Components (CSS-in-JS)
* Webpack
* OpenID
* Atomic design
* Storybook
<file_sep>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { startFireworks, stopFireworks } from './firework-animation'
const FireworksHolder = styled.div`
width: 100%;
height: 100%;
min-height: 300px;
min-width: 300px;
`
FireworksHolder.propTypes = {
height: PropTypes.number,
}
class Fireworks extends Component {
componentDidMount() {
startFireworks({ holder: this.fireworksHolder })
}
componentWillUnmount() {
stopFireworks()
}
render() {
const {className, height} = this.props
const addRef = (elem) => {
this.fireworksHolder = elem
}
return <FireworksHolder className={className} innerRef={addRef} height={height} />
}
}
Fireworks.propTypes = {
className: PropTypes.string,
height: PropTypes.number,
}
export default Fireworks
<file_sep>import React from 'react'
import { storiesOf } from '@storybook/react'
import WinWheelSVG from '.'
const items = [
{ text: 'Segment 1', image: 'https://picsum.photos/200?image=30', id: '0', mainPrize: true },
{ text: 'Segment 2', image: 'https://picsum.photos/200?image=31', id: '1' },
{ text: 'Segment 3', image: 'https://picsum.photos/200?image=32', id: '2' },
{ text: 'Segment 4', image: 'https://picsum.photos/200?image=33', id: '3' },
{ text: 'Segment 5', image: 'https://picsum.photos/200?image=34', id: '4' },
{ text: 'Segment 6', image: 'https://picsum.photos/200?image=35', id: '5' },
]
storiesOf('WinWheelSVG', module)
.add('default', () => (<WinWheelSVG winWheelItems={items} />))
<file_sep>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import { fromOffers } from 'store/selectors'
import { ActionPanel } from 'components'
import { offerPopupOpen, getOffersRequest, videoOfferOpen } from 'store/actions'
class DashboardActionsContainer extends Component {
constructor(props) {
super(props)
this.onShowAllActions = this.onShowAllActions.bind(this)
this.onActionApply = this.onActionApply.bind(this)
}
componentDidMount() {
this.props.getOffers()
}
onActionApply(action) {
this.props.videoOfferOpen(action)
}
onShowAllActions() {
this.props.history.push('earn')
}
render() {
const {
videoOffer: {
title, description, image, typeImage, reward, rewardType, playersCount, recentPlayers, customData: { url } = {},
} = {},
isLoading,
} = this.props
return !isLoading ? (
<ActionPanel
title={title}
description={description}
image={image || typeImage}
details={'The container component does the job of managing of state. The container, in this case, is the higher-order component.\nIn the search example we talked about earlier, the search component would be the container component that manages the search state and wraps the presentation components that need the search functionality. The presentation components otherwise have no idea of state or how it is being managed.'}
url={url}
reward={reward}
currency={rewardType}
usersDone={recentPlayers}
usersDoneTotal={playersCount}
onApply={this.onActionApply}
onShowAll={this.onShowAllActions}
/>
) : null
}
}
DashboardActionsContainer.propTypes = {
history: PropTypes.object,
offerPopupOpen: PropTypes.func,
videoOfferOpen: PropTypes.func,
offers: PropTypes.array,
getOffers: PropTypes.func,
videoOffer: PropTypes.objectOf(PropTypes.shape({
title: PropTypes.string,
description: PropTypes.string,
image: PropTypes.string,
typeImage: PropTypes.string,
reward: PropTypes.number,
rewardType: PropTypes.string,
playersCount: PropTypes.number,
recentPlayers: PropTypes.object,
customData: PropTypes.object,
})),
isLoading: PropTypes.bool,
}
const mapStateToProps = state => ({
offers: fromOffers.getOffers(state),
isLoading: fromOffers.isOffersLoading(state),
videoOffer: fromOffers.getVideoOffer(state),
})
const mapDispatchToProps = dispatch => ({
offerPopupOpen: offer => dispatch(offerPopupOpen(offer)),
videoOfferOpen: offer => dispatch(videoOfferOpen(offer)),
getOffers: () => dispatch(getOffersRequest()),
})
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(DashboardActionsContainer))
<file_sep>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router-dom'
import PageTemplate from '../../templates/PageTemplate'
import PageDummy from '../../atoms/PageDummy'
class DrawsPage extends Component {
/* eslint-disable no-underscore-dangle */
componentDidMount() {
const { hash } = this.props.location
if (window._DGPublic && window._DGPublic.openWidgetView) {
window.setTimeout(() => {
window.console.log('draws', hash.substr(1, hash.length))
window._DGPublic.openWidgetView('draws', hash.substr(1, hash.length))
}, 600)
}
}
componentWillUnmount() {
if (window._DGPublic && window._DGPublic.closeWidget) {
window._DGPublic.closeWidget()
}
}
render() {
return (
<PageTemplate>
<PageDummy />
</PageTemplate>
)
}
}
DrawsPage.propTypes = {
location: PropTypes.object,
}
export default withRouter(DrawsPage)
<file_sep>import styled from 'styled-components'
import { iconsPath } from '../../../config'
const WinProductsMoreButton = styled.div`
cursor: pointer;
width: 40px;
height: 40px;
background: url('${iconsPath}/icon-more.png') no-repeat center;
margin: -5px auto 0;
`
export default WinProductsMoreButton
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, size, font } from 'styled-theme'
import DashboardPanel from '../../molecules/DashboardPanel'
import UsersDone from '../../atoms/UsersDone'
import ButtonMain from '../../atoms/ButtonMain'
const FooterHolder = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
padding: 0 10px;
box-sizing: border-box;
`
const ShowAllLink = styled.div`
cursor: pointer;
font-family: ${font('main')};
color: ${palette('text', 0)};
font-size: ${size('textRegular')};
`
const Footer = ({ reward, currency, onApply, onShowAll }) => {
return (
<FooterHolder>
<ButtonMain onClick={onApply}>+{reward} {currency}</ButtonMain>
{onShowAll && <ShowAllLink onClick={onShowAll}>Show all</ShowAllLink>}
</FooterHolder>
)
}
Footer.propTypes = {
reward: PropTypes.number.isRequired,
currency: PropTypes.string,
onApply: PropTypes.func.isRequired,
onShowAll: PropTypes.func,
}
const Title = styled.h3`
color: ${palette('text', 0)};
font-size: ${size('textRegular')};
margin: 0 0 20px;
padding: 0;
display: flex;
align-items: center;
`
const Description = styled.p`
margin: 0 0 20px;
padding: 0;
color: ${palette('text', 0)};
font-size: ${size('textSubtitle')};
`
const ActionImage = styled.img`
height: auto;
width: 60px;
margin-right: 10px;
`
const Wrapper = styled.div`
padding: 20px 10px 0;
box-sizing: border-box;
`
const ActionPanel = ({ title, description, image, details, url, reward, currency = 'points', usersDone, usersDoneTotal, onApply, onShowAll }) => {
const onActionApply = () => onApply({title, image, description, url, details})
return (
<DashboardPanel
title={'Try an action'}
footer={<Footer reward={reward} currency={currency} onApply={onActionApply} onShowAll={onShowAll} />}
>
<Wrapper>
<Title><ActionImage src={image} />{title}</Title>
<Description>{description}</Description>
<UsersDone large totalAmount={usersDoneTotal} users={usersDone} />
</Wrapper>
</DashboardPanel>
)
}
ActionPanel.propTypes = {
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
details: PropTypes.string,
url: PropTypes.string,
reward: PropTypes.number.isRequired,
currency: PropTypes.string,
usersDone: PropTypes.arrayOf(
PropTypes.shape({
image: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
}),
),
usersDoneTotal: PropTypes.number,
onApply: PropTypes.func.isRequired,
onShowAll: PropTypes.func,
}
export default ActionPanel
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, size, font } from 'styled-theme'
import DashboardPanel from '../../molecules/DashboardPanel'
import UsersDone from '../../atoms/UsersDone'
import ButtonMain from '../../atoms/ButtonMain'
import FetchingLocal from '../../atoms/FetchingLocal'
const FooterHolder = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
padding: 0 10px;
box-sizing: border-box;
`
const ShowAllLink = styled.div`
cursor: pointer;
font-family: ${font('main')};
color: ${palette('text', 0)};
font-size: ${size('textRegular')};
`
const Footer = ({ onEnter, onShowAll }) => {
return (
<FooterHolder>
<ButtonMain onClick={onEnter}>Enter now</ButtonMain>
{onShowAll && <ShowAllLink onClick={onShowAll}>Show all</ShowAllLink>}
</FooterHolder>
)
}
Footer.propTypes = {
onEnter: PropTypes.func.isRequired,
onShowAll: PropTypes.func,
}
const Title = styled.h3`
color: ${palette('text', 0)};
font-size: ${size('textRegular')};
margin: 0 0 10px;
padding: 0;
`
const Description = styled.p`
margin: 0 0 20px;
padding: 0;
color: ${palette('text', 0)};
font-size: ${size('textSubtitle')};
`
const Countdown = styled.p`
margin: 0 0 20px;
padding: 0;
color: ${palette('main', 0)};
font-size: ${size('textSubtitle')};
`
const PrizeImage = styled.img`
height: auto;
max-width: 100%;
`
const Wrapper = styled.div`
width: 100%;
height: 100%;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
padding: 0 10px;
box-sizing: border-box;
position: relative;
`
const LeftPart = styled.div``
const RightPart = styled.div`
margin-left: 15px;
max-width: 35%;
`
const DrawsPanel = ({ title, description, image, endDate, usersDone, usersDoneTotal, onEnter, onShowAll }) => {
return (
<DashboardPanel
title={'Latest draw'}
footer={<Footer onEnter={onEnter} onShowAll={onShowAll} />}
>
<Wrapper>
<LeftPart>
<Title>{title}</Title>
<Description>{description}</Description>
<Countdown>{endDate}</Countdown>
<UsersDone large totalAmount={usersDoneTotal} users={usersDone} />
</LeftPart>
<RightPart>
<PrizeImage src={image} />
</RightPart>
</Wrapper>
</DashboardPanel>
)
}
DrawsPanel.propTypes = {
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
endDate: PropTypes.string.isRequired,
usersDone: PropTypes.arrayOf(
PropTypes.shape({
image: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
}),
),
usersDoneTotal: PropTypes.number,
onEnter: PropTypes.func.isRequired,
onShowAll: PropTypes.func,
}
export default DrawsPanel
<file_sep>import React from 'react'
import { storiesOf } from '@storybook/react'
import FetchingLocal from '.'
storiesOf('Fetching Local', module)
.add('default', () => (<FetchingLocal />))
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, font, size } from 'styled-theme'
import { imagesPath } from '../../../config'
const Holder = styled.div`
display: inline-block;
flex-grow: 1;
`
const Star = styled.div`
position: absolute;
top: -5px;
right: -5px;
width: 40px;
height: 40px;
background: url('${imagesPath}/star_gold.png') no-repeat center;
background-size: 100%;
z-index: 30;
transform: translate3d(0,0,0);
`
const Panel = styled.div`
cursor: pointer;
position: relative;
background-color: ${palette('grey', 0)};
display: flex;
flex-direction: column;
align-items: center;
padding: 20px 24px;
box-sizing: border-box;
border-radius: 4px;
opacity: 0.9;
transition: opacity 0.3s ease, transform 0.3s ease;
&:hover {
opacity: 1;
transform: scale(1.1);
}
`
const ImageHolder = styled.div`
height: 60px;
`
const Image = styled.img`
max-height: 100%;
width: auto;
`
const Title = styled.h3`
margin: 10px 0 0;
padding: 0;
text-align: center;
font-family: ${font('main')};
font-size: ${size('textRegular')};
color: ${palette('grey', 0)};
opacity: 0.8;
font-weight: 400;
`
const Cashback = styled.p`
margin: 10px 0 0;
padding: 0;
font-size: 10px;
font-family: ${font('main')};
color: ${palette('main', 0)};
text-transform: uppercase;
`
const openNewWindow = (url) => {
window.open(url, '_blank')
}
const getType = (type) => {
switch (type) {
default:
return '%'
}
}
const RetailerItem = ({
id,
image,
cashbackUrl,
url,
name,
comissionValue,
comissionType,
isFeatured,
userId,
}) => {
const updatedUrl = userId ? cashbackUrl.replace('[TID]', userId) : cashbackUrl
const onCashbackLinkClick = () => openNewWindow(updatedUrl)
return (
<Holder>
<Panel onClick={onCashbackLinkClick}>
<ImageHolder><Image src={image} /></ImageHolder>
<Cashback>Cashback {comissionValue}{getType(comissionType)}</Cashback>
{isFeatured && <Star />}
</Panel>
<Title>{name}</Title>
</Holder>
)
}
RetailerItem.propTypes = {
id: PropTypes.string,
image: PropTypes.string.isRequired,
cashbackUrl: PropTypes.string.isRequired,
url: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
comissionValue: PropTypes.number,
comissionType: PropTypes.string,
isFeatured: PropTypes.bool,
userId: PropTypes.string,
}
export default RetailerItem
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { palette, font, size } from 'styled-theme'
import {
PageTemplate,
ContainerLimited,
OfferPanel,
OfferCard,
PlayIncreaseModule,
WinWheelSVG,
WinProductsTable,
WinBadge,
ShoppingItemMobilePopup,
} from 'components'
import { playPageGradient } from '../../themes/gradients'
import { winWheelReveal, winWheelHide, prizeBadgeReveal } from '../../themes/keyframes'
const PageWrapper = styled.div`
position: relative;
${playPageGradient};
padding-bottom: 20px;
${size('mobileMediaQuery')} {
overflow: hidden;
}
`
const DummyForFireworks = styled.div`
width: 100%;
height: ${props => props.height ? props.height : 500}px;
`
DummyForFireworks.propTypes = {
height: PropTypes.number,
}
const mobileHeightShiftCSS = css`
margin-top: 50px;
`
const GameHolder = styled.div`
${size('mobileMediaQuery')} {
${mobileHeightShiftCSS};
}
`
const hideWheelAnimationCSS = css`
animation: ${winWheelHide} 1s ease forwards 1;
`
const WinWheelRestyled = styled(WinWheelSVG)`
position: absolute;
top: ${props => props.yPos ? props.yPos : '50%'}px;
left: 50%;
transform: translate(-50%, 10%);
animation: ${winWheelReveal} 1.5s ease 0.5s forwards 1;
z-index: 50;
${props => props.animateWheelHiding && hideWheelAnimationCSS};
${size('mobileMediaQuery')} {
${mobileHeightShiftCSS};
}
`
WinWheelRestyled.propTypes = {
yPos: PropTypes.number,
animateWheelHiding: PropTypes.bool,
}
const GameControls = styled.div`
position: relative;
max-height: 180px;
width: 100%;
padding: 10px 40px;
box-sizing: border-box;
display: flex;
flex-direction: row;
align-items: flex-end;
justify-content: space-between;
background-color: ${palette('grey', 0)};
box-shadow: inset 3px 3px 6px rgba(0,0,0,0.4),
inset -1px -1px 2px rgba(0,0,0,0.4);
z-index: 50;
${size('mobileMediaQuery')} {
box-shadow: none;
justify-content: center;
}
`
const OfferCardRestyled = styled(OfferCard)`
margin-bottom: 25px;
${size('mobileMediaQuery')} {
position: absolute;
top: -255%;
${props => props.rightShifted ? 'right: -10px;' : 'left: -10px;'};
transform: scale(0.8);
${props => props.isMobileHidden && 'display: none;'};
}
`
OfferCardRestyled.propTypes = {
rightShifted: PropTypes.bool,
isMobileHidden: PropTypes.bool,
}
const WinProductsTableRestyled = styled(WinProductsTable)`
position: relative;
z-index: 50;
box-shadow: 1px 2px 5px rgba(0,0,0,0.2);
`
const Row = styled.div`
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
position: relative;
z-index: 50;
& > * {
max-width: 26%;
box-shadow: 1px 2px 5px rgba(0,0,0,0.2);
}
${size('mobileMediaQuery')} {
flex-direction: column;
& > * {
max-width: 1000%;
margin-top: 10px;
}
}
`
const RowTitle = styled.h2`
font-size: ${size('textTitleLarge')};
font-family: ${font('main')};
color: ${palette('grey', 0)};
text-align: center;
margin: 30px 0 20px;
position: relative;
z-index: 50;
`
const WinBadgeRestyled = styled(WinBadge)`
position: absolute;
top: 0;
left: 50%;
transform: translate(-50%, 5%);
z-index: 40;
animation: ${prizeBadgeReveal} 0.5s ease forwards 1;
`
function getOfferCard({ offer, isRightSide, onOfferClick, isMobileHidden }) {
return (
<OfferCardRestyled
id={offer.id}
image={offer.image}
title={offer.title}
odds={offer.odds}
usersDone={offer.usersDone}
usersDoneTotal={offer.usersDoneTotal}
rightShifted={isRightSide}
isMobileHidden={isMobileHidden}
onButtonClick={onOfferClick}
/>
)
}
getOfferCard.propTypes = {
offer: PropTypes.object.isRequired,
isRightSide: PropTypes.bool,
isMobileHidden: PropTypes.bool,
onOfferClick: PropTypes.func.isRequired,
}
function getGameOffers(offers, onOfferClick, isMobileHidden) {
let leftOffer = null
let rightOffer = null
if (offers.length > 0) {
if (offers[0]) leftOffer = getOfferCard({ offer: offers[0], onOfferClick, isMobileHidden })
if (offers[1]) rightOffer = getOfferCard({ offer: offers[1], isRightSide: true, onOfferClick, isMobileHidden })
}
return {
leftOffer, rightOffer,
}
}
function getOfferPanels(offers, onOfferClick) {
return offers.map(offer => (
<OfferPanel
id={offer.id}
key={offer.id}
image={offer.image}
title={offer.title}
description={offer.description}
usersDone={offer.usersDone}
usersDoneTotal={offer.usersDoneTotal}
earnAmount={offer.earnAmount}
currency={offer.currency}
onOfferClick={onOfferClick}
/>
))
}
const PlayPage = ({
gameOffers: gameOffersData,
earnOffers: earnOffersData,
onOfferClick,
currency,
betAmount,
betLimitPercent,
onPlayBtnClick,
onDecreaseBet,
onIncreaseBet,
shoppedItems,
onShoppedItemClick,
onGetMoreShoppedItems,
winWheelItems,
onConnectWheelAsChild,
onWheelSpinComplete,
animateWheelHiding,
shoppedItemSelected,
winBadgeImage,
winBadgeTitle,
onCloseWinBadge,
itemPopup,
onMobileItemGetInfoClick,
}) => {
const gameOffers = getGameOffers(gameOffersData, onOfferClick, !!winBadgeImage)
const earnOffers = getOfferPanels(earnOffersData, onOfferClick)
const HEIGHT = 400
const winBadgeElement = winBadgeImage && (
<WinBadgeRestyled
image={winBadgeImage}
title={winBadgeTitle}
onClose={onCloseWinBadge}
/>
)
return (
<PageTemplate>
<PageWrapper>
<ContainerLimited noMobilePadding>
<DummyForFireworks height={HEIGHT} />
<GameHolder>
<WinWheelRestyled
size={HEIGHT + (HEIGHT * 0.25)}
yPos={HEIGHT}
winWheelItems={winWheelItems}
onRef={onConnectWheelAsChild}
onWheelSpinComplete={onWheelSpinComplete}
animateWheelHiding={animateWheelHiding}
/>
<GameControls>
{gameOffers.leftOffer && gameOffers.leftOffer}
<PlayIncreaseModule
currency={currency}
betAmount={betAmount}
progressPercent={betLimitPercent}
onPlayBtnClick={onPlayBtnClick}
onMinusButtonClick={onDecreaseBet}
onPlusButtonClick={onIncreaseBet}
/>
{gameOffers.rightOffer && gameOffers.rightOffer}
</GameControls>
{winBadgeElement}
</GameHolder>
<WinProductsTableRestyled
items={shoppedItems}
onItemClick={onShoppedItemClick}
onGetMoreItemsClick={onGetMoreShoppedItems}
shoppedItemSelected={shoppedItemSelected}
onMobileItemGetInfoClick={onMobileItemGetInfoClick}
/>
</ContainerLimited>
<ContainerLimited>
<RowTitle>Earn with picks of the day</RowTitle>
<Row>
{earnOffers}
</Row>
</ContainerLimited>
</PageWrapper>
{itemPopup && <ShoppingItemMobilePopup {...itemPopup} onClose={onMobileItemGetInfoClick} />}
</PageTemplate>
)
}
PlayPage.propTypes = {
// Offers props
gameOffers: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
currency: PropTypes.string,
earnAmount: PropTypes.number,
odds: PropTypes.string,
usersDone: PropTypes.arrayOf(PropTypes.shape({
image: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
})),
usersDoneTotal: PropTypes.number,
}),
),
earnOffers: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
currency: PropTypes.string,
earnAmount: PropTypes.number,
odds: PropTypes.string,
usersDone: PropTypes.arrayOf(PropTypes.shape({
image: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
})),
usersDoneTotal: PropTypes.number,
}),
),
onOfferClick: PropTypes.func.isRequired,
// End of offers props
// PlayButtonModule props
currency: PropTypes.string,
betAmount: PropTypes.number.isRequired,
betLimitPercent: PropTypes.number.isRequired,
onPlayBtnClick: PropTypes.func.isRequired,
onDecreaseBet: PropTypes.func.isRequired,
onIncreaseBet: PropTypes.func.isRequired,
// End of PlayButtonModule props
// WinTable props
shoppedItems: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
retailer: PropTypes.string.isRequired,
odds: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
points: PropTypes.number.isRequired,
}),
).isRequired,
onShoppedItemClick: PropTypes.func.isRequired,
onGetMoreShoppedItems: PropTypes.func.isRequired,
shoppedItemSelected: PropTypes.object,
// End of WinTable props
// Winning wheel props
winWheelItems: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
text: PropTypes.string,
image: PropTypes.string,
}),
),
onConnectWheelAsChild: PropTypes.func.isRequired,
onWheelSpinComplete: PropTypes.func.isRequired,
animateWheelHiding: PropTypes.bool,
// End of winning wheel props
// WinBadge
// winBadge: PropTypes.objectOf(PropTypes.shape({
// title: PropTypes.string.isRequired,
// image: PropTypes.string.isRequired,
// })),
winBadgeImage: PropTypes.string.isRequired,
winBadgeTitle: PropTypes.string.isRequired,
onCloseWinBadge: PropTypes.func.isRequired,
itemPopup: PropTypes.object,
onMobileItemGetInfoClick: PropTypes.func,
}
export default PlayPage
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { palette, font, size } from 'styled-theme'
import ButtonMain from '../../atoms/ButtonMain'
import UsersDone from '../../atoms/UsersDone'
import { lightGreyGradient } from '../../themes/gradients'
import { rightCardSlideIn, leftCardSlideIn } from '../../themes/keyframes'
const shapeCSS = css`
position: absolute;
width: 180px;
height: 230px;
border-radius: 16px;
box-shadow: 0 0 2px rgba(0,0,0,0.2);
box-sizing: border-box;
`
const rightSideShiftCSS = css`
left: 5px;
transform: rotateZ(4deg);
`
const leftSideShiftCSS = css`
left: -5px;
transform: rotateZ(-4deg);
`
const BackCard = styled.div`
${shapeCSS};
background-color: ${palette('main', 1)};
z-index: 1;
top: 1px;
${props => props.rightShifted ? rightSideShiftCSS : leftSideShiftCSS};
`
BackCard.propTypes = {
rightShifted: PropTypes.bool,
}
const rightFrontCardCSS = css`
animation: ${rightCardSlideIn} 0.5s ease 0.5s forwards 1;
transform: translate(170%, -50%) rotate(480deg);
`
const leftFrontCardCSS = css`
animation: ${leftCardSlideIn} 0.5s ease 0.3s forwards 1;
transform: translate(-170%, -50%) rotate(-480deg);
`
const FrontCard = styled.div`
${shapeCSS};
${lightGreyGradient};
z-index: 5;
padding: 15px 15px 10px;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
border: 4px solid ${palette('main', 0)};
opacity: 0;
${props => props.rightShifted ? rightFrontCardCSS : leftFrontCardCSS};
`
FrontCard.propTypes = {
rightShifted: PropTypes.bool,
}
const Image = styled.img`
width: 60px;
height: 60px;
border-radius: 50%;
overflow: hidden;
outline: none;
`
const Title = styled.h3`
font-family: ${font('main')};
color: ${palette('main', 1)};
font-size: ${size('textRegular')};
text-shadow: 1px 1px 2px rgba(0,0,0,0.15);
margin: 5px 0;
`
const Holder = styled.div`
width: 180px;
height: 230px;
position: relative;
`
const OfferCard = ({ className, rightShifted, id, image, title, description, odds, usersDone, usersDoneTotal, onButtonClick }) => {
const onClick = () => onButtonClick({ id, image, title, description })
return (
<Holder className={className}>
<BackCard rightShifted={rightShifted} />
<FrontCard rightShifted={rightShifted}>
<Image src={image} />
<Title>{title}</Title>
<ButtonMain onClick={onClick}>Increase {odds}</ButtonMain>
<UsersDone column users={usersDone} totalAmount={usersDoneTotal} />
</FrontCard>
</Holder>
)
}
OfferCard.propTypes = {
rightShifted: PropTypes.bool,
className: PropTypes.string,
id: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
odds: PropTypes.string.isRequired,
usersDone: PropTypes.array,
usersDoneTotal: PropTypes.number,
onButtonClick: PropTypes.func.isRequired,
}
export default OfferCard
<file_sep>import {
GET_OFFERS_REQUEST, GET_OFFERS_SUCCESS, GET_OFFERS_FAIL,
GET_USER_OFFERS_REQUEST, GET_USER_OFFERS_SUCCESS, GET_USER_OFFERS_FAIL,
TRACK_OFFER_REQUEST, TRACK_OFFER_SUCCESS, TRACK_OFFER_FAIL,
CANCEL_OFFER_REQUEST, CANCEL_OFFER_SUCCESS, CANCEL_OFFER_FAIL,
COMPLETE_OFFER_REQUEST, COMPLETE_OFFER_SUCCESS, COMPLETE_OFFER_FAIL,
} from './actions'
import { initialState } from './selectors'
const userNormalizer = user => ({
id: user.UserId,
name: user.UserName,
image: user.ImageUrl,
})
export default (state = initialState, { type, payload }) => {
switch (type) {
case GET_OFFERS_REQUEST:
case GET_USER_OFFERS_REQUEST:
case TRACK_OFFER_REQUEST:
case CANCEL_OFFER_REQUEST:
case COMPLETE_OFFER_REQUEST:
return {
...state,
isLoading: true,
}
case GET_OFFERS_SUCCESS:
case GET_USER_OFFERS_SUCCESS:
return {
...state,
isLoading: false,
offers: payload.offers.map(o => ({
id: o.Offer.Id,
title: o.Offer.Title,
description: o.Offer.Description,
image: o.Offer.ImageUrl,
reward: o.Offer.RewardAmount,
rewardType: o.Offer.RewardType.toLowerCase(),
customData: o.Offer.CustomData && {
...o.Offer.CustomData,
url: o.Offer.CustomData.Url,
},
type: o.Offer.Type.Name.toLowerCase(),
typeId: o.Offer.Type.OfferTypeId,
typeImage: o.Offer.Type.ImageUrl,
group: o.Offer.Type.Group.Name.toLowerCase(),
groupId: o.Offer.Type.Group.OfferGroupId,
groupImage: o.Offer.Type.Group.ImageUrl,
sponsor: o.Offer.Sponsor.Name,
sponsorId: o.Offer.Sponsor.Id,
sortBySponsor: o.Offer.Sponsor.SortOrder,
isFeatured: o.Offer.IsFeatured,
playersCount: o.TotalCompletersCount,
recentPlayers: o.RecentCompleters.map(user => userNormalizer(user)),
})),
}
case TRACK_OFFER_SUCCESS:
case CANCEL_OFFER_SUCCESS:
case COMPLETE_OFFER_SUCCESS:
return {
...state,
isLoading: false,
}
case GET_OFFERS_FAIL:
case GET_USER_OFFERS_FAIL:
case TRACK_OFFER_FAIL:
case CANCEL_OFFER_FAIL:
case COMPLETE_OFFER_FAIL:
return {
...state,
error: payload.err,
}
default:
return { ...state }
}
}
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, size, font } from 'styled-theme'
import { fadeIn, sideMenuReveal } from '../../themes/keyframes'
import Logo from '../../atoms/Logo'
import Button from '../../atoms/ButtonMain'
import ProfileElementAuthorized from '../../molecules/ProfileElementAuthorized'
const Overlay = styled.div`
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.4);
animation: ${fadeIn} 0.3s ease forwards 1;
z-index: 20000;
`
const Deck = styled.div`
background-color: ${palette('main', 0)};
height: 100%;
width: 70%;
max-width: 320px;
min-width: 160px;
box-shadow: 0 2px 6px rgba(0,0,0,0.7);
display: flex;
flex-direction: column;
justify-content: space-between;
box-sizing: border-box;
animation: ${sideMenuReveal} 0.4s ease forwards 1;
`
const TopPart = styled.div`
display: flex;
flex-direction: column;
padding: 20px;
& > *:not(:first-child) {
margin-top: 20px;
}
`
const BottomPart = styled.div`
flex-grow: 1;
border-top: 2px solid rgba(255,255,255,0.3);
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: space-around;
`
const MenuItem = styled.div`
font-size: ${size('textTitle')};
font-family: ${font('main')};
color: ${palette('grey', 0)};
width: 100%;
flex-grow: 1;
display: flex;
align-items: center;
box-sizing: border-box;
padding: 0 20px;
&:nth-of-type(2n) {
background-color: rgba(0,0,0,0.1);
}
`
const StyledLogo = styled(Logo)`
max-width: 50%;
`
const SideMenu = ({ onMenuClose, onMenuItemClick, menuItems, user, isUserAuthorized }) => {
const onAnyMenuItemClick = (item) => {
onMenuClose()
onMenuItemClick(item)
}
const onLogoClick = () => onAnyMenuItemClick('/')
const onSideMenuClick = ev => ev.currentTarget === ev.target && onMenuClose()
const menuItemsElements = menuItems.map(item => (
<MenuItem key={item.name} onClick={() => onAnyMenuItemClick(item.link)}>{item.name}</MenuItem>
))
const userElement = isUserAuthorized ? (
<ProfileElementAuthorized
onMenuItemClick={onAnyMenuItemClick}
lightSkin
{...user}
/>
) : (
<Button inverted onClick={() => onAnyMenuItemClick('profile')}>Log in</Button>
)
return (
<Overlay onClick={onSideMenuClick}>
<Deck>
<TopPart>
<StyledLogo white onClick={onLogoClick} />
{userElement}
</TopPart>
<BottomPart>
{menuItemsElements}
</BottomPart>
</Deck>
</Overlay>
)
}
SideMenu.propTypes = {
onMenuClose: PropTypes.func.isRequired,
onMenuItemClick: PropTypes.func.isRequired,
menuItems: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string,
link: PropTypes.string,
})),
user: PropTypes.objectOf(PropTypes.shape({
name: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
credits: PropTypes.number,
points: PropTypes.number,
})),
isUserAuthorized: PropTypes.bool,
}
export default SideMenu
<file_sep>export const GET_CASHBACK_CATEGORIES_REQUEST = 'GET_CASHBACK_CATEGORIES_REQUEST'
export const getCashbackCategoriesRequest = () => ({
type: GET_CASHBACK_CATEGORIES_REQUEST,
})
export const GET_CASHBACK_CATEGORIES_SUCCESS = 'GET_CASHBACK_CATEGORIES_SUCCESS'
export const getCashbackCategoriesSuccess = categories => ({
type: GET_CASHBACK_CATEGORIES_SUCCESS,
payload: {
categories,
},
})
export const GET_CASHBACK_CATEGORIES_FAIL = 'GET_CASHBACK_CATEGORIES_FAIL'
export const getCashbackCategoriesFail = err => ({
type: GET_CASHBACK_CATEGORIES_FAIL,
payload: {
err,
},
})
export const GET_CASHBACK_RETAILERS_REQUEST = 'GET_CASHBACK_RETAILERS_REQUEST'
export const getCashbackRetailersRequest = ({ categoryId, query, skip, take, sortAsc }) => ({
type: GET_CASHBACK_RETAILERS_REQUEST,
payload: {
categoryId, query, skip, take, sortAsc,
},
})
export const GET_CASHBACK_RETAILERS_SUCCESS = 'GET_CASHBACK_RETAILERS_SUCCESS'
export const getCashbackRetailersSuccess = retailers => ({
type: GET_CASHBACK_RETAILERS_SUCCESS,
payload: {
retailers,
},
})
export const GET_CASHBACK_RETAILERS_FAIL = 'GET_CASHBACK_RETAILERS_FAIL'
export const getCashbackRetailersFail = err => ({
type: GET_CASHBACK_RETAILERS_FAIL,
payload: {
err,
},
})
<file_sep>import React from 'react'
import styled from 'styled-components'
import { storiesOf } from '@storybook/react'
import RetailerItem from '.'
const Holder = styled.div`
display: flex;
flex-wrap: wrap;
& > * {
width: calc(20% - 20px);
margin: 10px;
}
`
storiesOf('Retailer Item', module)
.add('default', () => (
<Holder>
<RetailerItem
id={'12'}
image={'https://picsum.photos/200/300?image=98'}
cashbackUrl={'http://google.com/cashback-url'}
url={'http://google.com/'}
name={'Test retailer'}
comissionValue={2.52}
comissionType={'percent'}
isFeatured={false}
userId={'111'}
/>
<RetailerItem
id={'12'}
image={'https://picsum.photos/400/200?image=98'}
cashbackUrl={'http://google.com/cashback-url'}
url={'http://google.com/'}
name={'Test retailer'}
comissionValue={2.52}
comissionType={'percent'}
isFeatured={false}
userId={'111'}
/>
<RetailerItem
id={'12'}
image={'https://picsum.photos/200?image=98'}
cashbackUrl={'http://google.com/cashback-url'}
url={'http://google.com/'}
name={'Test retailer'}
comissionValue={2.52}
comissionType={'percent'}
isFeatured={false}
userId={'111'}
/>
<RetailerItem
id={'12'}
image={'https://picsum.photos/200?image=98'}
cashbackUrl={'http://google.com/cashback-url'}
url={'http://google.com/'}
name={'Test retailer'}
comissionValue={2.52}
comissionType={'percent'}
isFeatured={false}
userId={'111'}
/>
<RetailerItem
id={'12'}
image={'https://picsum.photos/200?image=98'}
cashbackUrl={'http://google.com/cashback-url'}
url={'http://google.com/'}
name={'Test retailer'}
comissionValue={2.52}
comissionType={'percent'}
isFeatured={false}
userId={'111'}
/>
</Holder>
))
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { palette, size, font } from 'styled-theme'
import { absoluteMiddleCSS } from '../../themes/style-snippets'
import { notificationTooltipShow } from '../../themes/keyframes'
import { imagesPath } from '../../../config'
import { splitCapitalsJoinSpaces } from '../../../services/helpers'
const NotificationImageHolder = styled.div`
width: 40px;
height: 40px;
border-radius: 50%;
overflow: hidden;
border: 2px solid ${palette('grey', 2)};
position: relative;
margin-right: 10px;
flex-shrink: 0;
`
const NotificationImage = styled.img`
display: inline-block;
${absoluteMiddleCSS};
max-width: 100%;
height: auto;
`
const NotificationText = styled.p`
margin: 0;
padding: 0;
font-size: ${size('textRegular')};
color: ${palette('text', 0)};
`
const NotificationDate = styled.p`
margin: 4px 0 0;
padding: 0;
font-size: ${size('textRegular')};
color: ${palette('grey', 4)};
`
const Highlighted = styled.span`
color: ${palette('main', 0)};
`
const NotificationTextHolder = styled.div`
flex-grow: 1;
margin-right: 10px;
`
const ImgInline = styled.img`
display: inline-block;
width: 20px;
height: 20px;
border-radius: 50%;
margin: 0 4px;
vertical-align: middle;
`
const NotificationMarkAsReadBullet = styled.div`
width: 6px;
height: 6px;
border-radius: 50%;
border: 3px solid ${palette('grey', 4)};
position: relative;
cursor: pointer;
transition: border 0.3s ease;
&:hover {
border: 3px solid ${palette('main', 0)};
& > * {
display: block;
}
}
`
const NotificationMarkAsReadTooltip = styled.div`
display: none;
background-color: ${palette('main', 0)};
color: ${palette('grey', 0)};
font-size: 12px;
padding: 5px 8px;
border-radius: 3px;
position: absolute;
top: 50%;
right: 15px;
white-space: nowrap;
//transform: translateY(-50%);
transform: translate(12px, -100%) rotateZ(90deg);
transform-origin: center right;
animation: ${notificationTooltipShow} 0.3s ease forwards 1;
&:after {
content: '';
width: 8px;
height: 8px;
position: absolute;
top: 50%;
right: 0;
transform: translate(45%,-50%) rotate(45deg);
background-color: ${palette('main', 0)};
border-radius: 2px;
}
`
const unreadCSS = css`
background-color: ${palette('main', 3)};
`
const Holder = styled.div`
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
padding: 8px 15px;
box-sizing: border-box;
width: 100%;
cursor: pointer;
transition: opacity 0.3s ease;
&:hover {
opacity: 0.7;
}
${props => props.isUnread && unreadCSS};
`
Holder.propTypes = {
isUnread: PropTypes.bool,
}
function getNotificationFormatting(n) {
let image
let text
let temp
let page
let pageId
let error
switch (n.type) {
case 'NewCommissionUser':
case 'CommissionConfirmedUser':
temp = n.WalletTransaction
image = `${imagesPath}/face_temp.jpg`
if (temp.Status.toLowerCase() === 'completed') {
text = (
<NotificationText>Your <Highlighted>£ {temp.Amount} {temp.Partner && temp.Partner.Name}</Highlighted> cashback
was confirmed.</NotificationText>
)
} else {
text = (
<NotificationText>Your <Highlighted>£ {temp.Amount} {temp.Partner && temp.Partner.Name}</Highlighted> has been
tracked and is pending.</NotificationText>
)
}
page = 'credits'
break
case 'AcceptFriendRequest':
text = (
<NotificationText><Highlighted>{n.User.UserName}</Highlighted> accepted your friend request.</NotificationText>
)
image = n.User.ImageUrl
page = 'public'
pageId = n.User.UserId
break
case 'SendFriendRequest':
text = (
<NotificationText><Highlighted>{n.User.UserName}</Highlighted> sent you a friend request, would you like to
accept it?</NotificationText>
)
image = n.User.ImageUrl
page = 'public'
pageId = n.User.UserId
break
case 'WinTheDrawRelatedUser':
text = (
<NotificationText><Highlighted>{n.Draw.Winner.UserName}</Highlighted> has just
won <Highlighted>{n.Draw.Prize.Title.toLowerCase()}</Highlighted> in the draw.</NotificationText>
)
image = n.Draw.Prize.ImageUrl
page = 'draws'
pageId = n.Draw.DrawId
break
case 'WinTheDrawUser':
text = (
<NotificationText>Congratulations! You won the draw! Get
your <Highlighted>{n.Draw.Prize.Title.toLowerCase()}</Highlighted></NotificationText>
)
image = n.Draw.Prize.ImageUrl
page = 'draws'
pageId = n.Draw.DrawId
break
case 'WinTheMatchQuizUser':
text = (
<NotificationText>Congratulations! You've made a correct prediction on the yield
<Highlighted>
{n.Fixture.HomeTeam.ImageUrl && <ImgInline src={n.Fixture.HomeTeam.ImageUrl} />}
{splitCapitalsJoinSpaces(n.Fixture.HomeTeam.Name)} vs
{n.Fixture.AwayTeam.ImageUrl && <ImgInline src={n.Fixture.AwayTeam.ImageUrl} />}
{splitCapitalsJoinSpaces(n.Fixture.AwayTeam.Name)}
</Highlighted>
game.
</NotificationText>
)
image = `${imagesPath}/face_temp.jpg`
page = 'score-predictor'
break
case 'WinTheMatchQuizRelatedUser':
text = (
<NotificationText>
<Highlighted>{n.Winner.UserName}</Highlighted> made a correct prediction on the
<Highlighted>
{n.Fixture.HomeTeam.ImageUrl && <ImgInline src={n.Fixture.HomeTeam.ImageUrl} />}
{splitCapitalsJoinSpaces(n.Fixture.HomeTeam.Name)} vs
{n.Fixture.AwayTeam.ImageUrl && <ImgInline src={n.Fixture.AwayTeam.ImageUrl} />}
{splitCapitalsJoinSpaces(n.Fixture.AwayTeam.Name)}
</Highlighted>
game.
</NotificationText>
)
image = n.Winner.ImageUrl
page = 'public'
pageId = n.Winner.UserId
break
default:
error = true
}
return {
text, image,
}
}
const NotificationItem = ({ id, date, isUnread, onClick, onMarkAsRead, ...restParams }) => {
const markAsRead = () => onMarkAsRead(id)
const onItemClick = () => {
markAsRead()
onClick(id)
}
const { text, image } = getNotificationFormatting(restParams)
const markAsReadElement = isUnread && (
<NotificationMarkAsReadBullet onClick={markAsRead}>
<NotificationMarkAsReadTooltip>Mark as read</NotificationMarkAsReadTooltip>
</NotificationMarkAsReadBullet>
)
return (
<Holder isUnread={isUnread} onClick={onItemClick}>
<NotificationImageHolder>
<NotificationImage src={image} />
</NotificationImageHolder>
<NotificationTextHolder>
{text}
<NotificationDate>{date}</NotificationDate>
</NotificationTextHolder>
{markAsReadElement}
</Holder>
)
}
// TODO: do proper types with required flags when connect to data
NotificationItem.propTypes = {
id: PropTypes.string,
image: PropTypes.string,
text: PropTypes.string,
date: PropTypes.string,
isUnread: PropTypes.bool,
onClick: PropTypes.func,
onMarkAsRead: PropTypes.func,
}
export default NotificationItem
<file_sep>import React from 'react'
import PageTemplate from '../../templates/PageTemplate'
import PageDummy from '../../atoms/PageDummy'
const CollectPage = () => {
return (
<PageTemplate>
<PageDummy>
COLLECT PAGE
</PageDummy>
</PageTemplate>
)
}
export default CollectPage
<file_sep>import React from 'react'
import styled from 'styled-components'
import { storiesOf } from '@storybook/react'
import NotificationItem from './NotificationItem'
import NotificationsList from '.'
const Holder = styled.div`
width: 400px;
margin: 0 30px;
`
const notifications = [
{ id: '1', isUnread: true },
{ id: '2', isUnread: false },
{ id: '3', isUnread: true },
{ id: '4', isUnread: true },
{ id: '5', isUnread: false },
{ id: '6', isUnread: true },
{ id: '7', isUnread: true },
]
storiesOf('Notifications', module)
.add('Notification Item', () => (
<Holder>
<NotificationItem key={'1'} id={'1'} isUnread />
<NotificationItem key={'2'} id={'2'} />
<NotificationItem key={'3'} id={'3'} isUnread />
<NotificationItem key={'4'} id={'4'} />
</Holder>
))
.add('Notification List', () => (
<NotificationsList notifications={notifications} />
))
<file_sep>export const GET_DRAWS_REQUEST = 'GET_DRAWS_REQUEST'
export const getDrawsRequest = ({ upcoming, my, skip, take, sortAsc }) => ({
type: GET_DRAWS_REQUEST,
payload: { upcoming, my, skip, take, sortAsc },
})
export const GET_DRAWS_SUCCESS = 'GET_DRAWS_SUCCESS'
export const getDrawsSuccess = draws => ({
type: GET_DRAWS_SUCCESS,
payload: { draws },
})
export const GET_DRAWS_FAIL = 'GET_DRAWS_FAIL'
export const getDrawsFail = err => ({
type: GET_DRAWS_FAIL,
payload: { err },
})
<file_sep>import axios from 'axios'
function fetch({ isPost = false, endpoint, data }) {
return new Promise((resolve, reject) => {
window._DGPublic.getAccessToken((token) => {
if (token) {
const axiosConfig = {
url: window._DGPublic.apiPrefix + endpoint,
method: isPost ? 'POST' : 'GET',
mode: 'cors',
headers: {
Authorization: token,
},
}
if (isPost) axiosConfig.data = data
else axiosConfig.params = data
window.console.info('Getting ' + endpoint + ' using axios')
axios(axiosConfig)
.then((result) => {
window.console.info('Getting ' + endpoint + ' succeed')
resolve(result.data)
})
.catch((error) => {
if (error.response) {
window.console.warn('Getting ' + endpoint + ' failed')
window.console.warn(error)
reject(error)
}
})
}
})
})
}
export default fetch
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, size } from 'styled-theme'
import DashboardPanel from '../../molecules/DashboardPanel'
import WinnersWheel from '../../molecules/WinnersWheel'
import Dropdown from '../../atoms/Dropdown'
import Dot from '../../atoms/Dot'
import AvatarCircular from '../../atoms/AvatarCircular'
import SimplePanelFooter from '../../atoms/SimplePanelFooter'
import DashboardAllWinnersPanel from '../../organisms/DashboardAllWinnersPanel'
import DashboardUserContainer from '../../../containers/DashboardUserContainer'
import { panelSlideUp } from '../../themes/keyframes'
const WheelHolder = styled.div`
position: relative;
text-align: center;
padding-top: 10px;
`
const WinnersWheelRestyled = styled(WinnersWheel)`
display: inline-block;
margin-top: 30px;
`
const LeftDropDown = styled(Dropdown)`
position: absolute;
top: 10px;
left: 0;
`
const RightDropDown = styled(Dropdown)`
position: absolute;
top: 10px;
right: 0;
`
const StatsHolder = styled.div`
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: space-between;
margin: 30px 0;
`
const StatsItem = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
align-items: center;
width: 80px;
`
const StatsAmount = styled.div`
color: ${palette('text', 0)};
font-size: 20px;
font-weight: 700;
margin: 5px 0 10px;
`
const StatsTitle = styled.div`
color: ${palette('text', 0)};
font-size: ${size('textSubtitle')};
`
const WinnerAvatar = styled(AvatarCircular)`
border: 2px solid transparent;
cursor: pointer;
margin: 2px;
&:hover {
border: 2px solid ${palette('main', 0)};
}
`
const WinnnerAvatarsHolder = styled.div`
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
align-items: flex-start;
`
const InsideDashboardUserContainer = styled(DashboardUserContainer)`
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow-y: auto;
animation: ${panelSlideUp} 0.3s ease forwards 1;
`
const InsideDashboardAllWinnersPanel = styled(DashboardAllWinnersPanel)`
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow-y: auto;
animation: ${panelSlideUp} 0.3s ease forwards 1;
`
const WinnersPanel = ({
timeFilters, onTimeFilterChange, selectedTimeFilter,
rankFilters, onRankFilterChange, selectedRankFilter,
winnersWheelTitle, usersAmount,
friendsWinnersPercent, connectionsWinnersPercent,
friendsWinnersAmount, connectionsWinnersAmount, allWinnersAmount,
winners, onWinnerClick, selectedWinnerId, onWinnerPanelClose,
onShowAllWinners, onHideAllWinners, allWinnersShown,
}) => {
const winnerItems = winners.map((winner) => {
const onClick = () => onWinnerClick(winner.id)
return <WinnerAvatar key={winner.id} forActivity image={winner.image} onClick={onClick} />
})
const footer = <SimplePanelFooter onClick={onShowAllWinners}>Show all winners</SimplePanelFooter>
return (
<DashboardPanel title={'Winners'} footer={footer}>
<WheelHolder>
<LeftDropDown
items={timeFilters}
onChange={onTimeFilterChange}
selectedItem={selectedTimeFilter}
/>
<WinnersWheelRestyled
title={winnersWheelTitle}
amount={usersAmount}
primaryPercent={friendsWinnersPercent}
secondaryPercent={connectionsWinnersPercent}
/>
<RightDropDown
items={rankFilters}
onChange={onRankFilterChange}
selectedItem={selectedRankFilter}
/>
</WheelHolder>
<StatsHolder>
<StatsItem>
<Dot color={'friends'} />
<StatsAmount>{friendsWinnersAmount}</StatsAmount>
<StatsTitle>Friends</StatsTitle>
</StatsItem>
<StatsItem>
<Dot color={'connections'} />
<StatsAmount>{connectionsWinnersAmount}</StatsAmount>
<StatsTitle>Connections</StatsTitle>
</StatsItem>
<StatsItem>
<Dot />
<StatsAmount>{allWinnersAmount}</StatsAmount>
<StatsTitle>All</StatsTitle>
</StatsItem>
</StatsHolder>
<WinnnerAvatarsHolder>
{winnerItems}
</WinnnerAvatarsHolder>
{allWinnersShown && (
<InsideDashboardAllWinnersPanel
onClose={onHideAllWinners}
winners={winnerItems}
/>
)}
{selectedWinnerId && (
<InsideDashboardUserContainer
selectedUserId={selectedWinnerId}
onPanelClose={onWinnerPanelClose}
/>
)}
</DashboardPanel>
)
}
WinnersPanel.propTypes = {
timeFilters: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string,
value: PropTypes.string.isRequired,
})).isRequired,
onTimeFilterChange: PropTypes.func.isRequired,
selectedTimeFilter: PropTypes.string.isRequired,
rankFilters: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string,
value: PropTypes.string.isRequired,
})).isRequired,
onRankFilterChange: PropTypes.func.isRequired,
selectedRankFilter: PropTypes.string.isRequired,
winnersWheelTitle: PropTypes.string.isRequired,
usersAmount: PropTypes.number.isRequired,
friendsWinnersPercent: PropTypes.number.isRequired,
connectionsWinnersPercent: PropTypes.number.isRequired,
friendsWinnersAmount: PropTypes.number.isRequired,
connectionsWinnersAmount: PropTypes.number.isRequired,
allWinnersAmount: PropTypes.number.isRequired,
winners: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
})),
onWinnerClick: PropTypes.func.isRequired,
onWinnerPanelClose: PropTypes.func.isRequired,
selectedWinnerId: PropTypes.string,
onShowAllWinners: PropTypes.func.isRequired,
onHideAllWinners: PropTypes.func.isRequired,
allWinnersShown: PropTypes.bool,
}
export default WinnersPanel
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { size } from 'styled-theme'
import { imagesPath } from '../../../config'
import { absoluteMiddleCSS } from '../../themes/style-snippets'
const WinImage = styled.img`
width: auto;
max-height: 100%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
`
const imageSelectedCSS = css`
&:after {
content: '';
width: 50px;
height: 50px;
background: url('${imagesPath}/star_gold.png') no-repeat;
background-position: center;
background-size: 85%;
opacity: 0.8;
${absoluteMiddleCSS};
}
`
const WinProductsHolder = styled.div`
width: ${props => props.size}px;
height: ${props => props.size}px;
overflow: hidden;
position: relative;
box-shadow: 3px 0 8px -1px rgba(0,0,0,0.4);
margin-right: 10px;
border-top-right-radius: 6px;
border-bottom-right-radius: 6px;
${size('mobileMediaQuery')} {
border-radius: 6px;
}
flex-shrink: 0;
${props => props.isSelected && imageSelectedCSS};
`
const WinProductsImage = ({ src, size, isSelected }) => (
<WinProductsHolder isSelected={isSelected} size={size}><WinImage src={src} /></WinProductsHolder>
)
WinProductsImage.propTypes = {
src: PropTypes.string,
size: PropTypes.number,
isSelected: PropTypes.bool,
}
export default WinProductsImage
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, font, size } from 'styled-theme'
import { Link } from 'react-router-dom'
import Logo from '../../atoms/Logo'
import ContainerLimited from '../../atoms/ContainerLimited'
const Holder = styled.div`
width: 100%;
background-color: ${palette('main', 0)};
`
const FlexHolder = styled.div`
display: flex;
flex-direction: row;
align-items: flex-end;
justify-content: space-between;
width: 100%;
padding: 30px 0 50px;
box-sizing: border-box;
position: relative;
z-index: 50;
${size('mobileMediaQuery')} {
flex-direction: column;
align-items: center;
}
`
const LinksHolder = styled.div`
display: inline-flex;
flex-direction: row;
align-items: center;
justify-content: center;
& > * {
margin-left: 20px;
}
${size('mobileMediaQuery')} {
margin-top: 20px;
& > * {
margin: 0 10px;
}
}
`
const StyledLink = styled(Link)`
font-family: ${font('main')};
color: ${palette('grey', 0)};
font-size: ${size('textRegular')};
font-weight: 400;
text-decoration: none;
&:hover {
text-decoration: underline;
}
`
const Footer = () => {
return (
<Holder>
<ContainerLimited>
<FlexHolder>
<Logo white />
<LinksHolder>
<StyledLink to={'./terms'}>Terms</StyledLink>
<StyledLink to={'./privacy'}>Privacy</StyledLink>
<StyledLink to={'./faq'}>FAQ</StyledLink>
</LinksHolder>
</FlexHolder>
</ContainerLimited>
</Holder>
)
}
export default Footer
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, font, size } from 'styled-theme'
import ButtonMain from '../../atoms/ButtonMain'
import { absoluteMiddleCSS } from '../../themes/style-snippets'
import { fadeIn, badgeAppear } from '../../themes/keyframes'
const Overlay = styled.div`
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
z-index: 20000;
animation: ${fadeIn} 0.3s ease forwards 1;
`
const Popup = styled.div`
${absoluteMiddleCSS};
background-color: ${palette('grey', 0)};
min-width: 300px;
min-height: 200px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
border-radius: 6px;
animation: ${badgeAppear} 0.3s ease forwards 1;
`
const Header = styled.div`
height: 40px;
line-height: 40px;
background-color: ${palette('main', 0)};
color: ${palette('grey', 0)};
font-size: 14px;
padding: 0 30px;
box-sizing: border-box;
width: 100%;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
`
const PopupBody = styled.div`
flex-grow: 1;
box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-around;
width: 100%;
padding: 30px;
`
const Top = styled.div`
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
margin-bottom: 30px;
`
const Title = styled.div`
font-size: 20px;
color: ${palette('text', 0)};
`
const ImageHolder = styled.div`
width: 90px;
height: 90px;
overflow: hidden;
position: relative;
margin-right: 30px;
`
const Image = styled.img`
${absoluteMiddleCSS};
max-width: 100%;
height: auto;
`
const Description = styled.p`
font-size: 14px;
color: ${palette('text', 0)};
width: 100%;
text-align: center;
padding: 0;
margin: 0 0 25px;
`
const Separator = styled.div`
width: 100%;
height: 1px;
background-color: ${palette('grey', 3)};
margin: 10px 0 20px;
`
const Details = styled.div`
font-size: 12px;
color: ${palette('grey', 4)};
width: 100%;
position: relative;
margin-top: 30px;
&:after {
content: 'Additional info';
background-color: ${palette('grey', 0)};
position: absolute;
top: 3px;
left: 50%;
padding: 0 10px;
transform: translateX(-50%);
}
`
const OfferPopup = ({ title, image, description, url, details, onClose, onActionClick }) => {
const onOverlayClick = ev => (ev.currentTarget === ev.target) && onClose()
return (
<Overlay onClick={onOverlayClick}>
<Popup>
<Header>You are leaving the site</Header>
<PopupBody>
<Top>
<ImageHolder>
<Image src={image} />
</ImageHolder>
<Title>{title}</Title>
</Top>
<Description>{description}</Description>
<ButtonMain onClick={onActionClick}>Do an action</ButtonMain>
{!!details && (
<Details>
<Separator />
{details}
</Details>
)}
</PopupBody>
</Popup>
</Overlay>
)
}
OfferPopup.propTypes = {
title: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
// other attributes might be here depending on offer type
url: PropTypes.string.isRequired,
details: PropTypes.string,
onClose: PropTypes.func.isRequired,
onActionClick: PropTypes.func,
}
export default OfferPopup
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import theme from '../../themes/default'
import { imagesPath } from '../../../config'
const WheelContainer = styled.div``
const Wheel = ({ className }) => {
return (
<WheelContainer className={className}>
<svg
style={{
fontFamily: theme.fonts.main,
paddingTop: '32px',
overflow: 'visible',
}}
className="wheelSVG"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
textRendering="optimizeSpeed"
>
<defs>
<filter id="shadow" x="-100%" y="-100%" width="550%" height="550%">
<feOffset in="SourceAlpha" dx="0" dy="0" result="offsetOut"></feOffset>
<feGaussianBlur stdDeviation="9" in="offsetOut" result="drop" />
<feColorMatrix
in="drop"
result="color-out"
type="matrix"
values="0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 .3 0"
/>
<feBlend in="SourceGraphic" in2="color-out" mode="normal" />
</filter>
<pattern id="peg-image" patternUnits="userSpaceOnUse" width="100" height="100">
<image xlinkHref={`${imagesPath}/wheel_pin.png`} x="0" y="0" width="65" height="119" />
</pattern>
</defs>
<g className="mainContainer">
<g className="wheel" />
</g>
<g className="centerCircle" />
<g className="wheelOutline" />
<g className="pegContainer" opacity="1">
<path
className="peg"
visibility="hidden"
fill="url(#peg-image)"
d="M33.8,0C8.6,0-2.3,23.8,0.4,41.3c5.2,33.1,33.4,64.5,33.4,64.5S62,74.4,67.2,41.3C69.9,23.8,59,0,33.8,0z"
/>
</g>
<g className="valueContainer" />
</svg>
<div className="toast" style={{ display: 'none' }}>
<p />
</div>
</WheelContainer>
)
}
Wheel.propTypes = {
className: PropTypes.string,
}
export default Wheel
<file_sep>export const initialState = { isLoading: false, activities: [], err: null }
export const getActivities = (state = initialState) => state.activities
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { palette, size } from 'styled-theme'
import { absoluteMiddleCSS } from '../../themes/style-snippets'
import { fadeIn, badgeAppear } from '../../themes/keyframes'
const Overlay = styled.div`
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.7);
animation: ${fadeIn} 0.3s ease forwards 1;
`
const Popup = styled.div`
${absoluteMiddleCSS};
background-color: ${palette('grey', 0)};
padding: 30px 15px;
border-radius: 14px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 80%;
animation: ${badgeAppear} 0.3s ease forwards 1;
`
const Image = styled.img`
display: inline-block;
max-width: 50%;
height: auto;
`
const Title = styled.h2`
margin: 30px 0 20px;
padding: 0;
font-size: ${size('prizeTitle')};
color: ${palette('main', 0)};
`
const Description = styled.p`
margin: 0;
padding: 0;
font-size: ${size('textRegular')};
color: ${palette('text', 0)};
text-align: center;
`
const BadgePopup = ({ image, title, description, onClose }) => {
return (
<Overlay onClick={onClose}>
<Popup>
<Image src={image} />
<Title>{title}</Title>
<Description>{description}</Description>
</Popup>
</Overlay>
)
}
BadgePopup.propTypes = {
image: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
description: PropTypes.string,
onClose: PropTypes.func.isRequired,
}
export default BadgePopup
|
77def6ce82f673ba355503ddb48900deacfd9be5
|
[
"JavaScript",
"Markdown"
] | 95
|
JavaScript
|
ppkinev/Win-what-you-buy
|
858eac8d674b20d4f6d4aa1007a55182d9364989
|
a20d78cb845ef94c3890be61e5c1a89f48746e94
|
refs/heads/master
|
<repo_name>wondek/stats<file_sep>/ch2_.py
"""
http://stackoverflow.com/questions/2682144/matplotlib-analog-of-rs-pairs
"""
from __future__ import division
import numpy as np
import pylab as pl
import pandas as pd
import rpy2
pd.set_option('display.width', 180)
pd.read_csv('Credit.csv')
credit = pd.read_csv('Credit.csv')
axes = pd.tools.plotting.scatter_matrix(credit)
cr2 = credit.set_index('Unnamed: 0')
axes = pd.tools.plotting.scatter_matrix(cr2)
pl.show()<file_sep>/outer.py
from __future__ import division
import sys
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
def p(X):
print '-' * 80
print X
print X.shape
X = np.ones((3, 2)) * 2
Y = np.ones((4, 2)) * 2
p(X)
p(Y)
A = np.subtract.outer(X, Y)
p(A)
A = np.subtract.outer(X, Y, axis=0)
p(A)
<file_sep>/find_k.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Testing the Gap Statistic to find the k in k-means
http://datasciencelab.wordpress.com/2013/12/27/finding-the-k-in-k-means-clustering/
"""
from __future__ import division
import sys
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
################################################################################
# ARRAY MANIPULATION CODE
################################################################################
def norm(a, axis=-1):
"""NumPy 1.8 style norm(). Needed for the NumPy 1.7.1 I am using.
a: A NumPy ndarray
axis: Axis to calculate norm along. Whole ndarray is normed if axis is None
Returns: norm along axis
"""
if axis is None:
return np.linalg.norm(a)
return np.apply_along_axis(np.linalg.norm, axis, a)
def subtract_outer(a, b):
"""The outer difference of a and b where
a_b = subtract_outer(a, b) => a_b[i, j, :] = a[i, :] - b[j, :]
a: A NumPy ndarray
b: A NumPy ndarray
Returns: outer difference of a and b
"""
assert a.shape[1] == b.shape[1]
assert len(a.shape) == 2 and len(b.shape) == 2
n = a.shape[1]
a_b = np.empty((a.shape[0], b.shape[0], n))
for i in xrange(n):
a_b[:, :, i] = np.subtract.outer(a[:, i], b[:, i])
return a_b
################################################################################
# CODE TO FIND K IN K-MEANS
################################################################################
def find_centers(X, k):
"""Divide the points in X into k clusters
X: points
k: number of clusters to separate points into
Returns: mu, labels
mu: centers of clusters
labels: indexes of points in X belonging to each cluster
"""
estimator = KMeans(init='k-means++', n_clusters=k, n_init=10)
estimator.fit(X)
mu = estimator.cluster_centers_
labels = estimator.labels_
return mu, labels
def Wk(X, mu, labels):
"""Compute the intra-cluster distances for the k clusters in X described by mu and labels.
X: points
mu: centers of clusters
labels: indexes of points in X belonging to each cluster
Returns: Normalized intra-cluster distance as defined in
http://datasciencelab.wordpress.com/2013/12/27/finding-the-k-in-k-means-clustering/
"""
k = mu.shape[0]
clusters = [X[np.where(labels == i)] for i in xrange(k)]
n = [x.shape[0] for x in clusters]
return sum(norm(clusters[i] - mu[i], None)**2/(2 * n[i]) for i in xrange(k))
def bounding_box(X):
"""Compute the bounding box for the points in X. This is the highest and lowest
x and y coordinates of all the points.
X: points
Returns: (xmin, xmax), (ymin, ymax)
xmin, xmax: min and max of x coordinates of X
ymin, ymax: min and max of y coordinates of X
"""
x, y = X[:, 0], X[:, 1]
return (x.min(), x.max()), (y.min(), y.max())
def gap_statistic(X, min_k, max_k, b):
"""Calculate gap statistic for X for k = min_k through k = max_k
using b reference data sets
X: points
min_k: lowest k to test
max_k: highest k to test
b: number of reference data sets to test against
Returns: Generator yielding k, logWk, logWkb, sk for min_k <= k <= max_k
k: This k
Wks: log(intra-cluster distance) for k
Wkbs: average reference log(intra-cluster distance) for k
sk: Normalized std dev log(intra-cluster distance) for k
"""
N = X.shape[0]
(xmin, xmax), (ymin, ymax) = bounding_box(X)
def reference_results(k):
# Create b reference data sets
BWkbs = np.zeros(b)
for i in xrange(b):
Xb = np.vstack([np.random.uniform(xmin, xmax, N),
np.random.uniform(ymin, ymax, N)]).T
mu, labels = find_centers(Xb, k)
BWkbs[i] = np.log(Wk(Xb, mu, labels))
logWkb = np.sum(BWkbs)/b
sk = np.sqrt(np.sum((BWkbs - logWkb)**2)/b) * np.sqrt(1 + 1/b)
return logWkb, sk
for k in xrange(min_k, max_k + 1):
mu, labels = find_centers(X, k)
logWk = np.log(Wk(X, mu, labels))
logWkb, sk = reference_results(k)
yield k, logWk, logWkb, sk
# Parameters for gap statistic calculation
B = 10 # Number of reference data sets
MIN_K = 1 # Lowest k to test
MAX_K = 10 # Highest k to test
def find_k(X, verbose=1):
"""Find the best k for k-means gap for X using the Gap Statistic
X: points
verbose: verbosity level: 0, 1 or 2
Returns: best k if found, otherwise -1
"""
for i, (k1, logWk1, logWkb1, sk1) in enumerate(gap_statistic(X, MIN_K, MAX_K + 1, B)):
gap1 = logWkb1 - logWk1
if i > 0:
if verbose >= 2:
print('%5d %5.2f %5.2f %5.2f : %5.2f' % (k, logWk, logWkb, sk, gap))
if gap > gap1 - sk1:
return k
k, logWk, logWkb, sk, gap = k1, logWk1, logWkb1, sk1, gap1
return -1
################################################################################
# TESTING CODE
################################################################################
# GRID_NUMBER is a square number close to GRID_NUMBER_TARGET
GRID_NUMBER_TARGET = 1000
GRID_WIDTH = int(np.sqrt(GRID_NUMBER_TARGET))
GRID_NUMBER = GRID_WIDTH**2
# UNIFORM_GRID an array of GRID_WIDTH x GRID_WIDTH evenly spaced points on [-1, 1] x [-1, 1]
xv, yv = np.meshgrid(np.linspace(-1, 1, GRID_WIDTH), np.linspace(-1, 1, GRID_WIDTH))
UNIFORM_GRID = np.vstack([xv.ravel(), yv.ravel()]).T
def maximally_spaced_points(k, r):
"""Return maximally spaced points in square of radius 1 around origin
(i.e. square containing x, y such that -1 <= x <= 1, -1 <= y <= 1)
Try to keep points at least distance r from edges of square
k: number of points
r: desired minimum distance from point to edge of square
Returns: ndarray of N 2-d points
"""
if k == 1:
return np.random.uniform(-min(r, 0.5), min(r, 0.5), size=(k, 2))
scale = 1.0 - min(r, 0.5)
# Start by randomly distributing points over unit radius square
x0 = np.random.uniform(-1.0, 1.0, size=(k, 2))
# Maximize minimum distance between centroids
for m in xrange(10):
changed = False
for i in xrange(k):
# Test replacing ith element in x0 all with elements in UNIFORM_GRID to find
# the one that maximizes the minimum distance to elements other than ith in x0
# If this minimum distance is greater than current_min then make it the ith element
# in x0
x1 = np.vstack((x0[:i, :], x0[i+1:, :]))
# minimum distance between ith element in x0 and all other elements in x0
current_min = norm(x1 - x0[i], 1).min()
# diffs[j] = minimum distance between jth element in UNIFORM_GRID and all elements
# in x0 other than ith
diffs = norm(subtract_outer(UNIFORM_GRID, x1)).min(axis=-1)
# max_j_min = index of element in UNIFORM_GRID that maximizes
# minimum distance between ith element in x0 and all other elements in x0
max_j_min = np.argmax(diffs)
if diffs[max_j_min] > current_min:
x0[i] = UNIFORM_GRID[max_j_min]
changed = True
if not changed and m > 1:
break
# Shrink square to get points r-ish distant from edges of unit radius square
return x0 * scale
def init_board_gauss(N, k, r):
"""Initialize board of N points with k clusters
Board is square of radius 1 around origin
(i.e. square containing x, y such that -1 <= x <= 1, -1 <= y <= 1)
Try to space cluster centers as far apart as possible while keeping them at least distance
r from edges of unit radius square. This is done in an approximate way by generating
random points around maximally spaced nuclei.
N: number of points
k: number of cluster
r: desired std dev of points in cluster from cluster center
Returns: X, centroids, labels
X: points
centroids: centroids of clusters
labels: cluster index for each point
"""
def add_cluster(X, j0, j1, cx, cy, s):
"""Add a cluster of normally distributed points to x for indexes [j0,j1)
around center cx, cy and std dev s.
X: points
j0, j1: Add points with indexs j such that j0 <= j < j1
cx, cy: Centers of normal distrubtion in x any y directions
s: Desired std dev of normal distrubtion in x any y directions
"""
j = j0
while j < j1:
a, b = np.random.normal(cx, s), np.random.normal(cy, s)
# Continue drawing points from the distribution in the range (-1, 1)
if abs(a) < 1 and abs(b) < 1:
X[j, :] = a, b
j += 1
return np.mean(X[j0:j1], axis=0)
nuclei = maximally_spaced_points(k, r)
n = N/k
X = np.empty((N, 2))
centroids = np.empty((k, 2))
labels = np.empty(N, dtype=int)
for i, (cx, cy) in enumerate(nuclei):
j0, j1 = int(round(i * n)), int(round((i + 1) * n))
centroids[i] = add_cluster(X, j0, j1, cx, cy, r)
labels[j0:j1] = i
return X, centroids, labels
def closest_indexes(centroids, mu):
"""Find the elements in centroids that are closest to the elements of mu and
return arrays of indexes that
map a centroid element to the closest element of mu, and
map a mu element to the closest element of centroids
centroids: ndarray of 2d points
mu: ndarray of 2d points
Returns: centroid_indexes, mu_indexes
centroid_indexes[m] is the centroid index corresponding to mu index m
mu_indexes[c] is the mu index corresponding to centroid index c
"""
k = centroids.shape[0]
if k == 1:
return [0], [0]
# separations[m, c] = distance between mu[m] and centroid[c]
separations = norm(subtract_outer(mu, centroids), 2)
# indexes of diffs in increasing order of distance
order = np.argsort(separations, axis=None)
centroids_done = set()
mu_done = set()
centroid_indexes = [-1] * k
mu_indexes = [-1] * k
# Go through the mu[m], centroid[c] pairs in order of increasing separation
# If m and c indexes are not assigned, set centroid_indexes[m] = c and mu_indexes[c] = m
for i in xrange(k**2):
c = order[i] % k
m = order[i] // k
if c in centroids_done or m in mu_done:
continue
centroid_indexes[m] = c
mu_indexes[c] = m
centroids_done.add(c)
mu_done.add(m)
if len(mu_done) >= k:
break
return centroid_indexes, mu_indexes
def match_clusters(centroids, mu, predicted_labels):
"""Return versions of mu and predicted_labels that are re-indexed so that
mu[i] is closer to centroids[i] than any other element of centroids.
centroids: ndarray of 2d points
mu: ndarray of 2d points
predicted_labels: ndarray of integers based on the mu indexes
Returns: mu2, predicted_labels2
mu2: mu re-indexed as described above
predicted_labels2: predicted_labels updated for the mu => mu2 re-indexing
"""
centroid_indexes, mu_indexes = closest_indexes(centroids, mu)
mu2 = mu[mu_indexes]
predicted_labels2 = np.empty(predicted_labels.shape, dtype=int)
for i in xrange(predicted_labels.shape[0]):
predicted_labels2[i] = centroid_indexes[predicted_labels[i]]
return mu2, predicted_labels2
def estimate_difficulty(k, X, centroids, labels):
"""Estimate difficulty of matching
1) find clusters for known k,
2) match them to the test clusters and
3) find which points don't belong to the clusters they were created for
This gives a crude measure of how much the test clusters overlap and of
how well the detected clusters match the test cluster
k: Number of clusters in test board
X: Points in test board
centroids: Centroids of clusters in test board
labels: Centroid labels of X
Returns: mu, different_labels
mu: Centroids of attempted clustering of test board
different_labels: Indexes of points in X for which the attempted clustering
gave different labels than board was created with
"""
mu, predicted_labels = find_centers(X, k)
mu, predicted_labels = match_clusters(centroids, mu, predicted_labels)
different_labels = np.nonzero(labels != predicted_labels)[0]
return mu, different_labels
COLOR_MAP = ['b', 'r', 'k', 'y', 'c', 'm']
# http://matplotlib.org/api/markers_api.html
MARKER_MAP = ['v', 'o', 's', '^', '<', '>', '8']
def COLOR(i): return COLOR_MAP[i % len(COLOR_MAP)]
def MARKER(i): return MARKER_MAP[i % len(MARKER_MAP)]
def graph_board(k, N, r, X, centroids, labels, mu, different_labels):
"""Graph a test board
k, N, r are the instructions for creating the test board
X, centroids, labels describe the test board that was created
mu, different_labels are an indication of how difficult the test board is.
boards with mu a long way from centroids or with a high
proprorting of different_labels are expected to be more difficult
k: Number of clusters in test board
N: Number of points in test board
r: Radius of cluster distributions in test board
X: Points in test board
centroids: Centroids of clusters in test board
labels: Centroid labels of X
mu: Centroids of attempted clustering of test board
different_labels: Indexes of points in X for which the attempted clustering gave different
labels than board was created with
"""
fig, ax = plt.subplots()
for i in xrange(k):
x = X[np.where(labels == i)]
ax.scatter(x[:, 0], x[:, 1], s=50, c=COLOR(i), marker=MARKER(i))
for i in different_labels:
ax.scatter(X[i, 0], X[i, 1], s=100, c='k', marker='x', linewidths=1, zorder=4)
for i in xrange(k):
cx, cy = centroids[i, :]
mx, my = mu[i, :]
dx, dy = mu[i, :] - centroids[i, :]
ax.scatter(cx, cy, marker='*', s=199, linewidths=3, c='k', zorder=10)
ax.scatter(cx, cy, marker='*', s=181, linewidths=2, c=COLOR(i), zorder=20)
ax.scatter(mx, my, marker='+', s=199, linewidths=4, c='k', zorder=11)
ax.scatter(mx, my, marker='+', s=181, linewidths=3, c=COLOR(i), zorder=21)
if dx**2 + dy**2 >= 0.001:
ax.arrow(cx, cy, dx, dy, lw=1, head_width=0.05, length_includes_head=True,
zorder=9, fc='y', ec='k')
ax.set_xlabel('x', fontsize=20)
ax.set_ylabel('y', fontsize=20)
ax.set_title('Clusters: k=%d, N=%d, r=%.2f, diff=%d (%.2f)' % (k, N, r,
different_labels.size, different_labels.size/N))
plt.xlim((-1.0, 1.0))
plt.ylim((-1.0, 1.0))
ax.grid(True)
fig.tight_layout()
plt.show()
def run_test(k, N, r, do_graph=False, verbose=1):
"""Run a test to see if find_k(X) returns the correct number of clusters for
test board X created with parameters k, N, r
k, N, r are the instructions for creating the test board
k: Number of clusters in test board
N: Number of points in test board
r: Radius of cluster distributions in test board
do_graph: Graph the test board if True
verbose: verbosity level: 0, 1 or 2
Returns: correct, n_different
correct: True if find_k() returned correct k
n_diffrent: Number points in test board for which the attempted clustering
gave different labels than board was created with. This is a measure
of difficulty
"""
assert MIN_K <= k <= MAX_K, 'invalid k=%d' % k
# Create a board of points to test
X, centroids, labels = init_board_gauss(N, k, r)
# Do the test!
predicted_k = find_k(X, verbose)
correct = predicted_k == k
# Estimate difficulty
mu, different_labels = estimate_difficulty(k, X, centroids, labels)
if verbose >= 1:
print(' k=%d,N=%3d,r=%.2f,diff=%.2f: predicted_k=%d,correct=%s' % (k, N, r,
different_labels.size/N, predicted_k, correct))
if do_graph:
graph_board(k, N, r, X, centroids, labels, mu, different_labels)
return correct, different_labels.size
def test_with_graphs():
"""Run some tests and graph the results
This lets you see what some typical test boards look like
"""
run_test(2, 50, 1.0, do_graph=True)
run_test(10, 100, 0.01, do_graph=True)
run_test(2, 100, 0.01, do_graph=True)
run_test(10, 100, 0.2, do_graph=True)
run_test(2, 100, 0.25, do_graph=True)
run_test(9, 200, 0.2, do_graph=True)
run_test(4, 200, 0.3, do_graph=True)
run_test(7, 200, 0.3, do_graph=True)
run_test(4, 200, r, do_graph=True)
run_test(5, 50, r, do_graph=True)
run_test(5, 50, r, do_graph=True)
run_test(7, 400, r, do_graph=True)
def test_range(n_repeats, verbose=1):
"""Run a range of tests with different test board parameters and printthe results to stdout.
n_repeats: Number of tests to run for each k, N, r combination
verbose: verbosity level: 0, 1 or 2
Returns: correct, n_different
correct: True if find_k() returned correct k
n_diffrent: Number points in test board for which the attempted clustering
gave different labels than board was created with. This is a measure
of difficulty
"""
results = []
print('n_repeats=%d' % n_repeats)
print('=' * 80)
# Run tests printing results as we go
for N in (20, 50, 100, 200, 400, 10**3, 10**4):
for k in (1, 2, 3, 5, 7, 9):
for r in (0.01, 0.1, 0.3, 0.5, 0.5**0.5, 1.0):
if not MIN_K <= k <= MAX_K:
continue
corrects, differents = zip(*(run_test(k, N, r, do_graph=False, verbose=verbose)
for _ in xrange(n_repeats)))
n_correct, n_different = sum(corrects), sum(differents)
results.append((k, N, r, n_correct, n_different))
print('k=%d,N=%3d,r=%.2f: %2d of %d = %3d%% (diff=%.2f)' % (k, N, r,
n_correct, n_repeats, int(100.0 * n_correct/n_repeats),
n_different/(n_repeats * N)))
if verbose >= 1:
print('-' * 80)
sys.stdout.flush()
# Print summary
print('=' * 80)
for k, N, r, n_correct, n_different in results:
print('k=%d,N=%3d,r=%.2f: %2d of %d = %3d%% (diff=%.2f)' % (k, N, r,
n_correct, n_repeats, int(100.0 * n_correct/n_repeats),
n_different/(n_repeats * N)))
def main():
print(__doc__)
print('')
print('NumPy: %s' % np.version.version)
np.random.seed(111)
#test_with_graphs()
n_repeats = 10
test_range(n_repeats, verbose=1)
print('')
main()
<file_sep>/forward_stepwise_regression.py
"""
http://statsmodels.sourceforge.net/devel/examples/generated/example_ols.html
"""
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt
from statsmodels.sandbox.regression.predstd import wls_prediction_std
def test_linear():
np.random.seed(111)
n_sample = 100
max_val = 10
x = np.linspace(0, max_val, n_sample)
#X = np.column_stack((x, x**2))
X = np.c_[x, x**2]
beta = np.array([1, 0.1, 10])
e = np.random.normal(size=n_sample)
X = sm.add_constant(X, prepend=False)
y = np.dot(X, beta) + e
for i in xrange(5):
print '%3d: %s %s' % (i, X[i, :], y[i])
print
print
model = sm.OLS(y, X)
results = model.fit()
print results.summary()
print
print
print results.params
print results.rsquared
def test_nonlinear():
np.random.seed(111)
n_sample = 50
max_val = 30
sig = 0.5
x = np.linspace(0, max_val, n_sample)
X = np.c_[x, np.sin(x), (x - 5)**2, np.ones(n_sample)]
beta = np.array([0.5, 0.5, -0.02, 5.0])
e = np.random.normal(size=n_sample)
#X = sm.add_constant(X, prepend=False)
y_true = np.dot(X, beta)
y = y_true + sig * e
for i in xrange(5):
print '%3d: %s %s' % (i, X[i, :], y[i])
print
print
model = sm.OLS(y, X)
results = model.fit()
print results.summary()
print
print
print results.params
print results.rsquared
print results.bse
print results.predict()
plt.figure()
plt.plot(x, y, 'o', x, y_true, 'b-')
prstd, iv_l, iv_u = wls_prediction_std(results)
plt.plot(x, results.fittedvalues, 'r--.')
plt.plot(x, iv_u, 'r--')
plt.plot(x, iv_l, 'r--')
plt.title('blue: true, red: OLS')
plt.show()
def test_dummy():
nsample = 50
groups = np.zeros(nsample, int)
groups[20:40] = 1
groups[40:] = 2
dummy = (groups[:, None] == np.unique(groups)).astype(float)
x = np.linspace(0, 20, nsample)
X = np.c_[x, dummy[:, 1:], np.ones(nsample)]
beta = [1., 3, -3, 10]
y_true = np.dot(X, beta)
e = np.random.normal(size=nsample)
y = y_true + e
#test_linear()
test_nonlinear()
<file_sep>/k_results.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Analyze results returns by find_k
usage: python k_results.py <results file> [sort key(s)]
Sort keys: k n r m d
Lower-case sorts in increasing order
Upper-case sorts in decreasing order
k: number of clusters
n: total number of points
r: cluster radius (~ std dev)
m: number of correct k estimates
d: a measure of difficulty, higher is more difficult
e.g.
python k_results.py results.txt k N
sorts results.txt by number of clusters in increasing order then by number of points
in decreasing order
python k_results.py results.txt m r
sorts results.txt by number of correct results in increasing order then by cluster
radius in decreasing order
"""
from __future__ import division
import re, sys
def is_upper(s):
return s.upper() == s
DIVIDER = '=' * 80
RE_RESULT = re.compile(r'''
\s*k\s*=\s*(\d+)\s*,
\s*N\s*=\s*(\d+)\s*,
\s*r\s*=\s*(\d*\.\d*)\s*:
\s*(\d+)\s*of\s*(\d+)
\s*=\s*(\d+)%\s*
\(\s*diff\s*=\s*(\d*\.\d*)\s*\)
''',
re.VERBOSE)
CONVERTERS = [
lambda s: int(s),
lambda s: int(s),
lambda s: float(s),
lambda s: int(s),
lambda s: int(s),
lambda s: int(s)/100.0,
lambda s: float(s),
]
SORT_KEY_NAMES = ['<KEY>']
def make_sort_key(options):
"""Make results sort key described in module doc string
"""
sort_order = SORT_KEY_NAMES[:]
sort_order_lower = [s.lower() for s in sort_order]
for s in reversed(options):
if not s.lower() in sort_order_lower:
continue
i = sort_order_lower.index(s.lower())
sort_order = [s] + sort_order[:i] + sort_order[i + 1:]
sort_order_lower = [s.lower() for s in sort_order]
return [(SORT_KEY_NAMES.index(s.lower()), -1 if is_upper(s) else 1) for s in sort_order]
def sort_func(result):
"""Sort function for results described in module doc string
"""
return [result[i] * sign for i, sign in sort_key]
def read_results(path):
results = []
num_dividers = 0
with open(path, 'rt') as f:
for i, line in enumerate(f):
line = line.rstrip('\r\n')
if line.startswith(DIVIDER):
num_dividers += 1
continue
elif num_dividers < 2:
continue
m = RE_RESULT.search(line)
if not m:
continue
k, N, r, m, M, mM, diff = [CONVERTERS[i](m.group(i + 1)) for i in range(7)]
n_correct = m
n_repeats = M
n_different = (int)(n_repeats * N * diff)
results.append((k, N, r, n_correct, n_different))
return results, n_repeats
if len(sys.argv) < 1:
print (__doc__)
exit(1)
path = sys.argv[1]
options = [s[0] for s in sys.argv[2:]]
results, n_repeats = read_results(path)
sort_key = make_sort_key(options)
results.sort(key=sort_func)
for k, N, r, n_correct, n_different in results:
print('k=%d,N=%3d,r=%.2f: %2d of %d = %3d%% (diff=%.2f)' % (k, N, r,
n_correct, n_repeats, int(100.0 * n_correct/n_repeats),
n_different/(n_repeats * N)))
<file_sep>/pinv.py
import numpy as np
a = np.random.randn(2, 3)
def my_pinv(a):
b = np.dot(a.T, a)
print b
c = np.linalg.inv(b)
print c
d = np.dot(c, a.T)
return d
return np.dot(np.linalg.inv(np.dot(a.T, a)), a.T)
def test(a):
print '-' * 80
b = np.linalg.pinv(a)
x = np.dot(b, a)
#c = my_pinv(a)
print a
# print
# print b
#print c
print
print x
#print np.dot(c, a)
print a.shape, np.max(np.abs(x- np.eye(x.shape[0]) ))
test(np.eye(3, dtype=float) * 2)
#test(np.ones((2, 2), dtype=float) * 2)
test(np.ones((2, 3), dtype=float) * 2)
test(np.ones((3, 2), dtype=float) * 2)
a = np.zeros((3, 3), dtype=float)
for i in xrange(a.shape[0]):
a[i, i] = np.random.randn()
test(a)
a = np.random.randn(3, 3) * 0.5
for i in xrange(a.shape[0]):
a[i, i] = np.random.randn()
test(a)
a = np.eye(3, dtype=float) + np.random.randn(3, 3) * 1e-9
test(a)
print '=' * 80
for _ in xrange(5):
a = np.eye(3, dtype=float) + np.random.randn(3, 3) * 1e-9
a[1, :] = a[0, :] + np.random.randn(3) * 1e-9
a[2, :] = a[0, :] + np.random.randn(3) * 1e-9
a[:, 0] = 1
a[0, 1] = 0
a[1, 1] = 0
a[0, 2] = 0
test(a)
a = np.eye(10, dtype=float) + np.random.randn(10, 10) * 1e-9
test(a) <file_sep>/norm.py
from __future__ import division
import sys
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
def norm(X, axis=-1):
return np.apply_along_axis(np.linalg.norm, axis, X)
def p(X):
print '-' * 80
print X
print X.shape
X = np.ones((4,3,2))
p(X)
X[0, 0, 0] = 1
p(X)
Y = [norm(X, i) for i in range(3)]
for i in range(3):
p(Y[i])
p(norm(X))
<file_sep>/find_k - Copy (2).py
"""
Testing the Gap Statistic to find the k in k-means
http://datasciencelab.wordpress.com/2013/12/27/finding-the-k-in-k-means-clustering/
"""
from __future__ import division
import sys
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
def find_centers(X, k):
"""Divide the points in X into k clusters
X: points
k: number of clusters to separate points into
Returns: mu, labels
mu: centers of clusters
labels: indexes of points in X belonging to each cluster
"""
estimator = KMeans(init='k-means++', n_clusters=k, n_init=10)
estimator.fit(X)
mu = estimator.cluster_centers_
labels = estimator.labels_
return mu, labels
def Wk(X, mu, labels):
"""Compute the intra-cluster distances for the k clusters in X described by mu and labels.
X: points
mu: centers of clusters
labels: indexes of points in X belonging to each cluster
Returns: Normalized intra-cluster distance as defined in
http://datasciencelab.wordpress.com/2013/12/27/finding-the-k-in-k-means-clustering/
"""
k = mu.shape[0]
clusters = [X[np.where(labels == i)] for i in xrange(k)]
n = [x.shape[0] for x in clusters]
return sum(np.linalg.norm(clusters[i] - mu[i])**2/(2 * n[i]) for i in xrange(k))
def bounding_box(X):
"""Compute the bounding box for the points in X. This is the highest and lowest
x and y coordinates of all the points.
X: points
Returns: (xmin, xmax), (ymin, ymax)
xmin, xmax: min and max of x coordinates of X
ymin, ymax: min and max of y coordinates of X
"""
x, y = X[:, 0], X[:, 1]
return (x.min(), x.max()), (y.min(), y.max())
def gap_statistic(X, min_k, max_k, b):
"""Calculate gap statistic for X for k = min_k through k = max_k
using b reference data sets
X: points
min_k: lowest k to test
max_k: highest k to test
b: number of reference data sets to test against
Returns: Generator yielding k, logWk, logWkb, sk for min_k <= k <= max_k
k: This k
Wks: log(intra-cluster distance) for k
Wkbs: average reference log(intra-cluster distance) for k
sk: Normalized std dev log(intra-cluster distance) for k
"""
(xmin, xmax), (ymin, ymax) = bounding_box(X)
N = X.shape[0]
def reference_results(k):
# Create b reference data sets
BWkbs = np.zeros(b)
for i in xrange(b):
Xb = np.vstack([np.random.uniform(xmin, xmax, N),
np.random.uniform(ymin, ymax, N)]).T
mu, labels = find_centers(Xb, k)
BWkbs[i] = np.log(Wk(Xb, mu, labels))
logWkb = sum(BWkbs)/b
sk = np.sqrt(sum((BWkbs - logWkb)**2)/b) * np.sqrt(1 + 1/b)
return logWkb, sk
for k in xrange(min_k, max_k + 1):
mu, labels = find_centers(X, k)
logWk = np.log(Wk(X, mu, labels))
logWkb, sk = reference_results(k)
yield k, logWk, logWkb, sk
# Parameters for gap statistic calculation
B = 10 # Number of reference data sets
MIN_K = 1 # Lowest k to test
MAX_K = 10 # Highest k to test
def find_k(X, verbose=1):
"""Find the best k for k-means gap for X using the Gap Statistic
X: points
verbose: verbosity level
Returns: best k if found, otherwise -1
"""
for i, (k1, logWk1, logWkb1, sk1) in enumerate(gap_statistic(X, MIN_K, MAX_K + 1, B)):
gap1 = logWkb1 - logWk1
if i > 0:
if verbose >= 2:
print('%5d %5.2f %5.2f %5.2f : %5.2f %s' % (k, logWk, logWkb, sk, gap))
if gap > gap1 - sk1:
return k
k, logWk, logWkb, sk, gap = k1, logWk1, logWkb1, sk1, gap1
return -1
################################################################################
# TESTING CODE
#################################################################################
# GRID_NUMBER is a square number close to GRID_NUMBER_TARGET
GRID_NUMBER_TARGET = 1000
GRID_WIDTH = int(np.sqrt(GRID_NUMBER_TARGET))
GRID_NUMBER = GRID_WIDTH**2
# UNIFORM_GRID an array of GRID_WIDTH x GRID_WIDTH evenly spaced points on [-1, 1] x [-1, 1]
xv, yv = np.meshgrid(np.linspace(-1, 1, GRID_WIDTH), np.linspace(-1, 1, GRID_WIDTH))
UNIFORM_GRID = np.vstack([xv.ravel(), yv.ravel()]).T
def maximally_spaced_points(k, r):
"""Return maximully spaced points in square of radius 1 around origin
(i.e. square containing x, y such that -1 <= x <= 1, -1 <= y <= 1)
Try to keep points at least distance r from edges of square
k: number of points
r: desired minimum distance from point to edge of square
Returns: ndarray of N 2-d points
"""
if k == 1:
return np.random.uniform(-min(r, 0.5), min(r, 0.5), size=(k, 2))
scale = 1.0 - min(r, 0.5)
# Start with randomly distributed over unit radius square
x0 = np.random.uniform(-1.0, 1.0, size=(k, 2))
# Maximize minimum distance between centroids
for m in xrange(10):
changed = False
for i in xrange(k):
# current_min = minimum distance between ith element in x0 and all other elements in x0
# Replace ith element in x0 all with elements in UNIFORM_GRID to find
# max_j_min = index of element in UNIFORM_GRID that maximizes
# minimum distance between ith element in x0 and all other elements in x0
# If the minimum distance with max_j_min is greater than current_min then make
# UNIFORM_GRID[max_j_min] the ith element in x0
x1 = np.vstack((x0[:i, :], x0[i+1:, :]))
current_min = np.apply_along_axis(np.linalg.norm, 1, x1 - x0[i]).min()
diffs = np.empty(GRID_NUMBER)
for j in xrange(GRID_NUMBER):
diffs[j] = np.apply_along_axis(np.linalg.norm, 1, x1 - UNIFORM_GRID[j]).min()
max_j_min = np.argmax(diffs)
if diffs[max_j_min] > current_min:
x0[i] = UNIFORM_GRID[max_j_min]
changed = True
if not changed and m > 1:
break
# Shrink square to get points r-ish distant from edges of unit radius square
return x0 * scale
def init_board_gauss(N, k, r):
"""Initialize board of N points with k clusters
Board is square of radius 1 around origin
(i.e. square containing x, y such that -1 <= x <= 1, -1 <= y <= 1)
Try to space cluster centers as far apart as possible while keeping them at least distance
r from edges of unit radius square. This is done in an approximate way by generating
random points around maximally spaced nuclei.
N: number of points
k: number of cluster
r: desired std dev of points in cluster from cluster center
Returns: X, centroids, labels
X: points
centroids: centroids of clusters
labels: cluster index for each point
"""
def add_cluster(X, j0, j1, cx, cy, s):
"""Add a cluster of normally distributed points to x for indexes [j0,j1)
around center cx, cy and std dev s.
X: points
: number of cluster
r: desired std dev of points in cluster from cluster center
"""
j = j0
while j < j1:
a, b = np.random.normal(cx, s), np.random.normal(cy, s)
# Continue drawing points from the distribution in the range (-1, 1)
if abs(a) < 1 and abs(b) < 1:
X[j, :] = a, b
j += 1
return np.mean(X[j0:j1], axis=0)
n = N/k
X = np.empty((N, 2))
nuclei = maximally_spaced_points(k, r)
centroids = np.empty((k, 2))
labels = np.empty(N, dtype=int)
for i, (cx, cy) in enumerate(nuclei):
j0, j1 = int(round(i * n)), int(round((i + 1) * n))
centroids[i] = add_cluster(X, j0, j1, cx, cy, r)
labels[j0:j1] = i
return X, centroids, labels
def closest_indexes(centroids, mu):
"""
k: number of labels
centroids: cluster centroids
mu: detected cluster centers
"""
k = centroids.shape[0]
if k == 1:
return [0]
x = np.empty((k, k, 2))
for i in 0, 1:
x[:, :, i] = np.subtract.outer(mu[:, i], centroids[:, i])
diffs = np.apply_along_axis(np.linalg.norm, 2, x)
order = np.argsort(diffs, axis=None)
centroids_done = set()
mu_done = set()
centroid_indexes = [-1] * k
mu_indexes = [-1] * k
for i in xrange(k**2):
c = order[i] % k
m = order[i] // k
if c in centroids_done or m in mu_done:
continue
centroid_indexes[m] = c
mu_indexes[c] = m
centroids_done.add(c)
mu_done.add(m)
if len(mu_done) >= k:
break
return centroid_indexes, mu_indexes
COLOR_MAP = ['b', 'r', 'k', 'y', 'c', 'm']
# http://matplotlib.org/api/markers_api.html
MARKER_MAP = ['v', 'o', 's', '^', '<', '>', '8']
def COLOR(i): return COLOR_MAP[i % len(COLOR_MAP)]
def MARKER(i): return MARKER_MAP[i % len(MARKER_MAP)]
def graph_data(k, N, r, X, centroids, mu, labels, different_labels):
"""
TODO: Draw circles of radius r around centroids
"""
fig, ax = plt.subplots()
for i in xrange(k):
x = X[np.where(labels == i)]
ax.scatter(x[:, 0], x[:, 1], s=50, c=COLOR(i), marker=MARKER(i))
for i in different_labels:
ax.scatter(X[i, 0], X[i, 1], s=100, c='k', marker='x', linewidths=1, zorder=4)
for i in xrange(k):
cx, cy = centroids[i, :]
mx, my = mu[i, :]
dx, dy = mu[i, :] - centroids[i, :]
ax.scatter(cx, cy, marker='*', s=199, linewidths=3, c='k', zorder=10)
ax.scatter(cx, cy, marker='*', s=181, linewidths=2, c=COLOR(i), zorder=20)
ax.scatter(mx, my, marker='+', s=199, linewidths=4, c='k', zorder=11)
ax.scatter(mx, my, marker='+', s=181, linewidths=3, c=COLOR(i), zorder=21)
if dx**2 + dy**2 >= 0.01:
ax.arrow(cx, cy, dx, dy, lw=1, head_width=0.05, length_includes_head=True,
zorder=9, fc='y', ec='k')
ax.set_xlabel('x', fontsize=20)
ax.set_ylabel('y', fontsize=20)
ax.set_title('Clusters: k=%d, N=%d, r=%.2f, diff=%d (%.2f)' % (k, N, r,
different_labels.size, different_labels.size/N))
plt.xlim((-1.0, 1.0))
plt.ylim((-1.0, 1.0))
ax.grid(True)
fig.tight_layout()
plt.show()
def match_clusters(N, centroids, labels, mu, predicted_labels):
centroid_indexes, mu_indexes = closest_indexes(centroids, mu)
mu = mu[mu_indexes]
predicted_labels2 = np.empty(predicted_labels.shape, dtype=int)
for i in xrange(N):
predicted_labels2[i] = centroid_indexes[predicted_labels[i]]
predicted_labels = predicted_labels2
return mu, predicted_labels
def test(k, N, r, do_graph=False, verbose=1):
assert MIN_K <= k <= MAX_K, 'invalid k=%d' % k
# Create a board of points to test
X, centroids, labels = init_board_gauss(N, k, r)
# Estimate difficulty of matching
# 1) find clusters for known k,
# 2) match them to the test clusters and
# 3) find which points don't belong to the clusters they were created for
# This gives a crude measure of how much the test clusters overlap and of
# how well the detected clusters match the test cluster
if verbose >= 1 or do_graph:
mu, predicted_labels = find_centers(X, k)
mu, predicted_labels = match_clusters(N, centroids, labels, mu, predicted_labels)
different_labels = np.nonzero(labels != predicted_labels)[0]
# Do the test!
predicted_k = find_k(X, verbose)
correct = predicted_k == k
if verbose >= 1:
print(' k=%d,N=%3d,r=%.2f,diff=%.2f: predicted_k=%d,correct=%s' % (k, N, r,
different_labels.size/N, predicted_k, correct))
if do_graph:
graph_data(k, N, r, X, centroids, mu, labels, different_labels)
return correct
def test_with_graphs():
test(2, 50, 1.0, do_graph=True)
test(10, 100, 0.01, do_graph=True)
test(2, 100, 0.01, do_graph=True)
test(10, 100, 0.2, do_graph=True)
test(2, 100, 0.25, do_graph=True)
test(9, 200, 0.2, do_graph=True)
test(4, 200, 0.3, do_graph=True)
test(7, 200, 0.3, do_graph=True)
test(4, 200, r, do_graph=True)
test(5, 50, r, do_graph=True)
test(5, 50, r, do_graph=True)
test(7, 400, r, do_graph=True)
def test_all(verbose=1):
M = 10
results = []
print('M=%d' % M)
print('=' * 80)
for N in (20, 50, 100, 200, 400, 10**3, 10**4):
for k in (1, 2, 3, 5, 7, 9):
for r in (0.01, 0.1, 0.3, 0.5, 0.5**0.5, 1.0):
if 5 * (k**2) > N: continue
if not MIN_K <= k <= MAX_K: continue
m = sum(test(k, N, r, do_graph=False, verbose=verbose) for _ in xrange(M))
results.append((k, N, r, m))
print 'k=%d,N=%3d,r=%.2f: %d of %d = %3d%%' % (k, N, r, m, M, int(100.0 * m/M))
if verbose >= 1:
print('-' * 80)
sys.stdout.flush()
print('=' * 80)
for k, N, r, m in results:
print 'k=%d,N=%3d,r=%.2f: %d of %d = %3d%%' % (k, N, r, m, M, int(100.0 * m/ M))
def main():
print('')
print('Numpy: %s' % np.version.version)
np.random.seed(111)
#test_with_graphs()
test_all(verbose=0)
print('')
main()
<file_sep>/README.md
stats
=====
Miscellaneous statistics, machine learning, etc
|
22a11fa650f1fd44aa72b894ce7a222b404e183f
|
[
"Markdown",
"Python"
] | 9
|
Python
|
wondek/stats
|
8fee8aba90f17fd175e8a67c1787b1e437d47bf8
|
b6ac3af05c809dc66d185c9edcde80458d1c79e6
|
refs/heads/master
|
<file_sep>#!/bin/bash
set -o errexit
set -o nounset
set -o pipefail
set -o xtrace
# Cleanup remote repositories.
for repo in "$WORKDIR/helloworld" "$WORKDIR/helloworld-release-infra"; do
cd "$repo"
git checkout master
git branch -D "$MYBRANCH"
git push origin ":$MYBRANCH"
done
# Cleanup local disk.
cd
rm -fr "$WORKDIR"
<file_sep># release infra for helloworld
This repository has 2 files:
- louhi-config/helloworld/gcb/release.yaml (GCB configuration)
- louhi-config/helloworld/flow.yaml (Louhi Flow configuration)
# Advanced
## Manual test of GCB file
You must have `gcloud` installed and also have a GCP project where you have
permissions to create a new build.
You can manually run a GCB build based on the file `./louhi-config/helloworld/gcb/release.yaml` by running:
```
gcloud container builds submit --no-source --config ./louhi-config/helloworld/gcb/release.yaml --substitutions=_BRANCH=master
```
This will build helloworld from the tip of `master` branch.
|
686134d36840ca45774abc7797d91f1864e73804
|
[
"Markdown",
"Shell"
] | 2
|
Shell
|
alex1545/helloworld-release-infra
|
d51d2e3b5ef37c186134fffbcd1146877f8e5801
|
df6f615dde8759ca5a2471c3e09a1dea6c1f63b5
|
refs/heads/master
|
<repo_name>WilliamY97/Finalytics<file_sep>/main.py
import os
import logging
from flask.ext.mysql import MySQL
from flask import Flask, render_template, json, jsonify, request
from flask import session, redirect
from werkzeug import generate_password_hash, check_password_hash
import pickle
import requests
app = Flask(__name__)
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
app.secret_key = 'why would I tell you my secret key?'
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = '<PASSWORD>'
app.config['MYSQL_DATABASE_DB'] = 'shit'
app.config['MYSQL_DATABASE_HOST'] = '127.0.0.1'
mysql.init_app(app)
conn = mysql.connect()
cursor = conn.cursor()
def get_user_id():
email = pickle.loads(session['u2']).email
query = "SELECT id FROM User where email = '%s'" % email
cursor.execute(query)
return cursor.fetchone()[0]
def format_currency(value):
return "${:,.2f}".format(value)
class User(object):
email = ""
first_name = ""
last_name = ""
def __init__(self,email,first_name,last_name):
self.email = email
self.first_name = first_name
self.last_name = last_name
def get_email(self):
"""Return the email address"""
return self.email
def get_first_name(self):
"""Return the first name"""
return self.first_name
def get_last_name(self):
"""Return the last name"""
return self.last_name
class Ticker(object):
def __init__(self,name,quantityShares):
self.name = name
self.quantityShares = quantityShares
portfolio = {}
def addUser(firstname,lastname,email,password):
_hashed_password = generate_password_hash(password)
cursor.callproc('sp_createUser',(firstname,lastname,email,_hashed_password))
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return jsonify({'message':'User created successfully !'})
else:
return jsonify({'error':str(data[0])})
def signInUser(logInEmail,logInPassword):
s = cursor.User.query.filter_by(logInEmail = email).first()
if check_password_hash(s.password,logInPassword):
return jsonify({'html':'<span>Log In Successful!</span>'})
else:
return jsonify({'html':'<span>Log In Failed...</span>'})
@app.route('/submitShares', methods=['POST'])
def submitShares():
ticker = request.form['ticker']
quantity = request.form['quantity']
email = pickle.loads(session['u2']).email
query = "SELECT id FROM User where email = '%s'" % email
cursor.execute(query)
user = cursor.fetchone()[0]
cursor.execute("SELECT portfolio_id FROM Portfolio WHERE user_id = %i" % user)
userPortfolio = cursor.fetchone()[0]
portfolio[ticker] = Ticker(ticker,quantity)
cursor.execute("select tickers from Portfolio where user_id = %i" % get_user_id())
port=pickle.loads(cursor.fetchone()[0])
portfolio.update(port)
query = 'UPDATE Portfolio SET tickers="%s" WHERE portfolio_id = %i' % (pickle.dumps(portfolio), userPortfolio)
cursor.execute(query)
conn.commit()
return redirect('/dashboard')
@app.route('/')
def home():
if session.get('user'):
return redirect('/userHome')
else:
return render_template('%s.html' % 'index')
@app.route('/dashboard')
def dashboard():
if session.get('user'):
cursor.execute("select tickers from Portfolio where user_id = %i" % get_user_id())
port=pickle.loads(cursor.fetchone()[0]).values()
total_price = sum([int(stock.quantityShares) * float(requests.get('http://finance.yahoo.com/d/quotes.csv', params={'s':stock.name, 'f':'a'}).content[:-1]) for stock in port])
percents = {stock.name: float(int(stock.quantityShares) * float(requests.get('http://finance.yahoo.com/d/quotes.csv', params={'s':stock.name, 'f':'a'}).content[:-1])) / total_price for stock in port}
positions = '|'.join(['%s~%f' % (k,v) for k,v in percents.iteritems()])
positionsArray = []
for k, v in percents.iteritems():
positionsArray.append([str(k), str(v)])
data = requests.get("https://test3.blackrock.com/tools/hackathon/portfolio-analysis", params={'positions': positions, 'calculateRisk': True, 'calculateExposures':True, 'startDate':'20160715'})
total_risk = data.json()['resultMap'][u'PORTFOLIOS'][0][u'portfolios'][0]['riskData']['totalRisk']
return render_template('dashboard/production/index2.html', portfolios=port, total_risk=round(total_risk, 2), total_price=format_currency(total_price),
total_return=format_currency(total_price*1.11), positions= positions, percents=positionsArray, username=pickle.loads(session['u2']).first_name)
else:
return redirect('/login')
@app.route('/stocklookup', methods=('GET',))
def stockLookUp():
if session.get('user'):
return render_template('%s.html' % 'dashboard/production/stockLookup')
else:
return render_template('error.html',error = 'Unauthorized Access')
@app.route('/about')
def about():
return render_template('%s.html' % 'about')
@app.route('/viewSignUp')
def viewSignUp():
return render_template('%s.html' % 'signup')
@app.route('/signUp', methods=['GET','POST'])
def signUp():
_firstname = request.form['firstname']
_lastname = request.form['lastname']
_email = request.form['email']
_password = request.form['<PASSWORD>']
_confirmpassword = request.form['password_confirm']
if _password != _confirmpassword:
return jsonify({'html':'<span>Password Confirmation Does Not Match!!</span>'})
elif _firstname and _lastname and _email and _password:
addUser(_firstname,_lastname, _email, _password)
return jsonify({'html':'<span>All fields good !!</span>'})
else:
return jsonify({'html':'<span>Enter the required fields</span>'})
@app.route('/login')
def login():
return render_template('%s.html' % 'login')
@app.route('/userHome')
def userHome():
userinfo = pickle.loads(session['u2'])
if session.get('user'):
logging.info(userinfo.get_first_name())
return render_template('userHome.html', data= userinfo.get_first_name())
else:
return render_template('error.html',error = 'Unauthorized Access')
@app.route('/validateLogin',methods=['POST'])
def validateLogin():
try:
_username = request.form['inputEmail']
_password = request.form['inputPassword']
# connect to mysql
cursor.callproc('sp_validateLogin',(_username,))
data = cursor.fetchall()
if len(data) > 0:
if check_password_hash(str(data[0][4]),_password):
userinfo = User(data[0][3], data[0][1], data[0][2])
session['u2'] = pickle.dumps(userinfo)
logging.info(userinfo.get_first_name())
session['user'] = data[0][0]
return redirect('/userHome')
else:
return render_template('error.html',error = 'Wrong Email address or Password.')
else:
return render_template('error.html',error = 'Wrong Email address or Password.')
except Exception as e:
return render_template('error.html',error = str(e))
@app.route('/delete/<name>')
def delete(name):
name = name.upper()
email = pickle.loads(session['u2']).email
query = "SELECT id FROM User where email = '%s'" % email
cursor.execute(query)
user = cursor.fetchone()[0]
cursor.execute("SELECT portfolio_id FROM Portfolio WHERE user_id = %i" % user)
userPortfolio = cursor.fetchone()[0]
cursor.execute("select tickers from Portfolio where user_id = %i" % get_user_id())
port=pickle.loads(cursor.fetchone()[0])
portfolio.update(port)
del portfolio[name]
query = 'UPDATE Portfolio SET tickers="%s" WHERE portfolio_id = %i' % (pickle.dumps(portfolio), userPortfolio)
cursor.execute(query)
conn.commit()
return redirect('/dashboard')
@app.route('/logout')
def logout():
session.pop('user',None)
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/README.md
# Finalytics
- Top Finance Hack 2016 at PennApps Spring 2016
- Top Data Visualization from Qualtrics Inc.
- Honourable mention Best Use of History Hack
- Honourable mention Best User Interface Hack

## About
Built to allow users to analyze equities on a dashboard and optimize their portfolios
with quantitative data pertaining to stock pulled from BlackRock, NY Times, & Yahoo
Finance APIs.
## Note
Since the development of this project at PennApps 2016, the Alladin API used to provide much of the data for the dashboard has been turned off. Unfortunately the application is unable to run without it, but more information (and visuals) of the project can be seen at https://devpost.com/software/finalytics
<file_sep>/static/js/ftimes.js
window.onload = function() {
var getNews = function (company) {
var $nytHeaderElem = $('#nytimes-header');
var $nytElem = $('#nytimes-articles');
$nytElem.text("");
var nytimesUrl = 'http://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + 'AAPL' + '&sort=newest&api-key=c2e884fe2a014ed4a5d4eea086b34180';
$.getJSON(nytimesUrl, function(data){
console.log("AJAX return for NY Times News", data)
$nytHeaderElem.text('New York Times Articles About ' + 'AAPL');
articles = data.response.docs;
for(var i = 0; i < articles.length; i++)
{
var article = articles[i];
$nytElem.append('<li class="article">' + '<a href="' + article.web_url +'">' + article.headline.main + '</a><a>' + ' -- ' + article.pub_date + '</a>' + '<p>' + article.snippet + '</p>' + '</li>');
};
}).error(function(e){
$nytElem.text('New York Times Articles Could Not Be Loaded');
});
}
};
<file_sep>/static/css/build/js/stock.js
var getStocks = function () {
var wsql = "select * from yahoo.finance.quotes where symbol in ('" + document.getElementById("stockSymbol").value.toUpperCase() + "')",
stockYQL = 'https://query.yahooapis.com/v1/public/yql?q='+encodeURIComponent(wsql)+'&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json&callback=?';
return $.ajax({
url: stockYQL,
dataType: 'jsonp'
});
};
var getStocksbySymbol = function (symbol) {
var wsql = "select * from yahoo.finance.quotes where symbol in ('" + symbol + "')",
stockYQL = 'https://query.yahooapis.com/v1/public/yql?q='+encodeURIComponent(wsql)+'&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json&callback=?';
return $.ajax({
url: stockYQL,
dataType: 'jsonp'
});
};
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
var getHistoricalData = function (timeframe){
var endDate = formatDate(new Date());
var startDate = new Date(endDate);
if(timeframe === 'week')
startDate.setDate(startDate.getDate() - 7);
else if (timeframe === 'month')
startDate.setMonth(startDate.getMonth() - 1);
else if (timeframe === 'year')
startDate.setMonth(startDate.getMonth() - 12);
// alert(formatDate(new Date(startDate)) + " AND " + endDate);
var symbol = document.getElementById("stockSymbol").value;
var wsql = "select * from yahoo.finance.historicaldata where symbol = \"" + symbol+ "\" and startDate = \"" + formatDate(new Date(startDate)) + "\" and endDate = \"" + endDate +"\"";
var stockYQL = "https://query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(wsql) + "&format=json%20&diagnostics=true%20&env=store://datatables.org/alltableswithkeys%20&callback=";
$.getJSON(stockYQL, function(data){
try {
console.log("historicalData", data);
var dates = [];
var close = [];
$.each(data.query.results, function(key,value) {
$.each(value, function (index, Obj) {
dates.unshift(Obj.Date);
close.unshift(parseFloat(Obj.Close).toFixed(2));
});
});
console.log("dates", dates);
console.log("close", close);
Chart.defaults.global.legend = {
enabled: false
};
$('#priceChart').remove(); // this is my <canvas> element
$('#chart_container').append('<canvas id="priceChart"><canvas>');
var ctx = document.getElementById("priceChart");
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels: dates,
datasets: [{
label: "Close Price",
backgroundColor: "rgba(38, 185, 154, 0.31)",
borderColor: "rgba(38, 185, 154, 0.7)",
pointBorderColor: "rgba(38, 185, 154, 0.7)",
pointBackgroundColor: "rgba(38, 185, 154, 0.7)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointBorderWidth: 1,
data: close,
lineTension: 0
}]
}
});
}
catch(err) {
console.log(err);
}
});
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
var getStats = function () {
var stockYQL = 'https://query1.finance.yahoo.com/v10/finance/quoteSummary/' + document.getElementById("stockSymbol").value + '?formatted=true&crumb=3EkOrBcb9HX&lang=en-US®ion=US&modules=defaultKeyStatistics%2CfinancialData%2CcalendarEvents&corsDomain=finance.yahoo.com';
return $.ajax({
url: stockYQL,
dataType: 'jsonp'
});
};
var getNews = function (company) {
var $nytHeaderElem = $('#nytimes-header');
var $nytElem = $('#nytimes-articles');
$nytElem.text("");
var nytimesUrl = 'http://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + company + '&sort=newest&api-key=c2e884fe2a014ed4a5d4eea086b34180';
$.getJSON(nytimesUrl, function(data){
console.log("AJAX return for NY Times News", data)
$nytHeaderElem.text('New York Times Articles About ' + company);
articles = data.response.docs;
for(var i = 0; i < articles.length; i++)
{
var article = articles[i];
$nytElem.append('<li class="article">' + '<a href="' + article.web_url +'">' + article.headline.main + '</a><a>' + ' -- ' + article.pub_date + '</a>' + '<p>' + article.snippet + '</p>' + '</li>');
};
}).error(function(e){
$nytElem.text('New York Times Articles Could Not Be Loaded');
});
}
function getQuote() {
getStocks().done(function(data){
console.log("AJAX for quotes Returned.",data);
var content = data.query.results.quote;
if (content.Name != null)
{
$('#summary').find('#name').text(content.Name);
$('#summary').find('#symbol').text(content.Symbol);
$('#summary').find('#stockExchange').text(content.StockExchange);
$('#summary').find('#lastTradePriceOnly').text(content.LastTradePriceOnly);
$('#summary').find('#change').text(content.Change);
$('#summary').find('#changeInPercent').text("(" + content.ChangeinPercent + ")");
$('#summary').find('#previousClose').text(content.PreviousClose);
$('#summary').find('#open').text(content.Open);
$('#summary').find('#bid').text(content.Bid);
$('#summary').find('#ask').text(content.Ask);
$('#summary').find('#daysLow').text(content.DaysLow);
$('#summary').find('#daysHigh').text(content.DaysHigh);
$('#summary').find('#yearLow').text(content.YearLow);
$('#summary').find('#yearHigh').text(content.YearHigh);
$('#summary').find('#volume').text(content.Volume);
if(content.Change >= 0)
{
$('#summary').find('#change').css({"color": "green"});
$('#summary').find('#changeInPercent').css({"color": "green"});
}
else
{
$('#summary').find('#change').css({"color": "red"});
$('#summary').find('#changeInPercent').css({"color": "red"});
}
var elem = document.getElementById('master_panel');
elem.style.visibility = 'visible';
getHistoricalData('month');
getNews(content.Name);
}
else
{
alert('Invalid Stock Symbol.');
}
});
/*getStats().done(function(data){
console.log("AJAX for stats Returned.", data);
var content = data.quoteSummary.result[0];
var color;
if(content.financialData.recommendationKey === "buy")
color = "green";
else
color = "red";
if (data.quoteSummary.error == null)
{
$('#summary_content').append("<div class=\"row\">"
+ "<div class=\"col-md-3 col-xs-12 widget widget_tally_box\">"
+ "<div class=\"x_panel\">"
+ "<div class=\"x_title\">"
+ "<h3 class=\"title-inline\">" + "Key Stats" + "</h3>"
+ "</div>"
+ "<div>"
+ "<h2 class=\"title-inline\">" + "Recommend: </h2><span class=\"" + color + " rec-inline\">" + content.financialData.recommendationKey + "</span>"
+ "</div>"
+ "<div class=\"x_content\">"
+ "<div>"
+ "<ul class=\"list-inline widget_tally\">"
+ "<li>"
+ "<p>"
+ "<span class=\"stock_attr\">Beta</span>"
+ "<span class=\"stock_val\">" + content.defaultKeyStatistics.beta.fmt + "</span>"
+ "<span class=\"stock_attr\">Share Outstanding</span>"
+ "<span class=\"stock_val\">" + content.defaultKeyStatistics.sharesOutstanding.fmt + "</span>"
+ "<span class=\"stock_attr\">Book Value</span>"
+ "<span class=\"stock_val\">$" + content.defaultKeyStatistics.bookValue.fmt + "</span>"
+ "<span class=\"stock_attr\">Enterprise Value</span>"
+ "<span class=\"stock_val\">$" + content.defaultKeyStatistics.enterpriseValue.fmt + "</span>"
+ "<span class=\"stock_attr\">EBITDA</span>"
+ "<span class=\"stock_val\">$" + content.financialData.ebitda.fmt + "</span>"
+ "<span class=\"stock_attr\">EV To EBITDA</span>"
+ "<span class=\"stock_val\">" + content.defaultKeyStatistics.enterpriseToEbitda.fmt + "</span>"
+ "<span class=\"stock_attr\">Current Ratio</span>"
+ "<span class=\"stock_val\">" + content.financialData.currentRatio.fmt + "</span>"
+ "<span class=\"stock_attr\">Quick Ratio</span>"
+ "<span class=\"stock_val\">" + content.financialData.quickRatio.fmt + "</span>"
+ "<span class=\"stock_attr\">Debt To Equity</span>"
+ "<span class=\"stock_val\">" + content.financialData.debtToEquity.fmt + "</span>"
+ "<span class=\"stock_attr\">EBITDA</span>"
+ "<span class=\"stock_val\">$" + content.financialData.ebitda.fmt + "</span>"
+ "<span class=\"stock_attr\">Free Cashflow</span>"
+ "<span class=\"stock_val\">$" + content.financialData.freeCashflow.fmt + "</span>"
+ "<span class=\"stock_attr\">Gross Profits</span>"
+ "<span class=\"stock_val\">$" + content.financialData.grossProfits.fmt + "</span>"
+ "<span class=\"stock_attr\">Total Cash</span>"
+ "<span class=\"stock_val\">$" + content.financialData.totalCash.fmt + "</span>"
+ "<span class=\"stock_attr\">Total Debt</span>"
+ "<span class=\"stock_val\">$" + content.financialData.totalDebt.fmt + "</span>"
+ "<span class=\"stock_attr\">Total Revenue</span>"
+ "<span class=\"stock_val\">$" + content.financialData.totalRevenue.fmt + "</span>"
+ "</p>"
+ "</li>"
+ "</ul>"
+ "</div>"
+ "</div>"
+ "</div>"
+ "</div>"
+ "</div>"
);
}
else
{
alert('Fail to get stats.');
}
});
*/
}
window.onload = function() {
var symbolArr = ['^GSPC', '^RUT', '^IXIC', 'CLQ16.NYM', 'GCQ16.CMX', '^TNX'];
getStocksbySymbol(symbolArr.join()).done(function(data){
console.log("AJAX for quotes Returned.",data);
var content = data.query.results.quote;
$('.tile_stats_count').find('.count_top').each(function(data){
var arrow;
if(content[data].Change >= 0)
{
$(this).parent().find('.count_bottom').css({"color": "green"});
arrow = "<i class=\"fa fa-sort-asc\"></i>";
}
else
{
$(this).parent().find('.count_bottom').css({"color": "red"});
arrow = "<i class=\"fa fa-sort-desc\"></i>";
}
var price = parseFloat(content[data].LastTradePriceOnly).toFixed(2);
var change = parseFloat(content[data].Change).toFixed(2);
var change_percent = parseFloat(content[data].ChangeinPercent).toFixed(2);
$(this).parent().find('.count').text(price);
$(this).parent().find('.count_bottom').text(change + " (" + change_percent + ") ");
$(this).parent().find('.count_bottom').append(arrow);
});
});
};
|
7e4a80ad182eb9805cec0d5fda3ea71317ce3578
|
[
"Markdown",
"Python",
"JavaScript"
] | 4
|
Python
|
WilliamY97/Finalytics
|
1c307d9ee3787e6a229178af1d44cc69975ff881
|
a56d045d2f1d7e053f4bc1a6313c408fe10fa3e0
|
refs/heads/main
|
<repo_name>Wojciech005/React-training---17<file_sep>/src/components/ButtonFetchUsers.js
import React from 'react';
import './ButtonComp.css'
const ButtonFetchUsers = (props) => {
return (
<button onClick = {props.click}>Add user</button>
);
}
export default ButtonFetchUsers ;<file_sep>/README.md
Method Fetch training - using API // app add users
<file_sep>/src/components/UsersList.js
import React from 'react';
import './UserList.css'
const UsersList = (props) => {
console.log(props.users)
const users = props.users.map(user => (
<div key={user.login.uuid}>
<img src={user.picture.large} alt={user.name.last}/>
<h1>{`${user.name.title} ${user.name.last}`}</h1>
<h2>{`city: ${user.location.city}`}</h2>
<p>{user.email}</p>
</div>
))
return (
<div className="users">
{users}
</div>
);
}
export default UsersList;
|
2c4b9bf0b57bac0c99bba600ffa215fcabd4096d
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
Wojciech005/React-training---17
|
58180899e78ea403540337f8b3d7af3fd952322f
|
36d5bb2a1f8e85e664e0a5f67c4ada0addbbf4dc
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
import re
import urllib.request
import requests
from bs4 import BeautifulSoup
import json
from flask import Flask, request, make_response
from slack import WebClient
from slackeventsapi import SlackEventAdapter
global user_name
user_name = ""
global user_location
user_location = ""
global zu_or_bit
SLACK_TOKEN = "<KEY>"
SLACK_SIGNING_SECRET = "382e0de70f9115f07e9bd247dbfd5128"
app = Flask(__name__)
# /listening 으로 슬랙 이벤트를 받습니다.
slack_events_adaptor = SlackEventAdapter(SLACK_SIGNING_SECRET, "/listening", app)
slack_web_client = WebClient(token=SLACK_TOKEN)
def set_info(name, location):
global user_name
global user_location
user_name = name
user_location = location
def get_chart(text):
print("@@@@@@@@@@@@@@@@@@@@@@get_chart@@@@@@@@@@@@@@@@@@@@@@@@")
ret_target = text
target=text.replace(" ", "").upper()
keywords = []
for page in range(1, 7):
req = requests.get('https://finance.naver.com/sise/sise_market_sum.nhn?&page='+str(page))
html = req.text
soup = BeautifulSoup(html, 'html.parser')
# 주식이름이 들어갈 예정 (ex 유한양행, 삼성전자, 삼성물산 ) 만약 삼성 전자 => 삼성전자, LG 전자 -> LG전자
#크롤링
# print(soup.find("table", class_="type_5"))
for tr in soup.find("table", class_="type_2").find_all("tr"):
if len(tr.select("td:nth-child(2)")) == 1:
# print(tr.select("td:nth-child(2)")[0].get_text().strip().replace(" ","").upper() )
if tr.select("td:nth-child(2)")[0].get_text().strip().replace(" ","").upper() == target:#주식 이름 tr.select("td:nth-child(2)")[0].get_text()
for idx in range(2, 13):
keywords.append(tr.select("td:nth-child(" + str(idx)+")")[0].get_text().strip())
# keywords[0] 종목
# keywords[1] 현재가
# keywords[3] 등락비율
sign = keywords[3][0]
print(keywords[3])
ret1 = user_name + \
" 고객님! CJ 대한통운입니다.\n\n" + \
keywords[0] + " " + keywords[1].replace(",","-") + \
"를 오늘 배달할 예정입니다.\n 송장번호: 35215334262345234" + \
"\n배달 장소: " + user_location + \
" 825-3\n\n" + \
user_location + " 대한통운 이령홍\n\n tel) 010-5367-1564\n\n" + \
"고객님 부재시 " + \
text + \
sign + " " + keywords[3].replace('.', '-')[1:-1] + "는 " + \
"근처 편의점에 맡기겠습니다.\n\n" + "자세한 서비스는 상세보기를 이용하여 주시기 바랍니다.\n\n아울러 상세보기를 클릭하시면\n우편물 배달 사전안내를 위한 개인정보 수집 동의가 가능합니다.\n" + \
"항상 CJ 대한통운을 이용해주셔서 감사합니다.\n\n통신망 상태에 따라 데이터 요금이 발생할 수 있습니다.\n"
ret2 = ret_target + "\n현재 시세: " + keywords[1] + "\n등락 비율: " + keywords[3]
return ret1, ret2
def get_price(text):
global user_name
global user_location
print("@@@@@@@@@@@@@@@@@@@@@@get_price@@@@@@@@@@@@@@@@@@@@@@@@")
req = requests.get('https://www.bithumb.com/')
html = req.text
soup = BeautifulSoup(html, 'html.parser')
ret_target = text
target = "assetReal" + text # target을 받는다. ex) btc, eth
price = soup.find("table", id="tableAsset").find("tbody", class_="coin_list").find("strong", id=target) # 현재 시세를 크롤링으로 가져온다.
price = price.getText()[:-1] # '원'은 빼고 숫자만 저장
target = "assetRealPrice" + text.upper()
# print(text)
result = soup.find("table", id="tableAsset").find("tbody", class_="coin_list").find("strong", id=target)
sign = result.getText().split()[0][0]
result = result.getText().split()[0][1:-1] # 변동 가격을 출력
# print(result)
# text 종목
# price 현재 가격
# result 변동률
ret1 = user_name + \
" 고객님! 우체국 택배입니다.\n\n" + \
text +" " + price.replace(',','-') + \
"를 오늘 배달할 예정입니다.\n 송장번호: 64813248763157486"+ \
"\n배달 장소: "+user_location+\
" 835-15\n\n" +\
user_location + " 우체국 이령홍\n\n tel) 010-5367-1564\n\n"+\
"고객님 부재시 " + \
text + \
sign + " " + result.replace(',', '-').replace('.', '-') + "는 " + \
"근처 편의점에 맡기겠습니다.\n\n" + "자세한 서비스는 상세보기를 이용하여 주시기 바랍니다.\n\n아울러 상세보기를 클릭하시면\n우편물 배달 사전안내를 위한 개인정보 수집 동의가 가능합니다.\n" + \
"항상 우체국 택배를 이용해주셔서 감사합니다.\n\n통신망 상태에 따라 데이터 요금이 발생할 수 있습니다.\n"
ret2 = ret_target + "\n현재 시세: " + price + "\n변동 가격: " + sign +result
return (ret1, ret2)
# 챗봇이 멘션을 받았을 경우
@slack_events_adaptor.on("app_mention")
def app_mentioned(event_data):
global user_name
global user_location
req = request.get_json()
print("metion" + str(req))
channel = event_data["event"]["channel"]
text = event_data["event"]["text"]
if len(text.split()) > 1:
user_name = text.split()[1]
user_location = text.split()[2]
attachments=[
{
"text": "서비스를 선택하세요.",
"fallback": "You are unable to choose a game",
"color": "#3AA3E3",
"attachment_type": "default",
"callback_id": "chase",
"actions": [
{
"name": "check bit con",
"text": "사용법",
"type": "button",
"style": "primary",
"value": "0"
},
{
"name": "check bit con",
"text": "우체국",
"type": "button",
"value": "8"
},
{
"name": "check bit con",
"text": "CJ 대한통운",
"type": "button",
"value": "9"
},
# {
# "name": "game",
# "text": "배송지 설정",
# "type": "button",
# "value": "3",
#
# }
]
}
]
slack_web_client.chat_postMessage(
channel=channel,
text="택배입니다.",
attachments=attachments
)
@app.route("/slack/message",methods=['POST'])
def incoming_slack_message():
global user_name
global user_location
global zu_or_bit
target_list = ['BTC', 'ETH', 'XRP', 'BCH', 'LTC', 'EOS', 'BSV', 'TRX', 'ADA', 'XLM', 'XMR', 'DASH', 'LINK', 'ETC',
'XEM', 'ZEC', 'BTG', 'QTUM', 'VET', 'BAT', 'OMG', 'BTT', 'BCD', 'HC', 'NPXS', 'WAVES', 'REP', 'ZRX',
'ICX', 'IOST', 'ZIL', 'XVG', 'AE', 'GXC', 'THETA', 'WTC', 'STEEM', 'ELF', 'MCO', 'BZNT', 'ENJ',
'SNT', 'MIX', 'GNT', 'STRAT', 'VALOR', 'WAX', 'HDAC', 'ORBS', 'CON', 'CMT', 'LRC', 'LOOM', 'PPT',
'TRUE', 'KNC', 'POWR', 'ETZ', 'PIVX', 'ABT', 'POLY', 'CTXC', 'ITC', 'BHP', 'MTL', 'ANKR', 'ROM',
'MITH', 'PAY', 'LBA', 'DAC', 'HYC', 'APIS', 'GTO', 'OCN', 'RDN', 'ETHOS', 'AUTO', 'RNT', 'INS',
'AMO', 'TMTG', 'SALT', 'ARN', 'PST', 'DACC', 'WET', 'PLY']
form_json = json.loads(request.form["payload"])
print(form_json)
if form_json["type"]== "dialog_submission": # 배송조회 혹은 배송지 설정으로 값을 입력받고 난 후
print(form_json['submission']['loc_origin'])
target = form_json['submission']['loc_origin'].upper() # 조회하려는 코인 종목
if zu_or_bit == 8:
if target not in target_list:
slack_web_client.chat_postMessage(
channel=form_json['channel']['id'],
text="해당 제품은 반송처리 되었습니다.",
)
else:
ret1, ret2 = get_price(target) # 가격을 출력한다.
slack_web_client.chat_postMessage(
channel=form_json['channel']['id'],
text=ret1,
attachments=[
{
"fallback": "You are unable to choose a game",
"attachment_type": "default",
"callback_id": "chase",
"actions": [
{
"name": "detail",
"text": "상세보기",
"type": "button",
"value": target,
}
]
}
]
)
else:
ret1, ret2 = get_chart(target) # 가격을 출력한다.
slack_web_client.chat_postMessage(
channel=form_json['channel']['id'],
text=ret1,
attachments=[
{
"fallback": "You are unable to choose a game",
"attachment_type": "default",
"callback_id": "chase",
"actions": [
{
"name": "detail",
"text": "상세보기",
"type": "button",
"value": target,
}
]
}
]
)
return make_response("", 200)
elif form_json["type"] == "interactive_message": # 처음 화면에서 버튼을 눌렀을 때 들어오는 조건문
if form_json["actions"][0]["value"] == str(0): # 설명서 버튼을 눌렀을 때
attachments = [
{
"title": "설명서",
"color": "#bd0811",
"text": "*0. 이름, 주소 등록*\n" +
"\t@봇 이름 주소\n" +
"\t이름과 주소를 입력 받는다.\n\n" +
"\t이후 @봇 으로 이용 가능\n"+
"\t*우체국 선택시* => 비트 코인 시세 확인\n" +
"\t*CJ 대한통운 선택시* => 주식 시세 확인\n\n\n" +
"*비트 코인 설명*\n" +
"\t*1. 실시간 코인 시세 확인* \n" +
"\t\t배송조회 버튼 클릭\n" +
"\t\t이름, 주소 설정하지 않을 시 0번 실행 필요\n"
"\t\t버튼 클릭시 종목 입력을 받습니다. ex) BTC, ETH(대소문자 상관 없음)\n" +
"\t\t*암호화폐* 실시간 시세 정보를 택배 정보 제공 서비스처럼 속여서 출력\n\n" +
"\t\tex)OOO고객님 비트 택배입니다.\n" +
"\t\t'ETH 364-500'를 오늘 배달할 예정입니다. \n" +
"\t\t=> ETH: 코인 종목\n\t\t364-500: 실시간 시세(364,500원)('-'은 ','로 생각)\n\n" +
"\t\t송장번호: 15489613216 \n\n" +
"\t\t배달 장소: OOO시 OOO동\n" +
"\t\t고객님 부재시 'ETH (+ or -) 5-200'는 근처 편의점에 맡기겠습니다. \n" +
"\t\t=> + or -: 가격 변동, 5-200: 5,200원\n\n" +
"\t\t상세보기 버튼을 클릭하면 원래 시세 정보를 제공\n\n\n"
"\t*2. 매수 링크*\n" +
"\t\t반송 링크 버튼 클릭\n" +
"\t\t바로 코인을 매수할 수 있는 링크가 열리게 됩니다.\n\n\n" +
"*주식 설명*\n" +
"\t*실시간 주식 정보 출력*\n" +
"\t\t실제 택배 배송정보처럼 보이기 위해 사용될 정보를 입력받는다.\n\n" +
"\t\t실시간 *주식* 정보를 택배 정보 제공 서비스처럼 속여서 출력\n\n" +
"\t\tex)OOO고객님 CJ 대한통운입니다.\n" +
"\t\t'금호타이어 126-500'를 오늘 배달할 예정입니다. \n" +
"\t\t=> 금호타이어: 코인 종목\n\t: 실시간 시세(126,500원)('-'은 ','로 생각)\n\n" +
"\t\t고객님 부재시 'ETH (+ or -) 2-24'는 근처 편의점에 맡기겠습니다. \n" +
"\t\t=> + or -: 등락율(가격 변동 비율) , 2-24: 2.24%\n\n" +
"\t\t상세보기 버튼을 클릭하면 원래 시세 정보를 제공\n\n\n" +
"*그 외*\n"+
"\t해당 제품은 반송처리 되었습니다.\n" +
"\t=> 해당 종목이 존재하지 않음.\n\n\n",
"mrkdwn_in": ["text"]
}
]
slack_web_client.chat_postMessage(
channel=form_json['channel']['id'],
attachments=attachments
)
elif form_json["actions"][0]["value"] == str(1): # 배송 조회 버튼을 눌렀을 때
if user_name is "": # 유저 네임이 아직 설정이 안되어 있으면 아래 메세지를 보여주고 챗봇 종료
slack_web_client.chat_postMessage(
channel=form_json['channel']['id'],
text = "배송지 설정을 먼저 해주세요"
)
return make_response("", 200)
else: # 유저네임이 설정되어 있으면 조회할 코인 종목을 입력받을 창을 띄운다.
dialogs = {
"callback_id": "dialog",
"title": "제품명 입력",
"submit_label": "제출",
"notify_on_cancel": True,
"state": "product",
"elements": [
{
"type": "text",
"label": "제품명",
"name": "loc_origin"
},
]
}
slack_web_client.dialog_open(trigger_id=form_json['trigger_id'], dialog=dialogs)
elif form_json["actions"][0]["value"] == str(4):
target = form_json["actions"][0]["name"]
if zu_or_bit == 8:
ret1, ret2 = get_price(target)
else :
ret1, ret2 = get_chart(target)
slack_web_client.chat_postMessage(
channel=form_json['channel']['id'],
text=ret1,
attachments=[
{
"fallback": "You are unable to choose a game",
"attachment_type": "default",
"callback_id": "chase",
"actions": [
{
"name": "back",
"text": "상세보기",
"type": "button",
"value": target,
}
]
}
]
)
elif form_json["actions"][0]["value"] == str(8): #우체국, 비트코인
zu_or_bit = 8
attachments = [
{
"text": "서비스를 선택하세요.",
"fallback": "비트코인",
"color": "#3AA3E3",
"attachment_type": "default",
"callback_id": "chase",
"actions": [
{
"name": "check bit con",
"text": "배송 조회",
"type": "button",
"value": "1"
},
{
"name": "매수페이지 링크",
"text": "반송 링크",
"type": "button",
'url': "https://www.bithumb.com/trade/order/BTC",
"value": "2"
}
]
}
]
slack_web_client.chat_postMessage(
channel=form_json['channel']['id'],
text="우체국 택배입니다.",
attachments=attachments
)
elif form_json["actions"][0]["value"] == str(9): # CJ, 주식
zu_or_bit = 9
attachments = [
{
"text": "서비스를 선택하세요.",
"fallback": "주식",
"color": "#3AA3E3",
"attachment_type": "default",
"callback_id": "chase",
"actions": [
{
"name": "check bit con",
"text": "배송 조회",
"type": "button",
"value": "1"
}
]
}
]
slack_web_client.chat_postMessage(
channel=form_json['channel']['id'],
text="CJ 대한통운입니다.",
attachments=attachments
)
else : # 상세 보기
target = form_json["actions"][0]["value"].upper()
if zu_or_bit == 8:
ret1, ret2 = get_price(target)
else :
ret1, ret2 = get_chart(target)
slack_web_client.chat_postMessage(
channel=form_json['channel']['id'],
text=ret2,
attachments=[
{
"fallback": "You are unable to choose a game",
"attachment_type": "default",
"callback_id": "chase",
"actions": [
{
"name": target,
"text": "돌아가기",
"type": "button",
"value": "4",
}
]
}
]
)
else:
print(form_json["actions"][0]['value'])
# # .. do something with the req ..
return make_response("",200)
@app.route("/", methods=["GET"])
def index():
return "<h1>Server is ready.</h1>"
if __name__ == '__main__':
app.run('0.0.0.0', port=8080)
|
100f0ca6e5290dd17b965086e2761332e40d97c1
|
[
"Python"
] | 1
|
Python
|
leesanha/slack_chatbot
|
fbf8740b586c93486f837d61d954014a5b89fe60
|
fea06644a154a72825d1dda7fee5d7a6cbda759f
|
refs/heads/master
|
<repo_name>gordomac/puzzle<file_sep>/rubix.js
"use strict";
var canvas;
var gl;
var won = 1;
var NumVertices = 36*27;
var points = [];
var colors = [];
var axis = 0;
var direction2 = [-1,-1,1,-1,1,1,-1,1,1];
var centerFaces = [
[-0.5,0,0],
[0.5,0,0],
[0, -0.5,0],
[0, 0.5, 0],
[0,0,-0.5],
[0,0,0.5]
];
var lastOrientation =[5,3];
var globTheta = mult(mat4(), rotate(0,[0,1,0]));
var globAngles = [0,0,0];
var lastMiddles = [1,1,1];
var thetaLoc;
var cubes;
var objAxis=[
[1,0,0],
[0,1,0],
[0,0,1]
];
var program;
var vBuffer;
var vPosition;
var inter;
var switchDirection = 1;
var rotCounter = 0;
var speed = 15;
var dontRotate = 0;
2, 11, 20,5,14,23,8,17,26
var faceMatrix = resetFceMatrix();
window.onload = function init()
{
canvas = document.getElementById( "gl-canvas" );
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't available" ); }
cubes = colorCubes();
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 1, 0.9, 0.8, 1.0 );
gl.enable(gl.DEPTH_TEST);
//
// Load shaders and initialize attribute buffers
//
program = initShaders( gl, "vertex-shader", "fragment-shader" );
gl.useProgram( program );
var cBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(colors), gl.STATIC_DRAW );
var vColor = gl.getAttribLocation( program, "vColor" );
gl.vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vColor );
vBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(points), gl.STATIC_DRAW );
vPosition = gl.getAttribLocation( program, "vPosition" );
gl.vertexAttribPointer( vPosition, 4, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vPosition );
//thetaLoc = gl.getUniformLocation(program, "theta");
//event listeners for buttons
document.getElementById( "direction" ).onclick = function () {
//direction = 0;
switchDirection = switchDirection * -1;
for(var count = 0; count < 9; count++){
direction2[count] = direction2[count]*-1;
}
};
document.addEventListener("keydown", function(event) {
var x = event.keyCode;
var cenFacesCoord = [];
if(rotCounter ==0 && dontRotate ==0){
if (x == 87) {
globTheta = mult(globTheta, rotate(15,[1,0,0]));
/*
globAngles[0] = globAngles[0] + 15;
if(globAngles[0] > 45){
globAngles[0] = globAngles[0]-90;
var tempAngle = globAngles[1];
globAngles[1] = globAngles[1]-globAngles[2];
globAngles[2] = tempAngle+globAngles[2];
switchFaces(0,-1);
console.log("w");
console.log(globTheta);
}*/
console.log(globTheta);
render();
requestAnimFrame(render);
}
if (x == 83) {
globTheta = mult(globTheta, rotate(-15,[1,0,0]));
globAngles[0] = globAngles[0] - 15;
if(globAngles[0] < -45){
globAngles[0] = globAngles[0]+90;
var tempAngle = globAngles[1];
globAngles[1] = globAngles[1]+globAngles[2];
globAngles[2] = -tempAngle+globAngles[2];
//switchFaces(0,1);
console.log("s");
}
render();
requestAnimFrame(render);
}
if (x == 81) {
globTheta = mult(globTheta, rotate(15,[0,0,1]));
globAngles[2] = globAngles[2] + 15;
if(globAngles[2] > 45){
globAngles[2] = globAngles[2]-90;
var tempAngle = globAngles[1];
globAngles[1] = globAngles[1]-globAngles[0];
globAngles[0] = tempAngle+globAngles[0];
//switchFaces(2,-1);
console.log("q");
}
render();
requestAnimFrame(render);
}
if (x == 69) {
globTheta = mult(globTheta, rotate(-15,[0,0,1]));
globAngles[2] = globAngles[2] - 15;
if(globAngles[2] < -45){
globAngles[2] = globAngles[2]+90;
var tempAngle = globAngles[1];
globAngles[1] = globAngles[1]+globAngles[0];
globAngles[0] = -tempAngle+globAngles[0];
//switchFaces(2,1);
console.log("e");
}
render();
requestAnimFrame(render);
}
if (x == 65) {
globTheta = mult(globTheta, rotate(15,[0,1,0]));
globAngles[1] = globAngles[1] + 15;
if(globAngles[1] > 45){
globAngles[1] = globAngles[1]-90;
var tempAngle = globAngles[2];
globAngles[2] = globAngles[2]+globAngles[0];
globAngles[0] = -tempAngle+globAngles[0];
//switchFaces(1,-1);
console.log("a");
}
render();
requestAnimFrame(render);
}
if (x == 68) {
globTheta = mult(globTheta, rotate(-15,[0,1,0]));
globAngles[1] = globAngles[1] - 15;
if(globAngles[1] < -45){
globAngles[1] = globAngles[1]+90;
var tempAngle = globAngles[2];
globAngles[2] = globAngles[2]-globAngles[0];
globAngles[0] = globAngles[0]+tempAngle;
//switchFaces(1,1);
console.log("d");
}
render();
requestAnimFrame(render);
}
for(var count = 0; count <6; count++){
var tempCoord =[0,0,0];
for(var i = 0; i < 3; i++){
for (var j =0; j<3; j++){
tempCoord[i] = tempCoord[i] + globTheta[j][i]*centerFaces[count][j];
}
}
cenFacesCoord.push(tempCoord);
}
var topFace = 0;
var topFaceCoord = 0;
var frontFace = 0;
var frontFaceCoord =0;
for(var count2 =0; count2<6; count2++ ){
if(cenFacesCoord[count2][1] > topFaceCoord){
topFaceCoord = cenFacesCoord[count2][1];
topFace = count2;
}
if(cenFacesCoord[count2][2] < frontFaceCoord){
frontFaceCoord = cenFacesCoord[count2][2];
//console.log(frontFaceCoord);
frontFace = count2;
}
}
console.log(cenFacesCoord);
console.log("FRONT"+frontFace + " : " + topFace);
//changeOrientation(frontFace,topFace);
render();
requestAnimFrame(render);
if(x==84){
rotateSide(0);
}
else if(x==89){
rotateSide(1);
}
else if(x==85){
rotateSide(2);
}
else if(x==71){
rotateSide(3);
}
else if(x==72){
rotateSide(4);
}
else if(x==74){
rotateSide(5);
}
else if(x==66){
rotateSide(6);
}
else if(x==78){
rotateSide(7);
}
else if(x==77){
rotateSide(8);
}
}
});
document.getElementById( "randomize" ).onchange = function (event) {
speed = 1;
var steps = parseInt(event.target.value);
if(rotCounter == 0 && dontRotate == 0){
dontRotate = 1;
randomize(steps);
}
};
document.getElementById( "save" ).onclick = function () {
if(won == 0){
document.getElementById("link").removeAttribute("hidden");
console.log("WE DID IT");
}
else{
console.log("NVM");
}
var saveString1 = "";
var saveString2 = "";
for(var count = 0; count < 27; count++){
saveString1 = saveString1 + "" + cubes[2*count+1] + "?";
}
for(var count2 = 0; count2 < 9; count2++){
saveString2 = saveString2 + "" + faceMatrix[count2] + "?";
}
console.log(saveString1 + saveString2);
};
document.getElementById("loadString").onkeydown = function(event){
var string = event.target.value;
var key = event.keyCode;
var partsOfStr = string.split('?');
if(key == 13){
for(var count = 0; count < 27; count++){
var eachVal = partsOfStr[count].split(',');
for(var count2 = 0; count2 < 4; count2++){
var temp = count2 * 4;
var hold = [temp, temp+1,temp+2,temp+3];
cubes[2*count+1][count2] = [parseFloat(eachVal[hold[0]]),parseFloat(eachVal[hold[1]]),parseFloat(eachVal[hold[2]]),parseFloat(eachVal[hold[3]])];
}
}
for(var count2 = 27; count2< 36; count2++){
var eachVal = partsOfStr[count2].split(',');
for(var count3 = 0; count3<9; count3++){
faceMatrix[count2-27][count3] = parseInt(eachVal[count3]);
}
}
render();
requestAnimFrame(render);
}
}
document.getElementById( "front" ).onclick = function () {
if(rotCounter == 0 && dontRotate == 0){
rotateSide(0);
}
}
document.getElementById( "sideMiddle" ).onclick = function () {
if(rotCounter == 0 && dontRotate == 0){
rotateSide(1);
}
}
document.getElementById( "back" ).onclick = function () {
if(rotCounter == 0 && dontRotate == 0){
rotateSide(2);
}
}
document.getElementById( "left" ).onclick = function () {
if(rotCounter == 0 && dontRotate == 0){
rotateSide(3);
}
}
document.getElementById( "middle" ).onclick = function () {
if(rotCounter == 0 && dontRotate == 0){
rotateSide(4);
}
}
document.getElementById( "right" ).onclick = function () {
if(rotCounter == 0 && dontRotate == 0){
rotateSide(5);
}
}
document.getElementById( "bottom" ).onclick = function () {
if(rotCounter == 0 && dontRotate == 0){
rotateSide(6);
}
}
document.getElementById( "frontMiddle" ).onclick = function () {
if(rotCounter == 0 && dontRotate == 0){
rotateSide(7);
}
}
document.getElementById( "top" ).onclick = function () {
if(rotCounter == 0 && dontRotate == 0){
rotateSide(8);
}
}
render();
}
function changeOrientation(fFace, tFace){
//faceMatrix = resetFceMatrix();
if(fFace != lastOrientation[0] || tFace != lastOrientation[1]){
faceMatrix = resetFceMatrix();
if(fFace == 0){
switchFaces(1,-1);
if(tFace == 2){
switchFaces(2,1);
switchFaces(2,1);
}
else if(tFace == 5){
switchFaces(2,-1);
}
else if(tFace == 4){
console.log("HELLO");
switchFaces(2,-1);
}
}
else if(fFace == 1){
switchFaces(1,1);
}
else if(fFace == 3){
switchFaces(0,-1);
}
else if(fFace == 2){
switchFaces(0,1);
}
else if(fFace == 5){
switchFaces(1,1);
switchFaces(1,1);
}
else if(fFace ==4){
if(tFace==1){
switchFaces(2,1);
}
}
}
lastOrientation = [fFace, tFace];
}
//front
//side middle
//back
//left
//middle
//right
//bottom
//front middle
//top
function switchFaces(axs,dir){
if(axs == 0){
var tempArr = [];
var reorderArr;
if(dir == 1){
reorderArr = [6,7,8,3,4,5,2,1,0];
}
else{
reorderArr = [8,7,6,3,4,5,0,1,2];
}
for(var faceCount = 0; faceCount<9; faceCount++){
tempArr.push(faceMatrix[faceCount]);
}
for(var count = 0; count<9; count++){
faceMatrix[count] = tempArr[reorderArr[count]];
}
if(dir == 1){
if(lastMiddles[0]==lastMiddles[2]){
direction2[1] = direction2[1]*-1;
lastMiddles[0] = lastMiddles[0]*-1;
}
else {
direction2[7] = direction2[7]*-1;
lastMiddles[2] = lastMiddles[2]*-1;
}
var tempAx = objAxis[2];
for(var ko = 0; ko < 3; ko++){
tempAx[ko] = tempAx[ko]*-1;
}
objAxis[2] = objAxis[1];
objAxis[1] = tempAx;
}
else{
if(lastMiddles[0]==lastMiddles[2]){
direction2[7] = direction2[7]*-1;
lastMiddles[2] = lastMiddles[2]*-1;
}
else {
direction2[1] = direction2[1]*-1;
lastMiddles[0] = lastMiddles[0]*-1;
}
var tempAx = objAxis[1];
for(var ko = 0; ko < 3; ko++){
tempAx[ko] = tempAx[ko]*-1;
}
objAxis[1] = objAxis[2];
objAxis[2] = tempAx;
}
}
else if(axs == 1){
var tempArr = [];
var reorderArr;
if(dir == -1){
reorderArr = [3,4,5,2,1,0,6,7,8];
}
else{
reorderArr = [5,4,3,0,1,2,6,7,8];
}
for(var faceCount = 0; faceCount<9; faceCount++){
tempArr.push(faceMatrix[faceCount]);
}
for(var count = 0; count<9; count++){
faceMatrix[count] = tempArr[reorderArr[count]];
}
if(dir == -1){
if(lastMiddles[0]==lastMiddles[1]){
direction2[1] = direction2[1]*-1;
lastMiddles[0] = lastMiddles[0]*-1;
}
else {
direction2[4] = direction2[4]*-1;
lastMiddles[1] = lastMiddles[1]*-1;
}
var tempAx = objAxis[2];
for(var ko = 0; ko < 3; ko++){
tempAx[ko] = tempAx[ko]*-1;
}
objAxis[2] = objAxis[0];
objAxis[0] = tempAx;
}
else{
if(lastMiddles[0]==lastMiddles[1]){
direction2[4] = direction2[4]*-1;
lastMiddles[1] = lastMiddles[1]*-1;
}
else {
direction2[1] = direction2[1]*-1;
lastMiddles[0] = lastMiddles[0]*-1;
}
var tempAx = objAxis[0];
for(var ko = 0; ko < 3; ko++){
tempAx[ko] = tempAx[ko]*-1;
}
objAxis[0] = objAxis[2];
objAxis[2] = tempAx;
}
}
else{
var tempArr = [];
var reorderArr;
if(dir ==-1){
reorderArr = [0,1,2,6,7,8,5,4,3];
}
else{
reorderArr = [0,1,2,8,7,6,3,4,5];
}
for(var faceCount = 0; faceCount<9; faceCount++){
tempArr.push(faceMatrix[faceCount]);
}
for(var count = 0; count<9; count++){
faceMatrix[count] = tempArr[reorderArr[count]];
}
if(dir == -1){
if(lastMiddles[2]==lastMiddles[1]){
direction2[7] = direction2[7]*-1;
lastMiddles[2] = lastMiddles[2]*-1;
}
else {
direction2[4] = direction2[4]*-1;
lastMiddles[1] = lastMiddles[1]*-1
}
var tempAx = objAxis[1];
for(var ko = 0; ko < 3; ko++){
//tempAx[ko] = tempAx[ko]*-1;
}
//objAxis[0] = objAxis[1];
//objAxis[1] = tempAx;
objAxis[1] = objAxis[2];
objAxis[2] = objAxis[0];
objAxis[0] = tempAx;
}
else{
if(lastMiddles[2]==lastMiddles[1]){
direction2[4] = direction2[4]*-1;
lastMiddles[1] = lastMiddles[1]*-1
}
else {
direction2[7] = direction2[7]*-1;
lastMiddles[2] = lastMiddles[2]*-1;
}
var tempAx = objAxis[1];
for(var ko = 0; ko < 3; ko++){
tempAx[ko] = tempAx[ko]*-1;
}
objAxis[1] = objAxis[0];
objAxis[0] = tempAx;
}
}
}
function switchMatrices(sideNom, dir){
var tempFace = [];
var tempC = [];
for(var count = 0; count < 9; count++){
tempC.push(faceMatrix[sideNom][count]);
tempFace.push(cubes[2*tempC[count]+1]);
}
var arrClock = [6,3,0,7,4,1,8,5,2];
var arrCounter = [2,5,8,1,4,7,0,3,6];
for(var sCount = 0; sCount<9; sCount++){
for(var fCount = 0; fCount<9; fCount++){
for(var count3 = 0; count3<9; count3++){
if(dir == 1){
if(faceMatrix[sCount][fCount] == tempC[count3]){
faceMatrix[sCount][fCount] = tempC[arrClock[count3]];
break;
}
}
else{
if(faceMatrix[sCount][fCount] == tempC[count3]){
faceMatrix[sCount][fCount] = tempC[arrCounter[count3]];
break;
}
}
}
/*
if(faceMatrix[sCount][fCount] == tempC[0]){
faceMatrix[sCount][fCount] = tempC[6];
}
else if(faceMatrix[sCount][fCount] == tempC[1]){
faceMatrix[sCount][fCount] = tempC[3];
}
else if(faceMatrix[sCount][fCount] == tempC[2]){
faceMatrix[sCount][fCount] = tempC[0];
}
else if(faceMatrix[sCount][fCount] == tempC[3]){
faceMatrix[sCount][fCount] = tempC[7];
}
else if(faceMatrix[sCount][fCount] == tempC[5]){
faceMatrix[sCount][fCount] = tempC[1];
}
else if(faceMatrix[sCount][fCount] == tempC[6]){
faceMatrix[sCount][fCount] = tempC[8];
}
else if(faceMatrix[sCount][fCount] == tempC[7]){
faceMatrix[sCount][fCount] = tempC[5];
}
else if(faceMatrix[sCount][fCount] == tempC[8]){
faceMatrix[sCount][fCount] = tempC[2];
}*/
}
}
var tempG = [];
for(var count = 0; count < 9; count++){
tempG.push(faceMatrix[sideNom][count]);
}
}
function resetFceMatrix(){
var mtrx = [
[ 0, 1, 2, 3, 4, 5, 6, 7, 8], //front
[ 9,10,11,12,13,14,15,16,17], //side middle
[24,25,26,21,22,23,18,19,20], //back
[ 18, 9, 0, 21,12,3,24,15, 6], //left
[ 1, 10,19, 4,13,22,7,16,25], //middle
[ 2, 11, 20,5,14,23,8,17,26], //right
[18,19,20, 9,10,11, 0, 1, 2], //bottom
[ 3, 4, 5,12,13,14,21,22,23], //front middle
[ 6, 7, 8,15,16,17,24,25,26] //top
];
return mtrx;
}
function checkFinish(){
//Every cubes rotation matrix needs to be the same permutation of the identity matrix with rows * -1 or switched with eachother
var finished = 0;
var h = [];
for(var q = 0; q < 27; q++){
for( var count2 = 0; count2 < 4; count2++){
var g = [];
for( var count3 = 0; count3 < 4; count3++){
var diff = Math.abs(cubes[2*q+1][count2][count3]-mat4()[count2][count3]);
var value = Math.round(cubes[2*q+1][count2][count3]);
if(q == 0){
g.push(Math.round(cubes[2*q+1][count2][count3]));
}
else if(value != h[count2][count3] && q!=13){
finished = 1;
break;
}
/*
if(diff > 0.001){
finished = 1;
}*/
}
if(q == 0){
h.push(g);
}
}
}
if(finished == 0){
alert("Congratulations! You've solved it! You did so amazingly fantastic, you should save the result");
won = 0;
//document.getElementsById("link").removeAttribute("hidden");
//document.getElementById( "save" ).onclick = function () {};
}
}
//front clockwise
//sidemiddle clockwise
//back counterclockwise
//left clockwise
//middle counterclockwise
//right counter clockwise
//top clockwise
//topmiddle counterclockwise
//bottom counter clockwise
function randomize(steps2){
var step2 = 0;
var interval = setInterval(function oneStep(){
var j = Math.floor(Math.random()*9);
/*
if( j != 1){
rotateSide(j);
}*/
rotateSide(Math.floor(Math.random()*9));
step2 = step2+1;
if(step2 >= steps2){
dontRotate = 0;
clearInterval(interval);
}
},300);
}
function rotateSide(sideNom){
var zeta = 0;
var ax;
if(sideNom<3){
ax = objAxis[2];
}
else if(sideNom<6){
ax = objAxis[0];
}
else{
ax = objAxis[1];
}
inter = setInterval(function rotating(){
var tempJ = [];
var direction = 1;
if(sideNom==0 || sideNom==1 || sideNom==3 || sideNom==6){
direction = -1;
}
direction = direction * switchDirection;
for(var p = 0; p < 9; p++){
var q = faceMatrix[sideNom][p];
tempJ.push(q);
cubes[2*q+1] = mult(cubes[2*q+1],rotate(3*switchDirection, ax));
}
rotCounter = rotCounter + 1;
zeta = zeta+1;
requestAnimFrame(render);
if(zeta >= 30){
rotCounter = 0;
switchMatrices(sideNom, direction2[sideNom]);
checkFinish();
clearInterval(inter);
}
},1);
//requestAnimFrame(render);}, 1);
}
function colorCubes()
{
var cubes = [];
for(var cub = 0; cub<27; ++cub){
var sides =[];
var vertexes = [];
vertexes = quad( 1, 0, 3, 2, cub, vertexes);
vertexes = quad( 2, 3, 7, 6, cub, vertexes );
vertexes = quad( 3, 0, 4, 7, cub, vertexes );
vertexes = quad( 6, 5, 1, 2, cub, vertexes);
vertexes = quad( 4, 5, 6, 7, cub, vertexes );
vertexes = quad( 5, 4, 0, 1, cub, vertexes );
cubes.push(vertexes);
cubes.push(mat4());
}
return cubes;
}
function quad(a, b, c, d, cub, vertexes)
{
var disX = 0;
var disY = 0;
var disZ = 0;
var sep = 0.34;
disX = (cub%3)*sep;
var temp = cub%9;
if(temp >= 6){
disY = 2*sep;
}
else if(temp >=3){
disY = sep;
}
if(cub >= 9){
disZ = sep;
}
if(cub >= 18){
disZ = 2*sep;
}
var vertices = [
vec4( -0.5+disX, -0.5+disY,-0.18+disZ, 1.0 ),
vec4( -0.5+disX,-0.18+disY,-0.18+disZ, 1.0 ),
vec4(-0.18+disX,-0.18+disY,-0.18+disZ, 1.0 ),
vec4(-0.18+disX, -0.5+disY,-0.18+disZ, 1.0 ),
vec4( -0.5+disX, -0.5+disY, -0.5+disZ, 1.0 ),
vec4( -0.5+disX,-0.18+disY, -0.5+disZ, 1.0 ),
vec4(-0.18+disX,-0.18+disY, -0.5+disZ, 1.0 ),
vec4(-0.18+disX, -0.5+disY, -0.5+disZ, 1.0 ),
vec4(0,0,0, 1.0)
];
var vertexColors = [
[ 0.0, 0.0, 0.0, 1.0 ], // black
[ 1.0, 0.0, 0.0, 1.0 ], // red
[ 1.0, 1.0, 0.0, 1.0 ], // yellow
[ 0.0, 0.0, 1.0, 1.0 ], // blue
[ 0.0, 1.0, 0.0, 1.0 ], // green
[ 1.0, 1.0, 1.0, 1.0 ], // white
[ 1.0, 0.65, 0.0, 1.0], //orange
//[ 0.0, 1.0, 1.0, 1.0 ], // cyan
[ 0.9, 0.9, 0.9, 1.0 ] // white
[ 1.0, 0.0, 1.0, 1.0 ] //magenta
];
// We need to parition the quad into two triangles in order for
// WebGL to be able to render it. In this case, we create two
// triangles from the quad indices
//vertex color assigned by the index of the vertex
var indices = [ a, b, c, a, c, d ];
var outer = false;
var vertarray =[];
var colarray =[];
var aDist = length(vertices[a]);
var bDist = length(vertices[b]);
var cDist = length(vertices[c]);
var dDist = length(vertices[d]);
var obj = {vertix:vec4(),color:vec4()};
for ( var i = 0; i < indices.length; ++i ) {
points.push( vertices[indices[i]] );
vertarray.push( vertices[indices[i]]);
vertexes.push(vertices[indices[i]]);
//colors.push( vertexColors[indices[i]] );
// for solid colored faces use
if(aDist > 1.1 && bDist > 1.1 && cDist > 1.1 && dDist>1.1){
colors.push(vertexColors[a]);
colarray.push(vertexColors[a]);
}
else{
colors.push(vertexColors[0]);
colarray.push(vertexColors[0]);
}
}
//return {vertix:vertexes,color:colarray};
return vertexes;
}
var count = 0;
function render()
{
gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
count = count +1;
var globMatrixLoc = gl.getUniformLocation(program,"globalRotMatrix");
gl.uniformMatrix4fv(globMatrixLoc, false, flatten(globTheta));
for( var k = 0; k < 27; k++){
var rotMatrixLoc = gl.getUniformLocation(program,"rotMatrix");
gl.uniformMatrix4fv(rotMatrixLoc, false, flatten(cubes[k*2+1]));
gl.drawArrays( gl.TRIANGLES, k*36, 36 );
}
//gl.drawArrays( gl.TRIANGLES, 0, 36 );
//theta[axis] +=0;
//gl.uniform3fv(thetaLoc, theta);
//requestAnimFrame( render );
}
|
9e1c345de806923e56c79cccc6c9c9c6c29e05a1
|
[
"JavaScript"
] | 1
|
JavaScript
|
gordomac/puzzle
|
854f0c0d665075e4e6c61efab87316a46a59ca5d
|
af7e81849f7ea7004736aaddbd004512e3fe0c81
|
refs/heads/main
|
<file_sep>const validarCrearCuenta = values => {
let errors = {};
if (!values.nombre.trim())
errors.nombre = 'El nombre es obligatorio';
if (!values.email.trim())
errors.email = "El email es obligatorio";
else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email.trim()))
errors.email = "Email no válido";
if (!values.password.trim())
errors.password = "El password es obligatorio";
else if (values.password.trim().length < 6)
errors.password = "El password tiene que tener almenos 6 caracteres";
return errors;
}
export default validarCrearCuenta;<file_sep>const validarCrearProducto = values => {
let errors = {};
if (!values.nombre.trim())
errors.nombre = "El nombre del producto es obligatorio";
if (!values.empresa.trim())
errors.empresa = "El Nombre de empresa es obligatorio";
if (!values.url.trim())
errors.url = "La url del producto es obligatorio";
else if (!/^(ftp|http|https):\/\/[^ "]+$/.test(values.url.trim()))
errors.url = "URL mal formateada o no válida";
if (!values.descripcion.trim())
errors.descripcion = "Agrega una descripción de tu producto";
return errors;
}
export default validarCrearProducto;<file_sep># Product Hunt App: Next
## 👨💻 [View Demo](https://awesome-johnson-24165b.netlify.app/)
|
2d2d1345620d6dddde0497fea673d11c5f9d0c0e
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
developaul/producthunt-next
|
2f310518ee238dcce0a46c12749577c9539fa88b
|
7f1078a2eb3ebd22861a3b43b277925b426999b9
|
refs/heads/master
|
<repo_name>zavolanlab/Liver3DCulture<file_sep>/05_PCA.R
#!/usr/bin/env Rscript
### Created: Jan 27, 2020
### Author: <NAME>
### Company: Zavolan Group, Biozentrum, University of Basel
# Load required libraries and set system parameters
options(java.parameters = "-Xmx10000m")
library(gplots)
library(broom)
library(ggplot2)
library(plyr)
library(grid)
library(dplyr)
library(matrixStats)
library(ggdendro)
require(gridExtra)
##### For making GO analysis with DAVID
if (!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("RDAVIDWebService")
library("RDAVIDWebService")
splitfun <- function(a) substr(a,12,1000000L)
#####
# Load gene annotation for human
ens2name_human_rel_96 <- read.table("GeneIdTOGeneName.txt",header=F, sep="\t")
colnames(ens2name_human_rel_96) <- c("ensembl_id","gene_symbol")
# Load pre-processed data
tpms_gene <- read.table("GSE142206_tpms.txt",header=T)
rownames(tpms_gene) <- tpms_gene$ensembl_id
tpms_gene <- tpms_gene[,-c(1,2)]
tpms_gene <- tpms_gene[,c(16,17,18,1:15)]
# Annotation of replicates
des=c("Control","Collagen (0.5 mg/ml)","Collagen (1.0 mg/ml)","Matrigel (1.5 mg/ml)","Matrigel (3.0 mg/ml)","Matrigel (6.0 mg/ml)")
n_rep <- c(3,3,3,3,3,3)
# Plot coordinates of nth (n_comp) component
plot_pca <- function(svd.mat,n,des,n_rep,n_comp){
n_cond=length(n_rep)
ev <- svd.mat$v
d_2 <- (svd.mat$d)^2
par(mar=c(8.1, 4.1, 4.1, 4.1), xpd=TRUE)
df_ggplot <- data.frame(des=rep(des,n_rep),coord=ev[((n_comp-1)*n+1):(n_comp*n)])
df_ggplot$des <- factor(df_ggplot$des, levels = des)
g <- (ggplot(df_ggplot, aes(x=des, y=coord)) +
geom_boxplot(outlier.shape = NA) +
geom_jitter(shape=19, position=position_jitter(0.2),size=2.5) +
theme_bw() + theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
text = element_text(family="Helvetica",size=8,color="black"),axis.title.x=element_blank(),
axis.text.x = element_text(family="Helvetica",size=8,angle = 45,hjust = 1),
axis.title.y = element_text(family="Helvetica",color="black", size=9)) +
ylab(paste("PC",toString(n_comp)," (explained variance: ",round(d_2[n_comp]/sum(d_2)*100,3),"%)",sep="")))
return(g)
}
# Get genes contributing to a principle component
pattern <- function(svd_mat,gene_list,n_rep,n_comp) {
ev <- svd_mat$v
# Calculate projections
proj <- svd_mat$u%*%diag(svd_mat$d)
rownames(proj) <- gene_list
# Calculate correlations
crl <- proj/sqrt(rowSums(proj^2))
# Scaling projections
sc.proj <- proj[,n_comp]/max(abs(proj[,n_comp]))
# Create a data frame with projections, correlations and z scores for projections
df <- data.frame(proj=sc.proj,cor=crl[,n_comp],proj.z = (sc.proj-mean(sc.proj))/sd(sc.proj))
rownames(df) <- rownames(proj)
df$ensembl_id <- rownames(df)
return(df)
}
# Perform principal component analysis for all conditions together
# Remove lowly expressed transcripts and perform SVD
keep <- rowSums(tpms_gene>1)>=min(n_rep)
tpms_gene_k <- tpms_gene[keep,]
tpms_gene.log <- log2(tpms_gene_k+1)
tpms_gene_s1 <- apply(tpms_gene.log,2,scale,scale=F,center=T)
tpms_gene_s2 <- apply(tpms_gene_s1,1,scale,scale=F,center=T)
svd.mat <- svd(t(tpms_gene_s2))
ev <- svd.mat$v
d <- svd.mat$d
pc1 <- ev[,1] # Increasing profile
pc1_var <- round(d[1]^2/sum(d^2)*100,digits=2)
pc2_var <- round(d[2]^2/sum(d^2)*100,digits=2)
plot_df <- data.frame(PC1=pc1,PC2=ev[,2])
plot_df$cond <- factor(rep(des,n_rep),levels = des)
p1 <- ggplot(plot_df, aes(x=PC1, y=PC2, color=cond))+
geom_point()+
scale_color_manual(values=c("cyan", "blue", "green","red","black","orange"))+
theme_bw()+
coord_fixed()+
xlab(paste0("PC1, ",pc1_var,"%"))+
ylab(paste0("PC2, ",pc2_var,"%"))+
theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank(),
axis.text.x = element_text(family="Helvetica",color="black", size=8),
axis.text.y = element_text(family="Helvetica",color="black", size=8),
axis.title.x = element_text(family="Helvetica",color="black", size=9),
axis.title.y = element_text(family="Helvetica",color="black", size=9))
p1
p1=plot_pca(svd.mat,sum(n_rep),des,n_rep,1)
p2=plot_pca(svd.mat,sum(n_rep),des,n_rep,2)
grid.newpage()
grid.draw(cbind(ggplotGrob(p1), ggplotGrob(p2),size = "last"))
# Align gene expression to PCs
pattern_genes_pc1 <- pattern(svd.mat,rownames(tpms_gene_k),n_rep,1)
pattern_genes_pc1 <- merge(ens2name_human_rel_96,pattern_genes_pc1,by="ensembl_id")
ord <- order(pattern_genes_pc1$proj)
pattern_genes_pc1 <- pattern_genes_pc1[ord,]
pattern_genes_pc2 <- pattern(svd.mat,rownames(tpms_gene_k),n_rep,2)
pattern_genes_pc2 <- merge(ens2name_human_rel_96,pattern_genes_pc2,by="ensembl_id")
ord <- order(pattern_genes_pc2$proj)
pattern_genes_pc2 <- pattern_genes_pc2[ord,]
# Subset genes
zscore_thresh <- 1.96
cor_thresh <- 0.6
pc1_genes_higher_cg <- pattern_genes_pc1[which(pattern_genes_pc1$proj.z>=zscore_thresh & pattern_genes_pc1$cor>=cor_thresh),]
pc1_genes_lower_cg <- pattern_genes_pc1[which(pattern_genes_pc1$proj.z<=-zscore_thresh & pattern_genes_pc1$cor<=-cor_thresh),]
pc2_genes_higher_mg <- pattern_genes_pc2[which(pattern_genes_pc2$proj.z>=zscore_thresh & pattern_genes_pc2$cor>=cor_thresh),]
pc2_genes_lower_mg <- pattern_genes_pc2[which(pattern_genes_pc2$proj.z<=-zscore_thresh & pattern_genes_pc2$cor<=-cor_thresh),]
# Make a heatmap for genes aligned with PC1 and PC2
df <- tpms_gene.log[c(as.character(pc1_genes_higher_cg$ensembl_id),
as.character(pc1_genes_lower_cg$ensembl_id),
as.character(pc2_genes_higher_mg$ensembl_id),
as.character(pc2_genes_lower_mg$ensembl_id)),]
df <- (as.matrix(df)-rowMeans(as.matrix(df)))/rowSds(as.matrix(df))
df[df > 1] <- 1
df[df < -1] <- -1
df <- df[nrow(df):1,]
heatmap_ggplot <- expand.grid(gene_ids = rownames(df),replicates = colnames(df))
heatmap_ggplot$zsc <- as.vector(as.matrix(df))
n_tot <- nrow(pc1_genes_higher_cg)+nrow(pc1_genes_lower_cg)+nrow(pc2_genes_higher_mg)+nrow(pc2_genes_lower_mg)
y1 <- nrow(pc2_genes_lower_mg)
y2 <- y1+nrow(pc2_genes_higher_mg)
y3 <- y2+nrow(pc1_genes_lower_cg)
my.lines<-data.frame(x=c(3,6,9,12,15,0,0,0)+0.5,y=c(0,0,0,0,0,y1,y2,y3)+0.5,xend=c(3,6,9,12,15,18,18,18)+0.5,yend=c(n_tot,n_tot,n_tot,n_tot,n_tot,y1,y2,y3)+0.5)
p1 <- (ggplot(data=heatmap_ggplot, aes(x = replicates, y = gene_ids))
+ geom_tile(aes(fill = zsc))
# indicate paramters of the colobar of the legend
+ scale_fill_gradient2(low = "blue", high = "red", mid = "white",midpoint = 0, space = "Lab",name="mRNA level (z-score)")
# put the legend on the top
+ theme(legend.position="top",
axis.ticks.y = element_blank(),
legend.text=element_text(family="Helvetica",color="black", size=8),
axis.title.x=element_blank(),axis.title.y=element_blank(),
axis.text.x = element_text(family="Helvetica",size=8,angle=45,hjust = 1,color = "black"),
axis.text.y = element_text(family="Helvetica",color="black", size=8))
# put gene labels on the right and reverse the order
+ scale_y_discrete(position="right",labels=c())
+ scale_x_discrete(labels=c("Control, rep1","Control, rep2","Control, rep3",
"Collagen (0.5 mg/ml), rep1","Collagen (0.5 mg/ml), rep2","Collagen (0.5 mg/ml), rep3",
"Collagen (1.0 mg/ml), rep1","Collagen (1.0 mg/ml), rep2","Collagen (1.0 mg/ml), rep3",
"Matrigel (1.5 mg/ml), rep1","Matrigel (1.5 mg/ml), rep2","Matrigel (1.5 mg/ml), rep3",
"Matrigel (3.0 mg/ml), rep1","Matrigel (3.0 mg/ml), rep2","Matrigel (3.0 mg/ml), rep3",
"Matrigel (6.0 mg/ml), rep1","Matrigel (6.0 mg/ml), rep2","Matrigel (6.0 mg/ml), rep3"))
+ geom_segment(data=my.lines, aes(x,y,xend=xend, yend=yend), size=0.5, inherit.aes=F)
+ theme(axis.title.x=element_blank(),axis.title.y=element_blank()))
print(p1)
# Perform DAVID analysis of genes aligned with PC1
david<-DAVIDWebService(email="your_email", url="https://david.ncifcrf.gov/webservice/services/DAVIDWebService.DAVIDWebServiceHttpSoap12Endpoint/")
# Problems with timing out while loading the background https://support.bioconductor.org/p/65696/
setTimeOut(david, 100000)
setAnnotationCategories(david, c("GOTERM_BP_DIRECT","GOTERM_MF_DIRECT", "GOTERM_CC_DIRECT"))
# Load background
BG <- addList(david,rownames(tpms_gene_k),idType = "ENSEMBL_GENE_ID",listName = "expr_genes",listType = "Background")
# Annotation of genes higher in CG than in Control
FG <- addList(david,as.character(pc1_genes_higher_cg$ensembl_id),idType = "ENSEMBL_GENE_ID",listName = "pc1_genes_higher_cg",listType = "Gene")
setCurrentBackgroundPosition(david, 2)
setCurrentGeneListPosition(david,1)
david
david_pc1_genes_higher_cg <- data.frame(getFunctionalAnnotationChart(david))
# Annotation of genes lower in CG than in Control
FG <- addList(david,as.character(pc1_genes_lower_cg$ensembl_id),idType = "ENSEMBL_GENE_ID",listName = "pc1_genes_lower_cg",listType = "Gene")
setCurrentBackgroundPosition(david, 2)
setCurrentGeneListPosition(david,2)
david
david_pc1_genes_lower_cg <- data.frame(getFunctionalAnnotationChart(david))
# Make barplots for top 20 enriched terms
# Barplot for top 20 GO terms for genes positively correlated with PC1
ax_lim <- min(c(log10(david_pc1_genes_lower_cg[20:1,"PValue"]),log10(david_pc1_genes_higher_cg[20:1,"PValue"])))
go_names <- as.character(david_pc1_genes_higher_cg[20:1,"Term"])
go_names <- apply(as.matrix(go_names),2,splitfun)
df <- data.frame(name=go_names,log10_pv=log10(david_pc1_genes_higher_cg[20:1,"PValue"]))
df$name <- factor(df$name, levels = df$name)
p1 <- ggplot(df, aes(name, log10_pv)) +
geom_col() +
coord_flip() +
scale_y_reverse(limits=c(0,ax_lim))+
scale_x_discrete(position="top") +
theme_bw() +
theme(axis.text.x = element_text(family="Helvetica",colour = "black", size=8),axis.text.y = element_text(family="Helvetica",colour = "black", size=8),
axis.title.y=element_blank(),axis.title.x=element_text(family="Helvetica",colour = "black", size=9),
panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
geom_abline(intercept=2, slope=0, linetype=2, color="red", size=0.5)+
ylab("log10(p-value)")
# Barplot for top 20 GO terms for genes negatively correlated with PC1
go_names <- as.character(david_pc1_genes_lower_cg[20:1,"Term"])
go_names <- apply(as.matrix(go_names),2,splitfun)
df <- data.frame(name=go_names,log10_pv=log10(david_pc1_genes_lower_cg[20:1,"PValue"]))
df$name <- factor(df$name, levels = df$name)
p2 <- ggplot(df, aes(name, log10_pv)) +
geom_col() +
coord_flip() +
ylim(ax_lim,0) +
theme_bw() +
theme(axis.text.x = element_text(family="Helvetica",colour = "black", size=8),axis.text.y = element_text(family="Helvetica",colour = "black", size=8),
axis.title.y=element_blank(),axis.title.x=element_text(family="Helvetica",colour = "black", size=9),
panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
geom_abline(intercept=-2, slope=0, linetype=2, color="red", size=0.5)+
ylab("log10(p-value)")
grid.newpage()
grid.draw(cbind(ggplotGrob(p2), ggplotGrob(p1),size = "last"))
# Get the list of genes contributing to extracellular region/extreacellular space; genes were used for the STRING annotation
tmp1 <- as.character(unlist(strsplit(david_pc1_genes_higher_cg[1,6],", ")))
tmp2 <- as.character(unlist(strsplit(david_pc1_genes_lower_cg[1,6],", ")))
View(data.frame(unique(c(tmp1,tmp2))))
# Perform DAVID analysis of genes aligned with PC2
# Annotation of genes higher in CG than in Control
FG <- addList(david,as.character(pc2_genes_higher_mg$ensembl_id),idType = "ENSEMBL_GENE_ID",listName = "pc2_genes_higher_mg",listType = "Gene")
setCurrentBackgroundPosition(david, 2)
setCurrentGeneListPosition(david,3)
david
david_pc2_genes_higher_mg <- data.frame(getFunctionalAnnotationChart(david))
# Annotation of genes lower in CG than in Control
FG <- addList(david,as.character(pc2_genes_lower_mg$ensembl_id),idType = "ENSEMBL_GENE_ID",listName = "pc2_genes_lower_mg",listType = "Gene")
setCurrentBackgroundPosition(david, 2)
setCurrentGeneListPosition(david,4)
david
david_pc2_genes_lower_mg <- data.frame(getFunctionalAnnotationChart(david))
# Make barplots for top 20 enriched terms
# Barplot for top 20 GO terms for genes positively correlated with PC2
ax_lim <- min(c(log10(david_pc2_genes_lower_mg[20:1,"PValue"]),log10(david_pc2_genes_higher_mg[20:1,"PValue"])))
go_names <- as.character(david_pc2_genes_higher_mg[20:1,"Term"])
go_names <- apply(as.matrix(go_names),2,splitfun)
df <- data.frame(name=go_names,log10_pv=log10(david_pc2_genes_higher_mg[20:1,"PValue"]))
df$name <- factor(df$name, levels = df$name)
p1 <- ggplot(df, aes(name, log10_pv)) +
geom_col() +
coord_flip() +
scale_y_reverse(limits=c(0,ax_lim))+
scale_x_discrete(position="top") +
theme_bw() +
theme(axis.text.x = element_text(family="Helvetica",colour = "black", size=8),axis.text.y = element_text(family="Helvetica",colour = "black", size=8),
axis.title.y=element_blank(),axis.title.x=element_text(family="Helvetica",colour = "black", size=9),
panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
geom_abline(intercept=2, slope=0, linetype=2, color="red", size=0.5)+
ylab("log10(p-value)")
# Barplot for top 20 GO terms for genes negatively correlated with PC2
go_names <- as.character(david_pc2_genes_lower_mg[20:1,"Term"])
go_names <- apply(as.matrix(go_names),2,splitfun)
df <- data.frame(name=go_names,log10_pv=log10(david_pc2_genes_lower_mg[20:1,"PValue"]))
df$name <- factor(df$name, levels = df$name)
p2 <- ggplot(df, aes(name, log10_pv)) +
geom_col() +
coord_flip() +
ylim(ax_lim,0) +
theme_bw() +
theme(axis.text.x = element_text(family="Helvetica",colour = "black", size=8),axis.text.y = element_text(family="Helvetica",colour = "black", size=8),
axis.title.y=element_blank(),axis.title.x=element_text(family="Helvetica",colour = "black", size=9),
panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
geom_abline(intercept=-2, slope=0, linetype=2, color="red", size=0.5)+
ylab("log10(p-value)")
grid.newpage()
grid.draw(cbind(ggplotGrob(p2), ggplotGrob(p1),size = "last"))
# Get the list of genes contributing to extracellular region/extreacellular space; genes were used for the STRING annotation
tmp1 <- as.character(unlist(strsplit(david_pc2_genes_higher_mg[1,6],", ")))
tmp2 <- as.character(unlist(strsplit(david_pc2_genes_lower_mg[1,6],", ")))
View(data.frame(unique(c(tmp1,tmp2))))
<file_sep>/01_GeneIdName.sh
#!/usr/bin/env bash
### Created: Jan 27, 2020
### Author: <NAME>
### Company: Zavolan Group, Biozentrum, University of Basel
# Download human GTF
wget ftp://ftp.ensembl.org/pub/release-96/gtf/homo_sapiens/Homo_sapiens.GRCh38.96.gtf.gz
gunzip Homo_sapiens.GRCh38.96.gtf.gz
# Get genes associated with chromosomes
awk '($1 == "1") || ($1 == "2") || ($1 == "3") || ($1 == "4") || ($1 == "5") || ($1 == "6") || ($1 == "7") || ($1 == "8") || ($1 == "9") || ($1 == "10") || ($1 == "11") || ($1 == "12") || ($1 == "13") || ($1 == "14") || ($1 == "15") || ($1 == "16") || ($1 == "17") || ($1 == "18") || ($1 == "19") || ($1 == "20")|| ($1 == "21") || ($1 == "22") || ($1 == "23") || ($1 == "MT") || ($1 == "X") || ($1 == "Y") { print $0}' Homo_sapiens.GRCh38.96.gtf > tmp2
awk '($3 == "gene") { print $10"\t"$14}' tmp2 > tmp3
# Assign Ensembl ids to gene symbols
sed 's/\"//g' tmp3 > tmp4
sed 's/;//g' tmp4 > GeneIdTOGeneName.txt
# Remove temporary variables
rm tmp2
rm tmp3
rm tmp4
<file_sep>/03_DE_analysis.R
#!/usr/bin/env Rscript
### Created: Jan 27, 2020
### Author: <NAME>
### Company: Zavolan Group, Biozentrum, University of Basel
# Load required libraries
#source("http://bioconductor.org/biocLite.R")
library(gplots)
library(edgeR)
library(broom)
library(ggplot2)
library(plyr)
library(grid)
library(dplyr)
library(matrixStats)
# Load gene annotation for human
ens2name_human_rel_96 <- read.table("GeneIdTOGeneName.txt",header=F, sep="\t")
colnames(ens2name_human_rel_96) <- c("ensembl_id","gene_symbol")
# Load pre-processed data
counts_gene_rnaseq <- read.table("GSE142206_counts.txt",header=T)
rownames(counts_gene_rnaseq) <- as.character(counts_gene_rnaseq$ensembl_id)
counts_gene_rnaseq <- counts_gene_rnaseq[,-c(1,2)]
# Annotation of replicates
des=c("CG_0.5","CG_1.0","MG_1.5","MG_3.0","MG_6.0","CON")
n_rep <- c(3,3,3,3,3,3)
# DE analysis for conditions
# Annotate conditions to replicates
group <- factor(rep(des,n_rep),levels = des)
# DE analysis is based on the analysis of raw counts
cts <- round(counts_gene_rnaseq)
y <- DGEList(counts=cts,group=group)
# Normalization
y <- calcNormFactors(y)
# Quantify counts per million
cpm_ent <- data.frame(cpm(y))
# Filtering lowly expressed genes
keep <- rowSums(cpm(y)>1)>=min(n_rep)
y <- y[keep,,keep.lib.sizes=F]
# Create a design matrix and estimate dispersion
design <- model.matrix(~group)
y <- estimateDisp(y,design,robust=TRUE)
plotBCV(y)
# Testing for DE genes
fit <- glmFit(y,design)
# Initialize matrices for storing the results of all pairwise comparisons
# Matrix with log fold changes
DE_logFC <- matrix(ncol=(length(des)/2)*(length(des)-1), nrow=nrow(y$counts))
# Matrix with p-values
DE_pval <- matrix(ncol=(length(des)/2)*(length(des)-1), nrow=nrow(y$counts))
# Matrix with FDRs
DE_FDR <- matrix(ncol=(length(des)/2)*(length(des)-1), nrow=nrow(y$counts))
# Matrix with median expression per condition
DE_expr <- matrix(ncol=(length(des)/2)*(length(des)-1), nrow=nrow(y$counts))
coln <- c()
# Perform comparisons of all conditions one by one to the 1st one
k=1
for (j in seq(2,length(des))){
# This is the difference between this and next for loops
DE <- glmLRT(fit,coef=j)
DEt <- DE$table
DE_logFC[,k]=DEt$logFC
DE_pval[,k]=DEt$PValue
DE_expr[,k]=DEt$logCPM
DE_FDR[,k]=p.adjust(DEt$PValue,method="BH")
k=k+1
coln <- c(coln,paste(des[j],"v",des[1],sep=""))
}
for (i in seq(2,length(des)-1)){
for (j in seq(i+1,length(des))){
# Create a constrast for comparing two conditions between each other
x <- rep(0,length(des))
x[i]=-1
x[j]=1
# This is the difference between this and previous for loops
DE <- glmLRT(fit,contrast=x)
DEt <- DE$table
DE_logFC[,k]=DEt$logFC
DE_pval[,k]=DEt$PValue
DE_expr[,k]=DEt$logCPM
DE_FDR[,k]=p.adjust(DEt$PValue,method="BH")
k=k+1
coln <- c(coln,paste(des[j],"v",des[i],sep=""))
}
}
DE_logFC <- data.frame(DE_logFC)
DE_pval <- data.frame(DE_pval)
DE_FDR <- data.frame(DE_FDR)
DE_expr <- data.frame(DE_expr)
rownames(DE_logFC) <- rownames(y$counts)
rownames(DE_pval) <- rownames(y$counts)
rownames(DE_FDR) <- rownames(y$counts)
rownames(DE_expr) <- rownames(y$counts)
colnames(DE_logFC) <- coln
colnames(DE_pval) <- coln
colnames(DE_FDR) <- coln
colnames(DE_expr) <- coln
# Create a directory for saving results of DE analysis
system("mkdir -p DE_analysis")
# Save the resulting table with the DE analysis for sharing
DE_logFC_save <- DE_logFC
DE_logFC_save$ensembl_id <- rownames(DE_logFC_save)
DE_logFC_save <- merge(ens2name_human_rel_96,DE_logFC_save,by="ensembl_id")
write.table(DE_logFC_save,"DE_analysis/DE_logFC.txt",quote = F,col.names = T,row.names = F,sep="\t")
DE_FDR_save <- DE_FDR
DE_FDR_save$ensembl_id <- rownames(DE_FDR_save)
DE_FDR_save <- merge(ens2name_human_rel_96,DE_FDR_save,by="ensembl_id")
write.table(DE_FDR_save,"DE_analysis/DE_FDR.txt",quote = F,col.names = T,row.names = F,sep="\t")
<file_sep>/README.md
This repository contains all scripts used for RNA-Seq data analysis presented in the manuscript by Ghosh et al. "The transcriptional landscapes of a hepatoma cell line grown on scaffolds of extracellular matrix proteins".
To get started, clone the repository and change to the directory you specified as the working directory:
```bash
git clone https://github.com/zavolanlab/Liver3DCulture.git path/to/workdir
cd path/to/workdir
```
Download and unzip pre-processed RNA-Seq data "GSE142206_counts.txt.gz" (a text file containing raw counts per gene across conditions) and "GSE142206_tpms.txt.gz" (a text file containing normalized expression per gene in TPM units across conditions) published in GEO in the working directory (see https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE142206). The analysis is based on processing these data files.
Execute the following scripts in the indicated order:
1. Create a table matching ensembl gene ids and gene symbols by running "sh 01_GeneIdGeneName.sh". The resulting table is saved as "GeneIdTOGeneName.txt".
2. Create a list of human KEGG pathways and associated genes. Run R script "02_HumanPathways.R". Resulting tables are saved as "HumanGenesPathways.txt" and "HumanPathIdName.txt".
3. Perform differential expression (DE) analysis. Run R script "03_DE_analysis.R". A directory with results called "DE_analysis" will be created within your working directory.
4. Perform gene set enrichment analysis. Run R script "04_GSEA.R". A directory with GSEA results called "GSEA" will be created within your working directory. Note that before running the script you should install GSEA software for the command line, see https://software.broadinstitute.org/gsea/downloads.jsp
5. Perform principal component analysis. Run R script "05_PCA.R".<file_sep>/04_GSEA.R
#!/usr/bin/env Rscript
### Created: Jan 27, 2020
### Author: <NAME>
### Company: Zavolan Group, Biozentrum, University of Basel
# Load required libraries
library(grid)
library(ggplot2)
# GSEA
# Download GSEA for command line and follow instructions, see https://software.broadinstitute.org/gsea/downloads.jsp
# Function for runnung GSEA
gsea_command_line <- function(gmt_file,rnk_file,report_label,out_dir) {
system(paste("ml purge &&","ml Java/11.0.3_7 &&",'export _JAVA_OPTIONS="-Xmx1024m" &&', "sh gsea_software/GSEA_4.0.3/gsea-cli.sh GSEAPreranked",
"-gmx", gmt_file,
"-rnk", rnk_file,
"-set_max 500",
"-set_min 15",
"-plot_top_x 50",
"-rpt_label", report_label,
"-zip_report false",
"-out", out_dir,sep=" "),wait=FALSE)
}
# Prepare tables for GSEA
# Load human KEGG pathways and genes assigned to pathways for human
path_id_name_human <- read.table("HumanPathIdName.txt",sep="\t")
path_gene_human <- read.table("HumanGenesPathways.txt",sep="\t")
# Remove pathways associated with deseases
path_id_name_human <- path_id_name_human[which(substr(path_id_name_human$path_id,10,10)!="5"),]
path_gene_human <- path_gene_human[which(substr(path_gene_human$path_id,10,10)!="5"),]
path_id_name_human <- path_id_name_human[-which(path_id_name_human$path_id %in% c("path:hsa04930","path:hsa04940","path:hsa04950","path:hsa04932","path:hsa04931","path:hsa04933","path:hsa04934")),]
path_gene_human <- path_gene_human[-which(path_gene_human$path_id %in% c("path:hsa04930","path:hsa04940","path:hsa04950","path:hsa04932","path:hsa04931","path:hsa04933","path:hsa04934")),]
# Create a table containing the code of the pathway and corresponding genes (gmt format required for GSEA)
mat_path <- matrix(,ncol=1500,nrow=length(path_id_name_human$path_id))
k <- 1
for (i in as.character(path_id_name_human$path_id)){
mat_path[k,1] <- i
genes_path <- as.character(path_gene_human[which(path_gene_human$path_id == i),"gene_symbol"])
j=3
for (g in genes_path){
mat_path[k,j] <- g
j <- j+1
}
k <- k+1
}
mat_path[1:(k-1),2] <- rep("na",k-1)
# Create a directory for storing GSEA
system("mkdir -p GSEA")
write.table(mat_path,"GSEA/KEGG_pathways_human.gmt",sep="\t",row.names = F,col.names = F,quote = F, na="")
# Load the table from DE analysis containing log fold changes
DE_logFC <- read.table("DE_analysis/DE_logFC.txt",sep="\t",header = T)
##### GSEA for Control vs MG 1.5
# Create a repository for storing the output
system("mkdir -p GSEA/GSEA_CONvMG_1.5")
# Prepare ranking tables for Control vs MG 1.5
DE_logFC_GSEA <- DE_logFC[,c("gene_symbol","CONvMG_1.5")]
ord <- order(DE_logFC_GSEA$CONvMG_1.5,decreasing = T)
DE_logFC_GSEA <- DE_logFC_GSEA[ord,]
write.table(DE_logFC_GSEA,"GSEA/GSEA_CONvMG_1.5/Preranked_CONvMG_1.5.rnk",sep="\t",row.names = F,col.names = F,quote = F)
# Specify the location of required repositories and files
gmt_file <- "GSEA/KEGG_pathways_human.gmt"
rnk_file <- "GSEA/GSEA_CONvMG_1.5/Preranked_CONvMG_1.5.rnk"
report_label <- "GSEA_CONvMG_1.5"
out_dir <- "GSEA/GSEA_CONvMG_1.5"
gsea_command_line(gmt_file,rnk_file,report_label,out_dir)
##### GSEA for Control vs MG 3
# Create a repository for storing the output
system("mkdir -p GSEA/GSEA_CONvMG_3.0")
# Prepare ranking tables for Control vs MG 3
DE_logFC_GSEA <- DE_logFC[,c("gene_symbol","CONvMG_3.0")]
ord <- order(DE_logFC_GSEA$CONvMG_3.0,decreasing = T)
DE_logFC_GSEA <- DE_logFC_GSEA[ord,]
write.table(DE_logFC_GSEA,"GSEA/GSEA_CONvMG_3.0/Preranked_CONvMG_3.0.rnk",sep="\t",row.names = F,col.names = F,quote = F)
# Specify the location of required repositories and files
gmt_file <- "GSEA/KEGG_pathways_human.gmt"
rnk_file <- "GSEA/GSEA_CONvMG_3.0/Preranked_CONvMG_3.0.rnk"
report_label <- "GSEA_CONvMG_3.0"
out_dir <- "GSEA/GSEA_CONvMG_3.0"
gsea_command_line(gmt_file,rnk_file,report_label,out_dir)
##### GSEA for Control vs MG 6
# Create a repository for storing the output
system("mkdir -p GSEA/GSEA_CONvMG_6.0")
# Prepare ranking tables for Control vs MG 6
DE_logFC_GSEA <- DE_logFC[,c("gene_symbol","CONvMG_6.0")]
ord <- order(DE_logFC_GSEA$CONvMG_6.0,decreasing = T)
DE_logFC_GSEA <- DE_logFC_GSEA[ord,]
write.table(DE_logFC_GSEA,"GSEA/GSEA_CONvMG_6.0/Preranked_CONvMG_6.0.rnk",sep="\t",row.names = F,col.names = F,quote = F)
# Specify the location of required repositories and files
gmt_file <- "GSEA/KEGG_pathways_human.gmt"
rnk_file <- "GSEA/GSEA_CONvMG_6.0/Preranked_CONvMG_6.0.rnk"
report_label <- "GSEA_CONvMG_6.0"
out_dir <- "GSEA/GSEA_CONvMG_6.0"
gsea_command_line(gmt_file,rnk_file,report_label,out_dir)
##### GSEA for Control vs CG 0.5
# Create a repository for storing the output
system("mkdir -p GSEA/GSEA_CONvCG_0.5")
# Prepare ranking tables for Control vs CG 0.5
DE_logFC_GSEA <- DE_logFC[,c("gene_symbol","CONvCG_0.5")]
ord <- order(DE_logFC_GSEA$CONvCG_0.5,decreasing = T)
DE_logFC_GSEA <- DE_logFC_GSEA[ord,]
write.table(DE_logFC_GSEA,"GSEA/GSEA_CONvCG_0.5/Preranked_CONvCG_0.5.rnk",sep="\t",row.names = F,col.names = F,quote = F)
# Specify the location of required repositories and files
gmt_file <- "GSEA/KEGG_pathways_human.gmt"
rnk_file <- "GSEA/GSEA_CONvCG_0.5/Preranked_CONvCG_0.5.rnk"
report_label <- "GSEA_CONvCG_0.5"
out_dir <- "GSEA/GSEA_CONvCG_0.5"
gsea_command_line(gmt_file,rnk_file,report_label,out_dir)
##### GSEA for Control vs CG 1
# Create a repository for storing the output
system("mkdir -p GSEA/GSEA_CONvCG_1.0")
# Prepare ranking tables for Control vs CG 1
DE_logFC_GSEA <- DE_logFC[,c("gene_symbol","CONvCG_1.0")]
ord <- order(DE_logFC_GSEA$CONvCG_1.0,decreasing = T)
DE_logFC_GSEA <- DE_logFC_GSEA[ord,]
write.table(DE_logFC_GSEA,"GSEA/GSEA_CONvCG_1.0/Preranked_CONvCG_1.0.rnk",sep="\t",row.names = F,col.names = F,quote = F)
# Specify the location of required repositories and files
gmt_file <- "GSEA/KEGG_pathways_human.gmt"
rnk_file <- "GSEA/GSEA_CONvCG_1.0/Preranked_CONvCG_1.0.rnk"
report_label <- "GSEA_CONvCG_1.0"
out_dir <- "GSEA/GSEA_CONvCG_1.0"
gsea_command_line(gmt_file,rnk_file,report_label,out_dir)
# Load GSEA reports !!!!!!!!! Note that names of output directories with GSEA results contain a time stamp !!!!!!!!!!!!!
# Control vs MG 1.5
gsea_con_v_mg1.5_pos <- read.table("GSEA/GSEA_CONvMG_1.5/GSEA_CONvMG_1.5.GseaPreranked.1578923228839/gsea_report_for_na_pos_1578923228839.xls",sep="\t")
gsea_con_v_mg1.5_pos <- gsea_con_v_mg1.5_pos[,-c(2,3,12)]
colnames(gsea_con_v_mg1.5_pos) <- unlist(gsea_con_v_mg1.5_pos[1,])
gsea_con_v_mg1.5_pos <- gsea_con_v_mg1.5_pos[-1,]
gsea_con_v_mg1.5_neg <- read.table("GSEA/GSEA_CONvMG_1.5/GSEA_CONvMG_1.5.GseaPreranked.1578923228839/gsea_report_for_na_neg_1578923228839.xls",sep="\t")
gsea_con_v_mg1.5_neg <- gsea_con_v_mg1.5_neg[,-c(2,3,12)]
colnames(gsea_con_v_mg1.5_neg) <- unlist(gsea_con_v_mg1.5_neg[1,])
gsea_con_v_mg1.5_neg <- gsea_con_v_mg1.5_neg[-1,]
gsea_con_v_mg1.5 <- rbind(gsea_con_v_mg1.5_pos,gsea_con_v_mg1.5_neg)
# Control vs MG 3.0
gsea_con_v_mg3.0_pos <- read.table("GSEA/GSEA_CONvMG_3.0/GSEA_CONvMG_3.0.GseaPreranked.1578923228843/gsea_report_for_na_pos_1578923228843.xls",sep="\t")
gsea_con_v_mg3.0_pos <- gsea_con_v_mg3.0_pos[,-c(2,3,12)]
colnames(gsea_con_v_mg3.0_pos) <- unlist(gsea_con_v_mg3.0_pos[1,])
gsea_con_v_mg3.0_pos <- gsea_con_v_mg3.0_pos[-1,]
gsea_con_v_mg3.0_neg <- read.table("GSEA/GSEA_CONvMG_3.0/GSEA_CONvMG_3.0.GseaPreranked.1578923228843/gsea_report_for_na_neg_1578923228843.xls",sep="\t")
gsea_con_v_mg3.0_neg <- gsea_con_v_mg3.0_neg[,-c(2,3,12)]
colnames(gsea_con_v_mg3.0_neg) <- unlist(gsea_con_v_mg3.0_neg[1,])
gsea_con_v_mg3.0_neg <- gsea_con_v_mg3.0_neg[-1,]
gsea_con_v_mg3.0 <- rbind(gsea_con_v_mg3.0_pos,gsea_con_v_mg3.0_neg)
# Control vs MG 6.0
gsea_con_v_mg6.0_pos <- read.table("GSEA/GSEA_CONvMG_6.0/GSEA_CONvMG_6.0.GseaPreranked.1578923228842/gsea_report_for_na_pos_1578923228842.xls",sep="\t")
gsea_con_v_mg6.0_pos <- gsea_con_v_mg6.0_pos[,-c(2,3,12)]
colnames(gsea_con_v_mg6.0_pos) <- unlist(gsea_con_v_mg6.0_pos[1,])
gsea_con_v_mg6.0_pos <- gsea_con_v_mg6.0_pos[-1,]
gsea_con_v_mg6.0_neg <- read.table("GSEA/GSEA_CONvMG_6.0/GSEA_CONvMG_6.0.GseaPreranked.1578923228842/gsea_report_for_na_neg_1578923228842.xls",sep="\t")
gsea_con_v_mg6.0_neg <- gsea_con_v_mg6.0_neg[,-c(2,3,12)]
colnames(gsea_con_v_mg6.0_neg) <- unlist(gsea_con_v_mg6.0_neg[1,])
gsea_con_v_mg6.0_neg <- gsea_con_v_mg6.0_neg[-1,]
gsea_con_v_mg6.0 <- rbind(gsea_con_v_mg6.0_pos,gsea_con_v_mg6.0_neg)
# Control vs CG 0.5
gsea_con_v_cg0.5_pos <- read.table("GSEA/GSEA_CONvCG_0.5/GSEA_CONvCG_0.5.GseaPreranked.1578923228842/gsea_report_for_na_pos_1578923228842.xls",sep="\t")
gsea_con_v_cg0.5_pos <- gsea_con_v_cg0.5_pos[,-c(2,3,12)]
colnames(gsea_con_v_cg0.5_pos) <- unlist(gsea_con_v_cg0.5_pos[1,])
gsea_con_v_cg0.5_pos <- gsea_con_v_cg0.5_pos[-1,]
gsea_con_v_cg0.5_neg <- read.table("GSEA/GSEA_CONvCG_0.5/GSEA_CONvCG_0.5.GseaPreranked.1578923228842/gsea_report_for_na_neg_1578923228842.xls",sep="\t")
gsea_con_v_cg0.5_neg <- gsea_con_v_cg0.5_neg[,-c(2,3,12)]
colnames(gsea_con_v_cg0.5_neg) <- unlist(gsea_con_v_cg0.5_neg[1,])
gsea_con_v_cg0.5_neg <- gsea_con_v_cg0.5_neg[-1,]
gsea_con_v_cg0.5 <- rbind(gsea_con_v_cg0.5_pos,gsea_con_v_cg0.5_neg)
# Control vs CG 1
gsea_con_v_cg1.0_pos <- read.table("GSEA/GSEA_CONvCG_1.0/GSEA_CONvCG_1.0.GseaPreranked.1578923228839/gsea_report_for_na_pos_1578923228839.xls",sep="\t")
gsea_con_v_cg1.0_pos <- gsea_con_v_cg1.0_pos[,-c(2,3,12)]
colnames(gsea_con_v_cg1.0_pos) <- unlist(gsea_con_v_cg1.0_pos[1,])
gsea_con_v_cg1.0_pos <- gsea_con_v_cg1.0_pos[-1,]
gsea_con_v_cg1.0_neg <- read.table("GSEA/GSEA_CONvCG_1.0/GSEA_CONvCG_1.0.GseaPreranked.1578923228839/gsea_report_for_na_neg_1578923228839.xls",sep="\t")
gsea_con_v_cg1.0_neg <- gsea_con_v_cg1.0_neg[,-c(2,3,12)]
colnames(gsea_con_v_cg1.0_neg) <- unlist(gsea_con_v_cg1.0_neg[1,])
gsea_con_v_cg1.0_neg <- gsea_con_v_cg1.0_neg[-1,]
gsea_con_v_cg1.0 <- rbind(gsea_con_v_cg1.0_pos,gsea_con_v_cg1.0_neg)
# Collect NES scores for all comparisons
df1 <- gsea_con_v_mg1.5[,c("NAME","NES")]
colnames(df1) <- c("path_id","NES_mg1.5")
df2 <- gsea_con_v_mg3.0[,c("NAME","NES")]
colnames(df2) <- c("path_id","NES_mg3.0")
df3 <- gsea_con_v_mg6.0[,c("NAME","NES")]
colnames(df3) <- c("path_id","NES_mg6.0")
df4 <- gsea_con_v_cg0.5[,c("NAME","NES")]
colnames(df4) <- c("path_id","NES_cg0.5")
df5 <- gsea_con_v_cg1.0[,c("NAME","NES")]
colnames(df5) <- c("path_id","NES_cg1.0")
# Merge NES scores from different comparisons into one data frame
gsea_nes <- merge(merge(merge(merge(df1,df2,by="path_id"),df3,by="path_id"),df4,by="path_id"),df5,by="path_id")
gsea_nes$path_id <- tolower(gsea_nes$path_id)
rownames(gsea_nes) <- gsea_nes$path_id
gsea_nes <- gsea_nes[,-1]
# Collect FDR scores for all comparisons
df1 <- gsea_con_v_mg1.5[,c("NAME","FDR q-val")]
colnames(df1) <- c("path_id","FDR_mg1.5")
df2 <- gsea_con_v_mg3.0[,c("NAME","FDR q-val")]
colnames(df2) <- c("path_id","FDR_mg3.0")
df3 <- gsea_con_v_mg6.0[,c("NAME","FDR q-val")]
colnames(df3) <- c("path_id","FDR_mg6.0")
df4 <- gsea_con_v_cg0.5[,c("NAME","FDR q-val")]
colnames(df4) <- c("path_id","FDR_cg0.5")
df5 <- gsea_con_v_cg1.0[,c("NAME","FDR q-val")]
colnames(df5) <- c("path_id","FDR_cg1.0")
# Merge FDR scores from different comparisons into one data frame
gsea_fdr <- merge(merge(merge(merge(df1,df2,by="path_id"),df3,by="path_id"),df4,by="path_id"),df5,by="path_id")
gsea_fdr$path_id <- tolower(gsea_fdr$path_id)
rownames(gsea_fdr) <- gsea_fdr$path_id
gsea_fdr <- gsea_fdr[,-1]
# Resulting data frame of FDRs and NESs consist of factors, convert factors to numeric
indx <- sapply(gsea_fdr, is.factor)
gsea_fdr[indx] <- lapply(gsea_fdr[indx], function(x) as.numeric(as.character(x)))
indx <- sapply(gsea_nes, is.factor)
gsea_nes[indx] <- lapply(gsea_nes[indx], function(x) as.numeric(as.character(x)))
# Reverse the sign of NES to perform the comparison to control
gsea_nes <- -gsea_nes
# Transform FDR for plotting heatmap
fdr_pos_nes <- 1-gsea_fdr
fdr_neg_nes <- -1+gsea_fdr
# Create a matrix for plotting a heatmap
fdr_heatmap <- matrix(,nrow=nrow(gsea_fdr),ncol=ncol(gsea_fdr))
for (i in seq(nrow(gsea_fdr))){
for (j in seq(ncol(gsea_fdr))){
# If NES >0, then the element of the matrix equals 1-FDR
if (gsea_nes[i,j]>0){
fdr_heatmap[i,j] <- fdr_pos_nes[i,j]
} else { # If NES <0, then the element of the matrix equals -1+FDR
fdr_heatmap[i,j] <- fdr_neg_nes[i,j]
}
}
}
fdr_heatmap <- data.frame(fdr_heatmap)
rownames(fdr_heatmap) <- rownames(gsea_fdr)
colnames(fdr_heatmap) <- colnames(gsea_fdr)
# Get pathway names
fdr_heatmap$path_id <- rownames(fdr_heatmap)
fdr_heatmap <- merge(path_id_name_human,fdr_heatmap,by="path_id")
rownames(fdr_heatmap) <- fdr_heatmap$path_name
fdr_heatmap <- fdr_heatmap[,-c(1,2)]
fdr_heatmap <- fdr_heatmap[,c(4,5,1,2,3)]
# Remove pathways that have FDR >=0.05 for all comparisons
fdr_heatmap <- fdr_heatmap[which(rowSums(abs(fdr_heatmap)>0.95)>=1),]
hc <- hclust(d = dist(fdr_heatmap, method = "euclidean"))
# Plot dendogram based on clustering results
dendo <- as.dendrogram(hc)
# Plot dendro
dendro.plot <- ggdendrogram(data = dendo, rotate = TRUE)
print(dendro.plot)
fdr_heatmap <- fdr_heatmap[hc$order,]
# Compose a matrix for plotting heatmap
com_heat <- expand.grid(path_id = rownames(fdr_heatmap),cond = colnames(fdr_heatmap))
# Add variable: transformed FDR
com_heat$fdr <- as.vector(as.matrix(fdr_heatmap))
p <- (ggplot(data=com_heat, aes(x = cond, y = path_id))
+ geom_tile(aes(fill = fdr))
# indicate paramters of the colorbar of the legend
+ scale_fill_gradient2(low = "blue", high = "red", mid = "white",midpoint = 0, space = "Lab",name="fdr")
# put the legend on the top
+ theme(legend.position="top",
legend.text=element_text(family="Helvetica",color="black", size=8),
axis.title.x=element_blank(),axis.title.y=element_blank(),
axis.text.x = element_text(family="Helvetica",size=8,angle=45,hjust = 1),
axis.text.y = element_text(family="Helvetica",color="black", size=8))
# put gene labels on the right and reverse the order
+ scale_y_discrete(position="right",labels=rownames(fdr_heatmap))
+ scale_x_discrete(labels=c("Collagen (0.5 mg/ml)","Collagen (1.0 mg/ml)","Matrigel (1.5 mg/ml)","Matrigel (3.0 mg/ml)","Matrigel (6.0 mg/ml)"))
+ coord_equal())
print(p)
<file_sep>/02_HumanPathways.R
#!/usr/bin/env Rscript
### Created: Jan 27, 2020
### Author: <NAME>
### Company: Zavolan Group, Biozentrum, University of Basel
# Load required libraries
source("https://bioconductor.org/biocLite.R")
biocLite("KEGGREST")
library(KEGGREST) # The version KEGGREST_1.16.1 was used
library(biomaRt)
path.list <- keggLink("hsa","pathway")
path.list.m <- as.matrix(path.list)
path.id <- unique(rownames(path.list.m))
path.gene <- data.frame(rownames(path.list.m),path.list.m)
colnames(path.gene) <- c("path_id", "entrez_id")
ent.id <- substring(path.gene$entrez_id,5)
path.gene$entrez_id <- as.numeric(ent.id)
# Convert Entrez Ids to Ensembl gene Ids
mart = useMart('ensembl')
listDatasets(mart)
human = useMart("ensembl", dataset = "hsapiens_gene_ensembl")
x <- listAttributes(human)
mapping <- getBM(attributes = c("entrezgene_id", "ensembl_gene_id"), mart = human, uniqueRows = TRUE)
colnames(mapping) <- c("entrez_id","ensembl_id")
map_ens_uniq <- mapping[!duplicated(mapping$ensembl_id), ]
# Merge pathways, entrez ids and pathway ids
path.gene <- merge(path.gene,map_ens_uniq,by="entrez_id")
# Add gene names
ens2name <- read.table("GeneIdTOGeneName.txt",header=F, sep="\t")
colnames(ens2name) <- c("ensembl_id","gene_symbol")
path.gene <- merge(path.gene,ens2name,by="ensembl_id")
# Add pathway names
pathid <- as.character(unique(path.gene$path_id))
tmp1 <- rep(NA,length(pathid))
tmp2 <- rep(NA,length(pathid))
for (i in seq(length(pathid))) {
tmp2[i] <- pathid[i]
res <- try(keggGet(pathid[i])[[1]]$NAME)
if(!inherits(res, "try-error"))
{ tmp1[i] <- keggGet(pathid[i])[[1]]$NAME
tmp1[i] <- substr(tmp1[i],1,nchar(tmp1[i])-23)
}
}
path_id_name <- data.frame(path_id=tmp2,path_name=tmp1)
# Write a table containing pathway IDs and pathway names
write.table(path_id_name,"HumanPathIdName.txt",sep="\t",quote = T)
# Write a table containing pathways and genes annotated to these pathways
path.gene <- merge(path.gene,path_id_name,by="path_id")
write.table(path.gene,"HumanGenesPathways.txt",sep="\t",quote = T)
|
add8c82ab1378a37087a2a154836b010f5262a52
|
[
"Markdown",
"R",
"Shell"
] | 6
|
R
|
zavolanlab/Liver3DCulture
|
11c12b94887cfaa60d83857f416a4243baddbeb4
|
e5c9d46d0e486e1283cf5f01da28325c2498256c
|
refs/heads/master
|
<repo_name>MJAlexander/blogdown-website<file_sep>/content/posts/2019-08-07-mrp.Rmd
---
title: "Analyzing name changes after marriage using a non-representative survey"
author: "<NAME>"
date: "2019-08-07"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Introduction
Recently on Twitter, sociologist [<NAME>](https://socy.umd.edu/facultyprofile/cohen/philip-n) put out a survey asking people about their decisions to change their name (or not) after marriage. The response was impressive - there are currently over 5,000 responses. Thanks to Phil, the data from the survey are publicly available and downloadable [here](https://osf.io/uzqdn/) for anyone to do their own analysis.
However, there's an issue with using the raw data without lots of caveats: the respondents are not very representative of the broader population, and in particular tend to have a higher education level and are younger than average. As such, if we looked at the raw estimates from the data, on indicators like the proportion of women who kept their name after marriage, it is unlikely to be a reasonable estimate for the broader population.
This is a very common problem for social scientists: trying to come up with representative estimates using non-representative data. In this post I'll introduce one particular technique of trying to do this: multilevel regression and post-stratification (MRP). In particular, I'll use data from the marital name change survey to estimate the proportion of women in the US who kept their maiden name after marriage.
# What is MRP?
First, a very brief outline of MRP. Imagine we run a survey asking people if they like olives. We have a survey with 1000 respondents, 500 of which are aged 21+ and 500 of which are under 21. We could use the survey results to calculate the proportion of people who like olives. However, [we know](https://www.census.gov/prod/cen2010/briefs/c2010br-03.pdf) that the population distribution below and above age 21 is closer to 30%/70%, rather than 50/50 implied by our survey. So just taking the raw result from our survey over-represents the opinions of young people.
## The 'P' bit: post-stratification
Given we know the age distribution of the broader population, we can reweight (post-stratify) our results: so in this example, an estimate of the proportion of people who like olives would be
$$
0.3 \times \text{Proportion of those <21} + 0.7 \times \text{Proportion of those 21+}
$$
This technique is called post-stratification. All we need is a reliable data source (such as a census, or the ACS in the US) that gives us the population weights. Data can be re-weighted based on many different categories, not just one: for example, we could post-stratify based on age, education, state of residence, etc.
## The 'MR' bit: multilevel regression
Now imagine that instead of the survey above, we had a different survey, still with 1000 respondents, but 995 were aged less than 21 and 5 were 21+. That is, our survey respondents are even more biased. We could still post-stratify in exactly the same way as above to get a more representative estimate of liking olives. However, our estimate for those aged 21+ is based only on 5 people. We are putting a huge amount of weight on only 5 people.
Using multilevel regression as a first step before post-stratification tries to adjust for this by regressing the outcome on different variables of interest. So instead of using the proportion of people in each subgroup who like olives calculated from the survey, we would estimate this proportion based on a regression. We could include covariates like age, sex, education and income, and end up with an estimate of the proportion in each of these [age/sex/education/income] subgroups. The key is that we have another reliable data source (such as a census or survey) that allows us to get the actual population counts in order to post-stratify on.
The multilevel part refers to a set-up where information across different age groups (or education groups, or state groups, etc) is 'pooled' such that the responses in one group are partially informed by responses in other groups. The fewer observations in a particular subgroup, the more they are 'pulled' towards the mean outcome based on other subgroups. In this way, subgroups that have a small number of responses are in a sense weighted downwards in determining the overall outcome.
# Example: retaining maiden names after marriage
Here's an explicit example with the marriage name change survey.
The [marital change name survey (MCNS)](https://osf.io/uzqdn/) asks lots of interesting questions, but for starters let's just look at estimating the proportion of heterosexual women who kept their maiden name after marriage. The survey collects this information as well as other characteristics that we would expect to be associated with a woman's propensity to keep their maiden name, including age at marriage, year of marriage, education of respondent and state of residence.
The goal of our analysis is to perform two steps:
1. Do a multilevel regression relating maiden name retention to age, year of marriage, state and education. In particular, for individual $i$ let $y_i$ equal 1 if the respondent did not change their name after marriage, and 0 otherwise. The model is
$$
Pr(y_i = 1) = \text{logit}^{-1}\left( \alpha^{age}_{a[i]} + \alpha^{educ}_{e[i]} + \alpha^{state}_{s[i]} + \alpha^{dec}_{d[i]}\right)
$$
where the $\alpha$s are age group, education group, state and decade married effects and the notation $a[i]$ refers to the age group $a$ to which individual $i$ belongs to, etc. These are modeled in the form:
$$
\alpha^{age}_{a} \sim N(0, \sigma_{age}) \text{ for } a=1,2\dots A
$$
where $A$ is the total number of age groups. There are similar set ups for the other $\alpha$s.
2. Using the estimates from the regression, post-stratify based on population weights in each age, year of marriage, education and state group, derived from the American Community Survey.
## MRP in R using `brms`
Now to work through the example in `R`. A few code snippets are included in this post, but the full code file is available [here](https://github.com/MJAlexander/marriage-name-change). In order to reproduce the results, you will need to download the MNCS file from [OSF](https://osf.io/uzqdn/), and also grab the 2017 5-year ACS data from [IPUMS-USA](https://usa.ipums.org/usa/index.shtml).[^1]
[^1]: IPUMS is a wonderful resource and free once you register. From the 2017 5-year ACS sample you will need to select the following variables: AGE, SEX, STATEFIP, MARST, YRMARR, EDUC.
### Data
First, I loaded in the MNCS data and did a bit of tidying up. I made a binary outcome variable `kept_name`, which indicates whether or not the respondent kept their original name after marriage. I also created a five year age group variable, a decade married variable (1979-1988, 1989-1998, ... 2009-2018), and a three-group education variable (<BA, BA, >BA)[^2]. The resulting data looks like this:
[^2]: This is probably a bit coarse; the data are available to do a finer-grained split if desired.
```{r, echo=FALSE, warning=FALSE, message=FALSE, background=TRUE}
library(tidyverse)
library(haven)
library(brms)
library(tidybayes)
library(statebins)
d_mncs <- readRDS("d_mncs.RDS")
```
```{r}
d_mncs
```
Next, I loaded in the ACS data that I got from IPUMS-USA. I extracted information on sex, age, marital status, year married, state, and education. I then restricted the data to just be ever-married women, and calculated new age, decade married and education variables to be consistent with those in the MNCS data. I then summed up to get the population counts in each age, education, decade married and state group. The data look like this:
```{r, echo=FALSE, warning=FALSE, message=FALSE}
cell_counts <- readRDS("cell_counts.RDS")
```
```{r}
cell_counts
```
These counts can be used to get proportions by group, which are in turn used in the post-stratification step. For example, to get the proportions in each age group:
```{r}
age_prop <- cell_counts %>%
group_by(age_group) %>%
mutate(prop = n/sum(n)) %>%
ungroup()
age_prop
```
### Model
Now we use the MNCS data to model the association between keeping name and age, education, state and decade married. I'm using the `brms` package, which is a wrapper to easily run models in Stan. The model is estimated in a Bayesian set up, which essentially means we put priors on the $\sigma$ terms in the model above.[^3] You could also run this model in a maximum likelihood setting using `glmer`.
[^3]: I just used the default priors in `brms`, which are half student's t distributions, see here for more info: https://cran.r-project.org/web/packages/brms/brms.pdf
```{r, eval=FALSE}
mod <- brm(kept_name ~ (1|age_group) + (1|educ_group) + (1|state_name) + (1|decade_married), data = d_mncs, family=bernoulli())
```
### Results
Now we can use the results of the regression to predict the outcome (whether or not a woman retained her name after marriage) for each of the age/education/state/decade married groups. We can make this prediction many, many times and then look at the resulting distribution to get the mean and 95% prediction intervals for whichever group of interest. For example, to get the estimated proportions and associated 95% PIs by age group:
```{r, eval=FALSE}
res_age <- mod %>%
add_predicted_draws(newdata=age_prop %>%
filter(age_group>20,
age_group<80,
decade_married>1969),
allow_new_levels=TRUE) %>%
rename(kept_name_predict = .prediction) %>%
mutate(kept_name_predict_prop = kept_name_predict*prop) %>%
group_by(age_group, .draw) %>%
summarise(kept_name_predict = sum(kept_name_predict_prop)) %>%
group_by(age_group) %>%
summarise(mean = mean(kept_name_predict),
lower = quantile(kept_name_predict, 0.025),
upper = quantile(kept_name_predict, 0.975))
```
Let's plot these and include the raw MNCS proportions for comparison:
```{r, eval=FALSE}
res_age %>%
ggplot(aes(y = mean, x = forcats::fct_inorder(age_group), color = "MRP estimate")) +
geom_point() +
geom_errorbar(aes(ymin = lower, ymax = upper), width = 0) +
ylab("proportion keeping name") +
xlab("age in 2019") +
geom_point(data = d_mncs %>%
group_by(age_group, kept_name) %>%
summarise(n = n()) %>%
group_by(age_group) %>%
mutate(prop = n/sum(n)) %>%
filter(kept_name==1, age_group<80, age_group>20),
aes(age_group, prop, color = "MNCS raw data")) +
scale_color_manual(name = "", values = c("MRP estimate" = "black", "MNCS raw data" = "red")) +
theme_bw(base_size = 14) +
ggtitle("Proportion of women keeping name after marriage")
```
<img src="/img/marriage_plots/age_plot.png">
The result is pretty interesting. Firstly, the MRP estimates are much lower than the raw -- this is likely due to the fact that the survey has an over-sample of highly educated women, who are more likely to keep their name.[^4] There is some evidence of an upside-down U shape over age, which is consistent with past observations that there was a [peak in name retention in the 80s and 90s](https://www.nytimes.com/2015/06/28/upshot/maiden-names-on-the-rise-again.html).
We can calculate the results by other groups. Here, you can see the increase in name retention with education, with a particularly high estimate for those with postgraduate education:
<img src="/img/marriage_plots/educ_plot.png">
And here it is by decade; some (weak) evidence to suggest maybe an increase in name retention in the most recent decade, which would be consistent with a [New York Times](https://www.nytimes.com/2015/06/28/upshot/maiden-names-on-the-rise-again.html) piece published a few years back.
<img src="/img/marriage_plots/dec_plot.png">
Finally, here are the results by state. Utah and New York stand out as particularly low and high, respectively. Note that these proportions are not standardized with respect to age or education.
<img src="/img/marriage_plots/state_plot.png">
[^4]: FWIW, I changed my name. The Tasmania effect outweighs any education effect, it seems.
# Summary
We often have to deal with data that, while containing interesting and useful information, are not representative of the broader population that we're interested in. The MNCS contains a wealth of information on name changes that occur around marriage, and the reasons for doing so. This information that is important to study social and demographic change, but not readily available in official data sources. However, raw estimates from this survey are most probably biased.
In this post I highlighted how MRP can be used to try and adjust for these biases. MRP is probably most commonly used in political analysis to reweight polling data,[^5] but it is a useful technique for many different survey responses. Many modeling extensions are possible. For example, the multilevel regression need not be limited to just using random effects, as was used here, and other model set ups could be investigated.[^6] MRP is a relatively easy and quick way of trying to get more representative estimates out of non-representative data, while giving you a sense of the uncertainty around the estimates (unlike traditional post-stratification). The example in this post serves as an introduction to both MRP and also the MNCS survey -- there is so much interesting data in there, and it's public![^7]
[^5]: Shout-out to [Petit Poll](https://www.petitpoll.com/)!
[^6]: Look out for the work of [<NAME>](https://arxiv.org/abs/1906.11323) et al. looking into the impact of different MRP set ups, particularly for age effects.
[^7]: If you're interested in reproducible research Phil and I are giving talks at the Rostock [Open Science Workshop](https://www.demogr.mpg.de/en/news_press/news/news/free_access_to_demographic_research_6289.htm) which is being held at the Max Planck Institute for Demographic Research (MPIDR) on October 10th and 11th, 2019.
<file_sep>/content/posts/2017-10-31-smoothing.Rmd
---
title: "Comparing methods for smoothing temporal demographic data"
author: "<NAME>"
date: "2017-10-31"
output: html_document
---
At the International Population Conference of the International Union for the Scientific Study of Population (IUSSP) I will present work on comparing different methods for smoothing demographic data. This post briefly outlines the motivation for the project and describes the R package `distortr` which accompanies the project.
## Motivation
An important part of demographic research is the ability to estimate and project time series of demographic and health indicators. However, it is often the case that populations that have the poorest outcomes also have poor-quality data. In these cases, the underlying trends may be unclear due to missing data or overly messy data.
In such situations, demographers often employ statistical models to help estimate and understand underlying trends. Often, these statistical models have the general form:
$$
\theta_t = f(X_t) + Z_t + \varepsilon_t
$$
where
- $\theta_t$ is the outcome of interest (mortality rate, fertility rate, etc)
- $f(X_t)$ is a regression framework, a function of covariates $X_t$
- $Z_t$ are temporal distortions, which capture data-driven non-linear trends over time, not otherwise captured in $f(X_t)$
- $\varepsilon_t$ is an error term.
While the inclusion of covariates in the regression framework is often well justified, the choice for modeling the distortions $Z_t$ is often more arbitrary. However, models for $Z_t$ are important: they allow for data-driven trends that may not be captured by simple regression models; they smooth distortions, accounting for error in data observations; they incorporate uncertainty in the underlying processes; and allow for a temporal mechanism to be projected into the future. Different model choice can sometimes lead to vastly different estimates.
This project aims to compare three main families of temporal models:
- ARMA models
- Gaussian Process regression
- Penalized splines regression
The aim is to compare the three methods theoretically and see how differences manifest into differences in estimates for different data scenarios.
The paper presented at IUSSP is available [here](https://www.monicaalexander.com/pdf/temporal_smoothing.pdf), and the slides are [here](https://github.com/MJAlexander/distortr/blob/master/IUSSP_011117.pdf).
## The `distortr` package
As part of this project, I am developing an R package to aid in comparing and fitting different models for estimation of demographic time series. The `distortr` package is available on [GitHub](https://github.com/MJAlexander/distortr).
The package consists of two main parts:
### 1. Simulate time series of distortions, and fit and validate models
This part of the package contains tools to investigate how different models perform in different simulation settings and how much it matters if the 'wrong' model is chosen.
Simulated time series of data can be created from any of the following processes:
- AR(1)
- ARMA(1,1)
- P-splines (first or second order penalization)
- Gaussian Process (squared exponential or Matern function)
The various parameters associated with each function can be specified. The user can also specify how much of the time series is missing, and the sampling error around data. The sample autocorrelation function of the time series can also be plotted.
In terms of model fitting, any of the above models can be fit to simulated data. Projections of time series can also easily be obtained. Estimates and uncertainty around estimates can be outputted and plotted.
### 2. Fit Bayesian hierarchical models to datasets with observations from multiple areas
Given data are often sparse or unreliable, especially in the case of developing countries, models that estimate demographic indicators for multiple areas/countries are often hierarchical, incorporating pooling of information across geographies. This part of the package has the infrastructure to fit Bayesian hierarchical models using one of the temporal smoothing methods. The user can specify whether or not to include a linear trend, and the type of temporal smoother to fit to the data.
Datasets with observations from multiple countries/areas can be used, with the following columns required:
- country/area name or code (e.g. country ISO code)
- value of observation
- year of observation
- sampling error of observation
- data source (e.g. survey, administrative)
In addition, a region column may also be included (e.g. World Bank region). By default the built-in models include a region hierarchy (i.e. a country within a region within the world). However, models can also be run without the region level.
For an example using real data, refer to the file [real_data_anc4_example.R](https://github.com/MJAlexander/distortr/blob/master/real_data_anc4_example.R).
## Summary
One of the aims of this project was to provide the tools to increase transparency of model choice and to help demographers and policymakers understand differences in models and sensitivities of estimates to model choice. The `distortr` package provides some infrastructure to explore and fit different methods. It is a work in progress and any feedback is much appreciated.
<file_sep>/content/posts/2018-23-05-demog_phd.Rmd
---
title: "Thoughts after finishing a Demography PhD"
author: "<NAME>"
date: "2018-06-04"
output: html_document
---
PhDs are hard. They are incredibly fulfilling, but mentally challenging and emotionally draining. You meet some amazing people, but also have to deal with some difficult people and difficult situations. During my time as a PhD student, a lot of things went better than I imagined, but I also made a fair few mistakes.
The following are a few thoughts after my experience. They are based on being involved in the demographic research field --- a relatively small and supportive academic community --- but the comments are pretty general. I'm writing this not so much to offer advice, but more in the hope that others read it and see similarities with their own experience.
## __Good mentors make a huge difference__
<center>
```{r echo=FALSE}
blogdown::shortcode('tweet', '1002535988248416256')
```
</center>
Do not underestimate the effect of mentorship on your PhD experience: perhaps more than anyone, mentors influence your learning trajectory, research output and self confidence.
Mentors need not be constrained to those on your formal advisory panel. In my own experience, I had a great panel, but the most invaluable mentorship came from people who were not formally associated with my committee or university.
Find mentors who you feel comfortable around: there is huge value in being able to email or talk to someone about your research without being worried about making mistakes or saying something stupid. Good mentors listen, know about your research, introduce you to people, and think of you when they see opportunities. They do exist :)
## __The peer review process can be LONG__
<center>
```{r echo=FALSE}
blogdown::shortcode('tweet', '520318869819252736')
```
</center>
It's well known that the peer review process can take a long time. Journal articles can take 6-12 months from the time of submission to publication. In hindsight, I didn't really think about this in terms of what it meant for my own timeline.
Having R&Rs or publications can be very valuable when you go on the job market. If you want to be at this stage, you need to think about submitting a year before you go on the market, i.e. two years before you finish your PhD. This is a huge lead time.
## __Doing a few extra projects is good, but don't do too many__
<center>
<img src="/img/distraction.jpg", width = 500>
</center>
There will probably be opportunities to be involved in side projects in addition to your dissertation. Side projects are a great way of learning new skills, collaborating with new researchers, and getting a little bit of extra income. However, it's easy for side projects to end up taking most of your time: deadlines are often more imminent, which means it's easy to put off the dissertation work for another day. Try not to fall into this trap.
## __Submit and go to conferences__
<center>
```{r echo=FALSE}
blogdown::shortcode('tweet', '766336056539029504')
```
</center>
Conferences are a great way of getting your work out there. If you're like me, they are also a great way of forcing yourself to have a deadline to get a working paper finished. Conferences are also a good opportunity to try and meet other researchers in your field. Introduce yourself to people who you might be interested in working with, so they can put a face to the name in future.
## __Write a little bit everyday__
<center>
```{r echo=FALSE}
blogdown::shortcode('tweet', '996526193510899712')
```
</center>
Demographers often like to play with data and graph things instead of writing. Trying to write a little bit most days helps immensely later on. Sometimes Past Monica was surprisingly clever, sometimes Past Monica was talking rubbish, but Present Monica was generally glad Past Monica had put some thoughts to paper.
## __Try not to compare yourself to others too much__
<center>
```{r echo=FALSE}
blogdown::shortcode('tweet', '999307291873574913')
```
</center>
It's hard to not suffer from imposter syndrome. It's hard to not compare yourself to others and their achievements. It's hard not worry about whether you're doing the right topic, selling your work enough, publishing in the right places. And you will likely come across really competitive people that want to put you down to make themselves feel better.
But in the end, it's important to focus on yourself: define your own research interests, know what your goals are and work to achieve them. Back yourself, and be proud of your work. And don't worry about the passive aggressors: surround yourself with fun, supportive and interesting people.
## __It's okay to feel overwhelmed__
<center>
```{r echo=FALSE}
blogdown::shortcode('tweet', '1002242560633573377')
```
</center>
Most people feel overwhelmed at some point, and it's okay. It's not a personal failing. Sometimes, it's part of the learning process. You're doing something you've never done before, at the limit of your knowledge, and there's no guarantee it will work (and it often doesn't). That said, [many graduate students suffer from mental health issues](https://www.nature.com/articles/nbt.4089) and it's important to surround yourself with supportive people and seek help when you need it.
## __Final thoughts __
### Good research is important, but so is working hard and being nice to people.
In the end, PhDs (and academia) are similar to any other job. Being successful is not just a function of how good your topic is. You have to put in the hours. You also have to learn to deal with people you disagree with in a professional manner. Be supportive of your peers and promote other people's work, not just your own. This helps to build a productive and supportive network for the future.
Around six years ago, [Rohan](https://www.rohanalexander.com/) convinced me to take the GRE and apply for some PhD programs. "If you don't try, you'll never know, and then you'll always wonder if you could have." This was right, of course. One year later we were on a plane, moving from Australia to the US.
I graduated about three weeks ago and it still hasn't really sunk in. I feel very lucky to have had this opportunity. <file_sep>/content/lab.Rmd
---
title: "Bayesian Demography Lab"
---
<center>{width="30%"}</center>
The Bayesian Demography Lab brings together researchers from fileds such as demography, statistics, sociology and public health to work on projects related to statistical demography and the study of demographic inequalities.
# Current researchers
### Postdoctoral Fellows
- [<NAME>](https://www.benjaminschluter.com/) (Statistics)
### PhD Students
- [<NAME>](https://www.statistics.utoronto.ca/people/directories/graduate-students/michael-chong) (Statistics)
- [<NAME>](https://www.demogr.mpg.de/en/about_us_6113/staff_directory_1899/esther_dorothea_denecke_4094) (Demography, Max Planck Institute for Demographic Research)
- [<NAME>](https://www.statistics.utoronto.ca/people/directories/graduate-students/michael-jongho-moon) (Statistics)
- [<NAME>](https://www.utm.utoronto.ca/geography/people/amanda-norton) (Geography)
- [<NAME>](https://scholar.google.com/citations?user=SsX55_MAAAAJ&hl=en) (Sociology)
- [<NAME>](https://www.statistics.utoronto.ca/people/directories/graduate-students/marija-pejcinovska) (Statistics)
- [<NAME>](https://www.statistics.utoronto.ca/people/directories/graduate-students/emily-somerset)(Statistics)
### Masters Students
- [<NAME>](https://github.com/abraham-mv) (Statistics)
### Visiting Students
- [<NAME>](https://aridecterfrain.com/) (Public Policy, Cornell University)
# Alumni
- [<NAME>](https://ameerd.github.io/) MA in Statistics (now PhD student in Biostatistics at University of Washington).
- [<NAME>](https://ca.linkedin.com/in/lindsaykatz16), MA in Statistics (now Research Analyst, Investigative Journalism Foundation)
- [<NAME>](http://cmajopen.ca/content/7/4/E665.short?rss=1), BSc, Statistics and Public Health (now PhD student in environmental health at Columbia University).
- [<NAME>](https://www.jessieyeung.ca/), MA in Statistics (now Research Analyst at StatCan and Sessional Lecturer, University of Toronto)
<!-- # Main collaborators -->
<!-- - [<NAME>](https://rohanalexander.com/), Information and Statistics, University of Toronto -->
<!-- - [<NAME>](https://leontinealkema.github.io/alkema_lab/), Biostatistics, UMass Amherst -->
<!-- - [<NAME>](https://www.alisongemmill.com/), Population, Family and Reproductive Health, Johns Hopkins University -->
<!-- - [<NAME>](https://www.site.demog.berkeley.edu/josh-goldstein), Demography, UC Berkeley -->
<!-- - [<NAME>](http://www.robertempickett.com/), Demography and Sociology, NYU -->
<!-- - [<NAME>](https://leslieroot.net/about/), Demography, University of Colorado, Boulder -->
<!-- - [<NAME>](https://en.wikipedia.org/wiki/Christopher_Wildeman), Sociology, Duke University -->
<!-- - [<NAME>](https://www.demogr.mpg.de/en/about_us_6113/staff_directory_1899/emilio_zagheni_2243), Demography, Max Planck Institute for Demographic Research -->
<file_sep>/content/posts/2016-02-05-nba.Rmd
---
title: "The Cost of NBA Games"
author: "<NAME>"
date: "2016-02-05"
runtime: shiny
output:
html_document:
theme: spacelab
---
I moved to the Bay Area almost three years ago, just in time to see the Golden State Warriors start to get pretty good. And then they got [really, really, good](https://www.youtube.com/watch?v=UdvA9w3Tmoc). Being the serious, hardworking PhD student that I am, following the Warriors became a hobby. Turns out that this hobby, [while healthier than drugs](http://www.cnn.com/2012/04/13/health/side-effects-sports-fan/), may not be any cheaper.
I grabbed all data on resale tickets from [StubHub](https://www.stubhub.com/) for all remaining games of the 2015-16 season. As at 1 Feb, there were around 264,200 tickets for sale on StubHub. Note that these do not represent all tickets available, but the large sample size means that the prices are fairly representative of what you could expect to pay.
For those who don't follow basketball: The NBA is made up of 30 teams, all of whom play each other at some point during the 82-game season. The teams are roughly geographically divided into either the Eastern Conference or the Western Conference. The Golden State Warriors are the number one ranked team in the Western Conference and won the Grand Final last season. Their star player is <NAME>, who has revolutionized basketball in the past few years with the [efficacy of his 3 point throws](http://basketball-players.pointafter.com/stories/10645/stephen-curry-three-point-shooting). The Warriors are followed by the San Antonio Spurs, and the Oklahoma City Thunder. The number one team in the Eastern Conference is the Cleveland Cavaliers, whose star player is <NAME>. They are followed by the Toronto Raptors and the Boston Celtics.
###Home Games
The plot below shows median ticket price for home games versus current overall standing of the team. Unsurprisingly, going to Warriors home games is generally much more expensive than for any other team. At 285 dollars, the median ticket price for remaining games at Oracle Arena is around \$100 more than the next closest team, the Spurs.
The median home game ticket price generally decreases as you go down the current standings. The most notable exception is the LA Lakers, where you can pay \$280 to [probably see them lose](http://bleacherreport.com/articles/2613737-la-lakers-have-somehow-surpassed-philadelphia-76ers-as-nbas-worst). But then, how long until we see another Kobe?
New York Knicks games are also more expensive than expected given their overall ranking, but is probably due to a Madison Square Garden premium and an income effect of living in New York (this income effect doesn't stretch to Brooklyn). Another income effect -- in the opposite direction -- may be the Detroit Pistons, who, despite winning more than half their games and being ranked in the top half of teams, have the cheapest tickets available.
Median ticket prices generally decrease with team rankings, but this observation really only holds for the top ten-ranked teams. After that, apart Lakers and the Knicks, there is not much difference between median home game prices. Maybe the [treadmill of mediocrity](http://espn.go.com/blog/truehoop/post/_/id/25914/mark-cuban-hopes-to-lose-and-lose-badly-someday) starts turning. You could be paying the same amount of money to see, for example, the Pacers or the Suns, even though the former have won twice as many games.
<center> <h4>Median ticket price for remaining 15/16 home games</h4> </center>
```{r, results = "asis", cache=F, comment=NA, echo=F, message=F}
library(rCharts)
#library(knitr)
dsum.home <- read.csv("dsum.home.csv")
cols <- c("#006BB6", "#552582", "#000000", "#007DC3", "#F58426", "#860038", "#006BB6",
"#F9A01B", "#CE1141", "#C4CED3", "#00A94F", "#CE1141", "#4FA8FF", "#724C9F",
"#CE1142", "#E03A3E", "#F0163A", "#000000", "#23375B", "#008348", "#20385B",
"#1D1160", "#E56020", "#FFC633", "#002566", "#00471B", "#002B5C", "#B4975A", "#006BB6", "#001F70" )
standPlot <- nPlot(
med.price ~ standing,
data = dsum.home,
group = "team",
type = "scatterChart", showLegend=F)
# Add axis labels and format the tooltip
standPlot$yAxis(axisLabel = "Ticket price, home games ($)", width = 62, tickValues = "#! function (x) {
tickvalues = [25, 75, 125, 175, 225, 275, 325, 375];
return tickvalues;
} !#")
standPlot$xAxis(axisLabel = "Current Team Standing",
tickValues = "#! function (x) {
tickvalues = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30];
return tickvalues;
} !#")
standPlot$chart(color = cols, tooltipContent = "#! function(key, x, y){
return '<h3>' + key + '</h3>' +
'<p>' + 'Standing: '+ x + ' , ' + 'Price: $'+ y + '</p>'
} !#")
standPlot$chart(showLegend=F, sizeRange = c(250,250), forceY = c(25, 375), forceX = c(0, 30))
standPlot$setTemplate(
afterScript = "<style>
.tick line {
opacity: 0;
}
</style>")
standPlot$show('iframesrc',cdn=TRUE)
```
### Everyone wants to see Curry (+ LeBron)
Oracle is notorious for its [electric atmosphere](http://abc7news.com/sports/expert-decibel-level-at-oracle-is-similar-to-jet-engine/773850/), and Warriors fans are some of the most passionate in the league, so maybe there is a price premium for the home-court advantage. The plot below shows the median ticket price for each team, with the home-game price plotted against away-game price. While the home game prices for the Warriors [are enough the make you fall over](https://www.youtube.com/watch?v=LB4rplyj3TU), the away game prices are even worse. The median price is 340 dollars for all remaining away games for the Warriors, \$55 more than their home games. Everyone wants to see [Curry score a three from their half court logo](https://www.youtube.com/watch?v=F8uoujg1XgE). The prospect of playing the Warriors must be daunting for any team, even at home. But the average price of tickets when the Warriors come to town must have the team and stadium owners rubbing their hands with joy.
For most other teams, home and away median prices are pretty close. The notable exception is the Cleveland Cavaliers, where the away game median price more than twice the home game price. This could be explained by the LeBron Effect: the King's Lands reach far and wide. However, the Cleveland locals aren't so excited. The number of times the Cavs have lost a championship is too high. They don't want to pay too much, only to get their hearts broken again.
The three dots to the far right of the chart show that the Warriors, Lakers and Cavs fetch far more in away games than any other team. On the other hand, the San Antonio Spurs, despite being the second-best team in the league, having an All-Star starter, a record home-game start to the season and playing to sellout crowds at home, fail to instill any excitement in non-San Antonians. After all, <NAME> only dunks when necessary.
<center> <h4>Median ticket price, home games versus away games</h4> </center>
```{r, results = "asis", cache=F, comment=NA, echo=F, message=F}
library(rCharts)
dsum.home <- read.csv("dsum.home.csv")
cols <- c("#006BB6", "#552582", "#000000", "#007DC3", "#F58426", "#860038", "#006BB6",
"#F9A01B", "#CE1141", "#C4CED3", "#00A94F", "#CE1141", "#4FA8FF", "#724C9F",
"#CE1142", "#E03A3E", "#F0163A", "#000000", "#23375B", "#008348", "#20385B",
"#1D1160", "#E56020", "#FFC633", "#002566", "#00471B", "#002B5C", "#B4975A", "#006BB6", "#001F70" )
pricePlot <- nPlot(
med.price ~ away.med.price,
data = dsum.home,
group = "team",
type = "scatterChart", showLegend=F)
# Add axis labels and format the tooltip
pricePlot$yAxis(axisLabel = "Ticket price, home games ($)", width = 62, tickValues = "#! function (x) {
tickvalues = [25, 75, 125, 175, 225, 275, 325, 375];
return tickvalues;
} !#")
pricePlot$xAxis(axisLabel = "Ticket price, away games ($)",
tickValues = "#! function (x) {
tickvalues = [25, 75, 125, 175, 225, 275, 325, 375];
return tickvalues;
} !#")
pricePlot$chart(color = cols, tooltipContent = "#! function(key, x, y){
return '<h3>' + key + '</h3>' +
'<p>' + 'Away: $'+ x + ' , ' + 'Home: $'+ y + '</p>'
} !#")
pricePlot$chart(showLegend=F, sizeRange = c(250,250), forceY = c(25, 375), forceX = c(25, 375))
pricePlot$setTemplate(
afterScript = "<style>
.tick line {
opacity: 0;
}
</style>")
#pricePlot$set(width = 600, height = 600)
pricePlot$show('iframesrc',cdn=TRUE)
```
### You pay for what you get
The plot below shows median ticket price for all remaining regular games in the 15/16 season, plotted against the average standing of the two teams playing. For example, if the game is between the Warriors and the Spurs, the average rating is (1+2)/2 = 1.5. You can select to see prices involving different games using the drop downs on the left; selections show up in red.
In general, you pay for what you get: the higher the combined ranking of the two teams playing, the more expensive the tickets. Lakers games buck this trend. Note that for visibility I left the most expensive game off this chart: Kobe's final game at the Staples Center on 13 April has a median ticket price of [around \$1650](https://www.stubhub.com/los-angeles-lakers-tickets-los-angeles-lakers-los-angeles-staples-center-4-13-2016/event/9370774/)!
Despite the high price of Warrior away-games in general, it could still be cheaper to [fly to Utah](https://www.kayak.com/flights/SFO-SLC/2016-03-30/2016-03-31) in late March to see the Jazz game, than to see any remaining home games. The most expensive games are between the Warriors and Spurs or OKC, the two teams who are most likely to threaten the Warriors chances of breaking the [Bull's 72-10 record](http://www.nba.com/history/season/19951996.html). No matter what happens, <NAME> still may be the [luckiest man in NBA history](http://www.huffingtonpost.com/2015/06/17/steve-kerr-warriors-coach_n_7603384.html).
<center> <h4>Median ticket price, all remaining NBA games</h4> </center>
```{r, echo=FALSE, cache = FALSE, fig.width=12}
knitr::include_app("http://shiny.demog.berkeley.edu/monicah/nba_app/", height = "600px")
```
#### Notes:
These charts were made using `rCharts` (thanks <NAME> for the awesome package). Code for scraping StubHub and analysis can be found [here](https://github.com/MJAlexander/nba).
<file_sep>/content/teaching.md
+++
title = "Teaching"
slug = "teaching"
+++
# University of Toronto
- **Applied Statistics II** (STA2201H, graduate level). Winter 2020-2023. Materials for 2023 are [here](https://github.com/MJAlexander/applied-stats-2023).
- **Intermediate Quantitative Methods** (SOC252H1S, undergraduate level). Fall 2020, Winter 2023.
- **Stats for Sociologists** (SOC6302H, graduate level). Winter 2023.
- **Intermediate Data Analysis** (SOC6707H, graduate level). Winter 2021, 2022.
- **Demographic Methods** (STA4525H). Winter 2019, Summer 2020. All materials for the course are [here](https://github.com/MJAlexander/demographic-methods).
- **Sociology R Bootcamp, 7 September 2022**
+ Slides: [Module 1](/pdf/1_intro.pdf); [Module 2](/pdf/2_tidy.pdf); [Module 3](/pdf/3_ggplot.pdf)
+ [Rstudio cloud link](https://rstudio.cloud/content/4459414)
+ Code from the course is [here](/code.R)
# Other
- I ran a workshop on 'Non-traditional data sources in demography' at Cedeplar in April 2022. All the materials and code are here: https://mjalexander.github.io/demopop-workshop/
- I ran a workshop on 'Social Media for Population Research' for [CAnD3](https://www.mcgill.ca/cand3/) Fellows in April 2021. All the materials and code are here: https://mjalexander.github.io/social_media_workshop/<file_sep>/content/professional.md
+++
# An example of using the custom widget to create your own homepage section.
# To create more sections, duplicate this file and edit the values below as desired.
date = "2016-04-20T00:00:00"
draft = false
title = "Professional Experience"
subtitle = ""
widget = "custom"
# Order that this section will appear in.
weight = 6
+++
## University of Massachusetts, Amherst
**Graduate Student Researcher**, January 2017 -- June 2018
## World Health Organization
**Consultant**, September 2016 -- June 2017
## Data Science for Social Good
**Fellow**, May 2016 -- September 2016
## Human Mortality Database
**Graduate Student Researcher**, January 2015 -- May 2016
## UNICEF Technical Advisory Group
**Consultant**, March 2014 -- December 2015
## The Centre for Aboriginal Economic Policy Research
**Research Officer**, April 2012 -- December 2014
## Reserve Bank of Australia
**Analyst/Senior Analyst**, February 2010 -- June 2013<file_sep>/content/posts/2019-08-09-australian_politicians.Rmd
---
title: "Exploring the AustralianPoliticans R Package"
author: "<NAME>"
date: "2019-09-08"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Australia federated in 1901.[^1] [Rohan Alexander](https://rohanalexander.com/) is unusually interested in the history of Australian politicians, and he decided to convert some of his knowledge into an R package, the appropriately named, [`AustralianPoliticians`](https://github.com/RohanAlexander/AustralianPoliticians). In brief, the package has datasets that contain information on every person who has ever sat in the House of Representatives (MPs) or the Senate since 1901. This post is a shameless plug for that package,[^2] and shows you how to read in and play around with the data.
[^1]: "Our nation was created with a vote, not a war": h/t to [this](https://www.youtube.com/watch?v=wkGEMYSgIo0&feature=youtu.be) ad for teaching me the name of Australia's first Prime Minister.
[^2]: Because why else is one in a relationship if not to have someone advertise your R package.
# Install the package and load in the data
First, let's load in some packages we need and install the `AustralianPoliticians` package. It's not on CRAN so you'll need to install it from GitHub.
```{r, message=F, warning=F}
library(tidyverse)
library(lubridate)
devtools::install_github("RohanAlexander/AustralianPoliticians")
```
The `AustralianPoliticians` package has a series of datasets built into it. Let's read in the main dataset `all` and the MP and Senate datasets:
```{r}
all <- AustralianPoliticians::all %>% as_tibble()
by_division_mps <- AustralianPoliticians::by_division_mps %>% as_tibble()
by_state_senators <- AustralianPoliticians::by_state_senators %>% as_tibble()
```
The [README](https://github.com/RohanAlexander/AustralianPoliticians) on GitHub has good explanations of what each dataset contains. Briefly, the `all` dataset contains one row for each politician, and has information on their name, gender, date of birth, date of death, Wikipedia page etc. The `by_division_mps` and `by_state_senators` datasets have info on which electoral divisions / states each politician held. Note, these can change over time, so there can be more than one row/observation per politician. There's dates the positions were held, the reason why the position ended (defeated, resigned, died etc), and other interesting info. The tables are easily joined the the `all` dataset based on the `uniqueID` column. There are other datasets available based on party and whether or not the person was a Prime Minister.
## Deaths of Australian politicians
Because I'm a demographer, and a fun sort of person, I wanted to look at the mortality of politicians. The following bit of code calculates the age of death for all those who have died, as well as the year and age they were first elected:
```{r, warning=F, message=F}
deaths <- all %>%
rowwise() %>%
# some people only have a birth year available, let's arbitrarily say they were born in the middle of the year
mutate(birth_final = as_date(ifelse(is.na(birthDate),
ymd(paste(birthYear, 06, 30, sep="-")),
birthDate))) %>%
select(uniqueID, displayName, deathDate, birth_final) %>%
# calculate age at death
mutate(age_at_death = interval(birth_final, deathDate)/years(1)) %>%
# filter(!is.na(age_at_death)) %>%
# join on MP and senate info
left_join(by_state_senators) %>%
left_join(by_division_mps) %>%
group_by(uniqueID) %>%
# just keep the initial election
filter(row_number()==1) %>%
mutate(year_first_active = ifelse(is.na(senatorsFrom), year(mpsFrom), year(senatorsFrom)),
age_active = ifelse(is.na(senatorsFrom),
interval(birth_final, mpsFrom)/years(1),
interval(birth_final, senatorsFrom)/years(1)),
birth_year = year(birth_final)) %>%
ungroup()
deaths
```
So what proportion of all politicians have died? Almost 56%:
```{r}
sum(!is.na(deaths$age_at_death))/nrow(deaths)
```
Let's look at the proportion of politicians who have died by birth year:
```{r, warning=F}
deaths %>%
group_by(birth_year) %>%
summarise(proportion = sum(!is.na(age_at_death))/n()) %>%
ggplot(aes(birth_year, proportion)) +
geom_point() +
theme_bw(base_size = 12) +
ggtitle("Proportion of politicians who are dead by birth year")
```
So all politicians born before 1916 are now dead. In contrast, no politicans born after 1963 has died so far. The oldest politician is <NAME>, who is almost 102:
```{r, message=F}
deaths %>%
filter(is.na(age_at_death)) %>%
arrange(birth_year) %>%
filter(row_number()==1) %>%
mutate(age = interval(birth_final, today())/years(1)) %>%
select(displayName, age)
```
### Average age at death by cohort
Let's look at the average age of death of these politicians and compare it to the national average. I got the national data from the [Australian Institute of Health and Welfare's website](https://www.aihw.gov.au/reports/life-expectancy-death/deaths-in-australia/data). The indicator is $e45+45$ for males, which is the expected age at death for those who lived at least until age 45. I didn't want to compare to the usual life expectancy at birth, because we know that politicians already have to survive long enough to become politicians. Looking at the average age that people entered parliament, 45 is not too far off:
```{r}
deaths %>%
summarise(mean(age_active, na.rm = T))
```
I use males because there's been hardly any women in parliament (:( ). Let's read in the national data and calculate a year mid-point:
```{r}
e45 <- read_csv("e45.csv")
e45 <- e45 %>%
mutate(start_year = as.numeric(str_sub(Year, 1,4)),
end_year = as.numeric(str_sub(Year, 6,9)),
year = floor((start_year+end_year)/2))
e45
```
Now graph the average age at death for politicians and the national data that we have. The size of the dot represents the number of people who died from that cohort.
```{r, message=F, warning=F}
deaths %>%
full_join(e45 %>% rename(birth_year = year)) %>%
filter(age_at_death>0) %>%
group_by(birth_year, e45) %>%
summarise(mean_age = mean(age_at_death),
deaths = n()) %>%
ggplot(aes(birth_year, mean_age)) + geom_point(aes(size = deaths)) +
geom_point(aes(birth_year, e45, color = 'National average'), size = 4, pch = 10) +
scale_color_manual(name = "", values = c("National average" = "red")) +
scale_size_continuous(name = "number of deaths") +
ylab("average age at death (years)") + xlab("birth year") +
ggtitle("Average age at death of Australian politicians by birth year") +
theme_bw(base_size = 12)
```
So the average age of death for politicians is generally well above the national average. There's a steep drop in the later years, from about 1935 onwards, as these cohorts are still fairly young. The youngest ten are listed below, along with their reason for leaving parliament:
```{r, message=F}
deaths %>%
filter(!is.na(age_at_death), birth_year>1935) %>%
arrange(age_at_death) %>%
mutate(reason_leaving = ifelse(is.na(senatorsEndReason), mpsEndReason, senatorsEndReason)) %>%
select(displayName, birth_year, age_at_death, reason_leaving) %>%
filter(row_number() %in% 1:10)
```
## Summary
If you've ever wanted to know about Australian Politicians, this is the package for you. These data could be combined with data from other sources, for example Twitter data to study more recent politicians, Hansard data, or data from other countries for international comparisons. This is also a great dataset to study a relatively privledged group of society.<file_sep>/content/code.R
# Intro to R
# <NAME>
# load the tidyverse package
library(tidyverse)
# install.package("lubridate")
library(lubridate)
a <- 87
b <- 898
a+b
a*b # multiply
a/b # divide
2*a
8*b - a
# can't go
2b
# order of operations
(b+a)*2/b*(3*(b/(a+b)))
##########################
### Variable types
# numeric
a_number <- 997
another_number <- 987
# using is.numeric function to test whether a_number is numeric
is.numeric(a_number)
# logical
# either TRUE or FALSE
is_september <- TRUE
is_january <- FALSE
# testing:
is.logical(is_september)
is.logical(a_number)
# character (string)
department <- "Sociology"
is.character(department)
# this is case sensitive
department2 <- "sociology"
## are these two departments equal to each other?
# use ==
department == department2
# install using code
#install.packages("tidyverse")
# different types of variables --------------------------------------------
# single values
fruit <- "pear"
d <- 7
# vectors
# defined with the function c()
vector_of_numbers <- c(98,4,1,5098)
c(6, 8,4,5)
vector_of_departments <- c("sociology", "statistics")
# check: length of a vector
length(vector_of_numbers)
# tibbles (data frames)
my_data <- tibble(
student = c(10909, 298798,87876),
grade = c("A", "A+", "A")
)
# check dimensions
dim(my_data) # nrows x n cols
# functions ---------------------------------------------------------------
# mean of numbers
mean(vector_of_numbers)
median(vector_of_numbers)
min(vector_of_numbers)
# notice you can't get the mean of characters
mean(vector_of_departments)
# paste: useful for characters
my_first_name <- "Monica"
my_last_name <- "Alexander"
paste(my_first_name, my_last_name)
# read in some data -------------------------------------------------------
d <- read_csv("deaths_fatality_type.csv")
# select
death_dates <- select(d,date)
## same thing:
d |>
select(date)
# arrange
# ascending
d |>
arrange(deaths_total)
# descending
d |>
arrange(-deaths_total)
# arrange by more than one
d |>
arrange(-deaths_total, -death_covid)
# mutate
# making a new column
d2 <- d |>
mutate(is_deaths_covid_neg = death_covid < 0) # checking to see whether covid detahs column is negative
# filter
# filtering out rows based on values in a specific column
df <- d |>
filter(deaths_total>=0) # just keep positive death counts
# summarize (summarise)
# getting summaries of variables
# calculate the mean number of total deaths (not negative)
df |>
summarise(mean_deaths_per_day = mean(deaths_total))
# earliest date
# latest date
df |>
summarise(first_day = min(date),
last_day = max(date))
# group_by
# use group_by and summarize to calculate the total deaths by year
# first step: create a new column called year
df <- df |>
mutate(year = year(date))
df |>
group_by(year) |>
summarize(total_yearly_deaths = sum(deaths_total))
df |>
group_by(year) |>
summarize(average_daily_deaths = mean(deaths_total))
monthly_totals <- df |>
mutate(month = month(date)) |>
group_by(year, month) |>
summarize(total_monthly_deaths = sum(deaths_total))
# ggplot ------------------------------------------------------------------
# filtering out deaths that are abnormally large
df <- df |>
filter(deaths_total<500)
ggplot(data = df, aes(x = date, y = deaths_total)) +
geom_point(col = "skyblue2") +
labs(title = "Daily deaths due to Covid",
subtitle = "Ontario, April 2022 -- Sep 2022",
x = "Date",
y = "Daily deaths"
)
<file_sep>/README.md
# blogdown_website
Files and folders for a new personal website created using blogdown
<file_sep>/content/posts/2017-12-16-svd.Rmd
---
title: "Using SVD in demographic modeling"
author: "<NAME>"
date: "2017-12-16"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
A core objective of demographic modeling is finding empirical regularities in age patterns in fertility, mortality and migration. One method to achieve this goal is using Singular Value Decomposition (SVD) to extract characteristic age patterns in demographic indicators over time. This post describes how SVD can be used in demographic research, and in particular, mortality estimation.
## Background
The SVD of matrix $X$ is
$$
X = UDV^T
$$
The three matrices resulting from the decomposition have special properties:
- The columns of $U$ and $V$ are orthonormal, i.e. they are orthogonal to each other and unit vectors. These are called the left and right singular vectors, respectively.
- $D$ is a diagonal matrix with positive real entries.
In practice, the components obtained from SVD help to summarize some characteristics of the matrix that we are interested in, $X$. In particular, the first right singular vector (i.e. the first column of $V$) gives the direction of the maximum variation of the data contained in $X.$ The second right singular vector, which is orthogonal to the first, gives the direction of the second-most variation of the data, and so on. The $U$ and $D$ elements represent additional rotation and scaling transformations to get back the original data in $X$.
SVD is useful as a dimensionality reduction technique: it allows us to describe our dataset using fewer dimensions than implied by the original data. For example, often a large majority of variation in the data is captured by the direction of the first singular vector, and so even just looking at this dimension can capture key patterns in the data. SVD is closely related to Principal Components Analysis: principal components are derived by projecting data $X$ onto principal axes, which are the right singular vectors $V$.
## Use in demographic modeling
Using SVD for demographic modeling and forecasting first gained popularity after [Lee and Carter](https://www.jstor.org/stable/2290201) used the technique as a basis for forecasting US mortality rates. They modeled age-specific mortality on the log scale as
$$
\log m_x = a_x + b_x \cdot k_t
$$
where
- $a_x$ is the mean age-specific mortality schedule across all years of analysis,
- $b_x$ is the average contribution of age group $x$ to overall mortality change over the period, and
- $k_t$ is the incremental change in period $t$.
The latter two quantities are obtained via SVD of a time x age matrix of demeaned, logged mortality rates: $b_x$ is the first right singular vector, while $k_t$ is the first left singular vector multiplied the first element of $D$.
More recently, SVD has become increasingly used in demographic modeling; for example [<NAME> et al.](http://www.tandfonline.com/doi/abs/10.1080/01621459.2014.881738) used it to model and forecast cohort fertility, [<NAME>](https://arxiv.org/abs/1612.01408) to estimate age schedules of mortality with limited data, and [<NAME>, <NAME> and myself](https://link.springer.com/article/10.1007/s13524-017-0618-7) to model subnational age-specific mortality.
### Example: age-specific mortality
Imagine you have observations of age-specific mortality rates in multiple years. Create a matrix, $X$, where each row represents the age-specific mortality rates in a particular year. Modeling of mortality rates is often done on the log scale (to ensure rates are positive), so you may want to take the log of $X$. Then do a SVD on this matrix - in `R` this is as easy as `svd(x)`. The age patterns of interest are then contained in the resulting `v` matrix; so for example `svd(x)$v[,1:3]` would give you the first three age 'principal components' of your matrix.
<img src="/img/svd_plots/svd.png">
For example, the first three principal components of US male mortality by state over the years 1980-2010 are plotted below. Each component has a demographic interpretation - the first represents baseline mortality, the second represents higher-than-baseline child mortality, and the third represents higher-than-baseline adult mortality.
<img src="/img/svd_plots/3pcs_states_neg.png">
For modeling, the idea is that different linear combinations of these components allow you to flexibly represent a wide range of different mortality curves. For example, log-mortality rates could be modeled as
$$
\log m_x = \beta_1 Y_{1x} + \beta_2 Y_{2x} + \beta_3 Y_{3x}
$$
where the $Y_{.x}$'s are the principal components above and the $\beta$'s are to be estimated. The plot below shows four different mortality curves derived from the US male principal components with different coefficient settings. You can also play with different settings interactively [here](http://shiny.demog.berkeley.edu/monicah/mort/).
<img src="/img/svd_plots/coeff.png">
### Example: race-specific opioid mortality
This technique of representing and modeling underlying age patterns need not be restricted to modeling all-cause mortality. For example, SVD proves useful when looking at deaths due to opioid overdoses by race and state in the US. Even though [opioid overdoses are rapidly increasing for both the black and white population](https://www.monicaalexander.com/2017/05/02/opioid-mortality-by-race-from-divergence-to-convergence/), overdoses are still a relatively rare event, and so death rates calculated from the raw data suffer from large stochastic/random variation.
For example, the chart below shows age-specific opioid mortality rates by race for North Carolina in 2004.[^1] As you can see, for the black population there are quite a few age groups were there are zero observed deaths, so the observed mortality rate is zero. However, given what we know about how mortality evolves over age, the zero observed death rates are likely due to random variation.
[^1]: cross-promotional plug: you can play with this data yourself with the help of the [narcan](https://github.com/mkiang/narcan) `R` package, which [<NAME>](http://mathewkiang.com) and I are working on.
<img src="/img/svd_plots/NC_age.png">
Even though age patterns are noisy at the state level, we have an idea of age patterns by race in opioid mortality in the national level. So we can use these national age patterns - via information captured in a SVD - to help model underlying mortality rates at the state level.
The figure below shows the first two principal components derived using SVD from race-specific opioid mortality in the US over the years 1999-2015. The first principal component again represents a baseline mortality schedule for opioid-related deaths for each race. The second principal component represents the contribution of each age group to mortality change over time. Notice the 'double-humped' shape for the white population - this is driven by heroin deaths being concentrated at younger ages, and prescription opioid-related deaths being concentrated at older ages.
<img src="/img/svd_plots/opioid_pcs.png">
Similar to the example above, we can use these principal components as a basis of a regression framework to estimate underlying age-specific mortality rates by age. Results from such a model for North Carolina in 2004 are shown below. The dots represent mortality rates calculated from the raw data, as above. The lines and associated shaded area represent estimates of the underlying mortality rates with 95\% uncertainty intervals. These were obtained from a model that utilized information from the principal components. Instead of dealing with zero observed deaths, we now have estimates that give more plausible values for the underlying mortality rates.
<img src="/img/svd_plots/NC_agefit.png">
## Summary
SVD is a useful technique to extract the main characteristics of age patterns in demographic indictors. These structural age patterns are useful to get a better idea of underlying processes when available data are sparse or noisy. Age patterns derived from SVD can be flexibly shifted and adjusted based on available data. Built-in functions in `R` make it relatively easy to use SVD to better understand, model and project demographic indicators.
<file_sep>/content/news.md
+++
title = "News"
slug = "news"
+++
- **25 July 2023** On 28-30 September I'll be teaching a short course on ['Extracting and Analyzing Web and Social Media Data: A Short Course'](https://codehorizons.com/Seminars/extracting-and-analyzing-web-and-social-media-data/), run through Code Horizons.
- **May 2023:** Excited to serve as a member of the Technical Advisory Group to the UN Interagency Group on Child Mortality Estimation (UN IGME).
- **27 February 2023:** Awarded a [Catalyst Grant from the Data Science Institute](https://datasciences.utoronto.ca/data-sciences-institute-catalyst-grants-support-2023/) to use web data to better understand inequalities in childcare in Canada (with <NAME>).
- **19 December 2022:** Awarded a [Computational & Quantitative Social Sciences Grant from the Data Science Institute](https://datasciences.utoronto.ca/computational-and-quantitative-social-sciences-grant/) to help develop methods to estimate migration changes since the COVID-19 pandemic.
- **10 December 2022:** Will be at [IMS International Conference on Statistics and Data Science ](https://sites.google.com/view/icsds2022/home?authuser=0) presenting wok on estimating stillbirths by timing.
- **3 November 2022:** Presented 'Racial Disparities in Infant Outcomes: insights from, and for, formal demography' at the Social Demography Seminar Series at Harvard's Center for Population and Development Studies. A copy of the slides is [here](/pdf/infant_formal.pdf).
- **1 November 2022** On 23-25 February I'll be teaching a short course on ['Extracting, Manipulating and Analyzing Social Media Data'](https://codehorizons.com/Seminars/extracting-manipulating-and-analyzing-social-media-data/), run through Code Horizons.
- **12 September 2022**: New paper in [*Demography*](https://read.dukeupress.edu/demography/article/doi/10.1215/00703370-10216406/318087/A-Bayesian-Cohort-Component-Projection-Model-to) with <NAME> discussing a Bayesian cohort component projection model for use in data-sparse settings.
- **7 September 2022**: The [Formal Demography Working Group](https://formaldemography.github.io/working_group/) is back on 30 September 2022.
<file_sep>/content/posts/2017-05-02-opioid-mortality-by-race.html
---
title: "Opioid mortality by race: from divergence to convergence"
author: "<NAME>"
date: "2017-05-02"
output: html_document
---
<p>Opioid-related mortality in the United States has been rising steadily since 2000. The opioid mortality rate has more than tripled since over the fifteen year period 2000–2015, and shows no signs of declining — in fact, the rate of increase has accelerated in recent years. This is unique to opioid-related drug deaths, with the non-opioid mortality rate remaining fairly level since 2005. The so-called ‘opioid epidemic’ has gained national attention and become an important part of the <a href="https://www.vox.com/policy-and-politics/2017/3/29/15089618/trump-opioid-epidemic-executive-order">political agenda</a>.</p>
<p>While the epidemic has also gained widespread media attention, coverage tends to focus on overall trends in deaths or for the <a href="https://www.nytimes.com/2016/01/17/science/drug-overdoses-propel-rise-in-mortality-rates-of-young-whites.html">white population only</a>. In a recent paper presented at <a href="https://paa.confex.com/paa/2017/webprogrampreliminary/Paper16497.html">PAA 2017</a>, we focused on differences in opioid mortality by race, to see how trends in underlying cause of death, opioid types and age patterns differ.</p>
<div class="figure">
<img src="/img/opiod_plots/fig1_nood_v_ci.png" />
</div>
<div id="a-story-in-two-stages" class="section level2">
<h2>2000–2015: A story in two stages</h2>
<p>While mortality rates were similar for both races in 2000, the opioid mortality rate for the non-Hispanic white population is now much higher than for the non-Hispanic black population. In 2015, the white opioid mortality rate was more than two times the black opioid mortality rate. This observation is different to what we usually see — by most other measures of mortality, the black population is worse off.</p>
<p>The combination of high opioid death rates, as well as a lower overall death rate compared to the black population, means that the impact is more noticeable in the white population. Opioid drug overdoses comprise some of the ‘deaths of despair’ (i.e. deaths due to drugs, alcohol and suicide) that <a href="https://www.brookings.edu/bpea-articles/mortality-and-morbidity-in-the-21st-century/">Case and Deaton</a> attributed to causing an increase in the mortality rate in the non-Hispanic white population aged 45-54.</p>
<p>However, looking over the period 2000–2015, we see that patterns in the race-specific opioid mortality rate exhibit two distinct periods:</p>
<ul>
<li><p>From <strong>2000–2010</strong>, shows a <strong>divergence</strong> in opioid mortality, with the non-Hispanic white mortality rate steadily increasing while the non-Hispanic black mortality rate remains fairly constant.</p></li>
<li><p><strong>Since 2010</strong> the opioid mortality rate has been increasing at a similar pace for both the white and black populations. As a consequence, the relative risk of opioid mortality in the white to black populations reached a peak in 2010 at around 2.5, but has since declined.</p></li>
</ul>
<div class="figure">
<img src="/img/opiod_plots/paa_2017_fig.png" />
</div>
</div>
<div id="from-prescription-drugs-to-heroin-fentanyl-mixes" class="section level2">
<h2>From prescription drugs to heroin-fentanyl mixes</h2>
<p>Breaking down the opioid mortality rate by underlying type of opioid, it is clear that there has been a shift in the types of opioids driving the increased mortality rates. In the first period, from 2000–2010, increases, which were mostly observed in the white population, were driven by an increased mortality rate due to other natural and semi-synthetic opioids — namely oxycodone and hydrocone, sold under the brand names OxyContin and Vicodin.</p>
<p>Since 2010, however, there has been a noticeable shift in the relative importance of deaths from heroin and other synthetic opioids. This is true for both races. Other synthetic opioids largely consist of fentanyl. Pharmaceutical fentanyl is a synthetic painkiller that is 50–100 times more powerful than morphine and is used for treating severe pain. However, the presence of illicitly-made fentanyl in the form of acetyl- and furanyl-fentanyl has increased in recent years. These products are often mixed with heroin or cocaine to increase potency.</p>
<p>In 2010 OxyContin was reformulated to be less easily abused, making it harder to crush (and therefore be snorted or dissolved and injected). This reformulation may explain some of the leveling-off in the white death rate since 2010. In addition, <a href="http://www.nber.org/papers/w23031">previous research</a> has found strong evidence to suggest that much of the increase in heroin overdoses is due a substitution effect since the reformulation of OxyContin.</p>
<div class="figure">
<img src="/img/opiod_plots/fig4_t40_adjusted_race_lines_v_ci.png" />
</div>
<p>Compared to earlier years, a larger proportion of opioid deaths now involve more than one type of opioid. In 2015, the proportion of all opioid deaths that involved two or more types of opioids was more than 25% for the black population and around 22% for the white population. This was an increase from around 12% of all deaths for both races in 2010.</p>
<p>Looking specifically at heroin deaths, the proportion of deaths involving other types has increased across the board since 2010 for both races. In particular, since 2012 there has been a ten-fold increase in the proportion of heroin deaths also involving other synthetic opioids, namely fentanyl. In 2015, around 35% of all heroin deaths in the black population involved other synthetic opioids.</p>
<div class="figure">
<img src="/img/opiod_plots/fig9_t401_combos_v_ci.png" />
</div>
</div>
<div id="black-opioid-deaths-tend-to-occur-at-older-ages" class="section level2">
<h2>Black opioid deaths tend to occur at older ages</h2>
<p>Since 2000, the age distribution of opioid deaths in the white population has been shifting to younger ages, with the highest mortality rate occurring in the 30-39 age group. In contrast, the age distribution for the black population has been shifting to older ages, and the peak mortality rate occurs in the 50-59 age group. This somewhat surprising observation is true for deaths relating to all types of opioids. Focusing specifically on the heroin mortality rate, the differences in age distributions creates a mortality ‘cross-over’, where black heroin mortality rates are higher at older ages.</p>
<p><img src="/img/opiod_plots/fig5_asmr_race_all_errorbars.png" /> <img src="/img/opiod_plots/fig7_t40_heroin_ci.png" /></p>
</div>
<div id="an-issue-for-both-races" class="section level2">
<h2>An issue for both races</h2>
<p>The nature of the epidemic has changed over the past fifteen years, and had different impacts on the black and white populations. Importantly, there has been an increase in mortality due to opioids since 2010 for both races, and this trend shows no sign of slowing. A better understanding of the differences across race and how they relate to the use of other drugs, place of residence, and socioeconomic status, is necessary to improve health policy and rehabilitation programs across the country.</p>
<div id="notes" class="section level4">
<h4>Notes</h4>
<p>This post is based on a <a href="https://github.com/MJAlexander/opioid-mcd/blob/master/report/paa_2017_paper/paa.pdf">paper</a> presented in the session on Trends and Causes of Adult Mortality in the United States at <a href="https://paa.confex.com/paa/2017/webprogrampreliminary/Paper16497.html">PAA 2017</a>. It is joint work with <a href="http://www.demog.berkeley.edu/directories/profiles/barbieri.shtml"><NAME></a> and <a href="https://mathewkiang.com/"><NAME></a>. All figures were derived from multiple cause of death data available from the <a href="https://www.cdc.gov/nchs/nvss/deaths.htm">National Center for Health Statistics</a>. The code to reproduce graphs from the raw data is available <a href="https://github.com/MJAlexander/opioid-mcd">here</a>.</p>
</div>
</div>
<file_sep>/content/about.md
+++
title = "About"
slug = "about"
+++
I am an Assistant Professor in [Statistical Sciences](http://www.utstat.utoronto.ca/) and [Sociology](http://sociology.utoronto.ca/) at the University of Toronto. I received my PhD in Demography from the [University of California, Berkeley](http://demog.berkeley.edu/). My research interests include statistical demography, mortality and health inequalities, and computational social science.
I have worked on research projects with the World Health Organization, UNICEF, UNHCR, and the [Human Mortality Database](http://mortality.org/). I was a 2016 Fellow at [Data Science for Social Good](https://dssg.uchicago.edu/), and have worked at the ANU's [Centre for Aboriginal Economic Policy Research](http://caepr.anu.edu.au/).
I am passionate about increasing the representation of women in STEM and other quantitative fields. I maintain a list of [women scholars in demography](https://www.monicaalexander.com/women_scholars/). I also co-organize the [Formal Demography Working Group](https://formaldemography.github.io/working_group).
I am married to [<NAME>](https://rohanalexander.com/) who is also faculty at UofT (and not a Jamaican-American cricketer as Google suggests). Outside of work I ~~am interested in photography, cycling, and music~~ have two children, and enjoy building Lego, reading stories, and dancing to The Wiggles.
A full CV can be found [here](/pdf/cv.pdf).
<file_sep>/content/papers.md
+++
title = "Scholarly work"
slug = "papers"
+++
Notes: (*) indicates student/trainee; (+) indicates co-first authorship; (#) indicates senior authorship
# Peer-reviewed articles
1. **<NAME>.**, and <NAME>., [‘A Bayesian cohort component projection model to estimate adult populations at the subnational level in data-sparse settings’](https://read.dukeupress.edu/demography/article/59/5/1713/318087/A-Bayesian-Cohort-Component-Projection-Model-to), *Demography*, 2022: 59(5), 1713-1737.
2. <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., **<NAME>.**, and <NAME>. ‘[A framework to model global, regional, and national estimates of intimate partner violence](https://bmcmedresmethodol.biomedcentral.com/articles/10.1186/s12874-022-01634-5)’, *BMC Medical Research Methodology*, 2022: 22(1), 1-17.
3. <NAME>., **<NAME>.**, and <NAME>., [Temporal models for demographic and global health outcomes in multiple populations: Introducing a new framework to review and standardize documentation of model assumptions and facilitate model comparison](https://onlinelibrary.wiley.com/doi/10.1111/insr.12491), *International Statistical Review*, 2022: 90(3), 437-467.
4. **<NAME>.**(+) and Root, L.(+) '[Competing effects on the average age of infant death](https://read.dukeupress.edu/demography/article/doi/10.1215/00703370-9779784/294667/Competing-Effects-on-the-Average-Age-of-Infant)'. *Demography*, 2022: 59(2), 587-605.
5. <NAME>., <NAME>., **<NAME>.**, <NAME>., <NAME>. '[Racial/Ethnic Disparities in Opioid-Related Mortality in the USA, 1999–2019: the Extreme Case of Washington DC.](https://pubmed.ncbi.nlm.nih.gov/34664185/)' *Journal of Urban Health*, 2021: 98(6), 589.
6. <NAME>., <NAME>., **<NAME>.**, <NAME>., and <NAME>. ['Methods for small area population forecasts: state-of-the-art and research needs'](/pdf/prpr_small_area.pdf), *Population Research and Policy Review*, 2021: 41, 865-898.
7. <NAME>., <NAME>., <NAME>., <NAME>., **<NAME>.**, <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>. [‘Sociodemographic characteristics of missing data in digital phenotyping’](https://www.nature.com/articles/s41598-021-94516-7). *Scientific Reports*, 2021: 11(1),15408.
8. **<NAME>.**, <NAME>., and <NAME>., ['Combining social media and survey data to nowcast migrant stocks in the United States'](https://link.springer.com/article/10.1007/s11113-020-09599-3), *Population Research and Policy Review*, 2020: 41, 1-28.
9. **<NAME>.**, <NAME>., and <NAME>., ['The impact of Hurricane Maria on out-migration from Puerto Rico: Evidence from Facebook data'](/pdf/pdr.pdf), *Population and Development Review*, 2019: 45(3), 617-630.
10. <NAME>., **<NAME>.**, <NAME>., and <NAME>. '[National, regional, and global levels and trends in neonatal mortality between 1990 and 2017, with scenario-based projections to 2030: a systematic analysis by the United Nations Inter-agency Group for Child Mortality Estimation](https://www.thelancet.com/journals/langlo/article/PIIS2214-109X(19)30163-9/fulltext)', *Lancet Global Health*, 2019, 7(6): 710-720.
11. <NAME>., <NAME>., <NAME>., and **<NAME>**(#). '[Assessment of Changes in the Geographical Distribution of Opioid-Related Mortality Across the United States by Opioid Type, 1999-2016](https://jamanetwork.com/journals/jamanetworkopen/fullarticle/2725487)'. *JAMA Network Open*. 2019, 2(2):e190040.
12. <NAME>., <NAME>., and **<NAME>.**(#), '[Trends in pregnancy-associated mortality involving opioids in the United States, 2007–2016](/pdf/ajog.pdf)', *American Journal of Obstetrics and Gynecology*, 2019, 220(1): 115-116.
13. **<NAME>.**(+), <NAME>.(+), and <NAME>., '[Trends in Black and White Opioid Mortality in the United States, 1979–2015](https://journals.lww.com/epidem/Fulltext/2018/09000/Trends_in_Black_and_White_Opioid_Mortality_in_the.16.aspx)', *Epidemiology*, 2018, 29(5): 707–715.
14. **<NAME>.**, and <NAME>., '[Global Estimation of Neonatal Mortality using a Bayesian Hierarchical Splines Regression Model](https://www.demographic-research.org/volumes/vol38/15/default.htm)', *Demographic Research*, 2018, 38(15): 335–372.
15. **<NAME>.**, <NAME>., and <NAME>., '[A Flexible Bayesian Model for Estimating Subnational Mortality](https://link.springer.com/article/10.1007/s13524-017-0618-7)', *Demography*, 2017, 54(6): 2025–2041.
16. **<NAME>.**, <NAME>., and <NAME>., '[Wages, government payments and other income of Indigenous and non-Indigenous Australians](/pdf/ajle_2016.pdf)', *Australian Journal of Labour Economics*, 2016, 19(2): 53–76.
17. <NAME>., **<NAME>.**, and <NAME>., '[The Economic Impact of the Mining Boom on Indigenous and Non-Indigenous Australians](https://onlinelibrary.wiley.com/doi/full/10.1002/app5.99#:~:text=Average%20household%20incomes%20are%20higher,employment%20rate%20in%20mining%20areas.)', *Asia & the Pacific Policy Studies*, 2015, 2(3): 517–530.
18. <NAME>., **<NAME>.**, and <NAME>., '[Labour Market Outcomes for Indigenous Australians](/pdf/elrr.pdf)', *The Economic and Labour Relations Review*, 2014, 25(3): 497–517.
19. <NAME>., **<NAME>.**, <NAME>., and <NAME>., '[Labour Market and Other Discrimination Facing Indigenous Australians](/pdf/ajle_2013.pdf)', *Australian Journal of Labour Economics*, 2013, 16(1): 91–113.
# Book chapters
20. **<NAME>.** '[Using social media advertising data to estimate migration trends over time](/pdf/book_chapter.pdf)'. In *Big Data Applications in Geography and Planning*. Edward Elgar Publishing. 2021.
# Non-refereed publications
21. <NAME>.(*), <NAME>., <NAME>., **<NAME>.**, and <NAME>. 2022. [‘Identifying and correcting bias in big crowd-sourced online genealogies’.](https://www.demogr.mpg.de/papers/working/wp-2022-005.pdf) *MPIDR Working Paper WP-2022-005*. Rostock, Max Planck Institute for Demographic Research.
22. <NAME>., **<NAME>.**, <NAME>.(*), <NAME>., and <NAME>. 2021. [‘Methods Protocol for the United States Mortality County Database.’](https://usa.mortality.org/uploads/counties/USCountyBayesianEstimationMethodsProtocol20210927.pdf).
23. <NAME>., **<NAME>.**, and <NAME>. 2014. [‘Modelling Exposure to Risk of Experiencing Discrimination in the Context of Endogenous Ethnic Identification’](https://docs.iza.org/dp8040.pdf), *IZA Discussion Paper* #8040.
24. <NAME>., <NAME>., and **<NAME>.** 2013. [‘Indigenous Employment: A Story of Continuing Growth’](https://caepr.cass.anu.edu.au/sites/default/files/docs/TI2013_02_Gray__Employment_0.pdf), *CAEPR Topical Issue* 2/2013, Australian National University, Canberra.
# Submitted manuscripts
25. <NAME>.(\*), <NAME>.(\*), and **<NAME>.** [‘Estimating causes of maternal death in data-sparse contexts’.](https://arxiv.org/abs/2101.05240) arXiv:2101.05240 (revise and resubmit, *Annals of Applied Statistics*).
26. <NAME>.(*), **<NAME>.**, and <NAME>. [‘Bayesian implementation of Rogers-Castro model migration schedules: An alternative technique for parameter estimation’.](/pdf/dr_rcbayes.pdf) (revise and resubmit, *Demographic Research*).
27. **<NAME>.** [‘Decomposing Dimensions of Mortality Inequality.’](https://osf.io/preprints/socarxiv/uqwxj) doi:10.31235/osf.io/uqwxj. (revise and resubmit, *Population Research and Policy Review*).
28. <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., **<NAME>.**, <NAME>., and <NAME>. [‘Predicting individual-level longevity with statistical and machine learning methods.’](https://www.demogr.mpg.de/papers/working/wp-2023-008.pdf) (revise and resubmit, *Science Advances*).
29. **<NAME>.**, and <NAME>. [‘Racial disparities in fetal and infant outcomes: a multiple-decrement life table approach’.](https://doi.org/10.31235/osf.io/k5qp7 ) doi:10.31235/osf.io/k5qp7 (under review at *Demography*)
30. <NAME>.(*) and **<NAME>.** [‘Estimating the timing of stillbirths in countries worldwide using a Bayesian hierarchical penalized splines regression model’.](https://arxiv.org/abs/2212.06219) arXiv:2212.06219 (under review at *Journal of the Royal Statistical Society (JRSS) Series C*).
31. <NAME>.(*), and **<NAME>.** [‘A Bayesian framework to account for misclassification error and uncertainty in the estimation of abortion incidence.’](https://doi.org/10.31235/osf.io/uz8ev) doi:10.31235/osf.io/uz8ev (under review at *Sociology Methodology*)
32. <NAME>.(\*), <NAME>(\*) and **<NAME>**. [‘Measuring Short-term Mobility Patterns in North America Using Facebook Advertising Data, with an Application to Adjusting Covid-19 Mortality Rates.’](https://doi.org/10.31235/osf.io/bev4p) doi:10.31235/osf.io/bev4p. (under review at *Demographic Research*)
33. <NAME>.(*) and **<NAME>**. ['Modelling transitions of opioid usage, addiction, and fatal overdoses using a Bayesian multistate model'.](/pdf/moon-alexander.pdf) (under review at *Statistics in Medicine*)
34. <NAME>.(\*), **<NAME>.**, <NAME>.(\*), <NAME>. ['MRP as a tool in the population sciences: potential benefits and challenges'.](/pdf/mrp_chapter.pdf) (under review, to appear in Kennedy, L., <NAME>., and <NAME>., (editors), *Multilevel Regression and Post-stratification: A Practical Guide and New Developments*, (accepted for publication by Cambridge University Press, expected 2024)).
# Works in progress
35. <NAME>.(*), **<NAME>.**, <NAME>., and <NAME>. ['Jointly Estimating Subnational Mortality for Multiple Populations'.](/pdf/subnational_joint.pdf) (*Status*: drafting of manuscript almost complete; to submit to *Demographic Research*)
36. Schluter, BS.(*), <NAME>., <NAME>., **<NAME>.**(#), and <NAME>.(#) ['Racial/ethnic disparities in parental loss due to drugs and firearms in the United States, 1999 - 2020'.](/pdf/kin_drugs_guns.pdf) (*Status*: drafting of manuscript almost complete; to submit as a research letter to to *JAMA*)
37. **<NAME>.**. 'Measures of premature life lost at a fixed level of life expectancy'. [Extended abstract submitted to PAA 2023](/pdf/Te0.pdf) (*Status*: need to discuss relationship with existing measures, apply to life expectancy post-Covid-19 to explore cross country differences).
38. **<NAME>.**, <NAME>., <NAME>., and <NAME>. 'Forecasting child welfare outcomes in the United States'. [Paper presented at PAA 2022](/pdf/fc_paa.pdf); [Shiny app](https://monica-alexander.shinyapps.io/foster_care/). (*Status*: need to expand discussion of context, apply to data post-Covid-19).
39. **<NAME>.**, and <NAME>.(*). ['Methods to estimate stateless populations'.](/pdf/case_studies.pdf) (*Status*: This was a report prepared for UNHCR. We need rewrite it to be in manuscript format.)
40. <NAME>., and **<NAME>.**. '[The Increased Effect of Elections and Changing Prime Ministers on Topics Discussed in the Australian Federal Parliament between 1901 and 2018](https://arxiv.org/abs/2111.09299)'. (*Status*: need to update data based on newly created dataset, simplify model to be a shorter time period).
41. **<NAME>.**, and <NAME>., '[Deaths without denominators: using a matched dataset to study mortality patterns in the United States](https://osf.io/preprints/socarxiv/q79ye/)'. (*Status*: need to update data based on newly created dataset).
# Software
42. <NAME>.(*), **<NAME>.**, and <NAME>. 'rcbayes: Estimate Rogers-Castro Migration Age Schedules with Bayesian Models'. https://cran.uib.no/web/packages/rcbayes/index.html
<file_sep>/content/posts/2020-28-02-bayes_viz.Rmd
---
title: "Visualizing the Bayesian workflow in R"
author: "<NAME>"
date: "2020-02-28"
output:
html_document:
number_sections: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = TRUE, warning=FALSE, message=FALSE)
```
# Introduction
The following (briefly) illustrates a Bayesian workflow of model fitting and checking using R and Stan. It was inspired by me reading ['Visualizing the Bayesian Workflow'](https://arxiv.org/abs/1709.01449) and writing lecture notes[^2] incorporating ideas in this paper.[^1] The paper presents a systematic workflow of visualizing the assumptions made in the modeling process, the model fit and comparison of different candidate models.
The goal of this post is to illustrate these steps in an accessible way, applied to a dataset on birth weight and gestational age. It's a bit of a choose your own adventure in some parts, because as is usually the case in R, there's about 100 different ways of doing the same thing. I show how to run things using both Stan and with the package `brms`, which is a wrapper for Stan that allows you to specify models in a similar way to `glm` or `lme4`. Using Stan for this example is a bit of overkill because the models are simple, but I find it useful to see what's going on (and also it's useful to build up more complex models in Stan from simple ones).
[^1]: I am very lucky to work with one of the authors, [<NAME>](https://twitter.com/dan_p_simpson), who listens to my questions and comments at length with an admirable level of patience, usually in exchange for coffee.
[^2]: If any students are reading this, it contains answers for most of the lab questions, lol.
# The data
I'm using (a sample of) the publicly available dataset of all births in the United States in 2017, available on the [NBER website](https://data.nber.org/data/vital-statistics-natality-data.html). For the purposes of this exercise, I'm just using a 0.1% sample of the births, which leads to 3842 observations. Details on how I got the data are [here](https://github.com/MJAlexander/states-mortality/tree/master/birthweight_bayes_viz/births_2017_prep.R).
Let's load in the packages we need and the dataset:
```{r, message=FALSE, warning=FALSE}
library(tidyverse)
library(rstan)
library(brms)
library(bayesplot)
library(loo)
library(tidybayes)
ds <- read_rds("births_2017_sample.RDS")
head(ds)
```
The dataset contains a few different variables, but for the purposes of this exercise I'm going to focus on birth weight and gestational age. Let's rename these variables, make a `preterm` variable (which indicates whether or not gestational length was less than 32 weeks)[^3] and filter out unknown observations, and any babies that died.
[^3]: Technically this is whether or not the birth was 'very preterm' according to WHO definitions: https://www.who.int/news-room/fact-sheets/detail/preterm-birth
```{r}
ds <- ds %>%
rename(birthweight = dbwt, gest = combgest) %>%
mutate(preterm = ifelse(gest<32, "Y", "N")) %>%
filter(ilive=="Y",gest< 99, birthweight<9.999)
```
# Super brief EDA
An important first step to model building is exploratory data analysis, which should help to inform potential variables or functional forms of the model. Here's some EDA in the most brief sense.[^4] Below is a scatter plot of gestational age (weeks) and birth weight (kg) on the log scale, which appears to show some relationship:
[^4]: Someone I [know](https://www.rohanalexander.com) was recently asked "when do you know that your EDA is done?" Their response was, EDA is never done, you just die.
```{r}
ds %>%
ggplot(aes(log(gest), log(birthweight))) +
geom_point() + geom_smooth(method = "lm") +
scale_color_brewer(palette = "Set1") +
theme_bw(base_size = 14) +
ggtitle("birthweight v gestational age")
```
It may be reasonable to allow for the relationship between weight and gestational age to vary by whether or not the baby was premature. If we split by prematurity, there is some evidence to suggest a different relationship between the two variables, which may lead us to consider interaction terms:
```{r}
ds %>%
ggplot(aes(log(gest), log(birthweight), color = preterm)) +
geom_point() + geom_smooth(method = "lm") +
scale_color_brewer(palette = "Set1") +
theme_bw(base_size = 14) +
ggtitle("birthweight v gestational age")
```
# Some simple candidate models
Based on my super-brief-EDA(tm) I've come up with two candidate models. Model 1 has log birth weight as a function of log gestational age
$$
\log(y_i) \sim N(\beta_0 + \beta_1\log(x_i), \sigma^2)
$$
Model 2 has an interaction term between gestation and prematurity
$$
\log(y_i) \sim N(\beta_0 + \beta_1\log(x_i) + \gamma_0 z_i + \gamma_1\log(x_i) z_i, \sigma^2)
$$
- $y_i$ is weight in kg
- $x_i$ is gestational age in weeks
- $z_i$ is preterm (0 or 1, if gestational age is less than 32 weeks)
# Prior predictive checks
Now we have some candidate models in terms of the likelihood, we need to set some priors for our coefficients ($\beta$s and $\gamma$s) and for the $\sigma$ term.
With prior predictive checks, we are essentially looking at the situation where we do not have any data on birthweights at all, and seeing what distribution of weights are implied by the choice of priors and likelihood. Ideally this distribution would have at least some mass around all plausible data sets.
To do this in R, we simulate from the priors and likelihood, and plot the resulting distribution.
## Vague priors
For example, the following plots the prior predictive distribution with vague priors on sigma, and the betas for Model 1. For reference, my current weight is marked with the purple line. While I can attest to babies feeling like they have the mass of a small planet once you've been carrying them for 9 months, it's highly implausible that my current adult weight should have so much probability mass assigned to it.
```{r}
set.seed(182)
nsims <- 100
sigma <- 1 / sqrt(rgamma(nsims, 1, rate = 100))
beta0 <- rnorm(nsims, 0, 100)
beta1 <- rnorm(nsims, 0, 100)
dsims <- tibble(log_gest_c = (log(ds$gest)-mean(log(ds$gest)))/sd(log(ds$gest)))
for(i in 1:nsims){
this_mu <- beta0[i] + beta1[i]*dsims$log_gest_c
dsims[paste0(i)] <- this_mu + rnorm(nrow(dsims), 0, sigma[i])
}
dsl <- dsims %>%
pivot_longer(`1`:`10`, names_to = "sim", values_to = "sim_weight")
dsl %>%
ggplot(aes(sim_weight)) + geom_histogram(aes(y = ..density..), bins = 20, fill = "turquoise", color = "black") +
xlim(c(-1000, 1000)) +
geom_vline(xintercept = log(60), color = "purple", lwd = 1.2, lty = 2) +
theme_bw(base_size = 16) +
annotate("text", x=300, y=0.0022, label= "Monica's\ncurrent weight",
color = "purple", size = 5)
```
## Weakly informative priors
Let's try this exercise again, but now with some [weakly informative priors](https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations). The distribution is much less spread out, and my current weight is now much further to the right of the distribution. Remember that these are the distributions before we look at any data, and we are doing so just to make sure that any plausible values have some probability of showing up. The picture will look much different once we take the observations into account.
```{r, warning=FALSE}
sigma <- abs(rnorm(nsims, 0, 1))
beta0 <- rnorm(nsims, 0, 1)
beta1 <- rnorm(nsims, 0, 1)
dsims <- tibble(log_gest_c = (log(ds$gest)-mean(log(ds$gest)))/sd(log(ds$gest)))
for(i in 1:nsims){
this_mu <- beta0[i] + beta1[i]*dsims$log_gest_c
dsims[paste0(i)] <- this_mu + rnorm(nrow(dsims), 0, sigma[i])
}
dsl <- dsims %>%
pivot_longer(`1`:`10`, names_to = "sim", values_to = "sim_weight")
dsl %>%
ggplot(aes(sim_weight)) + geom_histogram(aes(y = ..density..), bins = 20, fill = "turquoise", color = "black") +
geom_vline(xintercept = log(60), color = "purple", lwd = 1.2, lty = 2) +
theme_bw(base_size = 16) +
annotate("text", x=7, y=0.2, label= "Monica's\ncurrent weight", color = "purple", size = 5)
```
# Run the models
Now let's run the models described above. I will illustrate how to do this in both `stan` and `brms`.
## Running the models in Stan
The Stan code for model 1 is below. You can view the stan code for model 2 [here](https://github.com/MJAlexander/states-mortality/tree/master/birthweight_bayes_viz/simple_weight_preterm_int.stan). It's worth noticing the `generated quantities` block: for our model checks later on, we need to generate 1) pointwise estimates of the log-likelihood and 2) samples from the posterior predictive distribution. When using `brms` we don't have to worry about this because the log-likelihood is calculated by default, and the posterior predictive samples can be generated afterwards.[^5]
[^5]: It's also possible / easy to get posterior predictive samples in R after running the model, [here](https://github.com/MJAlexander/states-mortality/tree/master/birthweight_bayes_viz/yrep_birthweight_example.R) is some example code. Doing everything in Stan is neater, but it might be clearer to see what's going on doing it yourself in R.
```{stan output.var="mod1s"}
data {
int<lower=1> N; // number of observations
vector[N] log_gest; // log gestational age
vector[N] log_weight; // log birth weight
}
parameters {
vector[2] beta; // coefs
real<lower=0> sigma; // error sd for Gaussian likelihood
}
model {
// Log-likelihood
target += normal_lpdf(log_weight | beta[1] + beta[2] * log_gest, sigma);
// Log-priors
target += normal_lpdf(sigma | 0, 1)
+ normal_lpdf(beta | 0, 1);
}
generated quantities {
vector[N] log_lik; // pointwise log-likelihood for LOO
vector[N] log_weight_rep; // replications from posterior predictive dist
for (n in 1:N) {
real log_weight_hat_n = beta[1] + beta[2] * log_gest[n];
log_lik[n] = normal_lpdf(log_weight[n] | log_weight_hat_n, sigma);
log_weight_rep[n] = normal_rng(log_weight_hat_n, sigma);
}
}
```
Calculate the transformed variables, and put the data into a list for Stan.
```{r}
ds$log_weight <- log(ds$birthweight)
ds$log_gest_c <- (log(ds$gest) - mean(log(ds$gest)))/sd(log(ds$gest))
N <- nrow(ds)
log_weight <- ds$log_weight
log_gest_c <- ds$log_gest_c
preterm <- ifelse(ds$preterm=="Y", 1, 0)
# put into a list
stan_data <- list(N = N,
log_weight = log_weight,
log_gest = log_gest_c,
preterm = preterm)
```
Running the models in Stan looks like this:
```{r, results='hide', eval = FALSE}
mod1 <- stan(data = stan_data,
file = "models/simple_weight.stan",
iter = 500,
seed = 243)
mod2 <- stan(data = stan_data,
file = "models/simple_weight_preterm_int.stan",
iter = 500,
seed = 263)
```
Take a look at the estimates of parameters of interest. Note that I centered and standardized the gestation variable, so the interpretation in Model 1 for example is that a 1 standard deviation increase in the gestation weeks leads to a 0.14% increase in birth weight.
```{r, include=FALSE}
load("mod1.Rda")
load("mod2.Rda")
```
```{r}
summary(mod1)[["summary"]][c(paste0("beta[",1:2, "]"), "sigma"),]
```
For Model 2, the third $\beta$ relates to the effect of prematury, and the fourth $\beta$ is the interaction. The interaction effect suggests that the increase in birthweight with increased gestational age is more steep from premature babies.
```{r}
summary(mod2)[["summary"]][c(paste0("beta[",1:4, "]"), "sigma"),]
```
## Running the models in `brms`
Running the models in `brms` looks like this:
```{r, results='hide'}
mod1b <- brm(log_weight~log_gest_c, data = ds)
mod2b <- brm(log_weight~log_gest_c*preterm, data = ds)
```
# Posterior predictive checks
Now we've run the models, let's do some posterior predictive checks. The idea of posterior predictive checks is to compare our observed data to replicated data from the model.
If our model is a good fit, we should be able to use it to generate a dataset that resembles the observed data.
## PPCs with Stan output
For the Stan models, we want to extract the samples from the posterior predictive distribution and can then use `ppc_dens_overlay` to compare the densities of 100 sampled datasets to the actual data:
```{r}
set.seed(1856)
y <- log_weight
yrep1 <- extract(mod1)[["log_weight_rep"]]
samp100 <- sample(nrow(yrep1), 100)
ppc_dens_overlay(y, yrep1[samp100, ])
```
Model 2 is a bit better:
```{r}
yrep2 <- extract(mod2)[["log_weight_rep"]]
ppc_dens_overlay(y, yrep2[samp100, ])
```
If you would like to convince yourself you know what's going on with `ppc_dens_overlay` or would like to format your graphs from scratch, you can do the density plots yourself:
```{r}
# first, get into a tibble
rownames(yrep1) <- 1:nrow(yrep1)
dr <- as_tibble(t(yrep1))
dr <- dr %>% bind_cols(i = 1:N, log_weight_obs = log(ds$birthweight))
# turn into long format; easier to plot
dr <- dr %>%
pivot_longer(-(i:log_weight_obs), names_to = "sim", values_to ="y_rep")
# filter to just include 100 draws and plot!
dr %>%
filter(sim %in% samp100) %>%
ggplot(aes(y_rep, group = sim)) +
geom_density(alpha = 0.2, aes(color = "y_rep")) +
geom_density(data = ds %>% mutate(sim = 1),
aes(x = log(birthweight), col = "y")) +
scale_color_manual(name = "",
values = c("y" = "darkblue",
"y_rep" = "lightblue")) +
ggtitle("Distribution of observed and replicated birthweights") +
theme_bw(base_size = 16)
```
### Test statistics
As well as looking at the overall distributions of the replicated datasets versus the data, we can decide on a test statistic(s) that is a summary of interest, calculate the statistic for each replicated dataset, and compare the distribution of these values with the value of the statistic observed in the data.
For example, we can look at the distribution of the median (log) birth weight across the replicated data sets in comparison to the median in the data, and plot using `ppc_stat`. For both models, the predicted median birth weight is too low.
```{r}
ppc_stat(log_weight, yrep1, stat = 'median')
ppc_stat(log_weight, yrep2, stat = 'median')
```
As before, we can also construct these plots ourselves. Here I'm calculating the proportion of babies who have a weight less than 2.5kg (considered low birth weight) in each of the replicated datasets, and comparing to the proportion in the data. Model 2 seems to do a better job here:
```{r}
t_y <- mean(y<=log(2.5))
t_y_rep <- sapply(1:nrow(yrep1), function(i) mean(yrep1[i,]<=log(2.5)))
t_y_rep_2 <- sapply(1:nrow(yrep2), function(i) mean(yrep2[i,]<=log(2.5)))
ggplot(data = as_tibble(t_y_rep), aes(value)) +
geom_histogram(aes(fill = "replicated")) +
geom_vline(aes(xintercept = t_y, color = "observed"), lwd = 1.5) +
ggtitle("Model 1: proportion of births less than 2.5kg") +
theme_bw(base_size = 16) +
scale_color_manual(name = "",
values = c("observed" = "darkblue"))+
scale_fill_manual(name = "",
values = c("replicated" = "lightblue"))
ggplot(data = as_tibble(t_y_rep_2), aes(value)) +
geom_histogram(aes(fill = "replicated")) +
geom_vline(aes(xintercept = t_y, color = "observed"), lwd = 1.5) +
ggtitle("Model 2: proportion of births less than 2.5kg") +
theme_bw(base_size = 16) +
scale_color_manual(name = "",
values = c("observed" = "darkblue"))+
scale_fill_manual(name = "",
values = c("replicated" = "lightblue"))
```
## PPCs with `brms` output
With the models built in brms, we can use the `posterior_predict` function to get samples from the posterior predictive distribution:
```{r}
yrep1b <- posterior_predict(mod1b)
```
Alterantively, you can use the `tidybayes` package to add predicted draws to the original `ds` data tibble. This option is nice if you want to do a lot of ggplotting later on, because the data is already in tidy format.
```{r}
ds_yrep1 <- ds %>%
select(log_weight, log_gest_c) %>%
add_predicted_draws(mod1b)
head(ds_yrep1)
```
Once you have the posterior predictive samples, you can use the `bayesplot` package as we did above with the Stan output, or do the plots yourself in `ggplot`.
Another quick alternative with `brms` that avoids manually getting the posterior predictive samples altogether is to use the `pp_check` function, which is a wrapper for all the `bayesplot` options. e.g. density overlays:
```{r}
pp_check(mod1b, type = "dens_overlay", nsamples = 100)
```
e.g. test statistics:
```{r}
pp_check(mod1b, type = "stat", stat = 'median', nsamples = 100)
```
# LOO-CV
The last piece of this workflow is comparing models using leave-one-out cross validation. We are interested in estimating the out-of-sample predictive accuracy at each point $i$, when all we have to fit the model is data that without point $i$. We want to estimate the leave-one-out (LOO) posterior predictive densities $p(y_i|\boldsymbol{y_{-i}})$ and a summary of these across all points, which is called the LOO expected log pointwise predictive density ($\text{elpd}_{LOO}$). The bigger the numbers, the better we are at predicting the left out point $i$.
By comparing the ($\text{elpd}_{LOO}$) across models, we can choose the model that has the higher value. By looking at values for the individual points, we can see which observations are particularly hard to predict.
To calculate the ($\text{elpd}_{LOO}$) in R, we will use the `loo` package. This estimates the LOO posterior predictive densities using Pareto Smoothed Importance Sampling (PSIS)[^6], and requires point estimates of the log likelihood.
[^6]: More details [here](https://arxiv.org/abs/1507.04544).
## LOO-CV with Stan output
For the Stan models, we need to extract the log-likelihood, and then run `loo`. (The `save_psis = TRUE` is needed for the LOO-PIT graphs below).
```{r}
loglik1 <- extract(mod1)[["log_lik"]]
loglik2 <- extract(mod2)[["log_lik"]]
loo1 <- loo(loglik1, save_psis = TRUE)
loo2 <- loo(loglik2, save_psis = TRUE)
```
We can look at the summaries of these and also compare across models. The $\text{elpd}_{LOO}$ is higher for Model 2, so it is preferred.
```{r}
loo1
loo2
compare(loo1, loo2)
```
The output mentions Pareto k estimates, which give an indication of how 'influential' each point is. The higher the value of $k$, the more influential the point. [Values of $k$ over 0.7 are not good](https://mc-stan.org/loo/reference/pareto-k-diagnostic.html), and suggest the need for model re-specification. The values of $k$ can be extracted from the `loo` object like this:
```{r}
head(loo1$diagnostics$pareto_k)
```
or plotted easily like this:
```{r}
plot(loo1)
```
### LOO-PIT
Another useful model diagnostic is the LOO [probability integral transform](https://en.wikipedia.org/wiki/Probability_integral_transform) (PIT). This essentially looks to see where each point $y_i$ falls in its predictive distribution $p(y_i|\boldsymbol{y_{-i}})$. If the model is well calibrated these should look like Uniform distributions. We can use `bayesplot` to plot these against 100 simulate standard Uniforms. The results in this case aren't too bad.
```{r}
ppc_loo_pit_overlay(yrep = yrep1, y = y, lw = weights(loo1$psis_object)) + ggtitle("LOO-PIT Model 1")
ppc_loo_pit_overlay(yrep = yrep2, y = y, lw = weights(loo2$psis_object)) + ggtitle("LOO-PIT Model 2")
```
```{r, include = F}
lw = weights(loo1$psis_object)
dim(lw)
# X is posterior distribution
# Y is F(x)
# want to calculate the CDF of Y
# weights are probability mass on the log scale.
#
pit_man <- c()
for(i in 1:length(y)){
pit_man <- c(pit_man, sum(exp(lw[yrep1[,i] <=y[i],i])))
}
plot(density(pit_man))
```
## LOO-CV with `brms` output
With `brms`, the log likelihood is calculated automatically, and we can just pass the model objects directly to `loo`, for example:
```{r}
loo1b <- loo(mod1b, save_psis = TRUE)
```
Once we have the `loo` object, the rest of the plots etc can be done as above with the Stan output.
# Summary
Visualization is a powerful tool in assessing model assumptions and performance. For Bayesian models, it's important to think about how priors interplay with the likelihood (even before we observe data), to see how newly predicted data line up with the observed data, and to see how the model performs out of sample. For Bayesian models there are potentially an overwhelming number of different outputs, and in R there are a million different ways to do the same thing, so hopefully this post helps someone wade through these depths, towards a more structured Bayesian workflow.
<file_sep>/content/posts/2018-04-24-paa.Rmd
---
title: "Berkeley Demography at PAA 2018"
author: "<NAME>"
date: "2018-04-24"
output: html_document
---
Berkeley Demography and Population Center affiliates will be presenting their work at PAA 2018. Check out some of their great work!
- [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person11604.html)
+ Session 6-2: [Contribution of drug poisonings to divergence in life expectancy](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper20592.html)
+ Session 45-3: [Cause-specific mortality data at the subnational level](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper23025.html)
- [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person4688.html)
+ Poster (Health and Mortality 1): [Time poverty by ethnicity](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper21393.html)
- [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person2557.html)
+ Session 68-4: [Mortality rates from sibling histories](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper23921.html)
+ Session 83-2: [Bayesian melding to estimate census coverage](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper20223.html)
- [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person11985.html)
+ Poster (Health and Mortality 1): [Social networks and stress](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper19876.html)
- [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person264.html)
+ Session 72-3: [Cuba's cardiovascual risk factors](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper20106.html)
+ Poster (Children and Youth): [Parenting and Early Childhood Development in Indigenous and Non-Indigenous Mexican Communities](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper18486.html)
+ Poster (Health and Mortality 2): [Incentive-Based Interventions for Smoking Cessation](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper21504.html)
+ Poster (Marriage, Families, Households, and Unions 2; Gender, Race, and Ethnicity): [Paid parental leave](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper23528.html)
- [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person13558.html)
+ Poster (Marriage, Families, Households, and Unions 1): [Stress coping strategies](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper21415.html)
+ Poster (Health and Mortality 1): [Time poverty by ethnicity](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper21393.html)
- [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person14546.html)
+ Session 68-4: [Mortality rates from sibling histories](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper23921.html)
+ Session 167-3: [Estimating internet adoption using Facebook](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper23912.html)
- [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Session2138.html):
+ Organizer, Mathematical demography session
- [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person255.html)
+ Session 95-2: [Life expectancy, pension outcomes and income](paa/2018/webprogrampreliminary/Paper21830.html)
+ Session 140-3: [Aging and intergenerational flows](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper20137.html)
- [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person6435.html)
+ Session 160-4: [Risk and Protective Factors for Generational Refugee Children](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper18645.html)
- [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person2766.html)
+ Session 167-2: [Facebook as a Tool for Survey Data Collection](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper23984.html)
+ Session 174-4: [Inequalities in parental time](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper24054.html)
- [Ruijie (<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person9219.html)
+ Poster (Marriage, Families, Households, and Unions 2; Gender, Race, and Ethnicity): [Education and marriage in Japan](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper23830.html)
...and me!
- [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person6437.html):
+ Session 89-2: [Spatial distribution of opioid mortality](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper22264.html), presented by [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person15557.html)
+ Session 113-2: [Estimating subnational populations](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper21488.html), joint work with [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person16520.html)
+ Session 207-3: [Using Facebook and ACS to predict migration stocks](https://paa.confex.com/paa/2018/webprogrampreliminary/Paper23641.html), presented by [<NAME>](https://paa.confex.com/paa/2018/webprogrampreliminary/Person1727.html)
<center>
<img src="/img/demogseal2.png", width = 200>
</center>
<file_sep>/content/posts/2022-23-11-twitter.html
---
title: "Social media: the good, the bad, the unstable"
author: "<NAME>"
date: "2022-11-23"
output: html_document
---
<p>There’s been some <a href="https://www.bloomberg.com/news/videos/2022-11-20/elon-musk-may-cut-more-twitter-jobs-reinstates-trump-s-account">pretty wild stuff happen</a> over on Twitter in recent weeks. It’s a weird time to be on, and to think about, the future of a social media platform that has become central to how academics communicate new research and communicate with each other. <a href="https://twitter.com/search?q=%23AcademicTwitter&src=typeahead_click">#AcademicTwitter</a> and its many branches — such as <a href="https://twitter.com/search?q=%23PopTwitter&src=typeahead_click&f=top">#PopTwitter</a> for us demographers — contains thousands of scholars tweeting about job opportunities, latest papers and preprints, conferences and presentations (and also memes). But with the recent changes, there has been a move by many to other platforms (most notably Mastadon), with some cutting ties with the bird site altogether.</p>
<p>As someone who uses social media data in research, it’s always at the back of my mind that the data obtained from social media websites are constantly in flux: user bases change, company goals change, budgetary considerations change. Meta, for example, could just decide one day to remove the potential reach numbers from the Facebook Advertising Platform without paying, which would completely undermine this area of research.</p>
<p>Up until now, I’d thought less about the effect of platform changes on the other side of academia: that of the academic community. Maybe we all inherently assumed that this version of social media was around for good, and academia needs to work out how to incorporate it into our pre-existing structures and processes.</p>
<center>
{{% tweet "1593597413897474054" %}}
</center>
<p>So in light of avoiding thinking about the prospect of setting up yet another social media account<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a>, I decided it was a nice opportunity to write some reflections<a href="#fn2" class="footnote-ref" id="fnref2"><sup>2</sup></a> about my experience with Twitter, what’s great and not so great, and what that all means for the future. I’m not sure if it’s particularly insightful or useful, but it is a good way to express my gratitude for all the wonderful people I’ve met through this platform, in perhaps a more lasting way than saying it on Twitter (because who knows if it will just break one day)<a href="#fn3" class="footnote-ref" id="fnref3"><sup>3</sup></a>.</p>
<div id="the-good-stuff" class="section level2">
<h2>The good stuff</h2>
<div id="community-building" class="section level3">
<h3>Community building</h3>
<p>By far the best thing about Twitter for me has been meeting new people and forming new connections. This is both informally, through just tweeting at people and hearing about other people’s work<a href="#fn4" class="footnote-ref" id="fnref4"><sup>4</sup></a>, but also through creating academic groups with a relative ease and speed that just wouldn’t have been possible without something like Twitter.</p>
<p>From my own experience, the <a href="https://formaldemography.github.io/working_group/">Formal Demography Working Group</a> is the best example of this, and something that I will be forever grateful for. I helicoptered in to a tweet thread about formal demography, and then with two other early career researchers (<NAME> and <NAME>) set up a working group. We aim to meet about once a month to discuss formal demographic topics, which are often set aside at more generalist population workshops and conferences.</p>
<center>
{{% tweet "1451225679769620485" %}}
</center>
<p>Through Twitter, we built up a large email list, and over time and through word-of-mouth, we are getting participants beyond social media. The start of this coincided with the ‘Zoom era’ and people are maybe just generally more comfortable with tuning in online, but each month we get a large crowd from all over the world.</p>
</div>
<div id="promoting-junior-scholars" class="section level3">
<h3>Promoting junior scholars</h3>
<p>There is no doubt that Twitter has enabled the promotion and exposure of early career researchers unlike anything that came before it. You can tweet about papers, pre-prints, presentations, other projects; you can tweet interesting observations, jokes or memes, and there’s a good chance they might resonate with people, irrespective of your career stage. Many senior academics also promote junior scholar’s work.</p>
<p>I’m of the era where I’m thinking ‘it’s possible that Twitter helped me get a job’<a href="#fn5" class="footnote-ref" id="fnref5"><sup>5</sup></a>, and now I’m a ‘senior junior’ (geriatric junior?) I really enjoy reading about the work of talented students and postdocs, discovered largely through their tweets. Hashtags that are associated with conferences are another good example — whereas before, I was inclined to attend sessions where I recognized the name of the speaker, I now follow along with the hashtags to learn about interesting research.</p>
</div>
<div id="speed-of-research-and-research-impact" class="section level3">
<h3>Speed of research and research impact</h3>
<p>The Twitter era pairs well with the pre-print era. The big pre-print servers, like arXiv and SocArxiv have their own Twitter accounts, which tweet out new work as it is being posted. Research can be disseminated in a much faster time frame, and reach a much larger audience, than the traditional format.</p>
<center>
{{% tweet "1097872838806196224" %}}
</center>
<p>Indeed, one could argue that the workflow and timeline of producing academic work in many fields has completely changed, from a very linear path to a non-linear path that involves soliciting feedback at different stages of the project. Twitter is a big part of this, for better or for worse.</p>
<p>Additionally, I think Twitter has created opportunities for academics to engage more with public policy and the broader impact of their work. The Covid-19 pandemic has really brought this to the fore. When this whole thing started, Twitter became a place where uncertain estimates were hastily thrown about, while demographers were all shouting <a href="https://twitter.com/monjalexander/status/1239191247597731842">‘yes but what about the age structure’</a> into the void. Since then, there has been some outstanding work by demographers to really engage with the broader community, including academics, doctors, politicians, and journalists, to improve the measurement and communication of uncertainty in Covid-19 deaths.<a href="#fn6" class="footnote-ref" id="fnref6"><sup>6</sup></a> Yes, maybe this all would’ve happened with Twitter, but it provides a platform to communicate ideas to a broader audience.</p>
<center>
{{% tweet "1595022315452088325" %}}
</center>
</div>
</div>
<div id="the-not-so-good-stuff" class="section level2">
<h2>The not-so-good stuff</h2>
<p>Of course it’s not all sunshine and roses on Twitter, and there are parts of it and behaviors that are truly toxic. The flip side of community-building is community exclusion. As is the case with any group effort, we should strive for representation of participants and points of view from all backgrounds. This can be difficult on Twitter, because users are selected in very strong ways, and Twitter communities themselves are very <a href="https://www.polarizationlab.com/new-book">siloed</a>; this is studied extensively from a political point of view, but probably true of academic communities, too. The flip-side of having a more equal playing field for junior scholars is that there’s a lot of ‘punching down’, and the madness of crowds is such that Twitter can be full of nonconstructive criticism and personal attacks, even for those who have yet to properly start their career. And the flip side of increased speed of research dissemination is the increased speed of the spread of misinformation, and sometimes it is difficult to know the source of claims and whether they are reliable or not.</p>
</div>
<div id="the-future" class="section level2">
<h2>The future?</h2>
<p>I mentioned at the start of this about using social media data in demographic research, and how that could all change at the drop of a hat. Maybe this doesn’t matter, though, because of the data issues we’ve had to think about, and methods that have been developed in response such issues, are useful outside of the social media context, so it’s been a valuable exercise anyway.</p>
<p>Maybe the same can be said about social media platforms as a tool for academic community building. Social media website are dynamic environments, both in terms of the users and developers, and it’s probably inevitable that Twitter will be replaced with something else. A question is, should it serve exactly the same function as Twitter? Maybe not. New platforms call for evolution in how we interact, how we disseminate research, and how we support others.</p>
<p>Who knows what will happen in the future, but I will be forever grateful for the awesome people I met through Twitter, and will no doubt follow you all to the next big thing (albeit 10 steps behind).</p>
</div>
<div class="footnotes footnotes-end-of-document">
<hr />
<ol>
<li id="fn1"><p>I just started using BeReal in an effort to keep up with my lesser-geriatric millennial friends, but so far it’s just pictures of me at my desk or the kids building Lego<a href="#fnref1" class="footnote-back">↩︎</a></p></li>
<li id="fn2"><p>Also to keep up with the twice-per-year blog average<a href="#fnref2" class="footnote-back">↩︎</a></p></li>
<li id="fn3"><p>This is assuming I know how to fix my website if it breaks, which, dear Reader, I do not.<a href="#fnref3" class="footnote-back">↩︎</a></p></li>
<li id="fn4"><p>And the classic “Hey I know you from Twitter!” exchanges at conferences<a href="#fnref4" class="footnote-back">↩︎</a></p></li>
<li id="fn5"><p>Said with all the usual survivorship bias caveats<a href="#fnref5" class="footnote-back">↩︎</a></p></li>
<li id="fn6"><p>For example, work on life expectancy from the group at Leverhulme Centre for Demographic Science; work on providing high-quality mortality data by the HMD group; and work on racial disparities by Elizabeth Wrigley-Field.<a href="#fnref6" class="footnote-back">↩︎</a></p></li>
</ol>
</div>
<file_sep>/content/women_scholars/index.Rmd
---
title: "Women in Demography"
---
An ever-growing list of active scholars in demography who identify as women or as a gender minority, listed by broad sub-discipline, and with two notable papers.[^1] [^2]
[^1]: Thanks to <NAME>, <NAME>, <NAME> and <NAME> for their help in compiling the initial list.
[^2]: To dos: add social media handles, institution/country info. And do some data visualization!
If you or someone you know should be on this list and isn't, please fill out [this form](https://docs.google.com/forms/d/e/1FAIpQLSdb1XObnbO4KP0Xg65gakYA-CO_78OZFU7KPfddxdJJnehUtg/viewform). If you are on this list and would like different papers highlighted, or if you see any mistakes, email me!
Sub-disciplines are:[^3]
- Family, social demography
- Fertility
- Mathematical, statistical, digital demography, population projection
- Migration, environment, economic demography
- Mortality, health, aging, biodemography
[^3]: At some point I want to change these to actually be more informative.
<br>
```{r, echo=FALSE, warning=FALSE, message=FALSE}
library(tidyverse)
library(reactable)
library(here)
df <- read_csv(here("content/women_scholars/scholars.csv"),col_types = cols_only("Name" = col_character(), "page" = col_character(), "Category" = col_character(), "Paper 1" = col_character(), "paper_1_link" = col_character(), "Paper 2" = col_character(), "paper_2_link" = col_character()))
reactable(df %>% rename(`Sub-discipline` = Category) %>% select(-page, -paper_1_link, -paper_2_link),
columns = list(Name = colDef(cell = function(value, index) {
# Render as a link
url <- df[index, "page"] %>% pull()
htmltools::tags$a(href = url, target = "_blank", as.character(value))
}),
`Paper 1` = colDef(cell = function(value, index) {
# Render as a link
url <- df[index, "paper_1_link"] %>% pull()
htmltools::tags$a(href = url, target = "_blank", as.character(value))
}),
`Paper 2` = colDef(cell = function(value, index) {
# Render as a link
url <- df[index, "paper_2_link"] %>% pull()
htmltools::tags$a(href = url, target = "_blank", as.character(value))
})),
searchable = TRUE,
filterable = TRUE,
sortable = TRUE,
defaultPageSize = 30)
```
<file_sep>/content/posts/2018-21-09-tutorial.Rmd
---
title: "Estimating age-specific mortality rates at the subnational level"
author: "<NAME>"
date: "2018-09-21"
output: html_document
draft: false
---
# Introduction
This is a tutorial on estimating age-specific mortality rates at the subnational level, using a model similar to that described in our [Demography paper](https://link.springer.com/article/10.1007/s13524-017-0618-7). There are four main steps, which will be described below:
1. Prepare data and get it in the right format
2. Choose and create a mortality standard
3. Fit the model
4. Analyze results from the model
A few notes on this particular example:
- I'll be fitting the model to county-level mortality rates in California over the years 1999 to 2016. These are age-specific mortality rates for both sexes for the age groups <1, 1-4, 5-9, 10-14, 15-19, 20-24, 25-34, 35-44, 45-54, 55-64, 65-74, 75-84, 85+.
- Data on deaths and populations are publicly available through [CDC WONDER](https://wonder.cdc.gov/). However, age groups where death counts are less than 10 are suppressed, and so for some age group/year/county combinations, there are missing data. Also note that there are no observations for any years for two counties, Sierra and Alpine.
- All analysis was done in R and the model was fit using JAGS. Other MCMC options such as Stan, WinBUGS or PyMC would probably work just as well.
All the code to reproduce this example can be found here: https://github.com/MJAlexander/states-mortality/tree/master/CA_county_example. Please see the R file `CA.R` in the `code` folder.
A note on modeling: there are many adaptions that can be made to this broad model set up, which may be more suitable in different situations. When estimating mortality in your own work, make sure to undergo a suitable validation process to see that the estimates are sensible, and fully test alternatives.
# 1. Preparing the data
The first step is to obtain data on death counts and population by age (and potentially sex) groups, and get it in the right format for modeling purposes. Note that you need counts, not just the mortality rates, as inputs into the model.
In this example, I downloaded data on death and population counts by county (the files `CA.csv` and `CA_pop.csv` in the data folder). Because these two data sources had different age groups available, I had to a bit of cleaning up to make sure everything was consistent. The resulting deaths data has the following form:
```{r, echo = F, message=F, warning=F}
d <- read.csv("deaths.csv")
head(d)
```
For the JAGS model, the data has to has to be in the form of an array. The notation used throughout the JAGS model is referring to age $x$, time $t$, area $a$ and state $s$. So both the deaths and population data need to be in the form of an array with dimensions age x time x area x state. I did this in quite an ugly way combining loops and tidyverse, which probably isn't the most elegant way, but it works :) The resulting deaths data for the first county (Alameda) looks like this:
```{r, echo = F, message=F, warning=F}
load("y.xtas.Rda")
```
```{r}
y.xtas[,,1,1]
```
# 2. Preparing the mortality standard
The other main inputs to the mortality model are the principal components derived from the mortality standard. Which mortality standard you choose to derive your principal components from depends on your specific problem. In the case of this example, I decided to use state-level mortality schedules for all states in the US over the period 1959--2015. These data are available through the [United States Mortality Database](https://usa.mortality.org/).
The code I used to create the principal components using these data are [here](https://github.com/MJAlexander/states-mortality/blob/master/CA_county_example/code/pcs.R). Again note that for this particular example, I had to alter the data so that the age groups were consistent.
Once the principal components are obtained, they can be input into the model based on being in a matrix with dimension age x component. Note that the model fitted here uses three components. The inputs are below:
```{r, echo = F, message=F, warning=F}
pcs <- read.csv("US_state.csv")[,1:3]
pcs
```
# 3. Running the model
Now that we have the required data inputs, the JAGS model can be run. You need to create an input list of all the data required by JAGS, and specify the names of the parameters you would like to monitor and get posterior samples for.
```{r, eval=F}
jags.data <- list(y.xtas = y.xtas,
pop.xtas = pop.xtas,
Yx = pcs,
S = 1, X= length(age_groups), T = length(years),
n.a=length(counties), n.amax=length(counties), P=3 )
parnames <- c("beta.tas", "mu.beta" ,"sigma.beta", "tau.mu", "u.xtas", "mx.xtas")
```
Once that is done, the model can be run. Please look at the model text file in reference to the paper to see which variables refer to what aspects. The notation used in the JAGS model is (I hope) fairly consistent with the notation in the paper.
```{r, eval=F}
mod <- jags(data = jags.data,
parameters.to.save=parnames,
n.iter = 30000,
model.file = "../code/model.txt")
```
This may take a while to run, so be patient. You can look at a summary of the model estimates like this:
```{r, eval=F}
mod$BUGSoutput$summary
```
Note that the values of all Rhats should be less than 1.1, otherwise the estimates are unreliable and should not be interpreted. If you have Rhats that are greater than 1.1, try running the model for more iterations.
```{r, eval=F}
# check all Rhats are less than 1.1
max(mod$BUGSoutput$summary[,"Rhat"])
```
# 4. Extract results
Now that we have model estimates, we need to be able to extract them and look at the results. You can get the posterior samples for all parameters by extracting the `sims.array` from the model object:
```{r, eval=F}
mcmc.array <- mod$BUGSoutput$sims.array
```
Unless you're interested in the underlying mechanics of the model, you're probably most interested in the estimates for the age-specific mortality rates, `mx.xtas`. The `sims.array` has dimensions number iterations (default 1,000) x number of chains (default 3) x number of parameters. So to look at the posterior samples for `mx.xtas[1,1,1,1]` for example, you would type:
```{r, eval = F}
mcmc.array[,,"mx.xtas[1,1,1,1]"]
```
Once the posterior samples are obtained, these are used to obtain the best estimate of the parameter (usually the median) and Bayesian credible intervals. For example, a 95% credible interval can be calculated by getting the 2.5th and 97.5th quantile of the posterior samples. Below is a chart that illustrates some of the age-specific mortality estimates for six Californian counties in 2016. Code to generate this chart is included in `CA.R`.
{width=800px}
Once the estimate for mortality rates are extracted, you can also convert these into other mortality measures, such as life expectancy, using standard life table relationships. The code on GitHub includes a function which derives life expectancy from the mx's, called `derive_ex_values`. This function is loaded in at the beginning of the `CA.R`. Code to generate this chart is included at the end of `CA.R`.
{width=600px}
# Summary
This document gives a brief introduction into the practicalities of fitting a Bayesian subnational mortality model in R using JAGS. There are many different layers to the model and assumptions associated with it, so it is recommended that the user of this code and model is familiar with [the paper](https://link.springer.com/article/10.1007/s13524-017-0618-7) and the assumptions outlined in it. Good luck! :)
<file_sep>/content/posts/2018-02-15-gompertz.Rmd
---
title: "Gompertz mortality models"
author: "<NAME>"
date: "2018-02-18"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Introduction
The Gompertz model is one of the most well-known mortality models. It does remarkably well at explaining mortality rates at adult ages across a wide range of populations with just two parameters. This post briefly reviews the Gompertz model, highlighting the relationship between the two Gompertz parameters, $\alpha$ and $\beta$, and the implied mode age at death. I focus on the situation where we only observe death counts by age (rather than mortality rates), so estimation of the Gompertz model requires choosing $\alpha$ and $\beta$ to maximize the (log) density of deaths.
## Gompertz mortality
Here are a few important equations related to the Gompertz model.[^1] The Gompertz hazard (or force of mortality) at age $x$, $\mu(x)$, has the exponential form
$$
\mu(x) = \alpha e^{\beta x}
$$
The $\alpha$ parameter captures some starting level of mortality and the $\beta$ gives the rate of mortality increase over age. Note here that $x$ refers to the starting age of analysis and not necessarily age = 0. Indeed, Gompertz models don't do a very good job at younger ages (roughly $<40$ years).
Given the relationship between hazard rates and survivorship at age $x$, $l(x)$,
$$
\mu(x) = -\frac{d}{dx} \log l(x)
$$
the expression for $l(x)$ is
$$
l(x) = \exp\left(-\frac{\alpha}{\beta}\left(\exp(\beta x) - 1\right)\right)
$$
It then follows that the density of deaths at age $x$, $d(x)$ is
$$
d(x) = \mu(x) l(x) = \alpha \exp(\beta x) \exp\left(-\frac{\alpha}{\beta}\left(\exp(\beta x) - 1\right)\right)
$$
which probably looks worse than it is. $d(x)$ tells us about the distribution of deaths by age. It is a density, so
$$
\int d(x) = 1
$$
Say we observe death counts by age, $y(x)$, which implies a total number of deaths of $D$. If we multiply the total number of deaths $D$ by $d(x)$, then that gives the number of deaths at age $x$. In terms of fitting a model, we want to find values for $\alpha$ and $\beta$ that correspond to the density $d(x)$ which best describes the data we observe, $y(x)$.
## Parameterization in terms of the mode age
Under a Gompertz model, the mode age at death, $M$ is
$$
M = \frac{1}{\beta}\log \left(\frac{\beta}{\alpha}\right)
$$
Given a set of plausible mode ages, we can work out the relevant combinations of $\alpha$ and $\beta$ based on the equation above. For example, the chart belows shows all combinations of $\alpha$ and $\beta$ that result in a mode age between 60 and 90.
<img src="/img/plausible_values.png">
This chart suggests that plausible values of $\alpha$ and $\beta$ for human populations are pretty restricted. In addition, it shows the strong correlation between these two parameters: in general, the smaller the value of $\beta$, the larger the value of $\alpha$. This sort of correlation between parameters can cause issues with estimation. However, given we know the relationship between $\alpha$ and $\beta$ and the mode age, the Gompertz model can be reparameterized in terms of $M$ and $\beta$:
$$
\mu(x) = \beta \exp\left(\beta (x - M)\right)
$$
As [this paper](https://www.demographic-research.org/volumes/vol32/36/) notes, $M$ and $\beta$ are much less correlated than $\alpha$ and $\beta$. In addition, the modal age has a much more intuitive interpretation than $\alpha$.
## Implications for fitting
Given the reparameterization, we now want to find estimates for $M$ and $\beta$ such that the resulting deaths density $d(x)$ best reflects the data. If we assume that the number of deaths observed at a particular age, $y_x$, are Poisson distributed, and the total number of deaths observed is $D$, then we get the following hierarchical set up:
$$
y(x) \sim \text{Poisson} (\lambda(x))\\
\lambda(x) = D \cdot d(x)\\
d(x) = \mu(x) \cdot l(x)\\
\mu(x) = \beta \exp\left(\beta (x - M)\right) \\
l(x) = \exp \left( -\exp \left(-\beta M \right) \left(\exp(\beta x)-1 \right)\right)
$$
This can be fit in a Bayesian framework, with relevant priors put on $\beta$ and $M$.
### End notes
This is part of an ongoing project with [<NAME>](http://www.site.demog.berkeley.edu/josh-goldstein) on modeling mortality rates for a dataset of censored death observations. Thanks to [<NAME>](http://www.robertempickett.com/) who told me about the Tissov et al. paper and generally has interesting things to say about demography.
[^1]: A good reference for this is [Essential Demographic Methods, Chapter 3](http://www.hup.harvard.edu/catalog.php?isbn=9780674045576). <file_sep>/content/posts/2019-20-01-babynames.Rmd
---
title: "The concentration and uniqueness of baby names in Australia and the US"
author: "<NAME>"
date: "2019-01-21"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = F, message = F)
```
Some great people have compiled historical data on baby names into R packages for both the US [(thanks to Hadley Wickham)](https://github.com/hadley/babynames) and Australia [(thanks to the Monash group)](https://github.com/ropenscilabs/ozbabynames). This makes answering all manner of baby-name-related questions easy.
I was interested in looking at the distribution of baby names in these populations over time --- that is, how concentrated are name choices in the most popular baby names? Is there a big difference between the number of babies that are called the most popular names compared to other names, or is the distribution more evenly spread?
The summary: names are very concentrated --- the majority of babies are called a name from a relatively small subset. However, baby name concentration is declining over time, and additionally, the number of unique names is increasing.
# Data
I used the used the `babynames` and `ozbabynames` packages to look at names in the US and Australia. You will need to install the Australian version from [GitHub](https://github.com/ropenscilabs/ozbabynames). I restricted the period to be 1960-2015 where both datasets had data. For the Australian baby names, I restricted the dataset to only include South Australia, Western Australia and New South Wales, as the other states did not have full coverage over the specified time period.[^1]
Each dataset gives us the name, sex, year and count of number of babies. The following code loads them in and creates one tibble with both countries.
[^1]:For those who are a bit rusty on Australian geography, it's a shame we don't have Victoria and Queensland in particular, the two other big states.
```{r}
# load in the packages required
library(ozbabynames)
library(babynames)
library(tidyverse)
library(reldist)
# get the Australian and US data in one big tibble
da <- ozbabynames %>%
filter(state %in% c("New South Wales", "South Australia", "Western Australia"),
year>1959, year<2016) %>%
mutate(sex = ifelse(sex=="Female", "F", "M")) %>%
group_by(sex, year, name) %>%
summarise(count = sum(count)) %>%
arrange(sex, year, count) %>%
mutate(country = "AUS") %>%
filter(count>4) # remove weird stuff with really low counts
du <- babynames %>%
mutate(country = "USA") %>%
rename(count = n) %>%
arrange(sex, year, count) %>%
filter(count>4, year>1959, year<2016) %>%
select(-prop)
db <- da %>%
bind_rows(du)
head(db)
```
Note that the US is much larger than Australia --- there are around 60 times more babies in the US dataset. For example, in 2015 there were 3.7 million births in the US, compared to around 57,000 in Australia. This means the trends and patterns will be noisier for Australia.
```{r}
db %>%
group_by(year, country) %>%
summarise(n = sum(count)) %>%
filter(year==2015)
```
# Baby names are concentrated in a small subset of names
To look at the concentration of baby names, let's calculate the Gini coefficient for each country, sex and year. The Gini coefficient measures dispersion or inequality among values of a frequency distribution. It can take any value between 0 and 1. In the case of income distributions, a Gini coefficient of 1 would mean one person has all the income. In this case, a Gini coefficient of 1 would mean that all babies have the same name. In contrast, a Gini coefficient of 0 would mean names are evenly distributed across all babies.
The plot below shows the Gini coefficients by country and sex for the period 1960-2015. We can see that, in general, the Gini coefficients are high, meaning that most babies have similar names. Concentration of names is higher in the US compared to Australia and coefficients are generally decreasing over time, particularly for the US. In the US, concentration of names is higher for boys, while in Australia, the sex difference is less clear.
```{r}
db %>%
group_by(country, sex, year) %>%
summarise(gini = gini(count)) %>%
ggplot(aes(year, gini, color = sex, lty = country)) +
geom_line(lwd = 1.1) +
scale_color_brewer(palette = "Set1") +
ggtitle("Gini coefficients for baby names \nAustralia and USA, 1960-2015")
```
We can plot this concentration a different way: let's look at the proportion of babies who have a name in the top 5% most popular names.[^2]
[^2]: Note that I chose the top 5% rather than the top 5 because of the large difference in the number of unique names across the two countries.
Note that the trends and patterns are pretty much identical to those above. The levels are quite high: in 1960 in the US, almost 90% of all babies born were called a name that was in the top 5% most popular names (note that this corresponds to the around the 250 most popular names).
```{r}
db %>%
group_by(sex, year, country) %>%
mutate(id = row_number()-1,
cumul_count = cumsum(count)/max(cumsum(count))) %>% # get cumulative proportion of babies with each name
mutate(rank = ntile(id, 20)) %>% # find the top 5th percentile
filter(rank==20) %>%
slice(1) %>%
ggplot(aes(year, 1-cumul_count, color = sex, lty = country)) +
geom_line(lwd = 1.1) +
scale_color_brewer(palette = "Set1") +
ylab("proportion") +
ggtitle("Proportion of babies that have one of the top 5% names \nAustralia and USA, 1960 -2015")
```
# Names are getting more unique
Is the distribution of baby names become less concentrated because there are more unique names being used over time, or just because people are opting to choose less popular but already existing names?
It seems that there is an increase in unique names being used over time in both countries. However, there has been a slight decrease in uniqueness in the US since 2010. (Perhaps people are finally running out of alternative ways of spelling 'Jackson'.) Interestingly, the number of unique girls names is higher as a proportion of total births compared to boys. This is consistent with the observation above that Gini coefficients are higher for boys.
```{r}
db %>%
group_by(sex, year, country) %>%
summarise(prop_uniq = n()/sum(count)) %>%
ggplot(aes(year, prop_uniq, color = sex, lty = country)) +
geom_line(lwd = 1.1) +
scale_color_brewer(palette = "Set1") +
ylab("proportion") +
ggtitle("Unique baby names as a proportion of total births \nAustralia and USA, 1960 -2015")
```
# Summary notes
People tend to choose a baby name from a relatively small subset of popular names, although name uniqueness is increasing slightly over time. Concentration of baby names is generally higher for boys, and higher in the US compared to Australia. So even though there are many more interesting sounding names in the US, a larger proportion of the population just stick to the more usual names.
Changes in popular baby names and how people choose to name their baby are influenced by underlying social processes, such as era-specific events, country-specific cultural norms, and fertility intentions. Sociologists and demographers such as [<NAME>](https://www.theatlantic.com/sexes/archive/2012/12/why-dont-parents-name-their-daughters-mary-anymore/265881/) and [<NAME>](https://journals.sagepub.com/doi/abs/10.1177/0003122415621910) have done some interesting work in this area.
<file_sep>/content/research.md
+++
title = "Research"
slug = "research"
+++
A list of papers is also on [Google Scholar](https://scholar.google.ca/citations?user=EoBHlPQAAAAJ&hl=en&authuser=1).
# Peer-reviewed publications
- **<NAME>.**, and <NAME>., [‘A Bayesian cohort component projection model to estimate adult populations at the subnational level in data-sparse settings’](https://read.dukeupress.edu/demography/article/59/5/1713/318087/A-Bayesian-Cohort-Component-Projection-Model-to), *Demography*, 2022: 59(5), 1713-1737.
- <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., **<NAME>.**, and <NAME>. ‘[A framework to model global, regional, and national estimates of intimate partner violence](https://bmcmedresmethodol.biomedcentral.com/articles/10.1186/s12874-022-01634-5)’, *BMC Medical Research Methodology*, 2022: 22(1), 1-17.
- <NAME>., **<NAME>.**, and <NAME>., [Temporal models for demographic and global health outcomes in multiple populations: Introducing a new framework to review and standardize documentation of model assumptions and facilitate model comparison](https://onlinelibrary.wiley.com/doi/10.1111/insr.12491), *International Statistical Review*, 2022: 90(3), 437-467.
- **<NAME>.** and <NAME>. '[Competing effects on the average age of infant death](https://read.dukeupress.edu/demography/article/doi/10.1215/00703370-9779784/294667/Competing-Effects-on-the-Average-Age-of-Infant)'. *Demography*, 2022: 59(2), 587-605.
- <NAME>., <NAME>., **<NAME>.**, <NAME>., <NAME>. '[Racial/Ethnic Disparities in Opioid-Related Mortality in the USA, 1999–2019: the Extreme Case of Washington DC.](https://pubmed.ncbi.nlm.nih.gov/34664185/)' *Journal of Urban Health*, 2021: 98(6), 589.
- <NAME>., <NAME>., **<NAME>.**, <NAME>., and <NAME>. ['Methods for small area population forecasts: state-of-the-art and research needs'](https://link.springer.com/article/10.1007/s11113-021-09671-6), *Population Research and Policy Review*, 2021: 41, 865-898.
- <NAME>., <NAME>., <NAME>., <NAME>., **<NAME>.**, <NAME>., <NAME>.,
<NAME>., <NAME>., <NAME>., and <NAME>. [‘Sociodemographic characteristics of missing data in digital phenotyping’](https://www.nature.com/articles/s41598-021-94516-7). *Scientific Reports*, 2021: 11(1),15408.
- **<NAME>.**, <NAME>., and <NAME>., ['Combining social media and survey data to nowcast migrant stocks in the United States'](https://link.springer.com/article/10.1007/s11113-020-09599-3), *Population Research and Policy Review*, 2020: 41, 1-28.
- **<NAME>.**, <NAME>., and <NAME>., ['The impact of Hurricane Maria on out-migration from Puerto Rico: Evidence from Facebook data'](https://www.jstor.org/stable/45216967), *Population and Development Review*, 2019: 45(3), 617-630.
- <NAME>., **<NAME>.**, <NAME>., and <NAME>. '[National, regional, and global levels and trends in neonatal mortality between 1990 and 2017, with scenario-based projections to 2030: a systematic analysis by the United Nations Inter-agency Group for Child Mortality Estimation](https://www.thelancet.com/journals/langlo/article/PIIS2214-109X(19)30163-9/fulltext)', *Lancet Global Health*, 2019, 7(6): 710-720.
- <NAME>., <NAME>., <NAME>., and **<NAME>**. '[Assessment of Changes in the Geographical Distribution of Opioid-Related Mortality Across the United States by Opioid Type, 1999-2016](https://jamanetwork.com/journals/jamanetworkopen/fullarticle/2725487)'. *JAMA Network Open*. 2019, 2(2):e190040.
- <NAME>., <NAME>., and **<NAME>.**, '[Trends in pregnancy-associated mortality involving opioids in the United States, 2007–2016](https://www.ajog.org/article/S0002-9378(18)30820-2/fulltext)', *American Journal of Obstetrics and Gynecology*, 2019, 220(1): 115-116.
- **<NAME>.**, <NAME>., and <NAME>., '[Trends in Black and White Opioid Mortality in the United States, 1979–2015](https://journals.lww.com/epidem/Fulltext/2018/09000/Trends_in_Black_and_White_Opioid_Mortality_in_the.16.aspx)', *Epidemiology*, 2018, 29(5): 707–715.
- **<NAME>.**, and <NAME>., '[Global Estimation of Neonatal Mortality using a Bayesian Hierarchical Splines Regression Model](https://www.demographic-research.org/volumes/vol38/15/default.htm)', *Demographic Research*, 2018, 38(15): 335–372.
- **<NAME>.**, <NAME>., and <NAME>., '[A Flexible Bayesian Model for Estimating Subnational Mortality](https://link.springer.com/article/10.1007/s13524-017-0618-7)', *Demography*, 2017, 54(6): 2025–2041.
- **<NAME>.**, <NAME>., and <NAME>., '[Wages, government payments and other income of Indigenous and non-Indigenous Australians](https://www.proquest.com/docview/1857262478?pq-origsite=gscholar&parentSessionId=zTF77rxFjqioNCrebaxo%2Bns99sFdIGIBMkJcRnGH144%3D)', *Australian Journal of Labour Economics*, 2016, 19(2): 53–76.
- <NAME>., **<NAME>.**, and <NAME>., '[The Economic Impact of the Mining Boom on Indigenous and Non-Indigenous Australians](https://onlinelibrary.wiley.com/doi/full/10.1002/app5.99#:~:text=Average%20household%20incomes%20are%20higher,employment%20rate%20in%20mining%20areas.)', *Asia & the Pacific Policy Studies*, 2015, 2(3): 517–530.
- <NAME>., **<NAME>.**, and <NAME>., '[Labour Market Outcomes for Indigenous Australians](https://journals.sagepub.com/doi/abs/10.1177/1035304614545943)', *The Economic and Labour Relations Review*, 2014, 25(3): 497–517.
- <NAME>., **<NAME>.**, <NAME>., and <NAME>., '[Labour Market and Other Discrimination Facing Indigenous Australians](https://ajle.org/index.php/ajle_home/article/view/134)', *Australian Journal of Labour Economics*, 2013, 16(1): 91–113.
# Book chapters
- **<NAME>.** '[Using social media advertising data to estimate migration trends over time](https://www.elgaronline.com/view/edcoll/9781789909784/9781789909784.00007.xml)'. In *Big Data Applications in Geography and Planning*. Edward Elgar Publishing. 2021.
# Working papers, projects, and pre-prints
- <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., **<NAME>.**, <NAME>., <NAME>. (2023). [‘Predicting individual-level longevity with statistical and machine learning methods.’](https://www.demogr.mpg.de/papers/working/wp-2023-008.pdf).
- <NAME>., and **<NAME>.**. '[Estimating the timing of stillbirths in countries worldwide using a Bayesian hierarchical penalized splines regression model](https://arxiv.org/abs/2212.06219)'.
- **<NAME>.** and <NAME>. '[Racial disparities in premature births, fetal deaths and neonatal deaths: a multi-decrement lifetable approach](/pdf/paa2023.pdf)'.
- **<NAME>.**, '[Decomposing dimensions of mortality inequality](https://osf.io/preprints/socarxiv/uqwxj)'.
- <NAME>., <NAME>., <NAME>., **<NAME>.**, \& <NAME>. (2022). '[Identifying and correcting bias in big crowd-sourced online genealogies](https://www.demogr.mpg.de/papers/working/wp-2022-005.pdf).
- **<NAME>.**, <NAME>., and <NAME>. '[Estimating causes of maternal death in data-sparse contexts](https://arxiv.org/abs/2101.05240)'.
- **<NAME>.**, <NAME>., <NAME>., and <NAME>. 'Forecasting child welfare outcomes in the United States'. [Shiny app](https://monica-alexander.shinyapps.io/foster_care/); [Paper presented at PAA 2022](/pdf/fc_paa.pdf).
- <NAME>., and **<NAME>.**. '[The Increased Effect of Elections and Changing Prime Ministers on Topics Discussed in the Australian Federal Parliament between 1901 and 2018](https://arxiv.org/abs/2111.09299)'.
- **<NAME>.**, and <NAME>., '[Deaths without denominators: using a matched dataset to study mortality patterns in the United States](https://osf.io/preprints/socarxiv/q79ye/)'.
# Working papers where there is not so much working happening
- **<NAME>.**, '[Temporal smoothers for use in demographic estimation and projection](/pdf/temporal_smoothing.pdf)'. This paper turned into another paper (Susmann et al., above). I wrote an R package to accompany the paper, which can be found on my [GitHub](https://github.com/MJAlexander/distortr). One day I might translate the models from JAGS to Stan.
- <NAME>., and **<NAME>.**, '[Kin Dependency Ratios: An Extension and Application of the Goodman Method for Estimating the Availability of Kin](https://p-chung.com/paa/2019/abstract/)'.
# Talks
Here are recordings of some talks:
- [Using Facebook advertising data to estimate migration](https://www.youtube.com/watch?v=xM1vf_KT76g)
- [Overcoming barriers to sharing code](https://www.youtube.com/watch?v=yvM2C6aZ94k)
- [Estimating subnational populations in data-sparse contexts](https://www.youtube.com/watch?v=OyDEfGfDoCo&feature=youtu.be)
# Code and other fun projects
- A package to fit Rogers-Castro migration models, `rcbayes`, is on [CRAN](https://cran.uib.no/web/packages/rcbayes/index.html).
- I am a contributor to the [DemoTools](https://timriffe.github.io/DemoTools/) R package.
- I made a children's book in R called ['D is for Demography'](https://github.com/MJAlexander/d_is_for_demography). My toddler prefers 'The Very Hungry Caterpillar' or 'Wombat Stew'.
- [This repo](https://github.com/MJAlexander/states-mortality) on my GitHub has various bits and pieces of code, mostly related to mortality, but some other stuff too.
- [Shiny app](https://monica-alexander.shinyapps.io/babynames_app/) to explore baby names in Australia, Ontario, and USA
<file_sep>/content/posts/2018-21-12-lifespan.html
---
title: "Lifespan variation as a measure of mortality progress and inequality"
author: "<NAME>"
date: "2018-12-21"
output: html_document
---
<div id="introduction" class="section level2">
<h2>Introduction</h2>
<p>This post looks at how variation in lifespan has evolved over time for different states in the US, and how this measure complements trends in life expectancy. I was inspired to write this after hearing a great talk by <NAME> last week at MPIDR and reading her latest <a href="http://science.sciencemag.org/content/362/6418/1002">paper</a> on the topic.</p>
<p>One of the most common aggregate measure of mortality we tend to look at is life expectancy. The formal definition of (period) life expectancy at birth is the average number of years someone would live if the current age-specific mortality rates did not change in future. Given that age-specific mortality rates are generally improving over time, this isn’t really a realistic measure of longevity<a href="#fn1" class="footnoteRef" id="fnref1"><sup>1</sup></a>, but it’s a useful way of summarizing mortality at all ages into one number.</p>
<p>The ‘expectancy’ part of the name comes from the fact that life expectancy is an average, or expectation. Of all the deaths that happen in a population, we are just looking at the average age at which they occur. However, there are many other ways of summarizing distributions with one number: for example, the median or mode age at death. Another such measure — lifespan variation — captures the variation in ages at death.</p>
<p>As an example, the figure below shows the distribution of ages at deaths for Californian males in 1960 and 2010. (These data are from the <a href="https://usa.mortality.org/">HMD US states project</a>). Notice that the distribution has shifted to the right, which corresponds to improving mortality and increased life expectancy (as shown by the vertical lines). In addition, notice that the distribution in 2010 is not as spread out — the distribution of deaths is more concentrated around the mean age. That is, variation in lifespan has decreased from 1960 to 2010.</p>
<div class="figure">
<img src="/img/dx_CA.png" width="600" />
</div>
<p>Increases in life expectancy are usually coupled with decreases in lifespan variation. This is due to the fact that life expectancy increases usually occur because of improvements in infant mortality (which leads to a decrease in the spike observed in the first-year mortality) and decreases in premature deaths (e.g. decreases in cardiovascular diseases). However, as <NAME> and coauthors point out, this relationship of increasing life expectancy and decreasing lifespan variation is not always the case, and recently there has been a reversal of the trend for many populations.</p>
<p>I’ll briefly describe one way to calculate lifespan variation and show trends by US state. Note that all data come from the <a href="https://usa.mortality.org/">HMD US states Project</a>.</p>
</div>
<div id="measuring-lifespan-variation" class="section level2">
<h2>Measuring lifespan variation</h2>
<p>There are several different ways of measuring lifespan variation. In this post, I use the standard deviation of age of death, which can be calculated from lifetable quantities as</p>
<p><span class="math display">\[
\sqrt{\sum_0^\omega \frac{\left(x - e_0 \right)^2d_x}{\sum_0^\omega d_x}}
\]</span></p>
<p>where <span class="math inline">\(e_0\)</span> is life expectancy at birth, <span class="math inline">\(d_x\)</span> is the lifetable deaths at age <span class="math inline">\(x\)</span> and <span class="math inline">\(\omega\)</span> is the open age interval (110+ in the case of HMD data).</p>
<p>There are many other options to calculate, including: standard deviation from age 10 (which eliminates the effects of child mortality, see <a href="https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1728-4457.2005.00092.x"><NAME></a>); interquartile range; life disparity (<span class="math inline">\(e^\dagger\)</span>) (e.g. see the new paper by <a href="https://link.springer.com/article/10.1007/s13524-018-0729-9?wt_mc=alerts.TOCjournals"><NAME></a>). I chose standard deviation because I find it intuitive and it’s easy to calculate based on lifetable columns. However, other measures would probably show similar trends.</p>
</div>
<div id="lifespan-variation-in-the-us" class="section level2">
<h2>Lifespan variation in the US</h2>
<p>The plot below shows life expectancy at birth and lifespan variation for the United States (data from <a href="https://www.mortality.org">HMD</a>). The recent decline in life expectancy in the United States has gained a lot of <a href="https://www.washingtonpost.com/national/health-science/us-life-expectancy-declines-again-a-dismal-trend-not-seen-since-world-war-i/2018/11/28/ae58bc8c-f28c-11e8-bc79-68604ed88993_story.html?noredirect=on&utm_term=.9fc59cc5fb08">attention</a>. However, note that lifespan variation started to increase before life expectancy started to plateau/decrease.</p>
<div class="figure">
<img src="/img/USA.png" width="600" />
</div>
<p>Looking by state, life expectancy has increased everywhere, with recent evidence of plateauing and declining in some states (note that these data are only up to 2015, so the declines would be more apparent with more recent data). On the other hand, lifespan variation has generally declined, but plateaued much earlier than life expectancy. An increase in lifespan variation is apparent for some states, including some New England and Mid-West states.</p>
<div class="figure">
<img src="/img/facet.png" width="5600" />
</div>
<p>For example, the plots below show life expectancy and lifespan variation for New Hampshire and West Virginia, two states that have been <a href="https://github.com/mkiang/opioid_hotspots">hardest hit by the opioid epidemic</a>. For these states, lifespan variation has increased back up to the level it was in the 1980s-90s.</p>
<div class="figure">
<img src="/img/NH_WV.png" width="800" />
</div>
<p>It’s also interesting to compare trends in states that have a similar life expectancy. For instance, comparing Georgia and Ohio, the latter has experienced a much more pronounced increase in lifespan in recent years.</p>
<div class="figure">
<img src="/img/GA_OH.png" width="800" />
</div>
</div>
<div id="summary" class="section level2">
<h2>Summary</h2>
<p>Lifespan variation is easily calculable from lifetable quantities, and is an interesting measure of mortality progress and inequality. Even if life expectancy is increasing, the variation of lifespan could also be increasing, which suggests increased inequality in death – while a proportion of the population are dying at older ages, there is also an increased proportion dying prematurely. Increased variation in the age of death means greater uncertainty around timing of death, which has implications for how people think about their future.</p>
<p>All data are freely available and the code I used to generate plots etc is available on my <a href="https://github.com/MJAlexander/states-mortality">GitHub</a>.</p>
</div>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Follow <a href="https://twitter.com/les_ja"><NAME></a> on Twitter for amusing rants on people misinterpreting life expectancies.<a href="#fnref1">↩</a></p></li>
</ol>
</div>
<file_sep>/content/contact.md
+++
title = "Contact"
slug = "contact"
+++
I have offices in both the Statistical Sciences Department (Level 9, 700 University Ave, Toronto) and the Sociology Department (Level 3, 725 Spadina Avenue, Toronto).
My email is <EMAIL>.
<!-- I receive many emails from prospective students before they get entry to the U of T graduate program. Unfortunately the nature of the admissions process means that until you are admitted I'm not much use to you. Once you're admitted I'm more than happy to supervise you or discuss your research. --><file_sep>/content/women.md
+++
title = "Women in demography"
slug = "women_scholars_old"
+++
An ever-growing list of active scholars in demography who identify as women or as a gender minority, listed by broad sub-disicpline, and with two notable papers.[^1]
[^1]: Thanks to <NAME>, <NAME>, <NAME> and <NAME> for their help in compiling the initial list.
If you know of someone who should be on this list and isn't, or if you are on this list and would like different papers highlighted, or if you see any mistakes, email me!
Jump to:
- [Family, social demography](#family-social-demography)
- [Fertility](#fertility)
- [Mathematical, statistical, digital demography, population projection](#mathematical-statistical-digital-demography-population-projection)
- [Migration, environment, economic demography](#migration-environment-economic-demography)
- [Mortality, health, aging, biodemography](#mortality-health-aging-biodemography)
## Family, social demography
### [<NAME>](https://sociology.stanford.edu/people/aliya-saperstein)
- [Racial Fluidity and Inequality in the United States](https://doi.org/10.1086/667722)
- [Racial Formation in Perspective: Connecting Individuals, Institutions, and Power Relations](https://doi.org/10.1146/annurev-soc-071312-145639)
### [Sunita Kishor](https://www.icf.com/company/about/our-people/k/kishor-sunita)
- [Reproductive health and domestic violence: Are the poorest women uniquely disadvantaged?](https://doi.org/10.1353/dem.2006.0014)
- [Married Women's Risk of STIs in Developing Countries: The Role of Intimate Partner Violence and Partner's Infection Status](https://doi.org/10.1177/1077801212455358)
### [<NAME>](https://www.popcenter.umd.edu/mprc-associates/mdasgupt )
- [Selective Discrimination against Female Children in Rural Punjab, India](https://www.jstor.org/stable/1972121)
- [Death Clustering, Mothers' Education and the Determinants of Child Mortality in Rural Punjab, India](https://doi.org/10.1080/0032472031000144866)
### [<NAME>](https://aasd.umd.edu/facultyprofile/madhavan/sangeetha)
- ['Absent breadwinners': Father-child connections and paternal support in rural South Africa](https://doi.org/10.1080/03057070802259902)
- [The social context of children's nutritional status in rural South Africa](https://doi.org/10.1080/14034950701355700)
### [<NAME>](https://www.sc.edu/study/colleges_schools/artsandsciences/sociology/our_people/faculty_staff_directory/augustine_jennifer.php)
- [Doing it All? Mothers’ College Enrollment, Time Use, and Affective Well-Being](https://onlinelibrary.wiley.com/doi/abs/10.1111/jomf.12477)
- [Can Increased Educational Attainment among Lower Educated Mothers Reduce Inequalities in the Skill Development of Children? ](https://link.springer.com/article/10.1007/s13524-017-0637-4)
### [<NAME>](https://www.popcenter.umd.edu/mprc-associates/chrisbachrach)
- [A Cognitive-Social Model of Fertility Intentions](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4132897/)
- [Culture and Demography: From Reluctant Bedfellows to Committed Partners](https://link.springer.com/content/pdf/10.1007/s13524-013-0257-6.pdf)
### [<NAME>](https://devsoc.cals.cornell.edu/people/alaka-basu/)
- [The Sociocultural and Political Aspects of Abortion: Global Perspectives](https://books.google.ca/books?hl=en&lr=&id=YNY8NqdsA6UC&oi=fnd&pg=PP13&dq=The+Social+and+Political+Context+of+Abortion+basu&ots=l1t2WhWdmL&sig=BvGr6jpvoh7caAVlUrHs3nRRC4E#v=onepage&q=The%20Social%20and%20Political%20Context%20of%20Abortion%20basu&f=false)
- [Conditioning Factors for Fertility Decline in Bengal: History, Language Identity, and Openness to Innovations](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1728-4457.2000.00761.x)
### [<NAME>](https://www.sociology.northwestern.edu/people/faculty/core/julia-behrman.html)
- [Do Targeted Stipend Programs Reduce Gender and Socioeconomic Inequalities in Schooling Attainment? Insights From Rural Bangladesh](https://link.springer.com/article/10.1007/s13524-015-0435-9)
- [Contextual Declines in Educational Hypergamy and Intimate Partner Violence](https://academic.oup.com/sf/article-abstract/97/3/1257/5078440)
### [<NAME>](https://www.southampton.ac.uk/demography/about/staff/amb6.page)
- [Perpetual postponers? Women's, men's and couple's fertility intentions and subsequent fertility behaviour](https://eprints.soton.ac.uk/34148/)
- [Marital dissolution among the 1958 British birth cohort: The role of cohabitation](https://www.tandfonline.com/doi/abs/10.1080/00324720308066)
### [<NAME>](https://sites.google.com/view/valeriabordone)
- [Contact and proximity of older people to their adult children: A comparison between Italy and Sweden](https://onlinelibrary.wiley.com/doi/abs/10.1002/psp.559)
- [Patterns of grandparental child care across Europe: the role of the policy context and working mothers' need](https://www.cambridge.org/core/journals/ageing-and-society/article/patterns-of-grandparental-child-care-across-europe-the-role-of-the-policy-context-and-working-mothers-need/FD999CE0803BE444D37D1A9CD69C7175)
### [<NAME>](https://sociology.wisc.edu/staff/carlson-marcy/)
- [Family structure and children's behavioral and cognitive outcomes](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1741-3737.2001.00779.x)
- [Union formation in fragile families](https://link.springer.com/article/10.1353/dem.2004.0012)
### [<NAME>](https://www.katehchoi.com/)
- [Fertility in the context of Mexican migration to the United States: A case for incorporating the pre-migration fertility of immigrants](https://www.jstor.org/stable/26348215?seq=1#metadata_info_tab_contents)
- [Marriage‐Market Constraints and Mate‐Selection Behavior: Racial, Ethnic, and Gender Differences in Intermarriage](https://onlinelibrary.wiley.com/doi/abs/10.1111/jomf.12346)
### [<NAME>](https://www.mcgill.ca/sociology/contact-us/faculty/clark)
- [The impact of childcare on poor urban Women’s economic empowerment in Africa](https://link.springer.com/article/10.1007/s13524-019-00793-3#:~:text=This%20randomized%20control%20trial%20study,women's%20participation%20in%20paid%20work.&text=These%20findings%20demonstrate%20that%20the,marital%20status%20and%20across%20outcomes.)
- [Divorce in Sub-Saharan Africa: Are Unions Becoming Less Stable?](https://www.jstor.org/stable/24638576#metadata_info_tab_contents)
### [<NAME>](https://scholar.google.com/citations?user=dgf4d9gAAAAJ&hl=en)
- [White and Latino locational attainments: Assessing the role of race and resources in US metropolitan residential segregation](https://journals.sagepub.com/doi/abs/10.1177/2332649217748426)
- [The Unique Case of Minneapolis–St. Paul, MN: Locational Attainments and Segregation in the Twin Cities](https://link.springer.com/content/pdf/10.1007/s40980-019-00056-0.pdf)
### [<NAME>](https://web.uniroma1.it/memotef/en/users/de-rose-alessandra)
- [Italy: Delayed adaptation of social institutions to changes in family behaviour](https://www.jstor.org/stable/26349260)
- [Socio-Economic Factors and Family Size as Determinants of Marital Dissolution in Italy](https://doi.org/10.1093/oxfordjournals.esr.a036623)
### [<NAME>](https://www.sonaldedesai.org/)
- [Gender scripts and age at marriage in India](https://link.springer.com/article/10.1353/dem.0.0118)
- [Maternal education and child health: Is there a strong causal relationship?](https://link.springer.com/article/10.2307/3004028)
### [<NAME>](https://researchers.anu.edu.au/researchers/evans-aa)
- [Negotiating the Life Course: Stability and Change in Life Pathways](https://books.google.ca/books?hl=en&lr=&id=Tnq9aOqsJ6EC&oi=fnd&pg=PR5&dq=info:5eeNfNsOTjEJ:scholar.google.com&ots=XPUErOyzV-&sig=360RlSD9LFOnqOq_et_FM6QVpuM&redir_esc=y#v=onepage&q&f=false)
- [The influence of significant others on Australian teenagers' decisions about pregnancy resolution](https://www.jstor.org/stable/2673786?seq=1#metadata_info_tab_contents)
### [<NAME>](https://www.wzb.eu/en/persons/anette-eva-fasang)
- [The" second wave" of sequence analysis bringing the" course" back into the life course](https://journals.sagepub.com/doi/abs/10.1177/0049124109357532)
- [The interplay of work and family trajectories over the life course: Germany and the United States in comparison](https://www.journals.uchicago.edu/doi/abs/10.1086/691128)
### [<NAME>](https://pop.umn.edu/people/sarah-flood)
- [Time for each other: Work and family constraints among couples](https://onlinelibrary.wiley.com/doi/abs/10.1111/jomf.12255)
- [Healthy Time Use in the Encore Years: Do Work, Resources, Relations, and Gender Matter?](https://journals.sagepub.com/doi/abs/10.1177/0022146514568669)
### [<NAME>](https://lsa.umich.edu/soc/people/faculty/margaret-frye.html)
- [Bright futures in Malawi’s new dawn: Educational aspirations as assertions of identity](https://www.journals.uchicago.edu/doi/abs/10.1086/664542)
- [The demography of words: The global decline in non-numeric fertility preferences, 1993–2011](https://www.tandfonline.com/doi/abs/10.1080/00324728.2017.1304565)
### [<NAME>](https://t.co/BMHJq9QVCr?amp=1)
- [The impact of family policies on fertility in industrialized countries: a review of the literature](https://link.springer.com/article/10.1007/s11113-007-9033-x)
- [Generations and Gender Survey study profile. Longitudinal and Life Course Studies](https://www.llcsjournal.org/index.php/llcs/article/view/500)
### [<NAME>](https://scholar.google.com/citations?user=bFhMJ0sAAAAJ&hl=en)
- [No-fault divorce laws and the labor supply of women with and without children](http://jhr.uwpress.org/content/XLII/1/247.short)
- [Trends in spouses’ shared time in the United States, 1965–2012](https://link.springer.com/content/pdf/10.1007/s13524-016-0512-8.pdf)
### [<NAME>](http://susan-greenhalgh.com/)
- [Just One Child: Science and Policy in Deng’s China](https://www.ucpress.edu/book/9780520253391/just-one-child)
- [On the Crafting of Population Thought](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1728-4457.2012.00474.x)
### [<NAME>](https://www.bgsu.edu/arts-and-sciences/sociology/people/karen-benjamin-guzzo.html)
- [Multipartnered fertility among American men](https://link.springer.com/article/10.1353/dem.2007.0027)
- [Marital intentions and the stability of first cohabitations](https://journals.sagepub.com/doi/abs/10.1177/0192513x08323694)
### [<NAME>](https://sociology.sas.upenn.edu/people/harknett)
- [The relationship between private safety nets and economic outcomes among single mothers](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1741-3737.2006.00250.x)
- [Do family support environments influence fertility? Evidence from 20 European countries](https://link.springer.com/content/pdf/10.1007/s10680-013-9308-3.pdf)
### [<NAME>](https://dornsife.usc.edu/cf/soci/soci_faculty_display.cfm?Person_ID=1042774)
- [Care in context: Men's unpaid work in 20 countries, 1965–2003](https://journals.sagepub.com/doi/abs/10.1177/000312240607100406)
- [Gender inequality in the welfare state: Sex segregation in housework, 1965–2003](https://www.journals.uchicago.edu/doi/abs/10.1086/651384)
### [<NAME>](https://www.researchgate.net/profile/Vladimira_Kantorova)
- [Education And Entry Into Motherhood In The Czech Republic During State-Socialism And The Transition Period 1970-1997](https://doi.org/10.1007/1-4020-4716-9_10)
- [Setting Ambitious yet Achievable Targets Using Probabilistic Projections: Meeting Demand for Family Planning](https://doi.org/10.1111/sifp.12025)
### [<NAME>](https://www.waikato.ac.nz/nidea/people/tahuk)
- [In search of ethnic New Zealanders: National naming in the 2006 census](https://www.msd.govt.nz/documents/about-msd-and-our-work/publications-resources/journals-and-magazines/social-policy-journal/spj36/social-policy-journal-36.pdf#page=51)
- [White Mothers, Brown Children: Ethnic Identification of Maori‐European Children in New Zealand](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1741-3737.2007.00438.x)
### [<NAME>](https://danyalagos.com/)
- [Hearing Gender: Voice-Based Gender Classification Processes and Transgender Health Inequality](https://journals.sagepub.com/doi/abs/10.1177/0003122419872504)
- [Looking at population health beyond “male” and “female”: Implications of transgender identity and gender nonconformity for population health](https://link.springer.com/content/pdf/10.1007/s13524-018-0714-3.pdf)
### [<NAME>](https://mcgill.ca/sociology/contact-us/faculty/lebourdais)
- [Changes in conjugal life in Canada: Is cohabitation progressively replacing marriage?](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.0022-2445.2004.00063.x?casa_token=<PASSWORD>urWn66jHC0VyR16VbnGBCPp4-Yp3KMv3pt5iUfnFn4i31fGTglIhjvxU4q0vxV8E)
- [Impact of Conjugal Separation on Women’s Income in Canada – Does the Type of Union Matter](https://www.demographic-research.org/volumes/vol35/50/)
### [<NAME>](https://socialsciences.calpoly.edu/faculty/sara-lopus)
- [Relatives in Residence: Relatedness of Household Members Drives Schooling Differentials in Mozambique](https://onlinelibrary.wiley.com/doi/abs/10.1111/jomf.12393)
- [Visualizing Africa’s Educational Gender Gap](https://journals.sagepub.com/doi/full/10.1177/2378023118795956)
### [<NAME>](https://soc.washington.edu/people/hedwig-hedy-lee)
- [A Heavy Burden? The Health Consequences of Having a Family Member Incarcerated](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3953802/)
- [Racial inequalities in connectedness to imprisoned individuals in the United States](https://www.cambridge.org/core/journals/du-bois-review-social-science-research-on-race/article/racial-inequalities-in-connectedness-to-imprisoned-individuals-in-the-united-states/D015904ED108B3B0A18454450104845A)
### [<NAME>](https://www.bgsu.edu/arts-and-sciences/sociology/people/wendy-d-manning.html)
- [Adolescent well‐being in cohabiting, married, and single‐parent families](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1741-3737.2003.00876.x)
- [Measuring and modeling cohabitation: New perspectives from qualitative data](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1741-3737.2005.00189.x)
### [<NAME>](https://sociology.cornell.edu/vida-maralani)
- [The Changing Relationship between Family Size and Educational Attainment over the Course of Socioeconomic Development: Evidence from Indonesia](https://link.springer.com/article/10.1353/dem.0.0013)
- [From GED to College: Age Trajectories of Nontraditional Educational Paths](https://journals.sagepub.com/doi/abs/10.3102/0002831211405836)
### [<NAME>](https://www.rachelmargolis.net/)
- [A global perspective on happiness and fertility](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1728-4457.2011.00389.x)
- [The Changing Demography of Grandparenthood](https://onlinelibrary.wiley.com/doi/abs/10.1111/jomf.12286)
### [<NAME>](https://liberalarts.utexas.edu/prc/directory/faculty/ljm86)
- [Live Births and Fertility Amid the Zika Epidemic in Brazil](https://link.springer.com/content/pdf/10.1007/s13524-020-00871-x.pdf)
- [Women’s reproductive intentions and behaviors during the Zika epidemic in Brazil](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6663086/)
### [<NAME>](https://letiziamencarini.com/)
- [Life Satisfaction Favors Reproduction. The Universal Positive Effect of Life Satisfaction on Childbearing in Contemporary Low Fertility Countries](https://doi.org/10.1371/journal.pone.0206202)
- [Employed Women and Marital Union Stability: It Helps When Men Help](https://doi.org/10.1177/0192513X17710283)
### [<NAME>](https://scholar.google.co.uk/citations?user=GhqmkD8AAAAJ&hl=en)
- [Divorce, Separation, and Housing Changes: A Multiprocess Analysis of Longitudinal Data from England and Wales](https://link.springer.com/article/10.1007/s13524-017-0640-9)
- [Short-and long-term effects of divorce and separation on housing tenure in England and Wales](https://www.tandfonline.com/doi/full/10.1080/00324728.2017.1391955)
### [<NAME>](https://melissamilkie.com/)
- [Playing all the roles: Gender and the work-family balancing act](https://www.jstor.org/stable/353763?seq=1#metadata_info_tab_contents)
- [The time squeeze: Parental statuses and feelings about time with children](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.0022-2445.2004.00050.x)
### [<NAME>](https://www.sociology.ox.ac.uk/academic-staff/melinda-mills.html)
- [Why do people postpone parenthood? Reasons and social policy incentives](https://academic.oup.com/humupd/article/17/6/848/871500)
- [Globalization, uncertainty and the early life course](https://link.springer.com/article/10.1007/s11618-003-0023-4)
### [<NAME>](https://www.human.cornell.edu/people/kam386)
- [Reexamining the case for marriage: Union formation and changes in well‐being](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1741-3737.2011.00873.x)
- [Planned and unplanned childbearing among unmarried women](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1741-3737.2002.00915.x)
### [<NAME>](https://danielanegraia.weebly.com/publications.html)
- [Unpacking the Parenting Well-Being Gap: The Role of Dynamic Features of Daily Life across Broader Social Contexts](https://journals.sagepub.com/doi/10.1177/0190272520902453)
- [Gender Disparities in Parenting Time Across Activities, Child Ages, and Educational Groups](https://journals.sagepub.com/doi/10.1177/0192513X18770232)
### [<NAME>](https://cde.wisc.edu/staff/nobles-jenna/)
- [Parenting from abroad: Migration, nonresident father involvement, and children's education in Mexico](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1741-3737.2011.00842.x)
- [The effects of mortality on fertility: population dynamics after a natural disaster](https://link.springer.com/content/pdf/10.1007/s13524-014-0362-1.pdf)
### [<NAME>](https://www.bgsu.edu/arts-and-sciences/sociology/people/kei-m-nomaguchi.html)
- [Costs and rewards of children: The effects of becoming a parent on adults' lives](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1741-3737.2003.00356.x)
- [Exercise time: Gender differences in the effects of marriage, parenthood, and employment](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1741-3737.2004.00029.x)
### [<NAME>](https://law.vanderbilt.edu/bio/evelyn-patterson)
- [Incarcerating death: Mortality in US state correctional facilities, 1985–1998](https://link.springer.com/article/10.1353/dem.0.0123)
- [Estimating mean length of stay in prison: methods and applications](https://link.springer.com/content/pdf/10.1007/s10940-007-9037-z.pdf)
### [<NAME>](https://www.psc.isr.umich.edu/people/profile/1522/Sarah_Patterson)
- [The Demography of Multigenerational Caregiving: A Critical Aspect of the Gendered Life Course](https://journals.sagepub.com/doi/full/10.1177/2378023119862737)
- [Educational Attainment Differences in Attitudes toward Provisions of IADL Care for Older Adults in the US](https://www.tandfonline.com/doi/abs/10.1080/08959420.2020.1722898)
### [<NAME>](https://cls.ucl.ac.uk/team/alina-pelikh/)
- [Short‐and long‐distance moves of young adults during the transition to adulthood in Britain](https://onlinelibrary.wiley.com/doi/abs/10.1002/psp.2125)
- [Preschool services for children: Cross-national analysis of factors affecting use](https://journals.sagepub.com/doi/abs/10.1177/0020872814536415)
### [<NAME>](https://www.southampton.ac.uk/demography/about/staff/bgph1c10.page)
- [The educational gradient of childbearing within cohabitation in Europe](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1728-4457.2010.00357.x)
- [Changes in union status during the transition to parenthood in eleven European countries, 1970s to early 2000s](https://www.tandfonline.com/doi/abs/10.1080/00324728.2012.673004)
### [<NAME>](http://www.kateprickett.com/)
- [A research note on time with children in different-and same-sex two-parent families](https://link.springer.com/article/10.1007/s13524-015-0385-2)
- [Maternal education and investments in children's health](https://onlinelibrary.wiley.com/doi/abs/10.1111/jomf.12253)
### [<NAME>](https://sociology.ubc.ca/profile/yue-qian/)
- [Gender Asymmetry in Educational and Income Assortative Marriage](https://onlinelibrary.wiley.com/doi/abs/10.1111/jomf.12372)
- [Women's Fertility Autonomy in Urban China: The Role of Couple Dynamics Under the Universal Two-Child Policy](https://www.tandfonline.com/doi/abs/10.1080/21620555.2018.1428895)
### [<NAME>](https://liberalarts.utexas.edu/sociology/faculty/kraley)
- [The topography of the divorce plateau: Levels and trends in union stability in the United States after 1980](https://www.jstor.org/stable/26348083?seq=1#metadata_info_tab_contents)
- [Cohabitation and children's family instability](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.0022-2445.2004.00014.x-i1)
### [<NAME>](https://www.brown.edu/academics/sociology/people/emily-rauscher)
- [Why Who Marries Whom Matters: Effects of Educational Assortative Mating on Infant Health in the United States 1969–1994](https://academic.oup.com/sf/article-abstract/98/3/1143/5498123?redirectedFrom=fulltext)
- [Does Educational Equality Increase Mobility? Exploiting Nineteenth-Century U.S. Compulsory Schooling Laws](https://www.journals.uchicago.edu/doi/abs/10.1086/685443)
### [<NAME>](https://www.ssc.wisc.edu/~cschwart/)
- [Trends in educational assortative marriage from 1940 to 2003](https://link.springer.com/article/10.1353/dem.2005.0036)
- [Earnings inequality and the changing association between spouses’ earnings](https://www.journals.uchicago.edu/doi/abs/10.1086/651373)
### [<NAME>](https://soc.ucla.edu/faculty/judith-seltzer)
- [The Family Safety Net of Black and White Multigenerational Families](https://onlinelibrary.wiley.com/doi/abs/10.1111/padr.12233)
- [Stepfamily Structure and Transfers Between Generations in U.S. Families](https://link.springer.com/article/10.1007%2Fs13524-018-0740-1)
### [<NAME>](http://www.lse.ac.uk/gender/people/people-profiles/faculty/wendy-sigle)
- [Why demography needs (new) theories](http://eprints.lse.ac.uk/86429/1/Sigle_Demography%20needs%20theories_2018.pdf)
- [Fertility in England and Wales: a policy puzzle?](http://eprints.lse.ac.uk/31320/)
### [<NAME>](http://emilysmithgreenaway.org/)
- [Maternal reading skills and child mortality in Nigeria: a reassessment of why education matters](https://link.springer.com/article/10.1007%252Fs13524-013-0209-1)
- [Polygynous contexts, family structure, and infant mortality in sub-Saharan Africa](https://link.springer.com/content/pdf/10.1007/s13524-013-0262-9.pdf)
### [<NAME>](https://hcap.utsa.edu/directory/johnelle-sparks-ph-d/)
- [Do biological, sociodemographic, and behavioral characteristics explain racial/ethnic disparities in preterm births?](https://www.sciencedirect.com/science/article/abs/pii/S0277953609001117)
- [Racial/ethnic differences in breastfeeding duration among WIC-eligible families](https://www.sciencedirect.com/science/article/abs/pii/S1049386711000466)
### [<NAME>](https://www.researchgate.net/profile/Sarah_Staveteig)
- [Fear, opposition, ambivalence, and omission: Results from a follow-up study on unmet need for family planning in Ghana](https://doi.org/10.1371/journal.pone.0182076)
- [Reaching the ' first 90 ': Gaps in coverage of HIV testing among people living with HIV in 16 African countries](https://doi.org/10.1371/journal.pone.0186316)
### [<NAME>](https://apps.ualberta.ca/directory/person/las5)
- [Parental divorce and child mental health trajectories](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1741-3737.2005.00217.x)
- [Marital transitions and mental health: are there gender differences in the short-term effects of marital status change?](https://www.sciencedirect.com/science/article/abs/pii/S027795360500393X)
### [<NAME>](https://homes.stat.unipd.it/marialetiziatanturri/)
- [Childless or childfree? Paths to voluntary childlessness in Italy](https://www.jstor.org/stable/25434658)
- [Economic well-being in old age in Italy: does having children make a difference?](https://www.jstor.org/stable/41430836)
### [<NAME>](https://www.columbianeurology.org/profile/setom)
- [Frailty and Fracture, Disability, and Falls: A Multiple Country Study From the Global Longitudinal Study of Osteoporosis in Women](https://doi.org/10.1111/jgs.12146)
- [Characterization of Dementia and Alzheimer's Disease in an Older Population: Updated Incidence and Life Expectancy With and Without Dementia](https://doi.org/10.2105/AJPH.2014.301935)
### [<NAME>](https://sociology.stanford.edu/people/florencia-torche)
- [The effect of maternal stress on birth outcomes: exploiting a natural experiment](https://link.springer.com/content/pdf/10.1007/s13524-011-0054-z.pdf)
- [Educational assortative mating and economic inequality: A comparative analysis of three Latin American countries](https://link.springer.com/article/10.1353/dem.0.0109)
### [<NAME>](https://sociology.uchicago.edu/directory/jenny-trinitapoli)
- [The Flexibility of Fertility Preferences in a Context of Uncertainty](https://onlinelibrary.wiley.com/doi/full/10.1111/padr.12114)
- [AIDS & Religious Life in Malawi: Rethinking How Population Dynamics Shape Culture](https://muse.jhu.edu/article/593159/pdf)
### [<NAME>](https://researchers.anu.edu.au/researchers/utomo-aj)
- [Women as secondary earners: Gendered preferences on marriage and employment of university students in modern Indonesia](https://www.tandfonline.com/doi/abs/10.1080/17441730.2012.646841)
- [Marrying up? Trends in age and education gaps among married couples in Indonesia](https://journals.sagepub.com/doi/abs/10.1177/0192513X14538023)
### [<NAME>](https://www.demografia.hu/en/staff-vargha-lili)
- [The Quantity‐Quality Tradeoff: A Cross‐Country Comparison of Market and Nonmarket Investments per Child in Relation to Fertility](https://onlinelibrary.wiley.com/doi/abs/10.1111/padr.12245?af=R&utm_campaign=Feed%3A+PopulationAndDevelopmentReview+%28Population+and+Development+Review%29&utm_medium=feed&utm_source=feedburner)
- [Household production and consumption over the life cycle: National Time Transfer Accounts in 14 European countries](https://www.demographic-research.org/volumes/vol36/32/default.htm)
### [<NAME>](https://ccpr.ucla.edu/watkins/)
- [If all we knew about women was what we read in Demography, what would we know?](https://link.springer.com/article/10.2307/2061806)
- [Demographic Foundations of Family Change](https://www.jstor.org/stable/2095354?seq=1#metadata_info_tab_contents)
### [<NAME>](http://www.kateweisshaar.com/)
- [Labor Force Participation Over the Life Course: The Long-Term Effects of Employment Trajectories on Wages and the Gender Wage Gap](https://pubmed.ncbi.nlm.nih.gov/31997232/)
- [Publish and Perish? An Assessment of Gender Gaps in Promotion to Tenure in Academia](https://academic.oup.com/sf/article/96/2/529/3897008?guestAccessKey=edcee817-fdf5-4dbf-ad07-5ca46818a6c7)
### [<NAME>](https://artsandscience.usask.ca/profile/LWright#/profile)
- [Union Transitions and Fertility within First Premarital Cohahitations in Canada: Diverging Trends by Education](https://crdcn.org/union-transitions-and-fertility-within-first-premarital-cohabitations-canada-diverging-patterns)
- [Healthy Grandparenthood: How long is it and how has it Changed?](https://www.niussp.org/article/healthy-grandparenthood-how-long-is-it-and-how-has-it-changed/)
### [<NAME>](https://www.human.cornell.edu/people/yy567)
- [Leaving Home, Entering Institutions: Implications for Home-Leaving in the Transition to Adulthood](https://onlinelibrary.wiley.com/doi/abs/10.1111/jomf.12616)
- [Can Foster Care Interventions Diminish Justice System Inequality?](https://futureofchildren.princeton.edu/sites/futureofchildren/files/media/foc_vol_28.1_reducing_justice_compiled_5-1_0.pdf)
## Fertility
### [<NAME>](https://www.jhsph.edu/faculty/directory/profile/1025/amy-ong-tsui)
- [Family Planning and the Burden of Unintended Pregnancies](https://doi.org/10.1093/epirev/mxq012)
- [Contraceptive Practice in sub-Saharan Africa](https://doi.org/10.1111/padr.12051)
### [<NAME>](https://www.guttmacher.org/about/staff/ann-biddlecom)
- [Absent and problematic men: Demographic accounts of male reproductive roles](https://doi.org/10.1111/j.1728-4457.2000.00081.x)
- [Health care utilization, family context, and adaptation among immigrants to the United States](https://www.jstor.org/stable/2137215)
### [<NAME>](http://www.wittgensteincentre.org/en/staff/member/beaujouan.htm)
- [Repartnering in France: The role of gender, age and past fertility](https://www.sciencedirect.com/science/article/abs/pii/S1040260812000184)
- [Cohabitation and marriage in Britain since the 1970s](https://link.springer.com/article/10.1057/pt.2011.16)
### [<NAME>](https://www.linkedin.com/in/kristin-bietsch-81036386)
- [Family Planning During and After the West African Ebola Crisis](https://onlinelibrary.wiley.com/doi/full/10.1111/sifp.12110)
- [The Maximum CPR Model: a demographic tool for family planning policy](https://gatesopenresearch.org/articles/3-1736)
### [<NAME>](https://www.mcgill.ca/sociology/contact-us/faculty/brauner-otto)
- [The spread of health services and fertility transition](https://link.springer.com/article/10.1353/dem.2007.0041)
- [Parental family experiences, the timing of first sex, and contraception](https://www.sciencedirect.com/science/article/abs/pii/S0049089X10001316)
### [<NAME>](https://iussp.org/en/directoryprofile/22396)
- [Mapping the Timing, Pace, and Scale of the Fertility Transition in Brazil](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1728-4457.2010.00330.x)
- [Fertility and development: evidence from Brazil](https://www.jstor.org/stable/3180829?seq=1#metadata_info_tab_contents)
### [<NAME>](https://sites.google.com/site/dianelcoffey/)
- [Pre-pregnancy body mass and weight gain during pregnancy in India and sub-Saharan Africa](https://sites.google.com/site/dianelcoffey/research/Coffey2015_PNAS.pdf?attredirects=0&d=1)
- [Costs and consequences of a cash transfer for hospital births in a rural district of Uttar Pradesh, India](https://sites.google.com/site/dianelcoffey/research/Coffey_2014_SSM.pdf?attredirects=0&d=1)
### [<NAME>outinho](https://orcid.org/0000-0002-2841-1480)
- [Live Births and Fertility amidst the Zika Virus Epidemic in Brazil](https://liberalarts.utexas.edu/zika/events/live-births-and-fertility-amidst-the-zika-virus-epidemic-in-brazil)
- [Life satisfaction in Brazil: an exploration of theoretical correlates and age, period and cohort variations using the World Values Survey (1991-2014)](https://www.scielo.br/scielo.php?pid=S0102-30982020000100151&script=sci_arttext&tlng=en)
### [<NAME>](https://www.sarahkcowan.org/)
- [Enacted abortion stigma in the United States](https://www.sciencedirect.com/science/article/abs/pii/S0277953617300114)
- [Alternative estimates of lifetime prevalence of abortion from indirect survey questioning methods](https://d1wqtxts1xzle7.cloudfront.net/58636729/Cowan_Wu_England_Makela_Lifetime_Estimates_Abortion_Prevalence.pdf?1552766990=&response-content-disposition=inline%3B+filename%3DAlternative_Estimates_of_Lifetime_Preval.pdf&Expires=1595636437&Signature=Q5oJr6kvzHTJ8QcT7E6yg2Hc07YpMsEhszwyyynQO5bYlerrz4H~mlVrQavw-GRbiqW361-0LCnfOdkLMYcLfWz43DFeCg44ZdizDYJ~7uGY9sE2Zbf8HSVdfd7HRjFnBAa4Dh6hfX7-uYRlWTXU8CO<KEY> <KEY>
### [<NAME>](https://www.alisongemmill.com/)
- [From Some to None? Fertility Expectation Dynamics of Permanently Childless Women](https://pubmed.ncbi.nlm.nih.gov/30430426/)
- [Reduced fecundity in HIV-positive women](https://pubmed.ncbi.nlm.nih.gov/29579247/)
### [<NAME>](https://researchers.anu.edu.au/researchers/gray-ee)
- [Childbearing desires of childless men and women: When are goals adjusted?](https://www.sciencedirect.com/science/article/abs/pii/S1040260812000548)
- [Using a reproductive life course approach to understand contraceptive method use in Australia](https://search.proquest.com/openview/1cbbecd902d54618ddba532e7097ddbd/1?pq-origsite=gscholar&cbl=34392)
### [<NAME>](https://sc.edu/study/colleges_schools/artsandsciences/sociology/our_people/faculty_staff_directory/hartnett_caroline.php)
- [Racial Disparities in Emotional Well-Being during Pregnancy](https://journals.sagepub.com/doi/abs/10.1177/0022146520920259)
- [Births that are later-than-desired: correlates and consequences](https://link.springer.com/article/10.1007/s11113-019-09513-6)
### [<NAME>](https://sociology.berkeley.edu/faculty/jennifer-johnson-hanks)
- [Understanding Family Change and Variation](https://link.springer.com/chapter/10.1007%2F978-94-007-1945-3_1)
- [Natural Intentions: Fertility Decline in the African Demographic and Health Surveys](https://www.journals.uchicago.edu/doi/10.1086/508791)
### [<NAME>](http://somos.ufmg.br/professor/luciana-soares-luz-do-amaral)
- [Bridging user and provider perspectives: Family planning access and utilization in rural Mozambique](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4609646/)
- [Women’s decision-making autonomy and children’s schooling in rural Mozambique](https://pubmed.ncbi.nlm.nih.gov/26491400/)
### [<NAME>](https://globalhealth.duke.edu/people/merli-maria-giovanna)
- [Are births underreported in rural China? Manipulation of statistical records in response to China’s population policies](https://link.springer.com/article/10.2307/2648100)
- [Has the Chinese family planning policy been successful in changing fertility preferences?](https://link.springer.com/article/10.1353/dem.2002.0029)
### [<NAME>‐Ribeiro](http://somos.ufmg.br/professor/paula-de-miranda-ribeiro)
- [Fertility Differentials by Education in Brazil: From the Conclusion of Fertility to the Onset of Postponement Transition](https://onlinelibrary.wiley.com/doi/10.1111/padr.12165)
- [First conjugal union and religion: Signs contrary to the Second Demographic Transition in Brazil?](https://www.demographic-research.org/volumes/vol33/34/)
### [<NAME>](https://www.unige.ch/sciences-societe/ideso/membres/rossier/)
- [Estimating induced abortion rates: a review](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1728-4465.2003.00087.x)
- [Social interaction effects on fertility: Intentions and behaviors](https://link.springer.com/content/pdf/10.1007/s10680-009-9203-0.pdf)
### [<NAME>](https://www.lshtm.ac.uk/aboutus/people/sear.rebecca)
- [Evolutionary contributions to the study of human fertility](https://www.tandfonline.com/doi/abs/10.1080/00324728.2014.982905?journalCode=rpst20)
- [How much does family matter? The implications of a cooperative breeding strategy for the demographic transition](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1728-4457.2011.00379.x)
### [<NAME>](https://www.ined.fr/en/research/researchers/Trimarchi+Alessandra)
- [Education and the transition to fatherhood: The role of selection into union](https://doi.org/10.1007/s13524-016-0533-3)
- [Pathways to marital and non-marital first birth: the role of his and her education](https://www.jstor.org/stable/26506104)
### [<NAME>](https://heinivaisanen.com/)
- [Social Inequalities in Teenage Fertility Outcomes: Childbearing and Abortion Trends of Three Birth Cohorts In Finland](https://onlinelibrary.wiley.com/doi/abs/10.1363/46e1314)
- [The association between education and induced abortion for three cohorts of adults in Finland](https://www.tandfonline.com/doi/full/10.1080/00324728.2015.1083608)
### [<NAME>](http://gidr.ac.in/faculty/24)
- [Abortion in India: Ground Reality](https://books.google.ca/books/about/Abortion_in_India.html?id=E5IEAQAAIAAJ&redir_esc=y)
- [Abortion in India: Emerging Issues from Qualitative Studies](https://www.jstor.org/stable/4415809?seq=1#metadata_info_tab_contents)
### [<NAME>](https://webapps.unitn.it/du/en/Persona/PER0212776/Curriculum)
- [Preference theory and low fertility: A comparative perspective](https://link.springer.com/content/pdf/10.1007/s10680-009-9178-x.pdf)
- [Youth prospects in a time of economic recession](https://www.jstor.org/stable/26348180?seq=1#metadata_info_tab_contents)
## Mathematical, statistical, digital demography, population projection
### [<NAME>](https://www.prb.org/people/beth-jarosz/)
- [Using Assessor Parcel Data to Maintain Housing Unit Counts for Small Area Population Estimates](https://doi.org/10.1007/978-1-4020-8329-7_5)
- [Poisson Distribution: A Model for Estimating Households by Household Size](https://doi.org/10.1007/s11113-020-09575-x)
### [<NAME>](https://leontinealkema.github.io/alkema_lab/)
- [Probabilistic Projections of the Total Fertility Rate for All Countries](https://link.springer.com/content/pdf/10.1007/s13524-011-0040-5.pdf)
- [Global estimation of child mortality using a Bayesian B-spline bias-reduction model](https://www.jstor.org/stable/24522377?seq=1#metadata_info_tab_contents)
### [<NAME>](https://www.sdu.dk/en/forskning/forskningsenheder/samf/cpop/about_the_centre/our_people/cpop_dem/marie_pier_bergeron_boucher)
- [Decomposing changes in life expectancy: Compression versus shifting mortality](https://www.jstor.org/stable/26331991?seq=1#metadata_info_tab_contents)
- [Coherent forecasts of mortality with compositional data analysis](https://www.jstor.org/stable/26332204#metadata_info_tab_contents)
### [<NAME>](https://researchers.anu.edu.au/researchers/booth-h)
- [Demographic forecasting: 1980 to 2005 in review](https://www.sciencedirect.com/science/article/abs/pii/S016920700600046X)
- [Applying Lee-Carter under conditions of variable mortality decline](https://www.tandfonline.com/doi/abs/10.1080/00324720215935)
### [<NAME>](https://www.fengqingchao.com/)
- [Systematic assessment of the sex ratio at birth for all countries and estimation of national imbalances and regional reference level](https://www.pnas.org/content/116/19/9303)
- [National and regional under-5 mortality rate by economic status for low-income and middle-income countries: a systematic assessment](https://www.thelancet.com/action/showPdf?pii=S2214-109X%2818%2930059-7)
### [<NAME>](https://www.demogr.mpg.de/en/about_us_6113/staff_directory_1899/jutta_gampe_655)
- [Human mortality beyond age 110](https://www.demogr.mpg.de/en/publications_databases_6118/publications_1904/book_chapters/human_mortality_beyond_age_110_3980/)
- [Seasonal variation in death counts: P-spline smoothing in the presence of overdispersion](https://www.demogr.mpg.de/en/publications_databases_6118/publications_1904/book_chapters/seasonal_variation_in_death_counts_p_spline_smoothing_in_the_presence_of_overdispersion_1725/)
### [<NAME>](https://raquel-guimaraes.com/)
- [Uncertainty in population projections: the state of the art](https://www.scielo.br/scielo.php?pid=S0102-30982014000200003&script=sci_arttext)
- [The Demography of Skills-Adjusted Human Capital](http://pure.iiasa.ac.at/id/eprint/16477/)
### [<NAME>](https://www.nuffield.ox.ac.uk/people/profiles/ridhi-kashyap/)
- [An agent-based model of sex ratio at birth distortions](https://link.springer.com/chapter/10.1007/978-3-319-32283-4_12)
- [Using Facebook ad data to track the global digital gender gap](https://www.sciencedirect.com/science/article/pii/S0305750X18300883)
### [<NAME>](https://en.wikipedia.org/wiki/Evelyn_M._Kitagawa)[^2]
- [Components of a difference between two rates](https://www.jstor.org/stable/2281213?seq=1#metadata_info_tab_contents)
- [Standardized comparisons in population research](https://www.jstor.org/stable/2060055?seq=1#metadata_info_tab_contents)
[^2]: Passed away in 2007, but was such an important and influential woman scholar in demography.
### [<NAME>](http://www2.stat-athens.aueb.gr/~akostaki/)
- [A nine‐parameter version of the Heligman‐Pollard formula](https://doi.org/10.1080/08898489209525346)
- [Expanding an abridged life table](https://www.jstor.org/stable/26348031)
### [<NAME>](https://sociology.la.psu.edu/people/lzl65)
- [The Age-Period-Cohort-Interaction Model for Describing and Investigating Inter-cohort Deviations and Intra-cohort Life-course Dynamics](https://journals.sagepub.com/doi/10.1177/0049124119882451)
- [The Sensitivity of the Intrinsic Estimator to Coding Schemes: A Comment on Yang, Schulhofer-Wohl, Fu, and Land](https://www.journals.uchicago.edu/doi/abs/10.1086/689830?mobileUi=0)
### [<NAME>](https://en.wikipedia.org/wiki/Jane_Menken)
- [On Becoming a Mathematical Demographer—And the Career in Problem-Focused Inquiry that Followed](https://www.annualreviews.org/doi/pdf/10.1146/annurev-soc-073117-041059)
- [Age and infertility](https://science.sciencemag.org/content/233/4771/1389.abstract)
### [<NAME>](https://globalhealth.washington.edu/faculty/julie-rajaratnam)
- [Measuring under-five mortality: Validation of new low-cost methods](https://journals.plos.org/plosmedicine/article?id=10.1371/journal.pmed.1000253)
- [Worldwide mortality in men and women aged 15–59 years from 1970 to 2010: a systematic analysis](https://www.thelancet.com/journals/lancet/article/PIIS0140-6736%2810%2960517-X/fulltext)
### [<NAME>](https://www.stat.washington.edu/hana/)
- [Assessing uncertainty in urban simulations using Bayesian melding](https://doi.org/10.1016/j.trb.2006.11.001)
- [bayesTFR: An R Package for Probabilistic Projections of the Total Fertility Rate](https://doi.org/10.18637/jss.v043.i01)
### [<NAME>](https://coss.fsu.edu/sociology/mtaylor)
- [Timing, Accumulation, and the Black/White Disability Gap in Later Life: A Test of Weathering](https://journals.sagepub.com/doi/abs/10.1177/0164027507311838)
- [Cohort Differences and Chronic Disease Profiles of Differential Disability Trajectories](https://academic.oup.com/psychsocgerontology/article/66B/6/729/591502)
### [<NAME>](https://www.ssc.wisc.edu/~efield/)
- [Mortality deceleration and mortality selection: Three unexpected implications of a simple model](https://link.springer.com/content/pdf/10.1007/s13524-013-0256-7.pdf)
- [Multidimensional Mortality Selection: Why Individual Dimensions of Frailty Don’t Act Like Frailty](https://link.springer.com/content/pdf/10.1007/s13524-020-00858-8.pdf)
### [<NAME>](http://www.wittgensteincentre.org/en/staff/member/yildiz.htm)
- [Estimating population counts with capture-recapture models in the context of erroneous records in linked administrative data](https://www.oeaw.ac.at/fileadmin/subsites/Institute/VID/PDF/Publications/Working_Papers/WP2017_15.pdf)
- [Using Twitter data for demographic research](https://www.demographic-research.org/volumes/vol37/46/)
### [<NAME>](https://www.bayesiandemography.com/people)
- [Likelihood-Based Analysis of Causal Effects of Job-Training Programs Using Principal Stratification](https://doi.org/10.1198/jasa.2009.0012)
- [Fully Bayesian Benchmarking of Small Area Estimation Models](https://doi.org/10.2478/JOS-2020-0010)
## Migration, environment, economic demography
### [<NAME>](https://www.ilr.cornell.edu/people/shannon-gleeson)
- [When Do Papers Matter? An Institutional Analysis of Undocumented Life in the United States](https://doi.org/10.1111/j.1468-2435.2011.00726.x)
- [Labor Rights for All? The Role of Undocumented Immigrant Status for Worker Claims Making](https://doi.org/10.1111/j.1747-4469.2010.01196.x)
### [<NAME>]([https://www.un.org/en/development/desa/newsletter/desanews/cg/2012/02/index.html)
- [International migration 1965-96: An overview](https://doi.org/10.2307/2808151)
- [The use of hypothetical cohorts in estimating demographic parameters under conditions of changing fertility and mortality](https://doi.org/10.2307/2061052)
### [<NAME>](https://www.utmb.edu/scoa/membership/rebeca-wong)
- [Cohort Profile: The Mexican Health and Aging Study (MHAS)](https://doi.org/10.1093/ije/dyu263)
- [Wealth in middle and old age in Mexico: The role of international migration](https://doi.org/10.1111/j.1747-7379.2007.00059.x)
### [<NAME>](https://www.gc.cuny.edu/Page-Elements/Academics-Research-Centers-Initiatives/Doctoral-Programs/Sociology/Faculty-Bios/Holly-Reed)
- [Men's and women's migration in coastal Ghana: An event history analysis](https://dx.doi.org/10.4054%2FDemRes.2010.22.25)
- [Moving Across Boundaries: Migration in South Africa, 1950-2000](https://doi.org/10.1007/s13524-012-0140-x)
### [<NAME>](https://www.colgate.edu/about/directory/ekraly)
- [Estimates Of Long-Term Immigration To The United-States - Moving United-States Statistics Toward United-Nations Concepts](https://doi.org/10.2307/2061855)
- [Efforts To Improve International Migration Statistics - A Historical Perspective](https://doi.org/10.2307/2546500)
### [<NAME>](https://www.researchgate.net/scientific-contributions/2141066464_Beth_Osborne_Daponte)
- [Why do low-income households not use food stamps? Evidence from an experiment](https://doi.org/10.2307/146382)
- [How the private food assistance network evolved: Interactions between public and private responses to hunger](https://doi.org/10.1177/0899764006289771)
### [<NAME>](https://gero.usc.edu/faculty/ailshire/)
- [Fine particulate matter air pollution and cognitive function among older US adults](https://doi.org/10.1093/aje/kwu155)
- [Family relationships and troubled sleep among US adults: examining the influences of contact frequency and relationship quality](https://doi.org/10.1177/0022146512446642)
### [<NAME>](https://sees.uq.edu.au/profile/10064/aude-bernard)
- [Life‐course transitions and the age profile of internal migration](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1728-4457.2014.00671.x)
- [Improved measures for the cross-national comparison of age profiles of internal migration](https://www.tandfonline.com/doi/abs/10.1080/00324728.2014.890243)
### [<NAME>](https://sociology.berkeley.edu/faculty/irene-bloemraad)
- [Who Claims Dual Citizenship? The Limits of Postnationalism, the Possibilities of Transnationalism, and the Persistence of Traditional Citizenship](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1747-7379.2004.tb00203.x)
- [The promise and pitfalls of comparative research design in the study of migration](https://academic.oup.com/migration/article/1/1/27/941988)
### [<NAME>](http://www.profjenniebrand.com/)
- [Who benefits most from college? Evidence for negative selection in heterogeneous economic returns to higher education](https://journals.sagepub.com/doi/abs/10.1177/0003122410363567)
- [Regression and matching estimates of the effects of elite college attendance on educational and career achievement](https://www.sciencedirect.com/science/article/abs/pii/S0049089X05000268)
### [<NAME>](https://sees.uq.edu.au/profile/9017/elin-charles-edwards)
- [Where people move and when: temporary population mobility in Australia](https://search.informit.com.au/documentSummary;dn=157293264384755;res=IELAPA)
- [Internal migration and development: Comparing migration intensities around the world](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1728-4457.2015.00025.x)
### [<NAME>](https://siweicheng.weebly.com/research.html)
- [A life course trajectory framework for understanding the intracohort pattern of wage inequality](https://www.journals.uchicago.edu/doi/abs/10.1086/679103)
- [The accumulation of (dis) advantage: The intersection of gender and race in the long-term wage effect of marriage](https://journals.sagepub.com/doi/abs/10.1177/0003122415621263)
### [<NAME>](https://soc.washington.edu/people/sara-curran)
- [Engendering migrant networks: The case of Mexican migration](https://link.springer.com/article/10.1353/dem.2003.0011)
- [Mapping gender and migration in sociological scholarship: Is it segregation or integration?](https://journals.sagepub.com/doi/abs/10.1111/j.1747-7379.2006.00008.x)
### [<NAME>](https://www.ncl.ac.uk/hca/staff/profile/violettahionidou.html)
- [Abortion and Contraception in Modern Greece, 1830-1967. Medicine, Sexuality and Popular Culture](https://doi.org/10.1007/978-3-030-41490-0)
- [‘If we hadn’t left … we would have all died’: Escaping Famine on the Greek Island of Chios, 1941–44](https://doi.org/10.1093/jrs/fez041)
### [<NAME>](https://dces.wisc.edu/people/faculty/katherine-curtis/)
- [Rural Demography](https://link.springer.com/book/10.1007/978-3-030-10910-3)
- [Recovery Migration after Hurricanes Katrina and Rita: Spatial Concentration and Intensification in the Migration System](https://pubmed.ncbi.nlm.nih.gov/26084982/)
### [<NAME>](https://sociology.arizona.edu/people/christina-diaz)
- [Moving beyond salmon bias: Mexican return migration and health selection](https://link.springer.com/content/pdf/10.1007/s13524-016-0526-2.pdf)
- [The effect(s) of teen pregnancy: Reconciling theory, methods, and findings](https://link.springer.com/content/pdf/10.1007/s13524-015-0446-6.pdf)
### [<NAME>](https://www.american.edu/cas/faculty/dondero.cfm)
- [School stratification in new and established Latino destinations](https://academic.oup.com/sf/article-abstract/91/2/477/2235792)
- [Generational status, neighborhood context, and mother-child resemblance in dietary quality in Mexican-origin families](https://www.sciencedirect.com/science/article/abs/pii/S0277953615302835)
### [<NAME>](https://u.demog.berkeley.edu/~gretchen/)
- [Methodology of the National Time Transfer Accounts](https://link.springer.com/chapter/10.1007/978-3-030-11806-8_2#:~:text=NTA%20is%20a%20framework%20for,ages%20when%20we%20are%20not.)
- [Gender and Work in the United States and Patterns by Hispanic Ethnicity](https://link.springer.com/chapter/10.1007/978-3-030-11806-8_7)
### [<NAME>](https://www.hhh.umn.edu/directory/audrey-dor%C3%A9lien)
- [Birth Seasonality in Sub-Saharan Africa](https://www.jstor.org/stable/26332053#metadata_info_tab_contents)
- [What is Urban? Comparing a Satellite View with the Demographic and Health Surveys](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1728-4457.2013.00610.x)
### [Paula England](https://as.nyu.edu/content/nyu-as/as/faculty/paula-england.html)
- [Gender inequality in labor markets: The role of motherhood and segregation](https://academic.oup.com/sp/article-abstract/12/2/264/1685513)
- [Households, employment, and gender: A social, economic, and demographic view](https://books.google.ca/books?hl=en&lr=&id=KmZQDwAAQBAJ&oi=fnd&pg=PP1&dq=info:94IYgM3TQQ8J:scholar.google.com&ots=j3j1WlRtkz&sig=rM321rrLCZOd99RaevAagNBJLXc&redir_esc=y#v=onepage&q&f=false)
### [<NAME>](https://www.cpc.unc.edu/people/fellows/barbara-entwisle/)
- [Putting people into place](https://link.springer.com/article/10.1353/dem.2007.0045)
- [Multilevel effects of socioeconomic development and family planning programs on children ever born](https://www.journals.uchicago.edu/doi/abs/10.1086/228316)
### [<NAME>](https://sociology.wustl.edu/people/cynthia-feliciano)
- [Educational selectivity in US immigration: How do immigrants compare to those left behind?](https://link.springer.com/article/10.1353/dem.2005.0001)
- [Does Selective Migration Matter? Explaining Ethnic Disparities in Educational Attainment among Immigrants' Children](https://journals.sagepub.com/doi/abs/10.1111/j.1747-7379.2005.tb00291.x)
### [<NAME>](https://www.cpc.unc.edu/people/fellows/elizabeth-frankenberg/)
- [The real costs of Indonesia's economic crisis: Preliminary findings from the Indonesia Family Life Surveys](https://econpapers.repec.org/paper/fthrandlp/99-04.htm)
- [Health consequences of forest fires in Indonesia](https://link.springer.com/article/10.1353/dem.2005.0004)
### [<NAME>](https://www.oeaw.ac.at/vid/people/staff/alexia-fuernkranz-prskawetz/)
- [A brain gain with a brain drain](https://www.sciencedirect.com/science/article/abs/pii/S0165176597000852)
- [Human capital depletion, human capital formation, and migration: a blessing or a “curse”?](https://www.sciencedirect.com/science/article/abs/pii/S0165176598001256)
### [<NAME>](https://www.brown.edu/academics/population-studies/people/person/elizabeth-fussell)
- [The limits to cumulative causation: International migration from Mexican Urban Areas](https://link.springer.com/article/10.1353/dem.2004.0003)
- [The Long-Term Recovery of New Orleans Population After Hurricane Katrina](https://journals.sagepub.com/doi/abs/10.1177/0002764215591181)
### [<NAME>](https://sociology.cornell.edu/filiz-garip)
- [Social capital and migration: How do similar resources lead to divergent outcomes?](https://link.springer.com/article/10.1353/dem.0.0016)
- [Discovering Diverse Mechanisms of Migration: The Mexico- U.S. Stream from 1970 to 2000](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1728-4457.2012.00510.x)
### [<NAME>](https://sociology.la.psu.edu/people/jeg115)
- [Post-secondary school participation of immigrant and native youth: The role of familial resources and educational expectations](https://www.sciencedirect.com/science/article/abs/pii/S0049089X03000590)
- [Academic trajectories of immigrant youths: Analysis within and across cohorts](https://link.springer.com/article/10.1353/dem.2003.0034)
### [<NAME>](https://kathryn-grace.dash.umn.edu/about/)
- [Child malnutrition and climate in Sub-Saharan Africa: An analysis of recent trends in Kenya](https://doi-org.proxy.lib.fsu.edu/10.1016/j.apgeog.2012.06.017)
- [Using satellite remote sensing and household survey data to assess human health and nutrition response to environmental change](https://link.springer.com/article/10.1007%252Fs11111-013-0201-0)
### [<NAME>](https://publicpolicy.unc.edu/people/5178/)
- [The institutional determinants of health insurance: Moving away from labor market, marriage, and family attachments under the ACA](https://doi.org/10.1177/0003122418811112)
- [Employment and Health Among Recently Incarcerated Men Before and After the Affordable Care Act (2009–2017)](https://doi.org/10.2105/AJPH.2019.305419)
### [<NAME>](https://www.colorado.edu/sociology/lori-hunter)
- [Migration and Environmental Hazards](https://link.springer.com/content/pdf/10.1007/s11111-005-3343-x.pdf)
- [Environmental Dimensions of Migration](https://www.annualreviews.org/doi/abs/10.1146/annurev-soc-073014-112223)
### [<NAME>](https://sites.google.com/umn.edu/jannaj)
- [Is Occupational Licensing a Barrier to Interstate Migration?](https://www.nber.org/papers/w24107)
- [The long run health consequences of rural‐urban migration](https://onlinelibrary.wiley.com/doi/full/10.3982/QE962)
### [<NAME>](https://www.site.demog.berkeley.edu/liu-profile-page)
- [Migrant networks and international migration: Testing weak ties](https://link.springer.com/content/pdf/10.1007/s13524-013-0213-5.pdf)
- [Prospects for the comparative study of international migration using quasi-longitudinal micro-data](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5739584/)
### [<NAME>](http://www.columbia.edu/~yl2479/)
- [Test of the ‘healthy migrant hypothesis’: a longitudinal analysis of health selectivity of internal migration in Indonesia](https://www.sciencedirect.com/science/article/abs/pii/S0277953608003225)
- [Education of children left behind in rural China](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1741-3737.2011.00951.x)
### [<NAME>](https://ayeshamahmud.github.io/)
- [Comparative dynamics, seasonality in transmission, and predictability of childhood infections in Mexico](https://www.cambridge.org/core/journals/epidemiology-and-infection/article/comparative-dynamics-seasonality-in-transmission-and-predictability-of-childhood-infections-in-mexico/D42E1AE52EAEAED56EFD55EFE7A8D2A6)
- [Drivers of measles mortality: the historic fatality burden of famine in Bangladesh](https://www.cambridge.org/core/journals/epidemiology-and-infection/article/drivers-of-measles-mortality-the-historic-fatality-burden-of-famine-in-bangladesh/3DED1784C1B25607693B2C6B29C6D090)
### [<NAME>](https://www.mcgill.ca/sociology/contact-us/faculty/claudia-masferrer)
- [Does Family Matter for Recent Immigrants’ Life Satisfaction](https://www.sciencedirect.com/science/article/abs/pii/S1040260816300193)
- [Going Back Home? Changing Demography and Geography of Mexican Return Migration](https://link.springer.com/article/10.1007/s11113-012-9243-8)
### [<NAME>](https://metcalflab.princeton.edu/people/metcalf-c-jessica/)
- [Why evolutionary biologists should be demographers](https://www.sciencedirect.com/science/article/abs/pii/S0169534706003806)
- [Seasonality and comparative dynamics of six childhood infections in pre-vaccination Copenhagen](https://royalsocietypublishing.org/doi/full/10.1098/rspb.2009.1058)
### [<NAME>](https://spgs.asu.edu/content/valerie-mueller)
- [Heat stress increases long-term human migration in rural Pakistan](https://www.nature.com/articles/nclimate2103/)
- [Temporary migration and climate variation in eastern Africa](https://doi.org/10.1016/j.worlddev.2019.104704)
### [<NAME>](http://www.wittgensteincentre.org/en/staff/member/muttarak.htm)
- [Is Education a Key to Reducing Vulnerability to Natural Disasters and hence Unavoidable Climate Change?](https://www.jstor.org/stable/26269470?seq=1#metadata_info_tab_contents)
- [Climate change and seasonal floods: potential long-term nutritional consequences for children in Kerala, India](https://gh.bmj.com/content/4/2/e001215.abstract)
### [<NAME>](https://orcid.org/0000-0001-7589-107X)
- [Heterogeneity among Young People Neither in Employment Nor in Education in Brazil](https://journals.sagepub.com/doi/full/10.1177/0002716220913234)
- [Causes of death among people living with HIV/AIDS in Brazil](https://www.sciencedirect.com/science/article/pii/S1413867010701124)
### [<NAME>](https://ph.ucla.edu/faculty/pebley)
- [Demography and the Environment](https://link.springer.com/article/10.2307/3004008)
- [Prenatal and delivery care and childhood immunization in Guatemala: Do family and community matter?](https://link.springer.com/article/10.2307/2061874)
### [<NAME>](https://www.heatherrandell.com/)
- [Structure and agency in development-induced forced migration: the case of Brazilís Belo Monte Dam](https://link.springer.com/content/pdf/10.1007/s11111-015-0245-4.pdf)
- [Climate change and educational attainment in the global tropics](https://www.pnas.org/content/116/18/8840)
### [<NAME>](https://www.cpc.unc.edu/people/fellows/krista-m-perreira/)
- [Making it in America: High school completion by immigrant and native youth](https://doi.org/10.1353/dem.2006.0026)
- [Painful passages: Traumatic experiences and post-traumatic stress among US immigrant Latino adolescents and their primary caregivers](https://doi.org/10.1111/imre.12050)
- [Climate change and educational attainment in the global tropics](10.1073/pnas.1817480116)
### [<NAME>](https://www.uh.edu/class/cmas/about-us/cmas-faculty/gabriela-sanchez-soto/)
- [I Would Really Like to Go Where You Go’: Rethinking Migration Decision‐Making Among Educated Tied Movers](https://doi.org/10.1002/psp.1990)
- [Youth Education and Employment in Mexico City: A Mixed-Methods Analysis](https://doi.org/10.1177/0002716220910391)
### [<NAME>](https://sociology.sas.upenn.edu/people/xi-song)
- [Market transition theory revisited: Changing regimes of housing inequality in China, 1988-2002](https://www.sociologicalscience.com/download/volume%201/july/SocSci_v1_277to291.pdf)
- [Diverging mobility trajectories: Grandparent effects on educational attainment in one-and two-parent families in the United States](https://link.springer.com/content/pdf/10.1007/s13524-016-0515-5.pdf)
### [<NAME>](https://nidi.nl/en/employees/helga-de-valk/)
- [Co-residence of adult children with their parents: differences by migration background explored and explained](https://www.tandfonline.com/doi/abs/10.1080/1369183X.2018.1485207)
- [Intergenerational discrepancies in fertility preferences among immigrant and Dutch families](https://www.tandfonline.com/doi/abs/10.1080/1081602X.2013.826591)
### [<NAME>](https://sociology.la.psu.edu/people/jxv21)
- [Immigration and living arrangements: Moving beyond economic need versus acculturation](https://link.springer.com/article/10.1353/dem.2007.0019)
- [Ineligible parents, eligible children: Food stamps receipt, allotments, and food insecurity among children of immigrants](https://www.sciencedirect.com/science/article/abs/pii/S0049089X04000869)
### [<NAME>](https://www.brown.edu/academics/sociology/people/leah-vanwey)
- [Household demographic change and land use/land cover change in the Brazilian Amazon](https://link.springer.com/content/pdf/10.1007/s11111-007-0040-y.pdf)
- [Theories Underlying the Study of Human-Environmenta Interactions](https://books.google.com/books?hl=en&lr=&id=rkplSGlHJmwC&oi=fnd&pg=PA23&dq=info:dYXZktdAhpUJ:scholar.google.com&ots=fPv6O7khoo&sig=TKdNE3zfkJOiKchUo71n03I0M4w#v=onepage&q&f=false)
### [<NAME>](https://geesc.cedeplar.ufmg.br/integrantes/simone-wajnman/)
- [The motherhood penalty: participation in the labor market and job quality of women with children](https://www.scielo.br/scielo.php?pid=S0102-30982019000100159&script=sci_abstract)
- [From the causes to the economic consequences of the demographic transition in Brazil](https://www.researchgate.net/publication/262700193_From_the_causes_to_the_economic_consequences_of_the_demographic_transition_in_Brazil)
## Mortality, health, aging, biodemography
### [<NAME>](https://researchers.anu.edu.au/researchers/allen-e)
- [The Future of Us](https://www.bookdepository.com/Future-Us-Liz-Allen/9781742236506)
- [Post-separation patterns of children's overnight stays with each parent: A detailed snapshot](https://www.tandfonline.com/doi/abs/10.5172/jfs.2012.18.2-3.202)
### [Elisabetta Barbi](https://www.dss.uniroma1.it/it/dipartimento/persone/barbi-elisabetta)
- [The plateau of human mortality: Demography of longevity pioneers](https://science.sciencemag.org/content/360/6396/1459.full?ijkey=<KEY>&keytype=ref&siteid=sci)
- [Response to Comment on “The plateau of human mortality: Demography of longevity pioneers”](https://doi.org/10.1126/science.aav3229)
### [<NAME>](https://www.site.demog.berkeley.edu/barbieri-profile-page)
- [The contribution of drug-related deaths to the US disadvantage in mortality](https://academic.oup.com/ije/article-abstract/48/3/945/5265302)
- [Data Resource Profile: The Human Mortality Database (HMD) ](https://academic.oup.com/ije/article/44/5/1549/2594557)
### [<NAME>](https://portal.findresearcher.sdu.dk/en/persons/baudisch)
- [Hamilton's indicators of the force of selection](https://www.pnas.org/content/102/23/8263.short)
- [Getting to the Root of Aging](https://science.sciencemag.org/content/338/6107/618.summary)
### [<NAME>](http://web.sas.upenn.edu/cboen/)
- [The role of socioeconomic factors in Black-White health inequities across the life course: Point-in-time measures, long-term exposures, and differential health returns](https://www.sciencedirect.com/science/article/abs/pii/S0277953616305676)
- [The physiological impacts of wealth shocks in late life: Evidence from the Great Recession](https://www.sciencedirect.com/science/article/abs/pii/S0277953615302884)
### [<NAME>](https://www.ined.fr/en/research/researchers/Cambois+Emmanuelle)
- [Social inequalities in disability-free life expectancy in the french male population, 1980-1991](https://doi.org/10.1353/dem.2001.0033)
- [Aging and health in France: an unexpected expansion of disability in mid-adulthood over recent years](https://doi.org/10.1093/eurpub/cks136)
### [<NAME>](https://scholar.google.com/citations?user=Trf4DAkAAAAJ&hl=it)
- [Three dimensions of the survival curve: Horizontalization, verticalization, and longevity extension](https://doi.org/10.1353/dem.2005.0012)
- [Epidemiologic transition theory exceptions](https://www.jstor.org/stable/29788712)
### [<NAME>](https://www.hsph.harvard.edu/marcia-castro/)
- [Malaria risk on the Amazon frontier](https://www.pnas.org/content/103/7/2452.short)
- [Brazil's unified health system: the first 30 years and prospects for the future](https://www.sciencedirect.com/science/article/abs/pii/S0140673619312437)
### [<NAME>](https://en.wikipedia.org/wiki/Lynne_Cossman)
- [Reconsidering the Rural-Urban Continuum in Rural Health Research: A Test of Stable Relationships Using Mortality as a Health Measure](https://link.springer.com/article/10.1007/s11113-008-9069-6)
- [Persistent Clusters of Mortality in the United States](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2089111/)
### [<NAME>](https://gero.usc.edu/faculty/crimmins/)
- [Change in cognitively healthy and cognitively impaired life expectancy in the United States: 2000–2010](https://www.sciencedirect.com/science/article/pii/S2352827316301148)
- [Aging populations, mortality, and life expectancy](https://www.annualreviews.org/doi/abs/10.1146/annurev-soc-073117-041351)
### [<NAME>](http://www.emgo.nl/team/186/dorlydeeg/personal-information/)
- [Attrition in the Longitudinal Aging Study Amsterdam: The effect of differential inclusion in side studies](https://doi.org/10.1016/S0895-4356(01)00475-9)
- [Concepts of self-rated health: Specifying the gender difference in mortality risk](https://doi.org/10.1093/geront/43.3.376)
### [<NAME>](https://www.ined.fr/en/research/researchers/D%C3%A9sesquelles+Aline/)
- [Mortality From Alzheimer’s Disease, Parkinson’s Disease, and Dementias in France and Italy: A Comparison Using the Multiple Cause-of-Death Approach](https://pubmed.ncbi.nlm.nih.gov/24667337/)
- [Revisiting the mortality of France and Italy with the multiple-cause-of-death approach](https://www.demographic-research.org/volumes/vol23/28/default.htm)
### [<NAME>](https://www.demogr.mpg.de/en/about_us_6113/staff_directory_1899/viorela_diaconu_3714/)
- [Insight on 'typical' longevity: an analysis of the modal lifespan by leading causes of death in Canada](https://www.demographic-research.org/volumes/vol35/17/default.htm)
- [Living and Working Longer in an Aging Society: Toward Increasing Inequalities?](https://ir.lib.uwo.ca/pclc/vol3/iss1/11/)
### [<NAME>](https://www.oeaw.ac.at/vid/people/staff/vanessa-di-lego/)
- [Gender differences in healthy and unhealthy life years](https://link.springer.com/chapter/10.1007/978-3-030-37668-0_11#:~:text=Not%20surprisingly%2C%20women%20expect%20to,from%20ages%2065%20and%20over.)
- [Mortality selection among adults in Brazil: The survival advantage of Air Force officers](https://www.demographic-research.org/volumes/vol37/41/default.htm)
### [<NAME>](https://www.jenndowd.com/)
- [Demographic science aids in understanding the spread and fatality rates of COVID-19](https://www.pnas.org/content/117/18/9696.short)
- [Does the predictive power of self-rated health for subsequent mortality risk vary by socioeconomic status in the US?](https://academic.oup.com/ije/article/36/6/1214/822656)
### [<NAME>](https://pop.umn.edu/people/julia-rivera-drew)
- [Trends in Fatal and Nonfatal Injuries among Older Americans, 2004-2017](https://www.ajpmonline.org/article/S0749-3797(20)30057-X/fulltext)
- [Disability and the Self-Reliant Family: Revisiting the Literature on Parents with Disabilities](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5605814/)
### [<NAME>](https://www.ined.fr/en/research/researchers/Duth%C3%A9+G%C3%A9raldine)
- [Suicide among male prisoners in France: a prospective population-based study](https://www.sciencedirect.com/science/article/pii/S0379073813004313)
- [Mortality in the Caucasus: An attempt to re-estimate recent mortality trends in Armenia and Georgia](https://www.jstor.org/stable/26349571?seq=1#metadata_info_tab_contents)
### [<NAME>](http://www.healthdata.org/about/laura-dwyer-lindgren)
- [US County-Level Trends in Mortality Rates for Major Causes of Death, 1980-2014](https://pubmed.ncbi.nlm.nih.gov/27959996/)
- [Inequalities in Life Expectancy Among US Counties, 1980 to 2014: Temporal Trends and Key Drivers](https://pubmed.ncbi.nlm.nih.gov/28492829/)
### [<NAME>](https://sociology.sas.upenn.edu/people/irma-elo)
- [Social class differentials in health and mortality: Patterns and explanations in comparative perspective](https://www.annualreviews.org/doi/abs/10.1146/annurev-soc-070308-115929)
- [Mortality among elderly Hispanics in the United States: Past evidence and new results](https://link.springer.com/article/10.1353/dem.2004.0001)
### [<NAME>](https://theconversation.com/profiles/jenny-garcia-735043)
- [Trends in infant mortality in Venezuela between 1985 and 2016: a systematic analysis of demographic data](https://www.thelancet.com/journals/langlo/article/PIIS2214-109X(18)30479-0/fulltext)
- [Urban–rural differentials in Latin American infant mortality](https://www.demographic-research.org/volumes/vol42/8/42-8.pdf)
### [<NAME>](https://www.vanderbilt.edu/mhs/person/lauren-gaydosh/)
- [The Depths of Despair Among US Adults Entering Midlife](https://ajph.aphapublications.org/doi/full/10.2105/AJPH.2019.305002)
- [Childhood Family Instability and Young Adult Health](https://journals.sagepub.com/doi/abs/10.1177/0022146518785174)
### [<NAME>](http://danaglei.users.sonic.net/)
- [Participating in social activities helps preserve cognitive function: an analysis of a longitudinal, population-based study of the elderly](https://pubmed.ncbi.nlm.nih.gov/15764689/)
- [Utilization of care during pregnancy in rural Guatemala: does obstetrical need matter?](https://pubmed.ncbi.nlm.nih.gov/14572850/)
### [<NAME>](https://www.princeton.edu/~ngoldman/)
- [Socioeconomic differences in mortality among US adults: Insights into the Hispanic paradox](https://academic.oup.com/psychsocgerontology/article/62/3/S184/600844)
- [Mortality differentials by marital status: an international comparison](Mortality differentials by marital status: an international comparison)
### [<NAME>](https://gufaculty360.georgetown.edu/s/contact/0033600001i3sNCAAY/pamela-herd)
- [Socioeconomic position and health: the differential effects of education versus income on the onset versus progression of health problems](https://journals.sagepub.com/doi/abs/10.1177/002214650704800302)
- [Do functional health inequalities decrease in old age? Educational status and functional decline among the 1931-1941 birth cohort](https://journals.sagepub.com/doi/abs/10.1177/0164027505285845)
### [<NAME>](https://gero.usc.edu/faculty/jessica-ho-phd/)
- [Recent trends in life expectancy across high income countries: retrospective observational study](https://www.bmj.com/content/362/bmj.k2562.full)
- [The contribution of smoking to black-white differences in US mortality](https://link.springer.com/content/pdf/10.1007/s13524-012-0159-z.pdf)
### [<NAME>](https://nidi.nl/en/employees/fanny-janssen/)
- [ICD coding changes and discontinuities in trends in cause-specific mortality in six European countries, 1950-99](https://www.scielosp.org/article/bwho/2004.v82n12/904-913/en/)
- [Trends in old-age mortality in seven European countries, 1950–1999](https://www.sciencedirect.com/science/article/abs/pii/S0895435603002907)
### [<NAME>](http://www.luciekalousova.com/)
- [Increase in frailty of older workers and retirees predicted by negative psychosocial working conditions on the job](https://www.sciencedirect.com/science/article/abs/pii/S0277953614007874)
- [Debt and Foregone Medical Care](https://journals.sagepub.com/doi/abs/10.1177/0022146513483772)
### [<NAME>](https://jennkarasmontez.com/)
- [Trends in the educational gradient of US adult mortality from 1986 through 2006 by race, gender, and age group](https://journals.sagepub.com/doi/abs/10.1177/0164027510392388)
- [Educational attainment and adult mortality in the United States: A systematic analysis of functional form](https://link.springer.com/content/pdf/10.1007/s13524-011-0082-8.pdf)
### [<NAME>](https://www.demogr.mpg.de/en/about_us_6113/staff_directory_1899/mine_kuehn_3302/)
- [Gender differences in health in Havana versus in Mexico City and in the US Hispanic population](https://link.springer.com/content/pdf/10.1007/s10433-020-00563-w.pdf)
- [Trends in gender differences in health at working ages among West and East Germans](https://www.sciencedirect.com/science/article/pii/S2352827318300570)
### [<NAME>](http://www.lse.ac.uk/international-development/people/tiziana-leone)
- [Diabetes and depression comorbidity and socio-economic status in low and middle income countries (LMICs): a mapping of the evidence](https://globalizationandhealth.biomedcentral.com/articles/10.1186/1744-8603-8-39)
- [Impact and determinants of sex preference in Nepal](https://www.jstor.org/stable/3181060?seq=1#metadata_info_tab_contents)
### [<NAME>](https://www.demogr.mpg.de/en/about_us_6113/staff_directory_1899/silvia_loi_2870)
- [Migrant health convergence and the role of material deprivation](https://www.demographic-research.org/volumes/vol40/32/)
- [Migration, health and mortality in Italy: an unfinished story](https://www.iris.unina.it/handle/11588/714542)
### [<NAME>ummaa](https://www.utu.fi/en/people/virpi-lummaa)
- [Evolution of sex differences in lifespan and aging: causes and constraints](https://onlinelibrary.wiley.com/doi/abs/10.1002/bies.201300021)
- [Sons reduced maternal longevity in preindustrial humans](https://www.researchgate.net/profile/Virpi_Lummaa/publication/11367151_Sons_Reduced_Maternal_Longevity_in_Preindustrial_Humans/links/546086a70cf295b5616204b8/Sons-Reduced-Maternal-Longevity-in-Preindustrial-Humans.pdf)
### [<NAME>](https://sociology.usu.edu/people/directory/guadalupe-marquez-velarde)
- [Mental health disparities among low-income US Hispanic residents of a US-Mexico border colonia](https://doi.org/10.1007/s40615-015-0091-1)
- [Racial stratification in self-rated health among Black Mexicans and White Mexicans](https://doi.org/10.1016/j.ssmph.2019.100509)
### [<NAME>](https://www.lshtm.ac.uk/aboutus/people/marston.milly)
- [The relationship between HIV and fertility in the era of antiretroviral therapy in sub-Saharan Africa: evidence from 49 Demographic and Health Surveys](https://pubmed.ncbi.nlm.nih.gov/28986949/)
- [Net survival of perinatally and postnatally HIV-infected children: a pooled analysis of individual data from sub-Saharan Africa](https://pubmed.ncbi.nlm.nih.gov/21247884/)
### [<NAME>](https://anthropology.washington.edu/people/melanie-martin)
- [Differences in Tsimane children’s growth outcomes and associated determinants as estimated by WHO standards vs. within population references](https://anthropology.washington.edu/research/publications/tsimane-vs-who-growth-references)
- [Infant gut microbiota: developmental influences and health outcomes](https://link.springer.com/chapter/10.1007/978-1-4614-4060-4_11)
### [<NAME>](https://www.ined.fr/en/research/researchers/Mesl%C3%A9+France)
- [Diverging Trends in Female Old-Age Mortality: The United States and the Netherlands versus France and Japan](https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1728-4457.2006.00108.x)
- [Reconstructing Long-Term Series of Causes of Death](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6241024/)
### [<NAME>](https://www.demogr.mpg.de/en/about_us_6113/staff_directory_1899/marilia_r_nepomuceno_2921)
- [Besides population age-structure, health and other demographic factors can contribute to understanding the COVID-19 burden](https://dx.doi.org/10.1073/pnas.2008760117)
- [A cohort survival comparison of Central and Eastern European and high-longevity countries](https://www.cairn.info/revue-population-2019-3-page-299.htm?ref=doi)
### [<NAME>](https://www.demogr.mpg.de/en/about_us_6113/staff_directory_1899/anna_oksuzyan_1135/)
- [Men: good health and high mortality. Sex differences in health and aging](https://pubmed.ncbi.nlm.nih.gov/18431075/)
- [Is the story about sensitive women and stoical men true? Gender differences in health after adjustment for reporting behavior](https://www.sciencedirect.com/science/article/pii/S0277953619301388)
### [<NAME>](https://demo.umontreal.ca/repertoire-departement/professeurs/professeur/in/in29461/sg/Nadine%20Ouellette/)
- [Period-Based Mortality Change: Turning Points in Trends since 1950](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4091993/)
- [Changes in the age-at-death distribution in four low mortality countries: A nonparametric approach](https://www.demographic-research.org/volumes/vol25/19/25-19.pdf)
### [<NAME>](https://fhssfaculty.byu.edu/FacultyPage/hhayley)
- [Increasing Maternal Healthcare Use in Rwanda: Implications for Child Nutritional Status and Survival](https://pubmed.ncbi.nlm.nih.gov/24607667/)
- [Cohabitation or Marriage? How Relationship Status and Community Context Influence the Well-being of Children in Developing Nations](https://www.researchgate.net/publication/335480373_Cohabitation_or_Marriage_How_Relationship_Status_and_Community_Context_Influence_the_Well-being_of_Children_in_Developing_Nations)
### [<NAME>](http://www.ameliequesnelvallee.org/)
- [Self-rated health: caught in the crossfire of the quest for ‘true’ health?](https://academic.oup.com/ije/article/36/6/1161/824081)
- [Temporary work and depressive symptoms: a propensity score analysis](https://www.sciencedirect.com/science/article/abs/pii/S027795361000167X)
### [<NAME>](http://nanditasaikia.com/)
- [Trends and geographic differentials in mortality under age 60 in India](https://www.tandfonline.com/doi/abs/10.1080/00324728.2010.534642)
- [Does type of household affect maternal health? Evidence from India](https://pdfs.semanticscholar.org/2ece/463397868492798d0ef3382a1cc2a537b6c8.pdf)
### [<NAME>](https://www.scielo.br/scielo.php?pid=S1413-81232002000400012&script=sci_arttext)
- [Spatial patterns of malaria in the Amazon: implications for surveillance and targeted interventions](https://pubmed.ncbi.nlm.nih.gov/16815074/)
- [Profiles of health services utilization in Brazil](https://www.scielo.br/scielo.php?pid=S1413-81232002000400012&script=sci_arttext)
### [<NAME>](https://www.stir.ac.uk/people/1489025)
- [Increasing inequality in age of death at shared levels of life expectancy: A comparative study of Scotland and England and Wales](https://www.sciencedirect.com/science/article/pii/S235282731630101X )
- [The increasing lifespan variation gradient by area-level deprivation: A decomposition analysis of Scotland 1981–2011](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6711767/)
### [<NAME>](https://www.upf.edu/web/sole-auro)
- [Health of Immigrants in European Countries](https://journals.sagepub.com/doi/abs/10.1111/j.1747-7379.2008.00150.x)
- [Who cares? A comparison of informal and formal care provision in Spain, England and the USA](https://www.cambridge.org/core/journals/ageing-and-society/article/who-cares-a-comparison-of-informal-and-formal-care-provision-in-spain-england-and-the-usa/EB0202DF1C3D43193373DEA063599A7B)
### [<NAME>](https://portal.findresearcher.sdu.dk/en/persons/ctorres)
- [Life expectancy in urbanizing contexts: Patterns and causes of changes in mortality in historical populations](https://doi.org/10.21996/13hx-6h08)
- [The contribution of urbanization to changes in life expectancy in Scotland, 1861–1910](https://doi.org/10.1080/00324728.2018.1549746)
### [<NAME>](https://liberalarts.utexas.edu/sociology/faculty/dju)
- [Social relationships and health behavior across the life course](https://www.annualreviews.org/doi/abs/10.1146/annurev-soc-070308-120011?journalCode=soc)
- [Widowhood and depression: Explaining long-term gender differences in vulnerability](https://www.jstor.org/stable/2136854?seq=1#metadata_info_tab_contents)
### [<NAME>](https://sites.google.com/site/piedadurdinola/)
- [Could Political Violence Affect Infant Mortality? The Colombian Case](https://www.repository.fedesarrollo.org.co/handle/11445/1073)
- [The Homicide Atlas in Colombia: Contagion and Under-Registration for Small Areas](http://www.scielo.org.co/scielo.php?pid=S0121-215X2017000100008&script=sci_abstract&tlng=pt)
### [<NAME>](https://www.demogr.mpg.de/en/about_us_6113/staff_directory_1899/alyson_van_raalte_1575/)
- [The case for monitoring life-span inequality](https://science.sciencemag.org/content/362/6418/1002.summary)
- [Lifespan variation by occupational class: Compression or stagnation over time?](https://link.springer.com/content/pdf/10.1007/s13524-013-0253-x.pdf)
### [<NAME>](https://www.demogr.mpg.de/en/about_us_6113/staff_directory_1899/yana_catherine_vierboom_3786/)
- [Trends in Alcohol-Related Mortality by Educational Attainment in the U.S., 2000–2017](https://link.springer.com/article/10.1007%2Fs11113-019-09527-0)
- [The contribution of differences in adiposity to educational disparities in mortality in the United States](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5759347/)
### [<NAME>](http://somos.ufmg.br/professor/laura-lidia-rodriguez-wong)
- [The rapid process of aging in Brazil: serious challenges for public policies](https://www.scielo.br/scielo.php?pid=S0102-30982006000100002&script=sci_abstract)
- [Evidences of further decline of fertility in Latina America: Reproductive behavior and some thoughts on the consequences on the age structure](https://iussp2009.princeton.edu/papers/93516)
### [<NAME>](http://www.emmazang.net/)
- [Recent trends in US mortality in early and middle adulthood: racial/ethnic disparities in inter-cohort patterns](https://academic.oup.com/ije/article-abstract/48/3/934/5224527)
- [Frustrated achievers or satisfied losers? Inter-and intragenerational social mobility and happiness in China](https://www.sociologicalscience.com/download/vol-3/september/SocSci_v3_779to800.pdf)
### [<NAME>](https://portal.findresearcher.sdu.dk/en/persons/vzarulli)
- [Women live longer than men even during severe famines and epidemics](https://www.pnas.org/content/115/4/E832?xid=PS_smithsonian)
- [Mortality by education level at late-adult ages in Turin: a survival analysis using frailty models with period and cohort approaches ](https://bmjopen.bmj.com/content/3/7/e002841.short)
### [<NAME>](https://www.prb.org/people/toshiko-kaneda/)
- [Gender Differences in Functional Health and Mortality Among the Chinese Elderly Testing an Exposure Versus Vulnerability Hypothesis](https://doi.org/10.1177/0164027508330725)
- [Education, Gender, and Functional Transitions Among Indonesian Elderly](https://doi.org/10.1007/s10823-007-9041-7)
### [<NAME>](https://sph.umich.edu/faculty-profiles/geronimus-arline.html)
- ["Weathering" and age patterns of allostatic load scores among blacks and whites in the United States](https://doi.org/10.2105/AJPH.2004.060749)
- [Black/white differences in the relationship of maternal age to birthweight: A population-based test of the weathering hypothesis](https://doi.org/10.1016/0277-9536(95)00159-X)
### [<NAME>](https://blogs.worldbank.org/team/emi-suzuki)
- [Estimates of maternal mortality worldwide between 1990 and 2005: an assessment of available data](https://doi.org/10.1016/S0140-6736(07)61572-4)
- [Understanding Global Trends in Maternal Mortality](https://doi.org/10.1363/3903213)
### [Ewa Tabeau](https://www.wur.nl/en/Persons/Ewa-EW-Ewa-Tabeau-PhD-MSc.htm)
- [War-related Deaths in the 1992–1995 Armed Conflicts in Bosnia and Herzegovina: A Critique of Previous Estimates and Recent Results](https://doi.org/10.1007/s10680-005-6852-5)
- [Improving Overall Mortality Forecasts by Analysing Cause-of-Death, Period and Cohort Effects in Trends](https://doi.org/10.1023/A:1006109310764)
### [<NAME>](https://www.jhsph.edu/faculty/directory/profile/2243/li-liu)
- [Global, regional, and national causes of child mortality: an updated systematic analysis for 2010 with time trends since 2000](https://doi.org/10.1016/S0140-6736(12)60560-1)
- [Global, regional, and national causes of under-5 mortality in 2000-15: an updated systematic analysis with implications for the Sustainable Development Goals](https://doi.org/10.1016/S0140-6736(16)31593-8)
<file_sep>/content/posts/2017-10-08-migration-text.Rmd
---
title: "Text analysis of migration news articles"
author: "<NAME>"
date: "2017-10-08"
output: html_document
---
[Leslie Root](https://leslieroot.net/) and I did some exploratory text analysis of migration-related newspaper articles in the US. We analyzed almost 10,000 articles over the period 2008-2017, looking at how topics and sentiment about migration have changed.
Our initial analysis suggests that sentiment in migration news coverage has changed over time, and decreased since 2013. Major topics in migration news include political campaigns, the economy, illegal immigrants, Europe, and more recently, Donald Trump. Topics and language appears to be influenced by election cycles. Additionally, in recent years there has been increased focus on Mexican and Muslim migrants.
All analysis was done in `R` using the awesome package `tidytext` and following ['Text Mining in R: A tidy approach'](http://tidytextmining.com/) by <NAME> and <NAME>. Code can be found [here](https://github.com/lesliejroot/migration-news).
## Data
We searched [ProQuest](https://search.proquest.com) for newspaper articles that included the terms 'population' and 'immigra*'. This resulting in a total of 9,869 articles in the years 2008-2017. The search returned articles from the New York Times, Los Angeles Times, Wall Street Journal (WSJ) and WSJ Online. There is a drop in the number of articles in 2017 because we couldn't collect for the whole year.
<img src="/img/migration_plots/source_year.png" alt="number of articles by year">
## Important words and combinations
The plots below show the most 'important words' for articles in each year. We define important words based on the term frequency–inverse document frequency, or [tf-idf]([http://tidytextmining.com/tfidf.html) measure. This measures the number of times a word appears in the document, but adjusts for the fact that some words appear more frequently in general.
Throughout all years there is a strong political focus, with Obama, McCain, Clinton, Sanders and Trump all appearing as important words, as well as words like vote/r, campaign and republican. Other common words include hispanic/latino, law, workers and border. The words in 2015 show themes relating to the European migration crisis. In the most recent year, the words 'police' and 'muslim' have become important.
<img src="/img/migration_plots/tf_idf_year_barplot.png" alt="important words", height="4000">
We also looked at words preceding the words 'immigrant' and 'migrant' to see what the most important combinations were. In general the most common preceding word was 'illegal'. However, looking at changes over time suggests a shift to using alternative words such as 'undocumented' and 'unauthorized'. The number of instances of 'undocumented immigrant/migrant' overtook 'illegal immigrant/migrant' in 2017. Various ethnicities were also important preceding words, including Mexican, Latino, Hispanic, Asian and Muslim.
<img src="/img/migration_plots/bigram_immigration_year_barplot.png" alt="words preceding immigrant">
Focusing on the types of ethnicities/religions most commonly mentioned preceding the words immigrant or migrant, there appears to have been a shift in the discussion over time. The most common type of immigrant discussed in the news are Muslim immigrants, and this has broadly been increasing since 2013. In addition, there appears to have been a shift towards referring to Mexican immigrants and away from using the terms Latino and Hispanic.
<img src="/img/migration_plots/bigram_immigration_eth_year.png" alt="ethnicities mentioned">
## Sentiment
We also looked at how sentiment in migration news articles is changing over time. The plot below shows sentiment for all articles in each year, using the [AFINN](http://tidytextmining.com/sentiment.html#the-sentiments-dataset) measure. This lexicon assigns words with a score that runs between -5 and 5, with negative scores indicating negative sentiment and positive scores indicating positive sentiment.
Sentiment is negative for all years, but the level has been changing. After initially dropping, sentiment increased during Obama's second term, but has since decreased. This year's news articles display the most negative sentiment of the whole period.
<img src="/img/migration_plots/sentiment_year.png" alt="sentiment over time">
Looking at the top five negative words over time, as we saw in the word analysis above, we can see a shift away from the use of 'illegal' towards the use of 'undocumented'. The use of 'attack' peaked in 2015, corresponding to the Paris attacks.
<img src="/img/migration_plots/sent_neg_year.png" alt="sentiment over time">
## Topics
We used [LDA](http://tidytextmining.com/topicmodeling.html) to create an eight-topic model for all migration articles. The plots below show the terms that are most common with each topic. Broadly, the topics can be thought of as covering
- Hispanic/ Latinos in LA
- Europe
- Art and museums
- Workers, growth and the economy
- Communities
- Trump-related politics
- Illegal, border, law enforcement
- Elections
<img src="/img/migration_plots/tm_8topic.png" alt="eight topics">
Looking at the proportion of documents in five of the above topics by year, unsurprisingly the Trump-related topic has spiked in the last two years. The election topic peaks in line with election cycles. Talk of illegality and enforcement has spiked in the last year, while talk of the economy peaked in 2013, in line with when sentiment was the least negative.
<img src="/img/migration_plots/tm_doc_year_5.png" alt="topics over time">
## Summary
Coverage of migration issues in major news outlets in the US is generally negative, however it seems to have become even more negative over the past few years. Coverage is driven by the election cycles, and while many of the articles focus on illegal immigrants, there appears to have been a shift in terminology in recent years from 'illegal' to 'undocumented' and 'unauthorized'.
In future work we want to build on this initial analysis by gathering a more complete dataset of US news, and look at sentiment in public opinion surveys to see how it relates to changes in coverage in the media.
<file_sep>/content/posts/2016-04-26-mortality-sensitivities.Rmd
---
title: "Real differences and model artefacts in mortality inequality research"
author: "<NAME>"
date: "2016-04-26"
output:
html_document:
theme: spacelab
runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
A couple of weeks ago, [a paper](http://jama.jamanetwork.com/article.aspx?articleId=2513561&guestAccessKey=<KEY>) was published in the JAMA detailing income inequalities in mortality across cities in the United States. The research, which was led by <NAME> at Stanford University, received [wide attention](http://www.nytimes.com/interactive/2016/04/11/upshot/for-the-poor-geography-is-life-and-death.html). It is an important contribution to the literature, utilizing detailed income and mortality data from the IRS and SSA to estimate adult mortality by income at the city level.
The most striking finding of the research was that, while the rich live longer everywhere, life expectancy for those in the poorer income groups varies substantially by geography. The standard deviation of the average age at death for those in the bottom income quartile was found to be 1.39 years; the standard deviation for those in the top income quartile was only 0.7 years.
Although the authors had access to a rich, longitudinal dataset, there were some data limitations which meant that some assumptions had to be made. Here I want to draw attention to one assumption in particular -- that differences in mortality across race/ethnic groups are constant across the whole of the United States.
### Producing race-adjusted life expectancy estimates
The main metric of mortality used in the paper is a race-adjusted measure of life expectancy. (An aside: although it is referred to as life expectancy in the paper, it is actually life expectancy at age 40 + 40 years, i.e.\ $e_{40} + 40$ years, which is the average age at death having reached age 40).
On the log scale, the average mortality rate at age $x$ for a particular sex, area and income group is the weighted sum of the mortality rates of the white, black, Asian and Hispanic populations:
$$ \log(m_x) = p_{white} \log(m_{x,white}) + p_{black} \log(m_{x,black}) + p_{Hispanic} \log(m_{x,Hispanic}) + p_{Asian} \log(m_{x,Asian}) $$
where $p_{group}$ is the proportion of the total population in that group. Once the race-specific mortality rates are found and life expectancies calculated, the aggregate life expectancy is reweighted based on national values of $p_{group}$ to produce a race-adjusted life expectancy measure.
The average mortality rate, $\log(m_x)$ comes from the main dataset. But in this dataset information on race or ethnicity is not available, so the authors use information from the National Longitudinal Mortality Study (NLMS). Mortality rates for a particular race group are assumed to follow a Gompertz model, which models age-specific mortality as a function of two parameters, $\alpha$ and $\beta$; i.e.\ for age $x$:
$$ \log(m_{x,white}) = \alpha + \beta x $$
Now mortality rates for the other race groups can be represented in terms of the difference between that group and white mortality. For example, for the black population:
$$ \log(m_{x,black}) = \log(m_{x,white}) + \delta_{black} + \Delta_{black}x $$
The $(\delta, \Delta)$ are race shifters: the $\delta$ term is the difference in the intercept parameter and the $\Delta$ term is the difference in the slope for a particular race group. The key assumption made is that, for each group (black, Hispanic and Asian) those race shifters are **constant** across all areas and income groups. For example, the $\delta_{black}$ equals around 0.53, irrespective of location or income group.
This is implicitly assuming that mortality differences by race are constant across geography and income. This seems strange given the main finding of the paper was that overall mortality varies greatly by geography and income.
The authors [justify this assumption](https://healthinequality.org/documents/paper/healthineq_supplement.pdf) by showing that, in the NLMS, these race shifters do not differ significantly across broad Census regions (Northeast, Midwest, South, West). But just because there are no significant differences at the aggregate level does not mean that it holds when comparing one city to another, say, Detroit and Salt Lake City.
###Sensitivities
How might this assumption affect the race-adjusted life expectancy measure? Look at the equation for black log-mortality rates above. What if, in a particular city, the proportion of the black population was higher than the national average, and additionally the mortality differences were higher and black mortality was worse than assumed. Then the $(\delta, \Delta)$ values would be too small, and so $\log(m_{x,black})$ would be too low. But because all race-specific mortality rates are constrained to equal the average mortality rate $\log(m_x)$, if the $\log(m_{x,black})$ is too low, then, all else equal, $\log(m_{x,white})$ is too high. As a consequence, the race-adjusted mortality will be too high, so race-adjusted life expectancy will be too low.
The graph below illustrates this effect. The underlying race distribution is roughly equal to females in Detroit in the lowest income quartile. The mortality rates are made up using a Gompertz model, but with a life expectancy roughly equal to that published in the paper for females in Detroit in the lowest income quartile.
With $(\delta_{black}, \Delta_{black}) = (0.53, -0.0012)$, the race adjusted life expectancy is 80.4 years. These shifters are approximately equal to those used in the paper; I say approximately, because the values weren't actually published anywhere, so I had to eye-ball figure e6/7 in the [supplementary information](https://healthinequality.org/documents/paper/healthineq_supplement.pdf). If you change the values to $(\delta_{black}, \Delta_{black}) = (0.8, 0)$, the race adjusted life expectancy is 81.3 years.
```{r, echo=FALSE, fig.width= 12}
knitr::include_app("http://shiny.demog.berkeley.edu/monicah/mortality_app/", height = "600px")
```
###Summary
Demographic estimation usually involves using some sort of model process or set of assumptions, no matter how detailed or high-quality the data are. As data availability increases, we are producing estimates at more granular levels of geography, with disaggregation into smaller subpopulations. As this continues, it becomes even more important to be aware of how modeling assumptions may affect results.
The main conclusions in the Chetty et.\ al paper are most likely right, and it is a great paper. But without access to the raw data, it is difficult for other researchers to disentangle how much are real differences, versus model artefacts, with any confidence.
####Code
Code for this is [here](https://github.com/MJAlexander).
<file_sep>/content/posts/2021-21-02-mapping.Rmd
---
title: "Mapping a network of women in demography"
author: "<NAME>"
date: "2021-02-21"
output:
html_document:
number_sections: false
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = TRUE, warning=FALSE, message=FALSE)
```
```{r, echo=FALSE}
library(tidyverse)
library(leaflet)
library(rvest)
library(tidygeocoder)
geos <- read_csv("geos.csv")
```
Last summer, I ran a demography reading course and one of the students noticed that I didn't cite very many scholars who were women. She was absolutely right, so I decided to start putting together a [list of active scholars](https://www.monicaalexander.com/women_scholars/) in demography who identify as women or other gender minorities. Initially some friends and I put together about 60 names, and then I put it out on Twitter --- now it's over 300 names long. It's been a great way to discover new scholars and papers.
It was fun to see the list grow as people saw the tweets, and interesting that additions would tend to happen in geographic clusters as different people found it and then suggested their colleagues. I was curious to see how the locations of all these scholars mapped on a global scale. The list was never meant to be comprehensive and I am under no false pretenses that it is representative, but thought it might be interesting all the same.
The issue is that, perhaps rather foolishly, I had not been collecting or recording people's affiliations in any systematic way. Rather than going through the list and manually entering everyone's affiliations, I decided to use it as an excuse to write some R code. It is reading week after all and I'm only a little (read: extremely, very much) behind with work.
This post summarizes what I did to map affiliations of women in demography. In particular I grabbed (most) affiliations from Google Scholar with the help of the `rvest` package, and geocoded these affiliations with the help of the `tidygeocoder` package.
# Getting the affiliations through Google Scholar
The first step is to get a list of the universities or other institutions that people are affiliated with. I decided my best best to do this in a programmatic way was probably through Google Scholar. Most people have a Google Scholar page these days, so I only had to manually enter a few people's affiliations (probably ~15 in total).
Here's an example of how I did it. I'm using [<NAME>](https://twitter.com/les_ja) as an example, who is a great demographer and friend, and would probably be mildly embarrassed/irritated if she ever reads this post.
The first step is to define the URL that we want to look up. In particular, this is the Google Scholar author search page.
```{r, eval = FALSE}
this_name <- "root,leslie"
search_page <- paste(
"http://scholar.google.com/
citations?hl=en&view_op=search_authors&mauthors=",
this_name,
sep="")
```
Once the page is defined, we can use the `read_html` function from the `rvest` package to get the contents of that page.
```{r, eval = FALSE}
gs_result <- read_html(search_page)
```
This gives us a whole bunch of html that is largely useless. If you go to the [search page](https://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=root,leslie), you'll notice that the bit we want is "Postdoctoral Fellow, University of California, Berkeley". We can extract this from the html using the following code:
```{r, eval = FALSE}
affiliation <- gs_result %>%
xml_find_all("//div[contains(@class, 'gs_ai_aff')]") %>%
html_text()
```
Note that I worked out what bit I had to extract (the `gs_ai_aff`) by going to the search page, right clicking and selecting 'View Page Source', then searching for the bit that contained the affiliation.
Now that I have an automated way of grabbing the affiliation, I can iterate over the list of all scholars to get affiliations for everyone. A few things to note here: firstly, some people didn't have Google Scholar pages, so I entered them manually. Secondly, affiliations are self-reported and so are often in different formats, so there was a bit of text cleaning to get a standardized form. Finally, some people have names that returned more than one Google Scholar page. For these people I searched the pages to find the one that included the paper(s) that I have listed for that particular scholar.
# Geocoding the affiliation locations
Now that I have a list of affiliations, the next step is to geocode them so I can put them on a map. This may sound fancy but it's very easy in R with the help of specialized packages. There are lots of geocoding packages around, but I used `tidygeocoder`. The `geocode` function within this package takes a tibble of addresses (which can just be University names) and returns a tibble with a latitude and longitude column. For example:
```{r}
geo_example <- tibble(clean_affiliation = "University of California, Berkeley")
geo_example %>%
geocode(address = clean_affiliation,
method = 'osm', verbose = TRUE)
```
This worked great for the majority of affiliations I had listed. Some could not be found which I went through and manually entered (there were about 6 I did this for). In addition, a couple of geocodes were wrong (for example, the University of Southampton was put in Singapore?!), and I manually changed these. I did a cursory check but if anyone sees any remaining errors let me know.
# Mapping the affiliation locations
Now we have the geocoded affiliations we can map them easily using `leaflet`. Here's the map:
```{r}
leaflet() %>%
addTiles() %>%
addMarkers(lat = geos$lat,
lng = geos$long,
popup = geos$clean_affiliation)
```
There are 141 unique affiliations. Perhaps unsurprisingly these are very much concentrated in the US and Europe.
# Summary
I created a list of women in demography and stupidly did not record affiliations. But it was a nice excuse to use some nice R packages like `rvest` and `tidygeocoder` to get a map of this network so far. Hopefully this list will continue to grow over time; please add yourself or others if you see omissions!
|
3f20c6700cb423e63236bdb055745b460144e18b
|
[
"Markdown",
"HTML",
"R",
"RMarkdown"
] | 29
|
RMarkdown
|
MJAlexander/blogdown-website
|
760b4a73952206442a5e544b086d86443f3d2b69
|
9e0072d481d63c98e82b91f400c8d5d49fd4aded
|
refs/heads/main
|
<repo_name>danceli/Renting<file_sep>/src/store/User/actions.js
import axios from '@/http/request';
import { setToken, removeToken, getToken } from '@/utils/auth';
import { SET_USER, REMOVE_USER } from '../actions';
export function setUserInfo(token) {
return async dispatch => {
setToken(token);
const { data } = await axios.get("/user");
if(data.status === 200) {
dispatch({
type: SET_USER,
userInfo: data.body
})
}
}
}
export function unInstall() {
return async dispatch => {
const { data } = await axios.post('/user/logout');
if(data.status === 200) {
removeToken();
dispatch({
type: REMOVE_USER
})
}
}
}<file_sep>/src/pages/CityList/index.jsx
import React, { Component, createRef } from 'react'
import { Toast } from 'antd-mobile';
import axios from '@/http/request';
import { formatCityList, getCurCity, formatCityLetter } from '@/utils/ext';
import { List, AutoSizer } from 'react-virtualized';
import NavBar from '@/components/NavHeader'
import './index.scss';
const TITLE_HEIGHT = 36,
NAME_HEIGHT = 50;
const HOUSE_CITY = ["北京", "上海", "广州", "深圳"]
class CityList extends Component {
constructor(props) {
super(props);
this.list = createRef(null)
this.state = {
cityList: {},
cityKey: [],
activeKey: 0
}
}
getCityList = async () => {
const { data } = await axios.get('/area/city', {
params: {
"level": "1"
}
});
const {cityList, cityKey} = formatCityList(data.body);
const res = await axios.get('area/hot');
cityList["hot"] = res.data.body;
cityKey.unshift("hot");
//获取当前定位城市
const curCity = await getCurCity();
//将当前定位城市添加到cityList, 和cityKey
cityList['#'] = [curCity];
cityKey.unshift("#");
this.setState({
cityList: cityList,
cityKey: cityKey
})
}
selectCity = ({label, value}) => {
if(HOUSE_CITY.includes(label)) {
localStorage.setItem("curCity", JSON.stringify({ label, value }))
this.props.history.go(-1);
} else {
Toast.info("该城市暂无房源信息", 1, null, false);
}
}
rowRenderer = ({key, index, style}) => {
const { cityKey, cityList } = this.state;
const letter = cityKey[index];
const row = cityList[letter];
return (
<div key={key} style={style} className="city">
<div className="city-title">{formatCityLetter(letter)}</div>
{
row.map(item => (
<div className="city-name" key={item.label} onClick={() => this.selectCity(item)}>{item.label}</div>
))
}
</div>
)
}
onRowsRendered = ({startIndex}) => {
this.setState({
activeKey: startIndex
})
}
async componentDidMount() {
await this.getCityList();
//调用 measureAllRows, 提前计算List中每一行的高度,实现scrollToRow的精确跳转
//注意: 调用这个方法的时候,需要保证List组件中已经有了数据,如果List组件中的数据为空,就会导致该方法报错
this.list.measureAllRows();
}
getHeight = ({ index }) => {
return TITLE_HEIGHT + NAME_HEIGHT * this.state.cityList[this.state.cityKey[index]].length;
}
scrollToRow = (key) => {
this.list.scrollToRow(key)
}
render() {
const { cityKey, cityList, activeKey } = this.state;
return (
<div className="city-list">
<NavBar>城市列表</NavBar>
{/* 列表渲染 */}
<AutoSizer>
{({width, height}) => (
<List
ref={el => this.list = el}
width={width}
height={height}
rowCount={cityKey.length}
rowHeight={this.getHeight}
rowRenderer={this.rowRenderer}
onRowsRendered={this.onRowsRendered}
scrollToAlignment="start"
/>
)}
</AutoSizer>
<ul className="city-key">
{
cityKey.map((item, index) => (
<li key={item} className="city-key-item" onClick={() => this.scrollToRow(index)}>
<span className={ activeKey === index ? "key-active" : "" }>
{ item === "hot" ? "热门" : item.toLocaleUpperCase() }
</span>
</li>
))
}
</ul>
</div>
)
}
}
export default CityList
<file_sep>/src/pages/Home/index.jsx
import React, { Component } from 'react';
import Swiper from '../../components/Swiper';
import HomeNav from '@/components/HomeNav';
import axios from '@/http/request';
import { Grid, Flex, WingBlank } from 'antd-mobile';
import { getCurCity } from '@/utils/ext';
import './index.scss';
class Home extends Component {
constructor(...args) {
super(...args);
this.state = {
swiperData: [],
groups: [],
news: [],
curCityInfo: {}
}
}
getSwiperData = async () => {
const { data } = await axios.get('/home/swiper');
const { status, body } = data;
if(status === 200) {
this.setState({
swiperData: [...body]
})
}
}
getGroup = async () => {
const { data } = await axios.get("/home/groups");
this.setState({
groups: data.body
})
}
getNews = async () => {
const { data } = await axios.get("/home/news");
this.setState({
news: data.body
})
}
getGeoLocation = async () => {
const ret = await getCurCity();
this.setState({
curCityInfo: ret
})
}
componentDidMount() {
this.getSwiperData();
this.getGroup();
this.getNews();
this.getGeoLocation();
}
render() {
const { swiperData, groups, news, curCityInfo } = this.state;
return (
<div className="home">
{(swiperData && curCityInfo) && <Swiper curCityInfo={curCityInfo} swiperData={swiperData} /> }
<HomeNav />
{/* 租房小组 */}
<div className="group">
<h3>租房小组</h3>
<span className="more">更多</span>
</div>
<div className="grid-group">
<Grid
data={groups}
square={false}
hasLine={false}
columnNum={2}
renderItem={item => (
<Flex justify="around" className="list-item">
<div className="desc">
<h3 className="title">{ item.title }</h3>
<span className="info">{ item.desc }</span>
</div>
<img src={`http://localhost:8080${item.imgSrc}`} alt="" />
</Flex>
)} />
</div>
{/* 新闻资讯 */}
<div className="news">
<h3 className="new-title">新闻资讯</h3>
<WingBlank>
{
news.map(item => (
<div className="news-item" key={item.id}>
<Flex style={{height: "100%"}}>
<div className="imgWrap">
<img className="img" src={`http://localhost:8080${item.imgSrc}`} alt="" />
</div>
<Flex className="content" direction="column" justify="between">
<h3>{ item.title }</h3>
<Flex className="info" justify="between">
<span>{ item.from }</span>
<span>{ item.date }</span>
</Flex>
</Flex>
</Flex>
</div>
))
}
</WingBlank>
</div>
</div>
)
}
}
export default Home
<file_sep>/src/components/PrivateRouter/index.jsx
import { Route, Redirect } from 'react-router-dom';
import { useSelector } from 'react-redux'
const PrivateRouter = ({ component: Comp, ...rest }) => {
const { isLogin } = useSelector(state => state.user);
return (
<Route {...rest} render={props => isLogin ? <Comp {...props} /> : <Redirect to={{
pathname: "/login",
state: {
pathname: props.location.pathname
}
}} />} />
)
}
export default PrivateRouter;<file_sep>/src/pages/HourseList/components/FilterPicker/index.jsx
import { useState } from 'react';
import { PickerView } from 'antd-mobile';
import FilterFooter from '@/components/FilterFooter';
const FilterPicker = ({ onCancel, onSave, data, cols, type, defaultSelectVal }) => {
const [value, setValue] = useState(defaultSelectVal);
return (
<div>
<PickerView
data={data}
value={value}
cols={cols}
onChange={(val) => setValue(val)}
/>
{/* 底部按钮 */}
<FilterFooter onSave={() => onSave(type, value)} onCancel={() => onCancel(type)} />
</div>
)
}
export default FilterPicker;<file_sep>/src/components/FilterFooter/index.jsx
import { Flex } from 'antd-mobile';
import styles from './index.module.css';
const FilterFooted = ({ onCancel, onSave, className, cancelText }) => {
return (
<Flex>
<button className={[styles.cancleBtn, styles.btn].join(" ")} onClick={onCancel}>{cancelText ? cancelText : '取消'}</button>
<button className={[styles.okBtn, styles.btn].join(" ")} onClick={onSave}>确定</button>
</Flex>
)
}
export default FilterFooted;<file_sep>/README.md
# Renting
基于react的在线租房web app项目
集体技术栈见package.json
<file_sep>/src/components/NavHeader/index.jsx
import { NavBar } from 'antd-mobile';
import './index.scss';
import { withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
const NavHeader = ({ children, history, className, rightContent }) => {
return (
<NavBar
className={className ? className : ""}
mode="light"
icon={<i className="iconfont icon-back"></i>}
onLeftClick={() => history.go(-1)}
rightContent={rightContent && rightContent}
>
{ children }
</NavBar>
)
}
NavHeader.propTypes = {
children: PropTypes.string
}
export default withRouter(NavHeader)<file_sep>/src/components/SearchHeader/index.jsx
import React from 'react';
import { Flex } from 'antd-mobile';
import PropsType from 'prop-types';
import './index.scss';
const SearchHeader = ({ cityName, history, className }) => {
return (
<Flex className={["search-header", className || ""]}>
<Flex className="search">
<div className="location" onClick={() => history.push('/cityList')}>
<span>{ cityName }</span>
<i className="iconfont icon-arrow"></i>
</div>
<div className="search-form" onClick={() => history.push("/search")}>
<i className="iconfont icon-seach"></i>
<span>请输入搜索内容</span>
</div>
</Flex>
<i className="iconfont icon-map" onClick={() => history.push('/map')}></i>
</Flex>
)
}
SearchHeader.propsType = {
cityName: PropsType.string.isRequired
}
export default SearchHeader<file_sep>/src/utils/ext.js
import axios from "@/http/request";
export function formatCityList(list) {
const cityList = {};
list.forEach(item => {
const key = item.short.substring(0, 1);
if(!cityList[key]) {
cityList[key] = [item];
} else {
cityList[key].push(item)
}
});
// 获取索引数据
const cityKey = Object.keys(cityList).sort();
return {
cityList, cityKey
}
}
export function getCurCity() {
const localCity = JSON.parse(localStorage.getItem("curCity"));
if(!localCity) {
return new Promise((resolve, reject) => {
try {
const map = new window.BMapGL.LocalCity();
map.get(async ({name}) => {
const { data } = await axios.get('/area/info', {
params: {
"name": name
}
});
localStorage.setItem("curCity", JSON.stringify(data.body))
resolve(data.body);
})
} catch(e) {
reject(e);
}
})
}
return Promise.resolve(localCity);
}
export function formatCityLetter(letter) {
switch(letter) {
case "#":
return "当前定位";
break;
case "hot":
return "热门";
break;
default:
return letter.toLocaleUpperCase();
break;
}
}
export function debounce(fn, timer, triggle) {
let t = null;
return function() {
const _self = this,
args = arguments;
if(t) {
clearTimeout(t)
}
if(triggle) {
const exec = !t;
t = setTimeout(() => {
t = null;
}, timer);
if(exec) {
fn.apply(_self, args);
}
} else {
t = setTimeout(() => {
fn.apply(_self, args);
}, timer)
}
}
}<file_sep>/src/pages/HourseList/components/FilterTitle/index.jsx
import React, { Component } from 'react'
import { Flex } from 'antd-mobile';
import './index.scss'
const config = [
{ title: "区域", type: "area" },
{ title: "方式", type: "mode" },
{ title: "租金", type: "price" },
{ title: "筛选", type: "more" },
]
class FilterTitle extends Component {
render() {
const { titleSelectedStatus, onTitleClick } = this.props;
return (
<Flex align="center" className="root">
{
config.map(item => (
<Flex.Item key={item.title} onClick={() => onTitleClick(item.type)}>
<span className={ titleSelectedStatus[item.type] ? "dropdown selected" : "dropdown" }>
<span>{ item.title }</span>
<i className="iconfont icon-arrow"></i>
</span>
</Flex.Item>
))
}
</Flex>
)
}
}
export default FilterTitle<file_sep>/src/components/Sticky/index.jsx
import React, { Component, createRef } from 'react';
import PropTypes from 'prop-types';
import './index.scss';
class Sticky extends Component {
placeHolder = createRef(null);
content = createRef(null);
handleScroll = () => {
const { top } = this.placeHolder.getBoundingClientRect();
if(top < 0) {
//吸顶
this.content.classList.add("sticky");
this.placeHolder.style.height = `${this.props.height}px`;
} else {
//取消吸顶
this.content.classList.remove("sticky")
this.placeHolder.style.height = "0px";
}
}
componentDidMount() {
window.addEventListener('scroll', this.handleScroll, false);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleScroll, false);
}
render() {
const { children } = this.props;
return (
<div>
{/* 占位元素 */}
<div ref={el => this.placeHolder = el}>
</div>
{/* 筛选组件 */}
<div ref={el => this.content = el}>{ children }</div>
</div>
)
}
}
Sticky.propTypes = {
height: PropTypes.number.isRequired
}
export default Sticky;<file_sep>/src/utils/common.js
import Nav1 from '@/assets/imgs/nav-1.png';
import Nav2 from '@/assets/imgs/nav-2.png';
import Nav3 from '@/assets/imgs/nav-3.png';
import Nav4 from '@/assets/imgs/nav-4.png';
export const tabConfig = [
{
id: 1,
title: "首页",
icon: "icon-ind",
path: '/home'
},
{
id: 2,
title: "找房",
icon: "icon-findHouse",
path: '/home/list'
},
{
id: 3,
title: "咨询",
icon: "icon-infom",
path: '/home/news'
},
{
id: 4,
title: "我的",
icon: "icon-my",
path: '/home/profile'
}
]
//导航菜单的数据
export const HomeNavConfig = [
{
id: 1,
img: Nav1,
title: "整租",
path: '/home/list'
},
{
id: 2,
img: Nav2,
title: '合租',
path: '/home/list'
},
{
id: 3,
img: Nav3,
title: '地图找房',
path: '/map'
},
{
id: 4,
img: Nav4,
title: '去出租',
path: '/rent/add'
}
]
export const BASE_URL = "http://localhost:8080"<file_sep>/src/store/actions.js
//user
export const SET_USER = "set-user";
export const REMOVE_USER = "remove-user";
<file_sep>/src/pages/Detail/index.jsx
import React, { Component } from 'react';
import axios from '@/http/request';
import styles from './index.module.css';
import { connect } from 'react-redux';
import { BASE_URL } from '@/utils/common';
import NavHeader from '@/components/NavHeader';
import HousePackage from '@/components/HousePackage';
import HouseItem from '@/components/HouseItem';
import { Carousel, Flex, Modal, Toast } from 'antd-mobile';
const Alert = Modal.alert;
// 猜你喜欢
const recommendHouses = [
{
id: 1,
src: '/img/message/1.png',
desc: '72.32㎡/南 北/低楼层',
title: '安贞西里 3室1厅',
price: 4500,
tags: ['随时看房']
},
{
id: 2,
src: '/img/message/2.png',
desc: '83㎡/南/高楼层',
title: '天居园 2室1厅',
price: 7200,
tags: ['近地铁']
},
{
id: 3,
src: '/img/message/3.png',
desc: '52㎡/西南/低楼层',
title: '角门甲4号院 1室1厅',
price: 4300,
tags: ['集中供暖']
}
]
const labelStyle = {
position: 'absolute',
zIndex: -7982820,
backgroundColor: 'rgb(238, 93, 91)',
color: 'rgb(255, 255, 255)',
height: 25,
padding: '5px 10px',
lineHeight: '14px',
borderRadius: 3,
boxShadow: 'rgb(204, 204, 204) 2px 2px 2px',
whiteSpace: 'nowrap',
fontSize: 12,
userSelect: 'none'
}
const list = [
'电视', '冰箱', '洗衣机', "空调", "热水器", "沙发", "衣柜", "天然气"
]
class Detail extends Component {
state = {
houseDetail: {},
loading: false,
isFavorite: false
}
componentDidMount() {
this.getHouseDetail();
this.checkFavorite()
}
getHouseDetail = async () => {
const { id } = this.props.match.params;
this.setState({ loading: true })
const { data } = await axios.get(`/houses/${id}`);
this.setState({
houseDetail: data.body,
loading: false
}, () => {
//渲染地图
this.renderMap(this.state.houseDetail.community, this.state.houseDetail.coord);
});
}
renderSwiper = () => {
const { houseImg } = this.state.houseDetail;
return houseImg && houseImg.map(item => (
<a key="item" href="www.baidu.com">
<img src={"http://localhost:8080" + item} className={styles.imgHeight} alt="" />
</a>
))
}
renderMap = (community, coord) => {
const map = new window.BMapGL.Map("containerMap");
const point = new window.BMapGL.Point(coord.longitude, coord.latitude);
map.centerAndZoom(point, 17);
const label = new window.BMapGL.Label('', {
position: point,
offset: new window.BMapGL.Size(0, -36)
});
label.setStyle(labelStyle)
label.setContent(`
<span>${community}</span>
<div class="${styles.mapArrow}"></div>
`)
map.addOverlay(label);
}
checkFavorite = async () => {
const { user: { isLogin }, match: { params } } = this.props;
if (!isLogin) return;
const { data } = await axios.get(`/user/favorites/${params.id}`);
if (data.status === 200 && data.body.isFavorite) {
this.setState({ isFavorite: data.body.isFavorite })
}
}
handleFavorite = async () => {
const { user: { isLogin }, history, location, match } = this.props;
if (!isLogin) { //如果未登录,用Modal提示用户去登录
Alert("提示", "确认登录后才能收藏房源", [
{ text: "取消" },
{
text: "去登录", onPress: () => history.push('/login', {
pathname: location.pathname
})
}
])
}
const { isFavorite } = this.state;
const { id } = match.params;
if (isFavorite) { //已经收藏, 应该删除收藏
this.setState({ isFavorite: false })
const { data } = await axios.delete(`/user/favorites/${id}`);
if (data.status === 200) {
Toast.info("取消收藏成功", 1, null, false);
} else {
//token超时
Toast.info("登录超时, 请重新登录", 1, null, false);
}
} else { //未收藏,应该添加收藏
const { data } = await axios.post(`/user/favorites/${id}`);
if (data.status === 200) {
Toast.success("收藏成功", 1, null, false);
this.setState({ isFavorite: true });
} else {
Toast.info("登录超时, 请重新登录", 1, null, false);
}
}
}
render() {
const { houseDetail: { community, title, tags, price, roomType, size, floor, oriented, supporting, description }, loading, isFavorite } = this.state;
return (
<div className={styles.detail}>
{/* 导航栏 */}
<NavHeader
className={styles.navNoMargin}
rightContent={<i key="share" className="iconfont icon-share"></i>}
>
{community && community}
</NavHeader>
{/* 轮播图 */}
<div className={styles.detailSlider}>
{
!loading ? <Carousel infinite autoplay={true}>
{this.renderSwiper()}
</Carousel> : null
}
</div>
{/* 房屋基本信息 */}
<div className={styles.info}>
<h3 className={styles.title}>{title}</h3>
<Flex className={styles.tags}>
<Flex.Item>
{
tags && tags.map((item, i) => (
<span key={item} className={[styles.tag, (i + 1 < 3) ? styles["tag" + (i + 1)] : styles.tag3].join(" ")}>{item}</span>
))
}
</Flex.Item>
</Flex>
{/* 价钱信息 */}
<Flex className={styles.infoPrice}>
<Flex.Item className={styles.infoPriceItem}>
<div>{price}/月</div>
<div>租金</div>
</Flex.Item>
<Flex.Item className={styles.infoPriceItem}>
<div>{roomType}</div>
<div>房型</div>
</Flex.Item>
<Flex.Item className={styles.infoPriceItem}>
<div>{size}平米</div>
<div>面积</div>
</Flex.Item>
</Flex>
<Flex className={styles.infoBasic} align="start">
<Flex.Item>
<div>
<span className={styles.title}>装修:</span>
精装
</div>
<div>
<span className={styles.title}>楼层:</span>
{floor}
</div>
</Flex.Item>
<Flex.Item>
<div>
<span className={styles.title}>朝向:</span>
{oriented && oriented.join("、")}
</div>
<div>
<span className={styles.title}>类型:</span>普通住宅
</div>
</Flex.Item>
</Flex>
</div>
{/* 地图位置 */}
<div className={styles.map}>
<div className={styles.mapTitle}>
小区: <span className={styles.mapTitleArea}>{community}</span>
</div>
<div id="containerMap" className={styles.mapContainer}>
</div>
</div>
{/* 房屋配套 */}
<div className={styles.about}>
<div className={styles.houseTitle}>房屋配套</div>
{
(!supporting || supporting.length === 0) ? (
<div className={styles.noData}>暂无数据</div>
) : (
<HousePackage list={supporting && supporting} />
)
}
</div>
{/* 房源概况 */}
<div className={styles.set}>
<div className={styles.houseTitle}>房源概况</div>
<div className={styles.concact}>
<div className={styles.user}>
<img className={styles.avatar} src="http://localhost:8080/img/avatar.png" alt="" />
<div className={styles.userTag}>
<div>王女士</div>
<div className={styles.userAuth}><i className={`iconfont icon-auth ${styles.authIcon}`} />已认证房主</div>
</div>
</div>
<div>
<button className={styles.btn}>发消息</button>
</div>
</div>
<div className={styles.describe}>
{description ? description : "暂无房间描述..."}
</div>
</div>
{/* 猜你喜欢 */}
<div className={styles.love}>
<div className={styles.houseTitle}>猜你喜欢</div>
<div>
{
recommendHouses.map(item => (
<HouseItem key={item.id}
houseCode={String(item.id)}
houseImg={item.src}
title={item.title}
desc={item.desc}
tags={item.tags}
price={item.price}
/>
))
}
</div>
</div>
{/* 底部按钮 */}
<Flex className={styles.bottomAction}>
<Flex.Item className={styles.actionItem} onClick={this.handleFavorite}>
<img
src={BASE_URL + (isFavorite ? "/img/star.png" : "/img/unstar.png")}
className={styles.favoriteImg}
alt="收藏"
/>
<span className={styles.favorite}>{isFavorite ? "已收藏" : "收藏"}</span>
</Flex.Item>
<Flex.Item className={styles.actionItem}>
<span>电话预约</span>
</Flex.Item>
<Flex.Item className={styles.actionItem} style={{ backgroundColor: "#67C23A", color: '#fff' }}>
<span>在线咨询</span>
</Flex.Item>
</Flex>
</div>
)
}
}
export default connect(state => state)(Detail);<file_sep>/src/pages/HourseList/components/FilterMore/index.jsx
import { useState } from 'react';
import FilterFooter from '@/components/FilterFooter';
import './index.scss';
const FilterMore = ({ data, openType, onSave, selectedVal, onCancel }) => {
const { roomType, oriented, floor, characteristic } = data;
const [selectedValue, setSelected] = useState(selectedVal);
const handleSelect = ({ value }) => {
if(selectedValue.indexOf(value) !== -1) {
const index = selectedValue.findIndex(val => val === value);
selectedValue.splice(index, 1)
setSelected([...selectedValue])
} else {
setSelected([...selectedValue, value])
}
}
const renderFilter = (data) => {
return (
data.map(item => {
return <span onClick={() => handleSelect(item)} key={item.value} className={ selectedValue.includes(item.value) ? "tag selected" : "tag"}>{ item.label }</span>
})
)
}
const onClear = () => {
setSelected([]);
}
const onOk = () => {
onSave(openType, selectedValue);
}
return (
<div className="filter-more">
<div className="mask" onClick={() => onCancel(openType)}></div>
<div className="tags">
<dl className="dl">
<dt className="dt">户型</dt>
<dd className="dd">
{ renderFilter(roomType) }
</dd>
<dt className="dt">朝向</dt>
<dd className="dd">
{ renderFilter(oriented) }
</dd>
<dt className="dt">楼层</dt>
<dd className="dd">
{ renderFilter(floor) }
</dd>
<dt className="dt">房屋高亮</dt>
<dd className="dd">
{ renderFilter(characteristic) }
</dd>
</dl>
<div className="footer">
<FilterFooter cancelText="清除" onCancel={onClear} onSave={onOk} />
</div>
</div>
</div>
)
}
export default FilterMore;<file_sep>/src/pages/HourseList/components/Filter/index.jsx
import React, { Component } from 'react';
import FilterTitle from '../FilterTitle';
import FilterPicker from '../FilterPicker';
import FilterMore from '../FilterMore';
import { Spring, animated } from 'react-spring';
import './index.scss'
import axios from '@/http/request';
class Filter extends Component {
constructor(props) {
super(props);
this.state = {
titleSelectedStatus: {
area: false,
mode: false,
price: false,
more: false
},
openType: "", //控制filterPicker或者filterMore的显示隐藏,
filterData: {},
//筛选条件选中值
selectedValues: {
"area": ['area', "null"],
"mode": ['null'],
"price": ['null'],
"more": []
}
}
}
renderMask = () => {
const { openType } = this.state;
const isHide = (openType === "area" || openType === "mode" || openType === "price")
return <Spring from={{opacity: 0}} to={{opacity: isHide ? 1 : 0}}>
{styles => {
const isOpacity = styles.opacity.animation.from;
if(isHide === false) return null;
return (
<animated.div style={styles} className="mask" onClick={() => this.onCancel(openType)}></animated.div>
)
}}
</Spring>
// return openType === "area" || openType === "mode" || openType === "price" ? <Spring from={{opacity: 0}} to={{opacity: 1}}>
// {styles => <animated.div style={styles} className="mask" onClick={this.onCancle}></animated.div>}
// </Spring>
// : null
}
getFiltersData = async () => {
//获取当前定位id
const { value } = JSON.parse(localStorage.getItem('curCity'));
const { data } = await axios.get(`/houses/condition?id=${value}`);
this.setState({
filterData: data.body
})
}
renderFilterPicker = () => {
const { openType, filterData: { area, subway, rentType, price }, selectedValues } = this.state;
if(openType !== "area" && openType !== "price" && openType !== "mode") return null;
let data = [];
let cols = 3;
const defaultSelectVal = selectedValues[openType];
switch(openType) {
case "area":
data = [area, subway];
cols = 3;
break;
case 'mode':
data = rentType;
cols = 1;
break;
case "price":
data = price;
cols = 1
break;
default:
break;
}
return <FilterPicker key={openType} defaultSelectVal={defaultSelectVal} type={openType} cols={cols} data={data} onSave={this.onSave} onCancel={this.onCancel} />
}
componentDidMount() {
this.getFiltersData();
this.body = document.querySelector("body");
}
onTitleClick = (type) => {
// 在显示遮罩层的时候让body->overflow -> hidden取消滚动
this.body.classList.add('body-fixed');
const { titleSelectedStatus, selectedValues } = this.state;
//创建新的标题选中状态
const newTitleSelectStatus = {...titleSelectedStatus};
Object.keys(titleSelectedStatus).forEach(key => {
if(type === key) {
newTitleSelectStatus[key] = true;
} else {
//其他标题
const selectVal = selectedValues[key];
if(key === "area" && (selectVal.length !== 2 || selectVal[0] !== 'area')) {
newTitleSelectStatus[key] = true;
} else if(key === "mode" && selectVal[0] !== "null") {
newTitleSelectStatus[key] = true;
} else if(key === "price" && selectVal[0] !== 'null') {
newTitleSelectStatus[key] = true;
} else if(key === "more" && selectVal.length !== 0) {
newTitleSelectStatus[key] = true;
} else {
newTitleSelectStatus[key] = false;
}
}
})
this.setState({
titleSelectedStatus: newTitleSelectStatus,
openType: type
})
}
onCancel = (type) => {
const { selectedValues, titleSelectedStatus } = this.state,
selectVal = selectedValues[type],
newTitleSelectStatus = {...titleSelectedStatus};
//再点取消的时候看看当前title是否有选中的值,选中的话就高亮,没选中不高亮
if(type === "area" && (selectVal.length !== 2 || selectVal[0] !== 'area')) {
newTitleSelectStatus[type] = true;
} else if(type === "mode" && selectVal[0] !== "null") {
newTitleSelectStatus[type] = true;
} else if(type === "price" && selectVal[0] !== 'null') {
newTitleSelectStatus[type] = true;
} else if(type === "more" && selectVal.length !== 0) {
newTitleSelectStatus[type] = true;
} else {
newTitleSelectStatus[type] = false;
}
this.setState({
openType: '',
titleSelectedStatus: {...newTitleSelectStatus}
})
//再关闭对话框中移除body的限制滚动类
this.body.classList.remove("body-fixed");
}
onSave = (type, value) => {
this.body.className = ""
const { titleSelectedStatus } = this.state;
const selectVal = value;
const newTitleSelectStatus = {...titleSelectedStatus};
//再点确定的时候看看当前title是否有选中的值,选中的话就高亮,没选中不高亮
if(type === "area" && (selectVal.length !== 2 || selectVal[0] !== 'area')) {
newTitleSelectStatus[type] = true;
} else if(type === "mode" && selectVal[0] !== "null") {
newTitleSelectStatus[type] = true;
} else if(type === "price" && selectVal[0] !== 'null') {
newTitleSelectStatus[type] = true;
} else if(type === "more" && selectVal.length !== 0) {
newTitleSelectStatus[type] = true;
} else {
newTitleSelectStatus[type] = false;
}
this.setState({
selectedValues: {
...this.state.selectedValues,
[type]: value
},
openType: '',
titleSelectedStatus: {...newTitleSelectStatus}
}, () => {
//获取筛选值
const filters = {};
const { area, mode, price, more } = this.state.selectedValues;
let areaValue = "null";
if(area.length === 3) {
areaValue = area[2] !== "null" ? area[2] : area[1];
}
filters[area[0]] = areaValue;
filters.mode = mode[0];
filters.price = price[0];
filters.more = more.join(",");
this.props.onFilter(filters);
});
}
render() {
const { titleSelectedStatus, selectedValues, openType, filterData: { roomType, oriented, floor, characteristic } } = this.state;
const data = { roomType, oriented, floor, characteristic };
return (
<div className="filter">
{/* 遮罩层 */}
{
this.renderMask()
}
<div className="filter-content">
<FilterTitle titleSelectedStatus={titleSelectedStatus} onTitleClick={this.onTitleClick}/>
{ this.renderFilterPicker() }
{/* 更多筛选栏 */}
{ openType === "more" && <FilterMore onCancel={this.onCancel} selectedVal={selectedValues[openType]} openType={openType} onSave={this.onSave} data={data} /> }
</div>
</div>
)
}
}
export default Filter;<file_sep>/src/components/TabBar/index.jsx
import React, { PureComponent } from 'react';
import { TabBar } from 'antd-mobile';
import './index.scss';
class Tab extends PureComponent {
render() {
const { selectedTab, handleSelected, tabConfig } = this.props;
return (
<TabBar
tintColor="#21b97a"
barTintColor="white"
noRenderContent={true}
>
{
tabConfig.map(item => (
<TabBar.Item
title={item.title}
key={item.title}
icon={
<i className={`iconfont ${item.icon}`}></i>
}
selectedIcon={
<i className={`iconfont ${item.icon} icon-selected`}></i>
}
selected={selectedTab === item.path}
onPress={() => handleSelected(item.path)}
data-seed="logId"
>
</TabBar.Item>
))
}
</TabBar>
)
}
}
export default Tab<file_sep>/src/components/NoHouse/index.jsx
import PropTypes from 'prop-types';
import "./index.scss";
const NoHouse = ({ children }) => {
return (
<div className="no-house">
<img src="http://localhost:8080/img/not-found.png" alt="" />
<p>{children}</p>
</div>
)
}
NoHouse.propTypes = {
children: PropTypes.node.isRequired
}
export default NoHouse;<file_sep>/src/components/Loading/index.jsx
import styles from './index.module.css';
import loadImg from '@/assets/imgs/loading.gif'
const Loading = () => {
return (
<div className={styles.loading}>
<img className={styles.loadingImg} src={loadImg} alt="" />
</div>
)
}
export default Loading;<file_sep>/src/http/request.js
import axios from 'axios';
import { getToken, isAuth, removeToken } from '@/utils/auth';
axios.defaults.baseURL = "http://localhost:8080";
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
const service = axios.create({
// timeout: 5000
});
service.interceptors.request.use((config) => {
const { url } = config;
if(url.startsWith("/user") && !url.startsWith("/user/login") && !url.startsWith("/user/registered")) {
config.headers["Authorization"] = getToken();
}
//在请求发送前配置些什么, 例如token
return config;
}, error => {
console.log(error)
return Promise.reject(error);
});
service.interceptors.response.use((response) => {
if(response.data.status !== 200) {
//说明请求失败,移除token
removeToken();
}
return response;
}, error => {
return Promise.reject(error);
});
export default service;
//1.判断接口路径是否是以/user开头的,并且不是登录或注册接口
//2.如果是,加上请求头Authorization
//3.添加相应拦截
//4.判断返回值中的状态码
//5.如果是404,表示token超时或异常,直接移除token<file_sep>/src/pages/Login/index.jsx
import { Component } from 'react';
import NavHeader from '@/components/NavHeader';
import { WhiteSpace, WingBlank, Flex, Toast } from 'antd-mobile';
import { withFormik, Form, Field, ErrorMessage } from 'formik';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom'
import { bindActionCreators } from 'redux'
import { setUserInfo } from '@/store/User/actions';
import * as Yup from 'yup';
import axios from '@/http/request.js';
import styles from './index.module.css';;
class Login extends Component {
constructor(props) {
super(props);
}
render() {
const { values, handleSubmit, user: { isLogin }, history } = this.props;
const { pathname } = history.location.state;
if (isLogin) {
return <Redirect to={pathname} />
}
return (
<div>
<NavHeader className={styles.noMargin}>
登录
</NavHeader>
<WhiteSpace size="xl" />
<WingBlank>
<Form className={styles.form}>
<div className={styles.formItem}>
<Field className={styles.input} type="text" name="username" placeholder="请输入账号" />
{/* <input
type="text"
name="username"
placeholder="请输入账号"
className={styles.input}
value={values.username}
onChange={handleChange}
onBlur={handleBlur}
/> */}
</div>
<ErrorMessage className={styles.error} name="username" component="div" />
{/* {errors.username && touched.username && <div className={styles.error}>{errors.username}</div>} */}
<div className={styles.formItem}>
<Field className={styles.input} type="password" name="password" placeholder="<PASSWORD>" />
{/* <input
type="text"
name="password"
type="<PASSWORD>"
placeholder="<PASSWORD>"
className={styles.input}
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
/> */}
</div>
{/* {errors.password && touched.password && <div className={styles.error}>{errors.password}</div>} */}
<ErrorMessage className={styles.error} name="password" component="div" />
</Form>
<Flex className={styles.loginBox}>
<Flex.Item>
<button className={styles.login} onClick={handleSubmit}>登录</button>
</Flex.Item>
</Flex>
</WingBlank>
<div className={styles.register}>还没有账号,去注册~</div>
</div>
)
}
}
Login = withFormik({
mapPropsToValues: () => ({ username: "", password: "" }),
handleSubmit: async (values, { props }) => {
const { username, password } = values;
const { data: { status, body, description } } = await axios.post("/user/login", {
username, password
});
if (status === 200) {
// 登录成功
//存储数据到redux中
props.handleSetup(body.token);
// props.history.go(-1);
} else { //登陆失败
Toast.info(description, 2, null, false);
}
},
validationSchema: Yup.object().shape({
username: Yup.string().required("账号为必填项").matches(/^[a-zA-Z_\d]{5,8}$/, "长度为5-8位,只能出现数字,字母,下划线"),
password: Yup.string().required("密码为必填项").matches(/^[a-zA-Z_\d]{5,12}/, "长度为5-12位,只能出现数字,字母,下划线")
})
})(Login)
const mapActionsToProps = dispatch => ({
handleSetup: bindActionCreators(setUserInfo, dispatch)
})
export default connect(state => state, mapActionsToProps)(Login);<file_sep>/src/store/User/index.js
import { SET_USER, REMOVE_USER } from '../actions';
function reducer(state = {
isLogin: false,
userInfo: {}
}, action) {
switch(action.type) {
case SET_USER:
return {
...state,
isLogin: true,
userInfo: {...action.userInfo}
}
break;
case REMOVE_USER:
return {
...state,
isLogin: false,
userInfo: {}
}
default:
return state;
break;
}
}
export default reducer<file_sep>/src/pages/HourseList/index.jsx
import React, { Component } from 'react'
import './index.scss';
import { Flex, Toast } from "antd-mobile";
import axios from '@/http/request';
import SearchHeader from '@/components/SearchHeader';
import Filter from './components/Filter';
import Sticky from '@/components/Sticky';
import { List, AutoSizer, WindowScroller, InfiniteLoader } from 'react-virtualized';
import HouseItem from '../../components/HouseItem';
import NoHouse from '../../components/NoHouse';
import { getCurCity } from '@/utils/ext';
// const { label, value } = JSON.parse(localStorage.getItem("curCity"));
export default class HourseList extends Component {
constructor(props) {
super(props);
this.filters = {};
this.state = {
list: [],
count: 0,
loading: false
}
}
async componentDidMount() {
const { label, value } = await getCurCity();
this.label = label;
this.value = value;
this.searchHouseList();
}
onFilter = (filters) => {
this.filters = filters;
this.searchHouseList();
}
searchHouseList = async () => {
//每次筛选返回页面顶部
window.scrollTo(0, 0);
this.setState({ loading: true });
Toast.loading("Loading", 0, null, false)
const { data } = await axios.get("/houses", {
params: {
cityId: this.value,
...this.filters,
start: 1,
end: 20
}
});
this.setState({
list: data.body.list,
count: data.body.count,
loading: false
}, () => {
const { count } = this.state;
Toast.hide();
if(count != 0) {
Toast.info(`共找到了${count}套房源`, 1, null, true);
}
})
}
rowRenderer = ({key, index, style}) => {
const { list } = this.state;
const data = list[index];
//判断data是否存在如果不存在渲染Loading
if(!data) {
return (
<div key={key} style={style}>
<p className="loading"></p>
</div>
)
}
return (
<HouseItem key={key} style={style} {...data} />
)
}
//判断列表中的每一项是否加载成功
isRowLoaded = ({ index }) => {
return !!this.state.list[index]
}
//用来获取更多房屋列表数据
//该方法的返回值为Promise对象,
loadMoreRows = ({startIndex, stopIndex}) => {
return new Promise(resolve => {
//数据加载完成调用resove即可
axios.get("/houses", {
params: {
cityId: this.value,
...this.filters,
start: startIndex,
end: stopIndex
}
}).then((res) => {
//合并数据到list
this.setState({
list: [...this.state.list, ...res.data.body.list]
})
//调用resolve完成
resolve();
})
})
}
render() {
const { count, loading } = this.state;
const { history } = this.props;
return (
<div className="house-list">
<Flex className="search-box">
<i className="iconfont icon-back" onClick={() => history.go(-1)}></i>
<SearchHeader history={history} cityName={this.label} className="noPosi" />
</Flex>
{/* 筛选栏 */}
<Sticky height={40}>
<Filter onFilter={this.onFilter} />
</Sticky>
{
(count === 0 && loading === false) ? <NoHouse>未找到房源,请换个搜索条件吧!</NoHouse> : (
<div className="houseItems">
<InfiniteLoader
isRowLoaded={this.isRowLoaded}
loadMoreRows={this.loadMoreRows}
rowCount={count}
>
{
({onRowsRendered, registerChild}) => (
<WindowScroller>
{
({height, isScrolling, scrollTop}) => (
<AutoSizer>
{
({width}) => (
<List
ref={registerChild}
onRowsRendered={onRowsRendered}
autoHeight
width={width}
height={height}
rowCount={count}
rowHeight={120}
rowRenderer={this.rowRenderer}
isScrolling={isScrolling}
scrollTop={scrollTop}
/>
)
}
</AutoSizer>
)
}
</WindowScroller>
)
}
</InfiniteLoader>
</div>
)
}
</div>
)
}
}
<file_sep>/src/components/HouseItem/index.jsx
import PropTypes from 'prop-types';
import styles from './index.module.css';
import { withRouter } from 'react-router-dom';
const HouseItem = ({ houseCode, houseImg, title, desc, tags, price, history }) => {
return (
<div className={styles.house} key={houseCode} onClick={() => history.push(`/detail/${houseCode}`)}>
<div className={styles.imgWrap}>
<img src={`http://localhost:8080${houseImg}`} className={styles.img} />
</div>
<div className={styles.content}>
<h3 className={styles.title}>{title}</h3>
<div className={styles.desc}>{ desc }</div>
<div className={styles.tags}>
{
tags && tags.map((cItem,index) => (
<span key={cItem} className={[styles.tag, styles[`tag${index + 1}`]].join(" ")}>{cItem}</span>
))
}
</div>
<div className={styles.priceWrap}><span className={styles.price}>{price} </span>元/月</div>
</div>
</div>
)
}
HouseItem.propTypes = {
houseCode: PropTypes.string.isRequired,
houseImg: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
desc: PropTypes.string.isRequired,
tags: PropTypes.array.isRequired,
price: PropTypes.number.isRequired
}
export default withRouter(HouseItem);
<file_sep>/src/App.js
import { useEffect, lazy, Suspense } from 'react';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
import Router from './Router';
import { getToken, isAuth } from './utils/auth';
import axios from '@/http/request';
import { useDispatch } from 'react-redux';
import { setUserInfo } from '@/store/User/actions';
import PrivateRouter from './components/PrivateRouter';
import Loading from '@/components/Loading';
const CityList = lazy(() => import("./pages/CityList"))
const Map = lazy(() => import("./pages/Map"))
const Detail = lazy(() => import("./pages/Detail"));
const Login = lazy(() => import("./pages/Login"));
const Rent = lazy(() => import("./pages/Rent"));
const RentAdd = lazy(() => import("./pages/Rent/Add"));
const RentSearch = lazy(() => import("./pages/Rent/Search"));
function App() {
const dispatch = useDispatch();
const setup = async () => {
if(isAuth()) {
const token = getToken();
dispatch(setUserInfo(token));
}
}
useEffect(() => {
setup();
}, [])
return (
<div className="App">
<BrowserRouter>
<Switch>
<Suspense fallback={<Loading />}>
<Route path="/home" component={Router} />
<Route path="/citylist" component={CityList} />
<PrivateRouter path="/map" component={Map} />
<Route path="/detail/:id" component={Detail} />
<Route path="/login" component={Login} />
<PrivateRouter path="/rent" exact component={Rent} />
<PrivateRouter path="/rent/add" component={RentAdd} />
<PrivateRouter path="/rent/search" component={RentSearch} />
<Redirect from="/" to="/home"/>
</Suspense>
</Switch>
</BrowserRouter>
</div>
);
}
export default App;
|
d706ca8d8a329b95a34ba6f5e65b97b040dc8aed
|
[
"JavaScript",
"Markdown"
] | 26
|
JavaScript
|
danceli/Renting
|
b687c7fa264af0ede5bbf23a1a07aa4466321fa6
|
d97b4796afc6a785a3c3be0756cfd66a80fd73ef
|
refs/heads/main
|
<file_sep># Win10 - WebView2 - WPF - Virtual Host Name Long Path Length Problem Demo
Using [SetVirtualHostNameToFolderMapping](https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.setvirtualhostnametofoldermapping?view=webview2-dotnet-1.0.864.35) with WebView2 allows you to map a virutal host name to a folder path. This is like an excellent way to preview content but at present it doesn't support long file paths on Windows - this repo is a quick test/demonstration of that created in part to help me confirm all the details.
In the issue filed for this - [Long File Paths result in Broken Content when using SetVirtualHostNameToFolderMapping · Issue #1573 · MicrosoftEdge/WebView2Feedback · GitHub](https://github.com/MicrosoftEdge/WebView2Feedback/issues/1573) - @champnic noted that "This is a known limitation currently of file loading, and I believe it also affects Microsoft Edge and Chromium. I'll open this bug on our backlog, but in full transparency it's likely to be lower priority for us."
To check this repo out on Windows you will have to set the core.longpaths true HOWEVER you might want to see [git/core.txt at d003d728ffa6c0006da875ec6318d3f6b28a4ddb · git-for-windows/git](https://github.com/git-for-windows/git/blob/d003d728ffa6c0006da875ec6318d3f6b28a4ddb/Documentation/config/core.txt#L560-L565) for some potential downfalls. (If you are using GitHub Desktop and having problems try running 'git config --global core.longpaths true' - I found the sometimes recommended '--system' did not help.) (As an aside for me this repo was eye opening in regards to the current default support for long file paths in Windows, File Explorer, Git, GitHub Desktop and Visual Studio - if you haven't run into this issue just trying to check out this repo might be interesting...)
Directly related to this issues are [Maximum Path Length Limitation - Win32 apps | Microsoft Docs](https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd) and [Naming Files, Paths, and Namespaces - Win32 apps | Microsoft Docs](https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN#maxpath).
I did try a few other things before creating an Issue, none of which had any impact on the problem:
- Use group policy to enable the newer Win10 behavior that removes the MAX_PATH limitations -> Computer Configuration > Administrative Templates > System > Filesystem > Enable Win32 long paths.
- Use the \\\\?\\ prefix in the call to SetVirtualHostNameToFolderMapping
- Add an application manifest with:
```xml
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings xmlns:ws2="http://schemas.microsoft.com/SMI/2016/WindowsSettings">
<ws2:longPathAware>true</ws2:longPathAware>
</windowsSettings>
</application>
```

The screen shot above is from the sample app and shows:
- In the top panel the source is set to an html file that is below MAX_PATH value and loads, but the top image is a link to a file beyond the MAX_PATH - the error is: Failed to load resource: net::ERR_ACCESS_DENIED (the top panel also includes some other working content as a sanity check)
- In the bottom panel the source is set to a file with a long enough name to be over the MAX_PATH and it fails to load
<file_sep>using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
using Microsoft.Web.WebView2.Core;
using VirtualMappingPathLengthErrorWpfDemo.Annotations;
namespace VirtualMappingPathLengthErrorWpfDemo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
InitializeAsync();
DataContext = this;
}
public event PropertyChangedEventHandler? PropertyChanged;
private async void InitializeAsync()
{
//This is a quick hack to find the test directory - easily broken, this is just
//for testing and not meant to demonstrate anything.
//
//Note that the test directory is not included in the project because
//Visual Studio does not seem to currently support long file paths in the
//solution explorer GUI?
//
var directoryParts = AppContext.BaseDirectory.Split("\\", StringSplitOptions.RemoveEmptyEntries);
var testSiteFolder = new DirectoryInfo(
@$"{string.Join("\\", directoryParts[..Array.IndexOf(directoryParts, "VirtualMappingPathLengthErrorWpfDemo")])}\VirtualHostNameToFolderMappingPathLengthTestForLongFilePathLength-LongFolderNameToHelpEnsureLongPathLength");
await VirtualView.EnsureCoreWebView2Async();
VirtualView.CoreWebView2.SetVirtualHostNameToFolderMapping("webview2.test", testSiteFolder.FullName,
CoreWebView2HostResourceAccessKind.Allow);
VirtualView.Source = new Uri("https://webview2.test/index.html");
await VirtualViewLongIndex.EnsureCoreWebView2Async();
VirtualViewLongIndex.CoreWebView2.SetVirtualHostNameToFolderMapping("webview2longindex.test", testSiteFolder.FullName,
CoreWebView2HostResourceAccessKind.Allow);
VirtualViewLongIndex.Source = new Uri("https://webview2longindex.test/index-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long.html");
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
460b72ca6af190a36eedcdc8fcff9f2490cff1f3
|
[
"Markdown",
"C#"
] | 2
|
Markdown
|
cmiles/WebView2VirtualHostNamePathLengthProblem
|
d1ce69bcb99121b8834fa75357eb30c23ea57e81
|
925dbccde8f1963b3872b09c18975fdfa85f6cfa
|
refs/heads/master
|
<file_sep>
//cat1
var elem1 = document.getElementById('cat1');
var times1 = document.getElementsByClassName('cat1_times')[0].innerText;
elem1.addEventListener('click', function(){
times1 = parseInt(times1) + 1;
document.getElementsByClassName("cat1_times")[0].innerText=times1 + " Times Clicked";
}, false);
//cat2
var elem2 = document.getElementById('cat2');
var times2 = document.getElementsByClassName('cat2_times')[0].innerText;
elem2.addEventListener('click', function(){
times2 = parseInt(times2) + 1;
document.getElementsByClassName("cat2_times")[0].innerText=+ times2+" Times Clicked";
}, false);
|
e1ef1bf01029e6cfec27324eb973c9b845c931e3
|
[
"JavaScript"
] | 1
|
JavaScript
|
TAMAJJJ/Cat-Clicker
|
9722a6841506a1f92133978dd15b40bc8c2a9182
|
d164874f9eab6eb7fc136dde3f8370aba2223427
|
refs/heads/master
|
<repo_name>cseu2bw/CS-Build-Week-2<file_sep>/BackEnd/src/game.py
from util import Stack, Queue
from player import Player
import os
import json
from ls8 import CPU
dir = os.path.dirname(__file__)
rooms_file = os.path.join(dir, '../rooms.json')
# rooms_file = os.path.join(dir, '../warped.json')
class Game:
def __init__(self):
self.load_rooms()
def load_rooms(self):
saved_rooms = dict()
try:
with open(rooms_file) as json_file:
saved_rooms = json.load(json_file)
temp_adj = dict()
temp_rooms = dict()
for key, value in saved_rooms['adjacency'].items():
temp_adj[int(key)] = value
saved_rooms['adjacency'] = temp_adj
for key, value in saved_rooms['rooms'].items():
temp_rooms[int(key)] = value
saved_rooms['rooms'] = temp_rooms
except:
saved_rooms['adjacency'] = dict()
saved_rooms['rooms'] = dict()
self.saved_rooms = saved_rooms
found = 0
for id, room in saved_rooms['rooms'].items():
if room["title"] == "Shop":
self.shop_id = id
found += 1
if room["title"] == "Wishing Well":
self.well_id = id
found += 1
if room["title"] == "Linh's Shrine":
self.dash_shrine_id = id
found += 1
if room["title"] == "Pirate Ry's":
self.name_change_id = id
found += 1
if room["title"] == "The Peak of Mt. Holloway":
self.flight_shrine_id = id
found += 1
if found >= 5:
break
def bfs_path(self, starting_room_id, check_func):
adj = self.saved_rooms['adjacency']
queue = Queue()
final_path = None
visited = set()
queue.enqueue([starting_room_id])
while queue.len() > 0:
path = queue.dequeue()
vert = path[-1]
if vert not in visited:
if check_func(vert):
final_path = path
break
visited.add(vert)
for room in adj[vert].values():
new_path = list(path)
new_path.append(room)
queue.enqueue(new_path)
if final_path is None:
return
new_path = []
for idx, room in enumerate(final_path):
if idx > 0:
lastRoom = final_path[idx - 1]
for direction in adj[lastRoom]:
if adj[lastRoom][direction] == room:
new_path.append({'dir': direction, 'next_room': room})
return new_path
def find_path_to(self, player, target_id):
def check(room_id):
nonlocal target_id
return room_id == target_id
return self.bfs_path(player.current_room.id, check)
def find_closest_unvisited(self, player, visited):
def check(room_id):
nonlocal visited
return room_id not in visited
return self.bfs_path(player.current_room.id, check)
<file_sep>/BackEnd/src/room.py
class Room:
def __init__(self, id=0, exits=None, title=None, description=None, coordinates=None, elevation=None, terrain=None, items=None):
self.id = id
self.exits = exits
self.title = title
self.description = description
self.coordinates = coordinates
self.elevation = elevation
self.terrain = terrain
self.items = items
<file_sep>/BackEnd/src/ls8.py
"""CPU functionality."""
import sys
import os
class CPU:
"""Main CPU class."""
def __init__(self):
"""Construct a new CPU."""
self.ram = [0] * 256
self.reg = [0] * 8
self.reg[7] = 0xf3
self.pc = 0
self.fl = 0
self.pra_out = ""
def load(self, program_in):
"""Load a program into memory."""
address = 0
program = list()
program_in = program_in.split('\n')
try:
for line in program_in:
comment_split = line.split("#")
num = comment_split[0].strip()
if len(num) == 0:
continue
value = int(num, 2)
program.append(value)
except FileNotFoundError:
print(f"{file_name} not found")
sys.exit(2)
for instruction in program:
self.ram[address] = instruction
address += 1
def alu(self, op, reg_a, reg_b):
"""ALU operations."""
if op == "ADD":
self.reg[reg_a] += self.reg[reg_b]
elif op == "MUL":
self.reg[reg_a] *= self.reg[reg_b]
elif op == "CMP":
self.fl = 0
a, b = self.reg[reg_a], self.reg[reg_b]
if a < b:
self.fl = 0b100
elif a == b:
self.fl = 0b001
elif a > b:
self.fl = 0b010
elif op == "AND":
self.reg[reg_a] = self.reg[reg_a] & self.reg[reg_b]
elif op == "OR":
self.reg[reg_a] = self.reg[reg_a] | self.reg[reg_b]
elif op == "XOR":
self.reg[reg_a] = self.reg[reg_a] ^ self.reg[reg_b]
elif op == "NOT":
self.reg[reg_a] = ~self.reg[reg_a]
elif op == "SHL":
self.reg[reg_a] = self.reg[reg_a] << self.reg[reg_b]
elif op == "SHR":
self.reg[reg_a] = self.reg[reg_a] >> self.reg[reg_b]
elif op == "MOD":
self.reg[reg_a] = self.reg[reg_a] % self.reg[reg_b]
elif op == "DIV":
if self.reg[reg_b] == 0:
raise Exception("Cannot divide by zero")
self.reg[reg_a] = self.reg[reg_a] / self.reg[reg_b]
elif op == "DEC":
self.reg[reg_a] -= 1
elif op == "SUB":
self.reg[reg_a] -= self.reg[reg_b]
else:
raise Exception("Unsupported ALU operation")
def spc(self, op, reg):
if op == "CALL":
#Push return address onto stack
self.reg[7] -= 1
MAR = self.reg[7]
MDR = self.pc + 2
self.ram_write(MAR, MDR)
#Set new PC
self.pc = self.reg[reg]
elif op == "RET":
#Pop top value off stack
MAR = self.reg[7]
#Set new PC
self.pc = self.ram_read(MAR)
self.reg[7] += 1
elif op == "JMP":
self.pc = self.reg[reg]
elif op == "JEQ" and self.fl == 0b001:
self.pc = self.reg[reg]
elif op == "JNE" and self.fl & 0b001 == 0:
self.pc = self.reg[reg]
elif op == "JGE" and self.fl & 0b011 > 0:
self.pc = self.reg[reg]
elif op == "JGT" and self.fl == 0b010:
self.pc = self.reg[reg]
elif op == "JLE" and self.fl & 0b101 > 0:
self.pc = self.reg[reg]
elif op == "JLT" and self.fl == 0b100:
self.pc = self.reg[reg]
else:
return False
return True
def ram_read(self, mar):
mdr = self.ram[mar]
return mdr
def ram_write(self, mar, mdr):
self.ram[mar] = mdr
def trace(self):
"""
Handy function to print out the CPU state. You might want to call this
from run() if you need help debugging.
"""
print(f"TRACE: %02X | %02X %02X %02X |" % (
self.pc,
#self.fl,
#self.ie,
self.ram_read(self.pc),
self.ram_read(self.pc + 1),
self.ram_read(self.pc + 2)
), end='')
for i in range(8):
print(" %02X" % self.reg[i], end='')
print()
def __verify_reg__(self, register):
if (register >> 3 & 0b11111) != 0:
return False
return True
def get_registers(self, offset, count):
registers = list()
for i in range(offset, offset + count):
register = self.ram_read(self.pc + i)
if not self.__verify_reg__(register):
print(f"Invalid register {register}")
return False
registers.append(register >> 0 & 0b111)
return registers
def run(self):
"""Run the CPU."""
ALU_OPS = {
0b0010: "MUL",
0b0111: "CMP",
0b0000: "ADD",
0b1000: "AND",
0b1010: "OR",
0b1011: "XOR",
0b1001: "NOT",
0b1100: "SHL",
0b1101: "SHR",
0b0100: "MOD",
0b0011: "DIV",
0b0110: "DEC",
0b0001: "SUB"
}
SPC_OPS = {
0b0101: "JEQ",
0b0110: "JNE",
0b0100: "JMP",
0b1010: "JGE",
0b0111: "JGT",
0b1001: "JLE",
0b1000: "JLT",
0b0001: "RET",
0b0000: "CALL"
}
running = True
def LDI(cpu):
registers = cpu.get_registers(1, 1)
if not registers:
return False
cpu.reg[registers[0]] = cpu.ram_read(cpu.pc + 2)
def PRN(cpu):
registers = cpu.get_registers(1, 1)
if not registers:
return False
print(cpu.reg[registers[0]])
def PUSH(cpu):
registers = cpu.get_registers(1, 1)
if not registers:
return False
cpu.reg[7] -= 1
MAR = cpu.reg[7]
MDR = cpu.reg[registers[0]]
cpu.ram_write(MAR, MDR)
def POP(cpu):
registers = cpu.get_registers(1, 1)
if not registers:
return False
MAR = cpu.reg[7]
MDR = cpu.ram_read(MAR)
cpu.reg[registers[0]] = MDR
cpu.reg[7] += 1
def PRA(cpu):
registers = cpu.get_registers(1, 1)
if not registers:
return False
self.pra_out += chr(cpu.reg[registers[0]])
def HLT(cpu):
return False
def OPCODE_to_operation(cpu, opcode):
operations = {
0b0010: LDI,
0b0111: PRN,
0b0101: PUSH,
0b0110: POP,
0b0001: HLT,
0b1000: PRA
}
# Get the function from switcher dictionary
if opcode not in operations:
print(f"Invalid instruction {opcode} at address {cpu.pc}")
return False
func = operations[opcode]
ret = func(cpu)
if ret is None:
return True
else:
return ret
while running:
IR = self.ram_read(self.pc)
OPERANDS = IR >> 6 & 0b11
ALU = IR >> 5 & 1
SPC = IR >> 4 & 1
OPCODE = IR >> 0 & 0b1111
if SPC == 1:
registers = self.get_registers(1, 1)
if not registers:
return False
if not self.spc(SPC_OPS[OPCODE], registers[0]):
self.pc += 1 + OPERANDS
else:
if ALU == 1:
registers = self.get_registers(1, 2)
if not registers:
return False
self.alu(ALU_OPS[OPCODE], registers[0], registers[OPERANDS - 1])
elif not OPCODE_to_operation(self, OPCODE):
running = False
break
self.pc += 1 + OPERANDS<file_sep>/BackEnd/src/util.py
class Queue:
def __init__(self):
self.storage = list()
def enqueue(self, value):
self.storage.append(value)
def dequeue(self):
if self.len() > 0:
return self.storage.pop(0)
else:
return None
def len(self):
return len(self.storage)
def __len__(self):
return self.len()
class Stack:
def __init__(self):
self.size = 0
self.storage = list()
def push(self, value):
self.storage.append(value)
def pop(self):
return self.storage.pop()
def len(self):
return len(self.storage)
def __len__(self):
return self.len()<file_sep>/BackEnd/src/player.py
import requests
import os
import threading
import time
from room import Room
from util import Queue
from actions import Actions
from status import Status
from ls8 import CPU
try:
base_url = os.environ['BASE_URL']
token = os.environ['TOKEN']
except:
print("Please set both BASE_URL and TOKEN in env file")
if token == '' or token is None:
print('Invalid token')
class Player:
def __init__(self, game=None):
self.token = 'Token ' + token
self.base_url = base_url
self.next_action_time = time.time()
self.current_room = Room()
self.queue = Queue()
self.game = game
self.actions = Actions(self)
self.status = Status()
self.init()
self.has_dash = True
self.has_flight = True
self.last_examine = dict()
def next_action(self):
cooldown = max(0, (self.next_action_time - time.time())) + 0.01 #Add buffer to prevent cooldown violation
time.sleep(cooldown)
print(f"Running next action from cooldown {cooldown}")
self.next_action_time = time.time()
if len(self.queue) > 0:
action = self.queue.dequeue()
args = action['args']
kwargs = action['kwargs']
action['func'](*args, **kwargs)
def queue_func(self, func, *_args, **_kwargs):
self.queue.enqueue({'func': func, 'args': _args, 'kwargs': _kwargs})
if len(self.queue) == 1:
self.next_action()
def travel(self, dir, id=None):
print(f"Trying to move {dir} to {id}")
if self.has_flight:
self.queue_func(self.actions.fly, dir, id)
print(f"Flew in direction {dir}")
elif dir in ['n', 's', 'e', 'w']:
self.queue_func(self.actions.move, dir, id)
def travel_path(self, path):
dashes = self.get_path_dashes(path)
print(dashes)
i = 0
while i < len(path):
dir = path[i]
if self.has_dash and str(dir['next_room']) in dashes:
dash = dashes[str(dir['next_room'])]
self.dash(dash['dir'], dash['rooms'])
i += len(dash['rooms'])
else:
i += 1
self.travel(dir['dir'], dir['next_room'])
def get_path_dashes(self, path):
current_dir = None
rooms = list()
dashes = dict()
for dir in path:
if dir['dir'] != current_dir:
if len(rooms) > 2:
dashes[rooms[0]] = {'dir': current_dir, 'rooms': rooms}
current_dir = dir['dir']
rooms = list()
rooms.append(str(dir['next_room']))
return dashes
def travel_to_target(self, room_id):
path = self.game.find_path_to(self, room_id)
print(path)
self.travel_path(path)
def collect_treasures(self, target_items):
visited = set()
current_items = 0
while current_items < target_items:
path = self.game.find_closest_unvisited(self, visited)
self.travel_path(path)
visited.add(self.current_room.id)
if len(self.current_room.items) > 0:
for item in self.current_room.items:
self.queue_func(self.actions.take, item)
current_items += 1
print("Current items:", current_items)
def get_dash(self):
self.travel_to_target(self.game.dash_shrine_id)
self.queue_func(self.actions.pray)
self.has_dash = True
def get_flight(self):
self.travel_to_target(self.game.flight_shrine_id)
self.queue_func(self.actions.pray)
self.has_flight = True
def dash(self, dir, rooms):
delimiter = ','
room_str = delimiter.join(rooms)
self.queue_func(self.actions.dash, dir, str(len(rooms)), room_str)
def sell_items(self):
self.travel_to_target(self.game.shop_id)
self.queue_func(self.actions.check_status)
for item in self.status.inventory:
self.queue_func(self.actions.sell, item)
self.queue_func(self.actions.check_status)
print("Gold:", self.status.gold)
def change_name(self, name):
self.travel_to_target(self.game.name_change_id)
self.queue_func(self.actions.change_name, name)
self.queue_func(self.actions.check_status)
print("Name", self.status.name)
def mine_next_block(self):
self.travel_to_target(self.game.well_id)
self.queue_func(self.actions.examine, 'WELL')
program ="#" + self.last_examine['description']
cpu = CPU()
cpu.load(program)
cpu.run()
room = int(cpu.pra_out.split(" ")[-1])
self.travel_to_target(room)
self.queue_func(self.actions.get_last_proof)
self.queue_func(self.actions.proof_of_work,
self.actions.last_proof.proof, self.actions.last_proof.difficulty)
self.queue_func(self.actions.mine, self.actions.new_proof)
def get_next_snitch(self):
self.travel_to_target(self.game.well_id)
self.queue_func(self.actions.examine, 'WELL')
program ="#" + self.last_examine['description']
cpu = CPU()
cpu.load(program)
cpu.run()
room = int(cpu.pra_out.split(" ")[-1])
print(f'The golden snitch is in room {room}')
self.travel_to_target(room)
self.queue_func(self.actions.take, 'golden snitch') # Try to pick up snitch
def init(self):
self.queue_func(self.actions.init)
self.queue_func(self.actions.check_status) # To check if we have abilities
self.has_dash = 'dash' in self.status.abilities
self.has_flight = 'fly' in self.status.abilities<file_sep>/BackEnd/src/proof.py
class Proof:
def __init__(self, proof=0, difficulty=0, cooldown=0.0, messages=[], errors=[]):
self.proof = proof
self.difficulty = difficulty
self.cooldown = cooldown
self.messages = messages
self.errors = errors
<file_sep>/BackEnd/src/complete_game.py
from game import Game
from player import Player
import os
import math
try:
name = os.environ['PLAYER_NAME']
except:
print("Please set desired name in .env file (variable 'PLAYER_NAME')")
game = Game()
player = Player(game)
player.queue_func(player.init)
if player.status.name != name:
target_items = int(math.ceil(((1000 - player.status.gold) / 100)))
if target_items > 0:
player.collect_treasures(target_items)
player.sell_items()
player.change_name(name)
if not player.has_flight:
player.get_flight()
if not player.has_dash:
player.get_dash()
# player.queue_func(player.actions.warp)
# player.init()
# player.travel_to_target(383)
# player.queue_func(player.actions.undress, 'well-crafted boots')
# player.queue_func(player.actions.drop, 'well-crafted boots')
# player.travel_to_target(495)
# player.queue_func(player.actions.take, 'well-crafted boots')
# player.queue_func(player.actions.wear, 'well-crafted boots')
while True:
player.mine_next_block()
<file_sep>/BackEnd/src/traverse_warped.py
from player import Player
from game import Game
from room import Room
from util import Stack, Queue
import random
import os
dir = os.path.dirname(__file__)
rooms_file = os.path.join(dir, '../warped.json')
import json
saved_rooms = dict()
try:
with open(rooms_file) as json_file:
saved_rooms = json.load(json_file)
temp_adj = dict()
temp_rooms = dict()
for key, value in saved_rooms['adjacency'].items():
temp_adj[int(key)] = value
saved_rooms['adjacency'] = temp_adj
for key, value in saved_rooms['rooms'].items():
temp_rooms[int(key)] = value
saved_rooms['rooms'] = temp_rooms
except:
saved_rooms['adjacency'] = dict()
saved_rooms['rooms'] = dict()
game = Game()
player = Player(game)
player.queue_func(player.init)
def reverseDir(dir):
if dir == "n":
return "s"
if dir == "s":
return "n"
if dir == "e":
return "w"
if dir == "w":
return "e"
else:
return None
def findShortestPath(adj):
q = Queue()
q.enqueue([player.current_room.id])
visited = set()
while q.len() > 0:
path = q.dequeue()
vert = path[-1]
if vert not in visited:
if "?" in adj[vert].values():
return path
visited.add(vert)
for room in adj[vert].values():
new_path = list(path)
new_path.append(room)
q.enqueue(new_path)
return None
def getDirPath(adj, path):
new_path = []
for idx, room in enumerate(path):
if idx > 0:
lastRoom = path[idx - 1]
for direction in adj[lastRoom]:
if adj[lastRoom][direction] == room:
new_path.append({'dir': direction, 'next_room': room})
return new_path
def travelDirPath(path):
for dir in path:
player.travel(dir['dir'], dir['next_room'])
def createTraversalPath(lastDir=None, lastRoom=None, adjacency=saved_rooms['adjacency'], rooms=saved_rooms['rooms']):
global player
rooms[player.current_room.id] = {
'title': player.current_room.title,
'description': player.current_room.description,
'coordinates': player.current_room.coordinates,
'elevation': player.current_room.elevation,
'terrain': player.current_room.terrain,
'items': player.current_room.items
}
with open(rooms_file, 'w') as json_file:
json.dump(saved_rooms, json_file)
print("Current room:", player.current_room.id, player.current_room.exits)
if len(adjacency) < 500:
print(f"Traversed rooms: {len(adjacency)}")
if player.current_room.id not in adjacency:
adj = dict()
for ext in player.current_room.exits:
adj[ext] = "?"
adjacency[player.current_room.id] = adj
if lastRoom:
adjacency[lastRoom][lastDir] = player.current_room.id
adjacency[player.current_room.id][reverseDir(lastDir)] = lastRoom
lastRoom = player.current_room.id
cur_adj = adjacency[player.current_room.id]
unvisited = list()
for direction, room in cur_adj.items():
if room == "?":
unvisited.append(direction)
if len(unvisited) > 0:
random.shuffle(unvisited)
direction = unvisited[0]
lastDir = direction
player.travel(direction)
else:
path = findShortestPath(adjacency)
if path is not None:
dir_path = getDirPath(adjacency, path)
travelDirPath(dir_path)
lastDir = dir_path[-1]['dir']
lastRoom = path[-2]
player.queue_func(createTraversalPath, lastDir, lastRoom)
createTraversalPath()<file_sep>/BackEnd/src/status.py
class Status:
def __init__(self, name='', cooldown=0, encumbrance=0, strength=0, speed=None, gold=None, bodywear=None, footwear=None, inventory=None, status=None, errors=None, messages=None, abilities=None):
self.name = name
self.cooldown = cooldown
self.encumbrance = encumbrance
self.strength = strength
self.speed = speed
self.gold = gold
self.bodywear = bodywear
self.footwear = footwear
self.inventory = inventory
self.status = status
self.errors = errors
self.messages = messages
self.abilities = abilities
<file_sep>/BackEnd/src/actions.py
import requests
import os
import threading
import time
from room import Room
from util import Queue
from status import Status
from timeit import default_timer as timer
import hashlib
import random
from proof import Proof
base_url = os.environ['BASE_URL']
class Actions:
def __init__(self, player):
self.player = player
self.base_url = base_url
self.message = ''
self.last_proof = Proof()
self.new_proof = 0
def init(self):
data = None
response = requests.get(self.base_url + '/adv/init/', headers={'Authorization': self.player.token})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.current_room = Room(data.get('room_id'), data.get('exits'), data.get('title'), data.get('description'), data.get('coordinates'), data.get('elevation'), data.get('terrain'), data.get('items'))
def move(self, dir, id=None):
if dir not in self.player.current_room.exits:
print('Invalid direction ' + dir)
return
to_send = {'direction': dir}
if id is not None:
to_send["next_room_id"] = str(id)
print(f'Moving into known room {id}')
response = requests.post(self.base_url + '/adv/move/', headers={'Authorization': self.player.token}, json=to_send)
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.current_room = Room(data.get('room_id'), data.get('exits'), data.get('title'), data.get('description'), data.get('coordinates'), data.get('elevation'), data.get('terrain'), data.get('items'))
print("Response:", data)
def take(self, item):
response = requests.post(self.base_url + '/adv/take/',
headers={'Authorization': self.player.token}, json={'name': item})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.current_room = Room(data.get('room_id'), data.get('exits'), data.get('title'), data.get(
'description'), data.get('coordinates'), data.get('elevation'), data.get('terrain'), data.get('items'))
print("Response:", data)
def drop(self, item):
response = requests.post(self.base_url + '/adv/drop/',
headers={'Authorization': self.player.token}, json={'name': item})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.current_room = Room(data.get('room_id'), data.get('exits'), data.get('title'), data.get(
'description'), data.get('coordinates'), data.get('elevation'), data.get('terrain'), data.get('items'))
print("Response:", data)
def check_price(self, item):
response = requests.post(self.base_url + '/adv/sell/',
headers={'Authorization': self.player.token}, json={'name': item})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.current_room = Room(data.get('room_id'), data.get('exits'), data.get('title'), data.get(
'description'), data.get('coordinates'), data.get('elevation'), data.get('terrain'), data.get('items'))
print("Response:", data)
def sell(self, item):
response = requests.post(self.base_url + '/adv/sell/', headers={
'Authorization': self.player.token}, json={'name': item, 'confirm': 'yes'})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.current_room = Room(data.get('room_id'), data.get('exits'), data.get('title'), data.get(
'description'), data.get('coordinates'), data.get('elevation'), data.get('terrain'), data.get('items'))
print("Response:", data)
def check_status(self):
response = requests.post(
self.base_url + '/adv/status/', headers={'Authorization': self.player.token})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.status = Status(data.get('name'), data.get('cooldown'), data.get('encumbrance'), data.get('strength'), data.get('speed'), data.get('gold'), data.get('bodywear'), data.get('footwear'), data.get('inventory'), data.get('status'), data.get('errors'), data.get('messages'), data.get('abilities'))
print("Response:", data)
def examine(self, item_or_player):
response = requests.post(self.base_url + '/adv/examine/', headers={
'Authorization': self.player.token}, json={'name': item_or_player})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.last_examine = dict()
self.player.last_examine['name'] = data.get('name')
self.player.last_examine["description"] = data.get('description')
print("Response:", data)
def wear(self, item):
response = requests.post(self.base_url + '/adv/wear/',
headers={'Authorization': self.player.token}, json={'name': item})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.status = Status(data.get('name'), data.get('cooldown'), data.get('encumbrance'), data.get('strength'), data.get('speed'), data.get('gold'), data.get('bodywear'), data.get('footwear'), data.get('inventory'), data.get('status'), data.get('errors'), data.get('messages'))
print("Response:", data)
def undress(self, item):
response = requests.post(self.base_url + '/adv/undress/',
headers={'Authorization': self.player.token}, json={'name': item})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.status = Status(data.get('name'), data.get('cooldown'), data.get('encumbrance'), data.get('strength'), data.get('speed'), data.get('gold'), data.get('bodywear'), data.get('footwear'), data.get('inventory'), data.get('status'), data.get('errors'), data.get('messages'))
print("Response:", data)
def change_name(self, new_name):
response = requests.post(self.base_url + '/adv/change_name/',
headers={'Authorization': self.player.token}, json={'name': new_name, 'confirm': 'aye'})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.status = Status(data.get('name'), data.get('cooldown'), data.get('encumbrance'), data.get('strength'), data.get('speed'), data.get('gold'), data.get('bodywear'), data.get('footwear'), data.get('inventory'), data.get('status'), data.get('errors'), data.get('messages'))
print("Response:", data)
def pray(self):
response = requests.post(
self.base_url + '/adv/pray/', headers={'Authorization': self.player.token})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.current_room = Room(data.get('room_id'), data.get('exits'), data.get('title'), data.get('description'), data.get('coordinates'), data.get('elevation'), data.get('terrain'), data.get('items'))
print("Response:", data)
def fly(self, dir, id=None):
if dir not in self.player.current_room.exits:
print('Invalid direction ' + dir)
return
to_send = {'direction': dir}
if id is not None:
to_send["next_room_id"] = str(id)
print(f'Flying into known room {id}')
response = requests.post(self.base_url + '/adv/fly/', headers={'Authorization': self.player.token}, json=to_send)
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.current_room = Room(data.get('room_id'), data.get('exits'), data.get('title'), data.get('description'), data.get('coordinates'), data.get('elevation'), data.get('terrain'), data.get('items'))
print("Response:", data)
def dash(self, dir, num_rooms, next_room_ids):
if dir not in self.player.current_room.exits:
print('Invalid direction ' + dir)
return
to_send = {'direction': dir, 'num_rooms': num_rooms, 'next_room_ids': next_room_ids}
response = requests.post(self.base_url + '/adv/dash/', headers={'Authorization': self.player.token}, json=to_send)
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.current_room = Room(data.get('room_id'), data.get('exits'), data.get('title'), data.get('description'), data.get('coordinates'), data.get('elevation'), data.get('terrain'), data.get('items'))
print("Response:", data)
def carry(self, item):
response = requests.post(self.base_url + '/adv/carry/',
headers={'Authorization': self.player.token}, json={'name': item})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.current_room = Room(data.get('room_id'), data.get('exits'), data.get('title'), data.get(
'description'), data.get('coordinates'), data.get('elevation'), data.get('terrain'), data.get('items'))
print("Response:", data)
def receive(self):
response = requests.post(self.base_url + '/adv/receive/',
headers={'Authorization': self.player.token})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.current_room = Room(data.get('room_id'), data.get('exits'), data.get('title'), data.get(
'description'), data.get('coordinates'), data.get('elevation'), data.get('terrain'), data.get('items'))
print("Response:", data)
def get_balance(self):
response = requests.get(self.base_url + '/bc/get_balance/',
headers={'Authorization': self.player.token})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.message = data.get('messages')[0]
print("Response:", data)
def transmogrify(self, item):
response = requests.post(self.base_url + '/adv/transmogrify/',
headers={'Authorization': self.player.token}, json={'name': item})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.player.current_room = Room(data.get('room_id'), data.get('exits'), data.get('title'), data.get(
'description'), data.get('coordinates'), data.get('elevation'), data.get('terrain'), data.get('items'))
print("Response:", data)
def proof_of_work(self, last_proof, difficulty):
start = timer()
print("Searching for next proof")
print(last_proof)
proof = 100000000
while self.valid_proof(last_proof, proof, difficulty) is False:
proof -= 1
print("Proof found: " + str(proof) + " in " + str(timer() - start))
self.new_proof = proof
def valid_proof(self, last_proof, proof, difficulty):
guess = f'{last_proof}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:difficulty] == '0' * difficulty
def mine(self, new_proof):
response = requests.post(self.base_url + '/bc/mine/',
headers={'Authorization': self.player.token}, json={'proof': int(new_proof)})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
print("Response:", data)
def warp(self):
response = requests.post(self.base_url + '/adv/warp/',
headers={'Authorization': self.player.token})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
print("Response:", data)
def get_last_proof(self):
response = requests.get(self.base_url + '/bc/last_proof/',
headers={'Authorization': self.player.token})
try:
data = response.json()
except ValueError:
print("Error: Non-json response")
print("Response returned:")
print(response)
return
self.player.next_action_time = time.time() + float(data.get('cooldown'))
self.last_proof = Proof(data.get('proof'), data.get('difficulty'), data.get(
'cooldown'), data.get('message'), data.get('errors'))
print("Response:", data)
<file_sep>/README.md
1 - Add in .env :<br />
BASE_URL = https://lambda-treasure-hunt.herokuapp.com/api<br />
PLAYER_NAME = the_name_you_picked<br />
TOKEN = <PASSWORD><br />
2 - Launch from cli:<br />
pipenv shell<br />
python3 Backend/src/complete_game.py<br />
3 - Go back to sleep<br />
|
ab546b966c759b2e80504ff3f3f95b6deb9c30fe
|
[
"Markdown",
"Python"
] | 11
|
Python
|
cseu2bw/CS-Build-Week-2
|
9ab0b0935c40ba97c48e66a74ca4989f77a1186b
|
decda0315df4c41f448d3567d7b43f71a371c6fe
|
refs/heads/master
|
<repo_name>eandresh/ejercicio_arquitectura<file_sep>/movies/app/UseCases/ListMovies.php
<?php
namespace App\UseCases;
use App\Repositories\Contracts\MoviesRepository;
class ListMovies
{
/**
* @var MoviesRepository
*/
private $moviesRepo;
public function __construct(MoviesRepository $moviesRepo)
{
$this->moviesRepo = $moviesRepo;
}
/**
* Retorna el listado completo de peliculas
* @return array
*/
public function getListMovies(): array
{
return $this->moviesRepo->getAll();
}
}
<file_sep>/movies/database/migrations/2020_02_07_203050_movies.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Movies extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('movies', function (Blueprint $table){
$table->increments('id');
$table->integer('vote_count')->unsigned();
$table->decimal('vote_average', 2,1);
$table->string('title', 150);
$table->string('original_title', 150);
$table->string('original_language', 4);
$table->tinyInteger('adult');
$table->string('poster_path', 255)->nullable()->default(null);
$table->text('overview');
$table->date('release_date');
$table->decimal('popularity', 5,3);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('movies');
}
}
<file_sep>/movies/public/js/movies/render.js
getAllMovies()
.then(function(response){
for (const mov of response.data) {
let movTemplate =
movieTemplate
.replace('{movieImg}', mov.poster_path)
.replace('{movieImg}', mov.poster_path)
.replace('{movieAverage}', mov.vote_average)
.replace('{movieLang}', mov.original_language)
.replace('{movieRelease}', mov.release_date)
.replace('{movieOverview}', mov.overview)
.replace('{movieName}', mov.title)
.replace('{movieName}', mov.title);
$('.moviesappcont').append(movTemplate);
}
});<file_sep>/movies/public/js/movies/services/find.js
let findMovie = function(id) {
let urlFind = FIND_MOVIE.replace('{idMovie}', id)
$.get(urlFind, function(data) {
console.log(data);
})
}<file_sep>/movies/routes/api.php
<?php
Route::group(['prefix' => 'api'], function(){
Route::group(['prefix' => 'movies'], function(){
Route::get('/', 'MoviesController@all');
Route::get('{id:[0-9)]+}', 'MoviesController@getMovie');
});
});
<file_sep>/movies/app/Services/TheMoviedb.php
<?php
namespace App\Services;
use GuzzleHttp\Client;
class TheMoviedb
{
private $url;
private $apiKey;
private $client;
public function __construct ()
{
$this->url = env('THEMOVIESDBURL');
$this->apiKey = env('THEMOVIESDBKEY');
$this->client = new Client();
}
public function getAll(): array
{
$response = $this->client->request('GET', $this->url.$this->apiKey);
$result = $response->getBody()->getContents();
return json_decode($result, true);
}
}
<file_sep>/movies/tests/ExampleTest.php
<?php
use Laravel\Lumen\Testing\DatabaseMigrations;
use Laravel\Lumen\Testing\DatabaseTransactions;
use App\Repositories\Contracts\MoviesRepository;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testExample()
{
$this->get('/');
$this->assertEquals(
$this->app->version(), $this->response->getContent()
);
}
/**
* @test
*/
public function getAllRandomMovies()
{
$repo = app(MoviesRepository::class);
$data = $repo->getAll();
$this->assertIsIterable($data);
$this->assertNotEmpty($data);
}
/**
* @test
*/
public function getMoviesTester()
{
$db = app(\App\Services\TheMoviedb::class);
$result = $db->getAll();
dd($result);
}
}
<file_sep>/movies/app/UseCases/GetMovie.php
<?php
namespace App\UseCases;
use App\Repositories\Contracts\MoviesRepository;
class GetMovie
{
/**
* @var MoviesRepository
*/
private $moviesRepository;
public function __construct(MoviesRepository $moviesRepository)
{
$this->moviesRepository = $moviesRepository;
}
public function getMovie(int $id): array
{
return $this->moviesRepository->find($id);
}
}
<file_sep>/movies/README.md
# Ejercicio arquitectura
Arquitectura a aplicar
##[Arquitectura por Capas]
- Se decide aplicar esta arquitectura debido a que es la mas sencilla de usar y el tamaño del proyecto
# Estructura Proyecto Landing Page
Front - Capa de presentación - Síncrona / Asíncrona (ajax)
- Listado de películas.
- Detalle de película.
PHP(servicios) - Capa de lógica
- Controladores
- Obtener el listado de películas.
- Obtener el detalle de una película.
- Casos de uso
- Listar películas.
- Obtener una película.
- Repositorios
- Películas
- Obtener todas las películas.
- Obtener una película.
Base de datos - Capa de negocio
RDB
- Movies
# Integrantes
- <NAME>
- <NAME>
- <NAME>
# Cambios Release 2.0
* Se añade servicio para consumir api de themoviesdb.org
* se añade nuevo repositorio para consumir nuevo servicio
* se cambia el bind del repositorio para que apunte a la nueva base de datos
# Variable de entorno
APP_NAME=Lumen
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost:8084
APP_TIMEZONE=UTC
LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=movies
DB_USERNAME=root
DB_PASSWORD=
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
THEMOVIESDBURL=
THEMOVIESDBKEY=
<file_sep>/movies/app/Repositories/TheMoviesDBRepository.php
<?php
namespace App\Repositories;
use App\Repositories\Contracts\MoviesRepository;
use App\Services\TheMoviedb;
class TheMoviesDBRepository implements MoviesRepository
{
public function getAll (): array
{
$theMovieDB = app(TheMoviedb::class);
$data = $theMovieDB->getAll();
return $data['results'];
}
public function find (int $id): array
{
return [];
}
}
<file_sep>/movies/app/Repositories/EloquentMoviesRepository.php
<?php
namespace App\Repositories;
use App\Repositories\Contracts\MoviesRepository;
use App\Models\Movie;
class EloquentMoviesRepository implements MoviesRepository
{
public function find (int $id): array
{
$movie = Movie::findOrFail($id);
return $movie->toArray();
}
public function getAll (): array
{
$movies = Movie::all()->random(20);
return $movies->toArray();
}
}
<file_sep>/movies/.env.example
APP_NAME=Lumen
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost:8084
APP_TIMEZONE=UTC
LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=
DB_CONNECTION=mysql
DB_HOST=10.14.7.107
DB_PORT=3306
DB_DATABASE=movies
DB_USERNAME=root
DB_PASSWORD=<PASSWORD>
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
THEMOVIESDBURL=https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&language=es&api_key=
THEMOVIESDBKEY=97471e5be48ff4bedbb9d38e23f92ac3
<file_sep>/movies/public/js/movies/services/getAll.js
let getAllMovies = function() {
return $.get(ALL_MOVIES, function(data) {
movies = data.data.map(function(item) {
item.poster_path = 'img/movies' + item.poster_path;
return item;
});
});
}<file_sep>/movies/app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use App\UseCases\GetMovie;
use App\UseCases\ListMovies;
use Illuminate\Support\ServiceProvider;
use App\Repositories\Contracts\MoviesRepository;
//use App\Repositories\EloquentMoviesRepository;
use App\Repositories\TheMoviesDBRepository;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//$this->app->bind(MoviesRepository::class, EloquentMoviesRepository::class);
$this->app->bind(MoviesRepository::class, TheMoviesDBRepository::class);
$this->app->bind(ListMovies::class, function(){
return new ListMovies(app(MoviesRepository::class));
});
$this->app->bind(GetMovie::class, function (){
return new GetMovie(app(MoviesRepository::class));
});
}
}
<file_sep>/movies/app/Http/Controllers/MoviesController.php
<?php
namespace App\Http\Controllers;
use App\UseCases\GetMovie;
use App\UseCases\ListMovies;
class MoviesController extends Controller
{
/**
* @param ListMovies $listMoviesUC
* @return \Illuminate\Http\JsonResponse
*/
public function all(ListMovies $listMoviesUC)
{
$data = $listMoviesUC->getListMovies();
return $this->response($data);
}
/**
* @param GetMovie $getMovieUC
* @return \Illuminate\Http\JsonResponse
*/
public function getMovie(GetMovie $getMovieUC, $id)
{
$data = $getMovieUC->getMovie($id);
return $this->response($data);
}
/**
* @param array $data
* @return \Illuminate\Http\JsonResponse
*/
private function response(array $data)
{
return response()->json([
'data' => $data
]);
}
}
<file_sep>/movies/public/js/movies/template.js
let movieTemplate = ['<div class="col-6 col-sm-12 col-lg-6">',
'<div class="card card--list">',
'<div class="row">',
'<div class="col-12 col-sm-4">',
'<div class="card__cover">',
'<img src="{movieImg}" alt="">',
'<a href="#" class="card__play">',
'<i class="icon ion-ios-play"></i><div class="col-6 col-sm-12 col-lg-6">',
'<div class="card card--list">',
'<div class="row">',
'<div class="col-12 col-sm-4">',
'<div class="card__cover">',
'<img src="{movieImg}" alt="">',
'<a href="#" class="card__play">',
'<i class="icon ion-ios-play"></i>',
'</a>',
'</div>',
'</div>',
'</div>',
'</div>',
'</div>',
'</a>',
'</div>',
'</div>',
'<div class="col-12 col-sm-8">',
'<div class="card__content">',
'<h3 class="card__title"><a href="#">{movieName}</a></h3>',
'<span class="card__category">',
'<a href="#">{movieLang}</a>',
'<a href="#">{movieRelease}</a>',
'</span>',
'<div class="card__wrap">',
'<span class="card__rate"><i class="icon ion-ios-star"></i>{movieAverage}</span>',
'<ul class="card__list">',
'<li>HD</li>',
'<li>16+</li>',
'</ul>',
'</div>',
'<div class="card__description">',
'<p>{movieOverview}</p>',
'</div>',
'</div>',
'</div>',
'</div>',
'</div>',
'</div>'].join(' ');<file_sep>/movies/app/Repositories/Contracts/MoviesRepository.php
<?php
namespace App\Repositories\Contracts;
interface MoviesRepository
{
/**
* @return array
*/
public function getAll(): array;
/**
* @param int $id
* @return array
*/
public function find(int $id): array;
}
|
94e9e23e8a2f44a2e438cd4c0ed294396850cd2b
|
[
"JavaScript",
"Markdown",
"PHP",
"Shell"
] | 17
|
PHP
|
eandresh/ejercicio_arquitectura
|
017cf78169e063cff2b2c0070b3b0c294f54a1e1
|
0490e23770ac94a47eba417148377ca6a22b6f92
|
refs/heads/master
|
<repo_name>EmilAndreasyan/collections_practice-online-web-pt-090819<file_sep>/collections_practice.rb
def sort_array_asc(array)
array.sort
end
sort_array_asc([3, 10, 7, 9, 1, 4])
def sort_array_desc(arr)
arr.sort do |a, b|
b <=> a
end
end
sort_array_desc([3, 8, 1, 15, 7])
arr = ["Tatev", "Emil", "Michael", "Victoria"]
def sort_array_char_count(arr)
arr.sort do |a, b|
a.length <=> b.length
end
end
sort_array_char_count(arr)
def swap_elements(arr)
temp1 = arr[1]
temp2 = arr[2]
arr[1] = temp2
arr[2] = temp1
arr
end
swap_elements(["blake", "ashley", "scott"])
def reverse_array(arr)
arr.reverse
end
reverse_array([12, 4, 35])
def find_a(arr)
arr.select do |x|
x.start_with?("a")
end
end
find_a(["Tatev", "Emil", "Michael", "Victoria", "apple", "apply"])
def kesha_maker(arr)
arr.each {|name| name[2] = "$"}
end
kesha_maker(["blake", "ashley", "scott"])
def sum_array(arr)
arr.inject {|sum, x| sum + x}
end
sum_array([3, 8, 1, 15, 7])
def add_s(arr)
arr.each_with_index.collect do |element, index|
if index == 1
element
else
element + "s"
end
end
end
add_s(["hand", "feet", "knee", "table"])
|
2771a783c191a190623f5827eb6a5542f34ad1d7
|
[
"Ruby"
] | 1
|
Ruby
|
EmilAndreasyan/collections_practice-online-web-pt-090819
|
6042192d8de9580e40534db7834069a4f3b9b7b4
|
06cd6aae03da0036288e0d879be57bb0c0065df0
|
refs/heads/master
|
<file_sep><?php
require_once("db_connect/dbconnect.php");
$dbConnect = new dbConnect();
error_reporting(0);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</script>
<title>Technical Task</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<?php include("links.php") ?>
<script src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<style>
.color-palette {
height: 35px;
line-height: 35px;
text-align: center;
}
.color-palette-set {
margin-bottom: 15px;
}
.color-palette span {
display: none;
font-size: 12px;
}
.color-palette:hover span {
display: block;
}
.color-palette-box h4 {
position: absolute;
top: 100%;
left: 25px;
margin-top: -40px;
color: rgba(255, 255, 255, 0.8);
font-size: 12px;
display: block;
z-index: 7;
}
.example-modal .modal {
position: relative;
top: auto;
bottom: auto;
right: auto;
left: auto;
display: block;
z-index: 1;
}
.example-modal .modal {
background: transparent !important;
}
td:hover{
cursor: pointer;
}
</style>
</head>
<?php
session_start();
$user = $_SESSION['username'];
$userID = $_SESSION['userid'];
$currentDate = date("Y-m-d h:i:sa");
if(!empty($user)) {
//--------start code for detete--------------------//
if(!empty($_GET['id'])) {
$sold_id = $_GET['id'];
$sql_sold = "UPDATE car_model SET status ='0' WHERE model_pk = '$sold_id'";
$retval_del = $dbConnect->UpdateRecord($sql_sold);
if(! $retval_del ) {
//echo("<div align='center'; style ='font:18px Arial,tahoma,sans-serif;color:#ff0000;'> Could not Deleted data </div>" . mysql_error());
}
else{
echo "<script type=\"text/javascript\">";
echo "alert(\"Car Successfully Add in Sold List...\");";
// echo "window.location.href = \"view_inventory.php\";";
echo "</script>";
}
}
//----------end detete code------------------//
//query for view list
$query = "SELECT model_pk, manufacturer_name, model_name, color, fuel, manufacturer_year, registration_year,carcount, note, car_picture1, car_picture2 FROM car_model
LEFT JOIN manufacturer ON manufacturer.manufacturer_pk = car_model.manufacturer_fk
WHERE car_model.status = '1' ORDER BY model_name Asc";
$result = $dbConnect->FetchRecordsLarge($query);
?>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<?php include("header.php"); ?>
<?php include("nav_bar.php"); ?>
<!-- Left side column. contains the logo and sidebar -->
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<!-- View Manufacturer -->
<!-- <small>Preview of UI elements</small> -->
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a>
</li>
<li><a>Car Inventory</a>
</li>
<li><a>View Car Inventory</a>
</li>
<!-- <li class="active">General</li> -->
</ol>
<br><br>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box box-default box-solid">
<div class="box-header with-border">
<h3 class="box-title">List of Car Inventory</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
</div>
<!-- /.box-tools -->
</div>
<!-- /.box-header -->
<div class="box-body">
<span></span>
<div class="box">
<table id="example3" class="table table-bordered table-striped">
<thead>
<tr>
<th>Sr. No.</th>
<th>Manufacturer Name</th>
<th>Model Name</th>
<th>Count</th>
<!-- <th>Action</th> -->
</tr>
</thead>
<tbody>
<?php
$sr_no =1;
if ($result > 0) {
while($row = $result->fetch_assoc()){
$model_id = $row['model_pk'];
?>
<tr data-toggle="modal" data-target="#Inventory<?php echo $row['model_pk'];?>">
<td>
<?php echo $sr_no;?>
</td>
<td>
<?php echo $row['manufacturer_name'];?>
</td>
<td>
<?php echo $row['model_name'];?>
</td>
<td><?php echo $row['carcount'];?></td>
</tr>
<div id="Inventory<?php echo $row['model_pk'];?>" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title" style="color: #000">Car Details</h4>
</div>
<div class="modal-body" style="color: #000">
<p><b>Car Manufacturer :</b> <?php echo $row['manufacturer_name'];?> <b>Car Model :</b> <?php echo $row['model_name'];?></p>
<p><b>Car Color :</b> <?php echo $row['color'];?> <b>Car Fuel :</b> <?php echo $row['fuel'];?></p>
<p><b>Manufacturer Year :</b> <?php echo $row['manufacturer_year'];?> <b>Registration Year :</b> <?php echo $row['registration_year'];?></p>
<p><b>Note :</b> <?php echo $row['note'];?></p>
<p><b>Car Picture 1 :</b> <img src="Upload_Files/<?php if(isset($row['car_picture1'])) { echo $car_picture1 = $row['car_picture1']; } else { echo $car_picture1 = ""; } ?>" alt="" width="25%" height="25%"> <b>Car Picture 2 :</b> <img src="Upload_Files/<?php if(isset($row['car_picture2'])) { echo $car_picture2 = $row['car_picture2']; } else { echo $car_picture2 = ""; } ?>" alt="" width="25%" height="25%"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" style="text-align: center;"><a href="view_inventory.php?id=<?php echo $row['model_pk'];?>" style="color: #fff"> Sold</a></button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?php
$sr_no+=1; }
}
else { ?>
<td colspan="8">
<b><span style="text-align: center;"> Records Not Found...</span></b>
</td>
<?php }
?>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
</div>
<!-- /.box -->
</div>
</div>
<!-- /.row -->
<!-- END CUSTOM TABS -->
<script type="text/javascript">
CKEDITOR.replace('note');
</script>
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php include("footer.php") ?>
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
</body>
<?php
}
else {
header( 'Location: index.php' );
}
?>
</html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function(){
$('#myModal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
alert(rowid);
die();
$.ajax({
type : 'post',
url : 'view_inventory.php', //Here you will fetch records
data : 'rowid='+ rowid, //Pass $id
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
}
});
});
});
</script> <file_sep>
<?php
date_default_timezone_set("Asia/Calcutta");
error_reporting(~E_NOTICE && E_WARNING);
class dbConnect
{
private $mysqli;
private $autoIncrementId;
private $lastQueryNoOfRecords;
function __construct($databasename = 'mini_car_inventory_system')
{
$this -> mysqli = new mysqli("localhost","root","", $databasename);
$this -> mysqli->query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");
$this->autoIncrementId = 0;
$this->lastQueryNoOfRecords = 0;
}
function __destruct()
{
$this -> mysqli -> close();
}
function FetchRecords($sqlQuery)
{
$result = $this -> mysqli->query($sqlQuery);
$this->lastQueryNoOfRecords = $this -> mysqli -> affected_rows;
if($this->lastQueryNoOfRecords <= 0)
{
if($this->lastQueryNoOfRecords == 0) $result -> free();
return false;
}
else
{
$ArrReturn = array();
while($row = $result->fetch_assoc())
{
$ArrReturn[] = $row;
}
$result -> free();
return $ArrReturn;
}
}
function InsertRecord($sqlQuery)
{
$result = $this -> mysqli->query($sqlQuery);
$this->autoIncrementId = $this -> mysqli -> insert_id;
return $this->autoIncrementId;
//return $retVal;
}
function UpdateRecord($sqlQuery)
{
//$this->theResult = $this -> mysqli->query($sqlQuery);
$result = $this->mysqli->query($sqlQuery);
// echo $this->theResult;
// die();
// return $this->theResult;
if ($result == false) {
echo 'Error: cannot execute the command';
return false;
} else {
return true;
}
}
function FetchRecordsLarge($sqlQuery)
{
$this->theResult = $this -> mysqli->query($sqlQuery);
$this->lastQueryNoOfRecords = $this -> mysqli -> affected_rows;
if($this->lastQueryNoOfRecords <= 0)
{
if($this->lastQueryNoOfRecords == 0) $this->theResult -> free();
return false;
}
else
{
return $this->theResult;
//return $this->lastQueryNoOfRecords;
}
}
function NoOfRecords($sqlQuery)
{
$result = $this -> mysqli->query($sqlQuery);
$retVal = $this -> mysqli -> affected_rows;
$this->lastQueryNoOfRecords = $retVal;
$result -> free();
return $retVal;
}
function CountRows($sqlQuery)
{
$this->theResult = $this -> mysqli->query($sqlQuery);
return $result;
}
function getProperId($field, $table, $maxallowed=0)
{
$sql="SELECT max($field) AS maxfield FROM $table";
if($maxallowed>0)
{
$sql .= " WHERE $field<=$maxallowed";
}
$Arr = $this -> FetchRecords($sql);
return $Arr[0]['maxfield'] + 1;
}
function getCurrentDateTime()
{
$ArrDateTime = $this -> FetchRecords("SELECT NOW() AS currenttime");
$srinidatetime = $ArrDateTime[0]['currenttime'];
return $srinidatetime;
}
function runOtherQueries($sqlQuery, $withAutoIncrement=false)
{
$result = $this -> mysqli->query($sqlQuery);
$this->lastQueryNoOfRecords = $this -> mysqli -> affected_rows;
if($result === TRUE)
{
if($withAutoIncrement) $this->autoIncrementId = $this->mysqli->insert_id;
return true;
}
else return false;
// if(mysql_error())
}
function returnAutoIncrementId()
{
return $this->autoIncrementId;
}
function affectedRows()
{
return $this->lastQueryNoOfRecords;
}
}
?>
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.7.7
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Nov 06, 2018 at 02:40 PM
-- Server version: 5.6.41-84.1-log
-- PHP Version: 5.6.30
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `samaranb_mini_car_inventory_system`
--
-- --------------------------------------------------------
--
-- Table structure for table `car_model`
--
CREATE TABLE `car_model` (
`model_pk` int(8) NOT NULL,
`manufacturer_fk` int(5) NOT NULL,
`model_name` varchar(20) NOT NULL,
`color` varchar(10) NOT NULL,
`fuel` varchar(10) NOT NULL,
`manufacturer_year` varchar(20) NOT NULL,
`registration_year` int(5) NOT NULL,
`note` text NOT NULL,
`car_picture1` varchar(100) NOT NULL,
`car_picture2` varchar(100) NOT NULL,
`carcount` int(5) NOT NULL,
`created_date` date NOT NULL,
`status` enum('0','1') NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `car_model`
--
INSERT INTO `car_model` (`model_pk`, `manufacturer_fk`, `model_name`, `color`, `fuel`, `manufacturer_year`, `registration_year`, `note`, `car_picture1`, `car_picture2`, `carcount`, `created_date`, `status`) VALUES
(1, 1, 'Swift', 'white', 'Petrol', '2017', 2018, 'Swift ', 'Maruti-Suzuki-New-Swift-Left-Front-Three-Quarter-88877.jpg', 'Maruti-Suzuki-New-Swift-Rear-view-88878.jpg', 2, '2018-11-06', '1'),
(2, 1, '<NAME>', 'Gray', 'Diesel', '2018', 2018, ' \n ', 'Maruti-Suzuki-Vitara-Brezza-Exterior-100226.jpg', 'Maruti-Suzuki-Vitara-Brezza-Right-Front-Three-Quarter-118639.jpg', 2, '2018-11-06', '1'),
(3, 2, 'Santro', 'Blue', 'CNG', '2017', 2018, ' \n ', 'Hyundai-Santro-Right-Front-Three-Quarter-138738.jpg', 'Hyundai-Santro-Right-Rear-Three-Quarter-138739.jpg', 1, '2018-11-06', '1'),
(4, 3, 'Marazzo', '<NAME>', 'Diesel', '2018', 2018, '<p>Mahindra Marazzo price starts at ? 9.99 Lakhs and goes upto ? 13.9 Lakhs. Diesel Marazzo price starts at ? 9.99 Lakhs.</p>\n', 'Mahindra-Marazzo-Exterior-136955.jpg', 'Mahindra-Marazzo-Exterior-134818.jpg', 1, '2018-11-06', '1'),
(5, 5, 'Harrier', 'Orange', 'Diesel', '2018', 2018, ' \n ', 'harrier_front_view.jpg', 'harrier_back_view.jpg', 1, '2018-11-06', '1');
-- --------------------------------------------------------
--
-- Table structure for table `manufacturer`
--
CREATE TABLE `manufacturer` (
`manufacturer_pk` int(8) NOT NULL,
`manufacturer_name` varchar(20) NOT NULL,
`created_date` date NOT NULL,
`status` enum('0','1') NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `manufacturer`
--
INSERT INTO `manufacturer` (`manufacturer_pk`, `manufacturer_name`, `created_date`, `status`) VALUES
(1, '<NAME>', '2018-11-06', '1'),
(2, 'Hyundai', '2018-11-06', '1'),
(3, 'Mahindra', '2018-11-06', '1'),
(4, 'Toyota', '2018-11-06', '1'),
(5, 'TATA', '2018-11-06', '1');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`user_pk` int(8) NOT NULL,
`user_name` varchar(50) NOT NULL,
`user_id` varchar(20) NOT NULL,
`password` varchar(100) NOT NULL,
`status` enum('0','1') NOT NULL DEFAULT '1',
`token` int(8) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`user_pk`, `user_name`, `user_id`, `password`, `status`, `token`) VALUES
(1, 'Admin', 'Admin', '<PASSWORD>ecf8427e', '1', 0);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `car_model`
--
ALTER TABLE `car_model`
ADD PRIMARY KEY (`model_pk`);
--
-- Indexes for table `manufacturer`
--
ALTER TABLE `manufacturer`
ADD PRIMARY KEY (`manufacturer_pk`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`user_pk`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `car_model`
--
ALTER TABLE `car_model`
MODIFY `model_pk` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `manufacturer`
--
ALTER TABLE `manufacturer`
MODIFY `manufacturer_pk` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `user_pk` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
require_once("db_connect/dbconnect.php");
$dbConnect = new dbConnect();
error_reporting(0);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</script>
<title>Technical Task</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<?php include("links.php") ?>
<script src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<style>
.color-palette {
height: 35px;
line-height: 35px;
text-align: center;
}
.color-palette-set {
margin-bottom: 15px;
}
.color-palette span {
display: none;
font-size: 12px;
}
.color-palette:hover span {
display: block;
}
.color-palette-box h4 {
position: absolute;
top: 100%;
left: 25px;
margin-top: -40px;
color: rgba(255, 255, 255, 0.8);
font-size: 12px;
display: block;
z-index: 7;
}
</style>
</head>
<?php
session_start();
$user = $_SESSION['username'];
$userID = $_SESSION['userid'];
$currentDate = date("Y-m-d h:i:sa");
$carcount = 1;
if(!empty($user)) {
if(!empty($_POST) && $_POST['updateID'] == 0 && $_POST['modelId'] == 0) {
//print_r($_REQUEST);
if(isset($_REQUEST['manufacturer_fk'])) { $manufacturer_fk = $_REQUEST['manufacturer_fk']; } else { $manufacturer_fk = ""; }
if(isset($_REQUEST['model_name'])) { $model_name = $_REQUEST['model_name']; } else { $model_name = ""; }
if(isset($_REQUEST['car_color'])) { $car_color = $_REQUEST['car_color']; } else { $car_color = ""; }
if(isset($_REQUEST['fuel'])) { $fuel = $_REQUEST['fuel']; } else { $fuel = ""; }
if(isset($_REQUEST['manufacturer_year'])) { $manufacturer_year = $_REQUEST['manufacturer_year']; } else { $manufacturer_year = ""; }
if(isset($_REQUEST['registration_year'])) { $registration_year = $_REQUEST['registration_year']; } else { $registration_year = ""; }
// if(isset($_REQUEST['car_picture1'])) { $car_picture1 = $_REQUEST['car_picture1']; } else { $car_picture1 = ""; }
//if(isset($_REQUEST['car_picture2'])) { $car_picture2 = $_REQUEST['car_picture2']; } else { $car_picture2 = ""; }
if(isset($_REQUEST['note'])) { $note = $_REQUEST['note']; } else { $note = ""; }
$car_picture1 = $_FILES['car_picture1']['name'];
$car_picture2 = $_FILES['car_picture2']['name'];
// $target_dir = "Upload_Files/";
// Upload file
move_uploaded_file($_FILES['car_picture1']['tmp_name'],'Upload_Files/'.$car_picture1);
move_uploaded_file($_FILES['car_picture2']['tmp_name'],'Upload_Files/'.$car_picture2);
$sqlcheck= "SELECT model_pk,carcount FROM car_model WHERE manufacturer_fk = '$manufacturer_fk' AND model_name = '$model_name' AND color = '$car_color' AND fuel = '$fuel' AND manufacturer_year = '$manufacturer_year' AND registration_year = '$registration_year' AND status = '1' ORDER BY model_pk DESC LIMIT 0,1";
if ($checkResult = $dbConnect->FetchRecords($sqlcheck)) {
$model_pk = $checkResult[0]['model_pk'];
$carCount = $checkResult[0]['carcount'];
$carCount +=1;
$sql_update = "UPDATE car_model SET carcount ='$carCount' WHERE model_pk = '$model_pk'";
$retval = $dbConnect->UpdateRecord($sql_update);
}
else {
$sqlCount = "SELECT count FROM car_model WHERE manufacturer_fk = '$manufacturer_fk' AND model_name = '$model_name' AND status = '1' ORDER BY count DESC LIMIT 0,1";
if ($countResult = $dbConnect->FetchRecords($sqlCount)) {
$carcount = $countResult[0]['count'];
$carcount +=1;
}
$sql = "INSERT INTO car_model "."(manufacturer_fk,model_name,color,fuel,manufacturer_year,registration_year,note,car_picture1,car_picture2,carcount,created_date,status) "."VALUES "."('$manufacturer_fk','$model_name','$car_color','$fuel','$manufacturer_year','$registration_year','$note','$car_picture1','$car_picture2','$carcount','$currentDate','1')";
// $retval = mysql_query( $sql);
$retval = $dbConnect->InsertRecord($sql);
}
}
//--------start code for detete--------------------//
if(!empty($_GET['del_id'])) {
$delete_id = $_GET['del_id'];
$sql_del = "UPDATE car_model SET status ='0' WHERE model_pk = '$delete_id'";
$retval_del = $dbConnect->UpdateRecord($sql_del);
if(! $retval_del ) {
echo("<div align='center'; style ='font:18px Arial,tahoma,sans-serif;color:#ff0000;'> Could not Deleted data </div>" . mysql_error());
}
else{
echo "<script type=\"text/javascript\">";
echo "alert(\"Record Deleted successfully...\");";
echo "window.location.href = \"add_model.php\";";
echo "</script>";
}
}
//----------end detete code------------------//
//----------------start update------------------------------------------
if ($_POST['updateID'] == 1 && $_POST['modelId'] != 0) {
if(isset($_REQUEST['manufacturer_fk'])) { $manufacturer_fk = $_REQUEST['manufacturer_fk']; } else { $manufacturer_fk = ""; }
if(isset($_REQUEST['model_name'])) { $model_name = $_REQUEST['model_name']; } else { $model_name = ""; }
if(isset($_REQUEST['car_color'])) { $car_color = $_REQUEST['car_color']; } else { $car_color = ""; }
if(isset($_REQUEST['fuel'])) { $fuel = $_REQUEST['fuel']; } else { $fuel = ""; }
if(isset($_REQUEST['manufacturer_year'])) { $manufacturer_year = $_REQUEST['manufacturer_year']; } else { $manufacturer_year = ""; }
if(isset($_REQUEST['registration_year'])) { $registration_year = $_REQUEST['registration_year']; } else { $registration_year = ""; }
if(isset($_REQUEST['note'])) { $note = $_REQUEST['note']; } else { $note = ""; }
$car_picture1 = $_FILES['car_picture1']['name'];
$car_picture2 = $_FILES['car_picture2']['name'];
// Upload file
move_uploaded_file($_FILES['car_picture1']['tmp_name'],'Upload_Files/'.$car_picture1);
move_uploaded_file($_FILES['car_picture2']['tmp_name'],'Upload_Files/'.$car_picture2);
if(isset($_REQUEST['modelId'])) { $modelId = $_REQUEST['modelId']; } else { $modelId = ""; }
$sql_update = "UPDATE car_model SET manufacturer_fk = '$manufacturer_fk',model_name = '$model_name',color = '$car_color',fuel = '$fuel',manufacturer_year = '$manufacturer_year',registration_year = '$registration_year',note = '$note',car_picture1 = '$car_picture1',car_picture2 = '$$car_picture2' WHERE model_pk = '$modelId'";
$retval_del = $dbConnect->UpdateRecord($sql_update);
// if(! $retval_del ) {
// echo("<div align='center'; style ='font:18px Arial,tahoma,sans-serif;color:#ff0000;'> Could not updated data </div>" . mysql_error());
// }
// else{
// echo "<script type=\"text/javascript\">";
// echo "alert(\"Record Updated successfully...\");";
// echo "window.location.href = \"add_manufacturer.php\";";
// echo "</script>";
// }
}
if(!empty($_GET['id'])) {
$update_id = $_GET['id'];
$updateID = 1;
$query = "SELECT model_pk,manufacturer_fk,model_name,color,fuel,manufacturer_year,registration_year,note,car_picture1,car_picture2 FROM car_model WHERE model_pk = '$update_id' AND status = '1'";
$UpdateResult = $dbConnect->FetchRecords($query);
}
//---------------end update--------------------------------------------------
//query for view list
$query = "SELECT model_pk, manufacturer_name, model_name, color, fuel, manufacturer_year, registration_year, note, car_picture1, car_picture2 FROM car_model
LEFT JOIN manufacturer ON manufacturer.manufacturer_pk = car_model.manufacturer_fk
WHERE car_model.status = '1' ORDER BY model_name Asc";
$result = $dbConnect->FetchRecordsLarge($query);
//query for view Manufacturer DropDown list
$query = "SELECT manufacturer_pk,manufacturer_name,created_date FROM manufacturer WHERE status = '1' ORDER BY manufacturer_pk Desc";
$resultMfg = $dbConnect->FetchRecordsLarge($query);
// echo $query;
?>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<?php include("header.php"); ?>
<?php include("nav_bar.php"); ?>
<!-- Left side column. contains the logo and sidebar -->
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<!-- View Manufacturer -->
<!-- <small>Preview of UI elements</small> -->
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a>
</li>
<li><a>Car Model</a>
</li>
<li><a>Add Car Model</a>
</li>
<!-- <li class="active">General</li> -->
</ol>
</section>
<section class="content">
<br>
<br>
<div class="row">
<div class="col-md-12">
<div class="box box-default box-solid">
<div class="box-header with-border">
<h3 class="box-title">Add Car Model</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
</div>
<!-- /.box-tools -->
</div>
<!-- /.box-header -->
<div class="box-body">
<!-- form start -->
<form class="form-horizontal" id="Model" action="add_model.php" method="post" enctype='multipart/form-data'>
<div class="box-body">
<div class="form-group">
<label class="col-sm-2 control-label">Manufacturer Name <span style="color:#ff0000;">*</span>:</label>
<div class="col-sm-4">
<select name="manufacturer_fk" class="form-control manufacturer_fk" id="manufacturer_fk" tabindex="1" autofocus="autofocus">
<option value="0">-- SELECT MANUFACTURER --</option>
<?php while($row = $resultMfg->fetch_assoc()){
if ($UpdateResult[0]['manufacturer_fk'] == $row['manufacturer_pk'])
{
$selected = "selected=\"selected\"";
}
else
{
$selected = '';
}
?>
<option value="<?php echo $row['manufacturer_pk'];?>" <?php echo $selected ?>><?php echo $row['manufacturer_name'];?></option>
<?php } ?> </select>
</div>
<label class="col-sm-2 control-label">Model Name <span style="color:#ff0000;">*</span>:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="model_name" name="model_name" tabindex="1" required="required" value='<?php if(isset($UpdateResult[0]['model_name'])) { echo $model_name = $UpdateResult[0]['model_name']; } else { echo $model_name = ""; } ?>'>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Car Color<span style="color:#ff0000;">*</span> :</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="car_color" name="car_color" required="required" tabindex="1" value='<?php if(isset($UpdateResult[0]['color'])) { echo $color = $UpdateResult[0]['color']; } else { echo $color = ""; } ?>'>
</div>
<label class="col-sm-2 control-label">Fuel Type<span style="color:#ff0000;">*</span> :</label>
<div class="col-sm-4">
<select class="form-control" id="fuel" name="fuel" required="required" tabindex="1">
<option value="">--SELECT FUEL TYPE--</option>
<option value="CNG" <?php if($UpdateResult[0]['fuel']=="CNG"){echo"selected=selected";}?>>CNG</option>
<option value="Diesel" <?php if($UpdateResult[0]['fuel']=="Diesel"){echo"selected=selected";}?>>Diesel</option>
<option value="Petrol" <?php if($UpdateResult[0]['fuel']=="Petrol"){echo"selected=selected";}?>>Petrol</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Manufacturing Year<span style="color:#ff0000;">*</span> :</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="manufacturer_year" name="manufacturer_year" required="required" tabindex="1" value='<?php if(isset($UpdateResult[0]['manufacturer_year'])) { echo $manufacturer_year = $UpdateResult[0]['manufacturer_year']; } else { echo $manufacturer_year = ""; } ?>'>
</div>
<label class="col-sm-2 control-label">Registration Year<span style="color:#ff0000;">*</span> :</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="registration_year" name="registration_year" required="required" tabindex="1" value='<?php if(isset($UpdateResult[0]['registration_year'])) { echo $registration_year = $UpdateResult[0]['registration_year']; } else { echo $registration_year = ""; } ?>'>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Car Picture 1<span style="color:#ff0000;">*</span> :</label>
<div class="col-sm-4">
<input type="file" class="form-control" id="car_picture1" name="car_picture1" required="required" tabindex="1">
<br>
<img src="Upload_Files/<?php if(isset($UpdateResult[0]['car_picture1'])) { echo $car_picture1 = $UpdateResult[0]['car_picture1']; } else { echo $car_picture1 = ""; } ?>" alt="" width="25%" height="25%">
</div>
<label class="col-sm-2 control-label">Car Picture 2<span style="color:#ff0000;">*</span> :</label>
<div class="col-sm-4">
<input type="file" class="form-control" id="car_picture2" name="car_picture2" required="required" tabindex="1">
<br>
<img src="Upload_Files/<?php if(isset($UpdateResult[0]['car_picture2'])) { echo $car_picture2 = $UpdateResult[0]['car_picture2']; } else { echo $car_picture2 = ""; } ?>" alt="" width="25%" height="25%">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Note :</label>
<div class="col-sm-10">
<textarea id="note" name="note" tabindex="1">
<?php if(isset($UpdateResult[0]['note'])) { echo $note = $UpdateResult[0]['note']; } else { echo $note = ""; } ?>
</textarea>
</div>
<input type="hidden" name="updateID" id="updateID" value='<?php if(isset($updateID)){ echo "$updateID" ; } else { echo "0"; } ?>'>
<input type="hidden" name="modelId" id="modelId" value='<?php if(isset($UpdateResult[0]['model_pk'])) { echo $model_pk = $UpdateResult[0]['model_pk']; } else { echo $model_pk = "0"; } ?>'>
</div>
<!-- /.box-body -->
<div class="box-footer subtn" align="center">
<button type="submit" class="btn btn-info">Submit</button>
<button class="btn btn-default"><a href="add_model.php"> Reset</a></button>
</div>
<!-- /.box-footer -->
</form>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
</div>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box box-default box-solid">
<div class="box-header with-border">
<h3 class="box-title">List of Models</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
</div>
<!-- /.box-tools -->
</div>
<!-- /.box-header -->
<div class="box-body">
<span></span>
<div class="box">
<table id="example3" class="table table-bordered table-striped">
<thead>
<tr>
<th>Sr. No.</th>
<th>Manufacturer Name</th>
<th>Model Name</th>
<th>Color</th>
<th>Fuel</th>
<th>Mfg. Year</th>
<th>Registration Year</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$sr_no =1;
if ($result > 0) {
while($row = $result->fetch_assoc()){
?>
<tr>
<td>
<?php echo $sr_no;?>
</td>
<td>
<?php echo $row['manufacturer_name'];?>
</td>
<td>
<?php echo $row['model_name'];?>
</td>
<td>
<?php echo $row['color'];?>
</td>
<td>
<?php echo $row['fuel'];?>
</td>
<td>
<?php echo $row['manufacturer_year'];?>
</td>
<td>
<?php echo $row['registration_year'];?>
</td>
<td><a href="add_model.php?id=<?php echo $row['model_pk'];?>" > <span style="color:#33ACFF;"><button type="button" class="btn btn-block bg-navy btn-xs" data-toggle="tooltip" data-original-title="Edit Record"><i class="fa fa-edit"></i></button></span></a> | <a href="add_model.php?del_id=<?php echo $row['model_pk'];?>"><span style="color: #ffffff" onclick="return confirm('Are you sure to Delete?')"><span style="color:#ff0000;"><button type="button" class="btn btn-block btn-danger btn-xs" data-toggle="tooltip" data-original-title="Delete Record"><i class="fa fa-remove"></i></button></span>
</td>
</tr>
<?php
$sr_no+=1; }
}
else { ?>
<td colspan="8">
<b><span style="text-align: center;"> Records Not Found...</span></b>
</td>
<?php }
?>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
</div>
<!-- /.box -->
</div>
</div>
<!-- /.row -->
<!-- END CUSTOM TABS -->
<script type="text/javascript">
CKEDITOR.replace('note');
</script>
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php include("footer.php") ?>
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
</body>
<?php
}
else {
header( 'Location: index.php' );
}
?>
</html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#Model').ajaxForm(function() {
$('#Model')[0].reset();
alert("Record Inserted OR Updated successfully...!");
window.location.href = "add_model.php";
});
});
</script> <file_sep><?php
require_once("db_connect/dbconnect.php");
$dbConnect = new dbConnect();
error_reporting(0);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>ThyssenKrupp Engine Components India. Pvt. Ltd.</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<?php include("links.php") ?>
</head>
<?php
session_start();
$user = $_SESSION['username'];
$userID = $_SESSION['userid'];
if(!empty($user)) {
$querymfg = "SELECT * FROM manufacturer WHERE status = '1'";
$resultmfg = $dbConnect->NoOfRecords($querymfg);
$querymodel = "SELECT * FROM car_model WHERE status = '1'";
$resultmodel = $dbConnect->NoOfRecords($querymodel);
?>
<body class="hold-transition skin-blue fixed sidebar-mini" onunload="ajaxFunction()">
<div class="wrapper">
<?php include("header.php"); ?>
<?php
include("nav_bar.php"); ?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Dashboard
<!-- <small>Version 2.0</small> -->
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li>Dashboard</li>
</ol>
</section>
<!-- Main content -->
<section class="content" >
<div class="row"S >
<div class="col-lg-4 col-xs-6">
<!-- small box -->
<div class="small-box bg-aqua">
<div class="inner">
<h3><?php echo $resultmfg;?></h3>
<p>Total Car Manufacturers</p>
</div>
<div class="icon">
<i class="fa fa-cogs"></i>
</div>
<a href="add_manufacturer.php" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
<div class="col-lg-4 col-xs-6">
<!-- small box -->
<div class="small-box bg-blue">
<div class="inner">
<h3><?php echo $resultmodel;?></h3>
<p>Total Car Models</p>
</div>
<div class="icon">
<i class="fa fa-cogs"></i>
</div>
<a href="add_model.php" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
<div class="col-lg-4 col-xs-6">
<!-- small box -->
<div class="small-box bg-green">
<div class="inner">
<h3><?php echo $resultmodel;?></h3>
<p>Total Inventory Records</p>
</div>
<div class="icon">
<i class="fa fa-cogs"></i>
</div>
<a href="view_inventory.php" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
</div>
</section>
<!-- <br>
<br>
<div class="row" align="center">
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="info-box">
<span class="info-box-icon bg-aqua"><i class="fa fa-shopping-cart"></i></span>
<a href="">
<div class="info-box-content">
<span class="info-box-text">Services</span>
<span class="info-box-number">00</span>
</div></a>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="info-box">
<span class="info-box-icon bg-red"><i class="fa fa-user-o"></i></span>
<a href="">
<div class="info-box-content">
<span class="info-box-text">Customers</span>
<span class="info-box-number">00</span>
</div></a>
</div>
</div>
<div class="clearfix visible-sm-block"></div>
</div>
<div class="row">
</div>
</section> -->
<!-- <section class="content">
<div class="row" align="center">
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="info-box">
<span class="info-box-icon bg-yellow"><i class="fa fa-files-o"></i></span>
<a href="">
<div class="info-box-content">
<span class="info-box-text">Employees</span>
<span class="info-box-number">00</span>
</div></a>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="info-box">
<span class="info-box-icon bg-green"><i class="fa fa-money"></i></span>
<a href="#">
<div class="info-box-content">
<span class="info-box-text">Todays Schedule</span>
<span class="info-box-number">00</span>
</div></a>
</div>
</div>
<div class="clearfix visible-sm-block"></div>
</div>
<div class="row">
</div>
</section> -->
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php include("footer.php") ?>
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
</body>
<?php }
else{
header('Location: index.php');
}
?>
</html>
<file_sep># Car-Inventory-System
Interview Task: Mini Car Inventory System
<file_sep><?php
require_once("db_connect/dbconnect.php");
$dbConnect = new dbConnect();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Technical Task</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.7 -->
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="bower_components/Ionicons/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="dist/css/AdminLTE.min.css">
<!-- iCheck -->
<link rel="stylesheet" href="plugins/iCheck/square/blue.css">
<!-- Google Font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<style>
.example-modal .modal {
position: relative;
top: auto;
bottom: auto;
right: auto;
left: auto;
display: block;
z-index: 1;
}
.example-modal .modal {
background: transparent !important;
}
</style>
<body class="hold-transition login-page">
<?php
if(!empty($_POST)) {
if(isset($_REQUEST['user_id'])) { $user_id = $_REQUEST['user_id']; } else { $user_id = ""; }
if(isset($_REQUEST['password'])) { $password = $_REQUEST['password']; } else { $password = ""; }
echo $user_id = mysql_real_escape_string($user_id);
echo $pass = mysql_real_escape_string($password);
echo $password = md5($pass);
$sqlLigin = "SELECT user_pk, user_name, user_id, password FROM user WHERE BINARY user_id = '$user_id' AND BINARY password = '$<PASSWORD>'";
$rssqlLigin = $dbConnect->FetchRecords($sqlLigin);
if(!empty($rssqlLigin)) {
$first_name = $rssqlLigin[0]['user_name'];
$userid = $rssqlLigin[0]['user_pk'];
session_start();
$_SESSION['username']=$first_name; // You can set the value however you like.
$_SESSION['userid']=$userid;
header('Location: dashboard.php');
}
else {
echo "<br><br><div align='center'; style ='font:18px Arial,tahoma,sans-serif;color:#ff0000;'> Entered user name or password is incorrect. Please try again.</div>";
}
}
?>
<div class="login-box">
<div class="login-logo">
<a href="index.php"><b>Interview Task: Mini Car Inventory System</b></a>
</div>
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg">Sign in to start your session</p>
<form action="index.php" method="post">
<div class="form-group has-feedback">
<span class="glyphicon glyphicon-user form-control-feedback"></span>
<input class="form-control" name="user_id" id="user_id" placeholder="Employee Id">
</div>
<div class="form-group has-feedback">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
<input type="<PASSWORD>" class="form-control" name="password" id="password" placeholder="<PASSWORD>">
</div>
<div class="row">
<div class="col-xs-8">
<span data-toggle="" data-target=""><a href="forgot-password.php"> I forgot my password</a></span>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
<br>
<span align="right">
</span>
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
<!-- jQuery 3 -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- iCheck -->
<script src="plugins/iCheck/icheck.min.js"></script>
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
});
</script>
</body>
</html>
<file_sep><?php
require_once("db_connect/dbconnect.php");
$dbConnect = new dbConnect();
error_reporting(0);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</script>
<title>Technical Task</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<?php include("links.php") ?>
<style>
.color-palette {
height: 35px;
line-height: 35px;
text-align: center;
}
.color-palette-set {
margin-bottom: 15px;
}
.color-palette span {
display: none;
font-size: 12px;
}
.color-palette:hover span {
display: block;
}
.color-palette-box h4 {
position: absolute;
top: 100%;
left: 25px;
margin-top: -40px;
color: rgba(255, 255, 255, 0.8);
font-size: 12px;
display: block;
z-index: 7;
}
</style>
</head>
<?php
session_start();
$user = $_SESSION['username'];
$userID = $_SESSION['userid'];
$currentDate = date("Y-m-d h:i:sa");
if(!empty($user)) {
if(!empty($_POST) && $_POST['updateID'] == 0 && $_POST['manufacturerId'] == 0) {
if(isset($_REQUEST['manufacturerName'])) { $manufacturerName = $_REQUEST['manufacturerName']; } else { $manufacturerName = ""; }
if(isset($_REQUEST['status'])) { $status = $_REQUEST['status']; } else { $status = 1; }
$sql = "INSERT INTO manufacturer "."(manufacturer_name,created_date,status) "."VALUES "."('$manufacturerName','$currentDate','$status')";
// $retval = mysql_query( $sql);
$retval = $dbConnect->InsertRecord($sql);
}
//--------start code for detete--------------------//
if(!empty($_GET['del_id'])) {
$delete_id = $_GET['del_id'];
$sql_del = "UPDATE manufacturer SET status ='0' WHERE manufacturer_pk = '$delete_id'";
$retval_del = $dbConnect->UpdateRecord($sql_del);
if(! $retval_del ) {
echo("<div align='center'; style ='font:18px Arial,tahoma,sans-serif;color:#ff0000;'> Could not Deleted data </div>" . mysql_error());
}
else{
echo "<script type=\"text/javascript\">";
echo "alert(\"Record Deleted successfully...\");";
echo "window.location.href = \"add_manufacturer.php\";";
echo "</script>";
}
}
//----------end detete code------------------//
//----------------start update------------------------------------------
if ($_POST['updateID'] == 1 && $_POST['manufacturerId'] != 0) {
if(isset($_REQUEST['manufacturerName'])) { $manufacturerName = $_REQUEST['manufacturerName']; } else { $manufacturerName = ""; }
if(isset($_REQUEST['manufacturerId'])) { $manufacturerId = $_REQUEST['manufacturerId']; } else { $manufacturerId = 0; }
$sql_update = "UPDATE manufacturer SET manufacturer_name ='$manufacturerName' WHERE manufacturer_pk = '$manufacturerId'";
$retval_del = $dbConnect->UpdateRecord($sql_update);
}
if(!empty($_GET['id'])) {
$update_id = $_GET['id'];
$updateID = 1;
$query = "SELECT manufacturer_pk,manufacturer_name,created_date FROM manufacturer WHERE manufacturer_pk = '$update_id' AND status = '1'";
$UpdateResult = $dbConnect->FetchRecords($query);
}
//---------------end update--------------------------------------------------
//query for view list
$query = "SELECT manufacturer_pk,manufacturer_name,created_date FROM manufacturer WHERE status = '1' ORDER BY manufacturer_pk Desc";
$result = $dbConnect->FetchRecordsLarge($query);
// echo $query;
?>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<?php include("header.php"); ?>
<?php include("nav_bar.php"); ?>
<!-- Left side column. contains the logo and sidebar -->
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<!-- View Manufacturer -->
<!-- <small>Preview of UI elements</small> -->
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a>
</li>
<li><a>manufacturer</a>
</li>
<li><a>Add manufacturer</a>
</li>
<!-- <li class="active">General</li> -->
</ol>
</section>
<section class="content">
<br>
<br>
<div class="row">
<div class="col-md-12">
<div class="box box-default box-solid">
<div class="box-header with-border">
<h3 class="box-title">Add Manufacturer</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
</div>
<!-- /.box-tools -->
</div>
<!-- /.box-header -->
<div class="box-body">
<!-- form start -->
<form class="form-horizontal" id="Manufacturer" action="add_manufacturer.php" method="post">
<div class="box-body">
<div class="form-group">
<label class="col-sm-2 control-label">Manufacturer Name<span style="color:#ff0000;">*</span></label>
<div class="col-sm-8">
<input type="text" class="form-control" id="manufacturerName" name="manufacturerName" value='<?php if(isset($UpdateResult[0]['manufacturer_name'])) { echo $manufacturer_name = $UpdateResult[0]['manufacturer_name']; } else { echo $manufacturer_name = ""; } ?>' required="required" tabindex="1" autofocus="autofocus">
</div>
</div>
<input type="hidden" name="updateID" id="updateID" value='<?php if(isset($updateID)){ echo "$updateID" ; } else { echo "0"; } ?>'>
<input type="hidden" name="manufacturerId" id="manufacturerId" value='<?php if(isset($UpdateResult[0]['manufacturer_pk'])) { echo $manufacturer_pk = $UpdateResult[0]['manufacturer_pk']; } else { echo $manufacturer_pk = "0"; } ?>'>
</div>
<!-- /.box-body -->
<div class="box-footer subtn" align="center">
<button type="submit" class="btn btn-info">Submit</button>
<button class="btn btn-default"><a href="add_manufacturer.php"> Reset</a></button>
</div>
<!-- /.box-footer -->
</form>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
</div>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box box-default box-solid">
<div class="box-header with-border">
<h3 class="box-title">List of Manufacturer</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
</div>
<!-- /.box-tools -->
</div>
<!-- /.box-header -->
<div class="box-body">
<span></span>
<div class="box">
<table id="example3" class="table table-bordered table-striped">
<thead>
<tr>
<th>Sr. No.</th>
<th>Manufacturer Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$sr_no =1;
if ($result > 0) {
while($row = $result->fetch_assoc()){ ?>
<tr>
<td>
<?php echo $sr_no;?>
</td>
<td>
<?php echo $row['manufacturer_name'];?>
</td>
<td><a href="add_manufacturer.php?id=<?php echo $row['manufacturer_pk'];?>" > <span style="color:#33ACFF;"><button type="button" class="btn btn-block bg-navy btn-xs" data-toggle="tooltip" data-original-title="Edit Record"><i class="fa fa-edit"></i></button></span></a> | <a href="add_manufacturer.php?del_id=<?php echo $row['manufacturer_pk'];?>"><span style="color: #ffffff" onclick="return confirm('Are you sure to Delete?')"><span style="color:#ff0000;"><button type="button" class="btn btn-block btn-danger btn-xs" data-toggle="tooltip" data-original-title="Delete Record"><i class="fa fa-remove"></i></button></span>
</td>
</tr>
<?php
$sr_no+=1; }
}
else { ?>
<td colspan="3">
<b><span style="text-align: center;"> Records Not Found...</span></b>
</td>
<?php }
?>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
</div>
<!-- /.box -->
</div>
</div>
<!-- /.row -->
<!-- END CUSTOM TABS -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php include("footer.php") ?>
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
</body>
<?php
}
else {
header( 'Location: index.php' );
}
?>
</html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#Manufacturer').ajaxForm(function() {
$('#Manufacturer')[0].reset();
alert("Record Inserted OR Updated successfully...!");
window.location.href = "add_manufacturer.php";
});
});
</script>
<file_sep><?php
$currentPage = basename( $_SERVER[ 'REQUEST_URI' ] );
// echo "$currentPage"."<br>";
$cpage = explode( '?', $currentPage );
$name2 = $cpage[ 0 ];
//echo $name2 . "<br>";
//$role = $_SESSION['role'];
?>
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel -->
<div class="user-panel">
<div class="pull-left image">
<img src="dist/img/user2-160x160.png" class="img-circle" alt="User Image">
</div>
<div class="pull-left info">
<p>
<?php echo $user; ?>
</p>
<!-- <small>
<?php //echo $res['designation']; ?>
</small> -->
</div>
</div>
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu" data-widget="tree">
<!-- <li class="header">MAIN NAVIGATION</li> -->
<?php //if ($userID !== 0) { ?>
<li <?php if ($name2=='dashboard.php' ) { ?> class="active"
<?php }?>>
<a href="dashboard.php">
<i class="fa fa-dashboard"></i> <span>Dashboard</span>
</li>
<?php //}
// if ($userID !== 0) { ?>
<!-- -----------------------------------add_manufacturer Menu------------------------------------- -->
<li <?php if ($name2=='add_manufacturer.php') { ?> class="treeview active"
<?php } else { ?> class="treeview"
<?php }?>>
<a href="#">
<i class="fa fa-hdd-o"></i>
<span>Manufacturers</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li <?php if ($name2=='add_manufacturer.php'){ ?> class="active"
<?php }?>><a href="add_manufacturer.php"><i class="fa fa-edit"></i> Add Manufacturers</a>
</li>
</ul>
</li>
<!-- ---------------------------------Model------------------------------------------------------ -->
<li <?php if ($name2=='add_model.php' ) { ?> class="treeview active"
<?php } else { ?> class="treeview"
<?php }?>>
<a href="#">
<i class="fa fa-hdd-o"></i>
<span>Car Models</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li <?php if ($name2=='add_model.php'){ ?> class="active"
<?php }?>><a href="add_model.php"><i class="fa fa-edit"></i> Add Models</a>
</li>
</ul>
</li>
<!-- ----------------------------------Inventory------------------------------------------------------- -->
<li <?php if ($name2=='view_inventory.php') { ?> class="treeview active"
<?php } else { ?> class="treeview"
<?php }?>>
<a href="#">
<i class="fa fa-hdd-o"></i>
<span>Inventory</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li <?php if ($name2=='view_inventory.php'){ ?> class="active"
<?php }?>><a href="view_inventory.php"><i class="fa fa-edit"></i> View Inventory</a>
</li>
</ul>
</li>
</section>
<!-- /.sidebar -->
</aside><file_sep><html>
<?php
//include("dbconnect.php");
require_once("dbconnect.php");
$dbConnect = new dbConnect("algoreal_db");
?>
<head>
<link rel="icon" href="fevicon.png" type="image/gif">
<style type="text/css">
input{
border:1px solid olive;
border-radius:5px;
}
h1{
color:darkgreen;
font-size:22px;
text-align:center;
}
</style>
</head>
<body>
<h1>Forgot Password<h1>
<form action='#' method='post'>
<table cellspacing='5' align='center'>
<tr><td>Email id:</td><td><input type='text' name='mail'/></td></tr>
<tr><td></td><td><input type='submit' name='submit' value='Submit'/></td></tr>
</table>
</form>
<?php
if(isset($_POST['submit']))
{
$mail=$_POST['mail'];
$q="select employee_id,first_name,middle_name,last_name,contact_no,email_id, password from employee_info WHERE status = '1' AND email_id='".$mail."' ";
$p = $dbConnect->FetchRecords($query);
//$p=mysql_affected_rows();
if($p!=0)
{
//$res=mysql_fetch_array($q);
$to=$p[0]['email_id'];
$subject='Remind password';
$message='Your password : '.$res['password'];
$headers='From:<EMAIL>';
$m=mail($to,$subject,$message,$headers);
if($m)
{
echo'Check your inbox in mail';
}
else
{
echo'mail is not send';
}
}
else
{
echo'You entered mail id is not present';
}
}
?>
</body>
</html>
|
ff55b23491b6a005c719ab4c8cfc9caa16448ef9
|
[
"Markdown",
"SQL",
"PHP"
] | 10
|
PHP
|
Sanglesagar/Car-Inventory-System
|
53eca27291a28b0490613a225233b2402a407ac9
|
83d6998b260ed8375d4ff9c47a1bc6049861d96b
|
refs/heads/main
|
<repo_name>Enfedaque/GestionDeColegios<file_sep>/src/main/java/com/sanvalero/netflix/dao/Conexion.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sanvalero.netflix.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* @author <NAME>
*/
public class Conexion {
private final String DRIVER = "com.mysql.cj.jdbc.Driver";
private final String URL_CONEXION = "jdbc:mysql://localhost:3306/netflix";
private final String USUARIO = "netflixuser";
private final String CONTRASENA = "netflix1234";
private Connection connection;
public Conexion(){
}
public Connection getConexion(){
return connection;
}
public void connect() {
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL_CONEXION, USUARIO, CONTRASENA);
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
public void disconnect() {
try {
connection.close();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
}
<file_sep>/src/main/java/com/sanvalero/netflix/dao/MatriculadosDAO.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sanvalero.netflix.dao;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author <NAME>
*/
public class MatriculadosDAO {
private Conexion conexion;
public MatriculadosDAO(Conexion conexion) {
this.conexion=conexion;;
}
//AÑADIR MATRICULA
public void añadirMatricula(String año, int duracion) throws SQLException {
String sql = "INSERT INTO matriculas(ano, duracion) VALUES (?, ?)";
/*PreparedStatement sentencia = conexion.prepareStatement(sql);
sentencia.setString(1, conexion.getID_Asignatura());
sentencia.executeUpdate();*/
PreparedStatement sentenciaSql=conexion.getConexion().prepareStatement(sql);
//Le indico los parametros para cada hueco
sentenciaSql.setString(1, año);
sentenciaSql.setInt(2, duracion);
sentenciaSql.executeUpdate();
}
/*public ArrayList<Matriculas> verTodasAsignaturas() throws SQLException {
return new ArrayList<>();
}*/
public void borrarMatricula(int id) {
}
public void modificarAsignatura() {
}
}
<file_sep>/README.md
# GestionDeColegios
Aplicacion web para gestionar dentro de un colegio todos los profesores, alumnos, y asignaturas relacionadas entrre ellos
|
54290e200bb8010be702081415be9a3228ae6684
|
[
"Markdown",
"Java"
] | 3
|
Java
|
Enfedaque/GestionDeColegios
|
b78b99a69e9ef7a1e8d602a73ef587a571b4e0c6
|
6d28e5f277482b660231b6abb323ee261590f440
|
refs/heads/master
|
<file_sep>export class Test {}<file_sep>gulp-typescript-multiproject
============================
Easily compile projects made up of multiple tsconfig.json with a simple configuration. This project
works for projects that contain a mix of commonJS and AMD wrapped code.
[](https://travis-ci.org/justinm/gulp-typescript-multiproject)
[](https://codeclimate.com/github/justinm/gulp-typescript-multiproject)
[](https://codeclimate.com/github/justinm/gulp-typescript-multiproject/coverage)
Example
-------
gulp-typescript-multiproject exposes easy to use gulp tasks that can simply the build and cleaning process.
```es6
import * as rsMultiProject from 'gulp-typescript-multiproject';
import * as gulp from 'gulp';
let tsProject = rsMultiProject([
'./**/tsconfig.json',
'!**/node_modules',
'!**/bower_components'
]);
gulp.task('build', tsProject.build());
gulp.task('clean', tsProject.clean());
```
After starting a "gulp build", each tsconfig.json will be compiled as it's on independent
project. Using options in tsconfig.json, files can be easily included/excluded as needed, allowing
separation between two different types of applications (e.g. frontend, backend) while in the same project. <file_sep>import {GulpTypescriptMultiProject} from './lib/multi-project'
export = GulpTypescriptMultiProject;<file_sep>import * as mocha from 'mocha';
import * as should from 'should';
import * as fs from 'fs';
import * as gulp from 'gulp';
import * as path from 'path';
import GulpTypescriptMultiProject = require('../../index');
require('should');
describe('GulpTypescriptMultiProject', () => {
const pathToTestJs = path.join(__dirname, '../compiling/success/test.js')
describe('build', () => {
it('should error with no tsconfig files found', (callback) => {
let tsProject = new GulpTypescriptMultiProject(gulp, []);
let build = tsProject.build();
build()
.on('error', function(e: Error) {
callback(null);
});
});
it('should compile test/test.ts with test/tsconfig.json', function (callback) {
this.timeout(5000);
let tsProject = new GulpTypescriptMultiProject(gulp, [path.join(__dirname, '../*/success/tsconfig.json')]);
if (fs.existsSync(pathToTestJs)) {
fs.unlinkSync(pathToTestJs);
}
tsProject.build()()
.on('error', callback)
.on('finish', function() {
if (!fs.existsSync(pathToTestJs)) {
callback(new Error('Unable to locate compiled file ' + pathToTestJs))
} else {
callback(null);
}
});
});
it('should error with any compilation fails for any tsconfig.json files', function (callback) {
this.timeout(5000);
let tsProject = new GulpTypescriptMultiProject(gulp, [path.join(__dirname, '../**/tsconfig.json')]);
let hasErrored = false;
tsProject.build()()
.on('finish', function() {
if (!hasErrored) {
callback(new Error('Project did not report any errors'));
} else {
callback();
}
})
.on('error', function(err: Error) {
if (!hasErrored) {
hasErrored = true;
}
});
});
});
describe('clean', () => {
it('should error clean with no tsconfig files found', (callback) => {
let tsProject = new GulpTypescriptMultiProject(gulp, []);
let clean = tsProject.clean();
clean()
.on('error', function() {
callback(null);
});
});
it('should complete clean with after a successful build', function (callback) {
this.timeout(10000);
let tsProject = new GulpTypescriptMultiProject(gulp, [path.join(__dirname, '../*/success/tsconfig.json')]);
tsProject.build()().on('finish', () => {
fs.existsSync(pathToTestJs).should.be.true();
tsProject.clean()()
.on('error', function(err: Error) {
console.log('Hit error', err);
})
.on('finish', function (err: Error) {
console.log('Finished clean in test');
if (err) {
return callback(err);
}
fs.existsSync(pathToTestJs);
callback();
});
});
});
});
});
<file_sep>declare module "gulp-typescript-multiproject" {
import * as gulpCore from 'gulp';
import * as stream from 'stream';
function e(gulp: typeof gulpCore, srcGlob: string[], dest?: string): any;
namespace e {
interface GulpTypescriptMultiProject {
build: () => () => stream.Transform;
clean: () => () => stream.Transform;
}
}
}<file_sep>"use strict";
var fs = require('fs');
var gulp = require('gulp');
var path = require('path');
var GulpTypescriptMultiProject = require('../../index');
require('should');
describe('GulpTypescriptMultiProject', function () {
var pathToTestJs = path.join(__dirname, '../compiling/success/test.js');
describe('build', function () {
it('should error with no tsconfig files found', function (callback) {
var tsProject = new GulpTypescriptMultiProject(gulp, []);
var build = tsProject.build();
build()
.on('error', function (e) {
callback(null);
});
});
it('should compile test/test.ts with test/tsconfig.json', function (callback) {
this.timeout(5000);
var tsProject = new GulpTypescriptMultiProject(gulp, [path.join(__dirname, '../*/success/tsconfig.json')]);
if (fs.existsSync(pathToTestJs)) {
fs.unlinkSync(pathToTestJs);
}
tsProject.build()()
.on('error', callback)
.on('finish', function () {
if (!fs.existsSync(pathToTestJs)) {
callback(new Error('Unable to locate compiled file ' + pathToTestJs));
}
else {
callback(null);
}
});
});
it('should error with any compilation fails for any tsconfig.json files', function (callback) {
this.timeout(5000);
var tsProject = new GulpTypescriptMultiProject(gulp, [path.join(__dirname, '../**/tsconfig.json')]);
var hasErrored = false;
tsProject.build()()
.on('finish', function () {
if (!hasErrored) {
callback(new Error('Project did not report any errors'));
}
else {
callback();
}
})
.on('error', function (err) {
if (!hasErrored) {
hasErrored = true;
}
});
});
});
describe('clean', function () {
it('should error clean with no tsconfig files found', function (callback) {
var tsProject = new GulpTypescriptMultiProject(gulp, []);
var clean = tsProject.clean();
clean()
.on('error', function () {
callback(null);
});
});
it('should complete clean with after a successful build', function (callback) {
this.timeout(10000);
var tsProject = new GulpTypescriptMultiProject(gulp, [path.join(__dirname, '../*/success/tsconfig.json')]);
tsProject.build()().on('finish', function () {
fs.existsSync(pathToTestJs).should.be.true();
tsProject.clean()()
.on('error', function (err) {
console.log('Hit error', err);
})
.on('finish', function (err) {
console.log('Finished clean in test');
if (err) {
return callback(err);
}
fs.existsSync(pathToTestJs);
callback();
});
});
});
});
});
<file_sep>import * as typescript from 'gulp-typescript';
import * as stream from 'stream';
import * as gulpUtil from 'gulp-util';
import * as newer from 'gulp-newer';
import * as through from 'through2';
import * as gulpLib from 'gulp';
import * as path from 'path';
import * as fs from 'fs';
import * as merge from 'merge2';
let debug = require('gulp-debug');
export class GulpTypescriptMultiProject {
constructor(private gulp: typeof gulpLib, private srcGlob: string[], private dest?: string) {
}
private getProjectsStream(): stream.Transform {
let foundProject = false;
return this.gulp.src(this.srcGlob, { read: false })
.pipe(through.obj(function(file, enc, callback) {
if (file.isDirectory() || path.basename(file.path) !== 'tsconfig.json') {
return callback();
}
if (file.isStream()) {
return callback(new gulpUtil.PluginError({
plugin: 'gulp-typescript-multi-project',
message: 'Streams are not supported.'
}));
}
foundProject = true;
this.push(file);
return callback();
}))
.on('finish', function () {
if (!foundProject) {
this.emit('error', new gulpUtil.PluginError({
plugin: 'gulp-typescript-multiproject',
message: 'Unable to locate any tsconfig.json files'
}))
}
})
}
build(): () => stream.Transform {
return (): stream.Transform => {
let errors: Error[] = [];
let self = this;
return this.getProjectsStream()
.on('error', function (err: Error) {
gulpUtil.log(gulpUtil.colors.red(err.message));
errors.push(err);
})
.pipe(through.obj(function(file, enc, pipeCallback) {
let tlPipe = this;
gulpUtil.log('Building project: ' + file.path);
// The build path must be relative to the tsconfig.json path or the compiled results
let destPath = self.dest || path.dirname(file.path);
let tsProject = typescript.createProject(file.path);
let tsSrc = tsProject.src();
let tsResult = tsSrc
.pipe(newer({ dest: destPath, ext: '.js' }))
.pipe(tsProject())
.on('error', function (err: Error) {
errors.push(err);
});
return merge([
tsResult.js
.pipe(self.gulp.dest(destPath)),
tsResult.dts
// .pipe(debug())
.pipe(self.gulp.dest(destPath))
])
.on('finish', function () {
if (errors.length) {
errors.forEach((err) => {
tlPipe.emit('error', new gulpUtil.PluginError({
plugin: 'gulp-typescript-multiproject',
message: err.message
}));
});
}
pipeCallback();
});
}))
.on('finish', function () {
errors.forEach(function (err) {
this.emit('error', err);
}, this);
});
};
};
clean = () => {
return (): stream.Transform => {
let errors: Error[] = [];
return this.getProjectsStream()
.on('error', function(err: any) {
gulpUtil.log(gulpUtil.colors.red(err.message));
errors.push(err);
})
.pipe(through.obj(function (file, enc, callback) {
let tsProject = typescript.createProject(file.path);
let tsSrc = tsProject.src();
gulpUtil.log('Cleaning project: ' + file.path);
return tsSrc.pipe(through.obj((tsFile, enc, callback) => {
if (tsFile.path.substr(tsFile.path.length - 3) !== '.ts') {
return callback();
}
let jsPath = tsFile.path.substr(0, tsFile.path.length - 3) + '.js';
if (fs.existsSync(jsPath)) {
fs.unlinkSync(jsPath);
} else {
this.push(tsFile);
}
callback();
}))
.on('error', (err: Error) => errors.push(err))
.on('finish', function () {
let self = this;
errors.forEach((err) => {
self.emit('error', err);
});
callback();
});
}))
.on('finish', function () {
errors.forEach(function (err) {
this.emit('error', err);
}, this);
});
}
}
}<file_sep>export class TestTwo {}<file_sep>{
"parent": true,
"compilerOptions": {
"rootDir": "./",
"noImplicitAny": true,
"inlineSourceMap": true,
"noEmitOnError": true,
"target": "ES5",
"module": "commonjs",
"types": [
"gulp",
"gulp-util",
"through2",
"mocha"
]
},
"exclude": [
"node_modules",
"node_modules/@types",
"bower_components",
"test/compiling"
],
"include": [
"**/*.ts"
]
}
|
f730113485ef80528cde398503c99971b258bbaf
|
[
"JavaScript",
"TypeScript",
"JSON with Comments",
"Markdown"
] | 9
|
JavaScript
|
justinm/gulp-typescript-multiproject
|
998f60e42cac5ed1df28eb8e8f63087ba391261e
|
e43031a56c73dddd7366d26c2f4addb42c3c8033
|
refs/heads/master
|
<repo_name>haltokyo-gmo/exp-rtc<file_sep>/README.md
# exp-rtc
WebRTC(Webカメラ)の実験用リポジトリ
## Required
- Web Camera
- [Emotion API subscription key](https://www.microsoft.com/cognitive-services/en-US/subscriptions) (Replace [here](index.js#L70))
- [npm](https://www.npmjs.com/)
- [Go](https://golang.org/)
## Usage
```
$ npm install
$ go run main.go
```
Then open [http://localhost:8888](http://localhost:8888)
<file_sep>/index.js
$(function() {
function MaxEmotion(scores) {
var max = Math.max(
scores.anger,
scores.contempt,
scores.disgust,
scores.fear,
scores.happiness,
scores.neutral,
scores.sadness,
scores.surprise
);
switch(max) {
case scores.anger:
return 'anger ' + scores.anger.toFixed(4);
case scores.contempt:
return 'contempt ' + scores.contempt.toFixed(4);
case scores.disgust:
return 'disgust ' + scores.disgust.toFixed(4);
case scores.fear:
return 'fear ' + scores.fear.toFixed(4);
case scores.happiness:
return 'happiness ' + scores.happiness.toFixed(4);
case scores.neutral:
return 'neutral ' + scores.neutral.toFixed(4);
case scores.sadness:
return 'sadness ' + scores.sadness.toFixed(4);
case scores.surprise:
return 'surprise ' + scores.surprise.toFixed(4);
default:
return 'none';
}
}
var stream;
navigator.mediaDevices.getUserMedia({video: {
mandatory: {
maxWidth: 600,
maxHeight: 400
}
}, audio: false})
.then(function(s) {
stream = s;
var v = document.querySelector('#video');
v.src = URL.createObjectURL(stream);
v.play();
})
.catch(function(error) {
console.error(error);
})
var canvas = document.querySelector('#canvas');
var ctx = canvas.getContext('2d');
ctx.scale(-1, 1);
document.querySelector('#capture').addEventListener('click', function() {
ctx.drawImage(document.querySelector('#video'), -600, 0);
var base64 = canvas.toDataURL('image/jpeg');
var bin = atob(base64.replace(/^.*,/, ''));
var buffer = new Uint8Array(bin.length);
for (var i = 0; i < bin.length; i++) {
buffer[i] = bin.charCodeAt(i);
}
$.ajax({
cache: false,
contentType: 'application/octet-stream',
data: buffer.buffer,
dataType: 'json',
headers: {
'Ocp-Apim-Subscription-Key': 'subscription_key_here'
},
method: 'POST',
processData: false,
url: 'https://api.projectoxford.ai/emotion/v1.0/recognize'
})
.done(function(data) {
var canvas_overlay = document.querySelector('#canvas-overlay');
var ctx_overlay = canvas_overlay.getContext('2d');
ctx_overlay.clearRect(0, 0, canvas_overlay.width, canvas_overlay.height);
for(var i in data) {
var rect = data[i].faceRectangle;
var text = MaxEmotion(data[i].scores);
ctx_overlay.beginPath();
ctx_overlay.strokeRect(rect.left, rect.top, rect.width, rect.height);
ctx_overlay.fillStyle = 'black';
var m = ctx_overlay.measureText(text);
ctx_overlay.fillRect(rect.left, rect.top - 10, m.width, 10);
ctx_overlay.fillStyle = 'white';
ctx_overlay.fillText(text, rect.left, rect.top);
ctx_overlay.closePath();
}
})
.fail(function(error) {
console.log(error);
})
})
document.querySelector('#record').addEventListener('click', function() {
var recorder = new MediaRecorder(stream, {
videoBitsPerSecond: 1024 * 1024, // 1Mbps
mimeType: 'video/webm'
});
var chunks = [];
recorder.onstop = function(e) {
var blob = new Blob(chunks, { 'type' : 'video/webm' });
chunks = [];
var url = window.URL.createObjectURL(blob);
document.querySelector('#result').src = url;
}
recorder.ondataavailable = function(e) {
chunks.push(e.data);
}
recorder.start();
setTimeout(function() {
recorder.stop();
}, 5000);
})
})
|
e50834f4ad6053bd8a39036b5e6d03acd59bbed6
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
haltokyo-gmo/exp-rtc
|
0a91a8454d8d3ac36b8e47d8b26b33de80555781
|
78c4ebbe4cc9205fbbfb98664717f5e634b5ae21
|
refs/heads/master
|
<file_sep>import React from "react";
import "./login.css";
export const Login = () => {
return (
<div className="box-login">
<div className="box-form">
<h1 className="title">Signe In</h1>
<form className="form">
<input className="box-input" type="text" placeholder="Your Email" />
<input
className="box-input"
type="text"
placeholder="Your Password"
/>
<input className="box-input" type="submit" value="Send" />
</form>
<p className="title">Forgot password ?</p>
</div>
</div>
);
};
<file_sep>import React from "react";
import { RouterDashboard } from "../../routers/RouterDashboard";
export const Content = () => {
return (
<div>
<RouterDashboard />
</div>
);
};
<file_sep>import React from "react";
// import { BrowserRouter as Router } from "react-router-dom";
import "./dashboard-app.css";
import { RouterApp } from "./routers/RouterApp";
export const DashboardApp = () => {
return <RouterApp />;
};
<file_sep>import React from "react";
import { BrowserRouter as Router, Redirect, Route, Switch } from "react-router-dom";
import { Dashboard } from "../components/dashboard/Dashboard";
import { Login } from "../components/login/Login";
export const RouterApp = () => {
return (
<Router>
<>
<Switch>
<Route exact path="/" component={Login} />
<Route path="/dashboard" component={Dashboard} />
<Redirect to="/" />
</Switch>
</>
</Router>
);
};
<file_sep>import React from "react";
import "./navbar.css";
export const Navbar = () => {
return (
<div className="box-navbar">
<div className="box-item-navbar">
Menu
</div>
<div className="item-navbar">
Email
</div>
<div className="item-navbar">
Avatar
</div>
<div className="item-navbar">
Notificaciones
</div>
</div>
);
};
<file_sep>import React from "react";
import { Link } from "react-router-dom";
import "./sidebar.css";
export const Sidebar = () => {
return (
<div className="box-sidebar">
<div className="avatar">Usuario</div>
<div className="box-item-sidebar">Buscar...</div>
<div className="box-item-sidebar">
<Link to="/dashboard/categories">Categories</Link>
</div>
<div className="box-item-sidebar">
<Link to="/dashboard/menus">Menus</Link>
</div>
<div className="box-item-sidebar">
<Link to="/dashboard/clientes">Clientes</Link>
</div>
</div>
);
};
<file_sep>import React from "react";
import { Redirect, Route, Switch } from "react-router-dom";
import { Categories } from "../components/categories/Categories";
import { Clientes } from "../components/clients/Clientes";
import { Menus } from "../components/menus/Menus";
export const RouterDashboard = () => {
return (
<div>
<Switch>
<Route exact path="/dashboard/categories" component={Categories} />
<Route exact path="/dashboard/menus" component={Menus} />
<Route exact path="/dashboard/clientes" component={Clientes} />
<Redirect to="/dashboard" />
</Switch>
</div>
);
};
|
b44942f855f7e32d19ee14bcc945e5e8c963405f
|
[
"JavaScript"
] | 7
|
JavaScript
|
devlitus/dashboard-app
|
4b3382306db672d94fe0eda35192905fe9fd0020
|
95bc1b500b48e4ce50f81db24a56a86ee06aac08
|
refs/heads/master
|
<file_sep># **************************************************************************** #
# #
# ::: :::::::: #
# Makefile :+: :+: :+: #
# +:+ +:+ +:+ #
# By: <EMAIL> <asgaulti> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2021/06/21 20:39:07 by astridgault #+# #+# #
# Updated: 2021/07/23 16:19:22 by asgaulti ### ########.fr #
# #
# **************************************************************************** #
NAME = minitalk
SERVER = ./server/server
CLIENT = ./client/client
SRCS_SERVER = ./server/ft_server.c ./server/ft_utils.c
SRCS_CLIENT = ./client/ft_client.c ./client/ft_utils.c
OBJS_SERVER = ${SRCS_SERVER:.c=.o}
DEP_SERVER = ${SRCS_SERVER:.c=.d}
OBJS_CLIENT = ${SRCS_CLIENT:.c=.o}
DEP_CLIENT = ${SRCS_CLIENT:.c=.d}
CC = clang-9
RM = rm -f
CFLAGS = -Wall -Werror -Wextra -MMD
INCL = include
all: ${NAME}
$(NAME): ${SERVER} ${CLIENT}
$(SERVER): ${OBJS_SERVER}
${CC} ${CFLAGS} -o ${SERVER} ${OBJS_SERVER}
$(CLIENT): ${OBJS_CLIENT}
${CC} ${CFLAGS} -o ${CLIENT} ${OBJS_CLIENT}
-include ${DEP_SERVER} ${DEP_CLIENT}
.c.o:
${CC} ${CFLAGS} -I${INCL} -g -c $< -o ${<:.c=.o}
clean:
${RM} ${DEP_SERVER} ${DEP_CLIENT} ${OBJS_SERVER} ${OBJS_CLIENT}
fclean: clean
${RM} $(SERVER) $(CLIENT)
re: fclean all
.PHONY: all clean fclean re minitalk
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* minitalk.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: astridgaultier <<EMAIL>. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/24 12:17:53 by asgaulti #+# #+# */
/* Updated: 2021/07/13 18:17:16 by astridgault ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MINITALK_H
# define MINITALK_H
# include <signal.h>
# include <sys/types.h>
# include <stdbool.h>
# include <stdlib.h>
# include <unistd.h>
# include <stdio.h>
int main(int ac, char **av);
void ft_get_msg(int signal_num, siginfo_t *info, void *context);
bool ft_check_av(char **av);
void ft_find_bit(int pid, char *str);
void ft_send_signal(int pid, int bit);
void ft_get_bit(int sig, siginfo_t *info, void *context);
int ft_isdigit(char c);
int ft_atoi(const char *str);
void ft_putnbr(int nb);
void ft_putchar(char c);
#endif<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_server.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: astridgaultier <<EMAIL>. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/21 20:42:27 by astridgault #+# #+# */
/* Updated: 2021/07/22 16:53:19 by asgaulti ### ########.fr */
/* */
/* ************************************************************************** */
#include "minitalk.h"
void ft_get_bit(int sig, siginfo_t *info, void *context)
{
static unsigned char c = 0;
static int size = 0;
(void)context;
if (sig == SIGUSR2)
c |= (1 << (size));
size++;
if (size == 8)
{
if (c == '\0')
{
if (kill(info->si_pid, SIGUSR1) == -1)
{
write (1, "Failure in signal reception\n", 28);
exit (EXIT_FAILURE);
}
write (1, "\nMessage received\n", 18);
}
else
write (1, &c, 1);
size = 0;
c = 0;
}
}
int main(int ac, char **av)
{
struct sigaction sa;
(void)av;
sa.sa_sigaction = ft_get_bit;
sa.sa_flags = SA_SIGINFO;
sigaction(SIGUSR1, &sa, NULL);
sigaction(SIGUSR2, &sa, NULL);
if (ac != 1)
{
write(1, "Invalid parameters\n", 19);
return (EXIT_FAILURE);
}
else
{
write(1, "PID = ", 6);
ft_putnbr(getpid());
write(1, "\n", 1);
}
while (1)
pause();
return (0);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_client.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: astridgaultier <<EMAIL>. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/21 20:42:44 by astridgault #+# #+# */
/* Updated: 2021/07/13 17:56:29 by astridgault ### ########.fr */
/* */
/* ************************************************************************** */
#include "minitalk.h"
void ft_get_msg(int signal_num, siginfo_t *info, void *context)
{
(void)signal_num;
(void)context;
(void)info;
write(1, "Message received by server\n", 27);
exit(EXIT_SUCCESS);
}
void ft_find_bit(int pid, char *str)
{
int bit;
int count;
int i;
i = 0;
while (str[i])
{
bit = 0;
count = 0;
while (count < 8)
{
bit = (str[i] >> count++) & 1;
ft_send_signal(pid, bit);
usleep(42);
}
i++;
}
count = 0;
while (count < 8)
{
bit = ('\0' >> count++) & 1;
ft_send_signal(pid, bit);
usleep(42);
}
}
void ft_send_signal(int pid, int bit)
{
if (bit == 0)
{
if (kill(pid, SIGUSR1) == -1)
{
write(1, "Error : signal not send\n", 24);
exit (EXIT_FAILURE);
}
}
if (bit == 1)
{
if (kill(pid, SIGUSR2) == -1)
{
write(1, "Error : signal not send\n", 24);
exit (EXIT_FAILURE);
}
}
}
/*
** Check if PID is only number
**
** @param av Argv argument
**
** @return true if only number, false otherwise
*/
bool ft_check_av(char **av)
{
int j;
j = 0;
while (av[1][j])
{
if (ft_isdigit(av[1][j]) == 0)
{
return (false);
}
j++;
}
return (true);
}
int main(int ac, char **av)
{
pid_t pid;
struct sigaction sa;
pid = 0;
if (ac != 3)
{
write(1, "Wrong number of arguments\n", 26);
exit (EXIT_FAILURE);
}
else
{
sa.sa_sigaction = ft_get_msg;
sa.sa_flags = SA_SIGINFO;
sigaction(SIGUSR1, &sa, NULL);
pid = ft_atoi(av[1]);
if (ft_check_av(av) == false || pid < 1)
{
write (1, "Wrong PID\n", 10);
exit (EXIT_FAILURE);
}
}
ft_find_bit(pid, av[2]);
return (0);
}
|
80d3eb536b2b3acd6776a9e4ace69911cd214fc8
|
[
"C",
"Makefile"
] | 4
|
Makefile
|
astrid42-code/minitalk
|
4fbe41b78a1ac462d125311be86e7241e37364e5
|
031f303c2e2a50b0a65c7762b52561c012a528e9
|
refs/heads/master
|
<repo_name>bepronetwork/backoffice<file_sep>/src/redux/reducers/summaryReducer.js
const initialState = {
users: [],
games: [],
bets: [],
revenue: [],
wallet: [],
withdrawals: [],
};
export default function(state = initialState, action) {
switch (action.type) {
case "SET_USERS_DATA":
return { ...state, users: action.payload };
case "SET_GAMES_DATA":
return { ...state, games: action.payload };
case "SET_BETS_DATA":
return { ...state, bets: action.payload };
case "SET_REVENUE_DATA":
return { ...state, revenue: action.payload };
case "SET_WALLET_DATA":
return { ...state, wallet: action.payload };
case "SET_WITHDRAWALS_DATA":
return {
...state,
withdrawals: [...state.withdrawals, ...action.payload],
};
default:
return state;
}
}
<file_sep>/src/containers/Settings/tabs/AddressManagementContainer.js
import React from 'react';
import { Col, Container, Row } from 'reactstrap';
import { connect } from "react-redux";
import { EditableTable } from '../../../components';
const defaultProps = {
authorizedAddresses : [],
}
class AddressManagementContainer extends React.Component{
constructor(props){
super(props)
this.state = defaultProps;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
let { profile } = props;
let app = profile.getApp();
this.setState({...this.state,
authorizedAddresses : app.getInformation('authorizedAddresses') ? app.getInformation('authorizedAddresses').map( a => {
return {
address : a
}
}) : defaultProps.authorizedAddresses
})
}
onChange = async (new_data) => {
const { profile } = this.props;
let addressObject = new_data.filter(n => n.isNew == true)[0];
if(addressObject){
//Added
await profile.getApp().authorizeAddress({address : addressObject.address});
}else{
//Removed
let olderAddresses = profile.getApp().getInformation('authorizedAddresses');
let differenceAddressObject = olderAddresses.filter(x => !new_data.map( a => a.address).includes(x))[0];
await profile.getApp().unauthorizeAddress({address : differenceAddressObject});
}
await profile.getApp().updateAppInfoAsync();
await profile.update();
}
render = () => {
const { authorizedAddresses } = this.state;
return (
<div>
<h4> Manage here your Addresses </h4>
<p className='text-grey'> Authorized Addresses have the ability to allow user withdraws, not to withdraw the bankroller money, that is only for the ownerAddress </p>
<hr></hr>
<Row>
<Col lg={12}>
<EditableTable
title={'Authorized Addresses'}
onChange={this.onChange}
compareField={'address'}
columns={[
{ title: 'Address', field: 'address'}
]}
rawData={authorizedAddresses}
data={authorizedAddresses.map( v => {
return {
address: v.address
}
})}
/>
</Col>
</Row>
</div>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(AddressManagementContainer);
<file_sep>/src/redux/actions/walletReducer.js
export const SET_DATA_WALLET_VIEW = 'SET_DATA_WALLET_VIEW';
export function setWalletView(data) {
return {
type: SET_DATA_WALLET_VIEW,
action : data
};
}
<file_sep>/src/containers/Wizards/CreateApp/components/WizardForm.jsx
import React, { PureComponent } from 'react';
import { Col, Card, Row } from 'reactstrap';
import PropTypes from 'prop-types';
import WizardFormOne from './WizardFormOne';
import WizardFormThree from './WizardFormThree';
import NotificationSystem from 'rc-notification';
import { BasicNotification } from '../../../../shared/components/Notification';
let notification = null;
const showNotification = (message) => {
notification.notice({
content: <BasicNotification
title="Your App was Not Created"
message={message}
/>,
duration: 5,
closable: true,
style: { top: 0, left: 'calc(100vw - 100%)' },
className: 'right-up',
});
};
export default class WizardForm extends PureComponent {
static propTypes = {
onSubmit: PropTypes.func.isRequired,
};
constructor() {
super();
this.state = {
page: 1,
};
}
componentDidMount() {
NotificationSystem.newInstance({}, n => notification = n);
}
componentWillUnmount() {
notification.destroy();
}
showNotification = (message) => {
showNotification(message)
}
nextPage = () => {
this.setState({ page: this.state.page + 1 });
};
previousPage = () => {
this.setState({ page: this.state.page - 1 });
};
render() {
const { onSubmit } = this.props;
const { page } = this.state;
return (
<WizardFormOne showNotification={this.showNotification} handleSubmit={(e) => e.preventDefault()} {...this.props} onSubmit={false} />
);
}
}
<file_sep>/docs/README.md
# BetProtocol API
## Version: 0.0.1
### /admins/register
#### POST
##### Summary:
Register User Data
##### Description:
Search for matching accounts in the system.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| admin | body | Admin object to submit to the network | Yes | [AdminRegisterRequest](#adminregisterrequest) |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /admins/login
#### POST
##### Summary:
Login User
##### Description:
Login Admin Data
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| admin | body | Admin object to submit to the network | Yes | [UserLoginRequest](#userloginrequest) |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /users/register
#### POST
##### Summary:
Register User Data
##### Description:
Search for matching accounts in the system.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| user | body | User object to submit to the network | Yes | [UserRegisterRequest](#userregisterrequest) |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /users/login
#### POST
##### Summary:
Login User
##### Description:
Login User Data
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| user | body | User object to submit to the network | Yes | [UserLoginRequest](#userloginrequest) |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /users/summary
#### POST
##### Summary:
Get Summary Data for User
##### Description:
Get Summary Data for User
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| user | body | User Information | Yes | [UserSummaryRequest](#usersummaryrequest) |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /app/create
#### POST
##### Summary:
Create a App
##### Description:
Create a App for the user defined
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| app | body | App Information | Yes | [AppCreationRequest](#appcreationrequest) |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /app/summary
#### POST
##### Summary:
Get Summary Data for App
##### Description:
Get Summary Data for App
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| app | body | App Information | Yes | [AppSummaryRequest](#appsummaryrequest) |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /app/api/createToken
#### POST
##### Summary:
Get Summary Data for App
##### Description:
Get Summary Data for App
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| app | body | App Information | Yes | [AppTokenAPIRequest](#apptokenapirequest) |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /app/games/add
#### POST
##### Summary:
Create a Game in App Name
##### Description:
Create a Game for the App defined
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| game | body | Game Information | Yes | [GameCreationRequest](#gamecreationrequest) |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /app/games/bet/place
#### POST
##### Summary:
Place a Bet
##### Description:
Place a Bet for User Selected
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| bet | body | Bet Information | Yes | [PlaceBetRequest](#placebetrequest) |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /app/games/get
#### POST
##### Summary:
Get a game
##### Description:
Get a Game Data
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| bet | body | Game Information | Yes | [GameGetRequest](#gamegetrequest) |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /app/games/bet/resolve
#### POST
##### Summary:
Place a Bet
##### Description:
Place a Bet for User Selected
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| bet | body | Bet Information | Yes | [ResolveBetRequest](#resolvebetrequest) |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /deposit/generateReference
#### POST
##### Summary:
Create a Deposit Reference
##### Description:
Create a Deposit Reference for given CryptoCurrency
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| deposit | body | Deposit Reference Information | Yes | [GenerateReferenceRequest](#generatereferencerequest) |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /deposit/{id}/confirm
#### POST
##### Summary:
Confirm Deposit Creatione
##### Description:
Confirm Deposit Creation for given Crypto / PayBear
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| id | path | Deposit Id Paybear Callback | Yes | string |
| deposit | body | Deposit Reference Information | Yes | object |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /deposit/{id}/info
#### POST
##### Summary:
Get info Deposit
##### Description:
Info Deposit Creation for given Crypto / PayBear
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| id | path | Deposit Id Paybear Callback | Yes | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Success | [GeneralResponse](#generalresponse) |
| default | Error | [ErrorResponse](#errorresponse) |
### /swagger
### Models
#### AdminRegisterRequest
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| username | string (username) | Unique identifier of the user, besides the ID
| Yes |
| name | string | User Real Name
| Yes |
| email | string | User Email
| Yes |
| hash_password | string | Password Hased
| No |
#### UserRegisterRequest
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| username | string (username) | Unique identifier of the user, besides the ID
| Yes |
| name | string (name) | User Real Name
| Yes |
| email | string (email) | User Email
| Yes |
#### UserLoginRequest
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| username | string (username) | Unique identifier of the user, besides the ID
| Yes |
| password | <PASSWORD> | <PASSWORD> En<PASSWORD>
| Yes |
#### UserSummaryRequest
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| type | string (name) | Type of Summary Data
| Yes |
| user | string (name) | User ID
| Yes |
#### AppCreationRequest
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| name | string (name) | App Name
| Yes |
| description | string (description) | App Description
| Yes |
| marketType | integer | Market Mapping Number
| Yes |
| metadataJSON | string | Metadata JSON Object
| Yes |
| admin_id | string | Admin Id
| Yes |
#### GameGetRequest
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| id | string (name) | Game Id
| Yes |
#### AppSummaryRequest
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| type | string (name) | App Name
| Yes |
| app | string (name) | App ID
| Yes |
#### AppTokenAPIRequest
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| app | string (name) | App ID
| Yes |
#### GameCreationRequest
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| app | string | Game Name
| Yes |
| edge | integer | Edge for Each Bet (Money Put Aside for the App as a Fee)
| Yes |
| marketType | integer | Market Type - Example "CoinFlip" = 1
| Yes |
#### ResolveBetRequest
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| bet | string (string) | Bet Id
| Yes |
#### PlaceBetRequest
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| user | string (string) | User Id
| Yes |
| app | string (string) | App Id
| Yes |
| betAmount | integer | Bet Amount for Betting Action
| Yes |
| game | string (string) | App User Id
| Yes |
| result | [ integer ] | Win Outcome Amount
| Yes |
#### GenerateReferenceRequest
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| entityType | string (name) | Type of Entity
| Yes |
| user_external_id | string (name) | User External _id
| Yes |
| currency | string (name) | Currency Small Identificator ["btc", "eth", etc..]
| Yes |
| username | string (name) | Username of Email of the User
| Yes |
| full_name | string (name) | Full Name of the User
| Yes |
| name | string (name) | First Name of the User
| Yes |
| nationality | string (name) | UNICODE for Nationality like PT for Portugal
| Yes |
| age | number (number) | User Age
| Yes |
| email | string (name) | User Email
| Yes |
| app_id | string (name) | Company id for API Use
| Yes |
#### GeneralResponse
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| data | object (data) | Unique identifier of the user, besides the ID
| Yes |
| meta | object (meta) | User Real Name
| Yes |
#### ErrorResponse
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| message | string | | Yes |<file_sep>/src/containers/Wallet/components/paths/FreeCurrencyWidget.js
import React from 'react';
import { Row } from 'reactstrap';
import { connect } from "react-redux";
import { LockWrapper } from '../../../../shared/components/LockWrapper';
import { TabContainer } from '../WalletTabs/styles';
import { Paragraph } from '../LiquidityWalletContainer/styles';
import FreeCurrencyAddOn from './FreeCurrencyAddOn'
class FreeCurrencyWidget extends React.Component{
render = () => {
const { profile, data } = this.props;
const { wallet } = data;
const isSuperAdmin = profile.User.permission.super_admin;
return (
<TabContainer>
<Paragraph style={{ marginBottom: 15 }}>Define how much free currency users can earn in each time period</Paragraph>
<Row>
<LockWrapper hasPermission={isSuperAdmin}>
<FreeCurrencyAddOn wallet={wallet}/>
</LockWrapper>
</Row>
</TabContainer>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
wallet: (state.wallet.currency) ? state.wallet : state.profile.getApp().getSummaryData('walletSimple').data[0]
};
}
export default connect(mapStateToProps)(FreeCurrencyWidget);<file_sep>/src/shared/components/TextInput.js
import React, { PureComponent } from 'react';
import { Field, reduxForm } from 'redux-form';
import PropTypes from 'prop-types';
import TextField from '@material-ui/core/TextField';
const renderTextField = ({
input, label, meta: { touched, error }, disabled, children, select, type, defaultValue, autoFocus
}) => {
return (
<TextField
className="material-form__field"
label={label}
color={'#ccc'}
error={touched && error}
disabled={disabled}
autoFocus={autoFocus}
value={defaultValue}
defaultValue={defaultValue}
children={children}
type={type}
select={select}
onChange={(e) => {
e.preventDefault();
input.onChange(e);
}}
/>
)
}
renderTextField.propTypes = {
input: PropTypes.shape().isRequired,
label: PropTypes.string.isRequired,
meta: PropTypes.shape({
touched: PropTypes.bool,
error: PropTypes.string,
}),
select: PropTypes.bool,
children: PropTypes.arrayOf(PropTypes.element),
};
renderTextField.defaultProps = {
meta: null,
select: false,
children: [],
};
class TextInput extends PureComponent {
constructor(props) {
super(props);
this.state = {
showPassword: false,
};
}
changeContent = (type, item, index) => {
if(this.props.changeContent){
this.props.changeContent(type, item, index)
}
}
render() {
return (
<div className="form__form-group-field">
{this.props.icon ?
<div className="form__form-group-icon" style={{marginRight : 10}}>
<this.props.icon />
</div>
: null}
<Field
name={this.props.name}
label={this.props.label}
type={this.props.type}
autoFocus={this.props.autoFocus}
disabled={this.props.disabled}
defaultValue={this.props.defaultValue}
component={renderTextField}
placeholder={this.props.placeholder}
index={this.props.index}
onChange={(e) => this.changeContent(this.props.name, e.target.value, this.props.index)}/>
</div>
);
}
}
export default reduxForm({
form: 'new_form', // a unique identifier for this form
})(TextInput);
<file_sep>/src/containers/Stats/index.jsx
import React from 'react';
import { Card, Col, Container, Row } from 'reactstrap';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import DepositsWidget from './components/DepositsWidget';
import DepositsInfo from './components/DepositsInfo';
import WithdrawalsInfo from './components/WithdrawalsInfo';
import LiquidityInfo from './components/LiquidityInfo';
import PlatformCostsInfo from './components/PlatformCostsInfo';
import RevenueChart from './components/RevenueChart';
import DataWidget from '../DataWidget/DataWidget';
import ProfitResume from './components/ProfitResume';
import TurnoverResume from './components/TurnoverResume';
class StatsContainer extends React.Component{
constructor(props){
super(props)
}
render = () => {
const { currency, isLoading, periodicity } = this.props;
return (
<Container className="dashboard">
<Row>
<Col lg={3}>
<DataWidget>
<LiquidityInfo currency={currency} isLoading={isLoading} data={this.props.profile.getApp().getSummaryData('wallet')}/>
</DataWidget>
</Col>
<Col lg={3}>
<DataWidget>
<ProfitResume currency={currency} isLoading={isLoading} periodicity={periodicity} data={{
revenue : this.props.profile.getApp().getSummaryData('revenue'),
wallet : this.props.profile.getApp().getSummaryData('wallet'),
}}/>
</DataWidget>
</Col>
<Col lg={3}>
<DataWidget>
<TurnoverResume currency={currency} isLoading={isLoading} periodicity={periodicity} data={{
revenue : this.props.profile.getApp().getSummaryData('revenue'),
wallet : this.props.profile.getApp().getSummaryData('wallet'),
}} />
</DataWidget>
</Col>
</Row>
<Row>
<Col lg={12}>
<DataWidget>
<RevenueChart
currency={currency}
isLoading={isLoading}
data={{
revenue : this.props.profile.getApp().getSummaryData('revenue'),
wallet : this.props.profile.getApp().getSummaryData('wallet'),
}}
/>
</DataWidget>
</Col>
</Row>
<Row>
{/* <Col lg={6}>
<DataWidget>
<DepositsWidget/>
</DataWidget>
</Col> */}
</Row>
</Container>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
currency : state.currency,
periodicity: state.periodicity,
isLoading: state.isLoading
};
}
StatsContainer.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(StatsContainer);
<file_sep>/src/containers/Applications/components/GamesContainer.jsx
/* eslint-disable react/no-array-index-key */
import React from 'react';
import { connect } from "react-redux";
import { Col, Row } from 'reactstrap';
import GameInfo from './GameInfo';
import _ from 'lodash';
const image = `${process.env.PUBLIC_URL}/img/dashboard/empty.png`;
class GamesContainer extends React.Component {
constructor() {
super();
this.state = {
activeIndex : 0,
games : [],
wallet : {}
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { data, profile } = props;
const gamesInfo = await profile.getApp().getSummaryData('gamesInfo').data.data.message;
const games = !_.isNull(data.games.data) && (typeof data.games.data !== 'string') ? await getAllGames(data.games.data, gamesInfo) : [];
const wallet = data.wallet.data;
this.setState({...this.state,
wallet,
games
})
}
hasRestriction(game) {
if (game.name.toLowerCase().includes('jackpot')) {
return true;
} else {
return false;
}
}
render() {
const { wallet, games } = this.state;
const { isLoading, data } = this.props;
const myGames = games.filter(game => !this.hasRestriction(game));
return (
(myGames.length > 0) && !_.isNull(data.games.data) ?
<Row md={12} xl={12} lg={12} xs={12}>
{myGames.map(game => {
return (
<Col lg={4} style={{ minWidth: 290 }}>
<GameInfo game={game} isLoading={isLoading} wallet={wallet} {...this.props}/>
</Col>
)
})}
</Row>
:
<div style={{ margin: 20 }}>
<h4>You have no Games and/or Currencies enabled currently</h4>
<img src={image} style={{width :'30%', marginTop : 20}}/>
</div>
);
}
}
function getAllGames(data, gamesInfo){
let allGames = [];
const gamesOnPeriodicity = data.map(index => index.games);
const concatGames = [].concat(...gamesOnPeriodicity);
const games = Object.values([...concatGames].reduce((acc, { _id, name, edge, betsAmount, betAmount, profit, fees }) => {
acc[_id] = { _id, name,
edge: (acc[_id] ? acc[_id].edge : 0) + edge,
betsAmount: (acc[_id] ? acc[_id].betsAmount : 0) + betsAmount,
betAmount: (acc[_id] ? acc[_id].betAmount : 0) + betAmount,
profit: (acc[_id] ? acc[_id].profit : 0) + profit,
fees: (acc[_id] ? acc[_id].fees : 0) + fees };
return acc;
}, {}));
gamesInfo.filter(game => games.map(g => g._id).includes(game._id)).map(game => {
games.filter(g => g._id === game._id).map(g => allGames.push({...g, ...game}));
})
gamesInfo.filter(game => !games.map(g => g._id).includes(game._id)).map(game => {
allGames.push({edge: 0, betsAmount: 0, betAmount: 1, profit: 0, fees: 0, ...game });
});
return allGames;
}
function mapStateToProps(state){
return {
profile: state.profile,
isLoading: state.isLoading
};
}
export default connect(mapStateToProps)(GamesContainer);
<file_sep>/src/lib/etherscan.js
import { ETHEREUM_NET_DEFAULT } from "../config/apiConfig";
import { ierc20 } from '../controllers/interfaces';
const abiDecoder = require('abi-decoder'); // NodeJS
var abiDecoderERC20 = abiDecoder;
abiDecoderERC20.addABI(ierc20.abi);
export const ETHERSCAN_URL = `https://${ETHEREUM_NET_DEFAULT != 'mainnet' ? `${ETHEREUM_NET_DEFAULT}.` : ''}etherscan.io`;
const URL = `https://api${ETHEREUM_NET_DEFAULT != 'mainnet' ? ("-" + ETHEREUM_NET_DEFAULT) : ''}.etherscan.io/api`
const KEY = '<KEY>';
async function getPastTransactions(address){
let URL_FETCH = `${URL}?module=account&action=txlist&address=${address}&sort=desc&apikey=${KEY}`;
try{
let response = await fetch(URL_FETCH, { method : 'GET' });
return response.json();
}catch(err){
throw err;
}
}
function getTransactionDataERC20(transaction_data_encoded){
const input = transaction_data_encoded.input;
const decodedInput = abiDecoderERC20.decodeMethod(input);
if(!decodedInput){return null}
const functionName = decodedInput.name;
const functionParams = decodedInput.params;
let tokensTransferedTo = functionParams[0].value;
/* Response Object */
let res = {
tokensTransferedTo : tokensTransferedTo,
functionName : functionName,
from : transaction_data_encoded.from,
tokenAmount : functionParams[1].value
}
return res;
}
export {
getPastTransactions,
getTransactionDataERC20
}<file_sep>/src/utils/numberFormatation.js
export const formatCurrency = (value) => {
return parseFloat(value).toFixed(6);
}
export const formatPercentage = (value) => {
return parseFloat(value).toFixed(2);
}<file_sep>/src/containers/Settings/tabs/Account.js
import React from 'react';
import { Col, Container, Row, Card, CardBody, Button } from 'reactstrap';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import _ from 'lodash';
import Switch from '@material-ui/core/Switch';
import store from "../../../containers/App/store";
import { set2FA } from '../../../redux/actions/set2FA';
const defaultState = {
has2FA : false,
email : 'N/A',
nam : 'N/A',
username : 'N/A'
}
class SettingsAccountContainer extends React.Component{
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { profile, set2FA } = props;
let params = profile.getUserInfo();
let { success } = set2FA;
this.setState({
...this.state,
has2FA : params.security['2fa_set'] || success,
email : params.email,
name : params.name,
username : params.username
})
}
handleChange = async ({key, value}) => {
var { profile } = this.props;
switch(key){
case 'set2FA' : {
// Popup with QR Code and Instructions
await store.dispatch(set2FA({isActive : true}));
};
}
this.projectData(this.props);
};
render = () => {
const {
has2FA,
username,
email,
name
} = this.state;
return (
<div style={{ margin: 10 }}>
<p className="dashboard__visitors-chart-title text-left" style={{fontSize : 18, marginBottom : 10}}> My Account </p>
<hr></hr>
<Container>
<Row>
<Col sm={5}>
<h5> Name </h5>
</Col>
<Col sm={7}>
<p> {name}
</p>
</Col>
</Row>
</Container>
<Container>
<Row>
<Col sm={5}>
<h5> Username </h5>
</Col>
<Col sm={7}>
<p> {username}
</p>
</Col>
</Row>
</Container>
<Container>
<Row>
<Col sm={5}>
<h5> E-mail </h5>
</Col>
<Col sm={7}>
<p> {email}
</p>
</Col>
</Row>
</Container>
<Container>
<Row>
<Col sm={5}>
<h5> 2FA Authentication </h5>
</Col>
<Col sm={7}>
<Switch color="primary" checked={has2FA} onChange={(value) => this.handleChange({key : 'set2FA', value})}value="checkedF" inputProps={{ 'aria-label': 'primary checkbox' }} />
</Col>
</Row>
</Container>
</div>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
set2FA : state.set2FA
};
}
SettingsAccountContainer.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(SettingsAccountContainer);
<file_sep>/src/containers/Applications/Customization/components/Languages/index.js
import React from 'react';
import { connect } from 'react-redux';
import { Row, Card, CardBody } from 'reactstrap';
import { Title } from './styles';
import _ from 'lodash'
import Language from './Language'
const cardBodyStyle = {
margin: 10,
borderRadius: "10px",
border: "solid 1px rgba(164, 161, 161, 0.35)",
backgroundColor: "#fafcff",
boxShadow: "none",
padding: 30
}
class Languages extends React.Component {
constructor(props){
super(props);
this.state = {};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { profile } = props;
const { languages } = profile.getApp().getCustomization();
this.setState({ languages: languages })
}
render() {
const { languages } = this.state;
return (
<>
<Card>
<CardBody style={cardBodyStyle}>
<Title>Languages</Title>
<hr/>
{ languages && (
<Row>
{ !_.isEmpty(languages) && languages.map(language => {
return (
<Language language={language}/>
)
}) }
</Row>
)}
</CardBody>
</Card>
</>
)
}
};
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(Languages);<file_sep>/src/containers/Applications/Customization/components/Banners.js
import React, { Component } from 'react'
import EditLock from '../../../Shared/EditLock.js';
import TextInput from '../../../../shared/components/TextInput';
import { Col, Row, Card, CardBody } from 'reactstrap';
import { connect } from "react-redux";
import Dropzone from 'react-dropzone'
import 'react-alice-carousel/lib/alice-carousel.css'
import { GridList, withStyles, FormLabel } from '@material-ui/core';
import BooleanInput from '../../../../shared/components/BooleanInput';
import { styles } from './styles';
import styled from 'styled-components'
import { Select, Checkbox } from 'antd';
import { BrandingWatermarkSharp } from '@material-ui/icons';
const image2base64 = require('image-to-base64');
const upload = `${process.env.PUBLIC_URL}/img/dashboard/upload.png`;
const trash = `${process.env.PUBLIC_URL}/img/dashboard/clear.png`;
const { Option } = Select;
const defaultState = {
autoDisplay: false,
items: [],
links: [],
banners: [],
locked: true,
isLoading: false,
language: 'EN'
}
const labelStyle = {
fontFamily: "Poppins",
fontSize: 16,
color: "#646777",
padding: 10
}
const Text = styled.span`
font-family: Poppins;
font-size: 13px;
`;
class Banners extends Component {
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
onAddedFile = async (files) => {
const file = files[0];
let blob = await image2base64(file.preview) // you can also to use url
const banner = {
image_url : blob,
link_url : '',
button_text : '',
title : '',
subtitle : ''
}
this.setState({ banners : this.state.banners.concat([banner]) });
}
projectData = async (props) => {
const { language } = this.state;
await this.fetchLanguageData(language);
}
fetchLanguageData = async (language) => {
const { banners } = this.props.profile.getApp().getCustomization();
const banner = banners.languages.find(l => l.language.prefix === language);
const languages = banners.languages.map(l => l.language);
const { ids, autoDisplay, fullWidth, useStandardLanguage } = banner;
this.setState({...this.state,
language,
languages: languages,
useStandardLanguage,
banners : ids,
autoDisplay,
fullWidth: fullWidth
})
}
renderAddImage = () => {
return(
<div className='dropzone-image'>
<Dropzone onDrop={this.onAddedFile} width='100%' ref={(el) => (this.dropzoneRef = el)} disabled={this.state.locked}>
<img src={upload} className='image-info' style={{marginTop : 50}}/>
<p className='text-center'> Drop the Banner here</p>
</Dropzone>
</div>
)
}
removeImage = (src, index) => {
let banners = this.state.banners;
banners.splice(index, 1);
this.setState({ banners });
}
getLanguageImage = language => (
<div style={{ display: "flex", justifyContent: "flex-start", alignItems: "center" }}>
<img src={language.logo} alt={language.logo} style={{ height: 20, width: 20, margin: "0px 5px" }}/>
<Text>{language.name}</Text>
</div>
)
renderImage = (src, index) => {
const banners = this.state.banners;
const link_url = banners[index].link_url;
const button_text = banners[index].button_text;
const title = banners[index].title;
const subtitle = banners[index].subtitle;
if(!src.includes("https")){
src = "data:image;base64," + src;
}
return (
<div style={{paddingBottom : 20, width: '100%', height : 240, margin : 'auto'}}>
<button disabled={this.state.locked} onClick={() => this.removeImage(src, index)}
className='carousel-trash button-hover'
style={{right: 25, top: 3, position: 'relative'}}>
<img src={trash} style={{width : 15, height : 15}}/>
</button>
<img src={src} onDragStart={this.handleOnDragStart} style={{height : '100%'}}/>
<div style={{marginTop : 36}}>
<TextInput
name="link_url"
label="Link URL"
type="text"
value={link_url}
defaultValue={link_url}
disabled={this.state.locked}
index={index}
changeContent={(name, value, index) => this.onChange({name, value, index})}
/>
</div>
<div style={{marginTop : 10}}>
<TextInput
name="button_text"
label="URL Button Text"
type="text"
value={button_text}
defaultValue={button_text}
disabled={this.state.locked}
index={index}
changeContent={(name, value, index) => this.onChange({name, value, index})}
/>
</div>
<div style={{marginTop : 10}}>
<TextInput
name="title"
label="Title"
type="text"
value={title}
defaultValue={title}
disabled={this.state.locked}
index={index}
changeContent={(name, value, index) => this.onChange({name, value, index})}
/>
</div>
<div style={{ marginTop: 10 }}>
<TextInput
name="subtitle"
label="Subtitle"
type="text"
value={subtitle}
defaultValue={subtitle}
disabled={this.state.locked}
index={index}
changeContent={(name, value, index) => this.onChange({name, value, index})}
/>
</div>
</div>
)
}
onChange = ({name, value, index}) => {
let banners = this.state.banners;
switch(name){
case 'link_url' : {
banners[index].link_url = value;
break;
};
case 'button_text' : {
banners[index].button_text = value;
break;
};
case 'title' : {
banners[index].title = value;
break;
};
case 'subtitle' : {
banners[index].subtitle = value;
break;
}
}
this.setState({...this.state, banners })
}
onChangeLanguage = async (value) => {
this.setState({
language: value ? value : ""
})
await this.fetchLanguageData(value)
}
unlockField = () => {
this.setState({...this.state, locked : false})
}
lockField = () => {
this.setState({...this.state, locked : true})
}
onChangeFullwidth = () => {
const { fullWidth } = this.state;
this.setState({ fullWidth: !fullWidth });
}
confirmChanges = async () => {
var { profile } = this.props;
const { banners, fullWidth, languages, language, useStandardLanguage } = this.state;
const lang = languages.find(l => l.prefix === language)
this.setState({...this.state, isLoading : true});
const postData = {
banners,
autoDisplay: false,
fullWidth: fullWidth,
language: lang._id,
useStandardLanguage
}
await profile.getApp().editBannersCustomization(postData);
this.setState({...this.state, isLoading : false, locked: true})
this.projectData(this.props);
}
handleOnDragStart = (e) => e.preventDefault()
render() {
const { isLoading, locked, autoDisplay, banners, fullWidth, languages, useStandardLanguage, language } = this.state;
const { classes } = this.props;
return (
<Card>
<CardBody style={{ margin: 10, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<Row>
<Col md={12} style={{ padding: 0 }}>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'announcementTab'}
locked={locked}
>
<FormLabel component="legend" style={labelStyle}>Language</FormLabel>
<div style={{ display: "flex", flexDirection: "row", justifyContent: "flex-start", alignItems: "center", margin: "5px 0px", marginTop: 20, padding: "0px 10px" }}>
<Select
defaultValue="EN"
style={{ minWidth: 130 }}
placeholder="Language"
onChange={this.onChangeLanguage}
disabled={isLoading || locked}
>
{ languages && languages.filter(language => language.isActivated).map(language => (
<Option key={language.prefix}>{this.getLanguageImage(language)}</Option>
))}
</Select>
{ language !== 'EN' && (
<Checkbox style={{ marginLeft: 10 }} disabled={isLoading || locked} checked={useStandardLanguage} onChange={() => this.setState({ useStandardLanguage: !useStandardLanguage})}>Use the English Language Setup</Checkbox>
)}
</div>
<br/>
<div style={{width : '96%', margin : 'auto'}}>
<div style={{ marginTop: 10 }}>
<FormLabel component="legend">Show full width banner</FormLabel>
<BooleanInput
checked={fullWidth === true}
onChange={this.onChangeFullwidth}
disabled={locked}
type={'isFullWidth'}
id={'fullwidth'}
/>
</div>
<div className={classes.root}>
<GridList className={classes.gridList} cols={2.5} style={{ minHeight: '410px' }}>
{banners.map((i, index) => {
return (
<div style={{border: '1px solid rgba(0, 0, 0, 0.2)', backgroundColor: "white", borderRadius: 8, height : 630, width: 300, margin: 20, padding : "0px 30px 30px 30px"}}>
{this.renderImage(i.image_url, index)}
</div>
)
})}
<div style={{ display: "flex", flexDirection: "column", justifyContent: "flex-start" }}>
<h4 style={{padding: 20, width: 200 }}>Add Banner</h4>
<div style={{border: '1px solid rgba(0, 0, 0, 0.2)', backgroundColor: "white", borderRadius: 8, height : 270, width: 230, margin: "0px 20px 20px 20px"}}>
{this.renderAddImage(banners.length)}
</div>
</div>
</GridList>
</div>
</div>
</EditLock>
</Col>
</Row>
</CardBody>
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(withStyles(styles)(Banners));
<file_sep>/src/lib/string.js
function AddressConcat(string){
return `${string.substring(0, 6)}...${string.substring(string.length - 2)}`;
}
function compareIDS(id1, id2){
return (new String(id1).toString().toLowerCase() == new String(id2).toString().toLowerCase());
}
export { AddressConcat, compareIDS }<file_sep>/src/controllers/Account.js
import ConnectionSingleton from "../api/Connection";
import store from "../containers/App/store";
import { setProfileInfo } from "../redux/actions/profile";
import { setCurrencyView } from '../redux/actions/currencyReducer';
import App from "./App";
import { processResponse } from "../lib/errors";
import { setAuthToCookies, getAuthFromCookies } from "./services/services";
import _ from 'lodash';
class Account{
constructor(params=null){
this.params = params;
this.date = null;
this.versionControl = 0;
}
getUserInfo = () => {
return this.User;
}
getId = () => this.User.id;
getBearerToken = () => {return this.User.security.bearerToken};
auth = async () => {
try{
let auth = getAuthFromCookies();
if(!auth){throw null /* No Login Info */}
const { admin, bearerToken } = auth;
let response = await ConnectionSingleton.auth({
admin,
headers : authHeaders(bearerToken, admin)
});
return await this.handleLoginResponse(response);
}catch(err){
console.log(err);
throw err
}
}
register = async (token = null) => {
try{
let data = {
username : this.params.username,
name : this.params.name,
password : <PASSWORD>,
email : this.params.email,
};
if(token !== null) {
data['bearerToken'] = token;
}
let response = await ConnectionSingleton.register(data);
let {
message,
status
} = response.data;
if(status == 200){
return await this.login();
}else{
throw new Error(message)
}
}catch(err){
throw err
}
}
login = async () => {
try{
let response = await ConnectionSingleton.login({
username : this.params.username,
password : <PASSWORD>
});
return await this.handleLoginResponse(response);
}catch(err){
// TO DO
throw err;
}
}
login2FA = async () => {
try{
let response = await ConnectionSingleton.login2FA({
username : this.params.username,
password : <PASSWORD>,
token : this.params.token
});
return await this.handleLoginResponse(response);
}catch(err){
// TO DO
throw err;
}
}
resetAdminPassword = async () => {
try{
await ConnectionSingleton.resetAdminPassword({
username_or_email: this.params.username_or_email
});
}catch(err){
throw err;
}
}
confirmResetAdminPassword = async () => {
try{
const res = await ConnectionSingleton.confirmResetAdminPassword({
token: this.params.token,
password: <PASSWORD>,
admin_id: this.params.adminId
});
return res;
}catch(err){
throw err;
}
}
setGameDataAsync = async () => {
await this.getApp().setGamesAsync();
await this.update();
}
getData = async () => {
await this.getAppStatistics();
await this.update();
}
hasApp = () => {
return (typeof this.App != 'undefined')
}
update = async () => {
/* Add Everything to the Redux State */
this.versionControl += 1;
await store.dispatch(setProfileInfo(this));
}
addAdmin = async ({email}) => {
try{
let res = await ConnectionSingleton.addAdmin({
params : {
email, app : this.getApp().getId(), admin: this.getUserInfo().id
},
headers : authHeaders(this.getUserInfo().security.bearerToken, this.getId())
})
return res;
}catch(err){
throw err;
}
}
editAdminType = async ({adminToModify, permission}) => {
try{
let res = await ConnectionSingleton.editAdminType({
params: {
adminToModify,
permission,
admin: this.getUserInfo().id
},
headers : authHeaders(this.getUserInfo().security.bearerToken, this.getId())
})
return res;
}catch(err){
throw err;
}
}
getAdminByApp = async () => {
try{
let res = await ConnectionSingleton.getAdminByApp({
params : {
app : this.getApp().getId(), admin: this.getUserInfo().id
},
headers : authHeaders(this.getUserInfo().security.bearerToken, this.getId())
})
return res.data.message;
}catch(err){
throw err;
}
}
addPaybearToken = async (paybearToken) => {
try{
let res = await this.getApp().addPaybearToken(paybearToken);
await this.update();
return res;
}catch(err){
throw err;
}
}
addServices = async (services) => {
try{
let res = await this.getApp().addServices(services);
await this.update();
return res;
}catch(err){
throw err;
}
}
getTransactions = async (filters) => {
try{
let res = await this.getApp().getTransactions(filters);
await this.update();
return res;
}catch(err){
throw err;
}
}
getAddress = () => {
return this.App.getManagerAddress();
}
getOwnerAddress = () => {
return this.App.getOwnerAddress();
}
hasAppStats = (type) => {
try{
if(!this.hasApp()){throw new Error('There is no App Attributed')}
let res = this.getApp().getSummaryData(type);
return res;
}
catch(err){
return false
}
}
setProfileData = (data) => {
this.User = data;
}
getProfileData = () => {
return this.User;
}
createApp = async (params) => {
try{
let res = await ConnectionSingleton.createApp({
...params,
admin_id : this.getProfileData().id
});
await this.login();
res = await this.getApp().deployApp();
const { virtual } = this.getApp().getParams();
if(virtual === true) {
let ecosystemCurrencies = await this.getApp().getEcosystemCurrencies();
ecosystemCurrencies = ecosystemCurrencies.filter(el => el != null && el.virtual === virtual);
if(ecosystemCurrencies) {
const currency = ecosystemCurrencies[0];
await this.getApp().addCurrencyWallet({ currency: currency });
}
}
await this.getApp().addServices([101, 201]);
await this.login();
return res;
}catch(err){
throw err;
}
}
setApp = (app) => {
this.App = new App(app);
}
getApp = () => {
return this.App;
}
getAppStatistics = async () => {
return await this.App.getSummary();
}
getUsername = () => {
return this.User.name;
}
getDepositReference = async (params) => {
// TO DO : Change App to the Entity Type coming from Login
try{
let response = await this.getApp().getDepositReference(params);
return processResponse(response);
}catch(err){
throw err;
}
}
getDepositInfo = async (params) => {
try{
let response = await this.getApp().getDepositInfo(params);
return processResponse(response);
}catch(err){
throw err;
}
}
requestWithdraw = async (params) => {
try{
let response = await this.getApp().requestWithdraw(params);
return processResponse(response);
}catch(err){
throw err;
}
}
finalizeWithdraw = async (params) => {
try{
let response = await this.getApp().finalizeWithdraw(params);
return processResponse(response);
}catch(err){
throw err;
}
}
getWithdraws = () => {
return this.getApp().getWithdraws() || [];
}
cancelWithdraw = async (params) => {
try{
let response = await this.getApp().cancelWithdraw(params);
return processResponse(response);
}catch(err){
throw err;
}
}
set2FA = async ({secret, token}) => {
try{
let res = await ConnectionSingleton.set2FA(
{
secret,
token,
admin : this.getId(),
headers : authHeaders(this.getBearerToken(), this.getId())
});
return processResponse(res);
}catch(err){
throw err;
}
}
withdraw = async (params) => {
try{
return await this.getApp().withdraw(params);
}catch(err){
throw err;
}
}
handleLoginResponse = async (response) => {
let {
message : data,
status
} = response.data;
if(status == 200){
/* SET Profile Data */
this.setProfileData(data);
setAuthToCookies({
admin : data.id,
bearerToken : data.security.bearerToken
});
/* SET APP */
// If App Already Exists for this User
if(data.app.id){
this.setApp(data.app);
/* GET APP Stats */
await this.getData();
}
/* SET CURRENCY */
if(!_.isEmpty(data.app.wallet)) {
const appUseVirtualCurrencies = data.app.virtual;
const wallet = data.app.wallet;
if (appUseVirtualCurrencies) {
const currency = wallet.find(currency => currency.price != null);
await store.dispatch(setCurrencyView(currency.currency));
} else {
const currency = wallet[0];
await store.dispatch(setCurrencyView(currency.currency));
}
}
this.update()
// TO DO : Create an Initial Screen to choose between Apps or a top Dropdown for it
return response;
}else{
throw response.data;
}
}
}
function authHeaders(bearerToken, id){
return {
"authorization" : "Bearer " + bearerToken,
"payload" : JSON.stringify({ id : id })
}
}
export default Account;<file_sep>/src/containers/Applications/ThirdParties/components/EmailTab.js
import React, { Component } from 'react'
import EditLock from '../../../Shared/EditLock.js';
import { Col, Row, Card, CardBody } from 'reactstrap';
import { connect } from "react-redux";
import { EditableTable } from '../../../../components/index.js';
import { throwUIError } from '../../../../lib/errors';
import { Actions, InputField } from './styles'
const defaultState = {
apiKey: '',
templateIds: [],
locked: true
}
const sendinblue = `${process.env.PUBLIC_URL}/img/landing/sendinblue.svg`;
class EmailTab extends Component {
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { locked } = this.state;
if (locked) {
const email = props.profile.getApp().getEmailIntegration();
const { apiKey, templateIds } = email;
this.setState({...this.state,
apiKey,
templateIds
});
}
}
handleChangeAPIKey = value => {
this.setState({ apiKey: value })
}
onChangeTemplates = async (new_data) => {
const newArray = new_data.map(a =>
a.template_id
? { ...a, template_id: parseInt(a.template_id) }
: a
);
this.setState({...this.state, templateIds : newArray });
}
unlockField = () => {
this.setState({...this.state, locked : false})
}
lockField = () => {
this.setState({...this.state, locked : true})
}
confirmChanges = async () => {
const { profile } = this.props;
const { apiKey, templateIds } = this.state;
var errorMessage = null;
try {
if(!apiKey){
errorMessage = "API Key is empty.";
}
let templateArr = templateIds.filter(n => n.template_id == null)
if(templateArr.length) {
errorMessage = "Template Id cannot be null.";
}
if(errorMessage){
return throwUIError(errorMessage);
}
this.setState({...this.state, isLoading : true});
await profile.getApp().editEmailIntegration(this.state);
this.setState({...this.state, isLoading : false, locked: true})
this.projectData(this.props);
} catch(err){
console.log(err);
throwUIError(err);
}
}
render() {
const { isLoading, locked, apiKey, templateIds } = this.state;
return (
<Card>
<CardBody style={{ margin: 10, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'emailTab'}
locked={locked}
>
<Row>
<Col md={12}>
<div>
<img style={{width : 150, marginTop : 10}} src={sendinblue}></img>
<p className="text-small text-left" style={{marginTop : 10}}><a href="https://www.sendinblue.com" target="_blank">https://www.sendinblue.com</a></p>
</div>
<Actions>
<p className="text-left secondary-text" style={{ margin: "15px 0px" }}> Add your credentials to integrate </p>
<p>API Key</p>
<InputField disabled={locked || isLoading} value={apiKey} onChange={(e) => this.handleChangeAPIKey(e.target.value)}/>
</Actions>
</Col>
</Row>
<Row>
<Col md={12} style={{ padding: 0, marginTop: 15 }}>
<div>
<EditableTable
title={''}
onChange={this.onChangeTemplates}
compareField={'functionName'}
columns={[
{ title: 'Contact List Id', field: 'contactlist_Id', type : 'numeric', editable : 'never' },
{ title: 'Function Name', field: 'functionName', type: 'string', editable : 'never' },
{ title: 'Template Id', field: 'template_id', type : 'numeric' }
]}
rawData={templateIds}
data={templateIds.map( v => {
return {
contactlist_Id: v.contactlist_Id,
functionName: v.functionName,
template_id: v.template_id
}
})}
isEditable={!locked}
enableDelete={false}
enableAdd={false}
/>
</div>
</Col>
</Row>
</EditLock>
</CardBody>
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(EmailTab);
<file_sep>/src/containers/Dashboards/Default/components/VisitorsSessions.jsx
/* eslint-disable react/no-array-index-key */
import React from 'react';
import { PieChart, Pie, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import Panel from '../../../../shared/components/Panel';
import DashboardMapperSingleton from '../../../../services/mappers/Dashboard';
import Numbers from '../../../../services/numbers';
import AnimationNumber from '../../../UI/Typography/components/AnimationNumber';
import Skeleton from '@material-ui/lab/Skeleton';
const data01 = [{ name: 'CoinFlip', value: 2034, fill: '#894798' },
{ name: 'Dice', value: 934, fill: '#70bbfd' },
{ name: 'Roulette', value: 2432, fill: '#f6da6e' },
{ name: 'Crash', value: 8432, fill: '#ff4861' }];
const style = {
left: 0,
width: 150,
lineHeight: '24px',
};
const renderLegend = ({ payload }) => (
<ul className="dashboard__chart-legend">
{
payload.map((entry, index) => (
<li key={`item-${index}`}><span style={{ backgroundColor: entry.color }} />{entry.value}</li>
))
}
</ul>
);
renderLegend.propTypes = {
payload: PropTypes.arrayOf(PropTypes.shape({
color: PropTypes.string,
vslue: PropTypes.string,
})).isRequired,
};
const defaultProps = {
data : {
bets : [0],
games : []
}
}
class VisitorsSessions extends React.Component{
constructor(props){
super(props)
this.state = { ...defaultProps};
this.projectData(props);
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { bets, users } = props.data;
if(bets.data.length > 0 && users.data.length > 0){
const allBets = getAllBets(users.data);
let amount = allBets.reduce((acc, game) => acc+game.betAmount, 0);
let data = {
betAmount : amount,
games : DashboardMapperSingleton.toPieChart(allBets)
}
this.setState({...this.state,
data : data ? data : defaultProps.data
})
} else {
this.setState({...this.state,
data: defaultProps.data
})
}
}
render = () => {
const { data } = this.state;
const { isLoading, periodicity } = this.props;
return (
<Panel
title={'Users´ Stats'}
subhead="What games are more popular?"
>
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-title"> Total Bets <span>{periodicity}</span> </p>
{isLoading ? (
<>
<Skeleton variant="rect" width={50} height={29} style={{ marginTop: 10, marginBottom: 10, marginRight: 'auto' }}/>
<Skeleton variant="rect" height={210} style={{ marginTop: 10, marginBottom: 5 }}/>
</>
) : (
<>
<p className="dashboard__visitors-chart-number"><AnimationNumber decimals={0} number={data.betAmount}/></p>
<ResponsiveContainer className="dashboard__chart-pie" width="100%" height={220}>
<PieChart className="dashboard__chart-pie-container">
<Tooltip />
<Pie data={data.games} dataKey="value" cy={110} innerRadius={70} outerRadius={100} />
<Legend layout="vertical" verticalAlign="bottom" wrapperStyle={style} content={renderLegend} />
</PieChart>
</ResponsiveContainer>
</>
)}
</div>
</Panel>
)
}
};
function getAllBets(users){
const betsOnPeriodicity = users.map(index => index.games);
const concatBets = [].concat(...betsOnPeriodicity);
const allBets = Object.values([...concatBets].reduce((acc, { _id, name, edge, betsAmount, betAmount, profit, fees }) => {
acc[_id] = { _id, name,
edge: (acc[_id] ? acc[_id].edge : 0) + edge,
betsAmount: (acc[_id] ? acc[_id].betsAmount : 0) + betsAmount,
betAmount: (acc[_id] ? acc[_id].betAmount : 0) + betAmount,
profit: (acc[_id] ? acc[_id].profit : 0) + profit,
fees: (acc[_id] ? acc[_id].fees : 0) + fees };
return acc;
}, {}));
return allBets;
}
VisitorsSessions.propTypes = {
t: PropTypes.func.isRequired,
};
export default translate('common')(VisitorsSessions);
<file_sep>/src/containers/Applications/ThirdParties/components/GameProvidersTab/AddProvider/styles.js
import styled from 'styled-components';
import { Button as MaterialButton } from "@material-ui/core";
export const AddProviderContainer = styled.div`
padding: 15px;
border-radius: 10px !important;
background-color: white;
border: solid 1px rgba(164, 161, 161, 0.35) !important;
box-shadow: none !important;
width: 100%;
`;
export const Header = styled.section`
display: grid;
grid-template-columns: 120px 1fr;
width: 100%;
`;
export const Logo = styled.section`
display: flex;
justify-content: center;
align-items: center;
width: 120px;
`;
export const Details = styled.section`
display: flex;
flex-direction: column;
justify-content: center;
align-items: flex-start;
padding: 8px 10px;
> span {
font-family: Poppins;
font-size: 20px;
}
`;
export const Actions = styled.section`
display: flex;
justify-content: flex-start;
padding: 15px 10px 0px 10px;
`;
export const AddButton = styled(MaterialButton)`
margin: 7px 0px !important;
width: 90px;
text-transform: none !important;
background-color: #63c965 !important;
box-shadow: none !important;
height: 30px !important;
color: white !important;
opacity: ${props => props.disabled ? 0.7 : 1};
font-size: 12px;
`;
<file_sep>/src/redux/actions/game.js
export const SET_GAME_VIEW = 'SET_GAME_VIEW';
export function setGameView(data) {
return {
type: SET_GAME_VIEW,
action : data
};
}
<file_sep>/src/containers/Landing/components/NewsLetter.jsx
import React from 'react';
import { Col, Row, Container } from 'reactstrap';
import CheckIcon from 'mdi-react/CheckIcon';
import TextInput from '../../../shared/components/TextInput';
import { EmailIcon } from 'mdi-react';
const back = `${process.env.PUBLIC_URL}/img/landing/back-3.png`;
const bpro = `${process.env.PUBLIC_URL}/img/landing/betprotocol-logo-white.png`;
class NewsLetter extends React.Component{
constructor(props){super(props); this.state = {}}
changeContent = (type, item) => {
this.setState({[type] : item});
}
render = () => {
return(
<section className="landing__section ">
<div className=''>
<img className="landing_3_back" src={back} />
</div>
<Container className='container__all__landing newsletter-section'>
<Row>
<Col lg={12}>
<h3 className="landing__section-title">Want to Know More?</h3>
<a href={'https://www.t.me/betprotocol'} target={'__blank'}
>
<button style={{width : 200, marginTop : 50}} className="btn btn-primary account__btn">
🦄 Join the Telegram
</button>
</a>
</Col>
</Row>
</Container>
</section>
)
}
}
export default NewsLetter;
<file_sep>/src/redux/actions/seriesActions.js
export const actions = Object.freeze({
SET_SERIES_DATA: "SET_SERIES_DATA"
})
const extractSeriesFromVideogames = data => {
let series = {};
data.forEach(videogame => {
series[videogame._id] = videogame.series.map(serie => serie.id);
});
return series;
}
export function setSeriesData(data) {
return {
type: actions.SET_SERIES_DATA,
payload: extractSeriesFromVideogames(data)
}
}<file_sep>/src/containers/Wallet/components/LiquidityWalletWidget.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col, Row } from 'reactstrap';
import AnimationNumber from '../../UI/Typography/components/AnimationNumber';
import { DirectionsIcon } from 'mdi-react';
import store from '../../App/store';
import { setWalletView } from '../../../redux/actions/walletReducer';
const defaultProps = {
ticker : 'N/A',
platformBlockchain : 'N/A',
totalLiquidity : 0,
isIntegrated : false,
image : ''
}
class LiquidityWalletWidget extends PureComponent {
constructor(props){
super(props);
this.state = { ...defaultProps};
this.projectData(props);
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
goToWalletView = async (wallet) => {
await store.dispatch(setWalletView(wallet));
this.props.history.push('/wallet/currency');
}
projectData = (props) => {
const { wallet } = props.data;
if(wallet._id){
this.setState({...this.state,
wallet,
totalLiquidity : wallet.playBalance ? wallet.playBalance : defaultProps.totalLiquidity,
ticker : wallet.currency.ticker ? wallet.currency.ticker : defaultProps.ticker,
platformBlockchain : wallet.currency.name ? wallet.currency.name: defaultProps.platformBlockchain,
platformAddressLink : wallet.link_url,
tokenAddress : wallet.bank_address ? `${wallet.bank_address.substring(0, 6)}...${wallet.bank_address.substring(wallet.bank_address.length - 2)}` : null,
isIntegrated : true,
image : wallet.currency.image
})
}
}
render() {
const { image, wallet } = this.state;
return (
<Col md={12} xl={12} lg={12} xs={12}>
<Card>
<button className='clean_button' onClick={ () => this.goToWalletView(wallet)}>
<CardBody className="dashboard__card-widget dashboard_borderTop">
<Row>
<Col lg={5}>
<img style={{borderRadius : 0, position: "initial"}} className="company-logo-card" src={image} alt="avatar" />
<div className="dashboard__visitors-chart" style={{ marginTop: 20}}>
<p className="dashboard__visitors-chart-title" style={{fontSize : 25}}> {this.state.ticker} </p>
</div>
</Col>
<Col lg={7}>
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-number-second" style={
{color : '#646777'}
}><AnimationNumber decimals={6} number={ this.state.totalLiquidity}/> <span> {this.state.ticker}</span></p>
</div>
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-title">{new String(this.state.platformBlockchain).toUpperCase()} <span> Available </span></p>
</div>
{
this.state.platformAddressLink ?
<a target={'__blank'} className='ethereum-address-a' href={this.state.platformAddressLink}>
<p className="ethereum-address-name"> <DirectionsIcon className='icon-ethereum-address' />{this.state.tokenAddress}</p>
</a>
:
<p className="ethereum-address-name"> <DirectionsIcon className='icon-ethereum-address' />{this.state.tokenAddress}</p>
}
</Col>
</Row>
</CardBody>
</button>
</Card>
</Col>
);
}
}
export default LiquidityWalletWidget;
<file_sep>/src/esports/services/book.js
import { API_URL, config, addHeaders } from '../api/config';
export const setBookedMatch = async ({ params, headers }) => {
try {
const response = await fetch(API_URL + `/api/set/matches/booked`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
} catch(err) {
throw err;
}
}
export const removeBookedMatch = async ({ params, headers }) => {
try {
const response = await fetch(API_URL + `/api/remove/matches/booked`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
} catch(err) {
throw err;
}
}<file_sep>/src/containers/Applications/LanguagesPage/index.js
import React from 'react';
import { translate } from 'react-i18next';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import LanguageStoreContainer from "./Language";
import { LockWrapper } from "../../../shared/components/LockWrapper";
import { Grid } from '@material-ui/core';
class LanguageStorePageContainer extends React.Component{
constructor(props){
super(props)
this.state = {
ecosystemLanguages: [],
appLanguages: []
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { profile } = props;
const ecosystemLanguages = await profile.getApp().getEcosystemLanguages();
const { languages } = profile.getApp().getCustomization();
this.setState({ ecosystemLanguages: ecosystemLanguages.data.message, appLanguages: languages });
}
addLanguage = async (prefix) => {
const { profile } = this.props;
await profile.getApp().addLanguage({ prefix: prefix });
await profile.getApp().updateAppInfoAsync();
await profile.update();
}
isAdded = (language) => {
const { appLanguages } = this.state;
return !!(appLanguages).find(k => language.toLowerCase().replace(/\s+/g, '').includes(k.name.toLowerCase()));
}
render() {
const { ecosystemLanguages } = this.state;
const { User } = this.props.profile;
const isSuperAdmin = User.permission.super_admin;
return (
<div>
<Grid container direction="row" justify="flex-start" alignItems="flex-start">
{ecosystemLanguages && ecosystemLanguages.map(language => {
return (
<Grid item style={{ margin: 15, marginTop: 0 }}>
<LockWrapper hasPermission={isSuperAdmin}>
<LanguageStoreContainer
language={language}
isAdded={this.isAdded(language.name)}
addLanguage={this.addLanguage}
/>
</LockWrapper>
</Grid>
)
})}
</Grid>
</div>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default compose(
translate('common'),
connect(mapStateToProps)
)(LanguageStorePageContainer);
<file_sep>/src/containers/Applications/EsportsPage/components/MatchTabCollapsed/styles.js
import styled from 'styled-components';
export const Container = styled.div`
width: 100%;
`;
export const Tab = styled.section`
width: 100%;
/* min-height: 58px; */
background-color: white;
display: flex;
flex-direction: column;
justify-content: center;
align-content: center;
`;
export const MatchIcon = styled.a`
cursor: pointer;
display: grid;
grid-template-areas:
'indicator game';
grid-template-columns: 3px auto;
margin: 5px 0px;
`;
export const Indicator = styled.section`
grid-area: indicator;
z-index: 10;
margin-left: -1px;
background-color: ${props => props.status === "finished" ? "#ED5565" : "white"};
border-radius: 4px 0 0 4px;
`;
export const Game = styled.section`
grid-area: game;
width: 37px;
height: 37px;
border-radius: 3px;
background-color: #ecf1f4;
display: flex;
justify-content: center;
align-items: center;
span {
font-family: Poppins;
font-size: 14px;
color: #333;
}
`;<file_sep>/src/containers/Applications/GameStore/Game/index.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col, Row, Button } from 'reactstrap';
import { AddIcon } from 'mdi-react';
import game_images from '../../components/game_images';
import { Grid } from '@material-ui/core';
import Skeleton from "@material-ui/lab/Skeleton";
import { connect } from "react-redux";
class GameStoreContainer extends PureComponent {
constructor() {
super();
this.state = {
activeIndex: 0,
};
}
onClick = async () => {
const { onClick, game } = this.props;
this.setState({...this.state, isLoading : true})
if(onClick){ await onClick(game) }
this.setState({...this.state, isLoading : false})
}
render() {
const { game, isAdded } = this.props;
const { isLoading } = this.state;
if(!game){return null}
const { name, description, image_url } = game;
const game_image = game_images[String(name).toLowerCase().replace(/ /g,"_")];
const image = game_image ? game_image : game_images.default;
return (
<Col md={12} xl={12} lg={12} xs={12} style={{ minWidth: 288, maxWidth: 415, height: 230 }}>
<Card className='game-container'>
<CardBody className="dashboard__card-widget" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<Row>
<Col lg={4} >
<img className='application__game__image' style={{display: 'block', height: 50, width: 50 }} src={image} alt={name}/>
</Col>
<Col lg={8} >
<div className="dashboard__visitors-chart text-left">
<p className="dashboard__visitors-chart-title text-left" style={{fontSize : 20}}> {name} </p>
<p className="text-left secondary-text"> {description} </p>
</div>
</Col>
</Row>
<Button disabled={isLoading || isAdded} style={{margin : 0, marginTop : 10}} className="icon" onClick={() => this.onClick()} >
{
isLoading ?
"Adding"
: isAdded ?
"Added"
:
<p><AddIcon className="deposit-icon"/> Add </p>
}
</Button>
</CardBody>
</Card>
</Col>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(GameStoreContainer);
<file_sep>/src/containers/Users/UserPage/components/UserBetsTable.js
import React from 'react';
import { connect } from "react-redux";
import { compose } from 'lodash/fp';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TablePagination from '@material-ui/core/TablePagination';
import TableRow from '@material-ui/core/TableRow';
import TableSortLabel from '@material-ui/core/TableSortLabel';
import Paper from '@material-ui/core/Paper';
import Tooltip from '@material-ui/core/Tooltip';
import moment from 'moment';
import UserBetsFilter from './UserBetsFilter';
import Skeleton from '@material-ui/lab/Skeleton';
import _ from 'lodash';
import { CSVLink } from "react-csv";
import { Button as MaterialButton } from "@material-ui/core";
import { export2JSON } from '../../../../utils/export2JSON';
import { TableIcon, JsonIcon } from 'mdi-react';
import BetContainer from '../../../../shared/components/BetContainer';
import CurrencyContainer from '../../../../shared/components/CurrencyContainer';
import GameContainer from '../../../../shared/components/GameContainer';
function getSorting(data, order, orderBy) {
const sortedData = _.orderBy(data, [orderBy], order)
.map(row => ({...row, creation_timestamp: moment(row.creation_timestamp).format("lll")}));
return sortedData;
}
const fromDatabasetoTable = (data, currencies, user, games ) => {
return data.map( (key) => {
const currency = currencies.find(currency => currency._id === key.currency);
const game = games.find(game => game._id === key.game);
return {
_id: key._id,
user: user,
currency: currency,
app: key.app,
game: game,
ticker: currency.ticker,
isJackpot: key.isJackpot,
isWon: key.isWon,
winAmount: key.winAmount,
betAmount: key.betAmount,
nonce: key.nonce,
fee: key.fee,
creation_timestamp: key.timestamp,
clientSeed: key.clientSeed,
serverSeed: key.serverSeed,
serverHashedSeed: key.serverHashedSeed
}
})
}
const rows = [
{
id: '_id',
label: 'Id',
numeric: true
},
{
id: 'currency',
label: 'Currency',
numeric: false
},
{
id: 'game',
label: 'Game',
numeric: true
},
{
id: 'isJackpot',
label: 'Jackpot',
numeric: true
},
{
id: 'isWon',
label: 'Won',
numeric: false
},
{
id: 'winAmount',
label: 'Win Amount',
numeric: true
},
{
id: 'betAmount',
label: 'Bet Amount',
numeric: true
},
{
id: 'fee',
label: 'Fee',
numeric: true
},
{
id: 'creation_timestamp',
label: 'Created At',
numeric: false
}
];
class EnhancedTableHead extends React.Component {
createSortHandler = property => event => {
this.props.onRequestSort(event, property);
};
render() {
const { order, orderBy } = this.props;
return (
<TableHead>
<TableRow>
{rows.map(
row => (
<TableCell
key={row.id}
rowSpan={2}
align={'left'}
padding={row.disablePadding ? 'none' : 'default'}
sortDirection={orderBy === row.id ? order : false}
>
<Tooltip
title="Sort"
placement={row.numeric ? 'bottom-end' : 'bottom-start'}
enterDelay={300}
>
<TableSortLabel
active={orderBy === row.id}
direction={order}
onClick={this.createSortHandler(row.id)}
>
{row.label}
</TableSortLabel>
</Tooltip>
</TableCell>
),
this,
)}
</TableRow>
</TableHead>
);
}
}
EnhancedTableHead.propTypes = {
numSelected: PropTypes.number.isRequired,
onRequestSort: PropTypes.func.isRequired,
onSelectAllClick: PropTypes.func.isRequired,
order: PropTypes.string.isRequired,
orderBy: PropTypes.string.isRequired,
rowCount: PropTypes.number.isRequired,
};
const styles = theme => ({
root: {
width: '100%',
marginTop: theme.spacing.unit * 3,
},
table: {
minWidth: 1020,
boxShadow : 'none'
},
tableWrapper: {
overflowX: 'auto',
},
});
class UserBetsTable extends React.Component {
constructor(props){
super(props)
this.state = {
order: 'asc',
orderBy: 'id',
selected: [],
data: [],
page: 0,
isLoading: false,
ticker : 'N/A',
rowsPerPage: 5,
lastFilter: null
};
}
componentDidMount(){
this.projectData(this.props)
}
projectData = async (props) => {
const { user } = props;
this.setLoading(true);
const app = await props.profile.getApp();
const appBets = await app.getUserBets({ user: user._id, filters: { size: 100 }});
const bets = appBets.data.message.list;
const currencies = app.params.currencies;
const games = app.params.games;
if (bets.length > 0) {
this.setState({...this.state,
data: fromDatabasetoTable(bets, currencies, user, games),
currencies: currencies,
user: user,
games: games
})
} else {
this.setState({...this.state,
data: [],
currencies: currencies,
users: user,
games: games
})
}
this.setLoading(false);
}
setLoading = (status) => {
this.setState(state => ({ isLoading: status }));
}
handleRequestSort = (event, property) => {
const orderBy = property;
let order = 'desc';
if (this.state.orderBy === property && this.state.order === 'desc') {
order = 'asc';
}
this.setState({ order, orderBy });
};
handleSelectAllClick = event => {
if (event.target.checked) {
this.setState(state => ({ selected: state.data.map(n => n.id) }));
return;
}
this.setState({ selected: [] });
};
handleClick = (event, id) => {
const { selected } = this.state;
const selectedIndex = selected.indexOf(id);
let newSelected = [];
if (selectedIndex === -1) {
newSelected = newSelected.concat(selected, id);
} else if (selectedIndex === 0) {
newSelected = newSelected.concat(selected.slice(1));
} else if (selectedIndex === selected.length - 1) {
newSelected = newSelected.concat(selected.slice(0, -1));
} else if (selectedIndex > 0) {
newSelected = newSelected.concat(
selected.slice(0, selectedIndex),
selected.slice(selectedIndex + 1),
);
}
this.setState({ selected: newSelected });
};
setData = async (data) => {
const { currencies, user, games } = this.state;
this.setState({...this.state,
data: fromDatabasetoTable(data, currencies, user, games),
page: 0
})
}
setFilter = (filter) => {
this.setState({ lastFilter: filter });
}
reset = async () => {
await this.projectData();
}
handleChangePage = async (event, page) => {
const { data, rowsPerPage, currencies, user, games, lastFilter } = this.state;
const { App } = this.props.profile;
if (page === Math.ceil(data.length / rowsPerPage)) {
this.setLoading(true);
const res = await App.getUserBets({ user: user._id,
filters: lastFilter ? {...lastFilter, offset: data.length }
: { size: 100, offset: data.length } });
const bets = res.data.message.list;
if (bets.length > 0) {
this.setState({
data: data.concat(fromDatabasetoTable(bets, currencies, user, games)),
page: page
})
}
this.setLoading(false);
} else {
this.setState({ page });
}
};
handleChangeRowsPerPage = event => {
this.setState({ rowsPerPage: event.target.value });
};
isSelected = id => this.state.selected.indexOf(id) !== -1;
render() {
const { classes } = this.props;
const { data, order, orderBy, selected, rowsPerPage, page } = this.state;
const emptyRows = rowsPerPage - Math.min(rowsPerPage, data.length - page * rowsPerPage);
const isLoading = this.state.isLoading;
const headers = [
{ label: "Id", key: "_id" },
{ label: "Currency", key: "currency" },
{ label: "Game", key: "game" },
{ label: "Jackpot", key: 'isJackpot'},
{ label: "Won", key: "isWon" },
{ label: "Win Amount", key: "winAmount" },
{ label: "Bet Amount", key: "betAmount" },
{ label: "Fee", key: "fee" },
{ label: "Created At", key: "createdAt" }
];
let csvData = [{}];
let jsonData = [];
if (!_.isEmpty(data)) {
csvData = data.map(row => ({...row,
game: row.game._id,
currency: row.currency.name,
isWon: row.isWon ? 'Yes' : 'No',
isJackpot: row.isJackpot ? 'Yes' : 'No',
createdAt: moment(row.creation_timestamp).format("lll")}));
jsonData = csvData.map(row => _.pick(row, ['_id', 'currency', 'game', 'isJackpot', 'isWon', 'winAmount', 'betAmount', 'fee', 'creation_timestamp']));
}
return (
<Paper elevation={0} className={classes.root} style={{ backgroundColor: "#fafcff", marginTop: 0 }}>
<div style={{ display: "flex", justifyContent: "flex-end"}}>
<CSVLink data={csvData} filename={"user_bets.csv"} headers={headers}>
<MaterialButton variant="contained" size="small" style={{ textTransform: "none", backgroundColor: "#008000", color: "#ffffff", boxShadow: "none", margin: 10}}>
<TableIcon style={{marginRight: 7}}/> CSV
</MaterialButton>
</CSVLink>
<MaterialButton onClick={() => export2JSON(jsonData, "user_bets")} variant="contained" size="small" style={{ textTransform: "none", boxShadow: "none", margin: 10}}>
<JsonIcon style={{marginRight: 7}}/> JSON
</MaterialButton>
</div>
<br/>
<br/>
<UserBetsFilter setData={this.setData} reset={this.reset} user={this.props.user} setFilter={this.setFilter} setLoading={this.setLoading} loading={this.state.isLoading}/>
{isLoading ? (
<>
<Skeleton variant="rect" height={30} style={{ marginTop: 10, marginBottom: 20 }}/>
{[...Array(rowsPerPage)].map((e, i) => <Skeleton variant="rect" height={50} style={{ marginTop: 10, marginBottom: 10 }}/>)}
</>
) : (
<div className={classes.tableWrapper}>
<Table elevation={0} className={classes.table} aria-labelledby="tableTitle">
<EnhancedTableHead
numSelected={selected.length}
order={order}
orderBy={orderBy}
onSelectAllClick={this.handleSelectAllClick}
onRequestSort={this.handleRequestSort}
rowCount={data.length}
/>
<TableBody>
{getSorting(data, order, orderBy)
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map(n => {
const isSelected = this.isSelected(n.id);
return (
<TableRow
hover
onClick={event => this.handleClick(event, n.id)}
role="checkbox"
style={{padding : 0}}
aria-checked={isSelected}
tabIndex={-1}
key={n._id}
selected={isSelected}
>
<TableCell align="left">
<BetContainer bet={n}>
<p className='text-small'>{n._id}</p>
</BetContainer>
</TableCell>
<TableCell align="left">
<CurrencyContainer id={n.currency._id}>
<div style={{display: 'flex'}}>
<img src={n.currency.image} style={{ width : 25, height : 25}}/>
<p className='text-small' style={{margin: 5, alignSelf: "center" }}>{n.currency.name}</p>
</div>
</CurrencyContainer>
</TableCell>
<TableCell align="left">
<GameContainer id={n.game._id}>
<div style={{display: 'flex'}}>
<img src={n.game.image_url} style={{ width : 50, height : 40 }}/>
<p className='text-small' style={{margin: 5, marginLeft: 0, alignSelf: "center"}}>{n.game.name}</p>
</div>
</GameContainer>
</TableCell>
<TableCell align="left"><p className='text-small'>{n.isJackpot ? <p className='text-small background-green text-white'>Yes</p> : <p className='text-small background-red text-white'>No</p>}</p></TableCell>
<TableCell align="left"><p className='text-small'>{n.isWon ? <p className='text-small background-green text-white'>Yes</p> : <p className='text-small background-red text-white'>No</p>}</p></TableCell>
<TableCell align="left"><p className='text-small'>{`${n.winAmount.toFixed(6)} ${n.ticker}`}</p></TableCell>
<TableCell align="left"><p className='text-small'>{`${n.betAmount.toFixed(6)} ${n.ticker}`}</p></TableCell>
<TableCell align="left"><p className='text-small'>{`${n.fee.toFixed(6)} ${n.ticker}`}</p></TableCell>
<TableCell align="left"><p className='text-small'>{n.creation_timestamp}</p></TableCell>
</TableRow>
);
})}
{emptyRows > 0 && (
<TableRow style={{ height: 49 * emptyRows }}>
<TableCell colSpan={6} />
</TableRow>
)}
</TableBody>
</Table>
</div>)}
<TablePagination
rowsPerPageOptions={[5, 10, 25]}
component="div"
count={data.length + rowsPerPage}
rowsPerPage={rowsPerPage}
page={page}
labelDisplayedRows={({ from, to, count }) => `${from}-${to > count - rowsPerPage ? count - rowsPerPage : to} of ${count - rowsPerPage}`}
backIconButtonProps={{
'aria-label': 'Previous Page',
}}
nextIconButtonProps={{
'aria-label': 'Next Page',
}}
onChangePage={this.handleChangePage}
onChangeRowsPerPage={this.handleChangeRowsPerPage}
/>
</Paper>
);
}
}
UserBetsTable.propTypes = {
classes: PropTypes.object.isRequired,
};
function mapStateToProps(state){
return {
profile : state.profile
};
}
export default compose(connect(mapStateToProps))( withStyles(styles)(UserBetsTable) );<file_sep>/src/containers/Applications/Customization/components/EsportsMainPage.js
import React, { Component } from 'react'
import EditLock from '../../../Shared/EditLock.js';
import { Col, Row, Card, CardBody } from 'reactstrap';
import { connect } from "react-redux";
import { TextField, InputLabel, EsportsNotEnable } from './styles';
import './styles.css';
const esports = `${process.env.PUBLIC_URL}/img/landing/sports_small.png`;
class EsportsMainPage extends Component {
constructor(props){
super(props);
this.state = {
isLoading: false,
locked: true
};
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { profile } = props;
const customization = await profile.getApp().getCustomization();
const { button_text, link_url, subtitle, title } = customization.esportsScrenner;
this.setState({
button_text,
link_url,
subtitle,
title
})
}
unlockField = () => {
this.setState({ locked: false })
}
lockField = () => {
this.setState({ locked: true })
}
onChangeLinkURL = value => {
this.setState({ link_url: value ? value : "" })
}
onChangeButtonText = value => {
this.setState({ button_text: value ? value : "" })
}
onChangeTitle = value => {
this.setState({ title: value ? value : "" })
}
onChangeSubtitle = value => {
this.setState({ subtitle: value ? value : "" })
}
confirmChanges = async () => {
const { profile }= this.props;
const { App } = profile;
const { link_url, button_text, title, subtitle } = this.state;
this.setState({ isLoading: true });
await App.editEsportsPageCustomization({
link_url: link_url ? link_url : "",
button_text: button_text ? button_text : "",
title: title ? title : "",
subtitle: subtitle ? subtitle : ""
});
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({ isLoading: false, locked: true });
}
render() {
const { isLoading, locked, link_url, button_text, title, subtitle } = this.state;
const { profile } = this.props;
const app = profile.getApp();
const hasEsports = app.hasEsportsPermission();
return (
<Card>
<CardBody style={{ margin: "0px 15px", borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<Row>
{ hasEsports ? (
<Col md={12}>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'EsportsMainPage'}
locked={locked}>
<InputLabel>Link URL</InputLabel>
<TextField placeholder="" disabled={locked} value={link_url} onChange={(e) => this.onChangeLinkURL(e.target.value)}/>
<InputLabel>Button Text</InputLabel>
<TextField placeholder="" disabled={locked} value={button_text} onChange={(e) => this.onChangeButtonText(e.target.value)}/>
<InputLabel>Title</InputLabel>
<TextField placeholder="" disabled={locked} value={title} onChange={(e) => this.onChangeTitle(e.target.value)}/>
<InputLabel>Subtitle</InputLabel>
<TextField placeholder="" disabled={locked} value={subtitle} onChange={(e) => this.onChangeSubtitle(e.target.value)}/>
</EditLock>
</Col>
) : (
<EsportsNotEnable> <img src={esports} alt="esports"/> <span>Esports is not currently enabled</span></EsportsNotEnable>
)}
</Row>
</CardBody>
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(EsportsMainPage);
<file_sep>/src/esports/services/index.js
import { getVideoGamesAll, getAllVideogames } from './videogames';
import { getSpecificMatch } from './match';
import { getSeriesMatches, getMatchesAll, getBookedMatches, getBookedSeriesMatches } from './matches';
import { setBookedMatch, removeBookedMatch } from './book';
import { getTeamStats, getPlayerStats } from './stats';
export {
getVideoGamesAll,
getAllVideogames,
getSpecificMatch,
getSeriesMatches,
getMatchesAll,
setBookedMatch,
removeBookedMatch,
getTeamStats,
getPlayerStats,
getBookedMatches,
getBookedSeriesMatches
}<file_sep>/src/containers/Applications/Customization/components/SubSections/styles.js
import styled from 'styled-components';
import { Input, InputGroupText, Label, CardBody, Row } from 'reactstrap';
import { Button } from 'react-bootstrap';
import { Button as MaterialButton } from '@material-ui/core';
export const Container = styled(CardBody)`
margin: 10px;
padding: 15px;
background-color: #fafcff !important;
border-radius: 10px;
border: solid 1px rgba(164, 161, 161, 0.35);
box-shadow: none !important;
`;
export const Text = styled.h4`
font-size: 16px;
`;
export const TabsList = styled(Row)``;
export const TabCard = styled.section`
width: 100%;
min-width: 178px;
height: 362px;
border-radius: 10px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #fafcff;
box-shadow: none;
padding: 15px;
`;
export const TabCardContent = styled.section`
display: flex;
flex-direction: column;
align-items: center;
h1 {
font-family: Poppins;
font-size: 20px;
}
span {
font-display: Poppins;
font-size: 14px;
}
`;
export const TabImage = styled.section`
height: 50%;
width: 60%;
padding: 5px;
border: solid 2px rgba(164, 161, 161, 0.35);
border-radius: 6px;
border-style: dashed;
margin-bottom: 10px;
`;
export const InputField = styled(Input)`
margin: 12px 0px;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #FFFFFF;
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
margin-top: 0px;
`;
export const InputLabel = styled(Label)`
font-size: 16px;
font-family: Poppins;
`;
export const InputAddOn = styled(InputGroupText)`
margin: 12px 0px;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #FFFFFF;
height: 35px;
border-right: none;
span {
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
margin-right: 10px;
}
`;
export const ConfirmButton = styled(Button)`
margin: 42px 0px;
margin-bottom: 10px;
height: 50px;
width: 100%;
border-radius: 6px;
background-color: #814c94;
&.btn.icon {
padding-top: 8px;
}
span {
font-family: Poppins;
font-size: 14px;
font-weight: 400;
color: #ffffff;
}
`;
export const RemoveTab = styled(MaterialButton)`
width: 100%;
text-transform: none !important;
background-color: #e6536e !important;
box-shadow: none !important;
height: 30px !important;
color: white !important;
`;
export const AddTabButton = styled(MaterialButton)`
width: 100%;
text-transform: none !important;
background-color: #63c965 !important;
box-shadow: none !important;
height: 30px !important;
color: white !important;
opacity: ${props => props.disabled ? 0.7 : 1};
`;
export const Yes = styled(MaterialButton)`
width: 30%;
text-transform: none !important;
background-color: #63c965 !important;
box-shadow: none !important;
height: 30px !important;
color: white !important;
margin: 0px 5px !important;
`;
export const Cancel = styled(MaterialButton)`
width: 30%;
text-transform: none !important;
background-color: #e6536e !important;
box-shadow: none !important;
height: 30px !important;
color: white !important;
margin: 0px 5px !important;
`;
export const CreateNewSubSection = styled(MaterialButton)`
width: 220px;
text-transform: none !important;
background-color: #63c965 !important;
box-shadow: none !important;
color: white !important;
margin: 0px 5px !important;
`;
export const Title = styled.h1`
font-family: Poppins;
font-size: 20px;
margin: 20px 0px;
`;
export const TabIcon = styled.div`
width: 30px;
margin: 0px 5px;
`;
export const TabTitle = styled.div`
height: 100%;
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
padding: 5px;
font-family: Poppins;
font-size: 16px;
font-weight: 500;
`;
export const Header = styled.section`
display: flex;
flex-direction: column;
padding: 10px;
> h1 {
font-family: Poppins;
font-size: 16px;
color: #212529;
font-weight: 500;
}
`;
export const Content = styled.section`
display: flex;
flex-direction: column;
padding: 10px;
> h1 {
font-family: Poppins;
font-size: 16px;
color: #212529;
font-weight: 500;
}
`;
export const SubSectionsList = styled.div``;<file_sep>/src/redux/actions/matchesActions.js
export const actions = Object.freeze({
SET_MATCHES_DATA: "SET_MATCHES_DATA",
ADD_MATCHES_DATA: "ADD_MATCHES_DATA",
UPDATE_MATCH_DATA: "UPDATE_MATCH_DATA"
})
export function setMatchesData(data) {
return {
type: actions.SET_MATCHES_DATA,
payload: data && typeof data !== 'string' ? data : []
}
}
export function addMatchesData(data) {
return {
type: actions.ADD_MATCHES_DATA,
payload: data && typeof data !== 'string' ? data : []
}
}
export function updateMatchData(data) {
return {
type: actions.UPDATE_MATCH_DATA,
payload: data && typeof data !== 'string' ? data : []
}
}<file_sep>/src/containers/Applications/Customization/components/SubSections/AddSection/styles.js
import styled from 'styled-components';
import { Button as MaterialButton } from '@material-ui/core';
export const Container = styled.div`
display: flex;
flex-direction: column;
width: 100%;
padding: 10px;
> h1 {
font-family: Poppins;
font-size: 18px;
}
`;
export const SectionGrid = styled.div`
position: relative;
display: grid;
height: 200px;
width: 100%;
max-height: 200px;
margin: 15px 0px;
background-color: ${props => props.backgroundColor ? props.backgroundColor : "black"};
border: solid 1px rgba(164, 161, 161, 0.35);
&.RightImage {
grid-template-areas:
'Title Image'
'Text Image';
grid-template-rows: 40% 60%;
grid-template-columns: 50% 50%;
}
&.LeftImage {
grid-template-areas:
'Image Title'
'Image Text';
grid-template-rows: 40% 60%;
grid-template-columns: 50% 50%;
}
&.TopImage {
grid-template-areas:
'Image'
'Title'
'Text';
grid-template-rows: 50% 20% 30%;
grid-template-columns: 100%;
}
&.BottomImage {
grid-template-areas:
'Title'
'Text'
'Image';
grid-template-rows: 20% 30% 50%;
grid-template-columns: 100%;
}
`;
export const BackgroundImage = styled.div`
grid-area: 1 / 1;
> img {
position: absolute;
}
`;
export const Title = styled.section`
grid-area: Title;
display: flex;
justify-content: center;
align-items: flex-start;
padding: 10px;
> h1 {
position: absolute;
z-index: 10;
color: white;
font-size: 26px;
font-weight: 500;
word-break: break-all;
}
`;
export const Text = styled.section`
grid-area: Text;
display: flex;
justify-content: center;
align-items: flex-start;
padding: 10px;
> p {
position: absolute;
z-index: 10;
color: white;
font-size: 18px;
font-weight: 500;
word-break: break-all;
}
`;
export const Image = styled.section`
grid-area: Image;
height: 100%;
width: 100%;
> img {
position: relative;
z-index: 10;
}
`;
export const DropzoneImage = styled.div`
height: 100%;
width: 100%;
border-radius: 6px;
`;
export const BackgroundItems = styled.section`
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
grid-gap: 25px;
`;
export const UploadButton = styled(MaterialButton)`
margin: 7px 0px !important;
text-transform: none !important;
background-color: #63c965 !important;
box-shadow: none !important;
color: white !important;
opacity: ${props => props.disabled ? 0.7 : 1};
`;
export const RemoveButton = styled(MaterialButton)`
margin: 7px 0px !important;
text-transform: none !important;
background-color: #e6536e !important;
box-shadow: none !important;
height: 30px !important;
color: white !important;
opacity: ${props => props.disabled ? 0.7 : 1};
`;
export const DialogHeader = styled.div`
display: flex;
justify-content: flex-end;
width: 100%;
padding: 20px 30px 0px 30px;
`;
export const ConfirmButton = styled(MaterialButton)`
margin: 7px 0px !important;
width: 220px;
text-transform: none !important;
background-color: #63c965 !important;
box-shadow: none !important;
color: white !important;
opacity: ${props => props.disabled ? 0.7 : 1};
`;
<file_sep>/src/containers/Layout/topbar/Topbar.jsx
import React, { PureComponent } from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import TopbarSidebarButton from './TopbarSidebarButton';
import TopbarProfile from './TopbarProfile';
import TopbarMail from './TopbarMail';
import TopbarNotification from './TopbarNotification';
import TopBarWithdrawNotice from './TopBarWithdrawNotice';
import TopbarSearch from './TopbarSearch';
import TopbarLanguage from './TopbarLanguage';
import TopBarCurrencyView from './TopBarCurrencyView';
import TopBarPeriodicity from './TopBarPeriodicity';
import TopBarMoneyType from './TopBarMoneyType';
import Tooltip from '@material-ui/core/Tooltip';
import { IconButton } from '@material-ui/core';
import { CheckCircleIcon, AlertCircleIcon } from 'mdi-react';
import _ from 'lodash';
import { AddressConcat } from '../../../lib/string';
import { connect } from "react-redux";
import { compose } from 'lodash/fp';
import TopbarRefresh from './TopbarRefresh';
const defaultProps = {
userAddress : 'N/A',
isValid : false
}
const text = {
false : 'This Address can´t make decisions in this App, Please change to the right Address',
true : 'You are running in your address, you can make changes :)'
}
class Topbar extends React.Component {
static propTypes = {
changeMobileSidebarVisibility: PropTypes.func.isRequired,
changeSidebarVisibility: PropTypes.func.isRequired,
};
constructor(props){
super(props);
this.state = {
...defaultProps
};
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
let user = !_.isEmpty(props.profile) ? props.profile : null ;
if(user){
let ownerAddress = user.getApp().getInformation('ownerAddress');
this.setState({...this.state,
userAddress : ownerAddress ? AddressConcat(ownerAddress) : defaultProps.userAddress
})
}
}
render() {
const { changeMobileSidebarVisibility, changeSidebarVisibility } = this.props;
return (
<div className="topbar">
<div className="topbar__wrapper">
<div className="topbar__left">
<TopbarSidebarButton
changeMobileSidebarVisibility={changeMobileSidebarVisibility}
changeSidebarVisibility={changeSidebarVisibility}
/>
</div>
<div className="topbar__right">
<TopbarRefresh/>
<TopBarMoneyType/>
<TopBarPeriodicity/>
<TopBarCurrencyView/>
<TopBarWithdrawNotice/>
<TopbarNotification />
<TopbarProfile />
{/* <TopbarLanguage /> */}
</div>
</div>
</div>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
Topbar.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
connect(mapStateToProps)
)(Topbar);
<file_sep>/src/containers/Wallet/WalletContainer.js
import React from 'react';
import { Container } from 'reactstrap';
import { connect } from "react-redux";
import TabsContainer from '../../shared/components/tabs/Tabs'
import CurrencyStore from './CurrencyStore';
import { Wallet, Cash } from '../../components/Icons';
import LiquidityWalletContainer from './components/LiquidityWalletContainer';
import _ from 'lodash';
class WalletContainer extends React.Component{
render = () => {
const { profile } = this.props;
const app = profile.getApp();
const wallets = app.params.wallet;
return (
<Container className="dashboard">
<TabsContainer
items={
[ {
title : 'My Wallet',
container : ( <LiquidityWalletContainer wallets={wallets} /> ),
icon : <Wallet/>,
disabled: _.isEmpty(wallets) },
{
title : 'Currency Store',
container : ( <CurrencyStore/> ),
icon : <Cash/> }
] }
/>
</Container>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(WalletContainer);
<file_sep>/src/containers/Applications/ThirdParties/components/GameProvidersTab/Provider/index.js
import React, { useState } from 'react';
import { ProviderContainer, Header, Actions, InputField} from '../styles';
import EditLock from '../../../../../Shared/EditLock';
import { FormLabel } from '@material-ui/core';
import BooleanInput from '../../../../../../shared/components/BooleanInput';
const labelStyle = {
fontFamily: "Poppins",
fontSize: 14,
color: "#646777"
}
const Provider = ({ data, editProvider }) => {
const { activated, api_key, api_url, logo, name, partner_id, _id } = data;
const [apiKey, setApikey] = useState(api_key);
const [partnerId, setPartnerId] = useState(partner_id);
const [isActivated, setIsActivated] = useState(activated);
const [locked, setLocked] = useState(true);
const [loading, setLoading] = useState(false);
async function handleEditProvider() {
setLoading(true);
await editProvider({
_id: _id,
api_key: apiKey ? apiKey : "",
partner_id: partnerId ? partnerId : "",
activated: isActivated
});
setLoading(false);
setLocked(true);
}
return (
<ProviderContainer>
<EditLock
isLoading={loading}
unlockField={() => setLocked(false)}
lockField={() => setLocked(true)}
confirmChanges={() => handleEditProvider()}
locked={locked}>
<Header>
<img src={logo} alt={name} />
<p className="text-small text-left" style={{ marginTop: 0 }}><a style={{ pointerEvents: locked || loading ? "none" : "unset" }} href={api_url} target="_blank">{api_url}</a></p>
</Header>
<hr/>
<Actions>
<div style={{ marginBottom: 10 }}>
<FormLabel component="legend" style={labelStyle}>{ isActivated ? "Active" : "Inactive" }</FormLabel>
<BooleanInput
checked={isActivated}
onChange={() => setIsActivated(!isActivated)}
disabled={locked || loading}
type={'isActivated'}
id={'isactivated'}
/>
</div>
<p>Add your API Key to integrate</p>
<InputField disabled={locked || loading} value={apiKey} onChange={(e) => setApikey(e.target.value)}/>
<p>Partner ID</p>
<InputField disabled={locked || loading} value={partnerId} onChange={(e) => setPartnerId(e.target.value)}/>
</Actions>
</EditLock>
</ProviderContainer>
)
};
export default Provider;<file_sep>/src/containers/HorizontalTabs/index.js
import React from 'react';
import { makeStyles, withStyles, useTheme } from '@material-ui/core/styles';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import SwipeableViews from 'react-swipeable-views';
import Box from '@material-ui/core/Box';
const AntTabs = withStyles({
root: {
borderBottom: '1px solid #894798',
},
indicator: {
backgroundColor: '#894798',
},
})(Tabs);
const StyledTabs = withStyles({
indicator: {
display: 'flex',
justifyContent: 'center',
backgroundColor: 'transparent',
'& > div': {
maxWidth: 40,
width: '100%',
backgroundColor: '#894798',
},
},
})(props => <Tabs {...props} TabIndicatorProps={{ children: <div /> }} />);
const StyledTab = withStyles(theme => ({
root: {
textTransform: 'none',
color: '#894798',
marginRight: theme.spacing(1),
'&:focus': {
opacity: 1,
},
},
}))(props => <Tab disableRipple {...props} />);
function TabPanel(props) {
const { children, value, index, padding, ...other } = props;
return (
<div
component="div"
role="tabpanel"
hidden={value !== index}
id={`full-width-tabpanel-${index}`}
aria-labelledby={`full-width-tab-${index}`}
{...other}
>
<Box p={3} style={{ padding: padding === false ? 0 : 24 }}>{children}</Box>
</div>
);
}
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
},
padding: {
padding: theme.spacing(3),
},
demo1: {
backgroundColor: "#fafcff",
},
demo2: {
backgroundColor: "#fafcff",
},
}));
export default function HorizontalTabs({tabs, padding}) {
const classes = useStyles();
const [value, setValue] = React.useState(0);
const theme = useTheme();
const handleChange = (event, newValue) => {
setValue(newValue);
};
const handleChangeIndex = index => {
setValue(index);
};
return (
<div className={classes.root} style={{ backgroundColor: "#fafcff" }}>
<div className={classes.demo2}>
<StyledTabs value={value} onChange={handleChange} aria-label="styled tabs example">
{tabs.map( t => <StyledTab label={t.label} />) }
</StyledTabs>
</div>
<SwipeableViews
axis={theme.direction === 'rtl' ? 'x-reverse' : 'x'}
index={value}
onChangeIndex={handleChangeIndex}
>
{tabs.map( (t, index) => {
return (
<TabPanel value={value} index={index} dir={theme.direction} padding={padding}>
{t.tab}
</TabPanel>
)
})}
</SwipeableViews>
</div>
);
}
<file_sep>/src/containers/Modals/Modal2FA.js
import React from 'react';
import { Col, Container, Row, Card, CardBody, Button } from 'reactstrap';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import _ from 'lodash';
import ModalContainer from './ModalContainer';
import store from '../App/store';
import { set2FA } from '../../redux/actions/set2FA';
import Security2FASingleton from '../../services/security/2FA';
import QRCode from 'qrcode.react';
import StepWizard from 'react-step-wizard';
import { throwUIError } from '../../lib/errors';
import Input2FA from '../Inputs/Input2FA';
const defaultState = {
auth_2fa : {},
SW : {}
}
class Modal2FA extends React.Component{
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
async closeModal(success=false){
await store.dispatch(set2FA({isActive : false, success}));
}
projectData = async (props) => {
const { profile } = props;
if(!profile || _.isEmpty(profile)){return}
if(!profile.getUserInfo()){return}
let auth_2fa = this.state.auth_2fa;
let params = profile.getUserInfo();
if(_.isEmpty(this.state.auth_2fa)){
let res = Security2FASingleton.generateSecret2FA({name : 'BetProtocol', account_id : params.id});
auth_2fa = {
uri : decodeURIComponent(res.uri),
secret : res.secret
}
}
this.setState({...this.state,
auth_2fa,
})
}
setInstance = SW => this.setState({ ...this.state, SW });
confirm = async ({token}) => {
const { secret, uri } = this.state.auth_2fa;
const { profile } = this.props;
try{
this.setState({...this.state, isLoading : true})
// Confirm it is verified Locally
let verified = Security2FASingleton.isVerifiedToken2FA({secret, token});
if(!verified){return throwUIError('Token is Wrong')}
// Send confirmation to Server Side
let res = await profile.set2FA({
secret,
token
})
console.log(res);
this.setState({...this.state, isLoading : false})
this.closeModal(true);
}catch(err){
console.log(err);
this.setState({...this.state, isLoading : false})
throwUIError(err);
}
}
render = () => {
const { isActive, isLoading } = this.props.set2FA;
const { auth_2fa, SW } = this.state;
if(!isActive){return null};
let { secret, uri } = auth_2fa;
return (
<ModalContainer onClose={this.closeModal} title={'2FA Authentication'}>
<StepWizard
instance={this.setInstance}
>
<FirstPage uri={uri} SW={SW}/>
<Input2FA isLoading={isLoading} secret={secret} SW={SW} confirm={this.confirm}/>
</StepWizard>
</ModalContainer>
)
}
}
class FirstPage extends React.Component{
constructor(props){
super(props);
this.state = {};
}
render = () => {
return (
<Container className="dashboard">
<QRCode value={this.props.uri} />
<h5 style={{marginTop : 20}}>Install Google Authenticator and Scan the Above QR Code</h5>
<div style={{marginTop : 20}}>
<Button color="primary" type="submit" onClick={this.props.SW.nextStep}>
Next
</Button>
</div>
</Container>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
set2FA : state.set2FA
};
}
Modal2FA.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(Modal2FA);
<file_sep>/src/containers/Dashboards/Default/components/LiquidityWalletWidget.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col, Row } from 'reactstrap';
import AnimationNumber from '../../../UI/Typography/components/AnimationNumber';
import { InformationIcon } from 'mdi-react';
import IconButton from '@material-ui/core/IconButton';
import Tooltip from '@material-ui/core/Tooltip';
import { compareIDS } from '../../../../lib/string';
import { emptyObject } from '../../../../lib/misc';
import {formatCurrency} from '../../../../utils/numberFormatation';
import Skeleton from '@material-ui/lab/Skeleton';
const Ava = `${process.env.PUBLIC_URL}/img/dashboard/euro.png`;
const defaultProps = {
playBalance : 0,
ticker : 'N/A',
decimals : 6
}
class LiquidityWalletWidget extends PureComponent {
constructor(props){
super(props);
this.state = { ...defaultProps};
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { currency } = props;
if(emptyObject(currency)){return null};
let wallets = props.data.data.wallet;
const wallet = wallets.find(w => compareIDS(w.currency._id, currency._id));
if(emptyObject(wallet)){return null};
this.setState({...this.state,
playBalance : wallet.playBalance ? wallet.playBalance : defaultProps.playBalance,
decimals : currency.decimals,
ticker : currency.ticker ? currency.ticker : defaultProps.ticker
})
}
render() {
const { isLoading } = this.props;
return (
<Col md={12} lg={12} xl={12}>
<Card style={{ minWidth: 200 }}>
<CardBody className="dashboard__card-widget dashboard_borderTop" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<Row>
<Col lg={4}>
<img style={{borderRadius : 0}} className="company-logo-card" src={Ava} alt="avatar" />
</Col>
<Col lg={8} style={{ minWidth: 160 }}>
{isLoading ? (
<Skeleton
variant="rect"
animation="wave"
height={29}
style={{ marginTop: 10, marginBottom: 10 }}/>
) : (
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-number-second" style={{color : '#646777'}}>
<AnimationNumber decimals={6} number={ formatCurrency(this.state.playBalance)}/>
<span> {this.state.ticker}</span>
</p>
</div>)}
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-title"> {this.state.ticker} <span> Available </span></p>
</div>
</Col>
</Row>
</CardBody>
</Card>
</Col>
);
}
}
export default LiquidityWalletWidget;
<file_sep>/src/containers/Settings/tabs/AddAdminContainer.js
import React from 'react';
import { Col, Container, Row } from 'reactstrap';
import { connect } from "react-redux";
import { EditableTable } from '../../../components';
import EditAdminButton from './EditAdminButton';
import { Tooltip } from '@material-ui/core';
import _ from 'lodash';
import { CSVLink } from "react-csv";
import { Button as MaterialButton } from "@material-ui/core";
import { export2JSON } from '../../../utils/export2JSON';
import { TableIcon, JsonIcon } from 'mdi-react';
const defaultProps = {
authorizedAddAdmin : [],
}
class AddAdminContainer extends React.Component{
constructor(props){
super(props)
this.state = defaultProps;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
let { profile } = props;
let list = (await profile.getAdminByApp()).reverse();
this.setState({...this.state, authorizedAddAdmin : list });
}
onChange = async (new_data) => {
const { profile } = this.props;
let data = new_data.filter(n => n.isNew === true)[0];
if(data) {
await profile.addAdmin({email: data.email });
} else {
console.log(new_data);
}
await profile.update();
}
renderEmail = (user) => {
const permissions = user.permission;
return (
<Tooltip title={`Customization: ${permissions.customization} |
Financials: ${permissions.financials} |
Withdraw: ${permissions.withdraw} |
User Withdraw: ${permissions.user_withdraw}`} placement="top">
<p>{user.email}</p>
</Tooltip>
)
}
render = () => {
const { authorizedAddAdmin } = this.state;
const filteredAdmins = authorizedAddAdmin.filter(admin => admin.hasOwnProperty("permission"));
const { profile } = this.props;
const headers = [
{ label: "Id", key: "id" },
{ label: "Name", key: "name" },
{ label: "Email", key: "email"},
{ label: "Type", key: "type" }
];
const csvData =filteredAdmins.map(row => ({...row, type: row.permission.super_admin ? 'Super admin' : 'Collaborator' }));
const jsonData = csvData.map(row => _.pick(row, ['id', 'name', 'email', 'type']));
return (
<div>
<h4> Application Admins </h4>
{/* <p className='text-grey'> Authorized Addresses have the ability to allow user withdraws, not to withdraw the bankroller money, that is only for the ownerAddress </p> */}
<hr></hr>
<Row>
<Col lg={12}>
<div style={{ display: "flex", justifyContent: "flex-end"}}>
<CSVLink data={csvData} filename={"admins.csv"} headers={headers}>
<MaterialButton variant="contained" size="small" style={{ textTransform: "none", backgroundColor: "#008000", color: "#ffffff", boxShadow: "none", margin: 10}}>
<TableIcon style={{marginRight: 7}}/> CSV
</MaterialButton>
</CSVLink>
<MaterialButton onClick={() => export2JSON(jsonData, "admins")} variant="contained" size="small" style={{ textTransform: "none", boxShadow: "none", margin: 10}}>
<JsonIcon style={{marginRight: 7}}/> JSON
</MaterialButton>
</div>
<EditableTable
title={''}
onChange={this.onChange}
compareField={'email'}
columns={[
{ title: 'Email', field: 'email'},
{ title: 'Status', field: 'status', editable : 'never'},
{ title: 'Type', field: 'adminType', editable : 'never'}
]}
rawData={filteredAdmins}
data={filteredAdmins.map( v => {
return {
email: this.renderEmail(v),
status: ((v.registered === true) ? 'Registered' : 'Pending'),
adminType: <EditAdminButton profile={profile} user={v}/>
}
})}
enableUpdate={false}
enableDelete={false}
/>
</Col>
</Row>
</div>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(AddAdminContainer);<file_sep>/src/containers/Applications/ThirdParties/components/GameProvidersTab/index.js
import React from 'react'
import { Card } from 'reactstrap';
import { CardBody, ProvidersList } from './styles';
import { connect } from "react-redux";
import _ from 'lodash';
import Provider from './Provider';
import AddProvider from './AddProvider';
class GameProvidersTab extends React.Component {
constructor(props){
super(props);
this.state = {
providers: [],
isLoading: false
};
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { profile } = props;
this.setState({ isLoading: true })
const response = await profile.getApp().getAllGameProviders();
const providers = response.data.message ? response.data.message : [];
this.setState({ providers: !_.isEmpty(providers) ? providers : [], isLoading: false })
}
isAdded = ({ _id }) => {
const { profile } = this.props;
const appGameProviders = profile.App.params.casino_providers ? profile.App.params.casino_providers : [];
const provider = appGameProviders.find(provider => provider.providerEco === _id);
return !_.isEmpty(provider);
}
addProvider = async ({ provider_id }) => {
const { profile } = this.props;
await profile.getApp().createProvider({ provider_id });
this.projectData(this.props);
}
editProvider = async ({ _id, api_key, activated, partner_id }) => {
const { profile } = this.props;
await profile.getApp().editProvider({
providerParams: {
_id: _id,
api_key: api_key,
activated: activated,
partner_id: partner_id
}
});
}
render() {
const { providers } = this.state;
const { profile } = this.props;
const appGameProviders = profile.App.params.casino_providers ? profile.App.params.casino_providers : [];
const providersToAdd = providers.filter(provider => !this.isAdded({ _id: provider._id }));
return (
<Card>
<CardBody>
{ _.isEmpty(providersToAdd) ? (
<h5 style={{ marginBottom: 20 }}>There are no new providers available or all have already been added</h5>
) : (
<>
<h5 style={{ marginBottom: 20 }}>Available game providers</h5>
<ProvidersList>
{ providersToAdd.map(provider => (
<AddProvider data={provider} addProvider={this.addProvider}/>
))}
</ProvidersList>
<br/>
</>
)}
<hr/>
<br/>
{ _.isEmpty(appGameProviders) ? (
<h5 style={{ marginBottom: 20 }}>You have no added providers currently</h5>
) : (
<>
<h5 style={{ marginBottom: 20 }}>Currently enabled game providers</h5>
<ProvidersList>
{ appGameProviders.map(provider => (
<Provider data={provider} editProvider={this.editProvider}/>
))}
</ProvidersList>
</>
)}
</CardBody>
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(GameProvidersTab);
<file_sep>/src/containers/Applications/Customization/components/Icons/index.js
import React, { Component } from 'react'
import { Col, Row, Card, CardBody, Label } from 'reactstrap';
import { connect } from "react-redux";
import styled from 'styled-components';
import { IconsList } from './styles'
import Icon from './Icon'
import AddIcon from './AddIcon'
import _ from 'lodash';
import EditLock from '../../../../Shared/EditLock';
import enumIcons from './enumIcons';
import { FormLabel } from '@material-ui/core';
import BooleanInput from '../../../../../shared/components/BooleanInput';
const cardStyle = {
margin: 10,
borderRadius: "10px",
border: "solid 1px rgba(164, 161, 161, 0.35)",
backgroundColor: "#fafcff",
boxShadow: "none"
}
const labelStyle = {
fontFamily: "Poppins",
fontSize: 16,
color: "#646777"
}
export const InputLabel = styled(Label)`
font-size: 16px;
font-family: Poppins;
`;
class IconsTab extends Component {
constructor(props){
super(props);
this.state = {
locked: true,
isLoading: false,
icons: []
};
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
const { locked } = this.state;
if (locked) {
this.projectData(props);
}
}
projectData = async (props) => {
const { profile } = props;
const app = await profile.getApp();
const { params } = app;
const icons = params.customization.icons.ids;
const icon_id = params.customization.icons._id;
this.setState({
useDefaultIcons: params.customization.icons.useDefaultIcons,
icons: !_.isEmpty(icons) ? icons.filter(icon => !_.isEmpty(icon.name) && !_.isEmpty(icon.link)) : [],
icon_id: icon_id
})
}
setIcons = ({ newIcons }) => {
this.setState({ icons: newIcons })
}
renderImage = (src) => {
if(!src.includes("https")){
src = "data:image;base64," + src;
}
return src;
}
confirmChanges = async () => {
const { icons, icon_id, useDefaultIcons } = this.state;
const { profile } = this.props;
const filteredIcons = icons.map(icon => ({
name: icon.name,
link: icon.link,
position: enumIcons.find(i => i.name === icon.name).position
}));
this.setState({ isLoading: true })
await profile.getApp().editIconsCustomization({ icon_id: icon_id, icons: filteredIcons, useDefaultIcons: useDefaultIcons });
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({
isLoading: false,
locked: true
})
}
onChange = ({ type, value }) => {
this.setState({ [type]: value })
}
unlockField = () => {
this.setState({ locked: false })
}
lockField = () => {
this.setState({ locked: true })
}
render() {
const { isLoading, locked, icons, useDefaultIcons } = this.state;
return (
<Card>
<CardBody style={cardStyle}>
<Row>
<Col md={12}>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'skinType'}
locked={locked}
>
<div style={{ marginBottom: 10 }}>
<FormLabel component="legend" style={labelStyle}>{ useDefaultIcons ? "Use default icons" : "Use custom icons" }</FormLabel>
<BooleanInput
checked={useDefaultIcons === true}
onChange={this.onChange}
disabled={locked}
type={'useDefaultIcons'}
id={'useDefaultIcons'}
/>
</div>
<hr/>
<IconsList>
<AddIcon icons={icons} setIcons={this.setIcons} locked={locked}/>
{ !_.isEmpty(icons) && icons.map(icon => (
<Icon icons={icons} icon={icon} setIcons={this.setIcons} locked={locked}/>
))}
</IconsList>
</EditLock>
</Col>
</Row>
</CardBody>
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(IconsTab);
<file_sep>/src/containers/Dashboards/Default/components/CompanyId/index.jsx
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody } from 'reactstrap';
import PropTypes from 'prop-types';
import { DirectionsIcon, EditIcon } from 'mdi-react';
import { emptyObject } from '../../../../../lib/misc';
import { compareIDS } from '../../../../../lib/string';
import { Container, AppDetails, Edit, EditButton, BankAddress } from './styles';
import EditDialog from './EditDialog';
import { connect } from 'react-redux';
const Ava = `${process.env.PUBLIC_URL}/img/dashboard/brand.jpg`;
const defaultProps = {
platformAddress : '',
platformName : 'N/A',
platformId : 'N/A',
platformDescription : 'N/A',
ticker : 'No Currency Chosen',
platformAddressLink : 'N/A'
}
class CompanyId extends PureComponent {
static propTypes = {
t: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { ...defaultProps, open: false };
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
let app = props.app;
const { currency } = props;
if(emptyObject(currency)){return null};
if(!props.data.wallet.data.wallet){return null}
let wallets = props.data.wallet.data.wallet;
const wallet = wallets.find( w => compareIDS(w.currency._id, currency._id));
const bank_address = wallet ? wallet.bank_address : null;
const link_url = wallet ? wallet.link_url : null;
this.setState({...this.state,
platformAddress : bank_address ? `${bank_address.substring(0, 6)}...${bank_address.substring(bank_address.length - 2)}` : defaultProps.platformAddress,
platformId : app.getId(),
ticker : currency.ticker ? currency.ticker : defaultProps.ticker,
currencyImage: currency.image ? currency.image : null,
platformDescription :app.getDescription() ? app.getDescription() : defaultProps.platformDescription,
platformAddressLink : link_url,
})
}
handleOpenDialog = () => {
this.setState({ open: true });
}
handleCloseDialog = () => {
this.setState({ open: false });
}
setAppInfo = ({ name, description }) => {
this.setState({
platformName: name,
platformDescription: description
})
}
render() {
let { app } = this.props;
const { profile } = this.props;
let { platformName } = this.state;
const { ticker, currencyImage, platformAddressLink, platformAddress, platformDescription, open } = this.state;
const isSuperAdmin = profile.User.permission.super_admin;
platformName = app.getName() ? app.getName() : platformName;
return (
<Card style={{ padding: "0px 15px", paddingBottom: 30 }}>
<CardBody className="dashboard__card-widget" style={{ minWidth: 250, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none", padding: 15 }}>
<Container>
<AppDetails>
<img className="company-logo-card" src={Ava} alt="avatar" />
<div className="name-and-description">
<h4 className={"bold-text dashboard__total-stat"} style={{ margin: 0, padding: 0 }}>{platformName}</h4>
<p className="dashboard__total-stat">{platformDescription}</p>
</div>
</AppDetails>
<BankAddress>
<div style={{ display: "flex", alignItems: "flex-end" }}>
{ platformAddressLink ?
<a target={'__blank'} className='ethereum-address-a' href={platformAddressLink}>
<p className="ethereum-address-name" style={{ padding: '0px 5px' }}> <DirectionsIcon className='icon-ethereum-address' />{platformAddress}</p>
</a>
:
<p className="ethereum-address-name" style={{ padding: '0px 5px' }}> <DirectionsIcon className='icon-ethereum-address' />{platformAddress}</p>
}
{ currencyImage && (
<img src={currencyImage} style={{ width: 20, height: 20, margin: "2px 5px"}}/>
)}
</div>
{ isSuperAdmin && (
<Edit>
<EditDialog open={open} handleCloseDialog={this.handleCloseDialog} setAppInfo={this.setAppInfo}/>
<EditButton style={{ margin: 0, marginTop: 10 }} onClick={() => this.handleOpenDialog()}>
<p style={{ color: "white", fontSize: 12 }}><EditIcon className="deposit-icon"/> Edit </p>
</EditButton>
</Edit>
)}
</BankAddress>
</Container>
</CardBody>
</Card>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(CompanyId);
<file_sep>/src/containers/Applications/Customization/components/Languages/Language.js
import React from 'react';
import { FormGroup, Col } from 'reactstrap';
import { LanguageCard, LanguageCardContent, InputField, LanguageImage, InputLabel } from './styles';
import _ from 'lodash';
import Dropzone from 'react-dropzone'
import EditLock from '../../../../Shared/EditLock';
import BooleanInput from '../../../../../shared/components/BooleanInput';
import { Divider } from '@material-ui/core';
import { connect } from 'react-redux';
const upload = `${process.env.PUBLIC_URL}/img/dashboard/upload.png`;
const trash = `${process.env.PUBLIC_URL}/img/dashboard/clear.png`;
const image2base64 = require('image-to-base64');
const dropzoneStyle = {
width: "100%",
height: "100%",
backgroundColor: "white"
};
class Language extends React.Component {
constructor(props){
super(props);
this.state = {
locked: true,
isLoading: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { language } = props;
if (!_.isEmpty(language)) {
this.setState({
isActivated: language.isActivated,
logo: language.logo,
name: language.name,
prefix: language.prefix,
_id: language._id
})
}
}
onAddedFile = async ({ files }) => {
const file = files[0];
this.setState({ isSVG: false })
if (file.type === 'image/svg+xml') {
this.setState({ isSVG: true })
}
let blob = await image2base64(file.preview) // you can also to use url
this.setState({
logo: blob
})
}
renderAddImage = () => {
const { locked } = this.props;
return(
<Dropzone disabled={locked} style={dropzoneStyle} onDrop={(files) => this.onAddedFile({ files: files })} ref={(el) => (this.dropzoneRef = el)}>
<img src={upload} className='image-info' style={{ height: 20, width: 20 }}/>
<p className='text-center'> Drop the image here</p>
</Dropzone>
)
}
renderImage = (src) => {
const { isSVG } = this.state;
if(!src.includes("https")){
src = isSVG ? "data:image/svg+xml;base64," + src : "data:image;base64," + src;
}
return src;
}
removeImage = () => {
this.setState({ logo: "" })
}
onChange = ({ type, value }) => {
this.setState({ [type]: value })
}
unlockField = () => {
this.setState({ locked: false})
}
lockField = () => {
this.setState({ locked: true})
}
confirmChanges = async () => {
const { profile } = this.props;
const { logo, isActivated, _id } = this.state;
if (_.isEmpty(logo)) {
this.setState({ locked: true })
this.projectData(this.props)
} else {
this.setState({ isLoading: true });
await profile.getApp().editLanguage({ logo: logo, isActivated: isActivated, language_id: _id });
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({ isLoading: false, locked: true });
}
}
render() {
const { isActivated, logo, name, prefix, locked, isLoading } = this.state;
return (
<>
<Col md={3} style={{ minWidth: 300, margin: 10 }}>
<LanguageCard>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'languages'}
locked={locked}
>
<LanguageCardContent>
{ !_.isEmpty(logo) ?
<>
<div style={{ display: "flex", justifyContent: "flex-end", width: "100%", marginTop: -10, marginBottom: -30 }}>
<button
disabled={locked}
onClick={() => this.removeImage()}
style={{ position: "inherit", right: 20, top: 6 }}
className='carousel-trash button-hover'>
<img src={trash} style={{width : 15, height : 15}}/>
</button>
</div>
<img className='application__game__image' style={{ display: 'block', width: 78, height: 78 }} src={this.renderImage(logo)}/>
</>
:
<LanguageImage>
{ this.renderAddImage() }
</LanguageImage> }
<div style={{ display: "flex", flexDirection: "column", marginBottom: 5, padding: 10, width: "100%" }}>
<InputLabel for="isActivated" style={{ paddingLeft: 10 }}>{ isActivated ? "Active" : "Inactive" }</InputLabel>
<BooleanInput
checked={isActivated === true}
onChange={this.onChange}
disabled={locked || prefix === "EN"}
type={'isActivated'}
id={'isActivated'}
/>
</div>
<Divider/>
<FormGroup style={{ marginBottom: 5 }}>
<InputLabel for="name">Name</InputLabel>
<InputField
label="Name"
name="name"
type="text"
defaultValue={name}
disabled={true}
/>
</FormGroup>
<FormGroup style={{ marginBottom: 5 }}>
<InputLabel for="prefix">Prefix</InputLabel>
<InputField
label="Prefix"
name="prefix"
type="text"
defaultValue={prefix}
disabled={true}
/>
</FormGroup>
</LanguageCardContent>
</EditLock>
</LanguageCard>
</Col>
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(Language);
<file_sep>/src/containers/Users/UserPage/styles.js
import styled from 'styled-components'
export const ConvertContainer = styled.div`
padding: 25px;
width: 300px;
`;
export const EsportsNotEnable = styled.div`
display: flex;
justify-content: flex-start;
align-items: center;
> div {
&.spanGroup {
display: flex;
flex-direction: column;
> span {
font-size: 17px;
font-weight: 500;
color: #814c94;
}
}
}
> img {
height: 70px;
width: 70px;
margin: 0px 10px;
}
`;<file_sep>/src/containers/Applications/Customization/components/Icons/AddIcon.js
import React from 'react';
import { FormGroup, Col } from 'reactstrap';
import { IconCard, IconCardContent, InputField, IconImage, InputLabel, AddIconButton } from './styles';
import _ from 'lodash';
import Dropzone from 'react-dropzone'
import { PlusIcon } from 'mdi-react';
import enumIcons from './enumIcons';
const upload = `${process.env.PUBLIC_URL}/img/dashboard/upload.png`;
const trash = `${process.env.PUBLIC_URL}/img/dashboard/clear.png`;
const image2base64 = require('image-to-base64');
const dropzoneStyle = {
width: "100%",
height: "100%",
backgroundColor: "white"
};
class AddIcon extends React.Component {
constructor(props){
super(props);
this.state = {
newName: enumIcons[0].name,
newLink: "",
isSVG: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { icons } = props;
if (!_.isEmpty(icons)) {
this.setState({
icons: icons
})
}
}
renderImage = (src) => {
const { isSVG } = this.state;
if(!src.includes("https")){
src = isSVG ? "data:image/svg+xml;base64," + src : "data:image;base64," + src;
}
return src;
}
onChangeNewName = ({ value }) => {
if (value) {
this.setState({
newName: value
})
} else {
this.setState({
newName: ""
})
}
}
onAddedNewFile = async ({ files }) => {
const file = files[0];
this.setState({ isSVG: false })
if (file.type === 'image/svg+xml') {
this.setState({ isSVG: true })
}
let blob = await image2base64(file.preview) // you can also to use url
this.setState({
newLink: blob
})
}
renderAddNewIcon = () => {
const { locked } = this.props;
return(
<Dropzone disabled={locked} style={dropzoneStyle} onDrop={(files) => this.onAddedNewFile({ files: files })} ref={(el) => (this.dropzoneRef = el)}>
<img src={upload} className='image-info' style={{ height: 20, width: 20 }}/>
<p className='text-center'> Drop the icon here</p>
</Dropzone>
)
}
removeNewIcon = () => {
this.setState({
newLink: ""
})
}
addNewIcon = () => {
const { newName, newLink, isSVG } = this.state;
const { setIcons, icons } = this.props;
const icon = enumIcons.find(icon => icon.name === newName);
const newIconObj = { _id: Math.random().toString(36).substr(2, 9), name: newName, link: newLink, position: icon.position, isSVG: isSVG };
const newIcons = icons ? [...icons, newIconObj] : [newIconObj];
const filteredIcons = _.without(enumIcons.filter(icon => !icons.map(i => i.name).includes(icon.name)), icon);
this.setState({
newName: filteredIcons[0] ? filteredIcons[0].name : undefined,
newLink: ""
})
setIcons({ newIcons: newIcons })
}
render() {
const { newName, newLink } = this.state;
const { locked, icons } = this.props;
const filteredIcons = _.without(enumIcons.filter(icon => !icons.map(i => i.name).includes(icon.name)), undefined);
if (_.isEmpty(filteredIcons)) return null
const hasEmptyValues = _.isEmpty(newName) || _.isEmpty(newLink);
return (
<>
<Col md={3} style={{ minWidth: 178, maxWidth: 230, padding: 0, margin: "10px 15px" }}>
<IconCard>
<IconCardContent>
{ newLink ?
<>
<div style={{ display: "flex", justifyContent: "flex-end", width: "100%", marginTop: -10, marginBottom: -30 }}>
<button
disabled={locked}
onClick={() => this.removeNewIcon()}
style={{ position: "inherit", right: 20, top: 6 }}
className='carousel-trash button-hover'>
<img src={trash} style={{width : 15, height : 15}}/>
</button>
</div>
<img className='application__game__image' style={{ display: 'block', width: 100, height: 100 }} src={this.renderImage(newLink)}/>
</>
:
<IconImage>
{ this.renderAddNewIcon() }
</IconImage> }
<br/>
<FormGroup style={{ width: "-webkit-fill-available" }}>
<InputLabel for="name">Name</InputLabel>
<InputField
label="Name"
name="name"
type="select"
value={newName}
disabled={locked}
onChange={(e) => this.onChangeNewName({ value: e.target.value })}
>
{ _.sortBy(filteredIcons, ['name']).map(icon => (
<option key={icon.name}>{icon.name}</option>
))}
</InputField>
</FormGroup>
<AddIconButton disabled={locked || hasEmptyValues} onClick={() => this.addNewIcon()}>
<PlusIcon/> Add icon
</AddIconButton>
</IconCardContent>
</IconCard>
</Col>
</>
)
}
}
export default AddIcon;
<file_sep>/src/containers/Bets/components/UserBetsFilter.js
import React, { Component } from 'react'
import { Formik, Form } from 'formik';
import TextField from '@material-ui/core/TextField';
import { List, ExpansionPanel, ExpansionPanelSummary, ExpansionPanelDetails, ClickAwayListener, Select, MenuItem } from '@material-ui/core';
import { Button as MaterialButton } from '@material-ui/core';
import { Button, Col } from 'react-bootstrap';
import { ExpandMoreIcon } from 'mdi-react';
import { compose } from 'recompose';
import { connect } from 'react-redux';
import _ from 'lodash';
class UserBetsFilter extends Component {
constructor(props){
super(props)
this.state = {
loading: false,
currencies: [],
open: false
}
}
componentDidMount(){
this.projectData(this.props);
}
projectData = async(props) => {
const { profile } = props;
let app = await profile.getApp();
const currencies = app.params.currencies;
const users = app.params.users;
const games = app.params.games;
this.setState(state => ({
currencies: currencies,
users: users,
games: games
}));
}
setLoadingStatus = (status) => {
this.setState(state => ({ loading: status }));
}
getCurrency = (ticker) => {
const currencies = this.state.currencies;
const currency = currencies.find(currency => currency.ticker === ticker.toUpperCase());
if (currency) {
return currency._id;
} else {
return null
}
}
getUser = (name) => {
const users = this.state.users;
const user = users.find(user => user.name.toLowerCase().includes(name.toLowerCase()));
if (user) {
return user._id;
} else {
return name;
}
}
getGame = (name) => {
const games = this.state.games;
const game = games.find(game => game.name.toLowerCase().includes(name.toLowerCase()));
if (game) {
return game._id;
} else {
return null
}
}
handleData = async (data) => {
const { setLoading, setData, setFilter, profile } = this.props;
if (data.size && data.size > 200) {
data.size = 200;
}
const formData = Object.assign({}, data);
this.setLoadingStatus(true);
setLoading(true);
formData.currency = formData.currency ? this.getCurrency(formData.currency) : null;
formData.user = formData.user ? this.getUser(formData.user) : null;
formData.game = formData.game ? this.getGame(formData.game) : null;
const filters = _.pickBy(formData, _.identity);
setFilter(filters);
const appBets = await profile.getApp().getAllBets({ filters: {...filters, isJackpot: false } });
const bets = appBets.data.message.list;
if (bets.length > 0) {
setData(bets);
} else {
setData([]);
}
this.setLoadingStatus(false);
setLoading(false);
}
clear = async (resetForm) => {
const { setLoading, setData, setFilter, profile } = this.props;
resetForm({});
setFilter(null);
setLoading(true);
const app = await profile.getApp();
const appBets = await app.getAllBets({ filters: { size: 100, isJackpot: false }});
const bets = appBets.data.message.list;
if (bets.length > 0) {
setData(bets);
} else {
setData([]);
}
setLoading(false);
}
handleClickAway = () => {
this.setState({ open: false });
};
render() {
const { open, loading, currencies, games } = this.state;
if (!currencies || !games) return null
return (
<div style={{display: 'flex', width: '100%', justifyContent: 'flex-end', paddingBottom: 20}}>
<ClickAwayListener onClickAway={this.handleClickAway}>
<ExpansionPanel elevation={0} expanded={open} style={{position: 'absolute', zIndex: 10, marginTop: -40, width: 300, border: '1px solid rgba(0, 0, 0, 0.2)'}}>
<ExpansionPanelSummary
onClick={() => this.setState({ open: !open })}
expandIcon={<ExpandMoreIcon/>}
aria-controls="filters"
id="filter-head"
>
<h6>Show filters</h6>
</ExpansionPanelSummary>
<ExpansionPanelDetails style={{paddingBottom: 0, width: 300}}>
<Col style={{padding: 0}}>
<Formik
initialValues={{
bet: "",
user: "",
currency: "Currency",
game: "Game",
size: 100
}}
onSubmit={data => this.handleData(data)}
>
{({ handleChange, handleSubmit, resetForm, values }) => (
<>
<div style={{display: 'flex', width: '100%', justifyContent: 'flex-end'}}>
<MaterialButton size="small" variant="outlined"
style={{ marginLeft: 0, marginTop: 5, marginBottom: 5, alignSelf: 'end', textTransform: 'none' }}
onClick={() => this.clear(resetForm)}
>
Clear
</MaterialButton>
</div>
<Form onSubmit={handleSubmit}>
<List style={{width: 250, paddingTop: 0}}>
<List item key="bet">
<TextField
id="bet"
name="bet"
type="text"
placeholder="Bet Id"
onChange={handleChange}
value={values.bet}
fullWidth
/>
</List>
<List item key="user">
<TextField
id="user"
name="user"
type="text"
placeholder="User"
onChange={handleChange}
value={values.user}
fullWidth
/>
</List>
<List item key="currency">
<Select
labelId="currency"
id="currency"
value={values.currency}
onChange={handleChange("currency")}
placeholder="Currency"
fullWidth
MenuProps={{ disablePortal: true }}
>
<MenuItem value="Currency">
Currency
</MenuItem>
{ currencies.map(currency => (
<MenuItem value={currency.ticker}>{currency.ticker}</MenuItem>
))}
</Select>
</List>
<List item key="game">
<Select
labelId="game"
id="game"
value={values.game}
onChange={handleChange("game")}
placeholder="Game"
fullWidth
MenuProps={{ disablePortal: true }}
>
<MenuItem value="Game">
Game
</MenuItem>
{ games.map(game => (
<MenuItem value={game.name}>{game.name}</MenuItem>
))}
</Select>
</List>
<List item key="size">
<TextField
id="size"
name="size"
type="number"
placeholder="Size"
onChange={handleChange}
value={values.size}
fullWidth
/>
</List>
<div style={{display: 'flex', width: '100%', justifyContent: 'center'}}>
<Button disabled={loading} className="icon" size="sm" style={{ height: 40, marginLeft: 0, marginTop: 5, marginBottom: 5, alignSelf: 'end' }} onClick={handleSubmit}>
{loading ? 'Searching...' : 'Search'}
</Button>
</div>
</List>
</Form>
</>
)}
</Formik>
</Col>
</ExpansionPanelDetails>
</ExpansionPanel>
</ClickAwayListener>
</div>
)
}
}
function mapStateToProps(state){
return {
profile : state.profile
};
}
export default compose(connect(mapStateToProps))(UserBetsFilter);<file_sep>/src/containers/Wallet/components/paths/components/QRCode.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col, Row , Button} from 'reactstrap';
var QRCode = require('qrcode.react');
class QRCodeContainer extends PureComponent {
constructor() {
super();
this.state = {
activeIndex: 0,
};
}
handleClick = (index) => {
this.setState({
activeIndex: index,
});
};
render() {
return (
<Col md={12} xl={12} lg={12} xs={12}>
<Card style={{margin : 'auto'}}>
<QRCode style={{margin : 'auto'}} value={this.props.value} size={128} bgColor={'#ffffff'} fgColor={'#000000'} />
</Card>
</Col>
);
}
}
export default QRCodeContainer;
<file_sep>/src/containers/Applications/Customization/components/Tabs/index.js
import React, { Component } from 'react'
import EditLock from '../../../../Shared/EditLock.js';
import { connect } from "react-redux";
import _ from 'lodash';
import './styles.css';
import { Container, TabsPreview, Text, TabsList, TabPreview, TabIcon, TabTitle } from './styles';
import AddTab from './AddTab.js';
import Tab from './Tab.js';
import { ButtonBase, FormLabel } from '@material-ui/core';
import BooleanInput from '../../../../../shared/components/BooleanInput.js';
import { Select, Checkbox } from 'antd';
import styled from 'styled-components'
const { Option } = Select;
const labelStyle = {
fontFamily: "Poppins",
fontSize: 16,
color: "#646777"
}
const TextImage = styled.span`
font-family: Poppins;
font-size: 13px;
`;
class Tabs extends Component {
constructor(props){
super(props);
this.state = {
isLoading: false,
locked: true,
language: 'EN'
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { language } = this.state;
await this.fetchLanguageData(language)
}
fetchLanguageData = async (language) => {
const { profile } = this.props;
const customization = await profile.getApp().getCustomization();
const { topTab } = customization;
const languages = topTab.languages.map(l => l.language);
const tab = topTab.languages.find(l => l.language.prefix === language);
const { ids, isTransparent, useStandardLanguage } = tab;
this.setState({
language,
languages,
useStandardLanguage,
tabs: !_.isEmpty(ids) ? ids : [],
isTransparent: isTransparent
})
}
setTabs = ({ newTabs }) => {
this.setState({
tabs: newTabs
})
}
getLanguageImage = language => (
<div style={{ display: "flex", justifyContent: "flex-start", alignItems: "center" }}>
<img src={language.logo} alt={language.logo} style={{ height: 20, width: 20, margin: "0px 5px" }}/>
<TextImage>{language.name}</TextImage>
</div>
)
onChangeLanguage = async (value) => {
this.setState({
language: value ? value : ""
})
await this.fetchLanguageData(value)
}
renderImage = (src) => {
if(!src.includes("https")){
src = "data:image;base64," + src;
}
return src;
}
confirmChanges = async () => {
const { tabs, isTransparent, languages, language, useStandardLanguage } = this.state;
const { profile } = this.props;
const filteredTabs = tabs.map(({_id, ...rest}) => rest);
const lang = languages.find(l => l.prefix === language)
this.setState({
isLoading: true
})
await profile.getApp().editTopTabCustomization({ topTabParams: filteredTabs, isTransparent: isTransparent, language: lang._id, useStandardLanguage });
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({
isLoading: false,
locked: true
})
}
unlockField = () => {
this.setState({
locked: false
})
}
lockField = () => {
this.setState({
locked: true
})
}
onChange = ({ type, value }) => {
this.setState({ [type]: value })
}
render() {
const { isLoading, locked, tabs, isTransparent, languages, useStandardLanguage, language } = this.state;
return (
<Container>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
locked={locked}>
<FormLabel component="legend" style={labelStyle}>Language</FormLabel>
<div style={{ display: "flex", flexDirection: "row", justifyContent: "flex-start", alignItems: "center", margin: "5px 0px", marginTop: 20 }}>
<Select
defaultValue="EN"
style={{ minWidth: 130 }}
placeholder="Language"
onChange={this.onChangeLanguage}
disabled={isLoading || locked}
>
{ languages && languages.filter(language => language.isActivated).map(language => (
<Option key={language.prefix}>{this.getLanguageImage(language)}</Option>
))}
</Select>
{ language !== 'EN' && (
<Checkbox style={{ marginLeft: 10 }} disabled={isLoading || locked} checked={useStandardLanguage} onChange={() => this.setState({ useStandardLanguage: !useStandardLanguage})}>Use the English Language Setup</Checkbox>
)}
</div>
<br/>
<div style={{ margin: "10px 0px" }}>
<FormLabel component="legend" style={labelStyle}>{ `Style (${isTransparent ? "Transparent" : "Normal"})` }</FormLabel>
<BooleanInput
checked={isTransparent === true}
onChange={this.onChange}
disabled={locked}
type={'isTransparent'}
id={'istransparent'}
/>
</div>
<Text>Preview</Text>
<TabsPreview hasTabs={!_.isEmpty(tabs)} locked={locked}>
{ !_.isEmpty(tabs) ? tabs.map(tab => (
<ButtonBase>
<TabPreview target="_blank" href={tab.link_url}>
<TabIcon>
{ !_.isEmpty(tab.icon) ? <img src={this.renderImage(tab.icon)} alt="icon" /> : null }
</TabIcon>
<TabTitle>
{ tab.name }
</TabTitle>
</TabPreview>
</ButtonBase>
)) : <span>First, add a tab to show preview</span>}
</TabsPreview>
<br/>
<br/>
<TabsList>
<AddTab tabs={tabs} setTabs={this.setTabs} locked={locked}/>
{ !_.isEmpty(tabs) && tabs.map(tab => (
<Tab tabs={tabs} tab={tab} setTabs={this.setTabs} locked={locked}/>
))}
</TabsList>
</EditLock>
</Container>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(Tabs);
<file_sep>/src/shared/components/CurrencyContainer/index.js
import React from 'react';
import { connect } from "react-redux";
import { ButtonBase, Dialog, DialogContent, Button } from '@material-ui/core';
import { Row, Col } from 'reactstrap';
import _ from 'lodash';
import { Link } from 'react-router-dom';
import AnimationNumber from '../../../containers/UI/Typography/components/AnimationNumber';
import { CloseIcon, ArrowTopRightIcon, TableIcon, JsonIcon } from 'mdi-react';
import { DialogHeader, CloseButton, Title } from './styles';
import { CSVLink } from 'react-csv';
import { Button as MaterialButton } from "@material-ui/core";
import { export2JSON } from '../../../utils/export2JSON';
class CurrencyContainer extends React.Component {
constructor() {
super();
this.state = {
open: false,
currency: {},
wallet: {},
isLoading: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { id, profile } = props;
const { App } = profile;
if (!_.isEmpty(this.state.currency)) {
const wallets = App.params.wallet;
const currencies = App.params.currencies;
const currency = currencies.find(currency => currency._id === id);
const wallet = wallets.find(wallet => wallet.currency._id === currency._id);
if (!_.isEmpty(currency)) {
this.setState({
currency: currency,
wallet: wallet
})
} else {
this.setState({
currency: {},
wallet: {}
})
}
}
}
setOpen = async () => {
const { id, profile } = this.props;
const { App } = profile;
if (_.isEmpty(this.state.currency)) {
const wallets = App.params.wallet;
const currencies = App.params.currencies;
const currency = currencies.find(currency => currency._id === id);
const wallet = wallets.find(wallet => wallet.currency._id === currency._id);
if (!_.isEmpty(currency)) {
this.setState({
currency: currency,
wallet: wallet,
open: true
})
}
}
}
setClose = () => {
this.setState({
open: false,
currency: {},
wallet: {}
})
}
render() {
const { open, currency, wallet } = this.state;
let csvData = [{}];
let jsonData = [];
let headers = []
if (!_.isEmpty(currency)) {
const data = [
{
_id: currency._id,
name: currency.name,
ticker: currency.ticker,
walletId: wallet._id,
walletPlayBalance: wallet.playBalance ? parseFloat(wallet.playBalance).toFixed(6) : 0
}
]
headers = [
{ label: "Id", key: "_id" },
{ label: "Name", key: "name" },
{ label: "Ticker", key: "ticker" },
{ label: "Wallet", key: "walletId" },
{ label: "Wallet Balance", key: "walletPlayBalance" }
];
if (!_.isEmpty(data)) {
csvData = data;
jsonData = csvData.map(row => _.pick(row, ['_id', 'name', 'ticker', 'walletId', 'walletPlayBalance']));
}
}
return(
<>
<ButtonBase onClick={this.setOpen}>
{this.props.children}
</ButtonBase>
{ !_.isEmpty(currency) ?
<Dialog
// disableBackdropClick
open={open}
onClose={this.setClose}
>
<DialogHeader style={{ paddingBottom: 0 }}>
<div style={{ display: "flex", justifyContent: "flex-start", marginRight: 20 }}>
<CSVLink data={csvData} filename={"currency.csv"} headers={headers}>
<MaterialButton variant="contained" size="small" style={{ textTransform: "none", backgroundColor: "#008000", color: "#ffffff", boxShadow: "none", margin: 10}}>
<TableIcon style={{marginRight: 7}}/> CSV
</MaterialButton>
</CSVLink>
<MaterialButton onClick={() => export2JSON(jsonData, "currency")} variant="contained" size="small" style={{ textTransform: "none", boxShadow: "none", margin: 10}}>
<JsonIcon style={{marginRight: 7}}/> JSON
</MaterialButton>
</div>
<CloseButton onClick={this.setClose}>
<CloseIcon/>
</CloseButton>
</DialogHeader>
<DialogContent style={{ paddingTop: 0 }}>
<Title>Currency</Title>
<Row>
<Col sd={12} md={12} lg={4}>
<img src={currency.image} style={{ height: 75, width: 75 }}className='user-avatar' alt={currency.name}/>
</Col>
<Col sd={12} md={12} lg={8}>
<h4 style={{marginTop : 5}}> {currency.name}
{/* <span className='text-small'>{currency.ticker}</span> */}
</h4>
<p className='text-x-small'> #{currency._id} </p>
<hr></hr>
</Col>
</Row>
<Row>
<Col sd={12} md={12} lg={4}>
<Title>Wallet</Title>
<Link to={'/wallet'}>
<Button variant="outlined" size="small" style={{ textTransform: "none", backgroundColor: "#63c965", color: "#ffffff", boxShadow: "none", height: 35, margin: "10px 0px", marginTop: 0, marginLeft: -5 }}>
<ArrowTopRightIcon style={{ marginRight: 3 }}/> Wallet
</Button>
</Link>
</Col>
<Col sd={12} md={12} lg={8} style={{ paddingTop: 30 }}>
<h4 style={{marginTop : 5}}> <AnimationNumber decimals={6} font={'20pt'} number={wallet.playBalance ? wallet.playBalance : 0 }/> <span className='text-small'>{wallet.currency.ticker}</span></h4>
<p className='text-x-small'> #{wallet._id} </p>
<hr></hr>
</Col>
</Row>
</DialogContent>
</Dialog> : null }
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(CurrencyContainer);<file_sep>/src/containers/Applications/Customization/index.js
import React, { Component } from 'react'
import { AnnouncementTab, Banners, Logo, Footer, Colors, Fonts, Tabs, SubSections, Skins, Icons, Social, Languages } from './components';
import TabsContainer from '../../../shared/components/tabs/Tabs';
import Background from './components/Background';
import { Bet, Reward, Phone, Settings, Rewards, AddOn, Withdraw, User, Chat } from '../../../components/Icons';
import EsportsMainPage from './components/EsportsMainPage';
export default class CustomizationContainer extends Component {
render() {
return (
<div>
<TabsContainer
items={[{
title : 'Skins',
container : <Skins/>,
icon : <Rewards/>
},
{
title : 'Icons',
container : <Icons/>,
icon : <AddOn/>
},
{
title : 'Announc. Tab',
container : <AnnouncementTab />,
icon : <Bet/>
},
{
title : 'Logo',
container : <Logo/>,
icon : <Reward/>
},
{
title : 'Background',
container : <Background/>,
icon : <Phone/>
},
{
title : 'Tabs',
container : <Tabs/>,
icon : <Settings/>
},
{
title : 'Languages',
container : <Languages/>,
icon : <Chat/>
},
{
title : 'Subsections',
container : <SubSections/>,
icon : <Settings/>
},
{
title : 'Banners',
container : <Banners/>,
icon : <Settings/>
},
{
title : 'Colors',
container : <Colors/>,
icon : <Rewards/>
},
{
title : 'Font',
container : <Fonts/>,
icon : <AddOn/>
},
{
title : 'Footer',
container : <Footer/>,
icon : <Withdraw/>
},
{
title : 'Esports',
container : <EsportsMainPage/>,
icon : <Reward/>
},
{
title : 'Social Links',
container : <Social/>,
icon : <User/>
},
]
}
/>
</div>
)
}
}
<file_sep>/src/containers/Wallet/components/paths/BonusWidget.js
import React from 'react';
import { Col, Container, Row } from 'reactstrap';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import { LockWrapper } from '../../../../shared/components/LockWrapper';
import DepositBonus from './DepositBonus';
import { TabContainer } from '../WalletTabs/styles';
import { Paragraph } from '../LiquidityWalletContainer/styles';
class BonusWidget extends React.Component{
render = () => {
const { profile } = this.props;
const { currency } = this.props.data.wallet;
const isSuperAdmin = profile.User.permission.super_admin;
return (
<TabContainer>
<Paragraph style={{ marginBottom: 15 }}>Choose the bonus to deposit of your wallet</Paragraph>
<Row>
<LockWrapper hasPermission={isSuperAdmin}>
<DepositBonus profile={profile} data={currency}/>
</LockWrapper>
</Row>
</TabContainer>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
wallet: (state.wallet.currency) ? state.wallet : state.profile.getApp().getSummaryData('walletSimple').data[0]
};
}
BonusWidget.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(BonusWidget);<file_sep>/src/containers/Layout/topbar/TopbarRefresh.jsx
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import store from '../../App/store';
import { setLoadingStatus } from '../../../redux/actions/loadingAction';
import { ButtonBase } from '@material-ui/core';
import styled from "styled-components";
const MobileWrapper = styled.section`
@media (max-width: 756px) {
display: none !important;
}
`;
class TopbarRefresh extends PureComponent {
state = {
isLoading: false,
disabled: false
};
refresh = async () => {
const { profile } = this.props;
store.dispatch(setLoadingStatus(true));
this.setState({ isLoading: true, disabled: true });
await profile.getData();
this.setState({ isLoading: false, disabled: false })
store.dispatch(setLoadingStatus(false));
}
render() {
const { isLoading, disabled } = this.state;
return (
<MobileWrapper>
<ButtonBase style={{ height: "100%" }} onClick={this.refresh} disabled={disabled}>
{ isLoading ? (
<i className="fas fa-sync fa-spin fa-lg" style={{ margin: 7, color: '#646777' }}/>
) : (
<i className="fas fa-sync fa-lg" style={{ margin: 7, color: '#646777' }}/>
)}
</ButtonBase>
</MobileWrapper>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(TopbarRefresh);
<file_sep>/src/containers/Users/components/UsersTable.jsx
import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import { connect } from "react-redux";
import { compose } from 'lodash/fp';
import {
Table, TableBody, TableCell, TableHead, TablePagination, TableRow, IconButton,
TableSortLabel, Toolbar, Typography, Paper, Tooltip, FormControl, TextField
} from '@material-ui/core';
import { Col, Row } from 'reactstrap';
import { lighten } from '@material-ui/core/styles/colorManipulator';
import { FilterListIcon, TableIcon, JsonIcon, AlertCircleOutlineIcon } from 'mdi-react';
import { compareIDS } from '../../../lib/string';
import _ from 'lodash';
import { CSVLink } from "react-csv";
import { export2JSON } from "../../../utils/export2JSON";
import { Button as MaterialButton } from "@material-ui/core";
import Skeleton from '@material-ui/lab/Skeleton';
import { DebounceInput } from 'react-debounce-input';
const loadingImg = `${process.env.PUBLIC_URL}/img/loading.gif`;
function getSorting(data, order, orderBy) {
const sortedData = _.orderBy(data, [orderBy], order);
return sortedData;
}
const fromDatabasetoTable = (data, otherInfo, currency) => {
return data.map((key) => {
var d;
if(otherInfo){
d = otherInfo.find( f => f._id == key._id);
}
const wallet = key.wallet.find(w => compareIDS(w.currency._id, currency._id));
return {
_id : key._id,
full_info : {...d, ...key},
username : key.username,
kyc_status: key.kyc_status,
wallet: wallet && wallet.playBalance ? parseFloat(wallet.playBalance) : 0,
bets: parseFloat(key.bets.length),
email: key.email,
turnoverAmount: d ? parseFloat(d.betAmount) : 0,
profit: d ? parseFloat(d.profit) : 0,
isWithdrawing: key.isWithdrawing
}
})
}
const rows = [
{
id: '_id',
label: 'Id',
numeric: false
},
{
id: 'username',
label: 'Username',
numeric: false
},
{
id: 'actionToConfirm',
label: 'Action to confirm',
numeric: false
},
{
id: 'email',
label: 'Email',
numeric: false
},
{
id: 'kyc_status',
label: 'KYC',
numeric: false
},
{
id: 'wallet',
label: 'Balance',
numeric: false
},
{
id: 'bets',
label: 'Bets',
numeric: false
},
{
id: 'turnoverAmount',
label: 'Turnover',
numeric: false
},
{
id: 'profit',
label: 'Profit',
numeric: false
},
];
class EnhancedTableHead extends React.Component {
createSortHandler = property => event => {
this.props.onRequestSort(event, property);
};
render() {
const { order, orderBy } = this.props;
return (
<TableHead>
<TableRow>
{rows.map(
row => (
<TableCell
key={row.id}
align={row.position ? row.position : 'left'}
padding={row.disablePadding ? 'none' : 'default'}
sortDirection={orderBy === row.id ? order : false}
>
<Tooltip
title="Sort"
placement={row.numeric ? 'bottom-end' : 'bottom-start'}
enterDelay={300}
>
<TableSortLabel
active={orderBy === row.id}
direction={order}
onClick={this.createSortHandler(row.id)}
>
{row.label}
</TableSortLabel>
</Tooltip>
</TableCell>
),
this,
)}
</TableRow>
</TableHead>
);
}
}
EnhancedTableHead.propTypes = {
numSelected: PropTypes.number.isRequired,
onRequestSort: PropTypes.func.isRequired,
onSelectAllClick: PropTypes.func.isRequired,
order: PropTypes.string.isRequired,
orderBy: PropTypes.string.isRequired,
rowCount: PropTypes.number.isRequired,
};
const toolbarStyles = theme => ({
root: {
paddingRight: theme.spacing.unit,
},
highlight:
theme.palette.type === 'light'
? {
color: theme.palette.secondary.main,
backgroundColor: lighten(theme.palette.secondary.light, 0.85),
}
: {
color: theme.palette.text.primary,
backgroundColor: theme.palette.secondary.dark,
},
spacer: {
flex: '1 1 100%',
},
actions: {
color: theme.palette.text.secondary, zIndex: 20
},
title: {
flex: '0 0 auto',
},
});
let EnhancedTableToolbar = props => {
const { numSelected, classes, filterClick } = props;
return (
<Toolbar
className={classNames(classes.root, {
[classes.highlight]: numSelected > 0,
})}
>
<div className={classes.title}>
<Typography variant="h6" id="tableTitle">
Users
</Typography>
</div>
<div className={classes.spacer} />
<div className={classes.actions} onClick={filterClick}>
<div style={{position: "absolute", right: 0, margin: "14px 70px 0 0", cursor: "pointer"}}><p>Filter List</p></div>
<Tooltip title="Filter list">
<IconButton aria-label="Filter list">
<FilterListIcon />
</IconButton>
</Tooltip>
</div>
</Toolbar>
);
};
EnhancedTableToolbar.propTypes = {
classes: PropTypes.object.isRequired,
numSelected: PropTypes.number.isRequired,
};
EnhancedTableToolbar = withStyles(toolbarStyles)(EnhancedTableToolbar);
const styles = theme => ({
root: {
width: '100%',
marginTop: theme.spacing.unit * 3,
},
table: {
minWidth: 1020,
},
tableWrapper: {
overflowX: 'auto',
},
});
const defaultProps = {
profit : '0',
ticker : 'No Currency Chosen',
}
class UsersTable extends React.Component {
constructor(props){
super(props)
this.state = {
order: 'asc',
orderBy: 'id',
selected: [],
data: [],
page: 0,
rowsPerPage: 10,
usernameFilter: null,
emailFilter: null,
idFilter: null,
showFilter: false,
...defaultProps,
confirmingAnyProcess: {}
};
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props)
}
projectData = (props) => {
let data = props.data;
const { currency } = props;
this.setState({...this.state,
data : fromDatabasetoTable(data.users.data, data.usersOtherInfo.data, currency),
ticker : currency.ticker ? currency.ticker : defaultProps.ticker,
})
}
handleRequestSort = (event, property) => {
const orderBy = property;
let order = 'desc';
if (this.state.orderBy === property && this.state.order === 'desc') {
order = 'asc';
}
this.setState({ order, orderBy });
};
handleSelectAllClick = event => {
if (event.target.checked) {
this.setState(state => ({ selected: state.data.map(n => n.id) }));
return;
}
this.setState({ selected: [] });
};
handleClick = (event, id) => {
const { selected } = this.state;
const selectedIndex = selected.indexOf(id);
let newSelected = [];
if (selectedIndex === -1) {
newSelected = newSelected.concat(selected, id);
} else if (selectedIndex === 0) {
newSelected = newSelected.concat(selected.slice(1));
} else if (selectedIndex === selected.length - 1) {
newSelected = newSelected.concat(selected.slice(0, -1));
} else if (selectedIndex > 0) {
newSelected = newSelected.concat(
selected.slice(0, selectedIndex),
selected.slice(selectedIndex + 1),
);
}
this.setState({ selected: newSelected });
};
handleChangeInputContent = event => {
if (event.target.name) {
this.setState({
[event.target.name] : event.target.value ? event.target.value : null
}, () => {
this.fetchFilteredData();
}
);
}
}
fetchFilteredData = async () => {
const { profile, currency } = this.props;
const { usernameFilter, emailFilter, idFilter } = this.state;
const users = await profile.App.getUsersAsync({
size: 100,
offset: 0,
filters: {
username: usernameFilter,
email: emailFilter,
user: idFilter
}
});
if ((_.isArray(users) || _.isObject(users)) && !_.isString(users)) {
this.setState({
data: fromDatabasetoTable(users, this.props.data.usersOtherInfo.data, currency)
})
}
}
resetData = async () => {
const { profile, currency } = this.props;
this.setLoading(true);
const users = await profile.App.getUsersAsync({
size: 100,
offset: 0
});
this.setState({
data: fromDatabasetoTable(users, this.props.data.usersOtherInfo.data, currency)
})
this.setLoading(false);
}
handleChangePage = async (event, page) => {
const { data, rowsPerPage, usernameFilter, emailFilter, idFilter } = this.state;
const { currency } = this.props;
const { App } = this.props.profile;
if (page === Math.ceil(data.length / rowsPerPage)) {
this.setLoading(true);
const users = await App.getUsersAsync({
size: 100,
offset:
data.length,
filters: {
username: usernameFilter,
email: emailFilter,
user: idFilter
}
});
if (users.length > 0) {
this.setState({
data: data.concat(fromDatabasetoTable(users, this.props.data.usersOtherInfo.data, currency)),
page: page
})
}
this.setLoading(false);
} else {
this.setState({ page });
}
};
setLoading = (status) => {
this.setState(state => ({ loading: status }));
}
handleChangeRowsPerPage = event => {
this.setState({ rowsPerPage: event.target.value });
};
isSelected = id => this.state.selected.indexOf(id) !== -1;
handleFilterClick = () => {
const { showFilter } = this.state;
this.setState({ showFilter: showFilter ? false : true });
}
handleConfirmUserAction = async ({ id }) => {
const { data } = this.state;
const { profile } = this.props;
this.setState({ confirmingAnyProcess: {
...this.state.confirmingAnyProcess, [id] : true
}})
await profile.getApp().confirmUserAction({ id: id });
this.setState({ confirmingAnyProcess: {
...this.state.confirmingAnyProcess, [id] : false
}})
const user = !_.isEmpty(data) && data.find(u => u._id === id);
if (user) {
const index = data.indexOf(user);
let newData = [...data];
newData[index] = {...user, isWithdrawing: false };
this.setState({
data: newData
})
}
}
render() {
const { classes, currency, isLoading } = this.props;
const { showFilter, data, order, orderBy, selected, rowsPerPage, page, usernameFilter, emailFilter, idFilter, loading } = this.state;
const emptyRows = rowsPerPage - Math.min(rowsPerPage, data.length - page * rowsPerPage);
const styles = {
filter: {
padding: '30px 20px', border: "1px solid #d9d9d9", margin: '24px 14px 0 0',
backgroundColor: "#f2f4f7", borderRadius: 4, width: '92%', maxWidth: 400, position: 'absolute',
top: 0, right: 0, left: 'auto', zIndex: 10, display: showFilter ? 'block' : 'none'
}
};
const headers = [
{ label: "Id", key: "_id" },
{ label: "Username", key: "username" },
{ label: "Email", key: "email" },
{ label: "KYC", key: "kyc_status"},
{ label: "Balance", key: "wallet" },
{ label: "Bets", key: "bets" },
{ label: "Turnover", key: "turnoverAmount" },
{ label: "Profit", key: "profit"}
];
const jsonData = data.map(row => _.pick(row, ['_id', 'username', 'email', 'kyc_status', 'wallet', 'bets', 'turnoverAmount', 'profit']));
return (
<Paper className={classes.root} style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<EnhancedTableToolbar numSelected={selected.length} filterClick={this.handleFilterClick}/>
<div style={{ display: "flex", justifyContent: "flex-end", alignItems: "center" }}>
<CSVLink data={data} filename={"users.csv"} headers={headers}>
<MaterialButton variant="contained" size="small" style={{ textTransform: "none", backgroundColor: "#008000", color: "#ffffff", boxShadow: "none", margin: 10}}>
<TableIcon style={{marginRight: 7}}/> CSV
</MaterialButton>
</CSVLink>
<MaterialButton onClick={() => export2JSON(jsonData, "users")} variant="contained" size="small" style={{ textTransform: "none", boxShadow: "none", margin: 10}}>
<JsonIcon style={{marginRight: 7}}/> JSON
</MaterialButton>
</div>
<div style={{ display: "flex", justifyContent: "flex-end", alignItems: "center", padding: "10px 20px" }}>
<AlertCircleOutlineIcon size={18} style={{ margin: "0px 5px "}}/>
<span>Values may change according to periodicity</span>
</div>
{isLoading || loading ? (
<>
<Skeleton variant="rect" height={50} style={{ marginTop: 10, marginBottom: 20 }}/>
{ _.times(rowsPerPage, () => <Skeleton variant="rect" height={30} style={{ marginTop: 10, marginBottom: 10 }}/>)}
</>
) : (
<>
<div style={styles.filter}>
<Col>
<Row>
<FormControl style={{width : '100%', padding: 8 }}>
<DebounceInput
label={'Username'}
name={'usernameFilter'}
type={'text'}
debounceTimeout={500}
defaultValue={usernameFilter}
onChange={event => this.handleChangeInputContent(event)}
element={TextField} />
</FormControl>
</Row>
<Row>
<FormControl style={{width : '100%', padding: 8 }}>
<DebounceInput
label={'Email'}
name={'emailFilter'}
type={'text'}
debounceTimeout={500}
defaultValue={emailFilter}
onChange={event => this.handleChangeInputContent(event)}
element={TextField} />
</FormControl>
</Row>
<Row>
<FormControl style={{width : '100%', padding: 8}}>
<DebounceInput
label={'Id'}
name={'idFilter'}
type={'text'}
debounceTimeout={500}
defaultValue={idFilter}
onChange={event => this.handleChangeInputContent(event)}
element={TextField} />
</FormControl>
</Row>
<Row style={{ display: 'flex', justifyContent: 'flex-end' }}>
<MaterialButton size="small" variant="outlined"
style={{ marginLeft: 0, marginTop: 15, marginBottom: 5, alignSelf: 'end', textTransform: 'none' }}
onClick={() => this.resetData()}
disabled={loading}
>
Clear
</MaterialButton>
</Row>
</Col>
</div>
<div className={classes.tableWrapper}>
<Table className={classes.table} aria-labelledby="tableTitle">
<EnhancedTableHead
numSelected={selected.length}
order={order}
orderBy={orderBy}
onSelectAllClick={this.handleSelectAllClick}
onRequestSort={this.handleRequestSort}
rowCount={data.length}
/>
<TableBody>
{getSorting(data, order, orderBy)
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map(n => {
const isSelected = this.isSelected(n.id);
return (
<TableRow
hover
onClick={event => this.handleClick(event, n.id)}
role="checkbox"
style={{padding : 0}}
aria-checked={isSelected}
tabIndex={-1}
key={n.id}
selected={isSelected}
>
<TableCell align="left">
<p className='text-small'>
{n._id}
</p>
</TableCell>
<TableCell align="left">
<p className='text-small'>
{n.username}
</p>
</TableCell>
<TableCell align="left">
<p className='text-small'>
{ n.isWithdrawing ? (
<button
disabled={this.state.confirmingAnyProcess[n._id]}
className={`clean_button button-normal button-hover`}
style={{
height: "24px",
width: "110px",
padding: "5px 15px",
margin: "5px",
backgroundColor: this.state.confirmingAnyProcess[n._id] ? "grey" : "#63c965"
}}
onClick={ () => this.handleConfirmUserAction({ id: n._id })}>
{!this.state.confirmingAnyProcess[n._id]
? <p className='text-small text-white'>Yes, confirm</p>
: <img src={loadingImg} alt="Loading" style={{ width: 20, height: 20, marginTop: -5 }}/>}
</button>
) : 'No'}
</p>
</TableCell>
<TableCell align="left">
<p className='text-small'>
{n.email}
</p>
</TableCell>
<TableCell align="left">
<p className='text-small'>
{n.kyc_status}
</p>
</TableCell>
<TableCell align="left">
<p className='text-small'>
{!_.isEmpty(currency) ? n.wallet.toFixed(6) : null }
<span className={!_.isEmpty(currency) ? 'text-small text-grey' : 'text-small background-soft-grey text-white' } > {this.state.ticker}</span>
</p>
</TableCell>
<TableCell align="left">
<p className='text-small background-grey text-white'>
{n.bets}
</p>
</TableCell>
<TableCell align="left">
<p className='text-small'>
{!_.isEmpty(currency) ? n.turnoverAmount.toFixed(6) : null }
<span className={!_.isEmpty(currency) ? 'text-small text-grey' : 'text-small background-soft-grey text-white' } > {this.state.ticker}</span>
</p>
</TableCell>
<TableCell align="left">
<p className='text-small'>
{!_.isEmpty(currency) ? n.profit.toFixed(6) : null }
<span className={!_.isEmpty(currency) ? 'text-small text-grey' : 'text-small background-soft-grey text-white' } > {this.state.ticker}</span>
</p>
</TableCell>
<TableCell align="left">
<button className={`clean_button button-normal button-hover`} onClick={ () => this.props.goToUserPage({user : n.full_info})}>
<p className='text-small text-white'>See More</p>
</button>
</TableCell>
</TableRow>
);
})}
{emptyRows > 0 && (
<TableRow style={{ height: 49 * emptyRows }}>
<TableCell colSpan={6} />
</TableRow>
)}
</TableBody>
</Table>
</div>
</>)}
<TablePagination
rowsPerPageOptions={[5, 10, 25, 50, 100]}
component="div"
count={data.length + rowsPerPage}
rowsPerPage={rowsPerPage}
page={page}
labelDisplayedRows={({ from, to, count }) => `${from}-${to > count - rowsPerPage ? count - rowsPerPage : to} of ${count - rowsPerPage}`}
backIconButtonProps={{
'aria-label': 'Previous Page',
}}
nextIconButtonProps={{
'aria-label': 'Next Page',
}}
onChangePage={this.handleChangePage}
onChangeRowsPerPage={this.handleChangeRowsPerPage}
/>
</Paper>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile,
currency : state.currency
};
}
UsersTable.propTypes = {
classes: PropTypes.object.isRequired,
};
export default compose(withStyles(styles), connect(mapStateToProps))(UsersTable);
<file_sep>/src/containers/Dashboards/Default/components/CompanyId/styles.js
import styled from 'styled-components';
import { Button as MaterialButton } from '@material-ui/core';
import { Input } from 'reactstrap';
export const Container = styled.div`
display: flex;
flex-direction: column;
`;
export const AppDetails = styled.section`
display: flex;
flex-wrap: wrap;
> img {
justify-self: center;
margin: 0px 5px;
}
> div {
&.name-and-description {
display: flex;
flex-direction: column;
align-content: flex-start;
padding: 0px 10px;
> p {
margin: 5px 0px;
padding: 0;
height: auto;
}
}
}
`;
export const Edit = styled.section`
display: flex;
justify-content: flex-end;
flex: auto;
`;
export const BankAddress = styled.section`
display: flex;
flex-direction: row;
flex-wrap: wrap;
padding: 5px 0px;
align-items: flex-end;
justify-content: flex-start;
`;
export const EditButton = styled(MaterialButton)`
margin: 0px !important;
text-transform: none !important;
background-color: #894798 !important;
box-shadow: none !important;
height: 25px !important;
color: white !important;
opacity: ${props => props.disabled ? 0.7 : 1};
font-size: 12px;
`;
export const ConfirmButton = styled(MaterialButton)`
margin: 7px 0px !important;
width: 100px;
text-transform: none !important;
background-color: #63c965 !important;
box-shadow: none !important;
height: 30px !important;
color: white !important;
opacity: ${props => props.disabled ? 0.7 : 1};
`;
export const DialogHeader = styled.div`
display: flex;
justify-content: flex-end;
width: 100%;
padding: 20px 30px 0px 30px;
`;
export const DialogActions = styled.section`
display: flex;
flex-direction: row;
justify-content: flex-end;
align-items: center;
padding: 10px 24px;
`;
export const TextField = styled(Input)`
margin: 12px 0px;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: white;
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
`;
<file_sep>/src/services/converter.js
import APISingleton from "./api";
class converter{
constructor(){}
fromETHtoUsd = (eth_quantity) => {
let usd_quantity = APISingleton.getEthereumPrice(eth_quantity);
return usd_quantity;
}
}
let ConverterSingleton = new converter();
export default ConverterSingleton;<file_sep>/src/containers/Wallet/components/paths/limits/LimitsBox.js
import React from 'react';
import { Col, Row, Card, CardBody } from 'reactstrap';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import _ from 'lodash';
import EditLock from '../../../../Shared/EditLock';
import TextInput from '../../../../../shared/components/TextInput';
import DateInput from '../../../../../shared/components/DateInput';
class LimitsBox extends React.Component{
constructor(props){
super(props)
}
render = () => {
let {
title,
inputIcon,
currencyTicker,
image,
lock,
inputType,
type,
value,
new_value,
isLoading,
defaultValue,
/* Functions */
unlockField,
lockField,
onChange,
confirmChanges
} = this.props;
if(!inputType){
inputType = 'text'
}
return (
<Card>
<CardBody style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<img className='application__game__image' src={image}/>
<hr></hr>
<h5 className=""> {title} {
(currencyTicker ? `(${currencyTicker})` : null)
} </h5>
<h3 style={{marginTop : 20}} className={"bold-text dashboard__total-stat"}>{this.props.value}</h3>
<hr/>
<EditLock isLoading={isLoading} unlockField={unlockField} lockField={lockField} confirmChanges={confirmChanges} type={type} locked={lock}>
<h6 className="">New {title} </h6>
<h5 className={"bold-text dashboard__total-stat"}>{new_value} {currencyTicker} </h5>
{
inputType == 'text' ?
<TextInput
icon={inputIcon}
name={type}
type="number"
disabled={lock}
changeContent={ (type, value) => onChange({type, value})}
/>
: inputType == 'date' ?
<DateInput
name={type}
defaultValue={defaultValue}
label={type}
changeContent={ (type, value) => onChange({type, value})}
/>
: null
}
</EditLock>
</CardBody>
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
LimitsBox.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(LimitsBox);
<file_sep>/src/containers/Bets/components/BetsTable/styles.js
import styled from 'styled-components';
export const Container = styled.div`
padding: 10px;
border-radius: 10px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #FAFCFF;
display: grid;
grid-template-areas:
'header'
'table';
grid-template-columns: 100%;
grid-template-rows: auto 1fr;
`;
export const Header = styled.div`
grid-area: header;
display: grid;
grid-template-areas: 'filters export';
grid-template-columns: 70% 30%;
`;
export const TableContainer = styled.div`
grid-area: table;
width: 100%;
height: 100%;
padding-top: 15px;
`;
export const Filters = styled.div`
grid-area: filters;
display: flex;
justify-content: flex-start;
align-items: center;
flex-wrap: wrap;
padding: 5px;
`;
export const Export = styled.div`
grid-area: export;
display: flex;
justify-content: flex-end;
align-items: center;
padding: 5px;
`;
export const Text = styled.span`
font-family: Poppins;
font-size: 13px;
`;
export const BoldText = styled(Text)`
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
export const WonResult = styled.div`
display: flex;
justify-content: center;
align-items: center;
height: 22px;
width: 70px;
margin: 5px;
font-family: Poppins;
font-size: 13px;
font-weight: 400;
color: white;
background-color: ${props => props.isWon ? '#63c965' : '#e6536e' };
border-radius: 5px;
`;<file_sep>/src/containers/Stats/components/LiquidityInfo.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col } from 'reactstrap';
import Skeleton from '@material-ui/lab/Skeleton';
import AnimationNumber from '../../UI/Typography/components/AnimationNumber';
import { compareIDS } from '../../../../src/lib/string';
import { emptyObject } from '../../../../src/lib/misc';
const defaultProps = {
playBalance : 0,
ticker : 'N/A',
}
class LiquidityInfo extends PureComponent {
constructor(props){
super(props);
this.state = { ...defaultProps};
this.projectData(props);
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { currency } = props;
if(emptyObject(currency)){return null};
let wallets = props.data.data.wallet;
const wallet = wallets.find( w => compareIDS(w.currency._id, currency._id));
if(emptyObject(wallet)){return null};
this.setState({...this.state,
playBalance : wallet.playBalance ? wallet.playBalance : defaultProps.playBalance,
decimals : currency.decimals,
ticker : currency.ticker ? currency.ticker : defaultProps.ticker
})
}
render() {
const { isLoading } = this.props;
return (
<Col md={12} xl={12} lg={12} xs={12}>
<Card>
<CardBody className="dashboard__card-widget" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
{isLoading ? (
<Skeleton variant="rect" height={29} style={{ marginTop: 10, marginBottom: 10 }}/>
) : (
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-number-second" style={
{color : this.state.playBalance >= 0 ? '#76d076' : '#646777'}
}><AnimationNumber decimals={6} number={this.state.playBalance}/> <span> {this.state.ticker}</span></p>
</div>)}
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-title"> Liquidity <span> Available </span></p>
</div>
</CardBody>
</Card>
</Col>
);
}
}
export default LiquidityInfo;
<file_sep>/src/containers/Applications/AddOnPage/AddOnContainer/AddOn/AutoWithdraw.js
/* eslint-disable react/no-array-index-key */
import React from 'react';
import { Card, CardBody, Col, Row } from 'reactstrap';
import Skeleton from "@material-ui/lab/Skeleton";
import { connect } from "react-redux";
import { Grid, Switch, Typography, ExpansionPanelDetails, ExpansionPanelSummary, ExpansionPanel, makeStyles, Paper } from '@material-ui/core';
import TextInput from '../../../../../shared/components/TextInput';
import EditLock from '../../../../Shared/EditLock';
import { BankIcon, ExpandMoreIcon } from 'mdi-react';
import { LockWrapper } from '../../../../../shared/components/LockWrapper';
class AutoWithdraw extends React.Component {
constructor() {
super();
this.state = {
lock: true,
loading: false
}
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
if (this.state.lock) {
this.projectData(props);
}
}
projectData = (props) => {
const { autoWithdraw, currency } = props;
const { name, description, image_url, isAutoWithdraw } = autoWithdraw;
const maxWithdrawAmountCumulative = autoWithdraw.maxWithdrawAmountCumulative.filter(w => w.currency === currency._id)[0].amount;
const maxWithdrawAmountPerTransaction = autoWithdraw.maxWithdrawAmountPerTransaction.filter(w => w.currency === currency._id)[0].amount;
this.setState({...this.state,
name,
description,
image_url,
isAutoWithdraw,
maxWithdrawAmountCumulative,
maxWithdrawAmountPerTransaction
})
}
unlock = () => {
this.setState({...this.state, lock: false })
}
lock = () => {
this.setState({...this.state, lock: true })
}
handleChange = () => {
this.setState({...this.state, isAutoWithdraw: !this.state.isAutoWithdraw })
}
onChangeCumulative = (value) => {
this.setState({...this.state, maxWithdrawAmountCumulative: value ? parseFloat(value) : 0})
}
onChangePerTransaction = (value) => {
this.setState({...this.state, maxWithdrawAmountPerTransaction: value ? parseFloat(value) : 0})
}
confirmChanges = async (currency) => {
const { profile } = this.props;
const currencyId = currency._id;
const autoWithdrawParams = {
isAutoWithdraw: this.state.isAutoWithdraw,
maxWithdrawAmountCumulative: this.state.maxWithdrawAmountCumulative,
maxWithdrawAmountPerTransaction: this.state.maxWithdrawAmountPerTransaction
}
this.setState({...this.state, loading: true })
await profile.getApp().editAutoWithdraw({currency: currencyId, autoWithdrawParams})
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({...this.state, loading: false })
this.lock()
}
render() {
const { name, description, image_url, isAutoWithdraw, maxWithdrawAmountCumulative, maxWithdrawAmountPerTransaction, lock } = this.state;
const { currency, isLoading, profile } = this.props;
const isSuperAdmin = profile.User.permission.super_admin;
return (
<>
{isLoading ? (
<>
<Card className='game-container'>
<CardBody className="dashboard__card-widget" style={{ width: 320, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<Grid container direction='row' spacing={1}>
<Grid item xs={9}>
<Skeleton variant="rect" height={29} style={{ marginTop: 10, marginBottom: 10 }}/>
</Grid>
<Grid item xs={3}>
<Skeleton variant="circle" width={50} height={50} style={{ marginBottom: 10, marginLeft: 'auto', marginRight: 0 }}/>
</Grid>
</Grid>
<Skeleton variant="rect" height={35} style={{ marginTop: 10, marginBottom: 10 }}/>
</CardBody>
</Card>
</>
) : (
<Card className='game-container'>
<Paper elevation={0} style={{width: '320px', padding: 5, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<ExpansionPanel elevation={0}>
<ExpansionPanelSummary
style={{width: '320px', height: '120px', padding: 20, paddingBottom: 0, paddingTop: 0, justifyContent: 'space-between'}}
expandIcon={<ExpandMoreIcon />}
aria-controls="autowithdraw-content"
id="autowithdraw-header"
>
<div style={{display: 'flex', justifyContent: 'space-between', width: "100%"}}>
<div className="dashboard__visitors-chart text-left">
<p className="dashboard__visitors-chart-title text-left" style={{fontSize : 20}}>{name}</p>
</div>
<img className='application__game__image' style={{width: '60px', margin: 0, padding: 0}} src={image_url}/>
</div>
</ExpansionPanelSummary>
<LockWrapper hasPermission={isSuperAdmin}>
<ExpansionPanelDetails style={{padding: 0}}>
<Col>
<div className="dashboard__visitors-chart text-left" style={{marginTop : 10}}>
<h5>{description}</h5>
</div>
<hr/>
<EditLock
unlockField={this.unlock}
lockField={this.lock}
confirmChanges={() => this.confirmChanges(currency)}
isLoading={this.state.loading}
locked={lock}>
<h5 style={{ margin: 0 }} >AutoWithdraw</h5>
<Switch
checked={isAutoWithdraw}
onChange={this.handleChange}
color="primary"
name="isAutoWithdraw"
disabled={lock}
inputProps={{ 'aria-label': 'primary checkbox' }}
/>
<hr/>
<h5 className="">Max Withdraw Amount Cumulative Per User ({maxWithdrawAmountCumulative} {currency.ticker})</h5>
<TextInput
// icon={BankIcon}
name="maxWithdrawAmountCumulative"
label={<h6>Max Withdraw Amount Cumulative Per User</h6>}
type="text"
disabled={lock}
changeContent={(type, value) => this.onChangeCumulative(value)}
/>
<hr/>
<h5 className="">Max Withdraw Amount Per Transaction ({maxWithdrawAmountPerTransaction} {currency.ticker})</h5>
<TextInput
// icon={BankIcon}
name="maxWithdrawAmountPerTransaction"
label={<h6>Max Withdraw Amount Per Transaction</h6>}
type="text"
disabled={lock}
changeContent={(type, value) => this.onChangePerTransaction(value)}
/>
</EditLock>
</Col>
</ExpansionPanelDetails>
</LockWrapper>
</ExpansionPanel>
</Paper>
</Card> )}
</>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile,
currency : state.currency
};
}
export default connect(mapStateToProps)(AutoWithdraw);
<file_sep>/src/controllers/App.js
import ConnectionSingleton from "../api/Connection";
import store from "../containers/App/store";
import Numbers from "../services/numbers";
import { getNonce } from "../lib/number";
import { getPastTransactions, getTransactionDataERC20 } from "../lib/etherscan";
import { setCurrencyView } from "../redux/actions/currencyReducer";
import { setGamesData, setUsersData, setBetsData, setRevenueData, setWalletData, setWithdrawalsData } from "../redux/actions/summaryActions";
import { getAuthFromCookies } from "./services/services";
import _, { identity } from 'lodash';
import { getVideoGamesAll, getAllVideogames, getMatchesAll, getSeriesMatches, getSpecificMatch, setBookedMatch, removeBookedMatch, getTeamStats, getPlayerStats, getBookedMatches, getBookedSeriesMatches } from "../esports/services";
class App{
constructor(params){
this.params = params;
this.data = {
summary : {}
};
this.admin = getAuthFromCookies();
}
hasPermission(res){
return res.data.status === 200;
}
getSummary = async () => {
const state = store.getState();
const { currency } = state;
try{
let res = await Promise.all([
ConnectionSingleton.getApp({
admin : this.getAdminId(),
app : this.getId(),
headers : authHeaders(this.getBearerToken(), this.getAdminId())
}),
ConnectionSingleton.getTransactions({
admin : this.getAdminId(),
app : this.getId(),
filters : [],
headers : authHeaders(this.getBearerToken(), this.getAdminId())
}),
this.getGamesAsync({ currency: currency._id }),
this.getUsersAsync({size: 100, offset: 0 }),
this.getUsersWithdrawals({ size: 100, offset: 0 })
]);
let serverApiInfo = {
affiliates : res[0].data.message ? res[0].data.message.affiliateSetup : null,
app : res[0].data.message ? res[0].data.message : null,
walletSimple : res[0].data.message ? res[0].data.message.wallet : null,
transactions : res[1].data && this.hasPermission(res[1]) ? res[1].data.message[0] : null,
gamesInfo : res[2],
usersInfoSummary : res[3],
withdraws : res[4]
}
this.params = serverApiInfo.app;
this.params.users = serverApiInfo.usersInfoSummary;
this.data = {
...this.data,
summary : {
...serverApiInfo
}
};
if (!_.isEmpty(currency)) {
await this.getSummaryAsync(currency);
}
return res;
}catch(err){
throw err;
}
}
getSummaryAsync = async (currency) => {
await this.getUsersSummary(currency);
await this.getGamesSummary(currency);
await this.getBetsSummary(currency);
await this.getRevenueSummary(currency);
await this.getWalletSummary(currency);
}
getUsersSummary = async (currency) => {
const state = store.getState();
const { periodicity } = state;
const response = await ConnectionSingleton.getSummary({
params : {
admin : this.getAdminId(),
app : this.getId(),
type : 'USERS',
periodicity : periodicity,
currency : currency._id,
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
})
response.data && typeof response.data.message !== 'string' ? store.dispatch(setUsersData(response.data.message)) : store.dispatch(setUsersData([]))
}
getGamesSummary = async (currency) => {
const state = store.getState();
const { periodicity } = state;
const response = await ConnectionSingleton.getSummary({
params : {
admin : this.getAdminId(),
app : this.getId(),
type : 'GAMES',
periodicity : periodicity,
currency : currency._id,
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
})
response.data && typeof response.data.message !== 'string' ? store.dispatch(setGamesData(response.data.message)) : store.dispatch(setGamesData([]))
}
getBetsSummary = async (currency) => {
const state = store.getState();
const { periodicity } = state;
const response = await ConnectionSingleton.getSummary({
params : {
admin : this.getAdminId(),
app : this.getId(),
type : 'BETS',
periodicity : periodicity,
currency : currency._id,
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
})
response.data && typeof response.data.message !== 'string' ? store.dispatch(setBetsData(response.data.message)) : store.dispatch(setBetsData([]))
}
getRevenueSummary = async (currency) => {
const state = store.getState();
const { periodicity } = state;
const response = await ConnectionSingleton.getSummary({
params : {
admin : this.getAdminId(),
app : this.getId(),
type : 'REVENUE',
periodicity : periodicity,
currency : currency._id,
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
})
response.data && typeof response.data.message !== 'string' ? store.dispatch(setRevenueData(response.data.message)) : store.dispatch(setRevenueData([]))
}
getWalletSummary = async (currency) => {
const state = store.getState();
const { periodicity } = state;
const response = await ConnectionSingleton.getSummary({
params : {
admin : this.getAdminId(),
app : this.getId(),
type : 'WALLET',
periodicity : periodicity,
currency : currency._id,
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
})
response.data && typeof response.data.message !== 'string' && this.hasPermission(response) ? store.dispatch(setWalletData(response.data.message[0])) : store.dispatch(setWalletData([]))
}
updateAppInfoAsync = async () => {
this.params = (await ConnectionSingleton.getApp({
admin : this.getAdminId(),
app : this.getId(),
headers : authHeaders(this.getBearerToken(), this.getAdminId())
})).data.message;
}
getDepositReference = async ({currency}) => {
// TO DO : Change App to the Entity Type coming from Login
try{
return await ConnectionSingleton.getDepositReference(
{
currency,
entity : this.getId(),
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
getTransactions = async ({filters}) => {
// TO DO : Change App to the Entity Type coming from Login
try{
return await ConnectionSingleton.getTransactions(
{
admin : this.getAdminId(),
app : this.getId(),
filters,
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
getUsersDeposits = async ({ size, offset, filters={} }) => {
try{
return await ConnectionSingleton.getUsersTransactions(
{
params: {
size,
offset,
type: "deposit",
..._.pickBy(filters, identity)
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
getUsersWithdrawals = async ({ size, offset, filters={} }) => {
try{
const response = await ConnectionSingleton.getUsersTransactions(
{
params: {
size,
offset,
type: "withdraw",
..._.pickBy(filters, identity)
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
const data = response.data.message;
data ? store.dispatch(setWithdrawalsData(data)) : store.dispatch(setWithdrawalsData([]))
return data;
}catch(err){
throw err;
}
}
deployApp = async () => {
// TO DO : Change App to the Entity Type coming from Login
try{
return await ConnectionSingleton.deployApp(
{
params : {
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
editApp = async ({ editParams }) => {
try{
let res = await ConnectionSingleton.editApp({
params : {
admin : this.getAdminId(),
app : this.getId(),
editParams,
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
updateAppBalance = async ({ increase_amount, currency }) => {
try{
let res = await ConnectionSingleton.updateAppBalance({
params : {
admin : this.getAdminId(),
app : this.getId(),
increase_amount,
currency
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
return res;
}catch(err){
throw err;
}
}
setGamesAsync = async () => {
try{
const { currency } = store.getState();
this.data.summary.gamesInfo = await this.getGamesAsync({currency : currency._id});
}catch(err){
throw err;
}
}
async addServices(services){
try{
let res = await ConnectionSingleton.addServices({
admin : this.getAdminId(),
app : this.getId(),
headers : authHeaders(this.getBearerToken(), this.getAdminId()),
services
});
return res;
}catch(err){
throw err;
}
}
async editAffiliateStructure({structures}){
try{
return await ConnectionSingleton.editAffiliateStructure({
params : {
admin : this.getAdminId(),
app : this.getId(),
structures,
affiliateTotalCut : structures.reduce( (acc, s) => acc+parseFloat(s.percentageOnLoss), 0)
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
})
}catch(err){
throw err;
}
}
async setCustomAffiliateStructureToUser({user, affiliatePercentage}){
try{
return await ConnectionSingleton.setCustomAffiliateStructureToUser({
params : {
admin : this.getAdminId(),
app : this.getId(),
user,
affiliatePercentage
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
})
}catch(err){
throw err;
}
}
getName(){
return this.params.name;
}
getCroupier(){
return this.params.croupier;
}
getDescription(){
return this.params.description;
}
getServices(){
return this.params.services;
}
getAppLink(){
return this.params.web_url;
}
getId(){
return this.params.id;
}
getCustomization(){
return this.params.customization;
}
getTypography(){
return this.params.typography;
}
getChatIntegration(){
return this.params.integrations.chat;
}
getEmailIntegration(){
return this.params.integrations.mailSender;
}
getInformation(key){
return this.params[key];
}
getBearerToken(){
return this.admin.bearerToken;
}
getAdminId(){
return this.admin.admin;
}
getWallet = ({currency_id}) => {
return this.params.wallet.find( w => new String(w.currency._id).toString() == new String(currency_id).toString());
}
isConnected(){
return this.params.isValid;
}
isDeployed(){
return this.params.web_url;
}
hasPaybearToken(){
return this.params.paybearToken;
}
async updateWallet({amount, transactionHash, currency_id}){
try{
let res = await ConnectionSingleton.updateWallet({
params : {
admin : this.getAdminId(),
app : this.getId(),
amount,
transactionHash,
currency : currency_id
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
let {
message,
status
} = res.data;
if(parseInt(status) == 200){
return true;
}else{
throw new Error(res.data.message);
}
}catch(err){
console.log(err);
throw err;
}
}
getParams = () => this.params;
getWithdraws = ({currency}) => this.params.withdraws.filter( w => new String(w.currency).toString() == new String(currency._id).toString()) || [];
getDeposits = ({currency}) => this.params.deposits.filter( d => new String(d.currency).toString() == new String(currency._id).toString()) || [];
getDexDepositsAsync = async (address) => {
let depositsApp = this.params.deposits || [];
let allTxsDeposits = await this.getUnconfirmedBlockchainDeposits(address);
return (await Promise.all(allTxsDeposits.map( async tx => {
var isConfirmed = false, deposit = null;
for(var i = 0; i < depositsApp.length; i++){
if(new String(depositsApp[i].transactionHash).toLowerCase().trim() == new String(tx.transactionHash).toLowerCase().trim()){
isConfirmed = true;
deposit = depositsApp[i];
}
}
if(isConfirmed){
return {...deposit, isConfirmed}
}else{
return {...tx, isConfirmed}
}
}))).filter(el => el != null)
}
requestWithdraw = async ({tokenAmount, currency, toAddress}) => {
try{
/* Get Request Withdraw Response */
var res_with = await ConnectionSingleton.requestWithdraw({
params : {
address : toAddress,
nonce : getNonce(),
currency : currency._id,
tokenAmount,
app : this.getId(),
admin : this.getAdminId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId()),
});
return res_with;
}catch(err){
throw err;
}
}
finalizeWithdraw = async ({withdraw_id, currency}) => {
try{
/* Get Request Withdraw Response */
var res_with = await ConnectionSingleton.finalizeWithdraw({
params : {
withdraw_id,
nonce : getNonce(),
currency : currency._id,
app : this.getId(),
admin : this.getAdminId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId()),
});
return res_with;
}catch(err){
throw err;
}
}
getUserAsync = async ({user, currency}) => {
return (await ConnectionSingleton.getUser({
params : {
user,
app : this.getId(),
admin : this.getAdminId(),
currency: currency._id
},
headers : authHeaders(this.getBearerToken(), this.getAdminId()),
})).data.message;
}
getGameStats = async ({game, currency}) => {
return (await ConnectionSingleton.getGameStats({
params : {
game,
app : this.getId(),
admin : this.getAdminId(),
currency: currency._id
},
headers : authHeaders(this.getBearerToken(), this.getAdminId()),
})).data.message;
}
getUsersAsync = async ({ size, offset, filters={} }) => {
try{
/* Get App Users */
this.data.summary.usersInfoSummary = (await ConnectionSingleton.getAppUsers({
params : {
size,
offset,
..._.pickBy(filters, _.identity),
app : this.getId(),
admin : this.getAdminId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId()),
})).data.message;
return this.data.summary.usersInfoSummary;
}catch(err){
throw err;
}
}
getWithdrawsAsync = async ({ size, offset }) => {
try{
const data = (await ConnectionSingleton.getWithdraws({
params : {
size,
offset,
app : this.getId(),
admin : this.getAdminId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId()),
})).data.message;
data ? store.dispatch(setWithdrawalsData(data)) : store.dispatch(setWithdrawalsData([]))
return data;
}catch(err){
throw err;
}
}
externalApproveWithdraw = async ({ withdraw }) => {
const { _id } = withdraw;
try{
let res = await ConnectionSingleton.externalApproveWithdraw({
params : {
admin: this.getAdminId(),
withdraw_id : _id
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
})
return res;
}catch(err){
throw err;
}
}
externalCancelWithdraw = async ({ withdraw }) => {
const { _id } = withdraw;
try{
let res = await ConnectionSingleton.externalCancelWithdraw({
params : {
admin: this.getAdminId(),
withdraw_id : _id
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
})
return res;
}catch(err){
throw err;
}
}
approveWithdrawsBatch = async (items) => {
try{
let users_array = [];
for(var i = 0; i < items.length; i++){
if(users_array.findIndex(u => items[i].user == u));
/* TO DO */
let item = items[i];
let res = await ConnectionSingleton.finalizeUserWithdraw({
admin : this.getAdminId(), user : item.user, app : this.getId(), transactionHash : null, withdraw_id : item._id,
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
console.log(res);
}
return true;
}catch(err){
throw err;
}
}
editTableLimit = async ({game, tableLimit, wallet}) => {
try{
/* Cancel Withdraw Response */
return await ConnectionSingleton.editTableLimit({
admin : this.getAdminId(),
app : this.getId(),
game, tableLimit, wallet,
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
editLanguage = async ({ language_id, logo, isActivated }) => {
try{
/* Cancel Withdraw Response */
let res = await ConnectionSingleton.editLanguage({
params: {
admin: this.getAdminId(),
app: this.getId(),
language_id,
logo,
isActivated
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
return res;
}catch(err){
throw err;
}
}
editTopBarCustomization = async ({ textColor, backgroundColor, text, isActive, language, useStandardLanguage }) => {
try{
/* Cancel Withdraw Response */
let res = await ConnectionSingleton.editTopBarCustomization({
params: {
admin: this.getAdminId(),
app: this.getId(),
textColor,
backgroundColor,
text,
isActive,
language,
useStandardLanguage
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editSkinTypeCustomization = async ({ skinParams }) => {
try{
/* Cancel Withdraw Response */
let res = await ConnectionSingleton.editSkinTypeCustomization({
params: {
admin: this.getAdminId(),
app: this.getId(),
skinParams
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editTypography = async (typography) => {
try{
let res = await ConnectionSingleton.editTypography({
params : {
admin : this.getAdminId(),
app : this.getId(),
typography
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editIntegration = async ({isActive, integration_id, publicKey, privateKey, integration_type}) => {
try{
/* Cancel Withdraw Response */
let res = await ConnectionSingleton.editIntegration({
params : {
admin : this.getAdminId(),
app : this.getId(),
isActive,
integration_id,
publicKey,
privateKey,
integration_type
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editCrispIntegration = async ({ isActive, key, cripsr_id }) => {
try{
let res = await ConnectionSingleton.editCrispIntegration({
params : {
admin : this.getAdminId(),
app : this.getId(),
isActive,
key,
cripsr_id
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editKYCIntegration = async ({ kyc_id, isActive, clientId, flowId, client_secret }) => {
try{
let res = await ConnectionSingleton.editKYCIntegration({
params : {
admin : this.getAdminId(),
app : this.getId(),
kyc_id,
isActive,
clientId,
flowId,
client_secret
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editAnalyticsIntegration = async ({ analytics_id, google_tracking_id, isActive }) => {
try{
let res = await ConnectionSingleton.editAnalyticsIntegration({
params : {
admin : this.getAdminId(),
app : this.getId(),
analytics_id,
google_tracking_id,
isActive: isActive
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editMoonPayIntegration = async ({ moonpay_id, isActive, key }) => {
try{
let res = await ConnectionSingleton.editMoonPayIntegration({
params : {
admin : this.getAdminId(),
app : this.getId(),
moonpay_id,
isActive,
key
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editUserKYC = async ({ user, kyc_needed }) => {
try{
let res = await ConnectionSingleton.editUserKYC({
params : {
admin : this.getAdminId(),
app : this.getId(),
user: user,
kyc_needed: kyc_needed
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
return res;
}catch(err){
throw err;
}
}
editEmailIntegration = async ({apiKey, templateIds}) => {
try{
/* Cancel Withdraw Response */
let res = await ConnectionSingleton.editEmailIntegration({
params : {
admin : this.getAdminId(),
app : this.getId(),
apiKey,
templateIds
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editBannersCustomization = async ({ banners, autoDisplay, fullWidth, language, useStandardLanguage }) => {
try{
let res = await ConnectionSingleton.editBannersCustomization({
params : {
admin : this.getAdminId(),
app : this.getId(),
banners,
autoDisplay,
fullWidth,
language,
useStandardLanguage
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editEsportsPageCustomization = async ({ link_url, button_text, title, subtitle }) => {
try{
let res = await ConnectionSingleton.editEsportsPageCustomization({
params: {
admin: this.getAdminId(),
app: this.getId(),
link_url,
button_text,
title,
subtitle
},
headers: authHeaders(this.getBearerToken(), this.getAdminId())
});
return res;
}catch(err){
throw err;
}
}
editLogoCustomization = async ({logo}) => {
try{
let res = await ConnectionSingleton.editLogoCustomization({
params : {
admin : this.getAdminId(),
app : this.getId(),
logo
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editBackgroundCustomization = async ({background}) => {
try{
let res = await ConnectionSingleton.editBackgroundCustomization({
params : {
admin : this.getAdminId(),
app : this.getId(),
background
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editVirtualCurrency = async ({params}) => {
try{
let res = await ConnectionSingleton.editVirtualCurrency({
params : {
admin : this.getAdminId(),
app : this.getId(),
...params
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
return res;
}catch(err){
throw err;
}
}
editFaviconCustomization = async ({topIcon}) => {
try{
let res = await ConnectionSingleton.editFaviconCustomization({
params : {
admin : this.getAdminId(),
app : this.getId(),
topIcon
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editLoadingGifCustomization = async ({loadingGif}) => {
try{
let res = await ConnectionSingleton.editLoadingGifCustomization({
params : {
admin : this.getAdminId(),
app : this.getId(),
loadingGif
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editThemeCustomization = async ({theme}) => {
try{
let res = await ConnectionSingleton.editThemeCustomization({
params : {
admin : this.getAdminId(),
app : this.getId(),
theme
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editColorsCustomization = async ({colors}) => {
try{
/* Cancel Withdraw Response */
let res = await ConnectionSingleton.editColorsCustomization({
params : {
admin : this.getAdminId(),
app : this.getId(),
colors
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editFooterCustomization = async ({communityLinks, supportLinks, language, useStandardLanguage }) => {
try{
let res = await ConnectionSingleton.editFooterCustomization({
params : {
admin : this.getAdminId(),
app : this.getId(),
communityLinks,
supportLinks,
language,
useStandardLanguage
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
return res;
}catch(err){
throw err;
}
}
editSocialLinksCustomization = async ({ social_link_id, links }) => {
try{
let res = await ConnectionSingleton.editSocialLinksCustomization({
params : {
admin : this.getAdminId(),
app : this.getId(),
social_link_id,
links
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
return res;
}catch(err){
throw err;
}
}
editTopTabCustomization = async ({ topTabParams, isTransparent, language, useStandardLanguage }) => {
try{
let res = await ConnectionSingleton.editTopTabCustomization({
params : {
admin: this.getAdminId(),
app: this.getId(),
topTabParams,
isTransparent,
language,
useStandardLanguage
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
return res;
}catch(err){
throw err;
}
}
editIconsCustomization = async ({ icon_id, icons, useDefaultIcons }) => {
try{
let res = await ConnectionSingleton.editIconsCustomization({
params : {
admin: this.getAdminId(),
app: this.getId(),
icon_id,
icons,
useDefaultIcons: useDefaultIcons
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
return res;
}catch(err){
throw err;
}
}
editSubsectionsCustomization = async ({ subSections, language, useStandardLanguage }) => {
try{
let res = await ConnectionSingleton.editSubsectionsCustomization({
params : {
admin: this.getAdminId(),
app: this.getId(),
subSections,
language,
useStandardLanguage
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
return res;
}catch(err){
throw err;
}
}
editGameImage = async ({image_url, game}) => {
try{
let res = await ConnectionSingleton.editGameImage({
params : {
admin : this.getAdminId(),
app : this.getId(),
image_url,
game
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editBackgroundImage = async ({background_url, game}) => {
try{
let res = await ConnectionSingleton.editBackgroundImage({
params : {
admin : this.getAdminId(),
app : this.getId(),
background_url,
game
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
createProvider = async ({ provider_id }) => {
try{
let res = await ConnectionSingleton.createProvider({
params : {
admin : this.getAdminId(),
app : this.getId(),
provider_id,
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
editProvider = async ({ providerParams }) => {
try{
let res = await ConnectionSingleton.editProvider({
params : {
admin : this.getAdminId(),
app : this.getId(),
providerParams,
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
/* Update App Info Async */
await this.updateAppInfoAsync();
return res;
}catch(err){
throw err;
}
}
confirmUserAction = async ({ id }) => {
try{
return await ConnectionSingleton.confirmUserAction(
{
params: {
user: id,
admin: this.getAdminId(),
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
cancelWithdraw = async () => {
try{
/* Cancel Withdraw Response */
return await ConnectionSingleton.cancelWithdraw({
admin : this.getAdminId(),
app : this.getId(),
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
getAllGameProviders = async () => {
try {
return await ConnectionSingleton.getAllGameProviders();
} catch(err) {
throw err;
}
}
getGamesAsync = async ({currency}) => {
try{
return await ConnectionSingleton.getGames({
params : {
admin : this.getAdminId(),
app : this.getId(),
currency
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
getUserBets = async ({user, filters}) => {
try{
return await ConnectionSingleton.getUserBets({
params : {
user,
..._.pickBy(filters, identity),
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
getAllBets = async ({ filters }) => {
try{
return await ConnectionSingleton.getAllBets({
params : {
..._.pickBy(filters, identity),
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
getLogs = async ({ filters }) => {
try{
return await ConnectionSingleton.getLogs({
params : {
...filters,
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
addCurrencyWallet = async ({ currency }) => {
try{
let res = await ConnectionSingleton.addCurrencyWallet({
params : {
admin : this.getAdminId(),
app : this.getId(),
currency_id : currency._id
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
await setCurrencyView(currency)
return res;
}catch(err){
throw err;
}
}
getEcosystemVariables = async () => {
try{
return await ConnectionSingleton.getEcosystemVariables();
}catch(err){
throw err;
}
}
getEcosystemLanguages = async () => {
try{
return await ConnectionSingleton.getEcosystemLanguages();
}catch(err){
throw err;
}
}
getEcosystemSkins = async () => {
try{
return await ConnectionSingleton.getEcosystemSkins();
}catch(err){
throw err;
}
}
editEdge = async ({game, edge}) => {
try{
return await ConnectionSingleton.editEdge({
admin : this.getAdminId(),
app : this.getId(),
game,
edge,
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
editVideogamesEdge = async ({ esports_edge }) => {
try{
return await ConnectionSingleton.editVideogamesEdge({
admin : this.getAdminId(),
app : this.getId(),
esports_edge: parseFloat(esports_edge),
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
changeMaxDeposit = async ({amount, wallet_id}) => {
try{
let res = await ConnectionSingleton.changeMaxDeposit({
params : {
admin : this.getAdminId(),
app : this.getId(),
amount,
wallet_id : wallet_id
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
let {
status
} = res.data;
if(parseInt(status) == 200){
return true;
}else{
throw new Error(res.data.message);
}
}catch(err){
console.log(err);
throw err;
}
}
changeMaxWithdraw = async ({amount, wallet_id}) => {
try{
let res = await ConnectionSingleton.changeMaxWithdraw({
params : {
admin : this.getAdminId(),
app : this.getId(),
amount,
wallet_id : wallet_id
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
let {
status
} = res.data;
if(parseInt(status) == 200){
return true;
}else{
throw new Error(res.data.message);
}
}catch(err){
console.log(err);
throw err;
}
}
changeMinWithdraw = async ({amount, wallet_id}) => {
try{
let res = await ConnectionSingleton.changeMinWithdraw({
params : {
admin : this.getAdminId(),
app : this.getId(),
amount,
wallet_id : wallet_id
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
let {
status
} = res.data;
if(parseInt(status) == 200){
return true;
}else{
throw new Error(res.data.message);
}
}catch(err){
console.log(err);
throw err;
}
}
changeAffiliateMinWithdraw = async ({amount, wallet_id}) => {
try{
let res = await ConnectionSingleton.changeAffiliateMinWithdraw({
params : {
admin : this.getAdminId(),
app : this.getId(),
amount,
wallet_id : wallet_id
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
let {
status
} = res.data;
if(parseInt(status) == 200){
return true;
}else{
throw new Error(res.data.message);
}
}catch(err){
console.log(err);
throw err;
}
}
getSummaryData(type){
const state = store.getState();
const { summary } = state;
switch (type) {
case 'users':
return { data: summary.users, type: type }
case 'games':
return { data: summary.games, type: type }
case 'bets':
return { data: summary.bets, type: type }
case 'revenue':
return { data: summary.revenue, type: type }
case 'wallet':
return { data: summary.wallet, type: type }
default:
return { data: this.data.summary[type], type: type };
}
}
getCurrencyTicker = () => {
const state = store.getState();
const { currency } = state;
return currency.ticker ? currency.ticker : 'N/A';
}
getCurrency = () => {
const state = store.getState();
const { currency } = state;
return currency;
}
getVersion = () => this.params.version;
getManagerAddress = () => this.params.address;
getOwnerAddress = () => {console.log(this.params); return this.params.ownerAddress;}
getUnconfirmedBlockchainDeposits = async (address) => {
try{
var platformAddress = this.getInformation('platformAddress');
var platformTokenAddress = this.getInformation('platformTokenAddress');
var allTxs = (await getPastTransactions(address)).result;
let unconfirmedDepositTxs = (await Promise.all(allTxs.map( async tx => {
let res_transaction = await window.web3.eth.getTransaction(tx.hash);
let transactionData = getTransactionDataERC20(res_transaction);
if(!transactionData){return null}
return {
amount: Numbers.fromDecimals(transactionData.tokenAmount, this.params.decimals),
to : tx.to,
tokensTransferedTo : transactionData.tokensTransferedTo,
creation_timestamp: tx.timestamp,
transactionHash: tx.hash
}
}))).filter(el => el != null).filter( tx => {
return (
new String(tx.to).toLowerCase().trim() == new String(platformTokenAddress).toLowerCase().trim()
&& new String(tx.tokensTransferedTo).toLowerCase().trim() == new String(platformAddress).toLowerCase().trim()
)
})
return unconfirmedDepositTxs;
// TO DO : Finalize
}catch(err){
throw err;
}
}
addGameToPlatform = async ({game}) => {
try{
return await ConnectionSingleton.addGameToPlatform({
params : {
admin : this.getAdminId(),
app : this.getId(),
game
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
addLanguage = async ({ prefix }) => {
try{
return await ConnectionSingleton.addLanguage({
params : {
admin : this.getAdminId(),
app : this.getId(),
prefix
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
addAddOn = async ({url}) => {
try{
return await ConnectionSingleton.addAddOn({
url: url,
params : {
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
editAutoWithdraw = async ({currency, autoWithdrawParams}) => {
try{
return await ConnectionSingleton.editAutoWithdraw({
params : {
currency,
autoWithdrawParams,
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
editTxFee = async ({currency, txFeeParams}) => {
try{
return await ConnectionSingleton.editTxFee({
params : {
currency,
txFeeParams,
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
editDepositBonus = async ({currency, depositBonusParams}) => {
try{
return await ConnectionSingleton.editDepositBonus({
params : {
currency,
depositBonusParams,
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
editPointSystem = async ({ currency, pointSystemParams }) => {
try{
return await ConnectionSingleton.editPointSystem({
params : {
currency,
pointSystemParams,
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
editFreeCurrency = async ({ activated, currency, time, value, multiplier }) => {
try{
return await ConnectionSingleton.editFreeCurrency({
params : {
activated,
currency,
time,
value,
multiplier,
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
convertPoints = async ({ currency, user, isAbsolut }) => {
try{
return await ConnectionSingleton.convertPoints({
params : {
currency,
user,
isAbsolut,
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
editJackpot = async ({edge}) => {
try{
return await ConnectionSingleton.editJackpot({
params : {
edge,
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
editInitialBalance = async ({ balance, currency, multiplier }) => {
try{
return await ConnectionSingleton.editInitialBalance({
params : {
balance,
multiplier,
currency,
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
modifyUserBalance = async ({ user, wallet, currency, newBalance, reason }) => {
try{
return await ConnectionSingleton.modifyUserBalance({
params : {
user,
wallet,
currency,
newBalance,
reason,
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
editRestrictedCountries = async ({countries}) => {
try{
return await ConnectionSingleton.editRestrictedCountries({
params : {
countries,
admin : this.getAdminId(),
app : this.getId()
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
}catch(err){
throw err;
}
}
getComplianceFile = async ({ size=200, offset=0, begin_at, end_at }) => {
try{
let res = await ConnectionSingleton.getComplianceFile({
params : {
admin : this.getAdminId(),
app : this.getId(),
size,
offset,
begin_at,
end_at
},
headers : authHeaders(this.getBearerToken(), this.getAdminId())
});
return res;
}catch(err){
throw err;
}
}
getEcosystemGames = async () => {
try{
return (await ConnectionSingleton.getEcosystemGames()).data.message;
}catch(err){
throw err;
}
}
getEcosystemCurrencies = async () => {
try{
return (await ConnectionSingleton.getEcosystemVariables()).data.message.currencies;
}catch(err){
throw err;
}
}
getEcosystemCroupier = async () => {
try{
return (await ConnectionSingleton.getEcosystemVariables()).data.message.addresses[0].address
}catch(err){
throw err;
}
}
// Esports services
hasEsportsPermission = () => {
const ESPORTS_API_URL = process.env.REACT_APP_API_ESPORTS;
const WEBSOCKET_ESPORTS_URL = process.env.REACT_APP_WEBSOCKET_ESPORTS;
return (!_.isEmpty(ESPORTS_API_URL) && !_.isEmpty(WEBSOCKET_ESPORTS_URL))
}
getVideoGamesAll = async () => {
try {
await getVideoGamesAll({
params:{
admin: this.getAdminId()
},
headers: authHeaders(this.getBearerToken(), this.getAdminId())
})
} catch (err) {
throw err;
}
}
getAllVideogames = async () => {
try {
const res = await getAllVideogames({
params:{
admin: this.getAdminId()
},
headers: authHeaders(this.getBearerToken(), this.getAdminId())
})
return res;
} catch (err) {
throw err;
}
}
getMatchesAll = async ({ filters, isPagination=false }) => {
try {
await getMatchesAll({
params: {
admin: this.getAdminId(),
..._.pickBy(filters, _.identity)
},
headers: authHeaders(this.getBearerToken(), this.getAdminId()),
isPagination
})
} catch (err) {
throw err;
}
}
getMatchesAll = async ({ filters, isPagination=false }) => {
try {
await getMatchesAll({
params: {
admin: this.getAdminId(),
..._.pickBy(filters, _.identity)
},
headers: authHeaders(this.getBearerToken(), this.getAdminId()),
isPagination
})
} catch (err) {
throw err;
}
}
getBookedMatches = async ({ filters, isPagination=false }) => {
try {
await getBookedMatches({
params: {
admin: this.getAdminId(),
..._.pickBy(filters, _.identity)
},
headers: authHeaders(this.getBearerToken(), this.getAdminId()),
isPagination
})
} catch (err) {
throw err;
}
}
getSpecificMatch = async ({ match_id }) => {
try {
return await getSpecificMatch({
params:{
admin: this.getAdminId(),
match_id
},
headers: authHeaders(this.getBearerToken(), this.getAdminId())
})
} catch (err) {
throw err;
}
}
getSeriesMatches = async ({ filters, isPagination=false }) => {
try {
await getSeriesMatches({
params: {
admin: this.getAdminId(),
..._.pickBy(filters, _.identity)
},
headers: authHeaders(this.getBearerToken(), this.getAdminId()),
isPagination
})
} catch (err) {
throw err;
}
}
getBookedSeriesMatches = async ({ filters, isPagination=false }) => {
try {
await getBookedSeriesMatches({
params: {
admin: this.getAdminId(),
..._.pickBy(filters, _.identity)
},
headers: authHeaders(this.getBearerToken(), this.getAdminId()),
isPagination
})
} catch (err) {
throw err;
}
}
setBookedMatch = async ({ match_external_id }) => {
try {
return await setBookedMatch({
params:{
admin: this.getAdminId(),
app: this.getId(),
match_external_id
},
headers: authHeaders(this.getBearerToken(), this.getAdminId())
})
} catch (err) {
throw err;
}
}
removeBookedMatch = async ({ match_external_id }) => {
try {
return await removeBookedMatch({
params:{
admin: this.getAdminId(),
app: this.getId(),
match_external_id
},
headers: authHeaders(this.getBearerToken(), this.getAdminId())
})
} catch (err) {
throw err;
}
}
getTeamStats = async ({ slug, team_id }) => {
try {
return await getTeamStats({
params: {
admin: this.getAdminId(),
slug,
team_id
},
headers: authHeaders(this.getBearerToken(), this.getAdminId())
})
} catch (err) {
throw err;
}
}
getPlayerStats = async ({ slug, player_id }) => {
try {
return await getPlayerStats({
params: {
admin: this.getAdminId(),
slug,
player_id
},
headers: authHeaders(this.getBearerToken(), this.getAdminId())
})
} catch (err) {
throw err;
}
}
}
function authHeaders(bearerToken, id){
return {
"authorization" : "Bearer " + bearerToken,
"payload" : JSON.stringify({ id : id })
}
}
export default App;
<file_sep>/src/containers/Layout/topbar/TopBarCurrencyView.js
import React from 'react';
import { Collapse } from 'reactstrap';
import DownIcon from 'mdi-react/ChevronDownIcon';
import { setLoadingStatus } from '../../../redux/actions/loadingAction';
import { setCurrencyView } from '../../../redux/actions/currencyReducer';
import { connect } from "react-redux";
import _ from 'lodash';
import store from '../../App/store';
const renderCurrency = ({currency}) => (
<span className="topbar__language-btn-title" style={{height : 20}}>
<img src={currency.image} style={{width : 18, height : 'auto', marginRight: 8 }} alt="image" />
<p style={{marginTop : -3}}>{currency.ticker}</p>
</span>
)
const selectCurrency = () => (
<span className="topbar__language-btn-title" style={{height : 20}}>
<p style={{marginTop : -3}}>CURRENCY</p>
</span>
)
class TopBarCurrencyView extends React.Component {
constructor(props) {
super(props);
this.state = {
currencies : [],
collapse: false,
mainButtonContent: null
};
}
componentDidMount(props){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData(props){
var { profile, currency } = props;
const { virtual } = profile.getApp().getParams();
const currencies = profile.getApp().getSummaryData('walletSimple').data;
this.setState({
currencies: currencies ? currencies.map( w => w.currency).filter(c => (virtual === false && !c.hasOwnProperty('virtual') || c.virtual === virtual)) : [],
currency,
mainButtonContent : !_.isEmpty(currency) ? renderCurrency({currency : currency}) : selectCurrency()
});
}
toggle = () => {
this.setState({ collapse: !this.state.collapse });
};
changeCurrency = async ({currency}) => {
store.dispatch(setLoadingStatus(true));
await store.dispatch(setCurrencyView(currency));
this.toggle();
await this.props.profile.getApp().getSummary();
this.props.profile.update();
store.dispatch(setLoadingStatus(false));
};
render() {
const { currencies } = this.state;
return (
<div className="topbar__collapse topbar__collapse--language">
<button className="topbar__btn" onClick={this.toggle}>
{currencies.length > 0
?
this.state.mainButtonContent
:
<span className="topbar__currency-btn-title" style={{height : 20}}>
<p style={{marginTop : -3}}>No currencies installed</p>
</span>
}
<DownIcon className="topbar__icon" />
</button>
{currencies.length
?
<Collapse
isOpen={this.state.collapse}
className="topbar__collapse-content topbar__collapse-content--language"
>
{currencies.map( c => {
return (
<button
className="topbar__language-btn"
type="button"
onClick={() => this.changeCurrency({currency : c})}
key={c.id}
>
{renderCurrency({currency : c})}
</button>
)
})}
</Collapse>
:
null
}
</div>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile,
currency : state.currency
};
}
export default connect(mapStateToProps)(TopBarCurrencyView);
<file_sep>/src/containers/Bets/components/EsportsBetContainer/index.js
import React from 'react';
import { connect } from "react-redux";
import { ButtonBase, Dialog, DialogContent, Button, Grid } from '@material-ui/core';
import { Row, Col } from 'reactstrap';
import _ from 'lodash';
import { CloseIcon, TableIcon, JsonIcon } from 'mdi-react';
import { DialogHeader, CloseButton, Title, VideoGameIcon, MatchesContainer, Score, TeamOne, TeamTwo, Result, ResultValue, Draw, SerieInfo, DateInfo, Time, Date as DateSpan, WonResult } from './styles';
import moment from 'moment';
import { CSVLink } from 'react-csv';
import { Button as MaterialButton } from "@material-ui/core";
import { export2JSON } from '../../../../utils/export2JSON';
import { Carousel } from 'antd';
import { opponents } from './data';
import Avatar from 'react-avatar';
import Match from './Match';
class EsportsBetContainer extends React.Component {
constructor() {
super();
this.state = {
open: false,
bet: {},
isLoading: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { bet } = props;
if (!_.isEmpty(this.state.bet)) {
if (!_.isEmpty(bet)) {
this.setState({
bet: bet
})
} else {
this.setState({
bet: {}
})
}
}
}
setOpen = async () => {
const { bet } = this.props;
if (_.isEmpty(this.state.bet)) {
if (!_.isEmpty(bet)) {
this.setState({
bet: bet,
open: true
})
}
}
}
setClose = () => {
this.setState({
open: false,
bet: {}
})
}
render() {
const { open, bet } = this.state;
const { _id, user, currency, videogames, isWon, betAmount, winAmount, creation_timestamp, result } = bet;
// const [teamOne, teamTwo] = opponents;
let csvData = [{}];
let jsonData = [];
let headers = []
if (!_.isEmpty(user)) {
const data = [
{
_id: _id,
user: user.username,
currency: currency.name,
betAmount: betAmount ? parseFloat(betAmount).toFixed(6) : 0,
winAmount: winAmount ? parseFloat(winAmount).toFixed(6) : 0,
creation_timestamp: creation_timestamp
}
]
headers = [
{ label: "Id", key: "_id" },
{ label: "User", key: "user" },
{ label: "Currency", key: "currency" },
{ label: "Bet Amount", key: "betAmount" },
{ label: "Win Amount", key: "winAmount" },
{ label: "Created At", key: "creation_timestamp" }
];
if (!_.isEmpty(data)) {
csvData = data.map(row => ({...row, creation_timestamp: moment(row.creation_timestamp).format("lll")}));
jsonData = csvData.map(row => _.pick(row, ['_id', 'user', 'currency', 'betAmount', 'winAmount', 'creation_timestamp']));
}
}
return(
<>
<ButtonBase onClick={this.setOpen}>
{this.props.children}
</ButtonBase>
{ !_.isEmpty(bet) ?
<Dialog
// disableBackdropClick
open={open}
onClose={this.setClose}
>
<DialogHeader style={{ paddingBottom: 0 }}>
<div style={{ display: "flex", justifyContent: "flex-start", marginRight: 20 }}>
<CSVLink data={csvData} filename={"bet.csv"} headers={headers}>
<MaterialButton variant="contained" size="small" style={{ textTransform: "none", backgroundColor: "#008000", color: "#ffffff", boxShadow: "none", margin: 10}}>
<TableIcon style={{marginRight: 7}}/> CSV
</MaterialButton>
</CSVLink>
<MaterialButton onClick={() => export2JSON(jsonData, "bet")} variant="contained" size="small" style={{ textTransform: "none", boxShadow: "none", margin: 10}}>
<JsonIcon style={{marginRight: 7}}/> JSON
</MaterialButton>
</div>
<CloseButton onClick={this.setClose}>
<CloseIcon/>
</CloseButton>
</DialogHeader>
<DialogContent style={{ paddingTop: 0, maxWidth: 450 }}>
<Row>
{/* <Col sd={12} md={12} lg={12} style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<div style={{ display: "flex", justifyContent: "flex-start", alignItems: "center" }}>
<VideoGameIcon>
{ videogame.icon }
</VideoGameIcon>
<h5>{videogame.name}</h5>
<hr/>
</div>
</Col> */}
<Col sd={12} md={12} lg={12} style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<h5 style={{marginTop : 5}}> {user.username}
</h5>
<p className='text-small'> {creation_timestamp} </p>
<hr/>
</Col>
{ result.map(match => (
<Match data={match}/>
))}
</Row>
<Grid container direction="row" style={{ margin: "15px 0px" }}>
<Grid item xs>
<div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<h5 style={{margin: 5}}>Bet Amount</h5>
<div style={{display: 'flex'}}>
<h5 style={{margin: 5}}>{betAmount.toFixed(6)}</h5>
<img src={currency.image} style={{ width : 25, height : 25}} alt={currency.name}/>
</div>
</div>
</Grid>
<Grid item xs>
<div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<h5 style={{margin: 5}}>Win Amount</h5>
<div style={{display: 'flex'}}>
<h5 style={{margin: 5}}>{winAmount.toFixed(6)}</h5>
<img src={currency.image} style={{ width : 25, height : 25}} alt={currency.name}/>
</div>
</div>
</Grid>
</Grid>
{/* <Row style={{ marginTop: 20 }}>
<Col sd={12} md={12} lg={6} style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<h5 style={{margin: 5}}>Server Seed</h5>
<p className='text-small'> {serverSeed} </p>
</Col>
<Col sd={12} md={12} lg={6} style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<h5 style={{margin: 5}}>Client Seed</h5>
<p className='text-small'> {clientSeed} </p>
</Col>
</Row>
<Row style={{ marginTop: 20, paddingBottom: 30 }}>
<Col sd={12} md={12} lg={12} style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<h5 style={{margin: 5}}>Server Hashed Seed</h5>
<div style={{ width: "99%", marginTop: 10 }}>
<p className='text-small' style={{ padding: "0px 20px", overflowWrap: "break-word" }}> {serverHashedSeed} </p>
</div>
</Col>
</Row> */}
</DialogContent>
</Dialog> : null }
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(EsportsBetContainer);<file_sep>/src/containers/Applications/EsportsPage/components/Icons/Status.js
import React from "react";
import matchStatus from '../Enums/status';
const Status = props => {
const { status } = props;
return (
<svg
fill="none"
viewBox="0 0 234 26"
id="9674855289a3943b51dcc520de928f73"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M234 0H0v5h1.01a30 30 0 0120.78 8.362l3.655 3.51a30 30 0 0020.78 8.361h141.473a29.999 29.999 0 0020.009-7.648l5.516-4.937A29.997 29.997 0 01233.232 5H234V0z"
fill={matchStatus[status].backgroundColor}
/>
<text x="50%" y="50%" text-anchor="middle" fill={matchStatus[status].textColor} dy=".3em">{(matchStatus[status].text).toUpperCase()}</text>
</svg>
);
};
export default Status;
<file_sep>/src/containers/Layout/sidebar/SidebarLink.jsx
import React from 'react';
import PropTypes from 'prop-types';
import { NavLink } from 'react-router-dom';
import styled from 'styled-components';
import { ButtonBase } from '@material-ui/core';
const Icon = styled.section`
height: 24px;
width: 24px;
`;
const SidebarLink = ({
title, icon, route, onClick, disabled
}) => (
<ButtonBase>
<NavLink
to={disabled ? '#' : route}
onClick={onClick}
activeClassName={disabled ? "sidebar__link__not_active" : "sidebar__link-active"}
>
<div style={{ opacity : disabled ? 0.4 : 1 }} className={disabled ? "sidebar__link__not_active" : "sidebar__link"}>
<Icon>
{icon}
</Icon>
{!disabled ?
<p className={"sidebar__link-title"}>
{title}
</p>
: null}
</div>
</NavLink>
</ButtonBase>
);
SidebarLink.propTypes = {
title: PropTypes.string.isRequired,
icon: PropTypes.string,
newLink: PropTypes.bool,
route: PropTypes.string,
onClick: PropTypes.func,
};
SidebarLink.defaultProps = {
icon: '',
newLink: false,
route: '/',
onClick: () => {},
};
export default SidebarLink;
<file_sep>/src/redux/reducers/modalReducer.js
const initialState = {
isActive : false
};
export default function (state = initialState, action) {
switch (action.type) {
case 'SET_MODAL' :
return {...state, ...action.action, isActive : true}
case 'CLOSE_MODAL' :
return {isActive : false}
default:
return state;
}
}
<file_sep>/src/shared/components/color_picker_input/ColorPickerInput.js
import React from 'react';
import { CompactPicker } from 'react-color';
import './ColorPickerInput.css';
const defaultState = {
background: '#000'
}
class ColorPickerInput extends React.Component {
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { color } = props;
this.setState({ background : color })
}
onChange = (color) => {
this.props.onChange({type : this.props.name, value : color.hex});
};
render() {
return (
<div disabled={this.props.disabled} className='colorContainer' >
<h4 className='title'>{this.props.label}</h4>
<CompactPicker
color={ this.state.background }
onChangeComplete={this.onChange}
/>
</div>
);
}
}
export default ColorPickerInput;
<file_sep>/src/redux/actions/videogamesActions.js
export const actions = Object.freeze({
SET_VIDEOGAMES_DATA: "SET_VIDEOGAMES_DATA"
})
export function setVideogamesData(data) {
return {
type: actions.SET_VIDEOGAMES_DATA,
payload: data
}
}<file_sep>/src/containers/Dashboards/Default/index.jsx
import React from 'react';
import Fade from '@material-ui/core/Fade';
import _ from 'lodash';
import { compose } from 'lodash/fp';
import PropTypes, { string } from 'prop-types';
import { translate } from 'react-i18next';
import { connect } from "react-redux";
import { Col, Container, Row } from 'reactstrap';
import { setLoadingStatus } from '../../../redux/actions/loadingAction';
import store from '../../App/store';
import DataWidget from '../../DataWidget/DataWidget';
import NoData from '../../NoData';
import BetsStatistics from './components/BetsStatistics';
import BounceRateArea from './components/BounceRateArea';
import CompanyId from './components/CompanyId';
import LiquidityWalletWidget from './components/LiquidityWalletWidget';
import ProfitResume from './components/ProfitResume';
import RevenueChart from './components/RevenueChart';
import TurnoverResume from './components/TurnoverResume';
import VisitorsSessions from './components/VisitorsSessions';
class DefaultDashboard extends React.Component{
constructor(props){
super(props);
this.state = {
isDeployed : false,
periodicity : 'Daily',
currency : {}
}
}
componentDidMount(){
const { history } = this.props;
if (history && history.action === "POP") {
this.asyncCalls();
}
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData(props){
const { profile, periodicity } = props;
const app = profile.getApp();
let isDeployed = !_.isUndefined(app.isDeployed());
this.setState({...this.state, isDeployed, periodicity});
}
asyncCalls = async () => {
const { profile } = this.props;
store.dispatch(setLoadingStatus(true));
await profile.getApp().getSummary();
await profile.update();
store.dispatch(setLoadingStatus(false));
}
render = () => {
const { isDeployed } = this.state;
const { periodicity, currency, isLoading, profile } = this.props;
const revenue = profile.getApp().getSummaryData('revenue');
const wallet = profile.getApp().getSummaryData('wallet');
const users = profile.getApp().getSummaryData('games');
const bets = profile.getApp().getSummaryData('bets');
return (
<Fade in timeout={{ appear: 200, enter: 200, exit: 200 }}>
<Container className="dashboard">
<Row>
{ wallet && (
<Col lg={3}>
<CompanyId currency={currency} app={this.props.profile.getApp()} data={{
wallet : wallet
}} />
</Col>
)}
{ wallet && (
<Col lg={3}>
<DataWidget>
<LiquidityWalletWidget currency={currency} isLoading={isLoading} data={wallet} />
</DataWidget>
</Col>
)}
{ revenue && wallet && (
<Col lg={3}>
<DataWidget>
<ProfitResume currency={currency} periodicity={periodicity} isLoading={isLoading} data={{
revenue : revenue,
wallet : wallet,
}} />
</DataWidget>
</Col>
)}
{ revenue && wallet && (
<Col lg={3}>
<DataWidget>
<TurnoverResume currency={currency} periodicity={periodicity} isLoading={isLoading} data={{
revenue : revenue,
wallet : wallet,
}} />
</DataWidget>
</Col>
)}
</Row>
{ isDeployed ?
<div>
<Row>
{ revenue && wallet && (
<Col lg={12}>
<DataWidget>
<RevenueChart currency={currency} periodicity={periodicity} isLoading={isLoading} data={{
revenue : revenue,
wallet : wallet,
}}
/>
</DataWidget>
</Col>
)}
</Row>
<Row>
{ bets && wallet && (
<Col md={6}>
<DataWidget>
<BetsStatistics currency={currency} periodicity={periodicity} isLoading={isLoading} data={{
bets : bets,
wallet : wallet
}}/>
</DataWidget>
</Col>
)}
{ !_.isNull(users.data) && (typeof users.data !== 'string') && bets && wallet && (
<Col md={6}>
<DataWidget>
<VisitorsSessions currency={currency} periodicity={periodicity} isLoading={isLoading} data={{
users : users,
bets : bets,
wallet : wallet
}}/>
</DataWidget>
</Col>
)}
<Col md={4}>
<DataWidget>
<BounceRateArea currency={currency} />
</DataWidget>
</Col>
</Row>
</div>
:
<div>
<NoData {...this.props} app={this.props.profile.getApp()}/>
</div>
}
</Container>
</Fade>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
periodicity : state.periodicity,
currency : state.currency,
isLoading: state.isLoading
};
}
DefaultDashboard.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(DefaultDashboard);
<file_sep>/src/containers/Account/Register/index.jsx
import React from 'react';
import { Link } from 'react-router-dom';
import RegisterForm from './components/RegisterForm';
import { Col, Row } from 'reactstrap';
import { BasicNotification } from '../../../shared/components/Notification';
import NotificationSystem from 'rc-notification';
import TextLoop from 'react-text-loop';
import { BackgroundBox, VerticalSection, Container, BetProtocolLogo, Card, CardHeader, CardContent, Footer } from './styles';
const Back = `${process.env.PUBLIC_URL}/img/dashboard/background-login.png`;
let notification = null;
const showNotification = (message) => {
notification.notice({
content: <BasicNotification
title="There is a problem with your Registering"
message={message}
/>,
duration: 5,
closable: true,
style: { top: 0, left: 'calc(100vw - 100%)' },
className: 'right-up',
});
};
const words = [
{ id: 0, text: 'BetProtocol' },
{ id: 1, text: 'Scalable' },
{ id: 2, text: 'Secure & Audited' },
{ id: 3, text: 'No Coding Required' },
];
const Description = (props) => {
const { wordList } = props;
return (
<TextLoop>
{wordList.map((word) => (
<span key={word.id}>{word.text}</span>
))}
</TextLoop>
);
};
class Register extends React.Component{
constructor(props){super(props)}
componentDidMount() {
NotificationSystem.newInstance({}, n => notification = n);
}
componentWillUnmount() {
notification.destroy();
}
showNotification = (message) => {
showNotification(message)
}
render = () => {
return (
<>
<BackgroundBox>
<VerticalSection>
<ul>
<BetProtocolLogo />
<Description wordList={words} />
</ul>
<Container>
<Card>
<CardHeader />
<CardContent>
<h1>Register</h1>
<RegisterForm showNotification={this.showNotification} handleSubmit={(e) => e.preventDefault()} {...this.props} onSubmit={false} />
<div className="account__have-account">
<p>Already have an account? <Link to="/login">Login</Link></p>
</div>
</CardContent>
</Card>
<Footer>
<span>
<b>@BetProtocol</b> Technology is a SaaS Platform that provides
infrastructure for Gaming Applications
</span>
</Footer>
</Container>
</VerticalSection>
</BackgroundBox>
</>
)
}
};
{/* <div className={'container__all'}>
<Row className={'container__all'} style={{marginTop : '10%'}}>
<Col lg={6} className={'login_background'}>
<img className="login_background" src={Back} />
</Col>
<Col lg={6}>
<div className="account__wrapper">
<div className="account__card">
<RegisterForm showNotification={this.showNotification} handleSubmit={(e) => e.preventDefault()} {...this.props} onSubmit={false} />
<div className="account__have-account">
<p>Already have an account? <Link to="/login">Login</Link></p>
</div>
</div>
</div>
</Col>
</Row>
</div>
*/}
export default Register;
<file_sep>/src/containers/Users/UserPage/components/EsportsBetContainer/styles.js
import styled from 'styled-components';
import { ButtonBase } from '@material-ui/core';
export const DialogHeader = styled.section`
width: 100%;
padding: 10px 20px;
margin-bottom: 20px;
display: flex;
justify-content: flex-end;
`;
export const Title = styled.h1`
margin-top: 0px;
font-family: Poppins;
font-size: 18px;
`;
export const CloseButton = styled(ButtonBase)``;
export const VideoGameIcon = styled.section`
height: 25px;
width: 25px;
margin: 0px 5px;
`;
export const MatchesContainer = styled.div`
height: 160px;
width: 100%;
min-width: 402px;
margin: 10px 5px;
padding: 5px;
background-color: #FAFCFF;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
`;
export const Score = styled.section`
width: 100%;
min-height: 75px;
display: grid;
grid-template-areas:
'teamOne date teamTwo';
grid-template-columns: 40% 20% 40%;
grid-template-rows: auto;
align-self: center;
justify-self: center;
`;
export const TeamOne = styled.section`
grid-area: teamOne;
display: flex;
align-items: center;
justify-content: flex-end;
img {
height: auto;
width: 35px;
}
span {
margin: 0px 7px;
font-family: Poppins;
font-size: 13px;
&:last-child {
margin: 0px;
}
}
`;
export const TeamTwo = styled.section`
grid-area: teamTwo;
display: flex;
align-items: center;
justify-content: flex-start;
img {
height: auto;
width: 35px;
}
span {
margin: 0px 7px;
font-family: Poppins;
font-size: 13px;
&:first-child {
margin: 0px;
}
}
`;
export const Result = styled.section`
grid-area: date;
display: flex;
align-items: center;
justify-content: space-evenly;
padding: 0px 10px;
span {
font-family: Poppins;
font-size: 14px;
color: #828282;
}
`;
export const ResultValue = styled.span`
margin: 0px 8px;
font-family: Poppins !important;
font-size: 18px !important;
font-weight: 500;
color: ${props => props.color} !important;
`;
export const Draw = styled.div`
display: flex;
justify-content: center;
align-items: center;
width: 34px;
height: 19px;
border-radius: 3px;
background-color: #DFE1EC;
span {
font-family: Poppins !important;
font-size: 13px;
color: #333333 !important;
}
`;
export const SerieInfo = styled.section`
display: flex;
justify-content: space-between;
align-items: center;
padding: 0px 20px;
padding-right: 5px;
span {
padding-top: 10px;
color: rgb(95, 110, 133);
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.05em;
}
`;
export const DateInfo = styled.section`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-width: 120px;
`;
export const Time = styled.span`
font-family: Poppins;
margin-bottom: 3px;
font-size: 17px;
font-weight: 800;
color: rgb(95, 110, 133);
padding: 0px 8px;
`;
export const Date = styled.span`
font-family: Poppins;
font-size: 13px;
font-weight: 300;
color: rgb(95, 110, 133);
`;
export const WonResult = styled.div`
display: flex;
justify-content: center;
align-items: center;
height: 22px;
width: 70px;
margin: 5px;
font-family: Poppins;
font-size: 13px;
font-weight: 300;
color: ${props => props.textColor};
text-transform: capitalize;
background-color: ${props => props.backgroundColor};
border-radius: 5px;
`;<file_sep>/src/containers/App/GlobalStyles.js
import { createGlobalStyle } from 'styled-components';
export default createGlobalStyle`
p, h1, h2, h3, h4, h5, h6 {
margin-bottom: 0;
font-weight: 400;
}
a {
color: #894798;
}
`;<file_sep>/src/containers/Applications/AddOnPage/AddOnContainer/AddOn/Jackpot.js
/* eslint-disable react/no-array-index-key */
import React from 'react';
import { Card, CardBody, Col, Row } from 'reactstrap';
import Skeleton from "@material-ui/lab/Skeleton";
import { connect } from "react-redux";
import { Grid, ExpansionPanelDetails, ExpansionPanelSummary, ExpansionPanel, Paper, Dialog, DialogContent, Button } from '@material-ui/core';
import TextInput from '../../../../../shared/components/TextInput';
import EditLock from '../../../../Shared/EditLock';
import { ExpandMoreIcon, MoneyIcon, MedalIcon } from 'mdi-react';
import Slider from "./components/Slider"
import UserBetsTable from './components/UserBetsTable';
import _ from "lodash";
import WinnersTable from './components/WinnersTable';
import { LockWrapper } from '../../../../../shared/components/LockWrapper';
class Jackpot extends React.Component {
constructor() {
super();
this.state = {
lock: true,
loading: false,
newEdge: 0,
showWinnersDialog: false,
showBetsDialog: false
}
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
if (this.state.lock) {
this.projectData(props);
}
}
projectData = (props) => {
const { jackpot, currency } = props;
const { name, description, image_url, bets, winResult, edge } = jackpot;
const limits = jackpot.limits.find(l => l.currency === currency._id);
this.setState({...this.state,
name,
description,
image_url,
bets,
winResult,
limits,
edge
})
}
unlock = () => {
this.setState({...this.state, lock: false })
}
lock = () => {
this.setState({...this.state, lock: true })
}
onChangeEdge = (event) => {
this.setState({...this.state, newEdge: event.value ? parseFloat(event.value) : 0})
}
toggleWinnersDialog = () => {
this.setState({...this.state, showWinnersDialog: !this.state.showWinnersDialog})
}
toggleBetsDialog = () => {
this.setState({...this.state, showBetsDialog: !this.state.showBetsDialog})
}
confirmChanges = async () => {
const { profile } = this.props;
const { newEdge } = this.state;
this.setState({...this.state, loading: true })
await profile.getApp().editJackpot({edge: newEdge})
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({...this.state, loading: false })
this.lock()
}
render() {
const { currency, isLoading, profile } = this.props;
const { name, description, image_url, bets, winResult, edge, limits, newEdge, lock, showWinnersDialog, showBetsDialog } = this.state;
const isSuperAdmin = profile.User.permission.super_admin;
if (!limits) return null
return (
<Col style={{height: `100%`, padding: 0 }}>
{isLoading ? (
<>
<Card className='game-container'>
<CardBody className="dashboard__card-widget" style={{ width: 320, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<Grid container direction='row' spacing={1}>
<Grid item xs={9}>
<Skeleton variant="rect" height={29} style={{ marginTop: 10, marginBottom: 10 }}/>
</Grid>
<Grid item xs={3}>
<Skeleton variant="circle" width={50} height={50} style={{ marginBottom: 10, marginLeft: 'auto', marginRight: 0 }}/>
</Grid>
</Grid>
<Skeleton variant="rect" height={35} style={{ marginTop: 10, marginBottom: 10 }}/>
</CardBody>
</Card>
</>
) : (
<Card className='game-container'>
<Paper elevation={0} style={{width: '320px', padding: 5, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none"}}>
<ExpansionPanel elevation={0}>
<ExpansionPanelSummary
style={{width: '320px', height: '120px', padding: 20, paddingBottom: 0, paddingTop: 0, justifyContent: 'space-between'}}
expandIcon={<ExpandMoreIcon />}
aria-controls="jackpot-content"
id="jackpot-header"
>
<div style={{display: 'flex', justifyContent: 'space-between', width: "100%"}}>
<div className="dashboard__visitors-chart text-left">
<p className="dashboard__visitors-chart-title text-left" style={{fontSize : 20}}>{name}</p>
</div>
<img className='application__game__image' style={{width: '60px', margin: 0, padding: 0}} src={image_url}/>
</div>
</ExpansionPanelSummary>
<LockWrapper hasPermission={isSuperAdmin}>
<ExpansionPanelDetails style={{padding: 0}}>
<Col>
<div className="dashboard__visitors-chart text-left" style={{marginTop : 10}}>
<h5>{description}</h5>
</div>
<hr/>
<EditLock
unlockField={this.unlock}
lockField={this.lock}
confirmChanges={this.confirmChanges}
isLoading={this.state.loading}
locked={lock}>
<h5 className="">Pot</h5>
<div style={{ display: "flex"}}>
<h3 style={{marginTop: 20, marginRight: 0}} className={"dashboard__total-stat"}>{limits.pot.toFixed(6)}</h3>
<h3 style={{ fontSize: 17, marginLeft: 0 }} className={"dashboard__total-stat"}>{currency.ticker}</h3>
</div>
<Dialog open={showWinnersDialog} onClose={this.toggleWinnersDialog} fullWidth maxWidth="lg">
<DialogContent>
<WinnersTable winners={winResult} />
</DialogContent>
</Dialog>
<Dialog open={showBetsDialog} onClose={this.toggleBetsDialog} fullWidth maxWidth="lg">
<DialogContent>
<UserBetsTable bets={bets} />
</DialogContent>
</Dialog>
<LockWrapper hasPermission={true}>
<Button size="small" variant="outlined" disabled={_.isEmpty(winResult)}
style={{ textTransform: "none", backgroundColor: "#CFB53B", color: "#ffffff", boxShadow: "none", margin: 10, marginLeft: 0}}
onClick={this.toggleWinnersDialog}>
<MedalIcon style={{marginRight: 7}}/> Winners
</Button>
<Button size="small" variant="outlined"
style={{ textTransform: "none", backgroundColor: "#649B3A", color: "#ffffff", boxShadow: "none", margin: 10, marginLeft: 0}}
onClick={this.toggleBetsDialog}>
<MoneyIcon style={{marginRight: 7}}/> Bets
</Button>
</LockWrapper>
<hr/>
<h5 className="">Bet % that goes into the jackpot pot</h5>
<h3 style={{marginTop: 20}} className={"dashboard__total-stat"}>{edge}%</h3>
<br/>
<h6 className="">New %</h6>
<h5 className={"dashboard__total-stat"}>{newEdge}%</h5>
<Slider disabled={this.state.lock} value={newEdge} onChange={this.onChangeEdge}/>
</EditLock>
</Col>
</ExpansionPanelDetails>
</LockWrapper>
</ExpansionPanel>
</Paper>
</Card> )}
</Col>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile,
currency : state.currency
};
}
export default connect(mapStateToProps)(Jackpot);
<file_sep>/src/containers/Wallet/components/paths/LimitsWidget.js
import React from 'react';
import { Col, Container, Row } from 'reactstrap';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import _ from 'lodash';
import { ArrowExpandDownIcon, WalletProductIcon } from 'mdi-react';
import LimitsBox from './limits/LimitsBox';
import { TabContainer } from '../WalletTabs/styles';
import { Paragraph } from '../LiquidityWalletContainer/styles';
const deposit = `${process.env.PUBLIC_URL}/img/dashboard/deposit.png`;
const withdrawal = `${process.env.PUBLIC_URL}/img/dashboard/withdrawal.png`;
const defaultState = {
maxDeposit : 0,
new_maxDeposit : 0,
maxWithdrawal : 0,
new_maxWithdrawal : 0,
minWithdrawal: 0,
new_minWithdrawal: 0,
affiliateMinWithdrawal: 0,
new_affiliateMinWithdrawal: 0,
currencyTicker : 'N/A',
locks : {
maxWithdrawal: true,
maxDeposit: true,
minWithdrawal: true,
affiliateMinWithdrawal: true
},
isLoading : {
maxWithdrawal: false,
maxDeposit: false,
minWithdrawal: false,
affiliateMinWithdrawal: false
}
}
class LimitsWidget extends React.Component{
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
// this.projectData(props);
}
projectData = async (props) => {
const { wallet } = props.data;
let currencyTicker, maxDeposit, maxWithdrawal, minWithdrawal, affiliateMinWithdrawal;
currencyTicker = wallet.currency.ticker;
currencyTicker = wallet.currency.ticker;
maxDeposit = wallet.max_deposit;
maxWithdrawal = wallet.max_withdraw;
minWithdrawal = wallet.min_withdraw;
affiliateMinWithdrawal = wallet.affiliate_min_withdraw;
this.setState({...this.state,
currencyTicker,
maxDeposit,
maxWithdrawal,
minWithdrawal,
affiliateMinWithdrawal,
wallet
});
}
onChange = ({type, value}) => {
this.setState({...this.state, [`new_${type}`] : value })
}
unlockField = ({field}) => {
this.setState({...this.state, locks : {...this.state.locks, [field] : false }})
}
lockField = ({field}) => {
this.setState({...this.state, locks : {...this.state.locks, [field] : true }})
}
confirmChanges = async ({field}) => {
const { profile } = this.props;
const { wallet } = this.state;
this.setState({
...this.state,
isLoading : {
...this.state.isLoading,
[field] : true
}
});
// eslint-disable-next-line default-case
switch (field){
// eslint-disable-next-line no-lone-blocks
case 'maxDeposit' : {
// this.setState({...this.state,
// maxDeposit: this.state.new_maxDeposit
// });
await profile.getApp().changeMaxDeposit({ amount : this.state[`new_${field}`], wallet_id : wallet._id });
this.state.locks[field] = true;
this.setState({...this.state, isLoading : {...this.state.isLoading, [field] : false}, maxDeposit: this.state.new_maxDeposit});
break;
}
// eslint-disable-next-line no-lone-blocks
case 'maxWithdrawal' : {
// this.setState({...this.state,
// maxWithdrawal: this.state.new_maxWithdrawal
// });
await profile.getApp().changeMaxWithdraw({ amount : this.state[`new_${field}`], wallet_id : wallet._id });
this.state.locks[field] = true;
this.setState({...this.state, isLoading : {...this.state.isLoading, [field] : false}, maxWithdrawal: this.state.new_maxWithdrawal});
break;
}
case 'minWithdrawal' : {
await profile.getApp().changeMinWithdraw({ amount: this.state[`new_${field}`], wallet_id: wallet._id });
this.state.locks[field] = true;
this.setState({...this.state, isLoading : {...this.state.isLoading, [field] : false}, minWithdrawal: this.state.new_minWithdrawal});
break;
}
case 'affiliateMinWithdrawal' : {
await profile.getApp().changeAffiliateMinWithdraw({ amount: this.state[`new_${field}`], wallet_id: wallet._id });
this.state.locks[field] = true;
this.setState({...this.state, isLoading : {...this.state.isLoading, [field] : false}, affiliateMinWithdrawal: this.state.new_affiliateMinWithdrawal});
break;
}
}
// this.projectData(this.props);
// this.setState();
}
render = () => {
return (
<>
<TabContainer>
<Paragraph style={{ marginBottom: 15 }}>Choose the limits to deposit and withdraw of your wallet</Paragraph>
<Row>
<Col xl="6" lg="6" md="12" sm="12" xs="12">
<LimitsBox
title={'Max Deposit'}
inputIcon={ArrowExpandDownIcon}
currencyTicker={this.state.currencyTicker}
image={deposit}
lock={this.state.locks.maxDeposit}
type={'maxDeposit'}
value={this.state.maxDeposit}
new_value={this.state.new_maxDeposit}
/* Functions */
unlockField={this.unlockField}
isLoading={this.state.isLoading.maxDeposit}
lockField={this.lockField}
onChange={this.onChange}
confirmChanges={this.confirmChanges}
/>
</Col>
<Col xl="6" lg="6" md="12" sm="12" xs="12">
<LimitsBox
title={'Max Withdrawal'}
inputIcon={ArrowExpandDownIcon}
currencyTicker={this.state.currencyTicker}
image={withdrawal}
lock={this.state.locks.maxWithdrawal}
type={'maxWithdrawal'}
value={this.state.maxWithdrawal}
isLoading={this.state.isLoading.maxWithdrawal}
new_value={this.state.new_maxWithdrawal}
/* Functions */
unlockField={this.unlockField}
lockField={this.lockField}
onChange={this.onChange}
confirmChanges={this.confirmChanges}
/>
</Col>
<Col xl="6" lg="6" md="12" sm="12" xs="12">
<LimitsBox
title={'Min Withdrawal'}
inputIcon={ArrowExpandDownIcon}
currencyTicker={this.state.currencyTicker}
image={withdrawal}
lock={this.state.locks.minWithdrawal}
type={'minWithdrawal'}
value={this.state.minWithdrawal}
isLoading={this.state.isLoading.minWithdrawal}
new_value={this.state.new_minWithdrawal}
unlockField={this.unlockField}
lockField={this.lockField}
onChange={this.onChange}
confirmChanges={this.confirmChanges}
/>
</Col>
<Col xl="6" lg="6" md="12" sm="12" xs="12" >
<LimitsBox
title={'Affiliate Min Withdrawal'}
inputIcon={ArrowExpandDownIcon}
currencyTicker={this.state.currencyTicker}
image={withdrawal}
lock={this.state.locks.affiliateMinWithdrawal}
type={'affiliateMinWithdrawal'}
value={this.state.affiliateMinWithdrawal}
isLoading={this.state.isLoading.affiliateMinWithdrawal}
new_value={this.state.new_affiliateMinWithdrawal}
unlockField={this.unlockField}
lockField={this.lockField}
onChange={this.onChange}
confirmChanges={this.confirmChanges}
/>
</Col>
</Row>
</TabContainer>
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
wallet: (state.wallet.currency) ? state.wallet : state.profile.getApp().getSummaryData('walletSimple').data[0]
};
}
LimitsWidget.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(LimitsWidget);<file_sep>/src/containers/Wallet/components/paths/components/CurrencyBox.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col, Row , Button} from 'reactstrap';
import { DirectionsIcon } from 'mdi-react';
import QRCodeContainer from './QRCode';
import AddressBox from './AddressBox';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import {formatCurrency} from '../../../../../utils/numberFormatation';
const Ava = `${process.env.PUBLIC_URL}/img/dashboard/ethereum.png`;
const loading = `${process.env.PUBLIC_URL}/img/loading.gif`;
const defaultProps = {
playBalance : 'N/A',
ticker : 'N/A',
tokenAddress : 'N/A',
houseLiquidity : 0,
image : 'N/A',
amount : 100,
platformBlockchain : 'N/A'
}
class CurrencyBox extends PureComponent {
constructor(props){
super(props);
this.state = { ...defaultProps};
this.projectData(props);
}
componentDidMount(){
this.projectData(this.props)
}
projectData = (props) => {
let { wallet } = props;
const currency = wallet.currency;
let tokenAddress = wallet.bank_address;
this.setState({...this.state,
decimals : wallet.currency.decimals,
image : currency.image,
playBalance : wallet.playBalance ? wallet.playBalance : defaultProps.houseLiquidity,
ticker : currency.ticker ? currency.ticker : defaultProps.ticker,
tokenAddressLink : wallet.link_url,
tokenAddress : tokenAddress,
tokenAddressTrimmed : tokenAddress ? `${tokenAddress.substring(0, 6)}...${tokenAddress.substring(tokenAddress.length - 2)}` : null
})
}
render() {
const { image } = this.state;
return (
<Col md={12} xl={12} lg={12} xs={12}>
<Card style={{marginTop : 50}}>
<CardBody className="dashboard__card-widget" >
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-title" style={{fontSize : 20, textAlign : 'center'}}>
House Liquidity <span style={{fontSize : 20}}> {formatCurrency(parseFloat(this.state.playBalance))}</span> {this.state.ticker}
</p>
<hr></hr>
</div>
<Row>
<Col lg={12}>
<div className="dashboard__visitors-chart">
<Row>
<Col lg={6} style={{marginTop : 30}}>
<p className="dashboard__visitors-chart-number-second" style={
{color : '#646777'}
}>
<img style={{borderRadius : 0}} className="company-logo-card" src={image} alt="avatar" /> {this.state.ticker}
</p>
</Col>
<Col lg={6}>
{
this.state.tokenAddressLink ?
<a target={'__blank'} className='ethereum-address-a' href={this.state.tokenAddressLink} style={{marginTop : 30}}>
<p className="ethereum-address-name"> <DirectionsIcon className='icon-ethereum-address' />
{this.state.tokenAddressTrimmed}
</p>
</a>
:
<p className="ethereum-address-name"> <DirectionsIcon className='icon-ethereum-address' />
{this.state.tokenAddressTrimmed}
</p>
}
</Col>
</Row>
</div>
</Col>
<div className='container' style={{textAlign : 'center'}}>
<Col lg={12} style={{margin : '10px auto', textAlign : 'center'}} >
<QRCodeContainer value={this.state.tokenAddress}/>
<AddressBox value={this.state.tokenAddress}/>
</Col>
</div>
</Row>
</CardBody>
</Card>
</Col>
);
}
}
function mapStateToProps(state){
// console.log("sadfaaaaaaa", state.profile)
return {
profile: state.profile,
wallet : (state.wallet.currency) ? state.wallet : state.profile.getApp().getSummaryData('walletSimple').data[0]
};
}
CurrencyBox.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
connect(mapStateToProps)
)(CurrencyBox);
<file_sep>/src/containers/Applications/ThirdParties/components/GameProvidersTab/styles.js
import styled from 'styled-components';
import { CardBody as Card, Input } from 'reactstrap';
export const CardBody = styled(Card)`
margin: 10px !important;
padding: 25px 15px 15px 15px !important;
border-radius: 10px !important;
background-color: #fafcff !important;
border: solid 1px rgba(164, 161, 161, 0.35) !important;
box-shadow: none !important;
> h1 {
font-family: Poppins;
font-size: 16px;
color: #212529;
font-weight: 500;
line-height: 24px;
}
`;
export const ProvidersList = styled.div`
display: grid;
grid-template-columns: repeat(auto-fill, minmax(290px, 1fr));
grid-gap: 15px;
justify-items: start;
width: 100%;
height: 100%;
`;
export const ProviderContainer = styled.div`
width: 100%;
padding: 15px 25px;
border-radius: 10px !important;
background-color: white;
border: solid 1px rgba(164, 161, 161, 0.35) !important;
box-shadow: none !important;
`;
export const Header = styled.section`
> img {
height: 100px;
width: auto;
margin: 5px 0px !important;
}
`;
export const Actions = styled.section`
padding-top: 15px;
> p {
font-family: Poppins;
font-size: 13px;
}
`;
export const InputField = styled(Input)`
margin: 12px 0px;
border-radius: 6px;
border: solid 1.5px rgba(164, 161, 161, 0.35);
background-color: #fafcff;
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
`;
<file_sep>/src/containers/App/App.jsx
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { I18nextProvider } from 'react-i18next';
import i18next from 'i18next';
// eslint-disable-next-line import/no-extraneous-dependencies
import { hot } from 'react-hot-loader';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'react-bootstrap-range-slider/dist/react-bootstrap-range-slider.css';
import '../../scss/app.scss';
import './App.css';
import GlobalStyle from './GlobalStyles';
import Router from './Router';
import store from './store';
import ScrollToTop from './ScrollToTop';
import { config as i18nextConfig } from '../../translations';
import Web3 from 'web3';
import { ETHEREUM_NET_DEFAULT } from '../../config/apiConfig';
import { Modal2FA, ModalError, AbstractModal, ModalAddCurrencyWallet } from '../Modals';
const loadingBetprotocol = `${process.env.PUBLIC_URL}/img/loading-betprotocol.gif`;
i18next.init(i18nextConfig);
class App extends Component {
constructor() {
super();
this.state = {
loading: true,
loaded: false,
};
}
asyncCalls = async () => {
this.enterWebsite();
}
enterWebsite = () => {
window.addEventListener('load', () => {
this.setState({ loading: false });
setTimeout(() => this.setState({ loaded: true }), 500);
});
}
componentDidMount() {
this.asyncCalls();
this.startWallet();
}
startWallet = async () => {
// Modern dapp browsers...
if (window.ethereum) {
global.web3 = new Web3(window.ethereum);
try {
//await ethereum.enable();
//var myContract = new web3.eth.Contract(abi,contractAddress);
/* myContract.methods.RegisterInstructor('11','Ali')
.send(option,function(error,result){
if (! error)
console.log(result);
else
console.log(error);
}); */
} catch (error) {
global.web3 = new Web3(new Web3.providers.HttpProvider(`https://${ETHEREUM_NET_DEFAULT}.infura.io/`));
// User denied account access...
}
}
// Legacy dapp browsers...
else if (window.web3) {
global.web3 = new Web3(new Web3.providers.HttpProvider(`https://${ETHEREUM_NET_DEFAULT}.infura.io/`));
// Acccounts always exposed
}
// Non-dapp browsers...
else {
global.web3 = new Web3(new Web3.providers.HttpProvider(`https://${ETHEREUM_NET_DEFAULT}.infura.io/`));
console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
}
}
render() {
const { loaded, loading } = this.state;
return (
<Provider store={store}>
<BrowserRouter basename="/">
<I18nextProvider i18n={i18next}>
<ScrollToTop>
{!loaded &&
<div className={`load${loading ? '' : ' loaded'}`}>
<div class="load__icon-wrap">
<img src={loadingBetprotocol} alt="loading..."/>
</div>
</div>
}
<div>
<ModalAddCurrencyWallet/>
<Modal2FA/>
<ModalError/>
<AbstractModal/>
<Router />
<GlobalStyle/>
</div>
</ScrollToTop>
</I18nextProvider>
</BrowserRouter>
</Provider>
);
}
}
export default hot(module)(App);
<file_sep>/src/containers/Stats/components/PlatformCostsInfo.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col } from 'reactstrap';
import { BarChart, Bar, Cell, ResponsiveContainer } from 'recharts';
import TrendingUpIcon from 'mdi-react/TrendingUpIcon';
import AnimationNumber from '../../UI/Typography/components/AnimationNumber';
import Numbers from '../../../services/numbers';
class PlatformCostsInfo extends PureComponent {
constructor() {
super();
this.state = {
activeIndex: 0,
};
}
handleClick = (index) => {
this.setState({
activeIndex: index,
});
};
render() {
let costs = 456;
return (
<Col md={12} xl={12} lg={12} xs={12}>
<Card>
<CardBody className="dashboard__card-widget">
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-number-second" style={
{color : '#646777'}
}><AnimationNumber decimals={2} number={costs}/> €</p>
</div>
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-title"> Costs <span> this week </span></p>
</div>
</CardBody>
</Card>
</Col>
);
}
}
export default PlatformCostsInfo;
<file_sep>/src/containers/Layout/sidebar/SidebarContent.jsx
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import SidebarLink from './SidebarLink';
import { connect } from "react-redux";
import { compose } from 'lodash/fp';
import _ from 'lodash';
import { Casino, Wallet, Phone, User, Arrow, Confirmed, Bet, Hand, Settings, Reward, LogOut } from '../../../components/Icons';
class SidebarContent extends Component {
static propTypes = {
changeToDark: PropTypes.func.isRequired,
changeToLight: PropTypes.func.isRequired,
onClick: PropTypes.func.isRequired,
};
constructor(props){
super(props)
this.state = {
home : true,
application : true,
users : true,
stats : true,
transactions : true,
bets: true,
wallet : true,
affiliates : true,
settings : true,
developers : true
}
}
componentDidMount(){
this.getData(this.props);
}
hideSidebar = () => {
this.props.onClick();
};
componentWillReceiveProps(props){
this.getData(props);
}
hasData = (summary) => summary && !_.isEmpty(summary.data);
hasInfo = data => data ? true : false ;
getData = (props) => {
const User = props.profile.User;
let newState = {
home : User.permission.super_admin || User.permission.financials,
application : User.permission.super_admin || User.permission.customization || User.permission.financials,
users : this.hasData(props.profile.hasAppStats('usersInfoSummary')) &&
(User.permission.super_admin || User.permission.financials),
stats : this.hasData(props.profile.hasAppStats('revenue')) &&
(User.permission.super_admin || User.permission.financials),
wallet : User.permission.super_admin || User.permission.financials ||
User.permission.withdraw,
settings : User.permission.super_admin,//this.hasInfo(getApp().isDeployed()),
affiliates : this.hasData(props.profile.hasAppStats('affiliates')) && User.permission.super_admin,
transactions: this.hasData(props.profile.hasAppStats('withdraws')) && (User.permission.super_admin ||
User.permission.financials || User.permission.user_withdraw),
bets : User.permission.super_admin || User.permission.financials,
developers : User.permission.super_admin
}
this.setState({...this.state, ...newState})
}
render() {
return (
<div className="sidebar__content">
<ul className="sidebar__block">
<SidebarLink disabled={!this.state.home} title="Home" icon={<Casino/>} route="/home" onClick={this.hideSidebar} />
<SidebarLink disabled={!this.state.application} title="Application" icon={<Phone/>} route="/application" onClick={this.hideSidebar} />
<SidebarLink disabled={!this.state.users} title="Users" icon={<User/>} route="/users" onClick={this.hideSidebar} />
<SidebarLink disabled={!this.state.bets} title="Bets" icon={<Bet/>} route="/bets" onClick={this.hideSidebar} />
<SidebarLink disabled={!this.state.transactions} title="Transactions" icon={<Arrow/>} route="/transactions" onClick={this.hideSidebar} />
<SidebarLink disabled={!this.state.stats} title="Stats" icon={<Confirmed/>} route="/stats" onClick={this.hideSidebar} />
<SidebarLink disabled={!this.state.wallet} title="Wallet" icon={<Wallet/>} route="/wallet" onClick={this.hideSidebar} />
<SidebarLink disabled={!this.state.affiliates} title="Affiliates" icon={<Hand/>} route="/affiliates" onClick={this.hideSidebar} />
<SidebarLink disabled={!this.state.settings} title="Settings" icon={<Settings/>} route="/settings" onClick={this.hideSidebar} />
<SidebarLink disabled={!this.state.developers} title="Developers" icon={<Reward/>} route="/developers" onClick={this.hideSidebar} />
{/* <SidebarLink title="Log Out" icon={<LogOut/>} route="/login" /> */}
</ul>
</div>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default compose(
connect(mapStateToProps)
)(SidebarContent);<file_sep>/src/containers/Modals/styles.js
import styled from 'styled-components';
import { Input, InputGroupText } from 'reactstrap';
import { Button as MaterialButton } from '@material-ui/core';
export const WalletIDInput = styled(Input)`
margin: 12px 0px;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #fafcff;
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
`;
export const AddressInput = styled(Input)`
margin: 12px 0px;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #fafcff;
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
`;
export const InputAddOn = styled(InputGroupText)`
margin: 12px 0px;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #fafcff;
height: 35px;
border-right: none;
span {
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
margin-right: 10px;
}
`;
export const AddCurrencyButton = styled(MaterialButton)`
margin: 30px 0px !important;
height: 40px !important;
width: 100% !important;
border-radius: 6px !important;
background-color: #814c94 !important;
text-transform: none !important;
box-shadow: none !important;
span {
font-family: Poppins !important;
font-size: 18px !important;
font-weight: 400 !important;
color: #ffffff !important;
}
&:disabled {
opacity: 0.5;
}
`;
export const ErrorMessage = styled.section`
display: flex;
width: 100%;
justify-content: flex-start;
`;<file_sep>/src/containers/Applications/components/Wizard/WizardFormOne.jsx
import React, { PureComponent } from 'react';
import { Button, ButtonToolbar, Container, Row, Col, CardBody, Card } from 'reactstrap';
import { Field, reduxForm } from 'redux-form';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import store from "../../../App/store";
import { setAppCreationInfo } from '../../../../redux/actions/appCreation';
const back_2 = `${process.env.PUBLIC_URL}/img/landing/back-2.png`;
const DEFAULT_INTEGRATIONS = [101, 201];
class WizardFormOne extends PureComponent {
constructor() {
super();
this.state = {
showPassword: false,
};
}
changeContent = (type, item) => {
this.setState({[type] : item});
}
showPassword = (e) => {
e.preventDefault();
this.setState({
showPassword: !this.state.showPassword,
});
};
setWidget = (keys) => {
store.dispatch(setAppCreationInfo({key : 'services' , value : keys}));
}
createApp = async () => {
try{
await this.props.profile.createApp({
...this.state,
name : this.state.name,
description : this.state.description,
// TO DO : Create Metadata JSON Add on Inputs (Logo and Other Data)
metadataJSON : JSON.stringify({}),
// TO DO : Create MarketType Setup
marketType : 0
});
this.props.history.push('/home')
}catch(err){
this.props.showNotification(err.message);
}
}
render() {
let {
services
} = this.props.appCreation;
let isSet = (services.length != 0);
return (
<div style={{width : '80%'}}>
<Row>
<Col md={12} xl={12} lg={12} xs={12}>
<Card>
<Row>
<Col>
<button className={`button__widget clean_button`} onClick={() => this.setWidget(DEFAULT_INTEGRATIONS)}>
{isSet ? <div> <h5 className={`widget__use__big`}> Integrate </h5></div> : null}
<div className={`landing__product__widget available`}>
<div className='description'>
<h4> Casino </h4>
<p> A Casino Application from Layout, Engines, Games to Deposits </p>
</div>
<Row>
<Col sd={6}>
<h2 style={{marginTop : 30}}> $999 <h5>Monthly</h5></h2>
</Col>
<Col sd={1} style={{padding : 0}}>
<h2 style={{marginTop : 30}}> +</h2>
</Col>
<Col sd={5}>
<h2 style={{marginTop : 30}}> 0,5% <h5>In Volume</h5></h2>
</Col>
</Row>
<img className="landing_2_back" style={{left : '0%', bottom : '-20%',width : '200%'}} src={back_2} />
</div>
</button>
</Col>
</Row>
</Card>
</Col>
<ButtonToolbar style={{margin: 'auto', display : 'block'}} className="form__button-toolbar wizard__toolbar">
<Button onClick={() => this.props.onSubmit()} color="primary" type="submit" className="next">Next</Button>
</ButtonToolbar>
</Row>
</div>
);
}
}
function mapStateToProps(state){
return {
profile : state.profile,
appCreation : state.appCreation
};
}
export default compose(reduxForm({
form: 'wizard', // <------ same form name
}), connect(mapStateToProps))(WizardFormOne);
<file_sep>/src/redux/actions/loadingAction.js
export const SET_LOADING_STATUS = 'SET_LOADING_STATUS';
export function setLoadingStatus(status) {
return {
type: SET_LOADING_STATUS,
loading : status
};
}
<file_sep>/src/containers/Applications/Customization/components/Skins/index.js
import React, { Component } from 'react'
import EditLock from '../../../../Shared/EditLock.js';
import { Col, Row, Card, CardBody, Label } from 'reactstrap';
import { connect } from "react-redux";
import { ButtonBase, Checkbox, createMuiTheme, MuiThemeProvider, withStyles, FormControlLabel, RadioGroup, Radio } from '@material-ui/core';
import styled from 'styled-components';
import _ from 'lodash';
import { SkinPreview, MobileSkinPreview, MobileSkinsContainer, Header, Container } from './styles'
const defaultHome = `${process.env.PUBLIC_URL}/img/landing/default-home.png`;
const defaultHomeMobile = `${process.env.PUBLIC_URL}/img/landing/default-home-mobile.png`;
const digitalHome = `${process.env.PUBLIC_URL}/img/landing/digital-home.png`;
const digitalHomeMobile = `${process.env.PUBLIC_URL}/img/landing/digital-home-mobile.png`;
const theme = createMuiTheme({
palette: {
primary: {
main: '#894798'
}
},
});
const cardStyle = {
margin: 10,
borderRadius: "10px",
border: "solid 1px rgba(164, 161, 161, 0.35)",
backgroundColor: "#fafcff",
boxShadow: "none"
}
export const InputLabel = styled(Label)`
font-size: 18px;
font-family: Poppins;
margin-bottom: 35px;
`;
const WhiteCheckbox = withStyles({
root: {
color: 'white',
'&$checked': {
color: 'white',
},
},
checked: {},
})((props) => <Checkbox color="default" {...props} />);
const StyledFormControlLabel = withStyles({
label: {
fontFamily: "Poppins",
fontSize: "15px"
},
})(FormControlLabel);
class SkinsTab extends Component {
constructor(props){
super(props);
this.state = {
locked: true,
isLoading: false,
previewType: 'desktop',
skins: []
};
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
const { locked } = this.state;
if (locked) {
this.projectData(props);
}
}
projectData = async (props) => {
const { profile } = props;
const skins = await profile.getApp().getEcosystemSkins();
const app = await profile.getApp();
const { params } = app;
const selected_skin = params.customization.skin.skin_type;
const _id = params.customization.skin._id;
this.setState({
skins: skins.data ? skins.data.message : [],
selected_skin: selected_skin ? selected_skin : "default",
_id: _id
})
}
onChange = ({ type, value }) => {
this.setState({ [type]: value })
}
unlockField = () => {
this.setState({ locked: false})
}
lockField = () => {
this.setState({ locked: true})
}
confirmChanges = async () => {
const { profile } = this.props;
const { selected_skin, skins, _id } = this.state;
this.setState({ isLoading: true });
const skin = skins.find(skin => skin.skin_type === selected_skin);
await profile.getApp().editSkinTypeCustomization({ skinParams: {
_id: _id,
skin_type: skin.skin_type,
name: skin.name
}});
this.setState({ isLoading: false, locked: true });
this.projectData(this.props);
}
handleChangePreviewType = event => {
event.preventDefault();
this.setState({ previewType: event.target.value })
}
render() {
const { isLoading, locked, skins, selected_skin, previewType } = this.state;
return (
<Card>
<CardBody style={cardStyle}>
<Row>
<Col md={12}>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'skinType'}
locked={locked}
>
<Container>
<div className="header">
<h1>Skin type</h1>
<p>You can choose from available skins types</p>
<hr/>
</div>
{ !_.isEmpty(skins) && (
<MuiThemeProvider theme={theme}>
{/* <RadioGroup row aria-label="previewType" name="previewType" value={previewType} onChange={this.handleChangePreviewType}>
<StyledFormControlLabel value={"desktop"} control={<Radio color="primary" size="small" />} label={"Desktop"} disabled={locked}/>
<StyledFormControlLabel value={"mobile"} control={<Radio color="primary" size="small" />} label={"Mobile"} disabled={locked}/>
</RadioGroup>
<br/>
{ previewType === 'mobile' ? (
<MobileSkinsContainer>
<ButtonBase onClick={() => this.setState({ selected_skin: 'default' })} disabled={locked}>
<MobileSkinPreview selected={selected_skin === 'default'}>
<Header>
<h1>Default</h1> <WhiteCheckbox checked={selected_skin === 'default'} size="small"/>
</Header>
<img src={defaultHomeMobile} alt="Default home" />
</MobileSkinPreview>
</ButtonBase>
<ButtonBase onClick={() => this.setState({ selected_skin: 'digital' })} disabled={locked}>
<MobileSkinPreview selected={selected_skin === 'digital'}>
<Header>
<h1>Digital</h1> <WhiteCheckbox checked={selected_skin === 'digital'} size="small"/>
</Header>
<img src={digitalHomeMobile} alt="Digital home" />
</MobileSkinPreview>
</ButtonBase>
<div></div>
</MobileSkinsContainer>
) : (
<> */}
<ButtonBase onClick={() => this.setState({ selected_skin: 'default' })} disabled={locked}>
<SkinPreview selected={selected_skin === 'default'}>
<Header>
<h1>Default</h1> <WhiteCheckbox checked={selected_skin === 'default'} size="small"/>
</Header>
<img src={defaultHome} alt="Default home" />
</SkinPreview>
</ButtonBase>
<br/>
<br/>
<ButtonBase onClick={() => this.setState({ selected_skin: 'digital' })} disabled={locked}>
<SkinPreview selected={selected_skin === 'digital'}>
<Header>
<h1>Digital</h1> <WhiteCheckbox checked={selected_skin === 'digital'} size="small"/>
</Header>
<img src={digitalHome} alt="Digital home" />
</SkinPreview>
</ButtonBase>
{/* </>
)} */}
</MuiThemeProvider>
)}
</Container>
</EditLock>
</Col>
</Row>
</CardBody>
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(SkinsTab);
<file_sep>/src/containers/Wallet/components/paths/FreeCurrencyAddOn/styles.js
import styled from 'styled-components';
import { CardBody, Input, InputGroupText } from 'reactstrap';
import { Button } from '@material-ui/core';
export const Container = styled(CardBody)`
width: 307px;
margin: 10px;
padding: 20px;
border-radius: 10px;
border: solid 1px rgba(164, 161, 161, 0.35) !important;
background-color: #fafcff !important;
box-shadow: none !important;
`;
export const EditImage = styled.section`
width: 100%;
display: flex;
flex-direction: column;
align-items: flex-start;
`;
export const Image = styled.img`
width: 85px;
padding: 10px 5px;
`;
export const Name = styled.span`
font-family: Poppins;
font-size: 20px;
`;
export const UploadButton = styled(Button)`
height: 25px !important;
text-transform: none !important;
background-color: #63c965 !important;
box-shadow: none !important;
p {
font-size: 12px !important;
color: white !important;
}
svg {
color: white !important;
}
`;
export const Label = styled.h4`
font-size: 15px;
margin-bottom: 8px;
`;
export const TextField = styled(Input)`
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: white;
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
margin: 0px !important;
`;
export const InputAddOn = styled(InputGroupText)`
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #fafcff;
height: 35px;
border-right: none;
span {
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
margin-right: 10px;
}
`;
export const Logo = styled.section`
height: 50%;
width: 40%;
padding: 5px;
border: solid 2px rgba(164, 161, 161, 0.35);
border-radius: 6px;
border-style: dashed;
margin-bottom: 10px;
`;
export const ConvertContainer = styled.div`
padding: 25px;
width: 300px;
`;<file_sep>/src/containers/Applications/components/IntegrationsContainer.jsx
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col, Row } from 'reactstrap';
import WizardForm from './Wizard/WizardForm';
class IntegrationsContainer extends PureComponent {
constructor() {
super();
this.state = {
};
}
render() {
return (
<WizardForm/>
);
}
}
export default IntegrationsContainer;
<file_sep>/src/containers/Bets/components/OldBetsTable.jsx
import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import { TableBody, TableCell, TableHead, TablePagination,TableRow, TableSortLabel } from '@material-ui/core';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import Tooltip from '@material-ui/core/Tooltip';
import { lighten } from '@material-ui/core/styles/colorManipulator';
import { TableIcon, JsonIcon } from 'mdi-react';
import moment from 'moment';
import { connect } from "react-redux";
import { compose } from 'lodash/fp';
import _ from 'lodash';
import { CSVLink } from "react-csv";
import { export2JSON } from "../../../utils/export2JSON";
import { Button as MaterialButton } from "@material-ui/core";
import Skeleton from '@material-ui/lab/Skeleton';
import UserBetsFilter from './UserBetsFilter';
import UserContainer from '../../../shared/components/UserContainer';
import CurrencyContainer from '../../../shared/components/CurrencyContainer';
import BetContainer from '../../../shared/components/BetContainer';
import GameContainer from '../../../shared/components/GameContainer';
import styled from 'styled-components';
function getSorting(data, order, orderBy) {
const sortedData = _.orderBy(data, [orderBy], order)
.map(row => ({...row, creation_timestamp: moment(row.creation_timestamp).format("lll")}));
return sortedData;
}
const MobileWrapper = styled.section`
@media (max-width: 768px) {
display: none !important;
}
`;
const fromDatabasetoTable = (data, currencies, users, games) => {
return data.map(key => {
const currency = currencies.find(currency => currency._id === key.currency);
const game = games.find(game => game._id === key.game);
return {
_id: key._id,
user: key.user,
currency: currency,
app: key.app_id,
game: game,
ticker: currency.ticker,
isWon: key.isWon,
winAmount: key.winAmount,
betAmount: key.betAmount,
nonce: key.nonce,
fee: key.fee,
creation_timestamp: key.timestamp,
clientSeed: key.clientSeed,
serverSeed: key.serverSeed,
serverHashedSeed: key.serverHashedSeed
}
})
}
const rows = [
{
id: '_id',
label: 'Id',
numeric: true
},
{
id: 'user',
label: 'User',
numeric: false
},
{
id: 'currency',
label: 'Currency',
numeric: false
},
{
id: 'game',
label: 'Game',
numeric: true
},
{
id: 'isWon',
label: 'Won',
numeric: false
},
{
id: 'winAmount',
label: 'Win Amount',
numeric: true
},
{
id: 'betAmount',
label: 'Bet Amount',
numeric: true
},
{
id: 'fee',
label: 'Fee',
numeric: true
},
{
id: 'creation_timestamp',
label: 'Created At',
numeric: false
}
];
class EnhancedTableHead extends React.Component {
createSortHandler = property => event => {
this.props.onRequestSort(event, property);
};
render() {
const { order, orderBy } = this.props;
return (
<TableHead>
<TableRow>
{rows.map(
row => (
<TableCell
key={row.id}
rowSpan={2}
align={'left'}
padding={row.disablePadding ? 'none' : 'default'}
sortDirection={orderBy === row.id ? order : false}
>
<Tooltip
title="Sort"
placement={row.numeric ? 'bottom-end' : 'bottom-start'}
enterDelay={300}
>
<TableSortLabel
active={orderBy === row.id}
direction={order}
onClick={this.createSortHandler(row.id)}
>
{row.label}
</TableSortLabel>
</Tooltip>
</TableCell>
),
this,
)}
</TableRow>
</TableHead>
);
}
}
EnhancedTableHead.propTypes = {
numSelected: PropTypes.number.isRequired,
onRequestSort: PropTypes.func.isRequired,
onSelectAllClick: PropTypes.func.isRequired,
order: PropTypes.string.isRequired,
orderBy: PropTypes.string.isRequired,
rowCount: PropTypes.number.isRequired,
};
const toolbarStyles = theme => ({
root: {
paddingRight: theme.spacing.unit,
},
highlight:
theme.palette.type === 'light'
? {
color: theme.palette.secondary.main,
backgroundColor: lighten(theme.palette.secondary.light, 0.85),
}
: {
color: theme.palette.text.primary,
backgroundColor: theme.palette.secondary.dark,
},
spacer: {
flex: '1 1 100%',
},
actions: {
color: theme.palette.text.secondary, zIndex: 20
},
title: {
flex: '0 0 auto',
},
});
let EnhancedTableToolbar = props => {
const { numSelected, classes } = props;
return (
<Toolbar
className={classNames(classes.root, {
[classes.highlight]: numSelected > 0,
})}
>
<MobileWrapper>
<div className={classes.title}>
<Typography variant="h6" id="tableTitle">
Bets
</Typography>
</div>
</MobileWrapper>
<div className={classes.spacer} />
</Toolbar>
);
};
EnhancedTableToolbar.propTypes = {
classes: PropTypes.object.isRequired,
numSelected: PropTypes.number.isRequired,
};
EnhancedTableToolbar = withStyles(toolbarStyles)(EnhancedTableToolbar);
const styles = theme => ({
root: {
width: '100%',
marginTop: theme.spacing.unit * 3,
},
table: {
minWidth: 1020,
},
tableWrapper: {
overflowX: 'auto',
},
});
class EnhancedTable extends React.Component {
constructor(props){
super(props)
this.state = {
order: 'asc',
orderBy: 'id',
selected: [],
data: [],
page: 0,
isLoading: false,
ticker: 'N/A',
rowsPerPage: 5,
currencyFilter: '',
statusFilter: '',
idFilter: null,
userFilter: null,
showFilter: false,
lastFilter: null
};
}
componentDidMount(){
this.projectData(this.props)
}
projectData = async (props) => {
this.setLoading(true);
const app = await props.profile.getApp();
const appBets = await app.getAllBets({ filters: { size: 100, isJackpot: false }});
const bets = appBets.data.message.list;
const currencies = app.params.currencies;
const users = app.params.users;
const games = app.params.games;
if (bets.length > 0) {
this.setState({...this.state,
data: fromDatabasetoTable(bets, currencies, users, games),
currencies: currencies,
users: users,
games: games
})
} else {
this.setState({...this.state,
data: [],
currencies: currencies,
users: users,
games: games
})
}
this.setLoading(false);
}
setLoading = (status) => {
this.setState(state => ({ isLoading: status }));
}
setData = async (data) => {
const { currencies, users, games } = this.state;
this.setState({...this.state,
data: fromDatabasetoTable(data, currencies, users, games),
page: 0
})
}
setFilter = (filter) => {
this.setState({ lastFilter: filter });
}
reset = async () => {
await this.projectData();
}
handleRequestSort = (event, property) => {
const orderBy = property;
let order = 'desc';
if (this.state.orderBy === property && this.state.order === 'desc') {
order = 'asc';
}
this.setState({ order, orderBy });
};
handleSelectAllClick = event => {
if (event.target.checked) {
this.setState(state => ({ selected: state.data.map(n => n.id) }));
return;
}
this.setState({ selected: [] });
};
handleClick = (event, id) => {
const { selected } = this.state;
const selectedIndex = selected.indexOf(id);
let newSelected = [];
if (selectedIndex === -1) {
newSelected = newSelected.concat(selected, id);
} else if (selectedIndex === 0) {
newSelected = newSelected.concat(selected.slice(1));
} else if (selectedIndex === selected.length - 1) {
newSelected = newSelected.concat(selected.slice(0, -1));
} else if (selectedIndex > 0) {
newSelected = newSelected.concat(
selected.slice(0, selectedIndex),
selected.slice(selectedIndex + 1),
);
}
this.setState({ selected: newSelected });
};
handleChangePage = async (event, page) => {
const { data, rowsPerPage, currencies, users, games, lastFilter } = this.state;
const { App } = this.props.profile;
if (page === Math.ceil(data.length / rowsPerPage)) {
this.setLoading(true);
const res = await App.getAllBets({
filters: lastFilter ? {...lastFilter, offset: data.length, isJackpot: false }
: { size: 100, offset: data.length, isJackpot: false } });
const bets = res.data.message.list;
if (bets.length > 0) {
this.setState({
data: data.concat(fromDatabasetoTable(bets, currencies, users, games)),
page: page
})
}
this.setLoading(false);
} else {
this.setState({ page });
}
};
handleChangeRowsPerPage = event => {
this.setState({ rowsPerPage: event.target.value });
};
handleChangeInputContent = (type, item) => {
this.setState({[type] : item});
}
handleChangeDropDown = event => {
const field = event.target.name;
this.setState({ [field]: event.target.value });
};
isSelected = id => this.state.selected.indexOf(id) !== -1;
handleFilterClick = () => {
const { showFilter } = this.state;
this.setState({ showFilter: showFilter ? false : true });
}
render() {
const { classes } = this.props;
const { data, order, orderBy, selected, rowsPerPage, page, isLoading } = this.state;
const emptyRows = rowsPerPage - Math.min(rowsPerPage, data.length - page * rowsPerPage);
const headers = [
{ label: "Id", key: "_id" },
{ label: "User", key: "user" },
{ label: "Currency", key: "currency" },
{ label: "Game", key: "game" },
{ label: "Won", key: "isWon" },
{ label: "Win Amount", key: "winAmount" },
{ label: "Bet Amount", key: "betAmount" },
{ label: "Fee", key: "fee" },
{ label: "Created At", key: "createdAt" }
];
let csvData = [{}];
let jsonData = [];
if (!_.isEmpty(data)) {
csvData = data.map(row => ({...row, currency: row.currency.name,
user: row.user._id,
isWon: row.isWon ? 'Yes' : 'No',
game: row.game._id,
createdAt: moment(row.creation_timestamp).format("lll")}));
jsonData = csvData.map(row => _.pick(row, ['_id', 'user', 'currency', 'game', 'isWon', 'winAmount', 'betAmount', 'fee', 'creation_timestamp']));
}
return (
<Paper className={classes.root} style={{ padding: 20, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none"}}>
<div style={{ display: "flex", justifyContent: "flex-end"}}>
<CSVLink data={csvData} filename={"bets.csv"} headers={headers}>
<MaterialButton variant="contained" size="small" style={{ textTransform: "none", backgroundColor: "#008000", color: "#ffffff", boxShadow: "none", margin: 10}}>
<TableIcon style={{marginRight: 7}}/> CSV
</MaterialButton>
</CSVLink>
<MaterialButton onClick={() => export2JSON(jsonData, "bets")} variant="contained" size="small" style={{ textTransform: "none", boxShadow: "none", margin: 10}}>
<JsonIcon style={{marginRight: 7}}/> JSON
</MaterialButton>
</div>
<EnhancedTableToolbar numSelected={selected.length} filterClick={this.handleFilterClick}/>
<UserBetsFilter setData={this.setData} setFilter={this.setFilter} reset={this.reset} setLoading={this.setLoading} loading={this.state.isLoading}/>
{isLoading ? (
<>
<Skeleton variant="rect" height={30} style={{ marginTop: 10, marginBottom: 20 }}/>
{[...Array(rowsPerPage)].map((e, i) => <Skeleton variant="rect" height={50} style={{ marginTop: 10, marginBottom: 10 }}/>)}
</>
) : (
<>
<div className={classes.tableWrapper}>
<Table className={classes.table} aria-labelledby="tableTitle">
<EnhancedTableHead
numSelected={selected.length}
order={order}
orderBy={orderBy}
onSelectAllClick={this.handleSelectAllClick}
onRequestSort={this.handleRequestSort}
rowCount={data.length}
/>
<TableBody>
{getSorting(data, order, orderBy)
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map(n => {
const isSelected = this.isSelected(n.id);
return (
<TableRow
// hover
// onClick={event => this.handleClick(event, n.id)}
role="checkbox"
style={{padding : 0}}
aria-checked={isSelected}
tabIndex={-1}
key={n._id}
selected={isSelected}
>
<TableCell align="left">
<BetContainer bet={n} id={n.currency._id}>
<p className='text-small'>{n._id}</p>
</BetContainer>
</TableCell>
<TableCell align="left">
<UserContainer user={n.user._id}>
<div style={{display: 'flex'}}>
<img src={`https://avatars.dicebear.com/v2/avataaars/${n.user._id}.svg`} className={'avatar-image-small'} style={{ marginLeft: 0, marginRight: 0, width : 30, height : 30}}/>
<p className='text-small' style={{margin: 10}}>{n.user.username}</p>
</div>
</UserContainer>
</TableCell>
<TableCell align="left">
<CurrencyContainer id={n.currency._id}>
<div style={{display: 'flex'}}>
<img src={n.currency.image} style={{ width : 25, height : 25}}/>
<p className='text-small' style={{margin: 5, alignSelf: "center" }}>{n.currency.name}</p>
</div>
</CurrencyContainer>
</TableCell>
<TableCell align="left">
<GameContainer id={n.game._id}>
<div style={{display: 'flex'}}>
<img src={n.game.image_url} style={{ width : 50, height : 40 }}/>
<p className='text-small' style={{margin: 5, marginLeft: 0, alignSelf: "center"}}>{n.game.name}</p>
</div>
</GameContainer>
</TableCell>
<TableCell align="left"><p className='text-small'>{n.isWon ? <p className='text-small background-green text-white'>Yes</p> : <p className='text-small background-red text-white'>No</p>}</p></TableCell>
<TableCell align="left"><p className='text-small'>{`${n.winAmount.toFixed(6)} ${n.ticker}`}</p></TableCell>
<TableCell align="left"><p className='text-small'>{`${n.betAmount.toFixed(6)} ${n.ticker}`}</p></TableCell>
<TableCell align="left"><p className='text-small'>{`${n.fee.toFixed(6)} ${n.ticker}`}</p></TableCell>
<TableCell align="left"><p className='text-small'>{n.creation_timestamp}</p></TableCell>
</TableRow>
);
})}
{emptyRows > 0 && (
<TableRow style={{ height: 49 * emptyRows }}>
<TableCell colSpan={6} />
</TableRow>
)}
</TableBody>
</Table>
</div>
</>)}
<TablePagination
rowsPerPageOptions={[5, 10, 25, 50]}
component="div"
count={data.length + rowsPerPage}
rowsPerPage={rowsPerPage}
page={page}
labelDisplayedRows={({ from, to, count }) => `${from}-${to > count - rowsPerPage ? count - rowsPerPage : to} of ${count - rowsPerPage}`}
backIconButtonProps={{
'aria-label': 'Previous Page',
}}
nextIconButtonProps={{
'aria-label': 'Next Page',
}}
onChangePage={this.handleChangePage}
onChangeRowsPerPage={this.handleChangeRowsPerPage}
/>
</Paper>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile,
currency: state.currency
};
}
EnhancedTable.propTypes = {
classes: PropTypes.object.isRequired,
};
export default compose(
withStyles(styles),
connect(mapStateToProps)
)(EnhancedTable);
<file_sep>/src/containers/Layout/topbar/TopbarProfile.jsx
import React, { PureComponent } from 'react';
import DownIcon from 'mdi-react/ChevronDownIcon';
import { Collapse } from 'reactstrap';
import TopbarMenuLink from './TopbarMenuLink';
import { connect } from "react-redux";
import Cache from '../../../services/cache';
import store from '../../App/store';
import { addCurrencyWallet } from '../../../redux/actions/addCurrencyWallet';
const Ava = `${process.env.PUBLIC_URL}/img/dashboard/ava.png`;
class TopbarProfile extends PureComponent {
constructor() {
super();
this.state = {
collapse: false,
};
}
toggle = () => {
this.setState({ collapse: !this.state.collapse });
};
logout = () => {
store.dispatch(addCurrencyWallet({isActive : false, success: false}));
Cache.setToCache('Auth', null);
}
render() {
let profile = this.props.profile;
return (
<div className="topbar__profile">
<button className="topbar__avatar" onClick={this.toggle}>
<img className="topbar__avatar-img" src={Ava} alt="avatar" />
<p className="topbar__avatar-name">{profile.getUsername()}</p>
<DownIcon className="topbar__icon" />
</button>
{this.state.collapse && <button className="topbar__back" onClick={this.toggle} />}
<Collapse isOpen={this.state.collapse} className="topbar__menu-wrap">
<div className="topbar__menu">
<TopbarMenuLink onClick={this.logout} title="Log Out" icon="exit" path="/login" />
</div>
</Collapse>
</div>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile,
addCurrencyWallet : state.addCurrencyWallet
};
}
export default connect(mapStateToProps)(TopbarProfile);
<file_sep>/src/containers/Account/LogIn/index.jsx
import React from 'react';
import { Link } from 'react-router-dom';
import FacebookIcon from 'mdi-react/FacebookIcon';
import GooglePlusIcon from 'mdi-react/GooglePlusIcon';
import LogInForm from './components/LogInForm';
import { Col, Row } from 'reactstrap';
import { BasicNotification } from '../../../shared/components/Notification';
import NotificationSystem from 'rc-notification';
import * as qs from 'query-string';
import StepWizard from 'react-step-wizard';
import Input2FA from '../../Inputs/Input2FA';
import ConnectionSingleton from '../../../api/Connection';
import Account from '../../../controllers/Account';
import { BackgroundBox, VerticalSection, BetProtocolLogo, Container, Card, CardHeader, CardContent, Footer } from './styles';
import TextLoop from 'react-text-loop';
const Back = `${process.env.PUBLIC_URL}/img/dashboard/background-login.png`;
let notification = null;
const showNotification = (message) => {
notification.notice({
content: <BasicNotification
title="There is a problem with your Login"
message={message}
/>,
duration: 5,
closable: true,
style: { top: 0, left: 'calc(100vw - 100%)' },
className: 'right-up',
});
};
const defaultState = {
SW : {}
}
const words = [
{ id: 0, text: 'BetProtocol' },
{ id: 1, text: 'Scalable' },
{ id: 2, text: 'Secure & Audited' },
{ id: 3, text: 'No Coding Required' },
];
const Description = (props) => {
const { wordList } = props;
return (
<TextLoop>
{wordList.map((word) => (
<span key={word.id}>{word.text}</span>
))}
</TextLoop>
);
};
class LogIn extends React.Component{
constructor(props){super(props); this.state = defaultState}
componentDidMount() {
NotificationSystem.newInstance({}, n => notification = n);
}
componentWillUnmount() {
notification.destroy();
}
showNotification = (message) => {
showNotification(message)
}
onChangeUsername = value => {
if (value) {
this.setState({
username: value
})
} else {
this.setState({
username: null
})
}
}
onChangePassword = value => {
if (value) {
this.setState({
password: value
})
} else {
this.setState({
password: null
})
}
}
getInitialRoute = (permission) => {
switch (true) {
case permission.super_admin:
return "/home";
case permission.financials:
return '/home';
case permission.customization:
return '/application';
case permission.withdraw:
return '/wallet';
case permission.user_withdraw:
return '/transactions';
default:
return '/home';
}
}
setInstance = SW => this.setState({ ...this.state, SW });
goTo2FA = () => this.state.SW.nextStep();
login2FA = async ({token}) => {
const { username, password } = this.state;
try{
this.setState({...this.state, isLoading : true})
let account = new Account({username, password, token});
const res = await account.login2FA();
this.props.history.push(this.getInitialRoute(res.data.message.permission))
this.setState({...this.state, isLoading : false})
}catch(err){
this.setState({...this.state, isLoading : false})
this.showNotification(err.message);
}
}
login = async () => {
try{
this.setState({...this.state, isLoading : true})
let account = new Account(this.state);
const res = await account.login();
this.props.history.push(this.getInitialRoute(res.data.message.permission));
this.setState({...this.state, isLoading : false})
}catch(err){
this.setState({...this.state, isLoading : false})
if(err.status == 37){
this.goTo2FA();
}else{
this.showNotification(err.message);
}
}
}
render = () => {
const { SW } = this.state;
const parsed = qs.parse(this.props.location.search);
return (
<>
<BackgroundBox>
<VerticalSection>
<ul>
<BetProtocolLogo />
<Description wordList={words} />
</ul>
<Container>
<Card>
<CardHeader />
<CardContent>
<h1>Login</h1>
<StepWizard
instance={this.setInstance}
>
<LogInForm isLoading={this.state.isLoading} login={this.login} onChangeUsername={this.onChangeUsername} onChangePassword={<PASSWORD>} query={parsed} SW={SW} handleSubmit={(e) => e.preventDefault()} showNotification={this.showNotification} {...this.props} onSubmit={false} />
<Input2FA isLoading={this.state.isLoading} SW={SW} confirm={this.login2FA}/>
</StepWizard>
</CardContent>
</Card>
<Footer>
<span>
<b>@BetProtocol</b> Technology is a SaaS Platform that provides
infrastructure for Gaming Applications
</span>
</Footer>
</Container>
</VerticalSection>
</BackgroundBox>
</>
)
}
};
export default LogIn;
<file_sep>/src/containers/Applications/Customization/components/Social/index.js
import React from 'react';
import { connect } from 'react-redux';
import { Card, CardBody } from 'reactstrap';
import LinksContainer from './LinksContainer';
import { Title } from './styles';
const cardBodyStyle = {
margin: 10,
borderRadius: "10px",
border: "solid 1px rgba(164, 161, 161, 0.35)",
backgroundColor: "#fafcff",
boxShadow: "none",
padding: 30
}
class Social extends React.Component {
constructor(props){
super(props);
this.state = {};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { profile } = props;
const { socialLink } = profile.getApp().getCustomization();
const socialLinks = socialLink ? socialLink.ids : [];
const socialLinksId = socialLink._id;
this.setState({
socialLinks: socialLinks.map(link => { return { name: link.name, href: link.href, image_url: link.image_url ? link.image_url : "" } }),
socialLinksId: socialLinksId
})
}
render() {
const { socialLinks, socialLinksId } = this.state;
return (
<>
<Card>
<CardBody style={cardBodyStyle}>
<Title>Social Links</Title>
<hr/>
{ socialLinks && (
<LinksContainer links={socialLinks} id={socialLinksId}/>
)}
</CardBody>
</Card>
</>
)
}
};
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(Social);<file_sep>/src/controllers/services/services.js
import Cache from "../../services/cache";
let services = {
casino : 101,
crypto : 201
}
function fromServicesToCodes(servicesObject){
return Object.keys(servicesObject).map( (key, index) => {
return servicesObject[key] ? services[key] : null;
}).filter((el) => el != null );
}
function fromCodesToServices(servicesObject){
return servicesObject.map( (code) => {
let array = Object.keys(services).map( (key) => {
if(code == services[key]){
return key;
}
}).filter((el) => el != null );
return array[0];
})
}
function fromBigNumberToInteger(value, decimals=18){
return value.toNumber() / Math.pow(10, decimals)*1000000000000000000;
}
function setAuthToCookies(params){
Cache.setToCache('Auth', params);
}
function getAuthFromCookies(){
return Cache.getFromCache('Auth');
}
export {
services,
fromBigNumberToInteger,
fromServicesToCodes,
fromCodesToServices,
setAuthToCookies,
getAuthFromCookies
}<file_sep>/src/containers/Applications/CurrenciesPage/VirtualCurrencyInfo.js
/* eslint-disable react/no-array-index-key */
import React from 'react';
import { Card, CardBody, Col, Row, Button } from 'reactstrap';
import { BankIcon, UploadIcon } from 'mdi-react';
import TextInput from '../../../shared/components/TextInput';
import EditLock from '../../Shared/EditLock';
import Dropzone from 'react-dropzone'
import _ from 'lodash';
const image2base64 = require('image-to-base64');
class VirtualCurrencyInfo extends React.Component {
constructor() {
super();
this.state = {
currencies: [],
lock: true
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
unlock = () => {
this.setState({...this.state, lock: false })
}
lock = () => {
this.setState({...this.state, lock: true })
}
onChangeInitialBalance = (value) => {
this.setState({ initialBalance: value ? parseFloat(value) : 0})
}
onChangeMultiplier = (value) => {
this.setState({ multiplier: value ? parseFloat(value) : 0})
}
onChange = (type, value) => {
this.setState({
[`new${type}`]: value ? parseFloat(value) : 0
})
}
projectData = async (props) => {
const { profile, data } = props;
const app = await profile.getApp();
if (this.isAdded('Initial Balance')) {
this.setState({ currencies: app.params.addOn.balance.initialBalanceList });
}
if (app.params.wallet.length > 0) {
this.setState({
wallet: app.params.wallet.find(w => w.currency._id === data._id)
})
}
}
getCurrency = (currencyId) => {
const { currencies } = this.state;
const currency = currencies.find(c => c.currency === currencyId);
return currency;
}
confirmChanges = async () => {
const { profile, data } = this.props;
const app = profile.getApp();
this.setState({...this.state, loading: true })
if (this.state.initialBalance || this.state.multiplier) {
await app.editInitialBalance({
balance: this.state.initialBalance ? this.state.initialBalance : this.getCurrency(data._id).initialBalance,
currency: data._id,
multiplier: this.state.multiplier ? this.state.multiplier : this.getCurrency(data._id).multiplier
});
}
if (this.state.newImage) {
await app.editVirtualCurrency({ params: { image: this.state.newImage } });
}
const prices = _.pickBy(this.state, (value, key) => key.startsWith("new"))
for (const [key, value] of Object.entries(prices)) {
const currency = key.replace("new", "");
await app.editVirtualCurrency({ params: { price: value, currency: currency, image: this.state.newImage ? this.state.newImage : this.getCurrencyImage(data._id) } });
}
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({...this.state, loading: false })
this.lock()
}
onAddedFile = async (files) => {
const file = files[0];
let blob = await image2base64(file.preview) // you can also to use url
this.setState({
newImage: blob
})
}
getCurrencyInfo = (currencyId) => {
const { profile } = this.props;
const currencies = profile.App.params.currencies;
return currencies.find(c => c._id === currencyId);
}
getCurrencyImage = (currencyId) => {
const { profile } = this.props;
const wallet = profile.App.params.wallet;
const currency = wallet.find(c => c.currency._id === currencyId);
return currency.image;
}
renderImage = (src) => {
if(!src.includes("https")){
src = "data:image;base64," + src;
}
return src;
}
isAdded = (AddOn) => {
const { profile } = this.props;
const app = profile.App;
const appAddOns = app.params.addOn;
return !!Object.keys(appAddOns).find(k => AddOn.toLowerCase().includes(k.toLowerCase()));
}
render() {
const { data } = this.props;
const { _id, name, ticker } = data;
const { lock, wallet, newImage } = this.state;
const hasInitialBalanceAddOn = this.isAdded('Initial Balance');
if(!data || !wallet){return null};
return (
<Card className='game-container' style={{ width: 307 }}>
<CardBody className="dashboard__card-widget" style={{ width: 370 , paddingBottom: 10, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<EditLock
unlockField={this.unlock}
lockField={this.lock}
confirmChanges={this.confirmChanges}
isLoading={this.state.loading}
locked={lock}>
<Row>
<Col lg={4} >
<img className='application__game__image'
style={{display: 'block', width: '60px'}}
src={newImage ? this.renderImage(newImage) : this.getCurrencyImage(_id)}/>
<div className="dashboard__visitors-chart text-center">
<p className="dashboard__visitors-chart-title text-center" style={{fontSize: 26}}> {name} </p>
</div>
<Dropzone onDrop={this.onAddedFile} style={{ width: '100%', marginTop: 7, marginBottom: 15 }} ref={(el) => (this.dropzoneRef = el)} disabled={this.state.lock}>
<Button className="icon" style={{ padding: 2, margin: 0}} disabled={this.state.lock}>
<p style={{ fontSize: '12px' }}><UploadIcon className="deposit-icon"/> New Logo </p>
</Button>
</Dropzone>
</Col>
{ hasInitialBalanceAddOn && (this.getCurrency(_id) !== undefined) ? (
<>
<Col lg={8} >
<h3 style={{ fontSize: 17, marginLeft: 0 }} className={"dashboard__total-stat"}>Inital Balance</h3>
<div style={{ display: "flex"}}>
<h3 style={{marginTop: 20, marginRight: 0}} className={"dashboard__total-stat"}>{this.getCurrency(_id).initialBalance.toFixed(6)}</h3>
<h3 style={{ fontSize: 17, marginLeft: 0 }} className={"dashboard__total-stat"}>{ticker}</h3>
</div>
<TextInput
icon={BankIcon}
name="initialBalance"
label={<h6 style={{ fontSize: 11 }}>New Intial Balance</h6>}
type="text"
disabled={lock}
changeContent={(type, value) => this.onChangeInitialBalance(value)}
/>
</Col>
<Col lg={8} style={{ margin: "15px 0px" }}>
<h3 style={{ fontSize: 17, marginLeft: 0 }} className={"dashboard__total-stat"}>Multiplier</h3>
<div style={{ display: "flex"}}>
<h3 style={{marginTop: 20, marginRight: 0}} className={"dashboard__total-stat"}>{this.getCurrency(_id).multiplier}</h3>
</div>
<TextInput
name="multiplier"
label={<h6 style={{ fontSize: 11 }}>New Multiplier</h6>}
type="text"
disabled={lock}
changeContent={(type, value) => this.onChangeMultiplier(value)}
/>
</Col>
</>
) : null}
<Col lg={8}>
{ !_.isEmpty(wallet.price) ? <h3 style={{ fontSize: 17, marginLeft: 0 }} className={"dashboard__total-stat"}>Price</h3> : null }
{wallet.price.map(p => (
<>
<br/>
<img src={this.getCurrencyInfo(p.currency).image} style={{float : 'left', marginRight : 4, width : 25, height : 25}}/>
<p className='bold-text' style={{margin: 0}}>{p.amount} {this.getCurrencyInfo(p.currency).name}</p>
<TextInput
style={{ margin: 0}}
name={p.currency}
label={<h6 style={{ fontSize: 11 }}>{`New ${this.getCurrencyInfo(p.currency).name} price`}</h6>}
type="text"
disabled={lock}
changeContent={(type, value) => this.onChange(type, value)}
/>
</>
))}
</Col>
</Row>
</EditLock>
</CardBody>
</Card>
);
}
}
export default VirtualCurrencyInfo;
<file_sep>/src/containers/Settings/components/SettingsBox.js
import React from 'react';
import { Col, Container, Row, Card, CardBody } from 'reactstrap';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import _ from 'lodash';
import EditLock from '../../Shared/EditLock';
import TextInput from '../../../shared/components/TextInput';
import DateInput from '../../../shared/components/DateInput';
class SettingsBox extends React.Component{
constructor(props){
super(props)
}
render = () => {
let {
title,
inputIcon,
currencyTicker,
image,
lock,
inputType,
type,
value,
new_value,
isLoading,
defaultValue,
/* Functions */
unlockField,
lockField,
onChange,
confirmChanges
} = this.props;
if(!inputType){
inputType = 'text'
}
return (
<Card>
<CardBody>
<Row>
<Col md={4}>
<img className='application__game__image' src={image}/>
<hr></hr>
<h5 className=""> {title} {currencyTicker ? `(${currencyTicker})` : null } </h5>
<h3 style={{marginTop : 20}} className={"bold-text dashboard__total-stat"}>{value}</h3>
</Col>
<Col md={8}>
<EditLock isLoading={isLoading} unlockField={unlockField} lockField={lockField} confirmChanges={confirmChanges} type={type} locked={lock}>
<h6 className="">New {title} </h6>
<h5 className={"bold-text dashboard__total-stat"}>{new_value} {currencyTicker} </h5>
{
inputType == 'text' ?
<TextInput
icon={inputIcon}
name={type}
type="number"
disabled={lock}
changeContent={ (type, value) => onChange({type, value})}
/>
: inputType == 'date' ?
<DateInput
name={type}
defaultValue={defaultValue}
label={type}
changeContent={ (type, value) => onChange({type, value})}
/>
: null
}
</EditLock>
</Col>
</Row>
</CardBody>
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
SettingsBox.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(SettingsBox);
<file_sep>/src/containers/Transactions/components/TransactionsFilterUserId.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col, Row } from 'reactstrap';
import AnimationNumber from '../../UI/Typography/components/AnimationNumber';
import Numbers from '../../../services/numbers';
import { AccountBoxIcon } from 'mdi-react';
import TextInput from '../../../shared/components/TextInput';
class TransactionsFilter extends PureComponent {
constructor(props) {
super(props);
this.state = {
activeIndex: 0,
filters : []
};
}
changeFilter = (key, value) => {
this.setState({[key] : value});
}
render() {
let depositAmount = this.props.data.data.totalDeposited;
return (
<Col md={12} xl={12} lg={12} xs={12}>
<Card>
<CardBody className="dashboard__card-widget">
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-title"> User Id <span> </span></p>
</div>
<Row>
<Col lg={3}>
<div className="dashboard__visitors-chart">
<TextInput
icon={AccountBoxIcon}
name="User Id"
label="user_id"
type="text"
placeholder="539d32f2837ry28374"
defaultValue={this.state.user_id}
changeContent={this.changeContent}
/>
</div>
</Col>
</Row>
</CardBody>
</Card>
</Col>
);
}
}
export default TransactionsFilter;
<file_sep>/src/containers/App/routes.js
import UsersContainer from '../Users';
import Applications from '../Applications';
import StatsContainer from '../Stats'
import { WalletContainer } from '../Wallet';
import DefaultDashboard from '../Dashboards/Default';
import AffiliatesContainer from '../Affiliates';
import SettingsContainer from '../Settings';
import BetsContainer from '../Bets';
import DepositWidget from '../Wallet/components/paths/DepositWidget';
import WithdrawWidget from '../Wallet/components/paths/WithdrawWidget';
import GamePage from '../Applications/GamePage';
import UserPage from '../Users/UserPage';
import WalletWidget from '../Wallet/components/paths/WalletWidget';
export default [
{
path: "/home",
name: 'Home',
component : DefaultDashboard
},
{
path: "/initial",
name: 'Initial'
},
{
path: "/users",
name: 'Users',
component : UsersContainer,
children : [
{
path : "/user",
name : 'User View',
component : UserPage
}
]
},
{
path: "/application",
name: 'Application',
component : Applications,
children : [
{
path : "/game",
name : 'Game',
component : GamePage
}
]
},
{
path: "/stats",
name: 'Financial Stats',
component : StatsContainer
},
{
path: "/transactions",
name: 'Transactions',
component: BetsContainer
},
{
path: "/bets",
name: 'Application Bets'
},
{
path: "/wallet",
name: 'Operator Wallet',
component : WalletContainer,
children : [
{
path : "/currency",
name : 'Wallet',
component : WalletWidget
}
]
},
{
path: "/affiliates",
name: 'Affiliates',
component : AffiliatesContainer
},
{
path: "/settings",
name: 'Settings',
component : SettingsContainer
},
{
path: "/account-settings",
name: 'Account Settings',
component : SettingsContainer
},
{
path: "/developers",
name: 'Developers'
},
];<file_sep>/src/containers/Applications/Customization/components/SubSections/EditSubSection/index.js
import React, { Component } from 'react'
import _ from 'lodash';
import '../styles.css';
import { Container, SectionGrid, Title, Text, Image, DropzoneImage, BackgroundItems, UploadButton, RemoveButton, BackgroundImage, DialogHeader, ConfirmButton } from './styles';
import { FormGroup } from 'reactstrap';
import Dropzone from 'react-dropzone'
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import { createMuiTheme, MuiThemeProvider, withStyles, Dialog, DialogContent, ButtonBase } from '@material-ui/core';
import ColorPicker from '../../../../../../shared/components/color_picker_input/ColorPicker';
import { InputField, InputLabel } from '../styles';
import { UploadIcon, TrashCanOutlineIcon, CloseIcon, TitleBackwardIcon, ContentSaveIcon } from 'mdi-react';
const upload = `${process.env.PUBLIC_URL}/img/dashboard/upload.png`;
const trash = `${process.env.PUBLIC_URL}/img/dashboard/clear.png`;
const image2base64 = require('image-to-base64');
const dropzoneStyle = {
width: "100%",
height: "100%",
backgroundColor: "white",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
};
const theme = createMuiTheme({
palette: {
primary: {
main: '#894798'
}
},
});
const StyledFormControlLabel = withStyles({
label: {
fontFamily: "Poppins",
fontSize: "15px"
},
})(FormControlLabel);
const positionsEnum = Object.freeze({
0: "RightImage",
1: "LeftImage",
2: "BottomImage",
3: "TopImage"
});
class EditSection extends Component {
constructor(props){
super(props);
this.state = {};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { subSection } = props;
if (!_.isEmpty(subSection)) {
const { _id, position, location, image_url, background_url, background_color, title, text } = subSection;
this.setState({ _id, position, location, image_url, background_url, background_color, title, text });
}
}
handleConfirmChanges = () => {
const { setSubSections, subSections, setClose } = this.props;
const { _id, position, location, image_url, background_url, background_color, title, text } = this.state;
const index = subSections.findIndex(subSection => subSection._id === _id);
const newSubSections = [...subSections];
newSubSections[index] = { _id, position, location, image_url, background_url, background_color, title, text };
setSubSections({
newSubSections: newSubSections.filter(subSections => !_.isEmpty(subSections))
})
setClose();
}
renderImage = (src) => {
if(!src.includes("https")){
src = "data:image;base64," + src;
}
return src;
}
onAddedNewFile = async ({ files }) => {
const file = files[0];
let blob = await image2base64(file.preview)
this.setState({ image_url: blob })
}
onAddedNewBackgroundImage = async (files) => {
const file = files[0];
let blob = await image2base64(file.preview)
this.setState({ background_url: blob })
}
renderAddNewImage = () => {
const { locked } = this.props;
return(
<DropzoneImage>
<Dropzone disabled={locked} style={dropzoneStyle} onDrop={(files) => this.onAddedNewFile({ files: files })} ref={(el) => (this.dropzoneRef = el)}>
<img src={upload} alt="upload" style={{ height: 20, width: 20 }}/>
<p className='text-center'>Drop the image here</p>
</Dropzone>
</DropzoneImage>
)
}
removeNewImage = () => {
this.setState({ image_url: "" })
}
removeNewBackgroundImage = () => {
this.setState({ background_url: "" })
}
onChange = ({ type, value }) => {
this.setState({ [type]: value })
}
handleChangePosition = event => {
event.preventDefault();
this.setState({ position: parseInt(event.target.value) })
}
handleChangeLocation = event => {
event.preventDefault();
this.setState({ location: parseInt(event.target.value) })
}
handleChangeBackgroundColor = ({ _type, value }) => {
this.setState({ background_color: value })
}
handleChangeNewTitle = ({ value }) => {
this.setState({ title: value ? value : "" })
}
handleChangeNewText = ({ value }) => {
this.setState({ text: value ? value : "" })
}
render() {
const { locked, open, setClose, subSection } = this.props;
if (!subSection) return null;
const { position, location, image_url, background_url, background_color, title, text } = this.state;
return (
<Dialog open={open} fullWidth maxWidth="lg">
<DialogHeader>
<ButtonBase onClick={() => setClose()}>
<CloseIcon/>
</ButtonBase>
</DialogHeader>
<DialogContent>
<Container>
<SectionGrid className={positionsEnum[position]} backgroundColor={background_color}>
<Title>
<h1>{title}</h1>
</Title>
<Text>
<p>{text}</p>
</Text>
{ background_url && (
<BackgroundImage>
<img style={{ width: "100%", height: "100%", objectFit: "cover" }} alt="Background" src={this.renderImage(background_url)}/>
</BackgroundImage>
)}
<Image>
{ image_url ? (
<>
<div style={{ display: "flex", justifyContent: "flex-end", width: "100%", marginTop: -5.5, marginBottom: -30 }}>
<button
disabled={locked}
onClick={() => this.removeNewImage()}
style={{ position: "inherit", zIndex: 20, right: 20, top: 6, backgroundColor: "transparent" }}
className='carousel-trash button-hover'>
<img src={trash} alt="remove" style={{ width: 15, height: 15 }}/>
</button>
</div>
<img style={{ width: "100%", height: "100%", objectFit: "cover" }} alt="Image" src={this.renderImage(image_url)}/>
</>
) : (
this.renderAddNewImage()
)}
</Image>
</SectionGrid>
<div style={{ display: "flex", flexDirection: "column" }}>
<FormGroup style={{ margin: 0 }}>
<InputLabel for="title">Title</InputLabel>
<InputField
label="Title"
name="title"
type="text"
value={title}
disabled={locked}
onChange={(e) => this.handleChangeNewTitle({ value: e.target.value })}
/>
</FormGroup>
<FormGroup style={{ margin: 0 }}>
<InputLabel for="text">Text</InputLabel>
<InputField
label="Text"
name="text"
type="text"
value={text}
disabled={locked}
onChange={(e) => this.handleChangeNewText({ value: e.target.value })}
/>
</FormGroup>
<BackgroundItems>
<FormGroup style={{ marginTop: 10 }}>
<InputLabel for="backgroundColor">Background color</InputLabel>
<ColorPicker
name="backgroundColor"
color={background_color}
disabled={locked}
onChange={this.handleChangeBackgroundColor}
/>
</FormGroup>
<FormGroup style={{ marginTop: 10 }}>
<InputLabel>Background image</InputLabel>
{ !background_url ? (
<Dropzone onDrop={this.onAddedNewBackgroundImage} style={{ width: '100%', marginTop: 7, marginBottom: 15 }} ref={(el) => (this.dropzoneRef = el)} disabled={locked}>
<UploadButton disabled={locked}>
<p style={{ fontSize: '12px', color: "white" }}><UploadIcon className="deposit-icon"/> New background image </p>
</UploadButton>
</Dropzone>
) : (
<div style={{ width: '100%', marginTop: 7, marginBottom: 15 }}>
<RemoveButton onClick={() => this.removeNewBackgroundImage()} disabled={locked}>
<p style={{ fontSize: '12px', color: "white" }}><TrashCanOutlineIcon className="deposit-icon"/> Remove background image </p>
</RemoveButton>
</div>
)}
</FormGroup>
</BackgroundItems>
<MuiThemeProvider theme={theme}>
<InputLabel>Positioning</InputLabel>
<RadioGroup row aria-label="position" name="position" value={position} onChange={this.handleChangePosition}>
<StyledFormControlLabel value={0} control={<Radio color="primary" size="small" />} label="Image on the right" disabled={locked}/>
<StyledFormControlLabel value={1} control={<Radio color="primary" size="small" />} label="Image on the left" disabled={locked}/>
<StyledFormControlLabel value={2} control={<Radio color="primary" size="small" />} label="Image on the bottom" disabled={locked}/>
<StyledFormControlLabel value={3} control={<Radio color="primary" size="small" />} label="Image on the top" disabled={locked}/>
</RadioGroup>
<br/>
<InputLabel>Location</InputLabel>
<RadioGroup row aria-label="location" name="location" value={location} onChange={this.handleChangeLocation}>
<StyledFormControlLabel value={0} control={<Radio color="primary" size="small" />} label="Before the banners" disabled={locked}/>
<StyledFormControlLabel value={1} control={<Radio color="primary" size="small" />} label="Before the games list" disabled={locked}/>
<StyledFormControlLabel value={2} control={<Radio color="primary" size="small" />} label="Before the data lists" disabled={locked}/>
<StyledFormControlLabel value={3} control={<Radio color="primary" size="small" />} label="Before the footer" disabled={locked}/>
<StyledFormControlLabel value={4} control={<Radio color="primary" size="small" />} label="After the footer" disabled={locked}/>
</RadioGroup>
</MuiThemeProvider>
<div style={{ display: "flex", justifyContent: "flex-end", padding: "10px 20px" }}>
<ConfirmButton onClick={() => this.handleConfirmChanges()}>
<ContentSaveIcon style={{ margin: "0px 7px" }}/> Confirm changes
</ConfirmButton>
</div>
</div>
</Container>
</DialogContent>
</Dialog>
)
}
}
export default EditSection;
<file_sep>/src/containers/Settings/tabs/Components/AdminCard.js
import React, { Component } from 'react'
import { Card, CardBody, Col, Row } from 'reactstrap';
import { Grid, FormControl, FormGroup, FormControlLabel, Checkbox, createMuiTheme, ThemeProvider } from '@material-ui/core';
import { CheckBoxOutlineBlankIcon, CheckBoxIcon } from 'mdi-react';
import BooleanInput from "./BooleanInput";
import LockAdmin from './LockAdmin';
import { connect } from 'react-redux';
const theme = createMuiTheme({
palette: {
primary: {
main: '#894798'
}
},
});
class AdminCard extends Component {
constructor(props){
super(props)
this.state = {
lock: true,
loading: false
};
}
componentDidMount() {
this.projectData(this.props)
}
componentWillReceiveProps(props) {
this.projectData(props);
}
projectData = async (props) => {
const { id, email, name, registered, permission } = this.props.data;
this.setState({ id, email, name, registered, permission })
}
handleChange = (event) => {
event.persist();
this.setState(prevState => ({ permission: {
...prevState.permission,
[event.target.name]: event.target.checked }}));
}
onChangeSuperAdmin = () => {
const { super_admin } = this.state.permission;
this.setState({
permission: {...this.state.permission, super_admin: !super_admin } })
}
unlock = () => {
this.setState({ lock: false })
}
lock = () => {
this.setState({ lock: true })
}
confirmChanges = async () => {
const { id, permission } = this.state;
const { profile } = this.props;
this.setState({...this.state, loading: true });
await profile.editAdminType({ adminToModify: id, permission: permission });
this.setState({...this.state, loading: false });
this.lock();
}
render() {
const { id, email, name, registered, permission, lock, loading } = this.state;
if (!permission) return null;
const { super_admin, customization, withdraw, user_withdraw, financials } = permission;
return (
<Card className='game-container'>
<CardBody className="dashboard__card-widget" style={{ width: 310, padding: 20, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<div style={{ display: "flex" }}>
<h5 className="bold-text">{name}</h5>
<p className={`text-small ${registered ? "text-green" : "text-red"} `} style={{ margin: 0, marginLeft: 5 }} >
{ registered ? "( Registered )" : "( Pending )" }
</p>
</div>
<h5 className="subhead">{id}</h5>
<p className="dashboard__visitors-chart-title">{email}</p>
<LockAdmin
unlockField={this.unlock}
lockField={this.lock}
confirmChanges={this.confirmChanges}
isLoading={loading}
locked={lock}
add={false}
>
<FormControlLabel
style={{margin: 0, marginTop: 10 }}
control={
<BooleanInput
checked={super_admin}
onChange={this.onChangeSuperAdmin}
color="primary"
name="isSuperAdmin"
disabled={lock}
inputProps={{ 'aria-label': 'Super Admin' }}
/>}
label={super_admin ? <h4 style={{ fontSize: 13 }}>Super Admin</h4>
: <h4 style={{ fontSize: 13 }}>Collaborator</h4>}
labelPlacement="right"
/>
<hr style={{ margin: 7 }}/>
<ThemeProvider theme={theme}>
<FormControl component="fieldset" disabled={lock || super_admin}>
<FormGroup>
<FormControlLabel
control={
<Checkbox
style={{ width: 36, height: 36 }}
color="primary"
icon={<CheckBoxOutlineBlankIcon style={{ fontSize: 20 }} />}
checkedIcon={<CheckBoxIcon style={{ fontSize: 20 }} />}
checked={customization || super_admin } onChange={(e) => this.handleChange(e)} name="customization" />}
label={<span style={{ fontSize: "13px" }}>Customization</span>}
style={{ margin: 0 }}
/>
<FormControlLabel
control={
<Checkbox
style={{ width: 36, height: 36 }}
color="primary"
icon={<CheckBoxOutlineBlankIcon style={{ fontSize: 20 }} />}
checkedIcon={<CheckBoxIcon style={{ fontSize: 20 }} />}
checked={withdraw || super_admin } onChange={(e) => this.handleChange(e)} name="withdraw" />}
label={<span style={{ fontSize: "13px" }}>Withdraw</span>}
style={{ margin: 0 }}
/>
<FormControlLabel
control={
<Checkbox
style={{ width: 36, height: 36 }}
color="primary"
icon={<CheckBoxOutlineBlankIcon style={{ fontSize: 20 }} />}
checkedIcon={<CheckBoxIcon style={{ fontSize: 20 }} />}
checked={user_withdraw || super_admin } onChange={(e) => this.handleChange(e)} name="user_withdraw" />}
label={<span style={{ fontSize: "13px" }}>User withdraw</span>}
style={{ margin: 0 }}
/>
<FormControlLabel
control={
<Checkbox
style={{ width: 36, height: 36 }}
color="primary"
icon={<CheckBoxOutlineBlankIcon style={{ fontSize: 20 }} />}
checkedIcon={<CheckBoxIcon style={{ fontSize: 20 }} />}
checked={financials || super_admin } onChange={(e) => this.handleChange(e)} name="financials" />}
label={<span style={{ fontSize: "13px" }}>Financials</span>}
style={{ margin: 0 }}
/>
</FormGroup>
</FormControl>
</ThemeProvider>
</LockAdmin>
</CardBody>
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(AdminCard);<file_sep>/src/api/Connection.js
import React from 'react';
import config from "./config";
import { API_URL, API_URL_WITHDRAW, REACT_APP_EXTERNAL_APPROVE_WITHDRAW, REACT_APP_EXTERNAL_CANCEL_WITHDRAW } from "../config/apiConfig";
import { BasicNotification } from "../shared/components/Notification";
import Notification from 'rc-notification';
import _ from 'lodash';
const URL = API_URL;
class Connection {
constructor(){}
/**
* @param
*/
handleResponse = async response => {
const json = await response.json();
const { message, status, errors } = json;
if (message && errors && errors[0].message) {
!_.isEmpty(errors[0].errors)
? this.showNotification(message, errors[0].errors[0].message)
: this.showNotification(message, errors[0].message)
} else if (message && status && parseInt(status) !== 200 ) {
this.showNotification("There is a problem with your request", message);
}
return json;
}
showNotification = (title, message) => {
Notification.newInstance({}, notification => {
notification.notice({
content: <BasicNotification
title={title}
message={message}
/>,
duration: 5,
closable: true,
style: { top: 0, left: 'calc(100vw - 100%)' },
className: 'right-up',
}); })
};
auth = async ({admin, headers}) => {
try{
let response = await fetch(URL + '/api/admins/auth', {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify({admin})
});
return response.json();
}catch(err){
throw err;
}
}
register = async ({username, password, name, email, bearerToken}) => {
try{
let data = {username, password, name, email};
if(bearerToken != null){
data['bearerToken'] = bearerToken;
}
let response = await fetch(URL + '/api/admins/register', {
method : 'POST',
headers : config.headers,
body : JSON.stringify(data)
});
return response.json();
}catch(err){
throw err;
}
}
login = async ({username, password}) => {
try{
let response = await fetch(URL + '/api/admins/login', {
method : 'POST',
headers : config.headers,
body : JSON.stringify({username, password})
});
return response.json();
}catch(err){
throw err;
}
}
login2FA = async ({username, password, token}) => {
try{
let response = await fetch(URL + '/api/admins/login/2fa', {
method : 'POST',
headers : config.headers,
body : JSON.stringify({username, password, '2fa_token' : token})
});
return response.json();
}catch(err){
throw err;
}
}
resetAdminPassword = async ({ username_or_email }) => {
try{
let response = await fetch(URL + '/api/admins/password/reset/ask', {
method : 'POST',
headers : config.headers,
body : JSON.stringify({ username_or_email })
});
return response.json();
}catch(err){
throw err;
}
}
confirmResetAdminPassword = async ({ token, password, admin_id }) => {
try{
let response = await fetch(URL + '/api/admins/password/reset/set', {
method : 'POST',
headers : config.headers,
body : JSON.stringify({ token, password, admin_id })
});
return response.json();
}catch(err){
throw err;
}
}
createApp = async ({name, description, virtual, metadataJSON, admin_id, marketType}) => {
try{
let response = await fetch(URL + '/api/app/create', {
method : 'POST',
headers : config.headers,
body : JSON.stringify({name, description, virtual, metadataJSON, admin_id, marketType})
});
return response.json();
}catch(err){
throw err;
}
}
deployApp = async ({params, headers}) => {
try{
let response = await fetch(URL + '/api/app/deploy', {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
throw err;
}
}
getSummary = async ({params, headers}) => {
try{
let response = await fetch(URL+ '/api/app/summary', {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
throw err;
}
}
getApp = async ({admin, app, headers}) => {
try{
let response = await fetch(URL+ '/api/app/get/auth', {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify({admin, app})
});
return response.json();
}catch(err){
throw err;
}
}
editApp = async ({params, headers}) => {
try{
let response = await fetch(URL+ '/api/app/edit', {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
updateAppBalance = async ({params, headers}) => {
try{
let response = await fetch(URL+ '/api/app/update/balance', {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editTableLimit = async ({admin, app, game, tableLimit, wallet, headers}) => {
try{
let response = await fetch(URL+ '/api/app/games/editTableLimit', {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify({admin, app, game, tableLimit : parseFloat(tableLimit), wallet})
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editEdge = async ({admin, app, game, edge, headers}) => {
try{
let response = await fetch(URL+ '/api/app/games/editEdge', {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify({admin, app, game, edge})
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editVideogamesEdge = async ({admin, app, esports_edge, headers}) => {
try{
let response = await fetch(URL+ '/api/app/videogames/editEdge', {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify({admin, app, esports_edge})
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editRestrictedCountries = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/restrictedCountries/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response)
}catch(err){
throw err;
}
}
getTransactions = async ({admin, app, filters, headers}) => {
try{
let response = await fetch(URL + '/api/app/transactions', {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify({admin, app, filters})
});
return response.json();
}catch(err){
throw err;
}
}
getUsersTransactions = async ({params, headers}) => {
try{
let response = await fetch(API_URL_WITHDRAW + `/api/user/transactions/backoffice`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response)
}catch(err){
throw err;
}
}
confirmUserAction = async ({params, headers}) => {
try{
let response = await fetch(URL + `/api/app/process/confirm`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response)
}catch(err){
throw err;
}
}
externalApproveWithdraw = async ({params, headers}) => {
try{
let response = await fetch(`${REACT_APP_EXTERNAL_APPROVE_WITHDRAW}`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response)
}catch(err){
throw err;
}
}
externalCancelWithdraw = async ({params, headers}) => {
try{
let response = await fetch(`${REACT_APP_EXTERNAL_CANCEL_WITHDRAW}`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response)
}catch(err){
throw err;
}
}
getDepositReference = async ({currency, entity, headers}) => {
try{
let response = await fetch(URL+ '/api/app/deposit/generateReference', {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify({
"entity" : entity,
"currency" : currency
})
});
return response.json();
}catch(err){
throw err;
}
}
getEcosystemVariables = async () => {
try{
let response = await fetch(URL+ `/api/ecosystem/all`, {
method : 'GET',
headers : addHeaders(config),
});
return response.json();
}catch(err){
throw err;
}
}
getEcosystemLanguages = async () => {
try{
let response = await fetch(URL+ `/api/app/languageEcosystem/get`, {
method : 'GET',
headers : addHeaders(config),
});
return response.json();
}catch(err){
throw err;
}
}
getEcosystemSkins = async () => {
try{
let response = await fetch(URL+ `/api/app/skinEcosystem/get`, {
method : 'GET',
headers : addHeaders(config),
});
return response.json();
}catch(err){
throw err;
}
}
getDepositInfo = async ({id, headers}) => {
try{
let response = await fetch(URL+ `/api/deposit/${id}/info`, {
method : 'POST',
headers : addHeaders(config, headers),
});
return response.json();
}catch(err){
throw err;
}
}
addServices = async ({admin, app, services, headers}) => {
try{
let response = await fetch( URL + `/api/app/services/add`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify({
app,
admin,
services
})
});
return response.json();
}catch(err){
throw err;
}
}
set2FA = async ({secret, token, admin, headers}) => {
try{
let response = await fetch( URL + `/api/admins/2fa/set`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify({
admin,
'2fa_secret' : secret,
'2fa_token' : token
})
});
return response.json();
}catch(err){
throw err;
}
}
updateWallet = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/updateWallet`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
console.log(err);
throw err;
}
}
modifyUserBalance = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/balance/modify`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
changeMaxDeposit = async ({params, headers}) => {
try{
params.amount = parseFloat(params.amount)
let response = await fetch( URL + `/api/deposit/max/set`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
console.log(err);
throw err;
}
}
changeMaxWithdraw = async ({params, headers}) => {
try{
params.amount = parseFloat(params.amount)
let response = await fetch( URL + `/api/withdraw/max/set`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
console.log(err);
throw err;
}
}
changeMinWithdraw = async ({params, headers}) => {
try{
params.amount = parseFloat(params.amount)
let response = await fetch( URL + `/api/withdraw/min/set`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
console.log(err);
throw err;
}
}
changeAffiliateMinWithdraw = async ({params, headers}) => {
try{
params.amount = parseFloat(params.amount)
let response = await fetch( URL + `/api/affiliate/withdraw/min/set`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
console.log(err);
throw err;
}
}
requestWithdraw = async ({params, headers}) => {
try{
let response = await fetch( API_URL_WITHDRAW + `/api/app/requestWithdraw`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
finalizeUserWithdraw = async ({params, headers}) => {
try{
let response = await fetch( API_URL_WITHDRAW + `/api/users/finalizeWithdraw`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
cancelUserWithdraw = async ({params, headers}) => {
try{
let response = await fetch( API_URL_WITHDRAW + `/api/users/cancelWithdraw`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
finalizeWithdraw = async ({params, headers}) => {
try{
let response = await fetch( API_URL_WITHDRAW + `/api/app/finalizeWithdraw`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
getGames = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/games/getAll`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
throw err;
}
}
getUserBets = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/get/users/bets`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
throw err;
}
}
getAllBets = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/get/users/bets`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
throw err;
}
}
getLogs = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/logs/get`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
throw err;
}
}
getDepositInfo = async ({id, headers}) => {
try{
let response = await fetch(URL+ `/api/deposit/${id}/info`, {
method : 'POST',
headers : addHeaders(config, headers),
});
return response.json();
}catch(err){
throw err;
}
}
cancelWithdraw = async ({app, headers}) => {
try{
let response = await fetch( URL + `/api/app/cancelWithdraw`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify({
app,
})
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
getEcosystemGames = async () => {
try{
let response = await fetch( URL + `/api/ecosystem/games/casino`, {
method : 'GET',
});
return response.json();
}catch(err){
throw err;
}
}
addGameToPlatform = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/games/add`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
addAddOn = async ({url, params, headers}) => {
try{
let response = await fetch( URL + `/api${url}`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editAutoWithdraw = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/autoWithdraw/editAutoWithdraw`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editTxFee = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/txFee/editTxFee`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editDepositBonus = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/depositBonus/editDepositBonus`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editPointSystem = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/pointSystem/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editFreeCurrency = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/freeCurrency/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
convertPoints = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/convert/points`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editJackpot = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/jackpot/edge/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editInitialBalance = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/balance/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editVirtualCurrency = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/wallet/virtualCurrency/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editAffiliateStructure = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/affiliate/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
setCustomAffiliateStructureToUser = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/affiliate/custom/add`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
throw err;
}
}
editLanguage = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/language/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editTopBarCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/topBar`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editSkinTypeCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/skin`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editTypography = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/typography`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editIntegration = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/integrations/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editCrispIntegration = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/integrations/cripsr/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editEmailIntegration = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/integrations/mailSender/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editKYCIntegration = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/integrations/kyc/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editAnalyticsIntegration = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/analytics/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editMoonPayIntegration = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/integrations/moonpay/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editUserKYC = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/user/kyc_needed/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editBannersCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/banners`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editEsportsPageCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/esportsScrenner`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editLogoCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/logo`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editBackgroundCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/background`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editFaviconCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/topicon`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editLoadingGifCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/loadinggif`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editThemeCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/theme`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editGameImage = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/games/editImage`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editBackgroundImage = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/games/editBackgroundImage`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
addCurrencyWallet = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/wallet/currency/add`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editColorsCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/colors`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editFooterCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/footer`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editSocialLinksCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/socialLink`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editTopTabCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/topTab`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editIconsCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/icons`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editSubsectionsCustomization = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/subSections`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
createProvider = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/provider/create`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editProvider = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/provider/edit`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
getAllGameProviders = async () => {
try{
const response = await fetch( URL + `/api/app/providerEcosystem/get`, {
method: 'GET'
});
return response.json();
}catch(err){
throw err;
}
}
getAppUsers = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/users`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
throw err;
}
}
getUser = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/user/get`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
throw err;
}
}
getGameStats = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/game/stats`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
throw err;
}
}
getDeposits = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/deposit/get`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
throw err;
}
}
getWithdraws = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/users/withdraws`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
throw err;
}
}
addAdmin = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/admins/add`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
addLanguage = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/customization/language/add`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
editAdminType = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/admins/editType`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return this.handleResponse(response);
}catch(err){
throw err;
}
}
getComplianceFile = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/app/compliance/get`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
throw err;
}
}
getAdminByApp = async ({params, headers}) => {
try{
let response = await fetch( URL + `/api/admin/app/get`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
return response.json();
}catch(err){
throw err;
}
}
}
function addHeaders(config, newHeaders){
return {
...config.headers,
...newHeaders
}
}
let ConnectionSingleton = new Connection();
export default ConnectionSingleton;
<file_sep>/src/containers/Applications/EsportsPage/components/Skeletons/VideogameTabSkeleton/index.js
import React from 'react';
import { Container, Action, VideoGameIcon } from './styles';
import Skeleton from '@material-ui/lab/Skeleton';
import videogamesEnum from '../../Enums/videogames';
const VideoGameTabSkeleton = props => {
const { hasEsports } = props;
return (
<Container>
<Action>
<Skeleton variant="circle" width="35px" height="35px" animation={hasEsports} />
</Action>
<VideoGameIcon>
<Skeleton variant="rect" width="100%" height="100%" animation={hasEsports} />
</VideoGameIcon>
{ Object.keys(videogamesEnum).map(_videogame => (
<VideoGameIcon>
<Skeleton variant="rect" width="100%" height="100%" animation={hasEsports} />
</VideoGameIcon>
))}
</Container>
)
}
export default VideoGameTabSkeleton;<file_sep>/src/containers/Applications/EsportsPage/components/StatsPage/components/LastGames/index.js
import React from 'react';
import Avatar from 'react-avatar';
import { Container, Header, TeamResult, Team, TeamIcon, TeamName, MatchResultList, MatchResult } from './styles';
import _ from 'lodash';
import LastGamesSkeleton from '../../../Skeletons/LastGamesSkeleton';
const results = Object.freeze({
won: { text: "W", color: "#52b030" },
lost: { text: "L", color: "#ec5050" },
draw: { text: "D", color: "#b0b0b0" }
})
const getResult = ({ id, winner }) => {
switch (true) {
case winner.id === null:
return results.draw
case id === winner.id:
return results.won
case id !== winner.id:
return results.lost
default:
break;
}
}
const Result = team => {
const { id, name, image_url, last_games } = team.team;
return (
<>
<TeamResult>
<Team>
<TeamIcon>
{ image_url ? <img src={image_url} alt={name}/> : <Avatar name={name} size="22" round={true}/> }
</TeamIcon>
<TeamName>
<span>{ name }</span>
</TeamName>
</Team>
<MatchResultList>
{ last_games.map(game => (
<MatchResult color={getResult({ id, winner: game.winner }).color}>
<span>{ getResult({ id, winner: game.winner }).text }</span>
</MatchResult>
))}
</MatchResultList>
</TeamResult>
</>
)
}
const LastGames = props => {
const { teamOne, teamTwo, isLoading } = props;
if (isLoading) return <LastGamesSkeleton/>
if (_.isEmpty(teamOne) || _.isEmpty(teamTwo)) return null;
return (
<>
<Container>
<Header>
<span>Last games</span>
</Header>
<Result team={teamOne}/>
<Result team={teamTwo}/>
</Container>
</>
)
}
export default LastGames;<file_sep>/src/redux/reducers/index.js
import themeReducer from './themeReducer';
import sidebarReducer from './sidebarReducer';
import cryptoTableReducer from './cryptoTableReducer';
import newOrderTableReducer from './newOrderTableReducer';
import customizerReducer from './customizerReducer';
import profileReducer from './profileReducer';
import appCreationReducer from './appCreationReducer';
import gameReducer from './gameReducer';
import loadingReducer from './loadingReducer';
import messageContainerReducer from './messageContainerReducer';
import periodicityReducer from './periodicityReducer';
import set2FAReducer from './set2FAReducer';
import userViewReducer from './userViewReducer';
import modalReducer from './modalReducer';
import currencyReducer from './currencyReducer';
import walletReducer from './walletReducer';
import addCurrencyWalletReducer from './addCurrencyWalletReducer';
import videogamesReducer from './videogamesReducer';
import seriesReducer from './seriesReducer';
import matchesReducer from './matchesReducer';
import summaryReducer from './summaryReducer';
export {
themeReducer,
sidebarReducer,
currencyReducer,
modalReducer,
set2FAReducer,
walletReducer,
userViewReducer,
cryptoTableReducer,
loadingReducer,
messageContainerReducer,
gameReducer,
periodicityReducer,
newOrderTableReducer,
customizerReducer,
profileReducer,
appCreationReducer,
addCurrencyWalletReducer,
videogamesReducer,
seriesReducer,
matchesReducer,
summaryReducer
};
<file_sep>/src/containers/Applications/components/GameInfo.jsx
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col, Row } from 'reactstrap';
import Skeleton from "@material-ui/lab/Skeleton";
import AnimationNumber from '../../UI/Typography/components/AnimationNumber';
import Numbers from '../../../services/numbers';
import game_images from './game_images';
import store from '../../App/store';
import { setGameView } from '../../../redux/actions/game';
import { connect } from "react-redux";
import { Grid, ButtonBase } from '@material-ui/core';
class GameInfo extends PureComponent {
constructor() {
super();
this.state = {
activeIndex: 0,
};
}
goToGamePage = async () => {
let game = this.props.game;
await store.dispatch(setGameView(game));
this.props.history.push('/application/game');
}
render() {
const { currency, isLoading } = this.props;
let game = this.props.game;
let ticker = currency.ticker;
let game_image = game_images[new String(game.name).toLowerCase().replace(/ /g,"_")];
const image = game_image ? game_image : game_images.default;
return (
<Col md={12} xl={12} lg={12} xs={12} style={{height: `100%`, minWidth: 290 }}>
{isLoading ? (
<>
<Card className='game-container'>
<CardBody className="dashboard__card-widget" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<Grid container direction='row' spacing={1}>
<Grid item xs={9}>
<Skeleton variant="rect" width={120} height={29} style={{ marginTop: 10, marginBottom: 10 }}/>
</Grid>
<Grid item xs={3}>
<Skeleton variant="circle" width={50} height={50} style={{ marginBottom: 10, marginLeft: 'auto', marginRight: 0 }}/>
</Grid>
</Grid>
<Skeleton variant="rect" width={120} height={29} style={{ marginBottom: 10 }}/>
<Skeleton variant="rect" height={130} style={{ marginBottom: 10 }}/>
</CardBody>
</Card>
</>
) : (
<Card className='game-container'>
<ButtonBase onClick={ () => this.goToGamePage() } style={{ borderRadius: 10 }}>
<CardBody className="dashboard__card-widget" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<Row>
<Col lg={8} >
<div className="dashboard__visitors-chart text-left">
<p className="dashboard__visitors-chart-title text-left" style={{fontSize : 20}}> {game.name} </p>
</div>
<div className="dashboard__visitors-chart text-left" style={{marginTop : 10}}>
<p className="application__span" >Edge</p>
<h4><AnimationNumber number={game.edge}/>%</h4>
</div>
</Col>
<Col lg={4} >
<img className='application__game__image' style={{width: `50px`}} src={image}/>
</Col>
</Row>
<hr/>
<Row>
<Col lg={6} >
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-title"> Profit </p>
</div>
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-number-second" style={
{color : '#646777'}
}><AnimationNumber decimals={6} number={game.profit}/> <span> {ticker}</span></p>
</div>
</Col>
<Col lg={6} >
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-title"> Bets Amount</p>
</div>
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-number-second" style={
{color : '#646777'}
}><AnimationNumber decimals={0} number={game.betAmount-1}/></p>
</div>
</Col>
</Row>
<p className="application__span">this week </p>
</CardBody>
</ButtonBase>
</Card>
)}
</Col>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile,
currency : state.currency
};
}
export default connect(mapStateToProps)(GameInfo);
<file_sep>/src/containers/Users/UserPage/components/UserPageSkeleton/index.js
import React from 'react';
import Fade from '@material-ui/core/Fade';
import Skeleton from '@material-ui/lab/Skeleton';
import { Card, CardBody, Col, Container, Row } from 'reactstrap';
import _ from 'lodash';
class UserPageSkeleton extends React.Component{
renderDataTitle = ({ title }) => {
return (
<Card>
<CardBody className="dashboard__card-widget" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<p className='text-small pink-text'> {title} </p>
<Skeleton variant="rect" height={12} style={{ marginTop: 10, marginBottom: 10 }}/>
</CardBody>
</Card>
)
}
renderBalanceData = ({ title }) => {
return (
<Card>
<CardBody className="dashboard__card-widget" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none", paddingBottom: 10, paddingRight: 10 }}>
<p className='text-small pink-text'> {title} </p>
<Skeleton variant="rect" height={12} style={{ marginTop: 10, marginBottom: 10 }}/>
</CardBody>
</Card>
)
}
render = () => {
return (
<Fade in timeout={{ appear: 200, enter: 200, exit: 200 }}>
<Container className="dashboard">
<Row>
<Col md={4}>
<div className='user-page-top'>
<Card>
<CardBody className="dashboard__card-widget" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<Row>
<Col sd={12} md={12} lg={4}>
{/* Avatar */}
<div>
<Skeleton variant="circle" height={100} width={100} style={{ marginTop: 10, marginBottom: 10 }}/>
</div>
</Col>
<Col sd={12} md={12} lg={8}>
{/* UserInfo */}
<Skeleton variant="rect" height={12} style={{ marginTop: 10 }}/>
<hr></hr>
<Skeleton variant="rect" height={12} style={{ marginTop: 10 }}/>
<Skeleton variant="rect" height={12} style={{ marginTop: 10 }}/>
<Skeleton variant="rect" height={12} style={{ marginTop: 10 }}/>
</Col>
</Row>
</CardBody>
</Card>
</div>
</Col>
<Col md={8}>
<Row>
<Col sd={12} md={4} lg={3}>
{this.renderBalanceData({ title : 'Balance' })}
</Col>
<Col sd={12} md={4} lg={3}>
{this.renderDataTitle({ title : 'TurnOver' })}
</Col>
<Col sd={12} md={4} lg={3}>
{this.renderDataTitle({ title : 'Win Amount' })}
</Col>
<Col sd={12} md={4} lg={3}>
{this.renderDataTitle({ title : 'Profit' })}
</Col>
<Col sd={12} md={4} lg={3}>
{this.renderDataTitle({ title : 'Withdraws' })}
</Col>
<Col sd={12} md={4} lg={3}>
{this.renderDataTitle({ title : 'Deposits' })}
</Col>
<Col sd={12} md={4} lg={3}>
{this.renderDataTitle({ title : 'Affiliate Wallet' })}
</Col>
<Col sd={12} md={4} lg={3}>
{this.renderDataTitle({ title : 'Affiliates' })}
</Col>
</Row>
</Col>
</Row>
<Card>
<CardBody className="dashboard__card-widget" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none", padding: 10 }}>
<Skeleton variant="rect" height={50} style={{ marginTop: 10, marginBottom: 30 }}/>
{ _.times(10, () => <Skeleton variant="rect" height={30} style={{ marginTop: 10, marginBottom: 20 }}/> ) }
</CardBody>
</Card>
</Container>
</Fade>
)
}
}
export default UserPageSkeleton;
<file_sep>/src/containers/Settings/tabs/Components/CountryMap.js
import React from 'react';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import { ComposableMap, Geographies, Geography, ZoomableGroup } from "react-simple-maps"
const geoUrl = "https://raw.githubusercontent.com/zcreativelabs/react-simple-maps/master/topojson-maps/world-110m.json";
class CountryMap extends React.Component{
constructor(props){
super(props);
this.state = {
restrictedCountries: []
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { restrictedCountries } = props;
this.setState({
restrictedCountries: restrictedCountries
})
}
render = () => {
const { setContent, add, lock } = this.props;
const { restrictedCountries } = this.state;
return (
<div style={{ padding: 15}}>
<ComposableMap data-tip="" projectionConfig={{ scale: 200 }}>
<ZoomableGroup>
<Geographies geography={geoUrl}>
{({ geographies }) =>
geographies.map(geo => (
<Geography
key={geo.rsmKey}
geography={geo}
fill={restrictedCountries.includes(geo.properties.ISO_A2) ? "#8c449b" : "#D6D6DA"}
onMouseEnter={() => {
const { NAME } = geo.properties;
setContent(`${NAME}`);
}}
onMouseLeave={() => {
setContent("");
}}
onClick={() => {
if (!lock) {
add(geo.properties.ISO_A2)
}}}
style={{
default: {
outline: "none"
},
hover: {
fill: "#8c449b",
outline: "none"
},
pressed: {
outline: "none"
}
}}
/>
))
}
</Geographies>
</ZoomableGroup>
</ComposableMap>
</div>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
CountryMap.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(CountryMap);
<file_sep>/src/containers/Applications/index.jsx
import React, { Suspense } from 'react';
import { Col, Container, Row, Nav, NavItem, TabContent, TabPane } from 'reactstrap';
import Fade from '@material-ui/core/Fade';
import { connect } from "react-redux";
import { fromCodesToServices } from '../../controllers/services/services';
import TabsContainer from '../../shared/components/tabs/Tabs';
import HostingLink from './components/HostingLink';
import AddOnsContainer from './AddOnPage';
import CurrenciesContainer from './CurrenciesPage/CurrenciesContainer';
import { Bet, Reward, Settings, Rewards, AddOn, Wallet, CasinoWhite, EsportsWhite, SettingsWhite, Chat } from '../../components/Icons';
import styled from 'styled-components';
import { TabContainer, StyledNavLink, CasinoCard, CasinoContainer, Icon, Link, MobileWrapper } from './styles';
import classnames from 'classnames';
import CustomizationContainer from './Customization/index.js';
import GameStorePageContainer from './GameStore/index.js';
import ThirdPartiesContainer from './ThirdParties/index.js';
import GamesContainer from './components/GamesContainer';
import LanguageStorePageContainer from './LanguagesPage/'
const EsportsPage = React.lazy(() => import('./EsportsPage'));
const bitcoin = `${process.env.PUBLIC_URL}/img/landing/bitcoin.png`;
const back_2 = `${process.env.PUBLIC_URL}/img/landing/back-2.png`;
const casino = `${process.env.PUBLIC_URL}/img/landing/casino.png`;
const loading = `${process.env.PUBLIC_URL}/img/loading-betprotocol.gif`;
const EsportsIcon = styled.section`
height: 50px;
width: 50px;
opacity: 0.56;
`
const PlatformIcon = styled.section`
height: 50px;
width: 50px;
opacity: 0.56;
`
class ApplicationsContainer extends React.Component{
constructor(props){
super(props)
this.state = {
activeTab: 'platform'
}
}
isAdded = (AddOn) => {
const { appAddOns } = this.props.profile.App.addOn;
return !!Object.keys(appAddOns).find(k => AddOn.name.toLowerCase().includes(k.toLowerCase()));
}
toggle = (tab) => {
if (this.state.activeTab !== tab) {
this.setState({
activeTab: tab
});
}
}
getTabs = () => {
return {
myGames: {
title : 'My Games',
container : (
<GamesContainer data={{
games : this.props.profile.getApp().getSummaryData('games'),
wallet : this.props.profile.getApp().getSummaryData('wallet'),
}} {...this.props}/>
),
icon : <Bet/>
},
gameStore: {
title : 'Game Store',
container : (
<GameStorePageContainer/>
),
icon : <Reward/>
},
customization: {
title : 'Customization ',
container : (
<CustomizationContainer/>
),
icon : <Settings/>
},
thirdParties: {
title : 'Third-Parties ',
container : (
<ThirdPartiesContainer/>
),
icon : <Rewards/>
},
addOns: {
title : 'Add-Ons ',
container : (
<AddOnsContainer/>
),
icon : <AddOn/>
},
currencies: {
title : 'Currencies ',
container : (
<CurrenciesContainer />
),
icon : <Wallet/>
},
languages: {
title : 'Languages ',
container : (
<LanguageStorePageContainer />
),
icon : <Chat/>
}
}
}
getCasinoTabs = permission => {
const tabs = this.getTabs();
switch (true) {
case permission.super_admin:
return [tabs.myGames, tabs.gameStore];
case permission.customization && permission.financials:
return [tabs.myGames];
case permission.customization:
return [];
case permission.financials:
return [tabs.myGames];
default:
return [];
}
}
getPlatformTabs = permission => {
const tabs = this.getTabs();
switch (true) {
case permission.super_admin:
return [tabs.customization, tabs.thirdParties, tabs.addOns, tabs.currencies, tabs.languages];
case permission.customization && permission.financials:
return [tabs.customization, tabs.addOns, tabs.currencies];
case permission.customization:
return [tabs.customization];
case permission.financials:
return [tabs.addOns, tabs.currencies];
default:
return [];
}
}
render = () => {
const { profile } = this.props;
const services = this.props.profile.getApp().getServices();
const servicesCodes = fromCodesToServices(services);
const permission = profile.User.permission;
return (
<Fade in timeout={{ appear: 200, enter: 200, exit: 200 }}>
<Container className="dashboard">
<Row>
<Col lg={12}>
<div>
<Row>
<Col md={4} style={{ padding: 0 }}>
<Nav pills style={{ justifyContent: "flex-start", marginBottom: 25 }}>
<NavItem style={{ height: 80, marginTop: "20px" }}>
<StyledNavLink
className={classnames({ active: this.state.activeTab === 'platform' })}
onClick={() => {
this.toggle('platform');
}}
>
<span>Platform</span>
<PlatformIcon>
<SettingsWhite isActive={this.state.activeTab === 'platform'}/>
</PlatformIcon>
</StyledNavLink>
</NavItem>
<NavItem style={{ height: 80, marginTop: "20px" }}>
<StyledNavLink
className={classnames({ active: this.state.activeTab === 'casino' })}
onClick={() => {
this.toggle('casino');
}}
>
<span>Casino</span>
<Icon>
<CasinoWhite/>
</Icon>
</StyledNavLink>
</NavItem>
<NavItem style={{ height: 80, marginTop: "20px" }}>
<StyledNavLink
className={classnames({ active: this.state.activeTab === 'esports' })}
onClick={() => {
this.toggle('esports');
}}
>
<span>Esports</span>
<EsportsIcon>
<EsportsWhite isActive={this.state.activeTab === 'esports'}/>
</EsportsIcon>
</StyledNavLink>
</NavItem>
</Nav>
{/* <Row>
{servicesCodes.map( (key) => {
return widgets[key] ? widgets[key]() : null;
})}
</Row> */}
</Col>
<Col md={8} style={{ height: 70 }}>
<MobileWrapper>
<Link>Application link</Link>
</MobileWrapper>
<HostingLink/>
</Col>
</Row>
<TabContainer>
<TabContent activeTab={this.state.activeTab}>
<Suspense fallback={<div class="load">
<div class="load__icon-wrap">
<img src={loading} alt="loading..."/>
</div>
</div>}>
<TabPane tabId={'platform'} style={{ paddingTop: 30 }}>
<TabsContainer
items={
this.getPlatformTabs(permission)
}
/>
</TabPane>
<TabPane tabId={'casino'} style={{ paddingTop: 30 }}>
<TabsContainer
items={
this.getCasinoTabs(permission)
}
/>
</TabPane>
<TabPane tabId={'esports'} style={{ paddingTop: 30 }}>
{ this.state.activeTab === 'esports' && <EsportsPage/> }
</TabPane>
</Suspense>
</TabContent>
</TabContainer>
</div>
</Col>
</Row>
</Container>
</Fade>
)
}
}
const widgets = {
casino : () => {
return (
<CasinoCard>
<CasinoContainer>
<span>Casino</span>
<Icon>
<CasinoWhite/>
</Icon>
</CasinoContainer>
</CasinoCard>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(ApplicationsContainer);
<file_sep>/src/containers/Modals/index.js
import Modal2FA from './Modal2FA';
import ModalError from './ModalError';
import ModalUserAffiliateCustom from './ModalUserAffiliateCustom';
import AbstractModal from './AbstractModal';
import ModalAddCurrencyWallet from './ModalAddCurrencyWallet';
export {
Modal2FA,
AbstractModal,
ModalUserAffiliateCustom,
ModalError,
ModalAddCurrencyWallet
}<file_sep>/src/containers/Applications/AddOnPage/AddOnStore/AddOn/index.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col, Row, Button } from 'reactstrap';
import { AddIcon } from 'mdi-react';
class AddOnStoreContainer extends PureComponent {
constructor() {
super();
this.state = {
isLoading: false
};
}
handleAddAddOn = async () => {
const { addAddOn, addOn } = this.props;
this.setState({ isLoading: true })
await addAddOn(addOn.endpoint);
this.setState({ isLoading: false })
}
render() {
const { addOn, isAdded } = this.props;
const { isLoading } = this.state;
if(!addOn){return null}
const { name, description, image_url } = addOn;
return (
<CardBody className="dashboard__card-widget" style={{ minHeight: 187, maxWidth: 307, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<Row>
<Col lg={4} >
<img className='application__game__image'
style={{display: 'block', width: '60px'}}
src={image_url}/>
</Col>
<Col lg={8} >
<div className="dashboard__visitors-chart text-left">
<p className="dashboard__visitors-chart-title text-left" style={{fontSize : 20}}> {name} </p>
<p className="text-left secondary-text"> {description} </p>
</div>
</Col>
</Row>
<Button disabled={isLoading || isAdded} style={{margin : 0, marginTop : 10}} className="icon" onClick={this.handleAddAddOn} >
{
isLoading ?
"Adding"
: isAdded ?
"Added"
:
<p><AddIcon className="deposit-icon"/> Add </p>
}
</Button>
</CardBody>
);
}
}
export default AddOnStoreContainer;
<file_sep>/src/shared/components/CurrencyContainer/styles.js
import styled from 'styled-components';
import { ButtonBase } from '@material-ui/core';
export const DialogHeader = styled.section`
width: 100%;
padding: 10px 20px;
margin-bottom: 15px;
display: flex;
justify-content: flex-end;
`;
export const Title = styled.h1`
margin-top: 0px;
font-family: Poppins;
font-size: 18px;
`;
export const CloseButton = styled(ButtonBase)``;<file_sep>/src/shared/components/UserContainer/styles.js
import styled from 'styled-components';
import { ButtonBase } from '@material-ui/core';
export const DialogHeader = styled.section`
width: 100%;
padding: 10px 20px;
display: flex;
justify-content: flex-end;
`;
export const CloseButton = styled(ButtonBase)``;<file_sep>/src/containers/Account/ResetPassword/components/ResetPasswordForm.jsx
import React, { PureComponent } from 'react';
import { reduxForm } from 'redux-form';
import {CheckboxMultipleBlankCircleIcon, KeyVariantIcon } from 'mdi-react';
import PropTypes from 'prop-types';
import Account from '../../../../controllers/Account';
import TextField from '@material-ui/core/TextField';
import TextInput from '../../../../shared/components/TextInput';
import _ from 'lodash';
import { FormGroup } from 'reactstrap';
import { EmailInput, InputLabel } from '../styles';
const loading = `${process.env.PUBLIC_URL}/img/loading.gif`;
const queryString = require('query-string');
const renderTextField = ({
input, label, meta: { touched, error }, children, select, type
}) => (
<TextField
className="material-form__field"
label={label}
error={touched && error}
value={input.value}
children={children}
type={type}
select={select}
onChange={(e) => {
e.preventDefault();
input.onChange(e);
}}
/>
);
renderTextField.propTypes = {
input: PropTypes.shape().isRequired,
label: PropTypes.string.isRequired,
meta: PropTypes.shape({
touched: PropTypes.bool,
error: PropTypes.string,
}),
select: PropTypes.bool,
children: PropTypes.arrayOf(PropTypes.element),
};
renderTextField.defaultProps = {
meta: null,
select: false,
children: [],
};
class ResetPasswordForm extends PureComponent {
static propTypes = {
handleSubmit: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = {
isLoading : false,
sent: false
};
}
componentDidMount(){
const parsed = queryString.parse(window.location.search);
if (!_.isEmpty(parsed)) {
this.setState({
adminId: parsed.adminId,
token: parsed.token
})
}
}
onChangeUsername = value => {
if (value) {
this.setState({
username_or_email: value
})
} else {
this.setState({
username_or_email: null
})
}
}
onChangePassword = value => {
if (value) {
this.setState({
password: value
})
} else {
this.setState({
password: null
})
}
}
onChangeConfirmPassword = value => {
if (value) {
this.setState({
confirmPassword: value
})
} else {
this.setState({
confirmPassword: null
})
}
}
sendRecoveryEmail = async () => {
try{
this.setState({...this.state, isLoading: true});
let account = new Account(this.state);
await account.resetAdminPassword(this.state.username_or_email);
this.setState({...this.state, isLoading: false, sent: true });
}catch(err){
this.props.showNotification(err.message);
}
}
confirmNewAdminPassword = async () => {
const { token, adminId, password } = this.state;
try{
this.setState({...this.state, isLoading: true});
let account = new Account(this.state);
const res = await account.confirmResetAdminPassword({ token: token, admin_id: adminId, password: <PASSWORD> });
this.setState({...this.state, isLoading: false });
if (res.data && res.data.status === 200) {
this.props.history.push("/");
}
}catch(err){
this.props.showNotification(err.message);
}
}
render() {
const { handleSubmit } = this.props;
const { username_or_email, sent, adminId, token, password, confirmPassword } = this.state;
return (
!_.isEmpty(adminId) && !_.isEmpty(token) ? (
<form className="form" onSubmit={handleSubmit}>
<div className="form__form-group">
<FormGroup>
<InputLabel for="password">Password</InputLabel>
<EmailInput
label="Password"
name="password"
type="password"
// defaultValue={this.state.username}
onChange={(e) => this.onChangePassword(e.target.value)}
/>
</FormGroup>
<FormGroup>
<InputLabel for="confirmPassword"> Confirm Password</InputLabel>
<EmailInput
label="Confirm Password"
name="confirmPassword"
type="password"
// defaultValue={this.state.username}
onChange={(e) => this.onChangeConfirmPassword(e.target.value)}
/>
</FormGroup>
</div>
<div className="account__btns">
<button disabled={ password !== confirmPassword || _.isEmpty(password) || this.state.isLoading } onClick={ () => this.confirmNewAdminPassword() }className="btn btn-primary account__btn" to="/"> {
!this.state.isLoading ?
'Confirm change'
:
<img src={loading} className={'loading_gif'}></img>
}
</button>
</div>
</form>
) : (
<form className="form" onSubmit={handleSubmit}>
<div className="form__form-group">
{ !sent ? (
<FormGroup>
<InputLabel for="username_or_email">Username or E-mail</InputLabel>
<EmailInput
label="Username or E-mail"
name="username_or_email"
type="text"
// defaultValue={this.state.username}
onChange={(e) => this.onChangeUsername(e.target.value)}
/>
</FormGroup>
) : <h5 className="account__title">Sent, please check your inbox</h5> }
</div>
<div className="account__btns">
<button disabled={ _.isEmpty(username_or_email) || this.state.isLoading } onClick={ () => this.sendRecoveryEmail() }className="btn btn-primary account__btn"> {
!this.state.isLoading ?
!sent ? (
'Send e-mail'
) : 'Send again'
:
<img src={loading} className={'loading_gif'}></img>
}
</button>
</div>
</form> )
);
}
}
export default reduxForm({
form: 'reset_password_form', // a unique identifier for this form
})(ResetPasswordForm);
<file_sep>/src/containers/Wallet/components/paths/CurrencyInfo.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col, Row } from 'reactstrap';
import EditLock from '../../../Shared/EditLock';
import TextInput from '../../../../shared/components/TextInput';
import BooleanInput from './components/utils/BooleanInput';
const deposit = `${process.env.PUBLIC_URL}/img/dashboard/deposit.png`;
const withdrawal = `${process.env.PUBLIC_URL}/img/dashboard/withdrawal.png`;
class CurrencyInfo extends PureComponent {
constructor() {
super();
this.state = {
depositFee: 0,
withdrawFee: 0,
newDepositFee: null,
newWithdrawFee: null,
lock: true
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
unlock = () => {
this.setState({...this.state, lock: false })
}
lock = () => {
this.setState({...this.state, lock: true })
}
onChangeIsTxFee = () => {
this.setState({...this.state, isTxFee: !this.state.isTxFee })
}
onChangeDepositFee = (value) => {
this.setState({...this.state, newDepositFee: value ? parseFloat(value) : 0 })
}
onChangeWithdrawFee = (value) => {
this.setState({...this.state, newWithdrawFee: value ? parseFloat(value) : 0 })
}
projectData = (props) => {
const { profile, data } = props;
const app = profile.App;
const txFee = app.params.addOn.txFee;
this.setState({
currency: data._id,
isTxFee: txFee.isTxFee,
depositFee: txFee.deposit_fee.find(fee => fee.currency === data._id).amount,
withdrawFee: txFee.withdraw_fee.find(fee => fee.currency === data._id).amount
})
}
confirmChanges = async () => {
const { profile } = this.props;
const { currency, isTxFee, depositFee, newDepositFee, withdrawFee, newWithdrawFee } = this.state;
this.setState({...this.state, loading: true })
const txFeeParams = {
isTxFee: isTxFee,
deposit_fee: newDepositFee !== null ? newDepositFee : depositFee,
withdraw_fee: newWithdrawFee !== null ? newWithdrawFee : withdrawFee
}
await profile.getApp().editTxFee({ currency: currency, txFeeParams })
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({...this.state, loading: false })
this.lock()
}
render() {
const { data } = this.props;
const { lock, depositFee, withdrawFee, isTxFee } = this.state;
if(!data){return null}
return (
<Col md={12} xl={12} lg={12} xs={12}>
<Card className='game-container'>
<CardBody className="dashboard__card-widget" style={{width: '307px', paddingBottom: 10, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none"}}>
<EditLock
unlockField={this.unlock}
lockField={this.lock}
confirmChanges={this.confirmChanges}
isLoading={this.state.loading}
locked={lock}>
<h4 style={{ margin: 0 }} >Tx Fee</h4>
<BooleanInput
checked={isTxFee === true}
onChange={this.onChangeIsTxFee}
color="primary"
name="isTxFee"
disabled={lock}
inputProps={{ 'aria-label': 'primary checkbox' }}
/>
<hr/>
<Row>
<Col lg={4} >
<img className='application__game__image'
style={{display: 'block', width: '60px'}}
src={deposit}/>
</Col>
<Col lg={8} >
<h3 style={{ fontSize: 17, marginLeft: 0 }} className={"dashboard__total-stat"}>Deposit Fee</h3>
<div style={{ display: "flex"}}>
<h3 style={{marginTop: 20, marginRight: 0}} className={"dashboard__total-stat"}>{depositFee.toFixed(6)}</h3>
<h3 style={{ fontSize: 17, marginLeft: 0 }} className={"dashboard__total-stat"}>{data.ticker}</h3>
</div>
<TextInput
name="depositFee"
label={<h6 style={{ fontSize: 11 }}>New Deposit Fee</h6>}
type="text"
disabled={lock}
changeContent={(type, value) => this.onChangeDepositFee(value)}
/>
</Col>
<Col lg={4} style={{ marginTop: 20 }}>
<img className='application__game__image'
style={{display: 'block', width: '60px'}}
src={withdrawal}/>
</Col>
<Col lg={8} style={{ marginTop: 20 }}>
<h3 style={{ fontSize: 17, marginLeft: 0 }} className={"dashboard__total-stat"}>Withdraw Fee</h3>
<div style={{ display: "flex"}}>
<h3 style={{marginTop: 20, marginRight: 0}} className={"dashboard__total-stat"}>{withdrawFee.toFixed(6)}</h3>
<h3 style={{ fontSize: 17, marginLeft: 0 }} className={"dashboard__total-stat"}>{data.ticker}</h3>
</div>
<TextInput
name="withdrawFee"
label={<h6 style={{ fontSize: 11 }}>New Withdraw Fee</h6>}
type="text"
disabled={lock}
changeContent={(type, value) => this.onChangeWithdrawFee(value)}
/>
</Col>
</Row>
</EditLock>
</CardBody>
</Card>
</Col>
);
}
}
export default CurrencyInfo;
<file_sep>/src/containers/Layout/topbar_with_navigation/TopbarSidebarButton.jsx
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
const logo = `${process.env.PUBLIC_URL}/img/logo.png`;
class TopbarSidebarButton extends PureComponent {
static propTypes = {
changeMobileSidebarVisibility: PropTypes.func.isRequired,
};
render() {
const { changeMobileSidebarVisibility } = this.props;
return (
<div>
<button disabled={true} className="topbar__button topbar__button--mobile" onClick={changeMobileSidebarVisibility}>
<img src={logo} alt="" className="topbar__button-icon" />
</button>
</div>
);
}
}
export default TopbarSidebarButton;
<file_sep>/src/components/index.js
import EditableTable from "./EditableTable";
import InfoNumericCard from "./InfoNumericCard";
export {
EditableTable,
InfoNumericCard
}
<file_sep>/src/containers/Settings/tabs/Components/EditLock.js
import React from 'react';
import { Button } from 'reactstrap';
import { ArrowExpandRightIcon, LockIcon } from 'mdi-react';
const EditLock = (props) => {
return(
<div style={{ width: "100%"}} className={`${props.locked ? 'locker-container' : null}`}>
<div style={{ width: "100%", display: "flex"}}>
{props.children}
</div>
<div style={{marginTop : 20}}>
{props.locked ?
<Button onClick={() => props.unlockField({field : props.type})} className="icon" outline style={{ backgroundColor: "white" }}>
<p><LockIcon className="deposit-icon"/> Unlock</p>
</Button>
:
<div>
<Button onClick={() => props.lockField({field : props.type})} className="icon" outline style={{ backgroundColor: "white" }}>
<p><LockIcon className="deposit-icon"/> Lock </p>
</Button>
<Button disabled={props.isLoading} onClick={() => props.confirmChanges({field : props.type})} className="icon" outline style={{ backgroundColor: "white" }}>
<p><ArrowExpandRightIcon className="deposit-icon"/>
{props.isLoading ? 'Updating..' : 'Confirm'}
</p>
</Button>
</div>
}
</div>
</div>
)
}
export default EditLock;<file_sep>/src/containers/Applications/EsportsPage/components/MatchPage/styles.js
import styled from 'styled-components';
import { Button } from '@material-ui/core';
export const MatchContainer = styled.div`
display: flex;
flex-direction: column;
height: 100vh;
width: 100%;
`;
export const MatchSummary = styled.section`
background-color: #fafcff;
border: solid 1px rgba(164, 161, 161, 0.35);
width: 100%;
min-width: 450px;
display: grid;
grid-template-areas:
'serie'
'score'
'info';
grid-template-columns: 100%;
grid-template-rows: 58px auto 49px;
`;
export const SerieSummary = styled.section`
grid-area: serie;
display: flex;
justify-content: flex-start;
align-items: center;
display: grid;
grid-template-areas:
'matchStatus'
'serieInfo';
grid-template-columns: 100%;
grid-template-rows: 26px auto;
`;
export const MatchStatus = styled.section`
grid-area: matchStatus;
display: flex;
justify-content: center;
align-self: flex-start;
border-top: ${props => `6px solid ${props.color}`};
`;
export const SerieInfo = styled.section`
grid-area: serieInfo;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0px 20px;
span {
padding-top: 10px;
color: rgb(95, 110, 133);
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.05em;
}
`;
export const MatchIcon = styled.section`
height: 20px;
width: 220px;
margin-top: -6px;
`;
export const VideoGameIcon = styled.section`
margin: 0px 8px;
height: 14px;
width: 14px;
`;
export const Score = styled.section`
width: 75%;
min-height: 100px;
grid-area: score;
padding: 10px 20px;
display: grid;
grid-template-areas:
'teamOne date teamTwo';
grid-template-columns: 40% 20% 40%;
grid-template-rows: auto;
align-self: center;
justify-self: center;
`;
export const TeamOne = styled.section`
grid-area: teamOne;
display: flex;
align-items: center;
justify-content: flex-end;
img {
height: auto;
width: 35px;
}
span {
margin: 0px 7px;
font-family: Poppins;
font-size: 13px;
&:last-child {
margin: 0px;
}
}
`;
export const TeamTwo = styled.section`
grid-area: teamTwo;
display: flex;
align-items: center;
justify-content: flex-start;
img {
height: auto;
width: 35px;
}
span {
margin: 0px 7px;
font-family: Poppins;
font-size: 13px;
&:first-child {
margin: 0px;
}
}
`;
export const DateInfo = styled.section`
grid-area: date;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
`;
export const Time = styled.span`
font-family: Poppins;
margin-bottom: 3px;
font-size: 17px;
font-weight: 800;
color: rgb(95, 110, 133);
padding: 0px 8px;
`;
export const Date = styled.span`
font-family: Poppins;
font-size: 13px;
font-weight: 300;
color: rgb(95, 110, 133);
`;
export const InfoContainer = styled.section`
grid-area: info;
border-top: solid 1px rgba(164, 161, 161, 0.35);
display: flex;
justify-content: flex-end;
align-items: center;
padding: 5px 20px;
min-height: 49px;
`;
export const BookButton = styled(Button)`
text-transform: none !important;
background-color: #39f !important;
color: white !important;
box-shadow: none !important;
height: 23px;
position: absolute;
span {
font-family: Poppins;
font-size: 11px;
font-weight: 300;
}
`;
export const RemoveBookButton = styled(Button)`
text-transform: none !important;
background-color: #e6536e !important;
color: white !important;
box-shadow: none !important;
height: 23px;
position: absolute;
span {
font-family: Poppins;
font-size: 11px;
font-weight: 300;
}
`;
export const Result = styled.section`
grid-area: date;
display: flex;
align-items: center;
justify-content: space-evenly;
padding: 0px 10px;
span {
font-family: Poppins;
font-size: 14px;
color: #828282;
}
`;
export const ResultValue = styled.span`
margin: 0px 8px;
font-family: Poppins !important;
font-size: 18px !important;
font-weight: 500;
color: ${props => props.color} !important;
`;
export const Draw = styled.div`
display: flex;
justify-content: center;
align-items: center;
width: 34px;
height: 19px;
border-radius: 3px;
background-color: #DFE1EC;
span {
font-family: Poppins !important;
font-size: 13px;
color: #333333 !important;
}
`;
export const TabsContainer = styled.div`
margin: 10;
padding: 10;
`;<file_sep>/src/containers/Applications/Customization/components/styles.js
import styled from 'styled-components';
import { Input } from 'reactstrap';
export const styles = {
root: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'start',
overflow: 'hidden',
},
gridList: {
flexWrap: 'nowrap',
// Promote the list into his own layer on Chrome. This cost memory but helps keeping high FPS.
transform: 'translateZ(0)',
}
};
export const TextField = styled(Input)`
margin: 12px 0px;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: white;
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
`;
export const Label = styled.span`
font-family: Poppins;
font-size: 18px;
font-weight: 500;
line-height: 35px;
text-align: left;
color: #463e3e;
`;
export const InputLabel = styled.h4`
font-size: 16px;
`;
export const EsportsNotEnable = styled.div`
display: flex;
justify-content: flex-start;
align-items: center;
> img {
height: 70px;
width: 70px;
margin: 0px 10px;
}
> span {
font-size: 18px;
font-weight: 500;
color: #814c94;
}
`;
<file_sep>/src/containers/Dashboards/Default/components/RevenueChart.jsx
import React from 'react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, Label } from 'recharts';
import { translate } from 'react-i18next';
import Panel from '../../../../shared/components/Panel';
import DashboardMapperSingleton from '../../../../services/mappers/Dashboard';
import Skeleton from '@material-ui/lab/Skeleton';
const defaultProps = {
chartData : [
{
name : "N/A",
a : 0,
b : 0,
c : 0,
timestamp : new Date()
}
],
ticker : 'N/A',
timeline : 'Weekly'
}
class RevenueChart extends React.Component{
constructor(props){
super(props)
this.state = { ...defaultProps};
this.projectData(props);
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
let { data , periodicity, currency } = props;
this.setState({...this.state,
chartData : data.revenue.data ? DashboardMapperSingleton.toRevenueChart(data.revenue.data) : defaultProps.chartData,
ticker : currency.ticker ? currency.ticker : defaultProps.timeline,
timeline : periodicity ? periodicity : defaultProps.timeline
})
}
render(){
const { isLoading } = this.props;
return(
<Panel naked={true} md={12} lg={12} xl={12} title={`${this.state.timeline} Summary`}>
{isLoading ? (
<Skeleton variant="rect" height={250}/>
) : (
<ResponsiveContainer height={250} className="dashboard__area">
<AreaChart data={this.state.chartData} margin={{ top: 20, left: 5, bottom: 20 }} >
<XAxis dataKey="name" tickLine={false} />
<YAxis unit={` ${this.state.ticker}`} tickLine={false} >
</YAxis>
<Tooltip />
<Legend />
<CartesianGrid />
<Area name="Profit" type="monotone" dataKey="c" fill="#70bbfd" stroke="#70bbfd" fillOpacity={0.4} />
</AreaChart>
</ResponsiveContainer>)}
</Panel>
)
}
}
export default translate('common')(RevenueChart);
<file_sep>/src/containers/Applications/EsportsPage/components/MatchList/EditEdge/index.js
import React from 'react';
import { connect } from 'react-redux';
import { Slider, InputNumber, Row, Col, Button } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import { Container, Header, Actions, SaveButton } from './styles';
import { ButtonBase } from '@material-ui/core';
const loading = `${process.env.PUBLIC_URL}/img/loading.gif`;
class EditEdge extends React.Component {
constructor(props) {
super(props);
this.state = {
edge: 0,
newEdge: null,
isLoading: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { profile } = props;
const { App } = profile;
const edge = App.params.esports_edge;
this.setState({
edge: edge ? edge : 0,
newEdge: edge
})
}
onChangeEdge = value => {
this.setState({ newEdge: value });
};
resetNewEdge = () => {
const { edge } = this.state;
this.setState({ newEdge: edge });
}
updateVideogamesEdge = async () => {
const { newEdge } = this.state;
const { profile } = this.props;
const { App } = profile;
this.setState({ isLoading: true });
await App.editVideogamesEdge({ esports_edge: newEdge });
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({ isLoading: false });
}
render() {
const { edge, newEdge, isLoading } = this.state;
const { profile } = this.props;
const app = profile.getApp();
const hasEsports = app.hasEsportsPermission();
return (
<Container>
<Header>
<span>Edge</span>
</Header>
<Actions>
<Row style={{ width: "100%" }}>
<Col>
<Slider
disabled={!hasEsports}
style={{ width: 100 }}
defaultValue={edge}
min={0}
max={20}
onChange={this.onChangeEdge}
value={newEdge}
step={0.1}
/>
</Col>
<Col>
<InputNumber
disabled={!hasEsports}
defaultValue={edge}
min={0}
max={20}
style={{ margin: '0 16px', marginRight: 3 }}
step={0.1}
value={newEdge}
formatter={value => `${value}%`}
parser={value => value.replace('%', '')}
onChange={this.onChangeEdge}
/>
{ edge !== newEdge && (
<ButtonBase style={{ margin: "0px 5px" }} disabled={isLoading || !hasEsports} onClick={this.resetNewEdge}>
<CloseOutlined/>
</ButtonBase>) }
</Col>
<Col style={{ display: "flex", justifyContent: "center", alignItems: "center", padding: "5px 8px" }}>
{ edge !== newEdge && (
<div style={{ display: "flex", justifyContent: "flex-start", alignItems: "center" }}>
<SaveButton variant="contained" size="small" disabled={isLoading} onClick={this.updateVideogamesEdge}>
{ isLoading ? <img src={loading} alt="Loading..." className={'loading_gif'}/> : "Update" }
</SaveButton>
</div>
)}
</Col>
</Row>
</Actions>
</Container>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(EditEdge);
<file_sep>/src/containers/Applications/Customization/components/Tabs/AddTab.js
import React from 'react';
import { FormGroup, Col } from 'reactstrap';
import { TabCard, TabCardContent, InputField, TabImage, InputLabel, AddTabButton } from './styles';
import _ from 'lodash';
import Dropzone from 'react-dropzone'
import { PlusIcon } from 'mdi-react';
const upload = `${process.env.PUBLIC_URL}/img/dashboard/upload.png`;
const trash = `${process.env.PUBLIC_URL}/img/dashboard/clear.png`;
const image2base64 = require('image-to-base64');
const dropzoneStyle = {
width: "100%",
height: "100%",
backgroundColor: "white"
};
class AddTab extends React.Component {
constructor(props){
super(props);
this.state = {
newName: "",
newLink: "",
newIcon: ""
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { tabs } = props;
if (!_.isEmpty(tabs)) {
this.setState({
tabs: tabs
})
}
}
renderImage = (src) => {
if(!src.includes("https")){
src = "data:image;base64," + src;
}
return src;
}
onChangeNewName = ({ value }) => {
if (value) {
this.setState({
newName: value
})
} else {
this.setState({
newName: ""
})
}
}
onChangeNewLink = ({ value }) => {
if (value) {
this.setState({
newLink: value
})
} else {
this.setState({
newLink: ""
})
}
}
onAddedNewFile = async ({ files }) => {
const file = files[0];
let blob = await image2base64(file.preview) // you can also to use url
this.setState({
newIcon: blob
})
}
renderAddNewImage = () => {
const { locked } = this.props;
return(
<Dropzone disabled={locked} style={dropzoneStyle} onDrop={(files) => this.onAddedNewFile({ files: files })} ref={(el) => (this.dropzoneRef = el)}>
<img src={upload} className='image-info' style={{ height: 20, width: 20 }}/>
<p className='text-center'> Drop the icon here</p>
</Dropzone>
)
}
removeNewIcon = () => {
this.setState({
newIcon: ""
})
}
addNewTab = () => {
const { newName, newLink, newIcon } = this.state;
const { setTabs, tabs } = this.props;
const newTabObj = { name: newName, link_url: newLink, icon: newIcon, _id: Math.random().toString(36).substr(2, 9) }
const newTabs = tabs ? [...tabs, newTabObj] : [newTabObj];
this.setState({
newName: "",
newLink: "",
newIcon: ""
})
setTabs({
newTabs: newTabs,
})
}
render() {
const { newName, newLink, newIcon } = this.state;
const { locked } = this.props;
const hasEmptyValues = _.isEmpty(newName) || _.isEmpty(newLink);
return (
<>
<Col md={3} style={{ minWidth: 178, maxWidth: 230, padding: 0, margin: "10px 15px" }}>
<TabCard>
<TabCardContent>
{ newIcon ?
<>
<div style={{ display: "flex", justifyContent: "flex-end", width: "100%", marginTop: -10, marginBottom: -30 }}>
<button
disabled={locked}
onClick={() => this.removeNewIcon()}
style={{ position: "inherit", right: 20, top: 6 }}
className='carousel-trash button-hover'>
<img src={trash} style={{width : 15, height : 15}}/>
</button>
</div>
<img className='application__game__image' style={{ display: 'block', width: 100, height: 100 }} src={this.renderImage(newIcon)}/>
</>
:
<TabImage>
{ this.renderAddNewImage() }
</TabImage> }
<FormGroup>
<InputLabel for="name">Title</InputLabel>
<InputField
label="Name"
name="name"
type="text"
value={newName}
disabled={locked}
// defaultValue={name}
onChange={(e) => this.onChangeNewName({ value: e.target.value })}
/>
</FormGroup>
<FormGroup>
<InputLabel for="link">Link</InputLabel>
<InputField
label="Link"
name="link"
type="text"
value={newLink}
disabled={locked}
// defaultValue={href}
onChange={(e) => this.onChangeNewLink({ value: e.target.value })}
/>
</FormGroup>
<AddTabButton disabled={locked || hasEmptyValues} onClick={() => this.addNewTab()}>
<PlusIcon/> Add tab
</AddTabButton>
</TabCardContent>
</TabCard>
</Col>
</>
)
}
}
export default AddTab;
<file_sep>/src/containers/Wallet/components/LiquidityWalletContainer/styles.js
import styled from 'styled-components';
import { NavLink } from 'reactstrap';
export const Container = styled.section`
height: 100%;
width: 100%;
margin: 0;
padding: 10px;
`;
export const Header = styled.section`
display: flex;
flex-direction: column;
margin-bottom: 29px;
h3 {
margin: 0;
font-family: Poppins;
font-size: 18px;
font-weight: 500;
color: #463e3e;
}
p {
margin: 0;
font-size: 14px;
line-height: 27px;
color: #a4a1a1;
}
`;
export const Content = styled.section`
display: flex;
height: 100%;
width: 100%;
`;
export const CurrenciesTabContainer = styled.section`
margin-left: 15px;
height: 100%;
width: 100%;
min-width: 176px;
`;
export const TabsContainer = styled.section`
height: 100%;
width: 100%;
`;
export const StyledNavLink = styled(NavLink)`
cursor: pointer;
filter: grayscale(1);
opacity: 0.7;
padding: 0;
&.active {
padding: 0;
opacity: 1;
filter: grayscale(0);
border-left: none;
background-color: transparent !important;
}
`;
export const WalletContainer = styled.section`
display: flex;
height: 100%;
width: 100%;
`;
export const WalletDetails = styled.section`
display: flex;
flex-direction: column;
height: 100%;
padding-left: 15px;
pointer-events: all;
h3 {
margin-bottom: 0px;
font-family: Poppins;
font-size: 20px;
font-weight: 500;
color: #814c94;
}
span {
opacity: 0.86;
font-family: Poppins;
font-size: 16px !important;
line-height: 27px;
text-align: left;
color: #828282 !important;
}
`;
export const Paragraph = styled.p`
margin: 0;
font-size: 14px;
line-height: 27px;
color: #a4a1a1;
`;<file_sep>/src/containers/Settings/tabs/EditAdminButton.js
import React from 'react'
import { Button, Dialog, DialogTitle, Divider, DialogActions, DialogContent, FormControlLabel, Checkbox, FormControl, Select, MenuItem } from '@material-ui/core';
import { FormGroup } from 'reactstrap';
class EditAdminButton extends React.Component {
constructor(props) {
super(props);
this.state = {
userType: '',
isToggle: false,
userPermissions: {}
};
}
componentDidMount() {
this.projectData(this.props);
}
// componentWillReceiveProps() {
// this.projectData(this.props);
// }
handleOpen = () => {
this.setState(state => ({
isToggle: true
}));
}
handleClose = () => {
this.setState(state => ({
isToggle: false
}));
}
handleSelected = (event) => {
event.persist();
this.handleChangeUserType(event.target.value);
}
handleChangeUserType = (userType) => {
const { user } = this.props;
if (userType === 'Super Admin') {
this.handleSubmit(user.id,
{super_admin: true,
financials: true,
user_withdraw: true,
withdraw: true,
customization: true});
} else {
this.handleOpen();
}
}
handleSubmit = async (id, params) => {
const { profile } = this.props;
profile.editAdminType({adminToModify: id, permission: params});
this.setState(state => ({
userType: params.super_admin ? 'Super Admin' : 'Collaborator'
}));
this.handleClose();
}
handleChange = (event) => {
event.persist();
this.setState(prevState => ({ userPermissions: {
...prevState.userPermissions,
[event.target.name]: event.target.checked }}));
}
projectData = (props) => {
const { user } = props;
if (user && user.permission) {
this.setState(state => ({
userPermissions: user.permission,
userType: user.permission.super_admin ? 'Super Admin' : 'Collaborator'
}))
}
}
render() {
const { user } = this.props;
const { userType } = this.state;
const { customization, withdraw, user_withdraw, financials } = this.state.userPermissions;
return (
<div>
<Select
labelId="select-user-type-label"
id="select-user-type"
value={userType}
onChange={(e) => this.handleSelected(e)}
>
<MenuItem value={'Super Admin'}>Super Admin</MenuItem>
<MenuItem value={'Collaborator'}>Collaborator</MenuItem>
</Select>
<Dialog
open={this.state.isToggle}
onClose={this.handleClose}
>
<DialogTitle> {`Edit admin permissions for ${user.name}`}</DialogTitle>
<Divider/>
<DialogContent>
<FormControl component="fieldset">
<FormGroup>
<FormControlLabel
control={<Checkbox checked={customization} onChange={(e) => this.handleChange(e)} name="customization" />}
label="Customization"
/>
<FormControlLabel
control={<Checkbox checked={withdraw} onChange={(e) => this.handleChange(e)} name="withdraw" />}
label="Withdraw"
/>
<FormControlLabel
control={<Checkbox checked={user_withdraw} onChange={(e) => this.handleChange(e)} name="user_withdraw" />}
label="User withdraw"
/>
<FormControlLabel
control={<Checkbox checked={financials} onChange={(e) => this.handleChange(e)} name="financials" />}
label="Financials"
/>
</FormGroup>
</FormControl>
</DialogContent>
<DialogActions>
<Button color="primary" onClick={() => this.handleSubmit(user.id, {super_admin: false, customization, user_withdraw, withdraw, financials})}>
Save changes
</Button>
</DialogActions>
</Dialog>
</div>
)
}
}
export default EditAdminButton;<file_sep>/src/utils/export2JSON.js
export const export2JSON = (data, filename) => {
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2)], {
type: "text/plain"
}));
a.setAttribute("download", `${filename}.json`);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}<file_sep>/src/redux/actions/modal.js
export const SET_MODAL = 'SET_MODAL';
export const CLOSE_MODAL = 'CLOSE_MODAL';
export const MODAL_TYPES = {
USER_AFFILIATE_EDIT : 'USER_AFFILIATE_EDIT'
}
export function setModal(data) {
return {
type: SET_MODAL,
action : data
};
}
export function closeModal(data) {
return {
type: CLOSE_MODAL,
action : data
};
}
<file_sep>/src/containers/Settings/tabs/Components/LockAdmin.js
import React from 'react';
import { Button } from 'reactstrap';
import { ArrowExpandRightIcon, LockIcon } from 'mdi-react';
const LockAdmin = (props) => {
return(
<div className={`${props.locked ? 'locker-container' : null}`}>
{props.children}
<div style={{ height: "35px", marginTop: 10 }}>
{props.locked ?
<Button size="sm" style={{ margin: 0, backgroundColor: "white" }} onClick={() => props.unlockField({field : props.type})} className="icon" outline>
<p><LockIcon className="deposit-icon"/> Unlock</p>
</Button>
:
<div>
<Button size="sm" style={{ margin: 0, marginRight: 15, backgroundColor: "white" }} onClick={() => props.lockField({field : props.type})} className="icon" outline>
<p><LockIcon className="deposit-icon"/> Lock </p>
</Button>
<Button size="sm" style={{ margin: 0, backgroundColor: "white" }} disabled={props.isLoading} onClick={() => props.confirmChanges({field : props.type})} className="icon" outline>
{ props.add ? (
<p style={{ color: props.isLoading ? "black" : "unset" }}><ArrowExpandRightIcon style={{ color: props.isLoading ? "black" : "unset" }} className="deposit-icon"/>
{props.isLoading ? 'Sending..' : 'Send'}
</p>
) : (
<p style={{ color: props.isLoading ? "black" : "unset" }}><ArrowExpandRightIcon style={{ color: props.isLoading ? "black" : "unset" }} className="deposit-icon"/>
{props.isLoading ? 'Updating..' : 'Confirm'}
</p>
)}
</Button>
</div>
}
</div>
</div>
)
}
export default LockAdmin;<file_sep>/src/redux/actions/periodicityAction.js
export const SET_DATA_PERIODICITY = 'SET_DATA_PERIODICITY';
export function setDataPeriodicity(data) {
return {
type: SET_DATA_PERIODICITY,
action : data
};
}
<file_sep>/src/containers/Applications/Customization/components/SubSections/AddSection/index.js
import React, { Component } from 'react'
import _ from 'lodash';
import '../styles.css';
import { Container, SectionGrid, Title, Text, Image, DropzoneImage, BackgroundItems, UploadButton, RemoveButton, BackgroundImage, DialogHeader, ConfirmButton } from './styles';
import { FormGroup } from 'reactstrap';
import Dropzone from 'react-dropzone'
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import { createMuiTheme, MuiThemeProvider, withStyles, Dialog, DialogContent, ButtonBase, } from '@material-ui/core';
import ColorPicker from '../../../../../../shared/components/color_picker_input/ColorPicker';
import { InputField, InputLabel } from '../styles';
import { UploadIcon, TrashCanOutlineIcon, CloseIcon, ContentSaveIcon } from 'mdi-react';
const upload = `${process.env.PUBLIC_URL}/img/dashboard/upload.png`;
const trash = `${process.env.PUBLIC_URL}/img/dashboard/clear.png`;
const image2base64 = require('image-to-base64');
const dropzoneStyle = {
width: "100%",
height: "100%",
backgroundColor: "white",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
};
const theme = createMuiTheme({
palette: {
primary: {
main: '#894798'
}
},
});
const StyledFormControlLabel = withStyles({
label: {
fontFamily: "Poppins",
fontSize: "15px"
},
})(FormControlLabel);
const positionsEnum = Object.freeze({
0: "RightImage",
1: "LeftImage",
2: "BottomImage",
3: "TopImage"
});
class AddSection extends Component {
constructor(props){
super(props);
this.state = {
position: 0,
location: 0,
newTitle: "",
newText: "",
newImage: "",
newBackgroundColor: "",
newBackgroundImage: "",
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { subSections } = props;
this.setState({ subSections: !_.isEmpty(subSections) ? subSections : [] })
}
addNewSubSection = () => {
const { newTitle, newText, newImage, newBackgroundColor, newBackgroundImage, position, location } = this.state;
const { setSubSections, subSections, setClose } = this.props;
const newSubSectionsObj = {
_id: Math.random().toString(36).substr(2, 9),
title: newTitle,
text: newText,
image_url: newImage,
background_url: newBackgroundImage,
background_color: newBackgroundColor,
position: position,
location: location
}
const newSubSections = subSections ? [newSubSectionsObj,...subSections] : [newSubSectionsObj];
this.setState({
position: 0,
location: 0,
newTitle: "",
newText: "",
newImage: "",
newBackgroundColor: "",
newBackgroundImage: "",
})
setSubSections({ newSubSections: newSubSections });
setClose();
}
renderImage = (src) => {
if(!src.includes("https")){
src = "data:image;base64," + src;
}
return src;
}
onAddedNewFile = async ({ files }) => {
const file = files[0];
let blob = await image2base64(file.preview)
this.setState({ newImage: blob })
}
onAddedNewBackgroundImage = async (files) => {
const file = files[0];
let blob = await image2base64(file.preview)
this.setState({ newBackgroundImage: blob })
}
renderAddNewImage = () => {
const { locked } = this.props;
return(
<DropzoneImage>
<Dropzone disabled={locked} style={dropzoneStyle} onDrop={(files) => this.onAddedNewFile({ files: files })} ref={(el) => (this.dropzoneRef = el)}>
<img src={upload} alt="upload" style={{ height: 20, width: 20 }}/>
<p className='text-center'>Drop the image here</p>
</Dropzone>
</DropzoneImage>
)
}
removeNewImage = () => {
this.setState({ newImage: "" })
}
removeNewBackgroundImage = () => {
this.setState({ newBackgroundImage: "" })
}
onChange = ({ type, value }) => {
this.setState({ [type]: value })
}
handleChangePosition = event => {
event.preventDefault();
this.setState({ position: parseInt(event.target.value) })
}
handleChangeLocation = event => {
event.preventDefault();
this.setState({ location: parseInt(event.target.value) })
}
handleChangeBackgroundColor = ({ _type, value }) => {
this.setState({ newBackgroundColor: value })
}
handleChangeNewTitle = ({ value }) => {
this.setState({ newTitle: value ? value : "" })
}
handleChangeNewText = ({ value }) => {
this.setState({ newText: value ? value : "" })
}
render() {
const { locked, open, setClose } = this.props;
const { position, location, newImage, newBackgroundImage, newBackgroundColor, newTitle, newText } = this.state;
return (
<Dialog open={open} fullWidth maxWidth="lg">
<DialogHeader>
<ButtonBase onClick={() => setClose()}>
<CloseIcon/>
</ButtonBase>
</DialogHeader>
<DialogContent>
<Container>
<SectionGrid className={positionsEnum[position]} backgroundColor={newBackgroundColor}>
<Title>
<h1>{newTitle}</h1>
</Title>
<Text>
<p>{newText}</p>
</Text>
{ newBackgroundImage && (
<BackgroundImage>
<img style={{ width: "100%", height: "100%", objectFit: "cover" }} alt="Background" src={this.renderImage(newBackgroundImage)}/>
</BackgroundImage>
)}
<Image>
{ newImage ? (
<>
<div style={{ display: "flex", justifyContent: "flex-end", width: "100%", marginTop: -5.5, marginBottom: -30 }}>
<button
disabled={locked}
onClick={() => this.removeNewImage()}
style={{ position: "inherit", zIndex: 20, right: 20, top: 6, backgroundColor: "transparent" }}
className='carousel-trash button-hover'>
<img src={trash} alt="remove" style={{ width: 15, height: 15 }}/>
</button>
</div>
<img style={{ width: "100%", height: "100%", objectFit: "cover" }} alt="Image" src={this.renderImage(newImage)}/>
</>
) : (
this.renderAddNewImage()
)}
</Image>
</SectionGrid>
<div style={{ display: "flex", flexDirection: "column" }}>
<FormGroup style={{ margin: 0 }}>
<InputLabel for="title">Title</InputLabel>
<InputField
label="Title"
name="title"
type="text"
value={newTitle}
disabled={locked}
onChange={(e) => this.handleChangeNewTitle({ value: e.target.value })}
/>
</FormGroup>
<FormGroup style={{ margin: 0 }}>
<InputLabel for="text">Text</InputLabel>
<InputField
label="Text"
name="text"
type="text"
value={newText}
disabled={locked}
onChange={(e) => this.handleChangeNewText({ value: e.target.value })}
/>
</FormGroup>
<BackgroundItems>
<FormGroup style={{ marginTop: 10 }}>
<InputLabel for="backgroundColor">Background color</InputLabel>
<ColorPicker
name="backgroundColor"
color={newBackgroundColor}
disabled={locked}
onChange={this.handleChangeBackgroundColor}
/>
</FormGroup>
<FormGroup style={{ marginTop: 10 }}>
<InputLabel>Background image</InputLabel>
{ !newBackgroundImage ? (
<Dropzone onDrop={this.onAddedNewBackgroundImage} style={{ width: '100%', marginTop: 7, marginBottom: 15 }} ref={(el) => (this.dropzoneRef = el)} disabled={locked}>
<UploadButton disabled={locked}>
<p style={{ fontSize: '12px', color: "white" }}><UploadIcon className="deposit-icon"/> New background image </p>
</UploadButton>
</Dropzone>
) : (
<div style={{ width: '100%', marginTop: 7, marginBottom: 15 }}>
<RemoveButton onClick={() => this.removeNewBackgroundImage()} disabled={locked}>
<p style={{ fontSize: '12px', color: "white" }}><TrashCanOutlineIcon className="deposit-icon"/> Remove background image </p>
</RemoveButton>
</div>
)}
</FormGroup>
</BackgroundItems>
<MuiThemeProvider theme={theme}>
<InputLabel>Positioning</InputLabel>
<RadioGroup row aria-label="position" name="position" value={position} onChange={this.handleChangePosition}>
<StyledFormControlLabel value={0} control={<Radio color="primary" size="small" />} label="Image on the right" disabled={locked}/>
<StyledFormControlLabel value={1} control={<Radio color="primary" size="small" />} label="Image on the left" disabled={locked}/>
<StyledFormControlLabel value={2} control={<Radio color="primary" size="small" />} label="Image on the bottom" disabled={locked}/>
<StyledFormControlLabel value={3} control={<Radio color="primary" size="small" />} label="Image on the top" disabled={locked}/>
</RadioGroup>
<br/>
<InputLabel>Location</InputLabel>
<RadioGroup row aria-label="location" name="location" value={location} onChange={this.handleChangeLocation}>
<StyledFormControlLabel value={0} control={<Radio color="primary" size="small" />} label="Before the banners" disabled={locked}/>
<StyledFormControlLabel value={1} control={<Radio color="primary" size="small" />} label="Before the games list" disabled={locked}/>
<StyledFormControlLabel value={2} control={<Radio color="primary" size="small" />} label="Before the data lists" disabled={locked}/>
<StyledFormControlLabel value={3} control={<Radio color="primary" size="small" />} label="Before the footer" disabled={locked}/>
<StyledFormControlLabel value={4} control={<Radio color="primary" size="small" />} label="After the footer" disabled={locked}/>
</RadioGroup>
</MuiThemeProvider>
<div style={{ display: "flex", justifyContent: "flex-end", padding: "10px 0px" }}>
<ConfirmButton onClick={() => this.addNewSubSection()}>
<ContentSaveIcon style={{ marginRight: 7 }}/> Create a new Subsection
</ConfirmButton>
</div>
</div>
</Container>
</DialogContent>
</Dialog>
)
}
}
export default AddSection;
<file_sep>/src/redux/reducers/periodicityReducer.js
const initialState = 'daily';
export default function (state = initialState, action) {
switch (action.type) {
case 'SET_DATA_PERIODICITY' :
return action.action
default:
return state;
}
}
<file_sep>/src/controllers/Security.js
var bcrypt = require('bcryptjs');
var SALT_ROUNDS = bcrypt.genSaltSync(10);
class Security {
constructor(password){
this.state = {
password : <PASSWORD>
}
}
hash(){
//Hash Password
try{
return this.hashPassword(this.state.password);
}catch(error){
throw error;
}
}
hashPassword = (password) => {
try{
return bcrypt.hashSync(password, SALT_ROUNDS);
}catch(error){
throw error;
}
}
unhashPassword(password, hashPassword){
// Verifying a hash
try{
return bcrypt.compareSync(password, hashPassword);
}catch(error){
throw error;
}
}
}
export default Security;<file_sep>/src/lib/errors.js
import { setMessageNotification } from "../redux/actions/messageContainer";
import store from "../containers/App/store";
async function processResponse(response){
try{
if(parseInt(response.data.status) != 200){
throw new Error(response.data.message)
}
return response.data.message
}catch(err){
throwUIError(err.message);
}
}
async function throwUIError(err){
console.log(err);
await store.dispatch(setMessageNotification({isActive : true, message : new String(err).toString()}));
}
export { processResponse, throwUIError }<file_sep>/src/containers/Transactions/components/CancelWithdrawDialog.js
import React, { Component } from 'react'
import { Dialog, DialogTitle, Divider, DialogActions } from '@material-ui/core';
export default class CancelWithdrawDialog extends Component {
constructor(props){
super(props)
this.state = {
value: null,
reason: null
};
}
onSubmit = () => {
const { cancelWithdraw } = this.props;
cancelWithdraw();
}
render() {
const { open, onClose, withdraw, isLoading } = this.props;
if(!withdraw) {return null}
return (
<Dialog
open={open}
onClose={onClose}
>
<DialogTitle>Withdraw cancellation</DialogTitle>
<Divider/>
<DialogActions>
<button disabled={isLoading[withdraw._id]} className={`clean_button button-normal button-hover`} style={{ height: "35px", backgroundColor: "#e6536e", margin: "25px", pointerEvents: isLoading[withdraw._id] ? 'none' : 'all' }} onClick={this.onSubmit}>
{ !isLoading[withdraw._id]?
<p className='text-small text-white'>Yes, cancel withdraw</p>
: <p className='text-small text-white'>Canceling...</p> }
</button>
</DialogActions>
</Dialog>
)
}
}<file_sep>/src/containers/Applications/EsportsPage/components/StatsPage/components/Teams/styles.js
import styled from 'styled-components';
export const Container = styled.div`
display: flex;
flex-direction: column;
margin: 10px;
width: 100%;
`;
export const PlayerCardContainer = styled.div`
display: grid;
grid-template-areas:
'photo'
'info';
grid-template-columns: 100%;
grid-template-rows: 45% 55%;
height: 220px;
width: 150px;
background-color: white;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
margin: 10px;
overflow-y: scroll;
::-webkit-scrollbar {
display: none;
}
`;
export const PlayerPhoto = styled.section`
grid-area: photo;
display: flex;
justify-content: center;
align-items: center;
padding: 15px 5px;
img {
margin: 5px;
height: 80px;
width: auto;
}
`;
export const PlayerInfo = styled.section`
grid-area: info;
padding: 5px 10px;
display: flex;
flex-direction: column;
justify-content: flex-start;
`;
export const PlayerName = styled.span`
font-family: Poppins;
font-size: 14px;
font-weight: 500;
`;
export const PlayerFullName = styled.span`
font-family: Poppins;
font-size: 11px;
font-weight: 400;
`;
export const Age = styled.span`
font-family: Poppins;
font-size: 12px;
font-weight: 400;
`;
export const HomeTown = styled.span`
font-family: Poppins;
font-size: 12px;
font-weight: 400;
`;
export const Nationality = styled.section`
display: flex;
padding: 10px 0px;
span {
margin-right: 8px;
font-family: Poppins;
font-size: 12px;
font-weight: 400;
}
`;
export const Role = styled.section`
display: flex;
span {
font-family: Poppins;
font-size: 12px;
font-weight: 400;
}
`;
export const TeamCard = styled.div`
display: flex;
flex-direction: column;
background-color: #fafcff;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
padding: 10px;
margin: 10px 0px;
width: 100%;
`;
export const TeamList = styled.div`
display: flex;
flex-direction: row;
flex-wrap: wrap;
`;
export const TeamInfo = styled.section`
display: grid;
grid-template-areas:
'icon name';
width: 200px;
grid-template-columns: 20% 80%;
grid-template-rows: auto;
margin: 10px 0px;
`;
export const TeamIcon = styled.section`
grid-area: icon;
display: flex;
justify-content: center;
align-items: center;
img {
/* padding: 0px 8px; */
height: 22px;
width: 22px;
}
`;
export const TeamName = styled.section`
grid-area: name;
display: flex;
justify-content: flex-start;
align-items: center;
span {
padding: 0px 8px;
font-family: Poppins;
font-size: 13px;
}
`;<file_sep>/src/containers/Landing/components/Customer.jsx
import React from 'react';
import { Col, Row, Container } from 'reactstrap';
import CheckIcon from 'mdi-react/CheckIcon';
const sports = `${process.env.PUBLIC_URL}/img/landing/sports.png`;
const backoffice = `${process.env.PUBLIC_URL}/img/widgets/backoffice.png`;
const back = `${process.env.PUBLIC_URL}/img/landing/back-3.png`;
const Customer = () => (
<section className="landing__section landing_customer_section" >
<div className='landing__heading'>
<img className="landing_3_back" src={back} />
</div>
<Container className='container__all__landing' >
<h3 className="landing__section-title">Focus on Customer Experience</h3>
<p className='landing__section-text '>
Don't worry about hiring a huge tech team or developing a betting platform by yourself
<br></br>
We handle the technology so developers and entrepreneurs can focus on the customer.
</p>
<img src={sports} className='landing__image__big'></img>
<img src={backoffice} className='landing__image__big_mockup'></img>
</Container>
</section>
);
export default Customer;
<file_sep>/src/containers/Applications/ThirdParties/components/ChatTab/Crisp.js
import React, { Component } from 'react'
import EditLock from '../../../../Shared/EditLock.js';
import { connect } from "react-redux";
import { Actions, InputField } from './styles'
import { FormLabel } from '@material-ui/core';
import BooleanInput from '../../../../../shared/components/BooleanInput.js';
const defaultState = {
isActive: true,
id: '',
name: '',
key: '',
integration_type: 'chat',
locked: true
}
const labelStyle = {
fontFamily: "Poppins",
fontSize: 14,
color: "#646777"
}
const crisp = `${process.env.PUBLIC_URL}/img/landing/crisp.png`;
class Crisp extends Component {
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { profile } = props;
const App = profile.getApp();
const cripsr = App.params.integrations.cripsr;
const { isActive, key, name, _id } = cripsr;
this.setState({
id: _id,
name: name,
isActive: isActive,
key: key
})
}
handleChangeActive = value => {
this.setState({ isActive: value })
}
handleChangeAPIKey = value => {
this.setState({ key: value })
}
unlockField = () => {
this.setState({...this.state, locked : false})
}
lockField = () => {
this.setState({...this.state, locked : true})
}
confirmChanges = async () => {
const { profile } = this.props;
const { id, key, isActive} = this.state;
this.setState({ isLoading: true});
await profile.getApp().editCrispIntegration({
isActive: isActive,
key: key,
cripsr_id: id
});
this.setState({ isLoading: false, locked: true})
this.projectData(this.props);
}
render() {
const { isLoading, locked, key, isActive } = this.state;
return (
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'chatTab'}
locked={locked}
>
<div>
<img style={{width: 90}} src={crisp}></img>
<p className="text-small text-left" style={{marginTop: 8}}><a href="https://crisp.chat/en" target="_blank">https://crisp.chat/en</a></p>
</div>
<Actions>
<div style={{ margin: "10px 0px" }}>
<FormLabel component="legend" style={labelStyle}>{ isActive ? "Active" : "Inactive" }</FormLabel>
<BooleanInput
checked={isActive === true}
onChange={() => this.handleChangeActive(!isActive)}
disabled={locked || isLoading}
type={'isActive'}
id={'isActive'}
/>
</div>
<p className="text-left secondary-text" style={{ margin: "15px 0px" }}> Add your credentials to integrate </p>
<p>API Key</p>
<InputField disabled={locked || isLoading} value={key} onChange={(e) => this.handleChangeAPIKey(e.target.value)}/>
</Actions>
</EditLock>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(Crisp);
<file_sep>/src/lib/misc.js
import _ from 'lodash';
export function emptyObject(obg){
return _.isEmpty(obg)
}<file_sep>/src/containers/NoData/index.jsx
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col, Row, Button, Progress } from 'reactstrap';
import TrendingUpIcon from 'mdi-react/TrendingUpIcon';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import _ from 'lodash';
const Ava = `${process.env.PUBLIC_URL}/img/dashboard/astronaur.png`;
class NoDataContainer extends PureComponent {
static propTypes = {
t: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = {
progress: 0,
};
}
goToDeveloperTools = () => {
this.props.history.push('/developers')
}
goToWallet = () => {
this.props.history.push('/wallet')
}
goToApplication = () => {
this.props.history.push('/application')
}
getProgress(...args){
return (args.filter(v => v).length)/args.length*100;
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData(props){
const app = props.app;
let
hasBearerToken = !_.isUndefined(app.getBearerToken()),
isDeployed = !_.isUndefined(app.isDeployed());
let progress = this.getProgress(hasBearerToken, isDeployed)
this.setState({...this.state, progress, hasBearerToken, isDeployed});
}
render() {
return (
<Col md={12} lg={12} xl={12} >
<Card>
<Row>
<Col lg={12}>
<CardBody className="dashboard__card-widget">
<Row style={{align: 'center'}}>
<Col lg={4}>
<img style={{width : '80%', margin : 'auto'}} src={Ava} alt="avatar" />
</Col>
<Col lg={8}>
<h4 style={{marginTop : 20, marginBottom : 40}} className={"dashboard__total-stat"}>
{/*parseInt(this.state.progress)}%*/} One Last Step to get your platform running
</h4>
<div className="progress-wrap">
<Progress value={this.state.progress} style={{width : 100}} />
</div>
<Row>
<Col lg={12}>
<button disabled={this.state.isDeployed} className="btn btn-primary account_btn_app" onClick={() => this.goToApplication()} >
Add Games & Customize your platform!
</button>
</Col>
</Row>
</Col>
</Row>
</CardBody>
</Col>
</Row>
</Card>
</Col>
);
}
}
export default translate('common')(NoDataContainer);
<file_sep>/src/controllers/CasinoContract.js
import {
casino
} from "./interfaces";
import Contract from "../models/Contract";
import ERC20TokenContract from "./ERC20Contract";
import { fromBigNumberToInteger } from "./services/services";
import Numbers from "../services/numbers";
let self;
class CasinoContract{
constructor({contractAddress, tokenAddress, decimals, authorizedAddress, ownerAddress, croupierAddress}){
self = {
contract :
new Contract({
web3 : window.web3,
contract : casino,
address : contractAddress,
tokenAddress : tokenAddress
}),
erc20TokenContract : tokenAddress ? new ERC20TokenContract({
web3 : global.web3,
contractAddress : tokenAddress
}) : null,
decimals,
authorizedAddress,
ownerAddress,
contractAddress,
croupierAddress
}
}
/**
* @constructor Starting Function
*/
async __init__(){
let contractDepolyed = await this.deploy();
this.__assert(contractDepolyed);
await this.authorizeCroupier({addr : self.croupierAddress});
return this;
}
async authorizeAccountToManage({addr=self.ownerAddress}){
try{
let accounts = await window.web3.eth.getAccounts();
return new Promise ( (resolve, reject) => {
self.contract.getContract().methods.authorizeAccount(
addr
).send({from : accounts[0]})
.on('transactionHash', (hash) => {
})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}catch(err){
console.log(err);
}
}
async unauthorizeAccountToManage({addr}){
try{
let accounts = await window.web3.eth.getAccounts();
return new Promise ( (resolve, reject) => {
self.contract.getContract().methods.unauthorizeAccount(
addr
).send({from : accounts[0]})
.on('transactionHash', (hash) => {
})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}catch(err){
console.log(err);
}
}
async authorizeCroupier({addr=self.authorized}){
try{
let accounts = await window.web3.eth.getAccounts();
return new Promise ( (resolve, reject) => {
self.contract.getContract().methods.authorizeCroupier(
addr
).send({from : accounts[0]})
.on('transactionHash', (hash) => {
})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}catch(err){
console.log(err);
}
}
__assert(){
self.contract.use(
casino,
self.contractAddress);
}
/**
* @constructor Starting Function
*/
sendTokensToCasinoContract = async ({amount}) => {
try{
let accounts = await window.web3.eth.getAccounts();
let amountWithDecimals = Numbers.toSmartContractDecimals(amount, self.decimals);
return new Promise ( (resolve, reject) => {
self.erc20TokenContract.getContract().methods.transfer(
self.contractAddress,
amountWithDecimals
).send({from : accounts[0]})
.on('transactionHash', (hash) => {
})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}catch(err){
console.log(err);
}
}
async start(){
}
async getApprovedWithdrawAmount(address){
try{
return Numbers.fromBigNumberToInteger(
(await self.contract.getContract().methods.withdrawals(address).call()).amount
)
}catch(err){
throw err;
}
}
async withdrawTokens({amount, decimals}){
let amountWithDecimals = Numbers.toSmartContractDecimals(amount, decimals);
let accounts = await window.web3.eth.getAccounts();
return new Promise ( (resolve, reject) => {
self.contract.getContract().methods.withdraw(
amountWithDecimals
).send({from : accounts[0]})
.on('transactionHash', (hash) => {
})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}
async setUserWithdrawal({address, amount}){
try{
let accounts = await window.web3.eth.getAccounts();
let amountWithDecimals = Numbers.toSmartContractDecimals(amount, self.decimals);
return new Promise ( (resolve, reject) => {
self.contract.getContract().methods.setUserWithdrawal(
address,
amountWithDecimals
).send({from : accounts[0]})
.on('transactionHash', (hash) => {
})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}catch(err){
throw err;
}
}
async setUserWithdrawalBatch({addresses, amounts}){
try{
let accounts = await window.web3.eth.getAccounts();
let amountsWithDecimals = amounts.map( a => Numbers.toSmartContractDecimals(a, self.decimals))
return new Promise ( (resolve, reject) => {
self.contract.getContract().methods.setUserWithdrawalBatch(
addresses,
amountsWithDecimals
).send({from : accounts[0]})
.on('transactionHash', (hash) => {
})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}catch(err){
throw err;
}
}
async withdrawApp({amount}){
try{
let accounts = await window.web3.eth.getAccounts();
let amountWithDecimals = Numbers.toSmartContractDecimals(amount, self.decimals);
return new Promise ( (resolve, reject) => {
self.contract.getContract().methods.ownerWithdrawalTokens(
accounts[0],
amountWithDecimals
).send({from : accounts[0]})
.on('transactionHash', (hash) => {
})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}catch(err){
throw err;
}
}
async changeCasinoToken({address}){
try{
let accounts = await window.web3.eth.getAccounts();
return new Promise ( (resolve, reject) => {
self.contract.getContract().methods.changeSingleTokenContract(
address
).send({from : accounts[0]})
.on('transactionHash', (hash) => {
})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}catch(err){
throw err;
}
}
async getBankRoll(){
try{
return Numbers.fromBigNumberToInteger(await self.contract.getContract().methods.bankroll().call(), self.decimals);
}catch(err){
throw err;
}
}
fromIntToFloatEthereum(int){
return Math.round(int*100);
}
async getHouseTokenAmount(){
try{
let playersTokenAmount = await this.getAllPlayersTokenAmount();
let houseAmount = await this.getSmartContractLiquidity();
return houseAmount - playersTokenAmount;
}catch(err){
return 'N/A';
}
}
async getAllPlayersTokenAmount(){
try{
return Numbers.fromDecimals(await self.contract.getContract().methods.totalPlayerBalance().call(), self.decimals);
}catch(err){
return 'N/A';
}
}
async getSmartContractLiquidity(){
try{
return Numbers.fromDecimals(await self.erc20TokenContract.getTokenAmount(this.getAddress()), self.decimals);
}catch(err){
return 'N/A';
}
}
async getMaxDeposit(){
try{
return Numbers.fromDecimals(await self.contract.getContract().methods.maxDeposit().call(), self.decimals);
}catch(err){
return 'N/A';
}
}
async getMaxWithdrawal(){
try{
return Numbers.fromDecimals(await self.contract.getContract().methods.maxWithdrawal().call(), self.decimals);
}catch(err){
return 'N/A';
}
}
async isPaused(){
try{
return await self.contract.getContract().methods.paused().call();
}catch(err){
return 'N/A';
}
}
async pauseContract(){
try{
let accounts = await window.web3.eth.getAccounts();
return new Promise ( (resolve, reject) => {
self.contract.getContract().methods.pause().send({from : accounts[0]})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}catch(err){
throw err;
}
}
async unpauseContract(){
try{
let accounts = await window.web3.eth.getAccounts();
return new Promise ( (resolve, reject) => {
self.contract.getContract().methods.unpause().send({from : accounts[0]})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}catch(err){
throw err;
}
}
async getWithdrawalTimeLimit(){
try{
return Numbers.fromSmartContractTimeToMinutes(await self.contract.getContract().methods.releaseTime().call());
}catch(err){
console.log(err)
return 'N/A';
}
}
async changeMaxDeposit({amount}){
try{
let accounts = await window.web3.eth.getAccounts();
let amountWithDecimals = Numbers.toSmartContractDecimals(amount, self.decimals);
return new Promise ( (resolve, reject) => {
self.contract.getContract().methods.changeMaxDeposit(
amountWithDecimals
).send({from : accounts[0]})
.on('transactionHash', (hash) => {
})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}catch(err){
throw err;
}
}
async changeMaxWithdrawal({amount}){
try{
let accounts = await window.web3.eth.getAccounts();
let amountWithDecimals = Numbers.toSmartContractDecimals(amount, self.decimals);
return new Promise ( (resolve, reject) => {
self.contract.getContract().methods.changeMaxWithdrawal(
amountWithDecimals
).send({from : accounts[0]})
.on('transactionHash', (hash) => {
})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}catch(err){
throw err;
}
}
async changeWithdrawalTimeLimit({amount}){
try{
let accounts = await window.web3.eth.getAccounts();
let SCTime = Numbers.fromMinutesToSmartContracTime(amount);
return new Promise ( (resolve, reject) => {
self.contract.getContract().methods.changeReleaseTime(
SCTime
).send({from : accounts[0]})
.on('transactionHash', (hash) => {
})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}catch(err){
throw err;
}
}
/**
* @Functions
*/
async deploy(){
let accounts = await window.web3.eth.getAccounts();
let params = [
self.erc20TokenContract.getAddress(), // Token Contract
self.authorizedAddress, // Authorized Address
self.ownerAddress // Owner Address
];
let res = await self.contract.deploy(
accounts[0],
self.contract.getABI(),
self.contract.getJSON().bytecode,
params);
self.contract.setAddress(res.contractAddress);
self.contractAddress = res.contractAddress;
return res;
}
getAddress(){
return self.contractAddress || self.contract.getAddress();
}
}
export default CasinoContract;<file_sep>/src/containers/Applications/Customization/components/Icons/Icon.js
import React from 'react';
import { FormGroup, Col } from 'reactstrap';
import { Cancel, IconCard, IconCardContent, IconImage, InputField, InputLabel, RemoveIcon, Yes } from './styles';
import _ from 'lodash';
import Dropzone from 'react-dropzone'
import { TrashCanOutlineIcon } from 'mdi-react';
import enumIcons from './enumIcons';
const upload = `${process.env.PUBLIC_URL}/img/dashboard/upload.png`;
const trash = `${process.env.PUBLIC_URL}/img/dashboard/clear.png`;
const image2base64 = require('image-to-base64');
const dropzoneStyle = {
width: "100%",
height: "100%",
backgroundColor: "white"
};
class Icon extends React.Component {
constructor(props){
super(props);
this.state = {
removing: false,
isSVG: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { icons, icon } = props;
if (!_.isEmpty(icons)) {
this.setState({
icons: icons,
_id: icon._id,
name: icon.name,
link: icon.link,
position: icon.position,
isSVG: icon.isSVG
})
}
}
renderImage = (src) => {
const { isSVG } = this.state;
if(!src.includes("https")){
src = isSVG ? "data:image/svg+xml;base64," + src : "data:image;base64," + src;
}
return src;
}
onAddedFile = async ({ id, files }) => {
const { icons } = this.state;
const { setIcons } = this.props;
const file = files[0];
this.setState({ isSVG: false })
if (file.type === 'image/svg+xml') {
this.setState({ isSVG: true })
}
let blob = await image2base64(file.preview) // you can also to use url
const index = icons.findIndex(icon => icon._id === id);
const newIcons = [...icons];
newIcons[index].link = blob;
setIcons({ newIcons: newIcons })
}
renderAddImage = ({ id }) => {
const { locked } = this.props;
return(
<Dropzone disabled={locked} style={dropzoneStyle} onDrop={(files) => this.onAddedFile({ id: id, files: files })} ref={(el) => (this.dropzoneRef = el)}>
<img src={upload} className='image-info' style={{ height: 20, width: 20 }}/>
<p className='text-center'> Drop the icon here</p>
</Dropzone>
)
}
onChangeName = ({ id, value }) => {
const { icons } = this.state;
const { setIcons } = this.props;
const icon = enumIcons.find(icon => icon.name === value);
if (value) {
const index = icons.findIndex(icon => icon._id === id);
const newIcons = [...icons];
newIcons[index].name = value;
newIcons[index].position = icon.position;
setIcons({ newIcons: newIcons })
} else {
const index = icons.findIndex(icon => icon._id === id);
const newIcons = [...icons];
newIcons[index].name = "";
setIcons({ newIcons: newIcons })
}
}
onChangeLink = ({ id, value }) => {
const { icons } = this.state;
const { setIcons } = this.props;
if (value) {
const index = icons.findIndex(icon => icon._id === id);
const newIcons = [...icons];
newIcons[index].link = value;
setIcons({ newIcons: newIcons })
} else {
const index = icons.findIndex(icon => icon._id === id);
const newIcons = [...icons];
newIcons[index].link = "";
setIcons({ newIcons: newIcons })
}
}
removeImage = ({ id }) => {
const { icons } = this.state;
const { setIcons } = this.props;
const index = icons.findIndex(icon => icon._id === id);
const newIcons = [...icons];
newIcons[index].link = "";
setIcons({ newIcons: newIcons })
}
removeIcon = ({ id }) => {
this.setState({ removing: true })
}
cancelRemoveIcon = ({ id }) => {
this.setState({ removing: false })
}
removeIconCard = ({ id }) => {
const { icons } = this.state;
const { setIcons } = this.props;
const index = icons.findIndex(icon => icon._id === id);
const newIcons = [...icons];
newIcons[index] = {};
this.setState({ removing: false })
setIcons({
newIcons: newIcons.filter(icon => !_.isEmpty(icon))
})
}
render() {
const { _id, name, link, removing } = this.state;
const { locked, icons } = this.props;
if (!name || !icons) return null
const filteredIcons = _.without(enumIcons.filter(icon => !icons.map(i => i.name).includes(icon.name)).concat([enumIcons.find(i => i.name === name)]), undefined);
return (
<>
<Col md={3} style={{ minWidth: 178, maxWidth: 230, padding: 0, margin: "10px 15px" }}>
<IconCard>
<IconCardContent>
{ !_.isEmpty(link) ?
<>
<div style={{ display: "flex", justifyContent: "flex-end", width: "100%", marginBottom: -30 }}>
<button
disabled={locked}
onClick={() => this.removeImage({ id: _id })}
style={{ position: "inherit", right: 20, top: 6 }}
className='carousel-trash button-hover'>
<img src={trash} style={{width : 15, height : 15}}/>
</button>
</div>
<img className='application__game__image' style={{ display: 'block', width: 100, height: 100 }} src={this.renderImage(link)}/>
</>
:
<IconImage>
{ this.renderAddImage({ id: _id }) }
</IconImage> }
<br/>
<FormGroup>
<InputLabel for="name">Name</InputLabel>
<InputField
label="Name"
name="name"
type="select"
value={name}
disabled={locked}
onChange={(e) => this.onChangeName({ id: _id, value: e.target.value })}
>
{ filteredIcons && _.sortBy(filteredIcons, ['name']).map(icon => (
<option key={icon.name}>{icon.name}</option>
))}
</InputField>
</FormGroup>
{ !removing ?
<RemoveIcon disabled={locked} onClick={() => this.removeIcon({ id: _id })}>
<TrashCanOutlineIcon/> Remove icon
</RemoveIcon>
:
<div style={{ display: "flex" }}>
<Yes disabled={locked} onClick={() => this.removeIconCard({ id: _id })}>
Yes
</Yes>
<Cancel disabled={locked} onClick={() => this.cancelRemoveIcon({ id: _id })}>
Cancel
</Cancel>
</div> }
</IconCardContent>
</IconCard>
</Col>
</>
)
}
}
export default Icon;
<file_sep>/src/containers/Transactions/components/ConfirmWithdrawDialog.js
import React, { Component } from 'react'
import { Dialog, DialogContent, DialogActions } from '@material-ui/core';
export default class ConfirmWithdrawDialog extends Component {
onSubmit = () => {
const { allowWithdraw, withdraw } = this.props;
allowWithdraw(withdraw);
}
render() {
const { open, onClose, withdraw, isLoading } = this.props;
if (!withdraw) {return null};
return (
<Dialog
open={open}
onClose={onClose}
>
<DialogContent>
<h4>Are you sure you want to confirm the withdraw ?</h4>
</DialogContent>
<DialogActions>
<button disabled={isLoading[withdraw._id]}className={`clean_button button-normal button-hover`} style={{ height: "35px", backgroundColor: "#63c965", margin: "25px", pointerEvents: isLoading[withdraw._id] ? 'none' : 'all' }} onClick={this.onSubmit}>
{ !isLoading[withdraw._id] ?
<p className='text-small text-white'>Yes, confirm withdraw</p>
: <p className='text-small text-white'>Confirming...</p> }
</button>
</DialogActions>
</Dialog>
)
}
}<file_sep>/src/containers/Applications/ThirdParties/components/KYC/index.js
import React, { Component } from 'react'
import EditLock from '../../../../Shared/EditLock.js';
import { connect } from "react-redux";
import { FormLabel } from '@material-ui/core';
import { Card, CardBody } from 'reactstrap';
import { Actions, InputField, CopyButton } from './styles'
import BooleanInput from '../../../../../shared/components/BooleanInput.js';
import copy from "copy-to-clipboard";
const defaultState = {
isActive: true,
_id: '',
clientId: '',
flowId: '',
client_secret: '',
integration_type: 'kyc',
locked: true,
copied: false
}
const cardBodyStyle = {
margin: 10,
borderRadius: "10px",
border: "solid 1px rgba(164, 161, 161, 0.35)",
backgroundColor: "#fafcff",
boxShadow: "none"
}
const labelStyle = {
fontFamily: "Poppins",
fontSize: 14,
color: "#646777"
}
const groupStyle = {
display: "flex",
flexDirection: "row",
alignItems: "center",
gap: 20
}
const mati = `${process.env.PUBLIC_URL}/img/landing/mati.png`;
const MS_MASTER_URL = process.env.REACT_APP_API_MASTER;
class KYC extends Component {
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { profile } = props;
const App = profile.getApp();
const kyc = App.params.integrations.kyc;
const { _id, isActive, clientId, flowId, client_secret } = kyc;
this.setState({
_id: _id,
isActive: isActive,
clientId: clientId,
flowId: flowId,
client_secret: client_secret ? client_secret : ""
})
}
copyToClipboard = () => {
copy(`${MS_MASTER_URL}/api/app/kyc_webhook`);
this.setState({ copied: true })
setTimeout(() => {
this.setState({ copied: false });
}, 5000)
}
unlockField = () => {
this.setState({ locked: false })
}
lockField = () => {
this.setState({ locked: true })
}
handleChangeActive = value => {
this.setState({ isActive: value })
}
handleChangeClientID = value => {
this.setState({ clientId: value })
}
handleChangeFlowID = value => {
this.setState({ flowId: value })
}
handleChangeClientSecret = value => {
this.setState({ client_secret: value })
}
confirmChanges = async () => {
const { profile } = this.props;
const { _id, isActive, clientId, flowId, client_secret } = this.state;
this.setState({ isLoading: true});
await profile.getApp().editKYCIntegration({
kyc_id: _id,
isActive: isActive,
clientId: clientId ? clientId : "",
flowId: flowId ? flowId : "",
client_secret: client_secret ? client_secret : ""
});
this.setState({ isLoading: false, locked: true})
this.projectData(this.props);
}
render() {
const { isLoading, locked, isActive, clientId, flowId, client_secret, copied } = this.state;
return (
<Card>
<CardBody style={cardBodyStyle}>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'kyc'}
locked={locked}>
<div>
<img style={{ width: 90 }} alt="mati" src={mati}></img>
<p className="text-small text-left" style={{ marginTop: 8 }}><a href="https://getmati.com" target="_blank">https://getmati.com</a></p>
</div>
<Actions>
<div style={{ margin: "10px 0px" }}>
<FormLabel component="legend" style={labelStyle}>{ isActive ? "Active" : "Inactive" }</FormLabel>
<BooleanInput
checked={isActive === true}
onChange={() => this.handleChangeActive(!isActive)}
disabled={locked || isLoading}
type={'isActive'}
id={'isActive'}
/>
</div>
<p className="text-left secondary-text" style={{ margin: "15px 0px" }}> Add your credentials to integrate </p>
<p>Client ID</p>
<InputField disabled={locked || isLoading} value={clientId} onChange={(e) => this.handleChangeClientID(e.target.value)}/>
<p>Flow ID</p>
<InputField disabled={locked || isLoading} value={flowId} onChange={(e) => this.handleChangeFlowID(e.target.value)}/>
<p>Client Secret</p>
<InputField disabled={locked || isLoading} value={client_secret} onChange={(e) => this.handleChangeClientSecret(e.target.value)}/>
<hr/>
<p>Copy our Webhook URL</p>
<div style={groupStyle}>
<InputField disabled={true} value={`${MS_MASTER_URL}/api/app/kyc_webhook`}/>
<CopyButton variant="contained" onClick={() => this.copyToClipboard()} disabled={copied || locked}>
{copied ? 'Copied!' : 'Copy'}
</CopyButton>
</div>
</Actions>
</EditLock>
</CardBody>
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(KYC);
<file_sep>/src/containers/Wallet/components/WalletTabs/Deposit.js
import React, { Component } from 'react'
import { connect } from 'react-redux';
import { Paragraph } from '../LiquidityWalletContainer/styles';
import { TabContainer, DepositContent, InputAddOn, AmountInput, DepositButton } from './styles';
import { InputGroup, InputGroupAddon } from 'reactstrap';
import _, { isNull } from 'lodash';
const loading = `${process.env.PUBLIC_URL}/img/loading.gif`;
class Deposit extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: false,
newBalance: null
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { data } = props;
if (!_.isEmpty(data)) {
this.setState({
wallet: data.wallet
})
} else {
this.setState({
wallet: {}
})
}
}
handleChangeAmount = value => {
this.setState({ newBalance: value || null });
}
handleAddBalanceToApp = async () => {
const { profile } = this.props;
const { newBalance, wallet } = this.state;
const { currency } = wallet;
if (!isNull(newBalance) && newBalance > 0 ) {
this.setState({ isLoading: true });
await profile.getApp().updateAppBalance({ increase_amount: parseFloat(newBalance), currency: currency._id });
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({ isLoading: false, newBalance: null });
}
}
render() {
const { wallet, isLoading, newBalance } = this.state;
if (_.isEmpty(wallet)) return null
const { image, name } = wallet.currency;
return (
<>
<TabContainer>
<Paragraph>Choose the Amount of Liquidity you want to Deposit</Paragraph>
<DepositContent>
<InputGroup style={{ margin: "20px 0px" }}>
<InputGroupAddon addonType="prepend">
<InputAddOn style={{ marginTop: 0 }}>
<span>Amount</span>
<img className='application__game__image' style={{ display: 'block', marginLeft: 0, marginRight: 0, height: 20, width: 20 }} src={image} alt={name}/>
</InputAddOn>
</InputGroupAddon>
<AmountInput name="amount" type="number" onChange={(e) => this.handleChangeAmount(e.target.value)} style={{ margin: 0 }}/>
<InputGroupAddon addonType="append">
<DepositButton variant="contained" onClick={() => this.handleAddBalanceToApp()} disabled={ isLoading || isNull(newBalance) }>
{ !isLoading ? 'Deposit' : <img src={loading} className={'loading_gif'} alt="Loading.."/> }
</DepositButton>
</InputGroupAddon>
</InputGroup>
</DepositContent>
</TabContainer>
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(Deposit);
<file_sep>/src/containers/Dashboards/Default/components/TimePicker.js
import React from 'react';
import Grid from '@material-ui/core/Grid';
import Button from '@material-ui/core/Button';
import ButtonGroup from '@material-ui/core/ButtonGroup';
import store from '../../../App/store';
import { setDataPeriodicity } from '../../../../redux/actions/periodicityAction';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import PropTypes from 'prop-types';
class TimePicker extends React.Component{
constructor(props){
super(props);
}
change = async (value) => {
const { onChange } = this.props;
await store.dispatch(setDataPeriodicity(value));
if(onChange){onChange({value})}
}
render = () => {
const { periodicity } = this.props;
return (
<div className='panel-empty'>
<Grid container spacing={3}>
<Grid item>
<ButtonGroup size="small" aria-label="small button group">
<Button disabled={periodicity === 'daily'} onClick={() => this.change('daily')}> Daily </Button>
<Button disabled={periodicity === 'weekly'} onClick={() => this.change('weekly')}> Weekly </Button>
{/* <Button disabled={periodicity === 'monthly'} onClick={() => this.change('monthly')}> Monthly </Button>
<Button disabled={periodicity === 'all'} onClick={() => this.change('all')}> All </Button> */}
</ButtonGroup>
</Grid>
</Grid>
</div>
);
}
}
function mapStateToProps(state){
return {
periodicity : state.periodicity
};
}
TimePicker.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
connect(mapStateToProps)
)(TimePicker);
<file_sep>/src/containers/Settings/tabs/ComplianceContainer.js
import React from 'react';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import { Paper, Typography, Chip, TextField } from '@material-ui/core';
import CountryMap from './Components/CountryMap';
import ReactTooltip from 'react-tooltip';
import Autocomplete from '@material-ui/lab/Autocomplete';
import EditLock from './Components/EditLock';
import { DatePicker } from 'antd';
import ExportCompliance from './ExportCompliance';
const { RangePicker } = DatePicker;
const countries = require("i18n-iso-countries");
countries.registerLocale(require("i18n-iso-countries/langs/en.json"));
const countriesObj = countries.getNames('en');
let allCountries = [];
Object.keys(countriesObj).forEach((key) => {
allCountries.push({ code: key, label: countriesObj[key] })
});
class ComplianceContainer extends React.Component{
constructor(props){
super(props);
this.state = {
restrictedCountries: [],
content: "",
lock: true,
loading: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { profile } = props;
const app = profile.App;
this.setState({
restrictedCountries: app.params.restrictedCountries
})
}
addCountry = (country) => {
const { restrictedCountries } = this.state;
if (!restrictedCountries.includes(country)) {
restrictedCountries.push(country);
this.setState({
restrictedCountries: restrictedCountries
})
}
}
removeCountry = (country) => {
const { restrictedCountries } = this.state;
if (restrictedCountries.includes(country)) {
restrictedCountries.splice(restrictedCountries.indexOf(country), 1)
this.setState({
restrictedCountries: restrictedCountries
})
}
}
setContent = (content) => {
this.setState({
content: content
})
}
unlock = () => {
this.setState({...this.state, lock: false })
}
lock = () => {
this.setState({...this.state, lock: true })
}
confirmChanges = async (currency) => {
const { profile } = this.props;
const { restrictedCountries } = this.state;
const app = profile.App;
this.setState({...this.state, loading: true })
await app.editRestrictedCountries({ countries: restrictedCountries })
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({...this.state, loading: false })
this.lock()
}
render = () => {
const { restrictedCountries, content, lock } = this.state;
if (!restrictedCountries) { return null}
return (
<div style={{ margin: 10 }}>
<ExportCompliance />
<hr/>
<Paper style={{ padding: 15, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }} >
<Typography style={{ fontSize: 17 }} variant="h6" id="tableTitle">Restricted Countries</Typography>
<EditLock
style={{ width: "100%"}}
unlockField={this.unlock}
lockField={this.lock}
confirmChanges={() => this.confirmChanges()}
isLoading={this.state.loading}
locked={lock}>
<div style={{ display: "flex", flexDirection: "column", width: "100%", height: "100%" }}>
<div style={{ display: "flex", flexDirection: "row", width: "100%", flexWrap: 'wrap'}}>
<div style={{ display: "flex", flexDirection: "column", width: 250, padding: 15, alignSelf: "flex-end" }}>
<Typography style={{ fontSize: 15 }} variant="h6" id="tableTitle">Search country</Typography>
<br/>
<Autocomplete
id="country-select"
options={allCountries}
disabled={lock}
autoHighlight
onChange={(event, newValue) => {
if (newValue) {
this.addCountry(newValue.code)
}
}}
getOptionLabel={(option) => option.label}
renderOption={(option) => (
<>
{option.label}
</>
)}
renderInput={(params) => (
<TextField
{...params}
size="small"
label="Choose a country"
variant="filled"
inputProps={{
...params.inputProps,
autoComplete: 'new-password', // disable autocomplete and autofill
}}
/>
)}
/>
</div>
<div style={{ display: 'flex', justifyContent: 'center', flexWrap: "wrap", alignItems: "center", margin: "0px 10px" }}>
{ restrictedCountries.map(country => (
<Chip
disabled={lock}
label={countriesObj[country]}
onDelete={() => this.removeCountry(country)}
style={{ backgroundColor: "#8c449b", color: "#ffffff", margin: 5 }}
/>))}
</div>
</div>
<div style={{ width: "100%", height: "100%" }}>
<CountryMap
lock={lock}
restrictedCountries={restrictedCountries}
add={this.addCountry}
remove={this.removeCountry}
setContent={this.setContent}/>
<ReactTooltip>{content}</ReactTooltip>
</div>
</div>
</EditLock>
</Paper>
<br/>
</div>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
ComplianceContainer.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(ComplianceContainer);
<file_sep>/src/config/appCreation.js
const eth = `${process.env.PUBLIC_URL}/img/tokens/eth.png`;
const appCreationConfig = {
'blockchains' : {
'eth' : {
image : eth
}
}
}
export default appCreationConfig;<file_sep>/src/containers/Wallet/index.jsx
import WalletContainer from './WalletContainer';
import CurrencyStore from './CurrencyStore';
export {
WalletContainer,
CurrencyStore
}<file_sep>/src/containers/Dashboards/Default/components/CompanyId/EditDialog.js
import React from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import { DialogHeader, TextField, DialogActions, ConfirmButton } from './styles';
import { CloseIcon, ContentSaveIcon } from 'mdi-react';
import { Dialog, ButtonBase, DialogContent, FormLabel } from '@material-ui/core';
const labelStyle = {
fontFamily: "Poppins",
fontSize: 15,
color: "#646777"
}
class EditDialog extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: false,
name: "",
description: ""
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { profile } = this.props;
const { App } = profile;
const { name, description } = App.params;
this.setState({ name: name, description: description });
}
handleChangeName = value => {
this.setState({ name: value })
}
handleChangeDescription = value => {
this.setState({ description: value })
}
handleUpdateAppInfo = async () => {
const { profile, handleCloseDialog, setAppInfo } = this.props;
const { name, description } = this.state;
this.setState({ isLoading: true });
await profile.getApp().editApp({
editParams: {
name: name,
app_description: description
}
})
this.setState({ isLoading: false });
setAppInfo({ name, description });
handleCloseDialog();
}
render() {
const { open, handleCloseDialog } = this.props;
const { name, description, isLoading } = this.state;
return (
<Dialog open={open} fullWidth maxWidth="xs">
<DialogHeader>
<ButtonBase onClick={() => handleCloseDialog()} disabled={isLoading}>
<CloseIcon/>
</ButtonBase>
</DialogHeader>
<DialogContent>
<FormLabel component="legend" style={labelStyle} >Name</FormLabel>
<TextField placeholder="" value={name} onChange={(e) => this.handleChangeName(e.target.value)} disabled={isLoading}/>
<br/>
<FormLabel component="legend" style={labelStyle} >Description</FormLabel>
<TextField placeholder="" value={description} onChange={(e) => this.handleChangeDescription(e.target.value)} disabled={isLoading}/>
</DialogContent>
<DialogActions>
<ConfirmButton disabled={ _.isEmpty(name) || isLoading } onClick={() => this.handleUpdateAppInfo()}>
{ isLoading ? "Updating..." : <><ContentSaveIcon style={{ margin: "0px 7px" }}/> Update</> }
</ConfirmButton>
</DialogActions>
</Dialog>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(EditDialog);
<file_sep>/src/containers/Applications/EsportsPage/components/Skeletons/MatchSkeleton/index.js
import React from 'react';
import { MatchContainer, MatchInfo, TeamsInfo, ActionArea, Footer, TeamOne, Result, TeamTwo } from './styles';
import Skeleton from '@material-ui/lab/Skeleton';
const MatchSkeleton = props => {
const { hasEsports } = props;
return (
<>
<MatchContainer disableHover>
<MatchInfo>
<Skeleton variant="rect" width="100%" height="80%" animation={hasEsports} />
</MatchInfo>
<TeamsInfo>
<TeamOne>
<Skeleton variant="rect" width="70%" height="30%" animation={hasEsports} />
<Skeleton variant="circle" width="35px" height="35px" style={{ margin: "0px 8px" }} animation={hasEsports}/>
</TeamOne>
<Result>
<Skeleton variant="rect" width="100%" height="80%" animation={hasEsports} />
</Result>
<TeamTwo>
<Skeleton variant="circle" width="35px" height="35px" style={{ margin: "0px 8px" }} animation={hasEsports}/>
<Skeleton variant="rect" width="70%" height="30%" animation={hasEsports}/>
</TeamTwo>
</TeamsInfo>
<ActionArea>
<Skeleton variant="rect" width="80%" height="80%" animation={hasEsports}/>
</ActionArea>
<Footer>
<Skeleton variant="rect" width="100%" height="60%" animation={hasEsports} />
</Footer>
</MatchContainer>
</>
)
}
export default MatchSkeleton;<file_sep>/src/containers/Applications/EsportsPage/components/MarketsPage/components/WinnerThreeWay/index.js
import React from 'react';
import { Container, Header, Result, ResultHeader, MarketName, Status, Tag, Content, ResultTag, TeamName, TeamResult, Graph, CloseButton, GraphContainer } from './styles';
import _ from 'lodash';
import { Modal, Button } from 'antd';
import { LineChartOutlined } from '@ant-design/icons';
import { Line } from 'react-chartjs-2';
import matchStatusEnum from '../../../Enums/status';
const GraphModal = props => {
const { open, toggleModal, teamOne, teamTwo } = props;
const state = {
labels: ['06/26', '06/26', '06/27', '06/28', '06/29', '06/30', '07/01', '07/02', '07/03', '07/04'],
datasets: [{
label: teamOne.name,
fill: false,
data: Array.from({length: 10}, () => teamOne.probability),
borderColor: [
'rgb(51, 153, 255)'
],
borderWidth: 3
},
{
label: teamTwo.name,
fill: false,
data: Array.from({length: 10}, () => teamTwo.probability),
borderColor: [
'rgb(237, 85, 101)'
],
borderWidth: 3
}
]
}
return (
<>
<Modal
title="Winner 2-Way - MATCH"
centered
visible={open}
width={1000}
onOk={() => toggleModal()}
onCancel={() => toggleModal()}
footer={[
// <CloseButton key="close" onClick={() => toggleModal()}>
// Close
// </CloseButton>
]}
>
<GraphContainer>
<Line
data={state}
options={{
responsive: true,
maintainAspectRatio: true,
legend: {
display: true,
position: 'bottom'
},
scales: {
xAxes: [{
gridLines: {
display:false
}
}],
yAxes: [{
ticks: {
suggestedMin: 0,
max: 1,
beginAtZero: true
},
}]
},
elements: {
point:{
radius: 0
}
}
}}
/>
</GraphContainer>
</Modal>
</>
)
}
class WinnerThreeWay extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { selections, status, teamOneName, teamTwoName } = props;
const [teamOne, tie, teamTwo] = selections;
this.setState({
teamOne: teamOne,
tie: tie,
teamTwo: teamTwo,
teamOneName: teamOneName,
teamTwoName: teamTwoName,
status: status
})
}
getResultColor = team => {
switch (true) {
case team.result === 'win':
return "#c6ebcc"
case team.result === 'lose':
return "#facfd4"
default:
return "#f4f7fa";
}
}
getResultText = team => {
switch (true) {
case team.result === 'win':
return "Winner"
case team.result === 'lose':
return "Loser"
default:
return `${(1/team.probability).toFixed(2)}`;
}
}
getResultTextColor = team => {
switch (true) {
case team.result === 'win':
return "#246b31"
case team.result === 'lose':
return "#ac1120"
default:
return "#333333";
}
}
toggleModal = () => {
const { open } = this.state;
this.setState({
open: !open
})
}
render() {
const { teamOne, tie, teamTwo, status, teamOneName, teamTwoName, open } = this.state;
if (_.isEmpty(teamOne) || _.isEmpty(tie) || _.isEmpty(teamTwo)) return null;
const matchStatus = status ? matchStatusEnum[status] : null;
return (
<>
<Container>
<Header>
Winner
</Header>
<Result>
<ResultHeader>
<GraphModal open={open} toggleModal={this.toggleModal} teamOne={teamOne} teamTwo={teamTwo}/>
<MarketName>
Winner 3-Way - MATCH
</MarketName>
{/* <Graph>
<Button type="link" onClick={() => this.toggleModal()}>
See graph <LineChartOutlined style={{ fontSize: '16px' }} />
</Button>
</Graph> */}
<Status>
{ matchStatus && <Tag backgroundColor={matchStatus.backgroundColor} textColor={matchStatus.textColor}>
{ matchStatus.text }
</Tag> }
</Status>
</ResultHeader>
<Content>
<ResultTag backgroundColor={this.getResultColor(teamOne)}>
<TeamName>
{ teamOneName }
</TeamName>
<TeamResult color={this.getResultTextColor(teamOne)}>
{ this.getResultText(teamOne) }
</TeamResult>
</ResultTag>
<ResultTag backgroundColor={this.getResultColor(tie)} style={{ margin: "0px 10px"}}>
<TeamName>
Tie
</TeamName>
<TeamResult color={this.getResultTextColor(tie)}>
{ this.getResultText(tie) }
</TeamResult>
</ResultTag>
<ResultTag backgroundColor={this.getResultColor(teamTwo)}>
<TeamName>
{ teamTwoName }
</TeamName>
<TeamResult color={this.getResultTextColor(teamTwo)}>
{ this.getResultText(teamTwo) }
</TeamResult>
</ResultTag>
</Content>
</Result>
</Container>
</>
)
}
}
export default WinnerThreeWay;<file_sep>/src/containers/Applications/ThirdParties/components/ChatTab/Stream.js
import React, { Component } from 'react'
import EditLock from '../../../../Shared/EditLock.js';
import { connect } from "react-redux";
import BooleanInput from '../../../../../shared/components/BooleanInput.js';
import { FormLabel } from '@material-ui/core';
import { Actions, InputField } from './styles'
const defaultState = {
isActive: true,
integration_id: '',
publicKey: '',
privateKey: '',
integration_type: 'live_chat',
locked: true
}
const labelStyle = {
fontFamily: "Poppins",
fontSize: 14,
color: "#646777"
}
const stream = `${process.env.PUBLIC_URL}/img/landing/stream.png`;
class Stream extends Component {
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const chat = props.profile.getApp().getChatIntegration();
const { isActive, privateKey, publicKey } = chat;
this.setState({...this.state,
integration_id : chat._id,
isActive,
privateKey,
publicKey
})
}
handleChangeActive = value => {
this.setState({ isActive: value })
}
handleChangePublicKey = value => {
this.setState({ publicKey: value })
}
handleChangePrivateKey = value => {
this.setState({ privateKey: value })
}
unlockField = () => {
this.setState({...this.state, locked : false})
}
lockField = () => {
this.setState({...this.state, locked : true})
}
confirmChanges = async () => {
var { profile } = this.props;
this.setState({...this.state, isLoading : true});
await profile.getApp().editIntegration(this.state);
this.setState({...this.state, isLoading : false, locked: true})
this.projectData(this.props);
}
render() {
const { isLoading, locked, isActive, publicKey, privateKey } = this.state;
return (
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'chatTab'}
locked={locked}
>
<div>
<img style={{width : 70}} src={stream}></img>
<p className="text-small text-left" style={{marginTop : 0}}><a href="https://getstream.io" target="_blank">https://getstream.io</a></p>
</div>
<Actions>
<div style={{ margin: "10px 0px" }}>
<FormLabel component="legend" style={labelStyle}>{ isActive ? "Active" : "Inactive" }</FormLabel>
<BooleanInput
checked={isActive === true}
onChange={() => this.handleChangeActive(!isActive)}
disabled={locked || isLoading}
type={'isActive'}
id={'isActive'}
/>
</div>
<p className="text-left secondary-text" style={{ margin: "15px 0px" }}> Add your credentials to integrate </p>
<p>Public Key</p>
<InputField disabled={locked || isLoading} value={publicKey} onChange={(e) => this.handleChangePublicKey(e.target.value)}/>
<p>Private Key</p>
<InputField disabled={locked || isLoading} value={privateKey} onChange={(e) => this.handleChangePrivateKey(e.target.value)}/>
</Actions>
</EditLock>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(Stream);
<file_sep>/src/containers/Wallet/components/WalletTabs/styles.js
import styled from 'styled-components';
import { NavLink, Input, InputGroupText } from 'reactstrap';
import { Button } from 'react-bootstrap';
import { Button as MaterialButton } from '@material-ui/core';
export const StyledNavLink = styled(NavLink)`
/* margin: 0px 20px; */
cursor: pointer;
span {
font-family: Poppins;
font-size: 18px;
font-weight: 400;
color: #564f4f;
}
&.active {
border-left: none;
background-color: #814c94 !important;
border-bottom-left-radius: 0px;
border-bottom-right-radius: 0px;
padding: 8px 40px;
span {
font-family: Poppins;
font-size: 18px;
font-weight: 400;
color: #ffffff;
}
}
`;
export const TabsContainer = styled.section`
height: 100%;
width: 100%;
`;
export const TabContainer = styled.section`
height: 100%;
width: 100%;
margin-top: 7px;
padding: 30px 0px;
border-top: solid 1px rgba(164, 161, 161, 0.35);
`;
export const DepositContent = styled.section`
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
width: 100%;
`;
export const DepositAddress = styled.section`
display: flex;
height: 40px;
width: 100%;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #fafcff;
border-radius: 6px;
justify-content: space-between;
align-items: center;
padding-left: 25px;
h6 {
font-family: Poppins;
font-size: 14px;
color: #a4a1a1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
`;
export const CopyButton = styled(MaterialButton)`
margin: 0px !important;
margin-left: 10px !important;
height: 100% !important;
border-radius: 6px !important;
background-color: #814c94 !important;
min-width: 100px !important;
text-transform: none !important;
box-shadow: none !important;
font-family: Poppins !important;
font-size: 14px !important;
font-weight: 500 !important;
color: #ffffff !important;
overflow: hidden !important;
`;
export const DepositButton = styled(CopyButton)`
margin-left: 0px !important;
height: 35px !important;
&:disabled {
opacity: 0.7;
}
`;
export const WithdrawContent = styled.section`
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
width: 100%;
padding-top: 50px;
`;
export const AddressInput = styled(Input)`
margin: 12px 0px;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #fafcff;
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
`;
export const AmountInput = styled(Input)`
margin: 12px 0px;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #fafcff;
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
`;
export const InputAddOn = styled(InputGroupText)`
margin: 12px 0px;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #fafcff;
height: 35px;
border-right: none;
span {
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
margin-right: 10px;
}
`;
export const WithdrawButton = styled(MaterialButton)`
margin: 42px 0px !important;
margin-bottom: 10px !important;
height: 50px !important;
width: 100% !important;
border-radius: 6px !important;
background-color: #814c94 !important;
text-transform: none !important;
box-shadow: none !important;
span {
font-family: Poppins !important;
font-size: 18px !important;
font-weight: 400 !important;
color: #ffffff !important;
}
`;
export const ErrorMessage = styled.section`
display: flex;
width: 100%;
justify-content: flex-start;
`;<file_sep>/src/containers/Layout/topbar/TopBarMoneyType.js
import React from 'react';
import { connect } from "react-redux";
import _ from 'lodash';
import styled from 'styled-components';
const MobileWrapper = styled.section`
@media (max-width: 716px) {
display: none !important;
}
`;
class TopBarMoneyType extends React.Component {
constructor(props) {
super(props);
}
render() {
const { profile } = this.props;
const { virtual } = profile.getApp().getParams();
return (
<MobileWrapper>
<button className="topbar__btn" onClick={this.toggle}>
<span className="topbar__virutal-btn-title" style={{height : 35}}>
<p>{ virtual === true ? 'Fake Money' : 'Real Money' }</p>
</span>
</button>
</MobileWrapper>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(TopBarMoneyType);
<file_sep>/src/containers/Applications/Customization/components/SubSections/index.js
import React, { Component } from 'react'
import EditLock from '../../../../Shared/EditLock.js';
import { connect } from "react-redux";
import _ from 'lodash';
import './styles.css';
import { Container, Header, Content, SubSectionsList, CreateNewSubSection } from './styles';
import { Select, Checkbox } from 'antd';
import SubSection from './SubSection';
import AddSection from './AddSection';
import EditSubSection from './EditSubSection';
import { PlusIcon } from 'mdi-react';
import styled from 'styled-components'
import { FormLabel } from '@material-ui/core';
const { Option } = Select;
const labelStyle = {
fontFamily: "Poppins",
fontSize: 16,
color: "#646777",
padding: 10
}
const Text = styled.span`
font-family: Poppins;
font-size: 13px;
`;
class SubSections extends Component {
constructor(props){
super(props);
this.state = {
isLoading: false,
locked: true,
open: false,
openNewSubSection: false,
editedSubSection: null,
language: 'EN'
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { language } = this.state;
await this.fetchLanguageData(language)
}
fetchLanguageData = async (language) => {
const { profile } = this.props;
const customization = await profile.getApp().getCustomization();
const { subSections } = customization;
const languages = subSections.languages.map(l => l.language);
const sections = subSections.languages.find(l => l.language.prefix === language);
const { ids, useStandardLanguage } = sections;
this.setState({
language,
languages,
useStandardLanguage,
subSections: !_.isEmpty(ids) ? ids : []
})
}
getLanguageImage = language => (
<div style={{ display: "flex", justifyContent: "flex-start", alignItems: "center" }}>
<img src={language.logo} alt={language.logo} style={{ height: 20, width: 20, margin: "0px 5px" }}/>
<Text>{language.name}</Text>
</div>
)
setSubSections = ({ newSubSections }) => {
this.setState({ subSections: newSubSections })
}
confirmChanges = async () => {
const { subSections, language, languages, useStandardLanguage } = this.state;
const { profile } = this.props;
const filteredSubsections = subSections.map(({_id, ...rest}) => rest);
this.setState({ isLoading: true })
const lang = languages.find(l => l.prefix === language)
await profile.getApp().editSubsectionsCustomization({ subSections: filteredSubsections, language: lang._id, useStandardLanguage });
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({ isLoading: false, locked: true })
}
unlockField = () => {
this.setState({ locked: false })
}
lockField = () => {
this.setState({ locked: true })
}
onChange = ({ type, value }) => {
this.setState({ [type]: value })
}
onChangeLanguage = async (value) => {
this.setState({
language: value ? value : ""
})
await this.fetchLanguageData(value)
}
handleOpen = ({ id }) => {
const { subSections } = this.state;
const editedSubSection = subSections.find(subSection => subSection._id === id);
this.setState({ editedSubSection: editedSubSection, open: true })
}
handleClose = () => {
this.setState({ editedSubSection: null, open: false, openNewSubSection: false })
}
handleOpenNewSubSection = () => {
this.setState({ openNewSubSection: true });
}
render() {
const { isLoading, locked, subSections, editedSubSection, open, openNewSubSection, languages, useStandardLanguage, language } = this.state;
return (
<Container>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
locked={locked}>
<FormLabel component="legend" style={labelStyle}>Language</FormLabel>
<div style={{ display: "flex", flexDirection: "row", justifyContent: "flex-start", alignItems: "center", margin: "5px 0px", marginTop: 20, padding: "0px 10px" }}>
<Select
defaultValue="EN"
style={{ minWidth: 130 }}
placeholder="Language"
onChange={this.onChangeLanguage}
disabled={isLoading || locked}
>
{ languages && languages.filter(language => language.isActivated).map(language => (
<Option key={language.prefix}>{this.getLanguageImage(language)}</Option>
))}
</Select>
{ language !== 'EN' && (
<Checkbox style={{ marginLeft: 10 }} disabled={isLoading || locked} checked={useStandardLanguage} onChange={() => this.setState({ useStandardLanguage: !useStandardLanguage})}>Use the English Language Setup</Checkbox>
)}
</div>
<br/>
<Header>
<h1>You can create a new subsection or edit existing ones</h1>
<br/>
<CreateNewSubSection onClick={() => this.handleOpenNewSubSection()} disabled={locked}>
<PlusIcon/> Create a new Subsection
</CreateNewSubSection>
</Header>
<Content>
<AddSection setSubSections={this.setSubSections} subSections={subSections} locked={locked} open={openNewSubSection} setClose={this.handleClose}/>
{ !_.isEmpty(subSections) && (
<>
<h1>Subsections</h1>
<EditSubSection subSections={subSections} setSubSections={this.setSubSections} subSection={editedSubSection} open={open} setClose={this.handleClose}/>
<SubSectionsList>
{ !_.isEmpty(subSections) && subSections.map(subSection => (
<SubSection setSubSections={this.setSubSections} subSection={subSection} subSections={subSections} setOpen={this.handleOpen} locked={locked}/>
))}
</SubSectionsList>
</>
)}
</Content>
</EditLock>
</Container>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(SubSections);
<file_sep>/src/containers/Landing/components/Footer.jsx
import React from 'react';
import { Col, Row, Container } from 'reactstrap';
import { Link } from 'react-router-dom';
const logo = `${process.env.PUBLIC_URL}/img/landing/logo.png`;
const Footer = () => (
<footer className="landing__footer">
<Container>
<Row>
<Col md={8} style={{textAlign : 'left'}}>
<p className="landing__menu-logo">
<img src={logo} className={'landing__logo'} alt="" />
</p>
<h5 style={{maxWidth : 300, marginTop : 50}}>BetProtocol App is SaaS Platform built on Top of @BetProtocol</h5>
</Col>
<Col lg={4}>
<h4 style={{marginBottom : 20}}>Find your Way</h4>
<a href={'https://medium.com/@betprotocol'} target={'__blank'}
>
<h5>Blog</h5>
</a>
<a href={'https://docs.betprotocol.com'} target={'__blank'}
>
<h5>Docs</h5>
</a>
<Link to={'/about-us'}
>
<h5>About Us</h5>
</Link>
</Col>
</Row>
</Container>
</footer>
);
export default Footer;
<file_sep>/src/containers/Modals/ModalUserAffiliateCustom.js
import React from 'react';
import { Col, Container, Row, Card, CardBody, Button } from 'reactstrap';
import { connect } from "react-redux";
import _ from 'lodash';
import ModalContainer from './ModalContainer';
import { PercentIcon, UserIcon } from 'mdi-react';
import TextInput from '../../shared/components/TextInput';
const defaultState = {
}
class ModalUserAffiliateCustom extends React.Component{
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { profile } = props;
}
setCustomAffiliate = async () => {
const { profile, modal } = this.props;
const { user } = modal.data;
const { affiliatePercentage } = this.state;
await profile.getApp().setCustomAffiliateStructureToUser({
user : user._id,
affiliatePercentage : parseFloat(affiliatePercentage/100)
});
await profile.update();
this.props.closeModal();
}
changeContent = (type, item) => {
this.setState({[type] : item});
}
canSubmit = () => {
return !((this.state.affiliatePercentage > 0) && (this.state.affiliatePercentage <= 100));
}
render = () => {
const { isActive, data } = this.props.modal;
const { user } = data;
const canSubmit = this.canSubmit();
if(!isActive){return null};
return (
<ModalContainer onClose={this.props.closeModal} title={'Set Custom User Affiliate'}>
<Container className="dashboard">
<h5 style={{marginTop : 20, marginBottom : 20}}>Change User Affiliate Percentage</h5>
<TextInput
icon={UserIcon}
name="user"
label="User Id"
type="text"
defaultValue={user._id}
disabled={true}
/>
<TextInput
icon={PercentIcon}
name="affiliatePercentage"
label="Percentage (%)"
type="text"
placeholder="10"
changeContent={this.changeContent}
/>
<div style={{marginTop : 20}}>
<Button onClick={this.setCustomAffiliate} disabled={canSubmit} color="primary" type="submit">
Submit
</Button>
</div>
</Container>
</ModalContainer>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
modal : state.modal
};
}
export default connect(mapStateToProps)(ModalUserAffiliateCustom);
<file_sep>/src/containers/Applications/ThirdParties/components/ChatTab/styles.js
import styled from 'styled-components';
import { Input } from 'reactstrap';
export const InputField = styled(Input)`
margin: 12px 0px;
border-radius: 6px;
border: solid 1.5px rgba(164, 161, 161, 0.35);
background-color: #fafcff;
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
`;
export const Actions = styled.section`
padding-top: 15px;
> p {
font-family: Poppins;
font-size: 13px;
}
`;
<file_sep>/src/containers/Wizards/CreateApp/components/WizardFormOne.jsx
import React, { PureComponent } from 'react';
import { Row, Col, CardBody, Card, FormGroup } from 'reactstrap';
import { reduxForm } from 'redux-form';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import { ApplicationIcon, DesktopMacDashboardIcon, CoinIcon, EthereumIcon } from 'mdi-react';
import TextInput from '../../../../shared/components/TextInput';
import TextLoop from 'react-text-loop';
import { BackgroundBox, VerticalSection, BetProtocolLogo, Container, CreateAppCard, CardHeader, CardContent, InputLabel, NameInput, DescriptionInput, Footer } from '../styles';
const Back = `${process.env.PUBLIC_URL}/img/dashboard/background-login.png`;
const loading = `${process.env.PUBLIC_URL}/img/loading.gif`;
const words = [
{ id: 0, text: 'BetProtocol' },
{ id: 1, text: 'Scalable' },
{ id: 2, text: 'Secure & Audited' },
{ id: 3, text: 'No Coding Required' },
];
const Description = (props) => {
const { wordList } = props;
return (
<TextLoop>
{wordList.map((word) => (
<span key={word.id}>{word.text}</span>
))}
</TextLoop>
);
};
class WizardFormOne extends PureComponent {
constructor() {
super();
this.state = {
showPassword: false,
virtual : false
};
}
changeContent = (type, item) => {
this.setState({[type] : item});
}
showPassword = (e) => {
e.preventDefault();
this.setState({
showPassword: !this.state.showPassword,
});
};
selectMoneyType = () => {
const { virtual } = this.state;
this.setState({ virtual : !virtual });
};
onChangeName = value => {
if (value) {
this.setState({
name: value
})
} else {
this.setState({
name: null
})
}
}
onChangeDescription = value => {
if (value) {
this.setState({
description: value
})
} else {
this.setState({
description: null
})
}
}
createApp = async () => {
try{
this.setState({isLoading : true});
let res = await this.props.profile.createApp({
...this.state,
name : this.state.name,
description : this.state.description,
// TO DO : Create Metadata JSON Add on Inputs (Logo and Other Data)
metadataJSON : JSON.stringify({}),
// TO DO : Create MarketType Setup
marketType : 0
});
this.props.history.push('/home')
}catch(err){
console.log(err);
this.props.showNotification(err.message);
}
}
render() {
const { virtual } = this.state;
const { handleSubmit } = this.props;
return (
<>
<BackgroundBox>
<VerticalSection>
<ul>
<BetProtocolLogo />
<Description wordList={words} />
</ul>
<Container>
<CreateAppCard>
<CardHeader />
<CardContent>
<h1>Create your First Application</h1>
<FormGroup>
<InputLabel for="name">App</InputLabel>
<NameInput
label="App"
name="name"
type="text"
// defaultValue={this.state.username}
onChange={(e) => this.onChangeName(e.target.value)}
/>
</FormGroup>
<FormGroup>
<InputLabel for="description">Description</InputLabel>
<DescriptionInput
label="Description"
name="description"
type="text"
// defaultValue={this.state.username}
onChange={(e) => this.onChangeDescription(e.target.value)}
/>
</FormGroup>
<div style={{width : "100%", display : "inline-flex", justifyContent: "center" }}>
<div style={{ width : 130, textAlign : "center" }}>
<Card style={{paddingBottom : 10, cursor : "pointer"}} onClick={() => this.selectMoneyType('real')}>
<CardBody style={{padding : 10, backgroundColor: !virtual ? "rgba(137, 71, 152, 0.1)" : "#fff", border: !virtual ? "1px solid #894798" : "1px solid #bebdbd"}}>
<span style={{ display : "block", paddingBottom : 6}}><EthereumIcon color="grey"/></span>
<span>
<p className="text-small">
Real Money
</p>
</span>
</CardBody>
</Card>
</div>
<div style={{ width : 130, marginLeft : 30, textAlign : "center" }}>
<Card style={{paddingBottom : 10, cursor : "pointer"}} onClick={() => this.selectMoneyType('fake')}>
<CardBody style={{padding : 10, backgroundColor: virtual ? "rgba(137, 71, 152, 0.1)" : "#fff", border: virtual ? "1px solid #894798" : "1px solid #bebdbd"}}>
<span style={{ display : "block", paddingBottom : 6}}><CoinIcon color="grey"/></span>
<span>
<p className="text-small">
Fake Money
</p>
</span>
</CardBody>
</Card>
</div>
</div>
<div className="account__btns" style={{ justifyContent: "center" }}>
<button disabled={this.state.isLoading} style={{maxWidth : 350, marginTop :30}} onClick={() => this.createApp()} c className="btn btn-primary account__btn">
{this.state.isLoading ? <img src={loading} style={{width : 20}}/> : 'Register App'}
</button>
</div>
</CardContent>
</CreateAppCard>
<Footer>
<span>
<b>@BetProtocol</b> Technology is a SaaS Platform that provides
infrastructure for Gaming Applications
</span>
</Footer>
</Container>
</VerticalSection>
</BackgroundBox>
</>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default compose(reduxForm({
form: 'wizard', // <------ same form name
}), connect(mapStateToProps))(WizardFormOne);
<file_sep>/src/shared/components/tabs/styles.js
import styled from 'styled-components';
export const MobileIcon = styled.section`
height: 24px;
width: 24px;
`;
export const MobileTitle = styled.span`
font-family: Poppins;
font-size: 11px !important;
color: #a4a1a1;
`;
export const Icon = styled.section`
padding-top: 3px;
height: 24px;
width: 24px;
`;
export const Title = styled.span`
margin-left: 7px;
padding-top: 3px;
font-family: Poppins;
font-size: 14px;
color: #a4a1a1;
`;
export const DesktopWrapper = styled.section`
@media (max-width: 1137px) {
.desktop {
display: none !important;
}
}
`;
export const MobileWrapper = styled.section`
@media (max-width: 1137px) {
.mobile {
display: block !important;
}
}
`;
<file_sep>/src/containers/Applications/ThirdParties/index.js
import React, { Component } from 'react'
import { ChatTab, EmailTab, GameProviders, KYC, PaymentTab, Analytics } from './components';
import TabsContainer from '../../../shared/components/tabs/Tabs';
import { Chat, Email, Hand, Wallet, Settings } from '../../../components/Icons';
export default class ThirdPartiesContainer extends Component {
render() {
return (
<div>
<TabsContainer
items={
[
{
title : 'Chat',
container : <ChatTab />,
icon : <Chat/>
},
{
title : 'E-mail',
container : <EmailTab />,
icon : <Email/>
},
{
title : 'Game Providers',
container : <GameProviders />,
icon : <Hand/>
},
{
title : 'KYC',
container : <KYC />,
icon : <Chat/>
},
{
title : 'Payment',
container : <PaymentTab />,
icon : <Wallet/>
},
{
title : 'Analytics',
container : <Analytics/>,
icon : <Settings/>
}
]
}
/>
</div>
)
}
}
<file_sep>/src/containers/Transactions/components/deposit/codes.js
const depositStatus = {
'not-confirmed' : 'grey-box',
'confirmed' : 'green-box',
}
const depositStatusArray = ['Not Confirmed', 'Confirmed']
export default depositStatus;
export {
depositStatusArray
}<file_sep>/src/containers/Applications/LanguagesPage/Language/index.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { CardBody, Col, Row, Button } from 'reactstrap';
import { AddIcon } from 'mdi-react';
class LanguageStoreContainer extends PureComponent {
constructor() {
super();
this.state = {
isLoading: false
};
}
handleAddLanguage = async () => {
const { addLanguage, language } = this.props;
this.setState({ isLoading: true })
await addLanguage(language.prefix);
this.setState({ isLoading: false })
}
render() {
const { language, isAdded } = this.props;
const { isLoading } = this.state;
if(!language){return null}
const { name, logo, prefix } = language;
return (
<CardBody className="dashboard__card-widget" style={{ minHeight: 120, minWidth: 241, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none", padding: 20 }}>
<div style={{ display: "flex", flexDirection: "row", justifyContent: "space-between" }}>
<img className='application__game__image'
style={{display: 'block', width: '60px', margin: "0px 10px" }}
src={logo}/>
<div className="dashboard__visitors-chart text-left" style={{ margin: "0px 10px" }}>
<p className="dashboard__visitors-chart-title text-left" style={{fontSize : 20}}> {name} </p>
<p className="text-left secondary-text"> {prefix} </p>
</div>
</div>
<hr/>
<Button disabled={isLoading || isAdded} style={{margin : 0, marginTop : 10}} className="icon" onClick={this.handleAddLanguage} >
{
isLoading ?
"Adding"
: isAdded ?
"Added"
:
<p><AddIcon className="deposit-icon"/> Add </p>
}
</Button>
</CardBody>
);
}
}
export default LanguageStoreContainer;
<file_sep>/src/containers/Account/ResetPassword/index.jsx
import React from 'react';
import { Link } from 'react-router-dom';
import ResetPasswordForm from './components/ResetPasswordForm';
import { Col, Row } from 'reactstrap';
import { BasicNotification } from '../../../shared/components/Notification';
import NotificationSystem from 'rc-notification';
import { BackgroundBox, VerticalSection, Container, BetProtocolLogo, Card, CardHeader, CardContent } from './styles';
import TextLoop from 'react-text-loop';
const Back = `${process.env.PUBLIC_URL}/img/dashboard/background-login.png`;
let notification = null;
const showNotification = (message) => {
notification.notice({
content: <BasicNotification
title="There is a problem with your Request"
message={message}
/>,
duration: 5,
closable: true,
style: { top: 0, left: 'calc(100vw - 100%)' },
className: 'right-up',
});
};
const words = [
{ id: 0, text: 'BetProtocol' },
{ id: 1, text: 'Scalable' },
{ id: 2, text: 'Secure & Audited' },
{ id: 3, text: 'No Coding Required' },
];
const Description = (props) => {
const { wordList } = props;
return (
<TextLoop>
{wordList.map((word) => (
<span key={word.id}>{word.text}</span>
))}
</TextLoop>
);
};
class ResetPassword extends React.Component{
constructor(props){super(props)}
componentDidMount() {
NotificationSystem.newInstance({}, n => notification = n);
}
componentWillUnmount() {
notification.destroy();
}
showNotification = (message) => {
showNotification(message)
}
render = () => {
return (
<>
<BackgroundBox>
<VerticalSection>
<ul>
<BetProtocolLogo />
<Description wordList={words} />
</ul>
<Container>
<Card>
<CardHeader />
<CardContent>
<h1>Reset your Password</h1>
<ResetPasswordForm showNotification={this.showNotification} handleSubmit={(e) => e.preventDefault()} {...this.props} onSubmit={false} />
<div className="account__have-account">
<p>Back to <Link to="/login">Login</Link></p>
</div>
</CardContent>
</Card>
</Container>
</VerticalSection>
</BackgroundBox>
</>
)
}
};
export default ResetPassword;
<file_sep>/src/containers/Applications/Customization/components/Background.js
import React, { Component } from 'react'
import EditLock from '../../../Shared/EditLock.js';
import { connect } from "react-redux";
import Dropzone from 'react-dropzone';
import { Col, Row, Card, CardBody } from 'reactstrap';
import 'react-alice-carousel/lib/alice-carousel.css';
const image2base64 = require('image-to-base64');
const upload = `${process.env.PUBLIC_URL}/img/dashboard/upload.png`;
const trash = `${process.env.PUBLIC_URL}/img/dashboard/clear.png`;
const defaultState = {
backgroundItem: null,
isLoading: false,
locks : {
background : true
}
}
class Background extends Component {
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props);
}
onBackgroundAddedFile = async (files) => {
const file = files[0];
let blob = await image2base64(file.preview) // you can also to use url
this.setState({backgroundItem : blob});
}
projectData = async (props) => {
const { background } = props.profile.getApp().getCustomization();
this.setState({...this.state,
backgroundItem : background ? background.id : null
})
}
renderBackgroundAddImage = () => {
return(
<div style={{ marginBottom: 20 }}>
<Dropzone
style={{ height: "100%", width: "100%", borderWidth: 2, borderolor: "#666666", borderStyle: "dashed", borderRadius: 5, padding: 10 }}
onDrop={this.onBackgroundAddedFile}
ref={(el) => (this.dropzoneRef = el)}
disabled={this.state.locks.background}>
<img src={upload} className='image-info' style={{ marginTop: 50 }}/>
<p className='text-center' style={{ marginBottom: 20 }}> Drop the Background here</p>
</Dropzone>
</div>
)
}
removeImage = (src, field) => {
switch(field){
case 'background' : {
this.setState({backgroundItem : ""})
break;
};
}
}
renderImage = (src, field) => {
if(!src.includes("https")){
src = "data:image;base64," + src;
}
return (
<div style={{paddingBottom : 20, height : 220, overflow : 'hidden', margin : 'auto'}}>
<button disabled={[field] == 'background' ? this.state.locks.background : true} onClick={() => this.removeImage(src, field)}
style={{right : 20, top : 6}}
className='carousel-trash button-hover'>
<img src={trash} style={{width : 15, height : 15}}/>
</button>
<img src={src} onDragStart={this.handleOnDragStart}/>
</div>
)
}
onChange = ({type, value}) => {
this.setState({...this.state, [type] : value })
}
unlockField = ({field}) => {
this.setState({...this.state, locks : {...this.state.locks, [field] : false }})
}
lockField = ({field}) => {
this.setState({...this.state, locks : {...this.state.locks, [field] : true }})
}
confirmChanges = async ({field}) => {
var { profile } = this.props;
const { backgroundItem } = this.state;
this.setState({...this.state, isLoading : true});
switch(field){
case 'background' : {
const postData = {
background :backgroundItem
}
await profile.getApp().editBackgroundCustomization(postData);
break;
};
}
this.setState({...this.state, isLoading : false, locks : {...this.state.locks, [field] : true }});
this.projectData(this.props);
}
handleOnDragStart = (e) => e.preventDefault()
render() {
const { isLoading, backgroundItem } = this.state;
return (
<Card>
<CardBody style={{ margin: 10, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<div style={{ border: '1px solid rgba(0, 0, 0, 0.2)', backgroundColor: "white", borderRadius: 8, marginBottom : 30, padding : 30, maxWidth: 293 }}>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'background'}
locked={this.state.locks.background}>
<div style={{paddingBottom : 20}}>
<h5 className={"bold-text dashboard__total-stat"}>Background</h5>
<h6>Upload your background image</h6>
</div>
<div>
{
backgroundItem ?
/* Background is Set */
this.renderImage(backgroundItem, 'background')
:
/* Background is not Set */
this.renderBackgroundAddImage()
}
</div>
</EditLock>
</div>
</CardBody>
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(Background);
<file_sep>/src/containers/Applications/AddOnPage/index.js
import React from 'react'
import TabsContainer from '../../../shared/components/tabs/Tabs';
import AddOnStorePageContainer from './AddOnStore';
import AddOnContainer from './AddOnContainer';
import { AddOn, Cash } from '../../../components/Icons';
export default class AddOnsContainer extends React.PureComponent {
render() {
return (
<>
<TabsContainer
items={
[
{
title : 'Add-Ons Store',
container : <AddOnStorePageContainer />,
icon : <Cash/>
},
{
title : 'My Add-Ons',
container : <AddOnContainer />,
icon : <AddOn/>
}
]
}
/>
</>
)
}
}<file_sep>/src/containers/Applications/ThirdParties/components/index.js
import ChatTab from './ChatTab';
import EmailTab from './EmailTab';
import GameProviders from './GameProvidersTab'
import KYC from './KYC'
import PaymentTab from './PaymentTab'
import Analytics from './Analytics'
export {
ChatTab,
EmailTab,
GameProviders,
KYC,
PaymentTab,
Analytics
}<file_sep>/src/containers/Bets/components/BetsProfile.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col } from 'reactstrap';
import { BarChart, Bar, Cell, ResponsiveContainer } from 'recharts';
import TrendingUpIcon from 'mdi-react/TrendingUpIcon';
import AnimationNumber from '../../UI/Typography/components/AnimationNumber';
import Numbers from '../../../services/numbers';
import _ from 'lodash';
import Skeleton from '@material-ui/lab/Skeleton';
import { compose } from 'lodash/fp';
import { translate } from 'react-i18next';
import { connect } from "react-redux";
class BetsProfile extends PureComponent {
constructor() {
super();
this.state = {
bets: [],
periodicity: 'all',
betsAmount: 0
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { periodicity, profile } = props;
const data = await profile.getApp().getSummaryData('bets');
if (!_.isEmpty(data.data)) {
const bets = await this.getAllBets(data.data);
this.setState({
bets: bets,
periodicity: periodicity,
betsAmount: bets.amount
})
} else {
this.setState({
bets: [],
periodicity: periodicity,
betsAmount: 0
})
}
}
handleClick = (index) => {
this.setState({
activeIndex: index,
});
};
getAllBets(data) {
let allBets = {};
const betsOnPeriodicity = data.map(index => index.bets);
const concatBets = [].concat(...betsOnPeriodicity);
const betsAmont = concatBets.length;
const combined = [...concatBets].reduce((a, obj) => {
Object.entries(obj).forEach(([key, val]) => {
a[key] = (a[key] || 0) + val;
});
return a;
});
allBets.avg_bet = combined.avg_bet / betsAmont;
allBets.avg_bet_return = combined.avg_bet_return / betsAmont;
allBets.won = combined.won;
allBets.amount = combined.amount;
allBets.percentage_won = allBets.amount === 0 ? 0 : allBets.won / allBets.amount;
return allBets;
}
render() {
const { isLoading } = this.props;
const { betsAmount, periodicity } = this.state;
return (
<Col md={12} xl={12} lg={12} xs={12}>
<Card>
<CardBody className="dashboard__card-widget" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
{isLoading ? (
<Skeleton variant="rect" height={29} style={{ marginTop: 10, marginBottom: 10 }}/>
) : (
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-number-second" style={
{color : betsAmount >= 0 ? '#76d076' : '#646777'}
}>
<AnimationNumber decimals={0} number={betsAmount}/>
</p>
</div>)}
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-title"> Total Bets <span> {periodicity} </span></p>
</div>
</CardBody>
</Card>
</Col>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile,
periodicity: state.periodicity,
currency: state.currency,
isLoading: state.isLoading
};
}
export default compose(
translate('common'),
connect(mapStateToProps)
)(BetsProfile);<file_sep>/src/containers/Applications/Customization/components/SubSections/SubSection/index.js
import React, { Component } from 'react'
import _ from 'lodash';
import '../styles.css';
import { Container, SectionGrid, Title, Text, Image, BackgroundImage, Location, EditSubSection as EditSubSectionButton, RemoveSubSection, Yes, Cancel, Actions } from './styles';
import { TrashCanOutlineIcon, EditIcon } from 'mdi-react';
const positionsEnum = Object.freeze({
0: "RightImage",
1: "LeftImage",
2: "BottomImage",
3: "TopImage"
});
const locationsEnum = Object.freeze({
0: "Before the banners",
1: "Before the games list",
2: "Before the data lists",
3: "Before the footer",
4: "After the footer"
})
class SubSection extends Component {
constructor(props){
super(props);
this.state = {
removing: false,
open: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { subSection, subSections } = props;
this.setState({
subSection: !_.isEmpty(subSection) ? subSection : [],
subSections: !_.isEmpty(subSections) ? subSections : []
});
}
setTabs = ({ newTabs }) => {
this.setState({
tabs: newTabs
})
}
renderImage = (src) => {
if(!src.includes("https")){
src = "data:image;base64," + src;
}
return src;
}
onChange = ({ type, value }) => {
this.setState({ [type]: value })
}
removeSubSection = ({ _id }) => {
this.setState({ removing: true })
}
cancelRemoveSubSection = ({ _id }) => {
this.setState({
removing: false
})
}
handleRemoveSubSection = ({ id }) => {
const { subSections } = this.state;
const { setSubSections } = this.props;
const index = subSections.findIndex(subSection => subSection._id === id);
const newSubSections = [...subSections];
newSubSections[index] = {};
this.setState({ removing: false })
setSubSections({
newSubSections: newSubSections.filter(subSections => !_.isEmpty(subSections))
})
}
handleEditSubSection = () => {
const { setOpen } = this.props;
const { _id } = this.state.subSection;
setOpen({ id: _id });
}
render() {
const { subSection, removing } = this.state;
const { locked } = this.props;
if (!subSection) return null;
const { _id, title, text, image_url, background_url, background_color, position, location } = subSection;
return (
<Container>
<Location>{`Location: ${locationsEnum[location]} `}</Location>
<SectionGrid className={positionsEnum[position]} backgroundColor={background_color}>
<Title>
<h1>{title}</h1>
</Title>
<Text>
<p>{text}</p>
</Text>
{ background_url && (
<BackgroundImage>
<img style={{ width: "100%", height: "100%", objectFit: "cover" }} alt="Background" src={this.renderImage(background_url)} />
</BackgroundImage>
)}
{ image_url && (
<Image>
<img style={{ width: "100%", height: "100%", objectFit: "cover" }} alt="Image" src={this.renderImage(image_url)}/>
</Image>
)}
</SectionGrid>
{ !removing ?
<Actions>
<EditSubSectionButton disabled={locked} onClick={() => this.handleEditSubSection()}>
<EditIcon style={{ margin: "0px 5px" }}/> Edit
</EditSubSectionButton>
<RemoveSubSection disabled={locked} onClick={() => this.removeSubSection({ id: _id })}>
<TrashCanOutlineIcon style={{ margin: "0px 5px" }}/> Remove
</RemoveSubSection>
</Actions>
:
<Actions>
<Yes disabled={locked} onClick={() => this.handleRemoveSubSection({ id: _id })}>
Yes
</Yes>
<Cancel disabled={locked} onClick={() => this.cancelRemoveSubSection({ id: _id })}>
Cancel
</Cancel>
</Actions> }
</Container>
)
}
}
export default SubSection;
<file_sep>/src/containers/Users/UserPage/components/BetsTable/index.js
import React from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import moment from 'moment';
import { Container, Header, TableContainer, Filters, Export, Text, BoldText, WonResult } from './styles';
import { Table, Spin, DatePicker, Select, Input } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import { CSVLink } from "react-csv";
import { Button as MaterialButton } from "@material-ui/core";
import { TableIcon, JsonIcon } from 'mdi-react';
import BetContainer from '../../../../../shared/components/BetContainer';
import { export2JSON } from '../../../../../utils/export2JSON';
const { RangePicker } = DatePicker;
const { Option } = Select;
class BetsTable extends React.Component {
constructor(props){
super(props)
this.state = {
data: [],
games: [],
currencies: [],
pagination: {
current: 1,
pageSize: 10,
},
isLoading: false,
game: null,
currency: null,
begin_at: null,
end_at: null,
username: null,
bet: null
};
}
componentDidMount() {
this.projectData(this.props);
}
componentWillReceiveProps(props) {
this.projectData(props);
}
projectData = async (props) => {
const { profile, user } = props;
const { App } = profile;
this.setState({
isLoading: true
})
const response = await App.getUserBets({
user: user._id,
filters: {
size: 100,
isJackpot: false,
tag: 'cassino'
}
});
const bets = response.data.message.list;
const { currencies, games } = App.params;
this.setState({
data: _.isEmpty(bets) ? [] : this.prepareTableData(bets, currencies, games),
columns: this.prepareTableColumns(bets),
currencies: currencies,
games: games,
isLoading: false
})
}
prepareTableData = (bets, currencies, games) => {
if (_.isEmpty(bets) || _.isEmpty(currencies) || _.isEmpty(games)) return [];
return bets.map(bet => {
const currency = currencies.find(currency => currency._id === bet.currency);
const game = games.find(game => game._id === bet.game);
return {
key: bet._id,
_id: bet._id,
user: bet.user,
currency: currency,
app: bet.app,
game: game,
ticker: currency.ticker,
isWon: bet.isWon,
winAmount: bet.winAmount,
betAmount: bet.betAmount,
nonce: bet.nonce,
fee: bet.fee,
creation_timestamp: bet.timestamp,
clientSeed: bet.clientSeed,
serverSeed: bet.serverSeed,
serverHashedSeed: bet.serverHashedSeed
}
})
}
getBetContainer = data => {
const bet = {...data, creation_timestamp: moment(data.creation_timestamp).format('lll')};
return (
<BetContainer bet={bet} id={bet.currency._id}>
<BoldText>{bet._id}</BoldText>
</BetContainer>
)
}
getUserImage = user => (
<div style={{ display: "flex", justifyContent: "flex-start", alignItems: "center" }}>
<img src={`https://avatars.dicebear.com/v2/avataaars/${user._id}.svg`} alt={user.username} style={{ height: 30, width: 30, margin: "0px 10px" }}/>
<Text>{user.username}</Text>
</div>
)
getCurrencyImage = currency => (
<div style={{ display: "flex", justifyContent: "flex-start", alignItems: "center" }}>
<img src={currency.image} alt={currency.name} style={{ height: 25, width: 25, margin: "0px 10px" }}/>
<Text>{currency.name}</Text>
</div>
)
getGameImage = game => (
<div style={{ display: "flex", justifyContent: "flex-start", alignItems: "center" }}>
<img src={game.image_url} alt={game.name} style={{ height: 40, width: 50, margin: "0px 10px" }}/>
<Text>{game.name}</Text>
</div>
)
getFormatedAmount = ({ value, currency, colorized }) => (
<div style={{ display: "flex", justifyContent: "flex-start", alignItems: "center" }}>
{ colorized
? <Text style={{ color: value > 0 ? '#63c965' : '#e6536e' }}>{`${value.toFixed(6)} ${currency.ticker}`}</Text>
: <Text>{`${value.toFixed(6)} ${currency.ticker}`}</Text> }
</div>
)
prepareTableColumns = bets => {
if (_.isEmpty(bets)) return [];
return [
{ title: 'Id', dataIndex: '_id', key: '_id', render: (_id, data, _length) => this.getBetContainer(data) },
{ title: 'User', dataIndex: 'user', key: 'user', render: user => this.getUserImage(user) },
{ title: 'Currency', dataIndex: 'currency', key: 'currency', render: currency => this.getCurrencyImage(currency) },
{ title: 'Game', dataIndex: 'game', key: 'game', render: game => this.getGameImage(game) },
{ title: 'Won', dataIndex: 'isWon', key: 'isWon', render: isWon => <WonResult isWon={isWon}>{isWon ? 'Yes' : 'No'}</WonResult> },
{ title: 'Bet Amount', dataIndex: 'betAmount', key: 'betAmount', render: (betAmount, currency) => this.getFormatedAmount({ value: betAmount, currency: currency, colorized: false }) },
{ title: 'Win Amount', dataIndex: 'winAmount', key: 'winAmount', render: (winAmount, currency) => this.getFormatedAmount({ value: winAmount, currency: currency, colorized: true }) },
{ title: 'Fee', dataIndex: 'fee', key: 'fee', render: (fee, currency) => this.getFormatedAmount({ value: fee, currency: currency, colorized: false }) },
{ title: 'Created At', dataIndex: 'creation_timestamp', key: 'creation_timestamp', render: creation_timestamp => <Text>{ moment(creation_timestamp).format("lll") }</Text> }
]
}
handleTableChange = async (pagination, extra) => {
const { current, pageSize } = pagination;
const { currentDataSource } = extra;
this.setState({
pagination: pagination
})
const dataSize = _.size(currentDataSource);
if (parseInt(dataSize / pageSize) === current) {
await this.fetchMoreData(dataSize);
}
}
onChangeDate = (_value, dateString) => {
const [begin_at, end_at] = dateString;
this.setState({
begin_at: begin_at,
end_at: end_at
}, () => {
this.fetchFilteredData()
})
}
onChangeGame = value => {
this.setState({
game: value ? value : null
}, () => {
this.fetchFilteredData()
})
}
onChangeCurrency = value => {
this.setState({
currency: value ? value : null
}, () => {
this.fetchFilteredData()
})
}
onChangeBetId = event => {
this.setState({
bet: event.target.value ? event.target.value : null
}, () => {
this.fetchFilteredData()
})
}
onChangeUsername = event => {
this.setState({
username: event.target.value ? event.target.value : null
}, () => {
this.fetchFilteredData()
})
}
fetchMoreData = async (dataSize) => {
const { profile, user } = this.props;
const { App } = profile;
const { data, game, currency, begin_at, end_at, username, bet } = this.state;
this.setState({
isLoading: true
})
const response = await App.getUserBets({
user: user._id,
filters: {
size: 100,
offset: dataSize,
isJackpot: false,
tag: 'cassino',
game: game,
currency: currency,
bet: bet,
begin_at: begin_at,
end_at: end_at
}
});
const bets = response.data.message.list;
const { currencies, games } = App.params;
this.setState({
data: _.isEmpty(bets) ? data : _.concat(data, this.prepareTableData(bets, currencies, games)),
isLoading: false
})
}
fetchFilteredData = _.debounce(async () => {
const { game, currency, begin_at, end_at, username, bet } = this.state;
const { profile, user } = this.props;
const { App } = profile;
this.setState({
isLoading: true
})
const response = await App.getUserBets({
user: user._id,
filters: {
size: 100,
offset: 0,
isJackpot: false,
tag: 'cassino',
game: game,
currency: currency,
bet: bet,
begin_at: begin_at,
end_at: end_at
}
});
const bets = response.data.message.list;
const { currencies, games } = App.params;
this.setState({
data: _.isEmpty(bets) ? [] : this.prepareTableData(bets, currencies, games),
isLoading: false
})
}, 700);
render() {
const { data, columns, pagination, isLoading, games, currencies } = this.state;
const headers = [
{ label: "Id", key: "_id" },
{ label: "User", key: "user" },
{ label: "Currency", key: "currency" },
{ label: "Game", key: "game" },
{ label: "Won", key: "isWon" },
{ label: "Win Amount", key: "winAmount" },
{ label: "Bet Amount", key: "betAmount" },
{ label: "Fee", key: "fee" },
{ label: "Created At", key: "createdAt" }
];
let csvData = [{}];
let jsonData = [];
if (!_.isEmpty(data)) {
csvData = data.map(row => ({...row, currency: row.currency.name,
user: row.user._id,
isWon: row.isWon ? 'Yes' : 'No',
game: row.game._id,
createdAt: moment(row.creation_timestamp).format("lll")}));
jsonData = csvData.map(row => _.pick(row, ['_id', 'user', 'currency', 'game', 'isWon', 'winAmount', 'betAmount', 'fee', 'creation_timestamp']));
}
return (
<>
<Container>
<Header>
<Filters>
<RangePicker
style={{ margin: 5 }}
onChange={this.onChangeDate}
// onOk={this.onOk}
ranges={{
'Today': [moment().utc(), moment().utc()],
'Yesterday': [moment().subtract(1, 'days').utc(), moment().subtract(1, 'days').utc()],
'Last 7 days': [moment().subtract(7, 'days').utc(), moment().utc()],
'Last month': [moment().subtract(1, 'month').utc(), moment().utc()]
}}/>
<Input style={{ width: 150, height: 32, margin: 5 }} placeholder="Bet Id" onChange={event => this.onChangeBetId(event)}/>
{/* <Input style={{ width: 150, height: 32, margin: 5 }} placeholder="Username or E-mail" onChange={event => this.onChangeUsername(event)}/> */}
<Select
// mode="multiple"
style={{ minWidth: 150, margin: 5 }}
placeholder="Game"
onChange={this.onChangeGame}
>
<Option key={''}>All</Option>
{ games.map(game => (
<Option key={game._id}>{game.name}</Option>
))}
</Select>
<Select
// mode="multiple"
style={{ minWidth: 150, margin: 5 }}
placeholder="Currency"
onChange={this.onChangeCurrency}
>
<Option key={''}>All</Option>
{ currencies.map(currency => (
<Option key={currency._id}>{this.getCurrencyImage(currency)}</Option>
))}
</Select>
</Filters>
<Export>
<CSVLink data={csvData} filename={"bets.csv"} headers={headers}>
<MaterialButton variant="contained" size="small" style={{ textTransform: "none", backgroundColor: "#008000", color: "#ffffff", boxShadow: "none", margin: 10}}>
<TableIcon style={{marginRight: 7}}/> CSV
</MaterialButton>
</CSVLink>
<MaterialButton onClick={() => export2JSON(jsonData, "bets")} variant="contained" size="small" style={{ textTransform: "none", boxShadow: "none", margin: 10}}>
<JsonIcon style={{marginRight: 7}}/> JSON
</MaterialButton>
</Export>
</Header>
<TableContainer>
<Table
dataSource={data}
columns={columns}
size="small"
loading={{ spinning: isLoading, indicator: <Spin indicator={<LoadingOutlined style={{ fontSize: 30, color: '#894798' }} spin />}/> }}
pagination={pagination}
onChange={(pagination, _filters, _sorter, extra) => this.handleTableChange(pagination, extra)}/>
</TableContainer>
</Container>
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(BetsTable);<file_sep>/src/containers/Applications/EsportsPage/components/Skeletons/LastGamesSkeleton/styles.js
import styled from 'styled-components';
export const Container = styled.div`
display: flex;
flex-direction: column;
padding: 10px;
margin: 10px;
width: 400px;
height: 180px;
background-color: #fafcff;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
`;
export const Header = styled.section`
display: flex;
justify-content: flex-start;
align-items: center;
height: 20px;
padding: 10px 20px;
span {
text-transform: uppercase;
font-family: Poppins;
font-size: 14px;
color: #5f6e85
}
`;
export const TeamResult = styled.div`
display: grid;
grid-template-areas:
'team result';
grid-template-columns: 50% 50%;
grid-template-rows: 55px;
margin: 5px 0px;
`;
export const Team = styled.section`
grid-area: team;
display: grid;
grid-template-areas:
'icon name';
grid-template-columns: 30% 70%;
grid-template-rows: auto;
`;
export const TeamIcon = styled.section`
grid-area: icon;
display: flex;
justify-content: center;
align-items: center;
img {
/* padding: 0px 8px; */
height: 22px;
width: 22px;
}
`;
export const TeamName = styled.section`
grid-area: name;
display: flex;
justify-content: flex-start;
align-items: center;
span {
padding: 0px 8px;
font-family: Poppins;
font-size: 13px;
}
`;
export const MatchResultList = styled.section`
grid-area: result;
display: flex;
justify-content: center;
align-items: center;
`;
export const MatchResult = styled.div`
display: flex;
justify-content: center;
align-items: center;
margin: 3px;
padding: 0px;
`;<file_sep>/src/containers/Applications/components/HostingLink/index.js
import React from 'react';
import { Card } from 'reactstrap';
import { connect } from "react-redux";
import styled from 'styled-components';
import { Button } from '@material-ui/core';
const ApplicationLink = styled.section`
display: flex;
height: 40px;
max-width: 784px;
background-color: #fafcff;
border: solid 1px rgba(164, 161, 161, 0.35);
/* box-shadow: 0 2px 15px 0 rgba(0, 0, 0, 0.05); */
border-radius: 6px;
justify-content: space-between;
align-items: center;
padding-left: 25px;
h6 {
font-family: Poppins;
font-size: 14px;
color: #a4a1a1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
`;
const OpenAppButton = styled(Button)`
margin: 0px !important;
padding: 6px !important;
margin-left: 10px !important;
height: 100% !important;
border-radius: 6px !important;
background-color: #814c94 !important;
min-width: 100px !important;
box-shadow: none !important;
text-transform: none !important;
font-family: Poppins !important;
font-size: 14px !important;
font-weight: 500 !important;
color: #ffffff !important;
overflow: hidden !important;
`;
class HostingLink extends React.PureComponent{
render = () => {
let link = this.props.profile.getApp().getAppLink();
return (
<Card style={{ padding: 0 }}>
<ApplicationLink>
<h6> {link} </h6>
<OpenAppButton variant="contained" href={link} target={'__blank'}>
Open App
</OpenAppButton>
</ApplicationLink>
{/* <Row>
<Col sd={10}>
</Col>
<Col sd={2}>
<a className={'button-hover'} href={link} target={'__blank'} >
Open App
</a>
</Col>
</Row>
</div> */}
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(HostingLink);
<file_sep>/src/esports/services/matches.js
import { API_URL, config, addHeaders } from '../api/config';
import store from '../../containers/App/store';
import { setMatchesData, addMatchesData } from '../../redux/actions/matchesActions';
export const getSeriesMatches = async ({ params, headers, isPagination=false }) => {
try {
const res = await fetch(API_URL + `/api/get/matches/series`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
const response = await res.json();
if (response.data.message) {
isPagination ?
store.dispatch(addMatchesData(response.data.message))
: store.dispatch(setMatchesData(response.data.message));
}
} catch(err) {
throw err;
}
}
export const getBookedSeriesMatches = async ({ params, headers, isPagination=false }) => {
try {
const res = await fetch(API_URL + `/api/get/booked/matches/series`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
const response = await res.json();
if (response.data.message) {
isPagination ?
store.dispatch(addMatchesData(response.data.message.map(match => ({...match, booked: true}))))
: store.dispatch(setMatchesData(response.data.message.map(match => ({...match, booked: true}))));
}
} catch(err) {
throw err;
}
}
export const getMatchesAll = async ({ params, headers, isPagination=false }) => {
try {
const res = await fetch(API_URL + `/api/get/matches/all`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
const response = await res.json();
if (response.data.message) {
isPagination ?
store.dispatch(addMatchesData(response.data.message))
: store.dispatch(setMatchesData(response.data.message));
}
} catch(err) {
throw err;
}
}
export const getBookedMatches = async ({ params, headers, isPagination=false }) => {
try {
const res = await fetch(API_URL + `/api/get/booked/matches/all`, {
method : 'POST',
headers : addHeaders(config, headers),
body : JSON.stringify(params)
});
const response = await res.json();
if (response.data.message) {
isPagination ?
store.dispatch(addMatchesData(response.data.message.map(match => ({...match, booked: true}))))
: store.dispatch(setMatchesData(response.data.message.map(match => ({...match, booked: true}))));
}
} catch(err) {
throw err;
}
}<file_sep>/src/containers/Wallet/components/paths/FeesWidget.js
import React from 'react';
import { Col, Container, Row } from 'reactstrap';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import CurrencyInfo from './CurrencyInfo';
import { LockWrapper } from '../../../../shared/components/LockWrapper';
import { TabContainer } from '../WalletTabs/styles';
import { Paragraph } from '../LiquidityWalletContainer/styles';
class FeesWidget extends React.Component{
render = () => {
const { profile } = this.props;
const { currency } = this.props.data.wallet;
const isSuperAdmin = profile.User.permission.super_admin;
return (
<TabContainer>
<Paragraph style={{ marginBottom: 15 }}>Choose the fees to deposit and withdraw of your wallet</Paragraph>
<Row>
<LockWrapper hasPermission={isSuperAdmin}>
<CurrencyInfo profile={profile} data={currency}/>
</LockWrapper>
</Row>
</TabContainer>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
wallet: (state.wallet.currency) ? state.wallet : state.profile.getApp().getSummaryData('walletSimple').data[0]
};
}
FeesWidget.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(FeesWidget);<file_sep>/src/services/api.js
import config from "../api/config";
class API{
getETHPriceAPI = async () => {
return new Promise( (resolve) => {
fetch('https://api.coinmarketcap.com/v1/ticker/ethereum', {
headers : config.headers,
mode : 'cors'
})
.then(response => resolve(response.json()))
.catch(error => console.log(error))
})
}
getEthereumPrice = async (eth_quantity) => {
let response = await this.getETHPriceAPI();
return parseFloat(eth_quantity)*parseInt(response[0].price_usd);
}
}
let APISingleton = new API();
export default APISingleton;<file_sep>/src/containers/Applications/components/Wizard/WizardForm.jsx
import React, { PureComponent } from 'react';
import { Col, Card, Row } from 'reactstrap';
import PropTypes from 'prop-types';
import WizardFormOne from './WizardFormOne';
import WizardFormThree from './WizardFormThree';
import { connect } from "react-redux";
import { compose } from 'lodash/fp';
import NotificationSystem from 'rc-notification';
import { BasicNotification } from '../../../../shared/components/Notification';
import WizardFormTwo from './WizardFormTwo';
import { fromServicesToCodes } from '../../../../controllers/services/services';
import _ from 'lodash';
let notification = null;
Object.filter = (obj, predicate) =>
Object.keys(obj)
.filter( key => predicate(obj[key]) )
.reduce( (res, key) => (res[key] = obj[key], res)
, {} );
const showNotification = (message) => {
notification.notice({
content:
<BasicNotification
title="Your App was Not Created"
message={message}
/>,
duration: 5,
closable: true,
style: { top: 0, left: 'calc(100vw - 100%)' },
className: 'right-up',
});
};
const DEPLOYMENT_CONFIG = {
none : {
isSet : true,
message : 'Ready for Deployment'
},
deployment : {
isSet : false,
message : 'Smart-Contract Deployment being done...'
},
authorizeAddress : {
isSet : false,
message : 'Authorize Address to Control the App'
},
authorizeCroupier : {
isSet : false,
message : 'Authorize Address to Monitor the Owner'
},
choooseServices : {
isSet : false,
message : 'Alowing your Services..'
},
deployingApplication : {
isSet : false,
message : 'Deploying and Hosting your App..'
},
}
const defaultProps = {
page: 1,
blockchains : [],
currencies : [],
authorizedAddress : '0x',
progress : 0,
deploymentConfig : DEPLOYMENT_CONFIG,
deploymentState : DEPLOYMENT_CONFIG['none'].message
}
class WizardForm extends PureComponent {
static propTypes = {
onSubmit: PropTypes.func.isRequired,
};
constructor() {
super();
this.state = defaultProps;
}
componentDidMount() {
NotificationSystem.newInstance({}, n => notification = n);
this.projectData();
}
componentWillUnmount() {
notification.destroy();
}
showNotification = (message) => {
showNotification(message)
}
projectData = async () => {
const { profile } = this.props;
let app = profile.getApp();
let res = await app.getEcosystemVariables();
const { addresses, blockchains, currencies } = res.data.message;
this.setState({...this.state,
blockchains,
authorizedAddress : addresses[0].address,
currencies
})
}
sendServices = async ({services}) => {
try{
let res = await this.props.profile.addServices(services);
let{
status,
message
} = res.data;
if(status != 200){throw res.data}
}catch(err){
// TO DO : Show notification Error
}
}
deployAndHostApplication = async () => {
try{
let res = await this.props.profile.getApp().deployAndHostApplication();
let{
status,
message
} = res.data;
if(status != 200){throw res.data}
}catch(err){
// TO DO : Show notification Error
}
}
getProgress(args){
return (Object.keys(Object.filter(args, v => v.isSet)).length)/(Object.keys(args).length)*100;
}
getUpdateStateForProgress = ({deploymentConfig, state}) => {
let new_deploymentConfig = {
...deploymentConfig, [state] : {
...deploymentConfig[state],
isSet : true,
}
}
let progress = this.getProgress(new_deploymentConfig);
this.setState({...this.state,
deploymentState : DEPLOYMENT_CONFIG[state].message,
deploymentConfig : new_deploymentConfig,
progress
});
return new_deploymentConfig;
}
deployApp = async () => {
try{
const { profile, appCreation } = this.props;
this.setState({...this.state, isLoading : true});
var { authorizedAddress, deploymentConfig } = this.state;
let user = !_.isEmpty(profile) ? profile : null ;
const { services, blockchain, currency } = appCreation;
/* 1 - Deploy the Smart-Contract */
let state = 'deployment';
deploymentConfig = this.getUpdateStateForProgress({state, deploymentConfig});
let params = {
tokenAddress : currency.address,
decimals : currency.decimals,
authorizedAddress,
currencyTicker : currency.ticker,
blockchainTicker : blockchain.ticker
}
/* 2 - Authorize Address of Owner */
state = 'authorizeAddress';
deploymentConfig = this.getUpdateStateForProgress({state, deploymentConfig});
await profile.authorizeAddress({address : params.ownerAddress, platformParams : params});
/* 3 - Authorize Croupiers on the Platform */
state = 'authorizeCroupier';
deploymentConfig = this.getUpdateStateForProgress({state, deploymentConfig});
await profile.authorizeCroupier({address : authorizedAddress, platformParams : params});
/* 4 - Update Service on the Platform */
state = 'choooseServices';
deploymentConfig = this.getUpdateStateForProgress({state, deploymentConfig})
await this.sendServices({services});
/* 5 - Deploying and Hosting Application */
state = 'deployingApplication';
deploymentConfig = this.getUpdateStateForProgress({state, deploymentConfig})
await this.deployAndHostApplication();
/* Update all */
await profile.getData();
this.setState({...this.state, isLoading : false});
}catch(err){
console.log(err)
this.setState({...this.state, isLoading : false});
}
}
nextPage = () => {
this.setState({...this.state, page: this.state.page + 1 });
};
previousPage = () => {
this.setState({...this.state, page: this.state.page - 1 });
};
render() {
const { onSubmit } = this.props;
const { page, isLoading } = this.state;
return (
<Row>
<Col md={12} lg={12}>
<Card>
<div className="wizard">
<div className="wizard__steps">
<div className={`wizard__step${page === 1 ? ' wizard__step--active' : ''}`}><p>Choose Integrations</p></div>
<div className={`wizard__step${page === 2 ? ' wizard__step--active' : ''}`}><p>Setup Platform</p></div>
<div className={`wizard__step${page === 3 ? ' wizard__step--active' : ''}`}><p>Deploy</p></div>
</div>
<div className="wizard__form-wrapper">
{page === 1 && <WizardFormOne showNotification={this.showNotification}
onSubmit={this.nextPage}
handleSubmit={(e) => e.preventDefault()} {...this.props}
/>}
{page === 2 && <WizardFormTwo
showNotification={this.showNotification}
previousPage={this.previousPage}
currencies={this.state.currencies}
blockchains={this.state.blockchains}
handleSubmit={(e) => e.preventDefault()} {...this.props}
onSubmit={this.nextPage}
/>}
{page === 3 && <WizardFormThree
isLoading={isLoading}
deployApp={this.deployApp}
authorizedAddress={this.state.authorizedAddress}
addresses={this.state.addresses}
blockchains={this.state.blockchains}
deploymentState={this.state.deploymentState}
progress={this.state.progress}
currencies={this.state.currencies}
showNotification={this.showNotification}
previousPage={this.previousPage}
sendServices={this.sendServices}
handleSubmit={(e) => e.preventDefault()} {...this.props} />}
</div>
</div>
</Card>
</Col>
</Row>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile,
appCreation : state.appCreation
};
}
export default compose(connect(mapStateToProps))(WizardForm);
<file_sep>/src/containers/Applications/ThirdParties/components/ChatTab/index.js
import React from 'react'
import { Row, Card, CardBody } from 'reactstrap';
import Stream from './Stream';
import Crisp from './Crisp';
class ChatTab extends React.PureComponent {
render() {
return (
<Card>
<CardBody style={{ margin: 10, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<Stream/>
<br/>
<hr/>
<br/>
<Crisp/>
</CardBody>
</Card>
)
}
}
export default ChatTab;
<file_sep>/src/containers/Applications/Customization/components/Fonts.js
import React, { Component } from 'react'
import EditLock from '../../../Shared/EditLock.js';
import TextInput from '../../../../shared/components/TextInput';
import { Col, Row, Card, CardBody } from 'reactstrap';
import { connect } from "react-redux";
import saveFontImg from '../../../../shared/img/fonts/saveGoogleFont.gif';
const defaultState = {
url: '',
name: '',
locked: true,
isLoading: false
}
class Fonts extends Component {
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { locked } = this.state;
if (locked) {
const typography = props.profile.getApp().getTypography();
const { name, url } = typography;
this.setState({...this.state,
url,
name
});
}
}
onChange = ({type, value}) => {
this.setState({...this.state, [type] : value })
}
unlockField = () => {
this.setState({...this.state, locked : false})
}
lockField = () => {
this.setState({...this.state, locked : true})
}
confirmChanges = async () => {
var { profile } = this.props;
const { url, name } = this.state;
this.setState({...this.state, isLoading : true});
const typography = { url, name }
await profile.getApp().editTypography(typography);
this.setState({...this.state, isLoading : false, locked: true})
this.projectData(this.props);
}
render() {
const { isLoading, locked, url, name } = this.state;
return (
<Card>
<CardBody style={{ margin: 10, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<Row>
<Col md={12} style={{ padding: 0 }}>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'fontTab'}
locked={locked}
>
<div style={{marginBottom: 40}}>
<p className="text-small text-left" style={{marginTop : 0}}><a href="https://fonts.google.com" target="_blank">https://fonts.google.com</a></p>
<p className="text-left secondary-text" style={{marginTop: 20, marginBottom: 30}}> Choose a Google Font to install </p>
<img style={{ width: "100%"}} src={saveFontImg}/>
</div>
<TextInput
label={'Google Font URL'}
name={'url'}
type={'url'}
value={url}
defaultValue={url}
disabled={locked}
changeContent={(type, value) => this.onChange({type, value})}
/>
<TextInput
label={'Font Name'}
name={'name'}
type={'name'}
value={name}
defaultValue={name}
disabled={locked}
changeContent={(type, value) => this.onChange({type, value})}
/>
</EditLock>
</Col>
</Row>
</CardBody>
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(Fonts);
<file_sep>/src/containers/App/MainRoute.jsx
import React from 'react';
import 'bootstrap/dist/css/bootstrap.css';
import '../../scss/app.scss';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import Layout from '../Layout';
import { Route, Link } from 'react-router-dom';
import Account from '../../controllers/Account';
import routesStructure from './routes';
import _ from 'lodash';
import { WalletContainer } from '../Wallet';
import WalletWidget from '../Wallet/components/paths/WalletWidget';
import UsersContainer from '../Users';
import StatsContainer from '../Stats';
import AffiliatesContainer from '../Affiliates';
import Developers from '../Developers';
import TransactionsContainer from '../Transactions';
import BetsContainer from '../Bets';
import GamePage from '../Applications/GamePage';
import UserPage from '../Users/UserPage';
import SettingsContainer from '../Settings';
import DefaultDashboard from '../Dashboards/Default/index';
import Applications from '../Applications';
const loadingBetprotocol = `${process.env.PUBLIC_URL}/img/loading-betprotocol.gif`;
class MainRoute extends React.Component {
constructor() {
super();
this.state = {
loaded : false,
loading : true
};
}
asyncCalls = async () => {
try{
await this.loginAccount();
this.enterWebsite();
}catch(err){
console.log(err);
this.props.history.push('/login')
}
}
enterWebsite = () => {
setTimeout(() => this.setState({ loaded: true }), 300);
this.setState({ loading: false });
}
async loginAccount(){
let Acc = this.props.profile;
//If there is no Account
if(_.isEmpty(Acc)){ Acc = new Account() };
try{
await Acc.auth();
}catch(err){
throw err;
}
}
getName(object, path){
return object.filter(obj => {
return obj.path === path
})[0]
}
getrouteHistoryObjects = (object, full_path) => {
let paths = full_path.split("/").filter(el => el !== "");
let objectPaths = [];
for(var i = 0; i < paths.length; i++){
let search_object = i < 1 ? object : objectPaths[i-1].children;
objectPaths.push(this.getName(search_object, "/" + paths[i]));
}
return objectPaths;
}
componentDidMount() {
this.asyncCalls();
}
Main = (props) => {
let { profile } = this.props;
let routeHistory = this.getrouteHistoryObjects(routesStructure, props.location.pathname);
if(!profile.hasAppStats()) { return null; }
return (
<>
<Layout />
<div className="container__wrap">
{routeHistory.map( (routePath, i) => {
let last = (i === routeHistory.length - 1);
if(i === 0){
return <p className={`container__routing__info ${last ? 'routing__current' : null}`} key={i}> <Link to={routePath.path}> {routePath.name} </Link> </p>
}else{
return (
<div className={''}>
<p className={`container__routing__info__dot ${last ? 'routing__current' : null}`}> > </p>
<p className={`container__routing__info__dot ${last ? 'routing__current' : null}`}> {routePath.name}</p>
</div>
)
}
})}
<Route path={'/home'} component={DefaultDashboard}/>
<Route path={'/users'} component={wrappedUserRoutes}/>
<Route path={'/application'} component={wrappedApplicationRoutes}/>
<Route path={'/developers'} component={Developers}/>
<Route path={'/transactions'} component={TransactionsContainer}/>
<Route path={'/bets'} component={BetsContainer}/>
<Route path={'/stats'} component={StatsContainer}/>
<Route path={'/wallet'} component={wrappedWalletRoutes}/>
<Route path={'/settings'} component={SettingsContainer}/>
<Route path={'/account-settings'} component={SettingsContainer}/>
<Route path={'/affiliates'} component={AffiliatesContainer}/>
</div>
</>
)
}
render() {
const { loaded, loading } = this.state;
return (
<div>
{!loaded &&
<div className={`load${loading ? '' : ' loaded'}`}>
<div class="load__icon-wrap">
<img src={loadingBetprotocol} alt="loading..."/>
</div>
</div>
}
{loaded ?
<div>
{this.Main(this.props)}
</div>
: null
}
</div>
)};
}
const wrappedWalletRoutes = (props) => {
return(
<div>
<Route exact path="/wallet" component={WalletContainer} />
<Route path="/wallet/currency" component={WalletWidget} />
</div>
)
}
const wrappedUserRoutes = (props) => {
return(
<div>
<Route exact path="/users" component={UsersContainer} />
<Route path="/users/user" component={UserPage} />
</div>
)
}
const wrappedApplicationRoutes = (props) => {
return(
<div>
<Route exact path="/application" component={Applications} />
<Route path="/application/game" component={GamePage} />
</div>
)
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default compose(
connect(mapStateToProps)
)(MainRoute);<file_sep>/src/containers/Applications/CurrenciesPage/CurrenciesContainer.js
/* eslint-disable react/no-array-index-key */
import React from 'react';
import { connect } from "react-redux";
import CurrencyInfo from './CurrencyInfo';
import VirtualCurrencyInfo from './VirtualCurrencyInfo';
import { LockWrapper } from '../../../shared/components/LockWrapper';
import { Grid } from '@material-ui/core';
const image = `${process.env.PUBLIC_URL}/img/dashboard/empty.png`;
class CurrenciesContainer extends React.PureComponent {
isAdded = (AddOn) => {
const { App } = this.props.profile;
const appAddOns = App.params.addOn;
return !!Object.keys(appAddOns).find(k => AddOn.toLowerCase().includes(k.toLowerCase()));
}
render() {
const { profile } = this.props;
const { App } = profile;
const { currencies } = App.params;
const isAppWithFakeMoney = profile.App.params.virtual;
const hasInitialBalanceAddOn = this.isAdded('Initial Balance');
const realCurrencies = currencies.filter(currency => currency.virtual === false);
const virtualCurrencies = currencies.filter(currency => currency.virtual === true);
const isSuperAdmin = profile.User.permission.super_admin;
return (
((realCurrencies.length > 0 && hasInitialBalanceAddOn)||virtualCurrencies.length > 0 ) ?
<Grid container direction="row" justify="flex-start" alignItems="flex-start">
{virtualCurrencies.map(currency => (
<Grid item style={{ margin: "0px 15px" }}>
<LockWrapper hasPermission={isSuperAdmin}>
<VirtualCurrencyInfo data={currency} {...this.props}/>
</LockWrapper>
</Grid>
))}
{!isAppWithFakeMoney ? (
realCurrencies.map(currency => (
<Grid item style={{ margin: "0px 15px" }}>
<LockWrapper hasPermission={isSuperAdmin}>
<CurrencyInfo data={currency} {...this.props}/>
</LockWrapper>
</Grid>
))
) : null}
</Grid>
:
<div>
<h4>You have no Initial Balance Add-On enabled currently</h4>
<img src={image} alt="" style={{ width: "30%", marginTop: 20 }}/>
</div>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(CurrenciesContainer);
<file_sep>/src/containers/Applications/EsportsPage/components/StatsPage/index.js
import React from 'react';
import { connect } from 'react-redux';
import { StatsContainer } from './styles';
import _ from 'lodash';
import LastGames from './components/LastGames';
import SideBySide from './components/SideBySide';
import Teams from './components/Teams';
class StatsPage extends React.Component {
constructor(props) {
super(props);
this.state = {
match: {},
isLoading: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { match, profile } = props;
const { opponents, videogame } = match;
const [teamOne, teamTwo] = opponents.map(opponent => opponent.opponent);
const { App } = profile;
this.setState({ isLoading: true });
const teamOneData = await App.getTeamStats({ slug: videogame.slug, team_id: teamOne.id });
const teamTwoData = await App.getTeamStats({ slug: videogame.slug, team_id: teamTwo.id });
this.setState({ isLoading: false });
if (!_.isEmpty(match)) {
this.setState({
match: match,
opponents: opponents,
teamOne: teamOneData.data.message ? teamOneData.data.message : {},
teamTwo: teamTwoData.data.message ? teamTwoData.data.message : {},
})
}
}
render() {
const { teamOne, teamTwo, isLoading } = this.state;
// if (_.isEmpty(teamOne) || _.isEmpty(teamTwo)) return null;
return (
<>
<StatsContainer>
<Teams teamOne={teamOne} teamTwo={teamTwo} isLoading={isLoading}/>
<SideBySide teamOne={teamOne} teamTwo={teamTwo} isLoading={isLoading}/>
<LastGames teamOne={teamOne} teamTwo={teamTwo} isLoading={isLoading}/>
</StatsContainer>
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(StatsPage);<file_sep>/src/models/Crypto.js
var SHA512 = require("crypto-js/hmac-sha512");
var randomHex = require('randomhex');
class Crypto{
constructor(){
// TO DO : Finalize Client See e Server Seed Setup
}
generateSeed(length = 32){
return randomHex(length);
}
hashSeed(seed){
return SHA512(seed);
}
generateNonce(){
return Math.floor(Math.random() * 10000000000000000) + 1;
}
generateRandomResult(server_seed, client_seed){
let randomHex = SHA512(server_seed, client_seed);
return randomHex;
}
hexToInt = (randomHex) => {
// TO DO : If this number is over 999,999 than the next 5 characters (ex : aad5e) would be used. But in our case it's 697,969 so this will be used. Now you only have to apply a modulus of 10^4 and divide it by 100
let hexString = randomHex.toString().substring(0, 5);
return parseInt(hexString, 16)%(10000)/100;
}
}
let CryptographySingleton = new Crypto();
export default CryptographySingleton;<file_sep>/src/containers/Applications/EsportsPage/components/Match/index.js
import React from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import { MatchLink, MatchContainer, Indicator, MatchInfo, TeamsInfo, ActionArea, Footer, TeamOne,
Result, ResultValue, TeamTwo, SerieName, VideoGameIcon, VideogameInfo, DateInfo, Time, Date as DateSpan,
BookButton, RemoveBookButton, Status, Tag, Odds, OddValue, Draw } from './styles';
import Avatar from 'react-avatar';
import moment from 'moment';
import videogames from '../Enums/videogames';
import matchStatusEnum from '../Enums/status';
import { updateMatchData } from '../../../../../redux/actions/matchesActions';
import store from '../../../../App/store';
const loading = `${process.env.PUBLIC_URL}/img/loading.gif`;
const results = Object.freeze({
won: { text: "W", color: "#7bd389" },
lost: { text: "L", color: "#ed5565" },
draw: { text: "D", color: "#b0b0b0" }
})
class Match extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {},
isLoading: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { data, series } = props;
if (!_.isEmpty(data)) {
this.setState({
data: data
})
}
if (!_.isEmpty(series)) {
this.setState({
series: series
})
}
}
getTeamScore = id => {
const { results } = this.state.data;
const result = results.find(result => result.team_id === id);
return result ? result.score : null;
}
getLeagueName = id => {
const { serie, league } = this.state.data;
return `${league.name} ${serie.full_name}`;
}
getTwoWayOdds = odds => {
if (odds.winnerTwoWay) {
if (_.isEmpty(odds.winnerTwoWay)) {
return [];
} else {
return [parseFloat(odds.winnerTwoWay[0].odd), null, parseFloat(odds.winnerTwoWay[1].odd)];
}
} else {
switch (true) {
case _.isArray(odds):
const odd = odds.find(odd => odd.template === 'winner-2-way');
if (odd !== undefined) {
const { selections } = odd;
return [1/(selections[0].probability), null, 1/(selections[1].probability)];
} else {
return [];
}
case !_.isEmpty(odds.markets):
const market = odds.markets.find(market => market.template === 'winner-2-way');
if (market !== undefined && market.selections !== undefined) {
return [1/(market.selections[0].probability), null, 1/(market.selections[1].probability)];
} else {
return [];
}
default:
return [];
}
}
}
getThreeWayOdds = odds => {
if (odds.winnerThreeWay) {
if (_.isEmpty(odds.winnerThreeWay)) {
return [];
} else {
return [parseFloat(odds.winnerThreeWay[0].odd), parseFloat(odds.winnerThreeWay[1].odd), parseFloat(odds.winnerThreeWay[2].odd)];
}
} else {
switch (true) {
case _.isArray(odds):
const odd = odds.find(odd => odd.template === 'winner-3-way');
if (odd !== undefined) {
const { selections } = odd;
return [1/(selections[0].probability), 1/(selections[1].probability), 1/(selections[2].probability)];
} else {
return [];
}
case !_.isEmpty(odds.markets):
const market = odds.markets.find(market => market.template === 'winner-3-way');
if (market !== undefined && market.selections !== undefined) {
return [1/(market.selections[0].probability), 1/(market.selections[1].probability), 1/(market.selections[2].probability)];
} else {
return [];
}
default:
return [];
}
}
}
getResultColor = ({ id, winner_id }) => {
switch (true) {
case winner_id === null:
return results.draw.color
case id === winner_id:
return results.won.color
case id !== winner_id:
return results.lost.color
default:
break;
}
}
setMatchBooked = async e => {
e.stopPropagation();
const { profile } = this.props;
const { data } = this.state;
const { id } = data;
const { App } = profile;
this.setState({ isLoading: true });
const response = await App.setBookedMatch({ match_external_id: id });
if (response.data.status === 200) {
// Modify it later!!!
let matchUpdated = await App.getSpecificMatch({ match_id: id });
if (matchUpdated.data.message) {
// Modify it later!!!
matchUpdated.data.message.booked = true;
store.dispatch(updateMatchData(matchUpdated.data.message));
this.setState({
data: matchUpdated.data.message,
isLoading: false
})
}
}
this.setState({ isLoading: false });
};
removeMatchBooked = async e => {
e.stopPropagation();
const { profile } = this.props;
const { data } = this.state;
const { id } = data;
const { App } = profile;
this.setState({ isLoading: true });
const response = await App.removeBookedMatch({ match_external_id: id });
if (response.data.status === 200) {
const matchUpdated = await App.getSpecificMatch({ match_id: id });
if (matchUpdated.data.message) {
store.dispatch(updateMatchData(matchUpdated.data.message));
this.setState({
data: matchUpdated.data.message,
isLoading: false
})
}
}
this.setState({ isLoading: false });
};
render() {
const { data, isLoading } = this.state;
const { opponents, results, videogame, scheduled_at, booked, status, odds, winner_id } = data;
const { setMatchPage } = this.props;
if (_.isEmpty(data) || _.isEmpty(opponents)) return null;
const leagueName = this.getLeagueName(data.league_id);
const [teamOne, teamTwo] = opponents.map(opponent => opponent.opponent);
const [scoreTeamOne, scoreTeamTwo] = results ? opponents.map(opponent => this.getTeamScore(opponent.opponent.id)) : [null, null];
const winnerTwoWayOdds = this.getTwoWayOdds(odds);
const winnerThreeWayOdds = this.getThreeWayOdds(odds);
const [teamOneOdd, tieOdd, teamTwoOdd] = !_.isEmpty(winnerThreeWayOdds) ? winnerThreeWayOdds : !_.isEmpty(winnerTwoWayOdds) ? winnerTwoWayOdds : [undefined, undefined, undefined];
if (_.isEmpty(teamOne) || _.isEmpty(teamTwo)) return null;
const time = new Date(scheduled_at).toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric' });
const date = moment(new Date(scheduled_at)).format('MM/DD');
const matchStatus = status ? matchStatusEnum[status] : null;
const isMatchFinished = !_.isEmpty(status) && ['settled', 'finished'].includes(status);
const isPreMatch = !_.isEmpty(status) && ['pre_match'].includes(status);
const hasResults = !_.isEmpty(results) && ['live', 'settled', 'finished'].includes(status);
const isTie = scoreTeamOne !== null && scoreTeamTwo !== null && scoreTeamOne === scoreTeamTwo && isMatchFinished;
const hasOdds = teamOneOdd !== undefined && teamTwoOdd !== undefined;
return (
<>
<MatchLink
disabled={isLoading}
disableRipple
onClick={() => setMatchPage(data)}
>
<MatchContainer>
<Indicator color={videogames[videogame.id].indicatorColor}/>
<MatchInfo>
<VideogameInfo>
<VideoGameIcon>
{ videogames[videogame.id].icon }
</VideoGameIcon>
</VideogameInfo>
<DateInfo>
<Time>
{ time }
</Time>
<DateSpan>
{ date }
</DateSpan>
</DateInfo>
<Status>
{ matchStatus && <Tag backgroundColor={matchStatus.backgroundColor} textColor={matchStatus.textColor}>
{ matchStatus.text }
</Tag> }
</Status>
</MatchInfo>
<TeamsInfo>
<TeamOne>
<span>{teamOne.name}</span>
{ teamOne.image_url ? <img src={teamOne.image_url} alt={teamOne.name}/> : <Avatar name={teamOne.name} size="25" round={true}/> }
</TeamOne>
{ teamOneOdd && teamTwoOdd && !isMatchFinished ? (
<Odds>
<OddValue>
{ teamOneOdd.toFixed(2) }
</OddValue>
{ tieOdd ? <OddValue>{ tieOdd.toFixed(2) }</OddValue> : <span>vs</span> }
<OddValue>
{ teamTwoOdd.toFixed(2) }
</OddValue>
</Odds>
) : (
<Result>
<ResultValue color={this.getResultColor({ id: teamOne.id, winner_id: winner_id })}>
{ scoreTeamOne !== null && hasResults ? scoreTeamOne : '-' }
</ResultValue>
{ isTie ? <Draw>Tie</Draw> : <span>vs</span> }
<ResultValue color={this.getResultColor({ id: teamTwo.id, winner_id: winner_id })}>
{ scoreTeamTwo !== null && hasResults ? scoreTeamTwo : '-' }
</ResultValue>
</Result>
)}
<TeamTwo>
{ teamTwo.image_url ? <img src={teamTwo.image_url} alt={teamTwo.name}/> : <Avatar name={teamTwo.name} size="25" round={true}/> }
<span>{teamTwo.name}</span>
</TeamTwo>
</TeamsInfo>
<ActionArea>
{ booked ? (
<RemoveBookButton variant="contained" size="small" onClick={this.removeMatchBooked} disabled={isLoading}>
{ isLoading ? <img src={loading} alt="Loading..." className={'loading_gif'}/> : "Remove" }
</RemoveBookButton>
) : (
isPreMatch && hasOdds && (
<BookButton variant="contained" size="small" onClick={this.setMatchBooked} disabled={isLoading}>
{ isLoading ? <img src={loading} alt="Loading..." className={'loading_gif'}/> : "Book" }
</BookButton>)
)}
</ActionArea>
<Footer>
<SerieName>
{leagueName ? leagueName : ""}
</SerieName>
</Footer>
</MatchContainer>
</MatchLink>
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(Match);<file_sep>/src/containers/Modals/AbstractModal.js
import React from 'react';
import { connect } from "react-redux";
import _ from 'lodash';
import store from '../App/store';
import ModalUserAffiliateCustom from './ModalUserAffiliateCustom';
import { MODAL_TYPES, closeModal } from '../../redux/actions/modal';
const defaultState = {
auth_2fa : {},
SW : {}
}
class AbstractModal extends React.Component{
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
async closeModal(success=false){
await store.dispatch(closeModal({success}));
}
projectData = async (props) => {
const { profile } = props;
}
render = () => {
const { isActive, MODAL_TYPE } = this.props.modal;
if(!isActive){return null};
switch(MODAL_TYPE){
case MODAL_TYPES.USER_AFFILIATE_EDIT : {
return <ModalUserAffiliateCustom closeModal={this.closeModal} />
};
}
}
}
function mapStateToProps(state){
return {
profile: state.profile,
modal : state.modal
};
}
export default connect(mapStateToProps)(AbstractModal);
<file_sep>/src/containers/Modals/ModalAddCurrencyWallet.js
import React from 'react';
import { connect } from "react-redux";
import _ from 'lodash';
import ModalContainer from './ModalContainer';
import store from '../App/store';
import { addCurrencyWallet } from '../../redux/actions/addCurrencyWallet';
import { setCurrencyView } from '../../redux/actions/currencyReducer';
import { AddCurrencyButton, AddressInput, InputAddOn, WalletIDInput } from './styles';
import { InputGroup, InputGroupAddon } from 'reactstrap';
const loading = `${process.env.PUBLIC_URL}/img/loading.gif`;
class ModalAddCurrencyWallet extends React.Component{
constructor(props){
super(props);
this.state = {
isLoading: false,
address: "",
subWalletId: ""
};
}
handleCloseModal = () => {
store.dispatch(addCurrencyWallet({ isActive: false }));
}
handleChangeAddress = value => {
this.setState({ address: value || "" });
}
handleChangeWalletID = value => {
this.setState({ subWalletId: value || "" });
}
handleAddCurrency = async () => {
const { currency, profile } = this.props;
const { address, subWalletId } = this.state;
try {
this.setState({ isLoading: true });
await profile.getApp().addCurrencyWallet({ currency, address, subWalletId });
await profile.getApp().updateAppInfoAsync();
await profile.update();
store.dispatch(addCurrencyWallet({ isActive: false }));
this.setState({ isLoading: false });
}catch (err){
this.setState({ isLoading: false });
await store.dispatch(setCurrencyView({}));
store.dispatch(addCurrencyWallet({ isActive: false }));
}
}
render = () => {
const { addCurrencyWallet } = this.props;
const { isActive } = addCurrencyWallet;
if(!isActive){return null};
const { currency } = this.props;
const { name, image } = currency;
const { isLoading, address, subWalletId } = this.state;
return (
<ModalContainer overflowY="scroll" onClose={() => this.handleCloseModal()} >
<h4 style={{ margin: '20px 0px' }}>{`Please add your ${name} credentials`}</h4>
<InputGroup>
<InputGroupAddon addonType="prepend">
<InputAddOn>
<img className='application__game__image' style={{ display: 'block', marginLeft: 0, marginRight: 0, height: 20, width: 20 }} src={image} alt={name}/>
</InputAddOn>
</InputGroupAddon>
<AddressInput name="address" placeholder={`Your ${name} address`} onChange={(e) => this.handleChangeAddress(e.target.value)}/>
</InputGroup>
<WalletIDInput name="walletId" placeholder="Wallet ID" onChange={(e) => this.handleChangeWalletID(e.target.value)}/>
<AddCurrencyButton variant="contained" disabled={ isLoading || _.isEmpty(address) || _.isEmpty(subWalletId) } onClick={() => this.handleAddCurrency()}>
{ isLoading ? <img src={loading} className={'loading_gif'} alt="Loading.."/> : <span>{`Add ${name}`}</span> }
</AddCurrencyButton>
</ModalContainer>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
addCurrencyWallet : state.addCurrencyWallet,
currency: state.currency
};
}
export default connect(mapStateToProps)(ModalAddCurrencyWallet);
<file_sep>/src/containers/Wallet/store/Currency.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Button } from 'reactstrap';
import { AddIcon } from 'mdi-react';
import { CurrencyStoreCard, CardHeader, CardContent } from './styles';
import { connect } from 'react-redux';
import { Grid } from '@material-ui/core';
import Skeleton from '@material-ui/lab/Skeleton';
class CurrencyStoreContainer extends PureComponent {
constructor() {
super();
this.state = {
isLoading: false
};
}
handleAddCurrency = async () => {
const { currency, profile } = this.props;
this.setState({ isLoading: true });
await profile.getApp().addCurrencyWallet({ currency });
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({ isLoading: false });
}
render() {
const { currency, isAdded, loading } = this.props;
const { isLoading } = this.state;
if(!currency){return null}
const { image, ticker } = currency;
return (
<CurrencyStoreCard>
{ loading ? (
<>
<Grid container direction='row' spacing={1}>
<Grid item xs={3}>
<Skeleton variant="circle" width={60} height={60} style={{ marginBottom: 30, marginLeft: 'auto', marginRight: 0 }}/>
</Grid>
</Grid>
<Skeleton variant="rect" width="30%" height={30} style={{ marginBottom: 20 }}/>
<Skeleton variant="rect" width="40%" height={30} style={{ marginBottom: 10 }}/>
</>
) : (
<>
<CardHeader>
<img className='application__game__image' style={{display: 'block', marginLeft: `0px`, height: 60, width: 60 }} src={image}/>
</CardHeader>
<CardContent>
<h1>{ticker}</h1>
</CardContent>
<div className="flex-container">
<div style={{flexGrow: 5}} >
<Button disabled={isLoading || isAdded} style={{margin : 0, marginTop : 10}} className="icon" onClick={() => this.handleAddCurrency()} >
{
isLoading ?
"Adding"
: isAdded ?
"Added"
:
<p><AddIcon className="deposit-icon"/> Add </p>
}
</Button>
</div>
<div style={{flexGrow: 5}} >
</div>
</div>
</>
)}
</CurrencyStoreCard>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile,
loading: state.isLoading
};
}
export default connect(mapStateToProps)(CurrencyStoreContainer);
<file_sep>/src/controllers/ERC20Contract.js
import {
ierc20
} from "./interfaces";
import Contract from "../models/Contract";
import Numbers from "../services/numbers";
import { HeadphonesBluetoothIcon } from "mdi-react";
let self;
const options = {
token_amount : 1000000000 ,
decimals : 18
}
class ERC20TokenContract{
constructor(params){
self = {
contract :
new Contract({
web3 : window.web3,
contract : ierc20,
address : params.contractAddress
}),
...params
}
}
__assert(){
self.contract.use(
ierc20,
self.contractAddress);
}
async __init__(){
let contractDepolyed = await this.deploy();
// Start Contract use
this.__assert(contractDepolyed);
}
async deploy(){
console.log("Deploying...");
let params = [
options.token_amount,
options.decimals
];//[params]
let res = await self.contract.deploy(
self.account.getAccount(),
self.contract.getABI(),
self.contract.getJSON().bytecode,
params);
return res;
}
getContract(){
return self.contract.getContract();
}
getAddress(){
return self.contract.getAddress();
}
async getTokenAmount(address){
return await self.contract.getContract().methods.balanceOf(address).call();
}
async sendTokens({to, amount, decimals}){
let amountWithDecimals = Numbers.toSmartContractDecimals(amount, decimals);
let accounts = await window.web3.eth.getAccounts();
var myContract = new window.web3.eth.Contract(ierc20.abi, self.contractAddress);
return new Promise ( (resolve, reject) => {
myContract.methods.transfer(
to,
amountWithDecimals
).send({from : accounts[0]})
.on('transactionHash', (hash) => {
})
.on('confirmation', (confirmations, receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
}
getABI(){
return self.contract;
}
}
export default ERC20TokenContract;<file_sep>/src/services/etherscan.js
var api = require('etherscan-api').init('QPSKFN1UAJPK9NGVUMYMA1RAKKACQN6GQW');
export async function getContractData({address}){
return await api.contract.getabi(address);
}<file_sep>/src/containers/Applications/components/Wizard/WizardFormTwo.jsx
import React from 'react';
import { Button, ButtonToolbar, Container, Row, Col, CardBody, Card } from 'reactstrap';
import { Field, reduxForm } from 'redux-form';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import store from '../../../App/store';
import { AddressMarkerIcon, BitcoinIcon, Number1BoxOutlineIcon, DirectionsIcon } from 'mdi-react';
import { AddressConcat } from '../../../../lib/string';
import _ from 'lodash';
import { setAppCreationInfo } from '../../../../redux/actions/appCreation';
import appCreationConfig from '../../../../config/appCreation';
import { ETHEREUM_NET_DEFAULT } from '../../../../config/apiConfig';
class WizardFormTwo extends React.Component{
constructor(props){super(props); this.state = {}}
setWidget = ({key, value}) => {
store.dispatch(setAppCreationInfo({key, value}));
}
currencyBox = (object) => {
const { type, ticker, image, address, decimals } = object;
const { appCreation } = this.props;
let isSet = (appCreation[`${type.toLowerCase()}`] && (appCreation[`${type.toLowerCase()}`].ticker == ticker));
return (
<button className='clean_button' onClick={ () => this.setWidget({key : `${type.toLowerCase()}`, value : object})}>
<Card>
{isSet ? <div> <h5 className={`widget__use__big`} style={{marginTop : -40}}> Integrate </h5></div> : null}
<div className='landing__product__widget__small'>
<div className='description'>
<h4> {type}</h4>
<p> {ticker} </p>
<a target={'__blank'} className='ethereum-address-a' href={`https://${ETHEREUM_NET_DEFAULT}.etherscan.io/token/${address}`}>
<p className="ethereum-address-name"> <DirectionsIcon className='icon-ethereum-address'/>
{AddressConcat(address)}
</p>
</a>
<span> {decimals} Decimals </span>
</div>
<img className='image_widget' src={image}></img>
</div>
</Card>
</button>
)
}
blockchainBox = (object) => {
const { type, ticker, image, name } = object;
const { appCreation } = this.props;
let isSet = (appCreation[`${type.toLowerCase()}`] && (appCreation[`${type.toLowerCase()}`].ticker == ticker));
return (
<button className='clean_button' onClick={ () => this.setWidget({key : `${type.toLowerCase()}`, value : object})}>
<Card>
{isSet ? <div> <h5 className={`widget__use__big`} style={{marginTop : -40}}> Integrate </h5></div> : null}
<div className='landing__product__widget__small'>
<div className='description'>
<h4> {type}</h4>
<p> {name} </p>
</div>
<img className='image_widget' src={image}></img>
</div>
</Card>
</button>
)
}
render = () => {
const { blockchains, currencies } = this.props;
return(
<div style={{width : '80%'}}>
<Row>
<Col md={12} xl={12} lg={12} xs={12}>
<Card>
<Container>
<h4>
Blockchain Platform
</h4>
<Row>
{blockchains.map( (token) => {
let image = appCreationConfig['blockchains'][new String(token.ticker).toLowerCase()].image;
if(!image){return null}
return (
<Col lg={4}>
{this.blockchainBox({type : 'Blockchain', ticker : token.ticker, name : token.name, image : image})}
</Col>
)
})}
</Row>
</Container>
</Card>
</Col>
</Row>
<Row>
<Col md={12} xl={12} lg={12} xs={12}>
<Card>
<Container>
<h4>
Currency
</h4>
<Row>
{currencies.map( (token) => {
return (
<Col lg={4}>
{this.currencyBox({type : 'Currency', ticker : token.ticker, address : token.address, decimals : token.decimals, image : token.image})}
</Col>
)
})}
</Row>
</Container>
</Card>
</Col>
</Row>
<ButtonToolbar style={{margin : 'auto'}} className="form__button-toolbar wizard__toolbar">
<Button style={{margin : 'auto'}} color="primary" type="button" className="previous" onClick={ () => this.props.previousPage()}>Back</Button>
<Button style={{margin : 'auto'}} color="primary" type="submit" className="next" onClick={ () => this.props.onSubmit()}>Next</Button>
</ButtonToolbar>
</div>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
appCreation: state.appCreation
};
}
export default compose(reduxForm({
form: 'wizard', // <------ same form name
}), connect(mapStateToProps))(WizardFormTwo);
<file_sep>/src/models/Contract.js
class contract{
constructor(params){
this.web3 = params.web3;
this.abi = params.contract.abi;
this.address = params.address;
this.json = params.contract;
this.contract = new params.web3.eth.Contract(params.contract.abi, params.address)
}
async deploy(address, abi, byteCode, args=[]){
this.contract = new this.web3.eth.Contract(abi);
let transaction = await new Promise ( (resolve, reject) => {
this.contract.deploy({
data : byteCode,
arguments: args
}).send({
from: address,
gasPrice : 20000000000,
gas : 4000000
})
.on('receipt', (receipt) => {
resolve(receipt)
})
.on('error', () => {reject("Transaction Error")})
})
this.address = transaction.contractAddress;
return transaction;
}
async use(contract_json, address){
this.json = contract_json;
this.abi = contract_json.abi;
this.address = address ? address : this.address;
this.contract = new this.web3.eth.Contract(contract_json.abi, this.address)
}
async send(account, byteCode, value='0x0'){
let tx = {
data : byteCode,
from : account.address,
to : this.address,
gasPrice : 20000000000,
gas : 4000000,
value: value ? value : '0x0'
}
let result = await account.signTransaction(tx);
let transaction = await window.web3.eth.sendSignedTransaction(result.rawTransaction);
return transaction;
}
getContract(){
return this.contract;
}
getABI(){
return this.abi;
}
getJSON(){
return this.json;
}
setAddress(address){
this.address = address;
}
getAddress(){
return this.address;
}
}
export default contract;<file_sep>/src/containers/Applications/Customization/components/Footer/AddLink.js
import React from 'react';
import { connect } from 'react-redux';
import { FormGroup, Col } from 'reactstrap';
import { LinkCard, LinkCardContent, InputField, LinkImage, InputLabel, AddLinkButton } from './styles';
import _ from 'lodash';
import { Grid } from '@material-ui/core';
import Dropzone from 'react-dropzone'
import { PlusIcon } from 'mdi-react';
const upload = `${process.env.PUBLIC_URL}/img/dashboard/upload.png`;
const trash = `${process.env.PUBLIC_URL}/img/dashboard/clear.png`;
const image2base64 = require('image-to-base64');
const dropzoneStyle = {
width: "100%",
height: "100%",
backgroundColor: "white"
};
class AddLink extends React.Component {
constructor(props){
super(props);
this.state = {
newName: "",
newLink: "",
newImage: ""
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { links } = props;
if (!_.isEmpty(links)) {
this.setState({
links: links
})
}
}
renderImage = (src) => {
if(!src.includes("https")){
src = "data:image;base64," + src;
}
return src;
}
onChangeNewName = ({ value }) => {
if (value) {
this.setState({
newName: value
})
} else {
this.setState({
newName: ""
})
}
}
onChangeNewLink = ({ value }) => {
if (value) {
this.setState({
newLink: value
})
} else {
this.setState({
newLink: ""
})
}
}
onAddedNewFile = async ({ files }) => {
const file = files[0];
let blob = await image2base64(file.preview) // you can also to use url
this.setState({
newImage: blob
})
}
renderAddNewImage = () => {
const { locked } = this.props;
return(
<Dropzone disabled={locked} style={dropzoneStyle} onDrop={(files) => this.onAddedNewFile({ files: files })} ref={(el) => (this.dropzoneRef = el)}>
<img src={upload} className='image-info' style={{ height: 20, width: 20 }}/>
<p className='text-center'> Drop the image here</p>
</Dropzone>
)
}
removeNewImage = () => {
this.setState({
newImage: ""
})
}
addNewLink = () => {
const { newName, newLink, newImage } = this.state;
const { setLinks, links } = this.props;
const newLinkObj = { name: newName, href: newLink, image_url: newImage, _id: Math.random().toString(36).substr(2, 9) }
const newLinks = links ? [newLinkObj, ...links] : [newLinkObj];
this.setState({
newName: "",
newLink: "",
newImage: ""
})
setLinks({
newLinks: newLinks,
})
}
render() {
const { newName, newLink, newImage } = this.state;
const { locked } = this.props;
return (
<>
<Col md={3} style={{ minWidth: 178, margin: 5 }}>
<LinkCard>
<LinkCardContent>
{ newImage ?
<>
<div style={{ display: "flex", justifyContent: "flex-end", width: "100%", marginTop: -10, marginBottom: -30 }}>
<button
disabled={locked}
onClick={() => this.removeNewImage()}
style={{ position: "inherit", right: 20, top: 6 }}
className='carousel-trash button-hover'>
<img src={trash} style={{width : 15, height : 15}}/>
</button>
</div>
<img className='application__game__image' style={{ display: 'block', width: 100, height: 100 }} src={this.renderImage(newImage)}/>
</>
:
<LinkImage>
{ this.renderAddNewImage() }
</LinkImage> }
<FormGroup>
<InputLabel for="name">Name</InputLabel>
<InputField
label="Name"
name="name"
type="text"
value={newName}
disabled={locked}
// defaultValue={name}
onChange={(e) => this.onChangeNewName({ value: e.target.value })}
/>
</FormGroup>
<FormGroup>
<InputLabel for="link">Link</InputLabel>
<InputField
label="Link"
name="link"
type="text"
value={newLink}
disabled={locked}
// defaultValue={href}
onChange={(e) => this.onChangeNewLink({ value: e.target.value })}
/>
</FormGroup>
<AddLinkButton disabled={locked} onClick={() => this.addNewLink()}>
<PlusIcon/> Add link
</AddLinkButton>
</LinkCardContent>
</LinkCard>
</Col>
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(AddLink);
<file_sep>/src/redux/actions/messageContainer.js
export const SET_MESSAGE_NOTIFICATION = 'SET_MESSAGE_NOTIFICATION';
export function setMessageNotification(data) {
return {
type: SET_MESSAGE_NOTIFICATION,
action : data
};
}
<file_sep>/src/shared/components/LockWrapper.js
import styled from "styled-components";
export const LockWrapper = styled.section`
pointer-events: ${ props => props.hasPermission ? "all" : "none" };
opacity: ${ props => props.hasPermission ? 1.0 : 0.8 };
`;<file_sep>/src/containers/Applications/Customization/components/Tabs/Tab.js
import React from 'react';
import { FormGroup, Col } from 'reactstrap';
import { TabCard, TabCardContent, InputField, TabImage, InputLabel, RemoveTab, Yes, Cancel } from './styles';
import _ from 'lodash';
import Dropzone from 'react-dropzone'
import { TrashCanOutlineIcon } from 'mdi-react';
const upload = `${process.env.PUBLIC_URL}/img/dashboard/upload.png`;
const trash = `${process.env.PUBLIC_URL}/img/dashboard/clear.png`;
const image2base64 = require('image-to-base64');
const dropzoneStyle = {
width: "100%",
height: "100%",
backgroundColor: "white"
};
class Tab extends React.Component {
constructor(props){
super(props);
this.state = {
removing: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { tabs, tab } = props;
if (!_.isEmpty(tab)) {
this.setState({
_id: tab._id,
name: tab.name,
icon: tab.icon,
link_url: tab.link_url,
tabs: tabs
})
}
}
renderImage = (src) => {
if(!src.includes("https")){
src = "data:image;base64," + src;
}
return src;
}
onAddedFile = async ({ id, files }) => {
const { tabs } = this.state;
const { setTabs } = this.props;
const file = files[0];
let blob = await image2base64(file.preview) // you can also to use url
const index = tabs.findIndex(tab => tab._id === id);
const newTabs = [...tabs];
newTabs[index].icon = blob;
setTabs({
newTabs: newTabs
})
}
renderAddImage = ({ id }) => {
const { locked } = this.props;
return(
<Dropzone disabled={locked} style={dropzoneStyle} onDrop={(files) => this.onAddedFile({ id: id, files: files })} ref={(el) => (this.dropzoneRef = el)}>
<img src={upload} className='image-info' style={{ height: 20, width: 20 }}/>
<p className='text-center'> Drop the icon here</p>
</Dropzone>
)
}
onChangeName = ({ id, value }) => {
const { tabs } = this.state;
const { setTabs } = this.props;
if (value) {
const index = tabs.findIndex(tab => tab._id === id);
const newTabs = [...tabs];
newTabs[index].name = value;
setTabs({
newTabs: newTabs
})
} else {
const index = tabs.findIndex(tab => tab._id === id);
const newTabs = [...tabs];
newTabs[index].name = "";
setTabs({
newTabs: newTabs
})
}
}
onChangeLink = ({ id, value }) => {
const { tabs } = this.state;
const { setTabs } = this.props;
if (value) {
const index = tabs.findIndex(tab => tab._id === id);
const newTabs = [...tabs];
newTabs[index].link_url = value;
setTabs({
newTabs: newTabs
})
} else {
const index = tabs.findIndex(tab => tab._id === id);
const newTabs = [...tabs];
newTabs[index].link_url = "";
setTabs({
newTabs: newTabs
})
}
}
removeImage = ({ id }) => {
const { tabs } = this.state;
const { setTabs } = this.props;
const index = tabs.findIndex(tab => tab._id === id);
const newTabs = [...tabs];
newTabs[index].icon = "";
setTabs({
newTabs: newTabs
})
}
removeTab = ({ id }) => {
this.setState({
removing: true
})
}
cancelRemoveTab = ({ id }) => {
this.setState({
removing: false
})
}
removeTabCard = ({ id }) => {
const { tabs } = this.state;
const { setTabs } = this.props;
const index = tabs.findIndex(tab => tab._id === id);
const newTabs = [...tabs];
newTabs[index] = {};
this.setState({
removing: false
})
setTabs({
newTabs: newTabs ? newTabs.filter(tab => !_.isEmpty(tab)) : []
})
}
render() {
const { _id, name, icon, link_url, removing } = this.state;
const { locked } = this.props;
return (
<>
<Col md={3} style={{ minWidth: 178, maxWidth: 230, padding: 0, margin: "10px 15px" }}>
<TabCard>
<TabCardContent>
{ !_.isEmpty(icon) ?
<>
<div style={{ display: "flex", justifyContent: "flex-end", width: "100%", marginTop: -10, marginBottom: -30 }}>
<button
disabled={locked}
onClick={() => this.removeImage({ id: _id })}
style={{ position: "inherit", right: 20, top: 6 }}
className='carousel-trash button-hover'>
<img src={trash} style={{width : 15, height : 15}}/>
</button>
</div>
<img className='application__game__image' style={{ display: 'block', width: 100, height: 100 }} src={this.renderImage(icon)}/>
</>
:
<TabImage>
{ this.renderAddImage({ id: _id }) }
</TabImage> }
<FormGroup>
<InputLabel for="name">Title</InputLabel>
<InputField
label="Name"
name="name"
type="text"
defaultValue={name}
disabled={locked}
onChange={(e) => this.onChangeName({ id: _id, value: e.target.value })}
/>
</FormGroup>
<FormGroup>
<InputLabel for="link">Link</InputLabel>
<InputField
label="Link"
name="link"
type="text"
defaultValue={link_url}
disabled={locked}
onChange={(e) => this.onChangeLink({ id: _id, value: e.target.value })}
/>
</FormGroup>
{ !removing ?
<RemoveTab disabled={locked} onClick={() => this.removeTab({ id: _id })}>
<TrashCanOutlineIcon/> Remove tab
</RemoveTab>
:
<div style={{ display: "flex" }}>
<Yes disabled={locked} onClick={() => this.removeTabCard({ id: _id })}>
Yes
</Yes>
<Cancel disabled={locked} onClick={() => this.cancelRemoveTab({ id: _id })}>
Cancel
</Cancel>
</div> }
</TabCardContent>
</TabCard>
</Col>
</>
)
}
}
export default Tab;
<file_sep>/src/containers/Applications/EsportsPage/components/StatsPage/components/Teams/index.js
import React from 'react';
import { Container, PlayerCardContainer, PlayerPhoto, PlayerInfo, PlayerName, PlayerFullName, Nationality, Role, TeamCard, TeamInfo, TeamIcon, TeamName, TeamList } from './styles';
import _ from 'lodash';
import Avatar from 'react-avatar';
import FlagIconFactory from 'react-flag-icon-css'
import TeamsSkeleton from '../../../Skeletons/TeamsSkeleton';
const FlagIcon = FlagIconFactory(React, { useCssModules: false })
const PlayerCard = player => {
const { first_name, last_name, name, image_url, hometown, nationality, role } = player.player;
if (!nationality) return null;
return (
<>
<PlayerCardContainer>
<PlayerPhoto>
{ image_url ? <img src={image_url} alt={name}/> : <Avatar name={name} size="65" round={true}/> }
</PlayerPhoto>
<PlayerInfo>
<PlayerName>
{ name }
</PlayerName>
<PlayerFullName>
{ `${first_name} ${last_name}` }
</PlayerFullName>
<Nationality>
<span>{hometown ? hometown : "Nationality: "}</span>
<FlagIcon code={nationality.toLowerCase()} size={'1x'}/>
</Nationality>
<Role>
<span>{`Role: ${role}`}</span>
</Role>
</PlayerInfo>
</PlayerCardContainer>
</>
)
}
const Team = props => {
const { team, players } = props;
if (_.isEmpty(team) || _.isEmpty(players)) return null;
const { name, image_url } = team;
return (
<TeamCard>
<TeamInfo>
<TeamIcon>
{ image_url ? <img src={image_url} alt={name}/> : <Avatar name={name} size="65" round={true}/> }
</TeamIcon>
<TeamName>
<span>{ name }</span>
</TeamName>
</TeamInfo>
<TeamList>
{ players.map(player => (
<PlayerCard player={player}/>
))}
</TeamList>
</TeamCard>
)
}
const Teams = props => {
const { teamOne, teamTwo, isLoading } = props;
if (isLoading) return <TeamsSkeleton/>
if (_.isEmpty(teamOne) || _.isEmpty(teamTwo)) return null;
const teamOneplayers = teamOne.players;
const teamTwoplayers = teamTwo.players;
if (_.isEmpty(teamOneplayers) || _.isEmpty(teamTwoplayers)) return null;
return (
<>
<Container>
<Team team={teamOne} players={teamOneplayers}/>
<Team team={teamTwo} players={teamTwoplayers}/>
</Container>
</>
)
};
export default Teams;<file_sep>/src/containers/Users/UserPage/components/TopUpBalance/index.js
import React from 'react';
import { connect } from "react-redux";
import { Dialog, DialogContent, Button } from '@material-ui/core';
import _ from 'lodash';
import { CloseIcon, ArrowUpIcon } from 'mdi-react';
import { DialogHeader, CloseButton, Container, CardHeader, CardContent, InputAddOn, AmountInput, ConfirmButton, ReasonInput } from './styles';
import { Row, Col, InputGroup, InputGroupAddon } from 'reactstrap';
import AnimationNumber from '../../../../UI/Typography/components/AnimationNumber';
const loading = `${process.env.PUBLIC_URL}/img/loading.gif`;
class UserContainer extends React.Component {
constructor() {
super();
this.state = {
open: false,
user: {},
amount: null,
isLoading: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { user, currency } = props;
if (!_.isEmpty(user)){
this.setState({
user: user,
currency: currency,
wallet: user.wallet.find(wallet => wallet.currency._id === currency._id)
})
} else {
this.setState({
user: {}
})
}
}
setOpen = async () => {
this.setState({
open: true
})
}
setClose = () => {
this.setState({
open: false
})
}
onChangeAmount = value => {
if (value) {
this.setState({
amount: parseFloat(value)
})
} else {
this.setState({
amount: null
})
}
}
handleChangeReason = value => {
this.setState({ reason: value ? value : null })
}
confirmChanges = async () => {
const { profile } = this.props;
const { App } = profile;
const { user, wallet, amount, reason } = this.state;
if (amount && reason) {
this.setState({
isLoading: true
})
await App.modifyUserBalance({ user: user._id, wallet: wallet._id, currency: wallet.currency._id, newBalance: amount, reason: reason });
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({
isLoading: false,
open: false
})
}
}
render() {
const { open, user, wallet, isLoading, amount, reason } = this.state;
return(
<>
<Button onClick={this.setOpen} variant="outlined" size="small" style={{ textTransform: "none", backgroundColor: "#63c965", color: "#ffffff", boxShadow: "none", height: 25, margin: "10px 0px" }}>
<ArrowUpIcon style={{marginRight: 3}}/> Top Up
</Button>
{ !_.isEmpty(user) ?
<Dialog
// disableBackdropClick
open={open}
onClose={this.setClose}
>
<DialogHeader>
<CloseButton onClick={this.setClose}>
<CloseIcon/>
</CloseButton>
</DialogHeader>
<DialogContent style={{ paddingTop: 0 }}>
<Container style={{ paddingTop: 0 }}>
<CardHeader>
<h1>Wallet</h1>
<Row>
<Col sd={12} md={12} lg={4}>
<img src={wallet.currency.image} style={{ height: 75, width: 75 }}className='user-avatar' alt={wallet.currency.name}/>
</Col>
<Col sd={12} md={12} lg={8}>
{/* UserInfo */}
<h4 style={{marginTop : 5}}> <AnimationNumber decimals={6} font={'20pt'} number={wallet.playBalance ? wallet.playBalance : 0 }/> <span className='text-small'>{wallet.currency.ticker}</span></h4>
<hr></hr>
<p className='text-x-small'> #{wallet._id} </p>
</Col>
</Row>
</CardHeader>
<hr/>
<CardContent>
<h1>New balance</h1>
<InputGroup>
<InputGroupAddon addonType="prepend">
<InputAddOn>
<span>Amount</span>
<img className='application__game__image' style={{ display: 'block', marginLeft: 0, marginRight: 0, height: 20, width: 20 }} src={wallet.currency.image} alt={wallet.currency.name}/>
</InputAddOn>
</InputGroupAddon>
<AmountInput name="amount" type="number" onChange={(e) => this.onChangeAmount(e.target.value)}/>
</InputGroup>
<h1>Reason</h1>
<ReasonInput name="reason" type="text" onChange={(e) => this.handleChangeReason(e.target.value)}/>
<ConfirmButton disabled={ !amount || !reason || isLoading } onClick={this.confirmChanges}>
{ isLoading ? <img src={loading} className={'loading_gif'} alt="Confirming..."/> : <span>Confirm</span> }
</ConfirmButton>
</CardContent>
</Container>
</DialogContent>
</Dialog> : null }
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
currency: state.currency
};
}
export default connect(mapStateToProps)(UserContainer);<file_sep>/src/containers/Applications/EsportsPage/components/MatchTab/index.js
import React from 'react';
import { connect } from 'react-redux';
import { Container, Tab, Indicator, Game, Winner, Icon, TrophyIcon, Team } from './styles';
import _ from 'lodash';
import { Trophy } from '../Icons';
class MatchTab extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { data } = props;
if (!_.isEmpty(data)) {
this.setState({
data: data
})
}
}
getWinnerName = id => {
const { opponents } = this.state.data;
const winner = opponents.find(opponent => opponent.opponent.id === id);
return winner.opponent.name;
}
render() {
const { data } = this.state;
const { games } = data;
if (_.isEmpty(data)) return null;
return (
<>
<Container>
{ games.map(game => (
<Tab>
<Indicator status={game.status}/>
<Game>
<span>
{ `Game ${game.position}` }
</span>
</Game>
{ game.winner.id ? (
<Winner>
<Icon>
<TrophyIcon>
<Trophy/>
</TrophyIcon>
</Icon>
<Team>
<span>
{ this.getWinnerName(game.winner.id) }
</span>
</Team>
</Winner>
) : null }
</Tab>
))}
</Container>
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(MatchTab);<file_sep>/src/containers/Wallet/components/paths/components/AllCurrencyBox.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col, Row , Button} from 'reactstrap';
import { BarcodeIcon, TickCircleIcon } from 'mdi-react';
import AnimationNumber from '../../../../UI/Typography/components/AnimationNumber';
import ConverterSingleton from '../../../../../services/converter';
import QRCodeContainer from './QRCode';
import AddressBox from './AddressBox';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import ReciptBox from './ReciptBox';
const Ava = `${process.env.PUBLIC_URL}/img/dashboard/ethereum.png`;
class AllCurrencyBox extends PureComponent {
constructor() {
super();
this.state = {
usd : 0,
referenceAddress : '0x',
generatedReference : false
};
}
componentWillReceiveProps(props){
this.getAsyncCalls(props);
}
getAsyncCalls = async (props) => {
let usd = await ConverterSingleton.fromETHtoUsd(props.data.eth);
this.setState({...this.state, usd : usd});
}
handleClick = (index) => {
this.setState({
activeIndex: index,
});
};
setTimer = () => {
window.setInterval( () => {this.confirmDeposit()}, 2000);
}
getReference = async () => {
// TO DO : Change ETH to the Currency Type;
let data = await this.props.profile.getDepositReference({currency : 'eth'});
let {address, id} = data;
this.setState({...this.state, id, referenceAddress : address, generatedReference : true});
this.setTimer()
}
confirmDeposit = async () => {
// TO DO : Change ETH to the Currency Type;
let data = await this.props.profile.getDepositInfo({id : this.state.id});
let {
confirmed,
amount,
timestamp,
block
} = data;
let usd_amount = await ConverterSingleton.fromETHtoUsd(amount);
this.setState({...this.state,
confirmedDeposit : confirmed,
recipt : {
confirmedDeposit : confirmed,
amount, timestamp, block, usd_amount
}
});
}
render() {
let eth = this.props.data.eth;
return (
<Col md={12} xl={12} lg={12} xs={12}>
<Card>
<CardBody className="dashboard__card-widget" >
<Row>
<Col lg={3}>
<img style={{borderRadius : 0}} className="company-logo-card" src={Ava} alt="avatar" />
</Col>
<Col lg={9}>
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-number-second" style={
{color : '#646777'}
}><AnimationNumber decimals={6} number={eth}/> ETH</p>
</div>
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-title"> <AnimationNumber decimals={2} number={this.state.usd}/> <span> EUR </span></p>
</div>
</Col>
<div className='container' style={{textAlign : 'center'}}>
{!this.state.generatedReference ?
<Col lg={12} style={{marginTop : 30}}>
<Button onClick={() => this.getReference()} style={{margin : 0, marginTop : 10}} outline className="primary" ><p><BarcodeIcon className="deposit-icon"/> Generate Reference </p></Button>
</Col>
:
!this.state.confirmedDeposit ?
<Col lg={12} style={{margin : '10px auto', textAlign : 'center'}} >
<QRCodeContainer value={this.state.referenceAddress}/>
<AddressBox value={this.state.referenceAddress}/>
<hr></hr>
<Button disabled={true} onClick={() => this.confirmDeposit()} outline className="primary" ><p><TickCircleIcon className="deposit-icon"/> Waiting for Deposit...</p></Button>
</Col>
:
<ReciptBox recipt={this.state.recipt}/>
}
</div>
</Row>
</CardBody>
</Card>
</Col>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
AllCurrencyBox.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
connect(mapStateToProps)
)(AllCurrencyBox);
<file_sep>/src/containers/DataWidget/DataWidget.js
import React from 'react';
import { Col, Container, Row } from 'reactstrap';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import _ from 'lodash';
class DataWidget extends React.Component{
constructor(props){
super(props)
}
render = () => {
let {
data
} = this.props.children.props
let summary = {
data : {}
};
// TO DO : To setup correctly Condition Statement
try{
if(data){
if(data.data){
summary = this.props.profile.hasAppStats(data.type);
}else if(!_.has(data,'data')){
let array = Object.keys(data).map( (key) => {
return this.props.profile.hasAppStats(data[key].type);
})
for(var i = 0; i < array.length; i++){
summary.data[array[i].type] = array[i]
}
}else{
throw new Error('No Data')
}
}
}catch(err){
summary = null;
}
let hasData = summary && !_.isEmpty(summary.data);
return (
hasData ?
this.props.children
: null
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
DataWidget.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(DataWidget);
<file_sep>/src/containers/Applications/Customization/components/Colors.js
import React, { Component } from 'react'
import EditLock from '../../../Shared/EditLock.js';
import ColorPickerInput from '../../../../shared/components/color_picker_input/ColorPickerInput';
import ColorPicker from '../../../../shared/components/color_picker_input/ColorPicker.js';
import { Col, Row, Card, CardBody } from 'reactstrap';
import { connect } from "react-redux";
import { FormControlLabel } from '@material-ui/core';
import BooleanInput from "./utils/BooleanInput";
const defaultState = {
locked: true,
colors : [],
isLoading: false
}
const COLORS = Object.freeze({
backgroundColor: { name: "Background Color", locked: false },
primaryColor: { name: "Boxes", locked: false },
secondaryColor: { name: "Buttons", locked: false },
thirdColor: { name: "", locked: true },
forthColor: { name: "", locked: true },
fifthColor: { name: "Title/Tab Text", locked: false },
sixthColor: { name: "Overall Text", locked: false },
seventhColor: { name: "1st Color Icons", locked: false },
heightColor: { name: "2nd Color Icons", locked: false }
})
class Colors extends Component {
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props)
}
projectData = async (props) => {
const { colors, theme } = await props.profile.getApp().getCustomization();
this.setState({...this.state,
colors,
theme
})
}
onChange = ({type, value}) => {
let colors = this.state.colors;
let changedColorIndex = colors.findIndex(c => c.type == type);
colors[changedColorIndex].hex = value;
this.setState({...this.state, colors})
}
onChangeTheme = async ({type, value}) => {
const { theme } = this.state;
const newTheme = theme === 'dark' ? 'light' : 'dark';
this.setState({ theme: newTheme });
}
unlockField = () => {
this.setState({...this.state, locked : false})
}
lockField = () => {
this.setState({...this.state, locked : true})
}
confirmChanges = async () => {
const { App } = this.props.profile;
const { theme, colors } = this.state;
this.setState({...this.state, isLoading : true});
await App.editThemeCustomization({ theme: theme });
await App.editColorsCustomization({colors});
this.setState({...this.state, isLoading : false, locked: true})
this.projectData(this.props);
}
renderColor = ({ name, hex, type, locked, colorLock }) => {
if (colorLock) {
return null
}
return (
<>
<Col md={6}>
<ColorPicker
label={name}
name={type}
color={hex}
disabled={ locked }
onChange={this.onChange}
/>
</Col>
</>
)
}
render() {
const { isLoading, locked, colors, theme } = this.state;
return (
<>
<Card style={{ margin: "15px 10px", padding: 0 }}>
<h5> Note : Change of Colors will require a rebuild of the app, so expect a 5-20 min delay for the changes to take effect</h5>
</Card>
<Card>
<CardBody style={{ margin: 10, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'color'}
locked={locked}
>
<h4 style={{ fontSize: 16 }}>Theme</h4>
<FormControlLabel
style={{margin: 0, marginBottom: 30, padding: 0}}
control={
<BooleanInput
disabled={isLoading || locked}
checked={theme === 'light'}
onChange={this.onChangeTheme}
type={'theme'}
id={'check-theme'}
/>
}
label={theme === 'dark' ? <h4 style={{ fontSize: 14 }}>Dark</h4>
: <h4 style={{ fontSize: 14 }}>Light</h4>}
labelPlacement="right"
/>
<Row>
{colors.map ( c => {
return (
this.renderColor({ name: COLORS[c.type].name, type: c.type, hex: c.hex, locked: locked, colorLock: COLORS[c.type].locked })
)
})}
</Row>
</EditLock>
</CardBody>
</Card>
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(Colors);
<file_sep>/src/containers/Applications/Customization/components/utils/BooleanInput.js
import React, { Component } from 'react';
import Switch from '@material-ui/core/Switch';
import { withStyles } from '@material-ui/core';
import { purple } from '@material-ui/core/colors';
const PurpleSwitch = withStyles({
switchBase: {
color: purple[300],
'&$checked': {
color: purple[500],
},
'&$checked + $track': {
backgroundColor: purple[500],
},
},
checked: {},
track: {},
})(Switch);
class BooleanInput extends Component {
constructor(props){
super(props);
}
render() {
const { onChange, checked, id, type, disabled } = this.props;
return (
<PurpleSwitch
checked={checked}
onChange={() => onChange({type, value : !checked})}
value={id}
disabled={disabled}
inputProps={{ 'aria-label': 'primary checkbox' }}
/>
);
}
}
export default BooleanInput;
<file_sep>/src/containers/Applications/EsportsPage/components/Skeletons/TeamsSkeleton/index.js
import React from 'react';
import { Container, PlayerCardContainer, PlayerPhoto, PlayerInfo, PlayerName, PlayerFullName, Nationality, Role, TeamCard, TeamInfo, TeamIcon, TeamName, TeamList } from './styles';
import _ from 'lodash';
import Skeleton from '@material-ui/lab/Skeleton';
const PlayerCard = () => {
return (
<>
<PlayerCardContainer>
<PlayerPhoto>
<Skeleton variant="circle" width="65px" height="65px" />
</PlayerPhoto>
<PlayerInfo>
<PlayerName>
<Skeleton variant="rect" width="100%" height="80%" />
</PlayerName>
<PlayerFullName>
<Skeleton variant="rect" width="100%" height="80%" />
</PlayerFullName>
<Nationality>
<Skeleton variant="rect" width="100%" height="80%" />
</Nationality>
<Role>
<Skeleton variant="rect" width="100%" height="80%" />
</Role>
</PlayerInfo>
</PlayerCardContainer>
</>
)
}
const Team = () => {
return (
<TeamCard>
<TeamInfo>
<TeamIcon>
<Skeleton variant="circle" width="30px" height="30px" />
</TeamIcon>
<TeamName>
<Skeleton variant="rect" width="100%" height="30%" />
</TeamName>
</TeamInfo>
<TeamList>
{ _.times(5, () => <PlayerCard/>)}
</TeamList>
</TeamCard>
)
}
const Teams = () => {
return (
<>
<Container>
<Team/>
<Team/>
</Container>
</>
)
};
export default Teams;<file_sep>/src/containers/Applications/EsportsPage/components/MarketsPage/components/WinnerTwoWay/styles.js
import styled from 'styled-components';
import { Button } from '@material-ui/core';
export const Container = styled.div`
display: grid;
grid-template-areas:
'header'
'result';
grid-template-columns: 100%;
grid-template-rows: 42px 1fr;
height: 161px;
width: 512px;
margin: 10px;
padding: 10px;
background-color: #fafcff;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
`;
export const Header = styled.section`
display: flex;
justify-content: flex-start;
align-items: center;
padding: 0px 8px;
margin-bottom: 10px;
border-bottom: solid 1px rgba(164, 161, 161, 0.35);
font-family: Poppins;
font-size: 16px;
font-weight: 500;
color: #333333;
`;
export const Result = styled.section`
grid-area: result;
display: grid;
grid-template-areas:
'header'
'content'
'menu';
grid-template-columns: 100%;
grid-template-rows: 30% 50% 20%;
`;
export const ResultHeader = styled.section`
grid-area: header;
display: grid;
grid-template-areas:
'name graph tag';
grid-template-columns: 60% 25% 15%;
grid-template-rows: 100%;
padding: 0px 8px;
`;
export const MarketName = styled.section`
grid-area: name;
display: flex;
justify-content: flex-start;
align-items: center;
font-family: Poppins;
font-size: 14px;
font-weight: 400;
color: #333333;
`;
export const Graph = styled.section`
grid-area: graph;
display: flex;
justify-content: center;
align-items: center;
padding: 0px 8px;
svg {
margin-bottom: 5px;
}
`;
export const Status = styled.section`
grid-area: tag;
display: flex;
justify-content: center;
align-items: center;
padding: 0px 8px;
`;
export const Tag = styled.div`
display: flex;
justify-content: center;
align-items: center;
min-width: 70px;
min-height: 23px;
padding: 3px;
border-radius: 3px;
font-family: Poppins;
font-size: 11px;
font-weight: 300;
background-color: ${props => props.backgroundColor};
color: ${props => props.textColor};
`;
export const Content = styled.section`
grid-area: content;
display: flex;
justify-content: space-between;
align-items: center;
`;
export const ResultTag = styled.section`
display: grid;
grid-template-areas:
'name result';
grid-template-columns: 80% 20%;
grid-template-rows: 100%;
padding: 4px 8px;
height: 30px;
width: 234px;
border-radius: 3px;
background-color: ${props => props.backgroundColor};
`;
export const TeamName = styled.section`
grid-area: name;
display: flex;
justify-content: flex-start;
align-items: center;
font-family: Poppins;
font-size: 14px;
font-weight: 400;
color: black;
`;
export const TeamResult = styled.section`
grid-area: result;
display: flex;
justify-content: flex-end;
align-items: center;
font-family: Poppins;
font-size: 14px;
font-weight: 400;
color: ${props => props.color ? props.color : "#333333"};
`;
export const CloseButton = styled(Button)`
text-transform: none !important;
background-color: #39f !important;
color: white !important;
box-shadow: none !important;
height: 23px;
font-family: Poppins !important;
font-size: 11px !important;
font-weight: 300 !important;
`;
export const GraphContainer = styled.div`
display: flex;
justify-content: center;
align-items: center;
width: 950px;
height: 500px;
`;<file_sep>/src/containers/Account/LogIn/components/LogInForm.jsx
import React, { PureComponent } from 'react';
import { Field, reduxForm } from 'redux-form';
import EyeIcon from 'mdi-react/EyeIcon';
import KeyVariantIcon from 'mdi-react/KeyVariantIcon';
import AccountOutlineIcon from 'mdi-react/AccountOutlineIcon';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import renderCheckBoxField from '../../../../shared/components/form/CheckBox';
import Account from '../../../../controllers/Account';
import { CheckboxMultipleBlankCircleIcon } from 'mdi-react';
import TextInput from '../../../../shared/components/TextInput';
import { EmailInput, InputAddOn, InputLabel, PasswordInput } from '../styles';
import { InputGroup, InputGroupText, FormGroup, Label } from 'reactstrap';
const loading = `${process.env.PUBLIC_URL}/img/loading.gif`;
class LogInForm extends React.Component {
static propTypes = {
handleSubmit: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = {
showPassword: false,
};
this.showPassword = this.showPassword.bind(this);
}
componentDidMount(){
let {
username,
password
} = this.props.query;
this.setState({...this.state, username, password})
}
showPassword(e) {
e.preventDefault();
this.setState({
showPassword: !this.state.showPassword,
});
}
goTo2FA = () => {
this.props.SW.nextStep();
}
render() {
const { handleSubmit, onChangeUsername, onChangePassword } = this.props;
return (
<form className="form" onSubmit={handleSubmit}>
<div className="form__form-group">
<FormGroup>
<InputLabel for="username">Username or E-mail</InputLabel>
<EmailInput
label="Username or E-mail"
icon={CheckboxMultipleBlankCircleIcon}
name="username"
type="text"
defaultValue={this.state.username}
onChange={(e) => onChangeUsername(e.target.value)}
/>
</FormGroup>
<br/>
<FormGroup>
<InputLabel for="password">Password</InputLabel>
<PasswordInput
icon={KeyVariantIcon}
name="password"
label="Password"
type="password"
defaultValue={this.state.password}
onChange={(e) => onChangePassword(e.target.value)}
/>
</FormGroup>
<div className="account__forgot-password" >
<a href="/password/reset" >Forgot a password?</a>
</div>
</div>
<div className="account__btns" style={{marginTop :40}}>
<button disabled={this.props.isLoading} className="btn btn-primary account__btn" onClick={ () => this.props.login() } >
{
!this.props.isLoading ?
'Log In'
:
<img src={loading} className={'loading_gif'}></img>
}
</button>
<Link className='btn btn-outline-primary account__btn' to="/register">
Create Account
</Link>
</div>
</form>
);
}
}
export default reduxForm({
form: 'log_in_form', // a unique identifier for this form
})(LogInForm);
<file_sep>/src/containers/Wallet/components/paths/WithdrawWidget.js
import React from 'react';
import { Col, Container, Row } from 'reactstrap';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import WithdrawBox from './components/WithdrawBox';
import Numbers from '../../../../services/numbers';
import WithdrawsTable from './withdraw/Table';
import _ from 'lodash';
class WithdrawWidget extends React.Component{
constructor(props){
super(props)
this.state = {
disabled : false,
withdraws : [],
ticker : 'N/A'
}
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
if(_.isEmpty(props.profile)){return null}
const { wallet } = props;
const { currency } = wallet;
if(_.isEmpty(wallet)){return null}
let withdraws = props.profile.getApp().getWithdraws({currency});
let ticker = wallet.currency.ticker;
this.setState({...this.state,
withdraws,
ticker
})
}
withdrawTokens = async (withdrawObject) => {
var { id } = withdrawObject;
const { wallet } = this.props;
const { currency } = wallet;
try{
this.setState({...this.state, disabled : true});
/* Create Withdraw */
await this.props.profile.finalizeWithdraw({withdraw_id : id, currency});
await this.props.profile.getApp().updateAppInfoAsync();
await this.props.profile.update();
/* Update User Balance */
this.setState({...this.state, disabled : false});
}catch(err){
console.log(err)
alert(err);
this.setState({...this.state, disabled : true});
}
}
disable = () => {
this.setState({...this.state, disabled : true});
}
enable = () => {
this.setState({...this.state, disabled : false});
}
render = () => {
const { ticker, withdraws } = this.state;
return (
<Container className="dashboard">
<Col lg={12}>
<h3 style={{marginTop : 20}} className={"bold-text dashboard__total-stat"}>Withdraw</h3>
<p className="">
Choose the amount of Liquidity you want to withdraw
</p>
</Col>
<Row>
<Col lg={4}>
<WithdrawBox
enable={this.enable} disable={this.disable}
disabled={this.state.disabled} data={this.props.profile.getApp().getSummaryData('wallet')}/>
</Col>
<Col lg={8}>
<div style={{marginTop : 50}}>
<WithdrawsTable
profile={this.props.profile}
disabled={this.state.disabled}
withdraw={this.withdrawTokens}
currency={ticker} data={withdraws}
/>
</div>
</Col>
</Row>
</Container>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
wallet : state.wallet
};
}
WithdrawWidget.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(WithdrawWidget);
<file_sep>/src/containers/Applications/EsportsPage/components/VideogameTab/styles.js
import styled from 'styled-components';
export const Container = styled.div`
width: 100%;
`;
export const Tab = styled.div`
width: 100%;
/* min-height: 58px; */
background-color: white;
display: grid;
grid-template-areas:
'select videogame dropdown'
'subtab subtab subtab';
grid-template-columns: 10% 80% 10%;
grid-template-rows: 58px auto;
border-top: solid 1px rgba(164, 161, 161, 0.35);
`;
export const Select = styled.section`
grid-area: select;
display: flex;
justify-content: center;
align-items: center;
`;
export const Videogame = styled.section`
grid-area: videogame;
display: grid;
grid-template-areas: 'gameIcon gameName';
grid-template-columns: 20% 80%;
grid-template-rows: auto;
`;
export const VideoGameImage = styled.section`
grid-area: gameIcon;
display: flex;
justify-content: center;
align-items: center;
`;
export const VideoGameIcon = styled.section`
height: 22px;
width: 22px;
`;
export const VideogameName = styled.section`
grid-area: gameName;
display: flex;
justify-content: space-between;
align-items: center;
span {
font-family: Poppins;
font-size: 15px;
font-weight: 500;
color: ${props => props.selected ? "#3399ff": "#212529"}
}
`;
export const Dropdown = styled.section`
grid-area: dropdown;
display: flex;
justify-content: center;
align-items: center;
`;
export const SubTabContainer = styled.section`
grid-area: subtab;
padding: 0px 20px;
overflow-y: scroll;
::-webkit-scrollbar {
display: none;
}
`;
export const SubTab = styled.div`
width: 100%;
height: 40px;
background-color: white;
margin: 8px 0px;
display: grid;
grid-template-areas:
'select league';
grid-template-columns: 10% 90%;
grid-template-rows: auto;
`;
export const SubTabSelect = styled.section`
grid-area: select;
display: flex;
justify-content: center;
align-items: center;
`;
export const LeagueName = styled.section`
grid-area: league;
display: flex;
justify-content: flex-start;
align-items: center;
margin: 3px 0px;
span {
padding: 8px;
font-family: Poppins;
font-size: 12px;
font-weight: 400;
}
`;<file_sep>/src/redux/actions/appCreation.js
export const SET_APP_INFO = 'SET_APP_INFO';
export function setAppCreationInfo(data) {
return {
type: SET_APP_INFO,
action : data
};
}
<file_sep>/src/containers/Users/components/VectorMap/index.jsx
import React from 'react';
import { Col, Container, Row } from 'reactstrap';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import Map from './components/Map';
const VectorMap = ({ t }) => (
<Map />
);
VectorMap.propTypes = {
t: PropTypes.func.isRequired,
};
export default translate('common')(VectorMap);
<file_sep>/src/shared/components/BetContainer/index.js
import React from 'react';
import { connect } from "react-redux";
import { ButtonBase, Dialog, DialogContent, Button } from '@material-ui/core';
import { Row, Col } from 'reactstrap';
import _ from 'lodash';
import { Link } from 'react-router-dom';
import AnimationNumber from '../../../containers/UI/Typography/components/AnimationNumber';
import { CloseIcon, ArrowTopRightIcon, TableIcon, JsonIcon } from 'mdi-react';
import { DialogHeader, CloseButton, Title } from './styles';
import moment from 'moment';
import { CSVLink } from 'react-csv';
import { Button as MaterialButton } from "@material-ui/core";
import { export2JSON } from '../../../utils/export2JSON';
class BetContainer extends React.Component {
constructor() {
super();
this.state = {
open: false,
bet: {},
isLoading: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { bet } = props;
if (!_.isEmpty(this.state.bet)) {
if (!_.isEmpty(bet)) {
this.setState({
bet: bet
})
} else {
this.setState({
bet: {}
})
}
}
}
setOpen = async () => {
const { bet } = this.props;
if (_.isEmpty(this.state.bet)) {
if (!_.isEmpty(bet)) {
this.setState({
bet: bet,
open: true
})
}
}
}
setClose = () => {
this.setState({
open: false,
bet: {}
})
}
render() {
const { open, bet } = this.state;
const { _id, game, user, currency, betAmount, winAmount, creation_timestamp, serverSeed, clientSeed, serverHashedSeed } = bet;
let csvData = [{}];
let jsonData = [];
let headers = []
if (!_.isEmpty(user)) {
const data = [
{
_id: _id,
game: game.name,
user: user.username,
currency: currency.name,
betAmount: betAmount ? parseFloat(betAmount).toFixed(6) : 0,
winAmount: winAmount ? parseFloat(winAmount).toFixed(6) : 0,
creation_timestamp: creation_timestamp,
serverSeed: serverSeed,
clientSeed: clientSeed,
serverHashedSeed: serverHashedSeed
}
]
headers = [
{ label: "Id", key: "_id" },
{ label: "Game", key: "game" },
{ label: "User", key: "user" },
{ label: "Currency", key: "currency" },
{ label: "Bet Amount", key: "betAmount" },
{ label: "Win Amount", key: "winAmount" },
{ label: "Created At", key: "creation_timestamp" },
{ label: "Server Seed", key: "serverSeed" },
{ label: "Client Seed", key: "clientSeed" },
{ label: "Server Hashed Seed", key: "serverHashedSeed" }
];
if (!_.isEmpty(data)) {
csvData = data.map(row => ({...row, creation_timestamp: moment(row.creation_timestamp).format("lll")}));
jsonData = csvData.map(row => _.pick(row, ['_id', 'game', 'user', 'currency', 'betAmount', 'winAmount', 'creation_timestamp', 'serverSeed', 'clientSeed', 'serverHashedSeed']));
}
}
return(
<>
<ButtonBase onClick={this.setOpen}>
{this.props.children}
</ButtonBase>
{ !_.isEmpty(bet) ?
<Dialog
// disableBackdropClick
open={open}
onClose={this.setClose}
>
<DialogHeader style={{ paddingBottom: 0 }}>
<div style={{ display: "flex", justifyContent: "flex-start", marginRight: 20 }}>
<CSVLink data={csvData} filename={"bet.csv"} headers={headers}>
<MaterialButton variant="contained" size="small" style={{ textTransform: "none", backgroundColor: "#008000", color: "#ffffff", boxShadow: "none", margin: 10}}>
<TableIcon style={{marginRight: 7}}/> CSV
</MaterialButton>
</CSVLink>
<MaterialButton onClick={() => export2JSON(jsonData, "bet")} variant="contained" size="small" style={{ textTransform: "none", boxShadow: "none", margin: 10}}>
<JsonIcon style={{marginRight: 7}}/> JSON
</MaterialButton>
</div>
<CloseButton onClick={this.setClose}>
<CloseIcon/>
</CloseButton>
</DialogHeader>
<DialogContent style={{ paddingTop: 0, maxWidth: 350 }}>
<Row>
<Col sd={12} md={12} lg={12} style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<img src={game.image_url} style={{ height: 60, width: 60 }}className='user-avatar' alt={game.name}/>
<h5 style={{marginTop : 5}}> {game.name}</h5>
<hr/>
</Col>
<Col sd={12} md={12} lg={12} style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<h5 style={{marginTop : 5}}> {user.username}
</h5>
<p className='text-small'> {creation_timestamp} </p>
<hr/>
</Col>
</Row>
<Row>
<Col sd={12} md={12} lg={6} style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<h5 style={{margin: 5}}>Bet Amount</h5>
<div style={{display: 'flex'}}>
<h5 style={{margin: 5}}>{betAmount.toFixed(6)}</h5>
<img src={currency.image} style={{ width : 25, height : 25}} alt={currency.name}/>
</div>
</Col>
<Col sd={12} md={12} lg={6} style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<h5 style={{margin: 5}}>Win Amount</h5>
<div style={{display: 'flex'}}>
<h5 style={{margin: 5}}>{winAmount.toFixed(6)}</h5>
<img src={currency.image} style={{ width : 25, height : 25}} alt={currency.name}/>
</div>
</Col>
</Row>
<Row style={{ marginTop: 20 }}>
<Col sd={12} md={12} lg={6} style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<h5 style={{margin: 5}}>Server Seed</h5>
<p className='text-small'> {serverSeed} </p>
</Col>
<Col sd={12} md={12} lg={6} style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<h5 style={{margin: 5}}>Client Seed</h5>
<p className='text-small'> {clientSeed} </p>
</Col>
</Row>
<Row style={{ marginTop: 20, paddingBottom: 30 }}>
<Col sd={12} md={12} lg={12} style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<h5 style={{margin: 5}}>Server Hashed Seed</h5>
<div style={{ width: "99%", marginTop: 10 }}>
<p className='text-small' style={{ padding: "0px 20px", overflowWrap: "break-word" }}> {serverHashedSeed} </p>
</div>
</Col>
</Row>
</DialogContent>
</Dialog> : null }
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(BetContainer);<file_sep>/src/containers/Settings/tabs/Components/AddAdminCard.js
import React, { Component } from 'react'
import { Card, CardBody } from 'reactstrap';
import { TextField } from '@material-ui/core';
import LockAdmin from './LockAdmin';
import _ from 'lodash';
import { connect } from 'react-redux';
class AddAdminCard extends Component {
constructor(props){
super(props)
this.state = {
lock: true,
loading: false,
email: null
};
}
onChangeSuperAdmin = () => {
const { super_admin } = this.state.permission;
this.setState({
permission: {...this.state.permission, super_admin: !super_admin } })
}
unlock = () => {
this.setState({ lock: false })
}
lock = () => {
this.setState({ lock: true, email: "" })
}
confirmChanges = async () => {
const { email } = this.state;
const { profile, setAdmins } = this.props;
if (email) {
this.setState({ loading: true });
await profile.addAdmin({ email: email });
await setAdmins();
this.setState({ loading: false });
this.lock();
} else {
this.lock();
}
}
onChangeEmail = _.debounce((email) => {
if (email) {
this.setState({ email: email.replace(/\s/g, "").toLowerCase() })
} else {
this.setState({ email: null })
}
}, 20);
render() {
const { lock, loading, email } = this.state;
return (
<Card className='game-container'>
<CardBody className="dashboard__card-widget" style={{ width: 310, minHeight: 300, padding: "50px 20px", borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<h4 className="bold-text" style={{ marginBottom: 20 }}>Add new admin</h4>
<p className="dashboard__visitors-chart-title" style={{ marginBottom: 20 }}>We will send a confirmation email</p>
<LockAdmin
unlockField={this.unlock}
lockField={this.lock}
confirmChanges={this.confirmChanges}
isLoading={loading}
locked={lock}
add={true}>
<TextField
disabled={lock}
value={email}
style={{ marginBottom: 50 }}
label="E-mail"
id="add-admin"
size="small"
fullWidth
onChange={event => this.onChangeEmail(event.target.value)}
/>
</LockAdmin>
</CardBody>
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(AddAdminCard);<file_sep>/src/containers/Applications/Customization/components/Icons/enumIcons.js
export default [{ position: 0, name: "User Profile" },
{ position: 1, name: "User Group" },
{ position: 2, name: "Chat" },
{ position: 3, name: "LiveChat Crisp" },
{ position: 4, name: "Info" },
{ position: 5, name: "<NAME>" },
{ position: 6, name: "All Bets" },
{ position: 7, name: "Biggest Wins" },
{ position: 8, name: "Leader Board" },
{ position: 9, name: "Latest Wins" },
{ position: 10, name: "Latest Bets" },
{ position: 11, name: "Email" },
{ position: 12, name: "Rules" },
{ position: 13, name: "Sound" },
{ position: 14, name: "Maximize" },
{ position: 15, name: "Security" },
{ position: 16, name: "My Bets" },
{ position: 17, name: "Wallet" },
{ position: 18, name: "Deposits" },
{ position: 19, name: "Withdraws" },
{ position: 20, name: "Affiliates" },
{ position: 21, name: "Preferences" },
{ position: 22, name: "Affiliate Referral" },
{ position: 23, name: "Arrow" },
{ position: 24, name: "Arrow Up" },
{ position: 25, name: "Arrow Down" },
{ position: 26, name: "<NAME>" },
{ position: 27, name: "Copy" },
{ position: 28, name: "Country Restricted" },
{ position: 29, name: "Logout" },
{ position: 30, name: "Undo" },
{ position: 31, name: "Rotate" },
{ position: 32, name: "Casino" }]<file_sep>/src/containers/Applications/components/Wizard/WizardFormThree.jsx
import React from 'react';
import { Button, ButtonToolbar, Container, Row, Col, CardBody, Card } from 'reactstrap';
import _ from 'lodash';
import { Field, reduxForm } from 'redux-form';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import { Progress } from 'reactstrap';
import { ETHEREUM_NET_DEFAULT } from '../../../../config/apiConfig';
import { AddressConcat } from '../../../../lib/string';
import TextInput from '../../../../shared/components/TextInput';
import { DirectionsIcon } from 'mdi-react';
import appCreationConfig from '../../../../config/appCreation';
const loading = `${process.env.PUBLIC_URL}/img/loading.gif`;
const defaultProps = {
progress : 0
}
class WizardFormThree extends React.Component{
constructor(props){super(props); this.state = defaultProps}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
}
currencyBox = (object) => {
const { type, ticker, image, address, decimals } = object;
const { appCreation } = this.props;
let isSet = (appCreation[`${type.toLowerCase()}`] && (appCreation[`${type.toLowerCase()}`].ticker == ticker));
if(!isSet){return null};
return (
<Card>
<div className='landing__product__widget__small'>
<div className='description'>
<h4> {type}</h4>
<p> {ticker} </p>
<a target={'__blank'} className='ethereum-address-a' href={`https://${ETHEREUM_NET_DEFAULT}.etherscan.io/token/${address}`}>
<p className="ethereum-address-name"> <DirectionsIcon className='icon-ethereum-address'/>
{AddressConcat(address)}
</p>
</a>
<span> {decimals} Decimals </span>
</div>
<img className='image_widget' src={image}></img>
</div>
</Card>
)
}
blockchainBox = (object) => {
const { type, ticker, image, name } = object;
const { appCreation } = this.props;
let isSet = (appCreation[`${type.toLowerCase()}`] && (appCreation[`${type.toLowerCase()}`].ticker == ticker));
if(!isSet){return null};
return (
<Card>
<div className='landing__product__widget__small'>
<div className='description'>
<h4> {type}</h4>
<p> {name} </p>
</div>
<img className='image_widget' src={image}></img>
</div>
</Card>
)
}
render = () => {
const { isLoading, deployApp, blockchains, currencies, authorizedAddress, deploymentState, progress } = this.props;
return(
<div style={{width : '80%'}}>
<div className="dashboard__visitors-chart" >
<h3 className="dashboard__visitors-chart-title" style={{marginTop : 30, textAlign : 'center'}}> Complete </h3>
</div>
<Row>
<Col md={6}>
<Card>
<Container>
<h4>
Blockchain Platform
</h4>
<Row>
{blockchains.map( (token) => {
let image = appCreationConfig['blockchains'][new String(token.ticker).toLowerCase()].image;
if(!image){return null}
return (
<Col lg={4}>
{this.blockchainBox({type : 'Blockchain', ticker : token.ticker, name : token.name, image : image})}
</Col>
)
})}
</Row>
</Container>
</Card>
</Col>
<Col md={6}>
<Card>
<Container>
<h4>
Currency
</h4>
<Row>
{currencies.map( (token) => {
return (
<Col lg={4}>
{this.currencyBox({type : 'Currency', ticker : token.ticker, address : token.address, decimals : token.decimals, image : token.image})}
</Col>
)
})}
</Row>
</Container>
</Card>
</Col>
</Row>
<Row>
<Col md={12}>
<Card>
<Container>
<h4>
Platform Authorized Croupier
</h4>
<Row>
<Col lg={4}>
<Card>
<div className='landing__product__widget__small'>
<div className='description'>
<h5> {authorizedAddress} </h5>
<p> This Address will manage your App via @BetProtocol </p>
</div>
</div>
<h6> You can change this Address later </h6>
</Card>
</Col>
</Row>
</Container>
</Card>
</Col>
</Row>
<div>
<h4 style={{marginTop : 20, marginBottom : 40}} className={"dashboard__total-stat"}>
{parseInt(progress)}% {deploymentState}
</h4>
<div className="progress-wrap">
<Progress value={progress} style={{width : 100}} />
</div>
</div>
<ButtonToolbar style={{margin : 'auto'}} className="form__button-toolbar wizard__toolbar">
<Button style={{margin : 'auto'}} color="secondary" type="button" className="previous" onClick={ () => this.props.previousPage()}>Back</Button>
<Button disabled={isLoading} style={{margin : 'auto'}} color="primary" type="submit" className="next" onClick={ () => deployApp()}>
{ !isLoading ? 'Create Application' : <img src={loading} className={'loading_gif'}></img> }
</Button>
</ButtonToolbar>
</div>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
appCreation: state.appCreation
};
}
export default compose(reduxForm({
form: 'wizard', // <------ same form name
}), connect(mapStateToProps))(WizardFormThree);
<file_sep>/src/containers/Developers/components/TableKey.js
/* eslint-disable react/no-unused-state,react/no-unescaped-entities */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col } from 'reactstrap';
class TableKey extends PureComponent {
constructor(props) {
super(props);
}
onChangePage = (pageOfItems) => {
this.setState({ pageOfItems });
};
render() {
const { type, value } = this.props;
return (
<Col md={12} lg={12}>
<Card>
<CardBody style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<div className="card__title">
<h5 className="bold-text">{type}</h5>
</div>
<hr></hr>
<h6>
{value}
</h6>
</CardBody>
</Card>
</Col>
);
}
}
export default TableKey;<file_sep>/src/containers/Wallet/components/paths/FreeCurrencyAddOn/index.js
import React from 'react';
import { connect } from 'react-redux';
import EditLock from '../../../../Shared/EditLock';
import _ from 'lodash';
import './styles.css';
import { Container, InputAddOn, Label, TextField } from './styles';
import BooleanInput from '../components/utils/BooleanInput';
import { AlertCircleOutlineIcon } from 'mdi-react';
import { FormLabel } from '@material-ui/core';
import { InputGroup, InputGroupAddon } from 'reactstrap';
const labelStyle = {
fontFamily: "Poppins",
fontSize: 15,
color: "#646777"
}
class FreeCurrencyAddOn extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: false,
locked: true,
loadingConversion: false,
anchorEl: null,
selectingAbsolute: false,
selectingRatio: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { profile, wallet } = props;
const { currency } = wallet;
const freeCurrency = profile.App.params.addOn.freeCurrency;
const currentWallet = freeCurrency.wallets.find(wallet => wallet.currency === currency._id);
const { activated, time, value, _id, multiplier } = currentWallet;
this.setState({
activated: activated,
currency: currency,
time: time / 60000,
value: value,
multiplier: multiplier,
_id: _id
})
}
unlock = () => {
this.setState({ locked: false });
}
lock = () => {
this.setState({ locked: true });
}
getCurrencyImage = ({ id }) => {
const { profile } = this.props;
const wallet = profile.App.params.wallet;
const currency = wallet.find(c => c.currency._id === id);
return currency.image;
}
onChangeIsValid = () => {
const { isValid } = this.state;
this.setState({
isValid: !isValid
})
}
onChangeTime = value => {
this.setState({ time: value ? value : null })
}
onChangeMultiplier = value => {
this.setState({ multiplier: value ? value : null })
}
onChangeValue = value => {
this.setState({ value: value ? value : null })
}
handleChangeActive = value => {
this.setState({ activated: value })
}
confirmChanges = async () => {
const { activated, currency, time, value, multiplier } = this.state;
const { profile } = this.props;
if (!time || !value || !multiplier || time < 1) {
this.setState({ isLoading: false, locked: true });
this.projectData(this.props);
} else {
this.setState({ isLoading: true });
await profile.getApp().editFreeCurrency({
activated: activated,
currency: currency._id,
time: time * 60000,
value: parseFloat(value),
multiplier: parseFloat(multiplier)
});
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({
isLoading: false,
locked: true
});
}
}
render() {
const { locked, isLoading, currency, activated, time, value, multiplier } = this.state;
if (_.isEmpty(currency)) return null;
return (
<Container>
<EditLock
unlockField={this.unlock}
lockField={this.lock}
confirmChanges={this.confirmChanges}
isLoading={isLoading}
locked={locked}>
<div style={{ margin: "10px 0px" }}>
<FormLabel component="legend" style={labelStyle}>{ activated ? "Active" : "Inactive" }</FormLabel>
<BooleanInput
checked={activated}
onChange={() => this.handleChangeActive(!activated)}
disabled={locked || isLoading}
type={'isActive'}
id={'isActive'}
/>
</div>
<hr/>
<Label>Time in minutes</Label>
<TextField placeholder="" disabled={locked} value={time} type="number" onChange={(e) => this.onChangeTime(e.target.value)}/>
<br/>
<Label>Amount</Label>
<InputGroup>
<InputGroupAddon addonType="prepend">
<InputAddOn>
<img className='application__game__image' style={{ display: 'block', marginLeft: 0, marginRight: 0, height: 20, width: 20 }} src={currency.image} alt={currency.name}/>
</InputAddOn>
</InputGroupAddon>
<TextField disabled={locked} value={value} type="number" onChange={(e) => this.onChangeValue(e.target.value)}/>
</InputGroup>
<br/>
<Label>Multiplier</Label>
<TextField placeholder="" disabled={locked} value={multiplier} type="number" onChange={(e) => this.onChangeMultiplier(e.target.value)}/>
<br/>
<div style={{ display: "flex", justifyContent: "flex-end", alignItems: "center" }}>
{ time && value ? <span>{`${value} ${currency.ticker} after each ${time} minutes`}</span> : <span>Invalid time or amount</span> }
<AlertCircleOutlineIcon size={18} style={{ marginLeft: 5 }}/>
</div>
</EditLock>
</Container>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(FreeCurrencyAddOn);<file_sep>/src/containers/Wallet/components/LiquidityWalletContainer/index.js
import React, { Component } from 'react'
import { Container, Header, Content, CurrenciesTabContainer, TabsContainer, StyledNavLink, WalletContainer, WalletDetails } from './styles'
import { Nav, NavItem, TabContent, TabPane } from 'reactstrap';
import classnames from 'classnames';
import { connect } from 'react-redux';
import _ from 'lodash';
import WalletTabs from '../WalletTabs';
import { Grid, ButtonBase } from '@material-ui/core';
const Wallet = ({ data }) => {
const { image, currency, playBalance } = data;
return (
<>
<ButtonBase>
<WalletContainer>
<img className='application__game__image' style={{ display: 'block', marginLeft: 0, marginRight: 0, height: 50, width: 50 }} src={image} alt={currency.name}/>
<WalletDetails>
<h3>{`${currency.name} Wallet`}</h3>
<span>{playBalance.toFixed(2)}</span>
</WalletDetails>
</WalletContainer>
</ButtonBase>
</>
)
}
class LiquidityWalletContainer extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { wallets } = props;
if (!_.isEmpty(wallets)) {
this.setState({
wallets: wallets,
activeTab: wallets[0]._id
})
}
}
toggle = (tab) => {
if (this.state.activeTab !== tab) {
this.setState({
activeTab: tab
});
}
}
render() {
const { wallets } = this.state;
if (!wallets) return null;
return (
<div style={{ margin: 10 }}>
<Container>
<Header>
<h3>Application</h3>
<p>Current Liquidity</p>
</Header>
<Content>
<Grid container direction="row" spacing={4}>
<Grid item xs>
<CurrenciesTabContainer>
<Nav vertical pills>
{wallets.map(wallet => (
<NavItem style={{ height: 80, margin: "20px 0px" }}>
<StyledNavLink
className={classnames({ active: this.state.activeTab === wallet._id })}
onClick={() => {
this.toggle(wallet._id);
}}
>
<Wallet data={wallet}/>
</StyledNavLink>
</NavItem>
))}
</Nav>
</CurrenciesTabContainer>
</Grid>
<Grid item lg="8" md="12" xs="12">
<TabsContainer>
<TabContent activeTab={this.state.activeTab}>
{wallets.map(wallet => (
<TabPane tabId={wallet._id}>
<WalletTabs wallet={wallet}/>
</TabPane>))}
</TabContent>
</TabsContainer>
</Grid>
</Grid>
</Content>
</Container>
</div>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(LiquidityWalletContainer);<file_sep>/src/containers/Transactions/components/TransactionsOpen.jsx
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col, Row } from 'reactstrap';
import AnimationNumber from '../../UI/Typography/components/AnimationNumber';
import Numbers from '../../../services/numbers';
const loading = `${process.env.PUBLIC_URL}/img/loading.gif`;
class TransactionsOpen extends PureComponent {
constructor(props) {
super(props);
this.state = {
activeIndex: 0,
isLoading : false
};
}
allowWithdrawAll = async () => {
this.setState({...this.state, isLoading : true})
await this.props.allowWithdrawAll();
this.setState({...this.state, isLoading : false})
}
render() {
let withdraws = this.props.data.data;
let openWithdraws = withdraws.reduce( (acc, w) => {
if(w.status == 'Queue'){
return acc + 1;
}else{
return acc;
}
}, 0)
const disabled = this.state.isLoading || (openWithdraws == 0);
return (
<Col md={12} xl={12} lg={12} xs={12}>
<Card>
<CardBody className="dashboard__card-widget" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<Row>
<Col md={4}>
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-number-second" style={
{color : openWithdraws >= 0 ? '#76d076' : '#646777'}
}><AnimationNumber decimals={0} number={openWithdraws}/></p>
</div>
</Col>
</Row>
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-title"> On Queue Withdraws <span> All </span></p>
</div>
</CardBody>
</Card>
</Col>
);
}
}
export default TransactionsOpen;
<file_sep>/src/containers/Applications/GameStore/index.js
import React from 'react';
import { Grid } from '@material-ui/core';
import Skeleton from '@material-ui/lab/Skeleton';
import _ from 'lodash';
import { compose } from 'lodash/fp';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import { connect } from "react-redux";
import { Card, CardBody, Col } from 'reactstrap';
import GameStoreContainer from './Game';
const defaultState = {
ecosystemGames : [],
appGames : [],
isLoading: false
}
class GameStorePageContainer extends React.Component{
constructor(props){
super(props)
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
let { profile } = props;
this.setState({
isLoading: true
})
let ecosystemGames = await profile.getApp().getEcosystemGames();
if(!(await profile.getApp().getSummaryData('gamesInfo').data)){return null}
let appGames = (await profile.getApp().getSummaryData('gamesInfo')).data.data.message;
ecosystemGames = ecosystemGames.map( ecoGame => {
let exists = false;
appGames.map( appGame => {
if(appGame.metaName == ecoGame.metaName){
exists = true;
};
})
if(!exists){return ecoGame}
else{ return {...ecoGame, isAdded : true}}
}).filter(el => el != null);
this.setState({...this.state,
ecosystemGames,
appGames,
isLoading: false
})
}
addGame = async game => {
const { profile } = this.props;
await profile.getApp().addGameToPlatform({game : game._id});
await profile.setGameDataAsync();
await this.projectData(this.props)
}
render = () => {
const { ecosystemGames, isLoading } = this.state;
const { loading } = this.props;
const games = ecosystemGames.filter(game => game.isValid);
if ((_.isEmpty(games) && isLoading) || loading) {
return (
<div>
<Grid container direction="row" justify="flex-start" alignItems="flex-start">
{_.times(7, () => (
<Grid item xs>
<Col md={12} xl={12} lg={12} xs={12} style={{ minWidth: 288, maxWidth: 415, height: 230 }}>
<Card className='game-container'>
<CardBody className="dashboard__card-widget" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<Grid container direction='row' spacing={1}>
<Grid item xs={3}>
<Skeleton variant="circle" width={50} height={50} style={{ marginBottom: 10, marginLeft: 'auto', marginRight: 0 }}/>
</Grid>
<Grid item xs={9}>
<Skeleton variant="rect" width="60%" height={30} style={{ marginTop: 10, marginBottom: 10 }}/>
<Skeleton variant="rect" width="100%" height={20} style={{ marginTop: 10, marginBottom: 20 }}/>
</Grid>
</Grid>
<Skeleton variant="rect" width="30%" height={30} style={{ marginBottom: 10 }}/>
</CardBody>
</Card>
</Col>
</Grid>
))}
</Grid>
</div>
)
}
return (
<div>
<Grid container direction="row" justify="flex-start" alignItems="flex-start">
{games.map(game => {
return (
<Grid item xs>
<GameStoreContainer
game={game}
isAdded={game.isAdded}
onClick={this.addGame}
/>
</Grid>
)
})}
</Grid>
</div>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
loading: state.isLoading
};
}
GameStorePageContainer.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(GameStorePageContainer);
<file_sep>/src/containers/Applications/components/game_images.js
export default {
coinflip : `${process.env.PUBLIC_URL}/img/dashboard/coinflip.png`,
roulette : `${process.env.PUBLIC_URL}/img/dashboard/roulette.png`,
linear_dice : `${process.env.PUBLIC_URL}/img/dashboard/linear_dice.png`,
default : `${process.env.PUBLIC_URL}/img/dashboard/default-game.png`
}
<file_sep>/src/containers/Applications/Customization/components/Languages/styles.js
import styled from 'styled-components';
import { Input, InputGroupText, Label } from 'reactstrap';
export const LanguageCard = styled.section`
width: 100%;
min-width: 230px;
border-radius: 10px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #fafcff;
box-shadow: none;
padding: 15px;
`;
export const LanguageCardContent = styled.section`
display: flex;
flex-direction: column;
align-items: center;
h1 {
font-family: Poppins;
font-size: 20px;
}
span {
font-display: Poppins;
font-size: 14px;
}
`;
export const LanguageImage = styled.section`
height: 50%;
width: 60%;
padding: 5px;
border: solid 2px rgba(164, 161, 161, 0.35);
border-radius: 6px;
border-style: dashed;
margin-bottom: 10px;
`;
export const InputField = styled(Input)`
margin: 12px 0px;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #FFFFFF;
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
margin-top: 0px;
width: 100%;
`;
export const InputLabel = styled(Label)`
font-size: 14px;
font-family: Poppins;
`;
export const InputAddOn = styled(InputGroupText)`
margin: 12px 0px;
border-radius: 6px;
border: solid 1px rgba(164, 161, 161, 0.35);
background-color: #FFFFFF;
height: 35px;
border-right: none;
span {
font-family: Poppins;
font-size: 14px;
line-height: 24px;
color: #828282;
margin-right: 10px;
}
`;
export const Title = styled.h1`
font-family: Poppins;
font-size: 18px;
font-weight: 600;
`;<file_sep>/src/containers/Applications/EsportsPage/components/VideogameTab/index.js
import React from 'react';
import { connect } from 'react-redux';
import { Container, Tab, Select, Videogame, Dropdown, VideoGameImage, VideoGameIcon, VideogameName, SubTabContainer, SubTab, SubTabSelect, LeagueName } from './styles';
import _ from 'lodash';
import { ChevronUpIcon, ChevronDownIcon } from 'mdi-react';
import { ButtonBase, Checkbox, createMuiTheme, ThemeProvider } from '@material-ui/core';
const theme = createMuiTheme({
palette: {
primary: {
main: '#3399ff'
}
},
});
class VideogameTab extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {},
open: false,
selected: false,
selectedSeries: {}
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { data } = props;
if (!_.isEmpty(data)) {
this.setState({
data: data
})
}
}
toggleSelected = () => {
const { selected, open } = this.state;
this.setState({
selected: !selected,
open: !open
})
}
toggleDropdown = () => {
const { open } = this.state;
this.setState({
open: !open
})
}
getSerieName = (serie) => {
const { league } = serie;
return `${league.name} / ${serie.full_name}`;
}
render() {
const { toggleSelected, toggleSelectedSerie, selectedVideogames, seriesSelected, isLoading } = this.props;
const { data, open, selected } = this.state;
const { _id, name, icon, series } = data;
if (_.isEmpty(data)) return null;
return (
<>
<Container>
<Tab>
<Select>
<ThemeProvider theme={theme}>
<Checkbox
checked={selectedVideogames.includes(_id) && !_.isEmpty(seriesSelected)}
onChange={() => toggleSelected(_id)}
inputProps={{ 'aria-label': 'primary checkbox' }}
color="primary"
disabled={ _.isEmpty(series) || isLoading }
/>
</ThemeProvider>
</Select>
<ButtonBase disableRipple style={{ margin: 0, padding: 0, display: 'block' }} onClick={this.toggleSelected} disabled={_.isEmpty(series)}>
<Videogame style={{ opacity: _.isEmpty(series) ? 0.5 : 1 }}>
<VideoGameImage>
<VideoGameIcon>
{ icon }
</VideoGameIcon>
</VideoGameImage>
<VideogameName selected={selected || ( selectedVideogames.includes(_id) && !_.isEmpty(seriesSelected) )}>
<span>{ name }</span>
{ selected || ( selectedVideogames.includes(_id) && !_.isEmpty(seriesSelected) ) ? <span style={{ margin: '0px 8px' }}>{ seriesSelected ? seriesSelected.length : 0 }</span> : null }
</VideogameName>
</Videogame>
</ButtonBase>
<Dropdown>
<ButtonBase disableRipple onClick={this.toggleDropdown} disabled={_.isEmpty(series)} style={{ opacity: _.isEmpty(series) ? 0.5 : 1 }}>
{ open ? <ChevronDownIcon/> : <ChevronUpIcon/> }
</ButtonBase>
</Dropdown>
{ open ? <SubTabContainer>
{ series.map(serie => (
<SubTab>
<SubTabSelect>
<ThemeProvider theme={theme}>
<Checkbox
size="small"
checked={ seriesSelected ? seriesSelected.includes(serie.id) : false }
onChange={() => toggleSelectedSerie({ videogame_id: _id, serie_id: serie.id })}
inputProps={{ 'aria-label': 'primary checkbox' }}
color="primary"
disabled={isLoading}
/>
</ThemeProvider>
</SubTabSelect>
<LeagueName>
<span>
{ this.getSerieName(serie) }
</span>
</LeagueName>
</SubTab>
))}
</SubTabContainer> : null }
</Tab>
</Container>
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(VideogameTab);<file_sep>/src/shared/components/DateInput.js
import React, { PureComponent } from 'react';
import TextField from '@material-ui/core/TextField';
class DateInput extends PureComponent {
constructor(props) {
super(props);
this.state = {
showPassword: false,
};
}
changeContent = (type, item) => {
if(this.props.changeContent){
this.props.changeContent(type, item)
}
}
render() {
const { label, defaultValue } = this.props;
return (
<TextField
id="time"
type="time"
label={'Hours:Minutes'}
defaultValue={defaultValue}
onChange={(e) => this.changeContent(this.props.name, e.target.value)}
InputLabelProps={{
shrink: true,
}}
inputProps={{
step: 300, // 5 min
}}
/>
);
}
}
export default DateInput
<file_sep>/src/containers/Settings/tabs/TokenManager.js
import React from 'react';
import { Col, Container, Row, Card, CardBody, Button } from 'reactstrap';
import { connect } from "react-redux";
import _ from 'lodash';
import { UpdateIcon, DirectionsIcon } from 'mdi-react';
import { Progress } from 'reactstrap';
import Numbers from '../../../services/numbers';
import { ETHERSCAN_URL } from '../../../lib/etherscan';
import { AddressConcat } from '../../../lib/string';
const loading = `${process.env.PUBLIC_URL}/img/loading.gif`;
const DEPLOYMENT_CONFIG = {
none : {
isSet : true,
message : 'Ready for Updating'
},
pauseContract : {
isSet : false,
message : 'Pausing Contract'
},
withdrawAllFunds : {
isSet : false,
message : 'Withdrawing the Funds to Contract Transfer'
},
deployContract : {
isSet : false,
message : 'Smart-Contract Deployment being done...'
},
authorizeAddress : {
isSet : false,
message : 'Authorize Address to Control the App'
},
authorizeCroupier : {
isSet : false,
message : 'Authorize Croupier Address'
},
moveFundsToNewContract : {
isSet : false,
message : 'Move Funds to New Contract'
},
done : {
isSet : false,
message : 'Done with Success!'
},
}
const defaultState = {
isPaused : false,
locks : {},
tokens : [],
currencyTicker : 'N/A',
locks : {
},
progress : 0,
deploymentConfig : DEPLOYMENT_CONFIG,
deploymentState : DEPLOYMENT_CONFIG['none'].message,
isLoading : false
}
class TokenManager extends React.Component{
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
const { profile } = this.props;
let currencyTicker = props.profile.getApp().getCurrencyTicker();
let isPaused = await props.profile.getApp().isPaused();
let totalAmount = await props.profile.getApp().totalDecentralizedLiquidity();
const tokens = (await profile.getApp().getEcosystemVariables()).data.message.currencies;
console.log(tokens)
this.setState({...this.state,
currencyTicker,
isPaused,
tokens,
totalAmount
})
}
onChange = ({type, value}) => {
this.setState({...this.state, [`new_${type}`] : value })
}
unlockField = ({field}) => {
this.setState({...this.state, locks : {...this.state.locks, [field] : false }})
}
lockField = ({field}) => {
this.setState({...this.state, locks : {...this.state.locks, [field] : true }})
}
updateToken = async ({token}) => {
var { profile } = this.props;
this.setState({...this.state, isLoading : true});
await profile.getApp().changeTokenAddress({token : token});
/* Update All Info */
await profile.getApp().updateAppInfoAsync();
await profile.update();
this.setState({...this.state, isLoading : false});
this.projectData(this.props);
return;
}
renderCurrencyBox = (token, isSet=true) => {
return (
<div style={{height : 'auto'}}>
<Card>
<div style={{margin : 0}} className='landing__product__widget__small'>
<div className='description'>
<h4> {token.name}</h4>
<p> {token.ticker} </p>
<a target={'__blank'} className='ethereum-address-a' href={`${ETHERSCAN_URL}/token/${token.address}`}>
<p className="ethereum-address-name"> <DirectionsIcon className='icon-ethereum-address'/>
{AddressConcat(token.address)}
</p>
</a>
<span> {token.decimals} Decimals </span>
</div>
<img className='image_widget' src={token.image}></img>
</div>
</Card>
{!isSet ?
<Button color={'primary'} disabled={this.state.isLoading} onClick={() => this.updateToken({token})} className="icon" outline>
{!this.state.isLoading ?
<p><UpdateIcon className="deposit-icon"/> Change to {token.ticker} </p>
:
<img src={loading} style={{width : 20, height : 20}}/>
}
</Button>
: null}
</div>
)
}
render = () => {
const { deploymentState, progress, tokens, currencyTicker } = this.state;
const token = tokens.find( t => t.ticker.toLowerCase() == currencyTicker.toLowerCase());
const unlistedTokens = tokens.filter(t => t.ticker.toLowerCase() != currencyTicker.toLowerCase());
if(!token){return null}
return (
<div>
<p className="dashboard__visitors-chart-title text-left" style={{fontSize : 18, marginBottom : 10}}> Current Token Bank </p>
<p className='text-grey'> Your Bank token works as the cold storage currency behind all the ecosystem, after the change you should manipulate the trade of the bank tokens manually to the new ones </p>
<p> ALERT : Change at your own risk, please contact our team if you do have any questions, don´t do anything without understanding the full protocol </p>
<hr></hr>
<Row>
<Col>
{this.renderCurrencyBox(token)}
</Col>
</Row>
<p className="dashboard__visitors-chart-title text-left text-red" style={{fontSize : 18, marginBottom : 10}}> Available Bank Tokens </p>
<hr></hr>
<Row>
{unlistedTokens.map( t => {
return (
<Col md={3}>
{this.renderCurrencyBox(t, false)}
</Col>
)
})}
</Row>
</div>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(TokenManager);
<file_sep>/src/containers/Applications/EsportsPage/components/Enums/videogames.js
import React from 'react';
import { LoL, CSGO, Dota, Overwatch, RocketLeague, CoD, RainbowSix } from '../Icons';
export default Object.freeze({
"1": { name: 'League of Legends', indicatorColor: '#2c7888', icon: <LoL/> },
"3": { name: 'CS:GO', indicatorColor: '#333333', icon: <CSGO/> },
"4": { name: 'Dota 2', indicatorColor: '#ed5565', icon: <Dota/> },
"14": { name: 'Overwatch', indicatorColor: '#ffb333', icon: <Overwatch/> },
"22": { name: 'Rocket League', indicatorColor: '#0168bd', icon: <RocketLeague/> },
"23": { name: 'Call of Duty', indicatorColor: '#887a5e', icon: <CoD/> },
"24": { name: 'Rainbow Six', indicatorColor: '#333333', icon: <RainbowSix/> },
}) <file_sep>/src/containers/Applications/EsportsPage/components/MarketsPage/index.js
import React from 'react';
import { connect } from 'react-redux';
import { MarketsContainer } from './styles';
import _ from 'lodash';
import WinnerTwoWay from './components/WinnerTwoWay';
import WinnerThreeWay from './components/WinnerThreeWay';
class MarketsPage extends React.Component {
constructor(props) {
super(props);
this.state = {
markets: [],
isLoading: false
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { status, markets, teamOne, teamTwo } = props;
if (!_.isEmpty(markets)) {
this.setState({
status: status,
markets: markets,
teamOne: teamOne,
teamTwo: teamTwo
})
}
}
getWinnerTwoWay = () => {
const { markets } = this.state;
if (!markets) return [];
const market = markets.find(market => market.name === 'Winner 2-Way');
return market ? market.selections : [];
}
getWinnerThreeWay = () => {
const { markets } = this.state;
if (!markets) return [];
const market = markets.find(market => market.name === 'Winner 3-way');
return market ? market.selections : [];
}
render() {
const { markets, status, teamOne, teamTwo } = this.state;
if (_.isEmpty(markets)) return null;
// if (_.isEmpty(teamOne) || _.isEmpty(teamTwo)) return null;
return (
<>
<MarketsContainer>
<WinnerTwoWay selections={this.getWinnerTwoWay()} status={status} teamOneName={teamOne.name} teamTwoName={teamTwo.name}/>
<WinnerThreeWay selections={this.getWinnerThreeWay()} status={status} teamOneName={teamOne.name} teamTwoName={teamTwo.name}/>
</MarketsContainer>
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(MarketsPage);<file_sep>/src/containers/Transactions/index.jsx
import React from 'react';
import Fade from '@material-ui/core/Fade';
import { compose } from 'lodash/fp';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import { connect } from "react-redux";
import { CardBody, Col, Container, Row } from 'reactstrap';
import DataWidget from '../DataWidget/DataWidget';
import TransactionsOpen from './components/TransactionsOpen';
import TransactionsProfile from './components/TransactionsProfile';
import DepositsTable from './components/DepositsTable'
import HorizontalTabs from '../HorizontalTabs'
import WithdrawalsTable from './components/WithdrawalsTable';
class TransactionsContainer extends React.Component{
constructor(props){
super(props)
}
allowWithdraw = async (withdraw) => {
const { profile } = this.props;
await profile.getApp().externalApproveWithdraw({ withdraw });
await profile.getApp().getUsersWithdrawals({ size: 100, offset: 0 });
}
cancelWithdraw = async ({ withdraw }) => {
const { profile } = this.props;
await profile.getApp().externalCancelWithdraw({ withdraw });
await profile.getApp().getUsersWithdrawals({ size: 100, offset: 0 });
}
confirmDeposit = async (depositObject) => {
const { currency, profile } = this.props;
var { transactionHash, amount } = depositObject;
try{
await profile.getApp().updateWallet({amount, transactionHash, currency_id : currency._id});
await profile.getData();
this.projectData(this.props);
}catch(err){
// TO DO : Raise Notification System
throw err;
}
}
render = () => {
const { profile } = this.props;
const app = profile.getApp();
const deposits = app.params.deposits;
const currencies = app.params.currencies;
return (
<Fade in timeout={{ appear: 200, enter: 200, exit: 200 }}>
<Container className="dashboard">
<Row>
<Col lg={3}>
<DataWidget>
<TransactionsProfile data={this.props.profile.getApp().getSummaryData('withdraws')}/>
</DataWidget>
</Col>
<Col lg={3}>
<DataWidget>
<TransactionsOpen data={this.props.profile.getApp().getSummaryData('withdraws')}/>
</DataWidget>
</Col>
</Row>
<Row>
<Col lg={12}>
<CardBody className="dashboard__card-widget" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none", padding: 10 }}>
<HorizontalTabs
padding={false}
tabs={[
{
label : 'Deposits',
tab : <DepositsTable/>
},
{
label : 'Withdrawals',
tab : <WithdrawalsTable cancelWithdraw={this.cancelWithdraw} allowWithdraw={this.allowWithdraw}/>
}
]}
/>
</CardBody>
</Col>
</Row>
</Container>
</Fade>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
currency: state.currency
};
}
TransactionsContainer.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(TransactionsContainer);
<file_sep>/src/containers/Applications/EsportsPage/components/Enums/status.js
export default Object.freeze({
settled: {
text: "Settled",
backgroundColor: "#e7e9ed",
textColor: "#333"
},
canceled: {
text: "Canceled",
backgroundColor: "#5f6e85",
textColor: "#FFFFFF"
},
finished: {
text: "Finished",
backgroundColor: "#ed5565",
textColor: "#FFFFFF"
},
live: {
text: "Live",
backgroundColor: "#7bd389",
textColor: "#FFFFFF"
},
pre_match: {
text: "Pre match",
backgroundColor: "#39f",
textColor: "#FFFFFF"
}
});<file_sep>/src/containers/Wallet/components/paths/DepositWidget.js
import React from 'react';
import { Col, Container, Row } from 'reactstrap';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import { compose } from 'lodash/fp'
import CurrencyBox from './components/CurrencyBox';
import DepositsTable from './deposit/Table';
import _ from 'lodash';
const defaultState = {
ticker : 'N/A',
deposits : []
}
class DepositWidget extends React.Component{
constructor(props){
super(props)
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
if(_.isEmpty(props.profile)){return null}
const { wallet } = props;
const { currency } = wallet;
if(_.isEmpty(wallet)){return null}
let deposits = props.profile.getApp().getDeposits({currency});
let ticker = wallet.currency.ticker;
this.setState({...this.state,
deposits,
ticker
})
}
confirmDeposit = async (depositObject) => {
const { currency } = this.props.wallet;
var { transactionHash, amount } = depositObject;
try{
await this.props.profile.getApp().updateWallet({amount, transactionHash, currency_id : currency._id});
await this.props.profile.getData();
this.projectData(this.props);
}catch(err){
// TO DO : Raise Notification System
throw err;
}
}
disable = () => {
this.setState({...this.state, disabled : true});
}
enable = () => {
this.setState({...this.state, disabled : false});
}
render = () => {
const { wallet, currency } = this.props;
const { deposits, ticker } = this.state;
return (
<Container className="dashboard">
<Col lg={12}>
<h3 style={{marginTop : 20}} className={"bold-text dashboard__total-stat"}>Deposit</h3>
<p className="">
Choose the Amount of Liquidity you want to Deposit
</p>
</Col>
<Row>
<Col lg={5}>
<CurrencyBox data={wallet}/>
</Col>
<Col lg={7}>
<div style={{marginTop : 50}}>
<DepositsTable
disabled={this.state.disabled}
confirmDeposit={this.confirmDeposit}
currency={ticker} data={deposits}
/>
</div>
</Col>
</Row>
</Container>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile,
wallet : state.wallet
};
}
DepositWidget.propTypes = {
t: PropTypes.func.isRequired
};
export default compose(
translate('common'),
connect(mapStateToProps)
)(DepositWidget);
<file_sep>/src/containers/Wallet/components/WalletTabs/Withdraw.js
import React, { Component } from 'react'
import { connect } from 'react-redux';
import { Paragraph } from '../LiquidityWalletContainer/styles';
import { TabContainer, WithdrawContent, AddressInput, AmountInput, InputAddOn, WithdrawButton, ErrorMessage } from './styles';
import _ from 'lodash';
import { InputGroup, InputGroupAddon } from 'reactstrap';
const loading = `${process.env.PUBLIC_URL}/img/loading.gif`;
const withdrawMessage = Object.freeze({
"1": "Asking Withdraw Permission..",
"5": "Done!"
});
class Withdraw extends Component {
constructor(props) {
super(props);
this.state = {
state: null,
error: null,
isLoading: false,
toAddress: null,
amount: null
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { data } = props;
if (!_.isEmpty(data)) {
this.setState({
wallet: data.wallet,
bank_address: data.wallet.bank_address
})
} else {
this.setState({
wallet: {}
})
}
}
onChangeToAddress = value => {
if (value) {
this.setState({
toAddress: value
})
} else {
this.setState({
toAddress: null
})
}
}
onChangeAmount = value => {
if (value) {
this.setState({
amount: parseFloat(value)
})
} else {
this.setState({
amount: null
})
}
}
createTokenWithdraw = async () => {
try{
const { profile } = this.props;
const { amount, toAddress, wallet } = this.state;
const { currency } = wallet;
this.setState({
isLoading: true,
state: "1",
error: null
});
await profile.requestWithdraw({ tokenAmount: amount, currency, toAddress });
this.setState({
isLoading: false,
state: "5",
error: null
});
return true;
}catch(err){
this.setState({
isLoading: false,
error: err.message
});
}
}
render() {
const { wallet, error, toAddress, amount, isLoading, state } = this.state;
if (_.isEmpty(wallet)) return null
const { currency } = wallet;
return (
<>
<TabContainer>
<Paragraph>Choose the amount of Liquidity you want to withdraw</Paragraph>
<WithdrawContent>
<AddressInput placeholder={`Your ${currency.name} address`} name="toAddress" onChange={(e) => this.onChangeToAddress(e.target.value)}/>
<InputGroup>
<InputGroupAddon addonType="prepend">
<InputAddOn>
<span>Amount</span>
<img className='application__game__image' style={{ display: 'block', marginLeft: 0, marginRight: 0, height: 20, width: 20 }} src={wallet.image} alt={currency.name}/>
</InputAddOn>
</InputGroupAddon>
<AmountInput name="amount" onChange={(e) => this.onChangeAmount(e.target.value)}/>
</InputGroup>
<ErrorMessage>
{ error ? <Paragraph style={{ color: "#ec2727" }}>{error}</Paragraph> : null }
</ErrorMessage>
<WithdrawButton variant="contained" disabled={ _.isEmpty(toAddress) || !amount || isLoading } onClick={() => this.createTokenWithdraw()}>
{ isLoading ? <img src={loading} className={'loading_gif'} alt="Loading.."/> : <span>Withdraw</span> }
</WithdrawButton>
{ state ? <Paragraph>{withdrawMessage[state]}</Paragraph> : null }
</WithdrawContent>
</TabContainer>
</>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(Withdraw);
<file_sep>/src/containers/Transactions/components/TransactionsProfile.jsx
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody, Col } from 'reactstrap';
import { BarChart, Bar, Cell, ResponsiveContainer } from 'recharts';
import TrendingUpIcon from 'mdi-react/TrendingUpIcon';
import AnimationNumber from '../../UI/Typography/components/AnimationNumber';
import Numbers from '../../../services/numbers';
class UsersProfile extends PureComponent {
constructor() {
super();
this.state = {
activeIndex: 0,
};
}
handleClick = (index) => {
this.setState({
activeIndex: index,
});
};
render() {
let withdraws = this.props.data.data;
return (
<Col md={12} xl={12} lg={12} xs={12}>
<Card>
<CardBody className="dashboard__card-widget" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-number-second" style={
{color : '#646777'}
}><AnimationNumber decimals={0} number={withdraws.length}/></p>
</div>
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-title"> Total Withdraws <span> All </span></p>
</div>
</CardBody>
</Card>
</Col>
);
}
}
export default UsersProfile;
<file_sep>/src/components/InfoNumericCard/index.js
/* eslint-disable react/no-array-index-key */
import React, { PureComponent } from 'react';
import { Card, CardBody } from 'reactstrap';
import AnimationNumber from '../../containers/UI/Typography/components/AnimationNumber';
const defaultProps = {
title : 'N/A',
amount : 'N/A',
ticker : 'N/A',
subtitle : 'N/A'
}
class InfoNumericCard extends PureComponent {
constructor(props){
super(props);
this.state = { ...defaultProps};
this.projectData(props);
}
componentDidMount(){
this.projectData(this.props)
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = (props) => {
const { title, ticker, amount, subtitle } = props;
this.setState({...this.state,
title,
ticker,
amount,
subtitle
})
}
render() {
const { title, ticker, amount, subtitle} = this.state;
return (
<Card>
<CardBody className="dashboard__card-widget" style={{ borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none" }}>
<div className="dashboard__visitors-chart">
<p className="dashboard__visitors-chart-number-second"
><AnimationNumber decimals={2} number={amount}/>
<span style={ {color : '#646777'}}> {ticker}</span> </p>
</div>
<div className="dashboard__visitors-chart">
<h4 className="dashboard__visitors-chart-title"> {title}</h4>
<p className="dashboard__visitors-chart-title"> {subtitle} </p>
</div>
</CardBody>
</Card>
);
}
}
export default InfoNumericCard;
<file_sep>/src/containers/Account/Register/components/RegisterForm.jsx
import React, { PureComponent } from 'react';
import { Field, reduxForm } from 'redux-form';
import EyeIcon from 'mdi-react/EyeIcon';
import KeyVariantIcon from 'mdi-react/KeyVariantIcon';
import {CheckboxMultipleBlankCircleIcon, AccountOutlineIcon, AccountIcon} from 'mdi-react';
import MailRuIcon from 'mdi-react/MailRuIcon';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import Account from '../../../../controllers/Account';
import TextField from '@material-ui/core/TextField';
import TextInput from '../../../../shared/components/TextInput';
import { FormGroup } from 'reactstrap';
import { InputLabel, EmailInput, PasswordInput } from '../styles';
const queryString = require('query-string');
const loading = `${process.env.PUBLIC_URL}/img/loading.gif`;
const renderTextField = ({
input, label, meta: { touched, error }, children, select, type
}) => (
<TextField
className="material-form__field"
label={label}
error={touched && error}
value={input.value}
children={children}
type={type}
select={select}
onChange={(e) => {
e.preventDefault();
input.onChange(e);
}}
/>
);
renderTextField.propTypes = {
input: PropTypes.shape().isRequired,
label: PropTypes.string.isRequired,
meta: PropTypes.shape({
touched: PropTypes.bool,
error: PropTypes.string,
}),
select: PropTypes.bool,
children: PropTypes.arrayOf(PropTypes.element),
};
renderTextField.defaultProps = {
meta: null,
select: false,
children: [],
};
class RegisterForm extends PureComponent {
static propTypes = {
handleSubmit: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = {
showPassword: false,
isLoading : false
};
this.showPassword = this.showPassword.bind(this);
}
componentDidMount(){
const parsed = queryString.parse(window.location.search);
const queryEmail = parsed ? parsed.email : null;
this.setState({
token : parsed ? parsed.token : null,
queryEmail : queryEmail,
email : queryEmail
});
}
showPassword(e) {
e.preventDefault();
this.setState({
showPassword: !this.state.showPassword,
});
}
onChangeUsername = value => {
if (value) {
this.setState({
username: value
})
} else {
this.setState({
username: null
})
}
}
onChangeName = value => {
if (value) {
this.setState({
name: value
})
} else {
this.setState({
name: null
})
}
}
onChangeEmail = value => {
if (value) {
this.setState({
email: value
})
} else {
this.setState({
email: null
})
}
}
onChangePassword = value => {
if (value) {
this.setState({
password: value
})
} else {
this.setState({
password: null
})
}
}
register = async () => {
try{
this.setState({...this.state, isLoading : true})
let account = new Account(this.state);
await account.register(this.state.token);
if(!this.state.token) {
this.props.history.push('/initial');
} else {
this.props.history.push('/home');
}
this.setState({...this.state, isLoading : false})
}catch(err){
this.props.showNotification(err.message);
}
}
render() {
const { handleSubmit } = this.props;
return (
<form className="form" onSubmit={handleSubmit}>
<div className="form__form-group">
<FormGroup>
<InputLabel for="username">Username</InputLabel>
<EmailInput
label="Username"
name="username"
type="text"
// defaultValue={this.state.username}
onChange={(e) => this.onChangeUsername(e.target.value)}
/>
</FormGroup>
<FormGroup>
<InputLabel for="name">Name</InputLabel>
<EmailInput
label="Name"
name="name"
type="text"
// defaultValue={this.state.name}
onChange={(e) => this.onChangeName(e.target.value)}
/>
</FormGroup>
{/* Admin Registered via email */}
{!this.state.queryEmail ?
<FormGroup>
<InputLabel for="email">E-mail</InputLabel>
<EmailInput
label="E-mail"
name="email"
type="text"
defaultValue={this.state.queryEmail}
onChange={(e) => this.onChangeEmail(e.target.value)}
/>
</FormGroup>
: null}
<FormGroup>
<InputLabel for="password">Password</InputLabel>
<PasswordInput
// icon={KeyVariantIcon}
name="password"
label="Password"
type="password"
onChange={(e) => this.onChangePassword(e.target.value)}
/>
</FormGroup>
</div>
<div className="account__btns">
<button onClick={ () => this.register() }className="btn btn-primary account__btn" to="/dashboard_default"> {
!this.state.isLoading ?
'Sign Up'
:
<img src={loading} className={'loading_gif'}></img>
}
</button>
</div>
</form>
);
}
}
export default reduxForm({
form: 'register_form', // a unique identifier for this form
})(RegisterForm);
<file_sep>/src/esports/api/config.js
export const API_URL = process.env.REACT_APP_API_ESPORTS;
export const config = {
headers: {
'Content-Type' : 'application/json'
},
server: {
development : 'http://localhost:80',
production : 'https://api.betprotocol.com'
}
}
export function addHeaders(config, newHeaders){
return {
...config.headers,
...newHeaders
}
}
<file_sep>/src/containers/Applications/EsportsPage/components/MatchTab/styles.js
import styled from 'styled-components';
export const Container = styled.div`
width: 100%;
`;
export const Tab = styled.div`
width: 100%;
/* min-height: 58px; */
background-color: white;
display: grid;
grid-template-areas:
'indicator game winner';
grid-template-columns: 3px calc(30% - 3px) 70%;
grid-template-rows: 20px;
margin-bottom: 15px;
`;
export const Indicator = styled.section`
grid-area: indicator;
z-index: 10;
margin-left: -1px;
background-color: ${props => props.status === "finished" ? "#ED5565" : "white"};
border-radius: 4px 0 0 4px;
`;
export const Game = styled.section`
grid-area: game;
display: flex;
justify-content: center;
align-items: center;
span {
font-family: Poppins;
font-size: 14px;
font-weight: 400;
color: #5f6e85;
}
`;
export const Winner = styled.section`
grid-area: winner;
display: grid;
grid-template-areas:
'icon team';
grid-template-columns: 20px auto;
grid-template-rows: auto;
`;
export const Icon = styled.section`
grid-area: icon;
display: flex;
justify-content: center;
`;
export const TrophyIcon = styled.section`
height: 8px;
width: 8px;
`;
export const Team = styled.section`
grid-area: team;
display: flex;
justify-content: flex-start;
align-items: center;
span {
font-family: Poppins;
color: #c8c8c8;
font-size: 10px;
overflow: hidden;
text-overflow: ellipsis;
}
`;
<file_sep>/src/services/cache.js
class cache{
/**
* @type Authentication
*/
setToCache = (type, data) => {
localStorage.setItem(type, JSON.stringify(data), {expires : 365});
}
getFromCache = (type) => {
let result = localStorage.getItem(type);
return result ? JSON.parse(result) : null;
}
}
let Cache = new cache();
export default Cache;<file_sep>/src/containers/Applications/Customization/components/Logo.js
import React, { Component } from 'react'
import EditLock from '../../../Shared/EditLock.js';
import { connect } from "react-redux";
import Dropzone from 'react-dropzone';
import { Col, Row, Card, CardBody } from 'reactstrap';
import 'react-alice-carousel/lib/alice-carousel.css';
const image2base64 = require('image-to-base64');
const upload = `${process.env.PUBLIC_URL}/img/dashboard/upload.png`;
const trash = `${process.env.PUBLIC_URL}/img/dashboard/clear.png`;
const defaultState = {
logoItem: "",
faviconItem: "",
loadingGifItem: "",
isLoading: false,
locks : {
logo : true,
favicon : true,
loadingGif : true
}
}
class Logo extends Component {
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.projectData(this.props);
}
onLogoAddedFile = async ({ files }) => {
const file = files[0];
let blob = await image2base64(file.preview)
this.setState({logoItem : blob});
}
onFaviconAddedFile = async ({ files }) => {
const file = files[0];
let blob = await image2base64(file.preview)
this.setState({faviconItem : blob});
}
onLoadingGifAddedFile = async ({ files }) => {
const file = files[0];
let blob = await image2base64(file.preview)
this.setState({loadingGifItem : blob});
}
projectData = async (props) => {
const { logo, topIcon, loadingGif } = props.profile.getApp().getCustomization();
this.setState({...this.state,
logoItem : logo ? logo.id : "",
faviconItem : topIcon ? topIcon.id : "",
loadingGifItem : loadingGif ? loadingGif.id : ""
})
}
renderLogoAddImage = () => {
return(
<div className='dropzone-image' style={{ marginBottom: 40}}>
<Dropzone disabled={this.state.locks.logo} width={200} onDrop={(files) => this.onLogoAddedFile({ files: files })} ref={(el) => (this.dropzoneRef = el)}>
<img src={upload} className='image-info' style={{marginTop : 50}}/>
<p className='text-center'> Drop the Logo here</p>
</Dropzone>
</div>
)
}
renderFaviconAddImage = () => {
return(
<div className='dropzone-image' style={{ marginBottom: 40}}>
<Dropzone disabled={this.state.locks.favicon} width={200} onDrop={(files) => this.onFaviconAddedFile({ files: files })} ref={(el) => (this.dropzoneRef = el)}>
<img src={upload} className='image-info' style={{marginTop : 50}}/>
<p className='text-center'> Drop the Favicon here</p>
</Dropzone>
</div>
)
}
renderLoadingGifAddImage = () => {
return(
<div className='dropzone-image' style={{ marginBottom: 40}}>
<Dropzone disabled={this.state.locks.loadingGif} width={200} onDrop={(files) => this.onLoadingGifAddedFile({ files: files })} ref={(el) => (this.dropzoneRef = el)}>
<img src={upload} className='image-info' style={{marginTop : 50}}/>
<p className='text-center'> Drop the Loading Image here</p>
</Dropzone>
</div>
)
}
removeImage = (src, field) => {
switch(field){
case 'logo' : {
this.setState({logoItem : ""})
break;
};
case 'favicon' : {
this.setState({faviconItem : ""})
break;
}
;
case 'loadingGif' : {
this.setState({loadingGifItem : ""})
break;
}
}
}
renderImage = (src, field) => {
if(!src.includes("https")){
src = "data:image;base64," + src;
}
return (
<div style={{paddingBottom : 20, height : 220, overflow : 'hidden', margin : 'auto'}}>
<button disabled={[field] == 'logo' ? this.state.locks.logo : [field] == 'favicon' ? this.state.locks.favicon : [field] == 'loadingGif' ? this.state.locks.loadingGif : true} onClick={() => this.removeImage(src, field)}
style={{right : 20, top : 6}}
className='carousel-trash button-hover'>
<img src={trash} style={{width : 15, height : 15}}/>
</button>
<img src={src} onDragStart={this.handleOnDragStart}/>
</div>
)
}
onChange = ({type, value}) => {
this.setState({...this.state, [type] : value })
}
unlockField = ({field}) => {
this.setState({...this.state, locks : {...this.state.locks, [field] : false }})
}
lockField = ({field}) => {
this.setState({...this.state, locks : {...this.state.locks, [field] : true }})
}
confirmChanges = async ({field}) => {
var { profile } = this.props;
const { logoItem, faviconItem, loadingGifItem } = this.state;
this.setState({...this.state, isLoading : true});
switch(field){
case 'logo' : {
const postData = {
logo : logoItem
}
await profile.getApp().editLogoCustomization(postData);
break;
};
case 'favicon' : {
const postData = {
topIcon : faviconItem
}
await profile.getApp().editFaviconCustomization(postData);
break;
};
case 'loadingGif' : {
const postData = {
loadingGif : loadingGifItem
}
await profile.getApp().editLoadingGifCustomization(postData);
break;
}
}
this.setState({...this.state, isLoading : false, locks : {...this.state.locks, [field] : true }});
this.projectData(this.props);
}
handleOnDragStart = (e) => e.preventDefault()
render() {
const { isLoading, logoItem, faviconItem, loadingGifItem } = this.state;
return (
<Card>
<CardBody style={{ margin: 10, minWidth: 320, borderRadius: "10px", border: "solid 1px rgba(164, 161, 161, 0.35)", backgroundColor: "#fafcff", boxShadow: "none", padding: 15 }}>
<Row>
<Col md={6}>
<div style={{ border: '1px solid rgba(0, 0, 0, 0.2)', backgroundColor: "white", borderRadius: 8, height: 410, marginBottom: 30, padding: 15 }}>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'logo'}
locked={this.state.locks.logo}>
<div style={{paddingBottom : 20}}>
<h5 className={"bold-text dashboard__total-stat"}>Logo</h5>
<h6>Upload your logo</h6>
</div>
<div style={{margin : 'auto'}}>
{
logoItem && logoItem !== ""?
/* Logo is Set */
this.renderImage(logoItem, 'logo')
:
/* Logo is not Set */
this.renderLogoAddImage()
}
</div>
</EditLock>
</div>
</Col>
<Col md={6}>
<div style={{ border: '1px solid rgba(0, 0, 0, 0.2)', backgroundColor: "white", borderRadius: 8, height: 410, marginBottom: 30, padding: 15 }}>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'favicon'}
locked={this.state.locks.favicon}>
<div style={{paddingBottom : 20}}>
<h5 className={"bold-text dashboard__total-stat"}>Favicon</h5>
<h6>Upload your favicon</h6>
</div>
<div style={{margin : 'auto'}}>
{
faviconItem ?
this.renderImage(faviconItem, 'favicon')
:
this.renderFaviconAddImage()
}
</div>
</EditLock>
</div>
</Col>
</Row>
<Row>
<Col md={6}>
<div style={{ border: '1px solid rgba(0, 0, 0, 0.2)', backgroundColor: "white", borderRadius: 8, height: 410, marginBottom: 30, padding: 15 }}>
<EditLock
isLoading={isLoading}
unlockField={this.unlockField}
lockField={this.lockField}
confirmChanges={this.confirmChanges}
type={'loadingGif'}
locked={this.state.locks.loadingGif}>
<div style={{paddingBottom : 20}}>
<h5 className={"bold-text dashboard__total-stat"}>Loading Image</h5>
<h6>Upload your Loading Image</h6>
</div>
<div style={{margin : 'auto'}}>
{
loadingGifItem ?
this.renderImage(loadingGifItem, 'loadingGif')
:
this.renderLoadingGifAddImage()
}
</div>
</EditLock>
</div>
</Col>
</Row>
</CardBody>
</Card>
)
}
}
function mapStateToProps(state){
return {
profile: state.profile
};
}
export default connect(mapStateToProps)(Logo);
|
d4444d65f74dc13b7fe9f13f8f84357fbeb47372
|
[
"JavaScript",
"Markdown"
] | 230
|
JavaScript
|
bepronetwork/backoffice
|
6f20557cbe0bb598d9727a3a47ce1fb0a26b5e21
|
9e040d6d944631aac8846ba6d103a6a10f9db9f3
|
refs/heads/main
|
<file_sep>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CreateBlogComponent } from './create-blog/create-blog.component';
import { DetailBlogComponent } from './detail-blog/detail-blog.component';
const routes: Routes = [
{
path: 'create', component: CreateBlogComponent
},
{
path: 'details', component: DetailBlogComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
4affcbd554e93853de1efa7126578f8cf88594cc
|
[
"TypeScript"
] | 1
|
TypeScript
|
AbubakarAfzal243/Blogs
|
eb69b7f5eb24eb38360a43eef5c37b960933d687
|
a27af9a464a7dfc81a8a549772cd2d3a0b5a7d03
|
refs/heads/master
|
<repo_name>Saulo23/TrabChat<file_sep>/README.md
# TrabChat
Aluno: <NAME>
Matrícula: 1210802/8
Linguagem de programação utilizada: C#
Link github: https://github.com/Saulo23/TrabChat
Passos para executar:
- Projeto foi executado em ambiente windows 10.
- Possuir o Framework .NET da versão 4.0 até a mais recente.
- Descompactar a pasta
- O arquivo na pasta: \ChatApp\Server\bin\Debug\Server.exe, executa o servidor.
- O arquivo na pasta: ChatApp\client\bin\Debug\client.exe, executa o cliente.
- Após executar o cliente.exe, basta digitar seu nome, como sugere no terminal, e então será conectado na sala de bate papo.
Funções implementadas
- Uma sala de bate papo geral, onde todos os usuários logados podem trocar mensagens entre si;
- Permitir o usuário visualizar os nomes de usuários participantes do chat;
Funções Opcionais
- Utilizar o formato binário no protocolo de comunicação entre cliente e servidor.
<file_sep>/TrabRedesII/client/Client.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServerData;
using System.Net;
using System.IO;
using System.Net.Sockets;
using System.Threading;
namespace client
{
class Program
{
public static Socket clientS;
public static string nome;
public static int status; // 1 = online, 2 = offline
public static string id;
static void Main(string[] args)
{
Console.WriteLine("Digite seu nome: ");
nome = Console.ReadLine();
string ip = Packet.getIp4Address();
clientS = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), 4242 );
try
{
clientS.Connect(ipe);
Console.WriteLine(nome + " parabens, vc conseguiu se conectar com o servidor :)");
}
catch
{
Console.WriteLine("Nao foi possivel conectar com o servidor :(");
Thread.Sleep(1000);
}
Thread t = new Thread(data_IN);
t.Start();
for(;;)
{
Console.Write("::>");
string input = Console.ReadLine();
Packet p = new Packet(PacketType.chat, id);
p.Gdata.Add(nome);
p.Gdata.Add(input);
clientS.Send(p.toBytes());
}
}
static void data_IN()
{
byte[] buffer;
int readBytes;
for(;;)
{
try
{
buffer = new byte[clientS.SendBufferSize];
readBytes = clientS.Receive(buffer);
if (readBytes > 0)
{
DataManager(new Packet(buffer));
}
}
catch (SocketException ex)
{
Console.WriteLine("Servidor perdeu conexao!!");
Console.ReadLine();
Environment.Exit(0);
}
}
}
static void DataManager(Packet p)
{
switch (p.packetType)
{
case PacketType.Registration:
Console.WriteLine("Conectado ao servidor!");
id = p.Gdata[0];
break;
case PacketType.chat:
Console.WriteLine(p.Gdata[0] + ": " + p.Gdata[1]);
break;
}
}
}
}
|
978e5ac6f5ea8dd4e70a671999ac0e8789d5e9cb
|
[
"Markdown",
"C#"
] | 2
|
Markdown
|
Saulo23/TrabChat
|
595c17d902cd2f245e3152341fe9db8ecf39d0aa
|
e8c0007452b4f38e7e33f4f356f623db40e263e8
|
refs/heads/master
|
<file_sep>#!/bin/bash
SEARCHDIR="$1"
OPTIMIZER_SCRIPT="/home/incred/dev/jpgpngoptimizer"
if [ $# -eq 0 ]
then
echo "No arguments"
echo "Usage: $0 directory"
exit 1
fi
find $SEARCHDIR -type f -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" | while read FILE
do
if ! attr -g optimized "$FILE" > /dev/null 2>&1
then
$OPTIMIZER_SCRIPT "$FILE" && \
echo "Seting attribute to: $FILE" && \
attr -s optimized -V yes "$FILE"
fi
done
<file_sep>#!/bin/bash
trap 'echo "Killing process"; kill 0' EXIT
DIR="$1"
LOG="/tmp/inotify_test/log"
# Path to scripts
OPTIMIZER_SCRIPT="/home/incred/dev/jpgpngoptimizer"
FINDNOPTIMIZE_SCRIPT="/home/incred/dev/findimgswithoutattr"
echo "Starting process"
$FINDNOPTIMIZE_SCRIPT $1 &
inotifywait -r -m -q -e create --format %w%f $DIR | while read FILE
do
$OPTIMIZER_SCRIPT "$FILE" && attr -s optimized -V yes "$FILE"
done
<file_sep>#!/bin/bash
FILE="$1"
TMPDIR="/tmp"
TMPFILE="fake"
if [ $# -eq 0 ]
then
echo "No arguments"
echo "Usage: $0 filename"
exit 1
fi
if [[ -e "$FILE" && ${FILE: -4} != ".tmp" ]]
then
TYPE=$(file -b --mime-type "$FILE")
if [[ $TYPE == "image/jpeg" || $TYPE == "image/png" ]]
then
FILENAME=$(basename "$FILE")
TMPFILE="${TMPDIR}/${FILENAME}.tmp"
echo "Copying $FILE to $TMPFILE"
cp -f "$FILE" "$TMPFILE"
fi
else
echo "Skip this file: $FILE"
exit 1
fi
case $TYPE in
"image/jpeg")
echo "New jpeg file: $FILE"
echo "Start processing"
jpegoptim -f --strip-all "$TMPFILE" && \
echo "Success optimize" && \
mv -f "$TMPFILE" "${FILE}".tmp && \
mv -f "${FILE}".tmp "$FILE" && \
chmod 0644 "$FILE" && \
echo "File renamed back from $TMPFILE to $FILE"
;;
"image/png")
echo "New png file: $FILE"
optipng -force -o7 "$TMPFILE" && \
advpng -z4 "$TMPFILE" && \
pngcrush -rem gAMA -rem alla -rem cHRM -rem iCCP \
-rem sRGB -rem time "$TMPFILE" "${TMPFILE}".tmp && \
mv -f "${TMPFILE}".tmp "${FILE}".tmp && \
mv -f "${FILE}".tmp "$FILE" && \
chmod 0644 "$FILE" && \
echo "Renamed back from ${TMPFILE}.tmp to $FILE"
;;
*)
rm -f "$TMPFILE"
exit 1
;;
esac
if [ -e "$TMPFILE" ]
then
rm -f "$TMPFILE" && echo "Temporary file $TMPFILE deleted"
fi
exit 0
<file_sep> ImgsOptimizer
Set of scripts to optimize size of images (jpeg, png) in directory.
It search all png and jpeg files in directory (must be define in init script).
If found file is not marked yet (has no attribute optimized), then script trying
to optimize it and mark it with attribute. Also if any new files appear in the
directory (listen via inotifywait) it try to optimize it.
Requirements:
- jpegoptim;
- optipng;
- advpng (advancecomp);
- pngcrush;
- inotify-tools,
- support of extended file system attributes (mount with user_xattr option).
|
c29a518c43bdc8e44c5563b0f9ba33b25bf655f1
|
[
"Markdown",
"Shell"
] | 4
|
Shell
|
Incred/imgsoptimizer
|
987f7010a762e42bb47b3af08ad1261c4177e9eb
|
aa7f2e99bb406535fa323a806b8a04230e4e25cd
|
refs/heads/master
|
<file_sep>package br.unicamp.ft.d166336_m202618.trashtime.models;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.Cursor;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import br.unicamp.ft.d166336_m202618.trashtime.R;
public class Serie {
private int id, tmdb_code;
private String name, image;
private float grade;
private Date date;
private final String TABLE = "series";
public Serie(int tmdb_code, String name, String image, float grade) {
this.id = 0;
this.tmdb_code = tmdb_code;
this.name = name;
this.image = image;
this.grade = grade;
}
public Serie(int id, int tmdb_code, String name, String image, float grade) {
this.id = id;
this.tmdb_code = tmdb_code;
this.name = name;
this.image = image;
this.grade = grade;
}
public Serie() {
this.id = 0;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTmdb_code() {
return tmdb_code;
}
public void setTmdb_code(int tmdb_code) {
this.tmdb_code = tmdb_code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public String getFormattedImage() {
return "https://image.tmdb.org/t/p/w600_and_h900_bestv2" + image;
}
public void setImage(String image) {
this.image = image;
}
public float getGrade() {
return grade;
}
public void setGrade(float grade) {
this.grade = grade;
}
public Date getDate() {
return date;
}
public String getFormattedDate(String format) {
if (date != null) {
DateFormat dateFormat = new SimpleDateFormat(format, Locale.ENGLISH);
return dateFormat.format(date);
}
return "n/a";
}
public void setDate(String date, String format) {
try {
DateFormat dateFormat = new SimpleDateFormat(format);
this.date = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
<file_sep>package br.unicamp.ft.d166336_m202618.trashtime.ui.list;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Iterator;
import br.unicamp.ft.d166336_m202618.trashtime.R;
import br.unicamp.ft.d166336_m202618.trashtime.models.Serie;
import br.unicamp.ft.d166336_m202618.trashtime.models.SerieList;
import br.unicamp.ft.d166336_m202618.trashtime.ui.search.SearchAdaptor;
public class SerieAdaptor extends RecyclerView.Adapter {
private ArrayList<Serie> list_series;
private ArrayList<Serie> all_series;
public SerieAdaptor(ArrayList<Serie> series) {
this.list_series = series;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.adapter_serie_list, parent, false
);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (serieAdapterOnClickListner != null){
TextView txt = v.findViewById(R.id.list_serie_name);
String array[] = txt.getText().toString().split(",");
Log.i("testando", array[0]);
serieAdapterOnClickListner.onItemClick(array[0]);
}
}
});
return new SerieViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
((SerieViewHolder)holder).bind(list_series.get(position));
}
@Override
public int getItemCount() {
return list_series.size();
}
public void search (String words) {
if (all_series == null) {
all_series = list_series;
}
list_series = new ArrayList<>();
for(Serie serie : all_series) {
if (serie.getName().toLowerCase().contains(words.toLowerCase())) {
list_series.add(serie);
}
}
notifyDataSetChanged();
}
public void originalDataSet () {
list_series = all_series;
notifyDataSetChanged();
}
public int filterSeries (String name) {
Iterator<Serie> itr = list_series.iterator();
int index = 0;
while (itr.hasNext()){
if(itr.next().getName().equals(name)){
break;
}
index++;
}
return list_series.get(index).getId();
}
public void setList_series(ArrayList<Serie> list_series) {
this.list_series = list_series;
}
/**
* Interface de clique
*/
public interface SerieAdapterOnClickListner {
void onItemClick(String name);
}
private SerieAdaptor.SerieAdapterOnClickListner serieAdapterOnClickListner;
public void setSerieAdapterOnClickListner(SerieAdaptor.SerieAdapterOnClickListner a){
this.serieAdapterOnClickListner = a;
}
}
<file_sep>package br.unicamp.ft.d166336_m202618.trashtime.services;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public MyFirebaseMessagingService() {
}
@Override
public void onNewToken(String s){
super.onNewToken(s);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage){
System.out.println(("SERVICE --> Mensagem chegou"));
if (remoteMessage.getNotification() != null){
System.out.println("SERVICE -->"+remoteMessage.getNotification().getBody());
}
if(remoteMessage.getData().size() > 0){
System.out.println("SERVICE --> DADOS: "+remoteMessage.getData());
}
}
}<file_sep>package br.unicamp.ft.d166336_m202618.trashtime.ui.includes.toprelated;
import android.view.View;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import br.unicamp.ft.d166336_m202618.trashtime.R;
import br.unicamp.ft.d166336_m202618.trashtime.models.SerieList;
public class TopRelatedViewHolder extends RecyclerView.ViewHolder {
private ImageView image;
private View itemView;
public TopRelatedViewHolder(@NonNull View itemView) {
super(itemView);
this.itemView = itemView;
image = itemView.findViewById(R.id.list_serie_image);
}
public void bind (SerieList serie) {
Picasso.with(itemView.getContext()).load(serie.getImage()).into(image);
}
}
<file_sep># como-perder-uma-serie-em-10-dias
<file_sep>package br.unicamp.ft.d166336_m202618.trashtime.ui.quiz;
import java.io.Serializable;
import java.util.List;
import java.util.Random;
public class QuizPackage implements Serializable {
private int result;
private String name, sleep, thanos, cooker, worstFinal, signo;
private List<String> food;
public QuizPackage() {
Random random = new Random();
this.result = random.nextInt(3) + 1;
}
public QuizPackage(String name, String sleep, String thanos, String cooker, String worstFinal, String signo, List<String> food) {
this.name = name;
this.sleep = sleep;
this.thanos = thanos;
this.cooker = cooker;
this.worstFinal = worstFinal;
this.signo = signo;
this.food = food;
Random random = new Random();
this.result = random.nextInt(3) + 1;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSleep() {
return sleep;
}
public void setSleep(String sleep) {
this.sleep = sleep;
}
public String getThanos() {
return thanos;
}
public void setThanos(String thanos) {
this.thanos = thanos;
}
public String getCooker() {
return cooker;
}
public void setCooker(String cooker) {
this.cooker = cooker;
}
public String getWorstFinal() {
return worstFinal;
}
public void setWorstFinal(String worstFinal) {
this.worstFinal = worstFinal;
}
public String getSigno() {
return signo;
}
public void setSigno(String signo) {
this.signo = signo;
}
//public List<String> getFood() {
// return food;
//}
public String getFood() {
String finalStr = "";
for (String str : food) {
if (finalStr.trim().isEmpty()) {
finalStr = str;
} else {
finalStr = finalStr + ", " + str;
}
}
return finalStr;
}
public void setFood(List<String> food) {
this.food = food;
}
public int getResult() {
return result;
}
}
<file_sep>package br.unicamp.ft.d166336_m202618.trashtime.services;
import org.json.JSONObject;
public interface JsonReciver {
void recieveJson (JSONObject jsonObject);
}
<file_sep>rootProject.name='TrashTIme'
include ':app'
<file_sep>package br.unicamp.ft.d166336_m202618.trashtime.ui.includes.toprelated;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
import br.unicamp.ft.d166336_m202618.trashtime.R;
import br.unicamp.ft.d166336_m202618.trashtime.models.SerieList;
import br.unicamp.ft.d166336_m202618.trashtime.services.JsonReciver;
import br.unicamp.ft.d166336_m202618.trashtime.services.TmdbService;
public class TopRelatedAdaptor extends RecyclerView.Adapter implements JsonReciver {
private ArrayList<SerieList> series;
private TmdbService tmdbService;
public TopRelatedAdaptor(String code) {
series = new ArrayList<>();
tmdbService = new TmdbService("http://api.themoviedb.org/3",
"5472dbfc461c85f5a29197d9c1fef7d5",
"en-us",
TopRelatedAdaptor.this
);
tmdbService.recommendations(code);
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.adapter_recommendations_list, parent, false
);
final TopRelatedViewHolder topRelatedViewHolder = new TopRelatedViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (serieAdapterOnClickListner != null){
SerieList serie = series.get(topRelatedViewHolder.getAdapterPosition());
serieAdapterOnClickListner.onItemClick(serie.getName());
}
}
});
return topRelatedViewHolder;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
((TopRelatedViewHolder)holder).bind(series.get(position));
}
@Override
public int getItemCount() {
if (series != null) {
return series.size();
}
return 0;
}
public void cleanSeries() {
series = new ArrayList<>();
}
public void setSeries(JSONObject jsonObject) {
}
public int filterSeries (String name) {
Iterator<SerieList> itr = series.iterator();
int index = 0;
while (itr.hasNext()){
if(itr.next().getName().equals(name)){
break;
}
index++;
}
return series.get(index).getId();
}
@Override
public void recieveJson(JSONObject jsonObject) {
JSONArray array = null;
try {
array = jsonObject.getJSONArray("results");
for (int i = 0; i < array.length(); i++) {
JSONObject serie = array.getJSONObject(i);
int id = Integer.parseInt(serie.getString("id"));
float grade = Float.parseFloat(serie.getString("vote_average"));
SerieList serieList = new SerieList(id, serie.getString("original_name"), serie.getString("poster_path"), grade);
this.series.add(serieList);
}
} catch (JSONException e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
/**
* Interface de clique
*/
public interface SerieAdapterOnClickListner {
void onItemClick(String name);
}
private SerieAdapterOnClickListner serieAdapterOnClickListner;
public void setSerieAdapterOnClickListner(SerieAdapterOnClickListner a){
this.serieAdapterOnClickListner = a;
}
}
<file_sep>package br.unicamp.ft.d166336_m202618.trashtime.ui.evaluate;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import org.json.JSONException;
import org.json.JSONObject;
import br.unicamp.ft.d166336_m202618.trashtime.R;
import br.unicamp.ft.d166336_m202618.trashtime.models.Serie;
import br.unicamp.ft.d166336_m202618.trashtime.repositories.SerieRepository;
import br.unicamp.ft.d166336_m202618.trashtime.services.JsonReciver;
import br.unicamp.ft.d166336_m202618.trashtime.services.TmdbService;
import br.unicamp.ft.d166336_m202618.trashtime.ui.includes.recommendations.RecommendationsAdaptor;
/**
* A simple {@link Fragment} subclass.
*/
public class EvaluteFragment extends Fragment implements JsonReciver {
private View view;
private TmdbService tmdbService;
private Serie serie;
private SerieRepository serieRepository;
private TextView name, overview, tmdb_grade, our_grade;
private ImageView imageView;
private RatingBar ratingBar;
private LinearLayout add_btn, upd_btn;
private Button add_serie, change_serie, delete_serie;
private RecyclerView recyclerView;
private RecommendationsAdaptor recommendationsAdaptor;
public EvaluteFragment() {
serie = new Serie();
tmdbService = new TmdbService("https://api.themoviedb.org/3",
"5472dbfc461c85f5a29197d9c1fef7d5",
"pt-br",
EvaluteFragment.this
);
}
@Override
public void onStart() {
super.onStart();
serieRepository = new SerieRepository(getContext());
if (serie.getId() != 0) {
serie = serieRepository.find(serie.getId());
ratingBar.setRating(serie.getGrade());
Log.i("testando aqui viu", serie.getFormattedDate("dd/MM/yyyy"));
}
}
@Override
public void onStop() {
super.onStop();
serieRepository.destroy();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_evalute, container, false);
recyclerView = view.findViewById(R.id.recycler_view_recommendations);
Bundle bundle = getArguments();
EvalutePackage evalutePackage = (EvalutePackage) bundle.getSerializable("serie");
tmdbService.loadData(evalutePackage.getTmdbCode() + "");
recommendationsAdaptor = new RecommendationsAdaptor(evalutePackage.getTmdbCode() + "");
name = view.findViewById(R.id.evalute_serie_name);
overview = view.findViewById(R.id.evalute_serie_overview);
tmdb_grade = view.findViewById(R.id.evalute_serie_tmdb_grade);
our_grade = view.findViewById(R.id.evalute_serie_our_grade);
imageView = view.findViewById(R.id.evalute_image);
ratingBar = view.findViewById(R.id.evalute_serie_rating);
add_btn = view.findViewById(R.id.evalute_add_serie_layout);
upd_btn = view.findViewById(R.id.evalute_update_serie_layout);
if (evalutePackage.getId() != 0) {
serie.setId(evalutePackage.getId());
add_btn.setVisibility(LinearLayout.GONE);
upd_btn.setVisibility(LinearLayout.VISIBLE);
ratingBar.setRating(evalutePackage.getGrade());
}
add_serie = view.findViewById(R.id.evalute_add_serie);
change_serie = view.findViewById(R.id.evalute_change_serie);
delete_serie = view.findViewById(R.id.evalute_remove_serie);
add_serie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
float grade = ratingBar.getRating();
serie.setGrade(grade);
int id = serieRepository.insertOrChangeData(serie);
serie.setId(id);
add_btn.setVisibility(LinearLayout.GONE);
upd_btn.setVisibility(LinearLayout.VISIBLE);
}
});
change_serie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
float grade = ratingBar.getRating();
serie.setGrade(grade);
serieRepository.insertOrChangeData(serie);
}
});
delete_serie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
serieRepository.removeData(serie.getId());
upd_btn.setVisibility(LinearLayout.GONE);
add_btn.setVisibility(LinearLayout.VISIBLE);
}
});
RecommendationsAdaptor.SerieAdapterOnClickListner onClickListner = new RecommendationsAdaptor.SerieAdapterOnClickListner() {
@Override
public void onItemClick(String name) {
int code = recommendationsAdaptor.filterSeries(name);
Serie serie = serieRepository.findByCode(code);
EvalutePackage evalutePackage;
if (serie == null) {
evalutePackage = new EvalutePackage(0, code);
} else {
evalutePackage = new EvalutePackage(serie.getId(), code);
}
Bundle bundle = new Bundle();
bundle.putSerializable("serie", evalutePackage);
NavController navController = NavHostFragment.findNavController(EvaluteFragment.this);
navController.navigate(R.id.evalute_fragment, bundle);
}
};
recommendationsAdaptor.setSerieAdapterOnClickListner(onClickListner);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false));
recyclerView.setAdapter(recommendationsAdaptor);
return view;
}
@Override
public void recieveJson(JSONObject jsonObject) {
try {
int tmdb_code = Integer.parseInt(jsonObject.getString("id"));
float grade = Float.parseFloat(jsonObject.getString("vote_average"));
String name = jsonObject.getString("name");
String image = jsonObject.getString("poster_path");
String overview = jsonObject.getString("overview");
if (jsonObject.has("next_episode_to_air") && !jsonObject.isNull("next_episode_to_air")) {
String next_ep = jsonObject.getJSONObject("next_episode_to_air").getString("air_date");
serie.setDate(next_ep, "yyy-MM-dd");
}
serie.setGrade(grade);
serie.setName(name);
serie.setImage(image);
serie.setTmdb_code(tmdb_code);
serie.setGrade(0);
this.name.setText(name);
this.overview.setText(overview);
this.tmdb_grade.setText(String.valueOf(grade));
Picasso.with(getContext()).load(serie.getFormattedImage()).into(imageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
|
2fb1a1ccfbe06063ada400007eb01570030c98bd
|
[
"Markdown",
"Java",
"Gradle"
] | 10
|
Java
|
laendle1999/ComoPerderUmaSerieEm10Dias
|
f42117aa726ac25d3dcf97c997b1843b8c7eedda
|
f1f9ca9ce7a0eaa5822d25ae18bf5a4a755a2997
|
refs/heads/master
|
<repo_name>jacobsanz97/NeuroCI_Artifact<file_sep>/gitcode.py
import requests
import json
import sys
import os
def cbrain_login(username, password):
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
}
data = {
'login': username,
'password': <PASSWORD>
}
response = requests.post('https://portal.cbrain.mcgill.ca/session', headers=headers, data=data)
if response.status_code == 200:
print("Login success")
print(response.content)
jsonResponse = response.json()
return jsonResponse["cbrain_api_token"]
else:
print("Login failure")
return 1
def cbrain_FSLStats(token, fileID):
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
params = (
('cbrain_api_token', token),
)
data = {
"cbrain_task": {
"type": "CbrainTask::Fslstats",
"user_id": 1887,
"bourreau_id": 39,
"tool_config_id": 1698,
"params": {
"interface_userfile_ids": [
fileID
],
"input_file": fileID,
"t": False,
"l": 16.5,
"u": 17.5,
"a": False,
"n": False,
"r": False,
"R": False,
"e": False,
"E": False,
"v": False,
"V": True,
"m": False,
"M": False,
"s": False,
"S": False,
"w": False,
"x": False,
"X": False,
"c": False,
"C": False,
"output": "output.txt",
"_cbrain_output_output": [
2731401
]},
"status": "Completed",
"created_at": "2020-06-05T06:57:39.000-07:00",
"updated_at": "2020-06-05T06:58:46.000-07:00",
"run_number": None,
"results_data_provider_id": 27,
"cluster_workdir_size": 40960,
"workdir_archived": False,
"workdir_archive_userfile_id": None,
"description": ""
}
}
# convert into JSON:
y = json.dumps(data)
response = requests.post('https://portal.cbrain.mcgill.ca/tasks', headers=headers, params=params, data=y)
if response.status_code == 200:
print(response.text)
jsonResponse = response.json()
return jsonResponse[0]["id"]
else:
print("Task posting failed.")
return 1
def cbrain_getTaskOutputFile(token, taskID):
headers = {
'Accept': 'application/json',
}
params = (
('id', taskID),
('cbrain_api_token', token)
)
url = 'https://portal.cbrain.mcgill.ca/tasks/' + taskID
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
jsonResponse = response.json()
if jsonResponse["status"] == "Completed":
return jsonResponse["params"]["_cbrain_output_output"][0] #gets the first if there are many outputs.
else:
print("Task not completed yet")
return 1
else:
print("Failed to get task info")
return 1
def cbrain_download_text(fileID, token):
headers = {
'Accept': 'text',
}
params = (
('cbrain_api_token', token),
)
url = 'https://portal.cbrain.mcgill.ca/userfiles/' + fileID + '/content'
response = requests.get(url, headers=headers, params=params, allow_redirects=True)
if response.status_code == 200:
return response.text
else:
print('Download failure')
return 1
def cbrain_logout(token):
headers = {
'Accept': 'application/json',
}
params = (
('cbrain_api_token', token),
)
response = requests.delete('https://portal.cbrain.mcgill.ca/session', headers=headers, params=params)
if response.status_code == 200:
print("Logout success")
else:
print("Logout failure")
return 1
login = sys.argv[1]
password = sys.argv[2]
token = cbrain_login(login, password)
#taskID = cbrain_FSLStats(token, "<PASSWORD>")
print(os.getcwd())
outputFileID = cbrain_getTaskOutputFile(token, "1135602")
txtt = cbrain_download_text(str(outputFileID), token)
file = open("results.txt", "w")
file.write(txtt)
file.close()
cbrain_logout(token)
|
f927699a308e07dfc3c14a3332288edeb699288e
|
[
"Python"
] | 1
|
Python
|
jacobsanz97/NeuroCI_Artifact
|
e66d99a8501e209f5069d9eba9a8579588b80da7
|
9b2f106bbe49f8f2827b5832c9b0eb49f2810b22
|
refs/heads/master
|
<file_sep>#!/bin/bash
apt-get update
apt-get -y upgrade
apt-get -y autoremove
WORK_DIR=/home/vagrant/workspace
SHARE_DIR=$WORK_DIR/share
echo installing resilio...
wget -nv https://download-cdn.resilio.com/2.6.4.1344/Debian/resilio-sync_2.6.4.1344-1_amd64.deb
dpkg -i resilio-sync_2.6.4.1344-1_amd64.deb
echo configuring resilio...
usermod -aG vagrant rslsync
usermod -aG rslsync vagrant
chmod g+rw $SHARE_DIR
cp $WORK_DIR/config.json /etc/resilio-sync/
echo enabling resilio...
systemctl enable resilio-sync
systemctl start resilio-sync
echo
echo all done.<file_sep>#################################
# malpaw.vagrant.resilio-worker #
# Vagrant configuration #
#################################
Vagrant.require_version ">=2.0.0"
Vagrant.configure("2") do |config|
config.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 2
end
# have to use xenial instead of cosmic until elementary os updates vagrant to >=2.0
config.vm.box = "ubuntu/xenial64"
config.vm.hostname = "resilio-worker"
config.vm.network "forwarded_port", guest: 8888, host: 8888
config.vm.synced_folder "workspace/", "/home/vagrant/workspace"
config.vm.provision "shell", path: "provision.sh"
end
|
a8f22730cdf715f5df8ee0fa4ab5e972fc0ea142
|
[
"Ruby",
"Shell"
] | 2
|
Shell
|
malpaw/vagrant.resilio-worker
|
bf63e59c5cd7052c11422fd2033cc37f63393ea1
|
cf1d5408f42a0a4ea02d1cc76c6df09e4a9a733d
|
refs/heads/master
|
<file_sep> #include <map>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
long num;
string name;
cin >> num;
map <string,int> db;
vector <string> myv;
map <string, int> ::iterator it = db.begin();
vector<string>::iterator it1;
for (long i =0 ;i<num;i++)
{
cin >> name;
if (i==0)
{
db.insert(pair<string, int>(name, 0));
db[name] = db[name] + 1;
myv.push_back("OK");
}
else if (db.count(name) == 0 &&i!=0)
{
db.insert(pair<string, int>(name, 0));
db[name] = db[name] + 1;
myv.push_back("OK");
}
else if (db.count(name) != 0&&i!=0)
{
myv.push_back(name + to_string(db[name]));
db[name] = db[name] + 1;
}
}
for (it1 = myv.begin(); it1 != myv.end(); it1++)
cout << *it1 << "\n";
return 0;
}<file_sep> #include <stack>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// Function to check if array has 2 elements
// whose sum is equal to the given value
bool hasArrayTwoCandidates(long A[], long arr_size,
long sum)
{
int l, r;
/* Sort the elements */
sort(A, A + arr_size);
/* Now look for the two candidates in
the sorted array*/
l = 0;
r = arr_size - 1;
while (l < r) {
if (A[l] + A[r] == sum)
return 1;
else if (A[l] + A[r] < sum)
l++;
else // A[i] + A[j] > sum
r--;
}
return 0;
}
/* Driver program to test above function */
int main()
{
long size, num, x;
long* p;
cin >> size >> num;
p = new long[size];
for (long i = 0; i < size; i++)
{
cin >> x;
p[i] = x;
}
if (hasArrayTwoCandidates(p, size, num))
cout << "YES";
else
cout << "NO";
return 0;
}
|
09051cd429da089c23ca9dcd277b0c7283a8dfbe
|
[
"C"
] | 2
|
C
|
marwanmahmoud/CodeForces-Contests
|
d29df060daf035572b95faf351de2a74a51d5033
|
0fe1a847385d8bda58a07822d3ce83509ad396a8
|
refs/heads/master
|
<file_sep>// Cognizant Question
// Take an input of integers and check the individual numbers if odd or even.
// if the input is even, add 1 else subtract 1 . 0 is considered as even and 1 as odd.
import java.util.Scanner;
public class NumberAlter {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number below:");
int n = sc.nextInt();
int temp = n;
int result = 0;
while (temp != 0){
int rem = temp % 10;
if(rem % 2 == 0){
rem = rem + 1;
}else if (rem == 0)
{
rem = rem + 1;
}
else{
rem = rem - 1;
}
result = result * 10 + rem;
temp = temp / 10;
}
int result1 = 0;
while (result != 0){
int rem1 = result % 10;
result1 = result1 * 10 + rem1;
result = result / 10;
}
System.out.println("The desired output is: "+result1);
}
}
<file_sep>import java.util.Scanner;
public class greatestThreeNum {
public static void main(String[] args) {
int first = 0,second = 0,third = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number: ");
first = sc.nextInt();
System.out.println("Enter the second number: ");
second = sc.nextInt();
System.out.println("Enter the third number: ");
third = sc.nextInt();
if(first > second && first > third){
System.out.println("First input is the greatest");
}else if (second > first && second > third){
System.out.println("Second input is the greatest");
}else if(third > second && third > first){
System.out.println("Third input is the greatest");
}else{
System.out.println("All the numbers are equal");
}
sc.close(); // NOT REQUIRED BUT IT'S A BEST PRACTISE
}
}
<file_sep>import java.util.Scanner;
public class revArray {
static void reversedArray(int arr[], int start, int end){
int temp;
while(start < end){
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start ++;
end --;
}
}
static void printArray(int arr[], int size){
for(int i = 0; i< size; i++){
System.out.print(arr[i] + " ");
}
System.out.println("");
}
public static void main(String args[]){
int arr[] = {1,2,6,9,5,7};
System.out.print("Array: ");
printArray(arr, 6);
reversedArray(arr,0,5);
System.out.print("Reversed array is: ");
printArray(arr,6);
}
}
<file_sep>// Accenture system check assesment
// Q. input 123 , output: 20
// 1 + 2 + 3 = 6
// and 123 / 6 = 20
import java.util.Scanner;
public class sumNdivide {
public static int acc(int n){
int sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
int finalsum = 0;
finalsum = n / acc(n);
System.out.println(finalsum);
}
}
<file_sep>import java.util.Scanner;
public class sumRange {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number of the range: ");
int first = sc.nextInt();
System.out.println("Enter the second number of the range: ");
int second = sc.nextInt();
int sum = 0;
for(int i = first; i <= second; i ++){
sum = sum + i;
}
System.out.println("Sum of range from "+first+" to "+second+" is: "+sum);
}
}
<file_sep>import java.util.Scanner;
public class greatestNum {
public static void main(String args[]){
int first = 0,second =0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number: ");
first = sc.nextInt();
System.out.println("Enter the second number: ");
second = sc.nextInt();
if (first > second){
System.out.println("First number is greater than the second number.");
}else if(second > first){
System.out.println("Second number is greater than the first number.");
}else{
System.out.println("Both the number entered is equal.");
}
}
}
<file_sep>import java.util.Scanner;
public class sumNatural {
public static void main(String args[]){
System.out.print("Enter the value of n : ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
for(int i = 1; i <= n; i++){
sum = sum + i;
}
System.out.println("Sum of "+ n + " natural numbers is/are: "+ sum);
}
}
|
86ab93c6f61cebeccfa3b23f34859493dbe84462
|
[
"Java"
] | 7
|
Java
|
bornakpaul/100_questions_JAVA
|
218163a25b4af8c804b3f1d995e3c43ca448404e
|
442d0e47f7cb287cc72c00329ae946b94abf0f52
|
refs/heads/master
|
<repo_name>yangtaihua/snake<file_sep>/pkg/queue/rabbitmq/producer.go
package rabbitmq
import (
"fmt"
"github.com/streadway/amqp"
)
type Producer struct {
channel *amqp.Channel
queueName string
}
func NewProducer(channel *amqp.Channel, queueName string) Producer {
return Producer{channel: channel, queueName: queueName}
}
func (p Producer) Publish(message string) error {
if err := p.channel.Publish(
"",
p.queueName,
false,
false,
amqp.Publishing{
Headers: amqp.Table{},
ContentType: "text/plain",
Body: []byte(message),
}); err != nil {
return fmt.Errorf("failed to publish a message: %s", err)
}
return nil
}
<file_sep>/pkg/cache/driver.go
package cache
import (
"errors"
"time"
)
const (
// DefaultExpireTime 默认过期时间
DefaultExpireTime = time.Hour * 24
// DefaultNotFoundExpireTime 结果为空时的过期时间 1分钟, 常用于数据为空时的缓存时间(缓存穿透)
DefaultNotFoundExpireTime = time.Minute
// NotFoundPlaceholder .
NotFoundPlaceholder = "*"
)
var (
ErrPlaceholder = errors.New("cache: placeholder")
ErrSetMemoryWithNotFound = errors.New("cache: set memory cache err for not found")
)
// Client 生成一个缓存客户端,其中keyPrefix 一般为业务前缀
var Client Driver
// Driver 定义cache驱动接口
type Driver interface {
Set(key string, val interface{}, expiration time.Duration) error
Get(key string, val interface{}) error
MultiSet(valMap map[string]interface{}, expiration time.Duration) error
MultiGet(keys []string, valueMap interface{}) error
Del(keys ...string) error
Incr(key string, step int64) (int64, error)
Decr(key string, step int64) (int64, error)
SetCacheWithNotFound(key string) error
}
// Set 数据
func Set(key string, val interface{}, expiration time.Duration) error {
return Client.Set(key, val, expiration)
}
// Get 数据
func Get(key string, val interface{}) error {
return Client.Get(key, val)
}
// MultiSet 批量set
func MultiSet(valMap map[string]interface{}, expiration time.Duration) error {
return Client.MultiSet(valMap, expiration)
}
// MultiGet 批量获取
func MultiGet(keys []string, valueMap interface{}) error {
return Client.MultiGet(keys, valueMap)
}
// Del 批量删除
func Del(keys ...string) error {
return Client.Del(keys...)
}
// Incr 自增
func Incr(key string, step int64) (int64, error) {
return Client.Incr(key, step)
}
// Decr 自减
func Decr(key string, step int64) (int64, error) {
return Client.Decr(key, step)
}
func SetCacheWithNotFound(key string) error {
return Client.SetCacheWithNotFound(key)
}
<file_sep>/pkg/lock/try_lock.go
package lock
import (
"sync"
"sync/atomic"
"unsafe"
)
// 复制Mutex定义的常量
const (
mutexLocked = 1 << iota // 加锁标识位置
mutexWoken // 唤醒标识位置
mutexStarving // 锁饥饿标识位置
//mutexWaiterShift = iota // 标识waiter的起始bit位置
)
// Mutex 扩展一个Mutex结构
type Mutex struct {
sync.Mutex
}
// TryLock 尝试获取锁
func (m *Mutex) TryLock() bool {
// 如果能成功抢到锁
if atomic.CompareAndSwapInt32((*int32)(unsafe.Pointer(&m.Mutex)), 0, mutexLocked) {
return true
}
// 如果处于唤醒、加锁或者饥饿状态,这次请求就不参与竞争了,返回false
old := atomic.LoadInt32((*int32)(unsafe.Pointer(&m.Mutex)))
if old&(mutexLocked|mutexStarving|mutexWoken) != 0 {
return false
}
// 尝试在竞争的状态下请求锁
new := old | mutexLocked
return atomic.CompareAndSwapInt32((*int32)(unsafe.Pointer(&m.Mutex)), old, new)
}
<file_sep>/cmd/snake/go.mod
module github.com/1024casts/snake/cmd/snake
go 1.13
require (
github.com/go-git/go-git/v5 v5.2.0
github.com/spf13/cobra v1.1.3
golang.org/x/mod v0.4.1
)
<file_sep>/database/seeders/database_seeder.go
package seeders
//数据写入
func Seeder() {
SysTreeSeeder()
}
<file_sep>/main.go
/**
* ____ __
* / __/__ ___ _/ /_____
* _\ \/ _ \/ _ `/ '_/ -_)
* /___/_//_/\_,_/_/\_\\__/
*
* generate by http://patorjk.com/software/taag/#p=display&f=Small%20Slant&t=Snake
*/
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/spf13/pflag"
"github.com/uber/jaeger-lib/metrics"
jprom "github.com/uber/jaeger-lib/metrics/prometheus"
"github.com/1024casts/snake/internal/conf"
"github.com/1024casts/snake/internal/model"
"github.com/1024casts/snake/internal/server/grpc"
http2 "github.com/1024casts/snake/internal/server/http"
"github.com/1024casts/snake/internal/service"
logger "github.com/1024casts/snake/pkg/log"
"github.com/1024casts/snake/pkg/net/tracing"
redis2 "github.com/1024casts/snake/pkg/redis"
)
var (
cfgFile = pflag.StringP("config", "c", "", "snake config file path.")
Cfg *conf.Config
Svc *service.Service
)
func init() {
pflag.Parse()
// init config
Cfg, err := conf.Init(*cfgFile)
if err != nil {
panic(err)
}
// init log
logger.InitLog(&Cfg.Logger)
// init db
model.Init(&Cfg.MySQL)
// init redis
redis2.Init(&Cfg.Redis)
// init tracer
metricsFactory := jprom.New().Namespace(metrics.NSOptions{Name: Cfg.App.Name, Tags: nil})
_, closer, err := tracing.Init(Cfg.Jaeger.ServiceName, Cfg.Jaeger.Host, metricsFactory)
if err != nil {
panic(err)
}
defer closer.Close()
// init service
Svc := service.New(Cfg)
_ = Svc
}
// @title snake docs api
// @version 1.0
// @description snake demo
// @host localhost:8080
// @BasePath /v1
func main() {
gin.SetMode(conf.Conf.App.Mode)
// init http server
httpSrv := http2.Init(Svc)
// init grpc server
grpcSrv := grpc.Init(Cfg, Svc)
// init pprof server
go func() {
fmt.Printf("Listening and serving PProf HTTP on %s\n", conf.Conf.App.PprofPort)
if err := http.ListenAndServe(conf.Conf.App.PprofPort, http.DefaultServeMux); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen ListenAndServe for PProf, err: %s", err.Error())
}
}()
ctx, cancel := context.WithTimeout(context.Background(), conf.Conf.App.CtxDefaultTimeout*time.Second)
defer cancel()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-quit
log.Printf("Server receive a quit signal: %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
log.Println("Server is exiting")
// close http server
if httpSrv != nil {
if err := httpSrv.Shutdown(ctx); err != nil {
log.Fatalf("Server shutdown err: %s", err)
}
}
// close grpc server
if grpcSrv != nil {
grpcSrv.GracefulStop()
}
// close service
Svc.Close()
return
case syscall.SIGHUP:
// TODO: reload
default:
return
}
}
}
<file_sep>/pkg/lock/example_try_lock.go
package lock
import (
"fmt"
"math/rand"
"time"
)
// ExampleTry test try lock
func ExampleTry() {
var mu Mutex
go func() { // 启动一个goroutine持有一段时间的锁
mu.Lock()
time.Sleep(time.Duration(rand.Intn(2)) * time.Second)
mu.Unlock()
}()
time.Sleep(time.Second)
ok := mu.TryLock() // 尝试获取到锁
if ok { // 获取成功
fmt.Println("got the lock")
// do something
mu.Unlock()
return
}
// 没有获取到
fmt.Println("can't get the lock")
}
<file_sep>/database/migrations/database_migrate.go
package migrations
import (
"github.com/1024casts/snake/internal/model"
)
func Migrate() {
db := model.GetDB()
db.Set("gorm:table_options", "ENGINE=InnoDB")
db.AutoMigrate(&model.UserBaseModel{})
}
<file_sep>/pkg/email/init.go
package email
import (
"errors"
"sync"
"github.com/1024casts/snake/pkg/conf"
"github.com/1024casts/snake/pkg/log"
)
// Client 邮件发送客户端
var Client Driver
// Lock 读写锁
var Lock sync.RWMutex
var (
// ErrChanNotOpen 邮件队列没有开启
ErrChanNotOpen = errors.New("email queue does not open")
)
// Config email config
type Config struct {
Host string
Port int
Username string
Password string
Name string
Address string
ReplyTo string
KeepAlive int
}
// Init 初始化客户端
func Init() {
log.Info("email init")
Lock.Lock()
defer Lock.Unlock()
// 确保是已经关闭的
if Client != nil {
Client.Close()
}
client := NewSMTPClient(SMTPConfig{
Name: conf.Conf.Email.Name,
Address: conf.Conf.Email.Address,
ReplyTo: conf.Conf.Email.ReplyTo,
Host: conf.Conf.Email.Host,
Port: conf.Conf.Email.Port,
Username: conf.Conf.Email.Username,
Password: conf.Conf.Email.Password,
Keepalive: conf.Conf.Email.KeepAlive,
})
Client = client
}
<file_sep>/pkg/cache/lru_test.go
package cache
import (
"fmt"
"testing"
)
func TestLRU(t *testing.T) {
lru := NewLRU(3)
lru.Set(1, 1)
lru.Set(2, 2)
lru.Set(3, 3)
// Least 1 -> 2 -> 3 Most
lru.ShowQueue()
// 2
fmt.Println(lru.Get(2))
// Least 1 -> 3 -> 2 Most
lru.ShowQueue()
lru.Set(1, 100)
// Least 3 -> 2 -> 1 Most
lru.ShowQueue()
lru.Set(4, 4)
// Least 2 -> 1 -> 4 Most
lru.ShowQueue()
}
<file_sep>/pkg/net/http/raw.go
package http
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/1024casts/snake/pkg/log"
)
// raw 使用原生包封装的 http client
// rawClient
type rawClient struct{}
// newRawClient 实例化 http 客户端
func newRawClient() Client {
return &rawClient{}
}
// Get get data by get method
func (r *rawClient) Get(url string, params map[string]string, duration time.Duration) ([]byte, error) {
client := http.Client{Timeout: duration}
var target []byte
resp, err := client.Get(url)
if err != nil {
log.Warnf("get url:%s, err: %s", url, err)
return target, err
}
defer func() {
_ = resp.Body.Close()
}()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Warnf("read body: %s by ioutil, err: %s", b, err)
return target, err
}
if err := json.Unmarshal(b, &target); err != nil {
log.Warnf("can't unmarshal to target err: %s, body: %s", err, b)
return target, fmt.Errorf("can't unmarshal to target err: %s, body: %s", err, b)
}
return target, nil
}
// Post send data by post method
func (r *rawClient) Post(url string, data []byte, duration time.Duration) ([]byte, error) {
client := http.Client{Timeout: duration}
var target []byte
resp, err := client.Post(url, contentTypeJSON, bytes.NewBuffer(data))
if err != nil {
log.Warnf("post url:%s, err: %s", url, err)
return target, err
}
defer func() {
_ = resp.Body.Close()
}()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Warnf("read body: %s by ioutil, err: %s", b, err)
return target, err
}
log.Infof("resp: %+v", string(b))
if err := json.Unmarshal(b, &target); err != nil {
log.Warnf("can't unmarshal to target err: %s, body: %s", err, b)
return target, fmt.Errorf("can't unmarshal to target, err: %s, body: %s", err, b)
}
return target, nil
}
<file_sep>/database/seeders/sys_tree_seeder.go
package seeders
import "github.com/1024casts/snake/internal/model"
func SysTreeSeeder() {
db := model.GetDB()
db.AutoMigrate()
}
<file_sep>/internal/dao/user_stat_dao.go
package dao
import (
"context"
"time"
"github.com/pkg/errors"
"gorm.io/gorm"
"github.com/1024casts/snake/internal/model"
)
// IncrFollowCount 增加关注数
func (d *Dao) IncrFollowCount(ctx context.Context, db *gorm.DB, userID uint64, step int) error {
err := db.Exec("insert into user_stat set user_id=?, follow_count=1, created_at=? on duplicate key update "+
"follow_count=follow_count+?, updated_at=?",
userID, time.Now(), step, time.Now()).Error
if err != nil {
return errors.Wrap(err, "[user_stat_repo] incr user follow count")
}
return nil
}
// IncrFollowerCount 增加粉丝数
func (d *Dao) IncrFollowerCount(ctx context.Context, db *gorm.DB, userID uint64, step int) error {
err := db.Exec("insert into user_stat set user_id=?, follower_count=1, created_at=? on duplicate key update "+
"follower_count=follower_count+?, updated_at=?",
userID, time.Now(), step, time.Now()).Error
if err != nil {
return errors.Wrap(err, "[user_stat_repo] incr user follower count")
}
return nil
}
// GetUserStatByID 获取用户统计数据
func (d *Dao) GetUserStatByID(ctx context.Context, userID uint64) (*model.UserStatModel, error) {
userStat := model.UserStatModel{}
err := d.db.Where("user_id = ?", userID).First(&userStat).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, errors.Wrap(err, "[user_stat_repo] get user stat err")
}
return &userStat, nil
}
// GetUserStatByIDs 批量获取用户统计数据
func (d *Dao) GetUserStatByIDs(ctx context.Context, userID []uint64) (map[uint64]*model.UserStatModel, error) {
userStats := make([]*model.UserStatModel, 0)
retMap := make(map[uint64]*model.UserStatModel)
err := d.db.Where("user_id in (?)", userID).Find(&userStats).Error
if err != nil && err != gorm.ErrRecordNotFound {
return retMap, errors.Wrap(err, "[user_stat_repo] get user stat err")
}
for _, v := range userStats {
retMap[v.UserID] = v
}
return retMap, nil
}
<file_sep>/pkg/cache/sync_cache.go
package cache
import (
"sync"
"github.com/robfig/cron/v3"
)
var storeObj *store
type store struct {
sync.RWMutex
cron *cron.Cron
data map[int]interface{}
}
func NewSyncStore() *store {
return &store{
data: make(map[int]interface{}, 0),
cron: cron.New(),
}
}
func (s *store) syncStore(dataFn func() map[int]interface{}) {
s.Lock()
s.data = dataFn()
s.Unlock()
}
func (s *store) Get(id int) interface{} {
s.RLock()
defer s.RUnlock()
resp, _ := s.data[id]
return resp
}
<file_sep>/internal/server/http/server.go
package http
import (
"fmt"
"log"
"net/http"
"time"
"github.com/1024casts/snake/internal/conf"
"github.com/1024casts/snake/internal/routers"
"github.com/1024casts/snake/internal/service"
)
var (
UserSvc *service.Service
)
func Init(s *service.Service) *http.Server {
UserSvc = s
router := routers.NewRouter()
srv := &http.Server{
Addr: conf.Conf.App.Port,
Handler: router,
ReadTimeout: time.Second * conf.Conf.App.ReadTimeout,
WriteTimeout: time.Second * conf.Conf.App.WriteTimeout,
}
fmt.Printf("Listening and serving HTTP on %s\n", conf.Conf.App.Port)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("ListenAndServe, err: %s", err.Error())
}
return srv
}
<file_sep>/Dockerfile
# Compile stage
FROM golang:1.14-alpine AS builder
# The latest alpine images don't have some tools like (`git` and `bash`).
# Adding git, bash and openssh to the image
RUN apk add --no-cache git ca-certificates tzdata \
--repository http://mirrors.aliyun.com/alpine/v3.11/community \
--repository http://mirrors.aliyun.com/alpine/v3.11/main
# 镜像设置必要的环境变量
ENV GO111MODULE=on \
CGO_ENABLED=0 \
GOOS=linux \
GOARCH=amd64 \
GOPROXY="https://goproxy.cn,direct" \
TZ=Asia/Shanghai
# 移动到工作目录:/app
WORKDIR /build/app
# 复制项目中的 go.mod 和 go.sum文件并下载依赖信息
COPY go.mod .
COPY go.sum .
RUN go mod download
# 将代码复制到容器中
COPY . .
COPY config /app/conf
# Build the Go app
RUN go build -ldflags="-s -w" -o /app/snake .
# 创建一个小镜像
# Final stage
FROM debian:stretch-slim
WORKDIR /app
# 从builder镜像中把 /app 拷贝到当前目录
COPY --from=builder /app/snake /app/snake
COPY --from=builder /app/conf /app/conf
RUN mkdir -p /data/logs/
# Expose port 8080 to the outside world
EXPOSE 8080
# 需要运行的命令
CMD ["/app/snake", "-c", "conf/config.docker.yaml"]
# 1. build image: docker build -t snake:v1 -f Dockerfile .
# 2. start: docker run --rm -it -p 8080:8080 snake:v1
# 3. test: curl -i http://localhost:8080/health
<file_sep>/pkg/cache/sync_cache_test.go
// 异步缓存
// 场景1:本地缓存更新,可以使用cron同步远程数据到本地
package cache
import (
"fmt"
"sync"
"testing"
)
// go test -v sync_cache_test.go
func TestSyncCache(t *testing.T) {
storeObj = NewSyncStore()
storeObj.syncStore(getRemoteData)
storeObj.cron.AddFunc("*/1 * * * * *", func() {
storeObj.syncStore(getRemoteData)
})
storeObj.cron.Start()
var wg sync.WaitGroup
for i := 1; i < 6; i++ {
wg.Add(1)
go func(wg *sync.WaitGroup, i int) {
fmt.Println(storeObj.Get(i))
wg.Done()
}(&wg, i)
}
wg.Wait()
}
func getRemoteData() map[int]interface{} {
resp := make(map[int]interface{})
resp[1] = "test1"
resp[2] = "test2"
resp[3] = "test3"
resp[4] = "test4"
resp[5] = "test5"
return resp
}
<file_sep>/pkg/log/span_logger.go
// span logger for tracing
// reference: https://github.com/jaegertracing/jaeger/tree/master/examples/hotrod/pkg/log
package log
import (
"fmt"
"time"
"github.com/opentracing/opentracing-go"
tag "github.com/opentracing/opentracing-go/ext"
spanlog "github.com/opentracing/opentracing-go/log"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type spanLogger struct {
logger *zap.Logger
span opentracing.Span
spanFields []zapcore.Field
}
func (sl spanLogger) Debug(args ...interface{}) {
panic("implement me")
}
func (sl spanLogger) Debugf(format string, args ...interface{}) {
msg := fmt.Sprintf(format, args)
var fields []zap.Field
sl.logToSpan("info", msg)
sl.logger.Debug(msg, append(sl.spanFields, fields...)...)
}
func (sl spanLogger) Info(args ...interface{}) {
msg := fmt.Sprint(args)
var fields []zap.Field
sl.logToSpan("info", msg)
sl.logger.Info(msg, append(sl.spanFields, fields...)...)
}
func (sl spanLogger) Infof(format string, args ...interface{}) {
panic("implement me")
}
func (sl spanLogger) Warn(args ...interface{}) {
msg := fmt.Sprint(args)
var fields []zap.Field
sl.logToSpan("error", msg)
sl.logger.Warn(msg, append(sl.spanFields, fields...)...)
}
func (sl spanLogger) Warnf(format string, args ...interface{}) {
msg := fmt.Sprint(format, args)
var fields []zap.Field
sl.logToSpan("error", msg)
sl.logger.Warn(msg, append(sl.spanFields, fields...)...)
}
func (sl spanLogger) Error(args ...interface{}) {
msg := fmt.Sprint(args)
var fields []zap.Field
sl.logToSpan("error", msg)
sl.logger.Error(msg, append(sl.spanFields, fields...)...)
}
func (sl spanLogger) Errorf(format string, args ...interface{}) {
panic("implement me")
}
func (sl spanLogger) Fatal(args ...interface{}) {
msg := fmt.Sprint(args)
var fields []zap.Field
sl.logToSpan("fatal", msg)
tag.Error.Set(sl.span, true)
sl.logger.Fatal(msg, append(sl.spanFields, fields...)...)
}
func (sl spanLogger) Fatalf(format string, args ...interface{}) {
panic("implement me")
}
func (sl spanLogger) Panicf(format string, args ...interface{}) {
panic("implement me")
}
func (sl spanLogger) WithFields(keyValues Fields) Logger {
panic("implement me")
}
func (sl spanLogger) logToSpan(level string, msg string) {
// TODO rather than always converting the fields, we could wrap them into a lazy logger
fa := fieldAdapter(make([]spanlog.Field, 0, 2))
fa = append(fa, spanlog.String("event", msg))
fa = append(fa, spanlog.String("level", level))
sl.span.LogFields(fa...)
}
type fieldAdapter []spanlog.Field
func (fa *fieldAdapter) AddBool(key string, value bool) {
*fa = append(*fa, spanlog.Bool(key, value))
}
func (fa *fieldAdapter) AddFloat64(key string, value float64) {
*fa = append(*fa, spanlog.Float64(key, value))
}
func (fa *fieldAdapter) AddFloat32(key string, value float32) {
*fa = append(*fa, spanlog.Float64(key, float64(value)))
}
func (fa *fieldAdapter) AddInt(key string, value int) {
*fa = append(*fa, spanlog.Int(key, value))
}
func (fa *fieldAdapter) AddInt64(key string, value int64) {
*fa = append(*fa, spanlog.Int64(key, value))
}
func (fa *fieldAdapter) AddInt32(key string, value int32) {
*fa = append(*fa, spanlog.Int64(key, int64(value)))
}
func (fa *fieldAdapter) AddInt16(key string, value int16) {
*fa = append(*fa, spanlog.Int64(key, int64(value)))
}
func (fa *fieldAdapter) AddInt8(key string, value int8) {
*fa = append(*fa, spanlog.Int64(key, int64(value)))
}
func (fa *fieldAdapter) AddUint(key string, value uint) {
*fa = append(*fa, spanlog.Uint64(key, uint64(value)))
}
func (fa *fieldAdapter) AddUint64(key string, value uint64) {
*fa = append(*fa, spanlog.Uint64(key, value))
}
func (fa *fieldAdapter) AddUint32(key string, value uint32) {
*fa = append(*fa, spanlog.Uint64(key, uint64(value)))
}
func (fa *fieldAdapter) AddUint16(key string, value uint16) {
*fa = append(*fa, spanlog.Uint64(key, uint64(value)))
}
func (fa *fieldAdapter) AddUint8(key string, value uint8) {
*fa = append(*fa, spanlog.Uint64(key, uint64(value)))
}
func (fa *fieldAdapter) AddUintptr(key string, value uintptr) {}
func (fa *fieldAdapter) AddArray(key string, marshaler zapcore.ArrayMarshaler) error { return nil }
func (fa *fieldAdapter) AddComplex128(key string, value complex128) {}
func (fa *fieldAdapter) AddComplex64(key string, value complex64) {}
func (fa *fieldAdapter) AddObject(key string, value zapcore.ObjectMarshaler) error { return nil }
func (fa *fieldAdapter) AddReflected(key string, value interface{}) error { return nil }
func (fa *fieldAdapter) OpenNamespace(key string) {}
func (fa *fieldAdapter) AddDuration(key string, value time.Duration) {
// TODO inefficient
*fa = append(*fa, spanlog.String(key, value.String()))
}
func (fa *fieldAdapter) AddTime(key string, value time.Time) {
// TODO inefficient
*fa = append(*fa, spanlog.String(key, value.String()))
}
func (fa *fieldAdapter) AddBinary(key string, value []byte) {
*fa = append(*fa, spanlog.Object(key, value))
}
func (fa *fieldAdapter) AddByteString(key string, value []byte) {
*fa = append(*fa, spanlog.Object(key, value))
}
func (fa *fieldAdapter) AddString(key, value string) {
if key != "" && value != "" {
*fa = append(*fa, spanlog.String(key, value))
}
}
<file_sep>/pkg/conf/config.go
package conf
import (
"log"
"strings"
"time"
"github.com/fsnotify/fsnotify"
"github.com/pkg/errors"
"github.com/spf13/viper"
"github.com/1024casts/snake/pkg/database/orm"
)
var (
// Conf app global config
Conf *Config
)
// Init init config
func Init(configPath string) (*Config, error) {
cfgFile, err := LoadConfig(configPath)
if err != nil {
log.Fatalf("LoadConfig: %v", err)
}
cfg, err := ParseConfig(cfgFile)
if err != nil {
log.Fatalf("ParseConfig: %v", err)
}
WatchConfig(cfgFile)
Conf = cfg
return cfg, nil
}
// LoadConfig load config file from given path
func LoadConfig(confPath string) (*viper.Viper, error) {
v := viper.New()
if confPath != "" {
v.SetConfigFile(confPath) // 如果指定了配置文件,则解析指定的配置文件
} else {
v.AddConfigPath("config") // 如果没有指定配置文件,则解析默认的配置文件
v.SetConfigName("config.local")
}
v.SetConfigType("yaml") // 设置配置文件格式为YAML
v.AutomaticEnv() // 读取匹配的环境变量
viper.SetEnvPrefix("snake") // 读取环境变量的前缀为 snake
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
if err := v.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
return nil, errors.New("config file not found")
}
return nil, err
}
return v, nil
}
// Parse config file
func ParseConfig(v *viper.Viper) (*Config, error) {
var c Config
err := v.Unmarshal(&c)
if err != nil {
log.Printf("unable to decode into struct, %v", err)
return nil, err
}
return &c, nil
}
// 监控配置文件变化并热加载程序
func WatchConfig(v *viper.Viper) {
v.WatchConfig()
v.OnConfigChange(func(e fsnotify.Event) {
log.Printf("Config file changed: %s", e.Name)
})
}
// Config global config
// include common and biz config
type Config struct {
// common
App AppConfig
Logger Logger
MySQL orm.Config
Redis RedisConfig
Cache CacheConfig
Email EmailConfig
Web WebConfig
Cookie CookieConfig
QiNiu QiNiuConfig
Metrics Metrics
Jaeger Jaeger
MongoDB MongoDB
// here can add biz conf
}
// AppConfig app config
type AppConfig struct {
Name string
Version string
Mode string
Port string
PprofPort string
URL string
JwtSecret string
JwtTimeout int
ReadTimeout time.Duration
WriteTimeout time.Duration
SSL bool
CtxDefaultTimeout time.Duration
CSRF bool
Debug bool
}
// Logger config
type Logger struct {
Development bool
DisableCaller bool
DisableStacktrace bool
Encoding string
Level string
Name string
Writers string
LoggerFile string
LoggerWarnFile string
LoggerErrorFile string
LogFormatText bool
LogRollingPolicy string
LogRotateDate int
LogRotateSize int
LogBackupCount uint
}
// RedisConfig redis config
type RedisConfig struct {
Addr string
Password string
DB int
MinIdleConn int
DialTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
PoolSize int
PoolTimeout time.Duration
}
// CacheConfig define cache config struct
type CacheConfig struct {
Driver string
Prefix string
}
// EmailConfig email config
type EmailConfig struct {
Host string
Port int
Username string
Password string
Name string
Address string
ReplyTo string
KeepAlive int
}
// WebConfig web config
type WebConfig struct {
Name string
Domain string
Secret string
Static string
}
// CookieConfig cookie config
type CookieConfig struct {
Name string
MaxAge int
Secure bool
HttpOnly bool
Domain string
Secret string
}
// QiNiuConfig qiniu config
type QiNiuConfig struct {
AccessKey string
SecretKey string
CdnURL string
SignatureID string
TemplateID string
}
// Metrics config
type Metrics struct {
URL string
ServiceName string
}
// Jaeger config
type Jaeger struct {
Host string
ServiceName string
LogSpans bool
}
// MongoDB config
type MongoDB struct {
URI string
User string
Password string
DB string
}
<file_sep>/pkg/net/tracing/tracer.go
package tracing
import (
"fmt"
"io"
"time"
"github.com/1024casts/snake/pkg/log"
"github.com/uber/jaeger-lib/metrics"
"github.com/opentracing/opentracing-go"
"github.com/uber/jaeger-client-go"
"github.com/uber/jaeger-client-go/config"
)
// Jaeger config
type Config struct {
Host string
ServiceName string
LogSpans bool
}
// Init returns a new instance of Jaeger Tracer.
func Init(serviceName, agentHostPort string, metricsFactory metrics.Factory) (opentracing.Tracer, io.Closer, error) {
cfg := &config.Configuration{
ServiceName: serviceName,
// "const" sampler is a binary sampling strategy: 0=never sample, 1=always sample.
Sampler: &config.SamplerConfig{
Type: jaeger.SamplerTypeConst,
Param: 1,
},
// Log the emitted spans to stdout.
Reporter: &config.ReporterConfig{
LogSpans: true,
BufferFlushInterval: 1 * time.Second,
LocalAgentHostPort: agentHostPort,
},
}
jaegerLogger := jaegerLoggerAdapter{log.GetLogger()}
tracer, closer, err := cfg.NewTracer(
//config.Logger(jaeger.StdLogger),
config.Logger(jaegerLogger),
config.Metrics(metricsFactory),
config.ZipkinSharedRPCSpan(true),
)
if err != nil {
return nil, nil, err
}
opentracing.SetGlobalTracer(tracer)
return tracer, closer, err
}
type jaegerLoggerAdapter struct {
logger log.Logger
}
func (l jaegerLoggerAdapter) Error(msg string) {
l.logger.Error(msg)
}
func (l jaegerLoggerAdapter) Infof(msg string, args ...interface{}) {
l.logger.Info(fmt.Sprintf(msg, args...))
}
<file_sep>/pkg/cache/lru.go
// LRU cache
// wiki: https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)
// impl1: https://dev.to/clavinjune/lru-cache-in-go-1cfk
package cache
import "fmt"
type Node struct {
Key int
Value int
Prev *Node
Next *Node
}
func NewNode(key, value int) *Node {
return &Node{
Key: key,
Value: value,
}
}
type LRU struct {
capacity int
size int
data map[int]*Node
tail *Node
head *Node
}
func NewLRU(capacity int) *LRU {
return &LRU{
capacity: capacity,
size: 0,
data: make(map[int]*Node),
}
}
func (l *LRU) pushTail(n *Node) {
if l.head == nil {
l.head = n
l.tail = n
return
}
l.tail.Next = n
n.Prev = l.tail
l.tail = n
l.tail.Next = nil
}
func (l *LRU) popHead() *Node {
ret := l.head
if l.head == l.tail {
l.head = nil
} else {
l.head = l.head.Next
l.head.Prev = nil
}
return ret
}
func (l *LRU) popTail() *Node {
ret := l.tail
if l.head == l.tail {
l.head = nil
} else {
l.tail = l.tail.Prev
l.tail.Next = nil
}
return ret
}
func (l *LRU) pop(n *Node) *Node {
switch n {
case l.head:
return l.popHead()
case l.tail:
return l.popTail()
}
n.Next.Prev = n.Prev
n.Prev.Next = n.Next
return n
}
func (l *LRU) Set(key, value int) {
// check if the key exists
// if it exists, we need to remove it
// then we append it to the queue
// 4th rule (mark it as the most recently used)
if val, isOk := l.data[key]; isOk {
// this is the reason why we need to use popTail
l.pop(val)
l.size--
}
// 3rd rule
if l.size >= l.capacity {
n := l.popHead()
delete(l.data, n.Key)
l.size--
}
// push new data
n := NewNode(key, value)
l.data[key] = n
l.pushTail(n)
l.size++
}
func (l *LRU) Get(key int) int {
val, isOk := l.data[key]
if !isOk {
return -1
}
// remove it
l.pop(val)
// then mark it as the most recently used
l.pushTail(val)
return val.Value
}
func (l *LRU) ShowQueue() {
fmt.Printf("Least ")
for n := l.head; n != l.tail; n = n.Next {
fmt.Printf("%v -> ", n.Key)
}
fmt.Println(l.tail.Key, "Most")
}
<file_sep>/pkg/middleware/trace.go
package middleware
import (
"github.com/1024casts/snake/pkg/log"
"github.com/gin-gonic/gin"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
)
const (
// DefaultServiceName service name
DefaultServiceName = "snake"
)
func Trace() gin.HandlerFunc {
return func(c *gin.Context) {
tracer := opentracing.GlobalTracer()
var sp opentracing.Span
// for http
spanCtx, err := tracer.Extract(
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(c.Request.Header),
)
if err != nil && err != opentracing.ErrSpanContextNotFound {
log.Warn("err", err)
}
sp = tracer.StartSpan(
"HTTP "+c.Request.Method+" "+c.Request.URL.Path,
ext.RPCServerOption(spanCtx),
opentracing.Tag{Key: string(ext.Component), Value: "HTTP"},
)
// record HTTP method
ext.HTTPMethod.Set(sp, c.Request.Method)
// record HTTP url
ext.HTTPUrl.Set(sp, c.Request.URL.String())
c.Request = c.Request.WithContext(opentracing.ContextWithSpan(c.Request.Context(), sp))
c.Next()
// record HTTP status code
ext.HTTPStatusCode.Set(sp, uint16(c.Writer.Status()))
sp.Finish()
}
}
<file_sep>/pkg/net/http/resty.go
// http客户端 resty
package http
import (
"time"
"github.com/1024casts/snake/pkg/log"
"github.com/go-resty/resty/v2"
)
// docs: https://github.com/go-resty/resty
type restyClient struct{}
func newRestyClient() Client {
return &restyClient{}
}
// Get request url by get method
func (r *restyClient) Get(url string, params map[string]string, duration time.Duration) ([]byte, error) {
client := resty.New()
if duration != 0 {
client.SetTimeout(duration)
}
if len(params) > 0 {
client.SetQueryParams(params)
}
resp, err := client.R().
SetHeaders(map[string]string{
"Content-Type": contentTypeJSON,
}).
Get(url)
if err != nil {
log.Warnf("get url: %s err: %s", url, err)
return nil, err
}
return resp.Body(), nil
}
// Post request url by post method
func (r *restyClient) Post(url string, data []byte, duration time.Duration) ([]byte, error) {
client := resty.New()
if duration != 0 {
client.SetTimeout(duration)
}
cr := client.R().
SetBody(string(data)).
SetHeaders(map[string]string{
"Content-Type": contentTypeJSON,
})
resp, err := cr.Post(url)
if err != nil {
log.Warnf("post url: %s err: %s", url, err)
return nil, err
}
return resp.Body(), nil
}
<file_sep>/pkg/log/logger.go
package log
import (
"context"
"fmt"
)
// log is A global variable so that log functions can be directly accessed
var log Logger
// logger is A global variable with trace log
var logger Factory
// Fields Type to pass when we want to call WithFields for structured logging
type Fields map[string]interface{}
// Logger config
type Config struct {
Development bool
DisableCaller bool
DisableStacktrace bool
Encoding string
Level string
Name string
Writers string
LoggerFile string
LoggerWarnFile string
LoggerErrorFile string
LogFormatText bool
LogRollingPolicy string
LogRotateDate int
LogRotateSize int
LogBackupCount uint
}
// InitLog init log
func InitLog(cfg *Config) Logger {
zapLogger, err := newZapLogger(cfg)
if err != nil {
fmt.Errorf("Init newZapLogger err: %v", err)
}
l, err := newLogger(cfg)
if err != nil {
fmt.Errorf("Init newLogger err: %v", err)
}
// init logger with trace log
logger = NewFactory(zapLogger, l)
// normal log
log = l
return log
}
// Logger is our contract for the logger
type Logger interface {
Debug(args ...interface{})
Debugf(format string, args ...interface{})
Info(args ...interface{})
Infof(format string, args ...interface{})
Warn(args ...interface{})
Warnf(format string, args ...interface{})
Error(args ...interface{})
Errorf(format string, args ...interface{})
Fatal(args ...interface{})
Fatalf(format string, args ...interface{})
Panicf(format string, args ...interface{})
WithFields(keyValues Fields) Logger
}
func GetLogger() Logger {
return log
}
// Trace is a logger that can log msg and log span for trace
func Trace(ctx context.Context) Logger {
return logger.For(ctx)
}
// Debug logger
func Debug(args ...interface{}) {
log.Debug(args...)
}
// Info logger
func Info(args ...interface{}) {
log.Info(args...)
}
// Warn logger
func Warn(args ...interface{}) {
log.Warn(args...)
}
// Error logger
func Error(args ...interface{}) {
log.Error(args...)
}
// Fatal logger
func Fatal(args ...interface{}) {
log.Fatal(args...)
}
// Debugf logger
func Debugf(format string, args ...interface{}) {
log.Debugf(format, args...)
}
// Infof logger
func Infof(format string, args ...interface{}) {
log.Infof(format, args...)
}
// Warnf logger
func Warnf(format string, args ...interface{}) {
log.Warnf(format, args...)
}
// Errorf logger
func Errorf(format string, args ...interface{}) {
log.Errorf(format, args...)
}
// Fatalf logger
func Fatalf(format string, args ...interface{}) {
log.Fatalf(format, args...)
}
// Panicf logger
func Panicf(format string, args ...interface{}) {
log.Panicf(format, args...)
}
// WithFields logger
// output more field, eg:
// contextLogger := log.WithFields(log.Fields{"key1": "value1"})
// contextLogger.Info("print multi field")
// or more sample to use:
// log.WithFields(log.Fields{"key1": "value1"}).Info("this is a test log")
// log.WithFields(log.Fields{"key1": "value1"}).Infof("this is a test log, user_id: %d", userID)
func WithFields(keyValues Fields) Logger {
return log.WithFields(keyValues)
}
<file_sep>/pkg/lock/recursive.go
package lock
import (
"fmt"
"sync"
"sync/atomic"
"github.com/petermattis/goid"
)
// RecursiveMutex 包装一个Mutex,实现可重入, 即可重入锁(递归锁)
// 可重入锁主要用在线程需要多次进入临界区代码时,需要使用可重入锁,主要目的是为了避免死锁
// 临界区:一个被共享的资源
type RecursiveMutex struct {
sync.Mutex
owner int64 // 当前持有锁的goroutine id
recursion int32 // 这个goroutine 重入的次数
}
// Lock 请求锁
func (m *RecursiveMutex) Lock() {
// 获取当前goroutine id
gid := goid.Get()
// 如果当前持有锁的goroutine就是这次调用的goroutine,说明是重入
if atomic.LoadInt64(&m.owner) == gid {
m.recursion++
return
}
m.Mutex.Lock()
// 获得锁的goroutine第一次调用,记录下它的goroutine id,调用次数加1
atomic.StoreInt64(&m.owner, gid)
m.recursion = 1
}
// Unlock 释放锁
func (m *RecursiveMutex) Unlock() {
gid := goid.Get()
// 非持有锁的goroutine尝试释放锁,错误的使用
if atomic.LoadInt64(&m.owner) != gid {
panic(fmt.Sprintf("wrong the owner(%d): %d!", m.owner, gid))
}
// 调用次数减1
m.recursion--
if m.recursion != 0 { // 如果这个goroutine还没有完全释放,则直接返回
return
}
// 此goroutine最后一次调用,需要释放锁
atomic.StoreInt64(&m.owner, -1)
m.Mutex.Unlock()
}
|
3e74afbc75764b288af5267053b701d3ddc77cc0
|
[
"Go Module",
"Go",
"Dockerfile"
] | 25
|
Go
|
yangtaihua/snake
|
e44967a657eeb3e77ae1b549c85cbd7236293d9b
|
bccd0fb4228bcacc82b4afa76278545175c6cf6f
|
refs/heads/master
|
<repo_name>brandonleichty/library-manager-v2<file_sep>/routes/books.js
const express = require('express');
const router = express.Router();
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const Book = require('../models').Book;
const Loan = require('../models').Loan;
const Patron = require('../models').Patron;
// Get all books
router.get('/', (req, res) => {
Book.findAndCountAll()
.then((bookResults) => {
res.render('books', {
books: bookResults.rows,
pageTitle: 'Books',
});
});
});
// Display checked out books:
router.get('/checked_out', (req, res, next) => {
Book.findAll({
include: [{
model: Loan,
where: {
loaned_on: {
[Op.ne]: null
},
returned_on: {
[Op.eq]: null
}
}
}]
}).then((results) => {
res.render('books', {
books: results,
pageTitle: 'Checked out books',
});
});
});
// Overdue books
router.get('/overdue_books', (req, res, next) => {
Book.findAll({
include: [{
model: Loan,
where: {
return_by: {
[Sequelize.Op.lt]: new Date()
},
returned_on: null
}
}]
}).then((results) => {
res.render('books', {
books: results,
pageTitle: 'Overdue out books',
});
});
});
// Get new book route
router.get('/new_book', (req, res) => {
res.render('new_book', {
book: Book.build(),
pageTitle: 'New book'
});
});
// New book
router.post('/new_book', (req, res) => {
Book.create(req.body)
.then(book => {
res.redirect('/books');
})
.catch(err => {
if (err.name === 'SequelizeValidationError') {
res.render('new_book', {
book: Book.build(req.body),
title: 'New book',
errors: err.errors
});
} else {
throw err;
}
})
.catch(err => {
res.sendStatus(500);
});
});
// Get book details page
router.get('/details/:id', function (req, res, next) {
Book.findById(req.params.id, {
include: [{
model: Loan,
include: [{
model: Patron
}]
}]
}).then(function (results) {
if (results) {
res.render('book_details', {
book: results,
loans: results.Loans,
title: results.title
});
} else {
res.sendStatus(404);
}
});
});
// Post edited book details
router.post('/details/:id', (req, res, next) => {
Book.findById(req.params.id)
.then((book) => { // update book record
return book.update(req.body)
})
.then((book) => { // redirect to book listing page
res.redirect('/books')
})
.catch((err) => { // handle validation errors
if (err.name === 'SequelizeValidationError') {
Book.findById(req.params.id, {
include: [{
model: Loan,
include: [{
model: Patron
}]
}]
}).then(function (results) {
if (results) {
res.render('book_details', {
book: Book.build(req.body),
loans: results.Loans,
title: results.title,
errors: err.errors,
});
} else {
res.sendStatus(404);
}
})
}
})
});
// Return book
router.put('/details/:id/return', function (req, res, next) {
console.log('YAYYYY');
Loan.update({
returned_on: req.body.returned_on,
}, {
where: {
book_id: req.params.id
}
}).then((results) => {
res.redirect('/books');
}).catch((err) => {
if (err.name === 'SequelizeValidationError') {
}
});
});
module.exports = router;<file_sep>/README.md
# library-manager-v2
<file_sep>/routes/loans.js
const express = require('express');
const router = express.Router();
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const moment = require('moment');
const Book = require('../models').Book;
const Loan = require('../models').Loan;
const Patron = require('../models').Patron;
// Get all loans
router.get('/', function(req, res, next) {
Loan.findAll({
include: [Book, Patron]
}).then(function(results) {
res.render('all_loans', {
loans: results,
pageTitle: 'Loans'
});
});
});
// Return book form page
router.get('/return/:id', async (req, res) => {
const loan = await Loan.findById(req.params.id);
const [book, patron] = await Promise.all([
Book.findById(loan.book_id),
Patron.findById(loan.patron_id)
]);
if (loan) {
res.render('return_book', {
loan,
patron,
book,
title: 'Return book',
today: moment().format('YYYY-MM-DD')
});
} else {
res.sendStatus(404);
}
});
// Return loan
router.post('/return/:id', async (req, res) => {
const loan = await Loan.findById(req.params.id);
const [book, patron] = await Promise.all([
Book.findById(loan.book_id),
Patron.findById(loan.patron_id)
]);
Loan.findById(req.params.id)
.then(loan => {
// update loan record
return loan.update(req.body);
})
.then(loan => {
// redirect to loan listing page
res.redirect('/loans');
})
.catch(err => {
// handle any errors
if (err.name === 'SequelizeValidationError') {
res.render('return_book', {
loan,
patron,
book,
errors: err.errors,
title: 'Return book',
today: moment().format('YYYY-MM-DD')
});
} else {
res.sendStatus(500);
}
});
});
// Get overdue loans
router.get('/overdue_loans', function(req, res, next) {
Loan.findAll({
include: [Book, Patron],
where: {
return_by: {
[Op.lt]: new Date()
},
returned_on: null
}
}).then(function(loans) {
res.render('all_loans', {
loans,
pageTitle: 'Overdue Loans'
});
});
});
// Get checked out loans
router.get('/checked_loans', (req, res) => {
Loan.findAll({
include: [Book, Patron],
where: {
returned_on: {
[Op.eq]: null
}
}
}).then(function(loans) {
res.render('all_loans', {
loans,
pageTitle: 'Checked Loans'
});
});
});
// New loan
router.get('/new_loan', (req, res) => {
const loan = Loan.build({
loaned_on: moment().format('YYYY-MM-DD'),
return_by: moment()
.add(7, 'days')
.format('YYYY-MM-DD')
});
Book.findAll().then(books => {
Patron.findAll() // get all the patrons
.then(patrons => {
res.render('new_loan', {
// render the new loan form
loan: Loan.build({
loaned_on: moment().format('YYYY-MM-DD'),
return_by: moment()
.add(7, 'days')
.format('YYYY-MM-DD')
}),
books,
patrons,
pageTitle: 'New Loan'
});
});
});
});
// Save new loan
router.post('/new_loan', (req, res) => {
Loan.create(req.body) // create a new loan and redirect
.then(loan => {
// to loans index page
res.redirect('/loans');
})
.catch(err => {
// or show error messages
if (err.name === 'SequelizeValidationError') {
Book.findAll() // get all the books
.then(books => {
Patron.findAll() // get all the patrons
.then(patrons => {
res.render('new_loan', {
// render the new loan form
loan: Loan.build(req.body),
books,
patrons,
errors: err.errors,
pageTitle: 'New Loan'
});
});
});
}
});
});
module.exports = router;
|
9f8840b3a3a84dbd953f9819f493bf61a6c05b03
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
brandonleichty/library-manager-v2
|
ccd0a9be5d5e86cf9f083ec4d6a9060af1bc693e
|
d61a68b32603a3576c600ab3c76eb0ff36e8d3dd
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.