text:
Q: How would you use Java to handle various XML documents? I'm looking for the best method to parse various XML documents using a Java application.  I'm currently doing this with SAX and a custom content handler and it works great - zippy and stable.
I've decided to explore the option having the same program, that currently recieves a single format XML document, receive two additional XML document formats, with various XML element changes.  I was hoping to just swap out the ContentHandler with an appropriate one based on the first "startElement" in the document... but, uh-duh, the ContentHandler is set and then the document is parsed!
... constructor ...
{
SAXParserFactory spf = SAXParserFactory.newInstance();

try {
SAXParser sp = spf.newSAXParser();
parser = sp.getXMLReader();
parser.setErrorHandler(new MyErrorHandler());
} catch (Exception e) {}

... parse StringBuffer ...
try {
parser.setContentHandler(pP);
parser.parse(new InputSource(new StringReader(xml.toString())));
return true;
} catch (IOException e) {
    e.printStackTrace();
} catch (SAXException e) {
    e.printStackTrace();
}
...

So, it doesn't appear that I can do this in the way I initially thought I could.
That being said, am I looking at this entirely wrong?  What is the best method to parse multiple, discrete XML documents with the same XML handling code?  I tried to ask in a more general post earlier... but, I think I was being too vague.  For speed and efficiency purposes I never really looked at DOM because these XML documents are fairly large and the system receives about 1200 every few minutes.  It's just a one way send of information
To make this question too long and add to my confusion; following is a mockup of some various XML documents that I would like to have a single SAX, StAX, or ?? parser cleanly deal with.
products.xml:
<products>
<product>
  <id>1</id>
  <name>Foo</name>
<product>
  <id>2</id>
  <name>bar</name>
</product>
</products>

stores.xml:
<stores>
<store>
  <id>1</id>
  <name>S1A</name>
  <location>CA</location>
</store>
<store>
  <id>2</id>
  <name>A1S</name>
  <location>NY</location>
</store>
</stores>

managers.xml:
<managers>
<manager>
  <id>1</id>
  <name>Fen</name>
  <store>1</store>
</manager>
<manager>
  <id>2</id>
  <name>Diz</name>
  <store>2</store>
</manager>
</managers>

A: As I understand it, the problem is that you don't know what format the document is prior to parsing. You could use a delegate pattern. I'm assuming you're not validating against a DTD/XSD/etcetera and that it is OK for the DefaultHandler to have state.
public class DelegatingHandler extends DefaultHandler {

    private Map<String, DefaultHandler> saxHandlers;
    private DefaultHandler delegate = null;

    public DelegatingHandler(Map<String, DefaultHandler> delegates) {
        saxHandlers = delegates;
    }

    @Override
    public void startElement(String uri, String localName, String name,
            Attributes attributes) throws SAXException {
       if(delegate == null) {
           delegate = saxHandlers.get(name);
       }
       delegate.startElement(uri, localName, name, attributes);
    }

    @Override
    public void endElement(String uri, String localName, String name)
            throws SAXException {
        delegate.endElement(uri, localName, name);
    }

//etcetera...

A: You've done a good job of explaining what you want to do but not why. There are several XML frameworks that simplify marshalling and unmarshalling Java objects to/from XML.
The simplest is Commons Digester which I typically use to parse configuration files. But if you are want to deal with Java objects then you should look at Castor, JiBX, JAXB, XMLBeans, XStream, or something similar. Castor or JiBX are my two favourites.

A: I have tried the SAXParser once, but once I found XStream I never went back to it. With XStream you can create Java Objects and convert them to XML. Send them over and use XStream to recreate the object. Very easy to use, fast, and creates clean XML.
Either way you have to know what data your going to receiver from the XML file. You can send them over in different ways to know which parser to use. Or have a data object that can hold everything but only one structure is populated (product/store/managers). Maybe something like:
public class DataStructure {

    List<ProductStructure> products;

    List<StoreStructure> stors;

    List<ManagerStructure> managers;

    ...

    public int getProductCount() {
        return products.lenght();
    }

    ...
}

And with XStream convert to XML send over and then recreate the object. Then do what you want with it.

A: See the documentation for XMLReader.setContentHandler(), it says:

Applications may register a new or different handler in the middle of a parse, and the SAX parser must begin using the new handler immediately.

Thus, you should be able to create a SelectorContentHandler that consumes events until the first startElement event, based on that changes the ContentHandler on the XML reader, and passes the first start element event to the new content handler. You just have to pass the XMLReader to the SelectorContentHandler in the constructor. If you need all the events to be passes to the vocabulary specific content handler, SelectorContentHandler has to cache the events and then pass them, but in most cases this is not needed.
On a side note, I've lately used XOM in almost all my projects to handle XML ja thus far performance hasn't been the issue.

A: JAXB. The Java Architecture for XML Binding.  Basically you create an xsd defining your XML layout (I believe you could also use a DTD).  Then you pass the XSD to the JAXB compiler and the compiler creates Java classes to marshal and unmarshal your XML document into Java objects.  It's really simple.
BTW, there are command line options to jaxb to specify the package name you want to place the resulting classes in, etc.

A: If you want more dynamic handling, Stax approach would probably work better than Sax.
That's quite low-level, still; if you want simpler approach, XStream and JAXB are my favorites. But they do require quite rigid objects to map to.

A: Agree with StaxMan, who interestingly enough wants you to use Stax.  It's a pull based parser instead of the push you are currently using.  This would require some significant changes to your code though.

A: :-)
Yes, I have some bias towards Stax. But as I said, oftentimes data binding is more convenient than streaming solution. But if it's streaming you want, and don't need pipelining (of multiple filtering stages), Stax is simpler than SAX.
One more thing: as good as XOM is (wrt alternatives), often Tree Model is not the right thing to use if  you are not dealing with "document-centric" xml  (~= xhtml pages, docbook, open office docs).
For data interchange, config files etc data binding is more convenient, more efficient, more natural. Just say no to tree models like DOM for these use cases.
So, JAXB, XStream, JibX are good. Or, for more acquired taste, digester, castor, xmlbeans.

A: VTD-XML is known for being the best XML processing technology for heavy duty XML processing. See the reference below for a proof
http://sdiwc.us/digitlib/journal_paper.php?paper=00000582.pdf


text:
Q: Using RESTful API Calls to register a user When I want to register a user on my server, I use my RESTful API I created to do the job. So for example, I would make a POST request to  http://server.com/users
This API call will generate a new user id, if the user currently does not exist and save him to the database and then returns the newly created user id to the app, so the app knows about the user id being used from now on.
At the same time, I want to register the user's device as well to my web service, as I will send Push Notifications. Now this is not difficult in terms of how to do it, but I am thinking for a while now, how is it efficient? These are my thoughts:

*

*Using RESTful APIs means to me, that I use a clear way of separating tasks to different controllers. So I would have a APIUserController and a APIDeviceController. Therefore, if I want to register a user, it will be the POST request http://server.com/users, and to register a device it should be a POST request to http://server.com/devices. So the call to users would return the created userID and I would then make a POST request to devices with the userID I got returned by my first call. This means, two different calls from the app to the Server.

*But when I think about efficiency, my first thought would be, to make only one POST request to http://server.com/users containing all data needed (like the device token) and create the user on the server as well as creating the device. But this means, I would directly create the entry into the database, and mixing up responsibilities in the users controller.

I definitely need some help here on this. What is the purpose of differentiating the responsibilites when creating a new user AND registering a new device, when I then lose effiency by calling the server twice to use the restful approach?

A: I think that arguably the devices belong to the users, so I don't see any harm in including the device information when you add a new user as an optional component. Sort of like if a user wants to optionally include their "bio". You probably wouldn't have a separate endpoint for "bios".
Also since you have a direct relationship between users and devices, perhaps it might be more logical instead of using a separate /devices endpoint to make it a sub directory of /users. Something like /users/12345/devices.

redpajama_set_name: RedPajamaStackExchange


text:
Q: htaccess redirects not working in relative paths I'm trying to make a redirection from all files to a template file. But redirects only works when I specify an URL
For example:
Does not work (it does not redirects)
Options -Indexes
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /template.php?page=$1 [L,QSA]

Works (redirects to http://domain.com/versioned/template.php?page=index.html)
Options -Indexes
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) http://domain.com/versioned/template.php?page=$1 [L,QSA]

And the second option is change the URL in the browser. I need to keep the original URL.
Thanks
The problem is with
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} -f

If I quit this, it works, but instead of returning the current file in URL, it returns always template.php

A: If the htaccess file is in the versioned directory, you don't want the leading slash in the rule's target:
Options -Indexes
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) template.php?page=$1 [L,QSA]

The relative URL-path in this rule's target, template.php?page=$1, tells mod_rewrite to rewrite the request to this URL-path that is within the path that the htaccess file is in. When you had the target as /template.php?page=$1, it assumed an absolute URL-path, which would be equivalent to: http://domain.com/template.php?page=foo.


text:
Q: How to Exclude a Row in Look up Field in Sharepoint Form? Assume i have SP List A and SP List B.
in SP list B i have a look up field which uses SP list A as Data Source.
SP List A have two Fields (i.e. Field 1 : Project Name, Field 2: Project Status)
I need to exclude Entries with Project Status as "Closed" in look up.
is there any way to Exclude this in infopath form or something else ?

A: I found that in MS infopath we can filter out the content in Lookup by
right click the Look up field  field properties in Data tab select data source from add
 button and apply filter in forecoming Wizards


text:
Q: Minikube: automatically pull all the latest images from GCR and restarted those pods Is there a way to configure the minikube cluster to automatically pull "all" the latest docker images from GCR for all the pods in the cluster and restarted those pods once you start your minikube cluster?

A: You can use the AlwaysPullImages admission controller which forces the imagePullPolicy to Always which will repull images on pod restart. And then just restart all your pods.


text:
Q: OpenCV 2.4.3 to 2.4.9 version change I'm taking over a project that someone else started two years ago with OpenCV2.4.3 and I now downloaded OpenCV2.4.9 because I couldn't find 2.4.3 anymore.
When I try to compile in Visual Studio 12 it says:
1>LINK : fatal error LNK1104: cannot open file 'C:\OpenCV2.4.3\lib\Debug\opencv_core243d.lib'
Do I manually have to change all ...249.. to ...243.. or is there a easier way?

