Friday, May 31, 2019

Java String - 1 is not 1?

I'm a c++ programmer who wrote some php server code to be translated to java and pretty new to Java. But it feels quite common coming from c++.
I have a server up and running and this code:


String req = "1";
Document doc = loadXMLFromString (req);
Element root = doc.getDocumentElement(); // "xml"
// check version
Element e = firstChildElement (root, "version");
String result = e.getTextContent(); // returns "1"!
String expected = "1";
if (result != expected)
{
out.printLn ("wrong version: (" + result + "), expected: (" + expected + ")!");
return;
}

This prints "wrong version: (1), expected (1)". The same holds with if (result != "1").
Now even the debugger (eclipse) shows that result is actually "1", so I'm truly lost here.
I seem to be missing the obvious but just can't see it...can you help pls? Thanks!

c++ - Why does returning a floating-point value change its value?



The following code raises the assert on Red Hat 5.4 32 bits but works on Red Hat 5.4 64 bits (or CentOS).



On 32 bits, I must put the return value of millis2seconds in a variable, otherwise the assert is raised, showing that the value of the double returned from the function is different from the one that was passed to it.




If you comment the "#define BUG" line, it works.



Thanks to @R, passing the -msse2 -mfpmath options to the compiler make both variants of the millis2seconds function work.



/*
* TestDouble.cpp
*/

#include
#include

#include

static double millis2seconds(int millis) {
#define BUG
#ifdef BUG
// following is not working on 32 bits architectures for any values of millis
// on 64 bits architecture, it works
return (double)(millis) / 1000.0;
#else
// on 32 bits architectures, we must do the operation in 2 steps ?!? ...

// 1- compute a result in a local variable, and 2- return the local variable
// why? somebody can explains?
double result = (double)(millis) / 1000.0;
return result;
#endif
}

static void testMillis2seconds() {
int millis = 10;
double seconds = millis2seconds(millis);


printf("millis : %d\n", millis);
printf("seconds : %f\n", seconds);
printf("millis2seconds(millis) : %f\n", millis2seconds(millis));
printf("seconds < millis2seconds(millis) : %d\n", seconds < millis2seconds(millis));
printf("seconds > millis2seconds(millis) : %d\n", seconds > millis2seconds(millis));
printf("seconds == millis2seconds(millis) : %d\n", seconds == millis2seconds(millis));

assert(seconds == millis2seconds(millis));
}


extern int main(int argc, char **argv) {
testMillis2seconds();
}

Answer



With the cdecl calling convention, which is used on Linux x86 systems, a double is returned from a function using the st0 x87 register. All x87 registers are 80-bit precision. With this code:



static double millis2seconds(int millis) {
return (double)(millis) / 1000.0;

};


The compiler calculates the division using 80-bit precision. When gcc is using the GNU dialect of the standard (which it does by default), it leaves the result in the st0 register, so the full precision is returned back to the caller. The end of the assembly code looks like this:



fdivrp  %st, %st(1)  # Divide st0 by st1 and store the result in st0
leave
ret # Return



With this code,



static double millis2seconds(int millis) {
double result = (double)(millis) / 1000.0;
return result;
}


the result is stored into a 64-bit memory location, which loses some precision. The 64-bit value is loaded back into the 80-bit st0 register before returning, but the damage is already done:




fdivrp  %st, %st(1)   # Divide st0 by st1 and store the result in st0
fstpl -8(%ebp) # Store st0 onto the stack
fldl -8(%ebp) # Load st0 back from the stack
leave
ret # Return


In your main, the first result is stored in a 64-bit memory location, so the extra precision is lost either way:



double seconds = millis2seconds(millis);



but in the second call, the return value is used directly, so the compiler can keep it in a register:



assert(seconds == millis2seconds(millis));


When using the first version of millis2seconds, you end up comparing the value that has been truncated to 64-bit precision to the value with full 80-bit precision, so there is a difference.



On x86-64, calculations are done using SSE registers, which are only 64-bit, so this issue doesn't come up.




Also, if you use -std=c99 so that you don't get the GNU dialect, the calculated values are stored in memory and re-loaded into the register before returning so as to be standard-conforming.


.net - Regular expression for parsing links from a webpage?



I'm looking for a .NET regular expression extract all the URLs from a webpage but haven't found one to be comprehensive enough to cover all the different ways you can specify a link.



And a side question:



Is there one regex to rule them all? Or am I better off using a series of less complicated regular expressions and just using mutliple passes against the raw HTML? (Speed vs. Maintainability)



Answer



