Thursday, May 31, 2018

c++ - Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' on Visual Studio 2010 C ++?

I get the following error Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' when I compile my code using Win32 Console Application.

I tried fixing it my going into Projects -> Properties -> General -> Linker -> Enable Incremental Linking and I changed it from "Yes" to No (/INCREMENTAL:NO) and then I tried to debug my code again but got another error message :



1>------ Build started: Project: Someproject, Configuration: Debug Win32 ------
1>project1.obj : warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/INCREMENTAL:NO' specification
1>MSVCRTD.lib(crtexew.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup
1>c:\users\anne\documents\visual studio 2010\Projects\Someproject\Debug\Someproject.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


How can I fix it?




#include 
#include
#include
#include

volatile int counter = 0;

int isPrime(int n)
{

for(int i = 2; i < (int)(sqrt((float)n) + 1.0) ; i++) {
if (n % i == 0) return 0;
}
return 1;
}

unsigned int __stdcall mythread(void*)
{
char* s;
while (counter < 25) {

int number = counter++;
s = "No";
if(isPrime(number)) s = "Yes";
printf("Thread %d value = %d is prime = %s\n",
GetCurrentThreadId(), number, s);
}
return 0;
}

int main(int argc, char* argv[])

{
HANDLE myhandleA, myhandleB;
myhandleA = (HANDLE)_beginthreadex(0, 0, &mythread, (void*)0, 0, 0);
myhandleB = (HANDLE)_beginthreadex(0, 0, &mythread, (void*)0, 0, 0);

WaitForSingleObject(myhandleA, INFINITE);
WaitForSingleObject(myhandleB, INFINITE);

CloseHandle(myhandleA);
CloseHandle(myhandleB);


getchar();

system("pause");
return 0;
}

c++11 - How to check if a file exists in C++?

I want to determine if a file exists in C++ 11



I have the following codes:



ifstream inputFile(c);


if (!inputFile.good()) {
std::cout << "No file found" << '\n';
}


And



if (inputFile.peek() == std::ifstream::traits_type::eof()){
....

}



Which one is correct and idiomatic?

javascript - jQuery adding numbers not correctly sum with decimals

I have a js file which calculate all totals when a user click, this will sum up all clicked rows but if the number contains decimal, would not add correctly, instead always put 00 on decimals



function calculateRevenue(){
var sum = 0;

$("input#check_count_revenue[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("data-revenuecount"));
});

$("#revenue_count_totals").html(sum.toFixed(2)).digits();
};


Then calling the function like this




table.on("change","input#check_count_revenue", function() {
$(this).closest("td").addClass("checked_revenue");
calculateRevenue();
if ($(this).prop("checked") === false)
$(this).closest("td").removeClass("checked_revenue");
});


If the row contains the following




 12.00
13.00


That would correctly sum 25.00



But



 12.00
13.01



Still got 25.00 instead of 25.01



Any ideas? I already tried parseFloat in place of parseInt, does not resolve

r - Finding `n1` TRUEs wrapped in between two `n2` FALSEs, the whole thing wrapped in between `n3` TRUEs, etc



From a sequence of TRUEs and falses, I wanted to make a function that returns TRUE whether there is a series of at least n1 TRUEs somewhere in the sequence. Here is that function:



fun_1 = function(TFvec, n1){
nbT = 0
solution = -1
for (i in 1:length(x)){

if (x[i]){
nbT = nbT + 1
if (nbT == n1){
return(T)
break
}
} else {
nbT = 0
}
}

return (F)
}


Test:



x = c(T,F,T,T,F,F,T,T,T,F,F,T,F,F)
fun_1(x,3) # TRUE
fun_1(x,4) # FALSE



Then, I needed a function that returns TRUE if in a given list boolean vector, there is a series of at least n1 TRUEs wrapped by at least two series (one on each side) of n2 falses. Here the function:



fun_2 = function(TFvec, n1, n2){
if (n2 == 0){
fun_1(TFvec, n2)
}
nbFB = 0
nbFA = 0
nbT = 0

solution = -1
last = F
for (i in 1:length(TFvec)){
if(TFvec[i]){
nbT = nbT + 1
if (nbT == n1 & nbFB >= n2){
solution = i-n1+1
}
last = T
} else {

if (last){
nbFB = 0
nbFA = 0
}
nbFB = nbFB + 1
nbFA = nbFA + 1
nbT = 0
if (nbFA == n2 & solution!=-1){
return(T)
}

last = F
}
}
return(F)
}


It is maybe not a very efficient function though! And I haven't tested it 100 times but it looks like it works fine!



Test:




x = c(T,F,T,T,F,F,T,T,T,F,F,T,F,F)
fun_2(x, 3, 2) # TRUE
fun_2(x, 3, 3) # FALSE


Now, believe it or not, I'd like to make a function (fun_3) that returns TRUE if in the boolean vector there is a (at least) series of at least n1 TRUEs wrapped in between (at least) two (one on each side) series of n2 falses where the whole thing (the three series) are wrapped in between (at least) two (one on each side) series of n3 TRUEs. And as I am afraid to have to bring this problem even further, I am asking here for help to create a function fun_n in which we enter two arguments TFvec and list_n where list_n is a list of n of any length.



Can you help me to create the function fun_n?


Answer




For convenience, record the length of the number of thresholds



n = length(list_n)


Represent the vector of TRUE and FALSE as a run-length encoding, remembering the length of each run for convenience



r = rle(TFvec); l = r$length



Find possible starting locations



idx = which(l >= list_n[1] & r$value)


Make sure the starting locations are embedded enough to satisfy all tests



idx = idx[idx > n - 1 & idx + n - 1 <= length(l)]



Then check that lengths of successively remote runs are consistent with the condition, keeping only those starting points that are



for (i in seq_len(n - 1)) {
if (length(idx) == 0)
break # no solution
thresh = list_n[i + 1]
test = (l[idx + i] >= thresh) & (l[idx - i] >= thresh)
idx = idx[test]
}



If there are any values left in idx, then these are the indexes into the rle satisfying the condition; the starting point(s) in the initial vector are cumsum(l)[idx - 1] + 1.



Combined:



runfun = function(TFvec, list_n) {
## setup
n = length(list_n)
r = rle(TFvec); l = r$length


## initial condition
idx = which(l >= list_n[1] & r$value)
idx = idx[idx > n - 1 & idx + n - 1 <= length(l)]

## adjacent conditions
for (i in seq_len(n - 1)) {
if (length(idx) == 0)
break # no solution
thresh = list_n[i + 1]
test = (l[idx + i] >= thresh) & (l[idx - i] >= thresh)

idx = idx[test]
}

## starts = cumsum(l)[idx - 1] + 1
## any luck?
length(idx) != 0
}


This is fast and allows for runs >= the threshold, as stipulated in the question; for example




x = sample(c(TRUE, FALSE), 1000000, TRUE)
system.time(runfun(x, rep(2, 5)))


completes in less than 1/5th of a second.



A fun generalization allows for flexible condition, e.g., runs of exactly list_n, as in the rollapply solution



runfun = function(TFvec, list_n, cond=`>=`) {

## setup
n = length(list_n)
r = rle(TFvec); l = r$length

## initial condition
idx = which(cond(l, list_n[1]) & r$value)
idx = idx[idx > n - 1 & idx + n - 1 <= length(l)]

## adjacent conditions
for (i in seq_len(n - 1)) {

if (length(idx) == 0)
break # no solution
thresh = list_n[i + 1]
test = cond(l[idx + i], thresh) & cond(l[idx - i], thresh)
idx = idx[test]
}

## starts = cumsum(l)[idx - 1] + 1
## any luck?
length(idx) != 0

}