A: CMake is the much better way to handle such problems, all you need is to re-build on your PC and it will set all these stuffs for you.
CMake to setup OpenCV library (similar to others) is like:
find_package(OpenCV REQUIRED)
include_directories(${OPENCV_INCLUDE_DIRS})
link_directories(${OPENCV_LIBRARY_DIRS})
add_definitions(${OPENCV_DEFINITIONS})
target_link_libraries(your-project ${OpenCV_LIBS})


text:
Q: Test Multiple Criteria in VBA DO While loop I am trying to edit some VBA code which currently loops until a certain test is met. What I would like to do is loop until two conditions are met. I am having trouble getting it do so. Here is the original code, which works.
    Loop
    For j = 1 To 29
    Increment = Worksheets("Price & Energy Curve").Cells(8 + Start + j, 3).Value
    l = Int((Worksheets("Capacity").Cells(57 + j, 12).Value) * (-1) / Increment)
    k = WorksheetFunction.Max((l + 1) * Increment, 0)
    Worksheets("Capacity").Activate
    ActiveSheet.Cells(56 + j, 17).Value = k
    test = ActiveSheet.Cells(57 + j, 13).Value
    Do While test <> True
    k = k + Increment
    ActiveSheet.Cells(56 + j, 17).Value = k
    test = ActiveSheet.Cells(57 + j, 13).Value
    Loop
    Next j

I would like to add the additional test of
   test = ActiveSheet.Cells(57 + j, 37).Value

So that when
   test = ActiveSheet.Cells(57 + j, 13).Value

and
  test = ActiveSheet.Cells(57 + j, 37).Value

are true, the loop exits.

A: Check this loop
Do While test1 <> True Or test2 <> True
k = k + Increment
ActiveSheet.Cells(56 + j, 17).Value = k
test1 = ActiveSheet.Cells(57 + j, 13).Value
test2 = ActiveSheet.Cells(57 + j, 37).Value
Loop


text:
Q: FixedThreadPool not parallel enough I create a fixed threadpool using forPool = Executors.newFixedThreadPool(poolSize); where poolSize is initialized to the number of cores on the processor (lets say 4). In some runs, it works fine and the CPU utilisation is consistently at 400%.
But sometimes, the usage drops to 100%, and never rises back to 400%. I have 1000s of tasks scheduled, so the problem is not that. I catch every exception, but no exception is thrown. So the issue is random and not reproducible, but very much present. They are data parallel operations. At the end of each thread, there is a synchronised access to update a single variable. Highly unlikely I have a deadlock there. In fact, once I spot this issue, if I destroy the pool, and create a fresh one of size 4, it is still only 100% usage. There is no I/O.
It seems counter intuitive to java's assurance of a "FixedThreadPool". Am I reading the guarantee wrong? Is only concurrency guaranteed and not parallelism?
And to the question - Have you come across this issue and solved it? If I want parallelism, am I doing the correct thing?
Thanks!
On doing a thread dump:
I find that there are 4 threads all doing their parallel operations. But the usage is still ~100% only. Here are the thread dumps at 400% usage and 100% usage. I set the number of threads to 16 to trigger the scenario. It runs at 400% for a while, and then drops to 100%. When I use 4 threads, it runs on 400% and only rarely drops to 100%. This is the parallelization code.
****** [MAJOR UPDATE] ******
It turns out that if I give the JVM a huge amount of memory to play with, this issue is solved  and the performance does not drop. But I don't know how to use this information to solve this issue. Help!

A: Given the fact that increasing your heap size makes the problem 'go away' (perhaps not permanently), the issue is probably related to GC.
Is it possible that the Operation implementation is generating some state, that is stored on the heap, between calls to
pOperation.perform(...);

?  If so, then you might have a memory usage problem, perhaps a leak.  As more tasks complete, more data is on the heap.  The garbage collector has to work harder and harder to try and reclaim as much as it can, gradually taking up 75% of your total available CPU resources.  Even destroying the ThreadPool won't help, because that's not where the references are stored, it's in the Operation.
The 16 thread case hitting this problem more could be due to the fact that it's generating more state quicker (don't know the Operation implementation, so hard for me to say).
And increasing the heap size while keeping the problem set the same would make this problem appear to disappear, because you'd have more room for all this state.

A: I'll suggest that you use the Yourkit Thread Analysis feature to understand the real behavior. It will tell you exactly which threads are running, blocked or waiting and why.
If you can't/don't want to purchase it, next best option is to use Visual VM, which is bundled with the JDK to do this analysis. It won't give you as detailed information as Yourkit. Following blog post can get you started with Visual VM:
http://marxsoftware.blogspot.in/2009/06/thread-analysis-with-visualvm.html

A: My answer is based on a mixture of knowledge about JVM memory management and some guesses about facts which I could not find precise information on. I believe that your problem is related to the thread-local allocation buffers (TLABs) Java uses:

A Thread Local Allocation Buffer (TLAB) is a region of Eden that is
  used for allocation by a single thread. It enables a thread to do
  object allocation using thread local top and limit pointers, which is
  faster than doing an atomic operation on a top pointer that is shared
  across threads.

Let's say you have an eden size of 2M and use 4 threads: The JVM may choose a TLAB size of (eden/64)=32K and each thread gets a TLAB of that size. Once the 32K TLAB of a thread are exhausted, it needs to acquire a new one, which requires global synchronization. Global synchronization is also needed for allocation of objects which are larger than the TLAB.
But, to be honest with you, things are not as easy as I described: The JVM adaptively sizes a thread's TLAB based on its estimated allocation rate determined at minor GCs [1] which makes TLAB-related behavior even less predictable. However, I can imagine that the JVM scales the TLAB sizes down when more threads are working. This seems to make sense, because the sum of all TLABs must be less than the available eden space (and even some fraction of the eden space in practice to be able to refill the TLABs).
Let us assume a fixed TLAB size per thread of (eden size / (16 * user threads working)):

*

*for 4 threads this results in TLABs of 32K

*for 16 threads this results in TLABs of 8K

You can imagine that 16 threads which exhaust their TLAB faster because it's smaller will cause much more locks on the TLAB allocator than 4 threads with 32K TLABs.
To conclude, when you decrease the number of working threads or increase the memory available to the JVM, the threads can be given larger TLABs and the problem is solved.
https://blogs.oracle.com/daviddetlefs/entry/tlab_sizing_an_annoying_little

A: This is almost certainly due to GC.
If you want to be sure add the following startup flags to your Java program:
-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps
and check stdout.
You will see lines containing "Full GC" including the time this took: during this time you will see 100% CPU usage.
The default garbage collector on multi-CPU or multi-core machines is the throughput collector, which collects the young generation in parallel but uses serial collection (in one thread) for the old generation.
So what is probably happening is that in your 100% CPU example, GC is going on of the old generation which is done in one thread and so keeps one core busy only.
Suggestion for solution: use the concurrent mark-and-sweep collector, by using the flag  -XX:+UseConcMarkSweepGC at JVM startup.

A: Tune the JVM
The core of the Java platform is the Java Virtual Machine (JVM). The entire Java application server runs inside a JVM. The JVM takes many startup parameters as command line flags, and some of them have great implications on the application performance. So, let's examine some of the important JVM parameters for server applications.
First, you should allocate as much memory as possible to the JVM using the -Xms (minimum memory) and -Xmx (maximum memory) flags. For instance, the -Xms1g -Xmx1g tag allocates 1GB of RAM to the JVM. If you don't specify a memory size in the JVM startup flags, the JVM would limit the heap memory to 64MB (512MB on Linux), no matter how much physical memory you have on the server! More memory allows the application to handle more concurrent web sessions, and to cache more data to improve the slow I/O and database operations. We typically specify the same amount of memory for both flags to force the server to use all the allocated memory from startup. This way, the JVM wouldn't need to dynamically change the heap size at runtime, which is a leading cause of JVM instability. For 64-bit servers, make sure that you run a 64-bit JVM on top of a 64-bit operating system to take advantage of all RAM on the server. Otherwise, the JVM would only be able to utilize 2GB or less of memory space. 64-bit JVMs are typically only available for JDK 5.0.
With a large heap memory, the garbage collection (GC) operation could become a major performance bottleneck. It could take more than ten seconds for the GC to sweep through a multiple gigabyte heap. In JDK 1.3 and earlier, GC is a single threaded operation, which stops all other tasks in the JVM. That not only causes long and unpredictable pauses in the application, but it also results in very poor performance on multi-CPU computers since all other CPUs must wait in idle while one CPU is running at 100% to free up the heap memory space. It is crucial that we select a JDK 1.4+ JVM that supports parallel and concurrent GC operations. Actually, the concurrent GC implementation in the JDK 1.4 series of JVMs is not very stable. So, we strongly recommend you upgrade to JDK 5.0. Using the command line flags, you can choose from the following two GC algorithms. Both of them are optimized for multi-CPU computers.

*

*If your priority is to increase the total throughput of the
application and you can tolerate occasional GC pauses, you should use
the -XX:UseParallelGC and -XX:UseParallelOldGC (the latter is only
available in JDK 5.0) flags to turn on parallel GC. The parallel GC
uses all available CPUs to perform the GC operation, and hence it is
much faster than the default single thread GC. It still pauses all
other activities in the JVM during GC, however.

*If you need to minimize the GC pause, you can use the
-XX:+UseConcMarkSweepGC flag to turn on the concurrent GC. The concurrent GC still pauses the JVM and uses parallel GC to clean up
short-lived objects. However, it cleans up long-lived objects from
the heap using a background thread running in parallel with other JVM
threads. The concurrent GC drastically reduces the GC pause, but
managing the background thread does add to the overhead of the system
and reduces the total throughput.

Furthermore, there are a few more JVM parameters you can tune to optimize the GC operations.

*

