예제 #1
0
void testGrow(){
  HashTable<std::string,int> testHash;
  testHash.add("0",0);
  unsigned long startingSize = testHash.backingArraySize;
  unsigned long i=0;
  while(testHash.backingArraySize == startingSize){
    i++;
    std::ostringstream ss;
    ss << i;
    testHash.add(ss.str(),i);
  }
  unsigned long endingSize = testHash.backingArraySize;
  if(i*2 > startingSize){
    std::cout << "ERROR: You didn't grown soon enough. Starting size was " << startingSize << ", didn't grow until " << i+1 << "adds done." << std::endl;
    return;
  } else {
    std::cout << "SUCCESS: Grow called at the right time. Starting size was " << startingSize << " and grow called on the " << i+1 << "th add call" << std::endl;
  }

  if(testHash.size() == i+1){
    std::cout << "SUCCESS: Size of hash table unchanged by the grow" << std::endl;
  } else {
    std::cout << "ERROR: Size of hash table should be " << i+1 << ", but got " << testHash.size() << std::endl;
    return;
  }

  if(testHash.numRemoved == 0){
    std::cout << "SUCCESS: After grow called, all removed items have been cleared out." << std::endl;
  } else {
    std::cout << "ERROR: When grow is called, you should clear out all the removed items." << std::endl;
    return;
  }

  for(int j=0; j<=i;j++){
    std::ostringstream ss;
    ss << j;
    if(!testHash.keyExists(ss.str())){
      std::cout << "ERROR: During grow the item with key '" << j << "' was lost" << std::endl;
      return;
    }
  }
  std::cout << "SUCCESS: After grow all items from the original table made it to the new one." << std::endl;
}
예제 #2
0
파일: main.cpp 프로젝트: ScottEdg/COS-221
int main()
{
	ifstream fin;
	string word;
	HashTable Table;
	fin.open("jumbledwords.txt");
	fin >> word;
	while(!fin.fail()){
		Table.insert(word);
		fin >> word;
	}
	fin.close();
	for (int i = 0; i < Table.getSize(); i++) {
		if (Table.clusterLength(i) > 1) {
			cout << "index " << i << "  " << Table.clusterLength(i) << endl;
		}
	}
	cout << Table.getSize();
	return 0;
}
예제 #3
0
namespace JSC {

extern const HashTable arrayConstructorTable;
extern const HashTable arrayPrototypeTable;
extern const HashTable booleanPrototypeTable;
extern const HashTable jsonTable;
extern const HashTable dateTable;
extern const HashTable dateConstructorTable;
extern const HashTable errorPrototypeTable;
extern const HashTable globalObjectTable;
extern const HashTable mathTable;
extern const HashTable numberConstructorTable;
extern const HashTable numberPrototypeTable;
JS_EXPORTDATA extern const HashTable objectConstructorTable;
extern const HashTable objectPrototypeTable;
extern const HashTable privateNamePrototypeTable;
extern const HashTable regExpTable;
extern const HashTable regExpConstructorTable;
extern const HashTable regExpPrototypeTable;
extern const HashTable stringTable;
extern const HashTable stringConstructorTable;

// Note: Platform.h will enforce that ENABLE(ASSEMBLER) is true if either
// ENABLE(JIT) or ENABLE(YARR_JIT) or both are enabled. The code below
// just checks for ENABLE(JIT) or ENABLE(YARR_JIT) with this premise in mind.

#if ENABLE(ASSEMBLER)
static bool enableAssembler(ExecutableAllocator& executableAllocator)
{
    if (!executableAllocator.isValid() || (!Options::useJIT() && !Options::useRegExpJIT()))
        return false;

#if USE(CF)
#if COMPILER(GCC) && !COMPILER(CLANG)
    // FIXME: remove this once the EWS have been upgraded to LLVM.
    // Work around a bug of GCC with strict-aliasing.
    RetainPtr<CFStringRef> canUseJITKeyRetain(AdoptCF, CFStringCreateWithCString(0 , "JavaScriptCoreUseJIT", kCFStringEncodingMacRoman));
    CFStringRef canUseJITKey = canUseJITKeyRetain.get();
#else
    CFStringRef canUseJITKey = CFSTR("JavaScriptCoreUseJIT");
#endif // COMPILER(GCC) && !COMPILER(CLANG)
    RetainPtr<CFBooleanRef> canUseJIT(AdoptCF, (CFBooleanRef)CFPreferencesCopyAppValue(canUseJITKey, kCFPreferencesCurrentApplication));
    if (canUseJIT)
        return kCFBooleanTrue == canUseJIT.get();
#endif

#if USE(CF) || OS(UNIX)
    char* canUseJITString = getenv("JavaScriptCoreUseJIT");
    return !canUseJITString || atoi(canUseJITString);
#else
    return true;
#endif
}
#endif // ENABLE(!ASSEMBLER)

JSGlobalData::JSGlobalData(GlobalDataType globalDataType, HeapType heapType)
    :
#if ENABLE(ASSEMBLER)
      executableAllocator(*this),
#endif
      heap(this, heapType)
    , globalDataType(globalDataType)
    , clientData(0)
    , topCallFrame(CallFrame::noCaller())
    , arrayConstructorTable(fastNew<HashTable>(JSC::arrayConstructorTable))
    , arrayPrototypeTable(fastNew<HashTable>(JSC::arrayPrototypeTable))
    , booleanPrototypeTable(fastNew<HashTable>(JSC::booleanPrototypeTable))
    , dateTable(fastNew<HashTable>(JSC::dateTable))
    , dateConstructorTable(fastNew<HashTable>(JSC::dateConstructorTable))
    , errorPrototypeTable(fastNew<HashTable>(JSC::errorPrototypeTable))
    , globalObjectTable(fastNew<HashTable>(JSC::globalObjectTable))
    , jsonTable(fastNew<HashTable>(JSC::jsonTable))
    , mathTable(fastNew<HashTable>(JSC::mathTable))
    , numberConstructorTable(fastNew<HashTable>(JSC::numberConstructorTable))
    , numberPrototypeTable(fastNew<HashTable>(JSC::numberPrototypeTable))
    , objectConstructorTable(fastNew<HashTable>(JSC::objectConstructorTable))
    , objectPrototypeTable(fastNew<HashTable>(JSC::objectPrototypeTable))
    , privateNamePrototypeTable(fastNew<HashTable>(JSC::privateNamePrototypeTable))
    , regExpTable(fastNew<HashTable>(JSC::regExpTable))
    , regExpConstructorTable(fastNew<HashTable>(JSC::regExpConstructorTable))
    , regExpPrototypeTable(fastNew<HashTable>(JSC::regExpPrototypeTable))
    , stringTable(fastNew<HashTable>(JSC::stringTable))
    , stringConstructorTable(fastNew<HashTable>(JSC::stringConstructorTable))
    , identifierTable(globalDataType == Default ? wtfThreadData().currentIdentifierTable() : createIdentifierTable())
    , propertyNames(new CommonIdentifiers(this))
    , emptyList(new MarkedArgumentBuffer)
    , parserArena(adoptPtr(new ParserArena))
    , keywords(adoptPtr(new Keywords(this)))
    , interpreter(0)
    , jsArrayClassInfo(&JSArray::s_info)
    , jsFinalObjectClassInfo(&JSFinalObject::s_info)
#if ENABLE(DFG_JIT)
    , sizeOfLastScratchBuffer(0)
#endif
    , dynamicGlobalObject(0)
    , cachedUTCOffset(QNaN)
    , m_enabledProfiler(0)
    , m_regExpCache(new RegExpCache(this))
#if ENABLE(REGEXP_TRACING)
    , m_rtTraceList(new RTTraceList())
#endif
#ifndef NDEBUG
    , exclusiveThread(0)
#endif
#if CPU(X86) && ENABLE(JIT)
    , m_timeoutCount(512)
#endif
    , m_newStringsSinceLastHashConst(0)
#if ENABLE(ASSEMBLER)
    , m_canUseAssembler(enableAssembler(executableAllocator))
#endif
#if ENABLE(JIT)
    , m_canUseJIT(m_canUseAssembler && Options::useJIT())
#endif
#if ENABLE(YARR_JIT)
    , m_canUseRegExpJIT(m_canUseAssembler && Options::useRegExpJIT())
#endif
#if ENABLE(GC_VALIDATION)
    , m_initializingObjectClass(0)
#endif
    , m_inDefineOwnProperty(false)
    , m_codeCache(CodeCache::create())
{
    interpreter = new Interpreter(*this);

    // Need to be careful to keep everything consistent here
    JSLockHolder lock(this);
    IdentifierTable* existingEntryIdentifierTable = wtfThreadData().setCurrentIdentifierTable(identifierTable);
    structureStructure.set(*this, Structure::createStructure(*this));
    structureRareDataStructure.set(*this, StructureRareData::createStructure(*this, 0, jsNull()));
    debuggerActivationStructure.set(*this, DebuggerActivation::createStructure(*this, 0, jsNull()));
    interruptedExecutionErrorStructure.set(*this, InterruptedExecutionError::createStructure(*this, 0, jsNull()));
    terminatedExecutionErrorStructure.set(*this, TerminatedExecutionError::createStructure(*this, 0, jsNull()));
    stringStructure.set(*this, JSString::createStructure(*this, 0, jsNull()));
    notAnObjectStructure.set(*this, JSNotAnObject::createStructure(*this, 0, jsNull()));
    propertyNameIteratorStructure.set(*this, JSPropertyNameIterator::createStructure(*this, 0, jsNull()));
    getterSetterStructure.set(*this, GetterSetter::createStructure(*this, 0, jsNull()));
    apiWrapperStructure.set(*this, JSAPIValueWrapper::createStructure(*this, 0, jsNull()));
    JSScopeStructure.set(*this, JSScope::createStructure(*this, 0, jsNull()));
    executableStructure.set(*this, ExecutableBase::createStructure(*this, 0, jsNull()));
    nativeExecutableStructure.set(*this, NativeExecutable::createStructure(*this, 0, jsNull()));
    evalExecutableStructure.set(*this, EvalExecutable::createStructure(*this, 0, jsNull()));
    programExecutableStructure.set(*this, ProgramExecutable::createStructure(*this, 0, jsNull()));
    functionExecutableStructure.set(*this, FunctionExecutable::createStructure(*this, 0, jsNull()));
    regExpStructure.set(*this, RegExp::createStructure(*this, 0, jsNull()));
    sharedSymbolTableStructure.set(*this, SharedSymbolTable::createStructure(*this, 0, jsNull()));
    structureChainStructure.set(*this, StructureChain::createStructure(*this, 0, jsNull()));
    sparseArrayValueMapStructure.set(*this, SparseArrayValueMap::createStructure(*this, 0, jsNull()));
    withScopeStructure.set(*this, JSWithScope::createStructure(*this, 0, jsNull()));
    unlinkedFunctionExecutableStructure.set(*this, UnlinkedFunctionExecutable::createStructure(*this, 0, jsNull()));
    unlinkedProgramCodeBlockStructure.set(*this, UnlinkedProgramCodeBlock::createStructure(*this, 0, jsNull()));
    unlinkedEvalCodeBlockStructure.set(*this, UnlinkedEvalCodeBlock::createStructure(*this, 0, jsNull()));
    unlinkedFunctionCodeBlockStructure.set(*this, UnlinkedFunctionCodeBlock::createStructure(*this, 0, jsNull()));
    smallStrings.initializeCommonStrings(*this);

    wtfThreadData().setCurrentIdentifierTable(existingEntryIdentifierTable);

#if ENABLE(JIT)
    jitStubs = adoptPtr(new JITThunks());
    performPlatformSpecificJITAssertions(this);
#endif
    
    interpreter->initialize(this->canUseJIT());
    
#if ENABLE(JIT)
    initializeHostCallReturnValue(); // This is needed to convince the linker not to drop host call return support.
#endif

    heap.notifyIsSafeToCollect();

    LLInt::Data::performAssertions(*this);
    
    if (Options::enableProfiler())
        m_perBytecodeProfiler = adoptPtr(new Profiler::Database(*this));

#if ENABLE(DFG_JIT)
    if (canUseJIT())
        m_dfgState = adoptPtr(new DFG::LongLivedState());
#endif
}

JSGlobalData::~JSGlobalData()
{
    // Clear this first to ensure that nobody tries to remove themselves from it.
    m_perBytecodeProfiler.clear();
    
    ASSERT(!m_apiLock.currentThreadIsHoldingLock());
    heap.didStartVMShutdown();

    delete interpreter;
#ifndef NDEBUG
    interpreter = reinterpret_cast<Interpreter*>(0xbbadbeef);
#endif

    arrayPrototypeTable->deleteTable();
    arrayConstructorTable->deleteTable();
    booleanPrototypeTable->deleteTable();
    dateTable->deleteTable();
    dateConstructorTable->deleteTable();
    errorPrototypeTable->deleteTable();
    globalObjectTable->deleteTable();
    jsonTable->deleteTable();
    mathTable->deleteTable();
    numberConstructorTable->deleteTable();
    numberPrototypeTable->deleteTable();
    objectConstructorTable->deleteTable();
    objectPrototypeTable->deleteTable();
    privateNamePrototypeTable->deleteTable();
    regExpTable->deleteTable();
    regExpConstructorTable->deleteTable();
    regExpPrototypeTable->deleteTable();
    stringTable->deleteTable();
    stringConstructorTable->deleteTable();

    fastDelete(const_cast<HashTable*>(arrayConstructorTable));
    fastDelete(const_cast<HashTable*>(arrayPrototypeTable));
    fastDelete(const_cast<HashTable*>(booleanPrototypeTable));
    fastDelete(const_cast<HashTable*>(dateTable));
    fastDelete(const_cast<HashTable*>(dateConstructorTable));
    fastDelete(const_cast<HashTable*>(errorPrototypeTable));
    fastDelete(const_cast<HashTable*>(globalObjectTable));
    fastDelete(const_cast<HashTable*>(jsonTable));
    fastDelete(const_cast<HashTable*>(mathTable));
    fastDelete(const_cast<HashTable*>(numberConstructorTable));
    fastDelete(const_cast<HashTable*>(numberPrototypeTable));
    fastDelete(const_cast<HashTable*>(objectConstructorTable));
    fastDelete(const_cast<HashTable*>(objectPrototypeTable));
    fastDelete(const_cast<HashTable*>(privateNamePrototypeTable));
    fastDelete(const_cast<HashTable*>(regExpTable));
    fastDelete(const_cast<HashTable*>(regExpConstructorTable));
    fastDelete(const_cast<HashTable*>(regExpPrototypeTable));
    fastDelete(const_cast<HashTable*>(stringTable));
    fastDelete(const_cast<HashTable*>(stringConstructorTable));

    opaqueJSClassData.clear();

    delete emptyList;

    delete propertyNames;
    if (globalDataType != Default)
        deleteIdentifierTable(identifierTable);

    delete clientData;
    delete m_regExpCache;
#if ENABLE(REGEXP_TRACING)
    delete m_rtTraceList;
#endif

#if ENABLE(DFG_JIT)
    for (unsigned i = 0; i < scratchBuffers.size(); ++i)
        fastFree(scratchBuffers[i]);
#endif
}

PassRefPtr<JSGlobalData> JSGlobalData::createContextGroup(HeapType heapType)
{
    return adoptRef(new JSGlobalData(APIContextGroup, heapType));
}

PassRefPtr<JSGlobalData> JSGlobalData::create(HeapType heapType)
{
    return adoptRef(new JSGlobalData(Default, heapType));
}

PassRefPtr<JSGlobalData> JSGlobalData::createLeaked(HeapType heapType)
{
    return create(heapType);
}

bool JSGlobalData::sharedInstanceExists()
{
    return sharedInstanceInternal();
}

JSGlobalData& JSGlobalData::sharedInstance()
{
    GlobalJSLock globalLock;
    JSGlobalData*& instance = sharedInstanceInternal();
    if (!instance) {
        instance = adoptRef(new JSGlobalData(APIShared, SmallHeap)).leakRef();
        instance->makeUsableFromMultipleThreads();
    }
    return *instance;
}

JSGlobalData*& JSGlobalData::sharedInstanceInternal()
{
    static JSGlobalData* sharedInstance;
    return sharedInstance;
}

#if ENABLE(JIT)
static ThunkGenerator thunkGeneratorForIntrinsic(Intrinsic intrinsic)
{
    switch (intrinsic) {
    case CharCodeAtIntrinsic:
        return charCodeAtThunkGenerator;
    case CharAtIntrinsic:
        return charAtThunkGenerator;
    case FromCharCodeIntrinsic:
        return fromCharCodeThunkGenerator;
    case SqrtIntrinsic:
        return sqrtThunkGenerator;
    case PowIntrinsic:
        return powThunkGenerator;
    case AbsIntrinsic:
        return absThunkGenerator;
    case FloorIntrinsic:
        return floorThunkGenerator;
    case CeilIntrinsic:
        return ceilThunkGenerator;
    case RoundIntrinsic:
        return roundThunkGenerator;
    case ExpIntrinsic:
        return expThunkGenerator;
    case LogIntrinsic:
        return logThunkGenerator;
    default:
        return 0;
    }
}

NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function, NativeFunction constructor)
{
    return jitStubs->hostFunctionStub(this, function, constructor);
}
NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function, Intrinsic intrinsic)
{
    ASSERT(canUseJIT());
    return jitStubs->hostFunctionStub(this, function, intrinsic != NoIntrinsic ? thunkGeneratorForIntrinsic(intrinsic) : 0, intrinsic);
}

