Image * CPIImageReader::read(std::string filename)
	{

		ifstream input(filename.c_str(), ios::binary);

		try{
			if (!input) throw("The file you try to open cannot open or does not exist! Please try again");
			addLogEntry("Successfully opened "+filename+" for reading.");

			char cpi[3];

			input.read(cpi, sizeof(char) * 3);

			if ((cpi[0] != 'C') || (cpi[1] != 'P') || (cpi[2] != 'I')) throw("The image you tried to open is not CPI type. Please try again with another image");

			__int8 edition;
			input.read(&edition, sizeof(edition));
			if (edition != 1) throw("The image you tried to open is not of the proper CPI edition (1st). Please try again with another image");

			unsigned short BE_LE;
			input.read((char *)&BE_LE, sizeof(BE_LE));
			if (BE_LE != 258) throw("The image you tried to open cannot be read. Please try again with another image");

			unsigned short width, height;
			input.read((char *)&width, sizeof(width));
			input.read((char*)&height, sizeof(height));

			Component * buff = new Component[width*height * 3];
			input.read((char*)buff, sizeof(Component)*width*height * 3);

			Image * returnedImage = new Image(width, height, buff, false);

			delete[] buff;
			
			input.close(); 
			addLogEntry("The image was successfully read.");
			return returnedImage;

		}
		catch (char * err){
			fprintf(stderr, "%s\n", err);
			addLogEntry(err);
			input.close();
			destroyLogger();
			return NULL;
		}

	}
Beispiel #2
0
LogWindow::LogWindow(QWidget *theParent) :
    QMainWindow(theParent),
    ui(new Ui::LogWindow),
    m_log(NULL),
    m_maxEntries(NULL),
    m_logEntryBlockFormat(new QTextBlockFormat()),
    m_timeStampFormat(new QTextCharFormat()),
    m_debugMessageFormat(new QTextCharFormat()),
    m_notificationFormat(new QTextCharFormat()),
    m_warningFormat(new QTextCharFormat()),
    m_errorFormat(new QTextCharFormat()),
    m_moleQueueIdFormat(new QTextCharFormat()),
    m_messageFormat(new QTextCharFormat())
{
    createUi();

    // Restore geometry
    QSettings settings;
    settings.beginGroup("logWindow");
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("windowState").toByteArray());
    settings.endGroup();

    setupFormats();

    connect(Logger::getInstance(), SIGNAL(newLogEntry(MoleQueue::LogEntry)),
            this, SLOT(addLogEntry(MoleQueue::LogEntry)));

    initializeLogText();
}
Beispiel #3
0
SmugID SmugMug::createAlbum(const String& title, const int categoryId, const StringPairArray& albumFlags)
{
	SmugID newAlbum;
	newAlbum.id = -1;

	StringPairArray params(albumFlags);
	params.set(("Title"), title);
	params.set(("CategoryID"), String(categoryId));
	XmlElement* n = smugMugRequest(("smugmug.albums.create"), params);

	if (n)
	{
		XmlElement* a = n->getChildByName(("Album"));
		if (a) 
		{
			newAlbum.id  = a->getIntAttribute(("id"), -1);
			newAlbum.key = a->getStringAttribute(("Key"));
		}

		if (newAlbum.id != -1)
			addLogEntry(("Info: album created: ") + title);

		delete n;
	}
	return newAlbum;
}
Beispiel #4
0
XmlElement* SmugMug::smugMugRequest(const String& method, const StringPairArray& params_, bool upload)
{
	StringPairArray params(params_);
	params.set(("method"), method);
	params.set(("APIKey"), APIKEY);

	startTimer(LOGOUT_TIMER);

	if (sessionId.isNotEmpty())
		params.set(("SessionID"), sessionId);

	URL url(upload ? UPLOAD_URL : BASE_URL);

	StringArray keys = params.getAllKeys();
	StringArray vals = params.getAllValues();

	for (int i = 0; i < keys.size(); i++)
		url = url.withParameter(keys[i], vals[i]);

	XmlElement* x = url.readEntireXmlStream(upload);
#ifdef JUCE_DEBUG
	Logger::outputDebugString(url.toString(true));
	if (x)
		Logger::outputDebugString(x->createDocument(String::empty, true));
#endif
	if (x && x->getStringAttribute(("stat")) == ("fail"))
	{
		XmlElement* err = x->getChildByName(("err"));
		if (err)
		{
			addLogEntry(("Error: ") + err->getStringAttribute(("msg")));
		}
	}
	return x;
}
Beispiel #5
0
void SmugMug::login(const String& username, const String& password)
{
	sessionId = String::empty;

	StringPairArray params;
	params.set(("EmailAddress"), username);
	params.set(("Password"), password);

	XmlElement* n = smugMugRequest(("smugmug.login.withPassword"), params);
	
	if (n)
	{
		XmlElement* l = n->getChildByName(("Login"));
		if (l)
		{
			accountType = l->getStringAttribute(("AccountType"));
			XmlElement* s = l->getChildByName(("Session"));
			if (s)
			{
				sessionId = s->getStringAttribute(("id"));
				addLogEntry(("Info: logged in session: ") + sessionId);
			}
		}
		delete n;
	}
}
Beispiel #6
0
void LogWindow::initializeLogText()
{
    m_log->clear();
    foreach (const LogEntry &entry, Logger::log())
        addLogEntry(entry);

    m_log->moveCursor(QTextCursor::Start);
    m_log->ensureCursorVisible();
}
	void CPIImageWriter::write(std::string filename, const Image & src)
	{

		ofstream output;
		output.open(filename.c_str(), ios::binary | ios::trunc);

		try{

			if (!output) throw("Error opening file to write");
			addLogEntry("Successfully opened "+filename+" for writing.");

			output << "CPI";

			__int8 edition = 1;

			output.write((char*)&edition, sizeof(edition));

			unsigned short LE_BE = 258;

			output.write((char*)&LE_BE, sizeof(LE_BE));

			unsigned short width = (unsigned short)src.getWidth();
			unsigned short height = (unsigned short)src.getHeight();

			output.write((char*)&width, sizeof(width));

			output.write((char*)&height, sizeof(height));

			Component * imgBuffer = src.getRawDataPtr();

			output.write((char*)imgBuffer, (streamsize)sizeof(Component)*width*height * 3);

			std::cout << "The image was successfully written to " << filename << "\n";
			addLogEntry("The image was successfully written to "+filename);

		}
		catch (char * err){
			fprintf(stderr, "%s\n", err);
			addLogEntry(err);
		}

		output.close();

	}