((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)


I took this from regexlib.com



[editor's note: the {1} has no real function in this regex; see this post]


bash - In the shell, what does " 2>&1 " mean?



In a Unix shell, if I want to combine stderr and stdout into the stdout stream for further manipulation, I can append the following on the end of my command:



2>&1


So, if I want to use head on the output from g++, I can do something like this:




g++ lots_of_errors 2>&1 | head


so I can see only the first few errors.



I always have trouble remembering this, and I constantly have to go look it up, and it is mainly because I don't fully understand the syntax of this particular trick.



Can someone break this up and explain character by character what 2>&1 means?


Answer




File descriptor 1 is the standard output (stdout).
File descriptor 2 is the standard error (stderr).



Here is one way to remember this construct (although it is not entirely accurate): at first, 2>1 may look like a good way to redirect stderr to stdout. However, it will actually be interpreted as "redirect stderr to a file named 1". & indicates that what follows is a file descriptor and not a filename. So the construct becomes: 2>&1.


php - How to delete an array element based on key?






Possible Duplicate:
How to delete an element from an array in php?






For instance,




Array(      
[0] => Array
(
[0] => hello
[1] => open
)

[1] => Array
(

[0] => good
[1] => center
)

[2] => Array
(
[0] => hello
[1] => close
)
)



I want to delete the element which key is 1, after the operation:



Array(
[0] => Array
(
[0] => hello
[1] => open
)


[2] => Array
(
[0] => hello
[1] => close
)
)

Answer



PHP




unset($array[1]);

r - How to create pair-wise data.frame



I have a data.frame with sample data from multiple sites and years. I would like to create a new "pairwise" data.frame that takes creates three columns, Site_Year, Value_2008, Value_Year, where Value_Year is the value for any other year in the dataset. For example, in my sample dataset the site "Anjan" is visited in 2008, 2009, 2010. The new data.frame to have two records for this site:




Site_Year Value_2008 Value_Year
Anjan.2009 0.11 0.96
Anjan.2010 0.11 -0.25


If there is a site that was sampled before 2008 the results would look like:



Site_Year Value_2008 Value_Year
Ljungdalen.2005 0.09 -0.40

Ljungdalen.2009 0.09 0.32
Ljungdalen.2011 0.09 -0.00


Ultimately, I am going to plot these results so that I can look at changes in these (mean) values between years and test them to see if they are significantly different.



Sample data:



WW_Site_Year_Data <- structure(list(Site_Year = c("Anjan.2008", "Anjan.2009", "Anjan.2010",
"Fittjebodarna.2008", "Fittjebodarna.2009", "Flatruet.2008",

"Flatruet.2009", "Flatruet.2010", "Flatruet.2011", "Fotingen.2008",
"Fotingen.2009", "Gestvallen.2008", "Gestvallen.2009", "Glen.2008",
"Glen.2009", "Glen.2010", "Gräftåvallen.2008", "Gräftåvallen.2009",
"Hallbodarna.2008", "Hallbodarna.2009", "Ljungdalen.2005", "Ljungdalen.2008",
"Ljungdalen.2009", "Ljungdalen.2011", "Ljungris.2008", "Ljungris.2009",
"Ljungris.2010", "Mårdsund.2008", "Mårdsund.2009", "Mårdsund.2010",
"Öster_Galåbodarna.2008", "Öster_Galåbodarna.2009", "Ramundberget.2008",
"Ramundberget.2009", "Rätan.2008", "Rätan.2009", "Rätan.2010",
"Särvfjället.2008", "Särvfjället.2009", "Storulvån.2008", "Storulvån.2009",
"Storulvån.2010", "Tångböle.2005", "Tångböle.2008", "Tångböle.2009",

"Tossåsen.2008", "Tossåsen.2009", "Vålådalen.2008", "Vålådalen.2009",
"Vålådalen.2010", "Vemdalsskalet.2002", "Vemdalsskalet.2008",
"Vemdalsskalet.2009"), Site_Name = c("Anjan", "Anjan", "Anjan",
"Fittjebodarna", "Fittjebodarna", "Flatruet", "Flatruet", "Flatruet",
"Flatruet", "Fotingen", "Fotingen", "Gestvallen", "Gestvallen",
"Glen", "Glen", "Glen", "Gräftåvallen", "Gräftåvallen", "Hallbodarna",
"Hallbodarna", "Ljungdalen", "Ljungdalen", "Ljungdalen", "Ljungdalen",
"Ljungris", "Ljungris", "Ljungris", "Mårdsund", "Mårdsund", "Mårdsund",
"Öster_Galåbodarna", "Öster_Galåbodarna", "Ramundberget", "Ramundberget",
"Rätan", "Rätan", "Rätan", "Särvfjället", "Särvfjället", "Storulvån",

"Storulvån", "Storulvån", "Tångböle", "Tångböle", "Tångböle",
"Tossåsen", "Tossåsen", "Vålådalen", "Vålådalen", "Vålådalen",
"Vemdalsskalet", "Vemdalsskalet", "Vemdalsskalet"), Year = c("2008",
"2009", "2010", "2008", "2009", "2008", "2009", "2010", "2011",
"2008", "2009", "2008", "2009", "2008", "2009", "2010", "2008",
"2009", "2008", "2009", "2005", "2008", "2009", "2011", "2008",
"2009", "2010", "2008", "2009", "2010", "2008", "2009", "2008",
"2009", "2008", "2009", "2010", "2008", "2009", "2008", "2009",
"2010", "2005", "2008", "2009", "2008", "2009", "2008", "2009",
"2010", "2002", "2008", "2009"), Value = c(0.112816109860291,

0.960290707474735, -0.257326331130005, 0.216427465038733, 0.956767099330118,
0.0526510364211729, 0.588996350906268, -0.465285757216318, -0.0437472490447301,
0.535560060909972, 0.389645985829418, 0.89391173396597, 0.240894790643034,
0.469695915206932, 0.251017199176266, -0.208323019946377, 0.0849050148677196,
0.184296870311739, -0.107309010266098, 0.36349491505071, -0.396608387512831,
0.0931374765423872, 0.32514153209616, -0.00466699456138238, 0.336789804880864,
0.806764888899387, -0.13955949253251, 0.108716189818012, 0.0978498660969545,
-0.160915801270199, 0.623151244760041, 0.713080174849265, -0.279733235253308,
0.427277452192635, 0.296839613563375, 0.659552054627706, 0.356154916318252,
0.659219370597927, 0.825734934055685, 0.183577169158829, 1.31979282562961,

0.0574714990570691, -0.517636804796056, 0.478950613513035, 0.504156229919797,
0.915335741962761, 1.11129338570452, 0.205145037964442, 0.829430613619136,
-0.187573312149385, -0.646545555669656, -0.034670665219269, 1.68156971430668
)), .Names = c("Site_Year", "Site_Name", "Year", "Value"), row.names = c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L,
16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L,
29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L,
42L, 43L, 44L, 45L, 48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L), class = "data.frame")

Answer




A very useful package in this situation is plyr:



ddply(WW_Site_Year_Data, .(Site_Name), transform,
Value_2008 = if (2008 %in% Year) Value[Year==2008] else NA)


If records with no Value for 2008 are excluded from the data frame you could use



ddply(WW_Site_Year_Data, .(Site_Name), transform,
Value_2008 = Value[Year==2008])



It you want to use base R, it's uglier:



unsplit(lapply(split(WW_Site_Year_Data, WW_Site_Year_Data$Site_Name),
transform, Value_2008 = if (2008 %in% Year) Value[Year==2008] else NA),
WW_Site_Year_Data$Site_Name)

javascript - Why console.log((!+[]+[]+![]).length) gives 9?

Answer


Answer





By what logic js works (!+[]+[]+![]).length returns 9? How is that possible?

As I know js has dynamic types cast but very hard to understand whats going on here





console.log((!+[]+[]+![]).length);




Answer



First we have to understand !+[]+[]+![]:




!+[] = !0 = true   
true+[] = "true"
![] = false
"true"+false = "truefalse"


so length of !+[]+[]+![] is length of "truefalse" so it's 9


React Native/Javascript - How to know that object does not have the property?

Let say :



myVariable.color;
myVariable.height;
myVariable.width;


But sometimes, myVariable only have "color" and "height" property.



I have try this, but no luck :




if(myVariable.width == undefined) {
//but not filtered here
}


How to know if myVariable doesn't contain "width" property by code, is it possible ?

What does [:-1] mean/do in python?




Working on a python assignment and was curious as to what [:-1] means in the context of the following code: instructions = f.readline()[:-1]



Have searched on here on S.O. and on Google but to no avail. Would love an explanation!


Answer



It slices the string to omit the last character, in this case a newline character:



>>> 'test\n'[:-1]
'test'



Since this works even on empty strings, it's a pretty safe way of removing that last character, if present:



>>> ''[:-1]
''


This works on any sequence, not just strings.




For lines in a text file, I’d actually use line.rstrip('\n') to only remove a newline; sometimes the last line in the file doesn’t end in a newline character and using slicing then removes whatever other character is last on that line.


Cant connect my database with php




$con = mysqli_connect("localhost" "root" "") or die("Unable to connect");
mysqli_select_db("logindb", $con);

?>


This is the configuration of the connecting.



require 'config.php';
?>



This is where is connect the database to a registration page.



Can you see something wrong? This is the error i get:
Parse error: syntax error, unexpected '"root"' (T_CONSTANT_ENCAPSED_STRING)



Thanks,
Realcookie


Answer



You are missing the commas bro. Here is the corrected one




$con = mysqli_connect("localhost", "root", "") or die("Unable to connect");
mysqli_select_db($con, 'logindb');
?>

What is the yield keyword used for in C#?



In the How Can I Expose Only a Fragment of IList<> question one of the answers had the following code snippet:



IEnumerable FilteredList()
{
foreach(object item in FullList)

{
if(IsItemInPartialList(item))
yield return item;
}
}


What does the yield keyword do there? I've seen it referenced in a couple places, and one other question, but I haven't quite figured out what it actually does. I'm used to thinking of yield in the sense of one thread yielding to another, but that doesn't seem relevant here.


Answer



The yield keyword actually does quite a lot here.




The function returns an object that implements the IEnumerable interface. If a calling function starts foreaching over this object, the function is called again until it "yields". This is syntactic sugar introduced in C# 2.0. In earlier versions you had to create your own IEnumerable and IEnumerator objects to do stuff like this.



The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:



public void Consumer()
{
foreach(int i in Integers())
{
Console.WriteLine(i.ToString());

}
}

public IEnumerable Integers()
{
yield return 1;
yield return 2;
yield return 4;
yield return 8;
yield return 16;

yield return 16777216;
}


When you step through the example, you'll find the first call to Integers() returns 1. The second call returns 2 and the line yield return 1 is not executed again.



Here is a real-life example:



public IEnumerable Read(string sql, Func make, params object[] parms)
{

using (var connection = CreateConnection())
{
using (var command = CreateCommand(CommandType.Text, sql, connection, parms))
{
command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return make(reader);

}
}
}
}
}

