Friday, April 8, 2011

have differance two queue

how to update new queue to Queue3

Queue Getupdate(Queue q1,Queue q2) { How... }

From stackoverflow
  • The question is unclear; what is your desired result? The union? The intersection? What? If you want ("differance" [sic] in title) to return those in the original queue but not the second, perhaps (.NET 3.5):

    public static Queue<T> Except<T>(this Queue<T> original, Queue<T> remove)
    {
        return new Queue<T>(Enumerable.Except<T>(original,remove));
    }
    
  • using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace TestQC
    {
        class Program
        {
            static void Main(string[] args)
            {
                Queue q1 = new Queue();
                Queue q2 = new Queue();
                Queue q3 = new Queue();
                q1.Enqueue(1);
                q1.Enqueue(2);
                q1.Enqueue(3);
                q1.Enqueue(4);
                q2.Enqueue(1);
                q2.Enqueue(2);
                q2.Enqueue(3);
                q2.Enqueue(4);
                q2.Enqueue(5);
                q2.Enqueue(6);
                Console.Write("Q1: ");
                foreach (var o in q1)
                {
                    Console.Write(o.ToString()+ " ");
                }
                Console.WriteLine();
                Console.Write("Q2: ");
                foreach (var o in q2)
                {
                    Console.Write(o.ToString() + " ");
                }
                Console.WriteLine();
                q3 = GetQUpdate(q1, q2);
                Console.Write("Q3: ");
                foreach (var o in q3)
                {
                    Console.Write(o.ToString() + " ");
                }
    
                Console.ReadLine();
            }
            static Queue GetQUpdate(Queue q1, Queue q2)
            {
                Queue q3 = new Queue();
    
                return q3;
            }
        }
    }
    

    I am testing Function For Implement

    Marc Gravell : Yes, but what do you want the result to be? 5,6? then just use the code I posted earlier (perhaps swap the order - q3 = q2.Except(q1);)
    Marc Gravell : Note that using queues in this way is unusual; would a list / etc be more appropriate?
    Brian Rasmussen : You should edit your original question instead of posting updates in an answer.

How do you get your Fulltext boolean search to pick up the term C++ ?

So, I need to find out how to do a fulltext boolean search on a MySQL database to return a record containg the term "C++".

I have my SQL search string as:

SELECT * FROM mytable WHERE MATCH (field1, field2, field3) AGAINST ("C++" IN BOOLEAN MODE)

Although all of my fields contain the string C++, it is never returned in the search results.

How can I modify MySQL to accommodate this? Is it possible?

The only solution I have found would be to escape the + character during the process of entering my data as something like "__plus" and then modifying my search to accomodate, but this seems cumbersome and there has to be a better way.

From stackoverflow
  • Usually escaped characters are used in the query not in the database data. Try escaping each "+" in your query.

  • How can I modify MySQL to accommodate this?

    You'll have to change MySQL's idea of what a word is.

    Firstly, the default minimum word length is 4. This means that no search term containing only words of <4 letters will ever match, whether that's ‘C++’ or ‘cpp’. You can configure this using the ft_min_word_len config option, eg. in your my.cfg:

    [mysqld]
    ft_min_word_len=3
    

    (Then stop/start MySQLd and rebuild fulltext indices.)

    Secondly, ‘+’ is not considered a letter by MySQL. You can make it a letter, but then that means you won't be able to search for the word ‘fish’ in the string ‘fish+chips’, so some care is required. And it's not trivial: it requires recompiling MySQL or hacking an existing character set. See the section beginning “If you want to change the set of characters that are considered word characters...” in section 11.8.6 of the doc.

    escape the + character during the process of entering my data as something like "__plus" and then modifying my search to accomodate

    Yes, something like that is a common solution: you can keep your ‘real’ data (without the escaping) in a primary, definitive table — usually using InnoDB for ACID compliance. Then an auxiliary MyISAM table can be added, containing only the mangled words for fulltext search bait. You can also do a limited form of stemming using this approach.

    Another possibility is to detect searches that MySQL can't do, such as those with only short words, or unusual characters, and fall back to a simple-but-slow LIKE or REGEXP search for those searches only. In this case you will probably also want to remove the stoplist by setting ft_stopword_file to an empty string, since it's not practical to pick up everything in that as special too.

    A. Rex : @bobince: (Re the discussion in the comments above, thank you for answering this easily-understandable question in a clear manner.) Out of curiosity, how would you do stemming with this approach? Replace every word in the auxiliary table with its stem?
    bobince : Essentially yes (processing the words in search queries in the same way of course). Typically you'd use an existing suffix-stripping stemmer library for your preferred languages. (For both values of ‘language’; see eg. Porter's algorithm for English in many programming languages.)
  • From http://dev.mysql.com/doc/refman/5.0/en/fulltext-boolean.html:

    "A phrase that is enclosed within double quote (“"”) characters matches only rows that contain the phrase literally, as it was typed."

    This means you can search for 'C++' using this query:

    SELECT * FROM mytable WHERE MATCH (field1, field2, field3) AGAINST ('"C++"' IN BOOLEAN MODE)

