Exemple #1
0
void Topology::Open() {
  shapefileopen = false;

  #if USETOPOMARKS
  if (append) {
    if (msSHPOpenFile(&shpfile, (char*)"rb+", filename) == -1) {
      // StartupStore(_T(". Topology: Open: append failed for <%s> (this can be normal)%s"),filename,NEWLINE);
      return;
    }
  } else {
  #endif
    if (msSHPOpenFile(&shpfile, (char*)"rb", filename) == -1) {
      StartupStore(_T("------ Topology: Open FAILED for <%s>%s"),filename,NEWLINE);
      return;
    }
  #if USETOPOMARKS
  }
  #endif
  // StartupStore(_T(". Topology: Open <%s>%s"),filename,NEWLINE);

  scaleThreshold = 1000.0;
  shpCache = (XShape**)malloc(sizeof(XShape*)*shpfile.numshapes);
  if (shpCache) {
    shapefileopen = true;
#ifdef TOPOFASTCACHE
	initCache();
#else
    for (int i=0; i<shpfile.numshapes; i++) {
      shpCache[i] = NULL;
    }
#endif
  } else {
	StartupStore(_T("------ ERR Topology,  malloc failed shpCache%s"), NEWLINE);
  }
}
int main(){
	S=0, E=0, B=0, m=0, h=0, p=0, t=0, s=0, b=0, tag=0, setIndex=0, blockOffset=0;
	hits=0, misses=0, counter=0;
	scanf("%d %d %d %d",&S,&E,&B,&m);
	scanf("%s",rpolicy);
	scanf("%d %d",&h,&p);
	initCache();
	readAddress();
	int found, i;				
	while(address != -1){
		//set selection
		Set set = cache.sets[setIndex];
		//line matching
		found = 0;
		for(i=0;i<E;i++){
			if(set.lines[i].valid && set.lines[i].tag == tag){
				hit(&set.lines[i]);
				found = 1;
				break;
			}				
		}
		if(!found)
			miss(&set);
		readAddress();		
	}
	freeMemory();
	statistics();
	return 0;
}
AppConfig::AppConfig():m_globalBatchNode(NULL)
{
	initCache();
	CCSize winSize = CCDirector::sharedDirector()->getWinSize();
	m_worldBoundBox = CCRectMake(0,0,winSize.width,winSize.height);
	//SimpleAudioEngine::sharedEngine()->preloadEffect(USERPLANE_DEFAULT_EMIT_SE_FILE); //预加载发射音效
}
void mips1::init(int ac, char *av[]) {
  extern char* appfilename;
  initCache();
  ac_init_opt( ac, av);
  ac_init_app( ac, av);
  APP_MEM->load(appfilename);
  set_args(ac_argc, ac_argv);
#ifdef AC_VERIFY
  set_queue(av[0]);
#endif

  ac_pc = ac_start_addr;
  ISA._behavior_begin();
  cerr << "ArchC: -------------------- Starting Simulation --------------------" << endl;
  InitStat();

  hazard_count = 0;
  memset(hazard_count_by_type, 0, sizeof(hazard_count_by_type));

  signal(SIGINT, sigint_handler);
  signal(SIGTERM, sigint_handler);
  signal(SIGSEGV, sigsegv_handler);
  signal(SIGUSR1, sigusr1_handler);
#ifdef USE_GDB
  signal(SIGUSR2, sigusr2_handler);
#endif
#ifndef AC_COMPSIM
  set_running();
#else
  void Execute(int argc, char *argv[]);
  Execute(argc, argv);
#endif
}
Exemple #5
0
int main(int argc, char* argv[])
{
	char op;
	opterr = 0;
	while ((op = getopt(argc, argv, "vs:E:b:t:")) != -1) {
		switch (op) {
			case 'v':	v = true;
						break;
			case 's':	setBit = atoi(optarg);
						break;
			case 'E':	lineNum = atoi(optarg);
						break;
			case 'b':	blockBit = atoi(optarg);
						break;
			case 't':	printf("b\n");
						traceName = optarg;
						printf("c\n");
						break;
			default:	printf("Wrong Parametre!\n");
						break;
		}
	}
	setNum = 1 << setBit;
	blockSize = 1 << blockBit;
	if (setNum == 0 || lineNum == 0 || blockSize == 0 || traceName == 0) {
		printf("Missing parametre!\n");
		return 1;
	}
	initCache();
	parse();
    printSummary(hit, miss, eviction);
    return 0;
}
/* 
 * main function 
 */