sql server - How do I generate random number for each row in a TSQL Select?




I need a different random number for each row in my table. The following seemingly obvious code uses the same random value for each row.



SELECT table_name, RAND() magic_number 
FROM information_schema.tables


I'd like to get an INT or a FLOAT out of this. The rest of the story is I'm going to use this random number to create a random date offset from a known date, e.g. 1-14 days offset from a start date.



This is for Microsoft SQL Server 2000.


Answer




Take a look at SQL Server - Set based random numbers which has a very detailed explanation.



To summarize, the following code generates a random number between 0 and 13 inclusive with a normalized distribution:



ABS(CHECKSUM(NewId())) % 14


To change your range, just change the number at the end of the expression. Be extra careful if you need a range that includes both positive and negative numbers. If you do it wrong, it's possible to double-count the number 0.



A small warning for the math nuts in the room: there is a very slight bias in this code. CHECKSUM() results in numbers that are uniform across the entire range of the sql Int datatype, or at least as near so as my (the editor) testing can show. However, there will be some bias when CHECKSUM() produces a number at the very top end of that range. Any time you get a number between the maximum possible integer and the last exact multiple of the size of your desired range (14 in this case) before that maximum integer, those results are favored over the remaining portion of your range that cannot be produced from that last multiple of 14.




As an example, imagine the entire range of the Int type is only 19. 19 is the largest possible integer you can hold. When CHECKSUM() results in 14-19, these correspond to results 0-5. Those numbers would be heavily favored over 6-13, because CHECKSUM() is twice as likely to generate them. It's easier to demonstrate this visually. Below is the entire possible set of results for our imaginary integer range:




Checksum Integer: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Range Result: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 0 1 2 3 4 5


You can see here that there are more chances to produce some numbers than others: bias. Thankfully, the actual range of the Int type is much larger... so much so that in most cases the bias is nearly undetectable. However, it is something to be aware of if you ever find yourself doing this for serious security code.


javascript - Save local image or image path in local storage?



I'm working on a bookmarklet (Javascript that is triggered from a bookmark) that overlays an image over a webpage in order to check if the html is consistent with the design. (it uses opacity)



I want to save the reference-image on a per-url-basis. I have three options as far as I know:




  • save the path in a cookie

  • save the path in local storage

  • save the image in local storage



I'm currently planning to use local-storage to save the image. The pros are that It works een if the original image is removed and it syncs between diffrent computers in chrome. I don't know of any cons. I don't need pixel-perfection in IE7, so browser support is fine.



What is the best approach?


Answer



Sure, you can save images and/or the url to localStorage.



However, since localStorage only takes string you need to first convert the image to data-url either by serving the image as such from the server, or convert the image by the use of canvas (note that canvas can normally only set images from same origin, and of course canvas is not available in IE7 without a polyfill).



A better approach is perhaps to use indexedDB or the new File API (currently poorly supported, so far only Chrome) which allow you to request large storage space and it can save the image directly (as a Blob).



The images will be stored as you serve them (unless you rescale and re-compress using jpeg in canvas) so pixelation or quality reduction shouldn't be an issue.



IE7 does not support localStorage so you would need to revert to UserData (limited to 4 mb IIRC) or cookies with the url instead, in this case.



Though -



If it's not that important to keep the original image locally I would rather suggest to serve the image with a late expire data in its header.



This way it stays in the cache until the user deletes it or it expires. It you have restriction on traffic to your server then localStorage/indexedDB is probably a better option.


Understanding checked vs unchecked exceptions in Java




Joshua Bloch in "Effective Java" said that




Use checked exceptions for
recoverable conditions and runtime
exceptions for programming errors
(Item 58 in 2nd edition)





Let's see if I understand this correctly.



Here is my understanding of a checked exception:



try{
String userInput = //read in user input
Long id = Long.parseLong(userInput);
}catch(NumberFormatException e){
id = 0; //recover the situation by setting the id to 0
}



1. Is the above considered a checked exception?



2. Is RuntimeException an unchecked exception?



Here is my understanding of an unchecked exception:



try{
File file = new File("my/file/path");

FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){

//3. What should I do here?
//Should I "throw new FileNotFoundException("File not found");"?
//Should I log?
//Or should I System.exit(0);?
}



4. Now, couldn't the above code also be a checked exception? I can try to recover the situation like this? Can I? (Note: my 3rd question is inside the catch above)



try{
String filePath = //read in from user input file path
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
//Kindly prompt the user an error message
//Somehow ask the user to re-enter the file path.
}



5. Why do people do this?



public void someMethod throws Exception{

}


Why do they let the exception bubble up? Isn't handling the error sooner better? Why bubble up?




6. Should I bubble up the exact exception or mask it using Exception?



Below are my readings



In Java, when should I create a checked exception, and when should it be a runtime exception?



When to choose checked and unchecked exceptions


Answer



Many people say that checked exceptions (i.e. these that you should explicitly catch or rethrow) should not be used at all. They were eliminated in C# for example, and most languages don't have them. So you can always throw a subclass of RuntimeException (unchecked exception)




However, I think checked exceptions are useful - they are used when you want to force the user of your API to think how to handle the exceptional situation (if it is recoverable). It's just that checked exceptions are overused in the Java platform, which makes people hate them.



Here's my extended view on the topic.



As for the particular questions:




  1. Is the NumberFormatException consider a checked exception?
    No. NumberFormatException is unchecked (= is subclass of RuntimeException). Why? I don't know. (but there should have been a method isValidInteger(..))


  2. Is RuntimeException an unchecked exception?
    Yes, exactly.



  3. What should I do here?
    It depends on where this code is and what you want to happen. If it is in the UI layer - catch it and show a warning; if it's in the service layer - don't catch it at all - let it bubble. Just don't swallow the exception. If an exception occurs in most of the cases you should choose one of these:




    • log it and return

    • rethrow it (declare it to be thrown by the method)

    • construct a new exception by passing the current one in constructor


  4. Now, couldn't the above code also be a checked exception? I can try to recover the situation like this? Can I?
    It could've been. But nothing stops you from catching the unchecked exception as well


  5. Why do people add class Exception in the throws clause?
    Most often because people are lazy to consider what to catch and what to rethrow. Throwing Exception is a bad practice and should be avoided.





Alas, there is no single rule to let you determine when to catch, when to rethrow, when to use checked and when to use unchecked exceptions. I agree this causes much confusion and a lot of bad code. The general principle is stated by Bloch (you quoted a part of it). And the general principle is to rethrow an exception to the layer where you can handle it.


javascript - How do I add a class to a given element?



I have an element that already has a class:









Now I want to create a JavaScript function that will add a class to the div (not replace, but add).



How can I do that?


Answer






Add a space plus the name of your new class to the className property of the element. First, put an id on the element so you can easily get a reference.








Then



var d = document.getElementById("div1");

d.className += " otherclass";


Note the space before otherclass. It's important to include the space otherwise it compromises existing classes that come before it in the class list.



See also element.className on MDN.





Use element.classList.add to add a class:




element.classList.add("my-class");


And element.classList.remove to remove a class:



element.classList.remove("my-class");

html - How do I vertically center text with CSS?

I have a div element which contains text, and I want to align the contents of this div vertically center.



Here is my div style:






#box {
height: 170px;
width: 270px;
background: #000;
font-size: 48px;
color: #FFF;
text-align: center;

}


Lorem ipsum dolor sit





What is the best way to do this?

Thursday, May 30, 2019

c - feof(in) != EOF doesn't make while loop stop when at the end of file?

Answer


Answer





int main ()