c# - Dynamic + linq compilation error



I'll say up front that I am doing some really scary things with linq on dynamic data.
But I can't figure out why this query fails to compile:



Error 1 The property '<>h__TransparentIdentifier0' cannot be used with type arguments




public class Program

{
public static void Main(string[] args)
{
var docs = new dynamic[0];
var q = from doc in docs
where doc["@metadata"]["Raven-Entity-Name"] == "Cases"
where doc.AssociatedEntities != null
from entity in doc.AssociatedEntities
where entity.Tags != null // COMPILER ERROR HERE
from tag in entity.Tags

where tag.ReferencedAggregate != null
select new {tag.ReferencedAggregate.Id, doc.__document_id};
}
}

public static class LinqOnDynamic
{
private static IEnumerable Select(this object self)
{
if (self == null)

yield break;
if (self is IEnumerable == false || self is string)
throw new InvalidOperationException("Attempted to enumerate over " + self.GetType().Name);

foreach (var item in ((IEnumerable) self))
{
yield return item;
}
}


public static IEnumerable SelectMany(this object source,
Func> collectionSelector,
Func resultSelector)
{
return Enumerable.SelectMany(Select(source), collectionSelector, resultSelector);
}

public static IEnumerable SelectMany(this object source,
Func> collectionSelector,
Func resultSelector)

{
return Enumerable.SelectMany(Select(source), collectionSelector, resultSelector);
}

public static IEnumerable SelectMany(this object source,
Func> selector)
{
return Select(source).SelectMany(selector);
}


public static IEnumerable SelectMany(this object source,
Func> selector)
{
return Select(source).SelectMany(selector);

}
}


To add insult to injury, the following works:





var docs = new dynamic[0];
var q = from doc in docs
where doc["@metadata"]["Raven-Entity-Name"] == "Cases"
where doc.AssociatedEntities != null
from entity in doc.AssociatedEntities
where entity.Tags != null
from tag in entity.Tags
select new { tag.ReferencedAggregate.Id, doc.__document_id };



It is only when I add:



where tag.ReferencedAggregate != null



That I get an error two lines before:



where entity.Tags != null // COMPILER ERROR HERE




Not sure what is going on


Answer



If I try just converting your calls to:



var q = from doc in docs.Where(doc => doc["@metadata"]["Raven-Entity-Name"] == "Cases" || doc.AssociatedEntities != null)
from entity in doc.AssociatedEntities.Where(entity => entity.Tags != null)


I get a different compiler error which perhaps reveals what is going on:




'Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type'



So I guess you have to overload the Where operator.


linux - Unzip All Files In A Directory




I have a directory of ZIP files (created on a Windows machine). I can manually unzip them using unzip filename, but how can I unzip all the ZIP files in the current folder via the shell?



Using Ubuntu Linux Server.


Answer



This works in bash, according to this link:




unzip \*.zip



css3 - CSS: how to select parent's sibling

I have the following HTML in my page.









  • content ...

  • content ...

  • content ...

  • content ...

  • content ...





I am unable to change this HTML. I have hidden all LI's with the exception of the first by using the following CSS



ul#detailsList li:nth-child(1n+2) {
display:none;
}



So far so good. What I want to do now is to show those hidden LI's when the the checkbox is ticked, using pure CSS. My best attempt so far is



ul#detailsList li input#showCheckbox:checked + li {
display:block;
}


Obviously this doesn't work, as the + li will only select LI's immediately after the checkbox (i.e. siblings), not siblings of the parent.



Is this even possible?

Why did Sherlock Holmes jump from the balcony instead of letting Watson help him in the fight?

In the scene on the balcony where Moriarty and Holmes were playing chess and then Holmes thinks through their fight, he figures he can not win and therefor he jumps from the balcony, taking Moriarty with him (I guess to prevent him from doing any more harm). But in his calculation he never considers Watson helping him in the fight and they proved before, that together they can achieve much more than Holmes can do on his own.


Just before he jumped, Watson came in the door and Holmes saw him. Why wouldn't he just let Watson help? And how could he have survived this fall? Was this part of the plan or just good luck? Is it possible, that Moriarty survived, too?


Stop setInterval call in JavaScript



I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?



I want the user to be able to stop the repeated refresh of data.


Answer




setInterval() returns an interval ID, which you can pass to clearInterval():



var refreshIntervalId = setInterval(fname, 10000);

/* later */
clearInterval(refreshIntervalId);


See the docs for setInterval() and clearInterval().


Excel VBA: Update the formatting for all worksheets





I read through a few online tutorials, and use the macro record to learn how to set formats. But I am wondering is there a way to do the following, without using .Select? Or what is the preferred way by programmers?



Requirement for the simple macro:





  1. Loop through all the worksheets (visible only)

  2. Set bold format to the top row, and set the background to grey

  3. Reset the selection to A1 position



()



Sub SetAllTopRowBold()
Dim ws As Worksheet
On Error Resume Next


For Each ws In ThisWorkbook.Worksheets
If ws.Visible Then
ws.Activate
Rows(1).Select
Selection.Font.Bold = True
Selection.Interior.Color = RGB(190, 190, 190)
Range("A1").Select
End If
Next ws

End Sub

Answer



You can do it directly against the range object:



For Each ws In ThisWorkbook.Worksheets
If ws.Visible Then
ws.Rows(1).Font.Bold = True
ws.Rows(1).Interior.Color = RGB(190, 190, 190)
ws.Select

ws.Range("A1").Select
End If
Next ws

Wednesday, May 30, 2018

mysql - SQL - Syntax error near ','

I can't for the life of me figure out why this query won't work no matter which one of my local databases I try (oracle, mysql, microsoft sql).




INSERT INTO testtable
VALUES ( 'testvalue' , 12345678, 123.04, 0, '1950-01-03' )


For example, with Microsoft SQL Server I get an Error near ','.



With MySQL I get



You have an error in your SQL syntax near '12345678, 123.04, 0, )' at line 2.




I've tried playing with it, I've looked at W3 school for the syntax of INSERT INTO. Everything looks good. What could it be?



Thank you!



EDIT:



As requested: here's the layout for mysql





+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| TestString | varchar(600) | NO | | NULL | |
| TestInt | int(11) | NO | | NULL | |
| TestDouble | double | NO | | NULL | |
| Testbool | tinyint(1) | NO | | NULL | |
| TestDate | date | NO | | NULL | |
+------------+--------------+------+-----+---------+-------+



Also, it should be noted I can run a parameterized query using these values and it will work just fine. It's only when I go to manually create the query that it's a problem.

How to check whether a string contains a substring in JavaScript?

Another alternative is KMP (Knuth–Morris–Pratt).



The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst case of O(nm) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.



Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:



// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.

// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.




function kmpSearch(pattern, text) {
if (pattern.length == 0)
return 0; // Immediate match

// Compute longest suffix-prefix table

var lsp = [0]; // Base case
for (var i = 1; i < pattern.length; i++) {
var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP
while (j > 0 && pattern.charAt(i) != pattern.charAt(j))
j = lsp[j - 1];
if (pattern.charAt(i) == pattern.charAt(j))
j++;
lsp.push(j);
}


// Walk through text string
var j = 0; // Number of chars matched in pattern
for (var i = 0; i < text.length; i++) {
while (j > 0 && text.charAt(i) != pattern.charAt(j))
j = lsp[j - 1]; // Fall back in the pattern
if (text.charAt(i) == pattern.charAt(j)) {
j++; // Next char matched, increment position
if (j == pattern.length)
return i - (j - 1);
}

}
return -1; // Not found
}

