int main(int argc, char **argv)
{
  // this open and parse the XML file:  
  XMLNode xMainNode=XMLNode::openFileHelper("PMMLModelUnicode.xml",_T("PMML"));

  // this prints "RANK For <you>":
  XMLNode xNode=xMainNode.getChildNode(_T("Header"));  
  printf("Application Name is: '%S'\n", xNode.getChildNode(_T("Application")).getAttribute(_T("name")));

  // this prints "Hello World!"
  printf("Text inside Header tag is :'%S'\n", xNode.getText());
  
  // this gets the number of "NumericPredictor" tags:  
  xNode=xMainNode.getChildNode(_T("RegressionModel")).getChildNode(_T("RegressionTable")); 
  int n=xNode.nChildNode(_T("NumericPredictor"));

  // this prints the "coefficient" value for all the "NumericPredictor" tags:
  int iterator=0;
  for (int i=0; i<n; i++)
    printf("coeff %i=%S\n",i+1,xNode.getChildNode(_T("NumericPredictor"),&iterator).getAttribute(_T("coefficient")));

  // this create a file named "testUnicode.xml" based on the content of the first "Extension" tag of the XML file:  
  TCHAR *t=xMainNode.getChildNode(_T("Extension")).createXMLString(true,&i); 
  FILE *f=fopen("testUnicode.xml","wb");
  _fputts(_T("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"),f);
  fwrite(t,sizeof(TCHAR),i,f);
  printf("%S",t);
  fclose(f);
  free(t);

  // compare these 4 lines ...
  t=stringDup(xMainNode.getAttribute(_T("version")));       // get version number
  xMainNode=XMLNode::emptyXMLNode;                          // free from memory the top of the xml Tree
  printf("PMML Version :%S\n",t);                           // print version number
  free(t);                                                  // free version number

  // ... with the following 3 lines (currently commented, because of error):
  //  t=xMainNode.getAttribute(_T("version"));      // get version number (note that there is no 'stringDup')
  //  xMainNode=XMLNode::emptyXMLNode;              // free from memory the top of the xml Tree AND the version number inside 't' var
  //  printf("PMML Version :%S\n",t);               // since the version number in 't' has been free'd this will not work

  // We create in memory from scratch the following XML structure:
  //  <?xml version="1.0"?>
  //      <body> Hello "universe". </body>
  // ... and we transform it into a standard C string that is printed on screen.
  xNode=XMLNode::createXMLTopNode();
  XMLNode xn=xNode.addChild(stringDup(_T("xml")),TRUE); xn.addAttribute(stringDup(_T("version")),stringDup(_T("1.0")));
  xn=xn.addChild(stringDup(_T("body")));  xn.addText(stringDup(_T("Hello \"universe\"!")));
  t=xNode.createXMLString(true);
  printf("XMLString created from scratch:\n%S",t);
  free(t);

  return 0;
}
static void buildTree(SampleNode *pRoot)
{
   SampleNode *pVisualRoot, *pFood, *pNonFood, *pStreams, *pAudio;

   pVisualRoot = createNode(pRoot, "root", "root");

   pFood = createNode(pVisualRoot, "food", "Some food");
   createNode(pFood, "parsley", "tasty herb");
   createNode(pFood, "salad", "eat a lot of it!");

   pNonFood = createNode(pVisualRoot, "non-food", "tech stuff");

   pAudio = createNode(pNonFood, "audio", "ask Lawo");
   createGain(pAudio);
   createVolume(pAudio);
   createFormat(pAudio);
   createNode(pAudio, "dangling", NULL);

   pStreams = createNode(pNonFood, "streams", "see 'em move");
   pStreams->node.pSchemaIdentifiers = stringDup("de.l-s-b.emberplus.samples.streams");
   pStreams->fields |= GlowFieldFlag_SchemaIdentifier;
   createStream1(pStreams);
   createStream2(pStreams);
   createStream3(pStreams);
   createStream4(pStreams);
}
static void createGain(SampleNode *pParent)
{
   SampleNode *pParam = createParameter(pParent, "gain", "power in db");
   dword fields = pParam->fields;

   pParam->param.access = GlowAccess_ReadWrite;
   fields |= GlowFieldFlag_Access;

   pParam->param.value.choice.integer = 0;
   pParam->param.value.flag = GlowParameterType_Integer;
   fields |= GlowFieldFlag_Value;

   pParam->param.minimum.choice.integer = 0;
   pParam->param.minimum.flag = GlowParameterType_Integer;
   fields |= GlowFieldFlag_Minimum;

   pParam->param.maximum.choice.integer = 65535;
   pParam->param.maximum.flag = GlowParameterType_Integer;
   fields |= GlowFieldFlag_Maximum;

   pParam->param.factor = 64;
   fields |= GlowFieldFlag_Factor;

   pParam->param.pFormat = "%Lf db";
   fields |= GlowFieldFlag_Format;

   pParam->param.pSchemaIdentifiers = stringDup("de.l-s-b.emberplus.samples.gain");
   fields |= GlowFieldFlag_SchemaIdentifier;

   pParam->fields = (GlowFieldFlags)fields;
}
static SampleNode *createNode(SampleNode *pParent, pcstr pIdentifier, pcstr pDescription)
{
   SampleNode *pNode = newobj(SampleNode);
   dword fields = GlowFieldFlag_Identifier;
   sampleNode_init(pNode, pParent);
   pNode->node.pIdentifier = stringDup(pIdentifier);

   if(pDescription != NULL)
   {
      pNode->node.pDescription = stringDup(pDescription);
      fields |= GlowFieldFlag_Description;
   }

   pNode->fields = (GlowFieldFlags)fields;
   return pNode;
}
Exemple #5
0
static void _fileCreateDirectory(const char *fileName, unsigned short volRefNum)
{
#ifndef USE_FILE_API
    int i = 0;
    
    for (i = 0; i < stringLen(fileName); i++) {
        if (fileName[i] == '/') {
            char *tempPath = stringDup(fileName);

            if (tempPath) {
                FileRef fileRef;
                
                tempPath[i + 1] = 0;
                
                // Try to open the path, if that fails we need to create it
                if (!VFSFileOpen(volRefNum, tempPath, vfsModeRead, &fileRef)) {
                    VFSFileClose(fileRef);
                } else {
                    VFSDirCreate(volRefNum, tempPath);
                }

                memMgrChunkFree(tempPath);
            } else { // To bad, we'll just fail for now
                break;
            }
        }
    }
#endif
}
Exemple #6
0
void webDataSetContentType(char *mime, WebDataPtr webData)
{
    if (!webData)
        return;
    
    webData->contentType = stringDup(mime);
}
Exemple #7
0
void object_t::add(const char *const keyStr, std::unique_ptr<JSONAtom> &&value)
{
	if (children.find(keyStr) != children.end())
		return;
	string_t key = stringDup(keyStr);
	mapKeys.push_back(key.get());
	children[std::move(key)] = std::move(value);
}
Exemple #8
0
static inline void modify_request(clientHttpRequest * http)
{
	debug(97, 3)("modify_request: start, uri=[%s]\n", http->uri);
	request_t* old_request = http->request;
	request_t* new_request = urlParse(old_request->method, http->uri);
	safe_free(http->uri);

	if (new_request)
	{
		safe_free(http->uri);
		http->uri = xstrdup(urlCanonical(new_request));
		if(!http->log_uri)
			http->log_uri = xstrdup(urlCanonicalClean(old_request));
		new_request->http_ver = old_request->http_ver;
		httpHeaderAppend(&new_request->header, &old_request->header);
		new_request->client_addr = old_request->client_addr;
		new_request->client_port = old_request->client_port;
#if FOLLOW_X_FORWARDED_FOR
		new_request->indirect_client_addr = old_request->indirect_client_addr;
#endif /* FOLLOW_X_FORWARDED_FOR */
		new_request->my_addr = old_request->my_addr;
		new_request->my_port = old_request->my_port;
		new_request->flags = old_request->flags;
		new_request->flags.redirected = 1;
		if (old_request->auth_user_request)
		{
			new_request->auth_user_request = old_request->auth_user_request;
			authenticateAuthUserRequestLock(new_request->auth_user_request);
		}
		if (old_request->body_reader)
		{
			new_request->body_reader = old_request->body_reader;
			new_request->body_reader_data = old_request->body_reader_data;
			old_request->body_reader = NULL;
			old_request->body_reader_data = NULL;
		}
		new_request->content_length = old_request->content_length;
		if (strBuf(old_request->extacl_log))
			new_request->extacl_log = stringDup(&old_request->extacl_log);
		if (old_request->extacl_user)
			new_request->extacl_user = xstrdup(old_request->extacl_user);
		if (old_request->extacl_passwd)
			new_request->extacl_passwd = xstrdup(old_request->extacl_passwd);
		if(old_request->cc_request_private_data)
		{
			new_request->cc_request_private_data = old_request->cc_request_private_data;
			old_request->cc_request_private_data = NULL;
		}
		requestUnlink(old_request);
		http->request = requestLink(new_request);
	}
}
Exemple #9
0
LPVOID	TVTCreateXMLPacket4FinalizeSession(
	TCHAR*	sessionName,
		int	failureCount,
		int	summaryCount,
		int	numberOfTests,
		int	numberOfSuccessfulTests,
		int	numberOfUnsuccessfulTests)
{
	TCHAR*	result	= null,
		templatePath[MAX_PATH],
			tempText[MAX_PATH]	
	;
	if (!GetTemplateActionPath(templatePath)
	)	return	result
	;
//	This open and parse the XML file:  
	XMLNode	xRootNode	= XMLNode::openFileHelper(templatePath,"easyTest");
	XMLNode	xAction		= xRootNode.getChildNode("Action");
	XMLAttribute*	xAttribute	= xAction.AddAttribute(stringDup("command",0),stringDup("updateObject",	0));
	XMLNode	xAttributes	= xAction.getChildNode("Attributes");
	xAttribute	= xAttributes.AddAttribute(stringDup("object",	0),stringDup("session",		0));
	xAttribute	= xAttributes.AddAttribute(stringDup("session",	0),stringDup(sessionName,	0));
	
	XMLNode	xEntity	= xAction.AddChild(stringDup("Entity"),0);

//	Line 'Conclusion'
	XMLNode	xLine	= TVTAddXMLLine(xEntity);
	TVTAddXMLToken(xLine,"Conclusion: ");
	TVTAddXMLToken(xLine,itoa(summaryCount,tempText,10));
	TVTAddXMLToken(xLine," checks were made. There were ");
	TVTAddXMLToken(xLine,itoa(failureCount,tempText,10));
	TVTAddXMLToken(xLine," failures.");
	
//	Line 'Statistics'
	xLine	= TVTAddXMLLine(xEntity);
	TVTAddXMLToken(xLine,"Statistics:");
//	Line # tests are executes.
	xLine	= TVTAddXMLLine(xEntity);
	TVTAddXMLToken(xLine,itoa(numberOfTests,tempText,10));
	if (numberOfTests == 1)
		TVTAddXMLToken(xLine," test is executed.");
	else
		TVTAddXMLToken(xLine," tests are executed.")
	;
	xLine	= TVTAddXMLLine(xEntity);
	if (!numberOfUnsuccessfulTests)
	{
			TVTAddXMLToken(xLine,"No errors detected.");
	}
	else
	{
			TVTAddXMLToken(xLine,itoa(numberOfSuccessfulTests,tempText,10));
			if (numberOfSuccessfulTests == 1)
				TVTAddXMLToken(xLine," test is completed successfully. ");
			else
				TVTAddXMLToken(xLine," tests are completed successfully. ")
			;
		xLine	= TVTAddXMLLine(xEntity);
			TVTAddXMLToken(xLine,itoa(numberOfUnsuccessfulTests,tempText,10));
			if (numberOfUnsuccessfulTests == 1)
				TVTAddXMLToken(xLine," test failed.");
			else
				TVTAddXMLToken(xLine," tests failed.")
			;
	}

//	Line
	int		size;
	LPTSTR	pText	= xRootNode.createXMLString(1,&size);
	result	= new TCHAR [size+1];
	if (result)
	{
		_tcscpy(result,pText);
	}
	free(pText);
	return	result;
}
Exemple #10
0
/**
 * Recursively parse an XML element.
 */
