コード例 #1
0
ファイル: jsamaroo.c プロジェクト: jns0987654321/CIS_2500
int main(int argc, char *argv[]) {
	int *array;
	int width, height;
	int value;
	char **stringPtr;
	int **matrix;
	
	/* testing for part 1 */
	printf("Testing Part 1\n");
	width = 5;
	height = 6;
	
	array = create2DArray(height, width);
	
	printf("Store value 7 at [3,4].\n");
	set2DElement(array, 3, 4, 7);
	
	value = get2DElement(array, 3, 4);
	printf("Retrieve value %d from [3,4]\n\n", value);
	
	free2DArray(array);
	
	
	/* testing for part 2 */
	printf("Testing Part 2\n");
	stringPtr = createStringArray(100);
	
	printf("Store string - fred\n");
	setStringArray(stringPtr, 44, "fred");
	printf("Store string - barney\n");
	setStringArray(stringPtr, 80, "barney");
	
	printf("Get string - %s\n", getStringArray(stringPtr, 44));
	printf("Get string - %s\n", getStringArray(stringPtr, 80));
	/* test with NULL string */
	printf("Get string - %s\n\n", getStringArray(stringPtr, 3));
	
	freeStringArray(stringPtr, 100);
	
	
	/* testing for part 3 */
	printf("Testing Part 3\n");
	matrix = createArray(100, 100);
	
	printf("Store 33 44 55\n");
	matrix[22][76] = 33;
	matrix[83][29] = 44;
	matrix[99][65] = 55;
	
	printf("Retrieve %d %d %d\n", matrix[22][76], matrix[83][29],
		   matrix[99][65]);
	
	freeArray(matrix, 100);
	
	return(1);
}
コード例 #2
0
ファイル: galax_jni_stub.c プロジェクト: HanumathRao/Galax
JNIEXPORT jint JNICALL 
Java_galapi_ExternalContext_externalContextToItem
(JNIEnv * jne, jclass jc, jint pc, jint ctxt, jint tz,
 jobjectArray jarr, jintArray values) {

  jint *p = (*jne)->GetIntArrayElements (jne, values, NULL);
  //jsize n = (*jne)->GetArrayLength (jne, values);

  jsize sz = (*jne)->GetArrayLength (jne, jarr);
  char **a = getStringArray (jne, jarr);
  external_context ec;
  itemlist ctil = (itemlist) ctxt;
  itemlist tzil = (itemlist) tz;

  galax_err err =
    galax_build_external_context ((processing_context) pc, ctil, tzil, a, (itemlist*) p, sz, &ec);

    
  releaseStringArray (jne, jarr, a);
  (*jne)->ReleaseIntArrayElements (jne, values, p, 0); 

  if (0 != err)
    throw_galapi_exception (jne, galax_error_string, err);

  return (jint) ec;  
  
}// Java_galapi_ExternalContext_externalContextToItem()
コード例 #3
0
ファイル: ThermoFactory.cpp プロジェクト: arghdos/cantera
void installElements(Phase& th, const XML_Node& phaseNode)
{
    // get the declared element names
    if (!phaseNode.hasChild("elementArray")) {
        throw CanteraError("installElements",
                           "phase XML node doesn't have \"elementArray\" XML Node");
    }
    XML_Node& elements = phaseNode.child("elementArray");
    vector<string> enames;
    getStringArray(elements, enames);

    // // element database defaults to elements.xml
    string element_database = "elements.xml";
    if (elements.hasAttrib("datasrc")) {
        element_database = elements["datasrc"];
    }

    XML_Node* doc = get_XML_File(element_database);
    XML_Node* dbe = &doc->child("elementData");

    XML_Node& root = phaseNode.root();
    XML_Node* local_db = 0;
    if (root.hasChild("elementData")) {
        local_db = &root.child("elementData");
    }

    for (size_t i = 0; i < enames.size(); i++) {
        // Find the element data
        XML_Node* e = 0;
        if (local_db) {
            e = local_db->findByAttr("name",enames[i]);
        }
        if (!e) {
            e = dbe->findByAttr("name",enames[i]);
        }
        if (!e) {
            throw CanteraError("addElementsFromXML","no data for element "
                               +enames[i]);
        }

        // Add the element
        doublereal weight = 0.0;
        if (e->hasAttrib("atomicWt")) {
            weight = fpValue(e->attrib("atomicWt"));
        }
        int anum = 0;
        if (e->hasAttrib("atomicNumber")) {
            anum = intValue(e->attrib("atomicNumber"));
        }
        string symbol = e->attrib("name");
        doublereal entropy298 = ENTROPY298_UNKNOWN;
        if (e->hasChild("entropy298")) {
            XML_Node& e298Node = e->child("entropy298");
            if (e298Node.hasAttrib("value")) {
                entropy298 = fpValueCheck(e298Node["value"]);
            }
        }
        th.addElement(symbol, weight, anum, entropy298);
    }
}
コード例 #4
0
ファイル: riblexer.cpp プロジェクト: UIKit0/aqsis
RibLexer::StringArray RibLexerImpl::getStringParam()
{
    if(m_tokenizer.peek().type() == RibToken::STRING)
    {
        // special case where next token is a single string.
        MultiStringBuffer& buf = m_stringArrayPool.getBuf();
        buf.push_back(m_tokenizer.get().stringVal());
        return toRiArray(buf);
    }
    return getStringArray();
}
コード例 #5
0
ファイル: ctml.cpp プロジェクト: iokto/cantera
void getMap(const XML_Node& node, std::map<std::string, std::string>& m)
{
    std::vector<std::string> v;
    getStringArray(node, v);
    for (size_t i = 0; i < v.size(); i++) {
        size_t icolon = v[i].find(":");
        if (icolon == string::npos) {
            throw CanteraError("getMap","missing colon in map entry ("
                               +v[i]+")");
        }
        m[v[i].substr(0,icolon)] = v[i].substr(icolon+1, v[i].size());
    }
}
コード例 #6
0
ファイル: Elements.cpp プロジェクト: hkmoffat/cantera
  void Elements::addElementsFromXML(const XML_Node& phase) {

    // get the declared element names
    if (! phase.hasChild("elementArray")) {
      throw CanteraError("Elements::addElementsFromXML",
			 "phase xml node doesn't have \"elementArray\" XML Node");
    }
    XML_Node& elements = phase.child("elementArray");
    vector<string> enames;
    getStringArray(elements, enames);
        
    // // element database defaults to elements.xml
    string element_database = "elements.xml";
    if (elements.hasAttrib("datasrc")) 
      element_database = elements["datasrc"];

    XML_Node* doc = get_XML_File(element_database);
    XML_Node* dbe = &doc->child("ctml/elementData");

    XML_Node& root = phase.root();
    XML_Node* local_db = 0;
    if (root.hasChild("ctml")) {
      if (root.child("ctml").hasChild("elementData")) {
	local_db = &root.child("ctml/elementData");
      }
    }

    int nel = static_cast<int>(enames.size());
    int i;
    string enm;
    XML_Node* e = 0;
    for (i = 0; i < nel; i++) {
      e = 0;
      if (local_db) {
	//writelog("looking in local database.");
	e = local_db->findByAttr("name",enames[i]);
	//if (!e) writelog(enames[i]+" not found.");
      }
      if (!e)
	e = dbe->findByAttr("name",enames[i]);
      if (e) {
	addUniqueElement(*e);
      }
      else {
	throw CanteraError("addElementsFromXML","no data for element "
			   +enames[i]);
      }
    }

  }