int main(int argc, char **argv) {
    
    // ignore SIGPIPE signal
    Signal(SIGPIPE, SIG_IGN);

    int listenfd, *connfdp;
    socklen_t clientlen;
    struct sockaddr_storage clientaddr;
    pthread_t tid;// thread id

    /* Check command line args */
    if (argc != 2) {
        fprintf(stderr, "usage: %s <port>\n", argv[0]);
        exit(1);
    }

    // init mutex lock
    sem_init(&mutex, 0, 1);
    // init cache
    initCache(&cache);

    listenfd = Open_listenfd(argv[1]);
    while (1) {
        clientlen = sizeof(clientaddr);

        //accept request from client
        connfdp = Malloc(sizeof(int)); // avoid unintended sharing 
        *connfdp = Accept(listenfd, (SA *)&clientaddr, &clientlen); 
        // doit(connfd, &cache);    //line:netp:tiny:doit

        /* create thread to process request */
        Pthread_create(&tid, NULL, thread, connfdp);
    }
}
ExtragalacticUnits::ExtragalacticUnits()
{
    // select the appropriate units
    _unitForQty["length"] = "pc";
    _unitForQty["distance"] = "Mpc";
    _unitForQty["wavelength"] = "micron";
    _unitForQty["grainsize"] = "micron";
    _unitForQty["section"] = "m2";
    _unitForQty["volume"] = "pc3";
    _unitForQty["velocity"] = "km/s";
    _unitForQty["mass"] = "Msun";
    _unitForQty["bulkmass"] = "kg";
    _unitForQty["bulkmassdensity"] = "kg/m3";
    _unitForQty["masssurfacedensity"] = "Msun/pc2";
    _unitForQty["massvolumedensity"] = "Msun/pc3";
    _unitForQty["opacity"] = "m2/kg";
    _unitForQty["energy"] = "J";
    _unitForQty["bolluminosity"] = "Lsun";
    _unitForQty["monluminosity"] = "Lsun/micron";
    _unitForQty["neutralfluxdensity"] = "W/m2";
    _unitForQty["neutralsurfacebrightness"] = "W/m2/arcsec2";
    _unitForQty["wavelengthfluxdensity"] = "W/m2/micron";
    _unitForQty["wavelengthsurfacebrightness"] = "W/m2/micron/arcsec2";
    _unitForQty["frequencyfluxdensity"] = "Jy";
    _unitForQty["frequencysurfacebrightness"] = "MJy/sr";
    _unitForQty["temperature"] = "K";
    _unitForQty["angle"] = "arcsec";
    _unitForQty["posangle"] = "deg";
    _unitForQty["solidangle"] = "arcsec2";
    _unitForQty["pressure"] = "K/m3";

    // initialize conversion factors in base class
    initCache();
}
EHTFILE * openEHTFile(char * filename, int keySize) {
    char bucketIndexName[512];
    char bucketFilename[512];
    EHTFILE * file = (EHTFILE *)malloc(sizeof(EHTFILE));
    if ( file == NULL )
        return NULL;

    strncpy(bucketIndexName, filename, 508);
    strcat(bucketIndexName, ".eht");
    strncpy(bucketFilename, filename, 508);
    strcat(bucketFilename, ".bkt");

    file->keyLength = keySize;
    file->bucketIndex = openDirectAccessFile(bucketIndexName, "r", sizeof(unsigned), sizeof(unsigned));
    if ( file->bucketIndex == NULL )
        createIndex(file, bucketIndexName, bucketFilename);
    else {
        file->bucketFile = openDirectAccessFile(bucketFilename, "r", sizeof(BucketRecord), 0);
        if ( file->bucketFile == NULL ) {
            closeDirect(file->bucketIndex);
            createIndex(file, bucketIndexName, bucketFilename);
        } else
            readHeader(&(file->tableSize), file->bucketIndex);
    }
    initCache(file);
    return file;
}
void process_choice(int choice){
	BufferManager *bu = BufferManager::getBufferManager();
	float hr = -1;
	switch(choice){
		case 1: 
			initCache(bu);
			break;
		case 2:
			createDB(bu);
			break;
		case 3:
			openDB(bu);
			break;
		case 4:
			readDB(bu);
			break;
		case 5:
			writeDB(bu);
			break;
		case 6:
			expandDB(bu);
			break;
		case 7:
			commitDB(bu);
			break;
		case 8:
			closeDB(bu);
			break;
		case 9: 
			commitCache(bu);
			break;
		case 10:
			releaseCache(bu);
			break;
		case 11:
			dropDB(bu);
			break;
		case 12:
			cout<<endl<<"Enter Cache id: ";
			cin>>choice;
			(*bu).printHex(choice, (*bu).getPageSize());
			break;
		case 13:
			(*bu).printCacheHeaders();
			break;
		case 14:
			hr = (*bu).getHitRate();
			if(hr!=-1)
				cout<<endl<<"\tHit rate is: "<<hr*100.0<<" %"<<endl;
			else {
				cout<<endl<<"\tHit rate cannot be calculated because cache";
				cout<<" is either not initialized, or no operation";
				cout<<"	has been performed on cache yet."<<endl;
			}
			break;			
		case 15:
		//	releaseCache(bu);
			break;
	}
}
MSAEditorConsensusArea::MSAEditorConsensusArea(MsaEditorWgt *ui)
    : MaEditorConsensusArea(ui) {
    initCache();
    initRenderer();
    setupFontAndHeight();

    connect(editor, SIGNAL(si_buildStaticMenu(GObjectView *, QMenu *)), SLOT(sl_buildStaticMenu(GObjectView *, QMenu *)));
    connect(editor, SIGNAL(si_buildPopupMenu(GObjectView * , QMenu *)), SLOT(sl_buildContextMenu(GObjectView *, QMenu *)));
}
Exemple #11
0
/*
 * main - Main routine 
 */
