Esempio n. 1
0
//*******************************************************************
//* Извлечение раздела из файла и добавление его в таблицу разделов
//*
//  in - входной файл прошивки
//  Позиция в файле соответствует началу заголовка раздела
//*******************************************************************
void extract(FILE* in)  {

uint16_t hcrc,crc;
uint16_t* crcblock;
uint32_t crcblocksize;
uint8_t* zbuf;
long int zlen;
int res;

ptable[npart].zflag=0; 
// читаем заголовок в структуру
ptable[npart].offset=ftell(in);
fread(&ptable[npart].hd,1,sizeof(struct pheader),in); // заголовок
//  Ищем символическое имя раздела по таблице 
find_pname(ptable[npart].hd.code,ptable[npart].pname);

// загружаем блок контрольных сумм
ptable[npart].csumblock=0;  // пока блок не создан
crcblock=(uint16_t*)malloc(crcsize(npart)); // выделяем временную память под загружаемый блок
crcblocksize=crcsize(npart);
fread(crcblock,1,crcblocksize,in);

// загружаем образ раздела
ptable[npart].pimage=(uint8_t*)malloc(psize(npart));
fread(ptable[npart].pimage,1,psize(npart),in);

// проверяем CRC заголовка
hcrc=ptable[npart].hd.crc;
ptable[npart].hd.crc=0;  // старая CRC в рассчете не учитывается
crc=crc16((uint8_t*)&ptable[npart].hd,sizeof(struct pheader));
if (crc != hcrc) {
    printf("\n! Раздел %s (%02x) - ошибка контрольной суммы заголовка",ptable[npart].pname,ptable[npart].hd.code>>16);
    errflag=1;
}  
Esempio n. 2
0
//*******************************************************
//*  Вычисление блочной контрольной суммы раздела 
//*******************************************************
void calc_crc16(int n) {
  
uint32_t csize; // размер блока сумм в 16-битных словах
uint16_t* csblock;  // указатель на создаваемый блок
uint32_t off,len;
uint32_t i;
uint32_t blocksize=ptable[n].hd.blocksize; // размер блока, охватываемого суммой

// определяем размер и создаем блок
csize=psize(n)/blocksize;
if (psize(n)%blocksize != 0) csize++; // Это если размер образа не кратен blocksize
csblock=(uint16_t*)malloc(csize*2);

// цикл вычисления сумм
for (i=0;i<csize;i++) {
 off=i*blocksize; // смещение до текущего блока 
 len=blocksize;
 if ((ptable[n].hd.psize-off)<blocksize) len=ptable[n].hd.psize-off; // для последнего неполного блока 
 csblock[i]=crc16(ptable[n].pimage+off,len);
} 
// вписываем параметры в заголовок
if (ptable[n].csumblock != 0) free(ptable[n].csumblock); // уничтожаем старый блок, если он был
ptable[n].csumblock=csblock;
ptable[n].hd.hdsize=csize*2+sizeof(struct pheader);
// перевычисляем CRC заголовка
calc_hd_crc16(n);
  
}
ostream &
SMKStrStreambuf::dumpInfo(
  ostream &	dest,
  const char *  prefix,
  bool		showVer
  )
{
  if( showVer )
    dest << SMKStrStreambuf::getClassName() << ":\n"
	 << SMKStrStreambuf::getVersion() << '\n';

  dest << prefix << "length:  " << plen() << '\n'
#if defined( SMK_HAVE_STRBUF_BASE )
       << prefix << "base():  " << (void *) base() << '\n'
#endif
#if defined( SMK_HAVE_STRBUF_EBUF )
       << prefix << "ebuf():  " << (void *) ebuf() << '\n'
#endif
       << prefix << "pbase(): " << (void *) pbase() << '\n'
       << prefix << "pptr():  " << (void *) pptr() << '\n'
       << prefix << "epptr(): " << (void *) epptr() << '\n'
       << prefix << "eback(): " << (void *) eback() << '\n'
       << prefix << "gptr():  " << (void *) gptr() << '\n'
       << prefix << "egptr(): " << (void *) egptr() << '\n'
       << prefix << "n - b:   " << pptr() - pbase() << '\n'
       << prefix << "string:  '" << (void *)cstr() << "'\n"
       << prefix << "pbase(): " << (void *) pbase() << '\n'
       << prefix << "pptr():  " << (void *) pptr() << '\n'
       << prefix << "length:  " << plen() << '\n'
       << prefix << "size:    " << psize() << '\n'
    ;

  return( dest );
}
int main(int argc, char * const *argv)
{
  int M = 256;
  cv::Size imsize(512, 512);
  cv::Size psize(32,32);

  int lbdType;
  if (strncmp(argv[1], "freak", 5) == 0)
  {
    lbdType = lbd::eTypeFreak;;
  }
  else
  {
    if (strncmp(argv[1], "brief", 5) == 0)
    {
      lbdType = lbd::eTypeBrief;
    }
    else
    {
      std::cerr << "Error. The parameter should be either freak or brief.\n";
      return -1;
    }
  }

  lts2::LBDOperator *LBD = lts2::CreateLbdOperator(lbdType, M);
  LBD->initWithPatchSize(psize);

  cv::Mat destImage(cv::Size(imsize), CV_8UC3);
  LBD->drawSelfAsCircles(destImage);
  
  cv::imwrite(argv[2], destImage);

  return EXIT_SUCCESS;
}
Esempio n. 5
0
        bool model_t::resize(size_t rows, size_t cols, size_t outputs, color_mode color, bool verbose)
        {
                m_rows = rows;
                m_cols = cols;
                m_outputs = outputs;
                m_color = color;
                resize(verbose);

                if (verbose)
                {
                        log_info() << "model: parameters = " << psize() << ".";
                }

                return true;
        }
BOOL CMovieDialogBackground::SetFrame(int nFrame)
{
  if (m_nFrame == nFrame)
    return TRUE;

  m_nFrame = nFrame % CMovieDlgBkg::LEN_IMAGE_ARRAY;

  ResetResource();

  int nX = 0;
  int nY = 0;
  RECT rect;
  GetWindowRect(m_hWnd, &rect);
  //int w = rect.right - rect.left;
  //int h = rect.bottom - rect.top;
  int w = MOVIE_SIZE_W;
  int h = MOVIE_SIZE_H;
  //std::wstring image = CMovieDlgBkg::image_array[m_nFrame];
  WCHAR image[MAX_PATH] = {0};
  wsprintf(image, L"movie\\%d.png",m_nFrame);
  
  HDC hdc = GetDC(m_hWnd);
  m_hCacheDc  = CreateCompatibleDC(hdc);
  m_hCacheBitmap = CreateCompatibleBitmap(hdc, w, h);
  SelectObject(m_hCacheDc, m_hCacheBitmap);

  if (!m_pBackgroundImage)
    m_pBackgroundImage = new YGImage();
  m_pBackgroundImage->LoadImage(EXTEND_TO_FULL_PATH(image));

  m_pBackgroundImage->Draw(m_hCacheDc, nX, nY);
	
	//ÉèÖÃ͸Ã÷´°¿Ú-------------------------------------------------
	CPoint DestPt(0,0);
	CSize psize(w,h);
	BLENDFUNCTION blendFunc32bpp;
	blendFunc32bpp.AlphaFormat = AC_SRC_ALPHA;
	blendFunc32bpp.BlendFlags = 0;
	blendFunc32bpp.BlendOp = AC_SRC_OVER;
	blendFunc32bpp.SourceConstantAlpha = 255;
	::UpdateLayeredWindow(m_hWnd,hdc,NULL,&psize,m_hCacheDc,&DestPt,0,&blendFunc32bpp,ULW_ALPHA);

  ReleaseDC(m_hWnd, hdc);
	return TRUE;
}
Esempio n. 7
0
//**********************************************************************************************************************
vector<string> SummaryCommand::setParameters() {
    try {
        CommandParameter plist("list", "InputTypes", "", "", "LRSS", "LRSS", "none","summary",false,false,true);
        parameters.push_back(plist);
        CommandParameter prabund("rabund", "InputTypes", "", "", "LRSS", "LRSS", "none","summary",false,false);
        parameters.push_back(prabund);
        CommandParameter psabund("sabund", "InputTypes", "", "", "LRSS", "LRSS", "none","summary",false,false);
        parameters.push_back(psabund);
        CommandParameter pshared("shared", "InputTypes", "", "", "LRSS", "LRSS", "none","summary",false,false,true);
        parameters.push_back(pshared);
        CommandParameter psubsample("subsample", "String", "", "", "", "", "","",false,false);
        parameters.push_back(psubsample);
        CommandParameter piters("iters", "Number", "", "1000", "", "", "","",false,false);
        parameters.push_back(piters);
        CommandParameter plabel("label", "String", "", "", "", "", "","",false,false);
        parameters.push_back(plabel);
        CommandParameter pcalc("calc", "Multiple", "sobs-chao-nseqs-coverage-ace-jack-shannon-shannoneven-npshannon-heip-smithwilson-simpson-simpsoneven-invsimpson-bootstrap-geometric-qstat-logseries-bergerparker-bstick-goodscoverage-efron-boneh-solow-shen", "sobs-chao-ace-jack-shannon-npshannon-simpson", "", "", "","",true,false,true);
        parameters.push_back(pcalc);
        CommandParameter pabund("abund", "Number", "", "10", "", "", "","",false,false);
        parameters.push_back(pabund);
        CommandParameter psize("size", "Number", "", "0", "", "", "","",false,false);
        parameters.push_back(psize);
        CommandParameter pgroupmode("groupmode", "Boolean", "", "T", "", "", "","",false,false);
        parameters.push_back(pgroupmode);
        CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false);
        parameters.push_back(pinputdir);
        CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false);
        parameters.push_back(poutputdir);

        vector<string> myArray;
        for (int i = 0; i < parameters.size(); i++) {
            myArray.push_back(parameters[i].name);
        }
        return myArray;
    }
    catch(exception& e) {
        m->errorOut(e, "SummaryCommand", "setParameters");
        exit(1);
    }
}
Esempio n. 8
0
char *fillinfo(char *buf, struct _info *ent)
{
  int n;
  buf[n=0] = 0;
  #ifdef __USE_FILE_OFFSET64
  if (inodeflag) n += sprintf(buf," %7lld",(long long)ent->inode);
  #else
  if (inodeflag) n += sprintf(buf," %7ld",(long int)ent->inode);
  #endif
  if (devflag) n += sprintf(buf+n, " %3d", (int)ent->dev);
  #ifdef __EMX__
  if (pflag) n += sprintf(buf+n, " %s",prot(ent->attr));
  #else
  if (pflag) n += sprintf(buf+n, " %s", prot(ent->mode));
  #endif
  if (uflag) n += sprintf(buf+n, " %-8.32s", uidtoname(ent->uid));
  if (gflag) n += sprintf(buf+n, " %-8.32s", gidtoname(ent->gid));
  if (sflag) n += psize(buf+n,ent->size);
  if (Dflag) n += sprintf(buf+n, " %s", do_date(cflag? ent->ctime : ent->mtime));

  return buf;
}
Esempio n. 9
0
void MoveVirtualFunction ( DWORD const * const from, DWORD * const to )
{
#ifdef WIN32
	DWORD dwOld;
	if( !VirtualProtect ( to, sizeof ( DWORD ), PAGE_EXECUTE_READWRITE, &dwOld ) )
	{
		return;
	}
#else // LINUX
	uint32_t psize ( sysconf ( _SC_PAGESIZE ) );
	void *p = ( void * ) ( ( DWORD ) ( to ) & ~( psize - 1 ) );
	if( mprotect ( p, sizeof ( DWORD ) & ( psize - 1 ), PROT_READ | PROT_WRITE | PROT_EXEC ) < 0 )
	{
		return;
	}
#endif // WIN32
	DebugMessage ( Helpers::format ( "MoveVirtualFunction : function 0x%X replaced by 0x%X.", *to, *from ) );
	*to = *from;
#ifdef WIN32
	VirtualProtect ( to, sizeof ( DWORD ), dwOld, &dwOld );
#else // LINUX
	mprotect ( p, sizeof ( DWORD ) & ( psize - 1 ), PROT_READ | PROT_EXEC );
#endif // WIN32
}
Esempio n. 10
0
// ---------------------------------------------------------------------------
// CFotaSrvSession::ServiceL
// Handle client request
// ---------------------------------------------------------------------------
//
void CFotaSrvSession::ServiceL(const RMessage2& aMessage)
    {
    TInt err(KErrNone);
    TInt pkgid = 0;
    TPackageState state;
    RThread clt;
    aMessage.ClientL(clt);
    TFullName cltnm = clt.FullName();
    FLOG(_L( "CFotaSrvSession::ServiceL      %d   serving for %S?" ),
            aMessage.Function(), &cltnm);

    TFotaClient client = CheckClientSecureIdL(aMessage);

    if (client == EUnknown)
        {
        FLOG(_L("Permission denied to use fota services!"));
        User::Leave(KErrPermissionDenied);
        }

    TInt cmd = aMessage.Function();
    if ((cmd != EGetState) && (cmd != EGetResult) && (cmd != EGetCurrFwDetails) && (cmd != EGetUpdateTimestamp))
        {
    
        TInt fotaValue(1);
        CRepository* centrep(NULL);
        TUid uidValue =
            {
            0x101F9A08
            }; // KCRFotaAdapterEnabled

        centrep = CRepository::NewL(uidValue);
        if (centrep)
            {
            FLOG(_L("centralrepository found "));
            centrep->Get(1, fotaValue); // KCRFotaAdapterEnabled     
            delete centrep;
            }

        if (!fotaValue)
            {
            FLOG(_L("Fota is disabled or not supported!"));
            User::Leave(KErrNotSupported);
            }
            
        }

    switch (aMessage.Function())
        {

        case EFotaDownload:
            {
            FLOG(_L( "CFotaSrvSession::ServiceL DOWNLOAD"));
            TDownloadIPCParams ipc;
            TPckg<TDownloadIPCParams> pkg(ipc);
            aMessage.Read(0, pkg);
            TInt deslen = aMessage.GetDesLengthL(1);
            HBufC8* urlbuf = HBufC8::NewLC(deslen);
            TPtr8 urlptr = urlbuf->Des();
            aMessage.Read(1, urlptr);
            TInt silent = aMessage.Int2();
            FotaServer()->DownloadL(ipc, urlptr, client, silent, EFalse);
            CleanupStack::PopAndDestroy(urlbuf); // urlbuf
            aMessage.Complete(KErrNone);

            break;
            }
        case EFotaUpdate:
            {
            FLOG(_L( "CFotaSrvSession::ServiceL UPDATE" ));
            TDownloadIPCParams ipc;
            TPckg<TDownloadIPCParams> pkg(ipc);
            aMessage.Read(0, pkg);

            // If update started from omadmappui, no alert should be sent if 
            // update is cancelled
            if (client == EOMADMAppUi)
                {
                ipc.iSendAlert = EFalse;
                }
            FotaServer()->TryUpdateL(client);
            aMessage.Complete(KErrNone);
            break;
            }
        case EFotaDownloadAndUpdate:
            {
            FLOG(_L( "CFotaSrvSession::ServiceL DOWNLOADANDUPDATE" ));
            TDownloadIPCParams ipc;
            TPckg<TDownloadIPCParams> pkg(ipc);
            aMessage.Read(0, pkg);
            TInt deslen = aMessage.GetDesLengthL(1);
            HBufC8* urlbuf = HBufC8::NewLC(deslen);
            TPtr8 urlptr = urlbuf->Des();
            aMessage.Read(1, urlptr);
            TFotaClient requester = CheckClientSecureIdL(aMessage);

            TInt silent = aMessage.Int2();
            FotaServer()->DownloadL(ipc, urlptr, requester, silent, ETrue);
            CleanupStack::PopAndDestroy(urlbuf);
            aMessage.Complete(KErrNone);
            }
            break;

        case EFotaTryResumeDownload:
            {
            FLOG(_L( "CFotaSrvSession::ServiceL TRYRESUMEDOWNLOAD" ));
            if (client == EOMADMAppUi || client == EFMSServer || client
                    == EFotaTestApp)
                {
                TInt silent = aMessage.Int0();
                
                FotaServer()->TryResumeDownloadL(client, silent); // silent
                aMessage.Complete(KErrNone);
                }
            else
                {
                aMessage.Complete(KErrAccessDenied);
                }

            }
            break;

        case EDeletePackage:
            {
            FLOG(_L( "CFotaSrvSession::ServiceL DELETEPACKAGE"));
            pkgid = aMessage.Int0();
            FotaServer()->DeletePackageL(pkgid);
            aMessage.Complete(KErrNone);
            }
            break;
        case EGetState:
            {
            FLOG(_L( "CFotaSrvSession::ServiceL GETSTATE" ));
            pkgid = aMessage.Int0();

            state = FotaServer()->GetStateL(pkgid);

            FLOG(_L( "CFotaSrvSession::ServiceL GETSTATE << %d" ),  state.iState);
            TPckg<RFotaEngineSession::TState> pkg2(state.iState);
            aMessage.Write(1, pkg2);
            aMessage.Complete(KErrNone);
            }
            break;
        case EGetResult:
            {
            FLOG(_L( "CFotaSrvSession::ServiceL GETRESULT >>" ));
            pkgid = aMessage.Int0();
            state = FotaServer()->GetStateL(pkgid);
            TPckg<TInt> pkg2(state.iResult);
            FLOG(_L( "CFotaSrvSession::ServiceL GETRESULT << %d" ),
                    state.iResult);
            aMessage.Write(1, pkg2);
            aMessage.Complete(err);
            break;
            }
        case EGetUpdatePackageIds:
            {
            FLOG(_L( "CFotaSrvSession::ServiceL EGETUPDATEPACKAGEIDS" ));
            TPkgIdList pkgids;
            FotaServer()->GetUpdatePackageIdsL(pkgids);
            TPckg<TPkgIdList> pkgids_pkg(pkgids);
            aMessage.Write(0, pkgids_pkg);
            aMessage.Complete(KErrNone);
            }
            break;

        case EGetUpdateTimestamp:
            {
            FLOG(_L( "CFotaSrvSession::ServiceL EGETUPDATETIMESTAMP" ));
            TBuf16<15> timestamp;
            FotaServer()->GetUpdateTimeStampL(timestamp);
            aMessage.Write(0, timestamp);
            aMessage.Complete(KErrNone);
            }
            break;

        case EGenericAlertSentForPackage:
            {
            FLOG(_L( "CFotaSrvSession::ServiceL EGENERICALERTSENT FOR PKGID" ));
            TInt pkgid = aMessage.Int0();
            FotaServer()->ResetFotaStateL(pkgid);
            aMessage.Complete(err);
            }
            break;

        case EScheduledUpdate:
            {
            FLOG(_L( "CFotaSrvSession::ServiceL ESCHEDULEDUPDATE" ));
            TFotaScheduledUpdate sched(-1, -1);
            TPckg<TFotaScheduledUpdate> p(sched);
            aMessage.Read(0, p);

            FLOG(_L(" pkgid: %d   scheduleid:%d"), sched.iPkgId,
                    sched.iScheduleId);
            FotaServer()->ScheduledUpdateL(sched, client);
            aMessage.Complete(KErrNone);
            
            }
            break;

        case EPauseDownload:
            {
            FLOG(_L( "CFotaSrvSession::ServiceL EPAUSEDOWNLOAD" ));
            FotaServer()->PauseDownloadL();
            aMessage.Complete(KErrNone);
            }
            break;
        case EGetCurrFwDetails:
            {
            FLOG(_L( "CFotaSrvSession::ServiceL EGETCURRFWDETAILS" ));

            TBuf8<KFotaMaxPkgNameLength> name;
            TBuf8<KFotaMaxPkgVersionLength> version;
            TInt size(0);

            FotaServer()->GetCurrentFwDetailsL(name, version, size);

            /*
            aMessage.Write(1, name);
            aMessage.Write(2, version);
            TPckg<TInt> psize(size);
            aMessage.Write(3, psize);

            aMessage.Complete(KErrNone);*/
            
            aMessage.Write(0, name);
            aMessage.Write(1, version);
            TPckg<TInt> psize(size);
            aMessage.Write(2, psize);

            aMessage.Complete(KErrNone);


            }
            break;
        default:
            {
            FLOG(_L( "CFotaSrvSession::ServiceL In default case" ));
            }
            break;
        }
    }