コード例 #7
0
ファイル: ctml.cpp プロジェクト: anujg1991/cantera
  /*
   *  These are used, for example, in describing the element 
   *  composition of species.
   *
   *       <atomArray> H:4 C:1 <atomArray\>
   *
   *  The string is first separated into a string vector according
   * to the location of white space. Then each string is again
   * separated into two parts according to the location of a
   * colon in the string. The first part of the string is
   * used as the key, while the second part of the string is
   * used as the value, in the return map.
   * It is an error to not find a colon in each string pair.
   *
   *  @param node Current node
   *  @param m    Output Map containing the pairs of values found
   *              in the XML Node
   */
  void getMap(const Cantera::XML_Node& node, std::map<std::string, std::string>& m) {
    std::vector<std::string> v;
    getStringArray(node, v);
    std::string key, val;
    int n = static_cast<int>(v.size());
    string::size_type icolon;
    for (int i = 0; i < n; i++) {
      icolon = v[i].find(":");
      if (icolon == string::npos) {
	throw CanteraError("getMap","missing colon in map entry ("
			   +v[i]+")");
      }
      key = v[i].substr(0,icolon);
      val = v[i].substr(icolon+1, v[i].size());
      m[key] = val;
    }
  }
コード例 #8
0
ファイル: ctml.cpp プロジェクト: iokto/cantera
int getPairs(const XML_Node& node, std::vector<std::string>& key,
             std::vector<std::string>& val)
{
    vector<string> v;
    getStringArray(node, v);
    int n = static_cast<int>(v.size());
    for (int i = 0; i < n; i++) {
        size_t icolon = v[i].find(":");
        if (icolon == string::npos) {
            throw CanteraError("getPairs","Missing a colon in the Pair entry ("
                               +v[i]+")");
        }
        key.push_back(v[i].substr(0,icolon));
        val.push_back(v[i].substr(icolon+1, v[i].size()));
    }
    return n;
}
コード例 #9
0
// MFloatVector GlobalNodeHelper::getVector3(const MString& attrName )
// {
//  	MStatus status;
//  	MFloatVector value(-1.0f, -1.0f, -1.0f);
// // 	liquidGetPlugValue(m_GlobalNode, attrName.asChar(), value, status);
// // 	IfMErrorMsgWarn(status,"elvishray::GlobalNodeHelper::getVector("+attrName+")"
// 	MStringArray a(getStringArray(attrName));
// 	switch(a.length())
// 	{
// 		case 1: 
// 			value.x = a[0].asFloat();	
// 			break;
// 		case 2: 
// 			value.x = a[0].asFloat(); 
// 			value.y = a[1].asFloat();	
// 			break;
// 		case 3: 
// 			value.x = a[0].asFloat();
// 			value.y = a[1].asFloat();
// 			value.z = a[2].asFloat();	
// 			break;
// 		default:
// 			liquidMessage2(messageError, "GlobalNodeHelper::getVector3(%s), sub-element length=%d", attrName.asChar(), a.length());
// 	}
// 	return value;
// }
MFloatPoint GlobalNodeHelper::getVector(const MString& attrName )
{
 	MStatus status;
 	MFloatPoint value(-1.0f, -1.0f, -1.0f, -1.0f);
// 	liquidGetPlugValue(m_GlobalNode, attrName.asChar(), value, status);
// 	IfMErrorMsgWarn(status,"elvishray::GlobalNodeHelper::getVector("+attrName+")"
	MStringArray a(getStringArray(attrName));
	switch(a.length())
	{
		case 4: value.w = a[3].asFloat();
		case 3: value.z = a[2].asFloat();
		case 2: value.y = a[1].asFloat();
		case 1: value.x = a[0].asFloat(); break;
		default:
			liquidMessage2(messageError, "GlobalNodeHelper::getVector(%s), sub-element length=%d", attrName.asChar(), a.length());
	}
	return value;
}
コード例 #10
0
ファイル: ctml.cpp プロジェクト: anujg1991/cantera
  /*
   * Each pair consists of nonwhite-space characters.
   * The first two ":" found in the pair string is used to separate
   * the string into three parts. The first part is called the first
   * key. The second part is the second key. Both parts must match
   * an entry in the keyString1 and keyString2, respectively,
   * in order to provide a location to
   * place the object in the matrix.
   * The third part is called the value. It is expected to be
   * a double. It is translated into a double and placed into the
   * correct location in the matrix.
   *
   * Warning: No spaces are allowed in each triplet. Quotes are part
   *          of the string.
   *   Example
   *         keyString = red, blue, black, green
   *    <xmlNode>
   *        red:green:112
   *        blue:black:3.3E-23
   *
   *    </xmlNode>
   *
   * Returns:
   *     retnValues(0, 3) = 112
   *     retnValues(1, 2) = 3.3E-23
   *
   *
   *  @param node          XML Node containing the information for the matrix
   *  @param keyStringRow  Key string for the row
   *  @param keyStringCol  Key string for the column entries
   *  @param returnValues  Return Matrix.
   *  @param convert       If this is true, and if the node has a units 
   *                       attribute, then conversion to si units is carried
   *                       out. Default is true.
   *  @param matrixSymmetric  If true entries are made so that the matrix
   *                       is always symmetric. Default is false.
   */
  void getMatrixValues(const Cantera::XML_Node& node,
		       const std::vector<std::string>& keyStringRow,
		       const std::vector<std::string>& keyStringCol,
		       Cantera::Array2D &retnValues, const bool convert,
		       const bool matrixSymmetric) {
    int szKey1 = keyStringRow.size();
    int szKey2 = keyStringCol.size();
    int nrow   = retnValues.nRows();
    int ncol   = retnValues.nColumns();
    if (szKey1 > nrow) {
      throw CanteraError("getMatrixValues", 
			 "size of key1 greater than numrows");
    }
    if (szKey2 > ncol) {
      throw CanteraError("getMatrixValues", 
			 "size of key2 greater than num cols");
    }
    if (matrixSymmetric) {
      if (nrow != ncol) {
	throw CanteraError("getMatrixValues", 
			   "nrow != ncol for a symmetric matrix");
      }
    }

    /*
     * Get the attributes field, units, from the XML node
     * and determine the conversion factor, funit.
     */
    doublereal funit = 1.0;
    string units = node["units"];
    if (units != "" && convert) {
      funit = toSI(units);
    }
	
    string key1;
    string key2;
    string rmm;
    string val;
    vector<string> v;
    getStringArray(node, v);
    int icol, irow;
    int n = static_cast<int>(v.size());
    string::size_type icolon;
    for (int i = 0; i < n; i++) {
      icolon = v[i].find(":");
      if (icolon == string::npos) {
	throw CanteraError("getMatrixValues","Missing two colons ("
			   +v[i]+")");
      }
      key1 = v[i].substr(0,icolon);
      rmm = v[i].substr(icolon+1, v[i].size());
      icolon = rmm.find(":");
      if (icolon == string::npos) {
	throw CanteraError("getMatrixValues","Missing one colon ("
			   +v[i]+")");
      }
      key2 = rmm.substr(0,icolon);
      val = rmm.substr(icolon+1, rmm.size());
      icol = -1;
      irow = -1;
      for (int j = 0; j < szKey1; j++) {
	if (key1 == keyStringRow[j]) {
	  irow = j;
	  break;
	}
      }
      if (irow == -1) {
	throw CanteraError("getMatrixValues","Row not matched by string: "
			   + key1);		
      }
      for (int j = 0; j < szKey2; j++) {
	if (key2 == keyStringCol[j]) {
	  icol = j;
	  break;
	}
      }
      if (icol == -1) {
	throw CanteraError("getMatrixValues","Col not matched by string: "
			   + key2);	
      }
      double dval = atofCheck(val.c_str());
      dval *= funit;
      /*
       * Finally, insert the value;
       */
      retnValues(irow, icol) = dval;
      if (matrixSymmetric) {
	retnValues(icol, irow) = dval;
      }
    }
  }