{
FILE *in;
in = fopen("input.txt","r");
char c = fgetc(in);
while(feof(in) != EOF)
{
printf("%c",c);
c = fgetc(in);
}
}



feof(in) != EOF doesn't stop the while loop from stopping but something like !feof(in) seems to work. Any ideas?


Answer



feof doesn't return EOF on end of file; it returns true, which is not equal to EOF.



fgetc will return EOF when it hits end-of-file. Your code should be written as



int main ()
{

FILE *in;
in = fopen("input.txt","r");
int c = fgetc(in); // note int not char
while(c != EOF) // compare c to EOF
{
printf("%c",c);
c = fgetc(in);
}
}



You should not use feof as a loop condition, as it won't return true until after you attempt to read past the end of the file, meaning your loop will execute once too often.


php - Syntax error unexpected T_CONSTANT_ENCAPSED_STRING





I am getting the following error syntax error, unexpected T_CONSTANT_ENCAPSED_STRING on this line $this->email->subject($this->core_model->companyDetails()->coreCompanyName 'User Registration Confirmation'); have I make a mistake with the '' and ""? I have also past the name as $data can I include this in the subject instead of the model call?


Answer



You probably forgot a comma: Try this:



$this->email->subject($this->core_model->companyDetails()->coreCompanyName, 'User Registration Confirmation');


instead of



$this->email->subject($this->core_model->companyDetails()->coreCompanyName 'User Registration Confirmation');


objective c - Delegation and retrieving info on IOS



I'm trying to get heading info from CLLocationManager but it's not getting called. I did everything as the documentation says, but something is very wrong.
I'm using locationManager delegating into my app delegate.



Here is the method to retrieve heading messages:




  - (void) locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
NSLog(@"%@", newHeading);
}


Here is the part from main()



  locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];

[locationManager startUpdatingHeading];


But nothing happens! With debugging, NSLog is never getting called.
When I do same with [locationManager startUpdatingLocation] everything works fine, shows the location info, using another method (very same looking but using



- (void) locationManager:(CLLocationManager *) manager
didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation



but I need heading info here.


Answer



Found the deal.
Code is perfectly fine, the issue is in Iphone simulator.
Somehow it is providing location info just fine, but heading info is not provided thus the message is never sent.
Talk about weird things, apple.


html - What is the boundary in multipart/form-data?

Answer


I want to ask a question about the multipart/form-data. In the HTTP header, I find that the Content-Type: multipart/form-data; boundary=???.



Is the ??? free to be defined by the user? Or is it generated from the HTML? Is it possible for me to define the ??? = abcdefg?

What is purpose of ":" in python array access code line colors[rnd_ind, :]?




I am new to python and many constructions blows away my C styled brain.

Now I need to understand how some python code works.



#Training inputs for RGBcolors
colors = np.array(
[[0.0, 0.0, 0.0],
[0.0, 0.0, 1.0],
[0.0, 0.0, 0.5],
[0.125, 0.529, 1.0],
[0.33, 0.4, 0.67],
[0.6, 0.5, 1.0],

[0.0, 1.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 1.0],
[1.0, 0.0, 1.0],
[1.0, 1.0, 0.0],
[1.0, 1.0, 1.0],
[0.33, 0.33, 0.33],
[0.5, 0.5, 0.5],
[0.66, 0.66, 0.66]])


for i in range(num_training):
rnd_ind = np.random.randint(0, len(colors))
s.train(colors[rnd_ind, :]) //what's going on here?


This is the train body:



def train(self, input_x):
# Compute the winning unit
bmu_index, diff = self.session.run([self.bmu_index, self.diff], {self.input_placeholder:[input_x], self.current_iteration:self.num_iterations})


# Update the network's weights
self.session.run(self.update_weights, {self.diff_2:diff, self.dist_sliced:self.dist[bmu_index[0],:], self.current_iteration:self.num_iterations})

self.num_iterations = min(self.num_iterations+1, self.num_expected_iterations)


I set breakpoint to train beginning to see how it's input parameter looks like, but I no see anything unusual. This is just an array.



I tried searching and found this Colon (:) in Python list index question, but it looks like this is something different, because in my case : written after ,, but in their cases it follows after some value.



Answer



This has nothing to do with standard python arrays. If you use it in python lists you ll get an error.



Traceback (most recent call last):
File "asd.py", line 3, in
print(x[0, :])
TypeError: list indices must be integers or slices, not tuple


This is specific to numpy. It is an indexing of a multidimensional array. First number is the first dimension, second is the second and so on.




import numpy as np

x = np.array([[1,2,3], [3,4,5], [2,3,4], [4,7,8]])

print(x[0, 1:2])


Will output [2]


javascript - JSON parse error: Cannot read property



I have created some little jt code, but it gives me error




function Mind(){
var request = "request";
var reply = "reply";
var words = '';

this.Reply = function(){
if(request == words.nouns[0].noun){
reply = words.nouns[0].noun;
}

else
reply = this.words.nouns[0].noun;
}

this.SetRequest = function(req){
request = req;
}

this.GetReply = function(){
return reply;

}

this.Parse = function(u){
var xmlhttp = new XMLHttpRequest();
var url = u;
var result;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
words = JSON.parse(xmlhttp.responseText);
}

}
xmlhttp.open("GET", url, true);
xmlhttp.send();
return result;
}

this.Construct = function(){
words = this.Parse('mind/words.json');
}}


var mind = new Mind();
mind.Parse('mind/words.json');


and here is my json file



{
"nouns": [
{"noun": "child"},
{"noun": "father"}

]
}


In command live all goes well, but when I run this code, appears error




Uncaught TypeError: Cannot read property 'nouns' of undefined



Answer




Mutliple errors. The most fundamental one is that your code ignores that XMLHttpRequest is async, and wont return a value in the same way as "regular" functions. Read about it here: How to make a function wait until a callback has been called using node.js. The TL;DR is that you have to pass in a "callback-function" to your parse-method and "return" your value using that function, instead of using a return-statement. Google for "javascript callbacks" and read a few tutorials if this concept is new to you!



You also have some minor errors, like returning result from Parse, but never actually setting result to anything. Also words is being assigned in multiple places in a way that doesn't really make sense. But both of these things will go away when you solve the sync/async issues.



EDIT:



Essentially the fix looks like this:



this.Parse = function(u, callback){ // this "callback" is new
var xmlhttp = new XMLHttpRequest();

var url = u;
var result;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
words = JSON.parse(xmlhttp.responseText);
callback(null, words); // we're "returning" the words here
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

// no return statement here!
}

this.Construct = function(){
this.Parse('mind/words.json', function(error, words) {
// here you can use your words!
});
}}

c++ - multi-dimensional vectors and pointers to vectors