*On 64-bit systems, the call stack for each thread is allocated 1MB of
memory space. Most threads do not use that much space. Using the
-XX:ThreadStackSize=256k flag, you can decrease the stack size to 256k to allow more threads.

*Use the -XX:+DisableExplicitGC flag to ignore explicit application
calls to System.gc(). If the application calls this method
frequently, then we could be doing a lot of unnecessary GCs.

*The -Xmn flag lets you manually set the size of the "young
generation" memory space for short-lived objects. If your application
generates lots of new objects, you might improve GCs dramatically by
increasing this value. The "young generation" size should almost
never be more than 50% of heap.

Since the GC has a big impact on performance, the JVM provides several flags to help you fine-tune the GC algorithm for your specific server and application. It's beyond the scope of this article to discuss GC algorithms and tuning tips in detail, but we'd like to point out that the JDK 5.0 JVM comes with an adaptive GC-tuning feature called ergonomics. It can automatically optimize GC algorithm parameters based on the underlying hardware, the application itself, and desired goals specified by the user (e.g., the max pause time and desired throughput). That saves you time trying different GC parameter combinations yourself. Ergonomics is yet another compelling reason to upgrade to JDK 5.0. Interested readers can refer to Tuning Garbage Collection with the 5.0 Java Virtual Machine. If the GC algorithm is misconfigured, it is relatively easy to spot the problems during the testing phase of your application. In a later section, we will discuss several ways to diagnose GC problems in the JVM.
Finally, make sure that you start the JVM with the -server flag. It optimizes the Just-In-Time (JIT) compiler to trade slower startup time for faster runtime performance. There are more JVM flags we have not discussed; for details on these, please check out the JVM options documentation page.
Reference:
http://onjava.com/onjava/2006/11/01/scaling-enterprise-java-on-64-bit-multi-core.html

A: A total cpu utilisation at a 100% implied that you have written is single threaded. i.e. you may have any number of concurrent tasks, but due to locking, only one can execute at a time.
If you have high IO you can get less than 400% but it is unlikely you will get a round number of cpu utilisation. e.g. you might see 38%, 259%, 72%, 9% etc. (It is also likely to jump around)
A common problem is locking the data you are using too often. You need to consider how it could be re-written where locking is performed for the briefest period and smallest portion of the overall work. Ideally, you want to avoid locking all together.
Using multiple thread means you can use up to that many cpus, but if your code prevents it you are likely to be better off (i.e. faster) to write the code single threaded as it avoids the overhead of locking.

A: Since you are using locking, it is possible that one of your four threads attains the lock but is then context switched - perhaps to run the GC thread. The other threads can't make progress since they can't attain the lock. When the thread context switches back, it completes the work in the critical section and relinquishes the lock to allow only one other thread to attain the lock. So now you have two threads active. It is possible that while the second thread executes the critical section the first thread does the next piece of data parallel work but generates enough garbage to trigger the GC and we're back where we started :)
P.S. This is just a best guess since it is hard to figure out what is happenning without any code snippets.

A: Increasing the size of the Java heap usually improves throughput until the heap no longer resides in physical memory. When the heap size exceeds the physical memory, the heap begins swapping to disk which causes Java performance to drastically decrease. Therefore, it is important to set the maximum heap size to a value that allows the heap to be contained within physical memory.
Since you give the JVM ~90% of physical memory on the machines, problem may be related to IO happening due to memory paging and swapping when you try to allocate memory for more objects. Note that the physical memory is also used by other running processes as well as OS. Also since symptoms occur after a while, this is also indication for memory leaks.

Try to find out how much physical memory is available (not already
  used) and allocate ~90% of available physical memory to your JVM heap.

*

*What happens if you leave the system running for extended period of
time?

*Does it ever comes back at CPU 400% of utilization?

*Do you notice any disk activity when CPU is at 100% of utilization?

*Can you monitor which threads are running and which are blocked and
when?

Take a look at following link for tuning:
http://java.sun.com/performance/reference/whitepapers/tuning.html#section4


text:
Q: google cloud dataflow sdk - dependencies issue Added the dataflow dependency to the project. The project builds , but on start up ( using jetty ) I get a runtime exception
 <dependency>
        <groupId>com.google.cloud.dataflow</groupId>
        <artifactId>google-cloud-dataflow-java-sdk-all</artifactId>
        <version>1.9.0</version>
    </dependency>

caused by: java.lang.ClassNotFoundException: com.google.auth.http.HttpTransportFactory
at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:259)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:235)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:227)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:487)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:428)

if i remove the dependency. The start up has not issues.
Any idea why the dataflow dependency is causing startup error.

A: Added the exclusion for the conflicting dependency, and it works.
 <dependency>
        <groupId>com.google.cloud.dataflow</groupId>
        <artifactId>google-cloud-dataflow-java-sdk-all</artifactId>
        <version>1.9.0</version>
        <exclusions>
            <exclusion>
                <groupId>com.google.auth</groupId>
                <artifactId>google-auth-library-oauth2-http</artifactId>
            </exclusion>
        </exclusions>
    </dependency>


text: Q: Dataframe not available in the next field in iPython notebook I hope someone can help me with this problem. I'm new to iPython Notebook, so apologies... I run my script and in the end store the data into a data frame. But then when I jump to the next line and try to access it for future analysis I get this error: NameError: name 'parties' is not defined where parties is the name of my df. All I do is build the df from a list of dictionaries: parties = pd.DataFrame(alldict) within my code which I run using main(). I can print and access the df within the code with no problems but if I jump to the next line in the notebook I get this error. Should I save it in a different way? I'll appreciate your advice. Below a screenshot where you can see that I can manipulate the df inside the main but not outside.


text:
Q: Mapping between Azure AD and Snowflake roles I have seen a similar post here but it doesn't answer my question.
I have a long Azure AD group names and would like to map them to shorter role names in Snowflake. Is this possible? From my understanding the name of the group will become the name of the role (1 to 1), right?
I would be grateful for any feedback,
Rafal

A: That's correct. The Azure AD group name will become the name of the role within Snowflake.
More details:
https://learn.microsoft.com/en-us/azure/active-directory/saas-apps/snowflake-provisioning-tutorial
https://docs.snowflake.com/en/user-guide/scim-azure.html#azure-scim-integration-with-snowflake


text:
Q: Drupal table creation error I am trying to create a table in Drupal database using hook_schema function but I am getting the PDO exception error which I could not resolve. It would be great if you could provide me an solution to my issue
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error     in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'DEFAULT '' COMMENT
'first name of the user', `lname` VARCHAR DEFAULT '' COMMENT' at line 3:
CREATE TABLE {mage_user} ( `uid` INT unsigned NOT NULL auto_increment COMMENT
'The foreign identifier for a mage user.', `fname` VARCHAR DEFAULT ''
COMMENT 'first name of the user', `lname` VARCHAR DEFAULT '' COMMENT
'last name of the user', `address1` VARCHAR(255) DEFAULT '' COMMENT
'adress line 1', `address2` VARCHAR(255) DEFAULT '' COMMENT 'adress line 2',
`postcode` VARCHAR(7) DEFAULT '' COMMENT 'postcode', `gender` VARCHAR(6)
DEFAULT ''  COMMENT 'gender' ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8
COMMENT 'The base table for mage user.'; Array ( ) in db_create_table()
(line 2688 of E:\Server\drupal\includes\database\database.inc).

I am using
Apache/2.2.22 (Win32) PHP/5.3.10
MySQL client version: mysqlnd 5.0.8-dev - 20102224 - $Revision: 321634 $
MySQL server version 5.5.21
and my schema definition is
    function mageacc_schema() {

          $schema['mageuser'] = array(
        'description' => 'The base table for mage user.',
        'fields' => array(
        'uid' => array(
        'description' => 'The foreign identifier for a mage user.',
        'type' => 'serial',
        'not null' => TRUE,
  ),
  'fname' => array(
    'description' => 'first name of the user',
    'type' => 'varchar',
    'lenght' => 255,
    'default' => '',
  ),
      'lname' => array(
      'description' => 'last name of the user',
      'type' => 'varchar',
      'lenght' => 255,
      'default' => '',
  ),
     'address1' => array(
     'description' => 'adress line 1',
     'type' => 'varchar',
     'length' => 255,
     'default' => '',

  ),
  'address2' => array(
      'description' => 'adress line 2',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',

     ),
     'postcode' => array(
      'description' => 'postcode',
      'type' => 'varchar',
      'length' => 7,
       'default' => '',
    ),
    'gender'=>array(
    'description' => 'gender',
    'type' => 'varchar',
    'length' => 6,
    'default' => '',
    ),

  ),

        );

  return $schema;

}

Thanks in Advance

A: I spotted a few typos with the 'length' property. Try fixing those first in fname and lname to see if it works.


text:
Q: How to check cookie existence in .net framework 2.0? I've used this code to check if some cookie exists in request:
if (Request.Cookies.AllKeys.Contains("action")

But this code does not work in .net framework 2.0 since System.Array does not contain a definition for Contains.
What is the most simple thing to do this other than iterating through AllKeys?

A: You can check it on the Cookies collection itself by using the name as an index and avoid having to access AllKeys:
 if (Request.Cookies["action"] != null)


text:
Q: JavaScript checker for HTML5 and CSS3 Does anyone know what that script was called that checks for HTML5 and CSS3 support? I think it also adds support for them. It was called something like Modifier.

A: you looking for Modernizr?


text:
Q: Can I change GROUP_CONCAT Limit in SQLite? I am thinking about switching from MySQL to SQLite,
but in the MySQL Server I set the variable group_concat_max_len = 1000000;
Before I switch everything to the SQLite engine I want to know if there is a limit too and if I can change it, in case of, can I change the limit with this query?
set global group_concat_max_len = 1000000;


text:
Q: Rails devise sign in not working I have a problem - recently I created User with devise gem. Sadly, the "sign_in" button does not really work properly - after visiting sin_in page and clicking on sign in button nothing happens! It does not matter if I enter my email and password for signing in. I checked the logs and after clicking sign up button there are no changes in logs or on the terminal with server running on! So I guess it does not send any request? But the problem occurs only after I visit the login page the first time, after refreshing it all works as intended. Please help me, I have no idea what may cause such weird behaviour.
EDIT: Oddly enough, I noticed that only after heading to login page from my main page the problem occurs - If I proceed to login page simply by typing its address instead of clicking on sing in link in browser it works. But addresses after both actions are the same, so I have no idea... There are my welcome view:

<%= link_to "E-LEARN", "#" %>

<%= link_to "Watch guides", root_path %>

        <% unless user_signed_in? %>

<%= link_to "Log In", new_user_session_path %>

        <% else %>

<%= link_to "Log Out", destroy_user_session_path, method: :delete %>

<%= link_to "Settings", edit_user_registration_path %>

<%= link_to "My Account", current_user %>

        <% end %>

<%= link_to "Add tutorial", "#" %>

Learn programming from others, or share your experience with novices.

    <%= link_to "Learn something", new_user_registration_path , class: "button button-highlight" %>
    <%= link_to "Share experience", "#", class: "button button-dark"%>

There are my files:
application controller:
 class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_filter :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :description, :email, :password, :password_confirmation, :current_password) }
  end
