void MapVariant::insertKeyAtPos(int pos) { const std::vector<Variant> &keys = getKeyVector(); HphpMapVariantToInt newmap; m_nextIndex = 0; for (int i = 0; i <= (int)keys.size(); i++) { if (i == pos) { Variant newkey((int64)m_nextIndex++); newmap[newkey] = pos; } else { CVarRef key = keys[i > pos ? i-1 : i]; int value = m_map[key]; if (value >= pos) value++; if (key.isInteger() && key.toInt64() >= 0) { Variant newkey((int64)m_nextIndex++); newmap[newkey] = value; } else { newmap[key] = value; } } } m_map.swap(newmap); resetKeyVector(); }
//test bucket_find_entry and bucket_overflow_remove static void test_bucket_find_entry(struct lruhash *table) { testkey *k1 = newkey(12); testkey *k2 = newkey(12 + 1024); testkey *k3 = newkey(14); testkey *k4 = newkey(12 + 1024*2); hashvalue_t h = simplehash(12); struct lruhash_bucket bucket; memset(&bucket, 0, sizeof(bucket)); //remove from empty list bucket_overflow_remove(&bucket, &k1->entry); //find in empty list unit_assert(bucket_find_entry(table, &bucket, h, k1) == NULL); //insert bucket.overflow_list = &k1->entry; unit_assert(bucket_find_entry(table, &bucket, simplehash(13), k1) == NULL); unit_assert(k1->entry.hash == k2->entry.hash); unit_assert(bucket_find_entry(table, &bucket, h, k2) == NULL); unit_assert(bucket_find_entry(table, &bucket, h, k1) == &k1->entry); //remove bucket_overflow_remove(&bucket, &k1->entry); unit_assert(bucket_find_entry(table, &bucket, h, k1) == NULL); //insert multi unit_assert(k1->entry.hash == k4->entry.hash); k4->entry.overflow_next = &k1->entry; k3->entry.overflow_next = &k4->entry; bucket.overflow_list = &k3->entry; unit_assert(bucket_find_entry(table, &bucket, simplehash(13), k1) == NULL); unit_assert(k1->entry.hash == k2->entry.hash); unit_assert(bucket_find_entry(table, &bucket, h, k2) == NULL); unit_assert(bucket_find_entry(table, &bucket, h, k1) == &k1->entry); //remove mid unit_assert(bucket_find_entry(table, &bucket, k4->entry.hash, k4) == &k4->entry); bucket_overflow_remove(&bucket, &k4->entry); unit_assert(bucket_find_entry(table, &bucket, k4->entry.hash, k4) == NULL); //remove last bucket_overflow_remove(&bucket, &k1->entry); unit_assert(bucket_find_entry(table, &bucket, h, k1) == NULL); delkey(k1); delkey(k2); delkey(k3); delkey(k4); }
//same as arith rules for relative comparisons. UTI NodeBinaryOpCompare::calcNodeType(UTI lt, UTI rt) { if(!m_state.neitherNAVokUTItoContinue(lt, rt)) return Nav; if(!m_state.isComplete(lt) || !m_state.isComplete(rt)) return Hzy; //no atoms, elements nor void as either operand if(!NodeBinaryOp::checkForPrimitiveNotVoidTypes(lt, rt)) return Nav; // only int, unsigned, unary types; not bool, bits, etc.. if(!NodeBinaryOp::checkForNumericTypes(lt, rt)) return Nav; //err output UTI newType = Nav; //init // all operations are performed as Int(32) or Unsigned(32) in CastOps.h // if one is unsigned, and the other isn't -> output error if unsafe; // Signed Int wins, unless its a constant. // Class (i.e. quark) + anything goes to Int(32) if(checkScalarTypesOnly(lt, rt)) { s32 newbs = NodeBinaryOp::resultBitsize(lt, rt); ULAMTYPE ltypEnum = m_state.getUlamTypeByIndex(lt)->getUlamTypeEnum(); ULAMTYPE rtypEnum = m_state.getUlamTypeByIndex(rt)->getUlamTypeEnum(); // treat Unary using Unsigned rules if(ltypEnum == Unary) ltypEnum = Unsigned; if(rtypEnum == Unary) rtypEnum = Unsigned; if(ltypEnum == Unsigned && rtypEnum == Unsigned) { UlamKeyTypeSignature newkey(m_state.m_pool.getIndexForDataString("Unsigned"), newbs); newType = m_state.makeUlamType(newkey, Unsigned, UC_NOTACLASS); } else { UlamKeyTypeSignature newkey(m_state.m_pool.getIndexForDataString("Int"), newbs); newType = m_state.makeUlamType(newkey, Int, UC_NOTACLASS); } checkSafeToCastTo(getNodeType(), newType); ////Nav, Hzy or no change; outputs error msg } //both scalars return newType; } //calcNodeType
//test lru_front and lru_remove static void test_lru(struct lruhash *table) { testkey *k1 = newkey(12); testkey *k2 = newkey(14); lock_basic_lock(&table->lock); unit_assert(table->lru_head == NULL && table->lru_tail == NULL); lru_remove(table, &k1->entry); unit_assert(table->lru_head == NULL && table->lru_tail == NULL); //add one lru_front(table, &k1->entry); unit_assert( table->lru_head == &k1->entry && table->lru_tail == &k1->entry); //remove lru_remove(table, &k1->entry); unit_assert(table->lru_head == NULL && table->lru_tail == NULL); //add two lru_front(table, &k1->entry); unit_assert(table->lru_head == &k1->entry && table->lru_tail == &k1->entry); lru_front(table, &k2->entry); unit_assert(table->lru_head == &k2->entry && table->lru_tail == &k1->entry); //remove first lru_remove(table, &k2->entry); unit_assert(table->lru_head == &k1->entry && table->lru_tail == &k1->entry); lru_front(table, &k2->entry); unit_assert(table->lru_head == &k2->entry && table->lru_tail == &k1->entry); //remove last lru_remove(table, &k1->entry); unit_assert(table->lru_head == &k2->entry && table->lru_tail == &k2->entry); //empty lru_remove(table, &k2->entry); unit_assert(table->lru_head == NULL && table->lru_tail == NULL); lock_basic_unlock(&table->lock); delkey(k1); delkey(k2); }
//test remove a random element static void testremove(struct lruhash *table, testdata *ref[]) { int num = random() % MAXHASH; testkey *key = newkey(num); lruhash_remove(table, simplehash(num), key); if (ref) ref[num] = NULL; delkey(key); }
/** test adding a random element */ static void testremove(struct lruhash* table, testdata_t* ref[]) { int num = random() % HASHTESTMAX; testkey_t* key = newkey(num); lruhash_remove(table, myhash(num), key); ref[num] = NULL; delkey(key); }
/** test lru_front lru_remove */ static void test_lru(struct lruhash* table) { testkey_t* k = newkey(12); testkey_t* k2 = newkey(14); lock_quick_lock(&table->lock); unit_assert( table->lru_start == NULL && table->lru_end == NULL); lru_remove(table, &k->entry); unit_assert( table->lru_start == NULL && table->lru_end == NULL); /* add one */ lru_front(table, &k->entry); unit_assert( table->lru_start == &k->entry && table->lru_end == &k->entry); /* remove it */ lru_remove(table, &k->entry); unit_assert( table->lru_start == NULL && table->lru_end == NULL); /* add two */ lru_front(table, &k->entry); unit_assert( table->lru_start == &k->entry && table->lru_end == &k->entry); lru_front(table, &k2->entry); unit_assert( table->lru_start == &k2->entry && table->lru_end == &k->entry); /* remove first in list */ lru_remove(table, &k2->entry); unit_assert( table->lru_start == &k->entry && table->lru_end == &k->entry); lru_front(table, &k2->entry); unit_assert( table->lru_start == &k2->entry && table->lru_end == &k->entry); /* remove last in list */ lru_remove(table, &k->entry); unit_assert( table->lru_start == &k2->entry && table->lru_end == &k2->entry); /* empty the list */ lru_remove(table, &k2->entry); unit_assert( table->lru_start == NULL && table->lru_end == NULL); lock_quick_unlock(&table->lock); delkey(k); delkey(k2); }
//test add a random element static void testadd(struct lruhash *table, testdata *ref[]) { int num = random() % MAXHASH; testdata *data = newdata(num); testkey *key = newkey(num); key->entry.data = data; lruhash_insert(table, simplehash(num), &key->entry, data); if(ref) ref[num] = data; }
/** test adding a random element (unlimited range) */ static void testremove_unlim(struct lruhash* table, testdata_t** ref) { int num = random() % (HASHTESTMAX*10); testkey_t* key = newkey(num); lruhash_remove(table, myhash(num), key); if(ref) ref[num] = NULL; delkey(key); }
/** test adding a random element */ static void testadd(struct lruhash* table, testdata_t* ref[]) { int numtoadd = random() % HASHTESTMAX; testdata_t* data = newdata(numtoadd); testkey_t* key = newkey(numtoadd); key->entry.data = data; lruhash_insert(table, myhash(numtoadd), &key->entry, data, NULL); ref[numtoadd] = data; }
/** test adding a random element (unlimited range) */ static void testadd_unlim(struct lruhash* table, testdata_t** ref) { int numtoadd = random() % (HASHTESTMAX * 10); testdata_t* data = newdata(numtoadd); testkey_t* key = newkey(numtoadd); key->entry.data = data; lruhash_insert(table, myhash(numtoadd), &key->entry, data, NULL); if(ref) ref[numtoadd] = data; }
/** test hashtable using short sequence */ static void test_short_table(struct lruhash* table) { testkey_t* k = newkey(12); testkey_t* k2 = newkey(14); testdata_t* d = newdata(128); testdata_t* d2 = newdata(129); k->entry.data = d; k2->entry.data = d2; lruhash_insert(table, myhash(12), &k->entry, d, NULL); lruhash_insert(table, myhash(14), &k2->entry, d2, NULL); unit_assert( lruhash_lookup(table, myhash(12), k, 0) == &k->entry); lock_rw_unlock( &k->entry.lock ); unit_assert( lruhash_lookup(table, myhash(14), k2, 0) == &k2->entry); lock_rw_unlock( &k2->entry.lock ); lruhash_remove(table, myhash(12), k); lruhash_remove(table, myhash(14), k2); }
UTI NodeBinaryOpLogical::calcNodeType(UTI lt, UTI rt) //logical { if(!m_state.okUTItoContinue(lt, rt)) return Nav; if(!m_state.isComplete(lt) || !m_state.isComplete(rt)) return Hzy; //no atoms, elements nor voids as either operand if(!NodeBinaryOp::checkForPrimitiveTypes(lt, rt)) return Nav; UTI newType = Nav; //init // all logical operations are performed as Bool.BITSPERBOOL.-1 if(NodeBinaryOp::checkScalarTypesOnly(lt, rt)) { s32 maxbs = 1; FORECAST lscr = m_state.getUlamTypeByIndex(Bool)->safeCast(lt); FORECAST rscr = m_state.getUlamTypeByIndex(Bool)->safeCast(rt); //check for Bool, or safe Non-Bool to Bool casting cases: if(lscr != CAST_CLEAR || rscr != CAST_CLEAR) { std::ostringstream msg; msg << "Bool is the supported type for logical operator"; msg << getName() << "; Suggest casting "; msg << m_state.getUlamTypeNameBriefByIndex(lt).c_str() << " and "; msg << m_state.getUlamTypeNameBriefByIndex(rt).c_str(); msg << " to Bool"; if(lscr == CAST_BAD || rscr == CAST_BAD) { MSG(getNodeLocationAsString().c_str(), msg.str().c_str(), ERR); newType = Nav; } else { MSG(getNodeLocationAsString().c_str(), msg.str().c_str(), DEBUG); //hazy m_state.setGoAgain(); newType = Hzy; } } else { s32 lbs = m_state.getBitSize(lt); s32 rbs = m_state.getBitSize(rt); maxbs = (lbs > rbs ? lbs : rbs); //both bool. ok to cast. use larger bool bitsize. UlamKeyTypeSignature newkey(m_state.m_pool.getIndexForDataString("Bool"), maxbs); newType = m_state.makeUlamType(newkey, Bool, UC_NOTACLASS); } } //both scalars return newType; } //calcNodeType
ulong etimer(ulong key, int n) { if(Stimer != -1) drawerror(display, "events: timer started twice"); Stimer = newkey(key); if(n <= 0) n = 1000; eslave[Stimer].n = n; eslave[Stimer].nexttick = nsec()+n*1000000LL; return 1<<Stimer; }
//test lruhash_insert, lruhash_lookup and lruhash_remove static void test_short_table(struct lruhash *table) { testkey *k1 = newkey(12); testkey *k2 = newkey(14); testdata *d1 = newdata(128); testdata *d2 = newdata(129); k1->entry.data = d1; k2->entry.data = d2; lruhash_insert(table, simplehash(12), &k1->entry, d1); lruhash_insert(table, simplehash(14), &k2->entry, d2); unit_assert(lruhash_lookup(table, simplehash(12), k1) == &k1->entry); lock_basic_unlock(&k1->entry.lock); unit_assert(lruhash_lookup(table, simplehash(14), k2) == &k2->entry); lock_basic_unlock(&k2->entry.lock ); lruhash_remove(table, simplehash(12), k1); lruhash_remove(table, simplehash(14), k2); }
ulong estartfn(ulong key, int fd, int n, int (*fn)(int, Event*, uchar*, int)) { int i; if(fd < 0) drawerror(display, "events: bad file descriptor"); if(n <= 0 || n > EMAXMSG) n = EMAXMSG; i = newkey(key); eslave[i].fn = fn; eslave[i].fd = fd; eslave[i].n = n; return 1<<i; }
/* k:create(subkeyname) * k:create(subkeyname, SAM) */ static int hkey_create(lua_State *L) { HKEY k, *pk; const char *subkey; REGSAM sam = KEY_ALL_ACCESS; LONG ret; k = *checkkey(L, 1); subkey = luaL_checkstring(L, 2); if (!lua_isnoneornil(L, 3)) sam = (REGSAM)luaL_checknumber(L, 3); pk = newkey(L); ret = RegCreateKeyEx(k, subkey, 0, 0, 0, sam, 0, pk, 0); return windows_pusherror(L, ret, 1); }
UTI NodeUnaryOpBang::calcNodeType(UTI uti) { if(uti == Nav) return Nav; if(!m_state.isComplete(uti)) return Hzy; ULAMTYPE typEnum = m_state.getUlamTypeByIndex(uti)->getUlamTypeEnum(); if(typEnum == Bits) { std::ostringstream msg; msg << "Incompatible Bits type for unary "; msg << getName() << ". Suggest casting to a Bool first"; MSG(getNodeLocationAsString().c_str(), msg.str().c_str(), ERR); return Nav; } if(!NodeUnaryOp::checkForPrimitiveType(uti)) return Nav; UTI newType = Nav; s32 newbs = (typEnum == Bool ? m_state.getBitSize(uti) : 1); FORECAST scr = m_state.getUlamTypeByIndex(Bool)->safeCast(uti); if(scr != CAST_CLEAR) { std::ostringstream msg; msg << "Bool is the supported type for logical unary "; msg << getName() << "; Suggest casting "; msg << m_state.getUlamTypeNameBriefByIndex(uti).c_str(); msg << " to Bool"; if(scr == CAST_HAZY) { MSG(getNodeLocationAsString().c_str(), msg.str().c_str(), WAIT); m_state.setGoAgain(); newType = Hzy; } else MSG(getNodeLocationAsString().c_str(), msg.str().c_str(), ERR); } else { // safe to cast. use a bool bitsize. UlamKeyTypeSignature newkey(m_state.m_pool.getIndexForDataString("Bool"), newbs); newType = m_state.makeUlamType(newkey, Bool, UC_NOTACLASS); } return newType; } //calcNodeType
//test lookup a random element static void testlookup(struct lruhash *table, testdata *ref[]) { int num = random() % MAXHASH; testkey *key = newkey(num); struct lruhash_entry *e = lruhash_lookup(table, simplehash(num), key); testdata *data = e ? (testdata *)e->data : NULL; if(e) { unit_assert(e->key); unit_assert(e->data); lock_basic_unlock(&e->lock); } if (ref) unit_assert(data == ref[num]); delkey(key); }
/** test adding a random element */ static void testlookup(struct lruhash* table, testdata_t* ref[]) { int num = random() % HASHTESTMAX; testkey_t* key = newkey(num); struct lruhash_entry* en = lruhash_lookup(table, myhash(num), key, 0); testdata_t* data = en? (testdata_t*)en->data : NULL; if(en) { unit_assert(en->key); unit_assert(en->data); } if(0) log_info("lookup %d got %d, expect %d", num, en? data->data :-1, ref[num]? ref[num]->data : -1); unit_assert( data == ref[num] ); if(en) { lock_rw_unlock(&en->lock); } delkey(key); }
void MapVariant::renumber() { const std::vector<Variant> &keys = getKeyVector(); HphpMapVariantToInt newmap; m_nextIndex = 0; for (unsigned int i = 0; i < keys.size(); i++) { CVarRef key = keys[i]; if (key.isInteger()) { Variant newkey((int64)m_nextIndex++); newmap[newkey] = m_map[key]; } else { newmap[key] = m_map[key]; } } m_map.swap(newmap); resetKeyVector(); }
/** test adding a random element (unlimited range) */ static void testlookup_unlim(struct lruhash* table, testdata_t** ref) { int num = random() % (HASHTESTMAX*10); testkey_t* key = newkey(num); struct lruhash_entry* en = lruhash_lookup(table, myhash(num), key, 0); testdata_t* data = en? (testdata_t*)en->data : NULL; if(en) { unit_assert(en->key); unit_assert(en->data); } if(0 && ref) log_info("lookup unlim %d got %d, expect %d", num, en ? data->data :-1, ref[num] ? ref[num]->data : -1); if(data && ref) { /* its okay for !data, it fell off the lru */ unit_assert( data == ref[num] ); } if(en) { lock_rw_unlock(&en->lock); } delkey(key); }
/** test bin_find_entry function and bin_overflow_remove */ static void test_bin_find_entry(struct lruhash* table) { testkey_t* k = newkey(12); testdata_t* d = newdata(128); testkey_t* k2 = newkey(12 + 1024); testkey_t* k3 = newkey(14); testkey_t* k4 = newkey(12 + 1024*2); hashvalue_t h = myhash(12); struct lruhash_bin bin; memset(&bin, 0, sizeof(bin)); bin_init(&bin, 1); /* remove from empty list */ bin_overflow_remove(&bin, &k->entry); /* find in empty list */ unit_assert( bin_find_entry(table, &bin, h, k) == NULL ); /* insert */ lock_quick_lock(&bin.lock); bin.overflow_list = &k->entry; lock_quick_unlock(&bin.lock); /* find, hash not OK. */ unit_assert( bin_find_entry(table, &bin, myhash(13), k) == NULL ); /* find, hash OK, but cmp not */ unit_assert( k->entry.hash == k2->entry.hash ); unit_assert( bin_find_entry(table, &bin, h, k2) == NULL ); /* find, hash OK, and cmp too */ unit_assert( bin_find_entry(table, &bin, h, k) == &k->entry ); /* remove the element */ lock_quick_lock(&bin.lock); bin_overflow_remove(&bin, &k->entry); lock_quick_unlock(&bin.lock); unit_assert( bin_find_entry(table, &bin, h, k) == NULL ); /* prepend two different elements; so the list is long */ /* one has the same hash, but different cmp */ lock_quick_lock(&bin.lock); unit_assert( k->entry.hash == k4->entry.hash ); k4->entry.overflow_next = &k->entry; k3->entry.overflow_next = &k4->entry; bin.overflow_list = &k3->entry; lock_quick_unlock(&bin.lock); /* find, hash not OK. */ unit_assert( bin_find_entry(table, &bin, myhash(13), k) == NULL ); /* find, hash OK, but cmp not */ unit_assert( k->entry.hash == k2->entry.hash ); unit_assert( bin_find_entry(table, &bin, h, k2) == NULL ); /* find, hash OK, and cmp too */ unit_assert( bin_find_entry(table, &bin, h, k) == &k->entry ); /* remove middle element */ unit_assert( bin_find_entry(table, &bin, k4->entry.hash, k4) == &k4->entry ); lock_quick_lock(&bin.lock); bin_overflow_remove(&bin, &k4->entry); lock_quick_unlock(&bin.lock); unit_assert( bin_find_entry(table, &bin, k4->entry.hash, k4) == NULL); /* remove last element */ lock_quick_lock(&bin.lock); bin_overflow_remove(&bin, &k->entry); lock_quick_unlock(&bin.lock); unit_assert( bin_find_entry(table, &bin, h, k) == NULL ); lock_quick_destroy(&bin.lock); delkey(k); delkey(k2); delkey(k3); delkey(k4); deldata(d); }
int luaopen_windows_hkey(lua_State *L) { const luaL_reg hkey_lib[] = { {0,0} }; const luaL_reg hkey_methods[] = { { "open", hkey_open }, { "create", hkey_create }, { "close", hkey_close }, { "delete", hkey_delete }, { "queryvalue", hkey_queryvalue }, { "setvalue", hkey_setvalue }, { "deletevalue", hkey_deletevalue }, { "enumkeys", hkey_enumkeys }, { "enumvalues", hkey_enumvalues }, { "__tostring", hkey_tostring }, { "__gc", hkey_close }, { 0, 0 } }; const struct constant { const char *name; DWORD value; } *pconst, hkey_consts[] = { /* Registry Value Types */ { "REG_SZ", REG_SZ }, { "REG_EXPAND_SZ", REG_EXPAND_SZ }, { "REG_DWORD", REG_DWORD }, { "REG_QWORD", REG_QWORD }, { "REG_BINARY", REG_BINARY }, { "REG_NONE", REG_NONE }, { "REG_DWORD_LITTLE_ENDIAN", REG_DWORD_LITTLE_ENDIAN }, { "REG_DWORD_BIG_ENDIAN", REG_DWORD_BIG_ENDIAN }, { "REG_LINK", REG_LINK }, { "REG_MULTI_SZ", REG_MULTI_SZ }, { "REG_QWORD_LITTLE_ENDIAN", REG_QWORD_LITTLE_ENDIAN }, /* Registry access rights for open() and create() methods */ { "KEY_ALL_ACCESS", KEY_ALL_ACCESS }, { "KEY_CREATE_LINK", KEY_CREATE_LINK }, { "KEY_CREATE_SUB_KEY", KEY_CREATE_SUB_KEY }, { "KEY_ENUMERATE_SUB_KEYS", KEY_ENUMERATE_SUB_KEYS }, { "KEY_EXECUTE", KEY_EXECUTE }, { "KEY_NOTIFY", KEY_NOTIFY }, { "KEY_QUERY_VALUE", KEY_QUERY_VALUE }, { "KEY_READ", KEY_READ }, { "KEY_SET_VALUE", KEY_SET_VALUE }, { "KEY_WRITE", KEY_WRITE }, /* { "KEY_WOW64_64KEY", KEY_WOW64_64KEY }, { "KEY_WOW64_32KEY", KEY_WOW64_32KEY }, */ { 0, 0 } }; const struct toplevel { const char *name; HKEY key; } *ptop, hkey_top[] = { { "HKEY_CLASSES_ROOT", HKEY_CLASSES_ROOT }, { "HKEY_CURRENT_CONFIG", HKEY_CURRENT_CONFIG }, { "HKEY_CURRENT_USER", HKEY_CURRENT_USER }, { "HKEY_LOCAL_MACHINE", HKEY_LOCAL_MACHINE }, { "HKEY_USERS", HKEY_USERS }, { 0, 0 } }; luaL_newmetatable(L, HKEYHANDLE); /* mt */ lua_pushliteral(L, "__index"); /* mt, "__index" */ lua_pushvalue(L, -2); /* mt, "__index", mt */ lua_settable(L, -3); /* mt */ luaL_openlib(L, 0, hkey_methods, 0); /* mt */ luaL_register(L, "windows.hkey", hkey_lib); for (pconst = hkey_consts; pconst->name; pconst++) { lua_pushstring(L, pconst->name); /* hkey, name */ lua_pushnumber(L, pconst->value); /* hkey, name, value */ lua_settable(L, -3); /* hkey */ } for (ptop = hkey_top; ptop->name; ptop++) { lua_pushstring(L, ptop->name); /* hkey, name */ *newkey(L) = ptop->key; /* hkey, name, key */ lua_settable(L, -3); /* hkey */ } return 1; }
// ====================================================================== void EventInputQueue::push_KeyboardEventCallback(OSObject* target, unsigned int eventType, unsigned int flags, unsigned int key, unsigned int charCode, unsigned int charSet, unsigned int origCharCode, unsigned int origCharSet, unsigned int keyboardType, bool repeat, AbsoluteTime ts, OSObject* sender, void* refcon) { GlobalLock::ScopedLock lk; if (!lk) return; Params_KeyboardEventCallBack::log(true, EventType(eventType), Flags(flags), KeyCode(key), KeyboardType(keyboardType), repeat); // ------------------------------------------------------------ // Ignore unknown modifiers // // You can confirm an unknown modifier by setting key code to 255 on Seil. // This event also will be sent by Fn key on Leopold FC660M. // // KeyboardEventCallback [ caught]: eventType 12, flags 0x80000000, key 0x00ff, kbdType 43, repeat = 0 // // This key sends the same event at key pressing and key releasing. // Therefore, we cannot recognize whether key is pressed or key is released. // So, we have to ignore this key for PressingPhysicalKeys. // if (EventType::MODIFY == EventType(eventType)) { if (KeyCode(key).getModifierFlag() == ModifierFlag::ZERO) { IOLOG_DEBUG("An unknown modifier is pressed (KeyCode:0x%x, Flags:0x%x). Ignore it.\n", key, flags); return; } } // ------------------------------------------------------------ KeyboardType newkeyboardtype(keyboardType); RemapClassManager::remap_setkeyboardtype(newkeyboardtype); KeyCode newkey(key); Flags newflags(flags); KeyCode::normalizeKey(newkey, newflags, EventType(eventType), newkeyboardtype); // ------------------------------------------------------------ Params_KeyboardEventCallBack params(EventType(eventType), newflags, newkey, CharCode(charCode), CharSet(charSet), OrigCharCode(origCharCode), OrigCharSet(origCharSet), newkeyboardtype, repeat); // ------------------------------------------------------------ IOHIKeyboard* device = OSDynamicCast(IOHIKeyboard, sender); if (!device) return; ListHookedKeyboard::Item* item = static_cast<ListHookedKeyboard::Item*>(ListHookedKeyboard::instance().get(device)); if (!item) return; // ------------------------------------------------------------ // Device Hacks // Drop events if "Disable an internal keyboard while external keyboards are connected" is enabled. if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_disable_internal_keyboard_if_external_keyboard_exsits)) { if (item->isInternalDevice() && ListHookedKeyboard::instance().isExternalDevicesConnected()) { return; } } // Logitech Cordless Presenter (LCP) Hack // // When an LCP is first plugged in, it will send a CONTROL_L down event // when the first pageup/pagedown key is pressed without sending a corresponding // up event -- effectively rendering the device (and the Mac) useless until it is // unplugged from the system. // // Similarly, when the volume keys are first pressed, a SHIFT_L down event // is generated, with now up event. // // This code effectively throws these events away if they are received from an LCP. // // *** LCP has 6 keys (Page Up, Page Down, a 'B' key, an 'Esc' key, and volume up / down keys). *** // *** So, we can drop CONTROL_L and SHIFT_L without a problem. *** if ((item->getDeviceIdentifier()).isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_CORDLESS_PRESENTER)) { if (params.key == KeyCode::CONTROL_L) return; if (params.key == KeyCode::SHIFT_L) return; } // ------------------------------------------------------------ // NumLock Hacks // // As for some keypads, NumLock is off when it was connected. // We need to call setAlphaLock(true) to activate a device. RemapClassManager::remap_forcenumlockon(item); // ------------------------------------------------------------ CommonData::setcurrent_ts(ts); // ------------------------------------------------------------ // Because we handle the key repeat ourself, drop the key repeat by hardware. if (repeat) return; // ------------------------------------------------------------ bool retainFlagStatusTemporaryCount = false; bool push_back = true; bool isSimultaneousKeyPressesTarget = true; enqueue_(params, retainFlagStatusTemporaryCount, item->getDeviceIdentifier(), push_back, isSimultaneousKeyPressesTarget); setTimer(); }
// ====================================================================== void EventInputQueue::push_KeyboardEventCallback(OSObject* target, unsigned int eventType, unsigned int flags, unsigned int key, unsigned int charCode, unsigned int charSet, unsigned int origCharCode, unsigned int origCharSet, unsigned int keyboardType, bool repeat, AbsoluteTime ts, OSObject* sender, void* refcon) { IOLockWrapper::ScopedLock lk_eventlock(CommonData::getEventLock()); if (! lk_eventlock) return; IOLockWrapper::ScopedLock lk(timer_.getlock()); if (! lk) return; // ------------------------------------------------------------ KeyboardType newkeyboardtype(keyboardType); RemapClassManager::remap_setkeyboardtype(newkeyboardtype); KeyCode newkey(key); Flags newflags(flags); KeyCode::normalizeKey(newkey, newflags, EventType(eventType), newkeyboardtype); // ------------------------------------------------------------ Params_KeyboardEventCallBack::auto_ptr ptr(Params_KeyboardEventCallBack::alloc(EventType(eventType), newflags, newkey, CharCode(charCode), CharSet(charSet), OrigCharCode(origCharCode), OrigCharSet(origCharSet), newkeyboardtype, repeat)); if (! ptr) return; Params_KeyboardEventCallBack& params = *ptr; // ------------------------------------------------------------ DeviceVendor deviceVendor(0); DeviceProduct deviceProduct(0); { IOLockWrapper::ScopedLock lk_device(ListHookedKeyboard::instance().getListLock()); if (! lk_device) return; IOHIKeyboard* device = OSDynamicCast(IOHIKeyboard, sender); if (! device) return; ListHookedKeyboard::Item* item = static_cast<ListHookedKeyboard::Item*>(ListHookedKeyboard::instance().get_nolock(device)); if (! item) return; // ------------------------------------------------------------ // Logitech Cordless Presenter (LCP) Hack // // When an LCP is first plugged in, it will send a CONTROL_L down event // when the first pageup/pagedown key is pressed without sending a corresponding // up event -- effectively rendering the device (and the Mac) useless until it is // unplugged from the system. // // Similarly, when the volume keys are first pressed, a SHIFT_L down event // is generated, with now up event. // // This code effectively throws these events away if they are received from an LCP. // // *** LCP has 6 keys (Page Up, Page Down, a 'B' key, an 'Esc' key, and volume up / down keys). *** // *** So, we can drop CONTROL_L and SHIFT_L without a problem. *** if (item->isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_CORDLESS_PRESENTER)) { if (params.key == KeyCode::CONTROL_L) return; if (params.key == KeyCode::SHIFT_L) return; } // ------------------------------------------------------------ // "ts & keyboardType" are not used in filters like <not>/<only>. // Therefore, we can set current ts and keyboardType here. CommonData::setcurrent_ts(ts); CommonData::setcurrent_keyboardType(params.keyboardType); deviceVendor = item->getVendor(); deviceProduct = item->getProduct(); } // ------------------------------------------------------------ // Because we handle the key repeat ourself, drop the key repeat by hardware. if (repeat) return; // ------------------------------------------------------------ bool retainFlagStatusTemporaryCount = false; bool push_back = true; enqueue_(params, retainFlagStatusTemporaryCount, deviceVendor, deviceProduct, push_back); setTimer(); }
// Calls the same method of the superclass. bool svm::genericTrain(const dmatrix& input, const ivector& ids) { char buffer[80]; if (validProgressObject()) { getProgressObject().reset(); getProgressObject().setTitle("SVM: Training"); getProgressObject().setMaxSteps(nClasses); } bias.resize(nClasses,getParameters().bias,false,true); trainData=new dmatrix(input); alpha.resize(nClasses,input.rows(),0,false,true); makeTargets(ids); errorCache.resize(input.rows()); const parameters& param=getParameters(); C=param.C; tolerance=param.tolerance; epsilon=param.epsilon; bool abort=false; // train one SVM for each class for (int cid=0; cid<nClasses && !abort; cid++) { int numChanged=0; bool examineAll=true; currentTarget=&target->getRow(cid); currentClass=cid; currentAlpha=&alpha.getRow(cid); _lti_debug("Training class " << cid << "\n"); fillErrorCache(); while ((numChanged > 0 || examineAll) && !abort) { numChanged=0; if (examineAll) { // iterate over all alphas for (int i=0; i<trainData->rows(); i++) { if (examineExample(i)) { numChanged++; } } // next turn, look only at non-bound alphas examineAll=false; } else { // iterate over all non-0 and non-C alphas int *tmpAlpha=new int[alpha.getRow(cid).size()]; int j=0,i=0; for (i=0; i<alpha.getRow(cid).size(); i++) { if (alpha.getRow(cid).at(i) != 0.0 && alpha.getRow(cid).at(i) != C) { tmpAlpha[j++]=i; } } delete[] tmpAlpha; for (i=0; i<j; i++) { if (examineExample(i)) { numChanged++; } } // next turn, examine all if we did not succeed this time if (numChanged == 0) { examineAll=true; } } } // update progress info object if (validProgressObject()) { sprintf(buffer,"numChanged=%d, error=%f",numChanged,errorSum); getProgressObject().step(buffer); abort=abort || getProgressObject().breakRequested(); } // now limit the number of support vectors // does not work yet, so disable it if (0) { int supnum=0; ivector index(currentAlpha->size()); ivector newindex(currentAlpha->size()); dvector newkey(currentAlpha->size()); for (int i=0; i<currentAlpha->size(); i++) { if (currentAlpha->at(i) > 0) { supnum++; } index[i]=i; } if (supnum > param.nSupport && param.nSupport > 0) { lti::sort2<double> sorter; sorter.apply(*currentAlpha,index,newkey,newindex); int i; for (i=0; i<newkey.size() && lti::abs(newkey[i]) > std::numeric_limits<double>::epsilon(); i++) { } for (int j=i; j<currentAlpha->size()-param.nSupport; j++) { currentAlpha->at(newindex[j])=0; } _lti_debug("Final alpha: " << *currentAlpha << std::endl); } } } defineOutputTemplate(); _lti_debug("alpha:\n" << alpha << "\n"); // make sure that all lagrange multipliers are larger than // zero, otherwise we might get into trouble later alpha.apply(rectify); if (abort) { setStatusString("Training aborted by user!"); } return !abort; }
int main(int, char **) { introduction(); ReaderProviderPtr provider; ReaderUnitPtr readerUnit; ChipPtr chip; std::tie(provider, readerUnit, chip) = pcsc_test_init(); PRINT_TIME("CHip identifier: " << logicalaccess::BufferHelper::getHex(chip->getChipIdentifier())); LLA_ASSERT(chip->getCardType() == "DESFireEV1", "Chip is not an DESFireEV1, but is " + chip->getCardType() + " instead."); auto location_root_node = chip->getRootLocationNode(); auto cmd = std::dynamic_pointer_cast<logicalaccess::DESFireISO7816Commands>( chip->getCommands()); auto cmdev1 = std::dynamic_pointer_cast<logicalaccess::DESFireEV1ISO7816Commands>( chip->getCommands()); LLA_ASSERT(cmd && cmdev1, "Cannot get correct command object from chip."); cmd->selectApplication(0x00); cmd->authenticate(0); cmd->erase(); cmdev1->createApplication(0x521, logicalaccess::DESFireKeySettings::KS_DEFAULT, 3, logicalaccess::DESFireKeyType::DF_KEY_AES, logicalaccess::FIDS_NO_ISO_FID, 0, std::vector<unsigned char>()); cmd->selectApplication(0x521); std::shared_ptr<logicalaccess::DESFireKey> key(new logicalaccess::DESFireKey()); key->setKeyType(logicalaccess::DESFireKeyType::DF_KEY_AES); cmd->authenticate(0, key); LLA_SUBTEST_PASSED("Authenticate"); logicalaccess::DESFireAccessRights ar; ar.readAccess = logicalaccess::TaskAccessRights::AR_KEY2; ar.writeAccess = logicalaccess::TaskAccessRights::AR_KEY1; ar.readAndWriteAccess = logicalaccess::TaskAccessRights::AR_KEY1; ar.changeAccess = logicalaccess::TaskAccessRights::AR_KEY1; cmdev1->createStdDataFile(0x00, logicalaccess::EncryptionMode::CM_ENCRYPT, ar, 4, 0); cmd->authenticate(1, key); std::vector<unsigned char> data = {0x01, 0x02, 0x03, 0x04}, tmp; cmdev1->writeData(0, 0, data, logicalaccess::EncryptionMode::CM_ENCRYPT); cmd->authenticate(2, key); tmp = cmdev1->readData(0, 0, 4, logicalaccess::EncryptionMode::CM_ENCRYPT); LLA_ASSERT(std::equal(data.begin(), data.end(), tmp.begin()), "read and write data are different!"); LLA_SUBTEST_PASSED("WriteRead"); cmd->authenticate(0x00, key); cmd->deleteFile(0x00); cmd->authenticate(0x00, key); std::shared_ptr<logicalaccess::DESFireKey> newkey( new logicalaccess::DESFireKey("00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03")); cmd->changeKey(0x00, newkey); LLA_SUBTEST_PASSED("ChangeKey"); cmd->selectApplication(0x00); cmd->authenticate(0); cmd->deleteApplication(0x521); auto service = std::dynamic_pointer_cast<logicalaccess::AccessControlCardService>( chip->getService(logicalaccess::CardServiceType::CST_ACCESS_CONTROL)); LLA_ASSERT(service, "Cannot retrieve access control service from chip."); auto location = std::make_shared<logicalaccess::DESFireLocation>(); location->aid = 0x522; location->file = 0; auto ai = std::make_shared<logicalaccess::DESFireAccessInfo>(); auto format = std::make_shared<logicalaccess::Wiegand26Format>(); format->setUid(1000); format->setFacilityCode(67); service->writeFormat(format, location, ai, ai); auto formattmp = std::make_shared<logicalaccess::Wiegand26Format>(); auto rformat = std::dynamic_pointer_cast<logicalaccess::Wiegand26Format>( service->readFormat(formattmp, location, ai)); if (!rformat || rformat->getUid() != 1000 || rformat->getFacilityCode() != 67) THROW_EXCEPTION_WITH_LOG(std::runtime_error, "Bad format"); LLA_SUBTEST_PASSED("ReadFormat"); pcsc_test_shutdown(readerUnit); return EXIT_SUCCESS; }