#else // !ENABLE(JIT)
NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function, NativeFunction constructor)
{
    return NativeExecutable::create(*this, function, constructor);
}
#endif // !ENABLE(JIT)

JSGlobalData::ClientData::~ClientData()
{
}

void JSGlobalData::resetDateCache()
{
    cachedUTCOffset = QNaN;
    dstOffsetCache.reset();
    cachedDateString = String();
    cachedDateStringValue = QNaN;
    dateInstanceCache.reset();
}

void JSGlobalData::startSampling()
{
    interpreter->startSampling();
}

void JSGlobalData::stopSampling()
{
    interpreter->stopSampling();
}

void JSGlobalData::discardAllCode()
{
    m_codeCache->clear();
    heap.deleteAllCompiledCode();
    heap.reportAbandonedObjectGraph();
}

void JSGlobalData::dumpSampleData(ExecState* exec)
{
    interpreter->dumpSampleData(exec);
#if ENABLE(ASSEMBLER)
    ExecutableAllocator::dumpProfile();
#endif
}

SourceProviderCache* JSGlobalData::addSourceProviderCache(SourceProvider* sourceProvider)
{
    SourceProviderCacheMap::AddResult addResult = sourceProviderCacheMap.add(sourceProvider, 0);
    if (addResult.isNewEntry)
        addResult.iterator->value = adoptRef(new SourceProviderCache);
    return addResult.iterator->value.get();
}

void JSGlobalData::clearSourceProviderCaches()
{
    sourceProviderCacheMap.clear();
}

struct StackPreservingRecompiler : public MarkedBlock::VoidFunctor {
    HashSet<FunctionExecutable*> currentlyExecutingFunctions;
    void operator()(JSCell* cell)
    {
        if (!cell->inherits(&FunctionExecutable::s_info))
            return;
        FunctionExecutable* executable = jsCast<FunctionExecutable*>(cell);
        if (currentlyExecutingFunctions.contains(executable))
            return;
        executable->clearCodeIfNotCompiling();
    }
};

void JSGlobalData::releaseExecutableMemory()
{
    if (dynamicGlobalObject) {
        StackPreservingRecompiler recompiler;
        HashSet<JSCell*> roots;
        heap.getConservativeRegisterRoots(roots);
        HashSet<JSCell*>::iterator end = roots.end();
        for (HashSet<JSCell*>::iterator ptr = roots.begin(); ptr != end; ++ptr) {
            ScriptExecutable* executable = 0;
            JSCell* cell = *ptr;
            if (cell->inherits(&ScriptExecutable::s_info))
                executable = static_cast<ScriptExecutable*>(*ptr);
            else if (cell->inherits(&JSFunction::s_info)) {
                JSFunction* function = jsCast<JSFunction*>(*ptr);
                if (function->isHostFunction())
                    continue;
                executable = function->jsExecutable();
            } else
                continue;
            ASSERT(executable->inherits(&ScriptExecutable::s_info));
            executable->unlinkCalls();
            if (executable->inherits(&FunctionExecutable::s_info))
                recompiler.currentlyExecutingFunctions.add(static_cast<FunctionExecutable*>(executable));
                
        }
        heap.objectSpace().forEachLiveCell<StackPreservingRecompiler>(recompiler);
    }
    m_regExpCache->invalidateCode();
    heap.collectAllGarbage();
}
    
void releaseExecutableMemory(JSGlobalData& globalData)
{
    globalData.releaseExecutableMemory();
}

#if ENABLE(DFG_JIT)
void JSGlobalData::gatherConservativeRoots(ConservativeRoots& conservativeRoots)
{
    for (size_t i = 0; i < scratchBuffers.size(); i++) {
        ScratchBuffer* scratchBuffer = scratchBuffers[i];
        if (scratchBuffer->activeLength()) {
            void* bufferStart = scratchBuffer->dataBuffer();
            conservativeRoots.add(bufferStart, static_cast<void*>(static_cast<char*>(bufferStart) + scratchBuffer->activeLength()));
        }
    }
}
#endif

#if ENABLE(REGEXP_TRACING)
void JSGlobalData::addRegExpToTrace(RegExp* regExp)
{
    m_rtTraceList->add(regExp);
}

void JSGlobalData::dumpRegExpTrace()
{
    // The first RegExp object is ignored.  It is create by the RegExpPrototype ctor and not used.
    RTTraceList::iterator iter = ++m_rtTraceList->begin();
    
    if (iter != m_rtTraceList->end()) {
        dataLogF("\nRegExp Tracing\n");
        dataLogF("                                                            match()    matches\n");
        dataLogF("Regular Expression                          JIT Address      calls      found\n");
        dataLogF("----------------------------------------+----------------+----------+----------\n");
    
        unsigned reCount = 0;
    
        for (; iter != m_rtTraceList->end(); ++iter, ++reCount)
            (*iter)->printTraceData();

        dataLogF("%d Regular Expressions\n", reCount);
    }
    
    m_rtTraceList->clear();
}
#else
void JSGlobalData::dumpRegExpTrace()
{
}
#endif

} // namespace JSC
예제 #4
0
	/** flush (clear) the cache */
	inline void Flush()
	{
		m_map.Clear();
		m_heap.Clear();
	}