end

migration:
class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at

      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end

User.rb
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :guides
  validates :username, presence: true, length: { minimum: 5 }
end

routes:
Rails.application.routes.draw do

  root to: 'welcome#index'
  devise_for :users

  resources :users, only: [:show, :index] do
    resources :guides
  end

end

and gemfile:
source 'https://rubygems.org'

gem 'rails', '4.2.2'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'sqlite3'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'bcrypt', '~> 3.1.7'
gem 'devise', '~> 3.5', '>= 3.5.2'
gem 'paperclip', '~> 4.3', '>= 4.3.1'

group :development, :test do
  gem 'byebug'
  gem 'web-console', '~> 2.0'
  gem 'spring'
end

group :development do
  gem 'sqlite3'
end

group :production do
  gem 'pg', '0.17.1'
  gem 'rails_12factor'
end

routes:
                 Prefix Verb   URI Pattern                               Controller#Action
                    root GET    /                                         welcome#index
        new_user_session GET    /users/sign_in(.:format)                  devise/sessions#new
            user_session POST   /users/sign_in(.:format)                  devise/sessions#create
    destroy_user_session DELETE /users/sign_out(.:format)                 devise/sessions#destroy
           user_password POST   /users/password(.:format)                 devise/passwords#create
       new_user_password GET    /users/password/new(.:format)             devise/passwords#new
      edit_user_password GET    /users/password/edit(.:format)            devise/passwords#edit
                         PATCH  /users/password(.:format)                 devise/passwords#update
                         PUT    /users/password(.:format)                 devise/passwords#update
cancel_user_registration GET    /users/cancel(.:format)                   devise/registrations#cancel
       user_registration POST   /users(.:format)                          devise/registrations#create
   new_user_registration GET    /users/sign_up(.:format)                  devise/registrations#new
  edit_user_registration GET    /users/edit(.:format)                     devise/registrations#edit
                         PATCH  /users(.:format)                          devise/registrations#update
                         PUT    /users(.:format)                          devise/registrations#update
                         DELETE /users(.:format)                          devise/registrations#destroy
             user_guides GET    /users/:user_id/guides(.:format)          guides#index
                         POST   /users/:user_id/guides(.:format)          guides#create
          new_user_guide GET    /users/:user_id/guides/new(.:format)      guides#new
         edit_user_guide GET    /users/:user_id/guides/:id/edit(.:format) guides#edit
              user_guide GET    /users/:user_id/guides/:id(.:format)      guides#show
                         PATCH  /users/:user_id/guides/:id(.:format)      guides#update
                         PUT    /users/:user_id/guides/:id(.:format)      guides#update
                         DELETE /users/:user_id/guides/:id(.:format)      guides#destroy
                   users GET    /users(.:format)                          users#index
                    user GET    /users/:id(.:format)                      users#show

and my login view (devise/sessions/new.html.erb):
<%= render 'shared/header' %>

Log in

  <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

      <%= f.label :email %>

      <%= f.email_field :email, autofocus: true %>

      <%= f.label :password %>

      <%= f.password_field :password, autocomplete: "off" %>

    <% if devise_mapping.rememberable? -%>

        <%= f.check_box :remember_me %>
        <%= f.label :remember_me %>

    <% end -%>

      <%= f.submit "Log in" %>

  <% end %>

  <%= render "devise/shared/links" %>

A: Looks like turbolinks problem.

*

*Remove turbolinks gem from your Gemfile

*Run bundle install

*In app/views/layouts/application.html.haml set turbolinks to false like that:

= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => false
= javascript_include_tag 'application', 'data-turbolinks-track' => false
or remove them.

*remove //= require turbolinks from app/assets/javascripts/application.js

*Restart server

A: @JakubKopyś Here is nice way to exclude single link from turbolinks without removing gem (from turbolinks github repo):
"By default, all internal HTML links will be funneled through Turbolinks, but you can opt out by marking links or their parent container with data-no-turbolink. For example, if you mark a div with data-no-turbolink, then all links inside of that div will be treated as regular links. If you mark the body, every link on that entire page will be treated as regular links."

  Home (without Turbolinks)


text:
Q: How to fetch Data from mysql database into android I have an android application that contains 2 pages, one for login and the other for a list view.
The Login is good and when the PHP JSON result is good in the web but I can't view my items in the listview when I click on the button an error appears "Unfortunately the app has stopped " and application restart.

this is the PHP code :

<?php
    include 'DatabaseConfig.php';

    // Create connection
    $conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);

    if ($conn->connect_error) {

     die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT * FROM products";

    $result = $conn->query($sql);

    if ($result->num_rows >0) {

     while($row[] = $result->fetch_assoc()) {

     $tem = $row;

     $json = json_encode($tem);

     }

    } else {
     echo "No Results Found.";
    }
     echo $json;
    $conn->close();
    ?>

For the android:

MainPageActivity.java

package com.example.dell.apptest;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.support.design.widget.NavigationView;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainPageActivity extends AppCompatActivity
{
    String url="http://187.241.2.32:8089/AppTest/JSonTextView.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_page);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final ListView lv= (ListView) findViewById(R.id.lv);
        final Downloader d=new Downloader(this,url,lv);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //EXECUTE DOWNLOAD
                d.execute();
            }
        });
    }

}

It gives this JSON :
[{"Id":"7","Name":" test","Position":"description"},{"Id":"1","Name":"zerty","Position":"feztez"}]

Parser.java

package com.example.dell.apptest;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Parser extends AsyncTask<Void,Integer,Integer> {

    Context c;
    ListView lv;
    String data;

    ArrayList<String> products=new ArrayList<>();
    ProgressDialog pd;

    public Parser(Context c, String data, ListView lv) {
        this.c = c;
        this.data = data;
        this.lv = lv;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pd=new ProgressDialog(c);
        pd.setTitle("Parser");
        pd.setMessage("Parsing ....Please wait");
        pd.show();
    }

    @Override
    protected Integer doInBackground(Void... params) {

        return this.parse();
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);

        if(integer == 1)
        {
            //ADAPTER
            ArrayAdapter<String> adapter=new ArrayAdapter<String>(c,android.R.layout.simple_list_item_1,products);

            //ADAPT TO LISTVIEW
            lv.setAdapter(adapter);

            //LISTENET
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Snackbar.make(view,products.get(position),Snackbar.LENGTH_SHORT).show();;
                }
            });

        }else
        {
            Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
        }

        pd.dismiss();
    }

    //PARSE RECEIVED DATA
    private int parse()
    {
        try
        {
            //ADD THAT DATA TO JSON ARRAY FIRST
            JSONArray ja=new JSONArray(data);

            //CREATE JO OBJ TO HOLD A SINGLE ITEM
            JSONObject jo=null;

            products.clear();

            //LOOP THRU ARRAY
            for(int i=0;i<ja.length();i++)
            {
                jo=ja.getJSONObject(i);

                //RETRIOEVE NAME
                String name=jo.getString("Name");

                //ADD IT TO OUR ARRAYLIST
                products.add(name);
            }

            return 1;

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return 0;
    }
}