bool
XMLNode::ParseXMLElement(XML *pXML)
{
  const TCHAR *lpszTemp = NULL;
  size_t cbTemp;
  unsigned nDeclaration;
  const TCHAR *lpszText = NULL;
  XMLNode pNew;
  enum Status status; // inside or outside a tag
  enum Attrib attrib = eAttribName;

  assert(pXML);

  // If this is the first call to the function
  if (pXML->nFirst) {
    // Assume we are outside of a tag definition
    pXML->nFirst = false;
    status = eOutsideTag;
  } else {
    // If this is not the first call then we should only be called when inside a tag.
    status = eInsideTag;
  }

  // Iterate through the tokens in the document
  while (true) {
    // Obtain the next token
    size_t cbToken;
    enum TokenTypeTag type;
    NextToken token = GetNextToken(pXML, &cbToken, &type);
    if (gcc_unlikely(type == eTokenError))
      return false;

    // Check the current status
    switch (status) {
      // If we are outside of a tag definition
    case eOutsideTag:

      // Check what type of token we obtained
      switch (type) {
        // If we have found text or quoted text
      case eTokenText:
      case eTokenQuotedText:
      case eTokenEquals:
        if (!lpszText)
          lpszText = token.pStr;

        break;

        // If we found a start tag '<' and declarations '<?'
      case eTokenTagStart:
      case eTokenDeclaration:
        // Cache whether this new element is a declaration or not
        nDeclaration = type == eTokenDeclaration;

        // If we have node text then add this to the element
        if (lpszText) {
          cbTemp = token.pStr - lpszText;
          FindEndOfText(lpszText, &cbTemp);
          AddText(lpszText, cbTemp);
          lpszText = NULL;
        }

        // Find the name of the tag
        token = GetNextToken(pXML, &cbToken, &type);

        // Return an error if we couldn't obtain the next token or
        // it wasnt text
        if (type != eTokenText) {
          pXML->error = eXMLErrorMissingTagName;
          return false;
        }

        // If we found a new element which is the same as this
        // element then we need to pass this back to the caller..

#ifdef APPROXIMATE_PARSING
        if (d->lpszName && myTagCompare(d->lpszName, token.pStr)) {
          // Indicate to the caller that it needs to create a
          // new element.
          pXML->lpNewElement = token.pStr;
          pXML->cbNewElement = cbToken;
          return true;
        }
#endif

        // If the name of the new element differs from the name of
        // the current element we need to add the new element to
        // the current one and recurse
        pNew = AddChild(stringDup(token.pStr, cbToken), nDeclaration);

        while (true) {
          // Callself to process the new node.  If we return
          // FALSE this means we dont have any more
          // processing to do...

          if (!pNew.ParseXMLElement(pXML)) {
            return false;
          } else {
            // If the call to recurse this function
            // evented in a end tag specified in XML then
            // we need to unwind the calls to this
            // function until we find the appropriate node
            // (the element name and end tag name must
            // match)
            if (pXML->cbEndTag) {
              // If we are back at the root node then we
              // have an unmatched end tag
              if (!d->lpszName) {
                pXML->error = eXMLErrorUnmatchedEndTag;
                return false;
              }

              // If the end tag matches the name of this
              // element then we only need to unwind
              // once more...

              if (myTagCompare(d->lpszName, pXML->lpEndTag)) {
                pXML->cbEndTag = 0;
              }

              return true;
            } else if (pXML->cbNewElement) {
              // If the call indicated a new element is to
              // be created on THIS element.

              // If the name of this element matches the
              // name of the element we need to create
              // then we need to return to the caller
              // and let it process the element.

              if (myTagCompare(d->lpszName, pXML->lpNewElement))
                return true;

              // Add the new element and recurse
              pNew = AddChild(stringDup(pXML->lpNewElement,
                                        pXML->cbNewElement), false);
              pXML->cbNewElement = 0;
            } else {
              // If we didn't have a new element to create
              break;
            }
          }
        }
        break;

        // If we found an end tag
      case eTokenTagEnd:

        // If we have node text then add this to the element
        if (lpszText) {
          cbTemp = token.pStr - lpszText;
          FindEndOfText(lpszText, &cbTemp);
          TCHAR *text = fromXMLString(lpszText, cbTemp);
          if (text == NULL) {
            pXML->error = eXMLErrorUnexpectedToken;
            return false;
          }

          AddText(text);
          free(text);
          lpszText = NULL;
        }

        // Find the name of the end tag
        token = GetNextToken(pXML, &cbTemp, &type);

        // The end tag should be text
        if (type != eTokenText) {
          pXML->error = eXMLErrorMissingEndTagName;
          return false;
        }
        lpszTemp = token.pStr;

        // After the end tag we should find a closing tag
        token = GetNextToken(pXML, &cbToken, &type);
        if (type != eTokenCloseTag) {
          pXML->error = eXMLErrorMissingEndTagName;
          return false;
        }

        // We need to return to the previous caller.  If the name
        // of the tag cannot be found we need to keep returning to
        // caller until we find a match
        if (!myTagCompare(d->lpszName, lpszTemp)) {
          pXML->lpEndTag = lpszTemp;
          pXML->cbEndTag = cbTemp;
        }

        // Return to the caller
        return true;

        // Errors...
      case eTokenCloseTag: /* '>'         */
      case eTokenShortHandClose: /* '/>'        */
        pXML->error = eXMLErrorUnexpectedToken;
        return false;
      default:
        break;
      }
      break;

      // If we are inside a tag definition we need to search for attributes
    case eInsideTag:
      // Check what part of the attribute (name, equals, value) we
      // are looking for.
      switch (attrib) {
        // If we are looking for a new attribute
      case eAttribName:
        // Check what the current token type is
        switch (type) {
          // If the current type is text...
          // Eg.  'attribute'
        case eTokenText:
          // Cache the token then indicate that we are next to
          // look for the equals
          lpszTemp = token.pStr;
          cbTemp = cbToken;
          attrib = eAttribEquals;
          break;

          // If we found a closing tag...
          // Eg.  '>'
        case eTokenCloseTag:
          // We are now outside the tag
          status = eOutsideTag;
          break;

          // If we found a short hand '/>' closing tag then we can
          // return to the caller
        case eTokenShortHandClose:
          return true;

          // Errors...
        case eTokenQuotedText: /* '"SomeText"'   */
        case eTokenTagStart: /* '<'            */
        case eTokenTagEnd: /* '</'           */
        case eTokenEquals: /* '='            */
        case eTokenDeclaration: /* '<?'           */
          pXML->error = eXMLErrorUnexpectedToken;
          return false;
        default:
          break;
        }
        break;

        // If we are looking for an equals
      case eAttribEquals:
        // Check what the current token type is
        switch (type) {
          // If the current type is text...
          // Eg.  'Attribute AnotherAttribute'
        case eTokenText:
          // Add the unvalued attribute to the list
          AddAttribute(stringDup(lpszTemp, cbTemp), NULL);
          // Cache the token then indicate.  We are next to
          // look for the equals attribute
          lpszTemp = token.pStr;
          cbTemp = cbToken;
          break;

          // If we found a closing tag 'Attribute >' or a short hand
          // closing tag 'Attribute />'
        case eTokenShortHandClose:
        case eTokenCloseTag:
          // If we are a declaration element '<?' then we need
          // to remove extra closing '?' if it exists
          if (d->isDeclaration && (lpszTemp[cbTemp - 1]) == _T('?'))
            cbTemp--;

          if (cbTemp)
            // Add the unvalued attribute to the list
            AddAttribute(stringDup(lpszTemp, cbTemp), NULL);

          // If this is the end of the tag then return to the caller
          if (type == eTokenShortHandClose)
            return true;

          // We are now outside the tag
          status = eOutsideTag;
          break;

          // If we found the equals token...
          // Eg.  'Attribute ='
        case eTokenEquals:
          // Indicate that we next need to search for the value
          // for the attribute
          attrib = eAttribValue;
          break;

          // Errors...
        case eTokenQuotedText: /* 'Attribute "InvalidAttr"'*/
        case eTokenTagStart: /* 'Attribute <'            */
        case eTokenTagEnd: /* 'Attribute </'           */
        case eTokenDeclaration: /* 'Attribute <?'           */
          pXML->error = eXMLErrorUnexpectedToken;
          return false;
        default:
          break;
        }
        break;

        // If we are looking for an attribute value
      case eAttribValue:
        // Check what the current token type is
        switch (type) {
          // If the current type is text or quoted text...
          // Eg.  'Attribute = "Value"' or 'Attribute = Value' or
          // 'Attribute = 'Value''.
        case eTokenText:
        case eTokenQuotedText:
          // If we are a declaration element '<?' then we need
          // to remove extra closing '?' if it exists
          if (d->isDeclaration && (token.pStr[cbToken - 1]) == _T('?')) {
            cbToken--;
          }

          if (cbTemp) {
            // Add the valued attribute to the list
            if (type == eTokenQuotedText) {
              token.pStr++;
              cbToken -= 2;
            }
            AddAttribute(stringDup(lpszTemp, cbTemp), fromXMLString(
                                                                    token.pStr, cbToken));
          }

          // Indicate we are searching for a new attribute
          attrib = eAttribName;
          break;

          // Errors...
        case eTokenTagStart: /* 'Attr = <'          */
        case eTokenTagEnd: /* 'Attr = </'         */
        case eTokenCloseTag: /* 'Attr = >'          */
        case eTokenShortHandClose: /* "Attr = />"         */
        case eTokenEquals: /* 'Attr = ='          */
        case eTokenDeclaration: /* 'Attr = <?'         */
          pXML->error = eXMLErrorUnexpectedToken;
          return false;
        default:
          break;
        }
      }
    }
  }
}
Exemple #11
0
void ScanParseSkel::setReferenceHeader(const Char8 *szReferenceHeader)
{
    stringDup(szReferenceHeader, _szReferenceHeader);
}
Exemple #12
0
void AceptarDireccionDialogo(GtkWidget *widget, gpointer data)
{
    DatosDir *conector;
    gchar *nombre, *direccion, *telefono;
    char *datos[3];
    int aux,pos,error;
  
    conector=(DatosDir*)data;
    switch (conector->operacion) {

    case INSERTAR:  
        nombre=gtk_entry_get_text(GTK_ENTRY(conector->nombre));
        direccion=gtk_entry_get_text(GTK_ENTRY(conector->direccion));
        telefono=gtk_entry_get_text(GTK_ENTRY(conector->telefono));
        if (0 != strcmp(nombre,"")) {
            error=insertarDir((&datosAgenda.direcciones),nombre,
                               direccion,telefono);
            if (0 == error) {
                dialogoAviso("Direccion insertada");
            } else {
                dialogoAviso("No se pudo insertar la direccion");
            }
            gtk_grab_remove(conector->window);
            gtk_widget_destroy (conector->window); 
        } else {
            dialogoAviso("El campo nombre no debe tener valor nulo");
        }
        break;
        
    case BORRAR:    
        nombre=gtk_entry_get_text(GTK_ENTRY(conector->nombre));
        if (0 != strcmp(nombre,"")) {
            error=borrarDir((&datosAgenda.direcciones),nombre);      
            gtk_grab_remove(conector->window);
            gtk_widget_destroy (conector->window); 
            if (0 == error) {
                dialogoAviso("Direccion eliminada");
            } else {
                dialogoAviso("El nombre introducido no estaba en el libro de direcciones");
            }
        } else {
            dialogoAviso("Debe introducir un nombre");
        }
        break;

    case CONSULTAR:
        nombre=gtk_entry_get_text(GTK_ENTRY(conector->nombre));
        if (0 != strcmp(nombre,"")) {
            direccion=(char *)malloc(256);
            telefono=(char *)malloc(256);
            aux = consultarDirPorNombre((&datosAgenda.direcciones),nombre,
                                        &pos,&direccion,&telefono);
            datos[0]=stringDup(nombre);
            datos[1]=stringDup(direccion);
            datos[2]=stringDup(telefono);
            gtk_grab_remove(conector->window);
            gtk_widget_destroy (conector->window); 
            if (0 == aux) {
                /* Mostrar datos*/
                mostrarConsultaWindow(datos);
            } else {
                dialogoAviso("El nombre buscado no esta en el libro de direcciones");
            }        
        } else {
            dialogoAviso("Debe introducir un nombre");
        }
        break;
    }
}
Exemple #13
0
/*
 * Función listarDireccionWindow()
 */