コード例 #11
0
ファイル: ThermoFactory.cpp プロジェクト: arghdos/cantera
/*!
 *   @param spDataNodeList   Output vector of pointer to XML_Nodes which contain
 *       the species XML_Nodes for the species in the current phase.
 *   @param spNamesList      Output Vector of strings, which contain the names
 *       of the species in the phase
 *   @param spRuleList       Output Vector of ints, which contain the value of
 *       sprule for each species in the phase
 *   @param spArray_names    Vector of pointers to the XML_Nodes which contains
 *                           the names of the species in the phase
 *   @param spArray_dbases   Input vector of pointers to species data bases. We
 *                           search each data base for the required species
 *                           names
 *   @param  sprule          Input vector of sprule values
 */
static void formSpeciesXMLNodeList(std::vector<XML_Node*> &spDataNodeList,
                                   std::vector<std::string> &spNamesList,
                                   vector_int &spRuleList,
                                   const std::vector<XML_Node*> spArray_names,
                                   const std::vector<XML_Node*> spArray_dbases,
                                   const vector_int sprule)
{
    // used to check that each species is declared only once
    std::map<std::string, bool> declared;

    for (size_t jsp = 0; jsp < spArray_dbases.size(); jsp++) {
        const XML_Node& speciesArray = *spArray_names[jsp];

        // Get the top XML for the database
        const XML_Node* db = spArray_dbases[jsp];

        // Get the array of species name strings and then count them
        std::vector<std::string> spnames;
        getStringArray(speciesArray, spnames);
        size_t nsp = spnames.size();

        // if 'all' is specified as the one and only species in the
        // spArray_names field, then add all species defined in the
        // corresponding database to the phase
        if (nsp == 1 && spnames[0] == "all") {
            std::vector<XML_Node*> allsp = db->getChildren("species");
            nsp = allsp.size();
            spnames.resize(nsp);
            for (size_t nn = 0; nn < nsp; nn++) {
                string stemp = (*allsp[nn])["name"];
                if (!declared[stemp] || sprule[jsp] < 10) {
                    declared[stemp] = true;
                    spNamesList.push_back(stemp);
                    spDataNodeList.push_back(allsp[nn]);
                    spRuleList.push_back(sprule[jsp]);
                }
            }
        } else if (nsp == 1 && spnames[0] == "unique") {
            std::vector<XML_Node*> allsp = db->getChildren("species");
            nsp = allsp.size();
            spnames.resize(nsp);
            for (size_t nn = 0; nn < nsp; nn++) {
                string stemp = (*allsp[nn])["name"];
                if (!declared[stemp]) {
                    declared[stemp] = true;
                    spNamesList.push_back(stemp);
                    spDataNodeList.push_back(allsp[nn]);
                    spRuleList.push_back(sprule[jsp]);
                }
            }
        } else {
            std::map<std::string, XML_Node*> speciesNodes;
            for (size_t k = 0; k < db->nChildren(); k++) {
                XML_Node& child = db->child(k);
                speciesNodes[child["name"]] = &child;
            }
            for (size_t k = 0; k < nsp; k++) {
                string stemp = spnames[k];
                if (!declared[stemp] || sprule[jsp] < 10) {
                    declared[stemp] = true;
                    // Find the species in the database by name.
                    auto iter = speciesNodes.find(stemp);
                    if (iter == speciesNodes.end()) {
                        throw CanteraError("importPhase","no data for species, \""
                                           + stemp + "\"");
                    }
                    spNamesList.push_back(stemp);
                    spDataNodeList.push_back(iter->second);
                    spRuleList.push_back(sprule[jsp]);
                }
            }
        }
    }
}
コード例 #12
0
ファイル: clientList.c プロジェクト: duiliofelix/MAC448-EP1
void parseMessage(char *line, clientNode *thisClient) {
    char *message[256];
    char *lineCopy = malloc(sizeof(char) * (strlen(line) + 1));
    char replie[256];
    char dia[3], mes[4], nMes[3], ano[5];
    int sendReplie = 1;
    int temp;

    //Quebra a linha em palavras
    strcpy(lineCopy, line);
    getStringArray(lineCopy, message, " ");

    replie[0] = '\0';
    for(int i = 0; message[0][i]; i++)
        message[0][i] = toupper(message[0][i]);
    if(strcmp(message[0], "NICK") == 0) {
        if(message[1] == NULL)
            sprintf(replie, ":%s %d * :Nickname não foi passado!\n", SERVER_NAME, ERR_NONICKNAMEGIVEN);

        pthread_mutex_lock(&clientMutex);
        if(clientWithNick(message[1], thisClient->head) != NULL)
            sprintf(replie, ":%s %d * %s :Nickname já está sendo usado!\n", SERVER_NAME, ERR_NICKNAMEINUSE, message[1]);
        else {
            strcpy(thisClient->nick, message[1]);
            sendReplie = 0;
        }

        pthread_mutex_unlock(&clientMutex);
    } else if(strcmp(message[0], "LIST") == 0) {
        listChannels(thisClient->socket);
        sendReplie = 0;
    } else if(strcmp(message[0], "JOIN") == 0) {
        if(message[1] == NULL)
            sprintf(replie, ":%s %d * JOIN :Parâmetros insuficientes!\n", SERVER_NAME, ERR_NEEDMOREPARAMS);
        else if(thisClient->nick[0] == '\0')
            sprintf(replie, ":%s %d * :Você não registrou seu NICK!\n", SERVER_NAME, ERR_NOTREGISTERED);
        else {
            sprintf(replie, ":%s JOIN %s\n", thisClient->nick, message[1]);
            printf("[Cliente %d entrou no canal %s]\n", thisClient->socket, message[1]);
            joinChannel(message[1], thisClient);
        }
    } else if(strcmp(message[0], "PRIVMSG") == 0) {
        if(thisClient->nick[0] == '\0')
            sprintf(replie, ":%s %d * :Você não registrou seu NICK!\n", SERVER_NAME, ERR_NOTREGISTERED);
        else {
            if(message[1][0] == '#')
                broadcastMessage(line, thisClient->nick, message[1]);
            else
                sendMessage(line, thisClient, message[1]);
            sendReplie = 0;
        }
    } else if(strcmp(message[0], "PART") == 0) {
        sprintf(replie, ":%s PART %s\n", thisClient->nick, message[1]);
        printf("[Cliente %d saiu do canal %s]\n", thisClient->socket, message[1]);
        delRef(thisClient->socket, message[1]);
    } else if(strcmp(message[0], "QUIT") == 0) {
        sprintf(replie, ":%s QUIT\n", thisClient->nick);
        close(thisClient->socket);
    } else if(strcmp(message[0], "MACDATA") == 0) {
        strncat(dia, __DATE__ +4, 2);
        strncat(mes, __DATE__, 3);
        strncat(ano, __DATE__ +7, 4);

        if(strcmp(mes, "Jan") == 0)
            strncpy(nMes, "01", 2);
        else if(strcmp(mes, "Feb") == 0)
            strncpy(nMes, "02", 2);
        else if(strcmp(mes, "Mar") == 0)
            strncpy(nMes, "03", 2);
        else if(strcmp(mes, "Apr") == 0)
            strncpy(nMes, "04", 2);
        else if(strcmp(mes, "May") == 0)
            strncpy(nMes, "05", 2);
        else if(strcmp(mes, "Jun") == 0)
            strncpy(nMes, "06", 2);
        else if(strcmp(mes, "Jul") == 0)
            strncpy(nMes, "07", 2);
        else if(strcmp(mes, "Aug") == 0)
            strncpy(nMes, "08", 2);
        else if(strcmp(mes, "Sep") == 0)
            strncpy(nMes, "09", 2);
        else if(strcmp(mes, "Oct") == 0)
            strncpy(nMes, "10", 2);
        else if(strcmp(mes, "Nov") == 0)
            strncpy(nMes, "11", 2);
        else
            strncpy(nMes, "12", 2);

        sprintf(replie, "%s/%s/%s\n", dia, nMes, ano);
    } else if(strcmp(message[0], "MACHORA") == 0) {
        sprintf(replie, "%s\n", __TIME__);
    } else if(strcmp(message[0], "MACTEMPERATURA") == 0) {
        temp = getTemp();

        sprintf(replie, "Temperatura atual: %dºC\nObitido de http://developers.agenciaideias.com.br/tempo/xml/saopaulo-sp\n", temp);
    }
   
    if(sendReplie) {
        if(replie[0] == '\0') {
            sprintf(replie, "%s\n", line);
        }

        printf("[Resposta para cliente %d] %s", thisClient->socket, replie);
        write(thisClient->socket, replie, strlen(replie));
    }

    replie[0] = '\0';
    free(lineCopy);
}
コード例 #13
0
bool importKinetics(const XML_Node& phase, std::vector<ThermoPhase*> th,
                    Kinetics* k)
{
    if (k == 0) {
        return false;
    }

    // This phase will be the owning phase for the kinetics operator
    // For interfaces, it is the surface phase between two volumes.
    // For homogeneous kinetics, it's the current volumetric phase.
    string owning_phase = phase["id"];

    bool check_for_duplicates = false;
    if (phase.parent() && phase.parent()->hasChild("validate")) {
        const XML_Node& d = phase.parent()->child("validate");
        if (d["reactions"] == "yes") {
            check_for_duplicates = true;
        }
    }

    // If other phases are involved in the reaction mechanism, they must be
    // listed in a 'phaseArray' child element. Homogeneous mechanisms do not
    // need to include a phaseArray element.
    vector<string> phase_ids;
    if (phase.hasChild("phaseArray")) {
        const XML_Node& pa = phase.child("phaseArray");
        getStringArray(pa, phase_ids);
    }
    phase_ids.push_back(owning_phase);

    // for each referenced phase, attempt to find its id among those
    // phases specified.
    string msg = "";
    for (size_t n = 0; n < phase_ids.size(); n++) {
        string phase_id = phase_ids[n];
        bool phase_ok = false;
        // loop over the supplied 'ThermoPhase' objects representing
        // phases, to find an object with the same id.
        for (size_t m = 0; m < th.size(); m++) {
            if (th[m]->id() == phase_id) {
                phase_ok = true;
                // if no phase with this id has been added to
                //the kinetics manager yet, then add this one
                if (k->phaseIndex(phase_id) == npos) {
                    k->addPhase(*th[m]);
                }
            }
            msg += " "+th[m]->id();
        }
        if (!phase_ok) {
            throw CanteraError("importKinetics",
                               "phase "+phase_id+" not found. Supplied phases are:"+msg);
        }
    }

    // allocates arrays, etc. Must be called after the phases have been added to
    // 'kin', so that the number of species in each phase is known.
    k->init();

    // Install the reactions.
    return installReactionArrays(phase, *k, owning_phase, check_for_duplicates);
}
コード例 #14
0
ファイル: regstore.c プロジェクト: sfsy1989/j2me
/**
 * Fills <code>JSR211_content_handler</code> structure with data from 
 * <code>ContentHandlerImpl</code> object.
 * <BR>Fields <code>ID, storageId</code> and <code>classname</code>
 * are mandatory. They must have not 0 length.
 *
 * @param o <code>ContentHandlerImpl</code> object
 * @param handler pointer on <code>JSR211_content_handler</code> structure
 * to be filled up
 * @return KNI_OK - if successfully get all fields, 
 * KNI_ERR or KNI_ENOMEM - otherwise
 */