Downloader.java

   package com.example.dell.apptest;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Downloader extends AsyncTask<Void,Integer,String> {

    Context c;
    String address;
    ListView lv;

    ProgressDialog pd;

    public Downloader(Context c, String address, ListView lv) {
        this.c = c;
        this.address = address;
        this.lv = lv;
    }

    //B4 JOB STARTS
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pd=new ProgressDialog(c);
        pd.setTitle("Fetch Data");
        pd.setMessage("Fetching Data...Please wait");
        pd.show();
    }

    @Override
    protected String doInBackground(Void... params) {
        String data=downloadData();
        return data;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        pd.dismiss();;

        if(s != null)
        {
            Parser p=new Parser(c,s,lv);
            p.execute();

        }else
        {
            Toast.makeText(c,"Unable to download data",Toast.LENGTH_SHORT).show();
        }
    }

    private String downloadData()
    {
        //connect and get a stream
        InputStream is=null;
        String line =null;

        try {
            URL url=new URL(address);
            HttpURLConnection con= (HttpURLConnection) url.openConnection();
            is=new BufferedInputStream(con.getInputStream());

            BufferedReader br=new BufferedReader(new InputStreamReader(is));

            StringBuffer sb=new StringBuffer();

            if(br != null) {

                while ((line=br.readLine()) != null) {
                    sb.append(line+"\n");
                }

            }else {
                return null;
            }

            return sb.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is != null)
            {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}


text:
Q: What is the difference between PreviewContactChanged and ContactChanged? Title is fairly self-explanitory, I'm working on a Microsoft Surface application, and I don't know what the difference is between these two event handler sets beyond that the PreviewContact(Changed/Down/etc) set works and Contact(Changed/Down/etc) set often doesn't. Is the "Preview" set merely an update for the "regular" set, or does it have something to do with how the event is being fired?

A: In WPF - which the Surface SDK is built upon - a Routed Event has three routing strategies:

*

*Bubble

*Tunnel

*Direct

An event with a Bubble strategy will 'Bubble' up the visual tree from the event source to the root of the visual tree (SurfaceWindow) until it either reaches the root of the visual tree or is handled.  Conversely, an event with the Tunnel strategy will drill down the visual tree starting at the root until it reaches the event source.  Contact events will use both strategies, the Preview events (e.g.PreviewContactDown) use a tunneling strategy while the non-preview events (e.g. ContactDown) will use a Bubble strategy.
If ContactDown is not working then likely the event is being handled somewhere between the root of the visual tree and the event source.
For more information about Routed Events in WPF (this information also applies to Surface) I suggest reading Brian Noyes article Understanding Routed Events and Commands In WPF


text:
Q: 6D integral with gaussian ansatz Does anyone know how to handle this integral:
$$\int d^3 r \int d^3 r' \phi(\mathbf{r})\phi(\mathbf{r'})\frac{Y^{0}_{2}(\mathbf{r} - \mathbf{r'})}{|\mathbf{r} - \mathbf{r'}|^3}$$
with
$$\phi(\mathbf{r}) = \exp\left( -\frac{x^2}{\sigma_{1}^{2}} -\frac{y^2}{\sigma_{2}^{2}} -\frac{z^2}{\sigma_{3}^{2}}\right)$$
and $Y^{2}_0(\mathbf{r})$ being spherical harmonic:
$$Y_{2}^{0}(\mathbf{r}) = \frac{1}{4}\sqrt{\frac{5}{\pi}}\frac{2z^2 - x^2 - y^2}{x^2 + y^2 + z^2}$$
All variables extent from $-\infty$ to $+\infty$. I don't really know if any analitical formula exists. Maybe some series expansion of Green's function ?
Please help.


text:
Q: Does Haxe have a friendship with XPath? I need to get some XML node by it's XPath, how I can do it?
I tried to use this library https://github.com/djcsdy/haxe-xpath, but something wrong https://github.com/djcsdy/haxe-xpath/issues/26
and for my task xml-fast isn't good solution, because it looks "slightly worse" than XPath, I think:
js (xpath):
xml_doc.get('//project/classpaths/class[@path="' + src_path + '"]')

haxe (xml-fast):
(new Fast(xml_doc))).node.project.node.classpaths.nodes.class.filter(function (x:Fast) return x.has.path ? x.att.path == src_path : false)

thanks

A: As result was found two libraries and both require some fixes.
1. "Haxe XPath"
it can be used only if clone directory "haxe-xpath/src/xpath" into you sources (haxelib repo isn't contains this library).
Some fixes was needed for this library: this and this
example (delete first found element):
package;

import xpath.XPathHx;
using Lambda;

class Main {
    public static function main () {
        var xml = Xml.parse("<a> <b> <c>qwe</c> <c>asd</c> </b> </a>");
        trace(xml.toString());

        var xpExpr = new XPathHx("//a/b/c"); // create new XPath expression object
        var result = xpExpr.selectNodes(xml).array()[0]; // get first element from array of founded xml-nodes

        result.parent.removeChild(result); // remove selected node from xml-tree
        trace(xml.toString());
    }
}

2. "xmlTools"
it can be installed with haxelib:
haxelib install xmlTools
haxelib install composure

Some fix was needed for this library (in my task) and one nuance for xpath.
example (delete first found element):
package;

import xmlTools.XPath;
using Lambda;

class Main {
    public static function main () {
        var xml = Xml.parse("<a> <b> <c>qwe</c> <c>asd</c> </b> </a>");
        trace(xml.toString());

        var xpath  = new XPath(); // create new XPath expression object
        var result = xpath.resolve(xml, "*/a/b/c").array()[0]; // get first element from array of founded xml-nodes

        result.parent.removeChild(result); // remove selected node from xml-tree
        trace(xml.toString());
    }
}


text:
Q: Real analysis, limit points ,basics Prove that $S= \{(-1)^n:n\in\mathbb{N}\}$
has two limit points $-1$ and $1$.
How can set $S$ possess limit point since Set $S ={-1,1,-1,1....}$? It has $-1$ and $1$ as its element if $-1$ is its limit point then $(-1-\epsilon ,-1+ \epsilon)$ intersection $S -\{-1\}$ should have infinitely many points but that's not the case.

A: It depends on what you mean by "limit point" and how you interpret the notation.
If $S$ is a sequence, namely the sequence $n\mapsto(-1)^n$, then certainly $1$ and $-1$ are limit points in the sense of the following definition

a point $p$ is called a limit point (or a cluster point) of the sequence $n\mapsto a_n$ if for every neighborhood $U$ of $p$ and every $k$ there exists $n>k$ with $a_n\in U$.

In other words, a limit (or cluster) point is one such that a subsequence converges to.
If you consider $S$ as a set, then it has no limit points, because it's finite.


text:
Q: remove unused rows in jtable (Empty Rows)? a question about removing unused rows in jtable i am using DefualtTableModel my table already has some data & when i update it leave some columns empty to update theme later so they are null column.. i want to remove theme with a push button before saving data.. i actually tried this code:
private void btn_ClearActionPerformed(java.awt.event.ActionEvent evt) {
      table.setAutoCreateRowSorter(true);

      TableRowSorter sorter = (TableRowSorter) table.getRowSorter();
      sorter.setRowFilter(new RowFilterImpl());
}

i also tried this:
private void btn_ClearActionPerformed(java.awt.event.ActionEvent evt) {
    table.setAutoCreateRowSorter(true);
    TableRowSorter sorter = (TableRowSorter) table.getRowSorter();
    sorter.setRowFilter(new RowFilter<TableModel, Integer>() {
        @Override
        public boolean include(RowFilter.Entry<? extends TableModel, ? extends Integer> entry) {
            boolean included = true;
            Object cellValue = entry.getModel().getValueAt(entry.getIdentifier(), 0);
            if (cellValue == null || cellValue.toString().trim().isEmpty()) {
                included = false;
            }
            return included;
        }
    });
}

the code above is working but i don't like it  becuase it resizes rows after filtering so i want to do something with model.remove(); using if conditions.. and i want to specify columns for example column 7 & 12 and want to remove only empty rows in specified columns..
ok i tried this code:
for (int i = model.getRowCount() - 1; i >= 0; i--)
{
     Object col1 = model.getValueAt( i,model.getColumnCount() - 6);
     Object col2 = model.getValueAt( i,model.getColumnCount() - 11);

     if (col1 == null || col2 == null)
         model.removeRow(i);
}

i faced same problem and i found this code below cuasing that problem so i removed it ... i also found that it counts how many time you selected or clicked on a row and then resizes it as many you clicked!
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
       int lastRow = -1;

       public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
               if (lastRow != -1) {
                  table.setRowHeight(lastRow, table.getRowHeight());
              }

              int row = table.getSelectedRow();
              table.setRowHeight(row, 23);
              lastRow = row;
         }
       }
   });

any idea guys?
thanx in advance

A: Create a loop to remove the data from the model.
Maybe something like:
for (int i = model.getRowCount() - 1; i >= 0; i--)
{
    if (column?? == null && column?? == null)
        model.removeRow(i);
}

added the problem above in table.setRowHeight();

Well, that should have been part of the original question. How do we know you have custom logic doing something strange???
In the future post a proper SSCCE that demonstrates the problem so we don't have to guess what you are doing.

i get the same problem it resizes rows

Then remove the listener:

*

*remove the listener

*delete the rows

*add the listener


text:
Q: How do I open a FolderBrowserDialog at the selected folder? I have a FolderBrowserDialog, displayed with code shown below.  However, it keeps opening with 'Computer', i.e. the root of the folder tree, selected.  How do I get it to open on the selected folder?
       var folderBrowser = new FolderBrowserDialog();
        folderBrowser.Description = "Select Chase 6 Installation Folder";
        folderBrowser.RootFolder = Environment.SpecialFolder.MyComputer;
        folderBrowser.ShowNewFolderButton = false;
        if (Directory.Exists(Properties.Settings.Default.defaultChasePath))
        {
            string x = Properties.Settings.Default.defaultChasePath;
            folderBrowser.SelectedPath = x;
        }
        if (folderBrowser.ShowDialog(this) == DialogResult.OK)
        {
            chasePathtext.Text = folderBrowser.SelectedPath;
        }

A: Set rootfolder to
Environment.SpecialFolder.Desktop

and it should work as you want.
It is the only way to actually set the initial selected folder. You'd think using
Environment.SpecialFolder.MyComputer

would work, but it doesn't.

A: This works for me:
FolderBrowserDialog diag = new FolderBrowserDialog();
diag.Description = "Select a folder in which to save your workspace...";
diag.SelectedPath = Application.StartupPath;

if (DialogResult.OK == diag.ShowDialog())
{
    // do something here...
}

Set the SelectedPath property, not RootFolder.
EDIT:
Here's a screenshot showing the Application.StartupPath being in "C:\LocalDocuments\Visual Studio 2010\Projects\FolderBrowserDialogTest\FolderBrowserDialogTest\bin\Debug", which is most definitely not in the Desktop directory.