void listarDireccionWindow (void)
{
    int i, num, ret, indice;
    char *nombre, *direccion, *telefono;
    GtkWidget *datos[NUM_LETRAS];
    GtkWidget *window;
    GtkWidget *libro;
    GtkWidget *label;
    GtkWidget *scroll;
    char* dir[3];
    char letras[NUM_LETRAS][2]={"#","A","B","C","D","E","F","G","H","I","J","K","L","M","N","Ñ","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
    char inicial;

    /* 
     * Dialog
     */  
    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_widget_set_usize (GTK_WIDGET (window), 585, 300);
    gtk_window_set_policy(GTK_WINDOW (window), TRUE, TRUE, FALSE);      
    gtk_window_set_title (GTK_WINDOW (window), "Libro de direcciones");
    gtk_container_border_width (GTK_CONTAINER (window), 10);    
    gtk_widget_set_uposition( window, 300, 300 );   
  
    libro=gtk_notebook_new(); 
    gtk_notebook_set_tab_pos(GTK_NOTEBOOK(libro),GTK_POS_TOP);      
    for (indice=0;indice<NUM_LETRAS;indice++) {    
        scroll = gtk_scrolled_window_new (NULL, NULL);
        gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scroll),
                                        GTK_POLICY_AUTOMATIC,GTK_POLICY_ALWAYS);
        datos[indice]=gtk_clist_new(3);
        gtk_container_add(GTK_CONTAINER(scroll), datos[indice]);
        gtk_clist_set_column_title(GTK_CLIST(datos[indice]),0,"Nombre");    
        gtk_clist_set_column_title(GTK_CLIST(datos[indice]),1,"Direccion");
        gtk_clist_set_column_title(GTK_CLIST(datos[indice]),2,"Telefono");
        gtk_clist_column_titles_show(GTK_CLIST(datos[indice]));
        gtk_clist_set_column_width(GTK_CLIST(datos[indice]),0,175);
        gtk_clist_set_column_width(GTK_CLIST(datos[indice]),1,250);
        gtk_clist_set_column_width(GTK_CLIST(datos[indice]),2,75);          
        label=gtk_label_new(letras[indice]); 
        gtk_widget_set_usize(label,10,10);
        gtk_notebook_append_page((GtkNotebook*)libro,scroll,label);     
    }  
    num=numeroDir((&datosAgenda.direcciones));    
    gtk_container_add (GTK_CONTAINER (window),libro);
    for (i=0; i<num; i++) {
        ret = consultarDir((&datosAgenda.direcciones),i,&nombre, 
                           &direccion, &telefono);        
        if (0 == ret) { 
            dir[0]=stringDup(nombre);
            dir[1]=stringDup(direccion);
            dir[2]=stringDup(telefono);

            /*
             * Buscamos en el array de letras, la inicial del nombre. 
             * Insertaremos sus datos en la lista correspondiente.
             */    
            inicial=toupper(nombre[0]);
            indice=NUM_LETRAS-1;
            while ( (letras[indice][0]!=inicial) && (0 < indice) ) {    
                indice--;
            }
            gtk_clist_append(GTK_CLIST(datos[indice]),dir);
        }
    }
    gtk_grab_add(window);
    gtk_widget_show_all(window);
}
Exemple #14
0
void webDataSetCharSet(char *charSet, WebDataPtr webData)
{
    webData->charSet = stringDup(charSet);
}
Exemple #15
0
/*
 *?????Ǵ????޸ġ?????һ??header?Ĵ??�??
 */