I am trying to store pointers to vectors of pointers to vectors in a vector. (I hope that wasn't too mind boggling). Basically, I have a vector and I want to store multiple matrices in it, hence the 3 dimensions. There seems to be a problem with the way I am accessing elements. I don't particuarlily understand the error because the 3rd dimension is a pointer to a vector of ints. I don't think that should change the way you access the ints.



using namespace std;

vector< vector< vector* >* > matrixHolder;

int main() {

vector< vector* >* a;


a->push_back(new vector(10, 0));

matrixHolder.push_back(a);

matrixHolder[0][0][0] = 5; //Line 34


return 0;
}



main.cpp:34: error: invalid conversion from ‘int’ to ‘std::vector < int, std::allocator < int> >*’

angularjs - Confusing $locationChangeSuccess and $stateChangeStart



I am trying to do some authentication with AngularUI Router. $urlRouter.sync() looks like exactly what I need. However, that's only available when I intercept $locationChangeSuccess. But when I do that, $state.current.name is empty, whereas I want it to be the current state.



Here's my code so far:



$rootScope.$on('$locationChangeSuccess', function(event, next, nextParams) {
event.preventDefault();

if ($state.current.name === 'login') {
return userService.isAuthenticated().then(function(response) {
var authenticated;
authenticated = response.authenticated;
return alert(authenticated);
});
}
});



Any pointers as to what I'm doing wrong?


Answer



I would suggest to go more "UI-Router way". We should use $rootScope.$on('$stateChangeStart' event where $state.current would be properly provided. Here is a working example



Let's observe simple (but not naive) solution, which could be extended to any degree later. Also if you will like this approach, here is much more comprehensive implementation: angular ui-router login authentication



Firstly, let's have our user service defined like this:



.factory('userService', function ($timeout, $q) {


var user = undefined;

return {
// async way how to load user from Server API
getAuthObject: function () {
var deferred = $q.defer();

// later we can use this quick way -
// - once user is already loaded
if (user) {

return $q.when(user);
}

// server fake call, in action would be $http
$timeout(function () {
// server returned UN authenticated user
user = {isAuthenticated: false };
// here resolved after 500ms
deferred.resolve(user)
}, 500)


return deferred.promise;
},

// sync, quick way how to check IS authenticated...
isAuthenticated: function () {
return user !== undefined
&& user.isAuthenticated;
}
};

})


So, we use async (here $timeout) to load user object form a server. In our example it will have a property {isAuthenticated: false }, which will be used to check if is authenticated.



There is also sync method isAuthenticated() which, until user is loaded and allowed - always returns false.



And that would be our listener of the '$stateChangeStart' event:



.run(['$rootScope', '$state', 'userService',

function ($rootScope, $state, userService) {

$rootScope.$on('$stateChangeStart', function (event, toState, toParams
, fromState, fromParams) {
// if already authenticated...
var isAuthenticated = userService.isAuthenticated();
// any public action is allowed
var isPublicAction = angular.isObject(toState.data)
&& toState.data.isPublic === true;


if (isPublicAction || isAuthenticated) {
return;
}

// stop state change
event.preventDefault();

// async load user
userService
.getAuthObject()

.then(function (user) {

var isAuthenticated = user.isAuthenticated === true;

if (isAuthenticated) {
// let's continue, use is allowed
$state.go(toState, toParams)
return;
}
// log on / sign in...

$state.go("login");
})
...


What we are checking first, is if user is already loaded and authenticated (var isAuthenticated = ...). Next we will give green to any public method. This is done with the data {} property of the state object definition (see Attach Custom Data to State Objects)



And that's it. In case of states defined like in a below snippet we can experience:





  • the 'public', 'home' are allowed to anybody

  • the 'private', 'private' will redirect to login if isAuthenticated === false

  • the 'login' in this example provides quick way how to switch isAuthenticated on/off



    // States
    $stateProvider

    // public
    .state('home', {
    url: "/home",

    templateUrl: 'tpl.html',
    data: { isPublic: true },
    })
    .state('public', {
    url: "/public",
    templateUrl: 'tpl.html',
    data: { isPublic: true },
    })
    // private
    .state('private', {

    url: "/private",
    templateUrl: 'tpl.html',
    })
    .state('private2', {
    url: "/private2",
    templateUrl: 'tpl.html',
    })

    // login
    .state('login', {

    url: "/login",
    templateUrl: 'tpl.html',
    data: { isPublic: true },
    controller: 'loginCtrl',
    })



Check that all here




Some other resources:




java - How do event listeners constantly poll to check to see if a button, for example, was clicked?




How does, for example, a button in Java actually listen for an event to occur? I understand button events are handled once they are clicked in a special EDT (Event Dispatching Thread). But how without "busy waiting" does the button know that it has been actually clicked. The only way I understand this is possible if in a separate thread hidden from the user such as the Event Dispatching Thread there is a constant polling every so often, maybe every few milliseconds to check to see if it was clicked. On top of this, how does a button click invoke code?




I assume people are going to suggest it is the Observer Pattern at work here, but from the examples I have seen, the user more or less explicitly notifies the observers so it's almost no different than calling just a regular method.



s.setName("IceCream");
public void setName(String name) {
this.name = name;
setChanged();
notifyObservers();
}



and then the update() method is called. This isn't the Observer Pattern from scratch but using the Observable and Observer classes.



Let me know if anything needs to be clarified



This question is sort-of-similar to my last question regarding how to constantly poll a condition without busy waiting. How do you pause a thread until a condition becomes true without busy waiting?


Answer




How does, for example, a button in Java actually listen for an event to occur?





The button doesn't do anything. The button only provides a handler (i.e., a java.awt.event.ActionListener) that the event dispatch thread (EDT) will call when it decides that a given mouse click is intended for that button.



It's the EDT that waits for mouse and keyboard events. How it waits will depend on what operating system is running it. Some operating systems provide a single system call that lets a process wait for input from any one of several different sources. Under Windows it's WaitForMultipleObjects(...). Under Linux, it's either select(...) or poll(...).



Given some hypothetical operating system that provides native threads, but no select()-like function, the JVM could create one thread for each different source of input (e.g., a keyboard thread, a mouse thread, ...) and these could all push events onto a queue that the EDT would consume.







I assume people are going to suggest it is the Observer Pattern at work here,





Basically, yes, but since Java is almost as old as the idea of named patterns, you might not find the word "observer" in the source code.


plot explanation - How did Talia find her father? - Movies & TV



In the great revelation of The Dark Knight Rises, we are shown it was Talia who escaped The Pit, then brought her father back to rescue her savior, Bane.




However, considering the fact that Talia was born and raised in the prison, how did she know where to find her father or who he was?



One can assume that her mother instructed her on her father's name and nature of his profession, but it is reasonable to believe that her mother didn't know where Ra's was since her incarceration?


Answer



I believe it's more about how Ra's Al Ghul found his daughter rather than a matter of her finding him. The news of a child escaping the pit would have spread fast and must have reached to Ra's Al Ghul. He must have tried to contact the person who escaped the pit in order to make her join league of shadows and in that process he may have came to know she is his daughter.
I have to admit that I am not familiar with comics and this is the most logical explanation that came to my mind!


Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell



I have taken Problem #12 from Project Euler as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first triangle number with more than 1000 divisors instead of 500 as stated in the original problem.



The result is the following:



C:




lorenzo@enzo:~/erlang$ gcc -lm -o euler12.bin euler12.c
lorenzo@enzo:~/erlang$ time ./euler12.bin
842161320

real 0m11.074s
user 0m11.070s
sys 0m0.000s



Python:



lorenzo@enzo:~/erlang$ time ./euler12.py 
842161320

real 1m16.632s
user 1m16.370s
sys 0m0.250s



Python with PyPy:



lorenzo@enzo:~/Downloads/pypy-c-jit-43780-b590cf6de419-linux64/bin$ time ./pypy /home/lorenzo/erlang/euler12.py 
842161320

real 0m13.082s
user 0m13.050s
sys 0m0.020s



Erlang:



lorenzo@enzo:~/erlang$ erlc euler12.erl 
lorenzo@enzo:~/erlang$ time erl -s euler12 solve
Erlang R13B03 (erts-5.7.4) [source] [64-bit] [smp:4:4] [rq:4] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.4 (abort with ^G)
1> 842161320

real 0m48.259s

user 0m48.070s
sys 0m0.020s


Haskell:



lorenzo@enzo:~/erlang$ ghc euler12.hs -o euler12.hsx
[1 of 1] Compiling Main ( euler12.hs, euler12.o )
Linking euler12.hsx ...
lorenzo@enzo:~/erlang$ time ./euler12.hsx

842161320

real 2m37.326s
user 2m37.240s
sys 0m0.080s


Summary:





  • C: 100%

  • Python: 692% (118% with PyPy)

  • Erlang: 436% (135% thanks to RichardC)

  • Haskell: 1421%



I suppose that C has a big advantage as it uses long for the calculations and not arbitrary length integers as the other three. Also it doesn't need to load a runtime first (Do the others?).



Question 1:
Do Erlang, Python and Haskell lose speed due to using arbitrary length integers or don't they as long as the values are less than MAXINT?




Question 2:
Why is Haskell so slow? Is there a compiler flag that turns off the brakes or is it my implementation? (The latter is quite probable as Haskell is a book with seven seals to me.)



Question 3:
Can you offer me some hints how to optimize these implementations without changing the way I determine the factors? Optimization in any way: nicer, faster, more "native" to the language.



EDIT:



Question 4:

Do my functional implementations permit LCO (last call optimization, a.k.a tail recursion elimination) and hence avoid adding unnecessary frames onto the call stack?



I really tried to implement the same algorithm as similar as possible in the four languages, although I have to admit that my Haskell and Erlang knowledge is very limited.






Source codes used:



#include 
#include


int factorCount (long n)
{
double square = sqrt (n);
int isquare = (int) square;
int count = isquare == square ? -1 : 0;
long candidate;
for (candidate = 1; candidate <= isquare; candidate ++)
if (0 == n % candidate) count += 2;
return count;

}

int main ()
{
long triangle = 1;
int index = 1;
while (factorCount (triangle) < 1001)
{
index ++;
triangle += index;

}
printf ("%ld\n", triangle);
}





#! /usr/bin/env python3.2

import math


def factorCount (n):
square = math.sqrt (n)
isquare = int (square)
count = -1 if isquare == square else 0
for candidate in range (1, isquare + 1):
if not n % candidate: count += 2
return count

triangle = 1

index = 1
while factorCount (triangle) < 1001:
index += 1
triangle += index

print (triangle)






-module (euler12).
-compile (export_all).

factorCount (Number) -> factorCount (Number, math:sqrt (Number), 1, 0).

factorCount (_, Sqrt, Candidate, Count) when Candidate > Sqrt -> Count;

factorCount (_, Sqrt, Candidate, Count) when Candidate == Sqrt -> Count + 1;

factorCount (Number, Sqrt, Candidate, Count) ->

case Number rem Candidate of
0 -> factorCount (Number, Sqrt, Candidate + 1, Count + 2);
_ -> factorCount (Number, Sqrt, Candidate + 1, Count)
end.

nextTriangle (Index, Triangle) ->
Count = factorCount (Triangle),
if
Count > 1000 -> Triangle;
true -> nextTriangle (Index + 1, Triangle + Index + 1)

end.

solve () ->
io:format ("~p~n", [nextTriangle (1, 1) ] ),
halt (0).





factorCount number = factorCount' number isquare 1 0 - (fromEnum $ square == fromIntegral isquare)

where square = sqrt $ fromIntegral number
isquare = floor square

factorCount' number sqrt candidate count
| fromIntegral candidate > sqrt = count
| number `mod` candidate == 0 = factorCount' number sqrt (candidate + 1) (count + 2)
| otherwise = factorCount' number sqrt (candidate + 1) count

nextTriangle index triangle
| factorCount triangle > 1000 = triangle

| otherwise = nextTriangle (index + 1) (triangle + index + 1)

main = print $ nextTriangle 1 1

Answer



Using GHC 7.0.3, gcc 4.4.6, Linux 2.6.29 on an x86_64 Core2 Duo (2.5GHz) machine, compiling using ghc -O2 -fllvm -fforce-recomp for Haskell and gcc -O3 -lm for C.




  • Your C routine runs in 8.4 seconds (faster than your run probably because of -O3)

  • The Haskell solution runs in 36 seconds (due to the -O2 flag)


  • Your factorCount' code isn't explicitly typed and defaulting to Integer (thanks to Daniel for correcting my misdiagnosis here!). Giving an explicit type signature (which is standard practice anyway) using Int and the time changes to 11.1 seconds

  • in factorCount' you have needlessly called fromIntegral. A fix results in no change though (the compiler is smart, lucky for you).

  • You used mod where rem is faster and sufficient. This changes the time to 8.5 seconds.

  • factorCount' is constantly applying two extra arguments that never change (number, sqrt). A worker/wrapper transformation gives us:



 $ time ./so
842161320

real 0m7.954s

user 0m7.944s
sys 0m0.004s


That's right, 7.95 seconds. Consistently half a second faster than the C solution. Without the -fllvm flag I'm still getting 8.182 seconds, so the NCG backend is doing well in this case too.



Conclusion: Haskell is awesome.



Resulting Code




factorCount number = factorCount' number isquare 1 0 - (fromEnum $ square == fromIntegral isquare)
where square = sqrt $ fromIntegral number
isquare = floor square

factorCount' :: Int -> Int -> Int -> Int -> Int
factorCount' number sqrt candidate0 count0 = go candidate0 count0
where
go candidate count
| candidate > sqrt = count
| number `rem` candidate == 0 = go (candidate + 1) (count + 2)

| otherwise = go (candidate + 1) count

nextTriangle index triangle
| factorCount triangle > 1000 = triangle
| otherwise = nextTriangle (index + 1) (triangle + index + 1)

main = print $ nextTriangle 1 1


EDIT: So now that we've explored that, lets address the questions





Question 1: Do erlang, python and haskell lose speed due to using
arbitrary length integers or don't they as long as the values are less
than MAXINT?




In Haskell, using Integer is slower than Int but how much slower depends on the computations performed. Luckily (for 64 bit machines) Int is sufficient. For portability sake you should probably rewrite my code to use Int64 or Word64 (C isn't the only language with a long).





Question 2: Why is haskell so slow? Is there a compiler flag that
turns off the brakes or is it my implementation? (The latter is quite
probable as haskell is a book with seven seals to me.)



Question 3: Can you offer me some hints how to optimize these
implementations without changing the way I determine the factors?
Optimization in any way: nicer, faster, more "native" to the language.




That was what I answered above. The answer was





  • 0) Use optimization via -O2

  • 1) Use fast (notably: unbox-able) types when possible

  • 2) rem not mod (a frequently forgotten optimization) and

  • 3) worker/wrapper transformation (perhaps the most common optimization).




Question 4: Do my functional implementations permit LCO and hence

avoid adding unnecessary frames onto the call stack?




Yes, that wasn't the issue. Good work and glad you considered this.


regex - Java : scanner - I need to read alpha-numeric line including space/tab but not new-line



I am using java scanner to read input from System.in. I need to read alpha-numeric line including space/tab but not the new-line and should not allow empty input as well.



For example :



a new name



or



a-new-name-1


Here is my scanner:



Scanner reader = new Scanner(System.in);



I tried these ways:



String name = reader.nextLine();


or



String name = reader.next("^[A-Za-z0-9- ]+$");



or



name = reader.next("/^[a-z\\d\\-_\\s]+$/i");


For last 2 cases with input "a test name 1" , I had error:



Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)

at java.util.Scanner.next(Scanner.java:1418)
............


And when used reader.nextLine(),it's skips waiting for next input.For example:



For this part of the code:



System.out.println("Do you want to update audience name?[y/n]");
opt = reader.next().trim();


if( opt.equalsIgnoreCase("y") )
{
System.out.println("Enter audience name : ");
name = reader.nextLine();
}

System.out.println("Do you want to update audience description?[y/n]");
opt = reader.next().trim();


if( opt.equalsIgnoreCase("y") )
{
System.out.println("Enter audience description : ");
description = reader.nextLine();
}


I am seeing this:



Do you want to update audience name?[y/n]

y
Enter audience name :
Do you want to update audience description?[y/n]
y
Enter audience description :
Do you want to update audience rule?[y/n]


May I get any help here?


Answer




FOllow Jonny Henly's suggestion. Mixing up of reader.next and reader.nextLine was the problem.


c++11 - Trouble understanding C++ dependent types, vs what's on the current instantiation

The code below is adapted from the answer here: https://stackoverflow.com/a/17579889/352552



My purpose in asking this question is try to to understand better how C++ handles type resolution around dependent types, versus what's considered to be on the current instantiation, and therefore not needing a typename qualifier. I've been getting contradictory results from different compilers, so I've come here looking for a more canonical answer.



Consider this code



#include 


struct B {
typedef int result_type;
};

template
struct C {
};

template<>
struct C {

typedef float result_type;
};

template
struct D : B, C {
std::string show() {
//A) Default to current instantiation - ignore dependent type, even if one exists, or so I hope
D::result_type r1;

//B) What **exactly** does typename add, here?

//typename D::result_type r1;

return whichType(r1);
}

std::string whichType (int val){
return "INT";
}
std::string whichType (float val){
return "FLOAT";

}
};


int main() {
D stringD;
D floatD;
std::cout<<"String initialization "< std::cout<<"Float initialization "<}



line A) in show(), if I understand correctly, tells the compiler to use the current instantiation, so I should get INT INT. On GCC, I do. So far, so good.



Line B, again if I understand correctly, should either tell the compiler to consider dependent types, which would make that line error out because of the ambiguity; or, if that means only consider dependent types, I should get INT FLOAT. On GCC I get INT INT there, too. Why?






Running this on Clang.




Line A doesn't compile at all.




error: no type named 'result_type' in 'D'; did you mean simply 'result_type'? D::result_type r1;




dropping the D:: does indeed yield INT INT.



Should it have compiled, or is Clang correct here?




Line B does indeed error on the ambiguity




error: member 'result_type' found in multiple base classes of different types typename D::result_type r1







Can anyone here say with authority which compiler (if any!) is canonically correct, and why?




Assuming Clang is correct, it might imply that



MyType::F



is invalid for referencing a type from the current instantiation if it exists on a base type; it's only valid if the type is defined on that class. Ie adding



typedef double dd;



to D




and then



D::dd d = 1.1;
std::cout<


in show would work just fine, which is indeed the case.



Moreover,




typename D::sometype



seems to mean consider dependent types, but not exclusively, and so expect errors if such a type winds up defined in multiple places, either in the current instantiation, and or dependent on a template parameter.



But again, this all assumes Clang's behavior is correct according to spec, which I can't speak to.






Link to GCC repl I was using:
https://wandbox.org/




Link to Clang repl I was using:
https://repl.it/languages/cpp11

Wednesday, May 29, 2019

python - Add the trailing characters upto the first first occurrence of a vowel to the end of the word

I don't think the heading quite explained it sufficiently.



Basically I have a list containing all of the vowels and another list containing the characters that make up the word.



I need to take the list containing the word and take all of the characters up to the first vowel and add them onto the end in order.




What I can't wrap my head around is how to do it, I had two ideas:



for characters in word:
if(character != vowel):
vCount += 1
else:
break
break


for i in range(vCount):
print(i)
wList.append(wList.pop(i))


And another that was basically the same but every time it saw it wasn't a vowel it pop'd it out. The obvious issue I didn't see with these initially is that 'vowel' isn't just a singular entity, character doesn't equal a, pop, character doesn't equal e, pop, etc etc. Or in the case of vCount, it just got far longer than the actual length of wList.



Anyone have a thought on how to solve this?



EDIT: Sorry, that wasnt clear:




cat -> atc



bear -> earb

Is the type cast necessary when using malloc in C?











I just learned how to use the malloc function, and my teacher mentioned that it's necessary to make a type cast when passing the memory address to the pointer. For example, here's a code to get 16 new bytes allocated (4 ints) using malloc:



#include 

int main(){
int *p;
p = (int *)malloc(4*sizeof(int));


return 0;
}


My question: is the (int *) cast on the right side of the attribution necessary? After all p is already a pointer to ints, so the pointer arithmetic should work fine even without that cast.



Thanks


Answer



You only need the cast if you are using malloc in C++ code.




For C it's preferable to not use the cast as it is (a) unnecessary and (b) can mask problems that would otherwise be reported by the compiler.


mysql - Writing a single query for mutliple queries with same where condition



select column1,column2,column3 from table1
where column5=0 and column6=0;



select column4 from table2

where column5=0 and column6=0;



These are two sql statements reading data from table1 & table2, is there a way instead of 2 single queries, can i write in a single query?



Thanks.


Answer



You could use UNION to combine the results:



SELECT
column1,

column2,
column3,
NULL AS column4
FROM table1
WHERE column5 = 0
AND column6 = 0

UNION

SELECT

NULL AS column1,
NULL AS column2,
NULL AS column3,
column4
FROM table2
WHERE column5 = 0
AND column6 = 0

Java 'throws' clause not needed when throwing a new NPE? and why does adding "throws Exception" give compilation errors?




I got curious about the 'throws' clause and wrote the following piece of code (I use Eclipse with Java7). Originally I had started with only blocks 1 and 5 (expecting a compilation error, which did not occur...) and then this led me to writing the other blocks.



// 1
public void throwNPE() {

throw new NullPointerException();
}

// 2
public void throwNPEWithGenericClause() throws Exception {
throw new NullPointerException();
}

// 3
public void throwNPEWithNPEClause() throws NullPointerException {

throw new NullPointerException();
}

// 4
public void throwNPEWithIAEClause() throws IllegalArgumentException {
throw new NullPointerException();
}

// 5
public void callThrowNPE() {

throwNPE();
}

// 6
public void callThrowNPEWithGenericClause() {
throwNPEWithGenericClause(); // COMPILATION ERROR
}

// 7
public void callThrowNPEWithNPEClause() {

throwNPEWithNPEClause();
}

// 8
public void callThrowNPEWithIAEClause() {
throwNPEWithIAEClause();
}


To be honest I would have expected:




(a) a compilation error in 1. (unhandled exception? shouldn't my method notify any 'subsequent caller' that this is going to throw some kind of exception?)



(b) some kind of problem in 4. (possibly a compilation error? I'm throwing a NPE while the clause says IAE)



(c) compilation errors in 5. 6. 7. and 8. (unhandled exceptions? I'm omitting the 'throws' clause)



(d) perhaps someone could also tell me why 6. is the only one where I got the compilation error...


Answer



RuntimeException is unchecked, so compiler does not warn when you throw a exceptions subclass of RuntimeException. If you need compiler to warn you, then you should use Exception or its subclasses.




1) NullPointerException extends RuntimeException
so compiler does not give any error.



2) Even though your method throws NullPointerException, since you marked the method with throws Exception, compiler warns you to catch it in it's callers.



3) Same as 1st answer



4) Same as 1st answer
IllegalArgumentException extends RuntimeException




5) throwNPE does not throw anything at all.