예제 #5
0
int main() {
	//create_stu();
	welcome();
	command_tips();
	cout << endl;
	srand(time(0));
	
	HashTable<Student> h;
	HashTable2<Student> table;
	
	//read_stu(h, table);
	
	string command;
	while(cin >> command) {
		if (command[0] == '$') {
			if (command[1] == 'Q') break;
			switch(command[1]) {
			case 'I':
				{
					cout << "Please input a student's information (ID, name, age, gender):" << endl;
					string id, name;
					int age;
					bool sex;
					cin >> id >> name >> age >> sex;
					Student student(id, name, age, sex);
					if (h.insert(student)) {
						cout << "\nInserted successfully: " << endl;  //print the information that is removed
						cout << "Name: " << student.getName() << endl;
						cout << "ID: " << student.getID() << endl;
						cout << "Age: " << student.getAge() << endl;
						cout << "Gender: " << (student.getSex() == 0? "Male":"Female") << endl <<  endl;
					} else {
						cout << "\nInserted failed: The system already contains the student" << endl;
					}

				}
				break;
			case 'R': 
				{
					cout << "Please input the student's ID:" << endl;
					string s2;
					cin >> s2;
					h.remove(s2);
					cout << endl;
				}
				break;
			case 'F':
				{
					cout << "Please input the student's ID:" << endl;
					string s2;
					cin >> s2;
					h.findKey(s2);
					cout << endl;
				}
				break;
			case 'T':
				{
					cout << "Please wait for inputing the information from the file." << endl;
					read_stu(h, table);
					cout << "Input finished" << endl;
					cout << "Tatal numbers of student: " << totalNumber << endl;
					vector<list<Student> > ve = h.getList();
					double ave_CHI = 0, ave_OPEN = 0;
					int num = 30;
					for (int i = 0; i < num; i++) {
						list<Student>::iterator p = ve[rand() % ve.size()].end();
						string s1 = (*(--p)).getID();
						double CHAIN, OPEN;
						ave_CHI += (double)h.cal_time(s1) ;
						ave_OPEN += (double)table.cal_time(s1);
						cout << "chaning: " << setw(8) << (double)h.cal_time(s1) << " s" << "   open addressing: " << setw(8) << (double)table.cal_time(s1) << " s" << endl;
						Sleep(100);
					}
					cout << "Average time with chaining: " << (double)(ave_CHI / num) << " s"<< endl;
					cout << "Average time with open addressing: " << (double)(ave_OPEN / num) << " s" << endl;
					
					
					cout << endl;
				} break;
			default:
				{
					cout << "Command error! Please enter a right command!" << endl;
					command_tips();
				} break;
			}
		} else {
			cout << "Command error! Please enter a right command!" << endl;
			command_tips();
		}
	}
예제 #6
0
void HashTableTest::testInsert()
{
	std::string s1("str1");
	std::string s2("str2");
	HashTable<std::string, int> hashTable;
	assert (!hashTable.exists(s1));
	hashTable.insert(s1, 13);
	assert (hashTable.exists(s1));
	assert (hashTable.get(s1) == 13);
	int retVal = 0;

	assert (hashTable.get(s1, retVal));
	assert (retVal == 13);
	try
	{
		hashTable.insert(s1, 22);
		failmsg ("duplicate insert must fail");
	}
	catch (Exception&){}
	try
	{
		hashTable.get(s2);
		failmsg ("getting a non inserted item must fail");
	}
	catch (Exception&){}

	assert (!hashTable.exists(s2));
	hashTable.insert(s2, 13);
	assert (hashTable.exists(s2));
}
예제 #7
0
void
new_record(int cluster, int proc, int start_time, int evict_time, 
		   int good_time, int cpu_usage, char const *host)
{
	static bool initialized = false;
	char hash[40];
	int wall_time = evict_time-start_time;

	// We detect bad records here.  One cause of bad records is the
	// fact that userlogs timestamps do not contain years, so we
	// always assume we are in the same year, which causes time to run
	// backwards at the turn of the year.
	if (wall_time < 0 ||
		good_time < 0 ||
		cpu_usage < 0) {
		if (debug_mode) {
			fprintf(stderr, "internal error: negative time computed for "
					"%d.%d!\n", cluster, proc);
			fprintf(stderr, "  (records around the turn of "
					"the year are not handled correctly)\n");
		}
		return;
	}

	sprintf(hash, "%d.%d", cluster, proc);
	HashKey jobkey(hash);

	JobStatistics *js;
	if (Stats.lookup(jobkey, js) < 0) {
		js = new JobStatistics(cluster, proc);
		Stats.insert(jobkey, js);
		numJobStats++;
	}
	js->allocations++;
	js->kills += (wall_time != good_time);
	js->wall_time += wall_time;
	js->good_time += good_time;
	js->cpu_usage += cpu_usage;

	char ip_addr[128];
	// only use the IP address in the key [TODO:IPV6] Parse IPv6 Addr
	strncpy(ip_addr, host+1, sizeof(ip_addr)-1);
	ip_addr[sizeof(ip_addr)-1] = '\0';
	for (int i=0; i < 128; i++) {
		if (ip_addr[i] == ':') {
			ip_addr[i] = '\0';
			break;
		}
	}
	HostStatistics *hs;
	HashKey hostkey(ip_addr);
	if (HStats.lookup(hostkey, hs) < 0) {
		condor_sockaddr addr;
		const char* hostname = NULL;
		MyString hostname_str;
		addr.from_sinful(host);
		if (!avoid_dns) {
			hostname_str = get_hostname(addr);
			hostname = hostname_str.Value();
		}
		if (hostname == NULL) {
			hostname = ip_addr;
		}
		hs = new HostStatistics(hostname);
		HStats.insert(hostkey, hs);
		numHostStats++;
	}
	hs->allocations++;
	hs->kills += (wall_time != good_time);
	hs->wall_time += wall_time;
	hs->good_time += good_time;
	hs->cpu_usage += cpu_usage;

	if (!totals_only) {
		if (!raw_data && !initialized) {
			printf("\n");
			printf("%-8.8s %-15.15s %-11.11s %-11.11s %9s %9s %9s\n",
				   "Job", "Host", "Start Time", "Evict Time", "Wall Time",
				   "Good Time", "CPU Usage");
			initialized = true;
		}

		printf("%-8.8s %-15.15s ", hash, hs->host);
		printf("%11s ", format_date(start_time));
		printf("%11s ", format_date(evict_time));
		printf("%9s ", format_time_nosecs(wall_time));
		printf("%9s ", format_time_nosecs(good_time));
		printf("%9s\n", format_time_nosecs(cpu_usage));
	}
}
예제 #8
0
int Returns(xStationType statName,  LicenseType license, int mile, HashTable<LicenseType, BikePtr>&ht, Graph &stationMap) {
    
    BikePtr* bikeMetaPtr = ht.get(license);
    if( bikeMetaPtr ) {
        BikePtr bike = *bikeMetaPtr;
        //bike->Status=Free;

         vector<int> prev = stationMap.dijkstra(bike->Station);
         forward_list<int> shortest_path = stationMap.getPath(prev, statName);
         int dist=0;
         if( ! shortest_path.empty() ) {

             for(forward_list<int>::iterator it = shortest_path.begin(); it != shortest_path.end();) {
                 int from_tmp = *it;

                 forward_list<int>::iterator it_next = it;
                 it_next++;
                 if( it_next != shortest_path.end() ) {
                    int to_tmp = *(it_next);
                    dist += stationMap.distance(from_tmp, to_tmp);
                 }
                 it = it_next;
            }
         }

        int charge=0;
        int tmp=mile-bike->Mileage;

        if(tmp>dist){
            switch(bike->Class){
                case 0:
                    charge=tmp*40;
                    break;
                case 1:
                    charge=tmp*30;
                    break;
                case 2:
                    charge=tmp*20;
                    break;
                case 3:
                    charge=tmp*25;
                    break;
            }
        }
        else{
            switch(bike->Class){
                case 0:
                    charge=tmp*30;
                    break;
                case 1:
                    charge=tmp*25;
                    break;
                case 2:
                    charge=tmp*15;
                    break;
                case 3:
                    charge=tmp*20;
                    break;
            }
        }


        bike->Mileage=mile;
        int index = Station[bike->Station].HRent.find(bike, &licenseComp);
        Station[bike->Station].HRent.remove(index);
        Station[bike->Station].Nets[bike->Class] += charge;
        
        bike->Status = Free;
        Station[bike->Station].add(bike);
        
        cout<<"Rental charge for this bike is "<<charge<<"."<<endl;
    }
    return 0;
}
예제 #9
0
void setUpdater::updateSets(const mapPolyMesh& morphMap) const
{
    //
    // Update all sets in memory.
    //

    HashTable<const Type*> memSets = 
        morphMap.mesh().objectRegistry::lookupClass<Type>();

    for
    (
        typename HashTable<const Type*>::iterator iter = memSets.begin();
        iter != memSets.end();
        ++iter
    )
    {
        Type& set = const_cast<Type&>(*iter());

        if (debug)
        {
            Pout<< "Set:" << set.name() << " size:" << set.size()
                << " updated in memory" << endl;
        }

        set.updateMesh(morphMap);

        // Write or not? Debatable.
        set.write();
    }


    //
    // Update all sets on disk
    //

    // Get last valid mesh (discard points-only change)
    IOobjectList Objects
    (
        morphMap.mesh().time(),
        morphMap.mesh().time().findInstance
        (
            morphMap.mesh().meshDir(),
            "faces"
        ),
        "polyMesh/sets"
    );

    IOobjectList fileSets(Objects.lookupClass(Type::typeName));

    for
    (
        IOobjectList::const_iterator iter = fileSets.begin();
        iter != fileSets.end();
        ++iter
    )
    {
        if (!memSets.found(iter.key()))
        {
            // Not in memory. Load it.
            Type set(*iter());

            if (debug)
            {
                Pout<< "Set:" << set.name() << " size:" << set.size()
                    << " updated on disk" << endl;
            }

            set.updateMesh(morphMap);

            set.write();
        }
        else
        {
            if (debug)
            {
                Pout<< "Set:" << iter.key() << " already updated from memory"
                    << endl;
            }
        }
    }
}
예제 #10
0
void insertOnePoint(HashTable<Point, std::string>& htbl, const Point& p)
{
   std::stringstream stream;
   stream << "Point " << ": " << "(" << p.getX() << ";" << p.getY() << ")";
   htbl.insert(p, stream.str());
}
예제 #11
0
// Read boundary file without reading mesh
void rewriteBoundary
(
    const bool isTestRun,
    const IOobject& io,
    const fileName& regionPrefix,
    HashTable<word>& thisNames,
    HashTable<word>& nbrNames
)
{
    Info<< "Reading boundary from " << typeFilePath<IOPtrList<entry>>(io)
        << endl;

    // Read PtrList of dictionary.
    const word oldTypeName = IOPtrList<entry>::typeName;
    const_cast<word&>(IOPtrList<entry>::typeName) = word::null;
    IOPtrList<entry> patches(io);
    const_cast<word&>(IOPtrList<entry>::typeName) = oldTypeName;
    // Fake type back to what was in field
    const_cast<word&>(patches.type()) = patches.headerClassName();


    // Replace any 'cyclic'
    label nOldCyclics = 0;
    forAll(patches, patchi)
    {
        const dictionary& patchDict = patches[patchi].dict();

        if (word(patchDict["type"]) == cyclicPolyPatch::typeName)
        {
            if (!patchDict.found("neighbourPatch"))
            {
                Info<< "Patch " << patches[patchi].keyword()
                    << " does not have 'neighbourPatch' entry; assuming it"
                    << " is of the old type." << endl;
                nOldCyclics++;
            }
        }
    }

    Info<< "Detected " << nOldCyclics << " old cyclics." << nl << endl;


    // Save old patches.
    PtrList<entry> oldPatches(patches);

    // Extend
    label nOldPatches = patches.size();
    patches.setSize(nOldPatches+nOldCyclics);

    // Create reordering map
    labelList oldToNew(patches.size());


    // Add new entries
    label addedPatchi = nOldPatches;
    label newPatchi = 0;
    forAll(oldPatches, patchi)
    {
        const dictionary& patchDict = oldPatches[patchi].dict();

        if
        (
            word(patchDict["type"]) == cyclicPolyPatch::typeName
        )
        {
            const word& name = oldPatches[patchi].keyword();

            if (patchDict.found("neighbourPatch"))
            {
                patches.set(patchi, oldPatches.set(patchi, nullptr));
                oldToNew[patchi] = newPatchi++;

                // Check if patches come from automatic conversion
                word oldName;

                string::size_type i = name.rfind("_half0");
                if (i != string::npos)
                {
                    oldName = name.substr(0, i);
                    thisNames.insert(oldName, name);
                    Info<< "Detected converted cyclic patch " << name
                        << " ; assuming it originates from " << oldName
                        << endl;
                }
                else
                {
                    i = name.rfind("_half1");
                    if (i != string::npos)
                    {
                        oldName = name.substr(0, i);
                        nbrNames.insert(oldName, name);
                        Info<< "Detected converted cyclic patch " << name
                            << " ; assuming it originates from " << oldName
                            << endl;
                    }
                }
            }
            else
            {
                label nFaces = readLabel(patchDict["nFaces"]);
                label startFace = readLabel(patchDict["startFace"]);

                Info<< "Detected old style " << word(patchDict["type"])
                    << " patch " << name << " with" << nl
                    << "    nFaces    : " << nFaces << nl
                    << "    startFace : " << startFace << endl;

                word thisName = name + "_half0";
                word nbrName = name + "_half1";

                thisNames.insert(name, thisName);
                nbrNames.insert(name, nbrName);

                // Save current dictionary
                const dictionary patchDict(patches[patchi].dict());

                // Change entry on this side
                patches.set(patchi, oldPatches.set(patchi, nullptr));
                oldToNew[patchi] = newPatchi++;
                dictionary& thisPatchDict = patches[patchi].dict();
                thisPatchDict.add("neighbourPatch", nbrName);
                thisPatchDict.set("nFaces", nFaces/2);
                patches[patchi].keyword() = thisName;

                // Add entry on other side
                patches.set
                (
                    addedPatchi,
                    new dictionaryEntry
                    (
                        nbrName,
                        dictionary::null,
                        patchDict
                    )
                );
                oldToNew[addedPatchi] = newPatchi++;
                dictionary& nbrPatchDict = patches[addedPatchi].dict();
                nbrPatchDict.set("neighbourPatch", thisName);
                nbrPatchDict.set("nFaces", nFaces/2);
                nbrPatchDict.set("startFace", startFace+nFaces/2);
                patches[addedPatchi].keyword() = nbrName;

                Info<< "Replaced with patches" << nl
                    << patches[patchi].keyword() << " with" << nl
                    << "    nFaces    : "
                    << readLabel(thisPatchDict.lookup("nFaces"))
                    << nl
                    << "    startFace : "
                    << readLabel(thisPatchDict.lookup("startFace")) << nl
                    << patches[addedPatchi].keyword() << " with" << nl
                    << "    nFaces    : "
                    << readLabel(nbrPatchDict.lookup("nFaces"))
                    << nl
                    << "    startFace : "
                    << readLabel(nbrPatchDict.lookup("startFace"))
                    << nl << endl;

                addedPatchi++;
            }
        }
        else
        {
            patches.set(patchi, oldPatches.set(patchi, nullptr));
            oldToNew[patchi] = newPatchi++;
        }
    }

    patches.reorder(oldToNew);

    if (returnReduce(nOldCyclics, sumOp<label>()) > 0)
    {
        if (isTestRun)
        {
            // Info<< "-test option: no changes made" << nl << endl;
        }
        else
        {
            if (mvBak(patches.objectPath(), "old"))
            {
                Info<< "Backup to    "
                    << (patches.objectPath() + ".old") << nl;
            }

            Info<< "Write  to    "
                << patches.objectPath() << nl << endl;
            patches.write();
        }
    }
    else
    {
        Info<< "No changes made to boundary file." << nl << endl;
    }
}
예제 #12
0
Boolean MediaSubsession::initiate(int useSpecialRTPoffset) {
  if (fReadSource != NULL) return True; // has already been initiated

  do {
    if (fCodecName == NULL) {
      env().setResultMsg("Codec is unspecified");
      break;
    }

    // Create RTP and RTCP 'Groupsocks' on which to receive incoming data.
    // (Groupsocks will work even for unicast addresses)
    struct in_addr tempAddr;
    tempAddr.s_addr = connectionEndpointAddress();
        // This could get changed later, as a result of a RTSP "SETUP"

    if (fClientPortNum != 0) {
      // The sockets' port numbers were specified for us.  Use these:
      Boolean const protocolIsRTP = strcmp(fProtocolName, "RTP") == 0;
      if (protocolIsRTP) {
	fClientPortNum = fClientPortNum&~1; // use an even-numbered port for RTP, and the next (odd-numbered) port for RTCP
      }
      if (isSSM()) {
	fRTPSocket = new Groupsock(env(), tempAddr, fSourceFilterAddr, fClientPortNum);
      } else {
	fRTPSocket = new Groupsock(env(), tempAddr, fClientPortNum, 255);
      }
      if (fRTPSocket == NULL) {
	env().setResultMsg("Failed to create RTP socket");
	break;
      }
      
      if (protocolIsRTP) {
	// Set our RTCP port to be the RTP port +1
	portNumBits const rtcpPortNum = fClientPortNum|1;
	if (isSSM()) {
	  fRTCPSocket = new Groupsock(env(), tempAddr, fSourceFilterAddr, rtcpPortNum);
	} else {
	  fRTCPSocket = new Groupsock(env(), tempAddr, rtcpPortNum, 255);
	}
      }
    } else {
      // Port numbers were not specified in advance, so we use ephemeral port numbers.
      // Create sockets until we get a port-number pair (even: RTP; even+1: RTCP).
      // We need to make sure that we don't keep trying to use the same bad port numbers over and over again.
      // so we store bad sockets in a table, and delete them all when we're done.
      HashTable* socketHashTable = HashTable::create(ONE_WORD_HASH_KEYS);
      if (socketHashTable == NULL) break;
      Boolean success = False;
      NoReuse dummy(env()); // ensures that our new ephemeral port number won't be one that's already in use

      while (1) {
	// Create a new socket:
	if (isSSM()) {
	  fRTPSocket = new Groupsock(env(), tempAddr, fSourceFilterAddr, 0);
	} else {
	  fRTPSocket = new Groupsock(env(), tempAddr, 0, 255);
	}
	if (fRTPSocket == NULL) {
	  env().setResultMsg("MediaSession::initiate(): unable to create RTP and RTCP sockets");
	  break;
	}

	// Get the client port number, and check whether it's even (for RTP):
	Port clientPort(0);
	if (!getSourcePort(env(), fRTPSocket->socketNum(), clientPort)) {
	  break;
	}
	fClientPortNum = ntohs(clientPort.num()); 
	if ((fClientPortNum&1) != 0) { // it's odd
	  // Record this socket in our table, and keep trying:
	  unsigned key = (unsigned)fClientPortNum;
	  Groupsock* existing = (Groupsock*)socketHashTable->Add((char const*)key, fRTPSocket);
	  delete existing; // in case it wasn't NULL
	  continue;
	}

	// Make sure we can use the next (i.e., odd) port number, for RTCP:
	portNumBits rtcpPortNum = fClientPortNum|1;
	if (isSSM()) {
	  fRTCPSocket = new Groupsock(env(), tempAddr, fSourceFilterAddr, rtcpPortNum);
	} else {
	  fRTCPSocket = new Groupsock(env(), tempAddr, rtcpPortNum, 255);
	}
	if (fRTCPSocket != NULL && fRTCPSocket->socketNum() >= 0) {
	  // Success! Use these two sockets.
	  success = True;
	  break;
	} else {
	  // We couldn't create the RTCP socket (perhaps that port number's already in use elsewhere?).
	  delete fRTCPSocket;

	  // Record the first socket in our table, and keep trying:
	  unsigned key = (unsigned)fClientPortNum;
	  Groupsock* existing = (Groupsock*)socketHashTable->Add((char const*)key, fRTPSocket);
	  delete existing; // in case it wasn't NULL
	  continue;
	}
      }

      // Clean up the socket hash table (and contents):
      Groupsock* oldGS;
      while ((oldGS = (Groupsock*)socketHashTable->RemoveNext()) != NULL) {
	delete oldGS;
      }
      delete socketHashTable;

      if (!success) break; // a fatal error occurred trying to create the RTP and RTCP sockets; we can't continue
    }

    // Try to use a big receive buffer for RTP - at least 0.1 second of
    // specified bandwidth and at least 50 KB
    unsigned rtpBufSize = fBandwidth * 25 / 2; // 1 kbps * 0.1 s = 12.5 bytes
    if (rtpBufSize < 50 * 1024)
      rtpBufSize = 50 * 1024;
    increaseReceiveBufferTo(env(), fRTPSocket->socketNum(), rtpBufSize);

    if (isSSM() && fRTCPSocket != NULL) {
      // Special case for RTCP SSM: Send RTCP packets back to the source via unicast:
      fRTCPSocket->changeDestinationParameters(fSourceFilterAddr,0,~0);
    }

    // Create "fRTPSource" and "fReadSource":
    if (!createSourceObjects(useSpecialRTPoffset)) break;

    if (fReadSource == NULL) {
      env().setResultMsg("Failed to create read source");
      break;
    }

    // Finally, create our RTCP instance. (It starts running automatically)
    if (fRTPSource != NULL && fRTCPSocket != NULL) {
      // If bandwidth is specified, use it and add 5% for RTCP overhead.
      // Otherwise make a guess at 500 kbps.
      unsigned totSessionBandwidth
	= fBandwidth ? fBandwidth + fBandwidth / 20 : 500;
      fRTCPInstance = RTCPInstance::createNew(env(), fRTCPSocket,
					      totSessionBandwidth,
					      (unsigned char const*)
					      fParent.CNAME(),
					      NULL /* we're a client */,
					      fRTPSource);
      if (fRTCPInstance == NULL) {
	env().setResultMsg("Failed to create RTCP instance");
	break;
      }
    }

    return True;
  } while (0);

  delete fRTPSocket; fRTPSocket = NULL;
  delete fRTCPSocket; fRTCPSocket = NULL;
  Medium::close(fRTCPInstance); fRTCPInstance = NULL;
  Medium::close(fReadSource); fReadSource = fRTPSource = NULL;
  fClientPortNum = 0;
  return False;
}
예제 #13
0
namespace JSC {

extern const HashTable arrayConstructorTable;
extern const HashTable arrayPrototypeTable;
extern const HashTable booleanPrototypeTable;
extern const HashTable jsonTable;
extern const HashTable dateTable;
extern const HashTable dateConstructorTable;
extern const HashTable errorPrototypeTable;
extern const HashTable globalObjectTable;
extern const HashTable mathTable;
extern const HashTable numberConstructorTable;
extern const HashTable numberPrototypeTable;
JS_EXPORTDATA extern const HashTable objectConstructorTable;
extern const HashTable objectPrototypeTable;
extern const HashTable privateNamePrototypeTable;
extern const HashTable regExpTable;
extern const HashTable regExpConstructorTable;
extern const HashTable regExpPrototypeTable;
extern const HashTable stringTable;
extern const HashTable stringConstructorTable;

#if ENABLE(ASSEMBLER) && (ENABLE(CLASSIC_INTERPRETER) || ENABLE(LLINT))
static bool enableAssembler(ExecutableAllocator& executableAllocator)
{
    if (!executableAllocator.isValid() || !Options::useJIT())
        return false;

#if USE(CF)
    RetainPtr<CFStringRef> canUseJITKey(AdoptCF, CFStringCreateWithCString(0 , "JavaScriptCoreUseJIT", kCFStringEncodingMacRoman));
    RetainPtr<CFBooleanRef> canUseJIT(AdoptCF, (CFBooleanRef)CFPreferencesCopyAppValue(canUseJITKey.get(), kCFPreferencesCurrentApplication));
    if (canUseJIT)
        return kCFBooleanTrue == canUseJIT.get();
#endif

#if USE(CF) || OS(UNIX)
    char* canUseJITString = getenv("JavaScriptCoreUseJIT");
    return !canUseJITString || atoi(canUseJITString);
#else
    return true;
#endif
}
#endif

JSGlobalData::JSGlobalData(GlobalDataType globalDataType, ThreadStackType threadStackType, HeapType heapType)
    : heap(this, heapType)
    , globalDataType(globalDataType)
    , clientData(0)
    , topCallFrame(CallFrame::noCaller())
    , arrayConstructorTable(fastNew<HashTable>(JSC::arrayConstructorTable))
    , arrayPrototypeTable(fastNew<HashTable>(JSC::arrayPrototypeTable))
    , booleanPrototypeTable(fastNew<HashTable>(JSC::booleanPrototypeTable))
    , dateTable(fastNew<HashTable>(JSC::dateTable))
    , dateConstructorTable(fastNew<HashTable>(JSC::dateConstructorTable))
    , errorPrototypeTable(fastNew<HashTable>(JSC::errorPrototypeTable))
    , globalObjectTable(fastNew<HashTable>(JSC::globalObjectTable))
    , jsonTable(fastNew<HashTable>(JSC::jsonTable))
    , mathTable(fastNew<HashTable>(JSC::mathTable))
    , numberConstructorTable(fastNew<HashTable>(JSC::numberConstructorTable))
    , numberPrototypeTable(fastNew<HashTable>(JSC::numberPrototypeTable))
    , objectConstructorTable(fastNew<HashTable>(JSC::objectConstructorTable))
    , objectPrototypeTable(fastNew<HashTable>(JSC::objectPrototypeTable))
    , privateNamePrototypeTable(fastNew<HashTable>(JSC::privateNamePrototypeTable))
    , regExpTable(fastNew<HashTable>(JSC::regExpTable))
    , regExpConstructorTable(fastNew<HashTable>(JSC::regExpConstructorTable))
    , regExpPrototypeTable(fastNew<HashTable>(JSC::regExpPrototypeTable))
    , stringTable(fastNew<HashTable>(JSC::stringTable))
    , stringConstructorTable(fastNew<HashTable>(JSC::stringConstructorTable))
    , identifierTable(globalDataType == Default ? wtfThreadData().currentIdentifierTable() : createIdentifierTable())
    , propertyNames(new CommonIdentifiers(this))
    , emptyList(new MarkedArgumentBuffer)
#if ENABLE(ASSEMBLER)
    , executableAllocator(*this)
#endif
    , parserArena(adoptPtr(new ParserArena))
    , keywords(adoptPtr(new Keywords(this)))
    , interpreter(0)
    , jsArrayClassInfo(&JSArray::s_info)
    , jsFinalObjectClassInfo(&JSFinalObject::s_info)
#if ENABLE(DFG_JIT)
    , sizeOfLastScratchBuffer(0)
#endif
    , dynamicGlobalObject(0)
    , cachedUTCOffset(std::numeric_limits<double>::quiet_NaN())
    , maxReentryDepth(threadStackType == ThreadStackTypeSmall ? MaxSmallThreadReentryDepth : MaxLargeThreadReentryDepth)
    , m_enabledProfiler(0)
    , m_regExpCache(new RegExpCache(this))
#if ENABLE(REGEXP_TRACING)
    , m_rtTraceList(new RTTraceList())
#endif
#ifndef NDEBUG
    , exclusiveThread(0)
#endif
#if CPU(X86) && ENABLE(JIT)
    , m_timeoutCount(512)
#endif
    , m_newStringsSinceLastHashConst(0)
#if ENABLE(ASSEMBLER) && (ENABLE(CLASSIC_INTERPRETER) || ENABLE(LLINT))
    , m_canUseAssembler(enableAssembler(executableAllocator))
#endif
#if ENABLE(GC_VALIDATION)
    , m_initializingObjectClass(0)
#endif
    , m_inDefineOwnProperty(false)
{
    interpreter = new Interpreter;

    // Need to be careful to keep everything consistent here
    JSLockHolder lock(this);
    IdentifierTable* existingEntryIdentifierTable = wtfThreadData().setCurrentIdentifierTable(identifierTable);
    structureStructure.set(*this, Structure::createStructure(*this));
    debuggerActivationStructure.set(*this, DebuggerActivation::createStructure(*this, 0, jsNull()));
    activationStructure.set(*this, JSActivation::createStructure(*this, 0, jsNull()));
    interruptedExecutionErrorStructure.set(*this, InterruptedExecutionError::createStructure(*this, 0, jsNull()));
    terminatedExecutionErrorStructure.set(*this, TerminatedExecutionError::createStructure(*this, 0, jsNull()));
    staticScopeStructure.set(*this, JSStaticScopeObject::createStructure(*this, 0, jsNull()));
    strictEvalActivationStructure.set(*this, StrictEvalActivation::createStructure(*this, 0, jsNull()));
    stringStructure.set(*this, JSString::createStructure(*this, 0, jsNull()));
    notAnObjectStructure.set(*this, JSNotAnObject::createStructure(*this, 0, jsNull()));
    propertyNameIteratorStructure.set(*this, JSPropertyNameIterator::createStructure(*this, 0, jsNull()));
    getterSetterStructure.set(*this, GetterSetter::createStructure(*this, 0, jsNull()));
    apiWrapperStructure.set(*this, JSAPIValueWrapper::createStructure(*this, 0, jsNull()));
    scopeChainNodeStructure.set(*this, ScopeChainNode::createStructure(*this, 0, jsNull()));
    executableStructure.set(*this, ExecutableBase::createStructure(*this, 0, jsNull()));
    nativeExecutableStructure.set(*this, NativeExecutable::createStructure(*this, 0, jsNull()));
    evalExecutableStructure.set(*this, EvalExecutable::createStructure(*this, 0, jsNull()));
    programExecutableStructure.set(*this, ProgramExecutable::createStructure(*this, 0, jsNull()));
    functionExecutableStructure.set(*this, FunctionExecutable::createStructure(*this, 0, jsNull()));
    regExpStructure.set(*this, RegExp::createStructure(*this, 0, jsNull()));
    structureChainStructure.set(*this, StructureChain::createStructure(*this, 0, jsNull()));

    wtfThreadData().setCurrentIdentifierTable(existingEntryIdentifierTable);

#if ENABLE(JIT)
    jitStubs = adoptPtr(new JITThunks(this));
#endif
    
    interpreter->initialize(&llintData, this->canUseJIT());
    
    initializeHostCallReturnValue(); // This is needed to convince the linker not to drop host call return support.

    heap.notifyIsSafeToCollect();
    
    llintData.performAssertions(*this);
}

JSGlobalData::~JSGlobalData()
{
    ASSERT(!m_apiLock.currentThreadIsHoldingLock());
    heap.activityCallback()->didStartVMShutdown();
    heap.sweeper()->didStartVMShutdown();
    heap.lastChanceToFinalize();

    delete interpreter;
#ifndef NDEBUG
    interpreter = reinterpret_cast<Interpreter*>(0xbbadbeef);
#endif

    arrayPrototypeTable->deleteTable();
    arrayConstructorTable->deleteTable();
    booleanPrototypeTable->deleteTable();
    dateTable->deleteTable();
    dateConstructorTable->deleteTable();
    errorPrototypeTable->deleteTable();
    globalObjectTable->deleteTable();
    jsonTable->deleteTable();
    mathTable->deleteTable();
    numberConstructorTable->deleteTable();
    numberPrototypeTable->deleteTable();
    objectConstructorTable->deleteTable();
    objectPrototypeTable->deleteTable();
    privateNamePrototypeTable->deleteTable();
    regExpTable->deleteTable();
    regExpConstructorTable->deleteTable();
    regExpPrototypeTable->deleteTable();
    stringTable->deleteTable();
    stringConstructorTable->deleteTable();

    fastDelete(const_cast<HashTable*>(arrayConstructorTable));
    fastDelete(const_cast<HashTable*>(arrayPrototypeTable));
    fastDelete(const_cast<HashTable*>(booleanPrototypeTable));
    fastDelete(const_cast<HashTable*>(dateTable));
    fastDelete(const_cast<HashTable*>(dateConstructorTable));
    fastDelete(const_cast<HashTable*>(errorPrototypeTable));
    fastDelete(const_cast<HashTable*>(globalObjectTable));
    fastDelete(const_cast<HashTable*>(jsonTable));
    fastDelete(const_cast<HashTable*>(mathTable));
    fastDelete(const_cast<HashTable*>(numberConstructorTable));
    fastDelete(const_cast<HashTable*>(numberPrototypeTable));
    fastDelete(const_cast<HashTable*>(objectConstructorTable));
    fastDelete(const_cast<HashTable*>(objectPrototypeTable));
    fastDelete(const_cast<HashTable*>(privateNamePrototypeTable));
    fastDelete(const_cast<HashTable*>(regExpTable));
    fastDelete(const_cast<HashTable*>(regExpConstructorTable));
    fastDelete(const_cast<HashTable*>(regExpPrototypeTable));
    fastDelete(const_cast<HashTable*>(stringTable));
    fastDelete(const_cast<HashTable*>(stringConstructorTable));

    opaqueJSClassData.clear();

    delete emptyList;

    delete propertyNames;
    if (globalDataType != Default)
        deleteIdentifierTable(identifierTable);

    delete clientData;
    delete m_regExpCache;
#if ENABLE(REGEXP_TRACING)
    delete m_rtTraceList;
#endif

#if ENABLE(DFG_JIT)
    for (unsigned i = 0; i < scratchBuffers.size(); ++i)
        fastFree(scratchBuffers[i]);
#endif
}

PassRefPtr<JSGlobalData> JSGlobalData::createContextGroup(ThreadStackType type, HeapType heapType)
{
    return adoptRef(new JSGlobalData(APIContextGroup, type, heapType));
}

PassRefPtr<JSGlobalData> JSGlobalData::create(ThreadStackType type, HeapType heapType)
{
    return adoptRef(new JSGlobalData(Default, type, heapType));
}

PassRefPtr<JSGlobalData> JSGlobalData::createLeaked(ThreadStackType type, HeapType heapType)
{
    return create(type, heapType);
}

bool JSGlobalData::sharedInstanceExists()
{
    return sharedInstanceInternal();
}

JSGlobalData& JSGlobalData::sharedInstance()
{
    GlobalJSLock globalLock;
    JSGlobalData*& instance = sharedInstanceInternal();
    if (!instance) {
        instance = adoptRef(new JSGlobalData(APIShared, ThreadStackTypeSmall, SmallHeap)).leakRef();
        instance->makeUsableFromMultipleThreads();
    }
    return *instance;
}

JSGlobalData*& JSGlobalData::sharedInstanceInternal()
{
    static JSGlobalData* sharedInstance;
    return sharedInstance;
}

#if ENABLE(JIT)
static ThunkGenerator thunkGeneratorForIntrinsic(Intrinsic intrinsic)
{
    switch (intrinsic) {
    case CharCodeAtIntrinsic:
        return charCodeAtThunkGenerator;
    case CharAtIntrinsic:
        return charAtThunkGenerator;
    case FromCharCodeIntrinsic:
        return fromCharCodeThunkGenerator;
    case SqrtIntrinsic:
        return sqrtThunkGenerator;
    case PowIntrinsic:
        return powThunkGenerator;
    case AbsIntrinsic:
        return absThunkGenerator;
    case FloorIntrinsic:
        return floorThunkGenerator;
    case CeilIntrinsic:
        return ceilThunkGenerator;
    case RoundIntrinsic:
        return roundThunkGenerator;
    case ExpIntrinsic:
        return expThunkGenerator;
    case LogIntrinsic:
        return logThunkGenerator;
    default:
        return 0;
    }
}

NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function, NativeFunction constructor)
{
#if ENABLE(CLASSIC_INTERPRETER)
    if (!canUseJIT())
        return NativeExecutable::create(*this, function, constructor);
#endif
    return jitStubs->hostFunctionStub(this, function, constructor);
}
NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function, Intrinsic intrinsic)
{
    ASSERT(canUseJIT());
    return jitStubs->hostFunctionStub(this, function, intrinsic != NoIntrinsic ? thunkGeneratorForIntrinsic(intrinsic) : 0, intrinsic);
}
#else
NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function, NativeFunction constructor)
{
    return NativeExecutable::create(*this, function, constructor);
}
#endif