void
QtPlatformLogModel::addLogEntry(const PlatformEvent& event)
{
  const Poco::Message& entry = Poco::RefAnyCast<const Poco::Message>(*event.GetData());
  mbilog::LogMessage msg(mbilog::Info,"n/a",-1,"n/a");
  msg.message += entry.getText();
  msg.category = "BlueBerry."+entry.getSource();
  msg.moduleName = "n/a";
  addLogEntry(msg);
}
Beispiel #9
0
void SmugMug::logout()
{
	StringPairArray params;
	XmlElement* n = smugMugRequest(("smugmug.logout"), params);

	addLogEntry(("Info: logged out session ") + sessionId);
	if (n)
		delete n;

	sessionId = String::empty;
}
Beispiel #10
0
  /*
   * Set a multiphase mixture to a state of chemical equilibrium.
   * This is the top-level driver for multiphase equilibrium. It
   * doesn't do much more than call the equilibrate method of class
   * MultiPhase, except that it adds some messages to the logfile,
   * if loglevel is set > 0.
   *
   * @ingroup equil
   */
  doublereal equilibrate(MultiPhase& s, const char* XY, 
			 doublereal tol, int maxsteps, int maxiter, 
			 int loglevel) {
    
    if (loglevel > 0) {
      beginLogGroup("equilibrate",loglevel);
      addLogEntry("multiphase equilibrate function");
      beginLogGroup("arguments");
      addLogEntry("XY",XY);
      addLogEntry("tol",tol);
      addLogEntry("maxsteps",maxsteps);
      addLogEntry("maxiter",maxiter);
      addLogEntry("loglevel",loglevel);
      endLogGroup("arguments");
    }
    s.init();
    int ixy = _equilflag(XY);
    if (ixy == TP || ixy == HP || ixy == SP || ixy == TV) {
      try {
	double err = s.equilibrate(ixy, tol, maxsteps, maxiter, loglevel);
	if (loglevel > 0) {
	  addLogEntry("Success. Error",err);
	  endLogGroup("equilibrate");

	}
	return err;
      }
      catch (CanteraError &err) {
	if (loglevel > 0) {
	  addLogEntry("Failure.",lastErrorMessage());
	  endLogGroup("equilibrate");
	}
	throw err;
      }
    }
    else {
      if (loglevel > 0) {
	addLogEntry("multiphase equilibrium can be done only for TP, HP, SP, or TV");
	endLogGroup("equilibrate");
      }
      throw CanteraError("equilibrate","unsupported option");
      return -1.0;
    }
    return 0.0; 
  }
Beispiel #11
0
void SmugMug::cancelUploads()
{
	ScopedLock sl(lock);

	for (int i = 0; i < uploadQueue.size(); i++)
	{
		UploadRequest* ur = uploadQueue[i];
		for (int j = 0; j < ur->getNumImages(); j++)
		{
			UploadFile& uf = ur->getImageFileInfo(j);
			uf.status = UploadFile::Cancelled;
		}
	}

	addLogEntry(("Info: all uploads cancelled"));
}
Beispiel #12
0
void SmugMug::reSubmitFailedUploads()
{
	ScopedLock sl(lock);

	for (int i = 0; i < uploadQueue.size(); i++)
	{
		UploadRequest* ur = uploadQueue[i];
		for (int j = 0; j < ur->getNumImages(); j++)
		{
			UploadFile& uf = ur->getImageFileInfo(j);
			if (uf.status == UploadFile::Failed)
				uf.status = UploadFile::Waiting;
		}
	}

	while (uploadThreads.size() < Settings::getInstance()->uploadThreads)
	{
		UploadThread* ut = NULL;
		uploadThreads.add(ut = new UploadThread(this));
		ut->startThread();
	}

	addLogEntry(("Info: failed uploads readded to queue"));
}
Beispiel #13
0
/*
 *
 *  @param s         The MultiPhase object to be set to an equilibrium state
 *  @param iphase    Phase index within the multiphase object to be
 *                   tested for stability.
 *  @param funcStab  Function value that tests equilibrium. > 0 indicates stable
 *                   < 0 indicates unstable
 *
 *  @param printLvl   Determines the amount of printing that
 *                  gets sent to stdout from the vcs package
 *                  (Note, you may have to compile with debug
 *                   flags to get some printing).
 *
 *  @param loglevel Controls amount of diagnostic output. loglevel
 *                  = 0 suppresses diagnostics, and increasingly-verbose
 *                  messages are written as loglevel increases. The
 *                  messages are written to a file in HTML format for viewing
 *                  in a web browser. @see HTML_logs
 */