int main(int argc, char* argv[])
{
    char c;

    while( (c=getopt(argc,argv,"s:E:b:t:vh")) != -1){
        switch(c){
        case 's':
            s = atoi(optarg);
            break;
        case 'E':
            E = atoi(optarg);
            break;
        case 'b':
            b = atoi(optarg);
            break;
        case 't':
            trace_file = optarg;
            break;
        case 'v':
            verbosity = 1;
            break;
        case 'h':
            printUsage(argv);
            exit(0);
        default:
            printUsage(argv);
            exit(1);
        }
    }

    /* Make sure that all required command line args were specified */
    if (s == 0 || E == 0 || b == 0 || trace_file == NULL) {
        printf("%s: Missing required command line argument\n", argv[0]);
        printUsage(argv);
        exit(1);
    }

    /* Compute S, E and B from command line args */
     S=pow(2,s);
     B=pow(2,b);
    /* Initialize cache */
    initCache();

#ifdef DEBUG_ON
    printf("DEBUG: S:%u E:%u B:%u trace:%s\n", S, E, B, trace_file);
#endif
 
    /* Read the trace and access the cache */
    replayTrace(trace_file);

    /* Free allocated memory */
    freeCache();

    /* Output the hit and miss statistics for the autograder */
    printSummary(hit_count, miss_count, eviction_count);
    return 0;
}
Exemple #12
0
void IndexPage::init()
{
	//initFile();
	initCache(true);
	setIndexCount(0);
	setIndexSpace(0);
	setFreeCursor(0);
	setFreeSpace(pageSize - headerSize);
	//sync();
}
Exemple #13
0
void bob::learn::em::GMMMachine::resize(const size_t n_gaussians, const size_t n_inputs) {
  m_n_gaussians = n_gaussians;
  m_n_inputs = n_inputs;

  // Initialise weights
  m_weights.resize(m_n_gaussians);
  m_weights = 1.0 / m_n_gaussians;

  // Initialise Gaussians
  m_gaussians.clear();
  for(size_t i=0; i<m_n_gaussians; ++i)
    m_gaussians.push_back(boost::shared_ptr<bob::learn::em::Gaussian>(new bob::learn::em::Gaussian(n_inputs)));

  // Initialise cache arrays
  initCache();
}
Exemple #14
0
/* 主函数 */
int main(int argc, char *argv[])
{
	FILE *pf;
	char line_buf[100];
	int s, E, b, flag;
	char trace_name[100];
	int state;
	simu_cache cache;
	flag = 0;	
	getinfo(argc, argv, &s, &E, &b, trace_name, &flag);
	initCache(&cache, s, E);
	pf = fopen(trace_name, "r");
	if (!pf) {
		printf("Error: Cann't open file %s!\n", trace_name);
		return -1;
	}
	while (NULL != fgets(line_buf, 100, pf)) {
		if (' ' == line_buf[0]) {
			line_buf[strlen(line_buf)-1] = '\0';
			state = parse_traces(&cache, line_buf, s, E, b, flag);
			if (1 == flag) {
				switch (state) {
				case HIT:
					printf("%s hit\n", line_buf+1);
					break;
				case MISS:
					printf("%s miss\n", line_buf+1);
					break;
				case MISS_AND_HIT:
					printf("%s miss hit\n", line_buf+1);
					break;
				case MISS_AND_EVICTION:
					printf("%s miss eviction\n", line_buf+1);
					break;
				case MISS_EVICTION_AND_HIT:
					printf("%s miss eviction hit\n", line_buf+1);
					break;
				default:
					break;
				}
			}
		}
	}
	fclose(pf);
	printSummary(hits, misses, evictions);
	return 0;
}
Exemple #15
0
void bob::learn::em::GMMMachine::copy(const GMMMachine& other) {
  m_n_gaussians = other.m_n_gaussians;
  m_n_inputs = other.m_n_inputs;

  // Initialise weights
  m_weights.resize(m_n_gaussians);
  m_weights = other.m_weights;

  // Initialise Gaussians
  m_gaussians.clear();
  for(size_t i=0; i<m_n_gaussians; ++i) {
    boost::shared_ptr<bob::learn::em::Gaussian> g(new bob::learn::em::Gaussian(*(other.m_gaussians[i])));
    m_gaussians.push_back(g);
  }

  // Initialise cache
  initCache();
}
Exemple #16
0
LienFavoris::LienFavoris(QUrl urlA, QString nameA, QIcon iconA, QWidget *parent) : QWidget(parent){
    initCache();
    url=urlA;
    name=nameA;

    lien=new Label();
    icone=new Label();
    lienEdit=new QLineEdit();
    button=new QPushButton(QIcon("fleche_droite.png"), "");
    button->setFixedSize(25, 15);
    lienEdit->setFixedHeight(15);
    setFixedHeight(15);
    if(iconA.isNull()){
        if(name.isNull()){
            QWebView *page=new QWebView(parent);
            page->load(url);
            connect(page, SIGNAL(loadFinished(bool)), this, SLOT(loadFinish(bool)));
        }
        else{
Exemple #17
0
void eTuxtxtApp::setEnableTtCachingOnOff( int onoff )
{
    if (onoff && !enableTtCaching)		// Switch caching on
    {
        enableTtCaching = true;
        if (pid)
        {
            initCache();
            startCaching(pid, demux);
        }
    }
    else if (!onoff && enableTtCaching)	// Switch caching off
    {
        enableTtCaching = false;
        int savePid = pid;
        freeCache();
        pid = savePid;
    }
}
Exemple #18
0
void getMaxRectangle(u8* data, u8 val, int w, int h, vect2D* pos, vect2D* size)
{
	int x;
	vect2D originb=vect2(0,0),cornerb=vect2(-1,-1);
	pile_struct p;
	initPile(&p);
	int* c=initCache(h);
	for(x=w-1;x>=0;x--)
	{
		int y, width=0;
		fillCache(c,data,val,w,h,x);
		for(y=0;y<=h;y++)
		{
			if(c[y]>width)
			{
				pushPile(vect2(y,width),&p);
				width=c[y];
			}else if(c[y]<width)
			{
				int y0, w0;
				while(1)
				{
					vect2D v=popPile(&p);
					y0=v.x;w0=v.y;
					if(width*(y-y0)>area(originb,cornerb))
					{
						originb=vect2(x,y0);
						cornerb=vect2(x+width-1,y-1);
					}
					width=w0;
					if(c[y]>=width)break;
				}
				width=c[y];
				if(width)pushPile(vect2(y0,w0),&p);
			}
		}
	}
	if(c)free(c);
	*pos=originb;
	*size=vect2(cornerb.x-originb.x+1,cornerb.y-originb.y+1);
}
HistoryProxy::HistoryProxy(const QString &service,
                           const QString &path,
                           const QDBusConnection &connection,
                           QObject *parent)
    : org::ofono::CallHistory(service, path, connection, parent),
      m_cache(0)
{
    TRACE
    if (gHistory)
        qFatal("HistoryProxy: There can be only one!");

    if (!isValid()) {
        qWarning() << "HistoryProxy: Failed to connect to Ofono: \n\t"
                   << lastError().message();
    } else {
        initCache();

        connect(this, SIGNAL(VoiceHistoryChanged(uint)),
                this, SLOT(voiceHistoryChanged(uint)));
    }
    gHistory = this;
}
Exemple #20
0
void bob::learn::em::GMMMachine::load(bob::io::base::HDF5File& config) {
  int64_t v;
  v = config.read<int64_t>("m_n_gaussians");
  m_n_gaussians = static_cast<size_t>(v);
  v = config.read<int64_t>("m_n_inputs");
  m_n_inputs = static_cast<size_t>(v);

  m_gaussians.clear();
  for(size_t i=0; i<m_n_gaussians; ++i) {
    m_gaussians.push_back(boost::shared_ptr<bob::learn::em::Gaussian>(new bob::learn::em::Gaussian(m_n_inputs)));
    std::ostringstream oss;
    oss << "m_gaussians" << i;
    config.cd(oss.str());
    m_gaussians[i]->load(config);
    config.cd("..");
  }

  m_weights.resize(m_n_gaussians);
  config.readArray("m_weights", m_weights);

  // Initialise cache
  initCache();
}
int handleMessage(struct __message *arg)
{
	struct timeval tStart;
	struct __message msg = {0x0, };
	struct __message resp = {0x0, };

	memcpy(&msg, arg, sizeof(struct __message));

	//TODO: handle packet
	//gettimeofday(&tStart, NULL);

	//TODO: wait until other request responded
	pthread_mutex_lock(&m_lock);
	
	gettimeofday(&tStart, NULL);

	//TODO: use cached resource
	if(msg.cmd == RESOURCE_CMD_REGISTER)
	{
		if(g_uiCacheAlgorithm == 0)
		{
			addObserver0(msg.owner, msg.iFd, msg.resource, msg.req_dur);
		}
		else if(g_uiCacheAlgorithm == 1)
		{
			addObserver1(msg.owner, msg.iFd, msg.resource, msg.req_dur, tStart);
		}
		else if(g_uiCacheAlgorithm == 2)
		{
			addObserver1(msg.owner, msg.iFd, msg.resource, msg.req_dur, tStart);
		}
		dumpObserver();
	}
	else if (msg.cmd == RESOURCE_CMD_GET)
	{
		struct timeval tEnd;
		
		//TODO: get cached resource
		if(g_uiCacheMode && isCachedDataValid(tStart))
		{
			//TODO: update cache timing information
			updateCache(tStart);
			
			//TODO: set server process time with zero
			setTimeValue(&(msg.server_recved), 0, 0);
			setTimeValue(&(msg.server_started), 0, 0);
			setTimeValue(&(msg.server_finished), 0, 0);
			
			//TODO: set message with time information		
			gettimeofday(&tEnd, NULL);
			
			//TODO: set message with time information		
			msg.resource = g_Resource1.iCachedResource;
			msg.uiMaxAge = g_Resource1.uiMaxAge - g_Resource1.uiCachedAge;

			printf("CACHED! Owner=%d, R=%d, MaxAge=%d, CachedAge=%d(%ld.%06ld)\n", 
				msg.owner,
				g_Resource1.iCachedResource, 
				g_Resource1.uiMaxAge,
				g_Resource1.uiCachedAge,
				tEnd.tv_sec%1000,	\
				tEnd.tv_usec
				);
		}
		else
		{
			//TODO: init cache
			initCache();
	
			//TODO: get a fresh resource from a server
			getResourceFromServer(&msg);

			//TODO: get current time
			gettimeofday(&tEnd, NULL);
	
			//TODO: set cached with information
			setCache(msg, tEnd);
		
			printf("NOT cached! Owner=%d, R=%d, MaxAge=%d, CachedAge=%d(%ld.%06ld)\n",
				msg.owner,
				g_Resource1.iCachedResource, 
				g_Resource1.uiMaxAge,
				g_Resource1.uiCachedAge,
				tEnd.tv_sec%1000,	\
				tEnd.tv_usec
				);
		}
		
		//TODO: set client process time
		//setTimeValue(&(msg.client_recved), 0, 0);
		//setTimeValue(&(msg.client_started), 0, 0);
					
		//TODO: set proxy process time
		//setTimeValue(&(msg.proxy_recved), tStart.tv_sec, tStart.tv_usec);
		setTimeValue(&(msg.proxy_started), tStart.tv_sec, tStart.tv_usec);
		setTimeValue(&(msg.proxy_finished), tEnd.tv_sec, tEnd.tv_usec);

		//TODO: send information as response from proxy to client
		int temp = send(msg.iFd, &msg, sizeof(struct __message), 0);

		//TODO: set a new scheduled time of client
		/*
		struct timeval tB;
		tB.tv_sec = client->uiReqInterval/1000;
		tB.tv_usec = (client->uiReqInterval%1000)*1000;
			addTimeValue(&(client->tSched), client->tSched, tB);
		*/
#if 1
	dumpMessage(msg);
#endif
	}
	
	pthread_mutex_unlock(&m_lock);
//printf("---\n");		
	return 0;
}
Exemple #22
0
void initQuda(int dev)
{
  static int initialized = 0;
  if (initialized) {
    return;
  }
  initialized = 1;

#if (CUDA_VERSION >= 4000) && defined(MULTI_GPU)
  //check if CUDA_NIC_INTEROP is set to 1 in the enviroment
  char* cni_str = getenv("CUDA_NIC_INTEROP");
  if(cni_str == NULL){
    errorQuda("Environment variable CUDA_NIC_INTEROP is not set\n");
  }
  int cni_int = atoi(cni_str);
  if (cni_int != 1){
    errorQuda("Environment variable CUDA_NIC_INTEROP is not set to 1\n");    
  }
#endif

  int deviceCount;
  cudaGetDeviceCount(&deviceCount);
  if (deviceCount == 0) {
    errorQuda("No devices supporting CUDA");
  }

  for(int i=0; i<deviceCount; i++) {
    cudaDeviceProp deviceProp;
    cudaGetDeviceProperties(&deviceProp, i);
    printfQuda("QUDA: Found device %d: %s\n", i, deviceProp.name);
  }

#ifdef QMP_COMMS
  int ndim;
  const int *dim;

  if ( QMP_is_initialized() != QMP_TRUE ) {
    errorQuda("QMP is not initialized");
  }
  num_QMP=QMP_get_number_of_nodes();
  rank_QMP=QMP_get_node_number();
  
  dev += rank_QMP % deviceCount;
  ndim = QMP_get_logical_number_of_dimensions();
  dim = QMP_get_logical_dimensions();

#elif defined(MPI_COMMS)

  comm_init();
  dev=comm_gpuid();

#else
  if (dev < 0) dev = deviceCount - 1;
#endif
  
  // Used for applying the gauge field boundary condition
  if( commCoords(3) == 0 ) qudaPt0=true;
  else qudaPt0=false;

  if( commCoords(3) == commDim(3)-1 ) qudaPtNm1=true;
  else qudaPtNm1=false;

  cudaDeviceProp deviceProp;
  cudaGetDeviceProperties(&deviceProp, dev);
  if (deviceProp.major < 1) {
    errorQuda("Device %d does not support CUDA", dev);
  }

  
  printfQuda("QUDA: Using device %d: %s\n", dev, deviceProp.name);

  cudaSetDevice(dev);
#ifdef HAVE_NUMA
  if(numa_config_set){
    if(gpu_affinity[dev] >=0){
      printfQuda("Numa setting to cpu node %d\n", gpu_affinity[dev]);
      if(numa_run_on_node(gpu_affinity[dev]) != 0){
        printfQuda("Warning: Setting numa to cpu node %d failed\n", gpu_affinity[dev]);
      }
    }

  }
#endif

  initCache();
  quda::initBlas();
}
Exemple #23
0
void IndexPage::setFreeCursor(size_t cursor)
{
	initCache();
	cache.writeInt(6, cursor, 2);
	syncFlag = false;
}
Exemple #24
0
static UStringPrepProfile*
usprep_getProfile(const char* path,
                  const char* name,
                  UErrorCode *status){

    UStringPrepProfile* profile = NULL;

    initCache(status);

    if(U_FAILURE(*status)){
        return NULL;
    }

    UStringPrepKey stackKey;
    /*
     * const is cast way to save malloc, strcpy and free calls
     * we use the passed in pointers for fetching the data from the
     * hash table which is safe
     */
    stackKey.name = (char*) name;
    stackKey.path = (char*) path;

    /* fetch the data from the cache */
    umtx_lock(usprepMutex());
    profile = (UStringPrepProfile*) (uhash_get(SHARED_DATA_HASHTABLE,&stackKey));
    if(profile != NULL) {
        profile->refCount++;
    }
    umtx_unlock(usprepMutex());

    if(profile == NULL) {
        /* else load the data and put the data in the cache */
        LocalMemory<UStringPrepProfile> newProfile;
        if(newProfile.allocateInsteadAndReset() == NULL) {
            *status = U_MEMORY_ALLOCATION_ERROR;
            return NULL;
        }

        /* load the data */
        if(!loadData(newProfile.getAlias(), path, name, _SPREP_DATA_TYPE, status) || U_FAILURE(*status) ){
            return NULL;
        }

        /* get the options */
        newProfile->doNFKC = (UBool)((newProfile->indexes[_SPREP_OPTIONS] & _SPREP_NORMALIZATION_ON) > 0);
        newProfile->checkBiDi = (UBool)((newProfile->indexes[_SPREP_OPTIONS] & _SPREP_CHECK_BIDI_ON) > 0);

        LocalMemory<UStringPrepKey> key;
        LocalMemory<char> keyName;
        LocalMemory<char> keyPath;
        if( key.allocateInsteadAndReset() == NULL ||
            keyName.allocateInsteadAndCopy(static_cast<int32_t>(uprv_strlen(name)+1)) == NULL ||
            (path != NULL &&
             keyPath.allocateInsteadAndCopy(static_cast<int32_t>(uprv_strlen(path)+1)) == NULL)
         ) {
            *status = U_MEMORY_ALLOCATION_ERROR;
            usprep_unload(newProfile.getAlias());
            return NULL;
        }

        umtx_lock(usprepMutex());
        // If another thread already inserted the same key/value, refcount and cleanup our thread data
        profile = (UStringPrepProfile*) (uhash_get(SHARED_DATA_HASHTABLE,&stackKey));
        if(profile != NULL) {
            profile->refCount++;
            usprep_unload(newProfile.getAlias());
        }
        else {
            /* initialize the key members */
            key->name = keyName.orphan();
            uprv_strcpy(key->name, name);
            if(path != NULL){
                key->path = keyPath.orphan();
                uprv_strcpy(key->path, path);
            }
            profile = newProfile.orphan();

            /* add the data object to the cache */
            profile->refCount = 1;
            uhash_put(SHARED_DATA_HASHTABLE, key.orphan(), profile, status);
        }
        umtx_unlock(usprepMutex());
    }

    return profile;
}
Exemple #25
0
int IndexPage::indexCount()
{
	initCache();
	int count = cache.readInt(0, 2);
	return count;
}
Exemple #26
0
size_t IndexPage::indexSpace()
{
	initCache();
	size_t space = cache.readInt(2, 2);
	return space;
}
Exemple #27
0
size_t IndexPage::freeSpace()
{
	initCache();
	size_t space = cache.readInt(4, 2);
	return space;
}
Exemple #28
0
static UStringPrepProfile*
usprep_getProfile(const char* path,
                  const char* name,
                  UErrorCode *status){

    UStringPrepProfile* profile = NULL;

    initCache(status);

    if(U_FAILURE(*status)){
        return NULL;
    }

    UStringPrepKey stackKey;
    /*
     * const is cast way to save malloc, strcpy and free calls
     * we use the passed in pointers for fetching the data from the
     * hash table which is safe
     */
    stackKey.name = (char*) name;
    stackKey.path = (char*) path;

    /* fetch the data from the cache */
    profile = (UStringPrepProfile*) (uhash_get(SHARED_DATA_HASHTABLE,&stackKey));

    if(profile == NULL){
        UStringPrepKey* key   = (UStringPrepKey*) uprv_malloc(sizeof(UStringPrepKey));
        if(key == NULL){
            *status = U_MEMORY_ALLOCATION_ERROR;
            return NULL;
        }
        /* else load the data and put the data in the cache */
        profile = (UStringPrepProfile*) uprv_malloc(sizeof(UStringPrepProfile));
        if(profile == NULL){
            *status = U_MEMORY_ALLOCATION_ERROR;
            uprv_free(key);
            return NULL;
        }

        /* initialize the data struct members */
        uprv_memset(profile->indexes,0,sizeof(profile->indexes));
        profile->mappingData = NULL;
        profile->sprepData   = NULL;
        profile->refCount    = 0;

        /* initialize the  key memebers */
        key->name  = (char*) uprv_malloc(uprv_strlen(name)+1);
        if(key->name == NULL){
            *status = U_MEMORY_ALLOCATION_ERROR;
            uprv_free(key);
            uprv_free(profile);
            return NULL;
        }

        uprv_strcpy(key->name, name);

        key->path=NULL;

        if(path != NULL){
            key->path      = (char*) uprv_malloc(uprv_strlen(path)+1);
            if(key->path == NULL){
                *status = U_MEMORY_ALLOCATION_ERROR;
                uprv_free(key->path);
                uprv_free(key);
                uprv_free(profile);
                return NULL;
            }
            uprv_strcpy(key->path, path);
        }

        /* load the data */
        if(!loadData(profile, path, name, _SPREP_DATA_TYPE, status) || U_FAILURE(*status) ){
            return NULL;
        }

        /* get the options */
        profile->doNFKC            = (UBool)((profile->indexes[_SPREP_OPTIONS] & _SPREP_NORMALIZATION_ON) > 0);
        profile->checkBiDi         = (UBool)((profile->indexes[_SPREP_OPTIONS] & _SPREP_CHECK_BIDI_ON) > 0);

        if(profile->checkBiDi) {
            profile->bdp = ubidi_getSingleton(status);
            if(U_FAILURE(*status)) {
                usprep_unload(profile);
                uprv_free(key->path);
                uprv_free(key);
                uprv_free(profile);
                return NULL;
            }
        } else {
            profile->bdp = NULL;
        }

        umtx_lock(&usprepMutex);
        /* add the data object to the cache */
        uhash_put(SHARED_DATA_HASHTABLE, key, profile, status);
        umtx_unlock(&usprepMutex);
    }
    umtx_lock(&usprepMutex);
    /* increment the refcount */
    profile->refCount++;
    umtx_unlock(&usprepMutex);

    return profile;
}
Exemple #29
0
size_t IndexPage::freeCursor()
{
	initCache();
	size_t cursor = cache.readInt(6, 2);
	return cursor;
}
void *pthreadWatchResource(void *arg)
{
	struct timeval timeSched;
	struct timeval tStart;
			
	while(!g_iExit)
	{
		if(g_Resource1.iClientNumber)
		{
			//TODO: get current time
			//gettimeofday(&tStart, NULL);

			//TODO: search all clients registered
			struct __client *client = g_Resource1.next;
			while(client)
			{
				gettimeofday(&tStart, NULL);

				//TODO: find scheduled client
				if(isBiggerThan(tStart, client->tSched))
				{
					struct __message msg;
					struct timeval tEnd;

					//TODO: if cached resource is valid, then use it
					if(g_uiCacheMode && isCachedDataValid(tStart) )
					{
						//TODO: update cache timing information
						updateCache(tStart);
						
						//TODO: set server process time with zero
						setTimeValue(&(msg.server_recved), 0, 0);
						setTimeValue(&(msg.server_started), 0, 0);
						setTimeValue(&(msg.server_finished), 0, 0);
						
						//TODO: set message with time information		
						msg.resource = g_Resource1.iCachedResource;
						msg.uiMaxAge = g_Resource1.uiMaxAge - g_Resource1.uiCachedAge;
						//printf("%s:uiMaxAge=%d(%d-%d)\n", __func__, msg.uiMaxAge, g_Resource1.uiMaxAge, g_Resource1.uiCachedAge);	
						
						//TODO: get current time
						gettimeofday(&tEnd, NULL);
					}
					else
					{
						//TODO: init cache
						initCache();
						
						//TODO: get a fresh resource from a server
						getResourceFromServer(&msg);
						
						//TODO: get current time
						gettimeofday(&tEnd, NULL);
					
						//TODO: set cached with information
						setCache(msg, tEnd);
					}
					
					//TODO: set client process time
					setTimeValue(&(msg.client_recved), 0, 0);
					setTimeValue(&(msg.client_started), 0, 0);
					
					//TODO: set proxy process time
					setTimeValue(&(msg.proxy_recved), tStart.tv_sec, tStart.tv_usec);
					setTimeValue(&(msg.proxy_started), tStart.tv_sec, tStart.tv_usec);
					setTimeValue(&(msg.proxy_finished), tEnd.tv_sec, tEnd.tv_usec);

					//TODO: dump message
					dumpMessage(msg);
					
					//TODO: send information as response from proxy to client
					int temp = send(client->iFd, &msg, sizeof(struct __message), 0);
					
					//TODO: set a new scheduled time of client
					struct timeval tB;
					tB.tv_sec = client->uiReqInterval/1000;
					tB.tv_usec = (client->uiReqInterval%1000)*1000;
					addTimeValue(&(client->tSched), client->tSched, tB);
					
//printf("tStart=%ld.%06ld, tSched=%ld.%06ld\n", 
//	tStart.tv_sec, tStart.tv_usec,
//	client->tSched.tv_sec, client->tSched.tv_usec);
				}
				client = client->next;
//printf("%s:client=0x%x\n", __func__, (unsigned int)client);
			}
			
			//TODO: inser client node as time sequence
			//updateClient();
			
			//TODO: 
			if(g_uiCacheAlgorithm == 1)
			{
				if(isBiggerThan(tStart, g_Resource1.tBaseTime))
				{
					//TODO: update check point
					updateBaseTime();
				}
			}
			else if(g_uiCacheAlgorithm == 2)
			{
				struct timeval tCPaddMA; 
				struct timeval tMaxAge; 
				setTimeValue(&tMaxAge, g_Resource1.uiMaxAge/1000, (g_Resource1.uiMaxAge%1000)*1000);
				addTimeValue(&tCPaddMA, g_Resource1.tBaseTime, tMaxAge);				
				if(isBiggerThan(tStart, tCPaddMA))
				{
					setSchedule(tStart);
				}
			}			
			
			usleep(5*1000);
		}	//if(g_Resource1.iClientNumber)
		
		usleep(50*1000);
	}
		
	return NULL;
}