JSGlobalData::ClientData::~ClientData()
{
}

void JSGlobalData::resetDateCache()
{
    cachedUTCOffset = std::numeric_limits<double>::quiet_NaN();
    dstOffsetCache.reset();
    cachedDateString = UString();
    cachedDateStringValue = std::numeric_limits<double>::quiet_NaN();
    dateInstanceCache.reset();
}

void JSGlobalData::startSampling()
{
    interpreter->startSampling();
}

void JSGlobalData::stopSampling()
{
    interpreter->stopSampling();
}

void JSGlobalData::dumpSampleData(ExecState* exec)
{
    interpreter->dumpSampleData(exec);
#if ENABLE(ASSEMBLER)
    ExecutableAllocator::dumpProfile();
#endif
}

struct StackPreservingRecompiler : public MarkedBlock::VoidFunctor {
    HashSet<FunctionExecutable*> currentlyExecutingFunctions;
    void operator()(JSCell* cell)
    {
        if (!cell->inherits(&FunctionExecutable::s_info))
            return;
        FunctionExecutable* executable = jsCast<FunctionExecutable*>(cell);
        if (currentlyExecutingFunctions.contains(executable))
            return;
        executable->clearCodeIfNotCompiling();
    }
};

void JSGlobalData::releaseExecutableMemory()
{
    if (dynamicGlobalObject) {
        StackPreservingRecompiler recompiler;
        HashSet<JSCell*> roots;
        heap.getConservativeRegisterRoots(roots);
        HashSet<JSCell*>::iterator end = roots.end();
        for (HashSet<JSCell*>::iterator ptr = roots.begin(); ptr != end; ++ptr) {
            ScriptExecutable* executable = 0;
            JSCell* cell = *ptr;
            if (cell->inherits(&ScriptExecutable::s_info))
                executable = static_cast<ScriptExecutable*>(*ptr);
            else if (cell->inherits(&JSFunction::s_info)) {
                JSFunction* function = jsCast<JSFunction*>(*ptr);
                if (function->isHostFunction())
                    continue;
                executable = function->jsExecutable();
            } else
                continue;
            ASSERT(executable->inherits(&ScriptExecutable::s_info));
            executable->unlinkCalls();
            if (executable->inherits(&FunctionExecutable::s_info))
                recompiler.currentlyExecutingFunctions.add(static_cast<FunctionExecutable*>(executable));
                
        }
        heap.objectSpace().forEachCell<StackPreservingRecompiler>(recompiler);
    }
    m_regExpCache->invalidateCode();
    heap.collectAllGarbage();
}
    
void releaseExecutableMemory(JSGlobalData& globalData)
{
    globalData.releaseExecutableMemory();
}

#if ENABLE(DFG_JIT)
void JSGlobalData::gatherConservativeRoots(ConservativeRoots& conservativeRoots)
{
    for (size_t i = 0; i < scratchBuffers.size(); i++) {
        ScratchBuffer* scratchBuffer = scratchBuffers[i];
        if (scratchBuffer->activeLength()) {
            void* bufferStart = scratchBuffer->dataBuffer();
            conservativeRoots.add(bufferStart, static_cast<void*>(static_cast<char*>(bufferStart) + scratchBuffer->activeLength()));
        }
    }
}
#endif

#if ENABLE(REGEXP_TRACING)
void JSGlobalData::addRegExpToTrace(RegExp* regExp)
{
    m_rtTraceList->add(regExp);
}