static int modifyHeader3(struct action_part* acp, HttpReply* reply)
{
	assert(acp);
	assert(reply);

	int flag = 0;
	int act = acp->action;
	struct header_info* hdr = acp->hdr;
	HttpHeaderEntry e;
	//HttpHeaderEntry *mye;
	int i;
	HttpHeaderEntry *myheader;
	HttpHeaderPos pos = HttpHeaderInitPos + HDR_ENUM_END;
	e.name = stringDup(&hdr->header);
	e.value = stringDup(&hdr->value);
	i = httpHeaderIdByNameDef(strBuf(hdr->header), strLen(hdr->header));
	e.id = i;
	if(i == -1)
	{
		e.id = HDR_OTHER;
		if(0 == act)
		{
			httpHeaderAddEntry(&reply->header, httpHeaderEntryClone(&e));
		}
		else if(2 == act)
		{
			while ((myheader = httpHeaderGetEntryPlus(&reply->header, &pos))) 
			{
				if (myheader->id == HDR_OTHER && strCaseCmp(myheader->name, strBuf(hdr->header)) == 0)
				{
					debug(98, 3)("%s is myheader->value,%s is hdr->value\n",strBuf(myheader->value), strBuf(hdr->value));
					stringReset(&myheader->value, strBuf(hdr->value));

				}
			}
		}
		else if(1 == act)
		{
			httpHeaderDelByName(&reply->header,strBuf(hdr->header));
		}
		else if(3 == act)
		{
			while ((myheader = httpHeaderGetEntryPlus(&reply->header, &pos))) 
			{
				if (myheader->id == HDR_OTHER && strCaseCmp(myheader->name, strBuf(hdr->header)) == 0)
				{
					debug(98, 3)("%s is myheader->value,%s is hdr->value\n",strBuf(myheader->value), strBuf(hdr->value));
					flag = 1;
					stringReset(&myheader->value, strBuf(hdr->value));

				}
			}
			
			if(!flag)
				httpHeaderAddEntry(&reply->header, httpHeaderEntryClone(&e));
		}
	}
	else
	{
		//mye = httpHeaderFindEntry2(&reply->header, i);
		//debug(98, 3) ("%d is i\n", i);

		if(0 == act)
		{
			httpHeaderAddEntry(&reply->header, httpHeaderEntryClone(&e));
		}
		else if(2 == act)
		{
			if(httpHeaderDelByName(&reply->header,strBuf(hdr->header)))
			{
				httpHeaderAddEntry(&reply->header, httpHeaderEntryClone(&e));
			}
			//mye = httpHeaderFindEntry2(&reply->header, i);
			//debug(98, 3)("%s is newvalue\n",strBuf(mye->value));
		}
		else if(1 == act)
		{
			httpHeaderDelByName(&reply->header,strBuf(hdr->header));
		}
		else if(3 == act)
		{
			httpHeaderDelByName(&reply->header,strBuf(hdr->header));
			httpHeaderAddEntry(&reply->header, httpHeaderEntryClone(&e));
		}
	}
	stringClean(&e.name);
	stringClean(&e.value);

	return 0;
}
Exemple #16
0
int main(int argc, char **argv)
{
    ///////////////////////////////////////////////////////////////////////////////////
    //                                                                               //
    //    Example 1: Basic operations to parse and collect data from a XML file      //
    //                                                                               //
    ///////////////////////////////////////////////////////////////////////////////////

    printf("EXAMPLE 1\n");

    // this open and parse the XML file:
    XMLNode xMainNode=XMLNode::openFileHelper("PMMLModel.xml","PMML");

    // this prints "RANK For <you>":
    XMLNode xNode=xMainNode.getChildNode("Header");
    printf("  Application Name is: '%s' (note that &lt; has been replaced by '<')\n", xNode.getChildNode("Application").getAttribute("name"));

    // this prints "Hello World!"
    printf("  Text inside Header tag is :'%s'\n", xNode.getText());

    // this gets the number of "NumericPredictor" tags:
    xNode=xMainNode.getChildNode("RegressionModel").getChildNode("RegressionTable");
    int n=xNode.nChildNode("NumericPredictor");

    // this prints the "coefficient" value for all the "NumericPredictor" tags:
    int i,myIterator=0;
    for (i=0; i<n; i++)
        printf("    coeff %i=%s\n",i+1,xNode.getChildNode("NumericPredictor",&myIterator).getAttribute("coefficient"));

    // this create a file named "test.xml" based on the content of the first "Extension" tag of the XML file:
    xMainNode.getChildNode("Extension").writeToFile("test.xml","ISO-8859-1");

    printf("  The content of the clear tag is:%s\n",xMainNode.getChildNode("html_page").getClear().lpszValue);

    ///////////////////////////////////////////////////////////////////////////////////////////////
    //                                                                                           //
    //    Example 2: memory management: when to use the 'stringDup' and the 'free' functions     //
    //                                                                                           //
    ///////////////////////////////////////////////////////////////////////////////////////////////

    printf("EXAMPLE 2\n");

    // compare these 4 lines ...
    char *t=stringDup(xMainNode.getAttribute("version")); // get version number
    xMainNode=XMLNode::emptyNode();                       // free from memory the top of the xml Tree
    printf("  PMML Version :%s\n\n",t);                       // print version number
    myfree(t);                                              // free version number

    // ... with the following 3 lines (currently commented, because of error):
    //  t=xMainNode.getAttribute("version");      // get version number (note that there is no 'stringDup')
    //  xMainNode=XMLNode::emptyXMLNode;          // free from memory the top of the xml Tree AND the version number inside 't' var
    //  printf("PMML Version :%s\n",t);           // since the version number in 't' has been free'd, this will not work

    /////////////////////////////////////////////////////////////////
    //                                                             //
    //    Example 3: constructing & updating a tree of XMLNode     //
    //                                                             //
    /////////////////////////////////////////////////////////////////

    printf("EXAMPLE 3\n");

    // We create in memory from scratch the following XML structure:
    //  <?xml version="1.0"?>
    //      <body color="FFFFFF"> Hello universe. </body>
    // ... and we transform it into a standard C string that is printed on screen.
    xMainNode=XMLNode::createXMLTopNode("xml",TRUE);
    xMainNode.addAttribute("version","1.0");
    xNode=xMainNode.addChild("body");
    xNode.addText("Hello \"univ\"!");
    xNode.deleteText();
    xNode.addText("Hello \"universe\"!");
    xNode.addAttribute("color","#wrongcolor");
    xNode.updateAttribute("#FFFFFF",NULL,"color");

    t=xMainNode.createXMLString(false);
    printf("  XMLString created from scratch:\n  %s",t);
    myfree(t);

    // we delete some parts:
    xNode.deleteAttribute("color");
    t=xMainNode.createXMLString(false);
    printf("\n  With the \"color\" attribute deleted:\n  %s\n\n",t);
    myfree(t);

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //                                                                                                            //
    //    Example 4: by default, the XML parser is "forgiving" with respect to errors inside XML strings&files    //
    //                                                                                                            //
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    printf("EXAMPLE 4\n");

    // By default, the XML parser is "forgiving":
    // (You can de-activate this behavior: see the header of the xmlParser.cpp file)
    const char *t2="<a><b>some text</b><b>other text    </a>";
    XMLResults xe;
    xMainNode=XMLNode::parseString(t2,NULL,&xe);
    t=xMainNode.createXMLString(false);
    printf("  The following XML: %s\n    ...is parsed as: %s\n  with the following info: '%s'\n\n",t2,t?t:"(null)",XMLNode::getError(xe.error));
    myfree(t);

    /////////////////////////////////////////////////////////////
    //                                                         //
    //    Example 5: deleting a part of the tree of XMLNode    //
    //                                                         //
    /////////////////////////////////////////////////////////////

    printf("EXAMPLE 5\n");

    // this deletes the "<b>other text</b>" subtree part:
    xMainNode.getChildNode("b",1).deleteNodeContent();

    // To perform the same "delete" as above, we can also do:
    // xNode=xMainNode.getChildNode("a").getChildNode("b",1); xNode.deleteNodeContent(); xNode=XMLNode::emptyXMLNode;
    // If you forget the last part of the delete ("xNode=XMLNode::emptyXMLNode"), then the XMLNode will NOT be deleted:
    // In this case, as long as there exists a reference to the XMLNode, the smartPointer mechanism prevent the node to be deleted.

    // To perform the same "delete" as above, we can also do:
    // xNode=xMainNode.getChildNode("a").getChildNode("b",1); xNode.deleteNodeContent(true);
    // The "true" parameter will force the deletion, even if there still exists some references to the XMLNode.

    t=xMainNode.createXMLString(false);
    printf("  ...with the wrong node deleted: %s\n\n",t);
    myfree(t);

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //                                                                                                             //
    //   Example 6: inserting (and moving) a new XMLNode in the middle of an already existing XMLNode structure    //
    //                                                                                                             //
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    printf("EXAMPLE 6\n");

    // This creates a XMLNode 'a' that is "<a><b>some text</b><b>other text</b></a>":
    xMainNode=XMLNode::parseString(t2);
    // This creates a XMLNode 'c' that is "<c>hello</c>":
    xNode=XMLNode::parseString("<c>hello</c>");

    xMainNode.addChild(xNode,0);
    t=xMainNode.createXMLString(false);
    printf("  We inserted a new node 'c' as the first tag inside 'a':\n       %s",t);
    myfree(t);

    xMainNode.addChild(xNode,xMainNode.positionOfChildNode("b",1));
    t=xMainNode.createXMLString(false);
    printf("\n  We moved the node 'c' at the position of the second 'b' tag:\n       %s\n\n",t);
    myfree(t);


    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //                                                                                                             //
    //   Example 7: enumerate all the content of a xmlNode in the order in which they appear inside the XML        //
    //                                                                                                             //
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    printf("EXAMPLE 7\n");

    printf("  Enumeration of the content of the HEADER tag inside the PMML file:\n");
    xMainNode=XMLNode::openFileHelper("PMMLModel.xml","PMML").getChildNode("Header");

    XMLElementPosition ii=xMainNode.nAttribute(),   // we don't want to list all the attributes
                       nn=xMainNode.nElement();     // there are in total nElement.
    while (ii<nn)
    {
        XMLNodeContents xnc=xMainNode.enumContents(ii);
        printf("    Element %i is ",ii);
        switch(xnc.etype)
        {
        case eNodeAttribute: break; // in this example we skip the attributes
        case eNodeChild: printf("a childNode named '%s'\n",xnc.child.getName()); break;
        case eNodeText : printf("a text '%s'\n",xnc.text); break;
        case eNodeClear: printf("a '%s' clear Tag\n",xnc.clear.lpszOpenTag);
        }
        ii++;
    }

    ////////////////////////////////////////////////
    //                                            //
    //    Example 8: base 64 encoding/decoding    //
    //                                            //
    ////////////////////////////////////////////////

    printf("\nEXAMPLE 8\n");

    unsigned char *originalBinaryData=(unsigned char *)"this is binary data.";
    XMLParserBase64Tool b64;
    t=b64.encode(originalBinaryData,21);
    printf(
      "  To be able to include any binary data into an xml file, some Base64"
      "\n  conversion functions (binary data <--> ascii/utf8 text) are provided:\n"
      "    original binary data   : %s\n"
      "    encoded as text        : %s\n",originalBinaryData,t);
    printf("    decoded as binary again: %s\n\n",b64.decode(t));

    //////////////////////////////////////////////////////////////////////
    //                                                                  //
    //    Example 9: demonstration of multi-lingual XML file parsing    //
    //                                                                  //
    //////////////////////////////////////////////////////////////////////

    printf("EXAMPLE 9\n");
    printf("  Processing XML file containing chinese,cyrilic and other extended characters.\n");
    xMainNode=XMLNode::openFileHelper("utf8test.xml");
    xMainNode.writeToFile("outputTestUTF8.xml");
    printf("  ... resulting multi-lingual file is 'outputTestUTF8.xml'.\n\n");

    ////////////////////////////////////////////////////////////
    //                                                        //
    //    Example 10: usage of the "getParentNode()" method    //
    //                                                        //
    ////////////////////////////////////////////////////////////

    printf("EXAMPLE 10\n");
    printf("  Two examples of usage of the \"getParentNode()\" method:\n");
    // In the following two examples, I create a tree of XMLNode based on the string
    // "<a><b>some text</b><b>other text</b></a>". After parsing this string
    // I get a XMLNode that represents the <a> tag. Thereafter I "go down" one
    // level, using getChildNode: I now have a XMLNode that represents the <b> tag.
    // Thereafter I "go up" one level, using getParentNode(): I now have once again
    // a XMLNode that represents the <a> tag. Thereafter, I print the name ('a') of
    // this last XMLNode. The first example below is working as intended (it prints 'a'
    // on the screen). However, the second example below prints "null" because when we
    // did "xMainNode=xMainNode.getChildNode()" we lost all references to the
    // top node and thus it's automatically "garbage collected" (free memory).
    xMainNode=XMLNode::parseString(t2);     xNode=xMainNode.getChildNode();         xNode=xNode.getParentNode(); t=(char*)    xNode.getName(); printf("   Ex1: Name of top node; '%s'\n",t?t:"null");
    xMainNode=XMLNode::parseString(t2); xMainNode=xMainNode.getChildNode(); xMainNode=xMainNode.getParentNode(); t=(char*)xMainNode.getName(); printf("   Ex2: Name of top node; '%s'\n",t?t:"null");


    //////////////////////////////////////////////////////////
    //                                                      //
    //    Example 11: usage of the ToXMLStringTool class    //
    //                                                      //
    //////////////////////////////////////////////////////////

    printf("\nEXAMPLE 11\n");
    // For performance reason it's sometime better to use the old-style "fprintf"
    // function to create a XML file directly without constructing first
    // a XMLNode structure. In such case, the ToXMLStringTool class comes in handy.

    const char *t3="Hello to the <\"World\">";
    printf("  ToXMLStringTool demo: Original String: %s\n"
           "                        Encoded in XML : %s\n",t3,ToXMLStringTool().toXML(t3));

    // If you use several time (in different "fprintf") the same instance of
    // the ToXMLStringTool class, then the memory allocation (needed to create the output
    // buffer) will be performed only once. This is very efficient, very fast.
    // Usually, I create a global instance of the ToXMLStringTool class named "tx" (see
    // line 44 of this file) and then I use "tx" everywhere. For example:
    const char *t4="I say 'pick-a-boo'!";
    printf("  Global ToXMLStringTool: %s\n",tx.toXML(t4));
    printf("  Global ToXMLStringTool: %s\n",tx.toXML(t3));

    // However you must be careful because sometime the output buffer might be
    // erased before being printed. The next example is not working:
    printf("  Error using ToXMLStringTool: %s\n"
           "                               %s\n",tx.toXML(t4),tx.toXML(t3));

    // However, this is working fine:
    printf("  Correct usage of ToXMLStringTool: %s\n"
           "                                    %s\n",tx.toXML(t4),tx2.toXML(t3));

    // Using the "ToXMLStringTool class" and the "fprintf function" is THE most efficient
    // way to produce VERY large XML documents VERY fast.

    return 0;
}