Esempio n. 11
0
int main(int argc, char* argv[]) {

  if(argc != 2) {
    std::cerr << "Usage : " << argv[0] << "<0,1>" <<std::endl;
    std::cerr << "with : " << std::endl;
    std::cerr << "0 : quadratic loss" << std::endl;
    std::cerr << "1 : cross entropy loss" << std::endl;
    return -1;
  }

  bool quadratic_loss = (atoi(argv[1]) == 0);

  srand(time(NULL));

  // We compare our computation of the gradient to 
  // a finite difference approximation
  // The loss is also involved
  std::cout << "---------------------------------" << std::endl;
  std::cout << "Comparing the analytical gradient and numerical approximation " << std::endl;
  auto input = gaml::mlp::input<X>(INPUT_DIM, fillInput);
  auto l1 = gaml::mlp::layer(input, HIDDEN_LAYER_SIZE, gaml::mlp::mlp_sigmoid(), gaml::mlp::mlp_dsigmoid());
  auto l2 = gaml::mlp::layer(l1, HIDDEN_LAYER_SIZE, gaml::mlp::mlp_identity(), gaml::mlp::mlp_didentity());
  auto l3 = gaml::mlp::layer(l2, HIDDEN_LAYER_SIZE, gaml::mlp::mlp_tanh(), gaml::mlp::mlp_dtanh());
  auto l4 = gaml::mlp::layer(l3, OUTPUT_DIM, gaml::mlp::mlp_sigmoid(), gaml::mlp::mlp_dsigmoid());
  auto mlp = gaml::mlp::perceptron(l4, output_of);

  std::cout << "We use the following architecture : " << std::endl;
  std::cout << mlp << std::endl;
  std::cout << "which has a total of " << mlp.psize() << " parameters"<< std::endl;

  gaml::mlp::parameters_type params(mlp.psize());
  gaml::mlp::parameters_type paramsph(mlp.psize());
  gaml::mlp::values_type derivatives(mlp.psize());
  gaml::mlp::values_type forward_sweep(mlp.size());
  X x;

  auto loss_ce = gaml::mlp::loss::CrossEntropy();
  auto loss_quadratic = gaml::mlp::loss::Quadratic();

  auto f = [&mlp, &params] (const typename decltype(mlp)::input_type& x) -> gaml::mlp::values_type {
    auto output = mlp(x, params);
    gaml::mlp::values_type voutput(mlp.output_size());
    fillOutput(voutput.begin(), output);
    return voutput;
  };
  auto df = [&mlp, &forward_sweep, &params] (const typename decltype(mlp)::input_type& x, unsigned int parameter_dim) -> gaml::mlp::values_type {
    return mlp.deriv(x, params, forward_sweep, parameter_dim);
  };

  unsigned int nbtrials = 100;
  unsigned int nbfails = 0;
  std::cout << "I will compare " << nbtrials << " times a numerical approximation and the analytical gradient we compute" << std::endl;


  for(unsigned int t = 0 ; t < nbtrials ; ++t) {
  
    randomize_data(params, -1.0, 1.0);
    randomize_data(x, -1.0, 1.0);

    // Compute the output at params
    auto output = mlp(x, params);
    gaml::mlp::values_type raw_output(OUTPUT_DIM);
    fillOutput(raw_output.begin(), output);
    gaml::mlp::values_type raw_outputph(OUTPUT_DIM);

    // For computing the loss, we need a target
    gaml::mlp::values_type raw_target(OUTPUT_DIM);
    randomize_data(raw_target);

    double norm_dh = 0.0;

    for(unsigned int i = 0 ; i < mlp.psize() ; ++i) {
      // Let us compute params + h*[0 0 0 0 0 0 1 0 0 0 0 0], the 1 at the ith position
      std::copy(params.begin(), params.end(), paramsph.begin());
      double dh = (sqrt(DBL_EPSILON) * paramsph[i]);
      paramsph[i] += dh;
      norm_dh += dh*dh;
      // Compute the output at params + h
      auto outputph = mlp(x, paramsph);
      fillOutput(raw_outputph.begin(), outputph);
      
      // We now compute the approximation of the derivative
      if(quadratic_loss)
	derivatives[i] = (loss_quadratic(raw_target, raw_outputph) - loss_quadratic(raw_target, raw_output))/dh;
      else
	derivatives[i] = (loss_ce(raw_target, raw_outputph) - loss_ce(raw_target, raw_output))/dh;
	
    }
  
    // We now compute the analytical derivatives
    mlp(x, params);
    std::copy(mlp.begin(), mlp.end(), forward_sweep.begin());

    gaml::mlp::values_type our_derivatives(mlp.psize());
    for(unsigned int i = 0 ; i < mlp.psize() ; ++i) {
      if(quadratic_loss)
	our_derivatives[i] = loss_quadratic.deriv(x, raw_target, forward_sweep, f, df, i);
      else
	our_derivatives[i] = loss_ce.deriv(x, raw_target, forward_sweep, f, df, i);
	
    }
  
    // We finally compute the norm of the difference
    double error = 0.0;
    auto diter = derivatives.begin();
    for(auto& ourdi : our_derivatives) {
      error = (ourdi - *diter) * (ourdi - *diter);
      diter++;
    }
    error = sqrt(error);
    std::cout << "Error between the analytical and numerical gradients " << error << " with a step size of " << sqrt(norm_dh) << " in norm" << std::endl;
    if(error > 1e-7) 
      ++nbfails;

    /*
    std::cout << "numerical " << std::endl;
    for(auto & di : derivatives)
      std::cout << di << " ";
    std::cout << std::endl;
    std::cout << "our :" << std::endl;
    for(auto& di : our_derivatives)
      std::cout << di << " ";
    std::cout << std::endl;
    */

  }

  std::cout << nbfails << " / " << nbtrials << " with an error higher than 1e-7" << std::endl;
}
Esempio n. 12
0
int main(int argc, char **argv)
{
  char **dirname = NULL;
  int i,j=0,k,n,optf,p,q,dtotal,ftotal,colored = FALSE;
  struct stat st;
  char sizebuf[64], *stmp;
  off_t size = 0;
  mode_t mt;
  bool needfulltree;

  q = p = dtotal = ftotal = 0;
  aflag = dflag = fflag = lflag = pflag = sflag = Fflag = uflag = gflag = FALSE;
  Dflag = qflag = Nflag = Qflag = Rflag = hflag = Hflag = siflag = cflag = FALSE;
  noindent = force_color = nocolor = xdev = noreport = nolinks = reverse = FALSE;
  ignorecase = matchdirs = dirsfirst = inodeflag = devflag = Xflag = Jflag = FALSE;
  duflag = pruneflag = FALSE;
  flimit = 0;
  dirs = xmalloc(sizeof(int) * (maxdirs=4096));
  memset(dirs, 0, sizeof(int) * maxdirs);
  dirs[0] = 0;
  Level = -1;

  setlocale(LC_CTYPE, "");
  setlocale(LC_COLLATE, "");

  charset = getcharset();
  if (charset == NULL) {
    charset = "UTF-8";
  }

/* Until I get rid of this hack, make it linux/cygwin/HP nonstop only: */
#if defined (LINUX) || defined (CYGWIN) || defined (__TANDEM)
  mb_cur_max = (int)MB_CUR_MAX;
#else
  mb_cur_max = 1;
#endif

  memset(utable,0,sizeof(utable));
  memset(gtable,0,sizeof(gtable));
  memset(itable,0,sizeof(itable));

  optf = TRUE;
  for(n=i=1;i<argc;i=n) {
    n++;
    if (optf && argv[i][0] == '-' && argv[i][1]) {
      for(j=1;argv[i][j];j++) {
	switch(argv[i][j]) {
	case 'N':
	  Nflag = TRUE;
	  break;
	case 'q':
	  qflag = TRUE;
	  break;
	case 'Q':
	  Qflag = TRUE;
	  break;
	case 'd':
	  dflag = TRUE;
	  break;
	case 'l':
	  lflag = TRUE;
	  break;
	case 's':
	  sflag = TRUE;
	  break;
	case 'h':
	  hflag = TRUE;
	  sflag = TRUE; /* Assume they also want -s */
	  break;
	case 'u':
	  uflag = TRUE;
	  break;
	case 'g':
	  gflag = TRUE;
	  break;
	case 'f':
	  fflag = TRUE;
	  break;
	case 'F':
	  Fflag = TRUE;
	  break;
	case 'a':
	  aflag = TRUE;
	  break;
	case 'p':
	  pflag = TRUE;
	  break;
	case 'i':
	  noindent = TRUE;
	  _nl = "";
	  break;
	case 'C':
	  force_color = TRUE;
	  break;
	case 'n':
	  nocolor = TRUE;
	  break;
	case 'x':
	  xdev = TRUE;
	  break;
	case 'P':
	  if (argv[n] == NULL) {
	    fprintf(stderr,"tree: missing argument to -P option.\n");
	    exit(1);
	  }
	  pattern = argv[n++];
	  break;
	case 'I':
	  if (argv[n] == NULL) {
	    fprintf(stderr,"tree: missing argument to -I option.\n");
	    exit(1);
	  }
	  ipattern = argv[n++];
	  break;
	case 'A':
	  ansilines = TRUE;
	  break;
	case 'S':
	  charset = "IBM437";
	  break;
	case 'D':
	  Dflag = TRUE;
	  break;
	case 't':
	  cmpfunc = mtimesort;
	  break;
	case 'c':
	  cmpfunc = ctimesort;
	  cflag = TRUE;
	  break;
	case 'r':
	  reverse = TRUE;
	  break;
	case 'v':
	  cmpfunc = versort;
	  break;
	case 'U':
	  cmpfunc = NULL;
	  break;
	case 'X':
	  Hflag = FALSE;
	  Xflag = TRUE;
	  break;
	case 'J':
	  Jflag = TRUE;
	  break;
	case 'H':
	  Hflag = TRUE;
	  Xflag = FALSE;
	  if (argv[n] == NULL) {
	    fprintf(stderr,"tree: missing argument to -H option.\n");
	    exit(1);
	  }
	  host = argv[n++];
	  sp = "&nbsp;";
	  break;
	case 'T':
	  if (argv[n] == NULL) {
	    fprintf(stderr,"tree: missing argument to -T option.\n");
	    exit(1);
	  }
	  title = argv[n++];
	  break;
	case 'R':
	  Rflag = TRUE;
	  break;
	case 'L':
	  if ((sLevel = argv[n++]) == NULL) {
	    fprintf(stderr,"tree: Missing argument to -L option.\n");
	    exit(1);
	  }
	  Level = strtoul(sLevel,NULL,0)-1;
	  if (Level < 0) {
	    fprintf(stderr,"tree: Invalid level, must be greater than 0.\n");
	    exit(1);
	  }
	  break;
	case 'o':
	  if (argv[n] == NULL) {
	    fprintf(stderr,"tree: missing argument to -o option.\n");
	    exit(1);
	  }
	  outfilename = argv[n++];
	  break;
	case '-':
	  if (j == 1) {
	    if (!strcmp("--", argv[i])) {
	      optf = FALSE;
	      break;
	    }
	    if (!strcmp("--help",argv[i])) {
	      usage(2);
	      exit(0);
	    }
	    if (!strcmp("--version",argv[i])) {
	      char *v = version+12;
	      printf("%.*s\n",(int)strlen(v)-1,v);
	      exit(0);
	    }
	    if (!strcmp("--inodes",argv[i])) {
	      j = strlen(argv[i])-1;
	      inodeflag=TRUE;
	      break;
	    }
	    if (!strcmp("--device",argv[i])) {
	      j = strlen(argv[i])-1;
	      devflag=TRUE;
	      break;
	    }
	    if (!strcmp("--noreport",argv[i])) {
	      j = strlen(argv[i])-1;
	      noreport = TRUE;
	      break;
	    }
	    if (!strcmp("--nolinks",argv[i])) {
	      j = strlen(argv[i])-1;
	      nolinks = TRUE;
	      break;
	    }
	    if (!strcmp("--dirsfirst",argv[i])) {
	      j = strlen(argv[i])-1;
	      dirsfirst = TRUE;
	      break;
	    }
	    if (!strncmp("--filelimit",argv[i],11)) {
	      j = 11;
	      if (*(argv[i]+11) == '=') {
		if (*(argv[i]+12)) {
		  flimit=atoi(argv[i]+12);
		  j = strlen(argv[i])-1;
		  break;
		}
	      }
	      if (argv[n] != NULL) {
		flimit = atoi(argv[n++]);
		j = strlen(argv[i])-1;
	      } else {
		fprintf(stderr,"tree: missing argument to --filelimit\n");
		exit(1);
	      }
	      break;
	    }
	    if (!strncmp("--charset",argv[i],9)){
	      j = 9;
	      if (*(argv[i]+j) == '=') {
		if (*(charset = (argv[i]+10))) {
		  j = strlen(argv[i])-1;
		  break;
		}
	      }
	      if (argv[n] != NULL) {
		charset = argv[n++];
		j = strlen(argv[i])-1;
	      } else {
		initlinedraw(1);
		exit(1);
	      }
	      break;
	    }
	    if (!strncmp("--si", argv[i], 4)) {
	      j = strlen(argv[i])-1;
	      sflag = TRUE;
	      hflag = TRUE;
	      siflag = TRUE;
	      break;
	    }
	    if (!strncmp("--du",argv[i],4)) {
	      j = strlen(argv[i])-1;
	      sflag = TRUE;
	      duflag = TRUE;
	      break;
	    }
	    if (!strncmp("--prune",argv[i],7)) {
	      j = strlen(argv[i])-1;
	      pruneflag = TRUE;
	      break;
	    }
	    if (!strncmp("--timefmt",argv[i],9)) {
	      j = 9;
	      if (*(argv[i]+j) == '=') {
		if (*(argv[i]+ (++j))) {
		  timefmt=scopy(argv[i]+j);
		  j = strlen(argv[i])-1;
		  break;
		}
	      } else if (argv[n] != NULL) {
		timefmt = scopy(argv[n]);
		n++;
		j = strlen(argv[i])-1;
	      } else {
		fprintf(stderr,"tree: missing argument to --timefmt\n");
		exit(1);
	      }
	      Dflag = TRUE;
	      break;
	    }
	    if (!strncmp("--ignore-case",argv[i],13)) {
	      j = strlen(argv[i])-1;
	      ignorecase = TRUE;
	      break;
	    }
	    if (!strncmp("--matchdirs",argv[i],11)) {
	      j = strlen(argv[i])-1;
	      matchdirs = TRUE;
	      break;
	    }
	    if (!strncmp("--sort",argv[i],6)) {
	      j = 6;
	      if (*(argv[i]+j) == '=') {
		if (*(argv[i]+(++j))) {
		  stmp = argv[i]+j;
		  j = strlen(argv[i])-1;
		} else {
		  fprintf(stderr,"tree: missing argument to --sort=\n");
		  exit(1);
		}
	      } else if (argv[n] != NULL) {
		stmp = argv[n++];
	      } else {
		fprintf(stderr,"tree: missing argument to --sort\n");
		exit(1);
	      }
	      cmpfunc = (void *)1;
	      for(k=0;sorts[k].name;k++) {
		if (strcasecmp(sorts[k].name,stmp) == 0) {
		  cmpfunc = sorts[k].cmpfunc;
		  break;
		}
	      }
	      if (cmpfunc == (void *)1) {
		fprintf(stderr,"tree: sort type '%s' not valid, should be one of: ", stmp);
		for(k=0; sorts[k].name; k++)
		  printf("%s%c", sorts[k].name, sorts[k+1].name? ',': '\n');
		exit(1);
	      }
	      break;
	    }
	  }
	default:
	  fprintf(stderr,"tree: Invalid argument -`%c'.\n",argv[i][j]);
	  usage(1);
	  exit(1);
	  break;
	}
      }
    } else {
      if (!dirname) dirname = (char **)xmalloc(sizeof(char *) * (q=MINIT));
      else if (p == (q-2)) dirname = (char **)xrealloc(dirname,sizeof(char *) * (q+=MINC));
      dirname[p++] = scopy(argv[i]);
    }
  }
  if (p) dirname[p] = NULL;

  if (outfilename == NULL) {
#ifdef __EMX__
    _fsetmode(outfile=stdout,Hflag?"b":"t");
#else
    outfile = stdout;
#endif
  } else {
#ifdef __EMX__
    outfile = fopen(outfilename,Hflag?"wb":"wt");
#else
    outfile = fopen(outfilename,"w");
#endif
    if (outfile == NULL) {
      fprintf(stderr,"tree: invalid filename '%s'\n",outfilename);
      exit(1);
    }
  }

  parse_dir_colors();
  initlinedraw(0);

  needfulltree = duflag || pruneflag || matchdirs;

  /* Set our listdir function and sanity check options. */
  if (Hflag) {
    listdir = needfulltree ? html_rlistdir : html_listdir;
    Xflag = FALSE;
  } else if (Xflag) {
    listdir = needfulltree ? xml_rlistdir : xml_listdir;
    colorize = FALSE;
    colored = FALSE; /* Do people want colored XML output? */
  } else if (Jflag) {
    listdir = needfulltree ? json_rlistdir : json_listdir;
    colorize = FALSE;
    colored = FALSE; /* Do people want colored JSON output? */
  } else {
    listdir = needfulltree ? unix_rlistdir : unix_listdir;
  }
  if (dflag) pruneflag = FALSE;	/* You'll just get nothing otherwise. */


  if (Rflag && (Level == -1))
    Rflag = FALSE;

  if (Hflag) {
    emit_html_header(charset, title, version);

    fflag = FALSE;
    if (nolinks) {
      if (force_color) fprintf(outfile, "<b class=\"NORM\">%s</b>",host);
      else fprintf(outfile,"%s",host);
    } else {
      if (force_color) fprintf(outfile,"<a class=\"NORM\" href=\"%s\">%s</a>",host,host);
      else fprintf(outfile,"<a href=\"%s\">%s</a>",host,host);
    }
    curdir = gnu_getcwd();
  } else if (Xflag) {
    fprintf(outfile,"<?xml version=\"1.0\"");
    if (charset) fprintf(outfile," encoding=\"%s\"",charset);
    fprintf(outfile,"?>%s<tree>%s",_nl,_nl);
  } else if (Jflag)
    fputc('[',outfile);

  if (dirname) {
    for(colored=i=0;dirname[i];i++,colored=0) {
      if (fflag) {
	do {
	  j=strlen(dirname[i]);
	  if (j > 1 && dirname[i][j-1] == '/') dirname[i][--j] = 0;
	} while (j > 1 && dirname[i][j-1] == '/');
      }
      if ((n = lstat(dirname[i],&st)) >= 0) {
	saveino(st.st_ino, st.st_dev);
	if (colorize) colored = color(st.st_mode,dirname[i],n<0,FALSE);
	size += st.st_size;
      }
      if (Xflag || Jflag) {
	mt = st.st_mode & S_IFMT;
	for(j=0;ifmt[j];j++)
	  if (ifmt[j] == mt) break;
        if (Xflag)
	  fprintf(outfile,"%s<%s name=\"%s\">", noindent?"":"  ", ftype[j], dirname[i]);
        else if (Jflag) {
	  if (i) fprintf(outfile, ",");
          fprintf(outfile,"%s{\"type\":\"%s\",\"name\":\"%s\",\"contents\":[", noindent?"":"\n  ", ftype[j], dirname[i]);
	}
      } else if (!Hflag) printit(dirname[i]);
      if (colored) fprintf(outfile,"%s",endcode);
      if (!Hflag) size += listdir(dirname[i],&dtotal,&ftotal,0,0);
      else {
	if (chdir(dirname[i])) {
	  fprintf(outfile,"%s [error opening dir]\n",dirname[i]);
	  exit(1);
	} else {
	  size += listdir(".",&dtotal,&ftotal,0,0);
	  chdir(curdir);
	}
      }
      if (Xflag) fprintf(outfile,"%s</%s>\n",noindent?"":"  ", ftype[j]);
      if (Jflag) fprintf(outfile,"%s]}",noindent?"":"  ");
    }
  } else {
    if ((n = lstat(".",&st)) >= 0) {
      saveino(st.st_ino, st.st_dev);
      if (colorize) colored = color(st.st_mode,".",n<0,FALSE);
      size = st.st_size;
    }
    if (Xflag) fprintf(outfile,"%s<directory name=\".\">",noindent?"":"  ");
    else if (Jflag) fprintf(outfile, "{\"type\":\"directory\",\"name\": \".\",\"contents\":[");
    else if (!Hflag) fprintf(outfile,".");
    if (colored) fprintf(outfile,"%s",endcode);
    size += listdir(".",&dtotal,&ftotal,0,0);
    if (Xflag) fprintf(outfile,"%s</directory>%s",noindent?"":"  ", _nl);
    if (Jflag) fprintf(outfile,"%s]}",noindent?"":"  ");
  }

  if (Hflag)
    fprintf(outfile,"\t<br><br>\n\t</p>\n\t<p>\n");

  if (!noreport) {
    if (Xflag) {
      fprintf(outfile,"%s<report>%s",noindent?"":"  ", _nl);
      if (duflag) fprintf(outfile,"%s<size>%lld</size>%s", noindent?"":"    ", (long long int)size, _nl);
      fprintf(outfile,"%s<directories>%d</directories>%s", noindent?"":"    ", dtotal, _nl);
      if (!dflag) fprintf(outfile,"%s<files>%d</files>%s", noindent?"":"    ", ftotal, _nl);
      fprintf(outfile,"%s</report>%s",noindent?"":"  ", _nl);
    } else if (Jflag) {
      fprintf(outfile, ",%s{\"type\":\"report\"",noindent?"":"\n  ");
      if (duflag) fprintf(outfile,",\"size\":%lld", (long long int)size);
      fprintf(outfile,",\"directories\":%d", dtotal);
      if (!dflag) fprintf(outfile,",\"files\":%d", ftotal);
      fprintf(outfile, "}");
    } else {
      if (duflag) {
	psize(sizebuf, size);
	fprintf(outfile,"\n%s%s used in ", sizebuf, hflag || siflag? "" : " bytes");
      } else fputc('\n', outfile);
      if (dflag)
	fprintf(outfile,"%d director%s\n",dtotal,(dtotal==1? "y":"ies"));
      else
	fprintf(outfile,"%d director%s, %d file%s\n",dtotal,(dtotal==1? "y":"ies"),ftotal,(ftotal==1? "":"s"));
    }
  }

  if (Hflag) {
    fprintf(outfile,"\t<br><br>\n\t</p>\n");
    fprintf(outfile,"\t<hr>\n");
    fprintf(outfile,"\t<p class=\"VERSION\">\n");
    fprintf(outfile,hversion,linedraw->copy, linedraw->copy, linedraw->copy, linedraw->copy);
    fprintf(outfile,"\t</p>\n");
    fprintf(outfile,"</body>\n");
    fprintf(outfile,"</html>\n");
  } else if (Xflag) {
    fprintf(outfile,"</tree>\n");
  } else if (Jflag) {
      fprintf(outfile, "%s]\n",_nl);
  }

  if (outfilename != NULL) fclose(outfile);

  return 0;
}