예제 #1
0
        geometry_ptr read_multipolygon()
        {
            geometry_ptr poly(new polygon<vertex2d>(srid_));

            int num_polys=read_integer();
            for (int i=0;i<num_polys;++i)
            {
                pos_+=5;
                int num_rings=read_integer();
                for (int i=0;i<num_rings;++i)
                {
                    int num_points=read_integer();
                    CoordinateArray ar(num_points);
                    read_coords(ar);
                    poly->move_to(ar[0].x,ar[0].y);
                    for (int j=1;j<num_points;++j)
                    {
                        poly->line_to(ar[j].x,ar[j].y);
                    }
                    poly->line_to(ar[0].x,ar[0].y);
                }
            }
            return poly;
        }
예제 #2
0
nsresult
nsDOMWorkerScriptLoader::ExecuteScripts(JSContext* aCx)
{
  NS_ASSERTION(aCx, "Shouldn't be null!");

  // Now execute all the scripts.
  for (PRUint32 index = 0; index < mScriptCount; index++) {
    ScriptLoadInfo& loadInfo = mLoadInfos[index];

    JSAutoRequest ar(aCx);

    JSScript* script =
      static_cast<JSScript*>(JS_GetPrivate(aCx, loadInfo.scriptObj.ToJSObject()));
    NS_ASSERTION(script, "This shouldn't ever be null!");

    JSObject* global = mWorker->mGlobal ?
                       mWorker->mGlobal :
                       JS_GetGlobalObject(aCx);
    NS_ENSURE_STATE(global);

    // Because we may have nested calls to this function we don't want the
    // execution to automatically report errors. We let them propagate instead.
    uint32 oldOpts =
      JS_SetOptions(aCx, JS_GetOptions(aCx) | JSOPTION_DONT_REPORT_UNCAUGHT);

    jsval val;
    PRBool success = JS_ExecuteScript(aCx, global, script, &val);

    JS_SetOptions(aCx, oldOpts);

    if (!success) {
      return NS_ERROR_FAILURE;
    }
  }
  return NS_OK;
}
예제 #3
0
void CaIeaDataForLoadSave::LoadData (CaIEAInfo* pIEAData, CString& strFile)
{
	try
	{
		CFile f((LPCTSTR)strFile, CFile::shareDenyNone|CFile::modeRead);
		CArchive ar(&f, CArchive::load);
		Serialize (ar);
		ar.Flush();
		ar.Close();
		f.Close();
	}
	catch (CFileException* e)
	{
		throw e;
	}
	catch (CArchiveException* e)
	{
		throw e;
	}
	catch(...)
	{
		AfxMessageBox (_T("Serialization error. \nCause: Unknown."), MB_OK|MB_ICONEXCLAMATION);
	}
}
예제 #4
0
bool TRoleManager::loadData( char const* path )
{
	roleTable.clear();
	roleList.clear();
	try
	{
		std::ifstream fs( path );
		boost::archive::text_iarchive ar(fs);

		ar & roleList ;
		ar & roleTable;

	}
	catch ( ... )
	{
		roleTable.clear();
		roleList.clear();

		initDefultRole();

		return false;
	}
	return true;
}
예제 #5
0
bool GrBatchTextStrike::addGlyphToAtlas(GrDrawBatch::Target* target, GrGlyph* glyph,
                                        GrFontScaler* scaler, const SkGlyph& skGlyph,
                                        GrMaskFormat expectedMaskFormat) {
    SkASSERT(glyph);
    SkASSERT(scaler);
    SkASSERT(fCache.find(glyph->fPackedID));

    SkAutoUnref ar(SkSafeRef(scaler));

    int bytesPerPixel = GrMaskFormatBytesPerPixel(expectedMaskFormat);

    size_t size = glyph->fBounds.area() * bytesPerPixel;
    SkAutoSMalloc<1024> storage(size);

    if (GrGlyph::kDistance_MaskStyle == GrGlyph::UnpackMaskStyle(glyph->fPackedID)) {
        if (!scaler->getPackedGlyphDFImage(skGlyph, glyph->width(), glyph->height(),
                                           storage.get())) {
            return false;
        }
    } else {
        if (!scaler->getPackedGlyphImage(skGlyph, glyph->width(), glyph->height(),
                                         glyph->width() * bytesPerPixel, expectedMaskFormat,
                                         storage.get())) {
            return false;
        }
    }

    bool success = fBatchFontCache->addToAtlas(this, &glyph->fID, target, expectedMaskFormat,
                                               glyph->width(), glyph->height(),
                                               storage.get(), &glyph->fAtlasLocation);
    if (success) {
        SkASSERT(GrBatchAtlas::kInvalidAtlasID != glyph->fID);
        fAtlasedGlyphs++;
    }
    return success;
}
예제 #6
0
BOOL SLZWindowSetDlg::ReadStaffInfoFromFile()
{
	CFile file;
	CFileException e;
	if (file.Open(m_staffinfo_path,CFile::modeRead,&e))
	{
		SLZStaff* staffinfo=NULL;
		CArchive ar(&file,CArchive::load);
		if (file.GetLength()) 
			do
			{
				ar>>staffinfo;
				if (staffinfo)
				{
					m_map_staff[m_cs_LogStaff.AddString(staffinfo->GetStaffName())-1]
					= *staffinfo;
					delete staffinfo;
					staffinfo = NULL;
				}
			}while(!ar.IsBufferEmpty());
			ar.Close();
			file.Close();
			return TRUE;
	}
nsresult xpcJSWeakReference::Init(JSContext* cx, const JS::Value& object)
{
    JSAutoRequest ar(cx);

    if (!object.isObject())
        return NS_ERROR_FAILURE;

    JSObject& obj = object.toObject();

    XPCCallContext ccx(NATIVE_CALLER, cx);

    nsRefPtr<nsXPCWrappedJS> wrapped;
    nsresult rv = nsXPCWrappedJS::GetNewOrUsed(ccx,
                                               &obj,
                                               NS_GET_IID(nsISupports),
                                               nsnull,
                                               getter_AddRefs(wrapped));
    if (!wrapped) {
        NS_ERROR("can't get nsISupportsWeakReference wrapper for obj");
        return rv;
    }

    return wrapped->GetWeakReference(getter_AddRefs(mWrappedJSObject));
}
예제 #8
0
BOOL CDownloadGroups::Save(BOOL bForce)
{
	CSingleLock pLock( &m_pSection, TRUE );

	if ( ! bForce && m_nBaseCookie == m_nSaveCookie ) return FALSE;
	m_nSaveCookie = m_nBaseCookie;

	CString strPath = Settings.General.UserPath + _T("\\Data\\DownloadGroups.dat");
	DeleteFile( strPath + _T(".tmp") );

	CFile pFile;
	if ( ! pFile.Open( strPath + _T(".tmp"), CFile::modeWrite | CFile::modeCreate ) ) return FALSE;

	BYTE* pBuffer = new BYTE[ 4096 ];

	try
	{
		CArchive ar( &pFile, CArchive::store, 4096, pBuffer );
		Serialize( ar );
	}
	catch ( CException* pException )
	{
		delete [] pBuffer;
		pException->Delete();
		return FALSE;
	}

	delete [] pBuffer;

	pFile.Close();

	DeleteFile( strPath );
	MoveFile( strPath + _T(".tmp"), strPath );

	return TRUE;
}
예제 #9
0
BOOL CDocument::OnSaveDocument( LPCTSTR lpszPathName )
/****************************************************/
{
    CFileException ex;
    CFile *pFile = GetFile( lpszPathName, CFile::modeCreate | CFile::modeWrite, &ex );
    if( pFile == NULL ) {
        ReportSaveLoadException( lpszPathName, &ex, TRUE, AFX_IDP_FAILED_TO_SAVE_DOC );
        return( FALSE );
    }
    try {
        CArchive ar( pFile, CArchive::store );
        Serialize( ar );
        ar.Close();
        SetPathName( lpszPathName );
        SetTitle( pFile->GetFileTitle() );
        ReleaseFile( pFile, FALSE );
    } catch( CException *pEx ) {
        ReportSaveLoadException( lpszPathName, pEx, TRUE, AFX_IDP_FAILED_TO_SAVE_DOC );
        ReleaseFile( pFile, TRUE );
        return( FALSE );
    }
    SetModifiedFlag( FALSE );
    return( TRUE );
}
예제 #10
0
/////////////////////////////////////////////////////////////////////////////
// load a map from the database into the current map file
/////////////////////////////////////////////////////////////////////////////
void CMapDatabase::loadMap(int iMap)
{
	CFile file;

	//open the database file
	if(!file.Open(FILE_MAP, CFile::modeRead)) 
	{
		return;
	}

	//seek to this position in the game file
	file.Seek(m_dwOffsets[iMap], CFile::begin);
	CArchive ar(&file, CArchive::load);

	//load the file version
	ar >> m_fVer;
	
	//read the game data
	m_Map.Serialize(ar);

	//cleanup
	ar.Close();
	file.Close();
}
예제 #11
0
void berkeleydb_store<Object>::put_range(const std::vector<timestamp>& keys,
                                         const std::vector<obj_ptr>& values,
                                         const long lp_id) {
  boost::lock_guard<boost::mutex> guard(put_mutex_);
  for (int i = 0; i < keys.size(); ++i) {
    /* generate key */
    std::vector<char> key;
    key_lpid_to_char(keys[i], lp_id, key);

    /* serialize object */
    std::stringstream ss;
    boost::archive::binary_oarchive ar(ss);
    ar << *(values[i]);
    std::string binary = ss.str();
    std::vector<char> put_event_binary(binary.begin(), binary.end());

    Dbt db_key(&key[0], key.size());
    Dbt data(&put_event_binary[0], put_event_binary.size());
    DbTxn* txn = NULL;
    env->txn_begin(NULL, &txn, 0);
    int ret = db->put(txn, &db_key, &data, 0);
    txn->commit(0);
  }
};
예제 #12
0
BOOL CHashDatabase::GetED2K(DWORD nIndex, CED2K* pSet)
{
	pSet->Clear();

	CSingleLock pLock( &m_pSection, TRUE );
	if ( m_bOpen == FALSE ) return FALSE;

	HASHDB_INDEX* pIndex = Lookup( nIndex, HASH_ED2K );
	if ( pIndex == NULL ) return FALSE;

	try
	{
		m_pFile.Seek( pIndex->nOffset, 0 );
		CArchive ar( &m_pFile, CArchive::load );
		pSet->Serialize( ar );
	}
	catch ( CException* pException )
	{
		pException->Delete();
		return FALSE;
	}

	return TRUE;
}
예제 #13
0
bool COleDBConnectionProp::LoadFromFile(LPCTSTR FileName)
{
	LPCTSTR iniFileName = FileName;
	try
	{
		CFile file(iniFileName,CFile::modeRead);
		CArchive ar(&file,CArchive::load);
		Serialize(ar);
	}
	catch(CFileException *ex)
	{
		ex->Delete();
		return false;

	}
	catch(CArchiveException *exAr)
	{
		exAr->Delete();
		return false;

	}

	return true;
}
void reach_client::delete_verts()
{

    double x1 = std::min(square1_.x, square2_.x);
    double y1 = std::min(square1_.y, square2_.y);
    double x2 = std::max(square1_.x, square2_.x);
    double y2 = std::max(square1_.y, square2_.y);


    reach_graph *dst = new reach_graph();

    my_graph::graph_filter<reach_vertex_data, reach_edge_data> filter;
    filter.set_verts_filter([&](my_graph::vertex_id id) -> bool 
    {
        const reach_vertex& v = pgraph_->get_vertex(id);
        const vis_coord &c = v.get_data().c;
        return (c.x >= x1 && c.y >= y1 && c.x <= x2 && c.y <= y2);
    });

    filter.filter_graph(*pgraph_, *dst);
    
    pgraph_.reset(dst);
    free_vb(g_desc.vb);
    free_ib(g_desc.ib);

    g_desc = upload_graph(*pgraph_);

    cout << "saving graph...";
    std::ofstream ofs ("cropped.szd", std::ios_base::out | std::ios_base::binary);
    boost::archive::binary_oarchive ar (ofs);
    ar << *pgraph_;
    cout << "done" << endl;


    selected_.reset();
}
  nsresult Init()
  {
    mRuntime = JS_NewRuntime(sRuntimeHeapSize, JS_NO_HELPER_THREADS);
    NS_ENSURE_TRUE(mRuntime, NS_ERROR_OUT_OF_MEMORY);

    mContext = JS_NewContext(mRuntime, 0);
    NS_ENSURE_TRUE(mContext, NS_ERROR_OUT_OF_MEMORY);

    JSAutoRequest ar(mContext);

    mGlobal = JS_NewGlobalObject(mContext, &sGlobalClass, nullptr);
    NS_ENSURE_TRUE(mGlobal, NS_ERROR_OUT_OF_MEMORY);

    JS_SetGlobalObject(mContext, mGlobal);
    JS_InitStandardClasses(mContext, mGlobal);

    JS_SetVersion(mContext, JSVERSION_LATEST);
    JS_SetErrorReporter(mContext, PACErrorReporter);

    if (!JS_DefineFunctions(mContext, mGlobal, PACGlobalFunctions))
      return NS_ERROR_FAILURE;

    return NS_OK;
  }
예제 #16
0
파일: xec.c 프로젝트: Requaos/harvey
static void
jump(Iarg *to)
{
	print_func_entry();
	Cpu *cpu;

	cpu = to->cpu;
	switch(to->atype){
	default:
		abort();
	case AMp:
		to = afar(to, 1, to->len);
	case AAp:
		cpu->reg[RCS] = to->seg;
	case AJb:
	case AJv:
		cpu->reg[RIP] = to->off;
		break;
	case AEv:
		cpu->reg[RIP] = ar(to);
		break;
	}
	print_func_exit();
}
예제 #17
0
nsresult
nsXBLProtoImplAnonymousMethod::Execute(nsIContent* aBoundElement)
{
    NS_PRECONDITION(IsCompiled(), "Can't execute uncompiled method");

    if (!mJSMethodObject) {
        // Nothing to do here
        return NS_OK;
    }

    // Get the script context the same way
    // nsXBLProtoImpl::InstallImplementation does.
    nsIDocument* document = aBoundElement->OwnerDoc();

    nsIScriptGlobalObject* global = document->GetScriptGlobalObject();
    if (!global) {
        return NS_OK;
    }

    nsCOMPtr<nsIScriptContext> context = global->GetContext();
    if (!context) {
        return NS_OK;
    }

    JSContext* cx = context->GetNativeContext();

    JSObject* globalObject = global->GetGlobalJSObject();

    nsCOMPtr<nsIXPConnectJSObjectHolder> wrapper;
    jsval v;
    nsresult rv =
        nsContentUtils::WrapNative(cx, globalObject, aBoundElement, &v,
                                   getter_AddRefs(wrapper));
    NS_ENSURE_SUCCESS(rv, rv);

    JSObject* thisObject = JSVAL_TO_OBJECT(v);

    JSAutoRequest ar(cx);
    JSAutoEnterCompartment ac;

    if (!ac.enter(cx, thisObject))
        return NS_ERROR_UNEXPECTED;

    // Clone the function object, using thisObject as the parent so "this" is in
    // the scope chain of the resulting function (for backwards compat to the
    // days when this was an event handler).
    JSObject* method = ::JS_CloneFunctionObject(cx, mJSMethodObject, thisObject);
    if (!method)
        return NS_ERROR_OUT_OF_MEMORY;

    // Now call the method

    // Use nsCxPusher to make sure we call ScriptEvaluated when we're done.
    nsCxPusher pusher;
    NS_ENSURE_STATE(pusher.Push(aBoundElement));

    // Check whether it's OK to call the method.
    rv = nsContentUtils::GetSecurityManager()->CheckFunctionAccess(cx, method,
            thisObject);

    JSBool ok = JS_TRUE;
    if (NS_SUCCEEDED(rv)) {
        jsval retval;
        ok = ::JS_CallFunctionValue(cx, thisObject, OBJECT_TO_JSVAL(method),
                                    0 /* argc */, nsnull /* argv */, &retval);
    }

    if (!ok) {
        // If a constructor or destructor threw an exception, it doesn't stop
        // anything else.  We just report it.  Note that we need to set aside the
        // frame chain here, since the constructor invocation is not related to
        // whatever is on the stack right now, really.
        JSBool saved = JS_SaveFrameChain(cx);
        JS_ReportPendingException(cx);
        if (saved)
            JS_RestoreFrameChain(cx);
        return NS_ERROR_FAILURE;
    }

    return NS_OK;
}
예제 #18
0
nsresult
ProxyAutoConfig::SetupJS()
{
  mJSNeedsSetup = false;
  NS_ABORT_IF_FALSE(!sRunning, "JIT is running");

  delete mJSRuntime;
  mJSRuntime = nullptr;

  if (mPACScript.IsEmpty())
    return NS_ERROR_FAILURE;

  mJSRuntime = JSRuntimeWrapper::Create();
  if (!mJSRuntime)
    return NS_ERROR_FAILURE;

  JSAutoRequest ar(mJSRuntime->Context());
  JSAutoCompartment ac(mJSRuntime->Context(), mJSRuntime->Global());

  // check if this is a data: uri so that we don't spam the js console with
  // huge meaningless strings. this is not on the main thread, so it can't
  // use nsIRUI scheme methods
  bool isDataURI = nsDependentCSubstring(mPACURI, 0, 5).LowerCaseEqualsASCII("data:", 5);

  sRunning = this;
  JS::Rooted<JSObject *> global(mJSRuntime->Context(), mJSRuntime->Global());
  JS::CompileOptions options(mJSRuntime->Context());
  options.setFileAndLine(mPACURI.get(), 1);
  JSScript *script = JS_CompileScript(mJSRuntime->Context(), global,
                                      mPACScript.get(), mPACScript.Length(),
                                      options);
  if (!script ||
      !JS_ExecuteScript(mJSRuntime->Context(), mJSRuntime->Global(), script, nullptr)) {
    nsString alertMessage(NS_LITERAL_STRING("PAC file failed to install from "));
    if (isDataURI) {
      alertMessage += NS_LITERAL_STRING("data: URI");
    }
    else {
      alertMessage += NS_ConvertUTF8toUTF16(mPACURI);
    }
    PACLogToConsole(alertMessage);
    sRunning = nullptr;
    return NS_ERROR_FAILURE;
  }
  sRunning = nullptr;

  mJSRuntime->SetOK();
  nsString alertMessage(NS_LITERAL_STRING("PAC file installed from "));
  if (isDataURI) {
    alertMessage += NS_LITERAL_STRING("data: URI");
  }
  else {
    alertMessage += NS_ConvertUTF8toUTF16(mPACURI);
  }
  PACLogToConsole(alertMessage);

  // we don't need these now
  mPACScript.Truncate();
  mPACURI.Truncate();

  return NS_OK;
}
예제 #19
0
 void operator()(T const & value) const
 {
   ar( _CEREAL_NVP("data", value) );
 }
예제 #20
0
void Knob::paintEvent(QPaintEvent* /*ev*/)
      {
#if 0 // yet(?) unused
      QRect rr(ev->rect());
#endif
      QPainter p(this);
      p.setRenderHint(QPainter::Antialiasing, true);

      int markSize2  = _markSize/2;
      int restR      = 360      - _scaleSize;
      int w          = width()  - _scaleWidth - 2 * _border;
      int h          = height() - _scaleWidth/2 - 2 * _border;

      int xoffset, yoffset;
      if (_center)
            h -= _markSize;
      if (w > h) {
            yoffset = 0;
            xoffset = (w - h) / 2;
            w = h;
            }
      else {
            xoffset = 0;
            // yoffset = (h - w) / 2;     // center
            yoffset = h - w;              // top align
            h = w;
            }

      int x = xoffset + _scaleWidth / 2 + _border;
      int y = yoffset + _scaleWidth / 2 + _border + (_center ? _markSize+_scaleWidth/2 : 0);
      QRectF ar(x, y, w, h);

      QColor sc(isEnabled() ? _scaleColor : Qt::gray);
      QColor svc(isEnabled() ? _scaleValueColor : Qt::gray);

      //-----------------------------------------
      // draw arc
      //-----------------------------------------

      double dvalue = maxValue() - minValue();
      if (_center) {
            int size = _scaleSize * 8;
            if (_value >= 0) {
                  int offset = (restR-180) * 8;
                  int r1 = int (size * _value / maxValue());
                  int r2 = size - r1;
                  p.setPen(QPen(sc, _scaleWidth));
                  if (r2 > 1)
                        p.drawArc(ar, offset, r2);
                  if (size > 1)
                        p.drawArc(ar, 90*16, size);
                  if (r1 > 1) {
                        p.setPen(QPen(svc, _scaleWidth));
                        p.drawArc(ar, offset+r2, r1);
                        }
                  }
            else {
                  // int offset = (restR+180) * 8;
                  int r1 = int(size * _value / minValue());
                  int r2 = size - r1;

                  p.setPen(QPen(sc, _scaleWidth));
                  if (size > 1)
                        p.drawArc(ar, (restR-180)*8, size);
                  if (r2 > 1)
                        p.drawArc(ar, 90 * 16 + r1, r2);
                  if (r1 > 1) {
                        p.setPen(QPen(svc, _scaleWidth));
                        p.drawArc(ar, 90*16, r1);
                        }
                  }
            }
      else {
            int offset = (180-restR) * 8;
            int size   = _scaleSize * 16;
            int r1     = int(size * (_value - minValue()) / dvalue);
            int r2     = size - r1;
            if (r2 >= 1) {
                  p.setPen(QPen(sc, _scaleWidth));
                  p.drawArc(ar, -offset, r2);
                  }
            if (r1 >= 1) {
                  p.setPen(QPen(svc, _scaleWidth));
                  p.drawArc(ar, r2-offset, r1);
                  }
            }

      //-----------------------------------------
      // draw pointer
      //-----------------------------------------

      p.setPen(QPen(svc, _scaleWidth));
      double r1 = double(_scaleSize) * (_value-minValue()) / dvalue + 90.0
            + double(restR/2);
      r1     = r1 / 180.0 * M_PI;   // convert to radians
      int rd = w/2;
      int x1 = x + rd;
      int y1 = y + rd;
      int x2 = x1 + lrint(cos(r1) * double(rd));
      int y2 = y1 + lrint(sin(r1) * double(rd));
      p.drawLine(x1, y1, x2, y2);

      //-----------------------------------------
      // draw center mark
      //-----------------------------------------

      p.setPen(QPen(svc, 0));
      p.setBrush(svc);
      if (_center) {
            if (points)
                  delete points;
            qreal x = ar.width() / 2 + ar.x();
            qreal y = ar.y() - _markSize - _scaleWidth/2;
            points = new QPainterPath(QPointF(x - markSize2, y));
            points->lineTo(x + markSize2, y);
            points->lineTo(x, _markSize + y);
            points->closeSubpath();
            p.drawPath(*points);
            }

      //-----------------------------------------
      // draw text
      //-----------------------------------------

      if (!_text.isEmpty()) {
            p.drawText(ar, Qt::AlignBottom | Qt::AlignHCenter, _text);
            }
      }
예제 #21
0
// ######################################################################
int main()
{
  std::cout << std::boolalpha << std::endl;

  {
    std::ofstream os("file.json");
    cereal::JSONOutputArchive oar( os );

    //auto f = std::make_shared<Fixture>();
    //auto f2 = f;
    //oar( f );
    //oar( f2 );
    Stuff s; s.fillData();
    oar( cereal::make_nvp("best data ever", s) );
  }

  {
    std::ifstream is("file.json");
    std::string str((std::istreambuf_iterator<char>(is)), std::istreambuf_iterator<char>());
    std::cout << "---------------------" << std::endl << str << std::endl << "---------------------" << std::endl;
  }

  // playground
  {
    cereal::JSONOutputArchive archive( std::cout );
    bool arr[] = {true, false};
    std::vector<int> vec = {1, 2, 3, 4, 5};
    archive( CEREAL_NVP(vec),
        arr );
    auto f = std::make_shared<Fixture>();
    auto f2 = f;
    archive( f );
    archive( f2 );
  }

  // test out of order
  std::stringstream oos;
  {
    cereal::JSONOutputArchive ar(oos);
    cereal::JSONOutputArchive ar2(std::cout,
        cereal::JSONOutputArchive::Options(2, cereal::JSONOutputArchive::Options::IndentChar::space, 2) );

    ar( cereal::make_nvp( "1", 1 ),
        cereal::make_nvp( "2", 2 ),
        3,
        0, // unused
        cereal::make_nvp( "4", 4 ),
        cereal::make_nvp( "5", 5 ) );

    int x = 33;
    ar.saveBinaryValue( &x, sizeof(int), "bla" );

    ar2( cereal::make_nvp( "1", 1 ),
         cereal::make_nvp( "2", 2 ),
         3,
         0, // unused
         cereal::make_nvp( "4", 4 ),
         cereal::make_nvp( "5", 5 ) );
    ar2.saveBinaryValue( &x, sizeof(int), "bla" );

    OOJson oo( 1, 2, true, 4.2 );
    ar( CEREAL_NVP(oo) );
    ar2( CEREAL_NVP(oo) );

    // boost stuff
    ar & cereal::make_nvp("usingop&", oo ) & 6;
    ar << 5 << 4 << 3;

    ar2 & cereal::make_nvp("usingop&", oo ) & 6;
    ar2 << 5 << 4 << 3;

    long double ld = std::numeric_limits<long double>::max();
    long long ll = std::numeric_limits<long long>::max();
    unsigned long long ull = std::numeric_limits<unsigned long long>::max();

    ar( CEREAL_NVP(ld),
        CEREAL_NVP(ll),
        CEREAL_NVP(ull) );

    ar2( CEREAL_NVP(ld),
         CEREAL_NVP(ll),
         CEREAL_NVP(ull) );
  }

  {
    cereal::JSONInputArchive ar(oos);
    int i1, i2, i3, i4, i5, x;

    ar( i1 );
    ar( cereal::make_nvp( "2", i2 ), i3 );

    ar( cereal::make_nvp( "4", i4 ),
        i5 );

    ar.loadBinaryValue( &x, sizeof(int) );

    OOJson ii;
    ar( cereal::make_nvp("oo", ii) );
    ar( cereal::make_nvp( "2", i2 ) );

    std::cout << i1 << " " << i2 << " " << i3 << " " << i4 << " " << i5 << std::endl;
    std::cout << x << std::endl;
    std::cout << ii.a << " " << ii.b << " " << ii.c.first << " " << ii.c.second << " ";
    for( auto z : ii.d )
      std::cout << z << " ";
    std::cout << std::endl;

    OOJson oo;
    ar >> cereal::make_nvp("usingop&", oo );
    std::cout << oo.a << " " << oo.b << " " << oo.c.first << " " << oo.c.second << " ";
    for( auto z : oo.d )
      std::cout << z << " ";

    int aa, a, b, c;
    ar & aa & a & b & c;
    std::cout << aa << " " << a << " " << b << " " << c << std::endl;

    long double ld;
    long long ll;
    unsigned long long ull;

    ar( CEREAL_NVP(ld),
        CEREAL_NVP(ll),
        CEREAL_NVP(ull) );

    std::cout << (ld  == std::numeric_limits<long double>::max()) << std::endl;
    std::cout << (ll  == std::numeric_limits<long long>::max()) << std::endl;
    std::cout << (ull == std::numeric_limits<unsigned long long>::max()) << std::endl;
  }

  return 0;
}
예제 #22
0
nsresult
nsJSON::DecodeInternal(JSContext* cx,
                       nsIInputStream *aStream,
                       int32_t aContentLength,
                       bool aNeedsConverter,
                       JS::Value* aRetval,
                       DecodingMode mode /* = STRICT */)
{
  JSAutoRequest ar(cx);

  // Consume the stream
  nsCOMPtr<nsIChannel> jsonChannel;
  if (!mURI) {
    NS_NewURI(getter_AddRefs(mURI), NS_LITERAL_CSTRING("about:blank"), 0, 0 );
    if (!mURI)
      return NS_ERROR_OUT_OF_MEMORY;
  }

  nsresult rv =
    NS_NewInputStreamChannel(getter_AddRefs(jsonChannel), mURI, aStream,
                             NS_LITERAL_CSTRING("application/json"));
  if (!jsonChannel || NS_FAILED(rv))
    return NS_ERROR_FAILURE;

  nsRefPtr<nsJSONListener> jsonListener =
    new nsJSONListener(cx, aRetval, aNeedsConverter, mode);

  //XXX this stream pattern should be consolidated in netwerk
  rv = jsonListener->OnStartRequest(jsonChannel, nullptr);
  if (NS_FAILED(rv)) {
    jsonChannel->Cancel(rv);
    return rv;
  }

  nsresult status;
  jsonChannel->GetStatus(&status);
  uint64_t offset = 0;
  while (NS_SUCCEEDED(status)) {
    uint64_t available;
    rv = aStream->Available(&available);
    if (rv == NS_BASE_STREAM_CLOSED) {
      rv = NS_OK;
      break;
    }
    if (NS_FAILED(rv)) {
      jsonChannel->Cancel(rv);
      break;
    }
    if (!available)
      break; // blocking input stream has none available when done

    if (available > UINT32_MAX)
      available = UINT32_MAX;

    rv = jsonListener->OnDataAvailable(jsonChannel, nullptr,
                                       aStream,
                                       offset,
                                       (uint32_t)available);
    if (NS_FAILED(rv)) {
      jsonChannel->Cancel(rv);
      break;
    }

    offset += available;
    jsonChannel->GetStatus(&status);
  }
  NS_ENSURE_SUCCESS(rv, rv);

  rv = jsonListener->OnStopRequest(jsonChannel, nullptr, status);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}
nsresult 
nsXBLProtoImplProperty::CompileMember(nsIScriptContext* aContext, const nsCString& aClassStr,
                                      JSObject* aClassObject)
{
  NS_PRECONDITION(!mIsCompiled,
                  "Trying to compile an already-compiled property");
  NS_PRECONDITION(aClassObject,
                  "Must have class object to compile");

  if (!mName)
    return NS_ERROR_FAILURE; // Without a valid name, we can't install the member.

  // We have a property.
  nsresult rv = NS_OK;

  nsAutoCString functionUri;
  if (mGetterText || mSetterText) {
    functionUri = aClassStr;
    int32_t hash = functionUri.RFindChar('#');
    if (hash != kNotFound) {
      functionUri.Truncate(hash);
    }
  }

  bool deletedGetter = false;
  if (mGetterText && mGetterText->GetText()) {
    nsDependentString getter(mGetterText->GetText());
    if (!getter.IsEmpty()) {
      // Compile into a temp object so we don't wipe out mGetterText
      JSObject* getterObject = nullptr;
      JSContext* cx = aContext->GetNativeContext();
      JSAutoRequest ar(cx);
      JSAutoCompartment ac(cx, aClassObject);
      JS::CompileOptions options(cx);
      options.setFileAndLine(functionUri.get(), mGetterText->GetLineNumber())
             .setVersion(JSVERSION_LATEST)
             .setUserBit(true); // Flag us as XBL
      nsCString name = NS_LITERAL_CSTRING("get_") + NS_ConvertUTF16toUTF8(mName);
      js::RootedObject rootedNull(cx, nullptr); // See bug 781070.
      rv = nsJSUtils::CompileFunction(cx, rootedNull, options, name, 0, nullptr,
                                      getter, &getterObject);

      // Make sure we free mGetterText here before setting mJSGetterObject, since
      // that'll overwrite mGetterText
      delete mGetterText;
      deletedGetter = true;
      mJSGetterObject = getterObject;
    
      if (mJSGetterObject && NS_SUCCEEDED(rv)) {
        mJSAttributes |= JSPROP_GETTER | JSPROP_SHARED;
      }
      if (NS_FAILED(rv)) {
        mJSGetterObject = nullptr;
        mJSAttributes &= ~JSPROP_GETTER;
        /*chaining to return failure*/
      }
    }
  } // if getter is not empty

  if (!deletedGetter) {  // Empty getter
    delete mGetterText;
    mJSGetterObject = nullptr;
  }
  
  if (NS_FAILED(rv)) {
    // We failed to compile our getter.  So either we've set it to null, or
    // it's still set to the text object.  In either case, it's safe to return
    // the error here, since then we'll be cleaned up as uncompiled and that
    // will be ok.  Going on and compiling the setter and _then_ returning an
    // error, on the other hand, will try to clean up a compiled setter as
    // uncompiled and crash.
    return rv;
  }

  bool deletedSetter = false;
  if (mSetterText && mSetterText->GetText()) {
    nsDependentString setter(mSetterText->GetText());
    if (!setter.IsEmpty()) {
      // Compile into a temp object so we don't wipe out mSetterText
      JSObject* setterObject = nullptr;
      JSContext* cx = aContext->GetNativeContext();
      JSAutoRequest ar(cx);
      JSAutoCompartment ac(cx, aClassObject);
      JS::CompileOptions options(cx);
      options.setFileAndLine(functionUri.get(), mSetterText->GetLineNumber())
             .setVersion(JSVERSION_LATEST)
             .setUserBit(true); // Flag us as XBL
      nsCString name = NS_LITERAL_CSTRING("set_") + NS_ConvertUTF16toUTF8(mName);
      js::RootedObject rootedNull(cx, nullptr); // See bug 781070.
      rv = nsJSUtils::CompileFunction(cx, rootedNull, options, name, 1,
                                      gPropertyArgs, setter, &setterObject);

      // Make sure we free mSetterText here before setting mJSGetterObject, since
      // that'll overwrite mSetterText
      delete mSetterText;
      deletedSetter = true;
      mJSSetterObject = setterObject;

      if (mJSSetterObject && NS_SUCCEEDED(rv)) {
        mJSAttributes |= JSPROP_SETTER | JSPROP_SHARED;
      }
      if (NS_FAILED(rv)) {
        mJSSetterObject = nullptr;
        mJSAttributes &= ~JSPROP_SETTER;
        /*chaining to return failure*/
      }
    }
  } // if setter wasn't empty....

  if (!deletedSetter) {  // Empty setter
    delete mSetterText;
    mJSSetterObject = nullptr;
  }

#ifdef DEBUG
  mIsCompiled = NS_SUCCEEDED(rv);
#endif
  
  return rv;
}
static void test_quant_solve1() {
    ast_manager m;
    arith_util ar(m);
    reg_decl_plugins(m);
    sort* i = ar.mk_int();
    app_ref xr(m.mk_const(symbol("x"),i), m);
    app_ref yr(m.mk_const(symbol("y"),i), m);
    app* x = xr.get();
    app* y = yr.get();
    app* xy[2] = { x, y };


    test_quant_solver(m, x, "(and (<= x y) (= (mod x 2) 0))");
    test_quant_solver(m, x, "(and (<= (* 2 x) y) (= (mod x 2) 0))");
    test_quant_solver(m, x, "(and (>= x y) (= (mod x 2) 0))");
    test_quant_solver(m, x, "(and (>= (* 2 x) y) (= (mod x 2) 0))");
    test_quant_solver(m, x, "(and (<= (* 2 x) y) (>= x z) (= (mod x 2) 0))");
    test_quant_solver(m, x, "(and (<= (* 2 x) y) (>= (* 3 x) z) (= (mod x 2) 0))");
    test_quant_solver(m, x, "(>= (* 2 x) a)");
    test_quant_solver(m, x, "(<= (* 2 x) a)");
    test_quant_solver(m, x, "(< (* 2 x) a)");
    test_quant_solver(m, x, "(= (* 2 x) a)");
    test_quant_solver(m, x, "(< (* 2 x) a)");
    test_quant_solver(m, x, "(> (* 2 x) a)");
    test_quant_solver(m, x, "(and (<= a x) (<= (* 2 x) b))");
    test_quant_solver(m, x, "(and (<= a x) (<= x b))");
    test_quant_solver(m, x, "(and (<= (* 2 a) x) (<= x b))");
    test_quant_solver(m, x, "(and (<= (* 2 a) x) (<= (* 2 x) b))");
    test_quant_solver(m, x, "(and (<= a x) (<= (* 3 x) b))");
    test_quant_solver(m, x, "(and (<= (* 3 a) x) (<= x b))");
    test_quant_solver(m, x, "(and (<= (* 3 a) x) (<= (* 3 x) b))");
    test_quant_solver(m, x, "(and (< a (* 3 x)) (< (* 3 x) b))");    
    test_quant_solver(m, x, "(< (* 3 x) a)");
    test_quant_solver(m, x, "(= (* 3 x) a)");
    test_quant_solver(m, x, "(< (* 3 x) a)");
    test_quant_solver(m, x, "(> (* 3 x) a)");
    test_quant_solver(m, x, "(<= (* 3 x) a)");
    test_quant_solver(m, x, "(>= (* 3 x) a)");
    test_quant_solver(m, x, "(<= (* 2 x) a)");
    test_quant_solver(m, x, "(or (= (* 2 x) y) (= (+ (* 2 x) 1) y))");
    test_quant_solver(m, x, "(= x a)");
    test_quant_solver(m, x, "(< x a)");
    test_quant_solver(m, x, "(> x a)");
    test_quant_solver(m, x, "(and (> x a) (< x b))");
    test_quant_solver(m, x, "(and (> x a) (< x b))");
    test_quant_solver(m, x, "(<= x a)");
    test_quant_solver(m, x, "(>= x a)");
    test_quant_solver(m, x, "(and (<= (* 2 x) y) (= (mod x 2) 0))");
    test_quant_solver(m, x, "(= (* 2 x) y)");
    test_quant_solver(m, x, "(or (< x 0) (> x 1))");
    test_quant_solver(m, x, "(or (< x y) (> x y))");
    test_quant_solver(m, x, "(= x y)");
    test_quant_solver(m, x, "(<= x y)");
    test_quant_solver(m, x, "(>= x y)");
    test_quant_solver(m, x, "(and (<= (+ x y) 0) (<= (+ x z) 0))");
    test_quant_solver(m, x, "(and (<= (+ x y) 0) (<= (+ (* 2 x) z) 0))");
    test_quant_solver(m, x, "(and (<= (+ (* 3 x) y) 0) (<= (+ (* 2 x) z) 0))");
    test_quant_solver(m, x, "(and (>= x y) (>= x z))");
    test_quant_solver(m, x, "(< x y)");
    test_quant_solver(m, x, "(> x y)");
    test_quant_solver(m, 2, xy, "(and (<= (- (* 2 y) b) (+ (* 3 x) a)) (<= (- (* 2 x) a) (+ (* 4 y) b)))");

    test_quant_solver(m, "(exists ((c Cell)) (= c null))");
    test_quant_solver(m, "(exists ((c Cell)) (= c (cell null c1)))");

    test_quant_solver(m, "(exists ((c Cell)) (not (= c null)))", false);
    test_quant_solver(m, "(exists ((c Cell)) (= (cell c c) c1))", false);
    test_quant_solver(m, "(exists ((c Cell)) (= (cell c (cdr c1)) c1))", false);

    test_quant_solver(m, "(exists ((t Tuple)) (= (tuple a P r1) t))");
    test_quant_solver(m, "(exists ((t Tuple)) (= a (first t)))");
    test_quant_solver(m, "(exists ((t Tuple)) (= P (second t)))");
    test_quant_solver(m, "(exists ((t Tuple)) (= r2 (third t)))");
    test_quant_solver(m, "(exists ((t Tuple)) (not (= a (first t))))");
    test_quant_solver(m, "(exists ((t Tuple)) (not (= P (second t))))");
    test_quant_solver(m, "(exists ((t Tuple)) (not (= r2 (third t))))");
}
예제 #25
0
//////////////////
// Load from CFile
//
BOOL CPicture::Load(CFile& file)
{
	CArchive ar(&file, CArchive::load | CArchive::bNoFlushOnDelete);
	return Load(ar);
}
void CGuildHouseDBCtrl::Handler( LPDB_OVERLAPPED_PLUS pov, DWORD dwCompletionKey )
{
	CAr ar( pov->lpBuf, pov->uBufSize );

	switch( pov->nQueryMode )
	{
		case GUILDHOUSE_LOAD:
			if( !LoadGuildHouse() )
				AfxMessageBox( "GuildHouse Load Failed!!!" );
			break;

		case GUILDHOUSE_SEND:
			SendGuildHouse( dwCompletionKey );
#ifdef __GUILD_HOUSE_MIDDLE
			SendGuildHouseTenderInfo( dwCompletionKey );
#endif // GUILDHOUSE_SEND
			break;

		case GUILDHOUSE_CREATE:
			CreateGuildHouse( ar, dwCompletionKey );
			break;

		case GUILDHOUSE_REMOVE:
			RemoveGuildHouse( dwCompletionKey );
			break;

		case GUILDHOUSE_DEFAULT_PACKET:
			RunDefaultPacket( ar, dwCompletionKey );
			break;	

		case GUILDHOUSE_SAVE_RESTPOINT:
			DWORD dwPlayerId; int nRestPoint; time_t tLogOut;
			ar >> dwPlayerId >> nRestPoint >> tLogOut;
			GetQueryObject()->Execute( "usp_RestPoint_Update '%02d', '%07d', %d, %d", g_appInfo.dwSys, dwPlayerId, nRestPoint, tLogOut );
			break;

#ifdef __GUILD_HOUSE_MIDDLE
		case GUILDHOUSE_TENDER_JOIN:
			{
				JoinGuildHouseTender( ar, dwCompletionKey );
			}
			break;

		case GUILDHOUSE_GRADE_UPDATE:
			{
				UpgradeGuildHouseGrade( ar, dwCompletionKey );
			}
			break;

		case GUILDHOUSE_LEVEL_UPDATE:
			{
				UpgradeGuildHouseLevel( ar, dwCompletionKey );
			}
			break;
		case GUILDHOUSE_EXPIRED:
			{
				UpdateGuildHouseExpired( ar );
			}
			break;
#endif // __GUILD_HOUSE_MIDDLE
	}
}
예제 #27
0
//------------------------------------------------------------------------------
//## Variant serialization
TEST_F(Test_Base_Variant, Serialization)
{
	String json = _T("{\"v_Int32\":100}");

	struct Data
	{
		//Variant v_Null;	// TODO:
		Variant v_Bool;
		//Variant v_Char,	// TODO:
		Variant v_Int8;
		Variant v_Int16;
		Variant v_Int32;
		Variant v_Int64;
		Variant v_UInt8;
		Variant v_UInt16;
		Variant v_UInt32;
		Variant v_UInt64;
		Variant v_Float;
		Variant v_Double;
		Variant v_String;
		Variant v_List;

		void serialize(Archive& ar)
		{
			ar & LN_NVP(v_Bool);
			ar & LN_NVP(v_Int8);
			ar & LN_NVP(v_Int16);
			ar & LN_NVP(v_Int32);
			ar & LN_NVP(v_Int64);
			ar & LN_NVP(v_UInt8);
			ar & LN_NVP(v_UInt16);
			ar & LN_NVP(v_UInt32);
			ar & LN_NVP(v_UInt64);
			ar & LN_NVP(v_Float);
			ar & LN_NVP(v_Double);
			ar & LN_NVP(v_String);
			ar & LN_NVP(v_List);
		}
	};

	//* [ ] Save
	{
		JsonTextOutputArchive ar;
		Data data;
		data.v_Bool = true;
		data.v_Int8 = 1;
		data.v_Int16 = 2;
		data.v_Int32 = 3;
		data.v_Int64 = 4;
		data.v_UInt8 = 5;
		data.v_UInt16 = 6;
		data.v_UInt32 = 7;
		data.v_UInt64 = 8;
		data.v_Float = 1;
		data.v_Double = 1;
		data.v_String = _T("11");
		data.v_List = Variant(List<int>({ 1, 2, 3 }));
		ar.process(data);
		json = ar.toString(JsonFormatting::None);
	}

	//* [ ] Load
	{
		JsonTextInputArchive ar(json);
		Data data;
		ar.process(data);
		ASSERT_EQ(true, data.v_Bool.get<bool>());
		ASSERT_EQ(1, data.v_Int8.get<int8_t>());
		ASSERT_EQ(2, data.v_Int16.get<int16_t>());
		ASSERT_EQ(3, data.v_Int32.get<int32_t>());
		ASSERT_EQ(4, data.v_Int64.get<int64_t>());
		ASSERT_EQ(5, data.v_UInt8.get<uint8_t>());
		ASSERT_EQ(6, data.v_UInt16.get<uint16_t>());
		ASSERT_EQ(7, data.v_UInt32.get<uint32_t>());
		ASSERT_EQ(8, data.v_UInt64.get<uint64_t>());
		ASSERT_EQ(true, Math::nearEqual(1, data.v_Float.get<float>()));
		ASSERT_EQ(true, Math::nearEqual(1, data.v_Double.get<double>()));
		ASSERT_EQ(_T("11"), data.v_String.get<String>());
		ASSERT_EQ(3, data.v_List.list().size());
		ASSERT_EQ(1, data.v_List.list()[0].get<int32_t>());
		ASSERT_EQ(2, data.v_List.list()[1].get<int32_t>());
		ASSERT_EQ(3, data.v_List.list()[2].get<int32_t>());
	}
}
예제 #28
0
BOOL CAirportsManager::ReadCommonAirports(const CString& _path)
{
	CFile* pFile = NULL;
	CString sFileName = _path + "\\" + _strAirportFileName;
	BOOL bRet = TRUE;
	// airport file
	try
	{
		pFile = new CFile(sFileName, CFile::modeRead | CFile::shareDenyNone);
		CArchive ar(pFile, CArchive::load);
		char line[1024];
		//skip a line
		CString csLine;
		ar.ReadString( csLine );
		//read line 2
		ar.ReadString( csLine );
		csLine.MakeUpper();
		strcpy( line, csLine );
		if(_stricmp(line, "AIRPORTS DATABASE") == 0)
		{
			//skip the column names
			ar.ReadString( csLine );
			//read the values
			//read a line
			ar.ReadString( csLine );
			csLine.MakeUpper();
			strcpy( line, csLine );
			while( *line != '\0' )
			{
				CAirport* pAP = new CAirport();
				char* b = line;
				char* p = NULL;
				int c = 1;
				while((p = strchr(b, ',')) != NULL)
				{
					*p = '\0';
					switch(c)
					{
					case 1: //IATA code
						pAP->m_sIATACode = b;
						break;
					case 2: //Desc
						pAP->m_sLongName = b;
						break;
					case 3: // ICAO code...
						pAP->m_sICAOCode = b;
						break;
					case 4: // ARP coordinates...
						pAP->m_sARPCoordinates = b;
						break;
					case 5: // City...
						pAP->m_sCity = b;
						break;
					case 6: // Country...
						pAP->m_sCountry = b;
						break;
					case 7: // Country code...
						pAP->m_sCountryCode = b;
						break;
					case 8: // Elevation...
						pAP->m_sElevation = b;
						break;
					case 9: // Number of runways...
						pAP->m_sNumberOfRunways = b;
						break;
					case 10: // Maximum runway length...
						pAP->m_sMaximumRunwayLength = b;
						break;
					case 11: // Alternate airport ICAO code...
						pAP->m_sAlternateAirportICAOCode = b;
						break;
					default:
						CString tmp = b;
						break;
					}
					b = ++p;
					c++;
				}
				if(b!= NULL)
				{
					pAP->m_sAlternateAirportICAOCode = b;
				}
				if(!IsExist(pAP))
					m_vAirports.push_back(pAP);
				else
					delete pAP ;
				ar.ReadString( csLine );
				csLine.MakeUpper();
				strcpy( line, csLine );
			}
		}
		else {
			bRet = FALSE;
		}
		ar.Close();
		delete pFile;
	}
	catch(CException* e)
	{
		AfxMessageBox("Error reading Airports file: " + sFileName, MB_ICONEXCLAMATION | MB_OK);
		e->Delete();
		if(pFile != NULL)
			delete pFile;
		bRet = FALSE;
	}
	return bRet ;
}
예제 #29
0
BOOL CAirportsManager::LoadData( const CString& _strDBPath )
{
	Clear();
	m_strDBPath = _strDBPath;
//	ReadCommonAirports(m_strCommonDBPath) ;
	CFile* pFile = NULL;
	CString sFileName = _strDBPath + "\\" + _strAirportFileName;
	BOOL bRet = TRUE;
	// airport file
	try
	{
		pFile = new CFile(sFileName, CFile::modeRead | CFile::shareDenyNone);
		CArchive ar(pFile, CArchive::load);
		char line[1024];
		//skip a line
		CString csLine;
		ar.ReadString( csLine );
		//read line 2
		ar.ReadString( csLine );
		csLine.MakeUpper();
		strcpy( line, csLine );
		if(_stricmp(line, "AIRPORTS DATABASE") == 0)
		{
			//skip the column names
			ar.ReadString( csLine );
			//read the values
			//read a line
			ar.ReadString( csLine );
			csLine.MakeUpper();
			strcpy( line, csLine );
			while( *line != '\0' )
			{
				CAirport* pAP = new CAirport();
				char* b = line;
				char* p = NULL;
				int c = 1;
				while((p = strchr(b, ',')) != NULL)
				{
					*p = '\0';
					switch(c)
					{
					case 1: //IATA code
						pAP->m_sIATACode = b;
						break;
					case 2: //Desc
						pAP->m_sLongName = b;
						break;
                    case 3: // ICAO code...
                        pAP->m_sICAOCode = b;
                        break;
                    case 4: // ARP coordinates...
                        pAP->m_sARPCoordinates = b;
                        break;
                    case 5: // City...
                        pAP->m_sCity = b;
                        break;
                    case 6: // Country...
                        pAP->m_sCountry = b;
                        break;
                    case 7: // Country code...
                        pAP->m_sCountryCode = b;
                        break;
                    case 8: // Elevation...
                        pAP->m_sElevation = b;
                        break;
                    case 9: // Number of runways...
                        pAP->m_sNumberOfRunways = b;
                        break;
                    case 10: // Maximum runway length...
                        pAP->m_sMaximumRunwayLength = b;
                        break;
                    case 11: // Alternate airport ICAO code...
                        pAP->m_sAlternateAirportICAOCode = b;
                        break;
					default:
						CString tmp = b;
						break;
					}
					b = ++p;
					c++;
				}
				if(b!= NULL)
				{
                    pAP->m_sAlternateAirportICAOCode = b;
				}
				if(!IsExist(pAP))
				  m_vAirports.push_back(pAP);
				else
					delete pAP ;
				ar.ReadString( csLine );
				csLine.MakeUpper();
				strcpy( line, csLine );
			}
		}
		else {
			bRet = FALSE;
		}
		ar.Close();
		delete pFile;
	}
	catch(CException* e)
	{
		AfxMessageBox("Error reading Airports file: " + sFileName, MB_ICONEXCLAMATION | MB_OK);
		e->Delete();
		if(pFile != NULL)
			delete pFile;
		bRet = FALSE;
	}

	// sector file
	pFile = NULL;
	sFileName = _strDBPath + "\\" + _strSectorFileName;
	try
	{
		pFile = new CFile(sFileName, CFile::modeRead | CFile::shareDenyNone);
		CArchive ar(pFile, CArchive::load);
		char line[2048];
		CString csLine;
		ar.ReadString( csLine );
		//read line 2
		ar.ReadString( csLine );
		csLine.MakeUpper();
		strcpy( line, csLine );
		if(_stricmp(line, "SECTORS DATABASE") == 0)
		{
			//skip the column names
			ar.ReadString( csLine );
			//read the values
			//read a line
			ar.ReadString( csLine );
			csLine.MakeUpper();
			strcpy( line, csLine );
			while( *line != '\0')
			{
				//CSector* pS = new CSector();
				CString sSectorName;
				CString sAirport;
				char* b = line;
				char* p = NULL;
				int c = 1;
				while((p = strchr(b, ',')) != NULL)
				{
					*p = '\0';
					switch(c)
					{
					case 1: //name
						sSectorName = b;
						break;
					case 2: //airport(s)
						sAirport = b;
						break;
					default: //more airports
						CString tmp = b;
						sAirport = sAirport + "," + tmp;
						break;
					}
					b = ++p;
					c++;
				}
				if(b!=NULL) // the last column did not have a comma after it
				{
					switch(c)
					{
					case 1: //name
						sSectorName = b;
						break;
					case 2: //airport(s)
						sAirport = b;
						break;
					default: //more airports
						CString tmp = b;
						sAirport = sAirport + "," + tmp;
						break;
					}
				}
				CAIRPORTFILTER apFilter;
				while(TRUE) {
					int nIdx = sAirport.Find(',');
					if(nIdx != -1) { // found a comma
						apFilter.sIATACode = sAirport.Left(nIdx);
						AddSector(sSectorName, apFilter);
						sAirport = sAirport.Right(sAirport.GetLength()-nIdx-1);
					}
					else if(!sAirport.IsEmpty()){ // no comma, but string not empty
						apFilter.sIATACode = sAirport;
						AddSector(sSectorName, apFilter);
						break;
					}
					else { // no comma, string empty
						break;
					}
				}
				ar.ReadString( csLine );
				csLine.MakeUpper();
				strcpy( line, csLine );
			}
		}
		else
			bRet = FALSE;
		ar.Close();
		delete pFile;
	}
	catch(CException* e) {
		AfxMessageBox("Error reading Sectors file: " + sFileName, MB_ICONEXCLAMATION | MB_OK);
		e->Delete();
		if(pFile != NULL)
			delete pFile;
		bRet = FALSE;
	}
	return bRet;
}
예제 #30
0
void CMainFrame::OnFileSave() 
{
CFileDialog dlg(
		FALSE,
		_T("UI state"),
		_T(".\\Default.UI state"),
		OFN_ENABLESIZING|OFN_EXPLORER
			|OFN_LONGNAMES|OFN_PATHMUSTEXIST
			|OFN_NOCHANGEDIR|OFN_NODEREFERENCELINKS
			,
		_T("UI state files (*.UI state)|*.UI state|All files (*.*)|*.*||"),
		this
		);
	dlg.m_ofn.lpstrTitle = _T("Save UI state to file");
	if( dlg.DoModal() != IDOK )
		return;
	ASSERT( dlg.m_ofn.lpstrFile != NULL );
	try
	{
		CFile _file(
			dlg.m_ofn.lpstrFile,
			CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive
			);
		CArchive ar( &_file, CArchive::store);

		CWinApp * pApp = ::AfxGetApp();
		ASSERT( pApp != NULL );
		ASSERT( pApp->m_pszRegistryKey != NULL );
		ASSERT( pApp->m_pszRegistryKey[0] != _T('\0') );
		ASSERT( pApp->m_pszProfileName != NULL );
		ASSERT( pApp->m_pszProfileName[0] != _T('\0') );

		VERIFY(
			CExtControlBar::ProfileBarStateSerialize(
				ar,
				this
				)
			);
		VERIFY(
			g_CmdManager->SerializeState(
				pApp->m_pszProfileName,
				ar
				)
			);
	} // try
	catch( CException * pXept )
	{
		CString sErrorDescription;
		VERIFY(
			pXept->GetErrorMessage(
				sErrorDescription.GetBuffer(8192), 8192
				)
			);
		sErrorDescription.ReleaseBuffer();
		ASSERT( !sErrorDescription.IsEmpty() );
		pXept->Delete();
		MessageBox(
			LPCTSTR(sErrorDescription),
			_T("State save failed"),
			MB_ICONERROR
			);
	} // catch( CException * pXept )
	catch( ... )
	{
		MessageBox(
			_T("Unknown exception caught"),
			_T("State save failed"),
			MB_ICONERROR
			);
	} // catch( ... )
}