6) Eventhough you throw a NullPointerException (RuntimeException) within throwNPEWithGenericClause, since you mark the method as checked exception, compiler does not allow.



7, 8) Same as 1st answer. Both runtime exceptions, no need to check.


javascript - JS insert into array at specific index




I would like to insert a string into an array at a specific index. How can I do that?



I tried to use push()


Answer



Well, thats pretty easy. Assuming you have an array with 5 objects inside and you want to insert a string at index 2 you can simply use javascripts array splice method:



var array = ['foo', 'bar', 1, 2, 3],

insertAtIndex = 2,
stringToBeInserted = 'someString';

// insert string 'someString' into the array at index 2
array.splice( insertAtIndex, 0, stringToBeInserted );


Your result will be now:



['foo', 'bar', 'someString', 1, 2, 3]



FYI: The push() method you used just adds new items to the end of an array (and returns the new length)


Using MySQL stored procedures with Javascript objects



I am hoping to receive guidance on how to pass a mySQL stored procedure Javascript form data to use as parameters in a query.




I have been searching for an answer on how to use mySQL stored procedures with javascript form data as parameters.



This is what I have thus far:



    var first_name = req.body.firstName,
last_name= req.body.lastName,
email= req.body.email,
password= req.body.password,
gpa= req.body.gpa,
major = req.body.major,