int vcs_determine_PhaseStability(MultiPhase& s, int iphase,
                                 double& funcStab, int printLvl, int loglevel)
{
    int iStab = 0;
    static int counter = 0;
    beginLogGroup("PhaseStability",loglevel);
    addLogEntry("multiphase phase stability function");
    beginLogGroup("arguments");
    addLogEntry("iphase",iphase);
    addLogEntry("loglevel",loglevel);
    endLogGroup("arguments");

    int printLvlSub = std::max(0, printLvl-1);

    s.init();
    try {
        VCSnonideal::vcs_MultiPhaseEquil* eqsolve = new VCSnonideal::vcs_MultiPhaseEquil(&s, printLvlSub);
        iStab = eqsolve->determine_PhaseStability(iphase, funcStab, printLvlSub, loglevel);
        if (iStab != 0) {
            addLogEntry("Phase is stable  - ", iphase);
        } else {
            addLogEntry("Phase is not stable - ", iphase);
        }
        endLogGroup("PhaseStability");
        // hard code a csv output file.
        if (printLvl > 0) {
            string reportFile = "vcs_phaseStability.csv";
            if (counter > 0) {
                reportFile = "vcs_phaseStability_" + int2str(counter) + ".csv";
            }
            eqsolve->reportCSV(reportFile);
            counter++;
        }
        delete eqsolve;
    } catch (CanteraError& e) {
        addLogEntry("Failure.", lastErrorMessage());
        endLogGroup("equilibrate");
        throw e;
    }
    return iStab;
}
Beispiel #14
0
/**
 * Function: modifyMacData
 * Description: 修改Mac地址相关的配置信息,新的配置信息有用户通过post方法传入。新的配置信息包括老化时间、学习模式
				以及新添加的静态Mac地址选项,允许添加的最大静态Mac地址数为64条,该数目在页面中做了相应的判断
 * @param url  用户传入的新的Mac地址相关的配置
**/
void modifyMacData(char *url) {
    int i,j;
    int board_mac_index;
    int delete_num = 0;
    //int age_time;
    struct MacLink *temp;
    struct MacLink *p;

    char *disable_age_name = "DisableAgeing";
    char *disable_age_value = NULL;

    char *age_box_name = "agebox";
    char *age_box_value = NULL;

    char learn_port_name[20];
    char *learn_port_value = NULL;

    char vid_name[10];
    char *vid_value = NULL;
    uint8_t mac_vid;

    char mac_name[10];
    char *mac_value = NULL;


    char dest_name[15];
    char *dest_value = NULL;

    char delete_name[10];
    char *delete_value = NULL;

    uint32_t learn_mode = 0x00;

    unsigned char hex_mac[6];
    uint32_t port_vector = 0x00;
    unsigned char sucess = 0;
    unsigned char isExist;
    MAC_API_T mac_entry;  //删除时使用
    char message[96];
    uint8_t port_mode = 0x00;
    // printf("URL:%s\n",url);
    //获取和设置老化是否可用
    disable_age_value = getParameter(url,disable_age_name);
    if(disable_age_value) {
        if(board.mac_address.disable_age == 0) { //之前的状态为可用状态
            Set_Age_time(0);
            board.mac_address.disable_age = 1;  //修改board中老化不可用
            addLogEntry(INFO,"vorx","禁止了自动老化");
            printSystemLog();
        }

    } else {
        if(board.mac_address.disable_age == 1) { //之前的状态不可用
            board.mac_address.disable_age = 0;  //修改board中老化可用
            addLogEntry(INFO,"vorx","恢复了自动老化");
            printSystemLog();
        }

    }
    //获取和设置老化时间
    age_box_value = getParameter(url,age_box_name);
    if(age_box_value) {
        board.mac_address.disable_age = 0;  //修改board中老化可用
        age_time = Get_Age_time();
        if(atoi(age_box_value) != age_time) {
            Set_Age_time(atoi(age_box_value));
            age_time = Get_Age_time();
            board.mac_address.age_time = age_time;  //修改board中老化时间
            memset(message,0,sizeof(message));
            sprintf(message,"修改自动老化时间为 %d",age_time);
            addLogEntry(INFO,"vorx",message);
            printSystemLog();
        }
    } else {
        board.mac_address.disable_age = 1;  //修改board中老化不可用
    }
    //获取端口学习模式
    for(i = 0; i < ports_num; i++) {
        sprintf(learn_port_name,"learn_port_%d",i + 1);
        learn_port_value = getParameter(url,learn_port_name);
        //printf("port_name is %s; value is %s\n\r",learn_port_name,learn_port_value);
        //port_mode[i] = learn_port_value[6];
        port_mode = 0x00;
        if(learn_port_value[6] == 'D') {
            port_mode = board.mac_address.learn_mode & ((0x01 << i));
            learn_mode |= (0x01 << i);
            if(port_mode == 0x00) {     //某一个端口的学习模式更改了由自动模式更改为禁止模式
                memset(message,0,sizeof(message));
                sprintf(message,"端口 %d 禁用了学习模式",i + 1);
                addLogEntry(INFO,"vorx",message);
                printSystemLog();
            }

        } else {    //判断是否由禁止模式变为自动模式
            port_mode = board.mac_address.learn_mode & ((0x01 << i));
            if(port_mode != 0x00) { //之前的为禁止模式
                memset(message,0,sizeof(message));
                sprintf(message,"端口 %d 恢复了自动学习模式",i + 1);
				addLogEntry(INFO,"vorx",message);
                printSystemLog();
            }
        }
        freeMemory(learn_port_value);
    }
    //printf("learn_value is %0x\n\r",);
    //设置端口学习模式
    //printf("learn mode vector is %x\n\r",learn_mode);
    if(board.mac_address.learn_mode != learn_mode) {
        Set_Manual_learning_mode(learn_mode);
        board.mac_address.learn_mode = learn_mode;  //修改board中端口的学习模式
    }
    //获取用户新添静态Mac地址
    for( i = 0; i < MAX_MAC_ENTRY; i++) {
        port_vector = 0x00;
        sprintf(mac_name,"MAC_%d",i + 1);  //获取的mac地址
        mac_value = getParameter(url,mac_name);
        if( !mac_value) {
            freeMemory(mac_value);
            //printf("break");
            break;
        }
        //printf("need add mac address\n\r");
        getDivideMacAddress(hex_mac,mac_value);

        sprintf(vid_name,"VID_%d",i + 1);
        vid_value = getParameter(url,vid_name);
        mac_vid = atoi(vid_value);

        for(j = 0; j < ports_num; j++) {
            sprintf(dest_name,"h_Dest_%d_%d",i + 1,j + 1);
            dest_value = getParameter(url,dest_name);
            if( !strcmp(dest_value,"1")) {
                port_vector |= 0x01 << j;
            }
            freeMemory(dest_value);
        }


        sprintf(delete_name,"Delete_%d",i + 1);
        delete_value = getParameter(url,delete_name);  //获取需要删除的Vid

        if( delete_value == NULL ) { //判断该选项是否是需要删除的
            temp = (struct MacLink*)malloc(sizeof(struct MacLink));

            memcpy(temp->mac_entry.new_mac,hex_mac,sizeof(hex_mac));
            temp->mac_entry.port_vector = port_vector;
            temp->mac_entry.add_or_delet = 1;//添加标志
            temp->mac_entry.vlan_id = mac_vid;
            //添加之前先判断节点是否存在
            isExist = isExistNode(mac_root,temp,mac_value);
            if( !isExist) { //节点不存在添加到链表、board结构体和硬件表中
                sucess = Add_or_Delet_MACentry(&temp->mac_entry);
                if(sucess) {
                    temp->mac_entry.sta_or_dym = 0;
                    addMacLink(&mac_root,temp);
                    /* 向board中添加新的静态mac表项 */
                    addBoardMacAddress(mac_vid,hex_mac,port_vector);
                    //printf("add static mac sucess\n\r");
                    //printBoardInfo("config_mac");
                    memset(message,0,sizeof(message));
                    sprintf(message,"静态的MAC %s 添加成功",mac_value);
                    addLogEntry(INFO,"vorx",message);
                    printSystemLog();
                } else {
                    memset(message,0,sizeof(message));
                    sprintf(message,"静态的MAC %s 添加失败!!",mac_value);
                    addLogEntry(INFO,"vorx",message);
                    printSystemLog();
                    printf("add static mac failed\n\r");
                }
            } else if( isExist == 2) {
                /*节点存在只需要修改,需要从新添加到硬件表中,缓存中的数据的修改
                **在isExistNode方法中已经完成
                */

                /* 修改board中mac地址项信息 */
                //modifyBoardMacAddress(temp);
                sucess = Add_or_Delet_MACentry(&temp->mac_entry);
                if(sucess) {
                    //addMacLink(&root,temp);
                    //printf("modify static mac sucess\n\r");
                    /* 修改board中mac地址项信息 */
                    modifyBoardMacAddress(temp);
                    //printBoardInfo("config_mac");
                } else {
                    //printf("modify static mac failed\n\r");
                }
            }
        } else if(delete_value) {

            mac_entry.add_or_delet = 0;
            memcpy(mac_entry.new_mac,hex_mac,sizeof(hex_mac));
            mac_entry.port_vector = port_vector;
            mac_entry.vlan_id = mac_vid;
            sucess = Add_or_Delet_MACentry(&mac_entry);
            if(sucess) {
                deleteBoardMacAddress(mac_vid,hex_mac);//删除board中的mac地址项
                deleteMacLinkByVid(&mac_root,mac_vid,hex_mac);
                //printf("delete static mac sucess\n\r");
                //printBoardInfo("config_mac");
                memset(message,0,sizeof(message));
                sprintf(message,"静态的MAC %s 删除成功",mac_value);
                addLogEntry(INFO,"vorx",message);
                printSystemLog();
            } else {
                memset(message,0,sizeof(message));
                sprintf(message,"静态的MAC %s 添加失败",mac_value);
                addLogEntry(INFO,"vorx",message);
                printSystemLog();
                //printf("delete static mac failed\n\r");
            }

        }
        freeMemory(vid_value);
        freeMemory(dest_value);
        freeMemory(mac_value);
        freeMemory(delete_value);
    }//end for
    freeMemory(age_box_value);
    freeMemory(disable_age_value);
    //freeMemory(learn_port_value);
    //printf("modefy mac table finish\n\r");
}
Beispiel #15
0
int equilibrate(thermo_t& s, const char* XY, int solver,
                doublereal rtol, int maxsteps, int maxiter, int loglevel)
{
    bool redo = true;
    int retn = -1;
    int nAttempts = 0;
    int retnSub = 0;

    if (loglevel > 0) {
        beginLogGroup("equilibrate", loglevel);
        addLogEntry("Single-phase equilibrate function");
        {
            beginLogGroup("arguments");
            addLogEntry("phase",s.id());
            addLogEntry("XY",XY);
            addLogEntry("solver",solver);
            addLogEntry("rtol",rtol);
            addLogEntry("maxsteps",maxsteps);
            addLogEntry("maxiter",maxiter);
            addLogEntry("loglevel",loglevel);
            endLogGroup("arguments");
        }
    }
    while (redo) {
        if (solver >= 2) {
            int printLvlSub = 0;
            int estimateEquil = 0;
            try {
                MultiPhase m;
                m.addPhase(&s, 1.0);
                m.init();
                nAttempts++;
                vcs_equilibrate(m, XY, estimateEquil, printLvlSub, solver,
                                rtol, maxsteps, maxiter, loglevel-1);
                redo = false;
                if (loglevel > 0) {
                    addLogEntry("VCSnonideal solver succeeded.");
                }
                retn = nAttempts;
            } catch (CanteraError& err) {
                err.save();
                if (loglevel > 0) {
                    addLogEntry("VCSnonideal solver failed.");
                }
                if (nAttempts < 2) {
                    if (loglevel > 0) {
                        addLogEntry("Trying single phase ChemEquil solver.");
                    }
                    solver = -1;
                } else {
                    if (loglevel > 0) {
                        endLogGroup("equilibrate");
                    }
                    throw err;
                }
            }
        } else if (solver == 1) {
            try {
                MultiPhase m;
                m.addPhase(&s, 1.0);
                m.init();
                nAttempts++;
                equilibrate(m, XY, rtol, maxsteps, maxiter, loglevel-1);
                redo = false;
                if (loglevel > 0) {
                    addLogEntry("MultiPhaseEquil solver succeeded.");
                }
                retn = nAttempts;
            } catch (CanteraError& err) {
                err.save();
                if (loglevel > 0) {
                    addLogEntry("MultiPhaseEquil solver failed.");
                }
                if (nAttempts < 2) {
                    if (loglevel > 0) {
                        addLogEntry("Trying single phase ChemEquil solver.");
                    }
                    solver = -1;
                } else {
                    if (loglevel > 0) {
                        endLogGroup("equilibrate");
                    }
                    throw err;
                }
            }
        } else {      // solver <= 0
            /*
             * Call the element potential solver
             */
            try {
                ChemEquil e;
                e.options.maxIterations = maxsteps;
                e.options.relTolerance = rtol;
                nAttempts++;
                bool useThermoPhaseElementPotentials = true;
                retnSub = e.equilibrate(s, XY, useThermoPhaseElementPotentials,
                                        loglevel-1);
                if (retnSub < 0) {
                    if (loglevel > 0) {
                        addLogEntry("ChemEquil solver failed.");
                    }
                    if (nAttempts < 2) {
                        if (loglevel > 0) {
                            addLogEntry("Trying MultiPhaseEquil solver.");
                        }
                        solver = 1;
                    } else {
                        throw CanteraError("equilibrate",
                                           "Both equilibrium solvers failed");
                    }
                }
                retn = nAttempts;
                s.setElementPotentials(e.elementPotentials());
                redo = false;
                if (loglevel > 0) {
                    addLogEntry("ChemEquil solver succeeded.");
                }
            }

            catch (CanteraError& err) {
                err.save();
                if (loglevel > 0) {
                    addLogEntry("ChemEquil solver failed.");
                }
                // If ChemEquil fails, try the MultiPhase solver
                if (solver < 0) {
                    if (loglevel > 0) {
                        addLogEntry("Trying MultiPhaseEquil solver.");
                    }
                    solver = 1;
                } else {
                    redo = false;
                    if (loglevel > 0) {
                        endLogGroup("equilibrate");
                    }
                    throw err;
                }
            }
        }
    } // while (redo)
    /*
     * We are here only for a success
     */
    if (loglevel > 0) {
        endLogGroup("equilibrate");
    }
    return retn;
}
Beispiel #16
0
SmugID SmugMug::uploadFile(int queue, int index)
{
	SmugID retval;

	lock.enter();
	UploadFile& uf = uploadQueue[queue]->getImageFileInfo(index);
	lock.exit();

	int64 bytesDone = 0;
	MD5 md5(uf.file);

	Time start = Time::getCurrentTime();

	startTimer(LOGOUT_TIMER);

	String headers;
    String filename = uf.file.getFileName();
    headers = "PUT http://upload.smugmug.com/" + URL::addEscapeChars(filename, false) + " HTTP/1.1\r\n" +
		      "Host: upload.smugmug.com\r\n" +
			  "Content-Length: " + String(uf.file.getSize()) + "\r\n" +
		      "Content-MD5: " + md5.toHexString() + "\r\n" +
			  "X-Smug-SessionID: " + sessionId + "\r\n" +
			  "X-Smug-Version: 1.2.2\r\n" +
			  "X-Smug-ResponseType: REST\r\n" +
			  "X-Smug-AlbumID: " + String(uploadQueue[queue]->getAlbumId().id) + "\r\n" +
			  "X-Smug-FileName: " + filename + "\r\n\r\n";

#ifdef JUCE_DEBUG
	Logger::outputDebugString(headers);
#endif

	const char* headerUtf8 = headers.toUTF8();

	StreamingSocket soc;

	if (soc.connect("upload.smugmug.com", 80))
	{
		int bytesWritten = soc.write(headerUtf8, (int)strlen(headerUtf8));
		if (bytesWritten == -1)
		{
			uf.status = UploadFile::Failed;
			return retval;
		}

		FileInputStream* fos = uf.file.createInputStream();
		if (fos)
		{
			char buffer[1024 * 8];
			while (!fos->isExhausted())
			{
				int in = fos->read(buffer, sizeof(buffer));
				int out = soc.write(buffer, in);

				startTimer(LOGOUT_TIMER);

				if (in != out)
				{
					delete fos;
					uf.status = UploadFile::Failed;
					return retval;
				}
				else
				{
					bytesDone += in;
					uf.complete = float(bytesDone)/float(uf.file.getSize());
				}

				if (uf.status == UploadFile::Cancelled)
				{
					delete fos;
					return retval;
				}
			}
			delete fos;
		}
		else
		{
			uf.status = UploadFile::Failed;
			return retval;
		}

		String response;
		response.preallocateBytes(1024);

		while (1)
		{
			char buffer;
			int read = soc.read(&buffer, 1, true);
			if (read == -1)
				break;

			response += buffer;

			if (response.endsWith(("\r\n\r\n")) || response.endsWith(("\n\n")))
			{
				String len = response.fromFirstOccurrenceOf(("Content-Length: "), false, true);
				if (len.isNotEmpty())
				{
					// normal mode
					String num;

					int i = 0;
					while (CharacterFunctions::isDigit(len[i]))
						num += len[i++];
					
					int bytes = num.getIntValue();

					char* buffer = new char[bytes + 1];
					soc.read(buffer, bytes, true);
					buffer[bytes] = 0;

					response += buffer;
					delete[] buffer;
				}
				else
				{
					// chunked
					while (1)
					{
						String line;
						char ch;
						while (!line.endsWith("\r\n"))
						{
							soc.read(&ch, 1, true);
							line += ch;
						}

						int sz = line.getHexValue32();
						if (sz == 0)
							break;

						char* buf = new char[sz + 1];
						soc.read(buf, sz, true);
						buf[sz] = 0;

						response += buf;
						delete buf;

						soc.read(&ch, 1, true);
						soc.read(&ch, 1, true);
					}
				}

#ifdef JUCE_DEBUG				
				Logger::outputDebugString(response);
#endif
				soc.close();

				String xml = response.fromFirstOccurrenceOf(("<?xml"), true, true); 
				XmlDocument doc(xml);
				XmlElement* e = doc.getDocumentElement();
				if (e)
				{
					XmlElement* image = e->getChildByName(("Image"));
					if (image)
					{
						int val = image->getIntAttribute(("id"));
						if (val >= 0)
						{
							uf.status = UploadFile::Finished;
							uf.complete = 1.0f;
							uf.url = image->getStringAttribute("URL");

							Time end = Time::getCurrentTime();
							RelativeTime diff = end - start;

							addLogEntry(("Info: ") + uf.file.getFileName() + (" uploaded in ") + String(int(diff.inSeconds())) + (" seconds [") + String(uf.file.getSize() / 1024 / diff.inSeconds(), 1) + ("KB/s]"));

							retval.id  = val;
							retval.key = image->getStringAttribute(("Key"));
								
							delete e;
							return retval;
						}
					}
					delete e;
				}
			}
		} 		
	}

	uf.status = UploadFile::Failed;
	return retval;
}
Beispiel #17
0
/*
 *  This function uses the vcs_MultiPhaseEquil interface to the
 *  vcs solver.
 *  The function uses the element abundance vector that is
 *  currently consistent with the composition within the phases
 *  themselves. Two other thermodynamic quantities, determined by the
 *  XY string,  are held constant during the equilibration.
 *
 *  @param s The object to set to an equilibrium state
 *
 *  @param XY An integer specifying the two properties to be held
 *            constant.
 *
 *  @param estimateEquil integer indicating whether the solver
 *                   should estimate its own initial condition.
 *                   If 0, the initial mole fraction vector
 *                   in the %ThermoPhase object is used as the
 *                   initial condition.
 *                   If 1, the initial mole fraction vector
 *                   is used if the element abundances are
 *                   satisfied.
 *                   if -1, the initial mole fraction vector
 *                   is thrown out, and an estimate is
 *                   formulated.
 *
 *  @param printLvl Determines the amount of printing that
 *                  gets sent to stdout from the vcs package
 *                  (Note, you may have to compile with debug
 *                   flags to get some printing).
 *
 *  @param maxsteps The maximum number of steps to take to find
 *                  the solution.
 *
 *  @param maxiter For the MultiPhaseEquil solver only, this is
 *                 the maximum number of outer temperature or
 *                 pressure iterations to take when T and/or P is
 *                 not held fixed.
 *
 *  @param loglevel Controls amount of diagnostic output. loglevel
 *                  = 0 suppresses diagnostics, and increasingly-verbose
 *                  messages are written as loglevel increases. The
 *                  messages are written to a file in HTML format for viewing
 *                  in a web browser. @see HTML_logs
 *
 *  @ingroup equilfunctions
 */