void JSGlobalData::dumpRegExpTrace()
{
    // The first RegExp object is ignored.  It is create by the RegExpPrototype ctor and not used.
    RTTraceList::iterator iter = ++m_rtTraceList->begin();
    
    if (iter != m_rtTraceList->end()) {
        dataLog("\nRegExp Tracing\n");
        dataLog("                                                            match()    matches\n");
        dataLog("Regular Expression                          JIT Address      calls      found\n");
        dataLog("----------------------------------------+----------------+----------+----------\n");
    
        unsigned reCount = 0;
    
        for (; iter != m_rtTraceList->end(); ++iter, ++reCount)
            (*iter)->printTraceData();

        dataLog("%d Regular Expressions\n", reCount);
    }
    
    m_rtTraceList->clear();
}
#else
void JSGlobalData::dumpRegExpTrace()
{
}
#endif

} // namespace JSC
예제 #14
0
JSGlobalData::~JSGlobalData()
{
    ASSERT(!m_apiLock.currentThreadIsHoldingLock());
    heap.activityCallback()->didStartVMShutdown();
    heap.sweeper()->didStartVMShutdown();
    heap.lastChanceToFinalize();

    delete interpreter;
#ifndef NDEBUG
    interpreter = reinterpret_cast<Interpreter*>(0xbbadbeef);
#endif

    arrayPrototypeTable->deleteTable();
    arrayConstructorTable->deleteTable();
    booleanPrototypeTable->deleteTable();
    dateTable->deleteTable();
    dateConstructorTable->deleteTable();
    errorPrototypeTable->deleteTable();
    globalObjectTable->deleteTable();
    jsonTable->deleteTable();
    mathTable->deleteTable();
    numberConstructorTable->deleteTable();
    numberPrototypeTable->deleteTable();
    objectConstructorTable->deleteTable();
    objectPrototypeTable->deleteTable();
    privateNamePrototypeTable->deleteTable();
    regExpTable->deleteTable();
    regExpConstructorTable->deleteTable();
    regExpPrototypeTable->deleteTable();
    stringTable->deleteTable();
    stringConstructorTable->deleteTable();

    fastDelete(const_cast<HashTable*>(arrayConstructorTable));
    fastDelete(const_cast<HashTable*>(arrayPrototypeTable));
    fastDelete(const_cast<HashTable*>(booleanPrototypeTable));
    fastDelete(const_cast<HashTable*>(dateTable));
    fastDelete(const_cast<HashTable*>(dateConstructorTable));
    fastDelete(const_cast<HashTable*>(errorPrototypeTable));
    fastDelete(const_cast<HashTable*>(globalObjectTable));
    fastDelete(const_cast<HashTable*>(jsonTable));
    fastDelete(const_cast<HashTable*>(mathTable));
    fastDelete(const_cast<HashTable*>(numberConstructorTable));
    fastDelete(const_cast<HashTable*>(numberPrototypeTable));
    fastDelete(const_cast<HashTable*>(objectConstructorTable));
    fastDelete(const_cast<HashTable*>(objectPrototypeTable));
    fastDelete(const_cast<HashTable*>(privateNamePrototypeTable));
    fastDelete(const_cast<HashTable*>(regExpTable));
    fastDelete(const_cast<HashTable*>(regExpConstructorTable));
    fastDelete(const_cast<HashTable*>(regExpPrototypeTable));
    fastDelete(const_cast<HashTable*>(stringTable));
    fastDelete(const_cast<HashTable*>(stringConstructorTable));

    opaqueJSClassData.clear();

    delete emptyList;

    delete propertyNames;
    if (globalDataType != Default)
        deleteIdentifierTable(identifierTable);

    delete clientData;
    delete m_regExpCache;
#if ENABLE(REGEXP_TRACING)
    delete m_rtTraceList;
#endif

#if ENABLE(DFG_JIT)
    for (unsigned i = 0; i < scratchBuffers.size(); ++i)
        fastFree(scratchBuffers[i]);
#endif
}
예제 #15
0
void EQName::set(const QName& q, const HashTable& dict)
{
    prefix = dict.getKey(q.getPrefix());
    uri = dict.getKey(q.getUri());
    local = dict.getKey(q.getLocal());
}
예제 #16
0
// . returns 0.0 to 1.0
// . what percent of the alnum words in "w1" are in "w2" from words in [t0,t1)
// . gets 50% points if has all single words, and the other 50% if all phrases
// . Scores class applies to w1 only, use NULL if none
// . use word popularity information for scoring rarer term matches more
// . ONLY CHECKS FIRST 1000 WORDS of w2 for speed
float Title::getSimilarity ( Words  *w1 , int32_t i0 , int32_t i1 ,
			     Words  *w2 , int32_t t0 , int32_t t1 ) {
	// if either empty, that's 0% contained
	if ( w1->getNumWords() <= 0 ) return 0;
	if ( w2->getNumWords() <= 0 ) return 0;
	if ( i0 >= i1 ) return 0;
	if ( t0 >= t1 ) return 0;

	// invalids vals
	if ( i0 < 0   ) return 0;
	if ( t0 < 0   ) return 0;

	// . for this to be useful we must use idf
	// . get the popularity of each word in w1
	// . w1 should only be a few words since it is a title candidate
	// . does not add pop for word #i if scores[i] <= 0
	// . take this out for now since i removed the unified dict,
	//   we could use this if we added popularity to g_wiktionary
	//   but it would have to be language dependent
	Pops pops1;
	Pops pops2;
	if ( ! pops1.set ( w1 , i0 , i1 ) ) return -1.0;
	if ( ! pops2.set ( w2 , t0 , t1 ) ) return -1.0;

	// now hash the words in w1, the needle in the haystack
	int32_t nw1 = w1->getNumWords();
	if ( i1 > nw1 ) i1 = nw1;
	HashTable table;

	// this augments the hash table
	int64_t lastWid   = -1;
	float     lastScore = 0.0;

	// but we cannot have more than 1024 slots then
	if ( ! table.set ( 1024 ) ) return -1.0;

	// and table auto grows when 90% full, so limit us here
	int32_t count    = 0;
	int32_t maxCount = 20;

	// sum up everything we add
	float sum = 0.0;

	// loop over all words in "w1" and hash them
	for ( int32_t i = i0 ; i < i1 ; i++ ) {
		// the word id
		int64_t wid = w1->getWordId(i);

		// skip if not indexable
		if ( wid == 0 ) {
			continue;
		}

		// no room left in table!
		if ( count++ > maxCount ) {
			//logf(LOG_DEBUG, "query: Hash table for title "
			//    "generation too small. Truncating words from w1.");
			break;
		}

		// . make this a float. it ranges from 0.0 to 1.0
		// . 1.0 means the word occurs in 100% of documents sampled
		// . 0.0 means it occurs in none of them
		// . but "val" is the complement of those two statements!
		float score = 1.0 - pops1.getNormalizedPop(i);

		// accumulate
		sum += score;

		// add to table
		if ( ! table.addKey ( (int32_t)wid , (int32_t)score , NULL ) ) {
			return -1.0;
		}

		// if no last wid, continue
		if ( lastWid == -1LL ) {
			lastWid = wid;
			lastScore = score;
			continue;
		}

		// . what was his val?
		// . the "val" of the phrase: 
		float phrScore = score + lastScore;

		// do not count as much as single words
		phrScore *= 0.5;

		// accumulate
		sum += phrScore;

		// get the phrase id
		int64_t pid = hash64 ( wid , lastWid );

		// now add that
		if ( ! table.addKey ( (int32_t)pid , (int32_t)phrScore , NULL ) )
			return -1.0;
		// we are now the last wid
		lastWid   = wid;
		lastScore = score;
	}

	// sanity check. it can't grow cuz we keep lastWids[] 1-1 with it
	if ( table.getNumSlots() != 1024 ) {
		log(LOG_LOGIC,"query: Title has logic bug.");
		return -1.0;
	}

	// accumulate scores of words that are found
	float found = 0.0;

	// reset
	lastWid = -1LL;

	// loop over all words in "w1" and hash them
	for ( int32_t i = t0 ; i < t1 ; i++ ) {
		// the word id
		int64_t wid = w2->getWordId(i);

		// skip if not indexable
		if ( wid == 0 ) {
			continue;
		}

		// . make this a float. it ranges from 0.0 to 1.0
		// . 1.0 means the word occurs in 100% of documents sampled
		// . 0.0 means it occurs in none of them
		// . but "val" is the complement of those two statements!
		float score = 1.0 - pops2.getNormalizedPop(i);

		// accumulate
		sum += score;

		// is it in table? 
		int32_t slot = table.getSlot ( (int32_t)wid ) ;

		// . if in table, add that up to "found"
		// . we essentially find his wid AND our wid, so 2.0 times
		if ( slot >= 0 ) {
			found += 2.0 * score;
		}

		// now the phrase
		if ( lastWid == -1LL ) {
			lastWid = wid;
			lastScore = score;
			continue;
		}

		// . what was his val?
		// . the "val" of the phrase: 
		float phrScore = score + lastScore;

		// do not count as much as single words
		phrScore *= 0.5;

		// accumulate
		sum += phrScore;

		// get the phrase id
		int64_t pid = hash64 ( wid , lastWid );

		// is it in table? 
		slot = table.getSlot ( (int32_t)pid ) ;

		// . accumulate if in there
		// . we essentially find his wid AND our wid, so 2.0 times
		if ( slot >= 0 ) found += 2.0 * phrScore;

		// we are now the last wid
		lastWid   = wid;
		lastScore = score;
	}

	// do not divide by zero
	if ( sum == 0.0 ) return 0.0;
	// sanity check
	//if ( found > sum              ) { char *xx=NULL;*xx=0; }
	if ( found < 0.0 || sum < 0.0 ) { char *xx=NULL;*xx=0; }
	// . return the percentage matched
	// . will range from 0.0 to 1.0
	return found / sum;
}
예제 #17
0
Boolean MediaSubsession::initiate(int useSpecialRTPoffset) {
  if (fReadSource != NULL) return True; // has already been initiated

  do {
    if (fCodecName == NULL) {
      env().setResultMsg("Codec is unspecified");
      break;
    }

    // Create RTP and RTCP 'Groupsocks' on which to receive incoming data.
    // (Groupsocks will work even for unicast addresses)
    struct in_addr tempAddr;
    tempAddr.s_addr = connectionEndpointAddress();
        // This could get changed later, as a result of a RTSP "SETUP"

    if (fClientPortNum != 0) {
      // The sockets' port numbers were specified for us.  Use these:
      fClientPortNum = fClientPortNum&~1; // even
      if (isSSM()) {
	fRTPSocket = new Groupsock(env(), tempAddr, fSourceFilterAddr, fClientPortNum);
      } else {
	fRTPSocket = new Groupsock(env(), tempAddr, fClientPortNum, 255);
      }
      if (fRTPSocket == NULL) {
	env().setResultMsg("Failed to create RTP socket");
	break;
      }
      
      // Set our RTCP port to be the RTP port +1
      portNumBits const rtcpPortNum = fClientPortNum|1;
      if (isSSM()) {
	fRTCPSocket = new Groupsock(env(), tempAddr, fSourceFilterAddr, rtcpPortNum);
      } else {
	fRTCPSocket = new Groupsock(env(), tempAddr, rtcpPortNum, 255);
      }
      if (fRTCPSocket == NULL) {
	char tmpBuf[100];
	sprintf(tmpBuf, "Failed to create RTCP socket (port %d)", rtcpPortNum);
	env().setResultMsg(tmpBuf);
	break;
      }
    } else {
      // Port numbers were not specified in advance, so we use ephemeral port numbers.
      // Create sockets until we get a port-number pair (even: RTP; even+1: RTCP).
      // We need to make sure that we don't keep trying to use the same bad port numbers over and over again.
      // so we store bad sockets in a table, and delete them all when we're done.
      HashTable* socketHashTable = HashTable::create(ONE_WORD_HASH_KEYS);
      if (socketHashTable == NULL) break;
      Boolean success = False;

      while (1) {
	// Create a new socket:
	if (isSSM()) {
	  fRTPSocket = new Groupsock(env(), tempAddr, fSourceFilterAddr, 0);
	} else {
	  fRTPSocket = new Groupsock(env(), tempAddr, 0, 255);
	}
	if (fRTPSocket == NULL) {
	  env().setResultMsg("MediaSession::initiate(): unable to create RTP and RTCP sockets");
	  break;
	}

	// Get the client port number, and check whether it's even (for RTP):
	Port clientPort(0);
	if (!getSourcePort(env(), fRTPSocket->socketNum(), clientPort)) {
	  break;
	}
	fClientPortNum = ntohs(clientPort.num()); 
	if ((fClientPortNum&1) != 0) { // it's odd
	  // Record this socket in our table, and keep trying:
	  unsigned key = (unsigned)fClientPortNum;
	  socketHashTable->Add((char const*)key, fRTPSocket);
	  continue;
	}

	// Make sure we can use the next (i.e., odd) port number, for RTCP:
	portNumBits rtcpPortNum = fClientPortNum|1;
	if (isSSM()) {
	  fRTCPSocket = new Groupsock(env(), tempAddr, fSourceFilterAddr, rtcpPortNum);
	} else {
	  fRTCPSocket = new Groupsock(env(), tempAddr, rtcpPortNum, 255);
	}
	if (fRTCPSocket != NULL) {
	  // Success! Use these two sockets (and delete any others that we've created):
	  Groupsock* oldGS;
	  while ((oldGS = (Groupsock*)socketHashTable->RemoveNext()) != NULL) {
	    delete oldGS;
	  }
	  delete socketHashTable;
	  success = True;
	  break;
	} else {
	  // We couldn't create the RTCP socket (perhaps that port number's already in use elsewhere?).
	  // Record the first socket in our table, and keep trying:
	  unsigned key = (unsigned)fClientPortNum;
	  socketHashTable->Add((char const*)key, fRTPSocket);
	  continue;
	}
      }
      if (!success) break; // a fatal error occurred trying to create the RTP and RTCP sockets; we can't continue
    }

    // ASSERT: fRTPSocket != NULL && fRTCPSocket != NULL
    if (isSSM()) {
      // Special case for RTCP SSM: Send RTCP packets back to the source via unicast:
      fRTCPSocket->changeDestinationParameters(fSourceFilterAddr,0,~0);
    }

	//////////////////////////////////////////////////////////////////////////
	// 裁剪掉不需要的Source.

    // Check "fProtocolName"
    if (strcmp(fProtocolName, "UDP") == 0) {

#ifndef CUT_MIN_SIZE
      // A UDP-packetized stream (*not* a RTP stream)
      fReadSource = BasicUDPSource::createNew(env(), fRTPSocket);
      fRTPSource = NULL; // Note!

      if (strcmp(fCodecName, "MP2T") == 0) { // MPEG-2 Transport Stream
	fReadSource = MPEG2TransportStreamFramer::createNew(env(), fReadSource);
	    // this sets "durationInMicroseconds" correctly, based on the PCR values
      }
#endif

    } else {
      // Check "fCodecName" against the set of codecs that we support,
      // and create our RTP source accordingly
      // (Later make this code more efficient, as this set grows #####)
      // (Also, add more fmts that can be implemented by SimpleRTPSource#####)
      Boolean createSimpleRTPSource = False;
      Boolean doNormalMBitRule = False; // used if "createSimpleRTPSource"

	  if (strcmp(fCodecName, "H264") == 0) {
		  fReadSource = fRTPSource
			  = H264VideoRTPSource::createNew(env(), fRTPSocket,
			  fRTPPayloadFormat,
			  fRTPTimestampFrequency);
	  }  
	  else if (strcmp(fCodecName, "MP4V-ES") == 0) 
	  { // MPEG-4 Elem Str vid
		  fReadSource = fRTPSource
			  = MPEG4ESVideoRTPSource::createNew(env(), fRTPSocket,
			  fRTPPayloadFormat,
			  fRTPTimestampFrequency);
	  }
#ifndef CUT_MIN_SIZE	  
	  else if (strcmp(fCodecName, "QCELP") == 0) { // QCELP audio
	fReadSource =
	  QCELPAudioRTPSource::createNew(env(), fRTPSocket, fRTPSource,
					 fRTPPayloadFormat,
					 fRTPTimestampFrequency);
	// Note that fReadSource will differ from fRTPSource in this case
      } else if (strcmp(fCodecName, "AMR") == 0) { // AMR audio (narrowband)
	fReadSource =
	  AMRAudioRTPSource::createNew(env(), fRTPSocket, fRTPSource,
				       fRTPPayloadFormat, 0 /*isWideband*/,
				       fNumChannels, fOctetalign, fInterleaving,
				       fRobustsorting, fCRC);
	// Note that fReadSource will differ from fRTPSource in this case
      } else if (strcmp(fCodecName, "AMR-WB") == 0) { // AMR audio (wideband)
	fReadSource =
	  AMRAudioRTPSource::createNew(env(), fRTPSocket, fRTPSource,
				       fRTPPayloadFormat, 1 /*isWideband*/,
				       fNumChannels, fOctetalign, fInterleaving,
				       fRobustsorting, fCRC);
	// Note that fReadSource will differ from fRTPSource in this case
      } else if (strcmp(fCodecName, "MPA") == 0) { // MPEG-1 or 2 audio
	fReadSource = fRTPSource
	  = MPEG1or2AudioRTPSource::createNew(env(), fRTPSocket,
					      fRTPPayloadFormat,
					      fRTPTimestampFrequency);
      } else if (strcmp(fCodecName, "MPA-ROBUST") == 0) { // robust MP3 audio
	fRTPSource
	  = MP3ADURTPSource::createNew(env(), fRTPSocket, fRTPPayloadFormat,
				       fRTPTimestampFrequency);
	if (fRTPSource == NULL) break;

	// Add a filter that deinterleaves the ADUs after depacketizing them:
	MP3ADUdeinterleaver* deinterleaver
	  = MP3ADUdeinterleaver::createNew(env(), fRTPSource);
	if (deinterleaver == NULL) break;

	// Add another filter that converts these ADUs to MP3 frames:
	fReadSource = MP3FromADUSource::createNew(env(), deinterleaver);
      } else if (strcmp(fCodecName, "X-MP3-DRAFT-00") == 0) {
	// a non-standard variant of "MPA-ROBUST" used by RealNetworks
	// (one 'ADU'ized MP3 frame per packet; no headers)
	fRTPSource
	  = SimpleRTPSource::createNew(env(), fRTPSocket, fRTPPayloadFormat,
				       fRTPTimestampFrequency,
				       "audio/MPA-ROBUST" /*hack*/);
	if (fRTPSource == NULL) break;

	// Add a filter that converts these ADUs to MP3 frames:
	fReadSource = MP3FromADUSource::createNew(env(), fRTPSource,
						  False /*no ADU header*/);
      } else if (strcmp(fCodecName, "MP4A-LATM") == 0) { // MPEG-4 LATM audio
	fReadSource = fRTPSource
	  = MPEG4LATMAudioRTPSource::createNew(env(), fRTPSocket,
					       fRTPPayloadFormat,
					       fRTPTimestampFrequency);
      } else if (strcmp(fCodecName, "AC3") == 0) { // AC3 audio
	fReadSource = fRTPSource
	  = AC3AudioRTPSource::createNew(env(), fRTPSocket,
					 fRTPPayloadFormat,
					 fRTPTimestampFrequency);
      } else if (strcmp(fCodecName, "MPEG4-GENERIC") == 0) {
	fReadSource = fRTPSource
	  = MPEG4GenericRTPSource::createNew(env(), fRTPSocket,
					     fRTPPayloadFormat,
					     fRTPTimestampFrequency,
					     fMediumName, fMode,
					     fSizelength, fIndexlength,
					     fIndexdeltalength);
      } else if (strcmp(fCodecName, "MPV") == 0) { // MPEG-1 or 2 video
	fReadSource = fRTPSource
	  = MPEG1or2VideoRTPSource::createNew(env(), fRTPSocket,
					      fRTPPayloadFormat,
					      fRTPTimestampFrequency);
      } else if (strcmp(fCodecName, "MP2T") == 0) { // MPEG-2 Transport Stream
	fRTPSource = SimpleRTPSource::createNew(env(), fRTPSocket, fRTPPayloadFormat,
						fRTPTimestampFrequency, "video/MP2T",
						0, False);
	fReadSource = MPEG2TransportStreamFramer::createNew(env(), fRTPSource);
	    // this sets "durationInMicroseconds" correctly, based on the PCR values
      } else if (strcmp(fCodecName, "H261") == 0) { // H.261
	fReadSource = fRTPSource
	  = H261VideoRTPSource::createNew(env(), fRTPSocket,
					  fRTPPayloadFormat,
					  fRTPTimestampFrequency);
      } else if (strcmp(fCodecName, "H263-1998") == 0 ||
		 strcmp(fCodecName, "H263-2000") == 0) { // H.263+
	fReadSource = fRTPSource
	  = H263plusVideoRTPSource::createNew(env(), fRTPSocket,
					      fRTPPayloadFormat,
					      fRTPTimestampFrequency);
      } else if (strcmp(fCodecName, "JPEG") == 0) { // motion JPEG
	fReadSource = fRTPSource
	  = JPEGVideoRTPSource::createNew(env(), fRTPSocket,
					  fRTPPayloadFormat,
					  fRTPTimestampFrequency,
					  videoWidth(),
					  videoHeight());
      } else if (strcmp(fCodecName, "X-QT") == 0
		 || strcmp(fCodecName, "X-QUICKTIME") == 0) {
	// Generic QuickTime streams, as defined in
	// <http://developer.apple.com/quicktime/icefloe/dispatch026.html>
	char* mimeType
	  = new char[strlen(mediumName()) + strlen(codecName()) + 2] ;
	sprintf(mimeType, "%s/%s", mediumName(), codecName());
	fReadSource = fRTPSource
	  = QuickTimeGenericRTPSource::createNew(env(), fRTPSocket,
						 fRTPPayloadFormat,
						 fRTPTimestampFrequency,
						 mimeType);
	delete[] mimeType;
#ifdef SUPPORT_REAL_RTSP
      } else if (strcmp(fCodecName, "X-PN-REALAUDIO") == 0 ||
		 strcmp(fCodecName, "X-PN-MULTIRATE-REALAUDIO-LIVE") == 0 ||
		 strcmp(fCodecName, "X-PN-REALVIDEO") == 0 ||
		 strcmp(fCodecName, "X-PN-MULTIRATE-REALVIDEO-LIVE") == 0) {
	// A RealNetworks 'RDT' stream (*not* a RTP stream)
	fReadSource = RealRDTSource::createNew(env());
	fRTPSource = NULL; // Note!
	parentSession().isRealNetworksRDT = True;
#endif
      } 
#endif	// CUT_MIN_SIZE

	  else if (  strcmp(fCodecName, "PCMU") == 0 // PCM u-law audio
		   || strcmp(fCodecName, "GSM") == 0 // GSM audio
		   || strcmp(fCodecName, "PCMA") == 0 // PCM a-law audio
		   || strcmp(fCodecName, "L16") == 0 // 16-bit linear audio
		   || strcmp(fCodecName, "MP1S") == 0 // MPEG-1 System Stream
		   || strcmp(fCodecName, "MP2P") == 0 // MPEG-2 Program Stream
		   || strcmp(fCodecName, "L8") == 0 // 8-bit linear audio
		   || strcmp(fCodecName, "G726-16") == 0 // G.726, 16 kbps
		   || strcmp(fCodecName, "G726-24") == 0 // G.726, 24 kbps
		   || strcmp(fCodecName, "G726-32") == 0 // G.726, 32 kbps
		   || strcmp(fCodecName, "G726-40") == 0 // G.726, 40 kbps
		   || strcmp(fCodecName, "SPEEX") == 0 // SPEEX audio
		   ) {
	createSimpleRTPSource = True;
	useSpecialRTPoffset = 0;
      } else if (useSpecialRTPoffset >= 0) {
	// We don't know this RTP payload format, but try to receive
	// it using a 'SimpleRTPSource' with the specified header offset:
	createSimpleRTPSource = True;
      } else {
	env().setResultMsg("RTP payload format unknown or not supported");
	break;
      }

      if (createSimpleRTPSource) {
	char* mimeType
	  = new char[strlen(mediumName()) + strlen(codecName()) + 2] ;
	sprintf(mimeType, "%s/%s", mediumName(), codecName());
	fReadSource = fRTPSource
	  = SimpleRTPSource::createNew(env(), fRTPSocket, fRTPPayloadFormat,
				       fRTPTimestampFrequency, mimeType,
				       (unsigned)useSpecialRTPoffset,
				       doNormalMBitRule);
	delete[] mimeType;
      }
    }

    if (fReadSource == NULL) {
      env().setResultMsg("Failed to create read source");
      break;
    }

    // Finally, create our RTCP instance. (It starts running automatically)
    if (fRTPSource != NULL) {
      unsigned totSessionBandwidth = 500; // HACK - later get from SDP#####
      fRTCPInstance = RTCPInstance::createNew(env(), fRTCPSocket,
					      totSessionBandwidth,
					      (unsigned char const*)
					      fParent.CNAME(),
					      NULL /* we're a client */,
					      fRTPSource);
      if (fRTCPInstance == NULL) {
	env().setResultMsg("Failed to create RTCP instance");
	break;
      }
    }

    return True;
  } while (0);

  delete fRTPSocket; fRTPSocket = NULL;
  delete fRTCPSocket; fRTCPSocket = NULL;
  Medium::close(fRTCPInstance); fRTCPInstance = NULL;
  Medium::close(fReadSource); fReadSource = fRTPSource = NULL;
  fClientPortNum = 0;
  return False;
}
예제 #18
0
int mainFuntions(int hashFunc)
{
    HashTable h;
    h.hashInit();
    //h.insertOrderName("", -1);
    //h.insertOrderYear("", -1);



    string inName, inYear, dName, fName;
    int yearInt;
    int select = menuSelect();
    hashElem *foundNode = NULL;
    while (select != 8)
    {
        switch(select)
        {
        case 1:
            // choose hash function
            cout << "Enter title:" << endl;
            getline(cin, inName);
            cout << "Enter year:" << endl;
            getline(cin, inYear);
            yearInt = atoi(inYear.c_str());

            h.insertMovie(inName, yearInt, hashFunc);
            h.insertOrderYear(inName, yearInt);
            h.insertOrderName(inName, yearInt);
            break;

        case 2:
            cout << "Enter title:" << endl;
            getline(cin, dName);
            h.deleteMovie(dName, hashFunc);
            break;
        case 3:
            cout << "Enter title:" << endl;
            getline(cin, fName);
            foundNode = h.findMovie(fName, hashFunc);
            if (foundNode != NULL)
            {
                cout << foundNode -> title <<  ":" << foundNode -> year << endl;
            }else{
                cout << "not found" << endl;
            }
            break;
        case 4:
            h.printTableContents();
            break;
        case 5:
            h.printList();
            break;
        case 6:
            h.printListYear();
            break;
        case 7:
            h.colCount(hashFunc);
            break;
        }
        select = menuSelect();
    }
    cout << "Goodbye!" << endl;
    return 1;
}
예제 #19
0
void
display_stats()
{
	int i;

	// display HostStatistics
	printf("%-15.15s %9.9s %9.9s %9.9s %9.9s %9.9s %7.7s %6.6s\n",
		   "Host/Job", "Wall Time", "Good Time", "CPU Usage",
		   "Avg Alloc", "Avg Lost", "Goodput", "Util.");
	printf("\n");

	HostStatistics *hs;
	HStats.startIterations();
	while (HStats.iterate(hs) == 1) {
		printf("%-15.15s ", hs->host);
		printf("%9.9s ", format_time_nosecs(hs->wall_time));
		printf("%9.9s ", format_time_nosecs(hs->good_time));
		printf("%9.9s ", format_time_nosecs(hs->cpu_usage));
		printf("%9.9s ", format_time_nosecs(hs->wall_time/hs->allocations));
		printf("%9.9s ", hs->kills ?
			   format_time_nosecs((hs->wall_time-hs->good_time)/hs->kills) :
			   "0+00:00");
		printf("%6.1f%% %5.1f%%\n",
			   hs->wall_time ?
			   float(hs->good_time)/float(hs->wall_time)*100 : 0.0,
			   hs->good_time ?
			   float(hs->cpu_usage)/float(hs->good_time)*100 : 0.0);
		delete hs;
	}
	HStats.clear();
	printf("\n");

	// display JobStatistics
	JobStatistics **statarray = new JobStatistics* [numJobStats];
	JobStatistics *js;
	Stats.startIterations();
	for (i=0; Stats.iterate(js) == 1; i++) {
		statarray[i] = js;
	}

	qsort(statarray, numJobStats, sizeof(JobStatistics *), statsort);

	int allocations=0, kills=0;
	int wall_time=0, good_time=0, cpu_usage=0;
	char job[40];
	for (i=0; i < numJobStats; i++) {
		js = statarray[i];
		sprintf(job, "%d.%d", js->cluster, js->proc);
		printf("%-15.15s ", job);
		printf("%9.9s ", format_time_nosecs(js->wall_time));
		printf("%9.9s ", format_time_nosecs(js->good_time));
		printf("%9.9s ", format_time_nosecs(js->cpu_usage));
		printf("%9.9s ", format_time_nosecs(js->wall_time/js->allocations));
		printf("%9.9s ", js->kills ?
			   format_time_nosecs((js->wall_time-js->good_time)/js->kills) :
			   "0+00:00");
		printf("%6.1f%% %5.1f%%\n",
			   js->wall_time ?
			   float(js->good_time)/float(js->wall_time)*100 : 0.0,
			   js->good_time ?
			   float(js->cpu_usage)/float(js->good_time)*100 : 0.0);
		allocations += js->allocations;
		kills += js->kills;
		wall_time += js->wall_time;
		good_time += js->good_time;
		cpu_usage += js->cpu_usage;
		delete js;
	}
	printf("\n");
	printf("%-15.15s ", "Total");
	printf("%9.9s ", format_time_nosecs(wall_time));
	printf("%9.9s ", format_time_nosecs(good_time));
	printf("%9.9s ", format_time_nosecs(cpu_usage));
	printf("%9.9s ", allocations ?
		   format_time_nosecs(wall_time/allocations) :
		   "0+00:00");
	printf("%9.9s ", kills ?
		   format_time_nosecs((wall_time-good_time)/kills) :
		   "0+00:00");
	printf("%6.1f%% %5.1f%%\n",
		   wall_time ? float(good_time)/float(wall_time)*100 : 0.0,
		   good_time ? float(cpu_usage)/float(good_time)*100 : 0.0);
	Stats.clear();
	delete [] statarray;
}
예제 #20
0
int main( int argc, const char *argv[] )
{
    
    HashTable annaTable;
    // insert code here...
    
    int choice1;
    int choice2;
    string name;
    int id;
    
    while( 1 ) {
        cout << "\n----------------------" << endl;
        cout << "       The Hashers!" << endl;
        cout << "\n----------------------" << endl;
        cout << "1.Build the database!" << endl;
        cout << "2.Insert a new student" << endl;
        cout << "3.Display students" << endl;
        cout << "4.Search for a student" << endl;
        cout << "5.Exit" << endl;
        cout << "Enter your choice: " << endl;
        cin >> choice1;
        switch( choice1 )
        {
            case 1:
                cout << "\n----------------------" << endl;
                cout << "  The Hashers are building tables!" << endl;
                cout << "\n----------------------" << endl;
                cout << "1.Build using Direct Address" << endl;
                cout << "2.Build using Division" << endl;
                cout << "3.Build using Fibonacci" << endl;
                cout << "4.Build using Perfect" << endl;
                cout << "5.Build using Double Hashing" << endl;
                cout << "6.Build using Universal" << endl;
                cout << "7.Return " << endl;
                cout << "Enter your choice: " << endl;
                cin >> choice2;
                switch( choice2 )
            {
                case 1:
                    break;
                case 2:
                    
                    if (annaTable.isEmpty())
                    {
                        readData(annaTable,"data_set_1");
                    }
                    else
                    {
                        cout << "Table is already built!" << endl;
                    }
                    
                    break;
                case 3:
                    break;
                case 4:
                    break;
                case 5:
                    break;
                case 6:
                    break;
                case 7:
                    break;
                default:
                    break;
                    
            }
                break;
            case 2:
                cout << "\n----------------------" << endl;
                cout << "  INSERT: " << endl;
                cout << "\n----------------------" << endl;
                cout << "1.Insert using Direct Address" << endl;
                cout << "2.Insert using Division" << endl;
                cout << "3.Insert using Fibonacci" << endl;
                cout << "4.Insert using Perfect" << endl;
                cout << "5.Insert using Double Hashing" << endl;
                cout << "6.Insert using Universal" << endl;
                cout << "7.Return " << endl;
                cout << "Enter your choice: " << endl;
                cin >> choice2;
                switch( choice2 )
            {
                case 1:
                    break;
                case 2:
                    
                    cout << "what is the name of the student you want to insert ?" << endl;
                    cin >> name;
                    cout << "what is the id number of the student you want to insert ?" << endl;
                    cin >> id;
                    
                    annaTable.insert(name,id);
                    
                    break;
                case 3:
                    break;
                case 4:
                    break;
                case 5:
                    break;
                case 6:
                    break;
                case 7:
                    break;
                default:
                    break;
                    
            }
                break;
            case 3:
                cout << "\n----------------------" << endl;
                cout << "  PRINT : " << endl;
                cout << "\n----------------------" << endl;
                cout << "1.Print using Direct Address" << endl;
                cout << "2.Print using Division" << endl;
                cout << "3.Print using Fibonacci" << endl;
                cout << "4.Print using Perfect" << endl;
                cout << "5.Print using Double Hashing" << endl;
                cout << "6.Print using Universal" << endl;
                cout << "7.Return " << endl;
                cout << "Enter your choice: " << endl;
                cin >> choice2;
                switch( choice2 )
            {
                case 1:
                    break;
                case 2:
                    annaTable.print();
                    break;
                case 3:
                    break;
                case 4:
                    break;
                case 5:
                    break;
                case 6:
                    break;
                case 7:
                    break;
                default:
                    break;
                    
            }
                break;
            case 4:
                cout << "\n----------------------" << endl;
                cout << "  SEARCH: " << endl;
                cout << "\n----------------------" << endl;
                cout << "1.Search using Direct Address" << endl;
                cout << "2.Search using Division" << endl;
                cout << "3.Search using Fibonacci" << endl;
                cout << "4.Search using Perfect" << endl;
                cout << "5.Search using Double Hashing" << endl;
                cout << "6.Search using Universal" << endl;
                cout << "7.Return " << endl;
                cout << "Enter your choice: " << endl;
                cin >> choice2;
                switch( choice2 )
            {
                case 1:
                    break;
                case 2:
                    cout << "what is the id of the student you're lookign for?" << endl;
                    cin >> id;
                    
                    annaTable.search(id);
                    
                    break;
                case 3:
                    break;
                case 4:
                    break;
                case 5:
                    break;
                case 6:
                    break;
                case 7:
                    break;
                default:
                    break;
                    
            }
                break;
            case 5:
                exit( 1 );
            default:
                cout << "\nEnter correct option\n";
        }
    }
    
    // Anna();
    //    Jimmy();
    //Nikita();
    //Dharma();
    //Viktoriia();
    
    return 0;
};
예제 #21
0
ML_START_NAMESPACE