Loading dlls from gac is blocking app

The last few months my application grew bigger and bigger. It's runnable as Wpf .EXE and XBAP at the moment, both sharing the same code. At a few points in the application, the application locks. After invertigating I found out that the application is loading dlls from the GAC at these moments.

What happens is that the application starts, this takes a couple of seconds, and the user is presented with a logon screen. At the moment the user click the OK button to logon the application locks, because it has to load all kinds of dlls for the rest of the application. Because they're loaded from the UI thread all animations stop playing, event the mouseover of the OK button doesn't finish.

It started out as seconds, but at the moment at some points you'll have to wait a couple of minutes before the app continues. I think it's unexceptable.

Is there a way to move the loading of dlls from the GAC to another thread? So a "Please wait while application is loaded"-animation can be played? Or, even better, can I move the loading of all dlls needed to the start of the app, so there would be less waiting going on when working.

From stackoverflow
  • Yes (for "seconds" at least; not sure it scales to "minutes") - at the login screen, just spin up a worker thread (perhaps with ThreadPool) that does something that requires those assemblies. This will cause them to load...

    ThreadPool.QueueUserWorkItem(LoadAssemblies);
    ...
    static void LoadAssemblies(object state)
    {
        Widget1 widget = new Widget1(); // but just let it go (perhaps dispose it)
    }
    

    You are now off the UI thread, loading your assemblies while the user types their password.

    Sorskoot : I thought I tried a construction like that already, but this time it worked. Thanks!

static methods make Java a pseudo functional language?

I've been mulling about a post by Misko Hevery that static methods in Java are a death to testability. I don't want to discuss the testability issue but more on the concept of static methods. Why do people hate it so much?

It's true that we don't have closures (but we have a slightly awkward anonymous functions), lambdas & functions as first class objects. In a way, I think static methods can be used to mimic functions as first class objects.