console.log(kmpSearch('ays', 'haystack') != -1) // true
console.log(kmpSearch('asdf', 'haystack') != -1) // false


visual c++ - Why is this program erroneously rejected by three C++ compilers?




I am having some difficulty compiling a C++ program that I've written.




This program is very simple and, to the best of my knowledge, conforms to all the rules set forth in the C++ Standard. I've read over the entirety of ISO/IEC 14882:2003 twice to be sure.



The program is as follows:



enter image description here



Here is the output I received when trying to compile this program with Visual C++ 2010:



c:\dev>cl /nologo helloworld.png
cl : Command line warning D9024 : unrecognized source file type 'helloworld.png', object file assumed

helloworld.png : fatal error LNK1107: invalid or corrupt file: cannot read at 0x5172


Dismayed, I tried g++ 4.5.2, but it was equally unhelpful:



c:\dev>g++ helloworld.png
helloworld.png: file not recognized: File format not recognized
collect2: ld returned 1 exit status



I figured that Clang (version 3.0 trunk 127530) must work, since it is so highly praised for its standards conformance. Unfortunately, it didn't even give me one of its pretty, highlighted error messages:



c:\dev>clang++ helloworld.png
helloworld.png: file not recognized: File format not recognized
collect2: ld returned 1 exit status
clang++: error: linker (via gcc) command failed with exit code 1 (use -v to see invocation)


To be honest, I don't really know what any of these error message mean.




Many other C++ programs have source files with a .cpp extension, so I thought perhaps I needed to rename my file. I changed its name to helloworld.cpp, but that didn't help. I think there is a very serious bug in Clang because when I tried using it to compile the renamed program, it flipped out, printed "84 warnings and 20 errors generated." and made my computer beep a lot!



What have I done wrong here? Have I missed some critical part of the C++ Standard? Or are all three compilers really just so broken that they can't compile this simple program?


Answer



In the standard, §2.1/1 specifies:




Physical source file characters are mapped, in an implementation-defined manner, to the basic source character set (introducing new-line characters for end-of-line indicators) if necessary.





Your compiler doesn't support that format (aka cannot map it to the basic source character set), so it cannot move into further processing stages, hence the error. It is entirely possible that your compiler support a mapping from image to basic source character set, but is not required to.



Since this mapping is implementation-defined, you'll need to look at your implementations documentation to see the file formats it supports. Typically, every major compiler vendor supports (canonically defined) text files: any file produced by a text editor, typically a series of characters.






Note that the C++ standard is based off the C standard (§1.1/2), and the C(99) standard says, in §1.2:




This International Standard does not specify
— the mechanism by which C programs are transformed for use by a data-processing

system;
— the mechanism by which C programs are invoked for use by a data-processing
system;
— the mechanism by which input data are transformed for use by a C program;




So, again, the treatment of source files is something you need to find in your compilers documentation.


How to unzip a zip folder using php code




I want to unzip directorires.



That means i have a zipped directory name with xxx.zip.In manuall i right clicked on the zipped directory and do extract folder,then i got an unzipped dirtectory with name xxx and also in this directory have a same directory xxx.In the subfolder will contained the files.




That means, xxx->xxx->files this is the heirarchi of unzipped folder.



So in my site i want to unzipp a directory using php code.



How can i do this? I need only xxx->files not xxx->xxx->files structure.



How can i do this?


Answer



$zip = zip_open("zip.zip");

if ($zip) {
while ($zip_entry = zip_read($zip)) {
$fp = fopen("zip/".zip_entry_name($zip_entry), "w");
if (zip_entry_open($zip, $zip_entry, "r")) {
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
fwrite($fp,"$buf");
zip_entry_close($zip_entry);
fclose($fp);
}
}

zip_close($zip);
}
?>

R expand.grid() function in Python



Is there a Python function similar to the expand.grid() function in R ? Thanks in advance.



(EDIT) Below are the description of this R function and an example.



Create a Data Frame from All Combinations of Factors

Description:


Create a data frame from all combinations of the supplied vectors
or factors.

> x <- 1:3
> y <- 1:3
> expand.grid(x,y)
Var1 Var2
1 1 1
2 2 1
3 3 1

4 1 2
5 2 2
6 3 2
7 1 3
8 2 3
9 3 3


(EDIT2) Below is an example with the rpy package. I would like to get the same output object but without using R :




>>> from rpy import *
>>> a = [1,2,3]
>>> b = [5,7,9]
>>> r.assign("a",a)
[1, 2, 3]
>>> r.assign("b",b)
[5, 7, 9]
>>> r("expand.grid(a,b)")
{'Var1': [1, 2, 3, 1, 2, 3, 1, 2, 3], 'Var2': [5, 5, 5, 7, 7, 7, 9, 9, 9]}



EDIT 02/09/2012: I'm really lost with Python. Lev Levitsky's code given in his answer does not work for me:



>>> a = [1,2,3]
>>> b = [5,7,9]
>>> expandgrid(a, b)
Traceback (most recent call last):
File "", line 1, in
File "", line 2, in expandgrid
NameError: global name 'itertools' is not defined



However the itertools module seems to be installed (typing from itertools import * does not return any error message)


Answer



Here's an example that gives output similar to what you need:



import itertools
def expandgrid(*itrs):
product = list(itertools.product(*itrs))
return {'Var{}'.format(i+1):[x[i] for x in product] for i in range(len(itrs))}


>>> a = [1,2,3]
>>> b = [5,7,9]
>>> expandgrid(a, b)
{'Var1': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'Var2': [5, 7, 9, 5, 7, 9, 5, 7, 9]}


The difference is related to the fact that in itertools.product the rightmost element advances on every iteration. You can tweak the function by sorting the product list smartly if it's important.


java - GET data from NPM json-server throws NetworkOnMainThreadException

Im coding a little Android App which should get Data from a npm json-server. It throws an exception. I did extend the connection class with an AsyncTask and executed the code in "doInBackground" but it still throws an exception. Please Help me.



Here's the code:



import android.os.AsyncTask;

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

public class Network extends AsyncTask {
public String urlString = ("http://localhost:3000");


@Override
protected String doInBackground(String... params) {
StringBuffer chaine = new StringBuffer("");
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agnet", "");
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.connect();


InputStream inputStream = connection.getInputStream();

BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
chaine.append(line);
}

} catch (IOException e) {

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

}
return chaine.toString();
}
}



logcat is telling:




android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)

at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:361)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
at smoca.ch.kreagen.Network.doInBackground(Network.java:25)
at smoca.ch.kreagen.BackendMockup.getData(BackendMockup.java:11)
at smoca.ch.kreagen.FillRealm.initRealm(FillRealm.java:43)
at smoca.ch.kreagen.Fragments.HomeFragment.onCreateView(HomeFragment.java:42)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)

at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)

at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)




I know the problem is when "connection.connect();" gets called because its supposed to be in the main-Thread. But shouldn't. right?



Greetings John

mysql - How to insert into MySQLusing a prepared statement with PHP





I am just learning about databases and I want to be able to store user inputs. What would be a basic example on how to get form data and save it to a database using PHP?