A: The folderbrowser dialog is a wrapper around a windows API call that does not match all the relevant paths possible ( I suppose that would be an uphill task..) this can be mimicked using your own class though. Generate the following class inside your application (adding namespace and System.Reflection)
public class RootSetter
{
    [Flags()]
    public enum CsIdl
    {
        Desktop = 0x0000, // Desktop
        Internet = 0x0001, // Internet Explorer (icon on desktop)
        Programs = 0x0002, // Start Menu\Programs
        Controls = 0x0003, // My Computer\Control Panel
        Printers = 0x0004, // My Computer\Printers
        Personal = 0x0005, // My Documents
        Favorites = 0x0006, // user name\Favorites
        Startup = 0x0007, // Start Menu\Programs\Startup
        Recent = 0x0008, // user name\Recent
        SendTo = 0x0009, // user name\SendTo
        BitBucket = 0x000a, // desktop\Recycle Bin
        StartMenu = 0x000b, // user name\Start Menu
        MyDocuments = 0x000c, // logical "My Documents" desktop icon
        MyMusic = 0x000d, // "My Music" folder
        MyVideo = 0x000e, // "My Videos" folder
        DesktopDirectory = 0x0010, // user name\Desktop
        Drives = 0x0011, // My Computer
        Network = 0x0012, // Network Neighborhood (My Network Places)
        Nethood = 0x0013, // user name\nethood
        Fonts = 0x0014, // windows\fonts
        Templates = 0x0015,
        CommonStartMenu = 0x0016, // All Users\Start Menu
        CommonPrograms = 0x0017, // All Users\Start Menu\Programs
        CommonStartup = 0x0018, // All Users\Startup
        CommonDesktopDirectory = 0x0019, // All Users\Desktop
        AppData = 0x001a, // user name\Application Data
        PrintHood = 0x001b, // user name\PrintHood
        LocalAppData = 0x001c, // user name\Local Settings\Applicaiton Data (non roaming)
        AltStartup = 0x001d, // non localized startup
        CommonAltStartup = 0x001e, // non localized common startup
        CommonFavorites = 0x001f,
        InternetCache = 0x0020,
        Cookies = 0x0021,
        History = 0x0022,
        CommonAppdata = 0x0023, // All Users\Application Data
        Windows = 0x0024, // GetWindowsDirectory()
        System = 0x0025, // GetSystemDirectory()
        ProgramFiles = 0x0026, // C:\Program Files
        MyPictures = 0x0027, // C:\Program Files\My Pictures
        Profile = 0x0028, // USERPROFILE
        SystemX86 = 0x0029, // x86 system directory on RISC
        ProgramFilesX86 = 0x002a, // x86 C:\Program Files on RISC
        ProgramFilesCommon = 0x002b, // C:\Program Files\Common
        ProgramFilesCommonx86 = 0x002c, // x86 Program Files\Common on RISC
        CommonTemplates = 0x002d, // All Users\Templates
        CommonDocuments = 0x002e, // All Users\Documents
        CommonAdminTools = 0x002f, // All Users\Start Menu\Programs\Administrative Tools
        AdminTools = 0x0030, // user name\Start Menu\Programs\Administrative Tools
        Connections = 0x0031, // Network and Dial-up Connections
        CommonMusic = 0x0035, // All Users\My Music
        CommonPictures = 0x0036, // All Users\My Pictures
        CommonVideo = 0x0037, // All Users\My Video
        Resources = 0x0038, // Resource Direcotry
        ResourcesLocalized = 0x0039, // Localized Resource Direcotry
        CommonOemLinks = 0x003a, // Links to All Users OEM specific apps
        CdBurnArea = 0x003b, // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning
        ComputersNearMe = 0x003d, // Computers Near Me (computered from Workgroup membership)
        FlagCreate = 0x8000, // combine with CSIDL_ value to force folder creation in SHGetFolderPath()
        FlagDontVerify = 0x4000, // combine with CSIDL_ value to return an unverified folder path
        FlagNoAlias = 0x1000, // combine with CSIDL_ value to insure non-alias versions of the pidl
        FlagPerUserInit = 0x0800, // combine with CSIDL_ value to indicate per-user init (eg. upgrade)
        FlagMask = 0xFF00, // mask for all possible flag values
    }

    public static void SetRootFolder(System.Windows.Forms.FolderBrowserDialog fbd, CsIdl csidl)
    {
        Type t = fbd.GetType();
        FieldInfo fi = t.GetField("rootFolder", BindingFlags.Instance | BindingFlags.NonPublic);
        fi.SetValue(fbd, (System.Environment.SpecialFolder)csidl);
    }

and then inside your calling class when setting the root folder use the following syntax. It would be better to check the enum fior a close value should you find one but if you cannto then the one below is fairly generic and allows me to move thorugh my C drive easily enough.
private void button1_Click(object sender, EventArgs e)
    {
        FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
        folderBrowser.Description = "Select Chase 6 Installation Folder";
        folderBrowser.RootFolder = Environment.SpecialFolder.ProgramFiles;
        folderBrowser.ShowNewFolderButton = false;

        if (Directory.Exists(Properties.Settings.Default.defaultChasePath))
        {
            string x = Properties.Settings.Default.defaultChasePath;

            //Use API Flag to set correct path, following tahter a catch all better to check
            //enum for full list
            RootSetter.SetRootFolder(folderBrowser, RootSetter.CsIdl.FlagDontVerify);

            folderBrowser.SelectedPath = x;

        }
        if (folderBrowser.ShowDialog(this) == DialogResult.OK)
        {
            string huz = folderBrowser.SelectedPath;
        }
    }

Hope that helps :)

A: If you set RootFolder to Environment.SpecialFolder.Desktop then it will open to the SelectedFolder as long as the path is valid.
When you set RootFolder to Environment.SpecialFolder.MyComputer, then the first time the dialog opens, it will always start at MyComputer, not the SelectedFolder path.
If a valid selection is made, then subsequent uses of the same FolderBrowserDialog instance will open at the previously selected path.

A: My solution, here
I wrote this solution based on this solution by ParkerJay86. The solution worked on Windows 8 with several paths tested. Consider that your specified rootFolder should start with DriveLetter:\ like "C:\ProgramData"
        private void browseFolder_Click(object sender, EventArgs e)
        {
            String selectedPath;
            if (ShowFBD("C:\\", "Please Select a folder", out selectedPath))
            {
                MessageBox.Show(selectedPath);
            }
        }

        public bool ShowFBD(String rootFolder, String title, out String selectedPath)
        {
            var shellType = Type.GetTypeFromProgID("Shell.Application");
            var shell = Activator.CreateInstance(shellType);
            var result = shellType.InvokeMember("BrowseForFolder", BindingFlags.InvokeMethod, null, shell, new object[] { 0, title, 0, rootFolder });
            if (result == null)
            {
                selectedPath = "";
                return false;
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                while (result != null)
                {
                    var folderName = result.GetType().InvokeMember("Title", BindingFlags.GetProperty, null, result, null).ToString();
                    sb.Insert(0, String.Format("{0}\\", folderName));
                    result = result.GetType().InvokeMember("ParentFolder", BindingFlags.GetProperty, null, result, null);
                }
                selectedPath = sb.ToString();

                selectedPath = Regex.Replace(selectedPath, @"Desktop\\Computer\\.*\(\w:\)\\", rootFolder.Substring(0, 3));
                return true;
            }
        }

A: From the Microsoft help for FolderBrowserDialog class:

Typically, after creating a new
  FolderBrowserDialog, you set the
  RootFolder to the location from which
  to start browsing. Optionally, you can
  set the SelectedPath to an absolute
  path of a subfolder of RootFolder that
  will initially be selected.

Are you possibly setting the SelectedPath to a location that doesn't equate to a subfolder of RootFolder (i.e. My Computer)? That would probably cause it to dive back to the RootFolder as the presented location.

A: I was trying to assign a non-existent folder path to the SelectedFolder property.  When you use a valid path, the root folder loses relevance.  When you don't assign a SelectedFolder value, at least one of the Environment.SepcialFolder values will suffice.
COMING SOON:  Attempts at using reflection to dynamically set a non-special root folder.  Stay tuned.

A: To select existing path (no special f...ng folders) you must write own treeview based form.

A: I was seeing this problem using:
RootFolder = Environment.SpecialFolder.MyComputer
SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

By playing around with hard-wired versions of that path's subpaths and sibling branches, I decided this really is a permissions thing.  It doesn't work with C:\Users[UserID]\Documents, but it works fine with C:\Users, or C:\Users\Public\Documents (even though that doesn't exist or, at least it's called Public Documents instead of Documents), or C:\Users\Default\Documents (even though that doesn't exist or, at least it's called My Documents instead of Documents).
What I ended up doing was checking whether the SelectedPath contains "\users[UserID]", then using Environment.SpecialFolder.Desktop if it did and Environment.SpecialFolder.MyComputer if it didn't.
Probably, checking the SelectedPath folder permissions would be a better test, but this will do for the expected use cases.


text:
Q: Error trying to eiliminate a specific line of a file , by passing it all to an array I'm doing a school project, and my focus is to copy several lines of a text file to an arrays of strings and then ask to the user which string they want to remove and write back the array on a file.
My program is opening the file and copying the content right to the array, but when I try to compare line by line with the string that the user gave me it doesn't go so well.
If I have in the file pedropedro and I want to remove it I need to compare all the elements of the array with pedropedro, I'm using strcmp, but it never returns 0 so I can't delete this line. Why is this happening? Stay safe.
if (strcmp("6",numero)==0)
    {
            char nome_elim[15];
            char pass_elim[15];
            char final_elim[30];
            char c;
            int i=0;
            int tamanho;
           printf("Insira o nome de utilizador que pretende eliminar:\n");
           scanf("%s",nome_elim);
           printf("Insira a password referent ao nome de utilizador:\n");
           scanf("%s",pass_elim);
           strcat(final_elim,nome_elim);
           strcat(final_elim,pass_elim);
           strcat(final_elim,"\n");

           printf("Vai adicionar: %s\n",final_elim);

           FILE *fptr =fopen("logins.txt","r+");

          if(fptr == NULL)
           {
              printf("Error!");
             exit(1);
           }else{
           char ch;
           int count =0;
           do{
           ch=fgetc(fptr);
           if(ch=='\n')count++;

           }while(ch!=EOF);
           rewind(fptr);
            tamanho=count;
           int i;
           for(i=0;i<count;i++){
           fscanf(fptr,"%s",cur_member[i].a);
           printf("%s\n",cur_member[i].a);

           }

           }
           int pos=0;

              fclose(fptr);

            FILE *fptr1 =fopen("logins.txt","w");

          if(fptr == NULL)
           {
              printf("Error!");
             exit(1);
             }

           for(int y=0;y<tamanho;y++)
          {
           if(strcmp(cur_member[y].a,final_elim)==0)
           {
           printf("IGUALIGUAL");
           continue;
           }
           else{
           printf("%d",y);
           fputs(cur_member[y].a,fptr1);
           fputs("\n",fptr1);
           }

           }
            fclose(fptr1);

        strcpy(nome_elim,"\0");
        strcpy(pass_elim,"\0");
        strcpy(final_elim,"\0");

    }