static int fillHandlerData(jobject o, JSR211_content_handler* handler) {
    int ret;    // returned result code
    KNI_StartHandles(1);
    KNI_DeclareHandle(fldObj);   // field object

    do {
        // ID
        KNI_GetObjectField(o, chImplId, fldObj);
        if (PCSL_STRING_OK != midp_jstring_to_pcsl_string(fldObj, &(handler->id))) {
            ret = KNI_ENOMEM;
            break;
        }
        // check mandatory field
        if (pcsl_string_length(&(handler->id)) <= 0) {
            ret = KNI_ERR;
            break;
        }

        // suiteId
        handler->suite_id = KNI_GetIntField(o, chImplSuiteId);

        // classname
        KNI_GetObjectField(o, chImplClassname, fldObj);
        if (PCSL_STRING_OK != midp_jstring_to_pcsl_string(fldObj, &(handler->class_name))) {
            ret = KNI_ENOMEM;
            break;
        }

        // flag
        handler->flag = KNI_GetIntField(o, chImplregMethod);

        // types
        KNI_GetObjectField(o, chImplTypes, fldObj);
        handler->type_num = getStringArray(fldObj, &(handler->types));
        if (handler->type_num < 0) {
            ret = KNI_ENOMEM;
            break;
        }

        // suffixes        
        KNI_GetObjectField(o, chImplSuffixes, fldObj);
        handler->suff_num = getStringArray(fldObj, &(handler->suffixes));
        if (handler->suff_num < 0) {
            ret = KNI_ENOMEM;
            break;
        }

        // actions
        KNI_GetObjectField(o, chImplActions, fldObj);
        handler->act_num = getStringArray(fldObj, &(handler->actions));
        if (handler->act_num < 0) {
            ret = KNI_ENOMEM;
            break;
        }

        // action names
        if (handler->act_num > 0) {
            KNI_GetObjectField(o, chImplActionnames, fldObj);
            ret = fillActionMap(fldObj, handler);
            if (KNI_OK != ret) {
                break;
            }
        }

        // accesses
        KNI_GetObjectField(o, chImplAccesses, fldObj);
        handler->access_num = getStringArray(fldObj, &(handler->accesses));
        if (handler->access_num < 0) {
            ret = KNI_ENOMEM;
            break;
        }

        ret = KNI_OK;
    } while (0);

    KNI_EndHandles();
    return ret;
}
コード例 #15
0
ファイル: MargulesVPSSTP.cpp プロジェクト: anujg1991/cantera
  /*
   *   Import, construct, and initialize a HMWSoln phase 
   *   specification from an XML tree into the current object.
   *
   *   Most of the work is carried out by the cantera base
   *   routine, importPhase(). That routine imports all of the
   *   species and element data, including the standard states
   *   of the species.
   *
   *   Then, In this routine, we read the information 
   *   particular to the specification of the activity 
   *   coefficient model for the Pitzer parameterization.
   *
   *   We also read information about the molar volumes of the
   *   standard states if present in the XML file.
   *
   * @param phaseNode This object must be the phase node of a
   *             complete XML tree
   *             description of the phase, including all of the
   *             species data. In other words while "phase" must
   *             point to an XML phase object, it must have
   *             sibling nodes "speciesData" that describe
   *             the species in the phase.
   * @param id   ID of the phase. If nonnull, a check is done
   *             to see if phaseNode is pointing to the phase
   *             with the correct id. 
   */
  void MargulesVPSSTP::constructPhaseXML(XML_Node& phaseNode, std::string id) {
    string stemp;
    if (id.size() > 0) {
      string idp = phaseNode.id();
      if (idp != id) {
	throw CanteraError("MargulesVPSSTP::constructPhaseXML", 
			   "phasenode and Id are incompatible");
      }
    }

    /*
     * Find the Thermo XML node 
     */
    if (!phaseNode.hasChild("thermo")) {
      throw CanteraError("MargulesVPSSTP::constructPhaseXML",
			 "no thermo XML node");
    }
    XML_Node& thermoNode = phaseNode.child("thermo");

    /*
     * Possibly change the form of the standard concentrations
     */
 
    /*
     * Get the Name of the Solvent:
     *      <solvent> solventName </solvent>
     */
    string solventName = "";
    if (thermoNode.hasChild("solvent")) {
      XML_Node& scNode = thermoNode.child("solvent");
      vector<string> nameSolventa;
      getStringArray(scNode, nameSolventa);
      int nsp = static_cast<int>(nameSolventa.size());
      if (nsp != 1) {
	throw CanteraError("MargulesVPSSTP::constructPhaseXML",
			   "badly formed solvent XML node");
      }
      solventName = nameSolventa[0];
    }

    /*
     * Determine the form of the Pitzer model,
     *   We will use this information to size arrays below.
     */
    if (thermoNode.hasChild("activityCoefficients")) {
      XML_Node& scNode = thermoNode.child("activityCoefficients");
 
      stemp = scNode.attrib("model");
      string formString = lowercase(stemp);
      if (formString != "") {
	if        (formString == "margules" || formString == "default") {
	  formMargules_ = 0;

	} else {
	  throw CanteraError("MargulesVPSSTP::constructPhaseXML",
			     "Unknown ActivityCoeff model: "
			     + formString);
	}
      }

      /*
       * Determine the form of the temperature dependence
       * of the Pitzer activity coefficient model.
       */
      stemp = scNode.attrib("TempModel");
      formString = lowercase(stemp);
      if (formString != "") {
	if (formString == "constant" || formString == "default") {
	  formTempModel_ = 0;
	} else {
	  throw CanteraError("MargulesVPSSTP::constructPhaseXML",
			     "Unknown Pitzer ActivityCoeff Temp model: "
			     + formString);
	}
      }

      
    }

    /*
     * Call the Cantera importPhase() function. This will import
     * all of the species into the phase. This will also handle
     * all of the solvent and solute standard states
     */
    bool m_ok = importPhase(phaseNode, this);
    if (!m_ok) {
      throw CanteraError("MargulesVPSSTP::constructPhaseXML","importPhase failed "); 
    }
    
  }
