Thursday, March 1, 2018

java - Best way to convert an ArrayList to a string





I have an ArrayList that I want to output completely as a String. Essentially I want to output it in order using the toString of each element separated by tabs. Is there any fast way to do this? You could loop through it (or remove each element) and concatenate it to a String but I think this will be very slow.


Answer



Basically, using a loop to iterate over the ArrayList is the only option:



DO NOT use this code, continue reading to the bottom of this answer to see why it is not desirable, and which code should be used instead:



ArrayList list = new ArrayList();

list.add("one");
list.add("two");
list.add("three");

String listString = "";

for (String s : list)
{
listString += s + "\t";
}


System.out.println(listString);


In fact, a string concatenation is going to be just fine, as the javac compiler will optimize the string concatenation as a series of append operations on a StringBuilder anyway. Here's a part of the disassembly of the bytecode from the for loop from the above program:



   61:  new #13; //class java/lang/StringBuilder
64: dup
65: invokespecial #14; //Method java/lang/StringBuilder."":()V
68: aload_2

69: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
72: aload 4
74: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
77: ldc #16; //String \t
79: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
82: invokevirtual #17; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;


As can be seen, the compiler optimizes that loop by using a StringBuilder, so performance shouldn't be a big concern.




(OK, on second glance, the StringBuilder is being instantiated on each iteration of the loop, so it may not be the most efficient bytecode. Instantiating and using an explicit StringBuilder would probably yield better performance.)



In fact, I think that having any sort of output (be it to disk or to the screen) will be at least an order of a magnitude slower than having to worry about the performance of string concatenations.



Edit: As pointed out in the comments, the above compiler optimization is indeed creating a new instance of StringBuilder on each iteration. (Which I have noted previously.)



The most optimized technique to use will be the response by Paul Tomblin, as it only instantiates a single StringBuilder object outside of the for loop.



Rewriting to the above code to:




ArrayList list = new ArrayList();
list.add("one");
list.add("two");
list.add("three");

StringBuilder sb = new StringBuilder();
for (String s : list)
{
sb.append(s);
sb.append("\t");

}

System.out.println(sb.toString());


Will only instantiate the StringBuilder once outside of the loop, and only make the two calls to the append method inside the loop, as evidenced in this bytecode (which shows the instantiation of StringBuilder and the loop):



   // Instantiation of the StringBuilder outside loop:
33: new #8; //class java/lang/StringBuilder
36: dup

37: invokespecial #9; //Method java/lang/StringBuilder."":()V
40: astore_2

// [snip a few lines for initializing the loop]
// Loading the StringBuilder inside the loop, then append:
66: aload_2
67: aload 4
69: invokevirtual #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
72: pop
73: aload_2

74: ldc #15; //String \t
76: invokevirtual #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
79: pop


So, indeed the hand optimization should be better performing, as the inside of the for loop is shorter and there is no need to instantiate a StringBuilder on each iteration.


c# - In .NET, which loop runs faster, 'for' or 'foreach'?



In C#/VB.NET/.NET, which loop runs faster, for or foreach?



Ever since I read that a for loop works faster than a foreach loop a long time ago I assumed it stood true for all collections, generic collections, all arrays, etc.




I scoured Google and found a few articles, but most of them are inconclusive (read comments on the articles) and open ended.



What would be ideal is to have each scenario listed and the best solution for the same.



For example (just an example of how it should be):




  1. for iterating an array of 1000+
    strings - for is better than foreach

  2. for iterating over IList (non generic) strings - foreach is better

    than for



A few references found on the web for the same:




  1. Original grand old article by Emmanuel Schanzer

  2. CodeProject FOREACH Vs. FOR

  3. Blog - To foreach or not to foreach, that is the question

  4. ASP.NET forum - NET 1.1 C# for vs foreach






[Edit]



Apart from the readability aspect of it, I am really interested in facts and figures. There are applications where the last mile of performance optimization squeezed do matter.


Answer



Patrick Smacchia blogged about this last month, with the following conclusions:






  • for loops on List are a bit more than 2 times cheaper than foreach
    loops on List.

  • Looping on array is around 2 times cheaper than looping on List.

  • As a consequence, looping on array using for is 5 times cheaper
    than looping on List using foreach
    (which I believe, is what we all do).




PHP parse HTML tags





Possible Duplicate:
How to parse and process HTML with PHP?






I'm pretty new to PHP.
I have the text of a body tag of some page in a string variable.

I'd like to know if it contains some tag ... where the tag name tag1 is given, and if so, take only that tag from the string.
How can I do that simply in PHP?



