repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
elanderson/ASP.NET-Core-Entity-Framework
Postgres/Postgres/Data/Migrations/Contacts/20181128122253_Concurrency.Designer.cs
1791
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; using Postgres.Data; namespace Postgres.Data.Migrations.Contacts { [DbContext(typeof(ContactsDbContext))] [Migration("20181128122253_Concurrency")] partial class Concurrency { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn) .HasAnnotation("ProductVersion", "2.1.4-rtm-31024") .HasAnnotation("Relational:MaxIdentifierLength", 63); modelBuilder.Entity("Postgres.Data.Contact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address"); b.Property<string>("City"); b.Property<string>("Email"); b.Property<string>("Name"); b.Property<string>("Phone"); b.Property<string>("PostalCode"); b.Property<string>("Subregion"); b.Property<uint>("xmin") .IsConcurrencyToken() .ValueGeneratedOnAddOrUpdate() .HasColumnType("xid"); b.HasKey("Id"); b.ToTable("Contacts"); }); #pragma warning restore 612, 618 } } }
mit
oydang/CS4701-pokemon-AI
Tracer-VisualboyAdvance1.7.1/Tracer-VisualboyAdvance1.7.1/source/src/win32/GBACheats.cpp
28292
/* * VisualBoyAdvanced - Nintendo Gameboy/GameboyAdvance (TM) emulator * Copyrigh(c) 1999-2003 Forgotten (vb@emuhq.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // GBACheats.cpp : implementation file // #include "stdafx.h" #include "vba.h" #include "GBACheats.h" #include "../System.h" #include "../Cheats.h" #include "../CheatSearch.h" #include "../GBA.h" #include "../Globals.h" #include "Reg.h" #include "StringTokenizer.h" #include "WinResUtil.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // GBACheatSearch dialog GBACheatSearch::GBACheatSearch(CWnd* pParent /*=NULL*/) : CDialog(GBACheatSearch::IDD, pParent) { //{{AFX_DATA_INIT(GBACheatSearch) valueType = -1; sizeType = -1; searchType = -1; numberType = -1; updateValues = FALSE; //}}AFX_DATA_INIT data = NULL; } GBACheatSearch::~GBACheatSearch() { if(data) free(data); } void GBACheatSearch::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(GBACheatSearch) DDX_Control(pDX, IDC_VALUE, m_value); DDX_Control(pDX, IDC_CHEAT_LIST, m_list); DDX_Radio(pDX, IDC_OLD_VALUE, valueType); DDX_Radio(pDX, IDC_SIZE_8, sizeType); DDX_Radio(pDX, IDC_EQ, searchType); DDX_Radio(pDX, IDC_SIGNED, numberType); DDX_Check(pDX, IDC_UPDATE, updateValues); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(GBACheatSearch, CDialog) //{{AFX_MSG_MAP(GBACheatSearch) ON_BN_CLICKED(ID_OK, OnOk) ON_BN_CLICKED(IDC_START, OnStart) ON_BN_CLICKED(IDC_SEARCH, OnSearch) ON_BN_CLICKED(IDC_ADD_CHEAT, OnAddCheat) ON_BN_CLICKED(IDC_UPDATE, OnUpdate) ON_NOTIFY(LVN_GETDISPINFO, IDC_CHEAT_LIST, OnGetdispinfoCheatList) ON_NOTIFY(LVN_ITEMCHANGED, IDC_CHEAT_LIST, OnItemchangedCheatList) ON_CONTROL_RANGE(BN_CLICKED, IDC_OLD_VALUE, IDC_SPECIFIC_VALUE, OnValueType) ON_CONTROL_RANGE(BN_CLICKED, IDC_EQ, IDC_GE, OnSearchType) ON_CONTROL_RANGE(BN_CLICKED, IDC_SIGNED, IDC_HEXADECIMAL, OnNumberType) ON_CONTROL_RANGE(BN_CLICKED, IDC_SIZE_8, IDC_SIZE_32, OnSizeType) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // GBACheatSearch message handlers void GBACheatSearch::OnOk() { EndDialog(TRUE); } void GBACheatSearch::OnStart() { if(cheatSearchData.count == 0) { CheatSearchBlock *block = &cheatSearchData.blocks[0]; block->size = 0x40000; block->offset = 0x2000000; block->bits = (u8 *)malloc(0x40000>>3); block->data = workRAM; block->saved = (u8 *)malloc(0x40000); block = &cheatSearchData.blocks[1]; block->size = 0x8000; block->offset = 0x3000000; block->bits = (u8 *)malloc(0x8000>>3); block->data = internalRAM; block->saved = (u8 *)malloc(0x8000); cheatSearchData.count = 2; } cheatSearchStart(&cheatSearchData); GetDlgItem(IDC_SEARCH)->EnableWindow(TRUE); } void GBACheatSearch::OnSearch() { CString buffer; if(valueType == 0) cheatSearch(&cheatSearchData, searchType, sizeType, numberType == 0); else { m_value.GetWindowText(buffer); if(buffer.IsEmpty()) { systemMessage(IDS_NUMBER_CANNOT_BE_EMPTY, "Number cannot be empty"); return; } int value = 0; switch(numberType) { case 0: sscanf(buffer, "%d", &value); break; case 1: sscanf(buffer, "%u", &value); break; default: sscanf(buffer, "%x", &value); } cheatSearchValue(&cheatSearchData, searchType, sizeType, numberType == 0, value); } addChanges(true); if(updateValues) cheatSearchUpdateValues(&cheatSearchData); } void GBACheatSearch::OnAddCheat() { int mark = m_list.GetSelectionMark(); if(mark != -1) { LVITEM item; memset(&item,0, sizeof(item)); item.mask = LVIF_PARAM; item.iItem = mark; if(m_list.GetItem(&item)) { AddCheat dlg((u32)item.lParam); dlg.DoModal(); } } } void GBACheatSearch::OnUpdate() { if(GetDlgItem(IDC_UPDATE)->SendMessage(BM_GETCHECK, 0, 0) & BST_CHECKED) updateValues = true; else updateValues = false; regSetDwordValue("cheatsUpdate", updateValues); } void GBACheatSearch::OnGetdispinfoCheatList(NMHDR* pNMHDR, LRESULT* pResult) { LV_DISPINFO* info = (LV_DISPINFO*)pNMHDR; if(info->item.mask & LVIF_TEXT) { int index = info->item.iItem; int col = info->item.iSubItem; switch(col) { case 0: strcpy(info->item.pszText, data[index].address); break; case 1: strcpy(info->item.pszText, data[index].oldValue); break; case 2: strcpy(info->item.pszText, data[index].newValue); break; } } *pResult = TRUE; } void GBACheatSearch::OnItemchangedCheatList(NMHDR* pNMHDR, LRESULT* pResult) { GetDlgItem(IDC_ADD_CHEAT)->EnableWindow(m_list.GetSelectionMark() != -1); *pResult = TRUE; } BOOL GBACheatSearch::OnInitDialog() { CDialog::OnInitDialog(); CString temp = winResLoadString(IDS_ADDRESS); m_list.InsertColumn(0, temp, LVCFMT_CENTER, 125, 0); temp = winResLoadString(IDS_OLD_VALUE); m_list.InsertColumn(1, temp, LVCFMT_CENTER, 125, 1); temp = winResLoadString(IDS_NEW_VALUE); m_list.InsertColumn(2, temp, LVCFMT_CENTER, 125, 2); m_list.SetFont(CFont::FromHandle((HFONT)GetStockObject(SYSTEM_FIXED_FONT)), TRUE); m_list.SetExtendedStyle(LVS_EX_FULLROWSELECT); if(!cheatSearchData.count) { GetDlgItem(IDC_SEARCH)->EnableWindow(FALSE); GetDlgItem(IDC_ADD_CHEAT)->EnableWindow(FALSE); } valueType = regQueryDwordValue("cheatsValueType", 0); if(valueType < 0 || valueType > 1) valueType = 0; searchType = regQueryDwordValue("cheatsSearchType", SEARCH_EQ); if(searchType > 5 || searchType < 0) searchType = 0; numberType = regQueryDwordValue("cheatsNumberType", 2); if(numberType < 0 || numberType > 2) numberType = 2; sizeType = regQueryDwordValue("cheatsSizeType", 0); if(sizeType < 0 || sizeType > 2) sizeType = 0; updateValues = regQueryDwordValue("cheatsUpdate", 0) ? true : false; UpdateData(FALSE); if(valueType == 0) m_value.EnableWindow(FALSE); CenterWindow(); if(cheatSearchData.count) { addChanges(false); } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void GBACheatSearch::addChanges(bool showMsgs) { int count = cheatSearchGetCount(&cheatSearchData, sizeType); m_list.DeleteAllItems(); if(count > 1000) { if(showMsgs) systemMessage(IDS_SEARCH_PRODUCED_TOO_MANY, "Search produced %d results. Please refine better", count); return; } if(count == 0) { if(showMsgs) systemMessage(IDS_SEARCH_PRODUCED_NO_RESULTS, "Search produced no results."); return; } m_list.SetItemCount(count); if(data) free(data); data = (WinCheatsData *)calloc(count,sizeof(WinCheatsData)); int inc = 1; switch(sizeType) { case 1: inc = 2; break; case 2: inc = 4; break; } int index = 0; if(numberType == 0) { for(int i = 0; i < cheatSearchData.count; i++) { CheatSearchBlock *block = &cheatSearchData.blocks[i]; for(int j = 0; j < block->size; j+= inc) { if(IS_BIT_SET(block->bits, j)) { addChange(index++, block->offset | j, cheatSearchSignedRead(block->saved, j, sizeType), cheatSearchSignedRead(block->data, j, sizeType)); } } } } else { for(int i = 0; i < cheatSearchData.count; i++) { CheatSearchBlock *block = &cheatSearchData.blocks[i]; for(int j = 0; j < block->size; j+= inc) { if(IS_BIT_SET(block->bits, j)) { addChange(index++, block->offset | j, cheatSearchRead(block->saved, j, sizeType), cheatSearchRead(block->data, j, sizeType)); } } } } for(int i = 0; i < count; i++) { LVITEM item; item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_STATE; item.iItem = i; item.iSubItem = 0; item.lParam = data[i].addr; item.state = 0; item.stateMask = 0; item.pszText = LPSTR_TEXTCALLBACK; m_list.InsertItem(&item); m_list.SetItemText(i, 1, LPSTR_TEXTCALLBACK); m_list.SetItemText(i, 2, LPSTR_TEXTCALLBACK); } } void GBACheatSearch::addChange(int index, u32 address, u32 oldValue, u32 newValue) { data[index].addr = address; sprintf(data[index].address, "%08x",address); switch(numberType) { case 0: sprintf(data[index].oldValue, "%d", oldValue); sprintf(data[index].newValue, "%d", newValue); break; case 1: sprintf(data[index].oldValue, "%u", oldValue); sprintf(data[index].newValue, "%u", newValue); break; case 2: switch(sizeType) { case 0: sprintf(data[index].oldValue, "%02x", oldValue); sprintf(data[index].newValue, "%02x", newValue); break; case 1: sprintf(data[index].oldValue, "%04x", oldValue); sprintf(data[index].newValue, "%04x", newValue); break; case 2: sprintf(data[index].oldValue, "%08x", oldValue); sprintf(data[index].newValue, "%08x", newValue); break; } } } void GBACheatSearch::OnValueType(UINT id) { switch(id) { case IDC_OLD_VALUE: valueType = 0; m_value.EnableWindow(FALSE); regSetDwordValue("cheatsValueType", 0); break; case IDC_SPECIFIC_VALUE: valueType = 1; m_value.EnableWindow(TRUE); regSetDwordValue("cheatsValueType", 1); break; } } void GBACheatSearch::OnSearchType(UINT id) { switch(id) { case IDC_EQ: searchType = SEARCH_EQ; regSetDwordValue("cheatsSearchType", 0); break; case IDC_NE: searchType = SEARCH_NE; regSetDwordValue("cheatsSearchType", 1); break; case IDC_LT: searchType = SEARCH_LT; regSetDwordValue("cheatsSearchType", 2); break; case IDC_LE: searchType = SEARCH_LE; regSetDwordValue("cheatsSearchType", 3); break; case IDC_GT: searchType = SEARCH_GT; regSetDwordValue("cheatsSearchType", 4); break; case IDC_GE: searchType = SEARCH_GE; regSetDwordValue("cheatsSearchType", 5); break; } } void GBACheatSearch::OnNumberType(UINT id) { switch(id) { case IDC_SIGNED: numberType = 0; regSetDwordValue("cheatsNumberType", 0); if(m_list.GetItemCount()) { addChanges(false); } break; case IDC_UNSIGNED: numberType = 1; regSetDwordValue("cheatsNumberType", 1); if(m_list.GetItemCount()) { addChanges(false); } break; case IDC_HEXADECIMAL: numberType = 2; regSetDwordValue("cheatsNumberType", 2); if(m_list.GetItemCount()) { addChanges(false); } break; } } void GBACheatSearch::OnSizeType(UINT id) { switch(id) { case IDC_SIZE_8: sizeType = BITS_8; regSetDwordValue("cheatsSizeType", 0); if(m_list.GetItemCount()) { addChanges(false); } break; case IDC_SIZE_16: sizeType = BITS_16; regSetDwordValue("cheatsSizeType", 1); if(m_list.GetItemCount()) { addChanges(false); } break; case IDC_SIZE_32: sizeType = BITS_32; regSetDwordValue("cheatsSizeType", 2); if(m_list.GetItemCount()) { addChanges(false); } break; } } ///////////////////////////////////////////////////////////////////////////// // AddCheat dialog AddCheat::AddCheat(u32 address, CWnd* pParent /*=NULL*/) : CDialog(AddCheat::IDD, pParent) { //{{AFX_DATA_INIT(AddCheat) sizeType = -1; numberType = -1; //}}AFX_DATA_INIT this->address = address; } void AddCheat::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(AddCheat) DDX_Control(pDX, IDC_VALUE, m_value); DDX_Control(pDX, IDC_DESC, m_desc); DDX_Control(pDX, IDC_ADDRESS, m_address); DDX_Radio(pDX, IDC_SIZE_8, sizeType); DDX_Radio(pDX, IDC_SIGNED, numberType); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(AddCheat, CDialog) //{{AFX_MSG_MAP(AddCheat) ON_BN_CLICKED(ID_OK, OnOk) ON_BN_CLICKED(ID_CANCEL, OnCancel) ON_CONTROL_RANGE(BN_CLICKED, IDC_SIGNED, IDC_HEXADECIMAL, OnNumberType) ON_CONTROL_RANGE(BN_CLICKED, IDC_SIZE_8, IDC_SIZE_32, OnSizeType) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // AddCheat message handlers void AddCheat::OnOk() { // add cheat if(addCheat()) { EndDialog(TRUE); } } void AddCheat::OnCancel() { EndDialog(FALSE); } BOOL AddCheat::OnInitDialog() { CDialog::OnInitDialog(); if(address != 0) { CString buffer; buffer.Format("%08x", address); m_address.SetWindowText(buffer); m_address.EnableWindow(FALSE); } numberType = regQueryDwordValue("cheatsNumberType", 2); if(numberType < 0 || numberType > 2) numberType = 2; sizeType = regQueryDwordValue("cheatsSizeType", 0); if(sizeType < 0 || sizeType > 2) sizeType = 0; UpdateData(FALSE); GetDlgItem(IDC_DESC)->SendMessage(EM_LIMITTEXT, 32, 0); if(address != 0) { GetDlgItem(IDC_SIZE_8)->EnableWindow(FALSE); GetDlgItem(IDC_SIZE_16)->EnableWindow(FALSE); GetDlgItem(IDC_SIZE_32)->EnableWindow(FALSE); GetDlgItem(IDC_HEXADECIMAL)->EnableWindow(FALSE); GetDlgItem(IDC_UNSIGNED)->EnableWindow(FALSE); GetDlgItem(IDC_SIGNED)->EnableWindow(FALSE); } CenterWindow(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void AddCheat::OnNumberType(UINT id) { switch(id) { case IDC_SIGNED: numberType = 0; regSetDwordValue("cheatsNumberType", 0); break; case IDC_UNSIGNED: numberType = 1; regSetDwordValue("cheatsNumberType", 1); break; case IDC_HEXADECIMAL: numberType = 2; regSetDwordValue("cheatsNumberType", 2); break; } } void AddCheat::OnSizeType(UINT id) { switch(id) { case IDC_SIZE_8: sizeType = BITS_8; regSetDwordValue("cheatsSizeType", 0); break; case IDC_SIZE_16: sizeType = BITS_16; regSetDwordValue("cheatsSizeType", 1); break; case IDC_SIZE_32: sizeType = BITS_32; regSetDwordValue("cheatsSizeType", 2); break; } } bool AddCheat::addCheat() { CString buffer; CString code; m_address.GetWindowText(buffer); u32 address = 0; sscanf(buffer, "%x", &address); if((address >= 0x02000000 && address < 0x02040000) || (address >= 0x03000000 && address < 0x03008000)) { } else { systemMessage(IDS_INVALID_ADDRESS, "Invalid address: %08x", address); return false; } if(sizeType != 0) { if(sizeType == 1 && address & 1) { systemMessage(IDS_MISALIGNED_HALFWORD, "Misaligned half-word address: %08x", address); return false; } if(sizeType == 2 && address & 3) { systemMessage(IDS_MISALIGNED_WORD, "Misaligned word address: %08x", address); return false; } } u32 value; m_value.GetWindowText(buffer); if(buffer.IsEmpty()) { systemMessage(IDS_VALUE_CANNOT_BE_EMPTY, "Value cannot be empty"); return false; } switch(numberType) { case 0: sscanf(buffer, "%d", &value); break; case 1: sscanf(buffer, "%u", &value); break; default: sscanf(buffer, "%x", &value); } m_desc.GetWindowText(buffer); switch(sizeType) { case 0: code.Format("%08x:%02x", address, value); break; case 1: code.Format("%08x:%04x", address, value); break; case 2: code.Format("%08x:%08x", address, value); break; } cheatsAdd(code, buffer,address, value,-1, sizeType); return true; } ///////////////////////////////////////////////////////////////////////////// // GBACheatList dialog GBACheatList::GBACheatList(CWnd* pParent /*=NULL*/) : CDialog(GBACheatList::IDD, pParent) { //{{AFX_DATA_INIT(GBACheatList) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT duringRefresh = false; } void GBACheatList::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(GBACheatList) DDX_Control(pDX, IDC_RESTORE, m_restore); DDX_Control(pDX, IDC_CHEAT_LIST, m_list); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(GBACheatList, CDialog) //{{AFX_MSG_MAP(GBACheatList) ON_BN_CLICKED(IDC_ADD_CHEAT, OnAddCheat) ON_BN_CLICKED(IDC_ADD_CODE, OnAddCode) ON_BN_CLICKED(IDC_ADD_CODEBREAKER, OnAddCodebreaker) ON_BN_CLICKED(IDC_ADD_GAMESHARK, OnAddGameshark) ON_BN_CLICKED(IDC_ENABLE, OnEnable) ON_BN_CLICKED(IDC_REMOVE, OnRemove) ON_BN_CLICKED(IDC_REMOVE_ALL, OnRemoveAll) ON_BN_CLICKED(IDC_RESTORE, OnRestore) ON_BN_CLICKED(ID_OK, OnOk) ON_NOTIFY(LVN_ITEMCHANGED, IDC_CHEAT_LIST, OnItemchangedCheatList) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // GBACheatList message handlers void GBACheatList::OnAddCheat() { AddCheat dlg(0); dlg.DoModal(); refresh(); } void GBACheatList::OnAddCode() { AddCheatCode dlg; dlg.DoModal(); refresh(); } void GBACheatList::OnAddCodebreaker() { AddCBACode dlg; dlg.DoModal(); refresh(); } void GBACheatList::OnAddGameshark() { AddGSACode dlg; dlg.DoModal(); refresh(); } void GBACheatList::OnEnable() { int mark = m_list.GetSelectionMark(); int count = m_list.GetItemCount(); if(mark != -1) { LVITEM item; for(int i = 0; i < count; i++) { memset(&item,0, sizeof(item)); item.mask = LVIF_PARAM|LVIF_STATE; item.stateMask = LVIS_SELECTED; item.iItem = i; if(m_list.GetItem(&item)) { if(item.state & LVIS_SELECTED) { if(cheatsList[item.lParam].enabled) cheatsDisable(item.lParam); else cheatsEnable(item.lParam); } } } refresh(); } } void GBACheatList::OnRemove() { int mark = m_list.GetSelectionMark(); int count = m_list.GetItemCount(); if(mark != -1) { for(int i = count - 1; i >= 0; i--) { LVITEM item; memset(&item,0, sizeof(item)); item.mask = LVIF_PARAM|LVIF_STATE; item.iItem = i; item.stateMask = LVIS_SELECTED; if(m_list.GetItem(&item)) { if(item.state & LVIS_SELECTED) { cheatsDelete(item.lParam, restoreValues); } } } refresh(); } } void GBACheatList::OnRemoveAll() { cheatsDeleteAll(restoreValues); refresh(); } void GBACheatList::OnRestore() { restoreValues = !restoreValues; regSetDwordValue("cheatsRestore", restoreValues); } void GBACheatList::OnOk() { EndDialog(TRUE); } void GBACheatList::OnItemchangedCheatList(NMHDR* pNMHDR, LRESULT* pResult) { if(m_list.GetSelectionMark() != -1) { GetDlgItem(IDC_REMOVE)->EnableWindow(TRUE); GetDlgItem(IDC_ENABLE)->EnableWindow(TRUE); } else { GetDlgItem(IDC_REMOVE)->EnableWindow(FALSE); GetDlgItem(IDC_ENABLE)->EnableWindow(FALSE); } if(!duringRefresh) { LPNMLISTVIEW l = (LPNMLISTVIEW)pNMHDR; if(l->uChanged & LVIF_STATE) { if(((l->uOldState & LVIS_STATEIMAGEMASK)>>12) != (((l->uNewState & LVIS_STATEIMAGEMASK)>>12))) { if(m_list.GetCheck(l->iItem)) cheatsEnable(l->lParam); else cheatsDisable(l->lParam); refresh(); } } } *pResult = 0; } BOOL GBACheatList::OnInitDialog() { CDialog::OnInitDialog(); CString temp = winResLoadString(IDS_CODE); m_list.InsertColumn(0, temp, LVCFMT_LEFT, 170, 0); temp = winResLoadString(IDS_DESCRIPTION); m_list.InsertColumn(1, temp, LVCFMT_LEFT, 150, 1); temp = winResLoadString(IDS_STATUS); m_list.InsertColumn(2, temp, LVCFMT_LEFT, 80, 1); m_list.SetFont(CFont::FromHandle((HFONT)GetStockObject(SYSTEM_FIXED_FONT)), TRUE); m_list.SetExtendedStyle(LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT); restoreValues = regQueryDwordValue("cheatsRestore", 0) ? true : false; m_restore.SetCheck(restoreValues); refresh(); GetDlgItem(IDC_REMOVE)->EnableWindow(FALSE); GetDlgItem(IDC_ENABLE)->EnableWindow(FALSE); CenterWindow(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void GBACheatList::refresh() { duringRefresh = true; m_list.DeleteAllItems(); CString buffer; for(int i = 0; i < cheatsNumber; i++) { LVITEM item; item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_STATE; item.iItem = i; item.iSubItem = 0; item.lParam = i; item.state = 0; item.stateMask = 0; item.pszText = cheatsList[i].codestring; m_list.InsertItem(&item); m_list.SetCheck(i, (cheatsList[i].enabled) ? TRUE : FALSE); m_list.SetItemText(i, 1, cheatsList[i].desc); buffer = (cheatsList[i].enabled) ? 'E' : 'D'; m_list.SetItemText(i, 2, buffer); } duringRefresh = false; } ///////////////////////////////////////////////////////////////////////////// // AddGSACode dialog AddGSACode::AddGSACode(CWnd* pParent /*=NULL*/) : CDialog(AddGSACode::IDD, pParent) { //{{AFX_DATA_INIT(AddGSACode) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void AddGSACode::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(AddGSACode) DDX_Control(pDX, IDC_DESC, m_desc); DDX_Control(pDX, IDC_CODE, m_code); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(AddGSACode, CDialog) //{{AFX_MSG_MAP(AddGSACode) ON_BN_CLICKED(ID_OK, OnOk) ON_BN_CLICKED(ID_CANCEL, OnCancel) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // AddGSACode message handlers void AddGSACode::OnOk() { CString desc; CString buffer; CString part1; CString code; CString token; m_code.GetWindowText(buffer); m_desc.GetWindowText(desc); StringTokenizer st(buffer, " \t\n\r"); part1.Empty(); const char *t = st.next(); while(t) { token = t; token.MakeUpper(); if(token.GetLength() == 16) cheatsAddGSACode(token, desc, false); else if(token.GetLength() == 12) { code = token.Left(8); code += " "; code += token.Right(4); cheatsAddCBACode(code, desc); } else if(part1.IsEmpty()) part1 = token; else { if(token.GetLength() == 4) { code = part1; code += " "; code += token; cheatsAddCBACode(code, desc); } else { code = part1 + token; cheatsAddGSACode(code, desc, true); } part1.Empty(); } t = st.next(); } EndDialog(TRUE); } void AddGSACode::OnCancel() { EndDialog(FALSE); } BOOL AddGSACode::OnInitDialog() { CDialog::OnInitDialog(); m_code.LimitText(1024); m_desc.LimitText(32); CString title = winResLoadString(IDS_ADD_GSA_CODE); SetWindowText(title); CenterWindow(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } ///////////////////////////////////////////////////////////////////////////// // AddCBACode dialog AddCBACode::AddCBACode(CWnd* pParent /*=NULL*/) : CDialog(AddCBACode::IDD, pParent) { //{{AFX_DATA_INIT(AddCBACode) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void AddCBACode::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(AddCBACode) DDX_Control(pDX, IDC_DESC, m_desc); DDX_Control(pDX, IDC_CODE, m_code); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(AddCBACode, CDialog) //{{AFX_MSG_MAP(AddCBACode) ON_BN_CLICKED(ID_OK, OnOk) ON_BN_CLICKED(ID_CANCEL, OnCancel) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // AddCBACode message handlers void AddCBACode::OnOk() { CString desc; CString buffer; CString part1; CString code; CString token; m_code.GetWindowText(buffer); m_desc.GetWindowText(desc); StringTokenizer st(buffer, " \t\n\r"); part1.Empty(); const char *t = st.next(); while(t) { token = t; token.MakeUpper(); if(token.GetLength() == 16) cheatsAddGSACode(token, desc, false); else if(token.GetLength() == 12) { code = token.Left(8); code += " "; code += token.Right(4); cheatsAddCBACode(code, desc); } else if(part1.IsEmpty()) part1 = token; else { if(token.GetLength() == 4) { code = part1; code += " "; code += token; cheatsAddCBACode(code, desc); } else { code = part1 + token; cheatsAddGSACode(code, desc, true); } part1.Empty(); } t = st.next(); } EndDialog(TRUE); } void AddCBACode::OnCancel() { EndDialog(FALSE); } BOOL AddCBACode::OnInitDialog() { CDialog::OnInitDialog(); m_code.LimitText(1024); m_desc.LimitText(32); CString title = winResLoadString(IDS_ADD_CBA_CODE); SetWindowText(title); CenterWindow(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } ///////////////////////////////////////////////////////////////////////////// // AddCheatCode dialog AddCheatCode::AddCheatCode(CWnd* pParent /*=NULL*/) : CDialog(AddCheatCode::IDD, pParent) { //{{AFX_DATA_INIT(AddCheatCode) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void AddCheatCode::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(AddCheatCode) DDX_Control(pDX, IDC_DESC, m_desc); DDX_Control(pDX, IDC_CODE, m_code); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(AddCheatCode, CDialog) //{{AFX_MSG_MAP(AddCheatCode) ON_BN_CLICKED(ID_OK, OnOk) ON_BN_CLICKED(ID_CANCEL, OnCancel) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // AddCheatCode message handlers void AddCheatCode::OnOk() { CString desc; CString buffer; CString token; m_code.GetWindowText(buffer); m_desc.GetWindowText(desc); StringTokenizer st(buffer, " \t\n\r"); const char *t = st.next(); while(t) { token = t; token.MakeUpper(); cheatsAddCheatCode(token, desc); t = st.next(); } EndDialog(TRUE); } void AddCheatCode::OnCancel() { EndDialog(FALSE); } BOOL AddCheatCode::OnInitDialog() { CDialog::OnInitDialog(); m_code.LimitText(1024); m_desc.LimitText(32); CString title = winResLoadString(IDS_ADD_CHEAT_CODE); SetWindowText(title); CenterWindow(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
mit
kolodovskyy/joker-dmapi
lib/joker-dmapi/client.rb
3142
require "net/http" require "addressable/uri" require "#{File.dirname(__FILE__)}/version" require "#{File.dirname(__FILE__)}/result" require "#{File.dirname(__FILE__)}/contact" require "#{File.dirname(__FILE__)}/host" require "#{File.dirname(__FILE__)}/domain" module JokerDMAPI class Client include JokerDMAPI::Version DEFAULT_URI = 'https://dmapi.joker.com:443/request/' include JokerDMAPI::Result include JokerDMAPI::Contact include JokerDMAPI::Host include JokerDMAPI::Domain def initialize(username, password, uri = DEFAULT_URI) @username, @password, @uri = username, password, uri end def self.connection(username, password, uri = DEFAULT_URI, &block) connection = self.new(username, password, uri) if block_given? yield connection connection.logout else connection end end def logout unless @auth_sid.nil? query :logout @auth_sid = nil end end def query(request, params = {}) response = query_no_raise request, params return response if response[:headers][:status_code] == '0' return response if request == :logout && response[:headers][:status_code] == '1000' raise_response response end def tlds auth_sid unless @auth_sid @tlds end private def query_no_raise(request, params = {}) params['auth-sid'] = auth_sid request(request, params.inject({}) { |r, (key, value)| r[key.to_s.gsub('_', '-')] = value; r }) end def parse_line(line) parts = line.split /\s*:\s*/, 2 if parts.length == 2 { parts[0].downcase.gsub('-', '_').gsub('.', '_').to_sym => parts[1] } else line end end def parse_attributes(attributes) attributes.split("\n").inject({}) do |h, line| attribute = parse_line line h.merge!(attribute) if attribute.is_a? Hash h end end def parse_response(response) response.each_line { |line| puts "<< #{line}" } if ENV['JOKER_DMAPI_DEBUG'] parts = response.split "\n\n", 2 { headers: parse_attributes(parts[0]), body: parts[1] } end def request(request, params = {}) request = request.to_s.gsub('_', '-') uri = Addressable::URI.parse(@uri + request) uri.query_values = params http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE puts ">> #{uri}" if ENV['JOKER_DMAPI_DEBUG'] parse_response http.request(Net::HTTP::Get.new(uri.request_uri)).body end def auth_sid if @auth_sid.nil? response = request(:login, username: @username, password: @password) raise "Authentication error" unless response[:headers].has_key? :auth_sid @auth_sid = response[:headers][:auth_sid] @tlds = response[:body].split "\n" end @auth_sid end def raise_response(response) raise "\n\n" + response[:headers].inject([]) { |s, (key, value)| s << "#{key}: #{value}"}.join("\n") + "\n\n" + response[:body] + "\n\n" end end end
mit
Anastaszor/phpbbcodeparser
tests/QuoteBbcodeNodeTest.php
1460
<?php class QuoteBbcodeNodeTest extends PhpUnit_Framework_TestCase { private $_node = null; protected function setUp() { $this->_node = new QuoteBbcodeNode(); $this->_node->setAuthor("myself"); $this->_node->addChild(new TextBbcodeNode("some quoted text")); } protected function tearDown() { $this->_node = null; } public function test_isEmpty() { $this->assertFalse($this->_node->isEmpty()); } public function test_isEmpty2() { $nnode = new QuoteBbcodeNode(); $this->assertTrue($nnode->isEmpty()); } public function test_toString() { $this->assertEquals('[quote=myself]some quoted text[/quote]', $this->_node->toString()); } public function test_toHtml() { $this->assertEquals('<blockquote><cite>myself</cite>some quoted text</blockquote>', $this->_node->toHtml()); } public function test_simpleParsing() { $parser = new PhpBbcodeParser(); $node = $parser->parse('[quote=myself]some quoted text[/quote]'); $this->assertEquals($this->_node, $node); } public function test_sandwichParsing() { $parser = new PhpBbcodeParser(); $node = $parser->parse('some text before [quote=myself]some quoted text[/quote] and some text after'); $witness = new ArticleBbcodeNode(); $witness->addChild(new TextBbcodeNode("some text before ")); $witness->addChild($this->_node); $witness->addChild(new TextBbcodeNode(" and some text after")); $this->assertEquals($witness, $node); } }
mit
jwinzer/OpenSlides
server/openslides/topics/models.py
1413
from django.db import models from openslides.utils.manager import BaseManager from ..agenda.mixins import AgendaItemWithListOfSpeakersMixin from ..mediafiles.models import Mediafile from ..utils.models import RESTModelMixin from .access_permissions import TopicAccessPermissions class TopicManager(BaseManager): """ Customized model manager to support our get_prefetched_queryset method. """ def get_prefetched_queryset(self, *args, **kwargs): """ Returns the normal queryset with all topics. In the background all attachments and the related agenda item are prefetched from the database. """ return ( super() .get_prefetched_queryset(*args, **kwargs) .prefetch_related("attachments", "lists_of_speakers", "agenda_items") ) class Topic(RESTModelMixin, AgendaItemWithListOfSpeakersMixin, models.Model): """ Model for slides with custom content. Used to be called custom slide. """ access_permissions = TopicAccessPermissions() objects = TopicManager() title = models.CharField(max_length=256) text = models.TextField(blank=True) attachments = models.ManyToManyField(Mediafile, blank=True) class Meta: default_permissions = () def __str__(self): return self.title def get_title_information(self): return {"title": self.title}
mit
vanboom/active_merchant
test/remote/gateways/remote_pay_arc_test.rb
7412
require 'test_helper' class RemotePayArcTest < Test::Unit::TestCase def setup @gateway = PayArcGateway.new(fixtures(:pay_arc)) credit_card_options = { month: '12', year: '2022', first_name: 'Rex Joseph', last_name: '', verification_value: '999' } @credit_card = credit_card('4111111111111111', credit_card_options) @invalid_credit_card = credit_card('3111111111111111', credit_card_options) @invalid_cvv_card = credit_card('4111111111111111', credit_card_options.update(verification_value: '123')) @amount = 100 @options = { description: 'Store Purchase', card_source: 'INTERNET', billing_address: address.update(phone: '8772036624'), email: 'testy@test.com', phone: '8772036624' } end def test_successful_purchase response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_block do PayArcGateway::SUCCESS_STATUS.include? response.message end end def test_successful_purchase_with_more_options extra_options = { order_id: '1', ip: '127.0.0.1', email: 'joe@example.com', tip_amount: 10 } response = @gateway.purchase(1500, @credit_card, @options.merge(extra_options)) assert_success response assert_block do PayArcGateway::SUCCESS_STATUS.include? response.message end end def test_successful_two_digit_card_exp_month credit_card_options = { month: '02', year: '2022', first_name: 'Rex Joseph', last_name: '', verification_value: '999' } credit_card = credit_card('4111111111111111', credit_card_options) response = @gateway.purchase(1022, credit_card, @options) assert_success response assert_block do PayArcGateway::SUCCESS_STATUS.include? response.message end end def test_successful_one_digit_card_exp_month credit_card_options = { month: '2', year: '2022', first_name: 'Rex Joseph', last_name: '', verification_value: '999' } credit_card = credit_card('4111111111111111', credit_card_options) response = @gateway.purchase(1022, credit_card, @options) assert_success response assert_block do PayArcGateway::SUCCESS_STATUS.include? response.message end end def test_failed_three_digit_card_exp_month credit_card_options = { month: '200', year: '2022', first_name: 'Rex Joseph', last_name: '', verification_value: '999' } credit_card = credit_card('4111111111111111', credit_card_options) response = @gateway.purchase(1022, credit_card, @options) assert_failure response assert_equal 'error', response.params['status'] end def test_successful_adds_phone_number_for_purchase response = @gateway.purchase(250, @credit_card, @options) assert_success response assert_block do PayArcGateway::SUCCESS_STATUS.include? response.message end assert_equal '8772036624', response.params['receipt_phone'] end def test_failed_purchase response = @gateway.purchase(1300, @invalid_credit_card, @options) assert_failure response assert_equal 'error', response.params['status'] end def test_successful_authorize response = @gateway.authorize(1100, @credit_card, @options) assert_success response assert_equal 'authorized', response.message end # Failed due to invalid CVV def test_failed_authorize response = @gateway.authorize(500, @invalid_cvv_card, @options) assert_failure response assert_equal 'error', response.params['status'] end def test_successful_authorize_and_capture authorize_response = @gateway.authorize(2000, @credit_card, @options) assert_success authorize_response response = @gateway.capture(2000, authorize_response.authorization, @options) assert_success response assert_block do PayArcGateway::SUCCESS_STATUS.include? response.message end end def test_failed_capture response = @gateway.capture(2000, 'invalid_txn_refernece', @options) assert_failure response assert_equal 'error', response.params['status'] end def test_successful_void @options.update(reason: 'duplicate') charge_response = @gateway.purchase(1200, @credit_card, @options) assert_success charge_response assert void = @gateway.void(charge_response.authorization, @options) assert_success void assert_block do PayArcGateway::SUCCESS_STATUS.include? void.message end end def test_failed_void response = @gateway.void('invalid_txn_reference', @options) assert_failure response assert_equal 'error', response.params['status'] end def test_partial_capture authorize_response = @gateway.authorize(@amount, @credit_card, @options) assert_success authorize_response response = @gateway.capture(@amount - 1, authorize_response.authorization, @options) assert_success response assert_block do PayArcGateway::SUCCESS_STATUS.include? response.message end end def test_successful_refund purchase = @gateway.purchase(900, @credit_card, @options) assert_success purchase assert refund = @gateway.refund(900, purchase.authorization) assert_success refund assert_block do PayArcGateway::SUCCESS_STATUS.include? refund.message end assert_equal 'refunded', refund.message end def test_partial_refund purchase = @gateway.purchase(@amount, @credit_card, @options) assert_success purchase assert refund = @gateway.refund(@amount - 1, purchase.authorization) assert_success refund assert_block do PayArcGateway::SUCCESS_STATUS.include? refund.message end assert_equal 'partial_refund', refund.message end def test_failed_refund response = @gateway.refund(1200, '') assert_failure response assert_equal 'error', response.params['status'] end def test_successful_credit response = @gateway.credit(250, @credit_card, @options) assert_success response assert_block do PayArcGateway::SUCCESS_STATUS.include? response.message end assert_equal 'refunded', response.message end def test_failed_credit response = @gateway.credit('', @invalid_credit_card, @options) assert_failure response assert_equal 'error', response.params['status'] end def test_successful_verify response = @gateway.verify(@credit_card, @options) assert_success response end def test_failed_verify response = @gateway.verify(@invalid_credit_card, @options) assert_failure response assert_block do !(200..299).cover? response.error_code end end def test_invalid_login gateway = PayArcGateway.new(api_key: '<invalid bearer token>') response = gateway.purchase(@amount, @credit_card, @options) assert_failure response assert_equal 'error', response.params['status'] assert_block do !(200..299).cover? response.error_code end end def test_transcript_scrubbing transcript = capture_transcript(@gateway) do @gateway.purchase(@amount, @credit_card, @options) end transcript = @gateway.scrub(transcript) assert_scrubbed(fixtures(:pay_arc), transcript) assert_scrubbed(/card_number=#{@credit_card.number}/, transcript) assert_scrubbed(/cvv=#{@credit_card.verification_value}/, transcript) end end
mit
masa25michi/conference
fuel/app/views/layout/banner.php
523
<div class="wrapper style1 first "> <article class="container" id="top"> <div class="row"> <div class="4u 12u(mobile)"> <span class="image featured fit"><?php echo Asset::img('Hong_Kong_2017_Logo.png', array('alt'=>''));?></span> </div> <div class="8u 12u(mobile)"> <header> <h1><?php echo $banner_title; ?></h1> </header> </div> </div> </article> </div>
mit
TheGrandPackard/JMPPClient
src/com/jmpp/controllers/GUIController.java
236
package com.jmpp.controllers; public class GUIController { protected DefaultController defaultController; public void setDefaultController(DefaultController controller) { this.defaultController = controller; } }
mit
react-bootstrap/react-bootstrap
www/src/examples/Grid/ContainerFluid.js
71
<Container fluid> <Row> <Col>1 of 1</Col> </Row> </Container>;
mit
jenkinsci/tasks-plugin
src/main/java/hudson/plugins/tasks/TasksDescriptor.java
3665
package hudson.plugins.tasks; import java.io.IOException; import java.io.StringReader; import java.util.Collection; import org.apache.commons.lang3.StringUtils; import org.jenkinsci.Symbol; import org.kohsuke.stapler.QueryParameter; import hudson.Extension; import hudson.plugins.analysis.core.PluginDescriptor; import hudson.plugins.tasks.parser.Task; import hudson.plugins.tasks.parser.TaskScanner; import hudson.util.FormValidation; /** * Descriptor for the class {@link TasksPublisher}. Used as a singleton. The * class is marked as public so that it can be accessed from views. * * @author Ulli Hafner */ @Extension(ordinal = 100) @Symbol("openTasks") public final class TasksDescriptor extends PluginDescriptor { private static final String ICONS_PREFIX = "/plugin/tasks/icons/"; /** The ID of this plug-in is used as URL. */ static final String PLUGIN_ID = "tasks"; /** The URL of the result action. */ static final String RESULT_URL = PluginDescriptor.createResultUrlName(PLUGIN_ID); /** Icon to use for the result and project action. */ static final String ICON_URL = ICONS_PREFIX + "tasks-24x24.png"; /** * Creates a new instance of {@link TasksDescriptor}. */ public TasksDescriptor() { super(TasksPublisher.class); } @Override public String getDisplayName() { return Messages.Tasks_Publisher_Name(); } @Override public String getPluginName() { return PLUGIN_ID; } @Override public String getIconUrl() { return ICON_URL; } @Override public String getSummaryIconUrl() { return ICONS_PREFIX + "tasks-48x48.png"; } /** * Validates the example text that will be scanned for open tasks. * * @param example the text to be scanned for open tasks * @param high * tag identifiers indicating high priority * @param normal * tag identifiers indicating normal priority * @param low * tag identifiers indicating low priority * @param ignoreCase * if case should be ignored during matching * @param asRegexp * if the identifiers should be treated as regular expression * @return validation result * @throws IOException if an error occurs */ public FormValidation doCheckExample(@QueryParameter final String example, @QueryParameter final String high, @QueryParameter final String normal, @QueryParameter final String low, @QueryParameter final boolean ignoreCase, @QueryParameter final boolean asRegexp) throws IOException { if (StringUtils.isEmpty(example)) { return FormValidation.ok(); } TaskScanner scanner = new TaskScanner(high, normal, low, ignoreCase, asRegexp); if (scanner.isInvalidPattern()) { return FormValidation.error(scanner.getErrorMessage()); } Collection<Task> tasks = scanner.scan(new StringReader(example)); if (tasks.isEmpty()) { return FormValidation.warning(Messages.Validation_NoTask()); } else if (tasks.size() != 1) { return FormValidation.warning(Messages.Validation_MultipleTasks(tasks.size())); } else { Task task = tasks.iterator().next(); return FormValidation.ok(Messages.Validation_OneTask(task.getType(), task.getDetailMessage())); } } }
mit
EdgedesignCZ/phpqa
tests/GetVersionsTest.php
2124
<?php namespace Edge\QA\Tools; class GetVersionsTest extends \PHPUnit_Framework_TestCase { /** @dataProvider provideComposerVersion */ public function testNormalizeVersion($version, $expectedVersion) { assertThat(GetVersions::normalizeSemver($version), is($expectedVersion)); } public function provideComposerVersion() { return [ 'full semver' => ['2.7.4', '2.7.4'], 'minor release' => ['2.7.0', '2.7'], 'major release' => ['2.0.0', '2.0'], ]; } /** @dataProvider provideCliVersion */ public function testCliVersion($cliOutput, $expectedVersion) { assertThat(GetVersions::extractVersionFromConsole($cliOutput), is($expectedVersion)); } public function provideCliVersion() { return [ 'semver at the end' => ['irrelevant 0.12.86', '0.12.86'], 'semver at the start' => ['0.12.86 irrelevant', '0.12.86'], 'semver at 2nd line' => ["first\nirrele 4.8.36 vant\nsecond", '4.8.36'], 'custom format' => ['irrelevant v1.10', '1.10'], 'no space' => ['v1.13.7irrelevant', '1.13.7'], 'dev version' => ['irrelevant 4.x-dev@', '4.x'], 'prefer semver (semver + dev)' => ['v1.13.7 4.x-dev@', '1.13.7'], 'prefer semver (dev + semver)' => ['4.x-dev@ v1.13.7', '1.13.7'], 'no version' => ['irrelevant text', 'irrelevant text'], ]; } /** @dataProvider provideComparedVersions */ public function testCompareVersions($toolVersion, $operator, $version, $expectedResult) { assertThat(GetVersions::compareVersions($toolVersion, $operator, $version), is($expectedResult)); } public function provideComparedVersions() { return [ 'no version' => ['', '>', '1', false], 'is lower?' => ['7', '<', '6', false], 'is greater than dev version' => ['4', '>=', '4.x', true], 'semver is greater than' => ['4.1', '>=', '4', true], 'dev version is greater than' => ['4.x', '>=', '4', true], ]; } }
mit
rtaudio/ulltra
src/ulltra.cpp
2258
#include "UlltraProto.h" #ifndef _WIN32 #include <unistd.h> #endif #include <iostream> #include <signal.h> #include <rtt/rtt.h> #include "Controller.h" std::atomic<int> g_isRunning; Controller *g_controller; #ifdef _WIN32 void __CRTDECL sigintHandler(int sig) #else void sigintHandler(int sig) #endif { g_isRunning = false; } bool ulltraInit() { LOG(logDEBUG) << "ulltraInit():"; if (!RttThread::Init()) { LOG(logERROR) << "Failed to initialize rtt!"; return false; } LOG(logDEBUG1) << "rtt initialized!"; if (!UlltraProto::init()) { LOG(logERROR) << "Failed to initialize ulltra protocol!"; return false; } LOG(logDEBUG1) << "UlltraProto initialized!"; Discovery::initNetworking(); g_isRunning = true; signal(SIGINT, sigintHandler); LOG(logDEBUG1) << "creating controller..."; Controller::Params params; params.nodesFileName = "nodes.txt"; g_controller = new Controller(params); LOG(logINFO) << "ulltra is running ..." << std::endl; return true; } #ifdef ANDROID int ulltraMainAndroid() { LOG(logINFO) << "Ulltra android init"; return ulltraInit(); } #endif int main(int argc, const char* argv[]) { if (!ulltraInit()) return 1; /* g_isRunning = 1; JsonHttpServer server; SocketAddress httpBindAddr(Discovery::NodeDevice::localAny.getAddr(UP::HttpControlPort)); if (!server.start(httpBindAddr.toString())) { g_isRunning = false; //LOG(logERROR) << "RPC server init failed on address " << httpBindAddr.toString() << "!"; } while (g_isRunning) { server.update(); } */ RttThread::GetCurrent().SetName("main"); while (g_controller->isRunning() && g_isRunning) { #ifdef _WIN32 Sleep(1000); #else usleep(1000*1000); #endif } LOG(logINFO) << "exiting..."; return 0; } // SIG33 #ifdef ANDROID #ifdef __cplusplus extern "C" { #endif void ulltraServiceStart() { LOG(logINFO) << "Ulltra service started!"; if(ulltraInit()) LOG(logINFO) << "ulltra initialized, sleep looping..."; while (g_controller->isRunning() && g_isRunning) { usleep(1000*1000); } } void ulltraServiceStop() { g_isRunning = false; } #ifdef __cplusplus } #endif #endif
mit
EnigmaDragons/SecurityConsultantCore
src/SecurityConsultantCore/MapGeneration/ObjectInstruction.cs
3725
using System; using System.Collections.Generic; using System.Linq; using SecurityConsultantCore.Common; using SecurityConsultantCore.Domain.Basic; namespace SecurityConsultantCore.MapGeneration { public class ObjectInstruction { public ObjectInstruction(string objectName, XYOrientation placement) { ObjectName = objectName; Location = placement; } public string ObjectName { get; } public XYOrientation Location { get; } public override string ToString() { return $"{ObjectName}: ({Location})"; } protected bool Equals(ObjectInstruction other) { return string.Equals(ObjectName, other.ObjectName) && Equals(Location, other.Location); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((ObjectInstruction) obj); } public override int GetHashCode() { unchecked { return ((ObjectName?.GetHashCode() ?? 0)*397) ^ (Location?.GetHashCode() ?? 0); } } public static List<ObjectInstruction> FromString(string arg) { if (string.IsNullOrEmpty(arg) || !arg.Contains(":")) throw new ArgumentException( $"Invalid input string: '{arg}'. Expected format: 'objectname: (x, y, orientation)'"); var parts = arg.CleanAndSplit(':'); var objectName = parts.First(); var orientation = GetOrientation(parts); var placements = parts.Last().Split(';'); return CreateInstructions(placements, objectName, orientation); } private static Orientation GetOrientation(string[] parts) { return parts.Count() > 2 ? Orientation.FromAbbreviation(parts[1]) : Orientation.None; } private static List<ObjectInstruction> CreateInstructions(string[] placements, string objectName, Orientation orientation) { return placements.Where(x => x.Length > 0) .SelectMany(x => IsRangeInstruction(x) ? GetRangeInstructions(objectName, x, orientation) : new List<ObjectInstruction> { new ObjectInstruction(objectName, GetXYOrientation(x, orientation))}) .ToList(); } private static XYOrientation GetXYOrientation(string placement, Orientation defaultOrientation) { try { var loc = XYOrientation.FromString(placement); return loc.Orientation.Equals(Orientation.None) ? new XYOrientation(loc.X, loc.Y, defaultOrientation) : loc; } catch (Exception e) { throw new ArgumentException($"Invalid placement: {placement}", e); } } private static bool IsRangeInstruction(string line) { return line.Contains("-"); } private static IEnumerable<ObjectInstruction> GetRangeInstructions(string objectName, string arg, Orientation orientation) { var endpoints = arg.Split('-'); var start = GetXYOrientation(endpoints[0], orientation); var end = XY.FromString(endpoints[1]); var range = start.Thru(end); return range.Select( x => new ObjectInstruction(objectName, new XYOrientation(x.X, x.Y, start.Orientation))).ToList(); } } }
mit
inphomercial/Lootr
libs/rot.js
134306
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : factory(global.ROT = {}); })(this, function (exports) { 'use strict'; var FRAC = 2.3283064365386963e-10; var RNG = /*#__PURE__*/ function () { function RNG() { this._seed = 0; this._s0 = 0; this._s1 = 0; this._s2 = 0; this._c = 0; } var _proto = RNG.prototype; _proto.getSeed = function getSeed() { return this._seed; }; _proto.setSeed = function setSeed(seed) { seed = seed < 1 ? 1 / seed : seed; this._seed = seed; this._s0 = (seed >>> 0) * FRAC; seed = seed * 69069 + 1 >>> 0; this._s1 = seed * FRAC; seed = seed * 69069 + 1 >>> 0; this._s2 = seed * FRAC; this._c = 1; return this; }; _proto.getUniform = function getUniform() { var t = 2091639 * this._s0 + this._c * FRAC; this._s0 = this._s1; this._s1 = this._s2; this._c = t | 0; this._s2 = t - this._c; return this._s2; }; _proto.getUniformInt = function getUniformInt(lowerBound, upperBound) { var max = Math.max(lowerBound, upperBound); var min = Math.min(lowerBound, upperBound); return Math.floor(this.getUniform() * (max - min + 1)) + min; }; _proto.getNormal = function getNormal(mean, stddev) { if (mean === void 0) { mean = 0; } if (stddev === void 0) { stddev = 1; } var u, v, r; do { u = 2 * this.getUniform() - 1; v = 2 * this.getUniform() - 1; r = u * u + v * v; } while (r > 1 || r == 0); var gauss = u * Math.sqrt(-2 * Math.log(r) / r); return mean + gauss * stddev; }; _proto.getPercentage = function getPercentage() { return 1 + Math.floor(this.getUniform() * 100); }; _proto.getItem = function getItem(array) { if (!array.length) { return null; } return array[Math.floor(this.getUniform() * array.length)]; }; _proto.shuffle = function shuffle(array) { var result = []; var clone = array.slice(); while (clone.length) { var _index = clone.indexOf(this.getItem(clone)); result.push(clone.splice(_index, 1)[0]); } return result; }; _proto.getWeightedValue = function getWeightedValue(data) { var total = 0; for (var _id in data) { total += data[_id]; } var random = this.getUniform() * total; var id, part = 0; for (id in data) { part += data[id]; if (random < part) { return id; } } return id; }; _proto.getState = function getState() { return [this._s0, this._s1, this._s2, this._c]; }; _proto.setState = function setState(state) { this._s0 = state[0]; this._s1 = state[1]; this._s2 = state[2]; this._c = state[3]; return this; }; _proto.clone = function clone() { var clone = new RNG(); return clone.setState(this.getState()); }; return RNG; }(); var RNG$1 = new RNG().setSeed(Date.now()); var Backend = /*#__PURE__*/ function () { function Backend() {} var _proto2 = Backend.prototype; _proto2.getContainer = function getContainer() { return null; }; _proto2.setOptions = function setOptions(options) { this._options = options; }; return Backend; }(); var Canvas = /*#__PURE__*/ function (_Backend) { _inheritsLoose(Canvas, _Backend); function Canvas() { var _this; _this = _Backend.call(this) || this; _this._ctx = document.createElement("canvas").getContext("2d"); return _this; } var _proto3 = Canvas.prototype; _proto3.schedule = function schedule(cb) { requestAnimationFrame(cb); }; _proto3.getContainer = function getContainer() { return this._ctx.canvas; }; _proto3.setOptions = function setOptions(opts) { _Backend.prototype.setOptions.call(this, opts); var style = opts.fontStyle ? opts.fontStyle + " " : ""; var font = style + " " + opts.fontSize + "px " + opts.fontFamily; this._ctx.font = font; this._updateSize(); this._ctx.font = font; this._ctx.textAlign = "center"; this._ctx.textBaseline = "middle"; }; _proto3.clear = function clear() { this._ctx.fillStyle = this._options.bg; this._ctx.fillRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height); }; _proto3.eventToPosition = function eventToPosition(x, y) { var canvas = this._ctx.canvas; var rect = canvas.getBoundingClientRect(); x -= rect.left; y -= rect.top; x *= canvas.width / rect.width; y *= canvas.height / rect.height; if (x < 0 || y < 0 || x >= canvas.width || y >= canvas.height) { return [-1, -1]; } return this._normalizedEventToPosition(x, y); }; return Canvas; }(Backend); function mod(x, n) { return (x % n + n) % n; } function clamp(val, min, max) { if (min === void 0) { min = 0; } if (max === void 0) { max = 1; } if (val < min) return min; if (val > max) return max; return val; } function capitalize(string) { return string.charAt(0).toUpperCase() + string.substring(1); } function format(template) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var map = format.map; var replacer = function replacer(match, group1, group2, index) { if (template.charAt(index - 1) == "%") { return match.substring(1); } if (!args.length) { return match; } var obj = args[0]; var group = group1 || group2; var parts = group.split(","); var name = parts.shift() || ""; var method = map[name.toLowerCase()]; if (!method) { return match; } obj = args.shift(); var replaced = obj[method].apply(obj, parts); var first = name.charAt(0); if (first != first.toLowerCase()) { replaced = capitalize(replaced); } return replaced; }; return template.replace(/%(?:([a-z]+)|(?:{([^}]+)}))/gi, replacer); } format.map = { "s": "toString" }; var util = /*#__PURE__*/ Object.freeze({ mod: mod, clamp: clamp, capitalize: capitalize, format: format }); var Hex = /*#__PURE__*/ function (_Canvas) { _inheritsLoose(Hex, _Canvas); function Hex() { var _this2; _this2 = _Canvas.call(this) || this; _this2._spacingX = 0; _this2._spacingY = 0; _this2._hexSize = 0; return _this2; } var _proto4 = Hex.prototype; _proto4.draw = function draw(data, clearBefore) { var x = data[0], y = data[1], ch = data[2], fg = data[3], bg = data[4]; var px = [(x + 1) * this._spacingX, y * this._spacingY + this._hexSize]; if (this._options.transpose) { px.reverse(); } if (clearBefore) { this._ctx.fillStyle = bg; this._fill(px[0], px[1]); } if (!ch) { return; } this._ctx.fillStyle = fg; var chars = [].concat(ch); for (var i = 0; i < chars.length; i++) { this._ctx.fillText(chars[i], px[0], Math.ceil(px[1])); } }; _proto4.computeSize = function computeSize(availWidth, availHeight) { if (this._options.transpose) { availWidth += availHeight; availHeight = availWidth - availHeight; availWidth -= availHeight; } var width = Math.floor(availWidth / this._spacingX) - 1; var height = Math.floor((availHeight - 2 * this._hexSize) / this._spacingY + 1); return [width, height]; }; _proto4.computeFontSize = function computeFontSize(availWidth, availHeight) { if (this._options.transpose) { availWidth += availHeight; availHeight = availWidth - availHeight; availWidth -= availHeight; } var hexSizeWidth = 2 * availWidth / ((this._options.width + 1) * Math.sqrt(3)) - 1; var hexSizeHeight = availHeight / (2 + 1.5 * (this._options.height - 1)); var hexSize = Math.min(hexSizeWidth, hexSizeHeight); var oldFont = this._ctx.font; this._ctx.font = "100px " + this._options.fontFamily; var width = Math.ceil(this._ctx.measureText("W").width); this._ctx.font = oldFont; var ratio = width / 100; hexSize = Math.floor(hexSize) + 1; var fontSize = 2 * hexSize / (this._options.spacing * (1 + ratio / Math.sqrt(3))); return Math.ceil(fontSize) - 1; }; _proto4._normalizedEventToPosition = function _normalizedEventToPosition(x, y) { var nodeSize; if (this._options.transpose) { x += y; y = x - y; x -= y; nodeSize = this._ctx.canvas.width; } else { nodeSize = this._ctx.canvas.height; } var size = nodeSize / this._options.height; y = Math.floor(y / size); if (mod(y, 2)) { x -= this._spacingX; x = 1 + 2 * Math.floor(x / (2 * this._spacingX)); } else { x = 2 * Math.floor(x / (2 * this._spacingX)); } return [x, y]; }; _proto4._fill = function _fill(cx, cy) { var a = this._hexSize; var b = this._options.border; var ctx = this._ctx; ctx.beginPath(); if (this._options.transpose) { ctx.moveTo(cx - a + b, cy); ctx.lineTo(cx - a / 2 + b, cy + this._spacingX - b); ctx.lineTo(cx + a / 2 - b, cy + this._spacingX - b); ctx.lineTo(cx + a - b, cy); ctx.lineTo(cx + a / 2 - b, cy - this._spacingX + b); ctx.lineTo(cx - a / 2 + b, cy - this._spacingX + b); ctx.lineTo(cx - a + b, cy); } else { ctx.moveTo(cx, cy - a + b); ctx.lineTo(cx + this._spacingX - b, cy - a / 2 + b); ctx.lineTo(cx + this._spacingX - b, cy + a / 2 - b); ctx.lineTo(cx, cy + a - b); ctx.lineTo(cx - this._spacingX + b, cy + a / 2 - b); ctx.lineTo(cx - this._spacingX + b, cy - a / 2 + b); ctx.lineTo(cx, cy - a + b); } ctx.fill(); }; _proto4._updateSize = function _updateSize() { var opts = this._options; var charWidth = Math.ceil(this._ctx.measureText("W").width); this._hexSize = Math.floor(opts.spacing * (opts.fontSize + charWidth / Math.sqrt(3)) / 2); this._spacingX = this._hexSize * Math.sqrt(3) / 2; this._spacingY = this._hexSize * 1.5; var xprop; var yprop; if (opts.transpose) { xprop = "height"; yprop = "width"; } else { xprop = "width"; yprop = "height"; } this._ctx.canvas[xprop] = Math.ceil((opts.width + 1) * this._spacingX); this._ctx.canvas[yprop] = Math.ceil((opts.height - 1) * this._spacingY + 2 * this._hexSize); }; return Hex; }(Canvas); var Rect = /*#__PURE__*/ function (_Canvas2) { _inheritsLoose(Rect, _Canvas2); function Rect() { var _this3; _this3 = _Canvas2.call(this) || this; _this3._spacingX = 0; _this3._spacingY = 0; _this3._canvasCache = {}; return _this3; } var _proto5 = Rect.prototype; _proto5.setOptions = function setOptions(options) { _Canvas2.prototype.setOptions.call(this, options); this._canvasCache = {}; }; _proto5.draw = function draw(data, clearBefore) { if (Rect.cache) { this._drawWithCache(data); } else { this._drawNoCache(data, clearBefore); } }; _proto5._drawWithCache = function _drawWithCache(data) { var x = data[0], y = data[1], ch = data[2], fg = data[3], bg = data[4]; var hash = "" + ch + fg + bg; var canvas; if (hash in this._canvasCache) { canvas = this._canvasCache[hash]; } else { var b = this._options.border; canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); canvas.width = this._spacingX; canvas.height = this._spacingY; ctx.fillStyle = bg; ctx.fillRect(b, b, canvas.width - b, canvas.height - b); if (ch) { ctx.fillStyle = fg; ctx.font = this._ctx.font; ctx.textAlign = "center"; ctx.textBaseline = "middle"; var chars = [].concat(ch); for (var i = 0; i < chars.length; i++) { ctx.fillText(chars[i], this._spacingX / 2, Math.ceil(this._spacingY / 2)); } } this._canvasCache[hash] = canvas; } this._ctx.drawImage(canvas, x * this._spacingX, y * this._spacingY); }; _proto5._drawNoCache = function _drawNoCache(data, clearBefore) { var x = data[0], y = data[1], ch = data[2], fg = data[3], bg = data[4]; if (clearBefore) { var b = this._options.border; this._ctx.fillStyle = bg; this._ctx.fillRect(x * this._spacingX + b, y * this._spacingY + b, this._spacingX - b, this._spacingY - b); } if (!ch) { return; } this._ctx.fillStyle = fg; var chars = [].concat(ch); for (var i = 0; i < chars.length; i++) { this._ctx.fillText(chars[i], (x + 0.5) * this._spacingX, Math.ceil((y + 0.5) * this._spacingY)); } }; _proto5.computeSize = function computeSize(availWidth, availHeight) { var width = Math.floor(availWidth / this._spacingX); var height = Math.floor(availHeight / this._spacingY); return [width, height]; }; _proto5.computeFontSize = function computeFontSize(availWidth, availHeight) { var boxWidth = Math.floor(availWidth / this._options.width); var boxHeight = Math.floor(availHeight / this._options.height); var oldFont = this._ctx.font; this._ctx.font = "100px " + this._options.fontFamily; var width = Math.ceil(this._ctx.measureText("W").width); this._ctx.font = oldFont; var ratio = width / 100; var widthFraction = ratio * boxHeight / boxWidth; if (widthFraction > 1) { boxHeight = Math.floor(boxHeight / widthFraction); } return Math.floor(boxHeight / this._options.spacing); }; _proto5._normalizedEventToPosition = function _normalizedEventToPosition(x, y) { return [Math.floor(x / this._spacingX), Math.floor(y / this._spacingY)]; }; _proto5._updateSize = function _updateSize() { var opts = this._options; var charWidth = Math.ceil(this._ctx.measureText("W").width); this._spacingX = Math.ceil(opts.spacing * charWidth); this._spacingY = Math.ceil(opts.spacing * opts.fontSize); if (opts.forceSquareRatio) { this._spacingX = this._spacingY = Math.max(this._spacingX, this._spacingY); } this._ctx.canvas.width = opts.width * this._spacingX; this._ctx.canvas.height = opts.height * this._spacingY; }; return Rect; }(Canvas); Rect.cache = false; var Tile = /*#__PURE__*/ function (_Canvas3) { _inheritsLoose(Tile, _Canvas3); function Tile() { var _this4; _this4 = _Canvas3.call(this) || this; _this4._colorCanvas = document.createElement("canvas"); return _this4; } var _proto6 = Tile.prototype; _proto6.draw = function draw(data, clearBefore) { var x = data[0], y = data[1], ch = data[2], fg = data[3], bg = data[4]; var tileWidth = this._options.tileWidth; var tileHeight = this._options.tileHeight; if (clearBefore) { if (this._options.tileColorize) { this._ctx.clearRect(x * tileWidth, y * tileHeight, tileWidth, tileHeight); } else { this._ctx.fillStyle = bg; this._ctx.fillRect(x * tileWidth, y * tileHeight, tileWidth, tileHeight); } } if (!ch) { return; } var chars = [].concat(ch); var fgs = [].concat(fg); var bgs = [].concat(bg); for (var i = 0; i < chars.length; i++) { var tile = this._options.tileMap[chars[i]]; if (!tile) { throw new Error("Char \"" + chars[i] + "\" not found in tileMap"); } if (this._options.tileColorize) { var canvas = this._colorCanvas; var context = canvas.getContext("2d"); context.globalCompositeOperation = "source-over"; context.clearRect(0, 0, tileWidth, tileHeight); var _fg = fgs[i]; var _bg = bgs[i]; context.drawImage(this._options.tileSet, tile[0], tile[1], tileWidth, tileHeight, 0, 0, tileWidth, tileHeight); if (_fg != "transparent") { context.fillStyle = _fg; context.globalCompositeOperation = "source-atop"; context.fillRect(0, 0, tileWidth, tileHeight); } if (_bg != "transparent") { context.fillStyle = _bg; context.globalCompositeOperation = "destination-over"; context.fillRect(0, 0, tileWidth, tileHeight); } this._ctx.drawImage(canvas, x * tileWidth, y * tileHeight, tileWidth, tileHeight); } else { this._ctx.drawImage(this._options.tileSet, tile[0], tile[1], tileWidth, tileHeight, x * tileWidth, y * tileHeight, tileWidth, tileHeight); } } }; _proto6.computeSize = function computeSize(availWidth, availHeight) { var width = Math.floor(availWidth / this._options.tileWidth); var height = Math.floor(availHeight / this._options.tileHeight); return [width, height]; }; _proto6.computeFontSize = function computeFontSize() { throw new Error("Tile backend does not understand font size"); }; _proto6._normalizedEventToPosition = function _normalizedEventToPosition(x, y) { return [Math.floor(x / this._options.tileWidth), Math.floor(y / this._options.tileHeight)]; }; _proto6._updateSize = function _updateSize() { var opts = this._options; this._ctx.canvas.width = opts.width * opts.tileWidth; this._ctx.canvas.height = opts.height * opts.tileHeight; this._colorCanvas.width = opts.tileWidth; this._colorCanvas.height = opts.tileHeight; }; return Tile; }(Canvas); function fromString(str) { var cached, r; if (str in CACHE) { cached = CACHE[str]; } else { if (str.charAt(0) == "#") { var matched = str.match(/[0-9a-f]/gi) || []; var values = matched.map(function (x) { return parseInt(x, 16); }); if (values.length == 3) { cached = values.map(function (x) { return x * 17; }); } else { for (var i = 0; i < 3; i++) { values[i + 1] += 16 * values[i]; values.splice(i, 1); } cached = values; } } else if (r = str.match(/rgb\(([0-9, ]+)\)/i)) { cached = r[1].split(/\s*,\s*/).map(function (x) { return parseInt(x); }); } else { cached = [0, 0, 0]; } CACHE[str] = cached; } return cached.slice(); } function add(color1) { var result = color1.slice(); for (var _len2 = arguments.length, colors = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { colors[_key2 - 1] = arguments[_key2]; } for (var i = 0; i < 3; i++) { for (var j = 0; j < colors.length; j++) { result[i] += colors[j][i]; } } return result; } function add_(color1) { for (var _len3 = arguments.length, colors = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { colors[_key3 - 1] = arguments[_key3]; } for (var i = 0; i < 3; i++) { for (var j = 0; j < colors.length; j++) { color1[i] += colors[j][i]; } } return color1; } function multiply(color1) { var result = color1.slice(); for (var _len4 = arguments.length, colors = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { colors[_key4 - 1] = arguments[_key4]; } for (var i = 0; i < 3; i++) { for (var j = 0; j < colors.length; j++) { result[i] *= colors[j][i] / 255; } result[i] = Math.round(result[i]); } return result; } function multiply_(color1) { for (var _len5 = arguments.length, colors = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { colors[_key5 - 1] = arguments[_key5]; } for (var i = 0; i < 3; i++) { for (var j = 0; j < colors.length; j++) { color1[i] *= colors[j][i] / 255; } color1[i] = Math.round(color1[i]); } return color1; } function interpolate(color1, color2, factor) { if (factor === void 0) { factor = 0.5; } var result = color1.slice(); for (var i = 0; i < 3; i++) { result[i] = Math.round(result[i] + factor * (color2[i] - color1[i])); } return result; } var lerp = interpolate; function interpolateHSL(color1, color2, factor) { if (factor === void 0) { factor = 0.5; } var hsl1 = rgb2hsl(color1); var hsl2 = rgb2hsl(color2); for (var i = 0; i < 3; i++) { hsl1[i] += factor * (hsl2[i] - hsl1[i]); } return hsl2rgb(hsl1); } var lerpHSL = interpolateHSL; function randomize(color, diff) { if (!(diff instanceof Array)) { diff = Math.round(RNG$1.getNormal(0, diff)); } var result = color.slice(); for (var i = 0; i < 3; i++) { result[i] += diff instanceof Array ? Math.round(RNG$1.getNormal(0, diff[i])) : diff; } return result; } function rgb2hsl(color) { var r = color[0] / 255; var g = color[1] / 255; var b = color[2] / 255; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h = 0, s, l = (max + min) / 2; if (max == min) { s = 0; } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return [h, s, l]; } function hue2rgb(p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; } function hsl2rgb(color) { var l = color[2]; if (color[1] == 0) { l = Math.round(l * 255); return [l, l, l]; } else { var s = color[1]; var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; var r = hue2rgb(p, q, color[0] + 1 / 3); var g = hue2rgb(p, q, color[0]); var b = hue2rgb(p, q, color[0] - 1 / 3); return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; } } function toRGB(color) { var clamped = color.map(function (x) { return clamp(x, 0, 255); }); return "rgb(" + clamped.join(",") + ")"; } function toHex(color) { var clamped = color.map(function (x) { return clamp(x, 0, 255).toString(16).padStart(2, "0"); }); return "#" + clamped.join(""); } var CACHE = { "black": [0, 0, 0], "navy": [0, 0, 128], "darkblue": [0, 0, 139], "mediumblue": [0, 0, 205], "blue": [0, 0, 255], "darkgreen": [0, 100, 0], "green": [0, 128, 0], "teal": [0, 128, 128], "darkcyan": [0, 139, 139], "deepskyblue": [0, 191, 255], "darkturquoise": [0, 206, 209], "mediumspringgreen": [0, 250, 154], "lime": [0, 255, 0], "springgreen": [0, 255, 127], "aqua": [0, 255, 255], "cyan": [0, 255, 255], "midnightblue": [25, 25, 112], "dodgerblue": [30, 144, 255], "forestgreen": [34, 139, 34], "seagreen": [46, 139, 87], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "limegreen": [50, 205, 50], "mediumseagreen": [60, 179, 113], "turquoise": [64, 224, 208], "royalblue": [65, 105, 225], "steelblue": [70, 130, 180], "darkslateblue": [72, 61, 139], "mediumturquoise": [72, 209, 204], "indigo": [75, 0, 130], "darkolivegreen": [85, 107, 47], "cadetblue": [95, 158, 160], "cornflowerblue": [100, 149, 237], "mediumaquamarine": [102, 205, 170], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "slateblue": [106, 90, 205], "olivedrab": [107, 142, 35], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "mediumslateblue": [123, 104, 238], "lawngreen": [124, 252, 0], "chartreuse": [127, 255, 0], "aquamarine": [127, 255, 212], "maroon": [128, 0, 0], "purple": [128, 0, 128], "olive": [128, 128, 0], "gray": [128, 128, 128], "grey": [128, 128, 128], "skyblue": [135, 206, 235], "lightskyblue": [135, 206, 250], "blueviolet": [138, 43, 226], "darkred": [139, 0, 0], "darkmagenta": [139, 0, 139], "saddlebrown": [139, 69, 19], "darkseagreen": [143, 188, 143], "lightgreen": [144, 238, 144], "mediumpurple": [147, 112, 216], "darkviolet": [148, 0, 211], "palegreen": [152, 251, 152], "darkorchid": [153, 50, 204], "yellowgreen": [154, 205, 50], "sienna": [160, 82, 45], "brown": [165, 42, 42], "darkgray": [169, 169, 169], "darkgrey": [169, 169, 169], "lightblue": [173, 216, 230], "greenyellow": [173, 255, 47], "paleturquoise": [175, 238, 238], "lightsteelblue": [176, 196, 222], "powderblue": [176, 224, 230], "firebrick": [178, 34, 34], "darkgoldenrod": [184, 134, 11], "mediumorchid": [186, 85, 211], "rosybrown": [188, 143, 143], "darkkhaki": [189, 183, 107], "silver": [192, 192, 192], "mediumvioletred": [199, 21, 133], "indianred": [205, 92, 92], "peru": [205, 133, 63], "chocolate": [210, 105, 30], "tan": [210, 180, 140], "lightgray": [211, 211, 211], "lightgrey": [211, 211, 211], "palevioletred": [216, 112, 147], "thistle": [216, 191, 216], "orchid": [218, 112, 214], "goldenrod": [218, 165, 32], "crimson": [220, 20, 60], "gainsboro": [220, 220, 220], "plum": [221, 160, 221], "burlywood": [222, 184, 135], "lightcyan": [224, 255, 255], "lavender": [230, 230, 250], "darksalmon": [233, 150, 122], "violet": [238, 130, 238], "palegoldenrod": [238, 232, 170], "lightcoral": [240, 128, 128], "khaki": [240, 230, 140], "aliceblue": [240, 248, 255], "honeydew": [240, 255, 240], "azure": [240, 255, 255], "sandybrown": [244, 164, 96], "wheat": [245, 222, 179], "beige": [245, 245, 220], "whitesmoke": [245, 245, 245], "mintcream": [245, 255, 250], "ghostwhite": [248, 248, 255], "salmon": [250, 128, 114], "antiquewhite": [250, 235, 215], "linen": [250, 240, 230], "lightgoldenrodyellow": [250, 250, 210], "oldlace": [253, 245, 230], "red": [255, 0, 0], "fuchsia": [255, 0, 255], "magenta": [255, 0, 255], "deeppink": [255, 20, 147], "orangered": [255, 69, 0], "tomato": [255, 99, 71], "hotpink": [255, 105, 180], "coral": [255, 127, 80], "darkorange": [255, 140, 0], "lightsalmon": [255, 160, 122], "orange": [255, 165, 0], "lightpink": [255, 182, 193], "pink": [255, 192, 203], "gold": [255, 215, 0], "peachpuff": [255, 218, 185], "navajowhite": [255, 222, 173], "moccasin": [255, 228, 181], "bisque": [255, 228, 196], "mistyrose": [255, 228, 225], "blanchedalmond": [255, 235, 205], "papayawhip": [255, 239, 213], "lavenderblush": [255, 240, 245], "seashell": [255, 245, 238], "cornsilk": [255, 248, 220], "lemonchiffon": [255, 250, 205], "floralwhite": [255, 250, 240], "snow": [255, 250, 250], "yellow": [255, 255, 0], "lightyellow": [255, 255, 224], "ivory": [255, 255, 240], "white": [255, 255, 255] }; var color = /*#__PURE__*/ Object.freeze({ fromString: fromString, add: add, add_: add_, multiply: multiply, multiply_: multiply_, interpolate: interpolate, lerp: lerp, interpolateHSL: interpolateHSL, lerpHSL: lerpHSL, randomize: randomize, rgb2hsl: rgb2hsl, hsl2rgb: hsl2rgb, toRGB: toRGB, toHex: toHex }); function clearToAnsi(bg) { return "\x1B[0;48;5;" + termcolor(bg) + "m\x1B[2J"; } function colorToAnsi(fg, bg) { return "\x1B[0;38;5;" + termcolor(fg) + ";48;5;" + termcolor(bg) + "m"; } function positionToAnsi(x, y) { return "\x1B[" + (y + 1) + ";" + (x + 1) + "H"; } function termcolor(color) { var SRC_COLORS = 256.0; var DST_COLORS = 6.0; var COLOR_RATIO = DST_COLORS / SRC_COLORS; var rgb = fromString(color); var r = Math.floor(rgb[0] * COLOR_RATIO); var g = Math.floor(rgb[1] * COLOR_RATIO); var b = Math.floor(rgb[2] * COLOR_RATIO); return r * 36 + g * 6 + b * 1 + 16; } var Term = /*#__PURE__*/ function (_Backend2) { _inheritsLoose(Term, _Backend2); function Term() { var _this5; _this5 = _Backend2.call(this) || this; _this5._offset = [0, 0]; _this5._cursor = [-1, -1]; _this5._lastColor = ""; return _this5; } var _proto7 = Term.prototype; _proto7.schedule = function schedule(cb) { setTimeout(cb, 1000 / 60); }; _proto7.setOptions = function setOptions(options) { _Backend2.prototype.setOptions.call(this, options); var size = [options.width, options.height]; var avail = this.computeSize(); this._offset = avail.map(function (val, index) { return Math.floor((val - size[index]) / 2); }); }; _proto7.clear = function clear() { process.stdout.write(clearToAnsi(this._options.bg)); }; _proto7.draw = function draw(data, clearBefore) { var x = data[0], y = data[1], ch = data[2], fg = data[3], bg = data[4]; var dx = this._offset[0] + x; var dy = this._offset[1] + y; var size = this.computeSize(); if (dx < 0 || dx >= size[0]) { return; } if (dy < 0 || dy >= size[1]) { return; } if (dx !== this._cursor[0] || dy !== this._cursor[1]) { process.stdout.write(positionToAnsi(dx, dy)); this._cursor[0] = dx; this._cursor[1] = dy; } if (clearBefore) { if (!ch) { ch = " "; } } if (!ch) { return; } var newColor = colorToAnsi(fg, bg); if (newColor !== this._lastColor) { process.stdout.write(newColor); this._lastColor = newColor; } var chars = [].concat(ch); process.stdout.write(chars[0]); this._cursor[0]++; if (this._cursor[0] >= size[0]) { this._cursor[0] = 0; this._cursor[1]++; } }; _proto7.computeFontSize = function computeFontSize() { throw new Error("Terminal backend has no notion of font size"); }; _proto7.eventToPosition = function eventToPosition(x, y) { return [x, y]; }; _proto7.computeSize = function computeSize() { return [process.stdout.columns, process.stdout.rows]; }; return Term; }(Backend); var RE_COLORS = /%([bc]){([^}]*)}/g; var TYPE_TEXT = 0; var TYPE_NEWLINE = 1; var TYPE_FG = 2; var TYPE_BG = 3; function measure(str, maxWidth) { var result = { width: 0, height: 1 }; var tokens = tokenize(str, maxWidth); var lineWidth = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; switch (token.type) { case TYPE_TEXT: lineWidth += token.value.length; break; case TYPE_NEWLINE: result.height++; result.width = Math.max(result.width, lineWidth); lineWidth = 0; break; } } result.width = Math.max(result.width, lineWidth); return result; } function tokenize(str, maxWidth) { var result = []; var offset = 0; str.replace(RE_COLORS, function (match, type, name, index) { var part = str.substring(offset, index); if (part.length) { result.push({ type: TYPE_TEXT, value: part }); } result.push({ type: type == "c" ? TYPE_FG : TYPE_BG, value: name.trim() }); offset = index + match.length; return ""; }); var part = str.substring(offset); if (part.length) { result.push({ type: TYPE_TEXT, value: part }); } return breakLines(result, maxWidth); } function breakLines(tokens, maxWidth) { if (!maxWidth) { maxWidth = Infinity; } var i = 0; var lineLength = 0; var lastTokenWithSpace = -1; while (i < tokens.length) { var token = tokens[i]; if (token.type == TYPE_NEWLINE) { lineLength = 0; lastTokenWithSpace = -1; } if (token.type != TYPE_TEXT) { i++; continue; } while (lineLength == 0 && token.value.charAt(0) == " ") { token.value = token.value.substring(1); } var _index2 = token.value.indexOf("\n"); if (_index2 != -1) { token.value = breakInsideToken(tokens, i, _index2, true); var arr = token.value.split(""); while (arr.length && arr[arr.length - 1] == " ") { arr.pop(); } token.value = arr.join(""); } if (!token.value.length) { tokens.splice(i, 1); continue; } if (lineLength + token.value.length > maxWidth) { var _index3 = -1; while (1) { var nextIndex = token.value.indexOf(" ", _index3 + 1); if (nextIndex == -1) { break; } if (lineLength + nextIndex > maxWidth) { break; } _index3 = nextIndex; } if (_index3 != -1) { token.value = breakInsideToken(tokens, i, _index3, true); } else if (lastTokenWithSpace != -1) { var _token = tokens[lastTokenWithSpace]; var breakIndex = _token.value.lastIndexOf(" "); _token.value = breakInsideToken(tokens, lastTokenWithSpace, breakIndex, true); i = lastTokenWithSpace; } else { token.value = breakInsideToken(tokens, i, maxWidth - lineLength, false); } } else { lineLength += token.value.length; if (token.value.indexOf(" ") != -1) { lastTokenWithSpace = i; } } i++; } tokens.push({ type: TYPE_NEWLINE }); var lastTextToken = null; for (var _i = 0; _i < tokens.length; _i++) { var _token2 = tokens[_i]; switch (_token2.type) { case TYPE_TEXT: lastTextToken = _token2; break; case TYPE_NEWLINE: if (lastTextToken) { var _arr = lastTextToken.value.split(""); while (_arr.length && _arr[_arr.length - 1] == " ") { _arr.pop(); } lastTextToken.value = _arr.join(""); } lastTextToken = null; break; } } tokens.pop(); return tokens; } function breakInsideToken(tokens, tokenIndex, breakIndex, removeBreakChar) { var newBreakToken = { type: TYPE_NEWLINE }; var newTextToken = { type: TYPE_TEXT, value: tokens[tokenIndex].value.substring(breakIndex + (removeBreakChar ? 1 : 0)) }; tokens.splice(tokenIndex + 1, 0, newBreakToken, newTextToken); return tokens[tokenIndex].value.substring(0, breakIndex); } var text = /*#__PURE__*/ Object.freeze({ TYPE_TEXT: TYPE_TEXT, TYPE_NEWLINE: TYPE_NEWLINE, TYPE_FG: TYPE_FG, TYPE_BG: TYPE_BG, measure: measure, tokenize: tokenize }); var DEFAULT_WIDTH = 80; var DEFAULT_HEIGHT = 25; var DIRS = { 4: [[0, -1], [1, 0], [0, 1], [-1, 0]], 8: [[0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1]], 6: [[-1, -1], [1, -1], [2, 0], [1, 1], [-1, 1], [-2, 0]] }; var KEYS = { VK_CANCEL: 3, VK_HELP: 6, VK_BACK_SPACE: 8, VK_TAB: 9, VK_CLEAR: 12, VK_RETURN: 13, VK_ENTER: 14, VK_SHIFT: 16, VK_CONTROL: 17, VK_ALT: 18, VK_PAUSE: 19, VK_CAPS_LOCK: 20, VK_ESCAPE: 27, VK_SPACE: 32, VK_PAGE_UP: 33, VK_PAGE_DOWN: 34, VK_END: 35, VK_HOME: 36, VK_LEFT: 37, VK_UP: 38, VK_RIGHT: 39, VK_DOWN: 40, VK_PRINTSCREEN: 44, VK_INSERT: 45, VK_DELETE: 46, VK_0: 48, VK_1: 49, VK_2: 50, VK_3: 51, VK_4: 52, VK_5: 53, VK_6: 54, VK_7: 55, VK_8: 56, VK_9: 57, VK_COLON: 58, VK_SEMICOLON: 59, VK_LESS_THAN: 60, VK_EQUALS: 61, VK_GREATER_THAN: 62, VK_QUESTION_MARK: 63, VK_AT: 64, VK_A: 65, VK_B: 66, VK_C: 67, VK_D: 68, VK_E: 69, VK_F: 70, VK_G: 71, VK_H: 72, VK_I: 73, VK_J: 74, VK_K: 75, VK_L: 76, VK_M: 77, VK_N: 78, VK_O: 79, VK_P: 80, VK_Q: 81, VK_R: 82, VK_S: 83, VK_T: 84, VK_U: 85, VK_V: 86, VK_W: 87, VK_X: 88, VK_Y: 89, VK_Z: 90, VK_CONTEXT_MENU: 93, VK_NUMPAD0: 96, VK_NUMPAD1: 97, VK_NUMPAD2: 98, VK_NUMPAD3: 99, VK_NUMPAD4: 100, VK_NUMPAD5: 101, VK_NUMPAD6: 102, VK_NUMPAD7: 103, VK_NUMPAD8: 104, VK_NUMPAD9: 105, VK_MULTIPLY: 106, VK_ADD: 107, VK_SEPARATOR: 108, VK_SUBTRACT: 109, VK_DECIMAL: 110, VK_DIVIDE: 111, VK_F1: 112, VK_F2: 113, VK_F3: 114, VK_F4: 115, VK_F5: 116, VK_F6: 117, VK_F7: 118, VK_F8: 119, VK_F9: 120, VK_F10: 121, VK_F11: 122, VK_F12: 123, VK_F13: 124, VK_F14: 125, VK_F15: 126, VK_F16: 127, VK_F17: 128, VK_F18: 129, VK_F19: 130, VK_F20: 131, VK_F21: 132, VK_F22: 133, VK_F23: 134, VK_F24: 135, VK_NUM_LOCK: 144, VK_SCROLL_LOCK: 145, VK_CIRCUMFLEX: 160, VK_EXCLAMATION: 161, VK_DOUBLE_QUOTE: 162, VK_HASH: 163, VK_DOLLAR: 164, VK_PERCENT: 165, VK_AMPERSAND: 166, VK_UNDERSCORE: 167, VK_OPEN_PAREN: 168, VK_CLOSE_PAREN: 169, VK_ASTERISK: 170, VK_PLUS: 171, VK_PIPE: 172, VK_HYPHEN_MINUS: 173, VK_OPEN_CURLY_BRACKET: 174, VK_CLOSE_CURLY_BRACKET: 175, VK_TILDE: 176, VK_COMMA: 188, VK_PERIOD: 190, VK_SLASH: 191, VK_BACK_QUOTE: 192, VK_OPEN_BRACKET: 219, VK_BACK_SLASH: 220, VK_CLOSE_BRACKET: 221, VK_QUOTE: 222, VK_META: 224, VK_ALTGR: 225, VK_WIN: 91, VK_KANA: 21, VK_HANGUL: 21, VK_EISU: 22, VK_JUNJA: 23, VK_FINAL: 24, VK_HANJA: 25, VK_KANJI: 25, VK_CONVERT: 28, VK_NONCONVERT: 29, VK_ACCEPT: 30, VK_MODECHANGE: 31, VK_SELECT: 41, VK_PRINT: 42, VK_EXECUTE: 43, VK_SLEEP: 95 }; var BACKENDS = { "hex": Hex, "rect": Rect, "tile": Tile, "term": Term }; var DEFAULT_OPTIONS = { width: DEFAULT_WIDTH, height: DEFAULT_HEIGHT, transpose: false, layout: "rect", fontSize: 15, spacing: 1, border: 0, forceSquareRatio: false, fontFamily: "monospace", fontStyle: "", fg: "#ccc", bg: "#000", tileWidth: 32, tileHeight: 32, tileMap: {}, tileSet: null, tileColorize: false }; var Display = /*#__PURE__*/ function () { function Display(options) { if (options === void 0) { options = {}; } this._data = {}; this._dirty = false; this._options = {}; options = Object.assign({}, DEFAULT_OPTIONS, options); this.setOptions(options); this.DEBUG = this.DEBUG.bind(this); this._tick = this._tick.bind(this); this._backend.schedule(this._tick); } var _proto8 = Display.prototype; _proto8.DEBUG = function DEBUG(x, y, what) { var colors = [this._options.bg, this._options.fg]; this.draw(x, y, null, null, colors[what % colors.length]); }; _proto8.clear = function clear() { this._data = {}; this._dirty = true; }; _proto8.setOptions = function setOptions(options) { Object.assign(this._options, options); if (options.width || options.height || options.fontSize || options.fontFamily || options.spacing || options.layout) { if (options.layout) { var ctor = BACKENDS[options.layout]; this._backend = new ctor(); } this._backend.setOptions(this._options); this._dirty = true; } return this; }; _proto8.getOptions = function getOptions() { return this._options; }; _proto8.getContainer = function getContainer() { return this._backend.getContainer(); }; _proto8.computeSize = function computeSize(availWidth, availHeight) { return this._backend.computeSize(availWidth, availHeight); }; _proto8.computeFontSize = function computeFontSize(availWidth, availHeight) { return this._backend.computeFontSize(availWidth, availHeight); }; _proto8.computeTileSize = function computeTileSize(availWidth, availHeight) { var width = Math.floor(availWidth / this._options.width); var height = Math.floor(availHeight / this._options.height); return [width, height]; }; _proto8.eventToPosition = function eventToPosition(e) { var x, y; if ("touches" in e) { x = e.touches[0].clientX; y = e.touches[0].clientY; } else { x = e.clientX; y = e.clientY; } return this._backend.eventToPosition(x, y); }; _proto8.draw = function draw(x, y, ch, fg, bg) { if (!fg) { fg = this._options.fg; } if (!bg) { bg = this._options.bg; } var key = x + "," + y; this._data[key] = [x, y, ch, fg, bg]; if (this._dirty === true) { return; } if (!this._dirty) { this._dirty = {}; } this._dirty[key] = true; }; _proto8.drawText = function drawText(x, y, text, maxWidth) { var fg = null; var bg = null; var cx = x; var cy = y; var lines = 1; if (!maxWidth) { maxWidth = this._options.width - x; } var tokens = tokenize(text, maxWidth); while (tokens.length) { var token = tokens.shift(); switch (token.type) { case TYPE_TEXT: var isSpace = false, isPrevSpace = false, isFullWidth = false, isPrevFullWidth = false; for (var i = 0; i < token.value.length; i++) { var cc = token.value.charCodeAt(i); var c = token.value.charAt(i); isFullWidth = cc > 0xff00 && cc < 0xff61 || cc > 0xffdc && cc < 0xffe8 || cc > 0xffee; isSpace = c.charCodeAt(0) == 0x20 || c.charCodeAt(0) == 0x3000; if (isPrevFullWidth && !isFullWidth && !isSpace) { cx++; } if (isFullWidth && !isPrevSpace) { cx++; } this.draw(cx++, cy, c, fg, bg); isPrevSpace = isSpace; isPrevFullWidth = isFullWidth; } break; case TYPE_FG: fg = token.value || null; break; case TYPE_BG: bg = token.value || null; break; case TYPE_NEWLINE: cx = x; cy++; lines++; break; } } return lines; }; _proto8._tick = function _tick() { this._backend.schedule(this._tick); if (!this._dirty) { return; } if (this._dirty === true) { this._backend.clear(); for (var id in this._data) { this._draw(id, false); } } else { for (var key in this._dirty) { this._draw(key, true); } } this._dirty = false; }; _proto8._draw = function _draw(key, clearBefore) { var data = this._data[key]; if (data[4] != this._options.bg) { clearBefore = true; } this._backend.draw(data, clearBefore); }; return Display; }(); Display.Rect = Rect; Display.Hex = Hex; Display.Tile = Tile; Display.Term = Term; var StringGenerator = /*#__PURE__*/ function () { function StringGenerator(options) { this._options = { words: false, order: 3, prior: 0.001 }; Object.assign(this._options, options); this._boundary = String.fromCharCode(0); this._suffix = this._boundary; this._prefix = []; for (var i = 0; i < this._options.order; i++) { this._prefix.push(this._boundary); } this._priorValues = {}; this._priorValues[this._boundary] = this._options.prior; this._data = {}; } var _proto9 = StringGenerator.prototype; _proto9.clear = function clear() { this._data = {}; this._priorValues = {}; }; _proto9.generate = function generate() { var result = [this._sample(this._prefix)]; while (result[result.length - 1] != this._boundary) { result.push(this._sample(result)); } return this._join(result.slice(0, -1)); }; _proto9.observe = function observe(string) { var tokens = this._split(string); for (var i = 0; i < tokens.length; i++) { this._priorValues[tokens[i]] = this._options.prior; } tokens = this._prefix.concat(tokens).concat(this._suffix); for (var _i2 = this._options.order; _i2 < tokens.length; _i2++) { var context = tokens.slice(_i2 - this._options.order, _i2); var event = tokens[_i2]; for (var j = 0; j < context.length; j++) { var subcontext = context.slice(j); this._observeEvent(subcontext, event); } } }; _proto9.getStats = function getStats() { var parts = []; var priorCount = Object.keys(this._priorValues).length; priorCount--; parts.push("distinct samples: " + priorCount); var dataCount = Object.keys(this._data).length; var eventCount = 0; for (var p in this._data) { eventCount += Object.keys(this._data[p]).length; } parts.push("dictionary size (contexts): " + dataCount); parts.push("dictionary size (events): " + eventCount); return parts.join(", "); }; _proto9._split = function _split(str) { return str.split(this._options.words ? /\s+/ : ""); }; _proto9._join = function _join(arr) { return arr.join(this._options.words ? " " : ""); }; _proto9._observeEvent = function _observeEvent(context, event) { var key = this._join(context); if (!(key in this._data)) { this._data[key] = {}; } var data = this._data[key]; if (!(event in data)) { data[event] = 0; } data[event]++; }; _proto9._sample = function _sample(context) { context = this._backoff(context); var key = this._join(context); var data = this._data[key]; var available = {}; if (this._options.prior) { for (var event in this._priorValues) { available[event] = this._priorValues[event]; } for (var _event in data) { available[_event] += data[_event]; } } else { available = data; } return RNG$1.getWeightedValue(available); }; _proto9._backoff = function _backoff(context) { if (context.length > this._options.order) { context = context.slice(-this._options.order); } else if (context.length < this._options.order) { context = this._prefix.slice(0, this._options.order - context.length).concat(context); } while (!(this._join(context) in this._data) && context.length > 0) { context = context.slice(1); } return context; }; return StringGenerator; }(); var EventQueue = /*#__PURE__*/ function () { function EventQueue() { this._time = 0; this._events = []; this._eventTimes = []; } var _proto10 = EventQueue.prototype; _proto10.getTime = function getTime() { return this._time; }; _proto10.clear = function clear() { this._events = []; this._eventTimes = []; return this; }; _proto10.add = function add(event, time) { var index = this._events.length; for (var i = 0; i < this._eventTimes.length; i++) { if (this._eventTimes[i] > time) { index = i; break; } } this._events.splice(index, 0, event); this._eventTimes.splice(index, 0, time); }; _proto10.get = function get() { if (!this._events.length) { return null; } var time = this._eventTimes.splice(0, 1)[0]; if (time > 0) { this._time += time; for (var i = 0; i < this._eventTimes.length; i++) { this._eventTimes[i] -= time; } } return this._events.splice(0, 1)[0]; }; _proto10.getEventTime = function getEventTime(event) { var index = this._events.indexOf(event); if (index == -1) { return undefined; } return this._eventTimes[index]; }; _proto10.remove = function remove(event) { var index = this._events.indexOf(event); if (index == -1) { return false; } this._remove(index); return true; }; _proto10._remove = function _remove(index) { this._events.splice(index, 1); this._eventTimes.splice(index, 1); }; return EventQueue; }(); var Scheduler = /*#__PURE__*/ function () { function Scheduler() { this._queue = new EventQueue(); this._repeat = []; this._current = null; } var _proto11 = Scheduler.prototype; _proto11.getTime = function getTime() { return this._queue.getTime(); }; _proto11.add = function add(item, repeat) { if (repeat) { this._repeat.push(item); } return this; }; _proto11.getTimeOf = function getTimeOf(item) { return this._queue.getEventTime(item); }; _proto11.clear = function clear() { this._queue.clear(); this._repeat = []; this._current = null; return this; }; _proto11.remove = function remove(item) { var result = this._queue.remove(item); var index = this._repeat.indexOf(item); if (index != -1) { this._repeat.splice(index, 1); } if (this._current == item) { this._current = null; } return result; }; _proto11.next = function next() { this._current = this._queue.get(); return this._current; }; return Scheduler; }(); var Simple = /*#__PURE__*/ function (_Scheduler) { _inheritsLoose(Simple, _Scheduler); function Simple() { return _Scheduler.apply(this, arguments) || this; } var _proto12 = Simple.prototype; _proto12.add = function add(item, repeat) { this._queue.add(item, 0); return _Scheduler.prototype.add.call(this, item, repeat); }; _proto12.next = function next() { if (this._current && this._repeat.indexOf(this._current) != -1) { this._queue.add(this._current, 0); } return _Scheduler.prototype.next.call(this); }; return Simple; }(Scheduler); var Speed = /*#__PURE__*/ function (_Scheduler2) { _inheritsLoose(Speed, _Scheduler2); function Speed() { return _Scheduler2.apply(this, arguments) || this; } var _proto13 = Speed.prototype; _proto13.add = function add(item, repeat, time) { this._queue.add(item, time !== undefined ? time : 1 / item.getSpeed()); return _Scheduler2.prototype.add.call(this, item, repeat); }; _proto13.next = function next() { if (this._current && this._repeat.indexOf(this._current) != -1) { this._queue.add(this._current, 1 / this._current.getSpeed()); } return _Scheduler2.prototype.next.call(this); }; return Speed; }(Scheduler); var Action = /*#__PURE__*/ function (_Scheduler3) { _inheritsLoose(Action, _Scheduler3); function Action() { var _this6; _this6 = _Scheduler3.call(this) || this; _this6._defaultDuration = 1; _this6._duration = _this6._defaultDuration; return _this6; } var _proto14 = Action.prototype; _proto14.add = function add(item, repeat, time) { this._queue.add(item, time || this._defaultDuration); return _Scheduler3.prototype.add.call(this, item, repeat); }; _proto14.clear = function clear() { this._duration = this._defaultDuration; return _Scheduler3.prototype.clear.call(this); }; _proto14.remove = function remove(item) { if (item == this._current) { this._duration = this._defaultDuration; } return _Scheduler3.prototype.remove.call(this, item); }; _proto14.next = function next() { if (this._current && this._repeat.indexOf(this._current) != -1) { this._queue.add(this._current, this._duration || this._defaultDuration); this._duration = this._defaultDuration; } return _Scheduler3.prototype.next.call(this); }; _proto14.setDuration = function setDuration(time) { if (this._current) { this._duration = time; } return this; }; return Action; }(Scheduler); var index = { Simple: Simple, Speed: Speed, Action: Action }; var FOV = /*#__PURE__*/ function () { function FOV(lightPassesCallback, options) { if (options === void 0) { options = {}; } this._lightPasses = lightPassesCallback; this._options = Object.assign({ topology: 8 }, options); } var _proto15 = FOV.prototype; _proto15._getCircle = function _getCircle(cx, cy, r) { var result = []; var dirs, countFactor, startOffset; switch (this._options.topology) { case 4: countFactor = 1; startOffset = [0, 1]; dirs = [DIRS[8][7], DIRS[8][1], DIRS[8][3], DIRS[8][5]]; break; case 6: dirs = DIRS[6]; countFactor = 1; startOffset = [-1, 1]; break; case 8: dirs = DIRS[4]; countFactor = 2; startOffset = [-1, 1]; break; default: throw new Error("Incorrect topology for FOV computation"); break; } var x = cx + startOffset[0] * r; var y = cy + startOffset[1] * r; for (var i = 0; i < dirs.length; i++) { for (var j = 0; j < r * countFactor; j++) { result.push([x, y]); x += dirs[i][0]; y += dirs[i][1]; } } return result; }; return FOV; }(); var DiscreteShadowcasting = /*#__PURE__*/ function (_FOV) { _inheritsLoose(DiscreteShadowcasting, _FOV); function DiscreteShadowcasting() { return _FOV.apply(this, arguments) || this; } var _proto16 = DiscreteShadowcasting.prototype; _proto16.compute = function compute(x, y, R, callback) { callback(x, y, 0, 1); if (!this._lightPasses(x, y)) { return; } var DATA = []; var A, B, cx, cy, blocks; for (var r = 1; r <= R; r++) { var neighbors = this._getCircle(x, y, r); var angle = 360 / neighbors.length; for (var i = 0; i < neighbors.length; i++) { cx = neighbors[i][0]; cy = neighbors[i][1]; A = angle * (i - 0.5); B = A + angle; blocks = !this._lightPasses(cx, cy); if (this._visibleCoords(Math.floor(A), Math.ceil(B), blocks, DATA)) { callback(cx, cy, r, 1); } if (DATA.length == 2 && DATA[0] == 0 && DATA[1] == 360) { return; } } } }; _proto16._visibleCoords = function _visibleCoords(A, B, blocks, DATA) { if (A < 0) { var v1 = this._visibleCoords(0, B, blocks, DATA); var v2 = this._visibleCoords(360 + A, 360, blocks, DATA); return v1 || v2; } var index = 0; while (index < DATA.length && DATA[index] < A) { index++; } if (index == DATA.length) { if (blocks) { DATA.push(A, B); } return true; } var count = 0; if (index % 2) { while (index < DATA.length && DATA[index] < B) { index++; count++; } if (count == 0) { return false; } if (blocks) { if (count % 2) { DATA.splice(index - count, count, B); } else { DATA.splice(index - count, count); } } return true; } else { while (index < DATA.length && DATA[index] < B) { index++; count++; } if (A == DATA[index - count] && count == 1) { return false; } if (blocks) { if (count % 2) { DATA.splice(index - count, count, A); } else { DATA.splice(index - count, count, A, B); } } return true; } }; return DiscreteShadowcasting; }(FOV); var PreciseShadowcasting = /*#__PURE__*/ function (_FOV2) { _inheritsLoose(PreciseShadowcasting, _FOV2); function PreciseShadowcasting() { return _FOV2.apply(this, arguments) || this; } var _proto17 = PreciseShadowcasting.prototype; _proto17.compute = function compute(x, y, R, callback) { callback(x, y, 0, 1); if (!this._lightPasses(x, y)) { return; } var SHADOWS = []; var cx, cy, blocks, A1, A2, visibility; for (var r = 1; r <= R; r++) { var neighbors = this._getCircle(x, y, r); var neighborCount = neighbors.length; for (var i = 0; i < neighborCount; i++) { cx = neighbors[i][0]; cy = neighbors[i][1]; A1 = [i ? 2 * i - 1 : 2 * neighborCount - 1, 2 * neighborCount]; A2 = [2 * i + 1, 2 * neighborCount]; blocks = !this._lightPasses(cx, cy); visibility = this._checkVisibility(A1, A2, blocks, SHADOWS); if (visibility) { callback(cx, cy, r, visibility); } if (SHADOWS.length == 2 && SHADOWS[0][0] == 0 && SHADOWS[1][0] == SHADOWS[1][1]) { return; } } } }; _proto17._checkVisibility = function _checkVisibility(A1, A2, blocks, SHADOWS) { if (A1[0] > A2[0]) { var v1 = this._checkVisibility(A1, [A1[1], A1[1]], blocks, SHADOWS); var v2 = this._checkVisibility([0, 1], A2, blocks, SHADOWS); return (v1 + v2) / 2; } var index1 = 0, edge1 = false; while (index1 < SHADOWS.length) { var old = SHADOWS[index1]; var diff = old[0] * A1[1] - A1[0] * old[1]; if (diff >= 0) { if (diff == 0 && !(index1 % 2)) { edge1 = true; } break; } index1++; } var index2 = SHADOWS.length, edge2 = false; while (index2--) { var _old = SHADOWS[index2]; var _diff = A2[0] * _old[1] - _old[0] * A2[1]; if (_diff >= 0) { if (_diff == 0 && index2 % 2) { edge2 = true; } break; } } var visible = true; if (index1 == index2 && (edge1 || edge2)) { visible = false; } else if (edge1 && edge2 && index1 + 1 == index2 && index2 % 2) { visible = false; } else if (index1 > index2 && index1 % 2) { visible = false; } if (!visible) { return 0; } var visibleLength; var remove = index2 - index1 + 1; if (remove % 2) { if (index1 % 2) { var P = SHADOWS[index1]; visibleLength = (A2[0] * P[1] - P[0] * A2[1]) / (P[1] * A2[1]); if (blocks) { SHADOWS.splice(index1, remove, A2); } } else { var _P = SHADOWS[index2]; visibleLength = (_P[0] * A1[1] - A1[0] * _P[1]) / (A1[1] * _P[1]); if (blocks) { SHADOWS.splice(index1, remove, A1); } } } else { if (index1 % 2) { var P1 = SHADOWS[index1]; var P2 = SHADOWS[index2]; visibleLength = (P2[0] * P1[1] - P1[0] * P2[1]) / (P1[1] * P2[1]); if (blocks) { SHADOWS.splice(index1, remove); } } else { if (blocks) { SHADOWS.splice(index1, remove, A1, A2); } return 1; } } var arcLength = (A2[0] * A1[1] - A1[0] * A2[1]) / (A1[1] * A2[1]); return visibleLength / arcLength; }; return PreciseShadowcasting; }(FOV); var OCTANTS = [[-1, 0, 0, 1], [0, -1, 1, 0], [0, -1, -1, 0], [-1, 0, 0, -1], [1, 0, 0, -1], [0, 1, -1, 0], [0, 1, 1, 0], [1, 0, 0, 1]]; var RecursiveShadowcasting = /*#__PURE__*/ function (_FOV3) { _inheritsLoose(RecursiveShadowcasting, _FOV3); function RecursiveShadowcasting() { return _FOV3.apply(this, arguments) || this; } var _proto18 = RecursiveShadowcasting.prototype; _proto18.compute = function compute(x, y, R, callback) { callback(x, y, 0, 1); for (var i = 0; i < OCTANTS.length; i++) { this._renderOctant(x, y, OCTANTS[i], R, callback); } }; _proto18.compute180 = function compute180(x, y, R, dir, callback) { callback(x, y, 0, 1); var previousOctant = (dir - 1 + 8) % 8; var nextPreviousOctant = (dir - 2 + 8) % 8; var nextOctant = (dir + 1 + 8) % 8; this._renderOctant(x, y, OCTANTS[nextPreviousOctant], R, callback); this._renderOctant(x, y, OCTANTS[previousOctant], R, callback); this._renderOctant(x, y, OCTANTS[dir], R, callback); this._renderOctant(x, y, OCTANTS[nextOctant], R, callback); }; _proto18.compute90 = function compute90(x, y, R, dir, callback) { callback(x, y, 0, 1); var previousOctant = (dir - 1 + 8) % 8; this._renderOctant(x, y, OCTANTS[dir], R, callback); this._renderOctant(x, y, OCTANTS[previousOctant], R, callback); }; _proto18._renderOctant = function _renderOctant(x, y, octant, R, callback) { this._castVisibility(x, y, 1, 1.0, 0.0, R + 1, octant[0], octant[1], octant[2], octant[3], callback); }; _proto18._castVisibility = function _castVisibility(startX, startY, row, visSlopeStart, visSlopeEnd, radius, xx, xy, yx, yy, callback) { if (visSlopeStart < visSlopeEnd) { return; } for (var i = row; i <= radius; i++) { var dx = -i - 1; var dy = -i; var blocked = false; var newStart = 0; while (dx <= 0) { dx += 1; var mapX = startX + dx * xx + dy * xy; var mapY = startY + dx * yx + dy * yy; var slopeStart = (dx - 0.5) / (dy + 0.5); var slopeEnd = (dx + 0.5) / (dy - 0.5); if (slopeEnd > visSlopeStart) { continue; } if (slopeStart < visSlopeEnd) { break; } if (dx * dx + dy * dy < radius * radius) { callback(mapX, mapY, i, 1); } if (!blocked) { if (!this._lightPasses(mapX, mapY) && i < radius) { blocked = true; this._castVisibility(startX, startY, i + 1, visSlopeStart, slopeStart, radius, xx, xy, yx, yy, callback); newStart = slopeEnd; } } else { if (!this._lightPasses(mapX, mapY)) { newStart = slopeEnd; continue; } blocked = false; visSlopeStart = newStart; } } if (blocked) { break; } } }; return RecursiveShadowcasting; }(FOV); var index$1 = { DiscreteShadowcasting: DiscreteShadowcasting, PreciseShadowcasting: PreciseShadowcasting, RecursiveShadowcasting: RecursiveShadowcasting }; var Map = /*#__PURE__*/ function () { function Map(width, height) { if (width === void 0) { width = DEFAULT_WIDTH; } if (height === void 0) { height = DEFAULT_HEIGHT; } this._width = width; this._height = height; } var _proto19 = Map.prototype; _proto19._fillMap = function _fillMap(value) { var map = []; for (var i = 0; i < this._width; i++) { map.push([]); for (var j = 0; j < this._height; j++) { map[i].push(value); } } return map; }; return Map; }(); var Arena = /*#__PURE__*/ function (_Map) { _inheritsLoose(Arena, _Map); function Arena() { return _Map.apply(this, arguments) || this; } var _proto20 = Arena.prototype; _proto20.create = function create(callback) { var w = this._width - 1; var h = this._height - 1; for (var i = 0; i <= w; i++) { for (var j = 0; j <= h; j++) { var empty = i && j && i < w && j < h; callback(i, j, empty ? 0 : 1); } } return this; }; return Arena; }(Map); var Dungeon = /*#__PURE__*/ function (_Map2) { _inheritsLoose(Dungeon, _Map2); function Dungeon(width, height) { var _this7; _this7 = _Map2.call(this, width, height) || this; _this7._rooms = []; _this7._corridors = []; return _this7; } var _proto21 = Dungeon.prototype; _proto21.getRooms = function getRooms() { return this._rooms; }; _proto21.getCorridors = function getCorridors() { return this._corridors; }; return Dungeon; }(Map); var Feature = function Feature() {}; var Room = /*#__PURE__*/ function (_Feature) { _inheritsLoose(Room, _Feature); function Room(x1, y1, x2, y2, doorX, doorY) { var _this8; _this8 = _Feature.call(this) || this; _this8._x1 = x1; _this8._y1 = y1; _this8._x2 = x2; _this8._y2 = y2; _this8._doors = {}; if (doorX !== undefined && doorY !== undefined) { _this8.addDoor(doorX, doorY); } return _this8; } Room.createRandomAt = function createRandomAt(x, y, dx, dy, options) { var min = options.roomWidth[0]; var max = options.roomWidth[1]; var width = RNG$1.getUniformInt(min, max); min = options.roomHeight[0]; max = options.roomHeight[1]; var height = RNG$1.getUniformInt(min, max); if (dx == 1) { var y2 = y - Math.floor(RNG$1.getUniform() * height); return new this(x + 1, y2, x + width, y2 + height - 1, x, y); } if (dx == -1) { var _y = y - Math.floor(RNG$1.getUniform() * height); return new this(x - width, _y, x - 1, _y + height - 1, x, y); } if (dy == 1) { var x2 = x - Math.floor(RNG$1.getUniform() * width); return new this(x2, y + 1, x2 + width - 1, y + height, x, y); } if (dy == -1) { var _x = x - Math.floor(RNG$1.getUniform() * width); return new this(_x, y - height, _x + width - 1, y - 1, x, y); } throw new Error("dx or dy must be 1 or -1"); }; Room.createRandomCenter = function createRandomCenter(cx, cy, options) { var min = options.roomWidth[0]; var max = options.roomWidth[1]; var width = RNG$1.getUniformInt(min, max); min = options.roomHeight[0]; max = options.roomHeight[1]; var height = RNG$1.getUniformInt(min, max); var x1 = cx - Math.floor(RNG$1.getUniform() * width); var y1 = cy - Math.floor(RNG$1.getUniform() * height); var x2 = x1 + width - 1; var y2 = y1 + height - 1; return new this(x1, y1, x2, y2); }; Room.createRandom = function createRandom(availWidth, availHeight, options) { var min = options.roomWidth[0]; var max = options.roomWidth[1]; var width = RNG$1.getUniformInt(min, max); min = options.roomHeight[0]; max = options.roomHeight[1]; var height = RNG$1.getUniformInt(min, max); var left = availWidth - width - 1; var top = availHeight - height - 1; var x1 = 1 + Math.floor(RNG$1.getUniform() * left); var y1 = 1 + Math.floor(RNG$1.getUniform() * top); var x2 = x1 + width - 1; var y2 = y1 + height - 1; return new this(x1, y1, x2, y2); }; var _proto22 = Room.prototype; _proto22.addDoor = function addDoor(x, y) { this._doors[x + "," + y] = 1; return this; }; _proto22.getDoors = function getDoors(cb) { for (var key in this._doors) { var parts = key.split(","); cb(parseInt(parts[0]), parseInt(parts[1])); } return this; }; _proto22.clearDoors = function clearDoors() { this._doors = {}; return this; }; _proto22.addDoors = function addDoors(isWallCallback) { var left = this._x1 - 1; var right = this._x2 + 1; var top = this._y1 - 1; var bottom = this._y2 + 1; for (var x = left; x <= right; x++) { for (var y = top; y <= bottom; y++) { if (x != left && x != right && y != top && y != bottom) { continue; } if (isWallCallback(x, y)) { continue; } this.addDoor(x, y); } } return this; }; _proto22.debug = function debug() { console.log("room", this._x1, this._y1, this._x2, this._y2); }; _proto22.isValid = function isValid(isWallCallback, canBeDugCallback) { var left = this._x1 - 1; var right = this._x2 + 1; var top = this._y1 - 1; var bottom = this._y2 + 1; for (var x = left; x <= right; x++) { for (var y = top; y <= bottom; y++) { if (x == left || x == right || y == top || y == bottom) { if (!isWallCallback(x, y)) { return false; } } else { if (!canBeDugCallback(x, y)) { return false; } } } } return true; }; _proto22.create = function create(digCallback) { var left = this._x1 - 1; var right = this._x2 + 1; var top = this._y1 - 1; var bottom = this._y2 + 1; var value = 0; for (var x = left; x <= right; x++) { for (var y = top; y <= bottom; y++) { if (x + "," + y in this._doors) { value = 2; } else if (x == left || x == right || y == top || y == bottom) { value = 1; } else { value = 0; } digCallback(x, y, value); } } }; _proto22.getCenter = function getCenter() { return [Math.round((this._x1 + this._x2) / 2), Math.round((this._y1 + this._y2) / 2)]; }; _proto22.getLeft = function getLeft() { return this._x1; }; _proto22.getRight = function getRight() { return this._x2; }; _proto22.getTop = function getTop() { return this._y1; }; _proto22.getBottom = function getBottom() { return this._y2; }; return Room; }(Feature); var Corridor = /*#__PURE__*/ function (_Feature2) { _inheritsLoose(Corridor, _Feature2); function Corridor(startX, startY, endX, endY) { var _this9; _this9 = _Feature2.call(this) || this; _this9._startX = startX; _this9._startY = startY; _this9._endX = endX; _this9._endY = endY; _this9._endsWithAWall = true; return _this9; } Corridor.createRandomAt = function createRandomAt(x, y, dx, dy, options) { var min = options.corridorLength[0]; var max = options.corridorLength[1]; var length = RNG$1.getUniformInt(min, max); return new this(x, y, x + dx * length, y + dy * length); }; var _proto23 = Corridor.prototype; _proto23.debug = function debug() { console.log("corridor", this._startX, this._startY, this._endX, this._endY); }; _proto23.isValid = function isValid(isWallCallback, canBeDugCallback) { var sx = this._startX; var sy = this._startY; var dx = this._endX - sx; var dy = this._endY - sy; var length = 1 + Math.max(Math.abs(dx), Math.abs(dy)); if (dx) { dx = dx / Math.abs(dx); } if (dy) { dy = dy / Math.abs(dy); } var nx = dy; var ny = -dx; var ok = true; for (var i = 0; i < length; i++) { var x = sx + i * dx; var y = sy + i * dy; if (!canBeDugCallback(x, y)) { ok = false; } if (!isWallCallback(x + nx, y + ny)) { ok = false; } if (!isWallCallback(x - nx, y - ny)) { ok = false; } if (!ok) { length = i; this._endX = x - dx; this._endY = y - dy; break; } } if (length == 0) { return false; } if (length == 1 && isWallCallback(this._endX + dx, this._endY + dy)) { return false; } var firstCornerBad = !isWallCallback(this._endX + dx + nx, this._endY + dy + ny); var secondCornerBad = !isWallCallback(this._endX + dx - nx, this._endY + dy - ny); this._endsWithAWall = isWallCallback(this._endX + dx, this._endY + dy); if ((firstCornerBad || secondCornerBad) && this._endsWithAWall) { return false; } return true; }; _proto23.create = function create(digCallback) { var sx = this._startX; var sy = this._startY; var dx = this._endX - sx; var dy = this._endY - sy; var length = 1 + Math.max(Math.abs(dx), Math.abs(dy)); if (dx) { dx = dx / Math.abs(dx); } if (dy) { dy = dy / Math.abs(dy); } for (var i = 0; i < length; i++) { var x = sx + i * dx; var y = sy + i * dy; digCallback(x, y, 0); } return true; }; _proto23.createPriorityWalls = function createPriorityWalls(priorityWallCallback) { if (!this._endsWithAWall) { return; } var sx = this._startX; var sy = this._startY; var dx = this._endX - sx; var dy = this._endY - sy; if (dx) { dx = dx / Math.abs(dx); } if (dy) { dy = dy / Math.abs(dy); } var nx = dy; var ny = -dx; priorityWallCallback(this._endX + dx, this._endY + dy); priorityWallCallback(this._endX + nx, this._endY + ny); priorityWallCallback(this._endX - nx, this._endY - ny); }; return Corridor; }(Feature); var Uniform = /*#__PURE__*/ function (_Dungeon) { _inheritsLoose(Uniform, _Dungeon); function Uniform(width, height, options) { var _this10; _this10 = _Dungeon.call(this, width, height) || this; _this10._options = { roomWidth: [3, 9], roomHeight: [3, 5], roomDugPercentage: 0.1, timeLimit: 1000 }; Object.assign(_this10._options, options); _this10._map = []; _this10._dug = 0; _this10._roomAttempts = 20; _this10._corridorAttempts = 20; _this10._connected = []; _this10._unconnected = []; _this10._digCallback = _this10._digCallback.bind(_assertThisInitialized(_assertThisInitialized(_this10))); _this10._canBeDugCallback = _this10._canBeDugCallback.bind(_assertThisInitialized(_assertThisInitialized(_this10))); _this10._isWallCallback = _this10._isWallCallback.bind(_assertThisInitialized(_assertThisInitialized(_this10))); return _this10; } var _proto24 = Uniform.prototype; _proto24.create = function create(callback) { var t1 = Date.now(); while (1) { var t2 = Date.now(); if (t2 - t1 > this._options.timeLimit) { return null; } this._map = this._fillMap(1); this._dug = 0; this._rooms = []; this._unconnected = []; this._generateRooms(); if (this._rooms.length < 2) { continue; } if (this._generateCorridors()) { break; } } if (callback) { for (var i = 0; i < this._width; i++) { for (var j = 0; j < this._height; j++) { callback(i, j, this._map[i][j]); } } } return this; }; _proto24._generateRooms = function _generateRooms() { var w = this._width - 2; var h = this._height - 2; var room; do { room = this._generateRoom(); if (this._dug / (w * h) > this._options.roomDugPercentage) { break; } } while (room); }; _proto24._generateRoom = function _generateRoom() { var count = 0; while (count < this._roomAttempts) { count++; var room = Room.createRandom(this._width, this._height, this._options); if (!room.isValid(this._isWallCallback, this._canBeDugCallback)) { continue; } room.create(this._digCallback); this._rooms.push(room); return room; } return null; }; _proto24._generateCorridors = function _generateCorridors() { var cnt = 0; while (cnt < this._corridorAttempts) { cnt++; this._corridors = []; this._map = this._fillMap(1); for (var i = 0; i < this._rooms.length; i++) { var room = this._rooms[i]; room.clearDoors(); room.create(this._digCallback); } this._unconnected = RNG$1.shuffle(this._rooms.slice()); this._connected = []; if (this._unconnected.length) { this._connected.push(this._unconnected.pop()); } while (1) { var connected = RNG$1.getItem(this._connected); if (!connected) { break; } var room1 = this._closestRoom(this._unconnected, connected); if (!room1) { break; } var room2 = this._closestRoom(this._connected, room1); if (!room2) { break; } var ok = this._connectRooms(room1, room2); if (!ok) { break; } if (!this._unconnected.length) { return true; } } } return false; }; _proto24._closestRoom = function _closestRoom(rooms, room) { var dist = Infinity; var center = room.getCenter(); var result = null; for (var i = 0; i < rooms.length; i++) { var r = rooms[i]; var c = r.getCenter(); var dx = c[0] - center[0]; var dy = c[1] - center[1]; var d = dx * dx + dy * dy; if (d < dist) { dist = d; result = r; } } return result; }; _proto24._connectRooms = function _connectRooms(room1, room2) { var center1 = room1.getCenter(); var center2 = room2.getCenter(); var diffX = center2[0] - center1[0]; var diffY = center2[1] - center1[1]; var start; var end; var dirIndex1, dirIndex2, min, max, index; if (Math.abs(diffX) < Math.abs(diffY)) { dirIndex1 = diffY > 0 ? 2 : 0; dirIndex2 = (dirIndex1 + 2) % 4; min = room2.getLeft(); max = room2.getRight(); index = 0; } else { dirIndex1 = diffX > 0 ? 1 : 3; dirIndex2 = (dirIndex1 + 2) % 4; min = room2.getTop(); max = room2.getBottom(); index = 1; } start = this._placeInWall(room1, dirIndex1); if (!start) { return false; } if (start[index] >= min && start[index] <= max) { end = start.slice(); var value = 0; switch (dirIndex2) { case 0: value = room2.getTop() - 1; break; case 1: value = room2.getRight() + 1; break; case 2: value = room2.getBottom() + 1; break; case 3: value = room2.getLeft() - 1; break; } end[(index + 1) % 2] = value; this._digLine([start, end]); } else if (start[index] < min - 1 || start[index] > max + 1) { var diff = start[index] - center2[index]; var rotation = 0; switch (dirIndex2) { case 0: case 1: rotation = diff < 0 ? 3 : 1; break; case 2: case 3: rotation = diff < 0 ? 1 : 3; break; } dirIndex2 = (dirIndex2 + rotation) % 4; end = this._placeInWall(room2, dirIndex2); if (!end) { return false; } var mid = [0, 0]; mid[index] = start[index]; var index2 = (index + 1) % 2; mid[index2] = end[index2]; this._digLine([start, mid, end]); } else { var _index4 = (index + 1) % 2; end = this._placeInWall(room2, dirIndex2); if (!end) { return false; } var _mid = Math.round((end[_index4] + start[_index4]) / 2); var mid1 = [0, 0]; var mid2 = [0, 0]; mid1[index] = start[index]; mid1[_index4] = _mid; mid2[index] = end[index]; mid2[_index4] = _mid; this._digLine([start, mid1, mid2, end]); } room1.addDoor(start[0], start[1]); room2.addDoor(end[0], end[1]); index = this._unconnected.indexOf(room1); if (index != -1) { this._unconnected.splice(index, 1); this._connected.push(room1); } index = this._unconnected.indexOf(room2); if (index != -1) { this._unconnected.splice(index, 1); this._connected.push(room2); } return true; }; _proto24._placeInWall = function _placeInWall(room, dirIndex) { var start = [0, 0]; var dir = [0, 0]; var length = 0; switch (dirIndex) { case 0: dir = [1, 0]; start = [room.getLeft(), room.getTop() - 1]; length = room.getRight() - room.getLeft() + 1; break; case 1: dir = [0, 1]; start = [room.getRight() + 1, room.getTop()]; length = room.getBottom() - room.getTop() + 1; break; case 2: dir = [1, 0]; start = [room.getLeft(), room.getBottom() + 1]; length = room.getRight() - room.getLeft() + 1; break; case 3: dir = [0, 1]; start = [room.getLeft() - 1, room.getTop()]; length = room.getBottom() - room.getTop() + 1; break; } var avail = []; var lastBadIndex = -2; for (var i = 0; i < length; i++) { var x = start[0] + i * dir[0]; var y = start[1] + i * dir[1]; avail.push(null); var isWall = this._map[x][y] == 1; if (isWall) { if (lastBadIndex != i - 1) { avail[i] = [x, y]; } } else { lastBadIndex = i; if (i) { avail[i - 1] = null; } } } for (var _i3 = avail.length - 1; _i3 >= 0; _i3--) { if (!avail[_i3]) { avail.splice(_i3, 1); } } return avail.length ? RNG$1.getItem(avail) : null; }; _proto24._digLine = function _digLine(points) { for (var i = 1; i < points.length; i++) { var start = points[i - 1]; var end = points[i]; var corridor = new Corridor(start[0], start[1], end[0], end[1]); corridor.create(this._digCallback); this._corridors.push(corridor); } }; _proto24._digCallback = function _digCallback(x, y, value) { this._map[x][y] = value; if (value == 0) { this._dug++; } }; _proto24._isWallCallback = function _isWallCallback(x, y) { if (x < 0 || y < 0 || x >= this._width || y >= this._height) { return false; } return this._map[x][y] == 1; }; _proto24._canBeDugCallback = function _canBeDugCallback(x, y) { if (x < 1 || y < 1 || x + 1 >= this._width || y + 1 >= this._height) { return false; } return this._map[x][y] == 1; }; return Uniform; }(Dungeon); var Cellular = /*#__PURE__*/ function (_Map3) { _inheritsLoose(Cellular, _Map3); function Cellular(width, height, options) { var _this11; if (options === void 0) { options = {}; } _this11 = _Map3.call(this, width, height) || this; _this11._options = { born: [5, 6, 7, 8], survive: [4, 5, 6, 7, 8], topology: 8 }; _this11.setOptions(options); _this11._dirs = DIRS[_this11._options.topology]; _this11._map = _this11._fillMap(0); return _this11; } var _proto25 = Cellular.prototype; _proto25.randomize = function randomize(probability) { for (var i = 0; i < this._width; i++) { for (var j = 0; j < this._height; j++) { this._map[i][j] = RNG$1.getUniform() < probability ? 1 : 0; } } return this; }; _proto25.setOptions = function setOptions(options) { Object.assign(this._options, options); }; _proto25.set = function set(x, y, value) { this._map[x][y] = value; }; _proto25.create = function create(callback) { var newMap = this._fillMap(0); var born = this._options.born; var survive = this._options.survive; for (var j = 0; j < this._height; j++) { var widthStep = 1; var widthStart = 0; if (this._options.topology == 6) { widthStep = 2; widthStart = j % 2; } for (var i = widthStart; i < this._width; i += widthStep) { var cur = this._map[i][j]; var ncount = this._getNeighbors(i, j); if (cur && survive.indexOf(ncount) != -1) { newMap[i][j] = 1; } else if (!cur && born.indexOf(ncount) != -1) { newMap[i][j] = 1; } } } this._map = newMap; callback && this._serviceCallback(callback); }; _proto25._serviceCallback = function _serviceCallback(callback) { for (var j = 0; j < this._height; j++) { var widthStep = 1; var widthStart = 0; if (this._options.topology == 6) { widthStep = 2; widthStart = j % 2; } for (var i = widthStart; i < this._width; i += widthStep) { callback(i, j, this._map[i][j]); } } }; _proto25._getNeighbors = function _getNeighbors(cx, cy) { var result = 0; for (var i = 0; i < this._dirs.length; i++) { var dir = this._dirs[i]; var x = cx + dir[0]; var y = cy + dir[1]; if (x < 0 || x >= this._width || y < 0 || y >= this._height) { continue; } result += this._map[x][y] == 1 ? 1 : 0; } return result; }; _proto25.connect = function connect(callback, value, connectionCallback) { if (!value) value = 0; var allFreeSpace = []; var notConnected = {}; var widthStep = 1; var widthStarts = [0, 0]; if (this._options.topology == 6) { widthStep = 2; widthStarts = [0, 1]; } for (var y = 0; y < this._height; y++) { for (var x = widthStarts[y % 2]; x < this._width; x += widthStep) { if (this._freeSpace(x, y, value)) { var p = [x, y]; notConnected[this._pointKey(p)] = p; allFreeSpace.push([x, y]); } } } var start = allFreeSpace[RNG$1.getUniformInt(0, allFreeSpace.length - 1)]; var key = this._pointKey(start); var connected = {}; connected[key] = start; delete notConnected[key]; this._findConnected(connected, notConnected, [start], false, value); while (Object.keys(notConnected).length > 0) { var _p = this._getFromTo(connected, notConnected); var from = _p[0]; var to = _p[1]; var local = {}; local[this._pointKey(from)] = from; this._findConnected(local, notConnected, [from], true, value); var tunnelFn = this._options.topology == 6 ? this._tunnelToConnected6 : this._tunnelToConnected; tunnelFn.call(this, to, from, connected, notConnected, value, connectionCallback); for (var k in local) { var pp = local[k]; this._map[pp[0]][pp[1]] = value; connected[k] = pp; delete notConnected[k]; } } callback && this._serviceCallback(callback); }; _proto25._getFromTo = function _getFromTo(connected, notConnected) { var from = [0, 0], to = [0, 0], d; var connectedKeys = Object.keys(connected); var notConnectedKeys = Object.keys(notConnected); for (var i = 0; i < 5; i++) { if (connectedKeys.length < notConnectedKeys.length) { var keys = connectedKeys; to = connected[keys[RNG$1.getUniformInt(0, keys.length - 1)]]; from = this._getClosest(to, notConnected); } else { var _keys = notConnectedKeys; from = notConnected[_keys[RNG$1.getUniformInt(0, _keys.length - 1)]]; to = this._getClosest(from, connected); } d = (from[0] - to[0]) * (from[0] - to[0]) + (from[1] - to[1]) * (from[1] - to[1]); if (d < 64) { break; } } return [from, to]; }; _proto25._getClosest = function _getClosest(point, space) { var minPoint = null; var minDist = null; for (var k in space) { var p = space[k]; var d = (p[0] - point[0]) * (p[0] - point[0]) + (p[1] - point[1]) * (p[1] - point[1]); if (minDist == null || d < minDist) { minDist = d; minPoint = p; } } return minPoint; }; _proto25._findConnected = function _findConnected(connected, notConnected, stack, keepNotConnected, value) { while (stack.length > 0) { var p = stack.splice(0, 1)[0]; var tests = void 0; if (this._options.topology == 6) { tests = [[p[0] + 2, p[1]], [p[0] + 1, p[1] - 1], [p[0] - 1, p[1] - 1], [p[0] - 2, p[1]], [p[0] - 1, p[1] + 1], [p[0] + 1, p[1] + 1]]; } else { tests = [[p[0] + 1, p[1]], [p[0] - 1, p[1]], [p[0], p[1] + 1], [p[0], p[1] - 1]]; } for (var i = 0; i < tests.length; i++) { var key = this._pointKey(tests[i]); if (connected[key] == null && this._freeSpace(tests[i][0], tests[i][1], value)) { connected[key] = tests[i]; if (!keepNotConnected) { delete notConnected[key]; } stack.push(tests[i]); } } } }; _proto25._tunnelToConnected = function _tunnelToConnected(to, from, connected, notConnected, value, connectionCallback) { var a, b; if (from[0] < to[0]) { a = from; b = to; } else { a = to; b = from; } for (var xx = a[0]; xx <= b[0]; xx++) { this._map[xx][a[1]] = value; var p = [xx, a[1]]; var pkey = this._pointKey(p); connected[pkey] = p; delete notConnected[pkey]; } if (connectionCallback && a[0] < b[0]) { connectionCallback(a, [b[0], a[1]]); } var x = b[0]; if (from[1] < to[1]) { a = from; b = to; } else { a = to; b = from; } for (var yy = a[1]; yy < b[1]; yy++) { this._map[x][yy] = value; var _p2 = [x, yy]; var _pkey = this._pointKey(_p2); connected[_pkey] = _p2; delete notConnected[_pkey]; } if (connectionCallback && a[1] < b[1]) { connectionCallback([b[0], a[1]], [b[0], b[1]]); } }; _proto25._tunnelToConnected6 = function _tunnelToConnected6(to, from, connected, notConnected, value, connectionCallback) { var a, b; if (from[0] < to[0]) { a = from; b = to; } else { a = to; b = from; } var xx = a[0]; var yy = a[1]; while (!(xx == b[0] && yy == b[1])) { var stepWidth = 2; if (yy < b[1]) { yy++; stepWidth = 1; } else if (yy > b[1]) { yy--; stepWidth = 1; } if (xx < b[0]) { xx += stepWidth; } else if (xx > b[0]) { xx -= stepWidth; } else if (b[1] % 2) { xx -= stepWidth; } else { xx += stepWidth; } this._map[xx][yy] = value; var p = [xx, yy]; var pkey = this._pointKey(p); connected[pkey] = p; delete notConnected[pkey]; } if (connectionCallback) { connectionCallback(from, to); } }; _proto25._freeSpace = function _freeSpace(x, y, value) { return x >= 0 && x < this._width && y >= 0 && y < this._height && this._map[x][y] == value; }; _proto25._pointKey = function _pointKey(p) { return p[0] + "." + p[1]; }; return Cellular; }(Map); var FEATURES = { "room": Room, "corridor": Corridor }; var Digger = /*#__PURE__*/ function (_Dungeon2) { _inheritsLoose(Digger, _Dungeon2); function Digger(width, height, options) { var _this12; if (options === void 0) { options = {}; } _this12 = _Dungeon2.call(this, width, height) || this; _this12._options = Object.assign({ roomWidth: [3, 9], roomHeight: [3, 5], corridorLength: [3, 10], dugPercentage: 0.2, timeLimit: 1000 }, options); _this12._features = { "room": 4, "corridor": 4 }; _this12._map = []; _this12._featureAttempts = 20; _this12._walls = {}; _this12._dug = 0; _this12._digCallback = _this12._digCallback.bind(_assertThisInitialized(_assertThisInitialized(_this12))); _this12._canBeDugCallback = _this12._canBeDugCallback.bind(_assertThisInitialized(_assertThisInitialized(_this12))); _this12._isWallCallback = _this12._isWallCallback.bind(_assertThisInitialized(_assertThisInitialized(_this12))); _this12._priorityWallCallback = _this12._priorityWallCallback.bind(_assertThisInitialized(_assertThisInitialized(_this12))); return _this12; } var _proto26 = Digger.prototype; _proto26.create = function create(callback) { this._rooms = []; this._corridors = []; this._map = this._fillMap(1); this._walls = {}; this._dug = 0; var area = (this._width - 2) * (this._height - 2); this._firstRoom(); var t1 = Date.now(); var priorityWalls; do { priorityWalls = 0; var t2 = Date.now(); if (t2 - t1 > this._options.timeLimit) { break; } var wall = this._findWall(); if (!wall) { break; } var parts = wall.split(","); var x = parseInt(parts[0]); var y = parseInt(parts[1]); var dir = this._getDiggingDirection(x, y); if (!dir) { continue; } var featureAttempts = 0; do { featureAttempts++; if (this._tryFeature(x, y, dir[0], dir[1])) { this._removeSurroundingWalls(x, y); this._removeSurroundingWalls(x - dir[0], y - dir[1]); break; } } while (featureAttempts < this._featureAttempts); for (var id in this._walls) { if (this._walls[id] > 1) { priorityWalls++; } } } while (this._dug / area < this._options.dugPercentage || priorityWalls); this._addDoors(); if (callback) { for (var i = 0; i < this._width; i++) { for (var j = 0; j < this._height; j++) { callback(i, j, this._map[i][j]); } } } this._walls = {}; this._map = []; return this; }; _proto26._digCallback = function _digCallback(x, y, value) { if (value == 0 || value == 2) { this._map[x][y] = 0; this._dug++; } else { this._walls[x + "," + y] = 1; } }; _proto26._isWallCallback = function _isWallCallback(x, y) { if (x < 0 || y < 0 || x >= this._width || y >= this._height) { return false; } return this._map[x][y] == 1; }; _proto26._canBeDugCallback = function _canBeDugCallback(x, y) { if (x < 1 || y < 1 || x + 1 >= this._width || y + 1 >= this._height) { return false; } return this._map[x][y] == 1; }; _proto26._priorityWallCallback = function _priorityWallCallback(x, y) { this._walls[x + "," + y] = 2; }; _proto26._firstRoom = function _firstRoom() { var cx = Math.floor(this._width / 2); var cy = Math.floor(this._height / 2); var room = Room.createRandomCenter(cx, cy, this._options); this._rooms.push(room); room.create(this._digCallback); }; _proto26._findWall = function _findWall() { var prio1 = []; var prio2 = []; for (var _id2 in this._walls) { var prio = this._walls[_id2]; if (prio == 2) { prio2.push(_id2); } else { prio1.push(_id2); } } var arr = prio2.length ? prio2 : prio1; if (!arr.length) { return null; } var id = RNG$1.getItem(arr.sort()); delete this._walls[id]; return id; }; _proto26._tryFeature = function _tryFeature(x, y, dx, dy) { var featureName = RNG$1.getWeightedValue(this._features); var ctor = FEATURES[featureName]; var feature = ctor.createRandomAt(x, y, dx, dy, this._options); if (!feature.isValid(this._isWallCallback, this._canBeDugCallback)) { return false; } feature.create(this._digCallback); if (feature instanceof Room) { this._rooms.push(feature); } if (feature instanceof Corridor) { feature.createPriorityWalls(this._priorityWallCallback); this._corridors.push(feature); } return true; }; _proto26._removeSurroundingWalls = function _removeSurroundingWalls(cx, cy) { var deltas = DIRS[4]; for (var i = 0; i < deltas.length; i++) { var delta = deltas[i]; var x = cx + delta[0]; var y = cy + delta[1]; delete this._walls[x + "," + y]; x = cx + 2 * delta[0]; y = cy + 2 * delta[1]; delete this._walls[x + "," + y]; } }; _proto26._getDiggingDirection = function _getDiggingDirection(cx, cy) { if (cx <= 0 || cy <= 0 || cx >= this._width - 1 || cy >= this._height - 1) { return null; } var result = null; var deltas = DIRS[4]; for (var i = 0; i < deltas.length; i++) { var delta = deltas[i]; var x = cx + delta[0]; var y = cy + delta[1]; if (!this._map[x][y]) { if (result) { return null; } result = delta; } } if (!result) { return null; } return [-result[0], -result[1]]; }; _proto26._addDoors = function _addDoors() { var data = this._map; function isWallCallback(x, y) { return data[x][y] == 1; } for (var i = 0; i < this._rooms.length; i++) { var room = this._rooms[i]; room.clearDoors(); room.addDoors(isWallCallback); } }; return Digger; }(Dungeon); function addToList(i, L, R) { R[L[i + 1]] = R[i]; L[R[i]] = L[i + 1]; R[i] = i + 1; L[i + 1] = i; } function removeFromList(i, L, R) { R[L[i]] = R[i]; L[R[i]] = L[i]; R[i] = i; L[i] = i; } var EllerMaze = /*#__PURE__*/ function (_Map4) { _inheritsLoose(EllerMaze, _Map4); function EllerMaze() { return _Map4.apply(this, arguments) || this; } var _proto27 = EllerMaze.prototype; _proto27.create = function create(callback) { var map = this._fillMap(1); var w = Math.ceil((this._width - 2) / 2); var rand = 9 / 24; var L = []; var R = []; for (var i = 0; i < w; i++) { L.push(i); R.push(i); } L.push(w - 1); var j; for (j = 1; j + 3 < this._height; j += 2) { for (var _i4 = 0; _i4 < w; _i4++) { var x = 2 * _i4 + 1; var y = j; map[x][y] = 0; if (_i4 != L[_i4 + 1] && RNG$1.getUniform() > rand) { addToList(_i4, L, R); map[x + 1][y] = 0; } if (_i4 != L[_i4] && RNG$1.getUniform() > rand) { removeFromList(_i4, L, R); } else { map[x][y + 1] = 0; } } } for (var _i5 = 0; _i5 < w; _i5++) { var _x2 = 2 * _i5 + 1; var _y2 = j; map[_x2][_y2] = 0; if (_i5 != L[_i5 + 1] && (_i5 == L[_i5] || RNG$1.getUniform() > rand)) { addToList(_i5, L, R); map[_x2 + 1][_y2] = 0; } removeFromList(_i5, L, R); } for (var _i6 = 0; _i6 < this._width; _i6++) { for (var _j = 0; _j < this._height; _j++) { callback(_i6, _j, map[_i6][_j]); } } return this; }; return EllerMaze; }(Map); var DividedMaze = /*#__PURE__*/ function (_Map5) { _inheritsLoose(DividedMaze, _Map5); function DividedMaze() { var _this13; _this13 = _Map5.apply(this, arguments) || this; _this13._stack = []; _this13._map = []; return _this13; } var _proto28 = DividedMaze.prototype; _proto28.create = function create(callback) { var w = this._width; var h = this._height; this._map = []; for (var i = 0; i < w; i++) { this._map.push([]); for (var j = 0; j < h; j++) { var border = i == 0 || j == 0 || i + 1 == w || j + 1 == h; this._map[i].push(border ? 1 : 0); } } this._stack = [[1, 1, w - 2, h - 2]]; this._process(); for (var _i7 = 0; _i7 < w; _i7++) { for (var _j2 = 0; _j2 < h; _j2++) { callback(_i7, _j2, this._map[_i7][_j2]); } } this._map = []; return this; }; _proto28._process = function _process() { while (this._stack.length) { var room = this._stack.shift(); this._partitionRoom(room); } }; _proto28._partitionRoom = function _partitionRoom(room) { var availX = []; var availY = []; for (var i = room[0] + 1; i < room[2]; i++) { var top = this._map[i][room[1] - 1]; var bottom = this._map[i][room[3] + 1]; if (top && bottom && !(i % 2)) { availX.push(i); } } for (var j = room[1] + 1; j < room[3]; j++) { var left = this._map[room[0] - 1][j]; var right = this._map[room[2] + 1][j]; if (left && right && !(j % 2)) { availY.push(j); } } if (!availX.length || !availY.length) { return; } var x = RNG$1.getItem(availX); var y = RNG$1.getItem(availY); this._map[x][y] = 1; var walls = []; var w = []; walls.push(w); for (var _i8 = room[0]; _i8 < x; _i8++) { this._map[_i8][y] = 1; w.push([_i8, y]); } w = []; walls.push(w); for (var _i9 = x + 1; _i9 <= room[2]; _i9++) { this._map[_i9][y] = 1; w.push([_i9, y]); } w = []; walls.push(w); for (var _j3 = room[1]; _j3 < y; _j3++) { this._map[x][_j3] = 1; w.push([x, _j3]); } w = []; walls.push(w); for (var _j4 = y + 1; _j4 <= room[3]; _j4++) { this._map[x][_j4] = 1; w.push([x, _j4]); } var solid = RNG$1.getItem(walls); for (var _i10 = 0; _i10 < walls.length; _i10++) { var _w = walls[_i10]; if (_w == solid) { continue; } var hole = RNG$1.getItem(_w); this._map[hole[0]][hole[1]] = 0; } this._stack.push([room[0], room[1], x - 1, y - 1]); this._stack.push([x + 1, room[1], room[2], y - 1]); this._stack.push([room[0], y + 1, x - 1, room[3]]); this._stack.push([x + 1, y + 1, room[2], room[3]]); }; return DividedMaze; }(Map); var IceyMaze = /*#__PURE__*/ function (_Map6) { _inheritsLoose(IceyMaze, _Map6); function IceyMaze(width, height, regularity) { var _this14; if (regularity === void 0) { regularity = 0; } _this14 = _Map6.call(this, width, height) || this; _this14._regularity = regularity; _this14._map = []; return _this14; } var _proto29 = IceyMaze.prototype; _proto29.create = function create(callback) { var width = this._width; var height = this._height; var map = this._fillMap(1); width -= width % 2 ? 1 : 2; height -= height % 2 ? 1 : 2; var cx = 0; var cy = 0; var nx = 0; var ny = 0; var done = 0; var blocked = false; var dirs = [[0, 0], [0, 0], [0, 0], [0, 0]]; do { cx = 1 + 2 * Math.floor(RNG$1.getUniform() * (width - 1) / 2); cy = 1 + 2 * Math.floor(RNG$1.getUniform() * (height - 1) / 2); if (!done) { map[cx][cy] = 0; } if (!map[cx][cy]) { this._randomize(dirs); do { if (Math.floor(RNG$1.getUniform() * (this._regularity + 1)) == 0) { this._randomize(dirs); } blocked = true; for (var i = 0; i < 4; i++) { nx = cx + dirs[i][0] * 2; ny = cy + dirs[i][1] * 2; if (this._isFree(map, nx, ny, width, height)) { map[nx][ny] = 0; map[cx + dirs[i][0]][cy + dirs[i][1]] = 0; cx = nx; cy = ny; blocked = false; done++; break; } } } while (!blocked); } } while (done + 1 < width * height / 4); for (var _i11 = 0; _i11 < this._width; _i11++) { for (var j = 0; j < this._height; j++) { callback(_i11, j, map[_i11][j]); } } this._map = []; return this; }; _proto29._randomize = function _randomize(dirs) { for (var i = 0; i < 4; i++) { dirs[i][0] = 0; dirs[i][1] = 0; } switch (Math.floor(RNG$1.getUniform() * 4)) { case 0: dirs[0][0] = -1; dirs[1][0] = 1; dirs[2][1] = -1; dirs[3][1] = 1; break; case 1: dirs[3][0] = -1; dirs[2][0] = 1; dirs[1][1] = -1; dirs[0][1] = 1; break; case 2: dirs[2][0] = -1; dirs[3][0] = 1; dirs[0][1] = -1; dirs[1][1] = 1; break; case 3: dirs[1][0] = -1; dirs[0][0] = 1; dirs[3][1] = -1; dirs[2][1] = 1; break; } }; _proto29._isFree = function _isFree(map, x, y, width, height) { if (x < 1 || y < 1 || x >= width || y >= height) { return false; } return map[x][y]; }; return IceyMaze; }(Map); var Rogue = /*#__PURE__*/ function (_Map7) { _inheritsLoose(Rogue, _Map7); function Rogue(width, height, options) { var _this15; _this15 = _Map7.call(this, width, height) || this; _this15.map = []; _this15.rooms = []; _this15.connectedCells = []; options = Object.assign({ cellWidth: 3, cellHeight: 3 }, options); if (!options.hasOwnProperty("roomWidth")) { options["roomWidth"] = _this15._calculateRoomSize(_this15._width, options["cellWidth"]); } if (!options.hasOwnProperty("roomHeight")) { options["roomHeight"] = _this15._calculateRoomSize(_this15._height, options["cellHeight"]); } _this15._options = options; return _this15; } var _proto30 = Rogue.prototype; _proto30.create = function create(callback) { this.map = this._fillMap(1); this.rooms = []; this.connectedCells = []; this._initRooms(); this._connectRooms(); this._connectUnconnectedRooms(); this._createRandomRoomConnections(); this._createRooms(); this._createCorridors(); if (callback) { for (var i = 0; i < this._width; i++) { for (var j = 0; j < this._height; j++) { callback(i, j, this.map[i][j]); } } } return this; }; _proto30._calculateRoomSize = function _calculateRoomSize(size, cell) { var max = Math.floor(size / cell * 0.8); var min = Math.floor(size / cell * 0.25); if (min < 2) { min = 2; } if (max < 2) { max = 2; } return [min, max]; }; _proto30._initRooms = function _initRooms() { for (var i = 0; i < this._options.cellWidth; i++) { this.rooms.push([]); for (var j = 0; j < this._options.cellHeight; j++) { this.rooms[i].push({ "x": 0, "y": 0, "width": 0, "height": 0, "connections": [], "cellx": i, "celly": j }); } } }; _proto30._connectRooms = function _connectRooms() { var cgx = RNG$1.getUniformInt(0, this._options.cellWidth - 1); var cgy = RNG$1.getUniformInt(0, this._options.cellHeight - 1); var idx; var ncgx; var ncgy; var found = false; var room; var otherRoom; var dirToCheck; do { dirToCheck = [0, 2, 4, 6]; dirToCheck = RNG$1.shuffle(dirToCheck); do { found = false; idx = dirToCheck.pop(); ncgx = cgx + DIRS[8][idx][0]; ncgy = cgy + DIRS[8][idx][1]; if (ncgx < 0 || ncgx >= this._options.cellWidth) { continue; } if (ncgy < 0 || ncgy >= this._options.cellHeight) { continue; } room = this.rooms[cgx][cgy]; if (room["connections"].length > 0) { if (room["connections"][0][0] == ncgx && room["connections"][0][1] == ncgy) { break; } } otherRoom = this.rooms[ncgx][ncgy]; if (otherRoom["connections"].length == 0) { otherRoom["connections"].push([cgx, cgy]); this.connectedCells.push([ncgx, ncgy]); cgx = ncgx; cgy = ncgy; found = true; } } while (dirToCheck.length > 0 && found == false); } while (dirToCheck.length > 0); }; _proto30._connectUnconnectedRooms = function _connectUnconnectedRooms() { var cw = this._options.cellWidth; var ch = this._options.cellHeight; this.connectedCells = RNG$1.shuffle(this.connectedCells); var room; var otherRoom; var validRoom; for (var i = 0; i < this._options.cellWidth; i++) { for (var j = 0; j < this._options.cellHeight; j++) { room = this.rooms[i][j]; if (room["connections"].length == 0) { var directions = [0, 2, 4, 6]; directions = RNG$1.shuffle(directions); validRoom = false; do { var dirIdx = directions.pop(); var newI = i + DIRS[8][dirIdx][0]; var newJ = j + DIRS[8][dirIdx][1]; if (newI < 0 || newI >= cw || newJ < 0 || newJ >= ch) { continue; } otherRoom = this.rooms[newI][newJ]; validRoom = true; if (otherRoom["connections"].length == 0) { break; } for (var k = 0; k < otherRoom["connections"].length; k++) { if (otherRoom["connections"][k][0] == i && otherRoom["connections"][k][1] == j) { validRoom = false; break; } } if (validRoom) { break; } } while (directions.length); if (validRoom) { room["connections"].push([otherRoom["cellx"], otherRoom["celly"]]); } else { console.log("-- Unable to connect room."); } } } } }; _proto30._createRandomRoomConnections = function _createRandomRoomConnections() {}; _proto30._createRooms = function _createRooms() { var w = this._width; var h = this._height; var cw = this._options.cellWidth; var ch = this._options.cellHeight; var cwp = Math.floor(this._width / cw); var chp = Math.floor(this._height / ch); var roomw; var roomh; var roomWidth = this._options["roomWidth"]; var roomHeight = this._options["roomHeight"]; var sx; var sy; var otherRoom; for (var i = 0; i < cw; i++) { for (var j = 0; j < ch; j++) { sx = cwp * i; sy = chp * j; if (sx == 0) { sx = 1; } if (sy == 0) { sy = 1; } roomw = RNG$1.getUniformInt(roomWidth[0], roomWidth[1]); roomh = RNG$1.getUniformInt(roomHeight[0], roomHeight[1]); if (j > 0) { otherRoom = this.rooms[i][j - 1]; while (sy - (otherRoom["y"] + otherRoom["height"]) < 3) { sy++; } } if (i > 0) { otherRoom = this.rooms[i - 1][j]; while (sx - (otherRoom["x"] + otherRoom["width"]) < 3) { sx++; } } var sxOffset = Math.round(RNG$1.getUniformInt(0, cwp - roomw) / 2); var syOffset = Math.round(RNG$1.getUniformInt(0, chp - roomh) / 2); while (sx + sxOffset + roomw >= w) { if (sxOffset) { sxOffset--; } else { roomw--; } } while (sy + syOffset + roomh >= h) { if (syOffset) { syOffset--; } else { roomh--; } } sx = sx + sxOffset; sy = sy + syOffset; this.rooms[i][j]["x"] = sx; this.rooms[i][j]["y"] = sy; this.rooms[i][j]["width"] = roomw; this.rooms[i][j]["height"] = roomh; for (var ii = sx; ii < sx + roomw; ii++) { for (var jj = sy; jj < sy + roomh; jj++) { this.map[ii][jj] = 0; } } } } }; _proto30._getWallPosition = function _getWallPosition(aRoom, aDirection) { var rx; var ry; var door; if (aDirection == 1 || aDirection == 3) { rx = RNG$1.getUniformInt(aRoom["x"] + 1, aRoom["x"] + aRoom["width"] - 2); if (aDirection == 1) { ry = aRoom["y"] - 2; door = ry + 1; } else { ry = aRoom["y"] + aRoom["height"] + 1; door = ry - 1; } this.map[rx][door] = 0; } else { ry = RNG$1.getUniformInt(aRoom["y"] + 1, aRoom["y"] + aRoom["height"] - 2); if (aDirection == 2) { rx = aRoom["x"] + aRoom["width"] + 1; door = rx - 1; } else { rx = aRoom["x"] - 2; door = rx + 1; } this.map[door][ry] = 0; } return [rx, ry]; }; _proto30._drawCorridor = function _drawCorridor(startPosition, endPosition) { var xOffset = endPosition[0] - startPosition[0]; var yOffset = endPosition[1] - startPosition[1]; var xpos = startPosition[0]; var ypos = startPosition[1]; var tempDist; var xDir; var yDir; var move; var moves = []; var xAbs = Math.abs(xOffset); var yAbs = Math.abs(yOffset); var percent = RNG$1.getUniform(); var firstHalf = percent; var secondHalf = 1 - percent; xDir = xOffset > 0 ? 2 : 6; yDir = yOffset > 0 ? 4 : 0; if (xAbs < yAbs) { tempDist = Math.ceil(yAbs * firstHalf); moves.push([yDir, tempDist]); moves.push([xDir, xAbs]); tempDist = Math.floor(yAbs * secondHalf); moves.push([yDir, tempDist]); } else { tempDist = Math.ceil(xAbs * firstHalf); moves.push([xDir, tempDist]); moves.push([yDir, yAbs]); tempDist = Math.floor(xAbs * secondHalf); moves.push([xDir, tempDist]); } this.map[xpos][ypos] = 0; while (moves.length > 0) { move = moves.pop(); while (move[1] > 0) { xpos += DIRS[8][move[0]][0]; ypos += DIRS[8][move[0]][1]; this.map[xpos][ypos] = 0; move[1] = move[1] - 1; } } }; _proto30._createCorridors = function _createCorridors() { var cw = this._options.cellWidth; var ch = this._options.cellHeight; var room; var connection; var otherRoom; var wall; var otherWall; for (var i = 0; i < cw; i++) { for (var j = 0; j < ch; j++) { room = this.rooms[i][j]; for (var k = 0; k < room["connections"].length; k++) { connection = room["connections"][k]; otherRoom = this.rooms[connection[0]][connection[1]]; if (otherRoom["cellx"] > room["cellx"]) { wall = 2; otherWall = 4; } else if (otherRoom["cellx"] < room["cellx"]) { wall = 4; otherWall = 2; } else if (otherRoom["celly"] > room["celly"]) { wall = 3; otherWall = 1; } else { wall = 1; otherWall = 3; } this._drawCorridor(this._getWallPosition(room, wall), this._getWallPosition(otherRoom, otherWall)); } } } }; return Rogue; }(Map); var index$2 = { Arena: Arena, Uniform: Uniform, Cellular: Cellular, Digger: Digger, EllerMaze: EllerMaze, DividedMaze: DividedMaze, IceyMaze: IceyMaze, Rogue: Rogue }; var Noise = function Noise() {}; var F2 = 0.5 * (Math.sqrt(3) - 1); var G2 = (3 - Math.sqrt(3)) / 6; var Simplex = /*#__PURE__*/ function (_Noise) { _inheritsLoose(Simplex, _Noise); function Simplex(gradients) { var _this16; if (gradients === void 0) { gradients = 256; } _this16 = _Noise.call(this) || this; _this16._gradients = [[0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1]]; var permutations = []; for (var i = 0; i < gradients; i++) { permutations.push(i); } permutations = RNG$1.shuffle(permutations); _this16._perms = []; _this16._indexes = []; for (var _i12 = 0; _i12 < 2 * gradients; _i12++) { _this16._perms.push(permutations[_i12 % gradients]); _this16._indexes.push(_this16._perms[_i12] % _this16._gradients.length); } return _this16; } var _proto31 = Simplex.prototype; _proto31.get = function get(xin, yin) { var perms = this._perms; var indexes = this._indexes; var count = perms.length / 2; var n0 = 0, n1 = 0, n2 = 0, gi; var s = (xin + yin) * F2; var i = Math.floor(xin + s); var j = Math.floor(yin + s); var t = (i + j) * G2; var X0 = i - t; var Y0 = j - t; var x0 = xin - X0; var y0 = yin - Y0; var i1, j1; if (x0 > y0) { i1 = 1; j1 = 0; } else { i1 = 0; j1 = 1; } var x1 = x0 - i1 + G2; var y1 = y0 - j1 + G2; var x2 = x0 - 1 + 2 * G2; var y2 = y0 - 1 + 2 * G2; var ii = mod(i, count); var jj = mod(j, count); var t0 = 0.5 - x0 * x0 - y0 * y0; if (t0 >= 0) { t0 *= t0; gi = indexes[ii + perms[jj]]; var grad = this._gradients[gi]; n0 = t0 * t0 * (grad[0] * x0 + grad[1] * y0); } var t1 = 0.5 - x1 * x1 - y1 * y1; if (t1 >= 0) { t1 *= t1; gi = indexes[ii + i1 + perms[jj + j1]]; var _grad = this._gradients[gi]; n1 = t1 * t1 * (_grad[0] * x1 + _grad[1] * y1); } var t2 = 0.5 - x2 * x2 - y2 * y2; if (t2 >= 0) { t2 *= t2; gi = indexes[ii + 1 + perms[jj + 1]]; var _grad2 = this._gradients[gi]; n2 = t2 * t2 * (_grad2[0] * x2 + _grad2[1] * y2); } return 70 * (n0 + n1 + n2); }; return Simplex; }(Noise); var index$3 = { Simplex: Simplex }; var Path = /*#__PURE__*/ function () { function Path(toX, toY, passableCallback, options) { if (options === void 0) { options = {}; } this._toX = toX; this._toY = toY; this._passableCallback = passableCallback; this._options = Object.assign({ topology: 8 }, options); this._dirs = DIRS[this._options.topology]; if (this._options.topology == 8) { this._dirs = [this._dirs[0], this._dirs[2], this._dirs[4], this._dirs[6], this._dirs[1], this._dirs[3], this._dirs[5], this._dirs[7]]; } } var _proto32 = Path.prototype; _proto32._getNeighbors = function _getNeighbors(cx, cy) { var result = []; for (var i = 0; i < this._dirs.length; i++) { var dir = this._dirs[i]; var x = cx + dir[0]; var y = cy + dir[1]; if (!this._passableCallback(x, y)) { continue; } result.push([x, y]); } return result; }; return Path; }(); var Dijkstra = /*#__PURE__*/ function (_Path) { _inheritsLoose(Dijkstra, _Path); function Dijkstra(toX, toY, passableCallback, options) { var _this17; _this17 = _Path.call(this, toX, toY, passableCallback, options) || this; _this17._computed = {}; _this17._todo = []; _this17._add(toX, toY, null); return _this17; } var _proto33 = Dijkstra.prototype; _proto33.compute = function compute(fromX, fromY, callback) { var key = fromX + "," + fromY; if (!(key in this._computed)) { this._compute(fromX, fromY); } if (!(key in this._computed)) { return; } var item = this._computed[key]; while (item) { callback(item.x, item.y); item = item.prev; } }; _proto33._compute = function _compute(fromX, fromY) { while (this._todo.length) { var item = this._todo.shift(); if (item.x == fromX && item.y == fromY) { return; } var neighbors = this._getNeighbors(item.x, item.y); for (var i = 0; i < neighbors.length; i++) { var neighbor = neighbors[i]; var x = neighbor[0]; var y = neighbor[1]; var id = x + "," + y; if (id in this._computed) { continue; } this._add(x, y, item); } } }; _proto33._add = function _add(x, y, prev) { var obj = { x: x, y: y, prev: prev }; this._computed[x + "," + y] = obj; this._todo.push(obj); }; return Dijkstra; }(Path); var AStar = /*#__PURE__*/ function (_Path2) { _inheritsLoose(AStar, _Path2); function AStar(toX, toY, passableCallback, options) { var _this18; if (options === void 0) { options = {}; } _this18 = _Path2.call(this, toX, toY, passableCallback, options) || this; _this18._todo = []; _this18._done = {}; return _this18; } var _proto34 = AStar.prototype; _proto34.compute = function compute(fromX, fromY, callback) { this._todo = []; this._done = {}; this._fromX = fromX; this._fromY = fromY; this._add(this._toX, this._toY, null); while (this._todo.length) { var _item = this._todo.shift(); var id = _item.x + "," + _item.y; if (id in this._done) { continue; } this._done[id] = _item; if (_item.x == fromX && _item.y == fromY) { break; } var neighbors = this._getNeighbors(_item.x, _item.y); for (var i = 0; i < neighbors.length; i++) { var neighbor = neighbors[i]; var x = neighbor[0]; var y = neighbor[1]; var _id3 = x + "," + y; if (_id3 in this._done) { continue; } this._add(x, y, _item); } } var item = this._done[fromX + "," + fromY]; if (!item) { return; } while (item) { callback(item.x, item.y); item = item.prev; } }; _proto34._add = function _add(x, y, prev) { var h = this._distance(x, y); var obj = { x: x, y: y, prev: prev, g: prev ? prev.g + 1 : 0, h: h }; var f = obj.g + obj.h; for (var i = 0; i < this._todo.length; i++) { var item = this._todo[i]; var itemF = item.g + item.h; if (f < itemF || f == itemF && h < item.h) { this._todo.splice(i, 0, obj); return; } } this._todo.push(obj); }; _proto34._distance = function _distance(x, y) { switch (this._options.topology) { case 4: return Math.abs(x - this._fromX) + Math.abs(y - this._fromY); break; case 6: var dx = Math.abs(x - this._fromX); var dy = Math.abs(y - this._fromY); return dy + Math.max(0, (dx - dy) / 2); break; case 8: return Math.max(Math.abs(x - this._fromX), Math.abs(y - this._fromY)); break; } }; return AStar; }(Path); var index$4 = { Dijkstra: Dijkstra, AStar: AStar }; var Engine = /*#__PURE__*/ function () { function Engine(scheduler) { this._scheduler = scheduler; this._lock = 1; } var _proto35 = Engine.prototype; _proto35.start = function start() { return this.unlock(); }; _proto35.lock = function lock() { this._lock++; return this; }; _proto35.unlock = function unlock() { if (!this._lock) { throw new Error("Cannot unlock unlocked engine"); } this._lock--; while (!this._lock) { var actor = this._scheduler.next(); if (!actor) { return this.lock(); } var result = actor.act(); if (result && result.then) { this.lock(); result.then(this.unlock.bind(this)); } } return this; }; return Engine; }(); var Lighting = /*#__PURE__*/ function () { function Lighting(reflectivityCallback, options) { if (options === void 0) { options = {}; } this._reflectivityCallback = reflectivityCallback; this._options = {}; options = Object.assign({ passes: 1, emissionThreshold: 100, range: 10 }, options); this._lights = {}; this._reflectivityCache = {}; this._fovCache = {}; this.setOptions(options); } var _proto36 = Lighting.prototype; _proto36.setOptions = function setOptions(options) { Object.assign(this._options, options); if (options && options.range) { this.reset(); } return this; }; _proto36.setFOV = function setFOV(fov) { this._fov = fov; this._fovCache = {}; return this; }; _proto36.setLight = function setLight(x, y, color) { var key = x + "," + y; if (color) { this._lights[key] = typeof color == "string" ? fromString(color) : color; } else { delete this._lights[key]; } return this; }; _proto36.clearLights = function clearLights() { this._lights = {}; }; _proto36.reset = function reset() { this._reflectivityCache = {}; this._fovCache = {}; return this; }; _proto36.compute = function compute(lightingCallback) { var doneCells = {}; var emittingCells = {}; var litCells = {}; for (var key in this._lights) { var light = this._lights[key]; emittingCells[key] = [0, 0, 0]; add_(emittingCells[key], light); } for (var i = 0; i < this._options.passes; i++) { this._emitLight(emittingCells, litCells, doneCells); if (i + 1 == this._options.passes) { continue; } emittingCells = this._computeEmitters(litCells, doneCells); } for (var litKey in litCells) { var parts = litKey.split(","); var x = parseInt(parts[0]); var y = parseInt(parts[1]); lightingCallback(x, y, litCells[litKey]); } return this; }; _proto36._emitLight = function _emitLight(emittingCells, litCells, doneCells) { for (var key in emittingCells) { var parts = key.split(","); var x = parseInt(parts[0]); var y = parseInt(parts[1]); this._emitLightFromCell(x, y, emittingCells[key], litCells); doneCells[key] = 1; } return this; }; _proto36._computeEmitters = function _computeEmitters(litCells, doneCells) { var result = {}; for (var key in litCells) { if (key in doneCells) { continue; } var _color = litCells[key]; var reflectivity = void 0; if (key in this._reflectivityCache) { reflectivity = this._reflectivityCache[key]; } else { var parts = key.split(","); var x = parseInt(parts[0]); var y = parseInt(parts[1]); reflectivity = this._reflectivityCallback(x, y); this._reflectivityCache[key] = reflectivity; } if (reflectivity == 0) { continue; } var emission = [0, 0, 0]; var intensity = 0; for (var i = 0; i < 3; i++) { var part = Math.round(_color[i] * reflectivity); emission[i] = part; intensity += part; } if (intensity > this._options.emissionThreshold) { result[key] = emission; } } return result; }; _proto36._emitLightFromCell = function _emitLightFromCell(x, y, color, litCells) { var key = x + "," + y; var fov; if (key in this._fovCache) { fov = this._fovCache[key]; } else { fov = this._updateFOV(x, y); } for (var fovKey in fov) { var formFactor = fov[fovKey]; var result = void 0; if (fovKey in litCells) { result = litCells[fovKey]; } else { result = [0, 0, 0]; litCells[fovKey] = result; } for (var i = 0; i < 3; i++) { result[i] += Math.round(color[i] * formFactor); } } return this; }; _proto36._updateFOV = function _updateFOV(x, y) { var key1 = x + "," + y; var cache = {}; this._fovCache[key1] = cache; var range = this._options.range; function cb(x, y, r, vis) { var key2 = x + "," + y; var formFactor = vis * (1 - r / range); if (formFactor == 0) { return; } cache[key2] = formFactor; } this._fov.compute(x, y, range, cb.bind(this)); return cache; }; return Lighting; }(); var Util = util; var Color = color; var Text = text; exports.Util = Util; exports.Color = Color; exports.Text = Text; exports.RNG = RNG$1; exports.Display = Display; exports.StringGenerator = StringGenerator; exports.EventQueue = EventQueue; exports.Scheduler = index; exports.FOV = index$1; exports.Map = index$2; exports.Noise = index$3; exports.Path = index$4; exports.Engine = Engine; exports.Lighting = Lighting; exports.DEFAULT_WIDTH = DEFAULT_WIDTH; exports.DEFAULT_HEIGHT = DEFAULT_HEIGHT; exports.DIRS = DIRS; exports.KEYS = KEYS; Object.defineProperty(exports, '__esModule', { value: true }); });
mit
leahwong4/LeahTagLibEditor
LeahTabLibEditor/Form1.Designer.cs
8584
namespace LeahTagLibEditor { partial class Form1 { /// <summary> /// 設計工具所需的變數。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清除任何使用中的資源。 /// </summary> /// <param name="disposing">如果應該處置 Managed 資源則為 true,否則為 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form 設計工具產生的程式碼 /// <summary> /// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器 /// 修改這個方法的內容。 /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.textFileTB = new System.Windows.Forms.TextBox(); this.authorTB = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.AlbumTB = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.richTextBox1 = new System.Windows.Forms.RichTextBox(); this.songFormatTB = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.songFolderTB = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.checkBox1 = new System.Windows.Forms.CheckBox(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(29, 36); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(158, 13); this.label1.TabIndex = 0; this.label1.Text = "Song Name Text File Path (.txt)*"; // // textFileTB // this.textFileTB.Location = new System.Drawing.Point(189, 33); this.textFileTB.Name = "textFileTB"; this.textFileTB.Size = new System.Drawing.Size(320, 20); this.textFileTB.TabIndex = 2; // // authorTB // this.authorTB.Location = new System.Drawing.Point(189, 62); this.authorTB.Name = "authorTB"; this.authorTB.Size = new System.Drawing.Size(320, 20); this.authorTB.TabIndex = 3; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(29, 68); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(38, 13); this.label2.TabIndex = 2; this.label2.Text = "Author"; // // AlbumTB // this.AlbumTB.Location = new System.Drawing.Point(189, 95); this.AlbumTB.Name = "AlbumTB"; this.AlbumTB.Size = new System.Drawing.Size(320, 20); this.AlbumTB.TabIndex = 4; this.AlbumTB.TextChanged += new System.EventHandler(this.AlbumTB_TextChanged); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(29, 99); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(36, 13); this.label3.TabIndex = 4; this.label3.Text = "Album"; // // richTextBox1 // this.richTextBox1.Location = new System.Drawing.Point(32, 202); this.richTextBox1.Name = "richTextBox1"; this.richTextBox1.Size = new System.Drawing.Size(477, 139); this.richTextBox1.TabIndex = 8; this.richTextBox1.Text = ""; // // songFormatTB // this.songFormatTB.Location = new System.Drawing.Point(189, 127); this.songFormatTB.Name = "songFormatTB"; this.songFormatTB.Size = new System.Drawing.Size(320, 20); this.songFormatTB.TabIndex = 5; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(29, 132); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(90, 13); this.label4.TabIndex = 7; this.label4.Text = "Song File Format*"; // // button1 // this.button1.Location = new System.Drawing.Point(189, 167); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(320, 23); this.button1.TabIndex = 7; this.button1.Text = "Edit TagLib"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // songFolderTB // this.songFolderTB.Location = new System.Drawing.Point(189, 5); this.songFolderTB.Name = "songFolderTB"; this.songFolderTB.Size = new System.Drawing.Size(320, 20); this.songFolderTB.TabIndex = 1; this.songFolderTB.TextChanged += new System.EventHandler(this.textBox1_TextChanged); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(29, 8); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(68, 13); this.label5.TabIndex = 10; this.label5.Text = "Song Folder*"; this.label5.Click += new System.EventHandler(this.label5_Click); // // checkBox1 // this.checkBox1.AutoSize = true; this.checkBox1.Location = new System.Drawing.Point(32, 169); this.checkBox1.Name = "checkBox1"; this.checkBox1.Size = new System.Drawing.Size(97, 17); this.checkBox1.TabIndex = 6; this.checkBox1.Text = "Preview Result"; this.checkBox1.UseVisualStyleBackColor = true; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(564, 353); this.Controls.Add(this.checkBox1); this.Controls.Add(this.songFolderTB); this.Controls.Add(this.label5); this.Controls.Add(this.button1); this.Controls.Add(this.songFormatTB); this.Controls.Add(this.label4); this.Controls.Add(this.richTextBox1); this.Controls.Add(this.AlbumTB); this.Controls.Add(this.label3); this.Controls.Add(this.authorTB); this.Controls.Add(this.label2); this.Controls.Add(this.textFileTB); this.Controls.Add(this.label1); this.Name = "Form1"; this.Text = "LeahTagLibEditor"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textFileTB; private System.Windows.Forms.TextBox authorTB; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox AlbumTB; private System.Windows.Forms.Label label3; private System.Windows.Forms.RichTextBox richTextBox1; private System.Windows.Forms.TextBox songFormatTB; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox songFolderTB; private System.Windows.Forms.Label label5; private System.Windows.Forms.CheckBox checkBox1; } }
mit
ritashugisha/ASUEvents
ASUEvents/managers/migrations/0006_auto_20150417_1749.py
511
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('managers', '0005_auto_20150417_1747'), ] operations = [ migrations.AlterField( model_name='managerprofile', name='picture', field=models.ImageField(default=b'/static/assets/admin/layout/img/avatar.png', upload_to=b'profiles'), preserve_default=True, ), ]
mit
listochkin/dyn4j
src/main/java/com/github/listochkin/dyn/DynamicTyping.java
3277
package com.github.listochkin.dyn; import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class DynamicTyping { public static boolean isOfType(final Object object, final String typeName) { try { return Class.forName(typeName).isInstance(object); } catch (final ClassNotFoundException e) { throw new RuntimeException(e); } } private static final class ProxyHandler implements InvocationHandler { private final Object target; private ProxyHandler(final Object target) { this.target = target; } @Override public Object invoke(final Object proxy, final Method method, final Object[] params) throws Throwable { return target.getClass() .getMethod(method.getName(), method.getParameterTypes()) .invoke(target, params); } } public static <T> T cast(final Object target, final Class<T> type, final Class<?>... additionalInterfaces) { return type.cast(Proxy.newProxyInstance(type.getClassLoader(), concat(type, additionalInterfaces), new ProxyHandler(target))); } private static final class PatchedHandler implements InvocationHandler { private final Object target; private final Object patch; private PatchedHandler(final Object target, final Object patch) { this.target = target; this.patch = patch; } @Override public Object invoke(final Object proxy, final Method method, final Object[] params) throws Throwable { try { return patch .getClass() .getMethod(method.getName(), method.getParameterTypes()) .invoke(patch, params); } catch (final NoSuchMethodException e) { return target .getClass() .getMethod(method.getName(), method.getParameterTypes()) .invoke(target, params); } } } public static <T> T patch(final T target, final Object patch) { return patch(target, patch, target.getClass().getInterfaces()); } @SuppressWarnings("unchecked") public static <T> T patch(final T target, final Object patch, final Class<?>... interfaces) { return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), interfaces, new PatchedHandler(target, patch)); } private static <T> T[] concat(final T first, final T[] rest) { if (rest == null) { @SuppressWarnings("unchecked") final T[] result = (T[]) Array.newInstance(first.getClass(), 1); result[0] = first; return result; } else { @SuppressWarnings("unchecked") final T[] result = (T[]) Array.newInstance(rest.getClass() .getComponentType(), rest.length + 1); System.arraycopy(rest, 0, result, 1, rest.length); result[0] = first; return result; } } }
mit
mimmi20/browscap-js
src/index.js
1457
'use strict'; /** * main class */ class Browscap { /** * @param {string} cacheDir */ constructor(cacheDir) { if (typeof cacheDir === 'undefined') { cacheDir = require('path').dirname(require.resolve('browscap-json-cache-files')) + '/sources/'; } this.cacheDir = cacheDir; } /** * parses the given user agent to get the information about the browser * * if no user agent is given, it uses {@see \BrowscapPHP\Helper\Support} to get it * * @param {string} userAgent the user agent string * * @return {object} */ getBrowser(userAgent) { const Ini = require('./parser'); const GetPattern = require('./helper/pattern'); const BrowscapCache = require('browscap-js-cache'); const cache = new BrowscapCache(this.cacheDir); const GetData = require('./helper/data'); const patternHelper = new GetPattern(cache); const dataHelper = new GetData(cache); const parser = new Ini(patternHelper, dataHelper); const promise = parser.getBrowser(userAgent); // Unpack already resolved promises to ensure backward compatibility let result; promise.then((value) => { result = value; }); if (typeof result === 'undefined') { return promise; } else { return result; } } } module.exports = Browscap;
mit
sielenk/furnace
src/Config.hpp
208
// (C) 2016 Marvin Sielenkemper #pragma once #include "db/Config.hpp" class Config : boost::noncopyable { public: virtual db::Config const& dbConfig() const = 0; protected: Config(); ~Config(); };
mit
RandyyDSH/TokensSelector
src/board/board.ts
5665
import {AbstractToken} from "../token/abstract.token"; import {TokensGroup} from "../token/group/tokens.group"; import {BoardPropertys} from "./board.propertys"; import {TokensGroupType} from "../token/group/tokens.group.type"; import * as Konva from "konva"; import {Stage} from "konva"; export interface BoardElement { setBoard(board:Board, id:number):void; getBoard():{ id:number, board:Board } } export class Board { private propertys:BoardPropertys; private stage: Stage; private textLayer: Konva.Layer; private selectedTokens: AbstractToken[] = []; private isMouseDown: boolean = false; private stringLeftPadding = 5; private stringTopPadding = 5; // private objects:{ [key:number]:AbstractToken|TokensGroupType|TokensGroup; } = {}; private nexId = 0; private tokens:{[key:number]:AbstractToken} = {}; private tokensGroups:{[key:number]:TokensGroup} = {}; private tokensGroupType:{[key:number]:TokensGroupType} = {}; private currentTokensGroupType:TokensGroupType; constructor(stageConfig: any, tokens:AbstractToken[], propertys:BoardPropertys = new BoardPropertys) { this.propertys = propertys; this.stage = new Konva.Stage(stageConfig); this.textLayer = new Konva.Layer(); this.stage.add(this.textLayer); this.initBaseLayer(tokens); this.initOnHoverAction(); this.addTokensGroupType(); } getPropertys(): BoardPropertys { return this.propertys; } initBaseLayer(tokens:AbstractToken[]) { let x = this.stringLeftPadding; let y = this.stringTopPadding; for (let token of tokens) { this.add(token); const tokenView:Konva.Node = token.getView(); tokenView.setAttrs({ x: x, y: y }); this.textLayer.add(tokenView); x += tokenView.getWidth() + 2; } this.textLayer.draw(); } initOnHoverAction() { this.textLayer.on('mouseover', (evt:Event) => { if (evt.target instanceof Konva.Node) { const label: Konva.Label = (evt.target as Konva.Node).getParent() as Konva.Label; const tag: Konva.Tag = label.getTag() as Konva.Tag; tag.fill('yellow'); label.draw(); if (this.isMouseDown) { this.selectedTokens.push(label.getAttr('token')); } } }); this.textLayer.on('mouseout', (evt:Event) => { if (!this.isMouseDown && evt.target instanceof Konva.Node) { const label: Konva.Label = (evt.target as Konva.Node).getParent() as Konva.Label; const tag: Konva.Tag = label.getTag() as Konva.Tag; tag.fill('#E5FF80'); label.draw(); } }); this.textLayer.on("mousedown", (evt:Event) => { this.isMouseDown = true; if (evt.target instanceof Konva.Node) { const label: Konva.Label = (evt.target as Konva.Node).getParent() as Konva.Label; this.selectedTokens.push(label.getAttr('token')); } }); this.stage.on("mouseup", () => { this.isMouseDown = false; this.createTokenGroup(this.selectedTokens).then( (tokenGroup) => { this.currentTokensGroupType.addTokensGroup(tokenGroup); }, (mergedTokensGroup) => { console.log(`ERROR::${mergedTokensGroup}`) } ); for (let token of this.selectedTokens) { token.getTag().fill('#E5FF80'); token.getView().draw(); } this.selectedTokens = []; }); } getToken(id:number) : AbstractToken { return this.tokens[id]; } createTokenGroup(tokens:AbstractToken[]):Promise<any> { return new Promise((resolve, reject) => { const groupToken:TokensGroup = new TokensGroup(tokens, this.currentTokensGroupType); const mergedTokensGroup:string[] = []; for (let id in this.tokensGroups) { if (groupToken.hasMerge(this.tokensGroups[id])) { mergedTokensGroup.push(id); } } if (mergedTokensGroup.length) { reject(mergedTokensGroup); } else { let newGroupTokenId = this.add(groupToken); resolve(groupToken); } }); } addTokensGroupType(rgbColor:string = 'red') { const tokensGroupType = new TokensGroupType(rgbColor); this.add(tokensGroupType); this.currentTokensGroupType = tokensGroupType; this.stage.add(tokensGroupType.getLayer()); } getTokensGroupTypeViewY(id:number) : number { let y = this.stringTopPadding + this.propertys.getLineHeight(); for (let key in this.tokensGroupType) { if (key === id.toString()) break; y += 10; } return y; } private add(object:AbstractToken|TokensGroup|TokensGroupType):number { const currentId = this.nexId++; object.setBoard(this, currentId); if (object instanceof AbstractToken) { this.tokens[currentId] = <AbstractToken>object; } else if (object instanceof TokensGroup) { this.tokensGroups[currentId] = <TokensGroup>object; } else { this.tokensGroupType[currentId] = <TokensGroupType>object; } return currentId; } }
mit
achimha/ngx-datatable
release/components/body/selection.component.ngfactory.ts
7964
/** * @fileoverview This file is generated by the Angular 2 template compiler. * Do not edit. * @suppress {suspiciousCode,uselessCode,missingProperties} */ /* tslint:disable */ import * as import0 from '../../../../src/components/body/selection.component'; import * as import1 from '@angular/core/src/change_detection/change_detection_util'; import * as import2 from '@angular/core/src/linker/view'; import * as import3 from '@angular/core/src/linker/view_utils'; import * as import4 from '@angular/core/src/render/api'; import * as import5 from '@angular/core/src/metadata/view'; import * as import6 from '@angular/core/src/linker/view_type'; import * as import7 from '@angular/core/src/change_detection/constants'; import * as import8 from '@angular/core/src/linker/component_factory'; export class Wrapper_DataTableSelectionComponent { /*private*/ _eventHandler:Function; context:import0.DataTableSelectionComponent; /*private*/ _changed:boolean; /*private*/ _expr_0:any; /*private*/ _expr_1:any; /*private*/ _expr_2:any; /*private*/ _expr_3:any; /*private*/ _expr_4:any; /*private*/ _expr_5:any; subscription0:any; subscription1:any; constructor() { this._changed = false; this.context = new import0.DataTableSelectionComponent(); this._expr_0 = import1.UNINITIALIZED; this._expr_1 = import1.UNINITIALIZED; this._expr_2 = import1.UNINITIALIZED; this._expr_3 = import1.UNINITIALIZED; this._expr_4 = import1.UNINITIALIZED; this._expr_5 = import1.UNINITIALIZED; } ngOnDetach(view:import2.AppView<any>,componentView:import2.AppView<any>,el:any):void { } ngOnDestroy():void { (this.subscription0 && this.subscription0.unsubscribe()); (this.subscription1 && this.subscription1.unsubscribe()); } check_rows(currValue:any,throwOnChange:boolean,forceUpdate:boolean):void { if ((forceUpdate || import3.checkBinding(throwOnChange,this._expr_0,currValue))) { this._changed = true; this.context.rows = currValue; this._expr_0 = currValue; } } check_selected(currValue:any,throwOnChange:boolean,forceUpdate:boolean):void { if ((forceUpdate || import3.checkBinding(throwOnChange,this._expr_1,currValue))) { this._changed = true; this.context.selected = currValue; this._expr_1 = currValue; } } check_selectEnabled(currValue:any,throwOnChange:boolean,forceUpdate:boolean):void { if ((forceUpdate || import3.checkBinding(throwOnChange,this._expr_2,currValue))) { this._changed = true; this.context.selectEnabled = currValue; this._expr_2 = currValue; } } check_selectionType(currValue:any,throwOnChange:boolean,forceUpdate:boolean):void { if ((forceUpdate || import3.checkBinding(throwOnChange,this._expr_3,currValue))) { this._changed = true; this.context.selectionType = currValue; this._expr_3 = currValue; } } check_rowIdentity(currValue:any,throwOnChange:boolean,forceUpdate:boolean):void { if ((forceUpdate || import3.checkBinding(throwOnChange,this._expr_4,currValue))) { this._changed = true; this.context.rowIdentity = currValue; this._expr_4 = currValue; } } check_selectCheck(currValue:any,throwOnChange:boolean,forceUpdate:boolean):void { if ((forceUpdate || import3.checkBinding(throwOnChange,this._expr_5,currValue))) { this._changed = true; this.context.selectCheck = currValue; this._expr_5 = currValue; } } ngDoCheck(view:import2.AppView<any>,el:any,throwOnChange:boolean):boolean { var changed:any = this._changed; this._changed = false; return changed; } checkHost(view:import2.AppView<any>,componentView:import2.AppView<any>,el:any,throwOnChange:boolean):void { } handleEvent(eventName:string,$event:any):boolean { var result:boolean = true; return result; } subscribe(view:import2.AppView<any>,_eventHandler:any,emit0:boolean,emit1:boolean):void { this._eventHandler = _eventHandler; if (emit0) { (this.subscription0 = this.context.activate.subscribe(_eventHandler.bind(view,'activate'))); } if (emit1) { (this.subscription1 = this.context.select.subscribe(_eventHandler.bind(view,'select'))); } } } var renderType_DataTableSelectionComponent_Host:import4.RenderComponentType = import3.createRenderComponentType('',0,import5.ViewEncapsulation.None,([] as any[]),{}); class View_DataTableSelectionComponent_Host0 extends import2.AppView<any> { _el_0:any; compView_0:import2.AppView<import0.DataTableSelectionComponent>; _DataTableSelectionComponent_0_3:Wrapper_DataTableSelectionComponent; constructor(viewUtils:import3.ViewUtils,parentView:import2.AppView<any>,parentIndex:number,parentElement:any) { super(View_DataTableSelectionComponent_Host0,renderType_DataTableSelectionComponent_Host,import6.ViewType.HOST,viewUtils,parentView,parentIndex,parentElement,import7.ChangeDetectorStatus.CheckAlways); } createInternal(rootSelector:string):import8.ComponentRef<any> { this._el_0 = import3.selectOrCreateRenderHostElement(this.renderer,'datatable-selection',import3.EMPTY_INLINE_ARRAY,rootSelector,(null as any)); this.compView_0 = new View_DataTableSelectionComponent0(this.viewUtils,this,0,this._el_0); this._DataTableSelectionComponent_0_3 = new Wrapper_DataTableSelectionComponent(); this.compView_0.create(this._DataTableSelectionComponent_0_3.context); this.init(this._el_0,((<any>this.renderer).directRenderer? (null as any): [this._el_0]),(null as any)); return new import8.ComponentRef_<any>(0,this,this._el_0,this._DataTableSelectionComponent_0_3.context); } injectorGetInternal(token:any,requestNodeIndex:number,notFoundResult:any):any { if (((token === import0.DataTableSelectionComponent) && (0 === requestNodeIndex))) { return this._DataTableSelectionComponent_0_3.context; } return notFoundResult; } detectChangesInternal(throwOnChange:boolean):void { this._DataTableSelectionComponent_0_3.ngDoCheck(this,this._el_0,throwOnChange); this.compView_0.internalDetectChanges(throwOnChange); } destroyInternal():void { this.compView_0.destroy(); this._DataTableSelectionComponent_0_3.ngOnDestroy(); } visitRootNodesInternal(cb:any,ctx:any):void { cb(this._el_0,ctx); } visitProjectableNodesInternal(nodeIndex:number,ngContentIndex:number,cb:any,ctx:any):void { if (((nodeIndex == 0) && (ngContentIndex == 0))) { } } } export const DataTableSelectionComponentNgFactory:import8.ComponentFactory<import0.DataTableSelectionComponent> = new import8.ComponentFactory<import0.DataTableSelectionComponent>('datatable-selection',View_DataTableSelectionComponent_Host0,import0.DataTableSelectionComponent); const styles_DataTableSelectionComponent:any[] = ([] as any[]); var renderType_DataTableSelectionComponent:import4.RenderComponentType = import3.createRenderComponentType('',1,import5.ViewEncapsulation.None,styles_DataTableSelectionComponent,{}); export class View_DataTableSelectionComponent0 extends import2.AppView<import0.DataTableSelectionComponent> { _text_0:any; _text_1:any; constructor(viewUtils:import3.ViewUtils,parentView:import2.AppView<any>,parentIndex:number,parentElement:any) { super(View_DataTableSelectionComponent0,renderType_DataTableSelectionComponent,import6.ViewType.COMPONENT,viewUtils,parentView,parentIndex,parentElement,import7.ChangeDetectorStatus.CheckAlways); } createInternal(rootSelector:string):import8.ComponentRef<any> { const parentRenderNode:any = this.renderer.createViewRoot(this.parentElement); this._text_0 = this.renderer.createText(parentRenderNode,'\n ',(null as any)); this.projectNodes(parentRenderNode,0); this._text_1 = this.renderer.createText(parentRenderNode,'\n ',(null as any)); this.init((null as any),((<any>this.renderer).directRenderer? (null as any): [ this._text_0, this._text_1 ] ),(null as any)); return (null as any); } }
mit
HarleyKwyn/sudoku
static/src/main.js
81
window.requestAnimationFrame(function () { new GameManager(Sudoku, board); });
mit
asiertarancon/CarrerasPorLaRioja
src/App/AppBundle/Controller/OrganizacionController.php
579
<?php namespace App\AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; class OrganizacionController extends Controller { public function buscarPorSlugAction($slug) { $organizacion = $this -> get('organizacionrepository') -> BuscarPorSlug($slug); //return $this -> render ( "AppAppBundle:Organizaciones:organizacion.html.twig" , array ( 'organizacion' => $organizacion )); return new Response(implode("<br/>", array ( 'organizacion' => $organizacion ))); } }
mit
willynilly/grunt-solemn
test/solemn_test.js
953
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.solemn = { setUp: function(done) { // setup here if necessary done(); }, default_options: function(test) { test.expect(0); test.done(); }, custom_options: function(test) { test.expect(0); test.done(); }, };
mit
pex-gl/pex-renderer
shaders/chunks/shadowing.glsl.js
3983
module.exports = /* glsl */ ` #if NUM_DIRECTIONAL_LIGHTS > 0 || NUM_SPOT_LIGHTS > 0 //fron depth buf normalized z to linear (eye space) z //http://stackoverflow.com/questions/6652253/getting-the-true-z-value-from-the-depth-buffer // float ndcDepthToEyeSpaceProj(float ndcDepth, float near, float far) { // return 2.0 * near * far / (far + near - ndcDepth * (far - near)); // } //otho //z = (f - n) * (zn + (f + n)/(f-n))/2 //http://www.ogldev.org/www/tutorial47/tutorial47.html const float DEPTH_TOLERANCE = 0.000001; float ndcDepthToEyeSpace(float ndcDepth, float near, float far) { return (far - near) * (ndcDepth + (far + near) / (far - near)) / 2.0; } float readDepth(sampler2D depthMap, vec2 coord, float near, float far) { float z_b = texture2D(depthMap, coord).r; float z_n = 2.0 * z_b - 1.0; return ndcDepthToEyeSpace(z_n, near, far); } float texture2DCompare(sampler2D depthMap, vec2 uv, float compare, float near, float far) { float depth = readDepth(depthMap, uv, near, far); if (depth >= far - DEPTH_TOLERANCE) return 1.0; // if (depth >= far) return 1.0; return step(compare, depth); } float texture2DShadowLerp(sampler2D depthMap, vec2 size, vec2 uv, float compare, float near, float far){ vec2 texelSize = vec2(1.0)/size; vec2 f = fract(uv * size + 0.5); vec2 centroidUV = floor(uv*size+0.5)/size; float lb = texture2DCompare(depthMap, centroidUV+texelSize*vec2(0.0, 0.0), compare, near, far); float lt = texture2DCompare(depthMap, centroidUV+texelSize*vec2(0.0, 1.0), compare, near, far); float rb = texture2DCompare(depthMap, centroidUV+texelSize*vec2(1.0, 0.0), compare, near, far); float rt = texture2DCompare(depthMap, centroidUV+texelSize*vec2(1.0, 1.0), compare, near, far); float a = mix(lb, lt, f.y); float b = mix(rb, rt, f.y); float c = mix(a, b, f.x); return c; } float PCF3x3(sampler2D depths, vec2 size, vec2 uv, float compare, float near, float far){ float result = 0.0; for(int x=-1; x<=1; x++){ for(int y=-1; y<=1; y++){ vec2 off = vec2(x,y)/float(size); result += texture2DShadowLerp(depths, size, uv+off, compare, near, far); } } return result/9.0; } float PCF5x5(sampler2D depths, vec2 size, vec2 uv, float compare, float near, float far){ float result = 0.0; for(int x=-2; x<=2; x++){ for(int y=-2; y<=2; y++){ vec2 off = vec2(x,y)/float(size); result += texture2DShadowLerp(depths, size, uv+off, compare, near, far); } } return result/25.0; } float getShadow(sampler2D depths, vec2 size, vec2 uv, float compare, float near, float far) { if (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0) { return 1.0; } #if SHADOW_QUALITY == 0 float illuminated = 1.0; #endif #if SHADOW_QUALITY == 1 float illuminated = texture2DCompare(depths, uv, compare, near, far); #endif #if SHADOW_QUALITY == 2 float illuminated = texture2DShadowLerp(depths, size, uv, compare, near, far); #endif #if SHADOW_QUALITY == 3 float illuminated = PCF3x3(depths, size, uv, compare, near, far); #endif #if SHADOW_QUALITY == 4 float illuminated = PCF5x5(depths, size, uv, compare, near, far); #endif return illuminated; } #endif #if NUM_POINT_LIGHTS > 0 float getPunctualShadow(samplerCube depths, vec3 posToLight) { float dist = length(posToLight); vec3 N = -normalize(posToLight); float far = 10.0; float depth = unpackDepth(textureCube(depths, N)) * far; if (dist - 0.05 > depth) { return 0.0; } return 1.0; // float depth = textureCube(depths, N).r; // illuminated = (depth - dist); // illuminated = step(dist, depth / 2.0); // data.directDiffuse = vec3(fract(depth)); // data.directDiffuse = vec3(fract(dist)); // data.directDiffuse = vec3(illuminated); } #endif `
mit
sharathprabhal/NBS3Sync
src/main/java/com/example/services/FileOperation.java
125
package com.example.services; /** * Different file operations */ public enum FileOperation { CREATE, MODIFY, DELETE }
mit
tusharvjoshi/nbrunwithargs
src/com/tusharjoshi/runargs/RunProjectAction.java
2913
/* The MIT License (MIT) Copyright (c) 2014 Tushar Joshi Copyright (c) 2020 DAGOPT Optimization Technologies GmbH Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tusharjoshi.runargs; import java.awt.event.ActionEvent; import javax.swing.Action; import org.netbeans.api.project.Project; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.util.ContextAwareAction; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.util.Utilities; /** * * @author Tushar Joshi */ @ActionID( category = "Build", id = "com.tusharjoshi.runargs.RunProjectAction" ) @ActionRegistration(displayName = "#CTL_RunProjectAction", lazy = false) @ActionReferences({ @ActionReference(path = "Menu/BuildProject", position = 0), @ActionReference(path = "Projects/Actions", position = 0), @ActionReference(path = "Shortcuts", name = "D-S-R") }) @NbBundle.Messages({ "CTL_RunProjectAction=Run with Arguments"}) public class RunProjectAction extends ProjectAction implements ContextAwareAction { @Override public Action createContextAwareInstance(Lookup lkp) { return new RunProjectAction(lkp, Constants.COMMAND_RUN_NAME, "D-S-R"); } public RunProjectAction() { super(Utilities.actionsGlobalContext(), Constants.COMMAND_RUN_NAME, "D-S-R"); } public RunProjectAction(final Lookup lkp, String commandName, String accKey) { super(lkp,commandName, accKey); } @Override public void actionPerformed(final ActionEvent e) { Project project = getProject(); CommandHandler commandHandler = CommandHandler.createCommandHandler(project); if (commandHandler != null) { commandHandler.runProject(project); } } }
mit
mapillary/mapillary-js
test/state/StateService.test.ts
376
import { bootstrap } from "../Bootstrap"; bootstrap(); import { StateService } from "../../src/state/StateService"; import { State } from "../../src/state/State"; describe("StateService.ctor", () => { it("should be contructed", () => { let stateService: StateService = new StateService(State.Traversing); expect(stateService).toBeDefined(); }); });
mit
classmarcos/punto
application/views/back-end/modal.php
779
<div id="myModal" class="modal fade bs-example-modal-lg" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">Pagar Servicios</h4> </div> <div class="modal-body"> <p class="cuerpoModal"></p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default btn-sm" data-dismiss="modal"><i class="fa fa-times"></i> Cerrar</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal -->
mit
phroph/magicsim
magicsim/magicsim/objectModels/Azerite.cs
337
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace magicsim.objectModels { public class Azerite { public string Name; public string Id; public Azerite() { Name = ""; Id = ""; } } }
mit
elasota/rdx2
src/rdx/rdx_arraydefprototype.hpp
316
#ifndef __RDX_ARRAYDEFPROTOTYPE_HPP__ #define __RDX_ARRAYDEFPROTOTYPE_HPP__ #include "rdx_coretypes.hpp" #include "rdx_objectguid.hpp" struct rdxSArrayDefPrototype { rdxSObjectGUID containedTypeGUID; rdxLargeUInt numDimensions; bool isConstant; rdxLargeUInt tableIndex; }; #endif
mit
sensu-plugins/sensu-plugins-kubernetes
bin/check-kube-nodes-ready.rb
2719
#! /usr/bin/env ruby # frozen_string_literal: false # check-kube-nodes-ready.rb # # DESCRIPTION: # => Check if the Kubernetes nodes are in a ready to use state # # OUTPUT: # plain text # # PLATFORMS: # Linux # # DEPENDENCIES: # gem: sensu-plugin # gem: kube-client # # USAGE: # -s, --api-server URL URL to API server # -v, --api-version VERSION API version. Defaults to 'v1' # --in-cluster Use service account authentication # --ca-file CA-FILE CA file to verify API server cert # --cert CERT-FILE Client cert to present # --key KEY-FILE Client key for the client cert # -u, --user USER User with access to API # -p, --password PASSWORD If user is passed, also pass a password # -t, --token TOKEN Bearer token for authorization # --token-file TOKEN-FILE File containing bearer token for authorization # --exclude-nodes Exclude the specified nodes (comma separated list) # Exclude wins when a node is in both include and exclude lists # --include-nodes Include the specified nodes (comma separated list), an # empty list includes all nodes # # LICENSE: # Kel Cecil <kelcecil@praisechaos.com> # Released under the same terms as Sensu (the MIT license); see LICENSE # for details. # require 'sensu-plugins-kubernetes/cli' require 'sensu-plugins-kubernetes/exclude' class AllNodesAreReady < Sensu::Plugins::Kubernetes::CLI @options = Sensu::Plugins::Kubernetes::CLI.options.dup include Sensu::Plugins::Kubernetes::Exclude option :exclude_nodes, description: 'Exclude the specified nodes (comma separated list)', long: '--exclude-nodes NODES', proc: proc { |a| a.split(',') }, default: '' option :include_nodes, description: 'Include the specified nodes (comma separated list)', long: '--include-nodes NODES', proc: proc { |a| a.split(',') }, default: '' def run failed_nodes = [] client.get_nodes.each do |node| item = node.status.conditions.detect { |condition| condition.type == 'Ready' } if item.nil? warning "#{node.name} does not have a status" elsif item.status != 'True' next if should_exclude_node(node.metadata.name) failed_nodes << node.metadata.name unless node.spec.unschedulable end end if failed_nodes.empty? ok 'All nodes are reporting as ready' end critical "Nodes are not ready: #{failed_nodes.join(' ')}" rescue KubeException => e critical 'API error: ' << e.message end end
mit
Lukasss93/telegrambot-php
src/Types/ProximityAlertTriggered.php
590
<?php namespace TelegramBot\Types; /** * This object represents the content of a service message, sent whenever a user in the chat * triggers a proximity alert set by another user. * @see https://core.telegram.org/bots/api#proximityalerttriggered */ class ProximityAlertTriggered { /** * User that triggered the alert * @var User $traveler */ public $traveler; /** * User that set the alert * @var User $watcher */ public $watcher; /** * The distance between the users * @var int $distance */ public $distance; }
mit
ain/jquery-fieldsync
Gruntfile.js
1682
/*global module:false*/ module.exports = function(grunt) { // Enable Grunt plugins grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-contrib-watch'); // Project configuration. grunt.initConfig({ jshint: { all: { src: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'], options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, browser: true, globals: { jQuery: true } } } }, pkg: grunt.file.readJSON('package.json'), qunit: { files: ['test/**/*.html'] }, watch: { scripts: { files: 'src/**/*.js', tasks: ['jshint', 'qunit'] } }, uglify: { options: { banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' + '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' + ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> \n*/\n' }, dist: { files: { 'dist/<%= pkg.name %>.min.js': ['<banner:meta.banner>', 'src/<%= pkg.name %>.js'] } } } }); // Default task. grunt.registerTask('default', ['jshint', 'uglify']); // Travis CI task grunt.registerTask('travis', ['jshint']); };
mit
Azure/azure-sdk-for-java
sdk/mysqlflexibleserver/azure-resourcemanager-mysqlflexibleserver/src/main/java/com/azure/resourcemanager/mysqlflexibleserver/models/ReplicationRole.java
1333
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.mysqlflexibleserver.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for ReplicationRole. */ public final class ReplicationRole extends ExpandableStringEnum<ReplicationRole> { /** Static value None for ReplicationRole. */ public static final ReplicationRole NONE = fromString("None"); /** Static value Source for ReplicationRole. */ public static final ReplicationRole SOURCE = fromString("Source"); /** Static value Replica for ReplicationRole. */ public static final ReplicationRole REPLICA = fromString("Replica"); /** * Creates or finds a ReplicationRole from its string representation. * * @param name a name to look for. * @return the corresponding ReplicationRole. */ @JsonCreator public static ReplicationRole fromString(String name) { return fromString(name, ReplicationRole.class); } /** @return known ReplicationRole values. */ public static Collection<ReplicationRole> values() { return values(ReplicationRole.class); } }
mit
tgroshon/buildmypcn
public/modules/diagrams/config/diagrams.client.config.js
390
'use strict'; // Configuring the Diagrams module angular.module('diagrams').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Diagrams', 'diagrams', 'dropdown', '/diagrams(/create)?'); Menus.addSubMenuItem('topbar', 'diagrams', 'List Diagrams', 'diagrams'); Menus.addSubMenuItem('topbar', 'diagrams', 'New Diagram', 'diagrams/create'); } ]);
mit
lars-erik/Umbraco-CMS
src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs
10396
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Xml.XPath; using Examine.LuceneEngine.Providers; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web.Composing; using Umbraco.Web.Models; namespace Umbraco.Web.PublishedCache.XmlPublishedCache { /// <summary> /// An IPublishedContent that is represented all by a dictionary. /// </summary> /// <remarks> /// This is a helper class and definitely not intended for public use, it expects that all of the values required /// to create an IPublishedContent exist in the dictionary by specific aliases. /// </remarks> internal class DictionaryPublishedContent : PublishedContentBase { // note: I'm not sure this class fully complies with IPublishedContent rules especially // I'm not sure that _properties contains all properties including those without a value, // neither that GetProperty will return a property without a value vs. null... @zpqrtbnk // List of properties that will appear in the XML and do not match // anything in the ContentType, so they must be ignored. private static readonly string[] IgnoredKeys = { "version", "isDoc" }; public DictionaryPublishedContent( IReadOnlyDictionary<string, string> valueDictionary, Func<int, IPublishedContent> getParent, Func<int, XPathNavigator, IEnumerable<IPublishedContent>> getChildren, Func<DictionaryPublishedContent, string, IPublishedProperty> getProperty, ICacheProvider cacheProvider, PublishedContentTypeCache contentTypeCache, XPathNavigator nav, bool fromExamine) { if (valueDictionary == null) throw new ArgumentNullException(nameof(valueDictionary)); if (getParent == null) throw new ArgumentNullException(nameof(getParent)); if (getProperty == null) throw new ArgumentNullException(nameof(getProperty)); _getParent = new Lazy<IPublishedContent>(() => getParent(ParentId)); _getChildren = new Lazy<IEnumerable<IPublishedContent>>(() => getChildren(Id, nav)); _getProperty = getProperty; _cacheProvider = cacheProvider; LoadedFromExamine = fromExamine; ValidateAndSetProperty(valueDictionary, val => _id = Int32.Parse(val), "id", "nodeId", "__NodeId"); //should validate the int! ValidateAndSetProperty(valueDictionary, val => _key = Guid.Parse(val), "key"); //ValidateAndSetProperty(valueDictionary, val => _templateId = int.Parse(val), "template", "templateId"); ValidateAndSetProperty(valueDictionary, val => _sortOrder = Int32.Parse(val), "sortOrder"); ValidateAndSetProperty(valueDictionary, val => _name = val, "nodeName"); ValidateAndSetProperty(valueDictionary, val => _urlName = val, "urlName"); ValidateAndSetProperty(valueDictionary, val => _documentTypeAlias = val, "nodeTypeAlias", LuceneIndex.ItemTypeFieldName); ValidateAndSetProperty(valueDictionary, val => _documentTypeId = Int32.Parse(val), "nodeType"); //ValidateAndSetProperty(valueDictionary, val => _writerName = val, "writerName"); ValidateAndSetProperty(valueDictionary, val => _creatorName = val, "creatorName", "writerName"); //this is a bit of a hack fix for: U4-1132 //ValidateAndSetProperty(valueDictionary, val => _writerId = int.Parse(val), "writerID"); ValidateAndSetProperty(valueDictionary, val => _creatorId = Int32.Parse(val), "creatorID", "writerID"); //this is a bit of a hack fix for: U4-1132 ValidateAndSetProperty(valueDictionary, val => _path = val, "path", "__Path"); ValidateAndSetProperty(valueDictionary, val => _createDate = ParseDateTimeValue(val), "createDate"); ValidateAndSetProperty(valueDictionary, val => _updateDate = ParseDateTimeValue(val), "updateDate"); ValidateAndSetProperty(valueDictionary, val => _level = Int32.Parse(val), "level"); ValidateAndSetProperty(valueDictionary, val => { int pId; ParentId = -1; if (Int32.TryParse(val, out pId)) { ParentId = pId; } }, "parentID"); _contentType = contentTypeCache.Get(PublishedItemType.Media, _documentTypeAlias); _properties = new Collection<IPublishedProperty>(); //handle content type properties //make sure we create them even if there's no value foreach (var propertyType in _contentType.PropertyTypes) { var alias = propertyType.Alias; _keysAdded.Add(alias); string value; const bool isPreviewing = false; // false :: never preview a media var property = valueDictionary.TryGetValue(alias, out value) == false || value == null ? new XmlPublishedProperty(propertyType, this, isPreviewing) : new XmlPublishedProperty(propertyType, this, isPreviewing, value); _properties.Add(property); } //loop through remaining values that haven't been applied foreach (var i in valueDictionary.Where(x => _keysAdded.Contains(x.Key) == false // not already processed && IgnoredKeys.Contains(x.Key) == false)) // not ignorable { if (i.Key.InvariantStartsWith("__")) { // no type for that one, dunno how to convert, drop it //IPublishedProperty property = new PropertyResult(i.Key, i.Value, PropertyResultType.CustomProperty); //_properties.Add(property); } else { // this is a property that does not correspond to anything, ignore and log Current.Logger.Warn<PublishedMediaCache>("Dropping property '{PropertyKey}' because it does not belong to the content type.", i.Key); } } } private DateTime ParseDateTimeValue(string val) { if (LoadedFromExamine == false) return DateTime.Parse(val); //we need to parse the date time using Lucene converters var ticks = Int64.Parse(val); return new DateTime(ticks); } /// <summary> /// Flag to get/set if this was laoded from examine cache /// </summary> internal bool LoadedFromExamine { get; } //private readonly Func<DictionaryPublishedContent, IPublishedContent> _getParent; private readonly Lazy<IPublishedContent> _getParent; //private readonly Func<DictionaryPublishedContent, IEnumerable<IPublishedContent>> _getChildren; private readonly Lazy<IEnumerable<IPublishedContent>> _getChildren; private readonly Func<DictionaryPublishedContent, string, IPublishedProperty> _getProperty; private readonly ICacheProvider _cacheProvider; /// <summary> /// Returns 'Media' as the item type /// </summary> public override PublishedItemType ItemType => PublishedItemType.Media; public override IPublishedContent Parent => _getParent.Value; public int ParentId { get; private set; } public override int Id => _id; public override Guid Key => _key; public override int TemplateId => 0; public override int SortOrder => _sortOrder; public override string Name => _name; public override PublishedCultureInfo GetCulture(string culture = null) => throw new NotSupportedException(); public override IReadOnlyDictionary<string, PublishedCultureInfo> Cultures => throw new NotSupportedException(); public override string UrlSegment => _urlName; public override string WriterName => _creatorName; public override string CreatorName => _creatorName; public override int WriterId => _creatorId; public override int CreatorId => _creatorId; public override string Path => _path; public override DateTime CreateDate => _createDate; public override DateTime UpdateDate => _updateDate; public override int Level => _level; public override bool IsDraft(string culture = null) => false; public override IEnumerable<IPublishedProperty> Properties => _properties; public override IEnumerable<IPublishedContent> Children => _getChildren.Value; public override IPublishedProperty GetProperty(string alias) { return _getProperty(this, alias); } public override PublishedContentType ContentType => _contentType; private readonly List<string> _keysAdded = new List<string>(); private int _id; private Guid _key; //private int _templateId; private int _sortOrder; private string _name; private string _urlName; private string _documentTypeAlias; private int _documentTypeId; //private string _writerName; private string _creatorName; //private int _writerId; private int _creatorId; private string _path; private DateTime _createDate; private DateTime _updateDate; //private Guid _version; private int _level; private readonly ICollection<IPublishedProperty> _properties; private readonly PublishedContentType _contentType; private void ValidateAndSetProperty(IReadOnlyDictionary<string, string> valueDictionary, Action<string> setProperty, params string[] potentialKeys) { var key = potentialKeys.FirstOrDefault(x => valueDictionary.ContainsKey(x) && valueDictionary[x] != null); if (key == null) { throw new FormatException("The valueDictionary is not formatted correctly and is missing any of the '" + String.Join(",", potentialKeys) + "' elements"); } setProperty(valueDictionary[key]); _keysAdded.Add(key); } } }
mit
harborn/LeetCode
src/CountAndSay.cpp
1770
#include <iostream> #include <string> #include <sstream> using namespace std; string countAndSay(int n) { string res; if (n <= 0) return res; res.push_back('1'); n--; char last = '#'; int cnt = 0; while (n) { string ns; string s = res; cnt = 0; int p = 0; char c, lc = '#'; int size = res.size(); while (p < size) { c = s[p]; if (c != lc) { if (cnt != 0) { string ts; ts.append(std::to_string(cnt)); ts.push_back(lc); ns.append(ts); } lc = c; cnt = 1; } else { cnt++; } p++; } if (cnt != 0) { string ts; ts.append(std::to_string(cnt)); ts.push_back(c); ns.append(ts); } res = ns; n--; } return res; } string countAndSay2(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function string seq = "1"; int it = 1; while (it<n) { stringstream newSeq; char last = seq[0]; int count = 0; for (int i = 0; i <= seq.size(); i++) { if (seq[i] == last) { count++; continue; } else { newSeq << count << last; last = seq[i]; count = 1; } } seq = newSeq.str(); it++; } return seq; } string countAndSay3(int n) { if (n < 1)return ""; string prev = "1"; for (int i = 2; i <= n; i++) { char curChar = prev[0]; int times = 1;//curChar ³öÏֵĴÎÊý string tmpstr; prev.push_back('#');//´¦Àí±ß½çÌõ¼þ for (int k = 1; k < prev.size(); k++) { if (prev[k] == curChar) times++; else { tmpstr += to_string(times); tmpstr.push_back(curChar); curChar = prev[k]; times = 1; } } prev = tmpstr; } return prev; } int main(void) { string res = countAndSay(8); //string res = countAndSay2(12); string res3 = countAndSay3(8); return 0; }
mit
lukevers/chitchat
app/js/main.js
3054
// Store the url and websocket globally var url, ws; // Initialize the websockets (function init() { // Figure out current url with `ws` instead of http/https url = location.href.replace(location.protocol.slice(0, -1), 'ws'); // Create new websocket ws = new WebSocket(url+'ws'); // Add own class to autged user AddClassToAuthedUser(); // Load all old messages LoadMessages(); // Bind changing message category bindMessageSwitch(); // Bind enter key to send data bindEnterKeyToSend(); // Bind on message ws.onmessage = receive; })(); // Bind message window switch with other users function bindMessageSwitch() { $('.users ul li').bind('click', function(e) { $this = $(this); // Don't do anything if you click the active tab if (!$this.hasClass('active')) { // Remove active class on other tabs $('.users ul li.active').removeClass('active'); // Set the clicked one to active $this.addClass('active'); // Remove the active class from the active message window $('.messages.active').removeClass('active'); // Add the active class to our active message window $('#messages-'+$this.data('user')).addClass('active'); // Set in our active object active.messages = $this.data('user'); } }); } // Bind enter key to send data function bindEnterKeyToSend() { $('#message').keypress(function(e) { // Only if the enter key was pressed if (e.which == 13) { // First let's get the message var message = $(this).val().trim(); // Make sure message isn't empty if (message !== '') { if (active.messages === '') { alert('You must be in a conversation to send messages'); } else { // Then let's clear the input since we are sending it $(this).val(''); // Send message to server sendMessage(message); } } } }); } // Build HTML message function buildMessage(username, message) { return '<div class="msg"><div class="username">'+username+'</div><div class="message">'+message+'</div></div>'; } // Send data function sendMessage(message) { ws.send(JSON.stringify({ Type: "message", Message: { Sender: "", Receiver: active.messages, Message: message } })); } // Receive data function receive(data) { data = JSON.parse(data.data); console.log(data); if (data.Original) { $('#messages-'+data.Receiver).append(buildMessage(data.Sender, data.Message)); } else { $('#messages-'+data.Sender).append(buildMessage(data.Sender, data.Message)); } } // Load Messages function LoadMessages() { $('.users ul li.user').map(function(i, v) { var user = $(v).data('user'); $.getJSON('/messages/'+active.user+'/'+user, function(data) { data.map(function(msg) { console.log(msg); if (msg.Sender === active.user) { $('#messages-'+msg.Receiver).append(buildMessage(msg.Sender, msg.Message)); } else { $('#messages-'+msg.Sender).append(buildMessage(msg.Sender, msg.Message)); } }); }); }); } // function AddClassToAuthedUser() { $('.users ul li.user[data-user="'+active.user+'"]').addClass('authed'); }
mit
bermudoancio/GSR3
src/Jmbermudo/SGR3Bundle/Entity/VotoRepository.php
2322
<?php namespace Jmbermudo\SGR3Bundle\Entity; use Doctrine\ORM\EntityRepository; use Jmbermudo\SGR3Bundle\Entity\Voto; /** * VotoRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class VotoRepository extends EntityRepository { /** * Devuelve los votos que un usuario ha realizado para una reunión en concreto, * o un array de votos en blanco, uno por cada prereserva * @param Usuario $usuario * @param Reunion $reunion * @return \Jmbermudo\SGR3Bundle\Entity\Voto */ public function getVotosUsuario($usuario, $reunion) { $em = $this->getEntityManager(); $query = $em->createQuery( 'SELECT v FROM JmbermudoSGR3Bundle:Voto v JOIN v.prereserva p WHERE v.usuario = :usuario AND p.reunion = :reunion AND v.valido = true' ) ->setParameter('usuario', $usuario->getId()) ->setParameter('reunion', $reunion->getId()); $reuniones = $query->getResult(); // //Si está vacía devolvemos un voto en blanco por cada prereserva // if(empty($reuniones)){ // foreach($reunion->getPrereservas() as $prereserva){ // $v = new Voto(); // $v->setPrereserva($prereserva); // $v->setUsuario($usuario); // $reuniones[] = $v; // } // } // return $reuniones; } public function anulaVotoUsuarioReunion($usuario, $reunion) { $res = true; $em = $this->getEntityManager(); $query = $em->createQuery( 'UPDATE JmbermudoSGR3Bundle:Voto v SET v.valido = 0 WHERE v.usuario = :usuario AND v.prereserva in ( SELECT p FROM JmbermudoSGR3Bundle:Prereserva p WHERE p.reunion = :reunion )' ) ->setParameter('usuario', $usuario->getId()) ->setParameter('reunion', $reunion->getId()); try { $return = $query->execute(); } catch (\Exception $ex) { //La sentencia ha fallado $res = false; } return $res; } }
mit
Buuz135/Industrial-Foregoing
src/main/java/com/buuz135/industrial/recipe/provider/IndustrialRecipeProvider.java
3567
package com.buuz135.industrial.recipe.provider; import com.buuz135.industrial.api.conveyor.ConveyorUpgradeFactory; import com.buuz135.industrial.item.RangeAddonItem; import com.buuz135.industrial.module.ModuleCore; import com.buuz135.industrial.module.ModuleTool; import com.buuz135.industrial.utils.Reference; import com.hrznstudio.titanium.annotation.MaterialReference; import com.hrznstudio.titanium.block.BlockBase; import com.hrznstudio.titanium.recipe.generator.TitaniumRecipeProvider; import com.hrznstudio.titanium.recipe.generator.TitaniumShapedRecipeBuilder; import com.hrznstudio.titanium.recipe.generator.TitaniumShapelessRecipeBuilder; import net.minecraft.data.CookingRecipeBuilder; import net.minecraft.data.DataGenerator; import net.minecraft.data.IFinishedRecipe; import net.minecraft.item.Item; import net.minecraft.item.Items; import net.minecraft.item.crafting.Ingredient; import net.minecraft.tags.ItemTags; import net.minecraftforge.common.Tags; import java.util.function.Consumer; public class IndustrialRecipeProvider extends TitaniumRecipeProvider { @MaterialReference(type = "gear", material = "iron") public static Item IRON_GEAR; @MaterialReference(type = "gear", material = "gold") public static Item GOLD_GEAR; @MaterialReference(type = "gear", material = "diamond") public static Item DIAMOND_GEAR; public IndustrialRecipeProvider(DataGenerator generatorIn) { super(generatorIn); } @Override public void register(Consumer<IFinishedRecipe> consumer) { BlockBase.BLOCKS.stream().filter(blockBase -> blockBase.getRegistryName().getNamespace().equals(Reference.MOD_ID)).forEach(blockBase -> blockBase.registerRecipe(consumer)); //TRANSPORT ConveyorUpgradeFactory.FACTORIES.forEach(conveyorUpgradeFactory -> conveyorUpgradeFactory.registerRecipe(consumer)); //TOOL ModuleTool.INFINITY_DRILL.registerRecipe(consumer); ModuleTool.MOB_IMPRISONMENT_TOOL.registerRecipe(consumer); ModuleTool.MEAT_FEEDER.registerRecipe(consumer); //CORE ModuleCore.STRAW.registerRecipe(consumer); for (RangeAddonItem rangeAddon : ModuleCore.RANGE_ADDONS) { rangeAddon.registerRecipe(consumer); } TitaniumShapelessRecipeBuilder.shapelessRecipe(ModuleCore.DRY_RUBBER).addIngredient(ModuleCore.TINY_DRY_RUBBER, 9).build(consumer); CookingRecipeBuilder.smeltingRecipe(Ingredient.fromItems(ModuleCore.DRY_RUBBER), ModuleCore.PLASTIC, 0.3f, 200).addCriterion("has_plastic", this.hasItem(ModuleCore.DRY_RUBBER)).build(consumer); TitaniumShapedRecipeBuilder.shapedRecipe(ModuleCore.PITY) .patternLine("WIW").patternLine("IRI").patternLine("WIW") .key('W', ItemTags.LOGS) .key('I', Tags.Items.INGOTS_IRON) .key('R', Tags.Items.STORAGE_BLOCKS_REDSTONE) .build(consumer); TitaniumShapedRecipeBuilder.shapedRecipe(IRON_GEAR) .patternLine(" P ").patternLine("P P").patternLine(" P ") .key('P', Items.IRON_INGOT) .build(consumer); TitaniumShapedRecipeBuilder.shapedRecipe(GOLD_GEAR) .patternLine(" P ").patternLine("P P").patternLine(" P ") .key('P', Items.GOLD_INGOT) .build(consumer); TitaniumShapedRecipeBuilder.shapedRecipe(DIAMOND_GEAR) .patternLine(" P ").patternLine("P P").patternLine(" P ") .key('P', Items.DIAMOND) .build(consumer); } }
mit
matej116/gymn-dacice.cz
www/nette/app/router/RouterFactory.php
2513
<?php /** * Router factory. * all mthod static <- it's PHP 5.2 */ class RouterFactory { private $captchaControl; public function __construct(LazyCaptchaControl $captchaControl) { $this->captchaControl = $captchaControl; } /** * create back compatibility router matching all URLs from old website */ protected function createBCRouter() { $router = new RouteList; $router[] = new Route('clanek.php?id=<id \d+>', 'Article:show'); $router[] = new Route('vypis.php?m=<menu \d+>&str=<paginator-page \d+>', 'Article:list'); $router[] = new Route('navstevni_kniha.php', 'GuestBook:default'); $router[] = new Route('prispevek_kniha.php', 'GuestBook:add'); // fotogalerie v nové verzi neexsituje $router[] = new Route('galerie.php?cl_id=<id>', 'Article:show'); $router[] = new Route('ke-stazeni.php', 'SpecialPage:downloads'); $router[] = new Route('kalendar.php', 'Article:list'); $router[] = new Route('trid<? a|y >.php', 'SpecialPage:classes'); $router[] = new Route('kontakty.php', 'SpecialPage:contacts'); // @todo absolventi $router[] = new Route('vtip.php?clanek=<id>', 'Joke:show'); $router[] = new Route('login.php', 'Sign:in'); return $router; } /** * @return IRouter */ public function createRouter() { $router = new RouteList(); // router for CLI (command line) - default action is import data from old to new database if (PHP_VERSION_ID > 50300) { // only if PHP version > 5.3.0 $router[] = new CliRouter(array('action'=>'Import:import')); } // @TODO SEO URL (<id \d+>-<title>) $router[] = new Route('[index.php]', 'Article:list', Route::ONE_WAY); $router[] = new Route('article?id=<id \d+>', 'Article:show'); $router[] = new Route('[list]?menu=<menu \d+>&page=<page \d+>', 'Article:list'); $router[] = new Route('vtip?id=<id>', 'Joke:show'); // Admin $router[] = new Route('admin/<action>', 'Admin:default'); $router[] = new Route('navstevni-kniha[/<action>]', 'GuestBook:default'); $router[] = new Route('<action>', array( 'presenter' => 'SpecialPage', 'action' => array( Route::FILTER_TABLE => array( 'kontakty' => 'contacts', 'uredni-deska' => 'documents', 'ke-stazeni' => 'downloads', 'tridy' => 'classes', ), ), )); $router[] = $this->captchaControl->createImageRoute(); // Back compatibility URLs $router[] = $this->createBCRouter(); // Default fallback $router[] = new Route('<presenter>/<action>[/<id>]', 'Homepage:default'); return $router; } }
mit
vulcansteel/autorest
AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyComplex/models/cookiecuttershark.js
2210
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; var models = require('./index'); var util = require('util'); /** * @class * Initializes a new instance of the Cookiecuttershark class. * @constructor */ function Cookiecuttershark() { Cookiecuttershark['super_'].call(this); } util.inherits(Cookiecuttershark, models['Shark']); /** * Defines the metadata of Cookiecuttershark * * @returns {object} metadata of Cookiecuttershark * */ Cookiecuttershark.prototype.mapper = function () { return { required: false, serializedName: 'cookiecuttershark', type: { name: 'Composite', className: 'Cookiecuttershark', modelProperties: { species: { required: false, serializedName: 'species', type: { name: 'String' } }, length: { required: true, serializedName: 'length', type: { name: 'Number' } }, siblings: { required: false, serializedName: 'siblings', type: { name: 'Sequence', element: { required: false, serializedName: 'FishElementType', type: { name: 'Composite', polymorphicDiscriminator: 'fishtype', className: 'Fish' } } } }, fishtype: { required: true, serializedName: 'fishtype', type: { name: 'String' } }, age: { required: false, serializedName: 'age', type: { name: 'Number' } }, birthday: { required: true, serializedName: 'birthday', type: { name: 'DateTime' } } } } }; }; module.exports = Cookiecuttershark;
mit
phated/oviews
examples/todo/js/event-binding.js
900
define([ 'event/todo-added', 'event/todo-edit-selected', 'event/todo-edited', 'event/todo-completed', 'event/todo-destroyed', 'event/todo-destroy-completed', 'event/todo-toggle-all', 'dojo/on' ], function(todoAdded, todoEditSelected, todoEdited, todoCompleted, todoDestroyed, todoDestroyCompleted, todoToggleAll, on){ // Add new todo on(document, '#new-todo:keydown', todoAdded); // Select todo for editing on(document, '#todo-list li:dblclick', todoEditSelected); // Save edited todo on(document, '#todo-list li input.edit:keydown', todoEdited); // Completed Toggle on(document, '.view input.toggle:change', todoCompleted); // Todo Removal on(document, '.destroy:click', todoDestroyed); // Remove all completed on(document, '#clear-completed:click', todoDestroyCompleted); // Toggle all todos on(document, '#toggle-all:change', todoToggleAll); });
mit
saip106/Algorithms-DataStructures
app/sorting/merge-sort-spec.js
1558
'use strict'; var mergeSort = require('./merge-sort'), assert = require('assert'); describe('Merge Sort', function () { describe('when sorting an empty array', function () { it('should return empty array', function () { var input = []; mergeSort.sort(input); assert.deepEqual(input, []); }); }); describe('when sorting an array of one element', function () { it('should return the same array', function () { var input = [1]; mergeSort.sort(input); assert.deepEqual(input, [1]); }); }); describe('when sorting an array of two elements', function () { it('should return the sorted array', function () { var input = [2,1]; mergeSort.sort(input); assert.deepEqual(input, [1,2]); }); }); describe('when sorting an array or random numbers', function () { it('should return and fully sorted array', function () { var input = [7,12,54,6,7,3,2,1]; mergeSort.sort(input); assert.deepEqual(input, [1,2,3,6,7,7,12,54]); }); }); describe('when sorting an array or letters', function () { it('should return and fully sorted array', function () { var input = ['m','e','r','g','e','s','o','r','t','e','x','a','m','p','l','e']; mergeSort.sort(input); assert.deepEqual(input, ['a','e','e','e','e','g','l','m','m','o','p','r','r','s','t','x']); }); }); });
mit
cupy/cupy
tests/cupy_tests/test_cudnn.py
16446
import sys import numpy import pytest import cupy import cupy.cuda.cudnn as libcudnn from cupy import testing cudnn_enabled = libcudnn.available if cudnn_enabled: modes = [ libcudnn.CUDNN_ACTIVATION_SIGMOID, libcudnn.CUDNN_ACTIVATION_RELU, libcudnn.CUDNN_ACTIVATION_TANH, ] coef_modes = [ libcudnn.CUDNN_ACTIVATION_CLIPPED_RELU, ] layouts = [ libcudnn.CUDNN_TENSOR_NCHW, libcudnn.CUDNN_TENSOR_NHWC, ] cudnn_version = libcudnn.getVersion() if cudnn_version >= 6000: coef_modes.append(libcudnn.CUDNN_ACTIVATION_ELU) from cupy import cudnn else: cudnn_version = -1 modes = [] coef_modes = [] layouts = [] @testing.parameterize(*testing.product({ 'dtype': [numpy.float32, numpy.float64], 'mode': modes, })) @pytest.mark.skipif(not cudnn_enabled, reason='cuDNN is not available') class TestCudnnActivation: @pytest.fixture(autouse=True) def setUp(self): self.x = testing.shaped_arange((3, 4), cupy, self.dtype) self.y = testing.shaped_arange((3, 4), cupy, self.dtype) self.g = testing.shaped_arange((3, 4), cupy, self.dtype) def test_activation_forward(self): cudnn.activation_forward(self.x, self.mode) def test_activation_backward(self): cudnn.activation_backward(self.x, self.y, self.g, self.mode) @testing.parameterize(*testing.product({ 'dtype': [numpy.float32, numpy.float64], 'mode': coef_modes, })) @pytest.mark.skipif(not cudnn_enabled, reason='cuDNN is not available') class TestCudnnActivationCoef: @pytest.fixture(autouse=True) def setUp(self): self.x = testing.shaped_arange((3, 4), cupy, self.dtype) self.y = testing.shaped_arange((3, 4), cupy, self.dtype) self.g = testing.shaped_arange((3, 4), cupy, self.dtype) self.coef = self.dtype(0.75) def test_activation_forward(self): cudnn.activation_forward(self.x, self.mode, self.coef) def test_activation_backward(self): cudnn.activation_backward(self.x, self.y, self.g, self.mode, self.coef) @testing.parameterize(*testing.product({ 'dtype': [numpy.float32, numpy.float64], 'ratio': [0.0, 0.1, 0.2, 0.5], 'seed': [0, 100] })) @pytest.mark.skipif(not cudnn_enabled, reason='cuDNN is not available') class TestCudnnDropout: @pytest.fixture(autouse=True) def setUp(self): self.x = testing.shaped_arange((3, 4), cupy, self.dtype) self.gy = testing.shaped_arange((3, 4), cupy, self.dtype) self.states = cudnn.DropoutStates(None, self.seed) def test_dropout_forward(self): _, y = self.states.forward(None, self.x, self.ratio) if self.ratio == 0: assert cupy.all(self.x == y) else: assert cupy.all(self.x != y) def test_dropout_backward(self): rspace, y = self.states.forward(None, self.x, self.ratio) gx = self.states.backward( None, self.gy, self.ratio, rspace) forward_mask = y / self.x backward_mask = gx / self.gy # backward_mask must be the same as forward_mask assert cupy.all(forward_mask == backward_mask) def test_dropout_seed(self): # initialize Dropoutstates with the same seed states2 = cudnn.DropoutStates(None, self.seed) rspace, y = self.states.forward(None, self.x, self.ratio) rspace2, y2 = states2.forward(None, self.x, self.ratio) # forward results must be the same assert cupy.all(y == y2) gx = self.states.backward(None, self.gy, self.ratio, rspace) gx2 = states2.backward(None, self.gy, self.ratio, rspace2) # backward results must be the same assert cupy.all(gx == gx2) @testing.parameterize(*(testing.product({ 'tensor_core': ['always', 'auto', 'never'], 'dtype': [numpy.float16, numpy.float32, numpy.float64], 'dilate': [1, 2], 'groups': [1, 2], 'ndim': [2], 'max_workspace_size': [0, 2 ** 22], 'auto_tune': [True, False], 'bias': [True, False], 'layout': layouts, }))) @pytest.mark.skipif(not cudnn_enabled, reason='cuDNN is not available') class TestConvolutionForward: @pytest.fixture(autouse=True) def setUp(self): ndim = self.ndim dtype = self.dtype batches = 2 if self.layout == libcudnn.CUDNN_TENSOR_NHWC: # channel size must be multiple of 4 in_channels_a_group = 4 out_channels_a_group = 4 else: in_channels_a_group = 3 out_channels_a_group = 2 in_channels = in_channels_a_group * self.groups out_channels = out_channels_a_group * self.groups # TODO(anaruse): increase test cases. ksize = 3 stride = 2 pad = ksize // stride * self.dilate self.strides = (stride,) * ndim self.pads = (pad,) * ndim self.dilations = (self.dilate,) * ndim if self.layout == libcudnn.CUDNN_TENSOR_NHWC: self.x = cupy.zeros( (batches,) + (ksize,) * ndim + (in_channels,), dtype) self.W = cupy.zeros( (out_channels,) + (ksize,) * ndim + (in_channels_a_group,), dtype) self.y = cupy.ones( (batches,) + (2,) * ndim + (out_channels,), dtype) else: self.x = cupy.zeros( (batches, in_channels) + (ksize,) * ndim, dtype) self.W = cupy.zeros( (out_channels, in_channels_a_group) + (ksize,) * ndim, dtype) self.y = cupy.ones((batches, out_channels) + (2,) * ndim, dtype) self.b = None if self.bias: self.b = cupy.zeros((out_channels,), dtype) version = libcudnn.getVersion() self.err = None if ((self.dilate > 1 and version < 6000) or (self.groups > 1 and version < 7000)): self.err = ValueError elif ndim > 2 and self.dilate > 1: self.err = libcudnn.CuDNNError _workspace_size = cudnn.get_max_workspace_size() cudnn.set_max_workspace_size(self.max_workspace_size) yield cudnn.set_max_workspace_size(_workspace_size) def call(self): cudnn.convolution_forward( self.x, self.W, self.b, self.y, self.pads, self.strides, self.dilations, self.groups, auto_tune=self.auto_tune, tensor_core=self.tensor_core, d_layout=self.layout, w_layout=self.layout) def test_call(self): if self.layout == libcudnn.CUDNN_TENSOR_NHWC: version = libcudnn.getVersion() if self.groups > 1: pytest.skip() if self.dilate > 1 and version < 7300: pytest.skip() if self.dtype is numpy.float64 and version < 7100: pytest.skip() if self.err is None: self.call() assert (self.y == 0).all() else: with pytest.raises(self.err): self.call() @testing.parameterize(*(testing.product({ 'tensor_core': ['always', 'auto', 'never'], 'dtype': [numpy.float16, numpy.float32, numpy.float64], 'dilate': [1, 2], 'groups': [1, 2], 'ndim': [2, 3], 'max_workspace_size': [0, 2 ** 22], 'auto_tune': [True, False], 'deterministic': [True, False], }))) @pytest.mark.skipif(not cudnn_enabled, reason='cuDNN is not available') class TestConvolutionBackwardFilter: @pytest.fixture(autouse=True) def setUp(self): ndim = self.ndim dtype = self.dtype batches = 2 in_channels_a_group = 3 out_channels_a_group = 2 in_channels = in_channels_a_group * self.groups out_channels = out_channels_a_group * self.groups # TODO(anaruse): increase test cases. ksize = 3 stride = 2 pad = ksize // stride * self.dilate self.strides = (stride,) * ndim self.pads = (pad,) * ndim self.dilations = (self.dilate,) * ndim self.x = cupy.zeros( (batches, in_channels) + (ksize,) * ndim, dtype) self.gy = cupy.zeros((batches, out_channels) + (2,) * ndim, dtype) self.gW = cupy.ones( (out_channels, in_channels_a_group) + (ksize,) * ndim, dtype) version = libcudnn.getVersion() deterministic = self.deterministic self.err = None if ((self.dilate > 1 and version < 6000) or (self.groups > 1 and version < 7000)): self.err = ValueError elif deterministic and ( (self.dilate > 1 and version < 7000) or (ndim > 2 and version < 6000) or (ndim > 2 and self.dtype == numpy.float64 and version < 8100)): self.err = libcudnn.CuDNNError elif (8000 <= version < 8100 and self.max_workspace_size == 0 and int(cupy.cuda.device.get_compute_capability()) < 70 and self.groups > 1 and ndim > 2 and self.dtype == numpy.float16): self.err = RuntimeError _workspace_size = cudnn.get_max_workspace_size() cudnn.set_max_workspace_size(self.max_workspace_size) yield cudnn.set_max_workspace_size(_workspace_size) def call(self): cudnn.convolution_backward_filter( self.x, self.gy, self.gW, self.pads, self.strides, self.dilations, self.groups, deterministic=self.deterministic, auto_tune=self.auto_tune, tensor_core=self.tensor_core) def test_call(self): if self.deterministic and self.max_workspace_size == 0: # This test case is very unstable return if self.err is None: self.call() assert (self.gW == 0).all() else: with pytest.raises(self.err): self.call() @testing.parameterize(*(testing.product({ 'tensor_core': ['always', 'auto', 'never'], 'dtype': [numpy.float16, numpy.float32, numpy.float64], 'dilate': [1, 2], 'groups': [1, 2], 'ndim': [2, 3], 'max_workspace_size': [0, 2 ** 22], 'auto_tune': [True, False], 'deterministic': [True, False], 'bias': [True, False], }))) @pytest.mark.skipif(not cudnn_enabled, reason='cuDNN is not available') class TestConvolutionBackwardData: @pytest.fixture(autouse=True) def setUp(self): ndim = self.ndim dtype = self.dtype batches = 2 in_channels_a_group = 3 out_channels_a_group = 2 in_channels = in_channels_a_group * self.groups out_channels = out_channels_a_group * self.groups # TODO(anaruse): increase test cases. ksize = 3 stride = 2 pad = ksize // stride * self.dilate self.strides = (stride,) * ndim self.pads = (pad,) * ndim self.dilations = (self.dilate,) * ndim self.W = cupy.zeros( (out_channels, in_channels_a_group) + (ksize,) * ndim, dtype) self.gy = cupy.zeros((batches, out_channels) + (2,) * ndim, dtype) self.b = None if self.bias: self.b = cupy.zeros((in_channels,), dtype) self.gx = cupy.ones( (batches, in_channels) + (ksize,) * ndim, dtype) version = libcudnn.getVersion() deterministic = self.deterministic self.err = None if ((self.dilate > 1 and version < 6000) or (self.groups > 1 and version < 7000)): self.err = ValueError elif (sys.platform.startswith('win32') and version == 7605 and deterministic and self.dtype == numpy.float16 and self.ndim == 3 and self.dilate == 2 and self.groups == 2): # see https://github.com/cupy/cupy/pull/4893 self.err = RuntimeError elif deterministic and ( (self.dilate > 1 and (ndim != 2 and version < 8100 or version < 7300)) or (ndim > 2 and version < 6000) or (ndim > 2 and self.dtype == numpy.float64 and version < 8100)): self.err = libcudnn.CuDNNError elif (8000 <= version < 8100 and int(cupy.cuda.device.get_compute_capability()) < 70 and self.dilate > 1 and self.groups > 1 and ndim > 2 and self.dtype == numpy.float16): self.err = RuntimeError _workspace_size = cudnn.get_max_workspace_size() cudnn.set_max_workspace_size(self.max_workspace_size) yield cudnn.set_max_workspace_size(_workspace_size) def call(self): cudnn.convolution_backward_data( self.W, self.gy, self.b, self.gx, self.pads, self.strides, self.dilations, self.groups, deterministic=self.deterministic, auto_tune=self.auto_tune, tensor_core=self.tensor_core) def test_call(self): if self.deterministic and self.max_workspace_size == 0: # This test case is very unstable return if self.err is None: self.call() assert (self.gx == 0).all() else: with pytest.raises(self.err): self.call() @testing.parameterize(*testing.product({ 'dtype': [numpy.float32, numpy.float64], 'ksize': [1, 3, 5], 'stride': [2, 4], 'auto_tune': [True, False], })) @pytest.mark.skipif( not cudnn_enabled or cudnn_version < 7500 or cudnn_version >= 8000, reason='cuDNN 7.x (x >= 5) is required') class TestConvolutionNoAvailableAlgorithm: '''Checks if an expected error is raised. This checks if an expected error is raised when no available algorithm is found by cuDNN for a configuration. This (no available algorithm found) can occur when convolution_backward_data or convolution_backward_filter is performed with NHWC layout. Please notice that conditions that cause the error may change depending on cuDNN version. The conditions below are set based on cuDNN 7.5.0 and 7.6.0. ''' @pytest.fixture(autouse=True) def setUp(self): self.layout = libcudnn.CUDNN_TENSOR_NHWC n = 16 x_c, y_c = 64, 64 x_h, x_w = 32, 32 y_h, y_w = x_h // self.stride, x_w // self.stride self.pad = (self.ksize - 1) // 2 if self.layout == libcudnn.CUDNN_TENSOR_NHWC: x_shape = (n, x_h, x_w, x_c) y_shape = (n, y_h, y_w, y_c) W_shape = (y_c, self.ksize, self.ksize, x_c) else: x_shape = (n, x_c, x_h, x_w) y_shape = (n, y_c, y_h, y_w) W_shape = (y_c, x_c, self.ksize, self.ksize) self.x = cupy.ones(x_shape, dtype=self.dtype) self.W = cupy.ones(W_shape, dtype=self.dtype) self.y = cupy.empty(y_shape, dtype=self.dtype) self.gx = cupy.empty(x_shape, dtype=self.dtype) self.gW = cupy.empty(W_shape, dtype=self.dtype) self.gy = cupy.ones(y_shape, dtype=self.dtype) _workspace_size = cudnn.get_max_workspace_size() cudnn.set_max_workspace_size(0) yield cudnn.set_max_workspace_size(_workspace_size) def test_backward_filter(self): if not (self.layout == libcudnn.CUDNN_TENSOR_NHWC and self.dtype == numpy.float64): pytest.skip() with pytest.raises(RuntimeError): cudnn.convolution_backward_filter( self.x, self.gy, self.gW, pad=(self.pad, self.pad), stride=(self.stride, self.stride), dilation=(1, 1), groups=1, deterministic=False, auto_tune=self.auto_tune, tensor_core='always', d_layout=self.layout, w_layout=self.layout) def test_backward_data(self): if self.layout != libcudnn.CUDNN_TENSOR_NHWC: pytest.skip() with pytest.raises(RuntimeError): cudnn.convolution_backward_data( self.W, self.gy, None, self.gx, pad=(self.pad, self.pad), stride=(self.stride, self.stride), dilation=(1, 1), groups=1, deterministic=0, auto_tune=self.auto_tune, tensor_core='always', d_layout=self.layout, w_layout=self.layout) def _get_error_type(self): if self.auto_tune: return RuntimeError else: return libcudnn.CuDNNError
mit
karim/adila
database/src/main/java/adila/db/tbltetmo_sm2dn915t3.java
253
// This file is automatically generated. package adila.db; /* * Samsung Galaxy Note Edge * * DEVICE: tbltetmo * MODEL: SM-N915T3 */ final class tbltetmo_sm2dn915t3 { public static final String DATA = "Samsung|Galaxy Note Edge|Galaxy Note"; }
mit
johnwquarles/nodetunes
public/js/album-new.js
1407
var $searchBtn = $(".artist-search button"); var $searchInput = $(".artist-search input"); $searchBtn.on('click', function(){ var artistQuery = $searchInput.val(); var searchObj = {artist: artistQuery}; $(".artist-options") && $(".artist-options").empty(); $.get('/search', searchObj).done( function(results) { appendResults(results); }); }); catchReturns($searchInput, $searchBtn); function catchReturns(where, what) { where.keyup(function(event){ if(event.keyCode == 13){ what.click(); } }); } function appendResults(results) { var element = $("<div>").append($("<h3>Artists Found:</h3>")); results.forEach(function(result) { var entry = $('<p>').text(result.name); entry .append($('<button>') .attr('name', result.name) .attr('_id', result._id) .text("choose")); element.append(entry); }) $('.artist-options').append(element); } $(".artist-options").on('click', 'button', function(event) { var artistName = $(event.target).attr('name'); var _id = $(event.target).attr('_id'); $('.artist-options').attr('class', 'hidden'); $('.artist-search').attr('class', 'hidden'); $('.artist-form').removeClass('hidden'); $('.artist-form tr:first-of-type td:first-of-type').text(artistName); $('.artist-form input.hidden:nth-of-type(2)').val(artistName); $('.artist-form input.hidden:first-of-type').val(_id); })
mit
luxe/config-maker
src/attribute_set.cpp
28
#include "attribute_set.hpp"
mit
cuchi/payYourDebts
app/src/main/java/com/payyourdebts/view/AddDebtView.java
203
package com.payyourdebts.view; /** * @author Paulo Henrique Cuchi */ public interface AddDebtView { void onError(String message); void onSuccess(int messageResId); void toast(String s); }
mit
ringoteam/phpredmon-lib
src/Ringo/PhpRedmon/Logger/InstanceLogger.php
5934
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ namespace Ringo\PhpRedmon\Logger; use Ringo\PhpRedmon\Model\Instance; use Ringo\PhpRedmon\Manager\InstanceManager; use Ringo\PhpRedmon\Manager\LogManager; use Ringo\PhpRedmon\Worker\InstanceWorker; use Ringo\PhpRedmon\Model\Log; /** * Class InstanceLogger * * This class manage instance's logs * * @author Patrick Deroubaix <patrick.deroubaix@gmail.com> * @author Pascal DENIS <pascal.denis.75@gmail.com> */ class InstanceLogger { /** * Current instance * * @var \Ringo\Bundle\PhpRedmonBundle\Model\Instance */ protected $instance; /** * Expired timestamp * * @var int */ protected $expiredTimestamp; /** * Current instance manager * * @var \Ringo\PhpRedmon\Manager\InstanceManager */ protected $instanceManager; /** * Current instance manager * * @var \Ringo\PhpRedmon\Manager\LogManager */ protected $logManager; /** * Constructor * * @param \Ringo\PhpRedmon\Manager\InstanceManager $manager * @param \Ringo\PhpRedmon\Manager\LogManager $manager * @param \Ringo\PhpRedmon\Worker\InstanceWorker $worker * @param int $nbDays */ public function __construct(InstanceManager $instanceManager, LogManager $logManager, InstanceWorker $worker, $nbDays) { $this->instanceManager = $instanceManager; $this->logManager = $logManager; $this->worker = $worker; $this->expiredTimestamp = $nbDays * 24 * 60 * 60; } /** * Get current instance * * @return \Ringo\Bundle\PhpRedmonBundle\Model\Instance */ public function getInstance() { return $this->instance; } /** * Set current instance * * @param \Ringo\Bundle\PhpRedmonBundle\Model\Instance $instance * @return \Ringo\Bundle\PhpRedmonBundle\Logger\InstanceLogger */ public function setInstance(Instance $instance) { $this->instance = $instance; return $this; } /** * Get instance manager * * @return \Ringo\PhpRedmon\Manager\InstanceManager */ public function getInstanceManager() { return $this->manager; } /** * Set instance manager * * @param \Ringo\PhpRedmon\Manager\InstanceManager $manager * @return \Ringo\PhpRedmon\Logger\InstanceLogger */ public function setInstanceManager(InstanceManager $manager) { $this->instanceManager = $manager; return $this; } /** * Get instance manager * * @return \Ringo\PhpRedmon\Manager\LogManager */ public function getLogManager() { return $this->manager; } /** * Set instance manager * * @param \Ringo\PhpRedmon\Manager\LogManager $manager * @return \Ringo\PhpRedmon\Logger\InstanceLogger */ public function setLogManager(LogManager $manager) { $this->logManager = $manager; return $this; } /** * Get instance worker * * @return \Ringo\Bundle\PhpRedmonBundle\Worker\InstanceWorker */ public function getWorker() { return $this->worker; } /** * Set instance worker * * @param \Ringo\Bundle\PhpRedmonBundle\Worker\InstanceWorker $worker * @return \Ringo\Bundle\PhpRedmonBundle\Logger\InstanceLogger */ public function setWorker(InstanceWorker $worker) { $this->worker = $worker; return $this; } /** * Execute all steps for current instance * - Clean history * - Add log * - Save current instance state */ public function execute() { $this->cleanHistory(); $this->log(); $this->instanceManager->update($this->instance); } /** * Clean instance history. Delete expired logs */ protected function cleanHistory() { $createdAt = new \DateTime(); $logs = $this->instance->getLogs(); foreach($logs as $log) { if(($createdAt->getTimestamp() - $log->getCreatedAt()->getTimestamp()) > $this->expiredTimestamp) { $this->instance->removeLog($log); } } } /** * Create new log for the current instance */ protected function log() { $this->worker ->setInstance($this->instance); // If instance can be called if($this->worker->ping()) { $infos = $this->worker->getInfos(); $createdAt = new \DateTime(); $log = $this->logManager->createNew(); $log->setMemory($infos['Memory']['used_memory']); $log->setCpu($infos['CPU']['used_cpu_sys']); $log->setNbClients(sizeof($this->worker->getClients())); $log->setCreatedAt($createdAt); // Add log $this->instance->addLog($log); } } }
mit
nguyenvu12/react-metismenu2
dist/react-metismenu.js
120514
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["ReactMetismenu"] = factory(require("react")); else root["ReactMetismenu"] = factory(root["react"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _MetisMenu = __webpack_require__(1); var _MetisMenu2 = _interopRequireDefault(_MetisMenu); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _MetisMenu2.default; /** * src/main.js * Author: H.Alper Tuna <halpertuna@gmail.com> * Date: 16.09.2016 */ /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactRedux = __webpack_require__(3); var _redux = __webpack_require__(11); var _classnames = __webpack_require__(34); var _classnames2 = _interopRequireDefault(_classnames); var _simpleAjax = __webpack_require__(36); var _simpleAjax2 = _interopRequireDefault(_simpleAjax); var _Container = __webpack_require__(39); var _Container2 = _interopRequireDefault(_Container); var _DefaultLink = __webpack_require__(47); var _DefaultLink2 = _interopRequireDefault(_DefaultLink); var _reducers = __webpack_require__(48); var _reducers2 = _interopRequireDefault(_reducers); var _content = __webpack_require__(42); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * src/components/MetisMenu.jsx * Author: H.Alper Tuna <halpertuna@gmail.com> * Date: 16.09.2016 */ var MetisMenu = function (_React$Component) { _inherits(MetisMenu, _React$Component); function MetisMenu(props) { _classCallCheck(this, MetisMenu); var _this = _possibleConstructorReturn(this, (MetisMenu.__proto__ || Object.getPrototypeOf(MetisMenu)).call(this, props)); _this.store = (0, _redux.createStore)(_reducers2.default, { emitters: { emitSelected: props.onSelected || function () {} } }); _this.LinkComponent = props.LinkComponent || _DefaultLink2.default; if (props.content) { _this.updateContent(props.content); _this.updateActiveLink(props); } else if (props.ajax) { _this.updateRemoteContent(props); } _this.classStore = { classMainWrapper: (0, _classnames2.default)({ metismenu: !props.noBuiltInClassNames }, props.className), classContainer: (0, _classnames2.default)({ 'metismenu-container': !props.noBuiltInClassNames }, props.classNameContainer), classContainerVisible: (0, _classnames2.default)({ visible: !props.noBuiltInClassNames }, props.classNameContainerVisible), classSubContainer: (0, _classnames2.default)({ 'metismenu-sub-container': !props.noBuiltInClassNames }, props.classNameSubContainer), classSubContainerVisible: (0, _classnames2.default)({ visible: !props.noBuiltInClassNames }, props.classNameSubContainerVisible), classItem: (0, _classnames2.default)({ 'metismenu-item': !props.noBuiltInClassNames }, props.classNameItem), classLink: (0, _classnames2.default)({ 'metismenu-link': !props.noBuiltInClassNames }, props.classNameLink), classItemActive: props.classNameItemActive, classItemHasActiveChild: props.classNameItemHasActiveChild, classItemHasVisibleChild: props.classNameItemHasVisibleChild, classItemHeader: props.classNameItemHeader || 'metismenu-item-header', classItemDivider: props.classNameItemDivider || 'metismenu-item-divider', classLinkActive: (0, _classnames2.default)({ active: !props.noBuiltInClassNames }, props.classNameLinkActive), classLinkHasActiveChild: (0, _classnames2.default)({ 'has-active-child': !props.noBuiltInClassNames }, props.classNameLinkHasActiveChild), classIcon: (0, _classnames2.default)({ 'metismenu-icon': !props.noBuiltInClassNames }, props.classNameIcon), classStateIcon: (0, _classnames2.default)({ 'metismenu-state-icon': !props.noBuiltInClassNames }, props.classNameStateIcon), iconNamePrefix: props.iconNamePrefix || 'fa fa-', iconNameStateHidden: props.iconNameStateHidden || 'caret-left', iconNameStateVisible: props.iconNameStateVisible || 'caret-left rotate-minus-90' }; return _this; } _createClass(MetisMenu, [{ key: 'getChildContext', value: function getChildContext() { return { classStore: this.classStore, LinkComponent: this.LinkComponent }; } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (this.props.content !== nextProps.content) { this.updateContent(nextProps.content); } if (this.props.ajax !== nextProps.ajax) { this.updateRemoteContent(nextProps); } else { this.updateActiveLink(nextProps); } } }, { key: 'changeActiveLinkId', value: function changeActiveLinkId(value) { this.store.dispatch((0, _content.changeActiveLinkId)(value)); } }, { key: 'changeActiveLinkTo', value: function changeActiveLinkTo(value) { this.store.dispatch((0, _content.changeActiveLinkTo)(value)); } }, { key: 'changeActiveLinkLabel', value: function changeActiveLinkLabel(value) { this.store.dispatch((0, _content.changeActiveLinkLabel)(value)); } }, { key: 'changeActiveLinkFromLocation', value: function changeActiveLinkFromLocation() { this.store.dispatch((0, _content.changeActiveLinkFromLocation)()); } }, { key: 'updateActiveLink', value: function updateActiveLink(props) { if (props.activeLinkId) this.changeActiveLinkId(props.activeLinkId);else if (props.activeLinkTo) this.changeActiveLinkTo(props.activeLinkTo);else if (props.activeLinkLabel) this.changeActiveLinkLabel(props.activeLinkLabel);else if (props.activeLinkFromLocation) this.changeActiveLinkFromLocation(); } }, { key: 'updateRemoteContent', value: function updateRemoteContent(props) { var _this2 = this; var ajax = new _simpleAjax2.default(props.ajax); ajax.on('success', function (event) { var content = void 0; var responseText = event.target.responseText; try { content = JSON.parse(responseText); } catch (e) { throw new Error('MetisMenu: Ajax response expected to be json, but got; ' + responseText); } _this2.updateContent(content); _this2.updateActiveLink(props); }); ajax.send(); } }, { key: 'updateContent', value: function updateContent(content) { this.store.dispatch((0, _content.updateContent)(content)); } }, { key: 'render', value: function render() { return _react2.default.createElement( _reactRedux.Provider, { store: this.store }, _react2.default.createElement( 'div', { className: this.classStore.classMainWrapper }, _react2.default.createElement(_Container2.default, null) ) ); } }]); return MetisMenu; }(_react2.default.Component); MetisMenu.propTypes = { content: _react.PropTypes.arrayOf(_react.PropTypes.object), ajax: _react.PropTypes.oneOfType([_react.PropTypes.object, _react.PropTypes.string]), LinkComponent: _react.PropTypes.oneOfType([_react.PropTypes.element, _react.PropTypes.func]), noBuiltInClassNames: _react.PropTypes.bool, className: _react.PropTypes.string, classNameContainer: _react.PropTypes.string, classNameContainerVisible: _react.PropTypes.string, classNameSubContainer: _react.PropTypes.string, classNameSubContainerVisible: _react.PropTypes.string, classNameItem: _react.PropTypes.string, classNameItemActive: _react.PropTypes.string, classNameItemHasActiveChild: _react.PropTypes.string, classNameItemHasVisibleChild: _react.PropTypes.string, classNameItemHeader: _react.PropTypes.string, classNameItemDivider: _react.PropTypes.string, classNameLink: _react.PropTypes.string, classNameLinkActive: _react.PropTypes.string, classNameLinkHasActiveChild: _react.PropTypes.string, classNameIcon: _react.PropTypes.string, classNameStateIcon: _react.PropTypes.string, iconNamePrefix: _react.PropTypes.string, iconNameStateHidden: _react.PropTypes.string, iconNameStateVisible: _react.PropTypes.string, /* activeLinkId: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), activeLinkTo: PropTypes.string, activeLinkLabel: PropTypes.string, activeLinkFromLocation: PropTypes.bool,*/ onSelected: _react.PropTypes.func }; MetisMenu.childContextTypes = { classStore: _react.PropTypes.object.isRequired, LinkComponent: _react.PropTypes.oneOfType([_react.PropTypes.element, _react.PropTypes.func]).isRequired }; exports.default = MetisMenu; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.connect = exports.Provider = undefined; var _Provider = __webpack_require__(4); var _Provider2 = _interopRequireDefault(_Provider); var _connect = __webpack_require__(8); var _connect2 = _interopRequireDefault(_connect); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } exports.Provider = _Provider2["default"]; exports.connect = _connect2["default"]; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.__esModule = true; exports["default"] = undefined; var _react = __webpack_require__(2); var _storeShape = __webpack_require__(6); var _storeShape2 = _interopRequireDefault(_storeShape); var _warning = __webpack_require__(7); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); }return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass))); }subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var didWarnAboutReceivingStore = false; function warnAboutReceivingStore() { if (didWarnAboutReceivingStore) { return; } didWarnAboutReceivingStore = true; (0, _warning2["default"])('<Provider> does not support changing `store` on the fly. ' + 'It is most likely that you see this error because you updated to ' + 'Redux 2.x and React Redux 2.x which no longer hot reload reducers ' + 'automatically. See https://github.com/reactjs/react-redux/releases/' + 'tag/v2.0.0 for the migration instructions.'); } var Provider = function (_Component) { _inherits(Provider, _Component); Provider.prototype.getChildContext = function getChildContext() { return { store: this.store }; }; function Provider(props, context) { _classCallCheck(this, Provider); var _this = _possibleConstructorReturn(this, _Component.call(this, props, context)); _this.store = props.store; return _this; } Provider.prototype.render = function render() { return _react.Children.only(this.props.children); }; return Provider; }(_react.Component); exports["default"] = Provider; if (process.env.NODE_ENV !== 'production') { Provider.prototype.componentWillReceiveProps = function (nextProps) { var store = this.store; var nextStore = nextProps.store; if (store !== nextStore) { warnAboutReceivingStore(); } }; } Provider.propTypes = { store: _storeShape2["default"].isRequired, children: _react.PropTypes.element.isRequired }; Provider.childContextTypes = { store: _storeShape2["default"].isRequired }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5))) /***/ }, /* 5 */ /***/ function(module, exports) { 'use strict'; // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout() { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } })(); function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/'; }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function () { return 0; }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(2); exports["default"] = _react.PropTypes.shape({ subscribe: _react.PropTypes.func.isRequired, dispatch: _react.PropTypes.func.isRequired, getState: _react.PropTypes.func.isRequired }); /***/ }, /* 7 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports["default"] = warning; /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; exports["default"] = connect; var _react = __webpack_require__(2); var _storeShape = __webpack_require__(6); var _storeShape2 = _interopRequireDefault(_storeShape); var _shallowEqual = __webpack_require__(9); var _shallowEqual2 = _interopRequireDefault(_shallowEqual); var _wrapActionCreators = __webpack_require__(10); var _wrapActionCreators2 = _interopRequireDefault(_wrapActionCreators); var _warning = __webpack_require__(7); var _warning2 = _interopRequireDefault(_warning); var _isPlainObject = __webpack_require__(13); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _hoistNonReactStatics = __webpack_require__(32); var _hoistNonReactStatics2 = _interopRequireDefault(_hoistNonReactStatics); var _invariant = __webpack_require__(33); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); }return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass))); }subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var defaultMapStateToProps = function defaultMapStateToProps(state) { return {}; }; // eslint-disable-line no-unused-vars var defaultMapDispatchToProps = function defaultMapDispatchToProps(dispatch) { return { dispatch: dispatch }; }; var defaultMergeProps = function defaultMergeProps(stateProps, dispatchProps, parentProps) { return _extends({}, parentProps, stateProps, dispatchProps); }; function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } var errorObject = { value: null }; function tryCatch(fn, ctx) { try { return fn.apply(ctx); } catch (e) { errorObject.value = e; return errorObject; } } // Helps track hot reloading. var nextVersion = 0; function connect(mapStateToProps, mapDispatchToProps, mergeProps) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var shouldSubscribe = Boolean(mapStateToProps); var mapState = mapStateToProps || defaultMapStateToProps; var mapDispatch = void 0; if (typeof mapDispatchToProps === 'function') { mapDispatch = mapDispatchToProps; } else if (!mapDispatchToProps) { mapDispatch = defaultMapDispatchToProps; } else { mapDispatch = (0, _wrapActionCreators2["default"])(mapDispatchToProps); } var finalMergeProps = mergeProps || defaultMergeProps; var _options$pure = options.pure, pure = _options$pure === undefined ? true : _options$pure, _options$withRef = options.withRef, withRef = _options$withRef === undefined ? false : _options$withRef; var checkMergedEquals = pure && finalMergeProps !== defaultMergeProps; // Helps track hot reloading. var version = nextVersion++; return function wrapWithConnect(WrappedComponent) { var connectDisplayName = 'Connect(' + getDisplayName(WrappedComponent) + ')'; function checkStateShape(props, methodName) { if (!(0, _isPlainObject2["default"])(props)) { (0, _warning2["default"])(methodName + '() in ' + connectDisplayName + ' must return a plain object. ' + ('Instead received ' + props + '.')); } } function computeMergedProps(stateProps, dispatchProps, parentProps) { var mergedProps = finalMergeProps(stateProps, dispatchProps, parentProps); if (process.env.NODE_ENV !== 'production') { checkStateShape(mergedProps, 'mergeProps'); } return mergedProps; } var Connect = function (_Component) { _inherits(Connect, _Component); Connect.prototype.shouldComponentUpdate = function shouldComponentUpdate() { return !pure || this.haveOwnPropsChanged || this.hasStoreStateChanged; }; function Connect(props, context) { _classCallCheck(this, Connect); var _this = _possibleConstructorReturn(this, _Component.call(this, props, context)); _this.version = version; _this.store = props.store || context.store; (0, _invariant2["default"])(_this.store, 'Could not find "store" in either the context or ' + ('props of "' + connectDisplayName + '". ') + 'Either wrap the root component in a <Provider>, ' + ('or explicitly pass "store" as a prop to "' + connectDisplayName + '".')); var storeState = _this.store.getState(); _this.state = { storeState: storeState }; _this.clearCache(); return _this; } Connect.prototype.computeStateProps = function computeStateProps(store, props) { if (!this.finalMapStateToProps) { return this.configureFinalMapState(store, props); } var state = store.getState(); var stateProps = this.doStatePropsDependOnOwnProps ? this.finalMapStateToProps(state, props) : this.finalMapStateToProps(state); if (process.env.NODE_ENV !== 'production') { checkStateShape(stateProps, 'mapStateToProps'); } return stateProps; }; Connect.prototype.configureFinalMapState = function configureFinalMapState(store, props) { var mappedState = mapState(store.getState(), props); var isFactory = typeof mappedState === 'function'; this.finalMapStateToProps = isFactory ? mappedState : mapState; this.doStatePropsDependOnOwnProps = this.finalMapStateToProps.length !== 1; if (isFactory) { return this.computeStateProps(store, props); } if (process.env.NODE_ENV !== 'production') { checkStateShape(mappedState, 'mapStateToProps'); } return mappedState; }; Connect.prototype.computeDispatchProps = function computeDispatchProps(store, props) { if (!this.finalMapDispatchToProps) { return this.configureFinalMapDispatch(store, props); } var dispatch = store.dispatch; var dispatchProps = this.doDispatchPropsDependOnOwnProps ? this.finalMapDispatchToProps(dispatch, props) : this.finalMapDispatchToProps(dispatch); if (process.env.NODE_ENV !== 'production') { checkStateShape(dispatchProps, 'mapDispatchToProps'); } return dispatchProps; }; Connect.prototype.configureFinalMapDispatch = function configureFinalMapDispatch(store, props) { var mappedDispatch = mapDispatch(store.dispatch, props); var isFactory = typeof mappedDispatch === 'function'; this.finalMapDispatchToProps = isFactory ? mappedDispatch : mapDispatch; this.doDispatchPropsDependOnOwnProps = this.finalMapDispatchToProps.length !== 1; if (isFactory) { return this.computeDispatchProps(store, props); } if (process.env.NODE_ENV !== 'production') { checkStateShape(mappedDispatch, 'mapDispatchToProps'); } return mappedDispatch; }; Connect.prototype.updateStatePropsIfNeeded = function updateStatePropsIfNeeded() { var nextStateProps = this.computeStateProps(this.store, this.props); if (this.stateProps && (0, _shallowEqual2["default"])(nextStateProps, this.stateProps)) { return false; } this.stateProps = nextStateProps; return true; }; Connect.prototype.updateDispatchPropsIfNeeded = function updateDispatchPropsIfNeeded() { var nextDispatchProps = this.computeDispatchProps(this.store, this.props); if (this.dispatchProps && (0, _shallowEqual2["default"])(nextDispatchProps, this.dispatchProps)) { return false; } this.dispatchProps = nextDispatchProps; return true; }; Connect.prototype.updateMergedPropsIfNeeded = function updateMergedPropsIfNeeded() { var nextMergedProps = computeMergedProps(this.stateProps, this.dispatchProps, this.props); if (this.mergedProps && checkMergedEquals && (0, _shallowEqual2["default"])(nextMergedProps, this.mergedProps)) { return false; } this.mergedProps = nextMergedProps; return true; }; Connect.prototype.isSubscribed = function isSubscribed() { return typeof this.unsubscribe === 'function'; }; Connect.prototype.trySubscribe = function trySubscribe() { if (shouldSubscribe && !this.unsubscribe) { this.unsubscribe = this.store.subscribe(this.handleChange.bind(this)); this.handleChange(); } }; Connect.prototype.tryUnsubscribe = function tryUnsubscribe() { if (this.unsubscribe) { this.unsubscribe(); this.unsubscribe = null; } }; Connect.prototype.componentDidMount = function componentDidMount() { this.trySubscribe(); }; Connect.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (!pure || !(0, _shallowEqual2["default"])(nextProps, this.props)) { this.haveOwnPropsChanged = true; } }; Connect.prototype.componentWillUnmount = function componentWillUnmount() { this.tryUnsubscribe(); this.clearCache(); }; Connect.prototype.clearCache = function clearCache() { this.dispatchProps = null; this.stateProps = null; this.mergedProps = null; this.haveOwnPropsChanged = true; this.hasStoreStateChanged = true; this.haveStatePropsBeenPrecalculated = false; this.statePropsPrecalculationError = null; this.renderedElement = null; this.finalMapDispatchToProps = null; this.finalMapStateToProps = null; }; Connect.prototype.handleChange = function handleChange() { if (!this.unsubscribe) { return; } var storeState = this.store.getState(); var prevStoreState = this.state.storeState; if (pure && prevStoreState === storeState) { return; } if (pure && !this.doStatePropsDependOnOwnProps) { var haveStatePropsChanged = tryCatch(this.updateStatePropsIfNeeded, this); if (!haveStatePropsChanged) { return; } if (haveStatePropsChanged === errorObject) { this.statePropsPrecalculationError = errorObject.value; } this.haveStatePropsBeenPrecalculated = true; } this.hasStoreStateChanged = true; this.setState({ storeState: storeState }); }; Connect.prototype.getWrappedInstance = function getWrappedInstance() { (0, _invariant2["default"])(withRef, 'To access the wrapped instance, you need to specify ' + '{ withRef: true } as the fourth argument of the connect() call.'); return this.refs.wrappedInstance; }; Connect.prototype.render = function render() { var haveOwnPropsChanged = this.haveOwnPropsChanged, hasStoreStateChanged = this.hasStoreStateChanged, haveStatePropsBeenPrecalculated = this.haveStatePropsBeenPrecalculated, statePropsPrecalculationError = this.statePropsPrecalculationError, renderedElement = this.renderedElement; this.haveOwnPropsChanged = false; this.hasStoreStateChanged = false; this.haveStatePropsBeenPrecalculated = false; this.statePropsPrecalculationError = null; if (statePropsPrecalculationError) { throw statePropsPrecalculationError; } var shouldUpdateStateProps = true; var shouldUpdateDispatchProps = true; if (pure && renderedElement) { shouldUpdateStateProps = hasStoreStateChanged || haveOwnPropsChanged && this.doStatePropsDependOnOwnProps; shouldUpdateDispatchProps = haveOwnPropsChanged && this.doDispatchPropsDependOnOwnProps; } var haveStatePropsChanged = false; var haveDispatchPropsChanged = false; if (haveStatePropsBeenPrecalculated) { haveStatePropsChanged = true; } else if (shouldUpdateStateProps) { haveStatePropsChanged = this.updateStatePropsIfNeeded(); } if (shouldUpdateDispatchProps) { haveDispatchPropsChanged = this.updateDispatchPropsIfNeeded(); } var haveMergedPropsChanged = true; if (haveStatePropsChanged || haveDispatchPropsChanged || haveOwnPropsChanged) { haveMergedPropsChanged = this.updateMergedPropsIfNeeded(); } else { haveMergedPropsChanged = false; } if (!haveMergedPropsChanged && renderedElement) { return renderedElement; } if (withRef) { this.renderedElement = (0, _react.createElement)(WrappedComponent, _extends({}, this.mergedProps, { ref: 'wrappedInstance' })); } else { this.renderedElement = (0, _react.createElement)(WrappedComponent, this.mergedProps); } return this.renderedElement; }; return Connect; }(_react.Component); Connect.displayName = connectDisplayName; Connect.WrappedComponent = WrappedComponent; Connect.contextTypes = { store: _storeShape2["default"] }; Connect.propTypes = { store: _storeShape2["default"] }; if (process.env.NODE_ENV !== 'production') { Connect.prototype.componentWillUpdate = function componentWillUpdate() { if (this.version === version) { return; } // We are hot reloading! this.version = version; this.trySubscribe(); this.clearCache(); }; } return (0, _hoistNonReactStatics2["default"])(Connect, WrappedComponent); }; } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5))) /***/ }, /* 9 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = shallowEqual; function shallowEqual(objA, objB) { if (objA === objB) { return true; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports["default"] = wrapActionCreators; var _redux = __webpack_require__(11); function wrapActionCreators(actionCreators) { return function (dispatch) { return (0, _redux.bindActionCreators)(actionCreators, dispatch); }; } /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; exports.__esModule = true; exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined; var _createStore = __webpack_require__(12); var _createStore2 = _interopRequireDefault(_createStore); var _combineReducers = __webpack_require__(27); var _combineReducers2 = _interopRequireDefault(_combineReducers); var _bindActionCreators = __webpack_require__(29); var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators); var _applyMiddleware = __webpack_require__(30); var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware); var _compose = __webpack_require__(31); var _compose2 = _interopRequireDefault(_compose); var _warning = __webpack_require__(28); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if (process.env.NODE_ENV !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') { (0, _warning2['default'])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.'); } exports.createStore = _createStore2['default']; exports.combineReducers = _combineReducers2['default']; exports.bindActionCreators = _bindActionCreators2['default']; exports.applyMiddleware = _applyMiddleware2['default']; exports.compose = _compose2['default']; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5))) /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.__esModule = true; exports.ActionTypes = undefined; exports['default'] = createStore; var _isPlainObject = __webpack_require__(13); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _symbolObservable = __webpack_require__(23); var _symbolObservable2 = _interopRequireDefault(_symbolObservable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var ActionTypes = exports.ActionTypes = { INIT: '@@redux/INIT' }; /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [preloadedState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} enhancer The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ function createStore(reducer, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = preloadedState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.'); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!(0, _isPlainObject2['default'])(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { listeners[i](); } return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/zenparsing/es-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if ((typeof observer === 'undefined' ? 'undefined' : _typeof(observer)) !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[_symbolObservable2['default']] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[_symbolObservable2['default']] = observable, _ref2; } /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var baseGetTag = __webpack_require__(14), getPrototype = __webpack_require__(20), isObjectLike = __webpack_require__(22); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } module.exports = isPlainObject; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _Symbol = __webpack_require__(15), getRawTag = __webpack_require__(18), objectToString = __webpack_require__(19); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var root = __webpack_require__(16); /** Built-in value references. */ var _Symbol = root.Symbol; module.exports = _Symbol; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var freeGlobal = __webpack_require__(17); /** Detect free variable `self`. */ var freeSelf = (typeof self === 'undefined' ? 'undefined' : _typeof(self)) == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; /***/ }, /* 17 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** Detect free variable `global` from Node.js. */ var freeGlobal = (typeof global === 'undefined' ? 'undefined' : _typeof(global)) == 'object' && global && global.Object === Object && global; module.exports = freeGlobal; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _Symbol = __webpack_require__(15); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag; /***/ }, /* 19 */ /***/ function(module, exports) { "use strict"; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } module.exports = objectToString; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var overArg = __webpack_require__(21); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }, /* 21 */ /***/ function(module, exports) { "use strict"; /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function (arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }, /* 22 */ /***/ function(module, exports) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) == 'object'; } module.exports = isObjectLike; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(24); /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, module) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ponyfill = __webpack_require__(26); var _ponyfill2 = _interopRequireDefault(_ponyfill); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var root; /* global window */ if (typeof self !== 'undefined') { root = self; } else if (typeof window !== 'undefined') { root = window; } else if (typeof global !== 'undefined') { root = global; } else if (true) { root = module; } else { root = Function('return this')(); } var result = (0, _ponyfill2['default'])(root); exports['default'] = result; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(25)(module))) /***/ }, /* 25 */ /***/ function(module, exports) { "use strict"; module.exports = function (module) { if (!module.webpackPolyfill) { module.deprecate = function () {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; }; /***/ }, /* 26 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = symbolObservablePonyfill; function symbolObservablePonyfill(root) { var result; var _Symbol = root.Symbol; if (typeof _Symbol === 'function') { if (_Symbol.observable) { result = _Symbol.observable; } else { result = _Symbol('observable'); _Symbol.observable = result; } } else { result = '@@observable'; } return result; }; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; exports.__esModule = true; exports['default'] = combineReducers; var _createStore = __webpack_require__(12); var _isPlainObject = __webpack_require__(13); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _warning = __webpack_require__(28); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.'; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!(0, _isPlainObject2['default'])(inputState)) { return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]; }); unexpectedKeys.forEach(function (key) { unexpectedKeyCache[key] = true; }); if (unexpectedKeys.length > 0) { return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.'); } } function assertReducerSanity(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.'); } var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); if (typeof reducer(undefined, { type: type }) === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.'); } }); } /** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (process.env.NODE_ENV !== 'production') { if (typeof reducers[key] === 'undefined') { (0, _warning2['default'])('No reducer provided for key "' + key + '"'); } } if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); if (process.env.NODE_ENV !== 'production') { var unexpectedKeyCache = {}; } var sanityError; try { assertReducerSanity(finalReducers); } catch (e) { sanityError = e; } return function combination() { var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var action = arguments[1]; if (sanityError) { throw sanityError; } if (process.env.NODE_ENV !== 'production') { var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache); if (warningMessage) { (0, _warning2['default'])(warningMessage); } } var hasChanged = false; var nextState = {}; for (var i = 0; i < finalReducerKeys.length; i++) { var key = finalReducerKeys[i]; var reducer = finalReducers[key]; var previousStateForKey = state[key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(key, action); throw new Error(errorMessage); } nextState[key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5))) /***/ }, /* 28 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = warning; /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } /***/ }, /* 29 */ /***/ function(module, exports) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.__esModule = true; exports['default'] = bindActionCreators; function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(undefined, arguments)); }; } /** * Turns an object whose values are action creators, into an object with the * same keys, but with every function wrapped into a `dispatch` call so they * may be invoked directly. This is just a convenience method, as you can call * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. * * For convenience, you can also pass a single function as the first argument, * and get a function in return. * * @param {Function|Object} actionCreators An object whose values are action * creator functions. One handy way to obtain it is to use ES6 `import * as` * syntax. You may also pass a single function. * * @param {Function} dispatch The `dispatch` function available on your Redux * store. * * @returns {Function|Object} The object mimicking the original object, but with * every action creator wrapped into the `dispatch` call. If you passed a * function as `actionCreators`, the return value will also be a single * function. */ function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch); } if ((typeof actionCreators === 'undefined' ? 'undefined' : _typeof(actionCreators)) !== 'object' || actionCreators === null) { throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators === 'undefined' ? 'undefined' : _typeof(actionCreators)) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'); } var keys = Object.keys(actionCreators); var boundActionCreators = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var actionCreator = actionCreators[key]; if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; exports['default'] = applyMiddleware; var _compose = __webpack_require__(31); var _compose2 = _interopRequireDefault(_compose); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function (reducer, preloadedState, enhancer) { var store = createStore(reducer, preloadedState, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = _compose2['default'].apply(undefined, chain)(store.dispatch); return _extends({}, store, { dispatch: _dispatch }); }; }; } /***/ }, /* 31 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = compose; /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } var last = funcs[funcs.length - 1]; var rest = funcs.slice(0, -1); return function () { return rest.reduceRight(function (composed, f) { return f(composed); }, last.apply(undefined, arguments)); }; } /***/ }, /* 32 */ /***/ function(module, exports) { /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ 'use strict'; var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, arguments: true, arity: true }; var isGetOwnPropertySymbolsAvailable = typeof Object.getOwnPropertySymbols === 'function'; module.exports = function hoistNonReactStatics(targetComponent, sourceComponent, customStatics) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components var keys = Object.getOwnPropertyNames(sourceComponent); /* istanbul ignore else */ if (isGetOwnPropertySymbolsAvailable) { keys = keys.concat(Object.getOwnPropertySymbols(sourceComponent)); } for (var i = 0; i < keys.length; ++i) { if (!REACT_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]] && (!customStatics || !customStatics[keys[i]])) { try { targetComponent[keys[i]] = sourceComponent[keys[i]]; } catch (error) {} } } } return targetComponent; }; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function invariant(condition, format, a, b, c, d, e, f) { if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5))) /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames() { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg === 'undefined' ? 'undefined' : _typeof(arg); if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if ("function" === 'function' && _typeof(__webpack_require__(35)) === 'object' && __webpack_require__(35)) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } })(); /***/ }, /* 35 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__; /* WEBPACK VAR INJECTION */}.call(exports, {})) /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var EventEmitter = __webpack_require__(37).EventEmitter, queryString = __webpack_require__(38); function tryParseJson(data) { try { return JSON.parse(data); } catch (error) { return error; } } function timeout() { this.request.abort(); this.emit('timeout'); } function Ajax(settings) { var queryStringData, ajax = this; if (typeof settings === 'string') { settings = { url: settings }; } if ((typeof settings === 'undefined' ? 'undefined' : _typeof(settings)) !== 'object') { settings = {}; } ajax.settings = settings; ajax.request = new XMLHttpRequest(); ajax.settings.method = ajax.settings.method || 'get'; if (ajax.settings.cors && !'withCredentials' in ajax.request) { if (typeof XDomainRequest !== 'undefined') { // XDomainRequest only exists in IE, and is IE's way of making CORS requests. ajax.request = new XDomainRequest(); } else { // Otherwise, CORS is not supported by the browser. ajax.emit('error', new Error('Cors is not supported by this browser')); } } if (ajax.settings.cache === false) { ajax.settings.data = ajax.settings.data || {}; ajax.settings.data._ = new Date().getTime(); } if (ajax.settings.method.toLowerCase() === 'get' && _typeof(ajax.settings.data) === 'object') { var urlParts = ajax.settings.url.split('?'); queryStringData = queryString.parse(urlParts[1]); for (var key in ajax.settings.data) { queryStringData[key] = ajax.settings.data[key]; } var parsedQueryStringData = queryString.stringify(queryStringData); ajax.settings.url = urlParts[0] + (parsedQueryStringData ? '?' + parsedQueryStringData : ''); ajax.settings.data = null; } ajax.request.addEventListener('progress', function (event) { ajax.emit('progress', event); }, false); ajax.request.addEventListener('load', function (event) { var data = event.target.responseText; if (ajax.settings.dataType && ajax.settings.dataType.toLowerCase() === 'json') { if (data === '') { data = undefined; } else { data = tryParseJson(data); if (data instanceof Error) { ajax.emit('error', event, data); return; } } } if (event.target.status >= 400) { ajax.emit('error', event, data); } else { ajax.emit('success', event, data); } }, false); ajax.request.addEventListener('error', function (event) { ajax.emit('error', event); }, false); ajax.request.addEventListener('abort', function (event) { ajax.emit('error', event, new Error('Connection Aborted')); ajax.emit('abort', event); }, false); ajax.request.addEventListener('loadend', function (event) { clearTimeout(ajax._requestTimeout); ajax.emit('complete', event); }, false); ajax.request.open(ajax.settings.method || 'get', ajax.settings.url, true); if (ajax.settings.cors && 'withCredentials' in ajax.request) { ajax.request.withCredentials = !!settings.withCredentials; } // Set default headers if (ajax.settings.contentType !== false) { ajax.request.setRequestHeader('Content-Type', ajax.settings.contentType || 'application/json; charset=utf-8'); } if (ajax.settings.requestedWith !== false) { ajax.request.setRequestHeader('X-Requested-With', ajax.settings.requestedWith || 'XMLHttpRequest'); } if (ajax.settings.auth) { ajax.request.setRequestHeader('Authorization', ajax.settings.auth); } // Set custom headers for (var headerKey in ajax.settings.headers) { ajax.request.setRequestHeader(headerKey, ajax.settings.headers[headerKey]); } if (ajax.settings.processData !== false && ajax.settings.dataType === 'json') { ajax.settings.data = JSON.stringify(ajax.settings.data); } } Ajax.prototype = Object.create(EventEmitter.prototype); Ajax.prototype.send = function () { var ajax = this; ajax._requestTimeout = setTimeout(function () { timeout.apply(ajax, []); }, ajax.settings.timeout || 120000); ajax.request.send(ajax.settings.data && ajax.settings.data); }; module.exports = Ajax; /***/ }, /* 37 */ /***/ function(module, exports) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function (n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function (type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || isObject(this._events.error) && !this._events.error.length) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) { listeners[i].apply(this, args); } } return true; }; EventEmitter.prototype.addListener = function (type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener;else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener);else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function (type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function (type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || isFunction(list.listener) && list.listener === listener) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || list[i].listener && list[i].listener === listener) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function (type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {};else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) { this.removeListener(type, listeners[listeners.length - 1]); } } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function (type) { var ret; if (!this._events || !this._events[type]) ret = [];else if (isFunction(this._events[type])) ret = [this._events[type]];else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function (type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1;else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function (emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; /*! query-string Parse and stringify URL query strings https://github.com/sindresorhus/query-string by Sindre Sorhus MIT License */ (function () { 'use strict'; var queryString = {}; queryString.parse = function (str) { if (typeof str !== 'string') { return {}; } str = str.trim().replace(/^(\?|#)/, ''); if (!str) { return {}; } return str.trim().split('&').reduce(function (ret, param) { var parts = param.replace(/\+/g, ' ').split('='); var key = parts[0]; var val = parts[1]; key = decodeURIComponent(key); // missing `=` should be `null`: // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters val = val === undefined ? null : decodeURIComponent(val); if (!ret.hasOwnProperty(key)) { ret[key] = val; } else if (Array.isArray(ret[key])) { ret[key].push(val); } else { ret[key] = [ret[key], val]; } return ret; }, {}); }; queryString.stringify = function (obj) { return obj ? Object.keys(obj).map(function (key) { var val = obj[key]; if (Array.isArray(val)) { return val.map(function (val2) { return encodeURIComponent(key) + '=' + encodeURIComponent(val2); }).join('&'); } return encodeURIComponent(key) + '=' + encodeURIComponent(val); }).join('&') : ''; }; if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function () { return queryString; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module !== 'undefined' && module.exports) { module.exports = queryString; } else { self.queryString = queryString; } })(); /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _reactRedux = __webpack_require__(3); var _Container = __webpack_require__(40); var _Container2 = _interopRequireDefault(_Container); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * src/containers/Container.jsx * Author: H.Alper Tuna <halpertuna@gmail.com> * Date: 16.09.2016 */ var mapStateToProps = function mapStateToProps(_ref, ownProps) { var content = _ref.content; return { items: content.filter(function (item) { return item.parentId === ownProps.itemId; }) }; }; exports.default = (0, _reactRedux.connect)(mapStateToProps)(_Container2.default); /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /** * src/components/Container.jsx * Author: H.Alper Tuna <halpertuna@gmail.com> * Date: 16.09.2016 */ var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(34); var _classnames2 = _interopRequireDefault(_classnames); var _Item = __webpack_require__(41); var _Item2 = _interopRequireDefault(_Item); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Container = function Container(_ref, _ref2) { var items = _ref.items, visible = _ref.visible; var classStore = _ref2.classStore; return _react2.default.createElement( 'ul', { className: (0, _classnames2.default)(classStore.classContainer, visible && classStore.classContainerVisible) }, items.map(function (item, i) { return _react2.default.createElement(_Item2.default, _extends({ key: i }, item)); }) ); }; Container.propTypes = { items: _react.PropTypes.arrayOf(_react.PropTypes.object).isRequired, visible: _react.PropTypes.bool }; Container.contextTypes = { classStore: _react.PropTypes.object.isRequired }; exports.default = Container; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _reactRedux = __webpack_require__(3); var _content = __webpack_require__(42); var _emitters = __webpack_require__(43); var _Item = __webpack_require__(44); var _Item2 = _interopRequireDefault(_Item); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * src/containers/Item.js * Author: H.Alper Tuna <halpertuna@gmail.com> * Date: 16.09.2016 */ var mapDispatchToProps = function mapDispatchToProps(dispatch, ownProps) { return { toggleSubMenu: function toggleSubMenu(e) { if (!ownProps.hasSubMenu) return; e.preventDefault(); dispatch((0, _content.changeSubMenuVisibility)(ownProps.id, ownProps.trace, !ownProps.subMenuVisibility)); }, activateMe: function activateMe(e) { dispatch((0, _emitters.emitSelected)(e)); if (!e || !e.isDefaultPrevented || !e.isDefaultPrevented()) { dispatch((0, _content.changeActiveLinkId)(ownProps.id)); } } }; }; exports.default = (0, _reactRedux.connect)(null, mapDispatchToProps)(_Item2.default); /***/ }, /* 42 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * @file actions/content.js * @author H.Alper Tuna <halpertuna@gmail.com> * Date: 16.12.2016 */ var updateContent = exports.updateContent = function updateContent(content) { return { type: 'UPDATE_CONTENT', content: content }; }; var changeSubMenuVisibility = exports.changeSubMenuVisibility = function changeSubMenuVisibility(id, trace, subMenuVisibility) { return { type: 'CHANGE_SUBMENU_VISIBILITY', id: id, trace: trace, subMenuVisibility: subMenuVisibility }; }; var changeActiveLinkId = exports.changeActiveLinkId = function changeActiveLinkId(value) { return { type: 'CHANGE_ACTIVE_LINK', propName: 'id', value: value }; }; var changeActiveLinkTo = exports.changeActiveLinkTo = function changeActiveLinkTo(value) { return { type: 'CHANGE_ACTIVE_LINK', propName: 'to', value: value }; }; var changeActiveLinkLabel = exports.changeActiveLinkLabel = function changeActiveLinkLabel(value) { return { type: 'CHANGE_ACTIVE_LINK', propName: 'label', value: value }; }; var changeActiveLinkFromLocation = exports.changeActiveLinkFromLocation = function changeActiveLinkFromLocation() { return { type: 'CHANGE_ACTIVE_LINK_FROM_LOCATION' }; }; /***/ }, /* 43 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * @file actions/emitters.js * @author H.Alper Tuna <halpertuna@gmail.com> * Date: 16.12.2016 */ var emitSelected = exports.emitSelected = function emitSelected(e) { return { type: 'EMIT_SELECTED', event: e }; }; exports.default = true; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(34); var _classnames2 = _interopRequireDefault(_classnames); var _SubContainer = __webpack_require__(45); var _SubContainer2 = _interopRequireDefault(_SubContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Item = function Item(_ref, _ref2) { var id = _ref.id, icon = _ref.icon, label = _ref.label, to = _ref.to, itemType = _ref.itemType, externalLink = _ref.externalLink, hasSubMenu = _ref.hasSubMenu, active = _ref.active, hasActiveChild = _ref.hasActiveChild, subMenuVisibility = _ref.subMenuVisibility, toggleSubMenu = _ref.toggleSubMenu, activateMe = _ref.activateMe; var classStore = _ref2.classStore, LinkComponent = _ref2.LinkComponent; if (itemType === 'header') { return _react2.default.createElement( 'li', { className: (0, _classnames2.default)(classStore.classItemHeader, active && classStore.classItemActive) }, _react2.default.createElement( 'span', null, label ) ); } if (itemType === 'divider') { return _react2.default.createElement('li', { className: classStore.classItemDivider }); } if (itemType === 'menu' || itemType == null) { return _react2.default.createElement( 'li', { className: (0, _classnames2.default)(classStore.classItem, active && classStore.classItemActive, hasActiveChild && classStore.classItemHasActiveChild, hasSubMenu && subMenuVisibility && classStore.classItemHasVisibleChild) }, _react2.default.createElement( LinkComponent, { className: classStore.classLink, classNameActive: classStore.classLinkActive, classNameHasActiveChild: classStore.classLinkHasActiveChild, active: active, hasActiveChild: hasActiveChild, id: id, to: to, label: label, externalLink: externalLink, hasSubMenu: hasSubMenu, toggleSubMenu: toggleSubMenu, activateMe: activateMe }, _react2.default.createElement('i', { className: (0, _classnames2.default)(classStore.classIcon, classStore.iconNamePrefix + icon) }), label, hasSubMenu && _react2.default.createElement('i', { className: (0, _classnames2.default)(classStore.classStateIcon, classStore.iconNamePrefix + (subMenuVisibility ? classStore.iconNameStateVisible : classStore.iconNameStateHidden)) }) ), hasSubMenu && _react2.default.createElement(_SubContainer2.default, { itemId: id, visible: subMenuVisibility }) ); } }; /** * src/components/Container.jsx * Author: H.Alper Tuna <halpertuna@gmail.com> * Date: 16.09.2016 */ Item.propTypes = { id: _react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.string]).isRequired, icon: _react.PropTypes.string, label: _react.PropTypes.oneOfType([_react.PropTypes.element, _react.PropTypes.array, _react.PropTypes.string]), itemType: _react.PropTypes.string, to: _react.PropTypes.string, externalLink: _react.PropTypes.bool, hasSubMenu: _react.PropTypes.bool.isRequired, active: _react.PropTypes.bool.isRequired, hasActiveChild: _react.PropTypes.bool.isRequired, subMenuVisibility: _react.PropTypes.bool.isRequired, toggleSubMenu: _react.PropTypes.func, activateMe: _react.PropTypes.func.isRequired }; Item.contextTypes = { classStore: _react.PropTypes.object.isRequired, LinkComponent: _react.PropTypes.oneOfType([_react.PropTypes.element, _react.PropTypes.func]).isRequired }; exports.default = Item; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _reactRedux = __webpack_require__(3); var _SubContainer = __webpack_require__(46); var _SubContainer2 = _interopRequireDefault(_SubContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * src/containers/Container.jsx * Author: H.Alper Tuna <halpertuna@gmail.com> * Date: 16.09.2016 */ var mapStateToProps = function mapStateToProps(_ref, ownProps) { var content = _ref.content; return { items: content.filter(function (item) { return item.parentId === ownProps.itemId; }) }; }; exports.default = (0, _reactRedux.connect)(mapStateToProps)(_SubContainer2.default); /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(34); var _classnames2 = _interopRequireDefault(_classnames); var _Item = __webpack_require__(41); var _Item2 = _interopRequireDefault(_Item); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var SubContainer = function SubContainer(_ref, _ref2) { var items = _ref.items, visible = _ref.visible; var classStore = _ref2.classStore; return _react2.default.createElement( 'div', { className: (0, _classnames2.default)(classStore.classSubContainer, visible && classStore.classSubContainerVisible) }, _react2.default.createElement( 'ul', { className: (0, _classnames2.default)(classStore.classContainer, visible && classStore.classContainerVisible) }, items.map(function (item, i) { return _react2.default.createElement(_Item2.default, _extends({ key: i }, item)); }) ) ); }; SubContainer.propTypes = { items: _react.PropTypes.arrayOf(_react.PropTypes.object).isRequired, visible: _react.PropTypes.bool }; SubContainer.contextTypes = { classStore: _react.PropTypes.object.isRequired }; exports.default = SubContainer; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(34); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * src/components/DefaultLink.jsx * Author: H.Alper Tuna <halpertuna@gmail.com> * Date: 17.09.2016 */ var DefaultLink = function DefaultLink(_ref) { var className = _ref.className, classNameActive = _ref.classNameActive, classNameHasActiveChild = _ref.classNameHasActiveChild, active = _ref.active, hasActiveChild = _ref.hasActiveChild, to = _ref.to, externalLink = _ref.externalLink, hasSubMenu = _ref.hasSubMenu, toggleSubMenu = _ref.toggleSubMenu, activateMe = _ref.activateMe, children = _ref.children; return _react2.default.createElement( 'a', { className: (0, _classnames2.default)(className, active && classNameActive, hasActiveChild && classNameHasActiveChild), href: to, onClick: hasSubMenu ? toggleSubMenu : activateMe, target: externalLink ? '_blank' : undefined }, children ); }; DefaultLink.propTypes = { className: _react.PropTypes.string.isRequired, classNameActive: _react.PropTypes.string.isRequired, classNameHasActiveChild: _react.PropTypes.string.isRequired, active: _react.PropTypes.bool.isRequired, hasActiveChild: _react.PropTypes.bool.isRequired, to: _react.PropTypes.string.isRequired, externalLink: _react.PropTypes.bool, hasSubMenu: _react.PropTypes.bool.isRequired, toggleSubMenu: _react.PropTypes.func, activateMe: _react.PropTypes.func.isRequired, children: _react.PropTypes.oneOfType([_react.PropTypes.element, _react.PropTypes.array]).isRequired }; exports.default = DefaultLink; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _redux = __webpack_require__(11); var _content = __webpack_require__(49); var _content2 = _interopRequireDefault(_content); var _emitters = __webpack_require__(51); var _emitters2 = _interopRequireDefault(_emitters); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = (0, _redux.combineReducers)({ content: _content2.default, emitters: _emitters2.default }); /** * src/reducers/index.js * Author: H.Alper Tuna <halpertuna@gmail.com> * Date: 16.09.2016 */ /* eslint-env browser */ /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** * @file reducers/content.js * @author H.Alper Tuna <halpertuna@gmail.com> * Date: 16.12.2016 */ /* eslint-env browser */ var _content = __webpack_require__(42); var _flattenContent = __webpack_require__(50); var _flattenContent2 = _interopRequireDefault(_flattenContent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var item = function item(state, action) { switch (action.type) { case 'CHANGE_SUBMENU_VISIBILITY': { return Object.assign({}, state, { subMenuVisibility: state.id === action.id ? action.subMenuVisibility : action.trace.indexOf(state.id) !== -1 }); } case 'CHANGE_ACTIVE_LINK_FROM_LOCATION': case 'CHANGE_ACTIVE_LINK': { return Object.assign({}, state, { active: state.id === action.id, hasActiveChild: action.trace.indexOf(state.id) !== -1 }); } default: { return state; } } }; var findItem = function findItem(content, value, prop) { return content.find(function (i) { return i[prop] === value; }); }; var content = function content() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var action = arguments[1]; switch (action.type) { case 'UPDATE_CONTENT': { return (0, _flattenContent2.default)(action.content); } case 'CHANGE_SUBMENU_VISIBILITY': { return state.map(function (i) { return item(i, action); }); } case 'CHANGE_ACTIVE_LINK_FROM_LOCATION': case 'CHANGE_ACTIVE_LINK': { var _ret = function () { var activeItem = void 0; if (action.type === 'CHANGE_ACTIVE_LINK_FROM_LOCATION') { (function () { var locationSets = [window.location.pathname + window.location.search, // /path?search window.location.hash, // #hash window.location.pathname + window.location.search + window.location.hash]; activeItem = state.find(function (i) { return locationSets.indexOf(i.to) !== -1; }); })(); } else { activeItem = findItem(state, action.value, action.propName); } // If metismenu user tries to activate non-exist item if (!activeItem) return { v: state }; var _activeItem = activeItem, id = _activeItem.id, parentId = _activeItem.parentId, trace = _activeItem.trace; var stage = state.map(function (i) { return item(i, Object.assign({ id: id, trace: trace }, action)); }); // Trace also keeps parentId nonetheless it doesn't matter return { v: content(stage, (0, _content.changeSubMenuVisibility)(parentId, trace, true)) }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } default: { return state; } } }; exports.default = content; /***/ }, /* 50 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } /** * src/reducers/flattenContent.js * Author: H.Alper Tuna <halpertuna@gmail.com> * Date: 17.09.2016 */ /* eslint no-param-reassign: ["error", { "props": false }] */ var uid = void 0; var flattenLevel = function flattenLevel(content, parentId) { var flatContent = []; content.forEach(function (item) { var id = item.id || uid; uid += 1; flatContent.push({ id: id, parentId: item.parentId || parentId, icon: item.icon, label: item.label, to: item.to, itemType: item.itemType, externalLink: item.externalLink, active: false, hasActiveChild: false, subMenuVisibility: false }); if (typeof item.content !== 'undefined') { flatContent = [].concat(_toConsumableArray(flatContent), _toConsumableArray(flattenLevel(item.content, id))); } }); return flatContent; }; var trace = void 0; var mapTrace = function mapTrace(content, parentId) { var subItems = content.filter(function (item) { return item.parentId === parentId; }); subItems.forEach(function (item) { item.trace = [].concat(_toConsumableArray(trace)); trace.push(item.id); item.hasSubMenu = mapTrace(content, item.id); if (item.hasSubMenu) { item.to = '#'; } trace.pop(); }); return subItems.length > 0; }; exports.default = function (content) { uid = 1; trace = []; var flatContent = flattenLevel(content); mapTrace(flatContent); return flatContent; }; /***/ }, /* 51 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * @file reducers/emitters.js * @author H.Alper Tuna <halpertuna@gmail.com> * Date: 16.12.2016 */ var emitters = function emitters() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var action = arguments[1]; switch (action.type) { case 'EMIT_SELECTED': { state.emitSelected(action.event); return state; } default: { return state; } } }; exports.default = emitters; /***/ } /******/ ]) }); ;
mit
Saaka/WordHunt
WordHunt.WebAPI/Auth/Token/TokenUserContextProvider.cs
1387
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace WordHunt.WebAPI.Auth.Token { public interface ITokenUserContextProvider { UserInfo GetContextUserInfo(); } public class TokenUserContextProvider : ITokenUserContextProvider { private ClaimsPrincipal caller; public TokenUserContextProvider(ClaimsPrincipal caller) { this.caller = caller; } public UserInfo GetContextUserInfo() { if (caller == null || caller.Identity == null) throw new UnauthorizedAccessException("No user specified information"); var identity = caller.Identity as ClaimsIdentity; if (identity == null || !caller.Identity.IsAuthenticated) throw new UnauthorizedAccessException("User is not properly authenticated"); var idClaim = identity.Claims.FirstOrDefault(x => x.Type == "id"); if (idClaim == null) throw new UnauthorizedAccessException("No User information provided white authenticating"); return new UserInfo() { Id = Convert.ToInt32(idClaim.Value) }; } } public class UserInfo { public int Id { get; set; } } }
mit
polygonplanet/Chiffon
tests/fixtures/parse/test-0120.js
24
do { a(); } while (0);
mit
jkowens/sinatra
sinatra-contrib/lib/sinatra/config_file.rb
5182
require 'sinatra/base' require 'yaml' require 'erb' module Sinatra # = Sinatra::ConfigFile # # <tt>Sinatra::ConfigFile</tt> is an extension that allows you to load the # application's configuration from YAML files. It automatically detects if # the files contain specific environment settings and it will use those # corresponding to the current one. # # You can access those options through +settings+ within the application. If # you try to get the value for a setting that hasn't been defined in the # config file for the current environment, you will get whatever it was set # to in the application. # # == Usage # # Once you have written your configurations to a YAML file you can tell the # extension to load them. See below for more information about how these # files are interpreted. # # For the examples, lets assume the following config.yml file: # # greeting: Welcome to my file configurable application # # === Classic Application # # require "sinatra" # require "sinatra/config_file" # # config_file 'path/to/config.yml' # # get '/' do # @greeting = settings.greeting # haml :index # end # # # The rest of your classic application code goes here... # # === Modular Application # # require "sinatra/base" # require "sinatra/config_file" # # class MyApp < Sinatra::Base # register Sinatra::ConfigFile # # config_file 'path/to/config.yml' # # get '/' do # @greeting = settings.greeting # haml :index # end # # # The rest of your modular application code goes here... # end # # === Config File Format # # In its most simple form this file is just a key-value list: # # foo: bar # something: 42 # nested: # a: 1 # b: 2 # # But it also can provide specific environment configuration. There are two # ways to do that: at the file level and at the settings level. # # At the settings level (e.g. in 'path/to/config.yml'): # # development: # foo: development # bar: bar # test: # foo: test # bar: bar # production: # foo: production # bar: bar # # Or at the file level: # # foo: # development: development # test: test # production: production # bar: bar # # In either case, <tt>settings.foo</tt> will return the environment name, and # <tt>settings.bar</tt> will return <tt>"bar"</tt>. # # If you wish to provide defaults that may be shared among all the # environments, this can be done by using a YAML alias, and then overwriting # values in environments where appropriate: # # default: &common_settings # foo: 'foo' # bar: 'bar' # # production: # <<: *common_settings # bar: 'baz' # override the default value # module ConfigFile # When the extension is registered sets the +environments+ setting to the # traditional environments: development, test and production. def self.registered(base) base.set :environments, %w[test production development] end # Loads the configuration from the YAML files whose +paths+ are passed as # arguments, filtering the settings for the current environment. Note that # these +paths+ can actually be globs. def config_file(*paths) Dir.chdir(root || '.') do paths.each do |pattern| Dir.glob(pattern) do |file| raise UnsupportedConfigType unless ['.yml', '.yaml', '.erb'].include?(File.extname(file)) logger.info "loading config file '#{file}'" if logging? && respond_to?(:logger) document = ERB.new(IO.read(file)).result yaml = YAML.load(document) config = config_for_env(yaml) config.each_pair { |key, value| set(key, value) } end end end end class UnsupportedConfigType < Exception def message 'Invalid config file type, use .yml, .yaml or .erb' end end private # Given a +hash+ containing application configuration it returns # settings applicable to the current environment. Note: It gives # precedence to environment settings defined at the root-level. def config_for_env(hash) return from_environment_key(hash) if environment_keys?(hash) hash.each_with_object(IndifferentHash[]) do |(k, v), acc| if environment_keys?(v) acc.merge!(k => v[environment.to_s]) if v.key?(environment.to_s) else acc.merge!(k => v) end end end # Given a +hash+ returns the settings corresponding to the current # environment. def from_environment_key(hash) hash[environment.to_s] || hash[environment.to_sym] || {} end # Returns true if supplied with a hash that has any recognized # +environments+ in its root keys. def environment_keys?(hash) hash.is_a?(Hash) && hash.any? { |k, _| environments.include?(k.to_s) } end end register ConfigFile Delegator.delegate :config_file end
mit
gatkin/cDTO
src/test/scala/UnitSpec.scala
192
package dto import org.scalatest._ /** * Abstract base class used to mix in all traits used for all unit specification * tests */ abstract class UnitSpec extends FlatSpec with Matchers
mit
sirbootoo/giftplush
src/app/_services/mod.resolver.service.js
1943
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var router_1 = require("@angular/router"); var index_1 = require("../_services/index"); var ModResolver = (function () { function ModResolver(algoliaService, router) { this.algoliaService = algoliaService; this.router = router; } ModResolver.prototype.resolve = function (route, state) { var _this = this; var MerchantId = Number(route.params['id']); console.log(MerchantId); return this.algoliaService.getMerchant(MerchantId).map(function (merchant) { console.log(merchant); if (merchant) { return merchant; } else { _this.router.navigate(['/pick']); console.log(_this.router.navigate(['/pick'])); return null; } }); }; return ModResolver; }()); ModResolver = __decorate([ core_1.Injectable(), __metadata("design:paramtypes", [index_1.AlgoliaService, router_1.Router]) ], ModResolver); exports.ModResolver = ModResolver; //# sourceMappingURL=mod.resolver.service.js.map
mit
NetOfficeFw/NetOffice
Source/MSHTML/Records/_RemotableHandle.cs
729
//Generated by LateBindingApi.CodeGenerator using System; using System.Runtime.InteropServices; using NetOffice; using NetOffice.Attributes; namespace NetOffice.MSHTMLApi { /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] [StructLayout(LayoutKind.Sequential, Pack=4), Guid("00000000-0000-0000-0000-000000000000")] [EntityType(EntityType.IsStruct)] public struct _RemotableHandle { /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] public Int32 fContext; /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] [MarshalAs(UnmanagedType.Interface)] public object u; } }
mit
fahadonline/sulu
vendor/sulu/sulu/src/Sulu/Component/Webspace/Analyzer/Attributes/RequestAttributes.php
1226
<?php /* * This file is part of Sulu. * * (c) MASSIVE ART WebServices GmbH * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Sulu\Component\Webspace\Analyzer\Attributes; /** * Container for request attributes. */ class RequestAttributes { /** * @var array */ private $attributes; public function __construct(array $attributes = []) { $this->attributes = array_filter($attributes); } /** * Returns attribute with given name. * * @param string $name * @param mixed|null $default * * @return mixed */ public function getAttribute($name, $default = null) { if (!array_key_exists($name, $this->attributes)) { return $default; } return $this->attributes[$name]; } /** * Merges this and the given attributes and returns a new instance. * * @param RequestAttributes $requestAttributes * * @return RequestAttributes */ public function merge(RequestAttributes $requestAttributes) { return new self(array_merge($this->attributes, $requestAttributes->attributes)); } }
mit
flightlog/flsserver
src/FLS.Data.WebApi/AircraftReservation/AircraftReservationOverviewSearchFilter.cs
592
using System; namespace FLS.Data.WebApi.AircraftReservation { public class AircraftReservationOverviewSearchFilter { public DateTimeFilter Start { get; set; } public DateTimeFilter End { get; set; } public bool? IsAllDayReservation { get; set; } public string Immatriculation { get; set; } public string PilotName { get; set; } public string LocationName { get; set; } public string SecondCrewName { get; set; } public string ReservationTypeName { get; set; } public string Remarks { get; set; } } }
mit
icompuiz/toastycms
app/Plugin/ToastyCore/Model/ContentTypePropertySkel.php
4627
<?php App::uses('ToastyCoreAppModel', 'ToastyCore.Model'); class ContentTypePropertySkel extends ToastyCoreAppModel { public $name = "ContentTypePropertySkel"; public $_schema = array( 'id' => array( 'type' => 'integer', 'length' => 11 ), 'name' => array( 'type' => 'string', 'length' => 255 ), 'content_type_id' => array( 'type' => 'integer', 'length' => 11 ), 'input_format_id' => array( 'type' => 'integer', 'length' => 11 ), 'output_format_id' => array( 'type' => 'integer', 'length' => 11 ), 'created' => array( 'type' => 'datetime' ), 'modified' => array( 'type' => 'datetime' ) ); public function addSkel($data = null) { if (!empty($data)) { $this->create($data); $this->save(); return; } throw new Exception("index ContentTypePropertySkel not defined"); } public function getName($id = null) { $id = $this->checkId($id); $conditions = array( 'ContentTypePropertySkel.id' => $id ); $skel = $this->find('first', array("conditions" => $conditions)); $name = $skel['ContentTypePropertySkel']['name']; return $name; } public function setName($name = null, $id = null) { $id = $this->checkId($id); if (!empty($name)) { $data['ContentTypePropertySkel'] = array( 'id' => $id, 'name' => $name ); $this->save($data); return; } throw new Exception("name must be provided"); } public function getInputFormat($id = null) { $id = $this->checkId($id); $conditions = array( 'ContentTypePropertySkel.id' => $id ); $skel = $this->find('first', array("conditions" => $conditions)); $format = $skel['InputFormat']; return $format; } public function setInputFormat($format_id = null, $id = null) { $id = $this->checkId($id); if (!empty($format_id)) { $data['ContentTypePropertySkel'] = array( 'id' => $id, 'input_format_id' => $format_id ); $this->save($data); return; } throw new Exception("format_id must be provided"); } public function getOutputFormat($id = null) { $id = $this->checkId($id); $conditions = array( 'ContentTypePropertySkel.id' => $id ); $skel = $this->find('first', array("conditions" => $conditions)); $format = $skel['OutputFormat']; return $format; } public function setOutputFormat($format_id = null, $id = null) { $id = $this->checkId($id); if (!empty($format_id)) { $data['ContentTypePropertySkel'] = array( 'id' => $id, 'output_format_id' => $format_id ); $this->save($data); return; } throw new Exception("format_id must be provided"); } public function getContentType($id = null) { $id = $this->checkId($id); $conditions = array( 'ContentTypePropertySkel.id' => $id ); $skel = $this->find('first', array("conditions" => $conditions)); $format = $skel['ContentType']; return $format; } public function beforeDelete($cascade = true) { parent::beforeDelete($cascade); $propertyModel = ClassRegistry::init("ToastyCore.ContentTypeProperty"); $all = $propertyModel->find('all', array('conditions' => array('ContentTypeProperty.content_type_property_skel_id' => $this->id) )); foreach ($all as $one) { $propertyModel->id = $one['ContentTypeProperty']['id']; $propertyModel->delete(); } return true; } public $belongsTo = array( 'InputFormat' => array( 'className' => 'ToastyCore.OutputFormat', 'foreignKey' => 'input_format_id' ), 'OutputFormat' => array( 'className' => 'ToastyCore.OutputFormat', 'foreignKey' => 'output_format_id' ), 'ContentType' => array( 'className' => 'ToastyCore.ContentType' ) ); } ?>
mit
timplunkett/Routing
Tests/Routing/RouteMock.php
1074
<?php /* * This file is part of the Symfony CMF package. * * (c) 2011-2015 Symfony CMF * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Cmf\Component\Routing\Tests\Routing; use Symfony\Component\Routing\Route as SymfonyRoute; use Symfony\Cmf\Component\Routing\RouteObjectInterface; class RouteMock extends SymfonyRoute implements RouteObjectInterface { private $locale; public function setLocale($locale) { $this->locale = $locale; } public function getContent() { return null; } public function getDefaults() { $defaults = array(); if (! is_null($this->locale)) { $defaults['_locale'] = $this->locale; } return $defaults; } public function getRequirement($key) { if (! $key == '_locale') { throw new \Exception; } return $this->locale; } public function getRouteKey() { return null; } }
mit
dirtyfilthy/dirtyfilthy-bouncycastle
net/dirtyfilthy/bouncycastle/crypto/engines/Grainv1Engine.java
8559
package net.dirtyfilthy.bouncycastle.crypto.engines; import net.dirtyfilthy.bouncycastle.crypto.CipherParameters; import net.dirtyfilthy.bouncycastle.crypto.DataLengthException; import net.dirtyfilthy.bouncycastle.crypto.StreamCipher; import net.dirtyfilthy.bouncycastle.crypto.params.KeyParameter; import net.dirtyfilthy.bouncycastle.crypto.params.ParametersWithIV; /** * Implementation of Martin Hell's, Thomas Johansson's and Willi Meier's stream * cipher, Grain v1. */ public class Grainv1Engine implements StreamCipher { /** * Constants */ private static final int STATE_SIZE = 5; /** * Variables to hold the state of the engine during encryption and * decryption */ private byte[] workingKey; private byte[] workingIV; private byte[] out; private int[] lfsr; private int[] nfsr; private int output; private int index = 2; private boolean initialised = false; public String getAlgorithmName() { return "Grain v1"; } /** * Initialize a Grain v1 cipher. * * @param forEncryption Whether or not we are for encryption. * @param params The parameters required to set up the cipher. * @throws IllegalArgumentException If the params argument is inappropriate. */ public void init(boolean forEncryption, CipherParameters params) throws IllegalArgumentException { /** * Grain encryption and decryption is completely symmetrical, so the * 'forEncryption' is irrelevant. */ if (!(params instanceof ParametersWithIV)) { throw new IllegalArgumentException( "Grain v1 Init parameters must include an IV"); } ParametersWithIV ivParams = (ParametersWithIV)params; byte[] iv = ivParams.getIV(); if (iv == null || iv.length != 8) { throw new IllegalArgumentException( "Grain v1 requires exactly 8 bytes of IV"); } if (!(ivParams.getParameters() instanceof KeyParameter)) { throw new IllegalArgumentException( "Grain v1 Init parameters must include a key"); } KeyParameter key = (KeyParameter)ivParams.getParameters(); /** * Initialize variables. */ workingIV = new byte[key.getKey().length]; workingKey = new byte[key.getKey().length]; lfsr = new int[STATE_SIZE]; nfsr = new int[STATE_SIZE]; out = new byte[2]; System.arraycopy(iv, 0, workingIV, 0, iv.length); System.arraycopy(key.getKey(), 0, workingKey, 0, key.getKey().length); setKey(workingKey, workingIV); initGrain(); } /** * 160 clocks initialization phase. */ private void initGrain() { for (int i = 0; i < 10; i++) { output = getOutput(); nfsr = shift(nfsr, getOutputNFSR() ^ lfsr[0] ^ output); lfsr = shift(lfsr, getOutputLFSR() ^ output); } initialised = true; } /** * Get output from non-linear function g(x). * * @return Output from NFSR. */ private int getOutputNFSR() { int b0 = nfsr[0]; int b9 = nfsr[0] >>> 9 | nfsr[1] << 7; int b14 = nfsr[0] >>> 14 | nfsr[1] << 2; int b15 = nfsr[0] >>> 15 | nfsr[1] << 1; int b21 = nfsr[1] >>> 5 | nfsr[2] << 11; int b28 = nfsr[1] >>> 12 | nfsr[2] << 4; int b33 = nfsr[2] >>> 1 | nfsr[3] << 15; int b37 = nfsr[2] >>> 5 | nfsr[3] << 11; int b45 = nfsr[2] >>> 13 | nfsr[3] << 3; int b52 = nfsr[3] >>> 4 | nfsr[4] << 12; int b60 = nfsr[3] >>> 12 | nfsr[4] << 4; int b62 = nfsr[3] >>> 14 | nfsr[4] << 2; int b63 = nfsr[3] >>> 15 | nfsr[4] << 1; return (b62 ^ b60 ^ b52 ^ b45 ^ b37 ^ b33 ^ b28 ^ b21 ^ b14 ^ b9 ^ b0 ^ b63 & b60 ^ b37 & b33 ^ b15 & b9 ^ b60 & b52 & b45 ^ b33 & b28 & b21 ^ b63 & b45 & b28 & b9 ^ b60 & b52 & b37 & b33 ^ b63 & b60 & b21 & b15 ^ b63 & b60 & b52 & b45 & b37 ^ b33 & b28 & b21 & b15 & b9 ^ b52 & b45 & b37 & b33 & b28 & b21) & 0x0000FFFF; } /** * Get output from linear function f(x). * * @return Output from LFSR. */ private int getOutputLFSR() { int s0 = lfsr[0]; int s13 = lfsr[0] >>> 13 | lfsr[1] << 3; int s23 = lfsr[1] >>> 7 | lfsr[2] << 9; int s38 = lfsr[2] >>> 6 | lfsr[3] << 10; int s51 = lfsr[3] >>> 3 | lfsr[4] << 13; int s62 = lfsr[3] >>> 14 | lfsr[4] << 2; return (s0 ^ s13 ^ s23 ^ s38 ^ s51 ^ s62) & 0x0000FFFF; } /** * Get output from output function h(x). * * @return Output from h(x). */ private int getOutput() { int b1 = nfsr[0] >>> 1 | nfsr[1] << 15; int b2 = nfsr[0] >>> 2 | nfsr[1] << 14; int b4 = nfsr[0] >>> 4 | nfsr[1] << 12; int b10 = nfsr[0] >>> 10 | nfsr[1] << 6; int b31 = nfsr[1] >>> 15 | nfsr[2] << 1; int b43 = nfsr[2] >>> 11 | nfsr[3] << 5; int b56 = nfsr[3] >>> 8 | nfsr[4] << 8; int b63 = nfsr[3] >>> 15 | nfsr[4] << 1; int s3 = lfsr[0] >>> 3 | lfsr[1] << 13; int s25 = lfsr[1] >>> 9 | lfsr[2] << 7; int s46 = lfsr[2] >>> 14 | lfsr[3] << 2; int s64 = lfsr[4]; return (s25 ^ b63 ^ s3 & s64 ^ s46 & s64 ^ s64 & b63 ^ s3 & s25 & s46 ^ s3 & s46 & s64 ^ s3 & s46 & b63 ^ s25 & s46 & b63 ^ s46 & s64 & b63 ^ b1 ^ b2 ^ b4 ^ b10 ^ b31 ^ b43 ^ b56) & 0x0000FFFF; } /** * Shift array 16 bits and add val to index.length - 1. * * @param array The array to shift. * @param val The value to shift in. * @return The shifted array with val added to index.length - 1. */ private int[] shift(int[] array, int val) { array[0] = array[1]; array[1] = array[2]; array[2] = array[3]; array[3] = array[4]; array[4] = val; return array; } /** * Set keys, reset cipher. * * @param keyBytes The key. * @param ivBytes The IV. */ private void setKey(byte[] keyBytes, byte[] ivBytes) { ivBytes[8] = (byte)0xFF; ivBytes[9] = (byte)0xFF; workingKey = keyBytes; workingIV = ivBytes; /** * Load NFSR and LFSR */ int j = 0; for (int i = 0; i < nfsr.length; i++) { nfsr[i] = (workingKey[j + 1] << 8 | workingKey[j] & 0xFF) & 0x0000FFFF; lfsr[i] = (workingIV[j + 1] << 8 | workingIV[j] & 0xFF) & 0x0000FFFF; j += 2; } } public void processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) throws DataLengthException { if (!initialised) { throw new IllegalStateException(getAlgorithmName() + " not initialised"); } if ((inOff + len) > in.length) { throw new DataLengthException("input buffer too short"); } if ((outOff + len) > out.length) { throw new DataLengthException("output buffer too short"); } for (int i = 0; i < len; i++) { out[outOff + i] = (byte)(in[inOff + i] ^ getKeyStream()); } } public void reset() { index = 2; setKey(workingKey, workingIV); initGrain(); } /** * Run Grain one round(i.e. 16 bits). */ private void oneRound() { output = getOutput(); out[0] = (byte)output; out[1] = (byte)(output >> 8); nfsr = shift(nfsr, getOutputNFSR() ^ lfsr[0]); lfsr = shift(lfsr, getOutputLFSR()); } public byte returnByte(byte in) { if (!initialised) { throw new IllegalStateException(getAlgorithmName() + " not initialised"); } return (byte)(in ^ getKeyStream()); } private byte getKeyStream() { if (index > 1) { oneRound(); index = 0; } return out[index++]; } }
mit
zxx1988328/ins
frontend/themes/basic/modules/user/views/dashboard/index.php
4806
<?php use yii\helpers\Url; use yii\helpers\Html; use yii\bootstrap\ActiveForm; use yii\bootstrap\Modal; use shiyang\infinitescroll\InfiniteScrollPager; /* @var $this yii\web\View */ $this->title=Yii::$app->user->identity->username.' - '.Yii::t('app', 'Home'); ?> <div class="item widget-container share-widget fluid-height clearfix"> <div class="widget-content padded"> <?php $form = ActiveForm::begin([ 'enableClientValidation' => false, 'options' => ['id' => 'create-feed'] ]); ?> <?= $form->field($newFeed, 'content', ['inputOptions' => ['placeholder' => Yii::t('app', 'Record people around, things around.')]])->textarea(['rows' => 3])->label(false) ?> <div class="form-group"> <?= Html::submitButton(Yii::t('app', 'Create'), ['class' => 'btn btn-success']) ?> </div> <?php ActiveForm::end(); ?> </div> </div> <?php if (!empty($feeds)): ?> <div id="content"> <?php foreach($feeds as $feed): ?> <div class="item widget-container fluid-height social-entry" id="<?= $feed['id'] ?>"> <div class="widget-content padded"> <div class="profile-info clearfix"> <a class="pull-left" href="<?= Url::toRoute(['/user/view', 'id'=>$feed['username']]) ?>" rel="author" data-pjax="0"> <img width="50" height="50" class="social-avatar" src="<?= Yii::getAlias('@avatar') . $feed['avatar'] ?>" alt="@<?= $feed['username'] ?>"/> </a> <div class="profile-details"> <a class="user-name" href="<?= Url::toRoute(['/user/view', 'id'=>$feed['username']]) ?>" rel="author" data-pjax="0"> <?= Html::encode($feed['username']) ?> </a> <p> <em><?= Yii::$app->formatter->asRelativeTime($feed['created_at']) ?></em> </p> </div> </div> <p class="content"> <?php if (!empty($feed['content'])) { echo Html::encode($feed['content']); } else { echo strtr($feed['template'], unserialize($feed['feed_data'])); } ?> </p> </div> <div class="widget-footer"> <div class="footer-detail"> <?php if(Yii::$app->user->id == $feed['user_id']): ?> &nbsp; <a href="<?= Url::toRoute(['/home/feed/delete', 'id' => $feed['id']]) ?>" data-clicklog="delete" onclick="return false;" title="<?= Yii::t('app', 'Are you sure to delete it?') ?>"> <span class="glyphicon glyphicon-trash"></span> <?= Yii::t('app', 'Delete') ?> </a> &nbsp; <span class="item-line"></span> <?php endif ?> <a href="javascript:;" onclick="setRepostFormAction(<?= $feed['id'] ?>)" data-toggle="modal" data-target="#repost-modal"> <span class="glyphicon glyphicon-share-alt"></span> <?= Yii::t('app', 'Repost') ?> </a> </div> </div> </div> <?php endforeach; ?> </div> <?= InfiniteScrollPager::widget([ 'pagination' => $pages, 'widgetId' => '#content', ]);?> <?php else: ?> <div class="no-data-found"> <i class="glyphicon glyphicon-folder-open"></i> <?= Yii::t('app', 'No feed to display. Go to ') ?><?= Html::a(Yii::t('app', 'Explore') . '?', ['/explore/index']) ?> </div> <?php endif; ?> <?php Modal::begin([ 'header' => '<h4>' . Yii::t('app', 'Repost') . '</h4>', 'options' => ['id' => 'repost-modal'] ]); $newFeed->setScenario('repost'); ?> <?php $form = ActiveForm::begin([ 'options' => ['id' => 'repost-feed'], 'action' => ['/home/feed/create?id='] ]); ?> <?= $form->field($newFeed, 'content')->textarea(['rows' => 3, 'id' => 'repost-feed-content'])->label(false) ?> <div class="form-group"> <?= Html::submitButton(Yii::t('app', 'Repost'), ['class' => 'btn btn-success']) ?> </div> <?php ActiveForm::end(); ?> <?php Modal::end() ?> <script type="text/javascript"> function setRepostFormAction (id) { var action = document.getElementById("repost-feed").action; document.getElementById("repost-feed").action = action + id; } </script>
mit
wenhulove333/ScutServer
Sample/ClientSource/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp
729
#include "TestHeaderLayer.h" USING_NS_CC; USING_NS_CC_EXT; SEL_MenuHandler TestHeaderLayer::onResolveCCBCCMenuItemSelector(CCObject * pTarget, const char * pSelectorName) { CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "onBackClicked", TestHeaderLayer::onBackClicked); return NULL; } SEL_CCControlHandler TestHeaderLayer::onResolveCCBCCControlSelector(CCObject * pTarget, const char * pSelectorName) { return NULL; } void TestHeaderLayer::onNodeLoaded(cocos2d::CCNode * pNode, cocos2d::extension::CCNodeLoader * pNodeLoader) { CCLOG("TestHeaderLayer::onNodeLoaded"); } void TestHeaderLayer::onBackClicked(cocos2d::CCObject *pSender) { CCDirector::sharedDirector()->popScene(); }
mit
egovernment/eregistrations
view/statistics-time-per-person.js
5897
'use strict'; var copy = require('es5-ext/object/copy') , uncapitalize = require('es5-ext/string/#/uncapitalize') , memoize = require('memoizee') , ObservableValue = require('observable-value') , location = require('mano/lib/client/location') , _ = require('mano').i18n.bind('View: Statistics') , db = require('mano').db , getData = require('mano/lib/client/xhr-driver').get , setupQueryHandler = require('../utils/setup-client-query-handler') , getQueryHandlerConf = require('../apps/statistics/get-query-conf') , getDurationDaysHours = require('./utils/get-duration-days-hours-fine-grain') , dateFromToBlock = require('./components/filter-bar/select-date-range-safe-fallback') , getDynamicUrl = require('./utils/get-dynamic-url') , initializeRowOnClick = require('./utils/statistics-time-row-onclick') , processingStepsMetaWithoutFrontDesk = require('./../utils/processing-steps-meta-without-front-desk'); exports._parent = require('./statistics-time'); exports._customFilters = Function.prototype; exports['time-nav'] = { class: { 'submitted-menu-item-active': true } }; exports['per-person-nav'] = { class: { 'pills-nav-active': true } }; var queryServer = memoize(function (query) { return getData('/get-time-per-person/', query); }, { normalizer: function (args) { return JSON.stringify(args[0]); } }); var getRowResult = function (rowData) { var result = copy(rowData); result.avgTime = rowData.timedCount ? getDurationDaysHours(rowData.avgTime) : '-'; result.minTime = rowData.timedCount ? getDurationDaysHours(rowData.minTime) : '-'; result.maxTime = rowData.timedCount ? getDurationDaysHours(rowData.maxTime) : '-'; return result; }; exports['statistics-main'] = function () { var stepsMeta = processingStepsMetaWithoutFrontDesk(), stepsMap = {}, queryHandler, params, queryResult; Object.keys(stepsMeta).forEach(function (stepShortPath) { stepsMap[stepShortPath] = new ObservableValue(); }); queryHandler = setupQueryHandler(getQueryHandlerConf({ processingStepsMeta: stepsMeta }), location, '/time/per-person/'); params = queryHandler._handlers.map(function (handler) { return handler.name; }); queryHandler.on('query', function (query) { if (query.dateFrom) { query.dateFrom = query.dateFrom.toJSON(); } if (query.dateTo) { query.dateTo = query.dateTo.toJSON(); } queryServer(query).done(function (result) { queryResult = result; Object.keys(result).forEach(function (key) { var preparedResults = []; if (!stepsMap[key]) { stepsMap[key].value = null; return; } Object.keys(result[key].rows).forEach(function (rowId) { preparedResults.push(getRowResult(result[key].rows[rowId].processing || result[key].rows[rowId])); }); stepsMap[key].value = preparedResults; }); }); }); div({ class: 'block-pull-up' }, form({ action: '/time/per-person', autoSubmit: true }, section({ class: 'date-period-selector-positioned-on-submenu' }, dateFromToBlock()), section({ class: 'entities-overview-info' }, _("As processing time is properly recorded since 1st of February 2017." + " Below table only exposes data for files submitted after that day.")), br(), section({ class: 'section-primary users-table-filter-bar' }, div( { class: 'users-table-filter-bar-status' }, label({ for: 'service-select' }, _("Service"), ":"), select({ id: 'service-select', name: 'service' }, option({ value: '', selected: location.query.get('service').map(function (value) { return (value == null); }) }, _("All")), list(db.BusinessProcess.extensions, function (service) { var serviceName = uncapitalize.call(service.__id__.slice('BusinessProcess'.length)); return option({ value: serviceName, selected: location.query.get('service').map(function (value) { var selected = (serviceName ? (value === serviceName) : (value == null)); return selected ? 'selected' : null; }) }, service.prototype.label); }, null)) ), div( { class: 'users-table-filter-bar-status' }, exports._customFilters.call(this) ), div( a({ class: 'users-table-filter-bar-print', href: getDynamicUrl('/time-per-person.pdf', { only: params }), target: '_blank' }, span({ class: 'fa fa-print' }), " ", _("Print pdf")) ))), br(), insert(list(Object.keys(stepsMap), function (shortStepPath) { return stepsMap[shortStepPath].map(function (data) { if (!data) return; return [section({ class: "section-primary" }, h3(queryResult[shortStepPath].label), table({ class: 'statistics-table' }, thead( tr( th(), th({ class: 'statistics-table-number' }, _("Processing periods")), th({ class: 'statistics-table-number' }, _("Average time")), th({ class: 'statistics-table-number' }, _("Min time")), th({ class: 'statistics-table-number' }, _("Max time")) ) ), tbody({ onEmpty: tr(td({ class: 'empty statistics-table-number', colspan: 5 }, _("There are no files processed at this step"))) }, data, function (rowData) { var props = {}; if (rowData && rowData.processor && rowData.processingPeriods) { initializeRowOnClick(rowData, props, false); } return tr(props, td(rowData.processor), td({ class: 'statistics-table-number' }, rowData.timedCount), td({ class: 'statistics-table-number' }, rowData.avgTime), td({ class: 'statistics-table-number' }, rowData.minTime), td({ class: 'statistics-table-number' }, rowData.maxTime) ); }) )), br()]; }); }))); };
mit
miltonsarria/dsp-python
images/compare.py
1422
import sys from scipy.misc import imread from scipy.linalg import norm from scipy import sum, average #Main function, read two images, convert to grayscale, compare and print results: def main(): file1, file2 = sys.argv[1:1+2] # read images as 2D arrays (convert to grayscale for simplicity) img1 = to_grayscale(imread(file1).astype(float)) img2 = to_grayscale(imread(file2).astype(float)) # compare n_m, n_0 = compare_images(img1, img2) print "Manhattan norm:", n_m, "/ per pixel:", n_m/img1.size print "Zero norm:", n_0, "/ per pixel:", n_0*1.0/img1.size def compare_images(img1, img2): # normalize to compensate for exposure difference, this may be unnecessary # consider disabling it img1 = normalize(img1) img2 = normalize(img2) # calculate the difference and its norms diff = img1 - img2 # elementwise for scipy arrays m_norm = sum(abs(diff)) # Manhattan norm z_norm = norm(diff.ravel(), 0) # Zero norm return (m_norm, z_norm) def to_grayscale(arr): "If arr is a color image (3D array), convert it to grayscale (2D array)." if len(arr.shape) == 3: return average(arr, -1) # average over the last axis (color channels) else: return arr def normalize(arr): rng = arr.max()-arr.min() amin = arr.min() return (arr-amin)*255/rng #Run the main function: if __name__ == "__main__": main()
mit
ActiveSolution/lab-webben-vnext
src/WebbenVNext/src/calculator.spec.ts
466
import { Calculator } from './calculator'; import { expect } from 'chai'; import 'mocha'; describe('Calculator', () => { it('should add numbers', () => { const calc = new Calculator(); const result = calc.add(10, 20); expect(result).to.equal(30); }); it('should multiply numbers', () => { const calc = new Calculator(); const result = calc.multiply(10, 20); expect(result).to.equal(200); }); });
mit
Credit-Jeeves/Heartland
src/Payum2/Heartland/Soap/Base/CapturePreAuthorizedPayment.php
1334
<?php namespace Payum2\Heartland\Soap\Base; /** * This class is generated from the following WSDL: * https://heartlandpaymentservices.net/BillingDataManagement/v3/BillingDataManagementService.svc?xsd=xsd0 */ class CapturePreAuthorizedPayment { /** * CapturePreAuthorizedPaymentRequest * * The property has the following characteristics/restrictions: * - SchemaType: q61:CapturePreAuthorizedPaymentRequest * * @var CapturePreAuthorizedPaymentRequest */ protected $CapturePreAuthorizedPaymentRequest = null; /** * @param CapturePreAuthorizedPaymentRequest $capturePreAuthorizedPaymentRequest * * @return CapturePreAuthorizedPayment */ public function setCapturePreAuthorizedPaymentRequest(CapturePreAuthorizedPaymentRequest $capturePreAuthorizedPaymentRequest) { $this->CapturePreAuthorizedPaymentRequest = $capturePreAuthorizedPaymentRequest; return $this; } /** * @return CapturePreAuthorizedPaymentRequest */ public function getCapturePreAuthorizedPaymentRequest() { if (null === $this->CapturePreAuthorizedPaymentRequest) { $this->CapturePreAuthorizedPaymentRequest = new CapturePreAuthorizedPaymentRequest(); } return $this->CapturePreAuthorizedPaymentRequest; } }
mit
kanonirov/lanb-client
src/main/java/ru/lanbilling/webservice/wsdl/IPCalcResponse.java
2247
package ru.lanbilling.webservice.wsdl; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="ret" type="{urn:api3}soapIPMask" maxOccurs="unbounded"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "ret" }) @XmlRootElement(name = "IPCalcResponse") @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public class IPCalcResponse { @XmlElement(required = true) @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") protected List<SoapIPMask> ret; /** * Gets the value of the ret property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the ret property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRet().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SoapIPMask } * * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public List<SoapIPMask> getRet() { if (ret == null) { ret = new ArrayList<SoapIPMask>(); } return this.ret; } }
mit
ZahlGraf/IrrIMGUI
source/CBasicMemoryLeakDetection.cpp
3224
/** * The MIT License (MIT) * * Copyright (c) 2015-2016 Andre Netzeband * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * @file CBasicMemoryLeakDetection.cpp * @author Andre Netzeband * @brief Class for a very basic memory leak detection. * @addtogroup IrrIMGUITools */ // module includes #include <IrrIMGUI/Tools/CBasicMemoryLeakDetection.h> #include "private/IrrIMGUIDebug_priv.h" namespace IrrIMGUI { namespace Tools { CBasicMemoryLeakDetection::CBasicMemoryLeakDetection(void) { resetMemoryState(); return; } CBasicMemoryLeakDetection::~CBasicMemoryLeakDetection(void) { if (!mWasMemoryChecked) { int const MemoryLeak = compareMemoryState(); if (MemoryLeak != 0) { LOG_ERROR("Memory Leak detected: " << MemoryLeak << " Bytes has been allocated but not freed-up!"); } } return; } int CBasicMemoryLeakDetection::compareMemoryState(void) { int MemoryLeak = 0; #ifdef _ENABLE_MEMORY_LEAK_DETECTION_ _CrtMemState CurrentMemoryState; _CrtMemState MemoryDifference; _CrtMemCheckpoint(&CurrentMemoryState); _CrtMemDifference(&MemoryDifference, &mMemoryState, &CurrentMemoryState); MemoryLeak += static_cast<int>(MemoryDifference.lSizes[_NORMAL_BLOCK]); MemoryLeak += static_cast<int>(MemoryDifference.lSizes[_IGNORE_BLOCK]); MemoryLeak += static_cast<int>(MemoryDifference.lSizes[_CLIENT_BLOCK]); /* if (MemoryLeak) { LOG_WARNING("Detected Memory Leak for _NORMAL_BLOCK: " << std::dec << MemoryDifference.lSizes[_NORMAL_BLOCK] << std::endl); LOG_WARNING("Detected Memory Leak for _IGNORE_BLOCK: " << std::dec << MemoryDifference.lSizes[_IGNORE_BLOCK] << std::endl); LOG_WARNING("Detected Memory Leak for _CLIENT_BLOCK: " << std::dec << MemoryDifference.lSizes[_CLIENT_BLOCK] << std::endl); } */ #endif // _ENABLE_MEMORY_LEAK_DETECTION_ mWasMemoryChecked = true; return MemoryLeak; } void CBasicMemoryLeakDetection::resetMemoryState(void) { #ifdef _ENABLE_MEMORY_LEAK_DETECTION_ _CrtMemCheckpoint(&mMemoryState); #endif // _ENABLE_MEMORY_LEAK_DETECTION_ mWasMemoryChecked = false; return; } } }
mit
prevratnic/rest-web-example
src/main/java/com/degas/bean/TaskServiceBean.java
1675
package com.degas.bean; import com.degas.model.PriorityValues; import com.degas.model.StatusValues; import com.degas.model.Task; import org.jetbrains.annotations.NotNull; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.persistence.PersistenceContext; import java.util.List; /** * Author: Ilya Varlamov aka privratnik (contact with me) degas.developer@gmail.com * Date: 19.08.13 * Time: 23:37 */ @Stateless @LocalBean public class TaskServiceBean implements TaskService { @PersistenceContext(unitName = "restUnit") EntityManager em; @Override public void createOrModifyTask(@NotNull Task task) { em.merge(task); } @Override public void changeStatus(long id, @NotNull StatusValues statusValues) { Task task = em.find(Task.class, id); task.setStatus(statusValues); } @Override public void changePriority(long id, @NotNull PriorityValues statusValues) { Task task = em.find(Task.class, id); task.setPriority(statusValues); } @NotNull @Override public List<Task> getListTask() { return em.createNamedQuery("Task.findAll", Task.class).getResultList(); } @NotNull @Override public List<Task> getSubListTask(int start, int end) { Query query = em. createNativeQuery("SELECT * FROM " + "(SELECT t.*, row_number() OVER (ORDER BY ID) rn FROM task t) " + "WHERE rn BETWEEN ? AND ?", Task.class); query.setParameter(1, start); query.setParameter(2, end); return query.getResultList(); } }
mit
mstevenson/SeudoBuild
SeudoBuild.Agent/BuildQueue.cs
5484
using System.Collections.Generic; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; using System.IO; using SeudoBuild.Core; using SeudoBuild.Pipeline; namespace SeudoBuild.Agent { /// <summary> /// Queues projects and feeds them sequentially to a builder. /// </summary> public class BuildQueue : IBuildQueue { private const string OutputFolderName = "SeudoBuild"; private readonly IBuilder _builder; private readonly IModuleLoader _moduleLoader; private readonly ILogger _logger; private CancellationTokenSource _tokenSource; private int _buildIndex; private bool _isQueueRunning; public BuildResult ActiveBuild { get; private set; } private ConcurrentQueue<BuildResult> QueuedBuilds { get; } = new ConcurrentQueue<BuildResult>(); private ConcurrentDictionary<int, BuildResult> Builds { get; } = new ConcurrentDictionary<int, BuildResult>(); public BuildQueue(IBuilder builder, IModuleLoader moduleLoader, ILogger logger) { _builder = builder; _moduleLoader = moduleLoader; _logger = logger; } /// <summary> /// Begin executing builds in the queue. Builds will continue until the queue has been exhausted. /// </summary> public void StartQueue(IFileSystem fileSystem) { if (_isQueueRunning) { return; } _isQueueRunning = true; _tokenSource = new CancellationTokenSource(); // Create output folder in user's documents folder var outputPath = fileSystem.DocumentsPath; if (!fileSystem.DirectoryExists(outputPath)) { throw new DirectoryNotFoundException("User documents folder not found"); } outputPath = Path.Combine(outputPath, OutputFolderName); if (!fileSystem.DirectoryExists(outputPath)) { fileSystem.CreateDirectory(outputPath); } Task.Factory.StartNew(() => TaskQueuePump(outputPath, _moduleLoader), _tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); } private void TaskQueuePump(string outputPath, IModuleLoader moduleLoader) { while (true) { // Clean up and bail out if (_tokenSource.IsCancellationRequested) { ActiveBuild = null; return; } if (!_builder.IsRunning && QueuedBuilds.Count > 0) { if (QueuedBuilds.TryDequeue(out var build)) { // Ignore builds that have been cancelled if (build.BuildStatus != BuildResult.Status.Queued) { continue; } string printableTarget = string.IsNullOrEmpty(build.TargetName) ? "default target" : $"target '{build.TargetName}'"; _logger.QueueNotification($"Building project '{build.ProjectConfiguration.ProjectName}', {printableTarget}"); ActiveBuild = build; var pipeline = new PipelineRunner(new PipelineConfig { BaseDirectory = outputPath }, _logger); _builder.Build(pipeline, ActiveBuild.ProjectConfiguration, ActiveBuild.TargetName); } } Thread.Sleep(200); } } /// <summary> /// Queues a project for building. /// If target is null, the default target in the given ProjectConfig will be used. /// </summary> public BuildResult EnqueueBuild(ProjectConfig config, string target = null) { _buildIndex++; var result = new BuildResult { Id = _buildIndex, BuildStatus = BuildResult.Status.Queued, ProjectConfiguration = config, TargetName = target }; QueuedBuilds.Enqueue(result); Builds.TryAdd(result.Id, result); return result; } /// <summary> /// Returns results for all known builds, including successful, failed, in-progress, and queued builds. /// </summary> public IEnumerable<BuildResult> GetAllBuildResults() { return Builds.Values; } /// <summary> /// Return the result for a specific build. /// </summary> public BuildResult GetBuildResult(int buildId) { Builds.TryGetValue(buildId, out var result); return result; } /// <summary> /// Stop a given build. If the build is in progress it will be halted, otherwise it will be removed from the queue. /// </summary> public BuildResult CancelBuild(int buildId) { if (ActiveBuild != null && ActiveBuild.Id == buildId) { ActiveBuild = null; // TODO signal build process to stop } if (Builds.TryGetValue(buildId, out var result)) { result.BuildStatus = BuildResult.Status.Cancelled; } return result; } } }
mit
mariomka/yi-action-camera
constant.js
2096
'use strict'; // Constants var Constants = exports; Constants.action = { REQUEST_TOKEN: 257, TAKE_PHOTO: 769, START_RECORD: 513, STOP_RECORD: 514, DELETE_FILE: 1281, GET_CONFIG: 3, SET_CONFIG: 2, START_STREAM: 259, STOP_STREAM: 260 }; Constants.config = { video: { standard: { TYPE_NAME: 'video_standard', NTSC: 'NTSC', PAL: 'PAL' }, resolution: { TYPE_NAME: 'video_resolution', NTSC_1920_1080_60P: '1920x1080 60P 16:9', NTSC_1920_1080_30P: '1920x1080 30P 16:9', NTSC_1280_960_60P: '1280x960 60P 4:3', NTSC_1280_720_60P: '1280x720 60P 16:9', NTSC_1280_720_120P: '1280x720 120P 16:9', NTSC_848_480_240P: '848x480 240P 16:9', PAL_1920_1080_48P: '1920x1080 48P 16:9', PAL_1920_1080_24P: '1920x1080 24P 16:9', PAL_1920_960_48P: '1280x960 48P 4:3', PAL_1920_720_48P: '1280x720 48P 16:9' }, quality: { TYPE_NAME: 'video_quality', SUPER_FINE: 'S.Fine', FINE: 'Fine', NORMAL: 'Normal' }, stamp: { TYPE_NAME: 'video_stamp', OFF: 'off', DATE: 'date', TIME: 'time', DATE_TIME: 'date/time' } }, photo: { resolution: { TYPE_NAME: 'photo_size', R16MP: '16M (4608x3456 4:3)', R13MP: '13M (4128x3096 4:3)', R8MP: '8M (3264x2448 4:3)', R5MP: '5M (2560x1920 4:3)' }, quality: { TYPE_NAME: 'photo_quality', SUPER_FINE: 'S.Fine', FINE: 'Fine', NORMAL: 'Normal' }, stamp: { TYPE_NAME: 'photo_stamp', OFF: 'off', DATE: 'date', TIME: 'time', DATE_TIME: 'date/time' } } };
mit
fishkingsin/ofxRpiWS281x
src/Matrix.cpp
1720
//Matrix.cpp #include "Matrix.h" namespace ofxRpiWS281x{ Matrix::Matrix() { } void Matrix::setupMatrix(int _matrixWidth, int _matrixHeight, int _matrixColum, int _matrixRow){ matrixColum = _matrixColum; matrixRow = _matrixRow; matrixWidth = _matrixWidth; matrixHeight = _matrixHeight; totalMatrix = matrixWidth * matrixHeight; ledWidth = matrixWidth * matrixColum; ledHeight = matrixHeight * matrixRow; totalLED = ledWidth*ledHeight; BaseLED::setup(totalLED, 255); } Matrix::~Matrix() { for(int i = 0 ; i < totalLED ;i++) { drawPiexls(i,ofColor(0,0,0)); } update(); if (0) { void *p = malloc(32000000); memset(p, 42, 32000000); free(p); } ws2811_fini(&ledstring); } void Matrix::draw(){ for(int y = 0 ; y < getHeight() ;y++) { for(int x = 0 ; x < getWidth() ;x++) { ofRect(0,0,getWidth(),getHeight()); } } } // void setupStrip(int numPixes){}; // void setupGrid(){}; void Matrix::drawMatrix(int x, int y ,ofColor color){ drawPiexls( remapIndex(x, y), color); } int Matrix::getWidth(){ return ledWidth; } int Matrix::getHeight(){ return ledHeight; } int Matrix::getMatrixWidth(){ return matrixWidth; } int Matrix::getMatrixHeight(){ return matrixHeight; } int Matrix::getMatrixColum(){ return matrixColum; } int Matrix::getMatrixRow(){ return matrixRow; } int Matrix::remapIndex(int x, int y){ int mod = y%2; int block = ((( y / (matrixHeight ))* matrixColum )+( x / (matrixWidth ))) * totalMatrix; int tX = (mod==1)?(matrixWidth -1)- (x% matrixWidth):(x% matrixWidth); int tY = (y% matrixHeight)* matrixWidth; return block+tX+tY; } }
mit
tinchopas/ferreteria2.1
src/DNT/WorkshopBundle/Tests/Controller/ClienteControllerTest.php
1766
<?php namespace DNT\WorkshopBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class ClienteControllerTest extends WebTestCase { /* public function testCompleteScenario() { // Create a new client to browse the application $client = static::createClient(); // Create a new entry in the database $crawler = $client->request('GET', '/clients/'); $this->assertTrue(200 === $client->getResponse()->getStatusCode()); $crawler = $client->click($crawler->selectLink('Create a new entry')->link()); // Fill in the form and submit it $form = $crawler->selectButton('Create')->form(array( 'cliente[field_name]' => 'Test', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check data in the show view $this->assertTrue($crawler->filter('td:contains("Test")')->count() > 0); // Edit the entity $crawler = $client->click($crawler->selectLink('Edit')->link()); $form = $crawler->selectButton('Edit')->form(array( 'cliente[field_name]' => 'Foo', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check the element contains an attribute with value equals "Foo" $this->assertTrue($crawler->filter('[value="Foo"]')->count() > 0); // Delete the entity $client->submit($crawler->selectButton('Delete')->form()); $crawler = $client->followRedirect(); // Check the entity has been delete on the list $this->assertNotRegExp('/Foo/', $client->getResponse()->getContent()); } */ }
mit
lvzhihao/wechat
models/user_access_token.go
1259
package models import ( "time" "github.com/lvzhihao/wechat/core" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) func UserAccessTokenEnsureIndex(s *mgo.Session) { c := s.DB("").C(UserAccessToken{}.TableName()) c.EnsureIndex(mgo.Index{ Key: []string{"appid", "openid"}, Unique: true, DropDups: true, Background: true, // See notes. Sparse: true, }) } type UserAccessToken struct { AppId string `bson:"appid" json:"-"` OpenId string `bson:"openid" json:"openid"` AccessToken core.UserAccessToken `bson:"access_token" json:"access_token"` UpdatedTime time.Time `bson:"updated_time" json:"-"` } func (q UserAccessToken) TableName() string { return "user_access_token" } func (q *UserAccessToken) Upsert(s *mgo.Session) error { c := s.DB("").C(UserAccessToken{}.TableName()) q.UpdatedTime = time.Now() //updated time _, err := c.Upsert(bson.M{"appid": q.AppId, "openid": q.OpenId}, q) return err } func ListUserAccessToken(s *mgo.Session) (list []*UserAccessToken, err error) { c := s.DB("").C(UserAccessToken{}.TableName()) err = c.Find(bson.M{ "updated_time": bson.M{"$lte": time.Now().Add(-110 * time.Minute)}, }).Sort("updated_time").All(&list) return }
mit
artsy/force
src/v2/Apps/Partner/Components/PartnerArtists/PartnerArtistList/PartnerArtistListPlaceholder.tsx
1087
import { Box, Column, GridColumns, SkeletonText } from "@artsy/palette" import { PartnerArtistListContainer } from "./PartnerArtistList" const names = [ "xxxxxxxxxxxxxxx", "xxxxxxxxxx", "xxxxxxxxxxxxx", "xxxxxxxxxxxxxxx", "xxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxx", "xxxxxxxxxxxxxx", "xxxxxxxxxxx", "xxxxxxxxxxxxxxxxx", "xxxxxxxxxxx", "xxxxxxxxxxxxxxx", "xxxxxxxxxx", "xxxxxxxxxxxxx", ] function getName(i: number) { return names[i % names.length] } export const PartnerArtistListPlaceholder: React.FC = () => ( <PartnerArtistListContainer> <GridColumns minWidth={[1100, "auto"]} pr={[2, 0]} gridColumnGap={1}> <Column span={12}> <SkeletonText variant="md">Represented Artists</SkeletonText> <Box style={{ columnCount: 6 }} mt={2}> {[...new Array(60)].map((_, i) => { return ( <SkeletonText key={i} mb={1}> {getName(i)} </SkeletonText> ) })} </Box> </Column> </GridColumns> </PartnerArtistListContainer> )
mit
cjerdonek/open-rcv
openrcv/test/test_contestgen.py
6390
# # Copyright (c) 2014 Chris Jerdonek. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # from contextlib import contextmanager from copy import copy as copy_ import unittest from unittest.mock import patch, MagicMock from openrcv import models, streams from openrcv.contestgen import (make_standard_candidate_names, BallotGenerator, UniqueBallotGenerator, STOP_CHOICE) from openrcv.utiltest.helpers import UnitCase @contextmanager def _temp_ballots_resource(): resource = streams.ListResource() ballots_resource = models.BallotsResource(resource) yield ballots_resource class ModuleTest(UnitCase): def test_make_standard_candidate_names(self): names = make_standard_candidate_names(2) self.assertEqual(names, ['Ann', 'Bob']) names = make_standard_candidate_names(4, names=['A', 'B']) self.assertEqual(names, ['A', 'B', 'Person 3', 'Person 4']) class CopyingMock(MagicMock): def __call__(self, *args, **kwargs): # Shallow copy each arg. args = (copy_(arg) for arg in args) kwargs = {k: copy_(v) for k, v in kwargs} return super().__call__(*args, **kwargs) class BallotGeneratorMixin(object): def patch_sample_one(self, values): # random.sample() returns a k-length list. values = ([v, ] for v in values) return patch('openrcv.contestgen.sample', new_callable=CopyingMock, side_effect=values) class BallotGeneratorTest(UnitCase, BallotGeneratorMixin): def patch_random(self, return_value): return patch('openrcv.contestgen.random', return_value=return_value) def test_init__defaults(self): chooser = BallotGenerator((1, 2, 3)) self.assertEqual(chooser.choices, set([1, 2, 3])) self.assertEqual(chooser.max_length, 3) self.assertEqual(chooser.undervote, 0.1) def test_init__defaults(self): chooser = BallotGenerator((1, 2, 3), max_length=4, undervote=0.5) self.assertEqual(chooser.choices, set([1, 2, 3])) self.assertEqual(chooser.max_length, 4) self.assertEqual(chooser.undervote, 0.5) def test_choose(self): chooser = BallotGenerator((1, 2, 3)) self.assertEqual(chooser.choose([1]), 1) def test_make_choices__undervote(self): chooser = BallotGenerator((1, 2, 3), undervote=0.5) with self.patch_random(0.49): self.assertEqual(chooser.make_choices(), []) with self.patch_random(0.5): ballot = chooser.make_choices() self.assertTrue(len(ballot) > 0) with self.patch_random(0.51): ballot = chooser.make_choices() self.assertTrue(len(ballot) > 0) def test_make_choices__undervote__zero(self): """Check the zero edge case.""" # Zero chance of an undervote. chooser = BallotGenerator((1, 2, 3), undervote=0) with self.patch_random(0): ballot = chooser.make_choices() self.assertTrue(len(ballot) > 0) def test_make_choices(self): chooser = BallotGenerator((1, 2, 3), undervote=0) with self.patch_sample_one((1, 1, STOP_CHOICE)) as mock_sample: self.assertEqual(chooser.make_choices(), [1, 1]) self.assertEqual(mock_sample.call_count, 3) # Also check that random.sample() is being called with the # right args each time. expecteds = [ # The first call does not include STOP_CHOICE to ensure # that the ballot is not an undervote. ({1, 2, 3}, 1), ({1, 2, 3, STOP_CHOICE}, 1), ({1, 2, 3, STOP_CHOICE}, 1), ] for i, (actual, expected) in enumerate(zip(mock_sample.call_args_list, expecteds)): with self.subTest(index=i): # The 0-th element is the positional args. self.assertEqual(actual[0], expected) def test_add_random_ballots(self): chooser = BallotGenerator((1, 2, 3), undervote=0) with _temp_ballots_resource() as ballots_resource: chooser.add_random_ballots(ballots_resource, count=12) self.assertEqual(ballots_resource.count(), 12) class UniqueBallotGeneratorTest(UnitCase, BallotGeneratorMixin): def test_make_choices(self): chooser = UniqueBallotGenerator((1, 2, 3), undervote=0) with self.patch_sample_one((1, 2, STOP_CHOICE)) as mock_sample: self.assertEqual(chooser.make_choices(), [1, 2]) self.assertEqual(mock_sample.call_count, 3) # Also check that random.sample() is being called with the # right args each time (which is where UniqueBallotGenerator # differs from BallotGenerator). expecteds = [ ({1, 2, 3}, 1), # Since this is the unique ballot generator, each call does # not contain any of the previously chosen choices. ({2, 3, STOP_CHOICE}, 1), ({3, STOP_CHOICE}, 1), ] for i, (actual, expected) in enumerate(zip(mock_sample.call_args_list, expecteds)): with self.subTest(index=i): # The 0-th element is the positional args. self.assertEqual(actual[0], expected)
mit
Unobtanium-dev/Unobtanium
src/qt/locale/bitcoin_fi.ts
113257
<?xml version="1.0" ?><!DOCTYPE TS><TS language="fi" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Unobtanium</source> <translation>Tietoa Unobtaniumista</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Unobtanium&lt;/b&gt; version</source> <translation>&lt;b&gt;Unobtanium&lt;/b&gt; versio</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Tämä on kokeellinen ohjelmisto. Levitetään MIT/X11 ohjelmistolisenssin alaisuudessa. Tarkemmat tiedot löytyvät tiedostosta COPYING tai osoitteesta http://www.opensource.org/licenses/mit-license.php. Tämä ohjelma sisältää OpenSSL projektin OpenSSL työkalupakin (http://www.openssl.org/), Eric Youngin (eay@cryptsoft.com) kehittämän salausohjelmiston sekä Thomas Bernardin UPnP ohjelmiston. </translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Tekijänoikeus</translation> </message> <message> <location line="+0"/> <source>The Unobtanium developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Osoitekirja</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Kaksoisnapauta muokataksesi osoitetta tai nimeä</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Luo uusi osoite</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopioi valittu osoite leikepöydälle</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Uusi Osoite</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Unobtanium addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Nämä ovat Unobtanium-osoitteesi joihin voit vastaanottaa maksuja. Voit haluta antaa jokaiselle maksajalle omansa, että pystyt seuraamaan keneltä maksut tulevat.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopioi Osoite</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Näytä &amp;QR-koodi</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Unobtanium address</source> <translation>Allekirjoita viesti todistaaksesi, että omistat Unobtanium-osoitteen</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Allekirjoita &amp;viesti</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Poista valittu osoite listalta</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Vie auki olevan välilehden tiedot tiedostoon</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Unobtanium address</source> <translation>Tarkista viestin allekirjoitus varmistaaksesi, että se allekirjoitettiin tietyllä Unobtanium-osoitteella</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Varmista viesti...</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Poista</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Unobtanium addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopioi &amp;Nimi</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Muokkaa</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Lähetä &amp;Rahaa</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Vie osoitekirja</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Virhe viedessä osoitekirjaa</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ei voida kirjoittaa tiedostoon %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Nimi</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(ei nimeä)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Tunnuslauseen Dialogi</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Kirjoita tunnuslause</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Uusi tunnuslause</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Kiroita uusi tunnuslause uudelleen</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Anna lompakolle uusi tunnuslause.&lt;br/&gt;Käytä tunnuslausetta, jossa on ainakin &lt;b&gt;10 satunnaista mekkiä&lt;/b&gt; tai &lt;b&gt;kahdeksan sanaa&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Salaa lompakko</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Tätä toimintoa varten sinun täytyy antaa lompakon tunnuslause sen avaamiseksi.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Avaa lompakko</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Tätä toimintoa varten sinun täytyy antaa lompakon tunnuslause salauksen purkuun.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Pura lompakon salaus</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Vaihda tunnuslause</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Anna vanha ja uusi tunnuslause.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Vahvista lompakon salaus</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL YOUR UNOBTANIUM&lt;/b&gt;!</source> <translation>Varoitus: Jos salaat lompakkosi ja menetät tunnuslauseesi, &lt;b&gt;MENETÄT KAIKKI UNOBTANIUMISI&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Haluatko varmasti salata lompakkosi?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>TÄRKEÄÄ: Kaikki vanhat lompakon varmuuskopiot pitäisi korvata uusilla suojatuilla varmuuskopioilla. Turvallisuussyistä edelliset varmuuskopiot muuttuvat turhiksi, kun aloitat suojatun lompakon käytön.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Varoitus: Caps Lock on käytössä!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Lompakko salattu</translation> </message> <message> <location line="-56"/> <source>Unobtanium will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your unobtaniums from being stolen by malware infecting your computer.</source> <translation>Unobtanium sulkeutuu lopettaakseen salausprosessin. Muista, että salattukaan lompakko ei täysin suojaa sitä haittaohjelmien aiheuttamilta varkauksilta.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Lompakon salaus epäonnistui</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Lompakon salaaminen epäonnistui sisäisen virheen vuoksi. Lompakkoasi ei salattu.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Annetut tunnuslauseet eivät täsmää.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Lompakon avaaminen epäonnistui.</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Annettu tunnuslause oli väärä.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Lompakon salauksen purku epäonnistui.</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Lompakon tunnuslause vaihdettiin onnistuneesti.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Allekirjoita viesti...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Synkronoidaan verkon kanssa...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Yleisnäkymä</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Lompakon tilanteen yleiskatsaus</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Rahansiirrot</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Selaa rahansiirtohistoriaa</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Muokkaa tallennettujen nimien ja osoitteiden listaa</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Näytä Unobtaniumien vastaanottamiseen käytetyt osoitteet</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>L&amp;opeta</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Sulje ohjelma</translation> </message> <message> <location line="+4"/> <source>Show information about Unobtanium</source> <translation>Näytä tietoa Unobtanium-projektista</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Tietoja &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Näytä tietoja QT:ta</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Asetukset...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Salaa lompakko...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Varmuuskopioi Lompakko...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Vaihda Tunnuslause...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Tuodaan lohkoja levyltä</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Ladataan lohkoindeksiä...</translation> </message> <message> <location line="-347"/> <source>Send coins to a Unobtanium address</source> <translation>Lähetä kolikoita Unobtanium-osoitteeseen</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Unobtanium</source> <translation>Muuta Unobtaniumin konfiguraatioasetuksia</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Varmuuskopioi lompakko toiseen sijaintiin</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Vaihda lompakon salaukseen käytettävä tunnuslause</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Testausikkuna</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Avaa debuggaus- ja diagnostiikkakonsoli</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>Varmista &amp;viesti...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Unobtanium</source> <translation>Unobtanium</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Lompakko</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Lähetä</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Vastaanota</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Osoitteet</translation> </message> <message> <location line="+22"/> <source>&amp;About Unobtanium</source> <translation>&amp;Tietoa Unobtaniumista</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Näytä / Piilota</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Näytä tai piilota Unobtanium-ikkuna</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Suojaa yksityiset avaimet, jotka kuuluvat lompakkoosi</translation> </message> <message> <location line="+7"/> <source>Sign messages with your Unobtanium addresses to prove you own them</source> <translation>Allekirjoita viestisi omalla Unobtanium -osoitteellasi todistaaksesi, että omistat ne</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Unobtanium addresses</source> <translation>Varmista, että viestisi on allekirjoitettu määritetyllä Unobtanium -osoitteella</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Tiedosto</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Asetukset</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Apua</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Välilehtipalkki</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>Unobtanium client</source> <translation>Unobtanium-asiakas</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Unobtanium network</source> <translation><numerusform>%n aktiivinen yhteys Unobtanium-verkkoon</numerusform><numerusform>%n aktiivista yhteyttä Unobtanium-verkkoon</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Käsitelty %1 lohkoa rahansiirtohistoriasta</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n tunti</numerusform><numerusform>%n tuntia</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n viikko</numerusform><numerusform>%n viikkoa</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Viimeisin vastaanotettu lohko tuotettu %1.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>Virhe</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Varoitus</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Tietoa</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Rahansiirtohistoria on ajan tasalla</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Saavutetaan verkkoa...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Vahvista maksukulu</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Lähetetyt rahansiirrot</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Saapuva rahansiirto</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Päivä: %1 Määrä: %2 Tyyppi: %3 Osoite: %4</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI käsittely</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Unobtanium address or malformed URI parameters.</source> <translation>URIa ei voitu jäsentää! Tämä voi johtua kelvottomasta Unobtanium-osoitteesta tai virheellisistä URI parametreista.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Lompakko on &lt;b&gt;salattu&lt;/b&gt; ja tällä hetkellä &lt;b&gt;avoinna&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Lompakko on &lt;b&gt;salattu&lt;/b&gt; ja tällä hetkellä &lt;b&gt;lukittuna&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Unobtanium can no longer continue safely and will quit.</source> <translation>Peruuttamaton virhe on tapahtunut. Unobtanium ei voi enää jatkaa turvallisesti ja sammutetaan.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Verkkohälytys</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Muokkaa osoitetta</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Nimi</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Tähän osoitteeseen liitetty nimi</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Osoite</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Osoite, joka liittyy tämän osoitekirjan merkintään. Tätä voidaan muuttaa vain lähtevissä osoitteissa.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Uusi vastaanottava osoite</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Uusi lähettävä osoite</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Muokkaa vastaanottajan osoitetta</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Muokkaa lähtevää osoitetta</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Osoite &quot;%1&quot; on jo osoitekirjassa.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Unobtanium address.</source> <translation>Antamasi osoite &quot;%1&quot; ei ole validi Unobtanium-osoite.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Lompakkoa ei voitu avata.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Uuden avaimen luonti epäonnistui.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Unobtanium-Qt</source> <translation>Unobtanium-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versio</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Käyttö:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>komentorivi parametrit</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Käyttöliittymäasetukset</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Set language, for example &quot;de_DE&quot; (default: system locale)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Käynnistä pienennettynä</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Näytä aloitusruutu käynnistettäessä (oletus: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Asetukset</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Yleiset</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Maksa rahansiirtopalkkio</translation> </message> <message> <location line="+31"/> <source>Automatically start Unobtanium after logging in to the system.</source> <translation>Käynnistä Unobtanium kirjautumisen yhteydessä.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Unobtanium on system login</source> <translation>&amp;Käynnistä Unobtanium kirjautumisen yhteydessä</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Verkko</translation> </message> <message> <location line="+6"/> <source>Automatically open the Unobtanium client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Avaa Unobtanium-asiakasohjelman portti reitittimellä automaattisesti. Tämä toimii vain, jos reitittimesi tukee UPnP:tä ja se on käytössä.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Portin uudelleenohjaus &amp;UPnP:llä</translation> </message> <message> <location line="+7"/> <source>Connect to the Unobtanium network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Ota yhteys Unobtanium-verkkoon SOCKS-proxyn läpi (esimerkiksi kun haluat käyttää Tor-verkkoa).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Ota yhteys SOCKS-proxyn kautta:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxyn &amp;IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Välityspalvelimen IP-osoite (esim. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Portti</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Proxyn Portti (esim. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Versio:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Proxyn SOCKS-versio (esim. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Ikkuna</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Näytä ainoastaan ilmaisinalueella ikkunan pienentämisen jälkeen.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Pienennä ilmaisinalueelle työkalurivin sijasta</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Ikkunaa suljettaessa vain pienentää Unobtanium-ohjelman ikkunan lopettamatta itse ohjelmaa. Kun tämä asetus on valittuna, ohjelman voi sulkea vain valitsemalla Lopeta ohjelman valikosta.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>P&amp;ienennä suljettaessa</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Käyttöliittymä</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Käyttöliittymän kieli</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Unobtanium.</source> <translation>Tässä voit määritellä käyttöliittymän kielen. Muutokset astuvat voimaan seuraavan kerran, kun Unobtanium käynnistetään.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>Yksikkö jona unobtanium-määrät näytetään</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Valitse mitä yksikköä käytetään ensisijaisesti unobtanium-määrien näyttämiseen.</translation> </message> <message> <location line="+9"/> <source>Whether to show Unobtanium addresses in the transaction list or not.</source> <translation>Näytetäänkö Unobtanium-osoitteet rahansiirrot listassa vai ei.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Näytä osoitteet rahansiirrot listassa</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Peruuta</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Hyväksy</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>oletus</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Varoitus</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Unobtanium.</source> <translation>Tämä asetus astuu voimaan seuraavalla kerralla, kun Unobtanium käynnistetään.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Antamasi proxy-osoite on virheellinen.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Lomake</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Unobtanium network after a connection is established, but this process has not completed yet.</source> <translation>Näytetyt tiedot eivät välttämättä ole ajantasalla. Lompakkosi synkronoituu Unobtanium-verkon kanssa automaattisesti yhteyden muodostamisen jälkeen, mutta synkronointi on vielä meneillään.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Vahvistamatta:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Lompakko</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Epäkypsää:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Louhittu saldo, joka ei ole vielä kypsynyt</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Viimeisimmät rahansiirrot&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Tililläsi tällä hetkellä olevien Unobtaniumien määrä</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Niiden saapuvien rahansiirtojen määrä, joita Unobtanium-verkko ei vielä ole ehtinyt vahvistaa ja siten eivät vielä näy saldossa.</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>Ei ajan tasalla</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start unobtanium: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR-koodi Dialogi</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Vastaanota maksu</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Määrä:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Tunniste:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Viesti:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Tallenna nimellä...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Virhe käännettäessä URI:a QR-koodiksi.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Syötetty määrä on virheellinen. Tarkista kirjoitusasu.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Tuloksen URI liian pitkä, yritä lyhentää otsikon tekstiä / viestiä.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Tallenna QR-koodi</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG kuvat (*png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Pääteohjelman nimi</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>Ei saatavilla</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Pääteohjelman versio</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>T&amp;ietoa</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Käytössä oleva OpenSSL-versio</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Käynnistysaika</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Verkko</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Yhteyksien lukumäärä</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Käyttää testiverkkoa</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Lohkoketju</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Nykyinen Lohkojen määrä</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Arvioitu lohkojen kokonaismäärä</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Viimeisimmän lohkon aika</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Avaa</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Komentorivi parametrit</translation> </message> <message> <location line="+7"/> <source>Show the Unobtanium-Qt help message to get a list with possible Unobtanium command-line options.</source> <translation>Näytä Unobtanium-Qt komentoriviparametrien ohjesivu, jossa on listattuna mahdolliset komentoriviparametrit.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Näytä</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konsoli</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Kääntöpäiväys</translation> </message> <message> <location line="-104"/> <source>Unobtanium - Debug window</source> <translation>Unobtanium - Debug ikkuna</translation> </message> <message> <location line="+25"/> <source>Unobtanium Core</source> <translation>Unobtanium-ydin</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Debug lokitiedosto</translation> </message> <message> <location line="+7"/> <source>Open the Unobtanium debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Avaa lokitiedosto nykyisestä data-kansiosta. Tämä voi viedä useamman sekunnin, jos lokitiedosto on iso.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Tyhjennä konsoli</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Unobtanium RPC console.</source> <translation>Tervetuloa Unobtanium RPC konsoliin.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Ylös- ja alas-nuolet selaavat historiaa ja &lt;b&gt;Ctrl-L&lt;/b&gt; tyhjentää ruudun.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Kirjoita &lt;b&gt;help&lt;/b&gt; nähdäksesi yleiskatsauksen käytettävissä olevista komennoista.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Lähetä Unobtaniumeja</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Lähetä monelle vastaanottajalle</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Lisää &amp;Vastaanottaja</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Poista kaikki rahansiirtokentät</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>&amp;Tyhjennnä Kaikki</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123,456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Vahvista lähetys</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Lähetä</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Hyväksy Unobtaniumien lähettäminen</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Haluatko varmasti lähettää %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> ja </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Vastaanottajan osoite on virheellinen. Tarkista osoite.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Maksettavan summan tulee olla suurempi kuin 0 Unobtaniumia.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Määrä ylittää käytettävissä olevan saldon.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Kokonaismäärä ylittää saldosi kun %1 maksukulu lisätään summaan.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Sama osoite toistuu useamman kerran. Samaan osoitteeseen voi lähettää vain kerran per maksu.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Virhe: Rahansiirto hylättiin. Tämä voi tapahtua jos jotkin unobtaniumeistasi on jo käytetty, esimerkiksi jos olet käyttänyt kopiota wallet.dat-lompakkotiedostosta ja unobtaniumit on merkitty käytetyksi vain kopiossa.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Lomake</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>M&amp;äärä:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Maksun saaja:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Anna nimi tälle osoitteelle, jos haluat lisätä sen osoitekirjaan</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Nimi:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Valitse osoite osoitekirjasta</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Liitä osoite leikepöydältä</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Poista </translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Unobtanium address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Anna Unobtanium-osoite (esim. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Allekirjoitukset - Allekirjoita / Varmista viesti</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Allekirjoita viesti</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Voit allekirjoittaa viestit omalla osoitteellasi todistaaksesi että omistat ne. Ole huolellinen, että et allekirjoita mitään epämääräistä, phishing-hyökkääjät voivat huijata sinua allekirjoittamaan luovuttamalla henkilöllisyytesi. Allekirjoita selvitys täysin yksityiskohtaisesti mihin olet sitoutunut.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Osoite, jolla viesti allekirjoitetaan (esimerkiksi 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Valitse osoite osoitekirjasta</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Liitä osoite leikepöydältä</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Kirjoita tähän viesti minkä haluat allekirjoittaa</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Allekirjoitus</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Kopioi tämänhetkinen allekirjoitus leikepöydälle</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Unobtanium address</source> <translation>Allekirjoita viesti todistaaksesi, että omistat tämän Unobtanium-osoitteen</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Allekirjoita &amp;viesti</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Tyhjennä kaikki allekirjoita-viesti-kentät</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>&amp;Tyhjennä Kaikki</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Varmista viesti</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Syötä allekirjoittava osoite, viesti ja allekirjoitus alla oleviin kenttiin varmistaaksesi allekirjoituksen aitouden. Varmista että kopioit kaikki kentät täsmälleen oikein, myös rivinvaihdot, välilyönnit, tabulaattorit, jne.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Osoite, jolla viesti allekirjoitettiin (esimerkiksi 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Unobtanium address</source> <translation>Tarkista viestin allekirjoitus varmistaaksesi, että se allekirjoitettiin tietyllä Unobtanium-osoitteella</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Tyhjennä kaikki varmista-viesti-kentät</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Unobtanium address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Anna Unobtanium-osoite (esim. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Klikkaa &quot;Allekirjoita Viesti luodaksesi allekirjoituksen </translation> </message> <message> <location line="+3"/> <source>Enter Unobtanium signature</source> <translation>Syötä Unobtanium-allekirjoitus</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Syötetty osoite on virheellinen.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Tarkista osoite ja yritä uudelleen.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Syötetyn osoitteen avainta ei löydy.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Lompakon avaaminen peruttiin.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Yksityistä avainta syötetylle osoitteelle ei ole saatavilla.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Viestin allekirjoitus epäonnistui.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Viesti allekirjoitettu.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Allekirjoitusta ei pystytty tulkitsemaan.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Tarkista allekirjoitus ja yritä uudelleen.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Allekirjoitus ei täsmää viestin tiivisteeseen.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Viestin varmistus epäonnistui.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Viesti varmistettu.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+25"/> <source>The Unobtanium developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Avoinna %1 asti</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/vahvistamaton</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 vahvistusta</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Tila</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>lähetetty %n noodin läpi</numerusform><numerusform>lähetetty %n noodin läpi</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Päivämäärä</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Lähde</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generoitu</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Lähettäjä</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Saaja</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>oma osoite</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>nimi</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Credit</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>kypsyy %n lohkon kuluttua</numerusform><numerusform>kypsyy %n lohkon kuluttua</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>ei hyväksytty</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debit</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Maksukulu</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Netto määrä</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Viesti</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Viesti</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Siirtotunnus</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Generoitujen kolikoiden täytyy kypsyä 120 lohkon ajan ennen kuin ne voidaan lähettää. Kun loit tämän lohkon, se lähetettiin verkkoon lisättäväksi lohkoketjuun. Jos se ei päädy osaksi lohkoketjua, sen tila vaihtuu &quot;ei hyväksytty&quot; ja sitä ei voida lähettää. Näin voi joskus käydä, jos toinen noodi löytää lohkon muutamaa sekuntia ennen tai jälkeen sinun lohkosi löytymisen.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Debug tiedot</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Rahansiirto</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Sisääntulot</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Määrä</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>tosi</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>epätosi</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ei ole vielä onnistuneesti lähetetty</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>tuntematon</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Rahansiirron yksityiskohdat</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Tämä ruutu näyttää yksityiskohtaisen tiedon rahansiirrosta</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Päivämäärä</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Laatu</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Määrä</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Avoinna %1 asti</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Ei yhteyttä verkkoon (%1 vahvistusta)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Vahvistamatta (%1/%2 vahvistusta)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Vahvistettu (%1 vahvistusta)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Louhittu saldo on käytettävissä kun se kypsyy %n lohkon päästä</numerusform><numerusform>Louhittu saldo on käytettävissä kun se kypsyy %n lohkon päästä</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Tätä lohkoa ei vastaanotettu mistään muusta solmusta ja sitä ei mahdollisesti hyväksytä!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generoitu mutta ei hyväksytty</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Vastaanotettu osoitteella</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Vastaanotettu</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Saaja</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Maksu itsellesi</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Louhittu</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(ei saatavilla)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Rahansiirron tila. Siirrä osoitin kentän päälle nähdäksesi vahvistusten lukumäärä.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Rahansiirron vastaanottamisen päivämäärä ja aika.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Rahansiirron laatu.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Rahansiirron kohteen Unobtanium-osoite</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Saldoon lisätty tai siitä vähennetty määrä.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Kaikki</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Tänään</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Tällä viikolla</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Tässä kuussa</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Viime kuussa</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Tänä vuonna</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Alue...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Vastaanotettu osoitteella</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Saaja</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Itsellesi</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Louhittu</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Muu</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Anna etsittävä osoite tai tunniste</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Minimimäärä</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopioi osoite</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopioi nimi</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopioi määrä</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Muokkaa nimeä</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Näytä rahansiirron yksityiskohdat</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Vie rahansiirron tiedot</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Vahvistettu</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Aika</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Laatu</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Nimi</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Määrä</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Virhe tietojen viennissä</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ei voida kirjoittaa tiedostoon %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Alue:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>kenelle</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Lähetä Unobtaniumeja</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Vie auki olevan välilehden tiedot tiedostoon</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Varmuuskopio Onnistui</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Unobtanium version</source> <translation>Unobtaniumin versio</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Käyttö:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or unobtaniumd</source> <translation>Lähetä käsky palvelimelle tai unobtaniumd:lle</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Lista komennoista</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Hanki apua käskyyn</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Asetukset:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: unobtanium.conf)</source> <translation>Määritä asetustiedosto (oletus: unobtanium.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: unobtaniumd.pid)</source> <translation>Määritä pid-tiedosto (oletus: unobtanium.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Määritä data-hakemisto</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Aseta tietokannan välimuistin koko megatavuina (oletus: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>Kuuntele yhteyksiä portista &lt;port&gt; (oletus: 8333 tai testnet: 18333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Pidä enintään &lt;n&gt; yhteyttä verkkoihin (oletus: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Yhdistä noodiin hakeaksesi naapurien osoitteet ja katkaise yhteys</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Määritä julkinen osoitteesi</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Kynnysarvo aikakatkaisulle heikosti toimiville verkoille (oletus: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Sekuntien määrä, kuinka kauan uudelleenkytkeydytään verkkoihin (oletus: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Virhe valmisteltaessa RPC-portin %u avaamista kuunneltavaksi: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation>Kuuntele JSON-RPC -yhteyksiä portista &lt;port&gt; (oletus: 8332 or testnet: 18332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Hyväksy merkkipohjaiset- ja JSON-RPC-käskyt</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Aja taustalla daemonina ja hyväksy komennot</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Käytä test -verkkoa</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Hyväksy yhteyksiä ulkopuolelta (vakioasetus: 1 jos -proxy tai -connect ei määritelty)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=unobtaniumrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Unobtanium Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Virhe ilmennyt asetettaessa RPC-porttia %u IPv6:n kuuntelemiseksi, palataan takaisin IPv4:ään %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Unobtanium is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Aseta suurin korkean prioriteetin / matalan palkkion siirron koko tavuissa (vakioasetus: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Varoitus: -paytxfee on asetettu erittäin korkeaksi! Tämä on maksukulu jonka tulet maksamaan kun lähetät siirron.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Varoitus: Näytetyt siirrot eivät välttämättä pidä paikkaansa! Sinun tai toisten noodien voi olla tarpeen asentaa päivitys.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Unobtanium will not work properly.</source> <translation>Varoitus: Tarkista että tietokoneesi kellonaika ja päivämäärä ovat paikkansapitäviä! Unobtanium ei toimi oikein väärällä päivämäärällä ja/tai kellonajalla.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Lohkon luonnin asetukset:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Yhidstä ainoastaan määrättyihin noodeihin</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Hae oma IP osoite (vakioasetus: 1 kun kuuntelemassa ja ei -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Virhe avattaessa lohkoindeksiä</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Varoitus: Levytila on vähissä!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Virhe: Järjestelmävirhe</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Ei onnistuttu kuuntelemaan missään portissa. Käytä -listen=0 jos haluat tätä.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Lohkon kirjoitus epäonnistui</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Hae naapureita DNS hauilla (vakioasetus: 1 paitsi jos -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Tuodaan lohkoja ulkoisesta blk000??.dat tiedostosta</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation>Tietoa</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Virheellinen -tor osoite &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Suurin vastaanottopuskuri yksittäiselle yhteydelle, &lt;n&gt;*1000 tavua (vakioasetus: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Suurin lähetyspuskuri yksittäiselle yhteydelle, &lt;n&gt;*1000 tavua (vakioasetus: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Yhdistä vain noodeihin verkossa &lt;net&gt; (IPv4, IPv6 tai Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Tulosta enemmän debug tietoa. Aktivoi kaikki -debug* asetukset</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Tulosta lisää verkkoyhteys debug tietoa</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Lisää debuggaustiedon tulostukseen aikaleima</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Unobtanium Wiki for SSL setup instructions)</source> <translation>SSL asetukset (katso Unobtanium Wikistä tarkemmat SSL ohjeet)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Valitse käytettävän SOCKS-proxyn versio (4-5, vakioasetus: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Lähetä jäljitys/debug-tieto konsoliin, debug.log-tiedoston sijaan</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Lähetä jäljitys/debug-tieto debuggeriin</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Aseta suurin lohkon koko tavuissa (vakioasetus: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Asetan pienin lohkon koko tavuissa (vakioasetus: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Pienennä debug.log tiedosto käynnistyksen yhteydessä (vakioasetus: 1 kun ei -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Määritä yhteyden aikakataisu millisekunneissa (vakioasetus: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Järjestelmävirhe:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Käytä UPnP:tä kuunneltavan portin avaamiseen (vakioasetus: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Käytä UPnP:tä kuunneltavan portin avaamiseen (vakioasetus: 1 kun kuuntelemassa)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Käytä proxyä tor yhteyksien avaamiseen (vakioasetus: sama kuin -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Käyttäjätunnus JSON-RPC-yhteyksille</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Varoitus</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Varoitus: Tämä versio on vanhentunut, päivitys tarpeen!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Salasana JSON-RPC-yhteyksille</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Salli JSON-RPC yhteydet tietystä ip-osoitteesta</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Lähetä käskyjä solmuun osoitteessa &lt;ip&gt; (oletus: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Suorita käsky kun paras lohko muuttuu (%s cmd on vaihdettu block hashin kanssa)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Päivitä lompakko uusimpaan formaattiin</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Aseta avainpoolin koko arvoon &lt;n&gt; (oletus: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Skannaa uudelleen lohkoketju lompakon puuttuvien rahasiirtojen vuoksi</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Käytä OpenSSL:ää (https) JSON-RPC-yhteyksille</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Palvelimen sertifikaatti-tiedosto (oletus: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Palvelimen yksityisavain (oletus: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Hyväksyttävä salaus (oletus: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Tämä ohjeviesti</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Kytkeytyminen %s tällä tietokonella ei onnistu (kytkeytyminen palautti virheen %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Yhdistä socks proxyn läpi</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Salli DNS kyselyt -addnode, -seednode ja -connect yhteydessä</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Ladataan osoitteita...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa: Lompakko vioittunut</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Unobtanium</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa: Tarvitset uudemman version Unobtaniumista</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Unobtanium to complete</source> <translation>Lompakko tarvitsee uudelleenkirjoittaa: käynnistä Unobtanium uudelleen</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Virheellinen proxy-osoite &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Tuntematon verkko -onlynet parametrina: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Tuntematon -socks proxy versio pyydetty: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>-bind osoitteen &apos;%s&apos; selvittäminen epäonnistui</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>-externalip osoitteen &apos;%s&apos; selvittäminen epäonnistui</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>-paytxfee=&lt;amount&gt;: &apos;%s&apos; on virheellinen</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Virheellinen määrä</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Lompakon saldo ei riitä</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Ladataan lohkoindeksiä...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Linää solmu mihin liittyä pitääksesi yhteyden auki</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Unobtanium is probably already running.</source> <translation>Kytkeytyminen %s ei onnistu tällä tietokoneella. Unobtanium on todennäköisesti jo ajamassa.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Rahansiirtopalkkio per KB lisätään lähettämääsi rahansiirtoon</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Ladataan lompakkoa...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Et voi päivittää lompakkoasi vanhempaan versioon</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Oletusosoitetta ei voi kirjoittaa</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Skannataan uudelleen...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Lataus on valmis</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Käytä %s optiota</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Virhe</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Sinun täytyy asettaa rpcpassword=&lt;password&gt; asetustiedostoon: %s Jos tiedostoa ei ole, niin luo se ainoastaan omistajan kirjoitusoikeuksin.</translation> </message> </context> </TS>
mit
hovsepm/AutoRest
src/generator/AutoRest.CSharp.Azure.Fluent.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ArrayOperations.cs
36000
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureCompositeModelClient { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ArrayOperations operations. /// </summary> internal partial class ArrayOperations : IServiceOperations<AzureCompositeModel>, IArrayOperations { /// <summary> /// Initializes a new instance of the ArrayOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ArrayOperations(AzureCompositeModel client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AzureCompositeModel /// </summary> public AzureCompositeModel Client { get; private set; } /// <summary> /// Get complex types with array property /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ArrayWrapper>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/valid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ArrayWrapper>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types with array property /// </summary> /// <param name='array'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(IList<string> array = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { ArrayWrapper complexBody = new ArrayWrapper(); if (array != null) { complexBody.Array = array; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/valid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(complexBody != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get complex types with array property which is empty /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ArrayWrapper>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ArrayWrapper>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types with array property which is empty /// </summary> /// <param name='array'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutEmptyWithHttpMessagesAsync(IList<string> array = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { ArrayWrapper complexBody = new ArrayWrapper(); if (array != null) { complexBody.Array = array; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutEmpty", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(complexBody != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get complex types with array property while server doesn't provide a /// response payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ArrayWrapper>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/notprovided").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ArrayWrapper>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
mit
DigitalState/Core
src/Exception/DependencyInjection/Configuration.php
523
<?php namespace Ds\Component\Exception\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * Class Configuration * * @package Ds\Component\Exception */ final class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $builder = new TreeBuilder; $node = $builder->root('ds_exception'); return $builder; } }
mit
LugosFingite/LudOS
external/libc++/__debug.hpp
8318
// -*- C++ -*- //===--------------------------- __debug ----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef _LIBCPP_DEBUG_H #define _LIBCPP_DEBUG_H #include "__config.hpp" #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) #pragma GCC system_header #endif #if defined(_LIBCPP_HAS_NO_NULLPTR) # include <cstddef> #endif #if _LIBCPP_DEBUG_LEVEL >= 1 || defined(_LIBCPP_BUILDING_LIBRARY) # include <stdlib.h> # include <stdio.h> # include <stddef.h> #endif #if _LIBCPP_DEBUG_LEVEL >= 1 && !defined(_LIBCPP_ASSERT) # define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : \ _VSTD::__libcpp_debug_function(_VSTD::__libcpp_debug_info(__FILE__, __LINE__, #x, m))) #endif #if _LIBCPP_DEBUG_LEVEL >= 2 #ifndef _LIBCPP_DEBUG_ASSERT #define _LIBCPP_DEBUG_ASSERT(x, m) _LIBCPP_ASSERT(x, m) #endif #define _LIBCPP_DEBUG_MODE(...) __VA_ARGS__ #endif #ifndef _LIBCPP_ASSERT # define _LIBCPP_ASSERT(x, m) ((void)0) #endif #ifndef _LIBCPP_DEBUG_ASSERT # define _LIBCPP_DEBUG_ASSERT(x, m) ((void)0) #endif #ifndef _LIBCPP_DEBUG_MODE #define _LIBCPP_DEBUG_MODE(...) ((void)0) #endif #if _LIBCPP_DEBUG_LEVEL < 1 class _LIBCPP_EXCEPTION_ABI __libcpp_debug_exception; #endif _LIBCPP_BEGIN_NAMESPACE_STD struct _LIBCPP_TEMPLATE_VIS __libcpp_debug_info { _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR __libcpp_debug_info() : __file_(nullptr), __line_(-1), __pred_(nullptr), __msg_(nullptr) {} _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR __libcpp_debug_info(const char* __f, int __l, const char* __p, const char* __m) : __file_(__f), __line_(__l), __pred_(__p), __msg_(__m) {} const char* __file_; int __line_; const char* __pred_; const char* __msg_; }; /// __libcpp_debug_function_type - The type of the assertion failure handler. typedef void(*__libcpp_debug_function_type)(__libcpp_debug_info const&); /// __libcpp_debug_function - The handler function called when a _LIBCPP_ASSERT /// fails. extern _LIBCPP_EXTERN_VIS __libcpp_debug_function_type __libcpp_debug_function; /// __libcpp_abort_debug_function - A debug handler that aborts when called. _LIBCPP_NORETURN _LIBCPP_FUNC_VIS void __libcpp_abort_debug_function(__libcpp_debug_info const&); /// __libcpp_throw_debug_function - A debug handler that throws /// an instance of __libcpp_debug_exception when called. _LIBCPP_NORETURN _LIBCPP_FUNC_VIS void __libcpp_throw_debug_function(__libcpp_debug_info const&); /// __libcpp_set_debug_function - Set the debug handler to the specified /// function. _LIBCPP_FUNC_VIS bool __libcpp_set_debug_function(__libcpp_debug_function_type __func); // Setup the throwing debug handler during dynamic initialization. #if _LIBCPP_DEBUG_LEVEL >= 1 && defined(_LIBCPP_DEBUG_USE_EXCEPTIONS) # if defined(_LIBCPP_NO_EXCEPTIONS) # error _LIBCPP_DEBUG_USE_EXCEPTIONS cannot be used when exceptions are disabled. # endif static bool __init_dummy = __libcpp_set_debug_function(__libcpp_throw_debug_function); #endif #if _LIBCPP_DEBUG_LEVEL >= 2 || defined(_LIBCPP_BUILDING_LIBRARY) struct _LIBCPP_TYPE_VIS __c_node; struct _LIBCPP_TYPE_VIS __i_node { void* __i_; __i_node* __next_; __c_node* __c_; #ifndef _LIBCPP_CXX03_LANG __i_node(const __i_node&) = delete; __i_node& operator=(const __i_node&) = delete; #else private: __i_node(const __i_node&); __i_node& operator=(const __i_node&); public: #endif _LIBCPP_INLINE_VISIBILITY __i_node(void* __i, __i_node* __next, __c_node* __c) : __i_(__i), __next_(__next), __c_(__c) {} ~__i_node(); }; struct _LIBCPP_TYPE_VIS __c_node { void* __c_; __c_node* __next_; __i_node** beg_; __i_node** end_; __i_node** cap_; #ifndef _LIBCPP_CXX03_LANG __c_node(const __c_node&) = delete; __c_node& operator=(const __c_node&) = delete; #else private: __c_node(const __c_node&); __c_node& operator=(const __c_node&); public: #endif _LIBCPP_INLINE_VISIBILITY __c_node(void* __c, __c_node* __next) : __c_(__c), __next_(__next), beg_(nullptr), end_(nullptr), cap_(nullptr) {} virtual ~__c_node(); virtual bool __dereferenceable(const void*) const = 0; virtual bool __decrementable(const void*) const = 0; virtual bool __addable(const void*, ptrdiff_t) const = 0; virtual bool __subscriptable(const void*, ptrdiff_t) const = 0; void __add(__i_node* __i); _LIBCPP_HIDDEN void __remove(__i_node* __i); }; template <class _Cont> struct _C_node : public __c_node { _C_node(void* __c, __c_node* __n) : __c_node(__c, __n) {} virtual bool __dereferenceable(const void*) const; virtual bool __decrementable(const void*) const; virtual bool __addable(const void*, ptrdiff_t) const; virtual bool __subscriptable(const void*, ptrdiff_t) const; }; template <class _Cont> inline bool _C_node<_Cont>::__dereferenceable(const void* __i) const { typedef typename _Cont::const_iterator iterator; const iterator* __j = static_cast<const iterator*>(__i); _Cont* _Cp = static_cast<_Cont*>(__c_); return _Cp->__dereferenceable(__j); } template <class _Cont> inline bool _C_node<_Cont>::__decrementable(const void* __i) const { typedef typename _Cont::const_iterator iterator; const iterator* __j = static_cast<const iterator*>(__i); _Cont* _Cp = static_cast<_Cont*>(__c_); return _Cp->__decrementable(__j); } template <class _Cont> inline bool _C_node<_Cont>::__addable(const void* __i, ptrdiff_t __n) const { typedef typename _Cont::const_iterator iterator; const iterator* __j = static_cast<const iterator*>(__i); _Cont* _Cp = static_cast<_Cont*>(__c_); return _Cp->__addable(__j, __n); } template <class _Cont> inline bool _C_node<_Cont>::__subscriptable(const void* __i, ptrdiff_t __n) const { typedef typename _Cont::const_iterator iterator; const iterator* __j = static_cast<const iterator*>(__i); _Cont* _Cp = static_cast<_Cont*>(__c_); return _Cp->__subscriptable(__j, __n); } class _LIBCPP_TYPE_VIS __libcpp_db { __c_node** __cbeg_; __c_node** __cend_; size_t __csz_; __i_node** __ibeg_; __i_node** __iend_; size_t __isz_; __libcpp_db(); public: #ifndef _LIBCPP_CXX03_LANG __libcpp_db(const __libcpp_db&) = delete; __libcpp_db& operator=(const __libcpp_db&) = delete; #else private: __libcpp_db(const __libcpp_db&); __libcpp_db& operator=(const __libcpp_db&); public: #endif ~__libcpp_db(); class __db_c_iterator; class __db_c_const_iterator; class __db_i_iterator; class __db_i_const_iterator; __db_c_const_iterator __c_end() const; __db_i_const_iterator __i_end() const; template <class _Cont> _LIBCPP_INLINE_VISIBILITY void __insert_c(_Cont* __c) { __c_node* __n = __insert_c(static_cast<void*>(__c)); ::new(__n) _C_node<_Cont>(__n->__c_, __n->__next_); } void __insert_i(void* __i); __c_node* __insert_c(void* __c); void __erase_c(void* __c); void __insert_ic(void* __i, const void* __c); void __iterator_copy(void* __i, const void* __i0); void __erase_i(void* __i); void* __find_c_from_i(void* __i) const; void __invalidate_all(void* __c); __c_node* __find_c_and_lock(void* __c) const; __c_node* __find_c(void* __c) const; void unlock() const; void swap(void* __c1, void* __c2); bool __dereferenceable(const void* __i) const; bool __decrementable(const void* __i) const; bool __addable(const void* __i, ptrdiff_t __n) const; bool __subscriptable(const void* __i, ptrdiff_t __n) const; bool __less_than_comparable(const void* __i, const void* __j) const; private: _LIBCPP_HIDDEN __i_node* __insert_iterator(void* __i); _LIBCPP_HIDDEN __i_node* __find_iterator(const void* __i) const; friend _LIBCPP_FUNC_VIS __libcpp_db* __get_db(); }; _LIBCPP_FUNC_VIS __libcpp_db* __get_db(); _LIBCPP_FUNC_VIS const __libcpp_db* __get_const_db(); #endif // _LIBCPP_DEBUG_LEVEL >= 2 || defined(_LIBCPP_BUILDING_LIBRARY) _LIBCPP_END_NAMESPACE_STD #endif // _LIBCPP_DEBUG_H
mit
nathannfan/azure-sdk-for-net
src/SDKs/CognitiveServices/dataPlane/Vision/Microsoft.CognitiveServices.Vision/Generated/Face/FaceOperations.cs
56933
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.CognitiveServices.Vision.Face { using Microsoft.CognitiveServices; using Microsoft.CognitiveServices.Vision; using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// FaceOperations operations. /// </summary> public partial class FaceOperations : IServiceOperations<FaceAPI>, IFaceOperations { /// <summary> /// Initializes a new instance of the FaceOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public FaceOperations(FaceAPI client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the FaceAPI /// </summary> public FaceAPI Client { get; private set; } /// <summary> /// Given query face's faceId, find the similar-looking faces from a faceId /// array or a faceListId. /// </summary> /// <param name='faceId'> /// FaceId of the query face. User needs to call Face - Detect first to get a /// valid faceId. Note that this faceId is not persisted and will expire 24 /// hours after the detection call /// </param> /// <param name='faceListId'> /// An existing user-specified unique candidate face list, created in Face List /// - Create a Face List. Face list contains a set of persistedFaceIds which /// are persisted and will never expire. Parameter faceListId and faceIds /// should not be provided at the same time /// </param> /// <param name='faceIds'> /// An array of candidate faceIds. All of them are created by Face - Detect and /// the faceIds will expire 24 hours after the detection call. /// </param> /// <param name='maxNumOfCandidatesReturned'> /// The number of top similar faces returned. The valid range is [1, 1000]. /// </param> /// <param name='mode'> /// Similar face searching mode. It can be "matchPerson" or "matchFace". /// Possible values include: 'matchPerson', 'matchFace' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<IList<SimilarFaceResult>>> FindSimilarWithHttpMessagesAsync(string faceId, string faceListId = default(string), IList<string> faceIds = default(IList<string>), int? maxNumOfCandidatesReturned = 20, string mode = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionKey == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey"); } if (faceId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "faceId"); } if (faceId != null) { if (faceId.Length > 64) { throw new ValidationException(ValidationRules.MaxLength, "faceId", 64); } } if (faceListId != null) { if (faceListId.Length > 64) { throw new ValidationException(ValidationRules.MaxLength, "faceListId", 64); } if (!System.Text.RegularExpressions.Regex.IsMatch(faceListId, "^[a-z0-9-_]+$")) { throw new ValidationException(ValidationRules.Pattern, "faceListId", "^[a-z0-9-_]+$"); } } if (faceIds != null) { if (faceIds.Count > 1000) { throw new ValidationException(ValidationRules.MaxItems, "faceIds", 1000); } } if (maxNumOfCandidatesReturned > 1000) { throw new ValidationException(ValidationRules.InclusiveMaximum, "maxNumOfCandidatesReturned", 1000); } if (maxNumOfCandidatesReturned < 1) { throw new ValidationException(ValidationRules.InclusiveMinimum, "maxNumOfCandidatesReturned", 1); } FindSimilarRequest body = new FindSimilarRequest(); if (faceId != null || faceListId != null || faceIds != null || maxNumOfCandidatesReturned != null || mode != null) { body.FaceId = faceId; body.FaceListId = faceListId; body.FaceIds = faceIds; body.MaxNumOfCandidatesReturned = maxNumOfCandidatesReturned; body.Mode = mode; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "FindSimilar", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "findsimilars"; _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"')); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.SubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(body != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<IList<SimilarFaceResult>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<SimilarFaceResult>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Divide candidate faces into groups based on face similarity. /// </summary> /// <param name='faceIds'> /// Array of candidate faceId created by Face - Detect. The maximum is 1000 /// faces /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<GroupResponse>> GroupWithHttpMessagesAsync(IList<string> faceIds, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionKey == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey"); } if (faceIds == null) { throw new ValidationException(ValidationRules.CannotBeNull, "faceIds"); } if (faceIds != null) { if (faceIds.Count > 1000) { throw new ValidationException(ValidationRules.MaxItems, "faceIds", 1000); } } GroupRequest body = new GroupRequest(); if (faceIds != null) { body.FaceIds = faceIds; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Group", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "group"; _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"')); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.SubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(body != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<GroupResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<GroupResponse>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Identify unknown faces from a person group. /// </summary> /// <param name='personGroupId'> /// personGroupId of the target person group, created by PersonGroups.Create /// </param> /// <param name='faceIds'> /// Array of candidate faceId created by Face - Detect. /// </param> /// <param name='maxNumOfCandidatesReturned'> /// The number of top similar faces returned. /// </param> /// <param name='confidenceThreshold'> /// Confidence threshold of identification, used to judge whether one face /// belong to one person. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<IList<IdentifyResultItem>>> IdentifyWithHttpMessagesAsync(string personGroupId, IList<string> faceIds, int? maxNumOfCandidatesReturned = 1, double? confidenceThreshold = default(double?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionKey == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey"); } if (personGroupId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "personGroupId"); } if (faceIds == null) { throw new ValidationException(ValidationRules.CannotBeNull, "faceIds"); } if (faceIds != null) { if (faceIds.Count > 1000) { throw new ValidationException(ValidationRules.MaxItems, "faceIds", 1000); } } if (maxNumOfCandidatesReturned > 1000) { throw new ValidationException(ValidationRules.InclusiveMaximum, "maxNumOfCandidatesReturned", 1000); } if (maxNumOfCandidatesReturned < 1) { throw new ValidationException(ValidationRules.InclusiveMinimum, "maxNumOfCandidatesReturned", 1); } if (confidenceThreshold > 1) { throw new ValidationException(ValidationRules.InclusiveMaximum, "confidenceThreshold", 1); } if (confidenceThreshold < 0) { throw new ValidationException(ValidationRules.InclusiveMinimum, "confidenceThreshold", 0); } IdentifyRequest body = new IdentifyRequest(); if (personGroupId != null || faceIds != null || maxNumOfCandidatesReturned != null || confidenceThreshold != null) { body.PersonGroupId = personGroupId; body.FaceIds = faceIds; body.MaxNumOfCandidatesReturned = maxNumOfCandidatesReturned; body.ConfidenceThreshold = confidenceThreshold; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Identify", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "identify"; _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"')); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.SubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(body != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<IList<IdentifyResultItem>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<IdentifyResultItem>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Verify whether two faces belong to a same person or whether one face /// belongs to a person. /// </summary> /// <param name='faceId'> /// faceId the face, comes from Face - Detect /// </param> /// <param name='personId'> /// Specify a certain person in a person group. personId is created in /// Persons.Create. /// </param> /// <param name='personGroupId'> /// Using existing personGroupId and personId for fast loading a specified /// person. personGroupId is created in Person Groups.Create. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<VerifyResult>> VerifyWithHttpMessagesAsync(string faceId, string personId, string personGroupId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionKey == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey"); } if (faceId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "faceId"); } if (faceId != null) { if (faceId.Length > 64) { throw new ValidationException(ValidationRules.MaxLength, "faceId", 64); } } if (personId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "personId"); } if (personGroupId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "personGroupId"); } VerifyRequest body = new VerifyRequest(); if (faceId != null || personId != null || personGroupId != null) { body.FaceId = faceId; body.PersonId = personId; body.PersonGroupId = personGroupId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Verify", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "verify"; _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"')); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.SubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(body != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<VerifyResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VerifyResult>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Detect human faces in an image and returns face locations, and optionally /// with faceIds, landmarks, and attributes. /// </summary> /// <param name='url'> /// </param> /// <param name='returnFaceId'> /// A value indicating whether the operation should return faceIds of detected /// faces. /// </param> /// <param name='returnFaceLandmarks'> /// A value indicating whether the operation should return landmarks of the /// detected faces. /// </param> /// <param name='returnFaceAttributes'> /// Analyze and return the one or more specified face attributes in the /// comma-separated string like "returnFaceAttributes=age,gender". Supported /// face attributes include age, gender, headPose, smile, facialHair, glasses /// and emotion. Note that each face attribute analysis has additional /// computational and time cost. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<IList<DetectedFace>>> DetectWithHttpMessagesAsync(string url, bool? returnFaceId = true, bool? returnFaceLandmarks = false, string returnFaceAttributes = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionKey == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey"); } if (url == null) { throw new ValidationException(ValidationRules.CannotBeNull, "url"); } ImageUrl imageUrl = new ImageUrl(); if (url != null) { imageUrl.Url = url; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("returnFaceId", returnFaceId); tracingParameters.Add("returnFaceLandmarks", returnFaceLandmarks); tracingParameters.Add("returnFaceAttributes", returnFaceAttributes); tracingParameters.Add("imageUrl", imageUrl); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Detect", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "detect"; _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"')); List<string> _queryParameters = new List<string>(); if (returnFaceId != null) { _queryParameters.Add(string.Format("returnFaceId={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(returnFaceId, Client.SerializationSettings).Trim('"')))); } if (returnFaceLandmarks != null) { _queryParameters.Add(string.Format("returnFaceLandmarks={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(returnFaceLandmarks, Client.SerializationSettings).Trim('"')))); } if (returnFaceAttributes != null) { _queryParameters.Add(string.Format("returnFaceAttributes={0}", System.Uri.EscapeDataString(returnFaceAttributes))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.SubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(imageUrl != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(imageUrl, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<IList<DetectedFace>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<DetectedFace>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Detect human faces in an image and returns face locations, and optionally /// with faceIds, landmarks, and attributes. /// </summary> /// <param name='image'> /// An image stream. /// </param> /// <param name='returnFaceId'> /// A value indicating whether the operation should return faceIds of detected /// faces. /// </param> /// <param name='returnFaceLandmarks'> /// A value indicating whether the operation should return landmarks of the /// detected faces. /// </param> /// <param name='returnFaceAttributes'> /// Analyze and return the one or more specified face attributes in the /// comma-separated string like "returnFaceAttributes=age,gender". Supported /// face attributes include age, gender, headPose, smile, facialHair, glasses /// and emotion. Note that each face attribute analysis has additional /// computational and time cost. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<IList<DetectedFace>>> DetectInStreamWithHttpMessagesAsync(Stream image, bool? returnFaceId = true, bool? returnFaceLandmarks = false, string returnFaceAttributes = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionKey == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey"); } if (image == null) { throw new ValidationException(ValidationRules.CannotBeNull, "image"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("returnFaceId", returnFaceId); tracingParameters.Add("returnFaceLandmarks", returnFaceLandmarks); tracingParameters.Add("returnFaceAttributes", returnFaceAttributes); tracingParameters.Add("image", image); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "DetectInStream", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "detect"; _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"')); List<string> _queryParameters = new List<string>(); if (returnFaceId != null) { _queryParameters.Add(string.Format("returnFaceId={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(returnFaceId, Client.SerializationSettings).Trim('"')))); } if (returnFaceLandmarks != null) { _queryParameters.Add(string.Format("returnFaceLandmarks={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(returnFaceLandmarks, Client.SerializationSettings).Trim('"')))); } if (returnFaceAttributes != null) { _queryParameters.Add(string.Format("returnFaceAttributes={0}", System.Uri.EscapeDataString(returnFaceAttributes))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.SubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(image == null) { throw new System.ArgumentNullException("image"); } if (image != null && image != Stream.Null) { _httpRequest.Content = new StreamContent(image); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/octet-stream"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<IList<DetectedFace>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<DetectedFace>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
mit
juniwalk/Dispatcher
tests/Files/MessageFactory.php
775
<?php /** * @author Martin Procházka <juniwalk@outlook.cz> * @package Dispatcher * @link https://github.com/juniwalk/Dispatcher * @copyright Martin Procházka (c) 2015 * @license MIT License */ namespace JuniWalk\Dispatcher\Tests\Files; use Nette\Application\UI\ITemplate; use Tester\Assert; final class MessageFactory implements \JuniWalk\Dispatcher\IMessageFactory { /** * @param ITemplate $html * @param string $wwwDir * @return Nette\Mailer\Message */ public function create(ITemplate $html, $wwwDir = NULL) { $html->setFile(__DIR__.'/templates/message.latte'); Assert::same($wwwDir, $html->wwwDir); return (new \Nette\Mail\Message) ->setHtmlBody($html->__toString(1), $wwwDir) ->addTo('jane.doe@example.com'); } }
mit
tscholz/knipser
lib/gps.rb
271
require_relative 'gps/exif_parser' require_relative 'gps/lat_lng' module GPS module_function def lat_lng_from_exif(exif) LatLng.from_exif exif end def lat_lng(lat:, lng:) LatLng.new lat: lat, lng: lng end def exif_parser ExifParser end end
mit
periface/NorthLionAbpZero
NorthLion.Zero.Web/Areas/AdminMpa/Scripts/dist/Layout/GlobalModal.js
3911
"use strict"; System.register([], function (_export, _context) { "use strict"; var _createClass, PeriModalManager; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } return { setters: [], execute: function () { _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); _export("PeriModalManager", PeriModalManager = function () { function PeriModalManager() { var _this = this; var modalContainer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "#modal"; _classCallCheck(this, PeriModalManager); this.modal = modalContainer; this.listener = function () { $(_this.modal).on("hidden.bs.modal", function () { console.info("Modal closed"); _this.onClose = null; $(_this.modal).empty(); }); }; this.listener(); } _createClass(PeriModalManager, [{ key: "setContainer", value: function setContainer(container) { this.modal = container; } }, { key: "open", value: function open(url) { var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var onload = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {}; var $modal = $(modal).load(url, data, function () { $(modal).modal("show"); onload(); }); } }, { key: "close", value: function close() { var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!this.onClose) { throw new Error("On close function not defined"); } else { $(modal).modal("hide"); this.onClose(data); this.onClose = null; } } }, { key: "setOnClose", value: function setOnClose(onclose) { this.onClose = onclose; } }, { key: "getInstance", value: function getInstance() { return $(modal); } }]); return PeriModalManager; }()); _export("PeriModalManager", PeriModalManager); ; } }; });
mit
daltomi/oxygine-framework
tools/others/build_oxygine_with_sdl.py
4245
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import os import sys import shutil import zipfile import time def recursive_zip(zipf, directory, folder=""): for item in os.listdir(directory): if os.path.isfile(os.path.join(directory, item)): src = os.path.join(directory, item) dest = folder + os.sep + item ext = os.path.splitext(dest)[1] st = os.stat(src) mtime = time.localtime(st.st_mtime) date_time = mtime[0:6] info = zipfile.ZipInfo(dest, date_time) bts = open(src, "rb").read() if ext == ".sh" or item in ("PVRTexToolCLI", "oxyresbuild.py", "gen_template.py", "png_strip.py", "gradlew"): info.external_attr = 0755 << 16L # a+x # zipf.writestr(info, bts, zipfile.ZIP_DEFLATED) zipf.write(os.path.join(directory, item), folder + os.sep + item) elif os.path.isdir(os.path.join(directory, item)): recursive_zip(zipf, os.path.join( directory, item), folder + os.sep + item) def buildzip(name): print("building zip: " + name) destzip = "../../" + name with zipfile.ZipFile(destzip, "w", compression=zipfile.ZIP_DEFLATED) as zp: recursive_zip(zp, "../../temp") # return try: shutil.copyfile(destzip, "../../../gdrive/oxygine/" + name) except IOError, e: pass try: shutil.copyfile(destzip, "../../../Dropbox/Public/oxygine/" + name) except IOError, e: pass print("zip created: " + name) temp = "../../temp" SDL_dest = temp + "/SDL" OXYGINE_dest = temp + "/oxygine-framework/" SOUND_dest = temp + "/oxygine-sound/" FLOW_dest = temp + "/oxygine-flow/" FT_dest = temp + "/oxygine-freetype/" print("cleaning temp...") shutil.rmtree(temp, True) def export(repo, dest): print("exporting " + repo) cmd = "git -C %s checkout-index -a -f --prefix=%s/" % ( "d:/" + repo, "d:/oxygine-framework/temp/" + dest) os.system(cmd) export("oxygine-framework", "oxygine-framework") buildzip("oxygine-framework.zip") # ALL IN ONE #cmd = "hg archive -R ../../../SDL %s" % (SDL_dest, ) #os.system(cmd) export("SDL", "SDL") export("oxygine-sound", "oxygine-sound") export("oxygine-flow", "oxygine-flow") export("oxygine-freetype", "oxygine-freetype") shutil.rmtree(SDL_dest + "/test") def fix_file(name, cb): data = open(name, "rb").read() data = cb(data) open(name, "wb").write(data) fix_file(SDL_dest + "/include/SDL_config_windows.h", lambda data: data.replace( "#define SDL_AUDIO_DRIVER_XAUDIO2", "//#define SDL_AUDIO_DRIVER_XAUDIO2") ) fix_file(SDL_dest + "/src/video/uikit/SDL_uikitview.h", lambda data: data.replace( "#define IPHONE_TOUCH_EFFICIENT_DANGEROUS", "//#define IPHONE_TOUCH_EFFICIENT_DANGEROUS") ) def enum(folder, cb): for item in os.listdir(folder): path = folder + item if os.path.isdir(path): if item == "data": cb(path) enum(path + "/", cb) def copy(path): win32 = OXYGINE_dest + "/oxygine/third_party/win32/dlls/" items = (win32 + "zlib.dll", win32 + "pthreadVCE2.dll", "../../libs/SDL2.dll") if "Demo/" in path: items = items + (win32 + "libcurl.dll", win32 + "ssleay32.dll", win32 + "libssh2.dll", win32 + "libeay32.dll") for item in items: name = os.path.split(item)[1] shutil.copy(item, path + "/" + name) enum(OXYGINE_dest + "/examples/", copy) enum(SOUND_dest + "/examples/", copy) enum(FLOW_dest + "/examples/", copy) enum(FT_dest + "/examples/", copy) shutil.copy(SDL_dest + "/android-project/src/org/libsdl/app/SDLActivity.java", OXYGINE_dest + "/oxygine/SDL/android/lib/src/org/libsdl/app/SDLActivity.java") libs = ("SDL2.lib", "SDL2main.lib", ) for lib in libs: shutil.copy("../../libs/" + lib, OXYGINE_dest + "/libs/" + lib) """ libs = ("libSDL2main.a", "libSDL2.dll", "libSDL2.dll.a") for lib in libs: shutil.copy("../../libs/" + lib, OXYGINE_dest + "/libs/" + lib) """ buildzip("oxygine-framework-with-sdl.zip") print("done.")
mit
DailyActie/Surrogate-Model
01-codes/OpenMDAO-Framework-dev/openmdao.main/src/openmdao/main/test/test_vartree.py
23994
import copy import glob import os import unittest from openmdao.main.api import Component, Assembly, VariableTree, \ set_as_top, SimulationRoot from openmdao.main.case import flatten_obj from openmdao.main.datatypes.api import Array, Bool, Enum, Float, File, \ FileRef, Int, List, Str, VarTree, \ Instance from openmdao.util.testutil import assert_raises from traits.trait_base import not_none class DumbVT3(VariableTree): a = Float(1., units='ft') b = Float(12., units='inch') data = File() class DumbVT2(VariableTree): x = Float(-1.) y = Float(-2.) data = File() vt3 = VarTree(DumbVT3()) class BadVT2(VariableTree): x = Float(-1.) y = Float(-2.) data = File() vt3 = DumbVT3() class DumbVT(VariableTree): v1 = Float(1., desc='vv1') v2 = Float(2., desc='vv2') data = File() vt2 = VarTree(DumbVT2()) class SimpleComp(Component): cont_in = VarTree(DumbVT(), iotype='in') cont_out = VarTree(DumbVT(), iotype='out') def __init__(self): super(SimpleComp, self).__init__() self._dirty = True self._set_input_callback('cont_in') def execute(self): self._dirty = False self.cont_out.v1 = self.cont_in.v1 + 1.0 self.cont_out.v2 = self.cont_in.v2 + 1.0 self.cont_out.vt2.x = self.cont_in.vt2.x + 1.0 self.cont_out.vt2.y = self.cont_in.vt2.y + 1.0 self.cont_out.vt2.vt3.a = self.cont_in.vt2.vt3.a self.cont_out.vt2.vt3.b = self.cont_in.vt2.vt3.b if self.cont_in.data is not None: with self.cont_in.data.open() as inp: filename = '%s.data.vt' % self.name with open(filename, 'w') as out: out.write(inp.read()) self.cont_out.data = FileRef(filename, self) if self.cont_in.vt2.data is not None: with self.cont_in.vt2.data.open() as inp: filename = '%s.data.vt2' % self.name with open(filename, 'w') as out: out.write(inp.read()) self.cont_out.vt2.data = FileRef(filename, self) if self.cont_in.vt2.vt3.data is not None: with self.cont_in.vt2.vt3.data.open() as inp: filename = '%s.data.vt3' % self.name with open(filename, 'w') as out: out.write(inp.read()) self.cont_out.vt2.vt3.data = FileRef(filename, self) def get_vals(self, iotype): if iotype == 'in': cont = self.cont_in else: cont = self.cont_out return [ cont.v1, cont.v2, cont.vt2.x, cont.vt2.y, cont.vt2.vt3.a, cont.vt2.vt3.b, ] def get_files(self, iotype): if iotype == 'in': cont = self.cont_in else: cont = self.cont_out return [ cont.data, cont.vt2.data, cont.vt2.vt3.data, ] def _input_updated(self, *args, **kwargs): super(SimpleComp, self)._input_updated(*args, **kwargs) self._dirty = True class NamespaceTestCase(unittest.TestCase): def setUp(self): # SimulationRoot is static and so some junk can be left # over from other tests when running under nose, so # set it to cwd here just to be safe SimulationRoot.chroot(os.getcwd()) self.asm = set_as_top(Assembly()) obj = self.asm.add('scomp1', SimpleComp()) self.asm.add('scomp2', SimpleComp()) self.asm.driver.workflow.add(['scomp1', 'scomp2']) with self.asm.dir_context: filename = 'top.data.vt' with open(filename, 'w') as out: out.write('vt data\n') obj.cont_in.data = FileRef(filename, self.asm) filename = 'top.data.vt2' with open(filename, 'w') as out: out.write('vt2 data\n') obj.cont_in.vt2.data = FileRef(filename, self.asm) filename = 'top.data.vt3' with open(filename, 'w') as out: out.write('vt3 data\n') obj.cont_in.vt2.vt3.data = FileRef(filename, self.asm) def tearDown(self): for name in glob.glob('*.data.vt*'): os.remove(name) def _check_values(self, expected, actual): for e, a in zip(expected, actual): self.assertEqual(e, a) def _check_files(self, expected, actual): for e, a in zip(expected, actual): with e.open() as inp: edata = inp.read() with a.open() as inp: adata = inp.read() self.assertEqual(edata, adata) def test_pass_container(self): # scomp1 scomp2 # cont_in /------->cont_in # v1 | v1 # v2 | v2 # vt2 | vt2 # x | x # y | y # vt3 | vt3 # a | a # b | b # cont_out--------/ cont_out # v1 v1 # v2 v2 # vt2 vt2 # x x # y y # vt3 vt3 # a a # b b self.asm.connect('scomp1.cont_out', 'scomp2.cont_in') self.asm.scomp1.cont_out.v1 = 99. self.asm.scomp1.cont_out.v2 = 88. self.asm.scomp1.cont_out.vt2.x = 999. self.asm.scomp1.cont_out.vt2.y = 888. self.asm.scomp1.cont_out.vt2.vt3.a = 9999. self.asm.scomp1.cont_out.vt2.vt3.b = 8888. self.asm.run() self.assertFalse(self.asm.scomp2.cont_in is self.asm.scomp1.cont_out) self._check_values(self.asm.scomp1.get_vals('out'), self.asm.scomp2.get_vals('in')) # 'in/out' set for end-to-end check. self._check_files(self.asm.scomp1.get_files('in'), self.asm.scomp2.get_files('out')) # Check set_attributes on the vartrees attrs = self.asm.scomp1.cont_in.get_attributes() self.assertTrue("Inputs" in attrs.keys()) self.assertTrue({'name': 'v1', 'id': '.v1', 'indent': 0, 'value': 1.0, 'high': None, 'connected': '', 'low': None, 'type': 'float', 'desc': 'vv1', 'assumed_default': False} in attrs['Inputs']) self.assertTrue({'name': 'v2', 'id': '.v2', 'indent': 0, 'value': 2.0, 'high': None, 'connected': '', 'low': None, 'type': 'float', 'desc': 'vv2', 'assumed_default': False} in attrs['Inputs']) # The number shall be 11 becuase of recursion, and also including # file variables self.assertEqual(len(attrs['Inputs']), 11) attrs = self.asm.scomp1.cont_out.get_attributes() self.assertTrue("Outputs" in attrs.keys()) self.assertTrue({'name': 'v1', 'id': '.v1', 'indent': 0, 'value': 2.0, 'high': None, 'connected': '', 'low': None, 'type': 'float', 'desc': 'vv1', 'assumed_default': False} in attrs['Outputs']) self.assertTrue({'name': 'v2', 'id': '.v2', 'indent': 0, 'value': 3.0, 'high': None, 'connected': '', 'low': None, 'type': 'float', 'desc': 'vv2', 'assumed_default': False} in attrs['Outputs']) self.assertEqual(len(attrs['Outputs']), 11) # Now connect try: self.asm.connect('scomp1.cont_out.v1', 'scomp2.cont_in.v2') except Exception as err: self.assertEqual(str(err), ": Can't connect 'scomp1.cont_out.v1' to 'scomp2.cont_in.v2':" " 'scomp2.cont_in' is already connected to 'scomp1.cont_out'") else: self.fail("exception expected") def test_connect_subvartree(self): self.asm.connect('scomp1.cont_out.vt2', 'scomp2.cont_in.vt2') self.asm.run() self.assertEqual(self.asm.scomp1.cont_out.v1, self.asm.scomp2.cont_in.v1 + 1.0) self.assertEqual(self.asm.scomp1.cont_out.v2, self.asm.scomp2.cont_in.v2 + 1.0) # [2:] indicates that all values from vt2 on down should agree self._check_values(self.asm.scomp1.get_vals('out')[2:], self.asm.scomp2.get_vals('in')[2:]) # 'in/out' set for end-to-end check. self.assertEqual(self.asm.scomp2.get_files('out')[0], None) self._check_files(self.asm.scomp1.get_files('in')[1:], self.asm.scomp2.get_files('out')[1:]) def test_connect_subvar(self): self.asm.connect('scomp1.cont_out.v1', 'scomp2.cont_in.v2') self.asm.connect('scomp1.cont_out.v2', 'scomp2.cont_in.v1') self.asm.run() self.assertEqual(self.asm.scomp1.cont_out.v1, self.asm.scomp2.cont_in.v2) self.assertEqual(self.asm.scomp1.cont_out.v2, self.asm.scomp2.cont_in.v2 + 1.0) def test_connect_subsubvar(self): self.asm.connect('scomp1.cont_out.vt2.vt3.a', 'scomp2.cont_in.vt2.vt3.b') self.asm.run() self.assertAlmostEqual(12.0 * self.asm.scomp1.cont_out.vt2.vt3.a, self.asm.scomp2.cont_in.vt2.vt3.b) try: self.asm.connect('scomp1.cont_out.vt2', 'scomp2.cont_in.vt2') except Exception as err: self.assertEqual(str(err), ": Can't connect 'scomp1.cont_out.vt2' to 'scomp2.cont_in.vt2':" " 'scomp2.cont_in.vt2.vt3.b' is already connected to" " '_pseudo_0.out0'") else: self.fail("exception expected") try: self.asm.connect('scomp1.cont_out', 'scomp2.cont_in') except Exception as err: self.assertEqual(str(err), ": Can't connect 'scomp1.cont_out' to 'scomp2.cont_in':" " 'scomp2.cont_in.vt2.vt3.b' is already connected to" " '_pseudo_0.out0'") else: self.fail("exception expected") self.asm.disconnect('scomp1.cont_out.vt2.vt3.a', 'scomp2.cont_in.vt2.vt3.b') # now this should be allowed self.asm.connect('scomp1.cont_out.vt2', 'scomp2.cont_in.vt2') self.asm.disconnect('scomp1.cont_out.vt2', 'scomp2.cont_in.vt2') # and now this self.asm.connect('scomp1.cont_out', 'scomp2.cont_in') self.asm.disconnect('scomp1.cont_out', 'scomp2.cont_in') self.asm.connect('scomp1.cont_out.vt2', 'scomp2.cont_in.vt2') self.asm.disconnect('scomp1.cont_out', 'scomp2.cont_in') def test_callbacks(self): # verify that setting a var nested down in a VariableTree hierarchy will # notify the parent Component that an input has changed self.asm.run() self.assertEqual(self.asm.scomp1._dirty, False) self.asm.scomp1.cont_in.vt2.vt3.a = 5.0 self.assertEqual(self.asm.scomp1._dirty, True) self.asm.run() self.assertEqual(self.asm.scomp1._dirty, False) self.asm.scomp1.cont_in.vt2.x = -5.0 self.assertEqual(self.asm.scomp1._dirty, True) self.asm.run() # setting something in an output VariableTree should NOT set _call_execute self.asm.scomp1.cont_out.vt2.vt3.a = 55.0 self.assertEqual(self.asm.scomp1._dirty, False) def test_pathname(self): vt = self.asm.scomp2.cont_out.vt2.vt3 self.assertEqual('scomp2.cont_out.vt2.vt3', vt.get_pathname()) self.asm.scomp1.cont_in.vt2.vt3 = vt self.assertEqual('scomp1.cont_in.vt2.vt3', self.asm.scomp1.cont_in.vt2.vt3.get_pathname()) def test_iotype(self): vt = self.asm.scomp2.cont_out.vt2.vt3 self.assertEqual(vt._iotype, 'out') self.asm.scomp1.cont_in.vt2.vt3 = vt self.assertEqual(vt._iotype, 'in') dvt = DumbVT() self.assertEqual(dvt._iotype, '') self.asm.scomp2.cont_out = dvt self.assertEqual(self.asm.scomp2.cont_out._iotype, 'out') self.assertEqual(self.asm.scomp2.cont_out.vt2._iotype, 'out') self.assertEqual(self.asm.scomp2.cont_out.vt2.vt3._iotype, 'out') def test_items(self): vtvars = ['v1', 'v2', 'vt2', 'data'] vt2vars = ['vt2.x', 'vt2.y', 'vt2.vt3', 'vt2.data'] vt3vars = ['vt2.vt3.a', 'vt2.vt3.b', 'vt2.vt3.data'] result = dict(self.asm.scomp1.cont_out.items(iotype='out')) self.assertEqual(set(result.keys()), set(vtvars)) result = dict(self.asm.scomp1.cont_out.items(recurse=True, iotype='out')) self.assertEqual(set(result.keys()), set(vtvars + vt2vars + vt3vars)) result = dict(self.asm.scomp1.cont_out.items(iotype='in')) self.assertEqual(set(result.keys()), set([])) result = dict(self.asm.scomp1.cont_out.items(iotype=None)) self.assertEqual(set(result.keys()), set([])) result = dict(self.asm.scomp1.cont_out.items(iotype=not_none)) self.assertEqual(set(result.keys()), set(vtvars)) result = dict(self.asm.scomp1.cont_in.items(iotype='in')) self.assertEqual(set(result.keys()), set(vtvars)) result = dict(self.asm.scomp1.cont_in.items(recurse=True, iotype='in')) self.assertEqual(set(result.keys()), set(vtvars + vt2vars + vt3vars)) result = dict(self.asm.scomp1.cont_in.items(iotype='out')) self.assertEqual(set(result.keys()), set([])) def test_flatten(self): dvt = DumbVT() self.assertEqual(set(flatten_obj('foo', dvt)), set([('foo.vt2.vt3.a', 1.), ('foo.vt2.vt3.b', 12.), ('foo.vt2.x', -1.), ('foo.vt2.y', -2.), ('foo.v1', 1.), ('foo.v2', 2.), ('foo.vt2.vt3.data', ''), ('foo.vt2.data', ''), ('foo.data', '')])) def test_nesting(self): # Check direct nesting in class definition. code = 'vt2 = BadVT2()' msg = 'Nested VariableTrees are not supported,' \ ' please wrap BadVT2.vt3 in a VarTree' assert_raises(self, code, globals(), locals(), TypeError, msg, use_exec=True) # Check direct nesting via add(). vt3 = DumbVT3() vt3.add('ok', VarTree(DumbVT3())) code = "vt3.add('bad', DumbVT3())" msg = ': a VariableTree may only contain Variables or VarTrees' assert_raises(self, code, globals(), locals(), TypeError, msg) class Level2Tree(VariableTree): lev2float = Float() class Level1Tree(VariableTree): lev1float = Float() lev2 = VarTree(Level2Tree()) # no iotype class TopTree(VariableTree): lev1 = VarTree(Level1Tree()) # no iotype topfloat = Float() class NestedTreeComp(Component): top_tree_in = VarTree(TopTree(), iotype='in') def execute(self): pass class NestedVTTestCase(unittest.TestCase): def test_nested_iotype(self): # No iotype when creating TopTree. top = TopTree() self.assertEqual(top._iotype, '') self.assertEqual(top.iotype, '') self.assertEqual(top.lev1._iotype, '') self.assertEqual(top.lev1.iotype, '') self.assertEqual(top.lev1.lev2._iotype, '') self.assertEqual(top.lev1.lev2.iotype, '') # nested tree input -- iotype propagated all the way through. comp = NestedTreeComp() self.assertEqual(comp.top_tree_in._iotype, 'in') self.assertEqual(comp.top_tree_in.iotype, 'in') self.assertEqual(comp.top_tree_in.lev1._iotype, 'in') self.assertEqual(comp.top_tree_in.lev1.iotype, 'in') self.assertEqual(comp.top_tree_in.lev1.lev2._iotype, 'in') self.assertEqual(comp.top_tree_in.lev1.lev2.iotype, 'in') attr = comp.top_tree_in.get_attributes() outputs = attr.get('Outputs', []) self.assertEqual(outputs, []) inputs = attr['Inputs'] self.assertEqual(set([d['name'] for d in inputs]), set(['topfloat', 'lev1', 'lev1float', 'lev2', 'lev2float'])) newvt = comp.top_tree_in.copy() newvt._iotype = 'out' attr = newvt.get_attributes() inputs = attr.get('Inputs', []) outputs = attr.get('Outputs', []) self.assertEqual(inputs, []) self.assertEqual(set([d['name'] for d in outputs]), set(['topfloat', 'lev1', 'lev1float', 'lev2', 'lev2float'])) self.assertEqual(newvt.lev1.lev2.iotype, 'out') newvt._iotype = 'in' self.assertEqual(newvt.iotype, 'in') self.assertEqual(newvt.lev1.lev2.iotype, 'in') def test_nested_iotype_passthrough(self): # nested tree asm = set_as_top(Assembly()) comp = asm.add("comp", NestedTreeComp()) asm.create_passthrough('comp.top_tree_in') attr = asm.top_tree_in.get_attributes() outputs = attr.get('Outputs', []) self.assertEqual(outputs, []) inputs = attr['Inputs'] self.assertEqual(set([d['name'] for d in inputs]), set(['topfloat', 'lev1', 'lev1float', 'lev2', 'lev2float'])) newvt = asm.top_tree_in.copy() newvt._iotype = 'out' attr = newvt.get_attributes() inputs = attr.get('Inputs', []) outputs = attr.get('Outputs', []) self.assertEqual(inputs, []) self.assertEqual(set([d['name'] for d in outputs]), set(['topfloat', 'lev1', 'lev1float', 'lev2', 'lev2float'])) attr = comp.top_tree_in.get_attributes() outputs = attr.get('Outputs', []) self.assertEqual(outputs, []) inputs = attr['Inputs'] self.assertEqual(set([d['name'] for d in inputs]), set(['topfloat', 'lev1', 'lev1float', 'lev2', 'lev2float'])) class ListConnectTestCase(unittest.TestCase): def test_connect(self): class Vars(VariableTree): f1 = Float() f2 = Float() class TestAsm(Assembly): f_in = Float(iotype='in') def configure(self): self.add('c2', TestComponent2()) self.driver.workflow.add('c2') # Construct list with only one element for demo purposes self.c2.vtlist = [Vars()] self.connect('f_in', 'c2.vtlist[0].f1') self.c2.vtlist[0].f2 = 90 self.create_passthrough('c2.f_out') class TestComponent2(Component): vtlist = List(trait=Vars, value=[], iotype='in') f_out = Float(iotype='out') def execute(self): self.f_out = self.vtlist[0].f1 + self.vtlist[0].f2 top = set_as_top(Assembly()) # Init of model test_asm = TestAsm() top.add('asm', test_asm) top.driver.workflow.add('asm') test_asm.f_in = 10 test_asm.run() self.assertEqual(100, test_asm.f_out) def test_connect2(self): class VT(VariableTree): x = Float(iotype='in') y = Float(iotype='in') class C(Component): x = Float(iotype='in') out = Float(iotype='out') def execute(self): self.out = 2 * self.x class A(Assembly): vt = VarTree(VT(), iotype='in') def configure(self): self.add('c', C()) self.driver.workflow.add(['c']) self.connect('vt.x', 'c.x') self.create_passthrough('c.out') a = A() a.vt.x = 1.0 a.vt.y = 7.0 a.run() self.assertEqual(a.out, 2.0) class DeepCopyTestCase(unittest.TestCase): def test_deepcopy(self): # Check that complex tree is truly copied. # There had been a bug where added bodies were shared. class Simulation(VariableTree): time_stop = Float(300) solvertype = Int(1) convergence_limits = List([1.0e3, 1.0, 0.7]) eig_out = Bool(False) class Mann(VariableTree): turb_base_name = Str('turb') std_scaling = Array([1.0, 0.7, 0.5]) class Wind(VariableTree): horizontal_input = Enum(1, (0, 1)) mann = VarTree(Mann()) class BeamStructure(VariableTree): s = Array() class Body(VariableTree): body_name = Str('body') beam_structure = List(BeamStructure) class BodyList(VariableTree): def add_body(self, body_name, b): b.body_name = body_name self.add(body_name, VarTree(b)) class VarTrees(VariableTree): sim = VarTree(Simulation()) # Single level. wind = VarTree(Wind()) # Static multilevel. bodies = VarTree(BodyList()) # Dynamic multilevel. a = VarTrees() a.name = 'A' a.bodies.add_body('the_body', Body()) b = a.copy() errors = DeepCopyTestCase.checker(a, b) self.assertEqual(errors, 0) @staticmethod def checker(cont1, cont2, indent=0): errors = 0 prefix = ' ' * (4 * indent) print '%schecking' % prefix, cont1.get_pathname(), id(cont1), '0x%08x' % id(cont1) print '%s vs' % prefix, cont2.get_pathname(), id(cont2), '0x%08x' % id(cont2) if id(cont1) == id(cont2): print '%s ' % prefix, cont1.get_pathname(), 'is', cont2.get_pathname() errors += 1 for name in sorted(cont1.list_containers()): sub1 = getattr(cont1, name) if hasattr(cont2, name): sub2 = getattr(cont2, name) errors += DeepCopyTestCase.checker(sub1, sub2, indent + 1) else: print '%s ' % prefix, cont2.get_pathname(), 'is missing', name errors += 1 return errors def test_2nd_copy(self): # Test that copy of copy is valid (had 'lost' REGION00_v). class Region(VariableTree): thickness = Float() angle = Float() class StData(VariableTree): s = Float() def add_region(self, name): self.add(name + '_i', Instance(Region())) self.add(name + '_v', VarTree(Region())) self.add(name + '_f', Float()) s1 = StData() s1.add_region('REGION00') s2 = copy.deepcopy(s1) s3 = copy.deepcopy(s2) keys = sorted([key for key in s3.__dict__ if not key.startswith('_')]) expected = ['REGION00_f', 'REGION00_i', 'REGION00_v', 's'] self.assertEqual(keys, expected) if __name__ == "__main__": unittest.main()
mit
Kelzo/ProjetPoivre
app/cache/dev/twig/96/fd/81819480d96a62a5db0ffc98cfb8.php
875
<?php /* TwigBundle:Exception:error.xml.twig */ class __TwigTemplate_96fd81819480d96a62a5db0ffc98cfb8 extends Twig_Template { protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<?xml version=\"1.0\" encoding=\""; echo twig_escape_filter($this->env, $this->env->getCharset(), "html", null, true); echo "\" ?> <error code=\""; // line 3 echo twig_escape_filter($this->env, $this->getContext($context, "status_code"), "html", null, true); echo "\" message=\""; echo twig_escape_filter($this->env, $this->getContext($context, "status_text"), "html", null, true); echo "\" /> "; } public function getTemplateName() { return "TwigBundle:Exception:error.xml.twig"; } public function isTraitable() { return false; } }
mit
wolfgangimig/joa
java/joa-im/src-gen/com/wilutions/mslib/uccollaborationlib/_IPreviousConversationsManagerEvents.java
1381
/* ** GENEREATED FILE - DO NOT MODIFY ** */ package com.wilutions.mslib.uccollaborationlib; import com.wilutions.com.*; /** * _IPreviousConversationsManagerEvents. * _IPreviousConversationsManagerEvents Interface */ @CoInterface(guid="{D992371E-5161-453B-97E6-6E7C67BC075E}") public interface _IPreviousConversationsManagerEvents extends IDispatch { static boolean __typelib__loaded = __TypeLib.load(); @DeclDISPID(2100) public void onOnConnectionStateChanged(final IPreviousConversationsManager _eventSource, final IPreviousConversationsManagerConnectionStateChangedEventData _eventData) throws ComException; @DeclDISPID(2101) public void onOnNewItemCountSinceLastResetChanged(final IPreviousConversationsManager _eventSource, final IPreviousConversationsManagerNewItemCountChangedEventData _eventData) throws ComException; @DeclDISPID(2103) public void onOnItemsAdded(final IPreviousConversationsManager _eventSource, final IPreviousConversationBatchEventData _eventData) throws ComException; @DeclDISPID(2104) public void onOnItemsRemoved(final IPreviousConversationsManager _eventSource, final IPreviousConversationBatchEventData _eventData) throws ComException; @DeclDISPID(2105) public void onOnItemsModified(final IPreviousConversationsManager _eventSource, final IPreviousConversationBatchEventData _eventData) throws ComException; }
mit
cuckata23/wurfl-data
data/alcatel_ot_6012x_ver1_subuaachrome.php
260
<?php return array ( 'id' => 'alcatel_ot_6012x_ver1_subuaachrome', 'fallback' => 'alcatel_ot_6012x_ver1', 'capabilities' => array ( 'uaprof' => 'http://www-ccpp.tcl-ta.com/files/ONE_TOUCH_6012A.xml', 'model_name' => 'One Touch 6012A', ), );
mit
sergiubologa/travique
PublicJournal.Dal/Dao/EventDao.cs
1718
using PublicJournal.Dal.Contracts; using PublicJournal.Dal.Dao; using PublicJournal.Dal; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Entity.Core.Objects; namespace PublicJournal.Dal.Dao { public class EventDao : AbstractDao<Event>, IEventDao { public EventDao(IObjectContext objectContext) : base(objectContext) { } public Event GetEvent(int id) { var query = from obj in _objectSet where obj.Id == id select obj; return query.SingleOrDefault(); } public List<Event> GetAllEvents() { var query = from obj in _objectSet select obj; return query.ToList(); } public List<Event> GetListEventsByCategoryId(int categoryId) { var query = from obj in _objectSet where obj.GenericEvent.EventCategories.Where(x=>x.CategoryId == categoryId).ToList().Count > 0 select obj; return query.ToList(); } public List<Event> GetListEventsByCategoryIdAndByCountry(int categoryId, int countryId) { var query = from obj in _objectSet where obj.GenericEvent.EventCategories.Where(x => x.CategoryId == categoryId).ToList().Count > 0 && obj.CountryId == countryId select obj; return query.ToList(); } } }
mit
dscastillo171/morrocoi
js/index.js
1940
/* The MIT License (MIT) Copyright (c) 2013 Santiago Castillo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Used to avoid polluting the namespace. var Morrocoi = Morrocoi || {}; // Constants Morrocoi.COLORS = ["red", "yellow", "blue", "green"]; $(document).ready(function(){ // Load the stories. for(var i = 0; i < Morrocoi.cuentos.list.length; i ++){ $('#cuentos').append(Morrocoi.cuentos.parse(Morrocoi.cuentos.list[i])); } // Randomize the dates colors. $('div.story .date').each(function(){ var color = Morrocoi.COLORS[Math.floor(Math.random() * Morrocoi.COLORS.length)]; $(this).addClass(color); }); // Setup the canvas. var canvas = document.getElementById('funBackground'); Morrocoi.background.setUp(canvas); }); $(document).scroll( (function(){ var offset = 0; return function(event){ Morrocoi.background.addOffset($(document).scrollTop() - offset); offset = $(document).scrollTop(); }; })() );
mit
74th/vscode-vim
src/motion/FindCharacterMotion.ts
7977
import { GoAction } from "../action/GoAction"; import { Position } from "../VimStyle"; import { AbstractMotion } from "./AbstractMotion"; /** * fx Fx tx Tx ; , * cfx cFx ctx cTx c; c, */ export class FindCharacterMotion extends AbstractMotion implements IRequireCharacterMotion { public CharacterCode: number; public Direction: Direction; public OppositeDirection: boolean; public IsTill: boolean; public IsContainTargetChar: boolean; constructor(direction: Direction) { super(); this.Direction = direction; this.OppositeDirection = false; this.IsTill = false; this.IsContainTargetChar = false; this.CharacterCode = null; } public SetChar(c: string) { this.CharacterCode = c.charCodeAt(0); } public CalculateEnd(editor: IEditor, vim: IVimStyle, start: IPosition): IPosition { let line = editor.ReadLineAtCurrentPosition(); let end = new Position(); end.Line = start.Line; let i; let count = this.Count; if (this.CharacterCode === null) { if (vim.LastFindCharacterMotion === null) { return null; } let last: any; last = vim.LastFindCharacterMotion; if (this.OppositeDirection) { if (last.Direction === Direction.Left) { this.Direction = Direction.Right; } else { this.Direction = Direction.Left; } } else { this.Direction = last.Direction; } this.IsTill = last.IsTill; this.CharacterCode = last.CharacterCode; } else { // save direction for ; , vim.LastFindCharacterMotion = this; } if (this.CharacterCode === null) { return null; } if (this.Direction === Direction.Right) { for (i = start.Char + 1; i < line.length; i++) { if (this.IsTill && i === start.Char + 1) { continue; } if (this.CharacterCode === line.charCodeAt(i)) { count--; if (count === 0) { end.Char = i; break; } } } } else { for (i = start.Char - 1; i >= 0; i--) { if (this.IsTill && i === start.Char - 1) { continue; } if (this.CharacterCode === line.charCodeAt(i)) { count--; if (count === 0) { end.Char = i; break; } } } } if (count > 0) { return null; } if (this.IsTill) { if (this.Direction === Direction.Right) { end.Char -= 1; } else { end.Char += 1; } } if (this.IsContainTargetChar) { // use dfx dtx end.Char += 1; } return end; } } /** * fx */ export function GotoCharacterToRight(num: number): IAction { let a = new GoAction(); let m: FindCharacterMotion; m = new FindCharacterMotion(Direction.Right); m.Count = num > 0 ? num : 1; a.Motion = m; return a; } /** * Fx */ export function GotoCharacterToLeft(num: number): IAction { let a = new GoAction(); let m: FindCharacterMotion; m = new FindCharacterMotion(Direction.Left); m.Count = num > 0 ? num : 1; a.Motion = m; return a; } /** * tx */ export function GoTillBeforeCharacterToRight(num: number): IAction { let a = new GoAction(); let m: FindCharacterMotion; m = new FindCharacterMotion(Direction.Right); m.Count = num > 0 ? num : 1; m.IsTill = true; a.Motion = m; return a; } /** * Tx */ export function GoTillBeforeCharacterToLeft(num: number): IAction { let a = new GoAction(); let m: FindCharacterMotion; m = new FindCharacterMotion(Direction.Left); m.Count = num > 0 ? num : 1; m.IsTill = true; a.Motion = m; return a; } /** * cfx */ export function AddCharacterToRightMotion(num: number, action: IAction): void { let m: FindCharacterMotion; m = new FindCharacterMotion(Direction.Right); m.IsContainTargetChar = true; m.Count = num > 0 ? num : 1; let a = <IRequireMotionAction>action; a.Motion = m; } /** * cFx */ export function AddCharacterToLeftMotion(num: number, action: IAction): void { let m: FindCharacterMotion; m = new FindCharacterMotion(Direction.Left); m.Count = num > 0 ? num : 1; let a = <IRequireMotionAction>action; a.Motion = m; } /** * ctx */ export function AddTillCharacterToRightMotion(num: number, action: IAction): void { let m: FindCharacterMotion; m = new FindCharacterMotion(Direction.Right); m.IsContainTargetChar = true; m.Count = num > 0 ? num : 1; m.IsTill = true; let a = <IRequireMotionAction>action; a.Motion = m; } /** * cTx */ export function AddTillCharacterToLeftMotion(num: number, action: IAction): void { let m: FindCharacterMotion; m = new FindCharacterMotion(Direction.Left); m.Count = num > 0 ? num : 1; m.IsTill = true; let a = <IRequireMotionAction>action; a.Motion = m; } /** * vfx */ export function AddVisualGotoCharacterToRightMotion(num: number, action: IAction): IAction { let a = <IRequireMotionAction>action; let m: FindCharacterMotion; m = new FindCharacterMotion(Direction.Right); m.IsContainTargetChar = false; m.Count = num > 0 ? num : 1; a.Motion = m; return a; } /** * vFx */ export let AddVisualGotoCharacterToLeftMotion: (num: number, action: IAction) => void = AddCharacterToLeftMotion; /** * vtx */ export function AddVisualGoTillCharacterToRightMotion(num: number, action: IAction): IAction { let a = <IRequireMotionAction>action; let m: FindCharacterMotion; m = new FindCharacterMotion(Direction.Right); m.Count = num > 0 ? num : 1; m.IsContainTargetChar = false; m.IsTill = true; a.Motion = m; return a; } /** * vTx */ export let AddVisualGoTillCharacterToLeftMotion: (num: number, action: IAction) => void = AddTillCharacterToLeftMotion; /** * N; */ export function GotoRepeatCharacter(num: number): IAction { let a = new GoAction(); let m: FindCharacterMotion; m = new FindCharacterMotion(Direction.Right); m.Count = num > 0 ? num : 1; a.Motion = m; return a; } /** * c; */ export function AddRepeartCharacterMotion(num: number, action: IAction) { let m: FindCharacterMotion; m = new FindCharacterMotion(null); m.IsContainTargetChar = true; m.Count = num > 0 ? num : 1; let a = <IRequireMotionAction>action; a.Motion = m; } /** * vc; */ export function AddVisualGotoRepeartCharacterMotion(num: number, action: IAction) { let m: FindCharacterMotion; m = new FindCharacterMotion(null); m.IsContainTargetChar = false; m.Count = num > 0 ? num : 1; let a = <IRequireMotionAction>action; a.Motion = m; } /** * N, */ export function GotoRepeatCharacterOppositeDirection(num: number): IAction { let a = new GoAction(); let m: FindCharacterMotion; m = new FindCharacterMotion(null); m.OppositeDirection = true; m.Count = num > 0 ? num : 1; a.Motion = m; return a; } /** * c, */ export function AddRepeartCharacterMotionOppositeDirection(num: number, action: IAction) { let m: FindCharacterMotion; m = new FindCharacterMotion(null); m.OppositeDirection = true; m.Count = num > 0 ? num : 1; let a = <IRequireMotionAction>action; a.Motion = m; } /** * vcN, */ export let AddVisualGotoRepeartCharacterMotionOppositeDirection = AddRepeartCharacterMotionOppositeDirection;
mit
tinafallahi/Smellscape
Gruntfile.js
1649
module.exports = function(grunt) { 'use strict'; var tests = 'test/*.js'; var tasks = ['server/*.js', 'server.js']; var client = 'www/js/*.js'; var reportDir = 'build/reports/'; grunt.initConfig({ clean : [ 'build' ], /*nodeunit : { files : [ tests ] },*/ mochaTest: { options: { reporter: 'spec' }, src: tests }, watch : { files : [ tasks, tests ], tasks : 'default' }, jshint : { files : [ 'Gruntfile.js', tasks, tests, client], options : { curly : true, eqeqeq : true, immed : true, latedef : true, newcap : true, noarg : true, sub : true, //undef : true, boss : true, eqnull : true, node : true }, globals : {} }, instrument : { files : tasks, options : { lazy : true, basePath : 'build/instrument/' } }, reloadTasks : { rootPath : 'build/instrument/' }, storeCoverage : { options : { dir : reportDir } }, makeReport : { src : 'build/reports/**/*.json', options : { type : ['lcov', 'html'], dir : reportDir, print : 'detail' } } }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.registerTask('test', 'mochaTest'); grunt.registerTask('default', 'jshint'); grunt.registerTask('cover', [ 'clean', 'instrument', 'reloadTasks', 'test', 'storeCoverage', 'makeReport' ]); };
mit
VasilStamatov/GraphicsLearning
AI_Game/World.cpp
8554
#include "World.h" #include <fstream> #include <GameEngine\ResourceManager.h> World::World() : //Terrain(cost, isWater, isWalkable, texture) m_grassTerrain(std::make_shared<Terrain>(1, false, true, GameEngine::ResourceManager::GetTexture("Textures/grass.png"))), m_redBrickTerrain(std::make_shared<Terrain>(1, false, false, GameEngine::ResourceManager::GetTexture("Textures/red_bricks.png"))), m_lightBrickTerrain(std::make_shared<Terrain>(1, false, false, GameEngine::ResourceManager::GetTexture("Textures/light_bricks.png"))), m_glassTerrain(std::make_shared<Terrain>(1, false, false, GameEngine::ResourceManager::GetTexture("Textures/glass.png"))), m_riverTerrain(std::make_shared<Terrain>(5, true, true, GameEngine::ResourceManager::GetTexture("Textures/water.png"))) { m_randomGenerator.GenSeed(GameEngine::SeedType::CLOCK_TICKS); } World::~World() { m_terrainBatch.Dispose(); m_tiles.clear(); m_zombieSpawnPositions.clear(); } void World::GenerateRandomTerrain() { m_width = m_randomGenerator.GenRandInt(50, 150); m_height = m_randomGenerator.GenRandInt(25, 75); m_tiles.resize(m_width * m_height); m_worldGrid = std::make_shared<Grid>(m_width, m_height, TILE_WIDTH); for (size_t i = 0; i < m_tiles.size(); i++) { //get the 2d coordinates from the 1d array int x = i % m_width; int y = i / m_width; int randNum = m_randomGenerator.GenRandInt(0, 20); // Sprinkle some hills. switch (randNum) { case 0: { m_tiles.at(i) = m_redBrickTerrain; m_worldGrid->SetWalkableAt(glm::ivec2(x, y), m_tiles.at(i).lock()->IsWalkable()); m_worldGrid->SetTerrainCost(glm::ivec2(x, y), m_tiles.at(i).lock()->MovementCost()); break; } case 1: { m_tiles.at(i) = m_lightBrickTerrain; m_worldGrid->SetWalkableAt(glm::ivec2(x, y), m_tiles.at(i).lock()->IsWalkable()); m_worldGrid->SetTerrainCost(glm::ivec2(x, y), m_tiles.at(i).lock()->MovementCost()); break; } case 2: { m_tiles.at(i) = m_glassTerrain; m_worldGrid->SetWalkableAt(glm::ivec2(x, y), m_tiles.at(i).lock()->IsWalkable()); m_worldGrid->SetTerrainCost(glm::ivec2(x, y), m_tiles.at(i).lock()->MovementCost()); break; } default: { m_tiles.at(i) = m_grassTerrain; m_worldGrid->SetWalkableAt(glm::ivec2(x, y), m_tiles.at(i).lock()->IsWalkable()); m_worldGrid->SetTerrainCost(glm::ivec2(x, y), m_tiles.at(i).lock()->MovementCost()); break; } } } // Lay a river. { int x = m_randomGenerator.GenRandInt(0, m_width); for (int y = 0; y < m_height; y++) { int index = y * m_width + x; m_tiles.at(index) = m_riverTerrain; m_worldGrid->SetWalkableAt(glm::ivec2(x, y), m_tiles.at(index).lock()->IsWalkable()); m_worldGrid->SetTerrainCost(glm::ivec2(x, y), m_tiles.at(index).lock()->MovementCost()); } } //set the start player pos { int index = m_randomGenerator.GenRandInt(0, m_tiles.size()); while (!m_tiles.at(index).lock()->IsWalkable()) { index = m_randomGenerator.GenRandInt(0, m_tiles.size()); } int x = index % m_width; int y = index / m_width; m_startPlayerPos = glm::vec2((x * TILE_WIDTH), (y * TILE_WIDTH)); } //set a couple of zombie spawn points for (size_t i = 0; i < 3; i++) { int index = m_randomGenerator.GenRandInt(0, m_tiles.size()); while (!m_tiles.at(index).lock()->IsWalkable() && index != (m_startPlayerPos.y * m_width + m_startPlayerPos.x)) { index = m_randomGenerator.GenRandInt(0, m_tiles.size()); } int x = index % m_width; int y = index / m_width; m_zombieSpawnPositions.emplace_back(x * TILE_WIDTH, y * TILE_WIDTH); } } void World::LoadTerrainFromFile(const std::string & _filePath) { std::ifstream file; file.open(_filePath.c_str()); if (file.fail()) { throw std::runtime_error("File " + _filePath + " failed to load"); } std::vector<std::string> terrainData; std::string terrainLine; // Read the level data while (std::getline(file, terrainLine)) { terrainData.push_back(terrainLine); } m_width = terrainData.at(0).size(); m_height = terrainData.size(); m_tiles.resize(m_width * m_height); m_worldGrid = std::make_shared<Grid>(m_width, m_height, TILE_WIDTH); //Submit all the tiles to the spritebatch for (size_t i = 0; i < m_tiles.size(); i++) { //get the 2d coordinates from the 1d array int x = i % m_width; int y = i / m_width; // Grab the tile char tile = terrainData.at(y).at(x); // Process the tile switch (tile) { case 'b': case 'B': { m_tiles.at(i) = m_redBrickTerrain; m_worldGrid->SetWalkableAt(glm::ivec2(x, y), m_tiles.at(i).lock()->IsWalkable()); m_worldGrid->SetTerrainCost(glm::ivec2(x, y), m_tiles.at(i).lock()->MovementCost()); break; } case 'g': case 'G': { m_tiles.at(i) = m_glassTerrain; m_worldGrid->SetWalkableAt(glm::ivec2(x, y), m_tiles.at(i).lock()->IsWalkable()); m_worldGrid->SetTerrainCost(glm::ivec2(x, y), m_tiles.at(i).lock()->MovementCost()); break; } case 'l': case 'L': { m_tiles.at(i) = m_lightBrickTerrain; m_worldGrid->SetWalkableAt(glm::ivec2(x, y), m_tiles.at(i).lock()->IsWalkable()); m_worldGrid->SetTerrainCost(glm::ivec2(x, y), m_tiles.at(i).lock()->MovementCost()); break; } case 'w': case 'W': { m_tiles.at(i) = m_riverTerrain; m_worldGrid->SetWalkableAt(glm::ivec2(x, y), m_tiles.at(i).lock()->IsWalkable()); m_worldGrid->SetTerrainCost(glm::ivec2(x, y), m_tiles.at(i).lock()->MovementCost()); break; } case '@': { m_tiles.at(i) = m_grassTerrain; m_worldGrid->SetWalkableAt(glm::ivec2(x, y), m_tiles.at(i).lock()->IsWalkable()); m_worldGrid->SetTerrainCost(glm::ivec2(x, y), m_tiles.at(i).lock()->MovementCost()); m_startPlayerPos = glm::vec2((x * TILE_WIDTH), (y * TILE_WIDTH)); break; } case 'z': case 'Z': { m_tiles.at(i) = m_grassTerrain; m_worldGrid->SetWalkableAt(glm::ivec2(x, y), m_tiles.at(i).lock()->IsWalkable()); m_worldGrid->SetTerrainCost(glm::ivec2(x, y), m_tiles.at(i).lock()->MovementCost()); m_zombieSpawnPositions.emplace_back(x * TILE_WIDTH, y * TILE_WIDTH); break; } case 'p': case 'P': { m_tiles.at(i) = m_grassTerrain; m_worldGrid->SetWalkableAt(glm::ivec2(x, y), m_tiles.at(i).lock()->IsWalkable()); m_worldGrid->SetTerrainCost(glm::ivec2(x, y), m_tiles.at(i).lock()->MovementCost()); m_patrolWaypoints.emplace_back(x * TILE_WIDTH, y * TILE_WIDTH); break; } case '.': { m_tiles.at(i) = m_grassTerrain; m_worldGrid->SetWalkableAt(glm::ivec2(x, y), m_tiles.at(i).lock()->IsWalkable()); m_worldGrid->SetTerrainCost(glm::ivec2(x, y), m_tiles.at(i).lock()->MovementCost()); break; } default: std::printf("Unexpected symbol %c at (%d,%d)", tile, x, y); break; } } } void World::DrawUnsaved() { //Initialize the spritebatch m_terrainBatch.Init(); //Clear it and set the sort type m_terrainBatch.Begin(); //UV coordinates for all sprites glm::vec4 uvRect(0.0f, 0.0f, 1.0f, 1.0f); //Sumbit all the sprites to the batch for (size_t i = 0; i < m_tiles.size(); i++) { //get the 2d coordinates from the 1d array int x = i % m_width; int y = i / m_width; // Get dest rect glm::vec4 destRect(x * TILE_WIDTH, y * TILE_WIDTH, TILE_WIDTH, TILE_WIDTH); m_terrainBatch.Draw(destRect, uvRect, m_tiles.at(i).lock()->GetTexture().id, 0.0f, GameEngine::ColorRGBA8(255, 255)); } //Sort the sprites and create the batches m_terrainBatch.End(); //Render all the sprite batches m_terrainBatch.RenderBatch(); /* No need to submit the sprites every frame considering the world is unchanging, so save the spritebatch (by not clearing it in Begin() and just use the render call in the future */ m_savedBatch = true; } void World::Draw() { if (!m_savedBatch) { DrawUnsaved(); } else { //render the whole world in the saved terrain batch m_terrainBatch.RenderBatch(); } }
mit
WahlbergRu/Go-In-Shadow
jsiso/main.js
12885
require([ 'jsiso/canvas/Control', 'jsiso/canvas/Input', 'jsiso/img/load', 'jsiso/json/load', 'jsiso/tile/Field', 'jsiso/pathfind/pathfind', 'jsiso/particles/EffectLoader', 'jsiso/utils', 'requirejs/domReady!' ], function(CanvasControl, CanvasInput, imgLoader, jsonLoader, TileField, pathfind, EffectLoader, utils) { // -- FPS -------------------------------- window.requestAnimFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, element) { window.setTimeout(callback, 1000 / 60); }; })(); // --------------------------------------- // Editor Globals ------------------------ var tileSelection = {}; // --------------------------------------- var gameScheme = { tileHeight: 43,//30 градусов, отношение высоты к ширине tileWidth: 100, map: 'mapSmall.json', imageFiles: 'imageFiles.json', }; //TODO: сделать дравинг в зависимости от размера экрана function launch() { jsonLoader([gameScheme.map, gameScheme.imageFiles]).then(function(jsonResponse) { imgLoader([{graphics: jsonResponse[1].images}]).then(function(imgResponse) { var game = new main(0, 0, 20, 20); // X & Y drawing position, and tile span to draw - малая карта // var game = new main(45, 45, 45, 45);// X & Y drawing position, and tile span to draw - большая карта game.init([{ Title: "Graphics", layout: jsonResponse[0].ground, graphics: imgResponse[0].files, graphicsDictionary: imgResponse[0].dictionary, heightMap: { map: jsonResponse[0].height, offset: -80, heightTile: imgResponse[0].files["ground.png"] }, tileHeight: gameScheme.tileHeight, tileWidth: gameScheme.tileWidth, zeroIsBlank: true }]); addTilesToHUD("Graphics", imgResponse[0].dictionary, 1); }); }); } function tileChoice(layer, tile) { tileSelection.title = layer; tileSelection.value = tile; } //Функция добавления на лаяут других объктов function addTilesToHUD(layer, dictionary, offset) { var clickTile; dictionary.forEach(function(tile, i) { var clickTile = document.createElement("a"); clickTile.innerHTML += ("<img height='50' width='50' src='../img/Grass/" + tile +"' />"); document.getElementById("gameInfo").appendChild(clickTile); clickTile.addEventListener("click", function(e){ tileChoice(layer, (i + offset)) }); }); } function main(x, y, xrange, yrange) { var mapLayers = []; var startY = y; var startX = x; var rangeX = xrange; var rangeY = yrange; var defaultRangeY = rangeY; var context = CanvasControl.create("canavas", 920, 600, { background: "#000022", display: "block", marginLeft: "auto", marginRight: "auto" }); CanvasControl.fullScreen(); var input = new CanvasInput(document, CanvasControl()); input.mouse_action(function(coords) { mapLayers.map(function(layer) { // console.log(layer.getHeightMapTile()); tile_coordinates = layer.applyMouseFocus(coords.x, coords.y); // Get the current mouse location from X & Y Coords console.log(coords); //layer.setHeightmapTile(tile_coordinates.x, tile_coordinates.y, layer.getHeightMapTile(tile_coordinates.x, tile_coordinates.y) + 1); // Increase heightmap tile layer.setTile(tile_coordinates.x, tile_coordinates.y, tileSelection.value); // Force the chaning of tile graphic }); }); input.mouse_move(function(coords) { mapLayers.map(function(layer) { tile_coordinates = layer.applyMouseFocus(coords.x, coords.y); // Apply mouse rollover via mouse location X & Y }); }); input.keyboard(function(keyCode, pressed, e) { //Светить в консоли кейкод console.log(keyCode); switch(keyCode) { case 65: //a - отдалить mapLayers.map(function(layer) { if (startY + rangeY + 1 < mapLayers[0].getLayout().length) { layer.setZoom("out"); layer.align("h-center", CanvasControl().width, xrange, -60); layer.align("v-center", CanvasControl().height, yrange, 240); rangeX += 1; rangeY += 1 } }); break; case 83: //s - приблизить mapLayers.map(function(layer) { if (rangeY - 1 > defaultRangeY - 1) { layer.setZoom("in"); layer.align("h-center", CanvasControl().width, xrange, -60); layer.align("v-center", CanvasControl().height, yrange, 240); rangeX -= 1; rangeY -= 1 } }); break; case 49: // 1 - жми АДЫН mapLayers.map(function(layer) { layer.toggleGraphicsHide(true); layer.toggleHeightShadow(true); }); break; case 50: // 2 - жми два mapLayers.map(function(layer) { layer.toggleGraphicsHide(false); layer.toggleHeightShadow(false); }); break; case 66: if (pressed && document.getElementById('gameInfo').style.display !== 'none') { document.getElementById('gameInfo').style.display = 'none'; } else if (pressed){ document.getElementById('gameInfo').style.display = 'block'; } break; case 89: //Поворот Y, U if (pressed) { mapLayers.map(function(layer) { layer.rotate("left"); }); } break; case 85: //Поворот Y, U if (pressed) { mapLayers.map(function(layer) { layer.rotate("right"); }); } break; case 75: //save на кнопку, пока что-почему-то не работает, но метод лучше оставить. Вдруг пригодится))) //в нём чувствуется какая-то будущее нужда на ровне с вебсокетом var XML = new XMLPopulate(); XML.saveMap(44, mapLayers[0].getLayout(), mapLayers[0].getHeightLayout(), null); break; case 39: //down - X-- //left - Y++ //up - Y-- //right - X++ if (pressed) { mapLayers.map(function(layer) { console.log(layer); layer.move('down', gameScheme.tileHeight); layer.move('left', gameScheme.tileHeight); }); startX --; startY ++; } break; case 38: if (pressed) { mapLayers.map(function(layer) { layer.move('down', gameScheme.tileHeight); layer.move('up', gameScheme.tileHeight); }); startX --; startY --; } break; case 40: if (pressed) { mapLayers.map(function(layer) { layer.move("right", gameScheme.tileHeight); layer.move("left", gameScheme.tileHeight); }); startX ++; startY ++; } break; case 37: if (pressed) { mapLayers.map(function(layer) { layer.move("up",gameScheme.tileHeight); layer.move("right",gameScheme.tileHeight); }); startX ++; startY --; } break; } }); function draw() { context.clearRect(0, 0, CanvasControl().width, CanvasControl().height); for(i = startY; i < startY + rangeY; i++) { for(j = startX; j < startX + rangeX; j++) { mapLayers.map(function(layer) { layer.draw(i,j); }); } } requestAnimFrame(draw); } return { init: function(layers) { for (var i = 0; i < 0 + layers.length; i++) { mapLayers[i] = new TileField(context, CanvasControl().height, CanvasControl().width); mapLayers[i].setup(layers[i]); mapLayers[i].align("h-center", CanvasControl().width, xrange + startX, 0); mapLayers[i].align("v-center", CanvasControl().height, yrange + startY, (yrange + startY)); mapLayers[i].setZoom("in"); }; draw(); } } } launch(); });
mit
chumak84/dance-competition-system
dcs-api/Startup.cs
1786
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace dcs_api { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => options.AddPolicy("AllowDebugCors", builder => { builder.WithOrigins("http://localhost:3000") .AllowAnyMethod() .AllowAnyHeader(); })); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseCors("AllowDebugCors"); app.UseMvc(); } } }
mit
p-org/P
Src/PCompiler/CompilerCore/TypeChecker/AST/Expressions/IVariableRef.cs
201
using Plang.Compiler.TypeChecker.AST.Declarations; namespace Plang.Compiler.TypeChecker.AST.Expressions { public interface IVariableRef : IExprTerm { Variable Variable { get; } } }
mit