From stackoverflow
  • Static methods make testing hard because they can't be replaced, it's as simple as that.

    How can static methods "mimic" functions as first class objects? Arguably they're worse than anything else on this front. You can "mimic" functions as first class objects by creating single-method interfaces, and indeed Google's Java Collections does exactly this in a number of places (for predicates, projections etc). That can't be done with static methods - there's no way (other than with reflection) to pass the concept of "when you want to apply a function, use this method.

    No, I can't see how static methods help here. They discourage state-changing (as the only state available is the global state and any mutable state passed in via the parameters) but they don't help on the "functions as first class objects" side.

    C# has better support for this (with lambda expressions and delegates) but even that's not as general as it might be. (Compare it with F#, for example.)

    ThomasD : Why would you ever want to replace a method for testing? I want to test the method not the replacement!
    Anton Gogolev : What if the method goes to a webserver on the opposite hemishpere and you don't really want that, since you'd be better off with static mock data.
    Jon Skeet : +1 to Anton's comment. If you can't replace your dependencies, your "unit" tests will be testing those dependencies as well as the method they're really trying to test.
  • My biggest objection against static methods is that they are not polymorphic and that they are not used in an object-oriented way, instead one has to you the class (not an object) to access them.

  • Functional != function, and for the record I will claim that a method != function...

    Java is a statically typed, object oriented language. Java has also maintained a relative purity in that manner but it's no where near a functional language.

    While it's true that you can mimic the behavior of functional programming with imperative programming you're never gonna get that tidy syntax which you'll wanna have for lambda calculus. In a way, if the language doesn't support proper lambda calculus it's not a functional programming language.

    C++ has functions, but C++ also have classes. C++ therefore have two type of functions, member functions and functions. When you say method you mean a member function. Because the method is invoked on an instance of an object. But when you say static method you mean just function (in the C/C++ sense). This is just a vocabulary for referring to elements of your code. And in Java code can not exist outside a class, a method would imply that it belongs to some class i.e. type.

    So far nothing of what I've said relates to functional programming but I think you get the point where you wrong.

    I suggest you look at pure functional programming languages such as Haskell or Erlang. Because functional programming languages generally don't have closers either.

    Your claim that static methods can be used to mimic functions as first class objects sounds really bizarre to me. It sounds more like a dynamic programming language than functional programming.

  • If you only use static methods then you are programming in a procedural, non-object-oriented style.

    However, the only context I can think of where this would be OK is during the first programming lessons before object orientation is introduced.

  • In Java, you can't give a function as an argument to another function.

    In a functional language, if you have a function

    def addOne(i) = i + 1
    

    you can pass that to another function that eg applies it to all elements of a list.

    In Java, with

    public static int addOne(int i) { return i + 1; }
    

    there is no way to do that.

  • One characteristic of functional programming is immutability of data. static does imply that you don't need an object (instance) representing state, so that's not a bad start. You do however have state on the class level, but you can make this final. Since (static) methods aren't first-class functions at all, you will still need ugly constructions like anonymous classes to approach a certain style of functional programming in Java.

    FP is best done in an functional language, since it has the necessary language support for things like higher-order functions, immutability, referential transparency and so on.

    However, this does not mean that you can't program in a functional style in an imperative language like Java. Other examples can be given as well. It's not because you are programming in Java that you are doing OOP. You can program with global data and unstructured control flows (goto) in a structured language as C++. I can do OOP in a functional language like Scheme. Etc.

    Steve McConnell mentions the difference of programming in a language versus programming into a language in Code Complete (also a very popular reference on SO).

    So, in short, if you say that "static methods mimic first-class functions", I do not agree.

    If, however, and I think that this was more the point you were trying to get across, you would say that "static methods can help for programming in a functional style in Java", I agree.

Webservice problem with base64 data when upgrading to JBoss 4.2.3

Hi, This is a long one du to config files... I'm running a upgrade from JBoss 4.0.5 to 4.2.3 The system I work with have a legacy webservice. It is based on J2EE webservices 1.1. It has a SLSB (EJB2) as endpoint. The WSDL file points out a schema (XSD-file) file for the definition of the parameters to the webservice. And there is a mapping file which maps to the schema.

The problem: For starters, the service works in JBoss 4.0.5. In 4.2.3 it works perfectly fine for except for a attachment element, the base64 data doesn't convert properly into a byte array. Changing it to string works fine, so there is no problem with typos, it just won't convert into a byte array. Has anyone had a similar problem when upgrading from 4.0.5 to 4.2.3?

If i remove an attachments from the call, it works fine, but if I have one, if fails with:

    org.jboss.ws.WSException: org.jboss.ws.core.binding.BindingException: org.jboss.ws.core.jaxrpc.binding.jbossxb.UnmarshalException: Failed to
     parse source: Failed to resolve target property type on org.jboss.xb.binding.sunday.unmarshalling.ElementBinding@1f1804d({http://foo/newsws/types}attachment, type={http://foo/newsws/types}AttachmentElementType)
            at org.jboss.ws.core.soap.XMLContent.unmarshallObjectContents(XMLContent.java:250)
            at org.jboss.ws.core.soap.XMLContent.transitionTo(XMLContent.java:97)
            at org.jboss.ws.core.soap.SOAPContentElement.transitionTo(SOAPContentElement.java:141)
            at org.jboss.ws.core.soap.SOAPBodyElementDoc.transitionTo(SOAPBodyElementDoc.java:85)
            at org.jboss.ws.core.soap.SOAPContentElement.getObjectValue(SOAPContentElement.java:173)
            at org.jboss.ws.core.EndpointInvocation.transformPayloadValue(EndpointInvocation.java:263)
            at org.jboss.ws.core.EndpointInvocation.getRequestParamValue(EndpointInvocation.java:115)
            at org.jboss.ws.core.EndpointInvocation.getRequestPayload(EndpointInvocation.java:135)
            at org.jboss.ws.core.server.DelegatingInvocation.getArgs(DelegatingInvocation.java:82)
            at org.jboss.wsf.container.jboss42.InvocationHandlerEJB21.getMBeanInvocation(InvocationHandlerEJB21.java:169)
            at org.jboss.wsf.container.jboss42.InvocationHandlerEJB21.invoke(InvocationHandlerEJB21.java:144)
            at org.jboss.ws.core.server.ServiceEndpointInvoker.invoke(ServiceEndpointInvoker.java:221)
            at org.jboss.wsf.stack.jbws.RequestHandlerImpl.processRequest(RequestHandlerImpl.java:466)
            at org.jboss.wsf.stack.jbws.RequestHandlerImpl.handleRequest(RequestHandlerImpl.java:284)
            at org.jboss.wsf.stack.jbws.RequestHandlerImpl.doPost(RequestHandlerImpl.java:201)
            at org.jboss.wsf.stack.jbws.RequestHandlerImpl.handleHttpRequest(RequestHandlerImpl.java:134)
            at org.jboss.wsf.stack.jbws.EndpointServlet.service(EndpointServlet.java:84)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
            at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
            at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:182)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:524)
            at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
            at org.apache.catalina.authenticator.SingleSignOn.invoke(SingleSignOn.java:393)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262)
            at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
            at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
            at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446)
            at java.lang.Thread.run(Thread.java:619)
