text
stringlengths
27
775k
/* * Copyright (c) 2003-2015 Rony Shapiro <[email protected]>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ #include "../stdafx.h" #include "PWFilterLC.h" #include "PWFiltersDlg.h" #include "SetHistoryFiltersDlg.h" #include "SetPolicyFiltersDlg.h" #include "core/PWSFilters.h" #include "../resource3.h" #include "core/core.h" #include <algorithm> using namespace std; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif CPWFilterLC::CPWFilterLC() : m_pPWF(NULL), m_iType(0), m_pfilters(NULL), m_bInitDone(false), m_fwidth(-1), m_lwidth(-1), m_rowheight(-1), m_bSetFieldActive(false), m_bSetLogicActive(false), m_pComboBox(NULL), m_iItem(-1), m_numfilters(0), m_pFont(NULL), m_pwchTip(NULL), // Following 4 variables only used if "m_iType == DFTYPE_MAIN" m_bPWHIST_Set(false), m_bPOLICY_Set(false), m_GoodHistory(false), m_GoodPolicy(false) { m_crGrayText = ::GetSysColor(COLOR_GRAYTEXT); m_crWindow = ::GetSysColor(COLOR_WINDOW); m_crWindowText = ::GetSysColor(COLOR_WINDOWTEXT); m_crButtonFace = ::GetSysColor(COLOR_BTNFACE); m_crRedText = RGB(168, 0, 0); } CPWFilterLC::~CPWFilterLC() { // Do not delete filters, as they need to passed back to the caller m_pCheckImageList->DeleteImageList(); delete m_pCheckImageList; m_pImageList->DeleteImageList(); delete m_pImageList; delete m_pFont; delete m_pComboBox; delete m_pwchTip; } BEGIN_MESSAGE_MAP(CPWFilterLC, CListCtrl) //{{AFX_MSG_MAP(CPWFilterLC) ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, OnToolTipText) ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnCustomDraw) ON_WM_LBUTTONDOWN() //}}AFX_MSG_MAP END_MESSAGE_MAP() void CPWFilterLC::Init(CWnd *pParent, st_filters *pfilters, const int &filtertype) { m_pPWF = static_cast<CPWFiltersDlg *>(pParent); m_iType = filtertype; m_pfilters = pfilters; EnableToolTips(TRUE); const COLORREF crTransparent = RGB(192, 192, 192); CBitmap bitmap; BITMAP bm; bitmap.LoadBitmap(IDB_CHECKED); bitmap.GetBitmap(&bm); // should be 13 x 13 m_pCheckImageList = new CImageList; BOOL status = m_pCheckImageList->Create(bm.bmWidth, bm.bmHeight, ILC_MASK | ILC_COLOR, 2, 0); ASSERT(status != 0); m_pCheckImageList->Add(&bitmap, crTransparent); bitmap.DeleteObject(); bitmap.LoadBitmap(IDB_UNCHECKED); m_pCheckImageList->Add(&bitmap, crTransparent); bitmap.DeleteObject(); // Set CHeaderDtrl control ID m_pHeaderCtrl = GetHeaderCtrl(); m_pHeaderCtrl->SetDlgCtrlID(IDC_FILTERLC_HEADER); CString cs_text; cs_text = L" # "; InsertColumn(FLC_FILTER_NUMBER, cs_text); cs_text = L" ? "; InsertColumn(FLC_ENABLE_BUTTON, cs_text); cs_text = L" + "; InsertColumn(FLC_ADD_BUTTON, cs_text); cs_text = L" - "; InsertColumn(FLC_REM_BUTTON, cs_text); cs_text.LoadString(IDS_AND_OR); InsertColumn(FLC_LGC_COMBOBOX, cs_text); cs_text.LoadString(IDS_SELECTFIELD); InsertColumn(FLC_FLD_COMBOBOX, cs_text); cs_text.LoadString(IDS_CRITERIA_DESC); InsertColumn(FLC_CRITERIA_TEXT, cs_text); for (int i = 0; i <= FLC_CRITERIA_TEXT; i++) { SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER); } // Make +/- columns same size ('+' is bigger than '-') SetColumnWidth(FLC_REM_BUTTON, GetColumnWidth(FLC_ADD_BUTTON)); // Make checkbox, and button headers centered (and so their contents in the ListCtrl) LVCOLUMN lvc; lvc.mask = LVCF_FMT; lvc.fmt = LVCFMT_CENTER; SetColumn(FLC_FILTER_NUMBER, &lvc); SetColumn(FLC_ENABLE_BUTTON, &lvc); SetColumn(FLC_ADD_BUTTON, &lvc); SetColumn(FLC_REM_BUTTON, &lvc); switch (m_iType) { case DFTYPE_MAIN: // Set maximum number of filters per type and their own Control IDs m_FLD_ComboID = IDC_MFILTER_FLD_COMBOBOX; m_LGC_ComboID = IDC_MFILTER_LGC_COMBOBOX; m_pvfdata = &(m_pfilters->vMfldata); m_pnumactive = &(m_pfilters->num_Mactive); m_GoodHistory = m_pfilters->num_Hactive > 0; m_GoodPolicy = m_pfilters->num_Pactive > 0; break; case DFTYPE_PWHISTORY: // Set maximum number of filters per type and their own Control IDs m_FLD_ComboID = IDC_HFILTER_FLD_COMBOBOX; m_LGC_ComboID = IDC_HFILTER_LGC_COMBOBOX; m_pvfdata = &(m_pfilters->vHfldata); m_pnumactive = &(m_pfilters->num_Hactive); break; case DFTYPE_PWPOLICY: // Set maximum number of filters per type and their own Control IDs m_FLD_ComboID = IDC_PFILTER_FLD_COMBOBOX; m_LGC_ComboID = IDC_PFILTER_LGC_COMBOBOX; m_pvfdata = &(m_pfilters->vPfldata); m_pnumactive = &(m_pfilters->num_Pactive); break; default: ASSERT(0); } SetUpComboBoxData(); // Add dummy item to set column widths InsertItem(0, L"."); // FLC_ENABLE_BUTTON SetItemText(0, FLC_ADD_BUTTON, L"."); SetItemText(0, FLC_REM_BUTTON, L"."); SetItemText(0, FLC_LGC_COMBOBOX, L"."); SetItemText(0, FLC_FLD_COMBOBOX, L"."); SetItemText(0, FLC_CRITERIA_TEXT, L"."); SetItemData(0, FLC_CRITERIA_REDTXT | FLC_FLD_CBX_ENABLED); m_iItem = 0; st_FilterRow newfilter; m_pvfdata->push_back(newfilter); // Set up widths of columns with comboboxes - once for each combo DrawComboBox(FLC_FLD_COMBOBOX, -1); if (m_pComboBox) { m_pComboBox->DestroyWindow(); delete m_pComboBox; vWCFcbx_data.clear(); m_pComboBox = NULL; } DrawComboBox(FLC_LGC_COMBOBOX, -1); if (m_pComboBox) { m_pComboBox->DestroyWindow(); delete m_pComboBox; vWCFcbx_data.clear(); m_pComboBox = NULL; } // Remove dummy item DeleteItem(0); m_pvfdata->pop_back(); // If existing filters, set them up in the dialog DeleteFilters(); (*m_pnumactive) = 0; int i(0); DWORD_PTR dwData; vFilterRows::iterator Flt_iter; for (Flt_iter = m_pvfdata->begin(); Flt_iter != m_pvfdata->end(); Flt_iter++) { st_FilterRow &st_fldata = *Flt_iter; AddFilter_Controls(); if (st_fldata.bFilterActive) (*m_pnumactive)++; dwData = 0; if (st_fldata.bFilterActive) dwData |= FLC_FILTER_ENABLED; else dwData &= ~FLC_FILTER_ENABLED; if (st_fldata.ftype == FT_PWHIST) m_bPWHIST_Set = true; if (st_fldata.ftype == FT_POLICY) m_bPOLICY_Set = true; if (st_fldata.ftype != FT_INVALID) { dwData |= FLC_FLD_CBX_SET | FLC_FLD_CBX_ENABLED; SetField(i); SetLogic(i); vlast_ft[i] = st_fldata.ftype; vlast_mt[i] = st_fldata.mtype; vcbxChanged[i] = false; std::vector<st_Fcbxdata>::iterator Fcbxdata_iter; Fcbxdata_iter = std::find_if(vFcbx_data.begin(), vFcbx_data.end(), equal_ftype(st_fldata.ftype)); if (Fcbxdata_iter != vFcbx_data.end()) SetItemText(i, FLC_FLD_COMBOBOX, (*Fcbxdata_iter).cs_text); CString cs_criteria; if (st_fldata.ftype != FT_PWHIST && st_fldata.ftype != FT_POLICY && st_fldata.rule == PWSMatch::MR_INVALID) { cs_criteria.LoadString(IDS_NOTDEFINED); dwData |= FLC_CRITERIA_REDTXT; vCriteriaSet[i] = false; st_fldata.bFilterComplete = false; } else { cs_criteria = PWSFilters::GetFilterDescription(st_fldata).c_str(); dwData &= ~FLC_CRITERIA_REDTXT; vCriteriaSet[i] = true; st_fldata.bFilterComplete = true; } SetItemText(i, FLC_CRITERIA_TEXT, cs_criteria); SetColumnWidth(FLC_CRITERIA_TEXT, LVSCW_AUTOSIZE_USEHEADER); } if (i == 0) cs_text = L""; else cs_text = vLcbx_data[st_fldata.ltype == LC_AND ? 0 : 1].cs_text; SetItemText(i, FLC_LGC_COMBOBOX, cs_text); SetItemData(i, dwData); i++; } // Always show one filter! if (m_pvfdata->empty()) { AddFilter_Controls(); SetItemText(i, FLC_LGC_COMBOBOX, L""); // Add a new filter to vector st_FilterRow newfilter; m_pvfdata->push_back(newfilter); (*m_pnumactive)++; } ResetAndOr(); if (m_iType == DFTYPE_MAIN) m_pPWF->EnableDisableApply(); m_bInitDone = true; } BOOL CPWFilterLC::OnCommand(WPARAM wParam, LPARAM lParam) { // Since we are dynamically adding controls, we need to handle their // messages (i.e. user clicking on them) ourselves and not via "ON_BN_CLICKED" WORD wNotify = HIWORD(wParam); // notification message UINT nID = (UINT)LOWORD(wParam); // control identifier if (nID == m_FLD_ComboID || nID == m_LGC_ComboID) { switch (wNotify) { case CBN_SELENDOK: if (nID == m_FLD_ComboID) { m_bSetFieldActive = true; SetField(m_iItem); } else { m_bSetLogicActive = true; SetLogic(m_iItem); } return TRUE; case CBN_CLOSEUP: case CBN_KILLFOCUS: if (!m_bSetFieldActive && !m_bSetLogicActive) CloseKillCombo(); return TRUE; case CBN_DROPDOWN: if (!m_bSetFieldActive && !m_bSetLogicActive) DropDownCombo(nID); return TRUE; case CBN_SELENDCANCEL: if (nID == m_FLD_ComboID && !m_bSetFieldActive) CancelField(m_iItem); else if (nID == m_LGC_ComboID && !m_bSetLogicActive) CancelLogic(m_iItem); return TRUE; } } return CListCtrl::OnCommand(wParam, lParam); } int CPWFilterLC::AddFilter() { int newID = AddFilter_Controls(); // Check one was added if (newID < 0) return (-1); // Add a new filter to vector st_FilterRow newfilter; if (newID == 0) newfilter.ltype = LC_INVALID; else newfilter.ltype = LC_AND; m_pvfdata->push_back(newfilter); // Increase active number (*m_pnumactive)++; // Only if adding in the middle do we need to move things up and // reset the 'new' one if (m_iItem != newID - 1) { // Now move up any after us (only states - not actual pointers) // and reset the one immediately after use MoveUp(m_iItem); } ResetAndOr(); m_pPWF->UpdateStatusText(); return newID; } void CPWFilterLC::RemoveFilter() { ASSERT(m_iItem >= 0); // Main Filters dialog need to handle History/Policy before calling this if (m_iType == DFTYPE_MAIN) { st_FilterRow &st_fldata = m_pvfdata->at(m_iItem); if (m_bPWHIST_Set && st_fldata.ftype == FT_PWHIST) { // We are deleting the History so put option back in other Comboboxes m_bPWHIST_Set = false; } else if (m_bPOLICY_Set && st_fldata.ftype == FT_POLICY) { // We are deleting the Policy so put option back in other Comboboxes m_bPOLICY_Set = false; } } if (m_iItem == 0 && m_pvfdata->size() == 1) { // Don't remove the one and only filter - just reset it ResetFilter(0); // Set active counter & number of filters (*m_pnumactive) = 1; m_numfilters = 1; } else if ((m_iItem + 1) == (int)m_pvfdata->size()) { // Last entry - is relatively easy! // Decrement active filters if necessary if (m_pvfdata->at(m_iItem).bFilterActive) (*m_pnumactive)--; // Decrement number of filters m_numfilters--; // Remove Control windows, controls and filterdata RemoveLast(); } else { // Now remove one that is "not the only one" nor "the last one". if (m_pvfdata->at(m_iItem).bFilterActive) (*m_pnumactive)--; // Move all the information down one and then delete the last // Decrement active filters if necessary MoveDown(); // Decrement number of filters m_numfilters--; // Now remove the end one RemoveLast(); } ResetAndOr(); m_pPWF->UpdateStatusText(); } void CPWFilterLC::ResetFilter(const int num) { // Mustn't remove first and ONLY one - just reinitialise the controls. // Enable filter, disable GetCriterion button, set AND, unset Combobox selection DWORD_PTR dwData; dwData = FLC_CRITERIA_REDTXT | FLC_FILTER_ENABLED; SetItemData(num, dwData); CString cs_text(MAKEINTRESOURCE(IDS_PICKFIELD)); SetItemText(num, FLC_FLD_COMBOBOX, cs_text); vlast_ft[num] = FT_INVALID; vlast_mt[num] = PWSMatch::MT_INVALID; vcbxChanged[num] = true; vCriteriaSet[num] = false; vAddPresent[num] = false; // Make sure entry is pristine m_pvfdata->at(num).Empty(); if (num == 0) { m_pvfdata->at(num).ltype = LC_INVALID; SetItemText(num, FLC_LGC_COMBOBOX, L""); } else { m_pvfdata->at(num).ltype = LC_AND; SetItemText(num, FLC_LGC_COMBOBOX, vLcbx_data[0].cs_text); } // Update criterion text and window text CString cs_criteria(MAKEINTRESOURCE(IDS_NOTDEFINED)); SetItemText(num, FLC_CRITERIA_TEXT, cs_criteria); SetColumnWidth(FLC_CRITERIA_TEXT, LVSCW_AUTOSIZE_USEHEADER); } void CPWFilterLC::RemoveLast() { int num = GetItemCount(); ASSERT(num > 0); vlast_ft.pop_back(); vlast_mt.pop_back(); vcbxChanged.pop_back(); vCriteriaSet.pop_back(); vAddPresent.pop_back(); // Remove filter m_pvfdata->pop_back(); // Remove ListCtrl entry DeleteItem(num - 1); } int CPWFilterLC::AddFilter_Controls() { // First add filter at the end of current filters CString cs_text; CRect rect; int newID = m_numfilters; cs_text.Format(L"%d", newID + 1); InsertItem(newID, cs_text); // FLC_FILTER_NUMBER SetItemText(newID, FLC_ENABLE_BUTTON, L""); SetItemText(newID, FLC_ADD_BUTTON, L"+"); SetItemText(newID, FLC_REM_BUTTON, L"-"); cs_text.LoadString(IDSC_AND); SetItemText(newID, FLC_LGC_COMBOBOX, cs_text); cs_text.LoadString(IDS_PICKFIELD); SetItemText(newID, FLC_FLD_COMBOBOX, cs_text); // set status in cell cs_text.LoadString(IDS_NOTDEFINED); SetItemText(newID, FLC_CRITERIA_TEXT, cs_text); SetColumnWidth(FLC_CRITERIA_TEXT, LVSCW_AUTOSIZE_USEHEADER); SetItemData(newID, FLC_CRITERIA_REDTXT | FLC_FILTER_ENABLED); vlast_ft.push_back(FT_INVALID); vlast_mt.push_back(PWSMatch::MT_INVALID); vcbxChanged.push_back(true); vCriteriaSet.push_back(false); vAddPresent.push_back(false); // Increase total number m_numfilters++; return newID; } void CPWFilterLC::MoveDown() { // Move "states" down. i.e. deleting '1' means // '0' unchanged; '2'->'1'; '3'->'2'; '4'->'3' etc. DWORD_PTR dwData; CString cs_text; for (int i = m_iItem; i < m_numfilters - 1; i++) { cs_text.Format(L"%d", i + 1); SetItemText(i, FLC_FILTER_NUMBER, cs_text); cs_text = GetItemText(i + 1, FLC_FLD_COMBOBOX); SetItemText(i, FLC_FLD_COMBOBOX, cs_text); cs_text = GetItemText(i + 1, FLC_LGC_COMBOBOX); SetItemText(i, FLC_LGC_COMBOBOX, cs_text); cs_text = GetItemText(i + 1, FLC_CRITERIA_TEXT); SetItemText(i, FLC_CRITERIA_TEXT, cs_text); SetColumnWidth(FLC_CRITERIA_TEXT, LVSCW_AUTOSIZE_USEHEADER); // Data field contains flags for enabled state and text colour dwData = GetItemData(i + 1); SetItemData(i, dwData); vlast_ft[i] = vlast_ft[i + 1]; vlast_mt[i] = vlast_mt[i + 1]; vcbxChanged[i] = vcbxChanged[i + 1]; vCriteriaSet[i] = vCriteriaSet[i + 1]; vAddPresent[i] = vAddPresent[i + 1]; m_pvfdata->at(i) = m_pvfdata->at(i + 1); } } void CPWFilterLC::MoveUp(const int nAfter) { // Move up. i.e. adding after '1' means // '0' & '1' unchanged; '5'->'6'; '4'->'5'; '3'->'4'; // '2' then reset. // Move "states" up one; can't change pointers CString cs_text; DWORD_PTR dwData; for (int i = m_numfilters - 2; i > nAfter; i--) { cs_text.Format(L"%d", i + 2); SetItemText(i + 1, FLC_FILTER_NUMBER, cs_text); cs_text = GetItemText(i, FLC_FLD_COMBOBOX); SetItemText(i + 1, FLC_FLD_COMBOBOX, cs_text); cs_text = GetItemText(i + 1, FLC_LGC_COMBOBOX); SetItemText(i, FLC_LGC_COMBOBOX, cs_text); cs_text = GetItemText(i, FLC_CRITERIA_TEXT); SetItemText(i + 1, FLC_CRITERIA_TEXT, cs_text); SetColumnWidth(FLC_CRITERIA_TEXT, LVSCW_AUTOSIZE_USEHEADER); // Data field contains flags for enabled state and text colour dwData = GetItemData(i); SetItemData(i + 1, dwData); vlast_ft[i + 1] = vlast_ft[i]; vlast_mt[i + 1] = vlast_mt[i]; vcbxChanged[i + 1] = vcbxChanged[i]; vCriteriaSet[i + 1] = vCriteriaSet[i]; vAddPresent[i + 1] = vAddPresent[i]; m_pvfdata->at(i + 1) = m_pvfdata->at(i); } // Now reset the 'new' one. ResetFilter(nAfter + 1); } void CPWFilterLC::ResetAndOr() { // Ensure And/Or enabled DWORD_PTR dwData; for (int i = 1; i < GetItemCount(); i++) { dwData = GetItemData(i); dwData |= FLC_LGC_CBX_ENABLED; SetItemData(i, dwData); } // Except for the first one SetItemText(0, FLC_LGC_COMBOBOX, L""); dwData = GetItemData(0); dwData &= ~FLC_LGC_CBX_ENABLED; SetItemData(0, dwData); } void CPWFilterLC::DeleteFilters() { if (vlast_ft.empty()) return; // Clear the other vectors vlast_ft.clear(); vlast_mt.clear(); vcbxChanged.clear(); vCriteriaSet.clear(); vAddPresent.clear(); // Clear filter data m_pvfdata->clear(); // Zero counters *m_pnumactive = 0; m_numfilters = 0; } FieldType CPWFilterLC::EnableCriteria() { // User clicked "Enable/Disable" filter checkbox ASSERT(m_iItem >= 0); // Get offset into vector of controls st_FilterRow &st_fldata = m_pvfdata->at(m_iItem); // Did they enable or disable the filter? bool bIsChecked = !st_fldata.bFilterActive; st_fldata.bFilterActive = bIsChecked; // Check, when activating me, if there are any active filters before us // If not, we won't show the logic enable the And/Or logic value // This is a real pain! int j(0); for (int i = 0; i < (int)m_pvfdata->size(); i++) { if (m_pvfdata->at(i).bFilterActive) { DWORD_PTR dwData2 = GetItemData(i); dwData2 &= ~FLC_LGC_CBX_ENABLED; SetItemData(i, dwData2); j = i; break; } } for (int i = j + 1; i < (int)m_pvfdata->size(); i++) { if (m_pvfdata->at(i).bFilterActive) { DWORD_PTR dwData2 = GetItemData(i); dwData2 |= FLC_LGC_CBX_ENABLED; SetItemData(i, dwData2); } } DWORD_PTR dwData = GetItemData(m_iItem); FieldType ft = st_fldata.ftype; // If user (had) selected an entry, get its field type // If not, don't let them try and select a criterion if ((ft != FT_INVALID) && bIsChecked) dwData |= FLC_FLD_CBX_ENABLED; else dwData &= ~FLC_FLD_CBX_ENABLED; // Set state of this filter and adjust active count if (bIsChecked) { // Now active dwData |= FLC_FILTER_ENABLED; st_fldata.bFilterActive = true; (*m_pnumactive)++; } else { // Now inactive dwData &= ~FLC_FILTER_ENABLED; st_fldata.bFilterActive = false; (*m_pnumactive)--; } SetItemData(m_iItem, dwData); CString cs_text(MAKEINTRESOURCE(IDS_PICKFIELD)); if (m_iType == DFTYPE_MAIN) { if (st_fldata.bFilterActive) { if (ft == FT_PWHIST) { if (!m_bPWHIST_Set) m_bPWHIST_Set = true; else { SetItemText(m_iItem, FLC_FLD_COMBOBOX, cs_text); st_fldata.ftype = FT_INVALID; } } if (ft == FT_POLICY) { if (!m_bPOLICY_Set) m_bPOLICY_Set = true; else { SetItemText(m_iItem, FLC_FLD_COMBOBOX, cs_text); st_fldata.ftype = FT_INVALID; } } } else { if (m_bPWHIST_Set && ft == FT_PWHIST) m_bPWHIST_Set = false; if (m_bPOLICY_Set && ft == FT_POLICY) m_bPOLICY_Set = false; } m_pPWF->EnableDisableApply(); } // Update dialog window text m_pPWF->UpdateStatusText(); return ft; } bool CPWFilterLC::SetField(const int iItem) { // User has selected field bool retval(false); // Set focus to main window in case user does page up/down next // so that it changes the scoll bar not the value in this // ComboBox GetParent()->SetFocus(); // Get offset into vector of controls st_FilterRow &st_fldata = m_pvfdata->at(iItem); FieldType ft(FT_INVALID); // m_pComboBox is NULL during inital setup if (m_pComboBox) { int iSelect = m_pComboBox->GetCurSel(); if (iSelect != CB_ERR) { ft = (FieldType)m_pComboBox->GetItemData(iSelect); } st_fldata.ftype = ft; } else { ft = st_fldata.ftype; } CString cs_text(MAKEINTRESOURCE(IDS_PICKFIELD)); if (ft != FT_INVALID) { std::vector<st_Fcbxdata>::iterator Fcbxdata_iter; Fcbxdata_iter = std::find_if(vWCFcbx_data.begin(), vWCFcbx_data.end(), equal_ftype(ft)); if (Fcbxdata_iter != vWCFcbx_data.end()) cs_text = (*Fcbxdata_iter).cs_text; } SetItemText(iItem, FLC_FLD_COMBOBOX, cs_text); DWORD_PTR dwData = GetItemData(iItem); if (ft == FT_INVALID) { // Oh no they haven't! dwData &= ~FLC_FLD_CBX_SET; SetItemData(iItem, dwData); goto delete_combo; } else { dwData |= (FLC_FLD_CBX_ENABLED | FLC_FLD_CBX_SET); } // Get related fieldtype PWSMatch::MatchType mt(PWSMatch::MT_INVALID); // Default - do not add 'is present'/'is not present' to the match dialog bool bAddPresent(false); // Now get associated match type switch (m_iType) { case DFTYPE_MAIN: switch (ft) { case FT_GROUPTITLE: case FT_TITLE: // Title MUST be present - no need to add that check mt = PWSMatch::MT_STRING; break; case FT_PASSWORD: // Password MUST be present - no need to add that check mt = PWSMatch::MT_PASSWORD; break; case FT_PASSWORDLEN: mt = PWSMatch::MT_INTEGER; break; case FT_GROUP: case FT_USER: case FT_NOTES: case FT_URL: case FT_AUTOTYPE: case FT_RUNCMD: case FT_EMAIL: case FT_SYMBOLS: case FT_POLICYNAME: bAddPresent = true; mt = PWSMatch::MT_STRING; break; case FT_DCA: case FT_SHIFTDCA: mt = PWSMatch::MT_DCA; break; case FT_CTIME: case FT_PMTIME: case FT_ATIME: case FT_XTIME: case FT_RMTIME: bAddPresent = true; mt = PWSMatch::MT_DATE; break; case FT_PWHIST: // 'Add Present' doesn't make sense here - see sub-dialog mt = PWSMatch::MT_PWHIST; break; case FT_POLICY: // 'Add Present' doesn't make sense here - see sub-dialog mt = PWSMatch::MT_POLICY; break; case FT_XTIME_INT: bAddPresent = true; mt = PWSMatch::MT_INTEGER; break; case FT_PROTECTED: m_fbool.m_bt = CFilterBoolDlg::BT_IS; mt = PWSMatch::MT_BOOL; break; case FT_KBSHORTCUT: // 'Add Present' not needed - bool match m_fbool.m_bt = CFilterBoolDlg::BT_PRESENT; mt = PWSMatch::MT_BOOL; break; case FT_UNKNOWNFIELDS: // 'Add Present' not needed - bool match m_fbool.m_bt = CFilterBoolDlg::BT_PRESENT; mt = PWSMatch::MT_BOOL; break; case FT_ENTRYTYPE: // Entrytype is an entry attribute and MUST be present // - no need to add that check mt = PWSMatch::MT_ENTRYTYPE; break; case FT_ENTRYSTATUS: // Entrystatus is an entry attribute and MUST be present // - no need to add that check mt = PWSMatch::MT_ENTRYSTATUS; break; case FT_ENTRYSIZE: // Entrysize is an entry attribute and MUST be present // - no need to add that check mt = PWSMatch::MT_ENTRYSIZE; break; default: ASSERT(0); } break; case DFTYPE_PWHISTORY: switch (ft) { case HT_PRESENT: // 'Add Present' not needed - bool match m_fbool.m_bt = CFilterBoolDlg::BT_PRESENT; mt = PWSMatch::MT_BOOL; break; case HT_ACTIVE: // 'Add Present' not needed - bool match m_fbool.m_bt = CFilterBoolDlg::BT_ACTIVE; mt = PWSMatch::MT_BOOL; break; case HT_NUM: case HT_MAX: // 'Add Present' doesn't make sense here mt = PWSMatch::MT_INTEGER; break; case HT_CHANGEDATE: // 'Add Present' doesn't make sense here mt = PWSMatch::MT_DATE; break; case HT_PASSWORDS: // 'Add Present' doesn't make sense here mt = PWSMatch::MT_PASSWORD; break; default: ASSERT(0); } break; case DFTYPE_PWPOLICY: switch (ft) { case PT_PRESENT: // 'Add Present' not needed - bool match m_fbool.m_bt = CFilterBoolDlg::BT_PRESENT; mt = PWSMatch::MT_BOOL; break; case PT_EASYVISION: case PT_PRONOUNCEABLE: case PT_HEXADECIMAL: // 'Add Present' not needed - bool match m_fbool.m_bt = CFilterBoolDlg::BT_SET; mt = PWSMatch::MT_BOOL; break; case PT_LENGTH: case PT_LOWERCASE: case PT_UPPERCASE: case PT_DIGITS: case PT_SYMBOLS: // 'Add Present' doesn't make sense here mt = PWSMatch::MT_INTEGER; break; default: ASSERT(0); } break; default: ASSERT(0); } // Save if user has just re-selected previous selection - i.e. no change if (vlast_ft[iItem] != ft || vlast_mt[iItem] != mt) { vcbxChanged[iItem] = true; vCriteriaSet[iItem] = false; st_fldata.bFilterComplete = false; } else vcbxChanged[iItem] = false; vAddPresent[iItem] = bAddPresent; if (m_iType == DFTYPE_MAIN) { if (vlast_ft[iItem] == FT_PWHIST && ft != FT_PWHIST) m_bPWHIST_Set = false; else if (ft == FT_PWHIST) m_bPWHIST_Set = true; if (vlast_ft[iItem] == FT_POLICY && ft != FT_POLICY) m_bPOLICY_Set = false; else if (ft == FT_POLICY) m_bPOLICY_Set = true; } // Now we can update the last selected field vlast_ft[iItem] = ft; // Save last match type now vlast_mt[iItem] = mt; if (mt == PWSMatch::MT_INVALID) { dwData &= ~FLC_FLD_CBX_ENABLED; vCriteriaSet[iItem] = false; st_fldata.bFilterComplete = false; } // If criterion not set, update static text message to user if (vCriteriaSet[iItem] == false) { CString cs_criteria(MAKEINTRESOURCE(IDS_NOTDEFINED)); dwData |= FLC_CRITERIA_REDTXT; SetItemText(iItem, FLC_CRITERIA_TEXT, cs_criteria); SetColumnWidth(FLC_CRITERIA_TEXT, LVSCW_AUTOSIZE_USEHEADER); } if (mt == PWSMatch::MT_INVALID) { SetItemData(iItem, dwData); goto delete_combo; } dwData |= FLC_FLD_CBX_ENABLED; SetItemData(iItem, dwData); st_fldata.mtype = mt; st_fldata.ftype = ft; retval = true; delete_combo: if (m_pComboBox) { m_pComboBox->DestroyWindow(); delete m_pComboBox; vWCFcbx_data.clear(); m_pComboBox = NULL; } m_bSetFieldActive = false; return retval; } void CPWFilterLC::CancelField(const int iItem) { // User has selected field // Set focus to main window in case user does page up/down next // so that it changes the scoll bar not the value in this // ComboBox GetParent()->SetFocus(); // Get offset into vector of controls st_FilterRow &st_fldata = m_pvfdata->at(iItem); FieldType ft(st_fldata.ftype); CString cs_text(MAKEINTRESOURCE(IDS_PICKFIELD)); if (ft != FT_INVALID) { std::vector<st_Fcbxdata>::iterator Fcbxdata_iter; Fcbxdata_iter = std::find_if(vWCFcbx_data.begin(), vWCFcbx_data.end(), equal_ftype(ft)); if (Fcbxdata_iter != vWCFcbx_data.end()) cs_text = (*Fcbxdata_iter).cs_text; } SetItemText(iItem, FLC_FLD_COMBOBOX, cs_text); // m_pComboBox is NULL during inital setup if (m_pComboBox) { m_pComboBox->DestroyWindow(); delete m_pComboBox; vWCFcbx_data.clear(); m_pComboBox = NULL; } return; } void CPWFilterLC::SetLogic(const int iItem) { CString cs_text(L""); if (iItem == 0) { SetItemText(iItem, FLC_LGC_COMBOBOX, cs_text); goto delete_combo; } // Get offset into vector of controls st_FilterRow &st_fldata = m_pvfdata->at(iItem); LogicConnect lt(st_fldata.ltype); // m_pComboBox is NULL during inital setup if (m_pComboBox) { int iSelect = m_pComboBox->GetCurSel(); if (iSelect != CB_ERR) { lt = (LogicConnect)m_pComboBox->GetItemData(iSelect); } m_pvfdata->at(iItem).ltype = lt; } cs_text = vLcbx_data[0].cs_text; if (lt != LC_INVALID) { std::vector<st_Lcbxdata>::iterator Lcbxdata_iter; Lcbxdata_iter = std::find_if(vLcbx_data.begin(), vLcbx_data.end(), equal_ltype(lt)); if (Lcbxdata_iter != vLcbx_data.end()) cs_text = (*Lcbxdata_iter).cs_text; } SetItemText(iItem, FLC_LGC_COMBOBOX, cs_text); delete_combo: if (m_pComboBox) { m_pComboBox->DestroyWindow(); delete m_pComboBox; vWCFcbx_data.clear(); m_pComboBox = NULL; } m_bSetLogicActive = false; } void CPWFilterLC::CancelLogic(const int iItem) { CString cs_text(L""); // Get offset into vector of controls if (iItem == 0) { SetItemText(iItem, FLC_LGC_COMBOBOX, cs_text); goto delete_combo; } st_FilterRow &st_fldata = m_pvfdata->at(iItem); LogicConnect lt(st_fldata.ltype); cs_text = vLcbx_data[0].cs_text; if (lt != LC_INVALID) { std::vector<st_Lcbxdata>::iterator Lcbxdata_iter; Lcbxdata_iter = std::find_if(vLcbx_data.begin(), vLcbx_data.end(), equal_ltype(lt)); if (Lcbxdata_iter != vLcbx_data.end()) cs_text = (*Lcbxdata_iter).cs_text; } SetItemText(iItem, FLC_LGC_COMBOBOX, cs_text); delete_combo: // m_pComboBox is NULL during inital setup if (m_pComboBox) { m_pComboBox->DestroyWindow(); delete m_pComboBox; vWCFcbx_data.clear(); m_pComboBox = NULL; } } void CPWFilterLC::CloseKillCombo() { // Remove combo if (m_pComboBox) { m_pComboBox->DestroyWindow(); delete m_pComboBox; vWCFcbx_data.clear(); m_pComboBox = NULL; } } void CPWFilterLC::DropDownCombo(const UINT nID) { CString cs_text; int index(-1); if (nID == m_FLD_ComboID) { FieldType ft = m_pvfdata->at(m_iItem).ftype; cs_text.LoadString(IDS_PICKFIELD); if (ft != FT_INVALID) { std::vector<st_Fcbxdata>::iterator Fcbxdata_iter; Fcbxdata_iter = std::find_if(vWCFcbx_data.begin(), vWCFcbx_data.end(), equal_ftype(ft)); if (Fcbxdata_iter != vWCFcbx_data.end()) { cs_text = (*Fcbxdata_iter).cs_text; index = (int)(Fcbxdata_iter - vWCFcbx_data.begin()); } } SetItemText(m_iItem, FLC_FLD_COMBOBOX, cs_text); } else { LogicConnect lt = m_pvfdata->at(m_iItem).ltype; index = (lt == LC_AND) ? 0 : 1; cs_text.LoadString(lt == LC_AND ? IDSC_AND : IDSC_OR); SetItemText(m_iItem, FLC_LGC_COMBOBOX, cs_text); } m_pComboBox->SetCurSel(index); } bool CPWFilterLC::GetCriterion() { // User has already enabled the filter and selected the field type // Now get the criteron ASSERT(m_iItem >= 0); // Get offset into vector of controls INT_PTR rc(IDCANCEL); st_FilterRow &st_fldata = m_pvfdata->at(m_iItem); // Get Text const CString cs_selected = GetItemText(m_iItem, FLC_LGC_COMBOBOX); // Save fieldtype (need it when we reset the filter data) const FieldType ft = st_fldata.ftype; bool b_good(false); LogicConnect ltype(st_fldata.ltype); // Now go display the correct match dialog switch (st_fldata.mtype) { case PWSMatch::MT_STRING: m_fstring.m_add_present = vAddPresent[m_iItem]; m_fstring.m_title = cs_selected; if (!vcbxChanged[m_iItem] && st_fldata.rule != PWSMatch::MR_INVALID) { m_fstring.m_rule = st_fldata.rule; m_fstring.m_string = st_fldata.fstring.c_str(); m_fstring.m_case = st_fldata.fcase ? BST_CHECKED : BST_UNCHECKED; } else { m_fstring.m_rule = PWSMatch::MR_INVALID; } m_fstring.SetSymbol(st_fldata.ftype == FT_SYMBOLS); rc = m_fstring.DoModal(); if (rc == IDOK) { st_fldata.Empty(); st_fldata.bFilterActive = true; st_fldata.mtype = PWSMatch::MT_STRING; st_fldata.ftype = ft; st_fldata.rule = m_fstring.m_rule; st_fldata.fstring = m_fstring.m_string; if (st_fldata.rule == PWSMatch::MR_PRESENT || st_fldata.rule == PWSMatch::MR_NOTPRESENT) st_fldata.fcase = false; else st_fldata.fcase = (m_fstring.m_case == BST_CHECKED); b_good = true; } break; case PWSMatch::MT_PASSWORD: m_fpswd.m_title = cs_selected; if (!vcbxChanged[m_iItem] && st_fldata.rule != PWSMatch::MR_INVALID) { m_fpswd.m_rule = st_fldata.rule; m_fpswd.m_string = st_fldata.fstring.c_str(); m_fpswd.m_case = st_fldata.fcase ? BST_CHECKED : BST_UNCHECKED; m_fpswd.m_num1 = st_fldata.fnum1; } else { m_fpswd.m_rule = PWSMatch::MR_INVALID; } rc = m_fpswd.DoModal(); if (rc == IDOK) { st_fldata.Empty(); st_fldata.bFilterActive = true; st_fldata.mtype = PWSMatch::MT_PASSWORD; st_fldata.ftype = ft; st_fldata.rule = m_fpswd.m_rule; st_fldata.fstring = LPCWSTR(m_fpswd.m_string); st_fldata.fcase = (m_fpswd.m_case == BST_CHECKED); if (st_fldata.rule != PWSMatch::MR_WILLEXPIRE) st_fldata.fnum1 = 0; else st_fldata.fnum1 = m_fpswd.m_num1; b_good = true; } break; case PWSMatch::MT_INTEGER: m_finteger.m_add_present = vAddPresent[m_iItem]; m_finteger.m_title = cs_selected; if (!vcbxChanged[m_iItem] && st_fldata.rule != PWSMatch::MR_INVALID) { m_finteger.m_rule = st_fldata.rule; m_finteger.m_num1 = st_fldata.fnum1; m_finteger.m_num2 = st_fldata.fnum2; } else { m_finteger.m_rule = PWSMatch::MR_INVALID; } rc = m_finteger.DoModal(); if (rc == IDOK) { st_fldata.Empty(); st_fldata.bFilterActive = true; st_fldata.mtype = PWSMatch::MT_INTEGER; st_fldata.ftype = ft; st_fldata.rule = m_finteger.m_rule; st_fldata.fnum1 = m_finteger.m_num1; st_fldata.fnum2 = m_finteger.m_num2; b_good = true; } break; case PWSMatch::MT_DATE: m_fdate.m_add_present = vAddPresent[m_iItem]; m_fdate.m_title = cs_selected; if (!vcbxChanged[m_iItem] && st_fldata.rule != PWSMatch::MR_INVALID) { m_fdate.m_rule = st_fldata.rule; m_fdate.m_datetype = st_fldata.fdatetype; m_fdate.m_time_t1 = st_fldata.fdate1; m_fdate.m_time_t2 = st_fldata.fdate2; m_fdate.m_num1 = st_fldata.fnum1; m_fdate.m_num2 = st_fldata.fnum2; } else { m_fdate.m_rule = PWSMatch::MR_INVALID; } m_fdate.SetFieldType(ft); // Only FT_XTIME is allowed a future time rc = m_fdate.DoModal(); if (rc == IDOK) { st_fldata.Empty(); st_fldata.bFilterActive = true; st_fldata.mtype = PWSMatch::MT_DATE; st_fldata.ftype = ft; st_fldata.rule = m_fdate.m_rule; st_fldata.fdatetype = m_fdate.m_datetype; st_fldata.fdate1 = m_fdate.m_time_t1; st_fldata.fdate2 = m_fdate.m_time_t2; st_fldata.fnum1 = m_fdate.m_num1; st_fldata.fnum2 = m_fdate.m_num2; b_good = true; } break; case PWSMatch::MT_PWHIST: { st_filters filters(*m_pfilters); CSetHistoryFiltersDlg fhistory(this, &filters, m_pPWF->GetFiltername()); rc = fhistory.DoModal(); if (rc == IDOK) { st_fldata.Empty(); st_fldata.bFilterActive = true; st_fldata.mtype = PWSMatch::MT_PWHIST; st_fldata.ftype = ft; m_pfilters->num_Hactive = filters.num_Hactive; m_pfilters->vHfldata = filters.vHfldata; m_bPWHIST_Set = true; m_pPWF->UpdateStatusText(); } m_GoodHistory = m_pfilters->num_Hactive > 0; b_good = m_GoodHistory; } break; case PWSMatch::MT_POLICY: { st_filters filters(*m_pfilters); CSetPolicyFiltersDlg fpolicy(this, &filters, m_pPWF->GetFiltername()); rc = fpolicy.DoModal(); if (rc == IDOK) { st_fldata.Empty(); st_fldata.bFilterActive = true; st_fldata.mtype = PWSMatch::MT_POLICY; st_fldata.ftype = ft; m_pfilters->num_Pactive = filters.num_Pactive; m_pfilters->vPfldata = filters.vPfldata; m_bPOLICY_Set = true; m_pPWF->UpdateStatusText(); } m_GoodPolicy = m_pfilters->num_Pactive > 0; b_good = m_GoodPolicy; } break; case PWSMatch::MT_BOOL: m_fbool.m_title = cs_selected; if (!vcbxChanged[m_iItem] && st_fldata.rule != PWSMatch::MR_INVALID) { m_fbool.m_rule = st_fldata.rule; } else { m_fbool.m_rule = PWSMatch::MR_INVALID; } rc = m_fbool.DoModal(); if (rc == IDOK) { st_fldata.Empty(); st_fldata.bFilterActive = true; st_fldata.mtype = PWSMatch::MT_BOOL; st_fldata.ftype = ft; st_fldata.rule = m_fbool.m_rule; b_good = true; } break; case PWSMatch::MT_ENTRYTYPE: m_fentry.m_title = cs_selected; if (!vcbxChanged[m_iItem] && st_fldata.rule != PWSMatch::MR_INVALID) { m_fentry.m_rule = st_fldata.rule; m_fentry.m_etype = st_fldata.etype; } else { m_fentry.m_rule = PWSMatch::MR_INVALID; } rc = m_fentry.DoModal(); if (rc == IDOK) { st_fldata.Empty(); st_fldata.bFilterActive = true; st_fldata.mtype = PWSMatch::MT_ENTRYTYPE; st_fldata.ftype = ft; st_fldata.rule = m_fentry.m_rule; st_fldata.etype = m_fentry.m_etype; b_good = true; } break; case PWSMatch::MT_DCA: case PWSMatch::MT_SHIFTDCA: m_fDCA.m_title = cs_selected; if (!vcbxChanged[m_iItem] && st_fldata.rule != PWSMatch::MR_INVALID) { m_fDCA.m_rule = st_fldata.rule; m_fDCA.m_DCA = st_fldata.fdca; } else { m_fDCA.m_rule = PWSMatch::MR_INVALID; } rc = m_fDCA.DoModal(); if (rc == IDOK) { st_fldata.Empty(); st_fldata.bFilterActive = true; st_fldata.mtype = PWSMatch::MT_DCA; st_fldata.ftype = ft; st_fldata.rule = m_fDCA.m_rule; st_fldata.fdca = m_fDCA.m_DCA; b_good = true; } break; case PWSMatch::MT_ENTRYSTATUS: m_fstatus.m_title = cs_selected; if (!vcbxChanged[m_iItem] && st_fldata.rule != PWSMatch::MR_INVALID) { m_fstatus.m_rule = st_fldata.rule; m_fstatus.m_estatus = st_fldata.estatus; } else { m_fstatus.m_rule = PWSMatch::MR_INVALID; } rc = m_fstatus.DoModal(); if (rc == IDOK) { st_fldata.Empty(); st_fldata.bFilterActive = true; st_fldata.mtype = PWSMatch::MT_ENTRYSTATUS; st_fldata.ftype = ft; st_fldata.rule = m_fstatus.m_rule; st_fldata.estatus = m_fstatus.m_estatus; b_good = true; } break; case PWSMatch::MT_ENTRYSIZE: m_fsize.m_title = cs_selected; if (!vcbxChanged[m_iItem] && st_fldata.rule != PWSMatch::MR_INVALID) { m_fsize.m_rule = st_fldata.rule; m_fsize.m_unit = st_fldata.funit; m_fsize.m_size1 = st_fldata.fnum1 >> (m_fsize.m_unit * 10); m_fsize.m_size2 = st_fldata.fnum2 >> (m_fsize.m_unit * 10); } else { m_fsize.m_rule = PWSMatch::MR_INVALID; } rc = m_fsize.DoModal(); if (rc == IDOK) { st_fldata.Empty(); st_fldata.bFilterActive = true; st_fldata.mtype = PWSMatch::MT_ENTRYSIZE; st_fldata.ftype = ft; st_fldata.rule = m_fsize.m_rule; st_fldata.funit = m_fsize.m_unit; st_fldata.fnum1 = m_fsize.m_size1 << (m_fsize.m_unit * 10); st_fldata.fnum2 = m_fsize.m_size2 << (m_fsize.m_unit * 10); b_good = true; } break; default: ASSERT(0); } // Update static text if user has selected a new criterion if (rc == IDOK) { st_fldata.ltype = ltype; CString cs_criteria; DWORD_PTR dwData; dwData = GetItemData(m_iItem); if (b_good) { cs_criteria = PWSFilters::GetFilterDescription(st_fldata).c_str(); dwData &= ~FLC_CRITERIA_REDTXT; vcbxChanged[m_iItem] = false; vCriteriaSet[m_iItem] = true; st_fldata.bFilterComplete = true; } else { cs_criteria.LoadString(IDS_NOTDEFINED); dwData |= FLC_CRITERIA_REDTXT; } SetItemData(m_iItem, dwData); SetItemText(m_iItem, FLC_CRITERIA_TEXT, cs_criteria); SetColumnWidth(FLC_CRITERIA_TEXT, LVSCW_AUTOSIZE_USEHEADER); m_pPWF->UpdateDialogMaxWidth(); } return true; } void CPWFilterLC::SetUpComboBoxData() { // Set up the Field selction Combobox // NOTE: The ComboBox strings are NOT sorted by design ! if (vLcbx_data.empty()) { st_Lcbxdata stl; stl.cs_text.LoadString(IDSC_AND); stl.ltype = LC_AND; vLcbx_data.push_back(stl); stl.cs_text.LoadString(IDSC_OR); stl.ltype = LC_OR; vLcbx_data.push_back(stl); } if (vFcbx_data.empty()) { st_Fcbxdata stf; switch (m_iType) { case DFTYPE_MAIN: stf.cs_text = CItemData::FieldName(CItemData::GROUP).c_str(); stf.ftype = FT_GROUP; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::TITLE).c_str(); stf.ftype = FT_TITLE; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::GROUPTITLE).c_str(); stf.ftype = FT_GROUPTITLE; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::USER).c_str(); stf.ftype = FT_USER; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::PASSWORD).c_str(); stf.ftype = FT_PASSWORD; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::NOTES).c_str(); stf.ftype = FT_NOTES; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::URL).c_str(); stf.ftype = FT_URL; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::AUTOTYPE).c_str(); stf.ftype = FT_AUTOTYPE; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::RUNCMD).c_str(); stf.ftype = FT_RUNCMD; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::DCA).c_str(); stf.ftype = FT_DCA; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::SHIFTDCA).c_str(); stf.ftype = FT_SHIFTDCA; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::EMAIL).c_str(); stf.ftype = FT_EMAIL; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::SYMBOLS).c_str(); stf.ftype = FT_SYMBOLS; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::POLICYNAME).c_str(); stf.ftype = FT_POLICYNAME; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::PROTECTED).c_str(); stf.ftype = FT_PROTECTED; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::CTIME).c_str(); stf.ftype = FT_CTIME; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::ATIME).c_str(); stf.ftype = FT_ATIME; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::PMTIME).c_str(); stf.ftype = FT_PMTIME; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::XTIME).c_str(); stf.ftype = FT_XTIME; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::XTIME_INT).c_str(); stf.ftype = FT_XTIME_INT; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::RMTIME).c_str(); stf.ftype = FT_RMTIME; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_PASSWORDHISTORY); stf.ftype = FT_PWHIST; vFcbx_data.push_back(stf); stf.cs_text = CItemData::FieldName(CItemData::POLICY).c_str(); stf.ftype = FT_POLICY; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_PASSWORDLEN); stf.ftype = FT_PASSWORDLEN; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_KBSHORTCUT); stf.ftype = FT_KBSHORTCUT; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_ENTRYTYPE); stf.cs_text.TrimRight(L'\t'); stf.ftype = FT_ENTRYTYPE; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_ENTRYSTATUS); stf.cs_text.TrimRight(L'\t'); stf.ftype = FT_ENTRYSTATUS; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_ENTRYSIZE); stf.cs_text.TrimRight(L'\t'); stf.ftype = FT_ENTRYSIZE; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_UNKNOWNFIELDSFILTER); stf.cs_text.TrimRight(L'\t'); stf.ftype = FT_UNKNOWNFIELDS; vFcbx_data.push_back(stf); break; case DFTYPE_PWHISTORY: stf.cs_text.LoadString(IDS_PRESENT); stf.cs_text.TrimRight(L'\t'); stf.ftype = HT_PRESENT; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_HACTIVE); stf.cs_text.TrimRight(L'\t'); stf.ftype = HT_ACTIVE; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_HNUM); stf.cs_text.TrimRight(L'\t'); stf.ftype = HT_NUM; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_HMAX); stf.cs_text.TrimRight(L'\t'); stf.ftype = HT_MAX; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_HDATE); stf.cs_text.TrimRight(L'\t'); stf.ftype = HT_CHANGEDATE; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_HPSWD); stf.cs_text.TrimRight(L'\t'); stf.ftype = HT_PASSWORDS; vFcbx_data.push_back(stf); break; case DFTYPE_PWPOLICY: stf.cs_text.LoadString(IDS_PRESENT); stf.cs_text.TrimRight(L'\t'); stf.ftype = PT_PRESENT; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDSC_PLENGTH); stf.cs_text.TrimRight(L'\t'); stf.ftype = PT_LENGTH; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_PLOWER); stf.cs_text.TrimRight(L'\t'); stf.ftype = PT_LOWERCASE; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_PUPPER); stf.cs_text.TrimRight(L'\t'); stf.ftype = PT_UPPERCASE; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_PDIGITS); stf.cs_text.TrimRight(L'\t'); stf.ftype = PT_DIGITS; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDS_PSYMBOL); stf.cs_text.TrimRight(L'\t'); stf.ftype = PT_SYMBOLS; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDSC_PHEXADECIMAL); stf.cs_text.TrimRight(L'\t'); stf.ftype = PT_HEXADECIMAL; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDSC_PEASYVISION); stf.cs_text.TrimRight(L'\t'); stf.ftype = PT_EASYVISION; vFcbx_data.push_back(stf); stf.cs_text.LoadString(IDSC_PPRONOUNCEABLE); stf.cs_text.TrimRight(L'\t'); stf.ftype = PT_PRONOUNCEABLE; vFcbx_data.push_back(stf); break; default: ASSERT(0); } } } void CPWFilterLC::OnLButtonDown(UINT nFlags, CPoint point) { int iItem = -1; int iSubItem = -1; LVHITTESTINFO lvhti; lvhti.pt = point; SubItemHitTest(&lvhti); if (lvhti.flags & LVHT_ONITEM) { iItem = lvhti.iItem; iSubItem = lvhti.iSubItem; m_iItem = iItem; } if ((iItem < 0) || (iItem >= m_numfilters) || (iSubItem < 0) || (iSubItem >= FLC_NUM_COLUMNS)) { CListCtrl::OnLButtonDown(nFlags, point); } else { FieldType ftype = m_pvfdata->at(m_iItem).ftype; DWORD_PTR dwData = GetItemData(m_iItem); bool bFilterActive = (dwData & FLC_FILTER_ENABLED) == FLC_FILTER_ENABLED; bool bLogicCBXEnabled = (dwData & FLC_LGC_CBX_ENABLED) == FLC_LGC_CBX_ENABLED; switch (iSubItem) { case FLC_FILTER_NUMBER: EnsureVisible(m_iItem, FALSE); SetItemState(m_iItem, 0, LVIS_SELECTED); break; case FLC_ENABLE_BUTTON: // Change what user sees - then implement the result EnableCriteria(); break; case FLC_ADD_BUTTON: AddFilter(); break; case FLC_REM_BUTTON: RemoveFilter(); break; case FLC_LGC_COMBOBOX: if (bFilterActive && bLogicCBXEnabled && iItem > 0) { DrawComboBox(FLC_LGC_COMBOBOX, m_pvfdata->at(m_iItem).ltype == LC_OR ? 1 : 0); m_pComboBox->ShowDropDown(TRUE); } break; case FLC_FLD_COMBOBOX: if (bFilterActive) { DrawComboBox(FLC_FLD_COMBOBOX, (int)ftype); m_pComboBox->ShowDropDown(TRUE); } break; case FLC_CRITERIA_TEXT: dwData = GetItemData(m_iItem); if ((dwData & FLC_FILTER_ENABLED) && (dwData & FLC_FLD_CBX_SET)) GetCriterion(); break; default: break; } } if (m_iItem >= 0) SetItemState(m_iItem, 0, LVIS_SELECTED | LVIS_DROPHILITED); Invalidate(); } void CPWFilterLC::DrawComboBox(const int iSubItem, const int index) { // Draw the drop down list CRect rect; GetSubItemRect(m_iItem, iSubItem, LVIR_BOUNDS, rect); m_pComboBox = new CComboBox; ASSERT(m_pComboBox); if (!m_pComboBox) return; UINT nID; if (iSubItem == FLC_FLD_COMBOBOX) nID = m_FLD_ComboID; else if (iSubItem == FLC_LGC_COMBOBOX) nID = m_LGC_ComboID; else { ASSERT(0); return; } rect.top -= 1; CRect m_rectComboBox(rect); m_rectComboBox.left += 1; DWORD dwStyle = CBS_DROPDOWNLIST | WS_CHILD | WS_VISIBLE; BOOL bSuccess = m_pComboBox->Create(dwStyle, m_rectComboBox, this, nID); ASSERT(bSuccess); if (!bSuccess) return; if (!m_pFont) { CFont *pFont = GetFont(); ASSERT(pFont); LOGFONT logFont; SecureZeroMemory(&logFont, sizeof(logFont)); pFont->GetLogFont(&logFont); m_pFont = new CFont; m_pFont->CreateFontIndirect(&logFont); } m_pComboBox->SetFont(m_pFont); // add strings & data to ComboBox vWCFcbx_data = vFcbx_data; if (m_iType == DFTYPE_MAIN && iSubItem == FLC_FLD_COMBOBOX) { // Is PW History or Policy already selected somewhere else? // if so remove them as an option on this filter st_FilterRow &st_fldata = m_pvfdata->at(m_iItem); if (m_bPWHIST_Set && st_fldata.ftype != FT_PWHIST) DeleteEntry(FT_PWHIST); if (m_bPOLICY_Set && st_fldata.ftype != FT_POLICY) DeleteEntry(FT_POLICY); } switch (iSubItem) { case FLC_FLD_COMBOBOX: for (int i = 0; i < (int)vWCFcbx_data.size(); i++) { m_pComboBox->AddString(vWCFcbx_data[i].cs_text); m_pComboBox->SetItemData(i, vWCFcbx_data[i].ftype); } break; case FLC_LGC_COMBOBOX: for (int i = 0; i < (int)vLcbx_data.size(); i++) { m_pComboBox->AddString(vLcbx_data[i].cs_text); m_pComboBox->SetItemData(i, (int)vLcbx_data[i].ltype); } break; default: ASSERT(0); } // Find widths and height - only the first time this is called // In fact, called twice during 'Init' processing just for this purpose // once for each Combobox if ((m_fwidth < 0 && iSubItem == FLC_FLD_COMBOBOX) || (m_lwidth < 0 && iSubItem == FLC_LGC_COMBOBOX)) { // Find the longest string in the list box. CString str; CSize sz; int dx(0); TEXTMETRIC tm; CDC *pDC = m_pComboBox->GetDC(); CFont *pFont = m_pComboBox->GetFont(); // Select the ComboBox font, save the old font CFont *pOldFont = pDC->SelectObject(pFont); // Get the text metrics for avg char width pDC->GetTextMetrics(&tm); for (int i = 0; i < m_pComboBox->GetCount(); i++) { m_pComboBox->GetLBText(i, str); sz = pDC->GetTextExtent(str); // Add the average width to prevent clipping sz.cx += tm.tmAveCharWidth; if (sz.cx > dx) dx = sz.cx; } dx += 2 * ::GetSystemMetrics(SM_CXEDGE) + 5; // Select the old font back into the DC pDC->SelectObject(pOldFont); m_pComboBox->ReleaseDC(pDC); // Now set column widths if (iSubItem == FLC_FLD_COMBOBOX) { m_fwidth = max(dx, GetColumnWidth(FLC_FLD_COMBOBOX)); SetColumnWidth(FLC_FLD_COMBOBOX, m_fwidth); } else { m_lwidth = max(dx, GetColumnWidth(FLC_LGC_COMBOBOX)); SetColumnWidth(FLC_LGC_COMBOBOX, m_lwidth); } if (m_rowheight < 0) { // Set row height to take image by adding a dummy ImageList // Good trick - save making ComboBox "ownerdraw" CRect rect; m_pComboBox->GetClientRect(&rect); IMAGEINFO imageinfo; m_pCheckImageList->GetImageInfo(0, &imageinfo); m_rowheight = max(rect.Height(), abs(imageinfo.rcImage.top - imageinfo.rcImage.bottom)); m_pImageList = new CImageList; m_pImageList->Create(1, m_rowheight, ILC_COLOR4, 1, 1); SetImageList(m_pImageList, LVSIL_SMALL); } } // If the width of the list box is too small, adjust it so that every // item is completely visible. if (m_pComboBox->GetDroppedWidth() < ((iSubItem == FLC_FLD_COMBOBOX) ? m_fwidth : m_lwidth)) { m_pComboBox->SetDroppedWidth(iSubItem == FLC_FLD_COMBOBOX ? m_fwidth : m_lwidth); } // Try to ensure that dropdown list is big enough for all entries and // therefore no scrolling int n = m_pComboBox->GetCount(); int ht = m_pComboBox->GetItemHeight(0); m_pComboBox->GetWindowRect(&rect); CSize sz; sz.cx = rect.Width(); sz.cy = ht * (n + 2); if ((rect.top - sz.cy) < 0 || (rect.bottom + sz.cy > ::GetSystemMetrics(SM_CYSCREEN))) { int ifit = max((rect.top / ht), (::GetSystemMetrics(SM_CYSCREEN) - rect.bottom) / ht); int ht2 = ht * ifit; sz.cy = min(ht2, sz.cy); } m_pComboBox->SetWindowPos(NULL, 0, 0, sz.cx, sz.cy, SWP_NOMOVE | SWP_NOZORDER); int nindex(index); if (nindex >= n || nindex < 0) nindex = -1; else { if (iSubItem == FLC_FLD_COMBOBOX) { std::vector<st_Fcbxdata>::iterator Fcbxdata_iter; Fcbxdata_iter = std::find_if(vWCFcbx_data.begin(), vWCFcbx_data.end(), equal_ftype((FieldType)index)); if (Fcbxdata_iter == vWCFcbx_data.end()) nindex = -1; else nindex = (int)(Fcbxdata_iter - vWCFcbx_data.begin()); } } m_pComboBox->SetCurSel(nindex); m_pComboBox->ShowWindow(SW_SHOW); m_pComboBox->BringWindowToTop(); } void CPWFilterLC::DeleteEntry(FieldType ftype) { // User has selected Password History or Policy // Remove it from the Combobox data - Working Copy only! std::vector<st_Fcbxdata>::iterator Fcbxdata_iter; Fcbxdata_iter = std::find_if(vWCFcbx_data.begin(), vWCFcbx_data.end(), equal_ftype(ftype)); // Check if already deleted - should never happen! if (Fcbxdata_iter != vWCFcbx_data.end()) vWCFcbx_data.erase(Fcbxdata_iter); } void CPWFilterLC::OnCustomDraw(NMHDR *pNotifyStruct, LRESULT *pLResult) { NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW *>(pNotifyStruct); *pLResult = CDRF_DODEFAULT; const int iItem = (int)pLVCD->nmcd.dwItemSpec; const int iSubItem = pLVCD->iSubItem; const DWORD_PTR dwData = pLVCD->nmcd.lItemlParam; bool bFilterActive = (dwData & FLC_FILTER_ENABLED) == FLC_FILTER_ENABLED; bool bLogicCBXEnabled = (dwData & FLC_LGC_CBX_ENABLED) == FLC_LGC_CBX_ENABLED; int ix, iy; switch(pLVCD->nmcd.dwDrawStage) { case CDDS_PREPAINT: *pLResult = CDRF_NOTIFYITEMDRAW; break; case CDDS_ITEMPREPAINT: *pLResult = CDRF_NOTIFYSUBITEMDRAW; break; case CDDS_ITEMPREPAINT | CDDS_SUBITEM: { CRect rect; GetSubItemRect(iItem, iSubItem, LVIR_BOUNDS, rect); if (rect.top < 0) { *pLResult = CDRF_SKIPDEFAULT; break; } if (iSubItem == 0) { CRect rect1; GetSubItemRect(iItem, 1, LVIR_BOUNDS, rect1); rect.right = rect1.left; } pLVCD->clrText = m_crWindowText; pLVCD->clrTextBk = GetTextBkColor(); CDC* pDC = CDC::FromHandle(pLVCD->nmcd.hdc); CRect inner_rect(rect), first_rect(rect); inner_rect.DeflateRect(2, 2); switch (iSubItem) { case FLC_FILTER_NUMBER: first_rect.DeflateRect(1, 1); pDC->FillSolidRect(&first_rect, m_crButtonFace); DrawSubItemText(iItem, iSubItem, pDC, m_iItem == iItem ? m_crRedText : m_crWindowText, m_crButtonFace, inner_rect, m_iItem == iItem, true); *pLResult = CDRF_SKIPDEFAULT; break; case FLC_ENABLE_BUTTON: // Draw checked/unchecked image ix = inner_rect.CenterPoint().x; iy = inner_rect.CenterPoint().y; // The '7' below is ~ half the bitmap size of 13. inner_rect.SetRect(ix - 7, iy - 7, ix + 7, iy + 7); DrawImage(pDC, inner_rect, bFilterActive ? 0 : 1); *pLResult = CDRF_SKIPDEFAULT; break; case FLC_ADD_BUTTON: case FLC_REM_BUTTON: // Always bold DrawSubItemText(iItem, iSubItem, pDC, m_crWindowText, m_crWindow, inner_rect, true, false); *pLResult = CDRF_SKIPDEFAULT; break; case FLC_LGC_COMBOBOX: // Greyed out if filter inactive or logic not set if (!bFilterActive || !bLogicCBXEnabled) { pLVCD->clrText = m_crGrayText; } break; case FLC_FLD_COMBOBOX: // Greyed out if filter inactive or field not set if (!bFilterActive) { pLVCD->clrText = m_crGrayText; } break; case FLC_CRITERIA_TEXT: // Greyed out if filter inactive if (!bFilterActive) { pLVCD->clrText = m_crGrayText; } else if (dwData & FLC_CRITERIA_REDTXT) { // Red text if criteria not set pLVCD->clrText = m_crRedText; } break; default: break; } } break; default: break; } } void CPWFilterLC::DrawSubItemText(int iItem, int iSubItem, CDC *pDC, COLORREF crText, COLORREF crBkgnd, CRect &rect, bool bBold, bool bOpaque) { CRect rectText(rect); CString str = GetItemText(iItem, iSubItem); if (!str.IsEmpty()) { HDITEM hditem; hditem.mask = HDI_FORMAT; m_pHeaderCtrl->GetItem(iSubItem, &hditem); int nFmt = hditem.fmt & HDF_JUSTIFYMASK; UINT nFormat = DT_VCENTER | DT_SINGLELINE; if (nFmt == HDF_CENTER) nFormat |= DT_CENTER; else if (nFmt == HDF_LEFT) nFormat |= DT_LEFT; else nFormat |= DT_RIGHT; CFont *pOldFont = NULL; CFont boldfont; if (bBold) { CFont *pFont = pDC->GetCurrentFont(); if (pFont) { LOGFONT lf; pFont->GetLogFont(&lf); lf.lfWeight = FW_BOLD; boldfont.CreateFontIndirect(&lf); pOldFont = pDC->SelectObject(&boldfont); } } pDC->SetBkMode(bOpaque ? OPAQUE : TRANSPARENT); pDC->SetTextColor(crText); pDC->SetBkColor(crBkgnd); pDC->DrawText(str, &rectText, nFormat); if (pOldFont) pDC->SelectObject(pOldFont); } } void CPWFilterLC::DrawImage(CDC *pDC, CRect &rect, int nImage) { // Draw check image in given rectangle if (rect.IsRectEmpty() || nImage < 0) { return; } if (m_pCheckImageList) { SIZE sizeImage = {0, 0}; IMAGEINFO info; if (m_pCheckImageList->GetImageInfo(nImage, &info)) { sizeImage.cx = info.rcImage.right - info.rcImage.left; sizeImage.cy = info.rcImage.bottom - info.rcImage.top; } if (nImage >= 0) { if (rect.Width() > 0) { POINT point; point.y = rect.CenterPoint().y - (sizeImage.cy >> 1); point.x = rect.left; SIZE size; size.cx = rect.Width() < sizeImage.cx ? rect.Width() : sizeImage.cx; size.cy = rect.Height() < sizeImage.cy ? rect.Height() : sizeImage.cy; // Due to a bug in VS2010 MFC the following does not work! // m_pCheckImageList->DrawIndirect(pDC, nImage, point, size, CPoint(0, 0)); // So do it the hard way! IMAGELISTDRAWPARAMS imldp = {0}; imldp.cbSize = sizeof(imldp); imldp.i = nImage; imldp.hdcDst = pDC->m_hDC; imldp.x = point.x; imldp.y = point.y; imldp.xBitmap = imldp.yBitmap = 0; imldp.cx = size.cx; imldp.cy = size.cy; imldp.fStyle = ILD_NORMAL; imldp.dwRop = SRCCOPY; imldp.rgbBk = CLR_DEFAULT; imldp.rgbFg = CLR_DEFAULT; imldp.fState = ILS_NORMAL; imldp.Frame = 0; imldp.crEffect = CLR_DEFAULT; m_pCheckImageList->DrawIndirect(&imldp); } } } } INT_PTR CPWFilterLC::OnToolHitTest(CPoint point, TOOLINFO *pTI) const { LVHITTESTINFO lvhti; lvhti.pt = point; ListView_SubItemHitTest(this->m_hWnd, &lvhti); int nSubItem = lvhti.iSubItem; // nFlags is 0 if the SubItemHitTest fails // Therefore, 0 & <anything> will equal false if (lvhti.flags & LVHT_ONITEMLABEL) { // get the client (area occupied by this control RECT rcClient; GetClientRect(&rcClient); // fill in the TOOLINFO structure pTI->hwnd = m_hWnd; pTI->uId = (UINT) (nSubItem + 1); pTI->lpszText = LPSTR_TEXTCALLBACK; pTI->rect = rcClient; return pTI->uId; // By returning a unique value per listItem, // we ensure that when the mouse moves over another // list item, the tooltip will change } else { //Otherwise, we aren't interested, so let the message propagate return -1; } } BOOL CPWFilterLC::OnToolTipText(UINT /*id*/, NMHDR *pNotifyStruct, LRESULT *pLResult) { UINT_PTR nID = pNotifyStruct->idFrom; // check if this is the automatic tooltip of the control if (nID == 0) return TRUE; // do not allow display of automatic tooltip, // or our tooltip will disappear TOOLTIPTEXTW *pTTTW = (TOOLTIPTEXTW *)pNotifyStruct; *pLResult = 0; // get the mouse position const MSG* pMessage; pMessage = GetCurrentMessage(); ASSERT(pMessage); CPoint pt; pt = pMessage->pt; // get the point from the message ScreenToClient(&pt); // convert the point's coords to be relative to this control // see if the point falls onto a list item LVHITTESTINFO lvhti; lvhti.pt = pt; SubItemHitTest(&lvhti); int nSubItem = lvhti.iSubItem; // nFlags is 0 if the SubItemHitTest fails // Therefore, 0 & <anything> will equal false if (lvhti.flags & LVHT_ONITEMLABEL) { // If it did fall on a list item, // and it was also hit one of the // item specific subitems we wish to show tooltips for switch (nSubItem) { case FLC_FILTER_NUMBER: nID = IDS_FLC_TOOLTIP0; break; case FLC_ENABLE_BUTTON: nID = IDS_FLC_TOOLTIP1; break; case FLC_ADD_BUTTON: nID = IDS_FLC_TOOLTIP2; break; case FLC_REM_BUTTON: nID = IDS_FLC_TOOLTIP3; break; case FLC_LGC_COMBOBOX: nID = IDS_FLC_TOOLTIP4; break; case FLC_FLD_COMBOBOX: nID = IDS_FLC_TOOLTIP5; break; case FLC_CRITERIA_TEXT: nID = IDS_FLC_TOOLTIP6; break; default: return FALSE; } // If there was a CString associated with the list item, // copy it's text (up to 80 characters worth, limitation // of the TOOLTIPTEXT structure) into the TOOLTIPTEXT // structure's szText member CString cs_TipText(MAKEINTRESOURCE(nID)); delete m_pwchTip; m_pwchTip = new WCHAR[cs_TipText.GetLength() + 1]; wcsncpy_s(m_pwchTip, cs_TipText.GetLength() + 1, cs_TipText, _TRUNCATE); pTTTW->lpszText = (LPWSTR)m_pwchTip; return TRUE; // we found a tool tip, } return FALSE; // we didn't handle the message, let the // framework continue propagating the message } void CPWFilterLC::OnProcessKey(UINT nID) { /* Ctrl+S Select filter Up arrow Select previous Down Arrow Select next Ctrl+E Enable selected filter Ctrl+F Select Field Ctrl+C Select Criteria Ctrl+L Select Logic (And/Or) Delete Delete selected filter Insert Add after selected filter */ POSITION pos; DWORD_PTR dwData(0); if (m_iItem >=0 && m_iItem < GetItemCount()) dwData = GetItemData(m_iItem); switch (nID) { case ID_FLC_CRITERIA: if (m_iItem >= 0) { if ((dwData & FLC_FILTER_ENABLED) && (dwData & FLC_FLD_CBX_SET) && (dwData & FLC_FLD_CBX_ENABLED)) GetCriterion(); } break; case ID_FLC_ENABLE: if (m_iItem >= 0) EnableCriteria(); break; case ID_FLC_FIELD: if (m_iItem >= 0) { if (dwData & FLC_FILTER_ENABLED) { m_bSetFieldActive = true; DrawComboBox(FLC_FLD_COMBOBOX, (int)m_pvfdata->at(m_iItem).ftype); m_pComboBox->ShowDropDown(TRUE); m_pComboBox->SetFocus(); } } break; case ID_FLC_LOGIC: if (m_iItem > 0) { if ((dwData & FLC_FILTER_ENABLED) && (dwData & FLC_LGC_CBX_ENABLED)) { m_bSetLogicActive = true; DrawComboBox(FLC_LGC_COMBOBOX, m_pvfdata->at(m_iItem).ltype == LC_OR ? 1 : 0); m_pComboBox->ShowDropDown(TRUE); m_pComboBox->SetFocus(); } } break; case ID_FLC_SELECT: if (m_iItem < 0) m_iItem = 0; pos = GetFirstSelectedItemPosition(); if (pos > 0) m_iItem = (int)pos - 1; EnsureVisible(m_iItem, FALSE); SetItemState(m_iItem, 0, LVIS_SELECTED); break; case ID_FLC_DELETE: if (m_iItem >= 0) { RemoveFilter(); if (m_iItem > 0) m_iItem--; } break; case ID_FLC_INSERT: if (m_iItem >= 0) { m_iItem = AddFilter(); if (m_iItem >= 0) { EnsureVisible(m_iItem, FALSE); } } break; case ID_FLC_PREVIOUS: if (m_bSetFieldActive || m_bSetLogicActive) return; if (m_iItem <= 0) m_iItem = 0; else m_iItem--; EnsureVisible(m_iItem, FALSE); break; case ID_FLC_NEXT: if (m_bSetFieldActive || m_bSetLogicActive) return; if (m_iItem >= GetItemCount() - 1) m_iItem = GetItemCount() - 1; else m_iItem++; EnsureVisible(m_iItem, FALSE); break; default: ASSERT(0); } Invalidate(); }
Rails.application.routes.draw do get 'pages/home' resources :posts root 'pages#home' end
class AddSubmissionCountToCommodityPrices < ActiveRecord::Migration[6.1] def up add_column :commodity_prices, :submission_count, :integer, default: 0 CommodityPrice.where.not(submitted_by: nil).find_each do |price| price.update(submission_count: 1) end end def down remove_column :commodity_prices, :submission_count end end
# Change Log All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] ### Added ### Fixed ### Changed ### Deprecated ## [0.10.3] ### Fixed - ProcState.Get() doesn't fail under Windows when it cannot obtain process ownership information. #121 ## [0.10.2] ### Fixed - Fix memory leak when getting process arguments. #119 ## [0.10.1] ### Fixed - Replaced the WMI queries with win32 apis due to high CPU usage. #116 ## [0.10.0] ### Added - List filesystems on Windows that have an access path but not an assigned letter. #112 ### Fixed - Added missing runtime import for FreeBSD. #104 - Handle nil command line in Windows processes. #110 ## [0.9.0] ### Added - Added support for huge TLB pages on Linux #97 - Added support for big endian platform #100 ### Fixed - Add missing method for OpenBSD #99 ## [0.8.0] ### Added - Added partial `getrusage` support for Windows to retrieve system CPU time and user CPU time. #95 - Added full `getrusage` support for Unix. #95 ## [0.7.0] ### Added - Added method stubs for process handling for operating system that are not supported by gosigar. All methods return `ErrNotImplemented` on such systems. #88 ### Fixed - Fix freebsd build by using the common version of Get(pid). #91 ### Changed - Fixed issues in cgroup package by adding missing error checks and closing file handles. #92 ## [0.6.0] ### Added - Added method stubs to enable compilation for operating systems that are not supported by gosigar. All methods return `ErrNotImplemented` on these unsupported operating systems. #83 - FreeBSD returns `ErrNotImplemented` for `ProcTime.Get`. #83 ### Changed - OpenBSD returns `ErrNotImplemented` for `ProcTime.Get` instead of `nil`. #83 - Fixed incorrect `Mem.Used` calculation under linux. #82 - Fixed `ProcState` on Linux and FreeBSD when process names contain parentheses. #81 ### Removed - Remove NetBSD build from sigar_unix.go as it is not supported by gosigar. #83 ## [0.5.0] ### Changed - Fixed Trim environment variables when comparing values in the test suite. #79 - Make `kern_procargs` more robust under darwin when we cannot retrieve all the information about a process. #78 ## [0.4.0] ### Changed - Fixed Windows issue that caused a hang during `init()` if WMI wasn't ready. #74 ## [0.3.0] ### Added - Read `MemAvailable` value for kernel 3.14+ #71 ## [0.2.0] ### Added - Added `ErrCgroupsMissing` to indicate that /proc/cgroups is missing which is an indicator that cgroups were disabled at compile time. #64 ### Changed - Changed `cgroup.SupportedSubsystems()` to honor the "enabled" column in the /proc/cgroups file. #64 ## [0.1.0] ### Added - Added `CpuList` implementation for Windows that returns CPU timing information on a per CPU basis. #55 - Added `Uptime` implementation for Windows. #55 - Added `Swap` implementation for Windows based on page file metrics. #55 - Added support to `github.com/gosigar/sys/windows` for querying and enabling privileges in a process token. - Added utility code for interfacing with linux NETLINK_INET_DIAG. #60 - Added `ProcEnv` for getting a process's environment variables. #61 ### Changed - Changed several `OpenProcess` calls on Windows to request the lowest possible access privileges. #50 - Removed cgo usage from Windows code. - Added OS version checks to `ProcArgs.Get` on Windows because the `Win32_Process` WMI query is not available prior to Windows vista. On XP and Windows 2003, this method returns `ErrNotImplemented`. #55 ### Fixed - Fixed value of `Mem.ActualFree` and `Mem.ActualUsed` on Windows. #49 - Fixed `ProcTime.StartTime` on Windows to report value in milliseconds since Unix epoch. #51 - Fixed `ProcStatus.PPID` value is wrong on Windows. #55 - Fixed `ProcStatus.Username` error on Windows XP #56
""" Author: nplan https://github.com/nplan/gym-line-follower """ import numpy as np from shapely.geometry import LineString def interpolate_points(points, nb_out_points=None, segment_length=None): """ Interpolate points in equal intervals over a line string defined with input points. Exactly one out of nr_segments and interval must not be not. :param points: Input points, 2D array [[x1, y1], [x2, y2], ...]. Number of points must be greater than 0. :param nb_out_points: desired number of interpolated points :param segment_length: distance between points :return: 2D array of interpolated points points, nr of points is nr of segments + 1 """ if nb_out_points is not None: if nb_out_points == 1: return points[0] elif nb_out_points < 1: raise ValueError("nb_out_points must be grater than 0") nr_segments = nb_out_points - 1 else: nr_segments = None if len(points) == 0: raise ValueError("Point array is empty! Nothing to interpolate.") if len(points) < 2: return np.array([points[0]]) line = LineString(points) length = line.length if bool(nr_segments) and not bool(segment_length): segment_length = length / nr_segments elif not bool(nr_segments) and bool(segment_length): nr_segments = int(length // segment_length) else: raise ValueError("Exactly one out of nr_segments and interval must not be None.") new_points = [] for i in range(nr_segments + 1): pt_length = i * segment_length if pt_length > length + 1e-6: break pt = line.interpolate(i*segment_length) new_points.append(pt.coords[0]) new_points = np.array(new_points) return new_points def point_dist(p0, p1): """ Calculate distance between two points in 2D. :param p0: first point, array like coordinates :param p1: second point, array like coordinates :return: distance, float """ return ((p1[0] - p0[0])**2 + (p1[1] - p0[1])**2)**(1/2) def test_point_dist(): import random a = [random.random() for _ in range(10)] b = [random.random() for _ in range(10)] for p in zip(a, b): r = (0, 1) p = np.array(p) r = np.array(r) assert point_dist(p, r) == np.linalg.norm(p-r) def sort_points(points, origin=(0, 0)): """ Sort points in a track line sequence starting from origin. :param points: points to sort, array like :param origin: origin, starting point :return: sorted points, array """ origin = np.array(origin) points = np.array(points) sorted = np.empty((0, 2), dtype=np.float32) # Find point nearest to origin nearest_idx = 0 for i, pt in enumerate(points): if point_dist(pt, origin) < point_dist(points[nearest_idx], origin): nearest_idx = i sorted = np.append(sorted, [points[nearest_idx]], axis=0) points = np.delete(points, nearest_idx, axis=0) # Find next points while len(points) > 0: next_idx = 0 for i, pt in enumerate(points): if point_dist(pt, sorted[-1]) < point_dist(points[next_idx], sorted[-1]): next_idx = i # Check continuity if point_dist(points[next_idx], sorted[-1]) > 30e-3: break sorted = np.append(sorted, [points[next_idx]], axis=0) points = np.delete(points, next_idx, axis=0) return np.array(sorted) if __name__ == '__main__': import matplotlib.pyplot as plt points = np.array([(316, 369), (319, 269), (323, 191), (345, 147), (405, 116), (457, 115), (499, 112), (574, 108)]) new_points = interpolate_points(points, segment_length=400) print(len(new_points)) plt.gca().invert_yaxis() plt.grid() plt.plot(points[:, 0], points[:, 1], "-*") plt.plot(new_points[:, 0], new_points[:, 1], "*") # tck, u = interpolate.splprep(new_points.transpose(), s=0) # unew = np.arange(0, 1.01, 0.01) # out = interpolate.splev(unew, tck) # plt.plot(*out, "--") plt.show()
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using ValidateTransformDerive.Framework.Transformation; namespace ValidateTransformDerive.Framework.Tests.Transformation { [TestClass] public class TransformationServiceTests { protected readonly Exception GeneralException = new Exception(); protected readonly TransformationException TransformationException = new TransformationException(); protected readonly Mock<ITransform<string, bool>> TransformerMock = new Mock<ITransform<string, bool>>(); protected readonly TransformationService<string, bool> TransformationService; public TransformationServiceTests() { TransformationService = new TransformationService<string, bool>(TransformerMock.Object); } [TestMethod] public void CallsTransformInternal() { TransformationService.Transform(null); TransformerMock.Verify(transform => transform.Transform(null), Times.Once); TransformerMock.VerifyNoOtherCalls(); TransformerMock.Reset(); } [TestMethod] public void RethrowsTransformException() { TransformationException thrownEx = null; try { TransformerMock.Setup(transform => transform.Transform(null)).Throws(TransformationException); TransformationService.Transform(null); } catch (TransformationException tex) { thrownEx = tex; } Assert.AreEqual(TransformationException, thrownEx); TransformerMock.Verify(transform => transform.Transform(null), Times.Once); TransformerMock.VerifyNoOtherCalls(); TransformerMock.Reset(); } [TestMethod] public void WrapsExceptionInTransformException() { TransformationException thrownEx = null; try { TransformerMock.Setup(transform => transform.Transform(null)).Throws(GeneralException); TransformationService.Transform(null); } catch (TransformationException tex) { thrownEx = tex; } Assert.IsInstanceOfType(thrownEx, typeof(TransformationException)); Assert.AreEqual(GeneralException, thrownEx.InnerException); TransformerMock.Verify(transform => transform.Transform(null), Times.Once); TransformerMock.VerifyNoOtherCalls(); TransformerMock.Reset(); } [TestMethod] public void WrapsExceptionInTransformExceptionNullTransformer() { TransformationException thrownEx = null; try { new TransformationService<string, bool>(null).Transform(null); } catch (TransformationException tex) { thrownEx = tex; } Assert.IsInstanceOfType(thrownEx, typeof(TransformationException)); } } }
require 'closure-compiler' module JBundle class Compiler BUILDABLE_FILES = ['.js'] attr_reader :name, :src_dir, :dir def initialize(name, file_list, config) @config, @file_list, @src_dir = config, file_list, config.src_dir @name, @dir = parse_name(name) end def ext @ext ||= ::File.extname(name) end def buildable? BUILDABLE_FILES.include?(ext) end # This only makes sense for one-file objects def src_path ::File.join(@src_dir, @file_list.original_name) end def src @src ||= filter(filtered_licenses + filtered_src, :src) end def min @min ||= filter(filtered_licenses, :min) + Closure::Compiler.new.compile(filter(filtered_src, :min)) end def filtered_licenses @filtered_licenses ||= filter(licenses, :all) end def filtered_src @filtered_src ||= filter(raw_src, :all) end def min_name @min_name ||= ( ext = ::File.extname(name) name.sub(ext, '') + '.min' + ext ) end def licenses @licenses ||= if @file_list.respond_to?(:licenses) read_files @file_list.licenses else '' end end def raw_src @raw_src ||= read_files(@file_list) end protected def read_files(file_names) file_names.inject('') do |mem, file_name| mem << ::File.read(::File.join(src_dir, file_name)) mem << "\n" mem end end def parse_name(name) n = ::File.basename(name) d = ::File.dirname(name) if name =~ /\// [n,d] end def filter(content, mode) @config.filters[mode].each do |filter| content = filter.call(content, @config) end content end end class Builder def initialize(config) @config = config @sources = [] end def build! @sources = @config.bundles_and_files.map do |b| build_one b end end def build_one(f) Compiler.new(f.name, f, @config) end end end
// Package script is just here so that we can keep binary dependencies out of vendor. // There needs to be at least one go file in script for dep to work here. package script
const { DependentTypes, } = require('enterprise-edition'); console.log('DependentTypes:', Object.keys(DependentTypes)); console.log('Works fine!');
{"timestamp": 1565672265.0, "score_count": 108391, "score": 8.11} {"timestamp": 1565143950.0, "score_count": 108079, "score": 8.11} {"timestamp": 1565141748.0, "score_count": 108079, "score": 8.11} {"timestamp": 1565136449.0, "score_count": 108079, "score": 8.11} {"timestamp": 1564529832.0, "score_count": 107878, "score": 8.11} {"timestamp": 1563070652.0, "score_count": 107328, "score": 8.11} {"timestamp": 1562902408.0, "score_count": 107328, "score": 8.11} {"timestamp": 1560398621.0, "score_count": 106456, "score": 8.11} {"timestamp": 1559930623.0, "score_count": 106212, "score": 8.11} {"timestamp": 1556466592.0, "score_count": 105142, "score": 8.11} {"timestamp": 1556236250.0, "score_count": 105058, "score": 8.11} {"timestamp": 1555378392.0, "score_count": 104705, "score": 8.11} {"timestamp": 1555351030.0, "score_count": 104705, "score": 8.11} {"timestamp": 1555037407.0, "score_count": 104616, "score": 8.11} {"timestamp": 1554914990.0, "score_count": 104506, "score": 8.11} {"timestamp": 1462100753.0, "score_count": 62967, "score": 8.17} {"timestamp": 1448648294.0, "score_count": 55511, "score": 8.2} {"timestamp": 1554902865.0, "score_count": 104506, "score": 8.11} {"timestamp": 1553318646.0, "score_count": 103762, "score": 8.11} {"timestamp": 1553317214.0, "score_count": 103762, "score": 8.11} {"timestamp": 1553230942.0, "score_count": 103762, "score": 8.11} {"timestamp": 1553227303.0, "score_count": 103762, "score": 8.11} {"timestamp": 1553225469.0, "score_count": 103762, "score": 8.11} {"timestamp": 1553210002.0, "score_count": 103762, "score": 8.11} {"timestamp": 1552866646.0, "score_count": 103654, "score": 8.11} {"timestamp": 1551589023.0, "score_count": 103098, "score": 8.11} {"timestamp": 1543894331.0, "score_count": 99415, "score": 8.11} {"timestamp": 1537408280.0, "score_count": 96158, "score": 8.11} {"timestamp": 1534883390.0, "score_count": 95232, "score": 8.11} {"timestamp": 1534882172.0, "score_count": 95232, "score": 8.11} {"timestamp": 1534816215.0, "score_count": 95232, "score": 8.11} {"timestamp": 1534885318.0, "score_count": 95232, "score": 8.11} {"timestamp": 1487294188.0, "score_count": 75034, "score": 8.16} {"timestamp": 1522339442.0, "score_count": 90999, "score": 8.12} {"timestamp": 1487290822.0, "score_count": 75034, "score": 8.16} {"timestamp": 1487296508.0, "score_count": 75034, "score": 8.16} {"timestamp": 1487115480.0, "score_count": 74961, "score": 8.16} {"timestamp": 1487022064.0, "score_count": 74921, "score": 8.16} {"timestamp": 1486793093.0, "score_count": 74818, "score": 8.16} {"timestamp": 1485886196.0, "score_count": 74458, "score": 8.16} {"timestamp": 1485537531.0, "score_count": 74293, "score": 8.16} {"timestamp": 1485537414.0, "score_count": 74293, "score": 8.16} {"timestamp": 1484809337.0, "score_count": 73949, "score": 8.16} {"timestamp": 1484788119.0, "score_count": 73949, "score": 8.16} {"timestamp": 1484582875.0, "score_count": 73835, "score": 8.16} {"timestamp": 1484582701.0, "score_count": 73835, "score": 8.16} {"timestamp": 1484201911.0, "score_count": 73624, "score": 8.16} {"timestamp": 1483790813.0, "score_count": 73377, "score": 8.16} {"timestamp": 1483740886.0, "score_count": 73313, "score": 8.16} {"timestamp": 1483740600.0, "score_count": 73313, "score": 8.16} {"timestamp": 1483644722.0, "score_count": 73249, "score": 8.16} {"timestamp": 1483644588.0, "score_count": 73249, "score": 8.16} {"timestamp": 1483619409.0, "score_count": 73249, "score": 8.16} {"timestamp": 1483594604.0, "score_count": 73202, "score": 8.16} {"timestamp": 1483381467.0, "score_count": 73090, "score": 8.16} {"timestamp": 1478629983.0, "score_count": 71040, "score": 8.17} {"timestamp": 1483356397.0, "score_count": 73090, "score": 8.16} {"timestamp": 1468030976.0, "score_count": 65998, "score": 8.17} {"timestamp": 1466123919.0, "score_count": 64906, "score": 8.17} {"timestamp": 1463721710.0, "score_count": 63737, "score": 8.17} {"timestamp": 1460711940.0, "score_count": 62251, "score": 8.18} {"timestamp": 1459042639.0, "score_count": 61165, "score": 8.18} {"timestamp": 1458389983.0, "score_count": 60770, "score": 8.18} {"timestamp": 1458771417.0, "score_count": 61004, "score": 8.18} {"timestamp": 1458121848.0, "score_count": 60619, "score": 8.18} {"timestamp": 1457498417.0, "score_count": 60289, "score": 8.18} {"timestamp": 1453338972.0, "score_count": 58099, "score": 8.19} {"timestamp": 1451788585.0, "score_count": 57145, "score": 8.19} {"timestamp": 1441522256.0, "score_count": 52083, "score": 8.21} {"timestamp": 1545704506.0, "score_count": 100246, "score": 8.11} {"timestamp": 1548285283.0, "score_count": 101833, "score": 8.11} {"timestamp": 1553201699.0, "score_count": 103762, "score": 8.11} {"timestamp": 1553228993.0, "score_count": 103762, "score": 8.11} {"timestamp": 1553316494.0, "score_count": 103762, "score": 8.11} {"timestamp": 1553232245.0, "score_count": 103762, "score": 8.11}
import 'model.dart'; import 'objectbox.g.dart'; // created by `flutter pub run build_runner build` /// Provides access to the ObjectBox Store throughout the app. /// /// Create this in the apps main function. class ObjectBox { /// The Store of this app. late final Store store; /// Two Boxes: one for Tasks, one for Tags. late final Box<Task> taskBox; late final Box<Tag> tagBox; /// A stream of all tasks ordered by date. late final Stream<Query<Task>> tasksStream; late final Stream<Query<Tag>> tagsStream; ObjectBox._create(this.store) { taskBox = Box<Task>(store); tagBox = Box<Tag>(store); // Prepare a Query for all tasks, sorted by their date. // The Query is not run until find() is called or it is subscribed to. // https://docs.objectbox.io/queries final qBuilderTasks = taskBox.query() ..order(Task_.dateCreated, flags: Order.descending); tasksStream = qBuilderTasks.watch(triggerImmediately: true); final qBuilderTags = tagBox.query()..order(Tag_.name); tagsStream = qBuilderTags.watch(triggerImmediately: true); // Add some demo data if the box is empty. if (taskBox.isEmpty()) { _putDemoData(); } } /// Create an instance of ObjectBox to use throughout the app. static Future<ObjectBox> create() async { // Future<Store> openStore() {...} is defined in the generated objectbox.g.dart final store = await openStore(); return ObjectBox._create(store); } void _putDemoData() { Tag tag1 = Tag('work'); Tag tag2 = Tag('study'); Task task1 = Task('This is a work task.'); task1.tag.target = tag1; //set the relation Task task2 = Task('This is a study task.'); task2.tag.target = tag2; // When the Task is put, its Tag will automatically be put into the Tag Box. // Both ToOne and ToMany automatically put new Objects when the Object owning them is put. taskBox.putMany([task1, task2]); } }
import ctypes FILE_ATTRIBUTE_HIDDEN = 0x02 def hideFiles(folderPath): print '[*] Hiding files' try: ctypes.windll.kernel32.SetFileAttributesW.argtypes = (ctypes.c_wchar_p, ctypes.c_uint32) ret = ctypes.windll.kernel32.SetFileAttributesW(folderPath.encode('string-escape'), FILE_ATTRIBUTE_HIDDEN) if ret: print '[*] Folder is set to Hidden' else: # return code of zero indicates failure, raise Windows error raise ctypes.WinError() except Exception as e: print '[*] Error in hiding files' print e
--- title: Perseus Library description: Jedná se o databázi obsahující na 2356 antických děl a 3145 edicí a překladů řeckých a latinských textů. tags: - 2021-11-13_zdroje - 2021-11-14_historie - antika website: https://scaife.perseus.org/ cover: /images/perseus-cover.jpg ---
#!/bin/bash set -o errexit set -o nounset set -o pipefail set -o xtrace readonly PID="$1" sudo cat "/proc/${PID}/environ" | tr '\000' '\n'
; stack64.asm - Implements jmp_stack and init_stack for the x86-64 architecture .CODE ; Overview of MS x64 calling convention ; Parameters: ; Integer Params: ; rcx, rdx, r8, r9 ; Floating Point Params: ; xmm0, xmm1, xmm2, xmm3 ; Volatile Registers: ; rax, r10, r11, xmm4, xmm5 ; Non-volatile Registers: ; All Other registers ; Stack Pointer: ; Aligned to 16 bytes (rsp) ; jmp_stack: ; Switches between two stacks, saving all registers ; before changing the stack pointer ; This function complies to the microsoft ; x64 calling convention ; Arguments: (x64 calling convention) ; RCX - new stack pointer (void*) ; RDX - address of old stack pointer (void**) @@jmp_stack proc ; Save callee-save gp registers sub rsp, 64 ; Allocate stack space mov [rsp+56], rbx mov [rsp+48], rsi mov [rsp+40], rdi mov [rsp+32], rbp mov [rsp+24], r12 mov [rsp+16], r13 mov [rsp+8], r14 mov [rsp], r15 ; Save callee-save xmm registers sub rsp, 160 ; Allocate stack space movdqu [rsp+144], xmm15 movdqu [rsp+128], xmm14 movdqu [rsp+112], xmm13 movdqu [rsp+96], xmm12 movdqu [rsp+80], xmm11 movdqu [rsp+64], xmm10 movdqu [rsp+48], xmm9 movdqu [rsp+32], xmm8 movdqu [rsp+16], xmm7 movdqu [rsp], xmm6 ; Actual code to switch the stacks mov [rdx], rsp ; Save stack pointer to provided address mov rsp, rcx ; Set stack pointer to given new stack pointer ; Restore xmm registers movdqu xmm6, [rsp] movdqu xmm7, [rsp+16] movdqu xmm8, [rsp+32] movdqu xmm9, [rsp+48] movdqu xmm10, [rsp+64] movdqu xmm11, [rsp+80] movdqu xmm12, [rsp+96] movdqu xmm13, [rsp+112] movdqu xmm14, [rsp+128] movdqu xmm15, [rsp+144] add rsp, 160 ; Restore General pupose registers mov r15, [rsp] mov r14, [rsp+8] mov r13, [rsp+16] mov r12, [rsp+24] mov rbp, [rsp+32] mov rdi, [rsp+40] mov rsi, [rsp+48] mov rbx, [rsp+56] add rsp, 64 ret @@jmp_stack endp ; init_stack: ; Initializes the stack for the coroutine ; to perform the initial switch ; This procedure complies to microsoft x64 ; calling convention ; Arguments: ; RCX - A pointer to a struct of type tmpinfo (tmpinfo*) ; RDX - A pointer to a stack pointer (void**) @@init_stack proc mov r8, [rcx] ; Load the stack pointer that we are to jump to mov r9, [rcx+8] ; Load the function pointer that we will call mov rax, rcx ; Save a copy of the tmpinfo pointer mov rcx, r8 ; Set the stack pointer argument sub rcx, 232 ; Add a bunch of free space to the coroutine stack ; so that when jmp_stack pops off a whole bunch ; of nonexistent variables we don't fall off the ; bottom of the stack. 232 = 16*10 + 8*8 + 8 mov r10, coroutine_start mov [rcx+224], r10 ; Set the return address for jmp_stack ; so that it returns to where it would ; normally return in this function call @@jmp_stack ; Branch off to our new coroutine ; This clobbers all non-volatile registers ; and jumps to coroutine_start when starting ; the couroutine, returning as usual when ; resumed from the coroutine ret coroutine_start: ; Our coroutine effectively starts here ; (All non-volatile registers contain garbage) push rdx ; Save return stack pointer address push r8 ; Save the coroutine stack pointer mov rcx, rax ; Load the tmpinfo pointer into rcx sub rsp, 32 ; Allocate shadow space for parameters call r9 ; Call the coroutine function with rcx add rsp, 32 ; Free the shadow space for the parameters pop rdx ; Retrieve coroutine stack pointer pop r9 ; Retrieve old stack pointer sub rdx, 8 ; Bring rdx back into the stack space mov rcx, [r9] ; Get the top of the original stack ; jmp_stack will clobber the bottom ; of the coroutine stack but it isn't ; being used so this is fine call @@jmp_stack ; Exit the coroutine int 3 ; If this gets executed then there is a bug in the program @@init_stack endp coroutine_jmp_stack proc jmp @@jmp_stack coroutine_jmp_stack endp coroutine_init_stack proc jmp @@init_stack coroutine_init_stack endp END
#============================================================================== # Copyright (C) 2019-present Alces Flight Ltd. # # This file is part of FlightConfig. # # This program and the accompanying materials are made available under # the terms of the Eclipse Public License 2.0 which is available at # <https://www.eclipse.org/legal/epl-2.0>, or alternative license # terms made available by Alces Flight Ltd - please direct inquiries # about licensing to [email protected]. # # FlightConfig is distributed in the hope that it will be useful, but # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR # IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS # OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A # PARTICULAR PURPOSE. See the Eclipse Public License 2.0 for more # details. # # You should have received a copy of the Eclipse Public License 2.0 # along with FlightConfig. If not, see: # # https://opensource.org/licenses/EPL-2.0 # # For more information on FlightConfig, please visit: # https://github.com/openflighthpc/flight_config #============================================================================== lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "flight_config/version" Gem::Specification.new do |spec| spec.name = "flight_config" spec.version = FlightConfig::VERSION spec.authors = ["Alces Flight Ltd"] spec.email = ["[email protected]"] spec.license = 'EPL-2.0' spec.homepage = "https://github.com/openflighthpc/flight_config" spec.summary = "Manages the loading of config files" spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.bindir = "bin" spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_runtime_dependency 'tty-config' spec.add_development_dependency "bundler", "~> 1.16" spec.add_development_dependency 'fakefs' spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.0" spec.add_development_dependency 'pry-byebug' end
# Summary The Lua 5.1 standard library, abridged. # Description The **base** library is loaded directly into the global environment. It contains the following items from the [Lua 5.1 standard library](https://www.lua.org/manual/5.1/manual.html#5): $FIELDS # Fields ## \_G ### Summary The global environment. ### Description The **\_G** field holds the global environment (`_G._G == _G`). Setting \_G to a different value does not affect the content of the environment. ## \_VERSION ### Summary The current version of Lua. ### Description The **\_VERSION** field is the current version of the Lua interpreter. The current value is "Lua 5.1". ## assert ### Summary Tests a condition. ### Description The **assert** function throws an error if *v* evaluates to false. Otherwise, each argument (including *v* and *message*) is returned. *message* is used as the error if the assertion fails. ## error ### Summary Throws an error. ### Description The **error** function throws an error by terminating the last protected function that was called, using *message* as the error. *level* specifies the stack level from which error position information will be acquired. A *level* of 0 causes no position information to be included. ## getmetatable ### Summary Gets the metatable of a value. ### Description The **getmetatable** function gets the metatable of *v*. Returns nil if *v* does not have a metatable. Otherwise, if the metatable has the field "\__metatable", then its value is returned. Otherwise, the metatable itself is returned. ## ipairs ### Summary Returns an iterator over an array. ### Description The **ipairs** function iterates over the sequential integers keys of *t*. The values returned are suitable to be used directly with a generic for loop: ```lua for index, value in ipairs(t) do ... end ``` ## next ### Summary Gets the next field in a table. ### Description The **next** function allows all fields of a table to be traversed. *t* is the table, and *index* is the index in the table. next returns the next index and its associated value. If *index* is nil, then the first index and its value are returned. When called with the last index, nil is returned. The order in which fields are returned is undefined. This order is not changed after modifying existing fields, removing fields, or making no changes. How this order changes, when a value is assigned to a non-extant field, is undefined. ## pairs ### Summary Returns an iterator over a table. ### Description The **pairs** function iterates over all fields of *t*. The values returned are suitable to be used directly with a generic for loop: ```lua for key, value in pairs(t) do ... end ``` Specifically, *next* is the next function, *t* is the received *t*, and *start* is nil. ## pcall ### Summary Calls a function in protected mode. ### Description The **pcall** function calls *f* in protected mode. Any error thrown within *f* is caught and returned, instead of propagated. The remaining arguments are passed to *f*. *ok* will be true if the call succeeded without errors. In this case, the remaining values are those returned by *f*. If *ok* is false, then the next value is the error value. ## print ### Summary Prints values to standard output. ### Description The **print** function receives each argument, converts them to strings, and writes them to standard output. ## select ### Index #### Summary Returns arguments after a given index. #### Description The **select** function returns all arguments after the argument indicated by *index*. ```lua select(1, "A", "B", "C") --> "A", "B", "C" select(2, "A", "B", "C") --> "B", "C" select(3, "A", "B", "C") --> "C" select(4, "A", "B", "C") --> ``` If *index* is less than 0, then indexing starts from the end of the arguments. An error is thrown if *index* is 0. ### Count #### Summary Returns the number of arguments. #### Description The **select** function with a *count* of "#", returns the number of additional arguments passed. ## setmetatable ### Summary Sets the metatable of a value. ### Description The **setmetatable** function sets the metatable of *v* to *metatable*. If *metatable* is nil, then the metatable is removed. An error is thrown if the current metatable has a "\__metatable" field. ## tonumber #### Summary Converts a value to a number. #### Description The **tonumber** function attempts to convert *x* into a number. Returns a number if *x* is a number or a string that can be parsed as a number. Returns nil otherwise. *base* specifies the base to interpret the numeral. It may be any integer between 2 and 36, inclusive. In bases above 10, the letters A to Z (case-insensitive) represent 10 to 35, respectively. In base 10, the number can have a decimal part, as well as an optional exponent part. In other bases, only unsigned integers are accepted. ## tostring ### Summary Converts a value to a string. ### Description The **tostring** function converts *v* into a string in a reasonable format. If *v* has a metatable with the "\__tostring" field, then this field is called with *v* as its argument, and its result is returned. ## type ### Summary Returns the Lua type of a value. ### Description The **type** function returns the Lua type of *v* as a string. Possible values are "nil", "boolean", "number", "string", "table", "function, "thread", and "userdata". To get the internal type of userdata values, use the typeof function from the roblox library. ## unpack ### Summary Returns the elements in an array. ### Description The **unpack** function returns each element in *list* from *i* up to and including *j*. By default, *i* is 1, and *j* is the length of *list*. ## xpcall ### Summary Calls a function in protected mode with an error handler. ### Description The **xpcall** function is like pcall, except that it allows a custom error handler to be specified. *msgh* is the error handler, and is called within the erroring stack frame. *msgh* receives the current error message, and returns the new error message to be returned by xpcall. The remaining arguments to xpcall are passed to *f*.
package ch.leadrian.samp.kamp.core.api.entity import ch.leadrian.samp.kamp.core.api.entity.id.MenuId import ch.leadrian.samp.kamp.core.runtime.SAMPNativeFunctionExecutor import ch.leadrian.samp.kamp.core.runtime.callback.OnPlayerSelectedMenuRowReceiverDelegate import io.mockk.Runs import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.verify import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.catchThrowable import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource internal class MenuRowTest { private val menuId = MenuId.valueOf(69) private val menu = mockk<Menu>() private lateinit var menuRow: MenuRow private val onPlayerSelectedMenuRowReceiver = mockk<OnPlayerSelectedMenuRowReceiverDelegate>() private val nativeFunctionExecutor = mockk<SAMPNativeFunctionExecutor>() @BeforeEach fun setUp() { every { menu.id } returns menuId every { menu.numberOfColumns } returns 2 menuRow = MenuRow( menu = menu, index = 3, nativeFunctionExecutor = nativeFunctionExecutor, onPlayerSelectedMenuRowReceiver = onPlayerSelectedMenuRowReceiver ) } @Test fun shouldDisableMenuRow() { every { nativeFunctionExecutor.disableMenuRow(any(), any()) } returns true menuRow.disable() verify { nativeFunctionExecutor.disableMenuRow(menuid = menuId.value, row = 3) } } @ParameterizedTest @ValueSource(ints = [0, 1]) fun shouldInitializeTextsWithNull(column: Int) { val text = menuRow.getText(column) assertThat(text) .isNull() } @ParameterizedTest @ValueSource(ints = [0, 1]) fun shouldSetText(column: Int) { menuRow.setText(column, "Test 123") assertThat(menuRow.getText(column)) .isEqualTo("Test 123") } @ParameterizedTest @ValueSource(ints = [-1, 2]) fun givenInvalidColumnSetTextShouldThrowAnException(column: Int) { val caughtThrowable = catchThrowable { menuRow.setText(column, "Test 123") } assertThat(caughtThrowable) .isInstanceOf(IllegalArgumentException::class.java) } @ParameterizedTest @ValueSource(ints = [-1, 2]) fun givenInvalidColumnGetTextShouldThrowAnException(column: Int) { val caughtThrowable = catchThrowable { menuRow.getText(column) } assertThat(caughtThrowable) .isInstanceOf(IllegalArgumentException::class.java) } @Test fun shouldCallOnPlayerSelectedMenuRowReceiverDelegate() { val player = mockk<Player>() every { onPlayerSelectedMenuRowReceiver.onPlayerSelectedMenuRow(any(), any()) } just Runs menuRow.onSelected(player) verify { onPlayerSelectedMenuRowReceiver.onPlayerSelectedMenuRow(player, menuRow) } } }
const getters = { userName: state => state.app.userName, isOpen: state => state.app.isOpen, routeMatched: state => state.app.routeMatched } export default getters
/* See LICENSE file for license and copyright information */ #include <libzathura/plugin-api.h> #define _STR(x) #x #define STR(x) _STR(x) #define TEST_PLUGIN_DIR_PATH STR(_TEST_PLUGIN_DIR_PATH) #define TEST_PLUGIN_FILE_PATH STR(_TEST_PLUGIN_FILE_PATH) #define TEST_FILE_PATH STR(_TEST_FILE_PATH) const char* get_plugin_path(void); const char* get_plugin_dir_path(void); void setup_document_plugin(zathura_plugin_manager_t** plugin_manager, zathura_document_t** document);
package com.airwallex.android.redirect import android.app.Activity import android.content.Context import android.content.Intent import com.airwallex.android.core.* import com.airwallex.android.core.exception.AirwallexCheckoutException import com.airwallex.android.core.model.NextAction import com.airwallex.android.redirect.exception.RedirectException import com.airwallex.android.redirect.util.RedirectUtil class RedirectComponent : ActionComponent { companion object { val PROVIDER: ActionComponentProvider<RedirectComponent> = RedirectComponentProvider() } override fun handlePaymentIntentResponse( paymentIntentId: String, nextAction: NextAction?, activity: Activity, applicationContext: Context, cardNextActionModel: CardNextActionModel?, listener: Airwallex.PaymentListener<String> ) { when (nextAction?.type) { NextAction.NextActionType.REDIRECT -> { val redirectUrl = nextAction.url if (redirectUrl.isNullOrEmpty()) { listener.onFailed(AirwallexCheckoutException(message = "Redirect url not found")) return } try { listener.onSuccess(paymentIntentId) RedirectUtil.makeRedirect(activity = activity, redirectUrl = redirectUrl) } catch (e: RedirectException) { listener.onFailed(e) } } else -> { listener.onFailed(AirwallexCheckoutException(message = "Unsupported next action ${nextAction?.type}")) } } } override fun handleActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean { return false } override fun retrieveSecurityToken( paymentIntentId: String, applicationContext: Context, securityTokenListener: SecurityTokenListener ) { // Since only card payments require a device ID, this will not be executed securityTokenListener.onResponse("") } }
var table = d3.select('body').append('table') .style("border-collapse", "collapse") .style("border", "2px black solid"); var rows = ["put your rows here"] // headers table.append("thead").append("tr") .selectAll("th") .data(rows[0]) .enter().append("th") .text(function(d) { return d; }) .style("border", "1px black solid") .style("padding", "5px") .style("background-color", "lightgray") .style("font-weight", "bold") .style("text-transform", "uppercase"); // data table.append("tbody") .selectAll("tr").data(rows.slice(1)) .enter().append("tr") .selectAll("td") .data(function(d){return d;}) .enter().append("td") .style("border", "1px black solid") .style("padding", "5px") .on("mouseover", function(){ d3.select(this).style("background-color", "powderblue"); }) .on("mouseout", function(){ d3.select(this).style("background-color", "white"); }) .text(function(d){return d;}) .style("font-size", "12px");
package io.github.project_travel_mate.utilities.helper import com.blongho.country_data.Country import com.blongho.country_data.World class FlagHelper { companion object { fun retrieveFlagDrawable(country: String) : Int { return World.getCountryFrom(country).flagResource } } }
-- hcullide -- simple test program -- Author: Matthew Danish. License: BSD3 (see LICENSE file) -- -- Simple test of the Cullide library. There is a bunch of spheres -- bouncing around an enclosed space. They turn red when they -- collide. You can change direction of orthographic projection using -- x, y, and z keys. module Main where import Graphics.Collision.Cullide import Graphics.UI.GLUT import Data.IORef ( IORef, newIORef ) import System.Exit ( exitWith, ExitCode(ExitSuccess) ) import System.Random data Axis = AxisX | AxisY | AxisZ data State = State { objs :: IORef [(Vector3d, Vector3d, IO ())] , axisOf :: IORef Axis } boundMinX = -2 boundMaxX = 2 boundMinY = -2 boundMaxY = 2 boundMinZ = -2 boundMaxZ = 2 light0Position = Vertex4 1 1 1 0 light0Ambient = Color4 0.25 0.25 0.25 1 light0Diffuse = Color4 1 1 1 1 numObjs = 5 objW = 0.3 frameDelay = floor (1000.0 / 60.0) makeState0 = do let qstyle = (QuadricStyle (Just Smooth) GenerateTextureCoordinates Outside FillStyle) let w = objW dl1 <- defineNewList Compile (renderQuadric qstyle $ Sphere w 18 9) let actions = map (\ _ -> callList dl1) [ 1 .. numObjs ] objs <- flip mapM actions $ \ a -> do p <- randomVector3d v <- randomVector3d return (p, vecScale (0.01 / magnitude v) v, a) r_objs <- newIORef objs r_axis <- newIORef AxisZ return $ State r_objs r_axis main :: IO () main = do (progName, _args) <- getArgsAndInitialize initialDisplayMode $= [ DoubleBuffered, RGBMode, WithDepthBuffer ] initialWindowSize $= Size 640 480 initialWindowPosition $= Position 100 100 createWindow progName myInit state0 <- makeState0 displayCallback $= display state0 reshapeCallback $= Just reshape addTimerCallback frameDelay $ computeFrame state0 keyboardMouseCallback $= Just (keyboard state0) mainLoop computeFrame state = do os <- get (objs state) os' <- flip mapM os $ \ (p, v, a) -> do let Vector3 x y z = p let Vector3 vx vy vz = v let v' = Vector3 (if abs x > 1 then -vx else vx) (if abs y > 1 then -vy else vy) (if abs z > 1 then -vz else vz) return (p `vecAdd` v', v', a) objs state $= os' postRedisplay Nothing addTimerCallback frameDelay $ computeFrame state reshape :: ReshapeCallback reshape size = do viewport $= (Position 0 0, size) matrixMode $= Projection loadIdentity frustum (-1.0) 1.0 (-1.0) 1.0 2 10 lookAt (Vertex3 0 0 4) (Vertex3 0 0 0) (Vector3 0 1 0) matrixMode $= Modelview 0 display :: State -> DisplayCallback display state = do os <- get (objs state) -- collision detect collides <- detect (scaled (1/3, 1/3, 1/3)) . flip map os $ (\ (p, v, a) -> do preservingMatrix $ do translated' p a) clear [ ColorBuffer, DepthBuffer ] loadIdentity -- clear the matrix axis <- get (axisOf state) case axis of AxisX -> rotated (-90) (0, 1, 0) AxisY -> rotated ( 90) (1, 0, 0) AxisZ -> return () flip mapM_ (zip os collides) $ \ ((p, v, a), c) -> do preservingMatrix $ do translated' p if c then color3d (1, 0, 0) else color3d (0, 1, 1) a swapBuffers myInit :: IO () myInit = do clearColor $= Color4 0 0 0 0 shadeModel $= Smooth polygonMode $= (Fill, Fill) -- fill front and back colorMaterial $= Just (Front, AmbientAndDiffuse) position (Light 0) $= light0Position ambient (Light 0) $= light0Ambient diffuse (Light 0) $= light0Diffuse lighting $= Enabled light (Light 0) $= Enabled normalize $= Enabled depthFunc $= Just Less keyboard :: State -> KeyboardMouseCallback keyboard state (Char '\27') Down _ _ = exitWith ExitSuccess keyboard state (Char 'x') Down _ _ = axisOf state $= AxisX keyboard state (Char 'y') Down _ _ = axisOf state $= AxisY keyboard state (Char 'z') Down _ _ = axisOf state $= AxisZ keyboard state _ _ _ _ = return () -- utils randomVector3d :: IO Vector3d randomVector3d = do x <- randomRIO (-1, 1) y <- randomRIO (-1, 1) z <- randomRIO (-1, 1) return $ Vector3 x y z type Vector3d = Vector3 GLdouble uncurry3 f (a, b, c) = f a b c color3d' = color :: Color3 GLdouble -> IO () color3d = color3d' . uncurry3 Color3 scaled' = scale :: GLdouble -> GLdouble -> GLdouble -> IO () scaled = uncurry3 scaled' vertex3d' = vertex :: Vertex3 GLdouble -> IO () vertex3d = vertex3d' . uncurry3 Vertex3 normal3d' = normal :: Normal3 GLdouble -> IO () normal3d = normal3d' . uncurry3 Normal3 rotated' = rotate :: GLdouble -> Vector3d -> IO () rotated a = rotated' a . uncurry3 Vector3 translated' = translate :: Vector3d -> IO () translated = translated' . uncurry3 Vector3 magnitude (Vector3 x y z) = sqrt (x*x + y*y + z*z) s `vecScale` Vector3 x y z = Vector3 (s*x) (s*y) (s*z) Vector3 x1 y1 z1 `vecAdd` Vector3 x2 y2 z2 = Vector3 (x1+x2) (y1+y2) (z1+z2)
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace LoRaWan.Tests.Unit.LoRaTools.Regions { using System.Collections.Generic; using System.Linq; using global::LoRaTools.Regions; using static LoRaWan.DataRateIndex; using static LoRaWan.Metric; public static class RegionCN470RP2TestData { private static readonly Region region = RegionManager.CN470RP2; public static IEnumerable<object[]> TestRegionFrequencyData => from p in new[] { // 20 MHz plan A new { Frequency = new { Input = Mega(470.3), Output = Mega(483.9) }, JoinChannel = 0 }, new { Frequency = new { Input = Mega(471.5), Output = Mega(485.1) }, JoinChannel = 1 }, new { Frequency = new { Input = Mega(476.5), Output = Mega(490.1) }, JoinChannel = 2 }, new { Frequency = new { Input = Mega(503.9), Output = Mega(490.7) }, JoinChannel = 3 }, new { Frequency = new { Input = Mega(503.5), Output = Mega(490.3) }, JoinChannel = 4 }, new { Frequency = new { Input = Mega(504.5), Output = Mega(491.3) }, JoinChannel = 5 }, new { Frequency = new { Input = Mega(509.7), Output = Mega(496.5) }, JoinChannel = 7 }, // 20 MHz plan B new { Frequency = new { Input = Mega(476.9), Output = Mega(476.9) }, JoinChannel = 8 }, new { Frequency = new { Input = Mega(479.9), Output = Mega(479.9) }, JoinChannel = 8 }, new { Frequency = new { Input = Mega(503.1), Output = Mega(503.1) }, JoinChannel = 9 }, // 26 MHz plan A new { Frequency = new { Input = Mega(470.3), Output = Mega(490.1) }, JoinChannel = 10 }, new { Frequency = new { Input = Mega(473.3), Output = Mega(493.1) }, JoinChannel = 11 }, new { Frequency = new { Input = Mega(475.1), Output = Mega(490.1) }, JoinChannel = 12 }, new { Frequency = new { Input = Mega(471.1), Output = Mega(490.9) }, JoinChannel = 14 }, // 26 MHz plan B new { Frequency = new { Input = Mega(480.3), Output = Mega(500.1) }, JoinChannel = 15 }, new { Frequency = new { Input = Mega(485.1), Output = Mega(500.1) }, JoinChannel = 16 }, new { Frequency = new { Input = Mega(485.3), Output = Mega(500.3) }, JoinChannel = 17 }, new { Frequency = new { Input = Mega(489.7), Output = Mega(504.7) }, JoinChannel = 18 }, new { Frequency = new { Input = Mega(488.9), Output = Mega(503.9) }, JoinChannel = 19 }, } select new object[] { region, p.Frequency.Input, /* data rate */ 0, p.Frequency.Output, p.JoinChannel }; public static IEnumerable<object[]> TestRegionDataRateData => new List<object[]> { new object[] { region, 0, 0, 0 }, new object[] { region, 1, 1, 0 }, new object[] { region, 2, 2, 0 }, new object[] { region, 6, 6, 0 }, new object[] { region, 2, 1, 1 }, new object[] { region, 3, 1, 2 }, new object[] { region, 4, 2, 2 }, new object[] { region, 6, 3, 3 }, }; public static IEnumerable<object[]> TestRegionDataRateData_InvalidOffset => new List<object[]> { new object[] { region, 0, 6 }, new object[] { region, 2, 10 }, }; public static IEnumerable<object[]> TestRegionLimitData => from x in new (Hertz Frequency, ushort DataRate)[] { (Mega(470.0), 8), (Mega(510.0), 10), (Mega(509.8), 100), (Mega(469.9), 110), } select new object[] { region, x.Frequency, x.DataRate, 0 }; public static IEnumerable<object[]> TestRegionMaxPayloadLengthData => new List<object[]> { new object[] { region, 1, 31 }, new object[] { region, 2, 94 }, new object[] { region, 3, 192 }, new object[] { region, 4, 250 }, new object[] { region, 5, 250 }, new object[] { region, 6, 250 }, new object[] { region, 7, 250 }, }; public static IEnumerable<object[]> TestDownstreamRX2FrequencyData => from x in new[] { // OTAA devices new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 485.3, JoinChannel = new { Reported = (int?) 0, Desired = (int?)null } }, new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 486.9, JoinChannel = new { Reported = (int?) 1, Desired = (int?)9 } }, new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 496.5, JoinChannel = new { Reported = (int?) 7, Desired = (int?)null } }, new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 498.3, JoinChannel = new { Reported = (int?) 9, Desired = (int?)8 } }, new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 492.5, JoinChannel = new { Reported = (int?)10, Desired = (int?)null } }, new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 492.5, JoinChannel = new { Reported = (int?)12, Desired = (int?)null } }, new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 492.5, JoinChannel = new { Reported = (int?)14, Desired = (int?)14 } }, new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 502.5, JoinChannel = new { Reported = (int?)17, Desired = (int?)null } }, new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 502.5, JoinChannel = new { Reported = (int?)19, Desired = (int?)18 } }, new { NwkSrvRx2Freq = 498.3 , ExpectedFreq = 498.3, JoinChannel = new { Reported = (int?) 7, Desired = (int?)null } }, new { NwkSrvRx2Freq = 485.3 , ExpectedFreq = 485.3, JoinChannel = new { Reported = (int?)15, Desired = (int?)null } }, new { NwkSrvRx2Freq = 492.5 , ExpectedFreq = 492.5, JoinChannel = new { Reported = (int?)15, Desired = (int?)15 } }, // ABP devices new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 486.9, JoinChannel = new { Reported = (int?)null, Desired = (int?)0 } }, new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 486.9, JoinChannel = new { Reported = (int?)null, Desired = (int?)7 } }, new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 498.3, JoinChannel = new { Reported = (int?)null, Desired = (int?)8 } }, new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 498.3, JoinChannel = new { Reported = (int?)null, Desired = (int?)9 } }, new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 492.5, JoinChannel = new { Reported = (int?)null, Desired = (int?)14 } }, new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 502.5, JoinChannel = new { Reported = (int?)null, Desired = (int?)15 } }, new { NwkSrvRx2Freq = double.NaN, ExpectedFreq = 502.5, JoinChannel = new { Reported = (int?)null, Desired = (int?)19 } }, new { NwkSrvRx2Freq = 486.9 , ExpectedFreq = 486.9, JoinChannel = new { Reported = (int?)null, Desired = (int?)12 } }, new { NwkSrvRx2Freq = 502.5 , ExpectedFreq = 502.5, JoinChannel = new { Reported = (int?)null, Desired = (int?)17 } }, } select new object[] { region, !double.IsNaN(x.NwkSrvRx2Freq) ? Hertz.Mega(x.NwkSrvRx2Freq) : (Hertz?)null, Hertz.Mega(x.ExpectedFreq), x.JoinChannel.Reported, x.JoinChannel.Desired, }; public static IEnumerable<object[]> TestDownstreamRX2DataRateData => new List<object[]> { new object[] { region, null, null, DR1, 0, null }, new object[] { region, null, null, DR1, 8, null }, new object[] { region, null, null, DR1, 10, null }, new object[] { region, null, null, DR1, 19, null }, new object[] { region, null, null, DR1, null, 5 }, new object[] { region, null, null, DR1, null, 12 }, new object[] { region, null, null, DR1, 10, 14 }, new object[] { region, null, DR2 , DR2, 0, null }, new object[] { region, DR3 , null, DR3, 0, null }, new object[] { region, DR3 , DR2 , DR2, 0, null }, new object[] { region, DR4 , DR3 , DR3, 0, 8 }, new object[] { region, null, DR9 , DR1, 11, null }, }; public static IEnumerable<object[]> TestTranslateToRegionData => new List<object[]> { new object[] { region, LoRaRegionType.CN470RP2 }, }; public static IEnumerable<object[]> TestTryGetJoinChannelIndexData => from x in new[] { new { Freq = 470.9, ExpectedIndex = 0 }, new { Freq = 472.5, ExpectedIndex = 1 }, new { Freq = 475.7, ExpectedIndex = 3 }, new { Freq = 507.3, ExpectedIndex = 6 }, new { Freq = 479.9, ExpectedIndex = 8 }, new { Freq = 499.9, ExpectedIndex = 9 }, new { Freq = 478.3, ExpectedIndex = 14 }, new { Freq = 482.3, ExpectedIndex = 16 }, new { Freq = 486.3, ExpectedIndex = 18 }, new { Freq = 488.3, ExpectedIndex = 19 }, } select new object[] { region, Hertz.Mega(x.Freq), x.ExpectedIndex, }; public static IEnumerable<object[]> TestIsValidRX1DROffsetData => new List<object[]> { new object[] { region, 0, true }, new object[] { region, 5, true }, new object[] { region, 6, false }, }; public static IEnumerable<object[]> TestIsDRIndexWithinAcceptableValuesData => new List<object[]> { new object[] { region, DR0, true, true }, new object[] { region, DR2, true, true }, new object[] { region, DR7, true, true }, new object[] { region, DR0, false, true }, new object[] { region, DR2, false, true }, new object[] { region, DR7, false, true }, new object[] { region, DR9, true, false }, new object[] { region, DR10, false, false }, new object[] { region, null, false, false }, }; } }
require 'spec_helper' describe "Quill" do it "is at release 0.0.1" do Quill::VERSION.should == "0.0.1" end end
#!/usr/bin/env ruby # # Put description here # # # # # require 'swig_assert' require 'primitive_types' include Primitive_types raise RuntimeError if val_uchar(255) != 255 fail = 0 begin val_uchar(-1) rescue RangeError fail = 1 end fail = 0 begin val_uchar(256) rescue RangeError fail = 1 end raise RuntimeError if fail != 1 fail = 0 begin val_uchar(256.0) rescue TypeError fail = 1 end raise RuntimeError if fail != 1 fail = 0 begin val_uchar("caca") rescue TypeError fail = 1 end raise RuntimeError if fail != 1 # Test a number which won't fit in a 32 bit integer and is represented # as a FIXNUM by Ruby. raise RuntimeError if val_double(51767811298) != 51767811298 raise RuntimeError if val_double_2(1.0) != 4.0 raise RuntimeError if val_double_2(1) != 4 raise RuntimeError if val_double_2(1,1) != 2 fail = 0 begin val_double_2("1.0",1.0) rescue fail = 1 end raise RuntimeError if fail != 1 fail = 0 begin val_double_2(1.0,"1.0") rescue fail = 1 end raise RuntimeError if fail != 1 raise RuntimeError if val_float_2(1.0) != 4.0 raise RuntimeError if val_float_2(1) != 4 raise RuntimeError if val_float_2(1,1) != 2 fail = 0 begin val_float_2("1.0",1.0) rescue fail = 1 end raise RuntimeError if fail != 1 fail = 0 begin val_float_2(1.0,"1.0") rescue fail = 1 end raise RuntimeError if fail != 1
using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; namespace FoxTunes { public class DraggableSlider : Slider { public DraggableSlider() { this.IsMoveToPointEnabled = true; } public Track Track { get; private set; } public override void OnApplyTemplate() { base.OnApplyTemplate(); this.Track = this.Template.FindName("PART_Track", this) as Track; } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (e.LeftButton == MouseButtonState.Pressed) { this.Value = this.Track.ValueFromPoint(e.GetPosition(this.Track)); } } protected override void OnPreviewMouseDown(MouseButtonEventArgs e) { base.OnPreviewMouseDown(e); if (e.ChangedButton == MouseButton.Left) { ((UIElement)e.OriginalSource).CaptureMouse(); } } protected override void OnPreviewMouseUp(MouseButtonEventArgs e) { base.OnPreviewMouseUp(e); if (e.ChangedButton == MouseButton.Left) { ((UIElement)e.OriginalSource).ReleaseMouseCapture(); } } } }
/* * Copyright 2013 Google Inc. * * 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 com.google.maps.android; import com.google.android.gms.maps.model.LatLng; import java.util.List; import java.util.ArrayList; public class PolyUtil { /** * Decodes an encoded path string into a sequence of LatLngs. */ public static List<LatLng> decode(final String encodedPath) { int len = encodedPath.length(); // For speed we preallocate to an upper bound on the final length, then // truncate the array before returning. final List<LatLng> path = new ArrayList<LatLng>(); int index = 0; int lat = 0; int lng = 0; for (int pointIndex = 0; index < len; ++pointIndex) { int result = 1; int shift = 0; int b; do { b = encodedPath.charAt(index++) - 63 - 1; result += b << shift; shift += 5; } while (b >= 0x1f); lat += (result & 1) != 0 ? ~(result >> 1) : (result >> 1); result = 1; shift = 0; do { b = encodedPath.charAt(index++) - 63 - 1; result += b << shift; shift += 5; } while (b >= 0x1f); lng += (result & 1) != 0 ? ~(result >> 1) : (result >> 1); path.add(new LatLng(lat * 1e-5, lng * 1e-5)); } return path; } }
SELECT mov.id, mov.name FROM movies mov INNER JOIN genres gen ON mov.id_genres = gen.id WHERE gen.description = 'Action';
package edu.galileo.android.photofeed.photolist.ui; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable; import java.io.ByteArrayOutputStream; import javax.inject.Inject; import butterknife.Bind; import butterknife.ButterKnife; import edu.galileo.android.photofeed.PhotoFeedApp; import edu.galileo.android.photofeed.R; import edu.galileo.android.photofeed.entities.Photo; import edu.galileo.android.photofeed.photolist.PhotoListPresenter; import edu.galileo.android.photofeed.photolist.ui.adapters.OnItemClickListener; import edu.galileo.android.photofeed.photolist.ui.adapters.PhotoListAdapter; public class PhotoListFragment extends Fragment implements PhotoListView, OnItemClickListener { @Bind(R.id.container) RelativeLayout container; @Bind(R.id.recyclerView) RecyclerView recyclerView; @Bind(R.id.progressBar) ProgressBar progressBar; @Inject PhotoListAdapter adapter; @Inject PhotoListPresenter presenter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupInjection(); presenter.onCreate(); } @Override public void onDestroy() { presenter.unsubscribe(); presenter.onDestroy(); super.onDestroy(); } private void setupRecyclerView() { recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.setAdapter(adapter); } private void setupInjection() { PhotoFeedApp app = (PhotoFeedApp) getActivity().getApplication(); app.getPhotoListComponent(this, this, this).inject(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_list, container, false); ButterKnife.bind(this, view); setupRecyclerView(); presenter.subscribe(); return view; } @Override public void onPhotosError(String error) { Snackbar.make(container, error, Snackbar.LENGTH_SHORT).show(); } @Override public void showList() { recyclerView.setVisibility(View.VISIBLE); } @Override public void hideList() { recyclerView.setVisibility(View.GONE); } @Override public void showProgress() { progressBar.setVisibility(View.VISIBLE); } @Override public void hideProgress() { progressBar.setVisibility(View.GONE); } @Override public void addPhoto(Photo photo) { adapter.addPhoto(photo); } @Override public void removePhoto(Photo photo) { adapter.removePhoto(photo); } @Override public void onPlaceClick(Photo photo) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("geo:" + photo.getLatitutde() +"," + photo.getLongitude())); if (intent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(intent); } } @Override public void onShareClick(Photo photo, ImageView img) { Bitmap bitmap = ((GlideBitmapDrawable)img.getDrawable()).getBitmap(); Intent share = new Intent(Intent.ACTION_SEND); share.setType("image/jpeg"); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, null, null); Uri imageUri = Uri.parse(path); share.putExtra(Intent.EXTRA_STREAM, imageUri); startActivity(Intent.createChooser(share, getString(R.string.photolist_message_share))); } @Override public void onDeleteClick(Photo photo) { presenter.removePhoto(photo); } }
remote_directory '/tmp/remote_test_dir' do source 'remote_dir' owner 'root' group 'root' mode '0755' action :create end
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading.Tasks; namespace FolderSize { class FolderSize { static void Main(string[] args) { using(StreamWriter writer = new StreamWriter("output.txt")) { decimal size = 0M; foreach (var item in Directory.GetFiles("TestFolder")) { size += new FileInfo(item).Length; } size = (size / 1024) / 1024; writer.WriteLine(size); } } } }
import { useQuasar } from 'quasar' import { Ref } from '@vue/runtime-core/dist/runtime-core' import AltSourceDialog from '../components/AltSourceDialog.vue' export default function useAltSources ( altSources: Ref<Record<string, string>>, title: Ref<string>, newSources: Ref<Record<string, string> | undefined> ) { const $q = useQuasar() const openAltSourceDialog = () => { $q.dialog({ component: AltSourceDialog, componentProps: { sources: newSources.value || altSources.value || {}, initialSearch: title.value, searchPlaceholder: 'Search for a manga', manualPlaceholder: 'Or enter the url manually', confirmButton: 'Confirm' } }).onOk((sources: Record<string, string>) => { newSources.value = sources }) } const saveSources = (): boolean => { if (newSources.value === undefined) return false altSources.value = newSources.value return true } return { saveSources, openAltSourceDialog } }
package es.joseluisgs.kotlinspringbootrestservice.controllers.categorias import es.joseluisgs.kotlinspringbootrestservice.config.APIConfig import es.joseluisgs.kotlinspringbootrestservice.dto.categorias.CategoriaCreateDTO import es.joseluisgs.kotlinspringbootrestservice.dto.categorias.CategoriaProductosDTO import es.joseluisgs.kotlinspringbootrestservice.errors.categorias.CategoriaBadRequestException import es.joseluisgs.kotlinspringbootrestservice.errors.categorias.CategoriaNotFoundException import es.joseluisgs.kotlinspringbootrestservice.mappers.productos.ProductosMapper import es.joseluisgs.kotlinspringbootrestservice.models.Categoria import es.joseluisgs.kotlinspringbootrestservice.repositories.categorias.CategoriasRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* @RestController @RequestMapping(APIConfig.API_PATH + "/categorias") // Le aplico DI por constructor class CategoriasRestController @Autowired constructor( private val categoriasRepository: CategoriasRepository, private val productosMapper: ProductosMapper, ) { @GetMapping("") fun getAll(): ResponseEntity<MutableList<Categoria>> { val categorias = categoriasRepository.findAll() return ResponseEntity.ok(categorias) } @GetMapping("/{id}") fun getById(@PathVariable id: Long): ResponseEntity<Categoria> { val categoria = categoriasRepository.findById(id).orElseThrow { CategoriaNotFoundException(id) } return ResponseEntity.ok(categoria) } @PostMapping("") fun create(@RequestBody categoria: CategoriaCreateDTO): ResponseEntity<Categoria> { checkCategoriaData(categoria.nombre) val newCategoria = Categoria(categoria.nombre) try { val result = categoriasRepository.save(newCategoria) return ResponseEntity.status(HttpStatus.CREATED).body(result) } catch (e: Exception) { throw CategoriaBadRequestException( "Error: Insertar Categoria", "Campos incorrectos o nombre existente. ${e.message}" ) } } @PutMapping("/{id}") fun update(@RequestBody categoria: CategoriaCreateDTO, @PathVariable id: Long): ResponseEntity<Categoria> { checkCategoriaData(categoria.nombre) val updateCategoria = categoriasRepository.findById(id).orElseGet { throw CategoriaNotFoundException(id) } updateCategoria.nombre = categoria.nombre try { return ResponseEntity.ok(categoriasRepository.save(updateCategoria)) } catch (e: Exception) { throw CategoriaBadRequestException( "Error: Actualizar Categoria", "Campos incorrectos o nombre existente. ${e.message}" ) } } @DeleteMapping("/{id}") fun delete(@PathVariable id: Long): ResponseEntity<Categoria> { val categoria = categoriasRepository.findById(id).orElseGet { throw CategoriaNotFoundException(id) } val numberProductos = categoriasRepository.countByProductos(id) if (numberProductos > 0) { throw CategoriaBadRequestException( "Categoria con id $id", "Está asociadoa a $numberProductos producto(s)" ) } try { categoriasRepository.delete(categoria) return ResponseEntity.ok(categoria) } catch (e: Exception) { throw CategoriaBadRequestException( "Error: Eliminar Categoria", "Id de categoria inexistente o asociado a un producto. ${e.message}" ) } } @GetMapping("/{id}/productos") fun getProductos(@PathVariable id: Long): ResponseEntity<CategoriaProductosDTO> { val categoria = categoriasRepository.findById(id).orElseGet { throw CategoriaNotFoundException(id) } val productos = categoriasRepository.findProductosByCategoria(id) val res = CategoriaProductosDTO( categoria.id, categoria.nombre, productosMapper.toDTO(productos) ) try { return ResponseEntity.ok(res) } catch (e: Exception) { throw CategoriaBadRequestException( "Error: Obtener Productos", "Id de categoria inexistente. ${e.message}" ) } } private fun checkCategoriaData(nombre: String) { if (nombre.trim().isBlank()) { throw CategoriaBadRequestException("Nombre", "El nombre es obligatorio") } } }
// Copyright 2017, Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package tabletenv import ( "golang.org/x/net/context" ) type localContextKey int // LocalContext returns a context that's local to the process. func LocalContext() context.Context { return context.WithValue(context.Background(), localContextKey(0), 0) } // IsLocalContext returns true if the context is based on LocalContext. func IsLocalContext(ctx context.Context) bool { return ctx.Value(localContextKey(0)) != nil }
package com.example.plugins.koin import com.example.plugins.koin.modules.defaultModules import io.ktor.server.application.Application import io.ktor.server.application.install import org.koin.ktor.ext.Koin /** * Installs and configures the [Koin] plugin. */ fun Application.configureKoin() { install(KoinPlugin) { modules(defaultModules) } }
## Example implementation personal user settings Application with an example of implementing personal user settings via json 'settings' field.
# -*- encoding: utf-8 -*- # 2016/01/23 # ・公開 # agi1, agi2が指定されてない場合 if ARGV.size < 2 puts "Usage: #{File.basename(__FILE__, ".*")} agi1 agi2 [number=100000]" exit end $option = { agi1: ARGV[0].to_i, agi2: ARGV[1].to_i, number: ARGV.size > 2 ? ARGV[2].to_i : 100000, } # $psdq7rnd_state = 0 $psdq7rnd_state = rand(0..0xffffffff) # 乱数の状態 # PS版DQ7の乱数生成 rand(0..32767) def psdq7rnd() $psdq7rnd_state = ($psdq7rnd_state * 0x41c64e6d + 0x3039) & 0xffffffff return ($psdq7rnd_state >> 16) & 0x7fff end # 0..max-1の乱数を返す rand(max) def psdq7rnd_max(max) return (((psdq7rnd() * max) & 0xffffffff) >> 15) & 0xffff end # 範囲内の乱数を返す rand(range) def psdq7rnd_range(range) return range.min + psdq7rnd_max(range.max - range.min + 1) end # 行動順値のとりうる範囲を返す def make_speed_range(agi) [1, agi].max*32 .. [1, agi].max*64 end # $option[:speed_range] = make_speed_range($option[:target_agi]) # 行動順値を求める def make_speed(agi) psdq7rnd_range(make_speed_range(agi)) end # 試行回数で先攻率を求める def calc_preemptive_rate(a, b, number=10000) number.times.count { make_speed(a) >= make_speed(b) }.to_f / number end # おてうさんの近似式(http://oteu.net/blog/archives/2169)で先攻率を求める def calc_preemptive_rate_by_formula(a, b) a = [1, a].max b = [1, b].max if a > b * 2 1.0 elsif b > a * 2 0.0 elsif a >= b 1.0 - ((2 * b - a) ** 2).to_f / (2 * a * b) else ((2 * a - b) ** 2).to_f / (2 * b * a) end end def main rate_by_formula = calc_preemptive_rate_by_formula($option[:agi1], $option[:agi2]) rate = calc_preemptive_rate($option[:agi1], $option[:agi2], $option[:number]) puts "近似式\t%.2f%%" % [rate_by_formula * 100] puts "%d回試行\t%.2f%%" % [$option[:number], rate * 100] end # puts $option main()
using NHibernate; using System; using TauCode.Domain.NHibernate.Tests.Domain.Users; namespace TauCode.Domain.NHibernate.Tests.Base { public static class TestHelper { public static readonly UserId AkId = new UserId("ca2c8f0a-00eb-49a3-b495-cd14fe830b0f"); public static readonly UserId OliaId = new UserId("54bdcb8b-f3d9-4944-97d6-e5716dc1fe66"); public static readonly UserId IraId = new UserId("413d4230-e179-4c0d-a6e6-fc641c1d9c24"); public static readonly Guid NonExistingId = new Guid("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"); public static void DoInTransaction(this ISession session, Action action) { using (var tran = session.BeginTransaction()) { action(); tran.Commit(); } } } }
package httpserver import ( "log" "os" "github.com/ilgooz/service-http-server/httpserver/server" "github.com/ilgooz/service-http-server/x/xhttp" "github.com/sirupsen/logrus" ) // requestEventData is request event's data. type requestEventData struct { // SessionID is the of corresponding request.. SessionID string `json:"sessionID"` // Method is the request's method. Method string `json:"method"` // Host is the request's host. Host string `json:"host"` // Path is requested page's path. Path string `json:"path"` // QS is the query string data. QS string `json:"qs"` // Body is the request data. Body string `json:"body"` // IP address of client. IP string `json:"ip"` } func (s *HTTPServerService) handleSession(ses *server.Session) { logrus.WithFields(logrus.Fields{ "method": ses.Req.Method, "path": ses.Req.URL.Path, }).Info("new request") if os.Getenv("ENABLE_CORS") == "true" { xhttp.CORS(ses.W) } if ses.Req.Method == "OPTIONS" { ses.End() return } // use cached response if exists. c := s.findCache(ses.Req.Method, ses.Req.URL.Path) if c != nil { if err := sendResponse(ses.W, response{ code: c.code, mimeType: c.mimeType, content: c.content, }); err != nil { log.Println(err) } ses.End() logrus.WithFields(logrus.Fields{ "method": ses.Req.Method, "path": ses.Req.URL.Path, }).Info("responded from cache") return } qs, err := xhttp.JSONQuery(ses.Req) if err != nil { ses.End() log.Println(err) return } body, err := xhttp.BodyAll(ses.Req) if err != nil { ses.End() log.Println(err) return } s.addSession(ses) if err := s.service.Emit("request", requestEventData{ SessionID: ses.ID, Method: ses.Req.Method, Host: ses.Req.Host, Path: ses.Req.URL.Path, QS: string(qs), Body: string(body), IP: ses.Req.RemoteAddr, }); err != nil { log.Println(err) s.removeSession(ses.ID) } } func (s *HTTPServerService) addSession(ses *server.Session) { s.ms.Lock() defer s.ms.Unlock() s.sessions[ses.ID] = ses } func (s *HTTPServerService) getSession(id string) (ses *server.Session, found bool) { s.ms.RLock() defer s.ms.RUnlock() ses, ok := s.sessions[id] return ses, ok } func (s *HTTPServerService) removeSession(id string) { s.ms.Lock() defer s.ms.Unlock() delete(s.sessions, id) }
--26. Write a SQL query to display the minimal employee salary by department and job title -- along with the name of some of the employees that take it. USE TelerikAcademy GO SELECT empl.FirstName + ' ' + empl.LastName AS 'Employee Name', empl.Salary, dep.Name AS 'Department', empl.JobTitle FROM Employees empl INNER JOIN Departments dep ON empl.DepartmentID = dep.DepartmentID WHERE empl.Salary IN (SELECT MIN(e.Salary) FROM Employees e WHERE e.DepartmentID = empl.DepartmentID GROUP BY e.DepartmentID, e.JobTitle )
#!/usr/bin/python """ CstrikeRCON: An HLDS1-based Cstrike servers RCON querying library """ """ fully tested with Counter-Strike 1.6 (unit test included [test.py]) """ __author__ = "Alex Vanyan" __copyright__ = "Copyright 2013 alex-v.net" __version__ = "1.0.1" __status__ = "First Release" # exceptions... # base rcon exception type class RCON_Exception(Exception): def __init__(self, message): self.message = message def __str__(self): return str(self.message) class RCON_NoConnectionException(RCON_Exception): pass class RCON_NoPacketReceivedException(RCON_Exception): pass class RCON_BadPasswordException(RCON_Exception): pass class RCON_DataFormatMismatchException(RCON_Exception): pass class RCON_NoChallengeException(RCON_Exception): pass class RCON_NoStatusException(RCON_Exception): pass # dependencies... import socket import re class CstrikeRCON: _instance = None # class member variables RCONchallenge = None RCONpasswd = None status = {} players = {} rgx = { "challenge": "challenge\srcon\s(\d+)", "rcon_passwd_fail": "Bad\srcon_password", "status": "hostname.+\x00", "player_count": "(\d+)[^\d]+(\d+)", "map": "^[^\s]+", "map_coords": "(\d+)\sx[^\d]+(\d+)\sy[^\d]+(\d+)\sz" } # singleton'ize the class def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(CstrikeRcon, cls).__new__(cls, *args, **kwargs) return cls._instance # open datagram socket at class initialization stage def __init__(self, host, port=27015, passwd=""): self.sockinfo = (host, port) self.RCONpasswd = passwd self.datagram = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #This creates socket self.datagram.settimeout(2.0) if not self.datagram: raise RCON_NoConnectionException("Could not connect to the cstrike server") # get rcon challenge id def getChallenge(self): challenge = self.dispatchDatagram("challenge rcon").receiveDatagram("challenge") if challenge and challenge[0].isdigit(): return int(challenge[0]) else: raise RCON_NoChallengeException("Could not get RCON challenge") def getServerInfo(self): if not self.RCONchallenge: try: self.RCONchallenge = self.getChallenge() except RCON_NoChallengeException as e: return str(e) passwd = str(self.RCONpasswd) passwdStr = ' "' + passwd + '"' if passwd else "" status = self.dispatchDatagram("rcon " + str(self.RCONchallenge) + passwdStr + " status").receiveDatagram("status") self.closeSocket() status = "\n".join(status).strip("\xFF\x00").split("\n") startPlayers = False for i,v in enumerate(status): if status[i].strip(" \t\n\r") == '': continue statusSplit = status[i].split(":") if status[i][0] != "#" and len(statusSplit) > 1: statusSplit[0] = statusSplit[0].strip(" \t\n\r") statusSplit[1] = ":".join(statusSplit[1:]).strip(" \t\n\r") self.status[statusSplit[0]] = statusSplit[1] else: if status[i][0] == "#": playerArr = filter(None, [x.strip() for x in status[i][1:].split(" ")]) if not startPlayers: self.playerPattern = playerArr startPlayers = True else: playerName = playerArr[1][1:-1] playerPattern = self.playerPattern[1:] self.players[playerName] = {} self.players[playerName]["id"] = int(playerArr[0]) for i,v in enumerate(playerPattern): self.players[playerName][v] = playerArr[2 + i]; # prettify data for players dict tcpIP = self.players[playerName]["adr"].split(":") self.players[playerName]["ip"] = tcpIP[0] self.players[playerName]["port"] = tcpIP[1] self.players[playerName]["frags"] = self.players[playerName]["frag"] del self.players[playerName]["adr"] del self.players[playerName]["frag"] # prettify data for status dict tcpIP = self.status["tcp/ip"].split(":") playerCount = re.compile(self.rgx["player_count"]).findall(self.status["players"]) mapInfo = self.status["map"].split(":") map = re.compile(self.rgx["map"]).findall(mapInfo[0])[0] coords = list(re.compile(self.rgx["map_coords"]).findall(mapInfo[1])[0]) self.status["name"] = self.status["hostname"] self.status["ip"] = tcpIP[0] self.status["port"] = tcpIP[1] self.status["map"] = map self.status["coords"] = coords self.status["players"] = "/".join(playerCount[0]) del self.status["hostname"] del self.status["tcp/ip"] return {"status": self.status, "players": self.players} def checkRconPasswd(self, data): rgx = re.compile(self.rgx["rcon_passwd_fail"]) if type(data) == list: data = "".join(data) find = rgx.findall(data) if find and len(find) > 0: raise RCON_BadPasswordException("Rcon password is wrong") # generic request builder def buildRequest(self, request): initBytes = "\xFF\xFF\xFF\xFF" finalBytes = "\n" return initBytes + request + finalBytes def receiveDatagram(self, expect): # start reading from UDP socket while 1: try: data, addr = self.datagram.recvfrom(1024) except socket.timeout: raise RCON_NoPacketReceivedException("Timeout trying to receive data") else: if expect != "challenge": self.checkRconPasswd(data) find = re.compile(self.rgx[expect], re.DOTALL).findall(data) if len(find) > 0: return find else: raise RCON_DataFormatMismatchException("RCON protocol data format may have Mismatch") def dispatchDatagram(self, data): self.datagram.sendto(self.buildRequest(data), self.sockinfo) return self def closeSocket(self): self.datagram.close() return self
import { Route, Switch, Redirect } from "react-router-dom"; import AboutPage from "../components/AboutPage"; import LoginPage from "./LoginPage"; import NotFoundPage from "../components/NotFoundPage"; import React from "react"; import { hot } from "react-hot-loader"; import { Dashboard } from "./Dashboard"; import ProjectContainer from "./project/ProjectContainer"; import { isUserLoggedIn } from "../redux/reducers/authReducer"; import { connect } from 'react-redux'; import { isLoadingSelector } from "../redux/reducers"; import { CircularProgress } from "@material-ui/core"; interface AppProps { isLoggedIn: boolean; isLoading: boolean; } const Loading = ({ isLoading }) => { if (!isLoading) { return <></>; } return ( <div style={{ top: 0, right: 0, bottom: 0, left: 0, position: 'fixed', width: '100%', height: '100%', backgroundColor: 'rgba(0, 0, 0, 0.2)', display: 'flex', justifyContent: 'center', alignItems: 'center', zIndex: 1201, }} > <CircularProgress size={100} thickness={4} /> </div> ); } class App extends React.Component<AppProps> { checkLoggedInUser = () => { if (!this.props.isLoggedIn) { return ( <Redirect to={'/login'} /> ); } } render() { return ( <div> {/* <div> <NavLink exact to="/" activeStyle={activeStyle}>Home</NavLink> {' | '} <NavLink to="/about" activeStyle={activeStyle}>About</NavLink> </div> */} <Switch> <Route exact path="/login" component={LoginPage} /> <Route exact path="/" component={Dashboard} /> <Route exact path="/newproject" component={ProjectContainer} /> <Route path="/about" component={AboutPage} /> <Route component={NotFoundPage} /> </Switch> {this.checkLoggedInUser()} <Loading isLoading={this.props.isLoading} /> </div> ); } } const mapStateToProps = (state) => ({ isLoggedIn: isUserLoggedIn(state), isLoading: isLoadingSelector(state), }) export default hot(module)(connect( mapStateToProps )(App));
package kekmech.ru.feed import android.content.Context import androidx.appcompat.app.AlertDialog import androidx.lifecycle.LifecycleOwner import kekmech.ru.coreui.adapter.BaseAdapter interface IFeedFragment : LifecycleOwner { var requiredAction: String var onEditListener: () -> Unit var bottomReachListener: () -> Unit fun withinContext(listener: (context: Context) -> Unit) fun setStatus(title: String, dayInfo: String, weekInfo: String) fun showEditDialog(dialog: AlertDialog) fun updateAdapterIfNull(adapter: BaseAdapter) fun unlock() fun showMenu() fun hideMenu() fun updateMenu(menuAdapter: BaseAdapter) }
Write-Host '----> pwsh.ps1' -ForegroundColor Green ## ## Azure PowerShell Modules for PowerShell Core ## # https://docs.microsoft.com/en-us/powershell/azure/install-az-ps?view=azurermps-6.13.0 Install-Module -Verbose -AllowClobber -Force Az # To uninstall, see here: # https://docs.microsoft.com/en-us/powershell/azure/uninstall-azurerm-ps?view=azurermps-6.13.0 ## ## AWS Tools ## https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up-linux-mac.html Write-Host '----> AWS Tools for PowerShell Core' -ForegroundColor Green Install-Module -Verbose -AllowClobber -Force AWSPowerShell.NetCore # Install other PowerShell modules here ## YAML Install-Module -Verbose -AllowClobber -Force powershell-yaml Write-Host '----> Installed Modules' -ForegroundColor Green Get-InstalledModule | Select-Object Name, Version | Sort
# compile closure test source file $(npm bin)/tsc -p . # Run the Google Closure compiler java runnable with zone externs java -jar node_modules/google-closure-compiler/compiler.jar --flagfile 'scripts/closure/closure_flagfile' --externs 'lib/closure/zone_externs.js' # the names of Zone exposed API should be kept correctly with zone externs, test program should exit with 0. node build/closure/closure-bundle.js if [ $? -eq 0 ] then echo "Successfully pass closure compiler with zone externs" else echo "failed to pass closure compiler with zone externs" exit 1 fi # Run the Google Closure compiler java runnable without zone externs. java -jar node_modules/google-closure-compiler/compiler.jar --flagfile 'scripts/closure/closure_flagfile' # the names of Zone exposed API should be renamed and fail to be executed, test program should exit with 1. node build/closure/closure-bundle.js if [ $? -eq 1 ] then echo "Successfully detect closure compiler error without zone externs" else echo "failed to detect closure compiler error without zone externs" exit 1 fi exit 0
package com.airbnb.common.ml.strategy.params import org.apache.spark.sql.Row import com.airbnb.common.ml.strategy.config.TrainingOptions trait StrategyParams [T] extends Serializable { def apply(update: Array[Double]): StrategyParams[T] def params: Array[Double] def getDefaultParams(trainingOptions: TrainingOptions): StrategyParams[T] // default all use field params in hive def parseParamsFromHiveRow(row: Row): StrategyParams [T] = { this(row.getAs[scala.collection.mutable.WrappedArray[Double]]("params").toArray) } def score(example: T): Double def updatedParams(grad: Array[Double], option: TrainingOptions): StrategyParams[T] = { // Project parameters to boxed constraints, very essential to limit parameter feasibly region val update = params.zip(grad).map(x=>x._1-x._2). zip(option.min).map(x => math.max(x._1, x._2)). zip(option.max).map(x => math.min(x._1, x._2)) // project to additional constraints projectToAdditionalConstraints(update, option) this(update) } def projectToAdditionalConstraints(param: Array[Double], option: TrainingOptions): Unit = { // note: the constrained region has to be a convex hull // for now, we are just project it to a linear constraint: // b >= slope * a + intercept val slope: Double = option.additionalOptions.getOrElse("b_slope", 0d) .asInstanceOf[Number].doubleValue() val intercept: Double = option.additionalOptions.getOrElse("b_intercept", 0d) .asInstanceOf[Number].doubleValue() val bLowerBound = slope * param(0) + intercept // Project if the bound is larger than zero if (bLowerBound > 0d) { // also 0.5 <= b <= 1 val u = Math.max(Math.min(1d, bLowerBound), 0.5d) param(1) = Math.max(param(1), u) } } // computeGradient computes all gradients def computeGradient(grad: Double, example: T): Array[Double] def hasValidValue: Boolean = { valid(params) } def prettyPrint: String = { toString } // for save into ARRAY<DOUBLE> defined in strategy_model_dev_output // override it if not using same format or table override def toString: String = { params.mkString(StrategyParams.sepString) } /** * Check if all of the params in our param array are real numbers * * @param values params to check * @return true if none are invalid */ private def valid(values: Array[Double]): Boolean = { for(value <- values) { if (value.isNaN) { return false } } true } /* Used in parameter search pass in \t separated string format: id_key parameter_search_index parameters output ((id, parameter_search_index), StrategyParams) default */ def parseLine(line: String): ((java.lang.String, Int), StrategyParams[T]) = { val items: Array[String] = line.split("\t") assert(items.length == 3, s"line: $line ${items.mkString(",")}") val id = items(0) val paramIdx = items(1).toInt ((id, paramIdx), this(items(2).split(StrategyParams.sepString).map(_.toDouble))) } } object StrategyParams { val sepString = "\001" }
 namespace Microsoft.Extensions.DependencyInjection { internal record KeyedBridge<T> (T Target, string Key) : IKeyedBridge<T> where T : class; }
<?php namespace App\Services; use App\Serie; use Illuminate\Support\Facades\DB; use App\Season; class CreatorSerie { public function createSerie(string $nameSerie, int $qtdSeasons, int $epBySeason): Serie { DB::beginTransaction(); $serie = Serie::create(['name' => $nameSerie]); $this->createSeasons($qtdSeasons, $epBySeason, $serie); DB::commit(); return $serie; } private function createSeasons(int $qtdSeasons, int $epBySeason, Serie $serie): void{ for ($i=1; $i <= $qtdSeasons; $i++) { $season = $serie->seasons()->create(['number' => $i]); $this->createEpisodes($epBySeason, $season); } } private function createEpisodes(int $epBySeason, Season $season): void{ for ($j=1; $j <= $epBySeason; $j++) { $episode = $season->episodes()->create(['number' => $j]); } } }
-- ToMidi2: a module for allowing multiple tracks with the same GM instrument. -- Author: Donya Quick -- -- The writeMidi2 function allows use of the CustomInstrument constructor -- in a very specific way to permit two tracks that have the same instrument. -- The expected format is: -- -- CustomInstrument "GMInstrumentName UniqueIdentifier" -- -- For example: -- -- import Euterpea -- import Euterpea.IO.MIDI.ToMidi2 -- m = instrument (CustomInstrument "Flute A") (c 4 qn :+: d 4 qn) :=: -- instrument (CustomInstrument "Flute B") (c 5 qn) :=: -- instrument HonkyTonkPiano (rest hn :+: c 4 hn) -- main = writeMidi2 "test.mid" m -- -- This will create a MIDI file with three tracks, two of which are assigned -- the Flute instrument and the third with the HonkyTonkPiano instrument. -- -- Note: this module does NOT allow specification of particular track numbers. -- The order in which the tracks appear in the MIDI file is determined by the -- structure of the particular Music value. module Euterpea.IO.MIDI.ToMidi2 ( writeMidi2 , resolveInstrumentName ) where import Codec.Midi (FileType (MultiTrack, SingleTrack), Midi (Midi), TimeDiv (TicksPerBeat), fromAbsTime) import Data.List (elemIndex) import Data.Maybe (fromMaybe) import Euterpea.IO.MIDI.ExportMidiFile (exportMidiFile) import Euterpea.IO.MIDI.MEvent (MEvent (MEvent), eInst, perform) import Euterpea.IO.MIDI.ToMidi (UserPatchMap, allValid, defUpm, division, makeGMMap, mevsToMessages, splitByInst) import Euterpea.Music (InstrumentName (AcousticGrandPiano, CustomInstrument), Music, ToMusic1) instNameOnly :: String -> String instNameOnly [] = [] instNameOnly (x:xs) = if x == ' ' then [] else x : instNameOnly xs resolveInstrumentName :: InstrumentName -> InstrumentName resolveInstrumentName x@(CustomInstrument s) = if i >= 0 then allInsts !! i else x where i = fromMaybe (-1) . elemIndex iName $ show <$> allInsts allInsts = take 128 $ enumFrom AcousticGrandPiano iName = instNameOnly s resolveInstrumentName x = x resolveMEventInsts :: [(InstrumentName, [MEvent])] -> [(InstrumentName, [MEvent])] resolveMEventInsts = map f1 where f1 (iname, mevs) = (resolveInstrumentName iname, map f2 mevs) f2 mev = mev{eInst=resolveInstrumentName (eInst mev)} writeMidi2 :: ToMusic1 a => FilePath -> Music a -> IO () writeMidi2 fn m = exportMidiFile fn $ toMidiUPM2 defUpm $ perform m toMidiUPM2 :: UserPatchMap -> [MEvent] -> Midi toMidiUPM2 upm pf = Midi (if length split == 1 then SingleTrack else MultiTrack) (TicksPerBeat division) $ fromAbsTime . mevsToMessages rightMap <$> split where rightMap = if allValid upm insts then upm else makeGMMap insts insts = map fst split split = resolveMEventInsts $ splitByInst pf
// JS import Ajv from 'ajv' import { readFileSync } from 'fs' import { location, jsonSchema } from '@pixelpony/shared' // Type import { Share } from '@pixelpony/shared' let ajv = new Ajv() let schemaToValidator = <T>(schema: () => object | boolean) => { let validFunc: Ajv.ValidateFunction | undefined let validator = (input: unknown) => { if (!validFunc) { validFunc = ajv.compile(schema()) } let ok = validFunc(input) as boolean let data = input as T return ok ? { data } : { errors: validFunc.errors } } return validator } let schemaReader = (name: string) => () => { return JSON.parse( readFileSync(`${location}/${jsonSchema}/${name}.json`, 'utf-8'), ) } export const validate = { Share: schemaToValidator<Share>(schemaReader('Share')), } export type Validate = typeof validate
import { expect, fixture, html, waitUntil } from '@open-wc/testing'; import sinon from 'sinon'; // eslint-disable-next-line no-restricted-imports import { serialize } from '../../utilities/form'; import type SlTextarea from './textarea'; describe('<sl-textarea>', () => { it('should pass accessibility tests', async () => { const el = await fixture<SlTextarea>(html` <sl-textarea label="Name"></sl-textarea> `); await expect(el).to.be.accessible(); }); it('should be disabled with the disabled attribute', async () => { const el = await fixture<SlTextarea>(html` <sl-textarea disabled></sl-textarea> `); const textarea = el.shadowRoot!.querySelector<HTMLTextAreaElement>('[part="textarea"]')!; expect(textarea.disabled).to.be.true; }); it('should focus the textarea when clicking on the label', async () => { const el = await fixture<SlTextarea>(html` <sl-textarea label="Name"></sl-textarea> `); const label = el.shadowRoot!.querySelector('[part="form-control-label"]')!; const submitHandler = sinon.spy(); el.addEventListener('sl-focus', submitHandler); (label as HTMLLabelElement).click(); await waitUntil(() => submitHandler.calledOnce); expect(submitHandler).to.have.been.calledOnce; }); describe('when using constraint validation', () => { it('should be valid by default', async () => { const el = await fixture<SlTextarea>(html` <sl-textarea></sl-textarea> `); expect(el.invalid).to.be.false; }); it('should be invalid when required and empty', async () => { const el = await fixture<SlTextarea>(html` <sl-textarea required></sl-textarea> `); expect(el.invalid).to.be.true; }); it('should be invalid when required and after removing disabled ', async () => { const el = await fixture<SlTextarea>(html` <sl-textarea disabled required></sl-textarea> `); el.disabled = false; await el.updateComplete; expect(el.invalid).to.be.true; }); it('should be invalid when required and disabled is removed', async () => { const el = await fixture<SlTextarea>(html` <sl-textarea disabled required></sl-textarea> `); el.disabled = false; await el.updateComplete; expect(el.invalid).to.be.true; }); }); describe('when serializing', () => { it('should serialize its name and value with FormData', async () => { const form = await fixture<HTMLFormElement>(html` <form><sl-textarea name="a" value="1"></sl-textarea></form> `); const formData = new FormData(form); expect(formData.get('a')).to.equal('1'); }); it('should serialize its name and value with JSON', async () => { const form = await fixture<HTMLFormElement>(html` <form><sl-textarea name="a" value="1"></sl-textarea></form> `); const json = serialize(form); expect(json.a).to.equal('1'); }); }); });
package edu.utexas.clm.reconstructreader.reconstruct; import edu.utexas.clm.reconstructreader.Utils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import java.awt.geom.AffineTransform; import java.util.ArrayList; public class ReconstructSection { private final int index, oid; private final Document doc; private final ReconstructTranslator translator; private final ArrayList<ReconstructProfile> profiles; private final double mag; private double z; private double thickness; public ReconstructSection(final ReconstructTranslator t, final Document d) { double m; translator = t; //index = t.nextOID(); index = Integer.valueOf(d.getDocumentElement().getAttribute("index")); oid = t.nextOID(); doc = d; profiles = new ArrayList<ReconstructProfile>(); m = Utils.getMag(d); mag = Double.isNaN(m) ? t.getMag() : m; z = -1; thickness = -1; } public int getOID() { return oid; } public int getIndex() { return index; } public Document getDocument() { return doc; } public double getMag() { return mag; } public void addProfile(final ReconstructProfile rp) { profiles.add(rp); } public void setZ(double inZ) { z = inZ; } public double getThickness() { if (thickness < 0) { String thickStr = doc.getDocumentElement().getAttribute("thickness"); thickness = Double.valueOf(thickStr); } return thickness; } public double getPixelThickness() { return thickness / getMag(); } public void setThickness(double inThickness) { thickness = inThickness; } public void setZFromPrevious(ReconstructSection prev) { if (prev.getIndex() > getIndex()) { translator.log("Whoa! Sections not sorted!"); } setZ(prev.getZ() + getThickness() * (this.getIndex() - prev.getIndex())); } public double getZ() { return z; } public double getHeight() { NodeList imageList = getDocument().getElementsByTagName("Image"); double wh[] = Utils.getReconstructImageWH(imageList.item(0)); return Double.isNaN(wh[1]) ? translator.getStackHeight() : wh[1]; } public void appendXML(final StringBuilder sb) { //double mag = translator.getMag(); //int index = Integer.valueOf(doc.getDocumentElement().getAttribute("index")); //double aniso = th / mag; NodeList imageList = doc.getElementsByTagName("Image"); sb.append("<t2_layer oid=\"") .append(oid).append("\"\n" + "thickness=\"").append(getPixelThickness()).append("\"\n" + "z=\"").append(getZ()).append("\"\n" + "title=\"\"\n" + ">\n"); for (int i = 0; i < imageList.getLength(); ++i) { appendPatch(sb, (Element)imageList.item(i)); } for (ReconstructProfile profile : profiles) { profile.appendXML(sb); } sb.append("</t2_layer>\n"); } protected void appendPatch(final StringBuilder sb, final Element image) { Element rTransform = (Element)image.getParentNode(); double[] wh = Utils.getReconstructImageWH(image); double h = Double.isNaN(wh[1]) ? translator.getStackHeight() : wh[1]; double w = Double.isNaN(wh[0]) ? translator.getStackWidth() : wh[0]; AffineTransform trans; String src = image.getAttribute("src"); String transString; trans = Utils.reconstructTransform(rTransform, Double.valueOf(image.getAttribute("mag")), h); transString = Utils.transformToString(trans); sb.append("<t2_patch\n" + "oid=\"").append(translator.nextOID()).append("\"\n" + "width=\"").append(w).append("\"\n" + "height=\"").append(h).append("\"\n" + "transform=\"").append(transString).append("\"\n" + "title=\"").append(src).append("\"\n" + "links=\"\"\n" + "type=\"0\"\n" + "file_path=\"").append(src).append("\"\n" + "style=\"fill-opacity:1.0;stroke:#ffff00;\"\n" + "o_width=\"").append((int)w).append("\"\n" + "o_height=\"").append((int)h).append("\"\n" + "min=\"0.0\"\n" + "max=\"255.0\"\n" + ">\n" + "</t2_patch>\n"); } }
# TypeScript React MobX Inversify example ## Installation ``` git clone https://github.com/Corey-Maler/mobx-inversify-example cd mobx-inversify-example npm i node server.js ``` Open http://localhost:8888 ## Preview ![Preview](https://rawgithub.com/Corey-Maler/mobx-inversify-example/master/misc/screenshoot.PNG)
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_mentions/flutter_mentions.dart'; import 'package:flutter_progress_hud/flutter_progress_hud.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:pattern_formatter/pattern_formatter.dart'; import '../../../../models/token.dart'; import '../../../../utils/genius_toast.dart'; import '../../../../http/webclients/user_webclient.dart'; import '../../../../http/exceptions/http_exception.dart'; import '../../../../http/webclients/project_webclient.dart'; import '../../../../utils/navigator_util.dart'; import '../../../../models/tag.dart'; import '../../../../components/autocomplete_input.dart'; import '../../../../utils/application_colors.dart'; import '../../../../components/gradient_button.dart'; import '../../../../components/input_with_animation.dart'; import '../../../../models/user.dart'; import '../../../../models/project.dart'; import '../../../../http/webclients/tags_webclient.dart'; import '../../../../utils/convert.dart'; class ProjectForm extends StatefulWidget { final User user; final String type; final Project project; const ProjectForm({ Key key, @required this.user, this.type, this.project, }) : super(key: key); @override _ProjectFormState createState() => _ProjectFormState(); } class _ProjectFormState extends State<ProjectForm> { String _tagsInitState = ''; String _usernamesInitState = ''; final _titleController = TextEditingController(); final _institutionController = TextEditingController(); final _startDateController = TextEditingController(); final _abstractController = TextEditingController(); final _emailController = TextEditingController(); final _participantsFullNameController = TextEditingController(); final _tagsKey = GlobalKey<FlutterMentionsState>(); final _mainTeacherKey = GlobalKey<FlutterMentionsState>(); final _secondTeacherKey = GlobalKey<FlutterMentionsState>(); final _participantsKey = GlobalKey<FlutterMentionsState>(); final _tokenObject = Token(); final _navigator = NavigatorUtil(); @override void initState() { super.initState(); _verifyIfShouldFillFormOrNot(); } Future<List<dynamic>> _getProjectFormData() { var responses = Future.wait([_getUsersData(), _getTagsData()]); return responses; } Future<List<User>> _getUsersData() async { final userWebClient = UserWebClient(); final token = await _tokenObject.getToken(); final users = await userWebClient.getAllUsers(token); final usersList = Convert.convertToListOfUsers(jsonDecode(users)); return usersList; } Future<List<Tag>> _getTagsData() async { final tagsWebClient = TagsWebClient(); final token = await _tokenObject.getToken(); final tags = await tagsWebClient.getAllTags(token); final tagsList = Convert.convertToListOfTags(jsonDecode(tags)); return tagsList; } void _verifyIfShouldFillFormOrNot() { if (widget.type == 'edit') { _tagsInitState = _transformListOfTagsIntoStringOfTags( widget.project.tags, ); _usernamesInitState = _transformListOfUsersIntoStringOfUsernames( widget.project.participants, ); _titleController.text = widget.project.name; _institutionController.text = widget.project.institution; _startDateController.text = widget.project.startDate; _abstractController.text = widget.project.abstractText; _emailController.text = widget.project.email; _participantsFullNameController.text = widget.project.participantsFullName; } } String _transformListOfUsersIntoStringOfUsernames(List<User> users) { var stringOfUsers = ''; users.forEach((user) { stringOfUsers += user.username; stringOfUsers += ' '; }); return stringOfUsers; } String _transformListOfTagsIntoStringOfTags(List<Tag> tags) { var stringOfTags = ''; tags.forEach((tag) { stringOfTags += tag.name; stringOfTags += ' '; }); return stringOfTags; } @override Widget build(BuildContext context) { return ProgressHUD( borderColor: Theme.of(context).primaryColor, indicatorWidget: SpinKitPouringHourglass( color: Theme.of(context).primaryColor, ), child: Builder( builder: (loaderContext) => FutureBuilder( future: _getProjectFormData(), builder: (context, AsyncSnapshot<List<dynamic>> snapshot) { if (snapshot.hasData) { var usersList = []; usersList = _defineUserAutocomplete(snapshot.data[0]); var tagsList = []; tagsList = _defineTagAutocomplete(snapshot.data[1]); return Scaffold( appBar: AppBar( backgroundColor: ApplicationColors.appBarColor, elevation: 0, title: Text(_defineAppBarText()), ), body: SingleChildScrollView( child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.fromLTRB(16, 20, 16, 5), child: InputWithAnimation( controller: _titleController, type: TextInputType.name, label: 'Título do projeto', ), ), Padding( padding: const EdgeInsets.fromLTRB(16, 5, 16, 5), child: InputWithAnimation( controller: _emailController, type: TextInputType.emailAddress, label: 'Email do projeto', ), ), Padding( padding: const EdgeInsets.fromLTRB(16, 5, 16, 5), child: AutoCompleteInput( defaultText: _defineDefaultTagsText(), keyController: _tagsKey, hint: '#tag', label: 'Tags', data: tagsList, type: 'tag', triggerChar: '#', ), ), Padding( padding: const EdgeInsets.fromLTRB(16, 5, 16, 5), child: AutoCompleteInput( defaultText: _defineDefaultMainTeacherText(), hint: '@usuario ou Nome completo', keyController: _mainTeacherKey, label: 'Orientador', data: usersList, triggerChar: '@', position: SuggestionPosition.Bottom, ), ), Padding( padding: const EdgeInsets.fromLTRB(16, 5, 16, 5), child: AutoCompleteInput( defaultText: _defineDefaultSecondTeacherText(), hint: '@usuario ou Nome completo', keyController: _secondTeacherKey, label: 'Coorientador', data: usersList, triggerChar: '@', position: SuggestionPosition.Top, ), ), Padding( padding: const EdgeInsets.fromLTRB(16, 5, 16, 5), child: InputWithAnimation( controller: _institutionController, type: TextInputType.name, label: 'Instituição', ), ), Padding( padding: const EdgeInsets.fromLTRB(16, 5, 16, 5), child: InputWithAnimation( controller: _startDateController, type: TextInputType.datetime, label: 'Data de início', formatters: [ DateInputFormatter(), ], ), ), Padding( padding: const EdgeInsets.fromLTRB(16, 5, 16, 5), child: AutoCompleteInput( defaultText: _defineDefaultParticipantsText(), hint: '@usuario', keyController: _participantsKey, label: 'Participantes', data: usersList, triggerChar: '@', position: SuggestionPosition.Top, allowMultilines: true, ), ), Padding( padding: const EdgeInsets.fromLTRB(16, 5, 16, 5), child: InputWithAnimation( controller: _participantsFullNameController, type: TextInputType.multiline, label: 'Nomes completos dos participantes', allowMultilines: true, ), ), Padding( padding: const EdgeInsets.fromLTRB(16, 5, 16, 5), child: InputWithAnimation( controller: _abstractController, type: TextInputType.multiline, label: 'Resumo', allowMultilines: true, ), ), Padding( padding: const EdgeInsets.all(8.0), child: GradientButton( onPressed: () { _handleFormSubmit(loaderContext); }, text: 'Salvar', width: 270, height: 50, ), ), ], ), ), ); } else { return SpinKitFadingCube(color: ApplicationColors.primary); } }, ), ), ); } List<Map<String, dynamic>> _defineTagAutocomplete(List<Tag> tags) { var listOfTagsWithMap = <Map<String, dynamic>>[]; tags.forEach((tag) { var map = <String, dynamic>{}; map['display'] = tag.name.replaceAll('#', ''); map['id'] = tag.id.toString(); listOfTagsWithMap.add(map); }); return listOfTagsWithMap; } List<Map<String, dynamic>> _defineUserAutocomplete(List<User> users) { var listOfUsersWithMap = <Map<String, dynamic>>[]; users.forEach((user) { var map = <String, dynamic>{}; map['display'] = user.username.replaceAll('@', ''); map['id'] = user.id.toString(); map['name'] = user.name; listOfUsersWithMap.add(map); }); return listOfUsersWithMap; } void _handleFormSubmit(BuildContext context) async { final progress = ProgressHUD.of(context); progress.show(); var name = _titleController.text.trim(); var institution = _institutionController.text.trim(); var startDate = _startDateController.text.trim(); var mainTeacher = _mainTeacherKey.currentState.controller.text.trim(); var secondTeacher = _secondTeacherKey.currentState.controller.text.trim(); var abstractText = _abstractController.text.trim(); var email = _emailController.text.trim(); var participantsFullName = _participantsFullNameController.text.trim(); var tagsText = _tagsKey.currentState.controller.text; var participantsText = _participantsKey.currentState.controller.text; var tags = tagsText.trim().split(' '); tags = tags.toSet().toList(); var participants = participantsText.trim().split(' '); participants = participants.toSet().toList(); var projectTitleExists = await _projectTitleAlreadyExists(name, widget.project); var projectEmailAlreadyBeingUsed = false; if ((widget.type == 'edit' && email != widget.project.email) || widget.type != 'edit') { projectEmailAlreadyBeingUsed = await _projectEmailAlreadyBeingUsed(email); } final tagsVerificationPassed = _tagsStructureIsCorrect( tags, context, ); final participantsVerificationPassed = _participantsStructureIsCorrect( participants, context, ); final dateVerificationPassed = _dateIsValid( startDate, context, ); if (projectEmailAlreadyBeingUsed) { progress.dismiss(); GeniusToast.showToast( 'Ops! Parece que alguém já está usando o email de projeto que você tentou colocar.', ); } else if (projectTitleExists) { progress.dismiss(); GeniusToast.showToast( 'Ops! Parece que alguém já está usando o título de projeto que você tentou colocar.', ); } else if (tagsVerificationPassed && participantsVerificationPassed && dateVerificationPassed) { var mainTeacherText; var secondTeacherText; var mainTeacherNameText; var secondTeacherNameText; if (mainTeacher.contains('@')) { mainTeacherText = mainTeacher; mainTeacherNameText = null; } else { mainTeacherText = null; mainTeacherNameText = mainTeacher; } if (secondTeacher.contains('@') && secondTeacher != null) { secondTeacherText = secondTeacher; secondTeacherNameText = null; } else if (secondTeacher != null && secondTeacher != '') { secondTeacherText = null; secondTeacherNameText = secondTeacher; } else { secondTeacherText = null; secondTeacherNameText = null; } var project = Project( name: name, institution: institution, startDate: startDate, participants: participants, tags: tags, abstractText: abstractText, mainTeacher: mainTeacherText, mainTeacherName: mainTeacherNameText, secondTeacher: secondTeacherText, secondTeacherName: secondTeacherNameText, email: email, participantsFullName: participantsFullName, ); if (widget.type == 'edit') { _updateProject(project, widget.project.id, context); } else { _createProject(project, context); } } } Future<bool> _projectEmailAlreadyBeingUsed(String email) async { var projectEmailAlreadyExists = false; var projectWebClient = ProjectWebClient(); projectEmailAlreadyExists = await projectWebClient.verifyIfProjectEmailIsAlreadyBeingUsed(email); return projectEmailAlreadyExists; } bool _dateIsValid(String date, BuildContext context) { final progress = ProgressHUD.of(context); var dateArray = date.split('/'); var day = dateArray[0]; var month = dateArray[1]; var year = dateArray[2]; var formattedDate = year + '-' + month + '-' + day; var newDate = DateTime.tryParse(formattedDate); if (newDate == null) { GeniusToast.showToast('Formato de data inválido.'); progress.dismiss(); return false; } else { var greaterThanNow = DateTime.now().isBefore(newDate); if (greaterThanNow) { GeniusToast.showToast( 'Ops! Parece que um viajante do tempo passou por aqui'); progress.dismiss(); return false; } else { return true; } } } Future<bool> _projectTitleAlreadyExists( String title, Project oldProjectData, ) async { var projectTitleAlreadyExists = false; var projectWebClient = ProjectWebClient(); if (widget.type == 'edit') { if (oldProjectData.name != title) { projectTitleAlreadyExists = await projectWebClient.verifyIfProjectTitleAlreadyExists( title, ); } } else { projectTitleAlreadyExists = await projectWebClient.verifyIfProjectTitleAlreadyExists( title, ); } return projectTitleAlreadyExists; } bool _participantsStructureIsCorrect( List<String> participants, BuildContext context, ) { var verificationPassed = true; final progress = ProgressHUD.of(context); if (participants.length == 1 && (participants[0] == ' ' || participants[0] == '')) { participants.clear(); } if (participants.isEmpty) { GeniusToast.showToast( 'Seu projeto tem que ter pelo menos um participante!', ); verificationPassed = false; } else { participants.forEach((participant) { if (!participant.startsWith('@')) { GeniusToast.showToast('O participante $participant está sem @!'); verificationPassed = false; } }); } if (!verificationPassed) { progress.dismiss(); } return verificationPassed; } bool _tagsStructureIsCorrect(List<String> tags, BuildContext context) { var verification = true; final progress = ProgressHUD.of(context); if (tags.length == 1 && (tags[0] == ' ' || tags[0] == '')) { tags.clear(); } if (tags.isNotEmpty) { tags.forEach((tag) { if (!tag.startsWith('#')) { GeniusToast.showToast('A tag $tag está sem #!'); verification = false; } }); } if (!verification) { progress.dismiss(); } return verification; } void _createProject(Project project, BuildContext context) async { final projectWebClient = ProjectWebClient(); final progress = ProgressHUD.of(context); final token = await _tokenObject.getToken(); var creationTestsPassed = await projectWebClient .createProject( project, widget.user.id, token, ) .catchError((error) { progress.dismiss(); GeniusToast.showToast(error.message); }, test: (error) => error is HttpException).catchError((error) { progress.dismiss(); GeniusToast.showToast( 'Erro: o tempo para fazer login excedeu o esperado.'); }, test: (error) => error is TimeoutException).catchError((error) { progress.dismiss(); GeniusToast.showToast('Erro desconhecido.'); }) ?? false; if (creationTestsPassed) { progress.dismiss(); GeniusToast.showToast('Projeto criado com sucesso.'); _navigator.goBack(context); } } void _updateProject( Project project, int oldProjectId, BuildContext context, ) async { final projectWebClient = ProjectWebClient(); final progress = ProgressHUD.of(context); final token = await _tokenObject.getToken(); var updateTestsPassed = await projectWebClient .updateProject(project, oldProjectId, token) .catchError((error) { progress.dismiss(); GeniusToast.showToast(error.message); }, test: (error) => error is HttpException).catchError((error) { progress.dismiss(); GeniusToast.showToast( 'Erro: o tempo para fazer login excedeu o esperado.'); }, test: (error) => error is TimeoutException).catchError((error) { progress.dismiss(); GeniusToast.showToast('Erro desconhecido.'); }) ?? false; if (updateTestsPassed) { progress.dismiss(); GeniusToast.showToast('Projeto atualizado com sucesso.'); _navigator.goBack(context); } } String _defineAppBarText() { if (widget.type == 'edit') { return 'Edite o projeto'; } else { return 'Crie um projeto'; } } String _defineDefaultParticipantsText() { if (widget.type == 'edit') { return _usernamesInitState; } else { return widget.user.username + ' '; } } String _defineDefaultTagsText() { if (widget.type == 'edit') { return _tagsInitState; } else { return null; } } String _defineDefaultMainTeacherText() { if (widget.type == 'edit') { if (widget.project.mainTeacher != null) { return widget.project.mainTeacher; } else if (widget.project.mainTeacherName != null) { return widget.project.mainTeacherName; } else { return ''; } } else { return null; } } String _defineDefaultSecondTeacherText() { if (widget.type == 'edit') { if (widget.project.secondTeacher != null) { return widget.project.secondTeacher; } else if (widget.project.secondTeacherName != null) { return widget.project.secondTeacherName; } else { return ''; } } else { return null; } } }
require 'concurrent' require 'dry/configurable/config' require 'dry/configurable/error' require 'dry/configurable/nested_config' require 'dry/configurable/argument_parser' require 'dry/configurable/config/value' require 'dry/configurable/version' # A collection of micro-libraries, each intended to encapsulate # a common task in Ruby module Dry # A simple configuration mixin # # @example # # class App # extend Dry::Configurable # # setting :database do # setting :dsn, 'sqlite:memory' # end # end # # App.configure do |config| # config.database.dsn = 'jdbc:sqlite:memory' # end # # App.config.database.dsn # # => "jdbc:sqlite:memory'" # # @api public module Configurable # @private def self.extended(base) base.class_eval do @_config_mutex = ::Mutex.new @_settings = ::Concurrent::Array.new @_reader_attributes = ::Concurrent::Array.new end end # @private def inherited(subclass) subclass.instance_variable_set(:@_config_mutex, ::Mutex.new) subclass.instance_variable_set(:@_settings, @_settings.clone) subclass.instance_variable_set(:@_reader_attributes, @_reader_attributes.clone) subclass.instance_variable_set(:@_config, @_config.clone) if defined?(@_config) super end # Return configuration # # @return [Dry::Configurable::Config] # # @api public def config return @_config if defined?(@_config) create_config end # Return configuration # # @yield [Dry::Configuration::Config] # # @return [Dry::Configurable::Config] # # @api public def configure raise_frozen_config if frozen? yield(config) if block_given? end # Finalize and freeze configuration # # @return [Dry::Configurable::Config] # # @api public def finalize! freeze config.finalize! end # Add a setting to the configuration # # @param [Mixed] key # The accessor key for the configuration value # @param [Mixed] default # The default config value # # @yield # If a block is given, it will be evaluated in the context of # and new configuration class, and bound as the default value # # @return [Dry::Configurable::Config] # # @api public def setting(key, *args, &block) raise_already_defined_config(key) if defined?(@_config) value, options = ArgumentParser.call(args) if block if block.parameters.empty? value = _config_for(&block) else processor = block end end _settings << ::Dry::Configurable::Config::Value.new( key, !value.nil? ? value : ::Dry::Configurable::Config::Value::NONE, processor || ::Dry::Configurable::Config::DEFAULT_PROCESSOR ) store_reader_options(key, options) if options.any? end # Return an array of setting names # # @return [Array] # # @api public def settings _settings.map(&:name) end # @private no, really... def _settings @_settings end def _reader_attributes @_reader_attributes end private # @private def _config_for(&block) ::Dry::Configurable::NestedConfig.new(&block) end # @private def create_config @_config_mutex.synchronize do create_config_for_nested_configurations @_config = ::Dry::Configurable::Config.create(_settings) unless _settings.empty? end end # @private def create_config_for_nested_configurations nested_configs.map(&:create_config) end # @private def nested_configs _settings.select { |setting| setting.value.is_a?(::Dry::Configurable::NestedConfig) }.map(&:value) end # @private def raise_already_defined_config(key) raise AlreadyDefinedConfig, "Cannot add setting +#{key}+, #{self} is already configured" end # @private def raise_frozen_config raise FrozenConfig, 'Cannot modify frozen config' end # @private def store_reader_options(key, options) _reader_attributes << key if options.fetch(:reader, false) end # @private def method_missing(method, *args, &block) _reader_attributes.include?(method) ? config.public_send(method, *args, &block) : super end # @private def respond_to_missing?(method, _include_private = false) _reader_attributes.include?(method) || super end end end
import React from 'react'; import { styled, withTheme } from '@storybook/theming'; import { StorybookLogo } from '@storybook/components'; export const StorybookLogoStyled = styled(StorybookLogo)({ width: 'auto', height: '22px !important', display: 'block' }); export const Img = styled.img({ width: 'auto', height: 'auto', display: 'block', maxWidth: '100%' }); export const LogoLink = styled.a(({ theme }) => ({ display: 'inline-block', height: '100%', margin: '-3px -4px', padding: '2px 3px', border: '1px solid transparent', borderRadius: 3, color: 'inherit', textDecoration: 'none', '&:focus': { outline: 0, borderColor: theme.color.secondary } })); export const Brand = withTheme(({ theme }) => { const { title = 'Storybook', url = './', image } = theme.brand; const targetValue = url === './' ? '' : '_blank'; // When image is explicitly set to null, enable custom HTML support if (image === null) { if (title === null) return null; // eslint-disable-next-line react/no-danger if (!url) return /*#__PURE__*/React.createElement("div", { dangerouslySetInnerHTML: { __html: title } }); return /*#__PURE__*/React.createElement(LogoLink, { href: url, target: targetValue, dangerouslySetInnerHTML: { __html: title } }); } const logo = image ? /*#__PURE__*/React.createElement(Img, { src: image, alt: title }) : /*#__PURE__*/React.createElement(StorybookLogoStyled, { alt: title }); if (url) { return /*#__PURE__*/React.createElement(LogoLink, { title: title, href: url, target: targetValue }, logo); } // The wrapper div serves to prevent image misalignment return /*#__PURE__*/React.createElement("div", null, logo); });
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 BookStore.UI.Forms; using BookStore.Entity.Concrete; using BookStore.Business.Functions; namespace BookStore.UI.UserControls { public partial class UCStock : UserControl { #region Instantiates StockManager stockManager = new(); BookManager bookManager = new(); #endregion #region Constructor public UCStock() { InitializeComponent(); GetStocksTable(); } #endregion #region Methods private void btnAddBook_Click(object sender, EventArgs e) { AddStock addStock = new(this); addStock.Show(); } public void GetStocksTable() { List<Stock> stocks = stockManager.GetStocksList(); List<Book> books = bookManager.GetBooksList(); var result = (from t1 in stocks join t2 in books on t1.ISBNId equals t2.ISBN select new { colISBN = t2.Name, colStock = t1.AmountOfStock, colTime = t1.CreateTime }).ToList(); result.ForEach(x => { dgvStock.Rows.Add(x.colISBN, x.colStock, x.colTime); }); } #endregion } }
# -*- coding: utf-8 -*- # module Rouge module Lexers class Velocity < TemplateLexer title 'Velocity' desc 'Velocity is a Java-based template engine (velocity.apache.org)' tag 'velocity' filenames '*.vm', '*.velocity', '*.fhtml' mimetypes 'text/html+velocity' id = /[a-z_]\w*/i state :root do rule %r/[^{#$]+/ do delegate parent end rule %r/(#)(\*.*?\*)(#)/m, Comment::Multiline rule %r/(##)(.*?$)/, Comment::Single rule %r/(#\{?)(#{id})(\}?)(\s?\()/m do groups Punctuation, Name::Function, Punctuation, Punctuation push :directive_params end rule %r/(#\{?)(#{id})(\}|\b)/m do groups Punctuation, Name::Function, Punctuation end rule %r/\$\{?/, Punctuation, :variable end state :variable do rule %r/#{id}/, Name::Variable rule %r/\(/, Punctuation, :func_params rule %r/(\.)(#{id})/ do groups Punctuation, Name::Variable end rule %r/\}/, Punctuation, :pop! rule(//) { pop! } end state :directive_params do rule %r/(&&|\|\||==?|!=?|[-<>+*%&|^\/])|\b(eq|ne|gt|lt|ge|le|not|in)\b/, Operator rule %r/\[/, Operator, :range_operator rule %r/\b#{id}\b/, Name::Function mixin :func_params end state :range_operator do rule %r/[.]{2}/, Operator mixin :func_params rule %r/\]/, Operator, :pop! end state :func_params do rule %r/\$\{?/, Punctuation, :variable rule %r/\s+/, Text rule %r/,/, Punctuation rule %r/"(\\\\|\\"|[^"])*"/, Str::Double rule %r/'(\\\\|\\'|[^'])*'/, Str::Single rule %r/0[xX][0-9a-fA-F]+[Ll]?/, Num::Hex rule %r/\b[0-9]+\b/, Num::Integer rule %r/(true|false|null)\b/, Keyword::Constant rule %r/[(\[]/, Punctuation, :push rule %r/[)\]}]/, Punctuation, :pop! end end end end
from thehive4pyextended import TheHiveApiExtended from st2common.runners.base_action import Action from thehive4py.models import CaseTask __all__ = [ 'ChangeStatusTaskByJobIdAction' ] class ChangeStatusTaskByJobIdAction(Action): def run(self, job_id, status): task_id = self.action_service.get_value(name='thehive_job_{}'.format(job_id), local=False) api = TheHiveApiExtended(self.config['thehive_url'], self.config['thehive_api_key']) response = api.get_task(task_id) if response.status_code == 200: task_object = response.json() task = CaseTask(json=task_object) task.id = task_id task.status = status task.owner = self.config['thehive_bot_username'] api.update_case_task(task) if status == 'Completed': self.action_service.delete_value(name='thehive_job_{}'.format(job_id), local=False) else: raise ValueError('[ChangeStatusTaskByJobIdAction]: status_code %d' % response.status_code) return True
-- | Binary relational operations on 'S.Select's, that is, operations -- which take two 'S.Select's as arguments and return a single 'S.Select'. -- -- All the binary relational operations have the same type -- specializations. For example: -- -- @ -- unionAll :: S.Select (Field a, Field b) -- -> S.Select (Field a, Field b) -- -> S.Select (Field a, Field b) -- @ -- -- Assuming the @makeAdaptorAndInstance@ splice has been run for the product type @Foo@: -- -- @ -- unionAll :: S.Select (Foo (Field a) (Field b) (Field c)) -- -> S.Select (Foo (Field a) (Field b) (Field c)) -- -> S.Select (Foo (Field a) (Field b) (Field c)) -- @ -- -- If you want to run a binary relational operator on -- 'Select.SelectArr's you should apply 'Opaleye.Lateral.bilaterally' -- to it, for example -- -- @ -- 'Opaleye.Lateral.bilaterally' 'union' -- :: 'Data.Profunctor.Product.Default' 'B.Binaryspec' fields fields -- => 'S.SelectArr' i fields -> 'S.SelectArr' i fields -> 'S.SelectArr' i fields -- @ -- -- `unionAll` is very close to being the @\<|\>@ operator of a -- @Control.Applicative.Alternative@ instance but it fails to work -- only because of the typeclass constraint it has. {-# LANGUAGE MultiParamTypeClasses, FlexibleContexts #-} module Opaleye.Binary (-- * Binary operations unionAll, union, intersectAll, intersect, exceptAll, except, -- * Explicit versions unionAllExplicit, unionExplicit, intersectAllExplicit, intersectExplicit, exceptAllExplicit, exceptExplicit, -- * Adaptors binaryspecField, ) where import qualified Opaleye.Internal.Binary as B import qualified Opaleye.Internal.Column import qualified Opaleye.Internal.PrimQuery as PQ import qualified Opaleye.Select as S import Data.Profunctor.Product.Default (Default, def) unionAll :: Default B.Binaryspec fields fields => S.Select fields -> S.Select fields -> S.Select fields unionAll = unionAllExplicit def -- | The same as 'unionAll', except that it additionally removes any -- duplicate rows. union :: Default B.Binaryspec fields fields => S.Select fields -> S.Select fields -> S.Select fields union = unionExplicit def intersectAll :: Default B.Binaryspec fields fields => S.Select fields -> S.Select fields -> S.Select fields intersectAll = intersectAllExplicit def -- | The same as 'intersectAll', except that it additionally removes any -- duplicate rows. intersect :: Default B.Binaryspec fields fields => S.Select fields -> S.Select fields -> S.Select fields intersect = intersectExplicit def exceptAll :: Default B.Binaryspec fields fields => S.Select fields -> S.Select fields -> S.Select fields exceptAll = exceptAllExplicit def -- | The same as 'exceptAll', except that it additionally removes any -- duplicate rows. except :: Default B.Binaryspec fields fields => S.Select fields -> S.Select fields -> S.Select fields except = exceptExplicit def unionAllExplicit :: B.Binaryspec fields fields' -> S.Select fields -> S.Select fields -> S.Select fields' unionAllExplicit = B.sameTypeBinOpHelper PQ.UnionAll unionExplicit :: B.Binaryspec fields fields' -> S.Select fields -> S.Select fields -> S.Select fields' unionExplicit = B.sameTypeBinOpHelper PQ.Union intersectAllExplicit :: B.Binaryspec fields fields' -> S.Select fields -> S.Select fields -> S.Select fields' intersectAllExplicit = B.sameTypeBinOpHelper PQ.IntersectAll intersectExplicit :: B.Binaryspec fields fields' -> S.Select fields -> S.Select fields -> S.Select fields' intersectExplicit = B.sameTypeBinOpHelper PQ.Intersect exceptAllExplicit :: B.Binaryspec fields fields' -> S.Select fields -> S.Select fields -> S.Select fields' exceptAllExplicit = B.sameTypeBinOpHelper PQ.ExceptAll exceptExplicit :: B.Binaryspec fields fields' -> S.Select fields -> S.Select fields -> S.Select fields' exceptExplicit = B.sameTypeBinOpHelper PQ.Except binaryspecField :: (B.Binaryspec (Opaleye.Internal.Column.Column a) (Opaleye.Internal.Column.Column a)) binaryspecField = B.binaryspecColumn
$(function() { $('#mainLoadingDiv').prepend(disabledDiv); sendJSONAjaxRequest(false, 'getData/getAllApprovedRequests.html', null, fnViewRequestSuccess, null); }); function fnViewRequestSuccess(responseJSON) { $('#disabledDiv').remove(); if (responseJSON.result) { $('#viewRequestTable').show(); var str = ""; var request = responseJSON.approvedRequests; for (var item in request) { var classValue = null; if (item % 2 === 0) { classValue = 'oddRow'; } else { classValue = 'evenRow'; } var roles = ""; for (var role in request[item].roles) { roles += '<span data-i18n="label.role_' + request[item].roles[role].toLowerCase() + '" data-status="' + request[item].roles[role] + '">' + request[item].roles[role] + '</span>, '; } roles = roles.replace(/,\s*$/, ""); str += '<tr class="' + classValue + '">' + '<td class="viewRow1" title="' + request[item].fingerprint + '" name="name">' + request[item].name + '</td>' + '<td class="viewRow2" name="status" data-status="' + request[item].status + '" data-i18n="table.' + request[item].status.toLowerCase() + '">' + request[item].status + '</td>' + '<td class="viewRow3">' + roles + '</td>' + '<td class="viewRow4" name="expires">' + fnGetFormatedDate(request[item].expires) + '</td>'; var comment = request[item].comments == undefined || request[item].comments == null || request[item].comments == "" ? "&nbsp;" : request[item].comments; str += '<td class="viewRow5" name="expires">' + comment + '</td>'; str += '<td><a href="#" onclick="fnDeleteSelectedRequest(this)" data-toggle="tooltip" title="Delete"><span class="glyphicon glyphicon-trash"></span></a></td>'; str += '</tr>'; } $('#viewRequestTableContent').html(str); } else { $('#successMessage').html('<span class="errorMessage">' + responseJSON.message + '</span>'); } } function fnDeleteSelectedRequest(element) { $('#successMessage').html(''); var row = $(element).parent().parent(); var data="fingerprint="+$(row).find("td:eq(0)").attr('title'); $("#dialog-confirm").remove(); var str = '<div id="dialog-confirm" title="Delete User?" style="display:none;"><p>Are you sure you want to delete this request?</p></div>'; $('.container').append(str); // Define the Dialog and its properties. $("#dialog-confirm").dialog({ resizable: false, modal: true, height: 150, width: 400, buttons: { "Delete": function () { $(this).dialog('close'); $('#mainLoadingDiv').prepend(disabledDiv); sendJSONAjaxRequest(false, 'getData/deleteSelectedRequest.html', data, deleteSelectedRequestSuccess, null,element); }, "Cancel": function () { $(this).dialog('close'); } } }); } function deleteSelectedRequestSuccess(responsJSON,element) { $('#disabledDiv').remove(); if(responsJSON.result){ $('#successMessage').html('<div class="successMessage">Request has been successfully deleted.</div>'); $(element).parent().parent().remove(); }else{ $('#successMessage').html('<div class="errorMessage">'+ getHTMLEscapedMessage(responsJSON.message)+'</div>'); } }
# Define constants for program, PS way of doing this to make the real constants?? $CONFIG_FILE_NAME="counters.json" $PARAM_FILE_NAME="param.json" # Read configuration file which is encoded in JSON into PSObject # How to handle if the JSON is not properly formed. What is returned, null? $config = (Get-Content $CONFIG_FILE_NAME) -join "`n" | ConvertFrom-JSON $param = (Get-Content $PARAM_FILE_NAME) -join "`n" | ConvertFrom-JSON $hostname = Get-Content Env:\COMPUTERNAME # Get the source from the parameter file if missing or empty use # the name of the source $source = $param.source if ($source.Length -eq 0) { $source = $hostname } $delay = $param.delay $counter_names = @() $multipliers = @{} $metric_ids = @{} <# 1) Generate an array of the counter names we need to collect 2) Generate a map of the multiplier to counter name 3) Generate a map of the metric id to counter name #> foreach ($counter in $config.counters) { # add each of the counters into an array $counter_names += $counter.counter_name # Generate a key to lookup metric id and multiplier $counter_name = $counter.counter_name.ToString() $key = "\\$hostname$counter_name".ToUpper() # Add values to the lookup maps $multipliers[$key] = $counter.multiplier $metric_ids[$key] = $counter.metric_id } # Continuously loop collecting metrics from the Windows Performance Counters while($true) { $counters = Get-Counter -Counter $counter_names $timestamp = [math]::Round((Get-Date -Date (Get-Date).toUniversalTime() -UFormat %s)) $samples = $counters.CounterSamples foreach ($s in $samples) { $value = $s.CookedValue * $multipliers[$s.path] $metric_id = $metric_ids[($s.path).toUpper()] Write-Host $metric_id $value $source $timestamp } Start-Sleep -m $delay }
package Crixa::Channel; $Crixa::Channel::VERSION = '0.10'; # ABSTRACT: A Crixa Channel use Moose; use namespace::autoclean; use Crixa::Queue; use Crixa::Exchange; with qw(Crixa::HasMQ); has id => ( isa => 'Str', is => 'ro', required => 1 ); sub BUILD { $_[0]->_mq->channel_open( $_[0]->id ); } sub exchange { my $self = shift; Crixa::Exchange->new( @_, channel => $self, _mq => $self->_mq, ); } sub basic_qos { my $self = shift; my $args = @_ == 1 ? $_[0] : {@_}; $self->_mq->basic_qos( $self->id, $args ); } sub queue { my $self = shift; my $args = @_ == 1 ? shift : {@_}; $args->{_mq} = $self->_mq; $args->{channel} = $self; return Crixa::Queue->new($args); } sub ack { $_[0]->_mq->ack( shift->id, @_ ) } __PACKAGE__->meta->make_immutable; 1; __END__ =pod =head1 NAME Crixa::Channel - A Crixa Channel =head1 VERSION version 0.10 =head1 DESCRIPTION This class represents a channel. A channel is a lot like a socket. You will probably want to have a unique channel per process or thread for your application. You may also want to have separate channels for publishing and consuming messages. It is safe (and encouraged) to keep the same channel open over a long period of time for publishing or consuming messages. There is no need to create new channels on a regular basis. Also note that message delivery tags are scoped to the channel on which a message is delivered, and therefore message acks must go back to that same channel. Channels are created by calling the C<< Crixa->new_channel >> method. =head1 METHODS This class provides the following methods: =head2 $channel->exchange(...) This method creates a new L<Crixa::Exchange> object. Any parameters passed to this method are passed directly to the L<Crixa::Exchange> constructor, either as a hash or hashref. See the L<Crixa::Exchange> documentation for more details. =head2 $channel->queue(...) This method creates a new L<Crixa::Queue> object. Any parameters passed to this method are passed directly to the L<Crixa::Queue> constructor, either as a hash or hashref. See the L<Crixa::Queue> documentation for more details. =head2 $channel->basic_qos(...) This method sets quality of service flags for the channel. This method takes a hash or hash reference with the following keys: =over 4 =item * prefetch_count => $count If this is set, then the channel will fetch C<$count> additional messages to the client when it is consuming messages, rather than sending them down the socket one at a time. =item * prefetch_size => $size Set the maximum number of I<bytes> that will be prefetched. If both this and C<prefetch_count> are set then the smaller of the two wins. =item * global => $bool If this is true, then the QoS settings apply to all consumers on this channel. If it is false, then it only applies to new consumers created after this is set. In Crixa, a new AMQP consumer is created whenever you call any methods to get messages on a L<Crixa::Queue> object, so this setting doesn't really matter. =back Note that prefetching messages is only done when the queue is created in "no ack" mode (or "auto ack" if you prefer to think of it that way). =head2 $channel->ack(...) This method acknowledges delivery of a message received on this channel. It accepts two positional arguments. The first is the delivery tag for the message, which is required. The second is the "multiple" flag. If this is true, it means that you are acknowledging all messages up to the given delivery tag. It defaults to false. =head2 $channel->id This returns the channel's unique id. This is a positive integer. =head2 Crixa::Channel->new(...) Don't call this method directly. Instead, call C<new_channel> on a connected L<Crixa> object. =head1 AUTHORS =over 4 =item * Chris Prather <[email protected]> =item * Dave Rolsky <[email protected]> =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2012 - 2014 by Chris Prather. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut
package com.sandoval.besttodoapp.ui.fragments import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.NavController import androidx.navigation.fragment.findNavController import com.sandoval.besttodoapp.R import com.sandoval.besttodoapp.data.models.ToDoData import com.sandoval.besttodoapp.data.viewmodel.ToDoViewModel import com.sandoval.besttodoapp.databinding.FragmentAddBinding import com.sandoval.besttodoapp.ui.viewmodel.SharedViewModel import com.sandoval.besttodoapp.utils.actionAddToList class AddFragment : Fragment() { private lateinit var navController: NavController private val mTodoViewModel: ToDoViewModel by viewModels() private val mSharedViewModel: SharedViewModel by viewModels() private var _binding: FragmentAddBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentAddBinding.inflate(inflater, container, false) initViews() mSharedViewModel.hideSoftKeyboard(requireActivity()) setHasOptionsMenu(true) return binding.root } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.add_fragment_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.menu_add) { insertDataToDatabase() } return super.onOptionsItemSelected(item) } private fun insertDataToDatabase() { val mTitle = binding.addToDoTitle.text.toString() val mPriority = binding.addToDoPriority.selectedItem.toString() val mDescription = binding.addToDoDescription.text.toString() //Here we need to validate if this inputs are not null or empty. val validation = mSharedViewModel.verifyDataFromUserInput(mTitle, mDescription) if (validation) { val newData = ToDoData( 0, mTitle, mSharedViewModel.parsePriority(mPriority), mDescription ) // Function insertData to DB is needed to complete the process. newData obj we will be passed in this fun. // As the DAO is using a suspend function, this process has to be done in a coroutine. // the best practice to do this is using a ViewModel to access a dispatcher and in that // way the UI wont be blocked for the user while the insertion process is done. mTodoViewModel.insertData(newData) mSharedViewModel.hideSoftKeyboard(requireActivity()) mSharedViewModel.successDialog( requireActivity(), getString(R.string.add_fragment_dialog_title_success), getString(R.string.add_fragment_dialog_message_success) ) navController.navigate(actionAddToList) } else { mSharedViewModel.hideSoftKeyboard(requireActivity()) mSharedViewModel.errorDialog(requireActivity()) } } private fun initViews() { navController = findNavController() binding.addToDoPriority.onItemSelectedListener = mSharedViewModel.listener } override fun onDestroyView() { super.onDestroyView() _binding = null } }
from libgenget import * book_name = input("Enter book name\n") get_book(book_name)
#pragma once #include "StateMachine.h" #include "EndState.h" #include "SpritesManager.h" #include "AudioManager.h" #include "MilkShakeCookie.h" #include "Tools.h" #include <LibSchedule> #include <LibLOG> using PC = Pokitto::Core; using PD = Pokitto::Display; using PB = Pokitto::Buttons; constexpr int FOOD_FOR_LEVELUP = 3; constexpr int START_LIFES = 3; constexpr int START_TIME = 900; //x.xx seconds constexpr int FOOD_Y_REACH = 55; extern MilkShakeCookie milkShakeCookie; class IntroState; class GameState { enum States { Initialize, Eating, Loading, Mixing, Falling, Waiting, MovingLeft, MovingRight, Eaten, GameOver, GameOverCat, GameOverBunny }; private: static inline States state = States::Initialize; static inline SpritesManager::FoodType foodType; static inline int msState = PC::getTime(); static inline int foodX = 0; static inline int foodY = 0; static inline int foodRotation; static inline int catCounter = 0; static inline int bunnyCounter = 0; static inline bool finalStageCat; static inline bool finalStageBunny; static inline bool flip; static inline int timerGame; static inline int livesGame; static inline int scoreGame; static int ElapsedMs() { return PC::getTime() - msState; }; static void ChangeState(States newState) { msState = PC::getTime(); state = newState; //LOG("state", newState, "\n"); }; static void TickTimer() { if (state != Loading && state != GameOver && state != GameOverBunny && state != GameOverCat) if (timerGame > 0) timerGame--; else timerGame = 0; }; static void UpdateState() { switch (state) { case Initialize: scoreGame = 0; livesGame = START_LIFES; timerGame = START_TIME; ChangeState(Loading); break; case Eating: foodX = 0; foodY = 0; if (SpritesManager::catSprite.animEnd && SpritesManager::bunnySprite.animEnd) // ElapsedMs() > 600) { { //Stop animations SpritesManager::PlayCatAnimation(SpritesManager::AnimType::Idle); SpritesManager::PlayBunnyAnimation(SpritesManager::AnimType::Idle); if (bunnyCounter >= FOOD_FOR_LEVELUP || (SpritesManager::bunnyLevel >= 5 && bunnyCounter > 0)) { bunnyCounter = 0; SpritesManager::bunnyLevel++; SpritesManager::LoadBunny(SpritesManager::bunnyLevel); AudioManager::playLoading(); } if (catCounter >= FOOD_FOR_LEVELUP || (SpritesManager::catLevel >= 5 && catCounter > 0)) { catCounter = 0; SpritesManager::catLevel++; SpritesManager::LoadCat(SpritesManager::catLevel); AudioManager::playLoading(); } ChangeState(Loading); } break; case Loading: if (!SpritesManager::loadingCat && !SpritesManager::loadingBunny) { foodRotation += random(1000); ChangeState(Mixing); } break; case Mixing: foodX = 0; foodY = 0; if (ElapsedMs() > 500) { ChangeState(Falling); SpritesManager::PlayCatAnimation(SpritesManager::AnimType::Idle); SpritesManager::PlayBunnyAnimation(SpritesManager::AnimType::Idle); } break; case Falling: foodY += 5; if (foodY > FOOD_Y_REACH) ChangeState(Waiting); break; case Waiting: if (StateMachine::DemoMode) { if (ElapsedMs() > 250) { if (random(100) > 50) ChangeState(MovingLeft); else ChangeState(MovingRight); } } else { if (PB::leftBtn) ChangeState(MovingLeft); if (PB::rightBtn()) ChangeState(MovingRight); } break; case MovingLeft: if (PB::leftBtn() || StateMachine::DemoMode || finalStageBunny) foodX -= finalStageBunny ? 2 : 5; else if (PB::rightBtn()) ChangeState(MovingRight); else if (foodX < 0) foodX += finalStageBunny ? 2 : 5; if (foodX < -30) { if (foodType == SpritesManager::FoodType::Pancake) { SpritesManager::PlayBunnyAnimation(SpritesManager::AnimType::Good); AudioManager::playGood(); bunnyCounter++; scoreGame++; } else { SpritesManager::PlayBunnyAnimation(SpritesManager::AnimType::Bad); AudioManager::playBad(); livesGame--; } foodType = SpritesManager::FoodType::None; ChangeState(Eating); } break; case MovingRight: if (PB::rightBtn() || StateMachine::DemoMode || finalStageCat) foodX += finalStageCat ? 2 : 5; else if (PB::leftBtn()) ChangeState(MovingLeft); else if (foodX > 0) foodX -= finalStageCat ? 2 : 5; if (foodX > 30) { if (foodType == SpritesManager::FoodType::Milkshake) { SpritesManager::PlayCatAnimation(SpritesManager::AnimType::Good); AudioManager::playGood(); catCounter++; scoreGame++; } else { SpritesManager::PlayCatAnimation(SpritesManager::AnimType::Bad); AudioManager::playBad(); livesGame--; } foodType = SpritesManager::FoodType::None; ChangeState(Eating); } break; case GameOver: if (ElapsedMs() > 1000) { //--------------------------------------- EndState::EndType = EndState::Timeout; StateMachine::setState < EndState > (); AudioManager::playGameOver(); //--------------------------------------- } break; case GameOverCat: if (ElapsedMs() > 4000) { //--------------------------------------- EndState::EndType = EndState::BadCat; StateMachine::setState < EndState > (); AudioManager::playGameOverFull(); //--------------------------------------- } break; case GameOverBunny: if (ElapsedMs() > 4000) { //--------------------------------------- EndState::EndType = EndState::BadBunny; StateMachine::setState < EndState > (); AudioManager::playGameOverFull(); //--------------------------------------- } break; } }; public: static void Init() { PD::setTASRowMask(0b11111111111111111111); SpritesManager::LoadBunny(0); SpritesManager::LoadCat(0); ChangeState(Initialize); //Schedule::cancel<0>(); Schedule::repeat < 0 > (100, TickTimer); //-- milkShakeCookie.games++; milkShakeCookie.saveCookie(); }; static void Update() { if (StateMachine::DemoMode && Tools::AnyKey()) { StateMachine::DemoMode = false; StateMachine::setState < IntroState > (); } //Check final stage condition finalStageBunny = (SpritesManager::bunnyLevel >= 5); finalStageCat = (SpritesManager::catLevel >= 5); if (state == Mixing || state == Falling) { foodRotation += (FOOD_Y_REACH-foodY); foodType = (SpritesManager::FoodType)(1 + ((int)(foodRotation/200) % 2)); //Force food type at final stage if (finalStageBunny) foodType = SpritesManager::FoodType::Pancake; if (finalStageCat) foodType = SpritesManager::FoodType::Milkshake; //---------------------------------------------------------------- //foodType = SpritesManager::FoodType::Milkshake; //Test purpose only //---------------------------------------------------------------- } //Game over conditions if (state != Initialize && state != GameOver && state != GameOverCat && state != GameOverBunny && (livesGame <= 0 || timerGame <= 0)) { ChangeState(GameOver); } if (SpritesManager::catLevel > 5 && state != GameOverCat) { scoreGame += (timerGame / 20) + (livesGame * 2); ChangeState(GameOverCat); } if (SpritesManager::bunnyLevel > 5 && state != GameOverBunny) { scoreGame += (timerGame / 20) + (livesGame * 2); ChangeState(GameOverBunny); } //Save high score if (scoreGame > milkShakeCookie.highScore) { milkShakeCookie.highScore = scoreGame; milkShakeCookie.saveCookie(); } EndState::FinalScore = scoreGame; //--- UpdateState(); }; static void Draw() { SpritesManager::DrawStage(); if (StateMachine::DemoMode) { auto ms = PC::getTime(); auto c1 = 80 + (ms / 100) % 16; PD::setColor(c1, 15); Tools::PrintCentered(110, 80, c1, "DEMO MODE"); Tools::PrintCentered(110, 90, c1, "press any"); Tools::PrintCentered(110, 100, c1, "to play"); } if (SpritesManager::loadingBunny) SpritesManager::DrawDust(50, 90, 30, true); else SpritesManager::bunnySprite.draw(0, 74, false, false); if (state == GameOverBunny) SpritesManager::DrawDust(50, 90, 50, false, true, false); //draw food also if (SpritesManager::loadingCat) SpritesManager::DrawDust(150, 90, 30, true); else SpritesManager::catSprite.draw(116, 74, false, false); if (state == GameOverCat) SpritesManager::DrawDust(150, 90, 50, false, false, true); //draw food also if (!SpritesManager::loadingBunny && !SpritesManager::loadingCat) SpritesManager::DrawFood(110 + foodX, 65 + foodY, foodType); SpritesManager::DrawGameGui(timerGame, START_TIME, livesGame, scoreGame); }; };
package com.ficture7.aasexplorer; import android.os.AsyncTask; import com.ficture7.aasexplorer.model.Subject; import java.util.HashMap; import java.util.Map; public class AppExplorerSaver extends ExplorerSaver { private Map<Subject, SaveResourcesAsyncTask> saveResourcesAsyncTaskMap; private SaveSubjectsAsyncTask saveSubjectsAsyncTask; public AppExplorerSaver(Explorer explorer) { super(explorer); saveResourcesAsyncTaskMap = new HashMap<>(); } public SaveSubjectsAsyncTask getSaveSubjectsAsyncTask() { if (saveSubjectsAsyncTask == null) { saveSubjectsAsyncTask = new SaveSubjectsAsyncTask(); } return saveSubjectsAsyncTask; } public SaveResourcesAsyncTask getSaveResourcesAsyncTask(Subject subject) { SaveResourcesAsyncTask task = saveResourcesAsyncTaskMap.get(subject); if (task == null) { task = new SaveResourcesAsyncTask(subject); saveResourcesAsyncTaskMap.put(subject, task); } return task; } public class SaveSubjectsAsyncTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... args) { try { explorer().getALevel().getSubjects().save(); } catch (Exception e) { return null; } return null; } } public class SaveResourcesAsyncTask extends AsyncTask<Void, Void, Void> { private Subject subject; public SaveResourcesAsyncTask(Subject subject) { this.subject = subject; } @Override protected Void doInBackground(Void... args) { try { subject.getResources().save(); } catch (Exception e) { return null; } return null; } } }
#!/usr/bin/env bash # Prepares the app archive and manifest for upload: # - removes previous app archive # - creates app archive from core files # - copies the archive and manifest to the accessible Chrome OS # download folder, ready for upload via the Cockpit # Then uses 'cf push' to deploy directly. appname=$(yq r manifest.yml applications[0].name) echo CF app '${appname}' rm app.zip zip app.zip .npmrc package.json xs-app.json cp manifest.yml app.zip ${HOME}/Downloads/ cf d ${appname} -f cf push
<?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::group(['middleware' => ['web']], function () { //Routes for Menu Route::get('/', function () { return view('pentadbir.laman_utama_pentadbir'); }); Route::get('/laman-utama', function () { return view('pentadbir.laman_utama_pentadbir'); })->name('laman-utama'); Route::get('/daftar-kelas-subjek', function () { return view('pentadbir.daftar_kelas_subjek'); })->name('daftar-kelas-subjek'); //Routes for Admins Route::resource('admin', 'AdminController'); Route::resource('news', 'NewsController'); Route::resource('teacher', 'TeacherController'); Route::resource('student', 'StudentController'); Route::resource('subject', 'SubjectController'); Route::resource('classroom', 'ClassroomController'); Route::resource('classroomsubject', 'ClassroomSubjectController'); Route::resource('task', 'TaskController'); Route::resource('taskmark', 'TaskMarkController'); Route::get('addmark/{id}',[ 'as' => 'addmark', 'uses' => 'TaskMarkController@addmark']); Route::resource('attendance', 'AttendanceController'); Route::post('addattendance', 'AttendanceController@addattendance'); //Controller addattendance // Route::get('news/{id}',[ 'as' => 'delete-news', 'uses' => 'NewsController@destroy']); // Route::get('payment-belum-sah', 'PayZakatController@index2'); //Controller Index // Route::get('payment-belum-sah', 'PayZakatController@index2'); //Controller Create // Route::get('payment-belum-sah', 'PayZakatController@index2'); //Controller Store // Route::get('payment-belum-sah', 'PayZakatController@index2'); //Controller Show // Route::get('payment-belum-sah', 'PayZakatController@index2'); //Controller Edit // Route::get('payment-belum-sah', 'PayZakatController@index2'); //Controller Update // Route::get('payment-belum-sah', 'PayZakatController@index2'); //Controller Destroy });
#!/bin/bash # trap "kill 0" EXIT if [ -z "$2" ] then gpu=0 else gpu=$2 fi echo Running on GPU$gpu export PHYSX_GPU_DEVICE=$gpu let gpu_port=$gpu+5 # echo "Port:" "$gpu_port"00x sleep 1 counter=0 amount=$1 while [ $counter -lt $amount ] do # echo $counter echo Connecting server to port "$gpu_port"00$counter python3 laikago_stand_server.py --addr 127.0.0.1:"$gpu_port"00$counter & ((counter++)) done wait
<?php namespace App\Models; use App\Events\DepositStatusUpdate; use Illuminate\Database\Eloquent\Model; class Deposit extends BaseModel { // protected $table = 'deposits'; public function type() { return $this->belongsTo(DepositType::class, 'deposit_type_id'); } public function status() { return $this->belongsTo(DepositStatus::class, 'status_id'); } public function upgrade_type() { return $this->belongsTo(UpgradeType::class); } public function account() { return $this->belongsTo(Account::class); } protected function fireCustomModelEvent($event, $method) { if ('updated' == $event && $this->isDirty('status_id')) { event(new DepositStatusUpdate($this)); } return parent::fireCustomModelEvent($event, $method); } }
#ifndef LUPS_COMPILER_H #define LUPS_COMPILER_H #include "builtins.h" #include "code.h" #include "object.h" #include <optional> #include <unordered_map> typedef std::string SymbolScope; namespace scopes { static const SymbolScope GlobalScope = "GLOBAL"; static const SymbolScope LocalScope = "LOCAL"; static const SymbolScope BuiltinScope = "BUITLIN"; static const SymbolScope FreeScope = "FREE"; } // namespace scopes struct Bytecode { code::Instructions instructions; std::vector<Object *> constants; }; struct EmittedInstruction { code::Opcode op; int pos; }; struct CompilationScope { code::Instructions instructions; EmittedInstruction last_inst; EmittedInstruction prev_inst; }; struct Symbol { std::string name; SymbolScope scope; int index; }; class SymbolTable { public: SymbolTable() { definition_num_ = 0; store_ = std::unordered_map<std::string, std::unique_ptr<Symbol>>(); outer_ = nullptr; free_symbols_ = std::vector<Symbol>(); } SymbolTable(SymbolTable *outer) { definition_num_ = 0; store_ = std::unordered_map<std::string, std::unique_ptr<Symbol>>(); outer_ = outer; } const Symbol &define(const std::string &name); const Symbol &define_free(const Symbol &symbol); const Symbol &define_builtin(int index, const std::string &name); std::optional<Symbol> resolve(const std::string &name); int definition_num_; SymbolTable *outer_; std::unordered_map<std::string, std::unique_ptr<Symbol>> store_; std::vector<Symbol> free_symbols_; }; class Compiler { public: Compiler(); // The main compiling function. It returns an optional string containing an // error. so if compilation was successful then compile(node).has_value() == // false std::optional<std::string> compile(const Node &node); int add_constant(Object *obj); int emit(code::Opcode op, std::vector<int> operands); int emit(code::Opcode op); int add_instruction(std::vector<char> inst); void set_last_instruction(code::Opcode, int pos); bool last_instruction_is(const code::Opcode &op); void remove_last_pop(); void replace_instructions(int pos, const code::Instructions &new_inst); void change_operand(int op_pos, int operand); code::Instructions current_instructions(); int add_instructions(std::vector<char> &inst); Bytecode *bytecode() { return new Bytecode{current_instructions(), constants_}; } void replace_last_pop_with_return(); code::Instructions &scoped_inst() { return curr_scope().instructions; } CompilationScope &curr_scope() { return scopes_.back(); } void load_symbol(const Symbol &m); void enter_scope(); code::Instructions leave_scope(); std::vector<CompilationScope> scopes_; int scope_index_; SymbolTable *symbol_table_; private: code::Instructions instructions_; std::vector<Object *> constants_; EmittedInstruction *last_inst_; EmittedInstruction *prev_inst_; }; #endif
; RUN: llc < %s -O0 -fast-isel-abort=1 -relocation-model=pic -mtriple=armv7-pc-linux-gnueabi | FileCheck %s @var = dso_local global i32 42 define dso_local i32* @foo() { ; CHECK: foo: ; CHECK: ldr r0, .L[[POOL:.*]] ; CHECK-NEXT: .L[[ADDR:.*]]: ; CHECK-NEXT: add r0, pc, r0 ; CHECK-NEXT: bx lr ; CHECK: .L[[POOL]]: ; CHECK-NEXT: .long var-(.L[[ADDR]]+8) ret i32* @var } !llvm.module.flags = !{!0} !0 = !{i32 1, !"PIE Level", i32 2}
require 'rails_helper' describe Item do describe '#create' do context 'can save' do it "全てのバリデーションをクリアする場合は登録できること" do item = build(:item) expect(item).to be_valid end end context 'can not save nil test' do it "item_nameがない場合は登録できないこと" do item = build(:item, item_name: "") item.valid? expect(item.errors[:item_name]).to include() end it "priceがない場合は登録できないこと" do item = build(:item, price: "") item.valid? expect(item.errors[:price]).to include() end it "category_idがない場合は登録できないこと" do item = build(:item, category_id: "") item.valid? expect(item.errors[:category_id]).to include() end it "status_idがない場合は登録できないこと" do item = build(:item, status_id: "") item.valid? expect(item.errors[:status_id]).to include() end it "sizeがない場合は登録できないこと" do item = build(:item, size: "") item.valid? expect(item.errors[:size]).to include() end it "delivery_method_idがない場合は登録できないこと" do item = build(:item, delivery_method_id: "") item.valid? expect(item.errors[:delivery_method_id]).to include() end it "delivery_fee_idがない場合は登録できないこと" do item = build(:item, delivery_fee_id: "") item.valid? expect(item.errors[:delivery_fee_id]).to include() end it "prefecture_idがない場合は登録できないこと" do item = build(:item, prefecture_id: "") item.valid? expect(item.errors[:prefecture_id]).to include() end it "estimated_delivery_idがない場合は登録できないこと" do item = build(:item, estimated_delivery_id: "") item.valid? expect(item.errors[:estimated_delivery_id]).to include() end end end end
//===--- BPF.cpp - Implement BPF target feature support -------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements BPF TargetInfo objects. // //===----------------------------------------------------------------------===// #include "BPF.h" #include "Targets.h" #include "clang/Basic/MacroBuilder.h" #include "clang/Basic/TargetBuiltins.h" #include "llvm/ADT/StringRef.h" using namespace clang; using namespace clang::targets; const Builtin::Info BPFTargetInfo::BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) \ {#ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr}, #include "clang/Basic/BuiltinsBPF.def" }; void BPFTargetInfo::getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const { Builder.defineMacro("__bpf__"); Builder.defineMacro("__BPF__"); } static constexpr llvm::StringLiteral ValidCPUNames[] = {"generic", "v1", "v2", "v3", "probe"}; bool BPFTargetInfo::isValidCPUName(StringRef Name) const { return llvm::find(ValidCPUNames, Name) != std::end(ValidCPUNames); } void BPFTargetInfo::fillValidCPUList(SmallVectorImpl<StringRef> &Values) const { Values.append(std::begin(ValidCPUNames), std::end(ValidCPUNames)); } ArrayRef<Builtin::Info> BPFTargetInfo::getTargetBuiltins() const { return llvm::makeArrayRef(BuiltinInfo, clang::BPF::LastTSBuiltin - Builtin::FirstTSBuiltin); } bool BPFTargetInfo::handleTargetFeatures(std::vector<std::string> &Features, DiagnosticsEngine &Diags) { for (const auto &Feature : Features) { if (Feature == "+alu32") { HasAlu32 = true; } } return true; }
```js import { DOMHelper } from 'rsuite'; // or import DOMHelper from 'rsuite/lib/DOMHelper'; ```
package com.apps.pu.hibah.services; import com.apps.pu.hibah.entity.Log; import java.util.List; public interface MyService { Log addLog(Log log); List<Log> getLogs(); void deleteLog(Log log); }
--- template: page title: Form slug: form socialImage: /media/icon.jpeg draft: true --- <style> label{ padding:10px; margin: -5px; } input[type=text] { width: 100%; padding: 10px 10px; margin: 4px; display: inline-block; border: 1px solid #ccc; border-radius: 8px; box-sizing: border-box; } input[type=email] { width: 100%; padding: 10px 10px; margin: 4px 0; display: inline-block; border: 1px solid #ccc; border-radius: 8px; box-sizing: border-box; } textarea { width: 100%; height: 100px; margin: 4px 0; padding: 10px 10px; border: 1px solid #ccc; border-radius: 8px; box-sizing: border-box; } button[type=submit] { padding: 0 24px; width: 100%; line-height: 18px; text-align: center; color: #222; background-color:rgba(255,255,255); border: 1px solid rgba(0, 0, 0, .23); border-radius: 20px; padding: 14px 20px; cursor: pointer; } button[type=submit]:hover,focus { color: #5d93ff ; border-color:#5d93ff; } </style> 也歡迎透過下面的表單傳送訊息給我們。 <br/><br/> [](https://twitter.com/InfoSec_zip)<h2>傳送訊息</h2> <form name="Contact Form" method="POST" data-netlify="true" action="/pages/success"> <p> <label>如何稱呼您?</label><input type="text" name="name"/> </p> <p> <label>您的E-mail(方便我們回覆您的訊息,非必要):</label><input type="email" name="email" /> </p> <label>想說的話:</label><textarea name="message"></textarea> </p> <p> <button type="submit">傳送</button> </p> </form>
Puppet::Type.newtype(:vnx_nqm) do @doc = "Manage EMC VNX Qos Settings." ensurable newparam(:name, :namevar => true) do desc "The IOclass name" validate do |value| fail("IOclass name cannot exceed 64 characters") unless value.length <= 64 end end newproperty(:ioclass) do desc "The IOclass." end newproperty(:current_state) do desc "The current_state." end newproperty(:status) do desc "The status." end newproperty(:number_of_luns) do desc "The number_of_luns." end newproperty(:lun_number) do desc "The LUN Id." end newparam(:lun_name) do desc "The LUN name" validate do |value| fail("LUN name cannot exceed 64 characters") unless value.length <= 64 end end newproperty(:lun_wwn) do desc "The LUN WWN." end newproperty(:raid_type) do desc "The raid_type." end newproperty(:io_type) do desc "The io_type." end newproperty(:io_size_range) do desc "The io_size_range." end newproperty(:control_method) do desc "The control_method." end newproperty(:metric_type) do desc "The metric_type." end newproperty(:goal_value) do desc "The goal_value." end newproperty(:anyio) do desc "The anyio." end newproperty(:policy_name) do desc "The policy name." end newproperty(:fail_action) do desc "The fail_action." end #============Read Only Properties=============# end
<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?> <?='<?xml version="1.0" encoding="'.SITE_CHARSET.'"?>'?> <rss version="2.0"> <channel> <title><?=$arResult["NAME"]?></title> <link><?=$arResult["URL"]?></link> <description><?=$arResult["DESCRIPTION"]?></description> <lastBuildDate><?=date("r")?></lastBuildDate> <ttl><?=$arResult["RSS_TTL"]?></ttl> <?if(is_array($arResult["PICTURE"])):?> <image> <title><?=$arResult["NAME"]?></title> <url><?=$arResult["PICTURE"]["FILE"]["SRC"]?></url> <link><?=$arResult["URL"]?></link> <width><?=$arResult["PICTURE"]["WIDTH"]?></width> <height><?=$arResult["PICTURE"]["HEIGHT"]?></height> </image> <?endif?> <?foreach($arResult["Events"] as $arEvent):?> <item> <title><?=$arEvent["TITLE_FORMAT"]?></title> <link><?=$arEvent["URL"]?></link> <description><?=$arEvent["MESSAGE_FORMAT"]?></description> <pubDate><?=$arEvent["LOG_DATE"]?></pubDate> </item> <?endforeach?> </channel> </rss>
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the mediaconvert-2017-08-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.MediaConvert.Model { /// <summary> /// Selector for video. /// </summary> public partial class VideoSelector { private ColorSpace _colorSpace; private ColorSpaceUsage _colorSpaceUsage; private Hdr10Metadata _hdr10Metadata; private int? _pid; private int? _programNumber; private InputRotate _rotate; /// <summary> /// Gets and sets the property ColorSpace. If your input video has accurate color space /// metadata, or if you don't know about color space, leave this set to the default value /// FOLLOW. The service will automatically detect your input color space. If your input /// video has metadata indicating the wrong color space, or if your input video is missing /// color space metadata that should be there, specify the accurate color space here. /// If you choose HDR10, you can also correct inaccurate color space coefficients, using /// the HDR master display information controls. You must also set Color space usage (ColorSpaceUsage) /// to FORCE for the service to use these values. /// </summary> public ColorSpace ColorSpace { get { return this._colorSpace; } set { this._colorSpace = value; } } // Check to see if ColorSpace property is set internal bool IsSetColorSpace() { return this._colorSpace != null; } /// <summary> /// Gets and sets the property ColorSpaceUsage. There are two sources for color metadata, /// the input file and the job configuration (in the Color space and HDR master display /// informaiton settings). The Color space usage setting controls which takes precedence. /// FORCE: The system will use color metadata supplied by user, if any. If the user does /// not supply color metadata, the system will use data from the source. FALLBACK: The /// system will use color metadata from the source. If source has no color metadata, the /// system will use user-supplied color metadata values if available. /// </summary> public ColorSpaceUsage ColorSpaceUsage { get { return this._colorSpaceUsage; } set { this._colorSpaceUsage = value; } } // Check to see if ColorSpaceUsage property is set internal bool IsSetColorSpaceUsage() { return this._colorSpaceUsage != null; } /// <summary> /// Gets and sets the property Hdr10Metadata. Use the "HDR master display information" /// (Hdr10Metadata) settings to correct HDR metadata or to provide missing metadata. These /// values vary depending on the input video and must be provided by a color grader. Range /// is 0 to 50,000; each increment represents 0.00002 in CIE1931 color coordinate. Note /// that these settings are not color correction. Note that if you are creating HDR outputs /// inside of an HLS CMAF package, to comply with the Apple specification, you must use /// the following settings. Set "MP4 packaging type" (writeMp4PackagingType) to HVC1 (HVC1). /// Set "Profile" (H265Settings > codecProfile) to Main10/High (MAIN10_HIGH). Set "Level" /// (H265Settings > codecLevel) to 5 (LEVEL_5). /// </summary> public Hdr10Metadata Hdr10Metadata { get { return this._hdr10Metadata; } set { this._hdr10Metadata = value; } } // Check to see if Hdr10Metadata property is set internal bool IsSetHdr10Metadata() { return this._hdr10Metadata != null; } /// <summary> /// Gets and sets the property Pid. Use PID (Pid) to select specific video data from an /// input file. Specify this value as an integer; the system automatically converts it /// to the hexidecimal value. For example, 257 selects PID 0x101. A PID, or packet identifier, /// is an identifier for a set of data in an MPEG-2 transport stream container. /// </summary> [AWSProperty(Min=1, Max=2147483647)] public int Pid { get { return this._pid.GetValueOrDefault(); } set { this._pid = value; } } // Check to see if Pid property is set internal bool IsSetPid() { return this._pid.HasValue; } /// <summary> /// Gets and sets the property ProgramNumber. Selects a specific program from within a /// multi-program transport stream. Note that Quad 4K is not currently supported. /// </summary> [AWSProperty(Min=-2147483648, Max=2147483647)] public int ProgramNumber { get { return this._programNumber.GetValueOrDefault(); } set { this._programNumber = value; } } // Check to see if ProgramNumber property is set internal bool IsSetProgramNumber() { return this._programNumber.HasValue; } /// <summary> /// Gets and sets the property Rotate. Use Rotate (InputRotate) to specify how the service /// rotates your video. You can choose automatic rotation or specify a rotation. You can /// specify a clockwise rotation of 0, 90, 180, or 270 degrees. If your input video container /// is .mov or .mp4 and your input has rotation metadata, you can choose Automatic to /// have the service rotate your video according to the rotation specified in the metadata. /// The rotation must be within one degree of 90, 180, or 270 degrees. If the rotation /// metadata specifies any other rotation, the service will default to no rotation. By /// default, the service does no rotation, even if your input video has rotation metadata. /// The service doesn't pass through rotation metadata. /// </summary> public InputRotate Rotate { get { return this._rotate; } set { this._rotate = value; } } // Check to see if Rotate property is set internal bool IsSetRotate() { return this._rotate != null; } } }
@include('admin.layouts.header') <div class="container"> <title>Cập nhật lớp</title> <h2 class="text-center" >Cập nhật lớp</h2> <form style="margin:auto; text-align:center" method="POST" enctype="multipart/form-data"> @if(Session::has('error')) <h3 align="center" style="color: #FF0000">{{Session::get('error')}}</h3> @endif @csrf <div class="form-group input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fas fa-chalkboard-teacher"></i> </span> </div> <input name="id" class="form-control" placeholder="ID" readonly type="text"> </div> <div class="form-group input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fas fa-chalkboard-teacher"></i> </span> </div> <input name="name" value="{{$lop->name}}" class="form-control" placeholder="Tên lớp" required type="text"> </div> <div class="form-group input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fas fa-users"></i> </span> </div> <select class="form-control" name="id_khoa"> <option disabled>Chọn khóa</option> @foreach ($khoas as $item) <option {{$lop->id_khoahoc == $item->id?"selected":""}} value="{{$item->id}}">{{$item->name}}</option> @endforeach </select> </div> <div class="form-group input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fas fa-graduation-cap"></i> </span> </div> <select class="form-control" name="id_nganh"> <option disabled>Chọn ngành</option> @foreach ($nganhs as $item) <option {{$lop->id_nganhhoc == $item->id?"selected":""}} value="{{$item->id}}">{{$item->name}}</option> @endforeach </select> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-block">Sửa</button> </div> </form> </div> @include('admin.layouts.footer')
package openstack import "github.com/consensusnetworks/go-diagrams/diagram" type lifecyclemanagementContainer struct { path string opts []diagram.NodeOption } var Lifecyclemanagement = &lifecyclemanagementContainer{ opts: diagram.OptionSet{diagram.Provider("openstack"), diagram.NodeShape("none")}, path: "assets/openstack/lifecyclemanagement", }
package com.sample.marvelgallery.data.network.dto class DataWrapper<T> { var data: DataContainer<T>? = null }
<?php if(!empty($_POST['nom'])) { session_start(); if (is_file("tournois.txt")) { $tableauTournois = file('tournois.txt'); $tournoisAVerifier = []; foreach ($tableauTournois as $index => $value) { $tournoisAVerifier[$index] = explode('|', $value); } $c = 0; for ($i = 0; $i < count($tournoisAVerifier); $i++) { if (trim($tournoisAVerifier[$i][0]) == $_POST['nom']) { $tournoiresultat[$c] = $tournoisAVerifier[$i]; $c++; } } $_SESSION['array'] = $tournoiresultat; if (!empty($tournoiresultat)) { header('Location:resulatRecherche.php'); } else { header("Location: recherche.php?notFound=1"); } } else { header('Location : recherche.php?fileError=1'); } } else{ header('Location: recherche.php?errorEmpty=1'); }
# we create a connection (setq client (socket_connect "mulakus-MacBook-Pro.local" 2654)) # We then write something on the socket (socket_write client "Ceci est un test")
#ifndef DEMO_PLF_DEMO_H #define DEMO_PLF_DEMO_H #include "GL/glew.h" #include "ApplicationInterface.h" class AnimatedModel; class NavMeshAStar; class SceneManager; class Player; class Frustrum; class Entity; class Material; class Cube; class Terrain; class Monster; class SceneNode; class NavigationMesh; class Camera; class DynamicCamera; class SceneLeafModel; class Texture; class FPSLabel; class Label; class PLFDemo : public ApplicationInterface { public: PLFDemo(SceneManager& scene_manager); bool init(int argc, char** argv); bool postInit(); void tick(float dt); GLuint postProcess(Texture& color_texture, Texture& depth_texture, float dt); Player& getPlayer() const { return *player_; } //Entity& getStair() const { return *stair_entity_; } const Entity& getStepEntity() const { return *stair_step_entity_; } Camera& getCamera() const { return *camera_; } const AnimatedModel& getModel() const { return *snake_; } const Monster& getMonster() const { return *monster_; } void onResize(int width, int height); private: void generateFloor(Entity& parent); void generateWall(Entity& parent); Material* terrain_material_,* concrete_material_; Entity* terrain_node_; Cube* stair_step_, *floor_, *stair_; Player* player_; Camera* camera_; SceneManager* scene_manager_; Frustrum* frustrum_; GLuint textures[15]; Entity* stair_step_entity_; AnimatedModel* snake_; Terrain* terrain_; Monster* monster_; SceneNode* level_node_; NavigationMesh* navigation_mesh_; NavMeshAStar* pathfinder_; SceneLeafModel* waypoint_visualiser_; FPSLabel* fps_label_; Label* debug_label_; int width_, height_; //Entity* stair_entity_; }; #endif
#!/usr/bin/env node /** * © 2013 Liferay, Inc. <https://liferay.com> and Node GH contributors * (see file: README.md) * SPDX-License-Identifier: BSD-3-Clause */ import { run } from './cmd' const verbose = process.argv.indexOf('--verbose') !== -1 const insane = process.argv.indexOf('--insane') !== -1 process.on('unhandledRejection', r => console.log(r)) if (verbose || insane) { process.env.GH_VERBOSE = 'true' } if (insane) { process.env.GH_VERBOSE_INSANE = 'true' } run()
#!/bin/bash sudo yum install httpd -y sudo chown vagrant:vagrant -R /var/www sudo rpm -ivh https://artifacts.elastic.co/downloads/kibana/kibana-5.1.2-x86_64.rpm sudo service kibana start
--- layout: post title: My 2010 New Year's Resolutions tags: Dreams And Thoughts,New Year'S Resolutions --- I hear that it helps to sometimes write down your New Year's resolutions. Because I usually fail to complete most of my resolutions I figure that I should receive all and any the help that I can get. 1. Exercise at least three times per week. 2. Lose thirty pounds. 3. Take more pictures. 4. Eat healthier. 5. Take a vacation. 6. Start writing a book. 7. Get involved in volunteer work. 8. Launch a website. 9. Enjoy life.
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.db import javax.inject.{ Inject, Provider, Singleton } import scala.util.control.NonFatal import play.api.{ Configuration, Logger } /** * DB API for managing application databases. */ trait DBApi { /** * All configured databases. */ def databases(): Seq[Database] /** * Get database with given configuration name. * * @param name the configuration name of the database */ def database(name: String): Database /** * Shutdown all databases, releasing resources. */ def shutdown(): Unit } /** * Default implementation of the DB API. */ class DefaultDBApi( configuration: Configuration, connectionPool: ConnectionPool = new BoneConnectionPool, classLoader: ClassLoader = classOf[DefaultDBApi].getClassLoader) extends DBApi { import DefaultDBApi._ lazy val databases: Seq[Database] = { configuration.subKeys.toList map { name => val conf = configuration.getConfig(name).getOrElse { throw configuration.globalError(s"Missing configuration [db.$name]") } new PooledDatabase(name, conf, classLoader, connectionPool) } } private lazy val databaseByName: Map[String, Database] = { databases.map(db => (db.name, db)).toMap } def database(name: String): Database = { databaseByName.get(name).getOrElse { throw configuration.globalError(s"Could not find database for $name") } } /** * Try to connect to all data sources. */ def connect(logConnection: Boolean = false): Unit = { databases foreach { db => try { db.getConnection().close() if (logConnection) logger.info(s"Database [${db.name}] connected at ${db.url}") } catch { case NonFatal(e) => throw configuration.reportError(s"${db.name}.url", s"Cannot connect to database [${db.name}]", Some(e)) } } } def shutdown(): Unit = { databases foreach (_.shutdown()) } } object DefaultDBApi { private val logger = Logger(classOf[DefaultDBApi]) }
import { Injectable } from '@nestjs/common'; import { S3 } from 'aws-sdk'; import { Readable } from 'stream'; import { ConfigService } from './config.service'; @Injectable() export class AppService { static get CONTENT_DISPOSITION(): string { return 'inline'; } static get ACL(): string { return 'public-read'; } private readonly s3; constructor(private readonly config: ConfigService) { this.s3 = new S3({ accessKeyId: this.config.awsKey, secretAccessKey: this.config.awsSecret }); } async upload(fileName: string, file: Readable, mimeType: string): Promise<S3.ManagedUpload.SendData> { const s3Response = await this.s3.upload({ Key: fileName, Body: file, ContentType: mimeType, Bucket: this.config.awsS3Bucket, ACL: AppService.ACL, ContentDisposition: AppService.CONTENT_DISPOSITION, }).promise(); return s3Response; } }
/** @jsx jsx */ import { jsx } from "theme-ui" import { useTranslation } from "react-i18next" import Layout from "../components/layout" import SEO from "../components/seo" export default () => { const { t } = useTranslation("404") return ( <Layout> <SEO title={`404: ${t("notFound")}`} /> <div sx={{ variant: "container" }}> <h1>404</h1> <p>{t("notFoundMessage")}</p> </div> </Layout> ) }
export default class FragmentKind { public static readonly PREFIX = "PREFIX"; public static readonly SUFFIX = "SUFFIX"; public static readonly NGRAM = "NGRAM"; public static readonly TIME_INTERVAL = "TIME_INTERVAL"; public static readonly XYZ_TILE = "XYZ_TILE"; public static readonly IDENTITY = "IDENTITY"; }
$version = (git describe --tags --dirty) $date = Get-Date -UFormat "%m-%d-%Y" $version_cpp = @" #include "Version.h" const char * Version::build_git_version = "$version"; const char * Version::build_date = "$date"; "@ $version_cpp > "Version.cpp"
#![allow(unused_variables, unused_must_use)] extern crate sciter; use sciter::dom::event::*; use sciter::{Element, HELEMENT}; use sciter::video::{fragmented_video_destination, AssetPtr}; struct VideoGen { thread: Option<std::thread::JoinHandle<()>>, } impl Drop for VideoGen { fn drop(&mut self) { println!("[video] behavior is destroyed"); } } impl VideoGen { fn new() -> Self { Self { thread: None } } fn generation_thread(site: AssetPtr<fragmented_video_destination>) { println!("[video] thread is started"); // our video frame size and its part to update const FRAME: (i32, i32) = (1200, 800); const UPDATE: (i32, i32) = (256, 32); // our frame data (RGBA) let figure = [0xFF_FFA500u32; (UPDATE.0 * UPDATE.1) as usize]; // configure video output let mut site = site; let ok = site.start_streaming(FRAME, sciter::video::COLOR_SPACE::Rgb32, None); println!("[video] initialized: {:?}", ok); let mut x = 0; let mut xd = 1; let mut y = 0; let mut yd = 1; while site.is_alive() { // send an update portion let buf: &[u8] = unsafe { std::mem::transmute(figure.as_ref()) }; site.render_frame_part(buf, (x, y), UPDATE); // set the next position x += xd; y += yd; if x == 0 { xd = 1; } else if x + UPDATE.0 == FRAME.0 { xd = -1; } if y == 0 { yd = 1; } else if y + UPDATE.1 == FRAME.1 { yd = -1; } // simulate 25 FPS std::thread::sleep(std::time::Duration::from_millis(1000 / 25)); } site.stop_streaming(); println!("[video] thread is finished"); } } impl sciter::EventHandler for VideoGen { fn get_subscription(&mut self) -> Option<EVENT_GROUPS> { Some(EVENT_GROUPS::HANDLE_BEHAVIOR_EVENT) } fn detached(&mut self, _root: HELEMENT) { println!("[video] <video> element is detached"); if let Some(h) = self.thread.take() { h.join(); } } fn on_event( &mut self, root: HELEMENT, source: HELEMENT, target: HELEMENT, code: BEHAVIOR_EVENTS, phase: PHASE_MASK, reason: EventReason, ) -> bool { if phase != PHASE_MASK::BUBBLING { return false; } match code { BEHAVIOR_EVENTS::VIDEO_BIND_RQ => { let source = Element::from(source); println!("[video] {:?} {} ({:?})", code, source, reason); if let EventReason::VideoBind(ptr) = reason { if ptr.is_null() { // first, consume the event to announce us as a video producer. return true; } use sciter::video::*; // `VideoBind` comes with a video_destination interface let mut site = AssetPtr::from(ptr as *mut video_destination); // query a fragmented video destination interface if let Ok(fragmented) = AssetPtr::<fragmented_video_destination>::try_from(&mut site) { // and use it println!("[video] start video thread"); let tid = ::std::thread::spawn(|| VideoGen::generation_thread(fragmented)); self.thread = Some(tid); } } } BEHAVIOR_EVENTS::VIDEO_INITIALIZED => { println!("[video] {:?}", code); } BEHAVIOR_EVENTS::VIDEO_STARTED => { println!("[video] {:?}", code); let source = Element::from(source); use sciter::dom::ELEMENT_AREAS; let flags = ELEMENT_AREAS::CONTENT_BOX | ELEMENT_AREAS::SELF_RELATIVE; let rc = source.get_location(flags).unwrap(); println!("[video] start video thread on <{}> which is about {:?} pixels", source, rc.size()); } BEHAVIOR_EVENTS::VIDEO_STOPPED => { println!("[video] {:?}", code); } _ => return false, }; return true; } } fn main() { if cfg!(all(target_os = "windows", target_arch = "x86")) { println!("\nerror: Sciter video will not work on Windows x86."); println!("error: Consider using a nightly Rust version to enable `abi_thiscall`,"); println!("error: see https://github.com/rust-lang/rust/issues/42202"); println!(""); std::process::exit(126); } if sciter::version_num() < 0x04_04_02_0E { // since 4.4.2.14 println!("\nerror: `sciter::video` requires SOM support."); println!("error: Sciter API was changed in '4.4.2.14'"); println!("error: Sciter version is '{}' now", sciter::version()); println!("error: see https://sciter.com/native-code-exposure-to-script/"); println!("error: and https://sciter.com/developers/for-native-gui-programmers/sciter-object-model/"); println!(""); std::process::exit(126); } let mut frame = sciter::WindowBuilder::main_window() .with_size((750, 750)) .create(); frame.set_title("Video renderer sample"); frame.register_behavior("video-generator", || Box::new(VideoGen::new())); frame.load_html(include_bytes!("video.htm"), Some("example://video.htm")); frame.run_app(); }
package com.example.mp.retrofit import com.subscribe.snpa.SNPA.models.* import io.reactivex.Observable import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST interface NetworkApi { @POST("/add/customer") fun registerCustomer(@Body customerDTO: CustomerDTO): Observable<ResponseDTO<CustomerDTO>> @POST("/add/vendor") fun registerVendor(@Body vendorDTO: VendorDTO): Observable<ResponseDTO<VendorDTO>> @POST("/auth/vendor") fun doVendorLogin(@Body authDTO: AuthDTO): Observable<ResponseDTO<VendorDTO>> @POST("/auth/customer") fun doCustomerLogin(@Body authDTO: AuthDTO): Observable<ResponseDTO<CustomerDTO>> @GET("/area/list") fun locateArea(): Observable<ResponseListDTO<AreaDTO>> @GET("/newspaper/list") fun getNewsPapers(): Observable<ResponseListDTO<NewsPaperDTO>> @GET("/newspapers") fun subscribeNewsPaper(@Body subscribeDTO: SubscribeDTO): Observable<NewsPaper> companion object { fun getService(): NetworkApi { val retrofit = Retrofit.Builder() .baseUrl("http://d2787831.ngrok.io") .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() return retrofit.create(NetworkApi::class.java) } } }
import { WECUIComponent } from './component' export type PickerSlotItem = { slotIndex: number, divider: boolean, options?: any[] } export declare class WECPicker extends WECUIComponent { title: string slots: PickerSlotItem onModalClose: boolean itemCount?: number itemHeight?: number value?: any[] }