void AnimationExecuter::commandClip(vector<string>* tempEntryParams, kScriptFrameEntry* currentEntry, int /*frameNr*/, size_t /*FrameEntryListIter*/)
{
	//Params:					
	//on/off left/right/... percent toClip (notToClip) (aab/oab)
	if (tempEntryParams->size()>=4)
	{	
		//Parameter 1: on/off
		bool onOff = false;
		onOff=((*tempEntryParams)[0]=="ON");

		//Parameter 2: left/right/...
		//noch nicht
		string clipPlane;
		if ((*tempEntryParams)[1]=="LEFT")
			clipPlane = LAY_CLIPPINGLEFT;
		else if ((*tempEntryParams)[1]=="RIGHT")
			clipPlane = LAY_CLIPPINGRIGHT;
		else if ((*tempEntryParams)[1]=="TOP")
			clipPlane = LAY_CLIPPINGTOP;
		else if ((*tempEntryParams)[1]=="BOTTOM")
			clipPlane = LAY_CLIPPINGBOTTOM;
		else if ((*tempEntryParams)[1]=="REAR")
			clipPlane = LAY_CLIPPINGREAR;
		else clipPlane = LAY_CLIPPINGFRONT; //Front is default																			

		myObjMgr->setObjAttribute(O_CLIPPING,clipPlane,INF_CLIPPING_ON,new string((*tempEntryParams)[0]),omINFOTYPE_STRING,true,true);

		//Parameter 5: listNotToClip						
		vector<string>* listNotToClip = new vector<string>;
		if (tempEntryParams->size()>=5)
			myAnimationParser->getObjectStringList(kBasics::trimQuotatedStr((string)(*tempEntryParams)[4], kBasics::QUOTATION_SINGLE).c_str(),listNotToClip);

		//Parameter 4: listToClip, listForBB						
		HashTable<string>* listToClip = new HashTable<string>;						
		myAnimationParser->getObjectStringList(kBasics::trimQuotatedStr((string)(*tempEntryParams)[3], kBasics::QUOTATION_SINGLE).c_str(),listToClip);

		for ( size_t i = 0; i<listNotToClip->size(); i++)
			listToClip->remove((*listNotToClip)[i]);

		//Parameter 6: aab/oab

		//Transform ClippingBox
		//Get BoundingBox for objects to clip

		AnimationCache::Measures MasterBB = myCache->getMeasuresFromHT((string)(*tempEntryParams)[3]);
		SbVec3f BBCenter = myCache->getBoundingCenter(MasterBB);

		//Translation
		myObjMgr->setObjAttribute(O_CLIPPING,L_GLOBAL,INF_CLIPPING_TRANSLATION,new vec3(BBCenter[0],BBCenter[1],BBCenter[2]),omINFOTYPE_VEC3,true,true);

		//Scale
		//Scale nimmt sowieso nachher bei der ClipBox den größten der 3 werte
		SbVec3f tempScale;
		tempScale[0] = std::abs(MasterBB.BB_max[0]-MasterBB.BB_min[0])/2;
		tempScale[1] = std::abs(MasterBB.BB_max[1]-MasterBB.BB_min[1])/2;
		tempScale[2] = std::abs(MasterBB.BB_max[2]-MasterBB.BB_min[2])/2;
		myObjMgr->setObjAttribute(O_CLIPPING,L_GLOBAL,INF_CLIPPING_SCALE,new vec3(tempScale[0],tempScale[1],tempScale[2]),omINFOTYPE_VEC3,true,true);

		//Parameter 3: percent
		//left 
		//x +1 clip nothing
		//x -1 clip all
		string vecString;
		if (clipPlane == LAY_CLIPPINGLEFT)
			vecString = kBasics::FloatToString(1-2*kBasics::StringToFloat((string)(*tempEntryParams)[2]))+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0");
		else if (clipPlane == LAY_CLIPPINGRIGHT)
			vecString = kBasics::FloatToString(-1+2*kBasics::StringToFloat((string)(*tempEntryParams)[2]))+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0");
		else if (clipPlane == LAY_CLIPPINGTOP)
			vecString = string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+kBasics::FloatToString(1-2*kBasics::StringToFloat((string)(*tempEntryParams)[2]));
		else if (clipPlane == LAY_CLIPPINGBOTTOM)
			vecString = string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+kBasics::FloatToString(-1+2*kBasics::StringToFloat((string)(*tempEntryParams)[2]));
		else if (clipPlane == LAY_CLIPPINGREAR)							
			vecString = string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+kBasics::FloatToString(1-2*kBasics::StringToFloat((string)(*tempEntryParams)[2]))+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0");
		else
			vecString = string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+kBasics::FloatToString(-1+2*kBasics::StringToFloat((string)(*tempEntryParams)[2]))+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0");

		setV3ValueInterpol(O_CLIPPING, clipPlane,INF_CLIPPING_TRANSLATION, vecString, currentEntry->getCurrentFrame(), currentEntry->getFrameCount());

		//Nur beim ersten Frame einer setClipPlane-Anweisung soll er alle Clipping-Eigenschaften zurücksetzen.
		//Testen mit Anweisungen a la [1,10]
		if (currentEntry->getCurrentFrame()==0)
		{
			kDebug::Debug("Reset all Clipping to false",kDebug::DL_HIGH);
			//Get read-only access to object container
			const omObjectContainer *oc= getConstObjContainer();

			oc = getObjContainer();
			if(oc != NULL)
			{		
				omObjectContainer ::const_iterator iterObj;
				//definition in mlObjMgrObjectContainer.h: typedef std::map<omIDType, omObject> objVec;

				for ( iterObj = oc->begin(); iterObj!=oc->end(); iterObj++)
				{
					omObject tempObj = iterObj->second;
					//Als Typ für das Feld BOOL zu nehmen scheiterte daran, das nicht existente Felder bei z.B. viewer-Objekten auch TRUE zurückgeben wenn man nach dem Attribut fragt

					omAttribute attr2 = tempObj.getAttribute(LAY_DESCRIPTION,INF_NAME);
					if (attr2.getStringValue()!="")
					{
						if ((listToClip->find(kBasics::toUp(attr2.getStringValue()))!=NULL))
						{
							myObjMgr->setObjAttribute(tempObj.getID(),LAY_APPEARANCE,INF_CLIPPING,new string("ON"),omINFOTYPE_STRING,true,true);
							sendNotification();
						}
						else
						{
							if (tempObj.hasAttribute(LAY_APPEARANCE,INF_CLIPPING))
							{
								omAttribute attr1 = tempObj.getAttribute(LAY_APPEARANCE,INF_CLIPPING);
								if (kBasics::toUp(attr1.getStringValue()) == "ON")
								{			
									myObjMgr->setObjAttribute(tempObj.getID(),LAY_APPEARANCE,INF_CLIPPING,new string("OFF"),omINFOTYPE_STRING,true,true);
									sendNotification();
								}											
							}
						}
					}
				}
			}
		}

		delete listNotToClip; delete listToClip;
		sendNotification();
	}
	else kDebug::Debug("setClipPlane -> to few arguments",kDebug::DL_HIGH);					
}
예제 #22
0
int main() {

    HashTable<int>* h = new HashTable<int>(47);

    h->insert("sylvan",10);
    h->insert("lora",5);
    h->insert("jake",15);
    h->insert("kiran",20);
    h->insert("theo",16);
    h->insert("sylvan",41);
    h->insert("lora",39);
    h->insert("jake",6);
    h->insert("kiran",3);
    h->insert("theo",1);

    h->insert("will",10);
    h->insert("kelly",5);
    h->insert("nadine",15);
    h->insert("nick",20);
    h->insert("zoe",16);
    h->print();

    if (h->find("sylvan")!=0)
        cout << *(h->find("sylvan")) << endl;

    h->remove("sylvan");
    h->remove("lora");
    h->remove("will");
    h->print();

    h->insert("sylvan",30);
    h->insert("lora",28);
    h->insert("aili",0);
    h->insert("richard",70);
    h->insert("robert",70);
    h->insert("sandie",73);
    h->print();

    delete h;

}
예제 #23
0
bool
windows_suspend(DWORD pid)
{
	// make sure we haven't already suspended this process, then allocate
	// a SuspendedProcess object and add it to the hash table
	//
	SuspendedProcess* sp;
	int ret = suspended_processes.lookup(pid, sp);
	ASSERT(ret == -1);
	sp = new SuspendedProcess(11, hash_func);
	ASSERT(sp != NULL);
	ret = suspended_processes.insert(pid, sp);
	ASSERT(ret != -1);

	// we need to loop until iterating through the thread list for this
	// process shows that all threads are suspended
	//
	bool finished = false;
	while (!finished) {

		// assume we're going to succeed on this iteration until
		// proven otherwise
		//
		finished = true;

		// get the list of threads for this process
		//
		ExtArray<DWORD> tid_array;
		int num_tids = sys_info.GetTIDs(pid, tid_array);
		if (num_tids == 0) {
			// TODO: we need to handle this case!!!
			//
			EXCEPT("windows_suspend_process failed: can't get threads for pid %u",
			       pid);
		}

		// go through the thread list, calling SuspendThread on each
		//
		for (int i = 0; i < num_tids; i++) {

			// see if we already have a record for this thread
			//
			SuspendedThread* st;
			ret = sp->lookup(tid_array[i], st);
			if (ret == -1) {

				// no record yet; open up this thread's handle
				//
				HANDLE handle = OpenThread(THREAD_SUSPEND_RESUME, FALSE, tid_array[i]);
				if (handle == NULL) {

					// the thread probably exited; however, it may have called ResumeThread
					// or CreateThread first, so we'll have to loop again
					//
					finished = false;
					dprintf(D_FULLDEBUG,
					        "windows_suspend_process: OpenThread error: %u\n",
					        GetLastError());
					continue;
				}

				// now that we have a handle, create a record for this thread
				//
				st = new SuspendedThread;
				ASSERT(st != NULL);
				st->handle = handle;
				st->num_suspends = 0;
				ret = sp->insert(tid_array[i], st);
				ASSERT(ret != -1);
			}

			// now suspend the thread
			//
			DWORD result = SuspendThread(st->handle);
			if (result == (DWORD)-1) {

				// how can this happen? maybe the thread exited?
				//
				finished = false;
				dprintf(D_FULLDEBUG,
						"windows_suspend_process: SuspendThread error: %u\n",
						GetLastError());
				continue;
			}

			// if the thread was not suspended prior to our SuspendThread call,
			// it may have called CreateThread or ResumeThread so we need to loop
			// at least one more time
			//
			if (result == 0) {
				finished = false;
			}

			// keep track of how many suspends we've sent this thread
			//
			st->num_suspends++;
		}
	}

	return true;
}
예제 #24
0
#include <string>