Caused by: org.jboss.ws.core.binding.BindingException: org.jboss.ws.core.jaxrpc.binding.jbossxb.UnmarshalException: Failed to parse source:
Failed to resolve target property type on org.jboss.xb.binding.sunday.unmarshalling.ElementBinding@1369863({http://foo/newsws/t
ypes}attachment, type={http://foo/newsws/types}AttachmentElementType)
        at org.jboss.ws.core.jaxrpc.binding.JBossXBDeserializer.deserialize(JBossXBDeserializer.java:111)
        at org.jboss.ws.core.jaxrpc.binding.JBossXBDeserializer.deserialize(JBossXBDeserializer.java:62)
        at org.jboss.ws.core.binding.DeserializerSupport.deserialize(DeserializerSupport.java:60)
        at org.jboss.ws.core.soap.XMLContent.unmarshallObjectContents(XMLContent.java:180)
        ... 36 more
Caused by: org.jboss.ws.core.jaxrpc.binding.jbossxb.UnmarshalException: Failed to parse source: Failed to resolve target property type on or
g.jboss.xb.binding.sunday.unmarshalling.ElementBinding@1369863({http://foo/newsws/types}attachment, type={http://foo/newsws/types}AttachmentElementType)
        at org.jboss.ws.core.jaxrpc.binding.jbossxb.JBossXBUnmarshallerImpl.unmarshal(JBossXBUnmarshallerImpl.java:65)
        at org.jboss.ws.core.jaxrpc.binding.JBossXBDeserializer.deserialize(JBossXBDeserializer.java:103)
        ... 39 more
Caused by: org.jboss.xb.binding.JBossXBException: Failed to parse source: Failed to resolve target property type on org.jboss.xb.binding.sun
day.unmarshalling.ElementBinding@1369863({http://foo/newsws/types}attachment, type={http://foo/newsws/types}Attach
mentElementType)
        at org.jboss.xb.binding.parser.sax.SaxJBossXBParser.parse(SaxJBossXBParser.java:179)
        at org.jboss.xb.binding.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:126)
        at org.jboss.ws.core.jaxrpc.binding.jbossxb.JBossXBUnmarshallerImpl.unmarshal(JBossXBUnmarshallerImpl.java:61)
        ... 40 more
Caused by: org.jboss.ws.WSException: Failed to resolve target property type on org.jboss.xb.binding.sunday.unmarshalling.ElementBinding@1369
863({http://foo/newsws/types}attachment, type={http://foo/newsws/types}AttachmentElementType)
        at org.jboss.ws.extensions.xop.jaxrpc.JBossXBContentAdapter.beforeSetParent(JBossXBContentAdapter.java:115)
        at org.jboss.xb.binding.sunday.unmarshalling.SundayContentHandler.endElement(SundayContentHandler.java:1005)
        at org.jboss.xb.binding.sunday.unmarshalling.SundayContentHandler.endElement(SundayContentHandler.java:246)
        at org.jboss.xb.binding.parser.sax.SaxJBossXBParser$DelegatingContentHandler.endElement(SaxJBossXBParser.java:296)
        at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
        at org.apache.xerces.xinclude.XIncludeHandler.endElement(Unknown Source)
        at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanEndElement(Unknown Source)
        at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
        at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
        at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
        at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
        at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
        at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
        at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
        at org.jboss.xb.binding.parser.sax.SaxJBossXBParser.parse(SaxJBossXBParser.java:175)
        ... 42 more

this is the webservices.xml

<webservice-description>
    <webservice-description-name>FooService</webservice-description-name>
    <wsdl-file>META-INF/wsdl/FooService.wsdl</wsdl-file>
    <jaxrpc-mapping-file>META-INF/FooService-mapping.xml</jaxrpc-mapping-file>
    <port-component>
        <port-component-name>FooService</port-component-name>
        <wsdl-port>FooServicePort</wsdl-port>
        <service-endpoint-interface>com.foo.FooServiceEndpoint</service-endpoint-interface>
        <service-impl-bean>
                <ejb-link>FooServiceBean</ejb-link>

        </service-impl-bean>
    </port-component>
</webservice-description>

From the foo.xsd

<xs:complexType name="AttachmentElementType">
     <xs:annotation>
      <xs:documentation>Attachment data. When submitting, contains the attachment itself.</xs:documentation>
     </xs:annotation>
     <xs:simpleContent>
      <xs:extension base="xs:base64Binary">
       <xs:attribute name="filename" use="required">
        <xs:annotation>
         <xs:documentation>The filename of the attachment</xs:documentation>
        </xs:annotation>
       </xs:attribute>
       <xs:attribute name="href" type="xs:anyURI" use="optional">
        <xs:annotation>
         <xs:documentation>The URL from which the attachment can be downloaded. Not used when submitting news.</xs:documentation>
        </xs:annotation>
       </xs:attribute>
       <xs:attribute name="mimeType" type="xs:string" use="required">
        <xs:annotation>
         <xs:documentation>The MIME type of the attached file</xs:documentation>
        </xs:annotation>
       </xs:attribute>
      </xs:extension>
     </xs:simpleContent>
    </xs:complexType>

From FooService-mapping.xml

<java-xml-type-mapping>
      <java-type>foo.MessageElementType</java-type>
      <root-type-qname xmlns:typeNS='http://foo/newsws/types'>typeNS:MessageElementType</root-type-qname>
      <qname-scope>complexType</qname-scope>
      <variable-mapping>
       <java-variable-name>category</java-variable-name>
       <xml-element-name>category</xml-element-name>
      </variable-mapping>
      <variable-mapping>
       <java-variable-name>type</java-variable-name>
       <xml-element-name>type</xml-element-name>
      </variable-mapping>
      <variable-mapping>
       <java-variable-name>headline</java-variable-name>
       <xml-element-name>headline</xml-element-name>
      </variable-mapping>
      <variable-mapping>
       <java-variable-name>body</java-variable-name>
       <xml-element-name>body</xml-element-name>
      </variable-mapping>
      <variable-mapping>
       <java-variable-name>attachment</java-variable-name>
       <xml-element-name>attachment</xml-element-name>
      </variable-mapping>
      <variable-mapping>
       <java-variable-name>field</java-variable-name>
       <xml-element-name>field</xml-element-name>
      </variable-mapping>
     </java-xml-type-mapping>

And Attachment.java looks like this:

public class  AttachmentElementType
{

protected java.lang.String filename;

protected java.net.URI href;

protected java.lang.String mimeType;

protected byte[] _value;
public AttachmentElementType(){}

public AttachmentElementType(java.lang.String filename, java.net.URI href, java.lang.String mimeType, byte[] _value){
this.filename=filename;
this.href=href;
this.mimeType=mimeType;
this._value=_value;
}
public java.lang.String getFilename() { return filename ;}

public void setFilename(java.lang.String filename){ this.filename=filename; }

public java.net.URI getHref() { return href ;}

public void setHref(java.net.URI href){ this.href=href; }

public java.lang.String getMimeType() { return mimeType ;}

public void setMimeType(java.lang.String mimeType){ this.mimeType=mimeType; }

public byte[] get_value() { return _value ;}

public void set_value(byte[] _value){ this._value=_value; }

}
From stackoverflow
  • Soved this by reimplenting the service as a JAX-WS annotated webservice, following the same structure and using the same business logic. Not fun, but it worked.

.NET : How to validate XML file with DTD without DOCTYPE declaration

I have an XML file with no DOCTYPE declaration that I would like to validate with an external DTD upon reading.

Dim x_set As Xml.XmlReaderSettings = New Xml.XmlReaderSettings()
x_set.XmlResolver = Nothing
x_set.CheckCharacters = False
x_set.ProhibitDtd = False
x = XmlTextReader.Create(sChemin, x_set)

How do you set the path for that external DTD? How do you validate?

From stackoverflow
  • Could you create an Xml.XmlDocument with the DTD you want, then append the XML file data to the in-memory Xml.XmlDocument, then validate that?

  • I have used the following function successfully before, which should be easy to adapt. How ever this relies on creating a XmlDocument as magnifico mentioned. This can be achieved by:

    XmlDocument doc = new XmlDocument();
    doc.Load( filename );
    doc.InsertBefore( doc.CreateDocumentType( "doc_type_name", null, DtdFilePath, null ), 
     doc.DocumentElement );
    
    
    /// <summary>
    /// Class to test a document against DTD
    /// </summary>
    /// <param name="doc">XML The document to validate</param>
    private static bool ValidateDoc( XmlDocument doc )
    {
     bool isXmlValid = true;
     StringBuilder xmlValMsg = new StringBuilder();
    
     StringWriter sw = new StringWriter();
     doc.Save( sw );
     doc.Save( TestFilename );
    
     XmlReaderSettings settings = new XmlReaderSettings();
     settings.ProhibitDtd = false;
     settings.ValidationType = ValidationType.DTD;
     settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
     settings.ValidationEventHandler += new ValidationEventHandler( delegate( object sender, ValidationEventArgs args )
     {
      isXmlValid = false;
      xmlValMsg.AppendLine( args.Message );
     } );
    
     XmlReader validator = XmlReader.Create( new StringReader( sw.ToString() ), settings );
    
     while( validator.Read() )
     {
     }
     validator.Close();
    
     string message = xmlValMsg.ToString();
     return isXmlValid;
    }
    

Storing username that last modified database row via EJB3.0 and JPA

I'd like to store username that has last modified table row to as a field in every table.

I have following setup: an user logs in, web layer calls some EJB 3.0 beans. Those EJB beans create and modify some JPA entities. Now, I'd like that username (from weblayer) would be automatically stored to every JPA entity (and database row) that is created or modified during EJB method call.

I have this kind of table, (that is: every table has field modifier):

CREATE TABLE my_table (
  some_data INTEGER,
  modifier VARCHAR(20)
);

By automatically I mean, that I wouldn't need to set manually username to each entity inside EJB methods.

You could achive this by storing username to ThreadLocal variable and fetching username from ThreadLocal in JPA entity's EntityListener. However this works only you are using a local EJB call, it will not work with EJB calls that cross JVM boundaries. I'd like to make this work over remote EJB method calls.

It this possible at all?

I am using Weblogic Server 10.3, EJB3.0 and EclipseLink JPA. I am also interested in hearing if this works with other JPA implementations.

From stackoverflow
  • You can use an EJB interceptor (@Around) on the EJB class to get the current user (using standard EJB api) and storing the name in the threadlocal variable. This would work transparently for remote and local calls.

Show process status using AJAX and ASP.NET MVC

I have a method in my controller that kicks of a job on the server. I'll use a Ajax call (jQuery) to start this via a link on the page. This can take a while and I need to show some status on the page. I don't necessarily need "26% done ..." but more a status showing "working" or "done".

How do a get jQuery to continuously pull for the status of the job? Or should it be solved differently?

From stackoverflow
  • You will need some sort of state to hold the status of the task which both the task and Javascript can Access. For example Server Cache. Say you use a key of TaskComplete.

    Kick off your task with javascript through AJAX

    While Your Task Is Running

    Task updates Server Cache Item

    End While

    Parallel

    Use Javascript to poll the cache for a value

    Kick off your task with javascript through AJAX

    While Ajax Response Not Task Complete

    wait 2 seconds

    Call a javascript function through ajax again to read the value of the Server Cache Item

    Execute relevant task based on its value

    An Article you may find useful is here:

    http://msdn.microsoft.com/en-us/magazine/cc163393.aspx

    Riri : OK. Good that's what i thought. But how do I do this "loop"/"timer" in jQuery to keep pulling for status?
    kgiannakakis : Use: setTimeout(your_callback, timeout_in_ms);
    REA_ANDREW : Yes, using the setTimeout though I find it better to use the following syntax var t = setInterval(function(){//execute your function here},milliseconds); When finished clearInterval(t);
    REA_ANDREW : Or find a Jquery Timer Plugin. Both would be sufficient. Hope this helps :-)

Window XP Password policy

Hi, I want to read the values of Account policy of Windows XP programmatically. Source code in C++ (Will be more specific) would be appreciated.

If you have any guidelines then please help me soon.

Thanks in Advance

From stackoverflow
  • Check out this document here (from Microsoft).

    It's an Excel spreadsheet which lists a great deal of registry keys and what they mean, grouped by category.

    Note that it says the password policies aren't in the registry, but it does provide pointers to documents that state how to get at them.

What are the advantages and disadvantages of json vs xml for ajax requests?

What are the advantages and disadvantages of json vs xml for ajax requests? Is there a difference in performance? i.e. are browsers able to process one format faster than the other?

From stackoverflow
  • You may want to read this. With JSON you can fool around with callbacks to and fro between the source and the destination of a request and actually use it painlessly in your existing Javascript code.

    Ido : The link is broken (at least for me...)
    dirkgently : @ido: try json.org
  • In summary, JSON (which can be thought of a subset of JavaScript) is a lot leaner than XML. This has several side-effects, e.g. JSON is generally smaller than a XML document and there for faster to work with.

    JSON can be parsed more efficiently because it can be parsed as JavaScript, which the built-in eval() function will do for you. It's considered unsafe to allow remote JavaScript to execute in this manner, but for the most part it's really perfectly fine. The paranoid would apply a regex on the input to escape potential harmful input, it makes things a little bit slower, but it's a lot faster than a XML document (which comes with a sizable overhead).

    A big difference between JSON and XML (or HTML to be specific) is that HTML represents static content while JSON in conjunction with JavaScript can achieve dynamic content. JSON can be seen as a domain specific data source for browsers due to the nature of the relation between JSON and JavaScript.

    Guillaume : How is JSON more suited than XML to represent dynamic content ?
    dirkgently : @John: You are mixing parsing with execution. They are two different beasts.
    John Leidegren : @Guillaume and dirkgently - JSON is a lot simpler to work with in conjunction with browser scripting. More suitable for pushing data on to the client. I like to think about JSON as specialized JavaScript because it will let me emit behavior from sever-side code which is not as tidy with XML.
  • The link dirkgently provides has a good synopsis of the differences (scroll to the bottom). Important points are:

    JSON: smaller, can represent all unicode characters (xml can't, by its own spec). Its also trivial to make use of it in AJAX applications (because of javascript's eval() function), especially more advanced features like jsonp (responses invoke callbacks).

    XML: Has lots of tools to make querying its structure easy. Since its older and more established, it also has more tool support in general.

    In general, they can accomplish the same things (you could do jsonp through xml, it would just require manually parsing out the callback).

  • You have in this article "The AJAX response: XML, HTML, or JSON?" a full debate on that topic:

    XML

    • Advantages
      The most important advantage of XML is that it's the most easily readable format for other humans.
      A secondary advantage is that XML has been around for quite a while and that many developers are already accustomed to it.
    • Disadvantages
      The JavaScript required to insert the data into the HTML page is quite verbose.

    JSON

    • Advantages
      The most important advantage is that JSON circumvents JavaScript's same-source policy, if you import the JSON file as a new <script> tag. See Simon Willison's example for the gory details.
      JavaScript does not allow you to access documents (be they XML or HTML) that come from another server. However, if you import a JSON file as a script tag you circumvent this problem, and any JSON data can be imported into any website. It depends on your business goals whether this is a Good or a Bad Thing, but right now it's the only data format that allows unrestricted access.
      A secondary advantage is that scripts for JSON data are slightly simpler and slightly more in line with the rest of the JavaScript language than scripts for XML data.
    • Disadvantages
      The most important disadvantage of JSON is that the format is very hard to read for humans, and that, of course, every single comma, quote, and bracket should be in exactly the correct place. While this is also true of XML, JSON's welter of complicated-looking syntax, like the }}]} at the end of the data snippet, may frighten the newbies and make for complicated debugging.

    From the comments, JSON is considered faster to process than XML.

  • One advantage of XML I havent seen sofar in the discussion is that XML can have schema. This is of great value in describing the structure of the XML. For simple data structure, JSON and a bit of text describing what you are doing is fine. When working with more complex data structures, or when the creator and the consumers of the data are not the same team, having a Schema can help the communication a lot.

    Also, having a schema means that you can validate your data, which can be life saving when trying to debug complexe errors ...

  • While I like Json and would recommend it, I think that there is no fundamental difference between optimal processing speed. Differences between libraries and platforms are more significant: a good xml parser is faster than bad json parser and vice versa. So usually performance of formats themselves is not a big factor. Both can be lighting fast (Java has a few good parsers for both, for example, other languages problably too).

    As to compactness, that depends on type of data, Json is often bit more compact, but not radically so. Except if you have lots of arrays/lists, where json notation "{ ... }" is much more compact than xml tagging (unless you use white space if possible, like "1 2 3 4").

  • One advantage of XML that hasn't been mentioned yet is that it is possible to use XSLT to extract data from an XML document using arbitrarily complex XPath expressions. I can't see a way to do this in JSON. How would you find all objects in a JSON document that contain a "currency" field as a direct descendant, irrespective of where the objects occur in the structure? In XML with XSLT/XPath this is very easy.

    However, doing this in the browser comes at a price. You will run into browser-specific quirks, and it will probably be slower and more memory intensive.

Résumé parsing library for a .Net project

I need to extract information from hundreds of résumés. The ideal would be .doc, .docx, .pdf, .rtf --> hr-xml but since more than 90% of the résumés are .doc, the other formats are not a must have.

I'm looking to buy a third-party tool or a component.

Do you have any good/bad experience solving a similar problem?

Clarification: I'm not looking to use MS Indexing Services or Lucene or any other search indexing engine. It's not that straightforward. The biggest challenge is that the layout/format of the résumés is not the same, so simple indexing won't do.

From stackoverflow
  • Microsoft Indexing Service should be able to do what you want. There is a plug-in for PDF and it supports Word documents.

  • You could try Lucene, which is an open source .NET indexing library.

    vitule : Thanks, but see my clarification above.
  • You don't say exactly what info you are looking for, and that makes a big difference. If for example you wish to list email address and phone numbers for all candidates it should be straightforward case of dumping the text ("wv" should do what you for word docs) and constructing or googling for a suitable regex. Searching for specific strings (i.e. tomcat, .NET) is even easier.

    If you need parse out candidate names, street addresses etc. then you're into a whole different world of pain. There's someone trying to do street addresses here:

    In general anything other than the most standardised data formats are probably going to require hand verification and correcting.

    vitule : Sad but true. We tried a couple of third party tools but with the success rate below 60%, we ended up hiring an intern for couple of weeks and let her be our parser...
  • Surely Google must have automated this by now ;-)

    Some sites claiming to solve this:

    http://www.sovren.com/

    http://www.resumate.com/

    If you are screening new applicants for a job, why not offload the effort onto them by designing your own web form for them to fill out, then you will have all the applications in your own standard format.

    Adam Jaskiewicz : I hate when companies do that. It duplicates effort and is very impersonal---it feels like filling out a job-app form at a grocery store. I've had companies want me to fill that kind of stuff out *after* the interview. What, did you not read my resume before the interview? How demeaning.
    Aardvark : +1 for the two links, not for the web-based form idea...
    Bork Blatt : Sure - this isn't pleasant for the applicant. But when there is 1 interviewer, and 1000 resumes, all in different formats, with different names for the same skills, it can be a bit overwhelming. If someone has found a way to automate the screening of resumes in any format, fantastic.
  • In college I had a part-time job reading resumes and entering that data into a database. So the solution for that company was to hire students majoring the subjects relating to the positions they were filling. This was important so the reader would have some understanding of the terms used in the resumes.

    For example, Computer Science students for programming jobs would understand that C != C++ != C# BUT C# should indicate OO experience.

    So that's my non-programming suggestion!

    My technical idea would be to write some Microsoft Word VBA macro code to speed-up data entry. A human would still be involved, highlighting sections of the resume and pressing toolbar buttons that invoke VBA code. For example, have an parse_address macro. It could try to parse the selected text as an address, present a preview of the result in a VBA form, manually tweak as needed, and then press a button on the form to add this data to a database (or whatever...).

  • I've used both sovren and daxtra to do this as part of my current project and have found sovren to be both easier to use and produce better results. It comes as a .net library and is a real no brainer to develop against.

  • I'm using http://www.alt-soft.com Xml2PDF Server for similar purpose