Also making the form secure from SQL attacks.


Answer



File sample.html










File sample.php



    if (isset($_POST['submit'])) {


$mysqli = new mysqli('localhost', 'user', 'password', 'mysampledb');

/* Check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$stmt = $mysqli->prepare("INSERT INTO SampleTable VALUES (?)");

$stmt->bind_param('s', $sample); // Bind $sample to the parameter

$sample = isset($_POST['sample'])
? $_POST['sample']
: '';

/* Execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);


/* Close statement and connection */
$stmt->close();

/* Close connection */
$mysqli->close();
}
?>



This is a very basic example. Many PHP developers today are turning to PDO. Mysqli isn’t obsolete, but PDO is much easier, IMHO.


dialogue - Daniel Day Lewis Quote in Last of the Mohicans

In The Last of the Mohicans, Hawkeye, played by Daniel Day Lewis, appears out of the forest to save the Major from a raiding party of Indians. When the Major grabs a gun and is about to fire at one of the Indians who is running away from Chingachgook (Hawkeye's father), Hawkeye stops him and says


In case your aim's any better than your judgement

Shouldn't he have said


In case your aim's **not** any better than your judgement

I can't imagine the Major would intentionally shoot the people that saved his life.


Here is the action sequence:





The scene in question is about 2:50 in.


Answer


The problem here is that the major is aiming at Chingachgook. The major may think he's one of the attackers running away. It's clear that he's aiming at Chingachgook because even after Chingachgook kills the only other Indian within the line of site of the Major, the Major keeps taking aim.


Obviously HawkEye doesn't want Chingachgook shot, So since the Major's Judgement is that he should shoot Chingachgook, one of the guys who just saved him, his Judgement is considered by Hawkeye to be bad. If his aim is better he might actually hit Chingachgook


json - Comparing two strings in android






Possible Duplicate:
Comparing two identical strings with == returns false






I am having real hard time with solving this code. This might look silly but I am not able to figure out what is happening. I am parsing a JSONArray(No big deal!) I am traversing the array with a for loop. I want to break the loop when the user input and the value matches. Here is my code



String regi = null;
JSONObject studentObject = null;
try {

JSONArray returned = test.getInternetData();
int i;
for (i = 0; i < returned.length(); i++) {
studentObject = returned.getJSONObject(i);
regi = studentObject.getString("REGISTRATION_NO");
if (regi == reg) {
name = studentObject.getString("STUDENT_NAME");
break;
}
}

course = studentObject.getString("COURSE_CODE");
Log.d("Details", name + course + regi + i);//Out put: nullGraduate081018394:name - null
//course: Graduate (same for all), regi: last registration number,
//i: giving totalnumber of objects


As per my knowledge the loop should stop when it finds a match. The COURSE_CODE will be corresponding to the student. Am I missing something?



Please note: The function getInternetData() is returning the whole JSON Array. The loop is completely traversing every object.


Answer




Strings cannot be compared with == in Java. You have to use string1.equals(string2).


plot explanation - What really happened to Korra? - Movies & TV



In the finale to this season of Legend of Korra we see Korra finally battle Amon head-to head.



However, the turn out is unfavorable as Korra loses her bending skills, but somehow retains and activates her Airbending



In another twist, she connects to her past lives and Aang is shown restoring her bending and activating her Avatar State.



However, how are all these events possible?




Is it truly Amon's Blood-Bending that blocks the power or did Amon achieve what Tenzin thought impossible and learn Energy-Bending? And if so, how did bending Korra's energy take away all forms of bending except Air-Bending?



Finally, how is she able to gain all her bending back through connecting with her past lives?


Answer



Honestly, I got the same doubts when I watched this season yesterday. However, I am going to try answering your questions. Please keep in mind that I didn't watch previous three seasons, so I might lack some knowledge about this bending world, so correct me if I am wrong somewhere.




Are all these events possible?





Apparently, they are.




Is it truly Amon's Blood-Bending that blocks the power or did Amon achieve what Tenzin thought impossible and learn Energy-Bending?




No. Amon used bloodbending to take away bending abilities. He was able to duplicate the Energy Bending which is possible to avatars only, using his bloodbending. My guess is that he does something to the blood flow (to the areas that correspond to bending) in brain, that probably disables those parts of brain which are used to control bending. He must have got this knowledge about parts of brain and the energy flow in brain etc. because of his additional knowledge about chi-blocking. We should keep in mind that he is the only person who knows both chi-blocking and bloodbending. Amon must have used these both successfully to duplicate Energy Bending in this aspect.



Amon also doesn't heal/restore his brother's bending abilities at the end. He could have let his brother have at least the water bending abilities so that he could help him in his next quest. However, he doesn't/couldn't do that. Energy Benders can restore these abilities. It seems Bloodbenders like Amon can't do this sort of thing (not yet). This proves that Amon didn't have real Energy Bending abilities.





And if so, how did bending Korra's energy take away all forms of bending except Air-Bending?




It seems that there are parts of brain corresponding to each bending ability. When Korra's abilities were removed, she didn't have the ability to air bend. Also, Amon knew what abilities she had/ didn't have. So, he must have probably removed the other three. Trying to unlock them might have led korra to unlock the one that hasn't been unlocked before, because she was in a situation where she needed to bend in order to save her love. So, she might have directed all her bending chi to the area which she never was able to direct to before. This could also hint that she was connecting to her spiritual self.



Now, if in case there was nothing like parts of brain for each bending ability - it could mean two things.





  1. A person could do other form of bending that is different from what
    has been taken away. It means that a fire bender can learn water
    bending after their fire bending has been taken away.



    This is similar to alchemists learning Alkahestry in Full Metal Alchemist: Brotherhood no matter whether they still have Alchemy abilities or not.


  2. Korra must have started connecting to her spiritual self even more
    strongly and learned the air bending ability from Aang. It was said
    in the series that Aang connected to his previous lives and had this
    immense experience behind him to ask from. Korra must have done
    that, and got the air bending abilities from Aang.




    This would mean that her spiritual quest must have started when she
    was in the metal container, and made her learn the air bending
    abilities in the process and finally led to her becoming a perfect
    avatar.




Regarding what Amon did under the assumption that parts of brain didn't exist, it would mean that Amon wasn't able to simulate the Energy Bending totally. We know that Energy benders have some special abilities among which removing/ restoring bending is a part. Amon should have been able to use his skill only in the removing aspect and not the restoring aspect. Even when he was a child, he says that removing is the best quality among all - this could mean that he must have concentrated on this single aspect and forgot/ disregarded the other ones.



It also means that Amon was never interested in learning Energy Bending, but only the removing part of it, the only thing he was able to do successfully. In any case, Amon didn't Energy Bend.



initialization - How to initialise memory with new operator in C++?



I'm just beginning to get into C++ and I want to pick up some good habits. If I have just allocated an array of type int with the new operator, how can I initialise them all to 0 without looping through them all myself? Should I just use memset? Is there a “C++” way to do it?



Answer



It's a surprisingly little-known feature of C++ (as evidenced by the fact that no-one has given this as an answer yet), but it actually has special syntax for value-initializing an array:



new int[10]();


Note that you must use the empty parentheses — you cannot, for example, use (0) or anything else (which is why this is only useful for value initialization).



This is explicitly permitted by ISO C++03 5.3.4[expr.new]/15, which says:





A new-expression that creates an object of type T initializes that object as follows:



...




  • If the new-initializer is of the form (), the item is value-initialized (8.5);





and does not restrict the types for which this is allowed, whereas the (expression-list) form is explicitly restricted by further rules in the same section such that it does not allow array types.


soa - Complex architecture for simple application

As a consultant, I am responsible for designing the architecture of an application for an external company. The requirements for this application are rather simple and the whole thing could easily be solved with a basic web application, one or two incoming web services and a few outgoing document channels.




Things get more complicated because of two non-functional requirements:




  1. Said company mandates that all internal applications be offered through an enterprise portal (for UI, security and technical uniformity)

  2. Said company mandates that all applications be built using SOA principles so that services may be eventually published on an ESB and reused.



Architecture can be adapted to the portal requirement easily. Presentation will be built using portlets and integrate within the portal theme, and portal security will be reused. No big deal.




The SOA requirement is another story. Reusable services have not yet been identified. The way I see it, there are a few options:




  1. Business logic is deployed on the portal and co-located with the presentation layer. No services are exposed and this decision is deferred.

  2. Business logic is deployed on a separate server. An API is designed and all services are exposed using a closed protocol (e.g. RMI or Hessian). For services that need to be eventually reused, a SOAP API may be added on top of these services.

  3. Business logic is deployed on a separate server. A SOAP API is designed and all services are exposed using this mechanism.



I want to avoid building something too complicated. I have lived through projects with business delegates, remote facades and DTOs where every single change required modifying several layers. Yet, it feels as if this SOA requirement forcibly pushes me in that direction.




Update: The more I think about it, the more I realize that complexity arises from the need to design a remoting API. Of course this requires creating interfaces for services, but what about the exchanged entities? Either I go the DTO way and end up with two parallels object hierarchies (one for DTOs and one for the actual entities) or I go the interface way and declare interfaces for all entities that need to transit across servers. Either way, this brings up a whole new set of problems and we will end up writing lots of boiler-plate code. And I thought we were through with that era...



What would be the best (or least worse) way to design this?



Thanks all.

java - Why is printing "B" dramatically slower than printing "#"?



I generated two matrices of 1000 x 1000:



First Matrix: O and #.
Second Matrix: O and B.




Using the following code, the first matrix took 8.52 seconds to complete:



Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("#");

}
}