text:
Q: CodeIgniter with multi databases stored in database I'm working on 20 websites and each one has his own database, but they have the same structure of database.
The problem is that I have to login to the different back-end to do some work on each one.
So, I decided to write single CI back-end for all of the websites.
For that, I created a database with two tables (user, websites)
The user table is for the login action.
The websites table list all websites and the associated database.
What I would like to do is, in any view of my backend application, be able to select the database (or website), so that the current view can be reloaded with data from the selected database to perform some work on it and then submit it.
I'm using CI V1.7.2

A: This seems very plausible. However, note that once you change the database adapter, database session storage will not work as you expect since it's stored in the first database that you've mentioned.
So after when you verified the user and grabbed the database's DSN (database source name), you can change the database adapter when executing your queries by doing:
$this->database->load('dbdriver://username:password@hostname/database');

Note that dbdriver is the type of database you are using, refer to the config file for the types. You can also take a look at the documentation for more information.
If you want database session storage to work, you may want to create a new database adapter, the method is similar from above, but there's one more parameter.
$new_db = $this->database->load($dsn, TRUE);

However, this method would most likely require some refactoring in your code since you're used to performing queries like $this->database->query(); and you'll need to change it to $new_db->query().


text:
Q: Use Single Blog Post as Site Front Page Without Redirect I am attempting to do something similar to the accepted answer on this question Is it possible to use a single custom post as the site front page
My problem is that this implementation causes a redirect.
So for example if I add the code below to twentyeleven functions.php on a default WordPress install, and then select the Hello World post from the reading->front page drop down my home url such as mysite.com will redirect to mysite.com/?p=1. So it is impossible to actually stay on the home page because of this redirect.
Is it possible to avoid this redirect? If so, the solution below will be great for showing a post or custom post as the home page.
add_filter( 'get_pages', 'add_pages_to_dropdown', 10, 2 );

function add_pages_to_dropdown( $pages, $r ){
    if ( ! isset( $r[ 'name' ] ) )
        return $pages;

    if ( 'page_on_front' == $r[ 'name' ] ) {
        $args = array(
            'post_type' => 'post'
        );

        $portfolios = get_posts( $args );
        $pages = array_merge( $pages, $portfolios );
    }

    return $pages;
}

A: I'll just copy/paste my answer to that question, here:
There are many ways to accomplish this, though some are more advanced than others:

*

*Mark the blog post as sticky, and then set Posts per Page to 1 (Dashboard -> Settings -> Reading)

*Create a custom front-page.php template, and query the post in question, either via the sticky post designation, or via custom post meta

*Create a custom front-page.php template, and create a dynamic sidebar (i.e. Widget area), in which you add a Widget to display the post in question

*(Insert lots of other methods here...)

But I have to ask: why not just put that blog post content in a static Page, and then assign that static Page as the Front Page?
Edit
Also: be sure that you have pretty permalinks enabled, via Dashboard -> Settings -> Permalinks.

A: My solution so far has been to take the reading->front page option out of the equation and go with a custom post type settings page.
Adding a settings page requires a bit of code but it can be done starting with the add_submenu_page(); function.
Then you can use the pre_get_posts action to alter the query by using that option you set like so
add_action( 'pre_get_posts', 'my_pre_get_posts' );

function my_pre_get_posts($query){
        $option = get_option('my_option');
        if(is_front_page()){
                $query->set('p', $option);
                $query->set('post_type', 'post');
        }

    }

This allows you to avoid having to create a front-page.php file which could be a duplication of a more specific theme file. The drawbacks to this are obvious, you now have an extra settings page. Not sure there is really a "correct" answer to this one.

A: You can just make a copy single.php and name it home.php and put it in your theme folder.
Wordpress will use that as a home now.
Ref: http://codex.wordpress.org/Template_Hierarchy
Then you just change the loop inside your home.php (based on single.php) to look like it's explained here:
http://codex.wordpress.org/Function_Reference/query_posts#Retrieve_a_Particular_Post
So this:
<?php
if ( have_posts() ) while ( have_posts() ) : the_post();
?>

Becomes this:
<?php
query_posts( 'p=5' );
if ( have_posts() ) while ( have_posts() ) : the_post();
?>

Where the line "query_posts" specify the postID that you want as a home (check that on wp-admin side). In the example, p=5 will query for postID = 5.
Or you can just redefine a new loop using http://codex.wordpress.org/Class_Reference/WP_Query method to ensure nothing else be broken with the new loop.
Pretty neat and simple.


text:
Q: SAN spec'ing and IOPS counters I'd like to make sure that I'm measuring IOPS correctly across Windows and Linux servers. We're busy trying to figure out which SAN would best suit our environment and measuring IOPS across our servers is the kind of thing I just can't get wrong. Little bit of procurement paranoia kicking in.
On the Windows servers I'm using the \PhysicalDisk(_Total)\Disk Reads/sec and \PhysicalDisk(_Total)\Disk Writes/sec performance counters. On the Linux servers I run vmstat and am looking at the bi (read) and bo (write) counters. I'm pretty sure that I've got this right and that both sets of counters equate to IOPS.
If these counters are correct then I have a problem. The SAN we're going for can handle about 1600 IOPS. Our two mail filter servers, which run MailScanner, MailWatch and Sophos, are hitting around 1500 IOPS collectively. Our two MySQL server run at about 1600 IOPS collectively. We're way over the 1600 IOPS theoretical limit.
Hence the question, am I measuring correctly?
Ossan

A: Following on from the comment thread above, iostat -dxk 1 will give you r/s and w/s (read and write requests/sec) as well as kbytes read and written.

A: Possibly. Raid 5 is slow for updates. I never have seen Raid 5 used in high perofrmance setups, unless you count Raid 0s over multipel raid 5's as such (Raid 50, 60).
On top, seriously - a 5 disc raid 5 is not a "SAN" as "able to handle 100.000thousands of IOPS". It is an end user thingy.
Note the difference: Backup ismost likely not writing out randomly and / or read operrations on a Raid are faster than write.

A: Two important points here:

*

*be careful using your existing numbers -- depending on the workload, your current usage may reflect what the underlying storage is capable of. For example, you may see mysql using 1600 iops now because that's what those disks can do. If you put it on a SAN that can do 3000 iops, say, then mysql might start doing 3000 iops, and your queries would return faster. Talk with your vendor to properly size based on your workload.

*It's important to consider both iops and throughput (MBps), since they are not necessarily proportional and either can be a bottleneck at various points in the SAN -- disk, controller, hba, network, etc. Which of these will apply to you depends on how sequential or random your workload and the i/o size. Again, talk with your vendor to properly size based on your needs.


text:
Q: Angular HTML templating - How can I use the current value of a number input as the upper bound for my array slice? This is probably super simple but I can't figure it out. I have a number input, and I want to use the current value of that number input to display/hide a certain number of items in a list. template looks like this:
<input type="number" value="10" step="10" min="10" style="width: 4em" (change)="showNThings = this.value">
...

Initially it seems like this code works (10 items are displayed) but I think only because this.value is referencing the value attribute of the input tag. Items are not displayed/hidden when I manipulate the input number. How do I assign the CURRENT value of the input to my showNThings variable?

A: working demo : link
You can also do it using *ngFor's index property and *ngIf. Using them together you can achieve it. First in *ngFor pick the current iteration number using index then use *ngIf where you can check that iteration number should be less than limit number. If it satisfies above condition then only show the inner
 Like shown below.

app.component.html

    <div *ngIf="i<limit">ITEM NUMBER : {{item}}

app.component.ts

export class AppComponent  {
limit=4;
   arr:number[]=[1,2,3,4,5,6,7,8,9,10];
   clickHanler(val:number){
        this.limit = val;
   }
}

A: There are two-way to data binding.
the first way is
When typing into the input, the input's value is written into the username model and then reflected back into the view, resulting in a nice greeting.
<input [(ngModel)]="username">

Hello {{username}}!

and the second way is
<input [value]="username" (input)="username = $event.target.value">

Hello {{username}}!

[value]="username" - Binds the expression username to the input element's value property
(input)="expression" - Is a declarative way of binding an expression to the input element's input event (yes there's such event)
username = $event.target.value - The expression that gets executed when the input event is fired
$event - Is an expression exposed in event bindings by Angular, which has the value of the event's payload
Two-way Data Binding in Angular


text:
Q: Not able to update API method: PUT in a function update(). Not able to update all the attributes of a particular ID import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';

const RestaurantUpdate = () => {
const [state, setState] = useState({ name: '', email: '', address: '', rating: '' })
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [address, setAddress] = useState("");
const [rating, setRating] = useState("");
const { id } = useParams();

useEffect(() => {
    fetch('http://localhost:3000/restaurant/' + id).then((response) => {
        response.json().then((result) => {
            console.warn(result.name);
            setName(result.name);
            setEmail(result.email);
            setAddress(result.address);
            setRating(result.rating);
        })
    })
}, []);

function update() {
    fetch("http://localhost:3000/restaurant/" + id,
        {
            method: "PUT",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(state)
        }).then((result) => {
            result.json().then((resp) => {
                alert("Restaurant has been updated");
            })
        })
}
return (

Update

            <input onChange={(event) => setName(event.target.value)}
                placeholder="Restaurant Name" value={name} />

            <input onChange={(event) => setEmail(event.target.value)}
                placeholder="Restaurant Email" value={email} />

            <input onChange={(event) => setRating(event.target.value)}
                placeholder="Restaurant Rating" value={rating} />

            <input onChange={(event) => setAddress(event.target.value)}
                placeholder="Restaurant Address" value={address} />

            <button onClick={() => { update() }}>Update Restaurant</button>

);
};

export default RestaurantUpdate;

Want my API to get updated. But it is not working. Attributes of that particular id is getting blank. How to update all the data of that particular id in functional components?
Maybe I have some syntax error or is there any another alternative method?