コード例 #16
0
bool checkElectrochemReaction(const XML_Node& p, Kinetics& kin, const XML_Node& r)
{
    // If other phases are involved in the reaction mechanism, they must be
    // listed in a 'phaseArray' child element. Homogeneous mechanisms do not
    // need to include a phaseArray element.
    vector<string> phase_ids;
    if (p.hasChild("phaseArray")) {
        const XML_Node& pa = p.child("phaseArray");
        getStringArray(pa, phase_ids);
    }
    phase_ids.push_back(p["id"]);

    // Get reaction product and reactant information
    Composition reactants = parseCompString(r.child("reactants").value());
    Composition products = parseCompString(r.child("products").value());


    // If the reaction has undeclared species don't perform electrochemical check
    for (const auto& sp : reactants) {
        if (kin.kineticsSpeciesIndex(sp.first) == npos) {
            return true;
        }
    }

    for (const auto& sp : products) {
        if (kin.kineticsSpeciesIndex(sp.first) == npos) {
            return true;
        }
    }

    // Initialize the electron counter for each phase
    std::vector<double> e_counter(phase_ids.size(), 0.0);

    // Find the amount of electrons in the products for each phase
    for (const auto& sp : products) {
        const ThermoPhase& ph = kin.speciesPhase(sp.first);
        size_t k = ph.speciesIndex(sp.first);
        double stoich = sp.second;
        for (size_t m = 0; m < phase_ids.size(); m++) {
            if (phase_ids[m] == ph.id()) {
                e_counter[m] += stoich * ph.charge(k);
                break;
            }
        }
    }

    // Subtract the amount of electrons in the reactants for each phase
    for (const auto& sp : reactants) {
        const ThermoPhase& ph = kin.speciesPhase(sp.first);
        size_t k = ph.speciesIndex(sp.first);
        double stoich = sp.second;
        for (size_t m = 0; m < phase_ids.size(); m++) {
            if (phase_ids[m] == ph.id()) {
                e_counter[m] -= stoich * ph.charge(k);
                break;
            }
        }
    }

    // If the electrons change phases then the reaction is electrochemical
    bool echemical = false;
    for(size_t m = 0; m < phase_ids.size(); m++) {
        if (fabs(e_counter[m]) > 1e-4) {
            echemical = true;
            break;
        }
    }

    // If the reaction is electrochemical, ensure the reaction is identified as
    // electrochemical. If not already specified beta is assumed to be 0.5
    std::string type = ba::to_lower_copy(r["type"]);
    if (!r.child("rateCoeff").hasChild("electrochem")) {
        if ((type != "butlervolmer_noactivitycoeffs" &&
             type != "butlervolmer" &&
             type != "surfaceaffinity") &&
             echemical) {
            XML_Node& f = r.child("rateCoeff").addChild("electrochem","");
            f.addAttribute("beta",0.5);
        }
    }
    return true;
}
コード例 #17
0
ファイル: ctml.cpp プロジェクト: iokto/cantera
void getMatrixValues(const XML_Node& node,
                     const std::vector<std::string>& keyStringRow,
                     const std::vector<std::string>& keyStringCol,
                     Array2D& retnValues, const bool convert,
                     const bool matrixSymmetric)
{
    if (keyStringRow.size() > retnValues.nRows()) {
        throw CanteraError("getMatrixValues",
                           "size of key1 greater than numrows");
    } else if (keyStringCol.size() > retnValues.nColumns()) {
        throw CanteraError("getMatrixValues",
                           "size of key2 greater than num cols");
    } else if (matrixSymmetric && retnValues.nRows() != retnValues.nColumns()) {
        throw CanteraError("getMatrixValues",
                           "nrow != ncol for a symmetric matrix");
    }

    /*
     * Get the attributes field, units, from the XML node
     * and determine the conversion factor, funit.
     */
    doublereal funit = 1.0;
    if (convert && node["units"] != "") {
        funit = toSI(node["units"]);
    }

    vector<string> v;
    getStringArray(node, v);
    for (size_t i = 0; i < v.size(); i++) {
        size_t icolon = v[i].find(":");
        if (icolon == string::npos) {
            throw CanteraError("getMatrixValues","Missing two colons ("
                               +v[i]+")");
        }
        string key1 = v[i].substr(0,icolon);
        string rmm = v[i].substr(icolon+1, v[i].size());

        icolon = rmm.find(":");
        if (icolon == string::npos) {
            throw CanteraError("getMatrixValues","Missing one colon ("
                               +v[i]+")");
        }

        size_t irow = find(keyStringRow.begin(), keyStringRow.end(), key1)
                      - keyStringRow.begin();
        if (irow == keyStringRow.size()) {
            throw CanteraError("getMatrixValues","Row not matched by string: "
                               + key1);
        }

        string key2 = rmm.substr(0,icolon);
        size_t icol = find(keyStringCol.begin(), keyStringCol.end(), key2)
                      - keyStringCol.begin();
        if (icol == keyStringCol.size()) {
            throw CanteraError("getMatrixValues","Col not matched by string: "
                               + key2);
        }
        double dval = fpValueCheck(rmm.substr(icolon+1, rmm.size())) * funit;
        /*
         * Finally, insert the value;
         */
        retnValues(irow, icol) = dval;
        if (matrixSymmetric) {
            retnValues(icol, irow) = dval;
        }
    }
}
コード例 #18
0
ファイル: ThermoFactory.cpp プロジェクト: hkmoffat/cantera
  static void formSpeciesXMLNodeList(std::vector<XML_Node *> &spDataNodeList,
				     std::vector<std::string> &spNamesList,
				     std::vector<int> &spRuleList,
				     const std::vector<XML_Node *> spArray_names,
				     const std::vector<XML_Node *> spArray_dbases,
				     const vector_int sprule) {
    
    // used to check that each species is declared only once
    std::map<std::string, bool> declared;
    
    int nspa = spArray_dbases.size();
    int nSpecies = 0;
    bool skip;

    for (int jsp = 0; jsp < nspa; jsp++) {
      const XML_Node& speciesArray = *spArray_names[jsp]; 
      
      // Get the top XML for the database
      const XML_Node *db = spArray_dbases[jsp];

      // Get the array of species name strings and the count them
      std::vector<std::string> spnames;
      getStringArray(speciesArray, spnames);
      int nsp = static_cast<int>(spnames.size());

      // if 'all' is specified as the one and only species in the
      // spArray_names field, then add all species 
      // defined in the corresponding database to the phase
      if (nsp == 1 && spnames[0] == "all") {
	std::vector<XML_Node *> allsp;
	db->getChildren("species", allsp);
	nsp = static_cast<int>(allsp.size());
	spnames.resize(nsp);
	for (int nn = 0; nn < nsp; nn++) {
	  string stemp = (*allsp[nn])["name"];
	  bool skip = false;
	  if (declared[stemp]) {
	    if (sprule[jsp] >= 10) {
	      skip = true;
	    } else {
	      throw CanteraError("ThermoFactory::formSpeciesXMLNodeList()",
				 "duplicate species: \"" + stemp + "\"");
	    }
	  }
	  if (!skip) {
	    declared[stemp] = true;
	    nSpecies++;
	    spNamesList.resize(nSpecies);
	    spDataNodeList.resize(nSpecies, 0);
	    spRuleList.resize(nSpecies, 0);
	    spNamesList[nSpecies-1] = stemp;
	    spDataNodeList[nSpecies-1] = allsp[nn];
	    spRuleList[nSpecies-1] = sprule[jsp];
	  }
	}
      }
      else if (nsp == 1 && spnames[0] == "unique") {
	std::vector<XML_Node *> allsp;
	db->getChildren("species", allsp);
	nsp = static_cast<int>(allsp.size());
	spnames.resize(nsp);
	for (int nn = 0; nn < nsp; nn++) {
	  string stemp = (*allsp[nn])["name"];
	  bool skip = false;
	  if (declared[stemp]) {
	      skip = true;
	  }
	  if (!skip) {
	    declared[stemp] = true;
	    nSpecies++;
	    spNamesList.resize(nSpecies);
	    spDataNodeList.resize(nSpecies, 0);
	    spRuleList.resize(nSpecies, 0);
	    spNamesList[nSpecies-1] = stemp;
	    spDataNodeList[nSpecies-1] = allsp[nn];
	    spRuleList[nSpecies-1] = sprule[jsp];
	  }
	}
      } else {
	for (int k = 0; k < nsp; k++) {
	  string stemp = spnames[k];
	  skip = false;
	  if (declared[stemp]) {
	    if (sprule[jsp] >= 10) {
	      skip = true;
	    } else {
	      throw CanteraError("ThermoFactory::formSpeciesXMLNodeList()",
				 "duplicate species: \"" + stemp + "\"");
	    }
	  }
	  if (!skip) {
	    declared[stemp] = true;
	    // Find the species in the database by name.
	    XML_Node* s = db->findByAttr("name", stemp); 
	    if (!s) {
	      throw CanteraError("importPhase","no data for species, \""
				 + stemp + "\"");
	    }
	    nSpecies++;
	    spNamesList.resize(nSpecies);
	    spDataNodeList.resize(nSpecies, 0);
	    spRuleList.resize(nSpecies, 0);
	    spNamesList[nSpecies-1] = stemp;
	    spDataNodeList[nSpecies-1] = s;
	    spRuleList[nSpecies-1] = sprule[jsp];
	  }
	}
      }
    }
  }