branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>VsIG-official/KPI-OOP<file_sep>/Lab5/Lab2/my_table.h #pragma once #include "resource2.h" using namespace std; /// <summary> /// Class for table /// </summary> class MyTable { //якісь члени класу public: void Add(HWND, std::string); //функція додавання у таблицю нового рядка з описом об’єкту //інші функції }; <file_sep>/Lab4/Lab2/framework.h #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Исключите редко используемые компоненты из заголовков Windows // Файлы заголовков Windows #define APSTUDIO_HIDDEN_SYMBOLS #include <windows.h> #include "prsht.h" #undef APSTUDIO_HIDDEN_SYMBOLS // Файлы заголовков среды выполнения C #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <tchar.h> //--підключення бібліотеки Common Control Library-- #include <commctrl.h> #pragma comment(lib, "comctl32.lib") <file_sep>/Lab4/Lab2/my_editor.cpp #include "framework.h" #include "pch.h" #include "my_editor.h" #include "toolbar.h" #pragma region Variables const int Size_Of_Array = 110; Shape* pcshape[Size_Of_Array]; int size = 0; bool isPressed; int ID = 0; #pragma endregion Variables #pragma region Functions Shape* object = NULL; void MyEditor::Start(Shape* shape,int id) { ID = id; if (object) delete object; object = shape; }; //void MyEditor::Add(Shape* object) //{ // if (size < Size_Of_Array) // { // pcshape[size] = *&object; // size++; // } //} Shape* MyEditor::ReturnObject(int i) { return pcshape[i]; } /// <summary> /// Destructor /// </summary> MyEditor::~MyEditor() { delete pcshape; } void MyEditor::OnLBdown(HWND hWnd) { POINT pt; GetCursorPos(&pt); ScreenToClient(hWnd, &pt); x1 = x2 = pt.x; y1 = y2 = pt.y; isPressed = true; } void MyEditor::OnLBup(HWND hWnd) { POINT pt; GetCursorPos(&pt); ScreenToClient(hWnd, &pt); x2 = pt.x; y2 = pt.y; isPressed = false; pcshape[size]->Set(x1, y1, x2, y2); size++; InvalidateRect(hWnd, NULL, TRUE); } void MyEditor::OnMouseMove(HWND hWnd) { if (isPressed) { POINT pt; HPEN hPen, hPenOld; HDC hdc = GetDC(hWnd); SetROP2(hdc, R2_NOTXORPEN); MoveToEx(hdc, x1, y1, NULL); pcshape[size]->Set(x1, y1, x2, y2); //pcshape[size]->RubberTrack(hdc); GetCursorPos(&pt); ScreenToClient(hWnd, &pt); x2 = pt.x; y2 = pt.y; MoveToEx(hdc, x1, y1, NULL); pcshape[size]->Set(x1, y1, x2, y2); //pcshape[c]->RubberTrack(hdc); ReleaseDC(hWnd, hdc); } } void MyEditor::OnPaint(HWND hWnd) { PAINTSTRUCT ps; HDC hdc; hdc = BeginPaint(hWnd, &ps); for (int i = 0; i < size; i++) { if (pcshape[i]) pcshape[i]->Show(hdc); } EndPaint(hWnd, &ps); } /// <summary> /// Sets the mark in figures menu /// </summary> /// <param name="hWnd"></param> /// <param name="wParams"></param> void MyEditor::OnInitMenuPopup(HWND hWnd, WPARAM wParam) { HMENU hMenu, hSubMenu; hMenu = GetMenu(hWnd); hSubMenu = GetSubMenu(hMenu, 1); const int allTools = 6; int tools[allTools] = { ID_TOOL_POINT, ID_TOOL_LINE, ID_TOOL_RECTANGLE, ID_TOOL_ELLIPSE, ID_TOOL_LINEOO, ID_TOOL_CUBE }; if ((HMENU)wParam == hSubMenu) { for (int i = 0; i < sizeof(tools); i++) { CheckMenuItem(hSubMenu, tools[i], MF_UNCHECKED); } } CheckMenuItem(hSubMenu, ID, MF_CHECKED); } #pragma endregion Functions <file_sep>/Lab1/Lab1/resource1.h //{{NO_DEPENDENCIES}} // Included file created in Microsoft Visual C++. // Using module1.rc // #ifndef MODULE_1_H #define MODULE_1_H #define IDD_WORK_MOD1 101 #define IDC_SCROLLBAR1_MOD1 1002 #define IDC_STATIC_MOD1 1003 extern int pos_MOD1; extern int numOfDig_MOD1; extern BOOL canWrite_MOD1; #endif // MODULE_1_H // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 103 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1005 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>/Lab6/Object2/framework.h #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Исключите редко используемые компоненты из заголовков Windows // Файлы заголовков Windows #include <windows.h> // Файлы заголовков среды выполнения C #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <tchar.h> #include <shellapi.h> #include <string> <file_sep>/Lab1/Lab1/module3.h #pragma once #include "resource3.h" #pragma region Function extern int Func_MOD3(HINSTANCE hInst, HWND hWnd); #pragma endregion <file_sep>/Lab6/Object2/Object2.cpp // Object2.cpp : Defines the input point for the application. // // First Part #include "framework.h" #include "pch.h" #include "Object2.h" #include <vector> #include <random> #include "Resource.h" #include <sstream> #include <iostream> using namespace std; #define MAX_LOADSTRING 100 #pragma region VariablesAndFunctions // Global variables: HINSTANCE hInst; // Current instance WCHAR szTitle[MAX_LOADSTRING]; // Header row text WCHAR szWindowClass[MAX_LOADSTRING]; // Class name of main window // Send declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int RandomInt(int low, int high); static int Count(int element); void OnCopyData(HWND hWnd, WPARAM wParam, LPARAM lParam); int PutTextToClipboard(HWND hWnd, char* src); void StartObj3(HWND hWnd); void CreateMatrix(HWND hWnd); int SendCopyData(HWND hWndDest, HWND hWndSrc, void* lp, long cb); int const allValues = 3; int values_MOD2[allValues]; HWND hWndDataCreator = NULL; int n_MOD2; int Min_MOD2; int Max_MOD2; BOOL Counter = FALSE; std::string copyMatrix = ""; #pragma endregion VariablesAndFunctions #pragma region DefaultFunctions // Second Part // Enter Point "wWinMain" int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place the code here. // Global line initialization LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadStringW(hInstance, IDC_OBJECT2, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance(hInstance, nCmdShow)) { return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_OBJECT2)); MSG msg; // Main message cycle: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } //Compiler version g++ 6.3.0 return (int)msg.wParam; } // // FUNCTION: MyRegisterClass() // // OBJECTIVE: To register the window class. // Text of Function /// <summary> /// Register the window class. /// </summary> /// <param name="hInstance">The h instance.</param> /// <returns></returns> ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDC_OBJECT2)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_OBJECT2); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassExW(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // OBJECTIVE: Saves the instance marker and creates the main window // // COMMENTARIES: // // In this function, the instance marker is saved in a global variable, and also // the main program window is created and displayed. // /// <summary> /// Saves the instance marker and creates the main window /// </summary> /// <param name="hInstance">The h instance.</param> /// <param name="nCmdShow">The n command show.</param> /// <returns></returns> BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; // Save instance marker in global variable HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } /// <summary> /// Message handler for "About" window. /// </summary> /// <param name="hDlg">The h dialog.</param> /// <param name="message">The message.</param> /// <param name="wParam">The w parameter.</param> /// <param name="lParam">The l parameter.</param> /// <returns></returns> INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } #pragma endregion #pragma region ModifiedFuntions // Third Part // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // OBJECTIVE: Processes messages in the main window. // // WM_COMMAND - Process the application menu // WM_PAINT - Drawing of the main window // WM_DESTROY - Send message about exit and return // // /// <summary> /// Processes messages in the main window. /// </summary> /// <param name="hWnd">The h WND.</param> /// <param name="message">The message.</param> /// <param name="wParam">The w parameter.</param> /// <param name="lParam">The l parameter.</param> /// <returns></returns> LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: { SetWindowPos(hWnd, HWND_BOTTOM, 141, 40, 200, 700, SWP_DEFERERASE); } break; case WM_COPYDATA: { OnCopyData(hWnd, wParam, lParam); if (n_MOD2 > 0) { CreateMatrix(hWnd); } InvalidateRect(hWnd, 0, TRUE); } break; case WM_COMMAND: { int wmId = LOWORD(wParam); switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProcW(hWnd, message, wParam, lParam); } } break; case WM_PAINT: { RECT rc = { 0 }; GetClientRect(hWnd, &rc); PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); char* cstr = new char[copyMatrix.size() + 1]; strcpy_s(cstr, copyMatrix.size() + 1, copyMatrix.c_str()); PutTextToClipboard(hWnd, cstr); DrawTextA(hdc, cstr, -1, &rc, DT_TOP); EndPaint(hWnd, &ps); } break; case WM_DESTROY: { PostQuitMessage(0); } break; default: return DefWindowProcW(hWnd, message, wParam, lParam); } return 0; } /// <summary> /// Creates matrix /// </summary> /// <param name="hWnd"></param> /// <returns></returns> void CreateMatrix(HWND hWnd) { // dynamic allocation int** matrix = new int* [n_MOD2]; for (int i = 0; i < n_MOD2; ++i) { matrix[i] = new int[n_MOD2]; } // fill for (int i = 0; i < n_MOD2; ++i) { for (int j = 0; j < n_MOD2; ++j) { matrix[i][j] = RandomInt(Min_MOD2, Max_MOD2); copyMatrix += std::to_string(matrix[i][j]); if (j < n_MOD2-1) { copyMatrix += " "; } } if (i < n_MOD2) { copyMatrix += "\n"; } } // free for (int i = 0; i < n_MOD2; ++i) { delete[] matrix[i]; } delete[] matrix; StartObj3(hWnd); } /// <summary> /// Sends copydata /// </summary> /// <param name="hWndDest"></param> /// <param name="hWndSrc"></param> /// <param name="lp"></param> /// <param name="cb"></param> /// <returns></returns> int SendCopyData(HWND hWndDest, HWND hWndSrc, void* lp, long cb) { COPYDATASTRUCT cds{}; cds.dwData = 1; //а можна і будь-яке інше значення cds.cbData = cb; cds.lpData = lp; return SendMessage(hWndDest, WM_COPYDATA, (WPARAM)hWndSrc, (LPARAM)&cds); } /// <summary> /// Creates random number for matrix /// </summary> /// <param name="low"></param> /// <param name="high"></param> /// <returns></returns> int RandomInt(int low, int high) { std::random_device rd; std::mt19937 gen(rd()); // seed the generator std::uniform_int_distribution<> distr(low, high); return distr(gen); } /// <summary> /// Function to Count how many digits are in int /// </summary> /// <param name="pos"></param> /// <returns></returns> int Count(int element) { int count_MOD1 = 0; while (element != 0) { element = element / 10; ++count_MOD1; } return count_MOD1; } /// <summary> /// Copy the data from another window /// </summary> /// <param name="hWnd"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> void OnCopyData(HWND hWnd, WPARAM wParam, LPARAM lParam) { COPYDATASTRUCT* cds; cds = (COPYDATASTRUCT*)lParam; long* p = (long*)cds->lpData; n_MOD2 = p[0]; Min_MOD2 = p[1]; Max_MOD2 = p[2]; } /// <summary> /// Put text to clipboard /// </summary> /// <param name="hWnd"></param> /// <param name="src"></param> /// <returns></returns> int PutTextToClipboard(HWND hWnd, char* src) { HGLOBAL hglbCopy; BYTE* pTmp; long len; if (src == NULL) return 0; if (src[0] == 0) return 0; len = strlen(src); hglbCopy = GlobalAlloc(GHND, len + 1); if (hglbCopy == NULL) return FALSE; pTmp = (BYTE*)GlobalLock(hglbCopy); memcpy(pTmp, src, len + 1); GlobalUnlock(hglbCopy); if (!OpenClipboard(hWnd)) { GlobalFree(hglbCopy); return 0; } EmptyClipboard(); SetClipboardData(CF_TEXT, hglbCopy); CloseClipboard(); return 1; } /// <summary> /// Starts the object3 /// </summary> /// <param name="hWnd"></param> /// <returns></returns> void StartObj3(HWND hWnd) { hWndDataCreator = FindWindow("OBJECT3", NULL); if (hWndDataCreator == NULL) // the required program is already running { // call to run the desired program WinExec("Object3.exe", SW_SHOW); hWndDataCreator = FindWindow("OBJECT3", NULL); } //сформуємо дані як суцільний масив, наприклад, так long params[allValues] = { n_MOD2}; SendCopyData(hWndDataCreator, hWnd, params, sizeof(params)); } #pragma endregion ModifiedFuntions <file_sep>/Lab3/Lab2/Lab3.cpp // Lab1.cpp : Defines the input point for the application. // // First Part #include "framework.h" #include "pch.h" #include "Lab3.h" #include "Resource.h" #include "shape_editor.h" #include "toolbar.h" #define MAX_LOADSTRING 100 #pragma region VariablesAndFunctions // Global variables: HINSTANCE hInst; // Current instance WCHAR szTitle[MAX_LOADSTRING]; // Header row text WCHAR szWindowClass[MAX_LOADSTRING]; // Class name of main window ShapeObjectsEditor editorShape; LPCSTR currentShape; const LPCSTR POINT_NAME = "Крапка"; const LPCSTR LINE_NAME = "Лінія"; const LPCSTR RECTANGLE_NAME = "Прямокутник"; const LPCSTR ELLIPSE_NAME = "Овал"; Toolbar toolbar; // Send declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); static void CallToolPoint(); static void CallToolLine(); static void CallToolRectangle(); static void CallToolEllipse(); #pragma endregion VariablesAndFunctions #pragma region DefaultFunctions // Second Part // Enter Point "wWinMain" int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); InitCommonControls(); // TODO: Place the code here. // Global line initialization LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadStringW(hInstance, IDC_LAB3, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance(hInstance, nCmdShow)) { return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_LAB3)); MSG msg; // Main message cycle: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int)msg.wParam; } // // FUNCTION: MyRegisterClass() // // OBJECTIVE: To register the window class. // Text of Function /// <summary> /// Register the window class. /// </summary> /// <param name="hInstance">The h instance.</param> /// <returns></returns> ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LAB3)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_LAB3); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassExW(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // OBJECTIVE: Saves the instance marker and creates the main window // // COMMENTARIES: // // In this function, the instance marker is saved in a global variable, and also // the main program window is created and displayed. // /// <summary> /// Saves the instance marker and creates the main window /// </summary> /// <param name="hInstance">The h instance.</param> /// <param name="nCmdShow">The n command show.</param> /// <returns></returns> BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; // Save instance marker in global variable HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } /// <summary> /// Message handler for "About" window. /// </summary> /// <param name="hDlg">The h dialog.</param> /// <param name="message">The message.</param> /// <param name="wParam">The w parameter.</param> /// <param name="lParam">The l parameter.</param> /// <returns></returns> INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } #pragma endregion #pragma region ModifiedFuntions // Third Part // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // OBJECTIVE: Processes messages in the main window. // // WM_COMMAND - Process the application menu // WM_PAINT - Drawing of the main window // WM_DESTROY - Send message about exit and return // // /// <summary> /// Processes messages in the main window. /// </summary> /// <param name="hWnd">The h WND.</param> /// <param name="message">The message.</param> /// <param name="wParam">The w parameter.</param> /// <param name="lParam">The l parameter.</param> /// <returns></returns> LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: toolbar.OnCreate(hWnd); // here we will create Toolbar break; case WM_SIZE: // this message is sent if the window resizes toolbar.OnSize(hWnd); break; case WM_NOTIFY: // message from the buttons toolbar.OnNotify(hWnd, lParam); break; case WM_LBUTTONDOWN: editorShape.OnLBdown(hWnd); break; case WM_LBUTTONUP: editorShape.OnLBup(hWnd); break; case WM_MOUSEMOVE: editorShape.OnMouseMove(hWnd); break; case WM_PAINT: editorShape.OnPaint(hWnd); break; case WM_INITMENUPOPUP: editorShape.OnInitMenuPopup(hWnd, wParam); break; case WM_COMMAND: { int wmId = LOWORD(wParam); switch (wmId) { case ID_TOOL_POINT: CallToolPoint(); break; case ID_TOOL_LINE: CallToolLine(); break; case ID_TOOL_RECTANGLE: CallToolRectangle(); break; case ID_TOOL_ELLIPSE: CallToolEllipse(); break; case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProcW(hWnd, message, wParam, lParam); } } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProcW(hWnd, message, wParam, lParam); } return 0; } /// <summary> /// Do something when Point tool is used /// </summary> void CallToolPoint() { toolbar.OnToolPoint(); editorShape.StartPointEditor(); } /// <summary> /// Do something when Line tool is used /// </summary> void CallToolLine() { toolbar.OnToolLine(); editorShape.StartLineEditor(); } /// <summary> /// Do something when Rectangle tool is used /// </summary> void CallToolRectangle() { toolbar.OnToolRectangle(); editorShape.StartRectangleEditor(); } /// <summary> /// Do something when Ellipse tool is used /// </summary> void CallToolEllipse() { toolbar.OnToolEllipse(); editorShape.StartEllipseEditor(); } /// <summary> /// Sets the shape name /// </summary> void SetShape(int ShapeNumber) { switch (ShapeNumber) { case(0): currentShape = POINT_NAME; break; case(1): currentShape = LINE_NAME; break; case(2): currentShape = RECTANGLE_NAME; break; case(3): currentShape = ELLIPSE_NAME; break; default: break; } } #pragma endregion ModifiedFuntions <file_sep>/Lab1/Lab1/module2.h #pragma once #include "resource2.h" #pragma region Function extern int Func_MOD2(HINSTANCE hInst, HWND hWnd); #pragma endregion <file_sep>/Lab6/Lab6/resource1.h //{{NO_DEPENDENCIES}} // Включаемый файл, созданный в Microsoft Visual C++. // Используется InputValuesModule.rc // #define IDOK 1 #define IDD_WARNING_VALUES 104 #define IDD_INPUT 129 #define IDD_WARNING_NULL 130 #define IDC_EDIT_N 1000 #define IDC_EDIT_MIN 1001 #define IDC_EDIT_MAX 1002 #define IDC_STATIC_MIN 1004 #define IDC_STATIC_MAX 1005 #define IDC_WARNING_VALUES_TEXT 1011 #define IDC_WARNING_VALUES_TEXT2 1012 #define IDC_STATIC_N 1013 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 106 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1002 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>/Lab5/Lab2/framework.h #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Исключите редко используемые компоненты из заголовков Windows // Файлы заголовков Windows #define APSTUDIO_HIDDEN_SYMBOLS #include <windows.h> #include "prsht.h" #undef APSTUDIO_HIDDEN_SYMBOLS // Файлы заголовков среды выполнения C #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <tchar.h> #include <fstream> #include <string> //--підключення бібліотеки Common Control Library-- #include <commctrl.h> #pragma comment(lib, "comctl32.lib") <file_sep>/Lab1/Lab1/module2.cpp #include "pch.h" #include "framework.h" #include "module3.h" #include "module2.h" #include "Resource.h" #pragma region FunctionsDeclaration static void OnNext(HWND hDlg); static void OnCancel(HWND hDlg); static void OnClose(HWND hDlg); static INT_PTR CALLBACK Work_MOD2(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); #pragma endregion #pragma region Functions /// <summary> /// dialog box creation function /// </summary> /// <param name="hInst">The hinst.</param> /// <param name="hWnd">The hWND.</param> /// <returns></returns> int Func_MOD2(HINSTANCE hInst, HWND hWnd) { return DialogBox(hInst, MAKEINTRESOURCE(IDD_WORK1_MOD2), hWnd, Work_MOD2); } /// <summary> /// Callback-function for first dialog window /// </summary> /// <param name="hDlg">The h dialog.</param> /// <param name="message">The message.</param> /// <param name="wParam">The w parameter.</param> /// <param name="lParam">The l parameter.</param> /// <returns></returns> INT_PTR CALLBACK Work_MOD2(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_CANCEL1_MOD2: OnCancel(hDlg); return (INT_PTR)TRUE; case IDC_NEXT_MOD2: OnNext(hDlg); return (INT_PTR)TRUE; } break; case WM_CLOSE: { OnClose(hDlg); } break; } return (INT_PTR)FALSE; } /// <summary> /// Called when IDC_NEXT_MOD2 clicked /// </summary> /// <param name="hDlg">The dialog.</param> void OnNext(HWND hDlg) { EndDialog(hDlg, 1); Func_MOD3(hInst, hDlg); } /// <summary> /// Called when IDC_CANCEL1_MOD2 clicked /// </summary> /// <param name="hDlg">The dialog.</param> void OnCancel(HWND hDlg) { EndDialog(hDlg, 0); } /// <summary> /// Called when window is closing /// </summary> /// <param name="hDlg">The dialog.</param> void OnClose(HWND hDlg) { EndDialog(hDlg, 0); } #pragma endregion <file_sep>/Lab5/Lab2/my_editor.cpp #include "framework.h" #include "pch.h" #include "my_editor.h" #include "toolbar.h" #include <sstream> #include <algorithm> #include <string> #pragma region Variables const int Size_Of_Array = 110; Shape* pcshape[Size_Of_Array]; int size = 0; bool isPressed; int const menuCount = 6; int allMenus[menuCount] = { ID_TOOL_POINT, ID_TOOL_LINE, ID_TOOL_RECTANGLE, ID_TOOL_ELLIPSE, ID_TOOL_LINEOO, ID_TOOL_CUBE}; #pragma endregion Variables #pragma region Functions /// <summary> /// Destructor /// </summary> MyEditor::~MyEditor() { for (int i = 0; i < size; i++) { delete pcshape[i]; } delete *pcshape; } /// <summary> /// Starts new Shape /// </summary> /// <param name="shape"></param> void MyEditor::Start(Shape* shape) { pcshape[size] = shape; } /// <summary> /// Do something, when LB is clicked /// </summary> /// <param name="hWnd"></param> void MyEditor::OnLBdown(HWND hWnd) { POINT pt; GetCursorPos(&pt); ScreenToClient(hWnd, &pt); X1 = X2 = pt.x; Y1 = Y2 = pt.y; isPressed = true; } /// <summary> /// Do something, when LB is unclicked /// </summary> /// <param name="hWnd"></param> void MyEditor::OnLBup(HWND hWnd) { POINT pt; GetCursorPos(&pt); ScreenToClient(hWnd, &pt); X2 = pt.x; Y2 = pt.y; isPressed = false; pcshape[size]->Set(X1, Y1, X2, Y2); size++; InvalidateRect(hWnd, NULL, TRUE); pcshape[size] = pcshape[size - 1]->Duplicate(); } /// <summary> /// Do something, when mouse is moved /// </summary> /// <param name="hWnd"></param> void MyEditor::OnMouseMove(HWND hWnd) { if (isPressed) { POINT pt; HDC hdc = GetDC(hWnd); SetROP2(hdc, R2_NOTXORPEN); MoveToEx(hdc, X1, Y1, NULL); pcshape[size]->Set(X1, Y1, X2, Y2); pcshape[size]->Trail(hdc); GetCursorPos(&pt); ScreenToClient(hWnd, &pt); X2 = pt.x; Y2 = pt.y; MoveToEx(hdc, X1, Y1, NULL); pcshape[size]->Set(X1, Y1, X2, Y2); pcshape[size]->Trail(hdc); ReleaseDC(hWnd, hdc); } } /// <summary> /// Do something, when paint is called /// </summary> /// <param name="hWnd"></param> void MyEditor::OnPaint(HWND hWnd) { PAINTSTRUCT ps; HDC hdc; hdc = BeginPaint(hWnd, &ps); for (int i = 0; i < size; i++) { if (pcshape[i]) { pcshape[i]->Show(hdc); } } EndPaint(hWnd, &ps); } /// <summary> /// Change InitMenuPopup /// </summary> /// <param name="hWnd"></param> /// <param name="wParams"></param> void MyEditor::OnInitMenuPopup(HWND hWnd, WPARAM wParams) { HMENU hMenu, hSubMenu; hMenu = GetMenu(hWnd); hSubMenu = GetSubMenu(hMenu, 1); if ((HMENU)wParams == hSubMenu) { for (auto& item : allMenus) { CheckMenuItem(hSubMenu, item, MF_UNCHECKED); } switch (pcshape[size]->InitMenuPopup()) { case ID_TOOL_POINT: CheckMenuItem(hSubMenu, IDM_POINT, MF_CHECKED); break; case ID_TOOL_LINE: CheckMenuItem(hSubMenu, IDM_LINE, MF_CHECKED); break; case ID_TOOL_RECTANGLE: CheckMenuItem(hSubMenu, IDM_RECTANGLE, MF_CHECKED); break; case ID_TOOL_ELLIPSE: CheckMenuItem(hSubMenu, IDM_ELLIPSE, MF_CHECKED); break; case ID_TOOL_LINEOO: CheckMenuItem(hSubMenu, IDM_LINEOO, MF_CHECKED); break; case ID_TOOL_CUBE: CheckMenuItem(hSubMenu, IDM_CUBE, MF_CHECKED); break; } } } /// <summary> /// Get name and coords of the shape /// </summary> /// <returns></returns> std::string MyEditor::GetDetails() { std::stringstream buffer; buffer << pcshape[size]->GetShapeName(); buffer << " \t "; buffer << X1; buffer << " \t "; buffer << Y1; buffer << " \t "; buffer << X2; buffer << " \t "; buffer << Y2; std::string shapeString = buffer.str(); return shapeString; } #pragma endregion Functions <file_sep>/Lab6/Object3/Object3.cpp // Object3.cpp : Defines the input point for the application. // // First Part #include "framework.h" #include "pch.h" #include "Object3.h" #include "Resource.h" #include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; #define MAX_LOADSTRING 100 #pragma region VariablesAndFunctions // Global variables: HINSTANCE hInst; // Current instance WCHAR szTitle[MAX_LOADSTRING]; // Header row text WCHAR szWindowClass[MAX_LOADSTRING]; // Class name of main window char bufferText[1024]; int n_MOD3; std::vector<int> buffer; int determinant; // Send declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); long GetTextFromClipboard(HWND, char*, long); void CalculateDeterminant(HWND hWnd); void OnCopyData(HWND hWnd, WPARAM wParam, LPARAM lParam); #pragma endregion VariablesAndFunctions #pragma region DefaultFunctions // Second Part // Enter Point "wWinMain" int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place the code here. // Global line initialization LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadStringW(hInstance, IDC_OBJECT3, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance(hInstance, nCmdShow)) { return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_OBJECT3)); MSG msg; // Main message cycle: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int)msg.wParam; } // // FUNCTION: MyRegisterClass() // // OBJECTIVE: To register the window class. // Text of Function /// <summary> /// Register the window class. /// </summary> /// <param name="hInstance">The h instance.</param> /// <returns></returns> ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDC_OBJECT3)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_OBJECT3); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassExW(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // OBJECTIVE: Saves the instance marker and creates the main window // // COMMENTARIES: // // In this function, the instance marker is saved in a global variable, and also // the main program window is created and displayed. // /// <summary> /// Saves the instance marker and creates the main window /// </summary> /// <param name="hInstance">The h instance.</param> /// <param name="nCmdShow">The n command show.</param> /// <returns></returns> BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; // Save instance marker in global variable HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } /// <summary> /// Message handler for "About" window. /// </summary> /// <param name="hDlg">The h dialog.</param> /// <param name="message">The message.</param> /// <param name="wParam">The w parameter.</param> /// <param name="lParam">The l parameter.</param> /// <returns></returns> INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } #pragma endregion #pragma region ModifiedFuntions // Third Part // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // OBJECTIVE: Processes messages in the main window. // // WM_COMMAND - Process the application menu // WM_PAINT - Drawing of the main window // WM_DESTROY - Send message about exit and return // // /// <summary> /// Processes messages in the main window. /// </summary> /// <param name="hWnd">The h WND.</param> /// <param name="message">The message.</param> /// <param name="wParam">The w parameter.</param> /// <param name="lParam">The l parameter.</param> /// <returns></returns> LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: { GetTextFromClipboard(hWnd, bufferText, sizeof(bufferText)); SetWindowPos(hWnd, HWND_BOTTOM, 141, 40, 400, 300, SWP_DEFERERASE); } break; case WM_COPYDATA: { OnCopyData(hWnd, wParam, lParam); CalculateDeterminant(hWnd); InvalidateRect(hWnd, 0, TRUE); } break; case WM_COMMAND: { int wmId = LOWORD(wParam); switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProcW(hWnd, message, wParam, lParam); } } break; case WM_DESTROY: PostQuitMessage(0); break; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); RECT rc = { 0 }; GetClientRect(hWnd, &rc); UpdateWindow(hWnd); // dynamic allocation int** matrix = new int* [n_MOD3]; for (int i = 0; i < n_MOD3; ++i) { matrix[i] = new int[n_MOD3]; } std::string tempBufferForMatrixString = bufferText; string num; std::replace(tempBufferForMatrixString.begin(), tempBufferForMatrixString.end(), '\n', ' '); while (tempBufferForMatrixString != "") { num = tempBufferForMatrixString.substr( 0, tempBufferForMatrixString.find_first_of(" ")); buffer.push_back(stod(num)); tempBufferForMatrixString = tempBufferForMatrixString.substr( tempBufferForMatrixString.find_first_of(" ") + 1); } //fill for (int i = 0; i < n_MOD3; ++i) { for (int j = 0; j < n_MOD3; ++j) { matrix[i][j] = buffer[i]; //TextOutA(hdc, 0,0,(LPCSTR)buffer[i],1); } } int num1, num2, det = 1, index, total = 1; // Initialize result // temporary array for storing row int** tempArr = new int* [n_MOD3 + 1]; int temp; //// loop for traversing the diagonal elements for (int k = 0; k < n_MOD3; k++) { index = k; // initialize the index // finding the index which has non zero value while (matrix[index][k] == 0 && index < n_MOD3) { index++; } if (index == n_MOD3) // if there is non zero element { // the determinat of matrix as zero continue; } if (index != k) { // loop for swaping the diagonal element row and // index row for (int l = 0; l < n_MOD3; l++) { swap(matrix[index][l], matrix[k][l]); } // determinant sign changes when we shift rows // go through determinant properties det = det * pow(-1, index - k); } // storing the values of diagonal row elements for (int p = 0; p < n_MOD3; p++) { tempArr[p] = (int*)matrix[k][p]; } // traversing every row below the diagonal element for (int r = k + 1; r < n_MOD3; r++) { num1 = (int)tempArr[k]; // value of diagonal element num2 = matrix[r][k]; // value of next row element // traversing every column of row // and multiplying to every row for (int t = 0; t < n_MOD3; t++) { // multiplying to make the diagonal // element and next row element equal matrix[r][t] = (num1 * matrix[r][t]) - (num2 * (int)tempArr[t]); } total = total * num1; // Det(kA)=kDet(A); } int temp = det; temp = det * matrix[k][k]; } //// mulitplying the diagonal elements to get determinant //for (int i = 0; i < n_MOD3; i++) //{ // temp = det * matrix[i][i]; //} //determinant = (temp / total); // Det(kA)/k=Det(A); // free for (int z = 0; z < n_MOD3; ++z) { delete[] matrix[z]; } delete[] matrix; //TextOutA(hdc,0,0, (LPCSTR)determinant,10); EndPaint(hWnd, &ps); } break; default: return DefWindowProcW(hWnd, message, wParam, lParam); } return 0; } /// <summary> /// Calculates determinant /// </summary> /// <param name="hWnd"></param> void CalculateDeterminant(HWND hWnd) { } /// <summary> /// Copy the data from another window /// </summary> /// <param name="hWnd"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> void OnCopyData(HWND hWnd, WPARAM wParam, LPARAM lParam) { COPYDATASTRUCT* cds; cds = (COPYDATASTRUCT*)lParam; long* p = (long*)cds->lpData; n_MOD3 = p[0]; } /// <summary> /// Get text from Clipboard /// </summary> /// <param name="hWnd"></param> /// <param name="dest"></param> /// <param name="maxsize"></param> long GetTextFromClipboard(HWND hWnd, char* dest, long maxsize) { HGLOBAL hglb; LPTSTR lptstr; long size, res; res = 0; if (!IsClipboardFormatAvailable(CF_TEXT)) return 0; if (!OpenClipboard(hWnd)) return 0; hglb = GetClipboardData(CF_TEXT); if (hglb != NULL) { lptstr = (LPTSTR)GlobalLock(hglb); if (lptstr != NULL) { size = strlen((char*)lptstr); if (size > maxsize) { lptstr[maxsize] = 0; size = strlen((char*)lptstr); } strcpy_s(dest, maxsize, (char*)lptstr); res = size; GlobalUnlock(hglb); } } CloseClipboard(); return res; } #pragma endregion ModifiedFuntions <file_sep>/Lab2/Lab2/shape.h #include "pch.h" /// <summary> /// Main class for shapes /// </summary> class Shape { protected: long xs1, ys1, xs2, ys2; public: void Set(long x1, long y1, long x2, long y2); virtual void Show(HDC) = 0; }; /// <summary> /// Class for points /// </summary> class PointShape : public Shape { public: void Show(HDC); }; /// <summary> /// Class for lines /// </summary> class LineShape : public Shape { public: void Show(HDC); }; /// <summary> /// Class for rectangles /// </summary> class RectangleShape : public Shape { public: void Show(HDC); }; /// <summary> /// Class for ellipses /// </summary> class EllipseShape : public Shape { public: void Show(HDC); }; <file_sep>/Lab3/Lab2/toolbar.cpp #include "framework.h" #include "pch.h" #include "lab3.h" #include "toolbar.h" #include "resource1.h" #pragma region Variables HWND hwndToolBar = NULL; int point, line, rectangle, ellipse, buttonToChange = 0; const int allShapes = 5; int shapes[allShapes] = { point ,line ,rectangle ,ellipse ,buttonToChange }; const LPCSTR pointName = "Крапка"; const LPCSTR lineName = "Лінія"; const LPCSTR rectangleName = "Прямокутник"; const LPCSTR ellipseName = "Овал"; const LPCSTR unnkownName = "Щось невідоме"; #pragma endregion Variables #pragma region Functions /// <summary> /// Creates toolbar /// </summary> /// <param name="hWnd"></param> void Toolbar::OnCreate(HWND hWnd) { TBBUTTON tbb[5]; ZeroMemory(tbb, sizeof(tbb)); tbb[0].iBitmap = 0; tbb[0].fsState = TBSTATE_ENABLED; tbb[0].fsStyle = TBSTYLE_BUTTON; tbb[0].idCommand = ID_TOOL_POINT; tbb[1].iBitmap = 1; tbb[1].fsState = TBSTATE_ENABLED; tbb[1].fsStyle = TBSTYLE_BUTTON; tbb[1].idCommand = ID_TOOL_LINE; tbb[2].iBitmap = 2; // image index in BITMAP tbb[2].fsState = TBSTATE_ENABLED; tbb[2].fsStyle = TBSTYLE_BUTTON; tbb[2].idCommand = ID_TOOL_RECTANGLE; tbb[3].iBitmap = 3; tbb[3].fsState = TBSTATE_ENABLED; tbb[3].fsStyle = TBSTYLE_BUTTON; tbb[3].idCommand = ID_TOOL_ELLIPSE; tbb[4].iBitmap = 4; tbb[4].fsState = TBSTATE_ENABLED; tbb[4].fsStyle = TBSTYLE_SEP; // separator of groups of buttons tbb[4].idCommand = 0; hwndToolBar = CreateToolbarEx(hWnd, WS_CHILD | WS_VISIBLE | WS_BORDER | WS_CLIPSIBLINGS | CCS_TOP | TBSTYLE_TOOLTIPS, IDC_MY_TOOLBAR, 4, // number of images in BITMAP hInst, IDB_BITMAP1, // BITMAP resource ID tbb, 5, // number of buttons (with separator) 24, 24, 24, 24, // BITMAP button and image sizes sizeof(TBBUTTON)); } // --- message handler WM_SIZE --- /// <summary> /// Change size of toolbar /// </summary> /// <param name="hWnd"></param> void Toolbar::OnSize(HWND hWnd) { RECT rc, rw; if (hwndToolBar) { GetClientRect(hWnd, &rc); // new dimensions of the main window GetWindowRect(hwndToolBar, &rw); // we need to know the height of the Toolbar MoveWindow(hwndToolBar, 0, 0, rc.right - rc.left, rw.bottom - rw.top, FALSE); } } /// <summary> /// UnClick button and click button /// </summary> /// <param name="button"> button to unclick/click </param> /// <param name="shape"> shape element </param> void Toolbar::ChangeButton(int button, int shape) { SendMessage(hwndToolBar, TB_PRESSBUTTON, buttonToChange, 0); buttonToChange = button; SendMessage(hwndToolBar, TB_PRESSBUTTON, buttonToChange, shape); } /// <summary> /// Set all elements to zero /// </summary> void Toolbar::SetToZeros() { for (auto& item : shapes) { item = 0; } } /// <summary> /// Sets value to opposite value /// </summary> /// <param name="value"></param> void Toolbar::SetToOpposite(int value) { shapes[value] = !shapes[value]; } /// <summary> /// Function for drawing points with buttons animation /// </summary> void Toolbar::OnToolPoint() { SetToZeros(); SetToOpposite(0); ChangeButton(ID_TOOL_POINT,shapes[0]); } /// <summary> /// Function for drawing lines with buttons animation /// </summary> void Toolbar::OnToolLine() { SetToZeros(); SetToOpposite(1); ChangeButton(ID_TOOL_LINE, shapes[1]); } /// <summary> /// Function for drawing rectangles with buttons animation /// </summary> void Toolbar::OnToolRectangle() { SetToZeros(); SetToOpposite(2); ChangeButton(ID_TOOL_RECTANGLE, shapes[2]); } /// <summary> /// Function for drawing ellipses with buttons animation /// </summary> void Toolbar::OnToolEllipse() { SetToZeros(); SetToOpposite(3); ChangeButton(ID_TOOL_ELLIPSE, shapes[3]); } /// <summary> /// Function for tooltips /// </summary> /// <param name="hWnd"></param> /// <param name="lParam"></param> void Toolbar::OnNotify(HWND hWnd, LPARAM lParam) { LPNMHDR pnmh = (LPNMHDR)lParam; LPCSTR pText; if (pnmh->code == TTN_NEEDTEXT) { LPTOOLTIPTEXT lpttt = (LPTOOLTIPTEXT)lParam; switch (lpttt->hdr.idFrom) { case ID_TOOL_POINT: pText = pointName; break; case ID_TOOL_LINE: pText = lineName; break; case ID_TOOL_RECTANGLE: pText = rectangleName; break; case ID_TOOL_ELLIPSE: pText = ellipseName; break; default: pText = unnkownName; } lstrcpy(lpttt->szText, pText); } } #pragma endregion Functions <file_sep>/README.md # OOP <p align="center"> <img src="https://github.com/VsIG-official/KPI-OOP/blob/master/pict.png" data-canonical-src="https://github.com/VsIG-official/KPI-OOP/blob/master/pict.png" width="600" height="300" /> </p> ## Table of Contents - [Description](#description) - [Badges](#badges) - [Contributing](#contributing) - [License](#license) ### Description This repo was created for subject "OOP" and have both labs and lectures ## Badges > [![Theme](https://img.shields.io/badge/Theme-OOP-blue?style=flat-square)](https://en.wikipedia.org/wiki/Object-oriented_programming) > [![Language](https://img.shields.io/badge/Language-C++-blue?style=flat-square)](https://en.wikipedia.org/wiki/C%2B%2B) > [![License](http://img.shields.io/:license-mit-blue.svg?style=flat-square)](http://badges.mit-license.org) --- ## Example ```cpp /// <summary> /// Do something, when LB is unclicked /// </summary> /// <param name="hWnd"></param> void MyEditor::OnLBup(HWND hWnd) { POINT pt; GetCursorPos(&pt); ScreenToClient(hWnd, &pt); X2 = pt.x; Y2 = pt.y; isPressed = false; pcshape[size]->Set(X1, Y1, X2, Y2); size++; InvalidateRect(hWnd, NULL, TRUE); pcshape[size] = pcshape[size - 1]->Duplicate(); } ``` --- ## Contributing > To get started... ### Step 1 - 🍴 Fork this repo! ### Step 2 - **HACK AWAY!** 🔨🔨🔨 --- ## License [![License](http://img.shields.io/:license-mit-blue.svg?style=flat-square)](http://badges.mit-license.org) - **[MIT license](http://opensource.org/licenses/mit-license.php)** - Copyright 2021 © <a href="https://github.com/VsIG-official" target="_blank">VsIG</a>. <file_sep>/Lab5/Lab2/shape.h #include "pch.h" /// <summary> /// Main class for shapes /// </summary> class Shape { protected: long XS1, YS1, XS2, YS2; public: void Set(long X1, long Y1, long X2, long Y2); virtual void Show(HDC) = 0; virtual void Trail(HDC) = 0; virtual int InitMenuPopup() = 0; virtual Shape* Duplicate() = 0; virtual std::string GetShapeName() = 0; ~Shape(); }; /// <summary> /// Class for point /// </summary> class PointShape : public Shape { virtual void Show(HDC); void Trail(HDC); int InitMenuPopup(); virtual Shape* Duplicate(); virtual std::string GetShapeName(); }; /// <summary> /// Class for line /// </summary> class LineShape : public virtual Shape { public: virtual void Show(HDC); void Trail(HDC); int InitMenuPopup(); virtual Shape* Duplicate(); virtual std::string GetShapeName(); }; /// <summary> /// Class for rectangle /// </summary> class RectangleShape : public virtual Shape { public: virtual void Show(HDC); void Trail(HDC); int InitMenuPopup(); virtual Shape* Duplicate(); virtual std::string GetShapeName(); }; /// <summary> /// Class for ellipse /// </summary> class EllipseShape : public virtual Shape { public: virtual void Show(HDC); void Trail(HDC); int InitMenuPopup(); virtual Shape* Duplicate(); virtual std::string GetShapeName(); }; /// <summary> /// Class for lineOO /// </summary> class LineOOShape : public LineShape, public EllipseShape { public: void Show(HDC); void Trail(HDC); int InitMenuPopup(); virtual Shape* Duplicate(); virtual std::string GetShapeName(); }; /// <summary> /// Class for cube /// </summary> class CubeShape : public RectangleShape, public LineShape { public: void Show(HDC); void Trail(HDC); int InitMenuPopup(); virtual Shape* Duplicate(); virtual std::string GetShapeName(); }; <file_sep>/Lab5/Lab2/my_table.cpp #include "framework.h" #include "pch.h" #include "my_table.h" static string pathForShapes = "objects.txt"; static LPCSTR exceptionString = "Can't open a file or find a file"; /// <summary> /// Add shape to table /// </summary> /// <param name="shapeDetails">name and coords</param> void MyTable::Add(HWND hWndDlg, std::string shapeDetails) { ofstream myTableFile; myTableFile.open(pathForShapes, ofstream::app); if (myTableFile.is_open()) { myTableFile << shapeDetails << endl; } else { throw new exception(exceptionString); } myTableFile.close(); SendDlgItemMessage(hWndDlg, IDC_LIST, LB_ADDSTRING, 0, (LPARAM)shapeDetails.c_str()); } <file_sep>/Lab1/Lab1/Lab1.cpp // Lab1.cpp : Defines the input point for the application. // // First Part #include "pch.h" #include "framework.h" #include "Lab1.h" #include "module1.h" #include "module2.h" #define MAX_LOADSTRING 100 #pragma region Variables // Global variables: HINSTANCE hInst; // Current instance WCHAR szTitle[MAX_LOADSTRING]; // Header row text WCHAR szWindowClass[MAX_LOADSTRING]; // Class name of main window // Send declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); static INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); static void Work1(HWND hWnd); // Declaration of our function static void Work2(HWND hWnd); // Declaration of our function static void About1(HWND hWnd); // Declaration of our function static void DrawTextOnScreen(HWND hWnd); // Declaration of our function static int textHeightPosition = 0; static int textWidthPosition = 0; static TCHAR buffer[255] = { 0 }; #pragma endregion #pragma region DefaultFunctions // Second Part // Enter Point "wWinMain" int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place the code here. // Global line initialization LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadStringW(hInstance, IDC_LAB1, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance(hInstance, nCmdShow)) { return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_LAB1)); MSG msg; // Main message cycle: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int)msg.wParam; } // // FUNCTION: MyRegisterClass() // // OBJECTIVE: To register the window class. // Text of Function /// <summary> /// Register the window class. /// </summary> /// <param name="hInstance">The h instance.</param> /// <returns></returns> ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LAB1)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_LAB1); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassExW(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // OBJECTIVE: Saves the instance marker and creates the main window // // COMMENTARIES: // // In this function, the instance marker is saved in a global variable, and also // the main program window is created and displayed. // /// <summary> /// Saves the instance marker and creates the main window /// </summary> /// <param name="hInstance">The h instance.</param> /// <param name="nCmdShow">The n command show.</param> /// <returns></returns> BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; // Save instance marker in global variable HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } #pragma endregion #pragma region ModifiedFuntions // Third Part // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // OBJECTIVE: Processes messages in the main window. // // WM_COMMAND - Process the application menu // WM_PAINT - Drawing of the main window // WM_DESTROY - Send message about exit and return // // /// <summary> /// Processes messages in the main window. /// </summary> /// <param name="hWnd">The h WND.</param> /// <param name="message">The message.</param> /// <param name="wParam">The w parameter.</param> /// <param name="lParam">The l parameter.</param> /// <returns></returns> LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: { int wmId = LOWORD(wParam); // Disassemble the selection in the menu: switch (wmId) { case IDM_WORK_MOD1: // first menu Work1(hWnd); break; case IDM_WORK_MOD2: // second menu Work2(hWnd); break; case IDM_ABOUT: // About Menu About1(hWnd); break; case IDM_EXIT: // Exit menu DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } } break; case WM_PAINT: { DrawTextOnScreen(hWnd); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Fourth Part /// <summary> /// Message handler for "About" window. /// </summary> /// <param name="hDlg">The h dialog.</param> /// <param name="message">The message.</param> /// <param name="wParam">The w parameter.</param> /// <param name="lParam">The l parameter.</param> /// <returns></returns> INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { // When window is created case WM_INITDIALOG: return (INT_PTR)TRUE; // When OK is clicked case WM_COMMAND: if (LOWORD(wParam) == IDOK) { // End dialog window EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } else if (LOWORD(wParam) == IDCANCEL) { // End dialog window EndDialog(hDlg, 0); return (INT_PTR)TRUE; } break; case WM_CLOSE: { EndDialog(hDlg, 0); } break; } return (INT_PTR)FALSE; } /// <summary> /// Function-handler of the menu item "Work1" /// </summary> /// <param name="hWnd">The h WND.</param> void Work1(HWND hWnd) { // What we program here that will be done Func_MOD1(hInst,hWnd,buffer); // The update region represents the portion of the window's // client area that must be redrawn. InvalidateRect(hWnd, 0, TRUE); } /// <summary> /// Function-handler of the menu item "Work2" /// </summary> /// <param name="hWnd">The h WND.</param> void Work2(HWND hWnd) { // What we program here that will be done Func_MOD2(hInst, hWnd); // The update region represents the portion of the window's // client area that must be redrawn. InvalidateRect(hWnd, 0, TRUE); } /// <summary> /// Function-handler of the menu item "About" /// </summary> /// <param name="hWnd">The h WND.</param> void About1(HWND hWnd) { DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); } /// <summary> /// Draws the text on screen. /// </summary> /// <param name="hWnd">hWND</param> void DrawTextOnScreen(HWND hWnd) { PAINTSTRUCT ps; UpdateWindow(hWnd); HDC hdc = BeginPaint(hWnd, &ps); if (canWrite_MOD1) { _itoa_s(pos_MOD1, buffer, sizeof(pos_MOD1), 10); canWrite_MOD1 = FALSE; } TextOut(hdc, textHeightPosition, textWidthPosition, " ", 7); TextOut(hdc, textHeightPosition, textWidthPosition, buffer, numOfDig_MOD1); ZeroMemory(buffer, pos_MOD1); EndPaint(hWnd, &ps); } #pragma endregion <file_sep>/Lab1/Lab1/resource3.h //{{NO_DEPENDENCIES}} // Included file created in Microsoft Visual C++. // Using module3.rc // #ifndef MODULE_3_H #define MODULE_3_H #define IDD_WORK2_MOD2 103 #define IDC_BACK_MOD2 104 #define IDC_CANCEL2_MOD2 1002 #define IDC_OK2_MOD2 1003 #endif // MODULE_3_H // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>/Lab4/Lab2/shape.cpp #include "framework.h" #include "pch.h" #include "shape.h" #include "colors.h" #pragma region Functions /// <summary> /// // Get coords of points /// </summary> /// <param name="x1">first point</param> /// <param name="y1">second point</param> /// <param name="x2">third point</param> /// <param name="y2">fourth point</param> void Shape::Set(long x1, long y1, long x2, long y2) { xs1 = x1; ys1 = y1; xs2 = x2; ys2 = y2; } #pragma region Point /// <summary> /// Shows the pixel /// </summary> /// <param name="hdc">handle to a device context</param> void PointShape::Show(HDC hdc) { SetPixel(hdc, xs1, ys1, black); } //void PointShape::OnLBdown(HWND hWnd) //{ // POINT pt; // GetCursorPos(&pt); // ScreenToClient(hWnd, &pt); // int x = pt.x; // int y = pt.y; // this->Set(x, y, x, y); // InvalidateRect(hWnd, NULL, TRUE); //} //Shape* PointShape::OnLBup(HWND hWnd) //{ // return new PointShape; //} // //void PointShape::OnMouseMove(HWND hWnd) {}; #pragma endregion Point #pragma region Line /// <summary> /// Shows the line /// </summary> /// <param name="hdc">handle to a device context</param> void LineShape::Show(HDC hdc) { HPEN hPen, hPenOld; hPen = CreatePen(PS_SOLID, 1, black); hPenOld = (HPEN)SelectObject(hdc, hPen); MoveToEx(hdc, xs1, ys1, NULL); LineTo(hdc, xs2, ys2); SelectObject(hdc, hPenOld); DeleteObject(hPen); } #pragma endregion Line #pragma region Rectangle /// <summary> /// Shows the rectangle /// </summary> /// <param name="hdc">handle to a device context</param> void RectangleShape::Show(HDC hdc) { HPEN hPen, hPenOld; HBRUSH hBrush, hBrushOld; hPen = CreatePen(PS_SOLID, 1, black); hPenOld = (HPEN)SelectObject(hdc, hPen); hBrush = CreateSolidBrush(white); hBrushOld = (HBRUSH)SelectObject(hdc, hBrush); SelectObject(hdc, hBrush); Rectangle(hdc, xs1, ys1, xs2, ys2); SelectObject(hdc, hBrushOld); DeleteObject(hBrush); SelectObject(hdc, hPenOld); DeleteObject(hPen); } #pragma endregion Rectangle #pragma region Ellipse /// <summary> /// Shows the ellipse /// </summary> /// <param name="hdc">handle to a device context</param> void EllipseShape::Show(HDC hdc) { HPEN hPen, hPenOld; HBRUSH hBrush, hBrushOld; hPen = CreatePen(PS_SOLID, 1, black); hPenOld = (HPEN)SelectObject(hdc, hPen); Arc(hdc, xs1, ys1, xs2, ys2, 0, 0, 0, 0); SelectObject(hdc, hPenOld); DeleteObject(hPen); }; #pragma endregion Ellipse #pragma region LineOO /// <summary> /// Shows the ellipse /// </summary> /// <param name="hdc">handle to a device context</param> void LineOOShape::Show(HDC hdc) { HPEN hPen, hPenOld; HBRUSH hBrush, hBrushOld; hPen = CreatePen(PS_SOLID, 1, black); hPenOld = (HPEN)SelectObject(hdc, hPen); Arc(hdc, xs1, ys1, xs2, ys2, 0, 0, 0, 0); SelectObject(hdc, hPenOld); DeleteObject(hPen); }; #pragma endregion LineOO #pragma region Cube /// <summary> /// Shows the ellipse /// </summary> /// <param name="hdc">handle to a device context</param> void CubeShape::Show(HDC hdc) { HPEN hPen, hPenOld; HBRUSH hBrush, hBrushOld; hPen = CreatePen(PS_SOLID, 1, black); hPenOld = (HPEN)SelectObject(hdc, hPen); Arc(hdc, xs1, ys1, xs2, ys2, 0, 0, 0, 0); SelectObject(hdc, hPenOld); DeleteObject(hPen); }; #pragma endregion Cube Shape::~Shape() {}; #pragma endregion Functions <file_sep>/Lab1/Lab1/pch.cpp // pch.cpp: source code file corresponding to the pre-compiled header file #include "pch.h" // When using precompiled header files, the following source code file is required to perform the build. <file_sep>/Lab2/Lab2/editor.h #pragma once #include "pch.h" /// <summary> /// Main interface /// </summary> class Editor { public: virtual void OnLBdown(HWND) = 0; virtual void OnLBup(HWND) = 0; virtual void OnMouseMove(HWND) = 0; virtual void OnPaint(HWND) = 0; }; <file_sep>/Lab4/New/Lab2/my_editor.h #pragma once #include "pch.h" #include "Resource.h" #include "shape.h" #pragma region Editors /// <summary> /// Shape editor class for figures /// </summary> class MyEditor { public: void Start(Shape*); void OnLBdown(HWND); void OnLBup(HWND); void OnMouseMove(HWND); void OnPaint(HWND); void OnInitMenuPopup(HWND, WPARAM); ~MyEditor(); long X1, Y1, X2, Y2; }; #pragma endregion Editors <file_sep>/Lab4/Lab2/my_editor.h #pragma once #include "pch.h" #include "editor.h" #include "Resource.h" #include "shape.h" #pragma region Editors /// <summary> /// Shape editor class for figure objects /// </summary> class MyEditor { private: public: long x1, x2, y1, y2; ~MyEditor(); void OnLBdown(HWND); void OnLBup(HWND); void OnMouseMove(HWND); void OnPaint(HWND); void OnInitMenuPopup(HWND, WPARAM); //void Add(Shape* object); Shape* ReturnObject(int i); void Start(Shape* shape,int id); }; #pragma endregion Editors <file_sep>/Lab1/Lab1/pch.h // pch.h: this is a precompiled header file. // The files listed below are compiled only once, which speeds up subsequent builds. // It also affects the operation of IntelliSense, including many code review and termination functions. // However, changing any of the files listed here between build operations will result in a second compilation of all (!) of these files. // Do not add files that you plan to change frequently, as there will be no performance gain. #ifndef PCH_H #define PCH_H // Add header files for pre-compilation here #include "framework.h" #endif //PCH_H <file_sep>/Lab5/Lab2/colors.h #pragma once #include "pch.h" static COLORREF blue = RGB(0, 0, 255); static COLORREF black = RGB(0, 0, 0); static COLORREF white = RGB(255, 255, 255); <file_sep>/Lab4/New/Lab2/resource.h //{{NO_DEPENDENCIES}} // Включаемый файл, созданный в Microsoft Visual C++. // Используется Lab2.rc // #include "colors.h" #define IDC_MYICON 2 #define IDD_LAB3_DIALOG 102 #define IDS_APP_TITLE 103 #define IDD_ABOUTBOX 103 #define IDM_ABOUT 104 #define IDM_EXIT 105 #define IDI_LAB3 107 #define IDI_SMALL 1022 #define IDC_LAB3 109 #define IDM_POINT 32805 #define IDM_LINE 32806 #define IDM_RECTANGLE 32807 #define IDM_ELLIPSE 32809 #define IDM_LINEOO 32824 #define IDM_CUBE 32825 #define IDC_STATIC -1 extern HINSTANCE hInst; // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 #define _APS_NEXT_RESOURCE_VALUE 129 #define _APS_NEXT_COMMAND_VALUE 32779 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 110 #endif #endif <file_sep>/Lab5/Lab2/resource2.h //{{NO_DEPENDENCIES}} // Включаемый файл, созданный в Microsoft Visual C++. // Используется my_table.rc // #define IDD_TABLE 101 #define IDC_LIST 1002 #define IDC_EXIT 1003 #define IDC_CLEAR 1004 #define IDCLEAR 1004 #define IDC_EDIT1 1005 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 103 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1006 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>/Lab1/Lab1/Resource.h //{{NO_DEPENDENCIES}} // Include file created in Microsoft Visual C++. // Lab1.rc is used. // #define IDC_MYICON 2 #define IDD_LAB1_DIALOG 102 #define IDS_APP_TITLE 1003 #define IDD_ABOUTBOX 1093 #define IDM_ABOUT 10084 #define IDD_WORK 104 #define IDM_EXIT 105 #define IDI_LAB1 107 #define IDI_SMALL 108 #define IDC_LAB1 109 #define IDR_MAINFRAME 128 #define IDM_WORK 32771 #define IDM_WORK1 32772 #define IDM_WORK2 32773 #define IDM_WORK_MOD1 32775 #define IDM_WORK_MOD2 32776 #define IDC_STATIC -1 extern HINSTANCE hInst; // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 #define _APS_NEXT_RESOURCE_VALUE 132 #define _APS_NEXT_COMMAND_VALUE 32777 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 110 #endif #endif <file_sep>/Lab3/Lab2/shape_editor.h #pragma once #include "pch.h" #include "editor.h" #include "Resource.h" #pragma region Editors /// <summary> /// Shape editor class for figures /// </summary> class ShapeEditor : public Editor { protected: long x1, x2, y1, y2; public: void OnLBdown(HWND); void OnLBup(HWND); void OnMouseMove(HWND); void OnPaint(HWND); virtual void OnInitMenuPopup(HWND, WPARAM); }; /// <summary> /// Shape editor class for figure objects /// </summary> class ShapeObjectsEditor { private: ShapeEditor* pse; public: ShapeObjectsEditor(void); ~ShapeObjectsEditor(); void StartPointEditor(); void StartLineEditor(); void StartRectangleEditor(); void StartEllipseEditor(); void OnLBdown(HWND); void OnLBup(HWND); void OnMouseMove(HWND); void OnPaint(HWND); void OnInitMenuPopup(HWND, WPARAM); }; /// <summary> /// Point editor class for points /// </summary> class PointEditor : public ShapeEditor { public: void OnLBup(HWND); void OnInitMenuPopup(HWND, WPARAM); }; /// <summary> /// Line editor class for lines /// </summary> class LineEditor : public ShapeEditor { public: void OnLBup(HWND); void OnMouseMove(HWND); void OnInitMenuPopup(HWND, WPARAM); }; /// <summary> /// Rectangle editor class for rectangles /// </summary> class RectangleEditor : public ShapeEditor { public: void OnLBup(HWND); void OnMouseMove(HWND); void OnInitMenuPopup(HWND, WPARAM); }; /// <summary> /// Ellipse editor class for ellipses /// </summary> class EllipseEditor : public ShapeEditor { public: void OnLBup(HWND); void OnMouseMove(HWND); void OnInitMenuPopup(HWND, WPARAM); }; #pragma endregion Editors <file_sep>/Lab1/Lab1/resource2.h //{{NO_DEPENDENCIES}} // Included file created in Microsoft Visual C++. // Using module2.rc // #ifndef MODULE_2_H #define MODULE_2_H #define IDC_BACK_MOD2 104 #define IDD_WORK2_MOD2 103 #define IDD_WORK1_MOD2 105 #define IDC_CANCEL2_MOD2 1002 #define IDC_OK2_MOD2 1003 #define IDC_NEXT_MOD2 1008 #define IDC_CANCEL1_MOD2 1007 #endif // MODULE_2_H // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 107 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1008 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>/Lab3/Lab2/toolbar.h #pragma once #define ID_TOOL_POINT 32805 #define ID_TOOL_LINE 32806 #define ID_TOOL_RECTANGLE 32807 #define ID_TOOL_ELLIPSE 32809 #define IDC_MY_TOOLBAR 32811 /// <summary> /// Toolbar class for creating toolbar /// </summary> class Toolbar { private: static void SetToZeros(); static void SetToOpposite(int value); static void ChangeButton(int button, int shape); public: void OnSize(HWND hWnd); void OnCreate(HWND hWnd); void OnNotify(HWND hWnd, LPARAM lParam); void OnToolPoint(); void OnToolLine(); void OnToolRectangle(); void OnToolEllipse(); }; <file_sep>/Lab1/Lab1/targetver.h #pragma once // When SDKDKVer.h is enabled, the newest available Windows platform will be set. // If you plan to build the application for the previous version of the Windows platform, enable WinSDKVer.h and // specify the desired platform in the _WIN32_WINNT macro before enabling SDKDDKVer.h. #include <SDKDDKVer.h> <file_sep>/Lab5/Lab2/resource.h //{{NO_DEPENDENCIES}} // Включаемый файл, созданный в Microsoft Visual C++. // Используется Lab2.rc // #include "colors.h" #include <string> #include <fstream> #define IDC_MYICON 2 #define IDD_LAB3_DIALOG 102 #define IDS_APP_TITLE 103 #define IDD_ABOUTBOX 103 #define IDM_ABOUT 104 #define IDM_EXIT 105 #define IDI_LAB3 107 #define IDI_SMALL 1022 #define IDC_LAB3 109 #define IDM_POINT 32805 #define IDM_LINE 32806 #define IDM_RECTANGLE 32807 #define IDM_ELLIPSE 32809 #define IDM_LINEOO 32824 #define IDM_CUBE 32825 #define IDC_STATIC -1 #define IDD_TABLEINMENU 32779 extern HINSTANCE hInst; // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 #define _APS_NEXT_RESOURCE_VALUE 129 #define _APS_NEXT_COMMAND_VALUE 32779 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 110 #endif #endif <file_sep>/Lab1/Lab1/module1.h #pragma once #include "resource1.h" #pragma region Function extern int Func_MOD1(HINSTANCE hInst, HWND hWnd, char* dest); #pragma endregion <file_sep>/Lab5/Lab2/shape.cpp #include "framework.h" #include "pch.h" #include "shape.h" #include "colors.h" #include "toolbar.h" #pragma region Variables int lineOOInt = 20; int cubeInt = 50; long X1, X2, Y1, Y2; #pragma endregion Variables #pragma region Functions /// <summary> /// Get coords of points /// </summary> /// <param name="X1">first point</param> /// <param name="Y1">second point</param> /// <param name="X2">third point</param> /// <param name="Y2">fourth point</param> void Shape::Set(long X1, long Y1, long X2, long Y2) { XS1 = X1; YS1 = Y1; XS2 = X2; YS2 = Y2; } /// <summary> /// Function for showing final shape /// </summary> /// <param name="hdc"></param> void PointShape::Show(HDC hdc) { SetPixel(hdc, XS1, YS1, black); } /// <summary> /// Trail for point /// </summary> /// <param name="hdc"></param> void PointShape::Trail(HDC hdc) {} /// <summary> /// Function to get id for Menu /// </summary> /// <returns></returns> int PointShape::InitMenuPopup() { return ID_TOOL_POINT; } /// <summary> /// Function for duplicating /// </summary> /// <returns></returns> Shape* PointShape::Duplicate() { return new PointShape(); } /// <summary> /// Return name for table /// </summary> /// <returns></returns> std::string PointShape::GetShapeName() { return "Point"; } /// <summary> /// Function for showing final shape /// </summary> /// <param name="hdc"></param> void LineShape::Show(HDC hdc) { HPEN hPen, hPenOld; hPen = CreatePen(PS_SOLID, 1, black); hPenOld = (HPEN)SelectObject(hdc, hPen); MoveToEx(hdc, XS1, YS1, NULL); LineTo(hdc, XS2, YS2); SelectObject(hdc, hPenOld); DeleteObject(hPen); } /// <summary> /// Trail for line /// </summary> /// <param name="hdc"></param> void LineShape::Trail(HDC hdc) { HPEN hPen, hPenOld; hPen = CreatePen(PS_DOT, 1, black); hPenOld = (HPEN)SelectObject(hdc, hPen); MoveToEx(hdc, XS1, YS1, NULL); LineTo(hdc, XS2, YS2); SelectObject(hdc, hPenOld); DeleteObject(hPen); } /// <summary> /// Function to get id for Menu /// </summary> /// <returns></returns> int LineShape::InitMenuPopup() { return ID_TOOL_LINE; } /// <summary> /// Function for duplicating /// </summary> /// <returns></returns> Shape* LineShape::Duplicate() { return new LineShape(); } /// <summary> /// Return name for table /// </summary> /// <returns></returns> std::string LineShape::GetShapeName() { return "Line"; } /// <summary> /// Function for showing final shape /// </summary> /// <param name="hdc"></param> void RectangleShape::Show(HDC hdc) { HPEN hPen, hPenOld; HBRUSH hBrush, hBrushOld; hPen = CreatePen(PS_SOLID, 1, black); hPenOld = (HPEN)SelectObject(hdc, hPen); hBrush = CreateSolidBrush(white); hBrushOld = (HBRUSH)SelectObject(hdc, hBrush); SelectObject(hdc, hBrush); Rectangle(hdc, XS1, YS1, XS2, YS2); SelectObject(hdc, hBrushOld); DeleteObject(hBrush); SelectObject(hdc, hPenOld); DeleteObject(hPen); } /// <summary> /// Trail for rectangle /// </summary> /// <param name="hdc"></param> void RectangleShape::Trail(HDC hdc) { HPEN hPen, hPenOld; hPen = CreatePen(PS_DOT, 1, black); hPenOld = (HPEN)SelectObject(hdc, hPen); MoveToEx(hdc, XS1, YS1, NULL); LineTo(hdc, XS1, YS2); LineTo(hdc, XS2, YS2); LineTo(hdc, XS2, YS1); LineTo(hdc, XS1, YS1); SelectObject(hdc, hPenOld); DeleteObject(hPen); } /// <summary> /// Function to get id for Menu /// </summary> /// <returns></returns> int RectangleShape::InitMenuPopup() { return ID_TOOL_RECTANGLE; } /// <summary> /// Function for duplicating /// </summary> /// <returns></returns> Shape* RectangleShape::Duplicate() { return new RectangleShape(); } /// <summary> /// Return name for table /// </summary> /// <returns></returns> std::string RectangleShape::GetShapeName() { return "Rect"; } /// <summary> /// Function for showing final shape /// </summary> /// <param name="hdc"></param> void EllipseShape::Show(HDC hdc) { HPEN hPen, hPenOld; HBRUSH hBrush, hBrushOld; hPen = CreatePen(PS_SOLID, 1, black); hPenOld = (HPEN)SelectObject(hdc, hPen); Arc(hdc, 2 * XS1 - XS2, 2 * YS1 - YS2, XS2, YS2, 0, 0, 0, 0); SelectObject(hdc, hPenOld); DeleteObject(hPen); }; /// <summary> /// Trail for ellipse /// </summary> /// <param name="hdc"></param> void EllipseShape::Trail(HDC hdc) { HPEN hPen, hPenOld; hPen = CreatePen(PS_DOT, 1, black); hPenOld = (HPEN)SelectObject(hdc, hPen); MoveToEx(hdc, XS1, YS1, NULL); Arc(hdc, 2 * XS1 - XS2, 2 * YS1 - YS2, XS2, YS2, 0, 0, 0, 0); SelectObject(hdc, hPenOld); DeleteObject(hPen); } /// <summary> /// Function to get id for Menu /// </summary> /// <returns></returns> int EllipseShape::InitMenuPopup() { return ID_TOOL_ELLIPSE; } /// <summary> /// Function for duplicating /// </summary> /// <returns></returns> Shape* EllipseShape::Duplicate() { return new EllipseShape(); } /// <summary> /// Return name for table /// </summary> /// <returns></returns> std::string EllipseShape::GetShapeName() { return "Ellipse"; } /// <summary> /// Function for showing final shape /// </summary> /// <param name="hdc"></param> void LineOOShape::Show(HDC hdc) { X1 = XS1; Y1 = YS1; X2 = XS2; Y2 = YS2; LineShape::Set(X1, Y1, X2, Y2); LineShape::Show(hdc); EllipseShape::Set(X1, Y1, X1 - lineOOInt, Y1 - lineOOInt); EllipseShape::Show(hdc); EllipseShape::Set(X2, Y2, X2 - lineOOInt, Y2 - lineOOInt); EllipseShape::Show(hdc); LineShape::Set(X1, Y1, X2, Y2); } /// <summary> /// Trail for lineOO /// </summary> /// <param name="hdc"></param> void LineOOShape::Trail(HDC hdc) { X1 = XS1; Y1 = YS1; X2 = XS2; Y2 = YS2; LineShape::Set(X1, Y1, X2, Y2); LineShape::Trail(hdc); EllipseShape::Set(X1, Y1, X1 - lineOOInt, Y1 - lineOOInt); EllipseShape::Trail(hdc); EllipseShape::Set(X2, Y2, X2 - lineOOInt, Y2 - lineOOInt); EllipseShape::Trail(hdc); LineShape::Set(X1, Y1, X2, Y2); } /// <summary> /// Function to get id for Menu /// </summary> /// <returns></returns> int LineOOShape::InitMenuPopup() { return ID_TOOL_LINEOO; } /// <summary> /// Function for duplicating /// </summary> /// <returns></returns> Shape* LineOOShape::Duplicate() { return new LineOOShape(); } /// <summary> /// Return name for table /// </summary> /// <returns></returns> std::string LineOOShape::GetShapeName() { return "LineOO"; } /// <summary> /// Function for showing final shape /// </summary> /// <param name="hdc"></param> void CubeShape::Show(HDC hdc) { X1 = XS1; Y1 = YS1; X2 = XS2; Y2 = YS2; RectangleShape::Set(X1 - cubeInt, Y1 - cubeInt, X1 + cubeInt, Y1 + cubeInt); RectangleShape::Show(hdc); RectangleShape::Set(X2 - cubeInt, Y2 - cubeInt, X2 + cubeInt, Y2 + cubeInt); RectangleShape::Show(hdc); LineShape::Set(X1 - cubeInt, Y1 - cubeInt, X2 - cubeInt, Y2 - cubeInt); LineShape::Show(hdc); LineShape::Set(X1 - cubeInt, Y1 + cubeInt, X2 - cubeInt, Y2 + cubeInt); LineShape::Show(hdc); LineShape::Set(X1 + cubeInt, Y1 + cubeInt, X2 + cubeInt, Y2 + cubeInt); LineShape::Show(hdc); LineShape::Set(X1 + cubeInt, Y1 - cubeInt, X2 + cubeInt, Y2 - cubeInt); LineShape::Show(hdc); LineShape::Set(X1, Y1, X2, Y2); } /// <summary> /// Trail for cube /// </summary> /// <param name="hdc"></param> void CubeShape::Trail(HDC hdc) { X1 = XS1; Y1 = YS1; X2 = XS2; Y2 = YS2; RectangleShape::Set(X1 - cubeInt, Y1 - cubeInt, X1 + cubeInt, Y1 + cubeInt); RectangleShape::Trail(hdc); RectangleShape::Set(X2 - cubeInt, Y2 - cubeInt, X2 + cubeInt, Y2 + cubeInt); RectangleShape::Trail(hdc); LineShape::Set(X1 - cubeInt, Y1 - cubeInt, X2 - cubeInt, Y2 - cubeInt); LineShape::Trail(hdc); LineShape::Set(X1 - cubeInt, Y1 + cubeInt, X2 - cubeInt, Y2 + cubeInt); LineShape::Trail(hdc); LineShape::Set(X1 + cubeInt, Y1 + cubeInt, X2 + cubeInt, Y2 + cubeInt); LineShape::Trail(hdc); LineShape::Set(X1 + cubeInt, Y1 - cubeInt, X2 + cubeInt, Y2 - cubeInt); LineShape::Trail(hdc); LineShape::Set(X1, Y1, X2, Y2); } /// <summary> /// Function to get id for Menu /// </summary> /// <returns></returns> int CubeShape::InitMenuPopup() { return ID_TOOL_CUBE; } /// <summary> /// Function for duplicating /// </summary> /// <returns></returns> Shape* CubeShape::Duplicate() { return new CubeShape(); } /// <summary> /// Return name for table /// </summary> /// <returns></returns> std::string CubeShape::GetShapeName() { return "Cube"; } Shape::~Shape() {}; #pragma endregion Functions <file_sep>/Lab3/Lab2/shape_editor.cpp #include "framework.h" #include "pch.h" #include "shape_editor.h" #include "shape.h" #pragma region Variables const int Size_Of_Array = 110; Shape* pcshape[Size_Of_Array]; int size = 0; bool isPressed; #pragma endregion Variables #pragma region Functions #pragma region ShapeObjectsEditor /// <summary> /// Constructor /// </summary> ShapeObjectsEditor::ShapeObjectsEditor() { pse = new PointEditor; } /// <summary> /// Destructor /// </summary> ShapeObjectsEditor::~ShapeObjectsEditor() { for (int i = 0; i < size; i++) { delete pcshape[i]; } } /// <summary> /// Starts the PointEditor /// </summary> void ShapeObjectsEditor::StartPointEditor() { if (pse) { delete pse; } pse = new PointEditor; SetShape(0); } /// <summary> /// Starts the LineEditor /// </summary> void ShapeObjectsEditor::StartLineEditor() { if (pse) { delete pse; } pse = new LineEditor; SetShape(1); } /// <summary> /// Starts the RectangleEditor /// </summary> void ShapeObjectsEditor::StartRectangleEditor() { if (pse) { delete pse; } pse = new RectangleEditor; SetShape(2); } /// <summary> /// Starts the EllipseEditor /// </summary> void ShapeObjectsEditor::StartEllipseEditor() { if (pse) { delete pse; } pse = new EllipseEditor; SetShape(3); } /// <summary> /// Do something on left mouse button clicked /// </summary> /// <param name="hWnd">window</param> void ShapeObjectsEditor::OnLBdown(HWND hWnd) { if (pse) { pse->OnLBdown(hWnd); } } /// <summary> /// Do something on left mouse button unclicked /// </summary> /// <param name="hWnd">window</param> void ShapeObjectsEditor::OnLBup(HWND hWnd) { if (pse) { pse->OnLBup(hWnd); } } /// <summary> /// Do something on left mouse moving /// </summary> /// <param name="hWnd">window</param> void ShapeObjectsEditor::OnMouseMove(HWND hWnd) { if (pse && isPressed) { pse->OnMouseMove(hWnd); } } /// <summary> /// Do something on paint /// </summary> /// <param name="hWnd">window</param> void ShapeObjectsEditor::OnPaint(HWND hWnd) { ShapeEditor* draw = new ShapeEditor; draw->OnPaint(hWnd); } /// <summary> /// Sets the mark in figures menu /// </summary> /// <param name="hWnd"></param> /// <param name="wParams"></param> void ShapeObjectsEditor::OnInitMenuPopup(HWND hWnd, WPARAM wParams) { if (pse) { pse->OnInitMenuPopup(hWnd, wParams); } } #pragma endregion ShapeObjectsEditor #pragma region ShapeEditor void ShapeEditor::OnMouseMove(HWND hWnd) {}; /// <summary> /// Do something on left mouse button clicked /// </summary> /// <param name="hWnd">window</param> void ShapeEditor::OnLBdown(HWND hWnd) { isPressed = TRUE; POINT pt; GetCursorPos(&pt); ScreenToClient(hWnd, &pt); x1 = x2 = pt.x; y1 = y2 = pt.y; } /// <summary> /// Do something on left mouse button unclicked /// </summary> /// <param name="hWnd">window</param> void ShapeEditor::OnLBup(HWND hWnd) { POINT pt; GetCursorPos(&pt); ScreenToClient(hWnd, &pt); x2 = pt.x; y2 = pt.y; isPressed = FALSE; } /// <summary> /// InitMenu Popup /// </summary> /// <param name="hWnd"></param> /// <param name="wParams"></param> void ShapeEditor::OnInitMenuPopup(HWND hWnd, WPARAM wParams) {}; /// <summary> /// Do something on paint /// </summary> /// <param name="hWnd">window</param> void ShapeEditor::OnPaint(HWND hWnd) { PAINTSTRUCT ps; HDC hdc; hdc = BeginPaint(hWnd, &ps); for (int i = 0; i < size; i++) { if (pcshape[i]) { pcshape[i]->Show(hdc); } } EndPaint(hWnd, &ps); } #pragma endregion ShapeEditor #pragma region PointEditor /// <summary> /// Do something on left mouse button unclicked /// </summary> /// <param name="hWnd">window</param> void PointEditor::OnLBup(HWND hWnd) { __super::OnLBup(hWnd); PointShape* Point = new PointShape; Point->Set(x1, y1, x2, y2); pcshape[size] = Point; size++; InvalidateRect(hWnd, NULL, TRUE); } /// <summary> /// Sets the Check /// </summary> /// <param name="hWnd"></param> /// <param name="wParams"></param> void PointEditor::OnInitMenuPopup(HWND hWnd, WPARAM wParams) { HMENU hMenu, hSubMenu; hMenu = GetMenu(hWnd); hSubMenu = GetSubMenu(hMenu, 1); if ((HMENU)wParams == hSubMenu) { CheckMenuItem(hSubMenu, IDM_POINT, MF_CHECKED); CheckMenuItem(hSubMenu, IDM_LINE, MF_UNCHECKED); CheckMenuItem(hSubMenu, IDM_RECTANGLE, MF_UNCHECKED); CheckMenuItem(hSubMenu, IDM_ELLIPSE, MF_UNCHECKED); } } #pragma endregion PointEditor #pragma region LineEditor /// <summary> /// Do something on left mouse button unclicked /// </summary> /// <param name="hWnd">window</param> void LineEditor::OnLBup(HWND hWnd) { __super::OnLBup(hWnd); LineShape* Line = new LineShape; Line->Set(x1, y1, x2, y2); pcshape[size] = Line; size++; InvalidateRect(hWnd, NULL, TRUE); } /// <summary> /// Sets the Check /// </summary> /// <param name="hWnd"></param> /// <param name="wParams"></param> void LineEditor::OnInitMenuPopup(HWND hWnd, WPARAM wParams) { HMENU hMenu, hSubMenu; hMenu = GetMenu(hWnd); hSubMenu = GetSubMenu(hMenu, 1); if ((HMENU)wParams == hSubMenu) { CheckMenuItem(hSubMenu, IDM_POINT, MF_UNCHECKED); CheckMenuItem(hSubMenu, IDM_LINE, MF_CHECKED); CheckMenuItem(hSubMenu, IDM_RECTANGLE, MF_UNCHECKED); CheckMenuItem(hSubMenu, IDM_ELLIPSE, MF_UNCHECKED); } } /// <summary> /// Do something on Mouse moving /// </summary> /// <param name="hWnd">window</param> void LineEditor::OnMouseMove(HWND hWnd) { POINT pt; HPEN hPen, hPenOld; HDC hdc = GetDC(hWnd); SetROP2(hdc, R2_NOTXORPEN); hPen = CreatePen(PS_SOLID, 1, blue); hPenOld = (HPEN)SelectObject(hdc, hPen); MoveToEx(hdc, x1, y1, NULL); LineTo(hdc, x2, y2); GetCursorPos(&pt); ScreenToClient(hWnd, &pt); x2 = pt.x; y2 = pt.y; MoveToEx(hdc, x1, y1, NULL); LineTo(hdc, x2, y2); SelectObject(hdc, hPenOld); DeleteObject(hPen); ReleaseDC(hWnd, hdc); } #pragma endregion LineEditor #pragma region RectangleEditor /// <summary> /// Do something on left mouse button unclicked /// </summary> /// <param name="hWnd">window</param> void RectangleEditor::OnLBup(HWND hWnd) { __super::OnLBup(hWnd); RectangleShape* Rectangle = new RectangleShape; Rectangle->Set(x1, y1, x2, y2); pcshape[size] = Rectangle; size++; InvalidateRect(hWnd, NULL, TRUE); } /// <summary> /// Sets the Check /// </summary> /// <param name="hWnd"></param> /// <param name="wParams"></param> void RectangleEditor::OnInitMenuPopup(HWND hWnd, WPARAM wParams) { HMENU hMenu, hSubMenu; hMenu = GetMenu(hWnd); hSubMenu = GetSubMenu(hMenu, 1); if ((HMENU)wParams == hSubMenu) { CheckMenuItem(hSubMenu, IDM_POINT, MF_UNCHECKED); CheckMenuItem(hSubMenu, IDM_LINE, MF_UNCHECKED); CheckMenuItem(hSubMenu, IDM_RECTANGLE, MF_CHECKED); CheckMenuItem(hSubMenu, IDM_ELLIPSE, MF_UNCHECKED); } } /// <summary> /// Do something on Mouse moving /// </summary> /// <param name="hWnd">window</param> void RectangleEditor::OnMouseMove(HWND hWnd) { POINT pt; HPEN hPen, hPenOld; HDC hdc = GetDC(hWnd); SetROP2(hdc, R2_NOTXORPEN); hPen = CreatePen(PS_SOLID, 1, blue); hPenOld = (HPEN)SelectObject(hdc, hPen); Rectangle(hdc, x1, y1, x2, y2); GetCursorPos(&pt); ScreenToClient(hWnd, &pt); x2 = pt.x; y2 = pt.y; Rectangle(hdc, x1, y1, x2, y2); SelectObject(hdc, hPenOld); DeleteObject(hPen); ReleaseDC(hWnd, hdc); } #pragma endregion RectangleEditor #pragma region EllipseEditor /// <summary> /// Do something on left mouse button unclicked /// </summary> /// <param name="hWnd">window</param> void EllipseEditor::OnLBup(HWND hWnd) { __super::OnLBup(hWnd); EllipseShape* Ellipse = new EllipseShape; Ellipse->Set(2 * x1 - x2, 2 * y1 - y2, x2, y2); pcshape[size] = Ellipse; size++; InvalidateRect(hWnd, NULL, TRUE); } /// <summary> /// Sets the Check /// </summary> /// <param name="hWnd"></param> /// <param name="wParams"></param> void EllipseEditor::OnInitMenuPopup(HWND hWnd, WPARAM wParams) { HMENU hMenu, hSubMenu; hMenu = GetMenu(hWnd); hSubMenu = GetSubMenu(hMenu, 1); if ((HMENU)wParams == hSubMenu) { CheckMenuItem(hSubMenu, IDM_POINT, MF_UNCHECKED); CheckMenuItem(hSubMenu, IDM_LINE, MF_UNCHECKED); CheckMenuItem(hSubMenu, IDM_RECTANGLE, MF_UNCHECKED); CheckMenuItem(hSubMenu, IDM_ELLIPSE, MF_CHECKED); } } /// <summary> /// Do something on Mouse moving /// </summary> /// <param name="hWnd">window</param> void EllipseEditor::OnMouseMove(HWND hWnd) { POINT pt; HPEN hPen, hPenOld; HDC hdc = GetDC(hWnd); SetROP2(hdc, R2_NOTXORPEN); hPen = CreatePen(PS_SOLID, 1, blue); hPenOld = (HPEN)SelectObject(hdc, hPen); Arc(hdc, 2 * x1 - x2, 2 * y1 - y2, x2, y2, 0, 0, 0, 0); GetCursorPos(&pt); ScreenToClient(hWnd, &pt); x2 = pt.x; y2 = pt.y; Arc(hdc, 2 * x1 - x2, 2 * y1 - y2, x2, y2, 0, 0, 0, 0); SelectObject(hdc, hPenOld); DeleteObject(hPen); ReleaseDC(hWnd, hdc); } #pragma endregion EllipseEditor #pragma endregion Functions <file_sep>/Lab3/Lab2/shape.cpp #include "framework.h" #include "pch.h" #include "shape.h" #include "colors.h" #pragma region Functions /// <summary> /// // Get coords of points /// </summary> /// <param name="x1">first point</param> /// <param name="y1">second point</param> /// <param name="x2">third point</param> /// <param name="y2">fourth point</param> void Shape::Set(long x1, long y1, long x2, long y2) { xs1 = x1; ys1 = y1; xs2 = x2; ys2 = y2; } /// <summary> /// Shows the pixel /// </summary> /// <param name="hdc">handle to a device context</param> void PointShape::Show(HDC hdc) { SetPixel(hdc, xs1, ys1, black); } /// <summary> /// Shows the line /// </summary> /// <param name="hdc">handle to a device context</param> void LineShape::Show(HDC hdc) { HPEN hPen, hPenOld; hPen = CreatePen(PS_SOLID, 1, black); hPenOld = (HPEN)SelectObject(hdc, hPen); MoveToEx(hdc, xs1, ys1, NULL); LineTo(hdc, xs2, ys2); SelectObject(hdc, hPenOld); DeleteObject(hPen); } /// <summary> /// Shows the rectangle /// </summary> /// <param name="hdc">handle to a device context</param> void RectangleShape::Show(HDC hdc) { HPEN hPen, hPenOld; HBRUSH hBrush, hBrushOld; hPen = CreatePen(PS_SOLID, 1, black); hPenOld = (HPEN)SelectObject(hdc, hPen); hBrush = CreateSolidBrush(white); hBrushOld = (HBRUSH)SelectObject(hdc, hBrush); SelectObject(hdc, hBrush); Rectangle(hdc, xs1, ys1, xs2, ys2); SelectObject(hdc, hBrushOld); DeleteObject(hBrush); SelectObject(hdc, hPenOld); DeleteObject(hPen); } /// <summary> /// Shows the ellipse /// </summary> /// <param name="hdc">handle to a device context</param> void EllipseShape::Show(HDC hdc) { HPEN hPen, hPenOld; HBRUSH hBrush, hBrushOld; hPen = CreatePen(PS_SOLID, 1, black); hPenOld = (HPEN)SelectObject(hdc, hPen); Arc(hdc, xs1, ys1, xs2, ys2, 0, 0, 0, 0); SelectObject(hdc, hPenOld); DeleteObject(hPen); }; #pragma endregion Functions <file_sep>/Lab1/Lab1/module1.cpp #include "pch.h" #include "framework.h" #include "module1.h" #pragma region VariablesAndFunctionsDeclarations static int const maxSymbols_MOD1 = 255; static char tempPlaceForText_MOD1[maxSymbols_MOD1] = { 0 }; int pos_MOD1; static int nMinPos_MOD1 = 1; static int nMaxPos_MOD1 = 100; static HWND hWndScrollBar_MOD1; BOOL canWrite_MOD1 = FALSE; int numOfDig_MOD1; static INT_PTR CALLBACK Work1_MOD1(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam); static void OnInit(HWND hDlg); static void OnLineLeft(HWND hDlg); static void OnLineRight(HWND hDlg); static void OnOk(HWND hDlg); static void OnCancel(HWND hDlg); static void OnClose(HWND hDlg); static void GetPos(HWND hDlg); static void OnThumbPosAndTrack(HWND hDlg, WPARAM wParam); static int Count(int pos_MOD1); #pragma endregion #pragma region Functions /// <summary> /// dialog box creation function /// </summary> /// <param name="hInst">The hinst.</param> /// <param name="hWnd">The hWND.</param> /// <returns></returns> int Func_MOD1(HINSTANCE hInst, HWND hWnd, char *dest) { return DialogBox(hInst , MAKEINTRESOURCE(IDD_WORK_MOD1), hWnd, Work1_MOD1); dest = tempPlaceForText_MOD1; } /// <summary> /// Callback-function for hor.scrollbar /// </summary> /// <param name="hDlg"></param> /// <param name="iMessage"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> /// <returns></returns> INT_PTR CALLBACK Work1_MOD1(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam) { switch (iMessage) { case WM_INITDIALOG: OnInit(hDlg); break; case WM_HSCROLL: GetPos(hDlg); switch (LOWORD(wParam)) { case SB_LINELEFT: OnLineLeft(hDlg); break; case SB_LINERIGHT: OnLineRight(hDlg); break; case SB_THUMBPOSITION: case SB_THUMBTRACK: OnThumbPosAndTrack(hDlg, wParam); break; default: break; } SetScrollPos(hWndScrollBar_MOD1, SB_CTL, pos_MOD1, TRUE); break; case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: OnOk(hDlg); return (INT_PTR)TRUE; break; case IDCANCEL: OnCancel(hDlg); return (INT_PTR)TRUE; break; } break; case WM_CLOSE: { OnClose(hDlg); } break; default: break; } return FALSE; } /// <summary> /// Called on initializing /// </summary> /// <param name="hDlg">The dialog.</param> void OnInit(HWND hDlg) { hWndScrollBar_MOD1 = GetDlgItem(hDlg, IDC_SCROLLBAR1_MOD1); pos_MOD1 = 1; SetScrollRange(hWndScrollBar_MOD1, SB_CTL, nMinPos_MOD1, nMaxPos_MOD1, TRUE); } /// <summary> /// Called when scroll pos goes to the left. /// </summary> /// <param name="hDlg">The dialog.</param> void OnLineLeft(HWND hDlg) { if (pos_MOD1 != nMinPos_MOD1) { pos_MOD1--; } SetDlgItemInt(hDlg, IDC_STATIC_MOD1, pos_MOD1, TRUE); } /// <summary> /// Called when scroll pos goes to the right. /// </summary> /// <param name="hDlg">The dialog.</param> void OnLineRight(HWND hDlg) { if (pos_MOD1 != nMaxPos_MOD1) { pos_MOD1++; } SetDlgItemInt(hDlg, IDC_STATIC_MOD1, pos_MOD1, TRUE); } /// <summary> /// Called when thumb position has changed /// </summary> /// <param name="hDlg">The h dialog.</param> /// <param name="wParam">The w parameter.</param> void OnThumbPosAndTrack(HWND hDlg, WPARAM wParam) { pos_MOD1 = HIWORD(wParam); SetDlgItemInt(hDlg, IDC_STATIC_MOD1, pos_MOD1, TRUE); } /// <summary> /// Called when IDOK clicked /// </summary> /// <param name="hDlg">The dialog.</param> void OnOk(HWND hDlg) { canWrite_MOD1 = TRUE; numOfDig_MOD1 = Count(pos_MOD1); EndDialog(hDlg, 1); } /// <summary> /// Called when IDCANCEL clicked /// </summary> /// <param name="hDlg">The dialog.</param> void OnCancel(HWND hDlg) { EndDialog(hDlg, 0); } /// <summary> /// Called when window is closing /// </summary> /// <param name="hDlg">The dialog.</param> void OnClose(HWND hDlg) { EndDialog(hDlg, 0); } /// <summary> /// Get pos of scroll /// </summary> /// <param name="hDlg">The dialog.</param> void GetPos(HWND hDlg) { pos_MOD1 = GetScrollPos(GetDlgItem(hDlg, IDC_SCROLLBAR1_MOD1), SB_CTL); } /// <summary> /// Function to Count how many digits are in int /// </summary> /// <param name="pos"></param> /// <returns></returns> int Count(int pos_MOD1) { int count_MOD1 = 0; while (pos_MOD1 != 0) { pos_MOD1 = pos_MOD1 / 10; ++count_MOD1; } return count_MOD1; } #pragma endregion <file_sep>/Lab5/Lab2/my_editor.h #pragma once #include "pch.h" #include "Resource.h" #include "shape.h" #pragma region Editors /// <summary> /// Shape editor class for figures /// </summary> class MyEditor { private: MyEditor() {}; MyEditor(const MyEditor&); MyEditor& operator = (MyEditor&); public: static MyEditor& getInstance() { static MyEditor instance; return instance; } void Start(Shape*); void OnLBdown(HWND); void OnLBup(HWND); void OnMouseMove(HWND); void OnPaint(HWND); void OnInitMenuPopup(HWND, WPARAM); ~MyEditor(); long X1, Y1, X2, Y2; std::string GetDetails(); }; #pragma endregion Editors <file_sep>/Lab4/Lab2/shape.h #include "pch.h" /// <summary> /// Main class for shapes /// </summary> class Shape { protected: long xs1, ys1, xs2, ys2; public: void Set(long x1, long y1, long x2, long y2); virtual void Show(HDC) = 0; ~Shape(); }; /// <summary> /// Class for points /// </summary> class PointShape : public virtual Shape { public: void Show(HDC); //void OnLBdown(HWND hWnd); //void OnMouseMove(HWND hWnd); //Shape* OnLBup(HWND hWnd); }; /// <summary> /// Class for lines /// </summary> class LineShape : public virtual Shape { public: void Show(HDC); //void OnLBdown(HWND hWnd); //void OnMouseMove(HWND hWnd); //Shape* OnLBup(HWND hWnd); }; /// <summary> /// Class for rectangles /// </summary> class RectangleShape : public virtual Shape { public: void Show(HDC); //void OnLBdown(HWND hWnd); //void OnMouseMove(HWND hWnd); //Shape* OnLBup(HWND hWnd); }; /// <summary> /// Class for ellipses /// </summary> class EllipseShape : public virtual Shape { public: void Show(HDC); //void OnLBdown(HWND hWnd); //void OnMouseMove(HWND hWnd); //Shape* OnLBup(HWND hWnd); }; /// <summary> /// Class for rectangles /// </summary> class LineOOShape : public LineShape, public EllipseShape { public: void Show(HDC); //void OnLBdown(HWND hWnd); //void OnMouseMove(HWND hWnd); //Shape* OnLBup(HWND hWnd); }; /// <summary> /// Class for ellipses /// </summary> class CubeShape : public LineShape, public RectangleShape { public: void Show(HDC); //void OnLBdown(HWND hWnd); //void OnMouseMove(HWND hWnd); //Shape* OnLBup(HWND hWnd); };<file_sep>/Lab6/Lab6/Lab6.cpp // Lab6.cpp : Defines the input point for the application. // // First Part #include "framework.h" #include "pch.h" #include "Lab6.h" #include "InputValuesModule.h" #define MAX_LOADSTRING 100 #pragma region VariablesAndFunctions // Global variables: HINSTANCE hInst; // Current instance WCHAR szTitle[MAX_LOADSTRING]; // Header row text WCHAR szWindowClass[MAX_LOADSTRING]; // Class name of main window // Send declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); static void CallInputValues(HWND hWnd); // Declaration of our function HWND hWndObj2; HWND hWndObj3; #pragma endregion VariablesAndFunctions #pragma region DefaultFunctions // Second Part // Enter Point "wWinMain" int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place the code here. // Global line initialization LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadStringW(hInstance, IDC_LAB6, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance(hInstance, nCmdShow)) { return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_LAB6)); MSG msg; // Main message cycle: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int)msg.wParam; } // // FUNCTION: MyRegisterClass() // // OBJECTIVE: To register the window class. // Text of Function /// <summary> /// Register the window class. /// </summary> /// <param name="hInstance">The h instance.</param> /// <returns></returns> ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LAB6)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_LAB6); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassExW(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // OBJECTIVE: Saves the instance marker and creates the main window // // COMMENTARIES: // // In this function, the instance marker is saved in a global variable, and also // the main program window is created and displayed. // /// <summary> /// Saves the instance marker and creates the main window /// </summary> /// <param name="hInstance">The h instance.</param> /// <param name="nCmdShow">The n command show.</param> /// <returns></returns> BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; // Save instance marker in global variable HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } /// <summary> /// Message handler for "About" window. /// </summary> /// <param name="hDlg">The h dialog.</param> /// <param name="message">The message.</param> /// <param name="wParam">The w parameter.</param> /// <param name="lParam">The l parameter.</param> /// <returns></returns> INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } #pragma endregion #pragma region ModifiedFuntions // Third Part // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // OBJECTIVE: Processes messages in the main window. // // WM_COMMAND - Process the application menu // WM_PAINT - Drawing of the main window // WM_DESTROY - Send message about exit and return // // /// <summary> /// Processes messages in the main window. /// </summary> /// <param name="hWnd">The h WND.</param> /// <param name="message">The message.</param> /// <param name="wParam">The w parameter.</param> /// <param name="lParam">The l parameter.</param> /// <returns></returns> LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: { int wmId = LOWORD(wParam); switch (wmId) { case IDM_WORK: CallInputValues(hWnd); break; case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProcW(hWnd, message, wParam, lParam); } } break; case WM_DESTROY: PostQuitMessage(0); hWndObj2 = FindWindow("OBJECT2", NULL); if (hWndObj2) { PostMessage(hWndObj2, WM_DESTROY, (WPARAM)wParam, 0); } hWndObj3 = FindWindow("OBJECT3", NULL); if (hWndObj3) { PostMessage(hWndObj3, WM_DESTROY, (WPARAM)wParam, 0); } break; default: return DefWindowProcW(hWnd, message, wParam, lParam); } return 0; } /// <summary> /// Function-handler of the menu item "Work1" /// </summary> /// <param name="hWnd">The h WND.</param> void CallInputValues(HWND hWnd) { // What we program here that will be done Func_MOD1(hInst, hWnd); // The update region represents the portion of the window's // client area that must be redrawn. InvalidateRect(hWnd, 0, TRUE); } #pragma endregion ModifiedFuntions <file_sep>/Lab1/Lab1/module3.cpp #include "pch.h" #include "framework.h" #include "module3.h" #include "module2.h" #include "Resource.h" #pragma region FunctionsDeclaration static void OnBack(HWND hDlg); static void OnOk(HWND hDlg); static void OnCancel(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); static INT_PTR CALLBACK Work2_MOD2(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); #pragma endregion #pragma region Functions /// <summary> /// dialog box creation function /// </summary> /// <param name="hInst">The hinst.</param> /// <param name="hWnd">The hWND.</param> /// <returns></returns> int Func_MOD3(HINSTANCE hInst, HWND hWnd) { return DialogBox(hInst, MAKEINTRESOURCE(IDD_WORK2_MOD2), hWnd, Work2_MOD2); } /// <summary> /// Callback-function for second dialog window /// </summary> /// <param name="hDlg">The h dialog.</param> /// <param name="message">The message.</param> /// <param name="wParam">The w parameter.</param> /// <param name="lParam">The l parameter.</param> /// <returns></returns> INT_PTR CALLBACK Work2_MOD2(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_OK2_MOD2: // Next button OnOk(hDlg); return (INT_PTR)TRUE; case IDC_CANCEL2_MOD2: // Cancel button OnCancel(hDlg, message, wParam, lParam); return (INT_PTR)TRUE; case IDC_BACK_MOD2: // Back button OnBack(hDlg); return (INT_PTR)TRUE; } break; case WM_CLOSE: { EndDialog(hDlg, 0); } break; } return (INT_PTR)FALSE; } /// <summary> /// Called when IDC_BACK_MOD2 clicked /// </summary> /// <param name="hDlg">The dialog.</param> void OnBack(HWND hDlg) { EndDialog(hDlg, 1); Func_MOD2(hInst, hDlg); } /// <summary> /// Called when IDOK clicked /// </summary> /// <param name="hDlg">The dialog.</param> void OnOk(HWND hDlg) { EndDialog(hDlg, 1); } /// <summary> /// Called when IDCANCEL clicked /// </summary> /// <param name="hDlg">The dialog.</param> void OnCancel(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { EndDialog(hDlg, 0); DefWindowProc(hDlg, message, wParam, lParam); } #pragma endregion<file_sep>/Lab6/Lab6/InputValuesModule.h #pragma once #pragma once #include "resource1.h" #pragma region Function extern int Func_MOD1(HINSTANCE hInst, HWND hWnd); #pragma endregion <file_sep>/Lab6/Lab6/InputValuesModule.cpp #include "pch.h" #include "framework.h" #include "InputValuesModule.h" #pragma region VariablesAndFunctionsDeclarations HINSTANCE hInstCurrent; long n_MOD1; long Min_MOD1; long Max_MOD1; const int allValues = 3; HWND hWndDataCreator = NULL; static INT_PTR CALLBACK InputValues_MOD1(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam); static INT_PTR CALLBACK Warning_MOD1(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam); static void OnOk(HWND hDlg); static void OnCancel(HWND hDlg); static void OnClose(HWND hDlg); int SendCopyData(HWND hWndDest, HWND hWndSrc, void* lp, long cb); #pragma endregion #pragma region Functions /// <summary> /// dialog box creation function /// </summary> /// <param name="hInst">The hinst.</param> /// <param name="hWnd">The hWND.</param> /// <returns></returns> int Func_MOD1(HINSTANCE hInst, HWND hWnd) { return DialogBox(hInst, MAKEINTRESOURCE(IDD_INPUT), hWnd, InputValues_MOD1); } /// <summary> /// Callback-function for calling window with inputs /// </summary> /// <param name="hDlg"></param> /// <param name="iMessage"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> /// <returns></returns> INT_PTR CALLBACK InputValues_MOD1(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam) { switch (iMessage) { case WM_INITDIALOG: return (INT_PTR)TRUE; break; case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: OnOk(hDlg); return (INT_PTR)TRUE; break; case IDCANCEL: OnCancel(hDlg); return (INT_PTR)TRUE; break; } break; case WM_CLOSE: { OnClose(hDlg); } break; default: break; } return FALSE; } /// <summary> /// Called when IDOK clicked /// </summary> /// <param name="hDlg">The dialog.</param> void OnOk(HWND hDlg) { n_MOD1 = GetDlgItemInt(hDlg, IDC_EDIT_N, NULL, FALSE); Min_MOD1 = GetDlgItemInt(hDlg, IDC_EDIT_MIN, NULL, FALSE); Max_MOD1 = GetDlgItemInt(hDlg, IDC_EDIT_MAX, NULL, FALSE); if (n_MOD1 == NULL || Min_MOD1 == NULL || Max_MOD1 == NULL ) { // call "enter a values" window DialogBox(hInstCurrent, MAKEINTRESOURCE(IDD_WARNING_NULL), hDlg, Warning_MOD1); return; } // check if min is less or equals to max if (Min_MOD1 <= Max_MOD1) { // call two object2 and object3 windows hWndDataCreator = FindWindow("OBJECT2", NULL); if (hWndDataCreator == NULL) // the required program is already running { // call to run the desired program WinExec("Object2.exe", SW_SHOW); hWndDataCreator = FindWindow("OBJECT2", NULL); } //сформуємо дані як суцільний масив, наприклад, так long params[allValues] = { n_MOD1, Min_MOD1, Max_MOD1 }; //а тепер відправимо масив params вікну hWndOther іншої програми SendCopyData(hWndDataCreator, GetParent(hDlg), params, sizeof(params)); return; } else { DialogBox(hInstCurrent, MAKEINTRESOURCE(IDD_WARNING_VALUES), hDlg, Warning_MOD1); return; } } /// <summary> /// Callback-function for calling window with inputs /// </summary> /// <param name="hDlg"></param> /// <param name="iMessage"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> /// <returns></returns> INT_PTR CALLBACK Warning_MOD1(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam) { switch (iMessage) { case WM_INITDIALOG: return (INT_PTR)TRUE; break; case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: EndDialog(hDlg, 0); return (INT_PTR)TRUE; break; } break; case WM_CLOSE: { OnClose(hDlg); } break; default: break; } return FALSE; } /// <summary> /// Called when IDCANCEL clicked /// </summary> /// <param name="hDlg">The dialog.</param> void OnCancel(HWND hDlg) { EndDialog(hDlg, 0); } /// <summary> /// Called when window is closing /// </summary> /// <param name="hDlg">The dialog.</param> void OnClose(HWND hDlg) { EndDialog(hDlg, 0); } /// <summary> /// Sends copydata /// </summary> /// <param name="hWndDest"></param> /// <param name="hWndSrc"></param> /// <param name="lp"></param> /// <param name="cb"></param> /// <returns></returns> int SendCopyData(HWND hWndDest, HWND hWndSrc, void* lp, long cb) { COPYDATASTRUCT cds{}; cds.dwData = 1; //а можна і будь-яке інше значення cds.cbData = cb; cds.lpData = lp; return SendMessage(hWndDest, WM_COPYDATA, (WPARAM)hWndSrc, (LPARAM)&cds); } #pragma endregion
a2a50dce0f35375907b391681cd5eb6bb249b061
[ "Markdown", "C", "C++" ]
47
C++
VsIG-official/KPI-OOP
2dd9c09ed0730154239142f0d12065325e502f04
752cac9ca02b185dc15052d3658fdb13f3c47994
refs/heads/master
<repo_name>Roman84asas/Calculator-on-js5<file_sep>/javScript/worckerWithData.js var inputOne = document.getElementById('vall1'); var inputTwo = document.getElementById('vall2'); inputOne.onfocus = function() { var container = document.getElementById('container'); container.onclick = function (event) { if (event.target.parentElement.id != 'container') return; var numb = event.target.innerHTML; document.getElementById("vall1").value += numb; }; }; inputTwo.onfocus = function() { var container = document.getElementById('container'); container.onclick = function (event) { if (event.target.parentElement.id != 'container') return; var numb = event.target.innerHTML; document.getElementById('vall2').value += numb; }; };<file_sep>/README.md # Calculator-on-js5<file_sep>/javScript/chellForData.js var sumButton = document.form.sum; function returnSummNumb(e) { var inputOne = +document.getElementById("vall1").value; var inputTwo = +document.getElementById("vall2").value; var vallOper = form.keyForSumm.options.selectedIndex; var formReset = document.forms['form']; switch (vallOper) { case 0: alert( inputOne + inputTwo ); break; case 1: alert( inputOne - inputTwo ); break; case 2: alert( inputOne * inputTwo ); break; default: alert( inputOne / inputTwo ); } formReset.reset(); } sumButton.addEventListener('click', returnSummNumb);
886113a607de3bae8cbc049612962e3743d4d0b8
[ "JavaScript", "Markdown" ]
3
JavaScript
Roman84asas/Calculator-on-js5
f136239126c3a45d525c6b12014be4a581465ada
1d137f5520fbe20116dd81cc370ca0612f657d55
refs/heads/master
<file_sep>SELECT * FROM customer AS c WHERE NOT EXISTS (SELECT * FROM product AS P WHERE NOT EXISTS (SELECT * FROM purchase AS Pu WHERE Pu.productid = P.productid AND c.customerid = Pu.customerid)) AND (SELECT Sum(pu.qty) FROM purchase AS pu WHERE pu.customerid = c.customerid) >= 50 <file_sep>UPDATE sales.invoicelines SET sales.invoicelines.unitprice = sales.invoicelines.unitprice + 20 WHERE sales.invoicelines.invoicelineid = (SELECT TOP (1) il.invoicelineid FROM sales.customers AS c, sales.invoices AS i, sales.invoicelines AS il WHERE i.invoiceid = il.invoiceid AND i.customerid = c.customerid AND i.customerid = 1060 ORDER BY il.invoicelineid ASC) <file_sep>-- Doing it by Union Pivot SELECT temp.customerid, temp.customername,--temp is the alias for the select queries Sum(temp.invoicestotalvalue) AS InvoicesTotalValue, Sum(temp.ordertotalvalue) AS OrderTotalValue, Sum(temp.nbtotalinvoices) AS NBTotalInvoices, Sum(temp.nbtotalorders) AS NBTotalOrders, Abs(Sum(ordertotalvalue - invoicestotalvalue)) AS AbsoluteValueDifference FROM ((SELECT C.customerid, C.customername, Sum(il.quantity * il.unitprice) AS InvoicesTotalValue, 0 AS OrderTotalValue, 0 AS NBTotalInvoices, 0 AS NBTotalOrders FROM sales.invoices AS i, sales.invoicelines AS il, sales.customers AS c WHERE i.invoiceid = il.invoiceid AND i.customerid = c.customerid GROUP BY C.customerid, C.customername) UNION (SELECT C.customerid, C.customername, 0 AS InvoicesTotalValue, Sum(oi.quantity * oi.unitprice) AS OrderTotalValue, 0 AS NBTotalInvoices, 0 AS NBTotalOrders FROM sales.customers AS c, sales.invoices AS i, sales.orders AS o, sales.orderlines AS oi WHERE o.orderid = oi.orderid AND o.customerid = c.customerid AND i.orderid = o.orderid --makes sure orders are converted from invoices GROUP BY C.customerid, C.customername) UNION (SELECT C.customerid, C.customername, 0 AS InvoicesTotalValue, 0 AS OrderTotalValue, Count(DISTINCT i.invoiceid) AS NBTotalInvoices, 0 AS NBTotalOrders FROM sales.invoices AS i, sales.invoicelines AS il, sales.customers AS c WHERE i.invoiceid = il.invoiceid AND i.customerid = c.customerid GROUP BY C.customerid, C.customername) UNION (SELECT C.customerid, C.customername, 0 AS InvoicesTotalValue, 0 AS OrderTotalValue, 0 AS NBTotalInvoices, Count(DISTINCT o.orderid) AS NBTotalOrders FROM sales.orders AS o, sales.orderlines AS oi, sales.customers AS c, sales.invoices AS i WHERE o.orderid = oi.orderid AND o.customerid = c.customerid AND i.orderid = o.orderid GROUP BY C.customerid, C.customername))AS temp GROUP BY temp.customerid, temp.customername ORDER BY absolutevaluedifference DESC, nbtotalorders ASC, temp.customername ASC <file_sep>SELECT loss.customercategoryname, loss.maxloss, T2.customername, T2.customerid FROM (SELECT T1.customercategoryname, Max(T1.totalvaluelostorders) AS MaxLoss FROM (SELECT Cu.customerid, Cu.customername, Ca.customercategoryname, Sum(ol.quantity * ol.unitprice) AS TotalValueLostOrders FROM sales.orders AS O, sales.orderlines AS ol, sales.customers AS Cu, sales.customercategories AS Ca WHERE NOT EXISTS (SELECT * FROM sales.invoices AS I WHERE I.orderid = O.orderid) AND ol.orderid = O.orderid AND Cu.customerid = O.customerid AND Ca.customercategoryid = Cu.customercategoryid GROUP BY Cu.customerid, Cu.customername, Ca.customercategoryname) AS T1 GROUP BY customercategoryname) AS loss, (SELECT Cu.customerid, Cu.customername, Ca.customercategoryname, Sum(ol.quantity * ol.unitprice) AS TotalValueLostOrders FROM sales.orders AS O, sales.orderlines AS ol, sales.customers AS Cu, sales.customercategories AS Ca WHERE NOT EXISTS (SELECT * FROM sales.invoices AS I WHERE I.orderid = O.orderid) AND ol.orderid = O.orderid AND Cu.customerid = O.customerid AND Ca.customercategoryid = Cu.customercategoryid GROUP BY Cu.customerid, Cu.customername, Ca.customercategoryname) AS T2 WHERE loss.customercategoryname = T2.customercategoryname AND loss.maxloss = T2.totalvaluelostorders ORDER BY loss.maxloss DESC
cdef30b1e235ef1da3195a19a3db2a1b45d8f14e
[ "SQL" ]
4
SQL
famibelle/AdvancedSQLExercises
00c8b478fe8872bd4218cb7398e63070f227c4d9
e11a930f5ffd241bdf92c8bf847172be8013b84a
refs/heads/master
<file_sep>#from django.shortcuts import render # Create your views here. from django.contrib.auth.models import User, Group from rest_framework import viewsets from serializers import UserSerializer, GroupSerializer from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from quickstart.models import Snippet from quickstart.serializers import SnippetSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializer class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JSONResponse(serializer.data) elif request.method == 'POST': data = JSONParser().parse(request) serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400) @csrf_exempt def snippet_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = SnippetSerializer(snippet) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = SnippetSerializer(snippet, data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': snippet.delete() return HttpResponse(status=204)
0e8734e3c0cf62006ff12a2dd47e25e1560a17dc
[ "Python" ]
1
Python
bsunil115/django-rest
da7be2bf16bcd5dc36ed60643987e3d00e0e8334
96bd783a106b648d465f6990c443171cba6d8d47
refs/heads/master
<file_sep>import Midterm from "./Midterm"; export default Midterm;<file_sep>import React from "react"; import Logo from "../../atoms/Logo"; import { Nav, NavItem, NavLink } from "reactstrap" import { } from "./Nav.module.scss"; export default () => { return ( <Nav role="navigation" vertical> <Logo/> <NavItem> <NavLink href="/">Home</NavLink> </NavItem> <NavItem> <NavLink href="/notes">Course Notes</NavLink> </NavItem> <NavItem> <NavLink href="/samples">Sample Code</NavLink> </NavItem> <NavItem> <NavLink href="/midterm">Midterm Exam</NavLink> </NavItem> </Nav> ); };<file_sep>import React from "react"; import Helmet from "react-helmet"; import { } from "./Sample.module.scss"; export default () => { return ( <> <Helmet> <meta name="description" content=""/> <meta name="keywords" content=""/> <title></title> </Helmet> <main role="main"> </main> </> ); };<file_sep>import React from "react"; export default () => { return ( <img src="" alt="" className=""/> ); };
e75cb2fb26063105f3709fbec5e50fc53a34f295
[ "JavaScript" ]
4
JavaScript
richardantao/uwo-cs1027
eacf4e41c9154098cd28e9665125ad9b322df330
4401e94c2c7b561a52b057eee000498e854406f1
refs/heads/master
<repo_name>crestxu/omniWebsocket<file_sep>/websocket.c #include"websocket.h" struct websocketServer server; /* server global state */ static void resetDataFrame(websocket_frame_t *dataframe) { if(dataframe!=NULL) { dataframe->payload_len=0; dataframe->fin=0; dataframe->rsv1=0; dataframe->rsv2=0; dataframe->rsv3=0; dataframe->opcode=0; if(dataframe->payload!=NULL) { sdsfree(dataframe->payload); dataframe->payload=NULL; } //memcpy(dataframe,0,sizeof(dataframe)); } } void initHandShakeFrame(handshake_frame_t *handframe) { handframe->Connection=NULL; handframe->Method=NULL; handframe->Sec_WebSocket_Key=NULL; handframe->Sec_WebSocket_Origin=NULL; handframe->Sec_WebSocket_Version=NULL; handframe->Upgrade=NULL; handframe->Uri=NULL; handframe->Version=NULL; } static void resetHandShakeFrame(handshake_frame_t *handframe) { if(handframe!=NULL) { if(handframe->Connection!=NULL) { sdsfree(handframe->Connection); handframe->Connection=NULL; } if(handframe->Host!=NULL) { sdsfree(handframe->Method); handframe->Method=NULL; } if(handframe->Sec_WebSocket_Key!=NULL) { sdsfree(handframe->Sec_WebSocket_Key); handframe->Sec_WebSocket_Key=NULL; } if(handframe->Sec_WebSocket_Origin!=NULL) { sdsfree(handframe->Sec_WebSocket_Origin); handframe->Sec_WebSocket_Origin=NULL; } if(handframe->Sec_WebSocket_Version!=NULL) { sdsfree(handframe->Sec_WebSocket_Version); handframe->Sec_WebSocket_Version=NULL; } if(handframe->Upgrade!=NULL) { sdsfree(handframe->Upgrade); handframe->Upgrade=NULL; } if(handframe->Uri!=NULL) { sdsfree(handframe->Uri); handframe->Uri=NULL; } if(handframe->Version!=NULL) { sdsfree(handframe->Version); handframe->Version=NULL; } } } static void acceptCommonHandler(int fd) { websocketClient *c; if ((c = createClient(fd)) == NULL) { Log(RLOG_WARNING,"Error allocating resoures for the client"); close(fd); /* May be already closed, just ingore errors */ return; } /* If maxclient directive is set and this is one client more... close the * connection. Note that we create the client instead to check before * for this condition, since now the socket is already set in nonblocking * mode and we can send an error for free using the Kernel I/O */ if (server.maxclients && listLength(server.clients) > server.maxclients) { char *err = "-ERR max number of clients reached\r\n"; /* That's a best effort error message, don't check write errors */ if (write(c->fd,err,strlen(err)) == -1) { /* Nothing to do, Just to avoid the warning... */ } freeClient(c); return; } server.stat_numconnections++; } void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) { int cport, cfd; char cip[128]; WEBSOCKET_NOTUSED(el); WEBSOCKET_NOTUSED(mask); WEBSOCKET_NOTUSED(privdata); cfd = anetTcpAccept(server.neterr, fd, cip, &cport); if (cfd == AE_ERR) { Log(RLOG_VERBOSE,"Accepting client connection: %s", server.neterr); return; } Log(RLOG_VERBOSE,"Accepted %s:%d", cip, cport); acceptCommonHandler(cfd); } int initServer() { signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN); server.mainthread = pthread_self(); server.clients = listCreate(); server.el = aeCreateEventLoop(); if (server.port != 0) { server.ipfd = anetTcpServer(server.neterr,server.port,server.bindaddr); if (server.ipfd == ANET_ERR) { Log(RLOG_WARNING, "Opening port: %s", server.neterr); exit(1); } } if (server.ipfd < 0) { Log(RLOG_WARNING, "Configured to not listen anywhere, exiting."); exit(1); } aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL); if (server.ipfd > 0 && aeCreateFileEvent(server.el,server.ipfd,AE_READABLE, acceptTcpHandler,NULL) == AE_ERR) oom("creating file event"); return 0; } int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) { int j, loops = server.cronloops; WEBSOCKET_NOTUSED(eventLoop); WEBSOCKET_NOTUSED(id); WEBSOCKET_NOTUSED(clientData); server.unixtime = time(NULL); if(server.ping_interval){ if(!(loops%(10*server.ping_interval))){ sendServerPingMsg(); } } /* Show information about connected clients */ if (!(loops % 50)) { Log(RLOG_VERBOSE,"%d clients connected", listLength(server.clients)); } /* Close connections of timedout clients */ if ((server.maxidletime && !(loops % 100))) closeTimedoutClients(); server.cronloops++; return 100; } void closeTimedoutClients(void) { websocketClient *c; listNode *ln; time_t now = time(NULL); listIter li; listRewind(server.clients,&li); while ((ln = listNext(&li)) != NULL) { c = listNodeValue(ln); if (server.maxidletime && (now - c->lastinteraction > server.maxidletime)) { Log(RLOG_VERBOSE,"Closing idle client"); freeClient(c); } } } void freeClient(websocketClient *c) { if(server.onClose!=NULL) { server.onClose(c); } listNode *ln; /* Note that if the client we are freeing is blocked into a blocking * call, we have to set querybuf to NULL *before* to call * unblockClientWaitingData() to avoid processInputBuffer() will get * called. Also it is important to remove the file events after * this, because this call adds the READABLE event. */ sdsfree(c->querybuf); c->querybuf = NULL; aeDeleteFileEvent(server.el,c->fd,AE_READABLE); aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE); listRelease(c->reply); close(c->fd); /* Remove from the list of clients */ ln = listSearchKey(server.clients,c); //assert(ln != NULL); listDelNode(server.clients,ln); resetHandShakeFrame(&c->handshake_frame); zfree(c); } websocketClient *createClient(int fd) { websocketClient *c = zmalloc(sizeof(websocketClient)); c->bufpos = 0; anetNonBlock(NULL,fd); anetTcpNoDelay(NULL,fd); if (!c) return NULL; if (aeCreateFileEvent(server.el,fd,AE_READABLE, readQueryFromClient, c) == AE_ERR) { close(fd); zfree(c); return NULL; } c->flags=0; c->fd = fd; c->querybuf = sdsempty(); c->sentlen = 0; c->lastinteraction = time(NULL); c->reply = listCreate(); listSetFreeMethod(c->reply,sdsfree); listSetDupMethod(c->reply,sdsdup); c->stage = HandshakeStage; initHandShakeFrame(&c->handshake_frame); listAddNodeTail(server.clients,c); //initClientMultiState(c); return c; } void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) { websocketClient *c = (websocketClient*) privdata; char buf[WEBSOCKET_IOBUF_LEN]; int nread; WEBSOCKET_NOTUSED(el); WEBSOCKET_NOTUSED(mask); nread = read(fd, buf, WEBSOCKET_IOBUF_LEN); if (nread == -1) { if (errno == EAGAIN) { nread = 0; } else { Log(RLOG_VERBOSE, "Reading from client: %s",strerror(errno)); freeClient(c); return; } } else if (nread == 0) { Log(RLOG_VERBOSE, "Client closed connection"); freeClient(c); return; } if (nread) { c->querybuf = sdscatlen(c->querybuf,buf,nread); c->lastinteraction = time(NULL); } else { return; } Log(RLOG_VERBOSE,"rev:%s",c->querybuf); processInputBuffer(c); } void processInputBuffer(websocketClient *c) { /* Keep processing while there is something in the input buffer */ while(sdslen(c->querybuf)) { //LT mode Keep process buffer data until sucess if (c->flags & WEBSOCKET_CLOSE_AFTER_REPLY) return; if (c->stage == HandshakeStage) { //handshake if (processHandShake(c) != WEBSOCKET_OK) break; } else { //data frame if (processDataFrame(c) != WEBSOCKET_OK) { Log(RLOG_WARNING,"desc=recv_data_frame_error"); break; } } if (processCommand(c) == WEBSOCKET_OK) resetClient(c); } } void resetClient(websocketClient *c) { } int processHandShake(websocketClient *c) { //resetHandShakeFrame(&c->handshake_frame); if(parseWebSocketHead(c->querybuf,&c->handshake_frame)!=WEBSOCKET_OK) return WEBSOCKET_ERR; return WEBSOCKET_OK; } int parseWebSocketHead(sds querybuf,handshake_frame_t * handshake_frame) { int i=0; while(sdslen(querybuf)>0) { //first find the '/r/n/r/n' end of the http head // char *tmpend=strstr(querybuf,"\r\n\r\n"); // if(tmpend==NULL) // return WEBSOCKET_ERR; char *newline = strstr(querybuf,"\r\n"); int argc, j; sds *argv; size_t querylen; if (newline == NULL) return WEBSOCKET_ERR; querylen =newline - querybuf; argv = sdssplitlen(querybuf,querylen," ",1,&argc); querybuf = sdsrange(querybuf,querylen+2,-1); if(argc==0) break; if(i==0) //first line { if(argc==3) { handshake_frame->Method=argv[0]; handshake_frame->Uri=argv[1]; handshake_frame->Version=argv[2]; } else { Log(RLOG_WARNING,"bad params in first head of websocket"); return WEBSOCKET_ERR; } } else //other line { if(argc==2) { switch(argv[0][0]) { case 'u': case 'U': handshake_frame->Upgrade=argv[1]; break; case 'c': case 'C': handshake_frame->Connection=argv[1]; break; case 'h': case 'H': handshake_frame->Host=argv[1]; break; case 's': case 'S': if(!strcasecmp(argv[0],WEBSOCKET_SEC_WEBSOCKET_VERSION)){ handshake_frame->Sec_WebSocket_Version=argv[1]; } else if(!strcasecmp(argv[0],WEBSOCKET_SEC_WEBSOCKET_KEY)){ handshake_frame->Sec_WebSocket_Key=argv[1]; }else if(!strcasecmp(argv[0],WEBSOCKET_SEC_WEBSOCKET_ORIGIN)){ handshake_frame->Sec_WebSocket_Origin=argv[1]; } break; default: break; } } else { Log(RLOG_WARNING,"bad params in head of websocket: %d",argc); // return WEBSOCKET_ERR; } } if(i++>WEBSOCKET_MAX_HEAD_LEVEL) { Log(RLOG_WARNING,"error head in websocket"); return WEBSOCKET_ERR; } /* for (j = 0; j < argc; j++) { if (sdslen(argv[j])) { printf("sds: %s\r\n",argv[j]); } else { printf("sds: space%s\r\n",argv[j]); sdsfree(argv[j]); } }*/ zfree(argv); } // Log(RLOG_VERBOSE,"Method:%s\r\nUri:%s\r\nVersion:%s\r\nConnection:%s\r\nSec_key:%s\r\nSec_vesion:%s\r\nSec_origin:%s\r\n", // handshake_frame->Method,handshake_frame->Uri,handshake_frame->Version,handshake_frame->Connection, // handshake_frame->Sec_WebSocket_Key,handshake_frame->Sec_WebSocket_Version,handshake_frame->Sec_WebSocket_Origin); return WEBSOCKET_OK; } int parseWebSocketDataFrame(sds querybuf,websocket_frame_t * frame) { if(sdslen(querybuf)<2) { return WEBSOCKET_ERR; } int datalen,i; unsigned char *buf=querybuf; frame->fin = (buf[0] >> 7) & 1; frame->rsv1 = (buf[0] >> 6) & 1; frame->rsv2 = (buf[0] >> 5) & 1; frame->rsv3 = (buf[0] >> 4) & 1; frame->opcode = buf[0] & 0xf; frame->mask = (buf[1] >> 7) & 1; frame->payload_len = buf[1] & 0x7f; int offset=2; if (frame->payload_len == 126) { if(sdslen(querybuf)<4) { return WEBSOCKET_ERR; } unsigned short len; memcpy(&len, buf+2, 2); offset+=2; frame->payload_len = ntohs(len); } else if (frame->payload_len == 127) { if(sdslen(querybuf)<10) { return WEBSOCKET_ERR; } unsigned long len; memcpy(&len, buf+2, 8); offset+=8; frame->payload_len = websocket_ntohll(len); } if(sdslen(querybuf)-offset<4) { return WEBSOCKET_ERR; } if(frame->mask_key) { memcpy(frame->mask_key,buf+offset,4); offset+=4; } if((datalen=(sdslen(querybuf)-offset))!=frame->payload_len) { Log(RLOG_VERBOSE,"desc=recv_error packet_len=%d recv_data_len=%d",frame->payload_len,datalen); return WEBSOCKET_ERR; } else { Log(RLOG_DEBUG,"desc=dataframe len=%d",frame->payload_len); } if (frame->payload_len > 0) { //copy data to payload len if ((frame->opcode == WEBSOCKET_TEXT_OPCODE)) { frame->payload =sdsnewlen(buf+offset,frame->payload_len); // = sdsdup(sdsrange(buf,offset,frame->payload_len)); // sdscpylen(frame->payload,buf+offset,frame->payload_len); if (frame->mask) { for (i = 0; i < frame->payload_len; i++) { frame->payload[i] = frame->payload[i] ^ frame->mask_key[i % 4]; } } Log(RLOG_VERBOSE,"desc=data_frame value=%s",frame->payload); } } querybuf=sdsrange(querybuf,offset+frame->payload_len,-1); Log(RLOG_DEBUG,"desc=after_process_dataframe opcode=%d querybuf_len=%d",frame->opcode,sdslen(querybuf)); if (frame->opcode == WEBSOCKET_CLOSE_OPCODE) { Log(RLOG_DEBUG,"desc=recv_quit_code"); } if(frame->opcode==WEBSOCKET_PONG_OPCODE) { Log(RLOG_DEBUG,"desc=recv_pong_code"); } return WEBSOCKET_OK; } int processDataFrame(websocketClient *c) { // resetDataFrame(&c->data_frame); if(parseWebSocketDataFrame(c->querybuf,&c->data_frame)!=WEBSOCKET_OK) return WEBSOCKET_ERR; return WEBSOCKET_OK; } int _installWriteEvent(websocketClient *c) { if (c->fd <= 0) return WEBSOCKET_ERR; if (c->bufpos == 0 && listLength(c->reply) == 0 &&aeCreateFileEvent(server.el, c->fd, AE_WRITABLE, sendReplyToClient, c) == AE_ERR) return WEBSOCKET_ERR; return WEBSOCKET_OK; } int _addReplyToBuffer(websocketClient *c, char *s, size_t len) { size_t available = sizeof(c->buf)-c->bufpos; /* If there already are entries in the reply list, we cannot * add anything more to the static buffer. */ if (listLength(c->reply) > 0) return WEBSOCKET_ERR; /* Check that the buffer has enough space available for this string. */ if (len > available) return WEBSOCKET_ERR; memcpy(c->buf+c->bufpos,s,len); c->bufpos+=len; return WEBSOCKET_OK; } void _addReplySdsToList(websocketClient *c, sds s) { sds *tail; if (listLength(c->reply) == 0) { listAddNodeTail(c->reply,s); } else { tail = listNodeValue(listLast(c->reply)); /* Append to this object when possible. */ /* if (tail != NULL && sdslen(tail)+sdslen(s) <= WEBSOCKET_REPLY_CHUNK_BYTES) { tail = dupLastObjectIfNeeded(c->reply); tail = sdscatlen(tail,s,sdslen(s)); sdsfree(s); } else {*/ listAddNodeTail(c->reply,s); // } } } void addReplySds(websocketClient *c, sds s) { if (_installWriteEvent(c) != WEBSOCKET_OK) { /* The caller expects the sds to be free'd. */ sdsfree(s); return; } if (_addReplyToBuffer(c,s,sdslen(s)) == WEBSOCKET_OK) { sdsfree(s); } else { /* This method free's the sds when it is no longer needed. */ _addReplySdsToList(c,s); } } void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) { websocketClient *c = privdata; int nwritten = 0, totwritten = 0, objlen; sds o; WEBSOCKET_NOTUSED(el); WEBSOCKET_NOTUSED(mask); while(c->bufpos > 0 || listLength(c->reply)) { if (c->bufpos > 0) { nwritten = write(fd,c->buf+c->sentlen,c->bufpos-c->sentlen); if (nwritten <= 0) break; c->sentlen += nwritten; totwritten += nwritten; /* If the buffer was sent, set bufpos to zero to continue with * the remainder of the reply. */ if (c->sentlen == c->bufpos) { c->bufpos = 0; c->sentlen = 0; } } else { o = listNodeValue(listFirst(c->reply)); objlen = sdslen(o); if (objlen == 0) { listDelNode(c->reply,listFirst(c->reply)); continue; } nwritten = write(fd, ((char*)o)+c->sentlen,objlen-c->sentlen); if (nwritten <= 0) break; c->sentlen += nwritten; totwritten += nwritten; /* If we fully sent the object on head go to the next one */ if (c->sentlen == objlen) { listDelNode(c->reply,listFirst(c->reply)); c->sentlen = 0; } } /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT * bytes, in a single threaded server it's a good idea to serve * other clients as well, even if a very large request comes from * super fast link that is always able to accept data (in real world * scenario think about 'KEYS *' against the loopback interfae) */ //if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break; } if (nwritten == -1) { if (errno == EAGAIN) { nwritten = 0; } else { Log(RLOG_VERBOSE, "Error writing to client: %s", strerror(errno)); freeClient(c); return; } } if (totwritten > 0) c->lastinteraction = time(NULL); if (listLength(c->reply) == 0) { c->sentlen = 0; aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE); if (c->flags & WEBSOCKET_CLOSE_AFTER_REPLY) { Log(RLOG_VERBOSE,"desc=client_logout fd=%d",c->fd); freeClient(c); } } } sds formatted_websocket_ping() { sds frame; if (frame != NULL) { frame = sdsnewlen((void*)&WEBSOCKET_PING_LAST_FRAME_BYTE, sizeof(WEBSOCKET_PING_LAST_FRAME_BYTE)); } return frame; } sds formatted_websocket_frame(sds str) { sds frame= sdsnewlen(&WEBSOCKET_TEXT_LAST_FRAME_BYTE, sizeof(WEBSOCKET_TEXT_LAST_FRAME_BYTE)); long len=sdslen(str); if (frame != NULL) { if (len <= 125) { frame = sdscatlen(frame, &len, 1); } else if (len < (1 << 16)) { frame = sdscatlen(frame, (void*)&WEBSOCKET_PAYLOAD_LEN_16_BYTE, sizeof(WEBSOCKET_PAYLOAD_LEN_16_BYTE)); uint16_t len_net = htons(len); frame = sdscatlen(frame, &len_net, 2); } else { frame = sdscatlen(frame, (void*)&WEBSOCKET_PAYLOAD_LEN_64_BYTE, sizeof(WEBSOCKET_PAYLOAD_LEN_64_BYTE)); uint64_t len_net = websocket_ntohll(len); frame = sdscatlen(frame, &len_net, 8); } frame = sdscatlen(frame, str, sdslen(str)); } return frame; } int generateAcceptKey(sds webKey,char *key,int len) { //char buff[1024]={0}; unsigned char shastr[20]={0}; SHA1_CTX context; char *magicstr="258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; SHA1Init(&context); SHA1Update(&context,webKey,sdslen(webKey)); SHA1Update(&context,magicstr,strlen(magicstr)); SHA1Final(shastr,&context); base64_encode(shastr,20,key,len); Log(RLOG_VERBOSE,"dec=generate_accept_key value=%s",key); return WEBSOCKET_OK; } void sendMsg(list *monitors, sds msg) { listNode *ln; listIter li; listRewind(monitors,&li); while((ln = listNext(&li))) { websocketClient *monitor = ln->value; sds tmpmsg=sdsdup(msg); addReplySds(monitor,tmpmsg); } } void sendServerPingMsg(void){ websocketClient *c; listNode *ln; time_t now = time(NULL); listIter li; listRewind(server.clients,&li); while ((ln = listNext(&li)) != NULL) { c = listNodeValue(ln); if(c->stage==ConnectedStage) addReplySds(c,formatted_websocket_ping()); } } int processCommand(websocketClient *c) { if(c->stage==HandshakeStage){ //do hand shake char buff[1024]={0}; char *res="HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %s\r\nSec-WebSocket-Origin: null\r\nSec-WebSocket-Location: ws://example.com\r\n\r\n"; char key[128]={0}; generateAcceptKey(c->handshake_frame.Sec_WebSocket_Key,key,128); snprintf(buff,1024,res,key); sds m=sdsnew(buff); addReplySds(c,m); c->stage=ConnectedStage; } else{ //process data if(c->data_frame.payload_len>0) { if(server.onData!=NULL) { server.onData(c); } resetDataFrame(&c->data_frame); } else { if(c->data_frame.opcode==WEBSOCKET_CLOSE_OPCODE) { c->flags |= WEBSOCKET_CLOSE_AFTER_REPLY; addReplySds(c,formatted_websocket_ping()); } } } return WEBSOCKET_OK; } <file_sep>/test.c #include<stdio.h> #include<unistd.h> #include<stdlib.h> #include"ae.h" #include<string.h> #include"anet.h" #include"websocket.h" int testHandShake() { sds querybuf=sdsnew("GET /demo HTTP/1.1\r\nHost: example.com\r\nConnection: Upgrade\r\nHost: 10.15.1.218:12345\r\nSec-WebSocket-Origin: null\r\nSec-WebSocket-Key: <KEY>\r\nSec-WebSocket-Version: 8\r\n\r\n"); handshake_frame_t handshake_frame; parseWebSocketHead(querybuf,&handshake_frame); sdsfree(querybuf); printf("Method:%s\r\nUri:%s\r\nVersion:%s\r\nConnection:%s\r\nSec_key:%s\r\nSec_vesion:%s\r\nSec_origin:%s\r\n", handshake_frame.Method,handshake_frame.Uri,handshake_frame.Version,handshake_frame.Connection, handshake_frame.Sec_WebSocket_Key,handshake_frame.Sec_WebSocket_Version,handshake_frame.Sec_WebSocket_Origin); } int main(void) { testHandShake(); return 0; } <file_sep>/base64.h #include<stddef.h> void base64_encode(unsigned char const* src, unsigned int len,unsigned char *dst,unsigned int dst_len); void base64_decode(unsigned char const *s,unsigned int len,unsigned char *dst,unsigned int dst_len); <file_sep>/Makefile OBJ=WServer TESTOBJ=utest MCXXFLAGS =-g -pg -pipe INCLUDES=-I. PROGRAM = $(OBJ) OBJECTS =main.o websocket.o base64.o anet.o ae.o sha1.o ae_epoll.o adlist.o dict.o sds.o logs.o zmalloc.o TESTOBJECTS =test.o websocket.o base64.o anet.o ae.o sha1.o ae_epoll.o adlist.o dict.o sds.o logs.o zmalloc.o CC = gcc all : $(PROGRAM) #test : $(TESTOBJ) test : $(TESTOBJECTS) $(CC) -o $(TESTOBJ) $(TESTOBJECTS) $(MCXXFLAGS) $(INCLUDES) $(LIBS) $(OBJ) : $(OBJECTS) $(CC) -o $(OBJ) $(OBJECTS) $(MCXXFLAGS) $(INCLUDES) $(LIBS) %.o : %.c $(CC) $(MCXXFLAGS) $(INCLUDES) -o $@ -c $< clean : rm -fr *.o rm -f $(PROGRAM) rm -f $(TESTOBJ) <file_sep>/logs.c #include"logs.h" #include <time.h> #include <syslog.h> #include<unistd.h> #include <string.h> #include <stdarg.h> #include <ctype.h> #include <limits.h> #include <fcntl.h> #define LONG_LONG_MAX 9223372036854775807LL #include"websocket.h" //int verbosity=0; //char * logfile=NULL; struct websocketServer server; /* server global state */ void LogRaw(int level, const char *msg) { const int syslogLevelMap[] = { LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING }; const char *c = ".-*#"; FILE *fp; char buf[64]; int rawmode = (level & RLOG_RAW); level &= 0xff; /* clear flags */ if (level < server.verbosity) return; fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a"); if (!fp) return; if (rawmode) { fprintf(fp,"%s",msg); } else { int off; struct timeval tv; gettimeofday(&tv,NULL); off = strftime(buf,sizeof(buf),"%d %b %H:%M:%S.",localtime(&tv.tv_sec)); snprintf(buf+off,sizeof(buf)-off,"%03d",(int)tv.tv_usec/1000); fprintf(fp,"[%d] %s %c %s\n",(int)getpid(),buf,c[level],msg); } fflush(fp); if (server.logfile) fclose(fp); } void Log(int level, const char *fmt, ...) { va_list ap; char msg[MAX_LOGMSG_LEN]; if ((level&0xff) < server.verbosity) return; va_start(ap, fmt); vsnprintf(msg, sizeof(msg), fmt, ap); va_end(ap); LogRaw(level,msg); } void LogFromHandler(int level, const char *msg) { int fd; char buf[64]; if ((level&0xff) < server.verbosity || (server.logfile == NULL )) return; fd = server.logfile ? open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644) : STDOUT_FILENO; if (fd == -1) return; ll2string(buf,sizeof(buf),getpid()); if (write(fd,"[",1) == -1) goto err; if (write(fd,buf,strlen(buf)) == -1) goto err; if (write(fd," | signal handler] (",20) == -1) goto err; ll2string(buf,sizeof(buf),time(NULL)); if (write(fd,buf,strlen(buf)) == -1) goto err; if (write(fd,") ",2) == -1) goto err; if (write(fd,msg,strlen(msg)) == -1) goto err; if (write(fd,"\n",1) == -1) goto err; err: if (server.logfile) close(fd); } /* Glob-style pattern matching. */ int stringmatchlen(const char *pattern, int patternLen, const char *string, int stringLen, int nocase) { while(patternLen) { switch(pattern[0]) { case '*': while (pattern[1] == '*') { pattern++; patternLen--; } if (patternLen == 1) return 1; /* match */ while(stringLen) { if (stringmatchlen(pattern+1, patternLen-1, string, stringLen, nocase)) return 1; /* match */ string++; stringLen--; } return 0; /* no match */ break; case '?': if (stringLen == 0) return 0; /* no match */ string++; stringLen--; break; case '[': { int not, match; pattern++; patternLen--; not = pattern[0] == '^'; if (not) { pattern++; patternLen--; } match = 0; while(1) { if (pattern[0] == '\\') { pattern++; patternLen--; if (pattern[0] == string[0]) match = 1; } else if (pattern[0] == ']') { break; } else if (patternLen == 0) { pattern--; patternLen++; break; } else if (pattern[1] == '-' && patternLen >= 3) { int start = pattern[0]; int end = pattern[2]; int c = string[0]; if (start > end) { int t = start; start = end; end = t; } if (nocase) { start = tolower(start); end = tolower(end); c = tolower(c); } pattern += 2; patternLen -= 2; if (c >= start && c <= end) match = 1; } else { if (!nocase) { if (pattern[0] == string[0]) match = 1; } else { if (tolower((int)pattern[0]) == tolower((int)string[0])) match = 1; } } pattern++; patternLen--; } if (not) match = !match; if (!match) return 0; /* no match */ string++; stringLen--; break; } case '\\': if (patternLen >= 2) { pattern++; patternLen--; } /* fall through */ default: if (!nocase) { if (pattern[0] != string[0]) return 0; /* no match */ } else { if (tolower((int)pattern[0]) != tolower((int)string[0])) return 0; /* no match */ } string++; stringLen--; break; } pattern++; patternLen--; if (stringLen == 0) { while(*pattern == '*') { pattern++; patternLen--; } break; } } if (patternLen == 0 && stringLen == 0) return 1; return 0; } int stringmatch(const char *pattern, const char *string, int nocase) { return stringmatchlen(pattern,strlen(pattern),string,strlen(string),nocase); } /* Convert a string representing an amount of memory into the number of * bytes, so for instance memtoll("1Gi") will return 1073741824 that is * (1024*1024*1024). * * On parsing error, if *err is not NULL, it's set to 1, otherwise it's * set to 0 */ long long memtoll(const char *p, int *err) { const char *u; char buf[128]; long mul; /* unit multiplier */ long long val; unsigned int digits; if (err) *err = 0; /* Search the first non digit character. */ u = p; if (*u == '-') u++; while(*u && isdigit(*u)) u++; if (*u == '\0' || !strcasecmp(u,"b")) { mul = 1; } else if (!strcasecmp(u,"k")) { mul = 1000; } else if (!strcasecmp(u,"kb")) { mul = 1024; } else if (!strcasecmp(u,"m")) { mul = 1000*1000; } else if (!strcasecmp(u,"mb")) { mul = 1024*1024; } else if (!strcasecmp(u,"g")) { mul = 1000L*1000*1000; } else if (!strcasecmp(u,"gb")) { mul = 1024L*1024*1024; } else { if (err) *err = 1; mul = 1; } digits = u-p; if (digits >= sizeof(buf)) { if (err) *err = 1; return LONG_LONG_MAX ; } memcpy(buf,p,digits); buf[digits] = '\0'; val = strtoll(buf,NULL,10); return val*mul; } /* Convert a long long into a string. Returns the number of * characters needed to represent the number, that can be shorter if passed * buffer length is not enough to store the whole number. */ int ll2string(char *s, size_t len, long long value) { char buf[32], *p; unsigned long long v; size_t l; if (len == 0) return 0; v = (value < 0) ? -value : value; p = buf+31; /* point to the last character */ do { *p-- = '0'+(v%10); v /= 10; } while(v); if (value < 0) *p-- = '-'; p++; l = 32-(p-buf); if (l+1 > len) l = len-1; /* Make sure it fits, including the nul term */ memcpy(s,p,l); s[l] = '\0'; return l; } void oom(const char *msg) { Log(RLOG_WARNING, "%s: Out of memory\n",msg); sleep(1); abort(); } uint64_t websocket_ntohll(uint64_t value) { int num = 42; if (*(char *)&num == 42) { uint32_t high_part = ntohl((uint32_t)(value >> 32)); uint32_t low_part = ntohl((uint32_t)(value & 0xFFFFFFFFLL)); return (((uint64_t)low_part) << 32) | high_part; } else { return value; } } <file_sep>/websocket.h /** * @file websocket.h * @brief <CURSOR> * * Detailed description starts here. * * @author xujiajie (), <EMAIL> * * @internal * Created 04/15/2013 * Compiler gcc/g++ * Company baidu.com inc * Copyright Copyright (c) 2013, xujiajie * ===================================================================================== */ #ifndef WEBSOCKET_H #define WEBSOCKET_H #include<stdio.h> #include <signal.h> #include<unistd.h> #include<stdlib.h> #include"ae.h" #include<string.h> #include"anet.h" #include"sds.h" #include"adlist.h" #include"logs.h" #include"sha1.h" #include"base64.h" #include <sys/uio.h> #include <errno.h> #include"ae.h" #define WEBSOCKET_OK 0 #define WEBSOCKET_ERR 1 #define WEBSOCKET_REPLY_CHUNK_BYTES (5*1500) /* 5 TCP packets with default MTU */ #define WEBSOCKET_NOTUSED(V) ((void) V) #define WEBSOCKET_IOBUF_LEN 1024 #define WEBSOCKET_METHOD_GET "Get" #define WEBSOCKET_METHOD_POST "Post" #define WEBSOCKET_UPGRADE "Upgrade:" #define WEBSOCKET_CONNECTION "Connection:" #define WEBSOCKET_HOST "Host:" #define WEBSOCKET_SEC_WEBSOCKET_VERSION "Sec-WebSocket-Version:" #define WEBSOCKET_SEC_WEBSOCKET_KEY "Sec-WebSocket-Key:" #define WEBSOCKET_SEC_WEBSOCKET_ORIGIN "Sec-WebSocket-Origin:" #define WEBSOCKET_TEXT_OPCODE 0x1 #define WEBSOCKET_CLOSE_OPCODE 0x8 #define WEBSOCKET_PING_OPCODE 0x9 #define WEBSOCKET_PONG_OPCODE 0xA #define WEBSOCKET_LAST_FRAME 0x8 typedef unsigned char u_char; typedef unsigned short uint16_t; static const u_char WEBSOCKET_TEXT_LAST_FRAME_BYTE = WEBSOCKET_TEXT_OPCODE | (WEBSOCKET_LAST_FRAME << 4); static const u_char WEBSOCKET_CLOSE_LAST_FRAME_BYTE[] = {WEBSOCKET_CLOSE_OPCODE | (WEBSOCKET_LAST_FRAME << 4), 0x00}; static const u_char WEBSOCKET_PING_LAST_FRAME_BYTE[] = {WEBSOCKET_PING_OPCODE | (WEBSOCKET_LAST_FRAME << 4), 0x00}; static const u_char WEBSOCKET_PAYLOAD_LEN_16_BYTE = 126; static const u_char WEBSOCKET_PAYLOAD_LEN_64_BYTE = 127; #define WEBSOCKET_MAX_HEAD_LEVEL 20 //define the max head line of websocket #define WEBSOCKET_BLOCKED 16 /* The client is waiting in a blocking operation */ #define WEBSOCKET_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */ #define WEBSOCKET_CLOSE_AFTER_REPLY 128 /* Close after writing entire reply. */ #define WEBSOCKET_UNBLOCKED 256 /* This client was unblocked and is stored in server.unblocked_clients */ typedef void (*callback_t)(void *privdata); extern struct websocketServer server; /* server global state */ typedef struct { unsigned char fin:1; unsigned char rsv1:1; unsigned char rsv2:1; unsigned char rsv3:1; unsigned char opcode:4; unsigned char mask:1; unsigned char mask_key[4]; unsigned long payload_len; sds payload; } websocket_frame_t; typedef struct { sds Method; sds Uri; sds Version; sds Upgrade; sds Connection; sds Sec_WebSocket_Version; sds Host; sds Sec_WebSocket_Key; sds Sec_WebSocket_Origin; }handshake_frame_t; typedef struct websocketClient { enum { HandshakeStage = 0, LoginStage, ConnectedStage }WEB_SOCKET_STATUS; int fd; int flags; int stage; //web socket stage sds querybuf; list *reply; int sentlen; websocket_frame_t data_frame; handshake_frame_t handshake_frame; time_t lastinteraction; /* time of the last interaction, used for timeout */ /* Response buffer */ int bufpos; char buf[WEBSOCKET_REPLY_CHUNK_BYTES]; } websocketClient; /* Global server state structure */ struct websocketServer { pthread_t mainthread; int port; char *bindaddr; int ipfd; list *clients; time_t loading_start_time; char neterr[ANET_ERR_LEN]; aeEventLoop *el; int cronloops; /* number of times the cron function run */ time_t stat_starttime; /* server start time */ long long stat_numconnections; /* number of connections received */ /* Configuration */ int verbosity; int maxidletime; int ping_interval; int daemonize; char *logfile; int syslog_enabled; char *syslog_ident; int syslog_facility; //void (*onData)(void *privdata); //void (*onClose)(void *privdata); //void (*onOpen)(void *privdata); callback_t onData; callback_t onClose; callback_t onOpen; /* Limits */ unsigned int maxclients; time_t unixtime; /* Unix time sampled every second. */ }; int initServer(); int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData); void closeTimedoutClients(void); void freeClient(websocketClient *c); websocketClient *createClient(int fd); void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask); void processInputBuffer(websocketClient *c); int processDataFrame(websocketClient *c); int processHandShake(websocketClient *c); void resetClient(websocketClient *c); int processCommand(websocketClient *c); int parseWebSocketHead(sds querybuf,handshake_frame_t * handshake_frame); int parseWebSocketDataFrame(sds querybuf,websocket_frame_t * data_frame); void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask); sds formatted_websocket_ping(); void sendServerPingMsg(void); void sendMsg(list *monitors, sds msg); #endif <file_sep>/logs.h #ifndef UTILS_H #define UTILS_H #include<stdio.h> #define RLOG_RAW (1<<10) #define RLOG_DEBUG 0 #define RLOG_VERBOSE 1 #define RLOG_NOTICE 2 #define RLOG_WARNING 3 #define MAX_LOGMSG_LEN 1024 /* Default maximum length of syslog messages */ typedef unsigned int uint32_t; typedef unsigned long uint64_t; void LogRaw(int level, const char *msg); void Log(int level, const char *fmt, ...); void LogFromHandler(int level, const char *msg); void oom(const char *msg); int ll2string(char *s, size_t len, long long value) ; long long ustime(void); uint64_t websocket_ntohll(uint64_t value); long long mstime(void); #endif <file_sep>/main.c #include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<string.h> #include"websocket.h" void myData(websocketClient *c) { if(strlen(c->data_frame.payload)>0) { sds mm2=sdsdup(c->data_frame.payload); sds mm=formatted_websocket_frame(mm2); sendMsg(server.clients,mm); sdsfree(mm); sdsfree(mm2); Log(RLOG_DEBUG,"desc=querylen len=%d",sdslen(c->querybuf)); } } int main(void) { char *ip="10.26.190.45"; int port=8413; server.bindaddr=ip; server.port=port; server.ping_interval=5; server.maxidletime=15; server.onData=myData; initServer(); aeMain(server.el); aeDeleteEventLoop(server.el); return 0; } <file_sep>/README.md omniWebsocket ============= a c++ websocket server base on my omniwebsocket server
1b4f924deda378b2032dfa88ff7bb2b02c2f1f36
[ "Markdown", "C", "Makefile" ]
9
C
crestxu/omniWebsocket
145eb6a0f14b2c2a564bb249bd692a40fefe6f6d
d132f7815f9644ed7be11d0ada0036ab1575ae14
refs/heads/release/2.x
<file_sep># Z plugin to work with remote enviroments This plugin provides a set of utilities and tasks to work with remote SSH environments ## Usage To access remotes, you can organize them using the `envs` setting: ``` plugins: ['env'] envs: testing: ssh: foo@bar root: /var/www/my-site ``` You can now SSH into this remote by running: ``` z env:ssh testing ``` Unless you have already shared your public key with this environment, you'd be asked for your SSH password. I'd recommend to share your public key with the remote, so you don't have to supply your password everytime the plugin tries to access it. Of course, protecting your keyfile with a passphrase would be sensible. ## Share your key Using the `z env:ssh-copy-id` can copy your key to the remote. Of course, this is a convenience command, which simply wraps around catting your public key to the remote's user's `~/.ssh/authorized_keys` files. It doesn't bother if your ssh is already "connectable". ## Executing remote commands You can execute remote commands by accessing the shell: ``` z env:ssh testing ``` Run a command directly within the remote's root dir: ``` z env:ssh testing "rm -rf ./cache" ``` ## Accessing remotes from your Z file: You have a few options to do this. The most intuitive would be to implement your own ssh command: ``` envs: testing: ssh: foo@bar root: /var/www/my-site tasks: flush-cache: args: target_env: ? do: ssh $(envs[target_env].ssh) "rm -rf $(path(envs[target_env].root, cache))" ``` You can also use something that's called "decorators" to wrap commands in the remote shell. This is shorter, but it is especially useful since you do not need to wrap you command in quotes (which can become pretty hairy), and the `ssh` function respects your current shell. ``` tasks: flush-cache: args: target_env: ? do: @(sh ssh(target_env)) rm -rf $(path(envs[target_env].root, cache)) ``` _Note_: Under the hood, the contents of the command are fed to the STDIN of the shell that is the result of the `ssh` function call. You can verify this using `z z:eval 'ssh("production")'`. This will display the current shell `SHELL` (which is `/bin/bash -e` by default, and adds the `x` flag when in debugging mode) executed on the remote within an SSH. This effectively creates a pipe to which the command's content is streamed. You can mix and match this with other shells (for example a remote mysql client). Read the Z docs for more information on how to leverage this. # Maintainer(s) * <NAME> <<EMAIL>> <file_sep><?php /** * For licensing information, please see the LICENSE file accompanied with this file. * * @author <NAME> <<EMAIL>> * @copyright 2012 <NAME> <http://melp.nl> */ namespace Zicht\Tool\Plugin\Env; use \Zicht\Tool\Plugin as BasePlugin; use \Zicht\Tool\Container\Container; use \Symfony\Component\Process\Process; use \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; /** * Provides some utilities related to environments. */ class Plugin extends BasePlugin { /** * @{inheritDoc} */ public function appendConfiguration(ArrayNodeDefinition $rootNode) { $rootNode ->children() ->scalarNode('local_env')->end() ->arrayNode('envs') ->prototype('array') ->children() ->scalarNode('ssh')->end() ->scalarNode('root') ->validate() ->ifTrue( function($v) { return preg_match('~[^/]$~', $v); } ) ->then( function($v) { return $v . '/'; } ) ->end() ->end() ->scalarNode('ssh_port') ->defaultValue(22) ->end() ->scalarNode('web')->end() ->scalarNode('url')->end() ->scalarNode('db')->end() ->scalarNode('host')->end() ->scalarNode('db_defaults_file') ->defaultValue(null) ->beforeNormalization() ->ifString() ->then(function($v) { return sprintf(' --defaults-extra-file=%s ', $v); }) ->end() ->end() ->end() ->end() ->useAttributeAsKey('name') ->end() ->end() ; } public function setContainer(Container $container) { $container->method(array('ssh'), function($container, $env) { $envSsh = $container->resolve(array('envs', $env, 'ssh'), true); return sprintf('ssh ' . $envSsh . ' -tq "' . $container->resolve('SHELL') . '"'); }); $container->method( array('env', 'versionat'), function (Container $container, $env, $verbose = false) { static $envVcsInfo = array(); if (!isset($envVcsInfo[$env])) { $revFile = sprintf('%s/%s', rtrim($container->resolve(array('envs', $env, 'root'), true), '/'), $container->resolve(array('vcs', 'export', 'revfile'), true)); $envSsh = $container->resolve(array('envs', $env, 'ssh'), true); $tmp = tempnam(sys_get_temp_dir(), 'z_rev_'); $cmd = sprintf('scp -o ConnectTimeout=7 %s:%s %s || true', $envSsh, $revFile, $tmp); $container->helperExec($cmd); $envVcsInfo[$env] = file_get_contents($tmp); unlink($tmp); } if (!isset($envVcsInfo[$env]) || empty($envVcsInfo[$env])) { $envVcsInfo[$env] = 'commit 0000000'; } if ($verbose) { return $envVcsInfo[$env]; } else { return $container->call($container->get(array('vcs', 'versionid')), $envVcsInfo[$env]); } } ); $container->fn( array('ssh', 'connectable'), function ($ssh, $sshPort = null) { $sshOptions = '-o BatchMode=yes -o ConnectTimeout=1 -o StrictHostKeyChecking=no -Tq'; if ($sshPort) { $sshOptions .= ' -p ' . $sshPort; } $sshOptions .= ' ' . $ssh; return shell_exec(sprintf('ssh %s "echo 1" 2>/dev/null;', $sshOptions)); } ); } }
a3fe0f11f1a7c1e943563223adaa930b19861512
[ "Markdown", "PHP" ]
2
Markdown
zicht/z-plugin-env
9e799fe275ad031753484cdbf66c032650e329ef
6506f0b3f6766d3b726e82eb07850c16360af614
refs/heads/master
<file_sep>import React from 'react'; import './main-header.scss'; export default () => { return ( <header className="home-header"> <h1>Cold <span>(Brew)</span>ology</h1> </header> ); } <file_sep>#!/bin/bash mocha --watch --compilers js:babel-core/register --reporter mochawesome --reporter-options reportDir=test/integration/runner,reportFilename=runner,quiet=true,reportPageTitle='MyProject: Integration Test',reportTitle='MyProject: Integration Test' --require test/setup.js test/integration/**/*.test.js & browser-sync start --server --port 3018 --ss ./test/integration/runner -f ./test/integration/runner/* --index ./test/integration/runner/runner.html & <file_sep>import React from 'react'; import { NavLink } from 'react-router-dom'; import { main as content } from '../../constants/content/nav'; import './nav-bar.scss'; export default (props) => { const getNavItems = () => { return ( content.map((item, i) => { const path = item !== "home" ? `/${item}` : "/"; return [ <li key={Math.random()}><NavLink to={path} exact>{item}</NavLink></li>, <li key={Math.random()}>/</li> ]; }) ); } return ( <header className="main-header"> <nav className="main-navigation"> <ul className="nav-links"> { getNavItems() } </ul> </nav> </header> ); } <file_sep>import React from 'react'; import './shop-item.scss'; export default (props) => { const { item, index } = props; const { ListPrice, Title } = item.ItemAttributes; const image = item.MediumImage ? item.MediumImage : item.LargeImage; return ( <div className={`shop-item-container ${index}`}> <a className="title" href={item.DetailPageURL}>{Title}</a> <img src={image && image.URL} height={image.Height} width={image.Width} /> <p className="price">{ListPrice && ListPrice.FormattedPrice}</p> <a className="buy-btn" href={item.DetailPageUrl}>Buy Now</a> </div> ); } <file_sep>#!/bin/bash mocha \ --watch \ --compilers js:babel-core/register \ --reporter mochawesome \ --reporter-options \ reportDir=test/runner, \ reportFilename=runner, \ quiet=true,\ reportPageTitle='MyProject: Unit Test', \ reportTitle='MyProject: Unit Test'\ --require test/setup.js \ $(find src test -name '*.test.js' -not -path 'test/integration/*' -not -path 'node_modules/*' -not -path 'src/_news/*') \ & browser-sync \ start \ --server\ --port 3011 \ --ss ./test/runner \ -f ./test/runner/* \ --index ./test/runner/runner.html \ & <file_sep>import { FETCH_SHOP, FETCH_SHOP_SUCCESS, FETCH_SHOP_FAILURE, RESET_SHOP, } from '../constants'; import initialState from '../constants/initial-state'; export default function shop(state = initialState.shop, action) { switch(action.type) { case FETCH_SHOP: { return { ...state, shopList: { items: null, error: null, loading: true }}; } case FETCH_SHOP_SUCCESS: { const items = action.payload.result.ItemLookupResponse.Items.Item; return { ...state, shopList: { items, error: null, loading: false }}; } case FETCH_SHOP_FAILURE: { return { ...state, shopList: { items: null, error: action.payload, loading: false }} } case RESET_SHOP: { return { ...state, shopList: { items: null, error: null, loading: false }}; } default: { return state; } } } <file_sep>import axios from 'axios'; const API_URL = (typeof window === 'undefined' || process.env.NODE_ENV === 'test') ? process.env.BASE_URL || (`http://localhost:${process.env.PORT || '3001'}/api`) : '/api'; const API = axios.create({ baseURL: API_URL, headers: { "content-type": 'application/json', }, }); const articleConfig = { previewMax: 375, } export { API, API_URL, articleConfig, }; <file_sep>import express from 'express'; import pug from 'pug'; import path from 'path'; const Article = require('../modals/articles'); import { apiResponse } from '../util'; const router = express.Router(); router.get('/get-articles/:page', (req, res) => { const limit = 8; const page = Math.max(0, req.params.page); Article.find({}, null, {sort: {date: -1}}) .limit(limit) .skip(limit * page) .lean() .exec((err, articles) => { if (err) { apiResponse(res, 400, 1, 'error', err); } res.set({ 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Content-Type': 'application/json', }); apiResponse(res, 200, 0, 'success', articles); }); }); router.get('/get-article/:article', (req, res) => { Article.findOne({title: req.params.article}) .lean() .exec((err, article) => { if (err) { apiResponse(res, 400, 1, 'error', err); } apiResponse(res, 200, 0, 'success', article); }); }); router.post('/test-post', (req, res) => { const bodyFile = path.join(__dirname, '../views/posts/') + req.body.post_id + '.pug'; const body = pug.renderFile(bodyFile); const post = new Article({ title: req.body.title, author: '<NAME>', body }); post.save((err, results) => { if (err) console.log(err); console.log(results); }); apiResponse(res, 200, 0, 'success', body); }); export default router; <file_sep>import mongoose, { Schema } from 'mongoose'; const CommentsSchema = new Schema({ author: { type: String, default: '???' }, date: { type: Date, default: Date.now }, body: String, hidden: { type: Boolean, default: false }, likes: { type: Number, default: 0 }, }); CommentsSchema.method('like', (like, cb) => { this.likes += 1; this.parent().save(cb); }); export default CommentsSchema; <file_sep>import mongoose from 'mongoose'; import CommentsSchema from './comments'; const Schema = mongoose.Schema; const ArticleSchema = new Schema({ title: String, author: { type: String, default: '<NAME>' }, date: { type: Date, default: Date.now }, geekLevel: { type: String, default: 'Basic' }, body: String, comments: [CommentsSchema], hidden: { type: Boolean, default: false }, likes: { type: Number, default: 0 } }); ArticleSchema.method('like', (like, cb) => { this.likes += 1; this.parent().save(cb); }); const Article = mongoose.model('Article', ArticleSchema); module.exports = Article; <file_sep>import { combineReducers } from 'redux'; import nav from './reducer_nav'; import articles from './reducer_articles'; import shop from './reducer_shop'; const rootReducer = combineReducers({ nav, articles, shop, }); export default rootReducer; <file_sep>import titleCase from 'title-case'; const stripHTML = html => { return html.replace(/<(?:.|\n)*?>/gm, ''); } const formatTitle = title => { const newTitle = title.replace('-', ' '); return titleCase(newTitle); } export { stripHTML, formatTitle, } <file_sep># cold-brewology The science and art of making delicious cold brew coffee <file_sep>import { expect } from 'chai'; import { formatTitle, stripHTML } from './util'; describe('Util.js', function () { describe('formatTitle()', function () { const tests = [ {arg: "cold-brew-title", expected: "Cold Brew Title"}, {arg: "another-title", expected: "Another Title"}, {arg: "very-long-long-title", expected: "Very Long Long Title"}, {arg: "very-very-long-long-long-long-title", expected: "Very Very Long Long Long Long Title"}, {arg: "title-with-a-lowercase", expected: "Title With A Lowercase"}, {arg: "number-6", expected: "Number 6"}, {arg: "1-more-number", expected: "1 More Number"}, {arg: "another-3-title", expected: "Another 3 Title"}, {arg: "sansdashes", expected: "Sansdashes"}, {arg: "-weird-title", expected: "Weird Title"}, {arg: "another-weird-", expected: "Another Weird"}, {arg: " title-with-spaces ", expected: "Title With Spaces"} ]; it('Should return a string', function () { expect(formatTitle(tests[0].arg)).to.be.a('string'); }); tests.forEach((test, i) => { const { arg, expected } = test; it(`The string ${arg} should become: ${expected}`, function () { expect(formatTitle(arg)).to.equal(expected); }); }); }); }); <file_sep>import React from 'react'; import './measure-lines.scss'; export default (props) => { const buildMeasureLines = () => { const lineAmount = 1000; let lineArray = []; for(let i = lineAmount; i >= 0; i -= 100) { lineArray.push(<li className="line" key={`line${i}`}>{i}mL</li>); } return lineArray; } return ( <div className="measure-lines-container"> <ul className="measure-lines"> {buildMeasureLines()} </ul> </div> ); } <file_sep>//Global export const PAGE_LOADED = "PAGE_LOADED"; //ARTICLE list export const FETCH_ARTICLES = 'FETCH_ARTICLES'; export const FETCH_ARTICLES_SUCCESS = 'FETCH_ARTICLES_SUCCESS'; export const FETCH_ARTICLES_FAILURE = 'FETCH_ARTICLES_FAILURE'; export const RESET_ARTICLES = 'RESET_ARTICLES'; //Create new ARTICLE export const CREATE_ARTICLE = 'CREATE_ARTICLE'; export const CREATE_ARTICLE_SUCCESS = 'CREATE_ARTICLE_SUCCESS'; export const CREATE_ARTICLE_FAILURE = 'CREATE_ARTICLE_FAILURE'; export const RESET_NEW_ARTICLE = 'RESET_NEW_ARTICLE'; //Validate ARTICLE fields like Title, Categries on the server export const VALIDATE_ARTICLE_FIELDS = 'VALIDATE_ARTICLE_FIELDS'; export const VALIDATE_ARTICLE_FIELDS_SUCCESS = 'VALIDATE_ARTICLE_FIELDS_SUCCESS'; export const VALIDATE_ARTICLE_FIELDS_FAILURE = 'VALIDATE_ARTICLE_FIELDS_FAILURE'; export const RESET_ARTICLE_FIELDS = 'RESET_ARTICLE_FIELDS'; //Fetch ARTICLE export const FETCH_ARTICLE = 'FETCH_ARTICLE'; export const FETCH_ARTICLE_SUCCESS = 'FETCH_ARTICLE_SUCCESS'; export const FETCH_ARTICLE_FAILURE = 'FETCH_ARTICLE_FAILURE'; export const RESET_ACTIVE_ARTICLE = 'RESET_ACTIVE_ARTICLE'; //Delete ARTICLE export const DELETE_ARTICLE = 'DELETE_ARTICLE'; export const DELETE_ARTICLE_SUCCESS = 'DELETE_ARTICLE_SUCCESS'; export const DELETE_ARTICLE_FAILURE = 'DELETE_ARTICLE_FAILURE'; export const RESET_DELETED_ARTICLE = 'RESET_DELETED_ARTICLE'; //SHOP list export const FETCH_SHOP = 'FETCH_SHOP'; export const FETCH_SHOP_SUCCESS = 'FETCH_SHOP_SUCCESS'; export const FETCH_SHOP_FAILURE = 'FETCH_SHOP_FAILURE'; export const RESET_SHOP = 'RESET_SHOP'; <file_sep>import React, { Component } from 'react'; import axios from 'axios'; class PostTest extends Component { constructor(props) { super(props); this.state = { title: '', post_id: '' } } handleChange(e, type) { e.preventDefault(); switch(type) { case "title": this.setState({ title: e.target.value }); break; case "post": this.setState({ post_id: e.target.value }); break; default: break; } } handleSubmit(e) { e.preventDefault(); const { title, post_id } = this.state; axios.post('/api/test-post', { title, post_id, }) .then(res => { console.log(res); }) .catch(err => { console.log(err); }) } render() { return ( <div> <p>Add a new test post:</p> <form action="" onSubmit={(e) => this.handleSubmit(e)}> <label>Title</label> <input onChange={e => this.handleChange(e, 'title')} id="title" type="text" name="title"/> <label>Post ID</label> <input onChange={e => this.handleChange(e, 'post')} id="post_id" type="text" name="post_id"/> <input type="submit" /> </form> </div> ); } } export default PostTest; <file_sep>import express from 'express'; import articles from './articles'; import shop from './shop'; const router = express.Router(); router.use('/', articles); router.use('/', shop); export default router; <file_sep>import React from 'react'; import { Link } from 'react-router-dom'; import { formatDate } from '../../util/date'; import { stripHTML, formatTitle } from '../../util/util'; import { articleConfig as config } from '../../constants/config'; import './article-list-item.scss'; export default (props) => { const { index: i, title, date, author, body, geekLevel } = props; const getPreview = body => { const { previewMax } = config; const preview = stripHTML(body); return `${preview.length > previewMax ? preview.substring(0, previewMax) : preview}...`; } return ( <Link to={`/article/${title}`} className={`article-${i + 1}`} key={Math.random()}> <h3 className="title"> {formatTitle(title)} / <span className="author">{author}</span> </h3> <div className="info-container"> <p className="geek-level">Geek Level: <span>{geekLevel}</span></p> <p className="date">{formatDate(date)}</p> </div> <img src={require('../../assets/article-list/article-list-item.jpg')} /> <p className="preview">{getPreview(body)}</p> </Link> ); } <file_sep>import express from 'express'; import http from 'http'; import https from 'https'; import fs from 'fs'; import path from 'path'; import bodyParser from 'body-parser'; import React from 'react'; import mongoose from 'mongoose'; import { renderToString } from 'react-dom/server'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import { StaticRouter } from 'react-router'; import App from '../src/containers/app'; import reducers from '../src/reducers'; import config from './config'; import api from './api'; import criticalCSS from './views/critical.css'; // webpack import webpack from 'webpack'; import wpConfig from '../webpack.dev.config'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; // initialization const app = new express(); const viewDir = process.env.LIVE ? 'dist/views' : 'server/views'; const PORT = process.env.LIVE ? config.LIVE_PORT : config.DEV_PORT; app.set('view engine', 'pug'); app.set('views', viewDir); // connect to database and start server mongoose.Promise = global.Promise; mongoose.connect(`mongodb://${config.DB_HOST}:${config.DB_PORT}/cold-brewology`, { useMongoClient: true, }); const db = mongoose.connection; db.on('error', (err) => { console.error(err); }) db.once('open', () => { console.log('mongo connected...'); app.listen(PORT, err => { if (err) { console.error(err); } console.log(`Cold Brewology now live at ${PORT}!`); }); }) // Run Webpack dev server in development mode if (process.env.NODE_ENV === 'development') { const compiler = webpack(wpConfig); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: wpConfig.output.publicPath, stats: {colors: true} })); app.use(webpackHotMiddleware(compiler, { log: console.log })); } // Middlewares app.use(express.static(path.join(__dirname, 'public/'))); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); // API routes app.use('/api', api); // server side rendering app.use((req, res) => { const store = createStore(reducers); const context = {}; const html = renderToString( <Provider store={store}> <StaticRouter location={req.url} context={context}> <App /> </StaticRouter> </Provider> ); if (context.url) { res.redirect(301, context.url); res.end() } const preloadedState = store.getState(); res .set('Content-Type', 'text/html') .status(200) .render('index', { html, preloadedState, criticalCSS, }); }); <file_sep>import React from 'react'; import ArticleListItem from '../article-list-item'; import MeasureLines from '../measure-lines'; import './article-list.scss'; export default (props) => { const { articles, error, loading } = props; const renderArticleList = () => { switch(true) { case loading: { return ( <p>Loading...</p> ); } case error !== null: { return ( <p>{error}</p> ); } case articles !== null: { return ( articles.map((article, i) => { const { title, date, author, body, geekLevel } = article; return ( <ArticleListItem index={i} title={title} date={date} author={author} body={body} geekLevel={geekLevel} /> ) }) ); } default: { return; } } } const articleList = ( <div className="articles-list"> {renderArticleList()} </div> ); return ( <section className="articles-list-section"> {articleList} <MeasureLines /> </section> ); } <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import { fetchShop, fetchShopSuccess, fetchShopFailure, resetShop } from '../../actions/shop'; import { APAC, API } from '../../constants/config'; import ShopItem from '../../components/shop-item'; class Shop extends Component { constructor(props) { super(props); } componentDidMount() { const { fetchShop, shopType } = this.props; this.props.fetchShop(shopType, 0); } componentWillUnmount() { this.props.resetShop(); } render() { const { shopType, items, loading, error } = this.props; const renderShop = ( <div className="shop-container" key={Math.random()}> { items && items.map((item, i) => { return <ShopItem item={item} index={i} key={Math.random()}/>; }) } </div> ); return ( <div className={`shop-${shopType}`}> <h2>{shopType}</h2> { loading && <p>Loading...</p> } { error && error } { renderShop } </div> ); } } const mapStateToProps = ({ shop }) => { const { items, loading, error } = shop.shopList; return { items, loading, error, } } const mapDispatchToProps = dispatch => { return { fetchShop: (type, page) => { dispatch(fetchShop(type, page)) .then((result) => { const { payload } = result; if (payload && payload.status !== 200) { dispatch(fetchShopFailure(payload.data.message)); } else { dispatch(fetchShopSuccess(payload.data.data)); } }) }, resetShop: () => { dispatch(resetShop()); } } } export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Shop)); <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import { fetchArticle, fetchArticleSuccess, fetchArticleFailure } from '../../actions/articles'; import { formatDate } from '../../util/date'; import './article.scss'; class Article extends Component { constructor(props) { super(props); } componentDidMount() { const { fetchArticle, match } = this.props; fetchArticle(match.params.article || window.location.pathname.slice(9)); } renderBody(body) { return { __html: body }; } renderArticle() { const { article, loading, error } = this.props; switch (true) { case loading: { return ( <p>Loading...</p> ); } case error: { return ( <p>{error}</p> ); } case article !== null: { const { title, body, likes, hidden, author, date, comments } = article; const dateString = formatDate(date); return ( <article className="article-wrapper"> <h1>{title}</h1> <h2>By {author} / {dateString}</h2> <div className="article-likes">{`Likes: ${likes}`}</div> <div className="article-body" dangerouslySetInnerHTML={this.renderBody(body)}></div> </article> ); } default: return; } } render() { return ( <section className="article"> { this.renderArticle() } </section> ); } } const mapStateToProps = ({ articles }) => { const { activeArticle } = articles; return { article: activeArticle.article, error: activeArticle.error, loading: activeArticle.loading, } } const mapDispatchToProps = dispatch => { return { fetchArticle: article => { dispatch(fetchArticle(article)) .then(result => { const { payload } = result; if (payload && payload.status !== 200) { dispatch(fetchArticleFailure(payload.data.message)); } else { dispatch(fetchArticleSuccess(payload.data.data)); } }) .catch(err => { dispatch(fetchArticleFailure(err)); }); } } } export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Article)); <file_sep>import { API } from '../constants/config'; import { FETCH_ARTICLES, FETCH_ARTICLES_SUCCESS, FETCH_ARTICLES_FAILURE, RESET_ARTICLES, FETCH_ARTICLE, FETCH_ARTICLE_SUCCESS, FETCH_ARTICLE_FAILURE, RESET_ACTIVE_ARTICLE, CREATE_ARTICLE, CREATE_ARTICLE_SUCCESS, CREATE_ARTICLE_FAILURE, RESET_NEW_ARTICLE, DELETE_ARTICLE, DELETE_ARTICLE_SUCCESS, DELETE_ARTICLE_FAILURE, RESET_DELETED_ARTICLE, VALIDATE_ARTICLE_FIELDS,VALIDATE_ARTICLE_FIELDS_SUCCESS, VALIDATE_ARTICLE_FIELDS_FAILURE, RESET_ARTICLE_FIELDS } from '../constants'; export function fetchArticles(page) { const request = API.get(`/get-articles/${page}`); return { type: FETCH_ARTICLES, payload: request, } } export function fetchArticlesSuccess(data) { return { type: FETCH_ARTICLES_SUCCESS, payload: data, } } export function fetchArticlesFailure(error) { return { type: FETCH_ARTICLES_FAILURE, payload: error, } } export function fetchArticle(article) { const request = API.get(`/get-article/${article}`); return { type: FETCH_ARTICLE, payload: request, } } export function fetchArticleSuccess(data) { return { type: FETCH_ARTICLE_SUCCESS, payload: data, } } export function fetchArticleFailure(error) { return { type: FETCH_ARTICLE_FAILURE, payload: error, } } <file_sep>import express from 'express'; import path from 'path'; import { apiResponse } from '../util'; import { OperationHelper } from 'apac'; import products from '../data/products'; import config from '../config'; const router = express.Router(); const APAC = new OperationHelper(config.APAC); router.get('/get-shop/:type/:page', (req, res) => { APAC.execute('ItemLookup', { ItemId: products[req.params.type], idType: 'ASIN', ResponseGroup: "Medium, ItemAttributes, Images", }) .then((data) => { apiResponse(res, 200, 0, 'success', data); }) .catch((err) => { apiResponse(res, 500, 0, 'error', err); }); }); export default router;
202e392c2201125e52f6bc859446ad8a2baf2d91
[ "JavaScript", "Markdown", "Shell" ]
25
JavaScript
musicbender/cold-brewology
c1e4ee4bf210032d003b7d5f0d411a45f997499d
4bf54e1ef91ae9e0fdaa044aa1ea3c4ca47ac5dd
refs/heads/master
<file_sep>import React from 'react'; import Botao from '../Botao/Botao'; import './Contador.css'; class Contador extends React.Component { state = { contador: 0 } aumentar = () => { let novoContador = this.state.contador; novoContador++; this.setState({contador: novoContador}); } diminuir = () => { let novoContador = this.state.contador; novoContador--; this.setState({contador: novoContador}); } reset = () => { this.setState({contador:0}) } render(){ return ( <div> <h1>O valor do contador é: {this.state.contador} </h1> <Botao classe="botao" aoClicar={this.aumentar} titulo="Aumentar" /> <Botao classe="botao2" aoClicar={this.diminuir} titulo="Diminuir" /> <Botao classe="botao3" aoClicar={this.reset} titulo="Reset" /> </div> ); } } export default Contador;
02e865669aa1fd214887dd117ef51bda4078e093
[ "JavaScript" ]
1
JavaScript
BrennoHoffmann/reactTest
d60ca1b8c6dbc8122eab3a2e31892e696213dc7d
76cb66c19ee28b0d1eeab4a61195956f5aea71c0
refs/heads/master
<repo_name>herosugi/TrelloExcel<file_sep>/TrelloExcelAddIn/ExportCards/ExportCardsPresenter.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using TrelloNet; namespace TrelloExcelAddIn { public class ExportCardsPresenter { private readonly IExportCardsView view; private readonly TaskScheduler taskScheduler; private readonly IMessageBus messageBus; private readonly ITrello trello; private readonly ICreateNewCards transformer; private CancellationTokenSource exportCardsCancellationTokenSource; public ExportCardsPresenter(IExportCardsView view, ITrello trello, ICreateNewCards transformer, TaskScheduler taskScheduler, IMessageBus messageBus) { this.view = view; this.taskScheduler = taskScheduler; this.messageBus = messageBus; this.trello = trello; this.transformer = transformer; exportCardsCancellationTokenSource = new CancellationTokenSource(); SetupMessageEventHandlers(); SetupEventHandlers(); SetupInitialState(); } private void SetupMessageEventHandlers() { messageBus.Subscribe<TrelloWasAuthorizedEvent>(_ => FetchAndDisplayBoards()); } private void SetupEventHandlers() { view.BoardWasSelected += BoardWasSelected; view.ExportCardsWasClicked += ExportCardsWasClicked; view.RefreshButtonWasClicked += RefreshButtonWasClicked; view.CancelButtonWasClicked += CancelButtonWasClicked; } private void SetupInitialState() { DisableStuff(); } private void DisableStuff() { view.EnableSelectionOfBoards = false; view.EnableSelectionOfLists = false; view.EnableExportCards = false; view.EnableRefreshButton = false; } private void EnableStuff() { view.EnableSelectionOfBoards = true; view.EnableSelectionOfLists = true; view.EnableExportCards = true; view.EnableRefreshButton = true; } private void ExportCardsWasClicked(object sender, EventArgs eventArgs) { view.ShowStatusMessage("Adding cards..."); view.HideCancelButton = false; view.HideExportButton = true; DisableStuff(); var cards = transformer.CreateCards(view.SelectedList); var addCardsTask = Task.Factory.StartNew(() => ExportCards(cards), exportCardsCancellationTokenSource.Token); addCardsTask.ContinueWith(task => { view.ShowStatusMessage(exportCardsCancellationTokenSource.IsCancellationRequested ? "Canceled!" : "All cards added!"); exportCardsCancellationTokenSource = new CancellationTokenSource(); EnableStuff(); view.HideCancelButton = true; view.HideExportButton = false; }, taskScheduler); } private void RefreshButtonWasClicked(object sender, EventArgs eventArgs) { FetchAndDisplayBoards(); } private void CancelButtonWasClicked(object sender, EventArgs eventArgs) { exportCardsCancellationTokenSource.Cancel(); } private bool ExportCards(IEnumerable<NewCard> cards) { var totalCount = cards.Count(); var currentCard = 0; foreach (var newCard in cards) { if (exportCardsCancellationTokenSource.Token.IsCancellationRequested) return false; Task.Factory.StartNew(() => view.ShowStatusMessage(@"Adding card {0}/{1}.", ++currentCard, totalCount), CancellationToken.None, TaskCreationOptions.None, taskScheduler); trello.Cards.Add(newCard); } return true; } private void FetchAndDisplayBoards() { DisableStuff(); Task.Factory.StartNew(() => { // <WTF> var boards = trello.Boards.ForMe(BoardFilter.Open); var organizations = boards .Select(b => b.IdOrganization) .Where(s => !string.IsNullOrEmpty(s)) .Distinct() .Select(orgId => { try { return trello.Organizations.WithId(orgId); } catch (TrelloUnauthorizedException) { return null; } }) .Where(o => o != null) .ToDictionary(organization => organization.Id); return boards.Select(b => { var model = new BoardViewModel(b); if (b.IdOrganization != null && organizations.ContainsKey(b.IdOrganization)) model.SetOrganizationName(organizations[b.IdOrganization].DisplayName); return model; }); // </WTF> }) .ContinueWith(t => { if (t.Exception == null) { view.DisplayBoards(t.Result); view.EnableSelectionOfBoards = true; } else { HandleException(t.Exception); } }, taskScheduler); } private void BoardWasSelected(object sender, EventArgs e) { FetchAndDisplayLists(); } private void FetchAndDisplayLists() { trello.Async.Lists.ForBoard(view.SelectedBoard) .ContinueWith(t => { if (t.Exception == null) { view.DisplayLists(t.Result); EnableStuff(); } else { HandleException(t.Exception); } }, taskScheduler); } private void HandleException(AggregateException exception) { view.EnableSelectionOfLists = false; view.EnableSelectionOfBoards = false; view.DisplayBoards(Enumerable.Empty<BoardViewModel>()); view.DisplayLists(Enumerable.Empty<List>()); if (exception.InnerException is TrelloUnauthorizedException) messageBus.Publish(new TrelloWasUnauthorizedEvent()); view.ShowErrorMessage(exception.InnerException.Message); } } }<file_sep>/README.markdown # TrelloExcel An Excel Add-In that creates cards in [Trello](https://trello.com) from rows in Excel 2010 (Excel 2007 is not supported). Download it from the [download page](https://github.com/dillenmeister/TrelloExcel/downloads). Follow progress on [this Trello board](https://trello.com/board/trelloexcel/4f74e95f90253b853b2b547b). License: [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html) <file_sep>/TrelloExcelAddIn/TrelloWasUnauthorizedEvent.cs namespace TrelloExcelAddIn { public class TrelloWasUnauthorizedEvent { } }<file_sep>/Tests/Specs/ExportCards.cs // ReSharper disable InconsistentNaming using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using FakeItEasy; using Machine.Specifications; using TrelloExcelAddIn; using TrelloNet; namespace Tests.Specs { [Subject(typeof(ExportCardsPresenter))] public class ExportCards : ExportCardsSpecs { public class when_trello_was_authorized { Establish context = () => { boards = new List<Board> { new Board { Name = "board 1" }, new Board { Name = "board 2", IdOrganization = "123" } }; A.CallTo(() => trello.Boards.ForMe(BoardFilter.Open)).Returns(boards); A.CallTo(() => trello.Organizations.WithId("123")).Returns(new Organization { Id = "123", DisplayName = "org 1" }); }; Because of = () => { messageBus.Publish(new TrelloWasAuthorizedEvent(new Member())); Thread.Sleep(30); }; It should_display_boards = () => A.CallTo(() => view.DisplayBoards(A<IEnumerable<BoardViewModel>>._)).MustHaveHappened(); It should_display_boards_with_correct_names = () => A.CallTo(() => view.DisplayBoards(A<IEnumerable<BoardViewModel>>.That.Matches(b => b.ElementAt(0).ToString() == "board 1"))).MustHaveHappened(); It should_display_boards_with_organization_name = () => A.CallTo(() => view.DisplayBoards(A<IEnumerable<BoardViewModel>>.That.Matches(b => b.ElementAt(1).ToString() == "board 2 (org 1)"))).MustHaveHappened(); static List<Board> boards; } public class when_a_board_is_selected { Establish context = () => { var selectedBoard = new BoardId("dummy"); A.CallTo(() => view.SelectedBoard).Returns(selectedBoard); A.CallTo(() => trello.Async.Lists.ForBoard(selectedBoard, ListFilter.Open)) .Returns(Task.Factory.StartNew<IEnumerable<List>>(() => lists)); }; private Because of = () => { view.BoardWasSelected += Raise.WithEmpty().Now; Thread.Sleep(30); }; It should_display_lists_for_that_board = () => A.CallTo(() => view.DisplayLists(lists)).MustHaveHappened(); It should_enable_selection_of_lists = () => view.EnableSelectionOfLists.ShouldBeTrue(); It should_enable_export_cards = () => view.EnableExportCards.ShouldBeTrue(); static List<List> lists; } public class when_a_board_is_selected_and_trello_is_not_authenticated { Establish context = () => A.CallTo(() => trello.Async.Lists.ForBoard(A<IBoardId>._, ListFilter.Open)) .Returns(Task.Factory.StartNew<IEnumerable<List>>(() => { throw new TrelloUnauthorizedException("error"); })); Because of = () => { view.BoardWasSelected += Raise.WithEmpty().Now; Thread.Sleep(30); }; It should_show_an_error_message = () => A.CallTo(() => view.ShowErrorMessage("error")).MustHaveHappened(); It should_disable_selection_of_boards = () => view.EnableSelectionOfBoards.ShouldBeFalse(); It should_disable_selection_of_lists = () => view.EnableSelectionOfLists.ShouldBeFalse(); It should_empty_the_list_of_boards = () => A.CallTo(() => view.DisplayBoards(A<IEnumerable<BoardViewModel>>.That.IsEmpty())).MustHaveHappened(); It should_empty_the_list_of_lists = () => A.CallTo(() => view.DisplayLists(A<IEnumerable<List>>.That.IsEmpty())).MustHaveHappened(); } public class when_export_cards_is_clicked_and_two_rows_are_selected { Establish context = () => A.CallTo(() => transformer.CreateCards(A<IListId>._)).Returns(newCards); Because of = () => { view.ExportCardsWasClicked += Raise.WithEmpty().Now; Thread.Sleep(30); }; It should_display_a_status_message = () => A.CallTo(() => view.ShowStatusMessage("Adding cards...", A<object[]>._)).MustHaveHappened(); It should_add_each_card_to_trello = () => { A.CallTo(() => trello.Cards.Add(newCards[0])).MustHaveHappened(); A.CallTo(() => trello.Cards.Add(newCards[1])).MustHaveHappened(); }; It should_display_a_status_message_for_each_card_added = () => A.CallTo(() => view.ShowStatusMessage("Adding card {0}/{1}.", A<object[]>._)).MustHaveHappened(Repeated.Exactly.Twice); It should_display_a_status_message_when_all_cards_are_added = () => A.CallTo(() => view.ShowStatusMessage("All cards added!", A<object[]>._)).MustHaveHappened(); static NewCard[] newCards = new[] { new NewCard("card 1", new ListId("dummy")), new NewCard("card 2", new ListId("dummy")) }; } public class when_the_refresh_button_is_clicked { Establish context = () => { A.CallTo(() => trello.Boards.ForMe(BoardFilter.Open)).Returns(new[] { new Board { Name = "board 1" } }); }; Because of = () => { view.RefreshButtonWasClicked += Raise.WithEmpty().Now; Thread.Sleep(30); }; It should_refresh_the_list_of_boards = () => A.CallTo(() => view.DisplayBoards(A<IEnumerable<BoardViewModel>>.That.Matches(b => b.First().ToString() == "board 1"))).MustHaveHappened(); static List<Board> boards; } } public abstract class ExportCardsSpecs { protected static ExportCardsPresenter presenter; protected static IExportCardsView view; protected static ICreateNewCards transformer; protected static ITrello trello; protected static IMessageBus messageBus; Establish context = () => { view = A.Fake<IExportCardsView>(); transformer = A.Fake<ICreateNewCards>(); messageBus = new MessageBus(); trello = A.Fake<ITrello>(); presenter = new ExportCardsPresenter(view, trello, transformer, TaskScheduler.Current, messageBus); }; } } // ReSharper restore InconsistentNaming<file_sep>/TrelloExcelAddIn/ExportCards/ICreateNewCards.cs using System.Collections.Generic; using TrelloNet; namespace TrelloExcelAddIn { public interface ICreateNewCards { IEnumerable<NewCard> CreateCards(IListId list); IEnumerable<NewCard> CreateCards(Grid grid, IListId list); } }<file_sep>/TrelloExcelAddIn/TrelloRibbon.cs using System.Collections.Generic; using Microsoft.Office.Tools.Ribbon; using TrelloNet; namespace TrelloExcelAddIn { public partial class TrelloRibbon { private static readonly Dictionary<string, Expiration> ButtonIdsToExpirationMap = new Dictionary<string, Expiration> { { "LoginExpireOneHourButton", Expiration.OneHour }, { "LoginExpireOneDayButton", Expiration.OneDay }, { "LoginExpire30DaysButton", Expiration.ThirtyDays }, { "LoginNeverExpireButton", Expiration.Never } }; private void TrelloRibbon_Load(object sender, RibbonUIEventArgs e) { } private void AddToTrelloButton_Click(object sender, RibbonControlEventArgs e) { Globals.ThisAddIn.ExportCardsTaskPane.Visible = !Globals.ThisAddIn.ExportCardsTaskPane.Visible; } public void SetMessageBus(IMessageBus messageBus) { messageBus.Subscribe<TrelloWasUnauthorizedEvent>(@event => { ExportCardsButton.Enabled = false; LoginSplitButton.Visible = true; LoggedInButton.Visible = false; }); messageBus.Subscribe<TrelloWasAuthorizedEvent>(@event => { ExportCardsButton.Enabled = true; LoginSplitButton.Visible = false; LoggedInButton.Label = string.Format("Logged in as {0}", @event.Member.Username); LoggedInButton.Visible = true; }); } private void LoginButton_Click(object sender, RibbonControlEventArgs e) { Expiration expiration; if(!ButtonIdsToExpirationMap.TryGetValue(e.Control.Id, out expiration)) expiration = Expiration.Never; Globals.ThisAddIn.AuthorizePresenter.StartAuthorization(expiration); } } }
8dbda3a509fd0b04d7e7b37deefd5aa3c971d022
[ "Markdown", "C#" ]
6
C#
herosugi/TrelloExcel
0b4bf8dc602d9f70816f774cf7a48ee02df5f2b8
3926f75b63aaed2b43af779ecd54dbee6aae2ea0
refs/heads/master
<file_sep>enchant(); var game; var channel; var currentLevel = 1; var background; var navy; var clientIP, serverIP; var counterId = 0; var chosenNavy = 0; var gameMode = GAME_MODE.SINGLE_PLAYER; window.onload = function () { game = new Core(VIEWPORT.WIDTH, VIEWPORT.HEIGHT); game.fps = 60; game.preload(IMAGES.getAll ()); game.onload = function () { //--> Adicionar os handlers de eventos. bindEventKeys = function () { game.keybind(65, "kLeft"); game.keybind(68, "kRight"); game.keybind(87, "kUp"); game.keybind(83, "kDown"); game.keybind(85, "kA"); game.keybind(73, "kB"); game.keybind(81, "kC"); game.keybind(69, "kD"); game.keybind(13, "kPause"); //new TouchControl(); }; //--> Função para iniciar a pilha de levels. startLevels = function () { Panels.clearPanel(); bindEventKeys(); Layers.render(); GameStatus.refresh(); switch (currentLevel) { case 1: Levels.loadLevel_01(); break; } }; //--> Função para iniciar o game. main = function () { reset(); Util.getLocalIP(); Panels.mainPanel(); }; //--> Função para destruir toda a pilha de cenas. reset = function () { game.rootScene.on(enchant.Event.ENTER_FRAME, function () {}); var max = 1000; for (var name in Layers) { if (typeof(Layers[name]) == "object") { while (Layers[name].childNodes.length != undefined && Layers[name].childNodes.length > 0 && max-- > 0) { Layers[name].removeChild(Layers[name].childNodes[0]); game.rootScene.removeChild(Layers[name].childNodes[0]); Layers[name].childNodes[0] = null; Layers[name].childNodes.splice(0, 1); } Layers[name] = new Group(); } } }; //--> Inicio do game! main(); //--> Eventos do teclado. window.onkeyup = function (evt) { var keyCode = evt.keyCode; switch (keyCode) { default: if (evt.shiftKey) { console.log(evt, keyCode); } break; } }; }; $("#enchant-stage").css("left", ($("body").width() - $("#enchant-stage").width()) / 2 + "px"); game.start(); };<file_sep>var GUI = { puzzleConfig: {"dificulty" : 0, "sourceLanguage" : 0, "targetLanguage" : 0, "category" : 0}, addButton: function (buttonFrame, rect, action) { var delay = Math.floor(Math.random() * 30) + 60; var button = new Sprite(rect.width, rect.height); button.image = game.assets[RESOURCE.getPath("IMAGE", "button1.png")]; button.x = rect.x; button.y = rect.y; button.frame = buttonFrame; button.ontouchstart = function () { button.scale(0.95); }; button.ontouchend = function () { game.assets[RESOURCE.getPath("SOUND", "[click_button]")].play(); button.scale(1.05); (action != undefined) ? action() : undefined; }; button.tl.scaleTo(1.05,1.05,delay).scaleTo(0.98,0.98,delay - 20).scaleTo(1.02,1.02,delay - 10).scaleTo(1,1,delay - 30).delay(delay / 2).loop(); game.rootScene.addChild(button); return button; }, addImage: function (resource, rect) { var sprite = new Sprite(rect.width, rect.height); sprite.image = game.assets[resource]; sprite.x = rect.x; sprite.y = rect.y; game.rootScene.addChild(sprite); return sprite; }, addText: function (text, rect) { var label = new Label(text); label.x = rect.x; label.y = rect.y; label.width = rect.width; label.height = rect.height; game.rootScene.addChild(label); return label; }, addList: function (items, rect) { var label = GUI.addText(items[0], new Rect(rect.x + 30, rect.y + 11, rect.width, rect.height - 20)); var buttonBack = GUI.addButton(11, new Rect(rect.x, rect.y, 40, 40), function () {label.back();}); var buttonForward = GUI.addButton(3, new Rect(rect.x + rect.width + 20, rect.y, 40, 40), function () {label.next();}); label.back = function () { if (this.selectedIndex == 0) this.selectedIndex = this.items.length - 1; else this.selectedIndex--; this.text = this.items[this.selectedIndex]; }; label.next = function () { if (this.selectedIndex == this.items.length - 1) this.selectedIndex = 0; else this.selectedIndex++; this.text = this.items[this.selectedIndex]; }; label.select = function (index) { this.selectedIndex = index; this.text = this.items[this.selectedIndex]; }; label.font = "bold 14px Arial"; label.textAlign = "center"; label.items = items; label.backgroundColor = "#bbd"; label.color = "black"; label.selectedIndex = 0; return {"buttonBack": buttonBack, "buttonForward" : buttonForward, "label" : label}; }, addArc: function (color, circle) { var sprite = new Sprite(circle.width, circle.height); sprite.x = circle.centerX; sprite.y = circle.centerY; sprite.circle = circle; sprite.color = color; sprite.redraw = function (startAngle, endAngle) { var surface = new Surface(sprite.circle.width, sprite.circle.height); startAngle = (startAngle == undefined) ? 0 : startAngle; endAngle = (endAngle == undefined) ? Math.PI * 2 : endAngle; surface.context.fillStyle = sprite.color; surface.context.beginPath(); surface.context.moveTo(sprite.circle.ray, sprite.circle.ray); surface.context.arc(sprite.circle.ray, sprite.circle.ray, sprite.circle.ray, startAngle, endAngle, true); surface.context.closePath(); surface.context.fill(); sprite.image = surface; }; sprite.redraw(); game.rootScene.addChild(sprite); return sprite; }, onExitPuzzle: function () { GUI.onMain(); }, onRestartPuzzle: function () { GUI.onStartPuzzle(); }, onBeforeStartPuzzle: function () { gameStatus = GAME_STATUS.PAUSED; var bg = new Background(new Rect(0, 0, game.width, game.height), "#000", 0.65); var bgStrip = new Background(new Rect(0, -80, game.width, 80), "#eee"); var imageStrip = GUI.addImage(RESOURCE.getPath("IMAGE", "striped1"), new Rect(0, 320, game.width, 20)); var labelStart = GUI.addText("Vamos começar?! ;)", new Rect(50, 270, 200, 30)); var buttonStart = GUI.addButton(5, new Rect(400, 300, 40, 40), function () { game.rootScene.removeChild(imageStrip); game.rootScene.removeChild(buttonStart); game.rootScene.removeChild(labelStart); bgStrip.tl.moveTo(bgStrip.x, -bgStrip.height, 6).then(function () { //--> Iniciando o Puzzle!! game.rootScene.removeChild(bg); gameStatus = GAME_STATUS.PLAYING; game.assets[RESOURCE.getPath("SOUND", "[start]")].play(); }); }); labelStart.color = "#2980b9"; labelStart.textAlign = "center"; labelStart.font = "bold 20px Arial, Sans-Serif, Helvetica"; buttonStart.visible = false; labelStart.visible = false; imageStrip.visible = false; bgStrip.tl.delay(10).moveTo(bgStrip.x, 240, 5).then(function () { imageStrip.visible = true; buttonStart.visible = true; labelStart.visible = true; }); }, onFinishPuzzle: function (isWinner) { gameStatus = GAME_STATUS.FINISH_ROUND; var score = Puzzle.getScore(); var roundTime = ROUND_TIME[DIFICULTIES[GUI.puzzleConfig.dificulty].value]; var bg = new Background(new Rect(0, 0, game.width, game.height), "#000", 0.65); var bgStats = new Background(new Rect(100, -250, game.width - 200, 320), "#eee"); var bgBorderStats = new Background(new Rect(103, 184, game.width - 206, 283), "#dde"); var buttonRestart = GUI.addButton(4, new Rect(280, 410,40,40), function () {GUI.onRestartPuzzle();}); var buttonExit = GUI.addButton(14, new Rect(320, 410,40,40), function () {GUI.onExitPuzzle();}); var labelResult = GUI.addText("", new Rect(103, 153, game.width - 206, 28)); var labelHits = GUI.addText("Palavras encontradas: " + Puzzle.scopeTable.hits + " / " + Puzzle.scopeTable.totalWords, new Rect(-300, 190, game.width - 240, 30)); var labelTimer = GUI.addText("Tempo restante: " + (roundTime - Puzzle.currentTime), new Rect(game.width, 215, game.width - 240, 30)); var labelScore = GUI.addText("Pontuação: " + "0000".concat(score).slice(-4), new Rect(-300, 240, game.width - 240, 30)); var labelHighScore = GUI.addText("Novo recorde! " + "0000".concat(score).slice(-4), new Rect(110, 420, 150, 30)); if (isWinner) { game.assets[RESOURCE.getPath("SOUND", "[win]")].play(); labelResult.text = "Parabéns!!! :D"; labelResult.backgroundColor = "#1abc9c"; } else { game.assets[RESOURCE.getPath("SOUND", "[loss]")].play(); labelResult.text = "Aaah seu tempo acabou.. :("; labelResult.backgroundColor = "#cb4335"; } labelResult.textAlign = "center"; labelResult.font = "bold 20px Arial"; labelHits.textAlign = "center"; labelHits.font = "16px Arial"; labelTimer.textAlign = "center"; labelTimer.font = "16px Arial"; labelScore.textAlign = "center"; labelScore.font = "16px Arial"; labelHighScore.textAlign = "left"; labelHighScore.font = "18px Arial"; labelHighScore.color = "#f00"; bgBorderStats.visible = false; buttonRestart.visible = false; buttonExit.visible = false; labelHits.visible = false; labelTimer.visible = false; labelScore.visible = false; labelResult.visible = false; labelHighScore.visible = false; bgStats.tl.moveTo(100, 150, 7).then(function () { labelHits.moveTo(-300, labelHits.y); labelTimer.moveTo(game.width, labelTimer.y); labelScore.moveTo(-300, labelScore.y); bgBorderStats.visible = true; buttonRestart.visible = true; buttonExit.visible = true; labelHits.visible = true; labelTimer.visible = true; labelScore.visible = true; labelResult.visible = true; labelHits.tl.delay(80).then(function () {game.assets[RESOURCE.getPath("SOUND", "[stats]")].play();}).moveTo(120, labelHits.y, 5); labelTimer.tl.delay(110).then(function () {game.assets[RESOURCE.getPath("SOUND", "[stats]")].play();}).moveTo(120, labelTimer.y, 5); labelScore.tl.delay(140).then(function () {game.assets[RESOURCE.getPath("SOUND", "[stats]")].play();}).moveTo(120, labelScore.y, 5); bgStats.tl.delay(175).then(function () { //--> Jogador alcançou o seu recorde! if (score >= playerStats.highScore) { game.assets[RESOURCE.getPath("SOUND", "[record_reached]")].play(); playerStats.highScore = score; playerStats.time = roundTime - Puzzle.currentTime; playerStats.category = GUI.puzzleConfig.category; labelHighScore.tl.then(function () {labelHighScore.color = "#0f0";}).delay(20).then(function () {labelHighScore.color = "#f00";}).delay(20).loop(); labelHighScore.visible = true; updatePlayerStats(); }; }); }); }, onStartPuzzle: function () { gameStatus = GAME_STATUS.PAUSED; GUI.clear(); Puzzle.init(); var roundTime = ROUND_TIME[DIFICULTIES[GUI.puzzleConfig.dificulty].value]; var zeroAngle = -Math.PI / 2; var timerConstAngle = Math.PI * 2 / roundTime; var buttonRestart = GUI.addButton(4, new Rect(game.width - 45,50,40,40), function () {if (gameStatus == GAME_STATUS.PLAYING) GUI.onRestartPuzzle();}); var buttonExit = GUI.addButton(14, new Rect(game.width - 45,90,40,40), function () {if (gameStatus == GAME_STATUS.PLAYING) GUI.onExitPuzzle();}); var bgTimer = GUI.addArc(BG_TIMER_COLOR, new Circle(17, game.width - 45, 10)); var fgTimer = GUI.addArc(FG_TIMER_COLOR, new Circle(17, game.width - 45, 10)); var glossary = Puzzle.randGlossary(PUZZLE_CONTENT[GUI.puzzleConfig.category].words); var currentSecond = 0; fgTimer.onenterframe = function () { if ((gameStatus == GAME_STATUS.PLAYING) && (this.age % game.fps == 0)) { currentSecond++; Puzzle.currentTime = currentSecond; if (Puzzle.scopeTable.hits == Puzzle.scopeTable.totalWords) { GUI.onFinishPuzzle(true); fgTimer.onenterframe = undefined; } else { if (currentSecond < roundTime) { var timerAngle = timerConstAngle * currentSecond + zeroAngle; this.redraw(zeroAngle, timerAngle); bgTimer.tl.scaleTo(1.1,1.1,8).scaleTo(0.97,0.97,10).scaleTo(1.05,1.05,7).scaleTo(1,1,9); fgTimer.tl.scaleTo(1.1,1.1,8).scaleTo(0.97,0.97,10).scaleTo(1.05,1.05,7).scaleTo(1,1,9); if (roundTime - currentSecond <= 10 && Puzzle.scopeTable.hits != Puzzle.scopeTable.totalWords) { game.assets[RESOURCE.getPath("SOUND", "[stats]")].play(); } } else if (currentSecond == roundTime) { this.redraw(zeroAngle, timerAngle - 1); GUI.onFinishPuzzle(false); fgTimer.onenterframe = undefined; } } if (DEBUG) console.log("Round Timer: ", currentSecond); } }; MetadataService.translate(glossary, LANGUAGES[GUI.puzzleConfig.sourceLanguage].value, LANGUAGES[GUI.puzzleConfig.targetLanguage].value) .success(function (response) { Puzzle.start(response, LANGUAGES[GUI.puzzleConfig.sourceLanguage].value, LANGUAGES[GUI.puzzleConfig.targetLanguage].value, DIFICULTIES[GUI.puzzleConfig.dificulty].value); GUI.onBeforeStartPuzzle(); }).error(function (response) { setTimeout(GUI.onStartPuzzle, 3000); console.log("Tentando novamente..", response); }); }, onMain: function () { gameStatus = GAME_STATUS.MAIN_SCREEN; GUI.clear(); var bg = new Background(new Rect(0, 0, game.width, game.height), BACKGROUND_COLOR); var left = 260; var top = 420; var width = 110; var height = 40; var listSourceLanguage = GUI.addList(LANGUAGES.map(function (element) {return element.text;}), new Rect(left, top, width, height)); var listTargetLanguage = GUI.addList(LANGUAGES.map(function (element) {return element.text;}), new Rect(left, top + 40, width, height)); var listDificulty = GUI.addList(DIFICULTIES.map(function (element) {return element.text;}), new Rect(left, top + 80, width, height)); var listCategory = GUI.addList(PUZZLE_CONTENT.map(function (element) {return element.category;}), new Rect(left, top + 120, width, height)); var labelHighScore = GUI.addText("Recorde: " + "0000".concat(playerStats.highScore).slice(-4), new Rect(20, game.height - 40, 150, 30)); var buttonStart = GUI.addButton(1, new Rect(left + 130, top + 170, 40, height), function () { GUI.puzzleConfig.sourceLanguage = listSourceLanguage.label.selectedIndex; GUI.puzzleConfig.targetLanguage = listTargetLanguage.label.selectedIndex; GUI.puzzleConfig.dificulty = listDificulty.label.selectedIndex; GUI.puzzleConfig.category = listCategory.label.selectedIndex; GUI.onStartPuzzle(); }); listSourceLanguage.label.select(GUI.puzzleConfig.sourceLanguage); listTargetLanguage.label.select(GUI.puzzleConfig.targetLanguage); listDificulty.label.select(GUI.puzzleConfig.dificulty); listCategory.label.select(GUI.puzzleConfig.category); labelHighScore.font = "22px Arial"; labelHighScore.textAlign = "left"; labelHighScore.color = "#f00"; }, clear: function () { var attempts = game.rootScene.childNodes.length + 1; while (game.rootScene.childNodes.length > 0 && attempts-- > 0) { game.rootScene.removeChild(game.rootScene.childNodes[0]); } } };<file_sep>//--> Classe genérica para representar um NPC. var BaseNPC = enchant.Class.create (enchant.Sprite, { initialize: function (source) { enchant.Sprite.call(this, source.width, source.height); this.source = source; this.x = source.x; this.y = source.y; this.image = game.assets[this.source.image]; this.frame = source.frames.MOVE; this.armor = this.source.armor; this.speed = this.source.speed; this.id = counterId++; this.rateMaxCounter = this.source.rateMaxCounter; this.rateCounter = this.rateMaxCounter; this.damage = this.source.damage; this.shotConfig = this.source.shotConfig; this.isHighlightLocked = false; Layers.enemies.addChild(this); }, destroy: function () { Layers.enemies.removeChild(this) + game.rootScene.removeChild(this); }, onenterframe: function () { this.moveBy(0, this.speed); for (var i in Layers.navys.childNodes) { var navy = Layers.navys.childNodes[i]; if (this.intersect(navy)) { return navy.applyDamage(this.armor) + this.destroy(); } } if (background.y + this.y > game.height) { return this.destroy(); } if (this.rateCounter == this.rateMaxCounter) { $(this.shotConfig).each(function (index, config) { new EnemyShot(config); }); this.rateCounter = 0; } //--> Contadores this.rateCounter = (this.rateCounter > this.rateMaxCounter) ? this.rateMaxCounter : this.rateCounter + 1; }, move: function (x, y) { this.moveTo(x, y); }, highlight: function () { if (!this.isHighlightLocked) { this.isHighlightLocked = true; var _this = this; this.tl .fadeTo(0.6, parseInt(0.6 * DEFAULT.HIGHLIGHT_ENEMY_DURATION)) .fadeTo(1, parseInt(0.4 * DEFAULT.HIGHLIGHT_ENEMY_DURATION)) .then(function () { _this.isHighlightLocked = false; }); } }, applyDamage: function (damage) { this.armor -= damage; this.highlight(); if (this.armor <= 0) { return this.destroy(); } } });<file_sep>const VIEWPORT = { WIDTH: 680, HEIGHT: 800, DIAGONAL: Math.sqrt(680 * 680 + 800 * 800) }; const BACKGROUND_SPEED = 2; const DEFAULT = { SHOT_SPEED: 28, SHOT_ENEMY_SPEED: 18, SHOT_ENEMY_SPEED_SLOW: 6, SHOT_ENEMY_SPEED_MEDIUM: 10, SHOT_ENEMY_SPEED_FAST: 18, HIGHLIGHT_ENEMY_DURATION: 6 }; const IMAGES = { TEST: "images/chara2.png", LION_SHOT: "images/lion_shot.png", LION: "images/lion.png", LION_SPECIAL: "images/lion_shotspec.png", FLASH_SHOT: "images/flash_shot.png", FLASH: "images/flash.png", FLASH_SPECIAL: "images/flash_shotspec.png", SPACIAL_DEJECT_01: "images/dejetoespacial_01.png", BACKGROUND_LEVEL_01: "images/background_level_01.png", PLANET_01: "images/planeta_01.gif", BOSS_01: "images/chara2.png", BOSS_01_SHOT_02: "images/boss1_atk3.png", TOUCH_MOVE_PAD: "images/apad.png", RED: "images/red.png", BLUE: "images/blue.png", GREEN: "images/green.png", NPC_01: "images/npc1.png", SHOT_NPC_01: "images/npc1_shot.png", NPC_02: "images/npc2.png", SHOT_NPC_02: "images/npc2_shot.png", NPC_03: "images/npc2.png", NPC_04: "images/npc2.png", SHOT_NPC_04: "images/npc2_shot.png", getAll: function () { var arr = []; for (var i in this) { if (typeof(this[i]) == "string") { arr.push(this[i]); } } return arr; } }; const URL = { }; var TASK_I = 0; const TASK = { NAVY: { CREATE: ++TASK_I, MOVE: ++TASK_I, SHOT: ++TASK_I, JUMP: ++TASK_I, DASH: ++TASK_I, SHOT_CONFIG: ++TASK_I, DESTROY: ++TASK_I, TYPE: ++TASK_I, SET_FRAME: ++TASK_I }, SHOT: { DESTROY: ++TASK_I }, BACKGROUND: { MOVE: ++TASK_I }, CHANNEL: { OPENED: ++TASK_I, CLOSED: ++TASK_I }, DESTRUCTIBLE: { CREATE: ++TASK_I, DESTROY: ++TASK_I, MOVE: ++TASK_I, DAMAGE: ++TASK_I }, STACKED_LAYER: { CREATE: ++TASK_I, MOVE: ++TASK_I } }; const ANIM_FRAMES = { NAVY: { LEFT: [0, 1, 2], RIGHT: [0, 1, 2], UP: [0, 1, 2], DOWN: [0, 1, 2], IDLE: [0, 1, 2], DASH_UP: [0, 1, 2], DASH_DOWN: [0, 1, 2], DASH_LEFT: [0, 1, 2], DASH_RIGHT: [0, 1, 2], SHOT: [3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5], FLASH_SPECIAL: [0, 1, 1, 2, 2, 2, 2, 2], LION_SPECIAL: [0,1,2,3,4,5,6,7,7,7,7,7,7] }, BOSS_01: { SHOT_02: [0,1,2,3,4,5,6,7,8,9] }, NPC_01: { MOVE: [0,1,2,3] }, NPC_02: { MOVE: [0,1,2,3,4,5,6,7,8,9] } }; const ITEM = { DESTRUCTIBLE: { BOX : {name: "BOX", label: "Box", width: 64, height: 64, image: IMAGES.TEST, armor: 20}, SPACIAL_DEJECT_01 : {name: "SPACIAL_DEJECT_01", label: "Dejeto espacial 1", class: "Destructible", width: 128, height: 128, image: IMAGES.SPACIAL_DEJECT_01, armor: 5}, }, ENEMY: { NPC_01 : {name: "NPC_01", label: "NPC 1", class: "NPC_01", width: 64, height: 64, image: IMAGES.NPC_01, armor: 10, frames: ANIM_FRAMES.NPC_01, damage: 2, rateMaxCounter: 40, shotImage: IMAGES.SHOT_NPC_01, speed: 1}, NPC_02 : {name: "NPC_02", label: "NPC 2", class: "NPC_02", width: 64, height: 64, image: IMAGES.NPC_02, armor: 16, frames: ANIM_FRAMES.NPC_02, damage: 1, rateMaxCounter: 50, shotImage: IMAGES.SHOT_NPC_02, speed: 2}, NPC_03 : {name: "NPC_03", label: "NPC 3", class: "NPC_03", width: 64, height: 64, image: IMAGES.NPC_03, armor: 5}, NPC_04 : {name: "NPC_04", label: "NPC 4", class: "NPC_04", width: 64, height: 64, image: IMAGES.NPC_04, armor: 5}, BOSS_01 : {name: "BOSS_01", label: "The scorpion", class: "Boss_01", width: 180, height: 120, armor: 300, speed: 3}, } } const GAME_MODE = { SINGLE_PLAYER: 1, MULTI_PLAYER_SERVER: 2, MULTI_PLAYER_CLIENT: 3 }; const FRAME_STATE = { IDLE: 0, STARTED: 0, RUNNING: 1, FINISHED: 2 }; <file_sep>const LETTER_WIDTH = { "NORMAL": 16, "BIG": 21 }; const LETTER_SPACE_TABLE_WIDTH = 32;//26; const LETTER_SPACE_SCOPE_WIDTH = 20; const TABLE_MARGIN = 10; const SCOPE_MARGIN = 20; const SCOPE_HEIGHT = 100; const FIRST_LETTER_INDEX = 33; const WORD_DIRECTIONS = [ {dRow: 0, dCol: 1, level: 1},//--> HORIZONTAL DA ESQUERDA PARA DIREITA. {dRow: 0, dCol: -1, level: 2},//--> HORIZONTAL DA DIREITA PARA ESQUERDA. {dRow: 1, dCol: 0, level: 1},//--> VERTICAL DE CIMA PARA BAIXO {dRow: -1, dCol: 0, level: 2},//--> VERTICAL DE BAIXO PARA CIMA. {dRow: 1, dCol: 1, level: 3},//--> DIAGONAL DE CIMA PARA BAIXO APONTANDO PARA DIREITA. {dRow: -1, dCol: 1, level: 3},//--> DIAGONAL DE BAIXO PARA CIMA APONTANDO PARA DIREITA. {dRow: 1, dCol: -1, level: 3},//--> DIAGONAL DE CIMA PARA BAIXO APONTANDO PARA ESQUERDA. {dRow: -1, dCol: -1, level: 3}//--> DIAGONAL DE BAIXO PARA CIMA APONTANDO PARA ESQUERDA. ]; const BACKGROUND_COLOR = "#dde"; const SELECTION_COLOR = "#ccf"; const SELECTED_COLOR = "#7b241c"; const UNSELECTED_COLOR = "transparent"; const BG_TIMER_COLOR = "#cb4335"; const FG_TIMER_COLOR = "#1abc9c"; const LANGUAGES = [ {"text" : "Português", "value" : "pt"}, {"text" : "Inglês", "value" : "en"}]; const DIFICULTIES = [ {"text" : "Fácil", "value" : 1}, {"text" : "Médio", "value" : 2}, {"text" : "Dificil", "value" : 3}]; const LETTERS = [ "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 GAME_STATUS = { PLAYING: 0, PAUSED: 1, MAIN_SCREEN: 2, FINISH_ROUND: 3 }; const ROUND_TIME = { "1": 120,//--> EASY "2": 100,//--> MEDIUM "3": 90//--> HARD }; const DEBUG = false; //----> Cores http://htmlcolorcodes.com/color-chart/flat-design-color-chart/ //----> Sons https://freesound.org/people/Kastenfrosch/packs/10069/ //----> Fundo playing https://www.youtube.com/watch?v=QdIYVXCfrQM (loop em 3:30) //----> Fundo main https://www.youtube.com/watch?v=jdqcB_lKS1A<file_sep> //--> Classe para representar a nave do jogador ativo. var Navy = enchant.Class.create (enchant.Sprite, { initialize: function (x, y) { this.sizes = { normal: {width: 64, height: 64}, special: {width: 64, height: 256} } enchant.Sprite.call(this, this.sizes.normal.width, this.sizes.normal.height); this.x = x; this.y = y; this.normalImage = game.assets[IMAGES.FLASH]; this.specialImage = game.assets[IMAGES.FLASH_SPECIAL]; this.animSpecial = ANIM_FRAMES.NAVY.FLASH_SPECIAL; this.image = this.normalImage; this.shotImage = game.assets[IMAGES.FLASH_SHOT]; this.frame = ANIM_FRAMES.NAVY.IDLE; this.rateMaxCounter = 5; this.rateCounter = this.rateMaxCounter; this.dashMaxCounter = 80; this.dashCounter = this.dashMaxCounter; this.jumpMaxCounter = 50; this.jumpCounter = this.jumpMaxCounter; this.specialMaxCounter = 100; this.specialCounter = this.specialMaxCounter; this.damage = 1; this.specialDamage = 10; this.speed = 5; this.frameCounter = 0; this.armor = 30; //--> É multiplicado pelo dano dos npc's para calcular o valor do ataque. Deve estar em porcento. this.shield = 1; this.specialShield = 0.1; this.shotConfig = [{ xRelation: this.width/4, yRelation: this.height/2, image: this.shotImage, damage: this.damage, speed: -DEFAULT.SHOT_SPEED, parent: this },{ xRelation: this.width * 3/4, yRelation: this.height/2, image: this.shotImage, damage: this.damage, speed: -DEFAULT.SHOT_SPEED, parent: this }]; Layers.navys.addChild(this); if (gameMode != GAME_MODE.SINGLE_PLAYER) { channel.send(JSON.stringify({task: TASK.NAVY.CREATE})); channel.send(JSON.stringify({task: TASK.NAVY.MOVE, x: this.x, y: this.y})); } }, updateShotConfig: function () { var _this = this; $(this.shotConfig).each(function (index, config) { config.image = _this.shotImage; }); }, frameAnim: function (frames) { var frameDelay = 2; if (this.frameCounter == frames.length * frameDelay - 1) { this.frame = frames[frames.length - 1]; } else { this.frame = SpriteMath.buildArray(frames, frameDelay); this.frameCounter++; } if (gameMode != GAME_MODE.SINGLE_PLAYER) { channel.send(JSON.stringify({task: TASK.NAVY.SET_FRAME, frame: this.frame})); } }, onenterframe: function () { var kLeft = game.input.kLeft; var kRight = game.input.kRight; var kUp = game.input.kUp; var kDown = game.input.kDown; var kA = game.input.kA; var kB = game.input.kB; var kC = game.input.kC; var kD = game.input.kD; var kPause = game.input.kPause; //--> Direcionais. // // //--> Esquerda ou direita. if (kLeft && !kRight) { this.moveBy((this.x - this.speed > 0) ? -this.speed : -this.x, 0); } else if (!kLeft && kRight) { this.moveBy((this.x + this.speed + this.width < game.width) ? this.speed : 0, 0); } //--> Baixo ou cima. if (kDown && !kUp) { this.moveBy(0, (this.y + this.speed + this.height < game.height) ? this.speed : 0); } else if (!kDown && kUp) { this.moveBy(0, (this.y - this.speed > 0) ? -this.speed : -this.y); } //--> Botões de comando. // // //--> Tiro básico. if (kA) { if (this.rateCounter == this.rateMaxCounter) { $(this.shotConfig).each(function (index, config) { new Shot(config); }); this.rateCounter = 0; if (gameMode != GAME_MODE.SINGLE_PLAYER) { channel.send(JSON.stringify({task: TASK.NAVY.SHOT})); } } } //--> Tiro especial. if (kB) { if (this.specialCounter == this.specialMaxCounter) { kC = false; kD = false; this.specialCounter = 0; } } //--> Acelerar: dash if (kC && !kD) { if (this.dashCounter == this.dashMaxCounter) { var dashSpeed = this.speed * 15; this.moveBy(0, (this.y - dashSpeed > 0) ? -dashSpeed : -this.y); if (gameMode != GAME_MODE.SINGLE_PLAYER) { channel.send(JSON.stringify({task: TASK.NAVY.MOVE, x: this.x, y: this.y})); } this.dashCounter = 0; } } //--> Jump. if (!kC && kD) { if (this.jumpCounter == this.jumpMaxCounter) { var originalSpeed = this.speed; this.speed *= 0.5; window.setTimeout(function (_this) { _this.speed = originalSpeed; }, 1000 * this.jumpMaxCounter / game.fps + 1, this); this.jumpCounter = 0; if (gameMode != GAME_MODE.SINGLE_PLAYER) { channel.send(JSON.stringify({task: TASK.NAVY.JUMP})); } } } //--> Verificar alterações dos objetos e enviar o contexto para jogadores. if (gameMode != GAME_MODE.SINGLE_PLAYER) { if (kLeft || kRight || kDown || kUp || kA || kB || kC || kD) { channel.send(JSON.stringify({task: TASK.NAVY.MOVE, x: this.x, y: this.y})); } } //--> Alterando sprites da nave. if ((kLeft || kRight || kDown || kUp || kA || kB || kC || kD) && (this.specialCounter > this.animSpecial.length)) { if (kA) { if (this.frame != ANIM_FRAMES.NAVY.SHOT) { this.frame = ANIM_FRAMES.NAVY.SHOT; } } else if (!(kC || kD)) { if (kLeft && !kRight) { this.frameAnim (ANIM_FRAMES.NAVY.LEFT); } else if (!kLeft && kRight) { this.frameAnim (ANIM_FRAMES.NAVY.RIGHT); } else { if (kUp && !kDown) { this.frame = ANIM_FRAMES.NAVY.UP; } else { this.frame = ANIM_FRAMES.NAVY.IDLE; } this.frameCounter = 0; if (gameMode != GAME_MODE.SINGLE_PLAYER) { channel.send(JSON.stringify({task: TASK.NAVY.SET_FRAME, frame: this.frame})); } } } else if (kC && !kD) { if (this.dashCounter == 0) { if (kLeft && !kRight) { this.frameAnim (ANIM_FRAMES.NAVY.DASH_LEFT); } else if (!kLeft && kRight) { this.frameAnim (ANIM_FRAMES.NAVY.DASH_RIGHT); } else { this.frame = ANIM_FRAMES.NAVY.DASH_UP; this.frameCounter = 0; if (gameMode != GAME_MODE.SINGLE_PLAYER) { channel.send(JSON.stringify({task: TASK.NAVY.SET_FRAME, frame: this.frame})); } } this.tl.delay(4).then(function () { this.frame = ANIM_FRAMES.NAVY.IDLE; if (gameMode != GAME_MODE.SINGLE_PLAYER) { channel.send(JSON.stringify({task: TASK.NAVY.SET_FRAME, frame: this.frame})); } }); } } else if (!kC && kD) { if (this.jumpCounter == 0) { if (kLeft && !kRight) { this.frameAnim (ANIM_FRAMES.NAVY.DASH_LEFT); } else if (!kLeft && kRight) { this.frameAnim (ANIM_FRAMES.NAVY.DASH_RIGHT); } else { this.frame = ANIM_FRAMES.NAVY.DASH_UP; this.frameCounter = 0; if (gameMode != GAME_MODE.SINGLE_PLAYER) { channel.send(JSON.stringify({task: TASK.NAVY.SET_FRAME, frame: this.frame})); } } this.tl.delay(4).then(function () { this.frame = ANIM_FRAMES.NAVY.IDLE; if (gameMode != GAME_MODE.SINGLE_PLAYER) { channel.send(JSON.stringify({task: TASK.NAVY.SET_FRAME, frame: this.frame})); } }); } } } else if (this.specialCounter < this.animSpecial.length) { this[this.special](); } else { this.frame = SpriteMath.buildArray(ANIM_FRAMES.NAVY.IDLE, 5); this.frameCounter = 0; if (gameMode != GAME_MODE.SINGLE_PLAYER) { channel.send(JSON.stringify({task: TASK.NAVY.SET_FRAME, frame: this.frame})); } } //--> Contadores. this.rateCounter = (this.rateCounter > this.rateMaxCounter) ? this.rateMaxCounter : this.rateCounter + 1; this.specialCounter = (this.specialCounter > this.specialMaxCounter) ? this.specialMaxCounter : this.specialCounter + 1; this.dashCounter = (this.dashCounter > this.dashMaxCounter) ? this.dashMaxCounter : this.dashCounter + 1; this.jumpCounter = (this.jumpCounter > this.jumpMaxCounter) ? this.jumpMaxCounter : this.jumpCounter + 1; }, specialFlash: function () { if (this.specialCounter == 0) { //--> Início do special. var yOffset = this.y - (this.sizes.special.height - this.height); this.image = this.specialImage; this.width = this.sizes.special.width; this.height = this.sizes.special.height; this.y = yOffset; this.frame = this.animSpecial; var speed = 300; var yOffset = (this.y - speed < 0) ? 0 : (this.y - speed); this.tl.moveBy(0, -yOffset, 6); this.tmpDamage = this.damage; this.damage = this.specialDamage; this.tmpShield = this.shield; this.shield = this.specialShield; } else if (this.specialCounter == this.animSpecial.length - 1) { //--> Fim do special. this.image = this.normalImage; this.frame = SpriteMath.buildArray(ANIM_FRAMES.NAVY.IDLE, 5); this.width = this.sizes.normal.width; this.height = this.sizes.normal.height; this.damage = this.tmpDamage; this.tmpDamage = undefined; this.shield = this.tmpShield; this.tmpShield = undefined; } }, specialLion: function () { if (this.specialCounter == 0) { //--> Início do special. var yOffset = this.y - (this.sizes.special.height - this.height); this.image = this.specialImage; this.width = this.sizes.special.width; this.height = this.sizes.special.height; this.y = yOffset; this.frame = this.animSpecial; this.tmpDamage = this.damage; this.damage = this.specialDamage; this.tmpShield = this.shield; this.shield = this.specialShield; } else if (this.specialCounter == this.animSpecial.length - 1) { //--> Fim do special. var yOffset = this.height; this.image = this.normalImage; this.frame = SpriteMath.buildArray(ANIM_FRAMES.NAVY.IDLE, 5); this.width = this.sizes.normal.width; this.height = this.sizes.normal.height; this.y += yOffset - this.height; this.damage = this.tmpDamage; this.tmpDamage = undefined; this.shield = this.tmpShield; this.tmpShield = undefined; } }, //--> Retorna o sprite da nave, de acordo com o indice enviado. getNavyImageByIndex: function (index) { if (index == 0) { return IMAGES.LION; } else if (index == 1) { return IMAGES.FLASH; } }, //--> Retorna o sprite do special da nave, de acordo com o indice enviado. getSpecialImageByIndex: function (index) { if (index == 0) { return IMAGES.LION_SPECIAL; } else if (index == 1) { return IMAGES.FLASH_SPECIAL; } }, //--> Retorna o frameset do special da nave, de acordo com o indice enviado. getSpecialFramesetByIndex: function (index) { if (index == 0) { return ANIM_FRAMES.NAVY.LION_SPECIAL; } else if (index == 1) { return ANIM_FRAMES.NAVY.FLASH_SPECIAL; } }, //--> Retorna o nome do special da nave, de acordo com o indice enviado. getSpecialNameByIndex: function (index) { if (index == 0) { return "specialLion"; } else if (index == 1) { return "specialFlash"; } }, applyDamage: function (damage) { this.armor -= parseInt(damage * this.shield); if (this.armor <= 0) { return this.destroy(); } }, destroy: function () { return Layers.navys.removeChild(this) + game.rootScene.removeChild(this) + main(); } });<file_sep> //--> Estrutura para armazenar os recursos de um level. var BackgroundSource = function (image, speed) { this.source = new Sprite(); this.source.image = game.assets[image]; this.height = this.source.image.height; this.x = 0; this.y = -this.height + game.height; this.width = game.width; this.speed = speed; this.destructibles = []; this.destructibles.name = "destructibles"; this.enemies = []; this.enemies.name = "enemies"; }; <file_sep> //--> Classe para representar a nave do jogador de outro contexto. No contexto atual, é atualizado como se fosse uma marionete. var PuppetNavy = enchant.Class.create (enchant.Sprite, { initialize: function () { enchant.Sprite.call(this, 128, 128); this.x = 0; this.y = 0; this.image = game.assets[IMAGES.FLASH]; this.shotImage = game.assets[IMAGES.FLASH_SHOT]; this.frame = 0; this.damage = 1; this.speed = 10; this.shotConfig = [{ xRelation: this.width/4, yRelation: this.height/2, image: this.shotImage, damage: this.damage, speed: -DEFAULT.SHOT_SPEED, navy: this },{ xRelation: this.width * 3/4, yRelation: this.height/2, image: this.shotImage, damage: this.damage, speed: -DEFAULT.SHOT_SPEED, navy: this }]; Layers.navys.addChild(this); }, updateShotConfig: function () { var _this = this; $(this.shotConfig).each(function (index, config) { config.image = _this.shotImage; }); }, move: function (x, y) { this.moveTo(x, y); }, shot: function () { $(this.shotConfig).each(function (index, config) { new Shot(config); }); }, dash: function () { }, jump: function () { }, setSpeed: function (speed) { this.speed = speed; }, setImage: function (image) { this.image = game.assets[image]; }, setFrame: function (frame) { this.frame = frame; }, setShotConfig: function (shotConfig) { this.shot = shotConfig; } }); <file_sep> //--> Classe para representar um canal de comunicação, onde se usa os WebSockets. var Channel = function (url) { this.ws = undefined; this.port = 8011; this.url = url; this.nMessagesReceived = 0; this.nMessagesSent = 0; Channel.prototype.initWebSocket = function() { this.ws = new WebSocket ("ws://".concat(this.url).concat(":").concat(this.port).concat("/")); this.ws.onopen = function () { console.log("Canal aberto."); this.send(JSON.stringify({task: TASK.CHANNEL.OPENED})); this.nMessagesReceived = 0; this.nMessagesSent = 0; }; this.ws.onerror = function (error) { console.error("Canal fechado por erro.", error); }; this.ws.onclose = function () { console.log("Canal fechado."); this.send(JSON.stringify({task: TASK.NAVY.DESTROY})); }; this.ws.onmessage = function (e) { channel.receive(e.data); }; }; Channel.prototype.receive = function (data) { var context = JSON.parse(data); if (context.task == TASK.CHANNEL.OPENED) { if (gameMode == GAME_MODE.MULTI_PLAYER_SERVER) { this.send(JSON.stringify({task: TASK.CHANNEL.OPENED})); } startLevels(); } else { MultiplayerContext.update(context); } this.nMessagesReceived++; }; Channel.prototype.send = function (data) { this.ws.send(data); this.nMessagesSent++; }; this.initWebSocket(); }; <file_sep> var Letter = enchant.Class.create(enchant.Group, { initialize: function (letter, rect, letterWidth) { enchant.Group.call(this); this.x = rect.x; this.y = rect.y; this.width = rect.width; this.height = rect.height; this.rect = rect; this.letter = letter; this.letterWidth = (letterWidth != undefined) ? letterWidth : LETTER_WIDTH.NORMAL; this.finded = false; this.belongs = []; this.addLabel(); this.addSprite(letter); }, getFrameIndex: function (letter) { var letterIndex = FIRST_LETTER_INDEX + LETTERS.indexOf(letter.toUpperCase()); return letterIndex; }, addLabel: function () { var label = new Label(); label.x = 0; label.y = 0; label.width = this.width; label.height = this.height; this.label = label; this.addChild(label); }, addSprite: function (letter) { var sprite = new Sprite(); if (this.letterWidth == LETTER_WIDTH.NORMAL) sprite.image = game.assets[RESOURCE.getPath("IMAGE", "font_normal")]; else if (this.letterWidth == LETTER_WIDTH.BIG) sprite.image = game.assets[RESOURCE.getPath("IMAGE", "font_big")]; sprite.x = this.width / 2 - this.letterWidth / 2 + 2; sprite.y = this.height / 2 - this.letterWidth / 2 + 2; sprite.width = this.letterWidth; sprite.height = this.letterWidth; sprite.frame = (typeof(letter) === "string") ? this.getFrameIndex(letter) : letter; this.sprite = sprite; this.addChild(sprite); }, select: function () { if (!this.finded) this.label.backgroundColor = SELECTION_COLOR; }, unselect: function () { if (!this.finded) this.label.backgroundColor = UNSELECTED_COLOR; }, isSelected: function () { return (this.label.backgroundColor === SELECTION_COLOR); }, setFinded: function () { this.finded = true; this.label.backgroundColor = SELECTED_COLOR; } });<file_sep>from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket import threading import socket URL_PORT = 8011 clients = [] class FlashLion(WebSocket): def handleMessage(self): for client in clients: if client != self: client.sendMessage(str(self.data)) def handleConnected(self): clients.append(self) def handleClose(self): clients.remove(self) def thHandle(): try: print ("FlashLion Server iniciado!") server = SimpleWebSocketServer(getIp(), URL_PORT, FlashLion) server.serveforever() except KeyboardInterrupt as e: print("FlashLion Server finalizado!") def getIp(): return socket.gethostbyname_ex(socket.gethostbyname(socket.gethostname()))[0] print ("Server IP:", getIp()) threading.Thread(target=thHandle(), name="Thread_FlashLion", args=()) <file_sep><?php require 'vendor/autoload.php'; use Stichoza\GoogleTranslate\TranslateClient; define("METADATA_SOURCE_GOOGLE", "https://www.google.com.br/search?sourceid=chrome&ie=UTF-8&q="); define("METADATA_SOURCE_WIKIPEDIA", "https://pt.wikipedia.org/wiki/"); define("PUZZLE_CONTENT_LANGUAGE", "pt"); if (isset($_GET["type"]) && isset($_GET["data"])) { $data = $_GET["data"]; $sourceLanguage = $_GET["sourceLanguage"]; $targetLanguage = $_GET["targetLanguage"]; switch ((int) $_GET["type"]) { case 0: $metadataService = new MetadataService(); $metadataService->search($data); $response = $metadataService->toUpperCase()->removeUnusefulTags() ->removeNumbers()->replaceAccents()->removeSpecialChars() ->toUpperCase()->groupSpaces()->removeQueryWords()->removeUnusefulNouns() ->removeLittleWords()->groupSpaces()->removeDuplicatedWords()->getContent(); $arr = MetadataService::translateAssoc($response, $sourceLanguage, $targetLanguage); echo json_encode($arr); break; case 1: $response = json_decode($data); if ($sourceLanguage != PUZZLE_CONTENT_LANGUAGE || $targetLanguage != PUZZLE_CONTENT_LANGUAGE) { $arr = MetadataService::translateAssoc($response, $sourceLanguage, $targetLanguage); } else { $arr = MetadataService::assoc($response, $response, $sourceLanguage, $targetLanguage); } echo json_encode($arr); break; } } class MetadataService { private $content = null; private $queryString = null; public function search ($queryString) { $streamOptions = array("http"=> array("method"=>"GET")); $context = stream_context_create($streamOptions); $this->content = file_get_contents(METADATA_SOURCE_GOOGLE . http_build_query(array($queryString)), false, $context, 0, 10000000); //$this->content = file_get_contents(METADATA_SOURCE_WIKIPEDIA . $queryString, false, $context, 0, 10000000); $this->content = utf8_encode($this->content); $this->queryString = strtoupper($queryString); return $this; } public function getContent () { return trim($this->content); } public function removeUnusefulTags () { $this->content = preg_replace("/<HEAD>.*<\/HEAD>/", "", $this->content); $this->content = preg_replace("/<STYLE>.*<\/STYLE>/", "", $this->content); $this->content = preg_replace("/<A.*<\/A>/", "", $this->content); $this->content = preg_replace("/<SCRIPT.*<\/SCRIPT>/", "", $this->content); $this->content = preg_replace("/<TABLE.*<\/TABLE>/", "", $this->content); $this->content = preg_replace("/\&NBSP/", " ", $this->content); $this->content = preg_replace("/(DOCTYPE|<DOCTYPE>|<HTML>|<\/HTML>|<BODY>|<\/BODY>|<DIV>|<\/DIV>|<SPAN>|<\/SPAN>|<B>|<\/B>|<BR>|<\/BR>|<UL>|<\/UL>|<OL>|<\/OL>|<LI>|<\/LI>)/", " ", $this->content); $this->content = preg_replace("/(<DIV[^>]*>|<H[^>]*>|<META[^>]*>|<BODY[^>]*>|<SPAN[^>]*>|<HTML[^>]*>|<OL[^>]*>|<LI[^>]*>)/", "", $this->content); return $this; } public function removeNumbers () { $this->content = preg_replace("/[0-9]/", " ", $this->content); return $this; } public function removeSpecialChars () { $this->content = preg_replace("/[\-\+\/\(\)\=\%\&\*\!\"\'\$\#\@\º\ª\,\.\;\:\>\<\n\r]/", " ", $this->content); return $this; } public function groupSpaces () { $this->content = preg_replace("/[ ]+/", " ", $this->content); return $this; } public function replaceAccents () { $accents = array( "Á|À|Ã|Â|Ä|á|à|ã|â|ä" => "A", "É|Ê|È|Ë|é|ê|è|ë" => "E", "Í|Î|í|î" => "I", "Ó|Õ|Ô|Ö|Ò|ó|õ|ô|ö|ò" => "O", "Ú|Û|Ü|ú|û|ü" => "U", "Ç|ç" => "C"); $content = $this->content; foreach ($accents as $oldChar => $newChar) { $content = preg_replace("/$oldChar/i", "$newChar", $content); } $this->content = $content; return $this; } public function toUpperCase () { $this->content = strtoupper($this->content); return $this; } public function removeLittleWords () { $content = ""; $words = explode(" ", $this->content); foreach ($words as $word) { if (strlen($word) >= 5) { $content = $content . " " . $word; } } $this->content = $content; return $this; } public function removeQueryWords () { $words = explode(" ", $this->queryString); foreach ($words as $word) { $this->content = preg_replace("/($word)/i", "", $this->content); } return $this; } public function removeUnusefulNouns () { $nouns = array("LONGE","PERTO","EU","TU","ELE","NOS","VOS","ELES","ELAS","VOCES","VOCE"," MEU","MINHA","MEUS","MINHAS","TEU","TUA","TEUS","TUAS","NOSSO","NOSSA","NOSSOS","NOSSAS","VOSSO","VOSSA","VOSSOS","VOSSAS","SEU","SUA"," SEUS","SUAS","ESTE","ESTA","ESTES","ESTAS","ISTO","ESSE","ESSA","ESSES","ESSAS","ISSO","QUAL","QUAIS","CUJO","CUJA","CUJOS","CUJAS","QUE","QUEM","ONDE","ALGUM","ALGUMA"," ALGUNS","ALGUMAS","NENHUM","NENHUMA","NENHUNS","NENHUMAS","TODO","TODA","TODOS","TODAS","OUTRO","OUTRA","OUTROS","OUTRAS","MUITO","MUITA","MUITOS","MUITAS","POUCO"," POUCA","POUCOS","POUCAS","CERTO","CERTA","CERTOS","CERTAS","TAMPOUCO","VARIOS","NOENTANTO","ENTANTO","ENQUANTO","VARIAS","TANTO","TANTA","TANTOS","TANTAS","QUANTO","QUANTA","QUANTOS","QUANTAS","QUALQUER","QUAISQUER","TAL","TAIS","UM","UMA","UNS","UMAS","ALGUEM"," ALGO","NINGUEM","TUDO","OUTREM","NADA","CADA","A","ANTE","PERANTE","APOS","ATE","COM","CONTRA","DESDE","ENTRE","PARA","SEM","SOB","SOBRE","TRAS"," ATRAS","DENTRO","PARACOM","AONDE","PREPOSICAO","PRONOMES","MAIS","MENOS","MENOR","MAIOR","IGUAL","EQUIVALENTE","DELE","DELES","DELAS","DESTE","DESTES","DESTA","DESTAS","DESSE"," DESSES","DESSA","DESSAS","DAQUELE","DAQUELES","DAQUELA","DAQUELAS","DISTO","DISSO","DAQUILO","DAQUI","DAI","DALI","DOUTRO","DOUTROS","DOUTRA","DOUTRAS"," NESTE","NESTES","NESTA","NESTAS","OBSTANTE","NESSE","NESSES","NAQUELE","NAQUELES","NAQUELANAQUELAS","NISTO","NISSO","NAQUILO","AQUELE","AQUELES","AQUELA"," AQUELAS","AQUILO","A","AO","AOS","AS","DE","DO","DOS","DA","DAS","DUM","DUNS","DUMA","DUMAS","EM","NO","NOS","NA","NAS","NUM","NUNS","NUMA","NUMAS","POR","PER"," PELO","PELOS","PELA","PELAS","PONTO","SERA","NUNCA","SEMPRE","ASVEZES","VEZES","CERCA","SAIBA","CLIQUE", "OUTRO","AINDA", "DEU", "DANDO", "DENTRE", "DENTRO", "TAMBEM", "ZEROHORA", "CIRCA"); foreach ($nouns as $noun) { $this->content = preg_replace("/( $noun )/i", " ", $this->content); } return $this; } public function removeDuplicatedWords () { $this->content = implode(" ", array_unique(explode(" ", $this->content))); return $this; } public static function translate ($content, $source = "pt", $target = "en") { $tr = new TranslateClient(); return $tr->setSource($source)->setTarget($target)->translate($content); } public static function translateAssoc ($sourceContent, $source = "pt", $target = "en") { $tr = new TranslateClient(); $tr->setSource(PUZZLE_CONTENT_LANGUAGE);//--> O PUZZLE_CONTENT estará sempre em português. $tr->setTarget(($target == PUZZLE_CONTENT_LANGUAGE && $source != PUZZLE_CONTENT_LANGUAGE) ? $source : $target); $translationContent = implode("; ", $sourceContent); $translationContent = strtolower($translationContent); $translationContent = ucwords($translationContent); $translationContent = $tr->translate($translationContent); $translationContent = strtoupper($translationContent); $targetContent = explode("; ", $translationContent); return MetadataService::assoc($sourceContent, $targetContent, $source, $target); } public static function assoc ($sourceContent, $targetContent, $source = "pt", $target = "en") { $arr = array(); for ($i = 0; $i < sizeof($sourceContent); $i++) { $targetContent[$i] = preg_replace("/(\-)/i", " ", $targetContent[$i]); if ($target == PUZZLE_CONTENT_LANGUAGE && $source != PUZZLE_CONTENT_LANGUAGE) { $arr[]= array($source => $targetContent[$i], $target => $sourceContent[$i]); } else { $arr[]= array($source => $sourceContent[$i], $target => $targetContent[$i]); } } return $arr; } } ?><file_sep>var SpriteMath = { //--> Função que recebe um número e retorna um array com esse número N vezes. repeatNumber: function (val, n) { var arr = [val]; for (var i = 1; i < n; i++) { arr.push(val); } return arr; }, //--> Função que retorna um array com os elementos de baseArray N vezes. //--> Ex: buildArray([0, 1], 3) => [0,0,0,1,1,1] buildArray: function (baseArray, n) { var arr = []; for (var i in baseArray) { for (var j = 0; j < n; j++) { arr.push(baseArray[i]); } } return arr; }, //--> Função que recebe valores para min, max e um valor de incremento. //--> Retorna um array com valores min até max. //--> Ex: incrToArray(3, 5) => [3, 4, 5] incrToArray: function (min, max, incr) { incr = incr || 1; var arr = []; for (var i = min; i <= max; i += incr) { arr.push(i); } return arr; }, };<file_sep>//--> Classe para representar um inimigo estilo torre fixa, //--> pode ser um tanque, uma torre, ou qualquer coisa fixada no solo. //--> (Não há colisão com as naves). var NPC_04 = enchant.Class.create (enchant.Sprite, { initialize: function (x, y, source) { enchant.Sprite.call(this, source.width, source.height); this.source = source; this.x = x; this.y = y; this.direction = (this.x < 100) ? 1 : -1; this.image = game.assets[this.source.image]; this.shotImage = game.assets[IMAGES.SHOT_NPC_04]; this.frame = 0; this.armor = this.source.armor; this.id = counterId++; this.rateMaxCounter = 60; this.rateCounter = this.rateMaxCounter; this.delayBetweenShots = 10; this.damage = 1; this.shotConfig = [{ xRelation: this.width / 2, yRelation: this.height / 2, image: this.shotImage, damage: this.damage, xSpeed: 0, ySpeed: 0, rotateAngle: 20, parent: this },{ xRelation: this.width / 2, yRelation: this.height / 2, image: this.shotImage, damage: this.damage, xSpeed: 0, ySpeed: 0, delayed: 7, rotateAngle: 20, parent: this },{ xRelation: this.width / 2, yRelation: this.height / 2, image: this.shotImage, damage: this.damage, xSpeed: 0, ySpeed: 0, delayed: 14, rotateAngle: 20, parent: this }]; Layers.enemies.addChild(this); }, destroy: function () { Layers.enemies.removeChild(this) + game.rootScene.removeChild(this); }, onenterframe: function () { if (background.y + this.y > game.height) { return this.destroy(); } if (this.rateCounter == this.rateMaxCounter) { var pos = {x: this.x, y: this.y + background.y}; $(this.shotConfig).each(function (index, config) { var nearestNavy = Plain.nearestOf(pos, Layers.navys.childNodes).element; config.xSpeed = (nearestNavy.x - pos.x) / (4 * DEFAULT.SHOT_ENEMY_SPEED_FAST); config.ySpeed = (nearestNavy.y - pos.y) / (4 * DEFAULT.SHOT_ENEMY_SPEED_FAST); new EnemyShot(config); }); this.rateCounter = 0; } //--> Contadores this.rateCounter = (this.rateCounter > this.rateMaxCounter) ? this.rateMaxCounter : this.rateCounter + 1; }, move: function (x, y) { this.moveTo(x, y); }, applyDamage: function (damage) { this.armor -= damage; if (this.armor <= 0) { return this.destroy(); } } });<file_sep>var Rect = function (x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; }; var RectCell = function (row, col, rowSize, colSize) { this.row = row; this.col = col; this.rowSize = rowSize; this.colSize = colSize; this.x = this.col * this.colSize; this.y = this.row * this.rowSize; this.width = this.colSize; this.height = this.rowSize; }; var Circle = function (ray, centerX, centerY) { this.ray = ray; this.centerX = centerX; this.centerY = centerY; this.width = ray * 2; this.height = ray * 2; this.x = centerX - ray; this.y = centerY - ray; };<file_sep>const PIECE_TYPE = { "L":0, "S":1, "I":2, "T":3, "Q":4, "Z":5, "length":6, random: function(){ return ["L","S","I","T","Q","Z"][Math.floor(Math.random()*this.length)]; } }; const PIECE_BLOCK = { "L": [{x: 0, y: 0}, {x: 1, y: 0}, {x: 2, y: 0}, {x: 0, y: 1}], "S": [{x: 0, y: 0}, {x: -1, y: 1}, {x: 0, y: 1}, {x: 1, y: 0}], "I": [{x: 0, y: 0}, {x: 1, y: 0}, {x: 2, y: 0}, {x: 3, y: 0}], "T": [{x: 0, y: 0}, {x: -1, y: 0}, {x: 0, y: 1}, {x: 1, y: 0}], "Q": [{x: 0, y: 0}, {x: 1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}], "Z": [{x: 0, y: 0}, {x: -1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}] }; const PIECE_ROTATION = { "L": [ [{x: 1, y: 0}, {x: 2, y: 0}, {x: 0, y: 1}], [{x: 0, y: 1}, {x: 0, y: 2}, {x: -1, y: 0}], [{x: -1, y: 0}, {x: -2, y: 0}, {x: 0, y: -1}], [{x: 0, y: -1}, {x: 0, y: -2}, {x: 1, y: 0}] ], "S": [ [{x: -1, y: 1}, {x: 0, y: 1}, {x: 1, y: 0}], [{x: 0, y: -1}, {x: 1, y: 1}, {x: 1, y: 0}] ], "I": [ [{x: 1, y: 0}, {x: 2, y: 0}, {x: 3, y: 0}], [{x: 0, y: 1}, {x: 0, y: 2}, {x: 0, y: -1}] ], "T": [ [{x: -1, y: 0}, {x: 0, y: 1}, {x: 1, y: 0}], [{x: 0, y: -1}, {x: -1, y: 0}, {x: 0, y: 1}], [{x: 1, y: 0}, {x: 0, y: -1}, {x: -1, y: 0}], [{x: 0, y: 1}, {x: 1, y: 0}, {x: 0, y: -1}] ], "Z": [ [{x: -1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}], [{x: 0, y: -1}, {x: -1, y: 1}, {x: -1, y: 0}] ], "Q": [] }; var Piece = function(x,y,color,type){ this.x = x; this.y = y; this.color = color || "#fff"; this.type = type; this.isFixed = false; this.rotation = 0; this.blocks = []; Piece.prototype.moveDown = function(){ this.y += BW; for(var i in this.blocks){ this.blocks[i].moveBy(0,BW); } }; Piece.prototype.moveX = function(dx){ this.x += dx * BW; for(var i in this.blocks){ this.blocks[i].moveBy(dx*BW,0); } }; Piece.prototype.rotate = function(){ this.rotation = (this.rotation + 1 == PIECE_ROTATION[this.type].length) ? 0 : this.rotation + 1; var rotations = PIECE_ROTATION[this.type][this.rotation]; if(rotations != undefined){ var pivot = this.blocks[0]; for(var i=0;i<rotations.length;i++){ this.blocks[i+1].moveTo(pivot.x + rotations[i].x * BW, pivot.y + rotations[i].y * BW); } } }; Piece.prototype.createBlocks = function(){ var blocks = PIECE_BLOCK[this.type]; for(var i in blocks){ this.blocks.push(new Block(this.x + blocks[i].x * BW, this.y + blocks[i].y * BW)); } }; Piece.prototype.getBounds = function(){ var bounds = {"x": W, "y": H, "x2": 0, "y2": 0}; for(var i in this.blocks){ bounds.x = Math.min(bounds.x, this.blocks[i].x); bounds.y = Math.min(bounds.y, this.blocks[i].y); bounds.x2 = Math.max(bounds.x2, this.blocks[i].x2); bounds.y2 = Math.max(bounds.y2, this.blocks[i].y2); } return bounds; }; this.createBlocks(); }; <file_sep>var Item = enchant.Class.create(enchant.Sprite, { initialize: function (direction, y, attr) { enchant.Sprite.call(this, 50, 50); this.image = game.assets[RESOURCE.getPath("IMAGE", attr.IMAGE)]; this.x = (direction > 0) ? -this.width : game.width + this.width; this.y = y; this.frame = attr.FRAME; this.attr = attr; this.sprite = this; game.rootScene.addChild(this); this.moveDirection(direction); }, moveDirection: function (direction) { var self = this; var delay = 160; var exitPoint = (direction > 0) ? -this.width : game.width + this.width; this.tl .moveBy(game.width * 0.30 * direction, 0, delay + 20) .moveBy(-self.width * 0.20 * direction, -self.height * 0.20 * direction, delay + 30) .moveBy(self.width * 0.35 * direction, self.height * 0.20 * direction, delay + 30) .moveTo(exitPoint, self.height * 0.20, delay + 20) .scaleTo(0,0,8).then(function () { if (DEBUG) console.log("Perdeu o item"); game.rootScene.removeChild(self); GUI.currentDropItem = undefined; }) }, activate: function (navy) { if (DEBUG) console.log("Ativando item") var self = this; this.tl.clear().scaleTo(0,0,8).then(function () { self[self.attr.ACTION](navy); GUI.labelScore.update(self.attr.SCORE); game.rootScene.removeChild(self); GUI.currentDropItem = undefined; }); }, increaseLifeNavy: function (navy) { navy.increaseLife(this.attr.VALUE); }, increaseDamageNavy: function (navy) { navy.increaseDamage(this.attr.VALUE); }, decreaseRateNavy: function (navy) { navy.decreaseRate(this.attr.VALUE); }, });<file_sep>var Table = enchant.Class.create(enchant.Group, { initialize: function (rect) { enchant.Group.call(this); this.x = rect.x; this.y = rect.y; this.width = rect.width; this.height = rect.height; this.amountRows = Math.floor(this.height / LETTER_SPACE_TABLE_WIDTH); this.heightRows = this.height / this.amountRows; this.amountCols = Math.floor(this.width / LETTER_SPACE_TABLE_WIDTH); this.widthCols = this.width / this.amountCols; this.letters = []; this.selectedWord = []; this.lastSelection = undefined; this.addSelection(); this.words = []; this.level = 1; this.language = "pt"; game.rootScene.addChild(this); }, addLetter: function (letterChar, row, col, word) { var rectCell = new RectCell(row, col, this.heightRows, this.widthCols); var letter = new Letter(letterChar, rectCell, LETTER_WIDTH.BIG); this.letters.push(letter); letter.belongs.push(word); this.addChild(letter); }, getLevelWordDirections: function () { var directions = []; for (var i in WORD_DIRECTIONS) { if (WORD_DIRECTIONS[i].level <= this.level) { directions.push(WORD_DIRECTIONS[i]); } } return directions; }, addWord: function (word) { var maxAttempts = 100; var randRow, randCol, randDir, placedLetter; var outHorizontalBound, outVerticalBound, interceptLetter, sameInterceptLetters; var directions = this.getLevelWordDirections(); var letters = word.split(""); var wordLength = word.length; while (maxAttempts-- > 0) { randRow = Math.floor(Math.random() * this.amountRows); randCol = Math.floor(Math.random() * this.amountCols); randDir = directions[Math.floor(Math.random() * directions.length)]; //--> Verificando condições onde a palavra ficará fora do tabuleiro. outHorizontalBound = (randCol + wordLength > this.amountCols && randDir.dCol == 1) || (randCol - wordLength < 0 && randDir.dCol == -1); outVerticalBound = (randRow + wordLength > this.amountRows && randDir.dRow == 1) || (randRow - wordLength < 0 && randDir.dRow == -1); if (!outHorizontalBound && !outVerticalBound) { //--> Verificando condições onde alguma letra da palavra irá interceptar alguma outra letra do tabuleiro. //--> Permitir caso seja a mesma letra. interceptLetter = false; sameInterceptLetters = []; for (var i in letters) { placedLetter = this.getLetterAt(randRow + i * randDir.dRow, randCol + i * randDir.dCol); if (placedLetter != undefined) { if (placedLetter.letter != letters[i]) { //--> Buscar outra posição. interceptLetter = true; break; } else { //--> Mesma letra na interseção (Atualizar o array belongs da letra). sameInterceptLetters.push({index: i, letter: letters[i]}); if (placedLetter.belongs.indexOf(word) === -1) { placedLetter.belongs.push(word); } } } } if (!interceptLetter) { //--> A inserção da palavra no tabuleiro está validada. this.words.push(word); for (var i in letters) { var sameInterceptionIndex = sameInterceptLetters.filter(function (e) { return e.letter == letters[i] && e.index == i; }); if (sameInterceptionIndex.length == 0) { this.addLetter(letters[i], randRow + i * randDir.dRow, randCol + i * randDir.dCol, word); } } break; } } } }, addGlossary: function (words) { for (var i in words) { this.addWord(words[i][this.language]); } }, fillTable: function () { for (var row = 0; row < this.amountRows; row++) { for (var col = 0; col < this.amountCols; col++) { if (this.getLetterAt(row, col) == undefined) { var randLetter = LETTERS[Math.floor(Math.random() * LETTERS.length)]; this.addLetter(randLetter, row, col); } } } }, addSelection: function () { var currentSelecion = new Label(); currentSelecion.x = 0; currentSelecion.y = 0; currentSelecion.row = -1; currentSelecion.col = -1; currentSelecion.width = currentSelecion.height = 3; currentSelecion.backgroundColor = UNSELECTED_COLOR; this.currentSelecion = currentSelecion; this.addChild(currentSelecion); }, setCurrentSelection: function (e, row, col) { this.currentSelecion.x = e.x - TABLE_MARGIN; this.currentSelecion.y = e.y - 2 * SCOPE_MARGIN - SCOPE_HEIGHT; this.currentSelecion.row = row; this.currentSelecion.col = col; }, clearSelection: function () { for (var i in this.letters) { this.letters[i].unselect(); } }, getLetterAt: function (row, col) { for (var i in this.letters) { if (this.letters[i].rect.row == row && this.letters[i].rect.col == col) { return this.letters[i]; } } }, getIndexWordAt: function (row, col) { for (var i in this.selectedWord) { var letter = this.selectedWord[i]; if (letter.rect.row == row && letter.rect.col == col) return i; } return -1; }, getSelectedWord: function () { var word = ""; for (var i in this.selectedWord) { word += this.selectedWord[i].letter; } return word; }, getSelectedLetters: function () { return this.selectedWord; }, setFindedWord: function () { if (DEBUG) console.log(this.getSelectedWord()); var letters = this.getSelectedLetters(); var lettersLength = letters.length; var findedCounter = 0; for (var i in this.words) { var word = this.words[i]; if (word.length === lettersLength) { findedCounter = 0; for (var j = 0; j < lettersLength; j++) { if (letters[j].belongs.indexOf(word) > -1) { findedCounter++; } else { break; } } if (findedCounter == lettersLength) { for (var j in this.selectedWord) { if (!this.selectedWord[j].finded) { this.selectedWord[j].setFinded(); } } this.scopeTable.setFindedWord(word, this.language); game.assets[RESOURCE.getPath("SOUND", "[word_found]")].play(); return true; } } } game.assets[RESOURCE.getPath("SOUND", "[invalid_selection]")].play(); return false; }, ontouchstart: function (e) { this.clearSelection(); if (gameStatus == GAME_STATUS.PLAYING) { for (var i in this.letters) { var letter = this.letters[i]; this.setCurrentSelection(e, letter.rect.row, letter.rect.col); if (letter.sprite.intersect(this.currentSelecion)) { letter.select(); this.selectedWord.push(letter); this.lastSelection = {letter: letter.letter, row: letter.rect.row, col: letter.rect.col}; } } } }, ontouchmove: function (e) { if (gameStatus == GAME_STATUS.PLAYING) { for (var i in this.letters) { var letter = this.letters[i]; this.setCurrentSelection(e, letter.rect.row, letter.rect. col); if (letter.sprite.intersect(this.currentSelecion)) { if (this.lastSelection.row != this.currentSelecion.row || this.lastSelection.col != this.currentSelecion.col) { //--> Verificar se a letra está na palavra. if (this.selectedWord.length > 1) { var letterIndex = this.getIndexWordAt(this.currentSelecion.row, this.currentSelecion.col); if (letterIndex > -1) { for (var j = this.selectedWord.length - 1; j >= letterIndex; j--) { this.selectedWord[j].unselect(); this.selectedWord.splice(j, 1); } } } letter.select(); this.selectedWord.push(letter); this.lastSelection = {letter: letter.letter, row: letter.rect.row, col: letter.rect.col}; } } } } }, ontouchend: function (e) { if (gameStatus == GAME_STATUS.PLAYING) { this.setFindedWord(); } this.clearSelection(); this.selectedWord = []; } });<file_sep>enchant(); var game; var gameStatus = GAME_STATUS.MAIN_SCREEN; var playerStats = {highScore: 0, time: 0, category: 0}; loadPlayerStats = function () { if (localStorage.getItem("wordhunteren_player_stats") == undefined) { localStorage.setItem("wordhunteren_player_stats", JSON.stringify(playerStats)); } else { playerStats = JSON.parse(localStorage.getItem("wordhunteren_player_stats")); } }; updatePlayerStats = function () { localStorage.setItem("wordhunteren_player_stats", JSON.stringify(playerStats)); }; listCategories = function () { $(PUZZLE_CONTENT).each(function (index, element) {console.log((" " + element.category).slice(-12), "=> ", element.words.length);}); }; window.onload = function () { loadPlayerStats(); game = new Core(480, 640); game.fps = 60; game.preload(RESOURCE.getPath("IMAGE").concat(RESOURCE.getPath("SOUND"))); game.onload = function () { GUI.onMain(); }; game.start(); }; <file_sep> var NPC = enchant.Class.create(enchant.Group, { initialize: function (x, y, attr) { enchant.Group.call(this); this.x = (x != undefined) ? x : -100; this.y = (y != undefined) ? y : -100; this.width = 64; this.height = 64; this.attr = attr; this.life = attr.LIFE; this.shotSpeed = attr.SHOT_SPEED; this.rateTarget = attr.RATE + Math.floor(Math.random() * 20); this.rateCounter = this.rateTarget; this.isHidden = true; this.isDefeated = false; this.addSprite(); this.addLifeLabel(); game.rootScene.addChild(this); }, addSprite: function () { var sprite = new Sprite(this.width, this.height); sprite.image = game.assets[RESOURCE.getPath("IMAGE", this.attr.IMAGE)]; sprite.frame = 0; sprite.animCloseMouth = [0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3]; sprite.animDelay = 3 * sprite.animCloseMouth.length; sprite.idleDelay = Math.floor(Math.random() * 80) + 100; sprite.tl.delay(sprite.idleDelay).then(function () { this.frame = sprite.animCloseMouth; }).delay(sprite.animDelay).then(function () { this.frame = 0; }).loop(); this.sprite = sprite; this.addChild(sprite); return sprite; }, addBlastDamage: function () { var sprite = new Sprite(16, 16); sprite.image = game.assets[RESOURCE.getPath("IMAGE", "blast")]; sprite.x = this.x + (Math.random() * 20) + 8; sprite.y = this.y + (Math.random() * 20) + 8; sprite.frame = [ 0,0,0,0,0,0, 1,1,1,1,1,1, 2,2,2,2,2,2, 3,3,3,3,3,3,]; sprite.tl.moveBy(0, -10, 24).then(function () { game.rootScene.removeChild(sprite); }); game.rootScene.addChild(sprite); }, addLifeLabel: function () { this.bgLifeLabel = new Label(); this.bgLifeLabel.width = this.width * 0.8; this.bgLifeLabel.height = 3; this.bgLifeLabel.x = this.width * 0.1; this.bgLifeLabel.y = this.height - this.bgLifeLabel.height; this.bgLifeLabel.backgroundColor = NPC_LIFE.BGCOLOR; this.fgLifeLabel = new Label(); this.fgLifeLabel.width = this.width * 0.8; this.fgLifeLabel.height = 3; this.fgLifeLabel.x = this.width * 0.1; this.fgLifeLabel.y = this.height - this.fgLifeLabel.height; this.fgLifeLabel.backgroundColor = NPC_LIFE.FGCOLOR; this.addChild(this.bgLifeLabel); this.addChild(this.fgLifeLabel); }, onDamage: function (damage) { this.life -= damage; if (this.life <= 0) { var self = this; this.isDefeated = true; GUI.labelScore.update(this.attr.SCORE); GUI.enemiesDefeated++; this.fgLifeLabel.width = 0; this.tl.clear().scaleTo(0,0,8).then(function () { game.rootScene.removeChild(self); }); } else { this.fgLifeLabel.width = this.life * this.bgLifeLabel.width / this.attr.LIFE; this.addBlastDamage(); } }, addShot: function () { var damage = this.attr.DAMAGE; var sprite = new Sprite(10, 32); sprite.image = game.assets[RESOURCE.getPath("IMAGE", "npc_shot2")]; sprite.frame = 0; sprite.x = this.x + (this.width - sprite.width) / 2; sprite.y = this.y; sprite.shotSpeed = this.shotSpeed; sprite.onenterframe = function () { this.y += this.shotSpeed; $(game.rootScene.childNodes).each(function (index, element) { if (sprite.intersect(element.sprite)) { //--> Verificar colisões com Navy. if (element instanceof Navy && element.life > 0) { element.onDamage(damage); game.shotLayer.removeChild(sprite); } } }); if (sprite.y > game.height) { game.shotLayer.removeChild(sprite); } }; game.shotLayer.addChild(sprite); }, movePath: function (path, startDelay) { var self = this; var scaleX = game.width / 100; var scaleY = game.height / 100; var anim = "this.tl"; startDelay = (startDelay != undefined) ? startDelay : 1; this.isHidden = false; anim += ".delay(" + startDelay + ")"; for (var i in path) { anim += ".moveTo(" + path[i].x * scaleX + ", " + path[i].y * scaleY + ", " + path[i].time + ")"; } anim += ".then(function(){self.isHidden = true;})" eval(anim); }, onenterframe: function () { if (gameStatus == GAME_STATUS.PLAYING) { if (!this.isHidden && !this.isDefeated) { if (this.rateCounter > this.rateTarget) { this.addShot(); this.rateCounter = 0; } else { this.rateCounter++; } } } }, }); <file_sep>//--> Classe estendida de BaseNPC. Inimigo básico, anda e atira uma vez. var NPC_01 = enchant.Class.create (BaseNPC, { initialize: function (x, y, source) { source.x = x; source.y = y; var shotImage = game.assets[source.shotImage]; source.shotConfig = [{ xRelation: source.width / 2, yRelation: source.height / 2, image: shotImage, damage: source.damage, xSpeed: 0, ySpeed: DEFAULT.SHOT_ENEMY_SPEED, parent: this }]; BaseNPC.call(this, source); } });<file_sep>//--> Classe estática para definir os painéis que aparecem no jogo. var Panels = { //--> Função para limpar o painel ativo. clearPanel: function () { $("body #panel").remove(); }, //--> Painel de inicialização do game. mainPanel: function () { var panel = $("<div id='panel'><div class='back'></div><div class='front'></div></div>"); var front = panel.find(".front"); front.append("<ul></ul>"); front.find("ul").append("<li><button class='default' onclick='Panels.createServerPanel()'>Criar servidor</button></li>"); front.find("ul").append("<li><button class='default' onclick='Panels.connectServerPanel()'>Conectar servidor</button></li>"); front.find("ul").append("<li><button class='default' onclick='gameMode=GAME_MODE.SINGLE_PLAYER;Panels.chooseServerNavyPanel()'>Campanha</button></li>"); Panels.clearPanel(); panel.appendTo($("body")); gameMode = GAME_MODE.SINGLE_PLAYER; }, //--> Painel de inicialização da rede como servidor. createServerPanel: function () { var panel = $("<div id='panel'><div class='back'></div><div class='front'></div></div>"); var front = panel.find(".front"); front.append("<ul></ul>"); front.find("ul").append("<li><label>Nome do servidor:</label><input type='text' placeholder='teste' id='nome'/></li>"); front.find("ul").append("<li><label>Seu IP:</label><input type='text' placeholder='teste' value='"+ clientIP +"' disabled='true' /></li>"); front.find("ul").append("<li><button class='voltar' onclick='Panels.mainPanel()'>Voltar</button></li>"); front.find("ul").append("<li><button class='criar-servidor' onclick='MultiplayerContext.createServer()'>Concluir!</button></li>"); Panels.clearPanel(); panel.appendTo($("body")); }, //--> Painel de conexão na rede como cliente. connectServerPanel: function () { var panel = $("<div id='panel'><div class='back'></div><div class='front'></div></div>"); var front = panel.find(".front"); front.append("<ul></ul>"); front.find("ul").append("<li><label>IP do servidor:</label><input type='text' value='"+ clientIP +"' placeholder='teste' id='ip'/></li>"); front.find("ul").append("<li><label>Seu nome:</label><input type='text' placeholder='teste2' id='nome'/></li>"); front.find("ul").append("<li><label>Seu IP:</label><input type='text' placeholder='teste' value='"+ clientIP +"' disabled='true' /></li>"); front.find("ul").append("<li><button class='voltar' onclick='Panels.mainPanel()'>Voltar</button></li>"); front.find("ul").append("<li><button class='conectar-servidor' onclick='MultiplayerContext.connectServer()'>Conectar!</button></li>"); Panels.clearPanel(); panel.appendTo($("body")); }, //--> Painel de escolha da nave do server, ou player 1. chooseServerNavyPanel: function () { var panel = $("<div id='panel'><div class='back'></div><div class='front'></div></div>"); var front = panel.find(".front"); front.append("<ul></ul>"); front.find("ul").append("<li><label>Sua nave:</label></li>"); front.find("ul").append("<li><table cellpadding='10' cellspacing='10' class='navys' align='center'><tr></tr></table></li>"); front.find("ul table.navys tr").append("<td><img src='images/lion-entrance.gif' style='float: left;' onclick='chosenNavy=0;Panels.afterChosenNavy()' /></td>"); front.find("ul table.navys tr").append("<td><img src='images/flash-entrance.gif' style='float: right;' onclick='chosenNavy=1;Panels.afterChosenNavy()' /></td>"); Panels.clearPanel(); panel.appendTo($("body")); }, //--> Função para iniciar a campanha (single player) ou aguardar outros jogadores (multi player). afterChosenNavy: function () { if (gameMode == GAME_MODE.SINGLE_PLAYER) { startLevels (); } else if (gameMode == GAME_MODE.MULTI_PLAYER_SERVER) { Panels.waitingForClientPanel (); } }, //--> Painel para aguardar conexão do player 2. waitingForClientPanel: function () { var panel = $("<div id='panel'><div class='back'></div><div class='front'></div></div>"); var front = panel.find(".front"); front.append("<ul></ul>"); front.find("ul").append("<li><label style='display: block; text-align: center; width: 100%;'>Aguardando player 2</label></li>"); front.find("ul").append("<li><button class='voltar' onclick='Panels.mainPanel()'>Cancelar</button></li>"); Panels.clearPanel(); panel.appendTo($("body")); } };<file_sep>//--> Classe para representar um inimigo de tiro circular. var FixedCircleEnemy = enchant.Class.create (enchant.Sprite, { initialize: function (x, y, source) { enchant.Sprite.call(this, source.width, source.height); this.source = source; this.x = x; this.y = y; this.image = game.assets[this.source.image]; this.shotImage = game.assets[IMAGES.FLASH_SHOT]; this.frame = 0; this.armor = this.source.armor; this.id = counterId++; this.rateMaxCounter = 60; this.rateCounter = this.rateMaxCounter; this.damage = 1; this.shotConfig = EnemyShot.prototype.circleShotConfig(this, {from: 0, to: 360, step: 15}, DEFAULT.SHOT_ENEMY_SPEED_SLOW, {x: this.width / 2, y: this.height / 2}); Layers.enemies.addChild(this); }, destroy: function () { Layers.enemies.removeChild(this) + game.rootScene.removeChild(this); }, onenterframe: function () { if (background.y + this.y > game.height) { return this.destroy(); } if (this.rateCounter == this.rateMaxCounter) { $(this.shotConfig).each(function (index, config) { new EnemyShot(config); }); this.rateCounter = 0; } //--> Contadores this.rateCounter = (this.rateCounter > this.rateMaxCounter) ? this.rateMaxCounter : this.rateCounter + 1; }, move: function (x, y) { this.moveTo(x, y); }, applyDamage: function (damage) { this.armor -= damage; if (this.armor <= 0) { return this.destroy(); } } });<file_sep> var Car = function(x,y,color,carConfig){ this.x=x; this.y=y; this.color=color; this.carConfig = carConfig || CAR_CONFIG.CAR; this.width=0; this.height=0; this.speed = this.carConfig.SPEED; this.blocks=[]; this.destroyed = false; this.colorOld = this.color; this.colorToggled = false; this.destroyedAge = 0; Car.prototype.build=function(){ this.width = this.carConfig.W; this.height = this.carConfig.H; this.blocks = []; var color; for (var i = 0; i < this.height; i++){ for (var j = 0; j < this.width; j++){ if(this.carConfig.POS[i][j] != 0){ if (this.carConfig.POS[i][j] == 1 || (this.destroyed == true && this.colorToggled == true)) { color = this.color; } else if (this.carConfig.POS[i][j] > 1) { color = COLOR.getColor(this.carConfig.POS[i][j]); } this.blocks.push(new Block(this.x + j * BW, this.y + i * BW, color)); } } } }; Car.prototype.moveBy = function(dx,dy){ this.x += dx; this.y += dy; for(var i in this.blocks){ this.blocks[i].moveBy(dx, dy); } }; Car.prototype.scaleTo = function (scale) { this.blocks = []; for (var i = 0; i < this.height; i++){ for (var j = 0; j < this.width; j++){ if(this.carConfig.POS[i][j] != 0){ if (this.carConfig.POS[i][j] == 1) { color = this.color; } else if (this.carConfig.POS[i][j] > 1) { color = COLOR.getColor(this.carConfig.POS[i][j]); } this.blocks.push(new Block(this.x + j * BW * scale, this.y + i * BW * scale , color, BW * scale , BW * scale )); } } } }; Car.prototype.intersects = function (car2) { for (var i in this.blocks) { for (var j in car2.blocks) { if (this.blocks[i].rectInRect(car2.blocks[j])) { return true; } } } return false; }; Car.prototype.onCollision = function () { this.destroyed = true; this.speed = 1; this.toggleColor(); }; Car.prototype.toggleColor = function () { if (this.colorToggled) { this.colorOld = this.color; this.color = "transparent"; }else{ this.color = this.colorOld; } this.build(); this.colorToggled = !this.colorToggled; }; this.build(); };<file_sep>var storage = { items:function(){ return localStorage; }, init:function(){ var items = this.items(); if(items.length == 0){ localStorage["levelActual"] = 1; localStorage["levelMaxUnlocked"] = 1; localStorage["score"] = score_init; } if((__x=items["levelActual"]) != 1){ levelActual = (__x==undefined)?1:__x; }else{ levelActual = 1; } if((__x=items["levelMaxUnlocked"]) != 1){ levelMaxUnlocked = (__x==undefined)?1:__x; }else{ levelMaxUnlocked = 1; } if((__x=items["score"]) != 1){ score = (__x==undefined)?score_init:__x; } else { score = score_init; } }, save:function(a,b,c){ localStorage["levelActual"] = a; localStorage["levelMaxUnlocked"] = b; localStorage["score"] = c; }, clear:function(){ localStorage["levelActual"] = 1; localStorage["levelMaxUnlocked"] = 1; localStorage["score"] = score_init; } };<file_sep>//--> Classe estendida de BaseNPC. Anda e atira três vezes. var NPC_02 = enchant.Class.create (BaseNPC, { initialize: function (x, y, source) { source.x = x; source.y = y; var shotImage = game.assets[source.shotImage]; source.shotConfig = [{ xRelation: source.width / 2, yRelation: source.height / 2, image: shotImage, damage: source.damage, xSpeed: 0, ySpeed: DEFAULT.SHOT_ENEMY_SPEED, delayed: 1, parent: this },{ xRelation: source.width / 2, yRelation: source.height / 2, image: shotImage, damage: source.damage, xSpeed: 0, ySpeed: DEFAULT.SHOT_ENEMY_SPEED, delayed: 4, parent: this },{ xRelation: source.width / 2, yRelation: source.height / 2, image: shotImage, damage: source.damage, xSpeed: 0, ySpeed: DEFAULT.SHOT_ENEMY_SPEED, delayed: 7, parent: this }]; BaseNPC.call(this, source); } });<file_sep> window.onload=function(){ var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var loop, canRestart, score, jumpAvailables, age; var cars, currentCar, ties, jumping; var addCarCounter, addCarDelay, updateDifficulty, updateJumpAvailable; var raceSpeed, carsReachedCounter; var warningSignal; function start(){ cars = []; ties = []; score = 0; age = 0; canRestart = false; addCarCounter = 0; addCarDelay = 245; raceSpeed = 1; updateDifficulty = false; updateJumpAvailable = false; jumping = false; carsReachedCounter = 0; jumpAvailables = 2; warningSignal = new Signal(20,H-50,COLOR.YELLOW); currentCar = new Car((W - CAR_CONFIG.CAR.W * BW) / 2, H - (CAR_CONFIG.CAR.H + 5) * BW, COLOR.RED); currentCar.speed = PLAYER_SPEED; addTies(); loop=setInterval(update,FPS); } function update(){ if(addCarCounter++ > addCarDelay){ addCarCounter = 0; addCar(); } for (var i = 0; i < cars.length; i++) { if ((cars[i].y > H && cars[i].speed > 0) || (cars[i].y < 0 && cars[i].speed < 0)) { if (!cars[i].destroyed) { score += 10 * cars[i].height; carsReachedCounter++; updateDifficulty = true; updateJumpAvailable = true; } cars[i] = null; cars.splice(i, 1); i--; } else { cars[i].moveBy(0, raceSpeed * cars[i].speed); if (cars[i].destroyed && cars[i].destroyedAge++ % 5 == 0) cars[i].toggleColor(); } } for (var i = 0; i < ties.length; i++) { if (ties[i].y >= H) { ties[i].y = - H * 1 / 3; } else { ties[i].y += raceSpeed * 3; } } if (updateDifficulty == true && addCarDelay > ADD_CAR_DELAY_LIMIT && carsReachedCounter > 0 && carsReachedCounter % DIFFICULTY_PERIOD == 0){ addCarDelay -= ADD_CAR_DELAY_DECREASE; raceSpeed += RACE_SPEED_INCREASE; updateDifficulty = false; } if (updateJumpAvailable == true && carsReachedCounter > 0 && carsReachedCounter % ADD_JUMP_PERIOD == 0) { if (jumpAvailables < 99) { jumpAvailables++; } updateJumpAvailable = false; } if (warningSignal.counter > 0 && age % FPS == 0) { warningSignal.counter--; } draw(); checkCollisions(); age++; } function checkCollisions () { for (var i = 0; i < cars.length; i++) { if (jumping == false && cars[i].intersects(currentCar)){ currentCar.destroyed = true; cars[i].destroyed = true; clearInterval(loop); gameOver(); return false; } for (var j = 0; j < cars.length; j++) { if (i != j && cars[i].intersects(cars[j])) { cars[i].onCollision(); cars[j].onCollision(); continue; } } } return true; } function move(dx,dy){ if (canRestart == true) { return start(); } var x = currentCar.x + dx * currentCar.speed; var y = currentCar.y + dy * currentCar.speed; var px = dx * currentCar.speed; var py = dy * currentCar.speed; if (x < 0) { px = -currentCar.x; } else if (x + currentCar.width * BW > W) { px = W - (currentCar.x + currentCar.width * BW); } if (y < 0) { py = -currentCar.y; } else if (y + currentCar.height * BW > H) { py = H - (currentCar.y + currentCar.height * BW); } currentCar.moveBy(px, py); } function jump(){ if (canRestart == true) { return start(); } if (jumping == true|| jumpAvailables == 0 && canRestart == false) { return false; } var currentScale = 1; var done = 0; var raceSpeedOld = raceSpeed; var playerSpeedOld = currentCar.speed; var step = [ {from: 1, to: 1.2, duration: 2, counter: 0}, {from: 1.2, to: 1.28, duration: 3, counter: 0}, {from: 1.28, to: 1.35, duration: 4, counter: 0}, {from: 1.35, to: 1.35, duration: 4, counter: 0}, {from: 1.35, to: 1.28, duration: 3, counter: 0}, {from: 1.28, to: 1.2, duration: 3, counter: 0}, {from: 1.2, to: 1, duration: 2, counter: 0} ]; var thJump = setInterval(function () { done = 0; for(var i = 0; i < step.length; i++){ if (step[i].counter < step[i].duration) { step[i].counter++; currentScale += (step[i].to - step[i].from) / step[i].duration; currentCar.scaleTo(currentScale); currentCar.moveBy((step[i].to - step[i].from) * BW * -0.7, (step[i].to - step[i].from) * BW * -0.8); break; } else { done++; } } if (done == step.length) { raceSpeed = raceSpeedOld; currentCar.speed = playerSpeedOld; jumping = false; clearInterval(thJump); } }, 80); raceSpeed *= 0.7; currentCar.speed *= 0.4; jumpAvailables--; jumping = true; } function addCar(){ var randomConfig = CAR_CONFIG.random(); var randomX = 0; var n = Math.random(); var sectionWidth = W / 3; var y = -randomConfig.H * BW; if (currentCar.x <= sectionWidth) { randomX = sectionWidth * Math.floor((n < 0.6) ? 0 : n * 2);//0 ou 100 } else if (currentCar.x > sectionWidth && currentCar.x <= 2 * sectionWidth) { randomX = sectionWidth * Math.floor((n < 0.5) ? 1 : n * 3);//0, 100 ou 200 } else if (currentCar.x > 2 * sectionWidth) { randomX = sectionWidth + sectionWidth * Math.floor((n > 0.4) ? 1 : n * 2);//100 ou 200 } if (randomConfig.ID == 4) { y = 2 * H; warningSignal.counter = 5; warningSignal.x = randomX + (sectionWidth - warningSignal.blockWidth) / 2 ; } randomX += (sectionWidth - (randomConfig.W * BW)) / 2;//centralizando o carro na lacuna var car = new Car(randomX, y, COLOR.random(), randomConfig); cars.push(car); } function addTies(){ var tieLeft1 = new Tie(W / 3, - H * 1 / 3); var tieLeft2 = new Tie(W / 3, H * 0 / 3); var tieLeft3 = new Tie(W / 3, H * 1 / 3); var tieLeft4 = new Tie(W / 3, H * 2 / 3); var tieRight1 = new Tie(2 * W / 3, - H * 1 / 3); var tieRight2 = new Tie(2 * W / 3, H * 0 / 3); var tieRight3 = new Tie(2 * W / 3, H * 1 / 3); var tieRight4 = new Tie(2 * W / 3, H * 2 / 3); ties.push(tieLeft1, tieLeft2, tieLeft3, tieLeft4, tieRight1, tieRight2, tieRight3, tieRight4); } function draw(){ clear(); for (var i = 0; i < ties.length; i++) { ctx.fillStyle= COLOR.WHITE; ctx.fillRect(ties[i].x,ties[i].y,ties[i].width,ties[i].height); } for(var i=0;i<cars.length;i++){ for(var j in cars[i].blocks){ ctx.fillStyle=cars[i].blocks[j].color; ctx.fillRect(cars[i].blocks[j].x,cars[i].blocks[j].y,BW,BW); } } if(currentCar!=undefined){ for(var j in currentCar.blocks){ ctx.fillStyle= currentCar.blocks[j].color; ctx.fillRect(currentCar.blocks[j].x,currentCar.blocks[j].y, currentCar.blocks[j].width, currentCar.blocks[j].height); } } if (warningSignal.counter > 0) { for (var i =0; i < warningSignal.height; i++) { if (warningSignal.blocks[i] == 1) { ctx.fillStyle = warningSignal.color; ctx.fillRect(warningSignal.x, warningSignal.y + i * warningSignal.blockWidth, warningSignal.blockWidth, warningSignal.blockWidth); } } } ctx.font = "16px Monospaced"; ctx.fillStyle = COLOR.BLACK; ctx.fillText("Pontos: " + ("00000" + score).slice(-5) + " | Pulos: " + ("00" + jumpAvailables).slice(-2), 7, 21); ctx.fillStyle = COLOR.WHITE; ctx.fillText("Pontos: " + ("00000" + score).slice(-5) + " | Pulos: " + ("00" + jumpAvailables).slice(-2), 5, 19); ctx.fillStyle = COLOR.BLACK; ctx.fillText((raceSpeed * 60).toFixed(2)+ "mph", W - 88, H - 10); ctx.fillStyle = COLOR.GREEN; ctx.fillText((raceSpeed * 60).toFixed(2)+ "mph", W - 90, H - 12); } function addInputs(){ window.addEventListener("keydown",function(e){ if(e.keyCode==KEYS.LEFT) move(-1,0); if(e.keyCode==KEYS.UP) move(0,-1); if(e.keyCode==KEYS.RIGHT) move(1,0); if(e.keyCode==KEYS.DOWN) move(0,1); if(e.keyCode==KEYS.JUMP) jump(); }); } function gameOver(){ ctx.font="26px Serif"; ctx.fillStyle=COLOR.BLACK; ctx.fillText("GAME OVER", W/2-72, H/2-10); ctx.fillStyle=COLOR.WHITE; ctx.fillText("GAME OVER", W/2-70, H/2-8); setTimeout(function(){canRestart=true;},3000); } function clear(){ ctx.clearRect(0,0,W,H); ctx.fillStyle=COLOR.GREY; ctx.fillRect(0,0,W,H); } addInputs(); start(); }; <file_sep>var Background = enchant.Class.create(enchant.Label, { initialize: function (rect, color, opacity) { enchant.Label.call(this); this.x = rect.x; this.y = rect.y; this.width = rect.width; this.height = rect.height; this.backgroundColor = color; this.opacity = (opacity) ? opacity : 1; game.rootScene.addChild(this); } });<file_sep> //--> Classe estática para representar um contexto de informações das pontas das //--> instâncias de Channel. var MultiplayerContext = { //--> Atualizar o contexto com as informações que vieram do socket. update: function (context) { var puppetPlayer = Layers.navys.childNodes[1]; createPuppetNavy = function () { if (!puppetPlayer) { puppetPlayer = new PuppetNavy(); } }; switch (context.task) { case TASK.NAVY.CREATE: createPuppetNavy(); if (gameMode == GAME_MODE.MULTI_PLAYER_SERVER) { var inversedChosenNavy = (chosenNavy + 1) % 2; puppetPlayer.image = game.assets[Navy.prototype.getNavyImageByIndex(inversedChosenNavy)]; puppetPlayer.shotImage = game.assets[Shot.prototype.getNavyShotImageByIndex(inversedChosenNavy)]; puppetPlayer.updateShotConfig(); channel.send(JSON.stringify({task: TASK.NAVY.TYPE, value: chosenNavy})); } break; case TASK.NAVY.MOVE: createPuppetNavy(); puppetPlayer.move(context.x, context.y); break; case TASK.NAVY.SHOT: createPuppetNavy(); puppetPlayer.shot(); break; case TASK.NAVY.JUMP: createPuppetNavy(); puppetPlayer.jump(); break; case TASK.NAVY.DASH: createPuppetNavy(); puppetPlayer.dash(); break; case TASK.BACKGROUND.MOVE: background.move(context.x, context.y); break; case TASK.STACKED_LAYER.CREATE: background.stackLayer(Layers[context.name]); break; case TASK.STACKED_LAYER.MOVE: background.moveStackedLayer(context.name, context.x, context.y); break; case TASK.DESTRUCTIBLE.CREATE: new Destructible(context.x, context.y, context.item); break; case TASK.DESTRUCTIBLE.DESTROY: Layers.findById(Layers.destructibles,context.id).destroy(); break; case TASK.SHOT.DESTROY: Layers.findById(Layers.shots, context.id).destroy(); break; case TASK.DESTRUCTIBLE.DAMAGE: Layers.findById(Layers.destructibles, context.id).applyDamage(context.damage); break; case TASK.NAVY.TYPE: var inversedChosenNavy = (context.value + 1) % 2; navy.image = game.assets[Navy.prototype.getNavyImageByIndex(inversedChosenNavy)]; navy.shotImage = game.assets[Shot.prototype.getNavyShotImageByIndex(inversedChosenNavy)]; navy.updateShotConfig(); puppetPlayer.image = game.assets[Navy.prototype.getNavyImageByIndex(context.value)]; puppetPlayer.shotImage = game.assets[Shot.prototype.getNavyShotImageByIndex(context.value)]; puppetPlayer.updateShotConfig(); break; case TASK.NAVY.SET_FRAME: puppetPlayer.setFrame(context.frame); break; } }, //--> Criar um servidor e aguardar clientes. createServer: function () { var name = $("#nome").val(); serverIP = clientIP; channel = new Channel(serverIP); Panels.chooseServerNavyPanel(); gameMode = GAME_MODE.MULTI_PLAYER_SERVER; }, //--> Conectar ao servidor apontado. connectServer: function () { var ip = $("#ip").val(); serverIP = ip; channel = new Channel(serverIP); gameMode = GAME_MODE.MULTI_PLAYER_CLIENT; } };<file_sep>var MetadataService = { search: function (queryString, sourceLanguage, targetLanguage) { var request = $.ajax({ "type": "GET", "dataType": "json", "url": encodeURI("metadata_service.php?type=0&data=" + queryString + "&sourceLanguage=" + sourceLanguage + "&targetLanguage=" + targetLanguage), "async": true }); return request; }, translate: function (content, sourceLanguage, targetLanguage) { var request = $.ajax({ "type": "GET", "dataType": "json", "url": encodeURI("metadata_service.php?type=1&data=" + JSON.stringify(content) + "&sourceLanguage=" + sourceLanguage + "&targetLanguage=" + targetLanguage), "async": true }); return request; } };<file_sep>var ScopeTable = enchant.Class.create(enchant.Group, { initialize: function (rect) { enchant.Group.call(this); this.x = rect.x; this.y = rect.y; this.width = rect.width; this.height = rect.height; this.amountRows = Math.floor(this.height / LETTER_SPACE_SCOPE_WIDTH); this.heightRows = this.height / this.amountRows; this.amountCols = Math.floor(this.width / LETTER_SPACE_SCOPE_WIDTH); this.widthCols = this.width / this.amountCols; this.letters = []; this.words = []; this.hits = 0; this.totalWords = 0; this.language = "pt"; game.rootScene.addChild(this); }, addLetter: function (letterChar, row, col) { var rectCell = new RectCell(row, col, this.heightRows, this.widthCols); var letter = new Letter(letterChar, rectCell); this.letters.push(letter); this.addChild(letter); return letter; }, addWord: function (word) { var wordChosen = word[this.language]; var wordLength = wordChosen.length; for (var row = 0; row < this.amountRows; row++) { for (var col = 0; col < this.amountCols - wordLength; col++) { var hasIntersect = false; for (var k = 0; k < wordLength; k++) { if (this.getLetterAt(row, col + k) != undefined) { hasIntersect = true; break; } } if (!hasIntersect) { if (col > 0) { col++; } word["letters"] = []; for (var i in wordChosen) { var letter = this.addLetter(wordChosen[i], row, col + parseInt(i)); word["letters"].push(letter); } this.words.push(word); if (col + wordLength < this.amountCols) { this.addSeparator(row, col + wordLength); } return true; } } } }, addSeparator: function (row, col) { var rectCell = new RectCell(row, col, this.heightRows, this.widthCols); var letter = new Letter(10, rectCell); letter.sprite.tl.scaleTo(0.7, 0.7, 10); this.addChild(letter); }, addGlossary: function (words) { for (var i in words) { this.addWord(words[i]); this.totalWords++; } }, getLetterAt: function (row, col) { for (var i in this.letters) { if (this.letters[i].rect.row == row && this.letters[i].rect.col == col) { return this.letters[i]; } } }, setFindedWord: function (word, language) { for (var i in this.words) { if (word == this.words[i][language]) { var scopeWord = this.words[i]; for (var j in scopeWord.letters) { scopeWord.letters[j].setFinded(); } this.hits++; } } } });<file_sep>window.onload = function () { const VIEWPORT_DIMENSION = [ {W: 176, H: 220, SW: 11, DPI_MIN: 0.53, DPI_MAX: 0.60}, {W: 320, H: 400, SW: 20, DPI_MIN: 1.83, DPI_MAX: 1.90}, {W: 352, H: 440, SW: 22, DPI_MIN: 1.90, DPI_MAX: 1.97} ]; var colors = ["#f00","#0f0","#00f","#ff0","#f0f","#0ff"]; var Point = function(x,y,color){ this.x = x; this.y = y; this.color = color; }; var cnv = document.getElementById("canvas"); var ctx = cnv.getContext("2d"); var w = 0, h = 0, sw = 0; var snake = []; var fps = 20; var dx = 0, dy = 0; var moveDelayCounter = 0, moveDelayTarget = 30; var food = new Point(0,0,colors[0]); var loop; var canRestart = false; function start(){ scaleViewport(); console.log(w, h, sw); cnv.width = w; cnv.height = h; dx = dy = 0; snake=[new Point(w/2, h/2, colors[0])]; addFood(); loop=setInterval(update,fps); addInputs(); updateMoveDelay(); canRestart=false; } function update(){ clear(); for(var i=0;i<snake.length;i++){ ctx.fillStyle = snake[i].color; ctx.fillRect(snake[i].x, snake[i].y,sw,sw); } ctx.fillStyle = food.color; ctx.fillRect(food.x, food.y,sw,sw); ctx.fillStyle = "#fff"; ctx.fillText("Pontos:" + (snake.length-1), 2, 10); if(moveDelayCounter++ > moveDelayTarget){ moveDelayCounter=0; move(); eatFood(); if(hitSelf() || hitWall()){ gameOver(); clearInterval(loop); } } } function scaleViewport(){ var currentDpi = window.outerWidth / window.outerHeight; for (var i in VIEWPORT_DIMENSION) { if (currentDpi >= VIEWPORT_DIMENSION[i].DPI_MIN && currentDpi < VIEWPORT_DIMENSION[i].DPI_MAX) { w = VIEWPORT_DIMENSION[i].W; h = VIEWPORT_DIMENSION[i].H; sw = VIEWPORT_DIMENSION[i].SW; return true; } } return console.log("DPI não encontrado no array VIEWPORT_DIMENSION. Favor configurá-lo.") != undefined; } function addInputs(){ document.getElementById("up").addEventListener("click",function(e){changeDir(0,-1);}); document.getElementById("down").addEventListener("click",function(e){changeDir(0,1);}); document.getElementById("left").addEventListener("click",function(e){changeDir(-1,0);}); document.getElementById("right").addEventListener("click",function(e){changeDir(1,0);}); window.addEventListener("keyup",function(e){ if(e.keyCode==37) changeDir(-1,0); if(e.keyCode==38) changeDir(0,-1); if(e.keyCode==39) changeDir(1,0); if(e.keyCode==40) changeDir(0,1); }); } function changeDir(mx,my){ if(canRestart) return start(); if (dx != -mx) dx = mx; if (dy != -my) dy = my; } function addPiece(){ snake.push(new Point(snake[snake.length-1].x + dx * sw, snake[snake.length-1].y + dy * sw, food.color)); } function addFood(){ food.x = Math.floor(Math.random() * w / sw) * sw; food.y = Math.floor(Math.random() * h / sw) * sw; food.color = colors[Math.floor(Math.random() * colors.length)]; } function move(){ var newSnake = [], i = 0; for(i=1;i<snake.length;i++){ newSnake.push(new Point(snake[i].x, snake[i].y,snake[i-1].color)); } newSnake.push(new Point(snake[i-1].x + dx * sw, snake[i-1].y + dy * sw, snake[i-1].color)); snake = newSnake; } function eatFood(){ if(snake[snake.length-1].x == food.x && snake[snake.length-1].y == food.y){ addPiece(); addFood(); updateMoveDelay(); } } function updateMoveDelay(){ var length = snake.length; length = (length > 50) ? 50 : length; moveDelayTarget=Math.floor(30 - Math.floor(length / 5) * 2.5); moveDelayCounter = 0; } function hitSelf(){ var head = snake[snake.length-1]; for(var i=0;i<snake.length-1;i++){ if(snake[i].x == head.x && snake[i].y == head.y){ return true; } } return false; } function hitWall(){ var head = snake[snake.length-1]; return (head.x < 0 || head.x + sw > w || head.y < 0 || head.y + sw > h); } function gameOver(){ ctx.fillStyle="#fff"; ctx.font="Arial 25px"; ctx.fillText("GAME OVER", w/2-30, h/2-10); setTimeout(function(){canRestart=true;},3000); } function clear(){ ctx.clearRect(0,0,w,h); ctx.fillStyle="#000"; ctx.fillRect(0,0,w,h); } start(); }; <file_sep> var Block = function(x,y){ this.x = x; this.y = y; this.x2 = this.x + BW; this.y2 = this.y + BW; Block.prototype.moveBy = function(dx,dy){ this.x += dx; this.y += dy; this.x2 = this.x + BW; this.y2 = this.y + BW; }; Block.prototype.moveTo = function(dx,dy){ this.x = dx; this.y = dy; this.x2 = this.x + BW; this.y2 = this.y + BW; }; };<file_sep> //--> Classe estática para definir os recursos do jogo, objetos, inimigos.. //--> Possui uma função para cada level. Para chamar: Levels.loadLevel_01() var Levels = { loadLevel_01: function () { var source = new BackgroundSource(IMAGES.BACKGROUND_LEVEL_01, BACKGROUND_SPEED); //this.populate(source.destructibles, ITEM.DESTRUCTIBLE.SPACIAL_DEJECT_01, 40); //source.enemies.push({x: 250, y: 11000, item: ITEM.ENEMY.FIXED_STAR}); this.populate(source.enemies, ITEM.ENEMY.NPC_01, 100); this.populate(source.enemies, ITEM.ENEMY.NPC_02, 60); //var b = new Boss_01(); //b.start(); background = new Background(source); this.addNavy(); background.start(); }, populate: function (layer, item, n) { n = n || 1; for (var i = 0; i < n; i++) { var y = 1000 + Math.floor(Math.random() * 12000) + 1; layer.push({x: undefined, y: y, item: item}); } }, addNavy: function () { if (gameMode == GAME_MODE.MULTI_PLAYER_CLIENT) { navy = new Navy(game.width * 3 / 4, game.height - 100); } else { background.start(); background.stackLayer(Layers.destructibles); background.stackLayer(Layers.enemies); if (gameMode == GAME_MODE.SINGLE_PLAYER) { navy = new Navy(game.width * 1 / 2, game.height - 100); } else { navy = new Navy(game.width * 1 / 4, game.height - 100); } navy.normalImage = game.assets[Navy.prototype.getNavyImageByIndex(chosenNavy)]; navy.specialImage = game.assets[Navy.prototype.getSpecialImageByIndex(chosenNavy)]; navy.animSpecial = Navy.prototype.getSpecialFramesetByIndex(chosenNavy); navy.special = Navy.prototype.getSpecialNameByIndex(chosenNavy); navy.image = navy.normalImage; navy.shotImage = game.assets[Shot.prototype.getNavyShotImageByIndex(chosenNavy)]; navy.updateShotConfig(); } } };<file_sep>//--> Classe para representar o chefão da fase 1: Um escorpião. var Boss_01 = enchant.Class.create (enchant.Sprite, { initialize: function () { enchant.Sprite.call(this, ITEM.ENEMY.BOSS_01.width, ITEM.ENEMY.BOSS_01.height); this.image = game.assets[IMAGES.BOSS_01]; var img = game.assets[IMAGES.LION_SHOT]; this.shotImage = { shot01: img, shot04: img }; this.damage = { shot01: 2, shot04: 10 }; this.x = (game.width - ITEM.ENEMY.BOSS_01.width) / 2; this.y = -ITEM.ENEMY.BOSS_01.height; this.frame = 0; this.maxArmor = ITEM.ENEMY.BOSS_01.armor; this.armor = this.maxArmor; this.speed = ITEM.ENEMY.BOSS_01.speed; this.statesBeforeAnger = []; this.statesAfterAnger = []; this.environmentPivot = {x: (VIEWPORT.WIDTH - this.width) / 2, y: 65}; this.id = counterId++; this.isHighlightLocked = false; Layers.bosses.addChild(this); }, destroy: function () { return Layers.destructibles.removeChild(this) + game.rootScene.removeChild(this) + main(); }, start: function () { var entranceDuration = 40; var _this = this; this.tl .moveTo(this.environmentPivot.x, this.environmentPivot.y, entranceDuration) .then(function () { _this.idleState(); }); }, idleState: function () { var xDelay = 22; //var xDelay = 12; //var yDelay = 9; var yDelay = 19; var xPadding = 90; var yPadding = 50; var right = game.width - this.width - xPadding; var top = this.environmentPivot.y; var _this = this; this.tl .moveTo(xPadding, top, xDelay) .moveBy(0, yPadding, yDelay).then(function (){_this.shot01()}) .moveTo(right, top, xDelay) .moveBy(0, yPadding, yDelay).then(function (){_this.shot01()}) .moveTo(xPadding, top, xDelay) .moveBy(0, yPadding, yDelay).then(function (){_this.shot01()}) .moveTo(right, top, xDelay) .moveBy(0, yPadding, yDelay).then(function (){_this.shot01()}) .moveTo(xPadding, top, xDelay) .moveBy(0, yPadding, yDelay).then(function (){_this.shot01()}) .moveTo(right, top, xDelay) .moveBy(0, yPadding, yDelay).then(function (){_this.shot01()}) .moveTo((game.width - this.width) / 2, this.y - yPadding, xDelay).then(function () { _this.shot02(); }); }, shot01: function () { console.log("tiro pra frente com as garras, alternando esq e dir"); var xRelation = this.width / 2; var yRelation = this.height / 2; //--> Equalizando diferença entre as layers bosses e shots. xRelation -= background.x; yRelation -= background.y; $([{ xRelation: xRelation, yRelation: yRelation, image: this.shotImage.shot01, damage: this.damage.shot01, rotateAngle: 15, xSpeed: -3, ySpeed: DEFAULT.SHOT_ENEMY_SPEED_FAST, parent: this },{ xRelation: xRelation, yRelation: yRelation, image: this.shotImage.shot01, damage: this.damage.shot01, rotateAngle: 15, xSpeed: 0, ySpeed: DEFAULT.SHOT_ENEMY_SPEED_FAST, parent: this },{ xRelation: xRelation, yRelation: yRelation, image: this.shotImage.shot01, damage: this.damage.shot01, rotateAngle: 15, xSpeed: 3, ySpeed: DEFAULT.SHOT_ENEMY_SPEED_FAST, parent: this }]).each(function (index, config) { new EnemyShot(config); }); }, shot02: function () { console.log("sai da tela andando pra trás, aparece só a ponta da cauda e dispara um tirão."); var goingYDelay = 35; var waitingDelay = 16; var movingXDelay = 22; var xPadding = 90; var rightBoss = VIEWPORT.WIDTH - this.width - xPadding; var wShot = 80; var hShot = VIEWPORT.HEIGHT; var rightShot = VIEWPORT.WIDTH - wShot - xPadding; var _this = this; this.tl .moveTo(this.environmentPivot.x, -this.height, goingYDelay) .moveBy(0, -1, waitingDelay) .moveBy(0, this.height * 0.3, goingYDelay * 0.7) .then(function () { var bigShot = new Sprite(wShot, hShot); bigShot.image = game.assets[IMAGES.BOSS_01_SHOT_02]; bigShot.frame = ANIM_FRAMES.BOSS_01.SHOT_02; bigShot.onenterframe = function () { if (this.age >= ANIM_FRAMES.BOSS_01.SHOT_02.length) { this.frame = ANIM_FRAMES.BOSS_01.SHOT_02[ANIM_FRAMES.BOSS_01.SHOT_02.length - 1]; } }; bigShot.opacity = 0; var parent = new Group(); parent.width = _this.width; parent.x = (VIEWPORT.WIDTH - _this.width) / 2; parent.y = _this.y; Layers.bosses.addChild(parent); _this.x = (parent.width - _this.width) / 2; _this.y = 0; bigShot.x = (parent.width - bigShot.width) / 2; bigShot.y = _this.y + _this.height; parent.addChild(_this); parent.addChild(bigShot); bigShot.tl.fadeIn(5); parent.tl .delay(5) .moveTo(xPadding, parent.y, movingXDelay) .moveTo(rightBoss, parent.y, movingXDelay) .moveTo(xPadding, parent.y, movingXDelay) .moveTo(rightBoss, parent.y, movingXDelay) .moveTo(xPadding, parent.y, movingXDelay) .moveTo(rightBoss, parent.y, movingXDelay) .moveTo(_this.environmentPivot.x, parent.y, movingXDelay) .then(function () { bigShot.tl.fadeOut(5); }) .delay(5) .moveTo(_this.environmentPivot.x, _this.environmentPivot.y, movingXDelay * 0.4) .then(function () { Layers.bosses.addChild(_this); _this.moveTo(_this.environmentPivot.x, _this.environmentPivot.y); Layers.bosses.removeChild(parent); game.rootScene.removeChild(parent); //--> Verificar HP para escolher próximo ataque. if (_this.armor < _this.maxArmor * 0.40) { if (Math.random() * 100 > 70) { _this.shot04(); } else { _this.idleState(); } } else if (_this.armor < _this.maxArmor * 0.70) { if (Math.random() * 100 > 70) { _this.shot02(); } else { _this.idleState(); } } else { _this.idleState(); } }); }); }, shot03: function () { console.log("dropa minas destrutíveis na tela"); }, shot04: function () { console.log("Bate as garras, disparando tiros em várias direções."); var _this = this; var shotConfig = EnemyShot.prototype.circleShotConfig(this, {from: 0, to: 360, step: 15}, DEFAULT.SHOT_ENEMY_SPEED_SLOW, {x: this.width / 2, y: this.height / 2}); $(shotConfig).each(function (index, config) { config.damage = _this.damage.shot04; new EnemyShot(config); }); }, highlight: function () { if (!this.isHighlightLocked) { this.isHighlightLocked = true; var _this = this; this.tl .fadeTo(0.6, parseInt(0.6 * DEFAULT.HIGHLIGHT_ENEMY_DURATION)) .fadeTo(1, parseInt(0.4 * DEFAULT.HIGHLIGHT_ENEMY_DURATION)) .then(function () { _this.isHighlightLocked = false; }); } }, onenterframe: function () { }, move: function (x, y) { this.moveTo(x, y); }, applyDamage: function (damage) { this.armor -= damage; this.highlight(); if (this.armor <= 0) { return this.destroy(); } } });<file_sep>//--> Classe com funções estáticas úteis para cálculos e análises planas. var Plain = { inCoverage: function (content, container) { return (content.x >= 0 && content.x + content.width <= container.width && content.y >= 0 && content.y + content.height <= container.height); }, //--> Função para gerar posições x e y em um círculo. circlePos: function (config) { var pos = []; for (var i = config.from; i <= config.to; i += config.step) { pos.push({x: Math.cos(i), y: Math.sin(i)}); } return pos; }, //--> Função para retornar a distância euclideana entre dois pontos. distanceOf: function (p, q) { return Math.sqrt(Math.pow(p.x - q.x, 2) + Math.pow(p.y - q.y, 2)); }, //--> Função para receber um ponto A e um conjunto B de pontos e //--> retornar o ponto de B mais próximo de A. nearestOf: function (p, arr) { var iNearest = -1; var elNearest = undefined; var lowestDistance = VIEWPORT.DIAGONAL; for (var i in arr) { var q = arr[i]; if ((currentDistance = this.distanceOf (p, q)) < lowestDistance) { lowestDistance = currentDistance; iNearest = i; elNearest = q; } } return {index: iNearest, element: elNearest}; } };<file_sep>//--> Classe para representar um background de fase. var Background = enchant.Class.create (enchant.Sprite, { initialize: function (source) { enchant.Sprite.call(this, source.width, source.height); this.source = source; this.x = this.source.x; this.y = this.source.y; this.image = this.source.source.image; this.frame = 0; this.isStarted = false; this.stackedLayers = []; this.sourceStackedLayers = [this.source.destructibles, this.source.enemies]; this.percent = 0; Layers.backgrounds.addChild(this); }, stackLayer: function (layer) { layer.x = this.x; layer.y = this.y; layer.width = this.width; layer.height = this.height; this.stackedLayers.push(layer); if (gameMode == GAME_MODE.MULTI_PLAYER_SERVER) { channel.send(JSON.stringify({task: TASK.STACKED_LAYER.CREATE, name: layer.name})); } }, onenterframe: function () { if (this.isStarted && gameMode != GAME_MODE.MULTI_PLAYER_CLIENT) { var sendUpdates = false; if (this.y + this.source.speed < 0) { this.moveBy(0, this.source.speed); sendUpdates = true; } else if (this.y > 0) { this.y = 0; if (gameMode == GAME_MODE.MULTI_PLAYER_SERVER) { channel.send(JSON.stringify({task: TASK.BACKGROUND.MOVE, x: this.x, y: this.y})); } } if (sendUpdates) { if (gameMode == GAME_MODE.MULTI_PLAYER_SERVER) { channel.send(JSON.stringify({task: TASK.BACKGROUND.MOVE, x: this.x, y: this.y})); } //--> Verificar se há algum objeto para ser adicionado no game. $(this.sourceStackedLayers).each(function (iLayer, layer) { $(layer).each(function (index, element) { if (Math.abs(-element.y - background.y) < background.source.speed) { var x = (element.x != undefined) ? element.x : Math.random() * (game.width - element.item.width); new window[element.item.class](x, element.y, element.item); if (gameMode == GAME_MODE.MULTI_PLAYER_SERVER) { channel.send(JSON.stringify({task: TASK.DESTRUCTIBLE.CREATE, item: element.item, x: x, y: element.y})); } layer.splice(index, 1); } }); }); //--> Atualizar a posição das Layers empilhadas. $(this.stackedLayers).each(function (index, layer) { layer.moveTo(background.x, background.y); if (gameMode == GAME_MODE.MULTI_PLAYER_SERVER) { channel.send(JSON.stringify({task: TASK.STACKED_LAYER.MOVE, name: layer.name, x: layer.x, y: layer.y})); } }); } } }, move: function (x, y) { this.moveTo(x, y); }, moveStackedLayer: function (name, x, y) { $(this.stackedLayers).each(function (index, layer) { if (layer.name == name) { layer.moveTo(x, y); return false; } }); }, start: function () { this.isStarted = true; } });<file_sep>//--> Classe para representar um controle virtual para as ações do jogo (touch). var TouchControl = enchant.Class.create (enchant.Group, { initialize: function () { enchant.Group.call(this); var xPadding = 50; var yPadding = 50; this.width = VIEWPORT.WIDTH - 2 * xPadding; this.height = 200; this.x = xPadding; this.y = VIEWPORT.HEIGHT - this.height - yPadding; //--> Movimentação. this.addMovePad(); this.id = counterId++; Layers.touch_control.addChild(this); }, addMovePad: function () { this.movePad = new Group(); this.movePad.x = 0; this.movePad.y = 0; this.movePad.width = 200; this.movePad.height = 200; var movePad = this.movePad; //--> Pad de movimento - Parte visual. var movePadGraphic = new Sprite(movePad.width, movePad.height); movePadGraphic.x = 0; movePadGraphic.y = 0; movePadGraphic.image = game.assets[IMAGES.TOUCH_MOVE_PAD]; movePadGraphic.frame = 0; movePad.addChild(movePadGraphic); addPartMovePad = function (x, y, evt) { var movePadPart = new Sprite(movePad.width / 2, movePad.height / 2); movePadPart.rotate(45); movePadPart.x = x; movePadPart.y = y; movePadPart.image = game.assets[IMAGES.BLUE]; movePadPart.opacity = 0.3; movePadPart.ontouchstart = function () { game.input[evt] = true; }; movePadPart.ontouchmove = function () { game.input[evt] = true; }; movePadPart.ontouchend = function () { game.input[evt] = false; }; movePad.addChild(movePadPart); }; addPartMovePad(-(movePad.width / 4) * Math.cos(45) + 3, movePad.height / 4, "kLeft"); addPartMovePad(movePad.width / 2 + (movePad.width / 4) * Math.cos(45) - 3, movePad.height / 4, "kRight"); addPartMovePad(movePad.width / 4, -movePad.height / 8 + 2, "kUp"); addPartMovePad(movePad.width / 4, 5 * movePad.height / 8 - 2, "kDown"); this.addChild(movePad); }, onenterframe: function () { }, });<file_sep>var FallenPlain = enchant.Class.create(enchant.Group,{ initialize:function(row,col,blockTypes,blockGoals,iceLayer){ enchant.Group.call(this); this.row = row; this.col = col; this.width = this.col*80; this.height = this.row*80; this.x = (game.width-this.width)/2; this.y = (game.height-this.height)/2; this.blockTypes = (blockTypes == undefined)?[0]:blockTypes; this.cell = []; this.iceLayer = []; this.path = []; this.frame = -1; this.unInk = false; this.blockGoalsPosX = []; this.blockGoalsPosY = 20; this.blockGoals = blockGoals; this.validTypeGoals = []; this.moves = 0; for(var r=0;r<this.row;r++){ var __cell__ = []; var __ice__ = []; for(var c=0;c<this.col;c++){ __cell__.push(undefined); __ice__.push(false); } this.cell.push(__cell__); this.iceLayer.push(__ice__); } this.iceLayerCounter = 0; for(var i=0;i<iceLayer.length;i++){ this.iceLayer[iceLayer[i][0]][iceLayer[i][1]] = true; this.iceLayerCounter++; } this.iceLayerBefore = new Group(); this.iceLayerBefore.width = this.width; this.iceLayerBefore.height = this.height; this.addChild(this.iceLayerBefore); var bg = new Label(); bg.backgroundColor = "rgba(0,0,0,0.7)"; bg.width = this.width; bg.height = this.height; this.addChild(bg); this.iceLayerAfter = new Group(); this.iceLayerAfter.x = this.x; this.iceLayerAfter.y = this.y; this.iceLayerAfter.width = this.width; this.iceLayerAfter.height = this.height; //this.addChild(this.iceLayerAfter); this.witch = undefined; this.nFallens = 0;//to fall if( (i = this.blockTypes.indexOf(15) ) != -1 ){ this.nFallens = this.blockGoals[i]; } this.nextRedSkull = this.row*this.col; this.__nextRedSkull__ = this.nextRedSkull; game.rootScene.addChild(this); game.rootScene.addChild(this.iceLayerAfter); this.goals(); this.movesLabel(); this.pathLengthLabel(); this.refreshIceLayer(); this.buttons(); this.message(); }, turnOn:function(){ for(var r=0;r<this.row;r++){ for(var c=0;c<this.col;c++){ if(this.cell[r][c] != undefined && this.iceLayer[r][c] == false && this.cell[r][c].frame != 15){ this.cell[r][c].backgroundColor = 'rgba(200,200,40,0.7)'; } } } }, turnOff:function(){ for(var r=0;r<this.row;r++){ for(var c=0;c<this.col;c++){ if(this.cell[r][c] != undefined && this.iceLayer[r][c] == false && this.cell[r][c].frame != 15){ this.cell[r][c].backgroundColor = 'rgba(0,0,0,0)'; } } } }, noIce:function(){ var condition = false; for(var r=0;r<this.row;r++){ for(var c=0;c<this.col;c++){ if ( this.iceLayer[r][c] == true){ condition = true; } } } if(condition == false){ alert("Nao ha gelo neste level!"); return; } if ((confirm("Retirar todo o gelo. \n Custo: "+__COST_NO_ICE__+" scores. \n Seu score: "+score)) && score >= __COST_NO_ICE__) { score -= __COST_NO_ICE__; }else{ return; } for(var r=0;r<this.row;r++){ for(var c=0;c<this.col;c++){ this.iceLayer[r][c] = false; } } this.refreshIceLayer(); }, removeOne:function(b){ if(this.cell[b[0]][b[1]] != undefined && this.iceLayer[b[0]][b[1]] == false && this.cell[b[0]][b[1]].frame != 15){ this.takeCell(b); } }, collectSame:function(b){ if(this.cell[b[0]][b[1]] != undefined && this.iceLayer[b[0]][b[1]] == false && this.cell[b[0]][b[1]].frame != 15){ var frame = this.cell[b[0]][b[1]].frame; for(var r=0;r<this.row;r++){ for(var c=0;c<this.col;c++){ if(this.cell[r][c] != undefined && this.cell[r][c].frame == frame && this.cell[r][c] != undefined && this.iceLayer[r][c] == false && this.cell[r][c].frame != 15){ this.takeCell([r,c]); } } } } }, changeCells:function(cell1,cell2){ var tmp = this.cell[cell1[0]][cell1[1]].frame; this.cell[cell1[0]][cell1[1]].frame = this.cell[cell2[0]][cell2[1]].frame; this.cell[cell2[0]][cell2[1]].frame = tmp; this.cell[cell1[0]][cell1[1]].visible = false; this.cell[cell2[0]][cell2[1]].visible = false; var obj1 = this.cell[cell1[0]][cell1[1]]; var obj2 = this.cell[cell2[0]][cell2[1]]; var clone; clone = new Sprite(this.cell[cell1[0]][cell1[1]].width,this.cell[cell1[0]][cell1[1]].height); clone.x = this.x+this.cell[cell1[0]][cell1[1]].x; clone.y = this.y+this.cell[cell1[0]][cell1[1]].y; clone.image = this.cell[cell1[0]][cell1[1]].image; clone.frame = this.cell[cell1[0]][cell1[1]].frame; game.rootScene.addChild(clone); clone.tl.delay(1+Math.floor(Math.random()*3)).moveTo(this.x+this.cell[cell2[0]][cell2[1]].x,this.y+this.cell[cell2[0]][cell2[1]].y,3).then(function(){ obj2.visible = true; game.rootScene.removeChild(this); }); clone = new Sprite(this.cell[cell2[0]][cell2[1]].width,this.cell[cell2[0]][cell2[1]].height); clone.x = this.x+this.cell[cell2[0]][cell2[1]].x; clone.y = this.y+this.cell[cell2[0]][cell2[1]].y; clone.image = this.cell[cell2[0]][cell2[1]].image; clone.frame = this.cell[cell2[0]][cell2[1]].frame; game.rootScene.addChild(clone); clone.tl.delay(1+Math.floor(Math.random()*3)).moveTo(this.x+this.cell[cell1[0]][cell1[1]].x,this.y+this.cell[cell1[0]][cell1[1]].y,3).then(function(){ obj1.visible = true; game.rootScene.removeChild(this); }); }, randomCells:function(){ if ((confirm("Deseja embaralhar o tabuleiro? \n Custo: "+__COST_RANDOM__+" scores. \n Seu score: "+score)) && score >= __COST_RANDOM__) { score -= __COST_RANDOM__; }else{ return; } var possibles = []; for(var r=0;r<this.row;r++){ for(var c=0;c<this.col;c++){ //if(this.cell[r][c] != undefined){ if(this.cell[r][c] != undefined && this.cell[r][c].frame != 15 && this.iceLayer[r][c] == false){ possibles.push([r,c]); } } } var frameElements = possibles.map(function(p){return plain.cell[p[0]][p[1]].frame;}); var frameElementsSort = (frameElements.map(function(k){return k;})).sort(); var frameElementsCount = frameElementsSort.map(function(p){return [p,count(frameElementsSort,p)]}); for(var i in frameElementsCount){ if(frameElementsCount[i][1] >= 3){ var pos,r1,r2; var dpos = 0; //--1 pos = frameElements.indexOf(frameElementsCount[i][0],dpos); dpos = pos+1; r1 = possibles[pos]; r2 = possibles[0]; this.changeCells(r1,r2); //--2 pos = frameElements.indexOf(frameElementsCount[i][0],dpos); dpos = pos+1; r1 = possibles[pos]; r2 = possibles[1]; this.changeCells(r1,r2); //--3 pos = frameElements.indexOf(frameElementsCount[i][0],dpos); dpos = pos+1; r1 = possibles[pos]; r2 = possibles[2]; this.changeCells(r1,r2); //-- possibles.splice(0,1); possibles.splice(0,1); possibles.splice(0,1); break; } } var limit = 50000; while((limit-- >= 0) && possibles.length > 1){ var r1 = possibles[Math.floor(Math.random()*possibles.length)]; var r2 = possibles[Math.floor(Math.random()*possibles.length)]; if(r1 != r2){ this.changeCells(r1,r2); //console.log("change = ",r1," com ",r2); possibles.splice(possibles.indexOf(r1),1); possibles.splice(possibles.indexOf(r2),1); } } }, message:function(){ GAME_STATUS = 2; var g = new Group(); g.x = -game.width; g.y = (game.height-120)/2-10; g.width = game.width; g.height = 120; var l = new Label("Des\u00e7a as caveiras"); l.font = "40px Arial"; l.x = 0; l.y = 0; l.width = g.width; l.height = g.height/2; l.color = "white"; l.textAlign = "center"; l.backgroundColor = "rgba(0,0,0,0.8)"; g.addChild(l); l = new Label("Vermelhas!"); l.font = "52px sans-serif"; l.x = 0; l.y = g.height/2; l.width = g.width; l.height = g.height/2; l.color = "red"; l.textAlign = "center"; l.backgroundColor = "rgba(255,255,255,0.8)"; g.addChild(l); game.rootScene.addChild(g); g.tl.moveBy(game.width+25,0,8).moveBy(-25,0,5).delay(10).scaleTo(0.94,0.94,3).scaleTo(1.14,1.14,4).scaleTo(1,1,4).delay(10).moveBy(-25,0,5).moveBy(game.width+25,0,8) .then(function(){ GAME_STATUS = 1; game.rootScene.removeChild(this); }); }, buttons:function(){ back({x:10,y:game.height-10-80,scale:0.8}); restart({x:90,y:game.height-10-80,scale:0.8}); music({x:12,y:game.height-10-80-70,scale:0.7}); if(this.iceLayerCounter > 0){ noIce({x:230,y:game.height-10-80,scale:0.7}); } if(levelActual > 50){ removeOne({x:310,y:game.height-10-80,scale:0.7}); } if(levelActual > 75){ collectSame({x:395,y:game.height-10-80,scale:0.8}); } }, specialTile:function(p){ var s = new Sprite(80,80); s.image = game.assets["specialTile.png"]; //s.frame = [0,0,0,0,1,1,1,1,2,2,2,2]; s.frame = 0; s.x = p[1]*80; s.y = p[0]*80; this.addChild(s); s.tl.fadeOut(15).then(function(){ plain.removeChild(this); }); }, watermelon:function(p){ var r = p[0]; var c = p[1]; var spr = new Sprite(107,80); spr.image = game.assets["WatermelonSpecial107x80.png"]; spr.frame = [0,0,1,1,2,2,3,3,4,4]; spr.x = plain.x+c*80-(107-80)/2; spr.y = plain.y+r*80; game.rootScene.addChild(spr); spr.tl.scaleTo(1.5,1.5,5).scaleTo(1.2,1.2,5).then(function(){ game.rootScene.removeChild(this); }); var lbl = new Sprite(200,23); lbl.image = game.assets["MessageBombWatermelon200x23.png"]; lbl.frame = 0; lbl.x = (game.width-200)/2; lbl.y = (game.height-23)/2; lbl.scaleX = 2; lbl.scaleY = 2; game.rootScene.addChild(lbl); lbl.tl.scaleTo(2.5,3.8,12).moveBy(0,12,10).scaleTo(2,2,5).moveTo(lbl.x,0,5).then(function(){ game.rootScene.removeChild(this); }); this.tl.delay(10).then(function(){ var arr = [ [r-1,c-1],[r-1,c],[r-1,c+1], [r,c-1],[r,c],[r,c+1], [r+1,c-1],[r+1,c],[r+1,c+1] ]; for(var i in arr){ if(arr[i][0] > -1 && arr[i][0] < this.row && arr[i][1] > -1 && arr[i][1] < this.col && this.cell[arr[i][0]][arr[i][1]] != undefined){ if(this.iceLayer[arr[i][0]][arr[i][1]] == false){//dont take the ice cells! this.specialTile(arr[i]); this.takeCell(arr[i]); } } } }); __score__ += 5; }, pumpking:function(p){ var r = p[0]; var c = p[1]; var spr = new Sprite(26,26); spr.image = game.assets["PumpkinSpecial26x26.png"]; spr.frame = [0,1,2,3,4,5,6,7,8,9,10,11]; spr.x = plain.x+c*80-(26-80)/2; spr.y = plain.y+r*80; spr.scaleX = 2; spr.scaleY = 2; game.rootScene.addChild(spr); spr.tl.scaleTo(2.5,2.5,6).scaleTo(2,2,6).then(function(){ game.rootScene.removeChild(this); }); var lbl = new Sprite(200,26); lbl.image = game.assets["MessageFlashPumpkin200x26.png"]; lbl.frame = 0; lbl.x = (game.width-200)/2; lbl.y = (game.height-26)/2; lbl.scaleX = 2; lbl.scaleY = 2; game.rootScene.addChild(lbl); lbl.tl.scaleTo(2.5,3.8,12).moveBy(0,12,10).scaleTo(2,2,5).moveTo(lbl.x,0,5).then(function(){ game.rootScene.removeChild(this); }); this.tl.delay(12).then(function(){ var arr = [ [r,c-4],[r,c-3],[r,c-2],[r,c-1],[r,c],[r,c+1],[r,c+2],[r,c+3],[r,c+4], [r-4,c],[r-3,c],[r-2,c],[r-1,c],[r+1,c],[r+2,c],[r+3,c],[r+4,c] ]; for(var i in arr){ if(arr[i][0] > -1 && arr[i][0] < this.row && arr[i][1] > -1 && arr[i][1] < this.col && this.cell[arr[i][0]][arr[i][1]] != undefined){ if(this.iceLayer[arr[i][0]][arr[i][1]] == false){//dont take the ice cells! this.specialTile(arr[i]); this.takeCell(arr[i]); } } } }); __score__ += 10; }, check:function(){ var nGoals = 0; for(var i in this.blockGoals){ nGoals += this.blockGoals[i]; } var on = 0; if(this.moves >= 0 && nGoals == 0){ on = 1; //console.log("win"); if(levelMaxUnlocked == levelActual && levelMaxUnlocked < __monsterLevel__[__monsterLevel__.length-1][1]){ levelMaxUnlocked++; } levelActual = levelMaxUnlocked; __score__ += parseInt((this.moves*20)); score -= (-__score__); check_wait = false; winner(); var kxx = setInterval(function(){ if(check_wait){ main(); clearInterval(kxx); } },100); } if(on != 1 && this.moves <= 0){ //console.log("lose"); check_wait = false; loser(); var kxx = setInterval(function(){ if(check_wait){ main(); clearInterval(kxx); } },100); } //console.log("playing"); }, refreshIceLayer:function(){ var len = 0; len = this.iceLayerBefore.childNodes.length; for(var i=0;i<len;i++){ this.iceLayerBefore.removeChild(this.iceLayerBefore.childNodes[0]); } len = this.iceLayerAfter.childNodes.length; for(var i=0;i<len;i++){ this.iceLayerAfter.removeChild(this.iceLayerAfter.childNodes[0]); } for(var r=0;r<this.row;r++){ for(var c=0;c<this.col;c++){ var spr; if(this.iceLayer[r][c] == true){ spr = new Sprite(80,80); spr.x = c*80; spr.y = r*80; spr.image = game.assets["ice1.3.png"]; spr.frame = 0; this.iceLayerBefore.addChild(spr); spr = new Sprite(80,80); spr.x = c*80; spr.y = r*80; spr.image = game.assets["ice1.4.png"]; spr.frame = 0; this.iceLayerAfter.addChild(spr); } } } }, takeRedCell:function(cell){ var b = []; for(var r=0;r<this.row;r++){ for(var c=0;c<this.col;c++){ if(cell == this.cell[r][c]){ b = [r,c]; break; } } } var i = 0; for(var v in this.validTypeGoals){ if(this.validTypeGoals[v][0] == 15){ i = this.validTypeGoals[v][1]; break; } } var clone = new Sprite(80,80); clone.x = plain.x+this.cell[b[0]][b[1]].x; clone.y = plain.y+this.cell[b[0]][b[1]].y; clone.image = this.cell[b[0]][b[1]].image; clone.frame = this.cell[b[0]][b[1]].frame; game.rootScene.addChild(clone); //clone.tl.moveTo(plain.blockGoalsPosY+plain.blockGoalsPosX[i],plain.blockGoalsPosY,4).scaleTo(1.2,1.2,3).scaleTo(1,1,3).then(function(){ clone.tl.scaleTo(1.1,1.1,4).moveTo(plain.blockGoalsPosY+plain.blockGoalsPosX[i],plain.blockGoalsPosY,8).scaleTo(1.2,1.2,3).scaleTo(1,1,3).then(function(){ var nBlock = plain.blockTypes.indexOf(15); if(plain.blockGoals[nBlock] > 0){ plain.blockGoals[nBlock] -= 1; } if(game.assets["upMonster.ogg"]._state == 0){game.assets["upMonster.ogg"].play();} game.rootScene.removeChild(this); }); this.removeChild(this.cell[b[0]][b[1]]); this.cell[b[0]][b[1]] = undefined; }, takeCell:function(b){ /* If case b appoint to ice cell, just remove this ice, otherwise remove the cell, check goals... */ if(this.iceLayer[b[0]][b[1]] == true){ this.iceLayer[b[0]][b[1]] = false; this.refreshIceLayer(); game.assets["ice.wav"].play(); }else{ if(this.cell[b[0]][b[1]] != undefined && this.cell[b[0]][b[1]].frame != 15 && this.frame != 15){ var i = -1; if(this.blockTypes.indexOf(12) >= 0){ i = 0; }else{ for(var v in this.validTypeGoals){ if(this.validTypeGoals[v][0] == this.cell[b[0]][b[1]].frame){ i = this.validTypeGoals[v][1]; break; } } } if(i > -1){ var nBlock = -1; if((k=this.blockTypes.indexOf(12)) >= 0){ nBlock = k; }else{ for(var v in this.blockTypes){ //if(this.blockTypes[v] == this.cell[b[0]][b[1]].frame){ if(this.blockTypes[v] == this.cell[b[0]][b[1]].frame){ nBlock = v; break; } } } var clone = new Sprite(80,80); clone.x = plain.x+this.cell[b[0]][b[1]].x; clone.y = plain.y+this.cell[b[0]][b[1]].y; clone.image = this.cell[b[0]][b[1]].image; clone.frame = this.cell[b[0]][b[1]].frame; game.rootScene.addChild(clone); //clone.tl.moveTo(plain.blockGoalsPosY+plain.blockGoalsPosX[i],plain.blockGoalsPosY,4).scaleTo(1.2,1.2,3).scaleTo(1,1,3).then(function(){ clone.tl.scaleTo(1.1,1.1,4).moveTo(plain.blockGoalsPosY+plain.blockGoalsPosX[i],plain.blockGoalsPosY,4).scaleTo(1.2,1.2,3).scaleTo(1,1,3).then(function(){ if(plain.blockGoals[nBlock] > 0){ plain.blockGoals[nBlock] -= 1; } if(game.assets["upMonster.ogg"]._state == 0){game.assets["upMonster.ogg"].play();} game.rootScene.removeChild(this); }); } this.removeChild(this.cell[b[0]][b[1]]); this.cell[b[0]][b[1]] = undefined; }else{ } } }, pathLengthLabel:function(){ var bg = new Label("0"); bg.backgroundColor = "rgba(0,0,0,0.7)"; bg.width = 40; bg.height = 40; bg.color = "white"; bg.font = "35px sans-serif"; bg.textAlign = "center"; bg._visible = false; game.rootScene.addChild(bg); this.pathLabel = bg; }, refreshPathLengthLabel:function(){ if(this.path[this.path.length-1] != undefined){ var tr = this.path[this.path.length-1][0]; var tc = this.path[this.path.length-1][1]; if(tc == this.cell[0].length-1 && this.cell[0].length == 6){ this.pathLabel.x = this.x+80*(tc)-20; }else{ this.pathLabel.x = this.x+80*(1+tc)-20; } this.pathLabel.y = this.y+80*(1+tr)-20; this.pathLabel.text = this.path.length; if(this.path.length > 14){ this.pathLabel.color = "red"; }else if(this.path.length > 6){ this.pathLabel.color = "orange"; }else{ this.pathLabel.color = "white"; } this.pathLabel._visible = true; } }, movesLabel:function(){ var bg = new Label(); bg.backgroundColor = "rgba(0,0,0,0.7)"; bg.width = 90; bg.height = 50; bg.x = 370; bg.y = 20; bg.color = "white"; bg.font = "44px sans-serif"; bg.textAlign = "center"; bg.on("enterframe",function(){ if(plain.moves >= 0){ this.text = plain.moves; } }); game.rootScene.addChild(bg); }, goals:function(){ var n = 0; for(var i in this.blockGoals){ if(this.blockGoals[i] > 0){ this.validTypeGoals.push([this.blockTypes[i],n]); n++; } } //console.log(this.validTypeGoals); this.blockGoalsPosX = goalsPosX[n-1]; var g = new Group(); g.x = this.blockGoalsPosY; g.y = this.blockGoalsPosY; g.width = 330; g.height = 80; var bg = new Label(); bg.backgroundColor = "rgba(0,0,0,0.7)"; bg.width = g.width; bg.height = g.height; g.addChild(bg); var j = 0; for(var i in this.blockGoals){ if(this.blockGoals[i] > 0){ var spr = new Sprite(80,80); spr.x = this.blockGoalsPosX[j]; spr.y = 0; spr.image = game.assets["semgrade80x80.png"]; spr.frame = this.blockTypes[i]; spr.scale(0.8,0.8); g.addChild(spr); var num = new Label(""); num.x = this.blockGoalsPosX[j]+70; num.y = 30; num.width = 46; num.height = 30; num.color = "white"; num.textAlign = "center"; num.text = this.blockGoals[i]; num.font = "26px sans-serif"; num.i = i; num.on("enterframe",function(){ if(plain.blockGoals[this.i] > 0){ this.text = plain.blockGoals[this.i]; }else{ this.text = "ok"; } }); g.addChild(num); j++; } } game.rootScene.addChild(g); }, hasEmptyCells:function(){ for(var c=0;c<this.col;c++){ if(this.cell[0][c] == undefined){ return true; } } for(var r=0;r<this.row-1;r++){ for(var c=0;c<this.col;c++){ //if(this.cell[r+1][c] == undefined && this.iceLayer[r][c] == false){ if(this.cell[r+1][c] == undefined && this.iceLayer[r][c] == false && this.cell[r][c] != undefined){ return true; } } } return false; }, hasDownCells:function(){ for(var r=0;r<this.row-1;r++){ for(var c=0;c<this.col;c++){ if(this.cell[r+1][c] == undefined && this.iceLayer[r][c] == false && this.cell[r][c] != undefined){ return true; } } } return false; }, inkCells:function(arr){ for(var r=0;r<this.row;r++){ for(var c=0;c<this.col;c++){ if(this.cell[r][c] != undefined){ this.cell[r][c].backgroundColor = "rgba(0,0,0,0)"; } } } for(var i in arr){ if(this.cell[arr[i][0]][arr[i][1]] != undefined){ this.cell[arr[i][0]][arr[i][1]].backgroundColor = "rgba(140,20,20,0.7)"; } } }, insertBlocksFirstRow:function(){ for(var c=0;c<this.col;c++){ if(this.cell[0][c] == undefined){ var spr = new Sprite(80,80); spr.x = c*80; spr.y = 0; spr.image = game.assets["semgrade80x80.png"]; if(this.blockTypes.indexOf(12) >= 0){ var tmp = this.blockTypes.slice(0,this.blockTypes.indexOf(12)); spr.frame = tmp[Math.floor(Math.random()*tmp.length)]; }else{ //spr.frame = this.blockTypes[Math.floor(Math.random()*this.blockTypes.length)]; if(this.nextRedSkull-- == 0 && this.nFallens > 0){ spr.frame = this.blockTypes[this.blockTypes.length-1]; this.nextRedSkull = this.__nextRedSkull__; this.nFallens -= 1; }else{ spr.frame = this.blockTypes[Math.floor(Math.random()*(this.blockTypes.length-1))]; } } this.addChild(spr); this.cell[0][c] = spr; //spr.tl.delay(Math.floor(Math.random()*100)+100).scaleTo(1.2,1.2,3).scaleTo(0.9,0.9,3).scaleTo(1,1,2).loop(); } } }, downBlocks:function(){ for(var r=0;r<this.row-1;r++){ for(var c=0;c<this.col;c++){ if(this.cell[r][c] != undefined && this.iceLayer[r][c] == false){ var i = r*this.col + c;//iterador if(this.cell[r+1][c] == undefined){ var __cell__ = this.cell[r][c]; //-- MODE 1 //this.cell[r][c].tl.moveBy(0,80,3); this.cell[r][c].tl.moveBy(0,80,3).then(function(){ if(this.frame == 15 && parseInt(this.y + 80) == parseInt(plain.height)){ plain.takeRedCell(this); } }); //-- MODE 2 //__cell__.y += 80; this.cell[r+1][c] = __cell__; this.cell[r][c] = undefined; //-- } } } } } });
9b62f28eaf7345cd7326ec5209d77594be67cc0a
[ "JavaScript", "Python", "PHP" ]
39
JavaScript
leonardolanzellotti/goodproject
95a29519160c89aa18973bf1674a11f3e3c2cb53
fbe0428d039512260ffec45202c0ce5076a68c01
refs/heads/master
<file_sep>#pragma once #ifndef ALGORYTM_H #define ALGORYTM_H #include <stdio.h> int sprawdzaniezycia(char** ptab, int i, int j); int sprawdzaniesasiadow(char** ptab, int n, int m); char** zycie(char** ptab, int n, int m); #endif <file_sep>#include "array.h" #include "algorytm.h" #include <stdio.h> #define ALIVE 1 #define DEAD 0 int sprawdzaniezycia(char** ptab, int n, int m) { if (n == 0 || n == 22 || m == 0 || m == 80) return 0; else { if (ptab[n][m] == '*') return 1; else return 0; } } int sprawdzaniesasiadow(char** ptab, int n, int m) { int sasiedzi = 0; int i, j; if (n == 0 || n == 22 || m == 0 || m == 80) { return sasiedzi; } else { for (i = n - 1; i <= n + 1; i++) for (j = m - 1; j <= m + 1; j++) if (sprawdzaniezycia(ptab, i, j) == ALIVE) sasiedzi++; if (sprawdzaniezycia(ptab, n, m) == ALIVE) sasiedzi--; return sasiedzi; } } char** zycie(char** ptab, int n, int m) { int i, j; char** newptab = createMatrix(n, m); fillMatrix(newptab, n, m, ' '); for (i = 1; i<n; i++) { for (j = 1;j<m;j++) { if (sprawdzaniezycia(ptab, i, j) == DEAD) { if (sprawdzaniesasiadow(ptab, i, j) == 3) newptab[i][j] = '*'; } else { if (sprawdzaniesasiadow(ptab, i, j) == 2 || sprawdzaniesasiadow(ptab, i, j) == 3) { newptab[i][j] = '*'; } else newptab[i][j] = ' '; } } } deleteMatrix(ptab, n); return newptab; }<file_sep>#include "array.h" #include "algorytm.h" #include <stdio.h> #include <Windows.h> #define ROW 22 #define COL 80 int main(int argc, char *argv[]) { FILE *PlikWe; FILE *PlikWy; PlikWe = fopen("danewe.txt", "r"); PlikWy = fopen("danewy.txt", "w"); int i, j; char **Tab = createMatrix(ROW, COL); fillMatrix(Tab, ROW, COL, ' '); int temp1, temp2; while (!feof(PlikWe)) { fscanf(PlikWe, "%i", &temp1); fscanf(PlikWe, "%i", &temp2); Tab[temp2][temp1] = '*'; } for (i = 0;i<ROW;i++) { for (j = 0;j<COL;j++) printf("%c", Tab[i][j]); printf("\n"); } while (1) { Sleep(300); system("cls"); Tab = zycie(Tab, ROW, COL); for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) { printf("%c", atMatrix(Tab, i, j)); } printf("\n"); } } //system("pause"); for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) { fprintf(PlikWy, "%c", Tab[i][j]); } fprintf(PlikWy, "\n"); } fclose(PlikWe); fclose(PlikWy); return 0; } <file_sep>#pragma once #ifndef ARRAY_H #define ARRAY_H #include <stdio.h> void deleteMatrix(char** ptab, int n); char **createMatrix(int n, int m); char atMatrix(char** ptab, int n, int m); char** insertToMatrix(char** ptab, int n, int m, char wartosc); char** fillMatrix(char **ptab, int n, int m, char wartosc); char** resizeMatrix(char **ptab, int n, int m); #endif <file_sep>#include "array.h" #include <stdio.h> #include <stdlib.h> void deleteMatrix(char** ptab, int n) { int i; for (i = 0;i<n;i++) free(ptab[i]); free(ptab); } char **createMatrix(int n, int m) { char **tab = (char**)malloc(n * sizeof(char*)); if (!tab) return NULL; else { int i, j; for (i = 0;i<n;i++) { tab[i] = (char*)malloc(m * sizeof(char)); if (!tab[i]) { deleteMatrix(tab, i); return NULL; } } for (i = 0;i<n;i++) for (j = 0;j<m;j++) tab[i][j] = 0; return tab; } } char atMatrix(char** ptab, int n, int m) { return ptab[n][m]; } /*char** insertToMatrix (char** ptab, int n, int m, char wartosc) { ptab[n][m]=wartosc; return ptab; }*/ char** fillMatrix(char **ptab, int n, int m, char wartosc) { int i, j; for (i = 0; i<n; i++) for (j = 0; j<m; j++) ptab[i][j] = wartosc; return ptab; } char** resizeMatrix(char **ptab, int n, int m) { int i, j; int nKol = n + 5; int mWier = m + 5; char** newptab = createMatrix(nKol, mWier); for (i = 0; i<nKol; i++) for (j = 0; j<mWier; j++) newptab[i][j] = ptab[i][j]; deleteMatrix(ptab, n); return newptab; } <file_sep># mrsoczek Every file is different program. Some were written for scholl projects, some just for fun. Created in Microsoft Visual.
bbad69868e0ee5124c5c2b98f872621165b6400d
[ "Markdown", "C" ]
6
C
S0czek/mrsoczek
70689b3c9bfb3aff75117d45c2c351efa2203cec
9433fc65c57315858a8dbbf549ecf21efc8838bf
refs/heads/master
<file_sep>package siendev.corp.courses.springboot.model; public class UserEntity { } <file_sep>package siendev.corp.courses.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * */ @SpringBootApplication public class SpringBootCourseApplication { public static void main(String[] arg) { SpringApplication application = new SpringApplication(SpringBootCourseApplication.class); application.run(arg); } } <file_sep>package siendev.corp.courses.springboot.model; public class FilmEntity { }
d193c27141316d9f0a4c03669cc1156e67d076d0
[ "Java" ]
3
Java
Ghost-Rider-gu/Spring-Boot-Course
b1976ddd61664b0820a452457ce25209271bdd60
692f3eb5a1ead532b70d4ba1b184dbbb8f37d5ac
refs/heads/master
<repo_name>CrimsonDjubs/hotels_app<file_sep>/db/migrate/20150601083054_change_column_name.rb class ChangeColumnName < ActiveRecord::Migration def change rename_column :hotels, :photo_path, :image end end<file_sep>/spec/views/hotels/index.html.erb_spec.rb require 'spec_helper' describe "hotels/index" do before(:each) do assign(:hotels, [ stub_model(Hotel, :title => "Title", :star_rating => 1, :breakfast_included => "Breakfast Included", :room_description => "MyText", :photo_path => "", :price => 1.5 ), stub_model(Hotel, :title => "Title", :star_rating => 1, :breakfast_included => "Breakfast Included", :room_description => "MyText", :photo_path => "", :price => 1.5 ) ]) end it "renders a list of hotels" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "tr>td", :text => "Title".to_s, :count => 2 assert_select "tr>td", :text => 1.to_s, :count => 2 assert_select "tr>td", :text => "Breakfast Included".to_s, :count => 2 assert_select "tr>td", :text => "MyText".to_s, :count => 2 assert_select "tr>td", :text => "".to_s, :count => 2 assert_select "tr>td", :text => 1.5.to_s, :count => 2 end end <file_sep>/spec/views/hotels/show.html.erb_spec.rb require 'spec_helper' describe "hotels/show" do before(:each) do @hotel = assign(:hotel, stub_model(Hotel, :title => "Title", :star_rating => 1, :breakfast_included => "Breakfast Included", :room_description => "MyText", :photo_path => "", :price => 1.5 )) end it "renders attributes in <p>" do render # Run the generator again with the --webrat flag if you want to use webrat matchers rendered.should match(/Title/) rendered.should match(/1/) rendered.should match(/Breakfast Included/) rendered.should match(/MyText/) rendered.should match(//) rendered.should match(/1.5/) end end <file_sep>/db/migrate/20150601094130_alter_column_table_fieldname.rb class AlterColumnTableFieldname < ActiveRecord::Migration def up # change_table :hotels do |t| change_column :hotels, :breakfast_included, :boolean # end end end <file_sep>/app/models/hotel.rb class Hotel < ActiveRecord::Base mount_uploader :image, PhotoUploader validates :title, presence: true, length: { maximum: 100 } validates_numericality_of :star_rating, less_than_or_equal_to: 5 has_one :address has_many :comments end <file_sep>/app/models/address.rb class Address < ActiveRecord::Base belongs_to :hotel, autosave: true validates :hotel_id, presence: true end <file_sep>/config/initializers/secret.rb HotelsApp::Application.config.secret_key_base = '<KEY>'
dc620a64153c089b5edb4664003c4b92241c3b41
[ "Ruby" ]
7
Ruby
CrimsonDjubs/hotels_app
52c6134de7e7ba2a1f8e46b723d9b2b06475c98a
a0c5ab056ee58e4c7b4866d80293e85d2075cc40
refs/heads/master
<file_sep>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit6.h" //--------------------------------------------------------------------------- //#pragma package(smart_init) #pragma resource "*.dfm" TTextOptions *TextOptions; //--------------------------------------------------------------------------- __fastcall TTextOptions::TTextOptions(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TTextOptions::FormShow(TObject *Sender) { this->Edit1->SetFocus(); } //--------------------------------------------------------------------------- <file_sep>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "HelpForm.h" //--------------------------------------------------------------------------- //#pragma package(smart_init) #pragma resource "*.dfm" THelp *Help; //--------------------------------------------------------------------------- __fastcall THelp::THelp(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- <file_sep>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit5.h" //--------------------------------------------------------------------------- //#pragma package(smart_init) #pragma resource "*.dfm" TTimerOptions *TimerOptions; //--------------------------------------------------------------------------- __fastcall TTimerOptions::TTimerOptions(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TTimerOptions::UpDown1Click(TObject *Sender, TUDBtnType Button) { this->Edit1->Text = IntToStr(this->UpDown1->Position); } //--------------------------------------------------------------------------- <file_sep>//--------------------------------------------------------------------------- #ifndef Unit3H #define Unit3H //--------------------------------------------------------------------------- #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.StdCtrls.hpp> #include <Vcl.Forms.hpp> #include <Vcl.Buttons.hpp> #include <Vcl.ComCtrls.hpp> //--------------------------------------------------------------------------- class TPositionOptions : public TForm { __published: // IDE-managed Components TLabel *Label1; TUpDown *UpDown1; TEdit *Edit1; TBitBtn *BitBtn1; void __fastcall UpDown1Click(TObject *Sender, TUDBtnType Button); private: // User declarations public: // User declarations __fastcall TPositionOptions(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TPositionOptions *PositionOptions; //--------------------------------------------------------------------------- #endif <file_sep>//--------------------------------------------------------------------------- #ifndef HelpFormH #define HelpFormH //--------------------------------------------------------------------------- #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.StdCtrls.hpp> #include <Vcl.Forms.hpp> //--------------------------------------------------------------------------- class THelp : public TForm { __published: // IDE-managed Components TMemo *Memo1; private: // User declarations public: // User declarations __fastcall THelp(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE THelp *Help; //--------------------------------------------------------------------------- #endif <file_sep>// --------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "MainUnit.h" #include "petri_editor.h" // --------------------------------------------------------------------------- // #pragma package(smart_init) #pragma resource "*.dfm" TPetriEdit *PetriEdit; // --------------------------------------------------------------------------- int D_input_mas_backup[NNN + 1][NNN + 1], D_output_mas_backup[NNN + 1][NNN + 1]; int marking_mas_backup[NNN + 1]; gate_type gate_mas_backup[NNN + 1]; // --------------------------------------------------------------------------- __fastcall TPetriEdit::TPetriEdit(TComponent* Owner) : TForm(Owner) { } void __fastcall TPetriEdit::update_holst() { Form1->Draw(); Form1->update_marking(); } void __fastcall TPetriEdit::data_is_changed() { for (int i = 1; i < this->StringGrid3->ColCount; i++) marking_mas[i - 1] = (this->StringGrid3->Cells[i][1] != "" && StrToInt (this->StringGrid3->Cells[i][1]) >= 0 && StrToInt(this->StringGrid3->Cells[i][1]) <= 255) ? StrToInt(this->StringGrid3->Cells[i][1]) : 0; for (int i = 1; i < this->StringGrid4->ColCount; i++) gate_mas[i - 1].time_of_passing = (this->StringGrid4->Cells[i][1] != "" && StrToInt (this->StringGrid4->Cells[i][1]) >= 0 && StrToInt(this->StringGrid4->Cells[i][1]) <= 255) ? StrToInt(this->StringGrid4->Cells[i][1]) : 0; for (int i = 1; i < this->StringGrid5->ColCount; i++) gate_mas[i - 1].priority = (this->StringGrid5->Cells[i][1] != "" && StrToInt (this->StringGrid5->Cells[i][1]) >= 0 && StrToInt(this->StringGrid5->Cells[i][1]) <= 255) ? StrToInt(this->StringGrid5->Cells[i][1]) : 0; // for i:=1 to StringGrid4.ColCount-1 do // if (StringGrid4.Cells[i,1]!='') and (StrToInt(StringGrid4.Cells[i,1]) in [0..255]) then gate_mas[i].time_of_passing:=StrToInt(StringGrid4.Cells[i,1]) // else gate_mas[i].time_of_passing:=0; // for i:=1 to StringGrid5.ColCount-1 do // if (StringGrid5.Cells[i,1]!='') and (StrToInt(StringGrid5.Cells[i,1]) in [0..255]) then gate_mas[i].priority:=StrToInt(StringGrid5.Cells[i,1]) // else gate_mas[i].priority:=0; for (int i = 1; i < this->StringGrid1->RowCount; i++) for (int j = 1; j < this->StringGrid1->ColCount; j++) { D_input_mas[i - 1][j - 1] = (this->StringGrid1->Cells[j][i] != "" && StrToInt (this->StringGrid1->Cells[j][i]) >= 0 && StrToInt(this->StringGrid1->Cells[j][i]) <= 255) ? StrToInt(this->StringGrid1->Cells[j][i]) : 0; } for (int i = 1; i < this->StringGrid2->RowCount; i++) for (int j = 1; j < this->StringGrid2->ColCount; j++) { D_output_mas[i - 1][j - 1] = (this->StringGrid2->Cells[j][i] != "" && StrToInt (this->StringGrid2->Cells[j][i]) >= 0 && StrToInt(this->StringGrid2->Cells[j][i]) <= 255) ? StrToInt(this->StringGrid2->Cells[j][i]) : 0; } // for i:=1 to StringGrid1.RowCount-1 do // for j:=1 to StringGrid1.ColCount-1 do // if (StringGrid1.Cells[j,i]!='') and (StrToInt(StringGrid1.Cells[j,i]) in [0..255]) then D_input_mas[i,j]:=StrToInt(StringGrid1.Cells[j,i]) // else D_input_mas[i,j]:=0; // for i:=1 to StringGrid2.RowCount-1 do // for j:=1 to StringGrid2.ColCount-1 do // if (StringGrid2.Cells[j,i]!='') and (StrToInt(StringGrid2.Cells[j,i]) in [0..255]) then D_output_mas[i,j]:=StrToInt(StringGrid2.Cells[j,i]) // else D_output_mas[i,j]:=0; Form1->update_hint(); this->update_holst(); } // --------------------------------------------------------------------------- void __fastcall TPetriEdit::StringGrid1KeyUp(TObject *Sender, WORD &Key, TShiftState Shift) { this->data_is_changed(); } // --------------------------------------------------------------------------- void __fastcall TPetriEdit::StringGrid2KeyUp(TObject *Sender, WORD &Key, TShiftState Shift) { this->data_is_changed(); } // --------------------------------------------------------------------------- void __fastcall TPetriEdit::StringGrid3KeyUp(TObject *Sender, WORD &Key, TShiftState Shift){ this->data_is_changed(); } // --------------------------------------------------------------------------- void __fastcall TPetriEdit::StringGrid4KeyUp(TObject *Sender, WORD &Key, TShiftState Shift){ this->data_is_changed(); } // --------------------------------------------------------------------------- void __fastcall TPetriEdit::StringGrid5KeyUp(TObject *Sender, WORD &Key, TShiftState Shift){ this->data_is_changed(); } // --------------------------------------------------------------------------- void __fastcall TPetriEdit::N2Click(TObject *Sender) { for (int i = 0; i < number_of_positions; i++) marking_mas[i] = marking_mas_backup[i]; for (int i = 0; i < number_of_gates; i++) { gate_mas[i].time_of_passing = gate_mas_backup[i].time_of_passing; gate_mas[i].priority = gate_mas_backup[i].priority; } for (int i = 0; i < number_of_positions; i++) for (int j = 0; j < number_of_gates; j++) { D_input_mas[i][j] = D_input_mas_backup[i][j]; D_output_mas[i][j] = D_output_mas_backup[i][j]; } Form1->update_hint(); this->update_holst(); this->Close(); } //--------------------------------------------------------------------------- void __fastcall TPetriEdit::N1Click(TObject *Sender) { this->Close(); } //--------------------------------------------------------------------------- void __fastcall TPetriEdit::StringGrid1MouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { int R,C; this->StringGrid1->MouseToCell(X, Y, C, R); this->StringGrid1->Hint = IntToStr(R) + "*" + IntToStr(C); } //--------------------------------------------------------------------------- void __fastcall TPetriEdit::StringGrid2MouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { int R, C; this->StringGrid2->MouseToCell(X, Y, C, R); this->StringGrid2->Hint = IntToStr(R) + "*" + IntToStr(C); } __fastcall TPetriEdit::ShowHint(TObject *Sender){ this->StatusBar1->SimpleText = Application->Hint; } //--------------------------------------------------------------------------- void __fastcall TPetriEdit::FormShow(TObject *Sender) { // Application->OnHint = this->ShowHint; for (int i = 0; i <= NNN; i++) marking_mas_backup[i] = marking_mas[i]; for (int i = 0; i <= NNN; i++) { gate_mas_backup[i].time_of_passing = 0; gate_mas_backup[i].priority = 0; } for (int i = 0; i <= NNN; i++) for (int j = 0; j <= NNN; j++) { D_input_mas_backup[i][j] = 0; D_output_mas_backup[i][j] = 0; } for (int i = 0; i < number_of_positions; i++) marking_mas_backup[i] = marking_mas[i]; for (int i = 0; i < number_of_gates; i++) { gate_mas_backup[i].time_of_passing = gate_mas[i].time_of_passing; gate_mas_backup[i].priority = gate_mas[i].priority; } for (int i = 0; i < number_of_positions; i++) for (int j = 0; j < number_of_gates; j++) { D_input_mas_backup[i][j] = D_input_mas[i][j]; D_output_mas_backup[i][j] = D_output_mas[i][j]; } } //--------------------------------------------------------------------------- <file_sep>//--------------------------------------------------------------------------- #ifndef Unit2H #define Unit2H //--------------------------------------------------------------------------- #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.StdCtrls.hpp> #include <Vcl.Forms.hpp> #include <Vcl.Buttons.hpp> #include <Vcl.ExtCtrls.hpp> //--------------------------------------------------------------------------- class TForm2 : public TForm { __published: // IDE-managed Components TSpeedButton *posbutton; TSpeedButton *gatebutton; TSpeedButton *textbutton; TSpeedButton *arrorbutton; TBevel *Bevel1; TSpeedButton *DelButton; TComboBox *combobox1; void __fastcall arrorbuttonClick(TObject *Sender); void __fastcall textbuttonClick(TObject *Sender); void __fastcall posbuttonClick(TObject *Sender); void __fastcall DelButtonClick(TObject *Sender); private: // User declarations public: // User declarations __fastcall TForm2(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TForm2 *Form2; //--------------------------------------------------------------------------- #endif <file_sep>//--------------------------------------------------------------------------- #ifndef AboutUnitH #define AboutUnitH //--------------------------------------------------------------------------- #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.StdCtrls.hpp> #include <Vcl.Forms.hpp> #include <Vcl.ExtCtrls.hpp> #include <Vcl.Imaging.jpeg.hpp> //--------------------------------------------------------------------------- class TAboutForm : public TForm { __published: // IDE-managed Components TImage *Image1; TLabel *Label1; TLabel *Label2; TLabel *Label3; TLabel *Label4; TLabel *Label5; TLabel *Label6; TLabel *Label7; void __fastcall Image1Click(TObject *Sender); void __fastcall FormClick(TObject *Sender); void __fastcall Label6Click(TObject *Sender); void __fastcall Label6MouseMove(TObject *Sender, TShiftState Shift, int X, int Y); void __fastcall Image1MouseMove(TObject *Sender, TShiftState Shift, int X, int Y); private: // User declarations public: // User declarations __fastcall TAboutForm(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TAboutForm *AboutForm; //--------------------------------------------------------------------------- #endif <file_sep>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit4.h" //--------------------------------------------------------------------------- //#pragma package(smart_init) #pragma resource "*.dfm" TGateOptions *GateOptions; //--------------------------------------------------------------------------- __fastcall TGateOptions::TGateOptions(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TGateOptions::UpDown1Click(TObject *Sender, TUDBtnType Button) { this->Edit1->Text = IntToStr(this->UpDown1->Position); } //--------------------------------------------------------------------------- void __fastcall TGateOptions::UpDown2Click(TObject *Sender, TUDBtnType Button) { this->Edit2->Text = IntToStr(UpDown2->Position); } //--------------------------------------------------------------------------- <file_sep>// --------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop // #include "ShellAPI.h" #include <Shellapi.h> #include "petri_editor.h" #include "Unit2.h" #include "Unit3.h" #include "Unit4.h" #include "Unit5.h" #include "AboutUnit.h" #include "HelpForm.h" #include "Unit6.h" #include "MainUnit.h" // --------------------------------------------------------------------------- // #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; // --------------------------------------------------------------------------- const WM_FREEOBJECT = WM_APP + 1; int selected_gate, selected_position; bool gate_is_selected, position_is_selected; int Time_; TObject *object_to_destroy; TImage *ArrayPositions[NNN + 1]; TImage *ArrayGates[NNN + 1]; __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } // --------------------------------------------------------------------------- int trunc(double X) { return (int)X; }; string copy_(string str, int start, int length = -1, char *to = "") { if (to == "") to = ""; if (length == -1) length = str.length() - start; str.copy(to, length, start); // to[length] ='\0'; // string result(to); // delete to; return string(to); } // char *copy_(char *str, int start, int length = -1, char *to = NULL){string str_ = str;return copy_(string(str),start,length,to);} // --------------------------------------------------------------------------- void __fastcall TForm1::HolstMouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { position_is_selected = false; gate_is_selected = false; if (Form2->gatebutton->Down) { TImage *Image = new TImage(this); UnicodeString path = ".\\gate.bmp"; Image->Picture->LoadFromFile(path); Image->Name = "Gate" + IntToStr(number_of_gates); Image->Transparent = true; Image->AutoSize = true; Image->ShowHint = true; Image->Left = X + Holst->Left - 20; Image->Top = Y + Holst->Top - 20; Image->Hint = "Перехід: " + IntToStr(number_of_gates + 1); /* + ";Затримка:"+IntToStr(gate_mas[StrToInt(copy_(AnsiString(Image->Name).c_str(),4))].time_of_passing)+ ";Приорітет:"+IntToStr(gate_mas[StrToInt(copy_(AnsiString(Image->Name).c_str(),4))].priority) */ Image->Parent = Form1; Image->OnDblClick = DblClickGate; Image->OnMouseMove = MovePicture; Image->OnClick = ClickGate; ArrayGates[number_of_gates++] = Image; } else if (Form2->posbutton->Down) { TImage *Image = new TImage(this); // const char *filename = ; UnicodeString path = ".\\position.bmp"; Image->Picture->LoadFromFile(path); Image->Name = "Position" + IntToStr(number_of_positions); Image->Transparent = true; Image->AutoSize = true; Image->ShowHint = true; Image->Left = X + Holst->Left - 20; Image->Top = Y + Holst->Top - 20; Image->Hint = "Позиція: " + IntToStr(number_of_positions + 1); Image->Parent = Form1; Image->OnDblClick = DblClickPosition; Image->OnMouseMove = MovePicture; Image->OnClick = ClickPosition; ArrayPositions[number_of_positions++] = Image; // Image->Canvas->TextOutW(0,0, "Pos:" + IntToStr(number_of_positions)); } if (Form2->textbutton->Down) { TextOptions->Edit1->Text = ""; TextOptions->ShowModal(); if (TextOptions->ModalResult == mrOk && TextOptions->Edit1->Text != "") { number_of_text++; TLabel *Label = new TLabel(this); Label->Transparent = true; Label->AutoSize = true; Label->ShowHint = true; Label->Left = X + Holst->Left; Label->Top = Y + Holst->Top - 10; Label->Caption = TextOptions->Edit1->Text; Label->Name = "Text" + IntToStr(number_of_text); Label->Hint = "Text : " + IntToStr(number_of_text); Label->Parent = Form1; Label->OnMouseMove = MoveText; Label->OnDblClick = DblClickText; } } if (number_of_positions*number_of_gates >= 1) this->N25->Enabled = true; if (PetriEdit->Visible) this->update_grid(); } // --------------------------------------------------------------------------- void __fastcall TForm1::N2Click(TObject *Sender) { this->Close(); } // --------------------------------------------------------------------------- void __fastcall TForm1::N4Click(TObject *Sender) { object_to_destroy = NULL; Form1->VertScrollBar->Position = 0; Form1->HorzScrollBar->Position = 0; Holst->Canvas->FillRect(Holst->Canvas->ClipRect); for (int i = 0; i < NNN; i++) for (int j = 0; j < NNN; j++) { D_input_mas[i][j] = 0; D_output_mas[i][j] = 0; } for (int i = 0; i < NNN; i++) { marking_mas[i] = 0; gate_mas[i].time_of_passing = 0; gate_mas[i].priority = 0; gate_mas[i].is_breakpoint = false; } number_of_gates = 0; number_of_positions = 0; number_of_text = 0; Time_ = -1; label: for (int i = 0; i <= this->ComponentCount - 1; i++) { TLabel* label = dynamic_cast<TLabel*>(Components[i]); if (label) { delete(TLabel*)(Components[i]); goto label; } TImage* image = dynamic_cast<TImage*>(Components[i]); if (image) { if (image->Name != "Holst") { delete(TImage*)(Components[i]); goto label; } } } Form2->gatebutton->Enabled = true; Form2->posbutton->Enabled = true; Form2->textbutton->Enabled = true; Form2->arrorbutton->Enabled = true; Form2->DelButton->Enabled = true; N7->Enabled = true; N12->Enabled = true; N13->Enabled = true; N14->Enabled = true; N15->Enabled = true; N16->Enabled = true; N20->Enabled = true; N25->Enabled = false; next->Enabled = true; N5->Enabled = true; next->Caption = ""; if (PetriEdit->Visible) PetriEdit->Close(); Form1->Caption = "United - Petri Emul"; } // --------------------------------------------------------------------------- void __fastcall TForm1::FormShow(TObject *Sender) { Form2->Show(); } // --------------------------------------------------------------------------- void __fastcall TForm1::N6Click(TObject *Sender) { Form2->Show(); } // --------------------------------------------------------------------------- void __fastcall TForm1::N7Click(TObject *Sender) { if (this->SaveDialog1->Execute()) this->SaveToFile(this->SaveDialog1->FileName); } // --------------------------------------------------------------------------- void __fastcall TForm1::N8Click(TObject *Sender) { if (this->SaveDialog1->Execute()) this->LoadFromFile(this->SaveDialog1->FileName); } // --------------------------------------------------------------------------- void __fastcall TForm1::nextClick(TObject *Sender) { this->emulator_core(); if (number_of_positions*number_of_gates == 0) goto end_of_proc; for (int j = 0; j < number_of_gates; j++) { int sum = 0; for (int i = 0; i < number_of_positions; i++) sum += D_input_mas[i][j]; if (sum == 0) goto end_of_proc; } this->emulator_core(); return; end_of_proc: this->Timer1->Enabled = false; // ShowMessage("Ïðîâåðüòå ïðàâèëüíîñòü ïîñòðîåíèÿ ñåòè"); } // --------------------------------------------------------------------------- void __fastcall TForm1::N11Click(TObject *Sender) { TimerOptions->ShowModal(); if (TimerOptions->ModalResult == mrOk) this->Timer1->Interval = StrToInt(TimerOptions->Edit1->Text); } // --------------------------------------------------------------------------- void __fastcall TForm1::Timer1Timer(TObject *Sender) { this->nextClick(this); } // --------------------------------------------------------------------------- void __fastcall TForm1::N12Click(TObject *Sender) { this->Timer1->Enabled = true; } // --------------------------------------------------------------------------- void __fastcall TForm1::N13Click(TObject *Sender) { this->Timer1->Enabled = false; } // --------------------------------------------------------------------------- void __fastcall TForm1::N9Click(TObject *Sender) { AboutForm->ShowModal(); } // --------------------------------------------------------------------------- void __fastcall TForm1::N10Click(TObject *Sender) { Help->Show(); } // --------------------------------------------------------------------------- void __fastcall TForm1::N14Click(TObject *Sender) { String filename; this->Timer1->Enabled = false; // filename:=''; // filename:=copy(Form1.Caption,1,pos(' - Petri Emul',Form1.Caption)-1); if (FileExists(filename)) this->LoadFromFile(filename); } // --------------------------------------------------------------------------- void __fastcall TForm1::N15Click(TObject *Sender) { String filename = ""; // filename:=copy(Form1.Caption,1,pos(' - Petri Emul',Form1.Caption)-1); if (FileExists(filename)) this->SaveToFile(filename); } // --------------------------------------------------------------------------- void __fastcall TForm1::N25Click(TObject *Sender) { this->update_grid(); PetriEdit->Show(); } // --------------------------------------------------------------------------- void __fastcall TForm1::N24Click(TObject *Sender) { String filename; // filename:=copy(Form1.Caption,1,pos(' - Petri Emul',Form1.Caption)-1); // if (FileExists(filename)) // ShellExecute(Application->MainForm->Handle, L"open", AnsiString(filename), NULL, NULL, SW_SHOW); // else showmessage('Ïðîåêò íóæíî ñîõðàíèòü/îòêðûòü äëÿ îòîáðàæåíèÿ'); } void __fastcall TForm1::MovePicture(TObject *Sender, TShiftState Shift, int X, int Y) { if (Shift.Contains(ssLeft)) { ((TImage*)Sender)->Left = ((TImage*)Sender)->Left + X - 20; ((TImage*)Sender)->Top = ((TImage*)Sender)->Top + Y - 20; this->Draw(); } } void __fastcall TForm1::MoveText(TObject *Sender, TShiftState Shift, int X, int Y) { if (Shift.Contains(ssLeft)) { ((TLabel*)Sender)->Left = ((TLabel*)Sender)->Left + X - 5; ((TLabel*)Sender)->Top = ((TLabel*)Sender)->Top + Y - 5; this->Draw(); } } void __fastcall TForm1::DblClickText(TObject *Sender) { TextOptions->Edit1->Text = ((TLabel*)Sender)->Caption; TextOptions->ShowModal(); if (TextOptions->ModalResult == mrOk) { ((TLabel*)Sender)->Caption = TextOptions->Edit1->Text; } } void __fastcall TForm1::DblClickPosition(TObject *Sender) { selected_position = StrToInt(copy_(AnsiString(((TImage*)(Sender))->Name).c_str(), 8).c_str()); this->Caption = IntToStr(selected_position); if (gate_is_selected && Form2->arrorbutton->Down) { D_output_mas[selected_position][selected_gate] = (D_output_mas[selected_position][selected_gate] == 0) ? Form2->combobox1->ItemIndex + 1 : D_output_mas[selected_position][selected_gate] = 0; this->Draw(); gate_is_selected = false; } else { PositionOptions->Edit1->Text = IntToStr(marking_mas[selected_position]); PositionOptions->UpDown1->Position = marking_mas[selected_position]; PositionOptions->Caption = ((TImage*)Sender)->Name; PositionOptions->ShowModal(); if (PositionOptions->ModalResult == mrOk) { marking_mas[selected_position] = StrToInt(PositionOptions->Edit1->Text); this->update_marking(); } } if (PetriEdit->Visible) this->update_grid(); } void __fastcall TForm1::DblClickGate(TObject *Sender) { selected_gate = StrToInt(copy_(AnsiString(((TImage*)(Sender))->Name).c_str(), 4).c_str()); this->Caption = IntToStr(selected_gate); if (position_is_selected && Form2->arrorbutton->Down) { D_input_mas[selected_position][selected_gate] = (D_input_mas[selected_position][selected_gate] == 0) ? Form2->combobox1->ItemIndex + 1 : 0; this->Draw(); position_is_selected = false; } else { GateOptions->Edit1->Text = IntToStr(gate_mas[selected_gate].time_of_passing); GateOptions->UpDown1->Position = gate_mas[selected_gate].time_of_passing; GateOptions->Edit2->Text = IntToStr(gate_mas[selected_gate].priority); GateOptions->UpDown2->Position = gate_mas[selected_gate].priority; GateOptions->CheckBox1->Checked = gate_mas[selected_gate].is_breakpoint; GateOptions->Caption = ((TImage*)Sender)->Name; GateOptions->ShowModal(); if (GateOptions->ModalResult == mrOk) { gate_mas[selected_gate].time_of_passing = StrToInt(GateOptions->Edit1->Text); gate_mas[selected_gate].priority = StrToInt(GateOptions->Edit2->Text); gate_mas[selected_gate].is_breakpoint = GateOptions->CheckBox1->Checked; ((TImage*)Sender)->Hint = "Ïåðåõîä " + IntToStr(selected_gate) + ";òàéìåð:" + IntToStr(gate_mas[selected_gate].time_of_passing) + ";ïðèîðèòåò:" + IntToStr(gate_mas[selected_gate].priority); } } if (PetriEdit->Visible) this->update_grid(); } void __fastcall TForm1::ClickGate(TObject *Sender) { int gate; TImage *Image; gate_is_selected = false; gate = StrToInt(copy_(AnsiString(((TImage*)(Sender))->Name).c_str(), 4).c_str()); this->Caption = IntToStr(gate); if (Form2->arrorbutton->Down) { selected_gate = gate; gate_is_selected = true; } if (Form2->DelButton->Down) { delete((TImage*)(FindComponent("Gate" + IntToStr(gate)))); // PostMessage( this->Handle, WM_FREEOBJECT, Integer(Sender), 0 ); for (int i = 0; i < number_of_positions; i++) { for (int j = gate + 1; j < number_of_gates; j++) { D_input_mas[i][j - 1] = D_input_mas[i][j]; D_output_mas[i][j - 1] = D_output_mas[i][j]; } } for (int i = gate + 1; i < number_of_gates; i++) { gate_mas[i - 1] = gate_mas[i]; ArrayGates[i - 1] = ArrayGates[i]; Image = ((TImage*)((FindComponent("Gate" + IntToStr(i))))); Image->Name = "Gate" + IntToStr(i - 1); // Image->Hint = 'Ïåðåõîä '+copy(Image.Name,5,20)+';òàéìåð:'+IntToStr(gate_mas[strtoint(copy(Image.Name,5,20))].time_of_passing)+';ïðèîðèòåò:'+IntToStr(gate_mas[strtoint(copy(Image.Name,5,20))].priority); } for (int i = 0; i < number_of_positions; i++) { D_input_mas[i][number_of_gates] = 0; D_output_mas[i][number_of_gates] = 0; } gate_mas[number_of_gates].time_of_passing = 0; gate_mas[number_of_gates].priority = 0; gate_mas[number_of_gates].is_breakpoint = false; number_of_gates--; if (PetriEdit->Visible) this->update_grid(); this->Draw(); } } void __fastcall TForm1::ClickPosition(TObject *Sender) { TImage *Image; int position = StrToInt(copy_(AnsiString(((TImage*)(Sender))->Name).c_str(), 8).c_str()); this->Caption = IntToStr(position); position_is_selected = false; if (Form2->arrorbutton->Down) { selected_position = position; position_is_selected = true; } if (Form2->DelButton->Down) { delete(TImage*)(FindComponent("Position" + IntToStr(position))); // PostMessage(this->Handle, WM_FREEOBJECT, Integer(Sender), 0); for (int i = position + 1; i < number_of_positions; i++) { ArrayPositions[i - 1] = ArrayPositions[i]; marking_mas[i - 1] = marking_mas[i]; Image = (TImage*)(FindComponent("Position" + IntToStr(i))); Image->Name = "Position" + IntToStr(i - 1); Image->Hint = "Position " + IntToStr(i - 1); for (int j = 0; j < number_of_gates; j++) { D_input_mas[i - 1][j] = D_input_mas[i][j]; D_output_mas[i - 1][j] = D_output_mas[i][j]; } } for (int j = 0; j < number_of_gates; j++) { D_input_mas[number_of_positions][j] = 0; D_output_mas[number_of_positions][j] = 0; } marking_mas[number_of_positions] = 0; number_of_positions--; if (PetriEdit->Visible) this->update_grid(); this->Draw(); } } void __fastcall TForm1::Draw() { int sign; TImage *Image1, *Image2; double alpha; this->Holst->Canvas->FillRect(Holst->Canvas->ClipRect); for (int i = 0; i < number_of_positions; i++) { for (int j = 0; j < number_of_gates; j++) { if (D_input_mas[i][j] != 0) { Image1 = ArrayPositions[i]; Image2 = ArrayGates[j]; sign = (Image2->Left < Image1->Left) ? 1 : -1; alpha = ArcTan((Image2->Top - Image1->Top) / (Image2->Left - Image1->Left + (Image2->Left == Image1->Left))); Holst->Canvas->MoveTo(Image1->Left - Holst->Left + 20 + trunc((Image2->Left - Image1->Left) / 2), Image1->Top - Holst->Top + 20 + trunc((Image2->Top - Image1->Top) / 2)); Holst->Canvas->LineTo(Image1->Left - Holst->Left + 20 + trunc((Image2->Left - Image1->Left) / 2 + 10*cos(alpha + 0.4)*sign), Image1->Top - Holst->Top + 20 + trunc((Image2->Top - Image1->Top) / 2 + 10*sin(alpha + 0.4)*sign)); Holst->Canvas->MoveTo(Image1->Left - Holst->Left + 20 + trunc((Image2->Left - Image1->Left) / 2), Image1->Top - Holst->Top + 20 + trunc((Image2->Top - Image1->Top) / 2)); Holst->Canvas->LineTo(Image1->Left - Holst->Left + 20 + trunc((Image2->Left - Image1->Left) / 2 + 10*cos(alpha - 0.4)*sign), Image1->Top - Holst->Top + 20 + trunc((Image2->Top - Image1->Top) / 2 + 10*sin(alpha - 0.4)*sign)); Holst->Canvas->MoveTo(Image1->Left - Holst->Left + 20, Image1->Top - Holst->Top + 20); Holst->Canvas->LineTo(Image2->Left - Holst->Left + 20, Image2->Top - Holst->Top + 20); Holst->Canvas->TextOut(Image1->Left - Holst->Left + 20 + trunc((Image2->Left - Image1->Left) / 3), Image1->Top - Holst->Top + 20 + trunc((Image2->Top - Image1->Top) / 3), IntToStr(D_input_mas[i][j])); } if (D_output_mas[i][j] != 0) { Image1 = ArrayPositions[i]; Image2 = ArrayGates[j]; sign = (Image1->Left <= Image2->Left) ? 1 : -1; alpha = ArcTan((Image2->Top - Image1->Top) / (Image2->Left - Image1->Left + (Image2->Left == Image1->Left))); Holst->Canvas->MoveTo(Image1->Left - Holst->Left + 20 + trunc((Image2->Left - Image1->Left) / 2), Image1->Top - Holst->Top + 20 + trunc((Image2->Top - Image1->Top) / 2)); Holst->Canvas->LineTo(Image1->Left - Holst->Left + 20 + trunc((Image2->Left - Image1->Left) / 2 + 10*cos(alpha + 0.4)*sign), Image1->Top - Holst->Top + 20 + trunc((Image2->Top - Image1->Top) / 2 + 10*sin(alpha + 0.4)*sign)); Holst->Canvas->MoveTo(Image1->Left - Holst->Left + 20 + trunc((Image2->Left - Image1->Left) / 2), Image1->Top - Holst->Top + 20 + trunc((Image2->Top - Image1->Top) / 2)); Holst->Canvas->LineTo(Image1->Left - Holst->Left + 20 + trunc((Image2->Left - Image1->Left) / 2 + 10*cos(alpha - 0.4)*sign), Image1->Top - Holst->Top + 20 + trunc((Image2->Top - Image1->Top) / 2 + 10*sin(alpha - 0.4)*sign)); Holst->Canvas->MoveTo(Image1->Left - Holst->Left + 20, Image1->Top - Holst->Top + 20); Holst->Canvas->LineTo(Image2->Left - Holst->Left + 20, Image2->Top - Holst->Top + 20); Holst->Canvas->TextOut(Image2->Left - Holst->Left + 20 + trunc((-Image2->Left + Image1->Left) / 3), Image2->Top - Holst->Top + 20 + trunc((-Image2->Top + Image1->Top) / 3), IntToStr(D_output_mas[i][j])); } } } } // ----------------------------------------------------- emulator_core --------------- bool gate_enabled(int number_of_gate) { for (int i = 0; i < number_of_positions; i++) if (marking_mas[i] < D_input_mas[i][number_of_gate]) return false; return true; } void open_gate(int number_of_gate) { for (int i = 0; i < number_of_positions; i++) marking_mas[i] = marking_mas[i] - D_input_mas[i][number_of_gate] + D_output_mas[i][number_of_gate]; gate_mas[number_of_gate].active = false; Form1->update_marking(); if (gate_mas[number_of_gate].is_breakpoint) { if (Form1->Timer1->Enabled) { Form1->Timer1->Enabled = false; if (MessageDlg("Ïåðåõîä " + IntToStr(number_of_gate) + " âûïîëíåí. OK äëÿ ïðîäîëæåíèÿ âûïîëíåíèÿ ", mtInformation, mbOKCancel, 0) == mrOk) Form1->Timer1->Enabled = true; } else ShowMessage("Ïåðåõîä" + IntToStr(number_of_gate) + "âûïîëíåí."); } } bool any_enabled_gate_is_found() { int max_priority; TImage *Image; bool result = false; for (int i = 0; i < number_of_gates; i++) if (gate_enabled(i)) { result = true; if (!gate_mas[i].active) { gate_mas[i].active = true; gate_mas[i].timer = gate_mas[i].time_of_passing; } } else if (gate_mas[i].active) { Image = ArrayGates[i]; Image->Picture->LoadFromFile("gate.bmp"); gate_mas[i].active = false; } for (int i = 0; i < number_of_positions; i++) { max_priority = 0; for (int j = 0; j < number_of_gates; j++) if ((D_input_mas[i][j] > 0) && (gate_mas[j].active) && (gate_mas[j].priority > max_priority)) max_priority = gate_mas[j].priority; for (int j = 0; j < number_of_gates; j++) if ((gate_mas[j].active) && (gate_mas[j].priority < max_priority)) { Image = ArrayGates[i]; Image->Picture->LoadFromFile("gate.bmp"); gate_mas[j].active = false; } } return result; } void update_gates_info() { for (int i = 0; i < number_of_gates; i++) if (gate_mas[i].active) { TImage *Image = ArrayGates[i]; Image->Picture->LoadFromFile("gate_active.bmp"); Image->Canvas->Brush->Style = bsClear; Image->Canvas->TextOut(20, 17, IntToStr(gate_mas[i].timer)); gate_mas[i].timer--; } } bool any_open_is_possible() { for (int i = 0; i < number_of_gates; i++) if (any_enabled_gate_is_found() && gate_mas[i].active && gate_mas[i] .timer == 0) return true; return false; } string sfn(String LongName) { // Âîçâðàùàåò LongFileName ïðåîáðàçîâàííîå â ñîîòâåòñòâóþùåå êîðîòêîå èìÿ int i; string Result; i = 0; // i = GetShortPathName(pChar(LongName), pChar(Result), Length(Result)); // if (i > Length(Result){ // SetLength(Result,i); // i := GetShortPathName(pChar(LongName),pChar(Result),Length(Result)); // } // SetLength(Result,i); return Result; } int max_priority() { int max = 0; for (int i = 0; i < number_of_gates; i++) if (gate_mas[i].active && gate_mas[i].priority > max) max = gate_mas[i].priority; return max; } void __fastcall TForm1::emulator_core() { int i; TImage *Image; string filename, core_filename; for (i = 0; i < number_of_gates; i++) if (!gate_mas[i].active) { Image = ArrayGates[i]; Image->Picture->LoadFromFile("gate.bmp"); } if (any_enabled_gate_is_found()) { Time_++; this->next->Caption = "Time:" + IntToStr(Time_); while (any_open_is_possible()) { do { i = (rand() % number_of_gates) + 1; } while (!gate_mas[i].active && !gate_mas[i].timer == 0); open_gate(i); Image = ArrayGates[i]; Image->Picture->LoadFromFile("gate_opened.bmp"); } update_gates_info(); } else if (this->Timer1->Enabled) { this->Timer1->Enabled = false; core_filename = AnsiString(ExtractFilePath(Application->ExeName) + "core.exe").c_str(); // filename =copy(Form1.Caption,1,pos(' - Petri Emul',Form1.Caption)-1); if (!FileExists(filename.c_str())) filename = ""; if (FileExists(core_filename.c_str())) { ShellExecute(Application->MainForm->Handle, (LPCTSTR)"open", (LPCTSTR)(core_filename.c_str()), 0, 0, SW_SHOWNORMAL); // ShellExecute(Handle, (LPCTSTR)"open", "http://www.example.com/", 0, 0, SW_SHOWNORMAL); } else ShowMessage( "Ïîìåñòèòå â ïàïêó ñ Petri Emul ÿäðî ïðîãðàììû core.exe"); } } void __fastcall TForm1::update_marking() { for (int i = 0; i < number_of_positions; i++) { TImage *Image = ArrayPositions[i]; if (marking_mas[i] == 1) Image->Picture->LoadFromFile("position_1.bmp"); else { Image->Picture->LoadFromFile("position.bmp"); if (marking_mas[i] != 0) { Image->Canvas->Brush->Style = bsClear; Image->Canvas->TextOut(20, 17, IntToStr(marking_mas[i])); } } } if (PetriEdit->Visible) this->update_grid(); } void __fastcall TForm1::SaveToFile(String filename) { /* var output_file:textfile; i,j:integer; begin Form1.HorzScrollBar.Position:=0; Form1.VertScrollBar.Position:=0; assignfile(output_file,filename); rewrite(output_file); writeln(output_file,'Äàííûå:1)êîëè÷åñòâî ïîçèöèé è ïåðåõîäîâ;2)íà÷àëüíàÿ ìàðêèðîâêà;3)âðåìÿ âûïîëíåíèÿ äåéñòâèé,èõ ïðèîðèòåòû, ôëàã breakpoint;4)Ìàòðèöà èíöèäåíòíîñòè(âõîäíûå ïîçèöèè*ïåðåõîäû) D_;4)Ìàòðèöà èíöèäåíòíîñòè(âûõîäíûå ïîçèöèè*ïåðåõîäû) D+;5)Ãðàôè÷åñêàÿ ÷àñòü'); writeln(output_file); writeln(output_file,number_of_positions,' ',number_of_gates); writeln(output_file); for i:=1 to number_of_positions do write(output_file,IntToStr(marking_mas[i])+' '); writeln(output_file); writeln(output_file); for i:=1 to number_of_gates do write(output_file,IntToStr(gate_mas[i].time_of_passing)+' '); writeln(output_file); for i:=1 to number_of_gates do write(output_file,IntToStr(gate_mas[i].priority)+' '); writeln(output_file); for i:=1 to number_of_gates do write(output_file,IntToStr(ord(gate_mas[i].is_breakpoint))+' '); writeln(output_file); writeln(output_file); for i:=1 to number_of_positions do begin for j:=1 to number_of_gates do write(output_file,IntToStr(D_input_mas[i,j])+' '); writeln(output_file); end; writeln(output_file); for i:=1 to number_of_positions do begin for j:=1 to number_of_gates do write(output_file,IntToStr(D_output_mas[i,j])+' '); writeln(output_file); end; writeln(output_file); for i:=0 to ComponentCount-1 do if (Components[i] is TImage) and (copy(Timage(Components[i]).Name,1,4)='Gate') then begin writeln(output_file,'gate(',IntToStr(Timage(Components[i]).left),',',IntToStr(Timage(Components[i]).Top),',',Timage(Components[i]).Name,');'); end; for i:=0 to ComponentCount-1 do if (Components[i] is TImage) and (copy(Timage(Components[i]).Name,1,8)='Position') then begin writeln(output_file,'position(',IntToStr(Timage(Components[i]).left),',',IntToStr(Timage(Components[i]).Top),',',Timage(Components[i]).Name,');'); end; for i:=0 to ComponentCount-1 do if (Components[i] is TLabel) and (copy(TLabel(Components[i]).Name,1,4)='Text') and ((Components[i] as TLabel).Caption<>'') then begin writeln(output_file,'text(',IntToStr(TLabel(Components[i]).left),',',IntToStr(TLabel(Components[i]).Top),',',TLabel(Components[i]).Caption,');'); end; closefile(output_file); Form1.Caption:=filename+' - Petri Emul'; end; */ } void __fastcall TForm1::LoadFromFile(String filename) { /* var input_file:textfile; s:string; i,j:integer; buf:byte; begin N4Click(self); assignfile(input_file,FileName); reset(input_file); readln(input_file); read(input_file,number_of_positions); read(input_file,number_of_gates); for i:=1 to number_of_positions do read(input_file,marking_mas[i]); for i:=1 to number_of_gates do read(input_file,gate_mas[i].time_of_passing); for i:=1 to number_of_gates do read(input_file,gate_mas[i].priority); for i:=1 to number_of_gates do begin read(input_file,buf); gate_mas[i].is_breakpoint:=buf>0 end; for i:=1 to number_of_positions do for j:=1 to number_of_gates do read(input_file,D_input_mas[i,j]); for i:=1 to number_of_positions do for j:=1 to number_of_gates do read(input_file,D_output_mas[i,j]); readln(input_file); while not eof(input_file) do begin readln(input_file,s); if copy(s,1,4)='gate' then begin delete(s,1,5); with TImage.Create(self) do begin TransParent:=true; AutoSize:=true; showhint:=true; picture.LoadFromFile('gate.bmp'); left:=StrToInt(copy(s,1,pos(',',s)-1)); delete(s,1,pos(',',s)); top:=StrToInt(copy(s,1,pos(',',s)-1)); delete(s,1,pos(',',s)); name:=copy(s,1,pos(')',s)-1); hint:='Ïåðåõîä '+copy(Name,5,20)+';òàéìåð:'+IntToStr(gate_mas[strtoint(copy(Name,5,20))].time_of_passing)+';ïðèîðèòåò:'+IntToStr(gate_mas[strtoint(copy(Name,5,20))].priority); parent:=form1; OnDblClick:=DblClickGate; OnMouseMove:=MovePicture; Onclick:=clickGate; end; end else if copy(s,1,8)='position' then begin delete(s,1,9); with TImage.Create(self) do begin TransParent:=true; AutoSize:=true; showhint:=true; picture.LoadFromFile('position.bmp'); left:=StrToInt(copy(s,1,pos(',',s)-1)); delete(s,1,pos(',',s)); top:=StrToInt(copy(s,1,pos(',',s)-1)); delete(s,1,pos(',',s)); name:=copy(s,1,pos(')',s)-1); hint:='Ïîçèöèÿ '+copy(Name,9,20); parent:=form1; OnDblClick:=DblClickPosition; OnMouseMove:=MovePicture; Onclick:=clickPosition; end; end else if copy(s,1,4)='text' then begin delete(s,1,5); inc(number_of_text); with TLabel.Create(self) do begin TransParent:=true; AutoSize:=true; showhint:=true; left:=StrToInt(copy(s,1,pos(',',s)-1)); delete(s,1,pos(',',s)); top:=StrToInt(copy(s,1,pos(',',s)-1)); delete(s,1,pos(',',s)); caption:=copy(s,1,pos(')',s)-1);; name:='Text'+inttostr(number_of_text); hint:='Òåêñòîâûé êîììåíòàðèé '+inttostr(number_of_text); parent:=form1; OnMouseMove:=MoveText; OnDblClick:=DblClickText; end; end end; draw; update_marking; closefile(input_file); if number_of_positions*number_of_gates>=1 then N25.Enabled:=true; Form1.Caption:=FileName+' - Petri Emul'; end; */ } void __fastcall TForm1::update_grid() { int i, j, buf; PetriEdit->Width = 600; PetriEdit->Height = 600; for (i = 0; i < number_of_positions; i++) PetriEdit->StringGrid3->Cells[i + 1][1] = IntToStr(marking_mas[i]); for (i = 0; i < number_of_gates; i++) { PetriEdit->StringGrid4->Cells[i + 1][1] = IntToStr(gate_mas[i].time_of_passing); PetriEdit->StringGrid5->Cells[i + 1][1] = IntToStr(gate_mas[i].priority); } for (i = 0; i < number_of_positions; i++) for (j = 0; j < number_of_gates; j++) { PetriEdit->StringGrid1->Cells[i + 1][j + 1] = (D_input_mas[i][j] > 0) ? AnsiString(IntToStr(D_input_mas[i][j])).c_str() : AnsiString("").c_str(); } for (i = 0; i < number_of_positions; i++) for (j = 0; j < number_of_gates; j++) PetriEdit->StringGrid2->Cells[j + 1][i + 1] = (D_output_mas[i][j] > 0) ? AnsiString(IntToStr(D_output_mas[i][j])).c_str() : AnsiString("").c_str(); PetriEdit->StringGrid1->RowCount = number_of_gates + 1; PetriEdit->StringGrid1->ColCount = number_of_positions + 1; PetriEdit->StringGrid2->RowCount = number_of_gates + 1; PetriEdit->StringGrid2->ColCount = number_of_positions + 1; PetriEdit->StringGrid3->ColCount = number_of_positions + 1; PetriEdit->StringGrid4->ColCount = number_of_gates + 1; PetriEdit->StringGrid5->ColCount = number_of_gates + 1; PetriEdit->StringGrid1->Width = (PetriEdit->StringGrid1->ColCount + 1) * PetriEdit->StringGrid1->DefaultColWidth + PetriEdit->StringGrid1->ColCount; PetriEdit->StringGrid1->Height = (PetriEdit->StringGrid1->RowCount + 1) * PetriEdit->StringGrid1->DefaultRowHeight + PetriEdit->StringGrid1->RowCount; PetriEdit->StringGrid2->Width = (PetriEdit->StringGrid2->ColCount + 1) * PetriEdit->StringGrid2->DefaultColWidth + PetriEdit->StringGrid2->ColCount; PetriEdit->StringGrid2->Height = (PetriEdit->StringGrid2->RowCount + 1) * PetriEdit->StringGrid2->DefaultRowHeight + PetriEdit->StringGrid2->RowCount; PetriEdit->StringGrid3->Width = (PetriEdit->StringGrid3->ColCount + 1) * PetriEdit->StringGrid3->DefaultColWidth + PetriEdit->StringGrid3->ColCount; PetriEdit->StringGrid4->Width = (PetriEdit->StringGrid4->ColCount + 1) * PetriEdit->StringGrid4->DefaultColWidth + PetriEdit->StringGrid4->ColCount; PetriEdit->StringGrid5->Width = (PetriEdit->StringGrid5->ColCount + 1) * PetriEdit->StringGrid5->DefaultColWidth + PetriEdit->StringGrid5->ColCount; PetriEdit->StringGrid2->Left = PetriEdit->StringGrid1->Left + PetriEdit->StringGrid1->Width + 10; PetriEdit->Label2->Left = PetriEdit->StringGrid2->Left; PetriEdit->Label3->Top = PetriEdit->StringGrid1->Top + PetriEdit->StringGrid1->Height + 20; PetriEdit->StringGrid3->Top = PetriEdit->Label3->Top + 15; PetriEdit->Label4->Top = PetriEdit->StringGrid3->Top + PetriEdit->StringGrid3->Height + 20; PetriEdit->StringGrid4->Top = PetriEdit->Label4->Top + 15; PetriEdit->Label5->Top = PetriEdit->StringGrid4->Top + PetriEdit->StringGrid4->Height + 20; PetriEdit->StringGrid5->Top = PetriEdit->Label5->Top + 15; if ((PetriEdit->StringGrid1->Width + PetriEdit->StringGrid2->Width + 60 < PetriEdit->Width) && (PetriEdit->StringGrid3->Width + 40 < PetriEdit->Width)) if (PetriEdit->StringGrid1->Width + PetriEdit->StringGrid2->Width > PetriEdit->StringGrid3->Width) PetriEdit->Width = PetriEdit->StringGrid1->Width + PetriEdit->StringGrid2->Width + 60; else PetriEdit->Width = PetriEdit->StringGrid3->Width + 60; if (PetriEdit->StringGrid5->Top + 160 < PetriEdit->Height) PetriEdit->Height = PetriEdit->StringGrid5->Top + 160; for (i = 0; i < number_of_positions; i++) { PetriEdit->StringGrid1->Cells[0][i + 1] = IntToStr(i + 1); PetriEdit->StringGrid2->Cells[0][i + 1] = IntToStr(i + 1); PetriEdit->StringGrid3->Cells[i + 1][0] = IntToStr(i + 1); } for (i = 0; i < number_of_gates; i++) { PetriEdit->StringGrid1->Cells[i + 1][0] = IntToStr(i + 1); PetriEdit->StringGrid2->Cells[i + 1][0] = IntToStr(i + 1); PetriEdit->StringGrid4->Cells[i + 1][0] = IntToStr(i + 1); PetriEdit->StringGrid5->Cells[i + 1][0] = IntToStr(i + 1); } PetriEdit->StringGrid1->Cells[0][0] = "i/j"; PetriEdit->StringGrid2->Cells[0][0] = "i/j"; PetriEdit->StringGrid3->Cells[0][0] = "i"; PetriEdit->StringGrid4->Cells[0][0] = "j"; PetriEdit->StringGrid5->Cells[0][0] = "j"; } void __fastcall TForm1::update_hint() { for (int i = 0; i < number_of_gates; i++) { TImage *Image = ArrayGates[i]; // Image->Hint = "Ïåðåõîä "+copy_(AnsiString(Image->Name).c_str(),4)+";òàéìåð:"+ // IntToStr(gate_mas[strtoint(copy_(AnsiString(Image->Name).c_str(),4))].time_of_passing)+ // ";ïðèîðèòåò:"+IntToStr(gate_mas[StrToInt(copy_(AnsiString(Image->Name).c_str(), 4))].priority); } } // --------------------------------------------------------------------------- void __fastcall TForm1::HolstDblClick(TObject *Sender) { // this->N4Click(this); } // --------------------------------------------------------------------------- void __fastcall TForm1::N23Click(TObject *Sender) { this->N13Click(this->N23); } // --------------------------------------------------------------------------- <file_sep>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit2.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm2 *Form2; //--------------------------------------------------------------------------- __fastcall TForm2::TForm2(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm2::arrorbuttonClick(TObject *Sender) { if (this->arrorbutton->Enabled) this->combobox1->Visible = true; this->combobox1->ItemIndex =0; } //--------------------------------------------------------------------------- void __fastcall TForm2::textbuttonClick(TObject *Sender) { this->combobox1->Visible = false; this->combobox1->ItemIndex = 0; } //--------------------------------------------------------------------------- void __fastcall TForm2::posbuttonClick(TObject *Sender) { this->combobox1->Visible = false; this->combobox1->ItemIndex = 0; } //--------------------------------------------------------------------------- void __fastcall TForm2::DelButtonClick(TObject *Sender) { this->combobox1->Visible = false; this->combobox1->ItemIndex = 0; } //--------------------------------------------------------------------------- <file_sep>//--------------------------------------------------------------------------- #ifndef Unit5H #define Unit5H //--------------------------------------------------------------------------- #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.StdCtrls.hpp> #include <Vcl.Forms.hpp> #include <Vcl.Buttons.hpp> #include <Vcl.ComCtrls.hpp> //--------------------------------------------------------------------------- class TTimerOptions : public TForm { __published: // IDE-managed Components TUpDown *UpDown1; TEdit *Edit1; TBitBtn *BitBtn1; void __fastcall UpDown1Click(TObject *Sender, TUDBtnType Button); private: // User declarations public: // User declarations __fastcall TTimerOptions(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TTimerOptions *TimerOptions; //--------------------------------------------------------------------------- #endif <file_sep>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop //#include "ShellAPI.h" #include <Shellapi.h> #include "AboutUnit.h" //--------------------------------------------------------------------------- //#pragma package(smart_init) #pragma resource "*.dfm" TAboutForm *AboutForm; //--------------------------------------------------------------------------- __fastcall TAboutForm::TAboutForm(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TAboutForm::Image1Click(TObject *Sender) { this->Close(); } //--------------------------------------------------------------------------- void __fastcall TAboutForm::FormClick(TObject *Sender) { this->Close(); } //--------------------------------------------------------------------------- void __fastcall TAboutForm::Label6Click(TObject *Sender) { ShellExecute(this->Handle, L"open", L"http://petri.clan.su", NULL, NULL, SW_SHOW); } //--------------------------------------------------------------------------- void __fastcall TAboutForm::Label6MouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { this->Label6->Font->Color = clWhite; } //--------------------------------------------------------------------------- void __fastcall TAboutForm::Image1MouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { this->Label6->Font->Color = clTeal; } //--------------------------------------------------------------------------- <file_sep>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit3.h" //--------------------------------------------------------------------------- //#pragma package(smart_init) #pragma resource "*.dfm" TPositionOptions *PositionOptions; //--------------------------------------------------------------------------- __fastcall TPositionOptions::TPositionOptions(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TPositionOptions::UpDown1Click(TObject *Sender, TUDBtnType Button) { this->Edit1->Text = IntToStr(this->UpDown1->Position); } //--------------------------------------------------------------------------- <file_sep>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include <tchar.h> //--------------------------------------------------------------------------- USEFORM("petri_editor.cpp", Form1); USEFORM("MainUnit.cpp", PetriEdit); USEFORM("AboutUnit.cpp", AboutForm); USEFORM("HelpForm.cpp", Help); USEFORM("Unit2.cpp", Form2); USEFORM("Unit3.cpp", PositionOptions); USEFORM("Unit4.cpp", GateOptions); USEFORM("Unit5.cpp", TimerOptions); USEFORM("Unit6.cpp", TextOptions); //--------------------------------------------------------------------------- int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int) { try { Application->Initialize(); Application->MainFormOnTaskBar = true; Application->CreateForm(__classid(TForm1), &Form1); Application->CreateForm(__classid(TForm2), &Form2); Application->CreateForm(__classid(TPetriEdit), &PetriEdit); Application->CreateForm(__classid(TAboutForm), &AboutForm); Application->CreateForm(__classid(THelp), &Help); Application->CreateForm(__classid(TPositionOptions), &PositionOptions); Application->CreateForm(__classid(TGateOptions), &GateOptions); Application->CreateForm(__classid(TTimerOptions), &TimerOptions); Application->CreateForm(__classid(TTextOptions), &TextOptions); Application->Run(); } catch (Exception &exception) { Application->ShowException(&exception); } catch (...) { try { throw Exception(""); } catch (Exception &exception) { Application->ShowException(&exception); } } return 0; } //--------------------------------------------------------------------------- <file_sep>//--------------------------------------------------------------------------- #ifndef MainUnitH #define MainUnitH //--------------------------------------------------------------------------- #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.StdCtrls.hpp> #include <Vcl.Forms.hpp> #include <Vcl.ComCtrls.hpp> #include <Vcl.Grids.hpp> #include <Vcl.Menus.hpp> //--------------------------------------------------------------------------- class TPetriEdit : public TForm { __published: // IDE-managed Components TScrollBox *ScrollBox1; TLabel *Label1; TLabel *Label2; TLabel *Label3; TLabel *Label4; TLabel *Label5; TStringGrid *StringGrid3; TStringGrid *StringGrid4; TStringGrid *StringGrid1; TStringGrid *StringGrid2; TStringGrid *StringGrid5; TStatusBar *StatusBar1; TMainMenu *MainMenu1; TMenuItem *N1; TMenuItem *N2; void __fastcall StringGrid1KeyUp(TObject *Sender, WORD &Key, TShiftState Shift); void __fastcall StringGrid2KeyUp(TObject *Sender, WORD &Key, TShiftState Shift); void __fastcall StringGrid3KeyUp(TObject *Sender, WORD &Key, TShiftState Shift); void __fastcall StringGrid4KeyUp(TObject *Sender, WORD &Key, TShiftState Shift); void __fastcall StringGrid5KeyUp(TObject *Sender, WORD &Key, TShiftState Shift); void __fastcall N2Click(TObject *Sender); void __fastcall N1Click(TObject *Sender); void __fastcall StringGrid1MouseMove(TObject *Sender, TShiftState Shift, int X, int Y); void __fastcall StringGrid2MouseMove(TObject *Sender, TShiftState Shift, int X, int Y); void __fastcall FormShow(TObject *Sender); private: // User declarations public: // User declarations __fastcall TPetriEdit(TComponent* Owner); void __fastcall update_holst(); void __fastcall data_is_changed(); __fastcall ShowHint(TObject *Sender); }; //--------------------------------------------------------------------------- extern PACKAGE TPetriEdit *PetriEdit; //--------------------------------------------------------------------------- #endif <file_sep>//--------------------------------------------------------------------------- #ifndef Unit6H #define Unit6H //--------------------------------------------------------------------------- #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.StdCtrls.hpp> #include <Vcl.Forms.hpp> #include <Vcl.Buttons.hpp> //--------------------------------------------------------------------------- class TTextOptions : public TForm { __published: // IDE-managed Components TLabel *Label1; TBitBtn *BitBtn1; TBitBtn *BitBtn2; TEdit *Edit1; void __fastcall FormShow(TObject *Sender); private: // User declarations public: // User declarations __fastcall TTextOptions(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TTextOptions *TextOptions; //--------------------------------------------------------------------------- #endif <file_sep>//--------------------------------------------------------------------------- #ifndef Unit4H #define Unit4H //--------------------------------------------------------------------------- #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.StdCtrls.hpp> #include <Vcl.Forms.hpp> #include <Vcl.Buttons.hpp> #include <Vcl.ComCtrls.hpp> //--------------------------------------------------------------------------- class TGateOptions : public TForm { __published: // IDE-managed Components TLabel *label1; TLabel *Label2; TEdit *Edit1; TUpDown *UpDown1; TBitBtn *BitBtn1; TCheckBox *CheckBox1; TUpDown *UpDown2; TEdit *Edit2; void __fastcall UpDown1Click(TObject *Sender, TUDBtnType Button); void __fastcall UpDown2Click(TObject *Sender, TUDBtnType Button); private: // User declarations public: // User declarations __fastcall TGateOptions(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TGateOptions *GateOptions; //--------------------------------------------------------------------------- #endif <file_sep>//--------------------------------------------------------------------------- #ifndef petri_editorH #define petri_editorH #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.Dialogs.hpp> #include <Vcl.ExtCtrls.hpp> #include <Vcl.Menus.hpp> #include <Vcl.XPMan.hpp> #include <Vcl.StdCtrls.hpp> #include <string> #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.Dialogs.hpp> #include <Vcl.ExtCtrls.hpp> #include <Vcl.Menus.hpp> #include <Vcl.XPMan.hpp> #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.Dialogs.hpp> #include <Vcl.ExtCtrls.hpp> #include <Vcl.Menus.hpp> #include <Vcl.XPMan.hpp> //--------------------------------------------------------------------------- #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.StdCtrls.hpp> #include <Vcl.Forms.hpp> #include <Vcl.Dialogs.hpp> #include <Vcl.ExtCtrls.hpp> #include <Vcl.Menus.hpp> #include <Vcl.XPMan.hpp> //--------------------------------------------------------------------------- using namespace std; class TForm1 : public TForm { __published: // IDE-managed Components TImage *Holst; TXPManifest *XPManifest1; TMainMenu *MainMenu1; TMenuItem *N1; TMenuItem *N4; TMenuItem *N17; TMenuItem *N7; TMenuItem *N15; TMenuItem *N18; TMenuItem *N8; TMenuItem *N16; TMenuItem *N19; TMenuItem *N2; TMenuItem *N5; TMenuItem *N6; TMenuItem *N11; TMenuItem *N25; TMenuItem *N24; TMenuItem *N20; TMenuItem *N21; TMenuItem *N22; TMenuItem *N23; TMenuItem *next; TMenuItem *N12; TMenuItem *N13; TMenuItem *N14; TSaveDialog *SaveDialog1; TOpenDialog *OpenDialog1; TTimer *Timer1; void __fastcall HolstMouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y); void __fastcall N2Click(TObject *Sender); void __fastcall N4Click(TObject *Sender); void __fastcall FormShow(TObject *Sender); void __fastcall N6Click(TObject *Sender); void __fastcall N7Click(TObject *Sender); void __fastcall N8Click(TObject *Sender); void __fastcall nextClick(TObject *Sender); void __fastcall N11Click(TObject *Sender); void __fastcall Timer1Timer(TObject *Sender); void __fastcall N12Click(TObject *Sender); void __fastcall N13Click(TObject *Sender); void __fastcall N9Click(TObject *Sender); void __fastcall N10Click(TObject *Sender); void __fastcall N14Click(TObject *Sender); void __fastcall N15Click(TObject *Sender); void __fastcall N25Click(TObject *Sender); void __fastcall N24Click(TObject *Sender); void __fastcall HolstDblClick(TObject *Sender); void __fastcall N23Click(TObject *Sender); private: // User declarations public: // User declarations void __fastcall MovePicture(TObject *Sender, TShiftState Shift, int X, int Y); void __fastcall MoveText(TObject *Sender, TShiftState Shift, int X, int Y); void __fastcall DblClickText(TObject *Sender); void __fastcall DblClickPosition(TObject *Sender); void __fastcall DblClickGate(TObject *Sender); void __fastcall ClickGate(TObject *Sender); void __fastcall ClickPosition(TObject *Sender); void __fastcall Draw(); void __fastcall emulator_core(); void __fastcall update_marking(); void __fastcall SaveToFile(String filename); void __fastcall LoadFromFile(String filename); void __fastcall update_grid(); void __fastcall update_hint(); //TODO // __fastcall OnWMFreeObject(TMessage VMsg);message WM_FREEOBJECT; __fastcall TForm1(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TForm1 *Form1; const NNN = 100; struct gate_type { int time_of_passing, timer, priority; bool active, is_breakpoint; } gate_mas[NNN + 1]; int D_input_mas[NNN + 1][NNN + 1], D_output_mas[NNN + 1][NNN + 1]; int marking_mas[NNN + 1]; // TODO byte int number_of_gates, number_of_positions, number_of_text; //--------------------------------------------------------------------------- #endif
13f0749d62d76f8c2dc0cf3d71f2a79ec0cdfff9
[ "C++" ]
19
C++
Bohdan0703/net-petri
7ab5e956f7e7ab8e4087d14a16d0d52acfdcbc0c
aabc1c2dc4102da38c002cc6c6fd5edec5be4881
refs/heads/master
<file_sep>class Team < ActiveRecord::Base belongs_to :owner, class_name: 'Employee', foreign_key: 'employee_id' has_many :team_members has_many :members, through: :team_members, source: :employee has_many :progress_reports end <file_sep>class Employee < ActiveRecord::Base has_many :team_members has_many :teams, through: :team_members has_many :progress_reports has_many :owned_teams, class_name: 'Team' end
089db4fdadd0548c53312aedc640044e353b1923
[ "Ruby" ]
2
Ruby
cjvirtucio87/julio-musical-doodle
8431cc911658898306a8146e30a24a935272028b
9b47594dbf94e53ba46a213cb1ef067051fe25ad
refs/heads/master
<repo_name>xialiang18/kcf_dsst<file_sep>/include/timer.hpp // Copyright [2019] <<EMAIL>> #pragma once // #ifndef PERFORMANCE // #define Timer(name) // #else // #define Timer(name) TimeLogger timer(name) #define Timer_Begin(name) TimeLogger *timer##name = new TimeLogger(#name) #define Timer_End(name) timer##name->~TimeLogger(); #include <map> #include <vector> #include <chrono> #include <iostream> class TimeLogger { public: TimeLogger(const std::string &name) : name_(name), start_(std::chrono::system_clock::now()) { } ~TimeLogger() { auto duration = std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::system_clock::now() - start_); durations_[name_].push_back(duration); printf("> Duration [%s]: %.5f ms\n", name_.c_str(), duration.count() / 1000.0); } static void Print(const std::string &name) { // ignore first log duration if vector size is greater than 1 int index = durations_[name].size() > 1 ? -1 : 0; int64_t total_milliseconds = 0; for (const auto &duration : durations_[name]) { ++index; if (index) { total_milliseconds += duration.count() / 1000.0; } } double time_in_milliseconds = total_milliseconds / index; printf("> Benchmark [%s]: %.5f ms\n", name.c_str(), time_in_milliseconds); } static void PrintAll() { for (auto it : durations_) { Print(it.first); } } private: std::string name_; std::chrono::time_point<std::chrono::system_clock> start_; static std::map<std::string, std::vector<std::chrono::microseconds>> durations_; }; //#endif<file_sep>/rebuild.sh #!/usr/bin/env bash cd build make -j4 mv track ..<file_sep>/src/tracker/fhogcuda.h #ifndef FHOGCUDA_H #define FHOGCUDA_H #include <stdio.h> #include "opencv2/imgproc/imgproc_c.h" #include "float.h" typedef struct{ int sizeX; int sizeY; int numFeatures; float *map; } CvLSVMFeatureMapCaskade; namespace kcfcuda { #define PI CV_PI #define EPS 0.000001 #define F_MAX FLT_MAX #define F_MIN -FLT_MAX // The number of elements in bin // The number of sectors in gradient histogram building #define NUM_SECTOR 9 // The number of levels in image resize procedure // We need Lambda levels to resize image twice #define LAMBDA 10 // Block size. Used in feature pyramid building procedure #define SIDE_LENGTH 8 #define VAL_OF_TRUNCATE 0.2f //modified from "_lsvm_error.h" #define LATENT_SVM_OK 0 #define LATENT_SVM_MEM_NULL 2 #define DISTANCE_TRANSFORM_OK 1 #define DISTANCE_TRANSFORM_GET_INTERSECTION_ERROR -1 #define DISTANCE_TRANSFORM_ERROR -2 #define DISTANCE_TRANSFORM_EQUAL_POINTS -3 #define LATENT_SVM_GET_FEATURE_PYRAMID_FAILED -4 #define LATENT_SVM_SEARCH_OBJECT_FAILED -5 #define LATENT_SVM_FAILED_SUPERPOSITION -6 #define FILTER_OUT_OF_BOUNDARIES -7 #define LATENT_SVM_TBB_SCHEDULE_CREATION_FAILED -8 #define LATENT_SVM_TBB_NUMTHREADS_NOT_CORRECT -9 #define FFT_OK 2 #define FFT_ERROR -10 #define LSVM_PARSER_FILE_NOT_FOUND -11 class fhogFeature { public: fhogFeature(); virtual ~fhogFeature(); int init(int imgWidth, int imgHeight, int channels, int k); int getFeatureMaps(const IplImage * image, const int k, CvLSVMFeatureMapCaskade **map); int normalizeAndTruncate(CvLSVMFeatureMapCaskade *map, const float alfa); int PCAFeatureMaps(CvLSVMFeatureMapCaskade *map); int allocFeatureMapObject(CvLSVMFeatureMapCaskade **obj, const int sizeX, const int sizeY, const int p); int freeFeatureMapObject (CvLSVMFeatureMapCaskade **obj); private: /* * device memory */ unsigned char* imageData1; //char* imageData2; float* dxData; float* dyData; float* r; int *alfa; float *d_map; float *d_partOfNorm; float *h_newData; float *d_newData; float *featureData; /* * host memory */ }; } #endif // FHOGCUDA_H <file_sep>/src/tracker/fhogcuda.cpp #include "fhogcuda.h" #include <chrono> #include <iostream> #include <cuda_runtime.h> #include "timer.hpp" extern void fhogCudaInit(int cell_size); extern void imageGrad(unsigned char *imageData, float *dxData, float *dyData, cv::Size size); extern void maxGrad(float *dx, float *dy, float *r, int *alfa, cv::Size size, int channels); extern void featureMaps(float *r, int *alfa, float *map, int k, int sizeX, int sizeY, int p, cv::Size size); extern void squareSum(float* map, float* partOfNorm, int numFeatures, int num, int size); extern void normalization(float *map, float* partOfNorm, float * newData, cv::Size size, float alfa); extern void PCAMaps(float *newData, float *featureData, cv::Size size, int xp, int yp); namespace kcfcuda { fhogFeature::fhogFeature() { } fhogFeature::~fhogFeature() { //cudaFree(imageData); cudaFree(dxData); cudaFree(dyData); cudaFree(r); cudaFree(alfa); cudaFree(d_map); cudaFree(d_partOfNorm); //cudaFree(d_newData); cudaFreeHost((void *)h_newData); cudaFree(featureData); } int fhogFeature::init(int imgWidth, int imgHeight, int channels, int k) { cudaError_t err = cudaSuccess; int imageSize = imgWidth * imgHeight * channels; int sizeX = imgWidth / k; int sizeY = imgHeight / k; fhogCudaInit(k); #ifdef PERFORMANCE Timer_Begin(cudaMalloc); #endif err = cudaMallocManaged((void **)&imageData1, sizeof(char) * imageSize); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector imageData (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } err = cudaMallocManaged((void **)&dxData, sizeof(float) * imageSize); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector dx (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } err = cudaMallocManaged((void **)&dyData, sizeof(float) * imageSize); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector dy (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } err = cudaMallocManaged((void **)&r, sizeof(float) * (imgWidth * imgHeight)); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector r (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } err = cudaMallocManaged((void **)&alfa, sizeof(int ) * (imgWidth * imgHeight * 2)); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector alfa (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } err = cudaMallocManaged((void **)&d_map, sizeof (float) * (sizeX * sizeY * 3 * NUM_SECTOR)); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector map (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } err = cudaMallocManaged((void **)&d_partOfNorm, sizeof(float) * (sizeX * sizeY)); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector partOfNorm (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //err = cudaHostAlloc((void**)&h_newData, sizeof(float) * ((sizeX - 2) * (sizeY - 2) * 12 * NUM_SECTOR), cudaHostAllocMapped); //err = cudaHostGetDevicePointer((void **)&d_newData, (void *)h_newData, 0); err = cudaMallocManaged((void**)&d_newData, sizeof(float) * ((sizeX - 2) * (sizeY - 2) * 12 * NUM_SECTOR)); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector newData (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } err = cudaMallocManaged((void**)&featureData, sizeof(float) * ((sizeX - 2) * (sizeY - 2) * (NUM_SECTOR * 3 + 4))); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector featureData (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } #ifdef PERFORMANCE Timer_End(cudaMalloc); #endif return err; } /* // Getting feature map for the selected subimage // // API // int getFeatureMaps(const IplImage * image, const int k, featureMap **map); // INPUT // image - selected subimage // k - size of cells // OUTPUT // map - feature map // RESULT // Error status */ int fhogFeature::getFeatureMaps(const IplImage *image, const int k, CvLSVMFeatureMapCaskade **map) { int sizeX, sizeY; int p, px; int height, width, numChannels; height = image->height; width = image->width ; sizeX = width / k; sizeY = height / k; px = 3 * NUM_SECTOR; p = px; allocFeatureMapObject(map, sizeX, sizeY, p); numChannels = image->nChannels; cudaError_t err = cudaSuccess; Timer_Begin(cudaMemcpy); std::cout << "size " << image->imageSize << std::endl; err = cudaMemcpy(imageData1, image->imageData, sizeof(char) * image->imageSize, cudaMemcpyHostToDevice); if(err != cudaSuccess){ fprintf(stderr, "Failed to allocate device vector getfeaturemaps1 (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } Timer_End(cudaMemcpy); //#ifdef PERFORMANCE //Timer_Begin(imageGrad); //#endif imageGrad(imageData1, dxData, dyData, cv::Size(image->widthStep, image->height)); //cudaDeviceSynchronize(); //#ifdef PERFORMANCE //Timer_End(imageGrad); //#endif //Timer_Begin(maxGrad); maxGrad(dxData, dyData, r, alfa, cv::Size(width, height), numChannels); //cudaDeviceSynchronize(); //Timer_End(maxGrad); //Timer_Begin(cudaMemset); cudaMemset(d_map, 0, sizeof (float) * (sizeX * sizeY * p)); //cudaDeviceSynchronize(); //Timer_End(cudaMemset); //Timer_Begin(featureMaps); featureMaps(r, alfa, d_map, k, sizeX, sizeY, p, cv::Size(width, height)); //cudaDeviceSynchronize(); //Timer_End(featureMaps); return LATENT_SVM_OK; } /* // Feature map Normalization and Truncation // // API // int normalizeAndTruncate(featureMap *map, const float alfa); // INPUT // map - feature map // alfa - truncation threshold // OUTPUT // map - truncated and normalized feature map // RESULT // Error status */ int fhogFeature::normalizeAndTruncate(CvLSVMFeatureMapCaskade *map, const float alfa) { int sizeX, sizeY, p, pp, xp; //float * newData; sizeX = map->sizeX; sizeY = map->sizeY; p = NUM_SECTOR; xp = NUM_SECTOR * 3; pp = NUM_SECTOR * 12; //Timer_Begin(squareSum); squareSum(d_map, d_partOfNorm, xp, p, sizeX * sizeY); //cudaDeviceSynchronize(); //Timer_End(squareSum); sizeX -= 2; sizeY -= 2; //newData = (float *)malloc (sizeof(float) * (sizeX * sizeY * pp)); //Timer_Begin(normalization); normalization(d_map, d_partOfNorm, d_newData, cv::Size(sizeX, sizeY), alfa); //cudaDeviceSynchronize(); //Timer_End(normalization); //cudaMemcpy(newData, d_newData, sizeof(float) * (sizeX * sizeY * pp), cudaMemcpyDeviceToHost); map->numFeatures = pp; map->sizeX = sizeX; map->sizeY = sizeY; //free (map->map); map->map = d_newData; return LATENT_SVM_OK; } /* // Feature map reduction // In each cell we reduce dimension of the feature vector // according to original paper special procedure // // API // int PCAFeatureMaps(featureMap *map) // INPUT // map - feature map // OUTPUT // map - feature map // RESULT // Error status */ int fhogFeature::PCAFeatureMaps(CvLSVMFeatureMapCaskade *map) { int i,j, ii, jj, k; int sizeX, sizeY, p, pp, xp, yp, pos1, pos2; float * newData; float val; float nx, ny; sizeX = map->sizeX; sizeY = map->sizeY; p = map->numFeatures; pp = NUM_SECTOR * 3 + 4; yp = 4; xp = NUM_SECTOR; nx = 1.0f / sqrtf((float)(xp * 2)); ny = 1.0f / sqrtf((float)(yp )); //newData = (float *)malloc (sizeof(float) * (sizeX * sizeY * pp)); //Timer_Begin(PCAFeatureMaps); //PCAMaps(d_newData, featureData, cv::Size(sizeX, sizeY), xp, yp); cudaDeviceSynchronize(); for(i = 0; i < sizeY; i++) { for(j = 0; j < sizeX; j++) { pos1 = ((i)*sizeX + j)*p; pos2 = ((i)*sizeX + j)*pp; k = 0; for(jj = 0; jj < xp * 2; jj++) { val = 0; for(ii = 0; ii < yp; ii++) { val += map->map[pos1 + yp * xp + ii * xp * 2 + jj]; }/*for(ii = 0; ii < yp; ii++)*/ featureData[pos2 + k] = val * ny; k++; }/*for(jj = 0; jj < xp * 2; jj++)*/ for(jj = 0; jj < xp; jj++) { val = 0; for(ii = 0; ii < yp; ii++) { val += map->map[pos1 + ii * xp + jj]; }/*for(ii = 0; ii < yp; ii++)*/ featureData[pos2 + k] = val * ny; k++; }/*for(jj = 0; jj < xp; jj++)*/ for(ii = 0; ii < yp; ii++) { val = 0; for(jj = 0; jj < 2 * xp; jj++) { val += map->map[pos1 + yp * xp + ii * xp * 2 + jj]; }/*for(jj = 0; jj < xp; jj++)*/ featureData[pos2 + k] = val * nx; k++; } /*for(ii = 0; ii < yp; ii++)*/ }/*for(j = 0; j < sizeX; j++)*/ }/*for(i = 0; i < sizeY; i++)*/ //cudaMemcpy(newData, featureData, sizeof(float) * (sizeX * sizeY * pp), cudaMemcpyDeviceToHost); //Timer_End(PCAFeatureMaps); //swop data map->numFeatures = pp; //free (map->map); map->map = featureData; return LATENT_SVM_OK; } //modified from "lsvmc_routine.cpp" int fhogFeature::allocFeatureMapObject(CvLSVMFeatureMapCaskade **obj, const int sizeX, const int sizeY, const int numFeatures) { int i; (*obj) = (CvLSVMFeatureMapCaskade *)malloc(sizeof(CvLSVMFeatureMapCaskade)); (*obj)->sizeX = sizeX; (*obj)->sizeY = sizeY; (*obj)->numFeatures = numFeatures; // (*obj)->map = (float *) malloc(sizeof (float) * // (sizeX * sizeY * numFeatures)); // for(i = 0; i < sizeX * sizeY * numFeatures; i++) // { // (*obj)->map[i] = 0.0f; // } return LATENT_SVM_OK; } int fhogFeature::freeFeatureMapObject (CvLSVMFeatureMapCaskade **obj) { if(*obj == NULL) return LATENT_SVM_MEM_NULL; //free((*obj)->map); free(*obj); (*obj) = NULL; return LATENT_SVM_OK; } } <file_sep>/build.sh #!/usr/bin/env bash if [ -d "build" ]; then rm -rf build fi mkdir build && cd build #cmake -DPRECISION=ON \ cmake -DRESULT_SAVE_PHOTO=ON \ .. # -DPERFORMANCE=ON \ # .. #cmake .. make -j4 mv track ..<file_sep>/CMakeLists.txt CMAKE_MINIMUM_REQUIRED(VERSION 3.0) PROJECT(track) ADD_DEFINITIONS(-std=c++11) ADD_DEFINITIONS(-g -O3) FIND_PACKAGE(OpenCV REQUIRED) if(NOT OPENCV_FOUND) MESSAGE(WARNING "OpenCV not found!") else() INCLUDE_DIRECTORIES(${OpenCV_INCLUDE_DIRS}) endif() FIND_PACKAGE(CUDA REQUIRED) INCLUDE_DIRECTORIES(src/tracker) INCLUDE_DIRECTORIES(include) INCLUDE_DIRECTORIES(src) IF(PRECISION) ADD_DEFINITIONS(-DPRECISION) ENDIF() IF(RESULT_SAVE_PHOTO) ADD_DEFINITIONS(-DRESULT_SAVE_PHOTO) ENDIF() IF(PERFORMANCE) ADD_DEFINITIONS(-DPERFORMANCE) ENDIF() FILE(GLOB_RECURSE sourcefiles "src/tracker/*.cpp" "src/*.cpp") #SET(SRC main.cpp tracker/fhog.cpp tracker/kcftracker.cpp) #SET(CUDA_SRC src/tracker/fhog.cu) FILE(GLOB_RECURSE CUDA_SRC "src/tracker/*.cu") SET(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_53,code=sm_53;-std=c++11;) #ADD_EXECUTABLE(track ${SRC}) CUDA_ADD_EXECUTABLE(track ${sourcefiles} ${CUDA_SRC}) TARGET_LINK_LIBRARIES(track ${OpenCV_LIBS}) TARGET_LINK_LIBRARIES(track -lpthread -lm -lstdc++) SET(CMAKE_BUILD_TYPE "Release") IF(CMAKE_COMPILER_IS_GNUCC) set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0") set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -O0") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wall -O3") ENDIF(CMAKE_COMPILER_IS_GNUCC) <file_sep>/src/main.cpp #include <iostream> #include <chrono> #include <opencv2/opencv.hpp> #include <kcftracker.hpp> #include <string> #include <fstream> #include <sstream> #include <timer.hpp> #include <time.h> #include <sys/stat.h> #include <sys/types.h> /* std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now(); std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now(); std::chrono::duration<double> time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1); std::cout << "solve time cost " << time_used.count() << " seconds." << std::endl; */ //#ifdef PERFORMANCE std::map<std::string, std::vector<std::chrono::microseconds>> TimeLogger::durations_; //#endif #define max(a, b) (a) > (b) ? (a) : (b) #define min(a, b) (a) < (b) ? (a) : (b) float calc_iou(cv::Rect res_roi, cv::Rect gt_roi) { float iou; float resarea, gtarea, overlap; resarea = res_roi.width * res_roi.height; gtarea = gt_roi.width * gt_roi.height; float lx, ly, rx, ry; lx = max(res_roi.x, gt_roi.x); ly = max(res_roi.y, gt_roi.y); rx = min(res_roi.x + res_roi.width, gt_roi.x + gt_roi.width); ry = min(res_roi.y + res_roi.height, gt_roi.y + gt_roi.height); overlap = (rx - lx) * (ry - ly); iou = overlap / (resarea + gtarea - overlap + 1e-6); return iou; } void verify_result(std::string result, std::string gt, float threshold) { std::fstream resfile(result), gtfile(gt); std::string resline, gtline; cv::Rect_<float> res_roi, gt_roi; int cnt = 0; while(getline(resfile, resline)){ getline(gtfile, gtline); std::istringstream resstream(resline), gtstream(gtline); float resdata[4], gtdata[4]; char s; for(int i = 0; i < 4; i++){ resstream >> resdata[i]; resstream >> s; gtstream >> gtdata[i]; gtstream >> s; } res_roi.x = resdata[0]; res_roi.y = resdata[1]; res_roi.width = resdata[2]; res_roi.height = resdata[3]; gt_roi.x = gtdata[0]; gt_roi.y = gtdata[1]; gt_roi.width = gtdata[2]; gt_roi.height = gtdata[3]; float iou; float resarea, gtarea, overlap; resarea = res_roi.width * res_roi.height; gtarea = gt_roi.width * gt_roi.height; float lx, ly, rx, ry; lx = max(res_roi.x, gt_roi.x); ly = max(res_roi.y, gt_roi.y); rx = min(res_roi.x + res_roi.width, gt_roi.x + gt_roi.width); ry = min(res_roi.y + res_roi.height, gt_roi.y + gt_roi.height); overlap = (rx - lx) * (ry - ly); iou = overlap / (resarea + gtarea - overlap + 1e-6); cnt++; if(iou < threshold){ std::cout << "track failed!" << std::endl; }else{ std::cout << "Test " << cnt << " track success!" << std::endl; } } resfile.close(); gtfile.close(); } extern int test(void); cv::Mat move_image(cv::Mat image, int x, int y){ int width = image.cols; int height = image.rows; cv::Mat a = image.colRange(0, (width - x) % width); cv::Mat b = image.colRange((width - x) % width, width); cv::Mat temp_x = b.t(); a = a.t(); temp_x.push_back(a); temp_x = temp_x.t(); a = temp_x.rowRange(0, (height - y) % height); b = temp_x.rowRange((height - y) % height, height); b.push_back(a); return b; } void data_generate() { srand((unsigned int)time(0)); for(int length = 20; length < 420; length += 20){ int x = 496, y = 419, width = 40, height = 42; int cnt = 0; cv::Mat frame = cv::imread("data/ball1/00000001.jpg"); int frame_width = frame.cols; int frame_height = frame.rows; char path[50]; sprintf(path, "data/dist/dist_%d", length); mkdir(path, S_IRUSR | S_IWUSR | S_IXUSR | S_IRWXG | S_IRWXO); char gt[50]; sprintf(gt, "data/dist/dist_%d/gt.txt", length); std::ofstream fout(gt, std::ios::app); while(cnt < 1000){ float theta = (double)rand() / RAND_MAX * 2 * 3.141592654; int dx = (int)(length * cos(theta)); int dy = (int)(length * sin(theta)); if(x + dx >= 0 && x + dx + width < frame_width && y + dy >= 0 && y + dy + height < frame_height){ cnt++; frame = move_image(frame, dx, dy); x = x + dx; y = y + dy; //std::string data = "data/dist/dist_"; //data += length + "/" + cnt + ".jpg"; char data[100]; sprintf(data, "data/dist/dist_%d/%d.jpg", length, cnt); //sprintf(data, "") cv::imwrite(data, frame); fout << x << "," << y << "," << width << "," << height << std::endl; } } } } void test_search() { Tracker *tracker = new KCFTracker(); for(int length = 20; length < 420; length += 20){ std::cout << "running " << length << std::endl; char path[50], gt[50]; sprintf(gt, "data/dist/dist_%d/gt.txt", length); std::ifstream fin(gt); std::string ini; std::getline(fin, ini); fin.close(); std::istringstream temp(ini); char s; cv::Rect roi; temp >> roi.x >> s >> roi.y >> s >> roi.width >> s >> roi.height; cv::Mat frame; char outfile[50]; sprintf(outfile, "data/dist/dist_%d/result.txt", length); std::ofstream fout(outfile); int initFlag = 1; for(int i = 1; i <= 1000; i++){ sprintf(path, "data/dist/dist_%d/%d.jpg", length, i); frame = cv::imread(path); if(initFlag) tracker->init( roi, frame ); else{ roi = tracker->update(frame); } fout << roi.x << "," << roi.y << "," << roi.width << "," << roi.height << std::endl; initFlag = 0; } fout.close(); char result[50]; sprintf(result, "test_res/result_%d.txt", length); std::ofstream ff(result); std::vector<float> res_iou; std::ifstream gt_i(gt), res_i(outfile); std::string res_line, gt_line; cv::Rect gt_p, res_p; float dist = 0; while(getline(res_i, res_line) && getline(gt_i, gt_line)){ std::istringstream res_temp(res_line); std::istringstream gt_temp(gt_line); char s; res_temp >> res_p.x >> s >> res_p.y >> s >> res_p.width >> s >> res_p.height; gt_temp >> gt_p.x >> s >> gt_p.y >> s >> gt_p.width >> s >> gt_p.height; //dist += std::sqrt(std::pow(res_p.x - gt_p.x, 2.0) + std::pow(res_p.y - gt_p.y, 2.0)) / 1000.0; float iou = calc_iou(res_p, gt_p); res_iou.push_back(iou); } gt_i.close(); res_i.close(); for(float base = 0.1; base <= 1.001; base += 0.1){ dist = 0; for(auto v : res_iou){ if(v >= base){ dist++; } } dist /= 1000.0; ff << base << " " << dist << std::endl; } ff.close(); } } void test_scale() { for(int i = 0; i < 2; i++){ char result[50], gt[50], outfile[50]; if(i == 0){ sprintf(result, "res/result_scale.txt"); sprintf(outfile, "res/result_scale_1.txt"); }else{ sprintf(result, "res/result.txt"); sprintf(outfile, "res/result_1.txt"); } sprintf(gt, "res/groundtruth_rect.txt"); std::ofstream ff(outfile); std::vector<float> res_iou; std::ifstream gt_i(gt), res_i(result); std::string res_line, gt_line; cv::Rect gt_p, res_p; float dist = 0; int cnt = 0; while(getline(res_i, res_line) && getline(gt_i, gt_line)){ cnt++; std::istringstream res_temp(res_line); std::istringstream gt_temp(gt_line); char s; res_temp >> res_p.x >> s >> res_p.y >> s >> res_p.width >> s >> res_p.height; gt_temp >> gt_p.x >> s >> gt_p.y >> s >> gt_p.width >> s >> gt_p.height; //dist += std::sqrt(std::pow(res_p.x - gt_p.x, 2.0) + std::pow(res_p.y - gt_p.y, 2.0)) / 1000.0; float iou = calc_iou(res_p, gt_p); res_iou.push_back(iou); } gt_i.close(); res_i.close(); for(float base = 0.1; base <= 1.001; base += 0.05){ dist = 0; for(auto v : res_iou){ if(v >= base){ dist++; } } dist /= (float)cnt; ff << base << " " << dist << std::endl; } ff.close(); } } int main() { std::stringstream photoName; std::string picture_path = "data/ball1/"; //std::string picture_path = "data/cat/"; //std::string picture_path = "data/CarScale/img/"; //std::string picture_path = "data/dog/"; //std::string picture_path = "data/FaceOcc1/img/"; std::string result_file = "res/result.txt"; int num = 105; int initFlag = 1; //cv::Rect roi(556, 203, 222, 209); cv::Rect roi(496, 419, 40, 42); //cv::Rect roi(6, 166, 42, 26); //cv::Rect roi(205, 218, 69, 40); //cv::Rect roi(118, 69, 114, 162); bool HOG = true; bool FIXEDWINDOW = false; bool MULTISCALE = true; bool LAB = true; Tracker *tracker = new KCFTracker(HOG, FIXEDWINDOW, MULTISCALE, LAB); std::ofstream result(result_file); cv::Mat frame; for(int i = 1; i <= num; i++){ photoName.clear(); photoName << picture_path << std::setfill('0') << std::setw(8) << i << ".jpg"; //photoName << picture_path << i << ".jpg"; frame = cv::imread(photoName.str().c_str()); if(frame.empty()){ std::cout << "frame read error!" << std::endl; break; } //#ifdef PERFORMANCE Timer_Begin(main); //#endif if(initFlag) tracker->init( roi, frame ); else{ roi = tracker->update(frame); } //#ifdef PERFORMANCE Timer_End(main); //#endif cv::rectangle( frame, cv::Point( roi.x, roi.y ), cv::Point( roi.x + roi.width, roi.y + roi.height), cv::Scalar( 0, 255, 255 ), 1, 8 ); #ifdef RESULT_SAVE_PHOTO char result_photo[50]; sprintf(result_photo, "res/photo/%d.jpg", i); cv::imwrite(result_photo, frame); #endif result << roi.x << "," << roi.y << "," << roi.width << "," << roi.height << std::endl; initFlag = 0; photoName.str(""); } result.close(); #ifdef PRECISION std::string gt_file = "res/gt.txt"; verify_result(result_file, gt_file, 0.7); #endif //test(); return 0; }
300c6858baf6bbdd0246d2bc4b5f659f8a3cfb12
[ "CMake", "C++", "Shell" ]
7
C++
xialiang18/kcf_dsst
3c00ba5628b70babc9c0fc79db151610512a5811
5ff9dd2091db19dce3f1ee4271a4004a74fd00b3
refs/heads/main
<file_sep>let tijera = 1; let papel = 2; let piedra = 3; let cpu; var random = Math.ceil(Math.random() *3) if (random === 1){ cpu = "tijera"; } else if (random === 2) { cpu = "papel"; } else { cpu = "piedra"; } let eleccion = prompt("Cual eliges: Piedra, Papel o Tijera"); if (eleccion == "piedra"){ console.log("Elegiste Piedra mientras el cpu eligio "+ cpu); } else if (eleccion == "papel"){ console.log("Elegiste Papel mientras el cpu eligio "+ cpu); } else if (eleccion == "tijera"){ console.log("Elegiste Tijera mientras el cpu eligio "+ cpu); }
b0ef627a57e37ef920218d8a895f01f24f67c283
[ "JavaScript" ]
1
JavaScript
Viberth/PiedraPapelTijera
985696f9b805b91d3591a1d2efd2a4103299d733
dca3572983db6448c8c88eea048fe82d5a3a3172
refs/heads/master
<file_sep>/* <NAME> CNT 4714 project3 */ package project3; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.util.Callback; /** * * @author abmat */ public class FXMLDocumentController implements Initializable { public final DBUtil util = new DBUtil(); public ObservableList<ObservableList> data; @FXML public TableView tableView; public Label dbStatus; public Button clearResultsButton; public TextField usernameField = new TextField(); public Button executeSqlButton; public Button clearSqlButton; public Button connectDbButton; public TextField passwordField = new TextField(); public ComboBox drivers; public ComboBox URLS; public TextArea userSqlCommandText = new TextArea(); @FXML private void handleConnectDbButton(ActionEvent event) throws SQLException { util.setDriver(drivers.getValue().toString()); util.setDbURL(URLS.getValue().toString()); util.setUser(usernameField.getText()); util.setPassw(passwordField.getText()); try { util.dbConnect(); dbStatus.setText("Database Connected!"); } catch (SQLException | ClassNotFoundException ex) { Alert alert = new Alert(AlertType.ERROR, ex.getMessage()); alert.showAndWait(); Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); } util.dbDisconnect(); } @FXML private void handleExecuteSqlButton(ActionEvent event) { tableView.getItems().clear(); tableView.getColumns().clear(); try { System.out.println(userSqlCommandText.getText()); sqlCommand(userSqlCommandText.getText()); } catch (SQLException | ClassNotFoundException ex) { Alert alert = new Alert(AlertType.ERROR, ex.getMessage()); alert.showAndWait(); Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML private void handleClearSqlButton(ActionEvent event) { userSqlCommandText.setText(""); } @FXML private void handleClearResultsButton(ActionEvent event) { tableView.getItems().clear(); tableView.getColumns().clear(); } @FXML public void sqlCommand(String sql) throws SQLException, ClassNotFoundException { ObservableList<ObservableList> data = FXCollections.observableArrayList(); ResultSet rs; util.dbConnect(); Statement st = util.getConnection().createStatement(); boolean status = st.execute(sql); if (status) { rs = st.getResultSet(); for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) { //We are using non property style for making dynamic table final int j = i; TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i + 1)); col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList, String>, ObservableValue<String>>() { public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList, String> param) { return new SimpleStringProperty(param.getValue().get(j).toString()); } }); tableView.getColumns().addAll(col); } while (rs.next()) { //Iterate Row ObservableList<String> row = FXCollections.observableArrayList(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { //Iterate Column row.add(rs.getString(i)); } System.out.println("Row [1] added " + row); data.add(row); } tableView.setItems(data); } else { int count = st.getUpdateCount(); Alert alert = new Alert(AlertType.INFORMATION, "Performed " + count + " Updates"); alert.showAndWait(); } util.dbDisconnect(); } @Override public void initialize(URL url, ResourceBundle rb) { // TODO } public void setData() { String[] JDBC_DRIVERS = {"com.mysql.cj.jdbc.Driver"}; String[] DB_URL = {"jdbc:mysql://localhost:3306/bikedb", "jdbc:mysql://localhost:3306/project3"}; drivers.getItems().clear(); URLS.getItems().clear(); drivers.getItems().addAll(JDBC_DRIVERS[0]); URLS.getItems().addAll(DB_URL[0], DB_URL[1]); } } <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. */ package project3; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.TableView; import javafx.util.Callback; /** * * @author abmat */ public class DBUtil { private String JDBC_DRIVER; private String DB_URL; //Connection private Connection conn = null; private String USER; private String PASSW; public void setDriver(String driver) { this.JDBC_DRIVER = driver; } public String getDriver() { return this.JDBC_DRIVER; } public void setDbURL(String url) { this.DB_URL = url; } public String getDbURL() { return this.DB_URL; } public void setUser(String name) { this.USER = name; } public String getUser() { return this.USER; } public void setPassw(String passw) { this.PASSW = passw; } public String getPassw() { return this.PASSW; } public Connection getConnection() { return this.conn; } //Establlish Connection to selected database public void dbConnect() throws SQLException, ClassNotFoundException { try { Class.forName(this.getDriver()); } catch (ClassNotFoundException e) { System.out.println("No Driver"); throw e; } try { this.conn = DriverManager.getConnection(this.getDbURL(), this.getUser(), this.getPassw()); } catch (SQLException e) { System.out.println("Connection Failed" + e); throw e; } } //Disconnect from Database public void dbDisconnect() throws SQLException { try { if (this.conn != null && !this.conn.isClosed()) { this.conn.close(); } } catch (SQLException e) { throw e; } } }
d003269e85609fee68528dae62ff4593cd9c4db5
[ "Java" ]
2
Java
Barthor/sqlProject
2d8ef043021dcf99b3d1f7eed1184af4d183ebe4
162fd6743d6bcd83f602cc022d7c98d105ed8ffb
refs/heads/main
<file_sep>package main import "fmt" type ErrNegativeSqrt float64 func (e ErrNegativeSqrt) Error() string { return "cannot Sqrt negative number:" + fmt.Sprint(float64(e)) } func Sqrt(x float64) (float64, error) { if x < 0 { return 0, ErrNegativeSqrt(x) } return x, nil } func main() { fmt.Println(Sqrt(2)) fmt.Println(Sqrt(-2)) } <file_sep>module go-tour go 1.17
62c7402cf0437f4b5e19889c2fdc84555a411f63
[ "Go Module", "Go" ]
2
Go
im-wmkong/go-tour
a7d3373c0b22f27bef18c1f080f07ae61c3a3740
5b052126d69223e59ea1666d1b4c1f7b8d43cf55
refs/heads/master
<file_sep>class NavBar extends HTMLElement { connectedCallback() { this.id = this.getAttribute('id') || null this.src = this.getAttribute('src') || null this.alt = this.getAttribute('alt') || null this.render() } render() { this.innerHTML = ` <nav class="transparent z-depth-0"> <div class="nav-wrapper container"> <a href="#" class="brand-logo" id="logo-container"> <img src=${ this.src } alt=${ this.alt } /> </a> ${ this.id === 'index-navbar' ? '<a href="#" class="sidenav-trigger" data-target="nav-mobile"><img src="./src/images/icon-bar.svg" class="icon-bar" alt="Icon Bar" /></a>' : this.id === 'club-navbar' ? `<a href="./index.html#league" class="btn black-text btn-back"> <div> <i class="material-icons">arrow_back</i>Back </div> </a>` : '' } <ul class="topnav hide-on-med-and-down"></ul> <ul class="sidenav" id="nav-mobile"></ul> </div> </nav> ` } } customElements.define('nav-bar', NavBar)<file_sep>const dbPromised = idb.open('yubal', 1, upgradeDB => { const clubObjectStore = upgradeDB.createObjectStore('clubs', { keyPath: 'id' }) clubObjectStore.createIndex('club_name', 'club_name', { unique: false }) }) const getClubFavorite = () => { return new Promise((resolve, reject) => { dbPromised .then(db => { const tx = db.transaction('clubs', 'readonly') const store = tx.objectStore('clubs') return store.getAll() }) .then(club => { resolve(club) }) }) } const saveClubFavorite = club => { dbPromised .then(db => { const tx = db.transaction('clubs', 'readwrite') const store = tx.objectStore('clubs') store.put(club) return tx.complete }) .then(() => M.toast({ html: 'This club is your favorite club!' })) } const deleteClubFavorite = club => { dbPromised .then(db => { const tx = db.transaction('clubs', 'readwrite') const store = tx.objectStore('clubs') store.delete(club) return tx.complete }) .then(() => M.toast({ html: 'You have deleted your favorite club' })) } export { saveClubFavorite, getClubFavorite, deleteClubFavorite } <file_sep>class TablePlayerScorers extends HTMLElement { set setScorers(scorers) { this._scorers = scorers this.count = 0 this.render() } render() { this.innerHTML = ` <table> <thead> <tr> <th>Pos</th> <th>Name Player</th> <th>Total</th> </tr> </thead> <tbody> ${ this._scorers.map(value => ( ` <tr> <td>${ this.count+=1 }</td> <td>${ value.player.name }</td> <td>${ value.numberOfGoals }</td> </tr> ` )).join(' ') } </tbody> </table> ` } } customElements.define('table-scorers', TablePlayerScorers)<file_sep>class TableStandings extends HTMLElement { set setStandings(standings) { this._standings = standings this.render() } render() { this.innerHTML = ` <table> <thead> <tr> <th>Pos</th> <th>Name Club</th> <th>P</th> <th>W</th> <th>L</th> <th>D</th> <th>PT</th> </tr> </thead> <tbody> ${ this._standings.standings[0].table.map(value => ( ` <tr class="tooltiped" data-position="top" data-tooltip="Click to more detail !" > <td>${ value.position }</td> <td> <a href="./club.html?idLeague=${ this._standings.competition.id }&id=${ value.team.id }" class="black-text" data-idClub="${ value.team.id }" > ${ value.team.name } </a> </td> <td>${ value.playedGames }</td> <td>${ value.won }</td> <td>${ value.lost }</td> <td>${ value.draw }</td> <td>${ value.points }</td> </tr> ` )).join(' ') } </tbody> </table> ` this.elems = this.querySelectorAll('.tooltiped') this.instance = M.Tooltip.init(this.elems) } } customElements.define('table-standings', TableStandings)<file_sep>class TableMatches extends HTMLElement { set setMatches(matches) { this._matches = matches this.render() } render() { this.innerHTML = ` <div class="row match"> ${ this._matches.map(value => ( ` <div class="row"> <div class="col s7 l4 offset-l1 right-align">${ value.homeTeam.name }</div> <div class="col s4 l2 center-align red match-score">${ value.score.fullTime.homeTeam } : ${ value.score.fullTime.awayTeam }</div> <div class="col s12 l4 left-align">${ value.awayTeam.name }</div> </div> ` )).join(' ') } </div> ` } } customElements.define('table-match', TableMatches)<file_sep>import '../components/Preloader.js' const base_url = 'https://api.football-data.org/' const token = 'cc92f201a96b49f79ea79d54275ba9d7' const loading = document.getElementById('loading') const clubDetail = document.getElementById('club-detail') const mainContent = document.getElementsByTagName('main-content')[0] const fetchAPI = url => { return fetch(url, { headers: { "X-Auth-Token": token } }) } const showLoading = () => { loading.style.display = 'block' loading.innerHTML = '<pre-load></pre-load>' if (mainContent !== undefined && mainContent !== null) { mainContent.style.display = 'none' } if (clubDetail !== undefined && clubDetail !== null) { clubDetail.style.display = 'none' } } const hideLoading = () => { loading.style.display = 'none' loading.innerHTML = '' if (mainContent !== undefined && mainContent !== null) { mainContent.style.display = 'block' } if (clubDetail !== undefined && clubDetail !== null) { clubDetail.style.display = 'block' } } const getStandings = idLeague => { return new Promise((resolve, reject) => { if ('caches' in window) { caches.match(`${ base_url }v2/competitions/${ idLeague }/standings?standingType=TOTAL`).then(response => { if (response) { response.json().then(data => resolve(data)) } }) } fetchAPI(`${ base_url }v2/competitions/${ idLeague }/standings?standingType=TOTAL`) .then(response => { if (response.status !== 200) { reject(new Error(response.statusText)) } else { return response.json() } }) .then(responseJson => { resolve(responseJson) }) .catch(err => { console.log(err) reject(err) }) }) } const getScorers = idLeague => { showLoading() return new Promise((resolve, reject) => { if ('caches' in window) { caches.match(`${ base_url }v2/competitions/${ idLeague }/scorers`).then(response => { if (response) { response.json().then(data => resolve(data)) } }) } fetchAPI(`${ base_url }v2/competitions/${ idLeague }/scorers`) .then(response => { if (response.status !== 200) { reject(new Error(response.statusText)) } else { return response.json() } }) .then(responseJson => resolve(responseJson)) .finally(() => { hideLoading() }) .catch(err => reject(err)) }) } const getClubById = idClub => { showLoading() return new Promise((resolve, reject) => { // Request if ('caches' in window) { caches.match(`${ base_url }v2/teams/${ idClub }`).then(response => { if (response) { response.json().then(data => resolve(data)) } }) } fetchAPI(`${ base_url }v2/teams/${ idClub }`) .then(response => { if (response.status !== 200) { reject(new Error(response.statusText)) } else { return response.json() } }) .then(responseJson => resolve(responseJson)) .finally(() => { hideLoading() }) .catch(err => reject(err)) }) } const getMatchesClubById = idClub => { return new Promise((resolve, reject) => { if ('caches' in window) { caches.match(`${ base_url }v2/teams/${ idClub }/matches?status=FINISHED`).then(response => { if (response) { response.json() .then(data => resolve(data)) } }) } fetchAPI(`${ base_url }v2/teams/${ idClub }/matches?status=FINISHED`) .then(response => { if (response.status !== 200) { reject(new Error(response.statusText)) } else { return response.json() } }) .then(responseJson => resolve(responseJson)) .catch(err => reject(err)) }) } export { getStandings, getScorers, getClubById, getMatchesClubById}<file_sep>import './src/components/NavBar.js' import './src/components/MainContent.js' import './src/components/CardImage.js' import './src/components/WrapTable.js' import main from './src/view/main.js' import club from './src/view/club.js' document.getElementById('index') ? document.addEventListener('DOMContentLoaded', main) : document.addEventListener('DOMContentLoaded', club)<file_sep>class StandingsDetail extends HTMLElement { set setStandingsDetail(standings) { this._standings = standings this.render() } render() { this.innerHTML = ` <div class="row stand-detail"> <div class="col s12">Position</div> <p class="stand-detail-number">${ this._standings.position }</p> <div class="col s6 m4 l4 shadow-stand-detail offset-l2 offset-m4">Play</div> <div class="col s6 m4 l4 red">${ this._standings.playedGames }</div> <div class="col s6 m4 l4 shadow-stand-detail offset-l2 offset-m4">Win</div> <div class="col s6 m4 l4 red">${ this._standings.won }</div> <div class="col s6 m4 l4 shadow-stand-detail offset-l2 offset-m4">Lost</div> <div class="col s6 m4 l4 red">${ this._standings.lost }</div> <div class="col s6 m4 l4 shadow-stand-detail offset-l2 offset-m4">Draw</div> <div class="col s6 m4 l4 red">${ this._standings.draw }</div> <div class="col s6 m4 l4 shadow-stand-detail offset-l2 offset-m4">GD</div> <div class="col s6 m4 l4 red">${ this._standings.goalDifference }</div> <div class="col s6 m4 l4 shadow-stand-detail offset-l2 offset-m4">PTS</div> <div class="col s6 m4 l4 red">${ this._standings.points }</div> </div> ` } } customElements.define('standings-detail', StandingsDetail)<file_sep>importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.6.3/workbox-sw.js') // Cek Workbox if (workbox) console.log('Workbox berhasil dimuat') else console.log('Workbox gagal dimuat') // Precaching workbox.precaching.precacheAndRoute([ { url: '/', revision: '1' }, { url: '/index.html', revision: '1' }, { url: '/club.html', revision: '2' }, { url: '/nav.html', revision: '1' }, { url: '/app.js', revision: '1' }, { url: '/registrasi.js', revision: '1' }, { url: '/manifest.json', revision: '1' }, { url: '/src/components/CardImage.js', revision: '1' }, { url: '/src/components/MainContent.js', revision: '1' }, { url: '/src/components/NavBar.js', revision: '1' }, { url: '/src/components/Preloader.js', revision: '1' }, { url: '/src/components/StandingsDetail.js', revision: '1' }, { url: '/src/components/TableMatches.js', revision: '1' }, { url: '/src/components/TablePlayerScorers.js', revision: '1' }, { url: '/src/components/TableSquad.js', revision: '1' }, { url: '/src/components/TableStandings.js', revision: '1' }, { url: '/src/components/WrapTab.js', revision: '1' }, { url: '/src/components/WrapTable.js', revision: '1' }, { url: '/src/data/api.js', revision: '1' }, { url: '/src/data/db.js', revision: '1' }, { url: '/src/data/idb.js', revision: '1' }, { url: '/src/stylesheets/materialize.min.css', revision: '1' }, { url: '/src/stylesheets/style.css', revision: '1' }, { url: '/src/view/club.js', revision: '1' }, { url: '/src/view/main.js', revision: '1' }, { url: '/src/view/materialize.min.js', revision: '1' } ], { ignoreUrlParametersMatching: [/.*/] }) // Caching workbox.routing.registerRoute( new RegExp('/images/'), workbox.strategies.cacheFirst({ cacheName: 'images' }) ) workbox.routing.registerRoute( new RegExp('/fonts/'), workbox.strategies.cacheFirst({ cacheName: 'fonts-webfont' }) ) workbox.routing.registerRoute( new RegExp('/pages/'), workbox.strategies.staleWhileRevalidate({ cacheName: 'pages' }) ) workbox.routing.registerRoute( /^https:\/\/api\.football\-data\.org\/v2\//, workbox.strategies.staleWhileRevalidate({ cacheName: 'api-football' }) ) // Push self.addEventListener('push', function(event) { let body if (event.data) { body = event.data.text() } else { body = 'Push message no payload' } const options = { body: body, badge: './src/images/icons/icon-144x144.png', icon: './src/images/icons/icon-192x192.png', vibrate: [100, 50, 100], data: { dateOfArrival: Date.now(), primaryKey: 1 } } event.waitUntil( self.registration.showNotification('Yubal', options) ) })<file_sep>import './TableStandings.js' import './TablePlayerScorers.js' class WrapTable extends HTMLElement { connectedCallback() { this.title = this.getAttribute('title') || null this.id = this.getAttribute('id') || null this.render() } render() { this.innerHTML = ` <div class="white row wrapper"> <div class="col s12 m12 l12 ${ this.id === 'standings' ? 'standings': 'scorers' }"> <h5 class="center-align"> <i class="material-icons">${ this.id === 'standings' ? 'event_note' : 'gps_fixed' }</i> ${ this.title } </h5> </div> <div class="col s12 m12 l12 wrap-content" id=${ this.id }> ${ (this.id === 'standings') ? '<table-standings></table-standings>' : (this.id === 'scorers') && '<table-scorers></table-scorers>' } </div> </div> ` } } customElements.define('wrap-table', WrapTable)<file_sep>class PreLoader extends HTMLElement { connectedCallback() { this.render() } render() { this.innerHTML = ` <div class="progress mx-auto"> <div class="indeterminate yellow"></div> </div> ` } } customElements.define('pre-load', PreLoader)<file_sep><h1 align="center">Yubal</h1> <p align="center"> <img src="./src/images/icons/icon-512x512.png" alt="Logo" width="150" /> </p> <p align="justify">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Yubal merupakan sebuah website yang terkait dengan dunia sepak bola, website ini telah menerapkan PWA (Progressice Web Apps) serta untuk tampilannya saya menggunakan framework CSS yaitu Materialize CSS dan untuk melakukan caching saya menggunakan Workbox.</p> <br /> <br /> ## Link <a href="https://yubal-jgr.web.app">yubal-jgr.web.app</a> ## Dokumentasi Anda dapat melihatnya pada folder doc ## Tampilan pada laptop <img src="./doc/yubal-web-home.png" alt="Home on laptop" width="700" /> ## Tampilan pada mobile <img src="./doc/yubal-mobile-home.png" alt="Home on mobile" /> <file_sep>import '../components/Preloader.js' import '../../registrasi.js' import '../data/idb.js' import { getClubFavorite, deleteClubFavorite } from '../data/db.js' import { getStandings, getScorers } from '../data/api.js' import club from './club.js' const main = () => { const sidenav = document.querySelector('.sidenav') const content = document.querySelector('#body-content') let page = window.location.hash.substr(1) const getIdLeague = area => { switch (area) { case 'Germany': return 2002 break case 'England': return 2021 break case 'Spain': return 2014 break case 'Italy': return 2019 break case 'France': return 2015 break default: break } } const getFavorite = async () => { // Favorite const favorite = document.getElementById('favorite-section') let clubs = '' const resultFavorite = await getClubFavorite() .then(data => { data.forEach(value => { let url = value.crestUrl url = url.replace(/^http:\/\//i, 'https://') let idLeague = getIdLeague(value.area.name) clubs += ` <div class="col s12 m6 l4 container-fluid"> <div class="row"> <div class="col s12 center-align"> <img src="${ url }" alt="${ value.name }" class=" img-tab"> </div> <div class="col s12 transparent favorite"> <h4 class="white-text favorite-title">${ value.name }</h4> <table class="favorite-table"> <tr> <td><i class="material-icons">home</i></td> <td>${ value.venue }</td> </tr> <tr> <td><i class="material-icons">public</i></td> <td><a href="${ value.website }">${ value.website }</a></td> </tr> <tr> <td><i class="material-icons">palette</i></td> <td>${ value.clubColors }</td> </tr> <tr> <td><i class="material-icons">golf_course</i></td> <td>${ value.address }</td> </tr> </table> <a href="./club.html?idLeague=${ idLeague }&id=${ value.id }&favorite=true" class="btn waves-effect waves-light teal my-1" > Show Detail </a> <a class="btn red waves-effect waves-light remove my-1" data-idClub=${ value.id } > Remove </a> </div> </div> </div> ` }) favorite.innerHTML = clubs const urlParams = new URLSearchParams(window.location.search) const idClub = urlParams.get('id') const btnRemove = document.querySelectorAll('.remove') btnRemove.forEach(btn => { btn.addEventListener('click', e => { deleteClubFavorite(parseInt(e.target.dataset.idclub)) window.location.reload() }) }) // btnRemove.addEventListener('click', function() { // // }) if (data.length === 0) { throw new Error() } }) .catch(() => favorite.innerHTML = '<h2 class="center-align grey-text">You have not selected your favorite club</h2>') } const loadedPage = page => { const xhr = new XMLHttpRequest() xhr.onreadystatechange = async function() { if (this.readyState === 4) { if (this.status === 200) { content.innerHTML = xhr.responseText // Request API League const league = document.querySelector('.league') document.querySelectorAll('card-image a').forEach(elm => { elm.addEventListener('click', async function() { // Get data to table standings const resultStandings = await getStandings(this.dataset.idleague) .then(data => { league.innerHTML = ` <div class="row"> <div class="col s12 row-wrap m12 l7 h-70"> <wrap-table title="Standings" id="standings"></wrap-table> </div> <div class="col s12 m12 l4 offset-l1 row-wrap h-70"> <wrap-table title="Top Score" id="scorers"></wrap-table> </div> </div> ` const tableStandings = document.querySelector('table-standings') // Mengirimkan data tableStandings.setStandings = data }) .catch(err => { league.innerHTML = ` <div class="col s12 m6 l5 offset-m3 offset-l4"> <h2 class="grey-text">Something went wrong</h2> <button class="btn yellow waves-effect waves-yellow waves-light reload">Try Again</button> </div> ` const btnReload = document.querySelector('.reload') btnReload.addEventListener('click', () => { location.reload() }) }) // Get data to table scorers const tableScorers = document.querySelector('table-scorers') const resultScorers = await getScorers(this.dataset.idleague) .then(data => { tableScorers.setScorers = data.scorers }) }) }) // League const cardImage = document.querySelectorAll('.league .card-image') document.querySelector('.sidenav-trigger').addEventListener('click', function() { if (sidenav.style.transform = 'translateX(0%)') { cardImage.forEach(elm => elm.style.zIndex = '-3') document.querySelector('main').addEventListener('click', function() { sidenav.style.transform = 'translateX(-105%)' cardImage.forEach(elm => elm.style.zIndex = '1') }) } }) if (page === 'favorite') { getFavorite() } } } else if (this.status === 404) { content.innerHTML = '<h2 class="grey-text">Halaman tidak ditemukan</h2>' } else { content.innerHTML = '<pre-load></pre-load>' } } xhr.open('GET', './src/pages/' + page + '.html', true) xhr.send() } const loadNav = () => { const xhr = new XMLHttpRequest() xhr.onreadystatechange = function() { if (this.readyState === 4) { if (this.status !== 200) return // Muat Daftar tautan menu document.querySelectorAll('.topnav, .sidenav').forEach(elm => elm.innerHTML = xhr.responseText) // Daftarkan event listener untuk setiap tautan menu document.querySelectorAll('.sidenav a, .topnav a').forEach(elm => { elm.addEventListener('click', event => { // Tutup sidenav M.Sidenav.getInstance(sidenav).close() // Muat Konten halaman yang dipanggil page = event.target.getAttribute('href').substr(1) loadedPage(page) }) }) // List Navbar document.querySelectorAll('nav-bar nav ul li').forEach(elm => { elm.addEventListener('click', () => { document.querySelectorAll('nav-bar nav ul li').forEach(elm => elm.classList.remove('active-link')) elm.classList.add('active-link') }) }) } } xhr.open('GET', 'nav.html', true) xhr.send() } M.Sidenav.init(sidenav, { edge: 'left', draggable: true }) loadNav() if (page === '') page = 'home' loadedPage(page) } export default main<file_sep>class TableSquad extends HTMLElement { set setSquad(squad) { this._squad = squad this.count = 0 this.render() } render() { this.innerHTML = ` <table> <thead class="red-text"> <tr> <th>#</th> <th>Name Player</th> <th>Posision</th> </tr> </thead> <tbody> ${ this._squad.map(value => ( ` <tr> <td>${ this.count+=1 }</td> <td>${ value.name }</td> <td>${ value.position }</td> </tr> ` )).join(' ') } </tbody> </table> ` } } customElements.define('table-squad', TableSquad)
0b94501c80b0a19ea771c8c4d4b82bb0afffb3ae
[ "JavaScript", "Markdown" ]
14
JavaScript
CandraJengger/Progressive-Web-Apps--Yubal
c0c6deea9d2f68252d8392d3e98b09c8e8b0db56
9893e2a7ddbc4ecdc724af3e386e36d3e3ce0e06
refs/heads/master
<repo_name>MaxArt2501/versionoder<file_sep>/scripts/main.js const getReleaseType = release => { if (release.lts) return "lts"; if (release.version.startsWith("v0.")) return "legacy"; return "stable"; } fetch("https://nodejs.org/dist/index.json") .then(response => response.json()) .then(json => { const releases = json.map(rel => { const date = new Date(rel.date); return Object.assign({}, rel, { date }); }).sort((v1, v2) => v2.date - v1.date); const types = [ ...new Set(releases.map(getReleaseType)) ]; let html = `<table><thead><tr><th rowspan='2'>Date</th><th colspan='${types.length}'>Channels</th></tr><tr>`; for (let type of types) html += `<th>${type}</th>`; html += "</tr></thead><tbody>" + releases.map(rel => { const idx = types.indexOf(getReleaseType(rel)); const rest = types.length - idx; const row = `<tr><td>${rel.date.toLocaleDateString()}</td>` + Array(idx).fill("<td></td>").join("") + `<td><span class='version-list__tag'>${rel.version}</span></td>`; + Array(rest - 1).fill("<td></td>").join("") + "</tr>"; return row; }).join("") + "</tbody></table>"; document.querySelector(".version-list").innerHTML = html; }); <file_sep>/index.js "use strict"; const electron = require("electron"); const app = electron.app; // adds debug features like hotkeys for triggering dev tools and reload require("electron-debug")(); // prevent window being garbage collected let mainWindow; function createMainWindow() { if (mainWindow) return; mainWindow = new electron.BrowserWindow({ width: 600, height: 400 }); mainWindow.loadURL(`file://${__dirname}/views/main.html`); mainWindow.on("closed", () => mainWindow = null); } app.on("window-all-closed", () => { if (process.platform !== "darwin") { app.quit(); } }); app.on("activate", createMainWindow); app.on("ready", createMainWindow);
3cd7d2ad58968110bf78bc3799ad78949937edb3
[ "JavaScript" ]
2
JavaScript
MaxArt2501/versionoder
7cea490cdc55e4803af60ada5356930d9df0db0b
c862a35b043b5df0320b1f2771766f64a6323da6
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace GrcBoxCSharp { [DataContract] public class GrcBoxInterface { public enum Type { WIFISTA, WIFIAH, CELLULAR, ETHERNET, WIMAX, OTHERS, UNKNOWN }; [DataMember] public string name { get; set; } [DataMember] public string address{ get; set; } [DataMember] public string type{ get; set; } [DataMember] public string connection { get; set; } [DataMember] public double cost{ get; set; } [DataMember] public double rate{ get; set; } [DataMember] public bool up{ get; set; } [DataMember] public bool multicast{ get; set; } [DataMember] public bool hasInternet{ get; set; } [DataMember( Name = "default") ] public bool isDefault{ get; set; } public override string ToString() { return String.Format("GRCBoxIface:N=\"{0}\",T=\"{1}\",A=\"{2}\",Inet=\"{3}\","+ "M=\"{4}\"", name, type, address, hasInternet, multicast); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.NetworkInformation; using System.Runtime.Serialization.Json; using System.Text; using System.Threading; namespace GrcBoxCSharp { public class GRCBoxClient { private readonly string STATUS = "/"; private readonly string IFACES = "/ifaces"; private readonly string APPS = "/apps"; private readonly string RULES = "/rules"; private readonly int MAX_TRIES = 4; private readonly string KEEPALIVETHREAD = "Keep Alive Thread"; /// <summary> /// The name of the app /// </summary> private string appName; /// <summary> /// The network interface to connect with the GRCBox /// </summary> private NetworkInterface mIface; /// <summary> /// The base uri of the GRCBox /// </summary> private string baseUri; /// <summary> /// My appId after registration /// </summary> private int appId; /// <summary> /// My pass after registering for later communications /// </summary> private string mPass; /// <summary> /// A boolean field to /// </summary> private bool isRegistered; public bool IsRegistered { get { return isRegistered; } } long keepAliveInterval; /// <summary> /// Create a new GRCBoxClient instance with APP name "name" /// </summary> /// <param name="name"></param> public GRCBoxClient(string name, string baseUri, NetworkInterface iface) { this.appName = name; this.baseUri = baseUri; this.mIface = iface; } /// <summary> /// Register this instance in the server should be called before anything else /// </summary> public void register() { string uri = baseUri + APPS; IdSecret secret = makePostRequest<IdSecret>(uri, appName); appId = secret.appId; mPass = <PASSWORD>.secret.<PASSWORD>(); keepAliveInterval = secret.updatePeriod; informRegistered(keepAliveInterval); isRegistered = true; } /// <summary> /// Send a keep alive to the server /// </summary> public void keepAlive() { string uri = baseUri + APPS + "/" + appId; makePostRequest<Object>(uri, null, appId.ToString(), mPass); } /// <summary> /// Deregister an app from the server, it should be called when the applications /// is finished. All the rules will be removed. /// </summary> public void deregister() { string uri = baseUri + APPS + "/" + appId; isRegistered = false; makeDeleteRequest(uri, appId.ToString(), mPass); informDeregistered(); } /// <summary> /// Returns the list of availbale interfaces /// </summary> /// <returns></returns> public List<GrcBoxInterface> getInterfaces() { string uri = baseUri + IFACES; GrcBoxInterfaceList list = makeGetRequest<GrcBoxInterfaceList>(uri); return list.list; } /// <summary> /// Get a list of my registeres rules /// </summary> /// <returns></returns> public List<GrcBoxRule> getRules() { string uri = baseUri + APPS + "/" + appId + RULES; GrcBoxRuleList list = makeGetRequest<GrcBoxRuleList>(uri); return list.list; } /// <summary> /// Get the status of the GRCBox /// </summary> /// <returns></returns> public GrcBoxStatus getStatus() { string uri = baseUri + STATUS; GrcBoxStatus status = makeGetRequest<GrcBoxStatus>(uri); return status; } /// <summary> /// Register a new rule /// </summary> /// <param name="rule">The rule to be registered, the field ID is ignored by the server</param> /// <returns>The actual rule registered in the server, with the new ID</returns> public GrcBoxRule registerNewRule(GrcBoxRule.Protocol protocol, GrcBoxRule.RuleType t, GrcBoxInterface iface, long expireDate, int dstPort, string dstAddr = null, int srcPort = -1, string mcastPlugin = null, int dstFwdPort = -1, string srcAddr = null) { string ifName = iface.name; string type = t.ToString(); string dstFwdAddr; if (GrcBoxRule.RuleType.INCOMING.Equals(t)) { dstAddr = iface.address; dstFwdAddr = getMyIpAddr(); if (dstFwdPort == -1) { dstFwdPort = dstPort; } } else { srcAddr = getMyIpAddr(); dstFwdAddr = null; } GrcBoxRule rule = new GrcBoxRule(0, protocol.ToString(), type, appId, ifName, expireDate, srcPort, dstPort, srcAddr, dstAddr, mcastPlugin, dstFwdPort, dstFwdAddr); string uri = baseUri + APPS + "/" + appId + RULES; MemoryStream stream = new MemoryStream(); DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(GrcBoxRule)); jsonSerializer.WriteObject(stream, rule); stream.Position = 0; StreamReader r = new StreamReader(stream); string content = r.ReadToEnd(); GrcBoxRuleList list = makePostRequest<GrcBoxRuleList>(uri, content, appId.ToString(), mPass); return list.list[list.list.Count - 1]; } /// <summary> /// Remove a rule from the server /// </summary> /// <param name="rule"></param> public void removeRule(GrcBoxRule rule) { string uri = baseUri + APPS + "/" + appId + RULES + "/" + rule.id; makeDeleteRequest(uri, appId.ToString(), mPass); } private T makeGetRequest<T>(string uri, string authName = null, string authPass = null) { HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; request.Timeout = 1000; if (authName != null && authPass != null) { SetBasicAuthHeader(request, authName, authPass); } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T)); return (T)jsonSerializer.ReadObject(response.GetResponseStream()); } } private T makePostRequest<T>(string uri, string content, string authName = null, string authPass = null) { HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; request.Method = "POST"; request.Timeout = 500; if (authName != null && authPass != null) { SetBasicAuthHeader(request, authName, authPass); } if (content != null) { byte[] byteArray = Encoding.Default.GetBytes(content); request.ContentLength = byteArray.Length; request.ContentType = "application/json"; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.NoContent) { return default(T); } else if (!(response.StatusCode == HttpStatusCode.OK)) throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T)); return (T)jsonSerializer.ReadObject(response.GetResponseStream()); } } private static byte[] GetBytesFromString(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } private void makeDeleteRequest(string uri, string authName = null, string authPass = null) { HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; request.Method = "DELETE"; request.Timeout = 1000; if (authName != null && authPass != null) { SetBasicAuthHeader(request, authName, authPass); } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.NoContent) { return; } else if (!(response.StatusCode == HttpStatusCode.OK)) throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); return; } } public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword) { string authInfo = userName + ":" + userPassword; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); req.Headers["Authorization"] = "Basic " + authInfo; } private string getMyIpAddr() { string addr = null; foreach (UnicastIPAddressInformation ipInfo in mIface.GetIPProperties().UnicastAddresses) { if (ipInfo.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { addr = ipInfo.Address.ToString(); } } return addr; } #region monitor private List<GrcBoxMonitor> subscribers = new List<GrcBoxMonitor>(); public void subscribe(GrcBoxMonitor subs) { if(!subscribers.Contains(subs)) { subscribers.Add(subs); } } public void unsubscribe(GrcBoxMonitor subs) { if (subscribers.Contains(subs)) { subscribers.Remove(subs); } } private void informRegistered(long keepAliveInterval) { foreach(GrcBoxMonitor gm in subscribers) { gm.onRegistered(keepAliveInterval); } } private void informDeregistered() { foreach (GrcBoxMonitor gm in subscribers) { gm.onDeregistered(); } } public interface GrcBoxMonitor { void onRegistered(long keepAliverInterval); void onDeregistered(); } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace GrcBoxCSharp { [DataContract] public class StringList { [DataMember] public List<string> list { get; set; } public StringList(List<string> list) { this.list = list; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace GrcBoxCSharp { [DataContract] public class GrcBoxStatus { [DataMember] public string name { get; set; } [DataMember] public StringList supportedMulticastPlugins { get; set; } [DataMember] public int numIfaces { get; set; } [DataMember] public int numApps { get; set; } [DataMember] public int numRules { get; set; } public GrcBoxStatus(string name, StringList supportedMulticastPlugins, int numIfaces, int numApps, int numRules) { this.name = name; this.supportedMulticastPlugins = supportedMulticastPlugins; this.numIfaces = numIfaces; this.numApps = numApps; this.numRules = numRules; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace GrcBoxCSharp { [DataContract] public class GrcBoxRuleList { [DataMember] public List<GrcBoxRule> list { get; set; } } } <file_sep># GRCBox C\# Client This repository contains a GRCBox client library written in C#. It allows to implement GRCBox-aware applications for windows. It has been tested in Windows 7, but should work in Windows Mobile too. Issues: In windows 7, the hostname "grcbox" is not properly resolved. DNS were configured correctly since `nslookup grcbox` returned the correct IP.<file_sep>using System; using System.Collections.Generic; using System.Runtime.Serialization.Json; using System.Net; using GrcBoxCSharp; using System.IO; using System.Net.NetworkInformation; using System.Threading; namespace TestGRCBox { class Program { readonly static String GRCBOXBASEURL = "http://192.168.42.1:8080"; //Do not know why grcbox is not properly resolved :S static void Main(string[] args) { Console.WriteLine(GRCBOXBASEURL); NetworkInterface mIface = null; foreach( NetworkInterface iface in NetworkInterface.GetAllNetworkInterfaces()) { if(iface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) { mIface = iface; break; } } GRCBoxClient client = new GRCBoxClient("test", GRCBOXBASEURL, mIface); Console.Write(client.getStatus()); client.register(); Thread.Sleep(10000); List<GrcBoxInterface> ifaces = client.getInterfaces(); client.registerNewRule(GrcBoxRule.Protocol.TCP, GrcBoxRule.RuleType.INCOMING, ifaces[0], 0, 80); List<GrcBoxRule> rules = client.getRules(); client.deregister(); //Wait for any key Console.ReadKey(); } } } <file_sep>using System.Collections.Generic; using System.Runtime.Serialization; namespace GrcBoxCSharp { [DataContract] public class GrcBoxInterfaceList { [DataMember] public List<GrcBoxInterface> list { get; set; } } } <file_sep>using System; using System.Runtime.Serialization; namespace GrcBoxCSharp { [DataContract] public class GrcBoxAppInfo { [DataMember] public int appId { get; set; } [DataMember] public string name { get; set; } [DataMember] public long keepAlivePeriod { get; set;} } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace GrcBoxCSharp { [DataContract] public class IdSecret { [DataMember] public int appId { get; set; } [DataMember] public int secret { get; set; } [DataMember] public long updatePeriod { get; set; } } } <file_sep>using System.Runtime.Serialization; namespace GrcBoxCSharp { [DataContract] public class GrcBoxRule { public enum Protocol { TCP, UDP } public enum RuleType { INCOMING, OUTGOING, MULTICAST } [DataMember(Name = "@class")] public string javaclass { get; set; } = "es.upv.grc.grcbox.common.GrcBoxRule"; [DataMember] public int id { get; set; } [DataMember] public string proto { get; set; } [DataMember] public string type { get; set; } [DataMember] public int appid { get; set; } [DataMember] public string ifName { get; set; } [DataMember] public long expireDate { get; set; } [DataMember] public int srcPort { get; set; } [DataMember] public int dstPort { get; set; } [DataMember] public string srcAddr { get; set; } [DataMember] public string dstAddr { get; set; } [DataMember] public string mcastPlugin { get; set; } [DataMember] public int dstFwdPort { get; set; } [DataMember] public string dstFwdAddr { get; set; } public GrcBoxRule(int id, string protocol, string t, int appId, string ifName, long expireDate, int srcPort, int dstPort, string srcAddr, string dstAddr, string mcastPlugin, int dstFwdPort, string dstFwdAddr) { this.id = id; this.proto = protocol; this.type = t; this.appid = appId; this.ifName = ifName; this.expireDate = expireDate; this.srcPort = srcPort; this.dstPort = dstPort; this.srcAddr = srcAddr; this.dstAddr = dstAddr; this.mcastPlugin = mcastPlugin; this.dstFwdPort = dstFwdPort; this.dstFwdAddr = dstFwdAddr; } } }
103cb4e54ec49c164301e87d38483f91611ed6e6
[ "Markdown", "C#" ]
11
C#
GRCDEV/GRCBoxCSharpClient
72d20c8dc0a1bc623974f48bb3a0adec03a07e9f
dd985602ef887ce91ddb3a6922d0bdecf0210d28
refs/heads/master
<repo_name>onanying/mysqli-driver-php<file_sep>/Library/MysqliResult.php <?php namespace Library; /** * mysqli结果集 * @author 刘健 <<EMAIL>> */ class MysqliResult { protected $mysqli_result = ''; const MYSQLI_OBJECT = 0; const MYSQLI_ARRAY = 1; public $numRows = ''; public $currentField = ''; public $fieldCount = ''; public $lengths = ''; public function __construct($mysqli_result) { $this->mysqli_result = $mysqli_result; /* 赋值 */ $this->numRows = $mysqli_result->num_rows; $this->currentField = $mysqli_result->current_field; $this->fieldCount = $mysqli_result->field_count; $this->lengths = $mysqli_result->lengths; } /** * 返回全部查询结果,无数据返回**空数组** */ public function result($resultType = self::MYSQLI_OBJECT) { $tmp = array(); while ($row = $this->nextRow($resultType)) { $tmp[] = $row; } return $tmp; } /** * 这个方法返回单独一行结果。如果你的查询不止一行结果,它只返回第一行 */ public function row($resultType = self::MYSQLI_OBJECT) { $this->mysqli_result->data_seek(0); return $this->nextRow($resultType); } /** * 返回下一行 */ public function nextRow($resultType = self::MYSQLI_OBJECT) { return $resultType == self::MYSQLI_OBJECT ? $this->mysqli_result->fetch_object() : $this->mysqli_result->fetch_assoc(); } } <file_sep>/example.php <?php include 'autoload.php'; use Library\MysqliDriver; use Library\MysqliResult; // 初始化 $mysqli = new MysqliDriver(); $conf = ['username' => 'root', 'password' => '<PASSWORD>', 'database' => 'test']; $mysqli->connect($conf); // 查询 $query = $mysqli->query('select * from `money`'); print_r($query->result()); print_r($query->row()); $uid = 101; $number = -10; // 事务 $mysqli->transStart(); $mysqli->query('update `money` set number = number - ? where uid = ?', abs($number), $uid); $mysqli->query('insert `history`(uid, number) values(?, ?)', $uid, $number); $mysqli->transComplete(); echo 'Transaction execution status: ' . ($mysqli->transStatus() ? 'true' : 'false'); <file_sep>/Library/MysqliDriver.php <?php namespace Library; /** * mysqli驱动器 * @author 刘健 <<EMAIL>> */ class MysqliDriver { /* 内部参数 */ protected $mysqli = ''; protected $connectTimeout = 2; protected $transOpen = false; protected $allQuerySucc = false; /* 用户配置参数 */ protected $host = 'localhost'; protected $port = 3306; protected $username = 'root'; protected $password = ''; protected $database = ''; protected $charset = 'utf8'; protected $escapeString = true; // 转义字符串 protected $backZeroAffect = true; // 事务内的sql影响数量为0,则rollback该事务 /* 公共参数 */ public $affectedRows = 0; public function __construct($config = array()) { $this->mysqli = mysqli_init(); empty($config) or $this->connect($config); } public function __destruct() { $this->mysqli->close(); } /** * 连接数据库 * @param array $config [数据库配置参数] */ public function connect($config = array()) { // 配置参数 foreach ($config as $key => $value) { if (isset($this->$key)) { $this->$key = $value; } } // 连接 $this->mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, $this->connectTimeout); // 设置超时时间 $connect = @$this->mysqli->real_connect($this->host, $this->username, $this->password, $this->database, $this->port); if (!$connect) { throw new \Exception(sprintf('Connect Error: [%s] %s', $this->mysqli->connect_errno, $this->mysqli->connect_error)); } // 设置编码 if (!$this->mysqli->set_charset($this->charset)) { throw new \Exception(sprintf("Error loading character set utf8: [%s] %s", $this->mysqli->errno, $this->mysqli->error)); } } /** * 执行查询 */ public function query() { // 获取参数 $args = func_num_args(); $argv = func_get_args(); // 取出sql $sql = $argv[0]; unset($argv[0]); // 处理字符串参数 foreach ($argv as $key => $value) { if (!is_numeric($value)) { // 转义 if ($this->escapeString) { $argv[$key] = $this->mysqli->real_escape_string($argv[$key]); } // 加单引号 $argv[$key] = "'{$argv[$key]}'"; } } // 生成sql foreach ($argv as $key => $value) { if ($start = stripos($sql, '?')) { $sql = substr_replace($sql, $argv[$key], $start, 1); } } // 执行sql $resource = $this->mysqli->query($sql); // 设置影响的行数 $this->affectedRows = $this->mysqli->affected_rows; // 返回数据 if (is_bool($resource)) { if ($resource === false) { // sql执行失败 throw new \Exception(sprintf("Error SQL: [%s] %s", $this->mysqli->errno, $this->mysqli->error)); } if ($this->backZeroAffect && $this->transOpen && $this->affectedRows <= 0) { $this->allQuerySucc = false; } return $resource; } else { return new MysqliResult($resource); } } /** * 自动事务开始 */ public function transStart() { $this->transBegin(); } /** * 自动事务完成 (自动提交或回滚) */ public function transComplete() { if ($this->transStatus()) { $this->transCommit(); } else { $this->transRollback(); } } /** * 事务执行状态 */ public function transStatus() { return $this->allQuerySucc; } /** * 事务开始 */ public function transBegin() { $this->transOpen = true; $this->allQuerySucc = true; $this->mysqli->autocommit(false); // 关闭自动提交 } /** * 事务提交 */ public function transCommit() { $this->mysqli->commit(); $this->mysqli->autocommit(true); // 重新开启自动提交 $this->transOpen = false; } /** * 事务回滚 */ public function transRollback() { $this->mysqli->rollback(); $this->mysqli->autocommit(true); // 重新开启自动提交 $this->transOpen = false; } } <file_sep>/README.md ## 项目介绍 简易好用的mysqli驱动器与结果集,带自动事务,参数转义 ### 说明文档 > example.php 里有范例代码 #### 1. 连接数据库 ##### 方法1:使用构造方法连接 ```php $mysqli = new MysqliDriver(['username' => 'root', 'password' => '<PASSWORD>', 'database' => 'test']); ``` ##### 方法2:使用connect连接 ```php $mysqli = new MysqliDriver(); $conf = ['username' => 'root', 'password' => '<PASSWORD>', 'database' => 'test']; $mysqli->connect($conf); ``` ##### 方法3: 使用类文件里的默认值连接 ```php $mysqli = new MysqliDriver(); $mysqli->connect(); ``` #### 2. 执行查询 select ```php $query = $mysqli->query('select * from `money`'); print_r($query->result()); ``` update insert delete ```php $status = $mysqli->query('update `money` set number = number - ? where uid = ?', 10, 100); if($status){ echo $mysqli->affectedRows; } ``` #### 3. 结果集 返回全部记录,对象 ```php $query = $mysqli->query('select * from `money`'); print_r($query->result()); ``` 返回全部记录,数组 ```php $query = $mysqli->query('select * from `money`'); print_r($query->result(Library\MysqliResult::MYSQLI_ARRAY)); ``` 返回单独一行结果。如果你的查询不止一行结果,它只返回第一行 ```php $query = $mysqli->query('select * from `money`'); print_r($query->row()); ``` #### 4. 事务 事物中的sql执行失败,会自动回滚 注意: 默认update/insert/delete的affected_rows为0时事物也会自动回滚,如果你不想这样,请配置MysqliDriver::backZeroAffect = false; ```php $mysqli->transStart(); $mysqli->query('update `money` set number = number - ? where uid = ?', 10, 100); $mysqli->query('insert `history`(uid, number) values(?, ?)', 100, -10); $mysqli->transComplete(); echo 'Transaction execution status: ' . ($mysqli->transStatus() ? 'true' : 'false'); ```
a20bd0288c858e1521a23db520d414beb032f686
[ "Markdown", "PHP" ]
4
PHP
onanying/mysqli-driver-php
bd6ee273b8a2281868d842332505c4e81e50bc6b
caa3648219a8c771a3d08c68b1a84b236c7d3926
refs/heads/main
<file_sep> from flask import Flask, render_template from flask import request from flask.json import jsonify import jwt from flask_sqlalchemy import SQLAlchemy import psycopg2 app = Flask(__name__,template_folder="my_templates") app.config['SECRET_KEY'] = 'thisismyflasksecretkey' app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:1234567@localhost:5432/user_table' db = SQLAlchemy(app) class User(db.Model): __tablename__ = 'user_n' id = db.Column(db.Integer, primary_key=True) login = db.Column(db.String(80), unique=True, nullable=False) password = db.Column(db.String(120), nullable=False) token = db.Column(db.String(120), unique=True, nullable=False) @app.route("/login", methods=["GET", "POST"]) def login(): if request.method == "POST": login_ = request.form["login"] password = request.form["password"] user = User.query.filter_by(login=login_, password=<PASSWORD>).first() if user is not None: user_token=jwt.encode({"login": login_, "password": <PASSWORD>}, app.config['SECRET_KEY'], algorithm="HS256") user.token = user_token db.session.add(user) db.session.commit() return f"<h1>token: {user_token}</h1>" else: return f"<h1>Could not found a user with login: {login_}</h1>" return render_template("login.html") @app.route("/protected",methods=["GET"]) def protected(): s_token=request.args.get("token") jwt_token=jwt.decode(s_token,app.config['SECRET_KEY'],algorithms=["HS256"]) if jwt_token: login_ = jwt_token.get("login") password = jwt_token.get("password") user = User.query.filter_by(login=login_, password=<PASSWORD>).first() if user is not None: return "<h1>Hello, token which is provided is correct </h1>" return "<h1>Hello, Could not verify the token</h1>" if __name__ == '__main__': app.run(debug=True) db.create_all()<file_sep>Flask==2.0.2 Flask-SQLAlchemy==2.5.1 PyJWT==2.2.0 <file_sep># merey_kamila_SE-2010 ## Title This assignment is about tokens ```html Done by: <NAME>, <NAME> Group:SE-2010 ``` ### Table of Contents - [Installation](#installation) - [Usage](#usage) - [Examples](#examples) - [License](#lisense) --- ## Installation * ### Create a virtual environment: ```python $ virtualenv env``` * ### Activate a virtual environment: For Windows: ```python env\Scripts\activate``` For Mac OS,Linux: ```python source env/bin/activate``` * ### Flask ```python $ pip install flask``` * ### SQLAlchemy ```python $ pip install SQLAlchemy ``` * ### pyjwt ```python $ pip install pyjwt ``` * ### PostgreSQL Database [Download](https://www.enterprisedb.com/downloads/postgres-postgresql-downloads) [Back To The Top](#merey_kamila_SE-2010) ## Usage ```python from flask import Flask, render_template from flask import request import jwt from flask_sqlalchemy import SQLAlchemy import psycopg2 ``` [Back To The Top](#merey_kamila_SE-2010) ## Examples ```html Datas: login:Merey password:<PASSWORD> login:Kami password:<PASSWORD> login:Balzy password:<PASSWORD> ``` [Back To The Top](#merey_kamila_SE-2010) ## License MIT License Copyright (c) 2021 Overexm Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Back To The Top](#merey_kamila_SE-2010)
679e86dd3cbc72e2f8e236926f29bc9f977481c6
[ "Markdown", "Python", "Text" ]
3
Python
Overexm/merey_kamila_SE-2010
ae6b321a1d9fc153a0fed82b654e18f19878584d
ecd543471740545d333a572e4299144ec37dfc08
refs/heads/master
<file_sep>var lines = []; var img; function preload() { img = loadImage("images/GitHub-Mark.png"); } function setup() { var myCanvas = createCanvas(960, 533); myCanvas.parent("myCanvas"); bg = loadImage("images/map.png"); } function draw() { background(bg); stroke(226, 204, 0); for (var i = 0; i < lines.length; i++) { line(lines[i].mouseX, lines[i].mouseY, lines[i].pmouseX, lines[i].pmouseY) } } function mouseDragged() { cursor(CROSS); lines.push({ mouseX: mouseX, mouseY: mouseY, pmouseX: pmouseX, pmouseY: pmouseY }) } $("#drawimg").click( function () { } ); $("#savemap").click( function () { saveCanvas(myCanvas, 'myCanvas', 'jpg'); } ); $("#clearmap").click( function () { lines = []; } );
c9e6aacb4df03d0bcf8401fa4bdc9195bca67af7
[ "JavaScript" ]
1
JavaScript
eXt-Ra/Overwatch-Tools
90ca4de7ff2dae2da30ec4c29cc48efc0f2a4dc9
703a59e40a2875c5d88baa5dba72a6e52b98e12a
refs/heads/main
<repo_name>yunsarasak/yEcho<file_sep>/src/client.c #include "../lib/yEcho.h" #define TOTALFORK 30 void* sendFunc(void* _sock_fd) { int socket_fd = *(int*)_sock_fd; while(1){ SEND_MSG(socket_fd, "hello, TCP! %d speaking", socket_fd); //poll(NULL, 0, 1); } } void* recvFunc(void* _sock_fd) { int socket_fd = *(int*)_sock_fd; PrintWhenRecv(socket_fd); } int main() { int socket_fd; pthread_t thread_send, thread_recv; pid_t pids[TOTALFORK], pid; int runProcess = 0; //생성한 프로세스 수 int state; while(runProcess < TOTALFORK) { //30개의 프로세스를 loop 를 이용하여 생성 //자식 프로세스 종료 대기 (각 프로세스가 따로 동작하고, //종료를 기다려야 할 경우에 사용 pids[runProcess] = fork(); //fork 생성 //0보다 작을 경우 에러 (-1) if(pids[runProcess] < 0) { return -1; } else if(pids[runProcess] == 0) {//자식 프로세스 socket_fd = InitClient("127.0.0.1", PORT); pthread_create(&thread_send, NULL, sendFunc, (void*)&socket_fd); pthread_create(&thread_recv, NULL, recvFunc, (void*)&socket_fd); break; } else { //부모 프로세스 ; } runProcess++; } while(1){ poll(NULL, 0, 1000 * 10); } close(socket_fd); return 0; } <file_sep>/legacy/src/Makefile all : client server make client make server client : client.c gcc -g -o $@ $^ -I../lib -L../lib -lpthread -lyEcho server : server.c gcc -g -o $@ $^ -I../lib -L../lib -lpthread -lyEcho ctags : ctags -R ../*/*.[ch] clean : rm client rm server <file_sep>/src/Makefile server : server.c gcc -g -o $@ $^ -I../lib -L../lib -lpthread -lyEcho client : client.c gcc -g -o $@ $^ -I../lib -L../lib -lpthread -lyEcho ctags : ctags ../*/*.[ch] clean : rm server <file_sep>/legacy/src/client.c #include "../lib/yEcho.h" void *SendRecvFunc(void* _socket_fd) { int socket_fd = *(int*)_socket_fd; char msg[1024]; char buffer[1024]; int recv_len; while(1){ //send if( fgets(msg, sizeof(msg), stdin) != NULL){ if(send(socket_fd, msg, strlen(msg), 0) < 0){ perror("send :"); return NULL; } } //recv if((recv_len = recv(socket_fd, buffer, 1024, 0)) < 0){ perror("receive :"); return (void*)-1; } buffer[recv_len] = '\0'; printf("received msg : %s\n", buffer); memset(buffer, 0x00, 1024); memset(msg, 0x00, 1024); } return NULL; } int main(void) { int sock; char buffer[1024]; const char *msg = "hellow, world! from client2\n"; int recv_len; pthread_t thread_send_recv; if((sock = InitClient("127.0.0.1", 7777)) < 0){ printf("client init fail : %d, %s\n", errno, strerror(errno)); return -1; } if(pthread_create(&thread_send_recv, NULL, SendRecvFunc, (void*)&sock) != 0){ printf("socket : %d, %s\n", errno, strerror(errno)); return -2; } while(1){ poll(NULL, 0, 1000); } if((recv_len = recv(sock, buffer, 1024, 0)) < 0){ perror("receive :"); return -4; } buffer[recv_len] = '\0'; printf("received msg : %s\n", buffer); close(sock); return 0; } <file_sep>/lib/yEcho.c #include "yEcho.h" //summary : return socket fd when success //param : destination ipv4 address, port //return : socket fd on success, negative number on fail int InitClient(char* _str_dest_address, int _port) { int socket_fd; int iDSize; int iRet; pthread_mutex_init(&mutex_fd, NULL); struct sockaddr_in stAddr; iDSize = sizeof(struct sockaddr_in); bzero(&stAddr, iDSize); socket_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(socket_fd < 0) { printf("socket %d %s", errno, strerror(errno)); return -1; } stAddr.sin_family = AF_INET; iRet = inet_pton(AF_INET, _str_dest_address, &stAddr.sin_addr.s_addr); if(iRet == 0) { printf("pton %d %s", errno, strerror(errno)); return -2; } printf("IP : %s\n", inet_ntoa(stAddr.sin_addr)); stAddr.sin_port = htons(_port); if( 0 > connect(socket_fd, (struct sockaddr *)&stAddr, iDSize)) { printf("socket %d %s", errno, strerror(errno)); close(socket_fd); return -3; } return socket_fd; } //summary : return socket fd when success //param : port //return : socket fd on success, negative number on fail int InitServer(int _port) { int serv_sock; struct sockaddr_in serv_addr; pthread_mutex_init(&mutex_fd, NULL); socklen_t adr_sz; int fd_max, str_len, fd_num, i; //src address init. ipv4, pass (0.0.0.0) get any lancard address, use 7777 port serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(_port); //if socket stream type is 0, automatically apply serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //bind src addr to server socket if(bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1){ printf("bind %d %s", errno, strerror(errno)); return -1; } if(listen(serv_sock, 5) == -1){ printf("listen %d %s", errno, strerror(errno)); return -2; } return serv_sock; } //summary : send string with format to dest socket. //param : socket descriptor, format specifier , args //return : return 0 on suceess, -1 on error int SendMsg(int _dest_fd, char *_msg) { int send_result = -1; pthread_mutex_lock(&mutex_fd); send_result = send(_dest_fd, _msg, strlen(_msg), 0); pthread_mutex_unlock(&mutex_fd); return send_result; } void PrintWhenRecv(int _socket_fd_to_monitor) { char buff[BUF_SIZE]; fd_set rfds, copy_rfds; struct timeval tv; int retval; int recv_length; FD_ZERO(&rfds); FD_SET(_socket_fd_to_monitor, &rfds); tv.tv_sec = 5; tv.tv_usec = 0; while(1){ copy_rfds = rfds; retval = select(_socket_fd_to_monitor+1, &copy_rfds, NULL, NULL, &tv); if(retval == -1){ continue; }else if(retval == 0){ continue; }else{ memset(buff, 0x00, sizeof(buff)); pthread_mutex_lock(&mutex_fd); recv_length = recv(_socket_fd_to_monitor , buff, sizeof(buff), 0); pthread_mutex_unlock(&mutex_fd); buff[recv_length] = '\0'; printf("%s\n", buff); } } return; } //inner fucntion int SetAddress(struct sockaddr_in *_st_address, char* _str_address, int _i_port_number) { memset(_st_address, 0x00, sizeof(struct sockaddr_in)); _st_address->sin_family = AF_INET; if(_str_address == NULL){ _st_address->sin_addr.s_addr = htonl(INADDR_ANY); }else{ _st_address->sin_addr.s_addr = inet_addr(_str_address); } _st_address->sin_port = htons(_i_port_number); return 0; } char* make_message(const char *fmt, ...) { int n = 0; size_t size = 0; char *p = NULL; va_list ap; /* Determine required size. */ va_start(ap, fmt); n = vsnprintf(p, size, fmt, ap); va_end(ap); if (n < 0) return NULL; size = (size_t) n + 1; /* One extra byte for '\0' */ p = malloc(size); if (p == NULL) return NULL; va_start(ap, fmt); n = vsnprintf(p, size, fmt, ap); va_end(ap); if (n < 0) { free(p); return NULL; } return p; } <file_sep>/lib/Makefile libyEcho.a : yEcho.c yEcho.h gcc -c -g -o yEcho.o yEcho.c -lpthread ar rc $@ yEcho.o clean: rm yEcho.o rm libyEcho.a <file_sep>/lib/yEcho.h #include <stdio.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <pthread.h> #include <poll.h> #include <stdarg.h> #include <stdlib.h> #define BUF_SIZE 1024 #define PORT 7777 #define SEND_MSG(X, Y, ...) \ SendMsg(X, make_message(Y, __VA_ARGS__)) pthread_mutex_t mutex_fd; int InitClient(char* _str_dest_address, int _port); int InitServer(int _port); int SendMsg(int _dest_fd, char* _msg); void PrintWhenRecv(int _socket_fd_to_monitor); //inner function int SetAddress(struct sockaddr_in *_st_address, char* _str_address, int _i_port_number); char* make_message(const char *fmt, ...); <file_sep>/src/server.c #include "yEcho.h" int main(int argc, char* argv[]){ int serv_sock, clnt_sock; struct sockaddr_in clnt_addr; struct timeval timeout; fd_set reads, cpy_reads; socklen_t addr_size; int fd_max, str_len, fd_num, i; if((serv_sock = InitServer(PORT)) < 0){ printf("InitServer %d %s", errno, strerror(errno)); return serv_sock; } FD_ZERO(&reads);// initialize fd_set FD_SET(serv_sock, &reads);// add server socket into read fd set fd_max = serv_sock;//max file descriptor while(1) { cpy_reads = reads; //copy origin timeout.tv_sec = 5; timeout.tv_usec = 5000; //set timeout if((fd_num = select(fd_max+1, &cpy_reads, 0, 0, &timeout)) == -1){ break; }//there is only server socket in the set yet, so when receive connect request, data insert into server socket if(fd_num == 0){ continue; }// if time out, continue for(i = 0; i < fd_max+1; i++){ if(FD_ISSET(i, &cpy_reads)) { if( i == serv_sock) { addr_size = sizeof(clnt_addr); clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_addr, &addr_size); FD_SET(clnt_sock, &reads); if(fd_max < clnt_sock) { fd_max = clnt_sock; } printf("connect client %d\n", clnt_sock); }// if server socket is changed , it means there is connect request else { char buf[BUF_SIZE]; str_len = recv(i, buf, BUF_SIZE, 0); buf[str_len] = '\0'; if(str_len == 0) //close request { FD_CLR(i, &reads); close(i); printf("closed client %d\n", i); } else { SEND_MSG(i, "%d:%s", i, buf); //echo printf("%d: recv : %s\n", i, buf); } }// if other socket is changed, read data. } } } close(serv_sock); return 0; } <file_sep>/legacy/src/server.c #include "../lib/yEcho.h" int main(void){ int sock, client_sock; struct sockaddr_in addr, client_addr; char buffer[1024]; int len, addr_len, recv_len; sock = InitServer(7777); addr_len = sizeof(client_addr); printf("waiting for client..\n"); while((client_sock = accept(sock, (struct sockaddr *)&client_addr, &addr_len)) > 0){ printf("client ip : %s\n", inet_ntoa(client_addr.sin_addr)); while(1){ if((recv_len = recv(client_sock, buffer, 1024, 0)) < 0){ printf("recv : %d, %s\n", errno, strerror(errno)); return -4; } buffer[recv_len] = '\0'; printf("received data : %s\n", buffer); send(client_sock, buffer, strlen(buffer), 0); } close(client_sock); } close(sock); return 0; }
9fbe4fcbc363f0db663e6227458e4a5dc9242351
[ "C", "Makefile" ]
9
C
yunsarasak/yEcho
09399216cf8eecfc79a58045912a46c775afba47
f188823b370ab77dfcfe9be5ab0a2e9a29a379fc
refs/heads/master
<repo_name>ibhi/smartsync.git<file_sep>/README.md # smartsync.js This is just a bower package for managing smartsync.js(a library created by Salesforce for the Salesforce.com Mobile SDK Shared) easier during development. ### Installation Instructions `bower install smartsync` ### Package Dependencies smartsync.js depends on jquery, backbone.js and underscore.js ### Development Instructions #### Dev Dependencies To run the gulp tasks and update the library `Gulp`, `Gulp-Shell`, and `Bower` are needed. #### Update Instructions To pull from the latest code from salesforce for smartsync run `gulp` #### Gulp Tasks * default (alias to build task) * build (Updates smartsync.js file from SalesforceMobileSDK-Shared git repo) * update (Updates the SalesforceMobileSDK-Shared to the latest one from git repo) <file_sep>/gulpfile.js var gulp = require('gulp'), shell = require('gulp-shell'); var paths = { src: './bower_components/SalesforceMobileSDK-Shared/libs/smartsync.js', dest: './dist' } gulp.task('update', shell.task([ 'bower update SalesforceMobileSDK-Shared' ])); gulp.task('build', ['update'], () => { gulp .src(paths.src) .pipe(gulp.dest(paths.dest)); }); gulp.task('default', ['build']);
34255164eed405fa32bd2784604447754867f7db
[ "Markdown", "JavaScript" ]
2
Markdown
ibhi/smartsync.git
01aef1d0be9744f14e26df102fcc7bcf5bc85882
84e0bc4431407cb11e16c4e673fbd27c29a362cc
refs/heads/master
<file_sep>using System; using Xamarin.Forms; using System.Threading.Tasks; using System.Windows.Input; namespace RoomiesCalc { public class LoginViewModel :BaseViewModel { private INavigation _navigation; // HERE public LoginViewModel(INavigation navigation) { _navigation = navigation; } #region Command for Login button public ICommand LoginClick { get { return new Command (async () => { _navigation.PushModalAsync(new VerificationViewPage ()); } ); } } #endregion #region Command for Verfication button public ICommand VerficationClick { get { return new Command (async () => { _navigation.PushModalAsync(new AddPlaceViewPage ()); } ); } } #endregion } } <file_sep>using RoomiesCalc.Interfaces; using RoomiesCalc.Models; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; using Xamarin.Forms; namespace RoomiesCalc { public static class Extensions { public static void ToToast(this string message, ToastNotificationType type = ToastNotificationType.Info, string title = null) { Device.BeginInvokeOnMainThread(() => { var toaster = DependencyService.Get<IToastNotifier>(); toaster.Notify(type, title ?? type.ToString().ToUpper(), message, TimeSpan.FromSeconds(2.5f)); }); } public static bool IsEmpty(this string s) { return string.IsNullOrWhiteSpace(s); } public static T Get<T>(this ConcurrentDictionary<string, T> dict, string id) where T : BaseModel { if (id == null) return null; T v = null; dict.TryGetValue(id, out v); return v; } public static void AddOrUpdate<T>(this ConcurrentDictionary<string, T> dict, T model) where T : BaseModel { if (model == null) return; //TODO move to an IRefreshable interface var athlete = model as Roomie; if (athlete != null) { athlete.LocalRefresh(); } if (dict.ContainsKey(model.Id)) { if (!model.Equals(dict[model.Id])) dict[model.Id] = model; } else { dict.TryAdd(model.Id, model); } } } } <file_sep>using System; using System.Collections.Generic; using Xamarin.Forms; namespace RoomiesCalc { public partial class LoginViewPage : ContentPage { private LoginViewModel ViewModel { get { return BindingContext as LoginViewModel; } //Type cast BindingContex as HomeViewModel to access binded properties } public LoginViewPage () { BindingContext = new LoginViewModel(this.Navigation); this.BackgroundImage = "Bg1.png"; InitializeComponent (); } } } <file_sep>using System; using Xamarin.Forms; using System.Collections.Generic; using System.Threading.Tasks; using System.Collections.ObjectModel; namespace RoomiesCalc { public class AddPlaceViewModel:BaseViewModel { private INavigation _navigation; // HERE public AddPlaceViewModel() { _places = new Place(); _placeList = new ObservableCollection<Place>(); } private ObservableCollection<Place> _placeList; public ObservableCollection<Place> PlaceList { get { return _placeList; } set { _placeList = value; OnPropertyChanged(); } } private Place _places; public Place Places { get { return _places; } set { _places = value; OnPropertyChanged(); } } #region Load and add group Command private Command _addPlaceCommand; public Command AddPlaceCommand { get { return _addPlaceCommand ?? (_addPlaceCommand = new Command(async (param) => await ExecuteAddPlaceCommand(param))); } } private async Task ExecuteAddPlaceCommand(object param) { try { int i= App.Database.SaveItem<Place>(Places); } catch (Exception ex) { Console.WriteLine("An Exception Occured During Save Record {0}", ex.Message); return; } } private Command _LoadAllPlaces; public Command LoadAllPlaces { get { return _LoadAllPlaces ?? (_LoadAllPlaces = new Command(async () => await ExecuteLoadCommand())); } } private async Task ExecuteLoadCommand() { try { _placeList = App.Database.GetItems<Place>(); //From Local DB } catch (Exception ex) { Console.WriteLine("An Exception Occured During Save Record {0}", ex.Message); } } #endregion } } <file_sep>using System; using Xamarin.Forms; namespace RoomiesCalc { public class BalanceViewPage : ContentPage { public BalanceViewPage () { Content = new StackLayout { Children = { new Label { Text = "Hello ContentPage" } } }; } } } <file_sep>using System; namespace RoomiesCalc { public class Colors { public static readonly Colors RC_Pink = 0xFE2E64;//R254 G46 B100 public static readonly Colors RC_Green = 0x8BC34A;//R139 G195 B74 public double R, G, B; public static Colors FromHex(int hex) { Func<int, int> at = offset => (hex >> offset) & 0xFF; return new Colors { R = at(16) / 255.0, G = at(8) / 255.0, B = at(0) / 255.0 }; } public static implicit operator Colors(int hex) { return FromHex(hex); } public Xamarin.Forms.Color ToFormsColor() { return Xamarin.Forms.Color.FromRgb((int)(255 * R), (int)(255 * G), (int)(255 * B)); } #if __ANDROID__ public global::Android.Graphics.Color ToAndroidColor() { return global::Android.Graphics.Color.Rgb((int)(255 * R), (int)(255 * G), (int)(255 * B)); } public static implicit operator global::Android.Graphics.Color(Colors color) { return color.ToAndroidColor(); } #endif } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace RoomiesCalc.Interfaces { public interface IHUDProvider { void DisplayProgress(string message); void DisplaySuccess(string message); void DisplayError(string message); void Dismiss(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Xamarin.Forms.Platform.Android; using Xamarin.Forms; using RoomiesCalc; using RoomiesCalc.Droid.Renderer; [assembly: ExportRenderer(typeof(Entry), typeof(RCEntryRenderer))] namespace RoomiesCalc.Droid.Renderer { public class RCEntryRenderer : EntryRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if(Control!=null) { Control.SetBackgroundResource(Resource.Drawable.RCEntry); Control.SetBackgroundColor (global::Android.Graphics.Color.Transparent); Control.TextSize = 22; Control.SetHintTextColor (global::Android.Graphics.Color.White); } } } }<file_sep>using System; using Xamarin.Forms; namespace RoomiesCalc { public class LoginViewwPage: BaseViewPage { #region All Fileds public RelativeLayout rltv_MainLayout; public Button btn_Login; public Image img_Backgroud,img_logo; public RCEntry txt_Name,txt_Nmuber; public Label lbl_Country; public StackLayout stack_Main; public BoxView bx_Name,bx_Number; private LoginViewModel ViewModel { get { return BindingContext as LoginViewModel; } //Type cast BindingContex as HomeViewModel to access binded properties } #endregion public LoginViewwPage () { BindingContext = new LoginViewModel(this.Navigation); bx_Name = new BoxView { WidthRequest=(w/4)*3, HeightRequest=1, BackgroundColor=Color.Gray, }; bx_Number = new BoxView { WidthRequest=(w/4)*3, HeightRequest=1, BackgroundColor=Color.Gray, }; img_Backgroud = new Image { Source="Bg1.png", HeightRequest=h, Aspect= Aspect.Fill }; img_logo = new Image { Source="Logo.png", Aspect= Aspect.AspectFit, TranslationY=-w/10 }; txt_Name = new RCEntry { WidthRequest=w/2, HorizontalOptions=LayoutOptions.CenterAndExpand, TextColor=Color.White, Placeholder="FullName", BackgroundColor=Color.Transparent, TranslationX=10, }; txt_Nmuber = new RCEntry { WidthRequest=w/2, HorizontalOptions=LayoutOptions.CenterAndExpand, TextColor=Color.White, Placeholder="MobileNumber", BackgroundColor=Color.Transparent }; lbl_Country = new Label { Text="+91", TextColor=Color.White, //YAlign=TextAlignment.End, FontSize=22, TranslationY=5 }; btn_Login = new Button { Text="Login", TextColor=Color.White, BackgroundColor=Colors.RC_Green.ToFormsColor(), FontSize=22, WidthRequest=w/2, HorizontalOptions=LayoutOptions.CenterAndExpand, Command=ViewModel.LoginClick }; stack_Main = new StackLayout { HeightRequest=h/2, WidthRequest=(w/4)*3, HorizontalOptions=LayoutOptions.CenterAndExpand, VerticalOptions=LayoutOptions.CenterAndExpand, BackgroundColor=Color.Transparent, Spacing=w/20, Children= { img_logo, new StackLayout { Spacing=0, Orientation=StackOrientation.Vertical, HorizontalOptions=LayoutOptions.CenterAndExpand, Children= {txt_Name,bx_Name} }, new StackLayout { Spacing=0, Orientation=StackOrientation.Vertical, HorizontalOptions=LayoutOptions.CenterAndExpand, Children= { new StackLayout { Spacing=-3, Orientation=StackOrientation.Horizontal, HorizontalOptions=LayoutOptions.CenterAndExpand, Children= {lbl_Country,txt_Nmuber} }, bx_Number } }, btn_Login } }; rltv_MainLayout = new RelativeLayout { HeightRequest=h,WidthRequest=w, }; rltv_MainLayout.Children.Add(img_Backgroud, Constraint.Constant(0), Constraint.Constant(0)); rltv_MainLayout.Children.Add(stack_Main, Constraint.Constant((w/4)/2), Constraint.Constant(h/6)); this. Content= rltv_MainLayout; } } } <file_sep>using RoomiesCalc.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace RoomiesCalc { public partial class RegistrationPage : RegistrationPageXaml { public RegistrationPage() { InitializeComponent(); } } public partial class RegistrationPageXaml : BaseContentPage<LoginViewModel> { } } <file_sep>using Microsoft.WindowsAzure.MobileServices; using RoomiesCalc.App; using RoomiesCalc.Helper; using RoomiesCalc.Interfaces; using RoomiesCalc.Models; using RoomiesCalc.Services; using RoomiesCalc.ViewModels; using System; using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; [assembly: Dependency(typeof(LoginViewModel))] namespace RoomiesCalc.ViewModels { public class LoginViewModel : BaseViewModel { #region Properties IAuthentication _authenticator = DependencyService.Get<IAuthentication>(); string _authenticationStatus; public string AuthenticationStatus { get { return _authenticationStatus; } set { SetPropertyChanged(ref _authenticationStatus, value); } } internal GoogleUserProfile AuthUserProfile { get; set; } #endregion #region Authenticate User /// <summary> /// Performs a complete authentication pass /// </summary> public async Task<bool> AuthenticateCompletely() { await AuthenticateWithGoogle(); if (AuthUserProfile != null) await AuthenticateWithBackend(); return RoomieApp.CurrentRoomie != null; } #endregion #region Auth With Google /// <summary> /// Attempts to get the user's profile and will use WebView form to authenticate if necessary /// </summary> async Task<bool> AuthenticateWithGoogle() { await ShowGoogleAuthenticationView(); if (RoomieApp.AuthToken == null) return false; await GetUserProfile(); return AuthUserProfile != null; } #endregion #region Show Google Auth View /// <summary> /// Shows the Google authentication web view so the user can authenticate /// </summary> async Task ShowGoogleAuthenticationView() { if (RoomieApp.AuthToken != null && Settings.Instance.User != null) { var success = await GetUserProfile(); if (success) { AzureService.Instance.Client.CurrentUser = Settings.Instance.User; return; } } try { AuthenticationStatus = "Loading..."; MobileServiceUser user = await _authenticator.DisplayWebView(); var identity = await AzureService.Instance.Client.InvokeApiAsync("getUserIdentity", null, HttpMethod.Get, null); RoomieApp.AuthToken = identity.Value<string>("accessToken"); //Utility.SetSecured("AuthToken", App.AuthToken, "vdoers.roomie", "authentication"); Settings.Instance.User = user; await Settings.Instance.Save(); if (RoomieApp.CurrentRoomie != null && RoomieApp.CurrentRoomie.Id != null) { var task = AzureService.Instance.SaveRoomie(RoomieApp.CurrentRoomie); await RunSafe(task); } } catch (Exception e) { Debug.WriteLine("**ROOMIE AUTHENTICATION ERROR**\n\n" + e.GetBaseException()); // InsightsManager.Report(e); } } #endregion #region Auth With backend /// <summary> /// Authenticates the athlete against the Azure backend and loads all necessary data to begin the app experience /// </summary> async Task<bool> AuthenticateWithBackend() { Roomie roomie; using (new Busy(this)) { AuthenticationStatus = "Getting athlete's profile"; roomie = await GetAthletesProfile(); if (roomie == null) { //Unable to get athlete - try registering as a new athlete roomie = await RegisterAthlete(AuthUserProfile); } else { roomie.ProfileImageUrl = AuthUserProfile.Picture; if (roomie.IsDirty) { var task = AzureService.Instance.SaveRoomie(roomie); await RunSafe(task); } } Settings.Instance.RoomieID = roomie?.Id; await Settings.Instance.Save(); if (RoomieApp.CurrentRoomie != null) { //await GetAllLeaderboards(); RoomieApp.CurrentRoomie.IsDirty = false; MessagingCenter.Send<LoginViewModel>(this, Messages.UserAuthenticated); } AuthenticationStatus = "Done"; return RoomieApp.CurrentRoomie != null; } } #endregion #region Get Roomie Profile /// <summary> /// Gets the roomie's profile from the Azure backend /// </summary> async Task<Roomie> GetAthletesProfile() { Roomie roomie = null; //Let's try to load based on email address if (roomie == null && AuthUserProfile != null && !AuthUserProfile.Email.IsEmpty()) { var task = AzureService.Instance.GetAthleteByEmail(AuthUserProfile.Email); await RunSafe(task); if (task.IsCompleted && !task.IsFaulted) roomie = task.Result; } return roomie; } #endregion #region Register Roomie /// <summary> /// Registers an athlete with the backend and returns the new roomie profile /// </summary> async Task<Roomie> RegisterAthlete(GoogleUserProfile profile) { AuthenticationStatus = "Registering Roomie"; var roomie = new Roomie(profile); var task = AzureService.Instance.SaveRoomie(roomie); await RunSafe(task); if (task.IsCompleted && task.IsFaulted) return null; "You're now an registered as roomie!".ToToast(); return roomie; } #endregion #region Get User Profile /// <summary> /// Attempts to get the user profile from Google. Will use the refresh token if the auth token has expired /// </summary> async public Task<bool> GetUserProfile() { //Can't get profile w/out a token if (RoomieApp.AuthToken == null) return false; if (AuthUserProfile != null) return true; using (new Busy(this)) { AuthenticationStatus = "Getting Google user profile"; var task = GoogleApiService.Instance.GetUserProfile(); await RunSafe(task, false); if (task.IsFaulted && task.IsCompleted) { } if (task.IsCompleted && !task.IsFaulted && task.Result != null) { AuthenticationStatus = "Authentication complete"; AuthUserProfile = task.Result; //InsightsManager.Identify(AuthUserProfile.Email, new Dictionary<string, string> { // { // "Name", // AuthUserProfile.Name // } //}); Settings.Instance.AuthUserID = AuthUserProfile.Id; await Settings.Instance.Save(); } else { AuthenticationStatus = "Unable to authenticate"; } } return AuthUserProfile != null; } #endregion #region LogOut public void LogOut(bool clearCookies) { // Utility.SetSecured("AuthToken", string.Empty, "xamarin.sport", "authentication"); AzureService.Instance.Client.Logout(); RoomieApp.AuthToken = null; AuthUserProfile = null; Settings.Instance.RoomieID = null; Settings.Instance.AuthUserID = null; if (clearCookies) { Settings.Instance.RegistrationComplete = false; _authenticator.ClearCookies(); } Settings.Instance.Save(); } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace RoomiesCalc.Models { public class DeviceRegistration { public string Platform { get; set; } public string Handle { get; set; } public string[] Tags { get; set; } } public class NotificationPayload { public NotificationPayload() { Payload = new Dictionary<string, string>(); } public string Action { get; set; } public Dictionary<string, string> Payload { get; set; } } public struct PushActions { public static string ChallengePosted = "ChallengePosted"; public static string ChallengeRevoked = "ChallengeRevoked"; public static string ChallengeAccepted = "ChallengeAccepted"; public static string ChallengeDeclined = "ChallengeDeclined"; public static string ChallengeCompleted = "ChallengeCompleted"; public static string LeagueStarted = "LeagueStarted"; public static string LeagueEnded = "LeagueEnded"; public static string LeagueEnrollmentStarted = "LeagueEnrollmentStarted"; } } <file_sep>using System; using System.Collections.Generic; using Xamarin.Forms; namespace RoomiesCalc { public partial class VerificationViewPage : ContentPage { private LoginViewModel ViewModel { get { return BindingContext as LoginViewModel; } //Type cast BindingContex as HomeViewModel to access binded properties } public VerificationViewPage () { BindingContext = new LoginViewModel(this.Navigation); InitializeComponent (); BackgroundImage = "Bg1.png"; } } } <file_sep>using RoomiesCalc.App; using System; using System.Collections.Generic; using System.Text; namespace RoomiesCalc.Models { public class Roomie : BaseModel { public Roomie(GoogleUserProfile profile) { Name = profile.Name; Email = profile.Email; ProfileImageUrl = profile.Picture; //Initialize(); } string _userId; public string UserId { get { return _userId; } set { SetPropertyChanged(ref _userId, value); } } string _alias; public string Alias { get { return _alias; } set { _alias = value; } } string _name; public string Name { get { if (RoomieApp.CurrentRoomie != null && RoomieApp.CurrentRoomie.Id != Id && !string.IsNullOrEmpty(_name)) return _name.Split(' ')[0]; return _name; } set { SetPropertyChanged(ref _name, value); } } string _email; public string Email { get { if (RoomieApp.CurrentRoomie != null && RoomieApp.CurrentRoomie.Id != Id) return "<EMAIL>"; return _email; } set { SetPropertyChanged(ref _email, value); } } bool _isAdmin; public bool IsAdmin { get { return _isAdmin; } set { SetPropertyChanged(ref _isAdmin, value); } } string _deviceToken; public string DeviceToken { get { return _deviceToken; } set { SetPropertyChanged(ref _deviceToken, value); } } string _devicePlatform; public string DevicePlatform { get { return _devicePlatform; } set { SetPropertyChanged(ref _devicePlatform, value); } } string _notificationRegistrationId; public string NotificationRegistrationId { get { return _notificationRegistrationId; } set { SetPropertyChanged(ref _notificationRegistrationId, value); } } string _profileImageUrl; public string ProfileImageUrl { get { return _profileImageUrl; } set { SetPropertyChanged(ref _profileImageUrl, value); } } } } <file_sep>using System; using Xamarin.Forms; using SQLite; namespace RoomiesCalc { public interface IBusinessBase { int ItemID { get; set; } } } <file_sep>using RoomiesCalc.App; using RoomiesCalc.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace RoomiesCalc { public partial class LoginPage : LoginPageXaml { public LoginPage () { InitializeComponent (); } #region Attempt Login async public Task<bool> AttemptToAuthenticateAthlete(bool force = false) { await ViewModel.AuthenticateCompletely(); if (RoomieApp.CurrentRoomie != null) { MessagingCenter.Send<RoomieApp>(RoomieApp.Current, Messages.AuthenticationComplete); } return RoomieApp.CurrentRoomie != null; } #endregion } public partial class LoginPageXaml : BaseContentPage<LoginViewModel> { } } <file_sep>using RoomiesCalc.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace RoomiesCalc { public partial class DashboardPage : DashboardPageXaml { public DashboardPage () { InitializeComponent (); } } public partial class DashboardPageXaml : BaseContentPage<DashboardViewModel> { } } <file_sep>using System; using Xamarin.Forms; namespace RoomiesCalc { public class BaseViewPage:ContentPage { #region All Fields protected StackLayout stack_NavBar; public Image img_Back,img_Add,img_Share,img_Notification; public Label lbl_Tittle; public int h= App.ScreenHeight; public int w=App.ScreenWidth; #endregion public BaseViewPage () { img_Back = new Image { Source="icon.png", BackgroundColor=Color.Transparent, HorizontalOptions=LayoutOptions.Start, VerticalOptions=LayoutOptions.CenterAndExpand, Aspect=Aspect.AspectFit, TranslationX=10, #if __IOS__ TranslationY=10 #endif }; img_Add = new Image { Source="Add.png", BackgroundColor=Color.Transparent, HorizontalOptions=LayoutOptions.End, VerticalOptions=LayoutOptions.CenterAndExpand, Aspect=Aspect.AspectFit, TranslationX=-10, #if __IOS__ TranslationY=10 #endif }; img_Share = new Image { Source="Share.png", BackgroundColor=Color.Transparent, HorizontalOptions=LayoutOptions.End, VerticalOptions=LayoutOptions.CenterAndExpand, Aspect=Aspect.AspectFit, TranslationX=-10, #if __IOS__ TranslationY=10 #endif }; img_Notification = new Image { Source="Notification.png", BackgroundColor=Color.Transparent, HorizontalOptions=LayoutOptions.End, VerticalOptions=LayoutOptions.CenterAndExpand, Aspect=Aspect.AspectFit, TranslationX=-10, #if __IOS__ TranslationY=10 #endif }; lbl_Tittle = new Label { HorizontalOptions=LayoutOptions.CenterAndExpand, VerticalOptions=LayoutOptions.Center, TextColor=Color.White, FontSize=22, XAlign = TextAlignment.Center, YAlign = TextAlignment.Center, #if __IOS__ TranslationY=10 #endif }; stack_NavBar = new StackLayout { BackgroundColor=Color.Gray, Orientation=StackOrientation.Horizontal, WidthRequest=w, Opacity=0.6, #if __IOS__ HeightRequest=h/9, #endif #if __ANDROID__ HeightRequest=h/11, #endif Children= { img_Back,lbl_Tittle,img_Notification,img_Add,img_Share } }; } } } <file_sep>using Microsoft.WindowsAzure.MobileServices; using ModernHttpClient; using RoomiesCalc.App; using RoomiesCalc.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace RoomiesCalc.Services { public class AzureService { #region Properties static AzureService _instance; public static AzureService Instance { get { return _instance ?? (_instance = new AzureService()); } } MobileServiceClient _client; public MobileServiceClient Client { get { if (_client == null) { var handler = new NativeMessageHandler(); #if __IOS__ //Use ModernHttpClient for caching and to allow traffic to be routed through Charles/Fiddler/etc handler = new ModernHttpClient.NativeMessageHandler() { Proxy = CoreFoundation.CFNetwork.GetDefaultProxy(), UseProxy = true, }; #endif _client = new MobileServiceClient("Keys.AzureDomain", "Keys.AzureApplicationKey", new HttpMessageHandler[] { null, null, handler, }); CurrentPlatform.Init(); } return _client; } } #endregion #region Push Notifications /// <summary> /// This app uses Azure as the backend which utilizes Notifications hubs /// </summary> /// <returns>The athlete notification hub registration.</returns> public Task UpdateAthleteNotificationHubRegistration(Roomie roomie, bool forceSave = false, bool sendTestPush = false) { return new Task(() => { if (roomie == null) throw new ArgumentNullException("roomie"); if (roomie.Id == null || roomie.DeviceToken == null) return; var tags = new List<string> { RoomieApp.CurrentRoomie.Id, "All", }; RoomieApp.CurrentRoomie.LocalRefresh(); //App.CurrentRoomie.Memberships.Select(m => m.LeagueId).ToList().ForEach(tags.Add); roomie.DevicePlatform = Xamarin.Forms.Device.OS.ToString(); var reg = new DeviceRegistration { Handle = roomie.DeviceToken, Platform = roomie.DevicePlatform, Tags = tags.ToArray() }; var registrationId = Client.InvokeApiAsync<DeviceRegistration, string>("registerWithHub", reg, HttpMethod.Put, null).Result; roomie.NotificationRegistrationId = registrationId; //Used to verify the device is successfully registered with the backend if (sendTestPush) { var qs = new Dictionary<string, string>(); qs.Add("athleteId", roomie.Id); Client.InvokeApiAsync("sendTestPushNotification", null, HttpMethod.Get, qs).Wait(); } if (roomie.IsDirty || forceSave) { var task = SaveRoomie(roomie); task.Start(); task.Wait(); } }); } public Task UnregisterAthleteForPush(Roomie roomie) { return new Task(() => { if (roomie == null || roomie.NotificationRegistrationId == null) return; var values = new Dictionary<string, string> { { "id", roomie.NotificationRegistrationId } }; var registrationId = Client.InvokeApiAsync<string>("unregister", HttpMethod.Delete, values).Result; }); } #endregion #region Roomies public Task<List<Roomie>> GetAllAthletes() { return new Task<List<Roomie>>(() => { DataManager.Instance.Roomies.Clear(); var list = Client.GetTable<Roomie>().OrderBy(a => a.Name).ToListAsync().Result; list.ForEach(a => DataManager.Instance.Roomies.AddOrUpdate(a)); return list; }); } public Task<Roomie> GetAthleteByEmail(string email) { return new Task<Roomie>(() => { var list = Client.GetTable<Roomie>().Where(a => a.Email == email).ToListAsync().Result; var roomie = list.FirstOrDefault(); if (roomie != null) DataManager.Instance.Roomies.AddOrUpdate(roomie); return roomie; }); } public Task<Roomie> GetAthleteById(string id, bool force = false) { return new Task<Roomie>(() => { Roomie a = null; if (!force) DataManager.Instance.Roomies.TryGetValue(id, out a); a = a ?? Client.GetTable<Roomie>().LookupAsync(id).Result; if (a != null) { a.IsDirty = false; DataManager.Instance.Roomies.AddOrUpdate(a); } return a; }); } public Task SaveRoomie(Roomie roomie) { return new Task(() => { roomie.UserId = AzureService.Instance.Client.CurrentUser.UserId; if (roomie.Id == null) { Client.GetTable<Roomie>().InsertAsync(roomie).Wait(); } else { Client.GetTable<Roomie>().UpdateAsync(roomie).Wait(); } DataManager.Instance.Roomies.AddOrUpdate(roomie); }); } #endregion } } <file_sep>using Newtonsoft.Json; using RoomiesCalc.App; using RoomiesCalc.Models; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace RoomiesCalc.Services { public class GoogleApiService { #region Properties static GoogleApiService _instance; public static GoogleApiService Instance { get { return _instance ?? (_instance = new GoogleApiService()); } } #endregion #region Authentication public Task<GoogleUserProfile> GetUserProfile() { return new Task<GoogleUserProfile>(() => { using (var client = new HttpClient()) { const string url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json"; client.DefaultRequestHeaders.Add("Authorization", RoomieApp.AuthTokenAndType); var json = client.GetStringAsync(url).Result; var profile = JsonConvert.DeserializeObject<GoogleUserProfile>(json); return profile; } }); } #endregion } } <file_sep>using System; using Xamarin.Forms; namespace RoomiesCalc { public class Place :BaseModel { private string _PlaceName = string.Empty; public string PlaceName { get { return _PlaceName; } set { _PlaceName = value; OnPropertyChanged("PlaceName"); } } private int _PlaceID; public int PlaceID { get { return _PlaceID; } set { _PlaceID = value; OnPropertyChanged("PlaceID"); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace RoomiesCalc.iOS { [Register ("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { public override bool FinishedLaunching (UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init (); //Get width and hieght from current device App.ScreenHeight = (int)UIScreen.MainScreen.Bounds.Height; App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width; LoadApplication (new App ()); return base.FinishedLaunching (app, options); } } } <file_sep>using System; using Xamarin.Forms; namespace RoomiesCalc { public class NotificationViewPage: ContentPage { public NotificationViewPage () { Content = new StackLayout { Children = { new Label { Text = "Hello ContentPage" } } }; } } } <file_sep>using System; using Xamarin.Forms; namespace RoomiesCalc { public class AddPlaceViewPage : BaseViewPage { #region All Fileds public RelativeLayout rltv_MainLayout,rltv_PopUpLayout; public Button btn_Ok,btn_Cancel; public Image img_Backgroud,img_Place; public Label lbl_Placetitle; public Entry txt_Placetitle; public StackLayout stack_Popup,stack_Main,stack_PopupInside; public ListView list_Place; public Place PlaceInfo=new Place(); private AddPlaceViewModel ViewModel { get { return new AddPlaceViewModel(); } //Type cast BindingContex as AddPlaceViewModel to access binded properties } #endregion public AddPlaceViewPage () { BindingContext = new AddPlaceViewModel(); img_Backgroud = new Image { Source="Bg.png", HeightRequest=h, Aspect= Aspect.Fill }; img_Place = new Image { Source="Place.png", }; btn_Ok = new Button { Text = "OK" , Command=ViewModel.AddPlaceCommand, HorizontalOptions=LayoutOptions.CenterAndExpand }; btn_Cancel = new Button { Image="Cross.png,", BackgroundColor=Color.Transparent }; txt_Placetitle = new Entry { Placeholder = "Place Name" , WidthRequest=(w / 4) * 2 }; lbl_Placetitle = new Label { Text = "Make your Place" , FontSize=20 }; txt_Placetitle.SetBinding(Entry.TextProperty,"G.PlaceName"); list_Place = new ListView { VerticalOptions=LayoutOptions.FillAndExpand, BackgroundColor=Color.Transparent //This one is list view color //BackgroundColor=Colors.RC_Green.ToFormsColor(), }; rltv_PopUpLayout = new RelativeLayout { WidthRequest = (w / 4) * 3,//Get 75% of width HeightRequest = (w / 2),//Get 50% of width BackgroundColor = Colors.RC_Pink.ToFormsColor(), HorizontalOptions=LayoutOptions.CenterAndExpand, VerticalOptions=LayoutOptions.CenterAndExpand, TranslationY=-(h/5) }; stack_PopupInside = new StackLayout { BackgroundColor=Color.Transparent, HorizontalOptions=LayoutOptions.CenterAndExpand, VerticalOptions=LayoutOptions.CenterAndExpand, Children = { lbl_Placetitle, new StackLayout { Orientation=StackOrientation.Horizontal, BackgroundColor=Color.Transparent, Children= { img_Place, txt_Placetitle } }, btn_Ok } }; rltv_PopUpLayout.Children.Add (btn_Cancel, Constraint.Constant (w/2+(w/7)), Constraint.Constant (-w/10)); rltv_PopUpLayout.Children.Add (stack_PopupInside, Constraint.Constant (w/20), Constraint.Constant (w/10)); stack_Popup = new StackLayout { IsVisible=false, HeightRequest=h, WidthRequest=w, BackgroundColor=Color.Transparent, Children = { rltv_PopUpLayout } }; list_Place.ItemTemplate = new DataTemplate (typeof (PlaceCell)); list_Place.ItemsSource = ViewModel.PlaceList; btn_Ok.Clicked+= (object sender, EventArgs e) => { stack_Popup.IsVisible=false; }; btn_Cancel.Clicked+= (object sender, EventArgs e) => { stack_Popup.IsVisible=false; }; stack_Main = new StackLayout { BackgroundColor=Color.Transparent, Children = { list_Place } }; rltv_MainLayout = new RelativeLayout { VerticalOptions= LayoutOptions.FillAndExpand, HorizontalOptions=LayoutOptions.FillAndExpand, WidthRequest=w,HeightRequest=h, BackgroundColor=Color.Pink }; img_Share.IsVisible = false; lbl_Tittle.Text = "RoomiesCalc"; var Sharetap = new TapGestureRecognizer(OnShareTapped); Sharetap.NumberOfTapsRequired = 1; img_Share.IsEnabled = true; img_Share.GestureRecognizers.Clear(); img_Share.GestureRecognizers.Add(Sharetap); var Addtap = new TapGestureRecognizer(OnAddTapped); Addtap.NumberOfTapsRequired = 1; img_Add.IsEnabled = true; img_Add.GestureRecognizers.Clear(); img_Add.GestureRecognizers.Add(Addtap); rltv_MainLayout.Children.Add (img_Backgroud, Constraint.Constant (0), Constraint.Constant (0)); rltv_MainLayout.Children.Add (stack_NavBar, Constraint.Constant (0), Constraint.Constant (0)); #if __IOS__ rltv_MainLayout.Children.Add (stack_MainLayout, Constraint.Constant (0), Constraint.Constant ((h/9))); #endif #if __ANDROID__ rltv_MainLayout.Children.Add (stack_Main, Constraint.Constant (0), Constraint.Constant ((h/11))); #endif rltv_MainLayout.Children.Add (stack_Popup, Constraint.Constant (0), Constraint.Constant (0)); Content = rltv_MainLayout; } protected override void OnAppearing () { base.OnAppearing (); list_Place.ItemsSource = ViewModel.PlaceList; } void OnAddTapped(View view, object sender) { stack_Popup.IsVisible=true; } void OnShareTapped(View view, object sender) { //Navigation.PushModalAsync(new NotificationView ()); } #region Custom View cell /// <summary> /// This class is a ViewCell that will be displayed for each Place Cell. /// </summary> public class PlaceCell : ViewCell { public PlaceCell () { var label = new Label { XAlign = TextAlignment.Center }; label.SetBinding (Label.TextProperty, "Places.PlaceName"); var layout = new StackLayout { Padding = new Thickness (20, 0, 0, 0), Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.StartAndExpand, Children = { label } }; View = layout; } } #endregion } } <file_sep>using Microsoft.WindowsAzure.MobileServices; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace RoomiesCalc.Interfaces { public interface IAuthentication { Task<MobileServiceUser> DisplayWebView(); void ClearCookies(); } } <file_sep>using System; using Xamarin.Forms; namespace RoomiesCalc { public class App : Application { #region All Fields public static int ScreenHeight;// for device height public static int ScreenWidth;// for device width static RoomiesCalcDatabase database; #endregion public App () { Database.CreateTables<Place> (); MainPage = new LoginViewPage(); } public static RoomiesCalcDatabase Database { get { if (database == null) { database = new RoomiesCalcDatabase (); } return database; } } protected override void OnStart () { // Handle when your app starts } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } } <file_sep>using RoomiesCalc.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Reflection.Emit; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace RoomiesCalc { public class MainBaseContentPage : ContentPage { #region Private Fields bool _hasSubscribed; #endregion public MainBaseContentPage () { } #region Public Properties public Color BarTextColor { get; set; } public Color BarBackgroundColor { get; set; } public bool HasInitialized { get; private set; } #endregion #region Apply Theme public void ApplyTheme(NavigationPage nav) { nav.BarBackgroundColor = BarBackgroundColor; nav.BarTextColor = BarTextColor; } #endregion #region Add Donw Button public void AddDoneButton(string text = "Done", ContentPage page = null) { var btnDone = new ToolbarItem { Text = text, }; btnDone.Clicked += async (sender, e) => await Navigation.PopModalAsync(); page = page ?? this; page.ToolbarItems.Add(btnDone); } #endregion #region Track Page protected virtual void TrackPage(Dictionary<string, string> metadata) { var identifier = GetType().Name; //InsightsManager.Track(identifier, metadata); } #endregion #region Authenticate Stuff public async Task EnsureUserAuthenticated() { if (Navigation == null) throw new Exception("Navigation is null so unable to show auth form"); var authPage = new LoginPage(); await Navigation.PushModalAsync(authPage, true); await Task.Delay(300); var success = await authPage.AttemptToAuthenticateAthlete(); if (success && Navigation.ModalStack.Count > 0) { await Navigation.PopModalAsync(); } } async protected void LogoutUser() { var decline = await DisplayAlert("For ultra sure?", "Are you sure you want to log out?", "Yes", "No"); if (!decline) return; var authViewModel = DependencyService.Get<LoginViewModel>(); authViewModel.LogOut(true); // App.Current.StartRegistrationFlow(); } #endregion } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace RoomiesCalc.Helper { public class Helpers { public static T LoadFromFile<T>(string path) { string json = null; if (File.Exists(path)) { using (var sr = new StreamReader(path)) { json = sr.ReadToEnd(); } if (json != null) { try { return JsonConvert.DeserializeObject<T>(json); } catch (Exception) { } } } return default(T); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Reflection.Emit; using System.Text; using Xamarin.Forms; namespace RoomiesCalc.Pages { public class ThemedNavigationPage : NavigationPage { public ThemedNavigationPage () { } public ThemedNavigationPage(ContentPage root) : base(root) { } } } <file_sep>using RoomiesCalc.ViewModels; using System; using System.Collections.Generic; using System.Text; namespace RoomiesCalc { public class BaseContentPage<T>: MainBaseContentPage where T : BaseViewModel, new() { protected T _viewModel; public T ViewModel { get { return _viewModel ?? (_viewModel = new T()); } } ~BaseContentPage() { _viewModel = null; } public BaseContentPage() { BindingContext = ViewModel; } } } <file_sep> using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using Xamarin.Forms; using RoomiesCalc; using RoomiesCalc.iOS.Renderer; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(RCEntry), typeof(RCEntryRenderer))] namespace RoomiesCalc.iOS.Renderer { public class RCEntryRenderer : EntryRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if (Control != null) { Control.Layer.BorderColor = UIColor.White.CGColor; Control.Layer.BorderWidth = 0f; Control.ClipsToBounds = true; } } } } <file_sep>using System; using Xamarin.Forms; namespace RoomiesCalc { public class VerificationViewPage: BaseViewPage { #region All Fileds public RelativeLayout rltv_MainLayout; public Button btn_Verify; public Image img_Backgroud,img_logo; public Label lbl_Verify; public StackLayout stack_Main; private LoginViewModel ViewModel { get { return BindingContext as LoginViewModel; } //Type cast BindingContex as HomeViewModel to access binded properties } #endregion public VerificationViewPage () { BindingContext = new LoginViewModel(this.Navigation); lbl_Verify = new Label { TextColor=Colors.RC_Pink.ToFormsColor(), FontSize=22, Text="Enter your verfication code", FontAttributes=FontAttributes.Bold, }; img_Backgroud = new Image { Source="Bg2.png", HeightRequest=h, Aspect= Aspect.Fill }; img_logo = new Image { Source="Logo.png", Aspect= Aspect.AspectFit, TranslationY=-w/10 }; btn_Verify = new Button { Text="Verify", TextColor=Color.White, BackgroundColor=Colors.RC_Green.ToFormsColor(), FontSize=22, WidthRequest=w/2, HorizontalOptions=LayoutOptions.CenterAndExpand, Command=ViewModel.VerficationClick }; stack_Main = new StackLayout { HeightRequest=h/2, WidthRequest=(w/4)*3, HorizontalOptions=LayoutOptions.CenterAndExpand, VerticalOptions=LayoutOptions.CenterAndExpand, BackgroundColor=Color.Transparent, Spacing=w/20, Children= { img_logo, lbl_Verify, new StackLayout { Orientation=StackOrientation.Horizontal, HorizontalOptions=LayoutOptions.CenterAndExpand, Children= { Verifytext("1"), Verifytext("2"), Verifytext("3"), Verifytext("4")} }, btn_Verify } }; rltv_MainLayout = new RelativeLayout { HeightRequest=h,WidthRequest=w, }; rltv_MainLayout.Children.Add(img_Backgroud, Constraint.Constant(0), Constraint.Constant(0)); rltv_MainLayout.Children.Add(stack_Main, Constraint.Constant((w/4)/2), Constraint.Constant(h/6)); this. Content= rltv_MainLayout; } public StackLayout Verifytext(string number) { BoxView bx = new BoxView { WidthRequest=(w/4)*3, HeightRequest=1, BackgroundColor=Color.Gray, }; Entry txt = new Entry { WidthRequest=w/2, HorizontalOptions=LayoutOptions.CenterAndExpand, TextColor=Color.White, Text=number, BackgroundColor=Color.Transparent, }; StackLayout stack = new StackLayout { Spacing = 0, Orientation = StackOrientation.Vertical, WidthRequest=w/10, HeightRequest=h/10, Children = { txt, bx } }; return stack; } } }
325b75650771d38e9310ffcd68286f9df2ee36f3
[ "C#" ]
32
C#
XnainA/RoomiesCalc
7ebe5279eef2d3e1d818b62d5aa4e0a7bab3f7e7
f7a03e216b1527209e3c590c3706474ccbd20880
refs/heads/master
<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. */ package javaapplication1; /** * * @author <NAME> */ public class JavaApplication1 { static String nama; // nama adalah variable static int angka; // int, float, dll adalah tipe data = primitif static float koma; static double koma2; public static void main(String[] args) { // nama = "husna"; // angka = 123; // koma = 9.0f; // koma2 = 20.0; // // System.out.println("namaku" + nama + // "\n nomor rumah" + angka + // "\n nilai" + koma ); Manusia2 lk2 = new Manusia2(); //lk2 adalah objek yang dibuat dari kerangka objek manusia Manusia2 pr = new Manusia2(); Manusia2 m = new Manusia2("zahro", 'p', 23); Manusia3 b = new Manusia3("abang", 'l', 30); // lk2.nama = "Ady"; //value yang diberikan ddengan memanggil variable dari kerangka objek manusia // lk2.alamat = " tebet"; // lk2.usia =25; // // pr.nama = "nadya"; // pr.alamat = "depok"; // pr.usia = 30; lk2.setNama("Ady"); // System.out.println("nama = " + lk2.getNama()); pr.setIdentitas("nadya", 'a', 23); System.out.println(b.getIdentitas()); System.out.println(m.getIdentitas()); System.out.println("nama = " + lk2.getNama()); //System.out.println(pr.getIdentitas()); // System.out.println("nama dia adalah " + lk2.nama + " dan " + pr.nama + // "\n alamat di " + lk2.alamat + " dan "+ pr.alamat + // "\n usia " + lk2.usia + " dan " +pr.usia); // TODO code application logic here } } class Manusia2{ //manusia adalah kertangka objek String nama; String alamat; int usia; char genre; public Manusia2(){ //constractor kosong harus ada } public Manusia2(String nama, char jk, int usia){ this.nama = nama; genre = jk; this.usia = usia; } public void setNama(String nama){ this.nama = nama; } public String getNama(){ return nama; } public void setIdentitas(String nama, char genre, int usia){ this.nama = nama; this.genre = genre; this.usia = usia; } public String getIdentitas(){ return "nama " + nama + "genre :" +genre+ "usia: " +usia; } }
958cd8148becc5993156c0310c5859bea5429d12
[ "Java" ]
1
Java
Husna13/eksperimen
88654964bd61cf895b1a169e806e472e83d21f3f
cc316b1c6ad2f699c265df0478ee20c9df2bb066
refs/heads/master
<repo_name>qo7860vm/ShoppingMall<file_sep>/src/main/java/ci/jvision/admin201718037/web/ProductsApiController.java package ci.jvision.admin201718037.web; import ci.jvision.admin201718037.service.ProductsService; import ci.jvision.admin201718037.web.dto.ProductsSaveRequestDto; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; @RequiredArgsConstructor @RestController public class ProductsApiController { private final ProductsService productsService; @PostMapping("/api/v1/products") public Long save(@RequestBody ProductsSaveRequestDto requestDto) { return productsService.save(requestDto); } @DeleteMapping("/api/v1/products/{id}") public Long delete(@PathVariable Long id) { productsService.delete(id); return id; } }
f25832bd63cbeb81023fb10222c0691724d6e04d
[ "Java" ]
1
Java
qo7860vm/ShoppingMall
749ce7784464805ebfae71c6108b0fad1d2b62bb
50a4332675dde124c2bc2c2b7c682da17e5962a0
refs/heads/master
<repo_name>SeeMax/Mearsheimer<file_sep>/themes/seemax-theme/page-teaching.php <?php /* Template Name: Teaching */ get_header(); ?> <main class="teaching-page"> <?php get_template_part('partials/_duotone-svg');?> <?php while (have_posts()) : the_post(); ?> <section class="hero-section"> <svg viewBox="0 0 100 100" preserveAspectRatio="none" class="hero-pic"> <image height="100%" width='100%' xlink:href="<?php echo get_template_directory_uri(); ?>/img/teaching-back.jpg" filter="url(#duotone)" /> </svg> <div class="content"> <h1 class="c-width-50"><?php the_title(); ?></h1> <?php the_content(); ?> </div> </section> <section class="courses-section"> <div class="content"> <div class="grid-section-group"> <div class="course-section-courses grid-container-three"> <?php $loop = new WP_Query( array( 'post_type' => 'courses_taught', 'posts_per_page' => -1, ));?> <?php while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="single-course grid-item grid-item-halves"> <div class="color-back"></div> <div class="grid-info"> <h4 class="grid-date"> <?php if(get_field('courses_pdf_date')):?> <span><?php the_field('courses_pdf_date'); ?></span> <?php endif;?> <?php if(get_field('courses_pdf_2_date')):?> <span><?php the_field('courses_pdf_2_date'); ?></span> <?php endif;?> <?php if(get_field('courses_pdf_3_date')):?> <span><?php the_field('courses_pdf_3_date'); ?></span> <?php endif;?> </h4> <h3 class="grid-name"> <?php the_title(); ?> </h3> </div> <div class="course-pdf-group"> <?php $pdf1 = get_field('courses_pdf'); $pdf1date = get_field('courses_pdf_date'); $pdf2 = get_field('courses_pdf_2'); $pdf2date = get_field('courses_pdf_2_date'); $pdf3 = get_field('courses_pdf_3'); $pdf3date = get_field('courses_pdf_3_date'); ?> <?php if($pdf1):?> <div class="button grid-button"> <?php echo $pdf1date;?> PDF <i class="fal fa-file"></i> <a class="c-block-fill" href='<?php echo $pdf1;?>'></a> </div> <?php endif;?> <?php if($pdf2):?> <div class="button grid-button"> <?php echo $pdf2date;?> PDF <i class="fal fa-file"></i> <a class="c-block-fill" href='<?php echo $pdf2;?>'></a> </div> <?php endif;?> <?php if($pdf3):?> <div class="button grid-button"> <?php echo $pdf3date;?> PDF <i class="fal fa-file"></i> <a class="c-block-fill" href='<?php echo $pdf3;?>'></a> </div> <?php endif;?> </div> </div> <?php endwhile;?> </div> </div> </div> </section> <?php endwhile; ?> </main> <?php get_footer(); ?> <file_sep>/themes/seemax-theme/footer.php <footer class="footer" role="contentinfo"> <div class="content"> <div class="footer-tile logo-tile c-width-25"> <img src="<?php echo get_template_directory_uri(); ?>/img/footer-logo.svg" > <div class="copyright"> &copy; Copyright 2018 </div> </div> <div class="footer-tile info-tile c-width-25"> <ul> <li class="footer-tile-header"> Address </li> <li> <?php the_field('address', 'options'); ?> </li> </ul> </div> <div class="footer-tile social-tile c-width-25"> <ul> <li class="footer-tile-header"> Contact </li> <li> <a href="mailto:<?php the_field('email', 'options'); ?>"><?php the_field('email', 'options'); ?></a> </li> <li> <a href="tel:<?php the_field('phone', 'options'); ?>"><?php the_field('phone', 'options'); ?></a> </li> </ul> </div> <div class="footer-tile mailchimp-tile c-width-25"> <!-- Begin Mailchimp Signup Form --> <div id="mc_embed_signup"> <form action="https://mearsheimer.us3.list-manage.com/subscribe/post?u=ac11242fa5499df63804e5396&amp;id=26f9db18f4" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate> <div id="mc_embed_signup_scroll"> <div class="footer-tile-header">Subscribe</div> Stay up to date with the latest work, news, and appearances. <div class="mc-field-group"> <input type="email" value="" placeholder="your email" name="EMAIL" class="required email" id="mce-EMAIL"> </div> <div id="mce-responses" class="clear"> <div class="response" id="mce-error-response" style="display:none"></div> <div class="response" id="mce-success-response" style="display:none"></div> </div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups--> <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_ac11242fa5499df63804e5396_26f9db18f4" tabindex="-1" value=""></div> <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div> </div> </form> </div> <script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';}(jQuery));var $mcj = jQuery.noConflict(true);</script> <!--End mc_embed_signup--> </div> </div> </footer> <?php wp_footer(); ?> </div><!-- WRAPPER --> </body> </html> <file_sep>/themes/seemax-theme/page-projects.php <?php /* Template Name: Projects */ get_header(); ?> <main class="projects-page"> <?php get_template_part('partials/_duotone-svg');?> <?php while (have_posts()) : the_post(); ?> <section class="hero-section"> <img class="hero-pic duotone" src="<?php echo get_template_directory_uri(); ?>/img/jjm-headshot-2.jpg" > <div class="content"> <h1 class="c-width-50"><?php the_title(); ?></h1> <?php the_content(); ?> </div> </section> <section class="page-subnav-section"> <div class="content"> <?php if( have_rows('recent_lists') ): while ( have_rows('recent_lists') ) : the_row();?> <?php if( have_rows('recent_section') ): while ( have_rows('recent_section') ) : the_row();?> <?php $linkName = get_sub_field('title');?> <?php $linkName = str_replace(' ', '', $linkName);?> <?php $linkName = strtolower($linkName);?> <div class="subnav-link"> <a class="c-block-fill" href="#<?php echo $linkName;?>"></a> <?php the_sub_field('title');?> </div> <?php endwhile;?> <?php endif;?> <!-- Publication List Group --> <?php endwhile;?> <?php endif;?> </div> </section> <section class="publication-section"> <div class="content"> <?php if( have_rows('recent_lists') ): while ( have_rows('recent_lists') ) : the_row();?> <?php if( have_rows('recent_section') ): while ( have_rows('recent_section') ) : the_row();?> <?php $linkName = get_sub_field('title');?> <?php $linkName = str_replace(' ', '', $linkName);?> <?php $linkName = strtolower($linkName);?> <div id ="<?php echo $linkName;?>" class="grid-section-group"> <div class="grid-section-intro"> <h2><?php the_sub_field('title');?></h2> </div> <div class="publication-section-publications grid-container-two"> <?php if( have_rows('list') ): while ( have_rows('list') ) : the_row();?> <?php if( have_rows('single') ): while ( have_rows('single') ) : the_row();?> <?php $bookImage = get_sub_field('image');?> <?php $pubNote = get_sub_field('recent_note');?> <div class="single-publication grid-item grid-item-halves"> <div class="color-back"></div> <?php if($bookImage):?> <img class="publication-book" src="<?php echo $bookImage['url'];?>"> <?php endif;?> <div class="grid-info"> <?php if(get_sub_field('publisher')):?> <h4 class="grid-publication-name"> <?php the_sub_field('publisher');?> </h4> <?php endif;?> <h3 class="grid-name"> <?php the_sub_field('title');?> </h3> <h4 class="grid-author"> <?php the_sub_field('author');?> </h4> <?php if($pubNote):?> <div class="grid-item-note"> <?php echo $pubNote;?> </div> <?php endif;?> </div> <div class="single-publication-link"> <?php if( get_sub_field('link') == 'File' ): ?> <div class="button grid-button"> PDF <i class="fal fa-file"></i> </div> <?php elseif( get_sub_field('link') == 'Link' ): ?> <div class="button grid-button"> View <i class="fal fa-globe"></i> </div> <?php endif; ?> </div> <?php if( get_sub_field('link') == 'File' ): ?> <?php $file = get_sub_field('link_file');?> <a class="c-block-fill" href="<?php echo $file['url']; ?>" target="_blank"></a> <?php elseif( get_sub_field('link') == 'Link' ): ?> <a class="c-block-fill" href="<?php the_sub_field('link_page');?>" target="_blank"></a> <?php endif; ?> </div> <!-- Single Publication Repeater --> <?php endwhile;?> <?php endif;?> <!-- Publication List Group --> <?php endwhile;?> <?php endif;?> </div> </div> <!-- One Publication Section Repeater --> <?php endwhile;?> <?php endif;?> <!-- All Publication Groups --> <?php endwhile;?> <?php endif;?> </div> </section> <?php endwhile; ?> </main> <?php get_footer(); ?> <file_sep>/themes/seemax-theme/js/parts/function-template.js //USE THE BELOW AS TEMPLATE FOR FUNCTION FILES <file_sep>/themes/seemax-theme/js/parts/back-to-top.js $(window).scroll(function() { if ($(this).scrollTop() >= 500) { $('.backToTop').addClass('visible-btn'); } else { $('.backToTop').removeClass('visible-btn'); } }); $('.backToTop').on("click",function(){ $("html, body").animate({ scrollTop: "0px" }); }); <file_sep>/themes/seemax-theme/scripts.js (function ($, root, undefined) {$(function () { 'use strict'; $(window).scroll(function() { if ($(this).scrollTop() >= 500) { $('.backToTop').addClass('visible-btn'); } else { $('.backToTop').removeClass('visible-btn'); } }); $('.backToTop').on("click",function(){ $("html, body").animate({ scrollTop: "0px" }); }); //USE THE BELOW AS TEMPLATE FOR FUNCTION FILES $(function iframeHeight() { $('.iframe-box').each(function(){ var iframeH = $(this).find('iframe').attr('height'); var iframeW = $(this).find('iframe').attr('width'); var padding = iframeH / iframeW * 100; // console.log(iframeH); // console.log(iframeW); // console.log(padding); $(this).css('padding-top', padding+'%'); }); }); $(function mobileMenu() { $(".menuToggle").on('click', function() { console.log("click"); var tl = new TimelineMax(), $this = $(this), fullMenu = $(".main-nav"), links = $("nav li"), ham1 = $(".hamTop"), ham2 = $(".hamMid"), ham3 = $(".hamBot"), uniTime2 = 0.15, uniEase = Back.easeIn.config(1), uniEase2 = Back.easeOut.config(1); if ($this.hasClass("navOpen")) { $this.removeClass("navOpen"); tl.set($(".wrapper"), {height:"auto",overflow:"visible"}) .staggerTo(links, 0.3, {opacity:0, x:"50%", ease: uniEase2}, 0.03, "menuClose") .to(fullMenu, 0.3, {left:"101%"}, "menuClose+=0.2") .to(ham1, uniTime2, {width:"100%", rotation:0, y:0}, "menuClose") .to(ham2, uniTime2, {width:"100%", x:0, opacity:1}, "menuClose") .to(ham3, uniTime2, {width:"100%", rotation:0, y:0}, "menuClose"); } else { $this.addClass("navOpen"); tl.set($(".wrapper"), {height:"100%", overflow:"hidden"}) .set(links, {opacity:0, x:"50%"}) .to(fullMenu, 0.3, {left:"0%"}, "menuOpen") .staggerTo(links, 0.2, {opacity:1, x:"0%", ease: uniEase2}, 0.05, "menuOpen+=0.05") .to(ham1, uniTime2, {rotation:227, y:5, width:"80%"}, "menuOpen") .to(ham2, uniTime2, {width:"70%", x:5, opacity:0}, "menuOpen") .to(ham3, uniTime2, {rotation:-227, y:-5, width:"80%"}, "menuOpen"); } }); }); $(function preLoaderOn() { $(window).load(function(){ $('#preloader').fadeOut('slow',function(){$(this).remove();}); }); }); });})(jQuery, this); <file_sep>/themes/seemax-theme/header.php <!doctype html> <html <?php language_attributes(); ?> class="no-js loader-class"> <head> <meta charset="<?php bloginfo('charset'); ?>"> <title>Mearsheimer | <?php the_title(); ?></title> <!-- <link href="//www.google-analytics.com" rel="dns-prefetch"> --> <link href="<?php echo get_template_directory_uri(); ?>/img/jjm-favicon.png" rel="shortcut icon"> <!-- <link href="<?php echo get_template_directory_uri(); ?>/img/icons/touch.png" rel="apple-touch-icon-precomposed"> --> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="<?php bloginfo('description'); ?>"> <?php wp_head(); ?> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-77219320-2"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-77219320-2'); </script> </head> <body <?php body_class(); ?> > <div class="wrapper"> <div id="preloader"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 994 582"> <style> #leftLoad, #middleLoad, #rightLoad {fill:white;} </style> <path id="leftLoad" d="M179.7,3.3c0,2.2-0.4,3.3-1.1,3.3c-12.1,0-20.8,1.1-26.3,3.3c-5.5,2.2-9.2,5.9-11.2,11.2c-2,5.3-3,13.4-3,24.3 v311.9c0,36.1-8.4,64.8-25.2,86.2c-16.8,21.3-41.1,32-72.9,32c-12.4,0-22.2-2.1-29.3-6.3C3.6,465.1,0,459.3,0,452 c0-5.5,1.6-9.8,4.9-13.1c3.3-3.3,7.9-4.9,13.7-4.9c6.2,0,11,1.4,14.2,4.1c3.3,2.7,6.8,6.8,10.4,12.3c3.3,5.1,6.2,8.8,8.8,10.9 c2.6,2.2,6.2,3.3,11,3.3c13.2,0,22.9-7.6,29.3-22.7c6.4-15.1,9.6-39.5,9.6-73.1V44.3c0-10.9-1.3-19-3.8-24.1 c-2.6-5.1-7.6-8.7-15.1-10.7c-7.5-2-19.1-3-34.8-3c-0.7,0-1.1-1.1-1.1-3.3S47.5,0,48.2,0L80,0.5c16.8,0.7,29.9,1.1,39.5,1.1 c9.5,0,21.2-0.4,35.1-1.1L178.6,0C179.4,0,179.7,1.1,179.7,3.3z"/> <path id="middleLoad" d="M410.8,4c0,2.7-0.4,4-1.3,4c-14.8,0-25.5,1.3-32.2,4c-6.7,2.7-11.3,7.3-13.7,13.7c-2.5,6.5-3.7,16.4-3.7,29.8 v381.8c0,44.2-10.3,79.4-30.9,105.5C308.4,569,278.7,582,239.8,582c-15.2,0-27.2-2.6-35.9-7.7c-8.7-5.1-13.1-12.2-13.1-21.1 c0-6.7,2-12.1,6-16.1c4-4,9.6-6,16.8-6c7.6,0,13.4,1.7,17.4,5c4,3.3,8.3,8.4,12.7,15.1c4,6.2,7.6,10.7,10.7,13.4 c3.1,2.7,7.6,4,13.4,4c16.1,0,28.1-9.3,35.9-27.8c7.8-18.5,11.7-48.3,11.7-89.4V54.3c0-13.4-1.6-23.2-4.7-29.5 c-3.1-6.2-9.3-10.6-18.4-13.1C283.3,9.3,269.1,8,249.9,8c-0.9,0-1.3-1.3-1.3-4s0.4-4,1.3-4l38.9,0.7C309.3,1.6,325.4,2,337,2 C348.7,2,363,1.6,380,0.7L409.5,0C410.4,0,410.8,1.3,410.8,4z"/> <path id="rightLoad" d="M994,414.6c0,2.7-0.7,4-2,4c-13.9,0-24.8-0.2-32.9-0.7l-46.3-0.7l-42.9,0.7c-7.2,0.4-17.2,0.7-30.2,0.7 c-0.9,0-1.3-1.3-1.3-4s0.4-4,1.3-4c15.2,0,26.5-1.2,33.9-3.7c7.4-2.4,12.3-6.8,14.8-13.1c2.5-6.2,3.2-16.1,2.3-29.5L878.6,59.6 L725.7,413.9c-0.9,1.8-2.7,2.7-5.4,2.7c-2.2,0-4.3-0.9-6-2.7l-165-350.3l-6,282c-0.5,23.7,3.6,40.4,12.1,50.2 c8.5,9.8,23.5,14.7,44.9,14.7c0.9,0,1.3,1.3,1.3,4s-0.5,4-1.3,4c-12.5,0-22.1-0.2-28.8-0.7l-36.2-0.7l-34.9,0.7 c-6.3,0.4-15.2,0.7-26.8,0.7c-0.9,0-1.3-1.3-1.3-4s0.4-4,1.3-4c18.8,0,32.3-5,40.6-15.1c8.3-10,12.6-26.7,13.1-49.9l6-310.8 C519.8,17,501.5,8,478.3,8c-0.9,0-1.3-1.3-1.3-4s0.4-4,1.3-4l24.8,0.7c4.5,0.4,10.7,0.7,18.8,0.7c8,0,14.9-0.2,20.5-0.7 c5.6-0.4,9.9-0.7,13.1-0.7c5.8,0,10.6,2.1,14.4,6.4c3.8,4.3,9.3,13.7,16.4,28.5l149.6,314.8L882,16.7C886.9,5.6,893.6,0,902.1,0 c2.2,0,5.5,0.2,9.7,0.7c4.2,0.4,9.9,0.7,17.1,0.7l31.5-0.7c4.9-0.4,12.3-0.7,22.1-0.7c1.3,0,2,1.3,2,4s-0.7,4-2,4 c-22.4,0-38.3,3.2-48,9.7c-9.6,6.5-14.2,18.7-13.7,36.5l13.4,310.1c0.4,13.8,2.1,23.9,5,30.1c2.9,6.3,8.2,10.5,15.8,12.7 c7.6,2.2,19.9,3.3,36.9,3.3C993.3,410.6,994,411.9,994,414.6z"/> </svg> </div> <header class="header" role="banner"> <div class="content header-inner-wrap"> <div class="header-logo"> <a href="/"> <div class="logo-subhead"> <NAME> Distinguished Professor of Political Science </div> <img src="<?php echo get_template_directory_uri(); ?>/img/logo.svg" > <div class="logo-subhead"> The University of Chicago </div> </a> </div> <nav class="main-nav mainNav" role="navigation"> <?php main_theme_nav(); ?> </nav> <div class="mobile-menu menuToggle"> <span class="hamTop"></span> <span class="hamMid"></span> <span class="hamBot"></span> </div> </div> </header> <div class="back-to-top backToTop"> <i class="fal fa-arrow-up"></i> </div> <file_sep>/themes/seemax-theme/page-contact.php <?php /* Template Name: Contact */ get_header(); ?> <main class="contact-page"> <?php get_template_part('partials/_duotone-svg');?> <?php while (have_posts()) : the_post(); ?> <section class="hero-section"> <svg class="hero-pic" viewBox="0 0 100 100" preserveAspectRatio="none"> <image height="100%" width='100%' xlink:href="<?php echo get_template_directory_uri(); ?>/img/jjm-headshot-2.jpg" filter="url(#duotone)" /> </svg> <div class="content"> <!-- <h1><?php the_title(); ?></h1> --> <?php the_content(); ?> <div class="contact-block-container"> <div class="contact-page-block"> <h2>Address</h2><?php the_field('address', 'options'); ?> </div> <div class="contact-page-block"> <h2>Email</h2><a href="mailto:<?php the_field('email', 'options'); ?>"><?php the_field('email', 'options'); ?> <i class="fas fa-envelope-square"></i></a> </div> <div class="contact-page-block"> <?php if(get_field('phone', 'options')): ?> <h2>Phone</h2> <a href="tel:<?php the_field('phone', 'options'); ?>"><?php the_field('phone', 'options'); ?> <i class="fas fa-phone-square"></i></a> <?php endif;?> </div> <!-- <div class="contact-page-block c-width-33"> <?php if(get_field('fax', 'options')): ?> <h2>Fax</h2><?php the_field('fax', 'options'); ?> <?php endif;?> </div> --> </div> </div> </section> <?php endwhile; ?> </main> <?php get_footer(); ?> <file_sep>/themes/seemax-theme/page-home.php <?php /* Template Name: Home */ get_header(); ?> <main class="home-page"> <?php get_template_part('partials/_duotone-svg-light');?> <?php while (have_posts()) : the_post(); ?> <section class="hero-section"> <div class="content"> <!-- <h1><?php the_title();?></h1> --> <div class="hero-image"> <img src="<?php echo get_template_directory_uri(); ?>/img/Mearchiavelli-VIII-edit-5.jpg"/> <!-- <div class="hero-image-caption"> Mearchiavelli<br /> <span>Marwane Pallas, The Philomathean Society</span> </div> --> </div> <div class="hero-words"> <?php the_content(); ?> </div> </div> </section> <section class="featured-section"> <div class="content"> <div class="grid-section-group"> <div id="featured-work" class="grid-section-intro"> <h2>Featured Work</h2> </div> <div class="featured-work-section"> <?php if( have_rows('featured_work_two') ): while ( have_rows('featured_work_two') ) : the_row();?> <?php $pubType = get_sub_field('publication_type');?> <?php if( $pubType == 'book'):?> <?php get_template_part('partials/_home-featured-book');?> <?php elseif($pubType == 'oped'):?> <?php get_template_part('partials/_home-featured-oped');?> <?php elseif($pubType == 'article'):?> <?php get_template_part('partials/_home-featured-articles');?> <?php elseif($pubType == 'unpublished'):?> <?php get_template_part('partials/_home-featured-unpublished');?> <?php elseif($pubType == 'radiotv'):?> <?php get_template_part('partials/_home-featured-radiotv');?> <?php elseif($pubType == 'interviews'):?> <?php get_template_part('partials/_home-featured-interviews');?> <?php elseif($pubType == 'publictalks'):?> <?php get_template_part('partials/_home-featured-publictalks');?> <?php endif;?> <?php endwhile;?> <?php endif;?> <?php if(get_field('featured_writeup')):?> <div class="featured-writeup"> <?php the_field('featured_writeup');?> </div> <?php endif;?> </div> </div> </div> </section> <section class="main-section"> <div class="content"> <div class="grid-section-group"> <div id="recent-work" class="grid-section-intro"> <h2>Recent Work</h2> </div> <div class="publication-section-publications grid-container-two"> <?php if( have_rows('featured_publications') ): while ( have_rows('featured_publications') ) : the_row();?> <?php $pubType = get_sub_field('publication_type');?> <?php if( $pubType == 'book'):?> <?php get_template_part('partials/_home-featured-book');?> <?php elseif($pubType == 'oped'):?> <?php get_template_part('partials/_home-featured-oped');?> <?php elseif($pubType == 'article'):?> <?php get_template_part('partials/_home-featured-articles');?> <?php elseif($pubType == 'unpublished'):?> <?php get_template_part('partials/_home-featured-unpublished');?> <?php elseif($pubType == 'radiotv'):?> <?php get_template_part('partials/_home-featured-radiotv');?> <?php elseif($pubType == 'interviews'):?> <?php get_template_part('partials/_home-featured-interviews');?> <?php elseif($pubType == 'publictalks'):?> <?php get_template_part('partials/_home-featured-publictalks');?> <?php endif;?> <?php endwhile;?> <?php endif;?> </div> </div> </div> </section> <?php endwhile; ?> </main> <?php get_footer(); ?> <file_sep>/themes/seemax-theme/page-biography.php <?php /* Template Name: Biography */ get_header(); ?> <main class="biography-page general-page"> <?php while (have_posts()) : the_post(); ?> <section class="page-subnav-section"> <div class="content"> <?php if( have_rows('curriculum_vitae_bar') ): while ( have_rows('curriculum_vitae_bar') ) : the_row();?> <?php the_sub_field('copy');?> <div class="button"> <?php $linkName = get_sub_field('pdf_link');?> <a class="c-block-fill" href="<?php echo $linkName;?>"></a> PDF <i class="fal fa-file"></i> </div> <?php endwhile;?> <?php endif;?> </div> </section> <section class="main-section"> <div class="content no-flex"> <h1><?php the_title(); ?></h1> <?php the_content(); ?> </div> </section> <?php endwhile; ?> </main> <?php get_footer(); ?> <file_sep>/themes/seemax-theme/404.php <?php /* Template Name: 404 Page */ get_header(); ?> <main class="four-oh-four-page"> <section class="main-section"> <div class="content"> <h1>That Page Can't be found</h1> <div class="button"> <a class="c-block-fill" href="<?php echo site_url();?>"></a> Return Home </div> </div> </section> </main> <?php get_footer(); ?> <file_sep>/themes/seemax-theme/page-photos.php <?php /* Template Name: Photos */ get_header(); ?> <main class="photos-page"> <?php while (have_posts()) : the_post(); ?> <section class="hero-section"> <div class="content"> <h1><?php the_title(); ?></h1> </div> </section> <section class="page-subnav-section"> <div class="content"> <?php if( have_rows('photos_download_bar') ): while ( have_rows('photos_download_bar') ) : the_row();?> <?php the_sub_field('copy');?> <div class="button"> <?php $linkName = get_sub_field('zip_link');?> <a class="c-block-fill" href="<?php echo $linkName;?>"></a> ZIP <i class="fal fa-file-archive"></i> </div> <?php endwhile;?> <?php endif;?> </div> </section> <section class="main-section"> <div class="content"> <?php the_content(); ?> </div> </section> <?php endwhile; ?> </main> <?php get_footer(); ?> <file_sep>/themes/seemax-theme/page-publication-loops.php <?php /* Template Name: Publication Loops */ get_header(); ?> <main class="publications-page"> <?php get_template_part('partials/_duotone-svg');?> <?php while (have_posts()) : the_post(); ?> <section class="hero-section"> <svg class="hero-pic" viewBox="0 0 100 100" preserveAspectRatio="none"> <image height="100%" width='100%' xlink:href="<?php echo get_template_directory_uri(); ?>/img/jjm-headshot-2.jpg" filter="url(#duotone)" /> </svg> <div class="content"> <h1 class="c-width-50"><?php the_title(); ?></h1> <?php the_content(); ?> </div> </section> <section class="page-subnav-section"> <div class="content"> <div class="subnav-link"> <a class="c-block-fill" href="#books"></a> Books </div> <div class="subnav-link"> <a class="c-block-fill" href="#opeds"></a> Op-Ed Pieces </div> <div class="subnav-link"> <a class="c-block-fill" href="#articles-and-book-chapters"></a> Articles and Book Chapters </div> <!-- <div class="subnav-link"> <a class="c-block-fill" href="#public-affairs-commentary"></a> Public Affairs Commentary </div> --> <div class="subnav-link"> <a class="c-block-fill" href="#unpublished-works"></a> Unpublished Works </div> </div> </section> <section class="publication-section"> <div class="content"> <?php get_template_part('partials/_book-publication-section');?> <?php get_template_part('partials/_oped-publication-section');?> <?php get_template_part('partials/_articles-chapters-publication-section');?> <!-- <?php get_template_part('partials/_public-affairs-publication-section');?> --> <?php get_template_part('partials/_unpublished-publication-section');?> </div> </section> <?php endwhile; ?> </main> <?php get_footer(); ?> <file_sep>/themes/seemax-theme/partials/_articles-chapters-publication-section.php <div id ="articles-and-book-chapters" class="grid-section-group"> <div class="grid-section-intro"> <h2>Articles and Book Chapters</h2> </div> <div class="publication-section-publications grid-container-two"> <?php $loop = new WP_Query( array( 'post_type' => 'articles_chapters', 'posts_per_page' => -1, ));?> <?php while ( $loop->have_posts() ) : $loop->the_post(); ?> <?php if( have_rows('publication_details') ): while ( have_rows('publication_details') ) : the_row();?> <?php $bookImage = get_sub_field('image');?> <?php $pubNote = get_sub_field('publication_note');?> <div class="single-publication grid-item grid-item-halves"> <div class="color-back"></div> <?php if($bookImage):?> <img class="publication-book" src="<?php echo $bookImage['url'];?>"> <?php endif;?> <div class="grid-info"> <?php if(get_sub_field('publisher')):?> <h4 class="grid-publication-name"> <?php the_sub_field('publisher');?> </h4> <?php endif;?> <h3 class="grid-name"> <?php the_title();?> </h3> <h4 class="grid-author"> <?php the_sub_field('author');?> </h4> </div> <?php if($pubNote):?> <div class="grid-item-note"> <?php echo $pubNote;?> </div> <?php endif;?> <div class="single-publication-link"> <?php if( get_sub_field('link') == 'File' ): ?> <div class="button grid-button"> PDF <i class="fal fa-file"></i> </div> <?php elseif( get_sub_field('link') == 'Link' ): ?> <div class="button grid-button"> View <i class="fal fa-globe"></i> </div> <?php endif; ?> </div> <?php if( get_sub_field('link') == 'File' ): ?> <?php $file = get_sub_field('link_file');?> <a class="c-block-fill" href="<?php echo $file['url']; ?>" target="_blank"></a> <?php elseif( get_sub_field('link') == 'Link' ): ?> <a class="c-block-fill" href="<?php the_sub_field('link_page');?>" target="_blank"></a> <?php endif; ?> </div> <?php endwhile;?> <?php endif;?> <?php endwhile; wp_reset_query(); ?> </div> </div> <file_sep>/themes/seemax-theme/js/parts/iframe-height.js $(function iframeHeight() { $('.iframe-box').each(function(){ var iframeH = $(this).find('iframe').attr('height'); var iframeW = $(this).find('iframe').attr('width'); var padding = iframeH / iframeW * 100; // console.log(iframeH); // console.log(iframeW); // console.log(padding); $(this).css('padding-top', padding+'%'); }); }); <file_sep>/themes/seemax-theme/partials/_duotone-svg.php <!-- <svg xmlns="http://www.w3.org/2000/svg" class="svg-filters"> <filter id="duotone"> <feColorMatrix type="matrix" result="grayscale" values="0.35 0 0 0 0 0 0.1 0 0 0 0 0 0.2 0 0 0.4 5 1 0 0 "/> </filter> </svg> --> <svg xmlns="http://www.w3.org/2000/svg" class="svg-filters"> <filter id="duotone"> <feColorMatrix type="matrix" result="grayscale" values="0 0 0 0 0.235 0 0 0 0 0.02 0 0 0 0 0.035 0.05 .035 1 0 0 "/> </filter> </svg> <file_sep>/themes/seemax-theme/partials/_home-featured-radiotv.php <?php $post_object = get_sub_field('radio_tv'); if( $post_object ):$post = $post_object;setup_postdata( $post );?> <?php if( have_rows('single_public_appearance') ): while ( have_rows('single_public_appearance') ) : the_row();?> <div class="single-public-appearance grid-item grid-item-halves"> <div class="color-back"></div> <?php if( get_sub_field('link') == 'Embed' ): ?> <div class="embed-video-half c-width-100"> <div class="iframe-box"> <?php the_sub_field('iframe_link');?> </div> </div> <?php endif;?> <div class="grid-info"> <?php if(get_sub_field('date')):?> <h4 class="grid-date"> <?php the_sub_field('date');?> </h4> <?php endif;?> <h3 class="grid-name"> <?php the_title();?> </h3> <?php if(get_sub_field('publisher')):?> <h4 class="grid-publication-name"> <?php the_sub_field('publisher');?> </h4> <?php endif;?> </div> <div class="single-publication-link"> <?php if( get_sub_field('link') == 'PDF' ): ?> <div class="button grid-button"> Read <i class="fal fa-file"></i> </div> <?php elseif( get_sub_field('link') == 'Audio' ): ?> <div class="button grid-button"> <!-- View <i class="fal fa-arrow-right"></i> --> Listen <i class="fal fa-microphone"></i> </div> <?php elseif( get_sub_field('link') == 'Video' ): ?> <div class="button grid-button"> <!-- View <i class="fal fa-arrow-right"></i> --> Watch <i class="fal fa-video"></i> </div> <?php elseif( get_sub_field('link') == 'Website' ): ?> <div class="button grid-button"> <!-- View <i class="fal fa-arrow-right"></i> --> View <i class="fal fa-globe"></i> </div> <?php endif; ?> </div> <?php if( get_sub_field('link') == 'PDF' ): ?> <?php $file = get_sub_field('pdf_link');?> <a class="c-block-fill" href="<?php echo $file['url']; ?>" target="_blank"></a> <?php elseif( get_sub_field('link') == 'Audio' ): ?> <a class="c-block-fill" href="<?php the_sub_field('audio_link');?>" target="_blank"></a> <?php elseif( get_sub_field('link') == 'Video' ): ?> <a class="c-block-fill" href="<?php the_sub_field('video_link');?>" target="_blank"></a> <?php elseif( get_sub_field('link') == 'Website' ): ?> <a class="c-block-fill" href="<?php the_sub_field('website_link');?>" target="_blank"></a> <?php endif; ?>gitu </div> <?php endwhile;?> <?php endif;?> <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?> <?php endif; ?> <file_sep>/themes/seemax-theme/adminscript.js (function ($, root, undefined) {$(function () { 'use strict'; var pubSection = $('*[data-name="publication_section"]:not(:first)'); pubSection.prepend('<div class="acf-toggle">Show Publications List</div>') pubSection.parent().addClass('not-this-acf'); console.log("ok"); $('*[data-name="publication_section"]').each( function() { var $this = $(this); var thisList = $this.find($('*[data-name="list"]')); thisList.hide(); $this.find($('.acf-toggle')).on( 'click', function() { if($(this).hasClass('open')) { thisList.hide(); $(this).html('Show Publications List'); $(this).removeClass('open'); $(this).parent().parent().addClass('not-this-acf'); } else { thisList.show(); $(this).html('Hide Publications List'); $(this).addClass('open'); $(this).parent().parent().removeClass('not-this-acf'); } }); }); var pubAppSection = $('*[data-name="public_appearance_section"]:not(:first)'); pubAppSection.prepend('<div class="acf-toggle">Show Appearance List</div>') pubAppSection.parent().addClass('not-this-acf'); console.log("ok"); $('*[data-name="public_appearance_section"]').each( function() { var $this = $(this); var thisList = $this.find($('*[data-name="list"]')); thisList.hide(); $this.find($('.acf-toggle')).on( 'click', function() { if($(this).hasClass('open')) { thisList.hide(); $(this).html('Show Appearance List'); $(this).removeClass('open'); $(this).parent().parent().addClass('not-this-acf'); } else { thisList.show(); $(this).html('Hide Appearance List'); $(this).addClass('open'); $(this).parent().parent().removeClass('not-this-acf'); } }); }); var recentSection = $('*[data-name="recent_section"]:not(:first)'); recentSection.prepend('<div class="acf-toggle">Show Recent List</div>') recentSection.parent().addClass('not-this-acf'); console.log("ok"); $('*[data-name="recent_section"]').each( function() { var $this = $(this); var thisList = $this.find($('*[data-name="list"]')); thisList.hide(); $this.find($('.acf-toggle')).on( 'click', function() { if($(this).hasClass('open')) { thisList.hide(); $(this).html('Show Appearance List'); $(this).removeClass('open'); $(this).parent().parent().addClass('not-this-acf'); } else { thisList.show(); $(this).html('Hide Appearance List'); $(this).addClass('open'); $(this).parent().parent().removeClass('not-this-acf'); } }); }); });})(jQuery, this); <file_sep>/themes/seemax-theme/partials/_template.php <!-- Include Using: --> <!-- <?php get_template_part( 'partials/template.php' ); ?> --> <file_sep>/themes/seemax-theme/page-appearance-posts.php <?php /* Template Name: Public Appearance Posts */ get_header(); ?> <main class="public-appearances-page"> <?php get_template_part('partials/_duotone-svg');?> <?php while (have_posts()) : the_post(); ?> <section class="hero-section"> <svg viewBox="0 0 100 100" preserveAspectRatio="none" class="hero-pic"> <image height="100%" width='100%' xlink:href="<?php echo get_template_directory_uri(); ?>/img/public-back.jpg" filter="url(#duotone)" /> </svg> <div class="content"> <h1><?php the_title(); ?></h1> <?php the_content(); ?> </div> </section> <section class="page-subnav-section"> <div class="content"> <div class="subnav-link"> <a class="c-block-fill" href="#radio_and_tv_appearances"></a> Radio and TV Appearances </div> <div class="subnav-link"> <a class="c-block-fill" href="#interviews"></a> Interviews </div> <div class="subnav-link"> <a class="c-block-fill" href="#public-talks"></a> Public Talks </div> </div> </section> <section class="public-appearance-section"> <div class="content"> <?php get_template_part('partials/_radio-tv-appearances-section');?> <?php get_template_part('partials/_interviews-section');?> <?php get_template_part('partials/_public-talks-section');?> </div> </section> <?php endwhile; ?> </main> <?php get_footer(); ?>
4288e4aa5fce4a47758f0df398059c2b3cb34c2c
[ "JavaScript", "PHP" ]
20
PHP
SeeMax/Mearsheimer
82869f56b5f345c32a6cc35944626f6eab7a6e79
c86546a4ad932c3f8f4bc80c93f5ec8d53d0376a
refs/heads/master
<repo_name>fbfaisal/framework_Test<file_sep>/Framework_Test/src/test/java/com/framework/utility/Helper.java package com.framework.utility; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.io.FileHandler; public class Helper { public static String CaptureScreenshots(WebDriver driver) { TakesScreenshot ts=(TakesScreenshot)driver; File source=ts.getScreenshotAs(OutputType.FILE); String path = System.getProperty("user.dir") + "/Screenshots/Orange_" + getcurrentdatetime() + ".png"; File destination=new File(path); try { FileHandler.copy(source, destination); } catch (IOException e) { System.out.println("Capture Failed"+e.getMessage()); } return path; } public static String getcurrentdatetime() { DateFormat customformat= new SimpleDateFormat("MM_dd_yyyy_HH_mm_ss"); Date currentdate=new Date(); return customformat.format(currentdate); } }
eb7f5b7451ed25e28dd385943bbd8ae3a27f6292
[ "Java" ]
1
Java
fbfaisal/framework_Test
5984a2b5777fab50aec89bda1b1ddef80a25b879
5c855c780b37840f0237896f43e9d02dbf251418
refs/heads/master
<repo_name>allanalves23/tcc-front<file_sep>/src/components/Users/Management/Users.jsx import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import { userType, appTheme } from '@/types'; import { Container, TableHead, TableRow, TableCell, Table, TableBody, TableFooter, TablePagination, Paper, Box, LinearProgress, Typography, } from '@material-ui/core'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import axios from 'axios'; import { OPTIONS_LIMIT, DEFAULT_LIMIT, LIMIT_LABEL, DISPLAYED_ROWS, } from '@/config/dataProperties'; import { callToast as toastEmitter } from '@/redux/toast/toastActions'; import { info } from '@/config/toasts'; import { scrollToTop } from '@/shared/index'; import LoadingList from '@/components/LoadingList.jsx'; import CustomIconButton from '@/components/Buttons/IconButton.jsx'; import NotFound from '@/components/NotFound/DataNotFound.jsx'; import ErrorFromData from '@/components/Errors/ErrorFromData.jsx'; import CustomButton from '@/components/Buttons/Button.jsx'; import CustomChip from '@/components/Chip.jsx'; import Header from '@/components/Header.jsx'; import RemovedUsers from '@/components/Users/Management/RemovedUsers.jsx'; import DialogConfirmAdminPassword from './DialogConfirmAdminPassword'; import DialogConfirmRemoveUser from './DialogConfirmRemoveUser'; import DialogConfirmRestoreUser from './DialogConfirmRestoreUser'; import { HudLink, HudSearchBar, HudButtons, TableIcon, TableWrapper, CustomLink, } from './styles'; function Users(props) { const { user, callToast, theme, } = props; const [users, setUsers] = useState([]); const [skip, setSkip] = useState(0); const [count, setCount] = useState(0); const [take, setTake] = useState(DEFAULT_LIMIT); const [query, setQuery] = useState(''); const [error, setError] = useState(false); const [loading, setLoading] = useState(false); const [userSelected, setUserSelected] = useState({}); const [validateDialog, setValidateDialog] = useState(false); const [removedUsersDialog, setRemovedUsersDialog] = useState(false); const [confirmRestoreUserDialog, setConfirmRestoreUserDialog] = useState(false); const [confirmRemoveUserDialog, setConfirmRemoveUserDialog] = useState(false); const [reload, setReload] = useState(true); async function changeQueryValue(term) { setQuery(term); setSkip(0); setReload(true); } function changeSkip(event, page) { if (page) { if (!take) { setSkip(0); } else { const newSkip = page < (skip / take) ? (skip - take) : (skip + take); setSkip(newSkip); } } else { setSkip(0); } setReload(true); } function changeTake(event) { const { value } = event.target; setTake(value); setSkip(0); setReload(true); } function showRemovedUsersDialog() { setRemovedUsersDialog(true); } function hideRemovedUsersDialog(event) { const { needsReload } = event; if (needsReload) setReload(true); setRemovedUsersDialog(false); } function hideValidadeDialog(event) { setValidateDialog(false); const { authorized } = event; if (authorized) { showRemovedUsersDialog(); } } function showConfirmRemoveUserDialog(userNotYetSelected) { if (loading) return; // The User logged is trying remove their own account if (userNotYetSelected.id === user.userID) { callToast(info('Não é possível remover sua propria conta')); return; } setUserSelected(userNotYetSelected); setConfirmRemoveUserDialog(true); } function showConfirmRestoreUserDialog(userNotYetSelected) { if (loading) return; setUserSelected(userNotYetSelected); setConfirmRestoreUserDialog(true); } function hideConfirmUserDialog(event) { const { removed, restored } = event; if (removed || restored) { setSkip(0); setTake(DEFAULT_LIMIT); setReload(true); } setConfirmRemoveUserDialog(false); setConfirmRestoreUserDialog(false); } useEffect(() => { const source = axios.CancelToken.source(); const sourceCount = axios.CancelToken.source(); async function getCountUsers() { const url = `/usuarios/quantidade?termo=${query}`; await axios(url, { cancelToken: sourceCount.token }) .then((res) => { setCount(res.data); }); } async function searchUsers() { const url = `/usuarios?skip=${skip}&termo=${query}&take=${take}`; setLoading(true); await axios(url, { cancelToken: source.token }).then((res) => { setUsers(res.data); }).catch(() => { setError(true); }); setLoading(false); } if (reload) { scrollToTop(); setError(false); setReload(false); searchUsers(); getCountUsers(); } }, [reload, users, count, skip, error, take, query]); return ( <Container className="page"> <Header title="Usuários" description="Usuários do painel" icon="people" /> <DialogConfirmAdminPassword open={validateDialog} closeDialog={hideValidadeDialog} /> <DialogConfirmRemoveUser open={confirmRemoveUserDialog} closeDialog={hideConfirmUserDialog} user={userSelected} /> <DialogConfirmRestoreUser open={confirmRestoreUserDialog} closeDialog={hideConfirmUserDialog} user={userSelected} /> <RemovedUsers open={removedUsersDialog} closeDialog={hideRemovedUsersDialog} /> <Box mb={3}> <Box display="flex" justifyContent="space-between" alignItems="center" flexWrap="wrap" width="100%"> <HudButtons> <HudLink to="/user"> <CustomButton color="primary" icon="add_circle_outline" fullWidth /> </HudLink> </HudButtons> <HudSearchBar id="search_field" fullWidth placeholder="Pesquisar" value={query} onChange={(q) => changeQueryValue(q)} onCancelSearch={() => changeQueryValue('')} /> </Box> </Box> {loading && users.length === 0 && <LoadingList /> } {!loading && !error && users.length === 0 && ( <NotFound msg="Ops, Nenhum usuário encontrado" /> ) } { error && ( <ErrorFromData msg="Ops, ocorreu um erro ao obter os usuários" reload={() => setReload(true)} /> ) } <Paper> { users.length > 0 && loading && <LinearProgress />} { users.length > 0 && !error && ( <TableWrapper> <Table> <TableHead> <TableRow> <TableCell> <Box display="flex" alignItems="center"> <TableIcon fontSize="small" color="action"> alternate_email </TableIcon> <Typography component="span" variant="body1"> E-mail </Typography> </Box> </TableCell> <TableCell> <Box display="flex" alignItems="center"> <TableIcon fontSize="small" color="action"> bookmarks </TableIcon> <Typography component="span" variant="body1"> Perfil </Typography> </Box> </TableCell> <TableCell> <Box display="flex" alignItems="center"> <TableIcon fontSize="small" color="action"> status </TableIcon> <Typography component="span" variant="body1"> Status </Typography> </Box> </TableCell> <TableCell> <Box display="flex" alignItems="center"> <TableIcon fontSize="small" color="action"> build </TableIcon> <Typography component="span" variant="body1"> Ações </Typography> </Box> </TableCell> </TableRow> </TableHead> <TableBody> {users.map((elem) => ( <TableRow key={elem.id} hover> <TableCell scope="email"> {elem.email} </TableCell> <TableCell scope="perfilDeAcesso"> {elem.perfilDeAcesso === 'Admin' ? 'ADMINISTRADOR' : 'COMUM'} </TableCell> <TableCell scope="ativo"> <CustomChip size="small" color={elem.ativo ? 'primary' : 'default'} sizeIcon="small" icon={elem.ativo ? 'done' : 'delete'} text={elem.ativo ? 'Ativo' : 'Inativo'} /> </TableCell> <TableCell scope="id"> <CustomLink to={`/user/${elem.id}`}> <CustomIconButton icon="edit" color={theme === 'dark' ? 'inherit' : 'primary'} tooltip={<Typography component="span" variant="body2">Editar</Typography>} /> </CustomLink> {elem.ativo && ( <CustomIconButton icon="delete_forever" tooltip={<Typography component="span" variant="body2">Remover</Typography>} onClick={() => showConfirmRemoveUserDialog(elem)} /> )} {!elem.ativo && ( <CustomIconButton icon="restore_from_trash" tooltip={<Typography component="span" variant="body2">Reativar</Typography>} onClick={() => showConfirmRestoreUserDialog(elem)} /> )} </TableCell> </TableRow> ))} </TableBody> <TableFooter> <TableRow> <TablePagination rowsPerPageOptions={OPTIONS_LIMIT} colSpan={4} count={count} rowsPerPage={take} labelRowsPerPage={LIMIT_LABEL} labelDisplayedRows={DISPLAYED_ROWS} page={skip / take} onChangePage={changeSkip} onChangeRowsPerPage={changeTake} /> </TableRow> </TableFooter> </Table> </TableWrapper> ) } </Paper> </Container> ); } Users.propTypes = { user: userType.isRequired, callToast: PropTypes.func.isRequired, theme: appTheme.isRequired, }; const mapStateToProps = (state) => ({ user: state.user, toast: state.config, theme: state.theme }); const mapDispatchToProps = (dispatch) => bindActionCreators({ callToast: toastEmitter }, dispatch); export default connect(mapStateToProps, mapDispatchToProps)(Users); <file_sep>/src/types/index.js import { shape, string, bool, oneOf, oneOfType, number, object, } from 'prop-types'; export const userType = shape({ id: oneOfType([ string, number, ]), nome: string, email: string, genero: string, url: string, dataCadastro: oneOfType([ Date, string, ]), }); export const themeType = shape({ id: number, nome: string, descricao: string, }); export const categoryType = shape({ id: number, nome: string, descricao: string, tema: themeType, }); export const articleType = shape({ id: number, }); export const appTheme = oneOf([ 'light', 'dark', ]); export const reactRouterParams = shape({ path: string, url: string, isExact: bool, params: object, // Property types are changed according to the context }); export const toastConfig = shape({ type: string, msg: string, display: bool, }); export const asyncSelectValueType = shape({ label: string, value: oneOfType([ string, number, ]), }); <file_sep>/src/components/Users/MyAccount/GeneralInformation.jsx import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import { userType } from '@/types'; import { MenuItem, Grid, Icon, Box, InputAdornment, } from '@material-ui/core'; import CustomButton from '@/components/Buttons/Button.jsx'; import axios from 'axios'; import { defineErrorMsg } from '@/config/backend'; import { connect } from 'react-redux'; import { setUser as storeUser } from '@/redux/user/userActions'; import { bindActionCreators } from 'redux'; import { callToast as toastEmitter } from '@/redux/toast/toastActions'; import { success, error } from '@/config/toasts'; import { CustomTextField, FullTextField, } from './styles'; function GeneralInformation(props) { const { user, callToast, } = props; const [userState, setUserState] = useState({}); const [saving, setSaving] = useState(false); function handleChange(evt, attr) { const { value } = evt.target; setUserState({ ...userState, [attr]: value }); } async function save() { setSaving(true); try { const url = `/autores/${userState.id}`; await axios.put(url, userState).then(() => { callToast(success('Informações salvas com sucesso')); }); } catch (err) { const msg = defineErrorMsg(err); callToast(error(msg)); } setSaving(false); } useEffect(() => { if (!userState.id) { const newUser = user; setUserState(newUser); } }, [user, userState]); return ( <Box width="100%"> <Box display="flex" justifyContent="center" alignItems="center" flexWrap="wrap" width="100%" > <Grid item xs={12}> <FullTextField> <CustomTextField label="E-mail" value={userState.email || ''} onChange={(evt) => handleChange(evt, 'email')} fullWidth InputProps={userState.confirmEmail ? { startAdornment: ( <InputAdornment position="start"> <Icon fontSize="small" color="primary"> warning </Icon> </InputAdornment> ), } : {}} /> </FullTextField> <CustomTextField label="Nome" inputProps={{ maxLength: 50 }} value={userState.nome || ''} onChange={(evt) => handleChange(evt, 'nome')} /> <CustomTextField label="Genero" value={userState.genero || ''} select onChange={(evt) => handleChange(evt, 'genero')} > <MenuItem key="Masculino" value="Masculino"> Masculino </MenuItem> <MenuItem key="Feminino" value="Feminino"> Feminino </MenuItem> <MenuItem key="Outros" value="Outros"> Outros </MenuItem> <MenuItem key="PrefereNaoInformar" value="PrefereNaoInformar"> Prefere não informar </MenuItem> </CustomTextField> </Grid> </Box> <Box width="100%" display="flex" alignItems="center" justifyContent="flex-end"> <CustomButton color="primary" icon="done" iconSize="small" text={saving ? 'Salvando...' : 'Salvar'} onClick={save} loading={saving} /> </Box> </Box> ); } GeneralInformation.propTypes = { user: userType.isRequired, callToast: PropTypes.func.isRequired, }; const mapStateToProps = (state) => ({ toast: state.config, }); const mapDispatchToProps = (dispatch) => bindActionCreators({ setUser: storeUser, callToast: toastEmitter, }, dispatch); export default connect(mapStateToProps, mapDispatchToProps)(GeneralInformation); <file_sep>/src/components/Users/Management/UserForm.jsx import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import { reactRouterParams } from '@/types'; import { Redirect } from 'react-router-dom'; import { Container, MenuItem, Divider, Icon, Box, Breadcrumbs, Typography, CircularProgress, LinearProgress, } from '@material-ui/core'; import axios from 'axios'; import { defineErrorMsg } from '@/config/backend'; import { CODER_MIND_URL } from '@/config/dataProperties'; import { formatCustomURL, displayFullDate, } from '@/config/masks'; import { scrollToTop } from '@/shared/index'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { callToast as toastEmitter } from '@/redux/toast/toastActions'; import { success, error } from '@/config/toasts'; import Header from '@/components/Header.jsx'; import PasswordField from '@/components/PasswordField.jsx'; import UserFormSection from './UserFormSection'; import UserFormHud from './UserFormHud'; import DialogConfirmRemoveUser from './DialogConfirmRemoveUser'; import DialogSetPassword from './DialogSetPassword'; import { CustomLink, CustomTextField, CustomGrid, Form, CustomTooltip, } from './styles'; function UserForm(props) { const { callToast, match, } = props; const [userState, setUserState] = useState({}); const [reload, setReload] = useState(true); const [loading, setLoading] = useState(false); const [saving, setSaving] = useState(false); const [confirmRemoveUserDialog, setConfirmRemoveUserDialog] = useState(false); const [passwordDialog, setPasswordDialog] = useState(false); const [redirect, setRedirect] = useState(false); function hideConfirmRemoveUserDialog(event) { const { removed } = event; setConfirmRemoveUserDialog(false); if (removed) { setTimeout(() => setRedirect(true), 500); } } function hideSetPasswordDialog() { setPasswordDialog(false); } function handleChange(evt, attr) { let { value } = evt.target; // eslint-disable-next-line default-case switch (attr) { case 'customUrl': { value = formatCustomURL(value); break; } } setUserState({ ...userState, [attr]: value }); } function formatData() { const data = { ...userState }; data.perfilDeAcesso = data.perfilDeAcesso || 'Comum'; return data; } async function save() { if (saving) return; const method = userState.id ? 'put' : 'post'; const url = method === 'post' ? '/usuarios' : `/usuarios/${userState.id}`; const data = formatData(); setSaving(true); await axios[method](url, data).then(() => { callToast(success('Informações salvas com sucesso')); if (method === 'post') { setTimeout(() => { setRedirect(true); }, 1000); } }).catch(async (err) => { const msg = defineErrorMsg(err); callToast(error(msg)); }); setSaving(false); } useEffect(() => { const { id } = match && match.params; async function getUser() { const url = `/usuarios/${id}`; setLoading(true); await axios(url).then((res) => { setUserState({ ...res.data, }); }).catch((err) => { const msg = defineErrorMsg(err); callToast(error(msg)); }); setLoading(false); } if (reload) { scrollToTop(); } if (id && reload) { getUser(); } setReload(false); }, [userState, match, reload, callToast]); return ( <Container className="page"> <Header title="Usuário" description="Consulte, altere, crie e remova usuários do sistema" icon="person_add" /> { redirect && <Redirect to="/users" />} <DialogConfirmRemoveUser open={confirmRemoveUserDialog} closeDialog={hideConfirmRemoveUserDialog} user={userState} /> <DialogSetPassword open={passwordDialog} closeDialog={hideSetPasswordDialog} user={userState} /> <Form> { saving && <LinearProgress color="primary" /> } <Box display="flex" alignItems="center" p={2} > <Breadcrumbs separator={<Icon fontSize="small">navigate_next_icon</Icon>}> <CustomLink to="/management"> <Typography component="span" variant="body2">Configurações</Typography> </CustomLink> <CustomLink to="/users"> <Typography component="span" variant="body2">Usuários</Typography> </CustomLink> <Typography component="span" variant="body2"> {userState.id ? 'Editar usuário' : 'Cadastrar usuário'} </Typography> </Breadcrumbs> </Box> { loading && ( <Box display="flex" justifyContent="center" alignItems="center" width="100%" height="300px"> <CircularProgress color="primary" size={80} /> </Box> ) } { !loading && ( <Container> <UserFormHud save={save} isSaving={saving} /> <CustomGrid item xs={12}> <UserFormSection icon="person_outlined" title="Informações principais" description="Informações obrigatórias para manter o cadastro do usuário" /> <CustomTextField label="E-mail" value={userState.email || ''} helperText="Esta informação será usada para a autenticação no sistema" onChange={(evt) => handleChange(evt, 'email')} /> <CustomTextField label="Perfil de Acesso" value={userState.perfilDeAcesso || 'Comum'} helperText="Perfil de Acesso do usuário ao sistema" select onChange={(evt) => handleChange(evt, 'perfilDeAcesso')} > <MenuItem key="Admin" value="Admin"> Administrador </MenuItem> <MenuItem key="Comum" value="Comum"> Comum </MenuItem> </CustomTextField> </CustomGrid> <Divider /> { !userState.id && ( <CustomGrid item xs={12}> <UserFormSection icon="lock" title="Informações sigilosas" description="Senhas e outras informações de identificação" /> <PasswordField label="Senha" inputId="new-password" inputAutoComplete="new-password" value={userState.senha} fullWidth onChange={(evt) => handleChange(evt, 'senha')} /> </CustomGrid> )} { userState.id && ( <CustomGrid item xs={12}> <UserFormSection icon="security" title="Informações de gerenciamento" description="Informações de identificação e gerenciamento" /> <CustomTextField label="Identificador (ID)" value={userState.id} disabled /> <CustomTextField label="Usuário criado em" value={userState.dataDeCadastro ? displayFullDate(userState.dataDeCadastro) : 'N/D'} disabled /> <CustomTextField label="Ultima atualização de cadastro" value={userState.dataDeAtualizacao ? displayFullDate(userState.dataDeAtualizacao) : 'N/D'} disabled /> <CustomTextField label="Status" value={userState.ativo ? 'Ativo' : 'Inativo'} disabled /> { false && ( <CustomTooltip placement="top-start" arrow title={( <Typography component="span" variant="caption"> A url customizada ficará: {' '} {CODER_MIND_URL} /autores/ <strong>{userState.customUrl ? formatCustomURL(userState.customUrl) : ''}</strong> </Typography> )} > <CustomTextField label="URL customizada" value={userState.customUrl} onChange={(evt) => handleChange(evt, 'customUrl')} /> </CustomTooltip> )} </CustomGrid> )} </Container> )} </Form> </Container> ); } UserForm.propTypes = { callToast: PropTypes.func.isRequired, match: reactRouterParams, }; UserForm.defaultProps = { match: null, }; const mapStateToProps = (state) => ({ toast: state.config }); const mapDispatchToProps = (dispatch) => bindActionCreators({ callToast: toastEmitter }, dispatch); export default connect(mapStateToProps, mapDispatchToProps)(UserForm); <file_sep>/src/components/Menu/Drawer.jsx import React from 'react'; import PropTypes from 'prop-types'; import { userType } from '@/types'; import { connect } from 'react-redux'; import { List, Divider, Box, Typography, Icon, } from '@material-ui/core'; import { DrawerList, CustomLink, CustomListItem, CustomDrawer, } from './styles'; function DrawerMenu(props) { const { user, logout, } = props; return ( <CustomDrawer open variant="permanent" > <CustomLink to="/"> <Box id="coder-mind-logo" display="flex" alignItems="flex-start" justifyContent="center" mt={2} mb={1} /> </CustomLink> <Divider /> <DrawerList> <List> <CustomLink to="/articles" > <CustomListItem button > <Box display="flex" alignItems="center"> <Icon color="action"> article </Icon> <Typography component="span" variant="body2"> Artigos </Typography> </Box> </CustomListItem> </CustomLink> <CustomLink to="/themes" > <CustomListItem button > <Box display="flex" alignItems="center"> <Icon color="action"> bookmark </Icon> <Typography component="span" variant="body2"> Temas </Typography> </Box> </CustomListItem> </CustomLink> <CustomLink to="/categories" > <CustomListItem button > <Box display="flex" alignItems="center"> <Icon color="action"> category </Icon> <Typography component="span" variant="body2"> Categorias </Typography> </Box> </CustomListItem> </CustomLink> <CustomLink to="/my-account" > <CustomListItem button > <Box display="flex" alignItems="center"> <Icon color="action"> person_outline </Icon> <Typography component="span" variant="body2"> Minha conta </Typography> </Box> </CustomListItem> </CustomLink> { user.profileAccess === 'ADMIN' && ( <CustomLink to="/management" > <CustomListItem button > <Box display="flex" alignItems="center"> <Icon color="action"> settings </Icon> <Typography component="span" variant="body2"> Configurações </Typography> </Box> </CustomListItem> </CustomLink> )} </List> <List> <CustomListItem onClick={logout} button id="logout-button" > <Box display="flex" alignItems="center"> <Icon color="action"> exit_to_app </Icon> <Typography component="span" variant="body2"> Sair </Typography> </Box> </CustomListItem> </List> </DrawerList> </CustomDrawer> ); } DrawerMenu.propTypes = { user: userType.isRequired, logout: PropTypes.func.isRequired, }; const mapStateToProps = (state) => ({ user: state.user, theme: state.theme }); export default connect(mapStateToProps)(DrawerMenu); <file_sep>/src/components/Articles/Articles.jsx import React, { useState, useEffect } from 'react'; import { useHistory } from 'react-router-dom'; import { Container, Icon } from '@material-ui/core'; import { OPTIONS_LIMIT, DEFAULT_LIMIT } from '@/config/dataProperties'; import { scrollToTop } from '@/shared/index'; import axios from 'axios'; import { connect } from 'react-redux'; import { userType } from '@/types'; import MaterialTable from 'material-table'; import Header from '@/components/Header.jsx'; import NotFound from '@/components/NotFound/DataNotFound.jsx'; import Chip from '@/components/Chip.jsx'; import ArticleHeaderTableCell from './ArticleHeaderTableCell'; import CreateArticleDialog from './CreateArticleDialog'; import { TableWrapper } from './styles'; function Articles(props) { const { user, } = props; const [loading, setLoading] = useState(false); const [error, setError] = useState(false); const [viewAll, setViewAll] = useState(false); const [articles, setArticles] = useState([]); const [query, setQuery] = useState(''); const [count, setCount] = useState(0); const [take, setTake] = useState(DEFAULT_LIMIT); const [skip, setSkip] = useState(0); const [reload, setReload] = useState(true); const [createArticleDialog, setCreateArticleDialog] = useState(false); const history = useHistory(); function getArticleState(article) { let state; let icon; let color; switch (article.estado) { case 'PUBLICADO': { state = 'Publicado'; icon = 'public'; color = 'primary'; break; } case 'INATIVO': { state = 'Inativo'; icon = 'public_off'; color = 'default'; break; } case 'IMPULSIONADO': { state = 'Impulsionado'; icon = 'star_rate'; color = 'primary'; break; } case 'REMOVIDO': { state = 'Removido'; icon = 'delete'; color = 'secondary'; break; } default: { state = 'Rascunho'; icon = 'drafts'; color = 'default'; } } return { state, icon, color }; } function getArticleListColumns() { const authorColumns = [ { title: <ArticleHeaderTableCell icon="article" label="Artigo" />, field: 'titulo', }, { title: <ArticleHeaderTableCell icon="label" label="Status" />, field: 'state', render: (rowData) => { const { state, color, icon } = getArticleState(rowData); return (<Chip className="cm-chip" text={state} icon={icon} color={color} size="small" sizeIcon="small" />); }, }, { title: <ArticleHeaderTableCell icon="bookmark" label="Tema" />, field: 'tema.nome', }, { title: <ArticleHeaderTableCell icon="category" label="Categoria" />, field: 'categoria.nome', }, ]; const adminColumns = [ { title: <ArticleHeaderTableCell icon="article" label="Artigo" />, field: 'titulo', }, { title: <ArticleHeaderTableCell icon="person" label="Autor" />, field: 'autor.nome', }, { title: <ArticleHeaderTableCell icon="label" label="Status" />, field: 'state', render: (rowData) => { const { state, color, icon } = getArticleState(rowData); return (<Chip className="cm-chip" text={state} icon={icon} color={color} size="small" sizeIcon="small" />); }, }, { title: <ArticleHeaderTableCell icon="bookmark" label="Tema" />, field: 'tema.nome', }, { title: <ArticleHeaderTableCell icon="category" label="Categoria" />, field: 'categoria.nome', }, ]; return user.profileAccess === 'ADMIN' ? adminColumns : authorColumns; } function openCreateArticleDialog() { setCreateArticleDialog(true); } function closeArticleDialog(stack) { setCreateArticleDialog(false); if (stack && stack.reason === 'articleCreated') { history.push(`/articles/${stack.url}`); } } function changeSkip(value) { if (value) { if (!take) { setSkip(0); } else { const newSkip = value < (skip / take) ? (skip - take) : (skip + take); setSkip(newSkip); } } else { setSkip(0); } setReload(true); } function changeTake(value) { setTake(value); setReload(true); } function getBySearch(q) { setQuery(q); setSkip(0); setReload(true); } function openArticle(article) { history.push(`/articles/${article.url}`); } function toggleViewType() { setViewAll(!viewAll); setReload(true); } function getAdminActions() { const actions = [ { tooltip: 'Novo artigo', icon: 'add_circle', onClick: openCreateArticleDialog, position: 'toolbar', }, ]; if (user.profileAccess === 'ADMIN') { actions.push({ tooltip: viewAll ? 'Visualizar meus artigos' : 'Visualizar todos os artigos', icon: viewAll ? 'account_circle' : 'groups', onClick: toggleViewType, position: 'toolbar', }); } return actions; } useEffect(() => { const source = axios.CancelToken.source(); const sourceCount = axios.CancelToken.source(); async function getArticlesCount() { const url = `/artigos/quantidade?termo=${query}&all=${viewAll}`; await axios(url, { cancelToken: sourceCount.token }) .then((res) => { setCount(res.data); }); } async function getArticles() { try { const url = `/artigos?termo=${query}&skip=${skip}&take=${take}&all=${viewAll}`; setLoading(true); await axios(url, { cancelToken: source.token }) .then((res) => { setReload(false); setArticles(res.data); }); setLoading(false); } catch (err) { if (!axios.isCancel(err)) { setLoading(false); setReload(false); setError(true); } } } if (reload) { scrollToTop(); getArticles(); getArticlesCount(); } return () => source.cancel(); }, [articles, loading, skip, take, count, reload, error, query, viewAll]); return ( <Container id="component"> <Header title="Artigos" description="Consulte, altere e crie novos artigos" icon="article" /> <CreateArticleDialog open={createArticleDialog} onClose={closeArticleDialog} /> <TableWrapper> <MaterialTable columns={getArticleListColumns()} data={articles} isLoading={loading} totalCount={count} onChangeRowsPerPage={changeTake} onChangePage={changeSkip} page={skip / take} onSearchChange={getBySearch} showFirstLastPageButtons={false} icons={{ ResetSearch: () => (query ? <Icon color="action">clear</Icon> : ''), PreviousPage: () => <Icon color="action">chevron_left</Icon>, NextPage: () => <Icon color="action">chevron_right</Icon>, }} options={{ showTitle: false, showFirstLastPageButtons: false, showTextRowsSelected: false, pageSize: DEFAULT_LIMIT, pageSizeOptions: OPTIONS_LIMIT, toolbarButtonAlignment: 'left', headerStyle: { zIndex: 1, }, debounceInterval: 500, maxBodyHeight: 750, paginationType: 'normal', }} localization={{ body: { emptyDataSourceMessage: (<NotFound msg="Ops! Nenhum artigo encontrado" disableboxshadow />), }, toolbar: { searchPlaceholder: 'Titulo ou descrição', }, pagination: { previousTooltip: 'Página anterior', nextTooltip: 'Próxima página', labelRowsSelect: 'Linhas', labelDisplayedRows: '{from}-{to} de {count}', }, }} onRowClick={((evt, selectedRow) => openArticle(selectedRow))} actions={getAdminActions()} /> </TableWrapper> </Container> ); } Articles.propTypes = { user: userType.isRequired, }; const mapStateToProps = (state) => ({ user: state.user }); export default connect(mapStateToProps)(Articles); <file_sep>/src/components/Users/Management/UserFormHud.jsx import React from 'react'; import PropTypes from 'prop-types'; import { Box, useMediaQuery, } from '@material-ui/core'; import { devices } from '@/config/devices'; import CustomButton from '@/components/Buttons/Button.jsx'; import { FormHudButtons } from './styles'; function UserFormHud(props) { const { save, isSaving, } = props; const matches = useMediaQuery(devices.tablet); return ( <FormHudButtons> { !matches && ( <Box> <CustomButton color="primary" size="small" iconSize="small" icon="save" onClick={save} disabled={isSaving} /> </Box> )} </FormHudButtons> ); } UserFormHud.propTypes = { save: PropTypes.func.isRequired, isSaving: PropTypes.bool, }; UserFormHud.defaultProps = { isSaving: false, }; export default UserFormHud; <file_sep>/src/components/Authentications/Auth.jsx import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import { Grid, Box, LinearProgress, useMediaQuery, } from '@material-ui/core'; import { Redirect, useHistory } from 'react-router-dom'; import { connect } from 'react-redux'; import axios from 'axios'; import { devices } from '@/config/devices'; import CustomButtonBase from '@/components/Authentications/AuthButton.jsx'; import PasswordField from '@/components/PasswordField.jsx'; import { defineErrorMsg } from '@/config/backend'; import Logo from '@/assets/logo-unicarioca.png'; import { bindActionCreators } from 'redux'; import { setUser as defineUser } from '@/redux/user/userActions'; import { setMenu as defineMenu } from '@/redux/menu/menuActions'; import { GridPresentation, AuthSection, LogoArea, FormArea, AuthTextField, SpecialButton, SubmitArea, CustomAlert, CustomFormControl, AuthLabel, } from './styles'; function Auth(props) { const { appError, setUser, setMenu, } = props; const [userID, setUserID] = useState(''); const [password, setPassword] = useState(''); const [loading, setLoading] = useState(false); const [redirect, setRedirect] = useState(false); const [error, setError] = useState(null); const matches = useMediaQuery(devices.mobileLarge); const history = useHistory(); function handleChange(setAttr) { return (event) => { const { value } = event.target; setAttr(value); }; } function authFormFocus() { const input = document.querySelector('#coder-mind-username'); if (input) input.focus(); if (!matches) { window.scrollTo(0, window.screen.height); } } async function signIn(e) { e.preventDefault(); setLoading(true); const user = { userID, password, }; const url = '/auth'; await axios.post(url, user) .then((res) => { localStorage.setItem('user', JSON.stringify({ accessToken: res.data.accessToken, user: res.data.user })); setUser(res.data); setMenu(true); history.push('/'); }).catch((err) => { const msg = defineErrorMsg(err); setError(msg); setLoading(false); }); } useEffect(() => { async function verifyUser() { const user = localStorage.getItem('user'); if (user && !appError) setRedirect(true); } verifyUser(); }, [redirect, appError]); return ( <Box display="flex" alignItems="center" flexWrap="wrap" height="100%"> {redirect && <Redirect to="/" /> } <GridPresentation item xs={12} md={4}> <Box display="flex" flexDirection="column" height="60vh" justifyContent="flex-end" alignItems="center"> <Box display="flex" alignItems="center" flexDirection="column" mt={2} mb={2}> <SpecialButton onClick={authFormFocus} color="inherit" variant="outlined" fullWidth>Já tenho uma conta</SpecialButton> </Box> </Box> </GridPresentation> <Grid item xs={12} md={8}> <AuthSection> { loading && <LinearProgress color="primary" />} <LogoArea error={error}> <img src={Logo} alt="Painel Coder Mind" className="logo-img" /> </LogoArea> <FormArea> <form onSubmit={signIn} className="custom-form"> <AuthLabel>E-mail</AuthLabel> <AuthTextField variant="outlined" size="small" onChange={handleChange(setUserID)} inputProps={{ autoComplete: 'email', id: 'coder-mind-username' }} /> <AuthLabel>Senha</AuthLabel> <CustomFormControl> <PasswordField inputId="cm-password" variant="outlined" size="small" inputAutoComplete="password" value={password} onChange={handleChange(setPassword)} /> </CustomFormControl> { Boolean(error) && ( <CustomAlert severity="warning"> {error} </CustomAlert> ) } <SubmitArea item xs={12}> <CustomButtonBase type="submit" fullWidth disabledIcon severity="primary" loading={loading} text={loading ? 'Entrando...' : 'Entrar'} /> </SubmitArea> </form> </FormArea> </AuthSection> </Grid> </Box> ); } Auth.propTypes = { appError: PropTypes.bool, setUser: PropTypes.func.isRequired, setMenu: PropTypes.func.isRequired, }; Auth.defaultProps = { appError: false, }; const mapStateToProps = (state) => ({ appError: state.error, theme: state.theme }); const mapDispatchToProps = (dispatch) => bindActionCreators({ setUser: defineUser, setMenu: defineMenu, }, dispatch); export default connect(mapStateToProps, mapDispatchToProps)(Auth); <file_sep>/README.md ![TCC-Front](https://i.imgur.com/6t9hIld.png) [![code-style-airbnb](https://badgen.net/badge/codestyle/airbnb/ff5a5f.svg?icon=airbnb&color=green)](https://github.com/airbnb/javascript) [![All Contributors](https://img.shields.io/badge/all_contributors-2-blue.svg?style=flat-square)](#contributors) ![license-BS3](https://img.shields.io/badge/license-BSD%203-green) [![Build status](https://dev.azure.com/allanalves23/allanalves23/_apis/build/status/TCC-FRONT)](https://dev.azure.com/allanalves23/allanalves23/_build/latest?definitionId=2) ![Release status](https://vsrm.dev.azure.com/allanalves23/_apis/public/Release/badge/0a28a34f-5627-4ece-820c-b2d86e27cb5d/2/2) ## Trabalho de conclusão de curso - Instituição Unicarioca de Ensino Superior Interfaces de usuário projetadas com o intuito de comprovar as argumentações apresentadas sobre o tema de **Design Dirigido a Domínios**. ___ ## Alunos <table> <tr> <td align="center"> <a href="http://allanalves23.com"> <img src="https://avatars0.githubusercontent.com/u/27220715?v=4" width="100px;" alt="Foto de <NAME>" /> <br /> <sub> <b><NAME></b> </sub> </a> <br /> </td> <td> <a href="mailto://<EMAIL>"><EMAIL></a> </td> </tr> <br/> <tr> <td align="center"> <a href="https://github.com/allanalves23/tcc-front"> <img src="https://i.imgur.com/432wrXE.png" width="100px;" alt="Foto de <NAME>" /> <br /> <sub> <b><NAME></b> </sub> </a> <br /> </td> <td> <a href="mailto://<EMAIL>"><EMAIL></a> </td> </tr> <br/> </table>
accfc54ae563ebf5a946d85c8029af85eef43bdc
[ "JavaScript", "Markdown" ]
9
JavaScript
allanalves23/tcc-front
e3c5ea8df1a051e2625df06034c6c916b418586b
169a398acc6d46de56542e3548af42e429ff6765
refs/heads/main
<repo_name>csys-fresher-batch-2021/finapp-jeyalakshmi<file_sep>/src/main/java/in/jeya/service/servlet/AdminLoginServlet.java package in.jeya.service.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import in.jeya.service.validation.AdminLoginValid; /** * Servlet implementation class AdminLoginServlet */ @WebServlet("/AdminLoginServlet") public class AdminLoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public AdminLoginServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("<PASSWORD>"); boolean valid = AdminLoginValid.login(username, password); if (valid) { System.out.println("Successfully Logged In"); response.sendRedirect("AdminPage.jsp"); } else { String message = "Invalid Login - Enter Correct Details"; response.sendRedirect("AdminLogin.jsp?errorMessage=" + message); } } } <file_sep>/src/main/java/in/jeya/service/user/User.java package in.jeya.service.user; import in.jeya.service.validation.PasswordValid; import in.jeya.service.validation.UsernameValid; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { if (!UsernameValid.isValidUsername(username)) { throw new IllegalArgumentException("Invalid Username"); } this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { if (!PasswordValid.isValidPassword(password)) { throw new IllegalArgumentException("Invalid Password"); } this.password = <PASSWORD>; } } <file_sep>/src/main/java/in/jeya/service/validation/StringValidator.java package in.jeya.service.validation; public class StringValidator { private StringValidator() { } public static boolean isValidString(String string) { boolean isValid = true; if (string == null || string.trim().isEmpty()) { isValid = false; } return isValid; } }
f226414b078f1717e16bcf317068146f5482973a
[ "Java" ]
3
Java
csys-fresher-batch-2021/finapp-jeyalakshmi
428110a250185c003b9e460ced303a10f508ec8a
ff35990d104c09301b95f36879e88fb30e1ebf24
refs/heads/master
<file_sep>def square_numbers(nums): for i in nums: yield i*i my_nums = square_numbers([1,2,3,4,5,6]) print(my_nums) <file_sep>/** * @param {*} str * @return {boolean} - whether str is a palindrome, ignoring all non alphanumerical values */ function isPalindrome(str) { str = str.toLowerCase() .split('') .filter(char => /[a-z0-9]/.test(char)); for (let i = 0; i < str.length; i += 1) { if (str[i] !== str[str.length - 1 - i]) { return false; } } return true; } console.assert(!isPalindrome('asdf')) console.assert(isPalindrome("Was it Eliot's toilet I saw?"))
307e0fa90d77113c8fc3461eda5bafba7e654599
[ "JavaScript", "Python" ]
2
Python
Fullchee/leetcode-practice
ef101aedfb13d3472c6ec8f7d2c58ee4b090ad7d
5b19d6446ded4807a5da1f286dd9674544b70b46
refs/heads/master
<file_sep> /* * Tabs 0.3.2 */ ;(function ($) { $.fn.inner_tabs = function(custom) { var setting = { callback: null }; setting = $.extend({}, setting, custom); this.each(function() { var $inner_tabs = $(this); var $labels = $('.tab_label', $inner_tabs).filter(function() { return ( $inner_tabs[0] === $(this).closest('.inner_tabs')[0] ); }); var $contents = $('.tab_content', $inner_tabs).filter(function() { return ( $inner_tabs[0] === $(this).closest('.inner_tabs')[0] ); }); $labels.click(function() { var $this = $(this); var $link = $('a', $this); var hash = (1 == $link.length) ? $link.attr('href') : ''; var contentId = ''; var index = 0; $labels.removeClass('selected'); $contents.hide(); $this.addClass('selected'); contentId = hash.replace(/#/, '#t-'); if ( contentId && $('' + contentId).length ) { $('' + contentId).show(); window.location.hash = hash; } else { index = $.inArray(this, $labels); $( $contents[index] ).show(); } $(window).resize(); if ( setting.callback ) { setting.callback($inner_tabs); } return false; }); $(window).on('href-update', function() { $active = $('.tab_label [href="' + window.location.hash + '"]', $inner_tabs); if ( 0 != $active.length ) { $active.trigger('click'); return; } }); if ( window.location.hash ) { $active = $('.tab_label [href="' + window.location.hash + '"]', $inner_tabs); if ( 0 != $active.length ) { $active.trigger('click'); return; } } $( $labels[0] ).trigger('click'); }); }; }(jQuery)); <file_sep>(function() { angular.module("commander", []).service("commander", [ "$rootScope", function($rootScope) { this.commands = new Array; this.add = function(command) { var args, dependencies, undo, _i, _len; undo = command.splice(-1)[0]; args = new Array; for (_i = 0, _len = command.length; _i < _len; _i++) { dependencies = command[_i]; args.push(angular.copy(dependencies)); } undo.apply(this, args); return this.commands.push((function(_this) { return function() { return undo.apply(_this, args); }; })(this)); }; this.back = function() { if (this.commands.length > 1) { this.commands[this.commands.length - 2](); return this.commands.length = this.commands.length - 1; } }; return this; } ]); }).call(this); <file_sep>$(document).ready(function(){ var reg = /[0-9]{1,3}/; $('.list-gradient').each(function(){ var t = $(this); var ol = $(this).find('li'); var ok = $(this).find('li:first-child'); var om = $(this).find('li:last-child'); var color1 = $(ok).css('backgroundColor').split(' '); var color2 = $(om).css('backgroundColor').split(' '); console.log("color1: ", color1, "\n", "color2: ", color2); var count = $(ol).length; var r1 = parseInt(color1[0].match(reg)); var g1 = parseInt(color1[1].match(reg)); var b1 = parseInt(color1[2].match(reg)); var r2 = parseInt(color2[0].match(reg)); var g2 = parseInt(color2[1].match(reg)); var b2 = parseInt(color2[2].match(reg)); console.log(r1); var koef1 = Math.abs((r2-r1)/count); var koef2 = Math.abs((g2-g1)/count); var koef3 = Math.abs((b2-b1)/count); for (var i = 1; i < count-1; i++) { if (r1>r2) {var newcolor1 = -1*koef1*i} else{var newcolor1 = koef1*i}; if (g1>g2) {var newcolor2 = -1*koef2*i} else{var newcolor2 = koef2*i}; if (b1>b2) {var newcolor3 = -1*koef3*i} else{var newcolor3 = koef3*i}; var finr = Math.round(r1+newcolor1); var fing = Math.round(g1+newcolor2); var finb = Math.round(b1+newcolor3); var elemcount = i+1; var newcolor = 'rgb('+finr+','+fing+','+finb+')'; var elem = 'li:nth-child('+elemcount+')'; t.find(elem).css({'backgroundColor':newcolor}); }; }); });<file_sep>(function() { angular.module("blowfish", []).config([ "blowfishProvider", function(blowfishProvider) { return blowfishProvider.key = "terminal_good_authorization"; } ]).provider("blowfish", function() { return { $get: function() { return new Blowfish(this.key); } }; }); }).call(this); <file_sep>(function() { angular.module("flexible1", []).directive("flexible1", function() { return { restrict: "A", scope: { flexible: "=", length: "=", pages: "=", limit: "=", itemsWidth: "=", itemsHeight: "=" }, link: function($scope, $element, $attrs) { var limitOnPage; window.container = document.querySelector(".flexible-container"); limitOnPage = new Number; window.resizer = function() { var containerHeight, containerWidth, maxItemsHeight, maxItemsWidth, minItemsHeight, minItemsWidth, numberHeight, numberWidth, sizeSetting, value, _ref; _ref = $scope.flexible; for (sizeSetting in _ref) { value = _ref[sizeSetting]; $scope.flexible[sizeSetting] = ~~value; } container.style.height = window.innerHeight - container.getBoundingClientRect().top - $scope.flexible.marginTop - 5 + "px"; containerWidth = container.getBoundingClientRect().width; containerHeight = container.getBoundingClientRect().height; minItemsWidth = Math.floor(containerWidth / $scope.flexible.minWidth); maxItemsWidth = Math.floor(containerWidth / $scope.flexible.maxWidth); numberWidth = Math.ceil((minItemsWidth + maxItemsWidth) / 2); $scope.itemsWidth = containerWidth / numberWidth - $scope.flexible.marginLeft + "px"; minItemsHeight = Math.floor(containerHeight / $scope.flexible.minHeight); maxItemsHeight = Math.floor(containerHeight / $scope.flexible.maxHeight); numberHeight = Math.ceil((minItemsHeight + maxItemsHeight) / 2); $scope.itemsHeight = containerHeight / numberHeight - $scope.flexible.marginTop + "px"; limitOnPage = numberWidth * numberHeight; $scope.limit = limitOnPage; return $scope.pages = Math.ceil($scope.length / limitOnPage); }; window.addEventListener("resize", function(event) { event.stopPropagation(); return $scope.$apply(resizer); }); $scope.$watch("length", function(length) { if (length) { return $scope.pages = Math.ceil(length / limitOnPage); } }); return $scope.$watch("flexible", function(flexible, oldvalue) { if (flexible) { return resizer(); } }); } }; }); }).call(this); <file_sep>(function() { angular.module("scrollTo", []).directive("scrollTo", function() { return { restrict: "A", scope: { scrollTo: "@", params: "=", collection: "=", reset: "=" }, link: function($scope, $element, $attrs) { var $parent, $scrollBar, animation, count, countBorder, elementHeight, params, parentHeight, proportion, totallyY; $element.css({ position: "absolute" }); params = JSON.parse($scope.scrollTo); count = 0; countBorder = params.maxlists * params.inlist; $scope.params = { start: 0, end: countBorder * params.list, count: params.maxlists * params.inlist * params.list }; animation = { y: 0 }; totallyY = 0; $parent = $element.parent(); $parent.css({ position: "relative", overflow: "hidden" }); elementHeight = $element[0].clientHeight; parentHeight = $parent[0].clientHeight; proportion = 0; $scrollBar = angular.element("<div class='scroll-bar'></div>"); setTimeout(function() { var scrollHeight; elementHeight = $element[0].clientHeight; proportion = parentHeight / elementHeight; scrollHeight = parentHeight * proportion; if (scrollHeight < elementHeight) { $scrollBar.css({ height: scrollHeight + "px", opacity: 1 }); } else { $scrollBar.css({ height: scrollHeight + "px", opacity: 0 }); } return $parent.append($scrollBar); }, 300); $parent.on("mousewheel", function($event) { if ($event.wheelDeltaY > 0) { if (totallyY - parentHeight >= 0) { count--; totallyY = count * parentHeight; } else if (totallyY > 0) { count = 0; totallyY = 0; } } else if ($event.wheelDeltaY < 0) { if (totallyY + parentHeight <= elementHeight - parentHeight) { count++; totallyY = count * parentHeight; } else if (totallyY !== elementHeight - parentHeight) { totallyY = elementHeight - parentHeight; count++; } } if (count === countBorder - 1) { $scope.params.start = (countBorder - ~~params.inlist) * params.list; countBorder += ~~params.inlist; $scope.$apply(function() { return $scope.params.end = countBorder * params.list; }); console.log($scope.params.start, $scope.params.end); setTimeout(function() { elementHeight = $element[0].clientHeight; proportion = parentHeight / elementHeight; return $scrollBar.css({ height: parentHeight * proportion + "px" }); }, 100); } if ((0 <= totallyY && totallyY <= elementHeight) && totallyY !== animation.y) { TweenLite.to(animation, 0.6, { y: totallyY, ease: Power2.easeInOut, onUpdate: function() { return $element.css({ top: "" + (-animation.y) + "px" }); } }); return $scrollBar.css({ top: "" + (totallyY * proportion) + "px" }); } }); $scope.$watchCollection("collection", function(collection) { if (collection) { return setTimeout(function() { var scrollHeight; elementHeight = $element[0].clientHeight; proportion = parentHeight / elementHeight; scrollHeight = parentHeight * proportion; if (scrollHeight < elementHeight) { return $scrollBar.css({ height: scrollHeight + "px", opacity: 1 }); } else { return $scrollBar.css({ height: scrollHeight + "px", opacity: 0 }); } }, 100); } }); return $scope.$watch("reset", function() { count = 0; totallyY = 0; TweenLite.to(animation, 0.6, { y: totallyY, ease: Power2.easeInOut, onUpdate: function() { return $element.css({ top: "" + (-animation.y) + "px" }); } }); return setTimeout(function() { var scrollHeight; elementHeight = $element[0].clientHeight; proportion = parentHeight / elementHeight; scrollHeight = parentHeight * proportion; if (scrollHeight < elementHeight) { return $scrollBar.css({ height: scrollHeight + "px", opacity: 1, top: "" + (totallyY * proportion) + "px" }); } else { return $scrollBar.css({ height: scrollHeight + "px", opacity: 0, top: "" + (totallyY * proportion) + "px" }); } }, 100); }); } }; }); }).call(this); <file_sep>(function() { angular.module("connect", []).service("connect", [ "$rootScope", "$http", "$q", function($rootScope, $http, $q) { /* 0 - loaded 1 - load 2 - offline 3 - error */ return function(params) { var defer; $rootScope.connect = "load"; defer = $q.defer(); $http(params).success(function(data, status, headers, config) { $rootScope.connect = "loaded"; return defer.resolve(data, status, headers, config); }).error(function(data, status, headers, config) { $rootScope.connect = "error"; return defer.reject(data, status, headers, config); }); return defer.promise; }; } ]); }).call(this); <file_sep>/** * Created by drgoon on 30.12.2014. */ $(document).ready(function () { $('.el-menu').click(function() { $('.el-menu').removeClass('active-nav'); $(this).addClass('active-nav'); }); // Favorites // $('.add-goods').on('mouseup', function() { var elem = $(this).find('+.rm-goods').show(); var elemData = $(this).find('.data-id').data('goods-id'); console.log("elemData " + elemData); var price = $(this).find('.price').text(); var name = $(this).find('.name-goods').text(); var value = parseInt(elem.text()) + 1; elem.text(value); var quantity = elem.text(); var rowCheck = $('.hiddenField').clone(); rowCheck.find('.name').html(name); rowCheck.find('.price').text(price); rowCheck.find('.quantity').text(value); rowCheck.attr('#goods-id-' + elemData); var addClass = elem.attr("name", "goods-id-" + elemData); console.log("addClass " + addClass); var goodsId = $(rowCheck.attr('id', 'goods-id-' + elemData)).attr('id'); console.log(goodsId); var checkId = $('.checklist').find("#" + goodsId); console.log(checkId); checkId.replaceWith(rowCheck); rowCheck.toggleClass('hiddenField'); $('.hiddenField').after(rowCheck); }); $('.rm-goods').on('click', function() { var elem = $(this); var price = $(this).find('.price').text(); var name = $(this).find('.name-goods').text(); var value = parseInt(elem.text()) - 1; elem.text(value); var quantity = elem.text(); console.log(name + ' ' + quantity + ' ' + price); var nameRmGoods = $(this).attr("name"); console.log("nameRmGoods " + nameRmGoods); var field = $("#" + nameRmGoods); field.find(".quantity").text(value); if (value === 0) { $(this).hide(); field.remove(); } }); // -End- Favorites // // Scrollbar // $(".scrollbar").mCustomScrollbar({ autoHideScrollbar: true, advanced: { updateOnContentResize: true }, scrollInertia: 1, contentTouchScroll: 10 }); // -End- Scrollbar // ///* Open section Add Products */ //$('#addProduct').on('click', function() { // location.href = "menu-add-product.html"; //}); ///* -End- Open section Add Products */ /* Location */ $(".toggle .state").on("mouseup", function() { $(".state").removeClass("activeToggle"); $(this).addClass("activeToggle"); }); /* -End- Location */ /* Open Order */ $(".checklist").on("click", function() { location.href = 'menu-order.html'; }); /* -End- Open Order */ /* Open btnGrid */ $("#discount").on("click", function() { var eventOrder1 = $("#event-Order-1"); var eventOrder2 = $("#event-Order-2"); eventOrder1.toggleClass("btn-grid-hidden"); eventOrder2.toggleClass("btn-grid-hidden"); }); /* -End- Open btnGrid */ /* Active insert one field in Order goods */ $(".field").on("click", function() { var field = $(".field"); field.removeClass("active-field"); field.find(".order-goods-minus").css("visibility", "hidden"); field.find(".order-goods-plus").css("visibility", "hidden"); $(this).find(".order-goods-minus", ".order-goods-plus").css("visibility", "visible"); $(this).find(".order-goods-plus").css("visibility", "visible"); $(this).addClass("active-field"); }); /* -End- Active insert in Order goods */ /* Active All fields in Order */ $(".btnOk").on("click", function() { var field = $(".field"); $(".order").find(".field").addClass("active-field"); field.find(".order-goods-minus").css("visibility", "hidden"); field.find(".order-goods-plus").css("visibility", "hidden"); }); /* -End- Active All fields in Order */ /* Reset insert in Order goods */ $('#title-order').on('click', function() { var field = $(".field"); field.removeClass("active-field"); field.find(".order-goods-minus").css("visibility", "hidden"); field.find(".order-goods-plus").css("visibility", "hidden"); }); /* -End- Reset insert in Order goods */ /* Remove insert goods in the Order */ $(".order-goods-dell").on("click", function() { console.log("click Ok"); $(this).parents(".field").remove(); console.log("remove Ok"); }); /* -End- Remove insert goods in the Order */ /* Go to the Search */ $(".boxSearch").on("mousedown", function() { var crumbs = $(".crumbs"); var wrapSearchRoot = $(".wrapSearchRoot"); crumbs.addClass("hidden"); wrapSearchRoot.removeClass("hidden"); wrapSearchRoot.addClass("show"); console.log("Go to the Search. Ok"); }); $("#goToRoot").on("mousedown", function() { var crumbs = $(".crumbs"); var wrapSearchRoot = $(".wrapSearchRoot"); wrapSearchRoot.removeClass("show"); wrapSearchRoot.addClass("hidden"); crumbs.removeClass("hidden"); crumbs.addClass("show"); console.log("Go to the Search. Ok"); }); /* -End- Go to the Crumbs */ // Order. Toggle views page $("#v1").on("mouseup", function() { $(".orders").removeClass("V2"); $(".orders").addClass("V1"); $(".footer-bar").find(".v1").removeClass("v1"); $(this).addClass("v1") }); $("#v2").on("mouseup", function() { $(".orders").removeClass("V1"); $(".orders").addClass("V2"); $(".footer-bar").find(".v1").removeClass("v1"); $(this).addClass("v1") }); // -End- Order. Toggle views page // Modal Cash $("#modal-cash").on('mouseup', function(){ $(".modal").removeClass("hidden"); }); $("#cash-ok").on("mouseup", function() { $(".modal").addClass("hidden"); }); }); // body - nav = contentAll // contentAll - 2 * padding //100% = contentPading // (contentPading - 2 * paddingEl) / 3 = elemnt<file_sep>(function() { angular.module("pos-terminal-ligistics.client", ["ui.router", "connect"]).config([ "$stateProvider", function($stateProvider) { return $stateProvider.state("menu.type.client", { url: "/{client:sender||addressee}", abstract: true, template: "<div class='lvl-2 ui-view:parent@' style='padding: 0 10px; position: absolute; height: 100%; width: 100%;'>" }).state("menu.type.client.parent", { url: "", abstract: true, views: { "parent@": { templateUrl: "app/client/client.html", controller: "senderController", resolve: { counterLatter: [ "$stateParams", "connect", function($stateParams, connect) { var counter, counterLatter, i, index, latter, latterSector, latters, lattersSectors, n, sectorLength, sendersInSector, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1; connect({ method: "GET", url: "http://api2.cosmonova.net.ua/human/countletters" }); counterLatter = [ { id: 0, latters: [ { name: "A", count: 2 }, { name: "B", count: 7 }, { name: "C", count: 7 }, { name: "D", count: 8 }, { name: "F", count: 18 }, { name: "G", count: 5 }, { name: "H", count: 14 }, { name: "I", count: 10 }, { name: "K", count: 4 }, { name: "L", count: 1 }, { name: "M", count: 1 }, { name: "N", count: 4 }, { name: "O", count: 1 }, { name: "P", count: 1 }, { name: "R", count: 4 }, { name: "S", count: 13 }, { name: "T", count: 11 }, { name: "U", count: 1 }, { name: "V", count: 4 }, { name: "W", count: 2 }, { name: "І", count: 1 } ] }, { id: 1, latters: [ { name: "А", count: 6 }, { name: "Б", count: 3 }, { name: "В", count: 11 }, { name: "Г", count: 2 }, { name: "Д", count: 3 }, { name: "Ж", count: 1 }, { name: "З", count: 4 }, { name: "К", count: 6 }, { name: "Л", count: 2 }, { name: "М", count: 8 }, { name: "Н", count: 1 }, { name: "О", count: 3 }, { name: "П", count: 11 }, { name: "Р", count: 3 }, { name: "С", count: 8 }, { name: "Т", count: 5 }, { name: "У", count: 1 }, { name: "Х", count: 1 }, { name: "Ч", count: 5 }, { name: "Ю", count: 4 }, { name: "Ч", count: 1 } ] } ]; for (_i = 0, _len = counterLatter.length; _i < _len; _i++) { counter = counterLatter[_i]; counter.count = 0; _ref = counter.latters; for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { latter = _ref[_j]; counter.count += latter.count; } } lattersSectors = new Array; for (n = _k = 0, _len2 = counterLatter.length; _k < _len2; n = ++_k) { latters = counterLatter[n]; sendersInSector = latters.count / 10; lattersSectors[n] = { id: latters.id, sectors: new Array, title: (function() { switch (latters.id) { case 0: return "ENG"; case 1: return "RUS"; default: return "NONE"; } })() }; sectorLength = 0; index = 0; lattersSectors[n].sectors[0] = new Object; lattersSectors[n].sectors[0].title = ""; _ref1 = latters.latters; for (i = _l = 0, _len3 = _ref1.length; _l < _len3; i = ++_l) { latterSector = _ref1[i]; sectorLength += latterSector.count; if (sectorLength < sendersInSector) { lattersSectors[n].sectors[index].title += latterSector.name; } else { index++; lattersSectors[n].sectors[index] = new Object; lattersSectors[n].sectors[index].title = latterSector.name; sectorLength = 0; } if (i === latters.latters.length - 1) { index++; } } } return lattersSectors; } ] } } } }).state("menu.type.client.parent.page", { url: "/:page?lang?filter?find?limit?count", templateUrl: "app/client/client.list.html", controller: "senderListController", resolve: { sendersList: [ "$stateParams", "connect", "$q", function($stateParams, connect, $q) { var defer, _ref; if ($stateParams.limit) { defer = $q.defer(); connect({ method: "GET", url: "http://api2.cosmonova.net.ua/human/humanbusiness", params: { query: JSON.stringify((_ref = $stateParams.filter) != null ? _ref.split("") : void 0), order: "ASC", limit: $stateParams.limit, offset: $stateParams.limit * ($stateParams.page - 1), where: $stateParams.find } }).then(function(data) { return setTimeout(function() { return defer.resolve(data); }, 0); }); return defer.promise; } } ] } }); } ]).controller("senderController", [ "$rootScope", "$scope", "$state", "flexible", "commander", "counterLatter", function($rootScope, $scope, $state, flexible, commander, counterLatter) { var searchLanguage, _i, _len; $scope.counterLatter = counterLatter; $scope.sendersList = new Object; $scope.searchLanguage = counterLatter[0]; for (_i = 0, _len = counterLatter.length; _i < _len; _i++) { searchLanguage = counterLatter[_i]; if (searchLanguage.title === $rootScope.$stateParams.lang) { $scope.searchLanguage = searchLanguage; } } if ($rootScope.$stateParams.find) { $scope.activeSearch = $rootScope.$stateParams.find.slice(3, $rootScope.$stateParams.find.indexOf(":") - 1); $scope.dataToSearch = $rootScope.$stateParams.find.slice($rootScope.$stateParams.find.indexOf("%") + 1, -5); } flexible([ { width: 1024, height: 768, limit: 9 }, { width: 1366, height: 768, limit: 12 }, { width: 1680, height: 1050, limit: 20 }, { width: 1920, height: 1200, limit: 30 } ]); $scope.$watch("limit", function(limit) { if (limit && limit !== ~~$rootScope.$stateParams.limit) { $scope.animation = null; return setTimeout(function() { return $state.go("menu.type.client.parent.page", { limit: limit }, { notify: false }); }); } }); $scope.go = function(next) { var page, pages; pages = Math.ceil($rootScope.count / $rootScope.limit); if (next) { $scope.animation = "right"; if ($rootScope.$stateParams.page < pages) { page = ~~$rootScope.$stateParams.page + 1; } else { page = 1; } } else { $scope.animation = "left"; if ($rootScope.$stateParams.page > 1) { page = ~~$rootScope.$stateParams.page - 1; } else { page = pages; } } return $state.go("menu.type.client.parent.page", { page: page }); }; $scope.changeSearchLanguage = function(lang) { $scope.animation = null; $rootScope.$stateParams.lang = lang; $scope.activeSearch = null; $scope.dataToSearch = null; return $state.go("menu.type.client.parent.page", { filter: null, page: 1, find: null }, { notify: false }); }; $scope.filterActivator = function(filter) { $scope.animation = null; $scope.activeSearch = void 0; $scope.dataToSearch = void 0; if (filter) { $rootScope.$stateParams.filter = filter; } else { $rootScope.$stateParams.filter = void 0; } return $state.go("menu.type.client.parent.page", { filter: filter, page: 1, find: null }, { notify: false }); }; return $scope.findBy = function(searchParam, searchString) { $scope.animation = null; if (searchParam && searchString) { $scope.activeSearch = searchParam; return $state.go("menu.type.client.parent.page", { find: "{ \"" + searchParam + "\": \"LIKE '%" + searchString + "%'\" }", page: 1, filter: null }, { notify: false }); } }; } ]).controller("senderListController", [ "$rootScope", "$scope", "$state", "commander", "sendersList", function($rootScope, $scope, $state, commander, sendersList) { $scope.$watch(function() { return $state.$current.locals.globals.sendersList; }, function(sendersList) { if (sendersList) { $scope.sendersList = sendersList[1]; return $rootScope.count = sendersList[0].current_count; } }); return $scope.changeSender = function(customer) { if ($rootScope.$stateParams.client === "sender") { return $rootScope.Sender = customer; } else if ($rootScope.$stateParams.client === "addressee") { return $rootScope.Addressee = customer; } }; } ]); }).call(this); <file_sep>(function() { angular.module("pos-terminal-ligistics.packing", ["ui.router", "connect"]).config([ "$stateProvider", function($stateProvider) { return $stateProvider.state("menu.type.packing", { url: "/packing", abstract: true, templateUrl: "app/packing/packing.html" }).state("menu.type.packing.treatments", { url: "/:cargoName?treatments?cargoPrice?flatrateId", abstract: true, views: { "@treatments": { templateUrl: "app/packing/packing.treatments.html", controller: "packingController", resolve: { treatments: [ "$stateParams", "connect", "$q", function($stateParams, connect, $q) { var defer; defer = $q.defer(); connect({ method: "GET", url: "http://api.cosmonova.net.ua/type-treatment" }).then(function(data) { return setTimeout(function() { return defer.resolve(data); }, 0); }); return defer.promise; } ] } }, "": { template: "<div class='3d-right-left ui-view' style='position: absolute; width: 100%; height: 100%; overflow: hidden;'> </div>", controller: "packegesController", resolve: { flatrate: [ "$stateParams", "connect", "$q", function($stateParams, connect, $q) { var defer; defer = $q.defer(); connect({ method: "GET", url: 'http://api.cosmonova.net.ua/flat-rate?with=product.price&where={"flatRate.id":"=1"}' }).then(function(data) { return setTimeout(function() { return defer.resolve(data); }, 0); }); return defer.promise; } ] } } } }).state("menu.type.packing.treatments.flatrate", { url: "/flatrate", templateUrl: "app/packing/packing.flatrates.html", controller: "flatrateController", resolve: { flatrates: [ "$stateParams", "connect", "$q", function($stateParams, connect, $q) { var defer; defer = $q.defer(); connect({ method: "GET", url: "http://api.cosmonova.net.ua/flat-rate?with=product.price" }).then(function(data) { return setTimeout(function() { return defer.resolve(data); }, 0); }); return defer.promise; } ] } }).state("menu.type.packing.treatments.custom", { url: "/custom", templateUrl: "app/packing/packing.customs.html", controller: "customController", resolve: { customs: [ "$stateParams", "connect", "$q", function($stateParams, connect, $q) { var defer; defer = $q.defer(); connect({ method: "GET", url: "http://api.cosmonova.net.ua/product-to-category?with=product.category&where={%22Category.id%22%20:%20%22%20=%2091%22}" }).then(function(data) { return setTimeout(function() { return defer.resolve(data); }, 0); }); return defer.promise; } ] } }); } ]).controller("customController", [ "$rootScope", "$scope", "$state", "customs", function($rootScope, $scope, $state, customs) { return setTimeout(function() { return $scope.$apply(function() { return $scope.customs = customs[1]; }); }, 300); } ]).controller("flatrateController", [ "$rootScope", "$scope", "$state", "flatrates", function($rootScope, $scope, $state, flatrates) { $scope.addFlatrate = function(flatrate) { var flatrateId; flatrateId = flatrate.flatRate.id; if ($rootScope.$stateParams.flatrateId !== flatrateId) { return $state.go($state.current, { flatrateId: flatrateId }, { notify: false }); } else { return $state.go($state.current, { flatrateId: null }, { notify: false }); } }; return setTimeout(function() { return $scope.$apply(function() { return $scope.flatrates = flatrates[1]; }); }, 300); } ]).controller("packegesController", [ "$scope", function($scope) { return $scope.packages = { flatrate: new Object, customs: new Array }; } ]).controller("packingController", [ "$rootScope", "$scope", "$state", "treatments", function($rootScope, $scope, $state, treatments) { $scope.treatments = treatments[0]; $scope.selectTreatment = function(treatment) { var index; treatments = JSON.parse($rootScope.$stateParams.treatments); index = treatments.indexOf(treatment.id); if (index === -1) { treatments.push(treatment.id); } else { treatments.splice(index, 1); } return $state.go($state.current, { treatments: JSON.stringify(treatments) }, { reload: false, notify: false }); }; $scope.$watch("cargoName", function(cargoName) { return $state.go($state.current, { cargoName: cargoName }, { notify: false }); }); $scope.cargoName = $rootScope.$stateParams.cargoName; $scope.$watch("cargoPrice", function(cargoPrice) { if (cargoPrice) { if (/^\d+$/.test(cargoPrice)) { return $state.go($state.current, { cargoPrice: cargoPrice }, { notify: false }); } else { return $scope.cargoPrice = $scope.cargoPrice.slice(0, $scope.cargoPrice.length); } } }); if ($rootScope.$stateParams.cargoPrice) { return $scope.cargoPrice = parseInt($rootScope.$stateParams.cargoPrice); } } ]).filter("arrayContain", function() { return function(array, contain) { var i, _i, _ref; array = JSON.parse(array); for (i = _i = 0, _ref = array.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { if (array[i] === contain) { return true; } } }; }); }).call(this); <file_sep>(function() { angular.module("breadcrumbs", []).constant("breadcrumbs", new Array).directive("breadcrumbs", function() { return { restrict: "E", replace: true, templateUrl: "app/global/breadcrumbs.html", controller: function($scope, breadcrumbs) { return $scope.goCrumbs = function($index, state) { $scope.addCommand(state); return breadcrumbs.splice($index + 1); }; } }; }); }).call(this); <file_sep>(function() { angular.module("baseUrl", []).constant("baseUrl", { authorization: { name: "authorization", path: "/auth", login: "http://api2.cosmonova.net.ua/authorized/index", logout: "http://api2.cosmonova.net.ua/authorized/logout" }, outlet: { name: "outlet", path: "/outlet", list: "http://api2.cosmonova.net.ua/hierarchy/?with=outlet.business" }, topMenu: { name: "topmenu", path: "" }, waybill: { name: "topmenu.waybill", path: "/waybill", home: { name: "topmenu.waybill.home", path: "/home" }, sender: { name: "topmenu.waybill.sender", path: "/sender", list: { name: "topmenu.waybill.sender.list", path: "/list", page: { name: "topmenu.waybill.sender.list.page", path: "/:page?count&filter&lang&limit&search" } }, customer: { name: "topmenu.waybill.sender.customer", path: "/customer", human: { name: "topmenu.waybill.sender.customer.human", path: "/human" }, business: { name: "topmenu.waybill.sender.customer.bisuness", path: "/business", legalForm: "http://api.cosmonova.net.ua/legal-form" } } }, destination: { name: "topmenu.waybill.destination", path: "/destination?page&filter&lang&limit&where", department: { name: "topmenu.waybill.destination.department", path: "/department", city: { name: "topmenu.waybill.destination.department.city", path: "/city" }, postoffice: { name: "topmenu.waybill.destination.department.postoffice", path: "/postoffice" } }, door: { name: "topmenu.waybill.destination.door", path: "/door", find: { name: "topmenu.waybill.destination.door.find", path: "/find?find", street: { name: "topmenu.waybill.destination.door.find.street", path: "/street" }, location: { name: "topmenu.waybill.destination.door.find.location", path: "/location" } } } } }, cargo: { name: "topmenu.cargo", path: "/cargo", home: { name: "topmenu.cargo.home", path: "/home" } } }); }).call(this); <file_sep>(function() { angular.module("basicDate", []).directive("basicDate", function() { return { scope: { date: "=", name: "@" }, templateUrl: "app/global/basicDate.html", link: function($scope, $element, $attrs) { var day, year; $scope.$watch("[ year, month, day.value ]", function(birthday) { var date, daysInmonth, result, _i, _len; result = ""; for (_i = 0, _len = birthday.length; _i < _len; _i++) { date = birthday[_i]; if (!date) { return; } result = result.concat(date.concat("-")); } result = result.slice(0, -1); daysInmonth = new Date(birthday[0], birthday[1], 0).getDate(); if (daysInmonth < birthday[2]) { $scope.date = ""; return $scope.basicDate.$setValidity("badDay", false); } else { $scope.date = result; return $scope.basicDate.$setValidity("badDay", true); } }); return $scope.labels = { days: (function() { var _i, _results; _results = []; for (day = _i = 1; _i <= 31; day = ++_i) { if (day.toString().length === 1) { day = "0".concat(day); } else { day = day.toString(); } _results.push({ label: day, value: day }); } return _results; })(), months: [ { label: "январь", value: "01" }, { label: "февраль", value: "02" }, { label: "март", value: "03" }, { label: "апрель", value: "04" }, { label: "май", value: "05" }, { label: "июнь", value: "06" }, { label: "июль", value: "07" }, { label: "август", value: "08" }, { label: "сентябрь", value: "09" }, { label: "октябрь", value: "10" }, { label: "ноябрь", value: "11" }, { label: "декабрь", value: "12" } ], year: (function() { var _i, _results; _results = []; for (year = _i = 2015; _i >= 1915; year = _i += -1) { year = year.toString(); _results.push({ label: year, value: year }); } return _results; })() }; } }; }); }).call(this); <file_sep>(function() { angular.module("carousel", []).directive('carousel', function() { return { transclude: true, compile: function($element, $attr, $link) { return function($scope, $element, $attr) { var $body, $loader, $parent, $scroll, $template, collectionName, element, itemName, matchData, parent, speedValue; $element.css({ opacity: 0 }); element = $element[0]; $loader = angular.element("<div class='content-loader'></div>"); $scroll = angular.element("<div class='carousel-scroll'></div>"); $parent = $element.parent(); parent = $parent[0]; $template = $element.children().remove(); $parent.append($loader); TweenLite.to($loader, 0.16, { opacity: 1, ease: Sine.easeOut }); $body = angular.element(document.body); matchData = $attr.carousel.split(":"); collectionName = matchData[0]; itemName = matchData[1]; speedValue = matchData[2]; return $scope.$watchCollection(collectionName, function(collection) { var params; if (collection) { params = { opacity: 1 }; return TweenLite.to(params, 0.16, { opacity: 0, ease: Sine.easeOut, onUpdate: function() { return $loader.css({ opacity: params.opacity }); }, onComplete: function() { var carouselWidth, children, count, itemWidth, lastX, maxCount, nowX, onmove, rate, startX, step, wrapLeft, wrapWidth; angular.forEach(collection, function(itemData) { var childScope; childScope = $scope.$new(false, $scope); childScope[itemName] = itemData; return $scope.$apply(function() { return $link(childScope, function(clone) { return $element.append(clone); }); }); }); $parent.append($scroll); wrapWidth = parent.clientWidth; wrapLeft = 0; children = $element.children()[0]; itemWidth = children.clientWidth; carouselWidth = element.clientWidth; rate = wrapWidth / carouselWidth; $scroll.css({ width: "" + (rate * wrapWidth) + "px" }); startX = lastX = nowX = 0; count = 0; step = parseInt(speedValue); maxCount = -Math.ceil((wrapWidth - carouselWidth) / itemWidth); onmove = function($event) { $event.stopPropagation(); nowX = $event.pageX - wrapLeft - startX; if (nowX === lastX) { return; } if (-nowX - lastX > (count + 1) * step) { if (count < maxCount) { count++; } else { count = maxCount; } } if (-nowX - lastX <= count * step) { if (count > 0) { count--; } else { count = 0; } } TweenLite.to($element, 0.6, { left: "" + (-count * itemWidth) + "px", ease: Sine.easeOut }); TweenLite.to($scroll, 0.6, { left: "" + (count * itemWidth * rate) + "px", ease: Sine.easeOut }); return lastX = nowX; }; $parent.bind("mousedown", function($event) { $event.stopPropagation(); wrapLeft = parent.getBoundingClientRect().left; startX = $event.pageX - wrapLeft - lastX; return $body.bind("mousemove", onmove); }); $body.bind("mouseup", function($event) { $event.stopPropagation(); return $body.unbind("mousemove", onmove); }); return TweenLite.to($element, 0.6, { opacity: 1, ease: Sine.easeOut }); } }); } }); }; } }; }); }).call(this);
622570bc1505f45ee4fa52254f01b969041e5b46
[ "JavaScript" ]
14
JavaScript
tkachenko-vladislav/pos-terminal-logistics
766162e257f7deabf6b6eb0c4f35490d87a7e8e3
b14566c85fb49072f98800be516714a23bbf725c
refs/heads/main
<repo_name>Vinidamiaop/music-library<file_sep>/README.md # DevChallenge - Music Library Essa é um desafio da [DevChallenge](https://github.com/devchallenge-io/music-library-page) que eu estou fazendo para aprender e melhorar minhas habilidades com front-end. Pequenas melhorias ainda estão sendo feitas. ##### Desktop ![Print 1](./img/project-print/site1.png) ##### Mobile ![Print 1](./img/project-print/site2.png)<file_sep>/js/mobile.js export default class MobileMenu { constructor(menu, btnMenu, btnClose) { this.menu = document.querySelector(menu); this.btnMenu = document.querySelector(btnMenu); this.btnClose = document.querySelector(btnClose); this.eventList = ["touchstart", "click"]; this.activeClass = "active"; } toggleMenu() { this.menu.classList.toggle(this.activeClass); } handleClick() { const body = document.querySelector("body"); this.toggleMenu(); window.scrollTo({ top: 0, behavior: "smooth", }); if (this.menu.className.includes(this.activeClass)) { body.style.overflow = "hidden"; } else { body.style.overflow = "auto"; } } addMenuEvents() { this.eventList.forEach((item) => { this.btnMenu.addEventListener(item, this.handleClick); this.btnClose.addEventListener(item, this.handleClick); }); } bindFunctions() { this.handleClick = this.handleClick.bind(this); } init() { this.bindFunctions(); this.addMenuEvents(); console.log(this.menu); console.log(this.btnMenu); } } <file_sep>/js/script.js import MobileMenu from "./mobile.js"; const menu = new MobileMenu(".menu", ".btnMenu", ".btnClose"); menu.init();
1b07fdbf9b8e78831db8849cdb2ea95ed2b7a904
[ "Markdown", "JavaScript" ]
3
Markdown
Vinidamiaop/music-library
39582e5734af778da9a9e12d820f44dae00a4022
0dfe42926bb2a00cb92a86975cfc11ed24efd129
refs/heads/master
<repo_name>djlebersilvestre/new_lib<file_sep>/README.md # new_lib A base ruby lib project with some dependencies installed and configured to ease the development. The idea is to have a skeleton for new projects and keep the tech stack up to date. ## TODO: * Install and configure simple-cov and other metric gems * Try to incorporate metrics into guard or git-hooks <file_sep>/test/test_helper.rb require 'minitest/autorun' require 'mocha/mini_test' require_relative '../lib/bootstrap' <file_sep>/lib/classes/foo.rb # A Foo class class Foo include ActiveModel::Validations attr_accessor :p1, :p2 validates :p1, presence: true validates :p2, presence: true def initialize(params = {}) params.each do |key, value| instance_variable_set("@#{key}", value) end end end <file_sep>/Gemfile source 'http://rubygems.org' gem 'activemodel' gem 'byebug' gem 'guard' gem 'guard-minitest' gem 'guard-rubocop' gem 'minitest' gem 'mocha' gem 'rubocop' <file_sep>/lib/bootstrap.rb # Main libraries and dependencies %w( byebug active_model ).each { |l| require l } def require_all_in_dir(*dirnames) Dir[File.join(File.dirname(__FILE__), dirnames, '*.rb')].each do |f| require_relative File.join(dirnames, File.basename(f, '*.')) end end require_all_in_dir('classes') <file_sep>/test/foo_test.rb require_relative 'test_helper' class FooTest < Minitest::Test def test_params_initialization foo = Foo.new(p1: :p1, p2: :p2) assert_equal :p1, foo.p1 assert_equal :p2, foo.p2 end def test_valid foo = Foo.new refute foo.valid? assert_includes foo.errors.full_messages, "P1 can't be blank" assert_includes foo.errors.full_messages, "P2 can't be blank" foo.p1 = :a foo.p2 = :b assert foo.valid? end end <file_sep>/script/rubocop #!/bin/bash dir="$(cd -P -- "$(dirname -- "$0")" && pwd -P)" run_over_changed_files() { changed_files=$(git status --porcelain | grep -v 'D ' | grep '\.rb$' | awk '{print $2}') if [ -z "${changed_files}" ]; then echo "There are no files to commit therefore there are no files to be validated" else bundle exec rubocop --force-exclusion $changed_files fi } run_stats() { bundle exec rubocop -fo } case "$1" in changed) run_over_changed_files ;; stats) run_stats ;; *) echo "Usage: $0 [changed|stats]" echo "" echo "Details" echo " changed: runs rubocop over local git changes (before commit)" echo " stats: runs rubocop to extract overall stats of the project" echo " default: if no option is given it will run 'changed' option" echo "" run_over_changed_files ;; esac
b79289f7b79865f7f963d2fac957a4ad8df8e61d
[ "Markdown", "Ruby", "Shell" ]
7
Markdown
djlebersilvestre/new_lib
4fe626d25a1d0715122a12436053d7c77ac0e794
4f3b176cdf741990c43ccdcddcaeab7b1876c56e
refs/heads/master
<repo_name>GalasM/SpotifyApp<file_sep>/app/src/main/java/com/example/spotifyapp/SearchActivity.java package com.example.spotifyapp; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.AppCompatImageButton; import com.example.spotifyapp.models.Playlist; import com.example.spotifyapp.models.Track; import com.google.gson.Gson; import com.spotify.sdk.android.auth.AuthorizationRequest; import com.spotify.sdk.android.auth.AuthorizationResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Request; import okhttp3.Response; import static com.example.spotifyapp.Config.CLIENT_ID; import static com.example.spotifyapp.Config.REDIRECT_URI; import static com.example.spotifyapp.Config.TRACK_URI; import static com.example.spotifyapp.Config.cancelCall; import static com.example.spotifyapp.Config.mAccessToken; import static com.example.spotifyapp.Config.mCall; import static com.example.spotifyapp.Config.mOkHttpClient; import static com.example.spotifyapp.Config.mSpotifyAppRemote; public class SearchActivity extends AppCompatActivity { Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_layout); context = this; Config.connect(true, context); ListView list = (ListView) findViewById(R.id.songs); ArrayList<Track> arrayList = new ArrayList<>(); if (getIntent().hasExtra("json")) { try { JSONArray tracks = new JSONArray(getIntent().getStringExtra("json")); for (int i = 0; i < tracks.length(); i++) { JSONObject x = tracks.getJSONObject(i); Track t = new Track(); t.setName(x.getString("name")); t.setUri(x.getString("uri")); t.setArtist(x.getJSONArray("artists").getJSONObject(0).getString("name")); arrayList.add(t); } ArrayAdapter<Track> listAdapter = new SongAdapter(this, R.layout.search_row, arrayList); list.setAdapter(listAdapter); } catch (JSONException e) { e.printStackTrace(); } } if (getIntent().hasExtra("name")) { TextView nameView = findViewById(R.id.searched_song); nameView.setText(getIntent().getStringExtra("name")); } } private void setResponse(final String text) { runOnUiThread(new Runnable() { @Override public void run() { final TextView responseView = findViewById(R.id.response_text_view); responseView.setText(text); } }); } private AuthorizationRequest getAuthenticationRequest(AuthorizationResponse.Type type) { return new AuthorizationRequest.Builder(CLIENT_ID, type, getRedirectUri().toString()) .setShowDialog(false) .setScopes(new String[]{"user-read-email"}) .setCampaign("your-campaign-token") .build(); } private Uri getRedirectUri() { return Uri.parse(REDIRECT_URI); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.help) { openTutorial(); } return (super.onOptionsItemSelected(item)); } public void openTutorial() { Intent intent = new Intent(this, TutorialActivity.class); intent.putExtra("help", "search"); startActivity(intent); } public void openPlayer(View view) { TextView name = view.findViewById(R.id.name); Intent intent = new Intent(this, PlayerActivity.class); intent.putExtra("song_name", name.getText().toString()); startActivity(intent); } private class SongAdapter extends ArrayAdapter<Track> { private ArrayList<Track> items; public SongAdapter(Context context, int textViewResourceId, ArrayList<Track> items) { super(context, textViewResourceId, items); this.items = items; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.search_row, null); } Track o = items.get(position); if (o != null) { final TextView name = v.findViewById(R.id.name); name.setText(o.getArtist()+" - "+o.getName()); AppCompatImageButton play = v.findViewById(R.id.play); play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, PlayerActivity.class); Gson json = new Gson(); String j = json.toJson(o); intent.putExtra("track", j); startActivity(intent); } }); AppCompatImageButton favorite = v.findViewById(R.id.favorite); favorite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mSpotifyAppRemote .getUserApi() .addToLibrary(o.getUri()) .setResultCallback( empty -> Toast.makeText(context, name.getText().toString() + " has been added to favorites", Toast.LENGTH_SHORT).show()) .setErrorCallback(error -> Toast.makeText(context, error + " error", Toast.LENGTH_SHORT).show()); } }); AppCompatImageButton add = v.findViewById(R.id.add); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { addToPlaylist(o); } catch (MalformedURLException e) { e.printStackTrace(); } } }); } return v; } public void addToPlaylist(Track track) throws MalformedURLException { ArrayList<Playlist> list = new ArrayList<>(); TRACK_URI = track.getUri(); URL url = new URL("https://api.spotify.com/v1/me/playlists"); final Request request = new Request.Builder() .url(url) .addHeader("Authorization", "Bearer " + mAccessToken) .build(); //cancelCall(); mCall = mOkHttpClient.newCall(request); mCall.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { try { final JSONObject jsonObject = new JSONObject(response.body().string()); JSONArray playlists = jsonObject.getJSONArray("items"); Intent intent = new Intent(context, ListPlaylistActivity.class); intent.putExtra("playlists", playlists.toString()); startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }); } } } <file_sep>/app/src/main/java/com/example/spotifyapp/PlayerActivity.java package com.example.spotifyapp; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.AppCompatImageButton; import androidx.appcompat.widget.AppCompatSeekBar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.example.spotifyapp.models.Playlist; import com.example.spotifyapp.models.Track; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.spotify.android.appremote.api.ConnectionParams; import com.spotify.android.appremote.api.Connector; import com.spotify.android.appremote.api.SpotifyAppRemote; import com.spotify.protocol.client.Subscription; import com.spotify.protocol.types.Image; import com.spotify.protocol.types.PlayerContext; import com.spotify.protocol.types.PlayerState; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Request; import okhttp3.Response; import static com.example.spotifyapp.Config.cancelCall; import static com.example.spotifyapp.Config.mAccessToken; import static com.example.spotifyapp.Config.mCall; import static com.example.spotifyapp.Config.mOkHttpClient; import static com.example.spotifyapp.Config.mSpotifyAppRemote; import static com.example.spotifyapp.Config.TRACK_URI; public class PlayerActivity extends AppCompatActivity { private Context context; Gson gson = new GsonBuilder().setPrettyPrinting().create(); TextView mSongName; ImageView mCoverArtImageView; AppCompatImageButton mPlayPauseButton; AppCompatSeekBar mSeekBar; List<View> mViews; TrackProgressBar mTrackProgressBar; Subscription<PlayerState> mPlayerStateSubscription; Subscription<PlayerContext> mPlayerContextSubscription; private final Subscription.EventCallback<PlayerContext> mPlayerContextEventCallback = new Subscription.EventCallback<PlayerContext>() { @Override public void onEvent(PlayerContext playerContext) { } }; private final Subscription.EventCallback<PlayerState> mPlayerStateEventCallback = new Subscription.EventCallback<PlayerState>() { @Override public void onEvent(PlayerState playerState) { mSongName.setText(playerState.track.artist.name + " - " + playerState.track.name); TRACK_URI = playerState.track.uri; /*// Update progressbar if (playerState.playbackSpeed > 0) { mTrackProgressBar.unpause(); } else { mTrackProgressBar.pause(); }*/ if (playerState.isPaused) { mPlayPauseButton.setImageResource(R.drawable.btn_play); } else { mPlayPauseButton.setImageResource(R.drawable.btn_pause); } mSpotifyAppRemote .getImagesApi() .getImage(playerState.track.imageUri, Image.Dimension.LARGE) .setResultCallback( bitmap -> { mCoverArtImageView.setImageBitmap(bitmap); }); /* mSeekBar.setMax((int) playerState.track.duration); mTrackProgressBar.setDuration(playerState.track.duration); mTrackProgressBar.update(playerState.playbackPosition); mSeekBar.setEnabled(true);*/ } }; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.player_layout); context = this; mCoverArtImageView = findViewById(R.id.image); mPlayPauseButton = findViewById(R.id.play_pause_button); mSongName = findViewById(R.id.song_name); /*mSeekBar = findViewById(R.id.seek_to); mSeekBar.setEnabled(false); mSeekBar.getProgressDrawable().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP); mSeekBar.getIndeterminateDrawable().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);*/ /*mTrackProgressBar = new TrackProgressBar(mSeekBar);*/ mViews = Arrays.asList( mPlayPauseButton, findViewById(R.id.skip_prev_button), findViewById(R.id.skip_next_button) // mSeekBar ); SpotifyAppRemote.setDebugMode(true); //onDisconnected(); connect(true); } @Override protected void onStop() { super.onStop(); //SpotifyAppRemote.disconnect(mSpotifyAppRemote); //onDisconnected(); } private void onConnected() { for (View input : mViews) { input.setEnabled(true); } onSubscribedToPlayerStateButtonClicked(null); onSubscribedToPlayerContextButtonClicked(null); } private void onDisconnected() { for (View view : mViews) { view.setEnabled(false); } mCoverArtImageView.setImageResource(R.drawable.widget_placeholder); } private void connect(boolean showAuthView) { //SpotifyAppRemote.disconnect(mSpotifyAppRemote); SpotifyAppRemote.connect( getApplication(), new ConnectionParams.Builder(Config.CLIENT_ID) .setRedirectUri(Config.REDIRECT_URI) .showAuthView(showAuthView) .build(), new Connector.ConnectionListener() { @Override public void onConnected(SpotifyAppRemote spotifyAppRemote) { mSpotifyAppRemote = spotifyAppRemote; PlayerActivity.this.onConnected(); myConnect(); System.out.println("myconnect"); } @Override public void onFailure(Throwable error) { error.printStackTrace(); //PlayerActivity.this.onDisconnected(); } }); } public void onPlayTrackButtonClicked(View view) { playUri(TRACK_URI); } private void playUri(String uri) { mSpotifyAppRemote .getPlayerApi() .play(uri); } public void showCurrentPlayerContext(View view) { if (view.getTag() != null) { showDialog("PlayerContext", gson.toJson(view.getTag())); } } public void showCurrentPlayerState(View view) { if (view.getTag() != null) { showDialog("PlayerState", gson.toJson(view.getTag())); } } public void onSkipPreviousButtonClicked(View view) { mSpotifyAppRemote .getPlayerApi() .skipPrevious(); } public void onPlayPauseButtonClicked(View view) { mSpotifyAppRemote .getPlayerApi() .getPlayerState() .setResultCallback( playerState -> { if (playerState.isPaused) { mSpotifyAppRemote .getPlayerApi() .resume(); } else { mSpotifyAppRemote .getPlayerApi() .pause(); } }); } public void onSkipNextButtonClicked(View view) { mSpotifyAppRemote .getPlayerApi() .skipNext(); } public void onRemoveUriClicked(View view) { mSpotifyAppRemote .getUserApi() .removeFromLibrary(TRACK_URI); } public void onSaveUriClicked(View view) { mSpotifyAppRemote .getUserApi() .addToLibrary(TRACK_URI); Toast.makeText(context, "Track has been added to favotites", Toast.LENGTH_SHORT).show(); } public void onSubscribedToPlayerContextButtonClicked(View view) { if (mPlayerContextSubscription != null && !mPlayerContextSubscription.isCanceled()) { mPlayerContextSubscription.cancel(); mPlayerContextSubscription = null; } mPlayerContextSubscription = (Subscription<PlayerContext>) mSpotifyAppRemote .getPlayerApi() .subscribeToPlayerContext() .setEventCallback(mPlayerContextEventCallback); } public void onSubscribedToPlayerStateButtonClicked(View view) { if (mPlayerStateSubscription != null && !mPlayerStateSubscription.isCanceled()) { mPlayerStateSubscription.cancel(); mPlayerStateSubscription = null; } mPlayerStateSubscription = (Subscription<PlayerState>) mSpotifyAppRemote .getPlayerApi() .subscribeToPlayerState() .setEventCallback(mPlayerStateEventCallback) .setLifecycleCallback( new Subscription.LifecycleCallback() { @Override public void onStart() { } @Override public void onStop() { } }); } private void showDialog(String title, String message) { new AlertDialog.Builder(this).setTitle(title).setMessage(message).create().show(); } private class TrackProgressBar { private static final int LOOP_DURATION = 500; private final SeekBar mSeekBar; private final Handler mHandler; private final SeekBar.OnSeekBarChangeListener mSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { mSpotifyAppRemote .getPlayerApi() .seekTo(seekBar.getProgress()); } }; private final Runnable mSeekRunnable = new Runnable() { @Override public void run() { int progress = mSeekBar.getProgress(); mSeekBar.setProgress(progress + LOOP_DURATION); mHandler.postDelayed(mSeekRunnable, LOOP_DURATION); } }; private TrackProgressBar(SeekBar seekBar) { mSeekBar = seekBar; mSeekBar.setOnSeekBarChangeListener(mSeekBarChangeListener); mHandler = new Handler(); } private void setDuration(long duration) { mSeekBar.setMax((int) duration); } private void update(long progress) { mSeekBar.setProgress((int) progress); } private void pause() { mHandler.removeCallbacks(mSeekRunnable); } private void unpause() { mHandler.removeCallbacks(mSeekRunnable); mHandler.postDelayed(mSeekRunnable, LOOP_DURATION); } } private void myConnect() { if (getIntent().hasExtra("track")) { Gson json = new Gson(); Track track = json.fromJson(getIntent().getStringExtra("track"), Track.class); //mSongName = findViewById(R.id.song_name); //mSongName.setText(track.getArtist() + " - " + track.getName()); TRACK_URI = track.getUri(); onSubscribedToPlayerStateButtonClicked(null); onSubscribedToPlayerContextButtonClicked(null); playUri(track.getUri()); } else if (getIntent().hasExtra("playlist")) { Gson json = new Gson(); Playlist playlist = json.fromJson(getIntent().getStringExtra("playlist"), Playlist.class); onSubscribedToPlayerStateButtonClicked(null); onSubscribedToPlayerContextButtonClicked(null); playUri(playlist.getUri()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.help) { openTutorial(); } return (super.onOptionsItemSelected(item)); } public void openTutorial() { Intent browserIntent = new Intent(this, TutorialActivity.class); startActivity(browserIntent); } public void addToPlaylist(View view) throws MalformedURLException { ArrayList<Playlist> list = new ArrayList<>(); URL url = new URL("https://api.spotify.com/v1/me/playlists"); final Request request = new Request.Builder() .url(url) .addHeader("Authorization", "Bearer " + mAccessToken) .build(); //cancelCall(); mCall = mOkHttpClient.newCall(request); mCall.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { try { final JSONObject jsonObject = new JSONObject(response.body().string()); JSONArray playlists = jsonObject.getJSONArray("items"); Intent intent = new Intent(context, ListPlaylistActivity.class); intent.putExtra("playlists", playlists.toString()); startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }); } }<file_sep>/app/src/main/java/com/example/spotifyapp/PlaylistEditActivity.java package com.example.spotifyapp; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.AppCompatImageButton; import com.example.spotifyapp.interfaces.DialogCallback; import com.example.spotifyapp.models.Playlist; import com.example.spotifyapp.models.Track; import com.example.spotifyapp.utlis.GlobalUtils; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import static com.example.spotifyapp.Config.cancelCall; import static com.example.spotifyapp.Config.mAccessToken; import static com.example.spotifyapp.Config.mCall; import static com.example.spotifyapp.Config.currentPlaylist; import static com.example.spotifyapp.Config.mOkHttpClient; public class PlaylistEditActivity extends AppCompatActivity { Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit_playlist_layout); context = this; ListView list = (ListView) findViewById(R.id.playlists_edit); if (getIntent().hasExtra("playlist_name")) { TextView name = (TextView) findViewById(R.id.edit_name); name.setText("Edited: " + getIntent().getStringExtra("playlist_name")); } if(getIntent().hasExtra("tracks")){ try { ArrayList<Track> arrayList = new ArrayList<>(); JSONArray items = new JSONArray(getIntent().getStringExtra("tracks")); for (int i = 0; i < items.length(); i++) { JSONObject x = items.getJSONObject(i); Track t = new Track(); JSONObject track = x.getJSONObject("track"); t.setName(track.getString("name")); t.setUri(track.getString("uri")); t.setArtist(track.getJSONArray("artists").getJSONObject(0).getString("name")); arrayList.add(t); } ArrayAdapter<Track> listAdapter = new PlaylistEditActivity.PlaylistEditAdapter(context, R.layout.playlist_edit_row, arrayList); list.setAdapter(listAdapter); } catch (JSONException e) { e.printStackTrace(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.help) { openTutorial(); } return (super.onOptionsItemSelected(item)); } public void openTutorial() { Intent intent = new Intent(this, TutorialActivity.class); intent.putExtra("help", "edit_playlist"); startActivity(intent); } public void changeName(View view) { TextView text = findViewById(R.id.edit_name); EditText newName = findViewById(R.id.inputName); text.setText("Edited: " + newName.getText().toString()); Toast.makeText(this, "Name has been changed", Toast.LENGTH_SHORT).show(); try { changeNamePlaylist(newName.getText().toString()); } catch (JSONException e) { e.printStackTrace(); } } public void showDialog(View view) { GlobalUtils.showDialog(this, new DialogCallback() { @Override public void callback(int ratings) { } }); } private class PlaylistEditAdapter extends ArrayAdapter<Track> { private ArrayList<Track> items; public PlaylistEditAdapter(Context context, int textViewResourceId, ArrayList<Track> items) { super(context, textViewResourceId, items); this.items = items; } @Override public View getView(final int position, final View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.playlist_edit_row, null); } final Track o = items.get(position); if (o != null) { TextView name = (TextView) v.findViewById(R.id.song_name_edit); name.setText(o.getArtist() + " - " + o.getName()); AppCompatImageButton delete = v.findViewById(R.id.remove_song); delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { removeItemFromAdapter(o); } catch (JSONException e) { e.printStackTrace(); } } }); } return v; } public void removeItemFromAdapter(Track track) throws JSONException { this.remove(track); removeTrackFromPlaylist(track); } } public void removeTrackFromPlaylist(Track track) throws JSONException { JSONObject json = new JSONObject(); JSONArray tracks = new JSONArray(); JSONObject uri = new JSONObject(); uri.putOpt("uri", track.getUri()); tracks.put(uri); json.putOpt("tracks", tracks); URL url = null; try { url = new URL("https://api.spotify.com/v1/playlists/" + currentPlaylist.getId() + "/tracks"); } catch (MalformedURLException e) { e.printStackTrace(); } final Request request = new Request.Builder() .url(url) .delete(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json.toString())) .addHeader("Authorization", "Bearer " + mAccessToken) .build(); //cancelCall(); mCall = mOkHttpClient.newCall(request); mCall.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { } }); } public void changeNamePlaylist(String name) throws JSONException { JSONObject json = new JSONObject(); json.put("name", name); URL url = null; try { url = new URL("https://api.spotify.com/v1/playlists/" + currentPlaylist.getId()); } catch (MalformedURLException e) { e.printStackTrace(); } final Request request = new Request.Builder() .url(url) .put(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json.toString())) .addHeader("Authorization", "Bearer " + mAccessToken) .build(); //cancelCall(); mCall = mOkHttpClient.newCall(request); mCall.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { } }); } } <file_sep>/app/src/main/java/com/example/spotifyapp/ListPlaylistActivity.java package com.example.spotifyapp; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.example.spotifyapp.models.Playlist; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import static com.example.spotifyapp.Config.TRACK_URI; import static com.example.spotifyapp.Config.mAccessToken; import static com.example.spotifyapp.Config.mCall; import static com.example.spotifyapp.Config.mOkHttpClient; public class ListPlaylistActivity extends AppCompatActivity { Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_playlist_layout); context = this; ArrayList<Playlist> list = new ArrayList<>(); if (getIntent().hasExtra("playlists")) { try { JSONArray playlists = new JSONArray(getIntent().getStringExtra("playlists")); for (int i = 0; i < playlists.length(); i++) { JSONObject x = playlists.getJSONObject(i); Playlist p = new Playlist(x.getString("name")); p.setUri(x.getString("uri")); p.setId(x.getString("id")); list.add(p); } } catch (JSONException e) { e.printStackTrace(); } } ListView listView = (ListView) findViewById(R.id.playlists); ArrayAdapter<Playlist> listAdapter = new ListPlaylistActivity.PlaylistAdapter(this, R.layout.new_playlist_row, list); listView.setAdapter(listAdapter); } private class PlaylistAdapter extends ArrayAdapter<Playlist> { private ArrayList<Playlist> items; public PlaylistAdapter(Context context, int textViewResourceId, ArrayList<Playlist> items) { super(context, textViewResourceId, items); this.items = items; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.list_playlist_row, null); } Playlist o = items.get(position); if (o != null) { final Button name = (Button) v.findViewById(R.id.playlist_name); name.setText(o.getName()); name.setOnClickListener(v1 -> { try { addTrackToPlaylist(o); } catch (JSONException e) { e.printStackTrace(); } Intent intent = new Intent(context, MainActivity.class); startActivity(intent); }); } return v; } public void addTrackToPlaylist(Playlist p) throws JSONException { URL url = null; try { url = new URL("https://api.spotify.com/v1/playlists/" + p.getId() + "/tracks"); } catch (MalformedURLException e) { e.printStackTrace(); } JSONObject json = new JSONObject(); JSONArray tracks = new JSONArray(); tracks.put(TRACK_URI); json.putOpt("uris", tracks); final Request request = new Request.Builder() .url(url) .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json.toString())) .addHeader("Authorization", "Bearer " + mAccessToken) .build(); // cancelCall(); mCall = mOkHttpClient.newCall(request); mCall.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { } }); Toast.makeText(context, "Track has been added to playlist", Toast.LENGTH_SHORT).show(); } } } <file_sep>/app/src/main/java/com/example/spotifyapp/utlis/GlobalUtils.java package com.example.spotifyapp.utlis; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.example.spotifyapp.PlaylistActivity; import com.example.spotifyapp.PlaylistNewActivity; import com.example.spotifyapp.R; import com.example.spotifyapp.interfaces.DialogCallback; import com.example.spotifyapp.interfaces.FiltrPlaylistCallback; import com.example.spotifyapp.interfaces.NamePlaylistCallback; import com.example.spotifyapp.widgets.CustomDialog; public class GlobalUtils { public static void showDialog(Context context, final DialogCallback dialogCallback){ final CustomDialog dialog = new CustomDialog(context, R.style.CustomDialogTheme); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v =inflater.inflate(R.layout.dialog_layout,null); dialog.setContentView(v); Button btn_done = (Button)dialog.findViewById(R.id.btn_done); btn_done.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(dialogCallback != null) { dialogCallback.callback(0); dialog.dismiss(); } } }); dialog.show(); } public static void showNewPlaylistDialog(Context context, final NamePlaylistCallback dialogCallback){ final CustomDialog dialog = new CustomDialog(context, R.style.CustomDialogTheme); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v =inflater.inflate(R.layout.dialog_new_playlist_layout,null); dialog.setContentView(v); Button btn_done = (Button)dialog.findViewById(R.id.btn_done); btn_done.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(dialogCallback != null) { EditText name = dialog.findViewById(R.id.name_new_playlist); dialogCallback.callbackPlaylist(name.getText().toString()); dialog.dismiss(); } } }); dialog.show(); } public static void showFiltrDialog(Context context, final FiltrPlaylistCallback dialogCallback){ final CustomDialog dialog = new CustomDialog(context, R.style.CustomDialogTheme); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v =inflater.inflate(R.layout.dialog_filtr,null); dialog.setContentView(v); Button btn_name = (Button)dialog.findViewById(R.id.sort_name); Button btn_max = (Button)dialog.findViewById(R.id.sort_size_max); Button btn_min = (Button)dialog.findViewById(R.id.sort_size_min); Button btn_date = (Button)dialog.findViewById(R.id.sort_date); btn_name.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(dialogCallback != null) { dialogCallback.callbackFiltr("name"); dialog.dismiss(); } } }); btn_max.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(dialogCallback != null) { dialogCallback.callbackFiltr("max"); dialog.dismiss(); } } }); btn_min.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(dialogCallback != null) { dialogCallback.callbackFiltr("min"); dialog.dismiss(); } } }); btn_date.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(dialogCallback != null) { dialogCallback.callbackFiltr("date"); dialog.dismiss(); } } }); dialog.show(); } }
940b3c5b48c8c46e8fc30ffc60206f6abb103b6c
[ "Java" ]
5
Java
GalasM/SpotifyApp
2d97363d5869794f04bb5811a1e2662899de7530
b452dbff30e6f1ef0d28aaf9fbb904f3005b6cf6
refs/heads/main
<file_sep>#!/usr/bin/env bash # Bash wrappers for docker run commands dcleanup() { local containers mapfile -t containers < <(docker ps -aq 2>/dev/null) docker rm "${containers[@]}" 2>/dev/null local volumes mapfile -t volumes < <(docker ps --filter status=exited -q 2>/dev/null) docker rm -v "${volumes[@]}" 2>/dev/null local images mapfile -t images < <(docker images --filter dangling=true -q 2>/dev/null) docker rmi "${images[@]}" 2>/dev/null } del_stopped() { local name=$1 local state state=$(docker inspect --format "{{.State.Running}}" "$name" 2>/dev/null) if [[ "$state" == "false" ]]; then docker rm "$name" fi } rmctr() { # shellcheck disable=SC2068 docker rm -f $@ 2>/dev/null || true } relies_on() { for container in "$@"; do local state state=$(docker inspect --format "{{.State.Running}}" "$container" 2>/dev/null) if [[ "$state" == "false" ]] || [[ "$state" == "" ]]; then echo "$container is not running, starting it for you." $container fi done } dps() { docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}\t{{.ID}}' } cadvisor() { docker run -d \ --restart always \ -v /:/rootfs:ro \ -v /var/run:/var/run:rw \ -v /sys:/sys:ro \ -v /var/lib/docker/:/var/lib/docker:ro \ -p 9090:8080 \ --name cadvisor \ google/cadvisor } consul() { del_stopped consul # check if we passed args and if consul is running local state state=$(docker inspect --format "{{.State.Running}}" consul 2>/dev/null) if [[ "$state" == "true" ]] && [[ "$*" != "" ]]; then docker exec -it consul consul "$@" return 0 fi docker run -d \ --restart always \ -p 8500:8500 \ -p 8600:8600/udp \ --name consul \ consul agent -server -ui -node=consul-server -bootstrap-expect=1 -datacenter=acme -client=0.0.0.0 } mongodb() { del_stopped mongodb docker run -d \ --restart always \ -e MONGO_INITDB_ROOT_USERNAME=root \ -e MONGO_INITDB_ROOT_PASSWORD=<PASSWORD> -v $HOME/.mongodb_data:/data/db \ -p 27017:27017 \ mongo } prometheus() { del_stopped prometheus docker volume create prometheus_data docker run -d \ --restart always -v $HOME/.prometheus/prometheus.yml:/etc/prometheus/prometheus.yml \ -v prometheus_data:/prometheus \ -p 9090:9090 \ -config.file=/etc/prometheus/prometheus.yml \ -storage.local.path=/prometheus \ -storage.local.memory-chunks=10000 \ --name prometheus \ prom/prometheus } redis() { del_stopped redis docker volume create redis_data docker run -d \ --restart always \ -v redis_data:/data \ -p 6379:6379 \ --name redis \ redis --save 60 1 --loglevel warning } sourcegraph() { docker run -d \ --restart always \ -v $HOME/.sourcegraph/config:/etc/sourcegraph \ -v $HOME/.sourcegraph/data:/var/opt/sourcegraph \ -p 7080:7080 \ -p 127.0.0.1:3370:3370 \ --name sourcegraph \ --rm \ sourcegraph/server:3.16.0 } <file_sep>[aws] disabled = true [docker_context] only_with_files = true [hostname] format = "on [$homename](bold red)" disabled = false <file_sep>#!/usr/bin/env bash [ -z "$1" ] && echo "Provide your MFA token" && exit 0 OUTPUT="$(aws sts get-session-token --profile play --serial-number arn:aws:iam::528130383285:mfa/[email protected] --duration-seconds 129600 --token-code $1)" OUTPUT_FILE=$HOME'/.aws/credentials' PLAY_FILE=$HOME'/.aws/credentials_play' # echo "$OUTPUT" ACCESS_KEY_ID=$(jq -r '.Credentials.AccessKeyId' <<< $OUTPUT) SECRET_ACCESS_KEY=$(jq -r '.Credentials.SecretAccessKey' <<< $OUTPUT) SESSION_TOKEN=$(jq -r '.Credentials.SessionToken' <<< $OUTPUT) echo "[default]" > $OUTPUT_FILE echo "aws_access_key_id = $ACCESS_KEY_ID" >> $OUTPUT_FILE echo "aws_secret_access_key = $SECRET_ACCESS_KEY" >> $OUTPUT_FILE echo "aws_session_token = $SESSION_TOKEN" >> $OUTPUT_FILE cat $PLAY_FILE >> $OUTPUT_FILE echo "Values set in $OUTPUT_FILE" <file_sep> # dotfiles Setup for [Homebrew](https://brew.sh) and my personal dotfiles. Works on *nix, optimized for macOS. ## About ### Installing ```bash $ make ``` This will create symlinks from this repository to your home directory. ### Customizing Save env vars, etc in a `.extra` file that looks something like this: ``` ### ### Git credentials ### GIT_AUTHOR_NAME="Your Name" GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME" git config --global user.name "$GIT_AUTHOR_NAME" GIT_AUTHOR_EMAIL="<EMAIL>" GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL" git config --global user.email "$GIT_AUTHOR_EMAIL" GH_USER="nickname" git config --global github.user "$GH_USER" ``` <file_sep>tap "buo/cask-upgrade" tap "homebrew/bundle" tap "homebrew/cask" tap "homebrew/cask-fonts" tap "homebrew/core" cask_args appdir: "/Applications" brew "ag" brew "awscli" brew "bash" brew "bash-completion@2" brew "bat" brew "bufbuild/buf/buf" brew "curl" brew "dust" brew "exa" brew "fd" brew "fzf" brew "git" brew "git-delta" brew "git-lfs" brew "go" brew "gping" brew "graphviz" brew "htop" brew "ipcalc" brew "jq" brew "lnav" brew "make" brew "micro" brew "node" brew "openssh" brew "[email protected]" brew "procs" brew "protobuf" brew "ripgrep" brew "ruby" brew "sd" brew "tree" brew "tldr" brew "vim" brew "xh" cask "appcleaner" cask "docker" cask "font-fira-code" cask "font-jetbrains-mono" cask "font-open-sans" cask "font-source-code-pro" cask "fork" cask "google-chrome" cask "google-drive" cask "iterm2" cask "keka" cask "mpv" cask "mysqlworkbench" cask "obsidian" cask "pdf-expert" cask "postman" cask "pycharm-ce" cask "qlmarkdown" cask "quicklook-json" cask "raycast" cask "rider" cask "shottr" cask "slack" cask "tomighty" cask "visual-studio-code" cask "zoom" <file_sep>#!/usr/bin/env bash # If not running interactively, don't do anything case $- in *i*) ;; *) return ;; esac for file in ~/.{aliases,dockerfuncs,exports,extra,functions,path}; do if [[ -r "$file" ]] && [[ -f "$file" ]]; then # shellcheck source=/dev/null source "$file" fi done unset file # open file limits ulimit -n 5000 # check the window size after each command and, if necessary, # update the values of LINES and COLUMNS. shopt -s checkwinsize # Case-insensitive globbing (used in pathname expansion) shopt -s nocaseglob # Append to the Bash history file, rather than overwriting it shopt -s histappend # Autocorrect typos in path names when using `cd` shopt -s cdspell # Enable some Bash 4 features when possible: # * `autocd`, e.g. `**/qux` will enter `./foo/bar/baz/qux` # * Recursive globbing, e.g. `echo **/*.txt` for option in autocd globstar; do shopt -s "$option" 2>/dev/null done # Add tab completion for many Bash commands if which brew &>/dev/null && [ -r "$(brew --prefix)/etc/profile.d/bash_completion.sh" ]; then # Ensure existing Homebrew v1 completions continue to work export BASH_COMPLETION_COMPAT_DIR="$(brew --prefix)/etc/bash_completion.d" source "$(brew --prefix)/etc/profile.d/bash_completion.sh" elif [ -f /etc/bash_completion ]; then source /etc/bash_completion fi eval "$(starship init bash)" <file_sep>#!/usr/bin/env bash # Load .bashrc, which loads: ~/.{aliases,dockerfuncs,exports,extra,functions,path} if [[ -r "${HOME}/.bashrc" ]]; then # shellcheck source=/dev/null source "${HOME}/.bashrc" fi
f8ad0615a7133b53ccc9f358a1b34ffbb5d23772
[ "TOML", "Ruby", "Markdown", "Shell" ]
7
Shell
djamseed-khodabocus-cko/dotfiles
bcb2f441eaf9346a63ac9fa295ecdeef1156263b
f0de29cf4aa2e93b084f05d3842ad3aeec248d8a
refs/heads/master
<repo_name>Alihdnz/Exercicios-de-python<file_sep>/Exercicio41.py #A confederação nacional de natação precisa de um programa que leia # o ano de nascimento de um atleta e mostre sua categoria, de # acordo com a idade: # # - Até 9 anos: MIRIM # - Até 14 anos: INFANTIL # - Até 19 anos: JUNIOR # - Até 20 anos: SÊNIOR # - Acima: MASTER# nasc = int(input('Ano de nascimento: ')) atual = 2020 idade = 2020 - nasc if idade <= 9: print("O atleta tem {} anos, e esta na categoria MIRIM".format(idade)) elif idade > 9 and idade <= 14: print("o atleta tem {} anos, e esta na categoria INFANTIL".format(idade)) elif idade > 14 and idade <= 19: print('o atleta tem {} anos, e esta na categoria JUNIOR'.format(idade)) elif idade == 20: print('o atleta tem {} anos, e esta na categoria SÊNIOR'.format(idade)) else: print('o atleta tem {} anos, e esta na categoria MASTER'.format(idade))<file_sep>/Exercicio36.py #Desafio 36, programa para aprovar um empréstimo bancario para a compra de uma casa. #o programa vai perguntar o valor da casa, o salario do comprador e em quantos anos ela #vai pagar. #Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário ou #então o emprestimo sera negado. casa = float(input('Valor da casa: R$')) salário = float(input('Salario do comprador: R$')) anos = int(input('Quantos anos de financiamento? ')) prestação = casa / (anos * 12) mínimo = salário * 30 / 100 print('Para pagar um acasa de R${:.2f} em {} anos' .format(casa, anos), end='') print(', a prestação será de R${:.2f}'.format(prestação)) ##print('COMPARANDO tem que pagar {:.2f} e o minimo é de {}'.format(prestação, mínimo)) if prestação <= mínimo: print('Empréstimo aprovado') else: print('Empréstimo recusado') <file_sep>/Exercicio40.py #Crie um programa que leia duas notas de um aluno e # calcule sua média, mostrando uma mensagem no final, de # acordo com a média atingida: # # - Média abaixo de 5,0: REPROVADO # - Média entre 5,0 e 6,9: RECUPERAÇÃO # - Méda 7,0 ou superior: APROVADO# nota1 = float(input('primeira nota: ')) nota2 = float(input('segunda nota: ')) media = (nota1 + nota2) / 2 print('A primeira nota foi {:.2f} e a segunda nota foi {:.2f}, então a media foi {:.1f}'.format(nota1, nota2, media)) if media >= 5 and media < 7: print('RECUPERAÇÃO') elif media < 5: print('REPROVADO') elif media >= 7: print('APROVADO')<file_sep>/Exercicio39.py #Faça um programa que leia o ano de nascimento de um jovem e informe # de acordo com sua idade: # # - se ele ainda vai se alistar ao serviço militar # - se ja é hora de se alista. # - se ja passou do tempo de alistamento # # seu programa também devera mostra o tempo que falta que # passou do prazo # nasc = int(input('Ano de nascimento: ')) atual = 2020 alistamento = nasc + 18 if 2020 - nasc == 18: print('Você deve se alistar imediatamente!') elif 2020 - nasc > 18: print('Você deveria ter se alistado em {}'.format(alistamento)) elif 2020 - nasc < 18: print('Você deve se alistar somente em {}'.format(alistamento)) <file_sep>/Exercicio45.py #Crie um programa que faça o computador jogar Jokenpô com voce.# from random import randint from time import sleep itens = ('pedra', 'papel', 'tesoura') computador = randint(0, 2) jogador = int(input('''Suas opções: [0] PEDRA [1] PAPEL [2] TESOURA Qual é a sua jogada? ''')) print('JO') sleep(1) print('KEN') sleep(1) print('PO!!') sleep(1) print('Computador jogou {}'.format(itens[computador])) print('jogador jogou {}'.format(itens[jogador])) if jogador == computador: print('EMPATE') elif jogador == 0 and computador == 1 or jogador == 1 and computador == 2 or jogador == 2 and computador == 0: print('VOCÊ PERDEU') else: print('VOCÊ VENCEU')<file_sep>/Exercicio44.py #Elabore um programa que calcule o valor a ser pago por # um produto, considerando o seu preço normal e condição de # pagamento: # # -à vista dinheiro/cheque: 10% de desconto # -à vista no cartão: 5% de desconto # -em até 2x no cartão: preço normal # -3x ou mais no cartão: 20% de juros# produto = float(input('Valor do produto: ')) dinheiro = produto * 10 / 100 cartao1x = produto * 5 / 100 cartao3x= produto * 20 / 100 opc1 = produto - dinheiro opc2 = produto - cartao1x opc3 = produto / 2 opc4 = (produto + cartao3x) / 3 pgt = float(input('''Informe o metodo de pagamento: [1] à vista dinheiro/cheque: 10% de desconto [2] à vista no cartão: 5% de desconto [3] em até 2x no cartão: preço normal [4] 3x ou mais no cartão: 20% de juros ''')) if pgt == 1: print('O valor a ser pago à vista no dinheiro ou cheque é de R${:.2f}'.format(opc1)) elif pgt == 2: print('O valor a ser pago à vista no cartão é de R${:.2f}'.format(opc2)) elif pgt == 3: print('Em duas parcelas de R${:.2f}, sem juros, o valor total a ser pago pelo produto é de {:.2f}'.format(opc3, produto)) elif pgt == 4: total = produto + cartao3x print('Em três parcelas de R${:.2f}, com 30% de juros, o valor total a ser pago pelo produto é de {:.2f}'.format(opc4, total)) else: print('Opção invalida.')<file_sep>/Exercicio37.py #escreva um programa que leia um numero inteiro qualquer #e peça para o usuárui escolhar qual será a base de conversão: # - 1 para binario # - 2 para octal # - 3 para hexadecimal num = int(input('digite um numero inteiro: ')) print('''Escolha uma das bases para conversão: [1] Converter para binario [2] Converter para octal [3] Converter para hexadecima''') opção = int(input('Sua opção: ')) if opção == 1: print('{} convertido para BINARIO é igual a {}'.format(num, bin(num)[2:])) elif opção == 2: print('{} convertido para OCTAL é igual a {}'.format(num, oct(num)[2:])) elif opção == 3: print('{} convertido para HEXADECIMAL é igual a {}'.format(num, hex(num)[2:])) else: print('Opção invalida. Tente novamente.')
c1e09507adf3aa150eb76a58bd5a8b6cfb026ddd
[ "Python" ]
7
Python
Alihdnz/Exercicios-de-python
95086404bd1414cd4062bd9445bc7bbdb9942f0f
a8173974d54c10ad7f98d3cdc470fa4a66f36da8
refs/heads/main
<file_sep>remove(list=ls()) setwd("~/Desktop/incoming_projects/mating_system/simulation/selfing_sim/processed_data_offspring_dispersal/") library(dplyr) library(ggplot2) library(scales) #================== Viability selection ================== # Start in good patch df <-read.table(file = './good_via_offspring.out',header = FALSE, stringsAsFactors = FALSE) colnames(df) <- c("V1_AA","V1_Aa","V1_aa","V2_AA","V2_Aa","V2_aa", "WF1_AA","WF1_Aa","WF1_aa","WF2_AA","WF2_Aa","WF2_aa", "WM1_AA","WM1_Aa","WM1_aa","WM2_AA","WM2_Aa","WM2_aa", "wF1_A","wF1_a","wM1_A","wM1_a", "wF2_A","wF2_a","wM2_A","wM2_a", "mP1","mP2","mS1","mS2","sigma", "N1","N2","mu1","mu2","run_nb","rndSeed", "P_est","P_time") df <- df %>% select(V1_AA,V1_Aa,V1_aa,V2_AA,V2_Aa,V2_aa,sigma,mP1,mP2,mS1,mS2,P_est) %>% na.omit codom_vector <- c(1.01, 1.005, 1, 0.99, 0.995, 1) dom_vector <- c(1.01, 1.0075, 1, 0.99, 0.9925, 1) rec_vector <- c(1.01, 1.0025, 1, 0.99, 0.9975, 1) asym_sel <- c(1.0125, 1.01, 1, 0.99, 0.995, 1) df_codom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==codom_vector))),] df_dom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==dom_vector))),] df_rec <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==rec_vector))),] df_asym_sel <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==asym_sel))),] df_asym_mig <- df_codom[df_codom$mS2!=df_codom$mS1,] df_codom <- df_codom[df_codom$mS2==df_codom$mS1,] df_codom_plot <- df_codom %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_codom_plot, './good_via_codom_processed.csv', row.names = FALSE) ggplot(df_codom_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_dom_plot <- df_dom %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_dom_plot, './good_via_dom_processed.csv', row.names = FALSE) ggplot(df_dom_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_rec_plot <- df_rec %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_rec_plot, './good_via_rec_processed.csv', row.names = FALSE) ggplot(df_rec_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_sel_plot <- df_asym_sel %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_sel_plot, './good_via_asym_sel_processed.csv', row.names = FALSE) ggplot(df_asym_sel_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_mig_plot <- df_asym_mig %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_mig_plot, './good_via_asym_mig_processed.csv', row.names = FALSE) ggplot(df_asym_mig_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() # Start in bad patch df <-read.table(file = './bad_via_offspring.out',header = FALSE, stringsAsFactors = FALSE) colnames(df) <- c("V1_AA","V1_Aa","V1_aa","V2_AA","V2_Aa","V2_aa", "WF1_AA","WF1_Aa","WF1_aa","WF2_AA","WF2_Aa","WF2_aa", "WM1_AA","WM1_Aa","WM1_aa","WM2_AA","WM2_Aa","WM2_aa", "wF1_A","wF1_a","wM1_A","wM1_a", "wF2_A","wF2_a","wM2_A","wM2_a", "mP1","mP2","mS1","mS2","sigma", "N1","N2","mu1","mu2","run_nb","rndSeed", "P_est","P_time") df <- df %>% select(V1_AA,V1_Aa,V1_aa,V2_AA,V2_Aa,V2_aa,sigma,mP1,mP2,mS1,mS2,P_est) %>% na.omit codom_vector <- c(1.01, 1.005, 1, 0.99, 0.995, 1) dom_vector <- c(1.01, 1.0075, 1, 0.99, 0.9925, 1) rec_vector <- c(1.01, 1.0025, 1, 0.99, 0.9975, 1) asym_sel <- c(1.0125, 1.01, 1, 0.99, 0.995, 1) df_codom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==codom_vector))),] df_dom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==dom_vector))),] df_rec <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==rec_vector))),] df_asym_sel <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==asym_sel))),] df_asym_mig <- df_codom[df_codom$mS1!=df_codom$mS2,] df_codom <- df_codom[df_codom$mS1==df_codom$mS2,] df_codom_plot <- df_codom %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_codom_plot, './bad_via_codom_processed.csv', row.names = FALSE) ggplot(df_codom_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_dom_plot <- df_dom %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_dom_plot, './bad_via_dom_processed.csv', row.names = FALSE) ggplot(df_dom_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_rec_plot <- df_rec %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_rec_plot, './bad_via_rec_processed.csv', row.names = FALSE) ggplot(df_rec_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_sel_plot <- df_asym_sel %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_sel_plot, './bad_via_asym_sel_processed.csv', row.names = FALSE) ggplot(df_asym_sel_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_mig_plot <- df_asym_mig %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_mig_plot, './bad_via_asym_mig_processed.csv', row.names = FALSE) ggplot(df_asym_mig_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() #================== Female fitness component selection ================== # Start in good patch df <-read.table(file = './good_female_offspring.out',header = FALSE, stringsAsFactors = FALSE) colnames(df) <- c("V1_AA","V1_Aa","V1_aa","V2_AA","V2_Aa","V2_aa", "WF1_AA","WF1_Aa","WF1_aa","WF2_AA","WF2_Aa","WF2_aa", "WM1_AA","WM1_Aa","WM1_aa","WM2_AA","WM2_Aa","WM2_aa", "wF1_A","wF1_a","wM1_A","wM1_a", "wF2_A","wF2_a","wM2_A","wM2_a", "mP1","mP2","mS1","mS2","sigma", "N1","N2","mu1","mu2","run_nb","rndSeed", "P_est","P_time") df <- df %>% select(WF1_AA,WF1_Aa,WF1_aa,WF2_AA,WF2_Aa,WF2_aa,sigma,mP1,mP2,mS1,mS2,P_est) %>% na.omit codom_vector <- c(1.01, 1.005, 1, 0.99, 0.995, 1) dom_vector <- c(1.01, 1.0075, 1, 0.99, 0.9925, 1) rec_vector <- c(1.01, 1.0025, 1, 0.99, 0.9975, 1) asym_sel <- c(1.0125, 1.01, 1, 0.99, 0.995, 1) df_codom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==codom_vector))),] df_dom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==dom_vector))),] df_rec <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==rec_vector))),] df_asym_sel <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==asym_sel))),] df_asym_mig <- df_codom[df_codom$mS2!=df_codom$mS1,] df_codom <- df_codom[df_codom$mS2==df_codom$mS1,] df_codom_plot <- df_codom %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_codom_plot, './good_female_codom_processed.csv', row.names = FALSE) ggplot(df_codom_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_dom_plot <- df_dom %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_dom_plot, './good_female_dom_processed.csv', row.names = FALSE) ggplot(df_dom_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_rec_plot <- df_rec %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_rec_plot, './good_female_rec_processed.csv', row.names = FALSE) ggplot(df_rec_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_sel_plot <- df_asym_sel %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_sel_plot, './good_female_asym_sel_processed.csv', row.names = FALSE) ggplot(df_asym_sel_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_mig_plot <- df_asym_mig %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_mig_plot, './good_female_asym_mig_processed.csv', row.names = FALSE) ggplot(df_asym_mig_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() # Start in bad patch df <-read.table(file = './bad_female_offspring.out',header = FALSE, stringsAsFactors = FALSE) colnames(df) <- c("V1_AA","V1_Aa","V1_aa","V2_AA","V2_Aa","V2_aa", "WF1_AA","WF1_Aa","WF1_aa","WF2_AA","WF2_Aa","WF2_aa", "WM1_AA","WM1_Aa","WM1_aa","WM2_AA","WM2_Aa","WM2_aa", "wF1_A","wF1_a","wM1_A","wM1_a", "wF2_A","wF2_a","wM2_A","wM2_a", "mP1","mP2","mS1","mS2","sigma", "N1","N2","mu1","mu2","run_nb","rndSeed", "P_est","P_time") df <- df %>% select(WF1_AA,WF1_Aa,WF1_aa,WF2_AA,WF2_Aa,WF2_aa,sigma,mP1,mP2,mS1,mS2,P_est) %>% na.omit codom_vector <- c(1.01, 1.005, 1, 0.99, 0.995, 1) dom_vector <- c(1.01, 1.0075, 1, 0.99, 0.9925, 1) rec_vector <- c(1.01, 1.0025, 1, 0.99, 0.9975, 1) asym_sel <- c(1.0125, 1.01, 1, 0.99, 0.995, 1) df_codom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==codom_vector))),] df_dom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==dom_vector))),] df_rec <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==rec_vector))),] df_asym_sel <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==asym_sel))),] df_asym_mig <- df_codom[df_codom$mS2!=df_codom$mS1,] df_codom <- df_codom[df_codom$mS2==df_codom$mS1,] df_codom_plot <- df_codom %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_codom_plot, './bad_female_codom_processed.csv', row.names = FALSE) ggplot(df_codom_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_dom_plot <- df_dom %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_dom_plot, './bad_female_dom_processed.csv', row.names = FALSE) ggplot(df_dom_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_rec_plot <- df_rec %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_rec_plot, './bad_female_rec_processed.csv', row.names = FALSE) ggplot(df_rec_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_sel_plot <- df_asym_sel %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_sel_plot, './bad_female_asym_sel_processed.csv', row.names = FALSE) ggplot(df_asym_sel_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_mig_plot <- df_asym_mig %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_mig_plot, './bad_female_asym_mig_processed.csv', row.names = FALSE) ggplot(df_asym_mig_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() #================== Male fitness component selection ================== # Start in good patch df <-read.table(file = './good_male_offspring.out',header = FALSE, stringsAsFactors = FALSE) colnames(df) <- c("V1_AA","V1_Aa","V1_aa","V2_AA","V2_Aa","V2_aa", "WF1_AA","WF1_Aa","WF1_aa","WF2_AA","WF2_Aa","WF2_aa", "WM1_AA","WM1_Aa","WM1_aa","WM2_AA","WM2_Aa","WM2_aa", "wF1_A","wF1_a","wM1_A","wM1_a", "wF2_A","wF2_a","wM2_A","wM2_a", "mP1","mP2","mS1","mS2","sigma", "N1","N2","mu1","mu2","run_nb","rndSeed", "P_est","P_time") df <- df %>% select(WM1_AA,WM1_Aa,WM1_aa,WM2_AA,WM2_Aa,WM2_aa,sigma,mP1,mP2,mS1,mS2,P_est) %>% na.omit codom_vector <- c(1.01, 1.005, 1, 0.99, 0.995, 1) dom_vector <- c(1.01, 1.0075, 1, 0.99, 0.9925, 1) rec_vector <- c(1.01, 1.0025, 1, 0.99, 0.9975, 1) asym_sel <- c(1.0125, 1.01, 1, 0.99, 0.995, 1) df_codom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==codom_vector))),] df_dom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==dom_vector))),] df_rec <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==rec_vector))),] df_asym_sel <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==asym_sel))),] df_asym_mig <- df_codom[df_codom$mS2!=df_codom$mS1,] df_codom <- df_codom[df_codom$mS2==df_codom$mS1,] df_codom_plot <- df_codom %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_codom_plot, './good_male_codom_processed.csv', row.names = FALSE) ggplot(df_codom_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_dom_plot <- df_dom %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_dom_plot, './good_male_dom_processed.csv', row.names = FALSE) ggplot(df_dom_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_rec_plot <- df_rec %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_rec_plot, './good_male_rec_processed.csv', row.names = FALSE) ggplot(df_rec_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_sel_plot <- df_asym_sel %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_sel_plot, './good_male_asym_sel_processed.csv', row.names = FALSE) ggplot(df_asym_sel_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_mig_plot <- df_asym_mig %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_mig_plot, './good_male_asym_mig_processed.csv', row.names = FALSE) ggplot(df_asym_mig_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() # Start in bad patch df <-read.table(file = './bad_male_offspring.out',header = FALSE, stringsAsFactors = FALSE) colnames(df) <- c("V1_AA","V1_Aa","V1_aa","V2_AA","V2_Aa","V2_aa", "WF1_AA","WF1_Aa","WF1_aa","WF2_AA","WF2_Aa","WF2_aa", "WM1_AA","WM1_Aa","WM1_aa","WM2_AA","WM2_Aa","WM2_aa", "wF1_A","wF1_a","wM1_A","wM1_a", "wF2_A","wF2_a","wM2_A","wM2_a", "mP1","mP2","mS1","mS2","sigma", "N1","N2","mu1","mu2","run_nb","rndSeed", "P_est","P_time") df <- df %>% select(WM1_AA,WM1_Aa,WM1_aa,WM2_AA,WM2_Aa,WM2_aa,sigma,mP1,mP2,mS1,mS2,P_est) %>% na.omit codom_vector <- c(1.01, 1.005, 1, 0.99, 0.995, 1) dom_vector <- c(1.01, 1.0075, 1, 0.99, 0.9925, 1) rec_vector <- c(1.01, 1.0025, 1, 0.99, 0.9975, 1) asym_sel <- c(1.0125, 1.01, 1, 0.99, 0.995, 1) df_codom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==codom_vector))),] df_dom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==dom_vector))),] df_rec <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==rec_vector))),] df_asym_sel <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==asym_sel))),] df_asym_mig <- df_codom[df_codom$mS2!=df_codom$mS1,] df_codom <- df_codom[df_codom$mS2==df_codom$mS1,] df_codom_plot <- df_codom %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_codom_plot, './bad_male_codom_processed.csv', row.names = FALSE) ggplot(df_codom_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_dom_plot <- df_dom %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_dom_plot, './bad_male_dom_processed.csv', row.names = FALSE) ggplot(df_dom_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_rec_plot <- df_rec %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_rec_plot, './bad_male_rec_processed.csv', row.names = FALSE) ggplot(df_rec_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_sel_plot <- df_asym_sel %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_sel_plot, './bad_male_asym_sel_processed.csv', row.names = FALSE) ggplot(df_asym_sel_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_mig_plot <- df_asym_mig %>% group_by(sigma,mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_mig_plot, './bad_male_asym_mig_processed.csv', row.names = FALSE) ggplot(df_asym_mig_plot, aes(x=mS1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() <file_sep>#!/bin/bash # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++++++++ Comments +++++++++++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Usage: selfing_sim [w1AA][w1Aa][w1aa][w2AA][w2Aa][w2aa][m12pollen][m21pollen][m12seed][m21seed][sigma][patch1_size][patch2_size][mut_init1][mut_init2][run_nb][rand_seed] # # When running on personal computer, add gsl to PATH: LD_LIBRARY_PATH=/home/bogi/gsl/lib export LD_LIBRARY_PATH # If running on cluster, don't forget to load gsl module #module load gsl/2.4 # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++ The overall philosophy +++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # 1. Generate as many PRN as there are simulation runs; Use device files as PRNG # 2. Execute simulations via 'parallel' and pipe all PRNs; This yields data for one set of parameters (e.g., migration rate) # 3. Set new input parameters and goto step 1 generate_rnd() { >$rnd_src for ((k = 1 ; k <= sim_runs ; k++)) do cat /dev/urandom | od -vAn -N4 -tu4 >> $rnd_src done } # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++++++++ Parameters +++++++++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ sim_runs=1000 # For each combination of parameters, run 1000 simulations # Output is grouped by the patch where mutant was injected (good vs. bad), and selection mode (viability, female fecundity, and male fecundity, respectively) # We will process the raw output using 'compare_simulations.R' and finally plot it from Mathematica notebook good_start_via="./good_via_F.out" bad_start_via="./bad_via_F.out" rnd_src="rand_seed.out" >$rnd_src seed_pars=( 0.000 0.001 0.005 0.01 0.025 ) # Seed migration rates selfing_pars=( 0.00 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.00 ) dom_pars=( 0.20 0.40 0.60 0.80 ) wAA1=1.01 wAA2=0.99 waa=1 s=0.01 # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++++++++ Bulk run +++++++++++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Selection on viability >$good_start_via >$bad_start_via for i in "${selfing_pars[@]}" do for j in "${seed_pars[@]}" do for k in "${dom_pars[@]}" do wAa1=$(echo "1+$k*$s" | bc -l) wAa2=$(echo "1-$k*$s" | bc -l) generate_rnd cat $rnd_src | parallel "./selfing_sim $wAA1 $wAa1 $waa $wAA2 $wAa2 $waa 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 1 0 10000 {}" >> $good_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim $wAA1 $wAa1 $waa $wAA2 $wAa2 $waa 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 0 1 10000 {}" >> $bad_start_via done done done <file_sep>#include <stdio.h> #include <stdlib.h> #include <iostream> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <time.h> #include <string.h> #include <math.h> #include <stdbool.h> #define patch_nb 2 #define genotype_nb 3 int main(int argc, char *argv[]) { (void)argc; unsigned int i, j, k, u; unsigned int patch_size[patch_nb]; double mean_w; double gtype_freq[patch_nb][genotype_nb], offspring_self[genotype_nb], offspring_outcross[genotype_nb]; double w[patch_nb][genotype_nb], w_gphyte_female[patch_nb][genotype_nb], w_gphyte_male[patch_nb][genotype_nb]; double wA_gamete_female[patch_nb], wa_gamete_female[patch_nb], wA_gamete_male[patch_nb], wa_gamete_male[patch_nb]; double w_gphyte_female_mean[patch_nb], w_gphyte_male_mean[patch_nb], w_female_mean[patch_nb], w_male_mean[patch_nb]; double allele_freq_female_gamete[patch_nb], allele_freq_male_gamete[patch_nb]; double gametophyte_female[patch_nb], gametophyte_male[patch_nb]; double transit_frame[patch_nb][genotype_nb]; unsigned int offspring_full[genotype_nb]; double w_A_F_, w_a_F_, w_AA_F_, w_Aa_F_; double w_A_m_, w_a_m_; double sigma; double mig_rate_pollen[patch_nb], mig_rate_seed[patch_nb]; double allele_frame[patch_nb]; // define forward and backward migration rates double invader_nb; int mutant_init[2]; bool exit_; double invasion_thresh; unsigned int invasion_count=0; unsigned int time_threshold=10000; unsigned int run_nb; // Reading variables sscanf (argv[1], "%lf", &w[0][0]); sscanf (argv[2], "%lf", &w[0][1]); sscanf (argv[3], "%lf", &w[0][2]); sscanf (argv[4], "%lf", &w[1][0]); sscanf (argv[5], "%lf", &w[1][1]); sscanf (argv[6], "%lf", &w[1][2]); sscanf (argv[7], "%lf", &w_gphyte_female[0][0]); sscanf (argv[8], "%lf", &w_gphyte_female[0][1]); sscanf (argv[9], "%lf", &w_gphyte_female[0][2]); sscanf (argv[10], "%lf", &w_gphyte_female[1][0]); sscanf (argv[11], "%lf", &w_gphyte_female[1][1]); sscanf (argv[12], "%lf", &w_gphyte_female[1][2]); sscanf (argv[13], "%lf", &w_gphyte_male[0][0]); sscanf (argv[14], "%lf", &w_gphyte_male[0][1]); sscanf (argv[15], "%lf", &w_gphyte_male[0][2]); sscanf (argv[16], "%lf", &w_gphyte_male[1][0]); sscanf (argv[17], "%lf", &w_gphyte_male[1][1]); sscanf (argv[18], "%lf", &w_gphyte_male[1][2]); sscanf (argv[19], "%lf", &wA_gamete_female[0]); sscanf (argv[20], "%lf", &wa_gamete_female[0]); sscanf (argv[21], "%lf", &wA_gamete_female[1]); sscanf (argv[22], "%lf", &wa_gamete_female[1]); sscanf (argv[23], "%lf", &wA_gamete_male[0]); sscanf (argv[24], "%lf", &wa_gamete_male[0]); sscanf (argv[25], "%lf", &wA_gamete_male[1]); sscanf (argv[26], "%lf", &wa_gamete_male[1]); sscanf (argv[27], "%lf", &mig_rate_pollen[0]); sscanf (argv[28], "%lf", &mig_rate_pollen[1]); sscanf (argv[29], "%lf", &mig_rate_seed[0]); sscanf (argv[30], "%lf", &mig_rate_seed[1]); sscanf (argv[31], "%lf", &sigma); sscanf (argv[32], "%u", &patch_size[0]); sscanf (argv[33], "%u", &patch_size[1]); sscanf (argv[34], "%u", &mutant_init[0]); sscanf (argv[35], "%u", &mutant_init[1]); sscanf (argv[36], "%u", &run_nb); invasion_thresh=1000; /* Seed the random number generator */ gsl_rng *gBaseRand; int randSeed=10000; gBaseRand=gsl_rng_alloc(gsl_rng_mt19937); sscanf (argv[37], "%u", &randSeed); gsl_rng_set(gBaseRand,randSeed); unsigned int time_invasion=0; // Each iteration through the loop is a single simulation run for (u=0; u<run_nb; u++) { // Seed the population with number of mutants specified in input (i.e., mutant_init[patch]) // We are tracking genotype frequencies, so convert mutant numbers to frequencies gtype_freq[0][0]=0; gtype_freq[0][1]=(double)mutant_init[0]/(double)patch_size[0]; gtype_freq[0][2]=1-gtype_freq[0][1]; gtype_freq[1][0]=0; gtype_freq[1][1]=(double)mutant_init[1]/(double)patch_size[1]; gtype_freq[1][2]=1-gtype_freq[1][1]; exit_=false; unsigned int t=0; // Set elements of array holding offspring numbers to zero for (i=0;i<genotype_nb;i++) { offspring_self[i]=0; offspring_outcross[i]=0; } while (exit_==false) { /* ================================== Gamete production dispersal ================================== */ for (i = 0; i < patch_nb; i++) { // ***** Stage 1: Differential production of gametophytes by adults ***** // Calculate the mean gametophyte fitness, male and female w_male_mean[i] = (gtype_freq[i][0] * w_gphyte_male[i][0]) + (gtype_freq[i][1] * w_gphyte_male[i][1]) + (gtype_freq[i][2] * w_gphyte_male[i][2]); w_female_mean[i] = (gtype_freq[i][0] * w_gphyte_female[i][0]) + (gtype_freq[i][1] * w_gphyte_female[i][1]) + (gtype_freq[i][2] * w_gphyte_female[i][2]); // Frequency of A after gametophytic selection gametophyte_male[i] = (gtype_freq[i][0] * w_gphyte_male[i][0] + (gtype_freq[i][1] * w_gphyte_male[i][1])/2) / w_male_mean[i]; gametophyte_female[i] = (gtype_freq[i][0] * w_gphyte_female[i][0] + (gtype_freq[i][1] * w_gphyte_female[i][1])/2) / w_female_mean[i]; // ***** Stage 2: Differential production of gametes by gametophytes ***** // Calculate the mean gamete fitness, male and female w_gphyte_male_mean[i] = gametophyte_male[i] * wA_gamete_male[i] + (1-gametophyte_male[i]) * wa_gamete_male[i]; w_gphyte_female_mean[i] = gametophyte_female[i] * wA_gamete_female[i] + (1-gametophyte_female[i]) * wa_gamete_female[i]; // Frequency of A after gametic selection allele_freq_male_gamete[i] = gametophyte_male[i] * (wA_gamete_male[i])/(w_gphyte_male_mean[i]); allele_freq_female_gamete[i] = gametophyte_female[i] * (wA_gamete_female[i])/(w_gphyte_female_mean[i]); } // ***** Stage 3: Male gamete dispersal ***** // New patch i freq of A = fraction mig. j-->i + fraction stay in ith patch allele_frame[0] = (mig_rate_pollen[0] * allele_freq_male_gamete[1]) + ((1 - mig_rate_pollen[0]) * allele_freq_male_gamete[0]); allele_frame[1] = (mig_rate_pollen[1] * allele_freq_male_gamete[0]) + ((1 - mig_rate_pollen[1]) * allele_freq_male_gamete[1]); // update allele frequencies allele_freq_male_gamete[0]=allele_frame[0]; allele_freq_male_gamete[1]=allele_frame[1]; /* ================================== Reproduction ================================== */ // ***** Stage 4: Mating, (1-S) fraction of the population outcrosses and S fraction is selfing ***** for (i = 0; i < patch_nb; i++) { // Calculate the contribution parameters w_A_F_ = (wA_gamete_female[i])/(w_gphyte_female_mean[i]); w_a_F_ = (wa_gamete_female[i])/(w_gphyte_female_mean[i]); w_A_m_ = wA_gamete_male[i]/(wA_gamete_male[i] + wa_gamete_male[i]); w_a_m_ = wa_gamete_male[i]/(wA_gamete_male[i] + wa_gamete_male[i]); w_AA_F_ = (w_gphyte_female[i][0])/(w_female_mean[i]); w_Aa_F_ = (w_gphyte_female[i][1])/(w_female_mean[i]); offspring_self[0] = w_A_F_ * ( gtype_freq[i][0] * w_AA_F_ + w_Aa_F_ * w_A_m_ * gtype_freq[i][1]/2.0 ); offspring_self[1] = gtype_freq[i][1]/2.0 * w_Aa_F_ * ( w_A_F_ * w_a_m_ + w_a_F_ * w_A_m_ ); offspring_self[2] = 1 - offspring_self[0] - offspring_self[1]; offspring_outcross[0] = (allele_freq_male_gamete[i]*allele_freq_female_gamete[i]); offspring_outcross[1] = (allele_freq_male_gamete[i]*(1-allele_freq_female_gamete[i])+allele_freq_female_gamete[i]*(1-allele_freq_male_gamete[i])); offspring_outcross[2] = ((1-allele_freq_male_gamete[i])*(1-allele_freq_female_gamete[i])); for (k=0; k < genotype_nb; k++) gtype_freq[i][k] =(1-sigma)*offspring_outcross[k] + sigma*offspring_self[k]; gsl_ran_multinomial(gBaseRand, genotype_nb, patch_size[i], (const double*)gtype_freq[i], offspring_full); for (k=0; k < genotype_nb; k++) gtype_freq[i][k] = (double)offspring_full[k]/(double)patch_size[i]; } /* ================================== Offspring dispersal ================================== */ // ***** Stage 5: Formed offspring disperses ***** for (j = 0; j < genotype_nb; j++) { // new patch 0 = fraction mig. from patch 1 + fraction stay in patch 0 transit_frame[0][j] = (mig_rate_seed[0] * gtype_freq[1][j] + (1 - mig_rate_seed[0]) * gtype_freq[0][j]); // new patch 1 = fraction mig. from patch 0 + fraction stay in patch 1 transit_frame[1][j] = (mig_rate_seed[1] * gtype_freq[0][j] + (1 - mig_rate_seed[1]) * gtype_freq[1][j]); } for (i=0;i<patch_nb;i++) { for (j=0;j<genotype_nb;j++) gtype_freq[i][j]=transit_frame[i][j]; } /* ================================== Survival ================================== */ // ***** Stage 6: Differential survival of offspring to adulthood ***** for (i=0; i<patch_nb; i++) { mean_w = w[i][0]*gtype_freq[i][0]+w[i][1]*gtype_freq[i][1]+w[i][2]*gtype_freq[i][2]; // w_bar = fAA*WAA + fAa*WAa + faa*Waa for (j=0; j<genotype_nb; j++) gtype_freq[i][j]=(w[i][j]*gtype_freq[i][j])/(mean_w); // survival_prob(..)=f..*(W../w_bar) } /* ================================== Extinction/Fixation conditions ============ */ // if mutant number in the good patch exceeds 1/s, count as successful invasion // run the simulation until allele fixes or goes extinct --> record sojourn time invader_nb = patch_size[0]*(2*gtype_freq[0][0] + (gtype_freq[0][1])); if (((gtype_freq[0][0] + gtype_freq[0][1]/2.0)+(gtype_freq[1][0] + gtype_freq[1][1]/2.0)==0) || (t>time_threshold)) { exit_=true; } else { if ( invader_nb>invasion_thresh ) { exit_=true; time_invasion += t; invasion_count++; } } t++; } } // Print: input pars, invasion probability, mean invasion time printf("%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %u %u %u %u %u %u %lf %lf\n", w[0][0], w[0][1], w[0][2], w[1][0], w[1][1], w[1][2], w_gphyte_female[0][0], w_gphyte_female[0][1], w_gphyte_female[0][2], w_gphyte_female[1][0], w_gphyte_female[1][1], w_gphyte_female[1][2], w_gphyte_male[0][0], w_gphyte_male[0][1], w_gphyte_male[0][2], w_gphyte_male[1][0], w_gphyte_male[1][1], w_gphyte_male[1][2], wA_gamete_female[0], wa_gamete_female[0], wA_gamete_male[0], wa_gamete_male[0], wA_gamete_female[1], wa_gamete_female[1], wA_gamete_male[1], wa_gamete_male[1], mig_rate_pollen[0], mig_rate_pollen[1], mig_rate_seed[0], mig_rate_seed[1], sigma, patch_size[0], patch_size[1], mutant_init[0], mutant_init[1], run_nb, randSeed, (double)invasion_count/run_nb, (double)time_invasion/invasion_count); return 0; } <file_sep>remove(list=ls()) setwd("~/Desktop/incoming_projects/mating_system/simulation/selfing_sim/processed_data_selfing_varied/") library(dplyr) library(ggplot2) library(scales) sPar=0.01; # Note that whenever sigma is loaded it is converted to population inbreeding coefficient #================== Viability selection ================== # Start in good patch df <-read.table(file = './good_via_F.out',header = FALSE, stringsAsFactors = FALSE) colnames(df) <- c("V1_AA","V1_Aa","V1_aa","V2_AA","V2_Aa","V2_aa", "WF1_AA","WF1_Aa","WF1_aa","WF2_AA","WF2_Aa","WF2_aa", "WM1_AA","WM1_Aa","WM1_aa","WM2_AA","WM2_Aa","WM2_aa", "wF1_A","wF1_a","wM1_A","wM1_a", "wF2_A","wF2_a","wM2_A","wM2_a", "mP1","mP2","mS1","mS2","sigma", "N1","N2","mu1","mu2","run_nb","rndSeed", "P_est","P_time") df <- df %>% select(V1_AA,V1_Aa,V1_aa,V2_AA,V2_Aa,V2_aa,sigma,mP1,mP2,mS1,mS2,P_est) %>% na.omit df$sigma <- df$sigma/(2-df$sigma); df_plot <- df %>% group_by(sigma, V1_Aa, mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') df_plot$V1_Aa <- round((df_plot$V1_Aa-1)/sPar, digits = 4) write.csv(df_plot, './good_via_selfing_varied_processed.csv', row.names = FALSE) ggplot(df_plot, aes(x=sigma, y=mean_Pest, col=as.factor(mS1))) + scale_y_continuous(trans='log10') + geom_point() # Start in bad patch df <-read.table(file = './bad_via_F.out',header = FALSE, stringsAsFactors = FALSE) colnames(df) <- c("V1_AA","V1_Aa","V1_aa","V2_AA","V2_Aa","V2_aa", "WF1_AA","WF1_Aa","WF1_aa","WF2_AA","WF2_Aa","WF2_aa", "WM1_AA","WM1_Aa","WM1_aa","WM2_AA","WM2_Aa","WM2_aa", "wF1_A","wF1_a","wM1_A","wM1_a", "wF2_A","wF2_a","wM2_A","wM2_a", "mP1","mP2","mS1","mS2","sigma", "N1","N2","mu1","mu2","run_nb","rndSeed", "P_est","P_time") df <- df %>% select(V1_AA,V1_Aa,V1_aa,V2_AA,V2_Aa,V2_aa,sigma,mP1,mP2,mS1,mS2,P_est) %>% na.omit df$sigma <- df$sigma/(2-df$sigma); df_plot <- df %>% group_by(sigma, V1_Aa, mS1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') df_plot$V1_Aa <- round((df_plot$V1_Aa-1)/sPar, digits = 4) write.csv(df_plot, './bad_via_selfing_varied_processed.csv', row.names = FALSE) ggplot(df_plot, aes(x=sigma, y=mean_Pest, col=as.factor(mS1))) + scale_y_continuous(trans='log10') + geom_point() <file_sep># local_adaptation_single_locus 1. "mating_system_single_locus_revision.nb" * Mathematica notebook with all derivations and figures presented in the manuscript. Note that simulated data has to be separately prepared and imported. 2. "main.cpp" and "selfing_sim.pro" * The source code for simulator used to generate all the data. The project file contains information necessary for qmake to build the binary. 3. "mating_system_offspring.sh" and "compare_simulations_offspring.R" * Script used to run all the simulations in the paper for population genetic scenarios where seed migrates. * Executes selfing_sim binary, and returns .out files contain raw simulated data (i.e., for each replicate simulation). * * compare_simulations_offspring.R takes .out files and computes averages and standard deviations of the establishment probabilities; This is used for plotting in mating_system_locus_revision.nb 4. "mating_system_gamete_dispersal.sh" and "compare_simulations_gamete.R" * Script used to run all the simulations in the paper for population genetic scenarios where pollen migrates. * Executes selfing_sim binary, and returns .out files contain raw simulated data (i.e., for each replicate simulation). * compare_simulations_gamete.R takes .out files and computes averages and standard deviations of the establishment probabilities; This is used for plotting in mating_system_locus_revision.nb 5. "mating_system_seed_F_varied.sh" and "compare_simulations_self_varied.R" * Script used to run all the simulations in the paper for P~F plot (Figure 3) for different migration rates and dominances. * Executes selfing_sim binary, and returns .out files contain raw simulated data (i.e., for each replicate simulation). * compare_simulations_self_varied.R takes .out files and computes averages and standard deviations of the establishment probabilities; This is used for plotting in mating_system_locus_revision.nb 6. .zip files contain all of the simulated data required for plotting figures in Mathematica notebook * processed_data_offspring_dispersal.zip -- For cases when seed disperses * processed_data_gamete_dispersal.zip -- For cases when pollen disperses * processed_data_selfing_varied.zip -- For P~F plot across migrations and dominances <file_sep>#!/bin/bash # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++++++++ Comments +++++++++++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Usage: selfing_sim [w1AA][w1Aa][w1aa][w2AA][w2Aa][w2aa][m12pollen][m21pollen][m12seed][m21seed][sigma][patch1_size][patch2_size][mut_init1][mut_init2][run_nb][rand_seed] # # When running on personal computer, add gsl to PATH: LD_LIBRARY_PATH=/home/bogi/gsl/lib export LD_LIBRARY_PATH # Load gsl when running on the cluster #module load gsl/2.4 # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++ The overall philosophy +++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # 1. Generate as many PRN as there are simulation runs; Use device files as PRNG # 2. Execute simulations via 'parallel' and pipe all PRNs; This yields data for one set of parameters (e.g., migration rate) # 3. Set new input parameters and goto step 1 generate_rnd() { >$rnd_src for ((k = 1 ; k <= sim_runs ; k++)) do cat /dev/urandom | od -vAn -N4 -tu4 >> $rnd_src done } # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++++++++ Parameters +++++++++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ alpha=1.25 beta=1.0125 sim_runs=1000 good_start_via="./good_via_gamete.out" bad_start_via="./bad_via_gamete.out" good_start_female="./good_female_gamete.out" bad_start_female="./bad_female_gamete.out" good_start_male="./good_male_gamete.out" bad_start_male="./bad_male_gamete.out" rnd_src="rand_seed.out" >$rnd_src # All parameters are kept the same, except that seed_pars are passed as pollen dispersal rate to selfing_sim seed_pars=( 0.0002 0.000427592 0.000914176 0.00195447 0.00417859 0.00893367 0.0190999 0.0408348 0.0873032 0.186651 ) selfing_pars=( 0.00 0.50 1.00 ) # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++++++++ Bulk run +++++++++++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Execution order: # 1) Symmetric selection, symmetric migration, codominant # 2) Symmetric selection, symmetric migration, dominant # 3) Symmetric selection, symmetric migration, recessive # 4) Symmetric selection, asymmetric migration, codominant # 5) Asymmetric selection, symmetric migration, codominant # Selection on viability >$good_start_via >$bad_start_via for i in "${selfing_pars[@]}" do for j in "${seed_pars[@]}" do generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.0075 1 0.99 0.9925 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.0025 1 0.99 0.9975 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $(echo $alpha*$j | bc -l) $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim $beta 1.01 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_via done done for i in "${selfing_pars[@]}" do for j in "${seed_pars[@]}" do generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.0075 1 0.99 0.9925 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.0025 1 0.99 0.9975 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $(echo $alpha*$j | bc -l) $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim $beta 1.01 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_via done done # Selection on female component >$good_start_female >$bad_start_female for i in "${selfing_pars[@]}" do for j in "${seed_pars[@]}" do generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.0075 1 0.99 0.9925 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.0025 1 0.99 0.9975 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $(echo $alpha*$j | bc -l) $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 $beta 1.01 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_female done done for i in "${selfing_pars[@]}" do for j in "${seed_pars[@]}" do generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.0075 1 0.99 0.9925 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.0025 1 0.99 0.9975 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $(echo $alpha*$j | bc -l) $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 $beta 1.01 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_female done done # Selection on male component >$good_start_male >$bad_start_male for i in "${selfing_pars[@]}" do for j in "${seed_pars[@]}" do generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.0075 1 0.99 0.9925 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.0025 1 0.99 0.9975 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 $(echo $alpha*$j | bc -l) $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 $beta 1.01 1 0.99 0.995 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 1 0 10000 {}" >> $good_start_male done done for i in "${selfing_pars[@]}" do for j in "${seed_pars[@]}" do generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.0075 1 0.99 0.9925 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.0025 1 0.99 0.9975 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 $(echo $alpha*$j | bc -l) $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 $beta 1.01 1 0.99 0.995 1 1 1 1 1 1 1 1 1 $j $j 0 0 $i 10000 10000 0 1 10000 {}" >> $bad_start_male done done <file_sep>remove(list=ls()) setwd("~/Desktop/incoming_projects/mating_system/simulation/selfing_sim/processed_data_gamete_dispersal/") library(dplyr) library(ggplot2) library(scales) #================== Viability selection ================== # Start in good patch df <-read.table(file = './good_via_gamete.out',header = FALSE, stringsAsFactors = FALSE) colnames(df) <- c("V1_AA","V1_Aa","V1_aa","V2_AA","V2_Aa","V2_aa", "WF1_AA","WF1_Aa","WF1_aa","WF2_AA","WF2_Aa","WF2_aa", "WM1_AA","WM1_Aa","WM1_aa","WM2_AA","WM2_Aa","WM2_aa", "wF1_A","wF1_a","wM1_A","wM1_a", "wF2_A","wF2_a","wM2_A","wM2_a", "mP1","mP2","mS1","mS2","sigma", "N1","N2","mu1","mu2","run_nb","rndSeed", "P_est","P_time") # When considering viability selection, we can only focus on subset of all columns df <- df %>% select(V1_AA,V1_Aa,V1_aa,V2_AA,V2_Aa,V2_aa,sigma,mP1,mP2,mS1,mS2,P_est) %>% na.omit # Parameters used when running the simulation; Change if required codom_vector <- c(1.01, 1.005, 1, 0.99, 0.995, 1) dom_vector <- c(1.01, 1.0075, 1, 0.99, 0.9925, 1) rec_vector <- c(1.01, 1.0025, 1, 0.99, 0.9975, 1) asym_sel <- c(1.0125, 1.01, 1, 0.99, 0.995, 1) # Make separate data frames holding scenarios with different dominances df_codom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==codom_vector))),] # Simulations with codominance df_dom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==dom_vector))),] # Simulations with dominance df_rec <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==rec_vector))),] # Simulations with recessivity df_asym_sel <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==asym_sel))),] # Simulations with asymmetric selection df_asym_mig <- df_codom[df_codom$mP2!=df_codom$mP1,] # Simulations with asymmetric migration # Imporant note: Because asymmetric migration has been executed for a codominant case # when wanting to plot codominance and symmetric selection, one has to # subset the whole of results with codominance for those cases with symmetrical pollen dispersal df_codom <- df_codom[df_codom$mP2==df_codom$mP1,] # Plotting part df_codom_plot <- df_codom %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_codom_plot, './good_via_codom_processed.csv', row.names = FALSE) ggplot(df_codom_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_dom_plot <- df_dom %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_dom_plot, './good_via_dom_processed.csv', row.names = FALSE) ggplot(df_dom_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_rec_plot <- df_rec %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_rec_plot, './good_via_rec_processed.csv', row.names = FALSE) ggplot(df_rec_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_sel_plot <- df_asym_sel %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_sel_plot, './good_via_asym_sel_processed.csv', row.names = FALSE) ggplot(df_asym_sel_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_mig_plot <- df_asym_mig %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_mig_plot, './good_via_asym_mig_processed.csv', row.names = FALSE) ggplot(df_asym_mig_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() # Start in bad patch df <-read.table(file = './bad_via_gamete.out',header = FALSE, stringsAsFactors = FALSE) colnames(df) <- c("V1_AA","V1_Aa","V1_aa","V2_AA","V2_Aa","V2_aa", "WF1_AA","WF1_Aa","WF1_aa","WF2_AA","WF2_Aa","WF2_aa", "WM1_AA","WM1_Aa","WM1_aa","WM2_AA","WM2_Aa","WM2_aa", "wF1_A","wF1_a","wM1_A","wM1_a", "wF2_A","wF2_a","wM2_A","wM2_a", "mP1","mP2","mS1","mS2","sigma", "N1","N2","mu1","mu2","run_nb","rndSeed", "P_est","P_time") df <- df %>% select(V1_AA,V1_Aa,V1_aa,V2_AA,V2_Aa,V2_aa,sigma,mP1,mP2,mS1,mS2,P_est) %>% na.omit codom_vector <- c(1.01, 1.005, 1, 0.99, 0.995, 1) dom_vector <- c(1.01, 1.0075, 1, 0.99, 0.9925, 1) rec_vector <- c(1.01, 1.0025, 1, 0.99, 0.9975, 1) asym_sel <- c(1.0125, 1.01, 1, 0.99, 0.995, 1) df_codom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==codom_vector))),] df_dom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==dom_vector))),] df_rec <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==rec_vector))),] df_asym_sel <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==asym_sel))),] df_asym_mig <- df_codom[df_codom$mP1!=df_codom$mP2,] df_codom <- df_codom[df_codom$mP1==df_codom$mP2,] df_codom_plot <- df_codom %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_codom_plot, './bad_via_codom_processed.csv', row.names = FALSE) ggplot(df_codom_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_dom_plot <- df_dom %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_dom_plot, './bad_via_dom_processed.csv', row.names = FALSE) ggplot(df_dom_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_rec_plot <- df_rec %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_rec_plot, './bad_via_rec_processed.csv', row.names = FALSE) ggplot(df_rec_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_sel_plot <- df_asym_sel %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_sel_plot, './bad_via_asym_sel_processed.csv', row.names = FALSE) ggplot(df_asym_sel_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_mig_plot <- df_asym_mig %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_mig_plot, './bad_via_asym_mig_processed.csv', row.names = FALSE) ggplot(df_asym_mig_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() #================== Female fitness component selection ================== # Start in good patch df <-read.table(file = './good_female_gamete.out',header = FALSE, stringsAsFactors = FALSE) colnames(df) <- c("V1_AA","V1_Aa","V1_aa","V2_AA","V2_Aa","V2_aa", "WF1_AA","WF1_Aa","WF1_aa","WF2_AA","WF2_Aa","WF2_aa", "WM1_AA","WM1_Aa","WM1_aa","WM2_AA","WM2_Aa","WM2_aa", "wF1_A","wF1_a","wM1_A","wM1_a", "wF2_A","wF2_a","wM2_A","wM2_a", "mP1","mP2","mS1","mS2","sigma", "N1","N2","mu1","mu2","run_nb","rndSeed", "P_est","P_time") df <- df %>% select(WF1_AA,WF1_Aa,WF1_aa,WF2_AA,WF2_Aa,WF2_aa,sigma,mP1,mP2,mS1,mS2,P_est) %>% na.omit codom_vector <- c(1.01, 1.005, 1, 0.99, 0.995, 1) dom_vector <- c(1.01, 1.0075, 1, 0.99, 0.9925, 1) rec_vector <- c(1.01, 1.0025, 1, 0.99, 0.9975, 1) asym_sel <- c(1.0125, 1.01, 1, 0.99, 0.995, 1) df_codom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==codom_vector))),] df_dom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==dom_vector))),] df_rec <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==rec_vector))),] df_asym_sel <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==asym_sel))),] df_asym_mig <- df_codom[df_codom$mP2!=df_codom$mP1,] df_codom <- df_codom[df_codom$mP2==df_codom$mP1,] df_codom_plot <- df_codom %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_codom_plot, './good_female_codom_processed.csv', row.names = FALSE) ggplot(df_codom_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_dom_plot <- df_dom %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_dom_plot, './good_female_dom_processed.csv', row.names = FALSE) ggplot(df_dom_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_rec_plot <- df_rec %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_rec_plot, './good_female_rec_processed.csv', row.names = FALSE) ggplot(df_rec_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_sel_plot <- df_asym_sel %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_sel_plot, './good_female_asym_sel_processed.csv', row.names = FALSE) ggplot(df_asym_sel_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_mig_plot <- df_asym_mig %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_mig_plot, './good_female_asym_mig_processed.csv', row.names = FALSE) ggplot(df_asym_mig_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() # Start in bad patch df <-read.table(file = './bad_female_gamete.out',header = FALSE, stringsAsFactors = FALSE) colnames(df) <- c("V1_AA","V1_Aa","V1_aa","V2_AA","V2_Aa","V2_aa", "WF1_AA","WF1_Aa","WF1_aa","WF2_AA","WF2_Aa","WF2_aa", "WM1_AA","WM1_Aa","WM1_aa","WM2_AA","WM2_Aa","WM2_aa", "wF1_A","wF1_a","wM1_A","wM1_a", "wF2_A","wF2_a","wM2_A","wM2_a", "mP1","mP2","mS1","mS2","sigma", "N1","N2","mu1","mu2","run_nb","rndSeed", "P_est","P_time") df <- df %>% select(WF1_AA,WF1_Aa,WF1_aa,WF2_AA,WF2_Aa,WF2_aa,sigma,mP1,mP2,mS1,mS2,P_est) %>% na.omit codom_vector <- c(1.01, 1.005, 1, 0.99, 0.995, 1) dom_vector <- c(1.01, 1.0075, 1, 0.99, 0.9925, 1) rec_vector <- c(1.01, 1.0025, 1, 0.99, 0.9975, 1) asym_sel <- c(1.0125, 1.01, 1, 0.99, 0.995, 1) df_codom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==codom_vector))),] df_dom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==dom_vector))),] df_rec <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==rec_vector))),] df_asym_sel <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==asym_sel))),] df_asym_mig <- df_codom[df_codom$mP2!=df_codom$mP1,] df_codom <- df_codom[df_codom$mP2==df_codom$mP1,] df_codom_plot <- df_codom %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_codom_plot, './bad_female_codom_processed.csv', row.names = FALSE) ggplot(df_codom_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_dom_plot <- df_dom %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_dom_plot, './bad_female_dom_processed.csv', row.names = FALSE) ggplot(df_dom_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_rec_plot <- df_rec %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_rec_plot, './bad_female_rec_processed.csv', row.names = FALSE) ggplot(df_rec_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_sel_plot <- df_asym_sel %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_sel_plot, './bad_female_asym_sel_processed.csv', row.names = FALSE) ggplot(df_asym_sel_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_mig_plot <- df_asym_mig %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_mig_plot, './bad_female_asym_mig_processed.csv', row.names = FALSE) ggplot(df_asym_mig_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() #================== Male fitness component selection ================== # Start in good patch df <-read.table(file = './good_male_gamete.out',header = FALSE, stringsAsFactors = FALSE) colnames(df) <- c("V1_AA","V1_Aa","V1_aa","V2_AA","V2_Aa","V2_aa", "WF1_AA","WF1_Aa","WF1_aa","WF2_AA","WF2_Aa","WF2_aa", "WM1_AA","WM1_Aa","WM1_aa","WM2_AA","WM2_Aa","WM2_aa", "wF1_A","wF1_a","wM1_A","wM1_a", "wF2_A","wF2_a","wM2_A","wM2_a", "mP1","mP2","mS1","mS2","sigma", "N1","N2","mu1","mu2","run_nb","rndSeed", "P_est","P_time") df <- df %>% select(WM1_AA,WM1_Aa,WM1_aa,WM2_AA,WM2_Aa,WM2_aa,sigma,mP1,mP2,mS1,mS2,P_est) %>% na.omit codom_vector <- c(1.01, 1.005, 1, 0.99, 0.995, 1) dom_vector <- c(1.01, 1.0075, 1, 0.99, 0.9925, 1) rec_vector <- c(1.01, 1.0025, 1, 0.99, 0.9975, 1) asym_sel <- c(1.0125, 1.01, 1, 0.99, 0.995, 1) df_codom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==codom_vector))),] df_dom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==dom_vector))),] df_rec <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==rec_vector))),] df_asym_sel <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==asym_sel))),] df_asym_mig <- df_codom[df_codom$mP2!=df_codom$mP1,] df_codom <- df_codom[df_codom$mP2==df_codom$mP1,] df_codom_plot <- df_codom %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_codom_plot, './good_male_codom_processed.csv', row.names = FALSE) ggplot(df_codom_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_dom_plot <- df_dom %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_dom_plot, './good_male_dom_processed.csv', row.names = FALSE) ggplot(df_dom_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_rec_plot <- df_rec %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_rec_plot, './good_male_rec_processed.csv', row.names = FALSE) ggplot(df_rec_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_sel_plot <- df_asym_sel %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_sel_plot, './good_male_asym_sel_processed.csv', row.names = FALSE) ggplot(df_asym_sel_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_mig_plot <- df_asym_mig %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_mig_plot, './good_male_asym_mig_processed.csv', row.names = FALSE) ggplot(df_asym_mig_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() # Start in bad patch df <-read.table(file = './bad_male_gamete.out',header = FALSE, stringsAsFactors = FALSE) colnames(df) <- c("V1_AA","V1_Aa","V1_aa","V2_AA","V2_Aa","V2_aa", "WF1_AA","WF1_Aa","WF1_aa","WF2_AA","WF2_Aa","WF2_aa", "WM1_AA","WM1_Aa","WM1_aa","WM2_AA","WM2_Aa","WM2_aa", "wF1_A","wF1_a","wM1_A","wM1_a", "wF2_A","wF2_a","wM2_A","wM2_a", "mP1","mP2","mS1","mS2","sigma", "N1","N2","mu1","mu2","run_nb","rndSeed", "P_est","P_time") df <- df %>% select(WM1_AA,WM1_Aa,WM1_aa,WM2_AA,WM2_Aa,WM2_aa,sigma,mP1,mP2,mS1,mS2,P_est) %>% na.omit codom_vector <- c(1.01, 1.005, 1, 0.99, 0.995, 1) dom_vector <- c(1.01, 1.0075, 1, 0.99, 0.9925, 1) rec_vector <- c(1.01, 1.0025, 1, 0.99, 0.9975, 1) asym_sel <- c(1.0125, 1.01, 1, 0.99, 0.995, 1) df_codom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==codom_vector))),] df_dom <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==dom_vector))),] df_rec <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==rec_vector))),] df_asym_sel <- df[unlist(apply(df[,c(1:6)], 1, function(x) all(x==asym_sel))),] df_asym_mig <- df_codom[df_codom$mP2!=df_codom$mP1,] df_codom <- df_codom[df_codom$mP2==df_codom$mP1,] df_codom_plot <- df_codom %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_codom_plot, './bad_male_codom_processed.csv', row.names = FALSE) ggplot(df_codom_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_dom_plot <- df_dom %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_dom_plot, './bad_male_dom_processed.csv', row.names = FALSE) ggplot(df_dom_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_rec_plot <- df_rec %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_rec_plot, './bad_male_rec_processed.csv', row.names = FALSE) ggplot(df_rec_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_sel_plot <- df_asym_sel %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_sel_plot, './bad_male_asym_sel_processed.csv', row.names = FALSE) ggplot(df_asym_sel_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() df_asym_mig_plot <- df_asym_mig %>% group_by(sigma,mP1) %>% summarise(mean_Pest=mean(P_est), sd_Pest=sd(P_est), .groups='drop') write.csv(df_asym_mig_plot, './bad_male_asym_mig_processed.csv', row.names = FALSE) ggplot(df_asym_mig_plot, aes(x=mP1, y=mean_Pest, color=sigma)) + scale_x_continuous(trans = log10_trans()) + geom_point() <file_sep>#!/bin/bash # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++++++++ Comments +++++++++++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Usage: selfing_sim [w1AA][w1Aa][w1aa][w2AA][w2Aa][w2aa][m12pollen][m21pollen][m12seed][m21seed][sigma][patch1_size][patch2_size][mut_init1][mut_init2][run_nb][rand_seed] # # When running on personal computer, add gsl to PATH: LD_LIBRARY_PATH=/home/bogi/gsl/lib export LD_LIBRARY_PATH # If running on cluster, don't forget to load gsl module #module load gsl/2.4 # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++ The overall philosophy +++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # 1. Generate as many PRN as there are simulation runs; Use device files as PRNG # 2. Execute simulations via 'parallel' and pipe all PRNs; This yields data for one set of parameters (e.g., migration rate) # 3. Set new input parameters and goto step 1 generate_rnd() { >$rnd_src for ((k = 1 ; k <= sim_runs ; k++)) do cat /dev/urandom | od -vAn -N4 -tu4 >> $rnd_src done } # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++++++++ Parameters +++++++++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ alpha=1.25 # Multiplies migration rate (patch 1 --> patch 2) when asymmetrical migration is studied beta=1.0125 # Denotes selection coefficient (patch 1) when asymmetrical selection is studied sim_runs=1000 # For each combination of parameters, run 1000 simulations # Output is grouped by the patch where mutant was injected (good vs. bad), and selection mode (viability, female fecundity, and male fecundity, respectively) # We will process the raw output using 'compare_simulations.R' and finally plot it from Mathematica notebook good_start_via="./good_via_offspring.out" bad_start_via="./bad_via_offspring.out" good_start_female="./good_female_offspring.out" bad_start_female="./bad_female_offspring.out" good_start_male="./good_male_offspring.out" bad_start_male="./bad_male_offspring.out" rnd_src="rand_seed.out" >$rnd_src seed_pars=( 0.0002 0.000427592 0.000914176 0.00195447 0.00417859 0.00893367 0.0190999 0.0408348 0.0873032 0.186651 ) # Seed migration rates selfing_pars=( 0.00 0.50 1.00 ) # Three selfing rates examined # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++++++++ Bulk run +++++++++++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Execution order: # 1) Symmetric selection, symmetric migration, codominant # 2) Symmetric selection, symmetric migration, dominant # 3) Symmetric selection, symmetric migration, recessive # 4) Symmetric selection, asymmetric migration, codominant # 5) Asymmetric selection, symmetric migration, codominant # Selection on viability >$good_start_via >$bad_start_via for i in "${selfing_pars[@]}" do for j in "${seed_pars[@]}" do generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 1 0 10000 {}" >> $good_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.0075 1 0.99 0.9925 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 1 0 10000 {}" >> $good_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.0025 1 0.99 0.9975 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 1 0 10000 {}" >> $good_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $(echo $alpha*$j | bc -l) $j $i 10000 10000 1 0 10000 {}" >> $good_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim $beta 1.01 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 1 0 10000 {}" >> $good_start_via done done for i in "${selfing_pars[@]}" do for j in "${seed_pars[@]}" do generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 0 1 10000 {}" >> $bad_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.0075 1 0.99 0.9925 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 0 1 10000 {}" >> $bad_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.0025 1 0.99 0.9975 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 0 1 10000 {}" >> $bad_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $(echo $alpha*$j | bc -l) $j $i 10000 10000 0 1 10000 {}" >> $bad_start_via generate_rnd cat $rnd_src | parallel "./selfing_sim $beta 1.01 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 0 1 10000 {}" >> $bad_start_via done done # Selection on female component >$good_start_female >$bad_start_female for i in "${selfing_pars[@]}" do for j in "${seed_pars[@]}" do generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 1 0 10000 {}" >> $good_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.0075 1 0.99 0.9925 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 1 0 10000 {}" >> $good_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.0025 1 0.99 0.9975 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 1 0 10000 {}" >> $good_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $(echo $alpha*$j | bc -l) $j $i 10000 10000 1 0 10000 {}" >> $good_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 $beta 1.01 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 1 0 10000 {}" >> $good_start_female done done for i in "${selfing_pars[@]}" do for j in "${seed_pars[@]}" do generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 0 1 10000 {}" >> $bad_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.0075 1 0.99 0.9925 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 0 1 10000 {}" >> $bad_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.0025 1 0.99 0.9975 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 0 1 10000 {}" >> $bad_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $(echo $alpha*$j | bc -l) $j $i 10000 10000 0 1 10000 {}" >> $bad_start_female generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 $beta 1.01 1 0.99 0.995 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 0 1 10000 {}" >> $bad_start_female done done # Selection on male component >$good_start_male >$bad_start_male for i in "${selfing_pars[@]}" do for j in "${seed_pars[@]}" do generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 1 0 10000 {}" >> $good_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.0075 1 0.99 0.9925 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 1 0 10000 {}" >> $good_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.0025 1 0.99 0.9975 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 1 0 10000 {}" >> $good_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 0 0 $(echo $alpha*$j | bc -l) $j $i 10000 10000 1 0 10000 {}" >> $good_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 $beta 1.01 1 0.99 0.995 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 1 0 10000 {}" >> $good_start_male done done for i in "${selfing_pars[@]}" do for j in "${seed_pars[@]}" do generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 0 1 10000 {}" >> $bad_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.0075 1 0.99 0.9925 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 0 1 10000 {}" >> $bad_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.0025 1 0.99 0.9975 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 0 1 10000 {}" >> $bad_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 1.01 1.005 1 0.99 0.995 1 1 1 1 1 1 1 1 1 0 0 $(echo $alpha*$j | bc -l) $j $i 10000 10000 0 1 10000 {}" >> $bad_start_male generate_rnd cat $rnd_src | parallel "./selfing_sim 1 1 1 1 1 1 1 1 1 1 1 1 $beta 1.01 1 0.99 0.995 1 1 1 1 1 1 1 1 1 0 0 $j $j $i 10000 10000 0 1 10000 {}" >> $bad_start_male done done
8f383e4beb9ff0ec55efcd25c4d5a3b9bab1ff7f
[ "Markdown", "R", "C++", "Shell" ]
8
R
BogiTrick/local_adaptation_single_locus
b73572421339c2a55349594f1896a8e35d74bfc8
1966b75687d977e3cd7285320633633ec5dcbe2c
refs/heads/master
<repo_name>tityanka/myTemplate<file_sep>/gulpfile.js "use strict"; var gulp = require('gulp'); var server = require('gulp-server-livereload'), browserSync = require('browser-sync').create(), autoprefixer = require('gulp-autoprefixer'), wiredep = require('wiredep').stream, concatCss = require('gulp-concat-css'), sass = require('gulp-sass'), useref = require('gulp-useref'), gulpif = require('gulp-if'), uglify = require('gulp-uglify'), cleanCSS = require('gulp-clean-css'), imagemin = require('gulp-imagemin'), uncss = require('gulp-uncss'), del = require('del'), pug = require('gulp-pug'), smartgrid = require('smart-grid'), gcmq = require('gulp-group-css-media-queries'); //Styles gulp.task('sass', function() { return gulp.src('app/sass/**/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(autoprefixer({ browsers: ['last 15 versions'], cascade: false })) // .pipe(concatCss('main.css')) // .pipe(uncss({ // html: ['app/**/*.html'] // })) .pipe(gulp.dest('app/css')) .pipe(browserSync.stream()); }); gulp.task('browser-sync', function() { browserSync.init({ server: { baseDir: 'app/' }, port: 8080, open: true, notify: false }); }); gulp.task('watch', ['browser-sync', 'sass'], function() { gulp.watch('app/sass/**/*.scss', ['sass']); gulp.watch('app/html/**/*.pug', ['html']); gulp.watch("app/*.html").on('change', browserSync.reload); gulp.watch('app/js/**/*.js', browserSync.reload); gulp.watch('bower.json', ['bower']); }); //Bower gulp.task('bower', function() { gulp.src('app/*.html') .pipe(wiredep({ directory: 'app/bower_components' })) .pipe(gulp.dest('app')); }); //HTML gulp.task('html', function() { return gulp.src('app/html/**/*.pug') .pipe(pug({ pretty: true })) .pipe(gulp.dest('app')) .pipe(browserSync.stream()); }); //Images gulp.task('images', function() { return gulp.src('app/img/**/*') .pipe(imagemin({ progressive: true, optimizationLevel: 7 })) .pipe(gulp.dest('build/img')); }); // Fonts gulp.task('fonts', function() { return gulp.src('app/fonts/**/*') .pipe(gulp.dest('./build/fonts')); }); //Clean gulp.task('clean', function() { return del.sync('build'); }); //Build gulp.task('build', ['fonts', 'images', 'clean'], function() { return gulp.src('app/*.html') .pipe(useref()) .pipe(gulpif('*.js', uglify())) .pipe(gulp.dest('./build')); }); gulp.task('default', ['watch']);
610cfaa562d4522337e6d6e1ec6986c9f195a747
[ "JavaScript" ]
1
JavaScript
tityanka/myTemplate
c13b93c1eafeff9ae7d35e987175f1cd7023fe0b
e3e4617a4eaf5c81e895973d4cca112d9cfad6b0
refs/heads/master
<file_sep>package co.mobilemakers.todo; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.TextView; import java.util.List; /** * Created by agustin on 14/02/15. */ public class TaskAdapter extends ArrayAdapter<Task> { Context mContext; List<Task> mTasks; public TaskAdapter(Context context, List<Task> taskList) { super(context, R.layout.list_item_entry, taskList); mContext = context; mTasks = taskList; } @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView; rowView = reuseOrGenerateRowView(convertView, parent); displayContentInRowView(position, rowView); return rowView; } private void displayContentInRowView(int position, View rowView) { if (rowView != null){ TextView textViewTitle = (TextView)rowView.findViewById(R.id.text_view_task_title); textViewTitle.setText(mTasks.get(position).getmTitle()); CheckBox checkBoxDone = (CheckBox)rowView.findViewById(R.id.checkbox_task_done); checkBoxDone.setChecked(mTasks.get(position).getmDone()); } } private View reuseOrGenerateRowView(View convertView, ViewGroup parent) { View rowView; if (convertView != null) { rowView = convertView; } else { LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = inflater.inflate(R.layout.list_item_entry, parent, false); } return rowView; } } <file_sep>package co.mobilemakers.todo; /** * Created by agustin on 14/02/15. */ public class Task { private String mTitle; private Boolean mDone; public Task(String title) { this.mTitle = title; this.mDone = false; } public String getmTitle() { return mTitle; } public void setmTitle(String mTitle) { this.mTitle = mTitle; } public Boolean getmDone() { return mDone; } public void setmDone(Boolean mDone) { this.mDone = mDone; } }
878daa70f2fff2f7d012f20ccf3d63c5e17423bf
[ "Java" ]
2
Java
agustinglobant/ToDo
842084403ea629124373ad679f0fe8e250f2a8b3
0db4329c9e5eaadb7f9964e82f98542058045dc1
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Created on Thu Jul 20 16:15:23 2017 Author: <NAME> Description: (a) Grab information about different census tracts and (row, col) pairs (b) Reads CMAQ output - NO2, O3 and PM2.5 (c) Calculate the three hour rolling averages for O3, PM2.5 and NO2 (d) Calculate AQHI category (e) Assign AQHI value for each census tract (as is for smaller than 16 km2 tracts and an average of all (row,col) pairs in that tract if tract area is larger than 16 km2) """ from netCDF4 import Dataset import pandas as pd import numpy as np from numba import jit import time #%% cases = ['fire2015', 'ozone2012'] case = cases[0] # define and read files waTractsFile = r"C:\Users\vik\Documents\Projects\environmentalHealthJustice\WA_tracts.csv" orTractsFile = r"C:\Users\vik\Documents\Projects\environmentalHealthJustice\OR_tracts.csv" idTractsFile = r"C:\Users\vik\Documents\Projects\environmentalHealthJustice\ID_tracts.csv" waGridFile = r"C:\Users\vik\Documents\Projects\environmentalHealthJustice\WAgrid.csv" orGridFile = r"C:\Users\vik\Documents\Projects\environmentalHealthJustice\ORgrid.csv" idGridFile = r"C:\Users\vik\Documents\Projects\environmentalHealthJustice\IDgrid.csv" waTractsAll = pd.read_csv(waTractsFile) orTractsAll = pd.read_csv(orTractsFile) idTractsAll = pd.read_csv(idTractsFile) waGrid = pd.read_csv(waGridFile) orGrid = pd.read_csv(orGridFile) idGrid = pd.read_csv(idGridFile) waTracts = waTractsAll.loc[:, ['GEOID']] orTracts = orTractsAll.loc[:, ['GEOID']] idTracts = idTractsAll.loc[:, ['GEOID']] waGrid = waGrid.loc[:, ['I', 'J', 'GEOID']] orGrid = orGrid.loc[:, ['I', 'J', 'GEOID']] idGrid = idGrid.loc[:, ['I', 'J', 'GEOID']] #%% # define the various input files inputDir = r"C:\Users\vik\Documents\Projects\environmentalHealthJustice" outputDir = r"C:\Users\vik\Documents\Projects\environmentalHealthJustice" gridFileDir = "C:/Users/vik/Documents/Projects/MCIP_data/2011111100/MCIP/" cctmFile = '{d}/POST_CCTM_M3XTRACT_NCRCAT_{c}_2011_L01.ncf'.format(d=inputDir, c=case)# inputDir + "/" + "POST_CCTM_M3XTRACT_NCRCAT_fire2015_2011_L01.ncf" gridFile = gridFileDir + "GRIDCRO2D" #%% def readNETCDF(infile, chemSpecies): variable_conc = infile.variables[chemSpecies][:,0,:,:] # if the concentration is in ppm, convert it to ppb if infile.variables[chemSpecies].units.strip() == 'ppm': print ('concentration for {} in input file is in ppm, converting to ppb...'.format(chemSpecies)) variable_conc = 1000.0*variable_conc return variable_conc #%% # calculate three hour average as required by AQHI function # for a description of np.ma.average function used below, see: # http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.ma.average.html # also, the weights list created below is for assigning weight of 1 for the three # elements used for calculating 3 hour mean, and weight for all other elements is set to zero @jit def threeHourAverage(inVar): outVar = np.zeros((inVar.shape[0]-3, inVar.shape[1], inVar.shape[2])) for itime in np.arange(inVar.shape[0]-3): if ( itime%10 == 0 ): print (itime) weights = [] for ix in np.arange(itime): weights.append(0) for ix in np.arange(3): weights.append(1) for ix in np.arange(itime+3,inVar.shape[0]): weights.append(0) t3average = np.ma.average(inVar, axis=0, weights=weights) outVar[itime, :, :] = t3average #return weights, outVar return outVar #%% def getMaxAtCells(inVar): outVar = np.zeros((inVar.shape[1], inVar.shape[2])) for itime in np.arange(inVar.shape[0]): for row in np.arange(inVar.shape[1]): for col in np.arange(inVar.shape[2]): if (inVar[itime, row, col] > outVar[row, col]): outVar[row, col] = inVar[itime, row, col] return outVar #%% # convert aqhi > 10 to 10.5 for plotting purpose def greaterThanTenAQHI(inVar): outVar = np.zeros((inVar.shape[0], inVar.shape[1], inVar.shape[2])) for itime in np.arange(inVar.shape[0]): for row in np.arange(inVar.shape[1]): for col in np.arange(inVar.shape[2]): if (inVar[itime, row, col] > 10.0): outVar[itime, row, col] = 10.75 elif (inVar[itime, row, col] <= 10.0): outVar[itime, row, col] = inVar[itime, row, col] return outVar #%% # read the variables grd = Dataset(gridFile,'r') lat = grd.variables['LAT'][0,0,:,:] lon = grd.variables['LON'][0,0,:,:] ht = grd.variables['HT'][0,0,:,:] w = (grd.NCOLS)*(grd.XCELL) h = (grd.NROWS)*(grd.YCELL) lat_0 = grd.YCENT lon_0 = grd.XCENT nrows = grd.NROWS ncols = grd.NCOLS fileACONC = Dataset(cctmFile, 'r') pm = readNETCDF(fileACONC, 'PMIJ') o3 = readNETCDF(fileACONC, 'O3') nox = readNETCDF(fileACONC, 'NOX') no2 = 0.9*nox grd.close() fileACONC.close() #%% # apply the three hour averaging function begin_time = time.time() pm_3hr = threeHourAverage(pm) no2_3hr = threeHourAverage(no2) o3_3hr = threeHourAverage(o3) end_time = time.time() print ("time taken =%s"%(end_time-begin_time)) #%% no2CoeffCool = 0.000457 pm25CoeffCool = 0.000462 no2CoeffWarm = 0.00101 pm25CoeffWarm = 0.000621 o3CoeffWarm = 0.00104 aqhi_warm_base = (10.0/12.80)*(100*(np.exp(no2CoeffWarm*no2_3hr) -1 + np.exp(pm25CoeffWarm*pm_3hr) -1 + np.exp(o3CoeffWarm*o3_3hr) -1)) aqhi_warm_base = aqhi_warm_base.mean(axis=0) #%% outFileName = {0:'WA_tracts_mean_aqhi', 1:'OR_tracts_mean_aqhi', 2:'ID_tracts_mean_aqhi'} for i, df in enumerate(list([waGrid, orGrid, idGrid])): for idx in df.index: aqhi_at_IJ = aqhi_warm_base[df.at[idx, 'J'], df.at[idx, 'I']] df.at[idx, 'AQHI'] = aqhi_at_IJ df = df.set_index('GEOID', drop=True) df = df.groupby(by=df.index).mean() df.to_csv('{directory}/{fileName}_{case}.csv'.format(directory=outputDir, fileName=outFileName[i], case=case)) #%%
1a814ec7393e760665c9500bc687471ed8edc362
[ "Python" ]
1
Python
vikram-ravi/demographic_for_airpact
d4c9876e9368df61cc81a6ce1d4d65ec2736aa4d
00980a95beb05157487c48f42e12e046beea960e
refs/heads/master
<repo_name>shaner92/LogisticsApp-React<file_sep>/client/src/components/Home/Home.js import React, { Component } from 'react' import PieChart from '../Charts/PieChart' export class Home extends Component { constructor(){ super(); this.state = { data : { pass: 156, fail: 11, other: 23}, width : "500px", height : "500px" }; } render() { return ( <div> <PieChart data={this.state.data} /> </div> ) } } export default Home <file_sep>/client/src/components/BOL/CustomerInfo.js import React, { Component } from 'react' import Card from 'react-bootstrap/Card' export class CustomerInfo extends Component { render() { return ( <Card className="cardPanel"> <Card.Body className="cardBody"> <Card.Title>Ship To:</Card.Title> <Card.Subtitle className="mb-2 text-muted">{this.props.customer.name}</Card.Subtitle> <Card.Subtitle className="mb-2 text-muted">{this.props.customer.city}, {this.props.customer.province}, {this.props.customer.country}</Card.Subtitle> <Card.Subtitle className="mb-2 text-muted">{this.props.customer.address}, {this.props.customer.post_code}</Card.Subtitle> </Card.Body> </Card> ) } } export default CustomerInfo <file_sep>/README.md # LogisticsApp-React <file_sep>/client/src/components/BOL/DropDownItem.js import React, { Component } from 'react' import Dropdown from 'react-bootstrap/Dropdown' export class DropDownItem extends Component { handleSelect(value){ console.log(value); } render() { return ( <Dropdown.Item onSelect={this.handleSelect.bind(this, this.props.carrierName)} >{this.props.carrierName}</Dropdown.Item> ) } } export default DropDownItem <file_sep>/client/src/components/BOL/BolTable.js import React, { Component } from 'react' import BolSelector from './BolSelector'; import Table from 'react-bootstrap/Table' export class BolTable extends Component { render() { return ( <Table responsive hover > <thead className='bg-light'> <tr > <th>Bill of Lading ID</th> <th>Customer</th> <th>Date</th> <th>Select</th> </tr> </thead> <tbody > {this.props.bols.map(bol => <tr key={bol.id}> <td >{bol.id}</td> <td>{bol.customer.name}</td> <td>{bol.date}</td> <BolSelector bol={bol} handleSelect={this.props.handleSelect} /> </tr> )} </tbody> </Table> ) } } export default BolTable <file_sep>/client/src/components/ProductManager/ProdSort.js import React, { Component } from 'react' // import FontAwesomeIcon from 'react-fontawesome' export class ProdSort extends Component { render() { return ( <div> {/* <FontAwesomeIcon icon="star" > </FontAwesomeIcon> */} </div> ) } } export default ProdSort <file_sep>/client/src/components/BOL/CarrierInfo.js import React, { Component } from 'react' import './CarrierInfo.css'; import DropDownMenu from './DropDownMenu' import Card from 'react-bootstrap/Card' import Form from 'react-bootstrap/Form'; import FormControl from 'react-bootstrap/FormControl'; export class CarrierInfo extends Component { constructor() { super(); this.state = { carriers: [] }; } handleSelect(carrierID) { console.log(carrierID) } componentDidMount() { fetch('/api/carriers') .then(res => res.json()) .then(carriers => this.setState({ carriers })); } render() { return ( <Card className="cardPanel"> <Card.Body className="cardBody"> <Card.Title>Carrier Info:</Card.Title> <Card.Subtitle className="mb-2 text-muted">Please Fill the Below Fields in:</Card.Subtitle> <Form inline className="pb-3 pr-5"> <Form.Group > {/* <Form.Label>Select Carrier:</Form.Label> <FormControl type="text" className="mr-sm-2" /> */} <DropDownMenu dataset={this.state.carriers}/> </Form.Group> <Form.Group > <Form.Label>Trailer Number:</Form.Label> <FormControl type="text" className="mr-sm-2" /> </Form.Group> <Form.Group> <Form.Label>Seal Number:</Form.Label> <FormControl type="text" className="mr-sm-2" /> </Form.Group> </Form> </Card.Body> </Card> ) } } export default CarrierInfo <file_sep>/client/src/components/ProductManager/ProdManage.js import React, { Component } from 'react' import ProdPanel from './ProdPanel' import ProdSort from './ProdSort' import './ProdManage.css'; export class ProdManage extends Component { constructor() { super(); this.state = { products: [] }; } componentDidMount() { fetch('/api/products') .then(res => res.json()) .then(products => this.setState({ products })); } render() { return ( <div> <h2 className="pt-5 pb-3 prodHeader">Manager Your Products Here:</h2> <div className="prodManager"> {/* <ProdSort /> */} {this.state.products.map(product => <ProdPanel key={product.prod_id} name={product.name} description={product.description} qty={product.qty} /> )} </div> </div> ) } } export default ProdManage <file_sep>/client/src/components/BOL/BolCreate.js import React, { Component } from 'react' import {Link} from 'react-router-dom' import Button from 'react-bootstrap/Button' import './BolCreate.css'; import BolSearch from './BolSearch'; import BolTable from './BolTable'; class BolCreate extends Component { constructor() { super(); this.state = { bols: [] }; } componentDidMount() { fetch('/api/bols', {searchValue: this.state.searchValue}) .then(res => res.json()) .then(bols => this.setState({ bols })); } updateInput(event) { this.setState({ searchValue: event.target.value }) } handleSearch(event) { fetch('/api/bols?SearchValue='+ this.state.searchValue) .then(res => res.json()) .then(bols => this.setState({ bols })); } render() { return ( <div> <h2 className="pt-5 pb-3">Please Select a Bill of Lading to Process:</h2> <BolSearch updateInput = {this.updateInput.bind(this)} handleSearch={this.handleSearch.bind(this)} bols={this.state.bols}/> <BolTable bols={this.state.bols} /> <Link to="/Bill-of-Lading-Editor"> <Button variant="outline-dark" size="lg" className="launch-button"> Launch </Button> </Link> </div> ); } } export default BolCreate; <file_sep>/client/src/actions/index.js export const selectBol = (payload) => ({ type: 'SELECT_BOL', payload }) export const clearBol = (payload) => ({ type: 'CLEAR_BOL', payload }) <file_sep>/client/src/components/BOL/BolSelector.js import React, { Component } from 'react' import store from '../../store/index' import {selectBol} from '../.././actions' export class BolSelector extends Component { constructor(props) { super(props); this.handleSelect = this.handleSelect.bind(this); } handleSelect(event) { store.dispatch(selectBol({value: this.props.bol})); console.log(store.getState().selected_bol); } render() { return ( <td><input type="radio" name="name" onClick={this.handleSelect} />&nbsp;</td> ) } } export default BolSelector <file_sep>/client/src/components/BOL/BolEdit.js import React, { Component } from 'react' import store from '../../store/index' import { Link } from 'react-router-dom' import Button from 'react-bootstrap/Button' import './BolEdit.css'; import ShipperInfo from './ShipperInfo' import CustomerInfo from './CustomerInfo' import CarrierInfo from './CarrierInfo' import OrderInfo from './OrderInfo' export class BolEdit extends Component { constructor() { super(); this.state = { bol: {} }; } componentDidMount() { this.setState({ bol: store.getState().selected_bol }); } render() { let header, shipper, customer, carrier, order, report; //Build up page structer once data has been loaded if (this.state.bol.bol_id !== undefined) { header = <h2 className="pt-5 pb-3 bolHeader">Bill of Lading ID: {this.state.bol.bol_id}</h2> shipper = <ShipperInfo shipper={this.state.bol.shipper} /> customer = <CustomerInfo customer={this.state.bol.customer} />; carrier = <CarrierInfo carrier={this.state.bol.carrier} />; order = <OrderInfo order={this.state.bol.order} />; report = <Link to=""> <Button variant="outline-dark" size="lg" className="launch-button"> Generate Report </Button> </Link>; } else { //If not data has been loaded display error. header = <h2 className="pt-5 pb-3 bolHeader">Sorry, please return to Bill of Lading creation screen.</h2> } return ( <React.Fragment> {header} <div className="bolEdit"> {shipper} {customer} {carrier} {order} </div> {report} </React.Fragment> ) } } export default BolEdit <file_sep>/client/src/components/Layout/NavBar.js import React, { Component } from 'react'; import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'; import Navbar from 'react-bootstrap/Navbar'; import Nav from 'react-bootstrap/Nav'; import Home from '../Home/Home'; import BolCreate from '../BOL/BolCreate'; import BolEdit from '../BOL/BolEdit'; import PackSlip from '../PackingSlip/PackSlip'; import ProdManage from '../ProductManager/ProdManage'; export class NavBar extends Component { render() { return ( <Router> <div> <Navbar bg="dark" variant="dark" expand="lg"> <Navbar.Brand href="/">Logistics</Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="mr-auto"> <Link to="/" className="nav-link">Home</Link> <Link to="/Bill-of-Lading-Creator" className="nav-link">Bill of Lading</Link> <Link to="/Packing-Slip-Creator" className="nav-link">Packing Slip</Link> <Link to="/Product-Manager" className="nav-link">Product Management</Link> </Nav> {/* <Form inline> <FormControl type="text" placeholder="Search" className="mr-sm-2" /> <Button variant="outline-info">Search</Button> </Form> */} </Navbar.Collapse> </Navbar> <Switch> <Route exact path='/' component={Home} /> <Route path='/Bill-of-Lading-Creator' component={BolCreate} /> <Route path='/Bill-of-Lading-Editor' component={BolEdit} /> <Route path='/Packing-Slip-Creator' component={PackSlip} /> <Route path='/Product-Manager' component={ProdManage} /> </Switch> </div> </Router> ) } } export default NavBar
666a388b3b6e127ecc92ee83630bb7158061bcf5
[ "JavaScript", "Markdown" ]
13
JavaScript
shaner92/LogisticsApp-React
56ba10ba2df8988f4437b2eadb09dc3855547a8d
415137d1ea77824d4c2b56fc55beb1d69313fa8f
refs/heads/main
<file_sep>[tool.poetry] name = "esteemer" version = "0.1.0" description = "Rank and select feedback message(s)" authors = ["<NAME> <<EMAIL>>"] [tool.poetry.dependencies] python = "^3.10" rdfpandas = "^1.1.5" rdflib = "^6.1.1" SPARQLWrapper = "^2.0.0" [tool.poetry.dev-dependencies] pytest = "^7.1.2" isort = "^5.10.1" pycln = "^1.3.3" black = "^22.3.0" flake8 = "^4.0.1" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" [tool.pytest.ini_options] # tooling running pytest will not resolve modules in `src` testpaths = ["tests"] pythonpath = ["src"]<file_sep>import warnings import time import logging import pandas as pd from rdflib import Graph, Literal, Namespace, URIRef from rdflib.collection import Collection from rdflib.namespace import FOAF, RDF, RDFS, SKOS, XSD from rdflib.serializer import Serializer from rdfpandas.graph import to_dataframe from SPARQLWrapper import XML, SPARQLWrapper warnings.filterwarnings("ignore") def read(file): start_time = time.time() g = Graph() g.parse(file) logging.critical(" reading graph--- %s seconds ---" % (time.time() - start_time)) return g def read_contenders(graph_read): start_time = time.time() qres = graph_read.query( """ PREFIX obo: <http://purl.obolibrary.org/obo/> PREFIX slowmo: <http://example.com/slowmo#> construct { ?candidate ?p ?o . ?candidate obo:RO_0000091 ?o2 . ?o2 slowmo:RegardingComparator ?comparator . ?o2 slowmo:RegardingMeasure ?measure . ?candidate slowmo:acceptable_by ?o3 . } WHERE { ?candidate ?p ?o . ?candidate obo:RO_0000091 ?o2 . ?o2 slowmo:RegardingComparator ?comparator . ?o2 slowmo:RegardingMeasure ?measure . ?candidate slowmo:acceptable_by ?o3 . } """ ) logging.critical(" querying contenders graph--- %s seconds ---" % (time.time() - start_time)) return qres.graph def read_measures(graph_read): start_time = time.time() qres = graph_read.query( """ PREFIX obo: <http://purl.obolibrary.org/obo/> PREFIX slowmo: <http://example.com/slowmo#> construct { ?candidate slowmo:RegardingMeasure ?measure . ?measure ?p3 ?o3 . } WHERE { ?candidate slowmo:RegardingMeasure ?measure . ?measure ?p3 ?o3 . } """ ) logging.critical(" querying measures graph--- %s seconds ---" % (time.time() - start_time)) return qres.graph def read_comparators(graph_read): start_time = time.time() qres = graph_read.query( """ PREFIX obo: <http://purl.obolibrary.org/obo/> PREFIX slowmo: <http://example.com/slowmo#> construct { ?candidate slowmo:RegardingComparator ?comparator . ?comparator ?p2 ?o2 . } WHERE { ?candidate slowmo:RegardingComparator ?comparator . ?comparator ?p2 ?o2 . } """ ) logging.critical(" querying comparator graph--- %s seconds ---" % (time.time() - start_time)) return qres.graph def transform(contenders_graph,measures_graph,comparator_graph,measure_list): start_time = time.time() contenders_graph.bind("obo", "http://purl.obolibrary.org/obo/") contenders_graph.bind("slowmo", "http://example.com/slowmo#") # start implementation of esteemer algorithm contender_messages_df = to_dataframe(contenders_graph) contender_messages_df.reset_index(inplace=True) contender_messages_df = contender_messages_df.rename(columns={"index": "id"}) #contender_messages_df.to_csv("contenders.csv") measures_df = to_dataframe(measures_graph) measures_df.reset_index(inplace=True) measures_df = measures_df.rename(columns={"index": "id"}) #measures_df.to_csv("measures.csv") comparator_df = to_dataframe(comparator_graph) comparator_df.reset_index(inplace=True) comparator_df = comparator_df.rename(columns={"index": "id"}) #comparator_df.to_csv("comparators.csv") column_values = [ "obo:RO_0000091{BNode}[0]", "obo:RO_0000091{BNode}[1]", "obo:RO_0000091{BNode}[2]", "obo:RO_0000091{BNode}[3]", "obo:RO_0000091{BNode}[4]", "obo:RO_0000091{BNode}[5]", "obo:RO_0000091{BNode}[6]", "obo:RO_0000091{BNode}[7]", "obo:RO_0000091{BNode}[8]", "obo:RO_0000091{BNode}[9]", "obo:RO_0000091{BNode}[10]", "obo:RO_0000091{BNode}[11]", ] column_values1 =[ "RegardingComparator", ] column_values2 =[ "RegardingMeasure", ] reference_df = contender_messages_df.filter( [ "id", "rdf:type{URIRef}", "slowmo:RegardingComparator{BNode}", "slowmo:RegardingMeasure{BNode}", ], axis=1, ) reference_df2 = comparator_df.filter( [ "id", "http://example.com/slowmo#ComparisonValue{Literal}(xsd:double)", "http://schema.org/name{Literal}" ], axis=1, ) reference_df3 = measures_df.filter( [ "id", "dcterms:title{Literal}", "http://schema.org/identifier{Literal}" ], axis=1, ) meaningful_messages_df = contender_messages_df[ contender_messages_df["slowmo:AncestorPerformer{Literal}"].notna() ] #reference_df1 = reference_df.dropna() reference_df1 = reference_df RegardingComparator = [] RegardingMeasure = [] disposition = [] values = [] for rowIndex, row in meaningful_messages_df.iterrows(): # iterate over rows b = 0 for columnIndex, value in row.items(): if columnIndex in column_values: a = reference_df1.loc[reference_df1["id"] == value] if not a.empty: if b == 0: a.reset_index(drop=True, inplace=True) disposition.append(a["rdf:type{URIRef}"][0]) values.append(value) RegardingComparator.append( a["slowmo:RegardingComparator{BNode}"][0] ) RegardingMeasure.append(a["slowmo:RegardingMeasure{BNode}"][0]) b = b + 1 meaningful_messages_df["RegardingComparator"] = RegardingComparator meaningful_messages_df["RegardingMeasure"] = RegardingMeasure meaningful_messages_df["disposition"] = disposition meaningful_messages_df["reference_values"] = values intermediate_messages_final = meaningful_messages_df.filter( [ "id", "slowmo:AncestorPerformer{Literal}", "slowmo:AncestorTemplate{Literal}", "disposition", "reference_values", "rdf:type{URIRef}", "psdo:PerformanceSummaryDisplay{Literal}", "psdo:PerformanceSummaryTextualEntity{Literal}", "RegardingComparator", "RegardingMeasure", "slowmo:acceptable_by{URIRef}[0]", "slowmo:acceptable_by{URIRef}[1]", ], axis=1, ) #intermediate_messages_final.to_csv("intermediate.csv") # with_comparator_0 =[] # with_comparator_1 =[] title=[] identifier_1=[] comparison_value =[] name=[] for rowIndex, row in intermediate_messages_final.iterrows(): # iterate over rows for columnIndex, value in row.items(): if columnIndex in column_values1: a = reference_df2.loc[reference_df2["id"] == value] if not a.empty: a.reset_index(drop=True, inplace=True) # #with_comparator_0.append(a["slowmo:WithComparator{BNode}[0]"][0]) # #with_comparator_1.append(a["slowmo:WithComparator{BNode}[1]"][0]) # #title.append(a["dcterms:title{Literal}"][0]) # #identifier_1.append(a["http://schema.org/identifier{Literal}"][0]) comparison_value.append(a["http://example.com/slowmo#ComparisonValue{Literal}(xsd:double)"][0]) name.append(a["http://schema.org/name{Literal}"][0]) # #intermediate_messages_final["with_comparator_0"] = with_comparator_0 # #intermediate_messages_final["with_comparator_1"] = with_comparator_1 # #intermediate_messages_final["title"] = title # #intermediate_messages_final["Measure Name"] = identifier_1 intermediate_messages_final["comparison value"] = comparison_value intermediate_messages_final["name"]=name # #meaningful_messages_df["disposition"] = disposition # #meaningful_messages_df["reference_values"] = values for rowIndex, row in intermediate_messages_final.iterrows(): # iterate over rows for columnIndex, value in row.items(): if columnIndex in column_values2: a = reference_df3.loc[reference_df3["id"] == value] if not a.empty: a.reset_index(drop=True, inplace=True) # with_comparator_0.append(a["slowmo:WithComparator{BNode}[0]"][0]) # with_comparator_1.append(a["slowmo:WithComparator{BNode}[1]"][0]) title.append(a["dcterms:title{Literal}"][0]) identifier_1.append(a["http://schema.org/identifier{Literal}"][0]) # #comparison_value.append(a["slowmo:ComparisonValue{Literal}(xsd:double)"][0]) # #name.append(a["http://schema.org/name{Literal}"][0]) # intermediate_messages_final["with_comparator_0"] = with_comparator_0 # intermediate_messages_final["with_comparator_1"] = with_comparator_1 intermediate_messages_final["title"] = title intermediate_messages_final["Measure Name"] = identifier_1 # #intermediate_messages_final["comparison value"] = comparison_value # #intermediate_messages_final["name"]=name #intermediate_messages_final.to_csv("intermediate1.csv") meaningful_messages_final = intermediate_messages_final.filter( [ "id", "slowmo:AncestorPerformer{Literal}", "slowmo:AncestorTemplate{Literal}", "disposition", "reference_values", "rdf:type{URIRef}", "psdo:PerformanceSummaryDisplay{Literal}", "psdo:PerformanceSummaryTextualEntity{Literal}", "slowmo:acceptable_by{URIRef}[0]", "slowmo:acceptable_by{URIRef}[1]", "comparison value", "name", "title", "Measure Name" ], axis=1, ) newdf = meaningful_messages_final[meaningful_messages_final['Measure Name'].isin(measure_list)] #meaningful_messages_final.to_csv("final_list.csv") logging.critical("transforming--- %s seconds ---" % (time.time() - start_time)) # return contender_messages_df return newdf def graph_from_sparql_endpoint(endpoint): sparql = SPARQLWrapper(endpoint) sparql.setQuery( """ PREFIX obo: <http://purl.obolibrary.org/obo/> PREFIX slowmo: <http://example.com/slowmo#> construct { ?candidate ?p ?o . ?candidate obo:RO_0000091 ?disposition . ?disposition ?p2 ?o2 . } FROM <http://localhost:3030/ds/spek> WHERE { ?candidate a obo:cpo_0000053 . ?candidate slowmo:AncestorPerformer ?performer . ?candidate obo:RO_0000091 ?disposition . ?candidate ?p ?o . ?disposition ?p2 ?o2 . } """ ) results = sparql.queryAndConvert() return results <file_sep>import json import sys import warnings import time import logging import json #from asyncore import read import pandas as pd from rdflib import Graph, Literal, Namespace, URIRef from rdflib.collection import Collection from rdflib.namespace import FOAF, RDF, RDFS, SKOS, XSD from rdflib.serializer import Serializer from rdfpandas.graph import to_dataframe from SPARQLWrapper import XML, SPARQLWrapper # from .load_for_real import load from .load import read, transform,read_contenders,read_measures,read_comparators from .score import score, select,apply_indv_preferences,apply_history_message # load() warnings.filterwarnings("ignore") # TODO: process command line args if using graph_from_file() # Read graph and convert to dataframe start_time = time.time() graph_read = read(sys.argv[1]) f=open(sys.argv[2]) indv_preferences_read = json.load(f) f1=open(sys.argv[3]) message_code= json.load(f1) f2=open(sys.argv[4]) history=json.load(f2) performance_data_df = pd.read_csv(sys.argv[5]) measure_list=[] measure_list=performance_data_df['Measure_Name'].drop_duplicates() #indv_preferences_read_df = pd.read_json(sys.argv[2], lines=True) contenders_graph = read_contenders(graph_read) measures_graph = read_measures(graph_read) comparator_graph = read_comparators(graph_read) # print(contenders_graph) # contenders_graph=graph_from_sparql_endpoint("http://localhost:3030/ds/sparql") # print(contenders_graph.serialize(format="ttl")) # Transform dataframe to more meaningful dataframe meaningful_messages_final = transform(contenders_graph,measures_graph,comparator_graph,measure_list) # print(meaningful_messages_final) # assign score for each of meaningful_messages start_time1 = time.time() meaningful_messages_final = score(meaningful_messages_final) #apply individual preferences applied_individual_messages,max_val = apply_indv_preferences(meaningful_messages_final,indv_preferences_read) val = max_val.split('_') #print(val[0]) #filter history messages applied_history_filter = apply_history_message(applied_individual_messages,history,val[0],message_code) # select maximum of the meaningful_messages finalData = select(applied_history_filter,val[0],message_code) logging.critical("--score and select %s seconds ---" % (time.time() - start_time1)) print(finalData) time_taken = time.time()-start_time logging.critical("---total esteemer run time according python script %s seconds ---" % (time.time() - start_time)) #print("--- %s seconds ---" % (time.time() - start_time)) """with open('data.json', 'a') as f: f.write(finalData + '\n')""" <file_sep>import json import random import sys import warnings import operator import pandas as pd from rdflib import Graph, Literal, Namespace, URIRef from rdflib.collection import Collection from rdflib.namespace import FOAF, RDF, RDFS, SKOS, XSD from rdflib.serializer import Serializer from rdfpandas.graph import to_dataframe from SPARQLWrapper import XML, SPARQLWrapper warnings.filterwarnings("ignore") def score(meaningful_messages_final): len = meaningful_messages_final.shape[0] score = random.sample(range(10, 1000), len) meaningful_messages_final["score"] = score meaningful_messages_final.reset_index(drop=True, inplace=True) #meaningful_messages_final.to_csv("df_es1.csv") return meaningful_messages_final # meaningful_messages_final.to_csv("df_es1.csv") def apply_indv_preferences(meaningful_messages_final,indv_preferences_read): indv_preferences_df = pd.json_normalize(indv_preferences_read) display_preferences_df =indv_preferences_df [['Utilities.Display_Format.short_sentence_with_no_chart', 'Utilities.Display_Format.bar_chart','Utilities.Display_Format.line_graph']] message_preferences_df =indv_preferences_df[['Utilities.Message_Format.1','Utilities.Message_Format.2','Utilities.Message_Format.16','Utilities.Message_Format.24','Utilities.Message_Format.18','Utilities.Message_Format.11','Utilities.Message_Format.22','Utilities.Message_Format.14','Utilities.Message_Format.21']] display_preferences,max_val = displaypreferences(meaningful_messages_final,display_preferences_df) messages_preferences= messagepreferences(display_preferences,message_preferences_df) #display_preferences_df.to_csv('display_preferences.csv') #message_preferences_df.to_csv('message_preferences_df.csv') #indv_preferences_df.to_csv('individual_preferences.csv') #messages_preferences.to_csv('message_preferences_final.csv') return messages_preferences ,max_val def displaypreferences(meaningful_messages_final,display_preferences_df): nochart_pref=display_preferences_df.at[0,'Utilities.Display_Format.short_sentence_with_no_chart'] bar_pref=display_preferences_df.at[0,'Utilities.Display_Format.bar_chart'] line_pref=display_preferences_df.at[0,'Utilities.Display_Format.line_graph'] line_pref = float(line_pref) bar_pref = float(bar_pref) nochart_pref = float(nochart_pref) my_dict = {"line_pref":[],"bar_pref":[],"nochart_pref":[]} if line_pref == 0: line_pref= 1 elif bar_pref == 0: bar_pref =1 elif nochart_pref ==0: nochart_pref = 1 display_score =[] #max_pref =[] my_dict["line_pref"].append(line_pref) my_dict["bar_pref"].append(bar_pref) my_dict["nochart_pref"].append(nochart_pref) max_val = max(my_dict.items(), key=operator.itemgetter(1))[0] #max_val=max(max_pref) #print(max_val) #line_pref = int(line_pref) #bar_pref = int(bar_pref) #no_chart_pref = int(no_chart_pref) #print(type(line_pref)) for index, row in meaningful_messages_final.iterrows(): display_pref = row['psdo:PerformanceSummaryDisplay{Literal}'] display_pref = display_pref.replace("'", "") x = display_pref.split(",") bar='bar' line='line' text='none' if bar in x: row['score'] = row['score']*bar_pref if line in x: row['score'] = row['score']*line_pref if text in x : row['score'] = row['score']*nochart_pref display_score.append(row['score']) meaningful_messages_final['display_score'] = display_score return meaningful_messages_final,max_val def messagepreferences(display_preferences,message_preferences_df): #message_preferences_df.to_csv('before_select.csv') top_performer_pref=float(message_preferences_df.at[0,'Utilities.Message_Format.1']) nontop_performer_pref=float(message_preferences_df.at[0,'Utilities.Message_Format.2']) performance_dropped_below_peer_pref=float(message_preferences_df.at[0,'Utilities.Message_Format.16']) no_message_pref=float(message_preferences_df.at[0,'Utilities.Message_Format.24']) may_improve_pref=float(message_preferences_df.at[0,'Utilities.Message_Format.18']) approaching_goal_pref=float(message_preferences_df.at[0,'Utilities.Message_Format.11']) performance_improving_pref = float(message_preferences_df.at[0,'Utilities.Message_Format.22']) getting_worse_pref = float(message_preferences_df.at[0,'Utilities.Message_Format.14']) adverse_event_pref = float(message_preferences_df.at[0,'Utilities.Message_Format.21']) message_score = [] if top_performer_pref == 0: top_performer_pref= 1 elif nontop_performer_pref== 0: nontop_performer_pref =1 elif performance_dropped_below_peer_pref ==0: performance_dropped_below_peer_pref = 1 elif approaching_goal_pref ==0: approaching_goal_pref = 1 elif getting_worse_pref ==0: getting_worse_pref = 1 #print(top_performer_pref,nontop_performer_pref,performance_dropped_below_peer_pref ,approaching_goal_pref,getting_worse_pref ) for index, row in display_preferences.iterrows(): #message_pref = row['display_score'] text=row['psdo:PerformanceSummaryTextualEntity{Literal}'] #x = text.split(" ") #print(x) if text == "1" : row['display_score'] = row['display_score']*top_performer_pref if text == "2": row['display_score'] = row['display_score']*nontop_performer_pref #if (top and not not1 in x) or (reached and goal in x) or (reached and benchmark in x) or(above and goal in x): if text == "16": row['display_score'] = row['display_score']*performance_dropped_below_peer_pref if text == "24": row['display_score'] = row['display_score']*no_message_pref if text == "18": row['display_score'] = row['display_score']*may_improve_pref if text == "11": row['display_score'] = row['display_score']*approaching_goal_pref if text == "22": row['display_score'] = row['display_score']*performance_improving_pref if text == "14": row['display_score'] = row['display_score']*getting_worse_pref if text == "21": row['display_score'] = row['display_score']*adverse_event_pref message_score.append(row['display_score']) display_preferences['message_score'] = message_score return display_preferences def apply_history_message(applied_individual_messages,history,max_val,message_code): message_code_df = pd.json_normalize(message_code) history_df =pd.json_normalize(history) #history_df.to_csv("history_df.csv") month1 = history_df[['History.Month1.psdo:PerformanceSummaryDisplay{Literal}','History.Month1.Measure Name','History.Month1.Message Code']].copy() month2 = history_df[['History.Month2.psdo:PerformanceSummaryDisplay{Literal}','History.Month2.Measure Name','History.Month2.Message Code']].copy() month3 = history_df[['History.Month3.psdo:PerformanceSummaryDisplay{Literal}','History.Month3.Measure Name','History.Month3.Message Code']].copy() month4 = history_df[['History.Month4.psdo:PerformanceSummaryDisplay{Literal}','History.Month4.Measure Name','History.Month4.Message Code']].copy() month5 = history_df[['History.Month5.psdo:PerformanceSummaryDisplay{Literal}','History.Month5.Measure Name','History.Month5.Message Code']].copy() month6 = history_df[['History.Month6.psdo:PerformanceSummaryDisplay{Literal}','History.Month6.Measure Name','History.Month6.Message Code']].copy() applied_individual_messages.reset_index() for index, row in applied_individual_messages.iterrows(): disp=row['psdo:PerformanceSummaryDisplay{Literal}'].split(",") if (month1['History.Month1.psdo:PerformanceSummaryDisplay{Literal}'][0] in disp and month1['History.Month1.Measure Name'][0]== row['Measure Name'] and month1['History.Month1.Message Code'][0]== row['psdo:PerformanceSummaryTextualEntity{Literal}'] ): applied_individual_messages = applied_individual_messages.drop(index) if (month2['History.Month2.psdo:PerformanceSummaryDisplay{Literal}'][0] in disp and month2['History.Month2.Measure Name'][0]== row['Measure Name'] and month2['History.Month2.Message Code'][0]== row['psdo:PerformanceSummaryTextualEntity{Literal}'] ): applied_individual_messages = applied_individual_messages.drop(index) if (month3['History.Month3.psdo:PerformanceSummaryDisplay{Literal}'][0] in disp and month3['History.Month3.Measure Name'][0]== row['Measure Name'] and month3['History.Month3.Message Code'][0]== row['psdo:PerformanceSummaryTextualEntity{Literal}'] ): applied_individual_messages = applied_individual_messages.drop(index) if (month4['History.Month4.psdo:PerformanceSummaryDisplay{Literal}'][0] in disp and month4['History.Month4.Measure Name'][0]== row['Measure Name'] and month4['History.Month4.Message Code'][0]== row['psdo:PerformanceSummaryTextualEntity{Literal}'] ): applied_individual_messages = applied_individual_messages.drop(index) if (month5['History.Month5.psdo:PerformanceSummaryDisplay{Literal}'][0] in disp and month5['History.Month5.Measure Name'][0]== row['Measure Name'] and month5['History.Month5.Message Code'][0]== row['psdo:PerformanceSummaryTextualEntity{Literal}'] ): applied_individual_messages = applied_individual_messages.drop(index) if (month6['History.Month6.psdo:PerformanceSummaryDisplay{Literal}'][0] in disp and month6['History.Month6.Measure Name'][0]== row['Measure Name'] and month6['History.Month6.Message Code'][0]== row['psdo:PerformanceSummaryTextualEntity{Literal}'] ): applied_individual_messages = applied_individual_messages.drop(index) return applied_individual_messages def select(applied_individual_messages,max_val,message_code): # max value of score column = applied_individual_messages["message_score"] message_code_df = pd.json_normalize(message_code) #message_code_df.to_csv("message_code.csv") # max_value = column.max() h = applied_individual_messages["message_score"].idxmax() message_selected_df = applied_individual_messages.iloc[h, :] message_selected_df.at['psdo:PerformanceSummaryDisplay{Literal}']=max_val #message_selected_df.to_csv('message_selected.csv') mes_id=message_selected_df.at['psdo:PerformanceSummaryTextualEntity{Literal}'].split(".") #print(mes_id[0]) message = "Message_ids."+mes_id[0] message_selected_df = message_selected_df.append(pd.Series(message_selected_df.at['psdo:PerformanceSummaryTextualEntity{Literal}'], index=['Message Code'])) message_selected_df.at['psdo:PerformanceSummaryTextualEntity{Literal}']=message_code_df.at[0,message] message_selected_df = message_selected_df.drop(['score','display_score','message_score']); message_selected_df = message_selected_df.T data = message_selected_df.to_json(orient="index", indent=2 ) return data.replace("\\", "") #return column<file_sep>#!/usr/bin/env bash # Usage message read -r -d '' USE_MSG <<'HEREDOC' Usage: esteemer.sh -h esteemer.sh -p causal_pathway.json esteemer.sh -s spek.json Esteemer reads a spek from stdin or provided file path. Options: -h | --help print help and exit -p | --pathways path to causal pathways -s | --spek path to spek file (default to stdin) HEREDOC # Parse args PARAMS=() while (("$#")); do case "$1" in -h | --help) echo "${USE_MSG}" exit 0 ;; -p | --pathways) CP_FILE="${2}" shift 2 ;; -s | --spek) SPEK_FILE="${2}" shift 2 ;; --) # end argument parsing shift break ;; -* | --*=) # unsupported flags echo "Aborting: Unsupported flag $1" >&2 exit 1 ;; *) # preserve positional arguments PARAMS+=("${1}") shift ;; esac done # Check if FUSEKI is running. FUSEKI_PING=$(curl -s -o /dev/null -w "%{http_code}" localhost:3030/$/ping) if [[ -z ${FUSEKI_PING}} || ${FUSEKI_PING} -ne 200 ]]; then # Error echo >&2 "Fuseki not running locally." # Try to start custom fuseki locally # FUSEKI_DIR=/opt/fuseki/apache-jena-fuseki-3.10.0 ${FUSEKI_HOME}/fuseki-server --mem --update /ds 1>fuseki.out 2>&1 & exit 1 fi # Define SPARQL Queries for updates and results # Construct sub-graph of candidate nodes, and ancestor performer nodes (they are not connected here) read -r -d '' UPDATE_CANDIDATES_WITH_PROMOTED_BY << \ 'SPARQL' PREFIX obo: <http://purl.obolibrary.org/obo/> PREFIX slowmo: <http://example.com/slowmo#> INSERT { GRAPH <http://localhost:3030/ds/espek> { ?candidate slowmo:promoted_by <http://example.com/slowmo#default_esteemer_criteria> . } } USING <http://localhost:3030/ds/espek> WHERE { ?candidate a obo:cpo_0000053 . ?candidate slowmo:acceptable_by ?o } SPARQL # Read from SPEK_FILE or pipe from stdin # Use '-' to instruct curl to read from stdin if [[ -z ${SPEK_FILE} ]]; then SPEK_FILE="-" fi FUSEKI_DATASET_URL="http://localhost:3030/ds" SPEK_URL="${FUSEKI_DATASET_URL}/espek" # Load presteemer turtle spek into fuseki curl --silent PUT \ --data-binary @${SPEK_FILE} \ --header 'Content-type: text/turtle' \ "${FUSEKI_DATASET_URL}?graph=${SPEK_URL}" >&2 # run update sparql curl --silent POST \ --data-binary "${UPDATE_CANDIDATES_WITH_PROMOTED_BY}" \ --header 'Content-type: application/sparql-update' \ "${FUSEKI_DATASET_URL}/update" # get updated spek and emit to stdout. curl --silent \ --header 'Accept: application/ld+json' \ "${FUSEKI_DATASET_URL}?graph=${SPEK_URL}" <file_sep># Esteemer Scripts The main purpose of Esteemer stage is to promote the candidate messages that are marked as accepted by think pudding. The `esteemer` script should load the Think Pudding graph, extract relevant message parts, and mark one candidate per ancestor performer in the graph as `promoted` based on some criteria (tbd). ## Install the Esteemer package globally ```sh pip install [/path/or/url/to/esteemer-0.1.0-py3-none-any.whl] ``` ## Installing the Esteemer package in development mode ```sh pip install -e [path/to/module/displaylab/esteemer/python] ``` ## Running the Esteemer script ```sh python -m esteemer.esteemer [/path/to/spek_tp.json][/path/to/spek_preferences.json][/path/to/spek_message_id.json][/path/to/spek_history.json] ``` ## Running the pfp pipeline (pfp.sh) Note: This assumes that you installed the pfp pipeline installed and you have installed the esteemer package ```sh cd $DISPLAY_LAB_HOME/vert-ramp-affirmation/vignettes/aspire ./$DISPLAY_LAB_HOME/vert-ramp-affirmation/pfp.sh ``` See vert-ramp-affirmation readme docs for more info ## How it works #### Query inside ```PREFIX obo: <http://purl.obolibrary.org/obo/> PREFIX slowmo: <http://example.com/slowmo#> construct { ?candidate ?p ?o . ?candidate obo:RO_0000091 ?disposition . ?disposition ?p2 ?o2 . ?candidate slowmo:acceptable_by ?o3 . } WHERE { ?candidate a obo:cpo_0000053 . ?candidate slowmo:AncestorPerformer ?performer . ?candidate obo:RO_0000091 ?disposition . ?candidate ?p ?o . ?disposition ?p2 ?o2 . ?candidate slowmo:acceptable_by ?o3 . } ``` ### Esteemer Evaluate acceptable candidates for promotion to figure generation. #### Use (in progress): Options: - `-h | --help` print help and exit - `-p | --pathways` path to causal pathways - `-s | --spek` path to spek file (default to stdin) #### Default Esteemer Criteria Provides a passthrough for all acceptable candidates. Any candidate that is `acceptable_by` is annotated as `promoted_by http://example.com/slowmo#esteemer_default_criteria` <file_sep># Esteemer Scripts The main purpose of Esteemer stage is to promote the candidate messages that are marked as accepted by think pudding. The first stage `presteemer` creates a sub graph of all candidates that includes their `AncestorPerformer` attribute so that esteemer has that available to do its work. Then, the `esteemer` script should mark one candidate per ancestor performer in the graph as `promoted` based on some criteria (tbd). ## Presteemer Constructs a graph of all candidates with their AncestorPerformer attributes using the spek loaded in. ### Use Options: - `-h | --help` print help and exit - `-s | --spek` path to spek file (default to stdin) ##### Example ```bash $DISPLAY_LAB_HOME/esteemer/bin/presteemer.sh \ -s ./outputs/spek_tp.json \ 2>> vignette.log > ./outputs/spek_pe.ttl ``` #### Query inside ```sql PREFIX obo: <http://purl.obolibrary.org/obo/> PREFIX slowmo: <http://example.com/slowmo#> construct { ?candidate ?p ?o . ?candidate obo:RO_0000091 ?disposition . ?disposition ?p2 ?o2 . } FROM <http://localhost:3030/ds/spek> WHERE { ?candidate a obo:cpo_0000053 . ?candidate ?p ?o . ?candidate obo:RO_0000091 ?disposition . ?disposition ?p2 ?o2 . ?candidate slowmo:AncestorPerformer ?performer . } ``` ### Esteemer Evaluate acceptable candidates for promotion to figure generation. #### Use Options: - `-h | --help` print help and exit - `-p | --pathways` path to causal pathways - `-s | --spek` path to spek file (default to stdin) ##### Example ```bash $DISPLAY_LAB_HOME/esteemer/bin/esteemer.sh \ -s ./outputs/spek_pe.ttl \ -p ${KNOWLEDGE_BASE_DIR}/causal_pathways.json \ 2>> vignette.log > .outputs/spek_es.json ``` #### Default Esteemer Criteria Provides a passthrough for all acceptable candidates. Any candidate that is `acceptable_by` is annotated as `promoted_by http://example.com/slowmo#esteemer_default_criteria` <file_sep>#!/usr/bin/env bash # Usage message read -r -d '' USE_MSG <<'HEREDOC' Usage: presteemer.sh -h presteemer.sh -s spek.json Presteemer reads a spek from stdin or provided file path. Options: -h | --help print help and exit -s | --spek path to spek file (default to stdin) HEREDOC # Parse args PARAMS=() while (("$#")); do case "$1" in -h | --help) echo "${USE_MSG}" exit 0 ;; -s | --spek) SPEK_FILE="${2}" shift 2 ;; --) # end argument parsing shift break ;; -* | --*=) # unsupported flags echo "Aborting: Unsupported flag $1" >&2 exit 1 ;; *) # preserve positional arguments PARAMS+=("${1}") shift ;; esac done # Check if FUSEKI is running. FUSEKI_PING=$(curl -s -o /dev/null -w "%{http_code}" localhost:3030/$/ping) if [[ -z ${FUSEKI_PING}} || ${FUSEKI_PING} -ne 200 ]]; then # Error echo >&2 "Fuseki not running locally." # Try to start custom fuseki locally # FUSEKI_DIR=/opt/fuseki/apache-jena-fuseki-3.10.0 ${FUSEKI_HOME}/fuseki-server --mem --update /ds 1>fuseki.out 2>&1 & exit 1 fi read -r -d '' GET_CANDIDATES_AND_PERFORMER_GRAPH << \ 'SPARQL' PREFIX obo: <http://purl.obolibrary.org/obo/> PREFIX slowmo: <http://example.com/slowmo#> construct { ?candidate ?p ?o . ?candidate obo:RO_0000091 ?disposition . ?disposition ?p2 ?o2 . } FROM <http://localhost:3030/ds/spek> WHERE { ?candidate a obo:cpo_0000053 . ?candidate slowmo:AncestorPerformer ?performer . ?candidate obo:RO_0000091 ?disposition . ?candidate ?p ?o . ?disposition ?p2 ?o2 . } SPARQL # Read from SPEK_FILE or pipe from stdin # Use '-' to instruct curl to read from stdin if [[ -z ${SPEK_FILE} ]]; then SPEK_FILE="-" fi FUSEKI_DATASET_URL="http://localhost:3030/ds" SPEK_URL="${FUSEKI_DATASET_URL}/espek" # Load spek into fuseki curl --silent PUT \ --data-binary "@${SPEK_FILE}" \ --header 'Content-type: application/ld+json' \ "${FUSEKI_DATASET_URL}?graph=${SPEK_URL}" >&2 # run construct performer query curl --silent GET \ --data-binary "${GET_CANDIDATES_AND_PERFORMER_GRAPH}" \ --header 'Content-type: application/sparql-query' \ "${FUSEKI_DATASET_URL}/query"<file_sep># Esteemer stage of the precision feedback pipeline Currently, there are two implementations—a bash shellscript that uses the Fuseki server and a python implementation the wotrks with an in-memory graph. * [Bash Esteemer script](bin/readme.md) * [Python Esteemer module](python/readme.md)
f4caa2e2345481fdf590a485719990b1dd28d09e
[ "TOML", "Python", "Markdown", "Shell" ]
9
TOML
Display-Lab/esteemer
2d043525de8a8810f99850731b55ff5ae66b1038
d6da4fffb85acddb0d1d5437aa11aba8e402704f
refs/heads/master
<repo_name>jamal-Bahammou/REVENT-S<file_sep>/src/app/config/firebase.jsx import firebase from 'firebase'; import 'firebase/firestore'; // Your web app's Firebase configuration const firebaseConfig = { apiKey: "<KEY>", authDomain: "revents-775b9.firebaseapp.com", databaseURL: "https://revents-775b9.firebaseio.com", projectId: "revents-775b9", storageBucket: "revents-775b9.appspot.com", messagingSenderId: "658907608715", // appId: "1:658907608715:web:a267dad7ebf97fc1" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); const firestore = firebase.firestore(); const settings = { timestampsInSnapshots: true } firestore.settings(settings); export default firebase;<file_sep>/src/app/data/sampleData.jsx const sampleData = { events: [ { id: '1', title: 'Trip to Tower of London', date: '2019-03-27T18:00:00', category: 'culture', description: 'A software engineer develops various applications that enable users to accomplish tasks on their personal computers and electronic devices. Often, software engineers are employed by software publishers or computer systems design firms.', city: 'London, UK', venue: "Tower of London, St Katharine's & Wapping, London", venueLatLng: { lat: 40.7484405, lng: -73.98566440000002 }, hostedBy: 'Firas', hostPhotoURL: '/assets/firas.jpg', attendees: [ { id: 'a', name: 'David', photoURL: '/assets/davidcunha.xyz.jpg' }, { id: 'b', name: 'Jeffnhorner', photoURL: '/assets/jeffnhorner.jpg' } ] }, { id: '2', title: 'Trip to Punch and Judy Pub', date: '2019-04-24T18:00:59', category: 'drinks', description: 'A programmer, developer, coder, or software engineer is a person who creates computer software. The term computer programmer can refer to a specialist in one area of computers, or to a generalist who writes code for many kinds of software.', city: 'London, UK', venue: 'Punch & Judy, Henrietta Street, London, UK', venueLatLng: { lat: 51.5118074, lng: -0.12300089999996544 }, hostedBy: 'Vegangirlthatcodes', hostPhotoURL: '/assets/vegangirlthatcodes.jpg', attendees: [ { id: 'b', name: 'Fidalgo', photoURL: '/assets/fidalgo.dev.jpg' }, { id: 'a', name: 'Luca', photoURL: '/assets/lucabockmann.jpg' } ] } ] }; export default sampleData;
f48d1f111ebbffe0eed5f823ee51885d33acf20e
[ "JavaScript" ]
2
JavaScript
jamal-Bahammou/REVENT-S
29e8f5e46b2566dd85968982964803227f1e3fa5
16922820777fd9acdaf0eec2822b1a5f231d3755
refs/heads/main
<file_sep># project-euler These are my solutions for the problems at [Project Euler](https://projecteuler.net).<file_sep>function multiplesOf3and5(number) { let res = 0; let counter = 1; while (counter < number) { if (counter % 3 === 0) res += counter; else if (counter % 5 === 0) res += counter; counter++; } return res; } console.log(multiplesOf3and5(1000));
a89c607846150c8884e17f7cceee33291a418a91
[ "Markdown", "JavaScript" ]
2
Markdown
blendhamiti/project-euler
6326ac5878ee27bb320148b68a79836fabc71e9c
df6343110f945db32484b93ed89abf33ea3d6592
refs/heads/main
<repo_name>WilliamRoll/web-scraping-challenge<file_sep>/README.md # web-scraping-challenge In this assignment I scraped multiple different websites for Mars data as well as images. Utilized splinter to navigate to the sites and used BeautifulSoup to find and parse the data. Mission_to_Mars contains the Jupyter Notebook. Scrape_mars is the python file that will perform the scraping in the main directory. app is the Python file that will connect to Mongo, and scrape. HTML index file is contained within templates folder. Grader: If an "IndexError: list index out of range" occurs, please just refresh the page. For some reason this will occur when trying to scrape, while other times it will not. Refreshing the page will allow it to run correctly. Thanks! <file_sep>/scrape_mars.py #Dependency import pandas as pd import requests from bs4 import BeautifulSoup from splinter import Browser #initialyzing the browser def init_browser(): #load the chrome driver executable_path ={'executable_path': 'chromedriver.exe'} return Browser('chrome', **executable_path, headless=False) #scraping def scrape(): #Nasa Mars News Site browser = init_browser() #Scraping data from the existing NASA Mars News website url = "https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest" browser.visit(url) #find latest News Title and Paragraph by beautiful soup html = browser.html soup = BeautifulSoup(html, 'html.parser') content_title = soup.find_all('div', class_='content_title') teaser_body = soup.find_all('div', class_='article_teaser_body') #list items to store info article_header_ls = [] article_body_ls = [] #loop through titles for title in content_title: art_title = title.find_all('a') #loop through article titles for art in art_title: first_title = art.text.strip() article_header_ls.append(first_title) #loop through body for body in teaser_body: body = body.text.strip() article_body_ls.append(body) #set header and body 1 variables article_1_header = article_header_ls[0] article_1_body = article_body_ls[0] #Image Scrape #visit the URL for the JPL Featured Space Image by splinter url_2 = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars" browser.visit(url_2) html_2 = browser.html soup_2 = BeautifulSoup(html_2, 'html.parser') images = soup_2.find_all('a', class_='button fancybox') #loop through images for image in images: relative_img_path = image["data-fancybox-href"] base_url = 'https://www.jpl.nasa.gov' featured_image_url = base_url + relative_img_path #Mars Facts Table url_3 = 'https://space-facts.com/mars/' tables = pd.read_html(url_3) tables #convert the table to a dataframe df = tables[0] df #convert to an HTML html_table = df.to_html() #Mars Hemispheres #visit the Mars Hemispheres web url url_4 = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars' browser.visit(url_4) #HTML object and parser html_4 = browser.html soup_4 = BeautifulSoup(html_4, 'html.parser') #create list for hemisphere urls hemisphere_img_urls=[] #base url to be used to navigate to enhanced image urls base_url = 'https://astrogeology.usgs.gov' items = soup_4.find_all('div', class_='item') #loop through items for item in items: title = item.find("h3").text h_img_url = item.find("a", class_="itemLink product-item")["href"] #visit the img urls browser.visit(base_url + h_img_url) image_html = browser.html soup_5 = BeautifulSoup(image_html, "html.parser") full_img_url = base_url + soup_5.find("img", class_="wide-image")["src"] hemisphere_img_urls.append({"title":title, "img_url":full_img_url}) #mars data dictionary Mars_data = { "Mars_News_Title": article_1_header, "Mars_News_Paragraph": article_1_body, "Mars_Featured_Image": featured_image_url, "Mars_Facts": html_table, "Mars_Hemisphere_Images": hemisphere_img_urls } browser.quit() return Mars_data
8c91c73a08d21f22954164e3abd5b37e2aae7327
[ "Markdown", "Python" ]
2
Markdown
WilliamRoll/web-scraping-challenge
eafa0772c2d428a0912dfcda72f23a2d42c3cba2
8c5db8c18bdb1cc390e949cfb08d519bcb5c1c30
refs/heads/master
<file_sep># SourceTestTesse Download and then open the directory, open the index.html file and view other articles via the links on that page <file_sep>function draw(rows) { var string = ''; var count = 0, count1 = 0, k = 0; for(var i = 1; i <= rows; ++i) { for(var space = 1; space <= rows-i; ++space) { string = string + " "; ++count; } while(k != 2*i-1) { if (count <= rows-1) { string = string + LayDu(parseInt(i)+parseInt(k))+" "; ++count; } else { ++count1; string = string +LayDu(parseInt(i)+parseInt(k)-2*count1)+ " " ; } ++k; } count1 = count = k = 0; string = string +"</br>"; } console.log(string); return string; } function LayDu(num) { return num % 10; } function VeTamGiac() { var rows = document.getElementById('rows').value; console.log(rows); // Draw tam giac // console.log(draw(parseInt(rows))); document.getElementById('result').innerHTML = draw(parseInt(rows)); }; <file_sep>// Bài 2: var countryArray = new Array(); var persents = new Array(); countryArray[0] = "Anh"; countryArray[1] = "Phap"; countryArray[2] = "Duc"; countryArray[3] = "Nga"; countryArray[4] = "Nhat"; countryArray[5] = "Viet Nam"; countryArray[6] = "HoaKy"; function renderForm() { var data = ""; for (var i = 0; i < countryArray.length; i++) { data =data + countryArray[i] +"<input type='text' width='30px' id='" +countryArray[i] +"'/> <br/>"; } return data; } document.getElementById("country").innerHTML = renderForm(); function _style_Line_Chart(countryArray, persents) { for (var i = 0; i < countryArray.length; i++) { var idStyle = document.getElementById("barLine" + countryArray[i]); if (persents[i] != "") { idStyle.style.height = "25px"; idStyle.style.width = persents[i] * 2 + "px"; idStyle.style.background = "red"; } else { idStyle.style.width = "0px"; } } return; } function drawLineBar() { var data = ""; for (i = 0; i < countryArray.length; i++) { persents[i] = document.getElementById(countryArray[i]).value; data += "<tr><td>" + countryArray[i] + "</td><td class='result'> <div id='" + "barLine" + countryArray[i] + "'></div>" + persents[i] + "%</td>"; } document.getElementById("barLine").innerHTML = data; console.log(persents); _style_Line_Chart(countryArray, persents); return; } <file_sep>function draw(rows) { var string = ''; for (i = 1; i <= rows; i++) { for (j = i; j >= 1; j--) { string = string + ' &nbsp; ' + LayDu(j); } string = string + '</br>'; } return string; } function LayDu(num) { return num % 10; } function VeTamGiac() { var rows = document.getElementById('rows').value; console.log(rows); // Draw tam giac // console.log(draw(parseInt(rows))); document.getElementById('result').innerHTML = draw(parseInt(rows)); }; <file_sep>var hour = document.getElementById('hour'); var minute = document.getElementById('minute'); var second = document.getElementById('second'); var start = document.getElementById('start'); var stop = document.getElementById('stop'); var reset = document.getElementById('reset'); function renderTime(time) { var temp = ''; if (time < 10) { temp = temp + '0' + time.toString(); } else temp = temp + time.toString(); return temp; } start.onclick = function () { var countSecond = 0; var countMinute = 0; var countHour = 0; var _second = setInterval(() => { if (countSecond > 9) { minute.innerHTML = renderTime(++countMinute); countSecond = 1; second.innerHTML = renderTime(countSecond); if (countMinute > 59) { hour.innerHTML = renderTime(++countHour); countMinute = 0; minute.innerHTML = renderTime(countMinute); } } else { second.innerHTML = renderTime(++countSecond); minute.innerHTML = renderTime(countMinute); hour.innerHTML = renderTime(countHour); } }, 100); stop.onclick = function () { clearInterval(_second); }; reset.onclick = function () { clearInterval(_second); hour.innerHTML = "00"; minute.innerHTML = "00"; second.innerHTML = "0"; } }
73293c247f1792130c0b7799cde7180475f126dd
[ "Markdown", "JavaScript" ]
5
Markdown
letangco/SourceTestTesse
6331aab7cd39579c35c030bc4f819c0f2d2844b0
5bca1d5728b3501257fc4cdc0e81afdc7cb05bfc
refs/heads/master
<file_sep> <div class="general-product-block man-product-block" data-gender-type="man"> <? foreach ($products as $item):?> <div class="product-block"> <?if($item['discount'] != 0):?> <div class="discount"><span>-<?=$item['discount']?>%</span></div> <?endif;?> <a class="product-link" href="/product/card/?id=<?=$item['id']?>"> <img src="/img/product_img/<?=$item['photo']?>" alt="<?=$item['name']?>"> <div class="product-text"> <h4><?=$item['name']?></h4> <?if(isset($item['discount-price'])):?> <div class="price-block"> <p class="old-price">$<?=$item['price']?></p> <p class="new-price">$<?=$item['discount-price']?></p> </div> <?else:?> <p>$<?=$item['price']?></p> <?endif;?> </div> </a> </div> <?endforeach?> </div> <div class="crumbs"> <nav class="nav-numbers"> <ul class="numbers"> <?for ($i = 1; $i <= $pages; $i++):?> <li><a href="/product/pag/?page=<?=$i?>"><?=$i?></a></li> <?endfor;?> </ul> </nav> <a class="nav-button" href="/product/catalog">View All -></a> </div><file_sep><div class="container header-flex"> <div class="header-left"> <a class="logo" href="/home/"><img src="/img/logo/logo.png" alt="Logo">BRAN<span class="pink">D</span></a> </div> <div class="header-right"> <a class="cart-img" href="/cart/"><img src="/img/icons/cart.png" alt="Cart">(<span class = "cart-img-span"><?=$ngoods?></span>)</a> <a class="my-account" href="#">My&nbspAccount&nbsp</a> </div> </div> <file_sep><?php use app\engine\Render; class RenderTest extends \PHPUnit\Framework\TestCase { protected $fixture; /** * @dataProvider providerRender */ public function testRender($content, $template) { $this->assertContains($content, $this->fixture->renderTemplate($template, [])); } public function providerRender() { return [ ["</h2>", "index"], ["HOME","menu"] ]; } protected function setUp() { $this->fixture = new Render(); } protected function tearDown() { $this->fixture = null; } }<file_sep><?php namespace app\models\repositories; use app\models\entities\Feedback; use app\models\Repository; class FeedbackRepository extends Repository { public function getTableName() { return 'feedback'; } public function getEntityClass() { return Feedback::class; } }<file_sep><?php namespace app\controllers; use app\engine\Request; use app\models\entities\Cart; use app\models\repositories\CartRepository; use app\models\repositories\ProductRepository; class CartController extends Controller { public function actionIndex() { echo $this->render('cart', [ 'products' => (new CartRepository())->getBasket(session_id()) ]); } public function actionAddToCart() { //Поместить товар в корзину $id = (new Request())->getParams()['id']; $cart = (new CartRepository())->getOneWhere('product_id',$id); if(!empty($cart)) { if (session_id() == $cart->session_id) { $price = ((new ProductRepository())->getOne($id))->price; $quantity = $cart->quantity; $quantity++; $cart->setSubtotal($quantity * $price); $cart->setQuantity($quantity); (new CartRepository())->save($cart); } } else { (new CartRepository())->save(new Cart(null, session_id(), $id , null , 1, ((new ProductRepository())->getOne($id))->price)); }; $count = (new CartRepository())->getSumWhere('quantity', 'session_id', session_id()); $response = ['ngoods' => $count]; header('Content-Type: application/json'); echo json_encode($response); } public function actionDelete() { //Прежде чем удалять, убедимся что сессия совпадает $id = (new Request())->getParams()['id']; $basket = (new CartRepository())->getOneWhere('product_id',$id); if (session_id() == $basket->session_id) { (new CartRepository())->delete($basket); $count = (new CartRepository())->getSumWhere('quantity','session_id', session_id()); echo json_encode(['id' => $id, 'ngoods' => $count]); } } }<file_sep><?php use app\engine\Autoload; class AutoloadTest extends \PHPUnit\Framework\TestCase { protected $fixture; /** * @dataProvider providerLoadClass */ public function testLoadClass($className) { $this->assertNull($this->fixture->loadClass($className)); } public function providerLoadClass() { return [ ['..\app\engine\Db'], ['..\app\engine\Request'], ['..\app\controllers\Controller'], ['..\app\controllers\ProductController'], ['..\app\controllers\UserController'] ]; } protected function setUp() { $this->fixture = new Autoload(); } protected function tearDown() { $this->fixture = null; } }<file_sep><?php namespace app\models\entities; class Products extends DataEntity { public $id; public $name; public $description; public $price; public $properties = [ 'name' => false, 'description' => false, 'price' => false ]; public function __construct($id = null, $name = null, $description = null, $price = null) { $this->id = $id; $this->name = $name; $this->description = $description; $this->price = $price; } public function setName($name) { $this->name = $name; $this->properties['name'] = true; } public function setDescription($description) { $this->description = $description; $this->properties['description'] = true; } public function setPrice($price) { $this->price = $price; $this->properties['price'] = true; } public function getName() { return $this->name; } public function getDescription() { return $this->description; } public function getPrice() { return $this->price; } }<file_sep><?php namespace app\controllers; use app\engine\Request; use app\models\entities\Feedback; use app\models\repositories\FeedbackRepository; class FeedbackController extends Controller { public function actionFeedback() { $feedback = (new FeedbackRepository())->getAll(); echo $this->render("feedback", [ 'feedback' => $feedback ]); } public function actionInsert() { $userData = (new Request())->getParams(); $fb = new Feedback(); $fb->setUser_name($userData['name']); $fb->setText($userData['text']); $fb->setDate(date("Y-m-d H:i:s")); $fb->setProductId($userData['id']); $fb->setStatus('new'); (new FeedbackRepository())->save($fb); header('Location: /product/card/?id=' . $userData['id']); exit(); } }<file_sep><?php namespace app\models\entities; class Users extends DataEntity { public $id; public $login; public $nick_name; public $email; public $is_confirmed; public $role; public $password_hash; public $created_at; public $hash; public $properties = [ 'hash' => false ]; public function __construct($id = null, $login = null, $nick_name = null, $email = null, $is_confirmed = null, $created_at = null, $password_hash = null, $role = null, $hash = null) { $this->id = $id; $this->login = $login; $this->nick_name = $nick_name; $this->email = $email; $this->is_confirmed = $is_confirmed; $this->role = $role; $this->password_hash = $<PASSWORD>_<PASSWORD>; $this->created_at = $created_at; $this->hash = $hash; } public function setHash($hash) { $this->hash = $hash; $this->properties['hash'] = true; } }<file_sep><?if (!$enter):?> <div class="reg"> <h4 class="guest-h4">Already registed?</h4> <p class="guest-p reg-margin">Please log in. </p> </div> <form action="/user/login" method="post"> <div class="auth-form"> <label for="InputEmail"></label> <input class="auth-form-input" name="login" type="text" id="InputEmail" placeholder="Enter login"> </div> <div class="auth-form"> <label for="InputPassword"></label> <input class="auth-form-input" name="password" type="<PASSWORD>" id="InputPassword" placeholder="<PASSWORD>"> </div> <div class="auth-form remember"> <input name="remember" type="checkbox" id="Check"> <label for="Check">Remember me</label> </div> <div class="auth-form"> <button class="auth-button" type="submit" name="login_user">LOGIN</button> <a class="auth-button" href="/">Registration</a> </div> </form> <?else:?> <div class="reg-form"> <h4> Wellcom to our site!</h4> <a class="escape" href='/user/logout'>Escape</a> </div> <?endif;?> <file_sep><?php namespace app\models\repositories; use app\models\Repository; use app\models\entities\Users; class UserRepository extends Repository { public function getName() { return $this->isAuth() ? $_SESSION['login'] : "Guest"; } public function auth($login, $pass) { $user = $this->getOneWhere('login', $login); if (!empty($user)) { if (password_verify($pass, $user->password_hash)) { $_SESSION['auth'] = [ 'id' => $user->id, 'login' => $user->login, ]; return true; } return false; } } public function isAuth() { return isset($_SESSION['auth']['login']) ? true: false; } public function setCookies() { $hash = uniqid(rand(), true); $id = $_SESSION['auth']['id']; $user = $this->getOneWhere('id', $id); $user->setHash($hash); (new UserRepository())->save($user); setcookie("hash", $hash, time() + 3600); } public function getTableName() { return "users"; } public function getEntityClass() { return Users::class; } }<file_sep><?php namespace app\models\entities; class Cart extends DataEntity { public $id; public $session_id; public $product_id; public $user_id; public $quantity; public $subtotal; public $properties = [ 'quantity' => false, 'subtotal' => false ]; public function __construct($id = null, $session_id = null, $product_id = null, $user_id = null, $quantity = null, $subtotal = null) { $this->id = $id; $this->session_id = $session_id; $this->product_id = $product_id; $this->user_id = $user_id; $this->quantity = $quantity; $this->subtotal = $subtotal; } public function setQuantity($quantity) { $this->quantity = $quantity; $this->properties['quantity'] = true; } public function setSubtotal($subtotal) { $this->subtotal = $subtotal; $this->properties['subtotal'] = true; } public function getQuantity () { return $this->quantity; } }<file_sep><?php namespace app\models\entities; class Feedback extends DataEntity { public $id; public $user_id; public $product_id; public $user_name; public $text; public $date; public $status; public $likes; public $properties = [ 'text' => false, 'user_name' => false, 'status' => false, 'product_id' => false ]; public function __construct($id = null, $user_id = null, $product_id = null, $text = null, $user_name = null, $date = null, $status = null, $likes = null) { $this->id = $id; $this->user_id = $user_id; $this->product_id = $product_id; $this->text = $text; $this->user_name = $user_name; $this->date = $date; $this->status = $status; $this->likes = $likes; } public function setText($text) { $this->text = $text; $this->properties['text'] = true; } public function setUser_name($user_name) { $this->user_name = $user_name; $this->properties['user_name'] = true; } public function setStatus($status) { $this->status = $status; $this->properties['status'] = true; } public function setDate($date) { $this->date = $date; } public function setProductId($product_id) { $this->product_id = $product_id; $this->properties['product_id'] =true; } public function getText() { return $this->text; } public function getUser_name() { return $this->user_name; } }<file_sep><!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/css/stylecss.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <title>Document</title> </head> <body> <div class="main-container"> <div class="main"> <header class="header"> <?=$header?> </header> <nav class="one"> <?= $menu?> </nav> <div class="content container"> <div class="content-block"> <?=$content?> </div> <div class="auth-block"> <?=$auth?> </div> </div> </div> </div> <footer class="footer"> <?= date(Y)?> </footer> </body> </html><file_sep><?php namespace app\controllers; use app\interfaces\IRenderer; use app\models\repositories\CartRepository; use app\models\repositories\UserRepository; abstract class Controller implements IRenderer { protected $action; protected $layout = 'main'; protected $useLayout = true; private $renderer; public function __construct(IRenderer $renderer) { $this->renderer = $renderer; } public function runAction($action = null) { $this->action = $action ?: 'index'; $method = "action" . ucfirst($this->action); if (method_exists($this, $method)) { $this->$method(); } else { echo "404"; } } public function render($template, $params = []) { if ($this->useLayout) { return $this->renderTemplate("layouts/{$this->layout}",[ 'content' => $this->renderTemplate($template, $params), 'menu' => $this->renderTemplate('menu', $params), 'auth' => $this->renderTemplate('auth', [ 'enter' => (new UserRepository())->isAuth() ]), 'header' => $this->renderTemplate('header', [ 'ngoods' => (new CartRepository())->getSumWhere('quantity', 'session_id', session_id())]), ]); } else { return $this->renderTemplate($template, $params); } } public function renderTemplate($template, $params = []) { return $this->renderer->renderTemplate($template, $params); } }<file_sep><?php namespace app\controllers; use app\engine\Request; use app\models\entities\Users; use app\models\repositories\UserRepository; class UserController extends Controller { public function actionLogout() { session_destroy(); header("Location: /"); exit(); } public function actionLogin() { $request = new Request(); $userData = $request->getParams(); if (!empty($userData)) { $login = $userData['login']; $pass = $userData['password']; } if ((new UserRepository())->auth($login, $pass)) { Die("Не верный пароль!"); } else { if ($userData['remember']) { (new UserRepository())->setCookies(); } header("Location: /"); } } public function actionSignUp() { $request = new Request(); $userData = $request->getParams(); if (empty($userData['nick_name'])) { throw new \Exception('Не передан Name'); } if (empty($userData['e-mail'])) { throw new \Exception('Не передан E-mail'); } if (empty($userData['password'])) { throw new \Exception('Не передан Password'); } if (empty($userData['login'])) { throw new \Exception('Не передан Login'); } if (!empty ($userData)) { $user = new Users(); $user->id = null; $user->login = $userData['login']; $user->nick_name = $userData['nick_name']; $user->email = $userData['e-mail']; $user->password_hash = password_hash($userData['password'], PASSWORD_DEFAULT); $user->is_confirmed = false; $user->created_at = date("Y-m-d H:i:s"); $user->role = 'user'; $user->hash = uniqid(rand(), true); (new UserRepository())->save($user); header('Location: / '); exit(); } } }<file_sep><div class="table-position"> <table class="table"> <thead class="table-header"> <tr> <th scope="col">Product Details</th> <th scope="col">unite Price</th> <th scope="col">Quantity</th> <th scope="col">shipping</th> <th scope="col">Subtotal</th> <th scope="col">ACTION</th> </tr> </thead> <tbody id="cart"> <?if (is_array($products)):?> <? foreach ($products as $item):?> <tr class="table-row" data-table-row="<?=$item['id']?>"> <th scope="row"> <a class="row-a" href="/product/card/?id=<?=$item['id']?>"> <img class="table-row-img"src="/img/product_img/<?=$item['photo']?>" alt="product<?=$item['id']?>"> <h4><?=$item['name']?></h4> <p>Color:<span><?=$item['color']?></span></p> <p class="row-p" >Size:<span><?=$item['size']?></span></p> </a> </th> <?if (isset($item['discount-price'])):?> <td>$<?=$item['discount-price']?></td> <?else:?> <td>$<?=$item['price']?></td> <?endif;?> <td><input id="unt-qnt" class="unt-qnt" data-id="<?=$item['id']?>" type="number" value="<?=$item['quantity']?>" placeholder="1" min="1" step="1"></td> <td>FREE</td> <td id="subtotal" data-id="<?=$item['id']?>">$<?=$item['subtotal']?></td> <td> <a class="delete-item" data-id="<?=$item['id']?>" href="#"> <img src="/img/icons/cancel.png" alt="cancel"> </a> </td> </tr> <?endforeach;?> <?endif;?> </tbody> </table> <div><?=$msg?></div> <footer class="cart-footer"> <div class="cart-button"> <a href="/cart/clear">CLEAR SHOPPING CART</a> <a href="/product/catalog">CONTINUE SHOPPING</a> </div> <form id="review-form" action="/cart/checkout" method="post"> <select class="country" name="Country"> <option value="Country">Select Country...</option> <option value="Bangladesh">Bangladesh</option> <option value="USA">USA</option> </select> <input class="country" type="text" name="telephone" placeholder="+7 (111) 111-11-11" required> <div class="cart-form"> <div class="cart-total"> <h5>Sub Total $ <span id="cart-subtotal"><?=$total?></span></h5> <h4>GRAND TOTAL $<span id="cart-grandtotal"><?=$total?></span></h4> <a href="/cart/checkout"><button class="proceed-button">proceed to checkout</button></a> </div> </div> </form> </footer> </div> <script> (function($) { $(function () { $('#cart').on('click', '.delete-item', function () { //Получаем значение id товара из корзины var id = $(this).attr('data-id'); // Отправляем запрос на изменение количества $.ajax({ url: "/cart/delete/", type: "POST", dataType : "json", data:{ id: id }, error: function() {alert("Something went wrong ...");}, success: function(answer){ // Перерисовываем корзины $('.cart-img-span').text(answer.ngoods); $('tr[data-table-row="' + answer.id + '"]').remove(); } }) }); }); })(jQuery); </script><file_sep><?php define("DIR_ROOT", $_SERVER['DOCUMENT_ROOT']); define("DS", DIRECTORY_SEPARATOR); define("ON_PAGE", '3');<file_sep><h1>HOME</h1> <div class="shipping-adress"> <?php if (!empty($error)): ?> <div style="background-color: red;padding: 5px;margin: 15px"><?= $error ?></div> <?php endif; ?> <div class="guest"> <h4 class="guest-h4">Register and save time!</h4> <p class="guest-p">Register with us for future convenience</p> <p class="guest-p guest-p-margin">Fast and easy checkout</p> <p class="guest-p">Easy access to your order history and status</p> </div> <form action="/user/signUp" method="post"> <div class="auth-form"> <label for="inputEmail"></label> <input class="auth-form-input" name="login" type="text" id="inputLogin" placeholder="Enter login"> </div> <div class="auth-form"> <label for="inputPassword"></label> <input class="auth-form-input" name="password" type="<PASSWORD>" id="inputPassword" placeholder="<PASSWORD>"> </div> <div class="auth-form"> <label for="inputEmail"></label> <input class="auth-form-input" name="e-mail" type="e-mail" id="inputEmail" placeholder="Enter e-mail"> </div> <div class="auth-form"> <label for="inputEmail"></label> <input class="auth-form-input" name="nick_name" type="text" id="inputName" placeholder="Enter your name"> </div> <div class="auth-form remember"> <input name="remember" type="checkbox" id="reg"> <label for="reg">Remember me</label> </div> <div class="auth-form"> <button class="guest-button" type="submit" name="reg_user">Confirm</button> </div> </form> </div><file_sep> <!-- Вывод информации о товаре --> <a class="back-arrow" href="/product/pag"> <img src="/img/icons/left-arrow.png" alt="Back arrow"> <span>Back to product page</span> </a> <div class="product-info"> <div class="product-photo"> <img src="/img/product_img/<?=$product->photo?>" alt="product"> </div> <div class="description-block"> <section class="prod-description"> <div class="gray-line"><div class="pink-line"></div></div> <h2><?=$product->name?></h2> <p class="prod-description-text"><?=$product->description?></p> <div class="prod-point"> <p>MATERIAL : <span> <?=$product->material?></span></p> <p>DESIGNER : <span> <?=$product->designer?></span></p> </div> <?if(isset($params->discount_price)):?> <div class="price-block"> <p class="old-price single-price">$<?=$product->price?></p> <p class="new-price single-price">$<?=$product->discount_price?></p> </div> <?else:?> <p>$<?=$product->price?></p> <?endif;?> <div class="prod-line"></div> <div class="select-title"> <div> <h4>CHOOSE SIZE</h4> </div> </div> <form action="" method="post"> <div class="select-block"> <select class="size" name="size"> <?foreach ($product->size as $size):?> <option value="<?=$size?>"><?=$size?></option> <?endforeach?> </select> </div> <a class="cart-button-prod" data-id="<?=$product->id?>" href="#">Add to Cart</a> </form> <p><?=$status?></p> </section> </div> </div> <!-- Форма добавления отзыва о товаре --> <div class="feedback-form"> <h4>Here you can leave your feedback!</h4> <form class = "feedback-form-fields" action="/feedback/insert/" method="post"> <input name="id" value="<?=$product->id?>" type="hidden"> <p>Your name:</p> <input name="name" type="text" required> <p>Feedback:</p> <textarea name="text" required></textarea> <input name="submit" value="Send" type="submit"> </form> </div> <!-- Вывод всех отзывов о конктретном товаре --> <div class="feedback-block"> <h3>Feedbacks</h3> <?if (is_array($fb)):?> <?foreach ($fb as $feedback):?> <div class = "feedback-text"> <span class="feedback-user-name"><?= $feedback["user_name"]?></span> <span class="feedback-date"><?= $feedback["date"]?></span> <p><?=$feedback["text"]?></p> <!-- Добавление и показ лайков к отзыву --> <div class="feedback-likes"> <a class="feedback-likes-btn" href="/single_page/like/<?=$feedback['id']?>/?backid=<?=$product->id?>"" data-id="<?=$feedback['id']?>" > <img src="/img/icons/like.png" alt="Like"> <span><?=$feedback['likes']?></span> </a> </div> </div> <?endforeach?> <?else:?> <p><?=$fb?></p> <?endif;?> </div> <script> (function($) { $(function () { $('.prod-description').on ('click', '.cart-button-prod', function(){ var id = $(this).attr("data-id"); $.ajax({ url: "/cart/AddToCart/", type: "POST", dataType : "json", data:{ id: id }, error: function() {alert("Something went wrong ...");}, success: function(answer){ $('.cart-img-span').text(answer.ngoods); } }) }); }); })(jQuery); </script> <file_sep><?php namespace app\controllers; use app\models\repositories\FeedbackRepository; use app\models\repositories\ProductRepository; class ProductController extends Controller { public function actionIndex() { echo $this->render("index"); } public function actionCatalog() { $products = (new ProductRepository())->getAll(); echo $this->render("catalog", [ 'products' => $products ]); } public function actionCard() { $id = $_GET['id']; $product = (new ProductRepository())->getOne($id); echo $this->render("card", [ 'product' => $product, 'fb' => (new FeedbackRepository())->getAllWhere('product_id', $id), ]); } public function actionPag() { $page = isset($_GET["page"]) ? (int)$_GET["page"] : 1; $shift = ($page - 1) * ON_PAGE; $result = (new ProductRepository())->getLimit($shift, ON_PAGE); $count = count((new ProductRepository())->getAll()); $pages = ceil($count / ON_PAGE); echo $this->render("catalog", [ 'products' => $result, 'pages' => $pages ]); } }<file_sep><!-- Форма добавления отзыва о товаре --> <div class="feedback-form"> <h4>Here you can leave your feedback!</h4> <form class = "feedback-form-fields" action="?c=feedback&a=insert" method="post"> <p>Your name:</p> <input name="name" type="text" required> <p>Feedback:</p> <textarea name="text" required></textarea> <input name="submit" value="Send" type="submit"> </form> <!-- Вывод ошибок загрузки --> <?php if (!empty($error)): ?> <p class='upload_form_error'> <?= $error ?></p> <?php endif; ?> </div> <!-- Вывод всех отзывов о конктретном товаре --> <div class="feedback-block"> <h3>Feedbacks</h3> <?foreach ($feedback as $fb):?> <div class = "feedback-text"> <span class="feedback-user-name"><?= $fb["user_name"]?></span> <span class="feedback-date"><?= $fb["date"]?></span> <p><?=$fb["text"]?></p> </div> <?endforeach?> </div> <file_sep><?php namespace app\models\repositories; use app\models\Repository; use app\models\entities\Cart; class CartRepository extends Repository { public function getCount($session) { $sql = "SELECT count(*) as count FROM `basket` WHERE `session` = :session"; return $this->db->queryOne($sql, ['session' => $session])['count']; } public function getBasket($session) { $sql = "SELECT * FROM cart c,products p WHERE c.product_id=p.id AND session_id = :session"; return $this->db->queryAll($sql, ['session' => $session]); } public function getTableName() { return "cart"; } public function getEntityClass() { return Cart::class; } }
0a289415566b6f4f8633e70849eedad394770c06
[ "PHP" ]
23
PHP
StepanovaElena/PHP-2
b7859e06d6f16231d6357fff983e5f70e599f4aa
6d7202be95c861dbf8ad6126b1af90c588fa0c59
refs/heads/master
<file_sep>#' @title RNAmodR.Data #' #' @author <NAME> [aut], <NAME> [ctb] #' #' @description #' RNAmodR.Data contains example data, which is used for vignettes and example #' workflows in the \code{RNAmodR} and dependent #' packages. #' #' @docType package #' @name RNAmodR.Data NULL #' @import ExperimentHub #' @import ExperimentHubData NULL #' @name RNAmodR.Data.example #' @aliases RNAmodR.Data.example.fasta RNAmodR.Data.example.gff3 #' RNAmodR.Data.example.bam.1 RNAmodR.Data.example.bam.2 #' RNAmodR.Data.example.bam.3 #' #' @title RNAmodR general example data #' #' @description #' This dataset contains general example data used for different purposes. #' The indivicual identifiers are \code{RNAmodR.Data.} plus the header from the #' \code{Datasets} section. #' #' @section Datasets: #' \subsection{example.fasta}{ #' sequences of artificial genome for S. cerevisiae containing only rRNA and #' tRNA sequences #' } #' \subsection{example.gff3}{ #' annotation of artificial genome for S. cerevisiae containing only rRNA and #' tRNA sequences #' } #' \subsection{example.bam.1}{ #' sequencing reads mapped to artificial genome - replicate 1 #' } #' \subsection{example.bam.2}{ #' sequencing reads mapped to artificial genome - replicate 2 #' } #' \subsection{example.bam.3}{ #' sequencing reads mapped to artificial genome - replicate 3 #' } #' #' @examples #' RNAmodR.Data.example.fasta() #' RNAmodR.Data.example.gff3() #' RNAmodR.Data.example.bam.1() #' RNAmodR.Data.example.bam.2() #' RNAmodR.Data.example.bam.3() NULL #' @name RNAmodR.Data.RMS #' @aliases RNAmodR.Data.example.RMS.fasta RNAmodR.Data.example.RMS.gff3 #' RNAmodR.Data.example.RMS.1 RNAmodR.Data.example.RMS.2 #' #' @title RNAmodR RiboMethSeq example data #' #' @description #' This dataset contains example data for RiboMethSeq. #' The indivicual identifiers are \code{RNAmodR.Data.} plus the header from the #' \code{Datasets} section. #' #' @section Datasets: #' \subsection{example.RMS.fasta}{ #' sequence of artificial genome for H. sapiens containing only the 5.8S rRNA #' sequence #' } #' \subsection{example.RMS.gff3}{ #' annotation of artificial genome for H. sapiens containing only the 5.8S #' rRNA sequence #' } #' \subsection{example.RMS.1}{ #' sequencing reads mapped to artificial genome - replicate 1 #' } #' \subsection{example.RMS.2}{ #' sequencing reads mapped to artificial genome - replicate 2 #' } #' #' @examples #' RNAmodR.Data.example.RMS.fasta() #' RNAmodR.Data.example.RMS.gff3() #' RNAmodR.Data.example.RMS.1() #' RNAmodR.Data.example.RMS.2() NULL #' @name RNAmodR.Data.AAS #' @aliases RNAmodR.Data.example.AAS.fasta RNAmodR.Data.example.AAS.gff3 #' RNAmodR.Data.example.bud23.1 RNAmodR.Data.example.bud23.2 #' RNAmodR.Data.example.trm8.1 RNAmodR.Data.example.trm8.2 #' RNAmodR.Data.example.wt.1 RNAmodR.Data.example.wt.2 #' RNAmodR.Data.example.wt.3 #' #' @title RNAmodR AlkAnilineSeq example data #' #' @description #' This dataset contains exmaple data for AlkAnilineSeq. #' The indivicual identifiers are \code{RNAmodR.Data.} plus the header from the #' \code{Datasets} section. #' #' @section Datasets: #' \subsection{example.AAS.fasta}{ #' sequence of artificial genome for S. cerevisiae containing only the 18S #' rRNA sequence and 10 tRNA sequences #' } #' \subsection{example.AAS.gff3}{ #' annotation of artificial genome for S. cerevisiae containing only the 18S #' rRNA sequence and 10 tRNA sequences #' } #' \subsection{example.bud23.1}{ #' sequencing reads mapped to artificial genome from bud23del strain - #' replicate 1 #' } #' \subsection{example.bud23.2}{ #' sequencing reads mapped to artificial genome from bud23del strain - #' replicate 2 #' } #' \subsection{example.trm8.1}{ #' sequencing reads mapped to artificial genome from trm8del strain - #' replicate 1 #' } #' \subsection{example.trm8.2}{ #' sequencing reads mapped to artificial genome from trm8del strain - #' replicate 2 #' } #' \subsection{example.wt.1}{ #' sequencing reads mapped to artificial genome from wild type strain - #' replicate 1 #' } #' \subsection{example.wt.2}{ #' sequencing reads mapped to artificial genome from wild type strain - #' replicate 2 #' } #' \subsection{example.wt.3}{ #' sequencing reads mapped to artificial genome from wild type strain - #' replicate 3 #' } #' #' @examples #' RNAmodR.Data.example.AAS.fasta() #' RNAmodR.Data.example.AAS.gff3() #' RNAmodR.Data.example.bud23.1() #' RNAmodR.Data.example.bud23.2() #' RNAmodR.Data.example.trm8.1() #' RNAmodR.Data.example.trm8.2() #' RNAmodR.Data.example.wt.1() #' RNAmodR.Data.example.wt.2() #' RNAmodR.Data.example.wt.3() NULL #' @name example.man.fasta #' @aliases RNAmodR.Data.example.man.fasta RNAmodR.Data.example.man.gff3 #' #' @title RNAmodR example data for tests and man pages #' #' @description #' This dataset contains a small data set for tests and man page examples. #' The indivicual identifiers are \code{RNAmodR.Data.} plus the header from the #' \code{Datasets} section. #' #' @section Datasets: #' \subsection{example.man.fasta}{ #' sequence of artificial genome for S. cerevisiae containing partial #' sequences of the 18S rRNA #' } #' \subsection{example.man.gff3}{ #' annotation of artificial genome for S. cerevisiae containing partial #' sequences of the 18S rRNA #' } #' #' @examples #' RNAmodR.Data.example.man.fasta() #' RNAmodR.Data.example.man.gff3() NULL #' @name RNAmodR.Data.snoRNAdb #' #' @title snoRNAdb data #' #' @description #' The csv files contains a copy of data from the snoRNAdb #' (\url{https://www-snorna.biotoul.fr/}) downloaded on the 2019-02-11. #' The coordinates were updated to current rRNA sequences of hg38. #' #' @examples #' RNAmodR.Data.snoRNAdb() NULL<file_sep>library(testthat) library(RNAmodR.Data) test_check("RNAmodR.Data") <file_sep>#' @include RNAmodR.Data.R NULL .get_data_titles <- function(pkgname){ fl <- system.file("extdata", "metadata.csv", package=pkgname) titles <- read.csv(fl, stringsAsFactors=FALSE)$Title titles } #' @import utils .onLoad <- function(libname, pkgname) { titles <- .get_data_titles(pkgname) createHubAccessors(pkgname, titles) } <file_sep> # Base data for all data sets -------------------------------------------------- df_Base <- data.frame( BiocVersion = "3.9", Genome = NA, SourceVersion = NA, Coordinate_1_based = TRUE, Maintainer = "<NAME> <<EMAIL>>" ) UMS2008 <- "UMS2008 Next Generation Sequencing (NGS) Core Facility, Lorraine University" dlLabURL <- "http://www.lafontainelab.com" # basic example data from AlkAnilineSeq project df_Example <- rbind( cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.fasta", Description = paste0( "rRNA and tRNA sequences from S. cerevisiae. rRNA sequences from SGD", " and tRNA sequences retrieved from tRNAscan-SE output were used. tRNA", " sequences with Levensthein distances >= 3 were kept. This is used as an", "artificial genome for example data."), SourceType = "FASTA", DataProvider = "SGD, tRNAscan-SE", RDataClass = "FaFile", DispatchClass = "FaFile", RDataPath = "RNAmodR.Data/example.fasta:RNAmodR.Data/example.fai")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.gff3", Description = paste0( "Artificial annotations for rRNA and tRNA sequences from S. cerevisiae. ", "rRNA sequences from SGD and tRNA sequences retrieved from tRNAscan-SE output ", "were used. tRNA sequences with Levensthein distances >= 3 were kept. This is ", "used as an artificial genome for example data."), SourceType = "GFF", DataProvider = "SGD, tRNAscan-SE", RDataClass = "FilePath", DispatchClass = "FilePath", RDataPath = "RNAmodR.Data/example.gff3")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.bam.1", Description = paste0( "Mapped reads to artificial genome. Reads were taken from sequencing results ", "from AlkAnilineSeq project (DOI: 10.1002/anie.201810946). Replicate 1"), SourceType = "FASTQ", DataProvider = UMS2008, RDataClass = "BamFile", DispatchClass = "BamFile", RDataPath = "RNAmodR.Data/example1.bam:RNAmodR.Data/example1.bai")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.bam.2", Description = paste0( "Mapped reads to artificial genome. Reads were taken from sequencing results ", "from AlkAnilineSeq project (DOI: 10.1002/anie.201810946). Replicate 2"), SourceType = "FASTQ", DataProvider = UMS2008, RDataClass = "BamFile", DispatchClass = "BamFile", RDataPath = "RNAmodR.Data/example2.bam:RNAmodR.Data/example2.bai")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.bam.3", Description = paste0( "Mapped reads to artificial genome. Reads were taken from sequencing results ", "from AlkAnilineSeq project (DOI: 10.1002/anie.201810946). Replicate 3"), SourceType = "FASTQ", DataProvider = UMS2008, RDataClass = "BamFile", DispatchClass = "BamFile", RDataPath = "RNAmodR.Data/example3.bam:RNAmodR.Data/example3.bai")) ) df_Example$Species <- "Saccharomyces cerevisiae S288C" df_Example$TaxonomyId <- "559292" df_Example$SourceUrl <- dlLabURL df_Example$SourceVersion <- NA # example data from RiboMethSeq project df_RMS <- rbind( cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.RMS.fasta", Description = paste0("5.8S rRNA sequence from H. sapiens."), SourceType = "FASTA", DataProvider = "SGD, tRNAscan-SE", RDataClass = "FaFile", DispatchClass = "FaFile", RDataPath = "RNAmodR.Data/example_RMS.fasta:RNAmodR.Data/example_RMS.fai")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.RMS.gff3", Description = paste0( "Artificial annotation for 5.8S rRNA sequence from H. sapiens."), SourceType = "GFF", DataProvider = "SGD, tRNAscan-SE", RDataClass = "FilePath", DispatchClass = "FilePath", RDataPath = "RNAmodR.Data/example_RMS.gff3")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.RMS.1", Description = paste0( "Mapped reads to 5.8S rRNA of H. sapiens. Reads were taken from sequencing ", "results from RiboMethSeq project (DOI: tbd). Replicate 1" ), SourceType = "FASTQ", DataProvider = UMS2008, RDataClass = "BamFile", DispatchClass = "BamFile", RDataPath = "RNAmodR.Data/example_RMS1.bam:RNAmodR.Data/example_RMS1.bai")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.RMS.2", Description = paste0( "Mapped reads to 5.8S rRNA of H. sapiens. Reads were taken from sequencing ", "results from RiboMethSeq project (DOI: tbd). Replicate 2" ), SourceType = "FASTQ", DataProvider = UMS2008, RDataClass = "BamFile", DispatchClass = "BamFile", RDataPath = "RNAmodR.Data/example_RMS2.bam:RNAmodR.Data/example_RMS2.bai")) ) df_RMS$Species <- "Homo sapiens" df_RMS$TaxonomyId <- "9606" df_RMS$SourceUrl <- dlLabURL df_RMS$SourceVersion <- NA # example data from AlkAnilineSeq project df_AAS <- rbind( cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.AAS.fasta", Description = paste0( "18S rRNA and 10 tRNA sequences from S. cerevisiae. rRNA sequence from SGD ", "and tRNA sequences retrieved from tRNAscan-SE output were used. 10 tRNA ", "were selected manually. This is used as an artificial genome for example ", "data and sequences are named chr1-chr11."), SourceType = "FASTA", DataProvider = "SGD, tRNAscan-SE", RDataClass = "FaFile", DispatchClass = "FaFile", RDataPath = "RNAmodR.Data/example_AAS.fasta:RNAmodR.Data/example_AAS.fai")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.AAS.gff3", Description = paste0( "Annotations for 18S rRNA and 10 tRNA sequences from S. cerevisiae. rRNA ", "sequence from SGD and tRNA sequences retrieved from tRNAscan-SE output ", "were used. 10 tRNA were selected manually. This is used for an artificial ", "genome for example data and annotation is for sequences named chr1-chr11." ), SourceType = "GFF", DataProvider = "SGD, tRNAscan-SE", RDataClass = "FilePath", DispatchClass = "FilePath", RDataPath = "RNAmodR.Data/example_AAS.gff3")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.bud23.1", Description = paste0( "Mapped reads to 18S rRNA and 10 tRNA of S. cerevisiae. Reads were taken from ", "sequencing results from AlkAnilineSeq project for bud23del strain ", "(DOI: 10.1002/anie.201810946). Replicate 1"), SourceType = "FASTQ", DataProvider = UMS2008, RDataClass = "BamFile", DispatchClass = "BamFile", RDataPath = "RNAmodR.Data/example_bud23_1.bam:RNAmodR.Data/example_bud23_1.bai")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.bud23.2", Description = paste0( "Mapped reads to 18S rRNA and 10 tRNA of S. cerevisiae. Reads were taken from ", "sequencing results from AlkAnilineSeq project for bud23del strain ", "(DOI: 10.1002/anie.201810946). Replicate 2"), SourceType = "FASTQ", DataProvider = UMS2008, RDataClass = "BamFile", DispatchClass = "BamFile", RDataPath = "RNAmodR.Data/example_bud23_2.bam:RNAmodR.Data/example_bud23_2.bai")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.trm8.1", Description = paste0( "Mapped reads to 18S rRNA and 10 tRNA of S. cerevisiae. Reads were taken from ", "sequencing results from AlkAnilineSeq project for trm8del strain ", "(DOI: 10.1002/anie.201810946). Replicate 1"), SourceType = "FASTQ", DataProvider = UMS2008, RDataClass = "BamFile", DispatchClass = "BamFile", RDataPath = "RNAmodR.Data/example_trm8_1.bam:RNAmodR.Data/example_trm8_1.bai")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.trm8.2", Description = paste0( "Mapped reads to 18S rRNA and 10 tRNA of S. cerevisiae. Reads were taken from ", "sequencing results from AlkAnilineSeq project for trm8del strain ", "(DOI: 10.1002/anie.201810946). Replicate 2"), SourceType = "FASTQ", DataProvider = UMS2008, RDataClass = "BamFile", DispatchClass = "BamFile", RDataPath = "RNAmodR.Data/example_trm8_2.bam:RNAmodR.Data/example_trm8_2.bai")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.wt.1", Description = paste0( "Mapped reads to 18S rRNA and 10 tRNA of S. cerevisiae. Reads were taken from ", "sequencing results from AlkAnilineSeq project for wild type strain ", "(DOI: 10.1002/anie.201810946). Replicate 1"), SourceType = "FASTQ", DataProvider = UMS2008, RDataClass = "BamFile", DispatchClass = "BamFile", RDataPath = "RNAmodR.Data/example_wt_1.bam:RNAmodR.Data/example_wt_1.bai")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.wt.2", Description = paste0( "Mapped reads to 18S rRNA and 10 tRNA of S. cerevisiae. Reads were taken from ", "sequencing results from AlkAnilineSeq project for wild type strain ", "(DOI: 10.1002/anie.201810946). Replicate 2"), SourceType = "FASTQ", DataProvider = UMS2008, RDataClass = "BamFile", DispatchClass = "BamFile", RDataPath = "RNAmodR.Data/example_wt_2.bam:RNAmodR.Data/example_wt_2.bai")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.wt.3", Description = paste0( "Mapped reads to 18S rRNA and 10 tRNA of S. cerevisiae. Reads were taken from ", "sequencing results from AlkAnilineSeq project for wild type strain ", "(DOI: 10.1002/anie.201810946). Replicate 3"), SourceType = "FASTQ", DataProvider = UMS2008, RDataClass = "BamFile", DispatchClass = "BamFile", RDataPath = "RNAmodR.Data/example_wt_3.bam:RNAmodR.Data/example_wt_3.bai")) ) df_AAS$Species <- "Saccharomyces cerevisiae S288C" df_AAS$TaxonomyId <- "559292" df_AAS$SourceUrl <- dlLabURL df_AAS$SourceVersion <- NA # example data from AlkAnilineSeq project for man pages and tests df_Man <- rbind( cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.man.fasta", Description = paste0( "Nucleotides at position 1-100 and 1500-1600 of 18S rRNA from S. cerevisiae."), SourceType = "FASTA", DataProvider = "SGD, tRNAscan-SE", RDataClass = "FaFile", DispatchClass = "FaFile", RDataPath = "RNAmodR.Data/example1.fasta:RNAmodR.Data/example1.fai")), cbind(df_Base, data.frame(Title = "RNAmodR.Data.example.man.gff3", Description = paste0( "Annotations for nucleotides at position 1-100 and 1500-1600 of 18S rRNA from ", "S. cerevisiae."), SourceType = "GFF", DataProvider = "SGD, tRNAscan-SE", RDataClass = "FilePath", DispatchClass = "FilePath", RDataPath = "RNAmodR.Data/example1.gff3")) ) df_Man$Species <- "Saccharomyces cerevisiae S288C" df_Man$TaxonomyId <- "559292" df_Man$SourceUrl <- dlLabURL df_Man$SourceVersion <- NA # snoRNAdb df_snoRNAdb <- rbind( cbind(df_Base, data.frame(Title = "RNAmodR.Data.snoRNAdb", Description = paste0( "Information from the snoRNAdb was downloaded and manually adjusted for ", "changes in recent rRNA sequences from H. sapiens. The information provided ", "match hg38 release sequences."), SourceType = "TXT", DataProvider = "snoRNAdb", RDataClass = "FilePath", DispatchClass = "FilePath", RDataPath = "RNAmodR.Data/snoRNAdb.csv")) ) df_snoRNAdb$Species <- "Homo sapiens" df_snoRNAdb$TaxonomyId <- "9606" df_snoRNAdb$SourceUrl <- "https://www-snorna.biotoul.fr/" df_snoRNAdb$SourceVersion <- "2019-02-11" experimentData <- rbind(df_Example, df_RMS, df_AAS, df_Man, df_snoRNAdb) write.csv(experimentData, file = "inst/extdata/metadata.csv", row.names = FALSE) <file_sep>--- title: "RNAmodR.Data: example data for RNAmodR packages" author: "<NAME> and <NAME>" date: "`r Sys.Date()`" package: RNAmodR.Data output: BiocStyle::html_document: toc: true toc_float: true df_print: paged vignette: > %\VignetteIndexEntry{RNAmodR.Data} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} bibliography: references.bib --- ```{r style, echo = FALSE, results = 'asis'} BiocStyle::markdown(css.files = c('custom.css')) ``` # Available resources `RNAmodR.Data` contains example data for the `RNAmodR` and related packages. The data is provided as gff3, fasta and bam files. Four sets of data with multiple files are included ```{r, echo=FALSE} suppressPackageStartupMessages({ library(RNAmodR.Data) }) ``` ```{r, eval=FALSE} library(RNAmodR.Data) ``` ```{r} eh <- ExperimentHub() ExperimentHub::listResources(eh, "RNAmodR.Data") ``` These resources are grouped based on topic. Please have a look at the following man pages: - `?RNAmodR.Data.example` for general example data used for different purposes - `?RNAmodR.Data.RMS` for example data for RiboMethSeq - `?RNAmodR.Data.AAS` for example data for AlkAnilineSeq - `?RNAmodR.Data.man` for small data set for man page examples - `?RNAmodR.Data.snoRNAdb` for snoRNAdb as csv file # snoRNAdb `RNAmodR.Data.snoRNAdb` consists of a table containing the published data from the snoRNAdb [[@Lestrade.2006]](#References). The can be loaded as a GRanges object. ```{r, echo=FALSE} suppressPackageStartupMessages({ library(GenomicRanges) }) ``` ```{r, eval=FALSE} library(GenomicRanges) ``` ```{r} table <- read.csv2(RNAmodR.Data.snoRNAdb(), stringsAsFactors = FALSE) head(table, n = 2) # keep only the current coordinates table <- table[,1:7] snoRNAdb <- GRanges(seqnames = table$hgnc_symbol, ranges = IRanges(start = table$position, width = 1),strand = "+", type = "RNAMOD", mod = table$modification, Parent = table$hgnc_symbol, Activity = CharacterList(strsplit(table$guide,","))) # convert to current gene name snoRNAdb <- snoRNAdb[vapply(snoRNAdb$Activity != "unknown",all,logical(1)),] snoRNAdb <- split(snoRNAdb,snoRNAdb$Parent) head(snoRNAdb) ``` # Sessioninfo ```{r} sessionInfo() ``` <a name="References"></a> # References <file_sep>context("RNAmodR.Data") test_that("RNAmodR.Data:",{ libname <- system.file(package = "RNAmodR.Data") actual <- RNAmodR.Data:::.get_data_titles("RNAmodR.Data") expect_type(actual,"character") expect_true(all(grepl("RNAmodR.Data",actual))) }) <file_sep># RNAmodR.RData [![Build Status](https://travis-ci.com/FelixErnst/RNAmodR.Data.svg?branch=master)](https://travis-ci.com/FelixErnst/RNAmodR.Data) [![codecov](https://codecov.io/gh/FelixErnst/RNAmodR.Data/branch/master/graph/badge.svg)](https://codecov.io/gh/FelixErnst/RNAmodR.Data) The package contains example data for RNAmodR package and other related packages. It probably makes sense to have a look at [RNAmodR](https://github.com/FelixErnst/RNAmodR) to check out how the data can be used. # Installation The current version of the RNAmodR.Data package is available from Bioconductor. ``` if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("RNAmodR.Data") library(RNAmodR.Data) ```
8d21aff02b7924a2faf2cab1f7f5edcff82c6cb7
[ "Markdown", "R", "RMarkdown" ]
7
R
FelixErnst/RNAmodR.Data
e63f557b82873eed03138e6cc7636d5fb67d00a7
0ffa491e2ca82a9c73e3c5cdf108a25f9ca639ee
refs/heads/master
<repo_name>alfonsochaparro/bqapp<file_sep>/README.md # BqDropboxApp Proyecto desarrollado en Android Studio, usando la api de Dropbox. El funcionamiento es el siguiente: al abrir la app por primera vez, nos pedirá que iniciemos sesión con nuestra cuenta de dropbox mediante un enlace. Al clicarlo, nos mandará a la app de dropbox o bien a una web en el navegador por defecto, en caso de no tener la app de dropbox instalada en el dispositivo. Una vez realizado el login, de vuelta a la app, entraremos en la pantalla principal, donde la app se conectará a la api de dropbox para obtener los archivos con extensión .epub. También tienes las opciones de seleccionar el tipo de vista (cuadrícula o lista), de ordenar por título o fecha, y de subir un archivo .epub a dropbox desde el almacenamiento del dispositivo. Además en la misma pantalla, en el menú de la izquierda, aparecen los datos del usuario y la opción de cerrar la sesión. Al clicar en un ebook del listado nos iríamos a la pantalla de detalles, donde aparecerán la portada del libro, su título, su autor y el resumen de su contenido. También está la opción de abrir el archivo .epub desde cualquier app instalada en el dispositivo que sea capaz de leerlo. ## Estructura del proyecto - app - adapter * EbupsAdapter - config * Constants * Preferences - model * EpubModel - util * Util * DetailsActivity * ListActivity * MainActivity - network * DBApi * NetworkWueue ## Principales dificultades y decisiones tomadas Para empezar, tenemos las clases Constants y Preferences, donde se definen las constantes a usar en el proyecto y la información a almacenar cuando se cierre y se vuelva a abrir la app. Lo siguiente es crear la clase DBApi, un singleton con una instancia de la clase DropboxAPI, de forma que se puedan hacer peticiones a la api de drobox desde cualquier parte de la aplicación sin tener que crear una instancia cada vez. En el mismo paquete de esa clase se encuentra la clase NetworkQueue, que es otro singleton con una instancia de RequestQueue para hacer peticiones, aunque finalmente no ha sido necesario usarla dado que con las funciones que la clase DropboxAPI encapsula todas las llamadas. Otra decisión es la definición del modelo de datos para la app. Dado que no estaba muy claro qué datos iba a necesitar de las respuestas de la api de dropbox, en primer lugar opté por usar como modelo la propia clase que devuelve la api, con toda la información. Finalmente, como también es necesario guardar la información de cada ebook, no sólo de los metadatos que llegan desde dropbox, también se incluye en el modelo la clase Book, que nos da la información del título, portada y demás de cada libro. El listado de libros está realizado de la siguiente forma: en el layout tenemos un GridView, al cual tenemos conectado un adaptador de clase EpubsAdapter. el cual, en función de su propiedad mViewMode inflará el xml layout_item_list o layout_item_grid. El adaptador recibe una lista de metadatos devuelto por la api de dropbox, muestra el listado con una imagen por defecto para cada libro, con el nombre del fichero y la fecha de modificación, y lanza un AsyncTask que se descargue la información del ebook para que sea procesado con la librería EbookReader. En ese momento, si el elemento aún es visible, actualizará su vista con la imagen de portada del ebook y su título. En esta misma pantalla se añade el menú lateral NavigationView, donde aparece el nombre del usuario y su correo, y la opción para cerrar la sesión del usuario actual. También está presente en esta pantalla el componente SwipeRefreshLayout, que nos permite refrescar el contenido del listado. Al clicar en un libro, nos lo descargamos en el dispositivo, en el área interna de la app, pero con modo MODE_WORLD_READABLE, para que en la siguiente pantalla, donde se mostrará la información del libro descargado, podamos tener una opción de abrir el ebook con otra aplicación. En esta pantalla tendremos el componentes CollapsingToolbarLayout, que mostrará con efecto parallax la portada del libro junto con su título. Debajo, hacuendo uso de componentes CardView, mostramos por un lado portada, título y auto, y por otro la descripción del libro en un máximo de 5 líneas. <file_sep>/app/src/main/java/com/alfonsochap/bqdropboxapp/app/config/Preferences.java package com.alfonsochap.bqdropboxapp.app.config; import android.content.Context; import android.content.SharedPreferences; /** * Created by Alfonso on 10/12/2015. */ public class Preferences { public static final int VIEW_LIST = 0; public static final int VIEW_GRID = 1; public static final int SORT_NAME = 0; public static final int SORT_DATE = 1; private static final String SP_NAME = "prefs"; static SharedPreferences sp; public static void init(Context context) { sp = context.getSharedPreferences(SP_NAME, 0); } public static String getToken() { return sp.getString("token", ""); } public static boolean hasToken() { return getToken().length() > 0; } public static void setToken(String token) { sp.edit().putString("token", token).commit(); } public static void removeToken() { sp.edit().remove("token").commit(); } public static int getSortMode() { return sp.getInt("sort", SORT_NAME); } public static void setSortMode(int sortMode) { sp.edit().putInt("sort", sortMode).commit(); } public static int getViewMode() { return sp.getInt("view", VIEW_LIST); } public static void setViewMode(int viewMode) { sp.edit().putInt("view", viewMode).commit(); } } <file_sep>/app/src/main/java/com/alfonsochap/bqdropboxapp/app/adapter/EpubsAdapter.java package com.alfonsochap.bqdropboxapp.app.adapter; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.alfonsochap.bqdropboxapp.R; import com.alfonsochap.bqdropboxapp.app.model.EpubModel; import com.alfonsochap.bqdropboxapp.network.DBApi; import com.alfonsochap.bqdropboxapp.app.config.Preferences; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Locale; import nl.siegmann.epublib.domain.Book; import nl.siegmann.epublib.epub.EpubReader; /** * Created by Alfonso on 14/12/2015. */ public class EpubsAdapter extends BaseAdapter { private Context mContext; private LayoutInflater inflater; private List<EpubModel> mItems; private int mViewMode; private int mFolderIcon; private int mEpubIcon; private SimpleDateFormat mDateFormatInput = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US); private SimpleDateFormat mDateFormatOutput = new SimpleDateFormat("dd/MM/yyyy HH:mm"); private List<LoadBook> mTasks = new ArrayList<>(); public EpubsAdapter(Context context, List<EpubModel> items) { mContext = context; mItems = items; updateViewMode(); } @Override public int getCount() { return mItems.size(); } @Override public Object getItem(int location) { return mItems.get(location); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (inflater == null) inflater = LayoutInflater.from(mContext); if (convertView == null || ((Integer)convertView.getTag()) != mViewMode) { convertView = inflater.inflate(mViewMode == Preferences.VIEW_LIST ? R.layout.layout_item_list : R.layout.layout_item_grid, parent, false); convertView.setTag(mViewMode); } LoadBook task = new LoadBook(convertView, mItems.get(position)); mTasks.add(task); task.execute(); return convertView; } public void setItems(List<EpubModel> items) { clear(); mItems.addAll(items); } public List<EpubModel> getItems() { return mItems; } public void clear() { clearTasks(); mItems.clear(); } public void sort() { Collections.sort(mItems, new Comparator<EpubModel>() { @Override public int compare(EpubModel lhs, EpubModel rhs) { if (Preferences.getSortMode() == Preferences.SORT_NAME) { String name1 = lhs.getBook() == null ? lhs.getEntry().fileName() : lhs.getBook().getTitle(); String name2 = rhs.getBook() == null ? rhs.getEntry().fileName() : rhs.getBook().getTitle(); return name1.compareTo(name2); } try { Date d1 = mDateFormatInput.parse(lhs.getEntry().modified); Date d2 = mDateFormatInput.parse(rhs.getEntry().modified); return d2.compareTo(d1); } catch (Exception e) { return 0; } } }); } public void updateViewMode() { mViewMode = Preferences.getViewMode(); mFolderIcon = mViewMode == Preferences.VIEW_LIST ? R.drawable.folder : R.drawable.folder_big; mEpubIcon = mViewMode == Preferences.VIEW_LIST ? R.drawable.epub : R.drawable.epub_big; } public void clearTasks() { for(LoadBook task: mTasks) { if(task != null && task.getStatus() == AsyncTask.Status.RUNNING) { task.cancel(true); } } mTasks.clear(); } class LoadBook extends AsyncTask<Void, Void, Void> { View view; EpubModel item; public LoadBook(View view, EpubModel item) { this.view = view; this.item = item; } @Override protected void onPreExecute() { fillView(); } @Override protected Void doInBackground(Void... params) { try { if(item.getBook() == null && !item.getEntry().isDir) { Book book = (new EpubReader()).readEpub(DBApi.getInstance(mContext).api .getFileStream(item.getEntry().path, "")); item.setBook(book); } } catch (Exception e) { Log.v("tag", "Error: " + e.getMessage()); } return null; } @Override protected void onPostExecute(Void arg0) { if(!isCancelled()) { if (item.getBook() != null) { fillView(); } } } private void fillView() { if(view != null) { TextView txt = (TextView) view.findViewById(R.id.txt); TextView txt2 = (TextView) view.findViewById(R.id.txt2); ImageView img = (ImageView) view.findViewById(R.id.img); if (item.getBook() == null) { // Showing metadata info if book data has not been downloaded txt.setText(item.getEntry().fileName()); img.setImageResource(item.getEntry().isDir ? mFolderIcon : mEpubIcon); } else { txt.setText(item.getBook().getTitle()); try { Bitmap bmp = BitmapFactory.decodeStream(item.getBook().getCoverImage() .getInputStream()); img.setImageBitmap(bmp); } catch (Exception e) { img.setImageResource(mEpubIcon); } } try { txt2.setText(mDateFormatOutput.format(mDateFormatInput.parse( item.getEntry().modified))); } catch (ParseException e) { Log.v("tag", "Error: " + e.getMessage()); } } } } } <file_sep>/app/src/main/java/com/alfonsochap/bqdropboxapp/app/MainActivity.java package com.alfonsochap.bqdropboxapp.app; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.widget.ImageView; import android.widget.TextView; import com.alfonsochap.bqdropboxapp.R; import com.alfonsochap.bqdropboxapp.network.DBApi; import com.alfonsochap.bqdropboxapp.app.config.Preferences; public class MainActivity extends AppCompatActivity { private DBApi mDBApi; ImageView mImgLogo; View loginForm; TextView mBtnLogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().hide(); Preferences.init(getApplicationContext()); mDBApi = DBApi.getInstance(this); mImgLogo = (ImageView) findViewById(R.id.imgLogo); loginForm = findViewById(R.id.loginForm); mBtnLogin = (TextView) findViewById(R.id.btnLogin); initAnimation(); } @Override protected void onResume() { super.onResume(); if (mDBApi.api.getSession().authenticationSuccessful()) { try { // Required to complete auth, sets the access token on the session mDBApi.api.getSession().finishAuthentication(); String accessToken = mDBApi.api.getSession().getOAuth2AccessToken(); Preferences.setToken(accessToken); goForward(); } catch (IllegalStateException e) { Log.i("DbAuthLog", "Error authenticating", e); } } } void initAnimation() { mImgLogo.postDelayed(new Runnable() { @Override public void run() { checkDropBoxSession(); } }, 2000); } void checkDropBoxSession() { if(Preferences.hasToken()) { mDBApi.api.getSession().setOAuth2AccessToken(Preferences.getToken()); goForward(); } else { mImgLogo.animate().scaleX(0.9f).scaleY(0.9f).setInterpolator(new AccelerateInterpolator()).setDuration(150); loginForm.setVisibility(View.VISIBLE); mBtnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mDBApi.api.getSession().startOAuth2Authentication(MainActivity.this); } }); } } void goForward() { startActivity(new Intent(this, ListActivity.class)); finish(); } }
c761c7f48cecdf62b1ff2d212e88990e7310a80b
[ "Markdown", "Java" ]
4
Markdown
alfonsochaparro/bqapp
5c5c07f7494967b1ba09c0f72742b155816676d1
332e7ab0047dce37c1f1443869f32310aef79388
refs/heads/main
<file_sep><?php namespace App\DataFixtures; use App\Entity\City; use App\Entity\User; use App\Entity\Brand; use App\Entity\Address; use App\Entity\Product; use App\Entity\Category; use Doctrine\Persistence\ObjectManager; use Doctrine\Bundle\FixturesBundle\Fixture; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; class AppFixtures extends Fixture { private $encoder; public function __construct(UserPasswordHasherInterface $encoder) { $this->encoder = $encoder; } public function load(ObjectManager $manager) { for ($i = 0; $i < 20; $i++) { $brand = new Brand(); $brand->setName("brand".$i); $manager->persist($brand); } for ($i = 0; $i < 20; $i++) { $category = new Category(); $category->setName("category".$i); $manager->persist($category); } for ($i = 0; $i < 20; $i++) { $product = new Product(); $product->setName('product '.$i); $product->setDescription('description number '.$i); $product->setPrice(mt_rand(10, 100)); $product->setQuantity(mt_rand(10, 100)); $date = date("Y-m-d H:i:s"); $product->setCreatedAt(new \DateTimeImmutable($date)); $product->setIdBrand($brand); $product->addIdCategory($category); $manager->persist($product); } for ($i = 0; $i < 20; $i++) { $user = new User(); $user->setEmail("test".$i."<EMAIL>"); $user->setRoles(["ROLE_USER"]); $password = $this->encoder->hashPassword($user, '<PASSWORD>'); $user->setPassword($password); $user->setFirstName("firstname".$i); $user->setLastName("lastname".$i); $user->setStreetNumber($i); $manager->persist($user); } for ($i = 0; $i < 20; $i++) { $city = new City(); $city->setName("city".$i); $manager->persist($city); } $manager->flush(); } } <file_sep><?php declare(strict_types=1); namespace DoctrineMigrations; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20210924102548 extends AbstractMigration { public function getDescription(): string { return ''; } public function up(Schema $schema): void { // this up() migration is auto-generated, please modify it to your needs $this->addSql('CREATE TABLE address (id INT AUTO_INCREMENT NOT NULL, id_user_id INT NOT NULL, id_city_id INT NOT NULL, postal_code VARCHAR(5) NOT NULL, country VARCHAR(255) NOT NULL, address_complement VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_D4E6F8179F37AE5 (id_user_id), INDEX IDX_D4E6F815531CBDF (id_city_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); $this->addSql('CREATE TABLE brand (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); $this->addSql('CREATE TABLE category (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, image VARCHAR(255) DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); $this->addSql('CREATE TABLE city (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); $this->addSql('CREATE TABLE `order` (id INT AUTO_INCREMENT NOT NULL, id_user_id INT NOT NULL, payment_method VARCHAR(255) NOT NULL, shipping_price DOUBLE PRECISION NOT NULL, total_price DOUBLE PRECISION NOT NULL, is_paid TINYINT(1) NOT NULL, quantity SMALLINT NOT NULL, created_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\', INDEX IDX_F529939879F37AE5 (id_user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); $this->addSql('CREATE TABLE product (id INT AUTO_INCREMENT NOT NULL, id_brand_id INT NOT NULL, name VARCHAR(255) NOT NULL, description LONGTEXT DEFAULT NULL, image VARCHAR(255) DEFAULT NULL, price DOUBLE PRECISION NOT NULL, quantity SMALLINT NOT NULL, created_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\', INDEX IDX_D34A04AD142E3C9D (id_brand_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); $this->addSql('CREATE TABLE product_category (product_id INT NOT NULL, category_id INT NOT NULL, INDEX IDX_CDFC73564584665A (product_id), INDEX IDX_CDFC735612469DE2 (category_id), PRIMARY KEY(product_id, category_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); $this->addSql('CREATE TABLE `user` (id INT AUTO_INCREMENT NOT NULL, email VARCHAR(180) NOT NULL, roles JSON NOT NULL, password VARCHAR(255) NOT NULL, first_name VARCHAR(255) NOT NULL, last_name VARCHAR(255) NOT NULL, birth_date DATE DEFAULT NULL, street_number SMALLINT NOT NULL, avatar VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_8D93D649E7927C74 (email), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); $this->addSql('ALTER TABLE address ADD CONSTRAINT FK_D4E6F8179F37AE5 FOREIGN KEY (id_user_id) REFERENCES `user` (id)'); $this->addSql('ALTER TABLE address ADD CONSTRAINT FK_D4E6F815531CBDF FOREIGN KEY (id_city_id) REFERENCES city (id)'); $this->addSql('ALTER TABLE `order` ADD CONSTRAINT FK_F529939879F37AE5 FOREIGN KEY (id_user_id) REFERENCES `user` (id)'); $this->addSql('ALTER TABLE product ADD CONSTRAINT FK_D34A04AD142E3C9D FOREIGN KEY (id_brand_id) REFERENCES brand (id)'); $this->addSql('ALTER TABLE product_category ADD CONSTRAINT FK_CDFC73564584665A FOREIGN KEY (product_id) REFERENCES product (id) ON DELETE CASCADE'); $this->addSql('ALTER TABLE product_category ADD CONSTRAINT FK_CDFC735612469DE2 FOREIGN KEY (category_id) REFERENCES category (id) ON DELETE CASCADE'); } public function down(Schema $schema): void { // this down() migration is auto-generated, please modify it to your needs $this->addSql('ALTER TABLE product DROP FOREIGN KEY FK_D34A04AD142E3C9D'); $this->addSql('ALTER TABLE product_category DROP FOREIGN KEY FK_CDFC735612469DE2'); $this->addSql('ALTER TABLE address DROP FOREIGN KEY FK_D4E6F815531CBDF'); $this->addSql('ALTER TABLE product_category DROP FOREIGN KEY FK_CDFC73564584665A'); $this->addSql('ALTER TABLE address DROP FOREIGN KEY FK_D4E6F8179F37AE5'); $this->addSql('ALTER TABLE `order` DROP FOREIGN KEY FK_F529939879F37AE5'); $this->addSql('DROP TABLE address'); $this->addSql('DROP TABLE brand'); $this->addSql('DROP TABLE category'); $this->addSql('DROP TABLE city'); $this->addSql('DROP TABLE `order`'); $this->addSql('DROP TABLE product'); $this->addSql('DROP TABLE product_category'); $this->addSql('DROP TABLE `user`'); } } <file_sep><?php namespace App\Entity; use App\Repository\OrderRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=OrderRepository::class) * @ORM\Table(name="`order`") */ class Order { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $paymentMethod; /** * @ORM\Column(type="float") */ private $shippingPrice; /** * @ORM\Column(type="float") */ private $totalPrice; /** * @ORM\Column(type="boolean") */ private $isPaid; /** * @ORM\Column(type="smallint") */ private $quantity; /** * @ORM\Column(type="datetime_immutable") */ private $createdAt; /** * @ORM\ManyToOne(targetEntity=User::class, inversedBy="orders") * @ORM\JoinColumn(nullable=false) */ private $idUser; public function getId(): ?int { return $this->id; } public function getPaymentMethod(): ?string { return $this->paymentMethod; } public function setPaymentMethod(string $paymentMethod): self { $this->paymentMethod = $paymentMethod; return $this; } public function getShippingPrice(): ?float { return $this->shippingPrice; } public function setShippingPrice(float $shippingPrice): self { $this->shippingPrice = $shippingPrice; return $this; } public function getTotalPrice(): ?float { return $this->totalPrice; } public function setTotalPrice(float $totalPrice): self { $this->totalPrice = $totalPrice; return $this; } public function getIsPaid(): ?bool { return $this->isPaid; } public function setIsPaid(bool $isPaid): self { $this->isPaid = $isPaid; return $this; } public function getQuantity(): ?int { return $this->quantity; } public function setQuantity(int $quantity): self { $this->quantity = $quantity; return $this; } public function getCreatedAt(): ?\DateTimeImmutable { return $this->createdAt; } public function setCreatedAt(\DateTimeImmutable $createdAt): self { $this->createdAt = $createdAt; return $this; } public function getIdUser(): ?User { return $this->idUser; } public function setIdUser(?User $idUser): self { $this->idUser = $idUser; return $this; } } <file_sep><?php namespace App\Entity; use App\Repository\AddressRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=AddressRepository::class) */ class Address { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=5) */ private $postalCode; /** * @ORM\Column(type="string", length=255) */ private $country; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $addressComplement; /** * @ORM\OneToOne(targetEntity=User::class, cascade={"persist", "remove"}) * @ORM\JoinColumn(nullable=false) */ private $idUser; /** * @ORM\ManyToOne(targetEntity=City::class) * @ORM\JoinColumn(nullable=false) */ private $idCity; public function getId(): ?int { return $this->id; } public function getPostalCode(): ?string { return $this->postalCode; } public function setPostalCode(string $postalCode): self { $this->postalCode = $postalCode; return $this; } public function getCountry(): ?string { return $this->country; } public function setCountry(string $country): self { $this->country = $country; return $this; } public function getAddressComplement(): ?string { return $this->addressComplement; } public function setAddressComplement(?string $addressComplement): self { $this->addressComplement = $addressComplement; return $this; } public function getIdUser(): ?User { return $this->idUser; } public function setIdUser(User $idUser): self { $this->idUser = $idUser; return $this; } public function getIdCity(): ?City { return $this->idCity; } public function setIdCity(?City $idCity): self { $this->idCity = $idCity; return $this; } } <file_sep><?php namespace App\Controller; use App\Repository\ProductRepository; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class ProductController extends AbstractController { #[Route('/product', name: 'products', methods: ['GET'])] public function product(ProductRepository $productRepository): Response { return $this->render('product/index.html.twig', [ 'productList' => $productRepository->findAll(), ]); } #[Route('/product/{id}', name: 'product', methods: ['GET'])] public function productId($id, ProductRepository $productRepository): Response { return $this->render('product/productId.html.twig', [ 'product' => $productRepository->findbyId($id), ]); } }
f524a0f765cc4700d5657aa545eaa94982d35825
[ "PHP" ]
5
PHP
JayVince/ecom_practice
0bbe48ce51495043fa162244e0730a1c42433685
3ef9e104ba5098f6b852fbb14cda2b5a64b41e04
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <stdbool.h> int *croissant(int* tableau) { int passage = 0; bool permutation = true; int cas = 0; while (permutation) { permutation = false; passage ++; for (cas=0;tableau[cas +1] != NULL;cas++) { if (tableau[cas]>tableau[cas+1]){ permutation = true; int temp = tableau[cas]; tableau[cas] = tableau[cas+1]; tableau[cas+1] = temp; } } } return (tableau); } int main(int argc, char *argv[]) { int print = 0; int cas = 9; int tableau[cas]; tableau[0] = 97; tableau[1] = 42; tableau[2] = 89; tableau[3] = 21; tableau[4] = 14; tableau[5] = 36; tableau[6] = 58; tableau[7] = 65; tableau[8] = 73; int *result = croissant(tableau); for (print = 0; print<cas;print++) { printf("%d\n", result[print]); } return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include "menu.c" void csv(){ FILE* fichier = NULL; fichier = fopen("battements.csv","r"); if (fichier != NULL) { //lire ou écrire fclose(fichier); } else { printf("Impossible d'ouvrir le fichier"); } } void croissant (){ } void decroissant (){ } void ligneMemoire(){ } void poulsMin(){ } void poulsMax(){ } void quit(){ } <file_sep>#include <stdio.h> #include <stdlib.h> int choix; int main(int argc, char const *argv[]) { printf("O------------------------------------------------------------------O\n"); printf("| |MENU CARDIO-FREQUENCEMETRE| |\n"); printf("| -------- |\n"); printf("| |\n"); printf("|Choix des options d'affichage : |\n"); printf("| |\n"); printf("|1. Afficher les donnees dans l'ordre du fichier .csv |\n"); printf("|2. Afficher les donnees en ordre croissant |\n"); printf("|3. Afficher les données en ordre decroissant |\n"); printf("|4. Afficher la moyenne de pouls dans une plage de temps donnee |\n"); printf("|5. Afficher le nombre de lignes de donnees actuellement en memoire|\n"); printf("|6. Rechercher et afficher le minimum de pouls |\n"); printf("|7. Rechercher et afficher le maximum de pouls |\n"); printf("|8. Quitter l'application |\n"); printf("O------------------------------------------------------------------O\n"); scanf("%d", &choix); printf("Vous avez choisi: %d\n", choix); if (choix == 1) { //csv(); printf(""); } if (choix == 2) { //croissant(); } if (choix == 3) { } if (choix == 4) { //decroissant(); } if (choix == 5) { //ligneMemoire(); } if (choix == 6) { //poulsMin(); } if (choix == 7) { //poulsMax(); } if (choix == 8) { //quit(); } if(choix>8||choix<1) { printf("Erreur\n"); scanf("%d\n", &choix); printf("Vous avez choisi: %d\n", choix); } return 0; }
6614e3979e99ee2a0b8f966f9484cad1affc4df3
[ "C" ]
3
C
Basonee/A1-Jojos-Bizarre-Projects
ee28ef9a893e378dd0740b2227152fb1ba620797
2da9aeb72a4fceeb9cf2a0c87f3a7bb11a5c0751
refs/heads/master
<file_sep>import { Box, CircularProgress, Grid, makeStyles, Typography } from "@material-ui/core"; import Card from './Card'; const useStyles = makeStyles({ component: { margin: '50px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', }, container: { color: '#8ACA2B', marginBottom: 40 } }) const Cards = ({ data: { confirmed, recovered, deaths, lastUpdate } }) => { const classes = useStyles(); if (!confirmed) { return <CircularProgress /> } return ( <Box className={classes.component}> <Typography className={classes.container} variant="h4" gutterBottom>Covid-19 Cases Globally</Typography> <Grid container spacing={3} justify="center"> <Card cardTitle="Infected" value={confirmed.value} description="Number of Infected Cases of Covid-19" lastUpdate={lastUpdate} /> <Card cardTitle="Recovered" value={recovered.value} description="Number of Recovered Cases from Covid-19" lastUpdate={lastUpdate} /> <Card cardTitle="Deaths" value={deaths.value} description="Number of Deaths Caused by Covid-19" lastUpdate={lastUpdate} /> </Grid> </Box> ) } export default Cards;<file_sep>import { Box, Card, CardContent, Grid, makeStyles, Typography } from "@material-ui/core"; import Countup from 'react-countup' const useStyles = makeStyles({ header: { backgroundColor: '#F5F5F5', padding: 10 } }) const CardComponent = ({ cardTitle, value, description, lastUpdate }) => { const classes = useStyles(); return ( <Grid component={Card} style={{ margin: 20, borderBottom: "10px solid red" }}> <Box className={classes.header}> <Typography variant="h5" color="textSecondary">{cardTitle}</Typography> </Box> <CardContent> <Typography variant="h5"> <Countup start={0} end={value} duration={3} separator="," /> </Typography> <Typography color="textSecondary"> {description} </Typography> <Typography> {new Date(lastUpdate).toDateString()} </Typography> </CardContent> </Grid> ) } export default CardComponent;
d7bf575a0e3f0b180e159fe138ac48fc4495432d
[ "JavaScript" ]
2
JavaScript
RajaGupta2512/corona-tracker-website
41bcae36d212bb22cca8c047d440b65f65598c6d
2057d5d73169f77141edb80852dc78d8800ef3ef
refs/heads/master
<repo_name>j-c-levin/sample-telegram-bot<file_sep>/source/index.ts import * as telegraf from "telegraf"; import * as ngrok from "ngrok"; import * as dotenv from "dotenv"; import { setupHandlers } from "./handlers"; dotenv.config(); // Starts the bot up and registers it with telegram async function init() { // Initialise the bot const bot = new telegraf(process.env.BOT_TOKEN); // Start ngrok if not deployed const url = await ngrok.connect(80); // Set up the commands the bot will respond too setupHandlers(bot); // Set up and start the webhook bot.telegram.setWebhook(`${url}/secretpathhere`); bot.startWebhook(`/secretpathhere`, null, 80); console.log("bot running"); } init(); <file_sep>/source/handlers/custom_response/index.ts export const CustomResponse = { setupHandlers: function (bot: any): void { bot.command('/your-command', simpleTrigger); } }; function simpleTrigger(ctx: any): void { ctx.reply('your response here'); } <file_sep>/source/handlers/index.ts import { SimpleResponse } from './simple_response/index'; import { ImageResponse } from './image_response/index'; import { RandomChoiceResponse } from './random_choice_response/index'; import { HelpResponse } from './help/index'; import { CustomResponse } from './custom_response/index'; // Import and call 'setup handlers' on everything the bot should respond to export function setupHandlers(bot: any): void { HelpResponse.setupHandlers(bot); ImageResponse.setupHandlers(bot); SimpleResponse.setupHandlers(bot); RandomChoiceResponse.setupHandlers(bot); CustomResponse.setupHandlers(bot); } <file_sep>/source/handlers/random_choice_response/index.ts export const RandomChoiceResponse = { setupHandlers: function(bot: any): void { bot.command('/random', trigger); } }; const options = [ "I choose one!", "I choose two!", "I choose three!" ]; function trigger(ctx: any): void { const choice = Math.floor(Math.random() * options.length); ctx.reply(options[choice]); } <file_sep>/source/handlers/image_response/index.ts export const ImageResponse = { setupHandlers: function(bot: any): void { bot.command('/image', trigger); } }; function trigger(ctx: any): void { ctx.replyWithPhoto('http://via.placeholder.com/300x300'); } <file_sep>/README.md # sample-telegram-bot An example telegram bot using typescript and telegraf for learning purposes. # Video walkthrough You can watch a demonstration of me setting up a bot using this guide here: https://youtu.be/8QkFOnwZXSU # Create your bot 1) In telegram search for 'botfather' and create a new bot 2) Copy the access token that the botfather gives you # Installing 3) Download node and npm: https://nodejs.org/en/ 4) Download this repository using a git client or as a zip file that you extract 5) Navigate to the root directory in a command line (with package.json) 6) Run `npm install` ## Set up environment variables 7) Create a .env file in the root directory 8) Populate it with the following fields: ``` BOT_TOKEN=[your bot token from telegram's botfather] ``` ## Quick launch 9) Run `npm run start` 10) Beging chatting to your chatbot on telegram # Development Run `npm run develop` to set up the server to compile and relaunch itself automatically on any code change The best place to start making changes is inside the 'custom_response' handler. Copy and paste code from the other files, experiment with how they work and what you can do with them. Have fun!<file_sep>/source/handlers/help/index.ts export const HelpResponse = { setupHandlers: function (bot: any) { bot.command("/help", help); bot.start(help); } }; export function help(ctx) { const helpText = ` Let me tell you what I can do: /help - I'll send this message again with your options /image - I'll send a placeholder image /hello - I'll say hello back /random - I'll pick a number between one and three`; ctx.reply(helpText); } <file_sep>/source/handlers/simple_response/index.ts export const SimpleResponse = { setupHandlers: function(bot: any): void { bot.command('/hello', trigger); } }; function trigger(ctx: any): void { ctx.reply('hello world!!1!'); }
1e6d7e17dfde791c5bace7677899ed8e79972d08
[ "Markdown", "TypeScript" ]
8
TypeScript
j-c-levin/sample-telegram-bot
fd603065226796a833c26cea4250c3ca96ccee7a
6f1b732b5ac1b0b23140e21652a9a2aeb7df49e0
refs/heads/main
<file_sep>#!/bin/sh rm -rf peterhigginson.co.uk wget -k -r -np \ http://peterhigginson.co.uk/LMC/ \ http://peterhigginson.co.uk/LMC/help.html \ http://peterhigginson.co.uk/LMC/lmcgraphic_plh.gif \ http://peterhigginson.co.uk/LMC/pcMarker.png \ http://peterhigginson.co.uk/LMC/red.gif \ http://peterhigginson.co.uk/LMC/blue.gif \ http://peterhigginson.co.uk/LMC/blue1.gif \ \ https://peterhigginson.co.uk/ARMlite/ pip install jsbeautifier for f in `find peterhigginson.co.uk -name \*.js`; do js-beautify -r $f done <file_sep># <NAME> emulators [Copy and fixes/improvements](https://frbrgeorge.github.io/peterhigginson) of [<NAME>son](http://peterhigginson.co.uk/Home.php) online JS emulators * [Little man computer](peterhigginson.co.uk/LMC) * [ARM Lite](peterhigginson.co.uk/ARMlite) Original versions can be found here: * [Little man computer](http://peterhigginson.co.uk/LMC/) (see also [LMC at Wikipedia](https://en.wikipedia.org/wiki/Little_man_computer)) * [ARM Lite](https://peterhigginson.co.uk/ARMlite/)
4a73e626a8f7beba05ccbb65a64df3c5646fc629
[ "Markdown", "Shell" ]
2
Shell
stirlingstout/peterhigginson
53ad0250ea16949250b4e8ea88fd59f777f76768
72d139882c3efaa50d57a3f0ccec45844ea13a95
refs/heads/master
<file_sep>FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base WORKDIR /app1 FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build WORKDIR /app1 COPY ["app1.csproj", "app1/"] RUN dotnet restore "app1/app1.csproj" COPY . . WORKDIR /app1 RUN dotnet build "app1.csproj" -c Release -o /build FROM build AS publish RUN dotnet publish "app1.csproj" -c Release -o /publish FROM base AS final WORKDIR /app COPY --from=publish /publish . ENTRYPOINT ["dotnet", "app1.dll"]<file_sep>FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base WORKDIR /app2 FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build WORKDIR /app2 COPY ["app2.csproj", "app2/"] RUN dotnet restore "app2/app2.csproj" COPY . . WORKDIR /app2 RUN dotnet build "app2.csproj" -c Release -o /build FROM build AS publish RUN dotnet publish "app2.csproj" -c Release -o /publish FROM base AS final WORKDIR /app COPY --from=publish /publish . ENTRYPOINT ["dotnet", "app2.dll"]<file_sep>FROM envoyproxy/envoy-dev:latest RUN apt-get update COPY envoyconf.yaml /etc/envoy.yaml CMD /usr/local/bin/envoy -c /etc/envoy.yaml<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace app1.Controllers { [Route("api/[controller]")] [ApiController] public class MirroringController : ControllerBase { [HttpGet("normal")] public Task<string[]> GetNormal() { return Task.FromResult(new[] {"normal"}); } [HttpGet("bugs")] public Task<string[]> GetBugs() { return Task.FromResult(new[] { "bugs" }); } [HttpGet("slow")] public Task<string[]> GetSlow() { return Task.FromResult(new[] { "slow" }); } [HttpPost] public void Post([FromBody] Test value) { } public class Test { public int Value1 { get; set; } public string Value2 { get; set; } } } } <file_sep>version: "3.4" services: envoy: build: ./ ports: - "2001:2001" container_name: envoy depends_on: - app1 - app2 app1: container_name: envoy-app1 environment: - "ASPNETCORE_URLS=http://+:5000" build: ../app1 app2: container_name: envoy-app2 environment: - "ASPNETCORE_URLS=http://+:5003" build: ../app2
5f7cbf14c74a8d5fdb43eb553d6a6d76c18c691f
[ "C#", "Dockerfile", "YAML" ]
5
Dockerfile
DanielDziubecki/mirroring-sample
44c0abd0068bfbc078bfb231d2a56157d614348a
1fa5bd4b7e873c848ee106c0860288aa8b245bee
refs/heads/master
<file_sep># StudentInfo click on http://localhost:8080/ search for students with student id( sample ids-123451,123452,123453,123454,123455,123456) <file_sep>package com.example.student.controller; import java.util.List; import java.util.Optional; import javax.validation.Valid; import javax.validation.constraints.Digits; import javax.validation.constraints.Size; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.example.student.dao.StudentDao; import com.example.student.model.Student; @Validated @Controller public class StudentController { @Autowired private StudentDao dao; /* * @RequestMapping("/") public ModelAndView frontend(){ return new * ModelAndView("home.html"); }*/ @GetMapping("/") public String showForm(Model model) { model.addAttribute("st",new Student()); return "home.html"; } @RequestMapping(value={"/student","/student/{sid}"}, method = RequestMethod.GET) public ResponseEntity<ResponseEntity<Student>> getStudent( @RequestParam @Size(max=6 ,min=6,message="6 digits required")String sid ) { ResponseEntity<Student> st=dao.fineOne(sid); if(st==null) { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); } if(st.getStatusCode().is5xxServerError()) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } return ResponseEntity.of(Optional.of(st)); } } <file_sep>package com.example.student; import java.io.IOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class StudentInfoApplication { public static void main(String[] args) throws IOException { final Logger logger = LogManager.getLogger(StudentInfoApplication.class); SpringApplication.run(StudentInfoApplication.class, args); } }
002b67a884a5bdcbc6ffc663d7e7586136093aeb
[ "Markdown", "Java" ]
3
Markdown
PriyankaJyothish/StudentInfo
f1488b6fc08d5fbbee74af3c818cdfdc567172b3
6f9bdf27026fb3c47b17d1a4694d0546a4ff22ec
refs/heads/main
<file_sep># -*- coding: utf-8 -*- import turtle as t t.Screen() t.speed(0) t.pensize() def shape(size, sides): for i in range(sides): t.forward(sides) t.left(360/sides) t.right(180) t.penup() t.forward(240) t.left(90) t.forward(20) t.pendown() t.left(90) for j in range(18): for i in range(4): for colours in ['violet' , 'indigo' , 'blue' , 'green' , 'yellow' ,'orange' , 'red']: t.color(colours) shape(30,3) t.forward(10) t.left(90) t.forward(10) t.left(80) for i in range(4): for colours in ['violet' , 'indigo' , 'blue' , 'green' , 'yellow' , 'orange' , 'red']: t.color(colours) shape(30,3) t.forward(10) t.right(90) t.penup() t.forward(20) t.right(100) t.pendown() for i in range(4): for colours in ['violet' , 'indigo' , 'blue' , 'green' , 'yellow' , 'orange' , 'red']: t.color(colours) shape(30,3) t.forward(10) t.exitonclick()
83cfcb81eff2eb789b83a596e5018a741510afc4
[ "Python" ]
1
Python
LuanRamalho/Roda-Colorida-3
767b5a6a6f9d8fb0ce0590510205b76573f83532
20dd9243ef9f1917203af7a198a56b1bbb73b0e2
refs/heads/master
<file_sep>package list import ( "context" "encoding/json" "fmt" "time" "github.com/asaskevich/govalidator" "github.com/fox-one/mixin-cli/pkg/column" "github.com/fox-one/mixin-cli/pkg/jq" "github.com/fox-one/mixin-cli/session" "github.com/fox-one/mixin-sdk-go" "github.com/shopspring/decimal" "github.com/spf13/cobra" ) func NewCmdList() *cobra.Command { var opt struct { input mixin.TransferInput } cmd := &cobra.Command{ Use: "list", Short: "list assets", RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() s := session.From(ctx) client, err := s.GetClient() if err != nil { return err } var assets []*mixin.Asset if len(opt.input.OpponentMultisig.Receivers) > 0 && opt.input.OpponentMultisig.Threshold > 0 { assets, err = readMultisignAssets(ctx, client, opt.input) } else { assets, err = client.ReadAssets(ctx) } if err != nil { return err } // filter assets with positive balance var ( idx int totalValue decimal.Decimal ) for _, asset := range assets { if !asset.Balance.IsPositive() { continue } totalValue = totalValue.Add(asset.PriceUSD.Mul(asset.Balance)) assets[idx] = asset idx++ } assets = assets[:idx] data, _ := json.Marshal(assets) fields := []string{"asset_id", "symbol", "name", "balance"} for _, arg := range args { if !govalidator.IsIn(arg, fields...) { fields = append(fields, arg) } } lines, err := jq.ParseObjects(data, fields...) if err != nil { return err } fmt.Println(column.Print(lines)) fmt.Println("Total USD Value:", totalValue) return nil }, } cmd.Flags().StringSliceVar(&opt.input.OpponentMultisig.Receivers, "receivers", nil, "multisig receivers") cmd.Flags().Uint8Var(&opt.input.OpponentMultisig.Threshold, "threshold", 0, "multisig threshold") return cmd } func readMultisignAssets(ctx context.Context, client *mixin.Client, input mixin.TransferInput) ([]*mixin.Asset, error) { assets, err := mixin.ReadMultisigAssets(ctx) if err != nil { return nil, err } assetMap := map[string]*mixin.Asset{} for _, asset := range assets { assetMap[asset.AssetID] = asset } result := []*mixin.Asset{} resultMap := map[string]*mixin.Asset{} offset := time.Time{} limit := 500 for { outputs, err := client.ListMultisigOutputs(ctx, mixin.ListMultisigOutputsOption{ Members: input.OpponentMultisig.Receivers, Threshold: input.OpponentMultisig.Threshold, Offset: offset, Limit: limit, OrderByCreated: true, State: mixin.UTXOStateUnspent, }) if err != nil { return nil, err } if len(outputs) == 0 || offset.Equal(outputs[len(outputs)-1].CreatedAt) { break } noMore := len(outputs) < limit if outputs[0].CreatedAt.Equal(offset) { outputs = outputs[1:] } for _, output := range outputs { a := resultMap[output.AssetID] if a == nil { a = assetMap[output.AssetID] if a == nil { a = &mixin.Asset{ AssetID: output.AssetID, Symbol: "-", Name: "-", } } a.Balance = decimal.Zero result = append(result, a) resultMap[output.AssetID] = a } a.Balance = a.Balance.Add(output.Amount) } if noMore { break } offset = outputs[len(outputs)-1].CreatedAt } return result, nil } <file_sep>package sign import ( "encoding/json" "fmt" "net/http" "net/http/httputil" "net/url" "time" "github.com/fox-one/mixin-cli/session" "github.com/fox-one/mixin-sdk-go" "github.com/nojima/httpie-go/exchange" "github.com/nojima/httpie-go/input" "github.com/spf13/cobra" ) func NewCmdSign() *cobra.Command { var opt struct { exp time.Duration raw string scope string dumpRequest bool } cmd := &cobra.Command{ Use: "sign", Args: cobra.MinimumNArgs(1), Short: "sign token with custom exp & scope", RunE: func(cmd *cobra.Command, args []string) error { s := session.From(cmd.Context()) in, err := input.ParseArgs(args, cmd.InOrStdin(), &input.Options{JSON: true}) if err != nil { return err } host, _ := url.Parse(mixin.GetRestyClient().HostURL) in.URL.Host = host.Host in.URL.Scheme = host.Scheme in.Header.Fields = append(in.Header.Fields, input.Field{ Name: "User-Agent", Value: "mixin-cli/" + s.Version, }) if opt.raw != "" { var raw json.RawMessage if err := json.Unmarshal([]byte(opt.raw), &raw); err != nil { return fmt.Errorf("json decode raw body failed: %w", err) } in.Method = http.MethodPost in.Body = input.Body{ BodyType: input.RawBody, Raw: raw, } } req, err := exchange.BuildHTTPRequest(in, &exchange.Options{}) if err != nil { return err } if opt.dumpRequest { b, err := httputil.DumpRequest(req, true) if err != nil { return err } cmd.Println(string(b), "\n") } sig := mixin.SignRequest(req) store, err := s.GetKeystore() if err != nil { return err } if opt.scope != "" { store.Scope = opt.scope } auth, err := mixin.AuthFromKeystore(store) if err != nil { return err } requestID := mixin.RandomTraceID() uri := req.URL.Path if q := req.URL.RawQuery; q != "" { uri += "?" + q } cmd.Printf("sign %s %s with request id %s & exp %s\n\n", req.Method, uri, requestID, opt.exp) token := auth.SignToken(sig, requestID, opt.exp) _, err = fmt.Fprint(cmd.OutOrStdout(), token) return err }, } cmd.Flags().DurationVar(&opt.exp, "exp", time.Minute, "token expire duration") cmd.Flags().StringVar(&opt.raw, "raw", "", "raw json body") cmd.Flags().BoolVar(&opt.dumpRequest, "dump", false, "dump request information") cmd.Flags().StringVar(&opt.scope, "scope", "FULL", "jwt token scope") return cmd } <file_sep>package search import ( "encoding/json" "fmt" "github.com/fox-one/mixin-cli/session" "github.com/spf13/cobra" ) func NewCmdSearch() *cobra.Command { cmd := &cobra.Command{ Use: "search <mixin id or identity number>", Short: "search user by mixin id", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() s := session.From(ctx) client, err := s.GetClient() if err != nil { return err } user, err := client.ReadUser(ctx, args[0]) if err != nil { return err } data, _ := json.MarshalIndent(user, "", " ") fmt.Fprintln(cmd.OutOrStdout(), string(data)) return nil }, } return cmd } <file_sep>package cmdutil import ( "encoding/json" "fmt" "path" "github.com/fox-one/mixin-sdk-go" jsoniter "github.com/json-iterator/go" "github.com/mitchellh/go-homedir" "github.com/spf13/viper" ) type Keystore struct { *mixin.Keystore Pin string `json:"pin,omitempty"` } func DecodeKeystore(b []byte) (*mixin.Keystore, string, error) { var store Keystore if err := json.Unmarshal(b, &store); err != nil { return nil, "", fmt.Errorf("json decode keystore failed: %w", err) } return store.Keystore, store.Pin, nil } func (store *Keystore) String() string { b, _ := json.MarshalIndent(store, "", " ") return string(b) } func LookupAndLoadKeystore(name string) ([]byte, error) { home, err := homedir.Dir() if err != nil { return nil, err } v := viper.New() v.SetConfigName(name) v.SetConfigType("json") v.SetConfigType("yaml") v.AddConfigPath(path.Join(home, ".mixin-cli")) if err := v.ReadInConfig(); err != nil { return nil, err } return jsoniter.Marshal(v.AllSettings()) } <file_sep>package withdraw import ( "encoding/json" "errors" "fmt" "github.com/fox-one/mixin-cli/cmdutil" "github.com/fox-one/mixin-cli/session" "github.com/fox-one/mixin-sdk-go" "github.com/manifoldco/promptui" "github.com/shopspring/decimal" "github.com/spf13/cobra" ) func NewCmdWithdraw() *cobra.Command { var opt struct { yes bool tag string memo string } cmd := &cobra.Command{ Use: "withdraw <asset> <amount> <address>", Short: "withdraw to another wallet address", Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() s := session.From(ctx) client, err := s.GetClient() if err != nil { return err } assetID := args[0] asset, err := client.ReadAsset(ctx, assetID) if err != nil { return fmt.Errorf("read asset %s failed: %w", assetID, err) } chain := asset if asset.AssetID != asset.ChainID { chain, err = client.ReadAsset(ctx, asset.ChainID) if err != nil { return fmt.Errorf("read asset %s failed: %w", asset.ChainID, err) } } amount, _ := decimal.NewFromString(args[1]) if !amount.IsPositive() { return errors.New("amount must be positive") } pin, err := cmdutil.GetOrReadPin(s) if err != nil { return fmt.Errorf("read pin failed: %w", err) } address, err := client.CreateAddress(ctx, mixin.CreateAddressInput{ AssetID: asset.AssetID, Destination: args[2], Tag: opt.tag, Label: "by mixin-cli", }, pin) if err != nil { return fmt.Errorf("create address failed: %w", err) } cmd.Printf("withdraw %s %s (balance %s) to address %q & tag %q with fee %s %s (balance %s)\n", amount, asset.Symbol, asset.Balance, address.Destination, address.Tag, address.Fee, chain.Symbol, chain.Balance) if opt.yes || conformWithdraw() { snapshot, err := client.Withdraw(ctx, mixin.WithdrawInput{ AddressID: address.AddressID, Amount: amount, TraceID: mixin.RandomTraceID(), Memo: opt.memo, }, pin) if err != nil { return err } data, _ := json.MarshalIndent(snapshot, "", " ") fmt.Fprintln(cmd.OutOrStdout(), string(data)) } return nil }, } cmd.Flags().StringVar(&opt.tag, "tag", "", "address tag") cmd.Flags().StringVar(&opt.memo, "memo", "", "payment memo") cmd.Flags().BoolVar(&opt.yes, "yes", false, "approve payment automatically") return cmd } func conformWithdraw() bool { prompt := promptui.Prompt{ Label: "Continue", IsConfirm: true, } result, err := prompt.Run() if err != nil { return false } switch result { case "y", "Y": return true default: return false } } <file_sep>package pay import ( "encoding/json" "errors" "fmt" "github.com/fox-one/mixin-cli/cmdutil" "github.com/fox-one/mixin-cli/session" "github.com/fox-one/mixin-sdk-go" "github.com/manifoldco/promptui" "github.com/shopspring/decimal" "github.com/spf13/cobra" ) func NewCmdPay() *cobra.Command { var opt struct { memo string yes bool } cmd := &cobra.Command{ Use: "pay", Short: "transfer assets to other users", Long: "transfer {opponent_id} {asset_id} {amount} {memo}", Args: cobra.MinimumNArgs(3), RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() s := session.From(ctx) client, err := s.GetClient() if err != nil { return err } opponentID := args[0] opponent, err := client.ReadUser(ctx, opponentID) if err != nil { return fmt.Errorf("read opponent with id %q failed: %w", opponentID, err) } assetID := args[1] asset, err := client.ReadAsset(ctx, assetID) if err != nil { return fmt.Errorf("read asset failed: %w", err) } amount, _ := decimal.NewFromString(args[2]) if !amount.IsPositive() { return errors.New("amount must be positive") } memo := opt.memo if memo == "" && len(args) >= 4 { memo = args[3] } pin, err := cmdutil.GetOrReadPin(s) if err != nil { return fmt.Errorf("read pin failed: %w", err) } cmd.Printf("transfer %s %s (balance %s) to %s with memo %q\n", amount, asset.Symbol, asset.Balance, opponent.FullName, memo) if opt.yes || conformTransfer() { snapshot, err := client.Transfer(ctx, &mixin.TransferInput{ AssetID: assetID, OpponentID: opponent.UserID, Amount: amount, TraceID: mixin.RandomTraceID(), Memo: memo, }, pin) if err != nil { return err } data, _ := json.MarshalIndent(snapshot, "", " ") fmt.Fprintln(cmd.OutOrStdout(), string(data)) } return nil }, } cmd.Flags().StringVar(&opt.memo, "memo", "", "payment memo") cmd.Flags().BoolVar(&opt.yes, "yes", false, "approve payment automatically") return cmd } func conformTransfer() bool { prompt := promptui.Prompt{ Label: "Continue", IsConfirm: true, } result, err := prompt.Run() if err != nil { return false } switch result { case "y", "Y": return true default: return false } } <file_sep>package ownership import ( "fmt" "github.com/gofrs/uuid" "github.com/fox-one/mixin-cli/cmdutil" "github.com/fox-one/mixin-cli/session" "github.com/spf13/cobra" ) func NewCmdTransfer() *cobra.Command { var opt struct { UserID string } cmd := &cobra.Command{ Use: "transfer", Short: "transfer ownership", RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() s := session.From(ctx) client, err := s.GetClient() if err != nil { return err } if uuid.FromStringOrNil(opt.UserID).IsNil() { return fmt.Errorf("invalid user_id: %s", opt.UserID) } pin, err := cmdutil.GetOrReadPin(s) if err != nil { return fmt.Errorf("read pin failed: %w", err) } return client.TransferOwnership(ctx, opt.UserID, pin) }, } cmd.Flags().StringVar(&opt.UserID, "user_id", "", "user id") return cmd } <file_sep>module github.com/fox-one/mixin-cli go 1.19 require ( github.com/andrew-d/go-termutil v0.0.0-20150726205930-009166a695a2 github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 github.com/fox-one/mixin-sdk-go v1.7.11 github.com/fox-one/pkg v1.5.8 github.com/gofrs/uuid v4.4.0+incompatible github.com/iancoleman/strcase v0.3.0 github.com/itchyny/gojq v0.12.13 github.com/json-iterator/go v1.1.12 github.com/manifoldco/promptui v0.9.0 github.com/mitchellh/go-homedir v1.1.0 github.com/nojima/httpie-go v0.7.0 github.com/ryanuber/columnize v2.1.2+incompatible github.com/shopspring/decimal v1.3.1 github.com/spf13/cast v1.5.1 github.com/spf13/cobra v1.7.0 github.com/spf13/viper v1.16.0 golang.org/x/term v0.11.0 ) require ( filippo.io/edwards25519 v1.0.0 // indirect github.com/btcsuite/btcutil v1.0.3-0.20211129182920-9c4bbabe7acd // indirect github.com/chzyer/readline v1.5.1 // indirect github.com/fox-one/msgpack v1.0.0 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/go-resty/resty/v2 v2.7.0 // indirect github.com/golang-jwt/jwt v3.2.2+incompatible // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/itchyny/timefmt-go v0.1.5 // indirect github.com/klauspost/cpuid/v2 v2.2.5 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/mdp/qrterminal v1.0.1 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect github.com/pelletier/go-toml/v2 v2.0.9 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/spf13/afero v1.9.5 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/subosito/gotenv v1.4.2 // indirect github.com/vmihailenco/tagparser v0.1.2 // indirect github.com/zeebo/blake3 v0.2.3 // indirect golang.org/x/crypto v0.12.0 // indirect golang.org/x/net v0.14.0 // indirect golang.org/x/sync v0.3.0 // indirect golang.org/x/sys v0.11.0 // indirect golang.org/x/text v0.12.0 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/protobuf v1.31.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect rsc.io/qr v0.2.0 // indirect ) <file_sep>package tr import ( "github.com/fox-one/mixin-sdk-go" "github.com/spf13/cobra" ) var commands = []*cobra.Command{ { Use: "addressToAsset", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { cmd.Println(addressToAssetID(args[0])) }, }, { Use: "membersHash", Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { cmd.Println(mixin.HashMembers(args)) }, }, } func Bind(root *cobra.Command) { for _, cmd := range commands { root.AddCommand(cmd) } } <file_sep>package user import ( "github.com/fox-one/mixin-cli/cmd/user/create" "github.com/fox-one/mixin-cli/cmd/user/me" "github.com/fox-one/mixin-cli/cmd/user/search" "github.com/spf13/cobra" ) func NewCmdUser() *cobra.Command { cmd := &cobra.Command{ Use: "user", Short: "manager users", } cmd.AddCommand(create.NewCmdCreate()) cmd.AddCommand(search.NewCmdSearch()) cmd.AddCommand(me.NewCmdMe()) return cmd } <file_sep>package session import ( "context" "github.com/spf13/cobra" ) type contextKey struct{} func With(ctx context.Context, s *Session) context.Context { return context.WithValue(ctx, contextKey{}, s) } func From(ctx context.Context) *Session { return ctx.Value(contextKey{}).(*Session) } func FromCmd(cmd *cobra.Command) *Session { return From(cmd.Context()) } <file_sep>package cmdutil import ( "fmt" "syscall" "github.com/fox-one/mixin-cli/session" "golang.org/x/term" ) func GetOrReadPin(s *session.Session) (string, error) { pin := s.GetPin() if pin != "" { return pin, nil } for { fmt.Print("Enter PIN: ") inputData, err := term.ReadPassword(int(syscall.Stdin)) if err != nil { return "", err } fmt.Println() pin = string(inputData) if pin != "" { s.WithPin(pin) return pin, nil } } } <file_sep>package search import ( "encoding/json" "fmt" "github.com/asaskevich/govalidator" "github.com/fox-one/mixin-cli/pkg/column" "github.com/fox-one/mixin-cli/pkg/jq" "github.com/fox-one/mixin-cli/session" "github.com/gofrs/uuid" "github.com/spf13/cobra" ) func NewCmdSearch() *cobra.Command { cmd := &cobra.Command{ Use: "search <asset id or symbol>", Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() s := session.From(ctx) client, err := s.GetClient() if err != nil { return err } query := args[0] uri := fmt.Sprintf("/network/assets/search/%s", query) fields := []string{"asset_id", "symbol", "name", "chain_id", "price_usd"} parser := jq.ParseObjects if uuid.FromStringOrNil(query) != uuid.Nil { uri = fmt.Sprintf("/network/assets/%s", query) parser = jq.ParseObject fields = append(fields, "icon_url") } for _, field := range args[1:] { if !govalidator.IsIn(field, fields...) { fields = append(fields, field) } } var body json.RawMessage if err := client.Get(ctx, uri, nil, &body); err != nil { return err } lines, err := parser(body, fields...) if err != nil { return err } fmt.Fprintln(cmd.OutOrStdout(), column.Print(lines)) return nil }, } return cmd } <file_sep>package keystore import ( "github.com/spf13/cobra" ) func NewCmdKeystore() *cobra.Command { cmd := &cobra.Command{ Use: "keystore", Short: "update keystore", } cmd.AddCommand(NewCmdPin()) return cmd } <file_sep>package keystore import ( "crypto/rand" "github.com/fox-one/mixin-cli/session" "github.com/fox-one/mixin-sdk-go" "github.com/spf13/cobra" ) func NewCmdPin() *cobra.Command { cmd := &cobra.Command{ Use: "pin", Short: "keystore pin", } cmd.AddCommand(NewCmdCreateTipPin()) cmd.AddCommand(NewCmdUpdatePin()) cmd.AddCommand(NewCmdVerifyPin()) return cmd } func NewCmdCreateTipPin() *cobra.Command { cmd := &cobra.Command{ Use: "new-key", RunE: func(cmd *cobra.Command, args []string) error { cmd.Println("new tip pin:", mixin.NewKey(rand.Reader)) return nil }, } return cmd } func NewCmdVerifyPin() *cobra.Command { cmd := &cobra.Command{ Use: "verify", RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() s := session.From(ctx) client, err := s.GetClient() if err != nil { return err } if err := client.VerifyPin(ctx, s.GetPin()); err != nil { cmd.PrintErrf("verify pin failed: %s\n%s", s.GetPin(), err.Error()) return err } cmd.Println("pin verified!") return nil }, } return cmd } func NewCmdUpdatePin() *cobra.Command { cmd := &cobra.Command{ Use: "update <new-pin>", Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() s := session.From(ctx) client, err := s.GetClient() if err != nil { return err } newPin := args[0] if err := mixin.ValidatePinPattern(newPin); err != nil { cmd.PrintErrf("invalid pin: %s", newPin) return err } { newPin := newPin if len(newPin) > 6 { key, err := mixin.KeyFromString(newPin) if err != nil { cmd.PrintErrf("invalid pin: %s", newPin) return err } newPin = key.Public().String() } if err := client.ModifyPin(ctx, s.GetPin(), newPin); err != nil { cmd.PrintErrf("modify pin failed: %s", err.Error()) return err } } cmd.Printf("pin updated: %s", newPin) return nil }, } return cmd } <file_sep>package upload import ( "fmt" "io/ioutil" "os" "github.com/fox-one/mixin-cli/session" "github.com/fox-one/mixin-sdk-go" "github.com/spf13/cobra" ) func NewCmdUpload() *cobra.Command { cmd := &cobra.Command{ Use: "upload <file>", Short: "upload file to mixin storage", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() s := session.From(ctx) client, err := s.GetClient() if err != nil { return err } f, err := os.Open(args[0]) if err != nil { return err } defer f.Close() body, _ := ioutil.ReadAll(f) attachment, err := client.CreateAttachment(ctx) if err != nil { return err } if err := mixin.UploadAttachment(ctx, attachment, body); err != nil { return err } fmt.Fprintln(cmd.OutOrStdout(), attachment.AttachmentID) fmt.Fprintln(cmd.OutOrStdout(), attachment.ViewURL) return nil }, } return cmd } <file_sep>package column import ( "github.com/ryanuber/columnize" ) func Print(lines []string) string { cfg := columnize.DefaultConfig() cfg.Delim = "," cfg.Glue = " " cfg.Prefix = "" cfg.Empty = "NULL" return columnize.Format(lines, cfg) } <file_sep>package jq import ( "encoding/json" "fmt" "strings" "github.com/iancoleman/strcase" "github.com/itchyny/gojq" "github.com/spf13/cast" ) func Parse(v interface{}, query string) ([]string, error) { q, err := gojq.Parse(query) if err != nil { return nil, err } var outputs []string iter := q.Run(v) for { v, ok := iter.Next() if !ok { break } if err, ok := v.(error); ok { return nil, err } outputs = append(outputs, cast.ToString(v)) } return outputs, nil } func formatFields(fields []string, actions ...string) []string { formatted := make([]string, len(fields)) for i, field := range fields { field = "." + field if len(actions) > 0 { field = fmt.Sprintf("(%s|%s)", field, strings.Join(actions, ",")) } formatted[i] = field } return formatted } func buildObjectsQuery(fields ...string) string { return ".[] | " + strings.Join(formatFields(fields, "tostring"), ` + "," + `) } func ParseObjects(data []byte, fields ...string) ([]string, error) { query := buildObjectsQuery(fields...) var objects []interface{} if err := json.Unmarshal(data, &objects); err != nil { return nil, err } results, err := Parse(objects, query) if err != nil { return nil, err } headers := make([]string, len(fields)) for i, field := range fields { headers[i] = strcase.ToCamel(field) } return append([]string{strings.Join(headers, ",")}, results...), nil } func buildObjectQuery(fields ...string) string { return strings.Join(formatFields(fields), `,`) } func ParseObject(data []byte, fields ...string) ([]string, error) { query := buildObjectQuery(fields...) object := make(map[string]interface{}) if err := json.Unmarshal(data, &object); err != nil { return nil, err } results, err := Parse(object, query) if err != nil { return nil, err } for i, result := range results { results[i] = strcase.ToCamel(fields[i]) + "," + result } return results, nil } <file_sep>package transfer import ( "encoding/json" "errors" "fmt" "github.com/fox-one/mixin-cli/cmdutil" "github.com/fox-one/mixin-cli/session" "github.com/fox-one/mixin-sdk-go" "github.com/fox-one/pkg/qrcode" "github.com/manifoldco/promptui" "github.com/shopspring/decimal" "github.com/spf13/cobra" ) func NewCmdTransfer() *cobra.Command { var opt struct { input mixin.TransferInput amount string qrcode bool yes bool } cmd := &cobra.Command{ Use: "transfer", RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() s := session.From(ctx) client, err := s.GetClient() if err != nil { return err } input := opt.input input.Amount, _ = decimal.NewFromString(opt.amount) if input.TraceID == "" { input.TraceID = mixin.RandomTraceID() } if opt.qrcode && input.OpponentID == "" { input.OpponentID = client.ClientID } if !input.Amount.IsPositive() { return errors.New("amount must be positive") } asset, err := client.ReadAsset(ctx, input.AssetID) if err != nil { return fmt.Errorf("read asset failed: %w", err) } if opt.qrcode { url := mixin.URL.Pay(&input) if len(input.OpponentMultisig.Receivers) > 0 { payment, err := client.VerifyPayment(ctx, input) if err != nil { return fmt.Errorf("verify payment failed: %w", err) } url = mixin.URL.Codes(payment.CodeID) } cmd.Println(url) qrcode.Print(url) return nil } pin, err := cmdutil.GetOrReadPin(s) if err != nil { return fmt.Errorf("read pin failed: %w", err) } var ( receiverNames []string execute func() (interface{}, error) ) if count := len(input.OpponentMultisig.Receivers); count > 0 { if t := int(input.OpponentMultisig.Threshold); t <= 0 || t > count { return errors.New("threshold must be in range [1, receivers count]") } for _, id := range input.OpponentMultisig.Receivers { user, err := client.ReadUser(ctx, id) if err != nil { return fmt.Errorf("read user failed: %w", err) } receiverNames = append(receiverNames, user.FullName) execute = func() (interface{}, error) { return client.Transaction(ctx, &input, pin) } } } else { user, err := client.ReadUser(ctx, input.OpponentID) if err != nil { return fmt.Errorf("read user failed: %w", err) } receiverNames = append(receiverNames, user.FullName) execute = func() (interface{}, error) { return client.Transfer(ctx, &input, pin) } } cmd.Printf("Transfer %s %s to %s\n", input.Amount, asset.Symbol, receiverNames) if confirmRequired := !(opt.yes || opt.qrcode); confirmRequired && !conformTransfer() { return nil } result, err := execute() if err != nil { return fmt.Errorf("transfer failed: %w", err) } data, _ := json.MarshalIndent(result, "", " ") fmt.Fprintln(cmd.OutOrStdout(), string(data)) return nil }, } cmd.Flags().StringVar(&opt.input.AssetID, "asset", "", "asset id") cmd.Flags().StringVar(&opt.amount, "amount", "", "amount") cmd.Flags().StringVar(&opt.input.TraceID, "trace", "", "trace id") cmd.Flags().StringVar(&opt.input.Memo, "memo", "", "memo") cmd.Flags().StringVar(&opt.input.OpponentID, "opponent", "", "opponent id") cmd.Flags().StringSliceVar(&opt.input.OpponentMultisig.Receivers, "receivers", nil, "multisig receivers") cmd.Flags().Uint8Var(&opt.input.OpponentMultisig.Threshold, "threshold", 0, "multisig threshold") cmd.Flags().BoolVar(&opt.qrcode, "qrcode", false, "show qrcode") cmd.Flags().BoolVar(&opt.yes, "yes", false, "approve payment automatically") return cmd } func conformTransfer() bool { prompt := promptui.Prompt{ Label: "Continue", IsConfirm: true, } result, err := prompt.Run() if err != nil { return false } switch result { case "y", "Y": return true default: return false } } <file_sep>package asset import ( "github.com/fox-one/mixin-cli/cmd/asset/list" "github.com/fox-one/mixin-cli/cmd/asset/search" "github.com/spf13/cobra" ) func NewCmdAsset() *cobra.Command { cmd := &cobra.Command{ Use: "asset", Short: "manager assets", } cmd.AddCommand(list.NewCmdList()) cmd.AddCommand(search.NewCmdSearch()) return cmd } <file_sep># mixin-cli Command-line applications to manage mixin dapps ## Install ### From Source Code ```bash $ git clone <EMAIL>:fox-one/mixin-cli.git $ cd mixin-cli $ go install ``` ## KeyStore ### Format ```json5 { "client_id": "", "session_id": "", "private_key": "", "pin_token": "", "pin": "", // optional } ``` There are three ways to specify the keystore: 1. Use the ```--file``` option to specify the keystore file path. 2. Use ```--stdin``` option to read keystore content from os.Stdin. 3. Use the name of keystore file in ```~/.mixin-cli```, for example, ```mixin-cli bot``` will use ~/.mixin-cli/bot.json. 4. Use the ```--pin``` to specify the pin code. ## Commands ### List assets with balance ```bash $ mixin-cli asset list AssetId Symbol Name Balance 965e5c6e-434c-3fa9-b780-c50f43cd955c CNB <NAME> 9998898.552 Total USD Value: 0.09998898552 ``` ### Search asset with asset id or symbol search by asset id: ```bash $ mixin-cli asset search 965e5c6e-434c-3fa9-b780-c50f43cd955c AssetId 965e5c6e-434c-3fa9-b780-c50f43cd955c Symbol CNB Name <NAME> ChainId 43d61dcd-e413-450d-80b8-101d5e903357 PriceUsd 0.00000001 IconUrl https://mixin-images.zeromesh.net/0sQY63dDM<KEY> ``` search by asset symbol: ```bash $ mixin-cli asset search BOX AssetId Symbol Name ChainId PriceUsd f5ef6b5d-cc5a-3d90-b2c0-a2fd386e7a3c BOX BOX Token <PASSWORD> <PASSWORD> 2fea3c35-7fb7-3e01-91b1-99b3c744a729 BOX BOX Token <PASSWORD> 0 20b8c101-dffa-31c9-bf6e-d93a086686af BOX BOX Token <PASSWORD> 0 ``` ### Custom http request of mixin api get request with query: ```bash # GET /users/25566?foo=bar $ mixin-cli http /users/25566 foo==bar { "type": "user", "user_id": "fcb87491-4fa0-4c2f-b387-262b63cbc112", "identity_number": "25566", "phone": "", "full_name": "人", "biography": "Send me any transfer to start a conversation 💰", "avatar_url": "https://mixin-images.zeromesh.net/MiGX1hgHm7cpLznNYlaxgPTcj8LisYjAUUwcmOrZcwBgIZqaAUSfeuirJ2hAcZES9y3T6dDy31ljbbD2dpJHaHFgn_kkXlAZm_o=s256", "relationship": "FRIEND", "mute_until": "2020-05-25T08:23:09.409520437Z", "created_at": "2017-11-27T02:27:58.398423112Z", "is_verified": false, "is_scam": false } ``` post request with simple body: ```bash $ mixin-cli http post /attachments number:=1 foo=bar { "type": "attachment", "attachment_id": "a3bde58a-4861-418b-860d-aa26a001ac7b", "upload_url": "https://moments-shou-tv.s3.amazonaws.com/mixin/attachments/1638364433-4c67c4840fa610cb2570702a76c03fc79d46f29a8947bd24264fa624f2d51543?X-Amz-Algorithm=AWS4-HMAC-SHA256\u0026X-Amz-Credential=AKIAJW6D5Q3Z5WYA2KRQ%2F20211201%2Fus-east-1%2Fs3%2Faws4_request\u0026X-Amz-Date=20211201T131353Z\u0026X-Amz-Expires=21600\u0026X-Amz-SignedHeaders=content-type%3Bhost%3Bx-amz-acl\u0026X-Amz-Signature=90d8e950f17b87af94010d24e6a35f89c5325d6373afe5cfc7fe451eb32babd2", "view_url": "https://mixin-assets.zeromesh.net/mixin/attachments/1638364433-4c67c4840fa610cb2570702a76c03fc79d46f29a8947bd24264fa624f2d51543", "created_at": "2021-12-01T13:13:53.756443264Z" } ``` post request with raw json body ```bash $ mixin-cli http post /attachments --raw '{"foo":"bar"}' { "type": "attachment", "attachment_id": "db3e616e-8e91-4e08-b75c-890ad579649e", "upload_url": "https://moments-shou-tv.s3.amazonaws.com/mixin/attachments/1638364537-9b603a75c11768e1193401048fcf5ae5f01fff97ef7eeca40ecc0908407e7788?X-Amz-Algorithm=AWS4-HMAC-SHA256\u0026X-Amz-Credential=AKIAJW6D5Q3Z5WYA2KRQ%2F20211201%2Fus-east-1%2Fs3%2Faws4_request\u0026X-Amz-Date=20211201T131537Z\u0026X-Amz-Expires=21600\u0026X-Amz-SignedHeaders=content-type%3Bhost%3Bx-amz-acl\u0026X-Amz-Signature=4458a68e361c72f0ba17de9902ca4eddf407ea6dd89512c9bd7008100ae4ccc0", "view_url": "https://mixin-assets.zeromesh.net/mixin/attachments/1638364537-9b603a75c11768e1193401048fcf5ae5f01fff97ef7eeca40ecc0908407e7788", "created_at": "2021-12-01T13:15:37.515308839Z" } ``` ### Generate mixin auth token with custom path & expire duration ```bash $ mixin-cli sign /fiats --exp 262800h sign GET /fiats with request id b1785af1-6974-4cbe-a8e0-4b1f6d4680ea & exp 262800h0m0s <KEY>G4Ae0I1ep-fabSGDM-<KEY> ``` ### Transfer to any opponent ``` $ mixin-cli transfer --asset 965e5c6e-434c-3fa9-b780-c50f43cd955c \ --amount 100 \ --opponent 8017d200-7870-4b82-b53f-74bae1d2dad7 \ --memo hahaha { "snapshot_id": "fbc06508-1d8d-49cb-b17b-af7c1532e06c", "created_at": "2021-12-01T13:20:34.81424Z", "trace_id": "6e0e4349-8f30-4f18-96da-0f0264cf3149", "asset_id": "965e5c6e-434c-3fa9-b780-c50f43cd955c", "opponent_id": "8017d200-7870-4b82-b53f-74bae1d2dad7", "amount": "-100", "opening_balance": "9998898.552", "closing_balance": "9998798.552", "memo": "hahaha", "type": "transfer" } ``` ### Transfer to a multisig group ```bash $ mixin-cli transfer --asset 965e5c6e-434c-3fa9-b780-c50f43cd955c \ --amount 100 \ --receivers 8017d200-7870-4b82-b53f-74bae1d2dad7 \ --receivers 170e40f0-627f-4af2-acf5-0f25c009e523 \ --threshold 2 \ --memo hahaha { "type": "raw", "snapshot": "", "opponent_key": "", "asset_id": "965e5c6e-434c-3fa9-b780-c50f43cd955c", "amount": "-100", "trace_id": "917ec61f-d703-472f-afd4-6f32c99ea8af", "memo": "hahaha", "state": "signed", "created_at": "1970-01-01T00:03:39+00:03", "transaction_hash": "941bd691338f8077cfe7edb53a0315c0299e514921f1af9964828629f413ee95", "snapshot_at": "0001-01-01T00:00:00Z" } ``` ### Upload a file as attachment ```bash $ mixin-cli upload ~/path/to/the/file # attachment id 9b490939-9daf-4f09-8296-54f995f143d7 https://mixin-assets.zeromesh.net/mixin/attachments/1638365395-614893646cab4f829ac6936ea57345bc27e6751f36e22b06dbbbd9df30c7c754 ``` ### Create a new user ```bash $ mixin-cli user create haha --pin 123456 { "client_id": "041d9a17-fb5d-33fb-9efc-182dcc68b58f", "session_id": "b6a3430c-0b00-4bba-9f8f-555d0ef3c9c2", "private_key": "<KEY> "pin_token": "<KEY> "scope": "", "pin": "123456" } ``` ### Show own profile ```bash $ mixin-cli user me { "user_id": "5c4f30a6-1f49-43c3-b37b-c01aae5191af", "identity_number": "7000101692", "phone": "5c4f30a6-1f49-43c3-b37b-c01aae5191af", "full_name": "echo", "biography": "我是群消息通知机器人 echo。\r\n群主拉我进群,开始使用吧!", "avatar_url": "https://mixin-images.zeromesh.net/kQ4h_g2V8VRcl4DjqAhWJcthV4yEXl8Ytjrc8fx777LIA3ernaxU7UqcFolYKvWXJOtY7pkMG8NvKCtAhEJM3ptW=s256", "relationship": "ME", "mute_until": "0001-01-01T00:00:00Z", "created_at": "2018-12-23T14:20:34.188140494Z", "session_id": "db2f32bb-f2a5-42b1-b946-63a4e129b02c", "code_id": "7d97440b-fb4f-4ddd-a74b-58d8806835e0", "code_url": "https://mixin.one/codes/7d97440b-fb4f-4ddd-a74b-58d8806835e0", "has_pin": true, "receive_message_source": "EVERYBODY", "accept_conversation_source": "EVERYBODY", "accept_search_source": "EVERYBODY", "fiat_currency": "USD", "app": { "updated_at": "2021-08-08T17:05:19.73808177Z", "app_id": "5c4f30a6-1f49-43c3-b37b-c01aae5191af", "app_number": "7000101692", "redirect_uri": "https://ocean.one/auth", "home_uri": "https://workflow.yiplee.com", "name": "echo", "icon_url": "https://mixin-images.zeromesh.net/6EoTjFGVMyPQJOz3JaCkGssmPbwLZviBEmLqmgXqLITQW_Q3DWiOAjmEHvGk8R53qebinHePo1Dq4ngTSD5fRw=s256", "description": "我是群消息通知机器人 echo。\r\n群主拉我进群,开始使用吧!", "capabilities": [ "GROUP", "IMMERSIVE", "CONTACT" ], "resource_patterns": [], "category": "TOOLS", "creator_id": "8017d200-7870-4b82-b53f-74bae1d2dad7" } } ``` ### Search user by mixin id or identity number ```bash $ mixin-cli user search 25566 { "user_id": "fcb87491-4fa0-4c2f-b387-262b63cbc112", "identity_number": "25566", "full_name": "人", "biography": "Send me any transfer to start a conversation 💰", "avatar_url": "https://mixin-images.zeromesh.net/MiGX1hgHm7cpLznNYlaxgPTcj8LisYjAUUwcmOrZcwBgIZqaAUSfeuirJ2hAcZES9y3T6dDy31ljbbD2dpJHaHFgn_kkXlAZm_o=s256", "relationship": "FRIEND", "mute_until": "2020-05-25T08:23:09.409520437Z", "created_at": "2017-11-27T02:27:58.398423112Z" } ``` <file_sep>/* Copyright © 2021 NAME HERE <EMAIL ADDRESS> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "context" "os" "github.com/fox-one/mixin-cli/cmd/root" "github.com/fox-one/mixin-cli/cmdutil" "github.com/fox-one/mixin-cli/session" "github.com/spf13/cobra" ) var ( version = "2.0.0" ) func main() { ctx := context.Background() s := &session.Session{Version: version} ctx = session.With(ctx, s) expandedArgs := []string{} if len(os.Args) > 0 { expandedArgs = os.Args[1:] } rootCmd := root.NewCmdRoot(version) if len(expandedArgs) > 0 && !hasCommand(rootCmd, expandedArgs) { name := expandedArgs[0] if b, err := cmdutil.LookupAndLoadKeystore(name); err == nil { if store, pin, err := cmdutil.DecodeKeystore(b); err == nil { s.WithKeystore(store) s.WithPin(pin) expandedArgs = expandedArgs[1:] } } } rootCmd.SetArgs(expandedArgs) if err := rootCmd.ExecuteContext(ctx); err != nil { rootCmd.PrintErrln("execute failed:", err) os.Exit(1) } } func hasCommand(rootCmd *cobra.Command, args []string) bool { c, _, err := rootCmd.Traverse(args) return err == nil && c != rootCmd } <file_sep>package root import ( "fmt" "net/url" "os" "github.com/andrew-d/go-termutil" "github.com/fox-one/mixin-cli/cmd/asset" "github.com/fox-one/mixin-cli/cmd/http" "github.com/fox-one/mixin-cli/cmd/keystore" "github.com/fox-one/mixin-cli/cmd/ownership" "github.com/fox-one/mixin-cli/cmd/pay" "github.com/fox-one/mixin-cli/cmd/sign" "github.com/fox-one/mixin-cli/cmd/tr" "github.com/fox-one/mixin-cli/cmd/transfer" "github.com/fox-one/mixin-cli/cmd/upload" "github.com/fox-one/mixin-cli/cmd/user" "github.com/fox-one/mixin-cli/cmd/withdraw" "github.com/fox-one/mixin-cli/cmdutil" "github.com/fox-one/mixin-cli/session" "github.com/fox-one/mixin-sdk-go" jsoniter "github.com/json-iterator/go" "github.com/spf13/cobra" "github.com/spf13/viper" ) func NewCmdRoot(version string) *cobra.Command { var opt struct { host string KeystoreFile string accessToken string Pin string Stdin bool } cmd := &cobra.Command{ Use: "mixin-cli <command> <subcommand> [flags]", Short: "Mixin CLI", Long: `Work seamlessly with Mixin from the command line.`, SilenceErrors: true, SilenceUsage: true, Version: version, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { s := session.From(cmd.Context()) v := viper.New() v.SetConfigType("json") v.SetConfigType("yaml") if opt.KeystoreFile != "" { f, err := os.Open(opt.KeystoreFile) if err != nil { return fmt.Errorf("open keystore file %s failed: %w", opt.KeystoreFile, err) } defer f.Close() _ = v.ReadConfig(f) } else if opt.Stdin && isStdinAvailable() { _ = v.ReadConfig(cmd.InOrStdin()) } if values := v.AllSettings(); len(values) > 0 { b, _ := jsoniter.Marshal(values) store, pin, err := cmdutil.DecodeKeystore(b) if err != nil { return fmt.Errorf("decode keystore failed: %w", err) } if opt.Pin != "" { pin = opt.Pin } s.WithKeystore(store) if pin != "" { s.WithPin(pin) } } if opt.accessToken != "" { s.WithAccessToken(opt.accessToken) } if cmd.Flags().Changed("host") { u, err := url.Parse(opt.host) if err != nil { return err } if u.Scheme == "" { u.Scheme = "https" } mixin.UseApiHost(u.String()) } return nil }, } cmd.PersistentFlags().StringVar(&opt.host, "host", mixin.DefaultApiHost, "custom api host") cmd.PersistentFlags().StringVarP(&opt.KeystoreFile, "file", "f", "", "keystore file path (default is $HOME/.mixin-cli/keystore.json)") cmd.PersistentFlags().StringVar(&opt.accessToken, "token", "", "custom access token") cmd.PersistentFlags().StringVar(&opt.Pin, "pin", "", "raw pin") cmd.PersistentFlags().BoolVar(&opt.Stdin, "stdin", false, "read keystore from standard input") cmd.AddCommand(sign.NewCmdSign()) cmd.AddCommand(http.NewCmdHttp()) cmd.AddCommand(user.NewCmdUser()) cmd.AddCommand(upload.NewCmdUpload()) cmd.AddCommand(pay.NewCmdPay()) cmd.AddCommand(transfer.NewCmdTransfer()) cmd.AddCommand(withdraw.NewCmdWithdraw()) cmd.AddCommand(asset.NewCmdAsset()) cmd.AddCommand(keystore.NewCmdKeystore()) cmd.AddCommand(ownership.NewCmdOwnership()) tr.Bind(cmd) return cmd } func isStdinAvailable() bool { return !termutil.Isatty(os.Stdin.Fd()) } <file_sep>package session import ( "errors" "github.com/fox-one/mixin-sdk-go" ) var ( ErrKeystoreNotProvided = errors.New("keystore not provided, use --file or --stdin") ) type Session struct { Version string store *mixin.Keystore token string pin string } func (s *Session) WithKeystore(store *mixin.Keystore) *Session { s.store = store return s } func (s *Session) WithAccessToken(token string) *Session { s.token = token return s } func (s *Session) WithPin(pin string) *Session { s.pin = pin return s } func (s *Session) GetKeystore() (*mixin.Keystore, error) { if s.store != nil { return s.store, nil } return nil, ErrKeystoreNotProvided } func (s *Session) GetPin() string { return s.pin } func (s *Session) GetClient() (*mixin.Client, error) { store, err := s.GetKeystore() if err != nil { return mixin.NewFromAccessToken(s.token), nil } return mixin.NewFromKeystore(store) } <file_sep>package me import ( "encoding/json" "fmt" "github.com/fox-one/mixin-cli/session" "github.com/spf13/cobra" ) func NewCmdMe() *cobra.Command { cmd := &cobra.Command{ Use: "me", RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() s := session.From(ctx) client, err := s.GetClient() if err != nil { return err } me, err := client.UserMe(ctx) if err != nil { return err } data, _ := json.MarshalIndent(me, "", " ") fmt.Fprintln(cmd.OutOrStdout(), string(data)) return nil }, } return cmd } <file_sep>package tr import ( "crypto/md5" "io" "strings" "github.com/gofrs/uuid" ) const ethAssetID = "43d61dcd-e413-450d-80b8-101d5e903357" func addressToAssetID(contractAddr string) string { h := md5.New() _, _ = io.WriteString(h, ethAssetID) _, _ = io.WriteString(h, strings.ToLower(contractAddr)) sum := h.Sum(nil) sum[6] = (sum[6] & 0x0f) | 0x30 sum[8] = (sum[8] & 0x3f) | 0x80 return uuid.FromBytesOrNil(sum).String() } <file_sep>package ownership import ( "github.com/spf13/cobra" ) func NewCmdOwnership() *cobra.Command { cmd := &cobra.Command{ Use: "ownership", Short: "manage Dapp ownership, only available for tip PIN Dapp", } cmd.AddCommand(NewCmdTransfer()) return cmd } <file_sep>package create import ( "fmt" "github.com/fox-one/mixin-cli/cmdutil" "github.com/fox-one/mixin-cli/session" "github.com/fox-one/mixin-sdk-go" "github.com/spf13/cobra" ) func NewCmdCreate() *cobra.Command { var opt struct { pin string } cmd := &cobra.Command{ Use: "create <fullname>", Short: "create new user", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() s := session.From(ctx) client, err := s.GetClient() if err != nil { return err } _, store, err := client.CreateUser(ctx, mixin.GenerateEd25519Key(), args[0]) if err != nil { return err } newClient, err := mixin.NewFromKeystore(store) if err != nil { return err } pin := opt.pin if pin == "" { pin = mixin.RandomPin() } if err := newClient.ModifyPin(ctx, "", pin); err != nil { return err } storeWithPin := cmdutil.Keystore{ Keystore: store, Pin: pin, } fmt.Fprintln(cmd.OutOrStdout(), storeWithPin.String()) return nil }, } cmd.Flags().StringVar(&opt.pin, "pin", "", "mixin wallet pin") return cmd } <file_sep>package http import ( "encoding/json" "fmt" "net/http" "net/http/httputil" "net/url" "time" "github.com/fox-one/mixin-cli/session" "github.com/fox-one/mixin-sdk-go" "github.com/nojima/httpie-go/exchange" "github.com/nojima/httpie-go/input" "github.com/spf13/cobra" ) func NewCmdHttp() *cobra.Command { var opt struct { raw string dumpRequest bool } cmd := &cobra.Command{ Use: "http", Args: cobra.MinimumNArgs(1), Short: "mixin api http client", RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() s := session.From(ctx) client, err := s.GetClient() if err != nil { return err } in, err := input.ParseArgs(args, cmd.InOrStdin(), &input.Options{JSON: true}) if err != nil { return err } host, _ := url.Parse(mixin.GetRestyClient().HostURL) in.URL.Host = host.Host in.URL.Scheme = host.Scheme in.Header.Fields = append(in.Header.Fields, input.Field{ Name: "User-Agent", Value: "mixin-cli/" + s.Version, }) if opt.raw != "" { var raw json.RawMessage if err := json.Unmarshal([]byte(opt.raw), &raw); err != nil { return fmt.Errorf("json decode raw body failed: %w", err) } in.Method = http.MethodPost in.Body = input.Body{ BodyType: input.RawBody, Raw: raw, } } req, err := exchange.BuildHTTPRequest(in, &exchange.Options{}) if err != nil { return err } sig := mixin.SignRequest(req) if token := client.Signer.SignToken(sig, mixin.RandomTraceID(), time.Minute); token != "" { req.Header.Set("Authorization", "Bearer "+token) } req.Header.Set("Content-Type", "application/json") if opt.dumpRequest { b, err := httputil.DumpRequest(req, true) if err != nil { return err } cmd.Println(string(b), "\n") } resp, err := mixin.GetClient().Do(req) if err != nil { return err } defer resp.Body.Close() var body struct { Error *mixin.Error Data json.RawMessage `json:"data"` } if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { return fmt.Errorf("decode json body failed: %w", err) } if body.Error != nil && body.Error.Code > 0 { return body.Error } data, _ := json.MarshalIndent(body.Data, "", " ") fmt.Fprintln(cmd.OutOrStdout(), string(data)) return nil }, } cmd.Flags().StringVar(&opt.raw, "raw", "", "raw json body") cmd.Flags().BoolVarP(&opt.dumpRequest, "dump", "v", false, "dump request information") return cmd }
3fcbaf0a585428fb0500b8bdd0e45fc5cb11b63c
[ "Markdown", "Go Module", "Go" ]
29
Go
fox-one/mixin-cli
280e75c6db099dcca491021da139ae92c4848fce
2179e8caf6354d868fed9746de070c75a979a6de
refs/heads/master
<file_sep>using System; namespace Ejercicio3._0 { public class Program { static void Main(string[] args) { bool aux = true; char OP; char R; Cuenta cuenta = new Cuenta(); Console.Write("Digite su nombre: "); cuenta.nombre = Console.ReadLine(); Console.Write("Digite su número de cuenta: "); cuenta.nCuenta = Console.ReadLine(); Console.Write("Digite su saldo de apertura: "); cuenta.saldo = decimal.Parse(Console.ReadLine()); do { Console.Write("¿Desea consignar o retirar? (C/R): "); OP = char.Parse(Console.ReadLine().ToUpper()); switch (OP) { case 'C': Console.Write("Digite el valor a consignar: "); cuenta.Consignar(decimal.Parse(Console.ReadLine())); break; case 'R': Console.Write("Digite el valor a retirar: "); cuenta.Retirar(decimal.Parse(Console.ReadLine())); break; } Console.WriteLine("Su saldo es: " + cuenta.saldo); Console.Write("¿Va a realizar otra transacción? (S/N): "); R = char.Parse(Console.ReadLine().ToUpper()); if (R == 'S') { aux = true; } else { aux = false; } } while (aux == true); } } }
61b138168e89716831a834d21aa840a641a6ee84
[ "C#" ]
1
C#
RubenDarioAriza/Ejercicio3
79f2972dc3d0cc0cd23b151ef1c1fd3a588b6fa8
ee974a68f6bc137565a0329f1b1f3da0c9b3df2a
refs/heads/master
<repo_name>pvickers/SpotiFire<file_sep>/SpotiFire.LibSpotify/Utils.h // Utils.h #pragma once #include "Stdafx.h" template<typename T> __forceinline bool ArrayEquals(array<T> ^left, array<T> ^right, System::Collections::Generic::EqualityComparer<T> ^comparer) { if(Object::ReferenceEquals(left, right)) return true; if (Object::ReferenceEquals(left, nullptr) || Object::ReferenceEquals(right, nullptr)) return false; if(left->Length != right->Length) return false; for(int i = 0; i < left->Length; i++) { if(!comparer->Equals(left[0], right[0])) return false; } return true; } template<class T, class U> __forceinline bool isinst(U u) { return dynamic_cast<T>(u) != nullptr; }<file_sep>/SpotiFire.LibSpotify/PortraitId.h // PortraitId.h #pragma once #include "Stdafx.h" using namespace System; using namespace System::Collections::Generic; namespace SpotiFire { public value class PortraitId sealed : IEquatable<PortraitId> { private: initonly array<byte> ^_data; String^ _asString; internal: PortraitId(const byte *data) { _data = gcnew array<Byte>(20); for(int i = 0; i < 20; i++) { _data[i] = data[i]; } _asString = HEX(data,20); } const std::vector<byte> data() { std::vector<byte> ret(20); for(int i = 0; i < 20; i++) { ret[i] = _data[i]; } return ret; } static __forceinline String^ HEX(const byte *bytes, int count) { if(bytes==NULL) return String::Empty; char result[41]; result[40] = '\0'; char *current = result; for(int i = 0; i < count; i++) { sprintf(current, "%02X", bytes[i]); current += 2; } return UTF8(result); } public: virtual String ^ToString() override { return _asString; } ///------------------------------------------------------------------------------------------------- /// <summary> Gets the hash code for this artistbrowse object. </summary> /// /// <returns> The hash code. </returns> ///------------------------------------------------------------------------------------------------- virtual int GetHashCode() override { int hashCode = 0; for(int i = 0; i < 20; i++) { hashCode += _data[i]; } return hashCode; } ///------------------------------------------------------------------------------------------------- /// <summary> Checks if this artistbrowse object is considered to be the same as the given /// object. </summary> /// /// <param name="other"> The object to compare. </param> /// /// <returns> true if the given object is equal to the artistbrowse object, otherwise /// false. </returns> ///------------------------------------------------------------------------------------------------- virtual bool Equals(Object^ other) override { if(Object::ReferenceEquals(other, nullptr)) return false; if(other->GetType() == PortraitId::typeid) return Equals((PortraitId)other); return false; } ///------------------------------------------------------------------------------------------------- /// <summary> Checks if this artistbrowse object is considered to be the same as the given /// object. </summary> /// /// <param name="other"> The object to compare. </param> /// /// <returns> true if the given object is equal to the artistbrowse object, otherwise /// false. </returns> ///------------------------------------------------------------------------------------------------- virtual bool Equals(PortraitId other) sealed { return ArrayEquals<Byte>(other._data, _data, EqualityComparer<Byte>::Default); } ///------------------------------------------------------------------------------------------------- /// <summary> Checks if the given artistbrowse objects should be considered equal. </summary> /// /// <param name="left"> The artistbrowse object on the left-hand side of the operator. </param> /// <param name="right"> The artistbrowse object on the right-hand side of the operator. </param> /// /// <returns> true if the given artistbrowse objects are equal, otherwise false. </returns> ///------------------------------------------------------------------------------------------------- static bool operator== (PortraitId left, PortraitId right) { return left.Equals(right); } ///----------------------------------------------------------------------------------------------- /// <summary> Checks if the given artistbrowse objects should not be considered equal. </summary> /// /// <param name="left"> The artistbrowse object on the left-hand side of the operator. </param> /// <param name="right"> The artistbrowse object on the right-hand side of the operator. </param> /// /// <returns> true if the given artistbrowse objects are not equal, otherwise false. </returns> ///------------------------------------------------------------------------------------------------- static bool operator!= (PortraitId left, PortraitId right) { return !(left == right); } }; }
fba3483c6a51b207c215ff98ba459a57ee95fa7a
[ "C++" ]
2
C++
pvickers/SpotiFire
794642710651e44df023943060eacc1547869ec2
58dd670ed230f6ef226224e0a4a04136d2fc398e
refs/heads/master
<repo_name>junchil/leetcode<file_sep>/leetcodeCpp/Climbing_Stairs/Climbing_Stairs/Climbing_Stairs.cpp /* You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Example 1: Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step */ #include<iostream> using namespace std; class Solution { public: int climbStairs(int n) { int S; if (n == 0) { S=0; } if (n == 1) { S=1; } if (n == 2) { S = 2; } int S1 = 2, S2 = 1; for (int i = 3; i <= n; i++) { S = S1 + S2; S2 = S1; S1 = S; } return S; } }; int main() { Solution solobject; cout << solobject.climbStairs(20) << endl; system("pause"); return 0; }<file_sep>/leetcodePython/Reverse_Integer.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Mar 7 12:05:34 2018 @author: junchiliu Given a 32-bit signed integer, reverse digits of an integer. Note: Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """ def reverse(x): if x>=0: a = int(str(x)[::-1]) if a >=2**31: return 0 else: return a else: x=abs(x) a = int(str(x)[::-1]) if a >2**31: return 0 else: return a*(-1) <file_sep>/leetcodePython/1051.py class Solution: def heightChecker(self, heights) -> int: sorthei = sorted(heights) res = 0 for i in range(len(heights)): if heights[i] != sorthei[i]: res = res + 1 return res<file_sep>/leetcodePython/1859.py class Solution: def sortSentence(self, s: str) -> str: sarray = s.split() slist=sorted(sarray, key = lambda x:x[-1]) r = [] for i in slist: r.append(i[:-1]) return ' '.join(r)<file_sep>/leetcodePython/1694.py class Solution: def reformatNumber(self, number: str) -> str: newnumber = number.replace(" ", "").replace("-", "") ans = "" while len(newnumber) > 4: ans += newnumber[:3] + '-' newnumber = newnumber[3:] if len(newnumber) == 4: ans += newnumber[:2] + '-' + newnumber[2:] else: ans += newnumber return ans<file_sep>/leetcodePython/1002.py class Solution: def commonChars(self, words: List[str]) -> List[str]: intersect = set(words[0]) for word in words[1:]: intersect = intersect.intersection(set(word)) counter = {} for key in intersect: counter[key] = sys.maxsize for key in intersect: for word in words: counter[key] = min(counter[key], word.count(key)) results = [] for key, value in counter.items(): for i in range(value): results.append(key) return results<file_sep>/leetcodePython/0876.py class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: node_num = 0 res = head while head: head = head.next node_num = node_num + 1 mid = node_num // 2 + 1 while mid > 1: res = res.next mid = mid - 1 return res<file_sep>/leetcodeCpp/Symmetric_Tree/Symmetric_Tree/Symmetric_Tree.cpp /* Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3 */ struct TreeNode { int val; TreeNode *left; TreeNode *right; }; class Solution { public: bool isSymmetric(TreeNode *root) { if (!root) { return true; } return check_Symmetric(root->left, root->right); } bool check_Symmetric(TreeNode *left, TreeNode *right) { if (!left && !right) { return true; } if ((!left && right) || (left && !right) || (left->val != right->val)) { return false; } return check_Symmetric(left->left, right->right) && check_Symmetric(left->right, right->left); } }; <file_sep>/leetcodeGolang/026/main.go package main import "fmt" func contains(s []int, e int) bool { for _, a := range s { if a == e { return true } } return false } func removeDuplicates(nums []int) int { var res []int for i := 0; i <= len(nums)-1; i++ { if contains(res, nums[i]) { continue } else { res = append(res, nums[i]) } } return len(res) } func main() { nums := []int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4} num := removeDuplicates(nums) fmt.Println(num) } <file_sep>/leetcodePython/0058.py class Solution: def lengthOfLastWord(self, s: str) -> int: if len(s) == 0: return 0 x = s.split() if len(x) == 0: return 0 x= [y for y in x if len(y) > 0] if len(x) == 0: return 0 else: return len(x[-1]) str = "Hello World" len = Solution().lengthOfLastWord(s=str) print(len)<file_sep>/leetcodePython/0088.py class Solution: def merge(self, nums1, m, nums2, n) -> None: """ Do not return anything, modify nums1 in-place instead. """ mtemp = m - 1 ntemp = n -1 p = m + n - 1 while mtemp >= 0 and ntemp >= 0: if nums1[mtemp] >= nums2[ntemp]: nums1[p] = nums1[mtemp] mtemp = mtemp - 1 p = p - 1 else: nums1[p] = nums2[ntemp] ntemp = ntemp - 1 p = p - 1 while ntemp >= 0: nums1[p] = nums2[ntemp] ntemp = ntemp - 1 p = p - 1 nums1 = [1,2,3,0,0,0] m = 3 nums2 = [2,5,6] n = 3 Solution().merge(nums1=nums1, m=m, nums2=nums2, n=n) print(nums1) <file_sep>/leetcodeCpp/Remove Duplicates from Sorted Array/Remove Duplicates from Sorted Array/Remove_Duplicates_from_Sorted_Array.cpp /* Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. */ #include <iostream> #include <vector> using namespace std; class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.empty()) { return 0; } int size = 0; for (int i = 1; i < nums.size(); i++) { if (nums[size] != nums[i]) { nums[++size]=nums[i]; } } return size + 1; } }; int main() { Solution solObject; vector<int> A{ 1,1,1,2,3 }; int size; size= solObject.removeDuplicates(A); cout << size << endl; system("pause"); return 0; } <file_sep>/leetcodePython/1816.py class Solution: def truncateSentence(self, s: str, k: int) -> str: sarr = s.split() return " ".join(sarr[:k])<file_sep>/leetcodePython/1455.py class Solution: def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: sentencearr = sentence.split() for i in range(1, len(sentencearr) + 1): if sentencearr[i-1][:len(searchWord)] == searchWord: return i return -1<file_sep>/leetcodePython/1763.py class Solution: def longestNiceSubstring(self, s: str) -> str: maxstr = "" for i in range(len(s)): for j in range(len(s), i, -1): sub = s[i:j] lower_set = set(sub.lower()) upper_small_set = set(sub) if len(upper_small_set) == 2 * len(lower_set): if len(maxstr) < len(sub): maxstr = sub return maxstr<file_sep>/leetcodePython/1290.py # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def getDecimalValue(self, head: ListNode) -> int: t, node_num = head, 0 while(t): t = t.next node_num = node_num + 1 sum_n = 0 for i in range(node_num): x = head.val sum_n = sum_n + x*2**(node_num-1-i) head = head.next return sum_n <file_sep>/leetcodeCpp/Pascal's Triangle/Pascal's Triangle/Pascal's_Triangle.cpp /* Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] */ #include<iostream> #include<vector> using namespace std; class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> result; if (numRows == 0) { return {}; } if (numRows == 1) { return result = { {1} }; } if (numRows == 2) { return result = { {1},{1,1} }; } result = { { 1 },{ 1,1 } }; vector<int> res = { 1,1 }; for (int i = 3; i <= numRows; ++i) { int prev = 1; for (int j = 1; j < i-1; ++j) { int tem = res[j]; res[j] += prev; prev = tem; } res.push_back(1); result.push_back(res); } return result; } }; <file_sep>/leetcodePython/1624.py class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: longest = -1 visited = {} for i, c in enumerate(s): if c in visited: longest = max(longest, i - visited[c] - 1) else: visited[c] = i return longest<file_sep>/leetcodeGolang/README.md # Learning Note Leetcode 1. Index [1. 0001 Two Sum](https://github.com/junchil/leetcode/blob/master/leetcodeGolang/twoSum.go) [2. 0002 Add Two Numbers](https://github.com/junchil/leetcode/blob/master/leetcodeGolang/addTwoNumbers.go) [3. 0003 Longest Substring Without Repeating Characters](https://github.com/junchil/leetcode/blob/master/leetcodeGolang/longestSubstringWithoutRepeatingCharacters.go) <file_sep>/leetcodeCpp/Maximum Subarray/Maximum Subarray/Maximum_Subarray.cpp /* Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6. */ #include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: int maxSubArray(vector<int>& nums) { if (nums.empty()) { return 0; } int current = nums[0]; int max = nums[0]; int n = nums.size(); for (int i = 1; i < n; i++) { current = std::max(current + nums[i], nums[i]); max = std::max(current, max); } return max; } }; <file_sep>/leetcodePython/1507.py class Solution: def reformatDate(self, date: str) -> str: mapping = {"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"} year = date.split()[2] month = date.split()[1] day = date.split()[0] formatted_day = "" for c in day: if not c.isdigit(): break else: formatted_day += c if len(formatted_day) == 1: formatted_day = "0" + formatted_day reformatted_date = year + "-" + mapping[month] + "-" + formatted_day return reformatted_date<file_sep>/leetcodePython/1408.py class Solution: def stringMatching(self, words: List[str]) -> List[str]: res = [] for i in range(len(words)): for j in range(len(words)): if j == i: continue else: if words[i] in words[j]: res.append(words[i]) break return res<file_sep>/leetcodePython/1897.py class Solution: def makeEqual(self, words: List[str]) -> bool: if len(words) == 1: return True d = {} N = len(words) for word in words: for c in word: if c in d: d[c] += 1 else: d[c] = 1 for k, v in d.items(): if v % N != 0: return False return True<file_sep>/leetcodePython/2000.py class Solution: def reversePrefix(self, word: str, ch: str) -> str: ch_index = word.find(ch) return word[:ch_index+1][::-1] + word[ch_index+1:]<file_sep>/leetcodeCpp/Length_of_Last_Word/Length_of_Last_Word/Length_of_Last_Word.cpp /* Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. */ #include<iostream> #include<string> using namespace std; class Solution { public: int lengthOfLastWord(string s) { int i = s.length() - 1; //Shift i to the last word while (i >= 0 && s[i] == ' ') { --i; } //last word length int length = 0; while (i >= 0 && s[i] != ' ') { ++length; --i; } return length; } }; int main() { Solution solobject; string s = " He llo World "; int length; length = solobject.lengthOfLastWord(s); //cout << length << endl; system("pause"); return 0; } <file_sep>/leetcodePython/1758.py class Solution: def minOperations(self, s: str) -> int: s_arr = list(s) zero_start_arr = ['0' if i % 2 else '1' for i in range(len(s))] one_start_arr = ['1' if i % 2 else '0' for i in range(len(s))] zero_start_count = 0 for c, z_c in zip(s_arr, zero_start_arr): if c != z_c: zero_start_count += 1 one_start_count = 0 for c, o_c in zip(s_arr, one_start_arr): if c != o_c: one_start_count += 1 return min(one_start_count, zero_start_count)<file_sep>/leetcodeCpp/Merge Two Sorted Lists/Merge Two Sorted Lists/Merge_Two_Sorted_Lists.cpp /*Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ #include <iostream> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x):val(x),next(NULL){} }; class Solution { public: ListNode * mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode Newlist(0); ListNode* l3 = &Newlist; while (l1&&l2) { if (l1->val <= l2->val) { l3->next = l1; l1 = l1->next; } else{ l3->next = l2; l2 = l2->next; } l3 = l3->next; } if (l1) { l3->next = l1; } if (l2) { l3->next = l2; } return Newlist.next; } }; <file_sep>/leetcodePython/1812.py class Solution: def squareIsWhite(self, coordinates: str) -> bool: checkstr = "bdfh" if coordinates[0] in checkstr: if int(coordinates[1]) % 2 == 0: return False else: return True else: if int(coordinates[1]) % 2 == 0: return True else: return False<file_sep>/leetcodePython/0771.py class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: jew_type = set(jewels) count = 0 for stone in stones: if stone in jew_type: count = count + 1 return count print(Solution().numJewelsInStones("aA", "aAAbbbb"))<file_sep>/leetcodePython/2062.py class Solution: def countVowelSubstrings(self, word: str) -> int: vowels = ["a", "e", "i", "o", "u"] res = 0 if len(word) < 5: return 0 for i in range(5, len(word) + 1): for j in range(len(word) + 1 - i): if set(vowels) == set(word[j:j+i]): res += 1 return res<file_sep>/leetcodePython/Palindrome_Number.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Mar 7 12:58:00 2018 @author: junchiliu Determine whether an integer is a palindrome. Do this without extra space. """ class Solution: def isPalindrome(self, x): self.x = x if self.x >= 0: if self.x >= 2**31: return False else: if self.x == int(str(self.x)[::-1]): return True else: return False else: return False <file_sep>/leetcodePython/1979.py class Solution: def findGCD(self, nums: List[int]) -> int: l = sorted(nums) s = l[0] l1 = l[-1] mxd = 1 for i in range(1, s + 1): if s % i == 0 and l1 % i == 0: mxd = max(i, mxd) return mxd<file_sep>/leetcodePython/0242.py class Solution: def isAnagram(self, s: str, t: str) -> bool: if not set(s) == set(t): return False for c in set(s): if s.count(c) != t.count(c): return False return True<file_sep>/hackerrankPython/beautifulPairs.py # https://www.hackerrank.com/challenges/beautiful-pairs/problem #!/bin/python3 import math import os import random import re import sys # Complete the beautifulPairs function below. def beautifulPairs(A, B): arrA=[] arrB=[] result = 0 for indexI in range (len(A)): for indexJ in range(len(B)): if A[indexI] == B[indexJ]: arrA.append(indexI) arrB.append(indexJ) print(arrA) print(arrB) arrA = list(set(arrA)) arrB = list(set(arrB)) result= min(len(arrA)+1, len(A)) return result if __name__ == '__main__': A = [10, 11, 12, 5, 14] B = [8, 9, 11, 11, 5] result = beautifulPairs(A, B) print(result)<file_sep>/leetcodeCpp/Remove_Element/Remove_Element/Remove_Element.cpp /* Given an array and a value, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. */ #include <iostream> #include <vector> using namespace std; class Solution { public: int removeElement(vector<int>& nums, int val) { if (nums.empty()) { return 0; } int index = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] != val) { nums[index] = nums[i]; ++index; } } return index; } }; int main() { vector<int> A{ 1,1,2,3 }; int val = 3; Solution solobject; int index = solobject.removeElement(A, val); cout << index << endl; system("pause"); return 0; } <file_sep>/leetcodePython/1913.py class Solution: def maxProductDifference(self, nums) -> int: nums.sort() res = 0 return nums[-1]*nums[-2] - nums[0]*nums[1]<file_sep>/leetcodePython/1867.py class Solution: def countGoodSubstrings(self, s: str) -> int: sub_count = len(s) - 2 res = 0 for i in range(sub_count): if len(set(s[i:i+3])) == 3: res = res + 1 return res<file_sep>/leetcodeGolang/0387/main.go func firstUniqChar(s string) int { m := make(map[string]int) for _, c := range s { if _, ok := m[string(c)]; ok { m[string(c)] = m[string(c)] + 1 } else { m[string(c)] = 1 } } var res int res = len(s) + 1 for key, value := range m { if value == 1 { temp := strings.Index(s, key) if temp < res { res = temp } } } if res == len(s)+1 { return -1 } return res }<file_sep>/leetcodePython/1935.py class Solution: def canBeTypedWords(self, text: str, brokenLetters: str) -> int: res = 0 for word in text.split(): if (set(list(word)) & set(list(brokenLetters))): res = res else: res = res + 1 return res<file_sep>/leetcodeCpp/Pascal's Triangle II/Pascal's Triangle II/Pascal's_Triangle_II.cpp /* Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. */ #include<iostream> #include<vector> using namespace std; class Solution { public: vector<int> getRow(int rowIndex) { if (rowIndex == 0) { return {1}; } if (rowIndex == 1) { return { 1, 1 }; } vector<int> res = { 1,1 }; for (int i = 2; i <= rowIndex; ++i) { int prev = 1; for (int j = 1; j < i; ++j) { int temp = res[j]; res[j] += prev; prev = temp; } res.push_back(1); } return res; } };<file_sep>/leetcodePython/1351.py class Solution: def countNegatives(self, grid: List[List[int]]) -> int: i = [item for row in grid for item in row] return len([j for j in i if j<0])<file_sep>/leetcodePython/1732.py class Solution: def largestAltitude(self, gain: List[int]) -> int: maxres = 0 temp = 0 for i in range(len(gain)): temp += gain[i] if temp > maxres: maxres = temp return maxres<file_sep>/leetcodeGolang/349/main.go package main import "fmt" func contains(s []int, e int) bool { for _, a := range s { if a == e { return true } } return false } func intersection(nums1 []int, nums2 []int) []int { var res []int for _, num := range nums1 { if contains(nums2, num) && !contains(res, num) { res = append(res, num) } } return res } func main() { nums1 := []int{4, 9, 2, 2, 1} nums2 := []int{2, 2, 4, 9} res := intersection(nums1, nums2) fmt.Println(res) } <file_sep>/leetcodePython/Longest_Substring_Without_Repeating_Characters.py # https://leetcode.com/problems/longest-substring-without-repeating-characters/ class Solution: def lengthOfLongestSubstring(self, s: str) -> int: for maxlen in range(len(s)+1): for i in range(len(s)):<file_sep>/leetcodePython/1869.py class Solution: def checkZeroOnes(self, s: str) -> bool: maxa = 1 maxb = 1 tempa = 1 tempb = 1 slist = list(s) prev = "" if len(slist) == 1: if s == "1": return True else: return False for i in range(len(slist) - 1): if slist[i] == slist[i+1] and slist[i] == "1": tempa += 1 if tempa > maxa: maxa = tempa elif slist[i] == slist[i+1] and slist[i] == "0": tempb += 1 if tempb > maxb: maxb = tempb else: tempa = 1 tempb = 1 if maxa > maxb: return True else: return False<file_sep>/leetcodePython/1945.py class Solution: def getLucky(self, s: str, k: int) -> int: temps = "" for i in s: temps += str(ord(i) - 96) for j in range(k): temps = str(sum([int(j) for j in temps])) return int(temps)<file_sep>/leetcodePython/1436.py class Solution: def destCity(self, paths: List[List[str]]) -> str: start = [] end = [] for path in paths: start.append(path[0]) end.append(path[1]) return "".join(list(set(end) - set(start)))<file_sep>/leetcodePython/Valid_Palindrome.py """ Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false """ class Solution(object): def isPalindrome(self, s): if s == '': return True else: sTemp = '' for i in range(0, len(s)): if s[i] >= 'a' and s[i] <= 'z' or s[i] >= '0' and s[i] <= '9' or s[i] >= 'A' and s[i] <= 'Z': sTemp += s[i] sTemp = sTemp.lower() for i in range(0, len(sTemp)/2): if sTemp[i] != sTemp[len(sTemp) - i - 1]: return False return True if __name__ == "__main__": s = "A man, a plan, a canal: Panama" print Solution().isPalindrome(s) <file_sep>/leetcodeCpp/Convert_Sorted_Array_to_Binary_Search_Tree/Convert_Sorted_Array_to_Binary_Search_Tree/Convert_Sorted_Array_to_Binary_Search_Tree.cpp /* Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example: Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5 */ #include<iostream> #include<vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; }; class Solution { public: TreeNode * sortedArrayToBST(vector<int>& nums) { return ArrayToBST(nums, 0, nums.size() - 1); } TreeNode * ArrayToBST(vector<int>& nums, int start, int end) { if (start > end) { return NULL; } int mid = start + (end - start) / 2; TreeNode *root = new TreeNode; root->val = nums[mid]; root->left = ArrayToBST(nums,start,mid-1); root->right = ArrayToBST(nums, mid + 1, end); return root; } };<file_sep>/leetcodePython/0821.py class Solution: def shortestToChar(self, s: str, c: str) -> List[int]: res = [0] * len(s) indexarr= [i for i, x in enumerate(s) if x == c] for i in range(len(s)): minstep = len(s) for j in indexarr: if abs(j - i) < minstep: minstep = abs(j - i) res[i] = minstep return res<file_sep>/leetcodePython/0938.py class Solution: def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int: self.sumBST = 0 self.scanBST(root, low, high) return self.sumBST def scanBST(self, root, low, high): if root: if root.val >= low and root.val <= high: self.sumBST += root.val self.scanBST(root.left, low, high) self.scanBST(root.right, low, high)<file_sep>/leetcodePython/1189.py class Solution: def maxNumberOfBalloons(self, text: str) -> int: res = 0 keyc = {"b", "a", "l", "o", "n"} text_dict = dict.fromkeys(keyc, 0) for k in text_dict: if k in text: text_dict[k] = text.count(k) return min(text_dict["b"], text_dict["a"], text_dict["l"]//2, text_dict["o"]//2, text_dict["n"])<file_sep>/leetcodePython/1704.py class Solution: def halvesAreAlike(self, s: str) -> bool: first = s[:len(s)//2] last = s[len(s)//2:] vowels="aeiouAEIOU" countf = 0 countl = 0 for ch in first: if ch in vowels: countf = countf + 1 for ch in last: if ch in vowels: countl = countl + 1 if countf == countl: return True else: return False<file_sep>/hackerrankPython/minimumAbsoluteDifferenceInAnArray.py #https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem #!/bin/python3 import math import os import random import re import sys # Complete the minimumAbsoluteDifference function below. def minimumAbsoluteDifference(arr): arr.sort() min = arr[1] - arr[0] for i in range(len(arr)-1): if arr[i+1] - arr[i] < min: min = arr[i+1] - arr[i] else: min = min return min if __name__ == '__main__': arr=[-59, -36, -13, 1, -53, -92, -2, -96, -54, 75] result = minimumAbsoluteDifference(arr) print(result) <file_sep>/leetcodePython/0696.py class Solution: def countBinarySubstrings(self, s: str) -> int: res = 0 grouparr = [] count = 1 for i in range(0, len(s) - 1): if s[i] == s[i+1]: count += 1 else: grouparr.append(count) count = 1 grouparr.append(count) for i in range(len(grouparr) - 1): res += min(grouparr[i], grouparr[i+1]) return res<file_sep>/leetcodePython/2085.py class Solution: def countWords(self, words1: List[str], words2: List[str]) -> int: res = 0 newarr = list(set(words1 + words2)) for word in newarr: if words1.count(word) == 1 and words2.count(word) == 1: res = res + 1 return res<file_sep>/leetcodePython/1672.py class Solution: def maximumWealth(self, accounts: List[List[int]]) -> int: res = 0 for account in accounts: if sum(account) > res: res = sum(account) return res<file_sep>/leetcodePython/1941.py class Solution: def areOccurrencesEqual(self, s: str) -> bool: count = {} for c in s: if c in count: count[c] = count[c] + 1 else: count[c] = 1 return len(set(count.values())) == 1<file_sep>/leetcodePython/1929.py class Solution: def getConcatenation(self, nums: List[int]) -> List[int]: res = [] numscp = nums nums.extend(numscp) return nums<file_sep>/leetcodeCpp/Binary Tree Level Order Traversal II/Binary Tree Level Order Traversal II/Binary_Tree_Level_Order_Traversal_II.cpp /* Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its bottom-up level order traversal as: [ [15,7], [9,20], [3] ] */ #include<iostream> #include<vector> #include<queue> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; }; class Solution { public: vector<vector<int>> levelOrderBottom(TreeNode *root) { vector<vector<int>> res; if (!root) { return res; } queue<TreeNode *> q; q.push(root); while (!q.empty()) { vector<int> levelvalue; int size = q.size(); for (int i = 0; i < size; ++i) { TreeNode *levelroot = q.front(); q.pop(); levelvalue.push_back(levelroot->val); if (levelroot->left) { q.push(levelroot->left); } if (levelroot->right) { q.push(levelroot->right); } } res.insert(res.begin(), levelvalue); } return res; } };<file_sep>/leetcodeCpp/Merge_Sorted_Array/Merge_Sorted_Array/Merge_Sorted_Array.cpp /* Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. */ #include<iostream> #include<vector> using namespace std; class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int i = m-1; int j = n-1; int h = m + n - 1; while (i >= 0 && j >= 0) { if (nums2[j] >= nums1[i]) { nums1[h] = nums2[j]; --j; } else { nums1[h] = nums1[i]; --i; } --h; } while (i >= 0) { nums1[h] = nums1[i]; --i; --h; } while (j >= 0) { nums1[h] = nums2[j]; --j; --h; } } }; int main() { vector<int> nums1(15); nums1[0] = 1; nums1[1] = 4; nums1[2] = 4; nums1[3] = 8; nums1[4] = 12; nums1[5] = 13; vector<int> nums2 = { 4,6,7,9,10,12,15,16,20 }; Solution solobject; solobject.merge(nums1, 6, nums2, 9); for (int i = 0; i < nums1.size(); ++i) { cout << nums1[i] << endl; } system("pause"); return 0; }<file_sep>/README.md # Leetcode for fun<file_sep>/leetcodePython/Two_Sum.py ''' Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. ''' def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ length = len(nums) for i in range(length-1): for j in range(i+1, length): if nums[i] + nums[j] == target: print(nums[i] + nums[j]) return i, j break else: continue def twoSumNew(nums, target): d = {} index = 0 while index < len(nums): if target - nums[index] in d: #if d[target - nums[index]] < index: return [d[target-nums[index]], index] else: #print(d) d[nums[index]] = index index = index + 1 nums = [2, 7, 11, 6, 9, 4] target = 12 #print(twoSum(nums = nums,target = target)) print(twoSumNew(nums = nums, target = target)) <file_sep>/leetcodeCpp/Sqrt(x)/Sqrt(x)/Sqrt(x).cpp /* Implement int sqrt(int x). Compute and return the square root of x. x is guaranteed to be a non-negative integer. */ #include<iostream> using namespace std; class Solution { public: int mySqrt(int x) { if (x <= 1) { return x; } int start = 0, end =x; while (start <= end) { int mid = start + (end - start) / 2; if (x / mid == mid) { return mid; } else if (x / mid > mid) { start = mid+1; } else { end = mid-1; } } return end; } }; int main() { Solution solobject; cout << solobject.mySqrt(8) << endl; system("pause"); return 0; } <file_sep>/leetcodeCpp/Valid Parentheses/Valid Parentheses/Valid_Parentheses.cpp /* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. */ #include <iostream> #include <string> #include <vector> using namespace std; class Solution { public: bool isValid(string s) { vector<char> stk; if (s.empty()) return false; stk.push_back(s[0]); for (int i = 1; i < s.size(); i++) { if (s[i] == '(' || s[i] == '{' || s[i] =='[') { stk.push_back(s[i]); continue; } char current = stk.back(); if (s[i] == ')' && current != '(') return false; if (s[i] == '}' && current != '{') return false; if (s[i] == ']' && current != '[') return false; stk.pop_back(); } if (stk.size() != 0) return false; return true; } }; int main() { string A; A = { "()[]{}" }; Solution solutionobject; cout << solutionobject.isValid(A) << endl; system("pause"); return 0; }<file_sep>/leetcodePython/1446.py class Solution: def maxPower(self, s: str) -> int: longest = 1 count = 1 pre = None for i in range(len(s)): if s[i] == pre: count += 1 else: longest = max(longest, count) count = 1 pre = s[i] longest = max(longest, count) return longest<file_sep>/leetcodePython/0897.py class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def increasingBST(self, root: TreeNode) -> TreeNode: preorder = [] def pre_order(root): if not root: return pre_order(root.left) preorder.append(root.val) pre_order(root.right) pre_order(root) res = TreeNode(0) for i, val in enumerate(preorder): temp = TreeNode(val) temp.left = None temp.right = None if i == 0: res.right = temp cur = temp else: cur.right = temp cur = temp return res.right<file_sep>/leetcodePython/1971.py class Solution: def validPath(self, n: int, edges: List[List[int]], start: int, end: int) -> bool: if start == end: return True graph = [[] for _ in range(n)] for u, v in edges: graph[u].append(v) graph[v].append(u) visited = [False for _ in range(n)] stack = [start] while stack: ele = stack.pop(0) visited[ele] = True if end in graph[ele]: return True for ver in graph[ele]: if not visited[ver]: stack.append(ver) return False<file_sep>/leetcodeCpp/Maximum_Depth_of_Binary_Tree/Maximum_Depth_of_Binary_Tree/Maximum_Depth_of_Binary_Tree.cpp /* Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its depth = 3. */ #include<iostream> #include<algorithm> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; }; class Solution { public: int maxDepth(TreeNode *root) { if (!root) { return 0; } int leftmax = maxDepth(root->left); int rightmax = maxDepth(root->right); return max(leftmax, rightmax) + 1; } };<file_sep>/leetcodePython/0557.py class Solution: def reverseWords(self, s: str) -> str: c_arr = s.split() c_arr_re = [] for c in c_arr: c_arr_re.append(c[::-1]) return " ".join(c_arr_re)<file_sep>/leetcodePython/1313.py class Solution: def decompressRLElist(self, nums: List[int]) -> List[int]: res = [] for i in range(len(nums) // 2): res.extend(nums[2*i]*[nums[2*i+1]]) return res<file_sep>/leetcodeCpp/Balanced_Binary_Tree/Balanced_Binary_Tree/Balanced_Binary_Tree.cpp /* Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example 1: Given the following tree [3,9,20,null,null,15,7]: 3 / \ 9 20 / \ 15 7 Return true. Example 2: Given the following tree [1,2,2,3,3,null,null,4,4]: 1 / \ 2 2 / \ 3 3 / \ 4 4 Return false. */ #include<iostream> #include<algorithm> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; }; class Solution { public: bool isBalanced(TreeNode *root) { if (!root) { return true; } int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right); if (abs(leftDepth-rightDepth)>1) { return false; } return isBalanced(root->left) && (isBalanced(root->right)); } int maxDepth(TreeNode *node) { if (!node) { return 0; } int leftmax = maxDepth(node->left); int rightmax = maxDepth(node->right); return max(leftmax, rightmax) + 1; } };<file_sep>/leetcodeCpp/Add_Binary/Add_Binary/Add_Binary.cpp /* Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". */ #include<iostream> #include<string> using namespace std; class Solution { public: string addBinary(string a, string b) { string sum = "0"; int n1 = a.size(); int n2 = b.size(); int n; int flag = 0; if (n1 >= n2) { n = n1; flag = 1; } else { n = n2; } //add one more '0' a = string(n - n1 + 1, '0').append(a); b = string(n - n2 + 1, '0').append(b); sum = string(n, '0').append(sum); int current_index = 0; int last_index = 0; for (int i = n; i >= 1; --i) { if (last_index == 0) { if (a[i] == '1' && b[i] == '1') { sum[i] = '0'; current_index = 1; } else if (a[i] == '0' && b[i] == '1') { sum[i] = '1'; current_index = 0; } else if (a[i] == '1' && b[i] == '0') { sum[i] = '1'; current_index = 0; } else { sum[i] = '0'; current_index = 0; } } else { if (a[i] == '1' && b[i] == '1') { sum[i] = '1'; current_index = 1; } else if (a[i] == '0' && b[i] == '1') { sum[i] = '0'; current_index = 1; } else if (a[i] == '1' && b[i] == '0') { sum[i] = '0'; current_index = 1; } else{ sum[i] = '1'; current_index = 0; } } last_index = current_index; } if (current_index == 1) { sum[0] = '1'; } else { sum.erase(0,1); } cout << sum << endl; return sum; } }; int main() { string a = "100010"; string b = "10"; Solution solobject; solobject.addBinary(a,b); system("pause"); return 0; } <file_sep>/leetcodePython/Linked_List_Cycle.py """ Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? """ class Solution(object): def hasCycle(self, head): if head == None or head.next == None: return False fast = head slow = head while fast and fast.next: slow = slow.next fast = fast.next.next if fast == slow: return True else: continue return False <file_sep>/leetcodePython/1974.py class Solution: def minTimeToType(self, word: str) -> int: s=0 now='a' for i in range(len(word)): move=abs(ord(word[i])-ord(now)) if move > 13: move= 26 -move s+=(move+1) now=word[i] return s<file_sep>/leetcodePython/0338.py class Solution: def countBits(self, num: int) -> List[int]: res = [0] if num > 0: while len(res) < num + 1: res.extend([x+1 for x in res]) return res[:num+1]<file_sep>/leetcodePython/0929.py class Solution: def numUniqueEmails(self, emails: List[str]) -> int: ans = {''} for email in emails: acc, dom = email.split("@") acc = acc.split("+")[0].replace(".", "") ans.add(acc + "@" + dom) return len(ans)-1<file_sep>/leetcodePython/0884.py class Solution: def uncommonFromSentences(self, s1: str, s2: str) -> List[str]: s1arr = s1.split() s2arr = s2.split() res = [] words = set(s1arr + s2arr) for word in words: if word in s1arr and word not in s2arr: if s1arr.count(word) == 1: res.append(word) elif word in s2arr and word not in s1arr: if s2arr.count(word) == 1: res.append(word) else: continue return res<file_sep>/hackerrankPython/getStableMarketDate.py #!/bin/python3 import math import os import random import re import sys # # Complete the 'getStableMarketData' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts following parameters: # 1. INTEGER_ARRAY data # 2. INTEGER x # def getStableMarketData(data, x): # Write your code here v = [abs(data[i+1]-data[i]) for i in range(len(data)-1)] print(v) if x < min(v) or x > max(v): return [] a=0 index=0 position=0 for i in range(len(v)): if v[i] <= x: index=index+1 else: if index > a: a = index position = i index=0 print(position) print(a) return data[position-a:position+1] if __name__ == '__main__': data=[5, 1, 16, 16, 12, 5] x =25 result = getStableMarketData(data, x) print(result) <file_sep>/leetcodeCpp/Implement_strStr()/Implement_strStr()/Implement_strStr().cpp /* Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. */ #include <iostream> #include <string> using namespace std; class Solution { public: int strStr(string haystack, string needle) { if (haystack.empty()) { return -1; } if (needle.empty()) { return 0; } if (haystack.size() < needle.size()) { return-1; } for (int i = 0; i <= haystack.size()- needle.size(); ++i) { int j = 0; for (j = 0; j < needle.size(); ++j) { if (haystack[i + j] != needle[j]) { break; } } if (j == needle.size()) { return i; } } return -1; } }; int main() { string haystack = "hello"; string needle = "ll"; Solution solobject; int num; num = solobject.strStr(haystack, needle); cout << num << endl; system("pause"); return 0; } <file_sep>/leetcodePython/2037.py class Solution: def minMovesToSeat(self, seats, students) -> int: seats.sort() students.sort() res = 0 for i in range(len(seats)): res = res + abs(seats[i] - students[i]) return res<file_sep>/leetcodeGolang/028/main.go package main import ( "fmt" "strings" ) func strStr(haystack string, needle string) int { leng := len(needle) if needle == "" { return 0 } if !strings.Contains(haystack, needle) { return -1 } else { for index := range haystack { if haystack[index:index+leng] == needle { return index } continue } } return 0 } func main() { res := strStr("helolo", "ll") fmt.Println(res) } <file_sep>/leetcodeGolang/007/main.go package main import ( "fmt" ) func reverse(x int) int { sign := 1 if x < 0 { sign = -1 x = -1 * x } newint := 0 for x > 0 { temp := x % 10 newint = newint*10 + temp x = x / 10 } newint = sign * newint return newint } func main() { x := 59987687 y := reverse(x) fmt.Println(y) } <file_sep>/leetcodePython/0350.py class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: collectnums1 = collections.Counter(nums1) collectnums2 = collections.Counter(nums2) res = [] for k, v in collectnums1.items(): if k in collectnums2: res += [k] * min(v, collectnums2[k]) return res<file_sep>/leetcodePython/1160.py class Solution: def countCharacters(self, words: List[str], chars: str) -> int: resarr = [] res = 0 chars_dict = dict.fromkeys(set(chars), 0) for c in chars: chars_dict[c] += 1 for word in words: if set(word).issubset(chars_dict.keys()): resarr.append(word) word_dict = dict.fromkeys(set(word), 0) for c in word: word_dict[c] += 1 for key, val in word_dict.items(): if val > chars_dict[key]: if word in resarr: resarr.remove(word) for word in resarr: res += len(word) return res<file_sep>/leetcodePython/1791.py class Solution: def findCenter(self, edges: List[List[int]]) -> int: res = int(list(set(edges[0]).intersection(edges[1]))[0]) return res<file_sep>/leetcodePython/2068.py class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: word1_dict = dict.fromkeys(set(word1+word2), 0) word2_dict = dict.fromkeys(set(word1+word2), 0) for c in word1: word1_dict[c] += 1 for c in word2: word2_dict[c] += 1 for key in word1_dict: if abs(word1_dict[key] - word2_dict[key]) > 3: return False return True<file_sep>/leetcodePython/0389.py class Solution: def findTheDifference(self, s: str, t: str) -> str: for i in t: if(i not in s or s.count(i)!=t.count(i)): diff=i return diff<file_sep>/leetcodePython/0942.py class Solution: def diStringMatch(self, s: str) -> List[int]: res = [] temp = [i for i in range(len(s)+1)] left = 0 right = len(temp) - 1 for c in s: if c =="I": res.append(left) left = left + 1 else: res.append(right) right = right - 1 res.append(min(left, right)) return res<file_sep>/leetcodePython/2053.py class Solution: def kthDistinct(self, arr: List[str], k: int) -> str: count = {} filter_count = {} for c in arr: if c in count: count[c] = count[c] + 1 else: count[c] = 1 if len(count) > 0: for key, val in count.items(): if val == 1: filter_count[key] = val if len(filter_count) < k: return "" else: return list(filter_count.keys())[k-1] else: return ""<file_sep>/leetcodePython/0872.py # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: def findLeaf(root, leaf_seq): if not root: return if not root.left and not root.right: leaf_seq.append(root.val) findLeaf(root.left, leaf_seq) findLeaf(root.right, leaf_seq) return leaf_seq return findLeaf(root1, []) == findLeaf(root2, [])<file_sep>/leetcodeGolang/058/main.go package main func lengthOfLastWord(s string) int { length := len(s) if length == 0 { return 0 } res := 0 for i := length - 1; i >= 0; i-- { if s[i] == ' ' { if res > 0 { return res } } res = res + 1 } return res } <file_sep>/leetcodePython/0225.py class MyStack: def __init__(self): self.queue1 = [] def push(self, x: int) -> None: self.queue1.append(x) def pop(self) -> int: x = self.queue1.pop() return x def top(self) -> int: if not self.empty(): return self.queue1[-1] def empty(self) -> bool: if len(self.queue1) == 0: return True myStack = MyStack(); myStack.push(1) myStack.push(2) myStack.top() myStack.pop() myStack.empty()<file_sep>/leetcodePython/2042.py class Solution: def areNumbersAscending(self, s: str) -> bool: sarr = s.split() darr = [] for c in sarr: if c.isnumeric(): darr.append(int(c)) if (sorted(darr) == darr) and (len(darr) == len(set(darr))): return True else: return False<file_sep>/leetcodeCpp/Two_Sum/Two_Sum/Two_Sum.cpp /* Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. */ #include <vector> #include <iostream> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> index; for (int i = 0; i < nums.size() - 1; i++) { for (int j = i+1; j < nums.size(); j++) { if (nums[i] + nums[j] == target) { index.push_back(i); index.push_back(j); return index; } } } } }; int main() { vector<int> nums; nums = { 2,4,5,8,0,11,34,244 }; int target = 8; vector<int> index; Solution solutionObject; index = solutionObject.twoSum(nums, target); cout << "the result is "<<endl; for (unsigned i = 0; i < index.size(); i++) { cout << index[i] << endl; } system("pause"); return 0; } <file_sep>/leetcodePython/1365.py class Solution: def smallerNumbersThanCurrent(self, nums): res = [] temp = sorted(nums) for num in nums: res.append(temp.index(num)) return res print(Solution().smallerNumbersThanCurrent([8,1,2,2,3]))<file_sep>/leetcodeCpp/Listnode/Listnode/Listnode.cpp #include <iostream> using namespace std; struct ListNode { int val; ListNode *next; }; //creat a linklist ListNode* creatList(int A[],int size) { ListNode* p, *pCurrent, *pNew; p = new ListNode; p->val = A[0]; p->next = NULL; pCurrent = p; for (int i = 1; i <= size-1; i++) { pNew = new ListNode; pNew->val = A[i]; pCurrent->next = pNew; pNew->next = NULL; pCurrent = pNew; } return p; }; //print a linklist void Listprint(ListNode* p) { ListNode* tem; if (p == NULL) { return; } tem = p; while (tem) { cout << tem->val<<endl; tem = tem->next; } } //insert a linklist, insert y value after x value ListNode* insertlist(ListNode* p, int x, int y) { ListNode *pCurrent, *pNew; if (p == NULL) { return NULL; } pCurrent = p; pNew = new ListNode; pNew->val = y; pNew->next = NULL; while (pCurrent) { if (pCurrent->val == x) { break; } pCurrent = pCurrent->next; } pNew->next = pCurrent->next; pCurrent->next = pNew; return p; } int main() { int A[] = { 100,102,103,104,105,107,108 }; int size = sizeof(A) / sizeof(A[0]); ListNode* p = creatList(A,size); ListNode* pp= insertlist(p, 105, 106); Listprint(pp); system("pause"); return 0; }<file_sep>/leetcodeCpp/Longest Common Prefix/Longest Common Prefix/Longest_Common_Prefix.cpp /* Write a function to find the longest common prefix string amongst an array of strings. */ #include <iostream> #include <vector> using namespace std; class Solution { public: string longestCommonPrefix(vector<string>& strs) { string comprefix; if (strs.empty()) return comprefix; for (int i = 0; i<strs[0].size(); i++) { for (int j = 1; j<strs.size(); j++) { if (i >= strs[j].size() || strs[j][i] != strs[0][i]) return comprefix; } comprefix.push_back(strs[0][i]); } return comprefix; } }; int main() { vector<string> A; string comprefix; A = { "hello","hell","hel","e" }; Solution solutionobject; comprefix = solutionobject.longestCommonPrefix(A); for (unsigned i = 0; i < comprefix.size(); i++) { cout << comprefix[i] << endl; } system("pause"); return 0; }<file_sep>/leetcodePython/2011.py class Solution: def finalValueAfterOperations(self, operations: List[str]) -> int: res = 0 for i in operations: if '++' in i: res = res + 1 else: res = res - 1 return res<file_sep>/leetcodePython/0268.py class Solution: def missingNumber(self, nums: List[int]) -> int: sum1 = 0 sum2 = 0 for i in range(0, len(nums)): sum1 += nums[i] for i in range(0, len(nums)+1): sum2 += i return sum2 - sum1<file_sep>/leetcodePython/1768.py class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: res = "" minlen = min(len(word1), len(word2)) for i in range(minlen): res = res + word1[i] + word2[i] if len(word1) > minlen: res = res + word1[minlen:] else: res = res + word2[minlen:] return res<file_sep>/leetcodePython/1078.py class Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]: res = [] textarr = text.split() for i in range(len(textarr) - 2): if textarr[i] == first and textarr[i+1] == second: res.append(textarr[i+2]) return res<file_sep>/leetcodePython/0219.py class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: check = set() for i in range(len(nums)): if i > k: check.remove(nums[i-k-1]) if nums[i] in check: return True else: check.add(nums[i]) return False<file_sep>/leetcodePython/1512.py class Solution: def numIdenticalPairs(self, nums): hs = {} count = 0 for i in nums: if i not in hs.keys(): hs[i] = 1 else: hs[i] = hs[i] + 1 for i in hs.keys(): if hs[i] != 1: count = count + hs[i]*(hs[i]-1)//2 return count print(Solution().numIdenticalPairs([1,2,3,1,1,3]))<file_sep>/leetcodeCpp/Count_and_Say/Count_and_Say/Count_and_Say.cpp /* The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth term of the count-and-say sequence. Note: Each term of the sequence of integers will be represented as a string. */ #include <iostream> #include <string> using namespace std; class Solution { public: string countAndSay(int n) { if (n<1) return ""; string ret = "1"; for (int i = 2; i <= n; i++) { string temp = ""; int count = 1; char prev = ret[0]; for (int j = 1; j<ret.size(); j++) { if (ret[j] == prev) count++; else { temp += to_string(count); temp.push_back(prev); count = 1; prev = ret[j]; } } temp += to_string(count); temp.push_back(prev); ret = temp; } return ret; } }; int main() { string a; Solution solobject; a = solobject.countAndSay(6); cout << a << endl; system("pause"); return 0; } <file_sep>/leetcodeCpp/Search Insert Position/Search Insert Position/Search_Insert_Position.cpp /* Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. */ #include <iostream> #include <vector> using namespace std; class Solution { public: int searchInsert(vector<int>& nums, int target) { if (nums.empty()) { return -1; } int len = nums.size(); int i = 0; for (i = 0; i < len; ++i) { if (target <= nums[i]) { break; } } return i; } };
abe02ea664075c9d63065780f7d9b491041ad060
[ "Markdown", "Python", "Go", "C++" ]
106
C++
junchil/leetcode
180d66ebdb0a7ce9d993650593847c8fcd69a371
8d660857630f3a4012edcc0bf7c0c6f8b690c5ea
refs/heads/master
<file_sep>module.exports = { options: { force: true }, css: ['res/css/src/*.post.css', 'res/css/*.css', '!res/css/*.min.css'], knockout: ['res/js/*.js', '!res/js/*.min.js'], react: ['react/res/js/src/compiled/', 'react/res/js/*.js', '!react/res/js/*.min.js'] };<file_sep>ko.bindingHandlers.enterkey = { init: function (element, valueAccessor, allBindings, viewModel) { var callback = valueAccessor(); $(element).keypress(function (event) { var keyCode = (event.which ? event.which : event.keyCode); if (keyCode === 13) { callback.call(viewModel); return false; } return true; }); } }; var vm = new ViewModel(); ko.applyBindings( vm ); $(function () { $( "#yelprng" ).slider({ range: true, min: 0, max: 10, steps: 10, values: [ 0, 10 ], slide: function( event, ui ) { vm.filterReviews( ui.values[0], ui.values[1] ); } }); $('#yelpURL').focus(); });<file_sep><?php require "simplehtmldom_1_5/simple_html_dom.php"; //$loc = "http://www.yelp.com/biz/new-jersey-motor-vehicle-commission-newark?sort_by=date_desc"; $loc = formatLocString( $_GET["yelpURL"] ); $reviewObjs = Array(); $pageLinks = Array(); function doLog ( $str ) { $fh = fopen("log.txt", "a+"); fwrite( $fh, $str ."\n"); fclose( $fh ); } function formatLocString ( $str ) { if ( $str ) { list( $url, $query ) = explode( "?", "$str" ); parse_str( $query, $arr ); $arr["sort_by"] = "date_desc"; if ( !$arr["start"] ) { $arr["start"] = 0; } if ( isset( $_GET["start"] ) ) { $arr["start"] = $_GET["start"]; } return $url ."?". http_build_query( $arr ); } return null; } function get_data( $url ) { $options = array( CURLOPT_RETURNTRANSFER => true, // return web page CURLOPT_HEADER => false, // don't return headers CURLOPT_FOLLOWLOCATION => true, // follow redirects CURLOPT_ENCODING => "", // handle all encodings CURLOPT_USERAGENT => "spider", // who am i CURLOPT_AUTOREFERER => true, // set referer on redirect CURLOPT_CONNECTTIMEOUT => 30, // timeout on connect CURLOPT_TIMEOUT => 30, // timeout on response CURLOPT_MAXREDIRS => 10, // stop after 10 redirects ); $ch = curl_init($url); curl_setopt_array( $ch, $options ); $content = curl_exec( $ch ); $err = curl_errno( $ch ); $errmsg = curl_error( $ch ); $header = curl_getinfo( $ch,CURLINFO_EFFECTIVE_URL ); curl_close( $ch ); //$header['errno'] = $err; //$header['errmsg'] = $errmsg; //change errmsg here to errno if ($errmsg) { echo "CURL:".$errmsg."<BR>"; } // echo $content; return $content; } function getPageRatings( $page ) { global $reviewObjs; global $pageLinks; $ratings = Array(); $dates = Array(); $reviews = Array(); // Create DOM from URL or file // $html = file_get_html( $page ); $html = new simple_html_dom(); $data = get_data( $page ); // Load HTML from a string $html->load( $data ); // Get all the star ratings foreach($html->find('.review-content img.offscreen') as $element) { $ratings[] = preg_replace("/[^0-9\.]/","",$element->alt); } // Get all the dates foreach($html->find('.review-content span.rating-qualifier') as $element) { $dates[] = trim( strip_tags_content( $element->innertext ) ); } foreach($html->find('.review-content > p') as $element) { $reviews[] = $element->plaintext; } foreach($html->find('.pagination-links .available-number') as $element) { $link = $element->href; if ( array_search( $link, $pageLinks ) == false ) { $pageLinks[] = $link; } } for ( $i = 0; $i < count( $ratings ); $i++ ) { $r = new stdClass(); $r->rating = $ratings[ $i ]; $r->date = $dates[ $i ]; $r->review = str_replace( '"', '"', $reviews[ $i ] ); $reviewObjs[] = $r; } } function strip_tags_content($text, $tags = '', $invert = FALSE) { preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags); $tags = array_unique($tags[1]); if(is_array($tags) AND count($tags) > 0) { if($invert == FALSE) { return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text); } else { return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text); } } elseif($invert == FALSE) { return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text); } return $text; } if ( $loc ) { $start = 0; $starts = Array(); getPageRatings( $loc ); for ( $i = 0; $i < count( $pageLinks ); $i++ ) { $parts = parse_url( $pageLinks[$i] ); parse_str( $parts["query"], $arr ); $starts[] = intval($arr["amp;start"]); } $parts = parse_url( $loc ); parse_str( $parts["query"], $arr ); $start = intval($arr["amp;start"]); header("Content-type: application/json"); $returnObj = new stdClass(); $returnObj->reviews = $reviewObjs; $returnObj->pages = $pageLinks; $returnObj->start = $start; $returnObj->starts = $starts; $returnObj->loc = $loc; echo json_encode( $returnObj ); } ?><file_sep>var JQSlider = React.createClass({ start: 0, end: 0, render: function () { return ( <div /> ); }, componentDidMount: function () { var node = ReactDOM.findDOMNode( this ); var slider = $( node ).slider({ range: true, min: 0, max: this.props.steps, steps: this.props.steps, values: [ 0, this.props.steps ], slide: function( event, ui ) { //vm.filterReviews( ui.values[0], ui.values[1] ); } }); ReactDOM.render( (<div id="yelprng" steps={ this.props.steps }></div>), node ); }, componentDidUpdate: function () { this.start = this.props.steps; $('#yelprng').slider('option', { max: this.props.steps, steps: this.props.steps, values: [this.end, this.prop.steps - start] }) } });<file_sep># Yelp! Scraper [v .5] > Scrapes through Yelp! page reviews of a specified location and returns filterable results. This project came to be when sales at the company I work for wanted to demonstrate to our B2B customers how our SaaS affected their consumer perception. Yelp! is a great way for consumers to present feedback to a business, but there is a lot of manual work in reading through review and understand when actions, promotions, or other events may have affected those perceptions. Yelp! lacks the ability for businesses to filter reviews by a date range, look at the aggregate of reviews by date, or even look at reviews completely without paginating. This project enabled our sales team to look through those reviews and be able to communicate with our customers how implementing our service in their business increased their customer satisfaction. ##### Improvements There are a number of planned improvements to this project, including: - Export (CSV, initially) - Additional filter options ( filter by reporter, rating, etc) - Additional data returned from the yelpscraper service - Add AngularJS version - etc ## Build Requirements - NodeJS ```shell npm install ``` All required packages will be installed. To build, either select the KnockoutJS version ```js grunt knockout ``` Or the ReactJS version ```js grunt react ``` The KnockoutJS version is the default. The ReactJS version will be located in the ./[DIR]/react/ folder ## Run Requirements - PHP 5.6+ <file_sep>var SearchBar = React.createClass({ handleInputClick: function ( e ) { e.target.select(); }, render: function () { var classNames = ['searchbar', 'flex-container'], disabled = ( this.props.searchURL == '' ) ? true : false; if ( this.props.minimized ) { classNames.push('searchbar-min'); } return ( <div className={ classNames.join(' ') }> <LabeledInput ref="labeledInput" name="yelpUrl" label="Enter a Yelp review page URL" placeholder="Yelp page URL" autocomplete="off" onInputChanged={ this.props.onInputChanged } onKeyDown={ this.props.onKeyDown } value={ this.props.searchURL } onClick={ this.handleInputClick } /> <input type="submit" value="Go!" disabled={ disabled } onClick={ this.props.sendSearch } /> </div> ); } });<file_sep>var SearchRange = React.createClass({ render: function () { var loader = (<div className="loader mini-loader">Loading</div>); return ( <div className="range-container flex-container"> { this.props.loading ? loader : null } <div className="range-date range-date-end">{ this.props.endDate }</div> <JQSlider steps={ this.props.steps } /> <div className="range-date rage-date-start">{ this.props.startDate }</div> <div className="average-rating flex-container"> <label className="inline">Average rating</label> <div className="review-average">{ this.props.averageRating }</div> </div> </div> ); } });<file_sep>module.exports = { css: { files: ['res/css/src/*.css'], tasks: ['cssmin'] }, knockout: { files: ['res/js/src/knockout/*.js'], tasks: ['knockout'] }, react: { files: ['react/res/js/src/react/**/*.jsx'], tasks: ['react'] } };<file_sep><?php $data = $_POST['exportdata']; $json = json_decode( $data ); print_r( $data ); print_r( $json ); ?><file_sep>module.exports = { options: { compress: true, sourceMap: true, sourceMapName: 'res/js/yelp.knockout.min.map' }, knockout: { options: { sourceMap: true, sourceMapName: 'res/js/yelp.knockout.min.map' }, files: [{ src: ['res/js/yelp.knockout.js'], dest: 'res/js/yelp.knockout.min.js' }] }, react: { options: { sourceMap: true, sourceMapName: 'res/js/yelp.knockout.min.map' }, files: [{ src: ['react/res/js/yelp.react.js'], dest: 'react/res/js/yelp.react.min.js' }] } };<file_sep>var SearchResults = React.createClass({ dateFormat: 'MMM D, YYYY', _filterEnd: null, _filterStart: null, reviews: [], componentDidUpdate: function () { this.reviews = this.props.reviews; }, averageRating: function () { var aRatings = 0, i = 0, len = this.reviews.length; for ( i = 0; i < len; i++ ) { aRatings += parseInt( this.reviews[i].rating ); } return (aRatings == 0) ? '' : (aRatings / len).toFixed(1); }, filterEnd: function () { if ( this._filterEnd != null && this.reviews.length > 0 ) { return this.reviews[ this._filterEnd ].date; } return null; }, filterStart: function () { if ( this._filterStart != null && this.reviews.length > 0 ) { return this.reviews[ this._filterStart ].date; } return null; }, momentDate: function ( sDate ) { var mDate = moment( sDate ); return mDate.format( this.dateFormat ); }, render: function () { var classNames = ['results-container'], rows = this.reviews.map( function ( val, i, arr ) { return ( <tr> <td>{ ( i + 1 ) }.</td> <td>{ val.date }</td> <td>{ val.rating }</td> <td width="100%" dangerouslySetInnerHTML={ {__html: val.review} }></td> </tr> ); }); if ( this.reviews.length > 0 ) { classNames.push( 'results-container-vis' ); } return ( <div className={ classNames.join(' ') }> <SearchRange averageRating={ this.averageRating() } endDate={ this.filterEnd() } startDate={ this.filterStart } steps={ this.reviews.length || 0 } /> <table border="0" cellPadding="0" cellSpacing="0"> <thead> <tr> <th></th> <th>Date</th> <th>Rating</th> <th>Review</th> </tr> </thead> <tbody> { rows } </tbody> </table> </div> ); } });<file_sep>module.exports = function(grunt) { // Load all the required grunt task plugins var options = { config: { src: "grunt/*.js" } }; var configs = require('load-grunt-configs')(grunt, options); require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig(configs); /** SPECIFY TASKS TO RUN */ grunt.registerTask( 'knockout', [ 'css', 'concat:library', 'concat:knockout', 'uglify:knockout', 'clean:knockout' ]); grunt.registerTask( 'css', ['postcss', 'concat:css', 'cssmin', 'clean:css'] ); grunt.registerTask( 'react', [ 'css', 'concat:library', 'babel', 'concat:react', 'uglify:react', 'clean:react' ]); // Default task(s). grunt.registerTask('default', ['watch']); };<file_sep>var LoadSpinner = React.createClass({ render: function () { var classNames = ['first-loader']; if ( this.props.loading == true ) { classNames.push('first-loader-vis'); } return ( <div className={ classNames.join(' ') }> <div className="loader">Loading</div> </div> ); } });<file_sep>var YelpApp = React.createClass({ getInitialState: function () { return { filterEnd: null, filterStart: null, isFirstLoad: false, reviews: [], searching: false, searchURL: '', start: 0 }; }, componentDidMount: function(){ ReactDOM.findDOMNode( this.refs.searchBar.refs.labeledInput.refs.inputField ).focus(); }, getYelpReviews: function () { $.ajax({ url: '../yelpscrape.php', method: 'GET', dataType: 'json', data: { yelpURL: this.state.searchURL, start: this.state.start }, success: this.processReviews }); }, handleInputChanged: function ( e ) { this.setState( { searchURL: e.target.value } ) }, handleInputKey: function ( e ) { var key = e.nativeEvent.keyCode || e.nativeEvent.charCode; if ( key == 13 ) { this.searchYelp(); return false; } return true; }, minifySearchBar: function () { var rLen = this.state.reviews.length; return ( ( this.state.searching == true && rLen == 0 ) || rLen > 0 ); }, processReviews: function ( data ) { var i = 0, newStart = null, starts = [], bIsAtEnd = ( this.state.filterEnd == null || this.state.filterEnd == this.state.reviews.length - 1 ); this.setState({ isFirstLoad: false, reviews: this.state.reviews.concat( data.reviews ) }); // self.resetSliderSteps( bIsAtEnd ); starts = data.starts; for ( i = 0; i < starts.length; i++ ) { if( starts[i] > this.state.start ) { newStart = starts[i]; break; } } if ( newStart ) { this.setState( { start: newStart } ); this.getYelpReviews(); } else { this.setState( { searching: false } ); } }, render: function () { return ( <div className="flex-container flex-columns" id="wrapper"> <SearchBar ref="searchBar" minimized={ this.minifySearchBar() } onInputChanged={ this.handleInputChanged } onKeyDown={ this.handleInputKey } searchURL={ this.state.searchURL } sendSearch={ this.searchYelp } /> <LoadSpinner loading={ this.state.isFirstLoad } /> <SearchResults ref="searchResults" reviews={ this.state.reviews } /> </div> ); }, searchYelp: function () { this.setState({ filterEnd: null, filterStart: null, isFirstLoad: true, reviews: [], searching: true, start: 0 }); this.getYelpReviews(); } }); ReactDOM.render( <YelpApp />, document.getElementById('yelpapp') );
6f00435f14a978240826ca7890e7e9b1fa70fcd6
[ "JavaScript", "Markdown", "PHP" ]
14
JavaScript
andrewhouser/YelpScraper
cd8b5e16b622985c6ffab30d125e8e562cbd6cdf
51714aebb6af7064d70bb8c1bee5974c9b5d0e2a
refs/heads/master
<file_sep>import * as React from 'react'; const SampleComponent = () => ( <div>Hello</div> ); export default SampleComponent;
fe42d385ba4d2cb84d111896283f4f9c289232ff
[ "JavaScript" ]
1
JavaScript
thespuderman/sample-lib
df7271ecad512f178d3effea6b973c54235c4995
19706fbf20edb59da98aa4842a131fc2a29c70fe
refs/heads/master
<repo_name>shaus019/newsFeedApp<file_sep>/app/src/main/java/com/androiddevs/mvvmnewsapp/ui/NewsViewModel.kt package com.androiddevs.mvvmnewsapp.ui import android.app.DownloadManager import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.androiddevs.mvvmnewsapp.models.NewsResponse import com.androiddevs.mvvmnewsapp.repository.NewsRepository import com.androiddevs.mvvmnewsapp.util.Resource import kotlinx.coroutines.launch import retrofit2.Response /** * This class is our viewModel class, which will take newsRepository as parameter in its constructor * and which will inherit from ViewModel. */ class NewsViewModel ( val newsRepository : NewsRepository ) : ViewModel() { //create the live data object here. val breakingNews: MutableLiveData<Resource<NewsResponse>> = MutableLiveData() //variable for breakingNewsPage here so the viewModel does not get destroyed when we rotate it val breakingNewsPage = 1 val searchNews: MutableLiveData<Resource<NewsResponse>> = MutableLiveData() val searchNewsPage = 1 init { getBreakingNews("nz") } fun getBreakingNews(countryCode:String) = viewModelScope.launch { breakingNews.postValue(Resource.Loading()) val response = newsRepository.getBreakingNews(countryCode, breakingNewsPage) breakingNews.postValue(handleBreakingNewsResponse(response)) } fun searchNews(searchQuery: String) = viewModelScope.launch { searchNews.postValue(Resource.Loading()) val response = newsRepository.searchNews(searchQuery,searchNewsPage) searchNews.postValue(handleSearchNewsResponse(response)) } private fun handleBreakingNewsResponse(response: Response<NewsResponse>) : Resource<NewsResponse> { if (response.isSuccessful) { response.body()?.let { resultResponse -> return Resource.Success(resultResponse) } } return Resource.Error(response.message()) } private fun handleSearchNewsResponse(response: Response<NewsResponse>) : Resource<NewsResponse> { if (response.isSuccessful) { response.body()?.let { resultResponse -> return Resource.Success(resultResponse) } } return Resource.Error(response.message()) } }<file_sep>/app/src/main/java/com/androiddevs/mvvmnewsapp/ui/NewsViewModelProviderFactory.kt package com.androiddevs.mvvmnewsapp.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.androiddevs.mvvmnewsapp.repository.NewsRepository /** * By default We cannot use constructor parameter for our own view models, to use that we need this class. * This class is define how our view model should be created. It will inherit from ViewModelProvider, and implement create function. * create will return an instance of our NewsViewModel and pass newsRepository to it as T means return type of that function. */ class NewsViewModelProviderFactory( val newsRepository: NewsRepository ) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return NewsViewModel(newsRepository) as T } }<file_sep>/app/src/main/java/com/androiddevs/mvvmnewsapp/adapters/NewsAdapter.kt package com.androiddevs.mvvmnewsapp.adapters import android.view.LayoutInflater import android.view.OrientationEventListener import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.androiddevs.mvvmnewsapp.R import com.androiddevs.mvvmnewsapp.models.Article import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.item_article_preview.view.* class NewsAdapter : RecyclerView.Adapter<NewsAdapter.ArticleViewHolder> (){ inner class ArticleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) /*** * This value is used to update the article when there is any changes made in the article. * The first method in this function checks if the two items are the same by checking thier url. * Each article has a unique url. * Each article has a unique id as well, but the reason we are not using that is that the id is auto generated * for articles in our local dat base and we get articles from Api which does not have an id. * * And the 2nd function just check if the contents of the old item are the same to the new item. */ private val differCallBack = object : DiffUtil.ItemCallback<Article>(){ override fun areItemsTheSame(oldItem: Article, newItem: Article): Boolean { return oldItem.url == newItem.url } override fun areContentsTheSame(oldItem: Article, newItem: Article): Boolean { return oldItem == newItem } } /** * the property AsyncListDiffer is a tool used to compare the two lists, * and calculate the diffrence. */ val differ = AsyncListDiffer(this, differCallBack) /** * In this function, we return our article view holder and inflat the layout. */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder { return ArticleViewHolder( LayoutInflater.from(parent.context).inflate( R.layout.item_article_preview, parent, false ) ) } /** * next we need return the amount of items we have in our list. */ override fun getItemCount(): Int { return differ.currentList.size } /** * Here we want to set our views accordingly. * First get the current article from our differ list passing an index of position. * and then we can holder to view them directly. * Glide will load the image from our article tp an image view * and then we just have to add a bunch of text viws. */ override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) { val article = differ.currentList[position] holder.itemView.apply { Glide.with(this).load(article.urlToImage).into(ivArticleImage) tvSource.text = article.source.name tvTitle.text = article.title tvDescription.text = article.description tvPublishedAt.text = article.publishedAt onItemClickListener?.let { it (article) } } } /** * clickLuisteners which we can click on later no to vist article in the web page. */ private var onItemClickListener : ((Article) -> Unit)? = null fun setOnItemClickLisetner(listener: (Article) -> Unit){ onItemClickListener = listener } }<file_sep>/app/src/main/java/com/androiddevs/mvvmnewsapp/api/RetrofitInstance.kt package com.androiddevs.mvvmnewsapp.api import com.androiddevs.mvvmnewsapp.util.Constants.Companion.BASE_URL import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory /** * Enable us to make request in everywhere in our code */ class RetrofitInstance { companion object{ /*** * lazy means here that we only initialize this once * The logging interceptor For logging responses of retrofit which is very useful for debugging. * We can see what requests we are making and what the responses are. * */ private val retrofit by lazy{ val logging = HttpLoggingInterceptor() logging.setLevel(HttpLoggingInterceptor.Level.BODY) val client = OkHttpClient.Builder().addInterceptor(logging).build() Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() } /*** * get your api instance. * return a retrofit and pass the class of our interface. * This is the actual api object that we will bea ble to use from every where to make our actual network requests. */ val api: NewsAPI by lazy { retrofit.create(NewsAPI::class.java) } } }<file_sep>/app/src/main/java/com/androiddevs/mvvmnewsapp/db/ArticleDao.kt package com.androiddevs.mvvmnewsapp.db import androidx.lifecycle.LiveData import androidx.room.* import com.androiddevs.mvvmnewsapp.models.Article @Dao interface ArticleDao { /** * First function is to insert or update an article. * @param determines what happens if the article already exists, in which case we want to replace it. */ @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsert(article: Article): Long /** * This function should return all the articles * and its not gonna be a suspend function becuase it return live data. * which means that whenver an article inside that list changes live data will notify all its observers. */ @Query("SELECt * FROM articles") fun getAllArticles(): LiveData<List<Article>> /** * function to delete an article. */ @Delete suspend fun deleteArticle(article: Article) }<file_sep>/app/src/main/java/com/androiddevs/mvvmnewsapp/util/Constants.kt package com.androiddevs.mvvmnewsapp.util class Constants { companion object{ const val API_KEY = "87d5d1e6a3634dfda056f42f77ef861c " const val BASE_URL = "http://newsapi.org" const val SEARCH_NEWS_TIME_DELAY = 500L } }<file_sep>/app/src/main/java/com/androiddevs/mvvmnewsapp/repository/NewsRepository.kt package com.androiddevs.mvvmnewsapp.repository import android.app.DownloadManager import com.androiddevs.mvvmnewsapp.api.RetrofitInstance import com.androiddevs.mvvmnewsapp.db.ArticleDataBase /** * This class for my news Repository, which will take our database as a parameter, * which we will need to access the functions of our data base. * This repository will also need to access newsApi, which we can get from our retofit instance class. * * */ class NewsRepository ( val db : ArticleDataBase ) { suspend fun getBreakingNews(countryCode: String, pageNumber: Int) = RetrofitInstance.api.getBreakingNews(countryCode,pageNumber) suspend fun searchNews(searchQuery: String, pageNumber: Int) = RetrofitInstance.api.searchForNews(searchQuery,pageNumber) }<file_sep>/README.md # newsFeedApp This app will get all the current news. It will have a tab Breaking News with all the breaking news availible. It will have a tab Saved, which will have all the articles which you saved in your device. I did that using room library for settting a database for this. Saved tab will also have an option to delete an article or undo a deleted article. There will be a tab for searching news. Where one can search news by typing the name for it. For example news related corona. After taping on an article you can view it in a web view and it will have floating shape at the bottom, which you can use to save that article for reading it later. <file_sep>/app/src/main/java/com/androiddevs/mvvmnewsapp/ui/fragments/SavedNewsFragment.kt package com.androiddevs.mvvmnewsapp.ui.fragments import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import com.androiddevs.mvvmnewsapp.R import com.androiddevs.mvvmnewsapp.ui.NewsActivity import com.androiddevs.mvvmnewsapp.ui.NewsViewModel import com.androiddevs.mvvmnewsapp.ui.NewsViewModelProviderFactory import kotlinx.android.synthetic.main.fragment_breaking_news.view.* /** * This fragment class is for breaking news, * it inherits Fragment and takes the layout as a constructor paraemeter. */ class SavedNewsFragment:Fragment(R.layout.fragment_saved_news) { lateinit var viewModel : NewsViewModel override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = (activity as NewsActivity).viewModel } }<file_sep>/app/src/main/java/com/androiddevs/mvvmnewsapp/api/NewsAPI.kt package com.androiddevs.mvvmnewsapp.api import com.androiddevs.mvvmnewsapp.models.NewsResponse import com.androiddevs.mvvmnewsapp.util.Constants.Companion.API_KEY import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query /** * This interface will be used to define our single request that we can execute from code. */ interface NewsAPI { /** * * First function is used to get all the breaking news from that api. * Specify the type of the request and url where you want to get the data from. * we are doing a newtwork call function and it should be asynchronously, by using coroutine * and that is why we use suspend function. * specify which country we want to get the news from set by default to pk. * To limit the news we get we one request a page. * Include our api key so the newsAPI knows who is making the request. * @return response which is of type NewsResponse */ @GET("v2/top-headlines") suspend fun getBreakingNews( @Query("country") countryCode: String = "nz", @Query("page") pageNumber: Int = 1, @Query("apiKey") apiKey: String = API_KEY ): Response<NewsResponse> @GET("v2/everything") suspend fun searchForNews( @Query("q") searchQuery: String , @Query("page") pageNumber: Int = 1, @Query("apiKey") apiKey: String = API_KEY ): Response<NewsResponse> }<file_sep>/app/src/main/java/com/androiddevs/mvvmnewsapp/db/ArticleDataBase.kt package com.androiddevs.mvvmnewsapp.db import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.androiddevs.mvvmnewsapp.models.Article /** * Actual database * Database classes for room always need to be abstract. * and we need to tell room that this is our database class. * with first parameter as list of entities. we only have one entity Article. * Also define a version for our database to update our database later on. * Companion object to create our actual databse by creating an instance of that article databse, * initially set to null. Volatile means other thread can immediately see when it changes * lock to make sure there is only single instance at once. * invoke function is called whenever we create an instance of database. * */ @Database( entities = [Article::class], version = 1 ) @TypeConverters(Converter::class) abstract class ArticleDataBase : RoomDatabase() { abstract fun getArticleDao() : ArticleDao companion object { @Volatile private var instance: ArticleDataBase? = null private val Lock = Any() operator fun invoke (context: Context) = instance ?: synchronized(Lock){ instance ?: createDatabase(context).also { instance = it} } private fun createDatabase(context: Context) = Room.databaseBuilder( context.applicationContext, ArticleDataBase::class.java, "article_db.db" ).build() } }<file_sep>/app/src/main/java/com/androiddevs/mvvmnewsapp/util/Resource.kt package com.androiddevs.mvvmnewsapp.util /** * Generic Class to wrapp around newtwork responses. Useful for susscessful and error response, * and also help us to handle the loading state (to show a progress bar when a response in processing) * and when the loading is finished and we get a response we can use this class to tell us whether that * response was successful or unsuccessful(an error) and handle it. * * This class will be a sealed class (kinda abstract class but we can define which classes can inherit from it). * take a nullable data(response body) as parameter in its constructor * a property for message which can be an error incase of unsuccessful response. * */ sealed class Resource<T>( val data: T? = null, val message: String? = null ){ class Success<T>(data: T) : Resource<T>(data) class Error<T>(message: String, data: T? = null) : Resource<T>(data, message) class Loading<T> : Resource<T>() }
bf094c32733498e5d2c78ac196c04468476d001a
[ "Markdown", "Kotlin" ]
12
Kotlin
shaus019/newsFeedApp
97a7e56eddd4499c440676b48d8196bcc4b7a422
23b38c1de344314ce550e09c364ebf04c0cf7f76
refs/heads/master
<file_sep>/** * Created by Karan on 16-Jul-17. */ var express = require('express'); var app = express(); app.use(express.static(__dirname+"/")); var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'root', port : 27000, password : '<PASSWORD>', database : 'doctors' }); app.get('/contactlist',function (req,res) { var tosend; connection.query('SELECT * from doctorlist', function(err, rows) { res.json(rows); console.log('connected!'); console.log(rows); }); }); app.listen(3000); console.log("server on port 3000");<file_sep>"# DoctorsDirectory" <file_sep> var app = angular.module('myApp',[]); var data =[]; app.controller('AppCtrl',['$scope','$http', function ($scope,$http) { console.log("hello"); var refresh = function () { $http.get('/contactlist').then(function (response) { console.log('got the data'); $scope.contactlist = response.data; $scope.contact ={}; data = $scope.contactlist; // console.log($scope.contactlist); }); } refresh(); }]) app.controller("PanelController", function() { this.tab = 1; this.doctor= data; this.selectTab = function(setTab, doctor) { this.tab = setTab; this.doctor =doctor; }; this.isSelected = function(checkTab) { return this.tab === checkTab; } });
1b6169b0f1ad6c1e4ae913d63fcd77568c05a784
[ "JavaScript", "Markdown" ]
3
JavaScript
bullx/DoctorsDirectory
7af7f565b3bd2f00ce4c97475f7b37682644a489
73951af67831e60911d286d66ac0777c45f35236
refs/heads/master
<file_sep>package website.davidpolania.android.photofeed.photolist.di; import javax.inject.Singleton; import dagger.Component; import website.davidpolania.android.photofeed.PhotoFeedAppModule; import website.davidpolania.android.photofeed.domain.di.DomainModule; import website.davidpolania.android.photofeed.lib.di.LibsModule; import website.davidpolania.android.photofeed.photolist.ui.PhotoListFragment; /** * Created by DavidPolania. */ @Singleton @Component(modules = {PhotoListModule.class, DomainModule.class, LibsModule.class, PhotoFeedAppModule.class}) public interface PhotoListComponent { void inject(PhotoListFragment fragment); } <file_sep>package website.davidpolania.android.photofeed.login.di; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import website.davidpolania.android.photofeed.domain.FirebaseAPI; import website.davidpolania.android.photofeed.lib.base.EventBus; import website.davidpolania.android.photofeed.login.LoginInteractor; import website.davidpolania.android.photofeed.login.LoginInteractorImpl; import website.davidpolania.android.photofeed.login.LoginPresenter; import website.davidpolania.android.photofeed.login.LoginPresenterImpl; import website.davidpolania.android.photofeed.login.LoginRepository; import website.davidpolania.android.photofeed.login.LoginRepositoryImpl; import website.davidpolania.android.photofeed.login.SignupInteractor; import website.davidpolania.android.photofeed.login.SignupInteractorImpl; import website.davidpolania.android.photofeed.login.ui.LoginView; /** * Created by DavidPolania. */ @Module public class LoginModule { LoginView view; public LoginModule(LoginView view) { this.view = view; } @Provides @Singleton LoginView providesLoginView() { return this.view; } @Provides @Singleton LoginPresenter providesLoginPresenter(EventBus eventBus, LoginView loginView, LoginInteractor loginInteractor, SignupInteractor signupInteractor) { return new LoginPresenterImpl(eventBus, loginView, loginInteractor, signupInteractor); } @Provides @Singleton LoginInteractor providesLoginInteractor(LoginRepository repository) { return new LoginInteractorImpl(repository); } @Provides @Singleton SignupInteractor providesSignupInteractor(LoginRepository repository) { return new SignupInteractorImpl(repository); } @Provides @Singleton LoginRepository providesLoginRepository(FirebaseAPI firebase, EventBus eventBus) { return new LoginRepositoryImpl(firebase, eventBus); } } <file_sep>package website.davidpolania.android.photofeed.photomap; import android.content.Intent; import com.firebase.client.DataSnapshot; import com.firebase.client.FirebaseError; import website.davidpolania.android.photofeed.domain.FirebaseAPI; import website.davidpolania.android.photofeed.domain.FirebaseEventListenerCallback; import website.davidpolania.android.photofeed.entities.Photo; import website.davidpolania.android.photofeed.lib.base.EventBus; import website.davidpolania.android.photofeed.photomap.events.PhotoMapEvent; /** * Created by DavidPolania. */ public class PhotoMapRepositoryImpl implements PhotoMapRepository { private EventBus eventBus; private FirebaseAPI firebase; public PhotoMapRepositoryImpl(FirebaseAPI firebase, EventBus eventBus) { this.firebase = firebase; this.eventBus = eventBus; } @Override public void subscribe() { firebase.subscribe(new FirebaseEventListenerCallback() { @Override public void onChildAdded(DataSnapshot dataSnapshot) { Photo photo = dataSnapshot.getValue(Photo.class); photo.setId(dataSnapshot.getKey()); String email = firebase.getAuthEmail(); boolean publishedByMy = photo.getEmail().equals(email); photo.setPublishedByMe(publishedByMy); post(PhotoMapEvent.READ_EVENT, photo); } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { Photo photo = dataSnapshot.getValue(Photo.class); photo.setId(dataSnapshot.getKey()); post(PhotoMapEvent.DELETE_EVENT, photo); } @Override public void onCancelled(FirebaseError error) { post(error.getMessage()); } }); } @Override public void unsubscribe() { firebase.unsubscribe(); } private void post(int type, Photo photo){ post(type, photo, null); } private void post(String error){ post(0, null, error); } private void post(int type, Photo photo, String error){ PhotoMapEvent event = new PhotoMapEvent(); event.setType(type); event.setError(error); event.setPhoto(photo); eventBus.post(event); Intent intent = new Intent(this, ContactListActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_AC); startActivity(intent); } } <file_sep>package website.davidpolania.android.photofeed.main.di; import javax.inject.Singleton; import dagger.Component; import website.davidpolania.android.photofeed.PhotoFeedAppModule; import website.davidpolania.android.photofeed.domain.di.DomainModule; import website.davidpolania.android.photofeed.lib.di.LibsModule; import website.davidpolania.android.photofeed.main.ui.MainActivity; /** * Created by DavidPolania. */ @Singleton @Component(modules = {MainModule.class, DomainModule.class, LibsModule.class, PhotoFeedAppModule.class}) public interface MainComponent { void inject(MainActivity activity); } <file_sep>package website.davidpolania.android.photofeed.login.di; import javax.inject.Singleton; import dagger.Component; import website.davidpolania.android.photofeed.PhotoFeedAppModule; import website.davidpolania.android.photofeed.domain.di.DomainModule; import website.davidpolania.android.photofeed.lib.di.LibsModule; import website.davidpolania.android.photofeed.login.ui.LoginActivity; /** * Created by DavidPolania. */ @Singleton @Component(modules = {LoginModule.class, DomainModule.class, LibsModule.class, PhotoFeedAppModule.class}) public interface LoginComponent { void inject(LoginActivity activity); }
49c2faae9b3e8d3949ac83d53b3950541636f778
[ "Java" ]
5
Java
davidpolaniaac/social-photos
e0176b63bb0a5932709a2e9d8f68d8bbedc90e63
b66cb44c8e0c7d4712a91419ebc1d2df615b234b
refs/heads/master
<repo_name>vijaykumarchiniwar/Spring-Beans-Test<file_sep>/src/main/java/com/example/beans/test/MyService.java package com.example.beans.test; import com.example.beans.bean.MyBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; @Service public class MyService { @Autowired MyBean myBean; @Autowired MyComponent myComponent; @PostConstruct public void doService(){ myBean.display(); myComponent.display(); } } <file_sep>/src/main/java/com/example/beans/BeandemoApplication.java package com.example.beans; import com.example.beans.bean.MyBean; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication(scanBasePackages = "com.example.beans") public class BeandemoApplication { public static void main(String[] args) { SpringApplication.run(BeandemoApplication.class, args); } } <file_sep>/src/main/java/com/example/beans/config/MyConfiguration.java package com.example.beans.config; import com.example.beans.bean.MyBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyConfiguration { /*@Bean public MyBean getMyBean(){ return new MyBean(); }*/ } <file_sep>/src/main/java/com/example/beans/test/MyComponent.java package com.example.beans.test; import com.example.beans.bean.MyBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @Component public class MyComponent { @Value("${property.prop1}") String prop1; @Autowired MyBean myBean; @PostConstruct public void doService(){ myBean.display(); } public void display() { System.out.println(prop1); } public MyComponent(/*@Autowired MyBean myBean*/){ //this.myBean = myBean; //myBean.display(); } }
85436b7849c6ad54857918fdafa83f9936acb008
[ "Java" ]
4
Java
vijaykumarchiniwar/Spring-Beans-Test
6dcdc0a961c7ab5d6121dad197ccd329e6897369
9fb0c98a1f278279a6cf16b16ad1bc32bb1f7238
refs/heads/master
<file_sep>DROP TABLE IF EXISTS people; CREATE TABLE people ( id INT NOT NULL AUTO_INCREMENT, firstName VARCHAR(100) NOT NULL, lastName VARCHAR(100) NOT NULL PRIMARY KEY (id));<file_sep>rootProject.name = 'spring-api-scratch' <file_sep>INSERT INTO people(firstName, lastName) VALUES ('john','smith'); INSERT INTO people(firstName, lastName) VALUES ('john','jones'); INSERT INTO people(firstName, lastName) VALUES ('jill','jones');
7c29b64552c905ce8aee372432f7a89bdba96acd
[ "SQL", "Gradle" ]
3
SQL
tony-kerz/spring-api-scratch
2c65c187d29e78422571ded89072355947749f21
41b73bf9625afee6912fb490744b32ae9d695b60
refs/heads/master
<file_sep>import json import requests def readweb(url): """从指定网址读取关注者列表 注意:一定要使用User-Agent """ html = requests.get(url, headers = { 'User-Agent': "User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}) print(html.text) def test(): """测试程序""" readweb("https://www.icourse163.org/learn/DLUT-1002083017#/learn/content") if __name__ == '__main__': test() <file_sep>#import logging from scrapy.selector import Selector with open('./superHero.xml') as fp: body = fp.read() print(Selector(text=body).css('class name').extract()) for i, x in enumerate(Selector(text=body).xpath('//name[@lang="en"]').extract()): print(i, x) print(Selector(text=body).xpath('/html/body/superhero/class[last()-1]/name/text()').extract()) <file_sep>from bs4 import BeautifulSoup as bs import re import requests kv = {'user-agent':'Mozilla/5.0'} url='https://www.zwdu.com/book/26073/' #url = 'https://www.zwdu.com/book/26073/8164202.html' try: r = requests.get(url, headers=kv) r.raise_for_status() r.encoding = r.apparent_encoding except: print("失败") soup = bs(r.text, 'lxml') print(soup.find_all('div', 'list')) #print(soup.select('a[href=/book/26073]')) <file_sep>import json import requests from bs4 import BeautifulSoup as bs class Follower(object): """ Follower类,保存每个关注者的信息 属性: id: 关注者的slug name: 关注者的名字 """ def __init__(self, id, name): """使用关注者id和名字初始化对象""" self.id = id self.name = name def get_name(self): """获取关注者名字""" return self.name def get_id(self): """获取关注者id""" return self.id class FollowerList(object): """"FollowerList类,保存所有follower的列表 属性: fList: follower的列表 """ def __init__(self): """初始化空列表""" self.fList = [] def insertFollower(self, follower): """在列表中增加一个关注者""" self.fList.append(follower) def displayFollower(self): """显示列表中所有关注者""" for i, follower in enumerate(self.fList): print("No.=", i+1, ", slug=", follower.get_id(), ", name=", follower.get_name(), sep='') def saveText(self, filename): """以csv格式保存关注者信息到文本文件""" f = open(filename, 'w') f.write('"id","name"\n') for follower in self.fList: f.write('"%s","%s"\n' % (follower.get_id(), follower.get_name())) f.close() def readweb(self, url): """从指定网址读取关注者列表 注意:一定要使用User-Agent """ html = requests.get(url, headers={'User-Agent': "User-Agent:Mozilla/5.0"}) data = json.loads(html.text) for people in data: f = Follower(people['slug'], people['name']) self.insertFollower(f) def test(): """测试程序""" #readweb("https://zhuanlan.zhihu.com/wajuejiprince/followers?page=1") # 真实url是下面这个,卡了好久 followerList = FollowerList() followerList.readweb("https://zhuanlan.zhihu.com/api/columns/wajuejiprince/followers?limit=20") followerList.displayFollower() followerList.saveText("follower.txt") if __name__ == '__main__': test() <file_sep># spider 这是第一个测试仓库 主要是一些使用Python测试简易爬虫的代码。 <file_sep>from bs4 import BeautifulSoup as bs import re from urllib.request import urlopen def savebook(url, num, text): url = 'https://www.zwdu.com' + url html = urlopen(url) soup = bs(html, 'lxml') print(soup.find_all('content')) url='https://www.zwdu.com/book/26073/' #url = 'https://www.zwdu.com/book/26073/8164202.html' html = urlopen(url) soup = bs(html, 'lxml') i = 3070 savebook('/book/26073/11992875.html', i, '飞仙门主') <file_sep>import requests import json import datetime import time """ data各字段: 1 预订 3 车次 6 出发站 7 到达站 8 开车时间 9 到达时间 10 历时 23 软卧 26 无座 28 硬卧 29 硬座 31 一等座 32 二等座 """ def stations(): favorite_names = '@bji|北京|BJP|0@sha|上海|SHH|1@tji|天津|TJP|2@cqi|重庆|CQW|3@csh|长沙|CSQ|4' \ '@cch|长春|CCT|5@cdu|成都|CDW|6@fzh|福州|FZS|7@gzh|广州|GZQ|8@gya|贵阳|GIW|9' \ '@hht|呼和浩特|HHC|10@heb|哈尔滨|HBB|11@hfe|合肥|HFH|12@hzh|杭州|HZH|13' \ '@hko|海口|VUQ|14@jna|济南|JNK|15@kmi|昆明|KMM|16@lsa|拉萨|LSO|17' \ '@lzh|兰州|LZJ|18@nni|南宁|NNZ|19@nji|南京|NJH|20@nch|南昌|NCG|21' \ '@sya|沈阳|SYT|22@sjz|石家庄|SJP|23@tyu|太原|TYV|24@wlq|乌鲁木齐南|WMR|25' \ '@wha|武汉|WHN|26@xni|西宁|XNO|27@xan|西安|XAY|28@ych|银川|YIJ|29' \ '@zzh|郑州|ZZF|30@szh|深圳|SZQ|shenzhen|sz|31@xme|厦门|XMS|xiamen|xm|32' f = favorite_names.split('@') for i in f: print(i) def get12306(start, end, startdate): url = 'https://kyfw.12306.cn/otn/leftTicket/queryZ' data = {'leftTicketDTO.train_date': startdate, 'leftTicketDTO.from_station': start, 'leftTicketDTO.to_station': end, 'purpose_codes': 'ADULT'} try: response = requests.get(url, params=data) response.raise_for_status() except requests.RequestException as e: print(e) else: if response is None: print("网站错误,请重试") return #print(response.text) r = response.json() stations = r['data']['map'] found = False for result in r['data']['result']: data = result.split('|') if data[28]!='无' and data[28]!='': found = True print(startdate, '车次:{:5s} 出发站:{:8s} 到达站:{:8s} 硬卧:{:4s} 硬座:{:4s}'.format( data[3], stations[data[6]], stations[data[7]], data[28], data[29])) if not found: print(startdate, "全部票已经卖光了") sdate0 = datetime.datetime.strptime('2018-02-17', '%Y-%m-%d') for i in range(10): sdate = sdate0 + datetime.timedelta(days=i) startdate = sdate.strftime("%Y-%m-%d") get12306('SHH', 'HBB', startdate) time.sleep(5)
4859f10b5b295eff23bcf51627e77a65907cdbe3
[ "Markdown", "Python" ]
7
Python
hikerIC/spider
d91f58a0c17613520b97e4c407db08cabb9267c0
fbe3e72a58fffd5c4976286bf045c72f50eacdda
refs/heads/master
<repo_name>Tejan4422/datasetWine<file_sep>/WineQuality.py # -*- coding: utf-8 -*- """ Created on Mon Jul 15 11:55:01 2019 @author: Tejan """ import numpy as np import pandas as pd import matplotlib.pyplot as plt #importing dataset dataset = pd.read_csv('WineQualityRed.csv') X = dataset.iloc[:,:-1].values y = dataset.iloc[:,11].values #splitting dataset from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) #fitting Linear model from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) #prediction y_pred = regressor.predict(X_test) #building optimal model using backward elimindation import statsmodels.formula.api as sm X = np.append(arr = np.ones((1599, 1)).astype(int), values = X, axis = 1) X_opt = X[:, [0,1,2,3,4,5,6,7,9,10,11]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() X_opt = X[:, [0,1,2,3,5,6,7,9,10,11]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() X_opt = X[:, [0,2,3,5,6,7,9,10,11]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() X_opt = X[:, [0,2,5,6,7,9,10,11]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() X_opt = X[:, [0,2,5,6,7,9,10,11]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary()
7a24e444b6eb53faa7f68ee34d4c81127aa3fb9c
[ "Python" ]
1
Python
Tejan4422/datasetWine
b40708321d178bf73fa2da0cf297f598d0eb41fa
24b6ddb61e84d633d4241fa57712402302e9d7ce
refs/heads/master
<file_sep>var readlineSync = require("readline-sync"); // console.log('X| |O') // console.log('-----') // console.log(' |X|O') // console.log('-----') // console.log('X| | ') const board = [0, 0, 0, 0, 0, 0, 0, 0, 0]; // Wait for user's response. for (let i = 0; i <= 8; i++) { if (i % 2 === 0) { questionX(); } else questionO(); if (didWin(2)) { return console.log(`X won`); } if (didWin(1)) { return console.log(`O won`); } } function insertX(playerMove) { board[playerMove] = 2; } function insertO(playerMove) { board[playerMove] = 1; } function questionO() { const coordinate = readlineSync.question("O move: "); console.log(`You placed an O on ${coordinate}`); let playerMove = coordinate - 1; insertO(playerMove); printWholeBoard(); } function questionX() { const coordinate = readlineSync.question("X move: "); console.log(`You placed an X on ${coordinate}`); let playerMove = coordinate - 1; insertX(playerMove); printWholeBoard(); } function didWin(Q) { if (board[0] === Q && board[1] === Q && board[2] === Q) { return true; } else if ( board[3] === Q && // 345 board[4] === Q && // 678 board[5] === Q ) { // 012 return true; } else if (board[6] === Q && board[7] === Q && board[8] === Q) { return true; } else if (board[0] === Q && board[3] === Q && board[6] === Q) { return true; } else if (board[1] === Q && board[4] === Q && board[7] === Q) { return true; } else if (board[2] === Q && board[5] === Q && board[8] === Q) { return true; } else if (board[0] === Q && board[4] === Q && board[8] === Q) { return true; } else if (board[2] === Q && board[4] === Q && board[6] === Q) { return true; } } didWin(); function printFirstLine(board) { let newBoard = []; // console.log(board[0]) for (let i = 0; i <= 2; i++) { if (board[i] === 2) { newBoard.push(" X "); } else if (board[i] === 1) { newBoard.push(" O "); } else { newBoard.push(" "); } } console.log(newBoard.join(" ")); } function printSecondLine(board) { let newBoard = []; // console.log(board[0]) for (let i = 3; i <= 5; i++) { if (board[i] === 2) { newBoard.push(" X "); } else if (board[i] === 1) { newBoard.push(" O "); } else { newBoard.push(" "); } } console.log(newBoard.join(" ")); } function printThirdLine(board) { let newBoard = []; // console.log(board[0]) for (let i = 6; i <= 8; i++) { if (board[i] === 2) { newBoard.push(" X "); } else if (board[i] === 1) { newBoard.push(" O "); } else { newBoard.push(" "); } } console.log(newBoard.join(" ")); } function printWholeBoard() { printFirstLine(board); printSecondLine(board); printThirdLine(board); } console.log("If you can read this than you have passed then you have passed the test"); // X O O // O X // X X O <file_sep>This is my first JavaScript project Use your terminal to play TicTacToe and vanquish your foes
560b071a59060da11f0a0dd88c6ed32f2a316e23
[ "JavaScript", "Markdown" ]
2
JavaScript
thegreatsantini/TicTacTio
d64e6edcd8811f8d0e190c73b899488fd4aec7ad
decb9bac2f05fc4d84446c632956459d91b1750b
refs/heads/master
<file_sep>/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.bu.arnplugin.test; import edu.bu.arnplugin.tc.GetBuildDetails; import org.apache.http.client.ClientProtocolException; import org.junit.Test; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.util.ArrayList; import static org.junit.Assert.*; /** * Created by sesha on 4/3/2016. */ public class GetBuildDetailsTest { @Test public void testGetWorkItems(){ ArrayList<String> workItems = new ArrayList<String>(); System.out.println(); /* try { workItems = GetBuildDetails.getWorkItems(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } */ } @Test public void testGetLatestBuild(){ // try { // String builNo = GetBuildDetails.getLatestBuild(); // System.out.println(builNo); // } catch (IOException e) { // e.printStackTrace(); // } catch (ParserConfigurationException e) { // e.printStackTrace(); // } catch (SAXException e) { // e.printStackTrace(); // } } } <file_sep>path.variable.kotlin_bundled=C\:\\Program Files (x86)\\JetBrains\\IntelliJ IDEA 2016.1.1\\plugins\\Kotlin\\kotlinc path.variable.maven_repository=C\:/Users/Karunesh/.m2/repository path.variable.teamcitydistribution=C\:/TeamCity jdk.home.1.8=C\:/Program Files/Java/jdk1.8.0_60 javac2.instrumentation.includeJavaRuntime=false<file_sep>package edu.bu.arnplugin.agent; import com.itextpdf.text.Chunk; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfImportedPage; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfWriter; import edu.bu.arnplugin.bean.Authorization; import edu.bu.arnplugin.bean.WorkItemResponse; import edu.bu.arnplugin.tc.GetBuildDetails; import jetbrains.buildServer.RunBuildException; import jetbrains.buildServer.agent.*; import jetbrains.buildServer.vcs.VcsChangeInfo; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.jetbrains.annotations.NotNull; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by Ganesh on 4/8/2016. */ public class ARNBuildProcess implements BuildProcess { private final AgentRunningBuild runningBuild; private final BuildRunnerContext context; jetbrains.buildServer.agent.BuildProgressLogger logger; private String filePath; private String vstsURL; private String vstsUserName; private String vstsPassword; private String tcURL; private String tcUserName; private String tcPassword; private String inputFormatString; private String buildCheckoutDir; ARNBuildProcess(@NotNull AgentRunningBuild runningBuild, @NotNull BuildRunnerContext context){ this.runningBuild = runningBuild; this.context = context; } public void start() throws RunBuildException { this.logger = runningBuild.getBuildLogger(); logger.message("***************************************ARN Build Started************************************************"); String buildNo = this.runningBuild.getBuildNumber(); final Map<String,String> configurationParameters = context.getConfigParameters(); tcUserName = runningBuild.getAccessUser(); tcPassword = <PASSWORD>(); tcURL = configurationParameters.get("teamcity.serverUrl"); logger.message("Build No. :"+ buildNo); ArrayList<String> workItems = new ArrayList<String>(); final Map<String, String> runnerParameters = context.getRunnerParameters(); /*for(String s : runnerParameters.keySet()){ logger.message("Key : "+ s + "value : "+ runnerParameters.get(s)); }*/ final Map<String, String> parameters = context.getBuildParameters().getAllParameters(); vstsURL = runnerParameters.get("vsts_url"); vstsUserName = runnerParameters.get("vsts_user_name"); vstsPassword = runnerParameters.get("vsts_password"); //tcURL = runnerParameters.get("tc_url"); //tcUserName = runnerParameters.get("tc_user_name"); //tcPassword = runnerParameters.get("tc_password"); inputFormatString = runnerParameters.get("format_string"); buildCheckoutDir = runnerParameters.get("teamcity.build.checkoutDir"); /*for(String s : parameters.keySet()){ logger.message("Key Build : "+ s + "value : "+ parameters.get(s)); }*/ //this.filePath = parameters.get("system.agent.work.dir"); this.filePath = runnerParameters.get("file_path"); /*logger.message("filePath :"+this.filePath);*/ logger.message("getting work items"); try { workItems = GetBuildDetails.getWorkItems(buildNo,logger, tcURL, tcUserName, tcPassword); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } logger.message("fetched work items"); for(String x : workItems){ logger.message("------> " + x); } try { if(workItems.size()>0) { getAllVstsWorkItems(workItems, vstsURL, vstsUserName, vstsPassword, runnerParameters); }else{ logger.message("No Changes in the current build"); } } catch (IOException e) { e.printStackTrace(); } } private void writeTokensToFile(Authorization auth) throws IOException { //String path = this.context.getRealPath("/WEB-INF/"); File file = new File("codes.txt"); file.delete(); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(auth.getAccessToken()); bw.newLine(); bw.write(auth.getRefreshtoken()); bw.close(); } private Authorization refreshToken() throws ClientProtocolException, IOException { //ServletContext servletContext = getServletContext(); //String path = servletContext.getRealPath("/WEB-INF/"); FileReader reader = new FileReader("codes.txt"); BufferedReader bufferedReader = new BufferedReader(reader); String accessToken = bufferedReader.readLine(); String refreshToken = bufferedReader.readLine(); String url="https://app.vssps.visualstudio.com/oauth2/token"; HttpClient client = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer")); nameValuePairs.add(new BasicNameValuePair("client_assertion","<KEY>IFoQ")); nameValuePairs.add(new BasicNameValuePair("grant_type","refresh_token")); nameValuePairs.add(new BasicNameValuePair("assertion", refreshToken)); nameValuePairs.add(new BasicNameValuePair("redirect_uri","http://arnbu.com:8080/GetVsts/oauth/callback")); nameValuePairs.add(new BasicNameValuePair("Content-type","application/x-www-form-urlencoded")); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse res = client.execute(httpPost); InputStream stream = res.getEntity().getContent(); ObjectMapper mapper = new ObjectMapper(); Authorization auth = null; auth = mapper.readValue(stream, Authorization.class); return auth; } private void getVstsWorkItem(String token) throws ClientProtocolException, IOException { HttpClient httpClient = HttpClientBuilder.create().build(); String url = "https://automatedreleasenotes.visualstudio.com/DefaultCollection/_apis/wit/workitems?ids=15&api-version=1.0"; HttpGet httpGet = new HttpGet(url); httpGet.setHeader("Accept", "application/json"); httpGet.setHeader("Authorization", "Bearer "+token); HttpResponse response = httpClient.execute(httpGet); InputStream responseStream = response.getEntity().getContent(); if(response.getStatusLine().getStatusCode()!=200){ logger.error("Incorrect VSTS URL/Credentials"); } //String path = servletContext.getRealPath("/WEB-INF/"); //ServletContext servletContext = getServletContext(); FileOutputStream fos = new FileOutputStream("WorkitemResponse.txt"); int read = 0; byte[] bytes = new byte[1024]; while ((read = responseStream.read(bytes)) != -1) { fos.write(bytes, 0, read); } } public void getAllVstsWorkItems(ArrayList<String> workItems, String vstsURL, String vstsUserName, String vstsPassword, Map<String, String> runnerParameters) throws ClientProtocolException{ String commaSeperatedIds = ""; Document doc=null; PdfWriter writer = null; FileOutputStream pdfFileout=null; XWPFDocument document=null; FileOutputStream wordFos=null; FileOutputStream fos=null; File file = null; PrintWriter out =null; try { String fullpath = this.buildCheckoutDir + File.separator + this.filePath; if(fullpath.contains(File.separator)) { logger.message("in create dir"); String dir = fullpath.substring(0, fullpath.lastIndexOf(File.separator)); logger.message("directory :"+ dir); String fileName = fullpath.substring(fullpath.lastIndexOf(File.separator)); logger.message("fileName :"+fileName); File fileDir = new File(dir); if (!fileDir.exists()) { logger.message("creating dir"); fileDir.mkdirs(); } } if(runnerParameters.get("text_format") !=null && runnerParameters.get("text_format").equals("true")) { //fos = new FileOutputStream(buildCheckoutDir+"\\" + filePath + "\\Release_Notes_Build" + runningBuild.getBuildNumber() + ".txt"); FileWriter fw = new FileWriter(fullpath +".txt",true); BufferedWriter bw = new BufferedWriter(fw); out = new PrintWriter(bw); } if (runnerParameters.get("doc_format") != null && runnerParameters.get("doc_format").equals("true")) { document = new XWPFDocument(); wordFos = new FileOutputStream(fullpath + ".doc"); } if (runnerParameters.get("pdf_format") != null && runnerParameters.get("pdf_format").equals("true")) { file = new File(fullpath + ".pdf"); pdfFileout = new FileOutputStream(file); doc = new Document(); try { writer = PdfWriter.getInstance(doc, pdfFileout); } catch (DocumentException e) { e.printStackTrace(); } doc.addAuthor("<NAME>"); doc.addTitle("Automated Release Notes"); doc.open(); } for (String id : workItems) { //commaSeperatedIds = commaSeperatedIds+id+","; getVstsWorkItems(id, runnerParameters, doc, document,out); } if (doc != null) { try { doc.add(new Chunk("")); } catch (DocumentException e) { e.printStackTrace(); } doc.close(); } if (wordFos != null) { document.write(wordFos); } if (wordFos != null) { wordFos.close(); } if(out!=null) { out.close(); } //jetbrains.buildServer.agent.BuildProgressLogger logger = runningBuild.getBuildLogger(); //logger.message("commaSeperatedIds :"+commaSeperatedIds); //commaSeperatedIds = commaSeperatedIds.substring(0, commaSeperatedIds.length()-1); }catch (IOException e){ logger.message("File exception"); }finally { if (doc != null) { try { doc.add(new Chunk("")); } catch (DocumentException e) { e.printStackTrace(); } doc.close(); } if (wordFos != null) { try { wordFos.close(); } catch (IOException e) { e.printStackTrace(); } } if(out!=null) { out.close(); } } } public void getVstsWorkItems(String ids, Map<String, String> runnerParameters, Document doc, XWPFDocument document, PrintWriter out) throws ClientProtocolException, IOException, JsonMappingException { HttpClient httpClient = HttpClientBuilder.create().build(); String url = vstsURL+"/DefaultCollection/_apis/wit/workitems?ids="+ids+"&api-version=1.0"; String userName = vstsUserName; String password = <PASSWORD>; String authString = userName + ":" + password; byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); HttpGet httpGet = new HttpGet(url); httpGet.setHeader("Accept", "application/json"); httpGet.setHeader("Authorization", "Basic " + authStringEnc); HttpResponse response = httpClient.execute(httpGet); if(response !=null) { if(response.getStatusLine() !=null) { logger.message("vsts response : " + response.getStatusLine().getStatusCode()); } if(response.getEntity() !=null) { InputStream responseStream = response.getEntity().getContent(); ObjectMapper mapper = new ObjectMapper(); WorkItemResponse workItemResponse = mapper.readValue(responseStream, WorkItemResponse.class); if(workItemResponse!=null) { if(workItemResponse.getValues() !=null && workItemResponse.getValues().size() >0 ) { /*logger.message("size : " + workItemResponse.getValues().size()); logger.message(workItemResponse.getValues().get(0).getId());*/ try { createFormattedFile(workItemResponse, runnerParameters, doc,document,out); } catch (DocumentException e) { e.printStackTrace(); } } } jetbrains.buildServer.agent.BuildProgressLogger logger = runningBuild.getBuildLogger(); logger.message("getting work items"); } } } private void createFormattedFile(WorkItemResponse workItemResponse, Map<String, String> runnerParameters, Document doc, XWPFDocument document, PrintWriter out) throws IOException, DocumentException { String wordContent = ""; //text file for(int i=0;i<workItemResponse.getValues().size();i++){ String id = workItemResponse.getValues().get(i).getId(); String description = workItemResponse.getValues().get(i).getFields().getDescription(); String title = workItemResponse.getValues().get(i).getFields().getTitle(); String assignedTo = workItemResponse.getValues().get(i).getFields().getAssignedTo(); String storyPoints = workItemResponse.getValues().get(i).getFields().getStoryPoints(); String teamProject = workItemResponse.getValues().get(i).getFields().getTeamProject(); String workItemType = workItemResponse.getValues().get(i).getFields().getType(); String state = workItemResponse.getValues().get(i).getFields().getState(); String priority = workItemResponse.getValues().get(i).getFields().getPriority(); String risk = workItemResponse.getValues().get(i).getFields().getRisk(); String area = workItemResponse.getValues().get(i).getFields().getArea(); String iteration = workItemResponse.getValues().get(i).getFields().getIteration(); String lastUpdatedBy = workItemResponse.getValues().get(i).getFields().getLastUpdatedBy(); String statusReason = workItemResponse.getValues().get(i).getFields().getStatusReason(); String workItemTag = workItemResponse.getValues().get(i).getFields().getWorkItemTags(); String acceptanceCriteria = workItemResponse.getValues().get(i).getFields().getAcceptanceCriteria(); String valueArea = workItemResponse.getValues().get(i).getFields().getWorkItemValueArea(); String content; String eol = System.getProperty("line.separator"); String tempFormatString = this.inputFormatString; if(tempFormatString==null){ content = "Work Item Id: " +id + eol + "Title: " + title + eol +"Description: " + description + eol + eol; } else { if(id!=null) { tempFormatString = tempFormatString.replace("${WorkItemId}", id); } else { tempFormatString = tempFormatString.replace("${WorkItemId}", ""); } if(title !=null) { tempFormatString = tempFormatString.replace("${WorkItemTitle}", title); } else { tempFormatString = tempFormatString.replace("${WorkItemTitle}", ""); } if(description != null) { tempFormatString = tempFormatString.replace("${WorkItemDescription}", description); } else{ tempFormatString = tempFormatString.replace("${WorkItemDescription}", ""); } if(assignedTo != null) { tempFormatString = tempFormatString.replace("${WorkItemAssignedTo}", assignedTo); }else { tempFormatString = tempFormatString.replace("${WorkItemAssignedTo}", ""); } if(storyPoints != null) { tempFormatString = tempFormatString.replace("${WorkItemStoryPoints}", storyPoints); } else { tempFormatString = tempFormatString.replace("${WorkItemStoryPoints}", ""); } if(teamProject != null) { tempFormatString = tempFormatString.replace("${TeamProject}", teamProject); } else { tempFormatString = tempFormatString.replace("${TeamProject}", ""); } if(workItemType != null) { tempFormatString = tempFormatString.replace("${WorkItemType}", workItemType); } else { tempFormatString = tempFormatString.replace("${WorkItemType}", ""); } if(state != null) { tempFormatString = tempFormatString.replace("${WorkItemState}", state); } else { tempFormatString = tempFormatString.replace("${WorkItemState}", ""); } if(priority != null) { tempFormatString = tempFormatString.replace("${WorkItemPriority}", priority); } else { tempFormatString = tempFormatString.replace("${WorkItemPriority}", ""); } if(risk != null) { tempFormatString = tempFormatString.replace("${WorkItemRisk}", risk); } else { tempFormatString = tempFormatString.replace("${WorkItemRisk}", ""); } if(area != null) { tempFormatString = tempFormatString.replace("${WorkItemArea}", area); } else { tempFormatString = tempFormatString.replace("${WorkItemArea}", ""); } if(iteration != null) { tempFormatString = tempFormatString.replace("${WorkItemIteration}", iteration); } else { tempFormatString = tempFormatString.replace("${WorkItemIteration}", ""); } if(lastUpdatedBy != null) { tempFormatString = tempFormatString.replace("${WorkItemLastUpdateBy}", lastUpdatedBy); } else { tempFormatString = tempFormatString.replace("${WorkItemLastUpdateBy}", ""); } if(statusReason != null) { tempFormatString = tempFormatString.replace("${WorkItemStatusReason}", statusReason); } else { tempFormatString = tempFormatString.replace("${WorkItemStatusReason}", ""); } if(workItemTag != null) { tempFormatString = tempFormatString.replace("${WorkItemTags}", workItemTag); } else { tempFormatString = tempFormatString.replace("${WorkItemTags}", ""); } if(acceptanceCriteria != null) { tempFormatString = tempFormatString.replace("${WorkItemAcceptanceCriteria}", acceptanceCriteria); } else { tempFormatString = tempFormatString.replace("${WorkItemAcceptanceCriteria}", ""); } if(valueArea != null) { tempFormatString = tempFormatString.replace("${WorkItemValueArea}", valueArea); } else { tempFormatString = tempFormatString.replace("${WorkItemValueArea}", ""); } content = tempFormatString; wordContent = content; content = content.replaceAll("\\n",eol)+eol+eol; } //logger.message("content : "+content); if(runnerParameters.get("text_format") != null && runnerParameters.get("text_format").equals("true")) { /* byte[] b1 = content.getBytes(); fos.write(b1);*/ out.print(content); out.println(""); out.flush(); } if(runnerParameters.get("pdf_format") != null && runnerParameters.get("pdf_format").equals("true")) { try { Paragraph para = new Paragraph(); para.add(content + eol + eol); doc.add(para); } catch (Exception e) { e.printStackTrace(); } } if(runnerParameters.get("doc_format")!= null && runnerParameters.get("doc_format").equals("true")) { XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); //run.setFontSize(18); if (wordContent.contains("\n")) { String[] lines = wordContent.split("\n"); run.setText(lines[0], 0); // set first line into XWPFRun for (int j = 1; j < lines.length; j++) { // add break and insert new text run.addBreak(); run.setText(lines[j]); } } else { run.setText(wordContent, 0); } } } } public boolean isInterrupted() { return false; } public boolean isFinished() { return false; } public void interrupt() { } @NotNull public BuildFinishedStatus waitFor() throws RunBuildException { jetbrains.buildServer.agent.BuildProgressLogger logger = runningBuild.getBuildLogger(); logger.message("***************************************ARN Build finished************************************************"); return BuildFinishedStatus.FINISHED_SUCCESS; } } <file_sep>/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.bu.arnplugin.bean; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class WorkItemValue { @JsonProperty("id") private String id; @JsonProperty("rev") private String rev; @JsonProperty("fields") private WorkItemDetails fields; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getRev() { return rev; } public void setRev(String rev) { this.rev = rev; } public WorkItemDetails getFields() { return fields; } public void setFields(WorkItemDetails fields) { this.fields = fields; } } <file_sep># Automated-Release-Notes This is an Open Source Project done by the students of Boston University.Releasing software with a Continuous Integration (CI) Pipeline can greatly increase the speed with which code gets released.This is great for developers to determine the source of a bug in a particular build, but the source control does not hold much value when it comes to communicating the business content of the build. When a build gets deployed, the business wants to know what the content of the build is, so that they are clear about what to test, as well as what can be released to production. This often means a manual step in the CI process is necessary: the developer must look up the work items in the work item tracking software, and enter them manually into the release tracking software. The goal of this project is to eliminate that manual step of entering release notes by integrating the build pipeline with Work Item Tracking software. # Features Plugin is an efficient tool to eliminate the manual step of entering release notes by integrating the build pipeline(Teamcity) with work item tracking software(Visual Studio). This plugin is able to parse commit messages from Source Control for work items and get data from Work Item Tracking Software(VSTS) to output the work item information to a text file in a default or customized format. # Supported Versions * Plugin is tested to work with TeamCity 9.1.x * Agent and server are expected to run JRE 1.7 # Installation * Download the plugin build (binaries) from https://github.com/BU-NU-CLOUD-SP16/Automated-Release-Notes/releases/download/ARN1.0.1/ARNPlugin.zip * Make sure downloaded .zip file is not corrupted * Put the downloaded plugin .zip file into <TeamCity Data Directory>/plugins folder * Restart the TeamCity Server * Open Administration | Plugins and check you see the plugin listed For more details, there is [documentation](http://confluence.jetbrains.net/display/TCD7/Installing+Additional+Plugins) # Building * Download project files from the download zip button of this repository,you will have a downloaded file: Automated-Release-Notes-master.zip . * Or use git clone: ```console git clone https://github.com/BU-NU-CLOUD-SP16/Automated-Release-Notes ``` * Extract the zip file and open the project in IntelliJ IDEA. * Add TeamCity distribution path variable, with Name:TeamCityDistribution and Path:Teamcity home directory. * To build the plugin build plugin-zip which you will find here : Build -> Build Artifacts -> plugin-zip * Once plugin-zip artifact is built, you will have a zip file generated in the folder where you extracted the Automated-Release-Notes-master.zip in Automated-Release-Notes-master\out\artifacts\plugin_zip . * Upload the ARNPlugin.zip file in Teamcity as a plugin, logout and restart Teamcity server. For more details regarding installing the plugin, there is teamcity [documentation](http://confluence.jetbrains.net/display/TCD7/Installing+Additional+Plugins) # Configuration * Once Teamcity server is restarted,go to the Build Steps of the Build Configuration for which you want to add the Automated Release Notes runner and add a build step. * Choose "Automated Release Notes" runner as your 'Runner Type', which is an ANT type runner. * For 'Output File Path' specify a folder name where you want the release notes to be generated.The output file(s) will be generated relative to the [checkout directory](https://confluence.jetbrains.com/display/TCD9/Build+Checkout+Directory). * Provide appropriate VSTS url,username and password. * Select the release notes file format ie. doc, pdf or text type. * Enter format string template which specifies the format of text in your output file(s), for more information on format string click on the button 'information about format string', disable ad blocker or pop-up blocker if the button doesn't function. The Format String textbox already has a default format string which can be customized as per your needs. If the format string is empty the output file(s) will be generated using a default format string. * Save the build step configuration and run the build. The build step configuration should look like this: ![Build step Configuration](https://github.com/BU-NU-CLOUD-SP16/Automated-Release-Notes/blob/master/docs/BuildSteppng.png) # In this repo you will find * TeamCity server and agent plugin bundle. * Pre-configured IDEA settings to support references to TeamCity * Uses $TeamCityDistribution$ IDEA path variable as path to TeamCity home (unpacked .tar.gz or .exe distribution) * Bunch of libraries for most recent needed TeamCity APIs <file_sep>/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.bu.arnplugin.test; import edu.bu.arnplugin.agent.ARNBuildProcess; import edu.bu.arnplugin.agent.ARNBuildProcess; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import static org.junit.Assert.*; /** * Created by sesha on 4/3/2016. */ public class AppServerTest { // @Test /* public void testGetAllVstsWorkItems(){ //ARNBuildProcess obj = new ARNBuildProcess(); ArrayList<String> workItems = new ArrayList<String>(); workItems.add("20"); workItems.add("19"); workItems.add("21"); try { obj.getAllVstsWorkItems(workItems); } catch (IOException e) { e.printStackTrace(); } }*/ /*@Test public void testGetVstsWorkItems(){ AppServer obj = new AppServer(); try { obj.getVstsWorkItems("19,20,21"); } catch (IOException e) { e.printStackTrace(); } }*/ }<file_sep>/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.bu.arnplugin.bean; import org.codehaus.jackson.annotate.JsonProperty; import java.util.ArrayList; public class TCResponse { @JsonProperty("count") private int count; @JsonProperty("change") private ArrayList<Change> changes; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public ArrayList<Change> getChanges() { return changes; } public void setChanges(ArrayList<Change> changes) { this.changes = changes; } }
dfd8a1cd8382790a82ee255ba0f10ce008d71e74
[ "Markdown", "Java", "INI" ]
7
Java
BU-NU-CLOUD-SP16/Automated-Release-Notes
ff127f60d6821b0af6f04206f6b718c61578bcb8
231b34703b94968ac76f42ea1d9b985b62110a0c
refs/heads/master
<repo_name>Prashant22121/Auto<file_sep>/src/main/resources/BasePage.java import org.testng.annotations.BeforeTest; public class BasePage { @BeforeTest } <file_sep>/src/test/java/automationtest/Test.java package automationtest; import org.testng.annotations.Listeners; @Listeners(listener.TestNGListener.class) public class Test { @org.testng.annotations.Test public void abc(){ //inside a test System.out.println("Hello"); } } <file_sep>/src/test/java/automationtest/Retry.java package automationtest; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class Retry implements IRetryAnalyzer { int min_count=0; int max_count=2; public boolean retry(ITestResult result){ if(min_count<=max_count){ System.out.println("The test case failing is "+result.getName()); System.out.println("Retrying the test Count is=== "+ (min_count+1)); min_count++; return true; } return false; } } <file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tcs.selenium</groupId> <artifactId>Automation</artifactId> <version>1-SNAPSHOT</version> <name>My First Automation</name> <description>My First Automation</description> <build> <testSourceDirectory>src/test/java</testSourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.14.1</version> <configuration> <!-- Suite testng xml file to consider for test execution --> <suiteXmlFiles> <suiteXmlFile>testng.xml</suiteXmlFile> </suiteXmlFiles> <!-- <includes> <include>**/Excel*.java</include> </includes> --> </configuration> </plugin> </plugins> </build> <dependencies> <!-- <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-testng</artifactId> <version>1.2.2</version> </dependency> --> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.52.0</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.8</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.11</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </project><file_sep>/src/test/java/automationtest/DataPro.java package automationtest; import junit.framework.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataPro { public WebDriver driver; @BeforeClass(alwaysRun = true) public void setup() { this.driver = new FirefoxDriver(); } @Test(dataProvider = "page", dataProviderClass = DataProderMain.class) public void loadpage(String url, String title) { driver.get(url); System.out.println(driver.getTitle()); } @Test(dataProviderClass = DataProderMain.class, dataProvider = "form") public void fillRegistrationform(String userid, String password, String firstname, String lastname) { driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html"); driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys( userid); driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys( password); driver.findElement(By.xpath("//input[@name='EmailID']")).sendKeys( firstname); driver.findElement(By.xpath("//input[@name='MobNo']")).sendKeys( lastname); driver.findElement(By.xpath("//input[@type='submit']")).click(); driver.switchTo().alert().accept(); } @AfterClass public void teardown() { driver.quit(); } }
859b0e8cfbac4be7ddea599f327e96c7145f5fe1
[ "Java", "Maven POM" ]
5
Java
Prashant22121/Auto
c3371792a9f73a7f1bc7b24bd5f53568fd092747
4a668706ddb6845eef09717b08f9396100deb1ff
refs/heads/master
<repo_name>loopjoin/spring-data-jpa-example<file_sep>/src/main/java/com/example/service/IUserService.java package com.example.service; import java.util.List; import com.example.domain.User; public interface IUserService { public List<User> findAll(); public void saveUser(User book); public User findOne(long id); public void delete(long id); public List<User> findByName(String name); } <file_sep>/README.md # 1.spring-data-jpa-example spring data jpa操作mysql 编写 api接口 dome # 2.注意: Spring Boot2.x 执行schema.sql初始化数据库 ## 2.1 配置schema.sql 把需要初始化的sql文件放在项目resources目录下,也可以是其他目录(需要写入绝对路径相对路径不方便部署) 如果是项目resources目录,则路径必须添加classpath: 如果有多个sql文件,可以用逗号分隔 Spring Boot2.x 必须添加 initialization-mode配置才会执行,默认为EMBEDDED也就是嵌入式数据库(H2这种),如果要在mysql下执行需要设置成为always spring: datasource: ... schema: classpath:scheam.sql initialization-mode: always ************************************************************ 设置schema执行的username和password 如果sql脚本执行的数据库用户名和密码不相同,需要设置单独的属性 spring: datasource: ... schema: classpath:scheam.sql initialization-mode: always schema-username: root schema-password: <PASSWORD> data.sql的配置schema的基本相同,只需把schema改为data即可 备注:schema为建表语句,data为数据 <file_sep>/src/main/resources/data.sql INSERT INTO `user` VALUES ('1', '2', '3'); INSERT INTO `user` VALUES ('2', '老王', '老王'); INSERT INTO `user` VALUES ('3', 'gsdf', 'dsggd'); INSERT INTO `user` VALUES ('4', 'gg', 'g');<file_sep>/src/main/resources/application.properties spring.jpa.show-sql = true logging.level.org.springframework.data=DEBUG spring.jpa.hibernate.ddl-auto= spring.datasource.url=jdbc:mysql://localhost:3306/demo spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.datasource.driver-class-name=com.mysql.jdbc.Driver<file_sep>/src/main/resources/schema.sql CREATE TABLE `user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(200) NOT NULL, `address` varchar(1000) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; <file_sep>/src/main/java/com/example/service/impl/UserServiceImpl.java package com.example.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.example.domain.User; import com.example.repository.UserRepository; import com.example.repository.UserJpaRepository; import com.example.service.IUserService; @Service @Transactional public class UserServiceImpl implements IUserService { @Autowired private UserJpaRepository userJpaRepository; @Autowired private UserRepository userRepository; public List<User> findAll() { return userJpaRepository.findAll(); } public List<User> findByName(String name) { List<User> userList1 = userRepository.findByName1(name); List<User> userList2 = userRepository.findByName2(name); List<User> userList3 = userRepository.findByNameAndAddress(name, "3"); System.out.println("userList1:" + userList1); System.out.println("userList2:" + userList2); System.out.println("userList3:" + userList3); return userRepository.findByName(name); } public void saveUser(User book) { userJpaRepository.save(book); } @Cacheable("users") public User findOne(long id) { System.out.println("Cached Pages"); return userJpaRepository.findOne(id); } public void delete(long id) { userJpaRepository.delete(id); } } <file_sep>/src/main/java/com/example/repository/UserJpaRepository.java package com.example.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.example.domain.User; public interface UserJpaRepository extends JpaRepository<User,Long> { }
2767ff6595ec23800c3ec81d1c67947fd8f24d29
[ "Markdown", "Java", "SQL", "INI" ]
7
Java
loopjoin/spring-data-jpa-example
829649d213897aa6606243ce90c63818ecc956e8
bf45ea33ad87d08bd2bb4450f546e16e23c86fda
refs/heads/master
<repo_name>IrinaMos/BuyMeMobile<file_sep>/src/main/java/Constants.java import io.appium.java_client.MobileBy; import org.openqa.selenium.By; public class Constants { // Registration page constants public static String regpage = "הכל"; public static By LOGGEDIN = By.id("il.co.mintapp.buyme:id/tab_title"); public static By REGBTN = By.id("il.co.mintapp.buyme:id/skipButton"); public static By TYPEREG = By.id("il.co.mintapp.buyme:id/googleButton"); public static By ACCOUNT = By.id("com.google.android.gms:id/account_name"); //------------------------------------------------------------------------------------ // Home page constants public static String peletgift = "גיפט קארד למסעדות שף"; public static By CATEGORY = By.id("il.co.mintapp.buyme:id/main_toolbar_title"); public static By MONEY = By.id("il.co.mintapp.buyme:id/priceEditText"); public static By BUYBTN = By.id("il.co.mintapp.buyme:id/purchaseButton"); //------------------------------------------------------------------------------------ // SendANDReceiver page constants public static By RECEIVER = By.id("il.co.mintapp.buyme:id/toEditText"); public static By SENDER = By.id("il.co.mintapp.buyme:id/userFrom"); // public static By EVENT = By.xpath("//android.widget.Button[@text='מהו סוג האירוע? נעזור לכם לכתוב ברכה']"); public static By BLESS = By.id("il.co.mintapp.buyme:id/blessEditText"); public static By SCROLL = By.id("il.co.mintapp.buyme:id/fabAlikeContainer"); public static final By CONTINUEBTN = By.id("il.co.mintapp.buyme:id/goNextButton"); //------------------------------------------------------------------------------------ // SendScreen page constants public static final By CHECKBOX = By.id("il.co.mintapp.buyme:id/giftSendEmail"); // public static final By MAIL = (MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector()." // +"scrollable(true)).scrollIntoView(new UiSelector().resourceId(\"il.co.mintapp.buyme:id/description\"))")); public static final By MAIL = By.xpath("//android.widget.EditText[contains(@resource-id,'description')]"); public static By CONTINUEBTN1 = (MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector()." +"scrollable(true)).scrollIntoView(new UiSelector().resourceId(\"il.co.mintapp.buyme:id/goNextButton\"))")); // public static By CONTINUEBTN1 = By.id("il.co.mintapp.buyme:id/goNextButton"); } <file_sep>/src/main/java/HomeScreen.java import io.appium.java_client.MobileElement; import io.appium.java_client.android.AndroidDriver; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertEquals; public class HomeScreen extends Constants { protected WebDriver driver; //--------Filling data for group gift selection-------------- public static void categoryGift(AndroidDriver<MobileElement> driver) throws InterruptedException { // WebDriverWait wait = new WebDriverWait(driver, 5); // wait.until(ExpectedConditions.invisibilityOfElementLocated(Constants.CATEGORY)); // TouchAction action = new TouchAction((PerformsTouchActions) driver); // PointOption pointtoclick = new PointOption(); // pointtoclick.withCoordinates(0, 1224); // action.press(pointtoclick).perform(); List<MobileElement> areaPoints = driver.findElements(By.className("android.widget.RelativeLayout")); areaPoints.get(0).click(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); } public static void verifyScreenCategoryGift (AndroidDriver<MobileElement> driver) throws InterruptedException { System.out.println(driver.findElement(Constants.CATEGORY).getText()); try{ assertEquals(Constants.peletgift, driver.findElement(Constants.CATEGORY).getText()); System.out.println("correct webpage"); } catch(Throwable pageNavigationError){ System.out.println("Didn't navigate to correct webpage"); } } public static void buisnessGift(AndroidDriver<MobileElement> driver) { List<MobileElement> breakfastElements = driver.findElements(By.id("il.co.mintapp.buyme:id/businessName")); breakfastElements.get(1).click(); } public static void giftBudget(AndroidDriver<MobileElement> driver) { driver.findElement(Constants.MONEY).sendKeys("100"); driver.findElement(Constants.BUYBTN).click(); } } // // driver.findElement(Constants.SEARCHBTN).click(); // try { // Thread.sleep(10000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // public static void verifyGift(WebDriver driver) { // driver.get(expectedUrl); // try{ // Assert.assertEquals(expectedUrl, driver.getCurrentUrl()); // System.out.println("Navigated to correct webpage"); // } // catch(Throwable pageNavigationError){ // System.out.println("Didn't navigate to correct webpage"); // } // }
a0d779d82f337cd271d769cdfb2ecc0a25b0a4a6
[ "Java" ]
2
Java
IrinaMos/BuyMeMobile
9487cf99d50f07e7293d08e1c4163147cb99d113
91b8e6160b53f5c3349c0554dfb25ee320302484
refs/heads/master
<repo_name>tokembe/pentaho-platform-plugin-common-ui<file_sep>/package-res/resources/web/prompting/components/DojoDateTextBoxComponent.js /*! * Copyright 2010 - 2015 Pentaho Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * <h2>The Dojo Date Text Box Component class</h2> * * <p>The DojoDateTextBoxComponent renders a date picker box</p> * * To use the DojoDateTextBoxComponent you should require the appropriate file from common-ui: * * <pre><code> * require([ 'common-ui/promting/components/DojoDateTextBoxComponent' ], * function(DojoDateTextBoxComponent) { * var paramDefn = ...; * var param = ...; * var formatter = createFormatter(paramDefn, param); * var transportFormatter = createDataTransportFormatter(paramDefn, param); * var args = { * type: 'StaticAutocompleteBoxBuilder', * name: 'component_name', * htmlObject: 'dom_element_id', * formatter: formatter, * transportFormatter: transportFormatter, * executeAtStart: true * }; * var dojoDateTextBoxComponent = new DojoDateTextBoxComponent(args); * } * ); * </code></pre> * * where 'args' is an object that contains the parameters necessary for base CDF component and special options: * <ul> * <li>param - {@link Parameter} the parameter info about this widget</li> * <li>paramDefn - {@link ParameterDefinition} the parameter definition used to create the formatter</li> * <li>formatter - {@link formatting} utility to format values</li> * <li>transportFormatter - {@link formatting} utility to format values</li> * </ul> * * @name DojoDateTextBoxComponent * @class * @extends BaseComponent */ define(['cdf/components/BaseComponent', 'dijit/form/DateTextBox', 'dijit/registry', 'cdf/lib/jquery', 'dojo/on'], function (BaseComponent, DateTextBox, registry, $, on) { return BaseComponent.extend({ /** * Clears the widget from the dojo namespace * * @method * @name DojoDateTextBoxComponent#clear */ clear: function () { if (this.dijitId) { if (this.onChangeHandle) { this.onChangeHandle.remove(); } registry.byId(this.dijitId).destroyRecursive(); delete this.dijitId; } }, /** * Renders the Dojo Date Text Box Component * * @method * @name DojoDateTextBoxComponent#update */ update: function () { var myself = this; var parameterValue = this.dashboard.getParameterValue(this.parameter), value = undefined; if(this.transportFormatter) { value = this.transportFormatter.parse(parameterValue); } this.dijitId = this.htmlObject + '_input'; $('#' + this.htmlObject).html($('<input/>').attr('id', this.dijitId)); if(registry.byId(this.dijitId)) { registry.remove(this.dijitId); } var dateFormat = this.dateFormat; var dateTextBox = new DateTextBox({ name: this.name, constraints: { datePattern: dateFormat ? dateFormat : this.param.attributes['data-format'], selector: 'date', formatLength: 'medium' // Used if datePattern is not defined, locale specific } }, this.dijitId); dateTextBox.set('value', value, false); this.onChangeHandle = on(dateTextBox, "change", function () { myself.dashboard.processChange(this.name); }.bind(this)); this._doAutoFocus(); }, /** * Returns the value assigned to the component * * @method * @name DojoDateTextBoxComponent#getValue * * @returns {String} The date picked, parsed using the common-ui formatters */ getValue: function () { var date = registry.byId(this.dijitId).get('value'); if(this.transportFormatter) { return this.transportFormatter.format(date); } return date; } }); }); <file_sep>/package-res/resources/web/test/prompting/builders/GarbageCollectorBuilderSpec.js /*! * Copyright 2010 - 2015 Pentaho Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ define(['common-ui/prompting/builders/GarbageCollectorBuilder'], function(GarbageCollectorBuilder) { describe("GarbageCollectorBuilder", function() { var args = { promptPanel: { generateWidgetGUID: function() { return "12345"}, getParameterName: function() { }, removeDashboardComponents: function() { } }, param: { values: { }, attributes: { } }, components: [] }; var garbageCollectorBuilder; beforeEach(function() { garbageCollectorBuilder = new GarbageCollectorBuilder(); }); it("should throw an error building component with no parameters", function() { expect(garbageCollectorBuilder.build).toThrow(); }); it("should return a GarbageCollectorComponent", function() { var component = garbageCollectorBuilder.build(args); expect(component.name.indexOf('gc') == 0).toBeTruthy(); expect(component.preExecution).toBeDefined(); expect(component.preExecution()).toBeFalsy(); }); }); }); <file_sep>/package-res/resources/web/test/prompting/components/DojoDateTextBoxComponentSpec.js /*! * Copyright 2010 - 2015 Pentaho Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ define([ 'cdf/lib/jquery', 'dijit/registry', 'common-ui/prompting/components/DojoDateTextBoxComponent' ], function($, registry, DojoDateTextBoxComponent) { describe("DojoDateTextBoxComponent", function() { describe("clear", function() { var comp; var dijitElement = jasmine.createSpyObj("dijitElement", [ "destroyRecursive" ]); var changeHandler = jasmine.createSpyObj("changeHandler", [ "remove" ]); beforeEach(function() { spyOn(registry, "byId").and.returnValue(dijitElement); comp = new DojoDateTextBoxComponent(); }); it("should not clear if not exist dijitId", function() { comp.clear(); expect(comp.dijitId).not.toBeDefined(); expect(registry.byId).not.toHaveBeenCalled(); expect(dijitElement.destroyRecursive).not.toHaveBeenCalled(); }); it("should destroy element", function() { var dijitId = "test_id"; comp.dijitId = dijitId; comp.clear(); expect(comp.dijitId).not.toBeDefined(); expect(registry.byId).toHaveBeenCalledWith(dijitId); expect(dijitElement.destroyRecursive).toHaveBeenCalled(); }); it("should destroy element and remove change handler", function() { var dijitId = "test_id"; comp.dijitId = dijitId; comp.onChangeHandle = changeHandler; comp.clear(); expect(comp.dijitId).not.toBeDefined(); expect(changeHandler.remove).toHaveBeenCalled(); expect(registry.byId).toHaveBeenCalledWith(dijitId); expect(dijitElement.destroyRecursive).toHaveBeenCalled(); }); }); describe("update", function() { var testId = "test_id"; var testParam = "test_param"; var testVal = "test_val"; var parsedVal = "parsed_"; var comp; var transportFormatter; var dashboard; beforeEach(function() { dashboard = jasmine.createSpyObj("dashboard", [ "getParameterValue" ]); dashboard.getParameterValue.and.returnValue(testVal); transportFormatter = jasmine.createSpyObj("transportFormatter", [ "parse" ]); transportFormatter.parse.and.callFake(function(val) { return parsedVal + val; }); comp = new DojoDateTextBoxComponent(); comp.htmlObject = testId; comp.parameter = testParam; comp.dashboard = dashboard; comp.transportFormatter = transportFormatter; comp.param = { attributes : { 'data-format' : "dd.MM.yyyy" } }; spyOn($.fn, 'html'); spyOn($.fn, 'attr'); spyOn(comp, "_doAutoFocus"); }); it("should init date text box", function() { comp.update(); expect(dashboard.getParameterValue).toHaveBeenCalledWith(testParam); expect(transportFormatter.parse).toHaveBeenCalledWith(testVal); expect(comp.dijitId).toBe(testId + '_input'); expect($.fn.html).toHaveBeenCalled(); expect($.fn.attr).toHaveBeenCalledWith('id', comp.dijitId); expect(comp.onChangeHandle).toBeDefined(); expect(comp._doAutoFocus).toHaveBeenCalled(); }); }); describe("getValue", function() { it("should return formatted value", function() { var testVal = "test_val"; var testFormattedVal = "formatted_"; var dijitId = "test_id"; var comp = new DojoDateTextBoxComponent(); comp.dijitId = dijitId; var dijitElement = jasmine.createSpyObj("dijitElement", [ "get" ]); dijitElement.get.and.returnValue(testVal); spyOn(registry, "byId").and.returnValue(dijitElement); var transportFormatter = jasmine.createSpyObj("transportFormatter", [ "format" ]); transportFormatter.format.and.callFake(function(val) { return testFormattedVal + val; }); comp.transportFormatter = transportFormatter; var value = comp.getValue(); expect(value).toBe(testFormattedVal + testVal); expect(registry.byId).toHaveBeenCalledWith(dijitId); expect(dijitElement.get).toHaveBeenCalledWith('value'); expect(transportFormatter.format).toHaveBeenCalledWith(testVal); }); }); }); }); <file_sep>/package-res/resources/web/prompting/builders/GarbageCollectorBuilder.js /*! * Copyright 2010 - 2015 Pentaho Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ define(['cdf/Logger', 'cdf/lib/Base', '../components/GarbageCollectorComponent'], function (Logger, Base, GarbageCollectorComponent) { return Base.extend({ build: function (args) { return new GarbageCollectorComponent({ name: 'gc' + args.promptPanel.generateWidgetGUID(), preExecution: function () { // Clear the components in reverse since we have an exploded list of components. // Clearing them in order would empty the parent container thus removing all // elements from the dom before each individual component has a chance to clean up // after themselves. $.each(args.components.reverse(), function (i, c) { try { c.clear(); } catch (e) { Logger.log("Error clearing " + c.name + ":", 'error'); Logger.log(e, 'exception'); } }); // setTimeout allows for execution to be broken out from the current setTimeout(function () { // Remove myself from Dashboards.components when we're done updating args.promptPanel.removeDashboardComponents([this]); }.bind(this)); return false; // Don't try to update, we're done } }); } }) });
cf80e2405e442e3f9b2b29ca3859fe080710cccd
[ "JavaScript" ]
4
JavaScript
tokembe/pentaho-platform-plugin-common-ui
5b7d8af009f18d12f2c5d4753c3b32ae49ccfa67
03367c1997dbaf2f947479e67d6c6c0f94a6dd99
refs/heads/master
<repo_name>noa18-meet/meet201617YL1cs-mod3<file_sep>/TestUserAccount.py #This script performs some simple tests on the UserAccount class. from UserAccount import UserAccount #Two things are missing from the line below - fill them in my_username="noa" my_password="123" my_secret="my secret is" my_user=UserAccount(my_username, my_password, my_secret) #Call the print_secret method (function) - it takes one input - a guess for the password. my_user.print_secret("126") my_user.print_secret("123") #Use the wrong password as input here #my_user.noa124 #Use the right password here #my_user.<PASSWORD>
89e429922fcff6320810cda8637fffa297d136ab
[ "Python" ]
1
Python
noa18-meet/meet201617YL1cs-mod3
0a8f1637357d02ffd9618f9cbb9da1cbdde6ee4f
6c7751c1b1717a2409b253ea77ef4513665ba02b
refs/heads/master
<repo_name>eleazarfunk/68KB<file_sep>/upload/includes/application/controllers/admin/utility.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Admin Utility Controller * * Handles utilities * * @package 68kb * @subpackage Admin_Controllers * @category Admin_Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/settings.html * @version $Id: utility.php 134 2009-12-02 01:29:40Z suzkaw68 $ */ class utility extends controller { /** * Constructor * * @access public */ function __construct() { parent::__construct(); $this->load->model('init_model'); $this->load->helper('cookie'); $this->load->library('auth'); $this->auth->restrict(); $this->load->dbutil(); } // ------------------------------------------------------------------------ /** * Show utility list * * @access public */ function index() { $data['nav'] = 'settings'; if ( ! $this->auth->check_level(1)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $this->init_model->display_template('settings/utilities', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Repair DB * * @access public */ function repair() { $data['nav'] = 'settings'; $tables = $this->db->list_tables(); foreach ($tables as $table) { if ($this->dbutil->repair_table($table)) { $tb[]=$table; } } $data['table']=$tb; $this->init_model->display_template('settings/utilities', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Optimize the db * * @access public */ function optimize() { $data['nav'] = 'settings'; $tables = $this->db->list_tables(); foreach ($tables as $table) { if ($this->dbutil->optimize_table($table)) { $tb[]=$table; } } $data['optimized']=$tb; $this->init_model->display_template('settings/utilities', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Remove cache files * * @access public */ function delete_cache() { $this->load->helper('file'); delete_files($this->config->item('cache_path')); $this->session->set_flashdata('message', lang('kb_cache_deleted')); redirect('admin/utility/'); } // ------------------------------------------------------------------------ /** * Backup the databse * * @access public */ function backup() { // Backup your entire database and assign it to a variable $backup =& $this->dbutil->backup(); $name = '68kb-'.time().'.gz'; // Load the file helper and write the file to your server $this->load->helper('file'); write_file(KBPATH .'uploads/'.$name, $backup); // Load the download helper and send the file to your desktop $this->load->helper('download'); force_download($name, $backup); } // ------------------------------------------------------------------------ /** * Export to html * * @access public */ function export() { $this->load->helper('file'); $this->load->model('category_model'); $this->load->model('article_model'); $dir = KBPATH.'uploads/user_guide/'; $log[] = 'Deleting Files...'; if (is_dir($dir)) { delete_files($dir, TRUE); rmdir($dir); } mkdir($dir, 0755); //copy jquery stuff $src = KBPATH.'themes/admin/export/jquery-treeview'; $dst = KBPATH.'uploads/user_guide/jquery-treeview'; $this->recurse_copy($src, $dst); $src = KBPATH.'themes/admin/export/css'; $dst = KBPATH.'uploads/user_guide/css'; $this->recurse_copy($src, $dst); $log[] = 'Copying Files...'; //create cat tree $this->db->select('cat_id,cat_uri,cat_name,cat_parent')->from('categories')->where('cat_display !=', 'N')->order_by('cat_order DESC, cat_name ASC'); $query = $this->db->get(); if ($query->num_rows() > 0) { //$items = $query->result_array(); foreach ($query->result_array() as $row) { $categories[$row['cat_id']] = array( 'cat_id' => $row['cat_id'], 'cat_name' => $row['cat_name'], 'cat_parent' => $row['cat_parent'], 'cat_uri' => $row['cat_uri'] ); } } $log[] = 'Generating Tree...'; ob_start(); $this->generate_tree_list($categories, 0, 0); $r = ob_get_contents(); ob_end_clean(); $data['navigation'] = $r; $log[] = 'Writing Files...'; $data['settings'] = $this->init_model->get_settings(); $article_query = $this->article_model->get_articles(); if ($article_query->num_rows() > 0) { foreach($article_query->result() as $rs) { $data['title'] = $rs->article_title; $data['description'] = $rs->article_description; $contents = $this->load->view('admin/export/layout', $data, true); $filename = $dir.$rs->article_uri.'.html'; //echo $filename.'<BR>'; write_file($filename, $contents, 'x+'); } } $log[] = 'Finishing...'; $log[] = '<a href="'.base_url().'uploads/user_guide/">Preview</a>'; $data['nav']='settings'; $data['export']=$log; $this->init_model->display_template('settings/utilities', $data, 'admin'); } function generate_tree_list($array, $parent = 0, $level = 0) { // Reset the flag each time the function is called $has_children = false; // Loop through each item of the list array foreach($array as $key => $value) { // For the first run, get the first item with a parent_id of 0 (= root category) // (or whatever id is passed to the function) // // For every subsequent run, look for items with a parent_id matching the current item's key (id) // (eg. get all items with a parent_id of 2) // // This will return false (stop) when it find no more matching items/children // // If this array item's parent_id value is the same as that passed to the function // eg. [parent_id] => 0 == $parent = 0 (true) // eg. [parent_id] => 20 == $parent = 0 (false) // if ($value['cat_parent'] == $parent) { // Only print the wrapper ('<ul>') if this is the first child (otherwise just print the item) // Will be false each time the function is called again if ($has_children === false) { // Switch the flag, start the list wrapper, increase the level count $has_children = true; if($level==0) { echo '<ul id="browser" class="filetree"> '; } else { echo "\n".'<ul>'; } $level++; } // Print the list item echo "\n".'<li><span class="folder">' . $value['cat_name'] . '</span>'; echo $this->get_articles($value['cat_id'], $value['cat_uri']); // Repeat function, using the current item's key (id) as the parent_id argument // Gives us a nested list of subcategories $this->generate_tree_list($array, $key, $level); // Close the item echo "</li>\n"; } } // If we opened the wrapper above, close it. if ($has_children === true) echo '</ul>'."\n"; } function get_articles($id, $cat_uri = '') { $this->db->from('articles'); $this->db->join('article2cat', 'articles.article_id = article2cat.article_id', 'left'); $this->db->where('category_id', $id); $this->db->where('article_display', 'Y'); $query = $this->db->get(); $output = '<ul>'; if ($query->num_rows() > 0) { foreach($query->result() as $rs) { $title = $rs->article_title; $uri = $rs->article_uri; $output .= '<li><span class="file"><a href="./'.$uri.'.html">'.$title.'</a></span></li>'; } } else { //$output.='<li></li>'; } $output.='</ul>'; return $output; } function recurse_copy($src,$dst) { $dir = opendir($src); @mkdir($dst); while(false !== ( $file = readdir($dir)) ) { if (( $file != '.' ) && ( $file != '..' )) { if ( is_dir($src . '/' . $file) ) { $this->recurse_copy($src . '/' . $file,$dst . '/' . $file); } else { copy($src . '/' . $file,$dst . '/' . $file); } } } closedir($dir); } } /* End of file utility.php */ /* Location: ./upload/includes/application/controllers/admin/utility.php */ <file_sep>/upload/themes/admin/default/comments/grid.php <script language="javascript" type="text/javascript"> <!-- function deleteSomething(url){ removemsg = "<?php echo lang('kb_are_you_sure'); ?>" if (confirm(removemsg)) { document.location = url; } } // --> </script> <h2><?php echo $this->lang->line('kb_comments'); ?></h2> <div class="wrap"> <?php $attributes = array('id' => 'search'); echo form_open($this->uri->uri_string(), $attributes); ?> <fieldset><legend><?php echo $this->lang->line('kb_search_comments'); ?></legend> <?php echo $this->lang->line('kb_search_text'); ?>: <input type="text" name="searchtext" id="searchtext" value="<?php echo (isset($q)) ? form_prep($q) : ''; ?>" size="17" /> &nbsp; <?php echo $this->lang->line('kb_status'); ?>: <select name='comment_approved'> <option value=''><?php echo $this->lang->line('kb_all'); ?></option> <option value='1'<?php echo (isset($s_display) && $s_display=='1') ? ' selected="selected"' : ''; ?>><?php echo $this->lang->line('kb_active'); ?></option> <option value='0'<?php echo (isset($s_display) && $s_display=='0') ? ' selected="selected"' : ''; ?>><?php echo $this->lang->line('kb_notactive'); ?></option> <option value='spam'<?php echo (isset($s_display) && $s_display=='spam') ? ' selected="selected"' : ''; ?>><?php echo $this->lang->line('kb_spam'); ?></option> </select> &nbsp; <input type="submit" id="submit" value="<?php echo $this->lang->line('kb_search'); ?> &#187;" class="button" /> </fieldset> <?php echo form_close(); ?> <div class="clear"></div> <?php $attributes = array('id' => 'comments', 'name' => 'comments'); echo form_open('admin/comments/update', $attributes); ?> <input type="hidden" name="act" value="xxxxx" /> <table class="main" width="100%" cellpadding="3" cellspacing="1"> <tr> <th scope="col" width="5%"><input type="checkbox" name="checkbox" id="checkbox" value="checkbox" /></th> <th> <?php $class=''; if(isset($orderby) && isset($opp) && $orderby=="comment_author") { $class = $opp; } ?> <?php if(isset($sort) && $sort == 'desc'): ?> <a href="<?php echo site_url('admin/comments/grid/orderby/comment_author/asc'); ?>" class="<?php echo $class; ?>"> <?php else: ?> <a href="<?php echo site_url('admin/comments/grid/orderby/comment_author/desc'); ?>" class="<?php echo $class; ?>"> <?php endif; ?> <?php echo $this->lang->line('kb_name'); ?> </a> </th> <th> Content </th> <th> <?php $class=''; if(isset($orderby) && isset($opp) && $orderby=="article_title") { $class = $opp; } ?> <?php if(isset($sort) && $sort == 'desc'): ?> <a href="<?php echo site_url('admin/comments/grid/orderby/article_title/asc'); ?>" class="<?php echo $class; ?>"> <?php else: ?> <a href="<?php echo site_url('admin/comments/grid/orderby/article_title/desc'); ?>" class="<?php echo $class; ?>"> <?php endif; ?> <?php echo $this->lang->line('kb_article'); ?> </a> </th> <th><?php echo $this->lang->line('kb_actions'); ?></th> </tr> <?php $alt = true; foreach($items as $item): ?> <tr<?php if ($alt) echo ' class="second"'; else echo ' class="first"'; $alt = !$alt; ?>> <td width="5%"><input type="checkbox" name="commentid[]" value="<?php echo $item['comment_ID']; ?>" class="toggable" /></td> <td valign="top"> <div class="gravatar"><img class="gravatar2" src="<?php echo gravatar( $item['comment_author_email'], "PG", "24", "wavatar" ); ?>" /></div> <strong> <?php echo $item['comment_author']; ?> </strong><br /> <?php echo $item['comment_author_email']; ?><br /> <?php echo $item['comment_author_IP']; ?> </td> <td width="50%" valign="top"> <div class="submitted"><?php echo lang('kb_date_added') .' '. date($this->config->item('comment_date_format'), $item['comment_date']); ?></div><br /> <?php echo word_limiter($item['comment_content'], 15); ?><br /> <a href="<?php echo site_url('admin/comments/edit/'.$item['comment_ID']); ?>"><?php echo $this->lang->line('kb_edit'); ?></a> &nbsp;|&nbsp; <a href="javascript:void(0);" onclick="return deleteSomething('<?php echo site_url('admin/comments/delete/'.$item['comment_ID']); ?>');"><?php echo $this->lang->line('kb_delete'); ?></a> </td> <td valign="top"> <a href="<?php echo site_url('article/'.$item['article_uri']); ?>/#comment-<?php echo $item['comment_ID']; ?>"><?php echo $item['article_title']; ?></a> </td> <td> <?php if($item['comment_approved'] == 'spam') { echo '<span class="spam">'.$this->lang->line('kb_spam').'</span>'; } elseif($item['comment_approved'] == 0) { echo '<span class="inactive">'.$this->lang->line('kb_notactive').'</span>'; } else { echo '<span class="active">'.$this->lang->line('kb_active').'</span>'; } ?> </td> </tr> <?php endforeach; ?> </table> <table width="100%" border="0" cellspacing="0" cellpadding="3"> <tr> <td> <select name="newstatus"> <option value="" selected><?php echo lang('kb_change_status'); ?></option> <option value="1"><?php echo $this->lang->line('kb_active'); ?></option> <option value="0"><?php echo $this->lang->line('kb_notactive'); ?></option> <option value="spam"><?php echo $this->lang->line('kb_spam'); ?></option> <option value="5"><?php echo $this->lang->line('kb_delete'); ?></option> </select> <input type="submit" value="Update" onclick="document.comments.act.value='changestatus';" /> </td> <td align="right"> <div class="paginationNum"> <?php echo $this->lang->line('kb_pages'); ?>: <?php echo $pagination; ?> </div> </td> </tr> </table> <table width="30%" align="center"> <tr> <td align="right"><img src="<?php echo base_url(); ?>images/page_show.png" border="0" alt="<?php echo $this->lang->line('kb_show'); ?>" /></td> <td align="left"><?php echo $this->lang->line('kb_show'); ?></td> <td align="right"><img src="<?php echo base_url(); ?>images/page_edit.png" border="0" alt="<?php echo $this->lang->line('kb_edit'); ?>" /></td> <td align="left"><?php echo $this->lang->line('kb_edit'); ?></td> <td align="right"><img src="<?php echo base_url(); ?>images/page_delete.png" border="0" alt="<?php echo $this->lang->line('kb_delete'); ?>" /></td> <td align="left"><?php echo $this->lang->line('kb_delete'); ?></td> </tr> </table> </div><file_sep>/upload/includes/application/models/setup/install_model.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Install Model * * This class is used for installing your db. * * @package 68kb * @subpackage Models * @category Models * @author 68kb Dev Team * @link http://68kb.com/ * @version $Id: install_model.php 141 2009-12-04 13:16:36Z suzkaw68 $ */ class Install_model extends Model { function __construct() { parent::Model(); $this->obj =& get_instance(); $this->load->dbforge(); } // ------------------------------------------------------------------------ /** * Install Tables * * Loops through this class methods that begines with "table_" and runs them. * */ function install($username='demo', $password='<PASSWORD>', $email='<EMAIL>', $drop=FALSE) { $sample_data = TRUE; // make email global for use in settings define('KB_EMAIL', $email); $msg = ''; $class_methods = get_class_methods($this); foreach ($class_methods as $method_name) { if(substr($method_name, 0, 6) == 'table_') { if($method_name=='table_users') { $msg[] = $this->$method_name($username, $password, $email, $drop); } else { $msg[] = $this->$method_name($drop); } } } if($sample_data == TRUE) { $this->default_data(); } return $msg; } // ------------------------------------------------------------------------ /** * Install Articles Table */ function table_articlestocat($drop) { if($drop) { $this->dbforge->drop_table('article2cat'); } $this->dbforge->add_field("article_id int(20) default NULL"); $this->dbforge->add_field("category_id int(20) default NULL"); $this->dbforge->add_key('article_id', TRUE); $this->dbforge->add_key('category_id', TRUE); if($this->dbforge->create_table('article2cat')) { return 'article2cat table installed...<br />'; } } // ------------------------------------------------------------------------ /** * Install Articles Table */ function table_articles($drop) { if($drop) { $this->dbforge->drop_table('articles'); } $fields = array( 'article_id' => array('type' => 'INT','constraint' => 11,'unsigned' => TRUE,'auto_increment' => TRUE), ); $this->dbforge->add_field($fields); $this->dbforge->add_field("article_uri varchar(55) NOT NULL default '0'"); $this->dbforge->add_field("article_title varchar(255) NOT NULL default ''"); $this->dbforge->add_field("article_keywords varchar(255) NOT NULL default ''"); $this->dbforge->add_field("article_description text NOT NULL"); $this->dbforge->add_field("article_short_desc text NOT NULL"); $this->dbforge->add_field("article_date int(11) NOT NULL default '0'"); $this->dbforge->add_field("article_modified int(11) NOT NULL default '0'"); $this->dbforge->add_field("article_display char(1) NOT NULL default 'N'"); $this->dbforge->add_field("article_hits int(11) NOT NULL default '0'"); $this->dbforge->add_field("article_author int(11) NOT NULL default '0'"); $this->dbforge->add_field("article_order int(11) NOT NULL default '0'"); $this->dbforge->add_field("article_rating int(11) NOT NULL default '0'"); $this->dbforge->add_key('article_id', TRUE); $this->dbforge->add_key('article_uri', TRUE); $this->dbforge->add_key('article_title', TRUE); if($this->dbforge->create_table('articles')) { return 'articles table installed...<br />'; } } // ------------------------------------------------------------------------ /** * Install Articles Tags Table */ function table_article_tags($drop) { if($drop) { $this->dbforge->drop_table('article_tags'); } $this->dbforge->add_field("tags_tag_id int(11) NOT NULL default '0'"); $this->dbforge->add_field("tags_article_id int(11) NOT NULL default '0'"); $this->dbforge->add_key('tags_tag_id', TRUE); if($this->dbforge->create_table('article_tags')) { return 'article_tags table installed...<br />'; } } // ------------------------------------------------------------------------ /** * Install Attachments Table */ function table_attachments($drop) { if($drop) { $this->dbforge->drop_table('attachments'); } $fields = array( 'attach_id' => array('type' => 'INT','constraint' => 11,'unsigned' => TRUE,'auto_increment' => TRUE), ); $this->dbforge->add_field($fields); $this->dbforge->add_field("article_id int(11) NOT NULL default '0'"); $this->dbforge->add_field("attach_name varchar(55) NOT NULL default ''"); $this->dbforge->add_field("attach_type varchar(55) NOT NULL default ''"); $this->dbforge->add_field("attach_size varchar(55) NOT NULL default ''"); $this->dbforge->add_key('attach_id', TRUE); if($this->dbforge->create_table('attachments')) { return 'attachments table installed...<br />'; } } // ------------------------------------------------------------------------ /** * Install Captcha Table */ function table_captcha($drop) { if($drop) { $this->dbforge->drop_table('captcha'); } $fields = array( 'captcha_id' => array('type' => 'INT','constraint' => 11,'unsigned' => TRUE,'auto_increment' => TRUE), ); $this->dbforge->add_field($fields); $this->dbforge->add_field("captcha_time int(10) NOT NULL default '0'"); $this->dbforge->add_field("ip_address varchar(16) NOT NULL default '0'"); $this->dbforge->add_field("word varchar(20) NOT NULL default ''"); $this->dbforge->add_field("a_size varchar(255) NOT NULL default ''"); $this->dbforge->add_key('captcha_id', TRUE); $this->dbforge->add_key('word'); if($this->dbforge->create_table('captcha')) { return 'captcha table installed...<br />'; } } // ------------------------------------------------------------------------ /** * Install Categories */ function table_categories($drop) { if($drop) { $this->dbforge->drop_table('categories'); } $fields = array( 'cat_id' => array('type' => 'INT','constraint' => 11,'unsigned' => TRUE,'auto_increment' => TRUE), ); $this->dbforge->add_field($fields); $this->dbforge->add_field("cat_parent int(11) NOT NULL default '0'"); $this->dbforge->add_field("cat_uri varchar(55) NOT NULL default '0'"); $this->dbforge->add_field("cat_name varchar(255) NOT NULL default ''"); $this->dbforge->add_field("cat_description text NOT NULL"); $this->dbforge->add_field("cat_display char(1) NOT NULL DEFAULT 'N'"); $this->dbforge->add_field("cat_order int(11) NOT NULL default '0'"); $this->dbforge->add_key('cat_id', TRUE); $this->dbforge->add_key('cat_uri', TRUE); $this->dbforge->add_key('cat_name'); $this->dbforge->add_key('cat_parent'); $this->dbforge->add_key('cat_order'); if($this->dbforge->create_table('categories')) { return 'categories table installed...<br />'; } } // ------------------------------------------------------------------------ /** * Install Comments Table */ function table_comments($drop) { if($drop) { $this->dbforge->drop_table('comments'); } $fields = array( 'comment_ID' => array('type' => 'INT','constraint' => 11,'unsigned' => TRUE,'auto_increment' => TRUE), ); $this->dbforge->add_field($fields); $this->dbforge->add_field("comment_article_ID int(11) NOT NULL default '0'"); $this->dbforge->add_field("comment_author varchar(55) NOT NULL default ''"); $this->dbforge->add_field("comment_author_email varchar(55) NOT NULL default ''"); $this->dbforge->add_field("comment_author_IP varchar(16) NOT NULL default ''"); $this->dbforge->add_field("comment_date int(16) NOT NULL default '0'"); $this->dbforge->add_field("comment_content text NOT NULL"); $this->dbforge->add_field("comment_approved enum('0','1','spam') NOT NULL default '1'"); $this->dbforge->add_key('comment_ID', TRUE); $this->dbforge->add_key('comment_article_ID'); if($this->dbforge->create_table('comments')) { return 'comments table installed...<br />'; } } // ------------------------------------------------------------------------ /** * Install Glossary Table */ function table_glossary($drop) { if($drop) { $this->dbforge->drop_table('glossary'); } $fields = array( 'g_id' => array('type' => 'INT','constraint' => 11,'unsigned' => TRUE,'auto_increment' => TRUE), ); $this->dbforge->add_field($fields); $this->dbforge->add_field("g_term varchar(55) NOT NULL default ''"); $this->dbforge->add_field("g_definition text NOT NULL"); $this->dbforge->add_key('g_id', TRUE); $this->dbforge->add_key('g_term'); if($this->dbforge->create_table('glossary')) { return 'glossary table installed...<br />'; } } // ------------------------------------------------------------------------ /** * Install Modules Table */ function table_modules($drop) { if($drop) { $this->dbforge->drop_table('modules'); } $fields = array( 'id' => array('type' => 'INT','constraint' => 11,'unsigned' => TRUE,'auto_increment' => TRUE), ); $this->dbforge->add_field($fields); $this->dbforge->add_field("name varchar(255) NOT NULL default ''"); $this->dbforge->add_field("displayname varchar(255) NOT NULL default ''"); $this->dbforge->add_field("description varchar(255) NOT NULL default ''"); $this->dbforge->add_field("directory varchar(255) NOT NULL default ''"); $this->dbforge->add_field("version varchar(10) NOT NULL default ''"); $this->dbforge->add_field("active tinyint(1) NOT NULL default '0'"); $this->dbforge->add_key('id', TRUE); $this->dbforge->add_key('name', TRUE); $this->dbforge->add_key('displayname'); $this->dbforge->add_key('active'); if($this->dbforge->create_table('modules')) { return 'modules table installed...<br />'; } } // ------------------------------------------------------------------------ /** * Install Search Log Table */ function table_searchlog($drop) { if($drop) { $this->dbforge->drop_table('searchlog'); } $fields = array( 'searchlog_id' => array('type' => 'INT','constraint' => 11,'unsigned' => TRUE,'auto_increment' => TRUE), ); $this->dbforge->add_field($fields); $this->dbforge->add_field("searchlog_term varchar(55) NOT NULL default ''"); $this->dbforge->add_key('searchlog_id', TRUE); $this->dbforge->add_key('searchlog_term'); if($this->dbforge->create_table('searchlog')) { return 'searchlog table installed...<br />'; } } // ------------------------------------------------------------------------ /** * Install Sessions Table */ function table_sessions($drop) { if($drop) { $this->dbforge->drop_table('sessions'); } $fields = array( 'session_id' => array('type' => 'INT','constraint' => 11,'unsigned' => TRUE,'auto_increment' => TRUE), ); $this->dbforge->add_field($fields); $this->dbforge->add_field("ip_address varchar(16) NOT NULL default '0'"); $this->dbforge->add_field("user_agent varchar(50) NOT NULL default ''"); $this->dbforge->add_field("last_activity int(10) NOT NULL default '0'"); $this->dbforge->add_key('session_id', TRUE); if($this->dbforge->create_table('sessions')) { return 'sessions table installed...<br />'; } } // ------------------------------------------------------------------------ /** * Install Settings table */ function table_settings($drop) { if($drop) { $this->dbforge->drop_table('settings'); } $fields = array( 'option_id' => array( 'type' => 'INT', 'constraint' => 11, 'unsigned' => TRUE, 'auto_increment' => TRUE ), 'short_name' => array( 'type' => 'VARCHAR', 'constraint' => '55' ), 'name' => array( 'type' => 'VARCHAR', 'constraint' => '255' ), 'value' => array( 'type' => 'VARCHAR', 'constraint' => '255' ), 'auto_load' => array( 'type' => 'VARCHAR', 'constraint' => '16' ) ); $this->dbforge->add_field($fields); $this->dbforge->add_key('option_id', TRUE); $this->dbforge->add_key('short_name', TRUE); $this->dbforge->add_key('value'); $this->dbforge->add_key('auto_load'); $this->dbforge->create_table('settings'); $data = array('short_name' => 'site_name','name' => "Site Title",'value' => 'Your Site','auto_load' => 'yes'); $this->db->insert('settings', $data); $data = array('short_name' => 'site_email','name' => "Site Email",'value' => KB_EMAIL,'auto_load' => 'yes'); $this->db->insert('settings', $data); $data = array('short_name' => 'version','name' => "Script Version",'value' => KB_VERSION,'auto_load' => 'yes'); $this->db->insert('settings', $data); $data = array('short_name' => 'last_cron','name' => "Last Cron",'value' => "",'auto_load' => 'yes'); $this->db->insert('settings', $data); $data = array('short_name' => 'template','name' => "Template",'value' => 'emporium','auto_load' => 'yes'); $this->db->insert('settings', $data); $data = array('short_name' => 'admin_template','name' => "Admin Template",'value' => 'default','auto_load' => 'yes'); $this->db->insert('settings', $data); $data = array('short_name' => 'max_search','name' => "Per Page",'value' => '5','auto_load' => 'yes'); $this->db->insert('settings', $data); $data = array('short_name' => 'cache_time','name' => "Cache Time",'value' => '0','auto_load' => 'yes'); $this->db->insert('settings', $data); $data = array('short_name' => 'comments','name' => "Allow Comments",'value' => 'Y','auto_load' => 'yes'); $this->db->insert('settings', $data); $data = array('short_name' => 'latest','name' => "Latest 68KB Release",'value' => '0','auto_load' => 'no'); $this->db->insert('settings', $data); $data = array('short_name' => 'site_keywords','name' => "Site Keywords",'value' => 'keywords, go, here','auto_load' => 'yes'); $this->db->insert('settings', $data); $data = array('short_name' => 'site_description','name' => "Site Description",'value' => 'Site Description','auto_load' => 'yes'); $this->db->insert('settings', $data); return 'settings table installed...<br />'; } // ------------------------------------------------------------------------ /** * Install Tags Table */ function table_tags($drop) { if($drop) { $this->dbforge->drop_table('tags'); } $fields = array( 'id' => array('type' => 'INT','constraint' => 11,'unsigned' => TRUE,'auto_increment' => TRUE), ); $this->dbforge->add_field($fields); $this->dbforge->add_field("tag varchar(30) NOT NULL default '0'"); $this->dbforge->add_key('id', TRUE); if($this->dbforge->create_table('tags')) { return 'tags table installed...<br />'; } } // ------------------------------------------------------------------------ /** * Install Users Table */ function table_users($username, $password, $email, $drop) { if($drop) { $this->dbforge->drop_table('users'); } $fields = array( 'id' => array('type' => 'INT','constraint' => 11,'unsigned' => TRUE,'auto_increment' => TRUE), ); $this->dbforge->add_field($fields); $this->dbforge->add_field("custip varchar(16) NOT NULL default '0'"); $this->dbforge->add_field("firstname varchar(50) NOT NULL default ''"); $this->dbforge->add_field("lastname varchar(50) NOT NULL default ''"); $this->dbforge->add_field("email varchar(50) NOT NULL default ''"); $this->dbforge->add_field("username varchar(50) NOT NULL default ''"); $this->dbforge->add_field("password varchar(50) NOT NULL default ''"); $this->dbforge->add_field("joindate int(11) NOT NULL default '0'"); $this->dbforge->add_field("lastlogin int(11) NOT NULL default '0'"); $this->dbforge->add_field("cookie varchar(50) NOT NULL default ''"); $this->dbforge->add_field("session varchar(50) NOT NULL default ''"); $this->dbforge->add_field("level int(5) NOT NULL default '5'"); $this->dbforge->add_key('id', TRUE); if($this->dbforge->create_table('users')) { $data = array( 'firstname' => 'admin', 'lastname' => 'acount', 'email' => $email, 'username' => $username, 'password' => md5(<PASSWORD>), 'joindate' => time(), 'level' => 1 ); $this->db->insert('users', $data); return 'users table installed...<br />'; } } // ------------------------------------------------------------------------ function default_data() { $data = array( 'name' => 'jwysiwyg', 'displayname' => 'WYSIWYG jQuery Plugin', 'description' => 'This module is an inline content editor to allow editing rich HTML content on the fly.', 'directory' => 'jwysiwyg', 'version' => 'v1.0', 'active' => '1' ); $this->db->insert('modules', $data); $data = array( 'article_author' => 1, 'article_title' => "Welcome to 68kb", 'article_uri' => "welcome", 'article_keywords' => 'cat', 'article_short_desc' => 'Short Description', 'article_description' => 'Welcome to 68kb!<div><br></div><div>Thank you for downloading and installing 68kb. I know as with any script it probably does things differently than others and at this time we would like to highlight some of the available resources available to you.&nbsp;</div><div><br></div><div>1.&nbsp;<a href="http://68kb.com/knowledge-base/">Knowledge Base</a>&nbsp;- Our knowledge base includes information about using and working with the script.&nbsp;</div><div>2. <a href="http://68kb.com/support/">Support Forums</a> - We have community support forums where you can get help, advice, or talk with other 68kb users.&nbsp;</div><div>3. <a href="http://68kb.com/blog/">68kb Blog</a> - Our blog covers new releases and other tips and tricks to get you comfortable with 68kb.&nbsp;</div><div><br></div><div>Thanks again!</div>', 'article_display' => 'Y', 'article_date' => time(), 'article_modified ' => time() ); $this->db->insert('articles', $data); $data = array( 'article_id' => 1, 'category_id' => 1, ); $this->db->insert('article2cat', $data); $data = array( 'cat_parent' => 0, 'cat_name' => "Example Category", 'cat_uri' => "example", 'cat_description' => 'This is an example category.', 'cat_display' => 'Y' ); $this->db->insert('categories', $data); $data = array( 'g_term' => "68kb", 'g_definition' => '68kb is a php knowledge base script. This is an example of the glossary function.' ); $this->db->insert('glossary', $data); } } /* End of file db_model.php */ /* Location: ./upload/includes/application/models/db_model.php */<file_sep>/upload/includes/config.default.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Database |-------------------------------------------------------------------------- | | This is your database settings. If you are unsure of these please ask | your webhosting provider. | */ $db['default']['hostname'] = "localhost"; // Database Hostname $db['default']['username'] = ""; // Database Username $db['default']['password'] = ""; // Database Password $db['default']['database'] = ""; // Database Name $db['default']['dbprefix'] = "kb_"; // Database Prefix /* |-------------------------------------------------------------------------- | More Database Settings |-------------------------------------------------------------------------- | | You can edit the ones below but generally should be left the same. | */ $db['default']['dbdriver'] = "mysql"; $db['default']['pconnect'] = TRUE; $db['default']['db_debug'] = TRUE; $db['default']['cache_on'] = FALSE; $db['default']['cachedir'] = APPPATH .'cache/'; $db['default']['char_set'] = "utf8"; $db['default']['dbcollat'] = "utf8_general_ci"; /* |-------------------------------------------------------------------------- | Base Site URL |-------------------------------------------------------------------------- | | URL to your 68 Licensing root. Typically this will be your base URL, | WITH a trailing slash: | | http://example.com/ | | We have tried to auto guess this by using this hack: | http://codeigniter.com/forums/viewthread/60181/ */ //$config['base_url'] = "http://localhost/"; $config['base_url'] = "http://".$_SERVER['HTTP_HOST']; $config['base_url'] .= preg_replace('@/+$@','',dirname($_SERVER['SCRIPT_NAME'])).'/'; /* |-------------------------------------------------------------------------- | Index File |-------------------------------------------------------------------------- | | Typically this will be your index.php file, unless you've renamed it to | something else. If you are using mod_rewrite to remove the page set this | variable so that it is blank. | | http://68kb.com/user_guide/developer/urls.html | */ $config['index_page'] = "index.php"; /* |-------------------------------------------------------------------------- | URI PROTOCOL |-------------------------------------------------------------------------- | | This item determines which server global should be used to retrieve the | URI string. The default setting of "AUTO" works for most servers. | If your links do not seem to work, try one of the other delicious flavors: | | 'AUTO' Default - auto detects | 'PATH_INFO' Uses the PATH_INFO | 'QUERY_STRING' Uses the QUERY_STRING | 'REQUEST_URI' Uses the REQUEST_URI | 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO | */ $config['uri_protocol'] = "AUTO"; /* |-------------------------------------------------------------------------- | Enable/Disable System Hooks |-------------------------------------------------------------------------- | | If you would like to use the "hooks" feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = TRUE; /* |-------------------------------------------------------------------------- | Modules |-------------------------------------------------------------------------- | | This allows you to enable/disable modules from the config file | */ $config['modules_on'] = TRUE; /* |-------------------------------------------------------------------------- | URL suffix |-------------------------------------------------------------------------- | | This option allows you to add a suffix to all URLs generated by CodeIgniter. | For more information please see the user guide: | | http://68kb.com/user_guide/developer/urls.html */ $config['url_suffix'] = ""; /* |-------------------------------------------------------------------------- | Default Language |-------------------------------------------------------------------------- | | This determines which set of language files should be used. Make sure | there is an available translation if you intend to use something other | than english. | */ $config['language'] = "english"; /* |-------------------------------------------------------------------------- | Default Attachments |-------------------------------------------------------------------------- | | This determines the file types you are allowed to upload through the | administration. */ $config['attachment_types'] = "pdf|txt|zip|gif|jpg|png"; /* |-------------------------------------------------------------------------- | Date Formatting |-------------------------------------------------------------------------- | | This is the default date formating. Check http://php.net/date | | date_format - Is the default | comment_date_format - Is for comments | article_date_format - Is for the articles. | */ $config['date_format'] = 'Y-m-d H:i:s'; $config['comment_date_format'] = 'F j, Y h:i a'; $config['article_date_format'] = 'F j, Y'; /* |-------------------------------------------------------------------------- | Default Character Set |-------------------------------------------------------------------------- | | This determines which character set is used by default in various methods | that require a character set to be provided. | */ $config['charset'] = "UTF-8"; /* |-------------------------------------------------------------------------- | Error Logging Threshold |-------------------------------------------------------------------------- | | If you have enabled error logging, you can set an error threshold to | determine what gets logged. Threshold options are: | You can enable error logging by setting a threshold over zero. The | threshold determines what gets logged. Threshold options are: | | 0 = Disables logging, Error logging TURNED OFF | 1 = Error Messages (including PHP errors) | 2 = Debug Messages | 3 = Informational Messages | 4 = All Messages | | For a live site you'll usually only enable Errors (1) to be logged otherwise | your log files will fill up very fast. | */ $config['log_threshold'] = 1; /* |-------------------------------------------------------------------------- | Error Logging Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | system/logs/ folder. Use a full server path with trailing slash. | */ $config['log_path'] = APPPATH .'logs/'; /* |-------------------------------------------------------------------------- | Date Format for Logs |-------------------------------------------------------------------------- | | Each item that is logged has an associated date. You can use PHP date | codes to set your own date formatting | */ $config['log_date_format'] = 'Y-m-d H:i:s'; /* |-------------------------------------------------------------------------- | Cache Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | system/cache/ folder. Use a full server path with trailing slash. | */ $config['cache_path'] = APPPATH .'cache/'; /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | If you use the Encryption class or the Sessions class with encryption | enabled you MUST set an encryption key. | */ $config['encryption_key'] = ""; /* |-------------------------------------------------------------------------- | Output Compression |-------------------------------------------------------------------------- | | Enables Gzip output compression for faster page loads. When enabled, | the output class will test whether your server supports Gzip. | Even if it does, however, not all browsers support compression | so enable only if you are reasonably sure your visitors can handle it. | | VERY IMPORTANT: If you are getting a blank page when compression is enabled it | means you are prematurely outputting something to your browser. It could | even be a line of whitespace at the end of one of your scripts. For | compression to work, nothing can be sent before the output buffer is called | by the output class. Do not "echo" any values with compression enabled. | */ $config['compress_output'] = FALSE; /* |-------------------------------------------------------------------------- | Master Time Reference |-------------------------------------------------------------------------- | | Options are "local" or "gmt". This pref tells the system whether to use | your server's local time as the master "now" reference, or convert it to | GMT. | */ $config['time_reference'] = 'local';<file_sep>/upload/themes/admin/default/layout.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $this->config->item('charset');?>" /> <title>68 KB Administration</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript" src="<?php echo base_url();?>js/tooltip.js"></script> <link href="<?php echo base_url();?>themes/admin/default/style/default.css" rel="stylesheet" type="text/css" /> <meta http-equiv="pragma" content="no-cache" /> <?php $this->core_events->trigger('template/admin/header'); ?> </head> <body> <div id="wrapper"> <div id="header"><p><?php echo lang('kb_loggedin'); ?> <?php echo $this->session->userdata('username'); ?> | <a href="<?php echo site_url('admin/kb/logout');?>"><?php echo lang('kb_logout'); ?></a> | <a href="http://68kb.com/knowledge-base/" target="_blank"><?php echo lang('kb_support_knowledge_base'); ?></a> | <a href="<?php echo site_url();?>" target="_blank"><?php echo lang('kb_view_site'); ?></a></p></div> <div id="topmenu"> <div id="menu"> <?php //echo $this->session->userdata('level');?> <a href="<?php echo site_url('admin');?>" class="<?php echo ($nav=='dashboard') ? 'activeMenuItem' : 'inactiveMenuItem'; ?>" accesskey="D"><?php echo lang('kb_dashboard'); ?></a> <a href="<?php echo site_url('admin/articles');?>" class="<?php echo ($nav=='articles') ? 'activeMenuItem' : 'inactiveMenuItem'; ?>" accesskey="A"><?php echo lang('kb_articles'); ?></a> <?php if ($this->session->userdata('level') <= 3): ?> <a href="<?php echo site_url('admin/categories');?>" class="<?php echo ($nav=='categories') ? 'activeMenuItem' : 'inactiveMenuItem'; ?>" accesskey="C"><?php echo lang('kb_categories'); ?></a> <?php endif; ?> <?php if ($this->session->userdata('level') <= 3): ?> <a href="<?php echo site_url('admin/glossary');?>" class="<?php echo ($nav=='glossary') ? 'activeMenuItem' : 'inactiveMenuItem'; ?>" accesskey="G"><?php echo lang('kb_glossary'); ?></a> <?php endif; ?> <?php if ($this->session->userdata('level') == 1): ?> <a href="<?php echo site_url('admin/users');?>" class="<?php echo ($nav=='users') ? 'activeMenuItem' : 'inactiveMenuItem'; ?>" accesskey="U"><?php echo lang('kb_users'); ?></a> <?php endif; ?> <?php if ($this->session->userdata('level') <= 2): ?> <?php if($settings['comments'] == 'Y'): ?><a href="<?php echo site_url('admin/comments');?>" class="<?php echo ($nav=='comments') ? 'activeMenuItem' : 'inactiveMenuItem'; ?>" accesskey="1"><?php echo lang('kb_comments'); ?></a><?php endif; ?> <?php endif; ?> <?php if ($this->session->userdata('level') == 1): ?> <a href="<?php echo site_url('admin/settings');?>" class="<?php echo ($nav=='settings') ? 'activeMenuItem' : 'inactiveMenuItem'; ?>" accesskey="S"><?php echo lang('kb_settings'); ?></a> <?php endif; ?> </div> </div> <div id="submenu"> <?php if($nav=='dashboard'): ?> <div id="submenu_1"> <a href="<?php echo site_url('admin');?>" accesskey="H"><?php echo lang('kb_dashboard'); ?></a> <a href="http://68kb.com/forums/" accesskey="F" target="_blank"><?php echo lang('kb_forums'); ?></a> <a href="<?php echo site_url('admin/kb/logout');?>"><?php echo lang('kb_logout'); ?></a> </div> <?php endif;?> <?php if($nav=='articles'): ?> <div id="submenu_2"> <a href="<?php echo site_url('admin/articles');?>"><?php echo lang('kb_manage_articles'); ?></a> <a href="<?php echo site_url('admin/articles/add');?>"><?php echo lang('kb_add_article'); ?></a> <?php $this->core_events->trigger('template/admin/articles'); ?> </div> <?php endif; ?> <?php if($nav=='categories'): ?> <div id="submenu_3"> <a href="<?php echo site_url('admin/categories');?>"><?php echo lang('kb_manage_categories'); ?></a> <a href="<?php echo site_url('admin/categories/add');?>"><?php echo lang('kb_add_category'); ?></a> <?php $this->core_events->trigger('admin/template/nav/categories');?> </div> <?php endif; ?> <?php if($nav=='glossary'): ?> <div id="submenu_4"> <a href="<?php echo site_url('admin/glossary');?>"><?php echo lang('kb_manage_glossary'); ?></a> <a href="<?php echo site_url('admin/glossary/add');?>"><?php echo lang('kb_add_term'); ?></a> <?php $this->core_events->trigger('admin/template/nav/glossary');?> </div> <?php endif; ?> <?php if($nav=='users'): ?> <div id="submenu_5"> <a href="<?php echo site_url('admin/users');?>"><?php echo lang('kb_manage_users'); ?></a> <a href="<?php echo site_url('admin/users/add');?>"><?php echo lang('kb_add_user'); ?></a> <?php $this->core_events->trigger('admin/template/nav/users');?> </div> <?php endif; ?> <?php if($nav=='comments'): ?> <div id="submenu_6"> <a href="<?php echo site_url('admin/comments');?>"><?php echo lang('kb_comments'); ?></a> <?php $this->core_events->trigger('admin/template/nav/comments');?> </div> <?php endif; ?> <?php if($nav=='settings'): ?> <div id="submenu_7"> <a href="<?php echo site_url('admin/settings');?>"><?php echo lang('kb_settings'); ?></a> <a href="<?php echo site_url('admin/settings/templates/');?>" accesskey="T"><?php echo lang('kb_templates'); ?></a> <a href="<?php echo site_url('admin/modules/');?>" accesskey="M"><?php echo lang('kb_modules'); ?></a> <a href="<?php echo site_url('admin/stats/');?>"><?php echo lang('kb_stats'); ?></a> <a href="<?php echo site_url('admin/utility/');?>"><?php echo lang('kb_utilities'); ?></a> <?php $this->core_events->trigger('admin/template/nav/settings');?> </div> <?php endif; ?> </div> <div id="content"> <!-- // Content // --> <?php echo $body; ?> <!-- // End Content // --> </div> </div> <div id="footer"> &copy; 2008 - 2010 68 KB - <?php echo $settings['version']; ?> <br /> Time: <?=$this->benchmark->elapsed_time();?> - Memory: <?=$this->benchmark->memory_usage();?> </div> <?php $this->core_events->trigger('admin/template/footer');?> </body> </html><file_sep>/upload/themes/front/default/layout.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?php echo $title; ?></title> <link href="<?php echo base_url();?>themes/front/default/css/960.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url();?>themes/front/default/css/style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript" src="<?php echo base_url();?>js/tooltip.js"></script> <script type="text/javascript" src="<?php echo base_url();?>js/jfav.js"></script> </head> <body> <div id="content_bg"> <div class="container_16" id="header"> <div class="grid_16"> <h1><?php echo $settings['site_name']; ?></h1> </div> </div> <div class="container_16 clearfix"> <div class="grid_12"> <div id="content"> <?php echo $body; ?> </div> </div> <div class="grid_4"> <div id="sidebar"> <ul> <li><h2>Navigation</h2> <ul> <li><a href="<?php echo site_url(); ?>">Knowledge Base Home</a></li> <li><a href="<?php echo site_url('all'); ?>"><?php echo lang('kb_all_articles'); ?></a></li> <li><a href="<?php echo site_url('glossary'); ?>"><?php echo lang('kb_glossary'); ?></a></li> </ul> </li> <li><h2><?php echo lang('kb_categories'); ?></h2> <?php echo list_categories(); ?> </li> </ul> </div> </div> </div> </div> </body> </html><file_sep>/upload/themes/front/default/article.php <?php if(isset($article)):?> <script language="javascript" type="text/javascript"> $(document).ready(function() { $('a.rating').click(function(event) { event.preventDefault(); var id = this.id.replace('rate_', ""); var val = (id == 'up') ? "1" : "-1"; alert(val); }) }); </script> <h1 id="article_heading"><?php echo $article->article_title; ?></h1> <div class="meta"> <?php echo lang('kb_author'); ?> <?php echo $author->firstname; ?> <?php echo $author->lastname; ?> <?php echo lang('kb_on'); ?> <?php echo date($this->config->item('article_date_format'), $article->article_date); ?> | <a href="<?php echo site_url('article/printer/'.$article->article_uri); ?>"><?php echo lang('kb_print'); ?></a> | <a id="bookmark"><?php echo lang('kb_bookmark'); ?></a> <script language="javascript" type="text/javascript"> $(document).ready(function(){ $('#bookmark').jFav(); }); </script> </div> <?php echo $article->article_description; ?> <div id="rating"> <h3><?php echo lang('kb_helpful'); ?></h3> <?php if ($this->session->flashdata('rating')) { ?> <?php echo lang('kb_rate_success'); ?> <?php } else { ?> <form method="post" action="<?php echo site_url('article/rate'); ?>"> <?php echo lang('kb_yes'); ?> <input type="radio" name="rating" value="1" /> <?php echo lang('kb_no'); ?> <input type="radio" name="rating" value="-1" /> <input type="submit" name="submit" value="<?php echo lang('kb_rate'); ?>" /> <input type="hidden" name="article_id" value="<?php echo $article->article_id; ?>" /> <input type="hidden" name="article_uri" value="<?php echo $article->article_uri; ?>" /> </form> <?php } ?> </div> <a name="attachments"></a> <?php if ($attach->num_rows() > 0): ?> <fieldset> <legend><?php echo lang('kb_attachments'); ?></legend> <ul> <?php foreach($attach->result() as $item): ?> <li><a href="<?php echo base_url(); ?>uploads/<?php echo $article->article_id .'/'. $item->attach_name; ?>" target="_blank"><?php echo $item->attach_name; ?></a></li> <?php endforeach; ?> </ul> </fieldset> <?php endif; //end attachments ?> <div class="meta"> <?php if(isset($article_cats) && $article_cats->num_rows() > 0): ?> <p> <strong><?php echo lang('kb_category'); ?>:</strong> <?php // This is a hack to remove final comma. $count = count($article_cats->result()); $i=0; foreach($article_cats->result() as $row) { $i++; ?> <a href="<?php echo site_url('category/'.$row->cat_uri); ?>"><?php echo $row->cat_name; ?></a><?php if($i < $count) echo ','; ?> <?php } ?> </p> <?php endif; //end article_cats ?> <p><?php echo lang('kb_last_updated'); ?> <?php echo date($this->config->item('article_date_format'), $article->article_modified); ?> with <?php echo $article->article_hits; ?> views</p> </div> <?php if($settings['comments'] == 'Y'): ?> <?php echo $comment_template; ?> <?php endif; //end allow comments ?> <?php else: ?> <p><?php echo lang('kb_article_not_available'); ?></p> <?php endif; ?> <file_sep>/upload/includes/application/controllers/kb.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * KB Controller * * Main Home Page Controller * * @package 68kb * @subpackage Controllers * @category Controllers * @author 68kb Dev Team * @link http://68kb.com/ * @version $Id: kb.php 89 2009-08-13 01:54:20Z suzkaw68 $ */ class Kb extends Controller { /** * Constructor * * @return void */ function __construct() { parent::__construct(); log_message('debug', 'KB Controller Initialized'); $this->load->model('init_model'); $this->load->model('category_model'); if(!$this->db->table_exists('articles')) { redirect('setup'); } } // ------------------------------------------------------------------------ /** * Index Controller * * Show the home page * * @uses category_model::get_categories_by_parent * @uses article_model::get_most_popular * @uses article_model::get_latest * @access public */ function index() { $this->load->helper('form'); $this->load->model('article_model'); $this->load->model('tags_model'); $this->benchmark->mark('cats_start'); $data['parents'] = $this->category_model->get_categories_by_parent(0); $data['cat_tree'] = $this->category_model->get_cats_for_select(); $this->benchmark->mark('cats_end'); $this->benchmark->mark('articles_start'); $data['pop'] = $this->article_model->get_most_popular(10); $data['latest'] = $this->article_model->get_latest(10); $this->benchmark->mark('articles_end'); $data['title'] = $this->init_model->get_setting('site_name'); $this->init_model->display_template('home', $data); } } /* End of file kb.php */ /* Location: ./upload/includes/application/controllers/kb.php */ <file_sep>/upload/includes/application/controllers/admin/categories.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Admin Categories Controller * * Handles the categories pages * * @package 68kb * @subpackage Admin_Controllers * @category Admin_Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/categories.html * @version $Id: categories.php 134 2009-12-02 01:29:40Z suzkaw68 $ */ class Categories extends Controller { /** * Constructor * * Requires needed models and helpers. * * @access public */ function __construct() { parent::__construct(); $this->load->model('init_model'); $this->load->model('category_model'); $this->load->helper('cookie'); $this->load->library('auth'); $this->auth->restrict(); } // ------------------------------------------------------------------------ /** * Index Controller * * Redirects to this->grid * * @access public */ function index() { $data=''; redirect('admin/categories/grid/'); } // ------------------------------------------------------------------------ /** * Revert * * Show a message and redirect the user * * @access public * @param string -- The location to goto * @return array */ function revert($goto) { $data['goto'] = $goto; $data['nav'] = 'categories'; $this->init_model->display_template('content', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Grid * * Show a table of categories * * @access public * @return array */ function grid() { $data['nav'] = 'categories'; if ( ! $this->auth->check_level(3)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $data['options'] = $this->category_model->get_cats_for_select('',0,'',TRUE); $this->init_model->display_template('categories/grid', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Edit Category * * @access public */ function edit() { $this->load->library('form_validation'); $data['nav'] = 'categories'; if ( ! $this->auth->check_level(3)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $this->load->helper('form'); $id = (int) $this->uri->segment(4, 0); $data['art'] = $this->category_model->get_cat_by_id($id); $data['options'] = $this->category_model->get_cats_for_select('',0,'',TRUE); $data['action'] = site_url('admin/categories/edit/'.$id); $this->form_validation->set_rules('cat_name', 'lang:kb_title', 'required'); $this->core_events->trigger('categories/validation'); if ($this->form_validation->run() == FALSE) { $this->init_model->display_template('categories/form', $data, 'admin'); } else { //success $id = $this->input->post('cat_id', TRUE); $parent = $this->input->post('cat_parent', TRUE); if ($parent=='') { $parent=0; } $cat_uri = $this->input->post('cat_uri', TRUE); $data = array( 'cat_uri' => $cat_uri, 'cat_name' => $this->input->post('cat_name', TRUE), 'cat_description' => $this->input->post('cat_description', TRUE), 'cat_parent' => $parent, 'cat_display' => $this->input->post('cat_display', TRUE), 'cat_order' => $this->input->post('cat_order', TRUE) ); $var = $this->category_model->edit_category($id, $data); $this->revert('admin/categories/'); } } // ------------------------------------------------------------------------ /** * Add Category * * @access public */ function add() { $this->load->library('form_validation'); $data['nav'] = 'categories'; if ( ! $this->auth->check_level(3)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $this->load->helper('form'); $id = (int) $this->uri->segment(4, 0); $data['options'] = $this->category_model->get_cats_for_select('',0,'',TRUE); $data['action'] = site_url('admin/categories/add/'); $this->form_validation->set_rules('cat_name', 'lang:kb_title', 'required'); $this->form_validation->set_rules('cat_uri', 'lang:kb_uri', 'alpha_dash'); $this->form_validation->set_rules('cat_description', 'lang:kb_description', ''); $this->form_validation->set_rules('cat_parent', 'lang:kb_parent_cat', 'numeric'); $this->form_validation->set_rules('cat_order', 'lang:kb_weight', 'numeric'); $this->core_events->trigger('categories/validation'); if ($this->form_validation->run() == FALSE) { $this->init_model->display_template('categories/form', $data, 'admin'); } else { //success $parent = $this->input->post('cat_parent', TRUE); if ($parent=='') { $parent=0; } $cat_uri = $this->input->post('cat_uri', TRUE); $data = array( 'cat_uri' => $cat_uri, 'cat_name' => $this->input->post('cat_name', TRUE), 'cat_description' => $this->input->post('cat_description', TRUE), 'cat_parent' => $parent, 'cat_display' => $this->input->post('cat_display', TRUE), 'cat_order' => $this->input->post('cat_order', TRUE) ); $var = $this->category_model->add_category($data); $this->revert('admin/categories/'); } } // ------------------------------------------------------------------------ /** * Duplicate Article * * @access public */ function duplicate() { $data['nav'] = 'categories'; if ( ! $this->auth->check_level(3)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $this->load->helper('form'); $id = (int) $this->uri->segment(4, 0); $data['art'] = $this->category_model->get_cat_by_id($id); $data['options'] = $this->category_model->get_cats_for_select('',0); $data['action'] = 'add'; $this->init_model->display_template('categories/form', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Delete Category * * @access public */ function delete() { $data['nav'] = 'categories'; if ( ! $this->auth->check_level(3)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $id = (int) $this->uri->segment(4, 0); $this->db->delete('categories', array('cat_id' => $id)); $this->core_events->trigger('categories/delete', $id); $this->revert('admin/categories/'); } } /* End of file categories.php */ /* Location: ./upload/includes/application/controllers/admin/categories.php */ <file_sep>/upload/themes/admin/default/categories/grid.php <script language="javascript" type="text/javascript"> <!-- function deleteSomething(url){ removemsg = "<?php echo lang('kb_are_you_sure'); ?>" if (confirm(removemsg)) { document.location = url; } } // --> </script> <h2><?php echo lang('kb_categories'); ?> <a class="addnew" href="<?php echo site_url('admin/categories/add');?>"><?php echo lang('kb_add_category'); ?></a></h2> <table class="main" width="100%" cellpadding="0" cellspacing="0"> <tr> <th><?php echo lang('kb_id');?></th> <th><?php echo lang('kb_title');?></th> <th><?php echo lang('kb_description');?></th> <th><?php echo lang('kb_actions');?></th> </tr> <?php $alt = true; foreach($options as $row): ?> <tr<?php if ($alt) echo ' class="second"'; else echo ' class="first"'; $alt = !$alt; ?>> <td><?php echo $row['cat_id']; ?></td> <td class="title" nowrap><a href="<?php echo site_url('admin/categories/edit/'.$row['cat_id']); ?>"><?php echo $row['cat_name']; ?></a></td> <td><?php echo $row['cat_description']; ?></td> <td width="15%" nowrap> <a href="<?php echo site_url('admin/categories/edit/'.$row['cat_id']); ?>"><img src="<?php echo base_url(); ?>images/page_edit.png" border="0" alt="<?php echo lang('kb_edit'); ?>" title="<?php echo lang('kb_edit'); ?>" /></a> &nbsp; <a href="<?php echo site_url('admin/categories/duplicate/'.$row['cat_id']); ?>"><img src="<?php echo base_url(); ?>images/page_copy.png" border="0" alt="<?php echo lang('kb_duplicate'); ?>" title="<?php echo lang('kb_duplicate'); ?>" /></a> &nbsp; <a href="javascript:void(0);" onclick="deleteSomething('<?php echo site_url('admin/categories/delete/'.$row['cat_id']); ?>')"><img src="<?php echo base_url(); ?>images/page_delete.png" border="0" alt="<?php echo lang('kb_delete'); ?>" title="<?php echo lang('kb_delete'); ?>" /></a> </td> </tr> <?php endforeach; ?> </table> <br /> <table width="30%" align="center"> <tr> <td align="right"><img src="<?php echo base_url(); ?>images/page_edit.png" border="0" alt="<?php echo lang('kb_edit'); ?>" /></td> <td align="left"><?php echo lang('kb_edit'); ?></td> <td align="right"><img src="<?php echo base_url(); ?>images/page_copy.png" border="0" alt="<?php echo lang('kb_duplicate'); ?>" /></td> <td align="left"><?php echo lang('kb_duplicate'); ?></td> <td align="right"><img src="<?php echo base_url(); ?>images/page_delete.png" border="0" alt="<?php echo lang('kb_delete'); ?>" /></td> <td align="left"><?php echo lang('kb_delete'); ?></td> <td align="right"><img src="<?php echo base_url(); ?>images/lock.png" border="0" alt="<?php echo lang('kb_default'); ?>" /></td> <td align="left"><?php echo lang('kb_default'); ?></td> </tr> </table> <file_sep>/upload/includes/application/language/english/kb_lang.php <?php /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Knowledge Base Language File * * This file handles all the English language strings. * * @package 68kb * @subpackage Language * @category Language * @author 68kb Dev Team * @version $Id: kb_lang.php 143 2009-12-04 13:20:38Z suzkaw68 $ */ /** * Articles */ $lang['kb_all_articles'] = 'All Articles'; $lang['kb_article_not_available'] = 'Sorry this article is not available.'; $lang['kb_search'] = 'Search'; $lang['kb_search_articles'] = 'Search Articles'; $lang['kb_search_text'] = 'Search Text'; $lang['kb_status'] = 'Status'; $lang['kb_author'] = 'Author'; $lang['kb_on'] = 'on'; $lang['kb_all'] = 'All'; $lang['kb_active'] = 'Active'; $lang['kb_notactive'] = 'Not Active'; $lang['kb_keyword'] = 'Key Word'; $lang['kb_searchall'] = 'Search All'; $lang['kb_searchadvanced'] = 'Advanced Search'; $lang['kb_title'] = 'Title'; $lang['kb_views'] = 'Views'; $lang['kb_status'] = 'Status'; $lang['kb_short_description'] = 'Short Description'; $lang['kb_date_added'] = 'Date Added'; $lang['kb_last_updated'] = 'Last updated on'; $lang['kb_attachment'] = 'Add Attachment'; $lang['kb_attachments'] = 'Attachments'; $lang['kb_attachment_add'] = 'After you save this article you can add attachments'; $lang['kb_upload'] = 'Upload'; $lang['kb_show'] = 'Show'; $lang['kb_article_weight_desc'] = 'All articles are sorted alphabetically but you can override this by using a weight. The higher the weight the sooner the article will appear.'; $lang['kb_most_popular'] = 'Most Popular'; $lang['kb_new_articles'] = 'New Articles'; $lang['kb_print'] = 'Print'; $lang['kb_bookmark'] = 'Bookmark'; $lang['kb_keywords'] = 'Keywords'; $lang['kb_keywords_desc'] = 'Please add any keywords seperated by a comma.'; $lang['kb_edit_erro'] = 'Please add any keywords seperated by a comma.'; $lang['kb_helpful'] = 'Was this article helpful?'; $lang['kb_rate'] = 'Rate'; $lang['kb_rate_success'] = 'Thank you for rating this article.'; $lang['kb_tags'] = 'Tags'; $lang['kb_change_status'] = 'Change Status'; /** * Categories */ $lang['kb_id'] = 'ID'; $lang['kb_title'] = 'Title'; $lang['kb_uri'] = 'URI'; $lang['kb_category'] = 'Category'; $lang['kb_incat'] = 'In Category'; $lang['kb_browsecats'] = 'Browse Categories'; $lang['kb_categories'] = 'Categories'; $lang['kb_content'] = 'Content'; $lang['kb_parent_cat'] = 'Parent Category'; $lang['kb_no_parent'] = 'No Parent'; $lang['kb_display'] = 'Display'; $lang['kb_edit'] = 'Edit'; $lang['kb_duplicate'] = 'Duplicate'; $lang['kb_delete'] = 'Delete'; $lang['kb_weight'] = 'Weight'; $lang['kb_weight_desc'] = 'All categories are sorted alphabetically but you can override this by using a weight. The higher the weight the sooner the category will appear.'; $lang['kb_default'] = 'Default'; /** * Comments */ $lang['kb_comment'] = 'Comment'; $lang['kb_comments'] = 'Comments'; $lang['kb_recent_comments'] = 'Recent Comments'; $lang['kb_search_comments'] = 'Search Comments'; $lang['kb_ip'] = 'IP'; $lang['kb_spam'] = 'Spam'; $lang['kb_user_comments'] = 'User Comments'; $lang['kb_no_comments'] = 'There are no comments yet...Kick things off by filling out the form below.'; $lang['kb_leave_comment'] = 'Leave a Comment'; $lang['kb_thank_you'] = 'Thank You'; $lang['kb_comment_added'] = 'Your comment has been added. Please wait while you are forwarded. If this does not happen automatically please'; $lang['kb_click_here'] = 'Click Here'; $lang['kb_new_comment'] = 'New comment:'; $lang['kb_comment_link'] = 'You can approve or decline this comment here:'; /** * Contact */ $lang['kb_contact_related'] = 'Related Articles'; $lang['kb_contact'] = 'Contact'; $lang['kb_subject'] = 'Subject'; $lang['kb_contact_confirm'] = 'Your message has not been sent. Please first check the above articles and see if they answer your questions. If not then click the button below.'; $lang['kb_submit_message'] = 'Submit Your Request'; $lang['kb_thank_you'] = 'Thank You'; $lang['kb_thank_you_msg'] = 'Your message has been successfully sent.'; $lang['kb_captcha'] = 'Please enter the text shown'; /** * Fields */ $lang['kb_fields'] = 'Fields'; $lang['kb_field_name'] = 'Field Name'; $lang['kb_field_type'] = 'Field Type'; /** * Forward */ $lang['kb_success'] = 'Success'; $lang['kb_forward'] = 'Please wait while you are forwarded. If this does not happen automatically please'; $lang['kb_click_here'] = 'click here'; /** * General */ $lang['kb_pages'] = 'Pages'; $lang['kb_yes'] = 'Yes'; $lang['kb_no'] = 'No'; $lang['kb_welcome'] = 'Welcome'; $lang['kb_latest_news'] = 'Latest 68kb News'; $lang['kb_logout'] = 'Logout'; $lang['kb_forums'] = 'Support Forums'; $lang['kb_support_knowledge_base'] = 'Support Knowledge Base'; $lang['kb_view_site'] = 'View Site'; $lang['kb_please_login'] = 'Please Log In'; $lang['kb_enter_details'] = 'Please enter your details below'; $lang['kb_remember_me'] = 'Remember Me'; $lang['kb_login_invalid'] = 'Invalid Username or Password'; $lang['kb_loggedin'] = 'Logged in: '; $lang['kb_latest_news'] = 'Latest News'; $lang['kb_loading'] = 'Loading...'; $lang['kb_update_1'] = 'of 68KB is available!'; $lang['kb_update_2'] = 'Please update now'; /** * Glossary */ $lang['kb_manage_glossary'] = 'Manage Glossary'; $lang['kb_glossary'] = 'Glossary'; $lang['kb_term'] = 'Term'; $lang['kb_add_term'] = 'Add Term'; $lang['kb_definition'] = 'Definition'; $lang['kb_save'] = 'Save'; $lang['kb_save_and_continue'] = 'Save and Continue Editing'; /** * Home */ $lang['kb_knowledge_base'] = 'Knowledge Base'; $lang['kb_first_time'] = '<strong>Welcome!</strong> It looks like this is the first time you have used 68kb so you might find the <a href="http://68kb.com/knowledge-base/article/quick-start-guide">quick start guide</a> useful. If you need any assistance, don\'t hesitate to visit our <a href="http://68kb.com/support">user forums</a>.'; $lang['kb_pending_comments'] = 'Pending Comments'; $lang['kb_running'] = 'You are running'; $lang['kb_license_key'] = 'License Key'; $lang['kb_total_articles'] = 'Total Articles'; $lang['kb_total_categories'] = 'Total Categories'; $lang['kb_total_comments'] = 'Total Comments'; $lang['kb_article_search'] = 'Article Search'; /** * Javascript */ $lang['kb_please_enter'] = 'Please enter a value in the field'; $lang['kb_are_you_sure'] = 'Are you sure you want to delete this record? It can not be undone!'; $lang['kb_required'] = 'Required'; $lang['kb_uri_desc'] = ''; $lang['kb_please_goback'] = 'Please go back and fix those errors.'; /** * Modules */ $lang['kb_admin'] = 'Admin'; $lang['kb_modules'] = 'Modules'; $lang['kb_name'] = 'Name'; $lang['kb_description'] = 'Description'; $lang['kb_version'] = 'Version'; $lang['kb_actions'] = 'Actions'; $lang['kb_activate'] = 'Activate'; $lang['kb_activated'] = 'Module Activated'; $lang['kb_active_modules'] = 'Active Modules'; $lang['kb_deactive_modules'] = 'Deactive Modules'; $lang['kb_upgrade_module'] = 'Upgrade Module'; $lang['kb_deactivate'] = 'Deactivate'; $lang['kb_deactivated'] = 'Module Deactivated'; $lang['kb_upgraded'] = 'Module Upgraded'; $lang['kb_deleted'] = 'Module Deleted'; $lang['kb_delete_module'] = 'Are you sure you want to delete this record? \nPlease note this only removes it from the database. You will still need to remove the files from \"my-modules\" folder.'; /** * Nav */ $lang['kb_home'] = 'Home'; $lang['kb_dashboard'] = 'Dashboard'; $lang['kb_article'] = 'Article'; $lang['kb_articles'] = 'Articles'; $lang['kb_manage_articles'] = 'Manage Articles'; $lang['kb_add_article'] = 'Add Article'; $lang['kb_categories'] = 'Categories'; $lang['kb_manage_categories'] = 'Manage Categories'; $lang['kb_add_category'] = 'Add Category'; $lang['kb_settings'] = 'Settings'; $lang['kb_glossary'] = 'Glossary'; $lang['kb_users'] = 'Users'; /** * Search */ $lang['kb_search_kb'] = 'Search the knowledge base'; $lang['kb_search_results'] = 'Search Results'; $lang['kb_no_results'] = 'Sorry we didn\'t find any articles matching your search'; /** * Settings */ $lang['kb_main_settings'] = 'Main Settings'; $lang['kb_site_title'] = 'Site Title'; $lang['kb_site_keywords'] = 'Site Keywords'; $lang['kb_site_description'] = 'Site Description'; $lang['kb_email'] = 'Email'; $lang['kb_max_search'] = 'Max Search Results'; $lang['kb_templates'] = 'Templates'; $lang['kb_current_template'] = 'Current Theme'; $lang['kb_available_templates'] = 'Available Themes'; $lang['kb_allow_comments'] = 'Allow Comments'; $lang['kb_cache_time'] = 'Cache Time'; $lang['kb_delete_cache'] = 'Delete Cache'; $lang['kb_cache_deleted'] = 'Cache deleted successfully'; $lang['kb_cache_desc'] = 'The number of minutes you wish pages to remain cached. Enter 0 for no caching. Please make the includes/application/cache folder writable.'; $lang['kb_export_html'] = 'Export to HTML'; /** * Stats */ $lang['kb_stats'] = 'Stats'; $lang['kb_summary'] = 'Summary'; $lang['kb_most_viewed'] = 'Most Viewed'; $lang['kb_search_log'] = 'Search Log'; $lang['kb_searches'] = 'Searches'; /** * Users */ $lang['kb_manage_users'] = 'Manage Users'; $lang['kb_add_user'] = 'Add User'; $lang['kb_username'] = 'Username'; $lang['kb_password'] = '<PASSWORD>'; $lang['kb_confirmpassword'] = '<PASSWORD>'; $lang['kb_firstname'] = 'First Name'; $lang['kb_lastname'] = 'Last Name'; $lang['kb_name'] = 'Name'; $lang['kb_email'] = 'Email'; $lang['kb_user_group'] = 'User Group'; $lang['kb_username_inuse'] = 'That username is already in use.'; $lang['kb_password_change'] = 'If you would like to change the password type a new one twice below. Otherwise leave this blank.'; $lang['kb_level'] = 'User Group'; $lang['kb_not_allowed'] = 'I am sorry but you do not have sufficient privileges to view this page.'; /** * Utilities */ $lang['kb_utilities'] = 'Utilities'; $lang['kb_optimize_db'] = 'Optimize Database'; $lang['kb_repair_db'] = 'Repair Database'; $lang['kb_backup_db'] = 'Backup Database'; $lang['kb_optimize_success'] = 'Successfully Optimized...'; $lang['kb_repair_success'] = 'Successfully Repaired...'; /* End of file kb_lang.php */ /* Location: ./upload/includes/application/language/english/kb_lang.php */ <file_sep>/upload/includes/application/controllers/modules.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Modules Controller * * Handles any modules added to the script * * @package 68kb * @subpackage Controllers * @category Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/developer/modules.html * @version $Id: modules.php 85 2009-08-05 05:08:12Z suzkaw68 $ */ class Modules extends Controller { var $modules; function __construct() { parent::__construct(); log_message('debug', 'Modules Controller Initialized'); $this->load->model('init_model'); } // ------------------------------------------------------------------------ /** * List all modules * * @access public */ function index() { } // ------------------------------------------------------------------------ /** * Show a modules front end file * * @access public */ function show() { $name = $this->uri->segment(3, 0); $this->db->from('modules')->where('name', $name); $query = $this->db->get(); if ($query->num_rows() > 0) { $row = $query->row(); $file = KBPATH .'my-modules/'.$row->directory.'/index.php'; if (@file_exists($file)) { $data['file'] = $file; $this->core_events->trigger('modules/show', $file); $this->init_model->display_template('modules/show', $data); } else { //take me home. redirect('kb'); } } else { redirect('kb'); } } // ------------------------------------------------------------------------ /** * Get Module * * Get a single module * * @access public * @param int the module id * @return bool */ function get_module() { $name = $this->uri->segment(3, 0); $this->db->from('modules')->where('name', $name); $query = $this->db->get(); //echo $this->db->last_query(); if ($query->num_rows() > 0) { $row = $query->row(); $file = KBPATH .'my-modules/'.$row->directory.'/index.php'; if (@file_exists($file)) { $data['file'] = $file; require_once($file); } else { //take me home. redirect('kb'); } } else { redirect('kb'); } } } /* End of file modules.php */ /* Location: ./upload/includes/application/controllers/modules.php */ <file_sep>/upload/includes/application/controllers/search.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Search Controller * * Allows users to search articles * * @package 68kb * @subpackage Controllers * @category Controllers * @author 68kb Dev Team * @link http://68kb.com/ * @version $Id: search.php 123 2009-11-13 15:27:14Z suzkaw68 $ */ class Search extends Controller { function __construct() { parent::__construct(); log_message('debug', 'Search Controller Initialized'); $this->load->model('init_model'); $this->load->model('category_model'); $this->load->helper('form'); } function index() { $data['title'] = $this->init_model->get_setting('site_name'); $data['cat_tree'] = $this->category_model->get_cats_for_select(); $input = $this->input->post('searchtext', TRUE); $category = (int)$this->input->post('category', TRUE); if($input <> '' || $category <> '') { if ($input) { $insert = array('searchlog_term' => $input); $this->db->insert('searchlog', $insert); } $this->db->from('articles'); $this->db->join('article2cat', 'articles.article_id = article2cat.article_id', 'left'); if($category) { $this->db->where('category_id', $category); } $this->db->where('article_display', 'Y'); // This is a hack found here: // http://codeigniter.com/forums/viewthread/122223/ // And here: // http://68kb.com/support/topic/better-keyword-handling-in-search-a-solution if($input) { $keywords = array(); $keywords = explode(" ", $input); $numkeywords = count($keywords); $wherestring = ""; for ($i = 0; $i < $numkeywords; $i++) { if ($i > 0) { $wherestring .= " AND "; } $wherestring = $wherestring . " (article_title LIKE '%". mysql_real_escape_string($keywords[$i]) . "%' OR article_short_desc LIKE '%" . mysql_real_escape_string($keywords[$i]) . "%' OR article_description LIKE '%". mysql_real_escape_string($keywords[$i]) . "%' OR article_keywords LIKE '%". mysql_real_escape_string($keywords[$i]) ."%') "; } $this->db->where($wherestring,NULL,FALSE); } $this->db->orderby('article_order', 'DESC'); $this->db->orderby('article_hits', 'DESC'); $data['articles'] = $this->db->get(); $data['searchtext'] = $input; $data['category'] = $category; } $this->init_model->display_template('search', $data); } } /* End of file search.php */ /* Location: ./upload/includes/application/controllers/search.php */<file_sep>/upload/themes/admin/default/articles/grid.php <script language="javascript" type="text/javascript"> <!-- function deleteSomething(url){ removemsg = "<?php echo lang('kb_are_you_sure'); ?>" if (confirm(removemsg)) { document.location = url; } } // --> </script> <h2><?php echo lang('kb_articles'); ?> <a class="addnew" href="<?php echo site_url('admin/articles/add');?>"><?php echo lang('kb_add_article'); ?></a></h2> <?php $attributes = array('id' => 'search'); echo form_open($this->uri->uri_string(), $attributes); ?> <table> <tr> <td><input type="text" name="searchtext" id="searchtext" value="<?php echo (isset($q)) ? form_prep($q) : ''; ?>" size="17" /></td> <td> <select name="cat" id="cat"> <option value="0" selected><?php echo lang('kb_categories'); ?></option> <option value="0"><?php echo lang('kb_all'); ?></option> <?php foreach($categories as $row): ?> <option value="<?php echo $row['cat_id']; ?>"<?php echo (isset($s_cat) && $s_cat==$row['cat_id']) ? ' selected="selected"' : ''; ?>><?php echo $row['cat_name']; ?></option> <?php endforeach; ?> </select> </td> <td> <select name='article_display'> <option value='' selected><?php echo lang('kb_status'); ?></option> <option value=''><?php echo lang('kb_all'); ?></option> <option value='Y'<?php echo (isset($s_display) && $s_display=='Y') ? ' selected="selected"' : ''; ?>><?php echo lang('kb_active'); ?></option> <option value='N'<?php echo (isset($s_display) && $s_display=='N') ? ' selected="selected"' : ''; ?>><?php echo lang('kb_notactive'); ?></option> </select> </td> <td> <select name='a_author' id='a_author'> <option value='0' selected><?php echo lang('kb_author'); ?></option> <option value='0'><?php echo lang('kb_all'); ?></option> <?php foreach($authors->result() as $rs): ?> <option value="<?php echo $rs->id; ?>"<?php echo (isset($s_author) && $s_author==$rs->id) ? ' selected="selected"' : ''; ?>><?php echo $rs->username; ?></option> <?php endforeach; ?> </select> </td> <td> <input type="submit" id="submit" value="<?php echo lang('kb_search'); ?> &#187;" class="button" /> </td> </tr> </table> <input type="hidden" name="search" value="go" /> <?php echo form_close(); ?> <div class="clear"></div> <?php $attributes = array('id' => 'articles', 'name' => 'articles'); echo form_open('admin/articles/update', $attributes); ?> <input type="hidden" name="act" value="xxxxx" /> <table class="main" width="100%" cellpadding="0" cellspacing="0"> <tr> <th scope="col" class="row_small"><input type="checkbox" name="checkbox" id="checkbox" value="checkbox" /></th> <th> <?php $class=''; if(isset($orderby) && isset($opp) && $orderby=="article_title") { $class = $opp; } ?> <?php if(isset($sort) && $sort == 'desc'): ?> <a href="<?php echo site_url('admin/articles/grid/orderby/article_title/asc'); ?>" class="<?php echo $class; ?>"> <?php else: ?> <a href="<?php echo site_url('admin/articles/grid/orderby/article_title/desc'); ?>" class="<?php echo $class; ?>"> <?php endif; ?> <?php echo lang('kb_title'); ?> </a> </th> <th> <?php echo lang('kb_categories'); ?> </th> <th width="13%"> <?php $class=''; if(isset($orderby) && isset($opp) && $orderby=="article_date") { $class = $opp; } ?> <?php if(isset($sort) && $sort == 'desc'): ?> <a href="<?php echo site_url('admin/articles/grid/orderby/article_date/asc'); ?>" class="<?php echo $class; ?>"> <?php else: ?> <a href="<?php echo site_url('admin/articles/grid/orderby/article_date/desc'); ?>" class="<?php echo $class; ?>"> <?php endif; ?> <?php echo lang('kb_date_added'); ?> </a> </th> <th> <?php $class=''; if(isset($orderby) && isset($opp) && $orderby=="article_hits") { $class = $opp; } ?> <?php if(isset($sort) && $sort == 'desc'): ?> <a href="<?php echo site_url('admin/articles/grid/orderby/article_hits/asc'); ?>" class="<?php echo $class; ?>"> <?php else: ?> <a href="<?php echo site_url('admin/articles/grid/orderby/article_hits/desc'); ?>" class="<?php echo $class; ?>"> <?php endif; ?> <?php echo lang('kb_views'); ?> </a> </th> <th> <?php $class=''; if(isset($orderby) && isset($opp) && $orderby=="article_display") { $class = $opp; } ?> <?php if(isset($sort) && $sort == 'desc'): ?> <a href="<?php echo site_url('admin/articles/grid/orderby/article_display/asc'); ?>" class="<?php echo $class; ?>"> <?php else: ?> <a href="<?php echo site_url('admin/articles/grid/orderby/article_display/desc'); ?>" class="<?php echo $class; ?>"> <?php endif; ?> <?php echo lang('kb_display'); ?> </a> </th> <th><?php echo lang('kb_actions'); ?></th> </tr> <?php if(isset($items)): ?> <?php $alt = true; foreach($items as $item): ?> <tr<?php if ($alt) echo ' class="second"'; else echo ' class="first"'; $alt = !$alt; ?>> <td class="row_small"><input type="checkbox" name="articleid[]" value="<?php echo $item['article_id']; ?>" class="toggable" /></td> <td class="title"><a href="<?php echo site_url('admin/articles/edit/'.$item['article_id']); ?>"><?php echo $item['article_title']; ?></a></td> <td class="categories"> <?php if (isset($item['cats'])): ?> <?php foreach($item['cats']->result() as $row): ?> <a href="<?php echo site_url('admin/categories/edit/'.$row->cat_id); ?>"><?php echo $row->cat_name; ?></a>, <?php endforeach; ?> <?php endif; ?> </td> <td class=""><?php echo date($this->config->item('article_date_format'), $item['article_date']); ?></td> <td><?php echo $item['article_hits']; ?></td> <td> <?php if($item['article_display'] != 'Y') { echo '<span class="inactive">'.lang('kb_notactive').'</span>'; } else { echo '<span class="active">'.lang('kb_active').'</span>'; } ?> </td> <td width="10%" nowrap="nowrap"> <a href="<?php echo site_url('article/'.$item['article_uri']); ?>" target="_blank"><img src="<?php echo base_url(); ?>images/page_show.png" border="0" alt="<?php echo lang('kb_show'); ?>" title="<?php echo lang('kb_show'); ?>" /></a> &nbsp; <a href="<?php echo site_url('admin/articles/edit/'.$item['article_id']); ?>"><img src="<?php echo base_url(); ?>images/page_edit.png" border="0" alt="<?php echo lang('kb_edit'); ?>" title="<?php echo lang('kb_edit'); ?>" /></a> &nbsp; <a href="javascript:void(0);" onclick="return deleteSomething('<?php echo site_url('admin/articles/delete/'.$item['article_id']); ?>');"><img src="<?php echo base_url(); ?>images/page_delete.png" border="0" alt="<?php echo lang('kb_delete'); ?>" title="<?php echo lang('kb_delete'); ?>" /></a> </td> </tr> <?php endforeach; ?> <?php endif; ?> </table> <table width="100%" border="0" cellspacing="0" cellpadding="3"> <tr> <td> <select name="newstatus"> <option value="" selected><?php echo lang('kb_change_status'); ?></option> <option value="Y"><?php echo lang('kb_active'); ?></option> <option value="N"><?php echo lang('kb_notactive'); ?></option> <option value="D"><?php echo lang('kb_delete'); ?></option> </select> <input type="submit" value="Update" onclick="document.comments.act.value='changestatus';" /> </td> <td align="right"> <?php if($paginate==TRUE): ?> <div class="paginationNum"> <?php echo lang('kb_pages'); ?>: <?php echo $pagination; ?> </div> <?php endif; ?> </td> </tr> </table> </form> <table width="30%" align="center"> <tr> <td align="right"><img src="<?php echo base_url(); ?>images/page_show.png" border="0" alt="<?php echo lang('kb_show'); ?>" /></td> <td align="left"><?php echo lang('kb_show'); ?></td> <td align="right"><img src="<?php echo base_url(); ?>images/page_edit.png" border="0" alt="<?php echo lang('kb_edit'); ?>" /></td> <td align="left"><?php echo lang('kb_edit'); ?></td> <td align="right"><img src="<?php echo base_url(); ?>images/page_delete.png" border="0" alt="<?php echo lang('kb_delete'); ?>" /></td> <td align="left"><?php echo lang('kb_delete'); ?></td> </tr> </table> <file_sep>/upload/includes/application/language/dutch/kb_lang.php <?php /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Knowledge Base Language File * * This file handles all the Dutch language strings. * * @package 68kb * @subpackage Language * @category Language * @author jeroenwijnholds * @link http://code.google.com/p/68kb/issues/detail?id=39 * @version $Id: kb_lang.php 73 2009-07-31 04:31:19Z suzkaw68 $ */ /** * Articles */ $lang['kb_all_articles'] = 'Alle artikelen'; $lang['kb_article_not_available'] = 'Sorry dit artikel is niet beschikbaar.'; $lang['kb_search'] = 'Zoeken'; $lang['kb_search_articles'] = 'Doorzoek artikelen'; $lang['kb_search_text'] = 'Zoekwoorden'; $lang['kb_status'] = 'Status'; $lang['kb_author'] = 'Auteur'; $lang['kb_all'] = 'Alles'; $lang['kb_active'] = 'Actieg'; $lang['kb_notactive'] = 'Inactief'; $lang['kb_keyword'] = 'Keyword'; $lang['kb_searchall'] = 'Alles zoeken'; $lang['kb_searchadvanced'] = 'Geavanceerd zoeken'; $lang['kb_title'] = 'Titel'; $lang['kb_views'] = 'Views'; $lang['kb_status'] = 'Status'; $lang['kb_short_description'] = 'Korte beschrijving'; $lang['kb_date_added'] = 'Datum toegevoegd'; $lang['kb_last_updated'] = 'Voor het laatst aangepast op'; $lang['kb_attachment'] = 'Voeg bijlage toe'; $lang['kb_attachments'] = 'Bijlages'; $lang['kb_attachment_add'] = 'U kunt na het opslaan van dit artikel bijlagen toevoegen'; $lang['kb_upload'] = 'Upload'; $lang['kb_show'] = 'Toon'; $lang['kb_article_weight_desc'] = 'Alle artikelen zijn gesorteerd op alfabet, je kunt dit overschrijven door een rang toe te wijzen. Hoe hoger de rang hoe eerder het artikel naar voren komt.'; $lang['kb_most_popular'] = 'Meest Populair'; $lang['kb_new_articles'] = 'Nieuwe Artikelen'; $lang['kb_print'] = 'Print'; $lang['kb_bookmark'] = 'Bookmark'; $lang['kb_keywords'] = 'Keywords'; $lang['kb_keywords_desc'] = 'Voeg sleutelwoorden toe gescheiden met een komma. Bijvoorbeeld: router, switch.'; $lang['kb_edit_erro'] = 'Voeg sleutelwoorden toe gescheiden met een komma. Bijvoorbeeld: router, switch'; $lang['kb_helpful'] = 'Was dit artikel behulpzaam?'; $lang['kb_rate'] = 'Oordeel'; /** * Categories */ $lang['kb_id'] = 'ID'; $lang['kb_title'] = 'Titel'; $lang['kb_uri'] = 'URI'; $lang['kb_category'] = 'Categorie'; $lang['kb_incat'] = 'In Categorie'; $lang['kb_browsecats'] = 'Categorieën doorzoeken'; $lang['kb_categories'] = 'Categorieën'; $lang['kb_content'] = 'Inhoud'; $lang['kb_parent_cat'] = 'Bovenliggende map'; $lang['kb_no_parent'] = 'Geen bovenliggende map'; $lang['kb_display'] = 'Publiceren'; $lang['kb_edit'] = 'Aanpassen'; $lang['kb_duplicate'] = 'Dupliceren'; $lang['kb_delete'] = 'Verwijderen'; $lang['kb_weight'] = 'Rang'; $lang['kb_weight_desc'] = 'Alle artikelen zijn gesorteerd op alfabet, je kunt dit overschrijven door een rang toe te wijzen. Hoe hoger de rang hoe eerder het artikel naar voren komt.'; $lang['kb_default'] = 'Standaard'; /** * Comments */ $lang['kb_comment'] = 'Opmerking'; $lang['kb_comments'] = 'Opmerkingen'; $lang['kb_recent_comments'] = 'Recente Opmerkingen'; $lang['kb_search_comments'] = 'Doorzoek Opmerkingen'; $lang['kb_ip'] = 'IP'; $lang['kb_spam'] = 'Spam'; $lang['kb_user_comments'] = 'Opmerkingen van gebruikers'; $lang['kb_no_comments'] = 'Er zijn nog geen opmerkingen geplaatst... Wees de eerste door het formulier hieronder in te vullen.'; $lang['kb_leave_comment'] = 'Laat een opmerking achter'; $lang['kb_thank_you'] = 'Dankuwel'; $lang['kb_comment_added'] = 'Uw opmerking is geplaatst. U wordt automatisch doorverwezen, als dit niet gebeurt'; $lang['kb_click_here'] = 'kunt u hier klikken'; /** * Contact */ $lang['kb_contact_related'] = 'Gerelateerde artikelen'; $lang['kb_contact'] = 'Contact'; $lang['kb_subject'] = 'Onderwerp'; $lang['kb_contact_confirm'] = 'Uw bericht is niet verstuurd. Controleer eerst of bovenstaande berichten uw vraag beantwoorden. Zo niet dan kunt u op bovenstaande knop drukken.'; $lang['kb_submit_message'] = 'Verstuur uw aanvraag'; $lang['kb_thank_you'] = 'Dankuwel'; $lang['kb_thank_you_msg'] = 'Uw bericht is succesvol verzonden.'; $lang['kb_captcha'] = 'Voert u aub de weergegeven tekst in'; /** * Forward */ $lang['kb_success'] = 'Succes'; $lang['kb_forward'] = 'Wacht u alstublieft even terwijl u automatisch wordt doorverwezen, als dit niet gebeurt'; $lang['kb_click_here'] = 'kunt u hier klikken'; /** * General */ $lang['kb_pages'] = 'Pagina\'s'; $lang['kb_yes'] = 'Ja'; $lang['kb_no'] = 'Nee'; $lang['kb_welcome'] = 'Welkom'; $lang['kb_latest_news'] = 'Het laatste LAB21 nieuws'; $lang['kb_logout'] = 'Uitloggen'; $lang['kb_forums'] = 'Hulp Fora'; $lang['kb_support_knowledge_base'] = 'Vraag en antwoord centrum'; $lang['kb_view_site'] = 'Bekijk site'; $lang['kb_please_login'] = 'Logt u alstublieft in'; $lang['kb_enter_details'] = 'Vul hieronder uw inloggegevens in'; $lang['kb_remember_me'] = 'Mij onthouden op deze computer'; $lang['kb_login_invalid'] = 'Ongeldige gebruikersnaam en/of wachtwoord'; /** * Glossary */ $lang['kb_manage_glossary'] = 'Alfabetisch register onderhouden'; $lang['kb_glossary'] = 'Alfabetisch register'; $lang['kb_term'] = 'Term'; $lang['kb_add_term'] = 'Woord toevoegen'; $lang['kb_definition'] = 'Definitie'; $lang['kb_save'] = 'Opslaan'; $lang['kb_save_and_continue'] = 'Opslaan en doorgaan met aanpassen'; /** * Home */ $lang['kb_knowledge_base'] = 'Vraag en antwoord centrum'; $lang['kb_first_time'] = '<strong>Welkom!</strong> Het lijkt erop dat dit de eerste keer is dat u 68kb gebruikt kijk eens op <a href="http://68kb.com/knowledge-base/article/quick-start-guide">de quick start guide</a>. Mocht u hulp nodig hebben, twijfel niet en bezoek onze <a href="http://68kb.com/support">user forums</a>.'; $lang['kb_pending_comments'] = 'Berichten in wachtrij'; $lang['kb_running'] = 'Op dit moment draait versie:'; $lang['kb_license_key'] = 'License Key'; $lang['kb_total_articles'] = 'Totaal aantal artikelen'; $lang['kb_total_categories'] = 'Totaal aantal categorieën'; $lang['kb_total_comments'] = 'Totaal aantal berichten'; $lang['kb_article_search'] = 'Artikelen doorzoeken'; /** * Javascript */ $lang['kb_please_enter'] = 'Voert u alstublieft een waarde in bij dit veld'; $lang['kb_are_you_sure'] = 'Weet u zeker dat u deze regel wilt verwijderen? Je kunt dit niet ongedaan maken!'; $lang['kb_required'] = 'Verplicht'; $lang['kb_uri_desc'] = ''; $lang['kb_please_goback'] = 'Ga alstublieft terug en zoek een oplossing voor deze fouten.'; /** * Modules */ $lang['kb_admin'] = 'Admin'; $lang['kb_modules'] = 'Modules'; $lang['kb_name'] = 'Naam'; $lang['kb_description'] = 'Beschrijving'; $lang['kb_version'] = 'Versie'; $lang['kb_actions'] = 'Acties'; $lang['kb_activate'] = 'Activeren'; $lang['kb_activated'] = 'Module Geactiveerd'; $lang['kb_deactivate'] = 'Deactiveren'; $lang['kb_deactivated'] = 'Module Gedeactiveerd'; $lang['kb_deleted'] = 'Module Verwijderd'; $lang['kb_delete_module'] = 'Weet u zeker dat u deze regel wilt verwijderen? \nLet op dat deze actie alleen verwijderd uit de database. U moet nog steeds verwijderen uit de \"my-modules\" folder.'; /** * Nav */ $lang['kb_home'] = 'Home'; $lang['kb_dashboard'] = 'Dashboard'; $lang['kb_article'] = 'Artikel'; $lang['kb_articles'] = 'Artikelen'; $lang['kb_manage_articles'] = 'Beheer Artikelen'; $lang['kb_add_article'] = 'Voeg Artikel Toe'; $lang['kb_categories'] = 'Categorieën'; $lang['kb_manage_categories'] = 'Beheer Categorieën'; $lang['kb_add_category'] = 'Voeg Categorie Toe'; $lang['kb_settings'] = 'Instellingen'; $lang['kb_glossary'] = 'Alfabetisch Register'; $lang['kb_users'] = 'Gebruikers'; /** * Search */ $lang['kb_search_kb'] = 'Doorzoek de vragen en antwoorden'; $lang['kb_search_results'] = 'Zoekresultaten'; $lang['kb_no_results'] = 'Sorry we konden geen artikelen vinden die voldoen aan u zoekterm'; /** * Settings */ $lang['kb_main_settings'] = 'Hoofdinstellingen'; $lang['kb_site_title'] = 'Titel van site'; $lang['kb_site_keywords'] = 'Site Keywords'; $lang['kb_site_description'] = 'Site Beschrijving'; $lang['kb_email'] = 'Emailadres'; $lang['kb_max_search'] = 'Maximaal Aantal Zoekresultaten'; $lang['kb_templates'] = 'Templates'; $lang['kb_current_template'] = 'Huidige Theme'; $lang['kb_available_templates'] = 'Beschikbaar Themes'; $lang['kb_allow_comments'] = 'Sta opmerkingen toe'; $lang['kb_cache_time'] = 'Cache Tiijd'; $lang['kb_delete_cache'] = 'Verwijder Cache'; $lang['kb_cache_deleted'] = 'Cache succesvol verwijderd'; $lang['kb_cache_desc'] = 'Het aantal minuten dat de pagina\'s gecached moeten blijven. Voer 0 in om cachen uit te zetten. Maak de folder includes/application/cache writable.'; /** * Stats */ $lang['kb_stats'] = 'Statistieken'; $lang['kb_summary'] = 'Samenvatting'; $lang['kb_most_viewed'] = 'Meest bekeken'; $lang['kb_search_log'] = 'Zoek Log'; $lang['kb_searches'] = 'Aantal keer gezocht'; /** * Users */ $lang['kb_manage_users'] = 'Beheer Gebruikers'; $lang['kb_add_user'] = 'Voeg gebruiker toe'; $lang['kb_username'] = 'Gebruikersnaam'; $lang['kb_password'] = '<PASSWORD>'; $lang['kb_confirmpassword'] = '<PASSWORD>'; $lang['kb_firstname'] = 'Voornaam'; $lang['kb_lastname'] = 'Achternaam'; $lang['kb_name'] = 'Naam'; $lang['kb_email'] = 'Emailadres'; $lang['kb_user_group'] = 'Gebruikersgroep'; $lang['kb_username_inuse'] = 'De gebruikersnaam wordt al gebruikt.'; $lang['kb_password_change'] = 'Als u het wachtwoord wilt wijzigen vul dan hieronder tweemaal het nieuwe wachtwoord in, anders kunt u de velden leeg laten.'; /** * Utilities */ $lang['kb_utilities'] = 'Hulpmiddelen'; $lang['kb_optimize_db'] = 'Database optimaliseren'; $lang['kb_repair_db'] = 'Database repareren'; $lang['kb_backup_db'] = 'Database backup maken'; $lang['kb_optimize_success'] = 'Database met succes geoptimaliseerd'; $lang['kb_repair_success'] = 'Database met succes gerepareerd'; /* End of file kb_lang.php */ /* Location: ./upload/includes/application/language/dutch/kb_lang.php */ <file_sep>/upload/includes/application/models/category_model.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Category Model * * This class is used to handle the categories data. * * @package 68kb * @subpackage Models * @category Models * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/categories.html * @version $Id: category_model.php 89 2009-08-13 01:54:20Z suzkaw68 $ */ class Category_model extends model { /** * Constructor * * @uses get_settings * @return void */ function __construct() { parent::__construct(); log_message('debug', 'Category Model Initialized'); } // ------------------------------------------------------------------------ /** * Delete Category * * @param int $cat_id The id of the category to delete. * @return true on success. */ function delete_category($cat_id) { $cat_id=(int)trim($cat_id); $this->db->delete('categories', array('cat_id' => $cat_id)); if ($this->db->affected_rows() > 0) { $this->db->cache_delete_all(); return true; } else { return false; } } // ------------------------------------------------------------------------ /** * Edit Category * * @param array $data An array of data. * @uses format_uri * @return true on success. */ function edit_category($cat_id, $data) { $cat_id = (int)$cat_id; if (isset($data['cat_uri']) && $data['cat_uri'] != '') { $data['cat_uri'] = $this->format_uri($data['cat_uri'], 0, $cat_id); } else { $data['cat_uri'] = $this->format_uri($data['cat_name'], 0, $cat_id); } $this->db->where('cat_id', $cat_id); $this->db->update('categories', $data); if ($this->db->affected_rows() > 0) { $this->db->cache_delete_all(); return true; } else { log_message('info', 'Could not edit the category id '. $cat_id); return false; } } // ------------------------------------------------------------------------ /** * Add Category * * @param array $data An array of data. * @uses format_uri * @return mixed Id on success. */ function add_category($data) { if (isset($data['cat_uri']) && $data['cat_uri'] != '') { $data['cat_uri'] = $this->format_uri($data['cat_uri']); } else { $data['cat_uri'] = $this->format_uri($data['cat_name']); } $this->db->insert('categories', $data); if ($this->db->affected_rows() > 0) { $this->db->cache_delete_all(); return $this->db->insert_id(); } else { return false; } } // ------------------------------------------------------------------------ /** * Insert Article2Cats * * Insert the selected categories * into the article2cat table. * * @access public * @param int - The article id * @param array - The array of cats. * @return bool */ function insert_cats($id, $arr) { $this->db->delete('article2cat', array('article_id' => $id)); if (is_array($arr)) { foreach($arr as $catObj) { $data = array('article_id' => $id, 'category_id' => $catObj); $this->db->insert('article2cat', $data); } return true; } else { return false; } } // ------------------------------------------------------------------------ /** * Check URI * * Checks other categories for the same uri. * * @param string $cat_uri The uri name * @return boolean True if checks out ok, false otherwise */ function check_uri($cat_uri, $cat_id=false) { if ($cat_id !== false) { $cat_id=(int)$cat_id; $this->db->select('cat_uri')->from('categories')->where('cat_uri', $cat_uri)->where('cat_id !=', $cat_id); } else { $this->db->select('cat_uri')->from('categories')->where('cat_uri', $cat_uri); } $query = $this->db->get(); if ($query->num_rows() > 0) { return false; } else { return true; } } // ------------------------------------------------------------------------ /** * Format URI * * Formats a category uri. * * @param string $cat_uri The uri name * @uses check_uri * @uses remove_accents * @uses seems_utf8 * @uses utf8_uri_encode * @uses format_uri * @return string A cleaned uri */ function format_uri($cat_uri, $i=0, $cat_id=false) { $cat_uri = strip_tags($cat_uri); // Preserve escaped octets. $cat_uri = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $cat_uri); // Remove percent signs that are not part of an octet. $cat_uri = str_replace('%', '', $cat_uri); // Restore octets. $cat_uri = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $cat_uri); $cat_uri = remove_accents($cat_uri); if (seems_utf8($cat_uri)) { if (function_exists('mb_strtolower')) { $cat_uri = mb_strtolower($cat_uri, 'UTF-8'); } $cat_uri = utf8_uri_encode($cat_uri, 200); } $cat_uri = strtolower($cat_uri); $cat_uri = preg_replace('/&.+?;/', '', $cat_uri); // kill entities $cat_uri = preg_replace('/[^%a-z0-9 _-]/', '', $cat_uri); $cat_uri = preg_replace('/\s+/', '-', $cat_uri); $cat_uri = preg_replace('|-+|', '-', $cat_uri); $cat_uri = trim($cat_uri, '-'); if ($i>0) { $cat_uri=$cat_uri."-".$i; } if (!$this->check_uri($cat_uri, $cat_id)) { $i++; $cat_uri=$this->format_uri($cat_uri, $i); } return $cat_uri; } // ------------------------------------------------------------------------ /** * Get an array of categories. * * Get an array of categories and for use * in a select list. * * @access public * @param string the prefix to indent nested cats with. * @param int the parent id * @param bool Inside the admin * @return array */ function get_cats_for_select($prefix='', $parent=0, $article_id='', $admin=FALSE) { $arr = array(); $this->db->select('cat_id,cat_uri,cat_name,cat_description')->from('categories')->orderby('cat_order', 'DESC')->orderby('cat_name', 'asc')->where('cat_parent', $parent); if ($admin==FALSE) { $this->db->where('cat_display', 'Y'); } $query = $this->db->get(); //echo $this->db->last_query(); foreach ($query->result() as $row) { $rs['cat_name']=$prefix . $row->cat_name; $rs['cat_id']=$row->cat_id; $rs['cat_uri']=$row->cat_uri; $rs['cat_description']=$row->cat_description; $id=$row->cat_id; if ($article_id <> '') { $this->db->from('article2cat')->where('article_id', $article_id)->where('category_id', $row->cat_id); $art2cat = $this->db->get(); if ($art2cat->num_rows() > 0) { $rs['selected'] = 'Y'; } else { $rs['selected'] = 'N'; } } else { $rs['selected'] = 'N'; } array_push($arr, $rs); $arr = array_merge($arr, $this->get_cats_for_select($prefix .'&nbsp;&nbsp;&raquo;&nbsp;', $id, $article_id,$admin)); } return $arr; } // ------------------------------------------------------------------------ /** * Get Categories By Parent. * * Get an array of categories that have the * same parent. * * @access public * @param int the parent id * @return array */ function get_categories_by_parent($parent) { $arr = array(); $this->db->from('categories')->orderby('cat_order', 'DESC')->orderby('cat_name', 'asc')->where('cat_parent', $parent)->where('cat_display', 'Y'); $query = $this->db->get(); return $query; } // ------------------------------------------------------------------------ /** * Get Category By URI. * * Get a single category from its cat_uri * * @access public * @param string the unique uri * @return array */ function get_cat_by_uri($uri) { $this->db->from('categories')->where('cat_uri', $uri)->where('cat_display', 'Y'); $query = $this->db->get(); $data = $query->row(); $query->free_result(); return $data; } // ------------------------------------------------------------------------ /** * Get Category By ID. * * Get a single category from its id * * @access public * @param int the unique id * @return array */ function get_cat_by_id($id) { $id=(int)$id; $this->db->from('categories')->where('cat_id', $id); $query = $this->db->get(); $data = $query->row(); $query->free_result(); return $data; } // ------------------------------------------------------------------------ /** * Get Category Name By ID. * * Get a single category Name * * @access public * @param int the unique id * @return string */ function get_cat_name_by_id($id) { $this->db->select('cat_name')->from('categories')->where('cat_id', $id); $query = $this->db->get(); $data = $query->row(); $query->free_result(); return $data->cat_name; } // ------------------------------------------------------------------------ /** * Get Category By Article. * * Get a list of categories an article is associated with. * * @access public * @param int the unique id * @return array */ function get_cats_by_article($id) { $this->db->select('*'); $this->db->from('article2cat'); $this->db->join('categories', 'article2cat.category_id = categories.cat_id', 'left'); $this->db->where('article_id', $id); $this->db->where('cat_display', 'Y'); $query = $this->db->get(); return $query; } // ------------------------------------------------------------------------ /** * Get Category Tree. * * Get a recursive list of categories. * * @access public * @param string Orderby * @param string Order ASC or DESC * @param int The parent to start at * @return array */ function get_tree($orderby='cat_name', $order='ASC', $parent=0) { $cat = array(); $this->db->from('categories')->orderby('cat_order', 'DESC')->orderby($orderby, $order)->where('cat_parent', $parent)->where('cat_display', 'Y'); $query = $this->db->get(); foreach ($query->result() as $row) { $rs['cat_id']=$row->cat_id; $rs['cat_name']=$row->cat_name; $rs['cat_parent']=$row->cat_parent; $rs['cat_url']=$row->cat_uri; $rs['cat_total'] = $this->get_category_count($row->cat_id); $rs['cat_link'] = site_url("category/".$row->cat_uri."/"); $cat[]=$rs; } return $cat; } // ------------------------------------------------------------------------ /** * Get Category Tree. * * Get a recursive list of categories. * * @access public * @param string Orderby * @param string Order ASC or DESC * @param int The parent to start at * @return array */ function get_category_count($cat=0) { $this->db->from('articles'); $this->db->join('article2cat', 'articles.article_id = article2cat.article_id', 'left'); $this->db->where('category_id', $cat); $this->db->where('article_display', 'Y'); return $this->db->count_all_results(); } // ------------------------------------------------------------------------ /** * Get Sub Categories * * @param int parent id * @return mixed */ function get_sub_categories($parent) { $parent = (int)$parent; $this->db->select('cat_id,cat_uri,cat_name,cat_parent')->from('categories')->where('cat_parent', $parent)->where('cat_display !=', 'N')->order_by('cat_order DESC, cat_name ASC'); $query = $this->db->get(); if ($query->num_rows() > 0) { $cat = $query->result_array(); $query->free_result(); return $cat; } else { return false; } } } /* End of file category_model.php */ /* Location: ./upload/includes/application/models/category_model.php */ <file_sep>/upload/includes/application/controllers/glossary.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Glossary Controller * * Handles the glossary page * * @package 68kb * @subpackage Controllers * @category Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/glossary.html * @version $Id: glossary.php 46 2009-07-28 17:32:07Z suzkaw68 $ */ class Glossary extends Controller { function __construct() { parent::__construct(); log_message('debug', 'Glossary Controller Initialized'); $this->load->model('init_model'); $this->load->model('category_model'); } // ------------------------------------------------------------------------ /** * Index Controller * * Show the home page * * @access public */ function index() { $this->db->from('glossary')->orderby('g_term', 'asc'); $query = $this->db->get(); $data['title'] = $this->lang->line('kb_glossary') . ' | '. $this->init_model->get_setting('site_name'); $data['glossary'] = $query; $data['letter'] = range('a', 'z'); $this->init_model->display_template('glossary', $data); } // ------------------------------------------------------------------------ /** * Term * * Find the key term * * @access public */ function term($term='') { $term = $this->input->xss_clean($term); $this->db->from('glossary'); if($term == 'sym') { $this->db->where('g_term LIKE', '.%'); $this->db->orwhere('g_term LIKE', '0%'); $this->db->orwhere('g_term LIKE', '1%'); $this->db->orwhere('g_term LIKE', '2%'); $this->db->orwhere('g_term LIKE', '3%'); $this->db->orwhere('g_term LIKE', '4%'); $this->db->orwhere('g_term LIKE', '5%'); $this->db->orwhere('g_term LIKE', '6%'); $this->db->orwhere('g_term LIKE', '7%'); $this->db->orwhere('g_term LIKE', '8%'); $this->db->orwhere('g_term LIKE', '9%'); } else { $this->db->where('g_term LIKE', $term.'%'); } $query = $this->db->get(); $data['glossary'] = $query; $data['letter'] = range('a', 'z'); $data['title'] = $this->lang->line('kb_glossary') . ' | '. $this->init_model->get_setting('site_name'); $this->init_model->display_template('glossary', $data); } } /* End of file glossary.php */ /* Location: ./upload/includes/application/controllers/glossary.php */ <file_sep>/upload/themes/front/default/comments.php <div class="commentarea"> <h1 class="title" id="comments"><?php echo $comments_total; ?> <?php echo lang('kb_user_comments'); ?></h1> <div class="commentlist"> <?php if (isset($comments) && $comments->num_rows() > 0): ?> <?php $i=1; foreach($comments->result() as $row): ?> <div class="comment clearfix alt" id="comment-<?php echo $row->comment_ID; ?>"> <div class="pic"> <img class="gravatar" src="<?php echo gravatar( $row->comment_author_email, "PG", "40", "wavatar" ); ?>" /> </div> <div class="thecomment"> <div class="author"><?php echo $row->comment_author; ?></div> <div class="time"><?php echo date($this->config->item('comment_date_format'), $row->comment_date); ?></div> <div class="clear"></div> <div class="text"> <p><?php echo nl2br_except_pre(parse_smileys($row->comment_content, $this->config->item('base_url')."/images/")); ?></p> </div> </div> </div> <?php endforeach; ?> <?php else: ?> <p><?php echo lang('kb_no_comments'); ?></p> <?php endif; ?> </div> <a name="comment"></a> <h2 class="title"><?php echo lang('kb_leave_comment'); ?></h2> <?php if(validation_errors()) { echo '<div class="error">'.validation_errors().'</div>'; } ?> <form action="<?php echo site_url('article/comment'); ?>" method="post" id="comment_form"> <p> <input class="text_input" type="text" name="comment_author" id="comment_author" value="<?php echo (isset($comment_author)) ? form_prep($comment_author) : ''; ?>" tabindex="1" /> <label for="comment_author"><?php echo lang('kb_name'); ?></label> </p> <p> <input class="text_input" type="text" name="comment_author_email" id="comment_author_email" value="<?php echo (isset($comment_author_email)) ? form_prep($comment_author_email) : ''; ?>" tabindex="2" /><label for="comment_author_email"><?php echo lang('kb_email'); ?></label> </p> <p> <textarea class="text_input text_area" name="comment_content" id="comment_content" rows="7" tabindex="4"></textarea> </p> <p> <input name="submit" class="form_submit" type="submit" id="submit" tabindex="5" value="<?php echo lang('kb_save'); ?>" /> <input type="hidden" name="comment_article_ID" value="<?php echo $article->article_id; ?>" /> <input type="hidden" name="uri" value="<?php echo $article->article_uri; ?>" /> </p> </form> </div><file_sep>/upload/themes/admin/default/stats/main.php <div id="tabs"> <ul> <li><a href="<?php echo site_url('admin/stats/');?>" class="active"><span><?php echo $this->lang->line('kb_summary'); ?></span></a></li> <li><a href="<?php echo site_url('admin/stats/viewed');?>"><span><?php echo $this->lang->line('kb_most_viewed'); ?></span></a></li> <li><a href="<?php echo site_url('admin/stats/searchlog');?>"><span><?php echo $this->lang->line('kb_search_log'); ?></span></a></li> <li><a href="<?php echo site_url('admin/stats/rating');?>"><span>Rating</span></a></li> </ul> </div> <div class="clear"></div> <div class="wrap"> <table> <tr> <td>Total Articles: </td><td><?php echo $articles; ?></td> </tr> <tr> <td>Total Article Views: </td><td><?php echo $views; ?></td> </tr> <tr> <td>Total Categories: </td><td><?php echo $cats; ?></td> </tr> </table> </div><file_sep>/upload/themes/admin/default/login.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>68 KB Administration</title> <link href="<?php echo base_url();?>themes/admin/default/style/default.css" rel="stylesheet" type="text/css" /> <script language="javascript" type="text/javascript"> <!-- function checkform(frm) { if (frm.username.value == '') { alert("<?php echo lang('kb_please_enter'); ?> \"<?php echo lang('kb_username');?>\"."); frm.username.focus(); return(false); } if (frm.password.value == '') { alert("<?php echo lang('kb_please_enter'); ?> \"<?php echo lang('kb_password');?>\"."); frm.password.focus(); return(false); } } function setfocus() { document.forms[0].username.focus() } //--> </script> </head> <body onload="setfocus();"> <?php $attributes = '';//array('id' => 'login', 'onsubmit' => 'return checkform(this)'); echo form_open('admin/kb/login', $attributes); ?> <div id="loginwrapper"> <div id="header"></div> <div id="content"> <h2><?php echo lang('kb_please_login');?></h2> <div class="wrap"> <fieldset> <legend><?php echo lang('kb_enter_details'); ?></legend> <?php echo validation_errors(); ?> <table width="100%"> <?php if (isset($error) && $error<>""): ?> <tr> <td colspan="2" align="center"><span class="problem" style="padding: 5px; color: red; text-align: center;"><?php echo $error; ?></span></td> </tr> <?php endif; ?> <tr> <td><label for="username"><?php echo lang('kb_username');?>:</label></td> <td><input name="username" type="text" id="username" tabindex="1" /></td> </tr> <tr> <td><label for="password"><?php echo lang('kb_password');?>:</label></td> <td><input name="password" type="password" id="password" tabindex="2" /></td> </tr> <tr> <td>&nbsp;</td> <td><input type="checkbox" name="remember" id="remember" value="Y" />&nbsp;<label for="remember"><?php echo lang('kb_remember_me'); ?></label></td> </tr> <tr> <td colspan="2" valign="top"> <div align="center"> <input name="action" type="hidden" id="action" value="login" /> <input name="submit" type="submit" id="submit" value="Submit" /> </div> </td> </tr> </table> </fieldset> </div> </div> </div> <input type="hidden" name="goto" value="<?php //echo $goto; ?>" /> </form> <div id="footer"> &copy; 2008 68 KB <br /> Time: <?=$this->benchmark->elapsed_time();?> - Memory: <?=$this->benchmark->memory_usage();?> </div> </body> </html><file_sep>/upload/my-modules/developer/config.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * jwysiwyg * * @package 68kb * @subpackage Module * @category Module * @author 68kb Dev Team * @link http://68kb.com/user_guide/developer/modules.html * @version $Id: config.php 84 2009-08-05 03:26:00Z suzkaw68 $ */ /** * Module Name * * Used to identify the module file structure and call module functions. */ $data['module']['name'] = "developer"; /** * Module Display Name * * Used to give a user friendly name in the modules administration area. */ $data['module']['displayname'] = "Developer Module"; /** * Module Description * * Used to provide a brief description of the module's purpose. */ $data['module']['description'] = "This module is used to show developers how the module system works."; /** * Module Version * * Current version of the module. */ $data['module']['version'] = "v1.1"; /* End of file config.php */ /* Location: ./upload/my-modules/developer/config.php */ <file_sep>/upload/my-modules/jwysiwyg/config.php <?php /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * jwysiwyg * * @package 68kb * @subpackage Module * @category Module * @author 68kb Dev Team * @link http://68kb.com/user_guide/controller/article.html * @version $Id: config.php 45 2009-07-28 17:20:56Z suzkaw68 $ */ /** * Module Name * * Used to identify the module file structure and call module functions. */ $data['module']['name'] = "jwysiwyg"; /** * Module Display Name * * Used to give a user friendly name in the modules administration area. */ $data['module']['displayname'] = "WYSIWYG jQuery Plugin"; /** * Module Description * * Used to provide a brief description of the module's purpose. */ $data['module']['description'] = "This module is an inline content editor to allow editing rich HTML content on the fly."; /** * Module Version * * Current version of the module. */ $data['module']['version'] = "v1.0"; /* End of file config.php */ /* Location: ./upload/my-modules/jwysiwyg/config.php */ <file_sep>/upload/themes/setup/install-step1.php <h2>Installation Step 1 - Checking Settings</h2> <div id="form" class="wrap"> <form action="<?php echo site_url('setup/kb/run'); ?>" method="post"> <strong>Server Settings:</strong> <table width="100%" align="center" cellpadding="5" cellspacing="0" class="modules"> <tr> <td width="50%" class="row1">PHP Version</td> <td width="50%" class="row1"> <?php if (version_compare(phpversion(), "5.1.0", ">=")) { echo phpversion() ." Installed"; } else { $error=TRUE; echo "<span class='spam'>".phpversion() ." Installed</span>"; } ?> </td> </tr> <tr> <td class="row2">MySQL Version</td> <td class="row2"> <?php if($this->db->version() > '3.23') { echo $this->db->version() ." Installed"; } else { $error=TRUE; echo "<span class='spam'>".$this->db->version() ." Installed</span>"; } ?> </td> </tr> </table> <br /> <strong>CHMOD Settings:</strong> <table width="100%" align="center" cellpadding="5" cellspacing="0" class="modules"> <tr> <td class="row2">uploads</td> <td class="row2"> <?php if($uploads != 'Ok') $error=TRUE; ?> <?php echo $uploads; ?> </td> </tr> </table> <br /> <strong>Administration Settings:</strong> <table width="100%" align="center" cellpadding="5" cellspacing="0" class="modules"> <tr> <td width="50%" class="row1">Admin Username</td> <td width="50%" class="row1"> <input type="text" name="username" /> </td> </tr> <tr> <td class="row2">Admin Password</td> <td class="row2"> <input type="password" name="password" /> </td> </tr> <tr> <td width="50%" class="row1">Admin Email</td> <td width="50%" class="row1"> <input type="text" name="adminemail" /> </td> </tr> <tr> <td width="50%" class="row1">Overwrite Tables:</td> <td width="50%" class="row1"> <input type="checkbox" name="drop" value="Y" /> </td> </tr> </table> <p align="right"> <?php if($error==TRUE) { echo "<strong>Please fix the above errors and refresh this page."; } else { ?> <input type="hidden" name="step" value="<?php echo $nextStep; ?>" /> <input type="submit" name="submit" class="save" value="Next Step" /> <?php } ?> </p> </form> </div><file_sep>/upload/includes/application/helpers/articles_helper.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Articles Helper * * This is used to display a list of articles. * * @subpackage Plugins * @link http://68kb.com/user_guide/developer/plugin-articles.html */ if ( ! function_exists('articles_plugin')) { function articles_plugin($params = '') { $CI =& get_instance(); // Default Options $limit = 10; $author = ''; $category = ''; $keywords = ''; $sort = 'article_rating'; $order_by = 'desc'; // random, asc, desc $return = FALSE; // Parse what they are requesting parse_str($params, $options); // Validate the formatting foreach ($options as $_key => $_value) { switch ($_key) { case 'limit': case 'author': $$_key = (int) $_value; break; case 'featured': case 'order_by': case 'sort': case 'keywords': $$_key = (string) $_value; break; case 'category': case 'return': $$_key = $_value; break; } } // Do the articles query $CI->db->from('articles')->where('article_display', 'Y'); if ($category !== '') { $CI->db->join('article2cat', 'articles.article_id = article2cat.article_id', 'left'); } if ($author !== '') { $CI->db->where('article_author', $author); } if ($keywords !== '') { $CI->db->like('article_keywords', $keywords); } if ($category !== '' && ctype_digit($category)) // Single category { $CI->db->where('category_id', $category); } elseif ($category !== '') // Passing multiple categories { $CI->db->where_in('category_id', $category); } $CI->db->order_by($sort, $order_by); $CI->db->limit($limit); $query = $CI->db->get(); if ($query->num_rows() == 0) // no records so we can't continue { return FALSE; } // parse the list $output = '<ul class="articles">'; foreach ($query->result() as $row) { $output .= '<li><a href="'. site_url("article/".$row->article_uri."/").'">'.$row->article_title.'</a></li>'; } $output .= '</ul>'; // send it off if ($return) { return $output; } else { echo $output; } } } /* End of file articles_helper.php */ /* Location: ./upload/includes/application/helpers/articles_helper.php */ <file_sep>/upload/themes/setup/layout.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>68 KB Setup</title> <script type="text/javascript" src="<?php echo base_url();?>javascript/overlib/overlib.js"><!-- overLIB (c) <NAME> --></script> <link href="<?php echo base_url();?>themes/admin/default/style/default.css" rel="stylesheet" type="text/css" /> <script type="text/JavaScript"> <!-- function MM_openBrWindow(theURL,winName,features) { //v2.0 window.open(theURL,winName,features); } function disableDefault(){ event.returnValue = false; return false; } //--> </script> </head> <body> <div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div> <div id="wrapper"> <div id="header"></div> <div id="content"> <!-- // Content // --> <?php echo $body; ?> <!-- // End Content // --> </div> </div> <div id="footer"> &copy; 2009 68 KB - <?php echo KB_VERSION; ?> <br /> Time: <?=$this->benchmark->elapsed_time();?> - Memory: <?=$this->benchmark->memory_usage();?> </div> </body> </html><file_sep>/README.md # 68KB Installation / Upgrade ## Installing 68KB Please visit our installation instructions for complete details: <http://68kb.com/user_guide/installation/index.html> ## Upgrading 68KB Please visit our upgrading instructions for complete details on upgrading: <http://68kb.com/user_guide/installation/upgrading.html> ## Help & Support If you get stuck or need any help we offer many ways to help you out. * User Guide - <http://68kb.com/user_guide/> * Support Forums - <http://68kb.com/support/><file_sep>/user_guide/developer/config.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US" xml:lang="en-US"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Config : 68KB User Guide</title> <link href="../css/style.css" rel="stylesheet" type="text/css" media="all" /> <script type="text/javascript" src="../js/jquery.min.js"></script> <script type="text/javascript" src="../js/main.js"></script> <script type="text/javascript" src="../js/nav.js"></script> <meta http-equiv='expires' content='-1' /> <meta http-equiv='pragma' content='no-cache' /> <meta name='robots' content='all' /> </head> <body> <div id="panel"> <div id="panel_contents"> <script type="text/javascript">create_menu('../');</script> </div> </div> <div id="header"> <div class="container_16"> <div id="logo"> <div class="grid_10"> <img src="../images/logo-68kb.png" alt="logo" width="181" height="53" /> <a name="top" id="top"></a> </div> <div class="grid_6"> <div class="panel_button" style="visibility: visible;"> <a class="open" href="../toc.html">Table of Contents</a> </div> <div class="panel_button" id="hide_button" style="display: none;"> <a class="close" href="#">Close</a> </div> </div> <div class="clear"></div> <div id="title_area" class="grid_9"> <h4>User Guide v1.0.0 RC3</h4> </div> <div class="grid_7 search_area"> <form method="get" action="http://www.google.com/search"> <input type="hidden" name="as_sitesearch" id="as_sitesearch" value="68kb.com/user_guide/" /><input id="search" type="text" size="31" maxlength="255" name="s" value="Search the user guide" />&nbsp;<input type="submit" class="submit" name="sa" value="Go" /> </form> </div> <div class="clear"></div> </div> </div> </div> <p> <br class="clear" /> </p> <div class="container_16 main"> <div id="content" class="grid_16"> <div id="breadcrumb"> <a href="http://68kb.com/">68KB Home</a> &rarr; <a href="../index.html">User Guide Home</a> &rarr; Config </div> <h1>Config File</h1> <p>The config file is located at <dfn>settings/config.php</dfn> and should be opened in a text editor to make changes. Below is a list of all settings included in this file. </p> <table cellpadding="0" cellspacing="1" border="0" style="width:100%" class="tableborder"> <tr> <th>URL Settings</th> <th>Regional Settings</th> <th>Advanced</th> </tr> <tr> <td class="td" valign="top"> <ul> <li><a href="#base_url">Base Url</a></li> <li><a href="#index_file">Index File</a></li> <li><a href="#url_suffix">URL Suffix</a></li> </ul> </td> <td class="td" valign="top"> <ul> <li><a href="#language">Language</a></li> <li><a href="#date_formatting">Date Formatting</a></li> <li><a href="#charset">Charset</a></li> <li><a href="#time_reference">Master Time Reference</a></li> </ul> </td> <td class="td" valign="top"> <ul> <li><a href="#cache_path">Cache Path</a></li> <li><a href="#encryption_key">Encryption Key</a></li> <li><a href="#modules_on">Allow Modules</a></li> <li><a href="#compress_output">Output Compression</a></li> </ul> </td> </tr> </table> <h3 id="base_url">Base Url</h3> <p>URL to your 68KB root. Typically this will be your base URL, <strong>WITH</strong> a trailing slash. Please note that we have included code to try and auto guess this but is not 100% foil proof.</p> <code>$config['base_url'] = 'http://yoursite.com/';</code> <p class="top"><a href="#top">Back to Top</a></p> <h3 id="index_file">Index File</h3> <p>Typically this will be your index.php file, unless you've renamed it to something else. If you are using <a href="../developer/urls.html">mod_rewrite</a> to remove the page set this variable so that it is blank.</p> <code>$config['index_page'] = "index.php";</code> <p class="top"><a href="#top">Back to Top</a></p> <h3 id="url_suffix">URL Suffix</h3> <p>This option allows you to add a suffix to all URLs generated.</p> <code>$config['url_suffix'] = "";</code> <p>For example, if a URL is this: <dfn>example.com/index.php/category/my_cat</dfn> you could optionally add a suffix, like <kbd>.html</kbd>, making the page appear to be of a certain type: <dfn>example.com/index.php/category/my_cat<kbd>.html</kbd></dfn></p> <p class="top"><a href="#top">Back to Top</a></p> <h3 id="language">Language</h3> <p>This determines which set of language files should be used. Make sure there is an available translation if you intend to use something other than english.</p> <code>$config['language'] = "english";</code> <p>Please see <a href="../advanced/translate.html">Translate</a> for more info.</p> <p class="top"><a href="#top">Back to Top</a></p> <h3 id="date_formatting">Date Formatting</h3> <p>This is the default date formating. Check <a href="http://php.net/date">http://php.net/date</a> for options.</p> <code>$config['long_date_format'] = 'F j, Y H:i:s';<br /> $config['short_date_format'] = 'Y-m-d h:i a';</code> <p class="top"><a href="#top">Back to Top</a></p> <h3 id="charset">Charset</h3> <p>This determines which character set is used by default in various methods that require a character set to be provided. It is not recommended to change this once you have data in your database.</p> <code>$config['charset'] = "UTF-8";</code> <p class="top"><a href="#top">Back to Top</a></p> <h3 id="cache_path">Cache Path</h3> <p>This is the location where 68KB will store cached files if you enable caching. Full server path including trailing slash.</p> <code>$config['cache_path'] = ROOTPATH .'cache/';</code> <p class="top"><a href="#top">Back to Top</a></p> <h3 id="encryption_key">Encryption Key</h3> <p>If you use the Encryption class or the Sessions class with encryption enabled you MUST set an encryption key.</p> <code>$config['encryption_key'] = "";</code> <p class="important"><strong>Please Note:</strong> If you are going to use this you must set it before people register on your site.</p> <p class="top"><a href="#top">Back to Top</a></p> <h3 id="modules_on">Allow Modules</h3> <p>By setting this to FALSE you can prevent all modules from working. This is useful if you are experiencing a problem and think it is caused by a module.</p> <code>$config['modules_on'] = TRUE;</code> <p class="important"><strong>Please Note:</strong> Before reporting bugs please set this to FALSE to confirm the bug is part of the core.</p> <p class="top"><a href="#top">Back to Top</a></p> <h3 id="compress_output">Output Compression</h3> <p>Enables Gzip output compression for faster page loads. When enabled, the output class will test whether your server supports Gzip. Even if it does, however, not all browsers support compression so enable only if you are reasonably sure your visitors can handle it.</p> <code>$config['compress_output'] = FALSE;</code> <p class="important"><strong>VERY IMPORTANT:</strong> If you are getting a blank page when compression is enabled it means you are prematurely outputting something to your browser. It could even be a line of whitespace at the end of one of your scripts. For compression to work, nothing can be sent before the output buffer is called by the output class. Do not "echo" any values with compression enabled.</p> <p class="top"><a href="#top">Back to Top</a></p> <h3 id="time_reference">Master Time Reference</h3> <p>Options are "local" or "gmt". This pref tells the system whether to use your server's local time as the master "now" reference, or convert it to GMT.</p> <code>$config['time_reference'] = 'local';</code> </div> <div class="clear"></div> </div> <br class="clear" /> <div class="container_16 footer"> <div class="grid_8"> <p class="copy"> © 2009 68KB - All Rights Reserved.<br /> A division of <a href="http://68designs.com">68 Designs, LLC</a> </p> </div> <div class="grid_8 top"> <p> <a href="#top">Back to Top</a> </p> </div> </div> </body> </html><file_sep>/upload/themes/admin/default/settings/utilities.php <h2><?php echo lang('kb_utilities'); ?></h2> <div class="wrap"> <table> <tr> <td><a href="<?php echo site_url('admin/utility/optimize'); ?>"><?php echo lang('kb_optimize_db'); ?></a></td> </tr> <tr> <td><a href="<?php echo site_url('admin/utility/repair'); ?>"><?php echo lang('kb_repair_db'); ?></a></td> </tr> <tr> <td><a href="<?php echo site_url('admin/utility/delete_cache'); ?>"><?php echo lang('kb_delete_cache'); ?></a></td> </tr> <tr> <td><a href="<?php echo site_url('admin/utility/export'); ?>"><?php echo lang('kb_export_html'); ?></a></td> </tr> <tr> <td><a href="<?php echo site_url('admin/utility/backup'); ?>"><?php echo lang('kb_backup_db'); ?></a></td> </tr> </table> </div> <br /> <?php if($this->session->flashdata('message')) echo '<h2>'.$this->session->flashdata('message').'</h2>'; ?> <?php if(isset($table)): ?> <h2><?php echo lang('kb_repair_success'); ?></h2> <div class="wrap"> <ul> <?php foreach($table as $key): ?> <li><?php echo $key; ?></li> <?php endforeach; ?> </ul> </div> <?php endif;?> <?php if(isset($optimized)): ?> <h2><?php echo lang('kb_optimize_success'); ?></h2> <div class="wrap"> <ul> <?php foreach($optimized as $key): ?> <li><?php echo $key; ?></li> <?php endforeach; ?> </ul> </div> <?php endif;?> <?php if(isset($export)): ?> <h2>Export Complete</h2> <div class="wrap"> <ul> <?php foreach($export as $key): ?> <li><?php echo $key; ?></li> <?php endforeach; ?> </ul> </div> <?php endif;?> <file_sep>/upload/includes/application/controllers/admin/kb.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Admin Controller * * Handles the admin home page as well as login and logout. * * @package 68kb * @subpackage Admin_Controllers * @category Admin_Controllers * @author 68kb Dev Team * @link http://68kb.com/ * @version $Id: kb.php 134 2009-12-02 01:29:40Z suzkaw68 $ */ class Kb extends Controller { function __construct() { parent::__construct(); $this->load->model('init_model'); $this->load->library('session'); $this->load->helper('cookie'); $this->load->helper('form'); $this->load->library('auth'); } // ------------------------------------------------------------------------ /** * Index Controller * * Show the admin home page or revert to login * * @access public */ function index() { $this->auth->restrict(); $this->load->helper('gravatar'); $this->load->helper('text'); $this->load->model('init_model', 'init'); $data['nav'] = 'dashboard'; $this->core_events->trigger('admin/home'); // Get article count for virgin notice $data['cats'] = $this->db->count_all('categories'); $data['comment_count'] = $this->db->count_all('comments'); $data['articles'] = $this->db->count_all('articles'); if ($data['articles'] == 0) { $data['first_time'] = TRUE; } $data['install'] = $this->checkinstall(); $data['latest'] = $this->init_model->get_setting('latest'); // Get pending comments $this->db->select('comment_ID, comment_author, comment_author_email, comment_author_IP, comment_date, comment_content, comment_approved, article_title, article_uri'); $this->db->from("comments"); $this->db->join('articles', 'comments.comment_article_ID = articles.article_id', 'left'); $this->db->limit(5); $query = $this->db->get(); $data['comments'] = $query; $this->init->display_template('home', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Get News * * Get the latest 68kb news * * @access public */ function get_news() { $this->load->library('simplepie'); $link = 'http://feeds.feedburner.com/68KB'; $feed = new SimplePie(); $feed->set_feed_url($link); $feed->enable_cache(false); $feed->init(); $feed->handle_content_type(); $output = ''; $i = 0; if ($feed->data) { $items = $feed->get_items(); foreach ($items as $item) { if ($i < 3) { $output.="<strong><a href='".$item->get_permalink()."' target='_blank'>".$item->get_title()."</a></strong> - ".$item->get_date('j M Y'); $output.="<p>".$item->get_description() ."</p>"; } $i++; } } echo $output; } // ------------------------------------------------------------------------ /** * Login Controller * * Allow the admin to login * * @access public */ function login() { $this->load->library('form_validation'); $this->form_validation->set_rules('username', 'lang:kb_username', 'required'); $this->form_validation->set_rules('password', '<PASSWORD>', '<PASSWORD>'); $this->form_validation->set_error_delimiters('<p class="error">', '</p>'); $data=''; if ($this->form_validation->run() == false) { $this->load->view('admin/default/login', $data); } else { $login = array($this->input->post('username'), $this->input->post('password')); if($this->auth->process_login($login)) { redirect('admin'); } else { $data['error']=$this->lang->line('kb_login_invalid'); $this->load->view('admin/default/login', $data); } } } // ------------------------------------------------------------------------ /** * Logout Controller * * Log the user out. * * @access public */ function logout() { if ($this->auth->logout()) redirect('/admin/kb/login/'); } // ------------------------------------------------------------------------ /** * Check if the install file exists * * @access private * @param string the body * @return bool */ private function checkinstall() { $file = APPPATH.'controllers/setup/install.php'; if ( ! file_exists($file)) { return false; } return true; } } /* End of file kb.php */ /* Location: ./upload/includes/application/controllers/admin/kb.php */ <file_sep>/upload/includes/application/controllers/admin/stats.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Admin Stats Controller * * Handles displaying stats * * @package 68kb * @subpackage Admin_Controllers * @category Admin_Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/settings.html * @version $Id: stats.php 134 2009-12-02 01:29:40Z suzkaw68 $ */ class Stats extends Controller { /** * Constructor * * Requires needed models and helpers. * * @access public */ function __construct() { parent::__construct(); $this->load->model('init_model'); $this->load->helper('cookie'); $this->load->library('auth'); $this->auth->restrict(); } // ------------------------------------------------------------------------ /** * Index Controller * * @access public */ function index() { $data['nav'] = 'settings'; if ( ! $this->auth->check_level(1)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $views = 0; $data['cats'] = $this->db->count_all('categories'); $data['articles'] = $this->db->count_all('articles'); $this->db->select('article_hits')->from('articles'); $query = $this->db->get(); foreach ($query->result() as $row) { $views += $row->article_hits; } $data['views'] = $views; $this->init_model->display_template('stats/main', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Show most viewed * * @access public */ function viewed() { $data['nav'] = 'settings'; $this->db->from('articles')->orderby('article_hits', 'DESC'); $data['query'] = $this->db->get(); $this->init_model->display_template('stats/viewed', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Search Log * * @access public */ function searchlog() { $data['nav'] = 'settings'; $prefix = $this->db->dbprefix; $this->db->select('searchlog_term, COUNT(*) AS "total"', FALSE); $this->db->group_by('searchlog_term')->order_by('total', 'DESC'); $data['query'] = $this->db->get('searchlog'); $this->init_model->display_template('stats/searchlog', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Search Log * * @access public */ function rating() { $data['nav'] = 'settings'; $this->db->from('articles')->orderby('article_rating', 'DESC')->limit(50); $data['query'] = $this->db->get(); $this->init_model->display_template('stats/rating', $data, 'admin'); } } /* End of file stats.php */ /* Location: ./upload/includes/application/controllers/admin/stats.php */ <file_sep>/upload/includes/application/controllers/admin/modules.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Admin Modules Controller * * Handles the modules. Please see the developer module for a brief * overview or read the documentation. * * @package 68kb * @subpackage Admin_Controllers * @category Admin_Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/developer/modules.html * @version $Id: modules.php 134 2009-12-02 01:29:40Z suzkaw68 $ */ class Modules extends controller { var $modules; function __construct() { parent::__construct(); $this->load->model('init_model'); $this->load->model('modules_model'); $this->load->helper('cookie'); $this->load->library('auth'); $this->auth->restrict(); } // ------------------------------------------------------------------------ /** * Index controller * * Redirects to the Modules->manage() * * @access public */ function index() { //$this->modules_model->load_modules(); //$this->_regenerate(); redirect('admin/modules/manage/'); } // ------------------------------------------------------------------------ /** * List all modules * * @access public */ function manage() { $data['nav'] = 'settings'; if ( ! $this->auth->check_level(1)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $id = (int) $this->uri->segment(4, 0); $action = $this->uri->segment(5,0); if ($id > 0 && ($action == 'activate' || $action == 'deactivate' || $action = 'upgrade' || $action == 'delete')) { $data['msg'] = $this->modules_model->init_module($id, $action); } $data['modules'] = $this->modules_model->load_active(); $data['unactive'] = $this->modules_model->load_unactive(); $this->init_model->display_template('modules/managemodules', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Activate a module * * @access public */ function activate($module) { $this->modules_model->activate($module); $this->session->set_flashdata('msg', lang('kb_activated')); redirect('admin/modules/manage/'); } // ------------------------------------------------------------------------ /** * Upgrade a module * * @access public */ function upgrade($id) { $this->modules_model->init_module($id, 'upgrade'); $this->session->set_flashdata('msg', lang('kb_upgraded')); redirect('admin/modules/manage/'); } // ------------------------------------------------------------------------ /** * Show a modules admin file. * * This is used so you can have module files that are included in the * theme that is in use. This same method is used for both the front * end and the administration. * * @access public */ function show() { $nav = $this->core_events->trigger('admin/template/nav/parent'); $data['nav'] = ( empty($nav) ) ? 'settings': $nav; $name = $this->uri->segment(4, 0); $this->db->from('modules')->where('name', $name); $query = $this->db->get(); //echo $this->db->last_query(); if ($query->num_rows() > 0) { $row = $query->row(); $file = KBPATH .'my-modules/'.$row->directory.'/admin.php'; if (@file_exists($file)) { $data['file'] = $file; $this->init_model->display_template('modules/show', $data, 'admin'); } else { //take me home. redirect('admin'); } } else { redirect('admin'); } } // ------------------------------------------------------------------------ /** * Get Module * * Get a single module * * @access public * @param int the module id * @return bool */ function get_module($id) { $this->db->select('id,name,description,directory,version,active')->from('modules')->where('id', $id); $query = $this->db->get(); $data = $query->row(); //echo $this->db->last_query(); $query->free_result(); return $data; } // ------------------------------------------------------------------------ /** * Try to remove the module directory * * @access private * @param int the module id * @return bool */ function _remove_dir($id) { $this->db->select('name')->from('modules')->where('id', $id); $query = $this->db->get(); $data = $query->row(); $name = $data->name; $query->free_result(); if (file_exists(KBPATH .'my-modules/'.$name.'/config.php')) { $opendir = opendir(KBPATH .'my-modules/'.$name); while (false !== ($module = readdir($opendir))) { // Ignores . and .. that opendir displays if ($module != '.' && $module != '..') { @unlink(KBPATH .'my-modules/'.$name.'/'.$module); } } closedir($opendir); @rmdir(KBPATH .'my-modules/'.$name); } } } /* End of file modules.php */ /* Location: ./upload/includes/application/controllers/admin/modules.php */ <file_sep>/upload/includes/application/helpers/gravatar_helper.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ /** * Gravatar Helper * * @package 68kb * @subpackage Helpers * @category Helpers * @author <NAME> * @link http://codeigniter.com/wiki/Gravatars/ */ /** * Gravatar * * Fetches a gravatar from the Gravatar website using the specified params * * @access public * @param string * @param string * @param integer * @param string * @return string */ function gravatar( $email, $rating = 'X', $size = '80', $default = 'http://gravatar.com/avatar.php' ) { # Hash the email address $email = md5( $email ); # Return the generated URL return "http://gravatar.com/avatar.php?gravatar_id=" .$email."&amp;rating=" .$rating."&amp;size=" .$size."&amp;default=" .$default; } /* End of file gravatar_helper.php */ /* Location: ./upload/includes/application/helpers/gravatar_helper.php */ <file_sep>/upload/includes/application/config/config.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); include(INCPATH .'config.php'); /* |-------------------------------------------------------------------------- | Class Extension Prefix |-------------------------------------------------------------------------- | | This item allows you to set the filename/classname prefix when extending | native libraries. For more information please see the user guide: | | http://codeigniter.com/user_guide/general/core_classes.html | http://codeigniter.com/user_guide/general/creating_libraries.html | */ $config['subclass_prefix'] = 'core_'; /* |-------------------------------------------------------------------------- | Allowed URL Characters |-------------------------------------------------------------------------- | | This lets you specify with a regular expression which characters are permitted | within your URLs. When someone tries to submit a URL with disallowed | characters they will get a warning message. | | As a security measure you are STRONGLY encouraged to restrict URLs to | as few characters as possible. By default only these are allowed: a-z 0-9~%.:_- | | Leave blank to allow all characters -- but only if you are insane. | | DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! | */ $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; /* |-------------------------------------------------------------------------- | Enable Query Strings |-------------------------------------------------------------------------- | | By default CodeIgniter uses search-engine friendly segment based URLs: | example.com/who/what/where/ | | You can optionally enable standard query string based URLs: | example.com?who=me&what=something&where=here | | Options are: TRUE or FALSE (boolean) | | The other items let you set the query string "words" that will | invoke your controllers and its functions: | example.com/index.php?c=controller&m=function | | Please note that some of the helpers won't work as expected when | this feature is enabled, since CodeIgniter is designed primarily to | use segment based URLs. | */ $config['enable_query_strings'] = FALSE; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; $config['directory_trigger'] = 'd'; // experimental not currently in use /* |-------------------------------------------------------------------------- | Session Variables |-------------------------------------------------------------------------- | | 'session_cookie_name' = the name you want for the cookie | 'encrypt_sess_cookie' = TRUE/FALSE (boolean). Whether to encrypt the cookie | 'session_expiration' = the number of SECONDS you want the session to last. | by default sessions last 7200 seconds (two hours). Set to zero for no expiration. | 'time_to_update' = how many seconds between CI refreshing Session Information | */ $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_encrypt_cookie'] = FALSE; $config['sess_use_database'] = FALSE; $config['sess_table_name'] = 'ci_sessions'; $config['sess_match_ip'] = FALSE; $config['sess_match_useragent'] = TRUE; $config['sess_time_to_update'] = 300; /* |-------------------------------------------------------------------------- | Cookie Related Variables |-------------------------------------------------------------------------- | | 'cookie_prefix' = Set a prefix if you need to avoid collisions | 'cookie_domain' = Set to .your-domain.com for site-wide cookies | 'cookie_path' = Typically will be a forward slash | */ $config['cookie_prefix'] = ""; $config['cookie_domain'] = ""; $config['cookie_path'] = "/"; /* |-------------------------------------------------------------------------- | Global XSS Filtering |-------------------------------------------------------------------------- | | Determines whether the XSS filter is always active when GET, POST or | COOKIE data is encountered | */ $config['global_xss_filtering'] = FALSE; /* |-------------------------------------------------------------------------- | Rewrite PHP Short Tags |-------------------------------------------------------------------------- | | If your PHP installation does not have short tag support enabled CI | can rewrite the tags on-the-fly, enabling you to utilize that syntax | in your view files. Options are TRUE or FALSE (boolean) | */ $config['rewrite_short_tags'] = FALSE; /* |-------------------------------------------------------------------------- | Reverse Proxy IPs |-------------------------------------------------------------------------- | | If your server is behind a reverse proxy, you must whitelist the proxy IP | addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR | header in order to properly identify the visitor's IP address. | Comma-delimited, e.g. '10.0.1.200,10.0.1.201' | */ $config['proxy_ips'] = ''; /* |-------------------------------------------------------------------------- | Enable/Disable Migrations |-------------------------------------------------------------------------- | | Migrations are disabled by default for security reasons. | You should enable migrations whenever you intend to do a schema migration | and disable it back when you're done. | | Some more severe security measures might take place in future releases. | */ $config["migrations_enabled"] = TRUE; /* |-------------------------------------------------------------------------- | Migrations Path |-------------------------------------------------------------------------- | | Path to your migrations folder. | Typically, it will be within your application path. | Also, writing permission is required within the migrations path. | */ $config["migrations_path"] = APPPATH . "migrations/"; /* |-------------------------------------------------------------------------- | Migrations version |-------------------------------------------------------------------------- | | This is used to set the default migration for this code base. | Sometimes you want the system to automaticly migrate the database | to the most current migration. Or there might be higher migrations | that are not part of the production env. Setting the migration does | does nothing here. It is a way for a programer to check the config. | | On login you might want to do something like this | $this->migrate->version($this->config->item('migrations_version')); | */ $config["migrations_version"] = 0; /* End of file config.php */ /* Location: ./upload/includes/application/config/config.php */<file_sep>/upload/includes/application/models/modules_model.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Modules Model * * @package 68kb * @subpackage Models * @category Models * @author 68kb Dev Team * @link http://68kb.com/user_guide/developer/modules.html * @version $Id: modules_model.php 91 2009-08-13 02:10:14Z suzkaw68 $ */ class Modules_model extends Model { /** * Instance of database connection class * @access private * @var object */ var $modules_dir = ''; /** * Constructor * * @return void **/ public function __construct() { parent::Model(); log_message('debug', 'Modules_model Initialized'); $this->modules_dir = KBPATH .'my-modules'; } // ------------------------------------------------------------------------ /** * Loads active modules * @return array */ function load_active() { $modules = array(); $this->db->from('modules')->order_by('displayname', 'DESC'); $query = $this->db->get(); $result = $query->result_array(); foreach($result as $row) { if ($this->exists($row['name'])) { $data = $this->get_config($row['name']); if( ! empty($data)) { $row['server_version']=$data['module']['version']; $help_file = $this->modules_dir.'/'.$data['module']['name'].'/readme.txt'; if (file_exists($help_file)) { $row['help_file'] = base_url() .'my-modules/'.$data['module']['name'].'/readme.txt'; } } } $modules[] = $row; } return $modules; } // ------------------------------------------------------------------------ /** * Loads not active modules * * @return array */ function load_unactive() { $opendir = opendir($this->modules_dir); while (false !== ($module = readdir($opendir))) { // Ignores . and .. that opendir displays if ($module != '.' && $module != '..') { // Checks if they have the correct files if ($this->exists($module)) { $this->modules["$module"]['file'] = 'my-modules/'.$module.'/config.php'; } } } closedir($opendir); if (!empty($this->modules)) { //assign $data to null $available_module=array(); $i=0; foreach ($this->modules as $name => $module) { $data = $this->get_config($name); if( ! empty($data)) { $this->modules["$name"]['data'] = $data; $this->db->from('modules')->where('directory', $name); $query = $this->db->get(); if ($query->num_rows() == 0) { //it doesn't exist so not active $available_module[$i]['name']=$data['module']['name']; $available_module[$i]['displayname']=$data['module']['displayname']; $available_module[$i]['version']=$data['module']['version']; $available_module[$i]['description'] = $data['module']['description']; $help_file = $this->modules_dir.'/'.$name.'/readme.txt'; if (file_exists($help_file)) { $available_module[$i]['help']='../my-modules/'.$name.'/readme.txt'; } if (file_exists($this->modules_dir.'/'.$name.'/init.php')) { $available_module[$i]['uninstall']=TRUE; } } $i++; } } return $available_module; } } // ------------------------------------------------------------------------ /** * Get a module's config.php and return the $data array. * If the config.php file is not found or the $data array * is not present it returns an empty array. * * @access private * @param string $moduleName * @return array $mData */ function get_config($module_name) { $m_data = array(); if (file_exists($this->modules_dir.'/'.$module_name.'/config.php')) { include($this->modules_dir.'/'.$module_name.'/config.php'); if (isset($data)) { $m_data = $data; unset($data); } } elseif (file_exists($this->modules_dir.'/'.$module_name.'/events.php')) { include($this->modules_dir.'/'.$module_name.'/events.php'); if (isset($data)) { $m_data = $data; unset($data); } } return $m_data; } // ------------------------------------------------------------------------ /** * Checks if a module exists * * @return boolean True if files exist, false otherwise */ function exists($module_name, $file = 'config.php') { return (@file_exists($this->modules_dir.'/'.$module_name.'/'.$file)) ? true : false; } // ------------------------------------------------------------------------ /** * Activate a module * @param string */ function activate($name) { if ($this->exists($name)) { $data = $this->get_config($name); } $this->db->from('modules')->where('directory', $name); $query = $this->db->get(); if ($query->num_rows() == 0) { //it doesn't exist $module_data = array( 'name' => $data['module']['name'], 'displayname' => $data['module']['displayname'], 'description' => $data['module']['description'], 'directory' => $data['module']['name'], 'version' => $data['module']['version'], 'active' => 1 ); $this->db->insert('modules', $module_data); if($this->db->affected_rows() > 0) { $id = $this->db->insert_id(); $this->db->cache_delete_all(); $this->init_module($id, 'install'); } } else { return false; } } // ------------------------------------------------------------------------ /** * Get a single module * * @param int $id Id of the module. * @return array of results * @access public */ function get_module($id) { $this->db->from('modules')->where('id', $id); $query = $this->db->get(); return $query->row_array(); } // ------------------------------------------------------------------------ /** * Install, uninstall, or upgrade a module. This calls the init file in a module and runs one of the following functions: * install(), uninstall(), or upgrade(). * * @param int $id * @param string $action * */ function init_module($id, $action, $msg = '') { $directory=$this->get_module($id); if( ! $directory) { return false; } if ($this->exists($directory['directory'], '/init.php')) { require_once($this->modules_dir.'/'.$directory['directory'].'/init.php'); } if($action=="deactivate") { if(function_exists('uninstall')) { $msg = uninstall(); } $this->db->delete('modules', array('id' => $id)); return $msg; } elseif($action=="upgrade") { if(function_exists('upgrade')) { upgrade(); } if ($this->exists($directory['directory'])) { $data = $this->get_config($directory['directory']); $module_data = array( 'name' => $data['module']['name'], 'displayname' => $data['module']['displayname'], 'description' => $data['module']['description'], 'directory' => $data['module']['name'], 'version' => $data['module']['version'], 'active' => 1 ); $this->db->where('id', $id); $this->db->update('modules', $module_data); $this->db->cache_delete_all(); } } else { if(function_exists('install')) { install(); } } } } /* End of file modules_model.php */ /* Location: ./upload/includes/application/models/modules_model.php */<file_sep>/upload/includes/application/models/init_model.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Init Model * * This class is a global model used for the majority of your settings. * * @package 68kb * @subpackage Models * @category Models * @author 68kb Dev Team * @link http://68kb.com/ * @version $Id: init_model.php 89 2009-08-13 01:54:20Z suzkaw68 $ */ class Init_model extends Model { /** * User data, stored for embeded methods * * @access private * @var array */ var $settings = array(); /** * Constructor * * @uses get_settings * @return void */ function __construct() { parent::__construct(); log_message('debug', 'Init Model Initialized'); $this->get_settings(); } // ------------------------------------------------------------------------ /** * Get Settings * * Get all the auto loaded settings from the db. * * @return array * @uses this->_cron */ function get_settings() { if ( ! $this->db->table_exists('settings')) { redirect('setup'); } $this->db->select('short_name,value')->from('settings')->where('auto_load', 'yes'); $query = $this->db->get(); foreach ($query->result() as $k=>$row) { $this->settings[$row->short_name] = $row->value; } //check cron $this->_cron(); return $this->settings; } // ------------------------------------------------------------------------ /** * Get Setting (Notice Singular) * * Used to pull out one specific setting from the settings table. * * Here is an example: * <code> * <?php * $this->init_model->get_setting('site_name'); * ?> * </code> * * @access public * @param string * @return mixed */ function get_setting($name) { if ( ! empty($this->settings[$name])) { return $this->settings[$name]; } else { $this->db->select('value')->from('settings')->where('short_name', $name); $query = $this->db->get(); if ($query->num_rows() > 0) { $row = $query->row(); return $row->value; } return FALSE; } } // ------------------------------------------------------------------------ /** * Run Cron * * Runs the internal Cron Job based off the date. * * @return void */ function _cron() { $today=date("Y-m-d"); $this->load->plugin('version'); if ($this->settings['last_cron'] < $today) { $this->load->plugin('version'); $version = checklatest(); $data = array('value' => $version); $this->db->where('short_name', 'latest'); $this->db->update('settings', $data); log_message('info', 'Internal Cron ran'); $data = array('value' => $today); $this->db->where('short_name', 'last_cron'); $this->db->update('settings', $data); } } // ------------------------------------------------------------------------ /** * Test if a template file exists * * @access public * @param string * @return bool */ function test_exists($file) { $file = 'themes/'.$file; if (!file_exists($file)) { return false; } return true; } // ------------------------------------------------------------------------ /** * Load Body Template * * This method is used to load the body template file. Can be used without layout * for emails, printer, etc... * * @access public * @param string the template body file. * @param string the directory - admin or front. * @param array data array * @uses test_exists * @return object I think */ function load_body($template, $dir='front', $data) { $data['settings']=$this->settings; if ($dir=='admin') { $body_file = $dir.'/'.$data['settings']['admin_template'].'/'.$template.'.php'; } else { $body_file = $dir.'/'.$data['settings']['template'].'/'.$template.'.php'; } if ($this->test_exists($body_file)) { return $this->load->view($body_file, $data, true); } else { return $this->load->view($dir.'/default/'.$template, $data, true); } } // ------------------------------------------------------------------------ /** * Load layout Template * * This method is used to load the layout template file. * * @access public * @param string the directory - admin or front. * @param array data array * @uses test_exists * @return object */ function load_layout($dir='front', $data) { $data['settings']=$this->settings; if (defined('IN_ADMIN')) { $layout_file = $dir.'/'.$data['settings']['admin_template'].'/layout.php'; } else { $layout_file = $dir.'/'.$data['settings']['template'].'/layout.php'; } if ($this->test_exists($layout_file)) { return $this->load->view($layout_file, $data); } else { return $this->load->view($dir.'/default/layout.php',$data); } } // ------------------------------------------------------------------------ /** * Template Display * * Displays a template based off the current settings * Basically a wrapper for layout * * <code> * $this->init_model->display_template('category', $data); * </code> * * @access public * @param string the template body file * @param array the data to pass * @param string The directory. front or admin (Defaults to front) * @uses get_setting * @uses load_body * @uses test_exists */ function display_template($template, $data='', $dir='front') { $data['settings']=$this->settings; // check directory if ($dir=='admin') { define('IN_ADMIN', TRUE); } else { $dir='front'; // are we caching? if ($this->get_setting('cache_time') > 0) { $this->output->cache($this->get_setting('cache_time')); } } // meta content if ( ! isset($data['title'])) { $data['title'] = $this->get_setting('site_name'); } if ( ! isset($data['meta_keywords'])) { $data['meta_keywords'] = $this->get_setting('site_keywords'); } if ( ! isset($data['meta_description'])) { $data['meta_description'] = $this->get_setting('site_description'); } // Check the body exists $data['body'] = $this->load_body($template, $dir, $data); // Now check the layout exists $this->load_layout($dir, $data); // finally show the last hook $this->core_events->trigger('display_template'); } } /* End of file init_model.php */ /* Location: ./upload/includes/application/models/init_model.php */<file_sep>/upload/includes/application/controllers/setup/kb.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * KB Controller * * Main Setup Controller * * @package 68kb * @subpackage Controllers * @category Controllers * @author 68kb Dev Team * @link http://68kb.com/ * @version $Id: kb.php 125 2009-11-15 05:15:57Z suzkaw68 $ */ class Kb extends Controller { /** * Constructor * * @return void */ function __construct() { parent::__construct(); define('KB_VERSION', 'v1.0.0rc4'); } // ------------------------------------------------------------------------ /** * Index Controller * * Show the setup page * * @access public */ function index() { global $error; $data['error']=$error; $data['nextStep'] = 2; $data['cache'] = $this->_writeable(KBPATH.'cache'); $data['uploads'] = $this->_writeable(KBPATH.'uploads'); $data['body'] = $this->load->view('setup/index', $data, true); $this->load->view('setup/layout.php', $data); } // ------------------------------------------------------------------------ /** * Install step 1 * * @access public */ function install() { global $error; $data['error']=$error; $data['nextStep'] = 2; //$data['cache'] = $this->_writeable(KBPATH.'cache'); $data['uploads'] = $this->_writeable(KBPATH.'uploads'); $data['body'] = $this->load->view('setup/install-step1', $data, true); $this->load->view('setup/layout.php', $data); } // ------------------------------------------------------------------------ /** * Run the install * * @access public */ function run() { $this->load->model('setup/install_model'); $username = $this->input->post('username', TRUE); $password = $this->input->post('password', TRUE); $email = $this->input->post('adminemail', TRUE); $drop = $this->input->post('drop', TRUE); $data['log'] = $this->install_model->install($username,$password, $email, $drop); $data['body'] = $this->load->view('setup/install-step2', $data, true); $this->load->view('setup/layout.php', $data); } // ------------------------------------------------------------------------ /** * Do the upgrade * * @access public */ function upgrade() { $this->load->model('setup/upgrade_model'); $data['log'] = $this->upgrade_model->upgrade(); $data['body'] = $this->load->view('setup/upgrade', $data, true); $this->load->view('setup/layout.php', $data); } // ------------------------------------------------------------------------ /** * Check if a file is writeable. * * @param string The file name. * @access private */ private function _writeable($filename) { global $error; if ( ! is_writable($filename)) { $error=TRUE; return "<span style='color: red;'>ERROR!</span> Please CHMOD to 777"; } else { return 'Ok'; } } } /* End of file kb.php */ /* Location: ./upload/includes/application/controllers/setup/kb.php */ <file_sep>/upload/themes/admin/default/users/grid.php <script language="javascript" type="text/javascript"> <!-- function deleteSomething(url){ removemsg = "<?php echo lang('kb_are_you_sure'); ?>" if (confirm(removemsg)) { document.location = url; } } // --> </script> <h2><?php echo lang('kb_manage_users'); ?> <a class="addnew" href="<?php echo site_url('admin/users/add');?>"><?php echo lang('kb_add_user'); ?></a></h2> <table class="main" width="100%" cellpadding="5" cellspacing="1"> <tr> <th> <?php $class=''; if(isset($orderby) && isset($opp) && $orderby=="id") { $class = $opp; } ?> <?php if(isset($sort) && $sort == 'desc'): ?> <a href="<?php echo site_url('admin/users/grid/orderby/id/asc'); ?>" class="<?php echo $class; ?>"> <?php else: ?> <a href="<?php echo site_url('admin/users/grid/orderby/id/desc'); ?>" class="<?php echo $class; ?>"> <?php endif; ?> <?php echo lang('kb_id'); ?> </a> </th> <th> <?php $class=''; if(isset($orderby) && isset($opp) && $orderby=="username") { $class = $opp; } ?> <?php if(isset($sort) && $sort == 'desc'): ?> <a href="<?php echo site_url('admin/users/grid/orderby/username/asc'); ?>" class="<?php echo $class; ?>"> <?php else: ?> <a href="<?php echo site_url('admin/users/grid/orderby/username/desc'); ?>" class="<?php echo $class; ?>"> <?php endif; ?> <?php echo lang('kb_username'); ?> </a> </th> <th> <?php $class=''; if(isset($orderby) && isset($opp) && $orderby=="lastname") { $class = $opp; } ?> <?php if(isset($sort) && $sort == 'desc'): ?> <a href="<?php echo site_url('admin/users/grid/orderby/lastname/asc'); ?>" class="<?php echo $class; ?>"> <?php else: ?> <a href="<?php echo site_url('admin/users/grid/orderby/lastname/desc'); ?>" class="<?php echo $class; ?>"> <?php endif; ?> <?php echo lang('kb_name'); ?> </a> </th> <th> <?php $class=''; if(isset($orderby) && isset($opp) && $orderby=="email") { $class = $opp; } ?> <?php if(isset($sort) && $sort == 'desc'): ?> <a href="<?php echo site_url('admin/users/grid/orderby/email/asc'); ?>" class="<?php echo $class; ?>"> <?php else: ?> <a href="<?php echo site_url('admin/users/grid/orderby/email/desc'); ?>" class="<?php echo $class; ?>"> <?php endif; ?> <?php echo lang('kb_email'); ?> </a> </th> <th><?php echo lang('kb_actions'); ?></th> </tr> <?php $alt = true; $total=count($items); foreach($items as $item): ?> <tr<?php if ($alt) echo ' class="second"'; else echo ' class="first"'; $alt = !$alt; ?>> <td><?php echo $item['id']; ?></td> <td><?php echo $item['username']; ?></td> <td><?php echo $item['lastname']; ?>, <?php echo $item['firstname']; ?></td> <td><?php echo $item['email']; ?></td> <td> <a href="<?php echo site_url('admin/users/edit/'.$item['id']); ?>"><img src="<?php echo base_url(); ?>images/page_edit.png" border="0" alt="<?php echo lang('kb_edit'); ?>" title="<?php echo lang('kb_edit'); ?>" /></a> &nbsp; <?php if($total > 1): ?> <a href="javascript:void(0);" onclick="return deleteSomething('<?php echo site_url('admin/users/delete/'.$item['id']); ?>');"><img src="<?php echo base_url(); ?>images/page_delete.png" border="0" alt="<?php echo lang('kb_delete'); ?>" title="<?php echo lang('kb_delete'); ?>" /></a> <?php else: ?> <img src="<?php echo base_url(); ?>images/lock.png" alt="<?php echo lang('kb_default'); ?>" title="<?php echo lang('kb_default'); ?>"/> <?php endif; ?> </td> </tr> <?php endforeach; ?> </table> <div class="paginationNum"> <?php echo lang('kb_pages'); ?>: <?php echo $pagination; ?> </div> <file_sep>/upload/themes/front/default/category.php <?php if(isset($cat)): ?> <h2 class="catHeading"> <?php echo $cat->cat_name; ?> <a rel="nofollow" title="<?php echo $cat->cat_name; ?> RSS Feed" href="<?php echo site_url('rss/category/'.$cat->cat_uri); ?>"><img src="<?php echo base_url(); ?>themes/front/<?php echo $settings['template']; ?>/images/icon-rss.gif" /></a> </h2> <p class="catDescription"><?php echo $cat->cat_description; ?></p> <?php endif; ?> <?php /** * Show sub categories */ ?> <?php if ($parents->num_rows() > 0): ?> <table width="100%" border="0"> <tr> <th><?php echo $this->lang->line('kb_categories'); ?></th> </tr> <tr> <td> <table width="100%"> <?php $perline = 2; $set = $perline; foreach($parents->result() as $row): if(($set%$perline) == 0){ echo "<tr>"; } ?> <td width="33%"> <div class="folder"><a href="<?php echo site_url("category/".$row->cat_uri."/"); ?>"><?php echo $row->cat_name; ?></a></div> </td> <?php if((($set+1)%$perline) == 0){ echo "</tr>"; } $set = $set+1; ?> <?php endforeach; ?> </table> </td> </tr> </table> <?php endif; ?> <?php /** * Show articles */ ?> <?php if (isset($articles) && $articles->num_rows() > 0): ?> <ul class="articles"> <?php foreach($articles->result() as $row): ?> <li> <a href="<?php echo site_url("article/".$row->article_uri."/"); ?>"><?php echo $row->article_title; ?></a> <?php if($settings['comments'] == 'Y'): ?> <?php // This is a hack at best. Calling model from view. // Bad Eric, no doughnut! ?> <span>(<a class="comments" href="<?php echo site_url("article/".$row->article_uri."/#comments"); ?>"><?php echo $this->comments_model->get_article_comments_count($row->article_id); ?></a>)</span> <?php endif; ?> <br /> <?php echo $row->article_short_desc; ?> </li> <?php endforeach; ?> </ul> <?php if($pagination): ?> <div class="paginationNum"> <?php echo lang('kb_pages'); ?>: <?php echo $pagination; ?> </div> <?php endif; ?> <?php endif; ?><file_sep>/upload/includes/application/controllers/admin/users.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Admin Users Controller * * Handles all the users * * @package 68kb * @subpackage Admin_Controllers * @category Admin_Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/users.html * @version $Id: users.php 134 2009-12-02 01:29:40Z suzkaw68 $ */ class Users extends Controller { /** * Constructor * * Requires needed models and helpers. * * @access public */ function __construct() { parent::__construct(); $this->load->model('init_model'); $this->load->model('users_model'); $this->load->helper('cookie'); $this->load->library('auth'); $this->auth->restrict(); } // ------------------------------------------------------------------------ /** * Index Controller * * Redirects to this->grid * * @access public */ function index() { $data = ''; $cookie = get_cookie('usersgrid_orderby', TRUE); $cookie2 = get_cookie('usersgrid_orderby_2', TRUE); if($cookie<>'' && $cookie2 <> '') { redirect('admin/users/grid/orderby/'.$cookie.'/'.$cookie2); } else { redirect('admin/users/grid/'); } $this->init_model->display_template('users/grid', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Revert * * Show a message and redirect the user * * @access public * @param string -- The location to goto * @return array */ function revert($goto) { $data['goto'] = $goto; $data['nav'] = 'users'; $this->init_model->display_template('content', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Grid * * Show a table of users * * It assume this uri sequence: * /controller/simplepagination/[offset] * or * /controller/simplepagination/orderby/fieldname/orientation/[offset] * * @link http://codeigniter.com/forums/viewthread/45709/#217816 * @access public * @return array */ function grid() { $data['nav'] = 'users'; if ( ! $this->auth->check_level(1)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } #### settings ### $this->load->library("pagination"); $this->load->helper("url"); $config['per_page'] = $this->init_model->settings['max_search']; #### db init ### //total number of rows $config['total_rows'] = $this->db->count_all('users'); //prepare active record for new query (with limit/offeset/orderby) $this->db->select('id, username, firstname, lastname, email, level'); $this->db->from("users"); #### sniff uri/orderby ### $segment_array = $this->uri->segment_array(); $segment_count = $this->uri->total_segments(); $allowed = array('id','username', 'firstname', 'lastname', 'email', 'level'); //segments $do_orderby = array_search("orderby",$segment_array); $asc = array_search("asc",$segment_array); $desc = array_search("desc",$segment_array); //do orderby if ($do_orderby !== FALSE) { $orderby = $this->uri->segment($do_orderby+1); if( !in_array( trim ( $orderby ), $allowed )) { $orderby = 'id'; } $this->db->order_by($orderby, $this->uri->segment($do_orderby+2)); } else { $orderby = 'id'; } $data['orderby'] = $orderby; $data['sort'] = $this->uri->segment($do_orderby+2); if($data['sort'] == 'asc') { $data['opp'] = 'desc'; } else { $data['opp'] = 'asc'; } //set cookie $cookie = array( 'name' => 'usersgrid_orderby', 'value' => $this->uri->segment($do_orderby+1), 'expire' => '86500' ); $cookie2 = array( 'name' => 'usersgrid_orderby_2', 'value' => $this->uri->segment($do_orderby+2), 'expire' => '86500' ); set_cookie($cookie); set_cookie($cookie2); #### pagination & data subset ### //remove last segment (assume it's the current offset) if (ctype_digit($segment_array[$segment_count])) { $this->db->limit($config['per_page'], $segment_array[$segment_count]); array_pop($segment_array); } else { $this->db->limit($config['per_page']); } $query = $this->db->get(); $data['items'] = $query->result_array(); $config['base_url'] = site_url(join("/",$segment_array)); $config['uri_segment'] = count($segment_array)+1; $this->pagination->initialize($config); $data["pagination"] = $this->pagination->create_links(); $this->init_model->display_template('users/grid', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Edit User * * @access public */ function edit() { $data['nav'] = 'users'; if ( ! $this->auth->check_level(1)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $this->load->helper(array('form', 'url', 'security')); $this->load->library('form_validation'); $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); $id = (int) $this->uri->segment(4, 0); $data['art'] = $this->users_model->get_user_by_id($id); $data['action'] = site_url('admin/users/edit/'.$id); //$this->form_validation->set_rules('username', 'lang:kb_username', 'required'); $this->form_validation->set_rules('firstname', 'lang:kb_firstname', 'trim'); $this->form_validation->set_rules('lastname', 'lang:kb_lastname', 'trim'); $this->form_validation->set_rules('email', 'lang:kb_email', 'required'); if($this->input->post('password') <> '') { $this->form_validation->set_rules('password', 'lang:kb_password', 'required|matches[passconf]'); $this->form_validation->set_rules('passconf', 'lang:kb_confirmpassword', '<PASSWORD>'); } if ($this->form_validation->run() == FALSE) { $this->init_model->display_template('users/form', $data, 'admin'); } else { //success $id = $this->input->post('id', TRUE); $data = array( 'username' => $this->input->post('username', TRUE), 'firstname' => $this->input->post('firstname', TRUE), 'lastname' => $this->input->post('lastname', TRUE), 'email' => $this->input->post('email', TRUE), 'level' => $this->input->post('level', TRUE) ); if ($this->input->post('password')) { $pass = array('password' => $<PASSWORD>->post('password', TRUE)); $data = array_merge((array)$data, (array)$pass); } $var = $this->users_model->edit_user($id, $data); $this->revert('admin/users/'); } } // ------------------------------------------------------------------------ /** * Add User * * @access public */ function add() { $data['nav']='users'; if ( ! $this->auth->check_level(1)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $this->load->helper(array('form', 'url', 'security')); $this->load->library('form_validation'); $data['action'] = site_url('admin/users/add/'); /** Rules **/ $this->form_validation->set_rules('username', 'lang:kb_username', 'required|callback_username_check'); $this->form_validation->set_rules('firstname', 'lang:kb_firstname', 'trim'); $this->form_validation->set_rules('lastname', 'lang:kb_lastname', 'trim'); $this->form_validation->set_rules('email', 'lang:kb_email', 'required'); $this->form_validation->set_rules('password', 'lang:kb_password', 'required|matches[passconf]'); $this->form_validation->set_rules('passconf', 'lang:kb_confirmpassword', 'required'); if ($this->form_validation->run() == FALSE) { $this->init_model->display_template('users/form', $data, 'admin'); } else { $password = dohash($this->input->post('password', TRUE), 'md5'); // MD5 $data = array( 'firstname' => $this->input->post('firstname', TRUE), 'lastname' => $this->input->post('lastname', TRUE), 'email' => $this->input->post('email', TRUE), 'username' => $this->input->post('username', TRUE), 'password' => <PASSWORD>, 'joindate' => time(), 'level' => $this->input->post('level', TRUE) ); $this->db->cache_delete_all(); if ($this->db->insert('users', $data)) { $this->revert('admin/users/'); } } } // ------------------------------------------------------------------------ /** * Username check * * Checks to see if a username is in use. * * @access public */ function username_check($str) { $this->db->select('id')->from('users')->where('username', $str); $query = $this->db->get(); if ($query->num_rows() > 0) { $this->form_validation->set_message('username_check', $this->lang->line('kb_username_inuse')); return FALSE; } else { return TRUE; } } // ------------------------------------------------------------------------ /** * Delete User * * @access public */ function delete() { $data['nav'] = 'users'; if ( ! $this->auth->check_level(1)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $id = (int) $this->uri->segment(4, 0); $this->db->cache_delete_all(); $this->db->delete('users', array('id' => $id)); $this->core_events->trigger('users/delete', $id); $this->revert('admin/users/'); } } /* End of file users.php */ /* Location: ./upload/includes/application/controllers/admin/users.php */ <file_sep>/upload/includes/application/libraries/core_events.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Events Model * * This file works with the module system * * @package 68kb * @subpackage Libraries * @category Libraries * @author 68kb Dev Team * @link http://68kb.com/user_guide/developer/modules.html * @version $Id: core_events.php 139 2009-12-02 14:45:42Z suzkaw68 $ */ class core_events { /** * @var array Array of registered hooks and their listeners */ var $listeners = array(); /** * Kb events * * Allow users to extend the system. * Idea from Iono */ function __construct() { $data=''; $CI =& get_instance(); if($CI->db->table_exists('modules') && $CI->config->item('modules_on')) { $CI->db->from('modules'); $CI->db->where('active', '1'); $query = $CI->db->get(); foreach ($query->result() as $row) { if (@file_exists(KBPATH .'my-modules/'.$row->directory.'/events.php')) { include_once(KBPATH .'my-modules/'.$row->directory.'/events.php'); $class = $row->name.'_events'; if (class_exists($class)) { new $class($this); } } } } } // ------------------------------------------------------------------------ /** * Register a listner for a given hook * * @param string $hook * @param object $class_reference * @param string $method */ function register($hook, &$class_reference, $method) { // Specifies a key so we can't define the same handler more than once $key = get_class($class_reference).'->'.$method; $this->listeners[$hook][$key] = array(&$class_reference, $method); } // ------------------------------------------------------------------------ /** * Trigger an event * * @param string $hook * @param mixed $data */ function trigger($hook, $data='') { $call_it = ''; // Are there any hooks? if (isset($this->listeners[$hook]) && is_array($this->listeners[$hook]) && count($this->listeners[$hook]) > 0) { // Loop foreach ($this->listeners[$hook] as $listener) { // Set up variables $class =& $listener[0]; $method = $listener[1]; if (method_exists($class,$method)) { // Call method dynamically $call_it.=$class->$method($data); } } } return $call_it; } } /* End of file core_Events.php */ /* Location: ./upload/includes/application/libraries/core_Events.php */<file_sep>/upload/themes/admin/default/users/form.php <h2><?php echo lang('kb_manage_users'); ?></h2> <div id="form"> <?php if(validation_errors()) { echo '<div class="error">'.validation_errors().'</div>'; } ?> <form method="post" action="<?php echo $action; ?>" class="searchform"> <p class="row1"> <label for="username"><?php echo lang('kb_username'); ?>:</label> <input type="text" name="username" id="username" class="inputtext" value="<?php echo (isset($art->username)) ? set_value('username', $art->username) : set_value('username'); ?>" /> </p> <p class="row2"> <label for="firstname"><?php echo lang('kb_firstname'); ?>:</label> <input type="text" name="firstname" id="firstname" class="inputtext" value="<?php echo (isset($art->firstname)) ? set_value('firstname', $art->firstname) : set_value('firstname'); ?>" /> </p> <p class="row1"> <label for="lastname"><?php echo lang('kb_lastname'); ?>:</label> <input type="text" name="lastname" id="lastname" class="inputtext" value="<?php echo (isset($art->lastname)) ? set_value('lastname', $art->lastname) : set_value('lastname'); ?>" /> </p> <p class="row2"> <label for="email"><?php echo lang('kb_email'); ?>:</label> <input type="text" name="email" id="email" class="inputtext" value="<?php echo (isset($art->email)) ? set_value('email', $art->email) : set_value('email'); ?>" /> </p> <p class="row1"> <label for="level"><?php echo lang('kb_level'); ?>:</label> <select name="level" id="level"> <option value="1"<?php if (isset($art->level) && $art->level == 1) echo ' selected="selected"'; ?>>Administrator</option> <option value="2"<?php if (isset($art->level) && $art->level == 2) echo ' selected="selected"'; ?>>Moderator</option> <option value="3"<?php if (isset($art->level) && $art->level == 3) echo ' selected="selected"'; ?>>Editor</option> <option value="4"<?php if (isset($art->level) && $art->level == 4) echo ' selected="selected"'; ?>>Author</option> </select> </p> <?php if(isset($art->id)): ?> <div class="warning"><p><?php echo lang('kb_password_change'); ?></p></div></td> <?php endif; ?> <p class="row2"> <label for="password"><?php echo lang('kb_password'); ?>:</label> <input type="passconf" name="password" id="password" class="inputtext" value="" /> </p> <p class="row1"> <label for="passconf"><?php echo lang('kb_confirmpassword'); ?>:</label> <input type="passconf" name="passconf" id="passconf" class="inputtext" value="" /> </p> <?php $this->core_events->trigger('users/form', (isset($art->id)) ? $art->id : '');?> <p style="text-align: center;"> <input type="submit" name="submit" class="save" value="<?php echo lang('kb_save'); ?>" /> </p> <input type="hidden" name="id" value="<?php echo (isset($art->id)) ? $art->id : ''; ?>" /> <input type="hidden" name="action" value="<?php echo $action; ?>" /> <?php echo form_close(); ?> <div class="clear"></div> </div> <file_sep>/upload/includes/application/models/theme_model.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Theme Model * * This class is used for getting themes. * * @package 68kb * @subpackage Models * @category Models * @author 68kb Dev Team * @link http://68kb.com/user_guide/design/themes.html * @version $Id: theme_model.php 89 2009-08-13 01:54:20Z suzkaw68 $ */ class Theme_model extends Model { /** * Constructor * * @uses get_settings * @return void */ function __construct() { parent::__construct(); log_message('debug', 'Theme Model Initialized'); } // ------------------------------------------------------------------------ /** * Load Active Template * * Load the config file for the active template. * * @access private * @param string the file * @return bool */ function load_active_template($template) { if (file_exists(KBPATH .'themes/front/'.$template.'/config.php')) { require_once(KBPATH .'themes/front/'.$template.'/config.php'); $preview = 'front/'.$template.'/preview.png'; if ($this->_testexists($preview)) { $data['template']['preview']=base_url().'themes/'.$preview; } else { $data['template']['preview']=base_url().'images/nopreview.gif'; } return $data['template']; } else { return FALSE; } } // ------------------------------------------------------------------------ /** * Load All Other Templates * * @access public * @param string the default template * @return arr */ function load_templates($default) { $location = KBPATH.'themes/front/'; $available_theme = ''; $i=0; if ($handle = opendir($location)) { while (false !== ($file = readdir($handle))) { if (is_dir($location.$file) && $file != $default && $file != "." && $file != ".." && $file != ".DS_Store" && $file != ".svn" && $file != "modules" && $file != "index.htm") { $preview = $location.$file.'/preview.png'; if (file_exists($preview)) { $preview = base_url().'themes/front/'.$file.'/preview.png'; } else { $preview = base_url().'images/nopreview.gif'; } if (file_exists($location.$file.'/config.php')) { require_once($location.$file.'/config.php'); $available_theme[$i]['title']=$data['template']['name']; $available_theme[$i]['description']=$data['template']['description']; $available_theme[$i]['version']=$data['template']['version']; $available_theme[$i]['file'] = $file; $available_theme[$i]['preview_img'] = $preview; $available_theme[$i]['name']=$file; $available_theme[$i]['preview']=$preview; } else { $available_theme[$i]['title']=$file; $available_theme[$i]['preview_img'] = $preview; $available_theme[$i]['file'] = $file; } } $i++; } closedir($handle); } return $available_theme; } // ------------------------------------------------------------------------ /** * Test if a file exists * * @access private * @param string the file * @return bool */ function _testexists($file) { $file = KBPATH.'themes/'.$file; if ( ! file_exists($file)) { return false; } return true; } } /* End of file template_model.php */ /* Location: ./upload/includes/application/models/template_model.php */ <file_sep>/upload/includes/application/config/database.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); $active_group = "default"; $active_record = TRUE; include(INCPATH .'config.php'); /* End of file database.php */ /* Location: ./upload/includes/application/config/database.php */ <file_sep>/upload/includes/application/helpers/categories_helper.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Categories Plugin * * This is used to display a list of categories. * * @subpackage Plugins * @link http://68kb.com/user_guide/developer/plugin-categories.html */ if ( ! function_exists('categories_plugin')) { function categories_plugin($params) { $CI =& get_instance(); $parent = 0; // parent to start with $depth = 1; // category depth $type = 'list'; // list or table $table_attr = 'width="100%"'; $style = 1; $cols=2; $show_count = FALSE; $show_description = FALSE; $row_start = ''; $cell_start = ''; $row_alt_start = ''; $cell_alt_start = ''; $trail_pad = '&nbsp;'; parse_str($params, $options); foreach ($options as $_key=>$_value) { switch ($_key) { case 'parent': case 'depth': $$_key = (int)$_value; break; case 'type': $$_key = (string)$_value; break; case 'table_attr': case 'tr_attr': case 'td_attr': case 'show_count': case 'show_description': $$_key = $_value; break; } } $CI->load->model('category_model'); if ($type == 'table') { // setup table template $tmpl = array ( 'table_open' => '<table '. $table_attr .'>', 'row_start' => '<tr '. $row_start .'>', 'row_end' => '</tr>', 'cell_start' => '<td '. $cell_start .'>', 'cell_end' => '</td>', 'row_alt_start' => '<tr '. $row_alt_start .'>', 'row_alt_end' => '</tr>', 'cell_alt_start' => '<td '. $cell_alt_start .'>', 'cell_alt_end' => '</td>', 'table_close' => '</table>' ); $data = array(); $cats = $CI->category_model->get_categories_by_parent($parent); if ($cats->num_rows() == 0) // no records so we can't continue { return FALSE; } foreach ($cats->result_array() as $row) { $count = '0'; if ($show_count) { $count = '<span>('.$CI->category_model->get_category_count($row['cat_id']).')</span>'; } $td = '<h4 class="cat_name '.$row['cat_uri'].'"><a href="'.site_url('category/'.$row['cat_uri']).'">'.$row['cat_name'].'</a> '.$count.'</h4>'; if ($show_description) { $td .= '<p>'.$row['cat_description'].'</p>'; } // any sub cats? Only goes to a depth of 2. if ($depth > 1) { $children = $CI->category_model->get_categories_by_parent($row['cat_id']); if ($children->num_rows() > 0) { $td .= '<ul>'; foreach ($children->result_array() as $child) { $td .= '<li><a href="'.site_url('category/'.$child['cat_uri']).'">'.$child['cat_name'].'</a></li>'; } $td .= '</ul>'; } } // Make it into an array $td_arr = array($td); // Now merge this with others $data = array_merge($data, $td_arr); } // Load the table library $CI->load->library('table'); // Set the template as defined above. $CI->table->set_template($tmpl); $CI->table->set_empty($trail_pad); // Make the columns $new_list = $CI->table->make_columns($data, $cols); // echo it to the browser echo $CI->table->generate($new_list); // finally clear the template incase it is used twice. $CI->table->clear(); } else { // pass off to categories model to walk through it. return $CI->category_model->walk_categories($parent, $depth, $type); } } } /* End of file categories_helper.php */ /* Location: ./upload/includes/application/helpers/categories_helper.php */ <file_sep>/upload/includes/application/models/article_model.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Article Model * * This class is used to handle the article data. * * @package 68kb * @subpackage Models * @category Models * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/articles.html * @version $Id: article_model.php 89 2009-08-13 01:54:20Z suzkaw68 $ */ class Article_model extends model { /** * Constructor * * @return void */ function __construct() { parent::__construct(); log_message('debug', 'Article Model Initialized'); } // ------------------------------------------------------------------------ /** * Delete Article * * Responsible for deleting an article. * * @param int $cat_id The id of the category to delete. * @uses delete_article_attachments * @uses delete_article_tags * @return true on success. */ function delete_article($article_id) { $article_id=(int)trim($article_id); $this->core_events->trigger('articles/delete', $article_id); $this->delete_article_attachments($article_id); $this->delete_article_tags($article_id); $this->db->delete('articles', array('article_id' => $article_id)); if ($this->db->affected_rows() > 0) { $this->db->cache_delete_all(); return true; } else { return false; } } // ------------------------------------------------------------------------ /** * Delete all Uploaded files. * * @access public * @param int */ function delete_article_attachments($id) { $id = (int)$id; $this->load->helper('file'); $this->db->select('attach_id, article_id, attach_name')->from('attachments')->where('article_id', $id); $query = $this->db->get(); if ($query->num_rows() > 0) { foreach ($query->result() as $row) { $article_id = $row->article_id; @unlink(KBPATH .'uploads/'.$row->article_id.'/'.$row->attach_name); $this->db->delete('attachments', array('attach_id' => $id)); } } } // ------------------------------------------------------------------------ /** * Delete all article tags. * * @access public * @param int */ function delete_article_tags($id) { $id = (int)$id; $this->db->delete('article_tags', array('tags_article_id' => $id)); } // ------------------------------------------------------------------------ /** * Edit Category * * Handles editing an article. * * @param array $data An array of data. * @uses format_uri * @return bool true on success. */ function edit_article($article_id, $data) { $article_id = (int)$article_id; if (isset($data['article_uri']) && $data['article_uri'] != '') { $data['article_uri'] = $this->format_uri($data['article_uri'], 0, $article_id); } else { $data['article_uri'] = $this->format_uri($data['article_title'], 0, $article_id); } if ( ! isset($data['article_modified']) ) { $data['article_modified'] = time(); } $this->db->where('article_id', $article_id); $this->db->update('articles', $data); if($this->db->affected_rows() > 0) { $this->db->cache_delete_all(); return true; } else { log_message('info', 'Could not edit the post id '. $article_id); return false; } } // ------------------------------------------------------------------------ /** * Add Article * * Add an article to the db. * * @param array $data An array of data. * @uses format_uri * @return mixed Id on success. */ function add_article($data) { if (isset($data['article_uri']) && $data['article_uri'] != '') { $data['article_uri'] = $this->format_uri($data['article_uri']); } else { $data['article_uri'] = $this->format_uri($data['article_title']); } //update the time stamps. $data['article_date'] = time(); $data['article_modified'] = time(); $this->db->insert('articles', $data); if($this->db->affected_rows() > 0) { $this->db->cache_delete_all(); return $this->db->insert_id(); } else { return false; } } // ------------------------------------------------------------------------ /** * Check URI * * Checks other articles for the same uri. * * @param string $article_uri The uri name * @return boolean True if checks out ok, false otherwise */ function check_uri($article_uri, $article_id=false) { if ($article_id !== false) { $article_id=(int)$article_id; $this->db->select('article_uri')->from('articles')->where('article_uri', $article_uri)->where('article_id !=', $article_id); } else { $this->db->select('article_uri')->from('articles')->where('article_uri', $article_uri); } $query = $this->db->get(); if ($query->num_rows() > 0) { return false; } else { return true; } } // ------------------------------------------------------------------------ /** * Format URI * * Formats an articles uri. * * @param string $article_uri The uri name * @uses check_uri * @uses remove_accents * @uses seems_utf8 * @uses utf8_uri_encode * @uses format_uri * @return string A cleaned uri */ function format_uri($article_uri, $i=0, $cat_id=false) { $article_uri = strip_tags($article_uri); // Preserve escaped octets. $article_uri = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $article_uri); // Remove percent signs that are not part of an octet. $article_uri = str_replace('%', '', $article_uri); // Restore octets. $article_uri = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $article_uri); $article_uri = remove_accents($article_uri); if (seems_utf8($article_uri)) { if (function_exists('mb_strtolower')) { $article_uri = mb_strtolower($article_uri, 'UTF-8'); } $article_uri = utf8_uri_encode($article_uri, 200); } $article_uri = strtolower($article_uri); $article_uri = preg_replace('/&.+?;/', '', $article_uri); // kill entities $article_uri = preg_replace('/[^%a-z0-9 _-]/', '', $article_uri); $article_uri = preg_replace('/\s+/', '-', $article_uri); $article_uri = preg_replace('|-+|', '-', $article_uri); $article_uri = trim($article_uri, '-'); if ($i>0) { $article_uri=$article_uri."-".$i; } if ( ! $this->check_uri($article_uri, $cat_id)) { $i++; $article_uri=$this->format_uri($article_uri, $i); } return $article_uri; } // ------------------------------------------------------------------------ /** * Get Article * * Gets a list of all articles * * @param int The limit * @param int The offset * @param bool Should you count only? * @return mixed Either int or array. */ function get_articles() { $this->db->from('articles')->where('article_display', 'Y')->order_by('article_order DESC, article_title ASC'); $query = $this->db->get(); return $query; } // ------------------------------------------------------------------------ /** * Get Article By Cat ID. * * Get a list of articles from the * same category. * * @access public * @param int the category id * @param int Limit * @param int Current Row * @param bool * @return mixed */ function get_articles_by_catid($id, $limit=0, $current_row = 0, $show_count=FALSE) { $id = (int)$id; $this->db->from('articles'); $this->db->join('article2cat', 'articles.article_id = article2cat.article_id', 'left'); $this->db->where('category_id', $id); $this->db->where('article_display', 'Y'); if ($show_count) { return $this->db->count_all_results(); } if ($limit > 0) { $this->db->limit($limit, $current_row); } $query = $this->db->get(); return $query; } // ------------------------------------------------------------------------ /** * Get Article By URI. * * Get a single article from its a_uri * * @access public * @param string the unique uri * @return array */ function get_article_by_uri($uri) { $this->db->from('articles')->where('article_uri', $uri)->where('article_display', 'Y'); $query = $this->db->get(); if ($query->num_rows > 0) { $data = $query->row(); $query->free_result(); return $data; } else { return FALSE; } } // ------------------------------------------------------------------------ /** * Get Article By ID. * * Get a single article from its ID * * @access public * @param int the id * @return array */ function get_article_by_id($id) { $id = (int)$id; $this->db->from('articles')->where('article_id', $id); $query = $this->db->get(); $data = $query->row(); $query->free_result(); return $data; } // ------------------------------------------------------------------------ /** * Get Attachments * * Get all attachments by article ID * * @access public * @param int the id * @return array */ function get_attachments($id) { $id = (int)$id; $this->db->from('attachments')->where('article_id', $id); $query = $this->db->get(); return $query; } // ------------------------------------------------------------------------ /** * Get Most Popular. * * Get a list of the most popular articles. * * @access public * @param int the number to return * @return array */ function get_most_popular($number=25) { $number = (int)$number; $this->db->select('article_uri,article_title') ->from('articles') ->where('article_display', 'Y') ->orderby('article_hits', 'DESC') ->limit($number); $query = $this->db->get(); return $query; } // ------------------------------------------------------------------------ /** * Get Highest Rated. * * Get a list of the articles and order by rating. * Usuage: * <code> * $this->article_model->get_highest_rated(10); * </code> * * @access public * @param int the number to return * @return array */ function get_highest_rated($number=25) { $number = (int)$number; $this->db->select('article_uri,article_title') ->from('articles') ->where('article_display', 'Y') ->orderby('article_rating', 'DESC') ->limit($number); $query = $this->db->get(); return $query; } // ------------------------------------------------------------------------ /** * Get Latest Articles. * * Get a list of the latest articles * * @access public * @param int the number to return * @return array */ function get_latest($number=25) { $number = (int)$number; $this->db->select('article_uri,article_title') ->from('articles') ->where('article_display', 'Y') ->orderby('article_date', 'DESC') ->limit($number); $query = $this->db->get(); return $query; } // ------------------------------------------------------------------------ /** * Get Related Articles. * * Get a list of the latest articles * * @access public * @param int the number to return * @return array */ function get_related($id, $number=5) { $id = (int)$id; $number = (int)$number; $related = array(); $this->db->select('tags_tag_id,tag'); $this->db->join('tags', 'id = tags_tag_id', 'inner'); $this->db->where('tags_article_id', $id); $query = $this->db->get('article_tags'); $i = 0; if ($query->num_rows > 0) { $result = $query->result_array(); foreach ($result as $row) { $this->db->where('tags_tag_id', $row['tags_tag_id']); $this->db->where('tags_article_id !=', $id); $query2 = $this->db->get('article_tags'); if($query2->num_rows > 0 && $i < $number) { $result = $query2->result_array(); foreach($result as $rs) { $related[]=$rs; $i++; } } } } } // ------------------------------------------------------------------------ /** * Add Hit * * Increase the article hit count. * * @access public * @param int the article id. * @return bool */ function add_hit($id) { $id=(int)$id; $this->db->select('article_hits')->from('articles')->where('article_id', $id); $query = $this->db->get(); if ($query->num_rows() > 0) { $row = $query->row(); $hits = $row->article_hits+1; $data = array('article_hits' => $hits); $this->db->where('article_id', $id); $this->db->update('articles', $data); return TRUE; } return FALSE; } // ------------------------------------------------------------------------ /** * Glossary * * Checks for terms in the glossary and links the text to the term. Also * can be used in conjunction with jQuery tooltip. * * @link http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/ * @uses _dot * @param string the content * @return string the content with the link */ function glossary($content) { $this->db->select('g_id,g_term,g_definition')->from('glossary'); $query = $this->db->get(); if ($query->num_rows() > 0) { foreach ($query->result() as $row) { $pos = strpos(strtolower($content), strtolower($row->g_term)); if ($pos !== FALSE) { $sDef = $this->_dot($row->g_definition,75); $sDef = str_replace('"', '\'', $sDef); $replacement = ' <a href="'.site_url('glossary/term/'.$row->g_term).'" class="tooltip" title="'.$row->g_term.' - '.$sDef.'">'.$row->g_term.'</a> '; $content = preg_replace('/[\b|\s]('.$row->g_term.')[\b|^\s]/i', $replacement, $content, 1); } } } return $content; } // ------------------------------------------------------------------------ /** * dot * * Trims a string and adds periods to the end * * @access private * @param string the string * @param int the length * @param string the ending value * @return string the trimmed string */ private function _dot($str, $len, $dots = "...") { if (strlen($str) > $len) { $dotlen = strlen($dots); $str = substr_replace($str, $dots, $len - $dotlen); } return $str; } } /* End of file article_model.php */ /* Location: ./upload/includes/application/models/article_model.php */ <file_sep>/upload/themes/admin/default/comments/edit.php <script language="javascript" type="text/javascript"> <!-- // function checkform(frm) { if (frm.comment_author.value == "") {alert("<?php echo lang('kb_please_enter'); ?> '<?php echo lang('kb_name'); ?>'."); frm.comment_author.focus(); return (false);} if (frm.comment_author_email.value == "") {alert("<?php echo lang('kb_please_enter'); ?> '<?php echo lang('kb_email'); ?>'."); frm.comment_author_email.focus(); return (false);} } //--> </script> <h2><?php echo lang('kb_comments'); ?></h2> <div id="form" class="wrap"> <?php if(validation_errors()) { echo '<div class="error">'.validation_errors().'</div>'; } ?> <?php echo form_open('admin/comments/edit'); ?> <table width="100%" cellspacing="0"> <tr> <td class="row1"><label for="comment_author"><?php echo lang('kb_name'); ?>: <em>(<?php echo lang('kb_required'); ?>)</em></label></td> <td class="row1"><input tabindex="1" type="text" name="comment_author" id="comment_author" value="<?php echo (isset($art->comment_author)) ? form_prep($art->comment_author) : ''; ?>" /></td> </tr> <tr> <td class="row2"><label for="comment_author_email"><?php echo lang('kb_email'); ?>: <em>(<?php echo lang('kb_required'); ?>)</em></label></td> <td class="row2"><input tabindex="2" type="text" name="comment_author_email" id="comment_author_email" value="<?php echo (isset($art->comment_author_email)) ? form_prep($art->comment_author_email) : ''; ?>" /></td> </tr> <tr> <td class="row1" colspan="2"> <label for="comment_content"><?php echo lang('kb_content'); ?>:</label> </td> </tr> <tr> <td class="row1" colspan="2"> <textarea tabindex="3" name="comment_content" id="comment_content" cols="15" rows="15" class="inputtext"><?php echo (isset($art->comment_content)) ? form_prep($art->comment_content) : ''; ?></textarea> </td> </tr> <tr> <td class="row1"><label for="comment_approved"><?php echo lang('kb_display'); ?>:</label></td> <td class="row1"> <select tabindex="4" name="comment_approved" id="comment_approved"> <option value="1"<?php echo (isset($art->comment_approved) && $art->comment_approved==1) ? ' selected="selected"' : ''; ?>><?php echo lang('kb_active'); ?></option> <option value="0"<?php echo (isset($art->comment_approved) && $art->comment_approved==0) ? ' selected="selected"' : ''; ?>><?php echo lang('kb_notactive'); ?></option> <option value="spam"<?php echo (isset($art->comment_approved) && $art->comment_approved=='spam') ? ' selected="selected"' : ''; ?>><?php echo lang('kb_spam'); ?></option> </select> </td> </tr> <?php $this->core_events->trigger('comment/form', (isset($art->comment_ID)) ? $art->comment_ID : '');?> </table> <p><input type="submit" tabindex="6" name="submit" class="save" value="<?php echo lang('kb_save'); ?>" /></p> <input type="hidden" name="comment_ID" value="<?php echo (isset($art->comment_ID)) ? $art->comment_ID : ''; ?>" /> <input type="hidden" name="action" value="<?php echo $action; ?>" /> <?php echo form_close(); ?> <div class="clear"></div> </div><file_sep>/upload/includes/application/models/tags_model.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Tags Model * * This class is used to allow the admin to add new tags to articles. * http://codeigniter.com/forums/viewthread/73046/ * http://codeigniter.com/forums/viewthread/49356/#239045 * * @package 68kb * @subpackage Models * @category Models * @author 68kb Dev Team * @link http://68kb.com/ * @version $Id: tags_model.php 89 2009-08-13 01:54:20Z suzkaw68 $ */ class Tags_model extends Model { /** * Constructor * * @return void **/ public function __construct() { parent::__construct(); log_message('debug', 'Tags Model Initialized'); } // ------------------------------------------------------------------------ /** * Get tags for article * * @return array */ function get_article_tags($id) { $id = (int)$id; $this->db->select('tag'); $this->db->join('tags', 'id = tags_tag_id', 'inner'); $this->db->where('tags_article_id', $id); $query = $this->db->get('article_tags'); $tags = ''; if ($query->num_rows() > 0) { foreach ($query->result() as $row) { $tags .= $row->tag.', '; } $tags = rtrim($tags, ', '); } return $tags; } // ------------------------------------------------------------------------ /** * Get tag cloud * * @return array */ function tag_cloud($num='') { $this->db->select('tag, COUNT(tags_tag_id) as qty'); $this->db->join('article_tags', 'tags_tag_id = id', 'inner'); $this->db->groupby('id'); $query = $this->db->get('tags'); $built = array(); if ($query->num_rows > 0) { $result = $query->result_array(); foreach ($result as $row) { $built[$row['tag']] = $row['qty']; } return $built; } else { return array(); } } // ------------------------------------------------------------------------ /** * Get all tags * * @return array */ function get_all_tags() { $this->db->select('tag')->from('tags')->order_by('tag', 'DESC'); $query = $this->db->get(); $tags = ''; if ($query->num_rows > 0) { $result = $query->result_array(); foreach ($result as $row) { $tags .= $row['tag'].' '; } $tags = rtrim($tags, ' '); return $tags; } else { return array(); } } // ------------------------------------------------------------------------ /** * Insert Tags * * @param int * @param string */ function insert_tags($article_id, $tags) { $article_id = (int)$article_id; //first delete any article tags. $this->db->delete('article_tags', array('tags_article_id' => $article_id)); $tags = str_replace(', ', ',', $tags); $tags = str_replace('_', ' ', $tags); $tags = explode(',', $tags); foreach ($tags as $tag) { $tag = trim($tag); if ( ! empty($tag)) { $this->db->where('tag', $tag); $query = $this->db->get('tags',1); if ( $query->num_rows() == 1 ) { $row = $query->row_array(); $tag_id = $row['id']; } else { $tag_data = array('tag' => $tag); $this->db->insert('tags', $tag_data); $tag_id = $this->db->insert_id(); } $tag_assoc_data = array( 'tags_tag_id' => $tag_id, 'tags_article_id' => $article_id ); $this->db->insert('article_tags', $tag_assoc_data); } } } } /* End of file tags_model.php */ /* Location: ./upload/includes/application/models/tags_model.php */ <file_sep>/upload/includes/application/controllers/category.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Category Controller * * Handles the category pages * * @package 68kb * @subpackage Controllers * @category Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/categories.html * @version $Id: category.php 76 2009-07-31 14:47:18Z suzkaw68 $ */ class Category extends Controller { /** * Constructor * * @return void */ function __construct() { parent::__construct(); log_message('debug', 'Category Controller Initialized'); $this->load->model('init_model'); $this->load->model('category_model'); $this->load->model('article_model'); $this->load->model('comments_model'); } // ------------------------------------------------------------------------ /** * Index Controller * * Show a single category with all its articles. * * @access public * @param string the unique uri * @return array */ function index($uri='') { if($uri<>'' && $uri<>'index') { $uri = $this->input->xss_clean($uri); $data['cat']=$this->category_model->get_cat_by_uri($uri); if($data['cat']) { $id = $data['cat']->cat_id; $data['title'] = $data['cat']->cat_name. ' | '. $this->init_model->get_setting('site_name'); $data['parents'] = $this->category_model->get_categories_by_parent($id); //format description $data['cat']->cat_description = $this->category_model->glossary($data['cat']->cat_description); //pagination $this->load->library('pagination'); $config['total_rows'] = $this->article_model->get_articles_by_catid($id, 0, 0, TRUE); $config['per_page'] = $this->init_model->get_setting('max_search'); $config['uri_segment'] = '3'; $config['base_url'] = site_url("category/". $uri); $this->pagination->initialize($config); $data["pagination"] = $this->pagination->create_links(); $data['articles'] = $this->article_model->get_articles_by_catid($id, $config['per_page'], $this->uri->segment(3), FALSE); } else { redirect('all'); } } else { $data['title'] = $this->init_model->get_setting('site_name'); $data['parents'] = $this->category_model->get_categories_by_parent(0); } $this->init_model->display_template('category', $data); } // ------------------------------------------------------------------------ /** * Remap * * Need to document this. * * @link http://codeigniter.com/user_guide/general/controllers.html#remapping * @access private * @param string the unique uri * @return array */ function _remap($method) { $this->index($method); } } /* End of file category.php */ /* Location: ./upload/includes/application/controllers/category.php */ <file_sep>/upload/includes/application/language/spanish/kb_lang.php <?php /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Knowledge Base Language File * * This file handles all the Spanish language strings. * * @package 68kb * @subpackage Language * @category Language * @author ramon.cutanda * @version $Id: kb_lang.php 88 2009-08-12 14:18:04Z suzkaw68 $ */ /** * Articles */ $lang['kb_all_articles'] = 'Todos los artículos'; $lang['kb_articlenotavailable'] = 'Lo sentimos este artículo no está disponible.'; $lang['kb_search'] = 'Buscar'; $lang['kb_search_articles'] = 'Buscar Artículos'; $lang['kb_search_text'] = 'Buscar Texto'; $lang['kb_status'] = 'Estatus'; $lang['kb_author'] = 'Autor'; $lang['kb_all'] = 'Todos'; $lang['kb_active'] = 'Activo'; $lang['kb_notactive'] = 'No Activo'; $lang['kb_keyword'] = 'Palabra Clave'; $lang['kb_searchall'] = 'Buscar Todo'; $lang['kb_searchadvanced'] = 'Búsqueda Avanzada'; $lang['kb_title'] = 'Título'; $lang['kb_views'] = 'Vistas'; $lang['kb_status'] = 'Estado'; $lang['kb_short_description'] = 'Descripción Corta'; $lang['kb_date_added'] = 'Fecha de Creación'; $lang['kb_attachment'] = 'Adjuntar Archivo'; $lang['kb_attachments'] = 'Archivos Adjuntos'; $lang['kb_last_updated'] = 'Última actualización'; $lang['kb_attachment_add'] = 'Después de que guarde este artículo usted podrá adjuntar archivos.'; $lang['kb_upload'] = 'Subir'; $lang['kb_show'] = 'Mostrar'; $lang['kb_article_weight_desc'] = 'Todos los artículos están ordenados alfabéticamente, usted puede cambiar esto utilizando el peso, entre más alto sea el peso, más rápido aparecerá el artículo.'; $lang['kb_most_popular'] = 'Más Populares'; $lang['kb_new_articles'] = 'Nuevos artículos'; $lang['kb_print'] = 'Imprimir'; $lang['kb_bookmark'] = 'Agregar a favoritos'; $lang['kb_keywords'] = 'Palabras Clave'; $lang['kb_keywords_desc'] = 'Por favor agregue las palabras clave separadas por una coma. Ejemplo: caballo, vaca'; $lang['kb_edit_erro'] = 'Añada las palabras clave separadas por comas.'; $lang['kb_helpful'] = '¿Encuentras este artículo de utilidad?'; $lang['kb_rate'] = 'Valorar'; /** * Categories */ $lang['kb_id'] = 'ID'; $lang['kb_title'] = 'Título'; $lang['kb_uri'] = 'URI'; $lang['kb_category'] = 'Categoría'; $lang['kb_incat'] = 'En Categoría'; $lang['kb_browsecats'] = 'Navegar Categorías'; $lang['kb_categories'] = 'Categorías'; $lang['kb_content'] = 'Contenido'; $lang['kb_parent_cat'] = 'Categoría Padre'; $lang['kb_no_parent'] = 'Sin Padre'; $lang['kb_display'] = 'Mostrar'; $lang['kb_edit'] = 'Editar'; $lang['kb_duplicate'] = 'Duplicar'; $lang['kb_delete'] = 'Borrar'; $lang['kb_weight'] = 'Peso'; $lang['kb_weight_desc'] = 'Todas las categorías están ordenadas alfabéticamente, usted puede cambiar esto utilizando el peso, entre más alto sea el peso, más rápido aparecerá la categoría.'; $lang['kb_default'] = 'Defecto'; /** * Comments */ $lang['kb_comment'] = 'Comentario'; $lang['kb_comments'] = 'Comentarios'; $lang['kb_search_comments'] = 'Buscar Comentarios'; $lang['kb_ip'] = 'IP'; $lang['kb_spam'] = 'Spam'; $lang['kb_user_comments'] = 'Comentarios de Usuarios'; $lang['kb_no_comments'] = 'Aun no hay comentarios... Puede empezar llenando los datos que se muestran a continuación.'; $lang['kb_leave_comment'] = 'Deje un Comentario'; $lang['kb_thank_you'] = 'Gracias'; $lang['kb_comment_added'] = 'Su comentario ha sido agregado. Por favor espere mientras lo direccionamos. Si esto no sucede automáticamente por favor haga'; $lang['kb_click_here'] = 'Clic Aquí'; /** * Contact */ $lang['kb_contact_related'] = 'Artículos Relacionados'; $lang['kb_contact'] = 'Contacto'; $lang['kb_subject'] = 'Asunto'; $lang['kb_contact_confirm'] = 'Su mensaje no ha sido enviado. Por favor revise los artículos que se muestran en la parte superior y vea si contestan sus preguntas. Si no es así de clic en el botón de abajo.'; $lang['kb_submit_message'] = 'Enviar Petición'; $lang['kb_thank_you'] = 'Gracias'; $lang['kb_thank_you_msg'] = 'Su mensaje se ha enviado exitosamente.'; $lang['kb_captcha'] = 'Por favor escriba el texto que se le muestra'; /** * Forward */ $lang['kb_success'] = 'Correcto'; $lang['kb_forward'] = 'Por favor, espera mientras carga la siguiente página. Si no cargara, o si no deseas esperar, por favor'; $lang['kb_click_here'] = 'pincha aquí'; /** * General */ $lang['kb_pages'] = 'Páginas'; $lang['kb_yes'] = 'Si'; $lang['kb_no'] = 'No'; $lang['kb_welcome'] = 'Bienvenido'; $lang['kb_latest_news'] = 'Últimas Noticias'; $lang['kb_logout'] = 'Cerrar Sesión'; $lang['kb_forums'] = 'Foros de Soporte'; $lang['kb_support_knowledge_base'] = 'Soporte 68KB'; $lang['kb_view_site'] = 'Ver Sitio'; $lang['kb_please_login'] = 'Por favor inicie Sesión'; $lang['kb_enter_details'] = 'Escriba sus datos'; $lang['kb_remember_me'] = 'Recordarme'; $lang['kb_login_invalid'] = 'Nombre de usuario o contraseña inválidos.'; /** * Glossary */ $lang['kb_manage_glossary'] = 'Administrar Glosario'; $lang['kb_term'] = 'Término'; $lang['kb_add_term'] = 'Agregar Término'; $lang['kb_definition'] = 'Definición'; $lang['kb_save'] = 'Guardar'; $lang['kb_save_and_continue'] = 'Guardar y Continuar Editando'; /** * Home */ $lang['kb_first_time'] = '<strong>Bienvenido!</strong> Parece ser que es la primera vez que usa 68kb, puede que encuentre útil la <a href="http://68kb.com/knowledge-base/article/quick-start-guide">guía de comienzo rápido</a>. Si necesita ayuda no dude en visitar nuestros <a href="http://68kb.com/forums">foros de usuarios</a>.'; $lang['kb_pending_comments'] = 'Comentarios Pendientes'; $lang['kb_running'] = 'Está corriendo'; $lang['kb_license_key'] = 'Licencia'; $lang['kb_total_articles'] = 'Total de Artículos'; $lang['kb_total_categories'] = 'Total de Categorías'; $lang['kb_total_comments'] = 'Total de Comentarios'; $lang['kb_article_search'] = 'Búsqueda de Artículos'; /** * Javascript */ $lang['kb_please_enter'] = 'Por favor escriba un valor en el campo'; $lang['kb_are_you_sure'] = '¿Está seguro que quiere borrar este registro?, ¡Está operación no puede deshacerse!'; $lang['kb_required'] = 'Requerido'; $lang['kb_uri_desc'] = ''; $lang['kb_please_goback'] = 'Por favor revise los errores.'; /** * Modules */ $lang['kb_modules'] = 'Módulos'; $lang['kb_name'] = 'Nombre'; $lang['kb_description'] = 'Descripción'; $lang['kb_version'] = 'Versión'; $lang['kb_actions'] = 'Acciones'; $lang['kb_activate'] = 'Activar'; $lang['kb_activated'] = 'Módulo Activado'; $lang['kb_deactivate'] = 'Desactivar'; $lang['kb_deactivated'] = 'Module Desactivado'; $lang['kb_deleted'] = 'Módulo Borrado'; $lang['kb_delete_module'] = '¿Está seguro que quiere borrar este registro?\nEstá operación soló lo borrará de la base de datos. Tendrá que borrar los archivos del directorio \"my-modules\".'; /** * Nav */ $lang['kb_home'] = 'Inicio'; $lang['kb_dashboard'] = 'Panel'; $lang['kb_articles'] = 'Artículos'; $lang['kb_manage_articles'] = 'Administrar Artículos'; $lang['kb_add_article'] = 'Agregar Artículo'; $lang['kb_categories'] = 'Categorías'; $lang['kb_manage_categories'] = 'Administrar Categorías'; $lang['kb_add_category'] = 'Agregar Categorías'; $lang['kb_settings'] = 'Configuración'; $lang['kb_glossary'] = 'Glosario'; $lang['kb_users'] = 'Usuarios'; /** * Search */ $lang['kb_search_results'] = 'Buscar Resultados'; $lang['kb_no_results'] = 'Lo sentimos, no encontramos ningún artículo para su búsqueda'; /** * Settings */ $lang['kb_main_settings'] = 'Configuración del Sitio'; $lang['kb_site_keywords'] = 'Palabras clave del sitio'; $lang['kb_site_description'] = 'Site Description'; $lang['kb_site_title'] = 'Título del Sitio'; $lang['kb_email'] = 'Correo Electrónico'; $lang['kb_max_search'] = 'Resultados de búsqueda'; $lang['kb_templates'] = 'Temas'; $lang['kb_current_template'] = 'Tema Actual'; $lang['kb_available_templates'] = 'Temas Disponibles'; $lang['kb_allow_comments'] = 'Permitir Comentarios'; $lang['kb_cache_time'] = 'Tiempo de la Caché'; $lang['kb_delete_cache'] = 'Borrar Cache'; $lang['kb_cache_deleted'] = 'Caché borrada'; $lang['kb_cache_desc'] = 'Minutos que las páginas permanecerán en la caché. Para no cachear, usa 0. Asegúrate que el directorio includes/application/cache cuenta con permisos de escritura.'; /** * Stats */ $lang['kb_stats'] = 'Estádisticas'; $lang['kb_summary'] = 'Resumen'; $lang['kb_most_viewed'] = 'Más Vistos'; $lang['kb_search_log'] = 'Bítacora de Búsqueda'; $lang['kb_searches'] = 'Búsquedas'; /** * Users */ $lang['kb_manage_users'] = 'Administrar Usuarios'; $lang['kb_add_user'] = 'Agregar Usuario'; $lang['kb_username'] = 'Nombre de Usuario'; $lang['kb_password'] = '<PASSWORD>'; $lang['kb_confirmpassword'] = 'Confirmar Contraseña'; $lang['kb_firstname'] = 'Nombre'; $lang['kb_lastname'] = 'Apellidos'; $lang['kb_name'] = 'Nombre'; $lang['kb_email'] = 'Correo Electrónico'; $lang['kb_username_inuse'] = 'Ese nombre de usuario ya ha sido utilizado.'; $lang['kb_password_change'] = 'Si quiere cambiar la contraseña: escriba una nueva en los campos que aparecen abajo. Si no dejelos en blanco.'; /** * Utilities */ $lang['kb_utilities'] = 'Herramientas'; $lang['kb_optimize_db'] = 'Optimizar Base de Datos'; $lang['kb_repair_db'] = 'Reparar Base de Datos'; $lang['kb_backup_db'] = 'Respaldar Base de Datos'; $lang['kb_optimize_success'] = 'Optimizada Exitosamente...'; $lang['kb_repair_success'] = 'Reparada Exitosamente...'; /* End of file kb_lang.php */ /* Location: ./upload/includes/application/language/spanish/kb_lang.php */<file_sep>/upload/themes/setup/index.php <h2>Setup</h2> <div id="form" class=""> <p>Welcome to the 68KB setup!</p> <p>Please follow the steps carefully. If you have any troubles, do not hesitate to visit our support forums.</p> <input class="save" type="submit" name="submit" onClick="document.location = '<?php echo site_url('setup/kb/install/'); ?>'" value="Proceed with Installation" /> <input class="save" type="button" onClick="document.location = '<?php echo site_url('setup/kb/upgrade/'); ?>'" value="Proceed with Upgrade" /> </div><file_sep>/upload/includes/application/models/fields_model.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Fields Model * * This class is used to allow the admin to add new fields to tables. * Currently not in use. * * @package 68kb * @subpackage Models * @category Models * @author 68kb Dev Team * @link http://68kb.com/ * @version $Id: fields_model.php 57 2009-07-30 02:52:19Z suzkaw68 $ */ class Fields_model extends Model { /** * Constructor * * @return void **/ public function __construct() { parent::__construct(); log_message('debug', 'fields_model Initialized'); } // ------------------------------------------------------------------------ /** * Get the listing field names * * @return array */ function get_field_names() { return $this->db->list_fields('articles'); } // ------------------------------------------------------------------------ /** * Get a single listing extra fields * * @param int The listing id * @return mixed Array on success */ function get_fields() { $this->db->from('fields'); $query = $this->db->get(); if ($query->num_rows() > 0) { return $query; } return false; } // ------------------------------------------------------------------------ /** * Add a listing field * * @uses add_column * @param array Array of field data * @return bool */ function add_field($data) { if ( ! $this->db->field_exists($data['field_name'], 'articles')) { $this->db->insert('fields', $data); if($this->db->affected_rows() > 0) { $id = $this->db->insert_id(); if($this->add_column($data['field_name'], $data['field_type'], 'articles', $data['field_size'])) { return true; } return false; } return false; } return false; } // ------------------------------------------------------------------------ /** * Add a column * * @param sting The name of the column * @param string The type of column. See http://dev.mysql.com/doc/refman/5.0/en/data-types.html * @param string The table to add it to. * @param int The max limit on the field * @param string The default column value * @return bool */ function add_column($name, $type, $table='articles', $constrain=100, $default='') { $this->load->dbforge(); $field = array( $name => array( 'type' => $type, 'constraint' => $constrain, 'default' => $default, ), ); if($this->dbforge->add_column($table, $field)) { return true; } return false; } } /* End of file fields_model.php */ /* Location: ./upload/includes/application/models/fields_model.php */ <file_sep>/user_guide/developer/using-plugins.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US" xml:lang="en-US"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Modules : 68KB User Guide</title> <link href="../css/style.css" rel="stylesheet" type="text/css" media="all" /> <script type="text/javascript" src="../js/jquery.min.js"></script> <script type="text/javascript" src="../js/main.js"></script> <script type="text/javascript" src="../js/nav.js"></script> <meta http-equiv='expires' content='-1' /> <meta http-equiv='pragma' content='no-cache' /> <meta name='robots' content='all' /> </head> <body> <div id="panel"> <div id="panel_contents"> <script type="text/javascript">create_menu('../');</script> </div> </div> <div id="header"> <div class="container_16"> <div id="logo"> <div class="grid_10"> <img src="../images/logo-68kb.png" alt="logo" width="181" height="53" /> <a name="top" id="top"></a> </div> <div class="grid_6"> <div class="panel_button" style="visibility: visible;"> <a class="open" href="../toc.html">Table of Contents</a> </div> <div class="panel_button" id="hide_button" style="display: none;"> <a class="close" href="#">Close</a> </div> </div> <div class="clear"></div> <div id="title_area" class="grid_9"> <h4>User Guide v1.0.0 RC3</h4> </div> <div class="grid_7 search_area"> <form method="get" action="http://www.google.com/search"> <input type="hidden" name="as_sitesearch" id="as_sitesearch" value="68kb.com/user_guide/" /><input id="search" type="text" size="31" maxlength="255" name="s" value="Search the user guide" />&nbsp;<input type="submit" class="submit" name="sa" value="Go" /> </form> </div> <div class="clear"></div> </div> </div> </div> <p> <br class="clear" /> </p> <div class="container_16 main"> <div id="content" class="grid_16"> <div id="breadcrumb"> <a href="http://68kb.com/">68KB Home</a> &rarr; <a href="../index.html">User Guide Home</a> &rarr; <a href="../developer/modules.html">Modules &amp; Plugins</a> &rarr; Using Plugins </div> <h1>Using Plugins</h1> <p>Plugins allow you to add additional functionality to the script. A plugin in one php file that is added to the extensions/plugins directory.</p> <p>Once a plugin is uploaded to the proper directory it immediately becomes available to use and is called like a php function.</p> <p>Each plugin should contain documentation that shows you exactly how it is used but on average it would be called like this:</p> <code>&lt;?php plugin_name(); ?&gt;</code> <p>If a plugin allows parameters then it can be called in one of two ways:</p> <code>1. &lt;?php plugin_name('one', 'two', 'three'); ?&gt;<br /> 2. &lt;?php plugin_name('opt=one&opt2=two&opt3=3'); ?&gt; </code> <p>The plugin instructions should cover which way it is called.</p> </div> <div class="clear"></div> </div> <br class="clear" /> <div class="container_16 footer"> <div class="grid_8"> <p class="copy"> © 2009 68KB - All Rights Reserved.<br /> A division of <a href="http://68designs.com">68 Designs, LLC</a> </p> </div> <div class="grid_8 top"> <p> <a href="#top">Back to Top</a> </p> </div> </div> </body> </html><file_sep>/upload/my-modules/jwysiwyg/events.php <?php /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * jwysiwyg * * @package 68kb * @subpackage Module * @category Module * @author 68kb Dev Team * @link http://68kb.com/user_guide/controller/article.html * @version $Id: events.php 45 2009-07-28 17:20:56Z suzkaw68 $ */ class jwysiwyg_events { function __construct(&$core_events) { $core_events->register('glossary/form', $this, 'show_editor'); $core_events->register('category/form', $this, 'show_editor'); $core_events->register('articles/form/description', $this, 'show_editor'); $core_events->register('comment/form', $this, 'show_editor'); } function show_editor() { $output='<script type="text/javascript" src="'.base_url().'/my-modules/jwysiwyg/jquery.wysiwyg.js"></script>'; $output .= '<link rel="stylesheet" type="text/css" href="'.base_url().'/my-modules/jwysiwyg/jquery.wysiwyg.css" />'; $output .= ' <script type="text/javascript" > $(document).ready(function() { $(function() { $(\'#editcontent\').wysiwyg(); $(\'#article_short_desc\').wysiwyg(); $(\'#comment_content\').wysiwyg(); }); }); </script> '; echo $output; } } /* End of file events.php */ /* Location: ./upload/my-modules/jwysiwyg/events.php */ <file_sep>/upload/themes/admin/default/stats/searchlog.php <div id="tabs"> <ul> <li><a href="<?php echo site_url('admin/stats/');?>"><span><?php echo $this->lang->line('kb_summary'); ?></span></a></li> <li><a href="<?php echo site_url('admin/stats/viewed');?>"><span><?php echo $this->lang->line('kb_most_viewed'); ?></span></a></li> <li><a href="<?php echo site_url('admin/stats/searchlog');?>" class="active"><span><?php echo $this->lang->line('kb_search_log'); ?></span></a></li> <li><a href="<?php echo site_url('admin/stats/rating');?>"><span>Rating</span></a></li> </ul> </div> <div class="clear"></div> <div class="wrap"> <table width="100%" class="main" cellpadding="5" cellspacing="1"> <tr> <th><?php echo $this->lang->line('kb_term'); ?></th><th><?php echo $this->lang->line('kb_searches'); ?></th> </tr> <?php $alt = true; foreach ($query->result() as $row): ?> <tr<?php if ($alt) echo ' class="row1"'; else echo ' class="row2"'; $alt = !$alt; ?>> <td><?php echo $row->searchlog_term; ?></td><td><?php echo $row->total; ?></td> </tr> <?php endforeach; ?> </table> </div><file_sep>/upload/includes/application/controllers/api.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package API * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * API System * * The API System uses xml-rpc to communicate. * * @package API * @subpackage API * @category API * @author 68kb Dev Team * @link http://68kb.com/user_guide/developer/api.html * @version $Id: api.php 112 2009-11-10 01:08:48Z suzkaw68 $ */ class Api extends controller { /** * Constructor * * Requires needed models and helpers. * * @access public */ function __construct() { parent::__construct(); $this->load->model('init_model'); $this->load->model('category_model'); $this->load->model('article_model'); } // ------------------------------------------------------------------------ /** * Route the function * * @access public */ function index() { $this->load->library('xmlrpc'); $this->load->library('xmlrpcs'); // Users $config['functions']['add_user'] = array('function' => 'Api.add_user'); $config['functions']['edit_user'] = array('function' => 'Api.edit_user'); $config['functions']['get_user'] = array('function' => 'Api.get_user'); // Articles $config['functions']['add_article'] = array('function' => 'Api.add_article'); $config['functions']['edit_article'] = array('function' => 'Api.edit_article'); $config['functions']['add_article_to_cats'] = array('function' => 'Api.add_article_to_cats'); // Comments $config['functions']['add_comment'] = array('function' => 'Api.add_comment'); $config['functions']['edit_comment'] = array('function' => 'Api.edit_comment'); $this->xmlrpcs->initialize($config); $this->xmlrpcs->serve(); } // ------------------------------------------------------------------------ /** * Check for a valid user account * * @access public */ private function check_access($username, $password) { $this->db->where('username', $username); $this->db->where('password', md5($password)); $query = $this->db->get('users'); if ($query->num_rows() == 1) { return true; } else { return false; } } // ------------------------------------------------------------------------ /** * Username check * * Checks to see if a username is in use. * * @access public */ private function _username_check($str) { $this->db->select('id')->from('users')->where('username', $str); $query = $this->db->get(); //echo $this->db->last_query(); if ($query->num_rows() > 0) { return FALSE; } else { return TRUE; } } // ------------------------------------------------------------------------ /** * Add a new users * * Parameters: * <code> * $request = array( * array(array('username'=>'demo', 'password' => '<PASSWORD>'),'struct'), * array(array('firstname'=>'John','lastname'=>'Smith','email'=>'<EMAIL>','username'=>'john','password'=>'<PASSWORD>'),'struct') * ); * </code> * * @access public */ function add_user($request) { $parameters = $request->output_parameters(); $username = $parameters['0']['username']; $password = $parameters['0']['password']; if( ! $this->check_access($username, $password)) { return $this->xmlrpc->send_error_message('100', 'Invalid Access'); } $error = ''; //check errors $user_firstname = $parameters['1']['firstname']; $user_lastname = $parameters['1']['lastname']; $user_email = $parameters['1']['email']; $user_username = $parameters['1']['username']; $user_password = $parameters['1']['password']; if($user_username == '') { $error .= 'Username required'."\n"; } if($user_password == '') { $error .= 'Password required'."\n"; } if( ! $this->_username_check($user_username)) { $error .= 'Username already exists'."\n"; } if($error <> '') { return $this->xmlrpc->send_error_message('101', $error); } $user_password = md5($<PASSWORD>); $data = array( 'firstname' => $user_firstname, 'lastname' => $user_lastname, 'email' => $user_email, 'username' => $user_username, 'password' => $<PASSWORD>, 'joindate' => time() ); if ($this->db->insert('users', $data)) { $id = $this->db->insert_id(); $response = array(array('id' => $id), 'struct'); return $this->xmlrpc->send_response($response); } else { $response = array(false, 'boolean'); return $this->xmlrpc->send_response($response); } } // ------------------------------------------------------------------------ /** * Edit a users * * @access public */ function edit_user($request) { $parameters = $request->output_parameters(); $username = $parameters['0']['username']; $password = $parameters['0']['password']; if( ! $this->check_access($username, $password)) { return $this->xmlrpc->send_error_message('100', 'Invalid Access'); } $error = ''; //check errors $user_id = $parameters['1']['id']; $user_firstname = $parameters['1']['firstname']; $user_lastname = $parameters['1']['lastname']; $user_email = $parameters['1']['email']; $user_username = $parameters['1']['username']; $user_password = $parameters['1']['password']; if($user_username == '') { $error .= 'Username required'."\n"; } if($user_password == '') { $error .= 'Password required'."\n"; } if($error <> '') { return $this->xmlrpc->send_error_message('101', $error); } $user_password = md5($<PASSWORD>); $data = array( 'firstname' => $user_firstname, 'lastname' => $user_lastname, 'email' => $user_email, 'username' => $user_username, 'password' => $<PASSWORD> ); $this->db->where('id', $user_id); if ($this->db->update('users', $data)) { $response = array(true, 'boolean'); return $this->xmlrpc->send_response($response); } else { $response = array(false, 'boolean'); return $this->xmlrpc->send_response($response); } } // ------------------------------------------------------------------------ /** * Get User * * @access public */ function get_user($request) { $parameters = $request->output_parameters(); $username = $parameters['0']['username']; $password = $parameters['0']['password']; if( ! $this->check_access($username, $password)) { return $this->xmlrpc->send_error_message('100', 'Invalid Access'); } $user_username = $parameters['1']['username']; $this->db->from('users')->where('username', $user_username); $query = $this->db->get(); if ($query->num_rows() > 0) { $row = $query->row(); $response = array(array('id' => array($row->id,'string'), 'username' => array($row->username,'string'), 'firstname' => array($row->firstname,'string'), 'lastname' => array($row->lastname,'string'), 'email' => array($row->email,'string'), 'joindate' => array($row->joindate,'string') ), 'struct'); return $this->xmlrpc->send_response($response); } else { $response = array(false, 'boolean'); return $this->xmlrpc->send_response($response); } } // ------------------------------------------------------------------------ /** * Add a new article * * @access public */ function add_article($request) { $parameters = $request->output_parameters(); $username = $parameters['0']['username']; $password = $parameters['0']['password']; if( ! $this->check_access($username, $password)) { return $this->xmlrpc->send_error_message('100', 'Invalid Access'); } $error = ''; //check errors $article_author = $parameters['1']['article_author']; $article_title = $parameters['1']['article_title']; $article_keywords = $parameters['1']['article_keywords']; $article_short_desc = $parameters['1']['article_short_desc']; $article_description = $parameters['1']['article_description']; $article_display = $parameters['1']['article_display']; if($article_author == '') { $error .= 'Author required'."\n"; } if($article_title == '') { $error .= 'Title required'."\n"; } if($article_description == '') { $error .= 'Description required'."\n"; } if($error <> '') { return $this->xmlrpc->send_error_message('101', $error); } $data = array( 'article_author' => $article_author, 'article_title' => $article_title, 'article_keywords' => $article_keywords, 'article_short_desc' => $article_short_desc, 'article_description' => $article_description, 'article_display' => $article_display ); $id = $this->article_model->add_article($data); if(is_int($id)) { $response = array(array('id' => $id), 'struct'); return $this->xmlrpc->send_response($response); } else { $response = array(false, 'boolean'); return $this->xmlrpc->send_response($response); } } // ------------------------------------------------------------------------ /** * Edit an article * * @access public */ function edit_article($request) { $parameters = $request->output_parameters(); $username = $parameters['0']['username']; $password = $parameters['0']['password']; if( ! $this->check_access($username, $password)) { return $this->xmlrpc->send_error_message('100', 'Invalid Access'); } $error = ''; //check errors $article_id = $parameters['1']['article_id']; $article_author = $parameters['1']['article_author']; $article_title = $parameters['1']['article_title']; $article_keywords = $parameters['1']['article_keywords']; $article_short_desc = $parameters['1']['article_short_desc']; $article_description = $parameters['1']['article_description']; $article_display = $parameters['1']['article_display']; if($article_author == '') { $error .= 'Author required'."\n"; } if($article_title == '') { $error .= 'Title required'."\n"; } if($article_description == '') { $error .= 'Description required'."\n"; } if($error <> '') { return $this->xmlrpc->send_error_message('101', $error); } $data = array( 'article_author' => $article_author, 'article_title' => $article_title, 'article_keywords' => $article_keywords, 'article_short_desc' => $article_short_desc, 'article_description' => $article_description, 'article_display' => $article_display ); $this->db->where('article_id', $article_id); if ($this->db->update('articles', $data)) { $response = array(true, 'boolean'); return $this->xmlrpc->send_response($response); } else { $response = array(false, 'boolean'); return $this->xmlrpc->send_response($response); } } // ------------------------------------------------------------------------ /** * Add article to category * * @todo Get this working. :) * @access public */ function add_article_to_cats($request) { $parameters = $request->output_parameters(); $username = $parameters['0']['username']; $password = $parameters['0']['password']; if( ! $this->check_access($username, $password)) { return $this->xmlrpc->send_error_message('100', 'Invalid Access'); } $error = ''; //check errors $article_id = $parameters['1']['article_id']; $cats = $parameters['1']['cats']; if($article_id == '') { $error .= 'Article ID required'."\n"; } if($cats == '') { $error .= 'Category array is required'."\n"; } if($error <> '') { return $this->xmlrpc->send_error_message('101', $error); } if($this->category_model->insert_cats($article_id, $cats)) { //$response = array(array('response' => TRUE), 'boolean'); $response = array(true, 'boolean'); return $this->xmlrpc->send_response($response); } else { $response = array(false, 'boolean'); return $this->xmlrpc->send_response($response); } } // ------------------------------------------------------------------------ /** * Add a comment * * @access public */ function add_comment($request) { $parameters = $request->output_parameters(); $username = $parameters['0']['username']; $password = $parameters['0']['password']; if( ! $this->check_access($username, $password)) { return $this->xmlrpc->send_error_message('100', 'Invalid Access'); } //check errors $error = ''; $comment_author = $parameters['1']['comment_author']; $comment_article_ID = $parameters['1']['comment_article_ID']; $comment_author_email = $parameters['1']['comment_author_email']; $comment_content = $parameters['1']['comment_content']; if($comment_author == '') { $error .= 'Author required'."\n"; } if($comment_article_ID == '') { $error .= 'Article ID is required'."\n"; } if($comment_author_email == '') { $error .= 'Author Email required'."\n"; } if($comment_content == '') { $error .= 'Description required'."\n"; } if($error <> '') { return $this->xmlrpc->send_error_message('101', $error); } $data = array( 'comment_article_ID' => $comment_article_ID, 'comment_author' => $comment_author, 'comment_author_email' => $comment_author_email, 'comment_content' => $comment_content, 'comment_approved' => 1 ); $this->db->insert('comments', $data); $id = $this->db->insert_id(); if(is_int($id)) { $response = array(array('id' => $id), 'struct'); return $this->xmlrpc->send_response($response); } else { $response = array(false, 'boolean'); return $this->xmlrpc->send_response($response); } } // ------------------------------------------------------------------------ /** * Edit a comment * * @access public */ function edit_comment($request) { $parameters = $request->output_parameters(); $username = $parameters['0']['username']; $password = $parameters['0']['password']; if( ! $this->check_access($username, $password)) { return $this->xmlrpc->send_error_message('100', 'Invalid Access'); } //check errors $error = ''; $comment_ID = $parameters['1']['comment_ID']; $comment_author = $parameters['1']['comment_author']; $comment_article_ID = $parameters['1']['comment_article_ID']; $comment_author_email = $parameters['1']['comment_author_email']; $comment_content = $parameters['1']['comment_content']; $comment_approved = $parameters['1']['comment_approved']; if($comment_ID == '') { $error .= 'Comment id required'."\n"; } if($comment_author == '') { $error .= 'Author required'."\n"; } if($comment_article_ID == '') { $error .= 'Article ID is required'."\n"; } if($comment_author_email == '') { $error .= 'Author Email required'."\n"; } if($comment_content == '') { $error .= 'Description required'."\n"; } if($error <> '') { return $this->xmlrpc->send_error_message('101', $error); } $data = array( 'comment_article_ID' => $comment_article_ID, 'comment_author' => $comment_author, 'comment_author_email' => $comment_author_email, 'comment_content' => $comment_content, 'comment_approved' => $comment_approved ); $this->db->where('comment_ID', $comment_ID); $this->db->update('comments', $data); if($this->db->affected_rows() > 0) { $response = array(true, 'boolean'); return $this->xmlrpc->send_response($response); } else { $response = array(false, 'boolean'); return $this->xmlrpc->send_response($response); } } }<file_sep>/upload/my-modules/developer/events.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Developer Events File * * @package 68kb * @subpackage Module * @category Module * @author 68kb Dev Team * @link http://68kb.com/user_guide/developer/modules.html * @version $Id: events.php 84 2009-08-05 03:26:00Z suzkaw68 $ * * The class name must be named "yourmodule_events" where your module is the name * of the module. For this module it is named "developer". */ class developer_events { /** * Class constructor * * The constructor takes the $core_events as the param. * Inside this you will register your events to interact * with the core system. */ function __construct(&$core_events) { $core_events->register('display_template', $this, 'profiler'); $core_events->register('article/description', $this, 'article_description'); } // ------------------------------------------------------------------------ /** * Profiler * * This is used to dynamically enable the profiler. * * In order to use CodeIgniters libraries you must use something like: * $CI =& get_instance(); * * @access public */ function profiler() { $CI =& get_instance(); $CI->output->enable_profiler(TRUE); } // ------------------------------------------------------------------------ /** * Test article formating * * This method shows you how to alter the article content before it is * shown. * * @access public */ function article_description($article) { if($article['article_id'] == 1) { $article = 'This is text that came from the developer module.'; //return $article; } } } /* End of file events.php */ /* Location: ./upload/my-modules/jwysiwyg/events.php */ <file_sep>/upload/themes/front/default/all.php <h1><?php echo lang('kb_all_articles'); ?></h1> <div id="all"> <?php foreach($parents->result() as $row): ?> <h2> <a href="<?php echo site_url("category/".$row->cat_uri."/"); ?>"><?php echo $row->cat_name; ?></a> <a rel="nofollow" title="<?php echo $row->cat_name; ?> RSS Feed" href="<?php echo site_url('rss/category/'.$row->cat_uri); ?>"><img src="<?php echo base_url(); ?>themes/front/<?php echo $settings['template']; ?>/images/icon-rss.gif" /></a> </h2> <p><?php echo $row->cat_description; ?></p> <?php if ($subcats[$row->cat_id]->num_rows() > 0): ?> <table width="100%" border="0" id="categories_table"> <tr> <th><h3>Subcategories</h3></th> </tr> <tr> <td> <table width="100%"> <?php $perline = 2; $set = $perline; foreach($subcats[$row->cat_id]->result() as $child): if(($set%$perline) == 0){ echo "<tr>"; } ?> <td width="33%"> <div class="subCategory"><a href="<?php echo site_url("category/".$child->cat_uri."/"); ?>"><?php echo $child->cat_name; ?></a></div> </td> <?php if((($set+1)%$perline) == 0){ echo "</tr>"; } $set = $set+1; ?> <?php endforeach; ?> </table> </td> </tr> </table> <?php endif; ?> <?php if (isset($articles[$row->cat_id]) && $articles[$row->cat_id]->num_rows() > 0): ?> <ul class="articles"> <?php foreach($articles[$row->cat_id]->result() as $row): ?> <li> <a href="<?php echo site_url("article/".$row->article_uri."/"); ?>"><?php echo $row->article_title; ?></a><br /> <!--<?php echo $row->article_short_desc; ?>--> </li> <?php endforeach; ?> </ul> <?php endif; ?> <?php endforeach; ?> </div><file_sep>/upload/themes/front/default/config.php <?php /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Theme config file * * @package 68kb * @subpackage Theme * @category Theme * @author 68kb Dev Team * @link http://68kb.com/user_guide/controller/article.html * @version $Id: config.php 45 2009-07-28 17:20:56Z suzkaw68 $ */ /** * Theme Name * * Used to identify the theme in admin */ $data['template']['name'] = "default"; /** * Theme Description * * Used to provide a brief description of the theme. */ $data['template']['description'] = "Default 68kb template"; /** * Theme Version * * Current version of the theme. */ $data['template']['version'] = "1.0"; /* End of file config.php */ /* Location: ./upload/themes/front/default/config.php */ <file_sep>/upload/my-modules/developer/init.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Developer Init file * * This is an example file used to add a "test" table, alter it, and finally * delete it. Please note the use of the $CI =& get_instance(); which is * used to access the CodeIgniter object. * * * @package 68kb * @subpackage Models * @category Models * @author 68kb Dev Team * @link http://68kb.com/user_guide/developer/modules.html * @version $Id: init.php 98 2009-08-15 02:09:51Z suzkaw68 $ */ // ------------------------------------------------------------------------ /** * Install or alter any database fields. This is an example and you can * see the install function just adds a test table. */ function install() { $CI =& get_instance(); $CI->load->dbforge(); $fields = array( 'id' => array('type' => 'INT','constraint' => 20,'unsigned' => TRUE,'auto_increment' => TRUE), ); $CI->dbforge->add_field($fields); $CI->dbforge->add_field("test varchar(20) default NULL"); $CI->dbforge->add_key('id', TRUE); if($CI->dbforge->create_table('test')) { return 'test table installed...<br />'; } } // ------------------------------------------------------------------------ /** * Upgrade is ran to make any adjustments to any tables. */ function upgrade() { $CI =& get_instance(); $CI->load->dbforge(); if ( ! $CI->db->field_exists('preferences', 'test')) { $fields = array('preferences' => array('type' => 'TEXT')); $CI->dbforge->add_column('test', $fields); return 'test table altered'; } } // ------------------------------------------------------------------------ /** * Uninstall is used for removing any changes your module makes to the db. */ function uninstall() { $CI =& get_instance(); $CI->load->dbforge(); $CI->dbforge->drop_table('test'); return 'test table dropped'; }<file_sep>/upload/themes/front/default/thanks.php <?php if(isset($error)): ?> <?php echo $error; ?> <?php else: ?> <h2><?php echo lang('kb_thank_you'); ?></h2> <p><?php echo lang('kb_thank_you_msg'); ?></p> <?php endif; ?><file_sep>/upload/my-modules/developer/admin.php <h1>ADMIN</h1> <p>Anything in this file will be shown in the admin layout. </p> <p>You can add forms or whatever you wish.</p> <h2>Form Example</h2> <?php if(isset($_POST['test'])) { echo '<p>You submitted: '. $_POST['test'] .'</p>'; } ?> <form method="post" action="<?php echo site_url('/admin/modules/show/developer'); ?>"> <input type="text" name="test" value="Click Submit" /> <input type="submit" value="submit" /> </form> <h2>Database Example</h2> <p>Below will be a list of a few users:</p> <?php $CI =& get_instance(); $CI->db->from('users')->limit('4'); $query = $CI->db->get(); if ($query->num_rows() > 0) { echo '<ul>'; foreach ($query->result() as $row) { echo '<li>'.$row->username.'</li>'; } echo '</ul>'; } ?> <p>Here is the code used: </p> <pre> $CI =& get_instance(); $CI->db->from('users')->limit('4'); $query = $CI->db->get(); if ($query->num_rows() > 0) { echo '&lt;ul&gt;'; foreach ($query->result() as $row) { echo '&lt;li>'.$row->username.'&lt;/li>'; } echo '&lt;/ul>'; } </pre><file_sep>/upload/includes/application/controllers/admin/settings.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Admin Settings Controller * * Handles all the settings * * @package 68kb * @subpackage Admin_Controllers * @category Admin_Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/settings.html * @version $Id: settings.php 134 2009-12-02 01:29:40Z suzkaw68 $ */ class Settings extends Controller { /** * Constructor * * Requires needed models and helpers. * * @access public */ function __construct() { parent::__construct(); $this->load->model('init_model'); $this->load->helper('cookie'); $this->load->library('auth'); $this->auth->restrict(); $this->load->helper('form'); } // ------------------------------------------------------------------------ /** * Index Controller * * Redirects to this->main * * @access public */ function index() { redirect('admin/settings/main/'); } // ------------------------------------------------------------------------ /** * Save Settings * * @access public */ function main() { $this->load->library('form_validation'); $this->load->helper('form'); $data['nav']='settings'; if ( ! $this->auth->check_level(1)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $this->form_validation->set_rules('site_name', 'lang:kb_site_title', 'required'); $this->form_validation->set_rules('site_email', 'lang:kb_email', 'required|valid_email'); $this->form_validation->set_rules('max_search', 'lang:kb_max_search', 'required|numeric'); $this->form_validation->set_rules('cache_time', 'lang:kb_cache_time', 'required|numeric'); $this->core_events->trigger('settings/validation'); if ($this->form_validation->run() == FALSE) { $this->init_model->display_template('settings/main', $data, 'admin'); } else { foreach ($_POST as $key => $value) { $data = array( 'value' => $this->input->xss_clean($value) ); $this->db->where('short_name', $key); $this->db->update('settings', $data); } $this->revert('admin/settings/'); } } // ------------------------------------------------------------------------ /** * Template Controller * * Allow admin to select active template. * * @access public */ function templates() { $this->load->model('theme_model'); $settings['template'] = $this->init_model->get_setting('template'); $data['nav'] = 'settings'; if ( ! $this->auth->check_level(1)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $activate = $this->uri->segment(4, 0); if ($activate != '') { if (file_exists(KBPATH .'themes/front/'.$activate.'/config.php')) { $data = array( 'value' => $this->input->xss_clean($activate) ); $this->db->where('short_name', 'template'); $this->db->update('settings', $data); redirect('admin/settings/templates/'); } else { echo $activate; } } $data['active'] = $this->theme_model->load_active_template($settings['template']); $data['available_themes'] = $this->theme_model->load_templates($settings['template']); $this->init_model->display_template('settings/template', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Load Active Template * * Load the config file for the active template. * * @access private * @param string the file * @return bool */ function _load_active_template($template) { if (file_exists(KBPATH .'themes/front/'.$template.'/config.php')) { require_once(KBPATH .'themes/front/'.$template.'/config.php'); $preview = 'front/'.$template.'/preview.png'; if ($this->_testexists($preview)) { $data['template']['preview']=base_url().'templates/'.$preview; } else { $data['template']['preview']=base_url().'images/nopreview.gif'; } return $data['template']; } else { return FALSE; } } // ------------------------------------------------------------------------ /** * Test if a file exists * * Test if a file exists. * * @access private * @param string the file * @return bool */ function _testexists($file) { $file = KBPATH.'themes/'.$file; //echo $file.'<BR>'; if ( ! file_exists($file)) { return false; } return true; } // ------------------------------------------------------------------------ /** * Revert * * Show a message and redirect the user * * @access public * @param string -- The location to goto * @return array */ function revert($goto) { $data['nav'] = 'settings'; $data['goto'] = $goto; $this->init_model->display_template('content', $data, 'admin'); } } /* End of file settings.php */ /* Location: ./upload/includes/application/controllers/admin/settings.php */ <file_sep>/upload/themes/front/default/printer.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title><?php echo $article->article_title; ?></title> <style type="text/css"> body, td{font-family:verdana,arial,sans-serif;font-size:80%} a:link, a:active, a:visited{color:#0000CC} img{border:0} pre { font-family: Monaco, Verdana, Sans-serif;} </style> <script> function Print() { document.body.offsetHeight; window.print(); } </script> </head> <body onload="Print()"> <h2><?php echo $article->article_title; ?></h2> <hr> <?php echo $article->article_description; ?> <hr> You can view this article online at:<br /> <?php echo site_url('article/'.$article->article_uri); ?> </body> </html><file_sep>/upload/themes/front/default/home.php <?php /* This is the home page that shows the search, categories, and top articles. */ ?> <h1><?php echo lang('kb_knowledge_base'); ?></h1> <div class="search"> <form method="post" action="<?php echo site_url('search'); ?>" class="searchform"> <label for="searchtext"><?php echo lang('kb_search_kb'); ?>:</label><br /> <input type="text" name="searchtext" class="search_input" id="searchtext" value="" /> <select tabindex="4" name="category" id="category"> <option value="0"><?php echo lang('kb_incat'); ?></option> <?php foreach($cat_tree as $row): ?> <option value="<?php echo $row['cat_id']; ?>"><?php echo $row['cat_name']; ?></option> <?php endforeach; ?> </select> <input type="submit" name="Search" value="<?php echo lang('kb_search'); ?>" /> </form> </div> <h2><?php echo lang('kb_browsecats'); ?></h2> <table width="100%" border="0"> <tr> <td> <table width="100%"> <?php $perline = 2; $set = $perline; foreach($parents->result() as $row): if(($set%$perline) == 0){ echo "<tr>"; } ?> <td width="33%"> <div class="folder"><a href="<?php echo site_url("category/".$row->cat_uri."/"); ?>"><?php echo $row->cat_name; ?></a></div> </td> <?php if((($set+1)%$perline) == 0){ echo "</tr>"; } $set = $set+1; ?> <?php endforeach; ?> </table> </td> </tr> </table> <div class="grid_5"> <h2 class="pop"><?php echo lang('kb_most_popular'); ?></h2> <ul class="articles"> <?php foreach($pop->result() as $row): ?> <li><a href="<?php echo site_url("article/".$row->article_uri."/"); ?>"><?php echo $row->article_title;?></a></li> <?php endforeach; ?> </ul> </div> <div class="grid_5"> <h2 class="pop"><?php echo lang('kb_new_articles'); ?></h2> <ul class="articles"> <?php foreach($latest->result() as $row): ?> <li><a href="<?php echo site_url("article/".$row->article_uri."/"); ?>"><?php echo $row->article_title;?></a></li> <?php endforeach; ?> </ul> </div> <?php $this->core_events->trigger('template/home'); ?><file_sep>/upload/includes/application/models/comments_model.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Comments Model * * This class is used to handle the comments data. * * @package 68kb * @subpackage Models * @category Models * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/comments.html * @version $Id: comments_model.php 109 2009-09-29 17:47:20Z suzkaw68 $ */ class Comments_model extends model { /** * Constructor * * @uses get_settings * @return void */ function __construct() { parent::__construct(); log_message('debug', 'Comments Model Initialized'); } // ------------------------------------------------------------------------ /** * Delete Category * * @param int $cat_id The id of the category to delete. * @return true on success. */ function delete_comment($id) { $id=(int)trim($id); $this->db->delete('comments', array('comment_ID' => $id)); if ($this->db->affected_rows() > 0) { $this->core_events->trigger('comments/delete', $id); $this->db->cache_delete_all(); return true; } else { return false; } } // ------------------------------------------------------------------------ /** * Edit Category * * @param array $data An array of data. * @uses format_uri * @return true on success. */ function edit_comment($id, $data) { $id = (int)$id; $this->db->where('comment_ID', $id); $this->db->update('comments', $data); if ($this->db->affected_rows() > 0) { $this->core_events->trigger('comments/edit', $id); $this->db->cache_delete_all(); return true; } else { log_message('info', 'Could not edit the comment id '. $id); return false; } } // ------------------------------------------------------------------------ /** * Add Comment * * @param array $data An array of data. * @return mixed Id on success. */ function add_comment($data) { $data['comment_date'] = time(); $data['comment_approved'] = $this->spam_check($data['comment_author_email'], $data['comment_content']); $this->db->insert('comments', $data); if ($this->db->affected_rows() > 0) { $id = $this->db->insert_id(); $this->core_events->trigger('comments/add', $id); $this->db->cache_delete_all(); return $id; } else { return false; } } // ------------------------------------------------------------------------ /** * Spam Check * * Very simple spam checker. Checks the comment for links and if they * already have one approved comment. I didn't add any hooks here * because I thought it would be better to check after it is submitted * so you can do a query and get everything about the comment. * * @param string * @param string * @return mixed */ function spam_check($email, $comment) { $array = array('email' => $email, 'comment' => $comment); $this->core_events->trigger('comment/spam', $array); $this->db->from('comments')->where('comment_author_email', $email); $query = $this->db->get(); /* * Check the number of links included in the comment. If more that 2 is 90% spam. Idea from wp. */ if ( preg_match_all("|(href\t*?=\t*?['\"]?)?(https?:)?//|i", $comment, $out) >= 2 ) { return 'spam'; } elseif ($query->num_rows() > 0) { return '1'; //active } else { return '0'; //hold for review } } // ------------------------------------------------------------------------ /** * Chagne Display * * @param string The new status * @param int The comment id. * @access private */ function change_display($status, $id) { $id = (int)$id; if ($status==5) { $this->db->delete('comments', array('comment_ID' => $id)); $this->core_events->trigger('comments/delete', $id); $this->db->cache_delete_all(); } else { $data = array( 'comment_approved' => $status ); $this->db->where('comment_ID', $id); $this->db->update('comments', $data); $this->core_events->trigger('comments/changestatus', $id); $this->db->cache_delete_all(); } } // ------------------------------------------------------------------------ /** * Get approved comments * * Get approved comments based of article id * * @access public * @param int the unique id * @return array */ function get_article_comments($id) { $id=(int)$id; $this->db->from('comments')->where('comment_article_ID', $id)->where('comment_approved', '1')->orderby('comment_date', 'ASC'); $query = $this->db->get(); return $query; } // ------------------------------------------------------------------------ /** * Get approved comments count * * Get approved comments count based of article id * * @access public * @param int the unique id * @return int */ function get_article_comments_count($id) { $id = (int)$id; $this->db->where('comment_article_ID', $id)->where('comment_approved', '1'); $this->db->from('comments'); return $this->db->count_all_results(); } // ------------------------------------------------------------------------ /** * Email the admin about the comment * * @access public * @param int the unique id * @return int */ function email_admin($id, $data = '') { if ($data) { $this->load->library('email'); $site_email = $this->init_model->get_setting('site_email'); $title = $this->init_model->get_setting('site_name'); // first get the article info $this->db->select('article_author, article_title, article_uri')->from('articles')->where('article_id', $data['comment_article_ID']); $query = $this->db->get(); if ($query->num_rows() > 0) { $row = $query->row(); $subject = $title .' '. lang('kb_new_comment') .' '. $row->article_title; // now get the author $this->db->select('email')->from('users')->where('id', $row->article_author); $query2 = $this->db->get(); if($query2->num_rows() > 0) { $user = $query2->row(); $this->email->cc($user->email); } // now lets email it $message = lang('kb_name').': '.$data['comment_author'] ."\n"; $message .= lang('kb_email').': '. $data['comment_author_email'] ."\n"; $message .= lang('kb_ip').': '. $data['comment_author_IP'] ."\n"; $message .= lang('kb_comments').": \n"; $message .= $data['comment_content'] ."\n\n"; $message .= lang('kb_comment_link')."\n"; $message .= '{unwrap}'.site_url('admin/comments/edit/'.$id).'{/unwrap}'; $this->email->set_newline("\r\n"); $this->email->from($site_email, $title); $this->email->to($site_email); $this->email->subject($subject); $this->email->message($message); if ( ! $this->email->send()) { echo $this->email->print_debugger(); } } } } } /* End of file comments_model.php */ /* Location: ./upload/includes/application/models/comments_model.php */ <file_sep>/do_not_upload/build.xml <?xml version="1.0" encoding="UTF-8"?> <project name="68KB" default="init-work-bench" basedir="."> <property name="project.package" value="${phing.project.name}" override="true" /> <propertyprompt propertyName="revision" promptText="Enter the release to deploy: (example 1.0.0 'leave off the v')"/> <!--<property name="revision" value="v0.0.1"/>--> <property name="project.revision" value="${revision}" /> <property name="github.repos.dir" value="../../builds/68kb/v${project.revision}" override="true" /> <tstamp> <format property="build.time" pattern="%m%d%Y" /> <format property="build.ug" pattern="%B %e, %Y" /> </tstamp> <!-- deploy the applications files to the specific environment --> <target name="deploy" depends="init-work-bench, clean-files" description="update the application files in a specific environment"> <echo message="Finished deployment." /> </target> <target name="init-work-bench" depends="-init-ad-hoc-tasks, -clone-git-repos" description="Initializes the hypothetical workbench"> <echo message="Finished release package." /> </target> <target name="zip" description="Zip up the files"> <zip destfile="../../builds/ice/iclassengine_v${project.revision}.zip"> <fileset dir="${github.repos.dir}"> <include name="**/**" /> </fileset> </zip> </target> <target name="clean-files" description="Removes files not included in the release."> <delete file="${github.repos.dir}/68KB/README.md" /> <delete file="${github.repos.dir}/68KB/upload/unit_test.php" /> <delete file="${github.repos.dir}/68KB/upload/includes/application/cache" /> <delete file="${github.repos.dir}/68KB/.gitignore" /> <mkdir dir="${github.repos.dir}/68KB/upload/includes/application/cache" /> <touch file="${github.repos.dir}/68KB/upload/includes/application/cache/index.html" /> <delete dir="${github.repos.dir}/68KB/.git/" includeemptydirs="true" failonerror="true" /> <delete dir="${github.repos.dir}/68KB/do_not_upload/" includeemptydirs="true" failonerror="true" /> <!-- Set build date --> <reflexive> <fileset dir="${github.repos.dir}/iclassengine/"> <include name="upload/includes/iclassengine/controllers/setup.php" /> <include name="user_guide/index.html" /> </fileset> <filterchain> <replacetokens endtoken="##" begintoken="##"> <token key="BUILD" value="${build.time}"/> <token key="UGBUILD" value="${build.ug}"/> <token key="VERSION" value="${project.revision}"/> </replacetokens> </filterchain> </reflexive> </target> <target name="-clean-git-repos" description="Removes old repositories before initializing a new workbench"> <delete dir="${github.repos.dir}" includeemptydirs="true" failonerror="true" /> </target> <target name="-init-ad-hoc-tasks" description="Initializes the ad hoc task(s)"> <adhoc-task name="github-clone"><![CDATA[ class Github_Clone extends Task { private $repository = null; private $destDirectory = null; function setRepos($repository) { $this->repository = $repository; } function setDest($destDirectory) { $this->destDirectory = $destDirectory; } function main() { // Get project name from repos Uri $projectName = str_replace('.git', '', substr(strrchr($this->repository, '/'), 1)); $gitCommand = 'git clone ' . $this->repository . ' ' . $this->destDirectory . '/' . $projectName; exec(escapeshellcmd($gitCommand), $output, $return); if ($return !== 0) { throw new BuildException('Git clone failed'); } $logMessage = 'Cloned Git repository ' . $this->repository . ' into ' . $this->destDirectory . '/' . $projectName; $this->log($logMessage); } } ]]></adhoc-task> <echo message="Initialized github-clone ad hoc task." /> </target> <target name="-clone-git-repos" depends="-clean-git-repos" description="Clones the needed Git repositories from GitHub"> <github-clone repos="<EMAIL>:68designs/68KB.git" dest="${github.repos.dir}" /> </target> </project><file_sep>/upload/themes/front/default/rss.php <?php header('Content-Type: text/xml; charset=utf-8'); header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); echo '<?xml version="1.0" encoding="utf-8"?>' . "\n"; ?> <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/"> <channel> <title><?php echo $feed_name; ?></title> <link><?php echo $feed_url; ?></link> <description><?php echo $page_description; ?></description> <dc:language>en-ca</dc:language> <dc:creator><?php echo $creator_email; ?></dc:creator> <dc:rights>Copyright <?php echo gmdate("Y", time()); ?></dc:rights> <admin:generatorAgent rdf:resource="http://www.codeigniter.com/" /> <?php foreach($articles->result() as $row): ?> <item> <title><?php echo xml_convert($row->article_title); ?></title> <link><?php echo site_url("article/".$row->article_uri."/"); ?></link> <guid><?php echo site_url("article/".$row->article_uri."/"); ?></guid> <description><![CDATA[ <?php echo $row->article_description; ?> ]]></description> <pubDate><?php echo date ('r', $row->article_date);?></pubDate> </item> <?php endforeach; ?> </channel></rss><file_sep>/upload/themes/front/default/search.php <h1><?php echo lang('kb_search_articles'); ?></h1> <div class="search"> <form method="post" action="<?php echo site_url('search'); ?>" class="searchform"> <label for="searchtext"><?php echo lang('kb_search_kb'); ?>:</label><br /> <input type="text" name="searchtext" class="search_input" id="searchtext" value="<?php echo (isset($searchtext)) ? form_prep($searchtext) : ''; ?>" /> <select tabindex="4" name="category" id="category"> <option value="0"><?php echo lang('kb_incat'); ?></option> <?php foreach($cat_tree as $row): ?> <?php $default = ((isset($category) && $category == $row['cat_id'])) ? true : false; ?> <option value="<?php echo $row['cat_id']; ?>" <?php echo set_select('category', $row['cat_id'], $default); ?>><?php echo $row['cat_name']; ?></option> <?php endforeach; ?> </select> <input type="submit" name="Search" value="<?php echo lang('kb_search'); ?>" /> </form> </div> <?php if (isset($articles)): ?> <?php if ($articles->num_rows() > 0): ?> <h2><?php echo lang('kb_search_results'); ?></h2> <table width="100%" border="0" cellspacing="5"> <?php foreach($articles->result() as $row): ?> <tr> <td> <div class="article"> <a href="<?php echo site_url("article/".$row->article_uri."/"); ?>"><?php echo $row->article_title; ?></a> </div> <?php echo $row->article_short_desc; ?> </td> </tr> <?php endforeach; ?> </table> <?php else: ?> <h2><?php echo lang('kb_search_results'); ?></h2> <p><?php echo lang('kb_no_results'); ?></p> <?php endif; ?> <?php endif; ?><file_sep>/upload/includes/application/models/setup/upgrade_model.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Upgrade Model * * This class is used for upgrading your db. * * @package 68kb * @subpackage Models * @category Models * @author 68kb Dev Team * @link http://68kb.com/ * @version $Id: upgrade_model.php 130 2009-12-01 18:04:30Z suzkaw68 $ */ class Upgrade_model extends model { function __construct() { parent::Model(); $this->obj =& get_instance(); $this->load->dbforge(); } // ------------------------------------------------------------------------ /** * Upgrade the db. * * @access private */ function upgrade() { $prefix = $this->db->dbprefix; $log = ''; //update version $this->db->select('short_name,value')->from('settings')->where('short_name', 'version'); $query = $this->db->get(); foreach ($query->result() as $k=>$row) { $version = $row->value; } $log = $this->do_upgrade(); $data['value']=KB_VERSION; $this->db->where('short_name', 'version'); $this->db->update('settings', $data); //optimize db $this->load->dbutil(); $this->dbutil->optimize_database(); //delete cache $this->load->helper('file'); delete_files($this->config->item('cache_path')); return $log; } // ------------------------------------------------------------------------ /** * Upgrade * * @access public */ function do_upgrade() { $log[] = $this->upgrade_to_one(); return $log; } // ------------------------------------------------------------------------ /** * Upgrade to v1.0 */ function upgrade_to_one() { $prefix = $this->db->dbprefix; $log[] = 'Checking for levels...<br>'; if ( ! $this->db->field_exists('level', 'users')) { $sql = 'ALTER TABLE `'.$prefix.'users` ADD `level` INT( 5 ) NULL DEFAULT \'5\';'; $this->db->query($sql); $log[] = 'Level added...<br />'; $sql = 'UPDATE '.$prefix.'users SET level = 1'; $this->db->query($sql); } $log[] = 'Checking for tags...<br>'; if ( ! $this->db->table_exists('tags')) { $fields = array( 'id' => array('type' => 'INT','constraint' => 11,'unsigned' => TRUE,'auto_increment' => TRUE), ); $this->dbforge->add_field($fields); $this->dbforge->add_field("tag varchar(30) NOT NULL default '0'"); $this->dbforge->add_key('id', TRUE); if($this->dbforge->create_table('tags')) { $log[] = 'tags table installed...'; } $this->dbforge->add_field("tags_tag_id int(11) NOT NULL default '0'"); $this->dbforge->add_field("tags_article_id int(11) NOT NULL default '0'"); $this->dbforge->add_key('tags_tag_id', TRUE); if($this->dbforge->create_table('article_tags')) { $log[] = 'article_tags table installed...<br />'; } $this->db->where('active', 0); $this->db->delete('modules'); } $log[] = 'Checking for rating...<br>'; if ( ! $this->db->field_exists('article_rating', 'articles')) { $sql = 'ALTER TABLE `'.$prefix.'articles` ADD `article_rating` INT( 11 ) NULL DEFAULT \'0\';'; $this->db->query($sql); $log[] = 'Rating added...<br />'; } $log[] = 'Checking for new settings...<br>'; $this->db->select('short_name')->from('settings')->where('short_name', 'site_keywords'); $count = $this->db->count_all_results(); if($count == 0) { $data = array('short_name' => 'site_keywords','name' => "Site Keywords",'value' => '','auto_load' => 'yes'); $this->db->insert('settings', $data); $data = array('short_name' => 'site_description','name' => "Site Description",'value' => '','auto_load' => 'yes'); $this->db->insert('settings', $data); $log[] = 'Updating settings...<br>'; } $log[] = 'Checking for article changes...<br>'; if($this->db->field_exists('a_id', 'articles')) { // now alter table $sql = " ALTER TABLE `".$prefix."articles` CHANGE `a_id` `article_id` INT(20) UNSIGNED NOT NULL AUTO_INCREMENT, CHANGE `a_uri` `article_uri` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, CHANGE `a_title` `article_title` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, CHANGE `a_keywords` `article_keywords` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, CHANGE `a_short_desc` `article_short_desc` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, CHANGE `a_description` `article_description` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, CHANGE `a_date` `article_date` INT( 11 ) NOT NULL DEFAULT '0', CHANGE `a_modified` `article_modified` INT( 11 ) NOT NULL DEFAULT '0', CHANGE `a_display` `article_display` CHAR(1) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'N', CHANGE `a_hits` `article_hits` INT(11) NOT NULL DEFAULT '0', CHANGE `a_author` `article_author` INT( 11 ) NOT NULL DEFAULT '1', CHANGE `a_order` `article_order` INT( 11 ) NOT NULL DEFAULT '0'; "; $this->db->query($sql); // change datetime $this->db->select('article_id, article_date, article_modified')->from('articles'); $query = $this->db->get(); foreach ($query->result() as $row) { $data = array( 'article_date' => time(), 'article_modified' => time() ); $this->db->where('article_id', $row->article_id); $this->db->update('articles', $data); } $log[] = 'Updating articles...<br>'; // COMMENTS $sql = " ALTER TABLE `".$prefix."comments` CHANGE `comment_date` `comment_date` INT( 16 ) NOT NULL DEFAULT '0'; "; // change datetime $this->db->select('comment_ID, comment_date')->from('comments'); $query = $this->db->get(); foreach ($query->result() as $row) { $data = array( 'comment_date' => time() ); $this->db->where('comment_ID', $row->comment_ID); $this->db->update('articles', $data); } $this->db->query($sql); $log[] = 'Updating comments...<br>'; } $log[] = 'Checking for category changes...<br>'; if ($this->db->field_exists('c_id', 'categories')) { $sql = " ALTER TABLE `".$prefix."categories` CHANGE `c_id` `cat_id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT , CHANGE `c_parent` `cat_parent` INT( 11 ) NOT NULL DEFAULT '0', CHANGE `c_uri` `cat_uri` VARCHAR( 55 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '0', CHANGE `c_name` `cat_name` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , CHANGE `c_description` `cat_description` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , CHANGE `c_display` `cat_display` CHAR( 1 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'N', CHANGE `c_order` `cat_order` INT( 11 ) NOT NULL DEFAULT '0'; "; $this->db->query($sql); $log[] = 'Updating categories...<br>'; } $log[] = 'Checking for attachment changes...<br>'; if ($this->db->field_exists('a_id', 'attachments')) { $sql = " ALTER TABLE `".$prefix."attachments` CHANGE `a_id` `attach_id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT , CHANGE `a_name` `attach_name` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , CHANGE `a_type` `attach_type` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , CHANGE `a_size` `attach_size` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL; "; $this->db->query($sql); $log[] = 'Updating attachments...<br>'; } //this is from way long time ago. Left for backwards compatability. $log[] = 'Checking for Captcha...<br>'; if ( ! $this->db->table_exists('captcha')) { $fields = array( 'captcha_id' => array('type' => 'INT','constraint' => 11,'unsigned' => TRUE,'auto_increment' => TRUE), ); $this->dbforge->add_field($fields); $this->dbforge->add_field("captcha_time int(10) NOT NULL default '0'"); $this->dbforge->add_field("ip_address varchar(16) NOT NULL default '0'"); $this->dbforge->add_field("word varchar(20) NOT NULL default ''"); $this->dbforge->add_field("a_size varchar(255) NOT NULL default ''"); $this->dbforge->add_key('captcha_id', TRUE); $this->dbforge->add_key('word'); if($this->dbforge->create_table('captcha')) { $log[] = 'Captcha Table Created...'; } } return $log; } } /* End of file db_model.php */ /* Location: ./upload/includes/application/models/db_model.php */<file_sep>/upload/themes/admin/export/layout.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title><?php echo $title; ?> : <?php echo $settings['site_name']; ?></title> <link href="css/960.css" rel="stylesheet" type="text/css" media="all" /> <link href="css/master.css" rel="stylesheet" type="text/css" media="all" /> <script src="jquery-treeview/lib/jquery.js"></script> <script src="jquery-treeview/lib/jquery.cookie.js"></script> <script src="jquery-treeview/jquery.treeview.js"></script> <link rel="stylesheet" href="jquery-treeview/jquery.treeview.css" type="text/css" /> <script> $(document).ready(function(){ $("#browser").treeview({ control: "#treecontrol", persist: "cookie", cookieId: "treeview-black" }); }); </script> <meta http-equiv='expires' content='-1' /> <meta http-equiv= 'pragma' content='no-cache' /> <meta name='robots' content='all' /> </head> <body> <!-- START NAVIGATION --> <div id="nav"> <div class="container_12"> <div id="logo" class="grid_6"> <h1><?php echo $settings['site_name']; ?></h1> </div> <div id="search" class="grid_6"> <form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="68kb.com/user_guide/" />Search User Guide&nbsp; <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" />&nbsp;<input type="submit" class="submit" name="sa" value="Go" /></form> </div> </div> </div> <!-- END NAVIGATION --> <div class="container_12"> <div class="grid_12"> <a name="top">&nbsp;</a> <div id="breadcrumb" class="box"> <a href="<?php echo site_url(); ?>">68KB Home</a> &nbsp;&#8250;&nbsp; <a href="./index.html">User Guide Home</a> &nbsp;&#8250;&nbsp; <?php echo $title; ?> </div> </div> <div id="content" class="grid_9"> <div class="box"> <h1><?php echo $title; ?></h1> <?php echo $description; ?> </div> </div> <div id="sidebar" class="grid_3"> <div id="treecontrol"> <a title="Collapse the entire tree below" href="#"><img src="jquery-treeview/images/minus.gif" /> Collapse All</a> <a title="Expand the entire tree below" href="#"><img src="jquery-treeview/images/plus.gif" /> Expand All</a> <a title="Toggle the tree below, opening closed branches, closing open branches" href="#">Toggle All</a> </div> <?php echo $navigation; ?> </div> <div class="clear"></div> </div> <!--START Footer Section--> <div id="footer"> <p>Powered by <a href="http://68kb.com">68 Knowledge Base</a> &nbsp;&middot;&nbsp; <a href="#top">Top of Page</a></p> </div> <!--END Footer Section--> </body> </html> <file_sep>/upload/themes/admin/default/settings/template.php <div id="theme"> <h3><?php echo lang('kb_current_template'); ?></h3> <table id="current-theme"> <tr> <td> <img class="current" src="<?php echo $active['preview']; ?>" alt="Current theme preview" /> </td> <td> <h3><?php echo $active['name']; ?></h3> <p class="description"><?php echo $active['description']; ?></p> </td> </tr> </table> <h3><?php echo lang('kb_available_templates'); ?></h3> <br class="clear" /> <?php if(is_array($available_themes)): foreach($available_themes AS $row): ?> <div class="available_box"> <div class="available_box_heading"><?php echo $row['title']; ?></div> <a href="<?php echo site_url('admin/settings/templates/'.$row['file']);?>"><img src="<?php echo $row['preview']; ?>" width="200" height="167" /></a> <p><a href="<?php echo site_url('admin/settings/templates/'.$row['file']);?>"><?php echo lang('kb_activate'); ?></a></p> </div> <?php endforeach; endif; ?> <br class="clear" /> </div> <file_sep>/upload/themes/admin/default/articles/add.php <?php $this->core_events->trigger('articles/form', (isset($art->article_id)) ? $art->article_id : ''); ?> <h2><?php echo lang('kb_manage_articles'); ?></h2> <div id="form" class="wrap"> <?php if(validation_errors()) { echo '<div class="error">'.validation_errors().'</div>'; } ?> <?php $attributes = '';//array('id' => 'articles', 'onsubmit' => 'return checkform(this)'); echo form_open_multipart('admin/articles/add', $attributes); ?> <p class="row1"> <label for="article_title"><?php echo lang('kb_title'); ?>: <em>(<?php echo lang('kb_required'); ?>)</em></label> <input tabindex="1" type="text" class="inputtext" name="article_title" id="article_title" value="<?php echo (isset($art->article_title)) ? set_value('article_title', $art->article_title) : set_value('article_title'); ?>" /> </p> <p class="row2"> <label for="article_uri"><?php echo lang('kb_uri'); ?>:</label> <input tabindex="2" type="text" class="inputtext" name="article_uri" id="article_uri" value="<?php echo (isset($art->article_uri)) ? set_value('article_uri', $art->article_uri) : set_value('article_uri'); ?>" /> </p> <p class="row1"> <label for="article_keywords"><?php echo lang('kb_keywords'); ?>:</label> <input tabindex="3" type="text" class="inputtext" name="article_keywords" id="article_keywords" value="<?php echo (isset($art->article_keywords)) ? set_value('article_keywords', $art->article_keywords) : set_value('article_keywords'); ?>" /> <a href="javascript:void(0);" title="<?php echo lang('kb_keywords_desc'); ?>" class="tooltip"> <img src="<?php echo base_url(); ?>images/help.png" border="0" alt="<?php echo lang('kb_edit'); ?>" /> </a> </p> <p class="row2"> <label for="article_short_desc"><?php echo lang('kb_short_description'); ?>:</label> <textarea tabindex="4" name="article_short_desc" id="article_short_desc" cols="15" rows="5" class="inputtext"><?php echo (isset($art->article_short_desc)) ? set_value('article_short_desc', $art->article_short_desc) : set_value('article_short_desc'); ?></textarea> </p> <p class="row1"> <label for="article_description"><?php echo lang('kb_content'); ?>: <em>(<?php echo lang('kb_required'); ?>)</em></label> <textarea tabindex="5" name="article_description" id="editcontent" cols="35" rows="15" class="inputtext"><?php echo (isset($art->article_description)) ? set_value('article_description', $art->article_description) : set_value('article_description'); ?></textarea> </p> <?php $this->core_events->trigger('articles/form/description', (isset($art->article_id)) ? $art->article_id : ''); ?> <p class="row2"> <label for="article_cat"><?php echo lang('kb_category'); ?>:</label> <select tabindex="6" id="article_cat" name="cat[]" size="10" multiple="multiple"> <?php foreach($options as $row): ?> <option value="<?php echo $row['cat_id']; ?>"<?php if(isset($row['selected']) && $row['selected']=='Y') echo ' selected'; ?>><?php echo $row['cat_name']; ?></option> <?php endforeach; ?> </select> </p> <p class="row1"> <label for="article_order"><?php echo lang('kb_weight'); ?>:</label> <input tabindex="7" type="text" name="article_order" id="article_keywords" value="<?php echo (isset($art->article_order)) ? set_value('article_order', $art->article_order) : set_value('article_order'); ?>" /> <a href="javascript:void(0);" title="<?php echo lang('kb_article_weight_desc'); ?>" class="tooltip"> <img src="<?php echo base_url(); ?>images/help.png" border="0" alt="<?php echo lang('kb_edit'); ?>" /> </a> </p> <p class="row2"> <label for="article_display"><?php echo lang('kb_display'); ?>:</label> <select tabindex="8" name="article_display" id="article_display"> <option value="Y"<?php if(isset($art->article_display) && $art->article_display == 'Y') echo ' selected'; ?>><?php echo lang('kb_yes'); ?></option> <option value="N"<?php if(isset($art->article_display) && $art->article_display == 'N') echo ' selected'; ?>><?php echo lang('kb_no'); ?></option> </select> </p> <p class="row1"> <label for="userfile"><?php echo lang('kb_attachment'); ?>:</label> <input tabindex="9" type="file" id="userfile" name="userfile" size="20" /> </p> <!-- <p class="row2"> <label for="tags"><?php echo lang('kb_tags'); ?>:</label> <input tabindex="9.2" type="text" size="55" name="tags" id="tags" value="<?php echo set_value('tags'); ?>" /> </p> --> <?php $this->core_events->trigger('articles/form'); ?> <p style="text-align: right;"> <input type="submit" tabindex="10" name="submit" class="save" value="<?php echo lang('kb_save'); ?>" /> <input type="submit" tabindex="11" name="save" class="save" value="<?php echo lang('kb_save_and_continue'); ?>" /> </p> <?php echo form_close(); ?> <div class="clear"></div> </div><file_sep>/upload/themes/admin/default/home.php <script language="javascript" type="text/javascript"> <!-- $(document).ready(function() { $.ajax({ url: '<?php echo site_url('/admin/kb/get_news'); ?>', type: 'get', success: function (msg) { $("#rssnews").html(msg); } }); }); --> </script> <?php if(isset($first_time)) { ?> <div class="warning"><p><?php echo lang('kb_first_time'); ?></p></div> <?php } elseif($install==TRUE) { ?> <div class="warning"><p>Please delete the includes/application/controllers/setup folder.</p></div> <?php } ?> <?php if($settings['version'] <> $latest) { ?> <div class="warning"><p><?php echo $latest; ?> <?php echo lang('kb_update_1'); ?> <a href="http://68kb.com/download/"><?php echo lang('kb_update_2'); ?></a>.</p></div> <?php } ?> <h2><?php echo lang('kb_welcome'); ?> <?php //echo $username; ?></h2> <div class="wrap"> <table width="100%" border="0" cellspacing="3" cellpadding="3"> <tr> <td width="50%" valign="top"> <table width="100%" border="0" cellspacing="3" cellpadding="3"> <tr> <td width="25%"><?php echo lang('kb_running'); ?></td> <td width="18%"><?php echo $settings['version']; ?></td> </tr> <tr> <td><?php echo lang('kb_total_articles'); ?></td> <td><?php echo $articles; ?></td> </tr> <tr> <td><?php echo lang('kb_total_categories'); ?></td> <td><?php echo $cats; ?></td> </tr> <tr> <td><?php echo lang('kb_total_comments'); ?></td> <td><?php echo $comment_count; ?></td> </tr> </table> <form name="listings" id="listings" method="post" action="<?php echo site_url('admin/articles/grid'); ?>"> <table width="100%" border="0" cellpadding="3" cellspacing="0" class="modules"> <tr> <td colspan="2" class="moduleslinks" align="left"><strong><?php echo lang('kb_article_search'); ?></strong></td> </tr> <tr> <td align="left"><?php echo lang('kb_search_text'); ?></td> <td align="left"><input type="text" name="searchtext" /> <input type="submit" id="submit" value="<?php echo lang('kb_search'); ?> &#187;" class="button" /></td> </tr> </table> </form> </td> <td width="58%" valign="top"> <table width="100%" border="0" cellpadding="3" cellspacing="0" class="modules"> <tr> <td class="moduleslinks" align="left"><strong><?php echo lang('kb_latest_news'); ?></strong></td> </tr> <tr> <td> <div id="rssnews"><img src="<?php echo base_url();?>images/ajax-loader.gif" alt="Loading" /> <?php echo lang('kb_loading'); ?></div> </td> </tr> </table> </td> </tr> </table> <?php if($settings['comments'] == 'Y' && $comments->num_rows() > 0): ?> <h2><?php echo lang('kb_recent_comments'); ?></h2> <table class="main" width="100%" cellpadding="3" cellspacing="1"> <tr> <th><?php echo lang('kb_name'); ?></th> <th><?php echo lang('kb_content'); ?></th> <th><?php echo lang('kb_article'); ?></th> <th><?php echo lang('kb_status'); ?></th> </tr> <?php $alt = true; foreach($comments->result_array() as $item): ?> <tr<?php if ($alt) echo ' class="row1"'; else echo ' class="row2"'; $alt = !$alt; ?>> <td> <div class="gravatar"><img class="gravatar2" src="<?php echo gravatar( $item['comment_author_email'], "PG", "24", "wavatar" ); ?>" /></div> <strong> <?php echo $item['comment_author']; ?> </strong><br /> <?php echo $item['comment_author_email']; ?><br /> <?php echo $item['comment_author_IP']; ?> </td> <td> <div class="submitted"><?php echo lang('kb_date_added') .' '. date($this->config->item('comment_date_format'), $item['comment_date']); ?></div><br /> <?php echo word_limiter($item['comment_content'], 15); ?><br /> <a href="<?php echo site_url('admin/comments/edit/'.$item['comment_ID']); ?>"><?php echo lang('kb_edit'); ?></a> </td> <td valign="top"> <a href="<?php echo site_url('article/'.$item['article_uri']); ?>/#comment-<?php echo $item['comment_ID']; ?>"><?php echo $item['article_title']; ?></a> </td> <td> <?php if($item['comment_approved'] == 'spam') { echo '<span class="spam">'.lang('kb_spam').'</span>'; } elseif($item['comment_approved'] == 0) { echo '<span class="inactive">'.lang('kb_notactive').'</span>'; } else { echo '<span class="active">'.lang('kb_active').'</span>'; } ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <div class="clear"></div> </div> <br /> <file_sep>/upload/includes/application/plugins/categories_pi.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * List Categories Function * * Instructions: * * Load the plugin using: * $this->load->plugin('categories'); * Once loaded you can call the list_categories function: * <code><?php echo list_categories(); ?></code> * * @param int The parent category. Defaults to 0. * @param int Do you want to show the count? 1 = Yes 0 = No. Defaults to 1. * @param int Do you want to hide empty categories? Defaults to 0. * @param string Order by which column. Defaults to cat_name * @param string Order the results ASC or DESC. Defaults to ASC */ function list_categories($parent='0', $show_count='1', $hide_empty='0', $orderby='cat_name', $order='ASC') { $CI =& get_instance(); $CI->load->model('category_model'); $cats = $CI->category_model->get_tree($orderby, $order, $parent); $output = '<ul>'; foreach($cats AS $k=>$row) { $continue = true; if($hide_empty == 1 && $row['cat_total'] > 0) { $output .= '<li><a href="'.$row['cat_link'].'" class="cat '.$row['cat_url'].'">'.$row['cat_name'].'</a>'; } elseif($hide_empty == 0) { $output .= '<li><a href="'.$row['cat_link'].'" class="cat '.$row['cat_url'].'">'.$row['cat_name'].'</a>'; } else { $continue = false; } if($continue) { if($show_count == 1) { $output .= ' <span class="cat_count">('.$row['cat_total'].')</span>'; } $output .= '</li>'; } } $output .= '</ul>'; return $output; }<file_sep>/upload/themes/admin/default/content.php <?php if (isset($not_allowed)): ?> <?php echo lang('kb_not_allowed'); ?> <?php else: ?> <meta http-equiv="refresh" content="2;URL=<?php echo site_url($goto);?>" /> <fieldset> <legend><?php echo lang('kb_success'); ?></legend> <p> <?php echo lang('kb_forward'); ?> <?php echo anchor($goto, 'click here', array('title' => lang('ads_click_here'))); ?>. </p> </fieldset> <?php endif; ?><file_sep>/upload/themes/setup/install-step2.php <h2>Installation Complete</h2> <div id="form" class="wrap"> <p><strong>Everything installed succesfully !</strong></p> <div class="warning"><p><font color="#FF0000">Now please delete the <strong>includes/application/controllers/setup</strong> directory</font></p></div> <p><a href="<?php echo site_url('admin'); ?>">Click here</a> to visit your admin panel to modify the site settings.</p> <strong>Install Log</strong> <ul> <?php foreach($log as $row): ?> <li><?php echo $row; ?></li> <?php endforeach; ?> </ul> </div><file_sep>/upload/includes/application/controllers/admin/comments.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Admin Comments Controller * * Handles all the comments * * @package 68kb * @subpackage Admin_Controllers * @category Admin_Controllers * @author 68kb Dev Team * @link http://68kb.com/ * @version $Id: comments.php 134 2009-12-02 01:29:40Z suzkaw68 $ */ class Comments extends Controller { /** * Constructor * * Requires needed models and helpers. * * @access public */ function __construct() { parent::__construct(); $this->load->model('init_model'); $this->load->model('comments_model'); $this->load->helper('cookie'); $this->load->helper('gravatar'); $this->load->library('auth'); $this->auth->restrict(); } // ------------------------------------------------------------------------ /** * Index Controller * * Redirects to this->grid * * @access public */ function index() { $data=''; $cookie = get_cookie('commentsgrid_orderby', TRUE); $cookie2 = get_cookie('commentsgrid_orderby_2', TRUE); if ($cookie<>'' && $cookie2 <> '') { redirect('admin/comments/grid/orderby/'.$cookie.'/'.$cookie2); } else { redirect('admin/comments/grid/'); } $this->init_model->display_template('comments/grid', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Revert * * Show a message and redirect the user * * @access public * @param string -- The location to goto * @return array */ function revert($goto) { $data['nav'] = 'comments'; $data['goto'] = $goto; $this->init_model->display_template('content', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Grid * * Show a table of categories * * @access public * @return array */ function grid() { $data['nav'] = 'comments'; if ( ! $this->auth->check_level(2)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } #### settings ### $this->load->library("pagination"); $this->load->helper('text'); $this->load->helper(array('form', 'url')); $config['per_page'] = $this->init_model->settings['max_search']; #### db init ### //total number of rows $config['total_rows'] = $this->db->count_all('comments'); //prepare active record for new query (with limit/offeset/orderby) $this->db->select('comment_ID, comment_author, comment_author_email, comment_author_IP, comment_date, comment_content, comment_approved, article_title, article_uri'); $this->db->from("comments"); $this->db->join('articles', 'comments.comment_article_ID = articles.article_id', 'left'); #### SEARCHING #### if($this->input->post('searchtext') != '') { $q = $this->input->post('searchtext', TRUE); $data['q'] = $q; $this->db->like('comment_author', $q); $this->db->orlike('comment_author_email', $q); $this->db->orlike('comment_author_IP', $q); } if($this->input->post('comment_approved') != '') { $this->db->where('comment_approved', $this->input->post('comment_approved')); $data['s_display'] = $this->input->post('comment_approved'); } #### sniff uri/orderby ### $segment_array = $this->uri->segment_array(); $segment_count = $this->uri->total_segments(); $allowed = array('comment_ID','comment_author', 'comment_author_email', 'comment_author_IP', 'comment_date', 'article_title'); //segments $do_orderby = array_search("orderby",$segment_array); $asc = array_search("asc",$segment_array); $desc = array_search("desc",$segment_array); //do orderby if ($do_orderby!==FALSE) { $orderby = $this->uri->segment($do_orderby+1); if( ! in_array( trim ( $orderby ), $allowed )) { $orderby = 'comment_ID'; } $this->db->order_by($orderby, $this->uri->segment($do_orderby+2)); } else { $orderby = 'comment_ID'; } $data['orderby'] = $orderby; $data['sort'] = $this->uri->segment($do_orderby+2); if ($data['sort'] == 'asc') { $data['opp'] = 'desc'; } else { $data['opp'] = 'asc'; } //set cookie $cookie = array( 'name' => 'commentsgrid_orderby', 'value' => $this->uri->segment($do_orderby+1), 'expire' => '86500' ); $cookie2 = array( 'name' => 'commentsgrid_orderby_2', 'value' => $this->uri->segment($do_orderby+2), 'expire' => '86500' ); set_cookie($cookie); set_cookie($cookie2); #### pagination & data subset ### //remove last segment (assume it's the current offset) if (ctype_digit($segment_array[$segment_count])) { $this->db->limit($config['per_page'], $segment_array[$segment_count]); array_pop($segment_array); } else { $this->db->limit($config['per_page']); } $query = $this->db->get(); $data["items"] = $query->result_array(); $config['base_url'] = site_url(join("/",$segment_array)); $config['uri_segment'] = count($segment_array)+1; $this->pagination->initialize($config); $data["pagination"] = $this->pagination->create_links(); $this->init_model->display_template('comments/grid', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Update Status * * @access public */ function update() { $newstatus = $this->input->post('newstatus', TRUE); foreach ($this->input->post('commentid') AS $key) { $this->comments_model->change_display($newstatus, $key); } redirect('admin/comments/'); } // ------------------------------------------------------------------------ /** * Edit Comment * * @access public */ function edit() { $this->load->library('form_validation'); $data['nav'] = 'comments'; if ( ! $this->auth->check_level(2)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $this->load->helper('form'); $id = (int) $this->uri->segment(4, 0); if ($id=='') { $id = $this->input->post('comment_ID', TRUE); } $this->db->from('comments')->where('comment_ID', $id); $query = $this->db->get(); $data['art'] = $query->row(); $data['action'] = 'modify'; $this->form_validation->set_rules('comment_author', 'lang:kb_name', 'required'); $this->form_validation->set_rules('comment_author_email', 'lang:kb_email', 'required'); $this->form_validation->set_rules('comment_content', 'lang:kb_content', 'required'); $this->form_validation->set_rules('comment_approved', 'lang:kb_display', 'required'); $this->core_events->trigger('comments/validation'); if ($this->form_validation->run() == FALSE) { $this->init_model->display_template('comments/edit', $data, 'admin'); } else { //success $comment_ID = $this->input->post('comment_ID', TRUE); $data = array( 'comment_author' => $this->input->post('comment_author', TRUE), 'comment_author_email' => $this->input->post('comment_author_email', TRUE), 'comment_content' => $this->input->post('comment_content', TRUE), 'comment_approved' => $this->input->post('comment_approved', TRUE), ); $this->comments_model->edit_comment($comment_ID, $data); $this->revert('admin/comments/'); } } // ------------------------------------------------------------------------ /** * Delete Article * * @access public */ function delete() { $data['nav'] = 'comments'; if ( ! $this->auth->check_level(2)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $id = (int) $this->uri->segment(4, 0); $this->comments_model->delete_comment($id); $this->core_events->trigger('comments/delete', $id); $this->revert('admin/comments/'); } } /* End of file comments.php */ /* Location: ./upload/includes/application/controllers/admin/comments.php */ <file_sep>/upload/includes/application/hooks/Post.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * is_post * * This file checks that post data originates from your website. Idea * from vBulletin. * * @package 68kb * @subpackage Hooks * @category Hooks * @author 68kb Dev Team * @version $Id: Post.php 45 2009-07-28 17:20:56Z suzkaw68 $ */ function is_post() { // Here you can enter allowed websites. /* $allowed[] = '.test.com'; $allowed[] = '.paypal.com'; */ if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST' AND !defined('SKIP_REFERRER_CHECK')) { if ($_SERVER['HTTP_HOST'] OR $_ENV['HTTP_HOST']) { $http_host = ($_SERVER['HTTP_HOST'] ? $_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST']); } else if ($_SERVER['SERVER_NAME'] OR $_ENV['SERVER_NAME']) { $http_host = ($_SERVER['SERVER_NAME'] ? $_SERVER['SERVER_NAME'] : $_ENV['SERVER_NAME']); } if ($http_host AND isset($_SERVER['HTTP_REFERER'])) { $http_host = preg_replace('#:80$#', '', trim($http_host)); $referrer_parts = @parse_url($_SERVER['HTTP_REFERER']); $ref_port = intval(@$referrer_parts['port']); $ref_host = $referrer_parts['host'] . ((!empty($ref_port) AND $ref_port != '80') ? ":$ref_port" : ''); $allowed[] = preg_replace('#^www\.#i', '', $http_host); $pass_ref_check = false; foreach ($allowed AS $host) { if (preg_match('#' . preg_quote($host, '#') . '$#siU', $ref_host)) { $pass_ref_check = true; break; } } unset($allowed); if ($pass_ref_check == false) { die('I am sorry this action is not permitted.'); } } } } /* End of file Post.php */ /* Location: ./upload/includes/application/hooks/Post.php */ <file_sep>/upload/themes/admin/default/stats/viewed.php <div id="tabs"> <ul> <li><a href="<?php echo site_url('admin/stats/');?>"><span><?php echo lang('kb_summary'); ?></span></a></li> <li><a href="<?php echo site_url('admin/stats/viewed');?>" class="active"><span><?php echo lang('kb_most_viewed'); ?></span></a></li> <li><a href="<?php echo site_url('admin/stats/searchlog');?>"><span><?php echo lang('kb_search_log'); ?></span></a></li> <li><a href="<?php echo site_url('admin/stats/rating');?>"><span>Rating</span></a></li> </ul> </div> <div class="clear"></div> <div class="wrap"> <table width="100%" class="main" cellpadding="5" cellspacing="1"> <tr> <th>Title</th><th>Views</th> </tr> <?php $alt = true; foreach ($query->result() as $row): ?> <tr<?php if ($alt) echo ' class="row1"'; else echo ' class="row2"'; $alt = !$alt; ?>> <td><a href="<?php echo site_url('article/'.$row->article_uri.'/'); ?>"><?php echo $row->article_title; ?></a></td><td><?php echo $row->article_hits; ?></td> </tr> <?php endforeach; ?> </table> </div><file_sep>/upload/themes/admin/default/glossary/form.php <h2><?php echo lang('kb_glossary'); ?></h2> <div id="form" class="wrap"> <?php if(validation_errors()) { echo '<div class="error">'.validation_errors().'</div>'; } ?> <form method="post" action="<?php echo $action; ?>" class="searchform"> <label for="g_term"><?php echo lang('kb_term'); ?>:</label> <input type="text" name="g_term" id="cName" class="inputtext" value="<?php echo (isset($art->g_term)) ? set_value('g_term', $art->g_term) : set_value('g_term'); ?>" /> <label for="g_definition"><?php echo lang('kb_definition'); ?>:</label> <textarea name="g_definition" id="editcontent" cols="15" rows="15" class="inputtext"><?php echo (isset($art->g_definition)) ? set_value('g_definition', $art->g_definition) : set_value('g_definition'); ?></textarea> <?php $this->core_events->trigger('glossary/form');?> <p><input type="submit" name="submit" class="save" value="<?php echo lang('kb_save'); ?>" /></p> <input type="hidden" name="g_id" value="<?php echo (isset($art->g_id)) ? set_value('g_id', $art->g_id) : set_value('g_id'); ?>" /> <?php echo form_close(); ?> <div class="clear"></div> </div><file_sep>/upload/includes/application/controllers/admin/fields.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Fields Controller * * @package 68kb * @subpackage Admin_Controllers * @category Admin_Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/settings.html * @version $Id: fields.php 84 2009-08-05 03:26:00Z suzkaw68 $ */ class fields extends controller { /** * Constructor * * @access public */ function __construct() { parent::__construct(); $this->load->model('init_model'); $this->load->model('fields_model'); $this->load->helper('cookie'); $this->load->library('auth'); $this->auth->restrict(); } // ------------------------------------------------------------------------ /** * Show utility list * * @access public */ function index() { $data['nav']='articles'; $data['options'] = $this->fields_model->get_fields(); $this->init_model->display_template('fields/grid', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Add Field * * @access public */ function add() { $this->load->library('form_validation'); $data['nav'] = 'articles'; $this->load->helper('form'); $id = (int)$this->uri->segment(4, 0); $data['action']=site_url('admin/fields/add/'); $this->form_validation->set_rules('field_name', 'lang:kb_field_name', 'required'); $this->form_validation->set_rules('field_type', 'lang:kb_field_type', 'rquired'); $this->form_validation->set_rules('field_size', 'Size', 'numeric'); $this->form_validation->set_rules('field_validation', 'lang:kb_parent_cat', ''); $this->form_validation->set_rules('field_label', 'label', ''); $this->form_validation->set_rules('field_options', 'options', ''); if ($this->form_validation->run() == FALSE) { $this->init_model->display_template('fields/form', $data, 'admin'); } else { //success $data = array( 'field_name' => $this->input->post('field_name', TRUE), 'field_type' => $this->input->post('field_type', TRUE), 'field_size' => $this->input->post('field_size', TRUE), 'field_validation' => $this->input->post('field_validation', TRUE), 'field_label' => $this->input->post('field_label', TRUE), 'field_options' => $this->input->post('field_options', TRUE) ); $var = $this->fields_model->add_field($data); $this->revert('admin/fields/'); } } } /* End of file utility.php */ /* Location: ./upload/includes/application/controllers/admin/utility.php */<file_sep>/upload/includes/application/helpers/core_file_helper.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Category Model * * This class is used to handle the categories data. * * @package 68kb * @subpackage Helpers * @category Helpers * @author 68kb Dev Team * @link http://68kb.com/user_guide/helpers/uri.html * @version $Id: core_file_helper.php 96 2009-08-15 02:03:33Z suzkaw68 $ */ // ------------------------------------------------------------------------ /** * Delete Files * * Deletes all files contained in the supplied directory path. * Files must be writable or owned by the system in order to be deleted. * If the second parameter is set to TRUE, any directories contained * within the supplied base directory will be nuked as well. * * This function overrides the system file_helper because we needed to * suppress errors with the unlink function. * * @access public * @param string path to file * @param bool whether to delete any directories found in the path * @return bool */ function delete_files($path, $del_dir = FALSE, $level = 0) { // Trim the trailing slash $path = preg_replace("|^(.+?)/*$|", "\\1", $path); if ( ! $current_dir = @opendir($path)) return; while(FALSE !== ($filename = @readdir($current_dir))) { if ($filename != "." and $filename != "..") { if (is_dir($path.'/'.$filename)) { // Ignore empty folders if (substr($filename, 0, 1) != '.') { delete_files($path.'/'.$filename, $del_dir, $level + 1); } } else { @unlink($path.'/'.$filename); } } } @closedir($current_dir); if ($del_dir == TRUE AND $level > 0) { @rmdir($path); } } /* End of file core_file_helper.php */ /* Location: ./upload/includes/application/helpers/core_file_helper.php */ <file_sep>/upload/includes/application/models/users_model.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Users Model * * Handles users * * @package 68kb * @subpackage Models * @category Models * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/users.html * @version $Id: users_model.php 89 2009-08-13 01:54:20Z suzkaw68 $ */ class Users_model extends model { function __construct() { parent::__construct(); $this->obj =& get_instance(); } // ------------------------------------------------------------------------ /** * Edit User * * @param array $data An array of data. * @uses format_uri * @return true on success. */ function edit_user($user_id, $data) { if (isset($data['password']) && $data['password'] != '') { $data['password'] = md5($data['password']); } $user_id = (int)$user_id; $this->db->where('id', $user_id); $this->db->update('users', $data); if($this->db->affected_rows() > 0) { $this->db->cache_delete_all(); return true; } else { log_message('info', 'Could not edit the user id '. $user_id); return false; } } /** * Get User By ID. * * Get a single user by their ID * * @access public * @param int the id * @return array */ function get_user_by_id($id) { $this->db->from('users')->where('id', $id); $query = $this->db->get(); $data = $query->row(); //echo $this->db->last_query(); $query->free_result(); return $data; } /** * Add User * * Get all the settings from the db. * * @access public * * @return array */ function get_users() { $this->db->from('users'); $query = $this->db->get(); return $query; } } /* End of file users_model.php */ /* Location: ./upload/includes/application/models/users_model.php */ <file_sep>/upload/themes/admin/default/categories/form.php <h2><?php echo lang('kb_categories'); ?></h2> <div id="form" class="wrap"> <?php if(validation_errors()) { echo '<div class="error">'.validation_errors().'</div>'; } ?> <form method="post" action="<?php echo $action; ?>" class="searchform"> <p class="row1"> <label for="cat_name"><?php echo lang('kb_title'); ?>: <em>(<?php echo lang('kb_required'); ?>)</em></label> <input tabindex="1" type="text" class="inputtext" name="cat_name" id="cat_name" value="<?php echo (isset($art->cat_name)) ? set_value('cat_name', $art->cat_name) : set_value('cat_name'); ?>" /> </p> <p class="row2"> <label for="cat_uri"><?php echo lang('kb_uri'); ?>:</label></td> <input tabindex="2" type="text" class="inputtext" name="cat_uri" id="cat_uri" value="<?php echo (isset($art->cat_uri)) ? set_value('cat_uri', $art->cat_uri) : set_value('cat_uri'); ?>" /> </p> <p class="row1"> <label for="cat_description"><?php echo lang('kb_description'); ?>:</label> <textarea tabindex="3" id="editcontent" name="cat_description" id="cat_description" cols="15" rows="15" class="inputtext"><?php echo (isset($art->cat_description)) ? set_value('cat_description', $art->cat_description) : set_value('cat_description'); ?></textarea> </p> <?php $this->core_events->trigger('category/form');?> <table width="100%" cellspacing="0"> <tr> <td class="row2"><label for="cat_parent"><?php echo lang('kb_parent_cat'); ?>:</label></td> <td class="row2"> <select tabindex="4" name="cat_parent" id="cat_parent"> <option value="0"><?php echo lang('kb_no_parent'); ?></option> <?php foreach($options as $row): ?> <?php $default = ((isset($art->cat_parent) && $art->cat_parent == $row['cat_id'])) ? true : false; ?> <option value="<?php echo $row['cat_id']; ?>" <?php echo set_select('cat_parent', $row['cat_id'], $default); ?>><?php echo $row['cat_name']; ?></option> <?php endforeach; ?> </select> </td> </tr> <tr> <td class="row1"><label for="cat_order"><?php echo lang('kb_weight'); ?>:</label></td> <td class="row1"> <input tabindex="5" type="text" name="cat_order" id="cat_order" value="<?php echo (isset($art->cat_order)) ? set_value('cat_order', $art->cat_order) : set_value('cat_order'); ?>" /> <a href="javascript:void(0);" title="<?php echo lang('kb_weight_desc'); ?>" class="tooltip"> <img src="<?php echo base_url(); ?>images/help.png" border="0" alt="<?php echo lang('kb_edit'); ?>" /> </a> </td> </tr> <tr> <td class="row2"><label for="cat_display"><?php echo lang('kb_display'); ?>:</label></td> <td class="row2"> <select tabindex="6" name="cat_display" id="cat_display"> <option value="Y"<?php if(isset($art->cat_display) && $art->cat_display == 'Y') echo ' selected'; ?>><?php echo lang('kb_yes'); ?></option> <option value="N"<?php if(isset($art->cat_display) && $art->cat_display == 'N') echo ' selected'; ?>><?php echo lang('kb_no'); ?></option> </select> </td> </tr> <?php $this->core_events->trigger('categories/form', (isset($art->cat_id)) ? $art->cat_id : ''); ?> </table> <p><input type="submit" tabindex="7" name="submit" class="save" value="<?php echo lang('kb_save'); ?>" /></p> <input type="hidden" name="cat_id" value="<?php echo (isset($art->cat_id)) ? $art->cat_id : ''; ?>" /> <?php echo form_close(); ?> <div class="clear"></div> </div><file_sep>/upload/includes/application/controllers/all.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * KB Controller * * All Controller. Shows all articles * * @package 68kb * @subpackage Controllers * @category Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/articles.html * @version $Id: all.php 46 2009-07-28 17:32:07Z suzkaw68 $ */ class All extends Controller { /** * Constructor * * @return void */ function __construct() { parent::__construct(); log_message('debug', 'All Controller Initialized'); $this->load->model('init_model'); $this->load->model('category_model'); $this->load->model('article_model'); } // ------------------------------------------------------------------------ /** * Index Controller * * Show the home page * * @access public */ function index() { $data['parents'] = $this->category_model->get_categories_by_parent(0); foreach($data['parents']->result() as $row) { $data['articles'][$row->cat_id] = $this->article_model->get_articles_by_catid($row->cat_id); $data['subcats'][$row->cat_id] = $this->category_model->get_categories_by_parent($row->cat_id); } $data['title'] = $this->init_model->get_setting('site_name'); $this->init_model->display_template('all', $data); } } /* End of file kb.php */ /* Location: ./upload/includes/application/controllers/kb.php */<file_sep>/upload/includes/application/plugins/version_pi.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Check for latest release * */ function checklatest() { // Home call details $product_id = 1; $home_url_site = '68kb.com'; $home_url_port = 80; $home_url_kb = '/68downloads/version.php'; $fsock_terminate = false; // Build request $request = 'remote=version&product_id='.urlencode($product_id); $request = $home_url_kb.'?'.$request; // Build HTTP header $header = "GET $request HTTP/1.0\r\nHost: $home_url_site\r\nConnection: Close\r\nUser-Agent: 68kb (www.68kb.com)\r\n"; $header .= "\r\n\r\n"; // Contact license server $fpointer = fsockopen($home_url_site, $home_url_port, $errno, $errstr, 5); $return = ''; if ($fpointer) { fwrite($fpointer, $header); while(!feof($fpointer)) { $return .= fread($fpointer, 1024); } fclose($fpointer); } else { ($fsock_terminate) ? exit : NULL; } // Get rid of HTTP headers $content = explode("\r\n\r\n", $return); $content = explode($content[0], $return); // Assign version to var $version = trim($content[1]); // Clean up variables for security unset($home_url_site, $home_url_kb, $request, $header, $return, $fpointer, $content); return $version; } /* End of file version_pi.php */ /* Location: ./upload/includes/application/plugins/version_pi.php */ <file_sep>/upload/includes/application/controllers/contact.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Article Controller * * Handles the article pages * * @package 68kb * @subpackage Controllers * @category Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/articles.html * @version $Id: contact.php 143 2009-12-04 13:20:38Z suzkaw68 $ */ class Contact extends Controller { function __construct() { parent::__construct(); log_message('debug', 'Contact Controller Initialized'); $this->load->model('init_model'); $this->load->model('category_model'); $this->load->model('comments_model'); $this->load->model('article_model'); $this->load->helper('smiley'); } // ------------------------------------------------------------------------ /** * Index Controller * * Show a contact form * * @access public */ function index() { $data['title'] = $this->lang->line('kb_contact'). ' | '. $this->init_model->get_setting('site_name'); $this->load->helper(array('form', 'url')); $this->load->library('form_validation'); $this->form_validation->set_rules('subject', 'lang:kb_subject', 'required'); $this->form_validation->set_rules('name', 'lang:kb_name', 'required'); $this->form_validation->set_rules('content', 'lang:kb_content', 'required'); $this->form_validation->set_rules('email', 'lang:kb_email', 'required|valid_email'); $this->form_validation->set_rules('captcha', 'lang:kb_captcha', 'required|callback_captcha_check'); if ($this->form_validation->run() == FALSE) { $this->load->plugin('captcha'); /* TODO Get the font_path working. */ $vals = array( 'word' => '', 'img_path' => KBPATH .'uploads/', 'img_url' => base_url() .'uploads/', 'font_path' => '', //KBPATH .'includes/fonts/texb.ttf', 'img_width' => '150', 'img_height' => 30, 'expiration' => 7200 ); $cap = create_captcha($vals); $c_data = array( 'captcha_id' => '', 'captcha_time' => $cap['time'], 'ip_address' => $this->input->ip_address(), 'word' => $cap['word'] ); $query = $this->db->insert_string('captcha', $c_data); $this->db->query($query); $data['cap']= $cap; $this->init_model->display_template('contact', $data); } else { //success //lets get any related article $this->db->select('*'); $this->db->from('articles'); $subject = $this->input->post('subject', TRUE); $terms = explode(' ', $subject); foreach($terms as $row) { if(strlen($row) > 3) { $this->db->orlike('article_keywords', $row); } } $this->db->orderby('article_title', 'asc'); $query = $this->db->get(); $data['articles'] = $query; $data['subject'] = $subject; $data['name'] = $this->input->post('name', TRUE); $data['email'] = $this->input->post('email', TRUE); $data['content'] = $this->input->post('content', TRUE); $this->init_model->display_template('contact_confirm', $data); } } function captcha_check($str) { if ($str == '') { $this->validation->set_message('captcha_check', 'The %s field can not be blank'); return FALSE; } else { $expiration = time()-7200; // Two hour limit $this->db->where('captcha_time < ', $expiration); $this->db->delete('captcha'); // Then see if a captcha exists: $prefix = $this->db->dbprefix; $sql = "SELECT COUNT(*) AS count FROM ".$prefix."captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?"; $binds = array($str, $this->input->ip_address(), $expiration); $query = $this->db->query($sql, $binds); $row = $query->row(); if ($row->count == 0) { $this->form_validation->set_message('captcha_check', 'You must submit the word that appears in the image'); return FALSE; } else { return TRUE; } } } function submit() { $this->load->library('email'); $subject = $this->input->post('subject', TRUE); $name = $this->input->post('name', TRUE); $email = $this->input->post('email', TRUE); $content = $this->input->post('content', TRUE); $to = $this->init_model->get_setting('site_email'); $this->email->from($email, $name); $this->email->to($to); $this->email->subject($subject); $this->email->message($content); if ( ! $this->email->send()) { $data['error'] = $this->email->print_debugger(); } $data['title'] = $this->init_model->get_setting('site_name'); $this->init_model->display_template('thanks', $data); } } /* End of file contact.php */ /* Location: ./upload/includes/application/controllers/contact.php */ <file_sep>/upload/includes/application/controllers/admin/glossary.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Admin Glossary Controller * * Handles the glossary items * * @package 68kb * @subpackage Admin_Controllers * @category Admin_Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/glossary.html * @version $Id: glossary.php 134 2009-12-02 01:29:40Z suzkaw68 $ */ class Glossary extends Controller { /** * Constructor * * Requires needed models and helpers. * * @access public */ function __construct() { parent::__construct(); $this->load->model('init_model'); $this->load->helper('cookie'); $this->load->library('auth'); $this->auth->restrict(); } // ------------------------------------------------------------------------ /** * Index Controller * * Redirects to this->grid * * @access public */ function index() { $data = ''; $cookie = get_cookie('glossarygrid_orderby', TRUE); $cookie2 = get_cookie('glossarygrid_orderby_2', TRUE); if($cookie<>'' && $cookie2 <> '') { redirect('admin/glossary/grid/orderby/'.$cookie.'/'.$cookie2); } else { redirect('admin/glossary/grid/'); } } // ------------------------------------------------------------------------ /** * Revert * * Show a message and redirect the user * * @access public * @param string -- The location to goto * @return array */ function revert($goto) { $data['goto'] = $goto; $data['nav'] = 'glossary'; $this->init_model->display_template('content', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Grid * * Show a table of articles * * It assume this uri sequence: * /controller/simplepagination/[offset] * or * /controller/simplepagination/orderby/fieldname/orientation/[offset] * * @link http://codeigniter.com/forums/viewthread/45709/#217816 * @access public * @return array */ function grid() { #### settings ### $data['nav'] = 'glossary'; if ( ! $this->auth->check_level(3)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $this->load->library("pagination"); $this->load->helper("url"); $config['per_page'] = 25; #### db init ### //total number of rows $config['total_rows'] = $this->db->count_all('glossary'); //prepare active record for new query (with limit/offeset/orderby) //$this->db->select('aID, aURI, aTitle, aCat, aDisplay'); $this->db->from("glossary"); #### sniff uri/orderby ### $segment_array = $this->uri->segment_array(); $segment_count = $this->uri->total_segments(); $allowed = array('g_id','g_term'); //segments $do_orderby = array_search("orderby",$segment_array); $asc = array_search("asc",$segment_array); $desc = array_search("desc",$segment_array); //do orderby if ($do_orderby!==false) { $orderby = $this->uri->segment($do_orderby+1); if( ! in_array( trim ( $orderby ), $allowed )) { $orderby = 'g_id'; } $this->db->order_by($orderby, $this->uri->segment($do_orderby+2)); } else { $orderby = 'g_id'; } $data['orderby'] = $orderby; $data['sort'] = $this->uri->segment($do_orderby+2); if($data['sort'] == 'asc') { $data['opp'] = 'desc'; } else { $data['opp'] = 'asc'; } //set cookie $cookie = array( 'name' => 'glossarygrid_orderby', 'value' => $this->uri->segment($do_orderby+1), 'expire' => '86500' ); $cookie2 = array( 'name' => 'glossarygrid_orderby_2', 'value' => $this->uri->segment($do_orderby+2), 'expire' => '86500' ); set_cookie($cookie); set_cookie($cookie2); #### pagination & data subset ### //remove last segment (assume it's the current offset) if (ctype_digit($segment_array[$segment_count])) { $this->db->limit($config['per_page'], $segment_array[$segment_count]); array_pop($segment_array); } else { $this->db->limit($config['per_page']); } $query = $this->db->get(); $data["items"] = $query->result_array(); $config['base_url'] = site_url(join("/",$segment_array)); $config['uri_segment'] = count($segment_array)+1; $this->pagination->initialize($config); $data["pagination"] = $this->pagination->create_links(); $this->init_model->display_template('glossary/grid', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Edit Category * * @access public */ function edit() { $this->load->library('form_validation'); $data['nav'] = 'glossary'; if ( ! $this->auth->check_level(3)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $this->load->helper('form'); $id = (int) $this->uri->segment(4, 0); $this->db->from('glossary')->where('g_id', $id); $query = $this->db->get(); $row = $query->row(); $query->free_result(); $data['art'] = $row; $data['action'] = site_url('admin/glossary/edit/'.$id); $this->form_validation->set_rules('g_term', 'lang:kb_title', 'required'); $this->form_validation->set_rules('g_definition', 'lang:kb_definition', 'required'); if ($this->form_validation->run() == FALSE) { $this->init_model->display_template('glossary/form', $data, 'admin'); } else { //success $data = array( 'g_term' => $this->input->post('g_term', TRUE), 'g_definition' => $this->input->post('g_definition', TRUE) ); $this->db->where('g_id', $this->input->post('g_id', TRUE)); if ($this->db->update('glossary', $data)) { $this->revert('admin/glossary/'); } } } // ------------------------------------------------------------------------ /** * Add Category * * @access public */ function add() { $this->load->library('form_validation'); $data['nav'] = 'glossary'; if ( ! $this->auth->check_level(3)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $this->load->helper('form'); $data['action'] = site_url('admin/glossary/add'); $this->form_validation->set_rules('g_term', 'lang:kb_title', 'required'); $this->form_validation->set_rules('g_definition', 'lang:kb_definition', 'required'); if ($this->form_validation->run() == FALSE) { $this->init_model->display_template('glossary/form', $data, 'admin'); } else { $data = array( 'g_term' => $this->input->post('g_term', TRUE), 'g_definition' => $this->input->post('g_definition', TRUE) ); if ($this->db->insert('glossary', $data)) { $this->revert('admin/glossary/'); } } } // ------------------------------------------------------------------------ /** * Delete Article * * @access public */ function delete() { $data['nav']='glossary'; if ( ! $this->auth->check_level(3)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $id = (int) $this->uri->segment(4, 0); $this->db->delete('glossary', array('g_id' => $id)); $this->revert('admin/glossary/'); } } /* End of file glossary.php */ /* Location: ./upload/includes/application/controllers/admin/glossary.php */ <file_sep>/upload/includes/application/libraries/Auth.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Auth Libarary * * Handles the article pages * * @package 68kb * @subpackage Libraries * @category Libraries * @author Bramme.net * @link http://www.bramme.net/2008/07/auth-library-for-codeigniter-tutorial/ * @version $Id: Auth.php 130 2009-12-01 18:04:30Z suzkaw68 $ */ class Auth { var $CI = NULL; /** * User data of person attempting login or session/cookie owner * * @var array * @access private */ var $_user_data = array(); function __construct() { $this->CI =& get_instance(); // Load additional libraries, helpers, etc. $this->CI->load->library('session'); $this->CI->load->database(); $this->CI->load->helper('url'); } // ------------------------------------------------------------------------ /** * * Process the data from the login form * * @access public * @param array array with 2 values, username and password (in that order) * @return boolean */ function process_login($login = NULL) { // A few safety checks // Our array has to be set if( ! isset($login)) { return FALSE; } //Our array has to have 2 values //No more, no less! if(count($login) != 2) { return FALSE; } $username = $login[0]; $password = md5($login[1]); $this->CI->db->where('username', $username); $this->CI->db->where('password', $password); $query = $this->CI->db->get('users'); if ($query->num_rows() == 1) { $row = $query->row(); // Our user exists, update db $data = array( 'cookie' => md5(md5($row->id . $username)), 'session' => $this->CI->session->userdata('session_id'), 'custip' => $this->CI->input->ip_address() ); $this->CI->db->where('id', $row->id); $this->CI->db->update('users', $data); // Our user exists, set session. $this->CI->session->set_userdata('logged_user', $username); $this->CI->session->set_userdata('userid', $row->id); $this->CI->session->set_userdata('username', $username); $this->CI->session->set_userdata('cookie', md5(md5($row->id.$username))); $this->CI->session->set_userdata('level', $row->level); return TRUE; } else { // No existing user. return FALSE; } } // ------------------------------------------------------------------------ /** * * This function redirects users after logging in * * @access public * @return void */ function redirect() { if ($this->CI->session->userdata('redirected_from') == FALSE) { redirect('/admin'); } else { redirect($this->CI->session->userdata('redirected_from')); } } // ------------------------------------------------------------------------ /** * * This function restricts users from certain pages. * use restrict(TRUE) if a user can't access a page when logged in * * @access public * @param boolean wether the page is viewable when logged in * @return void */ function restrict($logged_out = FALSE) { // If the user is logged in and he's trying to access a page // he's not allowed to see when logged in, // redirect him to the index! if ($logged_out && $this->logged_in()) { redirect('admin'); } // If the user isn' logged in and he's trying to access a page // he's not allowed to see when logged out, // redirect him to the login page! if ( ! $this->_check_session() || ! $logged_out && ! $this->logged_in()) { $this->CI->session->set_userdata('redirected_from', $this->CI->uri->uri_string()); // We'll use this in our redirect method. redirect('admin/kb/login'); } } // ------------------------------------------------------------------------ /** * * Check the session against the db * * @access public * @param boolean wether the page is viewable when logged in * @return void */ private function _check_session() { $this->CI->db->select('id,username,level')->from('users')->where('username', $this->CI->session->userdata('username'))->where('cookie', $this->CI->session->userdata('cookie')); $query = $this->CI->db->get(); //echo $this->CI->db->last_query(); if ($query->num_rows() <> 1) { return false; } $this->_user_data = $query->result_array(); return true; } // ------------------------------------------------------------------------ /** * * Check the user level * * @access public * @param boolean wether the page is viewable when logged in * @return void */ function check_level($level) { $this->CI->db->select('id,username,level')->from('users') ->where('level <= ', $level) ->where('username', $this->CI->session->userdata('username')) ->where('cookie', $this->CI->session->userdata('cookie')); $query = $this->CI->db->get(); if ($query->num_rows() == 1) { return TRUE; } return FALSE; } // ------------------------------------------------------------------------ /** * * Checks if a user is logged in * * @access public * @return boolean */ function logged_in() { if ($this->CI->session->userdata('logged_user') == FALSE) { return FALSE; } else { return TRUE; } } // ------------------------------------------------------------------------ /** * * Logs user out by destroying the session. * * @access public * @return TRUE */ function logout() { $this->CI->session->sess_destroy(); return TRUE; } } /* End of file: Auth.php */ /* Location: ./system/application/libraries/Auth.php */<file_sep>/upload/themes/admin/default/glossary/grid.php <script language="javascript" type="text/javascript"> <!-- function deleteSomething(url){ removemsg = "<?php echo lang('kb_are_you_sure'); ?>" if (confirm(removemsg)) { document.location = url; } } // --> </script> <h2><?php echo lang('kb_glossary'); ?> <a class="addnew" href="<?php echo site_url('admin/glossary/add');?>"><?php echo lang('kb_add_term'); ?></a></h2> <table class="main" width="100%" cellpadding="5" cellspacing="1"> <tr> <th> <?php $class=''; if(isset($orderby) && isset($opp) && $orderby=="g_id") { $class = $opp; } ?> <?php if(isset($sort) && $sort == 'desc'): ?> <a href="<?php echo site_url('admin/glossary/grid/orderby/g_id/asc'); ?>" class="<?php echo $class; ?>"> <?php else: ?> <a href="<?php echo site_url('admin/glossary/grid/orderby/g_id/desc'); ?>" class="<?php echo $class; ?>"> <?php endif; ?> <?php echo lang('kb_id'); ?> </a> </th> <th> <?php $class=''; if(isset($orderby) && isset($opp) && $orderby=="g_term") { $class = $opp; } ?> <?php if(isset($sort) && $sort == 'desc'): ?> <a href="<?php echo site_url('admin/glossary/grid/orderby/g_term/asc'); ?>" class="<?php echo $class; ?>"> <?php else: ?> <a href="<?php echo site_url('admin/glossary/grid/orderby/g_term/desc'); ?>" class="<?php echo $class; ?>"> <?php endif; ?> <?php echo lang('kb_term'); ?> </a> </th> <th><?php echo lang('kb_actions'); ?></th> </tr> <?php $alt = true; foreach($items as $item): ?> <tr<?php if ($alt) echo ' class="second"'; else echo ' class="first"'; $alt = !$alt; ?>> <td width="5%" nowrap><?php echo $item['g_id']; ?></td> <td class="title"><a href="<?php echo site_url('admin/glossary/edit/'.$item['g_id']); ?>"><?php echo $item['g_term']; ?></a></td> <td width="10%" nowrap> <a href="<?php echo site_url('admin/glossary/edit/'.$item['g_id']); ?>"><img src="<?php echo base_url(); ?>images/page_edit.png" border="0" alt="<?php echo lang('kb_edit'); ?>" title="<?php echo lang('kb_edit'); ?>" /></a> &nbsp; <a href="javascript:void(0);" onclick="deleteSomething('<?php echo site_url('admin/glossary/delete/'.$item['g_id']); ?>')"><img src="<?php echo base_url(); ?>images/page_delete.png" border="0" alt="<?php echo lang('kb_delete'); ?>" title="<?php echo lang('kb_delete'); ?>" /></a> </td> </tr> <?php endforeach; ?> </table> <div class="paginationNum"> <?php echo lang('kb_pages'); ?>: <?php echo $pagination; ?> </div> <table width="20%" align="center"> <tr> <td align="right"><img src="<?php echo base_url(); ?>images/page_edit.png" border="0" alt="<?php echo lang('kb_edit'); ?>" /></td> <td align="left"><?php echo lang('kb_edit'); ?></td> <td align="right"><img src="<?php echo base_url(); ?>images/page_delete.png" border="0" alt="<?php echo lang('kb_delete'); ?>" /></td> <td align="left"><?php echo lang('kb_delete'); ?></td> </tr> </table> <file_sep>/upload/themes/front/default/contact.php <script language="javascript" type="text/javascript"> <!-- // function checkform(frm) { if (frm.subject.value == "") {alert("<?php echo lang('kb_please_enter'); ?> '<?php echo lang('kb_subject'); ?>'."); frm.subject.focus(); return (false);} if (frm.email.value == "") {alert("<?php echo lang('kb_please_enter'); ?> '<?php echo lang('kb_email'); ?>'."); frm.email.focus(); return (false);} if (frm.content.value == "") {alert("<?php echo lang('kb_please_enter'); ?> '<?php echo lang('kb_content'); ?>'."); frm.content.focus(); return (false);} } //--> </script> <?php echo validation_errors(); ?> <form action="<?php echo site_url('contact/index'); ?>" method="post" id="comment_form" onsubmit="return checkform(this)"> <p><input class="text_input" type="text" name="subject" id="subject" value="<?php echo set_value('subject'); ?>" tabindex="1" /><label for="subject"><strong><?php echo lang('kb_subject'); ?></strong></label></p> <p><input class="text_input" type="text" name="name" id="name" value="<?php echo set_value('name'); ?>" tabindex="2" /><label for="name"><strong><?php echo lang('kb_name'); ?></strong></label></p> <p><input class="text_input" type="text" name="email" id="email" value="<?php echo set_value('email'); ?>" tabindex="3" /><label for="email"><strong><?php echo lang('kb_email'); ?></strong></label></p> <p><textarea class="text_input text_area" name="content" id="content" rows="7" tabindex="4"><?php echo set_value('content'); ?></textarea></p> <p><?php echo $cap['image']; ?></p> <p><input type="text" name="captcha" value="" /><label for="captcha"><strong><?php echo lang('kb_captcha'); ?></strong></label></p> <p> <input name="submit" class="form_submit" type="submit" id="submit" tabindex="5" value="Submit" /> </p> </form><file_sep>/upload/themes/front/default/glossary.php <h2><?php echo lang('kb_glossary'); ?></h2> <table border="0" class="glossary_terms" width="100%"> <tr> <td><a href="<?php echo site_url('glossary/term/sym'); ?>">#</a></td> <?php foreach($letter as $row): ?> <td><a href="<?php echo site_url('glossary/term/'.$row); ?>"><?php echo strtoupper($row); ?></a></td> <?php endforeach; ?> </tr> </table> <?php foreach($glossary->result() as $row): ?> <dl> <dt><a name="<?php echo $row->g_term; ?>"></a><?php echo $row->g_term; ?></dt> <dd><?php echo $row->g_definition; ?></dd> </dl> <?php endforeach; ?><file_sep>/upload/includes/application/controllers/rss.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * RSS Controller * * * @package 68kb * @subpackage Controllers * @category Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/articles.html#rss * @version $Id: rss.php 76 2009-07-31 14:47:18Z suzkaw68 $ */ class Rss extends Controller { function __construct() { parent::__construct(); log_message('debug', 'RSS Controller Initialized'); $this->load->model('init_model'); $this->load->model('article_model'); $this->load->helper('xml'); } // ------------------------------------------------------------------------ /** * Default RSS View * * Show the latest articles * * @uses show_feed */ function index() { $data['feed_name'] = $this->init_model->get_setting('site_name'); $data['feed_url'] = base_url(); $data['page_description'] = $this->init_model->get_setting('site_description'); $data['creator_email'] = $this->init_model->get_setting('site_email'); $data['articles'] = $this->article_model->get_latest(); $this->show_feed($data); } // ------------------------------------------------------------------------ /** * Default RSS View * * Show the latest articles * * @param string - The category uri * @uses show_feed */ function category($uri = '') { $this->load->model('category_model'); if($uri <> '') { $uri = $this->input->xss_clean($uri); $data['cat']=$this->category_model->get_cat_by_uri($uri); if($data['cat']) { $id = $data['cat']->cat_id; $data['encoding'] = 'utf-8'; $data['feed_name'] = $data['cat']->cat_name. ' | '. $this->init_model->get_setting('site_name'); $data['feed_url'] = base_url(); $data['page_description'] = $this->init_model->get_setting('site_description'); $data['creator_email'] = $this->init_model->get_setting('site_email'); $data['articles'] = $this->article_model->get_articles_by_catid($id); $this->show_feed($data); } } } // ------------------------------------------------------------------------ /** * Dislay the template * * @access public */ function show_feed($data) { echo $this->init_model->load_body('rss', 'front', $data); } } /* End of file rss.php */ /* Location: ./upload/includes/application/controllers/rss.php */<file_sep>/upload/includes/application/controllers/admin/articles.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Admin Utility Controller * * Handles utilities * * @package 68kb * @subpackage Admin_Controllers * @category Admin_Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/articles.html * @version $Id: articles.php 134 2009-12-02 01:29:40Z suzkaw68 $ */ class Articles extends Controller { /** * Constructor * * Requires needed models and helpers. * * @access public */ function __construct() { parent::__construct(); $this->load->model('init_model'); $this->load->helper('cookie'); $this->load->library('auth'); $this->auth->restrict(); $this->load->model('category_model'); $this->load->model('article_model'); $this->load->model('tags_model'); } // ------------------------------------------------------------------------ /** * Index Controller * * Redirects to this->grid * * @access public */ function index() { $data=''; $cookie = get_cookie('articlesgrid_orderby', TRUE); $cookie2 = get_cookie('articlesgrid_orderby_2', TRUE); if($cookie<>'' && $cookie2 <> '') { redirect('admin/articles/grid/orderby/'.$cookie.'/'.$cookie2); } else { redirect('admin/articles/grid/'); } $this->init_model->display_template('articles/grid', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Revert * * Show a message and redirect the user * * @access public * @param string -- The location to goto * @return array */ function revert($goto) { $data['nav'] = 'articles'; $data['goto'] = $goto; $this->init_model->display_template('content', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Grid * * Show a table of articles * * It assume this uri sequence: * /controller/simplepagination/[offset] * or * /controller/simplepagination/orderby/fieldname/orientation/[offset] * * @link http://codeigniter.com/forums/viewthread/45709/#217816 * @access public * @return array */ function grid() { #### settings ### $data['nav'] = 'articles'; $this->load->library("pagination"); $this->load->helper(array('form', 'url')); $this->load->model('users_model'); $data['authors'] = $this->users_model->get_users(); $data['categories'] = $this->category_model->get_cats_for_select('',0); $config['per_page'] = 25; #### db init ### $data['paginate'] = TRUE; //total number of rows $config['total_rows'] = $this->db->count_all('articles'); //prepare active record for new query (with limit/offeset/orderby) $this->db->distinct(); $this->db->select('articles.article_id, article_uri, article_title, article_display, article_date, article_hits'); $this->db->from("articles"); $this->db->join('article2cat', 'articles.article_id = article2cat.article_id', 'left'); // User Level if ($this->session->userdata('level') == 4) { $this->db->where('article_author', $this->session->userdata['userid']); } #### SEARCHING #### if($this->input->post('searchtext') != '') { $q = $this->input->post('searchtext', TRUE); $data['q'] = $q; $this->db->like('article_title', $q); $this->db->orlike('article_short_desc', $q); $this->db->orlike('article_description', $q); $this->db->orlike('article_uri', $q); } if($this->input->post('article_display') != '') { $this->db->where('article_display', $this->input->post('article_display')); $data['s_display'] = $this->input->post('article_display', TRUE); } if($this->input->post('a_author') != 0) { $this->db->where('article_author', $this->input->post('a_author')); $data['s_author'] = $this->input->post('a_author', TRUE); } if($this->input->post('cat') != 0) { $this->db->where($this->db->dbprefix('article2cat').'.category_id', $this->input->post('cat')); $data['s_cat'] = $this->input->post('cat', TRUE); } #### sniff uri/orderby ### $segment_array = $this->uri->segment_array(); $segment_count = $this->uri->total_segments(); $allowed = array('article_id','article_uri', 'article_title', 'article_display', 'a_hits', 'article_date'); //segments $do_orderby = array_search("orderby",$segment_array); $asc = array_search("asc",$segment_array); $desc = array_search("desc",$segment_array); //do orderby if ($do_orderby !== FALSE) { $orderby = $this->uri->segment($do_orderby+1); if( ! in_array( trim ( $orderby ), $allowed )) { $orderby = 'article_id'; } $this->db->order_by($orderby, $this->uri->segment($do_orderby+2)); } else { $orderby = 'article_id'; } $data['orderby'] = $orderby; $data['sort'] = $this->uri->segment($do_orderby+2); if ($data['sort'] == 'asc') { $data['opp'] = 'desc'; } else { $data['opp'] = 'asc'; } //set cookie $cookie = array( 'name' => 'articlesgrid_orderby', 'value' => $this->uri->segment($do_orderby+1), 'expire' => '86500' ); $cookie2 = array( 'name' => 'articlesgrid_orderby_2', 'value' => $this->uri->segment($do_orderby+2), 'expire' => '86500' ); set_cookie($cookie); set_cookie($cookie2); #### pagination & data subset ### //remove last segment (assume it's the current offset) if($this->input->post('search') == 'go') { $data['paginate']=false; } elseif (ctype_digit($segment_array[$segment_count])) { $this->db->limit($config['per_page'], $segment_array[$segment_count]); array_pop($segment_array); } else { $this->db->limit($config['per_page']); } $query = $this->db->get(); //echo $this->db->last_query(); $results = array(); foreach ($query->result_array() as $art_row) { $art_row['cats'] = $this->category_model->get_cats_by_article($art_row['article_id']); $results[] = $art_row; } $data['items'] = $results; //$query->result_array(); $config['base_url'] = site_url(join("/",$segment_array)); $config['uri_segment'] = count($segment_array)+1; $this->pagination->initialize($config); $data["pagination"] = $this->pagination->create_links(); $this->init_model->display_template('articles/grid', $data, 'admin'); } // ------------------------------------------------------------------------ /** * Edit Article * * @access public */ function edit() { $data['nav'] = 'articles'; $this->load->library('form_validation'); $id = (int)$this->uri->segment(4, 0); if($id == '') { $id=$this->input->post('article_id'); } if($id == '') { redirect('admin/articles/'); } if($this->session->flashdata('error')) { $data['error'] = $this->session->flashdata('error'); } $this->load->helper(array('form', 'url')); $data['art'] = $this->article_model->get_article_by_id($id); $data['options'] = $this->category_model->get_cats_for_select('',0, $id, TRUE); $data['attach'] = $this->article_model->get_attachments($id); $data['action'] = 'modify'; $level = $this->auth->check_level(4); if ( ! $level) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } elseif ($this->session->userdata('level') == 4 && $this->session->userdata('userid') != $data['art']->article_author) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $continue = true; $this->form_validation->set_rules('article_title', 'lang:kb_title', 'required'); $this->form_validation->set_rules('article_uri', 'lang:kb_uri', 'alpha_dash'); $this->form_validation->set_rules('article_keywords', 'lang:kb_keywords', 'trim|xss_clean'); $this->form_validation->set_rules('article_short_desc', 'lang:kb_short_description', 'trim|xss_clean'); $this->form_validation->set_rules('article_description', 'lang:kb_description', 'required|trim|xss_clean'); $this->form_validation->set_rules('article_display', 'lang:kb_display', 'trim'); $this->form_validation->set_rules('article_order', 'lang:kb_weight', 'numeric'); $this->core_events->trigger('articles/validation'); if ($this->form_validation->run() == FALSE) { $this->init_model->display_template('articles/edit', $data, 'admin'); } else { //success $edit_data = array( 'article_uri' => $this->input->post('article_uri', TRUE), 'article_title' => $this->input->post('article_title', TRUE), 'article_keywords' => $this->input->post('article_keywords', TRUE), 'article_short_desc' => $this->input->post('article_short_desc', TRUE), 'article_description' => $this->input->post('article_description', TRUE), 'article_display' => $this->input->post('article_display', TRUE), 'article_order' => $this->input->post('article_order', TRUE) ); if ($this->article_model->edit_article($id, $edit_data)) { //$this->tags_model->insert_tags($id, $this->input->post('tags')); $this->category_model->insert_cats($id, $this->input->post('cat')); //now file uploads if ($_FILES['userfile']['name'] != "") { $target = KBPATH .'uploads/'.$id; $this->_mkdir($target); $config['upload_path'] = $target; $config['allowed_types'] = $this->config->item('attachment_types'); $this->load->library('upload', $config); if ( ! $this->upload->do_upload()) { $this->session->set_flashdata('error', $this->upload->display_errors()); redirect('admin/articles/edit/'.$id); } else { $upload = array('upload_data' => $this->upload->data()); $insert = array( 'article_id' => $id, 'attach_name' => $upload['upload_data']['file_name'], 'attach_type' => $upload['upload_data']['file_type'], 'attach_size' => $upload['upload_data']['file_size'] ); $this->db->insert('attachments', $insert); $data['attach'] = $this->article_model->get_attachments($id); } } //final continue if($continue) { $this->core_events->trigger('articles/edit', $id); if (isset($_POST['save']) && $_POST['save']<>"") { redirect('admin/articles/edit/'.$id); } else { $this->revert('admin/articles/'); } } } else { $data['error'] = 'Could not edit article'; $this->init_model->display_template('articles/edit', $data, 'admin'); } } } // ------------------------------------------------------------------------ /** * Add Article * * @access public */ function add() { $this->load->library('form_validation'); $data['nav'] = 'articles'; if ( ! $this->auth->check_level(4)) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $this->load->helper(array('form', 'url')); $data['options'] = $this->category_model->get_cats_for_select('',0, '', TRUE); $data['action'] = 'add'; $this->form_validation->set_rules('article_title', 'lang:kb_title', 'required'); $this->form_validation->set_rules('article_uri', 'lang:kb_uri', 'alpha_dash'); $this->form_validation->set_rules('article_keywords', 'lang:kb_keywords', 'trim|xss_clean'); $this->form_validation->set_rules('article_short_desc', 'lang:kb_short_description', 'trim|xss_clean'); $this->form_validation->set_rules('article_description', 'lang:kb_description', 'trim|xss_clean'); $this->form_validation->set_rules('article_display', 'lang:kb_display', 'trim'); $this->form_validation->set_rules('article_order', 'lang:kb_weight', 'numeric'); $this->core_events->trigger('articles/validation'); if ($this->form_validation->run() == FALSE) { $this->init_model->display_template('articles/add', $data, 'admin'); } else { //success $cats = $this->input->post('cat'); $article_uri = $this->input->post('article_uri', TRUE); $data = array( 'article_uri' => $article_uri, 'article_author' => $this->session->userdata('userid'), 'article_title' => $this->input->post('article_title', TRUE), 'article_keywords' => $this->input->post('article_keywords', TRUE), 'article_short_desc' => $this->input->post('article_short_desc', TRUE), 'article_description' => $this->input->post('article_description', TRUE), 'article_display' => $this->input->post('article_display', TRUE), 'article_order' => $this->input->post('article_order', TRUE) ); $id = $this->article_model->add_article($data); if (is_int($id)) { //$tags = $this->input->post('tags'); //$this->tags_model->insert_tags($id, $tags); $this->category_model->insert_cats($id, $cats); $this->core_events->trigger('articles/add', $id); if ($_FILES['userfile']['name'] != "") { $target = KBPATH .'uploads/'.$id; $this->_mkdir($target); $config['upload_path'] = $target; $config['allowed_types'] = $this->config->item('attachment_types'); $this->load->library('upload', $config); if ( ! $this->upload->do_upload()) { $this->session->set_flashdata('error', $this->upload->display_errors()); redirect('admin/articles/edit/'.$id); } else { $upload = array('upload_data' => $this->upload->data()); $insert = array( 'article_id' => $id, 'attach_name' => $upload['upload_data']['file_name'], 'attach_type' => $upload['upload_data']['file_type'], 'attach_size' => $upload['upload_data']['file_size'] ); $this->db->insert('attachments', $insert); $data['attach'] = $this->article_model->get_attachments($id); } } if (isset($_POST['save']) && $_POST['save']<>"") { redirect('admin/articles/edit/'.$id); } else { $this->revert('admin/articles/'); } } else { $this->revert('admin/articles/'); } } } // ------------------------------------------------------------------------ /** * Delete Article * * @access public */ function delete() { $data['nav'] = 'articles'; $id = (int) $this->uri->segment(4, 0); $level = $this->auth->check_level(4); if ( ! $level) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } elseif ($this->session->userdata('level') == 4 && $this->session->userdata('userid') != $id) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $this->article_model->delete_article($id); $this->revert('admin/articles/'); } // ------------------------------------------------------------------------ /** * Update status * * @access public */ function update() { $ordID = $this->input->post('articleid', TRUE); $newstatus = $_POST["newstatus"]; $data['nav'] = 'articles'; foreach ($_POST['articleid'] AS $key) { if ($newstatus == 'Y') { //active $data = array('article_display' => 'Y'); $this->db->where('article_id', $key); $this->db->update('articles', $data); } elseif ($newstatus == 'N') { //not active $data = array('article_display' => 'N'); $this->db->where('article_id', $key); $this->db->update('articles', $data); } elseif ($newstatus == 'D') { //delete $level = $this->auth->check_level(4); if ( ! $level) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } elseif ($this->session->userdata('level') == 4 && $this->session->userdata('userid') != $key) { $data['not_allowed'] = TRUE; $this->init_model->display_template('content', $data, 'admin'); return FALSE; } $this->article_model->delete_article($key); } } $this->revert('admin/articles/'); } // ------------------------------------------------------------------------ /** * Delete an Uploaded file. * * @access private */ function upload_delete() { $this->load->helper('file'); $id = (int) $this->uri->segment(4, 0); $this->db->select('attach_id, article_id, attach_name')->from('attachments')->where('attach_id', $id); $query = $this->db->get(); if ($query->num_rows() > 0) { $row = $query->row(); $article_id = $row->article_id; unlink(KBPATH .'uploads/'.$row->article_id.'/'.$row->attach_name); $this->db->delete('attachments', array('attach_id' => $id)); redirect('admin/articles/edit/'.$article_id.'/#attachments'); } else { redirect('admin/articles/'); } } // ------------------------------------------------------------------------ /** * Attempt to make a directory to house uploaded files. * * @access private */ function _mkdir($target) { // from php.net/mkdir user contributed notes if(file_exists($target)) { if( ! @is_dir($target)) { return false; } else { return true; } } // Attempting to create the directory may clutter up our display. if(@mkdir($target)) { $stat = @stat(dirname($target)); $dir_perms = $stat['mode'] & 0007777; // Get the permission bits. @chmod($target, $dir_perms); return true; } else { if(is_dir(dirname($target))) { return false; } } // If the above failed, attempt to create the parent node, then try again. if ($this->_mkdir(dirname($target))) { return $this->_mkdir($target); } return false; } } /* End of file articles.php */ /* Location: ./upload/includes/application/controllers/admin/articles.php */ <file_sep>/upload/includes/application/controllers/article.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * Article Controller * * Handles the article pages * * @package 68kb * @subpackage Controllers * @category Controllers * @author 68kb Dev Team * @link http://68kb.com/user_guide/overview/articles.html * @version $Id: article.php 143 2009-12-04 13:20:38Z suzkaw68 $ */ class Article extends Controller { function __construct() { parent::__construct(); log_message('debug', 'Article Controller Initialized'); $this->load->model('init_model'); $this->load->model('users_model'); $this->load->model('category_model'); $this->load->model('comments_model'); $this->load->model('article_model'); $this->load->helper('smiley'); } // ------------------------------------------------------------------------ /** * Index Controller * * Show a single article * * @access public * @param string the unique uri * @return array */ function index($uri='') { $this->load->helper('typography'); $this->load->helper('form'); $this->load->helper('cookie'); $this->load->helper('gravatar'); $data['title'] = $this->init_model->get_setting('site_name'); if($uri<>'' && $uri<>'index') { $uri = $this->input->xss_clean($uri); $article = $this->article_model->get_article_by_uri($uri); if($article) { $data['article'] = $article; $this->article_model->add_hit($data['article']->article_id); //format description $data['article']->article_description = $this->article_model->glossary($data['article']->article_description); // call hooks $arr = array('article_id' => $data['article']->article_id, 'article_title' => $data['article']->article_title); if($this->core_events->trigger('article/title', $arr) != '') { $data['article']->article_description = $this->core_events->trigger('article/title', $arr); } $arr = array('article_id' => $data['article']->article_id, 'article_description' => $data['article']->article_description); if($this->core_events->trigger('article/description', $arr) != '') { $data['article']->article_description = $this->core_events->trigger('article/description', $arr); } $data['article_cats'] = $this->category_model->get_cats_by_article($data['article']->article_id); $data['attach'] = $this->article_model->get_attachments($data['article']->article_id); $data['author'] = $this->users_model->get_user_by_id($data['article']->article_author); $data['title'] = $data['article']->article_title. ' | '. $this->init_model->get_setting('site_name'); $data['meta_keywords'] = $data['article']->article_keywords; $data['meta_description'] = $data['article']->article_short_desc; $data['comments'] = $this->comments_model->get_article_comments($data['article']->article_id); $data['comments_total'] = $this->comments_model->get_article_comments_count($data['article']->article_id); $data['comment_author'] = get_cookie('kb_author', TRUE); $data['comment_author_email'] = get_cookie('kb_email', TRUE); $data['comment_template'] = $this->init_model->load_body('comments', 'front', $data); } else { $data = ''; } } else { $data=''; } $this->init_model->display_template('article', $data); } // ------------------------------------------------------------------------ /** * Show the printer page * * @access public */ function printer() { $this->load->helper('typography'); $uri = $this->uri->segment(3, 0); if($uri<>'' && $uri<>'index') { $uri = $this->input->xss_clean($uri); $data['article']=$this->article_model->get_article_by_uri($uri); $data['article']->article_description = parse_smileys($data['article']->article_description, $this->config->item('base_url')."/images/"); $data['title'] = $data['article']->article_title. ' | '. $this->init_model->get_setting('site_name'); } else { $data=''; } echo $this->init_model->load_body('printer', 'front', $data); } // ------------------------------------------------------------------------ /** * Add Comment * * @access public */ function comment() { if($this->init_model->get_setting('comments') != 'Y') { redirect('/kb'); } $this->load->model('comments_model'); $this->load->library('form_validation'); $this->load->helper('cookie', 'session'); $this->load->helper('form'); $this->form_validation->set_rules('comment_author', 'lang:kb_name', 'required'); $this->form_validation->set_rules('comment_author_email', 'lang:kb_email', 'required|valid_email'); $this->form_validation->set_rules('comment_content', 'lang:kb_description', 'required'); if ($this->form_validation->run() == FALSE) { $this->index($this->input->post('uri')); } else { //success $parent = $this->input->post('cat_parent', TRUE); $author = $this->input->post('comment_author', TRUE); $email = $this->input->post('comment_author_email', TRUE); $comment = $this->input->post('comment_content', TRUE); set_cookie('kb_author', $author, '86500'); set_cookie('kb_email', $email, '86500'); $data = array( 'comment_article_ID' => $this->input->post('comment_article_ID', TRUE), 'comment_author' => $author, 'comment_author_email' => $email, 'comment_content' => $comment, 'comment_author_IP' => $this->input->ip_address() ); $id = $this->comments_model->add_comment($data); $this->comments_model->email_admin($id, $data); $this->index($this->input->post('uri')); } } // ------------------------------------------------------------------------ /** * Rate Article * * @access public */ function rate() { $article_uri = $this->input->post('article_uri', TRUE); $article_id = (int)$this->input->post('article_id', TRUE); $rating = $this->input->post('rating', TRUE); if($rating == 1) { $rating = '+1'; } else { $rating = '-1'; } $this->db->set('article_rating', 'article_rating'.$rating, FALSE); $this->db->where('article_id', $article_id); $this->db->update('articles'); $this->session->set_flashdata('rating', TRUE); redirect('article/'.$article_uri.'/#rating'); } // ------------------------------------------------------------------------ /** * Remap * * Need to document this. * * @link http://codeigniter.com/user_guide/general/controllers.html#remapping * @access public * @param string the unique uri * @return array */ function _remap($method) { if($method == 'printer') { $this->printer(); } elseif($method == 'comment') { $this->comment(); } elseif($method == 'rate') { $this->rate(); } else { $this->index($method); } } } /* End of file article.php */ /* Location: ./upload/includes/application/controllers/article.php */ <file_sep>/upload/themes/admin/default/settings/main.php <h2><?php echo lang('kb_main_settings'); ?></h2> <div id="form" class=""> <?php if(validation_errors()) { echo '<div class="error">'.validation_errors().'</div>'; } ?> <?php echo form_open('admin/settings/main'); ?> <table width="100%" cellspacing="0"> <tr> <td class="row1"><label for="site_name"><?php echo lang('kb_site_title'); ?>:</label></td> <td class="row1"><input type="text" size="50" name="site_name" id="site_name" value="<?php echo (isset($settings['site_name'])) ? form_prep($settings['site_name']) : ''; ?>" /></td> </tr> <tr> <td class="row2"><label for="site_keywords"><?php echo lang('kb_site_keywords'); ?>:</label></td> <td class="row2"><input type="text" size="50" name="site_keywords" id="site_keywords" value="<?php echo (isset($settings['site_keywords'])) ? form_prep($settings['site_keywords']) : ''; ?>" /></td> </tr> <tr> <td class="row1"><label for="site_description"><?php echo lang('kb_site_description'); ?>:</label></td> <td class="row1"><input type="text" size="50" name="site_description" id="site_description" value="<?php echo (isset($settings['site_description'])) ? form_prep($settings['site_description']) : ''; ?>" /></td> </tr> <tr> <td class="row2"><label for="site_email"><?php echo lang('kb_email'); ?>:</label></td> <td class="row2"><input type="text" size="50" name="site_email" id="site_email" value="<?php echo (isset($settings['site_email'])) ? form_prep($settings['site_email']) : ''; ?>" /></td> </tr> <tr> <td class="row1"><label for="max_search"><?php echo lang('kb_max_search'); ?>:</label></td> <td class="row1"><input type="text" size="50" name="max_search" id="max_search" value="<?php echo (isset($settings['max_search'])) ? form_prep($settings['max_search']) : ''; ?>" /></td> </tr> <tr> <td class="row2"><label for="max_search"><?php echo lang('kb_allow_comments'); ?>:</label></td> <td class="row2"> <select name="comments"> <option value="Y"<?php echo (isset($settings['comments']) && $settings['comments'] == 'Y') ? ' selected' : ''; ?>><?php echo lang('kb_yes'); ?></option> <option value="N"<?php echo (isset($settings['comments']) && $settings['comments'] == 'N') ? ' selected' : ''; ?>><?php echo lang('kb_no'); ?></option> </select> </td> </tr> <tr> <td class="row1"><label for="cache_time"><?php echo lang('kb_cache_time'); ?>:</label></td> <td class="row1"> <input type="text" size="4" name="cache_time" id="cache_time" value="<?php echo (isset($settings['cache_time'])) ? form_prep($settings['cache_time']) : ''; ?>" /> <a href="javascript:void(0);" title="<?php echo lang('kb_cache_desc'); ?>" class="tooltip"> <img src="<?php echo base_url(); ?>images/help.png" border="0" alt="<?php echo lang('kb_edit'); ?>" /> </a> </td> </tr> <?php $this->core_events->trigger('settings/form');?> </table> <p><input type="submit" name="submit" class="save" value="<?php echo lang('kb_save'); ?>" /></p> <?php echo form_close(); ?> <div class="clear"></div> </div><file_sep>/upload/themes/admin/default/modules/managemodules.php <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>js/jquery.fancybox/jquery.fancybox.css" media="screen" /> <script type="text/javascript" src="<?php echo base_url();?>js/jquery.fancybox/jquery.fancybox-1.2.1.pack.js"></script> <script type="text/javascript"> $(document).ready(function() { $("a.ajax").fancybox(); }); </script> <script language="javascript" type="text/javascript"> <!-- function deleteSomething(url){ removemsg = "<?php echo lang('kb_delete_module'); ?>" if (confirm(removemsg)) { document.location = url; } } // --> </script> <h2><?php echo lang('kb_active_modules'); ?></h2> <?php if(isset($msg) && $msg != ''): ?> <div id="message" class="updated fade"><p><?php echo $msg; ?></p></div> <?php elseif($this->session->flashdata('msg')): ?> <div id="message" class="updated fade"><p><?php echo $this->session->flashdata('msg'); ?></p></div> <?php endif; ?> <table width="100%" border="0" cellspacing="0" cellpadding="3" class="main"> <tr> <th><?php echo lang('kb_name'); ?></th> <th><?php echo lang('kb_description'); ?></th> <th width="5%"><?php echo lang('kb_version'); ?></th> <th><?php echo lang('kb_actions'); ?></th> </tr> <?php $alt = true; foreach($modules as $row): ?> <tr<?php if ($alt) echo ' class="second"'; else echo ' class="first"'; $alt = !$alt; ?>> <td nowrap> <?php echo $row['displayname']; ?> <?php if(file_exists(KBPATH.'my-modules/'.$row['name'].'/admin.php')): ?> <br /><a href="<?php echo site_url('admin/modules/show/'.$row['name']); ?>"><?php echo lang('kb_admin'); ?></a> <?php endif; ?> </td> <td> <?php echo $row['description']; ?> <?php if(isset($row['help_file'])) echo '<a class="ajax" title="'.$row['displayname'].'" href="'.$row['help_file'].'">Help</a>'; ?> </td> <td> <?php echo $row['version']; ?> <?php if($row['server_version'] > $row['version']): ?> <br /><a href="<?php echo site_url('admin/modules/upgrade/'.$row['id']); ?>"><?php echo lang('kb_upgrade_module'); ?></a> <?php endif; ?> </td> <td nowrap> <?php if($row['active'] == 1): ?> <span class="active"> <a href="<?php echo site_url('admin/modules/manage/'.$row['id'].'/deactivate'); ?>"><?php echo lang('kb_deactivate'); ?></a> </span> <?php else: ?> <span class="inactive"><a href="<?php echo site_url('admin/modules/manage/'.$row['id'].'/activate'); ?>"><?php echo lang('kb_activate'); ?></a></span> <?php endif; ?> </td> </tr> <?php endforeach; ?> </table> <h2><?php echo lang('kb_deactive_modules'); ?></h2> <table width="100%" border="0" cellspacing="0" cellpadding="3" class="main"> <tr> <th><?php echo lang('kb_name'); ?></th> <th><?php echo lang('kb_description'); ?></th> <th width="5%"><?php echo lang('kb_version'); ?></th> <th><?php echo lang('kb_actions'); ?></th> </tr> <?php $alt = true; foreach($unactive as $row): ?> <tr<?php if ($alt) echo ' class="second"'; else echo ' class="first"'; $alt = !$alt; ?>> <td nowrap> <?php echo $row['displayname']; ?> </td> <td><?php echo $row['description']; ?></td> <td><?php echo $row['version']; ?></td> <td nowrap> <span class="inactive"><a href="<?php echo site_url('admin/modules/activate/'.$row['name']); ?>"><?php echo lang('kb_activate'); ?></a> &nbsp; <a href="javascript:void(0);" onclick="deleteSomething('<?php echo site_url('admin/modules/manage/'.$row['name'].'/delete'); ?>')"><img src="<?php echo base_url(); ?>images/page_delete.png" border="0" alt="<?php echo lang('kb_delete'); ?>" title="<?php echo lang('kb_delete'); ?>" /></a> </span> </td> </tr> <?php endforeach; ?> </table> <file_sep>/upload/themes/front/default/contact_confirm.php <?php /** * Show articles */ ?> <?php if (isset($articles) && $articles->num_rows() > 0): ?> <h2><?php echo lang('kb_contact_related'); ?></h2> <ul class="articles"> <?php foreach($articles->result() as $row): ?> <li> <a href="<?php echo site_url("article/".$row->article_uri."/"); ?>"><?php echo $row->article_title; ?></a><br /> <?php echo $row->article_short_desc; ?> </li> <?php endforeach; ?> </ul> <?php endif; ?> <form action="<?php echo site_url('contact/submit'); ?>" method="post"> <input type="hidden" name="subject" id="subject" value="<?php echo $subject; ?>" /> <input type="hidden" name="name" id="name" value="<?php echo $name; ?>" /> <input type="hidden" name="email" id="email" value="<?php echo $email; ?>" /> <input type="hidden" name="content" id="content" value="<?php echo $content; ?>" /> <p><?php echo lang('kb_contact_confirm'); ?></p> <p><input name="submit" class="form_submit" type="submit" id="submit" tabindex="5" value="<?php echo lang('kb_submit_message'); ?>" /></p> </form><file_sep>/upload/includes/application/libraries/core_Loader.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 68KB * * An open source knowledge base script * * @package 68kb * @author 68kb Dev Team * @copyright Copyright (c) 2009, 68 Designs, LLC * @license http://68kb.com/user_guide/license.html * @link http://68kb.com * @since Version 1.0 */ // ------------------------------------------------------------------------ /** * 68KB Core Loader * * This extends the CI_Loader library so we can set the views to another directory. * * @package 68kb * @subpackage Libraries * @category Libraries * @author 68kb Dev Team * @link http://68kb.com/ * @version $Id: core_Loader.php 49 2009-07-28 19:21:51Z suzkaw68 $ */ class core_Loader extends CI_Loader{ var $_ci_view_path = ''; function __construct() { parent::__construct(); $this->_ci_view_path = KBPATH .'themes/'; } } /* End of file core_loader.php */ /* Location: ./upload/includes/application/libraries/core_loader.php */
814e696c4a4f02ddbc9fa51b796ae342ffe5aebb
[ "Markdown", "Ant Build System", "HTML", "PHP" ]
99
PHP
eleazarfunk/68KB
55d27738a4e30d502ce7a93c71282aa329e54b0f
a5f087efdb6e3066362eee604c9ceb6771d77a7e
refs/heads/master
<file_sep># Dice_Roller_app_Project ![screen_recording](https://github.com/Tanushree-coder/Dice_Roller_app_Project/blob/master/screen_recording.mp4) <file_sep>package com.example.dice_roller_app; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import java.util.Random; import static com.example.dice_roller_app.R.anim.rotate; public class MainActivity extends AppCompatActivity { ImageView diceImage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); diceImage=findViewById(R.id.dice_image); diceImage.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ rotateDice(); } }); } private void rotateDice() { Random r=new Random(); int i =r.nextInt(6)+1; Animation anim = AnimationUtils.loadAnimation(this,R.anim.rotate); diceImage.startAnimation(anim); switch(i){ case 1: diceImage.setImageResource(R.drawable.d1); break; case 2: diceImage.setImageResource(R.drawable.d2); break; case 3: diceImage.setImageResource(R.drawable.d3); break; case 4: diceImage.setImageResource(R.drawable.d4); break; case 5: diceImage.setImageResource(R.drawable.d5); break; case 6: diceImage.setImageResource(R.drawable.d6); break; } } }
0c41a044a7ea145c38311901709b1702ba28d74b
[ "Markdown", "Java" ]
2
Markdown
Tanushree1705/Dice_Roller_app_Project
37d9ee1e444e8b14148bd997817a1e929647e690
5cebfddace8b5a2c1d479b972ef514414dd40fce
refs/heads/master
<file_sep>var Vue = require('vue'); var VueRouter = require('vue-router'); Vue.use(VueRouter); Vue.use(require('vue-resource')); var router = new VueRouter({ hashbang: false, history: true }); require('vue-desktop'); import { default as routes } from './route'; router.map(routes); router.start(Vue.extend({ components: { app: require('./app.vue') } }), 'body');<file_sep>install: @npm --registry=http://registry.npm.taobao.org install @if [ ! -f "$$(which webpack)" ]; then sudo npm --registry=http://registry.npm.taobao.org install webpack -g; fi deploy: install @npm run deploy dev: install @npm run dev<file_sep># vue-desktop-starter A starter for vue-desktop. Used plugins: - vue-i18n - vue-resource - vue-router # Usage ```Bash # Run webpack with watch option make dev # Run webpack in production mode(use UglifyJs) make build # Run webpack in deploy mode(use UglifyJs and set public-path) make deploy ``` # LICENSE MIT.
07474f5d1c2670d80526c009c0f18e0911386b3a
[ "JavaScript", "Makefile", "Markdown" ]
3
JavaScript
tangxuke/vue-desktop-starter
4c68eb88f80d5284c696e7ff8da29c265269284b
2379dacb775ce714296c6f6ebbe9e62c891311ea
refs/heads/main
<file_sep># covid-19.github.io ## Cazuri zilnice in fiecare judet Date cazuri noi zilnice in fiecare judet <file_sep> const counties = "AB AG AR B BC BH BN BR BT BV BZ CJ CL CS CT CV DB DJ GJ GL GR HD HR IF IL IS MH MM MS NT OT PH SB SJ SM SV TL TM TR VL VN VS".split(" "); const currentDay = 31; let root = document.documentElement; const loadData = function() { fetch("/covid-19.github.io/data.json") .then(res => res.json()) .then(data => autoFill(data)) } const autoFill = function(data) { let countiesWithData = data.countyData.map((o)=> { let total = 0; if (o.cases != undefined) { o.cases.forEach((data) => { total = total + parseInt(data.number) }); } o.totalCases = total; return o; } ) countiesWithData.sort((a,b) => a.totalCases - b.totalCases); let elements = data.countyData.flatMap( o => o.cases).flatMap( o => o.number); let min = elements.reduce(function (a, b) { return Math.min(a,b); }) let max = elements.reduce(function (a, b) { return Math.max(a,b); }) let x = 45; let x1 = (max-min)/3 + x; root.style.setProperty("--rows", (currentDay+2)); root.style.setProperty("--columns", (countiesWithData.length+1)); let container = document.querySelector("#container"); container.appendChild(createGridItem("","item")); for(let i = 1 ; i <= currentDay; i++) { container.appendChild(createGridItem((new Date("2020", "9", i).toLocaleDateString('en-US', {day: 'numeric', month: 'short'})),"item")); } container.appendChild(createGridItem("Total", "item")); for(let i = 0; i < countiesWithData.length; i++) { container.appendChild(createGridItem(countiesWithData[i].countyId, "item ")); const casesData = [] countiesWithData[i].cases.forEach(e => { casesData[new Date(e['date']).getDate()] = e.number; }); for(let j = 1; j <= currentDay; j++ ) { let item = createGridItem(casesData[j]); if (casesData[j] < x) { item.style = "background-color:" + calculateGreenToYellow(casesData[j], min, x, x); } else { item.style = "background-color:" + calculateYellowToRed(casesData[j], x, max ,x1); } container.appendChild(item); } container.appendChild(createGridItem(countiesWithData[i].totalCases, "item")); } } const createGridItem = function(text, itemClass = "item border fade-in") { let gridItem = document.createElement("div"); gridItem.className = itemClass; if (text != undefined) gridItem.innerHTML = text; return gridItem; } const calculateGreenToYellow = function(value, min, max, middle = (max-min)/2){ let red = 0; let green = 0; if (value <= middle) { let ratio = value/middle; red = 255*ratio; green = 175+(255-175)*ratio; } return "rgba(" + Math.round(red) + "," + Math.round(green) + ", 107)"; } const calculateYellowToRed = function(value, min, max, middle = (max-min)/2){ let red = 0; let green = 0; let ratio = value/(max-middle); red = 248; green = 150-(150*(ratio-1)); return "rgba(" + Math.round(red) + "," + Math.round(green) + ", 50)"; } const percentile = function(arr, p) { if (arr.length === 0) return 0; if (typeof p !== 'number') throw new TypeError('p must be a number'); if (p <= 0) return arr[0]; if (p >= 1) return arr[arr.length - 1]; var index = (arr.length - 1) * p, lower = Math.floor(index), upper = lower + 1, weight = index % 1; if (upper >= arr.length) return arr[lower]; return arr[lower] * (1 - weight) + arr[upper] * weight; }
7e3d4886d1fe79e7677b2f384c0c96a8b5ed2f83
[ "Markdown", "JavaScript" ]
2
Markdown
radupetrica/covid-19.github.io
cab64b1cd86e54f2d26b3aba1039579892c38540
fe8406e0e2fb3afb93fbdda7631b0c37cbd675d0
refs/heads/master
<repo_name>GEugene98/EnglishLab<file_sep>/Исходники/EnglishLab_WindowsApplication/MainModule/Views/IMainView.cs using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; namespace MainModule.Views { public interface IMainView { #region Statistic string UserName { set; } string Level { set; } int CountLearntWords { set; } int CountWordSetsOnLearning { set; } int GoalPrecent { set; } string Goal { set; } #endregion #region Activities object GrammarActivities { set; } object ListeningActivities { set; } object PhrasesActivities { set; } object WordSetsOnLearning { set; } object SelectedTopic { get; } object SelectedListeningActivity { get; } object SlectedPhrasesActivity { get; } object SelectedWordSet { get; } event EventHandler GrammarActivitySelected; event EventHandler ListeningActivitySelected; event EventHandler PhrasesActivitySelected; #endregion #region Vocabulary //List<ListViewItem> WordSets { set; } void AddOrUpdateWordSet(object wordSet, Bitmap picture, string group); bool UpdateWordSet(object wordSet, string group); event EventHandler TakeSetToLearn; event EventHandler RemoveSetAtLearning; object UserVocabulary { set; } string Word { get; } string Transcription { get; } string Translation { get; } event EventHandler AddWord; event EventHandler RemoveWord; #endregion #region Grammar object GrammarTopics { set; } event EventHandler GrammarTopicSelected; #endregion #region TrainingMaterials //object TrainingMaterials { set; } event EventHandler TrainingMaterialSelected; #endregion event EventHandler INeedToUpdate; } } <file_sep>/Исходники/EnglishLab_WindowsApplication/MainModule/Views/MainView.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MetroFramework.Forms; namespace MainModule.Views { public partial class MainView : UserControl, IMainView { private static MainView MainViewControl; public static MainView Instance { get { if (MainViewControl == null) MainViewControl = new MainView(); return MainViewControl; } } private Panel ContainerPanel; private MainView() { InitializeComponent(); Dock = DockStyle.Fill; ContainerPanel = Dashboard.Instance.viewPanel; mainTabs.SelectedIndex = activitiesTabs.SelectedIndex = 0; //grammarActivitiesBox.Items[0] = ""; //grammarActivitiesBox.Items[0] = ""; //grammarActivitiesBox.Items[0] = ""; //grammarActivitiesBox.Items[0] = ""; //grammarActivitiesBox.Items[0] = ""; } #region Implementation IMainView public string UserName { set { greetingMessage.Text = greetingMessage.Text.Replace("username", value); materialsMessage.Text = materialsMessage.Text.Replace("username", value); } } public string Level { get; set; } public int CountLearntWords { set => learnt.Text = value.ToString(); } public int CountWordSetsOnLearning { set => onLearning.Text = value.ToString(); } public int GoalPrecent { set => progress.Value = value; } public string Goal { set => goal.Text = value; } public object GrammarActivities { set => grammarActivitiesBox.DataSource = value; } public object ListeningActivities { set => listeningBox.DataSource = value; } public object PhrasesActivities { set => phrasesBox.DataSource = value; } public object WordSetsOnLearning { set { setsOnLearning.DataSource = null; setsOnLearning.DataSource = value; } } public object SelectedTopic => grammarActivitiesBox.SelectedItem; public object SelectedListeningActivity => listeningBox.SelectedItem; public object SlectedPhrasesActivity => phrasesBox.SelectedItem; public object SelectedWordSet { get; private set; } public object UserVocabulary { set => userWordsTable.DataSource = value; } public string Word { get; private set; } public string Transcription { get; private set; } public string Translation { get; private set; } public object GrammarTopics { set => grammarBox.DataSource = value; } //public object TrainingMaterials { set => materialsBox.DataSource = value; } public event EventHandler GrammarActivitySelected; public event EventHandler ListeningActivitySelected; public event EventHandler PhrasesActivitySelected; public event EventHandler TakeSetToLearn; public event EventHandler RemoveSetAtLearning; public event EventHandler AddWord; public event EventHandler RemoveWord; public event EventHandler GrammarTopicSelected; public event EventHandler TrainingMaterialSelected; public event EventHandler INeedToUpdate; public void AddOrUpdateWordSet(object wordSet, Bitmap picture, string group) { if (!UpdateWordSet(wordSet, group)) { string name = wordSet.ToString(); imageList.Images.Add(name, picture); ListViewItem item = new ListViewItem(); item.Group = allSetsBox.Groups[group]; item.Text = name; item.ImageKey = name; item.Tag = wordSet; allSetsBox.Items.Add(item); } } public bool UpdateWordSet(object wordSet, string group) { bool updated = false; foreach (ListViewItem listItem in allSetsBox.Items) if (listItem.Text == wordSet.ToString()) { listItem.Tag = wordSet; if (listItem.Group.Name != group) { listItem.Group = allSetsBox.Groups[group]; updated = true; } } return updated; } #endregion private void addWordBtn_Click(object sender, EventArgs e) { Word = (String.IsNullOrWhiteSpace(wordBox.Text)) ? null : wordBox.Text; Transcription = (String.IsNullOrWhiteSpace(transcriptionBox.Text)) ? null : transcriptionBox.Text; Translation = (String.IsNullOrWhiteSpace(translationBox.Text)) ? null : translationBox.Text; wordBox.Text = "Слово "; transcriptionBox.Text = "Транскрипция "; translationBox.Text = "Перевод "; if (AddWord != null) AddWord(this, EventArgs.Empty); } private void someBox_Enter(object sender, EventArgs e) { string text = (sender as TextBox).Text; if (text == "Слово " || text == "Транскрипция " || text == "Перевод ") ((TextBox)sender).Clear(); } private Presenters.WordCardsPresenter CardsPresenter; private void cardsTile_Click(object sender, EventArgs e) { Dashboard.Instance.Text = cardsTile.Text; Dashboard.Instance.Refresh(); WordCardsView wordCardsView = new WordCardsView(); CardsPresenter = new Presenters.WordCardsPresenter(wordCardsView, setsOnLearning.SelectedItem); ContainerPanel.Controls.Remove(this); ContainerPanel.Controls.Add(wordCardsView); } private void wtTile_Click(object sender, EventArgs e) { Dashboard.Instance.Text = wtTile.Text; Dashboard.Instance.Refresh(); ContainerPanel.Controls.Remove(this); var wtw = new WordTestView(setsOnLearning.SelectedItem, true); wtw.Close += Wtw_Close; ContainerPanel.Controls.Add(wtw); } private void Wtw_Close(object sender, EventArgs e) { if (INeedToUpdate != null) INeedToUpdate(this, EventArgs.Empty); } private void twTile_Click(object sender, EventArgs e) { Dashboard.Instance.Text = twTile.Text; Dashboard.Instance.Refresh(); ContainerPanel.Controls.Remove(this); ContainerPanel.Controls.Add(new WordTestView(setsOnLearning.SelectedItem, false)); } private void constructorTile_Click(object sender, EventArgs e) { Dashboard.Instance.Text = constructorTile.Text; Dashboard.Instance.Refresh(); ContainerPanel.Controls.Remove(this); ContainerPanel.Controls.Add(new WordBuilderView()); } private void userWordsTable_DataSourceChanged(object sender, EventArgs e) { userWordsTable.Sort(userWordsTable.Columns[3], ListSortDirection.Ascending); } private void allSetsBox_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { if (allSetsBox.FocusedItem.Bounds.Contains(e.Location) == true) { var context = new ContextMenuStrip(); context.ShowImageMargin = false; if (allSetsBox.SelectedItems[0].Group == allSetsBox.Groups["allGroup"]) context.Items.Add("Изучать"); if (allSetsBox.SelectedItems[0].Group == allSetsBox.Groups["onLearningGroup"]) context.Items.Add("Не изучать"); context.Click += Context_Click; context.Show(Cursor.Position); } } } private void Context_Click(object sender, EventArgs e) { SelectedWordSet = allSetsBox.SelectedItems[0].Tag; var menu = sender as ContextMenuStrip; switch (menu.Items[0].Text) { case "Изучать": if (TakeSetToLearn != null) TakeSetToLearn(this, EventArgs.Empty); break; case "Не изучать": if (RemoveSetAtLearning != null) RemoveSetAtLearning(this, EventArgs.Empty); break; } } private void grammarBox_SelectedIndexChanged(object sender, EventArgs e) { Dashboard.Instance.Text = "Грамматика"; Dashboard.Instance.Refresh(); ContainerPanel.Controls.Remove(this); if (grammarBox.SelectedIndex == 0) ContainerPanel.Controls.Add(new DocViewer("1.rtf")); if (grammarBox.SelectedIndex == 1) ContainerPanel.Controls.Add(new DocViewer("2.rtf")); if (grammarBox.SelectedIndex == 2) ContainerPanel.Controls.Add(new DocViewer("3.rtf")); if (grammarBox.SelectedIndex == 3) ContainerPanel.Controls.Add(new DocViewer("4.rtf")); if (grammarBox.SelectedIndex == 4) ContainerPanel.Controls.Add(new DocViewer("5.rtf")); if (grammarActivitiesBox.SelectedIndex == 5) ContainerPanel.Controls.Add(new DocViewer("6.rtf")); } private void metroTile9_Click(object sender, EventArgs e) //lit { Dashboard.Instance.Text = "Литература"; Dashboard.Instance.Refresh(); ContainerPanel.Controls.Remove(this); ContainerPanel.Controls.Add(new DocViewer("lit.rtf")); } private void metroTile10_Click(object sender, EventArgs e) //sci { Dashboard.Instance.Text = "Наука"; Dashboard.Instance.Refresh(); ContainerPanel.Controls.Remove(this); ContainerPanel.Controls.Add(new DocViewer("sci.rtf")); } private void metroTile8_Click(object sender, EventArgs e) //ch { Dashboard.Instance.Text = "Для детей"; Dashboard.Instance.Refresh(); ContainerPanel.Controls.Remove(this); ContainerPanel.Controls.Add(new DocViewer("kids.rtf")); } private void metroTile7_Click(object sender, EventArgs e) // cul { Dashboard.Instance.Text = "Кулинария"; Dashboard.Instance.Refresh(); ContainerPanel.Controls.Remove(this); ContainerPanel.Controls.Add(new DocViewer("cooking.rtf")); } private void metroTile6_Click(object sender, EventArgs e) // talk { Dashboard.Instance.Text = "Болтовня по-английски"; Dashboard.Instance.Refresh(); ContainerPanel.Controls.Remove(this); ContainerPanel.Controls.Add(new DocViewer("talk.rtf")); } private void grammarActivitiesBox_SelectedIndexChanged(object sender, EventArgs e) { Dashboard.Instance.Text = "Упражнения"; Dashboard.Instance.Refresh(); ContainerPanel.Controls.Remove(this); if (grammarActivitiesBox.SelectedIndex == 0) ContainerPanel.Controls.Add(new DocViewer("ga1.rtf")); if (grammarActivitiesBox.SelectedIndex == 1) ContainerPanel.Controls.Add(new DocViewer("ga2.rtf")); } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/EnglishLab/Program.cs using System; using System.Diagnostics; using System.IO; namespace EnglishLab { static class Program { static void Main() { if (File.Exists(Path.Combine(Environment.CurrentDirectory, "UserInfo.dat"))) Process.Start(Path.Combine(Environment.CurrentDirectory, "MainModule.exe")); else Process.Start(@"FirstStart\FirstStart.exe"); } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/MainModule/Views/WordBuilderView.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MainModule.Views { public partial class WordBuilderView : UserControl, IWordBuilderView { public WordBuilderView() { InitializeComponent(); Dock = DockStyle.Fill; } public string InjectableWord { get; set; } public string Description { set => descriptionBox.Text = value; } public List<string> PartsOfWord { private get; set; } public bool Correct { private get; set; } public event EventHandler WordEntered; private void toMainView_Click(object sender, EventArgs e) { Panel containerPanel = Dashboard.Instance.viewPanel; containerPanel.Controls.Remove(this); containerPanel.Controls.Add(MainView.Instance); Dashboard.Instance.Text = Dashboard.HeaderText; Dashboard.Instance.Refresh(); } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/WordSetManager/WordSet.cs using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.IO; using System.Text; using System.Threading.Tasks; namespace WordSetManager { [Serializable] public class WordSet { private string Name; public Bitmap Picture { get; private set; } private List<Word> WordList; protected string CSVPath; public int CountWords { get => WordList.Count; } public int CountLearntWords { get { int sum = 0; foreach (Word word in WordList) { if (word.IsLearnt) sum++; } return sum; } } public WordSet(string name) { WordList = new List<Word>(); //CurrentList = new Word[5]; Name = name; r = new Random(); } public WordSet(string name, string pathToImage) : this(name) => Picture = new Bitmap(Image.FromFile(pathToImage)); public WordSet(string name, string pathToImage, string pathToCSV) : this(name, pathToImage) => CSVPath = pathToCSV; public void LoadFromCSV(string path) { string[] wordStrings = File.ReadAllLines(path); for (int i = 0; i < wordStrings.Length; i++) { string[] wordStr = wordStrings[i].Split(';'); Word word = new Word(wordStr[0], wordStr[1], wordStr[2]); WordList.Add(word); } } public void Load() => LoadFromCSV(CSVPath); public void AddWord(string text, string translation, string description) { Word word = new Word(text, translation, description); WordList.Add(word); } public void AddWord(Word word) => WordList.Add(word); public void RemoveWord(Word word) => WordList.Remove(word); public DataTable GetDataTable() { DataTable dataTable = new DataTable(); dataTable.Columns.Add("Слово"); dataTable.Columns.Add("Транскрипция"); dataTable.Columns.Add("Перевод"); dataTable.Columns.Add("Прогресс слова"); foreach (Word word in WordList) { DataRow dataRow = dataTable.NewRow(); dataRow[0] = word.ToString(); dataRow[1] = word.Description; dataRow[2] = word.Translation; dataRow[3] = word.Progress; dataTable.Rows.Add(dataRow); } return dataTable; } public static List<WordSet> GetList(string csvDirectory) { DirectoryInfo directory = new DirectoryInfo(csvDirectory); List<WordSet> wordSetList = new List<WordSet>(); foreach (FileInfo file in directory.GetFiles("*.csv")) { string csv = file.FullName, name = file.Name.Split('.')[0], pic = Path.Combine(csvDirectory, "Pictures", file.Name.Split('.')[0] + ".png"); wordSetList.Add(new WordSet(name, pic, csv)); } return wordSetList; } public override string ToString() => Name; #region ForActivities private Queue<Word> Words; private int NextIndex = 0; private bool NextWordGotten; public Word GetNextWord() { if (NextIndex == WordList.Count) NextIndex = 0; var word = WordList[NextIndex]; NextIndex++; NextWordGotten = true; return word; } private int PreviousIndex = -1; public Word GetPreviousWord() { if (PreviousIndex == -1) { PreviousIndex = WordList.Count - 1; return WordList[PreviousIndex]; } if (NextWordGotten) { PreviousIndex = NextIndex - 2; NextWordGotten = false; return WordList[PreviousIndex]; } var word = WordList[PreviousIndex]; PreviousIndex--; NextIndex = PreviousIndex + 2; return word; } public Word GetNextWordForLearning() { if (Words == null || Words.Count == 0) { Words = new Queue<Word>(); WordList[0].Progress = 1; WordList.Sort((a, b) => a.Progress.CompareTo(b.Progress)); for (int i = 0; i < 5; i++) { if (WordList[i].Progress < 10 && !Words.Contains(WordList[i])) Words.Enqueue(WordList[i]); } } return Words.Dequeue(); } Random r; public Word GetRandomWordExcepting(Word word) { //Word rndWord; //do //{ return WordList[r.Next(WordList.Count - 1)]; //} //while (rndWord == word); //return rndWord; } public void MakeWordLearnt(Word word) { word.Progress = 10; } #endregion } }<file_sep>/Исходники/EnglishLab_WindowsApplication/MainModule/Views/WordTestView.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing.Printing; using System.Speech.Synthesis; using WordSetManager; namespace MainModule.Views { public partial class WordTestView : UserControl { WordSet WordSet; Word CurrentWord; bool WordToTranslation; Button[] Variants; Color DColor; public event EventHandler Close; public WordTestView(object wordSet, bool wordToTranslation) { InitializeComponent(); Dock = DockStyle.Fill; WordSet = wordSet as WordSet; WordToTranslation = wordToTranslation; Variants = new Button[] { variant1, variant2, variant3, variant4 }; DColor = variant1.BackColor; LoadWord(); } private void toMainView_Click(object sender, EventArgs e) { Panel containerPanel = Dashboard.Instance.viewPanel; if (Close != null) Close(this, EventArgs.Empty); containerPanel.Controls.Remove(this); containerPanel.Controls.Add(MainView.Instance); Dashboard.Instance.Text = Dashboard.HeaderText; Dashboard.Instance.Refresh(); } private void Variant_MouseEnter(object sender, EventArgs e) => ((Button)sender).ForeColor = Color.White; private void Variant_MouseLeave(object sender, EventArgs e) => ((Button)sender).ForeColor = Color.Black; private void play_Click(object sender, EventArgs e) { SpeechSynthesizer speaker = new SpeechSynthesizer(); speaker.SelectVoice("Microsoft Zira Desktop"); speaker.SpeakAsync(wordBox.Text); } private void variant_Click(object sender, EventArgs e) { var variant = sender as Button; if (WordToTranslation) { if (variant.Text == CurrentWord.Translation) { CurrentWord.Progress++; LoadWord(); } else variant.BackColor = Color.Red; } else { if (variant.Text == CurrentWord.ToString()) { CurrentWord.Progress++; LoadWord(); } else variant.BackColor = Color.Red; } } private void LoadWord() { for (int i = 0; i < Variants.Length; i++) { Variants[i].BackColor = DColor; } CurrentWord = WordSet.GetNextWordForLearning(); if (WordToTranslation) { wordBox.Text = CurrentWord.ToString(); descriptionBox.Text = CurrentWord.Description; do { for (int i = 0; i < Variants.Length; i++) { Variants[i].Text = WordSet.GetRandomWordExcepting(CurrentWord).Translation; } } while ( Variants[0].Text == Variants[1].Text || Variants[0].Text == Variants[2].Text || Variants[0].Text == Variants[3].Text || Variants[1].Text == Variants[0].Text || Variants[1].Text == Variants[2].Text || Variants[1].Text == Variants[3].Text || Variants[2].Text == Variants[0].Text || Variants[2].Text == Variants[1].Text || Variants[2].Text == Variants[3].Text || Variants[3].Text == Variants[0].Text || Variants[3].Text == Variants[1].Text || Variants[3].Text == Variants[2].Text ); Variants[(new Random()).Next(3)].Text = CurrentWord.Translation; } else { wordBox.Text = CurrentWord.Translation; descriptionBox.Text = ""; do { for (int i = 0; i < Variants.Length; i++) { Variants[i].Text = WordSet.GetRandomWordExcepting(CurrentWord).ToString(); } } while ( Variants[0].Text == Variants[1].Text || Variants[0].Text == Variants[2].Text || Variants[0].Text == Variants[3].Text || Variants[1].Text == Variants[0].Text || Variants[1].Text == Variants[2].Text || Variants[1].Text == Variants[3].Text || Variants[2].Text == Variants[0].Text || Variants[2].Text == Variants[1].Text || Variants[2].Text == Variants[3].Text || Variants[3].Text == Variants[0].Text || Variants[3].Text == Variants[1].Text || Variants[3].Text == Variants[2].Text ); Variants[(new Random()).Next(3)].Text = CurrentWord.ToString(); } } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/FirstStart/Presenters/TestPresenter.cs using System; using FirstStart.Views; using FirstStart.Models; using UserData; namespace FirstStart.Presenters { class TestPresenter { ITestView TestView; QuestionManager _QuestionManager; public TestPresenter(ITestView view, QuestionManager questionManager) { TestView = view; _QuestionManager = questionManager; TestView.AnswerEntered += TestView_AnswerEntered; TestView.VariantChosen += TestView_VariantChosen; TestView.SkipClick += TestView_SkipClick; TestView.FinishClick += TestView_FinishClick; TestView.MaxCountQuestions = _QuestionManager.CountQuestions; ShowNextQuestion(); } private void TestView_FinishClick(object sender, EventArgs e) => TestView.SuccessFinish(); private void TestView_SkipClick(object sender, EventArgs e) => ShowNextQuestion(); private void TestView_VariantChosen(object sender, EventArgs e) { _QuestionManager.CheckAnswer(TestView.SelectedVariant); TestView.Status = _QuestionManager.RightGrammar.ToString(); ShowNextQuestion(); } private void TestView_AnswerEntered(object sender, EventArgs e) { _QuestionManager.CheckAnswer(TestView.EnteredAnswer); TestView.Status = _QuestionManager.RightGrammar.ToString(); ShowNextQuestion(); } private void ShowNextQuestion() { try { Question question = _QuestionManager.GetNextQuestion(); TestView.Mode = question.Mode; TestView.Question = question.TextQuestion; if (question.Mode == Mode.Choose) TestView.Variants = question.Variants; TestView.Progress++; TestView.Status = String.Format("{0} ({1}/{2})", question.Skill.ToString(), TestView.Progress, _QuestionManager.CountQuestions); } catch { TestView.SuccessFinish(); } } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/MainModule/Presenters/MainViewPresenter.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UserData; using WordSetManager; using MainModule.Views; namespace MainModule.Presenters { public class MainViewPresenter { IMainView MainView; User ActiveUser; public MainViewPresenter(IMainView mainView) { MainView = mainView; ActiveUser = User.GetUser("UserInfo.dat"); //ActiveUser = new User("ff", Level.Elementary); MainView.UserName = ActiveUser.ToString(); foreach (WordSet set in WordSet.GetList("WordSets")) mainView.AddOrUpdateWordSet(set, set.Picture, "allGroup"); foreach (WordSet set in ActiveUser.SetsOnLearning) { if (set.ToString() == "Мой словарь") continue; mainView.AddOrUpdateWordSet(set, set.Picture, "onLearningGroup"); } MainView.AddWord += MainView_AddWord; MainView.TakeSetToLearn += MainView_TakeSetToLearn; MainView.RemoveSetAtLearning += MainView_RemoveSetAtLearning; MainView.INeedToUpdate += MainView_INeedToUpdate; UpdateInfo(); } private void MainView_INeedToUpdate(object sender, EventArgs e) { UpdateInfo(); } private void MainView_RemoveSetAtLearning(object sender, EventArgs e) { ActiveUser.RemoveSetFromLearning(MainView.SelectedWordSet); MainView.UpdateWordSet(MainView.SelectedWordSet, "allGroup"); UpdateInfo(); } private void MainView_TakeSetToLearn(object sender, EventArgs e) { ActiveUser.AddSetToLearn(MainView.SelectedWordSet); MainView.UpdateWordSet(MainView.SelectedWordSet, "onLearningGroup"); UpdateInfo(); } private void MainView_AddWord(object sender, EventArgs e) { ActiveUser.AddWordInUserDictiornary(MainView.Word, MainView.Translation, MainView.Transcription); UpdateInfo(); } private void UpdateInfo() { MainView.CountLearntWords = ActiveUser.CountLearntWords; MainView.UserVocabulary = ActiveUser.UserDictornary.GetDataTable(); MainView.CountWordSetsOnLearning = ActiveUser.CountSetsOnLearning; MainView.WordSetsOnLearning = ActiveUser.SetsOnLearning; MainView.Level = ActiveUser.UserLevel.ToString(); ActiveUser.Save(); } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/MainModule/Program.cs using MainModule.Views; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using MainModule.Presenters; namespace MainModule { static class Program { /// <summary> /// Главная точка входа для приложения. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(Dashboard.Instance); } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/FirstStart/Views/Test.cs using System; using System.Windows.Forms; using MetroFramework.Forms; namespace FirstStart.Views { public partial class Test : MetroForm, ITestView { private VariantPanel VariantPanel; private WritePanel WritePanel; public Test() { InitializeComponent(); DialogResult = DialogResult.Abort; VariantPanel = new VariantPanel(); VariantPanel.Dock = DockStyle.Fill; panelForQuestion.Controls.Add(VariantPanel); VariantPanel.VariantsArray[0].Click += Var0_Click; VariantPanel.VariantsArray[1].Click += Var1_Click; VariantPanel.VariantsArray[2].Click += Var2_Click; VariantPanel.VariantsArray[3].Click += Var3_Click; WritePanel = new WritePanel(); WritePanel.Dock = DockStyle.Fill; panelForQuestion.Controls.Add(WritePanel); WritePanel.NextButton.Click += NextButton_Click; } #region Реализация ITestView private Mode _Mode; public Mode Mode { get { return _Mode; } set { if (value == Mode.Choose) { WritePanel.Visible = false; VariantPanel.Visible = true; } else if (value == Mode.Answer) { VariantPanel.Visible = false; WritePanel.Visible = true; } _Mode = value; } } public int Progress { get { return progress.Value; } set { progress.Value = value; } } public int MaxCountQuestions { set { progress.Maximum = value; } } public string Status { set { status.Text = value; } } public string Question { set { if (Mode == Mode.Answer) WritePanel.Browser.DocumentText = value; else if (Mode == Mode.Choose) VariantPanel.Browser.DocumentText = value; } } public string[] Variants { set { for (int i = 0; i < value.Length; i++) VariantPanel.VariantsArray[i].Text = value[i]; } } private int _SelectedVariant; public int SelectedVariant { get { return _SelectedVariant; } private set { _SelectedVariant = value; if (VariantChosen != null) VariantChosen(this, EventArgs.Empty); } } private string _EnteredAnswer; public string EnteredAnswer { get { return _EnteredAnswer; } private set { _EnteredAnswer = value; if (AnswerEntered != null) AnswerEntered(this, EventArgs.Empty); } } public event EventHandler FinishClick; public event EventHandler SkipClick; public event EventHandler VariantChosen; public event EventHandler AnswerEntered; public void SuccessFinish() { DialogResult = DialogResult.OK; Close(); } #endregion private void skip_Click(object sender, EventArgs e) { if (SkipClick != null) SkipClick(this, EventArgs.Empty); } private void end_Click(object sender, EventArgs e) { if (FinishClick != null) FinishClick(this, EventArgs.Empty); } private void Var0_Click(object sender, EventArgs e) => SelectedVariant = 0; private void Var1_Click(object sender, EventArgs e) => SelectedVariant = 1; private void Var2_Click(object sender, EventArgs e) => SelectedVariant = 2; private void Var3_Click(object sender, EventArgs e) => SelectedVariant = 3; private void NextButton_Click(object sender, EventArgs e) => EnteredAnswer = WritePanel.Answer; private void Test_FormClosed(object sender, FormClosedEventArgs e) { if (e.CloseReason == CloseReason.ApplicationExitCall) { DialogResult = DialogResult.Abort; } } } }<file_sep>/Исходники/EnglishLab_WindowsApplication/FirstStart/Program.cs using System; using System.Windows.Forms; using FirstStart.Views; using FirstStart.Presenters; using FirstStart.Models; using FirstStart.Properties; using MetroFramework.Forms; using UserData; using System.Diagnostics; using System.IO; namespace FirstStart { static class Program { [STAThread] static void Main() { //Auto-generted code Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //****************** try { StartDialog startDialog = new StartDialog(); Application.Run(startDialog); if (startDialog.DialogResult == DialogResult.OK) { User user = null; if (startDialog.UserLevel == Level.StartTest) { Test test = new Test(); QuestionManager manager = new QuestionManager(Resources.test); TestPresenter presenter = new TestPresenter(test, manager); Application.Run(test); if (test.DialogResult == DialogResult.OK) { Application.Run(new FinishDialog(manager)); user = new User(startDialog.UserName, manager.TotalLevel); } else return; } else user = new User(startDialog.UserName, startDialog.UserLevel); user.Save(@".\UserInfo.dat"); Process.Start(@".\MainModule.exe"); } } catch (Exception ex) { MessageBox.Show(ex.Message + '\n' + Environment.CurrentDirectory); } } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/FirstStart/Models/QuestionManager.cs using System; using System.Collections.Generic; using System.Xml.Linq; using UserData; namespace FirstStart.Models { public class QuestionManager { private Question[] Questions; private Question ActiveQuestion; private int IndexNextQuestion; public int CountGrammar { get; private set; } public int CountListening { get; private set; } public int CountSpeaking { get; private set; } //private int CountReading; public int CountWriting { get; private set; } public int RightGrammar { get; private set; } public int RightListening { get; private set; } public int RightSpeaking { get; private set; } //private int RightReading; public int RightWriting { get; private set; } public float AveragePrecent { get { return (int)Math.Round(RightGrammarPrecent + RightListeningPrecent + RightSpeakingPrecent + RightWritingPrecent) / 4; } } public float RightGrammarPrecent { get { return ((float)RightGrammar / (float)CountGrammar) * 100; } } public float RightListeningPrecent { get { return ((float)RightListening / (float)CountListening) * 100; } } public float RightSpeakingPrecent { get { return ((float)RightSpeaking / (float)CountSpeaking) * 100; } } public float RightWritingPrecent { get { return ((float)RightWriting / (float)CountWriting) * 100; } } public Level TotalLevel { get { float average = AveragePrecent; if (average < 25) return Level.Beginner; if (average >= 25 && average < 60) return Level.Elementary; if (average >= 60 && average < 95) return Level.Intermediate; if (average >= 95) return Level.Advanced; return Level.Beginner; } } public int TotalRight { get { return RightGrammar + RightListening + RightSpeaking + RightWriting; } } public readonly int CountQuestions; public QuestionManager(string xmlDocumentText) { Questions = GetArrayQuestions(xmlDocumentText); CountQuestions = Questions.Length; } private Question[] GetArrayQuestions(string xmlDocumentText) { XDocument doc = XDocument.Parse(xmlDocumentText); List<Question> allQuestionsList = new List<Question>(); List<Question> listening = GetListeningQuestions(doc); foreach (var item in listening) allQuestionsList.Add(item); List<Question> grammar = GetGrammarQuestions(doc); foreach (var item in grammar) allQuestionsList.Add(item); List<Question> speaking = GetSpeakingQuestions(doc); foreach (var item in speaking) allQuestionsList.Add(item); List<Question> writing = GetWritingQuestions(doc); foreach (var item in writing) allQuestionsList.Add(item); return allQuestionsList.ToArray(); } private List<Question> GetGrammarQuestions(XDocument doc) { List<Question> questions = new List<Question>(); DocumentMaker maker = new DocumentMaker("Resources/template.html", Skill.Grammar); foreach (XElement questionElement in doc.Element("questions").Elements("grammar")) foreach (XElement question in questionElement.Elements("qw")) { XElement q = question.Element("q"); XElement @as = question.Element("as"); XAttribute right = q.Attribute("right"); XAttribute type = q.Attribute("type"); List<string> variants = new List<string>(); foreach (XElement variant in @as.Elements("a")) variants.Add(variant.Value); if (type.Value == "choose") questions.Add(new Question(Skill.Grammar, maker.GetHTMLFromTextQuestion(q.Value), int.Parse(right.Value), variants.ToArray())); if (type.Value == "answer") questions.Add(new Question(Skill.Grammar, maker.GetHTMLFromTextQuestion(q.Value), variants.ToArray())); } CountGrammar = questions.Count; return questions; } private List<Question> GetListeningQuestions(XDocument doc) { List<Question> questions = new List<Question>(); DocumentMaker maker = new DocumentMaker("Resources/template_video.html", Skill.Listening); foreach (XElement questionElement in doc.Element("questions").Elements("listening")) foreach (XElement question in questionElement.Elements("qw")) { XElement q = question.Element("q"); XElement @as = question.Element("as"); XAttribute right = q.Attribute("right"); XAttribute type = q.Attribute("type"); List<string> variants = new List<string>(); foreach (XElement variant in @as.Elements("a")) variants.Add(variant.Value); if (type.Value == "choose") questions.Add(new Question(Skill.Listening, maker.GetHTMLFromTextQuestion(q.Value), int.Parse(right.Value), variants.ToArray())); if (type.Value == "answer") questions.Add(new Question(Skill.Listening, maker.GetHTMLFromTextQuestion(q.Value), variants.ToArray())); } CountListening = questions.Count; return questions; } private List<Question> GetSpeakingQuestions(XDocument doc) { List<Question> questions = new List<Question>(); DocumentMaker maker = new DocumentMaker("Resources/template_video.html", Skill.Speaking); foreach (XElement questionElement in doc.Element("questions").Elements("speaking")) foreach (XElement question in questionElement.Elements("qw")) { XElement q = question.Element("q"); XElement @as = question.Element("as"); XAttribute right = q.Attribute("right"); XAttribute type = q.Attribute("type"); List<string> variants = new List<string>(); foreach (XElement variant in @as.Elements("a")) variants.Add(variant.Value); if (type.Value == "choose") questions.Add(new Question(Skill.Speaking, maker.GetHTMLFromTextQuestion(q.Value), int.Parse(right.Value), variants.ToArray())); if (type.Value == "answer") questions.Add(new Question(Skill.Speaking, maker.GetHTMLFromTextQuestion(q.Value), variants.ToArray())); } CountSpeaking = questions.Count; return questions; } private List<Question> GetWritingQuestions(XDocument doc) { List<Question> questions = new List<Question>(); DocumentMaker maker = new DocumentMaker("Resources/template.html", Skill.Writing); foreach (XElement questionElement in doc.Element("questions").Elements("writing")) foreach (XElement question in questionElement.Elements("qw")) { XElement q = question.Element("q"); XElement @as = question.Element("as"); XAttribute right = q.Attribute("right"); XAttribute type = q.Attribute("type"); List<string> variants = new List<string>(); foreach (XElement variant in @as.Elements("a")) variants.Add(variant.Value); if (type.Value == "choose") questions.Add(new Question(Skill.Writing, maker.GetHTMLFromTextQuestion(q.Value), int.Parse(right.Value), variants.ToArray())); if (type.Value == "answer") questions.Add(new Question(Skill.Writing, maker.GetHTMLFromTextQuestion(q.Value), variants.ToArray())); } CountWriting = questions.Count; return questions; } private void Increase(Skill skill) { switch (skill) { case Skill.Grammar: RightGrammar++; break; case Skill.Listening: RightListening++; break; //case Skill.Reading: // RightReading++; // break; case Skill.Speaking: RightSpeaking++; break; case Skill.Writing: RightWriting++; break; } } public void CheckAnswer(int variant) { if (variant == ActiveQuestion.IndexRight) Increase(ActiveQuestion.Skill); } public void CheckAnswer(string userAnswer) { userAnswer = userAnswer.ToLower().Trim(); foreach (string possibleAnswer in ActiveQuestion.AllowableAnswers) if (userAnswer.Contains(possibleAnswer.ToLower().Trim())) Increase(ActiveQuestion.Skill); } public Question GetNextQuestion() { if (IndexNextQuestion >= Questions.Length) { //throw new Exception("Questions have been finished"); } int indexThisQuestion = IndexNextQuestion; IndexNextQuestion++; ActiveQuestion = Questions[indexThisQuestion]; return ActiveQuestion; } } }<file_sep>/Исходники/EnglishLab_WindowsApplication/FirstStart/Views/StartDialog.cs using System; using System.Windows.Forms; using MetroFramework.Forms; using UserData; namespace FirstStart { public partial class StartDialog : MetroForm { public string UserName { get; private set; } public Level UserLevel { get; private set; } public StartDialog() { InitializeComponent(); levelInfo.SelectedIndex = 0; } private void userName_Enter(object sender, EventArgs e) => userName.Text = ""; private void nextButton_Click(object sender, EventArgs e) { UserName = userName.Text; UserLevel = (Level)levelInfo.SelectedIndex; DialogResult = DialogResult.OK; this.Close(); } private void StartDialog_FormClosed(object sender, FormClosedEventArgs e) => DialogResult = DialogResult.Abort; } } <file_sep>/Исходники/EnglishLab_WindowsApplication/FirstStart/Enums/SkillEnum.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FirstStart { public enum Skill { Grammar, Listening, Speaking, Reading, Writing } } <file_sep>/Исходники/EnglishLab_WindowsApplication/FirstStart/Views/FinishDialog.cs using System; using MetroFramework.Forms; using FirstStart.Models; using System.Diagnostics; namespace FirstStart.Views { public partial class FinishDialog : MetroForm { public FinishDialog(QuestionManager manager) { InitializeComponent(); string message = "В среднем вами было верно выполнено {0}% заданий, что соответствует уровню {1}.\n"+ "Нажмите кнопку \"Продолжить\", чтобы перейти к главному окну приложения.\nВпереди много интересного!"; string totalLevel = manager.TotalLevel.ToString(); level.Text = String.Format("Ваш уровень - {0}", totalLevel); levelInfo.Text = String.Format(message, manager.AveragePrecent, totalLevel); chart.Series[0].Points.AddXY("Аудирование", manager.RightListeningPrecent); chart.Series[0].Points.AddXY("Грамматика", manager.RightGrammarPrecent); chart.Series[0].Points.AddXY("Речь", manager.RightSpeakingPrecent); chart.Series[0].Points.AddXY("Письмо", manager.RightWritingPrecent); } private void nextButton_Click(object sender, EventArgs e) { Close(); } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/UserData/User.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; using WordSetManager; namespace UserData { [Serializable] public class User { private string Name; public Level UserLevel { get; private set; } public List<WordSet> LearntSets { get; private set; } public List<WordSet> SetsOnLearning { get; private set; } public WordSet UserDictornary { get; private set; } private int CountLearntWordsFromRemovedSets; public int CountLearntWords { get { int sum = UserDictornary.CountLearntWords + CountLearntWordsFromRemovedSets; foreach (WordSet set in LearntSets) sum += set.CountLearntWords; foreach (WordSet set in SetsOnLearning) sum += set.CountLearntWords; return sum; } } public int CountSetsOnLearning { get { return SetsOnLearning.Count - 1; } } protected string Path = "UserInfo.dat"; public User(string name, Level level) { Name = name; UserLevel = level; LearntSets = new List<WordSet>(); SetsOnLearning = new List<WordSet>(); UserDictornary = new WordSet("Мой словарь"); SetsOnLearning.Add(UserDictornary); } public void Save(string path) { try { if (File.Exists(path)) { File.Delete(path); } FileStream fstream = File.Open(path, FileMode.Create); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(fstream, this); fstream.Close(); } catch (Exception) { throw new Exception("It's not possible to create file"); } } public void Save() => Save(this.Path); public void AddSetToLearn(object set) { (set as WordSet).Load(); SetsOnLearning.Add(set as WordSet); } public void AddLearntSet(WordSet set) => LearntSets.Add(set); public void AddWordInUserDictiornary(string text, string translation, string description) => UserDictornary.AddWord(text, translation, description); public void RemoveSetFromLearning(object wordSet) { var set = wordSet as WordSet; //CountLearntWordsFromRemovedSets += set.CountLearntWords; SetsOnLearning.Remove(set); } public override string ToString() => Name; public static User GetUser(string path) { if (File.Exists(path)) { User user; FileStream fstream = File.Open(path, FileMode.Open); BinaryFormatter binaryFormatter = new BinaryFormatter(); user = (User)binaryFormatter.Deserialize(fstream); user.Path = path; fstream.Close(); return user; } else throw new Exception("Cannot open file"); } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/WordSetManager/Word.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WordSetManager { [Serializable] public class Word { private string Text; public string Translation { get; private set; } public string Description { get; private set; } private byte progress; public byte Progress { get => progress; set { if (value > 10) throw new Exception("Progress cannot be over 10"); progress = value; } } public bool IsLearnt { get => Progress == 10; } public Word(string text, string translation, string description) { Text = text; Translation = translation; Description = description; } public char[] GetSplittedWord() => Text.ToCharArray(); public override string ToString() => Text; } } <file_sep>/Исходники/EnglishLab_WindowsApplication/MainModule/Views/IWordBuilderView.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MainModule.Views { interface IWordBuilderView { string InjectableWord { get; set; } string Description { set; } List<string> PartsOfWord { set; } bool Correct { set; } event EventHandler WordEntered; } } <file_sep>/Исходники/EnglishLab_WindowsApplication/Setup/InstallerForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MetroFramework.Forms; namespace Setup { public partial class InstallerForm : MetroForm { public InstallerForm() { InitializeComponent(); panel.Controls.Add(new Welcome(panel, this)); } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/MainModule/Views/Dashboard.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MainModule.Presenters; using MetroFramework.Forms; namespace MainModule.Views { public partial class Dashboard : MetroForm { private static Dashboard DashboardForm; public static Dashboard Instance { get { if (DashboardForm == null) DashboardForm = new Dashboard(); return DashboardForm; } } public static readonly string HeaderText = "EnglishLab"; private bool CloseFromTray; private MainViewPresenter MainViewPresenter; private Dashboard() { InitializeComponent(); CloseFromTray = false; } private void Dashboard_Shown(object sender, EventArgs e) { MainView view = MainView.Instance; MainViewPresenter = new MainViewPresenter(view); viewPanel.Controls.Add(view); } private void Dashboard_FormClosing(object sender, FormClosingEventArgs e) { bool shutDown = e.CloseReason == CloseReason.WindowsShutDown, taskKill = e.CloseReason == CloseReason.TaskManagerClosing; if (shutDown || taskKill) return; if (!CloseFromTray) { e.Cancel = true; WindowState = FormWindowState.Minimized; ShowInTaskbar = false; } } private void открытьToolStripMenuItem_Click(object sender, EventArgs e) { ShowInTaskbar = true; WindowState = FormWindowState.Normal; } private void выходToolStripMenuItem_Click(object sender, EventArgs e) { CloseFromTray = true; Close(); } } }<file_sep>/Исходники/EnglishLab_WindowsApplication/MainModule/Views/WordCardsView.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Speech.Synthesis; namespace MainModule.Views { public partial class WordCardsView : UserControl, IWordCardsView { public event EventHandler NextClick; public event EventHandler PreviousClick; public event EventHandler UserKnowsClick; public event EventHandler PlayClick; public string Word { set => wordBox.Text = value; } public string Description { set => descriptionBox.Text = value; } public string Translation { set => translationBox.Text = value; } public WordCardsView() { InitializeComponent(); Dock = DockStyle.Fill; } private void toMainView_Click(object sender, EventArgs e) { Panel containerPanel = Dashboard.Instance.viewPanel; containerPanel.Controls.Remove(this); containerPanel.Controls.Add(MainView.Instance); Dashboard.Instance.Text = Dashboard.HeaderText; Dashboard.Instance.Refresh(); } private void play_Click(object sender, EventArgs e) { if (PlayClick != null) PlayClick(this, EventArgs.Empty); SpeechSynthesizer speaker = new SpeechSynthesizer(); speaker.SelectVoice("Microsoft Zira Desktop"); //foreach (InstalledVoice voice in speaker.GetInstalledVoices()) //{ // VoiceInfo info = voice.VoiceInfo; // MessageBox.Show(" Voice Name: " + info.Name); //} speaker.SpeakAsync(wordBox.Text); } private void print_Click(object sender, EventArgs e) { } private void next_Click(object sender, EventArgs e) { if (NextClick != null) NextClick(this, EventArgs.Empty); } private void userKnows_Click(object sender, EventArgs e) { if (UserKnowsClick != null) UserKnowsClick(this, EventArgs.Empty); } private void previous_Click(object sender, EventArgs e) { if (PreviousClick != null) PreviousClick(this, EventArgs.Empty); } private void WordCardsView_Load(object sender, EventArgs e) { if (NextClick != null) NextClick(this, EventArgs.Empty); } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/FirstStart/VariantPanel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MetroFramework.Controls; namespace FirstStart { public partial class VariantPanel : UserControl { public WebBrowser Browser { get { return browser; } } public Button[] VariantsArray { get { return new Button[] { variant1, variant2, variant3, variant4 }; } } public VariantPanel() { InitializeComponent(); Visible = false; variant1.MouseEnter += Variant_MouseEnter; variant2.MouseEnter += Variant_MouseEnter; variant3.MouseEnter += Variant_MouseEnter; variant4.MouseEnter += Variant_MouseEnter; variant1.MouseLeave += Variant_MouseLeave; variant2.MouseLeave += Variant_MouseLeave; variant3.MouseLeave += Variant_MouseLeave; variant4.MouseLeave += Variant_MouseLeave; } private void Variant_MouseEnter(object sender, EventArgs e) => ((Button)sender).ForeColor = Color.White; private void Variant_MouseLeave(object sender, EventArgs e) => ((Button)sender).ForeColor = Color.Black; } } <file_sep>/Исходники/EnglishLab_WindowsApplication/FirstStart/Models/DocumentMaker.cs using System; using System.IO; namespace FirstStart.Models { class DocumentMaker { private string HTMLTemplate; private Skill SkillType; public DocumentMaker(string pathHtmlTemplate, Skill skillType) { HTMLTemplate = File.ReadAllText(pathHtmlTemplate); SkillType = skillType; } public string GetHTMLFromTextQuestion(string textQuestion) { switch (SkillType) { case Skill.Grammar: case Skill.Writing: return GetHTMLForPicContent(textQuestion); case Skill.Listening: case Skill.Speaking: return GetHTMLForVideoContent(textQuestion); } return null; } private string GetHTMLForPicContent(string textQuestion) { string picPath = ""; for (int i = 0; i < textQuestion.Length; i++) if (textQuestion[i] == '@') { picPath = textQuestion.Substring(i + 1); textQuestion = textQuestion.Substring(0, i); break; } if (picPath == "") picPath = "absence.png"; string document = HTMLTemplate.Replace("PICTURE_PATH", (Environment.CurrentDirectory + "/Resources/" + picPath).Replace('\\', '/')); return document.Replace("QUESTION_TEXT", textQuestion); } private string GetHTMLForVideoContent(string textQuestion) { string mediaPath = ""; for (int i = 0; i < textQuestion.Length; i++) if (textQuestion[i] == '@') { mediaPath = textQuestion.Substring(i + 1); textQuestion = textQuestion.Substring(0, i); break; } string document = HTMLTemplate.Replace("VIDEO_PATH", (Environment.CurrentDirectory + "/Resources/" + mediaPath).Replace('\\', '/')); return document.Replace("QUESTION_TEXT", textQuestion); } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/Setup/Welcome.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace Setup { public partial class Welcome : UserControl { public Panel ContainerPanel; private Form ParentShellForm; public Welcome(Panel panel, Form form) { InitializeComponent(); ParentShellForm = form; ContainerPanel = panel; info.Text = "0.1 Beta"; } private void openDialog_Click(object sender, EventArgs e) { if (folderBrowserDialog.ShowDialog() == DialogResult.OK) { path.Text = folderBrowserDialog.SelectedPath; } } private void next_Click(object sender, EventArgs e) { if (Directory.Exists(path.Text)) { ContainerPanel.Controls.Remove(this); ContainerPanel.Controls.Add(new ProcessSetup(path.Text, ParentShellForm)); } else MessageBox.Show("Выберите расположение или создайте папку нажав на значок справа от поля ввода", "Выбранного расположения не существует", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/FirstStart/Views/ITestView.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FirstStart.Views { interface ITestView { Mode Mode { get; set; } int Progress { get; set; } int MaxCountQuestions { set; } string Status { set; } string Question { set; } string[] Variants { set; } int SelectedVariant { get; } string EnteredAnswer { get; } void SuccessFinish(); event EventHandler FinishClick; event EventHandler SkipClick; event EventHandler VariantChosen; event EventHandler AnswerEntered; } } <file_sep>/Исходники/EnglishLab_WindowsApplication/MainModule/Presenters/WordCardsPresenter.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MainModule.Views; using WordSetManager; namespace MainModule.Presenters { class WordCardsPresenter { private IWordCardsView CardsView; private WordSet WordSet; private Word CurrentWord; public WordCardsPresenter(IWordCardsView cardsView, object wordSet) { CardsView = cardsView; WordSet = wordSet as WordSet; CardsView.NextClick += CardsView_NextClick; CardsView.PreviousClick += CardsView_PreviousClick; } private void CardsView_PreviousClick(object sender, EventArgs e) { CurrentWord = WordSet.GetPreviousWord(); CardsView.Word = CurrentWord.ToString(); CardsView.Translation = CurrentWord.Translation; CardsView.Description = CurrentWord.Description; } private void CardsView_NextClick(object sender, EventArgs e) { CurrentWord = WordSet.GetNextWord(); CardsView.Word = CurrentWord.ToString(); CardsView.Translation = CurrentWord.Translation; CardsView.Description = CurrentWord.Description; } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/FirstStart/Models/Question.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FirstStart.Models { public class Question { public string TextQuestion { get; private set; } public Mode Mode { get; private set; } public int IndexRight { get; private set; } public Skill Skill { get; private set; } public string[] Variants { get; private set; } public string[] AllowableAnswers { get; private set; } public Question(Skill skill, string textQuestion, int indexRight, string[] variants) { Skill = skill; TextQuestion = textQuestion; IndexRight = indexRight; Variants = variants; Mode = Mode.Choose; } public Question(Skill skill, string textQuestion, string[] allowableAnswers) { Skill = skill; TextQuestion = textQuestion; AllowableAnswers = allowableAnswers; Mode = Mode.Answer; } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/UserData/LevelEnum.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UserData { public enum Level { StartTest, Beginner, Elementary, Intermediate, Advanced } } <file_sep>/Исходники/EnglishLab_WindowsApplication/MainModule/Views/IWordCardsView.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MainModule.Views { interface IWordCardsView { string Word { set; } string Description { set; } string Translation { set; } event EventHandler NextClick; event EventHandler PreviousClick; event EventHandler UserKnowsClick; event EventHandler PlayClick; } } <file_sep>/Исходники/EnglishLab_WindowsApplication/FirstStart/Enums/ModeEnum.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FirstStart { public enum Mode { Choose, Answer } } <file_sep>/Исходники/EnglishLab_WindowsApplication/Setup/ProcessSetup.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.IO; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Setup { public partial class ProcessSetup : UserControl { protected BackgroundWorker bw = new BackgroundWorker(); protected string rootPath; protected string fsPath; protected string rsFsPath; protected string rsMainPath; protected string picsWordSet; protected DirectoryInfo FilesDirectory; protected DirectoryInfo FirstStartDirectory; protected DirectoryInfo FirstStartResourcesDirectory; protected DirectoryInfo MainResourcesDirectory; protected DirectoryInfo MainPicturesDirectory; protected Form ParentShellForm; protected bool isError; public ProcessSetup(string path, Form form) { InitializeComponent(); ParentShellForm = form; rootPath = path; fsPath = Path.Combine("files", "FirstStart"); rsFsPath = Path.Combine("files", "Resources"); rsMainPath = Path.Combine("files", "WordSets"); picsWordSet = Path.Combine(rsMainPath, "Pictures"); FilesDirectory = new DirectoryInfo("files"); FirstStartDirectory = new DirectoryInfo(fsPath); FirstStartResourcesDirectory = new DirectoryInfo(rsFsPath); MainResourcesDirectory = new DirectoryInfo(rsMainPath); MainPicturesDirectory = new DirectoryInfo(picsWordSet); progress.Maximum = FilesDirectory.GetFiles().Length + FirstStartDirectory.GetFiles().Length + FirstStartResourcesDirectory.GetFiles().Length + MainResourcesDirectory.GetFiles().Length; bw.DoWork += Bw_DoWork; bw.RunWorkerCompleted += Bw_RunWorkerCompleted; bw.WorkerReportsProgress = true; bw.ProgressChanged += Bw_ProgressChanged; bw.RunWorkerAsync(); } private void Bw_ProgressChanged(object sender, ProgressChangedEventArgs e) { try { progress.Value = e.ProgressPercentage; } catch (Exception) { progress.Maximum++; progress.Value = e.ProgressPercentage; } logger.Text += e.UserState + Environment.NewLine; } private void Bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (isError) { ParentShellForm.Close(); return; } logger.Text += "Копирование файлов завершено" + Environment.NewLine; var appPath = Path.Combine(rootPath, "EnglishLab", "EnglishLab.exe"); ShortcutManager.CreateShortcut("EnglishLab", appPath, appPath, ShortcutLocation.DESKTOP, String.Empty); ShortcutManager.CreateShortcut("EnglishLab", appPath, appPath, ShortcutLocation.START_MENU, String.Empty); logger.Text += "Создан ярлык на рабочем столе и в меню \"Пуск\"" + Environment.NewLine; logger.Text += "Нажмите \"Готово\" для выхода из программы установки"; next.Enabled = true; } private void Bw_DoWork(object sender, DoWorkEventArgs e) { int progress = 0; var destinationDir = Path.Combine(rootPath, "EnglishLab"); try { Directory.CreateDirectory(destinationDir); } catch (Exception) { MessageBox.Show("Запустите установку от имени администратора, если вы хотите установить приложение на диск C или измените путь", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); isError = true; return; } var files = FilesDirectory.GetFiles(); foreach (var file in files) { file.CopyTo(Path.Combine(destinationDir, file.Name)); bw.ReportProgress(++progress, "Копирование файла " + file.Name); } files = FirstStartResourcesDirectory.GetFiles(); Directory.CreateDirectory(Path.Combine(destinationDir, "Resources")); foreach (var file in files) { file.CopyTo(Path.Combine(destinationDir, "Resources", file.Name)); bw.ReportProgress(++progress, "Копирование файла " + file.Name); } files = MainResourcesDirectory.GetFiles(); Directory.CreateDirectory(Path.Combine(destinationDir, "WordSets")); foreach (var file in files) { file.CopyTo(Path.Combine(destinationDir, "WordSets", file.Name)); bw.ReportProgress(++progress, "Копирование файла " + file.Name); } files = MainPicturesDirectory.GetFiles(); Directory.CreateDirectory(Path.Combine(destinationDir, "WordSets", "Pictures")); foreach (var file in files) { file.CopyTo(Path.Combine(destinationDir, "WordSets", "Pictures", file.Name)); bw.ReportProgress(++progress, "Копирование файла " + file.Name); } files = FirstStartDirectory.GetFiles(); Directory.CreateDirectory(Path.Combine(destinationDir, "FirstStart")); foreach (var file in files) { file.CopyTo(Path.Combine(destinationDir, "FirstStart", file.Name)); bw.ReportProgress(++progress, "Копирование файла " + file.Name); } } private void logger_TextChanged(object sender, EventArgs e) { logger.SelectionStart = logger.Text.Length; logger.ScrollToCaret(); } private void next_Click(object sender, EventArgs e) { ParentShellForm.Close(); } } } <file_sep>/Исходники/EnglishLab_WindowsApplication/FirstStart/WritePanel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MetroFramework.Controls; namespace FirstStart { public partial class WritePanel : UserControl { public WebBrowser Browser { get { return browser; } } public string Answer { get { return answer.Text; } } public MetroButton NextButton { get { return next; } } public WritePanel() { InitializeComponent(); Visible = false; } private void WritePanel_VisibleChanged(object sender, EventArgs e) => answer.Text = ""; private void browser_Navigated(object sender, WebBrowserNavigatedEventArgs e) => answer.Text = ""; } } <file_sep>/Исходники/EnglishLab_WindowsApplication/MainModule/DocViewer.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MainModule.Views; using System.IO; namespace MainModule { public partial class DocViewer : UserControl { public DocViewer(string path) { InitializeComponent(); Dock = DockStyle.Fill; richTextBox1.LoadFile(path); } private void toMainView_Click(object sender, EventArgs e) { Panel containerPanel = Dashboard.Instance.viewPanel; containerPanel.Controls.Remove(this); containerPanel.Controls.Add(MainView.Instance); Dashboard.Instance.Text = Dashboard.HeaderText; Dashboard.Instance.Refresh(); } bool enabled; private void button1_Click(object sender, EventArgs e) { if (enabled) { richTextBox1.ForeColor = Color.Black; richTextBox1.BackColor = Color.White; enabled = false; } else { richTextBox1.ForeColor = Color.White; richTextBox1.BackColor = Color.Black; enabled = true; } } string[] dict = File.ReadAllLines("MainDict.txt"); private void richTextBox1_DoubleClick(object sender, EventArgs e) { char[] trimers = new char[] { ' ', '.', ',', '!', '?' }; string wordToTranslate = richTextBox1.SelectedText.Trim(trimers), translation = ""; toolTip1.IsBalloon = true; toolTip1.UseAnimation = true; toolTip1.UseFading = true; int count = 0; for (int i = 0; i < dict.Length; i++) { if (dict[i].Contains(wordToTranslate)) { translation += dict[i] + '\n'; count++; } if (count == 3) break; } toolTip1.ToolTipTitle = richTextBox1.SelectedText; toolTip1.SetToolTip(richTextBox1, translation); } } }
c265f589549505a61f6425a880afe6addde03c8c
[ "C#" ]
33
C#
GEugene98/EnglishLab
243e189938eda57eb721d87f9165756744350985
7b89d856767d2d8fa984d1bf38d0e2845d3fba3f
refs/heads/master
<file_sep>from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import traceback import simplejson import json import logging from . import ppsdb logger = logging.getLogger("django") @csrf_exempt def api(request): try: logger.info(simplejson.loads(request.body)) postJson=simplejson.loads(request.body) if postJson['task']=='warntask': return HttpResponse(json.dumps(_puttask(**{'postJson':postJson})),content_type='application/json') else: return HttpResponse(json.dumps({"msg":"unKnow"}),content_type='application/json') except Exception as info: logger.error(traceback.format_exc()) return HttpResponse(json.dumps({"msg":"error","content":str(traceback.format_exc())}),content_type='application/json') def _puttask(**kwages): task=kwages['postJson']['data'] dbcon=ppsdb.opMysqlObj(**{'dbname':'default','valueType':'dict'}) if dbcon.isExistsWarn(**task): dbcon.createWarn(**task) task['wid']=str(dbcon.getLaseID()) for i in dbcon.getUserid(**task): task['userid']=i['userid'] dbcon.createWarnMsg(**task) dbcon.create_warntask_w2m(**{'wid':task['wid'],'mid':str(dbcon.getLaseID())}) #dbcon.setWarnTaskMessId(**{'lastid':str(dbcon.getLaseID()),'id':task['wid']}) else: dbcon.setWarnRecoveryTime(**task) dbcon.commit() dbcon.close()<file_sep>#!/bin/bash DIR=/home/deployuser/logs LOGDIR="${DIR}" sourcelogpath="${DIR}/access.log" touchfile="${DIR}/touchforlogrotate" DATE=`date -d yesterday +%Y%m%d` destlogpath="${LOGDIR}/access.${DATE}.log" mv $sourcelogpath $destlogpath touch $touchfile <file_sep>if [ ! -n "$1" ] then echo "Usages: sh uwsgiserver.sh [start|stop|restart]" exit 0 fi if [ $1 = start ] then psid=`ps aux | grep "uwsgi" | grep -v "grep" | wc -l` echo $psid if [ $psid -gt 2 ] then echo "uwsgi is running!" exit 0 else uwsgi django.ini echo "Start uwsgi service [OK]" fi elif [ $1 = stop ];then killall -9 uwsgi echo "Stop uwsgi service [OK]" elif [ $1 = restart ];then killall -9 uwsgi uwsgi --ini django.ini echo "Restart uwsgi service [OK]" else echo "Usages: sh uwsgiserver.sh [start|stop|restart]" fi <file_sep>from django.db import models # Create your models here. class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' def __str__(self): return("/".join([self.username,self.first_name])) class PpsWarntype(models.Model): warntype = models.CharField(max_length=30, blank=True, null=True,verbose_name='预警类别') warnname = models.CharField(max_length=30, blank=True, null=True,verbose_name='预警名字') userid=models.ManyToManyField(AuthUser,verbose_name='预警处理人',blank=True,null=True) #userid = models.ForeignKey(AuthUser, models.DO_NOTHING, related_name='uid',db_column='userid', blank=True, null=True,verbose_name='预警处理人') auduserid = models.ForeignKey(AuthUser, models.DO_NOTHING, db_column='auduserid', blank=True, null=True,verbose_name='预警审核人') class Meta: managed = False db_table = 'pps_warntype' verbose_name_plural='报警负责人设置' verbose_name='报警负责人设置' def __str__(self): return("/".join([self.warntype,self.warnname,str(self.auduserid)])) class AuthGroup(models.Model): name = models.CharField(unique=True, max_length=80) class Meta: managed = False db_table = 'auth_group' def __str__(self): return(self.name) ''' class PpsAuditGroup(models.Model): gid = models.ForeignKey(AuthGroup, models.DO_NOTHING, related_name='gid',db_column='gid', blank=True, null=True,verbose_name='被审核组') uid = models.ForeignKey(AuthUser, models.DO_NOTHING, db_column='uid', blank=True, null=True,verbose_name='审核人') class Meta: managed = False db_table = 'pps_audit_group' verbose_name_plural='审核组设置' verbose_name='审核组设置' def __str__(self): return("/".join([str(self.gid),str(self.uid)])) ''' class PpsWarnlevel(models.Model): level = models.IntegerField(blank=True, null=True,verbose_name='预警等级ID') levelname = models.CharField(max_length=30, blank=True, null=True,verbose_name='预警等级名字') class Meta: managed = False db_table = 'pps_warnlevel' verbose_name_plural='预警等级设置' verbose_name='预警等级设置' def __str__(self): return("/".join([str(self.level),str(self.levelname)])) class PpsEnvitype(models.Model): envitype = models.CharField(max_length=50, blank=True, null=True,verbose_name='环境类型') enviname = models.CharField(max_length=50, blank=True, null=True,verbose_name='环境名字') class Meta: managed = False db_table = 'pps_envitype' verbose_name_plural='环境设置' verbose_name='环境设置' def __str__(self): return("/".join([str(self.envitype),str(self.enviname)])) <file_sep>from django.conf.urls import url from django.conf.urls import include, url from django.contrib.auth import views as views1 from . import views from . import api urlpatterns = [ url('undo/', views.undo, name='undo'), url('getdata/',views.getdata,name='getdata'), url('putdata/',views.putdata,name='putdata'), url('test/',views.test,name='test'), url('dowarn/', views.dowarn, name='dowarn'), url('review/', views.review, name='review'), url('querywarn/', views.querywarn, name='querywarn'), url('querywarninfo/', views.querywarninfo, name='querywarninfo'), url('tjwarn/', views.tjwarn, name='tjwarn'), url('api/', api.api, name='api'), ] <file_sep>from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate from django.contrib.auth import login from django.contrib import auth from aom import custom from . import ppsdb import traceback import simplejson import json import time import sys import logging logger = logging.getLogger("django") #logger = logging.getLogger(__name__) # Create your views here. #页面访问权限验证妆饰器 def _auth_page(view): #自动登录方法 def aauth(request, *args, **kwargs): #登录动作 user = authenticate(username=request.GET.get('empNo',''), password='<PASSWORD>'+request.GET.get('empNo','')) if user is not None: login(request, user) return view(request, *args, **kwargs) #主方法 def main(request, *args, **kwargs) : #判断是否登录了 if request.user.is_authenticated: #如果登录了直接访问对应方法 return view(request, *args, **kwargs) else: #如果没有登录运行aauth return aauth(request, *args, **kwargs) return main #首页 @_auth_page def index(request): return HttpResponse('''<meta http-equiv="refresh" content="0;url=/pps/undo/">''') #待处理消息 #@_auth_page @login_required(login_url="/admin/login/") def undo(request): return render(request, 'undo.html',{}) #处理预警消息 @login_required(login_url="/admin/login/") def dowarn(request): return render(request, 'dowarn.html',{}) #查看预警列表信息 @login_required(login_url="/admin/login/") def querywarn(request): return render(request, 'querywarn.html',{}) #查看预警信息 @login_required(login_url="/admin/login/") def querywarninfo(request): return render(request, 'querywarninfo.html',{}) #审核 @login_required(login_url="/admin/login/") def review(request): return render(request, 'review.html',{}) #统计 @login_required(login_url="/admin/login/") def tjwarn(request): return render(request, 'tjwarn.html',{}) #ajax获取入口 @csrf_exempt @login_required(login_url="/admin/login/") def getdata(request): return HttpResponse(json.dumps({"name":"liuyanli"}), content_type='application/json') #ajax提交入口 @csrf_exempt @login_required(login_url="/admin/login/") def putdata(request): try: if request.POST.get('task')=='test': return HttpResponse(json.dumps({"name":"liuyanli"}), content_type='application/json') #获取待处理消息 elif request.POST.get('task')=='getundo': return HttpResponse(json.dumps(_getUndoJson(request)), content_type='application/json') #获取预警信息 elif request.POST.get('task')=='getwarn': return HttpResponse(json.dumps(_getWarnJson(request)), content_type='application/json') #获取审计信息 elif request.POST.get('task')=='getaut': return HttpResponse(json.dumps(_getWarnJson(request)), content_type='application/json') #提交预警信息处理 elif request.POST.get('task')=='putwarn': return HttpResponse(json.dumps(_putWarnJson(request)), content_type='application/json') #提交审核信息 elif request.POST.get('task')=='putaud': return HttpResponse(json.dumps(_putAudJson(request)), content_type='application/json') #提交请求获取预警信息查询 elif request.POST.get('task')=='putquerywarn': return HttpResponse(json.dumps(_getQueryWarn(request)), content_type='application/json') #获取预警信息查询详细内容 elif request.POST.get('task')=='getquerywarninfo': return HttpResponse(json.dumps(_getWarnJson(request)), content_type='application/json') #获取统计信息 elif request.POST.get('task')=='gettjwarn': return HttpResponse(json.dumps(_getTjwarn(request)), content_type='application/json') else: return HttpResponse(json.dumps({"name":"liuyanli"}), content_type='application/json') except Exception as info: logger.error(traceback.format_exc()) @csrf_exempt def test(request): print(a) try: print(simplejson.loads(request.body)) #print(a) return_json={'a':'b'} return HttpResponse(json.dumps({"name":"liuyanli"}),content_type='application/json') except Exception as info: print(traceback.format_exc()) return HttpResponse(json.dumps({"msg":"error","content":str(traceback.format_exc())}),content_type='application/json') #return render(request, 'test.html',{'id':'hell'}) #获取统计信息 def _getTjwarn(request): dbcon=ppsdb.opMysqlObj(**{'dbname':'default','valueType':'dict'}) return_json=dbcon.getStatistics(**{'begindate':request.POST.get('begindate'),'enddate':request.POST.get('enddate')}) return(return_json) #获取警告记录 def _getQueryWarn(request): temp=[] for i in range(123): temp.append({'warndesc':'预警'+str(i),'createtime':time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()+(86448*i))),'status':'完成','url':'/pps/querywarninfo/?id='+str(i)}) dbcon=ppsdb.opMysqlObj(**{'dbname':'default','valueType':'dict'}) temp=dbcon.getQueryWarn(**{'id':request.POST.get('id')}) p=custom._my_pagination(request,temp,request.POST.get('display_num',5)) return_json={'list':p['list'],'total_num':len(temp),'num_pages':p['num_pages']} return(return_json) #获取审批页面信息 def _putAudJson(request): try: dbcon=ppsdb.opMysqlObj(**{'dbname':'default','valueType':'dict'}) #排它锁查看是否有该条信息 warnTaskCount=dbcon.getWarnTaskForUpdate(**{'id':request.POST.get('id',0),'status':2}) #如果有该条信息 if len(warnTaskCount)!=0: #将消息状态变更为已处理 #dbcon.setMessStatus(**{'fromstatus':1,'tostatus':2,'messid':request.POST.get('messid')}) for i in dbcon.getMessageId(**{'wid':request.POST.get('id')}) : dbcon.setMessStatus(**{'fromstatus':1,'tostatus':2,'messid':i['mid']}) #创建一条审核意见 dbcon.createWarnTaskAudMess(**{'warntaskMsg':request.POST.get('warntaskMsg'),'id':request.POST.get('id',0),'status':request.POST.get('status'),'userid':request.user.id}) #如果同意 if request.POST.get('status')=='1': #将预警信息标注为以处理完毕 dbcon.setWarnTaskStatus(**{'fromstatus':2,'tostatus':3,'id':request.POST.get('id',0)}) else: #不同意将预警信息状态从待审核变更为待处理 dbcon.setWarnTaskStatus(**{'fromstatus':2,'tostatus':1,'id':request.POST.get('id',0)}) #给处理人重新发消息 dbcon.createMess(**{'activityname':'重新处理','path':'/pps/dowarn/?id='+request.POST.get('id'),'userid':dbcon.getWarnTaskUserid(**{'id':request.POST.get('id',0)})}) #更新预警信息对应的消息id #dbcon.setWarnTaskMessId(**{'lastid':dbcon.getLaseID(),'id':request.POST.get('id',0)}) dbcon.create_warntask_w2m(**{'wid':request.POST.get('id'),'mid':str(dbcon.getLaseID())}) dbcon.commit() #获取预警信息对应的审核意见 warntaskMsg=dbcon.getWarnTaskAudMessS(**{'id':request.POST.get('id',0)}) dbcon.close() return_json={'status':'true','warntaskMsg':warntaskMsg} else: dbcon.commit() dbcon.close() return_json={'status':'false','warntaskMsg':[]} except Exception as info: print(traceback.format_exc()) return_json={'status':'false','warntaskMsg':[]} return(return_json) #提交处理预警信息表单信息 def _putWarnJson(request): try: dbcon=ppsdb.opMysqlObj(**{'dbname':'default','valueType':'dict'}) #排它锁查看是否有该条信息 warnTaskCount=dbcon.getWarnTaskForUpdate(**{'id':request.POST.get('id'),'status':1}) #如果有该条信息 if len(warnTaskCount)!=0: #如果预警级别小于3级 for i in dbcon.getMessageId(**{'wid':request.POST.get('id')}) : dbcon.setMessStatus(**{'fromstatus':1,'tostatus':2,'messid':i['mid']}) if warnTaskCount[0]['warnlevel']<3: #预警信息变为待审核 dbcon.setWarnTaskInfo(**{'reason':request.POST.get('reason'),'measure':request.POST.get('measure'),'id':request.POST.get('id'),'status':2,'userid':request.user.id}) #发出待审核消息 dbcon.createMess(**{'activityname':'待审核','path':'/pps/review/?id='+request.POST.get('id'),'userid':warnTaskCount[0]['auduserid']}) #将将待审核消息id写入预警信息中。 dbcon.create_warntask_w2m(**{'wid':request.POST.get('id'),'mid':str(dbcon.getLaseID())}) else: #否则直接将预警信息变更问以处理完毕。 dbcon.setWarnTaskInfo(**{'reason':request.POST.get('reason'),'measure':request.POST.get('measure'),'id':request.POST.get('id'),'status':3,'userid':request.user.id}) #将消息状态设置为已读。 dbcon.commit() dbcon.close() return_json={'status':'true'} except Exception as info: logger.error(traceback.format_exc()) return_json={'status':'false'} return(return_json) #获取处理预警信息表单信息 def _getWarnJson(request): dbcon=ppsdb.opMysqlObj(**{'dbname':'default','valueType':'dict'}) #如果是处理警告信息页面 或者是查询预警信息详细页面 if request.POST.get('task')=='getwarn' : return_json=dbcon.getWarnTask(**{'id':request.POST.get('id'),'userid':request.user.id}) return_json['warntaskMsg']=dbcon.getWarnTaskAudMess(**{'id':request.POST.get('id')}) #如果是审核信息页面 elif request.POST.get('task')=='getquerywarninfo': userid=dbcon.getWarnTaskUserid(**{'id':request.POST.get('id')}) return_json=dbcon.getWarnTask(**{'id':request.POST.get('id'),'userid':userid}) return_json['warntaskMsg']=dbcon.getWarnTaskAudMess(**{'id':request.POST.get('id')}) elif request.POST.get('task')=='getaut': userid=dbcon.getWarnTaskUserid(**{'id':request.POST.get('id')}) return_json=dbcon.getWarnTask(**{'id':request.POST.get('id'),'userid':userid}) return_json['warntaskMsg']=dbcon.getWarnTaskAudMessS(**{'id':request.POST.get('id')}) return(return_json) #获取未处理消息 def _getUndoJson(request): dbcon=ppsdb.opMysqlObj(**{'dbname':'default','valueType':'dict'}) #获取对应用户的未处理消息 undoList=dbcon.getUndoMess(**{'userid':request.user.id}) #分页处理 p=custom._my_pagination(request,undoList,request.POST.get('display_num',5)) return_json={'list':p['list'],'undo_num':len(undoList),'num_pages':p['num_pages']} return(return_json) <file_sep>from django.contrib import admin from .models import PpsWarntype #from .models import PpsAuditGroup from .models import PpsWarnlevel from .models import PpsEnvitype # Register your models here. admin.site.register(PpsWarntype) #admin.site.register(PpsAuditGroup) admin.site.register(PpsWarnlevel) admin.site.register(PpsEnvitype)<file_sep>from django.core.paginator import Paginator #分页 def _my_pagination(request, queryset, display_amount=10, after_range_num = 5,bevor_range_num = 4): #按参数分页 paginator = Paginator(queryset, display_amount) try: #得到request中的page参数 page =int(request.POST.get('page')) except: #默认为1 page = 1 #页码超出范围指向1 if page <1 or page > paginator.num_pages: page=1 try: #尝试获得分页列表 objects = paginator.page(page) #如果页数不存在 except EmptyPage: #获得最后一页 objects = paginator.page(paginator.num_pages) #如果不是一个整数 except: #获得第一页 objects = paginator.page(1) #根据参数配置导航显示范围 if page >=after_range_num and paginator.num_pages-page >= after_range_num: page_range = paginator.page_range[page-after_range_num:page+bevor_range_num] elif page >= after_range_num and page >paginator.num_pages-after_range_num: page_range = paginator.page_range[-(after_range_num+bevor_range_num):] else: page_range = paginator.page_range[0:bevor_range_num+bevor_range_num+1] return ({'list':list(objects),'num_pages':paginator.num_pages})<file_sep>import pymysql from django.conf import settings import logging logger = logging.getLogger("django") class opMysqlObj(object): def __init__(self,**kwages): self.databases=kwages['dbname'] if 'valueType' in kwages: self.valueType=kwages['valueType'] else: self.valueType='list' self._getdb() pass def _getdb(self): temp=settings.DATABASES[self.databases] temp2={} temp2['user'],temp2['password'],temp2['host'],temp2['database'],temp2['port']=temp['USER'],temp['PASSWORD'],temp['HOST'],temp['NAME'],int(temp['PORT']) temp2['charset']='utf8' if self.valueType=='dict': temp2['cursorclass']=pymysql.cursors.DictCursor #print(temp2) self.db=pymysql.connect(**temp2) #def usernameToUserid(self,**kwages): # sql="select id from auth_user where username='%s'"%(kwages['username']) # return(self.getData(**{'sql':sql})[0]['id']) def isExistsUser(self,**kwages): sql="select count(*) count from auth_user where username='%s'"%(kwages['username']) return(self.getData(**{'sql':sql})[0]['count']) def createMess(self,**kwages): sql="insert into pps_message (createtime,activityname,path,userid,status)values(now(),'%s','%s',%s,1)"%(kwages['activityname'],kwages['path'],kwages['userid']) logger.info(sql) self.putData(**{'sql':sql}) def getLaseID(self): return(self.getData(**{'sql':'SELECT LAST_INSERT_ID() lastid'})[0]['lastid']) def getData(self,**kwages): cur=self.db.cursor() cur.execute(kwages['sql']) return(cur.fetchall()) def commit(self): self.db.commit() def putData(self,**kwages): cur=self.db.cursor() cur.execute(kwages['sql']) def close(self): self.db.close() <file_sep>from django.db import models # Create your models here. class AddApp(models.Model): appid = models.AutoField(primary_key=True) appname = models.CharField(max_length=30, blank=True, null=True) appcname = models.CharField(max_length=30, blank=True, null=True) projectid = models.ForeignKey('AddProject', models.DO_NOTHING, db_column='projectid', blank=True, null=True) class Meta: managed = False db_table = 'add_app' verbose_name_plural='应用配置' verbose_name='应用配置' class AddAppserver(models.Model): appserverid = models.AutoField(primary_key=True) appservername = models.CharField(max_length=30, blank=True, null=True) appserverparams = models.TextField(blank=True, null=True) nodeid = models.ForeignKey('AddNode', models.DO_NOTHING, db_column='nodeid', blank=True, null=True) appid = models.ForeignKey(AddApp, models.DO_NOTHING, db_column='appid', blank=True, null=True) envid = models.ForeignKey('AddEnvironment', models.DO_NOTHING, db_column='envid', blank=True, null=True) class Meta: managed = False db_table = 'add_appserver' verbose_name_plural='应用服务器配置' verbose_name='应用服务器配置' class AddCustom(models.Model): customid = models.AutoField(primary_key=True) customname = models.CharField(max_length=30, blank=True, null=True) customcname = models.CharField(max_length=30, blank=True, null=True) class Meta: managed = False db_table = 'add_custom' verbose_name_plural='客户配置' verbose_name='客户配置' class AddEnvironment(models.Model): envid = models.AutoField(primary_key=True) envname = models.CharField(max_length=30, blank=True, null=True) envcname = models.CharField(max_length=30, blank=True, null=True) projectid = models.ForeignKey('AddProject', models.DO_NOTHING, db_column='projectid', blank=True, null=True) domain = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'add_environment' verbose_name_plural='环境配置' verbose_name='环境配置' class AddNode(models.Model): nodeid = models.AutoField(primary_key=True) nodekey = models.CharField(max_length=30, blank=True, null=True) ip = models.CharField(max_length=15, blank=True, null=True) class Meta: managed = False db_table = 'add_node' verbose_name_plural='节点配置' verbose_name='节点配置' class AddProject(models.Model): projectid = models.AutoField(primary_key=True) projectname = models.CharField(max_length=30, blank=True, null=True) projectcname = models.CharField(max_length=30, blank=True, null=True) customid = models.ForeignKey(AddCustom, models.DO_NOTHING, db_column='customid', blank=True, null=True) class Meta: managed = False db_table = 'add_project' verbose_name_plural='项目配置' verbose_name='项目配置'<file_sep>from django.contrib import admin from .models import AddCustom from .models import AddApp from .models import AddAppserver from .models import AddEnvironment from .models import AddNode from .models import AddProject # Register your models here. admin.site.register(AddCustom) admin.site.register(AddApp) admin.site.register(AddAppserver) admin.site.register(AddEnvironment) admin.site.register(AddNode) admin.site.register(AddProject)<file_sep>from aom import db import pymysql import time import logging logger = logging.getLogger("django") #继承db.opMysqlObj class opMysqlObj(db.opMysqlObj): def __init__(self,**kwages): db.opMysqlObj.__init__(self,**kwages) ''' 获取统计信息 方法kwage {'begindate':'2018-04-26','enddate':'2018-04-26'} ''' def getStatistics(self,**kwages): if kwages['begindate']!='': begindate=kwages['begindate'] else: begindate=time.strftime('%Y-%m-%d', time.localtime(time.time()-(86448*7))) if kwages['enddate']!='': enddate=kwages['enddate']+' 23:59:59' else: enddate=time.strftime('%Y-%m-%d', time.localtime(time.time()) ) sql1="SELECT b.warnname warntype,count FROM(SELECT warntype,COUNT(*) count FROM pps_warntask where createtime <='%s' and createtime >='%s' GROUP BY warntype ) a LEFT JOIN pps_warntype b ON a.warntype=b.warntype"%(enddate,begindate) sql2="SELECT b.enviname,a.count FROM (SELECT enviname,COUNT(*) count FROM pps_warntask where createtime <='%s' and createtime >='%s' GROUP BY enviname) a LEFT JOIN pps_envitype b ON a.enviname=b.envitype"%(enddate,begindate) sql3="select levelname warnlevel,count FROM (SELECT warnlevel,COUNT(*) count FROM pps_warntask where createtime <='%s' and createtime >='%s' GROUP BY warnlevel ) a LEFT JOIN pps_warnlevel b ON a.warnlevel=b.level" %(enddate,begindate) return_json={} return_json['warntype']=self.getData(**{'sql':sql1}) return_json['enviname']=self.getData(**{'sql':sql2}) return_json['warnlevel']=self.getData(**{'sql':sql3}) return(return_json) #获取历史预警信息 def getQueryWarn(self,**kwages): sql="SELECT CONCAT(substring(warndesc,1,30),'......') warndesc,date_format(createtime,'%Y-%m-%d %H:%i:%s') createtime,case when status=1 then '待处理' when status=2 then '待审核' when status=3 then '已完成' end status,CONCAT('/pps/querywarninfo/?id=',id) url FROM pps_warntask order by createtime desc LIMIT 0,1000" return(self.getData(**{'sql':sql})) ''' 排它获取是否存在该预警信息,引入**kwages status 填写预警信息对应状态 1待处理 2待审核 3处理完毕 ''' def getWarnTaskForUpdate(self,**kwages): sql="select a.id,warnid,a.warntype,enviname,warndesc,warnlevel,DATE_FORMAT(createtime, '%Y-%m-%d %H:%i:%s') createtime,DATE_FORMAT(recoverytime, '%Y-%m-%d %H:%i:%s') recoverytime,reason,measure,DATE_FORMAT(writetime, '%Y-%m-%d %H:%i:%s') writetime,status,messid,a.userid,b.auduserid FROM pps_warntask a LEFT JOIN pps_warntype b ON a.warntype=b.warntype where status="+str(kwages['status'])+" and a.id="+str(kwages['id'])+" for update" return(self.getData(**{'sql':sql})) ''' 设置消息状态,引入**kwages fromstatus 从什么状态 (1是未读,2是已读) tostatus 变更为什么状态 messid 消息id ''' def setMessStatus(self,**kwages): sql="update pps_message set status=%s,completetime=now() where status=%s and id=%s"%(kwages['tostatus'],kwages['fromstatus'],kwages['messid']) self.putData(**{'sql':sql}) ''' 新建预警信息审核消息,引入**kwages warntaskMsg 审核意见 id warntask的主键id userid 用户id status 1是同意 2是不同意 ''' def createWarnTaskAudMess(self,**kwages): sql="insert into pps_warntask_message(createtime,message,wid,uid,status) values(now(),'%s',%s,%s,%s) "%(pymysql.escape_string(kwages['warntaskMsg']),kwages['id'],kwages['userid'],kwages['status']) self.putData(**{'sql':sql}) ''' 设置预警信息状态,引入**kwages fromstatus 从什么状态 (1待处理 2待审核 3处理完毕) tostatus 变更为什么状态 id 预警信息主键id ''' def setWarnTaskStatus(self,**kwages): sql="update pps_warntask set status=%s where status=%s and id=%s"%(kwages['tostatus'],kwages['fromstatus'],kwages['id']) self.putData(**{'sql':sql}) ''' 对预警任务设置消息id,引入**kwages lastid 消息id id taskwarn的主键id def setWarnTaskMessId(self,**kwages): sql="update pps_warntask set messid=%s where id=%s"%(kwages['lastid'],kwages['id']) self.putData(**{'sql':sql}) 获取所有审核消息 ,引入**kwages id taskwarn的主键id ''' def getWarnTaskAudMessS(self,**kwages): sql="SELECT date_format(p.createtime, '%Y-%m-%d %H:%i:%s') createtime,p.message,a.first_name name,CASE WHEN p.status=1 THEN '不同意' ELSE '同意' END STATUS FROM pps_warntask_message p LEFT JOIN auth_user a ON p.uid=a.id where wid='"+kwages['id']+"'ORDER BY createtime desc" #print(sql) return(self.getData(**{'sql':sql})) ''' 获取审核消息最新的一条 ,引入**kwages id taskwarn的主键id ''' def getWarnTaskAudMess(self,**kwages): temp={} for i in self.getWarnTaskAudMessS(**kwages): temp=i break return(temp) ''' 设置预警信息,将原因和预防措施录入 ,引入**kwages reason 原因 measure 预防措施 status 状态 (1待处理 2待审核 3处理完毕) id taskwarn的主键id ''' def setWarnTaskInfo(self,**kwages): sql="update pps_warntask set reason='%s',measure='%s',writetime=now(),status=%s,userid=%s where status=1 and id=%s"%(pymysql.escape_string(kwages['reason']),pymysql.escape_string(kwages['measure']),kwages['status'],kwages['userid'],kwages['id']) self.putData(**{'sql':sql}) ''' 获取预警信息详情 ,引入**kwages userid 用户id id taskwarn的主键id ''' def getWarnTask(self,**kwages): if kwages['userid'] is not None: sql="SELECT a.id,warnid,c.warnname warntype,d.enviname,warndesc,b.levelname warnlevel,DATE_FORMAT(createtime, '%Y-%m-%d %H:%i:%s') createtime,DATE_FORMAT(recoverytime, '%Y-%m-%d %H:%i:%s') recoverytime,reason,measure,DATE_FORMAT(writetime, '%Y-%m-%d %H:%i:%s') writetime,STATUS,messid,a.userid FROM pps_warntask a LEFT JOIN pps_warnlevel b ON a.`warnlevel`=b.level LEFT JOIN pps_warntype c ON a.warntype=c.warntype LEFT JOIN pps_envitype d ON a.enviname=d.envitype LEFT JOIN pps_warntype_userid e ON c.id=e.ppswarntype_id WHERE e.authuser_id="+str(kwages['userid'])+" and a.id='"+kwages['id']+"'" else: sql="SELECT a.id,warnid,c.warnname warntype,d.enviname,warndesc,b.levelname warnlevel,DATE_FORMAT(createtime, '%Y-%m-%d %H:%i:%s') createtime,DATE_FORMAT(recoverytime, '%Y-%m-%d %H:%i:%s') recoverytime,reason,measure,DATE_FORMAT(writetime, '%Y-%m-%d %H:%i:%s') writetime,STATUS,messid,a.userid FROM pps_warntask a LEFT JOIN pps_warnlevel b ON a.`warnlevel`=b.level LEFT JOIN pps_warntype c ON a.warntype=c.warntype LEFT JOIN pps_envitype d ON a.enviname=d.envitype LEFT JOIN pps_warntype_userid e ON c.id=e.ppswarntype_id WHERE a.id='"+kwages['id']+"'" logger.info(sql) temp=self.getData(**{'sql':sql}) if len(temp)>0: return(temp[0]) else: return({}) ''' 获取warntask对用的用户id,引入**kwages id taskwarn的主键id ''' def getWarnTaskUserid(self,**kwages): sql="SELECT userid FROM pps_warntask WHERE id='"+kwages['id']+"'" #print(sql) temp=self.getData(**{'sql':sql}) if len(temp)>0: return(temp[0]['userid']) else: return(0) ''' #获取待处理消息条,引入**kwages userid 用户id ''' def getUndoMess(self,**kwages): sql="select activityname,date_format(createtime, '%Y-%m-%d %H:%i:%s') createtime,path from pps_message where status=1 and userid="+str(kwages['userid'])+" order by createtime desc" return(self.getData(**{'sql':sql})) ''' 获取预警等级名字,输入{'level':2} 返回一个字典{'levelname':'严重'} ''' def getWarnLevelName(self,**kwages): sql="select levelname from pps_warnlevel where level=%s"%(kwages['level']) return_json=self.getData(**{'sql':sql}) if len(return_json)>0: return(return_json['levelname']) else: return({'levelname':'未知'}) def isExistsWarn(self,**kwages): sql="select count(*) count from pps_warntask where warnid='%s'"%(kwages['id']) if self.getData(**{'sql':sql})[0]['count']>0: return(False) else: return(True) def getUserid(self,**kwages): sql="SELECT a.`authuser_id` userid FROM pps_warntype_userid a LEFT JOIN pps_warntype b ON a.`ppswarntype_id`=b.`id` where warntype='%s'"%(kwages['type']) temp=self.getData(**{'sql':sql}) return(temp) def createWarn(self,**kwages): sql="insert into pps_warntask(warnid,warntype,enviname,warndesc,warnlevel,createtime,status)values(%s,'%s','%s','%s','%s',now(),1)"%(kwages['id'],kwages['type'],kwages['evn'],kwages['msg'],str(self.getWarnLevel(**{'levelname':kwages['level']}))) self.putData(**{'sql':sql}) def getWarnLevel(self,**kwages): sql="select level from pps_warnlevel where levelname='%s'"%(kwages['levelname']) temp=self.getData(**{'sql':sql}) if len(temp)>0: return(temp[0]['level']) else: return(5) def createWarnMsg(self,**kwages): self.createMess(**{'activityname':self.getWarnTypeName(**kwages)+'预警','path':'/pps/dowarn/?id='+kwages['wid'],'userid':kwages['userid']}) pass #设置恢复时间 def setWarnRecoveryTime(self,**kwages): sql="update pps_warntask set recoverytime=now() where warnid=%s" %(kwages['id']) self.putData(**{'sql':sql}) #获取预警类型的名字 def getWarnTypeName(self,**kwages): sql="select warnname from pps_warntype where warntype='%s'"%(kwages['type']) temp=self.getData(**{'sql':sql}) if len(temp)>0: return(temp[0]['warnname']) else: return("未知") #获取环境名 def getEnviName(self,**kwages): sql="select enviname from pps_envitype where envitype='%s'"%(kwages['enviname']) temp=self.getData(**{'sql':sql}) if len(temp)>0: return(temp[0]['enviname']) else: return("未知环境") def create_warntask_w2m(self,**kwages): sql="insert into pps_warntask_w2m (wid,mid)values(%s,%s)"%(kwages['wid'],kwages['mid']) self.putData(**{'sql':sql}) def getMessageId(self,**kwages): sql="select mid from pps_warntask_w2m where wid=%s"%(kwages['wid']) temp=self.getData(**{'sql':sql}) return(temp) <file_sep>[uwsgi] socket=127.0.0.1:8000 pythonpath=/home/deployuser/aom daemonize=/home/deployuser/logs/access.log touch-logreopen = /home/deployuser/logs/touchforlogrotate logdate=%%Y-%%m-%%d %%H:%%M:%%S module=wsgi processes = 1 max-requests = 100 limit-as=1024 disable-logging=true
b3a9decace364ff830ada9068e0fb9367254aba9
[ "INI", "Python", "Shell" ]
13
Python
thcoffee/aom2
d5c45b9905d10906ba14c23f2cf6d29f9b90f60a
534a95dab5e3b68050a41dd3a5ce10b0c7f8ff19
refs/heads/master
<file_sep>package graphs1; import java.util.Iterator; /* * 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. */ public class PreflowPush { double[] heights; double[] excess; int indexofstart=-1; int indexofsink=-1; Double maxflow=(double) 0; SimpleGraph G; public double Preflow(SimpleGraph g){ G=g; Iterator<Vertex> i; Iterator <Vertex>j; Iterator<Edge>k; Iterator<Edge> l; Vertex v1,v2,v; Edge e1,e2; int index=0,index2=-10,count=0; boolean check=false; Double maxex=(double) -1; findvertex("t"); findvertex("s"); excess=new double[G.numVertices()]; for(j= G.vertices(); j.hasNext(); ) { v1= j.next(); v1.setData((double) 0); excess[index]=0; index++; } index=0; v1=G.vertexList.getFirst(); v1.setData((double) G.numVertices()); setflows(); setexcess(); while(true) { for (i= G.vertices(); i.hasNext(); ) { v= i.next(); if(excess[index]>0&&!(v.getName().equals("t"))) { v1=v; index2=index; count++; break; } index++; } index=0; if(count==0) { break; } count=0; for (k = G.incidentEdges(v1); k.hasNext();) { e1 = k.next(); v2=e1.getSecondEndpoint(); if((Double)e1.getName()>0&&(Double)v1.getData()>(Double)v2.getData()) { int index3=findedge(v2,v1); Push(excess[index2],(Double)e1.getName(),G.edgeList.indexOf(e1),index3,index2,G.vertexList.indexOf(v2)); check=true; break; } } if(check!=true) { Relabel(G.vertexList.indexOf(v1)); // break; } check=false; } for (l = G.incidentEdges(G.vertexList.get(indexofsink)); l.hasNext();) { e2 = l.next(); maxflow=maxflow+(Double)e2.getName(); } return maxflow; } public void Relabel(int ind) { Vertex v=G.vertexList.get(ind); v.setData((Double)v.getData()+1); } public void Push(Double ex, Double cap, int ind1, int ind2, int ind3, int ind4) { Double d=Math.min(ex, cap); Edge e1=G.edgeList.get(ind1); Edge e2=G.edgeList.get(ind2); e1.setName((Double)e1.getName()-d); e2.setName((Double)e2.getName()+d); excess[ind3]=excess[ind3]-d; excess[ind4]=excess[ind4]+d; } public void findvertex(String data) { Iterator<Vertex> i; int k=0; Vertex temp; for (i= G.vertices(); i.hasNext();k++ ) { temp = i.next(); if(temp.getName().toString().equals(data)) { if(data.equals("t")) {indexofsink=k; break; } else if(data.equals("s")) { indexofstart=k; break; } } } } public void setflows() { Vertex start,end; Edge e,e2; Iterator<Vertex> i; Iterator<Edge> j; Iterator <Edge> k; double temp; int ind; for (i= G.vertices(); i.hasNext(); ) { start = i.next(); for (j = G.incidentEdges(start); j.hasNext();) { e = j.next(); e.setName(e.getData()); } } for (j = G.incidentEdges(G.vertexList.getFirst()); j.hasNext();) { e = j.next(); temp=(Double)e.getName(); e.setName((double) 0); end=e.getSecondEndpoint(); ind=findedge(end, G.vertexList.getFirst()); e2=G.edgeList.get(ind); e2.setName(temp); } } public void setexcess() { double temp=new Double(0); Iterator <Edge> j; Edge e; Vertex end; for (j = G.incidentEdges(G.vertexList.getFirst()); j.hasNext();) { e = j.next(); end=e.getSecondEndpoint(); int ind=G.vertexList.indexOf(end); excess[ind]=(Double)e.getData(); temp=temp+(Double)e.getData(); } excess[0]=-temp; } public int findedge(Vertex st, Vertex en) { Iterator<Edge> j; Edge e; for (j = G.incidentEdges(st); j.hasNext();) { e = j.next(); if(e.getSecondEndpoint()==en) { return G.edgeList.indexOf(e); } } return -1; } } <file_sep># TCSS543B-NETWORK-FLOW-ALGORITHMS Implemented Three Network Flow Algorithms and Analyzed Performance Varying the Input Parameters SOFTWARE REQUIREMENTS : JAVA [JDK1.6 and above] The given "graphs1" folder contains all the graph files, algorithms and the compiled ".class" files for each of the java files. STEPS TO RUN CODE: 1) Go to the command line and navigate to the CODE DOCUMENTATION folder and execute the following command: "java graphs1.tcss543 path\filename.txt" where path should specify the path leading to the folder where we can find the input graphs and filename correspond to the input file you want to test. 2) Input text files were created from the generating the graph codes. These files are present in a separate folder called OUTPUT which contains sub-folders corresponding to each graph type. CODE DOCUMENTATION: FordFulkerson.java 1. Function: public double Ford_Fulkerson(SimpleGraph g) This function is the main ford Fulkerson algorithm that takes the input graph, finds augmenting paths and updates the graph accordingly. It returns the maxflow and calculates it by adding the bottleneck each time. 2. Function: public boolean findPath() This function calls DFS to search for augmenting paths in the graph and if it finds a path it returns true else false. 3. Function: public double update() This function finds the bottleneck in the path found, updates the graph and returns the bottleneck to be used for the calculation of the maxflow. 4. Function: public void findvertex(String data) This function finds the index of any particular vertex in the graph by just traversing the vertex list. We use it for finding the index of the source and sink. 5. Function: public int findedge(Vertex st, Vertex en) This function finds the index of the edge between the two input nodes. 6. Function: public boolean DFS(Vertex node, boolean []m ) DFS is the usual DFS algorithm function that tries to find a path between the source and sink and returns true if it finds one. ScalingFF.java 1. Function: public double Scaling_Ford_Fulkerson(SimpleGraph g) This is the main function of the scaling algorithm that calculates the delta and then finds augmenting paths using the delta, updates the graph and then calculates the maxflow. 2. Function: public double calculatedelta() This function calculates delta by summing up all capacities of edges going out of source. 3. Function: public boolean findPath() This function calls DFS to search for augmenting paths in the graph and if it finds a path it returns true else false. 4. Function: public double update() This function finds the bottleneck in the path found, updates the graph and returns the bottleneck to be used for the calculation of the maxflow. 5. Function: public void findvertex(String data) This function finds the index of any particular vertex in the graph by just traversing the vertex list. We use it for finding the index of the source and sink. 6. Function: public int findedge(Vertex st, Vertex en) This function finds the index of the edge between the two input nodes. 7. Function: public boolean DFS(Vertex node, boolean []m ) DFS is the usual DFS algorithm function that tries to find a path between the source and sink, the only difference here is that the capacity is checked against delta rather than zero. PreflowPush.java 1. Function: public double Preflow(SimpleGraph g) This function is the main function that runs the preflow push algorithm. It first initializes the flows, excess and heights. Then it checks if there is any node that has an excess and it is not the sink node, for every neighbor of that node through which excess can be pushed it pushes the overflow or else it relabels the node. 2. Function: public void Relabel(int ind) This function relabels the height of the input node by incrementing it. 3. Function: public void Push(Double ex, Double cap, int ind1, int ind2, int ind3, int ind4) This function implements push by finding the minimum out of the capacity of the edge and the excess on the node. Then it updates the flows and excess values. 4. Function: public void setflows() This function sets the initial flows on all edges. 5. Function: public void setexcess() This function sets the excess values of all nodes such that the source has negative excess, the nodes linked to the source have excess equivalent to the capacity of the edge between the source and that node and other nodes have zero excess initialy. 6. Function: public void findvertex(String data) This function finds the index of any particular vertex in the graph by just traversing the vertex list. We use it for finding the index of the source and sink. 7. Function: public int findedge(Vertex st, Vertex en) This function finds the index of the edge between the two input nodes.
049695c583932020d6016657e34d33d9d0198ecc
[ "Markdown", "Java" ]
2
Java
aadarshsampath/TCSS543B-NETWORK-FLOW-ALGORITHMS
9e95c6bccd732376d0b3987aa67cf9153ddf2abf
3bd2ada186ec3394584f3bdf93b73615536465cb
refs/heads/master
<file_sep># OAuth2Google Lab about how to integrate OAuth2 using Google Api # About - This project was created using NodeJs and Express as framework, you must to have installed NodeJs on your machines. - It is using a Google library in order to handle the Authentication, called google-api-nodejs-client - In order to get more info, please refer to https://github.com/google/google-api-nodejs-client/ - You must to create an account in Google Cloud in order to get a client_id and client_secret. Follow this link: https://console.developers.google.com # Preparing environment - Before to run the app, execute npm install in order to get all the dependecies - With all the dependecies already installed, run it using npm start ( Default port: 3000 ) # Steps - The class utils/auth.js was created in order to implement the authentication with Google - Class utils/globalVars.js works as a store of global vars - First up, in your browser execute the request 127.0.0.1:3000 in order to make the authentication (routes/index.js) - Then execute 127.0.0.1:3000/users in order to get a valid token (routes/users.js) - Finally, execute 127.0.0.1:3000/users/test in order to get an info related with Google Plus(routes/users.js) <file_sep>var express = require('express'); var router = express.Router(); var google = require('googleapis'); var plus = google.plus('v1'); var OAuth2 = require('../utils/auth.js');//Import middleware var globalV = require('../utils/globalVars.js');//Import global vars /* GET users listing. */ router.get('/', function(req, res, next) { //After redirect, we will have a authorization code and we need to store it in order to get a token later globalV.auth = req.query.code; //Store authorization code OAuth2.getToken(req.query.code, function(err, tokens) { // Now tokens contains an access_token and an optional refresh_token. Save them. if(!err) { OAuth2.setCredentials(tokens); } globalV.token = tokens; }); res.send('Auth OK'); }); /* Authenticated method */ router.get('/test', function(req, res, next) { var item = {}; //Set token before to request to the resource OAuth2.setCredentials({ access_token: globalV.token.access_token, }); // Requesting to the resource plus.people.get({ userId: '113551191017950459231', auth: OAuth2 }, function(err, response) { if(!err){ console.log('Errorplus: ' + err); } console.log('Errorplus: ' + err); item = response; console.log(JSON.stringify(response)); res.send('Authenticated as: ' + item.nickname); }); //res.send('Authenticated as: ' + item.nickname); }); module.exports = router; <file_sep>// Class for global variables var global = { auth: '', token: '' }; module.export = global;<file_sep>var express = require('express'); var router = express.Router(); var OAuth2 = require('../utils/auth.js');//Import middleware /* GET home page. */ router.get('/', function(req, res, next) { // Generate a url that asks permissions for Google+ and Google Calendar scopes var scopes = [ 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/calendar' ]; var url = OAuth2.generateAuthUrl({ access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token) scope: scopes // If you only need one scope you can pass it as string }); //Redirect client to the url generated res.redirect(url); }); module.exports = router;
0067d4947690e47e460a03b929452ace8a37604b
[ "Markdown", "JavaScript" ]
4
Markdown
juhunuque/OAuth2Google
183ac37bf39f68f9e43e77964b35e1fd856148a5
bee56d307ff2c4a0c211ae997511be20c094a19b
refs/heads/master
<repo_name>OS-Q/B128<file_sep>/README.md # [B20](https://github.com/OS-Q/B20) [![sites](http://172.16.31.10/link/resources/OSQ.png)](http://www.OS-Q.com) ### [简介](https://github.com/OS-Q/B20/wiki) [B20](https://github.com/OS-Q/B20) 板级支持 [CH554](https://github.com/SoCXin/CH554) ### [Q = (OpenSource & OperatingSystem) ](http://www.OS-Q.com) <file_sep>/include/spi.c #include <ch554.h> #include "spi.h" void SPIMasterModeSet(uint8_t mode) { SPI0_SETUP = 0; if(mode == 0) { SPI0_CTRL = 0x60; } else if(mode == 3) { SPI0_CTRL = 0x68; } P1_MOD_OC &= 0x0F; P1_DIR_PU |= 0xB0; P1_DIR_PU &= 0xBF; // Set clock speed SPI0_CK_SE = 0x02; } void CH554SPIInterruptInit() { //IP_EX |= bIP_SPI0; SPI0_SETUP |= bS0_IE_FIFO_OV | bS0_IE_BYTE; SPI0_CTRL |= bS0_AUTO_IF; SPI0_STAT |= 0xff; #ifdef SPI_Interrupt IE_SPI0 = 1; #endif } void CH554SPIMasterWrite(uint8_t dat) { SPI0_DATA = dat; while(S0_FREE == 0); } uint8_t CH554SPIMasterRead() { SPI0_DATA = 0xff; while(S0_FREE == 0); return SPI0_DATA; } void SPISlvModeSet( ) { SPI0_SETUP = 0x80; SPI0_CTRL = 0x81; P1_MOD_OC &= 0x0F; P1_DIR_PU &= 0x0F; } void CH554SPISlvWrite(uint8_t dat) { SPI0_DATA = dat; while(S0_IF_BYTE==0); S0_IF_BYTE = 0; } uint8_t CH554SPISlvRead() { while(S0_IF_BYTE==0); S0_IF_BYTE = 0; return SPI0_DATA; } <file_sep>/examples/adc/platformio.ini [env:test] platform = P04 board = ch554 ; build_flags = ; -D FREQ_SYS=24000000 <file_sep>/include/adc.h #ifndef __ADC_H__ #define __ADC_H__ extern void ADCInit(uint8_t speed); extern uint8_t ADC_ChannelSelect(uint8_t ch); extern uint8_t VoltageCMPModeInit(uint8_t fo,uint8_t re); #endif <file_sep>/include/spi.h #pragma once #include <stdint.h> #define SPI_CK_SET( n ) (SPI0_CK_SE = n) //SPIʱÖÓÉèÖú¯Êý #define SPIMasterAssertCS() (SCS = 0) #define SPIMasterDeassertCS() (SCS = 1) void SPIMasterModeSet(uint8_t mode); void CH554SPIInterruptInit(); void CH554SPIMasterWrite(uint8_t dat); uint8_t CH554SPIMasterRead(); void SPISlvModeSet( ); void CH554SPISlvWrite(uint8_t dat); uint8_t CH554SPISlvRead(); <file_sep>/examples/blink/Makefile TARGET = blink C_FILES = \ src/main.c \ ../../include/debug.c pre-flash: include ../Makefile.include
7ae5744fb6723e42b7750763ba918a1044ff985c
[ "Markdown", "C", "Makefile", "INI" ]
6
Markdown
OS-Q/B128
7ae7ee6ba4ad9aa058f01f1f0a314c8afbe72ca5
5a35d5662d98ce0c21309f6371c8372d7e88aa77
refs/heads/master
<repo_name>ThunderingWest4/work_timer<file_sep>/README.md # work_timer inspired by pomodoro idea to help me keep a track on how long to work and breaks, organization # How to use? At the moment, this is command line based so if you have python installed, navigate to this folder and type `python timer.py <number of times to repeat cycle> <length of work period in mins> <length of break period in mins>` (but with actual numbers) into the cmd line. If it doesn't work, you may need to include the full path to your Python installation and then the whole `timer.py <> <> <>` chunk (it's easiest to just reinstall/edit installation and add to PATH on win10). If you don't have Python, you can't really use this until I compile it to an exe or some other format that's more universal. <file_sep>/timer.py import time import sys from termcolor import colored from tqdm import tqdm import os # Formatting of command: # python timer.py n_cycles len_work len_break sysargs = [str(x) for x in sys.argv] #first arg is gonna be timer.py n_cycles = int(sysargs[1]) len_work = int(sysargs[2]) len_break = int(sysargs[3]) # time.sleep(t) works with t *seconds* clr = lambda: os.system('cls') for n in range(n_cycles): if n_cycles>1: print(colored(f"Cycle {n+1} of {n_cycles} cycles with {len_work} minute(s) working and {len_break} minute(s) on break per cycle", 'blue')) print(colored(f"Work Time! Try to focus on your work for {len_work} minute(s)", 'green')) for i in tqdm(range(4*len_work), desc="Working time"): time.sleep(15) # sleep 15 seconds print(colored(f"Break Time! {len_break} minute(s) off", 'blue')) for i in tqdm(range(4*len_break), desc="Break time"): time.sleep(15) clr() <file_sep>/requirements.txt time sys termcolor tqdm os
5298af64570058adc4361d974f5d3f9016d0c67f
[ "Markdown", "Python", "Text" ]
3
Markdown
ThunderingWest4/work_timer
571170291ffa25b0cf713fc900f4d68d5925a044
9072996f2f5eb99de8f5ed8439ca001bdec89ada
refs/heads/master
<file_sep><?php $folders = elgg_extract("folders", $vars); $folder = elgg_extract("folder", $vars); $selected_id = "file_tools_list_tree_main"; if ($folder instanceof ElggObject) { $selected_id = $folder->getGUID(); } $page_owner = elgg_get_page_owner_entity(); $site_url = elgg_get_site_url(); // load JS elgg_load_css("jquery.tree"); elgg_require_js('file_tools/tree'); $body = "<div id='file-tools-folder-tree' class='clearfix hidden'>"; $body .= elgg_view_menu("file_tools_folder_sidebar_tree", array( "container" => $page_owner, "sort_by" => "priority" )); $body .= "</div>"; if ($page_owner->canEdit() || ($page_owner instanceof ElggGroup && $page_owner->isMember() && $page_owner->file_tools_structure_management_enable != "no")) { elgg_load_js("lightbox"); elgg_load_css("lightbox"); $body .= "<div class='mtm'>"; $body .= elgg_view("input/button", array("value" => elgg_echo("file_tools:new:title"), "id" => "file_tools_list_new_folder_toggle", "class" => "elgg-button-action")); $body .= "</div>"; } // output file tree echo elgg_view_module("aside", "", $body, array("id" => "file_tools_list_tree_container"));
32fe5d6d123c4db9ef613df9ee4ae5325a136e63
[ "PHP" ]
1
PHP
hypeJunction/file_tools
dac20ca0e5e81a673c05e02b03033ae142b23708
54882c6a6f264507c955931088af39beb518f429
refs/heads/master
<file_sep>import AssessmentResult from './AssessmentResult'; export { AssessmentResult as default }; <file_sep>import React from 'react'; // import components import { ResultTitle, ResultContributor } from './components/Header'; import { YourLevel } from './components/YourLevel'; import TechnicalEvaluation from './components/TechnicalEvaluation'; const AssessmentResult = () => { return ( <div> <ResultTitle /> <ResultContributor /> <YourLevel /> <TechnicalEvaluation /> </div> ); }; export default AssessmentResult; <file_sep>import TechnicalEvaluation from './TechnicalEvaluation'; export default TechnicalEvaluation;<file_sep>import React from 'react'; import styled from 'styled-components'; const EvalContainer = styled.div` width: 100%; height: auto; `; const EvalTitle = styled.div` width: 100%; height: 50px; text-align: right; `; const EvalTitleContent = styled.p` font-family: Arial; font-weight: bold; font-size: 20px; text-align: right; color: blue; margin-right: 20px; `; const EvalTitleEn = styled.span` font-family: Arial; font-size: 15px; font-weight: 500; color: blue; `; const TechnicalEvaluation = () => { return ( <EvalContainer> <EvalTitle> <EvalTitleContent> <EvalTitleEn>Technical Evaluation</EvalTitleEn> ارزیابی فنی </EvalTitleContent> </EvalTitle> </EvalContainer> ); }; export default TechnicalEvaluation;<file_sep>import React from 'react'; import styled from 'styled-components'; // import child : ContentBox import ContentBox from './ContentBox'; const ContributorContainer = styled.div` width: 100%; height: auto; position: relative; display: flex; flex-direction: row; justify-content: space-around; flex-flow: wrap; `; const ResultContributor = () => { let DescObj = { "مصاحبه کننده" : "حسان امینی لو", "تاریخ مصاحبه" : "تابستان ۹۹", "موقعیت شغلی درخواستی" : "برنامه نویس ارشد", "نام مصاحبه شونده" : "متانت کرمی", }; return ( <ContributorContainer> { Object.entries(DescObj).map(( item, index ) => ( <ContentBox key={index} interViewDesc={item[0]} interViewValue={item[1]} /> )) } </ContributorContainer> ); }; export default ResultContributor; <file_sep>import React, { useState, useEffect } from 'react'; const AssessmentQuestions = () => { return ( <div> AssessmentQuestions </div> ); }; export default AssessmentQuestions; <file_sep>import ResultTitle from './ResultTitle'; import ResultContributor from './ResultContributor'; export { ResultTitle, ResultContributor }; <file_sep>import React from 'react'; import styled from 'styled-components'; import AssessmentQuestions from './components/AssessmentQuestions'; import AssessmentResult from './components/AssessmentResult'; const Container = styled.div` width: 80%; position: relative; left: 50%; transform: translateX(-50%); `; const App = () => { return ( <Container> <AssessmentResult /> </Container> ); }; export default App; <file_sep>import YourLevel from './Yourlevel'; export { YourLevel }; <file_sep>import React from 'react'; import styled from 'styled-components'; import './assets/SatisfactionLevel.css'; import './assets/SatisfactionLevelInner.css'; import './assets/SatisfactionLevelOuter.css'; import './assets/SatisfactionLevelTrigger.css'; const SemicircularContainer = styled.div` width: 350px; height: 175px; position: relative; left: 50%; transform: translateX(-50%); `; const SatisfactionLevel = () => { return ( <SemicircularContainer> <ul class="chart-skills-outer" /> <ul class="chart-skills"> <li /> <li /> <li /> </ul> <ul class="chart-skills-inner"> <li /> </ul> <ul class="chart-skills-trigger"> <li /> </ul> </SemicircularContainer> ); }; export default SatisfactionLevel;
64c391c99b98d6fb02e915357b119208e47923a9
[ "JavaScript" ]
10
JavaScript
alirezazbr/Assessment
b686a367fdb3167fafa287cec6bd7682a0b181d3
402779c60da0208bca0ab0b1a9e80810ae715747
refs/heads/master
<file_sep># react-easy-infinite-scroll <br/> [![npm](https://img.shields.io/npm/dt/react-easy-infinite-scroll.svg?style=flat-square)](https://www.npmjs.com/package/react-easy-infinite-scroll) [![npm](https://img.shields.io/npm/v/react-easy-infinite-scroll.svg?style=flat-square)](https://www.npmjs.com/package/react-easy-infinite-scroll) ![License: MIT](https://img.shields.io/badge/License-MIT-green.svg) <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section --> [![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-) <!-- ALL-CONTRIBUTORS-BADGE:END --> A component to make all your infinite scrolling! ## Install ```jsx npm install --save react-easy-infinite-scroll or yarn add react-easy-infinite-scroll // in code ES6 import ReactEasyInfiniteScroll from 'react-easy-infinite-scroll'; // or commonjs var ReactEasyInfiniteScroll = require('react-easy-infinite-scroll'); ``` ## Using ```jsx // payload: { skip: 0 } const getData = (payload) => { // api call }; <ReactEasyInfiniteScroll listLength={data.list.length} totalRecords={data.totalRecords} apiCallBack={getData} />; ``` ## props | name | type | description | | ------------------------- | -------- | ----------------------------------------------------------------------------- | | **listLength** | number | pass length of current data list. | | **totalRecords** | number | pass total records to show | | **apiCallBack** | function | api call back function, you will get `skip` value as object | | **loader** (optinal) | node | you can change the loader by this property, by default we have set the loader | | **loaderColor** (optinal) | string | default loader color can be change by this property | ## Contributors ✨ <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --> <!-- prettier-ignore-start --> <!-- markdownlint-disable --> <table> <tr> <td align="center"><a href="https://github.com/ParthPatel-DA"><img src="https://avatars.githubusercontent.com/u/35848924?s=100&v=4" width="100px;" alt=""/><br /><sub><b><NAME></b></sub></a></td> </tr> </table> <!-- markdownlint-restore --> <!-- prettier-ignore-end --> <!-- ALL-CONTRIBUTORS-LIST:END --> ## LICENSE [MIT](LICENSE) <file_sep>import React, { useEffect, useRef, useState } from "react"; // import ReactDOM from 'react-dom'; import Spinner from "./Spinner/Spinner"; const ReactEasyInfiniteScroll = (props) => { const { listLength, apiCallBack, totalRecords = 0, loader, loaderColor, } = props; const [isVisible, setIsVisible] = useState(false); const [waitForResponse, setWaitForResponse] = useState(false); const [loadMore, setLoadMore] = useState(true); const element = useRef(null); const isInViewport = () => { const offset = 0; if (!element.current) return false; const { top } = element.current.getBoundingClientRect(); setIsVisible(top + offset >= 0 && top - offset <= window.innerHeight); return top + offset >= 0 && top - offset <= window.innerHeight; }; useEffect(() => { setTimeout(() => { window.addEventListener("scroll", isInViewport); }, 1000); return () => { window.removeEventListener("scroll", isInViewport); }; }, []); useEffect(() => { if (listLength) { if (totalRecords === listLength) { setLoadMore(false); } else { setLoadMore(true); } } else { setLoadMore(false); } setWaitForResponse(false); }, [listLength]); useEffect(() => { if (isVisible === true) { if (waitForResponse === false) { apiCallBack({ skip: listLength }); setWaitForResponse(true); } } }, [isVisible]); return ( <> {/* {console.log(ReactDOM)} */} {listLength !== undefined && loadMore && ( <div ref={element}> {loader || <Spinner withoutMargin loaderColor={loaderColor} />} </div> )} </> ); }; export default ReactEasyInfiniteScroll;
b614c25742f71cbcd73466c500331c145917fe92
[ "Markdown", "JavaScript" ]
2
Markdown
parthpatelsolulab/react-easy-infinite-scroll
aeb0e7bba62f5cdce526015f5a4eceb19e717910
07265fcb86e2962c5fb841dc76f27b77475dfcb9
refs/heads/master
<repo_name>Ennaxor/eventify<file_sep>/globals.ts 'use strict'; export var USER_TOKEN=''; export function setUSER_TOKEN(tkn: string) { USER_TOKEN = tkn; } export function getUSER_TOKEN() { return USER_TOKEN; }<file_sep>/src/app/Event.ts export interface Event { name: string; description: string; start_time: string; end_time: string; attending: number; picture: string; latitude: number; longitude: number; place: string; }<file_sep>/src/app/events.service.ts import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import { Observable } from 'rxjs'; import { Subject } from 'rxjs/Subject'; //Eventos de facebook import FbEvents from '../assets/fb-events-es6'; import { Event } from './Event'; @Injectable() export class EventsService { private fbEvent; private mytkn; events: Event[] = []; constructor(private http: Http) { this.fbEvent = new FbEvents(); this.mytkn = localStorage.getItem('auth_token'); } getAllEvents(): Observable<Event[]> { localStorage.setItem("storageEvents", JSON.stringify(this.events)); return Observable.of(this.events); } searchEvents(lat, lng){ var eventOptions = { lat: lat, lon: lng, // since: 1500595200, // until: 1503187200, filter: true } this.fbEvent.setToken(this.mytkn) .then(() => { return this.fbEvent.getEvents(eventOptions); }) .then(evs => { for(let i of evs){ //console.log(evs); this.events.push({ name: i.name, description: i.description, start_time: i.start_time, end_time: i.end_time, attending: i.attending_count, picture: i.cover.source, latitude: i.venue.location.latitude, longitude: i.venue.location.longitude, place: i.venue.location.city }); } localStorage.setItem("storageEvents", JSON.stringify(this.events)); }) .catch(err => { console.log(err); }) } } <file_sep>/server/routes/api.js const express = require('express'); const router = express.Router(); const axios = require('axios'); const API = 'https://jsonplaceholder.typicode.com'; //MONGODB const mongojs = require('mongojs'); //mongodb://<dbuser>:<<EMAIL>:57500/eventify //colecciones const db = mongojs('mongodb://ennaxor:<EMAIL>:57500/eventify', ['events']); /* GET API */ router.get('/', (req, res) => { res.send('api works'); }); /* EJEMPLO SACANDO DATOS DE UNA API COMO AXIOS */ router.get('/posts', (req, res) => { axios.get(`${API}/posts`) .then(posts => { res.status(200).json(posts.data); }) .catch(error => { res.status(500).send(error) }); }); /* EJEMPLO SACANDO DATOS DE MONGOFB */ // Lista de eventos router.get('/events', (req, res) => { db.events.find(function(err, docs){ if(err){ res.status(500).send(err); } res.status(200).json(docs); }); }); // Evento en concreto según una ID router.get('/event/:id', (req, res) => { db.events.findOne({ id: mongojs.ObjectId(req.params.id)}, function(err, doc){ if(err){ res.status(500).send(err); } res.status(200).json(doc); }); }); module.exports = router;<file_sep>/src/app/events/events.component.ts import { Component, OnInit } from '@angular/core'; import { EventsService } from '../events.service'; import { Event } from '../Event'; @Component({ selector: 'app-events', templateUrl: './events.component.html', styleUrls: ['./events.component.css'] }) export class EventsComponent implements OnInit { //inicializar eventos en array vacío //events: any = []; events: Event[]; constructor(private eventsService: EventsService) { } ngOnInit() { // this.showEvents(); } showEvents(){ // this.events = this.eventsService.getAllEvents(); //console.log("events in component", this.events); } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { EventsComponent } from './events/events.component'; import { EventsService } from './events.service'; //MODULO DE FACEBOOK import { FacebookModule } from 'ngx-facebook'; //MODULO DE GOOGLE MAPS import { AgmCoreModule } from 'angular2-google-maps/core'; import {GoogleMapsAPIWrapper} from "../../node_modules/angular2-google-maps/core/services/google-maps-api-wrapper"; // RUTA const ROUTES = [ { path: '', redirectTo: 'events', pathMatch: 'full' }, { path: 'events', component: EventsComponent } ]; @NgModule({ declarations: [ AppComponent, EventsComponent ], imports: [ BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(ROUTES), //añade la ruta a la app FacebookModule.forRoot(), AgmCoreModule.forRoot({ apiKey: '<KEY>' }) ], providers: [EventsService, GoogleMapsAPIWrapper], //añadir el servicio aqui bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/server.js // Nuestras dependencias const express = require('express'); const path = require('path'); const http = require('http'); const bodyParser = require('body-parser'); // Las rutas API const api = require('./server/routes/api'); // Creación de la aplicación EXPRESS const app = express(); // Para parsear peticiones POST en el futuro app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // Apuntar el PATH a nuestra carpeta DIST app.use(express.static(path.join(__dirname, 'dist'))); // Setteando la ruta de nuestra API app.use('/api', api); // En nuestra app, siempre devolver nuestro INDEX en cualquier ruta app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'dist/index.html')); }); /*** * * * * * * * * * ***/ /** * Asignamos el puerto para la app de EXPRESS */ const port = process.env.PORT || '4000'; app.set('port', port); /** * Creando el Servidor HTTP... */ const server = http.createServer(app); /** * Puerto abierto en el 4000 */ server.listen(port, () => console.log(`API running on localhost:${port}`));<file_sep>/src/app/app.component.ts import { Component, OnInit, NgZone, EventEmitter } from '@angular/core'; import { Router } from '@angular/router'; import {FacebookService, LoginResponse, LoginOptions, UIResponse, UIParams, FBVideoComponent} from 'ngx-facebook'; import { Http, Response, RequestOptions, Headers, Request, RequestMethod } from '@angular/http'; import { EventsService } from './events.service'; import { MapsAPILoader } from 'angular2-google-maps/core'; import {GoogleMapsAPIWrapper} from "../../node_modules/angular2-google-maps/core/services/google-maps-api-wrapper"; import { Subscription } from 'rxjs/Subscription'; import * as myGlobals from '../../globals'; import { Event } from './Event'; declare var google: any; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Login con FACEBOOK y mapa de GOOGLE'; lat: number = 0; lng: number = 0; zoom: number = 12; subscription: Subscription; events: Event[]; markers: marker[] = []; mark private loggedIn = false; private mytkn; private myLat; private myLong; private myCoords; private faceName; //hallar direccion private geocoder; private userCity; private userProv; //llamada por primera vez antes del ngOnInit() constructor(private fb: FacebookService, private http: Http, private router: Router, private eventsService: EventsService, private mapsAPILoader: MapsAPILoader, private mapApiWrapper: GoogleMapsAPIWrapper, private ngZone : NgZone) { console.log('Initializing Facebook'); fb.init({ appId: '631545433723193', version: 'v2.9' }); this.loggedIn = !!localStorage.getItem('auth_token'); } //called after the constructor and called after the first ngOnChanges() ngOnInit(){ //inicializar google maps this.mapsAPILoader.load().then(() => { console.log('google script loaded'); this.geocoder = new google.maps.Geocoder(); if (localStorage.getItem("auth_token") != null) { this.mytkn = localStorage.getItem('auth_token'); if(this.isLoggedIn()){ //podemos trabajar con los eventos if(navigator.geolocation){ navigator.geolocation.getCurrentPosition((position) => { Promise.all([ this.myLat = position.coords.latitude, this.myLong = position.coords.longitude, this.lat = this.myLat, this.lng = this.myLong, this.getLocationName(this.lat, this.lng), //guardar coordenadas para html this.myLat = this.myLat.toString(), this.myLong = this.myLong.toString(), this.myCoords = this.myLat.substring(0,7) + ", " + this.myLong.substring(0,7) ]).then(() => this.eventsService.searchEvents(this.myLat, this.myLong)); }); Promise.all([ this.subscription = this.eventsService.getAllEvents() .subscribe(ev => { this.events = ev; }) ]).then(() => this.drawEvents()); }else{ //NO PODEMOS TRABAJAR } } } if (localStorage.getItem("name") != null) { this.faceName = localStorage.getItem('name'); console.log(this.faceName); } }); } ngOnChanges(){ if (localStorage.getItem("name") != null) { this.faceName = localStorage.getItem('name'); } } /* ************ MANEJAR EVENTOS *************** */ drawEvents(){ if (localStorage.getItem("storageEvents") != null && localStorage.getItem("storageEvents") != '[]'){ var aux = localStorage.getItem("storageEvents"); this.events = JSON.parse(aux); var formattedDateS, formattedDateE; var latlngAux; var latAdded = 0; var lngAdded = 0; for(var i of this.events){ console.log("evento concreto", i); formattedDateS = this.convertDate(i.start_time); formattedDateE = this.convertDate(i.end_time); //valor de lat + long para comprobar duplicados latlngAux = ""+i.latitude+i.longitude; if(this.markers.length > 0){ for(var j of this.markers){ if(j.latlng == latlngAux){ latAdded = 0.002; lngAdded = 0.002; } else{ latAdded = 0; lngAdded = 0; } } } this.markers.push({ lat: i.latitude+latAdded, lng: i.longitude+lngAdded, latlng: latlngAux, label: i.name, draggable: false, description: i.description, start_time: formattedDateS, end_time: formattedDateE, attending: i.attending, picture: i.picture, place: i.place }); } } } convertDate(inputFormat) { function pad(s) { return (s < 10) ? '0' + s : s; } var d = new Date(inputFormat); return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/'); } /** * LOGIN CON PERMISOS MÍNIMOS. Sólo recibimos el perfil. */ login() { this.fb.login() .then((res: LoginResponse) => { console.log('Logged in', res); }) .catch(this.handleError); } /** * LOGIN CON MÁS PERMISOS. Recibimos lista de amigos, de eventos... */ loginWithOptions() { const loginOptions: LoginOptions = { enable_profile_selector: true, return_scopes: true, scope: 'public_profile, user_friends, email, pages_show_list, user_events' }; this.fb.login(loginOptions) .then((res: LoginResponse) => { console.log('Logged in', res); this.loggedIn = true; localStorage.setItem('auth_token', res.authResponse.accessToken); myGlobals.setUSER_TOKEN(res.authResponse.accessToken); this.getProfile(); }) .catch(this.handleError); } logout(){ localStorage.removeItem('auth_token'); this.loggedIn = false; location.reload(); } isLoggedIn() { return this.loggedIn; } getLoginStatus() { this.fb.getLoginStatus() .then(console.log.bind(console)) .catch(console.error.bind(console)); } getLocationName(x, y){ var latlng = new google.maps.LatLng(x, y); var aux = this; this.geocoder.geocode({'latLng': latlng}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if(results[1]){ aux.userCity = results[1].address_components[0].long_name; aux.userProv = results[1].address_components[3].long_name; } else{ console.log("Sin resultados"); } } else{ console.log("Geocoder fallado"); } }); } /** * Get the user's profile */ getProfile() { this.fb.api('/me') .then((res: any) => { console.log('Got the users profile', res); var str = res.name; var i = str.indexOf(' '); str = str.substring(0, i); console.log('name:', str); localStorage.setItem('name', str); location.reload(); }) .catch(this.handleError); } /** * Get the users friends */ getFriends() { this.fb.api('/me/friends') .then((res: any) => { console.log('Got the users friends', res); }) .catch(this.handleError); } /* ------------ GOOGLE MAPS ------------ */ clickedMarker(label: string, index: number) { console.log(`clicked the marker: ${label || index}`) } mapClicked($event: any) { /*this.markers.push({ lat: $event.coords.lat, lng: $event.coords.lng, draggable: true });*/ } markerDragEnd(m: marker, $event: MouseEvent) { console.log('dragEnd', m, $event); } private handleError(error) { console.error('Error processing action', error); } } interface marker { lat: number; lng: number; latlng: string; label?: string; description: string; start_time: string; attending: number; picture: string; draggable: boolean; place: string; end_time: string; }
396debbe2e16f7898fa20efc0dffd59233362f26
[ "JavaScript", "TypeScript" ]
8
TypeScript
Ennaxor/eventify
e7728599615a4cb6789a76a6c2df07bc4fb7fa70
175386f8996e4b5346ff1169557eb304e389cb27
refs/heads/master
<file_sep>const _ = require('lodash'); const module = require('ui/modules').get('kibana'); define(function (require) { module.directive('fieldSelect', function (indexPatterns, Private) { return { restrict: 'E', replace: true, scope: { meta: '=', filterType: '=' }, template: require('./fieldSelect.html'), link: function (scope, element, attrs) { indexPatterns.getIds().then(ids => { scope.indexList = ids; }); if (!scope.filterType) { scope.filterType = "Query"; } scope.filterTypes = ["Query", "Geo Spatial"].map((value) => { return value }); scope.fieldnames = []; scope.fetchFields = function() { indexPatterns.get(this.meta.indexId).then(indexPattern => { scope.fieldnames = indexPattern.fields.map(function (field) { return field.name; }); scope.fieldnames = scope.fieldnames.sort((a, b) => { return a.localeCompare(b); }); }); } if (scope.meta.indexId) { scope.fetchFields(); } } } }); });<file_sep>import TemplateVisTypeTemplateVisTypeProvider from 'ui/template_vis_type/template_vis_type'; define(function (require) { require('ui/registry/vis_types').register(EzQueryVisProvider); require('plugins/ez-query/vis.less'); require('plugins/ez-query/ezQueryRegistry'); require('plugins/ez-query/directives/fieldSelect'); require('plugins/ez-query/directives/luceneQueries'); require('plugins/ez-query/visController'); function EzQueryVisProvider(Private, getAppState, courier, config) { const TemplateVisType = Private(TemplateVisTypeTemplateVisTypeProvider); return new TemplateVisType({ name: 'ez-query', title: 'EZ Query', icon: 'fa-ellipsis-v', description: 'Use this visualiation to provide a list of predefined Lucene queries for easy selection.', template: require('plugins/ez-query/vis.html'), params: { editor: require('plugins/ez-query/options.html'), defaults: { buttonType: 'radio', luceneQueries: [], field_meta: { filterType: "Query" }, filters: [], filterType: 'query' } }, requiresSearch: false }); } return EzQueryVisProvider; }); <file_sep>import _ from 'lodash'; import $ from 'jquery'; define(function (require) { var module = require('ui/modules').get('kibana/ez-query', ['kibana']); module.controller('KbnEzQueryVisController', function ($scope, $timeout, getAppState, Private, ezQueryRegistry, savedVisualizations, esAdmin) { const queryFilter = Private(require('ui/filter_bar/query_filter')); let $queryInput = null; let $querySubmit = null; const appState = getAppState(); const DEFAULT_QUERY = '*'; init(); // Get the visualization document in the index since we'll want to change the visState. let title = $scope.vis.title; esAdmin.search({ index: '.kibana', type: 'visualization', body: { query: { bool: { must: { match_phrase: { title } }, } }, size: 1 } }).then((response) => { if (response.hits.hits[0]) { $scope.visualizationId = response.hits.hits[0]._id; } }); const unregisterFunc = ezQueryRegistry.register(function() { const selected = getSelectedQueries(); if (selected.length === $scope.queries.length) { $scope.toggle.isChecked = true; } else { $scope.toggle.isChecked = false; } const queryString = _.map(selected, query => { return '(' + query.query + ')'; }).join(' OR '); return queryString; }); $scope.$on('$destroy', function() { if (unregisterFunc) unregisterFunc(); }); queryFilter.on('update', function() { if ($scope.vis.params.filterType === 'filter' && !findFilter()) { clearSelectedQueries(); } }); $scope.toggle = { isChecked: false }; $scope.toggleAll = function() { $scope.queries.forEach(query => { $scope.checkboxes[query.name] = $scope.toggle.isChecked; }); $scope.filter(); } $scope.filter = _.debounce(function() { switch ($scope.vis.params.filterType) { case 'filter': const selected = getSelectedQueries(); if (selected.length === 0) { const existingFilter = findFilter(); if (existingFilter) { queryFilter.removeFilter(existingFilter); } } else { setFilter(selected); } break; default: setQuery(ezQueryRegistry.buildQuery(), true); } }, _.get($scope.vis.params, 'selectionDebounce', 350), false); function isGeoSpatialFilterType() { return $scope.vis.params.field_meta.filterType === 'Geo Spatial'; } function setFilter(selected) { const alias = selected.map(function(query) { return query.name; }).join(','); let query_string = ""; let geoSpatialModel = null; if (!isGeoSpatialFilterType()) { query_string = { fields: [$scope.vis.params.field_meta.key], query: selected.map(function (query) { return query.query; }).join(' OR ') }; } else { let geoFilters = []; if (selected.length > 1) { geoSpatialType = 'bool'; selected.forEach((query) => { geoFilters.push(getGeoSpatialModel(query.filter)); }); geoSpatialModel = { bool: { should: geoFilters } }; } else { geoSpatialModel = getGeoSpatialModel(selected[0].filter); } } let existingFilter = findFilter(); if (existingFilter) { let updateFilter = null; if (isGeoSpatialFilterType()) { // Have to get existing type and pass it to updateFilter as type so it can delete // the source property after the merge. let existingType = ''; if (_.has(existingFilter, 'bool.should')) { existingType = 'bool'; } else if (_.has(existingFilter, 'geo_bounding_box')) { existingType = 'geo_bounding_box'; } else if (_.has(existingFilter, 'geo_polygon')) { existingType = 'geo_polygon'; } else if (_.has(existingFilter, 'geo_shape')) { existingType = 'geo_shape'; } updateFilter = { model: geoSpatialModel, source: existingFilter, type: existingType, alias: alias } } else { updateFilter = { model: { query_string: query_string }, source: existingFilter, alias: alias }; } queryFilter.updateFilter(updateFilter); } else { let newFilter = null; if (isGeoSpatialFilterType()) { newFilter = geoSpatialModel; } else { newFilter = { query_string: query_string, } } newFilter.meta = { alias: alias, negate: false, index: $scope.vis.params.field_meta.indexId, key: $scope.vis.params.field_meta.key } queryFilter.addFilters(newFilter); } } function setQuery(queryString, submit) { if (!$queryInput) { $queryInput = $("input[aria-label='Filter input']"); } if (!$querySubmit) { $querySubmit = $("button[aria-label='Filter Dashboards']"); } if ($queryInput && $querySubmit) { appState.query.query_string.query = queryString; //appState.save(); $queryInput.val(queryString); if (submit) { $timeout(function() { $querySubmit.trigger('click'); }, 0); } } } function isGeoFilter(filter, field) { if (filter.meta.key === field || _.has(filter, ['geo_bounding_box', field]) || _.has(filter, ['geo_distance', field]) || _.has(filter, ['geo_polygon', field]) || _.has(filter, ['geo_shape', field])) { return true; } else if(_.has(filter, ['bool', 'should'])) { let model = getGeoSpatialModel(filter); let found = false; for (let i = 0; i < model.bool.should.length; i++) { if (_.has(model.bool.should[i], ['geo_bounding_box', field]) || _.has(model.bool.should[i], ['geo_distance', field]) || _.has(model.bool.should[i], ['geo_polygon', field]) || _.has(model.bool.should[i], ['geo_shape', field])) { found = true; break; } } return found; } else { return false; } } function findFilter() { let existingFilter = null; _.flatten([queryFilter.getAppFilters(), queryFilter.getGlobalFilters()]).forEach(function (it) { if (isGeoSpatialFilterType()) { if (isGeoFilter(it, $scope.vis.params.field_meta.key)) { existingFilter = it; } } else { if (_.has(it, 'query_string.fields') && _.includes(_.get(it, 'query_string.fields', []), $scope.vis.params.field_meta.key)) { existingFilter = it; } } }); return existingFilter; } function getSelectedQueries() { const selected = []; switch ($scope.vis.params.buttonType) { case 'radio': $scope.queries.forEach(query => { if (query.name === $scope.radioVal) { selected.push(query); } }); break; case 'checkbox': const checked = []; _.forOwn($scope.checkboxes, (isChecked, queryName) => { if (isChecked) checked.push(queryName); }); $scope.queries.forEach(query => { if (_.includes(checked, query.name)) { selected.push(query); } }); break; } return selected; } function clearSelectedQueries() { switch ($scope.vis.params.buttonType) { case 'radio': $scope.radioVal = null; break; case 'checkbox': _.forOwn($scope.checkboxes, (value, key, object) => { object[key] = false; }); break; } } $scope.$watch('vis.params', function (visParams) { switch ($scope.vis.params.filterType) { case 'filter': $scope.queries = $scope.vis.params.filters; break; default: $scope.queries = $scope.vis.params.luceneQueries; } }); $scope.$listen(queryFilter, 'update', function () { getAvailableFilters(); }); $scope.addFilter = function() { const filter = $scope.availableFilters.find((filter) => filter.$$hashKey === $scope.filterToAdd); let name = $scope.newName ? $scope.newName : filter.meta.alias; filter.meta.alias = name; filter.meta.key = $scope.vis.params.field_meta.key; const newFilter = {name: name, filter: filter}; $scope.vis.params.filters.push(newFilter); $scope.queries = $scope.vis.params.filters; $scope.vis.setState($scope.vis); savedVisualizations.get($scope.visualizationId).then((visualization) => { visualization.visState.params.filters = $scope.vis.params.filters; visualization.save(); setFilter([newFilter]); getAvailableFilters(); $scope.radioVal = name; $scope.checkboxes[name] = true; }); } function getAvailableFilters() { $scope.filterToAdd = null; $scope.availableFilters = []; $scope.newName = null; if (!isGeoSpatialFilterType()) { return; } _.flatten(queryFilter.getFilters()).forEach(function (filter) { if (isGeoFilter(filter, $scope.vis.params.field_meta.key)) { let existingFilter = $scope.vis.params.filters.find((namedFilter) => { return containsGeoFilter(filter, namedFilter.filter); }); if (!existingFilter) { $scope.availableFilters.push(filter); // If we have available filters then any previously selected filter is technically no // longer selected because it's filter has been changed to something we dont know. clearSelectedQueries(); } } }); } $scope.clearSelect = function() { clearSelectedQueries(); let existingFilter = findFilter(); queryFilter.removeFilter(existingFilter); } function getGeoSpatialModel(filter) { let geoSpatialModel = null; if (_.has(filter, 'bool.should')) { geoSpatialModel = { bool: filter.bool }; } else if (_.has(filter, 'geo_bounding_box')) { geoSpatialModel = { geo_bounding_box: filter.geo_bounding_box }; } else if (_.has(filter, 'geo_polygon')) { geoSpatialModel = { geo_polygon: filter.geo_polygon }; } else if (_.has(filter, 'geo_shape')) { geoSpatialModel = { geo_shape: filter.geo_shape }; } return geoSpatialModel; } function containsGeoFilter(left, right) { const names = left.meta.alias.split(','); return names.indexOf(right.meta.alias) > -1; } function init() { $scope.radioVal = ''; $scope.checkboxes = {}; if (!$scope.vis.params.field_meta.filterType) { $scope.vis.params.field_meta.filterType = 'Query'; } switch ($scope.vis.params.filterType) { case 'filter': $scope.queries = $scope.vis.params.filters; let existingFilter = findFilter(); if (existingFilter) { $scope.vis.params.filters.forEach(query => { if (isGeoSpatialFilterType()) { if (containsGeoFilter(existingFilter, query.filter)) { $scope.radioVal = query.name; $scope.checkboxes[query.name] = true; } } else { if (_.includes(existingFilter.query_string.query, query.query)) { $scope.radioVal = query.query; $scope.checkboxes[query.name] = true; } } }); } getAvailableFilters(); break; default: $scope.queries = $scope.vis.params.luceneQueries; $scope.vis.params.luceneQueries.forEach(query => { if (_.includes(appState.query.query_string.query, query.query)) { $scope.radioVal = query.query; $scope.checkboxes[query.name] = true; } }); } } }); }); <file_sep>const _ = require('lodash'); const module = require('ui/modules').get('kibana'); define(function (require) { module.directive('queryList', function (Private) { return { restrict: 'E', replace: true, scope: { queries: '=', title: '=', addQuery: '=' }, template: require('./luceneQueries.html'), link: function (scope, element, attrs) { scope.add = function() { scope.queries.push({}); } scope.remove = function(index) { scope.queries.splice(index, 1); } } } }); });<file_sep>const _ = require('lodash'); const module = require('ui/modules').get('kibana'); module.service('ezQueryRegistry', function (Private, indexPatterns) { class EzQueryRegistry { constructor() { this.count = 0; this.registry = new Map(); } register(getQueryFunc) { const id = this.count++; this.registry.set(id, getQueryFunc); const self = this; return function() { self.registry.delete(id); } } buildQuery() { const fragments = []; for (var [key, getQueryFunc] of this.registry) { const fragment = getQueryFunc(); if (fragment && fragment.length > 0) { fragments.push('(' + fragment + ')'); } } if (fragments.length === 0) { fragments.push('*'); } return fragments.join(' AND '); } } return new EzQueryRegistry(); });<file_sep># ez-query Lucene Queries are a powerful tool that unleashes ElasticSearch. However, your average Kibana user will not understand the syntax and struggle crafting queries. EZ-query provides a simple kibana visualization that allows Dashboard authors to create a list of Lucene Queries that are then selectable from an easy to use GUI. ![alt text](https://github.com/nreese/ez-query/blob/gh-pages/images/multiple.gif) # Install ## Kibana 5.x ```bash cd KIBANA_HOME/plugins git clone <EMAIL>:nreese/ez-query.git vi ez-query/package.js //set version to match kibana version ``` # Uninstall ## Kibana 5.x ```bash ./bin/kibana-plugin remove ez-query ```
d64fcaf3a5a84cebaf17c013016c1f02588e82d9
[ "JavaScript", "Markdown" ]
6
JavaScript
nreese/ez-query
23b22ef2e5b93c3649b1c0230c82b43970eb038b
629d53eb013e494cb311674f2da6b5bb10773a33
refs/heads/master
<file_sep>package uri import "testing" func TestGetCompany(t *testing.T) { tt := []struct { companyNumber string companyName string }{ {"05581537", "OPEN RIGHTS"}, {"11302912", "DISTRIBUTED, BLOCKCHAIN AND BUSINESS SOLUTIONS LTD"}, } for _, tc := range tt { t.Run(tc.companyNumber, func(t *testing.T) { company, err := GetCompany(tc.companyNumber) if err != nil { t.Fatalf("Expected to pass, but got %v", err) } if company.Name != tc.companyName { t.Errorf("Expected company name to be %s. but got %s", tc.companyName, company.Name) } t.Logf("%v", company) }) } } <file_sep># Maintainer <NAME> <<EMAIL>><file_sep>package uri import ( "encoding/json" "fmt" "net/http" "strconv" "strings" "time" ) const url = "http://data.companieshouse.gov.uk/doc/company/%s.json" // ChDate is type which supports unmarshalling from CH json response to a Go time type type ChDate struct { time.Time } // UnmarshalJSON implements the unmarshalling functionality func (cd *ChDate) UnmarshalJSON(b []byte) (err error) { s := strings.Trim(string(b), "\"") if len(s) == 0 { return } cd.Time, err = time.Parse("02\\/01\\/2006", s) return } // AsPointerToTime is a helper function to convert with *ChDate to *time.Time func AsPointerToTime(cd *ChDate) *time.Time { if cd == nil { return nil } return &cd.Time } type strint int func (v *strint) UnmarshalJSON(b []byte) error { s := strings.Trim(string(b), "\"") i, err := strconv.Atoi(s) if err != nil { return err } *v = strint(i) return nil } func (v *strint) Int() int { return int(*v) } func (v strint) String() string { return strconv.Itoa(v.Int()) } type Company struct { Name string `json:"CompanyName"` RegistrationNumber string `json:"CompanyNumber"` RegisteredOffice struct { CareOf string `json:"Careof"` POBox string `json:"POBox"` AddressLine1 string `json:"AddressLine1"` AddressLine2 string `json:"AddressLine2"` PostTown string `json:"PostTown"` County string `json:"County"` Country string `json:"Country"` Postcode string `json:"Postcode"` } `json:"RegAddress"` Category string `json:"CompanyCategory"` Status string `json:"CompanyStatus"` CountryOfOrigin string `json:"CountryofOrigin"` IncorporationDate *ChDate `json:"IncorporationDate"` RegistrationDate *ChDate `json:"RegistrationDate"` DissolutionDate *ChDate `json:"DissolutionDate"` PreviousNames []struct { CONDate ChDate `json:"CONDate"` CompanyName string } `json:"PreviousName"` Accounts struct { RefDay strint `json:"AccountRefDay"` RefMonth strint `json:"AccountRefMonth"` NextDueDate *ChDate `json:"NextDueDate"` LastMadeUpDate *ChDate `json:"LastMadeUpDate"` Category string `json:"AccountsCategory"` } `json:"Accounts"` Returns struct { NextDueDate *ChDate `json:"NextDueDate"` LastMadeUpDate *ChDate `json:"LastMadeUpDate"` } `json:"Returns"` Mortgages struct { Charges strint `json:"NumMortCharges"` Outstanding strint `json:"NumMortOutstanding"` PartSatisfied strint `json:"NumMortPartSatisfied"` Satisfied strint `json:"NumMortSatisfied"` } `json:"Mortgages"` SICCodes struct { Text []string `json:"SicText"` } `json:"SICCodes"` LimtitedPartnerships struct { GeneralPartners strint `json:"NumGenPartners"` NumLimPartners strint `json:"NumLimPartners"` } } // HasTasks returns true if any statutory task is overdue func (c Company) HasTasks() bool { now := time.Now() return now.Sub(c.Accounts.NextDueDate.Time) < 0 || now.Sub(c.Returns.NextDueDate.Time) < 0 } type chResponse struct { PrimaryTopic Company `json:"primaryTopic"` } // GetCompany fetches data from Companies House and returns a Company func GetCompany(companyNumber string) (*Company, error) { a, err := http.Get(fmt.Sprintf(url, companyNumber)) if err != nil { return nil, err } defer a.Body.Close() res := chResponse{} if err := json.NewDecoder(a.Body).Decode(&res); err != nil { return nil, err } return &res.PrimaryTopic, nil } <file_sep># Globire project The Global Business Registers (globire) project, as the name hopefully reveils, offers access to various business registers around the world in a unified way. In other words: One API for access to various registers. This repo is the Go implementation of the *Companies House URI service* ## Structure The structure of the project is to offer libraries for the individual registers and a general API which gives access to all the libraries through a standard format. Each library uses the various options that the registers offer, which can be an API offered by the particular register, Open Data or a combination thereof. ## State of this repo Alpha stage. Not recommended for production use. # Todo - [X] Company profile - [X] Convinience functions (HasTasks, etc) - [ ] Improve testing <file_sep>module github.com/globire/uk-ch-uri-go go 1.17
cf6a0e03ba3665356d0a3dc8f97fef9b250a0787
[ "Markdown", "Go Module", "Go" ]
5
Go
globire/uk-ch-uri-go
243d7becd17774f9687f5a1e1093eff216b76417
98c55dc48231232c0d59949294c3e30cb8813271
refs/heads/master
<file_sep>import buildsrc.CassandraLoader buildscript { repositories { mavenLocal() mavenCentral() jcenter() maven { url 'https://plugins.gradle.org/m2/' } maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } } } plugins { id 'idea' id 'io.ratpack.ratpack-groovy' version '1.3.0' id 'com.github.ksoichiro.build.info' version '0.1.5' id 'nebula.lint' version '0.22.0' } apply from: 'gradle/publishing.gradle' repositories { mavenLocal() mavenCentral() jcenter() maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } } String log4j(String module) { "org.apache.logging.log4j:log4j-${module}:2.4" } dependencies { compile ratpack.dependency('rx') compile 'com.github.rahulsom:rp-config:0.1-SNAPSHOT' compile 'smartthings:ratpack-cassandra-rx:+' compile 'smartthings:ratpack-cassandra-migrate:+' testCompile 'org.spockframework:spock-core:1.0-groovy-2.4' //testCompile 'org.cassandraunit:cassandra-unit:3.0.0.1' compile 'org.cassandraunit:cassandra-unit:3.0.0.1' testRuntime 'cglib:cglib-nodep:2.2.2' runtime log4j('slf4j-impl'), log4j('api'), log4j('core') runtime 'com.lmax:disruptor:3.3.2' } task('startCassandra') { doLast { CassandraLoader.instance.start('fry') tasks.findByName('run').finalizedBy('stopCassandra') } } task('stopCassandra') { doLast { CassandraLoader.instance.stop() } }<file_sep>create table claim ( id text, version int, date_created date, account_id text, facility_id text, submitter_claim_id text, member_id text, patient_id text, payee_id text, payer_id text, body blob, PRIMARY KEY (id, version) ); insert into claim (id, version, date_created, account_id, facility_id, submitter_claim_id, member_id, patient_id, payee_id, payer_id, body) values ('123', 1, 1368438171, '1.2.3.4', '1.2.3.4.1.6', '201610209', '13422', '13423', '2.16.4.8.32', '192.168.3.11.99.32', textAsBlob('This is a claim') ); <file_sep>nexusUsername = undefined nexusPassword = <PASSWORD> <file_sep>buildscript { repositories { maven { url 'https://plugins.gradle.org/m2/' } } dependencies { classpath 'net.saliman:gradle-cobertura-plugin:2.3.1' classpath 'javazoom:jlayer:1.0.1' } } apply plugin: net.saliman.gradle.plugin.cobertura.CoberturaPlugin apply plugin: 'codenarc' dependencies { codenarc 'org.gmetrics:GMetrics:0.7' codenarc 'net.sourceforge.cobertura:cobertura:2.1.1' codenarc 'org.codenarc:CodeNarc:0.25.2' } codenarc { configFile = file("gradle/codenarc/rulesMain.groovy") toolVersion = '0.25.2' reportFormat = System.getenv('BUILD_NUMBER') ? 'xml' : 'html' } codenarcTest { configFile = file('gradle/codenarc/rulesTest.groovy') } cobertura { coverageCheckBranchRate = 100 coverageCheckLineRate = 100 coverageCheckPackageBranchRate = 100 coverageCheckPackageLineRate = 100 coverageCheckTotalBranchRate = 100 coverageCheckTotalLineRate = 100 coverageCheckHaltOnFailure = true coverageFormats = ['xml', 'html'] coverageExcludes = [ '.*Exception', '.*Module', ] } tasks.findByName('check').dependsOn tasks.findByName('coberturaCheck') tasks.findByName('codenarcMain').mustRunAfter tasks.findByName('generateCoberturaReport') task('shame') { doLast { def coberturaXml = file("$buildDir/reports/cobertura/coverage.xml") if (coberturaXml.exists()) { def slurper = new XmlSlurper() slurper.setFeature('http://apache.org/xml/features/disallow-doctype-decl', false) slurper.setFeature('http://apache.org/xml/features/nonvalidating/load-external-dtd', false) def xml = slurper.parse(coberturaXml) def minCoverage = xml.packages.package.collect { Math.min(Double.parseDouble(it['@line-rate'].text()), Double.parseDouble(it['@branch-rate'].text())) }.min() if (minCoverage < 1.0) { def file = new File(rootDir, 'gradle/shame.mp3') assert file.isFile() file.withInputStream { stream -> new javazoom.jl.player.Player(stream).play() } } } else { logger.warn "Could not find $coberturaXml" } } } tasks.findByName('generateCoberturaReport').finalizedBy tasks.findByName('shame') <file_sep>buildscript { repositories { maven { url 'https://plugins.gradle.org/m2/' } } dependencies { classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.3' } } apply plugin: com.github.jengelman.gradle.plugins.shadow.ShadowPlugin apply plugin: 'maven-publish' group 'com.cds' def minor = System.getenv('BUILD_NUMBER') ?: '9999-SNAPSHOT' version = "1.${minor}" shadowJar { baseName = project.name classifier = '' } publishing { repositories { maven { url 'http://ti-nexus.rsc.humad.com:8081/nexus/content/repositories/eng-releases' credentials { username = nexusUsername password = <PASSWORD> } } } publications { shadow(MavenPublication) { from components.shadow artifactId = project.name } } }
1f29ece171f3bd0545c3042a2dcc343cdc1f34cc
[ "SQL", "INI", "Gradle" ]
5
Gradle
rahulsom/ratpackEmbedCassandra
548ea0d45048033970659ecd5be0f9fe457cb444
da0765251c7b845658f142e8198e2c4748393a01