A: You're updating the individual pieces of state (name, email, address, rating), but sending the big piece of state (state) with your API call. This piece of state is never updated in your component. It will always send your defualt values, which are empty strings for every property.
You could pass the individual pieces of state to the API call:
function update() {
    fetch("http://localhost:3000/restaurant/" + id,
        {
            method: "PUT",
            headers: {
                'Content-Type': 'application/json'
            },
            // use object property shorthand to avoid
            // syntax like { name: name, email: email ... }
            body: { name, email, address, rating }
        }).then((result) => {
            result.json().then((resp) => {
                alert("Restaurant has been updated");
            })
        })
}


text:
Q: Python crypt package: Can type extra characters in password I'm using Python's crypt package to persist encrypted passwords in a MySQL databse for a Django website. I'm not sure if this is a bug, but here's the code I'm using:
To encrypt/persist the password:
user.password = crypt(request.POST['password'], netid)
user.save()

To check for a correct password on login:
if crypt(password, email) == user.password:
# Grant acccess to the user's profile, etc.

The problem is the following. If I encrypt a password with variable netid = test@example.com and request.POST['password'] = 'ABC123abc', it works fine. However, when I try to login, if I use the password 'ABC123abc[trailing_chars]', where the trailing_chars can be any valid string, I am still able to log in. Why is this? It poses to be a large security hole as is.

A: First of all, you should not be using an email address as a salt (the second argument) for crypt. This is not secure. You MUST pick a good random salt.
For traditional crypt, the salt is a two-character string chosen from the set [a–zA–Z0–9./]. This version of crypt accepts only 8 input characters and discards all following characters from the input after the 8th. That is what you're seeing here.
Modern crypt implementations also support other algorithms that are cryptographically much stronger than traditional crypt but they are not available on all platforms. The new algorithms also don't limit the input to 8 characters.
To use one of these better algorithms (if you are using a platform that supports them), you need to supply a salt that is in a special format. This is how the function recognizes that you would like to use an alternate algorithm.
For the extra algorithms supported by glibc (and therefore available on GNU/Linux), consult the "Glibc Notes" section of the crypt manpage.
By the way, when checking the password, you don't need to manually extract the salt. The encrypted password already starts with the salt, so just pass user.password (not email) as the second argument to crypt. This works whether you are using the old algorithm or one of the new ones. The choice of algorithm and generation of a salt in the correct format need only be done when encrypting the password, not when verifying it.


text:
Q: How to Avoid this Out of Memory Error when Generating Multiple Strings? I'm working on a benchmarking task, and I need to generate millions of rows of event json.
Here is my sample code:
def generateEntry() = {
 s"""
    |{
    | "memberId": ${java.util.UUID.randomUUID.toString},
    | "first_name": ${nameRandomizer},
    | "last_name": ${nameRandomizer
    |}""".stripMargin
}

// Generate 1000000 rows of Json String with fields: memberId, first_name, last_name
val entryList = mutable.ListBuffer[String]()
for (_ <- 1 to 1000000) {
 entryList += generateEntry()
}

val inputRDD: RDD[String] = sc.parallelize(entryList.result())

However this is causing an error:
Java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:3332)
    at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:124)
    at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:448)
    at java.lang.StringBuilder.append(StringBuilder.java:136)
    at scala.StringContext.standardInterpolator(StringContext.scala:126)
    at scala.StringContext.s(StringContext.scala:95)

I am coding in spark by the way. I tried doing this by batch, but error still seem to occur. Please let me know, or provide sample code that I can use as a guide to fix this. Thanks!

A: List buffer is not needed. You can just map a Spark range to your function:
val inputRDD: RDD[String] = spark.range(1000000).rdd.map(x => generateEntry())


text:
Q: How to pass arguments in dockerfile during docker run command I am new in docker. For learning purpose, I'm working on code submission platform (online judge). So, I know at high level that whenever a user submit a code, it will hit an API which will receive code, languageID and inputs(if any), and this code will run on a docker container and return the output at the client side(or error if any).
Dockerfile :
FROM gcc:latest

COPY main.cpp /usr/src/cpp_test/prog.cpp

WORKDIR /usr/src/cpp_test/

CMD [ "sh", "-c", "g++ -o Test prog.cpp && ./Test" ]

So, whenever user submit a code, Everytime, I am first building this dockerfile(docker build) because main.cpp file will be different everytime and then running the docker run command.
So, my question is, Is there any way that I build this dockerfile only once(by making it more general) and now whenever a user submit a code, I just only need to run the docker run command.
Remember, there are 3 arguments that I have to pass ie., code, languageID, inputs(if any) to dockerfile.
Any help will be appreciated.
Thankyou.

A: First, looking at your existing Dockerfile: the output of docker build is an image containing a compiled, ready-to-run binary.  The image you have now contains a compiler plus a source file, but you'd generally have a compiled binary.  (If you're used to a compiler like g++, think of docker build as the same sort of sequence: it creates a directly runnable image and doesn't need copy of the source or to be rebuilt.)  So I'd typically RUN g++, not defer it until container startup:
FROM gcc:latest
WORKDIR /usr/src/cpp_test
COPY main.cpp .
RUN g++ -o Test main.cpp
CMD [ "./Test" ]

Even for the higher-level workflow you describe, I'm not sure I'd stray too far from this Dockerfile.  It doesn't do a whole lot beyond running the compiler and then creating a runnable image; so long as the source file is named main.cpp and it doesn't have any library dependencies this will work for any C++ source file.

If you really wanted to build and run an arbitrary source file without building an image per submission, you can use the unmodified gcc image here; you don't need a custom image since it won't really do anything.  I'd suggest writing a launcher shell script:
#!/bin/sh
set -e
g++ -o Test main.cpp
./Test

Create an execution directory:
mkdir run_1
cp -a launcher.sh run_1
cp submission_1.cpp run_1/main.cpp

Then run the container against that tree:
docker run --rm \
  -v "$PWD/run_1:/code" \
  -w /code \
  gcc:latest \
  ./launcher.sh


text:
Q: Cx_Oracle : DatabaseError: ORA-28040: No matching authentication protocol I am facing this error while using Cx_Oracle package in python environment. I upgraded to oracle 12c from 11g but it still gets me this error. Also, I am using ojdbc6.jar.
DatabaseError: ORA-28040: No matching authentication protocol

A: ojdbc6.jar is driver for JVM/Java
Cx_Oracle is C/C++ library depending on libclnth.so library.
The errors states that your client is either to old (or too new) and you can not authenticate to the database. There is no auth protocol that both sides implement/accept.
Either you should upgrade your client or change
sqlnet.ora set SQLNET.ALLOWED_LOGON_VERSION to version of your client library.

A: From 12c onward, minimum supported version default has changed from 11 to 12 and SQLNET.ALLOWED_LOGON_VERSION is now replaced with the SQLNET.ALLOWED_LOGON_VERSION_SERVER and SQLNET.ALLOWED_LOGON_VERSION_CLIENT parameters
You need to add these two parameters in your sqlnet.ora file, you can find that file at
ORACLE_HOME/network/admin/
After you made the changed, do not forget to reload the listener using lsnrctl reload
For more see Oracle Official Doc

A: This helped me while using cx-Oracle 8.0.1
add in sqlnet.ora
SQLNET.ALLOWED_LOGON_VERSION_SERVER=11

The error disapears, but I got instead
ORA-01017: Invalid Username/Password

The workaround was to change the password:
alter user UUUUU identified by PWD;

After this the user PASSWORD_VERSIONS  were set from 10 to 12 and everything worked fine!
select PASSWORD_VERSIONS  from dba_users where username = 'UUUUU';

PASSWORD_VERSIONS
-----------------
10G 11G 12C


text:
Q: Extract all text from specific
* within a parent container with multiple dynamic child using puppeteer and cheerio I want to extract the texts from
 elements using puppeteer and cheerio. My problem is that there is no classes on
 elements and the count of
 element varies each time based on search, so I could not use nth-child. I have tried every possible way as far as I know, but couldn't get the desired results. Is there any way around. I have this structure and classes only available with the parent element:

Description:

Some text

Features

lines

lines

            ....

Includes

lines

lines

            ....

Titles:

lines

lines

            ....

Here is what I have tried so far:
in the helper.js.
const browser = await puppeteer.launch({
            timeout: 0,
            headless: false,
            ignoreHTTPSErrors: true,
            ignoreHTTPErrors: true,
            args: ["--start-maximized", "--no-sandbox", "--disable-setuid-sandbox"],
            ignoreDefaultArgs: ["--disable-extensions", "--enable-automation"],
            slowMo: 200,
          });
let skus='sdfh65asdchv'
let arr = await scrapeUl(page, skus);
            await sleep(3000);

            await page.close();

In scrapeUl I have:
const scrapeUl = async (page, singleSku) => {
  await page.goto("https://myweb.com", { waitUntil: "networkidle2" });
  await page.waitForXPath('//*[@id="parent-container-id"]/section/header/div/div/div[1]/form/div[1]/div/div');
  let [Input] = await page.$x('//*[@id="parent-container-id"]/section/header/div/div/div[1]/form/div[1]/div/div/input');
  await Input.type(singleSku);
  let [SearchBtn] = await page.$x('//*[@id="parent-container-id"]/section/header/div/div/div[1]/form/div[1]/div/button');
  await Promise.all([
      page.waitForNavigation({waitUntil: "domcontentloaded"}),
      page.keyboard.press("Enter"),
    ]);

    /* I want to scrape specification part of
 which can be any of the
 element, and it dynamically changes
        Sometimes it scrape but sometimes it skips since number of child changes in the parent container
        as one can see there are no classes or ids attached to
 element, this makes harder for me to select this element
    */
    const specifications = await page.$eval('div.card__section > div > ul:nth-child(8)', (el) => el.innerText);

  };

Thanks in advance.

A: -- a section of your HTML--

lines

lines

         ....

--In JavaScript---

You can add an "id" to the
 you want to pull, add a script function that returns document.getElementById("<ID NAME>").innerHTML
Here, innerHTML pulls the string of the
 not the object itself. you can assign a variable (maybe in this case an array) to store the strings of the
 to manipulate further. Here I have it just displaying it as an alert so you can see what it returns. In this case- it returns "lines, lines ...." in the alert.