Ejemplo n.º 1
0
int find(poly_t *p, double r[])
{
	int k;

	while (p->n > 0 && iszero(p->a[p->n]))
		p->n--;

	if (p->n == 0) {
		r[0] = 0;
		return 1;
	}

	if (p->n == 1) {
		r[0] = -(p->a[0] / p->a[1]);
		return 1;
	}

	if (p->n == 2) {
		double t;

		t = p->a[1] * p->a[1] - 4. * p->a[0] * p->a[2];
		t = (t < 0.) ? 0. : sqrt(t);

		r[0] = (-p->a[1] + t) / (2. * p->a[2]);
		r[1] = (-p->a[1] - t) / (2. * p->a[2]);
		return 2;
	}

	if ((k = bis(p, r)) > 0)
		return k;

	return 0;
}
Ejemplo n.º 2
0
int main(int argc,char** argv){
  if (argc!=4)
  {
    std::cerr << "Usage: " << argv[0] << " -estremo a- -estremo b- -precisione-"<<std::endl;
    return -1;
  }
  int npassi = 300;
  double a=atof(argv[1]);
  double b=atof(argv[2]);
  double prec=atof(argv[3]);
  if(a>b){
   double c=a;
   a=b;
   b=c;
  }
  Parabola p(3,5,-2);
  Retta r(1, 1);

  Bisezione bis(npassi);
  double zero=bis.Precision(prec).CercaZeri(a,b,&p);
  if(bis.Trovato()) 
  {
    std::cout << "Zero trovato in: " << std::fixed << std::setprecision(-log10(prec)) << zero << std::endl;
    std::cout << "in " << bis.Steps() << " passi, con un'incertezza di ±" << bis.Incertezza() << std::endl;
    std::cout << "la precisione richiesta era " << prec  << std::endl;
  } else 
    std::cerr << "Non è stato possibile trovare uno zero con la precisione richiesta" << std::endl;
    
  return 0;
}
Ejemplo n.º 3
0
void
MSDevice_Tripinfo::loadState(const SUMOSAXAttributes& attrs) {
    std::istringstream bis(attrs.getString(SUMO_ATTR_STATE));
    bis >> myDepartLane;
    bis >> myDepartPosLat;
    bis >> myDepartSpeed;
}
Ejemplo n.º 4
0
void testPLWAH1_2()
{
	vector<vector<int>> sets(SETNUM);
	int n = dataGen_2(sets);
#ifdef TIMING_FOR_PLWAH1
	clock_t t1,t2,t3,t4;
#endif
	vector<PLWAH1Set> bis(SETNUM);
	for(int i=0;i<SETNUM;i++){
		bis[i].fromVector(sets[i]);
	}
	vector<int> res;


#ifdef TIMING_FOR_PLWAH1
	t3 = clock();
#endif

	PLWAH1Set::intersection(bis,res);

#ifdef TIMING_FOR_APLWAH
	t4 = clock();
	printf("PLWAH1 Intersection:\n%d Sets, each with %d numbers, Step %d\nResult: %d numbers.\nIntersection Time: %d\n\n",SETNUM,INTNUM,STEP,res.size(),t4-t3);
#endif

#ifdef NUM_LIST
	printf("Intersection: ");
	int max = NUM_LIST < res.size()?NUM_LIST:res.size();
	for(int i=0;i<max;i++){
		printf(" %d",res[i]);
	}
#endif
}
Ejemplo n.º 5
0
int main(int argc, char* argv[])
{
	// read the file
	std::ifstream ifs(argv[1], std::ios::binary);
	std::string buffer((std::istreambuf_iterator<char>(ifs)),
				(std::istreambuf_iterator<char>()));

	if (!buffer.size()) {
		std::ofstream ofs(argv[2], std::ios::binary);
		exit(0);
	}

	// make Stream
	std::stringstream ss(buffer);
	BitInputStream bis(ss);

	// build tree
	HCTree hct;
	hct.build(bis.frequences);
	bis.size = getSize(hct, bis.frequences);

	std::ofstream ofs(argv[2], std::ios::binary);

	// decode 
	int c = hct.decode(bis);
	int i = 0;
	while (c >= 0) {
		ofs << (byte)c;
		c = hct.decode(bis);
	}

	return 0;
}
Ejemplo n.º 6
0
/*
 * Fill up caching arrays for path and cdpath
 */