int vcs_equilibrate_1(MultiPhase& s, int ixy,
                      int estimateEquil, int printLvl, int solver,
                      doublereal tol, int maxsteps, int maxiter, int loglevel)
{
    static int counter = 0;
    int retn = 1;

    beginLogGroup("equilibrate",loglevel);
    addLogEntry("multiphase equilibrate function");
    beginLogGroup("arguments");
    addLogEntry("XY",ixy);
    addLogEntry("tol",tol);
    addLogEntry("maxsteps",maxsteps);
    addLogEntry("maxiter",maxiter);
    addLogEntry("loglevel",loglevel);
    endLogGroup("arguments");

    int printLvlSub = std::max(0, printLvl-1);

    s.init();

    if (solver == 2) {
        try {
            VCSnonideal::vcs_MultiPhaseEquil* eqsolve =  new VCSnonideal::vcs_MultiPhaseEquil(&s, printLvlSub);
            int err = eqsolve->equilibrate(ixy, estimateEquil, printLvlSub, tol, maxsteps, loglevel);
            if (err != 0) {
                retn = -1;
                addLogEntry("vcs_equilibrate Error   - ", err);
            } else {
                addLogEntry("vcs_equilibrate Success - ", err);
            }
            endLogGroup("equilibrate");
            // hard code a csv output file.
            if (printLvl > 0) {
                string reportFile = "vcs_equilibrate_res.csv";
                if (counter > 0) {
                    reportFile = "vcs_equilibrate_res_" + int2str(counter) + ".csv";
                }
                eqsolve->reportCSV(reportFile);
                counter++;
            }
            delete eqsolve;
        } catch (CanteraError& e) {
            e.save();
            retn = -1;
            addLogEntry("Failure.", lastErrorMessage());
            endLogGroup("equilibrate");
            throw e;
        }
    } else if (solver == 1) {
        if (ixy == TP || ixy == HP || ixy == SP || ixy == TV) {
            try {
                double err = s.equilibrate(ixy, tol, maxsteps, maxiter, loglevel);

                addLogEntry("Success. Error",err);
                endLogGroup("equilibrate");

                return 0;
            } catch (CanteraError& e) {
                e.save();
                addLogEntry("Failure.",lastErrorMessage());
                endLogGroup("equilibrate");

                throw e;
            }
        } else {

            addLogEntry("multiphase equilibrium can be done only for TP, HP, SP, or TV");
            endLogGroup("equilibrate");

            throw CanteraError("equilibrate","unsupported option");
            //return -1.0;
        }
    } else {
        throw CanteraError("vcs_equilibrate_1", "unknown solver");
    }
    return retn;
}
Beispiel #18
0
  /*
   *  Set a single-phase chemical solution to chemical equilibrium.
   *  This is a convenience function that uses one or the other of
   *  the two chemical equilibrium solvers.
   * 
   *  @param s The object to set to an equilibrium state
   * 
   *  @param XY An integer specifying the two properties to be held
   *  constant.
   * 
   *  @param solver The equilibrium solver to use. If solver = 0,
   *  the ChemEquil solver will be used, and if solver = 1, the
   *  MultiPhaseEquil solver will be used (slower than ChemEquil,
   *  but more stable). If solver < 0 (default, then ChemEquil will
   *  be tried first, and if it fails MultiPhaseEquil will be tried.
   * 
   *  @param maxsteps The maximum number of steps to take to find
   *  the solution.
   * 
   *  @param maxiter For the MultiPhaseEquil solver only, this is
   *  the maximum number of outer temperature or pressure iterations
   *  to take when T and/or P is not held fixed.
   * 
   *  @param loglevel Controls amount of diagnostic output. loglevel
   *  = 0 suppresses diagnostics, and increasingly-verbose messages
   *  are written as loglevel increases. The messages are written to
   *  a file in HTML format for viewing in a web browser.
   *  @see HTML_logs
   * 
   *  @ingroup equil
   */
  int equilibrate(thermo_t& s, const char* XY, int solver,
		  doublereal rtol, int maxsteps, int maxiter, int loglevel) {
    MultiPhase* m = 0;
    ChemEquil* e = 0;
    bool redo = true;
    int retn = -1;
    int nAttempts = 0;
    int retnSub = 0;
  

    if (loglevel > 0) {
      beginLogGroup("equilibrate", loglevel);
      addLogEntry("Single-phase equilibrate function");
      {
	beginLogGroup("arguments");
	addLogEntry("phase",s.id());
	addLogEntry("XY",XY);
	addLogEntry("solver",solver);
	addLogEntry("rtol",rtol);
	addLogEntry("maxsteps",maxsteps);
	addLogEntry("maxiter",maxiter);
	addLogEntry("loglevel",loglevel);
	endLogGroup("arguments");
      }
    }
    while (redo) {
      if (solver >= 2) {
#ifdef WITH_VCSNONIDEAL
	int printLvlSub = 0;
	int estimateEquil = 0;
	m = new MultiPhase;
	try { 
	  m->addPhase(&s, 1.0);
	  m->init();
	  nAttempts++;
	  vcs_equilibrate(*m, XY, estimateEquil, printLvlSub, solver,
			  rtol, maxsteps, maxiter, loglevel-1); 
	  redo = false;
          if (loglevel > 0) 
	    addLogEntry("VCSnonideal solver succeeded.");
	  delete m;
	  retn = nAttempts;
	}
	catch (CanteraError &err) {
	  if (loglevel > 0) 
	    addLogEntry("VCSnonideal solver failed.");
	  delete m;
	  if (nAttempts < 2) {
	    if (loglevel > 0) 
	      addLogEntry("Trying single phase ChemEquil solver.");
	    solver = -1;
	  } 
	  else {
	    if (loglevel > 0) 
	      endLogGroup("equilibrate");
	    throw err;
	  }
	}
#else
	throw CanteraError("equilibrate", 
			   "VCSNonIdeal solver called, but not compiled");
#endif
      } else if (solver == 1) {
	m = new MultiPhase;
	try { 
	  m->addPhase(&s, 1.0);
	  m->init();
	  nAttempts++;
	  (void) equilibrate(*m, XY, rtol, maxsteps, maxiter, loglevel-1); 
	  redo = false;
          if (loglevel > 0) 
	    addLogEntry("MultiPhaseEquil solver succeeded.");
	  delete m;
	  retn = nAttempts;
	}
	catch (CanteraError &err) {
	  if (loglevel > 0) 
	    addLogEntry("MultiPhaseEquil solver failed.");
	  delete m;
	  if (nAttempts < 2) {
	    if (loglevel > 0) 
	      addLogEntry("Trying single phase ChemEquil solver.");
	    solver = -1;
	  } 
	  else {
	    if (loglevel > 0) 
	      endLogGroup("equilibrate");
	    throw err;
	  }
	}
      }
      else {        // solver <= 0
	/*
	 * Call the element potential solver
	 */
	e = new ChemEquil;
	try {
	  e->options.maxIterations = maxsteps;
	  e->options.relTolerance = rtol;
	  nAttempts++;
          bool useThermoPhaseElementPotentials = true;
	  retnSub = e->equilibrate(s,XY,
                                   useThermoPhaseElementPotentials, loglevel-1);
	  if (retnSub < 0) {
	    if (loglevel > 0) 
	      addLogEntry("ChemEquil solver failed.");
	    if (nAttempts < 2) {
	      if (loglevel > 0) 
		addLogEntry("Trying MultiPhaseEquil solver.");
	      solver = 1;
	    } else {
	      throw CanteraError("equilibrate", 
				 "Both equilibrium solvers failed");
	    }
	  }
	  retn = nAttempts;
	  s.setElementPotentials(e->elementPotentials());
	  redo = false;
	  delete e;
          if (loglevel > 0) 
	    addLogEntry("ChemEquil solver succeeded.");
	}

	catch (CanteraError &err) {
	  delete e;
          if (loglevel > 0) 
	    addLogEntry("ChemEquil solver failed.");
	  // If ChemEquil fails, try the MultiPhase solver
	  if (solver < 0) {
	    if (loglevel > 0) 
	      addLogEntry("Trying MultiPhaseEquil solver.");
	    solver = 1;
	  }
	  else {
	    redo = false;
            if (loglevel > 0) 
	      endLogGroup("equilibrate");
	    throw err;
	  }
	}
      } 
    } // while (redo)
    /*
     * We are here only for a success
     */
    if (loglevel > 0) 
      endLogGroup("equilibrate");
    return retn;
  }