Thanks!!


Answer



You would be looking at something like this:



$content = "";
$doc = new DOMDocument();

$doc->load("example.html");
$items = $doc->getElementsByTagName('tag1');
if(count($items) > 0) //Only if tag1 items are found
{
foreach ($items as $tag1)
{
// Do something with $tag1->nodeValue and save your modifications
$content .= $tag1->nodeValue;
}
}

else
{
$content = $doc->saveHTML();
}
echo $content;
?>


DomDocument represents an entire HTML or XML document; serves as the root of the document tree. So you will have a valid markup, and by finding elements By Tag Name you won't find comments.


plot explanation - Where did Hollowface come from, and how was he defeated in Intruders?

I found Intruders to be a rather confusing, and intellectually unsatisfying film. I felt it left too many questions unanswered. Or maybe I just didn't catch the answers--which could well be the case, considering I watched it in Mexico, where the Spanish scenes were not subtitled. And although I do speak some Spanish, I didn't understand all of the Spanish-language dialog in the film.


What was the origin of Hollowface, and how was he finally defeated?


My best understanding of his defeat was that by sheer will power and/or knowledge of his nature, his power to frighten was lost. Is this much accurate?


Answer


The movie opens with a young boy, Juan, in Spain having nightmares about
Hollowface, a monster with no face. The plot then moves to England, following John and his family.


It shows two parallel stories with a connection;Juan is actually John (Mia's father).


At the end, John realizes his Hollowface connection with his daughter. Hollowface is disguised as a monster to suppress post traumatic stress.


John's mom relocated to England to escape the death of Juan's father in Spain. John's biological father is Hollowface, who he created as the young Juan through storytelling. Mia and John shared a psychic connection, so Hollowface is a fabricated spirit.


John's biological father who was released from jail attempted to abduct him. As a result, Juan and the mom watch the father fall off the ledge and into cement/soil. The mom refused to confess to the priest about the traumatic event that caused Juan nightmares.


Original synopsis found at Twist Endings.


Excel VBA: Get Last Cell Containing Data within Selected Range

using Find like below is useful as it




  • can find the last (or first) cell in a 2D range immediately

  • testing for Nothing identifies a blank range

  • will work on a range that may not be contiguous (ie a SpecialCells range)




change "YourSheet" to the name of the sheet you are searching



Sub Method2()
Dim ws As Worksheet
Dim rng1 As Range
Set ws = Sheets("YourSheet")
Set rng1 = ws.Columns("A:B").Find("*", ws.[a1], xlValues, , xlByRows, xlPrevious)
If Not rng1 Is Nothing Then

MsgBox "last cell is " & rng1.Address(0, 0)
Else
MsgBox ws.Name & " columns A:B are empty", vbCritical
End If
End Sub

c# - Automatically exit generated Excel file correctly

My program generates an Excel in a loop and sends it by Email. In each loop iteration it should overwrite the Excel, but the Excel is still used by the old Excel process which is why I get a System.IO.IOException exception.


Here is the process:


enter image description here


Here is the Code:


if(File.Exists(PfadXlsx)) File.Delete(PfadXlsx);
mExcel.Visible = true;
mExcelWs.SaveAs(PfadXlsx, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, missing, missing, false, false, false, missing, missing, missing); // Datei speichern
mExcelWb.Close(true, missing, missing);
mExcel.Application.Quit();
mExcel.Quit();


mExcel == Excel.Application mExcelWB == Excel.Workbook
mExcel==Excel.Worksheet missing == type.missing


How to find out the starting point for each match in ruby




Say, i have a following string



string = "#Sachin is Indian cricketer. #Tendulkar is right hand batsman. #Sachin has been honoured with the Padma Vibhushan award "


I want o/p as



"#Sachin|0|7;#Tendulkar|29|10;#Sachinn|63|7;"



I tried following



 new_string = ""
string.scan(/#\S+/).each{|match| new_string+="#{match}|#{string.index(match)}|#{match.length};" }


which gives me



 "#Sachin|0|7;#Tendulkar|29|10;#Sachin|0|7;" 



So how i will get the starting index of each sub-string?


Answer



This is actually quite a non-trivial task, and has been discussed quite a bit in other questions on SO. This is the most common solution:



string = "#Sachin is Indian cricketer. #Tendulkar is right hand batsman. #Sachin has been honoured with the Padma Vibhushan award "
new_string = string.to_enum(:scan,/#\S+/i).inject(''){|s,m| s + "#{m}|#{$`.size}|#{m.length};"}

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...