System.out.println("");
}


With this code, the second matrix took 259.152 seconds to complete:



Random r = new Random();

for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B"); //only line changed
}
}

System.out.println("");

}


What is the reason behind the dramatically different run times?






As suggested in the comments, printing only System.out.print("#"); takes 7.8871 seconds, whereas System.out.print("B"); gives still printing....



As others who pointed out that it works for them normally, I tried Ideone.com for instance, and both pieces of code execute at the same speed.




Test Conditions:




  • I ran this test from Netbeans 7.2, with the output into its console

  • I used System.nanoTime() for measurements


Answer



Pure speculation is that you're using a terminal that attempts to do word-wrapping rather than character-wrapping, and treats B as a word character but # as a non-word character. So when it reaches the end of a line and searches for a place to break the line, it sees a # almost immediately and happily breaks there; whereas with the B, it has to keep searching for longer, and may have more text to wrap (which may be expensive on some terminals, e.g., outputting backspaces, then outputting spaces to overwrite the letters being wrapped).




But that's pure speculation.


Tuesday, May 29, 2018

regex - PHP Reverse Preg_match





if(preg_match("/" . $filter . "/i", $node)) {
echo $node;
}


This code filters a variable to decide whether to display it or not. An example entry for $filter would be "office" or "164(.*)976".



I would like to know whether there is a simple way to say: if $filter does not match in $node. In the form of a regular expression?



So... not an "if(!preg_match" but more of a $filter = "!office" or "!164(.*)976" but one that works?



Answer



This can be done if you definitely want to use a "negative regex" instead of simply inverting the result of the positive regex:



if(preg_match("/^(?:(?!" . $filter . ").)*$/i", $node)) {
echo $node;
}


will match a string if it doesn't contain the regex/substring in $filter.




Explanation: (taking office as our example string)



^          # Anchor the match at the start of the string
(?: # Try to match the following:
(?! # (unless it's possible to match
office # the text "office" at this point)
) # (end of negative lookahead),
. # Any character
)* # zero or more times
$ # until the end of the string


c++ - Unresolved external symbol with template function



I searched around the web but I haven't found an answer yet, as to why I get this error:





Error 1 error LNK2019: unresolved external symbol "public: class Mesh * __thiscall AssetManager::GetAsset(class std::basic_string,class std::allocator >)" (??$GetAsset@PAVMesh@@@AssetManager@@QAEPAVMesh@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function "public: void __thiscall SceneManager::AddMesh(class std::basic_string,class std::allocator >)" (?AddMesh@SceneManager@@QAEXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) C:\Users\Dirk\documents\visual studio 2010\Projects\OpenGameEngine\OpenGameEngine\SceneManager.obj




Here is my code:



AssetManager.h



#pragma once

#include
#include
#include "Asset.h"
#include "Mesh.h"

using namespace std;

class AssetManager
{
public:

AssetManager(string rootFolder);
bool LoadAsset(string assetName, int assetType, string assetFile, bool subDirectory);
void UnloadAsset(string assetName);
template T GetAsset(string assetName);
bool AddAssetSubDirectory(int assetType, string subDirectory);

private:
string m_rootFolder;
map m_assetSubs;
map m_assets;

};


AssetManager.cpp



#include "AssetManager.h"

AssetManager::AssetManager(string rootFolder)
{
m_rootFolder = rootFolder;

}

bool AssetManager::AddAssetSubDirectory(int assetType, string subDirectory)
{
if (m_assetSubs.find(assetType) == m_assetSubs.end())
{
m_assetSubs[assetType] = subDirectory;
return true;
}
else

{
return false;
}
}

bool AssetManager::LoadAsset(string assetName, int type, string assetFile, bool subDirectory)
{
string filePos;
if (subDirectory)
{

filePos = m_rootFolder.append(m_assetSubs[type]).append(assetFile);
}
else
{
filePos = m_rootFolder.append(assetFile);
}
return true;
}

void AssetManager::UnloadAsset(string assetName)

{
if (m_assets.find(assetName) != m_assets.end())
{
m_assets.erase(assetName);
}
}

template T AssetManager::GetAsset(string assetName)
{
if (m_assets.find(assetName) != m_assets.end())

{
return m_assets[assetName];
}
else
{
return null;
}
}



SceneManager.h



#pragma once
#include
#include
#include "AssetManager.h"

using namespace std;

class SceneManager

{
public:
static SceneManager* Instance();
void AddMesh(string assetName);
void RemoveMesh(string assetName);
void Draw();
void Run();
void SetAssetManager(AssetManager*);
void Destroy();


private:
SceneManager();
SceneManager(SceneManager const&);
~SceneManager();
SceneManager& operator=(SceneManager const&){};
static SceneManager* m_Instance;
AssetManager *m_assetMgr;

private:
map m_staticMeshes;

};


SceneManager.cpp



#include "SceneManager.h"
#include "AssetManager.h"

SceneManager* SceneManager::m_Instance = NULL;


SceneManager::SceneManager()
{
m_assetMgr = 0;
}

SceneManager::SceneManager(SceneManager const&)
{

}


SceneManager::~SceneManager()
{
delete m_assetMgr;
m_assetMgr = 0;
}

void SceneManager::Destroy()
{
delete m_Instance;
m_Instance = 0;

}

SceneManager* SceneManager::Instance()
{
if (!m_Instance)
m_Instance = new SceneManager();

return m_Instance;
}


void SceneManager::SetAssetManager(AssetManager *am)
{
m_assetMgr = am;
}

void SceneManager::AddMesh(string assetName)
{
m_assetMgr->GetAsset(assetName);
}


void SceneManager::RemoveMesh(string assetName)
{
if (m_staticMeshes.find(assetName) != m_staticMeshes.end())
{
m_staticMeshes.erase(assetName);
}
}

void SceneManager::Draw()
{

for (map::Iterator it = m_staticMeshes.begin(); it != m_staticMeshes.end(); ++it)
{
it->second->Draw();
}
}

void SceneManager::Run()
{

}



Thanks in advance for the responses!


Answer



C++ does not allow you to declare a template in a header file and define it in a .cpp file. The reason is that templates can only be created when the template parameters are known and so they can't be complied in advance.



To solve your problem, you will need to declare and define template T GetAsset(string assetName) in the AssetManager.h file


python - What does ** (double star/asterisk) and * (star/asterisk) do for parameters?



In the following method definitions, what does the * and ** do for param2?



def foo(param1, *param2):
def bar(param1, **param2):

Answer



The *args and **kwargs is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation.




The *args will give you all function parameters as a tuple:



def foo(*args):
for a in args:
print(a)

foo(1)
# 1


foo(1,2,3)
# 1
# 2
# 3


The **kwargs will give you all
keyword arguments except for those corresponding to a formal parameter as a dictionary.



def bar(**kwargs):

for a in kwargs:
print(a, kwargs[a])

bar(name='one', age=27)
# age 27
# name one


Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:




def foo(kind, *args, **kwargs):
pass


It is also possible to use this the other way around:



def foo(a, b, c):
print(a, b, c)

obj = {'b':10, 'c':'lee'}


foo(100,**obj)
# 100 10 lee


Another usage of the *l idiom is to unpack argument lists when calling a function.



def foo(bar, lee):
print(bar, lee)


l = [1,2]

foo(*l)
# 1 2


In Python 3 it is possible to use *l on the left side of an assignment (Extended Iterable Unpacking), though it gives a list instead of a tuple in this context:



first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]