void
dohash(char cachearray[])
{
	struct stat stb;
	DIR *dirp;
	struct dirent *dp;
	int cnt;
	int i = 0;
	struct varent *v;
	tchar **pv;
	int hashval;
	tchar curdir_[MAXNAMLEN+1];

#ifdef TRACE
	tprintf("TRACE- dohash()\n");
#endif
	/* Caching $path */
	if (cachearray == xhash) {
		havhash = 1;
		v = adrof(S_path /* "path" */);
	} else {    /* Caching $cdpath */
		havhash2 = 1;
		v = adrof(S_cdpath /* "cdpath" */);
	}

	for (cnt = 0; cnt < (HSHSIZ / 8); cnt++)
		cachearray[cnt] = 0;
	if (v == 0)
		{
		return;
		}
	for (pv = v->vec; *pv; pv++, i++) {
		if (pv[0][0] != '/')
			continue;
		dirp = opendir_(*pv);
		if (dirp == NULL)
			continue;
		if (fstat(dirp->dd_fd, &stb) < 0 || !isdir(stb)) {
			unsetfd(dirp->dd_fd);
			closedir_(dirp);
			continue;
		}
		while ((dp = readdir(dirp)) != NULL) {
			if (dp->d_ino == 0)
				continue;
			if (dp->d_name[0] == '.' &&
			    (dp->d_name[1] == '\0' ||
			    dp->d_name[1] == '.' && dp->d_name[2] == '\0'))
				continue;
			hashval = hash(hashname(strtots(curdir_, dp->d_name)), i);
			bis(cachearray, hashval);
		}
		unsetfd(dirp->dd_fd);
		closedir_(dirp);
	}
}
Ejemplo n.º 7
0
 void protein_load_truth_data_from_file(std::string fname,
                     protein_truth_asg_type& truth_asgs) {
   binary_input_stream bis(fname.c_str());
   size_t num_vertices = bis.read<int>();
   truth_asgs.resize(num_vertices);
   foreach(protein_asg_set_type& asgs, truth_asgs) {
     size_t valid_assignments = bis.read<int>();
     assert(valid_assignments > 0);
     for(size_t i = 0; i < valid_assignments; ++i) {
       size_t asg = bis.read<int>();
       asgs.insert(asg);
     }
   }
int main( int argc, char *argv[] ) {
    if( argc != 3 ) {
        cerr << "Invalid number of arguments.\n";
        return EXIT_FAILURE;
    }

    ifstream fin;
    ofstream fout;

    fin.open( argv[1], ios::binary );

    /* Check to see if the input file opened correctly. */
    if( !fin.is_open() ) {
        return EXIT_FAILURE;
    }

    vector<int> freqs( 256, 0 );
    int fsize = 0;
    HCTree hufftree;

    fin.clear();


    /* Read in the header. */
    for( size_t i = 0; i < freqs.size(); ++i ) {
        fin.read( (char *) &freqs[i], sizeof( int ) );
        fsize += freqs[i];
    }

    /* Build the Huffman tree. */
    if( fsize != 0 ) {
        hufftree.build( freqs );
    }

    fout.open( argv[2], ios::binary );
    
    BitInputStream bis( fin );

    byte tmp = 0;  

    for( int i = 0; i < fsize; ++i ) {
        tmp = hufftree.decode( bis );
        fout.write( (char *) &tmp, 1);
    } 

    fin.close();
    fout.close();

    return EXIT_SUCCESS;
}
Ejemplo n.º 9
0
int main(int argc,char** argv){
double prec = 1e-6;
Buca bu(0);
FunzioneBase* t = &(bu);
Bisezione bis(3000);
bis.Precision(prec);
double a, b, zero;
for (int i=0;i<21;++i){
	a=i*M_PI;
	b=i*M_PI+M_PI/2;
	zero = bis.CercaZeri(a,b,&bu);
	std::cout << std::fixed << "Zero trovato: " << std::setprecision(-log10(prec)) << zero << " nell'intervallo ["<<a<<","<<b<<"]"<<std::endl;
}

return 0;
}
Ejemplo n.º 10
0
void PopPredict::LoadModel() {
    Log::I("recsys", "PopPredict::LoadModel()");
    BinaryInputStream bis(mModelFilepath);
    int numItem;
    bis >> numItem;
    assert(numItem == mTrainData->NumItem());
    mItemAverages.resize(numItem);
    bis.Read(mItemAverages.data(), mItemAverages.size());
    mItemPopularities.resize(numItem);
    bis.Read(mItemPopularities.data(), mItemPopularities.size());
    int numUser;
    bis >> numUser;
    assert(numUser == mTrainData->NumUser());
    mUserAverages.resize(numUser);
    bis.Read(mUserAverages.data(), mUserAverages.size());
}
Ejemplo n.º 11
0
void robust::solve(real a, real b){
		real tol_bis = cfratio * tol;
		
		bisection bis(f,tol_bis,maxit/2,criteria);
		bis.solve(a,b);
		real x_d=bis.get_result();
		
		newton nwt(f,fprime,tol,maxit/2,criteria);
		nwt.solve(x_d);
		alpha=nwt.get_result();
		done=true;
		
		nit_coarse=bis.get_iter();
		nit=nwt.get_iter();
		return;
}
Ejemplo n.º 12
0
/*----------------------------------------------------------------------
|       main
+---------------------------------------------------------------------*/
int
main(int /*argc*/, char** /*argv*/)
{
    // setup debugging
#if defined(_DEBUG) && defined(WIN32)
    int flags = _crtDbgFlag       | 
        _CRTDBG_ALLOC_MEM_DF      |
        _CRTDBG_DELAY_FREE_MEM_DF |
        _CRTDBG_CHECK_ALWAYS_DF;

    _CrtSetDbgFlag(flags);
    //AllocConsole();
    //freopen("CONOUT$", "w", stdout);
#endif 

#if 0
    const char* b0 = "";
    const char* b1 = "\n";
    const char* b2 = "\r";
    const char* b3 = "\r\n";
    const char* b4 = "0\r1\r\r2\r\r\r"       // only \r, up to 3
                     "3\n4\n\n5\n\n\n"       // only \n, up to 3
                     "6\r\n7\n\r"            // one \r and one \n
                     "8\r\n\r9\r\r\na\n\r\r" // two \r and one \n
                     "b\n\r\nc\n\n\rd\r\n\n" // two \n and one \r
                     ;
    const char* b5 = "aaa\r";
    const char* b6 = "aaa\n";
    const char* b7 = "aaa\r\n";

    printf("BufferedInputStream test1 passed\n");
#endif

    NPT_InputStreamReference isr1(new NPT_MemoryStream("0123456789", 10));
    NPT_BufferedInputStream bis(isr1, 3);
    char buffer[256];
    NPT_Result result = bis.ReadLine(buffer, 2);
    CHECK(result == NPT_ERROR_NOT_ENOUGH_SPACE);
    
    return 0;
}
Ejemplo n.º 13
0
void
/*ARGSUSED*/
dohash(Char **v, struct command *t)
{
    struct dirent *dp;
    struct varent *pathv;
    DIR *dirp;
    Char **pv;
    size_t cnt;
    int hashval, i;

    i = 0;
    havhash = 1;
    pathv = adrof(STRpath);

    for (cnt = 0; cnt < sizeof xhash; cnt++)
	xhash[cnt] = 0;
    if (pathv == 0)
	return;
    for (pv = pathv->vec; *pv; pv++, i++) {
	if (pv[0][0] != '/')
	    continue;
	dirp = opendir(short2str(*pv));
	if (dirp == NULL)
	    continue;
	while ((dp = readdir(dirp)) != NULL) {
	    if (dp->d_ino == 0)
		continue;
	    if (dp->d_name[0] == '.' &&
		(dp->d_name[1] == '\0' ||
		 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
		continue;
	    hashval = hash(hashname(str2short(dp->d_name)), i);
	    bis(xhash, hashval);
	    /* tw_add_comm_name (dp->d_name); */
	}
	(void) closedir(dirp);
    }
}
Ejemplo n.º 14
0
int main()
{
	int x = 0x98FDECBA;

	int temp = x;	
	mask_height_bit((byte_pointer)&temp, sizeof(x));
	printf("reset all bit without least:%x\n", temp);

	int temp1 = x;
	complement_least((byte_pointer)&temp1);
	printf("complement least without other:%x\n", temp1);

	int temp2 = x;
	reset_least((byte_pointer)&temp2);
	printf("reset least bit without other:%x\n", temp2);

	int temp3 = bis(0x0000000, 31);
	printf("0 after bis operator:%08x\n", temp3);

	
	int temp4 = bic(0x80000000, 31);
	printf("0 after bic operator:%08x\n", temp4);
	return 0;
}
Ejemplo n.º 15
0
NDIS_STATUS
xmpSetInformation(
  IN xmpNicCtx_t             *pNicCtx,
  IN PNDIS_OID_REQUEST       NdisRequest
  )
{
  NDIS_STATUS                 Status = NDIS_STATUS_SUCCESS;
  NDIS_OID                    Oid;
  PVOID                       InformationBuffer;
  ULONG                       InformationBufferLength;
  ULONG                       BytesRead;
  ULONG                       BytesNeeded;
  ULONG                       PacketFilter;
  ULONG                       MCastCnt;
  ULONG                       HashType;
  ULONG                       validBits;
  USHORT                      i;
  xge_hal_device_t           *pHalDev;
  NDIS_RECEIVE_SCALE_PARAMETERS *pRssParam;
  xmpSetRssContext			      SetRssCtx = {0};
  static ULONG setRssCount = 10;

  pHalDev = XMP_NIC_GET_DEV(pNicCtx);
  Oid = NdisRequest->DATA.SET_INFORMATION.Oid;
  InformationBuffer = NdisRequest->DATA.SET_INFORMATION.InformationBuffer;
  InformationBufferLength = 
    NdisRequest->DATA.SET_INFORMATION.InformationBufferLength;

  XMPTRACE(XMP_DBG_REQ, ("==> xmpSetInformation %x\n", Oid));
  BytesRead = 0;
  BytesNeeded = 0;

  switch(Oid)
  {
  case OID_802_3_MULTICAST_LIST:
    XMPTRACE(XMP_DBG_REQ, ("xmpSetInformation Multicast list\n"));
    if ( InformationBufferLength % ETH_LENGTH_OF_ADDRESS != 0 )
      return(NDIS_STATUS_INVALID_LENGTH);

    MCastCnt = InformationBufferLength / ETH_LENGTH_OF_ADDRESS;
    xmpHalMcastFilterClr(pNicCtx);
    Status = xmpHalSetMcastList(pNicCtx,
                                (UCHAR *) InformationBuffer,
                                &MCastCnt);
    BytesRead = MCastCnt * ETH_LENGTH_OF_ADDRESS;
    break;

  case OID_GEN_CURRENT_PACKET_FILTER:
    XMPTRACE(XMP_DBG_REQ, ("xmpSetInformation: packet filter\n"));
    if ( InformationBufferLength != sizeof (ULONG) )
      return ( NDIS_STATUS_INVALID_LENGTH );

    BytesRead = InformationBufferLength;
    PacketFilter = *((PULONG) InformationBuffer);
    Status = xmpSetFilter(pNicCtx, PacketFilter);
    break;

  case OID_GEN_CURRENT_LOOKAHEAD:
    XMPTRACE(XMP_DBG_REQ, ("xmpSetInformation: current lookahead\n"));
    if( InformationBufferLength < sizeof(ULONG) )
    {
      BytesNeeded = sizeof(ULONG);
      Status = NDIS_STATUS_INVALID_LENGTH;
      break;
    }
    pNicCtx->LookAheadSz = *((PULONG) InformationBuffer);
    BytesRead = sizeof(ULONG);
    Status = NDIS_STATUS_SUCCESS;
    break;

  case OID_GEN_RECEIVE_SCALE_PARAMETERS:

    XMPTRACE(XMP_DBG_INFO, ("xmpSetInformation: OID_GEN_RECEIVE_SCALE_PARAMETERS\n"));
    if ( !(XMP_NIC_RSS_IN_CONFIG(pNicCtx)) )
    {
      Status = NDIS_STATUS_NOT_SUPPORTED;
      break;
    }

    if ( InformationBufferLength < sizeof(NDIS_RECEIVE_SCALE_PARAMETERS) )
    {
      BytesNeeded = sizeof(NDIS_RECEIVE_SCALE_PARAMETERS);
      Status = NDIS_STATUS_INVALID_LENGTH;
      break;
    }
    pRssParam = (PNDIS_RECEIVE_SCALE_PARAMETERS)InformationBuffer;

#ifdef NDISTEST_BUG
    if ( !XENAMP_NDIS_OBJECT_VALID(&pRssParam->Header,
                                   NDIS_RECEIVE_SCALE_PARAMETERS_REVISION_1,
                                   NDIS_OBJECT_TYPE_RSS_PARAMETERS,
                                   sizeof(NDIS_RECEIVE_SCALE_PARAMETERS)) )
    {
      XMPTRACE(XMP_DBG_WRN, ("xmpSetInformation:RSS_PARAMETERS invalid!!"       
                             " Revision=%d Type=%d Size=%d\n",
                             pRssParam->Header.Revision,
                             pRssParam->Header.Type,
                             pRssParam->Header.Size));
      BytesRead = sizeof(NDIS_OBJECT_HEADER);
      Status = NDIS_STATUS_INVALID_PARAMETER;
      break;
    }
#endif

    BytesRead = sizeof(NDIS_RECEIVE_SCALE_PARAMETERS);

    if ( (InformationBufferLength < (pRssParam->IndirectionTableSize
                                     + pRssParam->IndirectionTableOffset)) ||
         (InformationBufferLength < (pRssParam->HashSecretKeySize
                                     + pRssParam->HashSecretKeyOffset)) )
    {
      BytesNeeded = sizeof(NDIS_RECEIVE_SCALE_PARAMETERS);
      Status = NDIS_STATUS_INVALID_LENGTH;
      break;
    }

    HashType = NDIS_RSS_HASH_TYPE_FROM_HASH_INFO(pRssParam->HashInformation);   
    /*if ( HashType != 0 || NDIS_RSS_HASH_FUNC_FROM_HASH_INFO(pRssParam->HashInformation) != 0) */
    validBits = (NDIS_HASH_IPV4 | NDIS_HASH_TCP_IPV4
#ifndef XMP_RSS_IPV4_ONLY
                 | NDIS_HASH_IPV6 | NDIS_HASH_TCP_IPV6
                 | NDIS_HASH_IPV6_EX | NDIS_HASH_TCP_IPV6_EX
#endif
                 );
    if ( ((NDIS_RSS_HASH_FUNC_FROM_HASH_INFO(pRssParam->HashInformation) !=
           NdisHashFunctionToeplitz) ||  /* the only hash function supported */
          !bit(HashType, validBits) ||    /* at least one type should be set */
          (HashType & ~validBits)) &&         /* no other type should be set */
         (!(bit(pRssParam->Flags, NDIS_RSS_PARAM_FLAG_DISABLE_RSS)) &&
          NDIS_RSS_HASH_FUNC_FROM_HASH_INFO(pRssParam->HashInformation) != 0) )
    {
      Status = NDIS_STATUS_INVALID_PARAMETER;
      break;
    }

    if ( /*(pRssParam->IndirectionTableSize < (1 << pRssParam->NumberOfLsbs)) || */
         (pRssParam->HashSecretKeySize & 0x7) ||    /* must be 8-bytes align */
         (pRssParam->HashSecretKeySize > 40)  ||      /* max secret key size */
         (pRssParam->BaseCpuNumber & (pRssParam->BaseCpuNumber - 1)) )/*pow2 */
    {
      XMPTRACE(XMP_DBG_WRN, ("xmpReqSetRss:Invalid settings: Key Size=%d"
                             " IDT size=%d BaseCpu=%d\n",
                             pRssParam->HashSecretKeySize,
                             pRssParam->IndirectionTableSize,
                             pRssParam->BaseCpuNumber));
      Status = NDIS_STATUS_INVALID_PARAMETER;
      break;
    }


    if ((pRssParam->IndirectionTableSize + pRssParam->IndirectionTableOffset) >
        (pRssParam->HashSecretKeySize + pRssParam->HashSecretKeyOffset))
      BytesRead = (pRssParam->IndirectionTableSize + 
                    pRssParam->IndirectionTableOffset);
    else
      BytesRead = (pRssParam->HashSecretKeySize +
                    pRssParam->HashSecretKeyOffset);

    SetRssCtx.pNicCtx = pNicCtx;
    SetRssCtx.pParams = pRssParam;

#if 0
    if(NdisMSynchronizeWithInterruptEx(pNicCtx->hInterrupt, 0, xmpReqSetRss, &SetRssCtx))
#endif
    if ( NDIS_RSS_HASH_FUNC_FROM_HASH_INFO(pRssParam->HashInformation) == 0 )
      bis(pRssParam->Flags, NDIS_RSS_PARAM_FLAG_DISABLE_RSS);

    if ( bit(pRssParam->Flags, NDIS_RSS_PARAM_FLAG_DISABLE_RSS) )
    {
      pNicCtx->ndisRssSet.size = sizeof(NDIS_RECEIVE_SCALE_PARAMETERS);
      pNicCtx->ndisRssSet.params.BaseCpuNumber          = 0;
      pNicCtx->ndisRssSet.params.Flags                  = 0;
      pNicCtx->ndisRssSet.params.HashInformation        = 0;
      pNicCtx->ndisRssSet.params.IndirectionTableSize   = 0;
      pNicCtx->ndisRssSet.params.IndirectionTableOffset = 0;
      pNicCtx->ndisRssSet.params.HashSecretKeySize      = 0;
      pNicCtx->ndisRssSet.params.HashSecretKeyOffset    = 0;
    }
    else
    {
      NdisMoveMemory(&pNicCtx->ndisRssSet.params, pRssParam, BytesRead);
      pNicCtx->ndisRssSet.size = BytesRead;
    }

      xmpReqSetRss(pNicCtx);
#if 0
    if ( !(setRssCount % 10) )
    {
      xmpReqSetRss(pNicCtx);
    }
    setRssCount++;
#endif
    Status = NDIS_STATUS_SUCCESS;
    break;

  case OID_OFFLOAD_ENCAPSULATION:
    XMPTRACE(XMP_DBG_OFLD, ("xmpSetInformation: offload encapsulation\n"));
    if ( InformationBufferLength < sizeof(NDIS_OFFLOAD_ENCAPSULATION) )
    {
      BytesNeeded = sizeof(NDIS_OFFLOAD_ENCAPSULATION);
      Status = NDIS_STATUS_INVALID_LENGTH;
      break;
    }

    NdisMoveMemory(&pNicCtx->OffloadEncapsulation,
                   InformationBuffer,
                   sizeof(NDIS_OFFLOAD_ENCAPSULATION));
    BytesRead = sizeof(NDIS_OFFLOAD_ENCAPSULATION);
    Status    = NDIS_STATUS_SUCCESS;
    break;

  case OID_GEN_INTERRUPT_MODERATION:
    {
      NDIS_INTERRUPT_MODERATION_PARAMETERS *pIntrModr;
      if ( InformationBufferLength < sizeof(NDIS_INTERRUPT_MODERATION_PARAMETERS) )
      {
        BytesNeeded = sizeof(NDIS_INTERRUPT_MODERATION_PARAMETERS);
        Status = NDIS_STATUS_INVALID_LENGTH;
        break;
      }
      pIntrModr  = (NDIS_INTERRUPT_MODERATION_PARAMETERS *) InformationBuffer;
      if ( !XENAMP_NDIS_OBJECT_VALID(&pIntrModr->Header,
                                 NDIS_INTERRUPT_MODERATION_PARAMETERS_REVISION_1,
                                 NDIS_OBJECT_TYPE_DEFAULT,
                                 sizeof(NDIS_INTERRUPT_MODERATION_PARAMETERS)) )
      {
        BytesRead = sizeof(NDIS_OBJECT_HEADER);
        Status = NDIS_STATUS_INVALID_DATA;
        break;
      }
     break;
    }

  case OID_TCP_OFFLOAD_PARAMETERS:
    {
      NDIS_OFFLOAD_PARAMETERS *pAdmin;
      NDIS_STATUS_INDICATION  StatusIndication;
      ULONG size;

      pAdmin  = (NDIS_OFFLOAD_PARAMETERS *) InformationBuffer;
  
      if ( InformationBufferLength < NDIS_SIZEOF_OFFLOAD_PARAMETERS_REVISION_1 )
      {
        BytesNeeded = NDIS_SIZEOF_OFFLOAD_PARAMETERS_REVISION_1;
        Status = NDIS_STATUS_INVALID_LENGTH;
        break;
      }

      if ( !XENAMP_NDIS_OBJECT_VALID(&pAdmin->Header,
                                     NDIS_OFFLOAD_PARAMETERS_REVISION_1,
                                     NDIS_OBJECT_TYPE_DEFAULT,
                                     NDIS_SIZEOF_OFFLOAD_PARAMETERS_REVISION_1 ))
      {
        BytesRead = sizeof(NDIS_OBJECT_HEADER);
        Status = NDIS_STATUS_INVALID_DATA;
        break;
      }

      XMP_NIC_SET_ADMIN_OFFLOADS(pNicCtx, pAdmin);
      xmpNicSetCkoFlags(pNicCtx);
      xmpNicInitOffloadCapabilities(pNicCtx, &pNicCtx->OffloadCapabilities);    
       /* TODO: Generate event */
      BytesRead = NDIS_SIZEOF_OFFLOAD_PARAMETERS_REVISION_1;
      Status    = NDIS_STATUS_SUCCESS;

      XENAMP_NDIS_OBJECT_INIT(&StatusIndication.Header,
         NDIS_OBJECT_TYPE_STATUS_INDICATION,
         NDIS_STATUS_INDICATION_REVISION_1,
         sizeof(NDIS_STATUS_INDICATION));

      StatusIndication.SourceHandle = pNicCtx->hMPAdapter;
      StatusIndication.PortNumber = 0;
      StatusIndication.StatusCode = NDIS_STATUS_TASK_OFFLOAD_CURRENT_CONFIG;
      StatusIndication.Flags = 0;
      StatusIndication.DestinationHandle = NULL;
      StatusIndication.RequestId = NdisRequest->RequestId;
      StatusIndication.StatusBuffer = &pNicCtx->OffloadCapabilities;
      StatusIndication.StatusBufferSize = sizeof(NDIS_OFFLOAD);
      NdisMIndicateStatusEx(pNicCtx->hMPAdapter, &StatusIndication);
    }
    break;
    
  case OID_GEN_HD_SPLIT_PARAMETERS:
     {
       NDIS_HD_SPLIT_PARAMETERS *pHdSplit;
    
       pHdSplit  = (NDIS_HD_SPLIT_PARAMETERS *) InformationBuffer;
       if ( InformationBufferLength < NDIS_SIZEOF_HD_SPLIT_PARAMETERS_REVISION_1 )
       {
         BytesNeeded = NDIS_SIZEOF_HD_SPLIT_PARAMETERS_REVISION_1;
         Status = NDIS_STATUS_INVALID_LENGTH;
         break;
       }

       if ( !XENAMP_NDIS_OBJECT_VALID(&pHdSplit->Header,
                                    NDIS_HD_SPLIT_PARAMETERS_REVISION_1,
                                    NDIS_OBJECT_TYPE_DEFAULT,                                     
                                    NDIS_SIZEOF_HD_SPLIT_PARAMETERS_REVISION_1 ))
       {
         BytesRead = sizeof(NDIS_OBJECT_HEADER);
         Status = NDIS_STATUS_INVALID_DATA;
         break;
       }
      
       if( bit(pHdSplit->HDSplitCombineFlags, NDIS_HD_SPLIT_COMBINE_ALL_HEADERS) ) 
         bis( pNicCtx->Flags, XMP_NIC_FLAGS_RX_SPLIT_COMBINE ); 
       else
         bic( pNicCtx->Flags, XMP_NIC_FLAGS_RX_SPLIT_COMBINE ); 
    }
    break;

  default:
    XMPTRACE(XMP_DBG_INFO, ("xmpSetInformation: unsupported OID=%lx\n", Oid));
    Status = xmpDiagSetInformation(
                                   pNicCtx, 
                                   Oid, 
                                   InformationBuffer, 
                                   InformationBufferLength,
                                   &BytesRead,
                                   &BytesNeeded);
    break;
  }

  NdisRequest->DATA.SET_INFORMATION.BytesRead = BytesRead;
  NdisRequest->DATA.SET_INFORMATION.BytesNeeded = BytesNeeded;

  XMPTRACE(XMP_DBG_REQ, ("<== xmpSetInformation: Status=%x\n", Status));
  return Status;
}
Ejemplo n.º 16
0
void ana_network_manager::handle_receive( ana::error_code          error,
                                          ana::net_id              client,
                                          ana::read_buffer buffer)
{
    if (error)
        network::disconnect( client );
    else
    {
        std::set< ana_component* >::iterator it;

        it = std::find_if( components_.begin(), components_.end(),
                            boost::bind(&ana_component::get_id, _1) == client );

        if ( it != components_.end() )
            (*it)->add_buffer( buffer, client );
        else
        {
            if (components_.empty() )
                throw std::runtime_error("Received a message while no component was running.\n");

            std::map< ana::server*, clients_manager* >::iterator mgrs;

            for ( mgrs = server_manager_.begin(); mgrs != server_manager_.end(); ++mgrs)
            {
                if (mgrs->second->is_a_client( client ) ) // Is this your client?
                {
                    if ( mgrs->second->is_pending_handshake( client ) ) // Did he login already?
                    {
                        // all handshakes are 4 bytes long
                        if ( buffer->size() != sizeof(ana::ana_uint32) )
                            mgrs->first->disconnect( client );

                        ana::ana_uint32 handshake;
                        {
                            ana::serializer::bistream bis( buffer->string() );

                            bis >> handshake;
                            ana::network_to_host_long( handshake ); //I'm expecting a 0 anyway
                        }

                        if ( handshake != 0 )
                            mgrs->first->disconnect( client );
                        else
                        {
                            mgrs->second->handshaked( client );
                            //send back it's id
                            ana::serializer::bostream bos;
                            ana::ana_uint32 network_byte_order_id = client;
                            ana::host_to_network_long( network_byte_order_id );
                            bos << network_byte_order_id;

                            ana_handshake_finisher_handler* handler
                                = new ana_handshake_finisher_handler( mgrs->first,
                                                                      mgrs->second);

                            mgrs->first->send_one(client, ana::buffer( bos.str() ), handler );
                            mgrs->first->set_header_first_mode( client );
                        }
                    }
                    else // just add the buffer to the associated clients_manager
                    {
                        ana::net_id server_id = mgrs->first->id();

                        it = std::find_if( components_.begin(), components_.end(),
                                        boost::bind(&ana_component::get_id, _1) == server_id );

                        if ( (*it)->is_client() )
                            throw std::runtime_error("Wrong id to receive from.");

                        (*it)->add_buffer( buffer, client );
                    }
                }
            }
        }
    }
Ejemplo n.º 17
0
/* Compute x&y using only calls to functions bis and bic */
int bool_and(int x, int y)
{
    int result = bic(bis(x, y), bis(bic(x, y), bic(y, x)));
    return result;
}
Ejemplo n.º 18
0
  bool parse_protein(universe& universe,
                     factor_graph_model<F>& fg,
                     const std::string& filename) {

    typedef typename factor_graph_model<F>::variable_type variable_type;

    binary_input_stream bis(filename.c_str());
    size_t  numvars = bis.read<int32_t>();
    size_t  numedges = bis.read<int32_t>();
    if (bis.fail()) return false;
    std::vector<variable_type*> idtovar;
    idtovar.resize(numvars);
    // ignore the next 2 * num_edges * int32_t bytes
    // this will contain the list of edges which we do not need
    // we can construct this from the factors later on
    bis.seekg(2 * numedges * sizeof(int32_t), std::ios_base::cur);
    if (bis.fail()) return false;
    // this will now be the node potentials
    for (size_t i = 0;i < numvars; ++i) {
      // will be nice if the node potentials are given to me in numerical order
      // but I certainly can't guarantee that given the file format
      size_t  varid = bis.read<int32_t>();
      size_t  cardinality = bis.read<int32_t>();
      if (bis.fail()) return false;
      if (cardinality <= 0) return false;
      // create the variable
      //char temp[16]; sprintf(temp,"%d", varid);
      std::stringstream varname;
      varname << varid;
      variable_type* var = universe.new_finite_variable(varname.str(), cardinality);
      idtovar[varid] = var;

      // create the factor
      F factor(make_domain(var), 0.0);
      for (size_t asg = 0; asg < cardinality; ++asg) {
        factor.set_logv(asg, proteinparsing::bound_infinity(bis.read<double>()));
      }
      factor.normalize();
      fg.add_factor(factor);
    }

    // this will now be the edge potentials
    size_t table_count = bis.read<int32_t>();
    if (bis.fail()) return false;
    // this may or may not be equal to num_edges depending on whether
    // both edge directions were counted... so lets not check that
    if(! (table_count == numedges || table_count == numedges / 2)) {
      return false;
    }
      // read the binary factors
    for (size_t  i = 0;i < table_count; ++i) {
      // read the src vertex
      size_t srcid = bis.read<int32_t>();
      assert(srcid< numvars);
      variable_type* varsrc = idtovar[srcid];
      size_t srccard = bis.read<int32_t>();
      if (bis.fail()) return false;
      // read the destination vertex
      size_t destid = bis.read<int32_t>();
      assert(destid < numvars);
      variable_type* vardest = idtovar[destid];
      size_t destcard = bis.read<int32_t>();
      if (bis.fail()) return false;
      
      if (srccard != varsrc->size() || destcard != vardest->size()) {
        return false;
      }

      F factor(make_domain(varsrc, vardest), 0.0);
      for (size_t j = 0; j < srccard * destcard; ++j) {
        size_t srcasg = bis.read<int32_t>();
        size_t destasg = bis.read<int32_t>();
        double value = bis.read<double>();
        if (bis.fail()) return false;
        if (!((srcasg < srccard) && (destasg < destcard))) return false;
        //assert(srcasg < srccard);
        //assert(destasg < destcard);
        // slow!
        /*
        finite_assignment fasg;
        fasg[varsrc] = srcasg;
        fasg[vardest] = destasg;
        proteinparsing::valueassign(factor(fasg), value);
        */
        // faster, but a little awkward
        if (factor.arg_vector()[0] == varsrc) {
          factor.set_logv(srcasg, destasg, proteinparsing::bound_infinity(value));
        }
        else {
          factor.set_logv(destasg, srcasg, proteinparsing::bound_infinity(value));
        }
      }
      if (std::isinf(-std::log(factor.minimum())) ) {
//        std::cout << factor << "\n";
//        getchar();
      }

      fg.add_factor(factor);
    }
//    std::cout << "done!" << std::endl;
    return true;
  }
Ejemplo n.º 19
0
void CryptoManager::decodeHuffman(const u_int8_t* is, string& os, const size_t len) throw(CryptoException) {
//	BitInputStream bis;
	int pos = 0;

	if(len < 11 || is[pos] != 'H' || is[pos+1] != 'E' || !((is[pos+2] == '3') || (is[pos+2] == '0'))) {
		throw CryptoException(STRING(DECOMPRESSION_ERROR));
	}
	pos+=5;

	int size;
	size = *(int*)&is[pos];

	pos+=4;

	dcdebug("Size: %d\n", size);
	
	unsigned short treeSize;
	treeSize = *(unsigned short*)&is[pos];

	pos+=2;

	if(len < (size_t)(11 + treeSize * 2)) 
		throw CryptoException(STRING(DECOMPRESSION_ERROR));
	Leaf** leaves = new Leaf*[treeSize];

	int i;
	for(i=0; i<treeSize; i++) {
		int chr =  is[pos++];
		int bits = is[pos++];
		leaves[i] = new Leaf(chr, bits);
	}

	BitInputStream bis(is, pos, len);

	DecNode* root = new DecNode();

	for(i=0; i<treeSize; i++) {
		DecNode* node = root;
		for(int j=0; j<leaves[i]->len; j++) {
			try {
				if(bis.get()) {
					if(node->right == NULL)
						node->right = new DecNode();

					node = node->right;
				} else {
					if(node->left == NULL)
						node->left = new DecNode();

					node = node->left;
				}
			} catch(const BitStreamException&) {
				throw CryptoException(STRING(DECOMPRESSION_ERROR));
			}
		}
		node->chr = leaves[i]->chr;
	}
	
	bis.skipToByte();
	
	// We know the size, so no need to use strange STL stuff...
	AutoArray<char> buf(size+1);

	pos = 0;
	for(i=0; i<size; i++) {
		DecNode* node = root;
		while(node->chr == -1) {
			try {
				if(bis.get()) {
					node = node->right;
				} else {
					node = node->left;
				}
			} catch(const BitStreamException&) {
				throw CryptoException(STRING(DECOMPRESSION_ERROR));
			}

			if(node == NULL) {
				for(i=0; i<treeSize; i++) {
					delete leaves[i];
				}
				
				delete[] leaves;
				delete root;

				dcdebug("Bad node found!!!\n");
				throw CryptoException(STRING(DECOMPRESSION_ERROR));
			}
		}
		buf[pos++] = (u_int8_t)node->chr;
	}
	buf[pos] = 0;
	os.assign(buf, size);

	for(i=0; i<treeSize; i++) {
		delete leaves[i];
	}
	
	delete[] leaves;
	delete root;
}
Ejemplo n.º 20
0
void Trimmer::CutTrack(string outputFLACFile, unsigned int leftSecond, unsigned int rightSecond)
{
   /* if (bs.GetString(3) == "ID3")
    {
    	bs.Skip(3);
    	uint32_t id3size = 0;
    	uint32_t b1 = 0, b2 = 0, b3 = 0, b4 = 0;
    	bs.GetInteger(&b1, 8);
    	bs.GetInteger(&b2, 8);
    	bs.GetInteger(&b3, 8);
    	bs.GetInteger(&b4, 8);
    	id3size = (b1 << 21) | (b2 << 14) | (b3 << 7) | b4;
    	bs.Skip(id3size);
    }*/

	BitIStream bis(fileName);
	BitOStream bos(outputFLACFile);
	FLACMetaStreamInfo msi;

	if (bis.ReadString(4) != "fLaC")
	{
		throw NoFLACFile();
	}
	bos.WriteString("fLaC");
			
	FLACMetaBlockHeader mbh;
	mbh.IsLastBlock = false;
			
	while (!mbh.IsLastBlock)
	{
		ReadMetaBlockHeader(bis, &mbh);
		WriteMetaBlockHeader(bos, &mbh);
		switch (mbh.BlockType)
		{
			case FLAC_META_STREAMINFO:
				ReadStreamInfo(bis, &msi);
				WriteStreamInfo(bos, &msi);
			break;

			case FLAC_META_SEEKTABLE:
			case FLAC_META_APPLICATION:
			case FLAC_META_VORBIS_COMMENT:
			case FLAC_META_CUESHEET:
			case FLAC_META_PADDING:
				CopyBytes(bis, bos, mbh.BlockSize);
			break;

			default:
				cerr << "Warning: unknown block type" << endl;
				CopyBytes(bis, bos, mbh.BlockSize);
			break;
		}
	}
	for (int i = 0; i < 10; i++)
	{

		//Frame start
		FLACFrameHeader fh;
		ReadFrameHeader(bis, &fh);
		WriteFrameHeader(bos, &fh);
		if (fh.SyncCode != 0b11111111111110) 
		{
			cout << "Invalid sync code" << endl;
			throw NoFLACFile();
		}
		for (int subframeN = 0; subframeN <= msi.ChannelsCount; subframeN++)
		{
			FLACSubframeHeader sfh;
			ReadSubframeHeader(bis, &sfh);
			WriteSubframeHeader(bos, &sfh);
			switch (sfh.Type)
			{
				case FLAC_SF_CONSTANT:	
					cout << "const" << endl;
					CopyConstantSubframe(bis, bos, &fh, &msi);
				break;
				case FLAC_SF_VERBATIM:
					cout << "verbatim" << endl;
					CopyVerbatimSubframe(bis, bos, &fh, &msi);
				break;
				case FLAC_SF_FIXED:
					cout << "fixed" << endl;
					CopyFixedSubframe(bis, bos, &fh, &msi, &sfh);
				break;
				case FLAC_SF_LPC:
					cout << "lpc" << endl;
					CopyLPCSubframe(bis, bos, &fh, &msi, &sfh);
				break;
				default:
				break;
			}
		}
		bos.AlignByte();
		uint16_t crc16;
		bis.ReadInteger(&crc16, 16);
		bos.WriteInteger(crc16, 16);

	/*ReadFrameHeader(bis, &fh);
	cout << fh.SyncCode << endl;*/
		//Frame end

	}
		
}
Ejemplo n.º 21
0
unsigned char readvirtIOport(struct virtual_IO_port *virtualPort) {
    unsigned char pin;
    unsigned char result = 0x00; /* buffer for pin status -> port status */

    READ_IO_DEBUG("\r\nreadIOport\r\n");

    for (pin = 0; pin < VIRTUAL_PORT_PINCOUNT; pin++) { /* loop over all virtual IO Pins */
        READ_IO_DEBUG("pPort:0x%x;",virtualPort->pins[pin].PPORT);
        READ_IO_DEBUG("pDDR:0x%x;",virtualPort->pins[pin].PDDR);
        READ_IO_DEBUG("pPin:0x%x;",virtualPort->pins[pin].PPIN);
        READ_IO_DEBUG("pin:%i\r\n",pin);
        READ_IO_DEBUG("func:0x%x\r\n",virtualPort->pins[pin].function_code);

        if(virtualPort->pins[pin].PPORT == 0
                || virtualPort->pins[pin].PDDR == 0
                || virtualPort->pins[pin].PPIN == 0)
        {
            READ_IO_DEBUG("conti\r\n");
            continue;
        }

        switch (virtualPort->pins[pin].function_code) {
        case PIN_S0:
            /*
             * S0 functionality
             * - check ddr/port/pin for S0 pin (only interrupt pins possible for this function)
             * - write current counter value to virtual pin data area of txbuffer
             */
            break;
        case PIN_INPUT: /* input pin -> read pin status to buffer */
            if (bis(*(virtualPort->pins[pin].PPIN),virtualPort->pins[pin].pin)) { /* get status of current pin */
                //set "ON"
                cbi(result, pin%8);
                /* clear bit */
            } else {
                //set "OFF"
                sbi(result, pin%8);
                /* set bit */
            }
            break;
        case PIN_SWITCH: /* switch pin -> read current pin status to buffer */
        case PIN_TOGGLE:
        case PIN_PULSE:
            if (bis(*(virtualPort->pins[pin].PPORT),virtualPort->pins[pin].pin)) { /* get status of current pin */
                //set "ON"
                cbi(result, pin%8);
                /* clear bit */
            } else {
                //set "OFF"
                sbi(result, pin%8);
                /* set bit */
            }
            break;
#ifdef USE_OW
        case PIN_OW_POWER_PARASITE:
            read1WirePin(&virtualPort->pins[pin], DS18X20_POWER_PARASITE);
            break;
        case PIN_OW_POWER_EXTERN:
            read1WirePin(&virtualPort->pins[pin], DS18X20_POWER_EXTERN);
            break;
#endif
        case PIN_DISABLED:
        default: /* default handling */
            cbi(result, (pin%8));
            /* clear bit in buffer */
            break;
        }

    }
    READ_IO_DEBUG("result0x%x\r\n",result);
    return result;
}
Ejemplo n.º 22
0
bool RapMapIndex::load(std::string& indexPrefix) {
    auto logger = spdlog::get("stderrLog");
    std::string kmerInfosName = indexPrefix + "kinfo.bin";
    std::string eqClassListName = indexPrefix + "eqclass.bin";
    std::string eqLabelListName = indexPrefix + "eqlab.bin";
    std::string posListName = indexPrefix + "pos.bin";
    std::string jfFileName = indexPrefix + "rapidx.jfhash";
    std::string txpNameFile = indexPrefix + "txpnames.bin";
    std::string txpLenFile = indexPrefix + "txplens.bin";
    std::string fwdJumpFile = indexPrefix + "fwdjump.bin";
    std::string revJumpFile = indexPrefix + "revjump.bin";

    // Load the kmer info list first --- this will
    // give us the # of unique k-mers
    std::ifstream kmerInfoStream(kmerInfosName, std::ios::binary);
    {
        logger->info("loading k-mer info list . . .");
        ScopedTimer timer;
        cereal::BinaryInputArchive kmerInfoArchive(kmerInfoStream);
        kmerInfoArchive(kmerInfos);
        logger->info("done\n");
    }
    kmerInfoStream.close();

    size_t numDistinctKmers = kmerInfos.size();
    {
        ScopedTimer timer;
        logger->info("loading k-mer => id hash . . . ");
        std::ifstream bis(jfFileName);
        const SpecialHeader bh(bis);
        // mapFile.reset(new jellyfish::mapped_file(jfFileName.c_str()));
        const size_t sizeInBytes = bh.size_bytes();
        // Load the hash from file
        logger->info("\theader format = {}"      , bh.format());
        logger->info("\t# distinct k-mers = {}"  , numDistinctKmers);
        logger->info("\thash key len = {}"       , bh.key_len());
        logger->info("\tcounter len = {}"        , bh.counter_len());
        logger->info("\tmax reprobe offset = {}" , bh.max_reprobe());
        logger->info("\tsize in bytes = {}"      , sizeInBytes);

        // Allocate the actual storage
        rawHashMem.reset(new char[sizeInBytes]);
        bis.read(rawHashMem.get(), sizeInBytes);
        // We can close the file now
        bis.close();

        merHash.reset( new FileMerArray(rawHashMem.get(),//mapFile->base() + bh.offset(),
                    sizeInBytes,
                    bh.size(),
                    bh.key_len(),
                    bh.counter_len(),
                    bh.max_reprobe(),
                    bh.matrix()));
        // Set the key size
        rapmap::utils::my_mer::k(bh.key_len() / 2);
        logger->info("done");
    }


    std::ifstream eqClassStream(eqClassListName, std::ios::binary);
    {
        logger->info("loading eq classes . . . ");
        ScopedTimer timer;
        cereal::BinaryInputArchive eqClassArchive(eqClassStream);
        eqClassArchive(eqClassList);
        logger->info("[{}] classes", eqClassList.size());
        logger->info("done");
    }
    eqClassStream.close();
    std::ifstream eqLabelStream(eqLabelListName, std::ios::binary);
    {
        logger->info("loading eq class labels . . . ");
        ScopedTimer timer;
        cereal::BinaryInputArchive eqLabelArchive(eqLabelStream);
        eqLabelArchive(eqLabelList);
        logger->info("[{}] labels", eqLabelList.size());
        logger->info("done");
    }
    eqLabelStream.close();
    std::ifstream posStream(posListName, std::ios::binary);
    {
        logger->info("loading position list . . . ");
        ScopedTimer timer;
        cereal::BinaryInputArchive posArchive(posStream);
        posArchive(posList);
        logger->info("[{}] total k-mer positions", posList.size());
        logger->info("done");
    }
    posStream.close();
    std::ifstream txpNameStream(txpNameFile, std::ios::binary);
    {
        logger->info("loading transcript names ");
        ScopedTimer timer;
        cereal::BinaryInputArchive txpNameArchive(txpNameStream);
        txpNameArchive(txpNames);
        logger->info("[{}] transcripts in index ", txpNames.size());
        logger->info("done ");
    }
    txpNameStream.close();

    std::ifstream txpLenStream(txpLenFile, std::ios::binary);
    {
        logger->info("loading transcript lengths");
        ScopedTimer timer;
        cereal::BinaryInputArchive txpLenArchive(txpLenStream);
        txpLenArchive(txpLens);
        logger->info("[{}] transcripts in index", txpLens.size());
        logger->info("done ");
    }
    txpLenStream.close();

    std::ifstream fwdJumpStream(fwdJumpFile, std::ios::binary);
    {
        logger->info("loading forward jumps");
        ScopedTimer timer;
        cereal::BinaryInputArchive fwdJumpArchive(fwdJumpStream);
        fwdJumpArchive(fwdJumpTable);
        logger->info("[{}] forward jumps", fwdJumpTable.size());
        logger->info("done ");
    }
    fwdJumpStream.close();

    std::ifstream revJumpStream(revJumpFile, std::ios::binary);
    {
        logger->info("loading forward jumps");
        ScopedTimer timer;
        cereal::BinaryInputArchive revJumpArchive(revJumpStream);
        revJumpArchive(revJumpTable);
        logger->info("[{}] reverse jumps", revJumpTable.size());
        logger->info("done ");
    }
    revJumpStream.close();
    return true;
}
Ejemplo n.º 23
0
void handleIOport(struct virtual_IO_port *virtualPort,
                  unsigned char instructions, const unsigned char mask) {

    unsigned char *cur_DDR = 0; /* pointer to DDR register */
    unsigned char *cur_PORT = 0; /* pointer to O Port */
    unsigned char *cur_PIN = 0; /* pointer to I Pin */
    unsigned char cur_pin = 0;	/* pin number */

    HANDLE_IO_DEBUG("\r\nhandleIOport:0x%x\r\n",instructions);

    for (int pin = 0; pin < VIRTUAL_PORT_PINCOUNT; pin++) { /* loop over all virtual IO Pins */

        if (!(mask & (1 << pin)))
        {
            continue;
        }

        if(virtualPort->pins[pin].PPORT == 0
                || virtualPort->pins[pin].PDDR == 0
                || virtualPort->pins[pin].PPIN == 0)
        {
            continue;
        }

        /*
         * first get all needed address information for current pin/port
         * - the "action" data is written by i2c into the rxbuffer -> need correct rxbuffer address
         * - the function of the current pin is readout from the eeprom -> need correct eeprom address
         */

        cur_PORT = virtualPort->pins[pin].PPORT; /* get pointer to current port */
        HANDLE_IO_DEBUG("pPort:0x%x;",cur_PORT);

        cur_DDR = virtualPort->pins[pin].PDDR; /* get pointer to current datadirectionregister */
        HANDLE_IO_DEBUG("pDDR:0x%x;",cur_DDR);

        cur_PIN = virtualPort->pins[pin].PPIN; /* get pointer to current pin */
        HANDLE_IO_DEBUG("pPIN:0x%x\r\n",cur_PIN);

        cur_pin = virtualPort->pins[pin].pin;
        HANDLE_IO_DEBUG("pin:0x%x\r\n",cur_pin);

        HANDLE_IO_DEBUG("func:0x%x\r\n",virtualPort->pins[pin].function_code);

        switch (virtualPort->pins[pin].function_code) { /* handle current pin by function code */
        case PIN_DISABLED: /* pin is marked as disabled */
            *cur_DDR &= ~(1 << cur_pin); //disable PIN
            *cur_PORT &= ~(1 << cur_pin); //disable PULLUP
            break;
        case PIN_INPUT: /* pin marked as input -> set as input nothing else to to (value is readout @readIOpins() */
            *cur_DDR &= ~(1 << cur_pin); //set DDR "0"
            *cur_PORT |= (1 << cur_pin); //enable pullup PORT "1"
            break;
        case PIN_SWITCH: /* pin marked as output -> set as output and set the value of the specific bit of rxbuffer*/
            *cur_DDR |= (1 << cur_pin); /* set DDR "1" -> output */
            if (bis(instructions,(pin%8))) { //on or off
                *cur_PORT &= ~(1 << cur_pin); //set 0 -> "OFF"
            } else {
                *cur_PORT |= (1 << cur_pin); //set 1 -> "ON"
            }
            break;
        case PIN_PULSE: /* pin marked as output -> set as output and pulse the specific pin */
            *cur_DDR |= (1 << cur_pin); /* set DDR "1" -> output */
            if (bis(instructions,(pin%8))) { //only handle active pins
                *cur_PORT &= ~(1 << cur_pin); //set 0 > "OFF"
                _delay_ms(pulse_time); /* wait x ms */
                *cur_PORT |= (1 << cur_pin); //set 1 -> "ON"
            }
            break;
        case PIN_TOGGLE: /* pin marked as output -> set as output and pulse the specific pin */
            *cur_DDR |= (1 << cur_pin); /* set DDR "1" -> output */
            if (bis(instructions,(pin%8))) { //only handle active pins
                if (bis(*cur_PORT,(cur_pin%8))) { //test old value
                    *cur_PORT &= ~(1 << cur_pin); //set OFF
                } else {
                    *cur_PORT |= (1 << cur_pin); //set 1 -> "ON"
                }
            }
            break;
#ifdef USE_OW
        case PIN_OW_POWER_PARASITE:
            set1WirePin(&virtualPort->pins[pin], DS18X20_POWER_PARASITE);
            break;
        case PIN_OW_POWER_EXTERN:
            set1WirePin(&virtualPort->pins[pin], DS18X20_POWER_EXTERN);
            break;
#endif
        case PIN_S0:
            /*
             * S0 functionality
             *
             * @todo test this function
             */

            /*//INT0
             if((cur_PORT == P_S0_0_PORT) && (cur_DDR == P_S0_0_DDR) && (io_pins[pin].pin == S0_0_PIN)){
             //enable S0
             *cur_DDR &= ~(1 << io_pins[pin].pin); //set DDR "0"
             *cur_PORT |= (1 << io_pins[pin].pin); //enable pullup PORT "1"
             S0_Start(0);
             S0_0 = 1;
             if(get_S0_data(0)%S0_interval == 0){
             save_eeprom(0);
             }
             break;
             }else{
             //INT1
             if((cur_PORT == P_S0_1_PORT) && (cur_DDR == P_S0_1_DDR) && (io_pins[pin].pin == S0_1_PIN)){

             //enable S0
             *cur_DDR &= ~(1 << io_pins[pin].pin); //set DDR "0"
             *cur_PORT |= (1 << io_pins[pin].pin); //enable pullup PORT "1"
             S0_Start(1);
             S0_1 = 1;
             if(get_S0_data(1)%S0_interval == 0){
             save_eeprom(1);
             }
             break;
             }else{
             eeprom_busy_wait ();
             eeprom_write_byte(eeprom_address,PIN_DISABLED);	//write function code to eeprom
             }
             }*/
            break;
        default:
            HANDLE_IO_DEBUG("unknown_func\r\n");
            *cur_DDR &= ~(1 << virtualPort->pins[pin].pin); //disable PIN
            *cur_PORT &= ~(1 << virtualPort->pins[pin].pin); //disable PULLUP
            break;
        }
    }

    /*	//S0 deaktivieren
     if(!S0_0){
     S0_Stop(0);
     }

     if(!S0_1){
     S0_Stop(1);
     }*/

}
Ejemplo n.º 24
0
	bool ScreenPub::onHandleOpen(const void* buf, size_t len, OutputStream& out)
	{
		
		u32 timeStamp = Timer::currentTimeMillis();
		ScreenInfo sinfo;
		ByteBufferInputStream bis((const u8*)buf,len,false);
		sinfo.load(bis);
		
		String dimdimId = "defaultUser";
		String roomId = getScreen().getConfKey();
		String sessionId = "defaultSession";
		String installationId = "";
		if(bis.getRemainingByteCount() > 0)
		{
			//u32 lenRemains = bis.getRemainingByteCount();
			//char *tmp = new char[lenRemains];
			//bis.peek(tmp,lenRemains);
			//std::cout<<"Remaining buffer : "<<lenRemains<<std::endl;
			//Dump::hexDump(std::cout,tmp,lenRemains);
			//std::cout<<"Reading RAD strings\n"<<std::endl;
			size_t len = 0;
			{
				
				bis.readLong((u32*)&len);
				std::cout<<"Length Read : "<<len<<std::endl;
				char *buf = new char[len+1];
				ScopedArray<char> bufPtr(buf);
				memset(buf,0,len+1);
				bis.read(buf,len);
				std::cout<<"dimdim id : ["<<buf<<"]"<<std::endl;
				String identity = buf;
				StringTokenizer st(identity,DDSS_IDENTITY_SEP);
				if(st.countTokens() == 1)
				{
					dimdimId = buf;
					installationId = "";
				}
				else
				{
					installationId = st.nextToken();
					dimdimId = st.nextToken();
				}

                DDSS_INFO("ScreenPub")<<"Install ID ["<<installationId<<"] Dimdim ID : ["<<dimdimId<<"]"<<std::endl;
			}
			len = 0;
			{
			
				bis.readLong((u32*)&len);
                                std::cout<<"Length Read : "<<len<<std::endl;
				char *buf = new char[len+1];
				ScopedArray<char> bufPtr(buf);
				memset(buf,0,len+1);
				bis.read(buf,len);
				std::cout<<"room name : ["<<buf<<"]"<<std::endl;
				roomId = buf;
			}
			len = 0;
			{
				
				bis.readLong((u32*)&len);
				
				std::cout<<"Length Read : "<<len<<std::endl;
				char *buf = new char[len+1];
				ScopedArray<char> bufPtr(buf);
				memset(buf,0,len+1);
				bis.read(buf,len);
				std::cout<<"session id : ["<<buf<<"]"<<std::endl;
				sessionId = buf;
			}
			
		}
		DDSS_VERBOSE("ScreenPub")<<"LOADED SCREEN INFO : "<<sinfo<<std::endl;
		getScreen().init(sinfo);
		getScreen().setRADParams(dimdimId, roomId, sessionId, installationId);
		DDSS_VERBOSE("ScreenPub")<<"SCREEN INIT DONE : "<<getScreen().getInfo()<<std::endl;
		out.write(getId().c_str(),getId().size());
		out.write("\n",1);
		
		if(dumpOn)
		{
				std::cout<<"RAD Dir : "<<getScreen().getRADDir()<<std::endl;
				String dumpFileName = getScreen().getRADDir();
				dumpFileName += "/Inbox/DTP/";
				dumpFileName += getScreen().getStreamName();
				dumpFileName += ".bin";
				std::cout<<"Dumping incoming traffic to : "<<dumpFileName<<"..."<<std::endl;
				dumpFile.open(dumpFileName.c_str(), std::ios::out | std::ios::binary);
				if(!dumpFile.is_open())
				{
					DDSS_WARN("ScreenPub")<<"[DUMP-FAIL] Failed to open : ("<<dumpFileName<<")"<<std::endl;
					dumpOn = false;
				}
		}
		
		if(dumpOn && dumpFile.is_open() && buf)
		{
			ScopedLock sl(dumpLock);
			//std::cout<<"Writing open buffer of length : "<<len<<"bytes!!! "<<std::endl;
			dumpFile.write((const char*)&len,4);
			dumpFile.write((const char*)&timeStamp,4);
			dumpFile.write((const char*)buf,(int)len);
			dumpFile.flush();
		}
		return true;
	}
Ejemplo n.º 25
0
/* Compute x|y using only calls to functions bis and bic */
int bool_or(int x, int y) {
    int result = bis(x, y);
    return result;
};
Ejemplo n.º 26
0
/* Compute x^y using only calls to functions bis and bic */
int bool_xor(int x, int y) {
    int result = bic ( bis(x, y), bic ( x, bic (x, y)));
    return result;
}
Ejemplo n.º 27
0
SetupReader* SetupReader::get_empty_reader(){
	char *c = new char[1];
	BinaryInputByteStream bis(c, 1);
	SetupReader *sr = new SetupReader(bis, false);
	return sr;
}