Beispiel #19
0
/*
 *  Set a single-phase chemical solution to chemical equilibrium.
 *  This is a convenience function that uses one or the other of
 *  the two chemical equilibrium solvers.
 *
 *  @param s The object to set to an equilibrium state
 *
 *  @param XY An integer specifying the two properties to be held
 *            constant.
 *
 *  @param estimateEquil integer indicating whether the solver
 *                   should estimate its own initial condition.
 *                   If 0, the initial mole fraction vector
 *                   in the %ThermoPhase object is used as the
 *                   initial condition.
 *                   If 1, the initial mole fraction vector
 *                   is used if the element abundances are
 *                   satisfied.
 *                   if -1, the initial mole fraction vector
 *                   is thrown out, and an estimate is
 *                   formulated.
 *
 *  @param printLvl Determines the amount of printing that
 *                  gets sent to stdout from the vcs package
 *                  (Note, you may have to compile with debug
 *                   flags to get some printing).
 *
 *  @param solver The equilibrium solver to use. If solver = 0,
 *                the ChemEquil solver will be used, and if
 *                solver = 1, the vcs_MultiPhaseEquil solver will
 *                be used (slower than ChemEquil,
 *                but more stable). If solver < 0 (default, then
 *                ChemEquil will be tried first, and if it fails
 *                vcs_MultiPhaseEquil will be tried.
 *
 *  @param maxsteps The maximum number of steps to take to find
 *                  the solution.
 *
 *  @param maxiter For the MultiPhaseEquil solver only, this is
 *                 the maximum number of outer temperature or
 *                 pressure iterations to take when T and/or P is
 *                 not held fixed.
 *
 *  @param loglevel Controls amount of diagnostic output. loglevel
 *                  = 0 suppresses diagnostics, and increasingly-verbose
 *                  messages are written as loglevel increases. The
 *                  messages are written to a file in HTML format for viewing
 *                  in a web browser. @see HTML_logs
 */