Also Python 3 adds new semantic (refer PEP 3102):



def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass


Such function accepts only 3 positional arguments, and everything after * can only be passed as keyword arguments.


film techniques - How do they prevent animal cruelty in movies?

According to a number of sources, cruelty to animals is an offence and it is punishable in most countries. But in historical film it's inevitable, because if a film is looking to be historically accurate, and hunting animals (for example) was something important to the historical period and in battle sequences. For instance, in Gladiator the horse sequence at the initial battle were worst and of course that's a worst animal abuse sequences.


According to wikipedia,



TV & film making


Animal cruelty has long been an issue with the art form of filmmaking,
with even some big-budget Hollywood films receiving criticism for
allegedly harmful—and sometimes lethal—treatment of animals during
production. One of the most infamous examples of animal cruelty in
film was Michael Cimino's legendary flop Heaven's Gate, in which
numerous animals were brutalized and even killed during production.



I'm curious to know about, nowadays, do the directors follow any techniques to prevent animal cruelty i.e filming with trained animals, faking the slaughter of animals?


c++ - More about EOF in loop condition

Okay, when I saw this thread: Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?



I read the answers but I really didn't understand what is wrong in this, maybe because I don't have much experience in c++ but my code works exactly the way it's supposed to.



int main()
{
ifstream file;
string text, search;
int offset;

cout << "Enter a word: "; cin >> search;
file.open("Find.txt");
if (file.is_open()) {
while (!file.eof()) {
file >> text;
offset = text.find(search, 0);
if (offset != string::npos) {
cout << text << endl;
}
}

}
else {
cout << "Error!";
return 0;
}
file.close();
}


I enter in a word, and it searches for it in a text file, and I had zero problems using that. So, when is this condition considered wrong?

android - HttpURLConnection url.openStream() java.io.IOException: No authentication challenges found

an I am trying to load an image from my Server with Android and REST. But when I try to open the stream it crashes with this exception:



myapp: W/System.err? java.io.IOException: No authentication challenges found
myapp: W/System.err? at libcore.net.http.HttpURLConnectionImpl.getAuthorizationCredentials(HttpURLConnectionImpl.java:427)
myapp: W/System.err? at libcore.net.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:407)
myapp: W/System.err? at libcore.net.http.HttpURLConnectionImpl.processResponseHeaders(HttpURLConnectionImpl.java:356)
myapp: W/System.err? at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:292)
myapp: W/System.err? at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)

myapp: W/System.err? at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
myapp: W/System.err? at java.net.URL.openStream(URL.java:462)
myapp: W/System.err? at de.facentis.GenerstoAndroidTester.Rest.asynctasks.TheOneAndOnlyAsync.getStream(TheOneAndOnlyAsync.java:199)
myapp: W/System.err? at de.facentis.GenerstoAndroidTester.Rest.asynctasks.TheOneAndOnlyAsync.doInBackground(TheOneAndOnlyAsync.java:74)
myapp: W/System.err? at de.facentis.GenerstoAndroidTester.Rest.asynctasks.TheOneAndOnlyAsync.doInBackground(TheOneAndOnlyAsync.java:22)
myapp: W/System.err? at android.os.AsyncTask$2.call(AsyncTask.java:287)
myapp: W/System.err? at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
myapp: W/System.err? at java.util.concurrent.FutureTask.run(FutureTask.java:137)
myapp: W/System.err? at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
myapp: W/System.err? at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)

myapp: W/System.err? at java.lang.Thread.run(Thread.java:856)


I found in other threads, here on stackoverflow, it is maybe a 401 from server. I check it and my server sends me a 200 statuscode. The method from server works correctly on other clients.



Here is the method I use:



try {
InputStream input = null;
OutputStream output = null;


try {
URL url = new URL(methodUri);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();

connection.setRequestProperty("Authorization", basicHeader);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept-Language", Locale.getDefault().getLanguage());
connection.setConnectTimeout(5000);

connection.connect();

input = new BufferedInputStream(url.openStream()); // <--- Crash
output = new FileOutputStream(context.getFileStreamPath(filename));

byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}


return;
} catch (java.net.SocketTimeoutException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}finally{
try {
output.flush();
output.close();

input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}catch (Exception ex) {
ex.printStackTrace();
}
return;



Someone na idea?



best regards

javascript - setTimeout or setInterval?




As far as I can tell, these two pieces of javascript behave the same way:



Option A:



function myTimeoutFunction()
{
doStuff();
setTimeout(myTimeoutFunction, 1000);
}


myTimeoutFunction();


Option B:



function myTimeoutFunction()
{
doStuff();
}


myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);


Is there any difference between using setTimeout and setInterval?


Answer



They essentially try to do the same thing, but the setInterval approach will be more accurate than the setTimeout approach, since setTimeout waits 1000ms, runs the function and then sets another timeout. So the wait period is actually a bit more than 1000ms (or a lot more if your function takes a long time to execute).



Altough one might think that setInterval will execute exactly every 1000ms, it is important to note that setInterval will also delay, since JavaScript isn't a multi-threaded language, which means that - if there are other parts of the script running - the interval will have to wait for that to finish.