classification= req.body.classification;
var query = connection.query("CALL new_student()", function (err, result) {
if (err) {
res.send(err);
}
res.json(result);
})


Here is the stored procedure:




     CREATE DEFINER=`root`@`localhost` PROCEDURE `new_student`(IN first_name VARCHAR(45), 
IN last_name VARCHAR(45), IN email VARCHAR(45), IN password VARCHAR(45), IN gpa DECIMAL(3,2),
IN major INT(10), IN classification VARCHAR(45))
BEGIN
INSERT INTO users (first_name, last_name, email, password)
VALUES (first_name, last_name, email, password);
INSERT INTO student (user_id, gpa, major, classification)
VALUES (LAST_INSERT_ID(),gpa, major, classification);
END



My intention is to take the variables, or a Javascript object that encapsulates the variables, and pass them in through "new_student()."



I am aware this may seem trivial. I am in the process of learning how to use stored procedures with Javascript.


Answer



You need to provide arguments to the function. If you're using the node-mysql-native you can provide the parameters using syntax like a prepared statement.



var query = connection.query("CALL new_student(?, ?, ?, ?, ?, ?, ?)", [first_name, last_name, email, password, gpa, major, classification], 
function (err, result) {

if (err) {
res.send(err);
}
res.json(result);
})


For more information about this, see Preventing SQL injection in Node.js