int vcs_equilibrate(thermo_t& s, const char* XY,
                    int estimateEquil,  int printLvl,
                    int solver,
                    doublereal rtol, int maxsteps, int maxiter,
                    int loglevel)
{
    MultiPhase* m = 0;
    int retn = 1;
    int retnSub = 0;

    beginLogGroup("equilibrate", loglevel);
    // retry:
    addLogEntry("Single-phase equilibrate function");
    {
        beginLogGroup("arguments");
        addLogEntry("phase",s.id());
        addLogEntry("XY",XY);
        addLogEntry("solver",solver);
        addLogEntry("rtol",rtol);
        addLogEntry("maxsteps",maxsteps);
        addLogEntry("maxiter",maxiter);
        addLogEntry("loglevel",loglevel);
        endLogGroup("arguments");
    }

    if (solver == 2) {
        m = new MultiPhase;
        try {
            /*
             *  Set the kmoles of the phase to 1.0, arbitrarily.
             *  It actually doesn't matter.
             */
            m->addPhase(&s, 1.0);
            m->init();

            retn = vcs_equilibrate(*m, XY, estimateEquil, printLvl, solver,
                                   rtol, maxsteps, maxiter, loglevel);
            if (retn == 1) {
                addLogEntry("MultiPhaseEquil solver succeeded.");
            } else {
                addLogEntry("MultiPhaseEquil solver returned an error code: ", retn);
            }
            delete m;
        } catch (CanteraError& err) {
            err.save();
            addLogEntry("MultiPhaseEquil solver failed.");
            delete m;
            throw err;
        }
    } else if (solver == 1) {
        m = new MultiPhase;
        try {
            m->addPhase(&s, 1.0);
            m->init();
            (void) equilibrate(*m, XY, rtol, maxsteps, maxiter, loglevel-1);
            if (loglevel > 0) {
                addLogEntry("MultiPhaseEquil solver succeeded.");
            }
            delete m;
            retn = 1;
        } catch (CanteraError& err) {
            err.save();
            if (loglevel > 0) {
                addLogEntry("MultiPhaseEquil solver failed.");
            }
            delete m;
            throw err;
        }
    } else if (solver == 0) {
        ChemEquil* e = new ChemEquil;
        try {
            e->options.maxIterations = maxsteps;
            e->options.relTolerance = rtol;
            bool useThermoPhaseElementPotentials = false;
            if (estimateEquil == 0) {
                useThermoPhaseElementPotentials = true;
            }
            retnSub = e->equilibrate(s, XY,
                                     useThermoPhaseElementPotentials, loglevel-1);
            if (retnSub < 0) {
                if (loglevel > 0) {
                    addLogEntry("ChemEquil solver failed.");
                }
                delete e;
                throw CanteraError("equilibrate",
                                   "ChemEquil equilibrium solver failed");
            }
            retn = 1;
            s.setElementPotentials(e->elementPotentials());
            delete e;
            if (loglevel > 0) {
                addLogEntry("ChemEquil solver succeeded.");
            }
        } catch (CanteraError& err) {
            err.save();
            if (loglevel > 0) {
                addLogEntry("ChemEquil solver failed.");
            }
            delete e;
            throw err;
        }
    } else {
        throw CanteraError("vcs_equilibrate",
                           "unknown solver");
    }

    /*
     * We are here only for a success
     */
    endLogGroup("equilibrate");
    return retn;
}
Beispiel #20
0
/**
 * Function: get_ntp_time
 * Description: NTP服务器响应请求时该函数会被调用,根据服务器响应的数据,来获取服务器当前的时间以此来更新本机时间
**/
void get_ntp_time(void *arg, struct udp_pcb *pcb, struct pbuf *p,ip_addr_t *addr, u16_t port){
    //fd_set pending_data;
	  int i,num;
      struct timeval tv1;
	  struct ntp_packet newpack,ntppack;
	  char compile_date[20];
	  char *recv_data;    //存放收到的数据
	  uint64_t last;
      uint64_t seconds;
	  time_t tt;
	  struct tm *local;
	  uint32_t high_time;
	  uint32_t low_time;
	  //struct tm temp_tm;
	  time_t temp_time;
	  uint8_t is_need_update_log_time;  //是否需要更新日志时间
	  char *current_system_time = NULL;
	  char message[96];
	  num = 0;
	  request_failed_num = 0; //请求失败的次数重置为0
	  //printf("recv ntp server length is %d\n\r",uip_len);
	  newpack = *((struct ntp_packet*)p->payload);
	  memcpy(&high_time,((char*)p->payload) + 40,sizeof(high_time));
	  memcpy(&low_time,((char*)p->payload) + 44,sizeof(low_time));
	high_time = ntohl(high_time);
	last = high_time  - 2208988800;
    tt = last + 8 * 3600;
	local = localtime(&tt);
	//printf("string time is %s\n\r",ctime(&tt));
	//printf("get time is \n\r%d-%02d-%02d %02d:%02d:%02d %d\n\r",(local->tm_year + 1900),(local->tm_mon + 1),local->tm_mday,local->tm_hour,
	//		local->tm_min,local->tm_sec,local->tm_wday);
			
	/* 先检测是否需要记录系统启动的时间,记录此时系统时间,之后判断是否需要更新日志中时间 */
	is_need_update_log_time = recordSystemStartTime(&system_time,tt);
	/* 只需要记录此时系统时间的总秒数,系统时间以此为基础进行计算 */
	system_time.year = (local->tm_year + 1900);  //作为判断是否使用了系统默认时间的依据
	system_time.system_sec = tt;
	/* 是否需要更新日志列表中的时间,该方法只会调用一次 */
	if(is_need_update_log_time == 1){  //需要更新日志列表的时间
		updateSystemLogTime(system_start_time);
	}
	/* 关闭计时器,重置计时器 */
	is_open_ntp_request_timer = 0;
	ntp_send_request_time = sCount;
	time_update_interval = sCount;
	if(is_need_record_time_log){  //之前时间同步失败过,现在时间恢复了,需要记录
		current_system_time = calcSystemTime();
		memset(message,0,sizeof(message));
		sprintf(message,"系统时间同步完成,当前系统时间为 %s",current_system_time);
		addLogEntry(INFO,"vorx",message);   //时间同步完成
		printSystemLog();
		is_need_record_time_log = 0;    //设置需要记录标志为false
	}
	/* 收到数据以后设置ntp请求时间为默认值 */
	ntp_request_timeout = DEFAULT_NTP_TIME_OUT;  
	free(current_system_time);
	current_system_time = NULL;
	/* 释放下层传递过来的内存空间,由于在udp_input函数中没有发现释放该空间的相关代码
	** 因此需要把该部分空间释放。
	*/
	pbuf_free(p);  //释放空间
}