In this Fiddle, you can clearly see that the timeout will fall behind, while the interval is almost all the time at almost 1 call/second (which the script is trying to do). If you change the speed variable at the top to something small like 20 (meaning it will try to run 50 times per second), the interval will never quite reach an average of 50 iterations per second.



The delay is almost always negligible, but if you're programming something really precise, you should go for a self-adjusting timer (which essentially is a timeout-based timer that constantly adjusts itself for the delay it's created)


PHP string not concatonating











I'm getting the following error:




Parse error: syntax error, unexpected '.', expecting ',' or ';' in xxx
on line 19





On this line:



public $metad_name = "lol" . "lol";

Answer



This error is saying that an expression can't be used in class properties:



Works



class Foo {


public $metad_name = '';

function __construct() {
$this->metad_name = 'lol' . 'lol';
}

}



Parse error



class Bar {

public $metad_name = 'lol' . 'lol';

}


If your code isn't a class property - just delete the public



html5 - Integrating Boilerplate and Bootstrap with CodeIgniter or Yii



I've always been a PHP programmer, but until now without any framework. Now I've a nice project to start and I'd like to introduce some PHP framework: Yii or CodeIgniter.



I don't know yet which one is best for me. I'd like to integrate this project with these 'tools':




  • JQuery

  • HTML5 Boilerplate


  • Twitter Bootstrap

  • CSS SASS



Do you know which framework is more easy to integrate with these tools? And, do you know where I can find a good tutorial for this integration?



Thx


Answer



CodeIgniter and Yii are server-side frameworks. The libraries in question (with the exception of SASS), live on the client-side. Whether you choose CodeIgniter or Yii, the basic integration will be the same. Because I'm a CodeIgniter developer, I can give you one-half of the story:




I urge you to read everything under the Introduction section of the documentation and take a few days to fly through the tutorials and set your brain straight on MVC. Only then, check out a previous answer of mine that explains how to create modular layouts. Once you're comfortable with this, including jQuery and Bootstrap into your project is trivial.



As for Boilerplate - please pick and choose the sections that are relevant to your project and plug-them-into the right 'view' as per linked answer. There are some parts of Boilerplate that will step on Bootstrap's toes (specifically CSS resets, be careful).



Paul Irish gave an excellent talk on HTML5 Boilerplate last year. The Boilerplate itself has probably been updated significantly, but it should get you started.



CodeIgniter has unparalleled documentation and a fantastic community. If you choose this route - welcome!


java - How to use AsyncTask



AsyncTask question




I've followed some tutorials but it still isn't clear to me. Here's the code I currently have with some questions below the code. MainActivity calls SomeClassWithHTTPNeeds, which then calls the JSONParser (AsyncTask<>)






MainActivity:



String station = SomeClassWithHTTPNeeds.getInstance().getStation(123);






SomeClassWithHTTPNeeds:



getStation {

JSONParser = new JSONParser();
JSONObject station = parser.getJSONFromUrl("https://api....");
return JSONObject.getString("station");
}






JSONParser (AsyncTask< String, Void, String >)



protected String doInBackground(); ==> Seperate thread
protected void onPostExecute(); ==> On GUI thread



I was thinking:
--- Put the HTTPRequest in doInBackground();



Problem is I'm not sure how to:
get the JSONParser to return the JSONObject to the getStation method?



What I need to know



=> Where should I return the JSONObject: in background or execute?




=> How do I use the JSONParser once it's an AsyncTask? Will the execute() function return the value?



=> AsyncTask< String, Void, String > ==> How does this work? It's the return type?



Thanks a lot!


Answer



FAQs and general explaination of the usage of AsyncTask




=> Where should I do network operations? Where should I return my aquired values?





In general, you should do Network Operations in a Seperate Thread -> doInBackground(); since you do not want your UI to freeze when a Network Operation takes its time. So you should connect to your Service or .php script or wherever you get the Data from inside the doInBackground() method. Then you could also parse the data there and return the parsed data from the doInBackground() method by specifying the return type of doInBackground() to your desires, more about that down there. The onPostExecute() method will then receive your returned values from doInBackground() and represent them using the UI.




=> AsyncTask< String, Integer, Long> ==> How does this work?




In general, the AsyncTask class looks like this, which is nothing more than a generic class with 3 different generic types:




AsyncTask



You can specify the type of Parameter the AsyncTask takes, the Type of the Progress indicator and the type of the result (the return type
of doInBackGround()).




Here is an Example of an AsyncTask looking like this:




AsyncTask


We have type String for the Parameters, Type Integer for the Progress and Type Long for the Result (return type of doInBackground()). You can use any type you want for Params, Progress and Result.



private class DownloadFilesTask extends AsyncTask {

// these Strings / or String are / is the parameters of the task, that can be handed over via the excecute(params) method of AsyncTask
protected Long doInBackground(String... params) {


String param1 = params[0];
String param2 = params[1];
// and so on...
// do something with the parameters...
// be careful, this can easily result in a ArrayIndexOutOfBounds exception
// if you try to access more parameters than you handed over

long someLong;
int someInt;


// do something here with params
// the params could for example contain an url and you could download stuff using this url here

// the Integer variable is used for progress
publishProgress(someInt);

// once the data is downloaded (for example JSON data)
// parse the data and return it to the onPostExecute() method
// in this example the return data is simply a long value
// this could also be a list of your custom-objects, ...

return someLong;
}

// this is called whenever you call puhlishProgress(Integer), for example when updating a progressbar when downloading stuff
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}

// the onPostexecute method receives the return type of doInBackGround()
protected void onPostExecute(Long result) {

// do something with the result, for example display the received Data in a ListView
// in this case, "result" would contain the "someLong" variable returned by doInBackground();
}
}



=> How to use AsyncTask? How can I "call" it? How can I "execute" it?





In this case, the AsyncTask takes a String or String Array as a Parameter which will look like this once the AsyncTask is called: (The specified parameter is used in the execute(param) method of AsyncTask).



new DownloadFilesTask().execute("Somestring"); // some String as param


Be aware, that this call does not have a return value, the only return value you should use is the one returned from doInBackground(). Use the onPostExecute() method do make use of the returned value.



Also be careful with this line of code: (this execution will actually have a return value)



long myLong = new DownloadFilesTask().execute("somestring").get();



The .get() call causes the UI thread to be blocked (so the UI freezes if the operation takes longer than a few millisecons) while the AsyncTask is executing, because the execution does not take place in a separate thread. If you remove the call to .get() it will perform asynchronously.




=> What does this notation "execute(String... params)" mean?




This is a method with a so called "varargs" (variable arguments) parameter. To keep it simple, I will just say that it means that the actual number of values you can pass on to the method via this parameter is not specified, and any amount of values you hand to the method will be treated as an array inside the method. So this call could for example look like this:




execute("param1");


but it could however also look like this:



execute("param1", "param2");


or even more parameters. Assuming we are still talking about AsyncTask, the parameters can be accessed in this way in the doInBackground(String... params) method:




 protected Long doInBackground(String... params) {

String str1 = params[0];
String str2 = params[1]; // be careful here, you can easily get an ArrayOutOfBoundsException

// do other stuff
}


You can read more about AsyncTask here: http://developer.android.com/reference/android/os/AsyncTask.html




Also take a look at this AsyncTask example: https://stackoverflow.com/a/9671602/1590502


javascript - Why getElementsByClassName doesn't work on xhr reponseXML



Why xhr.responseXML.getElementsByClassName('clazz') doesn't work?



Here is the js:





var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var happiness = xhr.responseXML.getElementsByClassName('clazz');