plot explanation - What kind of apparatus is Bane's mask? - Movies & TV



During the course of the film, it is explained that Bane has to wear his mask in order to keep his pain level down to a bare minimum.




During the final fight, we see Batman start to disable this device by disconnecting some of the piping on it.



What kind of device is this exactly and is there a real-world equivalent that causes the same effects?


Answer



I don't think I really answered the original question.
Regarding real-life variations on Bane's mask, the following snippet can be found on wikipedia:



Other gases or vapors which produce general anesthesia by inhalation include nitrous oxide, cyclopropane and xenon. These are stored in gas cylinders and administered using flow meters, rather than vaporizers




I found a couple of real world images that struck a chord - the first looks like the masks worn in Batman Begins (in shape only, not in function)



enter image description here



and the second image is of a concept mask for firefighters which could be attached to gas cylinders. I have to say though, that no cylinders were apparent on Bane's costume.



enter image description here


What is (the 'Spaceship' Operator) in PHP 7?

Answer


Answer






PHP 7, which will come out in November this year will introduce the Spaceship (<=>) operator. What is it and how does it work?



This question already has an answer in our general reference question about PHP operators.


Answer



The <=> ("Spaceship") operator will offer combined comparison in that it will :




Return 0 if values on either side are equal
Return 1 if the value on the left is greater
Return -1 if the value on the right is greater


The rules used by the combined comparison operator are the same as the currently used comparison operators by PHP viz. <, <=, ==, >= and >. Those who are from Perl or Ruby programming background may already be familiar with this new operator proposed for PHP7.



   //Comparing Integers

echo 1 <=> 1; //output 0

echo 3 <=> 4; //output -1
echo 4 <=> 3; //output 1

//String Comparison

echo "x" <=> "x"; //output 0
echo "x" <=> "y"; //output -1
echo "y" <=> "x"; //output 1

python - What is __init__.py for?

In addition to labeling a directory as a Python package and defining __all__, __init__.py allows you to define any variable at the package level. Doing so is often convenient if a package defines something that will be imported frequently, in an API-like fashion. This pattern promotes adherence to the Pythonic "flat is better than nested" philosophy.


An example


Here is an example from one of my projects, in which I frequently import a sessionmaker called Session to interact with my database. I wrote a "database" package with a few modules:


database/
__init__.py
schema.py
insertions.py
queries.py

My __init__.py contains the following code:


import os
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
engine = create_engine(os.environ['DATABASE_URL'])
Session = sessionmaker(bind=engine)

Since I define Session here, I can start a new session using the syntax below. This code would be the same executed from inside or outside of the "database" package directory.


from database import Session
session = Session()

Of course, this is a small convenience -- the alternative would be to define Session in a new file like "create_session.py" in my database package, and start new sessions using:


from database.create_session import Session
session = Session()

Further reading


There is a pretty interesting reddit thread covering appropriate uses of __init__.py here:


http://www.reddit.com/r/Python/comments/1bbbwk/whats_your_opinion_on_what_to_include_in_init_py/


The majority opinion seems to be that __init__.py files should be very thin to avoid violating the "explicit is better than implicit" philosophy.

PHP array delete by value (not key)



I have a PHP array as follows:



$messages = [312, 401, 1599, 3, ...];



I want to delete the element containing the value $del_val (for example, $del_val=401), but I don't know its key. This might help: each value can only be there once.



I'm looking for the simplest function to perform this task, please.


Answer



Using array_search() and unset, try the following:



if (($key = array_search($del_val, $messages)) !== false) {
unset($messages[$key]);

}


array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset(). It will return FALSE on failure, however it can return a false-y value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.



The if() statement will check whether array_search() returned a value, and will only perform an action if it did.


analysis - What is the relationship between the three intertwined stories of The Fountain?

In The Fountain (2006) there are three separate but related stories told in parallel--Imperial Spain, present day, and .. um, space bubble. Hugh Jackman and Rachel Weisz play the leading lad and lady in each.


Can we consider space bubble "Tom" to be one and the same with present-day "Tommy" after some years have passed? Or is it more symbolic just as Imperial Spain "Tomas" was an envisioning of Izzy's novel?


I ask because it is possible that the doctor/researcher Tommy, who towards the end declares that "Death is a disease", actually manages to find the cure. He could then become immortal and eventually take Izzy's tree in the space bubble to Xibalba.


The linking of these two story threads explains Tom's visions of Izzy amongst other things. However I also feel it betrays the message I got from the film--namely that we cannot win against death--and that at the end Tommy accepted Izzy's passing and stopped his search for a cure for death.


Answer


I think that could be reading too much into it and drawing conclusions that are not there. However, that is not to say that isn't the director's intentions as the whole movie is one big symbolic piece.


The way it plays out to me is that the movie is suppose to represent these 2 lovers intertwined in destiny and almost cursed to play out the same role of loving man and dying woman for eternity, no matter the time period.


javascript - How do I check whether a checkbox is checked in jQuery?

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.



For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.



But the following code returns false by default:





if ($('#isAgeSelected').attr('checked'))
{

$("#txtAge").show();
}
else
{
$("#txtAge").hide();
}











How do I successfully query the checked property?

c# - Returning IEnumerable vs. IQueryable

Answer


Answer





What is the difference between returning IQueryable vs. IEnumerable?




IQueryable custs = from c in db.Customers
where c.City == ""
select c;

IEnumerable custs = from c in db.Customers
where c.City == ""
select c;


Will both be deferred execution and when should one be preferred over the other?



Answer



Yes, both will give you deferred execution.



The difference is that IQueryable is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable, that query will be executed in the database, if possible.



For the IEnumerable case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database.



In code:



IQueryable custs = ...;

// Later on...
var goldCustomers = custs.Where(c => c.IsGold);


That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:



IEnumerable custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);



This is quite an important difference, and working on IQueryable can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take and Skip on IQueryable, you will only get the number of rows requested; doing that on an IEnumerable will cause all of your rows to be loaded in memory.


plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; 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...