NS_BEGIN(elloop);

template <typename T>
void dumpHashTable(const HashTable<T> &ht) {
    psln(ht.size());
    psln(ht.capacity());
}

// todo: use HashTable to solve real oj problem.
BEGIN_TEST(HashTableTest, StringHash, @@);

    std::cout << std::boolalpha;
    bool isUnique(false);

    HashTable<std::string> ht;

    dumpHashTable(ht);

    psln(ht.search("hello"));

    psln(ht.insert("hello", isUnique));
    psln(isUnique);
    psln(ht.search("hello"));

END_TEST;

NS_END(elloop);

예제 #25
0
	HashTable(const HashTable& hash_table) : hasher(), n(0), table(*(new table_type(hash_table.Size())))
	{
		for (hash_iterator_type it = hash_table.begin(); it != hash_table.end(); ++it)
			Add(*it);
	}
예제 #26
0
void dumpHashTable(const HashTable<T> &ht) {
    psln(ht.size());
    psln(ht.capacity());
}
예제 #27
0
Foam::processorGAMGInterface::processorGAMGInterface
(
    const lduInterface& fineInterface,
    const labelField& localRestrictAddressing,
    const labelField& neighbourRestrictAddressing
)
:
    GAMGInterface
    (
        fineInterface,
        localRestrictAddressing,
        neighbourRestrictAddressing
    ),
    fineProcInterface_(refCast<const processorLduInterface>(fineInterface))
{
    // Make a lookup table of entries for owner/neighbour
    HashTable<SLList<label>, label, Hash<label> > neighboursTable
    (
        localRestrictAddressing.size()
    );

    // Table of face-sets to be agglomerated
    HashTable<SLList<SLList<label> >, label, Hash<label> > faceFaceTable
    (
        localRestrictAddressing.size()
    );

    label nCoarseFaces = 0;

    forAll (localRestrictAddressing, ffi)
    {
        label curMaster = -1;
        label curSlave = -1;

        // Do switching on master/slave indexes based on the owner/neighbour of
        // the processor index such that both sides get the same answer.
        if (myProcNo() < neighbProcNo())
        {
            // Master side
            curMaster = localRestrictAddressing[ffi];
            curSlave = neighbourRestrictAddressing[ffi];
        }
        else
        {
            // Slave side
            curMaster = neighbourRestrictAddressing[ffi];
            curSlave = localRestrictAddressing[ffi];
        }

        // Look for the master cell.  If it has already got a face,
        // add the coefficient to the face.  If not, create a new face.
        if (neighboursTable.found(curMaster))
        {
            // Check all current neighbours to see if the current slave already
            // exists and if so, add the fine face to the agglomeration.

            SLList<label>& curNbrs = neighboursTable.find(curMaster)();

            SLList<SLList<label> >& curFaceFaces =
                faceFaceTable.find(curMaster)();

            bool nbrFound = false;

            SLList<label>::iterator nbrsIter = curNbrs.begin();

            SLList<SLList<label> >::iterator faceFacesIter =
                curFaceFaces.begin();

            for
            (
                ;
                nbrsIter != curNbrs.end(), faceFacesIter != curFaceFaces.end();
                ++nbrsIter, ++faceFacesIter
            )
            {
                if (nbrsIter() == curSlave)
                {
                    nbrFound = true;
                    faceFacesIter().append(ffi);
                    break;
                }
            }

            if (!nbrFound)
            {
                curNbrs.append(curSlave);
                curFaceFaces.append(ffi);

                // New coarse face created
                nCoarseFaces++;
            }
        }
        else
        {
            // This master has got no neighbours yet.  Add a neighbour
            // and a coefficient, thus creating a new face
            neighboursTable.insert(curMaster, SLList<label>(curSlave));
            faceFaceTable.insert(curMaster, SLList<SLList<label> >(ffi));

            // New coarse face created
            nCoarseFaces++;
        }
    } // end for all fine faces
예제 #28
0
void Display::ShowDataStructItems()
{
	ArrayStack<int> dsArrayStack;
	ListStack<int>	lsListStack;
	ArrayQueue<int> aqArrayQueue;
	CycleDoublyLinkList<int> dcllCycleDoublyLinkList;
	BinarySearchTree<int> bstBinarySearchTree;
	RedBlackTree<int> rbtRedBlackTree;
	MergeFindSet<int> mfsMergeFindSet;
	HashTable<int> htHashTable;
	cout<<WELCOME_STRING<<endl;
	cout<<"This is the Implement of Data Structs"<<endl;
	cout<<"Please Select the Item you are Interest in:"<<endl;
	cout<<"1.	Stack(Implement of Array);"<<endl;
	cout<<"2.	Stack(Implement of List);"<<endl;
	cout<<"3.	Queue(Implement of Array);"<<endl;
	cout<<"4.	Cycle Doubly Linked List"<<endl;
	cout<<"5.	Binary Search Tree"<<endl;
	cout<<"6.	Red Black Tree"<<endl;
	cout<<"7.	Merge Find Set"<<endl;
	cout<<"8.	Hash Table"<<endl;
	cout<<"98.	Up Layer;"<<endl;
	cout<<"99.	Quit."<<endl;
	cout<<STAR_STRING<<endl;
	cout<<endl;
	int nSelect;
	while(1)
	{
		cin>>nSelect;
		if(cin.fail())
		{
			ClearScreen();
			cout<<"Input Error! Please Select Again!"<<endl;
			cin.clear();
			cin.sync();
			ShowDataStructItems();
		}
		ClearScreen();
		switch(nSelect)
		{
		case 1:
			cout<<dsArrayStack.GetTitle().c_str()<<endl;
			dsArrayStack.Description();
			dsArrayStack.Test();
			ShowDataStructItems();
			break;
		case 2:
			cout<<lsListStack.GetTitle().c_str()<<endl;
			lsListStack.Description();
			lsListStack.Test();
			ShowDataStructItems();
			break;
		case 3:
			cout<<aqArrayQueue.GetTitle().c_str()<<endl;
			aqArrayQueue.Description();
			aqArrayQueue.Test();
			ShowDataStructItems();
			break;
		case 4:
			cout<<dcllCycleDoublyLinkList.GetTitle().c_str()<<endl;
			dcllCycleDoublyLinkList.Description();
			dcllCycleDoublyLinkList.Test();
			ShowDataStructItems();
			break;
		case 5:
			cout<<bstBinarySearchTree.GetTitle().c_str()<<endl;
			bstBinarySearchTree.Description();
			bstBinarySearchTree.Test();
			ShowDataStructItems();
			break;
		case 6:
			cout<<rbtRedBlackTree.GetTitle().c_str()<<endl;
			rbtRedBlackTree.Description();
			rbtRedBlackTree.Test();
			ShowDataStructItems();
			break;
		case 7:
			cout<<mfsMergeFindSet.GetTitle().c_str()<<endl;
			mfsMergeFindSet.Description();
			mfsMergeFindSet.Test();
			ShowDataStructItems();
			break;
		case 8:
			cout<<htHashTable.GetTitle().c_str()<<endl;
			htHashTable.Description();
			htHashTable.Test();
			ShowDataStructItems();
			break;
		case 98:
			goto ShowWelcome;
			break;
		case 99:
			exit(0);
			break;
		default:
			ClearScreen();
			cout<<"Select Error! Please Select Again!"<<endl;
			cin.clear();
			cin.sync();
			ShowDataStructItems();
			break;
		}
	}
ShowWelcome:
	Show();
	return;
}
예제 #29
0
int main(int argc, char *argv[])
{
    wordHashSet setA(0);
    HashTable<label, word> tableA;

    HashTable<nil> tableB;
    Map<label> mapA;

    setA.insert("kjhk");
    setA.insert("kjhk2");

    tableA.insert("value1", 1);
    tableA.insert("value2", 2);
    tableA.insert("value3", 3);

    tableB.insert("value4", nil());
    tableB.insert("value5", nil());
    tableB.insert("value6", nil());

    mapA.set(1, 1);
    mapA.set(2, 2);
    mapA.set(3, 3);
    mapA.set(4, 4);

    Info<< setA << endl;
    Info<< tableA << endl;
    Info<< mapA << endl;

    Info<< "create from HashSet: ";
    Info<< wordHashSet(setA) << endl;
    Info<< "create from HashTable<T>: ";
    Info<< wordHashSet(tableA) << endl;
    Info<< "create from HashTable<nil>: ";
    Info<< wordHashSet(tableB) << endl;

    Info<< "create from Map<label>: ";
    Info<< labelHashSet(mapA) << endl;

    Info<<"combined toc: "
        << (wordHashSet(setA) | wordHashSet(tableA) | wordHashSet(tableB))
        << nl;


    labelHashSet setB(1);
    setB.insert(11);
    setB.insert(42);

    Info<< "setB : " << setB << endl;

    labelHashSet setC(1);
    setC.insert(2008);
    setC.insert(1984);

    Info<< "setC : " << setC << endl;

    labelHashSet setD(1);
    setD.insert(11);
    setD.insert(100);
    setD.insert(49);
    setD.insert(36);
    setD.insert(2008);

    Info<< "setD : " << setD << endl;

    Info<< "setB == setC: " << (setB == setC) << endl;
    Info<< "setC != setD: " << (setC != setD) << endl;

    // test operations
    setB += setC;
    Info<< "setB += setC : " << setB << endl;

    setB &= setD;
    Info<< "setB &= setD : " << setB << endl;

    Info<< "setB : " << setB << endl;
    Info<< "setC : " << setC << endl;
    Info<< "setD : " << setD << endl;
    Info<< "setB ^ setC ^ setD : " << (setB ^ setC ^ setD) << endl;

    // test operator[]

    Info<< "setD : " << setD << endl;
    if (setD[0])
    {
        Info<< "setD has 0" << endl;
    }
    else
    {
        Info<< "setD has no 0" << endl;
    }


    if (setD[11])
    {
        Info<< "setD has 11" << endl;
    }
    else
    {
        Info<< "setD has no 0" << endl;
    }

    Info<< "setD : " << setD << endl;

    // this doesn't work (yet?)
    // setD[12] = true;

    List<label> someLst(10);
    forAll(someLst, elemI)
    {
        someLst[elemI] = elemI*elemI;
    }
예제 #30
0
void OracleBuilder::exploreNode(ConcurrentMap<string, HashTable *> &tables,
                                NodeStack &nodes, Color playFor, int commId)
{
    Position pos;
    Comm::UCICommunicatorPool &pool = Comm::UCICommunicatorPool::getInstance();
    Options &opt = Options::getInstance();
    HashTable *oracle = tables[""];
    pool.sendOption(commId, "MultiPV", to_string(opt.getMaxMoves()));
    //Main loop
    Node *current = nullptr;
    while ((current = nodes.poptop())) {
        string iterationOutput;
        const string currentPos = current->getPos();

        Line bestLine;
        /*Set the chessboard to current pos*/
        pos.set(currentPos);
        Color active = pos.side_to_move();
        string signature = pos.signature();
        uint64_t curHash = pos.hash();
        bool insertCopyInSignTable = false;

        /*Lookup in signature tables*/
        if (signature.length() <= opt.getMaxPiecesEnding()) {
            HashTable *table = nullptr;
            if (tables.count(signature) == 0) {
                string filename = opt.getTableFolder() + "/" + signature
                                  + ".autosave."
                                  + opt.getVariantAsString()
                                  + to_string(opt.getCutoffThreshold())
                                  + ".bin";
                table = new HashTable(filename);
                if (tables.findOrInsert(signature, table) != table) {
                    delete table;
                    table = tables[signature];
                }
            } else {
                table = tables[signature];
            }
            Node *s = nullptr;
            if ((s = table->findVal(curHash))) {
                current->updateStatus((Node::StatusFlag)
                                      (s->getStatus() | Node::SIGNATURE_TABLE));
                if (current->getStatus() & Node::THEM) {
                    OracleBuilder::displayNodeHistory(current);
                    Out::output("Iteration output for error :\n" + iterationOutput);
                    Err::handle("A node has gone from draw to mate, this is an error"
                                " until we decide on what to do, and if it's a bug"
                                " in the engine.");
                }
                if (oracle->findOrInsert(curHash, current) != current)
                    delete current;
                continue;
            } else {
                insertCopyInSignTable = true;
            }
        }

        /*Try to find the position and insert it if not found*/
        if (oracle->findOrInsert(curHash, current) != current) {
            Out::output(iterationOutput, "Position already in table.\n", 1);
            delete current;
            continue;
        }

        /* TODO rethink this, as we should probably remove the position if cut
         *if (OracleBuilder::cutNode(pos, current)) {
         *    Out::output("Node cut by user-defined function", 1);
         *    continue;
         *}
         */
        Out::output(iterationOutput, "[" + color_to_string(active)
                    + "] Proceed size : " + to_string(nodes.size())
                    + "\n");

        /*Clear cut*/
        if (!pos.hasSufficientMaterial()) {
            current->updateStatus(Node::DRAW);
            Out::output(iterationOutput, "[" + color_to_string(active)
                        + "] Insuficient material.\n", 2);
            //Proceed to next node...
            continue;
        }


        Out::output(iterationOutput, pos.pretty(), 2);

        /*Hit statistic*/
        __atomic_fetch_add(&OracleFinder::signStat_[signature], 1, __ATOMIC_SEQ_CST);

        string position = "position fen ";
        position += pos.fen();
        pool.send(commId, position);

        if (playFor != active) {
            /*We are on a node where the opponent has to play*/
            current->updateStatus(Node::AGAINST);
            /*proceedAgainstNode(pos, current);*/
            vector<Move> all = gen_all(pos);
            /*
             * Push all node for the side we "play for".
             * eg: if we are building an oracle for white, we need to push all
             * possible white positions when computing a black node.
             */
            Out::output(iterationOutput, "Push all lines : ", 2);
            for (Move m : all) {
                string uciMv = move_to_string(m);
                Out::output(iterationOutput, "+", 2);
                if (!pos.tryAndApplyMove(m))
                    Err::handle("Illegal move pushed ! (While proceeding against Node)");
                string fen = pos.fen();
                pos.undoLastMove();
                Node *next = new Node(current, fen, Node::PENDING);
                nodes.push(next);
                MoveNode move(uciMv, next);
                current->safeAddMove(move);
            }
            Out::output(iterationOutput, "\n", 2);
            continue;
        }

        /**********************************************/
        /*Here we are on a node with "playfor" to play*/
        /**********************************************/

        const vector<Line> &lines = pool.getResultLines(commId);

        /*Thinking according to the side the engine play for*/
        int moveTime = opt.getPlayforMovetime();

        Out::output(iterationOutput, "[" + color_to_string(active)
                    + "] Thinking... (" + to_string(moveTime) + ")\n", 1);

        string cmd = "go ";
        switch (opt.getSearchMode()) {
            case DEPTH:
                cmd += "depth " + to_string(opt.getSearchDepth());
                break;
            case MIXED://Intentional no-break
            /*TODO: implement mixed search ? likely not,
             * early multipv in stockfish*/
            case TIME:
            default:
                cmd += "movetime " + to_string(moveTime);
                break;
        }
        //Send go and wait for engine to finish thinking
        pool.sendAndWaitBestmove(commId, cmd);


        Out::output(iterationOutput, Utils::getPrettyLines(pos, lines), 2);

        bestLine = lines[0];
        bool skipThisNode = false;
        if (bestLine.empty()) {
            //STALEMATE
            current->updateStatus(Node::STALEMATE);
            Out::output(iterationOutput, "[" + color_to_string(active)
                        + "] Bestline is stalemate (cut)\n", 2);
            //Proceed to next node...
            skipThisNode = true;
        } else if (bestLine.isMat()) {
            Out::output(iterationOutput, "[" + color_to_string(active)
                        + "] Bestline is mate (cut)\n", 2);
            /*Eval is always negative if it's bad for us*/
            if (bestLine.getEval() < 0) {
                current->updateStatus((Node::StatusFlag)(Node::MATE | Node::THEM));
                Out::output("Iteration output for error :\n" + iterationOutput);
                OracleBuilder::displayNodeHistory(current);
                Err::handle("A node has gone from draw to mate, this is an error"
                            " until we decide on what to do, and if it's a bug"
                            " in the engine.");
            } else {
                current->updateStatus((Node::StatusFlag)(Node::MATE | Node::US));
            }
            skipThisNode = true;
        } else if (fabs(bestLine.getEval()) > opt.getCutoffThreshold()) {
            Out::output(iterationOutput, "[" + color_to_string(active)
                        + "] Bestline is above threshold (cut)\n", 2);
            if (bestLine.getEval() < 0) {
                current->updateStatus((Node::StatusFlag)(Node::THRESHOLD | Node::THEM));
                Out::output("Iteration output for error :\n" + iterationOutput);
                OracleBuilder::displayNodeHistory(current);
                Err::handle("A node has gone from draw to threshold, this is an error"
                            " until we decide on what to do, and if it's a bug"
                            " in the engine.");
            } else {
                current->updateStatus((Node::StatusFlag)(Node::THRESHOLD | Node::US));
            }
            skipThisNode = true;
        }

        /*Trick to avoid code duplicaton for inserting copy in table*/
        if (!skipThisNode) {
            current->updateStatus(Node::DRAW);
            /* If we are not in fullBuild mode, just insert a pending node in
             * table if the signature is low enough
             */
            if (!opt.fullBuild() &&
                signature.length() <= opt.getMaxPiecesEnding()) {
                if (oracle->findOrInsert(curHash, current) != current)
                    delete current;
                else
                    current->updateStatus((Node::StatusFlag)
                                          (current->getStatus() | Node::PENDING));
                continue;
            }
        }

        if (insertCopyInSignTable) {
            Node *cpy = current->lightCopy();
            if (tables[signature]->findOrInsert(curHash, cpy) != cpy)
                delete cpy;
        }

        if (skipThisNode)
            continue;

        /*If we are here, bestLine is "draw", and we should continue to explore*/
        vector<Line> playableLines;

        /*Select all the candidate lines (bestmove +- deviation)*/
        for (Line l : lines) {
            if (!(l.empty() || l.isMat())
                && (fabs(bestLine.getEval() - l.getEval())
                   <= opt.getBestmoveDeviation()
                   || l.getEval() >= -1))
                playableLines.push_back(l);
        }



        /*
         *Then proceed the balanced lines according to the side the engine
         *play for.
         */
        if (playFor != active)
            Err::handle("Current side should be the engine plays for");

        /*
         * General Idea : try to force repetition by trying to find a playable
         * position in the hashtable. If not sort the playable moves
         * according to a user defined comparator
         */
        Node *next = NULL;
        /*The elected move*/
        string mv;

        /*Try to find a position in the table*/
        /* There must be a reason to go trough it backward, but I can't
         * remember it right now.
         */
        Line l;
        for (auto rit = playableLines.rbegin();
             rit != playableLines.rend(); ++rit) {
            l = *rit;
            mv = l.firstMove();
            if (!pos.tryAndApplyMove(mv)) {
                Err::output(pos.pretty());
                Err::output("Move : " + mv);
                Err::handle("Illegal move while proceeding a draw node");
            }
            /*This is the next pos*/
            uint64_t hashpos = pos.hash();
            pos.undoLastMove();
            //Jean Louis' idea to force finding positions in oracle
            next = oracle->findVal(hashpos);
            if (next) {
                next->safeAddParent(current);
                break;
            }
        }

        /*No repetition found, sort the playable lines*/
        if (!next) {
            std::sort(playableLines.begin(), playableLines.end(),
                         [&pos](const Line &lhs, const Line &rhs)
                         {
                             return pos.compareLines(lhs, rhs);
                         });
            l = playableLines[0];
            mv = l.firstMove();
            pos.tryAndApplyMove(mv);
            string fenpos = pos.fen();
            pos.undoLastMove();

            //no next position in the table, push the node to stack
            next = new Node(current, fenpos, Node::PENDING);
            Out::output(iterationOutput, "[" + color_to_string(active)
                        + "] Pushed first line (" + mv + ") : " + fenpos + "\n", 2);
            nodes.push(next);
        }

        /*Whatever the move is, add it to our move list*/
        MoveNode move(mv, next);
        current->safeAddMove(move);
        Out::output(iterationOutput, "-----------------------\n", 1);
        /*Send the whole iteration output*/
        Out::output(iterationOutput);
    }
}