//Uncaught TypeError: Cannot read property 'innerHTML' of undefined
console.log("happiness ? " + happiness[0].innerHTML);
}

};

//xhr.overrideMimeType("application/xml");
xhr.open("GET", "xhr.php", true);
xhr.send(null);


xhr.php contains the following:






header('Content-type: application/xml; charset=UTF-8');

echo " \n";

?>







I'm the XHR response





xhr happiness







can you please explain the following output in the Chrome console?




xhr.responseXML.getElementById('x')



xhr.responseXML.getElementsByClassName('y')
[]

Answer



xhr.responseXML is XML nodes and not HTML elements which means that class attribute has not a special meaning.



However, when I added xmlns declaration to the html tag, the getElementsByClassName on responseXML just worked (tested on Chrome).







sql server - How do I find a stored procedure containing ?

Answer


Answer




I need to search a SQL server 2008 for stored procedures containing where maybe
the name of a database field or variable name.


Answer



SELECT ROUTINE_NAME, ROUTINE_DEFINITION

FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%Foo%'
AND ROUTINE_TYPE='PROCEDURE'





SELECT OBJECT_NAME(id) 
FROM SYSCOMMENTS
WHERE [text] LIKE '%Foo%'

AND OBJECTPROPERTY(id, 'IsProcedure') = 1
GROUP BY OBJECT_NAME(id)





SELECT OBJECT_NAME(object_id)
FROM sys.sql_modules
WHERE OBJECTPROPERTY(object_id, 'IsProcedure') = 1
AND definition LIKE '%Foo%'


object - How do I check this boolean hashmap is empty in javascript?



Possible Duplicates:
Object comparison in JavaScript
How do I test for an empty Javascript object from JSON?






var abc = {};
console.log(abc=={}) //false, why?


Why is it false? How do I match a blank hash map...?

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');

sql - MYSQL Update Single column with different values





There is this table "Trade" with column "call",Call contains values(C,P) when loaded from CSV
I want to update Trade from java program such that if call='C' then call='CE' and



if call='P' then call='PE'



I figured out this can be done using 2 queries.like this



update Trade set call='CE' where call='C';

update Trade set call='PE' where call='P';



is there anyway this can be done in single query?


Answer



CALL is a reserved keyword and needs to be escaped.



UPDATE  Trade
SET `CALL` = CASE WHEN `Call` = 'C' THEN 'CE'
WHEN `Call` = 'P' THEN 'PE'
ELSE `CALL` END

WHERE `CALL` IN ('C','P')

Model-View-Controller in JavaScript

tl;dr: How does one implement MVC in JavaScript in a clean way?



I'm trying to implement MVC in JavaScript. I have googled and reorganized with my code countless times but have not found a suitable solution. (The code just doesn't "feel right".)



Here's how I'm going about it right now. It's incredibly complicated and is a pain to work with (but still better than the pile of code I had before). It has ugly workarounds that sort of defeat the purpose of MVC.



And behold, the mess, if you're really brave:



// Create a "main model"
var main = Model0();

function Model0() {
// Create an associated view and store its methods in "view"
var view = View0();

// Create a submodel and pass it a function
// that will "subviewify" the submodel's view
var model1 = Model1(function (subview) {
view.subviewify(subview);
});

// Return model methods that can be used by
// the controller (the onchange handlers)
return {
'updateModel1': function (newValue) {
model1.update(newValue);
}
};
}

function Model1(makeSubView) {
var info = '';

// Make an associated view and attach the view
// to the parent view using the passed function
var view = View1();
makeSubView(view.__view); // Dirty dirty

// Return model methods that can be used by
// the parent model (and so the controller)
return {
'update': function (newValue) {
info = newValue;

// Notify the view of the new information
view.events.value(info);
}
};
}

function View0() {
var thing = document.getElementById('theDiv');
var input = document.getElementById('theInput');

// This is the "controller", bear with me
input.onchange = function () {
// Ugly, uses a global to contact the model
main.updateModel1(this.value);
};

return {
'events': {},

// Adds a subview to this view.
'subviewify': function (subview) {
thing.appendChild(subview);
}
};
}

// This is a subview.
function View1() {

var element = document.createElement('div');
return {
'events': {
// When the value changes this is
// called so the view can be updated
'value': function (newValue) {
element.innerHTML = newValue;
}
},

// ..Expose the DOM representation of the subview
// so it can be attached to a parent view
'__view': element
};
}


How does one implement MVC in JavaScript in a cleaner way? How can I improve this system? Or is this the completely wrong way to go, should I follow another pattern?

Monday, May 28, 2018

Unexpected Result With JavaScript Substr()




I'm having a problem with substr() in JavaScript.

Please look at the code below.




The following works as expected. y = 2017




var add_date = "20170505";

var y = add_date.substr(0, 4);
alert(y);



But... the following doesn't work. It should return '05' but instead it returns 0505. m = 0505




var add_date = "20170505";
var m = add_date.substr(4, 6);

alert(m);


Could someone explain me what's wrong?



Thanks,



Nathan


Answer



.substr(4,6) method returns 6 characters starting at index 4. Use .substring instead.






var add_date = "20170505",
y = add_date.substring(0, 4);
console.log(y);


var add_date = "20170505",
m = add_date.substring(4, 6);

console.log(m);




html - jquery - Click event not working for dynamically created button




My requirement is to create number of buttons equal to the json array count. I was successful in creating buttons dynamically in jquery. But the method in .ready function of jquery is not called for the click action. I have tried searching in SO. Found few solutions but nothing worked for me. I am very new to jquery. Please help...



my code:
jQuery:




$(document).ready(function()
{
currentQuestionNo = 0;
var questionsArray;
$.getJSON('http://localhost/Sample/JsonCreation.php', function(data)
{
questionsArray = data;
variable = 1;
//CREATE QUESTION BUTTONS DYNAMICALLY ** NOT WORKING

for (var question in questionsArray)
{
var button = $("").attr("type", "button").attr("id", "questionButton").val(variable);

$('body').append(button);

//Tried using .next here - but it dint work...
//$('body').append('');
variable++;
}

displayQuestionJS(questionsArray[currentQuestionNo], document);
});




$("button").click(function()
{

if ($(this).attr('id') == "nextQuestion")

{
currentQuestionNo = ++currentQuestionNo;
}
else if ($(this).attr('id') == "previousQuestion")
{
currentQuestionNo = --currentQuestionNo;
}

displayQuestionJS(questionsArray[currentQuestionNo], document);


});



function displayQuestionJS(currentQuestion, document)
{
document.getElementById('questionNumber').innerText = currentQuestion.questionNumber;
document.getElementById('questionDescription').innerText = currentQuestion.quesDesc;
$('label[for=optionA]').html(currentQuestion.optionA);
$('label[for=optionB]').html(currentQuestion.optionB);

$('label[for=optionC]').html(currentQuestion.optionC);
}

HTML content


.  

















EDIT -- Sample .on Method code - Separate file: WORKING - THANKS A LOT













Answer



You create buttons dynamically because of that you need to call them with .live() method if you use jquery 1.7




but this method is deprecated (you can see the list of all deprecated method here) in newer version. if you want to use jquery 1.10 or above you need to call your buttons in this way:



$(document).on('click', 'selector', function(){ 
// Your Code
});


For Example




If your html is something like this




MyButton




You can write your jquery like this



$(document).on('click', '#btn-list .btn12', function(){ 

// Your Code
});

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...